From 8eff962cab608341a6f2fedc640a0e32d96f26e2 Mon Sep 17 00:00:00 2001 From: altaf-creator Date: Sun, 9 Nov 2025 11:15:19 +0800 Subject: pain --- .../node_modules/@firebase/firestore/README.md | 24 + .../firestore/dist/firestore/lite/index.d.ts | 29 + .../firestore/dist/firestore/lite/register.d.ts | 23 + .../firestore/dist/firestore/src/api.d.ts | 65 + .../dist/firestore/src/api/aggregate.d.ts | 77 + .../firestore/dist/firestore/src/api/bundle.d.ts | 94 + .../firestore/dist/firestore/src/api/bytes.d.ts | 17 + .../dist/firestore/src/api/cache_config.d.ts | 222 + .../dist/firestore/src/api/credentials.d.ts | 222 + .../firestore/dist/firestore/src/api/database.d.ts | 279 + .../dist/firestore/src/api/field_path.d.ts | 17 + .../dist/firestore/src/api/field_value.d.ts | 17 + .../dist/firestore/src/api/field_value_impl.d.ts | 17 + .../firestore/dist/firestore/src/api/filter.d.ts | 17 + .../dist/firestore/src/api/geo_point.d.ts | 17 + .../firestore/src/api/index_configuration.d.ts | 139 + .../firestore/src/api/long_polling_options.d.ts | 55 + .../firestore/dist/firestore/src/api/observer.d.ts | 29 + .../dist/firestore/src/api/parse_context.d.ts | 21 + .../src/api/persistent_cache_index_manager.d.ts | 59 + .../dist/firestore/src/api/reference.d.ts | 17 + .../dist/firestore/src/api/reference_impl.d.ts | 536 + .../firestore/dist/firestore/src/api/settings.d.ts | 108 + .../firestore/dist/firestore/src/api/snapshot.d.ts | 550 + .../dist/firestore/src/api/timestamp.d.ts | 17 + .../dist/firestore/src/api/transaction.d.ts | 61 + .../firestore/src/api/transaction_options.d.ts | 17 + .../dist/firestore/src/api/write_batch.d.ts | 31 + .../firestore/dist/firestore/src/auth/user.d.ts | 36 + .../dist/firestore/src/core/aggregate.d.ts | 38 + .../firestore/dist/firestore/src/core/bound.d.ts | 49 + .../firestore/dist/firestore/src/core/bundle.d.ts | 80 + .../dist/firestore/src/core/bundle_impl.d.ts | 88 + .../firestore/src/core/component_provider.d.ts | 146 + .../dist/firestore/src/core/database_info.d.ts | 64 + .../dist/firestore/src/core/event_manager.d.ts | 133 + .../firestore/dist/firestore/src/core/filter.d.ts | 130 + .../dist/firestore/src/core/firestore_client.d.ts | 138 + .../dist/firestore/src/core/listen_sequence.d.ts | 39 + .../dist/firestore/src/core/order_by.d.ts | 35 + .../firestore/dist/firestore/src/core/query.d.ts | 142 + .../dist/firestore/src/core/snapshot_version.d.ts | 34 + .../dist/firestore/src/core/sync_engine.d.ts | 37 + .../dist/firestore/src/core/sync_engine_impl.d.ts | 255 + .../firestore/dist/firestore/src/core/target.d.ts | 89 + .../firestore/src/core/target_id_generator.d.ts | 38 + .../dist/firestore/src/core/transaction.d.ts | 60 + .../firestore/src/core/transaction_options.d.ts | 25 + .../firestore/src/core/transaction_runner.d.ts | 41 + .../firestore/dist/firestore/src/core/types.d.ts | 65 + .../firestore/dist/firestore/src/core/version.d.ts | 18 + .../firestore/dist/firestore/src/core/view.d.ts | 152 + .../dist/firestore/src/core/view_snapshot.d.ts | 59 + .../firestore/dist/firestore/src/global_index.d.ts | 10145 ++++++ .../firestore/dist/firestore/src/index.d.ts | 28 + .../firestore/dist/firestore/src/index.node.d.ts | 17 + .../firestore/dist/firestore/src/index.rn.d.ts | 17 + .../src/index/directional_index_byte_encoder.d.ts | 24 + .../src/index/firestore_index_value_writer.d.ts | 34 + .../firestore/src/index/index_byte_encoder.d.ts | 31 + .../dist/firestore/src/index/index_entry.d.ts | 49 + .../firestore/src/index/ordered_code_writer.d.ts | 60 + .../dist/firestore/src/lite-api/aggregate.d.ts | 100 + .../firestore/src/lite-api/aggregate_types.d.ts | 86 + .../dist/firestore/src/lite-api/bytes.d.ts | 83 + .../dist/firestore/src/lite-api/components.d.ts | 49 + .../dist/firestore/src/lite-api/database.d.ts | 179 + .../dist/firestore/src/lite-api/field_path.d.ts | 48 + .../dist/firestore/src/lite-api/field_value.d.ts | 33 + .../firestore/src/lite-api/field_value_impl.d.ts | 81 + .../dist/firestore/src/lite-api/geo_point.d.ts | 79 + .../dist/firestore/src/lite-api/query.d.ts | 404 + .../dist/firestore/src/lite-api/reference.d.ts | 362 + .../firestore/src/lite-api/reference_impl.d.ts | 172 + .../dist/firestore/src/lite-api/settings.d.ts | 77 + .../dist/firestore/src/lite-api/snapshot.d.ts | 367 + .../dist/firestore/src/lite-api/timestamp.d.ts | 134 + .../dist/firestore/src/lite-api/transaction.d.ts | 122 + .../src/lite-api/transaction_options.d.ts | 23 + .../dist/firestore/src/lite-api/types.d.ts | 61 + .../firestore/src/lite-api/user_data_reader.d.ts | 224 + .../firestore/src/lite-api/user_data_writer.d.ts | 48 + .../dist/firestore/src/lite-api/vector_value.d.ts | 58 + .../dist/firestore/src/lite-api/write_batch.d.ts | 125 + .../dist/firestore/src/local/bundle_cache.d.ts | 44 + .../src/local/document_overlay_cache.d.ts | 76 + .../firestore/src/local/encoded_resource_path.d.ts | 73 + .../dist/firestore/src/local/globals_cache.d.ts | 39 + .../dist/firestore/src/local/index_backfiller.d.ts | 44 + .../dist/firestore/src/local/index_manager.d.ts | 124 + .../src/local/indexeddb_bundle_cache.d.ts | 27 + .../local/indexeddb_document_overlay_cache.d.ts | 45 + .../src/local/indexeddb_globals_cache.d.ts | 25 + .../src/local/indexeddb_index_manager.d.ts | 136 + .../src/local/indexeddb_lru_delegate.d.ts | 22 + .../src/local/indexeddb_lru_delegate_impl.d.ts | 56 + .../src/local/indexeddb_mutation_batch_impl.d.ts | 35 + .../src/local/indexeddb_mutation_queue.d.ts | 99 + .../firestore/src/local/indexeddb_persistence.d.ts | 270 + .../src/local/indexeddb_remote_document_cache.d.ts | 36 + .../dist/firestore/src/local/indexeddb_schema.d.ts | 509 + .../src/local/indexeddb_schema_converter.d.ts | 43 + .../src/local/indexeddb_schema_legacy.d.ts | 29 + .../firestore/src/local/indexeddb_sentinels.d.ts | 267 + .../src/local/indexeddb_target_cache.d.ts | 81 + .../firestore/src/local/indexeddb_transaction.d.ts | 25 + .../firestore/src/local/local_documents_view.d.ts | 127 + .../dist/firestore/src/local/local_serializer.d.ts | 80 + .../dist/firestore/src/local/local_store.d.ts | 41 + .../dist/firestore/src/local/local_store_impl.d.ts | 208 + .../firestore/src/local/local_view_changes.d.ts | 32 + .../firestore/src/local/lru_garbage_collector.d.ts | 102 + .../src/local/lru_garbage_collector_impl.d.ts | 37 + .../firestore/src/local/memory_bundle_cache.d.ts | 32 + .../src/local/memory_document_overlay_cache.d.ts | 37 + .../firestore/src/local/memory_globals_cache.d.ts | 25 + .../firestore/src/local/memory_index_manager.d.ts | 55 + .../firestore/src/local/memory_mutation_queue.d.ts | 80 + .../firestore/src/local/memory_persistence.d.ts | 134 + .../src/local/memory_remote_document_cache.d.ts | 33 + .../firestore/src/local/memory_target_cache.d.ts | 65 + .../dist/firestore/src/local/mutation_queue.d.ts | 123 + .../firestore/src/local/overlayed_document.d.ts | 40 + .../dist/firestore/src/local/persistence.d.ts | 217 + .../firestore/src/local/persistence_promise.d.ts | 83 + .../src/local/persistence_transaction.d.ts | 34 + .../dist/firestore/src/local/query_context.d.ts | 28 + .../dist/firestore/src/local/query_engine.d.ts | 110 + .../dist/firestore/src/local/reference_set.d.ts | 68 + .../firestore/src/local/remote_document_cache.d.ts | 91 + .../src/local/remote_document_change_buffer.d.ts | 88 + .../firestore/src/local/shared_client_state.d.ts | 312 + .../src/local/shared_client_state_schema.d.ts | 84 + .../src/local/shared_client_state_syncer.d.ts | 40 + .../dist/firestore/src/local/simple_db.d.ts | 233 + .../dist/firestore/src/local/target_cache.d.ts | 130 + .../dist/firestore/src/local/target_data.d.ts | 127 + .../dist/firestore/src/model/collections.d.ts | 50 + .../dist/firestore/src/model/document.d.ts | 150 + .../firestore/src/model/document_comparator.d.ts | 19 + .../dist/firestore/src/model/document_key.d.ts | 45 + .../dist/firestore/src/model/document_set.d.ts | 57 + .../dist/firestore/src/model/field_index.d.ts | 171 + .../dist/firestore/src/model/field_mask.d.ts | 45 + .../dist/firestore/src/model/mutation.d.ts | 270 + .../dist/firestore/src/model/mutation_batch.d.ts | 88 + .../dist/firestore/src/model/normalize.d.ts | 33 + .../dist/firestore/src/model/object_value.d.ts | 78 + .../dist/firestore/src/model/overlay.d.ts | 32 + .../firestore/dist/firestore/src/model/path.d.ts | 121 + .../firestore/src/model/server_timestamps.d.ts | 34 + .../firestore/src/model/target_index_matcher.d.ts | 76 + .../firestore/src/model/transform_operation.d.ts | 75 + .../dist/firestore/src/model/type_order.d.ts | 38 + .../firestore/dist/firestore/src/model/values.d.ts | 114 + .../dist/firestore/src/platform/base64.d.ts | 25 + .../firestore/src/platform/browser/base64.d.ts | 22 + .../src/platform/browser/byte_stream_reader.d.ts | 21 + .../firestore/src/platform/browser/connection.d.ts | 23 + .../src/platform/browser/connectivity_monitor.d.ts | 33 + .../dist/firestore/src/platform/browser/dom.d.ts | 20 + .../src/platform/browser/format_json.d.ts | 18 + .../src/platform/browser/random_bytes.d.ts | 22 + .../firestore/src/platform/browser/serializer.d.ts | 20 + .../src/platform/browser/snapshot_to_json.d.ts | 23 + .../src/platform/browser/text_serializer.d.ts | 24 + .../platform/browser/webchannel_connection.d.ts | 47 + .../src/platform/browser_lite/base64.d.ts | 17 + .../platform/browser_lite/byte_stream_reader.d.ts | 17 + .../src/platform/browser_lite/connection.d.ts | 21 + .../firestore/src/platform/browser_lite/dom.d.ts | 17 + .../platform/browser_lite/fetch_connection.d.ts | 28 + .../src/platform/browser_lite/format_json.d.ts | 17 + .../src/platform/browser_lite/random_bytes.d.ts | 17 + .../src/platform/browser_lite/serializer.d.ts | 17 + .../platform/browser_lite/snapshot_to_json.d.ts | 17 + .../src/platform/browser_lite/text_serializer.d.ts | 17 + .../firestore/src/platform/byte_stream_reader.d.ts | 18 + .../dist/firestore/src/platform/connection.d.ts | 21 + .../firestore/dist/firestore/src/platform/dom.d.ts | 20 + .../dist/firestore/src/platform/format_json.d.ts | 18 + .../dist/firestore/src/platform/node/base64.d.ts | 22 + .../src/platform/node/byte_stream_reader.d.ts | 21 + .../firestore/src/platform/node/connection.d.ts | 23 + .../dist/firestore/src/platform/node/dom.d.ts | 20 + .../firestore/src/platform/node/format_json.d.ts | 18 + .../src/platform/node/grpc_connection.d.ts | 43 + .../firestore/src/platform/node/load_protos.d.ts | 28 + .../firestore/src/platform/node/random_bytes.d.ts | 22 + .../firestore/src/platform/node/serializer.d.ts | 20 + .../src/platform/node/snapshot_to_json.d.ts | 23 + .../src/platform/node/text_serializer.d.ts | 25 + .../firestore/src/platform/node_lite/base64.d.ts | 17 + .../src/platform/node_lite/byte_stream_reader.d.ts | 17 + .../src/platform/node_lite/connection.d.ts | 21 + .../dist/firestore/src/platform/node_lite/dom.d.ts | 17 + .../src/platform/node_lite/format_json.d.ts | 17 + .../src/platform/node_lite/random_bytes.d.ts | 17 + .../src/platform/node_lite/serializer.d.ts | 17 + .../src/platform/node_lite/snapshot_to_json.d.ts | 17 + .../src/platform/node_lite/text_serializer.d.ts | 17 + .../dist/firestore/src/platform/random_bytes.d.ts | 22 + .../dist/firestore/src/platform/rn/base64.d.ts | 22 + .../src/platform/rn/byte_stream_reader.d.ts | 17 + .../dist/firestore/src/platform/rn/connection.d.ts | 17 + .../dist/firestore/src/platform/rn/dom.d.ts | 17 + .../firestore/src/platform/rn/format_json.d.ts | 17 + .../firestore/src/platform/rn/random_bytes.d.ts | 17 + .../dist/firestore/src/platform/rn/serializer.d.ts | 17 + .../src/platform/rn/snapshot_to_json.d.ts | 17 + .../firestore/src/platform/rn/text_serializer.d.ts | 17 + .../firestore/src/platform/rn_lite/base64.d.ts | 17 + .../src/platform/rn_lite/byte_stream_reader.d.ts | 17 + .../firestore/src/platform/rn_lite/connection.d.ts | 17 + .../dist/firestore/src/platform/rn_lite/dom.d.ts | 17 + .../src/platform/rn_lite/format_json.d.ts | 17 + .../src/platform/rn_lite/random_bytes.d.ts | 17 + .../firestore/src/platform/rn_lite/serializer.d.ts | 17 + .../src/platform/rn_lite/snapshot_to_json.d.ts | 17 + .../src/platform/rn_lite/text_serializer.d.ts | 17 + .../dist/firestore/src/platform/serializer.d.ts | 19 + .../firestore/src/platform/snapshot_to_json.d.ts | 28 + .../firestore/src/platform/text_serializer.d.ts | 24 + .../src/protos/firestore_bundle_proto.d.ts | 72 + .../firestore/src/protos/firestore_proto_api.d.ts | 836 + .../firestore/dist/firestore/src/register.d.ts | 17 + .../dist/firestore/src/remote/backoff.d.ts | 106 + .../dist/firestore/src/remote/bloom_filter.d.ts | 34 + .../dist/firestore/src/remote/connection.d.ts | 99 + .../firestore/src/remote/connectivity_monitor.d.ts | 47 + .../src/remote/connectivity_monitor_noop.d.ts | 21 + .../dist/firestore/src/remote/datastore.d.ts | 44 + .../firestore/src/remote/existence_filter.d.ts | 22 + .../firestore/src/remote/internal_serializer.d.ts | 46 + .../firestore/src/remote/number_serializer.d.ts | 36 + .../firestore/src/remote/online_state_tracker.d.ts | 81 + .../firestore/src/remote/persistent_stream.d.ts | 308 + .../dist/firestore/src/remote/remote_event.d.ts | 156 + .../dist/firestore/src/remote/remote_store.d.ts | 85 + .../dist/firestore/src/remote/remote_syncer.d.ts | 68 + .../dist/firestore/src/remote/rest_connection.d.ts | 53 + .../dist/firestore/src/remote/rpc_error.d.ts | 74 + .../dist/firestore/src/remote/serializer.d.ts | 124 + .../dist/firestore/src/remote/stream_bridge.d.ts | 45 + .../dist/firestore/src/remote/watch_change.d.ts | 231 + .../dist/firestore/src/tsdoc-metadata.json | 11 + .../firestore/dist/firestore/src/util/array.d.ts | 70 + .../firestore/dist/firestore/src/util/assert.d.ts | 78 + .../dist/firestore/src/util/async_observer.d.ts | 31 + .../dist/firestore/src/util/async_queue.d.ts | 180 + .../dist/firestore/src/util/async_queue_impl.d.ts | 75 + .../firestore/src/util/base64_decode_error.d.ts | 22 + .../firestore/src/util/bundle_builder_impl.d.ts | 97 + .../dist/firestore/src/util/bundle_reader.d.ts | 67 + .../firestore/src/util/bundle_reader_impl.d.ts | 19 + .../src/util/bundle_reader_sync_impl.d.ts | 59 + .../dist/firestore/src/util/byte_stream.d.ts | 29 + .../dist/firestore/src/util/byte_string.d.ts | 46 + .../dist/firestore/src/util/debug_uid.d.ts | 28 + .../firestore/dist/firestore/src/util/error.d.ts | 195 + .../dist/firestore/src/util/input_validation.d.ts | 56 + .../dist/firestore/src/util/json_validation.d.ts | 70 + .../firestore/dist/firestore/src/util/log.d.ts | 39 + .../dist/firestore/src/util/logic_utils.d.ts | 52 + .../firestore/dist/firestore/src/util/misc.d.ts | 46 + .../dist/firestore/src/util/node_api.d.ts | 58 + .../firestore/dist/firestore/src/util/obj.d.ts | 23 + .../firestore/dist/firestore/src/util/obj_map.d.ts | 48 + .../firestore/dist/firestore/src/util/promise.d.ts | 34 + .../dist/firestore/src/util/sorted_map.d.ts | 100 + .../dist/firestore/src/util/sorted_set.d.ts | 80 + .../dist/firestore/src/util/testing_hooks.d.ts | 52 + .../dist/firestore/src/util/testing_hooks_spi.d.ts | 93 + .../firestore/dist/firestore/src/util/types.d.ts | 45 + .../test/integration/api/aggregation.test.d.ts | 17 + .../integration/api/array_transforms.test.d.ts | 17 + .../test/integration/api/batch_writes.test.d.ts | 17 + .../test/integration/api/bundle.test.d.ts | 17 + .../api/composite_index_query.test.d.ts | 17 + .../test/integration/api/cursor.test.d.ts | 17 + .../test/integration/api/database.test.d.ts | 17 + .../test/integration/api/fields.test.d.ts | 17 + .../test/integration/api/get_options.test.d.ts | 17 + .../integration/api/index_configuration.test.d.ts | 17 + .../integration/api/numeric_transforms.test.d.ts | 17 + .../api/persistent_cache_index_manager.test.d.ts | 17 + .../test/integration/api/provider.test.d.ts | 17 + .../firestore/test/integration/api/query.test.d.ts | 18 + .../integration/api/server_timestamp.test.d.ts | 17 + .../firestore/test/integration/api/smoke.test.d.ts | 17 + .../api/snapshot_listener_source.test.d.ts | 17 + .../test/integration/api/transactions.test.d.ts | 17 + .../firestore/test/integration/api/type.test.d.ts | 17 + .../test/integration/api/validation.test.d.ts | 17 + .../test/integration/api_internal/auth.test.d.ts | 17 + .../integration/api_internal/database.test.d.ts | 17 + .../api_internal/idle_timeout.test.d.ts | 17 + .../integration/api_internal/transaction.test.d.ts | 17 + .../dist/firestore/test/integration/bootstrap.d.ts | 17 + .../test/integration/browser/indexeddb.test.d.ts | 17 + .../test/integration/browser/webchannel.test.d.ts | 17 + .../test/integration/prime_backend.test.d.ts | 17 + .../test/integration/remote/remote.test.d.ts | 17 + .../test/integration/remote/stream.test.d.ts | 54 + .../util/composite_index_test_helper.d.ts | 41 + .../test/integration/util/events_accumulator.d.ts | 39 + .../test/integration/util/firebase_export.d.ts | 23 + .../firestore/test/integration/util/helpers.d.ts | 138 + .../test/integration/util/internal_helpers.d.ts | 34 + .../firestore/test/integration/util/settings.d.ts | 24 + .../test/integration/util/testing_hooks_util.d.ts | 44 + .../dist/firestore/test/lite/bootstrap.d.ts | 17 + .../dist/firestore/test/lite/helpers.d.ts | 41 + .../dist/firestore/test/lite/integration.test.d.ts | 17 + .../firestore/dist/firestore/test/register.d.ts | 17 + .../firestore/test/unit/api/aggregate.test.d.ts | 17 + .../dist/firestore/test/unit/api/bytes.test.d.ts | 17 + .../firestore/test/unit/api/database.test.d.ts | 17 + .../test/unit/api/document_change.test.d.ts | 17 + .../firestore/test/unit/api/field_path.test.d.ts | 17 + .../firestore/test/unit/api/field_value.test.d.ts | 17 + .../firestore/test/unit/api/geo_point.test.d.ts | 17 + .../test/unit/api/long_polling_options.test.d.ts | 17 + .../firestore/test/unit/api/timestamp.test.d.ts | 17 + .../firestore/test/unit/api/vector_value.test.d.ts | 17 + .../dist/firestore/test/unit/bootstrap.d.ts | 24 + .../test/unit/core/event_manager.test.d.ts | 17 + .../dist/firestore/test/unit/core/filter.test.d.ts | 17 + .../test/unit/core/listen_sequence.test.d.ts | 17 + .../dist/firestore/test/unit/core/query.test.d.ts | 17 + .../dist/firestore/test/unit/core/view.test.d.ts | 17 + .../test/unit/core/webchannel_wrapper.test.d.ts | 17 + .../index/firestore_index_value_writer.test.d.ts | 1 + .../test/unit/index/ordered_code_writer.test.d.ts | 1 + .../firestore/test/unit/lite-api/types.test.d.ts | 1 + .../test/unit/local/bundle_cache.test.d.ts | 17 + .../test/unit/local/counting_query_engine.d.ts | 60 + .../unit/local/document_overlay_cache.test.d.ts | 1 + .../unit/local/encoded_resource_path.test.d.ts | 17 + .../test/unit/local/globals_cache.test.d.ts | 17 + .../test/unit/local/index_backfiller.test.d.ts | 17 + .../test/unit/local/index_manager.test.d.ts | 17 + .../unit/local/indexeddb_persistence.test.d.ts | 17 + .../test/unit/local/local_serializer.test.d.ts | 17 + .../test/unit/local/local_store.test.d.ts | 24 + .../unit/local/local_store_indexeddb.test.d.ts | 17 + .../unit/local/lru_garbage_collector.test.d.ts | 17 + .../test/unit/local/mutation_queue.test.d.ts | 17 + .../test/unit/local/persistence_promise.test.d.ts | 17 + .../test/unit/local/persistence_test_helpers.d.ts | 67 + .../unit/local/persistence_transaction.test.d.ts | 17 + .../test/unit/local/query_engine.test.d.ts | 17 + .../test/unit/local/reference_set.test.d.ts | 17 + .../unit/local/remote_document_cache.test.d.ts | 17 + .../local/remote_document_change_buffer.test.d.ts | 17 + .../firestore/test/unit/local/simple_db.test.d.ts | 17 + .../test/unit/local/target_cache.test.d.ts | 17 + .../test/unit/local/test_bundle_cache.d.ts | 32 + .../unit/local/test_document_overlay_cache.d.ts | 39 + .../test/unit/local/test_globals_cache.d.ts | 29 + .../test/unit/local/test_index_manager.d.ts | 44 + .../test/unit/local/test_mutation_queue.d.ts | 43 + .../unit/local/test_remote_document_cache.d.ts | 54 + .../local/test_remote_document_change_buffer.d.ts | 34 + .../test/unit/local/test_target_cache.d.ts | 46 + .../web_storage_shared_client_state.test.d.ts | 17 + .../firestore/test/unit/model/document.test.d.ts | 17 + .../test/unit/model/document_set.test.d.ts | 17 + .../test/unit/model/field_index.test.d.ts | 17 + .../firestore/test/unit/model/mutation.test.d.ts | 17 + .../test/unit/model/object_value.test.d.ts | 17 + .../test/unit/model/object_value_builder.test.d.ts | 17 + .../dist/firestore/test/unit/model/path.test.d.ts | 17 + .../firestore/test/unit/model/target.test.d.ts | 17 + .../test/unit/model/target_index_matcher.test.d.ts | 17 + .../firestore/test/unit/model/values.test.d.ts | 17 + .../test/unit/remote/bloom_filter.test.d.ts | 1 + .../bloom_filter_golden_test_data/index.d.ts | 40 + .../firestore/test/unit/remote/datastore.test.d.ts | 17 + .../test/unit/remote/fetch_connection.test.d.ts | 17 + .../test/unit/remote/remote_event.test.d.ts | 17 + .../test/unit/remote/rest_connection.test.d.ts | 28 + .../test/unit/remote/serializer.browser.test.d.ts | 17 + .../test/unit/remote/serializer.helper.d.ts | 25 + .../test/unit/remote/serializer.node.test.d.ts | 21 + .../test/unit/specs/bundle_spec.test.d.ts | 36 + .../test/unit/specs/collection_spec.test.d.ts | 17 + .../firestore/test/unit/specs/describe_spec.d.ts | 44 + .../unit/specs/existence_filter_spec.test.d.ts | 17 + .../unit/specs/garbage_collection_spec.test.d.ts | 17 + .../firestore/test/unit/specs/index_spec.test.d.ts | 17 + .../firestore/test/unit/specs/limbo_spec.test.d.ts | 17 + .../firestore/test/unit/specs/limit_spec.test.d.ts | 17 + .../test/unit/specs/listen_source_spec.test.d.ts | 17 + .../test/unit/specs/listen_spec.test.d.ts | 17 + .../test/unit/specs/offline_spec.test.d.ts | 17 + .../test/unit/specs/orderby_spec.test.d.ts | 17 + .../firestore/test/unit/specs/perf_spec.test.d.ts | 17 + .../test/unit/specs/persistence_spec.test.d.ts | 17 + .../firestore/test/unit/specs/query_spec.test.d.ts | 17 + .../test/unit/specs/recovery_spec.test.d.ts | 17 + .../test/unit/specs/remote_store_spec.test.d.ts | 17 + .../test/unit/specs/resume_token_spec.test.d.ts | 17 + .../firestore/test/unit/specs/spec_builder.d.ts | 287 + .../firestore/test/unit/specs/spec_rpc_error.d.ts | 24 + .../test/unit/specs/spec_test_components.d.ts | 156 + .../test/unit/specs/spec_test_runner.d.ts | 323 + .../firestore/test/unit/specs/write_spec.test.d.ts | 17 + .../dist/firestore/test/unit/util/array.test.d.ts | 17 + .../dist/firestore/test/unit/util/assert.test.d.ts | 17 + .../firestore/test/unit/util/async_queue.test.d.ts | 17 + .../dist/firestore/test/unit/util/base64.test.d.ts | 17 + .../dist/firestore/test/unit/util/bundle.test.d.ts | 8 + .../dist/firestore/test/unit/util/bundle_data.d.ts | 50 + .../firestore/test/unit/util/logic_utils.test.d.ts | 17 + .../dist/firestore/test/unit/util/misc.test.d.ts | 17 + .../firestore/test/unit/util/node_api.test.d.ts | 17 + .../firestore/test/unit/util/obj_map.test.d.ts | 17 + .../firestore/test/unit/util/sorted_map.test.d.ts | 17 + .../firestore/test/unit/util/sorted_set.test.d.ts | 17 + .../dist/firestore/test/util/api_helpers.d.ts | 49 + .../dist/firestore/test/util/equality_matcher.d.ts | 33 + .../dist/firestore/test/util/helpers.d.ts | 206 + .../dist/firestore/test/util/node_persistence.d.ts | 17 + .../dist/firestore/test/util/promise.d.ts | 28 + .../firestore/test/util/spec_test_helpers.d.ts | 19 + .../dist/firestore/test/util/test_platform.d.ts | 61 + .../@firebase/firestore/dist/index.cjs.js | 23241 +++++++++++++ .../@firebase/firestore/dist/index.cjs.js.map | 1 + .../@firebase/firestore/dist/index.d.ts | 3223 ++ .../@firebase/firestore/dist/index.esm.js | 23119 +++++++++++++ .../@firebase/firestore/dist/index.esm.js.map | 1 + .../@firebase/firestore/dist/index.node.cjs.js | 33938 +++++++++++++++++++ .../@firebase/firestore/dist/index.node.cjs.js.map | 1 + .../@firebase/firestore/dist/index.node.mjs | 33795 ++++++++++++++++++ .../@firebase/firestore/dist/index.node.mjs.map | 1 + .../@firebase/firestore/dist/index.rn.js | 23143 +++++++++++++ .../@firebase/firestore/dist/index.rn.js.map | 1 + .../@firebase/firestore/dist/internal.d.ts | 8045 +++++ .../firestore/dist/lite/firestore/lite/index.d.ts | 29 + .../dist/lite/firestore/lite/register.d.ts | 23 + .../firestore/dist/lite/firestore/src/api.d.ts | 65 + .../dist/lite/firestore/src/api/aggregate.d.ts | 77 + .../dist/lite/firestore/src/api/bundle.d.ts | 94 + .../dist/lite/firestore/src/api/bytes.d.ts | 17 + .../dist/lite/firestore/src/api/cache_config.d.ts | 222 + .../dist/lite/firestore/src/api/credentials.d.ts | 222 + .../dist/lite/firestore/src/api/database.d.ts | 279 + .../dist/lite/firestore/src/api/field_path.d.ts | 17 + .../dist/lite/firestore/src/api/field_value.d.ts | 17 + .../lite/firestore/src/api/field_value_impl.d.ts | 17 + .../dist/lite/firestore/src/api/filter.d.ts | 17 + .../dist/lite/firestore/src/api/geo_point.d.ts | 17 + .../firestore/src/api/index_configuration.d.ts | 139 + .../firestore/src/api/long_polling_options.d.ts | 55 + .../dist/lite/firestore/src/api/observer.d.ts | 29 + .../dist/lite/firestore/src/api/parse_context.d.ts | 21 + .../src/api/persistent_cache_index_manager.d.ts | 59 + .../dist/lite/firestore/src/api/reference.d.ts | 17 + .../lite/firestore/src/api/reference_impl.d.ts | 536 + .../dist/lite/firestore/src/api/settings.d.ts | 108 + .../dist/lite/firestore/src/api/snapshot.d.ts | 550 + .../dist/lite/firestore/src/api/timestamp.d.ts | 17 + .../dist/lite/firestore/src/api/transaction.d.ts | 61 + .../firestore/src/api/transaction_options.d.ts | 17 + .../dist/lite/firestore/src/api/write_batch.d.ts | 31 + .../dist/lite/firestore/src/auth/user.d.ts | 36 + .../dist/lite/firestore/src/core/aggregate.d.ts | 38 + .../dist/lite/firestore/src/core/bound.d.ts | 49 + .../dist/lite/firestore/src/core/bundle.d.ts | 80 + .../dist/lite/firestore/src/core/bundle_impl.d.ts | 88 + .../firestore/src/core/component_provider.d.ts | 146 + .../lite/firestore/src/core/database_info.d.ts | 64 + .../lite/firestore/src/core/event_manager.d.ts | 133 + .../dist/lite/firestore/src/core/filter.d.ts | 130 + .../lite/firestore/src/core/firestore_client.d.ts | 138 + .../lite/firestore/src/core/listen_sequence.d.ts | 39 + .../dist/lite/firestore/src/core/order_by.d.ts | 35 + .../dist/lite/firestore/src/core/query.d.ts | 142 + .../lite/firestore/src/core/snapshot_version.d.ts | 34 + .../dist/lite/firestore/src/core/sync_engine.d.ts | 37 + .../lite/firestore/src/core/sync_engine_impl.d.ts | 255 + .../dist/lite/firestore/src/core/target.d.ts | 89 + .../firestore/src/core/target_id_generator.d.ts | 38 + .../dist/lite/firestore/src/core/transaction.d.ts | 60 + .../firestore/src/core/transaction_options.d.ts | 25 + .../firestore/src/core/transaction_runner.d.ts | 41 + .../dist/lite/firestore/src/core/types.d.ts | 65 + .../dist/lite/firestore/src/core/version.d.ts | 18 + .../dist/lite/firestore/src/core/view.d.ts | 152 + .../lite/firestore/src/core/view_snapshot.d.ts | 59 + .../firestore/dist/lite/firestore/src/index.d.ts | 28 + .../dist/lite/firestore/src/index.node.d.ts | 17 + .../dist/lite/firestore/src/index.rn.d.ts | 17 + .../src/index/directional_index_byte_encoder.d.ts | 24 + .../src/index/firestore_index_value_writer.d.ts | 34 + .../firestore/src/index/index_byte_encoder.d.ts | 31 + .../dist/lite/firestore/src/index/index_entry.d.ts | 49 + .../firestore/src/index/ordered_code_writer.d.ts | 60 + .../lite/firestore/src/lite-api/aggregate.d.ts | 100 + .../firestore/src/lite-api/aggregate_types.d.ts | 86 + .../dist/lite/firestore/src/lite-api/bytes.d.ts | 83 + .../lite/firestore/src/lite-api/components.d.ts | 49 + .../dist/lite/firestore/src/lite-api/database.d.ts | 179 + .../lite/firestore/src/lite-api/field_path.d.ts | 48 + .../lite/firestore/src/lite-api/field_value.d.ts | 33 + .../firestore/src/lite-api/field_value_impl.d.ts | 81 + .../lite/firestore/src/lite-api/geo_point.d.ts | 79 + .../dist/lite/firestore/src/lite-api/query.d.ts | 404 + .../lite/firestore/src/lite-api/reference.d.ts | 362 + .../firestore/src/lite-api/reference_impl.d.ts | 172 + .../dist/lite/firestore/src/lite-api/settings.d.ts | 77 + .../dist/lite/firestore/src/lite-api/snapshot.d.ts | 367 + .../lite/firestore/src/lite-api/timestamp.d.ts | 134 + .../lite/firestore/src/lite-api/transaction.d.ts | 122 + .../src/lite-api/transaction_options.d.ts | 23 + .../dist/lite/firestore/src/lite-api/types.d.ts | 61 + .../firestore/src/lite-api/user_data_reader.d.ts | 224 + .../firestore/src/lite-api/user_data_writer.d.ts | 48 + .../lite/firestore/src/lite-api/vector_value.d.ts | 58 + .../lite/firestore/src/lite-api/write_batch.d.ts | 125 + .../lite/firestore/src/local/bundle_cache.d.ts | 44 + .../src/local/document_overlay_cache.d.ts | 76 + .../firestore/src/local/encoded_resource_path.d.ts | 73 + .../lite/firestore/src/local/globals_cache.d.ts | 39 + .../lite/firestore/src/local/index_backfiller.d.ts | 44 + .../lite/firestore/src/local/index_manager.d.ts | 124 + .../src/local/indexeddb_bundle_cache.d.ts | 27 + .../local/indexeddb_document_overlay_cache.d.ts | 45 + .../src/local/indexeddb_globals_cache.d.ts | 25 + .../src/local/indexeddb_index_manager.d.ts | 136 + .../src/local/indexeddb_lru_delegate.d.ts | 22 + .../src/local/indexeddb_lru_delegate_impl.d.ts | 56 + .../src/local/indexeddb_mutation_batch_impl.d.ts | 35 + .../src/local/indexeddb_mutation_queue.d.ts | 99 + .../firestore/src/local/indexeddb_persistence.d.ts | 270 + .../src/local/indexeddb_remote_document_cache.d.ts | 36 + .../lite/firestore/src/local/indexeddb_schema.d.ts | 509 + .../src/local/indexeddb_schema_converter.d.ts | 43 + .../src/local/indexeddb_schema_legacy.d.ts | 29 + .../firestore/src/local/indexeddb_sentinels.d.ts | 267 + .../src/local/indexeddb_target_cache.d.ts | 81 + .../firestore/src/local/indexeddb_transaction.d.ts | 25 + .../firestore/src/local/local_documents_view.d.ts | 127 + .../lite/firestore/src/local/local_serializer.d.ts | 80 + .../dist/lite/firestore/src/local/local_store.d.ts | 41 + .../lite/firestore/src/local/local_store_impl.d.ts | 208 + .../firestore/src/local/local_view_changes.d.ts | 32 + .../firestore/src/local/lru_garbage_collector.d.ts | 102 + .../src/local/lru_garbage_collector_impl.d.ts | 37 + .../firestore/src/local/memory_bundle_cache.d.ts | 32 + .../src/local/memory_document_overlay_cache.d.ts | 37 + .../firestore/src/local/memory_globals_cache.d.ts | 25 + .../firestore/src/local/memory_index_manager.d.ts | 55 + .../firestore/src/local/memory_mutation_queue.d.ts | 80 + .../firestore/src/local/memory_persistence.d.ts | 134 + .../src/local/memory_remote_document_cache.d.ts | 33 + .../firestore/src/local/memory_target_cache.d.ts | 65 + .../lite/firestore/src/local/mutation_queue.d.ts | 123 + .../firestore/src/local/overlayed_document.d.ts | 40 + .../dist/lite/firestore/src/local/persistence.d.ts | 217 + .../firestore/src/local/persistence_promise.d.ts | 83 + .../src/local/persistence_transaction.d.ts | 34 + .../lite/firestore/src/local/query_context.d.ts | 28 + .../lite/firestore/src/local/query_engine.d.ts | 110 + .../lite/firestore/src/local/reference_set.d.ts | 68 + .../firestore/src/local/remote_document_cache.d.ts | 91 + .../src/local/remote_document_change_buffer.d.ts | 88 + .../firestore/src/local/shared_client_state.d.ts | 312 + .../src/local/shared_client_state_schema.d.ts | 84 + .../src/local/shared_client_state_syncer.d.ts | 40 + .../dist/lite/firestore/src/local/simple_db.d.ts | 233 + .../lite/firestore/src/local/target_cache.d.ts | 130 + .../dist/lite/firestore/src/local/target_data.d.ts | 127 + .../dist/lite/firestore/src/model/collections.d.ts | 50 + .../dist/lite/firestore/src/model/document.d.ts | 150 + .../firestore/src/model/document_comparator.d.ts | 19 + .../lite/firestore/src/model/document_key.d.ts | 45 + .../lite/firestore/src/model/document_set.d.ts | 57 + .../dist/lite/firestore/src/model/field_index.d.ts | 171 + .../dist/lite/firestore/src/model/field_mask.d.ts | 45 + .../dist/lite/firestore/src/model/mutation.d.ts | 270 + .../lite/firestore/src/model/mutation_batch.d.ts | 88 + .../dist/lite/firestore/src/model/normalize.d.ts | 33 + .../lite/firestore/src/model/object_value.d.ts | 78 + .../dist/lite/firestore/src/model/overlay.d.ts | 32 + .../dist/lite/firestore/src/model/path.d.ts | 121 + .../firestore/src/model/server_timestamps.d.ts | 34 + .../firestore/src/model/target_index_matcher.d.ts | 76 + .../firestore/src/model/transform_operation.d.ts | 75 + .../dist/lite/firestore/src/model/type_order.d.ts | 38 + .../dist/lite/firestore/src/model/values.d.ts | 114 + .../dist/lite/firestore/src/platform/base64.d.ts | 25 + .../firestore/src/platform/browser/base64.d.ts | 22 + .../src/platform/browser/byte_stream_reader.d.ts | 21 + .../firestore/src/platform/browser/connection.d.ts | 23 + .../src/platform/browser/connectivity_monitor.d.ts | 33 + .../lite/firestore/src/platform/browser/dom.d.ts | 20 + .../src/platform/browser/format_json.d.ts | 18 + .../src/platform/browser/random_bytes.d.ts | 22 + .../firestore/src/platform/browser/serializer.d.ts | 20 + .../src/platform/browser/snapshot_to_json.d.ts | 23 + .../src/platform/browser/text_serializer.d.ts | 24 + .../platform/browser/webchannel_connection.d.ts | 47 + .../src/platform/browser_lite/base64.d.ts | 17 + .../platform/browser_lite/byte_stream_reader.d.ts | 17 + .../src/platform/browser_lite/connection.d.ts | 21 + .../firestore/src/platform/browser_lite/dom.d.ts | 17 + .../platform/browser_lite/fetch_connection.d.ts | 28 + .../src/platform/browser_lite/format_json.d.ts | 17 + .../src/platform/browser_lite/random_bytes.d.ts | 17 + .../src/platform/browser_lite/serializer.d.ts | 17 + .../platform/browser_lite/snapshot_to_json.d.ts | 17 + .../src/platform/browser_lite/text_serializer.d.ts | 17 + .../firestore/src/platform/byte_stream_reader.d.ts | 18 + .../lite/firestore/src/platform/connection.d.ts | 21 + .../dist/lite/firestore/src/platform/dom.d.ts | 20 + .../lite/firestore/src/platform/format_json.d.ts | 18 + .../lite/firestore/src/platform/node/base64.d.ts | 22 + .../src/platform/node/byte_stream_reader.d.ts | 21 + .../firestore/src/platform/node/connection.d.ts | 23 + .../dist/lite/firestore/src/platform/node/dom.d.ts | 20 + .../firestore/src/platform/node/format_json.d.ts | 18 + .../src/platform/node/grpc_connection.d.ts | 43 + .../firestore/src/platform/node/load_protos.d.ts | 28 + .../firestore/src/platform/node/random_bytes.d.ts | 22 + .../firestore/src/platform/node/serializer.d.ts | 20 + .../src/platform/node/snapshot_to_json.d.ts | 23 + .../src/platform/node/text_serializer.d.ts | 25 + .../firestore/src/platform/node_lite/base64.d.ts | 17 + .../src/platform/node_lite/byte_stream_reader.d.ts | 17 + .../src/platform/node_lite/connection.d.ts | 21 + .../lite/firestore/src/platform/node_lite/dom.d.ts | 17 + .../src/platform/node_lite/format_json.d.ts | 17 + .../src/platform/node_lite/random_bytes.d.ts | 17 + .../src/platform/node_lite/serializer.d.ts | 17 + .../src/platform/node_lite/snapshot_to_json.d.ts | 17 + .../src/platform/node_lite/text_serializer.d.ts | 17 + .../lite/firestore/src/platform/random_bytes.d.ts | 22 + .../lite/firestore/src/platform/rn/base64.d.ts | 22 + .../src/platform/rn/byte_stream_reader.d.ts | 17 + .../lite/firestore/src/platform/rn/connection.d.ts | 17 + .../dist/lite/firestore/src/platform/rn/dom.d.ts | 17 + .../firestore/src/platform/rn/format_json.d.ts | 17 + .../firestore/src/platform/rn/random_bytes.d.ts | 17 + .../lite/firestore/src/platform/rn/serializer.d.ts | 17 + .../src/platform/rn/snapshot_to_json.d.ts | 17 + .../firestore/src/platform/rn/text_serializer.d.ts | 17 + .../firestore/src/platform/rn_lite/base64.d.ts | 17 + .../src/platform/rn_lite/byte_stream_reader.d.ts | 17 + .../firestore/src/platform/rn_lite/connection.d.ts | 17 + .../lite/firestore/src/platform/rn_lite/dom.d.ts | 17 + .../src/platform/rn_lite/format_json.d.ts | 17 + .../src/platform/rn_lite/random_bytes.d.ts | 17 + .../firestore/src/platform/rn_lite/serializer.d.ts | 17 + .../src/platform/rn_lite/snapshot_to_json.d.ts | 17 + .../src/platform/rn_lite/text_serializer.d.ts | 17 + .../lite/firestore/src/platform/serializer.d.ts | 19 + .../firestore/src/platform/snapshot_to_json.d.ts | 28 + .../firestore/src/platform/text_serializer.d.ts | 24 + .../src/protos/firestore_bundle_proto.d.ts | 72 + .../firestore/src/protos/firestore_proto_api.d.ts | 836 + .../dist/lite/firestore/src/register.d.ts | 17 + .../dist/lite/firestore/src/remote/backoff.d.ts | 106 + .../lite/firestore/src/remote/bloom_filter.d.ts | 34 + .../dist/lite/firestore/src/remote/connection.d.ts | 99 + .../firestore/src/remote/connectivity_monitor.d.ts | 47 + .../src/remote/connectivity_monitor_noop.d.ts | 21 + .../dist/lite/firestore/src/remote/datastore.d.ts | 44 + .../firestore/src/remote/existence_filter.d.ts | 22 + .../firestore/src/remote/internal_serializer.d.ts | 46 + .../firestore/src/remote/number_serializer.d.ts | 36 + .../firestore/src/remote/online_state_tracker.d.ts | 81 + .../firestore/src/remote/persistent_stream.d.ts | 308 + .../lite/firestore/src/remote/remote_event.d.ts | 156 + .../lite/firestore/src/remote/remote_store.d.ts | 85 + .../lite/firestore/src/remote/remote_syncer.d.ts | 68 + .../lite/firestore/src/remote/rest_connection.d.ts | 53 + .../dist/lite/firestore/src/remote/rpc_error.d.ts | 74 + .../dist/lite/firestore/src/remote/serializer.d.ts | 124 + .../lite/firestore/src/remote/stream_bridge.d.ts | 45 + .../lite/firestore/src/remote/watch_change.d.ts | 231 + .../dist/lite/firestore/src/util/array.d.ts | 70 + .../dist/lite/firestore/src/util/assert.d.ts | 78 + .../lite/firestore/src/util/async_observer.d.ts | 31 + .../dist/lite/firestore/src/util/async_queue.d.ts | 180 + .../lite/firestore/src/util/async_queue_impl.d.ts | 75 + .../firestore/src/util/base64_decode_error.d.ts | 22 + .../firestore/src/util/bundle_builder_impl.d.ts | 97 + .../lite/firestore/src/util/bundle_reader.d.ts | 67 + .../firestore/src/util/bundle_reader_impl.d.ts | 19 + .../src/util/bundle_reader_sync_impl.d.ts | 59 + .../dist/lite/firestore/src/util/byte_stream.d.ts | 29 + .../dist/lite/firestore/src/util/byte_string.d.ts | 46 + .../dist/lite/firestore/src/util/debug_uid.d.ts | 28 + .../dist/lite/firestore/src/util/error.d.ts | 195 + .../lite/firestore/src/util/input_validation.d.ts | 56 + .../lite/firestore/src/util/json_validation.d.ts | 70 + .../dist/lite/firestore/src/util/log.d.ts | 39 + .../dist/lite/firestore/src/util/logic_utils.d.ts | 52 + .../dist/lite/firestore/src/util/misc.d.ts | 46 + .../dist/lite/firestore/src/util/node_api.d.ts | 58 + .../dist/lite/firestore/src/util/obj.d.ts | 23 + .../dist/lite/firestore/src/util/obj_map.d.ts | 48 + .../dist/lite/firestore/src/util/promise.d.ts | 34 + .../dist/lite/firestore/src/util/sorted_map.d.ts | 100 + .../dist/lite/firestore/src/util/sorted_set.d.ts | 80 + .../lite/firestore/src/util/testing_hooks.d.ts | 52 + .../lite/firestore/src/util/testing_hooks_spi.d.ts | 93 + .../dist/lite/firestore/src/util/types.d.ts | 45 + .../test/integration/api/aggregation.test.d.ts | 17 + .../integration/api/array_transforms.test.d.ts | 17 + .../test/integration/api/batch_writes.test.d.ts | 17 + .../test/integration/api/bundle.test.d.ts | 17 + .../api/composite_index_query.test.d.ts | 17 + .../test/integration/api/cursor.test.d.ts | 17 + .../test/integration/api/database.test.d.ts | 17 + .../test/integration/api/fields.test.d.ts | 17 + .../test/integration/api/get_options.test.d.ts | 17 + .../integration/api/index_configuration.test.d.ts | 17 + .../integration/api/numeric_transforms.test.d.ts | 17 + .../api/persistent_cache_index_manager.test.d.ts | 17 + .../test/integration/api/provider.test.d.ts | 17 + .../firestore/test/integration/api/query.test.d.ts | 18 + .../integration/api/server_timestamp.test.d.ts | 17 + .../firestore/test/integration/api/smoke.test.d.ts | 17 + .../api/snapshot_listener_source.test.d.ts | 17 + .../test/integration/api/transactions.test.d.ts | 17 + .../firestore/test/integration/api/type.test.d.ts | 17 + .../test/integration/api/validation.test.d.ts | 17 + .../test/integration/api_internal/auth.test.d.ts | 17 + .../integration/api_internal/database.test.d.ts | 17 + .../api_internal/idle_timeout.test.d.ts | 17 + .../integration/api_internal/transaction.test.d.ts | 17 + .../lite/firestore/test/integration/bootstrap.d.ts | 17 + .../test/integration/browser/indexeddb.test.d.ts | 17 + .../test/integration/browser/webchannel.test.d.ts | 17 + .../test/integration/prime_backend.test.d.ts | 17 + .../test/integration/remote/remote.test.d.ts | 17 + .../test/integration/remote/stream.test.d.ts | 54 + .../util/composite_index_test_helper.d.ts | 41 + .../test/integration/util/events_accumulator.d.ts | 39 + .../test/integration/util/firebase_export.d.ts | 23 + .../firestore/test/integration/util/helpers.d.ts | 138 + .../test/integration/util/internal_helpers.d.ts | 34 + .../firestore/test/integration/util/settings.d.ts | 24 + .../test/integration/util/testing_hooks_util.d.ts | 44 + .../dist/lite/firestore/test/lite/bootstrap.d.ts | 17 + .../dist/lite/firestore/test/lite/helpers.d.ts | 41 + .../lite/firestore/test/lite/integration.test.d.ts | 17 + .../dist/lite/firestore/test/register.d.ts | 17 + .../firestore/test/unit/api/aggregate.test.d.ts | 17 + .../lite/firestore/test/unit/api/bytes.test.d.ts | 17 + .../firestore/test/unit/api/database.test.d.ts | 17 + .../test/unit/api/document_change.test.d.ts | 17 + .../firestore/test/unit/api/field_path.test.d.ts | 17 + .../firestore/test/unit/api/field_value.test.d.ts | 17 + .../firestore/test/unit/api/geo_point.test.d.ts | 17 + .../test/unit/api/long_polling_options.test.d.ts | 17 + .../firestore/test/unit/api/timestamp.test.d.ts | 17 + .../firestore/test/unit/api/vector_value.test.d.ts | 17 + .../dist/lite/firestore/test/unit/bootstrap.d.ts | 24 + .../test/unit/core/event_manager.test.d.ts | 17 + .../lite/firestore/test/unit/core/filter.test.d.ts | 17 + .../test/unit/core/listen_sequence.test.d.ts | 17 + .../lite/firestore/test/unit/core/query.test.d.ts | 17 + .../lite/firestore/test/unit/core/view.test.d.ts | 17 + .../test/unit/core/webchannel_wrapper.test.d.ts | 17 + .../index/firestore_index_value_writer.test.d.ts | 1 + .../test/unit/index/ordered_code_writer.test.d.ts | 1 + .../firestore/test/unit/lite-api/types.test.d.ts | 1 + .../test/unit/local/bundle_cache.test.d.ts | 17 + .../test/unit/local/counting_query_engine.d.ts | 60 + .../unit/local/document_overlay_cache.test.d.ts | 1 + .../unit/local/encoded_resource_path.test.d.ts | 17 + .../test/unit/local/globals_cache.test.d.ts | 17 + .../test/unit/local/index_backfiller.test.d.ts | 17 + .../test/unit/local/index_manager.test.d.ts | 17 + .../unit/local/indexeddb_persistence.test.d.ts | 17 + .../test/unit/local/local_serializer.test.d.ts | 17 + .../test/unit/local/local_store.test.d.ts | 24 + .../unit/local/local_store_indexeddb.test.d.ts | 17 + .../unit/local/lru_garbage_collector.test.d.ts | 17 + .../test/unit/local/mutation_queue.test.d.ts | 17 + .../test/unit/local/persistence_promise.test.d.ts | 17 + .../test/unit/local/persistence_test_helpers.d.ts | 67 + .../unit/local/persistence_transaction.test.d.ts | 17 + .../test/unit/local/query_engine.test.d.ts | 17 + .../test/unit/local/reference_set.test.d.ts | 17 + .../unit/local/remote_document_cache.test.d.ts | 17 + .../local/remote_document_change_buffer.test.d.ts | 17 + .../firestore/test/unit/local/simple_db.test.d.ts | 17 + .../test/unit/local/target_cache.test.d.ts | 17 + .../test/unit/local/test_bundle_cache.d.ts | 32 + .../unit/local/test_document_overlay_cache.d.ts | 39 + .../test/unit/local/test_globals_cache.d.ts | 29 + .../test/unit/local/test_index_manager.d.ts | 44 + .../test/unit/local/test_mutation_queue.d.ts | 43 + .../unit/local/test_remote_document_cache.d.ts | 54 + .../local/test_remote_document_change_buffer.d.ts | 34 + .../test/unit/local/test_target_cache.d.ts | 46 + .../web_storage_shared_client_state.test.d.ts | 17 + .../firestore/test/unit/model/document.test.d.ts | 17 + .../test/unit/model/document_set.test.d.ts | 17 + .../test/unit/model/field_index.test.d.ts | 17 + .../firestore/test/unit/model/mutation.test.d.ts | 17 + .../test/unit/model/object_value.test.d.ts | 17 + .../test/unit/model/object_value_builder.test.d.ts | 17 + .../lite/firestore/test/unit/model/path.test.d.ts | 17 + .../firestore/test/unit/model/target.test.d.ts | 17 + .../test/unit/model/target_index_matcher.test.d.ts | 17 + .../firestore/test/unit/model/values.test.d.ts | 17 + .../test/unit/remote/bloom_filter.test.d.ts | 1 + .../bloom_filter_golden_test_data/index.d.ts | 40 + .../firestore/test/unit/remote/datastore.test.d.ts | 17 + .../test/unit/remote/fetch_connection.test.d.ts | 17 + .../test/unit/remote/remote_event.test.d.ts | 17 + .../test/unit/remote/rest_connection.test.d.ts | 28 + .../test/unit/remote/serializer.browser.test.d.ts | 17 + .../test/unit/remote/serializer.helper.d.ts | 25 + .../test/unit/remote/serializer.node.test.d.ts | 21 + .../test/unit/specs/bundle_spec.test.d.ts | 36 + .../test/unit/specs/collection_spec.test.d.ts | 17 + .../firestore/test/unit/specs/describe_spec.d.ts | 44 + .../unit/specs/existence_filter_spec.test.d.ts | 17 + .../unit/specs/garbage_collection_spec.test.d.ts | 17 + .../firestore/test/unit/specs/index_spec.test.d.ts | 17 + .../firestore/test/unit/specs/limbo_spec.test.d.ts | 17 + .../firestore/test/unit/specs/limit_spec.test.d.ts | 17 + .../test/unit/specs/listen_source_spec.test.d.ts | 17 + .../test/unit/specs/listen_spec.test.d.ts | 17 + .../test/unit/specs/offline_spec.test.d.ts | 17 + .../test/unit/specs/orderby_spec.test.d.ts | 17 + .../firestore/test/unit/specs/perf_spec.test.d.ts | 17 + .../test/unit/specs/persistence_spec.test.d.ts | 17 + .../firestore/test/unit/specs/query_spec.test.d.ts | 17 + .../test/unit/specs/recovery_spec.test.d.ts | 17 + .../test/unit/specs/remote_store_spec.test.d.ts | 17 + .../test/unit/specs/resume_token_spec.test.d.ts | 17 + .../firestore/test/unit/specs/spec_builder.d.ts | 287 + .../firestore/test/unit/specs/spec_rpc_error.d.ts | 24 + .../test/unit/specs/spec_test_components.d.ts | 156 + .../test/unit/specs/spec_test_runner.d.ts | 323 + .../firestore/test/unit/specs/write_spec.test.d.ts | 17 + .../lite/firestore/test/unit/util/array.test.d.ts | 17 + .../lite/firestore/test/unit/util/assert.test.d.ts | 17 + .../firestore/test/unit/util/async_queue.test.d.ts | 17 + .../lite/firestore/test/unit/util/base64.test.d.ts | 17 + .../lite/firestore/test/unit/util/bundle.test.d.ts | 8 + .../lite/firestore/test/unit/util/bundle_data.d.ts | 50 + .../firestore/test/unit/util/logic_utils.test.d.ts | 17 + .../lite/firestore/test/unit/util/misc.test.d.ts | 17 + .../firestore/test/unit/util/node_api.test.d.ts | 17 + .../firestore/test/unit/util/obj_map.test.d.ts | 17 + .../firestore/test/unit/util/sorted_map.test.d.ts | 17 + .../firestore/test/unit/util/sorted_set.test.d.ts | 17 + .../dist/lite/firestore/test/util/api_helpers.d.ts | 49 + .../lite/firestore/test/util/equality_matcher.d.ts | 33 + .../dist/lite/firestore/test/util/helpers.d.ts | 206 + .../lite/firestore/test/util/node_persistence.d.ts | 17 + .../dist/lite/firestore/test/util/promise.d.ts | 28 + .../firestore/test/util/spec_test_helpers.d.ts | 19 + .../lite/firestore/test/util/test_platform.d.ts | 61 + .../firestore/dist/lite/index.browser.esm.js | 7660 +++++ .../firestore/dist/lite/index.browser.esm.js.map | 1 + .../@firebase/firestore/dist/lite/index.cjs.js | 7660 +++++ .../@firebase/firestore/dist/lite/index.cjs.js.map | 1 + .../@firebase/firestore/dist/lite/index.d.ts | 2030 ++ .../firestore/dist/lite/index.node.cjs.js | 9870 ++++++ .../firestore/dist/lite/index.node.cjs.js.map | 1 + .../@firebase/firestore/dist/lite/index.node.mjs | 9798 ++++++ .../firestore/dist/lite/index.node.mjs.map | 1 + .../@firebase/firestore/dist/lite/index.rn.esm.js | 7672 +++++ .../firestore/dist/lite/index.rn.esm.js.map | 1 + .../@firebase/firestore/dist/lite/internal.d.ts | 6201 ++++ .../@firebase/firestore/dist/lite/private.d.ts | 5939 ++++ .../@firebase/firestore/dist/private.d.ts | 7590 +++++ .../@firebase/firestore/lite/package.json | 14 + .../node_modules/@firebase/firestore/package.json | 150 + 879 files changed, 272138 insertions(+) create mode 100644 frontend-old/node_modules/@firebase/firestore/README.md create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/lite/index.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/lite/register.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/aggregate.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/bundle.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/bytes.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/cache_config.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/credentials.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/database.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/field_path.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/field_value.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/field_value_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/filter.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/geo_point.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/index_configuration.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/long_polling_options.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/observer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/parse_context.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/persistent_cache_index_manager.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/reference.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/reference_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/settings.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/snapshot.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/timestamp.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/transaction.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/transaction_options.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/write_batch.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/auth/user.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/aggregate.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/bound.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/bundle.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/bundle_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/component_provider.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/database_info.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/event_manager.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/filter.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/firestore_client.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/listen_sequence.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/order_by.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/query.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/snapshot_version.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/sync_engine.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/sync_engine_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/target.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/target_id_generator.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/transaction.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/transaction_options.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/transaction_runner.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/types.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/version.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/view.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/view_snapshot.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/global_index.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index.node.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index.rn.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index/directional_index_byte_encoder.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index/firestore_index_value_writer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index/index_byte_encoder.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index/index_entry.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index/ordered_code_writer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/aggregate.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/aggregate_types.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/bytes.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/components.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/database.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/field_path.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/field_value.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/field_value_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/geo_point.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/query.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/reference.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/reference_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/settings.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/snapshot.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/timestamp.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/transaction.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/transaction_options.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/types.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/user_data_reader.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/user_data_writer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/vector_value.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/write_batch.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/bundle_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/document_overlay_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/encoded_resource_path.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/globals_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/index_backfiller.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/index_manager.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_bundle_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_document_overlay_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_globals_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_index_manager.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_lru_delegate.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_lru_delegate_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_mutation_batch_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_mutation_queue.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_persistence.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_remote_document_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_schema.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_schema_converter.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_schema_legacy.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_sentinels.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_target_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_transaction.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/local_documents_view.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/local_serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/local_store.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/local_store_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/local_view_changes.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/lru_garbage_collector.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/lru_garbage_collector_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_bundle_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_document_overlay_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_globals_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_index_manager.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_mutation_queue.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_persistence.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_remote_document_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_target_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/mutation_queue.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/overlayed_document.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/persistence.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/persistence_promise.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/persistence_transaction.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/query_context.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/query_engine.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/reference_set.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/remote_document_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/remote_document_change_buffer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/shared_client_state.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/shared_client_state_schema.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/shared_client_state_syncer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/simple_db.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/target_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/target_data.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/collections.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/document.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/document_comparator.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/document_key.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/document_set.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/field_index.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/field_mask.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/mutation.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/mutation_batch.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/normalize.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/object_value.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/overlay.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/path.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/server_timestamps.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/target_index_matcher.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/transform_operation.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/type_order.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/values.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/base64.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/base64.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/byte_stream_reader.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/connectivity_monitor.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/dom.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/format_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/random_bytes.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/snapshot_to_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/text_serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/webchannel_connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/base64.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/byte_stream_reader.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/dom.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/fetch_connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/format_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/random_bytes.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/snapshot_to_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/text_serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/byte_stream_reader.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/dom.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/format_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/base64.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/byte_stream_reader.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/dom.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/format_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/grpc_connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/load_protos.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/random_bytes.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/snapshot_to_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/text_serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/base64.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/byte_stream_reader.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/dom.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/format_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/random_bytes.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/snapshot_to_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/text_serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/random_bytes.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/base64.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/byte_stream_reader.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/dom.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/format_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/random_bytes.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/snapshot_to_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/text_serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/base64.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/byte_stream_reader.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/dom.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/format_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/random_bytes.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/snapshot_to_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/text_serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/snapshot_to_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/text_serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/protos/firestore_bundle_proto.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/protos/firestore_proto_api.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/register.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/backoff.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/bloom_filter.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/connectivity_monitor.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/connectivity_monitor_noop.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/datastore.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/existence_filter.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/internal_serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/number_serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/online_state_tracker.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/persistent_stream.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/remote_event.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/remote_store.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/remote_syncer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/rest_connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/rpc_error.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/stream_bridge.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/watch_change.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/tsdoc-metadata.json create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/array.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/assert.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/async_observer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/async_queue.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/async_queue_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/base64_decode_error.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/bundle_builder_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/bundle_reader.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/bundle_reader_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/bundle_reader_sync_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/byte_stream.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/byte_string.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/debug_uid.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/error.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/input_validation.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/json_validation.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/log.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/logic_utils.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/misc.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/node_api.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/obj.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/obj_map.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/promise.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/sorted_map.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/sorted_set.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/testing_hooks.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/testing_hooks_spi.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/types.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/aggregation.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/array_transforms.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/batch_writes.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/bundle.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/composite_index_query.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/cursor.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/database.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/fields.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/get_options.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/index_configuration.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/numeric_transforms.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/persistent_cache_index_manager.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/provider.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/query.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/server_timestamp.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/smoke.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/snapshot_listener_source.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/transactions.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/type.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/validation.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api_internal/auth.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api_internal/database.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api_internal/idle_timeout.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api_internal/transaction.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/bootstrap.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/browser/indexeddb.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/browser/webchannel.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/prime_backend.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/remote/remote.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/remote/stream.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/util/composite_index_test_helper.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/util/events_accumulator.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/util/firebase_export.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/util/helpers.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/util/internal_helpers.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/util/settings.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/util/testing_hooks_util.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/lite/bootstrap.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/lite/helpers.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/lite/integration.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/register.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/aggregate.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/bytes.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/database.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/document_change.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/field_path.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/field_value.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/geo_point.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/long_polling_options.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/timestamp.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/vector_value.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/bootstrap.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/core/event_manager.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/core/filter.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/core/listen_sequence.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/core/query.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/core/view.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/core/webchannel_wrapper.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/index/firestore_index_value_writer.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/index/ordered_code_writer.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/lite-api/types.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/bundle_cache.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/counting_query_engine.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/document_overlay_cache.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/encoded_resource_path.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/globals_cache.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/index_backfiller.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/index_manager.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/indexeddb_persistence.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/local_serializer.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/local_store.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/local_store_indexeddb.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/lru_garbage_collector.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/mutation_queue.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/persistence_promise.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/persistence_test_helpers.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/persistence_transaction.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/query_engine.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/reference_set.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/remote_document_cache.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/remote_document_change_buffer.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/simple_db.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/target_cache.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_bundle_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_document_overlay_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_globals_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_index_manager.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_mutation_queue.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_remote_document_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_remote_document_change_buffer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_target_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/web_storage_shared_client_state.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/document.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/document_set.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/field_index.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/mutation.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/object_value.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/object_value_builder.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/path.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/target.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/target_index_matcher.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/values.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/bloom_filter.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/bloom_filter_golden_test_data/index.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/datastore.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/fetch_connection.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/remote_event.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/rest_connection.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/serializer.browser.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/serializer.helper.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/serializer.node.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/bundle_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/collection_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/describe_spec.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/existence_filter_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/garbage_collection_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/index_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/limbo_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/limit_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/listen_source_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/listen_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/offline_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/orderby_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/perf_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/persistence_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/query_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/recovery_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/remote_store_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/resume_token_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/spec_builder.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/spec_rpc_error.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/spec_test_components.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/spec_test_runner.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/write_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/array.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/assert.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/async_queue.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/base64.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/bundle.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/bundle_data.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/logic_utils.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/misc.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/node_api.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/obj_map.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/sorted_map.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/sorted_set.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/util/api_helpers.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/util/equality_matcher.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/util/helpers.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/util/node_persistence.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/util/promise.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/util/spec_test_helpers.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/firestore/test/util/test_platform.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/index.cjs.js create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/index.cjs.js.map create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/index.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/index.esm.js create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/index.esm.js.map create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/index.node.cjs.js create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/index.node.cjs.js.map create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/index.node.mjs create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/index.node.mjs.map create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/index.rn.js create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/index.rn.js.map create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/internal.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/lite/index.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/lite/register.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/aggregate.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/bundle.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/bytes.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/cache_config.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/credentials.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/database.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/field_path.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/field_value.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/field_value_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/filter.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/geo_point.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/index_configuration.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/long_polling_options.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/observer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/parse_context.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/persistent_cache_index_manager.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/reference.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/reference_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/settings.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/snapshot.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/timestamp.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/transaction.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/transaction_options.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/write_batch.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/auth/user.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/aggregate.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/bound.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/bundle.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/bundle_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/component_provider.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/database_info.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/event_manager.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/filter.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/firestore_client.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/listen_sequence.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/order_by.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/query.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/snapshot_version.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/sync_engine.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/sync_engine_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/target.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/target_id_generator.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/transaction.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/transaction_options.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/transaction_runner.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/types.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/version.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/view.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/view_snapshot.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index.node.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index.rn.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/directional_index_byte_encoder.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/firestore_index_value_writer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/index_byte_encoder.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/index_entry.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/ordered_code_writer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/aggregate.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/aggregate_types.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/bytes.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/components.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/database.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/field_path.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/field_value.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/field_value_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/geo_point.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/query.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/reference.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/reference_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/settings.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/snapshot.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/timestamp.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/transaction.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/transaction_options.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/types.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/user_data_reader.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/user_data_writer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/vector_value.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/write_batch.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/bundle_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/document_overlay_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/encoded_resource_path.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/globals_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/index_backfiller.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/index_manager.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_bundle_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_document_overlay_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_globals_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_index_manager.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_lru_delegate.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_lru_delegate_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_mutation_batch_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_mutation_queue.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_persistence.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_remote_document_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_schema.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_schema_converter.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_schema_legacy.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_sentinels.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_target_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_transaction.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_documents_view.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_store.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_store_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_view_changes.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/lru_garbage_collector.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/lru_garbage_collector_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_bundle_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_document_overlay_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_globals_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_index_manager.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_mutation_queue.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_persistence.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_remote_document_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_target_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/mutation_queue.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/overlayed_document.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/persistence.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/persistence_promise.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/persistence_transaction.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/query_context.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/query_engine.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/reference_set.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/remote_document_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/remote_document_change_buffer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/shared_client_state.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/shared_client_state_schema.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/shared_client_state_syncer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/simple_db.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/target_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/target_data.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/collections.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document_comparator.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document_key.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document_set.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/field_index.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/field_mask.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/mutation.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/mutation_batch.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/normalize.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/object_value.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/overlay.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/path.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/server_timestamps.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/target_index_matcher.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/transform_operation.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/type_order.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/values.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/base64.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/base64.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/byte_stream_reader.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/connectivity_monitor.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/dom.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/format_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/random_bytes.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/snapshot_to_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/text_serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/webchannel_connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/base64.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/byte_stream_reader.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/dom.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/fetch_connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/format_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/random_bytes.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/snapshot_to_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/text_serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/byte_stream_reader.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/dom.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/format_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/base64.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/byte_stream_reader.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/dom.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/format_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/grpc_connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/load_protos.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/random_bytes.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/snapshot_to_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/text_serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/base64.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/byte_stream_reader.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/dom.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/format_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/random_bytes.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/snapshot_to_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/text_serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/random_bytes.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/base64.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/byte_stream_reader.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/dom.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/format_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/random_bytes.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/snapshot_to_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/text_serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/base64.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/byte_stream_reader.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/dom.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/format_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/random_bytes.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/snapshot_to_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/text_serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/snapshot_to_json.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/text_serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/protos/firestore_bundle_proto.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/protos/firestore_proto_api.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/register.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/backoff.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/bloom_filter.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/connectivity_monitor.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/connectivity_monitor_noop.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/datastore.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/existence_filter.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/internal_serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/number_serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/online_state_tracker.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/persistent_stream.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/remote_event.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/remote_store.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/remote_syncer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/rest_connection.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/rpc_error.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/serializer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/stream_bridge.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/watch_change.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/array.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/assert.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/async_observer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/async_queue.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/async_queue_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/base64_decode_error.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_builder_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_reader.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_reader_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_reader_sync_impl.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/byte_stream.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/byte_string.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/debug_uid.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/error.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/input_validation.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/json_validation.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/log.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/logic_utils.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/misc.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/node_api.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/obj.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/obj_map.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/promise.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/sorted_map.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/sorted_set.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/testing_hooks.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/testing_hooks_spi.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/types.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/aggregation.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/array_transforms.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/batch_writes.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/bundle.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/composite_index_query.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/cursor.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/database.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/fields.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/get_options.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/index_configuration.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/numeric_transforms.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/persistent_cache_index_manager.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/provider.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/query.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/server_timestamp.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/smoke.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/snapshot_listener_source.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/transactions.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/type.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/validation.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/auth.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/database.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/idle_timeout.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/transaction.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/bootstrap.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/browser/indexeddb.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/browser/webchannel.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/prime_backend.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/remote/remote.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/remote/stream.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/composite_index_test_helper.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/events_accumulator.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/firebase_export.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/helpers.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/internal_helpers.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/settings.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/testing_hooks_util.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/lite/bootstrap.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/lite/helpers.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/lite/integration.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/register.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/aggregate.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/bytes.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/database.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/document_change.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/field_path.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/field_value.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/geo_point.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/long_polling_options.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/timestamp.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/vector_value.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/bootstrap.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/event_manager.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/filter.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/listen_sequence.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/query.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/view.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/webchannel_wrapper.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/index/firestore_index_value_writer.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/index/ordered_code_writer.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/lite-api/types.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/bundle_cache.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/counting_query_engine.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/document_overlay_cache.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/encoded_resource_path.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/globals_cache.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/index_backfiller.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/index_manager.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/indexeddb_persistence.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/local_serializer.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/local_store.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/local_store_indexeddb.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/lru_garbage_collector.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/mutation_queue.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/persistence_promise.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/persistence_test_helpers.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/persistence_transaction.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/query_engine.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/reference_set.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/remote_document_cache.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/remote_document_change_buffer.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/simple_db.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/target_cache.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_bundle_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_document_overlay_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_globals_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_index_manager.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_mutation_queue.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_remote_document_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_remote_document_change_buffer.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_target_cache.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/web_storage_shared_client_state.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/document.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/document_set.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/field_index.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/mutation.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/object_value.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/object_value_builder.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/path.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/target.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/target_index_matcher.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/values.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/bloom_filter.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/bloom_filter_golden_test_data/index.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/datastore.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/fetch_connection.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/remote_event.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/rest_connection.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/serializer.browser.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/serializer.helper.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/serializer.node.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/bundle_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/collection_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/describe_spec.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/existence_filter_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/garbage_collection_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/index_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/limbo_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/limit_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/listen_source_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/listen_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/offline_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/orderby_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/perf_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/persistence_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/query_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/recovery_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/remote_store_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/resume_token_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_builder.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_rpc_error.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_test_components.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_test_runner.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/write_spec.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/array.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/assert.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/async_queue.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/base64.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/bundle.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/bundle_data.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/logic_utils.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/misc.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/node_api.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/obj_map.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/sorted_map.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/sorted_set.test.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/api_helpers.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/equality_matcher.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/helpers.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/node_persistence.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/promise.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/spec_test_helpers.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/test_platform.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/index.browser.esm.js create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/index.browser.esm.js.map create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/index.cjs.js create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/index.cjs.js.map create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/index.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.cjs.js create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.cjs.js.map create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.mjs create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.mjs.map create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/index.rn.esm.js create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/index.rn.esm.js.map create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/internal.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/lite/private.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/dist/private.d.ts create mode 100644 frontend-old/node_modules/@firebase/firestore/lite/package.json create mode 100644 frontend-old/node_modules/@firebase/firestore/package.json (limited to 'frontend-old/node_modules/@firebase/firestore') diff --git a/frontend-old/node_modules/@firebase/firestore/README.md b/frontend-old/node_modules/@firebase/firestore/README.md new file mode 100644 index 0000000..504f6ab --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/README.md @@ -0,0 +1,24 @@ +# @firebase/firestore + +This is the [Cloud Firestore](https://firebase.google.com/docs/firestore/) component of the +[Firebase JS SDK](https://www.npmjs.com/package/firebase). + +**This package is not intended for direct usage, and should only be used via the officially +supported [firebase](https://www.npmjs.com/package/firebase) package.** + +If you are developing a Node.js application that requires administrative access to Cloud Firestore, +use the [`@google-cloud/firestore`](https://www.npmjs.com/package/@google-cloud/firestore) Server +SDK with your developer credentials. + +## Documentation + +For comprehensive documentation please see the [Firebase Reference +Docs][reference-docs]. + +[reference-docs]: https://firebase.google.com/docs/reference/js/ + +## Contributing +See [Contributing to the Firebase SDK](../../CONTRIBUTING.md) for general +information about contributing to the firebase-js-sdk repo and +[Contributing to the Cloud Firestore Component](./CONTRIBUTING.md) for +details specific to the Cloud Firestore code and tests. diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/lite/index.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/lite/index.d.ts new file mode 100644 index 0000000..86dd215 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/lite/index.d.ts @@ -0,0 +1,29 @@ +/** + * Firestore Lite + * + * @remarks Firestore Lite is a small online-only SDK that allows read + * and write access to your Firestore database. All operations connect + * directly to the backend, and `onSnapshot()` APIs are not supported. + * @packageDocumentation + */ +export { aggregateQuerySnapshotEqual, getCount, getAggregate, count, sum, average, aggregateFieldEqual } from '../src/lite-api/aggregate'; +export { AggregateField, AggregateFieldType, AggregateSpec, AggregateSpecData, AggregateQuerySnapshot, AggregateType } from '../src/lite-api/aggregate_types'; +export { FirestoreSettings as Settings } from '../src/lite-api/settings'; +export { Firestore as Firestore, EmulatorMockTokenOptions, initializeFirestore, getFirestore, terminate, connectFirestoreEmulator } from '../src/lite-api/database'; +export { DocumentData, UpdateData, WithFieldValue, PartialWithFieldValue, SetOptions, DocumentReference, Query, CollectionReference, collection, collectionGroup, doc, refEqual, queryEqual } from '../src/lite-api/reference'; +export { and, endAt, endBefore, startAt, startAfter, limit, limitToLast, where, or, orderBy, query, QueryConstraint, QueryConstraintType, QueryCompositeFilterConstraint, QueryFilterConstraint, QueryFieldFilterConstraint, QueryOrderByConstraint, QueryLimitConstraint, QueryNonFilterConstraint, QueryStartAtConstraint, QueryEndAtConstraint, OrderByDirection, WhereFilterOp } from '../src/lite-api/query'; +export { addDoc, deleteDoc, updateDoc, setDoc, getDoc, getDocs } from '../src/lite-api/reference_impl'; +export { Primitive, NestedUpdateFields, ChildUpdateFields, AddPrefixToKeys, UnionToIntersection } from '../src/lite-api/types'; +export { FieldPath, documentId } from '../src/lite-api/field_path'; +export { FieldValue } from '../src/lite-api/field_value'; +export { increment, arrayRemove, arrayUnion, serverTimestamp, deleteField, vector } from '../src/lite-api/field_value_impl'; +export { FirestoreDataConverter, DocumentSnapshot, QueryDocumentSnapshot, QuerySnapshot, snapshotEqual } from '../src/lite-api/snapshot'; +export { VectorValue } from '../src/lite-api/vector_value'; +export { WriteBatch, writeBatch } from '../src/lite-api/write_batch'; +export { TransactionOptions } from '../src/lite-api/transaction_options'; +export { Transaction, runTransaction } from '../src/lite-api/transaction'; +export { setLogLevel, LogLevelString as LogLevel } from '../src/util/log'; +export { Bytes } from '../src/lite-api/bytes'; +export { GeoPoint } from '../src/lite-api/geo_point'; +export { Timestamp } from '../src/lite-api/timestamp'; +export { FirestoreErrorCode, FirestoreError } from '../src/util/error'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/lite/register.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/lite/register.d.ts new file mode 100644 index 0000000..21b4ab3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/lite/register.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Firestore } from '../src/lite-api/database'; +declare module '@firebase/component' { + interface NameServiceMapping { + 'firestore/lite': Firestore; + } +} +export declare function registerFirestore(): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api.d.ts new file mode 100644 index 0000000..f5d6e02 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api.d.ts @@ -0,0 +1,65 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { aggregateFieldEqual, aggregateQuerySnapshotEqual, average, count, getAggregateFromServer, getCountFromServer, sum } from './api/aggregate'; +export { AggregateField, AggregateFieldType, AggregateQuerySnapshot, AggregateSpec, AggregateSpecData, AggregateType } from './lite-api/aggregate_types'; +export { FirestoreLocalCache, MemoryCacheSettings, MemoryEagerGarbageCollector, memoryEagerGarbageCollector, MemoryGarbageCollector, MemoryLocalCache, memoryLocalCache, MemoryLruGarbageCollector, memoryLruGarbageCollector, PersistentCacheSettings, PersistentLocalCache, persistentLocalCache, PersistentMultipleTabManager, persistentMultipleTabManager, PersistentSingleTabManager, persistentSingleTabManager, PersistentSingleTabManagerSettings, PersistentTabManager } from './api/cache_config'; +export { documentId, FieldPath } from './api/field_path'; +export { clearIndexedDbPersistence, connectFirestoreEmulator, disableNetwork, EmulatorMockTokenOptions, enableIndexedDbPersistence, enableMultiTabIndexedDbPersistence, enableNetwork, ensureFirestoreConfigured, Firestore, getFirestore, initializeFirestore, loadBundle, namedQuery, terminate, waitForPendingWrites } from './api/database'; +export { LoadBundleTask, LoadBundleTaskProgress, TaskState } from './api/bundle'; +export { FirestoreSettings, PersistenceSettings } from './api/settings'; +export type { PrivateSettings } from './lite-api/settings'; +export { ExperimentalLongPollingOptions } from './api/long_polling_options'; +export { DocumentChange, DocumentChangeType, DocumentSnapshot, documentSnapshotFromJSON, FirestoreDataConverter, QueryDocumentSnapshot, QuerySnapshot, querySnapshotFromJSON, snapshotEqual, SnapshotMetadata, SnapshotOptions } from './api/snapshot'; +export { collection, collectionGroup, CollectionReference, doc, DocumentData, DocumentReference, PartialWithFieldValue, Query, queryEqual, refEqual, SetOptions, UpdateData, WithFieldValue } from './api/reference'; +export { and, endAt, endBefore, limit, limitToLast, or, orderBy, OrderByDirection, query, QueryCompositeFilterConstraint, QueryConstraint, QueryConstraintType, QueryEndAtConstraint, QueryFieldFilterConstraint, QueryFilterConstraint, QueryLimitConstraint, QueryNonFilterConstraint, QueryOrderByConstraint, QueryStartAtConstraint, startAfter, startAt, where, WhereFilterOp } from './api/filter'; +export { ListenSource, SnapshotListenOptions, Unsubscribe } from './api/reference_impl'; +export { TransactionOptions } from './api/transaction_options'; +export { runTransaction, Transaction } from './api/transaction'; +export { addDoc, deleteDoc, executeWrite, getDoc, getDocFromCache, getDocFromServer, getDocs, getDocsFromCache, getDocsFromServer, onSnapshot, onSnapshotsInSync, onSnapshotResume, setDoc, updateDoc } from './api/reference_impl'; +export { FieldValue } from './api/field_value'; +export { arrayRemove, arrayUnion, deleteField, increment, serverTimestamp, vector } from './api/field_value_impl'; +export { VectorValue } from './lite-api/vector_value'; +export { LogLevelString as LogLevel, setLogLevel } from './util/log'; +export { Bytes } from './api/bytes'; +export { WriteBatch, writeBatch } from './api/write_batch'; +export { GeoPoint } from './api/geo_point'; +export { Timestamp } from './api/timestamp'; +export { CACHE_SIZE_UNLIMITED } from './api/database'; +export { FirestoreError, FirestoreErrorCode } from './util/error'; +export { AbstractUserDataWriter } from './lite-api/user_data_writer'; +export { AddPrefixToKeys, ChildUpdateFields, NestedUpdateFields, Primitive, UnionToIntersection } from '../src/lite-api/types'; +export { Index, IndexConfiguration, IndexField, setIndexConfiguration } from './api/index_configuration'; +export { PersistentCacheIndexManager, getPersistentCacheIndexManager, deleteAllPersistentCacheIndexes, enablePersistentCacheIndexAutoCreation, disablePersistentCacheIndexAutoCreation } from './api/persistent_cache_index_manager'; +/** + * Internal exports + */ +export { isBase64Available as _isBase64Available } from './platform/base64'; +export { DatabaseId as _DatabaseId } from './core/database_info'; +export { _internalQueryToProtoQueryTarget, _internalAggregationQueryToProtoRunAggregationQueryRequest } from './remote/internal_serializer'; +export { cast as _cast, validateIsNotUsedTogether as _validateIsNotUsedTogether } from './util/input_validation'; +export { DocumentKey as _DocumentKey } from './model/document_key'; +export { debugAssert as _debugAssert } from './util/assert'; +export { FieldPath as _FieldPath } from './model/path'; +export type { ResourcePath as _ResourcePath } from './model/path'; +export { ByteString as _ByteString } from './util/byte_string'; +export { logWarn as _logWarn } from './util/log'; +export { AutoId as _AutoId } from './util/misc'; +export type { AuthTokenFactory, FirstPartyCredentialsSettings } from './api/credentials'; +export { EmptyAuthCredentialsProvider as _EmptyAuthCredentialsProvider } from './api/credentials'; +export { EmptyAppCheckTokenProvider as _EmptyAppCheckTokenProvider } from './api/credentials'; +export { ExistenceFilterMismatchCallback as _TestingHooksExistenceFilterMismatchCallback, TestingHooks as _TestingHooks } from './util/testing_hooks'; +export { ExistenceFilterMismatchInfo as _TestingHooksExistenceFilterMismatchInfo } from './util/testing_hooks_spi'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/aggregate.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/aggregate.d.ts new file mode 100644 index 0000000..39bd4b4 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/aggregate.d.ts @@ -0,0 +1,77 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AggregateField, AggregateSpec, DocumentData, Query } from '../api'; +import { AggregateQuerySnapshot } from '../lite-api/aggregate_types'; +export { aggregateQuerySnapshotEqual, count, sum, average, aggregateFieldEqual } from '../lite-api/aggregate'; +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ +export declare function getCountFromServer(query: Query): Promise; +}, AppModelType, DbModelType>>; +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregateFromServer(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ +export declare function getAggregateFromServer(query: Query, aggregateSpec: AggregateSpecType): Promise>; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/bundle.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/bundle.d.ts new file mode 100644 index 0000000..15c33af --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/bundle.d.ts @@ -0,0 +1,94 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirestoreError } from '../util/error'; +/** + * Represents the state of bundle loading tasks. + * + * Both 'Error' and 'Success' are sinking state: task will abort or complete and there will + * be no more updates after they are reported. + */ +export type TaskState = 'Error' | 'Running' | 'Success'; +/** + * Represents a progress update or a final state from loading bundles. + */ +export interface LoadBundleTaskProgress { + /** How many documents have been loaded. */ + documentsLoaded: number; + /** How many documents are in the bundle being loaded. */ + totalDocuments: number; + /** How many bytes have been loaded. */ + bytesLoaded: number; + /** How many bytes are in the bundle being loaded. */ + totalBytes: number; + /** Current task state. */ + taskState: TaskState; +} +/** + * Represents the task of loading a Firestore bundle. It provides progress of bundle + * loading, as well as task completion and error events. + * + * The API is compatible with `Promise`. + */ +export declare class LoadBundleTask implements PromiseLike { + private _progressObserver; + private _taskCompletionResolver; + private _lastProgress; + /** + * Registers functions to listen to bundle loading progress events. + * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur + * each time a Firestore document is loaded from the bundle. + * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the + * error, and there should be no more updates after this. + * @param complete - Called when the loading task is complete. + */ + onProgress(next?: (progress: LoadBundleTaskProgress) => unknown, error?: (err: Error) => unknown, complete?: () => void): void; + /** + * Implements the `Promise.catch` interface. + * + * @param onRejected - Called when an error occurs during bundle loading. + */ + catch(onRejected: (a: Error) => R | PromiseLike): Promise; + /** + * Implements the `Promise.then` interface. + * + * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update. + * The update will always have its `taskState` set to `"Success"`. + * @param onRejected - Called when an error occurs during bundle loading. + */ + then(onFulfilled?: (a: LoadBundleTaskProgress) => T | PromiseLike, onRejected?: (a: Error) => R | PromiseLike): Promise; + /** + * Notifies all observers that bundle loading has completed, with a provided + * `LoadBundleTaskProgress` object. + * + * @private + */ + _completeWith(progress: LoadBundleTaskProgress): void; + /** + * Notifies all observers that bundle loading has failed, with a provided + * `Error` as the reason. + * + * @private + */ + _failWith(error: FirestoreError): void; + /** + * Notifies a progress update of loading a bundle. + * @param progress - The new progress. + * + * @private + */ + _updateProgress(progress: LoadBundleTaskProgress): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/bytes.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/bytes.d.ts new file mode 100644 index 0000000..0c9f5fd --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/bytes.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { Bytes } from '../lite-api/bytes'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/cache_config.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/cache_config.d.ts new file mode 100644 index 0000000..936f21e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/cache_config.d.ts @@ -0,0 +1,222 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { OfflineComponentProviderFactory, OnlineComponentProviderFactory } from '../core/component_provider'; +/** + * Provides an in-memory cache to the SDK. This is the default cache unless explicitly + * configured otherwise. + * + * To use, create an instance using the factory function {@link memoryLocalCache()}, then + * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using + * the settings object. + */ +export type MemoryLocalCache = { + kind: 'memory'; + /** + * @internal + */ + _onlineComponentProvider: OnlineComponentProviderFactory; + /** + * @internal + */ + _offlineComponentProvider: OfflineComponentProviderFactory; +}; +/** + * Provides a persistent cache backed by IndexedDb to the SDK. + * + * To use, create an instance using the factory function {@link persistentLocalCache()}, then + * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using + * the settings object. + */ +export type PersistentLocalCache = { + kind: 'persistent'; + /** + * @internal + */ + _onlineComponentProvider: OnlineComponentProviderFactory; + /** + * @internal + */ + _offlineComponentProvider: OfflineComponentProviderFactory; +}; +/** + * Union type from all supported SDK cache layer. + */ +export type FirestoreLocalCache = MemoryLocalCache | PersistentLocalCache; +/** + * Union type from all support garbage collectors for memory local cache. + */ +export type MemoryGarbageCollector = MemoryEagerGarbageCollector | MemoryLruGarbageCollector; +/** + * A garbage collector deletes documents whenever they are not part of any + * active queries, and have no local mutations attached to them. + * + * This collector tries to ensure lowest memory footprints from the SDK, + * at the risk of documents not being cached for offline queries or for + * direct queries to the cache. + * + * Use factory function {@link memoryEagerGarbageCollector()} to create an + * instance of this collector. + */ +export type MemoryEagerGarbageCollector = { + kind: 'memoryEager'; + /** + * @internal + */ + _offlineComponentProvider: OfflineComponentProviderFactory; +}; +/** + * A garbage collector deletes Least-Recently-Used documents in multiple + * batches. + * + * This collector is configured with a target size, and will only perform + * collection when the cached documents exceed the target size. It avoids + * querying backend repeated for the same query or document, at the risk + * of having a larger memory footprint. + * + * Use factory function {@link memoryLruGarbageCollector()} to create a + * instance of this collector. + */ +export type MemoryLruGarbageCollector = { + kind: 'memoryLru'; + /** + * @internal + */ + _offlineComponentProvider: OfflineComponentProviderFactory; +}; +/** + * Creates an instance of `MemoryEagerGarbageCollector`. This is also the + * default garbage collector unless it is explicitly specified otherwise. + */ +export declare function memoryEagerGarbageCollector(): MemoryEagerGarbageCollector; +/** + * Creates an instance of `MemoryLruGarbageCollector`. + * + * A target size can be specified as part of the setting parameter. The + * collector will start deleting documents once the cache size exceeds + * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes). + */ +export declare function memoryLruGarbageCollector(settings?: { + cacheSizeBytes?: number; +}): MemoryLruGarbageCollector; +/** + * An settings object to configure an `MemoryLocalCache` instance. + */ +export type MemoryCacheSettings = { + /** + * The garbage collector to use, for the memory cache layer. + * A `MemoryEagerGarbageCollector` is used when this is undefined. + */ + garbageCollector?: MemoryGarbageCollector; +}; +/** + * Creates an instance of `MemoryLocalCache`. The instance can be set to + * `FirestoreSettings.cache` to tell the SDK which cache layer to use. + */ +export declare function memoryLocalCache(settings?: MemoryCacheSettings): MemoryLocalCache; +/** + * An settings object to configure an `PersistentLocalCache` instance. + * + * Persistent cache cannot be used in a Node.js environment. + */ +export type PersistentCacheSettings = { + /** + * An approximate cache size threshold for the on-disk data. If the cache + * grows beyond this size, Firestore will start removing data that hasn't been + * recently used. The SDK does not guarantee that the cache will stay below + * that size, only that if the cache exceeds the given size, cleanup will be + * attempted. + * + * The default value is 40 MB. The threshold must be set to at least 1 MB, and + * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection. + */ + cacheSizeBytes?: number; + /** + * Specifies how multiple tabs/windows will be managed by the SDK. + */ + tabManager?: PersistentTabManager; +}; +/** + * Creates an instance of `PersistentLocalCache`. The instance can be set to + * `FirestoreSettings.cache` to tell the SDK which cache layer to use. + * + * Persistent cache cannot be used in a Node.js environment. + */ +export declare function persistentLocalCache(settings?: PersistentCacheSettings): PersistentLocalCache; +/** + * A tab manager supporting only one tab, no synchronization will be + * performed across tabs. + */ +export type PersistentSingleTabManager = { + kind: 'persistentSingleTab'; + /** + * @internal + */ + _initialize: (settings: Omit | undefined) => void; + /** + * @internal + */ + _onlineComponentProvider?: OnlineComponentProviderFactory; + /** + * @internal + */ + _offlineComponentProvider?: OfflineComponentProviderFactory; +}; +/** + * A tab manager supporting multiple tabs. SDK will synchronize queries and + * mutations done across all tabs using the SDK. + */ +export type PersistentMultipleTabManager = { + kind: 'PersistentMultipleTab'; + /** + * @internal + */ + _initialize: (settings: Omit) => void; + /** + * @internal + */ + _onlineComponentProvider?: OnlineComponentProviderFactory; + /** + * @internal + */ + _offlineComponentProvider?: OfflineComponentProviderFactory; +}; +/** + * A union of all available tab managers. + */ +export type PersistentTabManager = PersistentSingleTabManager | PersistentMultipleTabManager; +/** + * Type to configure an `PersistentSingleTabManager` instance. + */ +export type PersistentSingleTabManagerSettings = { + /** + * Whether to force-enable persistent (IndexedDB) cache for the client. This + * cannot be used with multi-tab synchronization and is primarily intended for + * use with Web Workers. Setting this to `true` will enable IndexedDB, but cause + * other tabs using IndexedDB cache to fail. + */ + forceOwnership?: boolean; +}; +/** + * Creates an instance of `PersistentSingleTabManager`. + * + * @param settings Configures the created tab manager. + */ +export declare function persistentSingleTabManager(settings: PersistentSingleTabManagerSettings | undefined): PersistentSingleTabManager; +/** + * Creates an instance of `PersistentMultipleTabManager`. + */ +export declare function persistentMultipleTabManager(): PersistentMultipleTabManager; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/credentials.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/credentials.d.ts new file mode 100644 index 0000000..98ed3c2 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/credentials.d.ts @@ -0,0 +1,222 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseApp } from '@firebase/app'; +import { AppCheckInternalComponentName } from '@firebase/app-check-interop-types'; +import { FirebaseAuthInternalName } from '@firebase/auth-interop-types'; +import { Provider } from '@firebase/component'; +import { User } from '../auth/user'; +import { AsyncQueue } from '../util/async_queue'; +/** + * @internal + */ +export type AuthTokenFactory = () => string; +/** + * @internal + */ +export interface FirstPartyCredentialsSettings { + ['type']: 'firstParty'; + ['sessionIndex']: string; + ['iamToken']: string | null; + ['authTokenFactory']: AuthTokenFactory | null; +} +export interface ProviderCredentialsSettings { + ['type']: 'provider'; + ['client']: CredentialsProvider; +} +/** Settings for private credentials */ +export type CredentialsSettings = FirstPartyCredentialsSettings | ProviderCredentialsSettings; +export type TokenType = 'OAuth' | 'FirstParty' | 'AppCheck'; +export interface Token { + /** Type of token. */ + type: TokenType; + /** + * The user with which the token is associated (used for persisting user + * state on disk, etc.). + * This will be null for Tokens of the type 'AppCheck'. + */ + user?: User; + /** Header values to set for this token */ + headers: Map; +} +export declare class OAuthToken implements Token { + user: User; + type: TokenType; + headers: Map; + constructor(value: string, user: User); +} +/** + * A Listener for credential change events. The listener should fetch a new + * token and may need to invalidate other state if the current user has also + * changed. + */ +export type CredentialChangeListener = (credential: T) => Promise; +/** + * Provides methods for getting the uid and token for the current user and + * listening for changes. + */ +export interface CredentialsProvider { + /** + * Starts the credentials provider and specifies a listener to be notified of + * credential changes (sign-in / sign-out, token changes). It is immediately + * called once with the initial user. + * + * The change listener is invoked on the provided AsyncQueue. + */ + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + /** Requests a token for the current user. */ + getToken(): Promise; + /** + * Marks the last retrieved token as invalid, making the next GetToken request + * force-refresh the token. + */ + invalidateToken(): void; + shutdown(): void; +} +/** + * A CredentialsProvider that always yields an empty token. + * @internal + */ +export declare class EmptyAuthCredentialsProvider implements CredentialsProvider { + getToken(): Promise; + invalidateToken(): void; + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + shutdown(): void; +} +/** + * A CredentialsProvider that always returns a constant token. Used for + * emulator token mocking. + */ +export declare class EmulatorAuthCredentialsProvider implements CredentialsProvider { + private token; + constructor(token: Token); + /** + * Stores the listener registered with setChangeListener() + * This isn't actually necessary since the UID never changes, but we use this + * to verify the listen contract is adhered to in tests. + */ + private changeListener; + getToken(): Promise; + invalidateToken(): void; + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + shutdown(): void; +} +/** Credential provider for the Lite SDK. */ +export declare class LiteAuthCredentialsProvider implements CredentialsProvider { + private auth; + constructor(authProvider: Provider); + getToken(): Promise; + invalidateToken(): void; + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + shutdown(): void; +} +export declare class FirebaseAuthCredentialsProvider implements CredentialsProvider { + private authProvider; + /** + * The auth token listener registered with FirebaseApp, retained here so we + * can unregister it. + */ + private tokenListener; + /** Tracks the current User. */ + private currentUser; + /** + * Counter used to detect if the token changed while a getToken request was + * outstanding. + */ + private tokenCounter; + private forceRefresh; + private auth; + constructor(authProvider: Provider); + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + getToken(): Promise; + invalidateToken(): void; + shutdown(): void; + private getUser; +} +export declare class FirstPartyToken implements Token { + private readonly sessionIndex; + private readonly iamToken; + private readonly authTokenFactory; + type: TokenType; + user: User; + private _headers; + constructor(sessionIndex: string, iamToken: string | null, authTokenFactory: AuthTokenFactory | null); + /** + * Gets an authorization token, using a provided factory function, or return + * null. + */ + private getAuthToken; + get headers(): Map; +} +export declare class FirstPartyAuthCredentialsProvider implements CredentialsProvider { + private sessionIndex; + private iamToken; + private authTokenFactory; + constructor(sessionIndex: string, iamToken: string | null, authTokenFactory: AuthTokenFactory | null); + getToken(): Promise; + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + shutdown(): void; + invalidateToken(): void; +} +export declare class AppCheckToken implements Token { + private value; + type: TokenType; + headers: Map; + constructor(value: string); +} +export declare class FirebaseAppCheckTokenProvider implements CredentialsProvider { + private appCheckProvider; + /** + * The AppCheck token listener registered with FirebaseApp, retained here so + * we can unregister it. + */ + private tokenListener; + private forceRefresh; + private appCheck; + private latestAppCheckToken; + private serverAppAppCheckToken; + constructor(app: FirebaseApp, appCheckProvider: Provider); + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + getToken(): Promise; + invalidateToken(): void; + shutdown(): void; +} +/** + * An AppCheck token provider that always yields an empty token. + * @internal + */ +export declare class EmptyAppCheckTokenProvider implements CredentialsProvider { + getToken(): Promise; + invalidateToken(): void; + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + shutdown(): void; +} +/** AppCheck token provider for the Lite SDK. */ +export declare class LiteAppCheckTokenProvider implements CredentialsProvider { + private appCheckProvider; + private appCheck; + private serverAppAppCheckToken; + constructor(app: FirebaseApp, appCheckProvider: Provider); + getToken(): Promise; + invalidateToken(): void; + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + shutdown(): void; +} +/** + * Builds a CredentialsProvider depending on the type of + * the credentials passed in. + */ +export declare function makeAuthCredentialsProvider(credentials?: CredentialsSettings): CredentialsProvider; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/database.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/database.d.ts new file mode 100644 index 0000000..8004dae --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/database.d.ts @@ -0,0 +1,279 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseApp } from '@firebase/app'; +import { User } from '../auth/user'; +import { OfflineComponentProviderFactory, OnlineComponentProviderFactory } from '../core/component_provider'; +import { DatabaseId } from '../core/database_info'; +import { FirestoreClient } from '../core/firestore_client'; +import { Firestore as LiteFirestore } from '../lite-api/database'; +import { Query } from '../lite-api/reference'; +import { AsyncQueue } from '../util/async_queue'; +import { LoadBundleTask } from './bundle'; +import { CredentialsProvider } from './credentials'; +import { FirestoreSettings, PersistenceSettings } from './settings'; +export { connectFirestoreEmulator, EmulatorMockTokenOptions } from '../lite-api/database'; +declare module '@firebase/component' { + interface NameServiceMapping { + 'firestore': Firestore; + } +} +/** + * Constant used to indicate the LRU garbage collection should be disabled. + * Set this value as the `cacheSizeBytes` on the settings passed to the + * {@link Firestore} instance. + */ +export declare const CACHE_SIZE_UNLIMITED = -1; +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ +export declare class Firestore extends LiteFirestore { + /** + * Whether it's a {@link Firestore} or Firestore Lite instance. + */ + type: 'firestore-lite' | 'firestore'; + _queue: AsyncQueue; + readonly _persistenceKey: string; + _firestoreClient: FirestoreClient | undefined; + _componentsProvider?: { + _offline: OfflineComponentProviderFactory; + _online: OnlineComponentProviderFactory; + }; + /** @hideconstructor */ + constructor(authCredentialsProvider: CredentialsProvider, appCheckCredentialsProvider: CredentialsProvider, databaseId: DatabaseId, app?: FirebaseApp); + protected _terminate(): Promise; +} +/** + * Initializes a new instance of {@link Firestore} with the provided settings. + * Can only be called before any other function, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will + * be associated. + * @param settings - A settings object to configure the {@link Firestore} instance. + * @param databaseId - The name of the database. + * @returns A newly initialized {@link Firestore} instance. + */ +export declare function initializeFirestore(app: FirebaseApp, settings: FirestoreSettings, databaseId?: string): Firestore; +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @returns The default {@link Firestore} instance of the default app. + */ +export declare function getFirestore(): Firestore; +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @returns The default {@link Firestore} instance of the provided app. + */ +export declare function getFirestore(app: FirebaseApp): Firestore; +/** + * Returns the existing named {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param databaseId - The name of the database. + * @returns The named {@link Firestore} instance of the default app. + * @beta + */ +export declare function getFirestore(databaseId: string): Firestore; +/** + * Returns the existing named {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @param databaseId - The name of the database. + * @returns The named {@link Firestore} instance of the provided app. + * @beta + */ +export declare function getFirestore(app: FirebaseApp, databaseId: string): Firestore; +/** + * @internal + */ +export declare function ensureFirestoreConfigured(firestore: Firestore): FirestoreClient; +export declare function configureFirestore(firestore: Firestore): void; +/** + * Attempts to enable persistent storage, if possible. + * + * On failure, `enableIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. + * + * * failed-precondition: The app is already open in another browser tab. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. + * + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. + * + * Note: `enableIndexedDbPersistence()` must be called before any other functions + * (other than {@link initializeFirestore}, {@link (getFirestore:1)} or + * {@link clearIndexedDbPersistence}. + * + * Persistence cannot be used in a Node.js environment. + * + * @param firestore - The {@link Firestore} instance to enable persistence for. + * @param persistenceSettings - Optional settings object to configure + * persistence. + * @returns A `Promise` that represents successfully enabling persistent storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on IndexedDb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. + */ +export declare function enableIndexedDbPersistence(firestore: Firestore, persistenceSettings?: PersistenceSettings): Promise; +/** + * Attempts to enable multi-tab persistent storage, if possible. If enabled + * across all tabs, all operations share access to local persistence, including + * shared execution of queries and latency-compensated local document updates + * across all connected instances. + * + * On failure, `enableMultiTabIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. + * + * * failed-precondition: The app is already open in another browser tab and + * multi-tab is not enabled. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. + * + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. + * + * @param firestore - The {@link Firestore} instance to enable persistence for. + * @returns A `Promise` that represents successfully enabling persistent + * storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on indexeddb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. + */ +export declare function enableMultiTabIndexedDbPersistence(firestore: Firestore): Promise; +/** + * Clears the persistent storage. This includes pending writes and cached + * documents. + * + * Must be called while the {@link Firestore} instance is not started (after the app is + * terminated or when the app is first initialized). On startup, this function + * must be called before other functions (other than {@link + * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore} + * instance is still running, the promise will be rejected with the error code + * of `failed-precondition`. + * + * Note: `clearIndexedDbPersistence()` is primarily intended to help write + * reliable tests that use Cloud Firestore. It uses an efficient mechanism for + * dropping existing data but does not attempt to securely overwrite or + * otherwise make cached data unrecoverable. For applications that are sensitive + * to the disclosure of cached data in between user sessions, we strongly + * recommend not enabling persistence at all. + * + * @param firestore - The {@link Firestore} instance to clear persistence for. + * @returns A `Promise` that is resolved when the persistent storage is + * cleared. Otherwise, the promise is rejected with an error. + */ +export declare function clearIndexedDbPersistence(firestore: Firestore): Promise; +/** + * Waits until all currently pending writes for the active user have been + * acknowledged by the backend. + * + * The returned promise resolves immediately if there are no outstanding writes. + * Otherwise, the promise waits for all previously issued writes (including + * those written in a previous app session), but it does not wait for writes + * that were added after the function is called. If you want to wait for + * additional writes, call `waitForPendingWrites()` again. + * + * Any outstanding `waitForPendingWrites()` promises are rejected during user + * changes. + * + * @returns A `Promise` which resolves when all currently pending writes have been + * acknowledged by the backend. + */ +export declare function waitForPendingWrites(firestore: Firestore): Promise; +/** + * Re-enables use of the network for this {@link Firestore} instance after a prior + * call to {@link disableNetwork}. + * + * @returns A `Promise` that is resolved once the network has been enabled. + */ +export declare function enableNetwork(firestore: Firestore): Promise; +/** + * Disables network usage for this instance. It can be re-enabled via {@link + * enableNetwork}. While the network is disabled, any snapshot listeners, + * `getDoc()` or `getDocs()` calls will return results from cache, and any write + * operations will be queued until the network is restored. + * + * @returns A `Promise` that is resolved once the network has been disabled. + */ +export declare function disableNetwork(firestore: Firestore): Promise; +/** + * Terminates the provided {@link Firestore} instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` function + * may be used. Any other function will throw a `FirestoreError`. + * + * To restart after termination, create a new instance of FirebaseFirestore with + * {@link (getFirestore:1)}. + * + * Termination does not cancel any pending writes, and any promises that are + * awaiting a response from the server will not be resolved. If you have + * persistence enabled, the next time you start this instance, it will resume + * sending these writes to the server. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all + * of its resources or in combination with `clearIndexedDbPersistence()` to + * ensure that all local state is destroyed between test runs. + * + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ +export declare function terminate(firestore: Firestore): Promise; +/** + * Loads a Firestore bundle into the local cache. + * + * @param firestore - The {@link Firestore} instance to load bundles for. + * @param bundleData - An object representing the bundle to be loaded. Valid + * objects are `ArrayBuffer`, `ReadableStream` or `string`. + * + * @returns A `LoadBundleTask` object, which notifies callers with progress + * updates, and completion or error events. It can be used as a + * `Promise`. + */ +export declare function loadBundle(firestore: Firestore, bundleData: ReadableStream | ArrayBuffer | string): LoadBundleTask; +/** + * Reads a Firestore {@link Query} from local cache, identified by the given + * name. + * + * The named queries are packaged into bundles on the server side (along + * with resulting documents), and loaded to local cache using `loadBundle`. Once + * in local cache, use this method to extract a {@link Query} by name. + * + * @param firestore - The {@link Firestore} instance to read the query from. + * @param name - The name of the query. + * @returns A `Promise` that is resolved with the Query or `null`. + */ +export declare function namedQuery(firestore: Firestore, name: string): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/field_path.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/field_path.d.ts new file mode 100644 index 0000000..7e463e5 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/field_path.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { FieldPath, documentId } from '../lite-api/field_path'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/field_value.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/field_value.d.ts new file mode 100644 index 0000000..eded0bc --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/field_value.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { FieldValue } from '../lite-api/field_value'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/field_value_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/field_value_impl.d.ts new file mode 100644 index 0000000..aac67c3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/field_value_impl.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { increment, arrayRemove, arrayUnion, serverTimestamp, deleteField, vector } from '../lite-api/field_value_impl'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/filter.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/filter.d.ts new file mode 100644 index 0000000..1dee60b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/filter.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { and, endAt, endBefore, startAfter, startAt, limitToLast, limit, or, orderBy, OrderByDirection, where, WhereFilterOp, query, QueryCompositeFilterConstraint, QueryConstraint, QueryConstraintType, QueryFilterConstraint, QueryFieldFilterConstraint, QueryOrderByConstraint, QueryLimitConstraint, QueryStartAtConstraint, QueryEndAtConstraint, QueryNonFilterConstraint } from '../lite-api/query'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/geo_point.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/geo_point.d.ts new file mode 100644 index 0000000..b14def6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/geo_point.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { GeoPoint } from '../lite-api/geo_point'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/index_configuration.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/index_configuration.d.ts new file mode 100644 index 0000000..8b10775 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/index_configuration.d.ts @@ -0,0 +1,139 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FieldIndex } from '../model/field_index'; +import { Firestore } from './database'; +export { connectFirestoreEmulator, EmulatorMockTokenOptions } from '../lite-api/database'; +/** + * A single field element in an index configuration. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export interface IndexField { + /** The field path to index. */ + readonly fieldPath: string; + /** + * What type of array index to create. Set to `CONTAINS` for `array-contains` + * and `array-contains-any` indexes. + * + * Only one of `arrayConfig` or `order` should be set; + */ + readonly arrayConfig?: 'CONTAINS'; + /** + * What type of array index to create. Set to `ASCENDING` or 'DESCENDING` for + * `==`, `!=`, `<=`, `<=`, `in` and `not-in` filters. + * + * Only one of `arrayConfig` or `order` should be set. + */ + readonly order?: 'ASCENDING' | 'DESCENDING'; + [key: string]: unknown; +} +/** + * The SDK definition of a Firestore index. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export interface Index { + /** The ID of the collection to index. */ + readonly collectionGroup: string; + /** A list of fields to index. */ + readonly fields?: IndexField[]; + [key: string]: unknown; +} +/** + * A list of Firestore indexes to speed up local query execution. + * + * See {@link https://firebase.google.com/docs/reference/firestore/indexes/#json_format | JSON Format} + * for a description of the format of the index definition. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export interface IndexConfiguration { + /** A list of all Firestore indexes. */ + readonly indexes?: Index[]; + [key: string]: unknown; +} +/** + * Configures indexing for local query execution. Any previous index + * configuration is overridden. The `Promise` resolves once the index + * configuration has been persisted. + * + * The index entries themselves are created asynchronously. You can continue to + * use queries that require indexing even if the indices are not yet available. + * Query execution will automatically start using the index once the index + * entries have been written. + * + * Indexes are only supported with IndexedDb persistence. If IndexedDb is not + * enabled, any index configuration is ignored. + * + * @param firestore - The {@link Firestore} instance to configure indexes for. + * @param configuration -The index definition. + * @throws FirestoreError if the JSON format is invalid. + * @returns A `Promise` that resolves once all indices are successfully + * configured. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare function setIndexConfiguration(firestore: Firestore, configuration: IndexConfiguration): Promise; +/** + * Configures indexing for local query execution. Any previous index + * configuration is overridden. The `Promise` resolves once the index + * configuration has been persisted. + * + * The index entries themselves are created asynchronously. You can continue to + * use queries that require indexing even if the indices are not yet available. + * Query execution will automatically start using the index once the index + * entries have been written. + * + * Indexes are only supported with IndexedDb persistence. Invoke either + * `enableIndexedDbPersistence()` or `enableMultiTabIndexedDbPersistence()` + * before setting an index configuration. If IndexedDb is not enabled, any + * index configuration is ignored. + * + * The method accepts the JSON format exported by the Firebase CLI (`firebase + * firestore:indexes`). If the JSON format is invalid, this method throws an + * error. + * + * @param firestore - The {@link Firestore} instance to configure indexes for. + * @param json -The JSON format exported by the Firebase CLI. + * @throws FirestoreError if the JSON format is invalid. + * @returns A `Promise` that resolves once all indices are successfully + * configured. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare function setIndexConfiguration(firestore: Firestore, json: string): Promise; +export declare function parseIndexes(jsonOrConfiguration: string | IndexConfiguration): FieldIndex[]; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/long_polling_options.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/long_polling_options.d.ts new file mode 100644 index 0000000..0088194 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/long_polling_options.d.ts @@ -0,0 +1,55 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options that configure the SDK’s underlying network transport (WebChannel) + * when long-polling is used. + * + * Note: This interface is "experimental" and is subject to change. + * + * See `FirestoreSettings.experimentalAutoDetectLongPolling`, + * `FirestoreSettings.experimentalForceLongPolling`, and + * `FirestoreSettings.experimentalLongPollingOptions`. + */ +export interface ExperimentalLongPollingOptions { + /** + * The desired maximum timeout interval, in seconds, to complete a + * long-polling GET response. Valid values are between 5 and 30, inclusive. + * Floating point values are allowed and will be rounded to the nearest + * millisecond. + * + * By default, when long-polling is used the "hanging GET" request sent by + * the client times out after 30 seconds. To request a different timeout + * from the server, set this setting with the desired timeout. + * + * Changing the default timeout may be useful, for example, if the buffering + * proxy that necessitated enabling long-polling in the first place has a + * shorter timeout for hanging GET requests, in which case setting the + * long-polling timeout to a shorter value, such as 25 seconds, may fix + * prematurely-closed hanging GET requests. + * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987. + */ + timeoutSeconds?: number; +} +/** + * Compares two `ExperimentalLongPollingOptions` objects for equality. + */ +export declare function longPollingOptionsEqual(options1: ExperimentalLongPollingOptions, options2: ExperimentalLongPollingOptions): boolean; +/** + * Creates and returns a new `ExperimentalLongPollingOptions` with the same + * option values as the given instance. + */ +export declare function cloneLongPollingOptions(options: ExperimentalLongPollingOptions): ExperimentalLongPollingOptions; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/observer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/observer.d.ts new file mode 100644 index 0000000..1aa4b85 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/observer.d.ts @@ -0,0 +1,29 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirestoreError } from '../util/error'; +/** + * Observer/Subscribe interfaces. + */ +export type NextFn = (value: T) => void; +export type ErrorFn = (error: FirestoreError) => void; +export type CompleteFn = () => void; +export interface PartialObserver { + next?: NextFn; + error?: ErrorFn; + complete?: CompleteFn; +} +export declare function isPartialObserver(obj: unknown): obj is PartialObserver; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/parse_context.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/parse_context.d.ts new file mode 100644 index 0000000..d2b0beb --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/parse_context.d.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseId } from '../core/database_info'; +export interface ParseContext { + readonly databaseId: DatabaseId; + readonly ignoreUndefinedProperties: boolean; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/persistent_cache_index_manager.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/persistent_cache_index_manager.d.ts new file mode 100644 index 0000000..c6e4b46 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/persistent_cache_index_manager.d.ts @@ -0,0 +1,59 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Firestore } from './database'; +/** + * A `PersistentCacheIndexManager` for configuring persistent cache indexes used + * for local query execution. + * + * To use, call `getPersistentCacheIndexManager()` to get an instance. + */ +export declare class PersistentCacheIndexManager { + readonly _firestore: Firestore; + /** A type string to uniquely identify instances of this class. */ + readonly type: 'PersistentCacheIndexManager'; + /** @hideconstructor */ + constructor(_firestore: Firestore); +} +/** + * Returns the PersistentCache Index Manager used by the given `Firestore` + * object. + * + * @return The `PersistentCacheIndexManager` instance, or `null` if local + * persistent storage is not in use. + */ +export declare function getPersistentCacheIndexManager(firestore: Firestore): PersistentCacheIndexManager | null; +/** + * Enables the SDK to create persistent cache indexes automatically for local + * query execution when the SDK believes cache indexes can help improve + * performance. + * + * This feature is disabled by default. + */ +export declare function enablePersistentCacheIndexAutoCreation(indexManager: PersistentCacheIndexManager): void; +/** + * Stops creating persistent cache indexes automatically for local query + * execution. The indexes which have been created by calling + * `enablePersistentCacheIndexAutoCreation()` still take effect. + */ +export declare function disablePersistentCacheIndexAutoCreation(indexManager: PersistentCacheIndexManager): void; +/** + * Removes all persistent cache indexes. + * + * Please note this function will also deletes indexes generated by + * `setIndexConfiguration()`, which is deprecated. + */ +export declare function deleteAllPersistentCacheIndexes(indexManager: PersistentCacheIndexManager): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/reference.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/reference.d.ts new file mode 100644 index 0000000..0e38648 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/reference.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { DocumentReference, CollectionReference, Query, collection, collectionGroup, doc, queryEqual, SetOptions, DocumentData, UpdateData, WithFieldValue, PartialWithFieldValue, refEqual } from '../lite-api/reference'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/reference_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/reference_impl.d.ts new file mode 100644 index 0000000..5dd95e6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/reference_impl.d.ts @@ -0,0 +1,536 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Bytes } from '../lite-api/bytes'; +import { FieldPath } from '../lite-api/field_path'; +import { CollectionReference, DocumentData, DocumentReference, PartialWithFieldValue, Query, SetOptions, UpdateData, WithFieldValue } from '../lite-api/reference'; +import { AbstractUserDataWriter } from '../lite-api/user_data_writer'; +import { Mutation } from '../model/mutation'; +import { ByteString } from '../util/byte_string'; +import { FirestoreError } from '../util/error'; +import { Firestore } from './database'; +import { DocumentSnapshot, FirestoreDataConverter, QuerySnapshot } from './snapshot'; +/** + * An options object that can be passed to {@link (onSnapshot:1)} and {@link + * QuerySnapshot.docChanges} to control which types of changes to include in the + * result set. + */ +export interface SnapshotListenOptions { + /** + * Include a change even if only the metadata of the query or of a document + * changed. Default is false. + */ + readonly includeMetadataChanges?: boolean; + /** + * Set the source the query listens to. Default to "default", which + * listens to both cache and server. + */ + readonly source?: ListenSource; +} +/** + * Describe the source a query listens to. + * + * Set to `default` to listen to both cache and server changes. Set to `cache` + * to listen to changes in cache only. + */ +export type ListenSource = 'default' | 'cache'; +/** + * Reads the document referred to by this `DocumentReference`. + * + * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting + * for data from the server, but it may return cached data or fail if you are + * offline and the server cannot be reached. To specify this behavior, invoke + * {@link getDocFromCache} or {@link getDocFromServer}. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +export declare function getDoc(reference: DocumentReference): Promise>; +export declare class ExpUserDataWriter extends AbstractUserDataWriter { + protected firestore: Firestore; + constructor(firestore: Firestore); + protected convertBytes(bytes: ByteString): Bytes; + protected convertReference(name: string): DocumentReference; +} +/** + * Reads the document referred to by this `DocumentReference` from cache. + * Returns an error if the document is not currently cached. + * + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +export declare function getDocFromCache(reference: DocumentReference): Promise>; +/** + * Reads the document referred to by this `DocumentReference` from the server. + * Returns an error if the network is not available. + * + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +export declare function getDocFromServer(reference: DocumentReference): Promise>; +/** + * Executes the query and returns the results as a `QuerySnapshot`. + * + * Note: `getDocs()` attempts to provide up-to-date data when possible by + * waiting for data from the server, but it may return cached data or fail if + * you are offline and the server cannot be reached. To specify this behavior, + * invoke {@link getDocsFromCache} or {@link getDocsFromServer}. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +export declare function getDocs(query: Query): Promise>; +/** + * Executes the query and returns the results as a `QuerySnapshot` from cache. + * Returns an empty result set if no documents matching the query are currently + * cached. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +export declare function getDocsFromCache(query: Query): Promise>; +/** + * Executes the query and returns the results as a `QuerySnapshot` from the + * server. Returns an error if the network is not available. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +export declare function getDocsFromServer(query: Query): Promise>; +/** + * Writes to the document referred to by this `DocumentReference`. If the + * document does not yet exist, it will be created. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +export declare function setDoc(reference: DocumentReference, data: WithFieldValue): Promise; +/** + * Writes to the document referred to by the specified `DocumentReference`. If + * the document does not yet exist, it will be created. If you provide `merge` + * or `mergeFields`, the provided data can be merged into an existing document. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @returns A Promise resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +export declare function setDoc(reference: DocumentReference, data: PartialWithFieldValue, options: SetOptions): Promise; +/** + * Updates fields in the document referred to by the specified + * `DocumentReference`. The update will fail if applied to a document that does + * not exist. + * + * @param reference - A reference to the document to update. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +export declare function updateDoc(reference: DocumentReference, data: UpdateData): Promise; +/** + * Updates fields in the document referred to by the specified + * `DocumentReference` The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * @param reference - A reference to the document to update. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +export declare function updateDoc(reference: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): Promise; +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * @param reference - A reference to the document to delete. + * @returns A Promise resolved once the document has been successfully + * deleted from the backend (note that it won't resolve while you're offline). + */ +export declare function deleteDoc(reference: DocumentReference): Promise; +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend (Note that it + * won't resolve while you're offline). + */ +export declare function addDoc(reference: CollectionReference, data: WithFieldValue): Promise>; +/** + * A function returned by `onSnapshot()` that removes the listener when invoked. + */ +export interface Unsubscribe { + /** Removes the listener when invoked. */ + (): void; +} +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshot(reference: DocumentReference, observer: { + next?: (snapshot: DocumentSnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshot(reference: DocumentReference, options: SnapshotListenOptions, observer: { + next?: (snapshot: DocumentSnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(reference: DocumentReference, onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param options - Options controlling the listen behavior. + * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(reference: DocumentReference, options: SnapshotListenOptions, onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The + * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(query: Query, observer: { + next?: (snapshot: QuerySnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The + * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(query: Query, options: SnapshotListenOptions, observer: { + next?: (snapshot: QuerySnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The + * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(query: Query, onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The + * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param options - Options controlling the listen behavior. + * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(query: Query, options: SnapshotListenOptions, onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events based on data generated by invoking + * {@link QuerySnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. + * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking + * {@link DocumentSnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. + * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are + * never ending. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events based on data generated by invoking + * {@link QuerySnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, options: SnapshotListenOptions, onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking + * {@link DocumentSnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks + * or pass a single observer object with `next` and `error` callbacks. The listener can be cancelled + * by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, options: SnapshotListenOptions, onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events based on QuerySnapshot data generated by invoking + * {@link QuerySnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, observer: { + next: (snapshot: QuerySnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking + * {@link DocumentSnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks + * or pass a single observer object with `next` and `error` callbacks. The listener can be cancelled + * by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, observer: { + next: (snapshot: DocumentSnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events based on QuerySnapshot data generated by invoking + * {@link QuerySnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, options: SnapshotListenOptions, observer: { + next: (snapshot: QuerySnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events based on QuerySnapshot data generated by + * invoking {@link DocumentSnapshot.toJSON} You may either pass individual `onNext` and `onError` + * callbacks or pass a single observer object with `next` and `error` callbacks. The listener can be + * cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, options: SnapshotListenOptions, observer: { + next: (snapshot: DocumentSnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync + * event indicates that all listeners affected by a given change have fired, + * even if a single server-generated change affects multiple listeners. + * + * NOTE: The snapshots-in-sync event only indicates that listeners are in sync + * with each other, but does not relate to whether those snapshots are in sync + * with the server. Use SnapshotMetadata in the individual listeners to + * determine if a snapshot is from the cache or the server. + * + * @param firestore - The instance of Firestore for synchronizing snapshots. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel the snapshot + * listener. + */ +export declare function onSnapshotsInSync(firestore: Firestore, observer: { + next?: (value: void) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}): Unsubscribe; +/** + * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync + * event indicates that all listeners affected by a given change have fired, + * even if a single server-generated change affects multiple listeners. + * + * NOTE: The snapshots-in-sync event only indicates that listeners are in sync + * with each other, but does not relate to whether those snapshots are in sync + * with the server. Use `SnapshotMetadata` in the individual listeners to + * determine if a snapshot is from the cache or the server. + * + * @param firestore - The `Firestore` instance for synchronizing snapshots. + * @param onSync - A callback to be called every time all snapshot listeners are + * in sync with each other. + * @returns An unsubscribe function that can be called to cancel the snapshot + * listener. + */ +export declare function onSnapshotsInSync(firestore: Firestore, onSync: () => void): Unsubscribe; +/** + * Locally writes `mutations` on the async queue. + * @internal + */ +export declare function executeWrite(firestore: Firestore, mutations: Mutation[]): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/settings.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/settings.d.ts new file mode 100644 index 0000000..8565811 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/settings.d.ts @@ -0,0 +1,108 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirestoreSettings as LiteSettings } from '../lite-api/settings'; +import { FirestoreLocalCache } from './cache_config'; +import { ExperimentalLongPollingOptions } from './long_polling_options'; +export { DEFAULT_HOST } from '../lite-api/settings'; +/** + * Settings that can be passed to `enableIndexedDbPersistence()` to configure + * Firestore persistence. + * + * Persistence cannot be used in a Node.js environment. + */ +export interface PersistenceSettings { + /** + * Whether to force enable persistence for the client. This cannot be used + * with multi-tab synchronization and is primarily intended for use with Web + * Workers. Setting this to `true` will enable persistence, but cause other + * tabs using persistence to fail. + */ + forceOwnership?: boolean; +} +/** + * Specifies custom configurations for your Cloud Firestore instance. + * You must set these before invoking any other methods. + */ +export interface FirestoreSettings extends LiteSettings { + /** + * NOTE: This field will be deprecated in a future major release. Use `cache` field + * instead to specify cache size, and other cache configurations. + * + * An approximate cache size threshold for the on-disk data. If the cache + * grows beyond this size, Firestore will start removing data that hasn't been + * recently used. The size is not a guarantee that the cache will stay below + * that size, only that if the cache exceeds the given size, cleanup will be + * attempted. + * + * The default value is 40 MB. The threshold must be set to at least 1 MB, and + * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection. + */ + cacheSizeBytes?: number; + /** + * Specifies the cache used by the SDK. Available options are `MemoryLocalCache` + * and `PersistentLocalCache`, each with different configuration options. + * + * When unspecified, `MemoryLocalCache` will be used by default. + * + * NOTE: setting this field and `cacheSizeBytes` at the same time will throw + * exception during SDK initialization. Instead, using the configuration in + * the `FirestoreLocalCache` object to specify the cache size. + */ + localCache?: FirestoreLocalCache; + /** + * Forces the SDK’s underlying network transport (WebChannel) to use + * long-polling. Each response from the backend will be closed immediately + * after the backend sends data (by default responses are kept open in + * case the backend has more data to send). This avoids incompatibility + * issues with certain proxies, antivirus software, etc. that incorrectly + * buffer traffic indefinitely. Use of this option will cause some + * performance degradation though. + * + * This setting cannot be used with `experimentalAutoDetectLongPolling` and + * may be removed in a future release. If you find yourself using it to + * work around a specific network reliability issue, please tell us about + * it in https://github.com/firebase/firebase-js-sdk/issues/1674. + * + * This setting cannot be used in a Node.js environment. + */ + experimentalForceLongPolling?: boolean; + /** + * Configures the SDK's underlying transport (WebChannel) to automatically + * detect if long-polling should be used. This is very similar to + * `experimentalForceLongPolling`, but only uses long-polling if required. + * + * After having had a default value of `false` since its inception in 2019, + * the default value of this setting was changed in May 2023 to `true` in + * v9.22.0 of the Firebase JavaScript SDK. That is, auto-detection of long + * polling is now enabled by default. To disable it, set this setting to + * `false`, and please open a GitHub issue to share the problems that + * motivated you disabling long-polling auto-detection. + * + * This setting cannot be used in a Node.js environment. + */ + experimentalAutoDetectLongPolling?: boolean; + /** + * Options that configure the SDK’s underlying network transport (WebChannel) + * when long-polling is used. + * + * These options are only used if `experimentalForceLongPolling` is true or if + * `experimentalAutoDetectLongPolling` is true and the auto-detection + * determined that long-polling was needed. Otherwise, these options have no + * effect. + */ + experimentalLongPollingOptions?: ExperimentalLongPollingOptions; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/snapshot.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/snapshot.d.ts new file mode 100644 index 0000000..24d863e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/snapshot.d.ts @@ -0,0 +1,550 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ChangeType, ViewSnapshot } from '../core/view_snapshot'; +import { FieldPath } from '../lite-api/field_path'; +import { DocumentData, PartialWithFieldValue, Query, SetOptions, WithFieldValue } from '../lite-api/reference'; +import { DocumentSnapshot as LiteDocumentSnapshot, FirestoreDataConverter as LiteFirestoreDataConverter } from '../lite-api/snapshot'; +import { UntypedFirestoreDataConverter } from '../lite-api/user_data_reader'; +import { AbstractUserDataWriter } from '../lite-api/user_data_writer'; +import { Document } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { Property } from '../util/json_validation'; +import { Firestore } from './database'; +import { SnapshotListenOptions } from './reference_impl'; +/** + * Converter used by `withConverter()` to transform user objects of type + * `AppModelType` into Firestore data of type `DbModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * In this context, an "AppModel" is a class that is used in an application to + * package together related information and functionality. Such a class could, + * for example, have properties with complex, nested data types, properties used + * for memoization, properties of types not supported by Firestore (such as + * `symbol` and `bigint`), and helper functions that perform compound + * operations. Such classes are not suitable and/or possible to store into a + * Firestore database. Instead, instances of such classes need to be converted + * to "plain old JavaScript objects" (POJOs) with exclusively primitive + * properties, potentially nested inside other POJOs or arrays of POJOs. In this + * context, this type is referred to as the "DbModel" and would be an object + * suitable for persisting into Firestore. For convenience, applications can + * implement `FirestoreDataConverter` and register the converter with Firestore + * objects, such as `DocumentReference` or `Query`, to automatically convert + * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel` + * to `AppModel` when retrieving from Firestore. + * + * @example + * + * Simple Example + * + * ```typescript + * const numberConverter = { + * toFirestore(value: WithFieldValue) { + * return { value }; + * }, + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) { + * return snapshot.data(options).value as number; + * } + * }; + * + * async function simpleDemo(db: Firestore): Promise { + * const documentRef = doc(db, 'values/value123').withConverter(numberConverter); + * + * // converters are used with `setDoc`, `addDoc`, and `getDoc` + * await setDoc(documentRef, 42); + * const snapshot1 = await getDoc(documentRef); + * assertEqual(snapshot1.data(), 42); + * + * // converters are not used when writing data with `updateDoc` + * await updateDoc(documentRef, { value: 999 }); + * const snapshot2 = await getDoc(documentRef); + * assertEqual(snapshot2.data(), 999); + * } + * ``` + * + * Advanced Example + * + * ```typescript + * // The Post class is a model that is used by our application. + * // This class may have properties and methods that are specific + * // to our application execution, which do not need to be persisted + * // to Firestore. + * class Post { + * constructor( + * readonly title: string, + * readonly author: string, + * readonly lastUpdatedMillis: number + * ) {} + * toString(): string { + * return `${this.title} by ${this.author}`; + * } + * } + * + * // The PostDbModel represents how we want our posts to be stored + * // in Firestore. This DbModel has different properties (`ttl`, + * // `aut`, and `lut`) from the Post class we use in our application. + * interface PostDbModel { + * ttl: string; + * aut: { firstName: string; lastName: string }; + * lut: Timestamp; + * } + * + * // The `PostConverter` implements `FirestoreDataConverter` and specifies + * // how the Firestore SDK can convert `Post` objects to `PostDbModel` + * // objects and vice versa. + * class PostConverter implements FirestoreDataConverter { + * toFirestore(post: WithFieldValue): WithFieldValue { + * return { + * ttl: post.title, + * aut: this._autFromAuthor(post.author), + * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis) + * }; + * } + * + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post { + * const data = snapshot.data(options) as PostDbModel; + * const author = `${data.aut.firstName} ${data.aut.lastName}`; + * return new Post(data.ttl, author, data.lut.toMillis()); + * } + * + * _autFromAuthor( + * author: string | FieldValue + * ): { firstName: string; lastName: string } | FieldValue { + * if (typeof author !== 'string') { + * // `author` is a FieldValue, so just return it. + * return author; + * } + * const [firstName, lastName] = author.split(' '); + * return {firstName, lastName}; + * } + * + * _lutFromLastUpdatedMillis( + * lastUpdatedMillis: number | FieldValue + * ): Timestamp | FieldValue { + * if (typeof lastUpdatedMillis !== 'number') { + * // `lastUpdatedMillis` must be a FieldValue, so just return it. + * return lastUpdatedMillis; + * } + * return Timestamp.fromMillis(lastUpdatedMillis); + * } + * } + * + * async function advancedDemo(db: Firestore): Promise { + * // Create a `DocumentReference` with a `FirestoreDataConverter`. + * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter()); + * + * // The `data` argument specified to `setDoc()` is type checked by the + * // TypeScript compiler to be compatible with `Post`. Since the `data` + * // argument is typed as `WithFieldValue` rather than just `Post`, + * // this allows properties of the `data` argument to also be special + * // Firestore values that perform server-side mutations, such as + * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`. + * await setDoc(documentRef, { + * title: 'My Life', + * author: 'Foo Bar', + * lastUpdatedMillis: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `setDoc()` is _not_ compatible with `WithFieldValue`. This + * // type checking prevents the caller from specifying objects with incorrect + * // properties or property values. + * // @ts-expect-error "Argument of type { ttl: string; } is not assignable + * // to parameter of type WithFieldValue" + * await setDoc(documentRef, { ttl: 'The Title' }); + * + * // When retrieving a document with `getDoc()` the `DocumentSnapshot` + * // object's `data()` method returns a `Post`, rather than a generic object, + * // which would have been returned if the `DocumentReference` did _not_ have a + * // `FirestoreDataConverter` attached to it. + * const snapshot1: DocumentSnapshot = await getDoc(documentRef); + * const post1: Post = snapshot1.data()!; + * if (post1) { + * assertEqual(post1.title, 'My Life'); + * assertEqual(post1.author, 'Foo Bar'); + * } + * + * // The `data` argument specified to `updateDoc()` is type checked by the + * // TypeScript compiler to be compatible with `PostDbModel`. Note that + * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`, + * // the `data` argument to `updateDoc()` must be compatible with + * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed + * // as `WithFieldValue` rather than just `PostDbModel`, this + * // allows properties of the `data` argument to also be those special + * // Firestore values, like `arrayRemove()`, `deleteField()`, and + * // `serverTimestamp()`. + * await updateDoc(documentRef, { + * 'aut.firstName': 'NewFirstName', + * lut: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `updateDoc()` is _not_ compatible with `WithFieldValue`. + * // This type checking prevents the caller from specifying objects with + * // incorrect properties or property values. + * // @ts-expect-error "Argument of type { title: string; } is not assignable + * // to parameter of type WithFieldValue" + * await updateDoc(documentRef, { title: 'New Title' }); + * const snapshot2: DocumentSnapshot = await getDoc(documentRef); + * const post2: Post = snapshot2.data()!; + * if (post2) { + * assertEqual(post2.title, 'My Life'); + * assertEqual(post2.author, 'NewFirstName Bar'); + * } + * } + * ``` + */ +export interface FirestoreDataConverter extends LiteFirestoreDataConverter { + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. To use `set()` + * with `merge` and `mergeFields`, `toFirestore()` must be defined with + * `PartialWithFieldValue`. + * + * The `WithFieldValue` type extends `T` to also allow FieldValues such as + * {@link (deleteField:1)} to be used as property values. + */ + toFirestore(modelObject: WithFieldValue): WithFieldValue; + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link (setDoc:1)}, {@link (WriteBatch.set:1)} and + * {@link (Transaction.set:1)} with `merge:true` or `mergeFields`. + * + * The `PartialWithFieldValue` type extends `Partial` to allow + * FieldValues such as {@link (arrayUnion:1)} to be used as property values. + * It also supports nested `Partial` by allowing nested fields to be + * omitted. + */ + toFirestore(modelObject: PartialWithFieldValue, options: SetOptions): PartialWithFieldValue; + /** + * Called by the Firestore SDK to convert Firestore data into an object of + * type `AppModelType`. You can access your data by calling: + * `snapshot.data(options)`. + * + * Generally, the data returned from `snapshot.data()` can be cast to + * `DbModelType`; however, this is not guaranteed because Firestore does not + * enforce a schema on the database. For example, writes from a previous + * version of the application or writes from another client that did not use a + * type converter could have written data with different properties and/or + * property types. The implementation will need to choose whether to + * gracefully recover from non-conforming data or throw an error. + * + * To override this method, see {@link (FirestoreDataConverter.fromFirestore:1)}. + * + * @param snapshot - A `QueryDocumentSnapshot` containing your data and metadata. + * @param options - The `SnapshotOptions` from the initial call to `data()`. + */ + fromFirestore(snapshot: QueryDocumentSnapshot, options?: SnapshotOptions): AppModelType; +} +/** + * Options that configure how data is retrieved from a `DocumentSnapshot` (for + * example the desired behavior for server timestamps that have not yet been set + * to their final value). + */ +export interface SnapshotOptions { + /** + * If set, controls the return value for server timestamps that have not yet + * been set to their final value. + * + * By specifying 'estimate', pending server timestamps return an estimate + * based on the local clock. This estimate will differ from the final value + * and cause these values to change once the server result becomes available. + * + * By specifying 'previous', pending timestamps will be ignored and return + * their previous value instead. + * + * If omitted or set to 'none', `null` will be returned by default until the + * server value becomes available. + */ + readonly serverTimestamps?: 'estimate' | 'previous' | 'none'; +} +/** + * Metadata about a snapshot, describing the state of the snapshot. + */ +export declare class SnapshotMetadata { + /** + * True if the snapshot contains the result of local writes (for example + * `set()` or `update()` calls) that have not yet been committed to the + * backend. If your listener has opted into metadata updates (via + * `SnapshotListenOptions`) you will receive another snapshot with + * `hasPendingWrites` equal to false once the writes have been committed to + * the backend. + */ + readonly hasPendingWrites: boolean; + /** + * True if the snapshot was created from cached data rather than guaranteed + * up-to-date server data. If your listener has opted into metadata updates + * (via `SnapshotListenOptions`) you will receive another snapshot with + * `fromCache` set to false once the client has received up-to-date data from + * the backend. + */ + readonly fromCache: boolean; + /** @hideconstructor */ + constructor(hasPendingWrites: boolean, fromCache: boolean); + /** + * Returns true if this `SnapshotMetadata` is equal to the provided one. + * + * @param other - The `SnapshotMetadata` to compare against. + * @returns true if this `SnapshotMetadata` is equal to the provided one. + */ + isEqual(other: SnapshotMetadata): boolean; +} +/** + * The type of a `DocumentChange` may be 'added', 'removed', or 'modified'. + */ +export type DocumentChangeType = 'added' | 'removed' | 'modified'; +/** + * A `DocumentChange` represents a change to the documents matching a query. + * It contains the document affected and the type of change that occurred. + */ +export interface DocumentChange { + /** The type of change ('added', 'modified', or 'removed'). */ + readonly type: DocumentChangeType; + /** The document affected by this change. */ + readonly doc: QueryDocumentSnapshot; + /** + * The index of the changed document in the result set immediately prior to + * this `DocumentChange` (i.e. supposing that all prior `DocumentChange` objects + * have been applied). Is `-1` for 'added' events. + */ + readonly oldIndex: number; + /** + * The index of the changed document in the result set immediately after + * this `DocumentChange` (i.e. supposing that all prior `DocumentChange` + * objects and the current `DocumentChange` object have been applied). + * Is -1 for 'removed' events. + */ + readonly newIndex: number; +} +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ +export declare class DocumentSnapshot extends LiteDocumentSnapshot { + readonly _firestore: Firestore; + private readonly _firestoreImpl; + /** + * Metadata about the `DocumentSnapshot`, including information about its + * source and local modifications. + */ + readonly metadata: SnapshotMetadata; + /** @hideconstructor protected */ + constructor(_firestore: Firestore, userDataWriter: AbstractUserDataWriter, key: DocumentKey, document: Document | null, metadata: SnapshotMetadata, converter: UntypedFirestoreDataConverter | null); + /** + * Returns whether or not the data exists. True if the document exists. + */ + exists(): this is QueryDocumentSnapshot; + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * By default, `serverTimestamp()` values that have not yet been + * set to their final value will be returned as `null`. You can override + * this by passing an options object. + * + * @param options - An options object to configure how data is retrieved from + * the snapshot (for example the desired behavior for server timestamps that + * have not yet been set to their final value). + * @returns An `Object` containing all fields in the document or `undefined` if + * the document doesn't exist. + */ + data(options?: SnapshotOptions): AppModelType | undefined; + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * By default, a `serverTimestamp()` that has not yet been set to + * its final value will be returned as `null`. You can override this by + * passing an options object. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @param options - An options object to configure how the field is retrieved + * from the snapshot (for example the desired behavior for server timestamps + * that have not yet been set to their final value). + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + get(fieldPath: string | FieldPath, options?: SnapshotOptions): any; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + bundleSource: Property<"string">; + bundleName: Property<"string">; + bundle: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `DocumentSnapshot` instance. + * + * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this + * `DocumentSnapshot` has pending writes. + */ + toJSON(): object; +} +/** + * Builds a `DocumentSnapshot` instance from a JSON object created by + * {@link DocumentSnapshot.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json - a JSON object represention of a `DocumentSnapshot` instance. + * @returns an instance of {@link DocumentSnapshot} if the JSON object could be + * parsed. Throws a {@link FirestoreError} if an error occurs. + */ +export declare function documentSnapshotFromJSON(db: Firestore, json: object): DocumentSnapshot; +/** + * Builds a `DocumentSnapshot` instance from a JSON object created by + * {@link DocumentSnapshot.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json - a JSON object represention of a `DocumentSnapshot` instance. + * @param converter - Converts objects to and from Firestore. + * @returns an instance of {@link DocumentSnapshot} if the JSON object could be + * parsed. Throws a {@link FirestoreError} if an error occurs. + */ +export declare function documentSnapshotFromJSON(db: Firestore, json: object, converter: FirestoreDataConverter): DocumentSnapshot; +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ +export declare class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * By default, `serverTimestamp()` values that have not yet been + * set to their final value will be returned as `null`. You can override + * this by passing an options object. + * + * @override + * @param options - An options object to configure how data is retrieved from + * the snapshot (for example the desired behavior for server timestamps that + * have not yet been set to their final value). + * @returns An `Object` containing all fields in the document. + */ + data(options?: SnapshotOptions): AppModelType; +} +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ +export declare class QuerySnapshot { + readonly _firestore: Firestore; + readonly _userDataWriter: AbstractUserDataWriter; + readonly _snapshot: ViewSnapshot; + /** + * Metadata about this snapshot, concerning its source and if it has local + * modifications. + */ + readonly metadata: SnapshotMetadata; + /** + * The query on which you called `get` or `onSnapshot` in order to get this + * `QuerySnapshot`. + */ + readonly query: Query; + private _cachedChanges?; + private _cachedChangesIncludeMetadataChanges?; + /** @hideconstructor */ + constructor(_firestore: Firestore, _userDataWriter: AbstractUserDataWriter, query: Query, _snapshot: ViewSnapshot); + /** An array of all the documents in the `QuerySnapshot`. */ + get docs(): Array>; + /** The number of documents in the `QuerySnapshot`. */ + get size(): number; + /** True if there are no documents in the `QuerySnapshot`. */ + get empty(): boolean; + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ + forEach(callback: (result: QueryDocumentSnapshot) => void, thisArg?: unknown): void; + /** + * Returns an array of the documents changes since the last snapshot. If this + * is the first snapshot, all documents will be in the list as 'added' + * changes. + * + * @param options - `SnapshotListenOptions` that control whether metadata-only + * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger + * snapshot events. + */ + docChanges(options?: SnapshotListenOptions): Array>; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + bundleSource: Property<"string">; + bundleName: Property<"string">; + bundle: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `QuerySnapshot` instance. + * + * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this + * `QuerySnapshot` has pending writes. + */ + toJSON(): object; +} +/** + * Builds a `QuerySnapshot` instance from a JSON object created by + * {@link QuerySnapshot.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json - a JSON object represention of a `QuerySnapshot` instance. + * @returns an instance of {@link QuerySnapshot} if the JSON object could be + * parsed. Throws a {@link FirestoreError} if an error occurs. + */ +export declare function querySnapshotFromJSON(db: Firestore, json: object): QuerySnapshot; +/** + * Builds a `QuerySnapshot` instance from a JSON object created by + * {@link QuerySnapshot.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json - a JSON object represention of a `QuerySnapshot` instance. + * @param converter - Converts objects to and from Firestore. + * @returns an instance of {@link QuerySnapshot} if the JSON object could be + * parsed. Throws a {@link FirestoreError} if an error occurs. + */ +export declare function querySnapshotFromJSON(db: Firestore, json: object, converter: FirestoreDataConverter): QuerySnapshot; +/** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */ +export declare function changesFromSnapshot(querySnapshot: QuerySnapshot, includeMetadataChanges: boolean): Array>; +export declare function resultChangeType(type: ChangeType): DocumentChangeType; +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ +export declare function snapshotEqual(left: DocumentSnapshot | QuerySnapshot, right: DocumentSnapshot | QuerySnapshot): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/timestamp.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/timestamp.d.ts new file mode 100644 index 0000000..35969cd --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/timestamp.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { Timestamp } from '../lite-api/timestamp'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/transaction.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/transaction.d.ts new file mode 100644 index 0000000..eccd1fb --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/transaction.d.ts @@ -0,0 +1,61 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Transaction as InternalTransaction } from '../core/transaction'; +import { DocumentData, DocumentReference } from '../lite-api/reference'; +import { Transaction as LiteTransaction } from '../lite-api/transaction'; +import { Firestore } from './database'; +import { DocumentSnapshot } from './snapshot'; +import { TransactionOptions } from './transaction_options'; +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ +export declare class Transaction extends LiteTransaction { + protected readonly _firestore: Firestore; + /** @hideconstructor */ + constructor(_firestore: Firestore, _transaction: InternalTransaction); + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ + get(documentRef: DocumentReference): Promise>; +} +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ +export declare function runTransaction(firestore: Firestore, updateFunction: (transaction: Transaction) => Promise, options?: TransactionOptions): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/transaction_options.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/transaction_options.d.ts new file mode 100644 index 0000000..578e4f4 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/transaction_options.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { TransactionOptions } from '../lite-api/transaction_options'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/write_batch.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/write_batch.d.ts new file mode 100644 index 0000000..13b31d8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/api/write_batch.d.ts @@ -0,0 +1,31 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { WriteBatch } from '../lite-api/write_batch'; +import { Firestore } from './database'; +export { WriteBatch }; +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch} + * is 500. + * + * Unlike transactions, write batches are persisted offline and therefore are + * preferable when you don't need to condition your writes on read data. + * + * @returns A {@link WriteBatch} that can be used to atomically execute multiple + * writes. + */ +export declare function writeBatch(firestore: Firestore): WriteBatch; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/auth/user.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/auth/user.d.ts new file mode 100644 index 0000000..920a290 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/auth/user.d.ts @@ -0,0 +1,36 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Simple wrapper around a nullable UID. Mostly exists to make code more + * readable. + */ +export declare class User { + readonly uid: string | null; + /** A user with a null UID. */ + static readonly UNAUTHENTICATED: User; + static readonly GOOGLE_CREDENTIALS: User; + static readonly FIRST_PARTY: User; + static readonly MOCK_USER: User; + constructor(uid: string | null); + isAuthenticated(): boolean; + /** + * Returns a key representing this user, suitable for inclusion in a + * dictionary. + */ + toKey(): string; + isEqual(otherUser: User): boolean; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/aggregate.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/aggregate.d.ts new file mode 100644 index 0000000..16da2bb --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/aggregate.d.ts @@ -0,0 +1,38 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FieldPath } from '../model/path'; +/** + * Union type representing the aggregate type to be performed. + */ +export type AggregateType = 'count' | 'avg' | 'sum'; +/** + * Represents an Aggregate to be performed over a query result set. + */ +export interface Aggregate { + readonly fieldPath?: FieldPath; + readonly alias: string; + readonly aggregateType: AggregateType; +} +/** + * Concrete implementation of the Aggregate type. + */ +export declare class AggregateImpl implements Aggregate { + readonly alias: string; + readonly aggregateType: AggregateType; + readonly fieldPath?: FieldPath | undefined; + constructor(alias: string, aggregateType: AggregateType, fieldPath?: FieldPath | undefined); +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/bound.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/bound.d.ts new file mode 100644 index 0000000..8289126 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/bound.d.ts @@ -0,0 +1,49 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Document } from '../model/document'; +import { Value as ProtoValue } from '../protos/firestore_proto_api'; +import { OrderBy } from './order_by'; +/** + * Represents a bound of a query. + * + * The bound is specified with the given components representing a position and + * whether it's just before or just after the position (relative to whatever the + * query order is). + * + * The position represents a logical index position for a query. It's a prefix + * of values for the (potentially implicit) order by clauses of a query. + * + * Bound provides a function to determine whether a document comes before or + * after a bound. This is influenced by whether the position is just before or + * just after the provided values. + */ +export declare class Bound { + readonly position: ProtoValue[]; + readonly inclusive: boolean; + constructor(position: ProtoValue[], inclusive: boolean); +} +/** + * Returns true if a document sorts after a bound using the provided sort + * order. + */ +export declare function boundSortsAfterDocument(bound: Bound, orderBy: OrderBy[], doc: Document): boolean; +/** + * Returns true if a document sorts before a bound using the provided sort + * order. + */ +export declare function boundSortsBeforeDocument(bound: Bound, orderBy: OrderBy[], doc: Document): boolean; +export declare function boundEquals(left: Bound | null, right: Bound | null): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/bundle.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/bundle.d.ts new file mode 100644 index 0000000..6a81fcf --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/bundle.d.ts @@ -0,0 +1,80 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { LoadBundleTaskProgress } from '@firebase/firestore-types'; +import { DocumentMap } from '../model/collections'; +import { MutableDocument } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { BundledDocumentMetadata as ProtoBundledDocumentMetadata } from '../protos/firestore_bundle_proto'; +import { Document as ApiDocument, Timestamp as ApiTimestamp } from '../protos/firestore_proto_api'; +import { Query } from './query'; +import { SnapshotVersion } from './snapshot_version'; +/** + * Represents a bundled document, including the metadata and the document + * itself, if it exists. + */ +export interface BundledDocument { + metadata: ProtoBundledDocumentMetadata; + document?: ApiDocument; +} +/** + * An array of `BundledDocument`. + */ +export type BundledDocuments = BundledDocument[]; +export interface BundleLoadResult { + readonly progress: LoadBundleTaskProgress; + readonly changedCollectionGroups: Set; + readonly changedDocs: DocumentMap; +} +/** + * Represents a Firestore bundle saved by the SDK in its local storage. + */ +export interface BundleMetadata { + /** + * Id of the bundle. It is used together with `createTime` to determine if a + * bundle has been loaded by the SDK. + */ + readonly id: string; + /** Schema version of the bundle. */ + readonly version: number; + /** + * Set to the snapshot version of the bundle if created by the Server SDKs. + * Otherwise set to SnapshotVersion.MIN. + */ + readonly createTime: SnapshotVersion; +} +/** + * Represents a Query saved by the SDK in its local storage. + */ +export interface NamedQuery { + /** The name of the query. */ + readonly name: string; + /** The underlying query associated with `name`. */ + readonly query: Query; + /** The time at which the results for this query were read. */ + readonly readTime: SnapshotVersion; +} +/** + * Helper to convert objects from bundles to model objects in the SDK. + */ +export interface BundleConverter { + toDocumentKey(name: string): DocumentKey; + /** + * Converts a BundleDocument to a MutableDocument. + */ + toMutableDocument(bundledDoc: BundledDocument): MutableDocument; + toSnapshotVersion(time: ApiTimestamp): SnapshotVersion; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/bundle_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/bundle_impl.d.ts new file mode 100644 index 0000000..55395f2 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/bundle_impl.d.ts @@ -0,0 +1,88 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { LoadBundleTaskProgress } from '@firebase/firestore-types'; +import { LocalStore } from '../local/local_store'; +import { MutableDocument } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { BundleMetadata as ProtoBundleMetadata, NamedQuery as ProtoNamedQuery } from '../protos/firestore_bundle_proto'; +import { Timestamp as ApiTimestamp } from '../protos/firestore_proto_api'; +import { JsonProtoSerializer } from '../remote/serializer'; +import { SizedBundleElement } from '../util/bundle_reader'; +import { BundleConverter, BundledDocument, BundledDocuments, BundleLoadResult } from './bundle'; +import { SnapshotVersion } from './snapshot_version'; +/** + * Helper to convert objects from bundles to model objects in the SDK. + */ +export declare class BundleConverterImpl implements BundleConverter { + private readonly serializer; + constructor(serializer: JsonProtoSerializer); + toDocumentKey(name: string): DocumentKey; + /** + * Converts a BundleDocument to a MutableDocument. + */ + toMutableDocument(bundledDoc: BundledDocument): MutableDocument; + toSnapshotVersion(time: ApiTimestamp): SnapshotVersion; +} +/** + * A class to process the elements from a bundle, and optionally load them into local + * storage and provide progress update while loading. + */ +export declare class BundleLoader { + private bundleMetadata; + private serializer; + /** The current progress of loading */ + private progress; + /** Batched queries to be saved into storage */ + private _queries; + /** Batched documents to be saved into storage */ + private _documents; + /** The collection groups affected by this bundle. */ + private collectionGroups; + constructor(bundleMetadata: ProtoBundleMetadata, serializer: JsonProtoSerializer); + /** + * Returns the named queries that have been parsed from the SizeBundleElements added by + * calling {@link adSizedElement}. + */ + get queries(): ProtoNamedQuery[]; + /** + * Returns the BundledDocuments that have been parsed from the SizeBundleElements added by + * calling {@link addSizedElement}. + */ + get documents(): BundledDocuments; + /** + * Adds an element from the bundle to the loader. + * + * Returns a new progress if adding the element leads to a new progress, + * otherwise returns null. + */ + addSizedElement(element: SizedBundleElement): LoadBundleTaskProgress | null; + private getQueryDocumentMapping; + /** + * Update the progress to 'Success' and return the updated progress. + */ + completeAndStoreAsync(localStore: LocalStore): Promise; +} +/** + * Returns a `LoadBundleTaskProgress` representing the initial progress of + * loading a bundle. + */ +export declare function bundleInitialProgress(metadata: ProtoBundleMetadata): LoadBundleTaskProgress; +/** + * Returns a `LoadBundleTaskProgress` representing the progress that the loading + * has succeeded. + */ +export declare function bundleSuccessProgress(metadata: ProtoBundleMetadata): LoadBundleTaskProgress; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/component_provider.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/component_provider.d.ts new file mode 100644 index 0000000..97b6814 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/component_provider.d.ts @@ -0,0 +1,146 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { CredentialsProvider } from '../api/credentials'; +import { User } from '../auth/user'; +import { IndexedDbPersistence } from '../local/indexeddb_persistence'; +import { LocalStore } from '../local/local_store'; +import { Scheduler, Persistence } from '../local/persistence'; +import { ClientId, SharedClientState } from '../local/shared_client_state'; +import { Datastore } from '../remote/datastore'; +import { RemoteStore } from '../remote/remote_store'; +import { JsonProtoSerializer } from '../remote/serializer'; +import { AsyncQueue } from '../util/async_queue'; +import { DatabaseInfo } from './database_info'; +import { EventManager } from './event_manager'; +import { SyncEngine } from './sync_engine'; +type Kind = 'memory' | 'persistent'; +export interface ComponentConfiguration { + asyncQueue: AsyncQueue; + databaseInfo: DatabaseInfo; + authCredentials: CredentialsProvider; + appCheckCredentials: CredentialsProvider; + clientId: ClientId; + initialUser: User; + maxConcurrentLimboResolutions: number; +} +export interface OfflineComponentProviderFactory { + build(onlineComponents: OnlineComponentProvider): OfflineComponentProvider; +} +/** + * Initializes and wires components that are needed to interface with the local + * cache. Implementations override `initialize()` to provide all components. + */ +export interface OfflineComponentProvider { + readonly kind: Kind; + persistence: Persistence; + sharedClientState: SharedClientState; + localStore: LocalStore; + gcScheduler: Scheduler | null; + indexBackfillerScheduler: Scheduler | null; + synchronizeTabs: boolean; + initialize(cfg: ComponentConfiguration): Promise; + terminate(): Promise; +} +/** + * Provides all components needed for Firestore with in-memory persistence. + * Uses EagerGC garbage collection. + */ +export declare class MemoryOfflineComponentProvider implements OfflineComponentProvider { + kind: Kind; + static readonly provider: OfflineComponentProviderFactory; + persistence: Persistence; + sharedClientState: SharedClientState; + localStore: LocalStore; + gcScheduler: Scheduler | null; + indexBackfillerScheduler: Scheduler | null; + synchronizeTabs: boolean; + serializer: JsonProtoSerializer; + initialize(cfg: ComponentConfiguration): Promise; + createGarbageCollectionScheduler(cfg: ComponentConfiguration, localStore: LocalStore): Scheduler | null; + createIndexBackfillerScheduler(cfg: ComponentConfiguration, localStore: LocalStore): Scheduler | null; + createLocalStore(cfg: ComponentConfiguration): LocalStore; + createPersistence(cfg: ComponentConfiguration): Persistence; + createSharedClientState(cfg: ComponentConfiguration): SharedClientState; + terminate(): Promise; +} +export declare class LruGcMemoryOfflineComponentProvider extends MemoryOfflineComponentProvider { + protected readonly cacheSizeBytes: number | undefined; + constructor(cacheSizeBytes: number | undefined); + createGarbageCollectionScheduler(cfg: ComponentConfiguration, localStore: LocalStore): Scheduler | null; + createPersistence(cfg: ComponentConfiguration): Persistence; +} +/** + * Provides all components needed for Firestore with IndexedDB persistence. + */ +export declare class IndexedDbOfflineComponentProvider extends MemoryOfflineComponentProvider { + protected readonly onlineComponentProvider: OnlineComponentProvider; + protected readonly cacheSizeBytes: number | undefined; + protected readonly forceOwnership: boolean | undefined; + kind: Kind; + persistence: IndexedDbPersistence; + sharedClientState: SharedClientState; + localStore: LocalStore; + gcScheduler: Scheduler | null; + indexBackfillerScheduler: Scheduler | null; + synchronizeTabs: boolean; + constructor(onlineComponentProvider: OnlineComponentProvider, cacheSizeBytes: number | undefined, forceOwnership: boolean | undefined); + initialize(cfg: ComponentConfiguration): Promise; + createLocalStore(cfg: ComponentConfiguration): LocalStore; + createGarbageCollectionScheduler(cfg: ComponentConfiguration, localStore: LocalStore): Scheduler | null; + createIndexBackfillerScheduler(cfg: ComponentConfiguration, localStore: LocalStore): Scheduler | null; + createPersistence(cfg: ComponentConfiguration): IndexedDbPersistence; + createSharedClientState(cfg: ComponentConfiguration): SharedClientState; +} +/** + * Provides all components needed for Firestore with multi-tab IndexedDB + * persistence. + * + * In the legacy client, this provider is used to provide both multi-tab and + * non-multi-tab persistence since we cannot tell at build time whether + * `synchronizeTabs` will be enabled. + */ +export declare class MultiTabOfflineComponentProvider extends IndexedDbOfflineComponentProvider { + protected readonly onlineComponentProvider: OnlineComponentProvider; + protected readonly cacheSizeBytes: number | undefined; + synchronizeTabs: boolean; + constructor(onlineComponentProvider: OnlineComponentProvider, cacheSizeBytes: number | undefined); + initialize(cfg: ComponentConfiguration): Promise; + createSharedClientState(cfg: ComponentConfiguration): SharedClientState; +} +export interface OnlineComponentProviderFactory { + build(): OnlineComponentProvider; +} +/** + * Initializes and wires the components that are needed to interface with the + * network. + */ +export declare class OnlineComponentProvider { + static readonly provider: OnlineComponentProviderFactory; + protected localStore: LocalStore; + protected sharedClientState: SharedClientState; + datastore: Datastore; + eventManager: EventManager; + remoteStore: RemoteStore; + syncEngine: SyncEngine; + initialize(offlineComponentProvider: OfflineComponentProvider, cfg: ComponentConfiguration): Promise; + createEventManager(cfg: ComponentConfiguration): EventManager; + createDatastore(cfg: ComponentConfiguration): Datastore; + createRemoteStore(cfg: ComponentConfiguration): RemoteStore; + createSyncEngine(cfg: ComponentConfiguration, startAsPrimary: boolean): SyncEngine; + terminate(): Promise; +} +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/database_info.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/database_info.d.ts new file mode 100644 index 0000000..5429403 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/database_info.d.ts @@ -0,0 +1,64 @@ +import { FirebaseApp } from '@firebase/app'; +import { ExperimentalLongPollingOptions } from '../api/long_polling_options'; +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare class DatabaseInfo { + readonly databaseId: DatabaseId; + readonly appId: string; + readonly persistenceKey: string; + readonly host: string; + readonly ssl: boolean; + readonly forceLongPolling: boolean; + readonly autoDetectLongPolling: boolean; + readonly longPollingOptions: ExperimentalLongPollingOptions; + readonly useFetchStreams: boolean; + readonly isUsingEmulator: boolean; + /** + * Constructs a DatabaseInfo using the provided host, databaseId and + * persistenceKey. + * + * @param databaseId - The database to use. + * @param appId - The Firebase App Id. + * @param persistenceKey - A unique identifier for this Firestore's local + * storage (used in conjunction with the databaseId). + * @param host - The Firestore backend host to connect to. + * @param ssl - Whether to use SSL when connecting. + * @param forceLongPolling - Whether to use the forceLongPolling option + * when using WebChannel as the network transport. + * @param autoDetectLongPolling - Whether to use the detectBufferingProxy + * option when using WebChannel as the network transport. + * @param longPollingOptions Options that configure long-polling. + * @param useFetchStreams Whether to use the Fetch API instead of + * XMLHTTPRequest + */ + constructor(databaseId: DatabaseId, appId: string, persistenceKey: string, host: string, ssl: boolean, forceLongPolling: boolean, autoDetectLongPolling: boolean, longPollingOptions: ExperimentalLongPollingOptions, useFetchStreams: boolean, isUsingEmulator: boolean); +} +/** The default database name for a project. */ +export declare const DEFAULT_DATABASE_NAME = "(default)"; +/** + * Represents the database ID a Firestore client is associated with. + * @internal + */ +export declare class DatabaseId { + readonly projectId: string; + readonly database: string; + constructor(projectId: string, database?: string); + static empty(): DatabaseId; + get isDefaultDatabase(): boolean; + isEqual(other: {}): boolean; +} +export declare function databaseIdFromApp(app: FirebaseApp, database?: string): DatabaseId; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/event_manager.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/event_manager.d.ts new file mode 100644 index 0000000..38b980f --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/event_manager.d.ts @@ -0,0 +1,133 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirestoreError } from '../util/error'; +import { EventHandler } from '../util/misc'; +import { ObjectMap } from '../util/obj_map'; +import { Query } from './query'; +import { OnlineState } from './types'; +import { ViewSnapshot } from './view_snapshot'; +/** + * Holds the listeners and the last received ViewSnapshot for a query being + * tracked by EventManager. + */ +declare class QueryListenersInfo { + viewSnap: ViewSnapshot | undefined; + listeners: QueryListener[]; + hasRemoteListeners(): boolean; +} +/** + * Interface for handling events from the EventManager. + */ +export interface Observer { + next: EventHandler; + error: EventHandler; +} +/** + * EventManager is responsible for mapping queries to query event emitters. + * It handles "fan-out". -- Identical queries will re-use the same watch on the + * backend. + * + * PORTING NOTE: On Web, EventManager `onListen` and `onUnlisten` need to be + * assigned to SyncEngine's `listen()` and `unlisten()` API before usage. This + * allows users to tree-shake the Watch logic. + */ +export interface EventManager { + onListen?: (query: Query, enableRemoteListen: boolean) => Promise; + onUnlisten?: (query: Query, disableRemoteListen: boolean) => Promise; + onFirstRemoteStoreListen?: (query: Query) => Promise; + onLastRemoteStoreUnlisten?: (query: Query) => Promise; + terminate(): void; +} +export declare function newEventManager(): EventManager; +export declare class EventManagerImpl implements EventManager { + queries: ObjectMap; + onlineState: OnlineState; + snapshotsInSyncListeners: Set>; + /** Callback invoked when a Query is first listen to. */ + onListen?: (query: Query, enableRemoteListen: boolean) => Promise; + /** Callback invoked once all listeners to a Query are removed. */ + onUnlisten?: (query: Query, disableRemoteListen: boolean) => Promise; + /** + * Callback invoked when a Query starts listening to the remote store, while + * already listening to the cache. + */ + onFirstRemoteStoreListen?: (query: Query) => Promise; + /** + * Callback invoked when a Query stops listening to the remote store, while + * still listening to the cache. + */ + onLastRemoteStoreUnlisten?: (query: Query) => Promise; + terminate(): void; +} +export declare function eventManagerListen(eventManager: EventManager, listener: QueryListener): Promise; +export declare function eventManagerUnlisten(eventManager: EventManager, listener: QueryListener): Promise; +export declare function eventManagerOnWatchChange(eventManager: EventManager, viewSnaps: ViewSnapshot[]): void; +export declare function eventManagerOnWatchError(eventManager: EventManager, query: Query, error: FirestoreError): void; +export declare function eventManagerOnOnlineStateChange(eventManager: EventManager, onlineState: OnlineState): void; +export declare function addSnapshotsInSyncListener(eventManager: EventManager, observer: Observer): void; +export declare function removeSnapshotsInSyncListener(eventManager: EventManager, observer: Observer): void; +export declare enum ListenerDataSource { + /** Listen to both cache and server changes */ + Default = "default", + /** Listen to changes in cache only */ + Cache = "cache" +} +export interface ListenOptions { + /** Raise events even when only the metadata changes */ + readonly includeMetadataChanges?: boolean; + /** + * Wait for a sync with the server when online, but still raise events while + * offline. + */ + readonly waitForSyncWhenOnline?: boolean; + /** Set the source events raised from. */ + readonly source?: ListenerDataSource; +} +/** + * QueryListener takes a series of internal view snapshots and determines + * when to raise the event. + * + * It uses an Observer to dispatch events. + */ +export declare class QueryListener { + readonly query: Query; + private queryObserver; + /** + * Initial snapshots (e.g. from cache) may not be propagated to the wrapped + * observer. This flag is set to true once we've actually raised an event. + */ + private raisedInitialEvent; + private options; + private snap; + private onlineState; + constructor(query: Query, queryObserver: Observer, options?: ListenOptions); + /** + * Applies the new ViewSnapshot to this listener, raising a user-facing event + * if applicable (depending on what changed, whether the user has opted into + * metadata-only changes, etc.). Returns true if a user-facing event was + * indeed raised. + */ + onViewSnapshot(snap: ViewSnapshot): boolean; + onError(error: FirestoreError): void; + /** Returns whether a snapshot was raised. */ + applyOnlineStateChange(onlineState: OnlineState): boolean; + private shouldRaiseInitialEvent; + private shouldRaiseEvent; + private raiseInitialEvent; + listensToRemoteStore(): boolean; +} +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/filter.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/filter.d.ts new file mode 100644 index 0000000..ccb871f --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/filter.d.ts @@ -0,0 +1,130 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Document } from '../model/document'; +import { FieldPath } from '../model/path'; +import { Value as ProtoValue } from '../protos/firestore_proto_api'; +export declare const enum Operator { + LESS_THAN = "<", + LESS_THAN_OR_EQUAL = "<=", + EQUAL = "==", + NOT_EQUAL = "!=", + GREATER_THAN = ">", + GREATER_THAN_OR_EQUAL = ">=", + ARRAY_CONTAINS = "array-contains", + IN = "in", + NOT_IN = "not-in", + ARRAY_CONTAINS_ANY = "array-contains-any" +} +export declare const enum CompositeOperator { + OR = "or", + AND = "and" +} +export declare abstract class Filter { + abstract matches(doc: Document): boolean; + abstract getFlattenedFilters(): readonly FieldFilter[]; + abstract getFilters(): Filter[]; +} +export declare class FieldFilter extends Filter { + readonly field: FieldPath; + readonly op: Operator; + readonly value: ProtoValue; + protected constructor(field: FieldPath, op: Operator, value: ProtoValue); + /** + * Creates a filter based on the provided arguments. + */ + static create(field: FieldPath, op: Operator, value: ProtoValue): FieldFilter; + private static createKeyFieldInFilter; + matches(doc: Document): boolean; + protected matchesComparison(comparison: number): boolean; + isInequality(): boolean; + getFlattenedFilters(): readonly FieldFilter[]; + getFilters(): Filter[]; +} +export declare class CompositeFilter extends Filter { + readonly filters: readonly Filter[]; + readonly op: CompositeOperator; + private memoizedFlattenedFilters; + protected constructor(filters: readonly Filter[], op: CompositeOperator); + /** + * Creates a filter based on the provided arguments. + */ + static create(filters: Filter[], op: CompositeOperator): CompositeFilter; + matches(doc: Document): boolean; + getFlattenedFilters(): readonly FieldFilter[]; + getFilters(): Filter[]; +} +export declare function compositeFilterIsConjunction(compositeFilter: CompositeFilter): boolean; +export declare function compositeFilterIsDisjunction(compositeFilter: CompositeFilter): boolean; +/** + * Returns true if this filter is a conjunction of field filters only. Returns false otherwise. + */ +export declare function compositeFilterIsFlatConjunction(compositeFilter: CompositeFilter): boolean; +/** + * Returns true if this filter does not contain any composite filters. Returns false otherwise. + */ +export declare function compositeFilterIsFlat(compositeFilter: CompositeFilter): boolean; +export declare function canonifyFilter(filter: Filter): string; +export declare function filterEquals(f1: Filter, f2: Filter): boolean; +export declare function fieldFilterEquals(f1: FieldFilter, f2: Filter): boolean; +export declare function compositeFilterEquals(f1: CompositeFilter, f2: Filter): boolean; +/** + * Returns a new composite filter that contains all filter from + * `compositeFilter` plus all the given filters in `otherFilters`. + */ +export declare function compositeFilterWithAddedFilters(compositeFilter: CompositeFilter, otherFilters: Filter[]): CompositeFilter; +/** Returns a debug description for `filter`. */ +export declare function stringifyFilter(filter: Filter): string; +export declare function stringifyCompositeFilter(filter: CompositeFilter): string; +export declare function stringifyFieldFilter(filter: FieldFilter): string; +/** Filter that matches on key fields (i.e. '__name__'). */ +export declare class KeyFieldFilter extends FieldFilter { + private readonly key; + constructor(field: FieldPath, op: Operator, value: ProtoValue); + matches(doc: Document): boolean; +} +/** Filter that matches on key fields within an array. */ +export declare class KeyFieldInFilter extends FieldFilter { + private readonly keys; + constructor(field: FieldPath, value: ProtoValue); + matches(doc: Document): boolean; +} +/** Filter that matches on key fields not present within an array. */ +export declare class KeyFieldNotInFilter extends FieldFilter { + private readonly keys; + constructor(field: FieldPath, value: ProtoValue); + matches(doc: Document): boolean; +} +/** A Filter that implements the array-contains operator. */ +export declare class ArrayContainsFilter extends FieldFilter { + constructor(field: FieldPath, value: ProtoValue); + matches(doc: Document): boolean; +} +/** A Filter that implements the IN operator. */ +export declare class InFilter extends FieldFilter { + constructor(field: FieldPath, value: ProtoValue); + matches(doc: Document): boolean; +} +/** A Filter that implements the not-in operator. */ +export declare class NotInFilter extends FieldFilter { + constructor(field: FieldPath, value: ProtoValue); + matches(doc: Document): boolean; +} +/** A Filter that implements the array-contains-any operator. */ +export declare class ArrayContainsAnyFilter extends FieldFilter { + constructor(field: FieldPath, value: ProtoValue); + matches(doc: Document): boolean; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/firestore_client.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/firestore_client.d.ts new file mode 100644 index 0000000..a3a2b24 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/firestore_client.d.ts @@ -0,0 +1,138 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { GetOptions } from '@firebase/firestore-types'; +import { LoadBundleTask } from '../api/bundle'; +import { CredentialsProvider } from '../api/credentials'; +import { User } from '../auth/user'; +import { LocalStore } from '../local/local_store'; +import { Document } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { FieldIndex } from '../model/field_index'; +import { Mutation } from '../model/mutation'; +import { ApiClientObjectMap, Value } from '../protos/firestore_proto_api'; +import { JsonProtoSerializer } from '../remote/serializer'; +import { AsyncQueue } from '../util/async_queue'; +import { BundleReaderSync } from '../util/bundle_reader'; +import { FirestoreError } from '../util/error'; +import { Aggregate } from './aggregate'; +import { NamedQuery } from './bundle'; +import { ComponentConfiguration, OfflineComponentProvider, OnlineComponentProvider } from './component_provider'; +import { DatabaseId, DatabaseInfo } from './database_info'; +import { EventManager, ListenOptions, Observer } from './event_manager'; +import { Query } from './query'; +import { SyncEngine } from './sync_engine'; +import { Transaction } from './transaction'; +import { TransactionOptions } from './transaction_options'; +import { ViewSnapshot } from './view_snapshot'; +export declare const MAX_CONCURRENT_LIMBO_RESOLUTIONS = 100; +/** + * FirestoreClient is a top-level class that constructs and owns all of the // + * pieces of the client SDK architecture. It is responsible for creating the // + * async queue that is shared by all of the other components in the system. // + */ +export declare class FirestoreClient { + private authCredentials; + private appCheckCredentials; + /** + * Asynchronous queue responsible for all of our internal processing. When + * we get incoming work from the user (via public API) or the network + * (incoming GRPC messages), we should always schedule onto this queue. + * This ensures all of our work is properly serialized (e.g. we don't + * start processing a new operation while the previous one is waiting for + * an async I/O to complete). + */ + asyncQueue: AsyncQueue; + private databaseInfo; + private user; + private readonly clientId; + private authCredentialListener; + private appCheckCredentialListener; + _uninitializedComponentsProvider?: { + _offline: OfflineComponentProvider; + _online: OnlineComponentProvider; + }; + _offlineComponents?: OfflineComponentProvider; + _onlineComponents?: OnlineComponentProvider; + constructor(authCredentials: CredentialsProvider, appCheckCredentials: CredentialsProvider, + /** + * Asynchronous queue responsible for all of our internal processing. When + * we get incoming work from the user (via public API) or the network + * (incoming GRPC messages), we should always schedule onto this queue. + * This ensures all of our work is properly serialized (e.g. we don't + * start processing a new operation while the previous one is waiting for + * an async I/O to complete). + */ + asyncQueue: AsyncQueue, databaseInfo: DatabaseInfo, componentProvider?: { + _offline: OfflineComponentProvider; + _online: OnlineComponentProvider; + }); + get configuration(): ComponentConfiguration; + setCredentialChangeListener(listener: (user: User) => Promise): void; + setAppCheckTokenChangeListener(listener: (appCheckToken: string, user: User) => Promise): void; + terminate(): Promise; +} +export declare function setOfflineComponentProvider(client: FirestoreClient, offlineComponentProvider: OfflineComponentProvider): Promise; +export declare function setOnlineComponentProvider(client: FirestoreClient, onlineComponentProvider: OnlineComponentProvider): Promise; +/** + * Decides whether the provided error allows us to gracefully disable + * persistence (as opposed to crashing the client). + */ +export declare function canFallbackFromIndexedDbError(error: FirestoreError | DOMException): boolean; +export declare function ensureOnlineComponents(client: FirestoreClient): Promise; +export declare function getLocalStore(client: FirestoreClient): Promise; +export declare function getSyncEngine(client: FirestoreClient): Promise; +export declare function getEventManager(client: FirestoreClient): Promise; +/** Enables the network connection and re-enqueues all pending operations. */ +export declare function firestoreClientEnableNetwork(client: FirestoreClient): Promise; +/** Disables the network connection. Pending operations will not complete. */ +export declare function firestoreClientDisableNetwork(client: FirestoreClient): Promise; +/** + * Returns a Promise that resolves when all writes that were pending at the time + * this method was called received server acknowledgement. An acknowledgement + * can be either acceptance or rejection. + */ +export declare function firestoreClientWaitForPendingWrites(client: FirestoreClient): Promise; +export declare function firestoreClientListen(client: FirestoreClient, query: Query, options: ListenOptions, observer: Partial>): () => void; +export declare function firestoreClientGetDocumentFromLocalCache(client: FirestoreClient, docKey: DocumentKey): Promise; +export declare function firestoreClientGetDocumentViaSnapshotListener(client: FirestoreClient, key: DocumentKey, options?: GetOptions): Promise; +export declare function firestoreClientGetDocumentsFromLocalCache(client: FirestoreClient, query: Query): Promise; +export declare function firestoreClientGetDocumentsViaSnapshotListener(client: FirestoreClient, query: Query, options?: GetOptions): Promise; +export declare function firestoreClientRunAggregateQuery(client: FirestoreClient, query: Query, aggregates: Aggregate[]): Promise>; +export declare function firestoreClientWrite(client: FirestoreClient, mutations: Mutation[]): Promise; +export declare function firestoreClientAddSnapshotsInSyncListener(client: FirestoreClient, observer: Partial>): () => void; +/** + * Takes an updateFunction in which a set of reads and writes can be performed + * atomically. In the updateFunction, the client can read and write values + * using the supplied transaction object. After the updateFunction, all + * changes will be committed. If a retryable error occurs (ex: some other + * client has changed any of the data referenced), then the updateFunction + * will be called again after a backoff. If the updateFunction still fails + * after all retries, then the transaction will be rejected. + * + * The transaction object passed to the updateFunction contains methods for + * accessing documents and collections. Unlike other datastore access, data + * accessed with the transaction will not reflect local changes that have not + * been committed. For this reason, it is required that all reads are + * performed before any writes. Transactions must be performed while online. + */ +export declare function firestoreClientTransaction(client: FirestoreClient, updateFunction: (transaction: Transaction) => Promise, options: TransactionOptions): Promise; +export declare function firestoreClientLoadBundle(client: FirestoreClient, databaseId: DatabaseId, data: ReadableStream | ArrayBuffer | string, resultTask: LoadBundleTask): void; +export declare function firestoreClientGetNamedQuery(client: FirestoreClient, queryName: string): Promise; +export declare function createBundleReaderSync(bundleData: string, serializer: JsonProtoSerializer): BundleReaderSync; +export declare function firestoreClientSetIndexConfiguration(client: FirestoreClient, indexes: FieldIndex[]): Promise; +export declare function firestoreClientSetPersistentCacheIndexAutoCreationEnabled(client: FirestoreClient, isEnabled: boolean): Promise; +export declare function firestoreClientDeleteAllFieldIndexes(client: FirestoreClient): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/listen_sequence.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/listen_sequence.d.ts new file mode 100644 index 0000000..c824db1 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/listen_sequence.d.ts @@ -0,0 +1,39 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ListenSequenceNumber } from './types'; +/** + * `SequenceNumberSyncer` defines the methods required to keep multiple instances of a + * `ListenSequence` in sync. + */ +export interface SequenceNumberSyncer { + writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void; + sequenceNumberHandler: ((sequenceNumber: ListenSequenceNumber) => void) | null; +} +/** + * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to + * exceed. All subsequent calls to next will return increasing values. If provided with a + * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as + * well as write out sequence numbers that it produces via `next()`. + */ +export declare class ListenSequence { + private previousValue; + static readonly INVALID: ListenSequenceNumber; + private writeNewSequenceNumber?; + constructor(previousValue: ListenSequenceNumber, sequenceNumberSyncer?: SequenceNumberSyncer); + private setPreviousValue; + next(): ListenSequenceNumber; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/order_by.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/order_by.d.ts new file mode 100644 index 0000000..1d7aa86 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/order_by.d.ts @@ -0,0 +1,35 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FieldPath } from '../model/path'; +/** + * The direction of sorting in an order by. + */ +export declare const enum Direction { + ASCENDING = "asc", + DESCENDING = "desc" +} +/** + * An ordering on a field, in some Direction. Direction defaults to ASCENDING. + */ +export declare class OrderBy { + readonly field: FieldPath; + readonly dir: Direction; + constructor(field: FieldPath, dir?: Direction); +} +export declare function canonifyOrderBy(orderBy: OrderBy): string; +export declare function stringifyOrderBy(orderBy: OrderBy): string; +export declare function orderByEquals(left: OrderBy, right: OrderBy): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/query.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/query.d.ts new file mode 100644 index 0000000..d23e0f1 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/query.d.ts @@ -0,0 +1,142 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Document } from '../model/document'; +import { FieldPath, ResourcePath } from '../model/path'; +import { SortedSet } from '../util/sorted_set'; +import { Bound } from './bound'; +import { Filter } from './filter'; +import { OrderBy } from './order_by'; +import { Target } from './target'; +export declare const enum LimitType { + First = "F", + Last = "L" +} +/** + * The Query interface defines all external properties of a query. + * + * QueryImpl implements this interface to provide memoization for `queryNormalizedOrderBy` + * and `queryToTarget`. + */ +export interface Query { + readonly path: ResourcePath; + readonly collectionGroup: string | null; + readonly explicitOrderBy: OrderBy[]; + readonly filters: Filter[]; + readonly limit: number | null; + readonly limitType: LimitType; + readonly startAt: Bound | null; + readonly endAt: Bound | null; +} +/** + * Query encapsulates all the query attributes we support in the SDK. It can + * be run against the LocalStore, as well as be converted to a `Target` to + * query the RemoteStore results. + * + * Visible for testing. + */ +export declare class QueryImpl implements Query { + readonly path: ResourcePath; + readonly collectionGroup: string | null; + readonly explicitOrderBy: OrderBy[]; + readonly filters: Filter[]; + readonly limit: number | null; + readonly limitType: LimitType; + readonly startAt: Bound | null; + readonly endAt: Bound | null; + memoizedNormalizedOrderBy: OrderBy[] | null; + memoizedTarget: Target | null; + memoizedAggregateTarget: Target | null; + /** + * Initializes a Query with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + */ + constructor(path: ResourcePath, collectionGroup?: string | null, explicitOrderBy?: OrderBy[], filters?: Filter[], limit?: number | null, limitType?: LimitType, startAt?: Bound | null, endAt?: Bound | null); +} +/** Creates a new Query instance with the options provided. */ +export declare function newQuery(path: ResourcePath, collectionGroup: string | null, explicitOrderBy: OrderBy[], filters: Filter[], limit: number | null, limitType: LimitType, startAt: Bound | null, endAt: Bound | null): Query; +/** Creates a new Query for a query that matches all documents at `path` */ +export declare function newQueryForPath(path: ResourcePath): Query; +/** + * Helper to convert a collection group query into a collection query at a + * specific path. This is used when executing collection group queries, since + * we have to split the query into a set of collection queries at multiple + * paths. + */ +export declare function asCollectionQueryAtPath(query: Query, path: ResourcePath): Query; +/** + * Returns true if this query does not specify any query constraints that + * could remove results. + */ +export declare function queryMatchesAllDocuments(query: Query): boolean; +export declare function getInequalityFilterFields(query: Query): SortedSet; +/** + * Creates a new Query for a collection group query that matches all documents + * within the provided collection group. + */ +export declare function newQueryForCollectionGroup(collectionId: string): Query; +/** + * Returns whether the query matches a single document by path (rather than a + * collection). + */ +export declare function isDocumentQuery(query: Query): boolean; +/** + * Returns whether the query matches a collection group rather than a specific + * collection. + */ +export declare function isCollectionGroupQuery(query: Query): boolean; +/** + * Returns the normalized order-by constraint that is used to execute the Query, + * which can be different from the order-by constraints the user provided (e.g. + * the SDK and backend always orders by `__name__`). The normalized order-by + * includes implicit order-bys in addition to the explicit user provided + * order-bys. + */ +export declare function queryNormalizedOrderBy(query: Query): OrderBy[]; +/** + * Converts this `Query` instance to its corresponding `Target` representation. + */ +export declare function queryToTarget(query: Query): Target; +/** + * Converts this `Query` instance to its corresponding `Target` representation, + * for use within an aggregate query. Unlike targets for non-aggregate queries, + * aggregate query targets do not contain normalized order-bys, they only + * contain explicit order-bys. + */ +export declare function queryToAggregateTarget(query: Query): Target; +export declare function queryWithAddedFilter(query: Query, filter: Filter): Query; +export declare function queryWithAddedOrderBy(query: Query, orderBy: OrderBy): Query; +export declare function queryWithLimit(query: Query, limit: number | null, limitType: LimitType): Query; +export declare function queryWithStartAt(query: Query, bound: Bound): Query; +export declare function queryWithEndAt(query: Query, bound: Bound): Query; +export declare function queryEquals(left: Query, right: Query): boolean; +export declare function canonifyQuery(query: Query): string; +export declare function stringifyQuery(query: Query): string; +/** Returns whether `doc` matches the constraints of `query`. */ +export declare function queryMatches(query: Query, doc: Document): boolean; +/** + * Returns the collection group that this query targets. + * + * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab + * synchronization for query results. + */ +export declare function queryCollectionGroup(query: Query): string; +/** + * Returns a new comparator function that can be used to compare two documents + * based on the Query's ordering constraint. + */ +export declare function newQueryComparator(query: Query): (d1: Document, d2: Document) => number; +export declare function compareDocs(orderBy: OrderBy, d1: Document, d2: Document): number; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/snapshot_version.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/snapshot_version.d.ts new file mode 100644 index 0000000..10c508b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/snapshot_version.d.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Timestamp } from '../lite-api/timestamp'; +/** + * A version of a document in Firestore. This corresponds to the version + * timestamp, such as update_time or read_time. + */ +export declare class SnapshotVersion { + private timestamp; + static fromTimestamp(value: Timestamp): SnapshotVersion; + static min(): SnapshotVersion; + static max(): SnapshotVersion; + private constructor(); + compareTo(other: SnapshotVersion): number; + isEqual(other: SnapshotVersion): boolean; + /** Returns a number representation of the version for use in spec tests. */ + toMicroseconds(): number; + toString(): string; + toTimestamp(): Timestamp; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/sync_engine.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/sync_engine.d.ts new file mode 100644 index 0000000..2c28d31 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/sync_engine.d.ts @@ -0,0 +1,37 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * SyncEngine is the central controller in the client SDK architecture. It is + * the glue code between the EventManager, LocalStore, and RemoteStore. Some of + * SyncEngine's responsibilities include: + * 1. Coordinating client requests and remote events between the EventManager + * and the local and remote data stores. + * 2. Managing a View object for each query, providing the unified view between + * the local and remote data stores. + * 3. Notifying the RemoteStore when the LocalStore has new mutations in its + * queue that need sending to the backend. + * + * The SyncEngine’s methods should only ever be called by methods running in the + * global async queue. + * + * PORTING NOTE: On Web, SyncEngine does not have an explicit subscribe() + * function. Instead, it directly depends on EventManager's tree-shakeable API + * (via `ensureWatchStream()`). + */ +export interface SyncEngine { + isPrimaryClient: boolean; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/sync_engine_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/sync_engine_impl.d.ts new file mode 100644 index 0000000..0d2aef9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/sync_engine_impl.d.ts @@ -0,0 +1,255 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { LoadBundleTask } from '../api/bundle'; +import { User } from '../auth/user'; +import { LocalStore } from '../local/local_store'; +import { ReferenceSet } from '../local/reference_set'; +import { ClientId, SharedClientState } from '../local/shared_client_state'; +import { QueryTargetState } from '../local/shared_client_state_syncer'; +import { DocumentKeySet, DocumentMap } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { Mutation } from '../model/mutation'; +import { MutationBatchResult } from '../model/mutation_batch'; +import { RemoteEvent } from '../remote/remote_event'; +import { RemoteStore } from '../remote/remote_store'; +import { BundleReader } from '../util/bundle_reader'; +import { FirestoreError } from '../util/error'; +import { ObjectMap } from '../util/obj_map'; +import { Deferred } from '../util/promise'; +import { SortedMap } from '../util/sorted_map'; +import { EventManager } from './event_manager'; +import { Query } from './query'; +import { SyncEngine } from './sync_engine'; +import { TargetIdGenerator } from './target_id_generator'; +import { BatchId, MutationBatchState, OnlineState, OnlineStateSource, TargetId } from './types'; +import { View } from './view'; +import { ViewSnapshot } from './view_snapshot'; +/** + * QueryView contains all of the data that SyncEngine needs to keep track of for + * a particular query. + */ +declare class QueryView { + /** + * The query itself. + */ + query: Query; + /** + * The target number created by the client that is used in the watch + * stream to identify this query. + */ + targetId: TargetId; + /** + * The view is responsible for computing the final merged truth of what + * docs are in the query. It gets notified of local and remote changes, + * and applies the query filters and limits to determine the most correct + * possible results. + */ + view: View; + constructor( + /** + * The query itself. + */ + query: Query, + /** + * The target number created by the client that is used in the watch + * stream to identify this query. + */ + targetId: TargetId, + /** + * The view is responsible for computing the final merged truth of what + * docs are in the query. It gets notified of local and remote changes, + * and applies the query filters and limits to determine the most correct + * possible results. + */ + view: View); +} +/** Tracks a limbo resolution. */ +declare class LimboResolution { + key: DocumentKey; + constructor(key: DocumentKey); + /** + * Set to true once we've received a document. This is used in + * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to + * decide whether it needs to manufacture a delete event for the target once + * the target is CURRENT. + */ + receivedDocument: boolean; +} +/** + * A function that updates a QueryView with a set of document changes (and a + * remote event if applicable). + */ +type ApplyDocChangesHandler = (queryView: QueryView, changes: DocumentMap, remoteEvent?: RemoteEvent) => Promise; +/** + * Callbacks implemented by EventManager to handle notifications from + * SyncEngine. + */ +interface SyncEngineListener { + /** Handles new view snapshots. */ + onWatchChange?(snapshots: ViewSnapshot[]): void; + /** Handles the failure of a query. */ + onWatchError?(query: Query, error: FirestoreError): void; +} +/** + * An implementation of `SyncEngine` coordinating with other parts of SDK. + * + * The parts of SyncEngine that act as a callback to RemoteStore need to be + * registered individually. This is done in `syncEngineWrite()` and + * `syncEngineListen()` (as well as `applyPrimaryState()`) as these methods + * serve as entry points to RemoteStore's functionality. + * + * Note: some field defined in this class might have public access level, but + * the class is not exported so they are only accessible from this module. + * This is useful to implement optional features (like bundles) in free + * functions, such that they are tree-shakeable. + */ +declare class SyncEngineImpl implements SyncEngine { + readonly localStore: LocalStore; + readonly remoteStore: RemoteStore; + readonly eventManager: EventManager; + readonly sharedClientState: SharedClientState; + currentUser: User; + readonly maxConcurrentLimboResolutions: number; + syncEngineListener: SyncEngineListener; + /** + * A callback that updates the QueryView based on the provided change. + * + * PORTING NOTE: On other platforms, this logic lives in + * `emitNewSnapshotsAndNotifyLocalStore()`, but on Web it is extracted to + * ensure that all view logic only exists in bundles that include views. + */ + applyDocChanges?: ApplyDocChangesHandler; + queryViewsByQuery: ObjectMap; + queriesByTarget: Map; + /** + * The keys of documents that are in limbo for which we haven't yet started a + * limbo resolution query. The strings in this set are the result of calling + * `key.path.canonicalString()` where `key` is a `DocumentKey` object. + * + * The `Set` type was chosen because it provides efficient lookup and removal + * of arbitrary elements and it also maintains insertion order, providing the + * desired queue-like FIFO semantics. + */ + enqueuedLimboResolutions: Set; + /** + * Keeps track of the target ID for each document that is in limbo with an + * active target. + */ + activeLimboTargetsByKey: SortedMap; + /** + * Keeps track of the information about an active limbo resolution for each + * active target ID that was started for the purpose of limbo resolution. + */ + activeLimboResolutionsByTarget: Map; + limboDocumentRefs: ReferenceSet; + /** Stores user completion handlers, indexed by User and BatchId. */ + mutationUserCallbacks: { + [uidKey: string]: SortedMap>; + }; + /** Stores user callbacks waiting for all pending writes to be acknowledged. */ + pendingWritesCallbacks: Map[]>; + limboTargetIdGenerator: TargetIdGenerator; + onlineState: OnlineState; + _isPrimaryClient: undefined | boolean; + constructor(localStore: LocalStore, remoteStore: RemoteStore, eventManager: EventManager, sharedClientState: SharedClientState, currentUser: User, maxConcurrentLimboResolutions: number); + get isPrimaryClient(): boolean; +} +export declare function newSyncEngine(localStore: LocalStore, remoteStore: RemoteStore, eventManager: EventManager, sharedClientState: SharedClientState, currentUser: User, maxConcurrentLimboResolutions: number, isPrimary: boolean): SyncEngine; +/** + * Initiates the new listen, resolves promise when listen enqueued to the + * server. All the subsequent view snapshots or errors are sent to the + * subscribed handlers. Returns the initial snapshot. + */ +export declare function syncEngineListen(syncEngine: SyncEngine, query: Query, shouldListenToRemote?: boolean): Promise; +/** Query has been listening to the cache, and tries to initiate the remote store listen */ +export declare function triggerRemoteStoreListen(syncEngine: SyncEngine, query: Query): Promise; +/** Stops listening to the query. */ +export declare function syncEngineUnlisten(syncEngine: SyncEngine, query: Query, shouldUnlistenToRemote: boolean): Promise; +/** Unlistens to the remote store while still listening to the cache. */ +export declare function triggerRemoteStoreUnlisten(syncEngine: SyncEngine, query: Query): Promise; +/** + * Initiates the write of local mutation batch which involves adding the + * writes to the mutation queue, notifying the remote store about new + * mutations and raising events for any changes this write caused. + * + * The promise returned by this call is resolved when the above steps + * have completed, *not* when the write was acked by the backend. The + * userCallback is resolved once the write was acked/rejected by the + * backend (or failed locally for any other reason). + */ +export declare function syncEngineWrite(syncEngine: SyncEngine, batch: Mutation[], userCallback: Deferred): Promise; +/** + * Applies one remote event to the sync engine, notifying any views of the + * changes, and releasing any pending mutation batches that would become + * visible because of the snapshot version the remote event contains. + */ +export declare function syncEngineApplyRemoteEvent(syncEngine: SyncEngine, remoteEvent: RemoteEvent): Promise; +/** + * Applies an OnlineState change to the sync engine and notifies any views of + * the change. + */ +export declare function syncEngineApplyOnlineStateChange(syncEngine: SyncEngine, onlineState: OnlineState, source: OnlineStateSource): void; +/** + * Rejects the listen for the given targetID. This can be triggered by the + * backend for any active target. + * + * @param syncEngine - The sync engine implementation. + * @param targetId - The targetID corresponds to one previously initiated by the + * user as part of TargetData passed to listen() on RemoteStore. + * @param err - A description of the condition that has forced the rejection. + * Nearly always this will be an indication that the user is no longer + * authorized to see the data matching the target. + */ +export declare function syncEngineRejectListen(syncEngine: SyncEngine, targetId: TargetId, err: FirestoreError): Promise; +export declare function syncEngineApplySuccessfulWrite(syncEngine: SyncEngine, mutationBatchResult: MutationBatchResult): Promise; +export declare function syncEngineRejectFailedWrite(syncEngine: SyncEngine, batchId: BatchId, error: FirestoreError): Promise; +/** + * Registers a user callback that resolves when all pending mutations at the moment of calling + * are acknowledged . + */ +export declare function syncEngineRegisterPendingWritesCallback(syncEngine: SyncEngine, callback: Deferred): Promise; +export declare function syncEngineGetActiveLimboDocumentResolutions(syncEngine: SyncEngine): SortedMap; +export declare function syncEngineGetEnqueuedLimboDocumentResolutions(syncEngine: SyncEngine): Set; +export declare function syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngine: SyncEngine, changes: DocumentMap, remoteEvent?: RemoteEvent): Promise; +export declare function syncEngineHandleCredentialChange(syncEngine: SyncEngine, user: User): Promise; +export declare function syncEngineGetRemoteKeysForTarget(syncEngine: SyncEngine, targetId: TargetId): DocumentKeySet; +/** + * Retrieves newly changed documents from remote document cache and raises + * snapshots if needed. + */ +export declare function syncEngineSynchronizeWithChangedDocuments(syncEngine: SyncEngine, collectionGroup: string): Promise; +/** Applies a mutation state to an existing batch. */ +export declare function syncEngineApplyBatchState(syncEngine: SyncEngine, batchId: BatchId, batchState: MutationBatchState, error?: FirestoreError): Promise; +/** Applies a query target change from a different tab. */ +export declare function syncEngineApplyPrimaryState(syncEngine: SyncEngine, isPrimary: boolean): Promise; +/** Returns the IDs of the clients that are currently active. */ +export declare function syncEngineGetActiveClients(syncEngine: SyncEngine): Promise; +/** Applies a query target change from a different tab. */ +export declare function syncEngineApplyTargetState(syncEngine: SyncEngine, targetId: TargetId, state: QueryTargetState, error?: FirestoreError): Promise; +/** Adds or removes Watch targets for queries from different tabs. */ +export declare function syncEngineApplyActiveTargetsChange(syncEngine: SyncEngine, added: TargetId[], removed: TargetId[]): Promise; +export declare function syncEngineEnsureWriteCallbacks(syncEngine: SyncEngine): SyncEngineImpl; +/** + * Loads a Firestore bundle into the SDK. The returned promise resolves when + * the bundle finished loading. + * + * @param syncEngine - SyncEngine to use. + * @param bundleReader - Bundle to load into the SDK. + * @param task - LoadBundleTask used to update the loading progress to public API. + */ +export declare function syncEngineLoadBundle(syncEngine: SyncEngine, bundleReader: BundleReader, task: LoadBundleTask): void; +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/target.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/target.d.ts new file mode 100644 index 0000000..fcfed20 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/target.d.ts @@ -0,0 +1,89 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FieldIndex } from '../model/field_index'; +import { FieldPath, ResourcePath } from '../model/path'; +import { Value as ProtoValue } from '../protos/firestore_proto_api'; +import { Bound } from './bound'; +import { Filter, FieldFilter } from './filter'; +import { OrderBy } from './order_by'; +/** + * A Target represents the WatchTarget representation of a Query, which is used + * by the LocalStore and the RemoteStore to keep track of and to execute + * backend queries. While a Query can represent multiple Targets, each Targets + * maps to a single WatchTarget in RemoteStore and a single TargetData entry + * in persistence. + */ +export interface Target { + readonly path: ResourcePath; + readonly collectionGroup: string | null; + readonly orderBy: OrderBy[]; + readonly filters: Filter[]; + readonly limit: number | null; + readonly startAt: Bound | null; + readonly endAt: Bound | null; +} +export declare class TargetImpl implements Target { + readonly path: ResourcePath; + readonly collectionGroup: string | null; + readonly orderBy: OrderBy[]; + readonly filters: Filter[]; + readonly limit: number | null; + readonly startAt: Bound | null; + readonly endAt: Bound | null; + memoizedCanonicalId: string | null; + constructor(path: ResourcePath, collectionGroup?: string | null, orderBy?: OrderBy[], filters?: Filter[], limit?: number | null, startAt?: Bound | null, endAt?: Bound | null); +} +/** + * Initializes a Target with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + * + * NOTE: you should always construct `Target` from `Query.toTarget` instead of + * using this factory method, because `Query` provides an implicit `orderBy` + * property. + */ +export declare function newTarget(path: ResourcePath, collectionGroup?: string | null, orderBy?: OrderBy[], filters?: Filter[], limit?: number | null, startAt?: Bound | null, endAt?: Bound | null): Target; +export declare function canonifyTarget(target: Target): string; +export declare function stringifyTarget(target: Target): string; +export declare function targetEquals(left: Target, right: Target): boolean; +export declare function targetIsDocumentTarget(target: Target): boolean; +/** Returns the field filters that target the given field path. */ +export declare function targetGetFieldFiltersForPath(target: Target, path: FieldPath): FieldFilter[]; +/** + * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY + * filters. Returns `null` if there are no such filters. + */ +export declare function targetGetArrayValues(target: Target, fieldIndex: FieldIndex): ProtoValue[] | null; +/** + * Returns the list of values that are used in != or NOT_IN filters. Returns + * `null` if there are no such filters. + */ +export declare function targetGetNotInValues(target: Target, fieldIndex: FieldIndex): ProtoValue[] | null; +/** + * Returns a lower bound of field values that can be used as a starting point to + * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound + * exists. + */ +export declare function targetGetLowerBound(target: Target, fieldIndex: FieldIndex): Bound; +/** + * Returns an upper bound of field values that can be used as an ending point + * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no + * upper bound exists. + */ +export declare function targetGetUpperBound(target: Target, fieldIndex: FieldIndex): Bound; +/** Returns the number of segments of a perfect index for this target. */ +export declare function targetGetSegmentCount(target: Target): number; +export declare function targetHasLimit(target: Target): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/target_id_generator.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/target_id_generator.d.ts new file mode 100644 index 0000000..7a00fcd --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/target_id_generator.d.ts @@ -0,0 +1,38 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { TargetId } from './types'; +/** + * Generates monotonically increasing target IDs for sending targets to the + * watch stream. + * + * The client constructs two generators, one for the target cache, and one for + * for the sync engine (to generate limbo documents targets). These + * generators produce non-overlapping IDs (by using even and odd IDs + * respectively). + * + * By separating the target ID space, the query cache can generate target IDs + * that persist across client restarts, while sync engine can independently + * generate in-memory target IDs that are transient and can be reused after a + * restart. + */ +export declare class TargetIdGenerator { + private lastId; + constructor(lastId: number); + next(): TargetId; + static forTargetCache(): TargetIdGenerator; + static forSyncEngine(): TargetIdGenerator; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/transaction.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/transaction.d.ts new file mode 100644 index 0000000..4a982e9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/transaction.d.ts @@ -0,0 +1,60 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ParsedSetData, ParsedUpdateData } from '../lite-api/user_data_reader'; +import { Document } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { Datastore } from '../remote/datastore'; +/** + * Internal transaction object responsible for accumulating the mutations to + * perform and the base versions for any documents read. + */ +export declare class Transaction { + private datastore; + private readVersions; + private mutations; + private committed; + /** + * A deferred usage error that occurred previously in this transaction that + * will cause the transaction to fail once it actually commits. + */ + private lastTransactionError; + /** + * Set of documents that have been written in the transaction. + * + * When there's more than one write to the same key in a transaction, any + * writes after the first are handled differently. + */ + private writtenDocs; + constructor(datastore: Datastore); + lookup(keys: DocumentKey[]): Promise; + set(key: DocumentKey, data: ParsedSetData): void; + update(key: DocumentKey, data: ParsedUpdateData): void; + delete(key: DocumentKey): void; + commit(): Promise; + private recordVersion; + /** + * Returns the version of this document when it was read in this transaction, + * as a precondition, or no precondition if it was not read. + */ + private precondition; + /** + * Returns the precondition for a document if the operation is an update. + */ + private preconditionForUpdate; + private write; + private ensureCommitNotCalled; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/transaction_options.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/transaction_options.d.ts new file mode 100644 index 0000000..bf52930 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/transaction_options.d.ts @@ -0,0 +1,25 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare const DEFAULT_TRANSACTION_OPTIONS: TransactionOptions; +/** + * Options to customize transaction behavior. + */ +export declare interface TransactionOptions { + /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */ + readonly maxAttempts: number; +} +export declare function validateTransactionOptions(options: TransactionOptions): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/transaction_runner.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/transaction_runner.d.ts new file mode 100644 index 0000000..794c7d3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/transaction_runner.d.ts @@ -0,0 +1,41 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Datastore } from '../remote/datastore'; +import { AsyncQueue } from '../util/async_queue'; +import { Deferred } from '../util/promise'; +import { Transaction } from './transaction'; +import { TransactionOptions } from './transaction_options'; +/** + * TransactionRunner encapsulates the logic needed to run and retry transactions + * with backoff. + */ +export declare class TransactionRunner { + private readonly asyncQueue; + private readonly datastore; + private readonly options; + private readonly updateFunction; + private readonly deferred; + private attemptsRemaining; + private backoff; + constructor(asyncQueue: AsyncQueue, datastore: Datastore, options: TransactionOptions, updateFunction: (transaction: Transaction) => Promise, deferred: Deferred); + /** Runs the transaction and sets the result on deferred. */ + run(): void; + private runWithBackOff; + private tryRunUpdateFunction; + private handleTransactionError; + private isRetryableTransactionError; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/types.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/types.d.ts new file mode 100644 index 0000000..6c3b8ca --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/types.d.ts @@ -0,0 +1,65 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * BatchID is a locally assigned ID for a batch of mutations that have been + * applied. + */ +export type BatchId = number; +/** + * A locally-assigned ID used to refer to a target being watched via the + * Watch service. + */ +export type TargetId = number; +export type ListenSequenceNumber = number; +/** The different states of a mutation batch. */ +export type MutationBatchState = 'pending' | 'acknowledged' | 'rejected'; +/** + * Describes the online state of the Firestore client. Note that this does not + * indicate whether or not the remote store is trying to connect or not. This is + * primarily used by the View / EventManager code to change their behavior while + * offline (e.g. get() calls shouldn't wait for data from the server and + * snapshot events should set metadata.isFromCache=true). + * + * The string values should not be changed since they are persisted in + * WebStorage. + */ +export declare const enum OnlineState { + /** + * The Firestore client is in an unknown online state. This means the client + * is either not actively trying to establish a connection or it is currently + * trying to establish a connection, but it has not succeeded or failed yet. + * Higher-level components should not operate in offline mode. + */ + Unknown = "Unknown", + /** + * The client is connected and the connections are healthy. This state is + * reached after a successful connection and there has been at least one + * successful message received from the backends. + */ + Online = "Online", + /** + * The client is either trying to establish a connection but failing, or it + * has been explicitly marked offline via a call to disableNetwork(). + * Higher-level components should operate in offline mode. + */ + Offline = "Offline" +} +/** The source of an online state event. */ +export declare const enum OnlineStateSource { + RemoteStore = 0, + SharedClientState = 1 +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/version.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/version.d.ts new file mode 100644 index 0000000..9edc565 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/version.d.ts @@ -0,0 +1,18 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare let SDK_VERSION: string; +export declare function setSDKVersion(version: string): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/view.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/view.d.ts new file mode 100644 index 0000000..57680a5 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/view.d.ts @@ -0,0 +1,152 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { QueryResult } from '../local/local_store_impl'; +import { DocumentKeySet, DocumentMap } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { DocumentSet } from '../model/document_set'; +import { TargetChange } from '../remote/remote_event'; +import { Query } from './query'; +import { OnlineState } from './types'; +import { DocumentChangeSet, ViewSnapshot } from './view_snapshot'; +export type LimboDocumentChange = AddedLimboDocument | RemovedLimboDocument; +export declare class AddedLimboDocument { + key: DocumentKey; + constructor(key: DocumentKey); +} +export declare class RemovedLimboDocument { + key: DocumentKey; + constructor(key: DocumentKey); +} +/** The result of applying a set of doc changes to a view. */ +export interface ViewDocumentChanges { + /** The new set of docs that should be in the view. */ + documentSet: DocumentSet; + /** The diff of these docs with the previous set of docs. */ + changeSet: DocumentChangeSet; + /** + * Whether the set of documents passed in was not sufficient to calculate the + * new state of the view and there needs to be another pass based on the + * local cache. + */ + needsRefill: boolean; + mutatedKeys: DocumentKeySet; +} +export interface ViewChange { + snapshot?: ViewSnapshot; + limboChanges: LimboDocumentChange[]; +} +/** + * View is responsible for computing the final merged truth of what docs are in + * a query. It gets notified of local and remote changes to docs, and applies + * the query filters and limits to determine the most correct possible results. + */ +export declare class View { + private query; + /** Documents included in the remote target */ + private _syncedDocuments; + private syncState; + private hasCachedResults; + /** + * A flag whether the view is current with the backend. A view is considered + * current after it has seen the current flag from the backend and did not + * lose consistency within the watch stream (e.g. because of an existence + * filter mismatch). + */ + private current; + private documentSet; + /** Documents in the view but not in the remote target */ + private limboDocuments; + /** Document Keys that have local changes */ + private mutatedKeys; + /** Query comparator that defines the document order in this view. */ + private docComparator; + constructor(query: Query, + /** Documents included in the remote target */ + _syncedDocuments: DocumentKeySet); + /** + * The set of remote documents that the server has told us belongs to the target associated with + * this view. + */ + get syncedDocuments(): DocumentKeySet; + /** + * Iterates over a set of doc changes, applies the query limit, and computes + * what the new results should be, what the changes were, and whether we may + * need to go back to the local cache for more results. Does not make any + * changes to the view. + * @param docChanges - The doc changes to apply to this view. + * @param previousChanges - If this is being called with a refill, then start + * with this set of docs and changes instead of the current view. + * @returns a new set of docs, changes, and refill flag. + */ + computeDocChanges(docChanges: DocumentMap, previousChanges?: ViewDocumentChanges): ViewDocumentChanges; + private shouldWaitForSyncedDocument; + /** + * Updates the view with the given ViewDocumentChanges and optionally updates + * limbo docs and sync state from the provided target change. + * @param docChanges - The set of changes to make to the view's docs. + * @param limboResolutionEnabled - Whether to update limbo documents based on + * this change. + * @param targetChange - A target change to apply for computing limbo docs and + * sync state. + * @param targetIsPendingReset - Whether the target is pending to reset due to + * existence filter mismatch. If not explicitly specified, it is treated + * equivalently to `false`. + * @returns A new ViewChange with the given docs, changes, and sync state. + */ + applyChanges(docChanges: ViewDocumentChanges, limboResolutionEnabled: boolean, targetChange?: TargetChange, targetIsPendingReset?: boolean): ViewChange; + /** + * Applies an OnlineState change to the view, potentially generating a + * ViewChange if the view's syncState changes as a result. + */ + applyOnlineStateChange(onlineState: OnlineState): ViewChange; + /** + * Returns whether the doc for the given key should be in limbo. + */ + private shouldBeInLimbo; + /** + * Updates syncedDocuments, current, and limbo docs based on the given change. + * Returns the list of changes to which docs are in limbo. + */ + private applyTargetChange; + private updateLimboDocuments; + /** + * Update the in-memory state of the current view with the state read from + * persistence. + * + * We update the query view whenever a client's primary status changes: + * - When a client transitions from primary to secondary, it can miss + * LocalStorage updates and its query views may temporarily not be + * synchronized with the state on disk. + * - For secondary to primary transitions, the client needs to update the list + * of `syncedDocuments` since secondary clients update their query views + * based purely on synthesized RemoteEvents. + * + * @param queryResult.documents - The documents that match the query according + * to the LocalStore. + * @param queryResult.remoteKeys - The keys of the documents that match the + * query according to the backend. + * + * @returns The ViewChange that resulted from this synchronization. + */ + synchronizeWithPersistedState(queryResult: QueryResult): ViewChange; + /** + * Returns a view snapshot as if this query was just listened to. Contains + * a document add for every existing document and the `fromCache` and + * `hasPendingWrites` status of the already established view. + */ + computeInitialSnapshot(): ViewSnapshot; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/view_snapshot.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/view_snapshot.d.ts new file mode 100644 index 0000000..8b284df --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/core/view_snapshot.d.ts @@ -0,0 +1,59 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentKeySet } from '../model/collections'; +import { Document } from '../model/document'; +import { DocumentSet } from '../model/document_set'; +import { Query } from './query'; +export declare const enum ChangeType { + Added = 0, + Removed = 1, + Modified = 2, + Metadata = 3 +} +export interface DocumentViewChange { + type: ChangeType; + doc: Document; +} +export declare const enum SyncState { + Local = 0, + Synced = 1 +} +/** + * DocumentChangeSet keeps track of a set of changes to docs in a query, merging + * duplicate events for the same doc. + */ +export declare class DocumentChangeSet { + private changeMap; + track(change: DocumentViewChange): void; + getChanges(): DocumentViewChange[]; +} +export declare class ViewSnapshot { + readonly query: Query; + readonly docs: DocumentSet; + readonly oldDocs: DocumentSet; + readonly docChanges: DocumentViewChange[]; + readonly mutatedKeys: DocumentKeySet; + readonly fromCache: boolean; + readonly syncStateChanged: boolean; + readonly excludesMetadataChanges: boolean; + readonly hasCachedResults: boolean; + constructor(query: Query, docs: DocumentSet, oldDocs: DocumentSet, docChanges: DocumentViewChange[], mutatedKeys: DocumentKeySet, fromCache: boolean, syncStateChanged: boolean, excludesMetadataChanges: boolean, hasCachedResults: boolean); + /** Returns a view snapshot as if all documents in the snapshot were added. */ + static fromInitialDocuments(query: Query, documents: DocumentSet, mutatedKeys: DocumentKeySet, fromCache: boolean, hasCachedResults: boolean): ViewSnapshot; + get hasPendingWrites(): boolean; + isEqual(other: ViewSnapshot): boolean; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/global_index.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/global_index.d.ts new file mode 100644 index 0000000..0cecbff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/global_index.d.ts @@ -0,0 +1,10145 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +interface VersionService { + library: string; + version: string; +} +interface PlatformLoggerService { + getPlatformInfoString(): string; +} +interface HeartbeatService { + /** + * Called to report a heartbeat. The function will generate + * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it + * to IndexedDB. + * Note that we only store one heartbeat per day. So if a heartbeat for today is + * already logged, subsequent calls to this function in the same day will be ignored. + */ + triggerHeartbeat(): Promise; + /** + * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly. + * It also clears all heartbeats from memory as well as in IndexedDB. + */ + getHeartbeatsHeader(): Promise; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * A {@link @firebase/app#FirebaseApp} holds the initialization information for a collection of + * services. + * + * Do not call this constructor directly. Instead, use + * {@link (initializeApp:1) | initializeApp()} to create an app. + * + * @public + */ +interface FirebaseApp { + /** + * The (read-only) name for this app. + * + * The default app's name is `"[DEFAULT]"`. + * + * @example + * ```javascript + * // The default app's name is "[DEFAULT]" + * const app = initializeApp(defaultAppConfig); + * console.log(app.name); // "[DEFAULT]" + * ``` + * + * @example + * ```javascript + * // A named app's name is what you provide to initializeApp() + * const otherApp = initializeApp(otherAppConfig, "other"); + * console.log(otherApp.name); // "other" + * ``` + */ + readonly name: string; + /** + * The (read-only) configuration options for this app. These are the original + * parameters given in {@link (initializeApp:1) | initializeApp()}. + * + * @example + * ```javascript + * const app = initializeApp(config); + * console.log(app.options.databaseURL === config.databaseURL); // true + * ``` + */ + readonly options: FirebaseOptions; + /** + * The settable config flag for GDPR opt-in/opt-out + */ + automaticDataCollectionEnabled: boolean; +} +/** + * @public + * + * Firebase configuration object. Contains a set of parameters required by + * services in order to successfully communicate with Firebase server APIs + * and to associate client data with your Firebase project and + * Firebase application. Typically this object is populated by the Firebase + * console at project setup. See also: + * {@link https://firebase.google.com/docs/web/setup#config-object | Learn about the Firebase config object}. + */ +interface FirebaseOptions { + /** + * An encrypted string used when calling certain APIs that don't need to + * access private user data + * (example value: `AIzaSyDOCAbC123dEf456GhI789jKl012-MnO`). + */ + apiKey?: string; + /** + * Auth domain for the project ID. + */ + authDomain?: string; + /** + * Default Realtime Database URL. + */ + databaseURL?: string; + /** + * The unique identifier for the project across all of Firebase and + * Google Cloud. + */ + projectId?: string; + /** + * The default Cloud Storage bucket name. + */ + storageBucket?: string; + /** + * Unique numerical value used to identify each sender that can send + * Firebase Cloud Messaging messages to client apps. + */ + messagingSenderId?: string; + /** + * Unique identifier for the app. + */ + appId?: string; + /** + * An ID automatically created when you enable Analytics in your + * Firebase project and register a web app. In versions 7.20.0 + * and higher, this parameter is optional. + */ + measurementId?: string; +} +/** + * @internal + */ +interface _FirebaseService { + app: FirebaseApp; + /** + * Delete the service and free it's resources - called from + * {@link @firebase/app#deleteApp | deleteApp()} + */ + _delete(): Promise; +} +declare module '@firebase/component' { + interface NameServiceMapping { + 'app': FirebaseApp; + 'app-version': VersionService; + 'heartbeat': HeartbeatService; + 'platform-logger': PlatformLoggerService; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +type LogLevelString = 'debug' | 'verbose' | 'info' | 'warn' | 'error' | 'silent'; + +/** + * An object that can be injected into the environment as __FIREBASE_DEFAULTS__, + * either as a property of globalThis, a shell environment variable, or a + * cookie. + * + * This object can be used to automatically configure and initialize + * a Firebase app as well as any emulators. + * + * @public + */ +interface FirebaseDefaults { + config?: Record; + emulatorHosts?: Record; + _authTokenSyncURL?: string; + _authIdTokenMaxAge?: number; + /** + * Override Firebase's runtime environment detection and + * force the SDK to act as if it were in the specified environment. + */ + forceEnvironment?: 'browser' | 'node'; + [key: string]: unknown; +} +declare global { + var __FIREBASE_DEFAULTS__: FirebaseDefaults | undefined; +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +type FirebaseSignInProvider = 'custom' | 'email' | 'password' | 'phone' | 'anonymous' | 'google.com' | 'facebook.com' | 'github.com' | 'twitter.com' | 'microsoft.com' | 'apple.com'; +interface FirebaseIdToken { + iss: string; + aud: string; + sub: string; + iat: number; + exp: number; + user_id: string; + auth_time: number; + provider_id?: 'anonymous'; + email?: string; + email_verified?: boolean; + phone_number?: string; + name?: string; + picture?: string; + firebase: { + sign_in_provider: FirebaseSignInProvider; + identities?: { + [provider in FirebaseSignInProvider]?: string[]; + }; + }; + [claim: string]: unknown; + uid?: never; +} +type EmulatorMockTokenOptions = ({ + user_id: string; +} | { + sub: string; +}) & Partial; + +declare class FirebaseError extends Error { + /** The error code for this error. */ + readonly code: string; + /** Custom data for this error. */ + customData?: Record | undefined; + /** The custom name for all FirebaseErrors. */ + readonly name: string; + constructor( + /** The error code for this error. */ + code: string, message: string, + /** Custom data for this error. */ + customData?: Record | undefined); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Simple wrapper around a nullable UID. Mostly exists to make code more + * readable. + */ +declare class User { + readonly uid: string | null; + /** A user with a null UID. */ + static readonly UNAUTHENTICATED: User; + static readonly GOOGLE_CREDENTIALS: User; + static readonly FIRST_PARTY: User; + static readonly MOCK_USER: User; + constructor(uid: string | null); + isAuthenticated(): boolean; + /** + * Returns a key representing this user, suitable for inclusion in a + * dictionary. + */ + toKey(): string; + isEqual(otherUser: User): boolean; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +interface FirebaseAppCheckInternal { + // Get the current AttestationToken. Attaches to the most recent in-flight request if one + // is present. Returns null if no token is present and no token requests are in-flight. + getToken(forceRefresh?: boolean): Promise; + + // Always returns a fresh limited-use token suitable for Replay Protection. + // The returned token must be used and consumed as soon as possible. + getLimitedUseToken(): Promise; + + // Registers a listener to changes in the token state. There can be more than one listener + // registered at the same time for one or more FirebaseAppAttestation instances. The + // listeners call back on the UI thread whenever the current token associated with this + // FirebaseAppAttestation changes. + addTokenListener(listener: AppCheckTokenListener): void; + + // Unregisters a listener to changes in the token state. + removeTokenListener(listener: AppCheckTokenListener): void; +} + +type AppCheckTokenListener = (token: AppCheckTokenResult) => void; + +// If the error field is defined, the token field will be populated with a dummy token +interface AppCheckTokenResult { + readonly token: string; + readonly error?: Error; +} + +declare module '@firebase/component' { + interface NameServiceMapping { + 'app-check-internal': FirebaseAppCheckInternal; + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +interface FirebaseAuthTokenData { + accessToken: string; +} + +interface FirebaseAuthInternal { + getToken(refreshToken?: boolean): Promise; + getUid(): string | null; + addAuthTokenListener(fn: (token: string | null) => void): void; + removeAuthTokenListener(fn: (token: string | null) => void): void; +} + +declare module '@firebase/component' { + interface NameServiceMapping { + 'auth-internal': FirebaseAuthInternal; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * The set of Firestore status codes. The codes are the same at the ones + * exposed by gRPC here: + * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md + * + * Possible values: + * - 'cancelled': The operation was cancelled (typically by the caller). + * - 'unknown': Unknown error or an error from a different error domain. + * - 'invalid-argument': Client specified an invalid argument. Note that this + * differs from 'failed-precondition'. 'invalid-argument' indicates + * arguments that are problematic regardless of the state of the system + * (e.g. an invalid field name). + * - 'deadline-exceeded': Deadline expired before operation could complete. + * For operations that change the state of the system, this error may be + * returned even if the operation has completed successfully. For example, + * a successful response from a server could have been delayed long enough + * for the deadline to expire. + * - 'not-found': Some requested document was not found. + * - 'already-exists': Some document that we attempted to create already + * exists. + * - 'permission-denied': The caller does not have permission to execute the + * specified operation. + * - 'resource-exhausted': Some resource has been exhausted, perhaps a + * per-user quota, or perhaps the entire file system is out of space. + * - 'failed-precondition': Operation was rejected because the system is not + * in a state required for the operation's execution. + * - 'aborted': The operation was aborted, typically due to a concurrency + * issue like transaction aborts, etc. + * - 'out-of-range': Operation was attempted past the valid range. + * - 'unimplemented': Operation is not implemented or not supported/enabled. + * - 'internal': Internal errors. Means some invariants expected by + * underlying system has been broken. If you see one of these errors, + * something is very broken. + * - 'unavailable': The service is currently unavailable. This is most likely + * a transient condition and may be corrected by retrying with a backoff. + * - 'data-loss': Unrecoverable data loss or corruption. + * - 'unauthenticated': The request does not have valid authentication + * credentials for the operation. + */ +type FirestoreErrorCode$1 = 'cancelled' | 'unknown' | 'invalid-argument' | 'deadline-exceeded' | 'not-found' | 'already-exists' | 'permission-denied' | 'resource-exhausted' | 'failed-precondition' | 'aborted' | 'out-of-range' | 'unimplemented' | 'internal' | 'unavailable' | 'data-loss' | 'unauthenticated'; +/** An error returned by a Firestore operation. */ +declare class FirestoreError$1 extends FirebaseError { + /** + * The backend error code associated with this error. + */ + readonly code: FirestoreErrorCode$1; + /** + * A custom error description. + */ + readonly message: string; + /** The stack of the error. */ + readonly stack?: string; + /** @hideconstructor */ + constructor( + /** + * The backend error code associated with this error. + */ + code: FirestoreErrorCode$1, + /** + * A custom error description. + */ + message: string); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Wellknown "timer" IDs used when scheduling delayed operations on the + * AsyncQueue. These IDs can then be used from tests to check for the presence + * of operations or to run them early. + * + * The string values are used when encoding these timer IDs in JSON spec tests. + */ +declare const enum TimerId { + /** All can be used with runDelayedOperationsEarly() to run all timers. */ + All = "all", + /** + * The following 5 timers are used in persistent_stream.ts for the listen and + * write streams. The "Idle" timer is used to close the stream due to + * inactivity. The "ConnectionBackoff" timer is used to restart a stream once + * the appropriate backoff delay has elapsed. The health check is used to mark + * a stream healthy if it has not received an error during its initial setup. + */ + ListenStreamIdle = "listen_stream_idle", + ListenStreamConnectionBackoff = "listen_stream_connection_backoff", + WriteStreamIdle = "write_stream_idle", + WriteStreamConnectionBackoff = "write_stream_connection_backoff", + HealthCheckTimeout = "health_check_timeout", + /** + * A timer used in online_state_tracker.ts to transition from + * OnlineState.Unknown to Offline after a set timeout, rather than waiting + * indefinitely for success or failure. + */ + OnlineStateTimeout = "online_state_timeout", + /** + * A timer used to update the client metadata in IndexedDb, which is used + * to determine the primary leaseholder. + */ + ClientMetadataRefresh = "client_metadata_refresh", + /** A timer used to periodically attempt LRU Garbage collection */ + LruGarbageCollection = "lru_garbage_collection", + /** + * A timer used to retry transactions. Since there can be multiple concurrent + * transactions, multiple of these may be in the queue at a given time. + */ + TransactionRetry = "transaction_retry", + /** + * A timer used to retry operations scheduled via retryable AsyncQueue + * operations. + */ + AsyncQueueRetry = "async_queue_retry", + /** + * A timer used to periodically attempt index backfill. + */ + IndexBackfill = "index_backfill" +} +/** + * Represents an operation scheduled to be run in the future on an AsyncQueue. + * + * It is created via DelayedOperation.createAndSchedule(). + * + * Supports cancellation (via cancel()) and early execution (via skipDelay()). + * + * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type + * in newer versions of TypeScript defines `finally`, which is not available in + * IE. + */ +declare class DelayedOperation implements PromiseLike { + private readonly asyncQueue; + readonly timerId: TimerId; + readonly targetTimeMs: number; + private readonly op; + private readonly removalCallback; + private timerHandle; + private readonly deferred; + private constructor(); + get promise(): Promise; + /** + * Creates and returns a DelayedOperation that has been scheduled to be + * executed on the provided asyncQueue after the provided delayMs. + * + * @param asyncQueue - The queue to schedule the operation on. + * @param id - A Timer ID identifying the type of operation this is. + * @param delayMs - The delay (ms) before the operation should be scheduled. + * @param op - The operation to run. + * @param removalCallback - A callback to be called synchronously once the + * operation is executed or canceled, notifying the AsyncQueue to remove it + * from its delayedOperations list. + * PORTING NOTE: This exists to prevent making removeDelayedOperation() and + * the DelayedOperation class public. + */ + static createAndSchedule(asyncQueue: AsyncQueue, timerId: TimerId, delayMs: number, op: () => Promise, removalCallback: (op: DelayedOperation) => void): DelayedOperation; + /** + * Starts the timer. This is called immediately after construction by + * createAndSchedule(). + */ + private start; + /** + * Queues the operation to run immediately (if it hasn't already been run or + * canceled). + */ + skipDelay(): void; + /** + * Cancels the operation if it hasn't already been executed or canceled. The + * promise will be rejected. + * + * As long as the operation has not yet been run, calling cancel() provides a + * guarantee that the operation will not be run. + */ + cancel(reason?: string): void; + then: (onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined) => Promise; + private handleDelayElapsed; + private clearTimeout; +} +interface AsyncQueue { + readonly isShuttingDown: boolean; + /** + * Adds a new operation to the queue without waiting for it to complete (i.e. + * we ignore the Promise result). + */ + enqueueAndForget(op: () => Promise): void; + /** + * Regardless if the queue has initialized shutdown, adds a new operation to the + * queue without waiting for it to complete (i.e. we ignore the Promise result). + */ + enqueueAndForgetEvenWhileRestricted(op: () => Promise): void; + /** + * Initialize the shutdown of this queue. Once this method is called, the + * only possible way to request running an operation is through + * `enqueueEvenWhileRestricted()`. + * + * @param purgeExistingTasks Whether already enqueued tasked should be + * rejected (unless enqueued with `enqueueEvenWhileRestricted()`). Defaults + * to false. + */ + enterRestrictedMode(purgeExistingTasks?: boolean): void; + /** + * Adds a new operation to the queue. Returns a promise that will be resolved + * when the promise returned by the new operation is (with its value). + */ + enqueue(op: () => Promise): Promise; + /** + * Enqueue a retryable operation. + * + * A retryable operation is rescheduled with backoff if it fails with a + * IndexedDbTransactionError (the error type used by SimpleDb). All + * retryable operations are executed in order and only run if all prior + * operations were retried successfully. + */ + enqueueRetryable(op: () => Promise): void; + /** + * Schedules an operation to be queued on the AsyncQueue once the specified + * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel + * or fast-forward the operation prior to its running. + */ + enqueueAfterDelay(timerId: TimerId, delayMs: number, op: () => Promise): DelayedOperation; + /** + * Verifies there's an operation currently in-progress on the AsyncQueue. + * Unfortunately we can't verify that the running code is in the promise chain + * of that operation, so this isn't a foolproof check, but it should be enough + * to catch some bugs. + */ + verifyOperationInProgress(): void; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @internal + */ +type AuthTokenFactory = () => string; +/** + * @internal + */ +interface FirstPartyCredentialsSettings { + ['type']: 'firstParty'; + ['sessionIndex']: string; + ['iamToken']: string | null; + ['authTokenFactory']: AuthTokenFactory | null; +} +interface ProviderCredentialsSettings { + ['type']: 'provider'; + ['client']: CredentialsProvider; +} +/** Settings for private credentials */ +type CredentialsSettings = FirstPartyCredentialsSettings | ProviderCredentialsSettings; +type TokenType = 'OAuth' | 'FirstParty' | 'AppCheck'; +interface Token { + /** Type of token. */ + type: TokenType; + /** + * The user with which the token is associated (used for persisting user + * state on disk, etc.). + * This will be null for Tokens of the type 'AppCheck'. + */ + user?: User; + /** Header values to set for this token */ + headers: Map; +} +/** + * A Listener for credential change events. The listener should fetch a new + * token and may need to invalidate other state if the current user has also + * changed. + */ +type CredentialChangeListener = (credential: T) => Promise; +/** + * Provides methods for getting the uid and token for the current user and + * listening for changes. + */ +interface CredentialsProvider { + /** + * Starts the credentials provider and specifies a listener to be notified of + * credential changes (sign-in / sign-out, token changes). It is immediately + * called once with the initial user. + * + * The change listener is invoked on the provided AsyncQueue. + */ + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + /** Requests a token for the current user. */ + getToken(): Promise; + /** + * Marks the last retrieved token as invalid, making the next GetToken request + * force-refresh the token. + */ + invalidateToken(): void; + shutdown(): void; +} +/** + * A CredentialsProvider that always yields an empty token. + * @internal + */ +declare class EmptyAuthCredentialsProvider implements CredentialsProvider { + getToken(): Promise; + invalidateToken(): void; + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + shutdown(): void; +} +/** + * An AppCheck token provider that always yields an empty token. + * @internal + */ +declare class EmptyAppCheckTokenProvider implements CredentialsProvider { + getToken(): Promise; + invalidateToken(): void; + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + shutdown(): void; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options that configure the SDK’s underlying network transport (WebChannel) + * when long-polling is used. + * + * Note: This interface is "experimental" and is subject to change. + * + * See `FirestoreSettings.experimentalAutoDetectLongPolling`, + * `FirestoreSettings.experimentalForceLongPolling`, and + * `FirestoreSettings.experimentalLongPollingOptions`. + */ +interface ExperimentalLongPollingOptions { + /** + * The desired maximum timeout interval, in seconds, to complete a + * long-polling GET response. Valid values are between 5 and 30, inclusive. + * Floating point values are allowed and will be rounded to the nearest + * millisecond. + * + * By default, when long-polling is used the "hanging GET" request sent by + * the client times out after 30 seconds. To request a different timeout + * from the server, set this setting with the desired timeout. + * + * Changing the default timeout may be useful, for example, if the buffering + * proxy that necessitated enabling long-polling in the first place has a + * shorter timeout for hanging GET requests, in which case setting the + * long-polling timeout to a shorter value, such as 25 seconds, may fix + * prematurely-closed hanging GET requests. + * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987. + */ + timeoutSeconds?: number; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +declare class DatabaseInfo { + readonly databaseId: DatabaseId; + readonly appId: string; + readonly persistenceKey: string; + readonly host: string; + readonly ssl: boolean; + readonly forceLongPolling: boolean; + readonly autoDetectLongPolling: boolean; + readonly longPollingOptions: ExperimentalLongPollingOptions; + readonly useFetchStreams: boolean; + readonly isUsingEmulator: boolean; + /** + * Constructs a DatabaseInfo using the provided host, databaseId and + * persistenceKey. + * + * @param databaseId - The database to use. + * @param appId - The Firebase App Id. + * @param persistenceKey - A unique identifier for this Firestore's local + * storage (used in conjunction with the databaseId). + * @param host - The Firestore backend host to connect to. + * @param ssl - Whether to use SSL when connecting. + * @param forceLongPolling - Whether to use the forceLongPolling option + * when using WebChannel as the network transport. + * @param autoDetectLongPolling - Whether to use the detectBufferingProxy + * option when using WebChannel as the network transport. + * @param longPollingOptions Options that configure long-polling. + * @param useFetchStreams Whether to use the Fetch API instead of + * XMLHTTPRequest + */ + constructor(databaseId: DatabaseId, appId: string, persistenceKey: string, host: string, ssl: boolean, forceLongPolling: boolean, autoDetectLongPolling: boolean, longPollingOptions: ExperimentalLongPollingOptions, useFetchStreams: boolean, isUsingEmulator: boolean); +} +/** + * Represents the database ID a Firestore client is associated with. + * @internal + */ +declare class DatabaseId { + readonly projectId: string; + readonly database: string; + constructor(projectId: string, database?: string); + static empty(): DatabaseId; + get isDefaultDatabase(): boolean; + isEqual(other: {}): boolean; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * BatchID is a locally assigned ID for a batch of mutations that have been + * applied. + */ +type BatchId = number; +/** + * A locally-assigned ID used to refer to a target being watched via the + * Watch service. + */ +type TargetId = number; +type ListenSequenceNumber = number; +/** + * Describes the online state of the Firestore client. Note that this does not + * indicate whether or not the remote store is trying to connect or not. This is + * primarily used by the View / EventManager code to change their behavior while + * offline (e.g. get() calls shouldn't wait for data from the server and + * snapshot events should set metadata.isFromCache=true). + * + * The string values should not be changed since they are persisted in + * WebStorage. + */ +declare const enum OnlineState { + /** + * The Firestore client is in an unknown online state. This means the client + * is either not actively trying to establish a connection or it is currently + * trying to establish a connection, but it has not succeeded or failed yet. + * Higher-level components should not operate in offline mode. + */ + Unknown = "Unknown", + /** + * The client is connected and the connections are healthy. This state is + * reached after a successful connection and there has been at least one + * successful message received from the backends. + */ + Online = "Online", + /** + * The client is either trying to establish a connection but failing, or it + * has been explicitly marked offline via a call to disableNetwork(). + * Higher-level components should operate in offline mode. + */ + Offline = "Offline" +} + +/** + * Path represents an ordered sequence of string segments. + */ +declare abstract class BasePath> { + private segments; + private offset; + private len; + constructor(segments: string[], offset?: number, length?: number); + /** + * Abstract constructor method to construct an instance of B with the given + * parameters. + */ + protected abstract construct(segments: string[], offset?: number, length?: number): B; + /** + * Returns a String representation. + * + * Implementing classes are required to provide deterministic implementations as + * the String representation is used to obtain canonical Query IDs. + */ + abstract toString(): string; + get length(): number; + isEqual(other: B): boolean; + child(nameOrPath: string | B): B; + /** The index of one past the last segment of the path. */ + private limit; + popFirst(size?: number): B; + popLast(): B; + firstSegment(): string; + lastSegment(): string; + get(index: number): string; + isEmpty(): boolean; + isPrefixOf(other: this): boolean; + isImmediateParentOf(potentialChild: this): boolean; + forEach(fn: (segment: string) => void): void; + toArray(): string[]; + /** + * Compare 2 paths segment by segment, prioritizing numeric IDs + * (e.g., "__id123__") in numeric ascending order, followed by string + * segments in lexicographical order. + */ + static comparator>(p1: BasePath, p2: BasePath): number; + private static compareSegments; + private static isNumericId; + private static extractNumericId; +} +/** + * A slash-separated path for navigating resources (documents and collections) + * within Firestore. + * + * @internal + */ +declare class ResourcePath extends BasePath { + protected construct(segments: string[], offset?: number, length?: number): ResourcePath; + canonicalString(): string; + toString(): string; + /** + * Returns a string representation of this path + * where each path segment has been encoded with + * `encodeURIComponent`. + */ + toUriEncodedString(): string; + /** + * Creates a resource path from the given slash-delimited string. If multiple + * arguments are provided, all components are combined. Leading and trailing + * slashes from all components are ignored. + */ + static fromString(...pathComponents: string[]): ResourcePath; + static emptyPath(): ResourcePath; +} +/** + * A dot-separated path for navigating sub-objects within a document. + * @internal + */ +declare class FieldPath$2 extends BasePath { + protected construct(segments: string[], offset?: number, length?: number): FieldPath$2; + /** + * Returns true if the string could be used as a segment in a field path + * without escaping. + */ + private static isValidIdentifier; + canonicalString(): string; + toString(): string; + /** + * Returns true if this field references the key of a document. + */ + isKeyField(): boolean; + /** + * The field designating the key of a document. + */ + static keyField(): FieldPath$2; + /** + * Parses a field string from the given server-formatted string. + * + * - Splitting the empty string is not allowed (for now at least). + * - Empty segments within the string (e.g. if there are two consecutive + * separators) are not allowed. + * + * TODO(b/37244157): we should make this more strict. Right now, it allows + * non-identifier path components, even if they aren't escaped. + */ + static fromServerFormat(path: string): FieldPath$2; + static emptyPath(): FieldPath$2; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Union type representing the aggregate type to be performed. + */ +type AggregateType = 'count' | 'avg' | 'sum'; + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A list of data types Firestore objects may serialize in their toJSON implemenetations. + * @private + * @internal + */ +type JsonTypeDesc = 'object' | 'string' | 'number' | 'boolean' | 'null' | 'undefined'; +/** + * An association of JsonTypeDesc values to their native types. + * @private + * @internal + */ +type TSType = T extends 'object' ? object : T extends 'string' ? string : T extends 'number' ? number : T extends 'boolean' ? boolean : T extends 'null' ? null : T extends 'undefined' ? undefined : never; +/** + * The representation of a JSON object property name and its type value. + * @private + * @internal + */ +interface Property { + value?: TSType; + typeString: JsonTypeDesc; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * A `Timestamp` represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. + * + * It is encoded using the Proleptic Gregorian Calendar which extends the + * Gregorian calendar backwards to year one. It is encoded assuming all minutes + * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59.999999999Z. + * + * For examples and further specifications, refer to the + * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. + */ +declare class Timestamp$1 { + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + readonly seconds: number; + /** + * The fractions of a second at nanosecond resolution.* + */ + readonly nanoseconds: number; + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns a new timestamp representing the current date. + */ + static now(): Timestamp$1; + /** + * Creates a new timestamp from the given date. + * + * @param date - The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the given + * date. + */ + static fromDate(date: Date): Timestamp$1; + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds - Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the given + * number of milliseconds. + */ + static fromMillis(milliseconds: number): Timestamp$1; + /** + * Creates a new timestamp. + * + * @param seconds - The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds - The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ + constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + seconds: number, + /** + * The fractions of a second at nanosecond resolution.* + */ + nanoseconds: number); + /** + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ + toDate(): Date; + /** + * Converts a `Timestamp` to a numeric timestamp (in milliseconds since + * epoch). This operation causes a loss of precision. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ + toMillis(): number; + _compareTo(other: Timestamp$1): number; + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other - The `Timestamp` to compare against. + * @returns true if this `Timestamp` is equal to the provided one. + */ + isEqual(other: Timestamp$1): boolean; + /** Returns a textual representation of this `Timestamp`. */ + toString(): string; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + seconds: Property<"number">; + nanoseconds: Property<"number">; + }; + /** + * Returns a JSON-serializable representation of this `Timestamp`. + */ + toJSON(): { + seconds: number; + nanoseconds: number; + type: string; + }; + /** + * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}. + */ + static fromJSON(json: object): Timestamp$1; + /** + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. + */ + valueOf(): string; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * A version of a document in Firestore. This corresponds to the version + * timestamp, such as update_time or read_time. + */ +declare class SnapshotVersion { + private timestamp; + static fromTimestamp(value: Timestamp$1): SnapshotVersion; + static min(): SnapshotVersion; + static max(): SnapshotVersion; + private constructor(); + compareTo(other: SnapshotVersion): number; + isEqual(other: SnapshotVersion): boolean; + /** Returns a number representation of the version for use in spec tests. */ + toMicroseconds(): number; + toString(): string; + toTimestamp(): Timestamp$1; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @internal + */ +declare class DocumentKey { + readonly path: ResourcePath; + constructor(path: ResourcePath); + static fromPath(path: string): DocumentKey; + static fromName(name: string): DocumentKey; + static empty(): DocumentKey; + get collectionGroup(): string; + /** Returns true if the document is in the specified collectionId. */ + hasCollectionId(collectionId: string): boolean; + /** Returns the collection group (i.e. the name of the parent collection) for this key. */ + getCollectionGroup(): string; + /** Returns the fully qualified path to the parent collection. */ + getCollectionPath(): ResourcePath; + isEqual(other: DocumentKey | null): boolean; + toString(): string; + static comparator(k1: DocumentKey, k2: DocumentKey): number; + static isDocumentKey(path: ResourcePath): boolean; + /** + * Creates and returns a new document key with the given segments. + * + * @param segments - The segments of the path to the document + * @returns A new instance of DocumentKey + */ + static fromSegments(segments: string[]): DocumentKey; +} + +interface ApiClientObjectMap { + [k: string]: T; +} +declare type Timestamp = string | { + seconds?: string | number; + nanos?: number; +}; +declare type CompositeFilterOp = 'OPERATOR_UNSPECIFIED' | 'AND' | 'OR'; +declare type FieldFilterOp = 'OPERATOR_UNSPECIFIED' | 'LESS_THAN' | 'LESS_THAN_OR_EQUAL' | 'GREATER_THAN' | 'GREATER_THAN_OR_EQUAL' | 'EQUAL' | 'NOT_EQUAL' | 'ARRAY_CONTAINS' | 'IN' | 'ARRAY_CONTAINS_ANY' | 'NOT_IN'; +declare type FieldTransformSetToServerValue = 'SERVER_VALUE_UNSPECIFIED' | 'REQUEST_TIME'; +declare type IndexFieldMode = 'MODE_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING'; +declare type IndexState$1 = 'STATE_UNSPECIFIED' | 'CREATING' | 'READY' | 'ERROR'; +declare type OrderDirection = 'DIRECTION_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING'; +declare type TargetChangeTargetChangeType = 'NO_CHANGE' | 'ADD' | 'REMOVE' | 'CURRENT' | 'RESET'; +declare type UnaryFilterOp = 'OPERATOR_UNSPECIFIED' | 'IS_NAN' | 'IS_NULL' | 'IS_NOT_NAN' | 'IS_NOT_NULL'; +declare type ValueNullValue = 'NULL_VALUE'; +declare namespace firestoreV1ApiClientInterfaces { + interface ArrayValue { + values?: Value[]; + } + interface BatchGetDocumentsRequest { + database?: string; + documents?: string[]; + mask?: DocumentMask; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface BatchGetDocumentsResponse { + found?: Document; + missing?: string; + transaction?: string; + readTime?: string; + } + interface BeginTransactionRequest { + options?: TransactionOptions; + } + interface BeginTransactionResponse { + transaction?: string; + } + interface CollectionSelector { + collectionId?: string; + allDescendants?: boolean; + } + interface CommitRequest { + database?: string; + writes?: Write[]; + transaction?: string; + } + interface CommitResponse { + writeResults?: WriteResult[]; + commitTime?: string; + } + interface CompositeFilter { + op?: CompositeFilterOp; + filters?: Filter[]; + } + interface Cursor { + values?: Value[]; + before?: boolean; + } + interface Document { + name?: string; + fields?: ApiClientObjectMap; + createTime?: Timestamp; + updateTime?: Timestamp; + } + interface DocumentChange { + document?: Document; + targetIds?: number[]; + removedTargetIds?: number[]; + } + interface DocumentDelete { + document?: string; + removedTargetIds?: number[]; + readTime?: Timestamp; + } + interface DocumentMask { + fieldPaths?: string[]; + } + interface DocumentRemove { + document?: string; + removedTargetIds?: number[]; + readTime?: string; + } + interface DocumentTransform { + document?: string; + fieldTransforms?: FieldTransform[]; + } + interface DocumentsTarget { + documents?: string[]; + } + interface Empty { + } + interface ExistenceFilter { + targetId?: number; + count?: number; + unchangedNames?: BloomFilter; + } + interface BloomFilter { + bits?: BitSequence; + hashCount?: number; + } + interface BitSequence { + bitmap?: string | Uint8Array; + padding?: number; + } + interface FieldFilter { + field?: FieldReference; + op?: FieldFilterOp; + value?: Value; + } + interface FieldReference { + fieldPath?: string; + } + interface FieldTransform { + fieldPath?: string; + setToServerValue?: FieldTransformSetToServerValue; + appendMissingElements?: ArrayValue; + removeAllFromArray?: ArrayValue; + increment?: Value; + } + interface Filter { + compositeFilter?: CompositeFilter; + fieldFilter?: FieldFilter; + unaryFilter?: UnaryFilter; + } + interface Index { + name?: string; + collectionId?: string; + fields?: IndexField[]; + state?: IndexState$1; + } + interface IndexField { + fieldPath?: string; + mode?: IndexFieldMode; + } + interface LatLng { + latitude?: number; + longitude?: number; + } + interface ListCollectionIdsRequest { + pageSize?: number; + pageToken?: string; + } + interface ListCollectionIdsResponse { + collectionIds?: string[]; + nextPageToken?: string; + } + interface ListDocumentsResponse { + documents?: Document[]; + nextPageToken?: string; + } + interface ListIndexesResponse { + indexes?: Index[]; + nextPageToken?: string; + } + interface ListenRequest { + addTarget?: Target; + removeTarget?: number; + labels?: ApiClientObjectMap; + } + interface ListenResponse { + targetChange?: TargetChange; + documentChange?: DocumentChange; + documentDelete?: DocumentDelete; + documentRemove?: DocumentRemove; + filter?: ExistenceFilter; + } + interface MapValue { + fields?: ApiClientObjectMap; + } + interface Operation { + name?: string; + metadata?: ApiClientObjectMap; + done?: boolean; + error?: Status; + response?: ApiClientObjectMap; + } + interface Order { + field?: FieldReference; + direction?: OrderDirection; + } + interface Precondition { + exists?: boolean; + updateTime?: Timestamp; + } + interface Projection { + fields?: FieldReference[]; + } + interface QueryTarget { + parent?: string; + structuredQuery?: StructuredQuery; + } + interface ReadOnly { + readTime?: string; + } + interface ReadWrite { + retryTransaction?: string; + } + interface RollbackRequest { + transaction?: string; + } + interface RunQueryRequest { + parent?: string; + structuredQuery?: StructuredQuery; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface RunQueryResponse { + transaction?: string; + document?: Document; + readTime?: string; + skippedResults?: number; + } + interface RunAggregationQueryRequest { + parent?: string; + structuredAggregationQuery?: StructuredAggregationQuery; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface RunAggregationQueryResponse { + result?: AggregationResult; + transaction?: string; + readTime?: string; + } + interface AggregationResult { + aggregateFields?: ApiClientObjectMap; + } + interface StructuredAggregationQuery { + structuredQuery?: StructuredQuery; + aggregations?: Aggregation[]; + } + interface Aggregation { + count?: Count; + sum?: Sum; + avg?: Avg; + alias?: string; + } + interface Count { + upTo?: number; + } + interface Sum { + field?: FieldReference; + } + interface Avg { + field?: FieldReference; + } + interface Status { + code?: number; + message?: string; + details?: Array>; + } + interface StructuredQuery { + select?: Projection; + from?: CollectionSelector[]; + where?: Filter; + orderBy?: Order[]; + startAt?: Cursor; + endAt?: Cursor; + offset?: number; + limit?: number | { + value: number; + }; + } + interface Target { + query?: QueryTarget; + documents?: DocumentsTarget; + resumeToken?: string | Uint8Array; + readTime?: Timestamp; + targetId?: number; + once?: boolean; + expectedCount?: number | { + value: number; + }; + } + interface TargetChange { + targetChangeType?: TargetChangeTargetChangeType; + targetIds?: number[]; + cause?: Status; + resumeToken?: string | Uint8Array; + readTime?: Timestamp; + } + interface TransactionOptions { + readOnly?: ReadOnly; + readWrite?: ReadWrite; + } + interface UnaryFilter { + op?: UnaryFilterOp; + field?: FieldReference; + } + interface Value { + nullValue?: ValueNullValue; + booleanValue?: boolean; + integerValue?: string | number; + doubleValue?: string | number; + timestampValue?: Timestamp; + stringValue?: string; + bytesValue?: string | Uint8Array; + referenceValue?: string; + geoPointValue?: LatLng; + arrayValue?: ArrayValue; + mapValue?: MapValue; + } + interface Write { + update?: Document; + delete?: string; + verify?: string; + transform?: DocumentTransform; + updateMask?: DocumentMask; + updateTransforms?: FieldTransform[]; + currentDocument?: Precondition; + } + interface WriteRequest { + streamId?: string; + writes?: Write[]; + streamToken?: string | Uint8Array; + labels?: ApiClientObjectMap; + } + interface WriteResponse { + streamId?: string; + streamToken?: string | Uint8Array; + writeResults?: WriteResult[]; + commitTime?: Timestamp; + } + interface WriteResult { + updateTime?: Timestamp; + transformResults?: Value[]; + } +} +declare type MapValue = firestoreV1ApiClientInterfaces.MapValue; +declare type StructuredQuery = firestoreV1ApiClientInterfaces.StructuredQuery; +declare type Value = firestoreV1ApiClientInterfaces.Value; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Provides a set of fields that can be used to partially patch a document. + * FieldMask is used in conjunction with ObjectValue. + * Examples: + * foo - Overwrites foo entirely with the provided value. If foo is not + * present in the companion ObjectValue, the field is deleted. + * foo.bar - Overwrites only the field bar of the object foo. + * If foo is not an object, foo is replaced with an object + * containing foo + */ +declare class FieldMask { + readonly fields: FieldPath$2[]; + constructor(fields: FieldPath$2[]); + static empty(): FieldMask; + /** + * Returns a new FieldMask object that is the result of adding all the given + * fields paths to this field mask. + */ + unionWith(extraFields: FieldPath$2[]): FieldMask; + /** + * Verifies that `fieldPath` is included by at least one field in this field + * mask. + * + * This is an O(n) operation, where `n` is the size of the field mask. + */ + covers(fieldPath: FieldPath$2): boolean; + isEqual(other: FieldMask): boolean; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * An ObjectValue represents a MapValue in the Firestore Proto and offers the + * ability to add and remove fields (via the ObjectValueBuilder). + */ +declare class ObjectValue { + readonly value: { + mapValue: MapValue; + }; + constructor(value: { + mapValue: MapValue; + }); + static empty(): ObjectValue; + /** + * Returns the value at the given path or null. + * + * @param path - the path to search + * @returns The value at the path or null if the path is not set. + */ + field(path: FieldPath$2): Value | null; + /** + * Sets the field to the provided value. + * + * @param path - The field path to set. + * @param value - The value to set. + */ + set(path: FieldPath$2, value: Value): void; + /** + * Sets the provided fields to the provided values. + * + * @param data - A map of fields to values (or null for deletes). + */ + setAll(data: Map): void; + /** + * Removes the field at the specified path. If there is no field at the + * specified path, nothing is changed. + * + * @param path - The field path to remove. + */ + delete(path: FieldPath$2): void; + isEqual(other: ObjectValue): boolean; + /** + * Returns the map that contains the leaf element of `path`. If the parent + * entry does not yet exist, or if it is not a map, a new map will be created. + */ + private getFieldsMap; + /** + * Modifies `fieldsMap` by adding, replacing or deleting the specified + * entries. + */ + private applyChanges; + clone(): ObjectValue; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Represents a document in Firestore with a key, version, data and whether the + * data has local mutations applied to it. + */ +interface Document { + /** The key for this document */ + readonly key: DocumentKey; + /** + * The version of this document if it exists or a version at which this + * document was guaranteed to not exist. + */ + readonly version: SnapshotVersion; + /** + * The timestamp at which this document was read from the remote server. Uses + * `SnapshotVersion.min()` for documents created by the user. + */ + readonly readTime: SnapshotVersion; + /** + * The timestamp at which the document was created. This value increases + * monotonically when a document is deleted then recreated. It can also be + * compared to `createTime` of other documents and the `readTime` of a query. + */ + readonly createTime: SnapshotVersion; + /** The underlying data of this document or an empty value if no data exists. */ + readonly data: ObjectValue; + /** Returns whether local mutations were applied via the mutation queue. */ + readonly hasLocalMutations: boolean; + /** Returns whether mutations were applied based on a write acknowledgment. */ + readonly hasCommittedMutations: boolean; + /** + * Whether this document had a local mutation applied that has not yet been + * acknowledged by Watch. + */ + readonly hasPendingWrites: boolean; + /** + * Returns whether this document is valid (i.e. it is an entry in the + * RemoteDocumentCache, was created by a mutation or read from the backend). + */ + isValidDocument(): boolean; + /** + * Returns whether the document exists and its data is known at the current + * version. + */ + isFoundDocument(): boolean; + /** + * Returns whether the document is known to not exist at the current version. + */ + isNoDocument(): boolean; + /** + * Returns whether the document exists and its data is unknown at the current + * version. + */ + isUnknownDocument(): boolean; + isEqual(other: Document | null | undefined): boolean; + /** Creates a mutable copy of this document. */ + mutableCopy(): MutableDocument; + toString(): string; +} +/** + * Represents a document in Firestore with a key, version, data and whether it + * has local mutations applied to it. + * + * Documents can transition between states via `convertToFoundDocument()`, + * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does + * not transition to one of these states even after all mutations have been + * applied, `isValidDocument()` returns false and the document should be removed + * from all views. + */ +declare class MutableDocument implements Document { + readonly key: DocumentKey; + private documentType; + version: SnapshotVersion; + readTime: SnapshotVersion; + createTime: SnapshotVersion; + data: ObjectValue; + private documentState; + private constructor(); + /** + * Creates a document with no known version or data, but which can serve as + * base document for mutations. + */ + static newInvalidDocument(documentKey: DocumentKey): MutableDocument; + /** + * Creates a new document that is known to exist with the given data at the + * given version. + */ + static newFoundDocument(documentKey: DocumentKey, version: SnapshotVersion, createTime: SnapshotVersion, value: ObjectValue): MutableDocument; + /** Creates a new document that is known to not exist at the given version. */ + static newNoDocument(documentKey: DocumentKey, version: SnapshotVersion): MutableDocument; + /** + * Creates a new document that is known to exist at the given version but + * whose data is not known (e.g. a document that was updated without a known + * base document). + */ + static newUnknownDocument(documentKey: DocumentKey, version: SnapshotVersion): MutableDocument; + /** + * Changes the document type to indicate that it exists and that its version + * and data are known. + */ + convertToFoundDocument(version: SnapshotVersion, value: ObjectValue): MutableDocument; + /** + * Changes the document type to indicate that it doesn't exist at the given + * version. + */ + convertToNoDocument(version: SnapshotVersion): MutableDocument; + /** + * Changes the document type to indicate that it exists at a given version but + * that its data is not known (e.g. a document that was updated without a known + * base document). + */ + convertToUnknownDocument(version: SnapshotVersion): MutableDocument; + setHasCommittedMutations(): MutableDocument; + setHasLocalMutations(): MutableDocument; + setReadTime(readTime: SnapshotVersion): MutableDocument; + get hasLocalMutations(): boolean; + get hasCommittedMutations(): boolean; + get hasPendingWrites(): boolean; + isValidDocument(): boolean; + isFoundDocument(): boolean; + isNoDocument(): boolean; + isUnknownDocument(): boolean; + isEqual(other: Document | null | undefined): boolean; + mutableCopy(): MutableDocument; + toString(): string; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +declare const enum Operator { + LESS_THAN = "<", + LESS_THAN_OR_EQUAL = "<=", + EQUAL = "==", + NOT_EQUAL = "!=", + GREATER_THAN = ">", + GREATER_THAN_OR_EQUAL = ">=", + ARRAY_CONTAINS = "array-contains", + IN = "in", + NOT_IN = "not-in", + ARRAY_CONTAINS_ANY = "array-contains-any" +} +declare const enum CompositeOperator { + OR = "or", + AND = "and" +} +declare abstract class Filter { + abstract matches(doc: Document): boolean; + abstract getFlattenedFilters(): readonly FieldFilter[]; + abstract getFilters(): Filter[]; +} +declare class FieldFilter extends Filter { + readonly field: FieldPath$2; + readonly op: Operator; + readonly value: Value; + protected constructor(field: FieldPath$2, op: Operator, value: Value); + /** + * Creates a filter based on the provided arguments. + */ + static create(field: FieldPath$2, op: Operator, value: Value): FieldFilter; + private static createKeyFieldInFilter; + matches(doc: Document): boolean; + protected matchesComparison(comparison: number): boolean; + isInequality(): boolean; + getFlattenedFilters(): readonly FieldFilter[]; + getFilters(): Filter[]; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * The direction of sorting in an order by. + */ +declare const enum Direction { + ASCENDING = "asc", + DESCENDING = "desc" +} +/** + * An ordering on a field, in some Direction. Direction defaults to ASCENDING. + */ +declare class OrderBy { + readonly field: FieldPath$2; + readonly dir: Direction; + constructor(field: FieldPath$2, dir?: Direction); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +type Comparator = (key1: K, key2: K) => number; +interface Entry { + key: K; + value: V; +} +declare class SortedMap { + comparator: Comparator; + root: LLRBNode | LLRBEmptyNode; + constructor(comparator: Comparator, root?: LLRBNode | LLRBEmptyNode); + insert(key: K, value: V): SortedMap; + remove(key: K): SortedMap; + get(key: K): V | null; + indexOf(key: K): number; + isEmpty(): boolean; + get size(): number; + minKey(): K | null; + maxKey(): K | null; + inorderTraversal(action: (k: K, v: V) => T): T; + forEach(fn: (k: K, v: V) => void): void; + toString(): string; + reverseTraversal(action: (k: K, v: V) => T): T; + getIterator(): SortedMapIterator; + getIteratorFrom(key: K): SortedMapIterator; + getReverseIterator(): SortedMapIterator; + getReverseIteratorFrom(key: K): SortedMapIterator; +} +declare class SortedMapIterator { + private isReverse; + private nodeStack; + constructor(node: LLRBNode | LLRBEmptyNode, startKey: K | null, comparator: Comparator, isReverse: boolean); + getNext(): Entry; + hasNext(): boolean; + peek(): Entry | null; +} +declare class LLRBNode { + key: K; + value: V; + readonly color: boolean; + readonly left: LLRBNode | LLRBEmptyNode; + readonly right: LLRBNode | LLRBEmptyNode; + readonly size: number; + static EMPTY: LLRBEmptyNode; + static RED: boolean; + static BLACK: boolean; + constructor(key: K, value: V, color?: boolean, left?: LLRBNode | LLRBEmptyNode, right?: LLRBNode | LLRBEmptyNode); + copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode | LLRBEmptyNode | null, right: LLRBNode | LLRBEmptyNode | null): LLRBNode; + isEmpty(): boolean; + inorderTraversal(action: (k: K, v: V) => T): T; + reverseTraversal(action: (k: K, v: V) => T): T; + private min; + minKey(): K | null; + maxKey(): K | null; + insert(key: K, value: V, comparator: Comparator): LLRBNode; + private removeMin; + remove(key: K, comparator: Comparator): LLRBNode | LLRBEmptyNode; + isRed(): boolean; + private fixUp; + private moveRedLeft; + private moveRedRight; + private rotateLeft; + private rotateRight; + private colorFlip; + checkMaxDepth(): boolean; + protected check(): number; +} +declare class LLRBEmptyNode { + get key(): never; + get value(): never; + get color(): never; + get left(): never; + get right(): never; + size: number; + copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode | LLRBEmptyNode | null, right: LLRBNode | LLRBEmptyNode | null): LLRBEmptyNode; + insert(key: K, value: V, comparator: Comparator): LLRBNode; + remove(key: K, comparator: Comparator): LLRBEmptyNode; + isEmpty(): boolean; + inorderTraversal(action: (k: K, v: V) => boolean): boolean; + reverseTraversal(action: (k: K, v: V) => boolean): boolean; + minKey(): K | null; + maxKey(): K | null; + isRed(): boolean; + checkMaxDepth(): boolean; + protected check(): 0; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * SortedSet is an immutable (copy-on-write) collection that holds elements + * in order specified by the provided comparator. + * + * NOTE: if provided comparator returns 0 for two elements, we consider them to + * be equal! + */ +declare class SortedSet { + private comparator; + private data; + constructor(comparator: (left: T, right: T) => number); + has(elem: T): boolean; + first(): T | null; + last(): T | null; + get size(): number; + indexOf(elem: T): number; + /** Iterates elements in order defined by "comparator" */ + forEach(cb: (elem: T) => void): void; + /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ + forEachInRange(range: [T, T], cb: (elem: T) => void): void; + /** + * Iterates over `elem`s such that: start <= elem until false is returned. + */ + forEachWhile(cb: (elem: T) => boolean, start?: T): void; + /** Finds the least element greater than or equal to `elem`. */ + firstAfterOrEqual(elem: T): T | null; + getIterator(): SortedSetIterator; + getIteratorFrom(key: T): SortedSetIterator; + /** Inserts or updates an element */ + add(elem: T): SortedSet; + /** Deletes an element */ + delete(elem: T): SortedSet; + isEmpty(): boolean; + unionWith(other: SortedSet): SortedSet; + isEqual(other: SortedSet): boolean; + toArray(): T[]; + toString(): string; + private copy; +} +declare class SortedSetIterator { + private iter; + constructor(iter: SortedMapIterator); + getNext(): T; + hasNext(): boolean; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Represents a bound of a query. + * + * The bound is specified with the given components representing a position and + * whether it's just before or just after the position (relative to whatever the + * query order is). + * + * The position represents a logical index position for a query. It's a prefix + * of values for the (potentially implicit) order by clauses of a query. + * + * Bound provides a function to determine whether a document comes before or + * after a bound. This is influenced by whether the position is just before or + * just after the provided values. + */ +declare class Bound { + readonly position: Value[]; + readonly inclusive: boolean; + constructor(position: Value[], inclusive: boolean); +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * An index definition for field indexes in Firestore. + * + * Every index is associated with a collection. The definition contains a list + * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or + * `CONTAINS` for ArrayContains/ArrayContainsAny queries). + * + * Unlike the backend, the SDK does not differentiate between collection or + * collection group-scoped indices. Every index can be used for both single + * collection and collection group queries. + */ +declare class FieldIndex { + /** + * The index ID. Returns -1 if the index ID is not available (e.g. the index + * has not yet been persisted). + */ + readonly indexId: number; + /** The collection ID this index applies to. */ + readonly collectionGroup: string; + /** The field segments for this index. */ + readonly fields: IndexSegment[]; + /** Shows how up-to-date the index is for the current user. */ + readonly indexState: IndexState; + /** An ID for an index that has not yet been added to persistence. */ + static UNKNOWN_ID: number; + constructor( + /** + * The index ID. Returns -1 if the index ID is not available (e.g. the index + * has not yet been persisted). + */ + indexId: number, + /** The collection ID this index applies to. */ + collectionGroup: string, + /** The field segments for this index. */ + fields: IndexSegment[], + /** Shows how up-to-date the index is for the current user. */ + indexState: IndexState); +} +/** The type of the index, e.g. for which type of query it can be used. */ +declare const enum IndexKind { + /** + * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries. + */ + ASCENDING = 0, + /** + * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries. + */ + DESCENDING = 1, + /** Contains index. Can be used for ArrayContains and ArrayContainsAny. */ + CONTAINS = 2 +} +/** An index component consisting of field path and index type. */ +declare class IndexSegment { + /** The field path of the component. */ + readonly fieldPath: FieldPath$2; + /** The fields sorting order. */ + readonly kind: IndexKind; + constructor( + /** The field path of the component. */ + fieldPath: FieldPath$2, + /** The fields sorting order. */ + kind: IndexKind); +} +/** + * Stores the "high water mark" that indicates how updated the Index is for the + * current user. + */ +declare class IndexState { + /** + * Indicates when the index was last updated (relative to other indexes). + */ + readonly sequenceNumber: number; + /** The the latest indexed read time, document and batch id. */ + readonly offset: IndexOffset; + constructor( + /** + * Indicates when the index was last updated (relative to other indexes). + */ + sequenceNumber: number, + /** The the latest indexed read time, document and batch id. */ + offset: IndexOffset); + /** The state of an index that has not yet been backfilled. */ + static empty(): IndexState; +} +/** + * Stores the latest read time, document and batch ID that were processed for an + * index. + */ +declare class IndexOffset { + /** + * The latest read time version that has been indexed by Firestore for this + * field index. + */ + readonly readTime: SnapshotVersion; + /** + * The key of the last document that was indexed for this query. Use + * `DocumentKey.empty()` if no document has been indexed. + */ + readonly documentKey: DocumentKey; + readonly largestBatchId: number; + constructor( + /** + * The latest read time version that has been indexed by Firestore for this + * field index. + */ + readTime: SnapshotVersion, + /** + * The key of the last document that was indexed for this query. Use + * `DocumentKey.empty()` if no document has been indexed. + */ + documentKey: DocumentKey, largestBatchId: number); + /** Returns an offset that sorts before all regular offsets. */ + static min(): IndexOffset; + /** Returns an offset that sorts after all regular offsets. */ + static max(): IndexOffset; +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * A Target represents the WatchTarget representation of a Query, which is used + * by the LocalStore and the RemoteStore to keep track of and to execute + * backend queries. While a Query can represent multiple Targets, each Targets + * maps to a single WatchTarget in RemoteStore and a single TargetData entry + * in persistence. + */ +interface Target { + readonly path: ResourcePath; + readonly collectionGroup: string | null; + readonly orderBy: OrderBy[]; + readonly filters: Filter[]; + readonly limit: number | null; + readonly startAt: Bound | null; + readonly endAt: Bound | null; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +declare const enum LimitType$1 { + First = "F", + Last = "L" +} +/** + * The Query interface defines all external properties of a query. + * + * QueryImpl implements this interface to provide memoization for `queryNormalizedOrderBy` + * and `queryToTarget`. + */ +interface Query$2 { + readonly path: ResourcePath; + readonly collectionGroup: string | null; + readonly explicitOrderBy: OrderBy[]; + readonly filters: Filter[]; + readonly limit: number | null; + readonly limitType: LimitType$1; + readonly startAt: Bound | null; + readonly endAt: Bound | null; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Immutable class that represents a "proto" byte string. + * + * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when + * sent on the wire. This class abstracts away this differentiation by holding + * the proto byte string in a common class that must be converted into a string + * before being sent as a proto. + * @internal + */ +declare class ByteString { + private readonly binaryString; + static readonly EMPTY_BYTE_STRING: ByteString; + private constructor(); + static fromBase64String(base64: string): ByteString; + static fromUint8Array(array: Uint8Array): ByteString; + [Symbol.iterator](): Iterator; + toBase64(): string; + toUint8Array(): Uint8Array; + approximateByteSize(): number; + compareTo(other: ByteString): number; + isEqual(other: ByteString): boolean; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** An enumeration of the different purposes we have for targets. */ +declare const enum TargetPurpose { + /** A regular, normal query target. */ + Listen = "TargetPurposeListen", + /** + * The query target was used to refill a query after an existence filter + * mismatch. + */ + ExistenceFilterMismatch = "TargetPurposeExistenceFilterMismatch", + /** + * The query target was used if the query is the result of a false positive in + * the bloom filter. + */ + ExistenceFilterMismatchBloom = "TargetPurposeExistenceFilterMismatchBloom", + /** The query target was used to resolve a limbo document. */ + LimboResolution = "TargetPurposeLimboResolution" +} +/** + * An immutable set of metadata that the local store tracks for each target. + */ +declare class TargetData { + /** The target being listened to. */ + readonly target: Target; + /** + * The target ID to which the target corresponds; Assigned by the + * LocalStore for user listens and by the SyncEngine for limbo watches. + */ + readonly targetId: TargetId; + /** The purpose of the target. */ + readonly purpose: TargetPurpose; + /** + * The sequence number of the last transaction during which this target data + * was modified. + */ + readonly sequenceNumber: ListenSequenceNumber; + /** The latest snapshot version seen for this target. */ + readonly snapshotVersion: SnapshotVersion; + /** + * The maximum snapshot version at which the associated view + * contained no limbo documents. + */ + readonly lastLimboFreeSnapshotVersion: SnapshotVersion; + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + readonly resumeToken: ByteString; + /** + * The number of documents that last matched the query at the resume token or + * read time. Documents are counted only when making a listen request with + * resume token or read time, otherwise, keep it null. + */ + readonly expectedCount: number | null; + constructor( + /** The target being listened to. */ + target: Target, + /** + * The target ID to which the target corresponds; Assigned by the + * LocalStore for user listens and by the SyncEngine for limbo watches. + */ + targetId: TargetId, + /** The purpose of the target. */ + purpose: TargetPurpose, + /** + * The sequence number of the last transaction during which this target data + * was modified. + */ + sequenceNumber: ListenSequenceNumber, + /** The latest snapshot version seen for this target. */ + snapshotVersion?: SnapshotVersion, + /** + * The maximum snapshot version at which the associated view + * contained no limbo documents. + */ + lastLimboFreeSnapshotVersion?: SnapshotVersion, + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + resumeToken?: ByteString, + /** + * The number of documents that last matched the query at the resume token or + * read time. Documents are counted only when making a listen request with + * resume token or read time, otherwise, keep it null. + */ + expectedCount?: number | null); + /** Creates a new target data instance with an updated sequence number. */ + withSequenceNumber(sequenceNumber: number): TargetData; + /** + * Creates a new target data instance with an updated resume token and + * snapshot version. + */ + withResumeToken(resumeToken: ByteString, snapshotVersion: SnapshotVersion): TargetData; + /** + * Creates a new target data instance with an updated expected count. + */ + withExpectedCount(expectedCount: number): TargetData; + /** + * Creates a new target data instance with an updated last limbo free + * snapshot version number. + */ + withLastLimboFreeSnapshotVersion(lastLimboFreeSnapshotVersion: SnapshotVersion): TargetData; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** Base interface for the Serializer implementation. */ +interface Serializer { + readonly useProto3Json: boolean; +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** Used to represent a field transform on a mutation. */ +declare class TransformOperation { + private _; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** A field path and the TransformOperation to perform upon it. */ +declare class FieldTransform { + readonly field: FieldPath$2; + readonly transform: TransformOperation; + constructor(field: FieldPath$2, transform: TransformOperation); +} +/** The result of successfully applying a mutation to the backend. */ +declare class MutationResult { + /** + * The version at which the mutation was committed: + * + * - For most operations, this is the updateTime in the WriteResult. + * - For deletes, the commitTime of the WriteResponse (because deletes are + * not stored and have no updateTime). + * + * Note that these versions can be different: No-op writes will not change + * the updateTime even though the commitTime advances. + */ + readonly version: SnapshotVersion; + /** + * The resulting fields returned from the backend after a mutation + * containing field transforms has been committed. Contains one FieldValue + * for each FieldTransform that was in the mutation. + * + * Will be empty if the mutation did not contain any field transforms. + */ + readonly transformResults: Array; + constructor( + /** + * The version at which the mutation was committed: + * + * - For most operations, this is the updateTime in the WriteResult. + * - For deletes, the commitTime of the WriteResponse (because deletes are + * not stored and have no updateTime). + * + * Note that these versions can be different: No-op writes will not change + * the updateTime even though the commitTime advances. + */ + version: SnapshotVersion, + /** + * The resulting fields returned from the backend after a mutation + * containing field transforms has been committed. Contains one FieldValue + * for each FieldTransform that was in the mutation. + * + * Will be empty if the mutation did not contain any field transforms. + */ + transformResults: Array); +} +declare const enum MutationType { + Set = 0, + Patch = 1, + Delete = 2, + Verify = 3 +} +/** + * Encodes a precondition for a mutation. This follows the model that the + * backend accepts with the special case of an explicit "empty" precondition + * (meaning no precondition). + */ +declare class Precondition { + readonly updateTime?: SnapshotVersion | undefined; + readonly exists?: boolean | undefined; + private constructor(); + /** Creates a new empty Precondition. */ + static none(): Precondition; + /** Creates a new Precondition with an exists flag. */ + static exists(exists: boolean): Precondition; + /** Creates a new Precondition based on a version a document exists at. */ + static updateTime(version: SnapshotVersion): Precondition; + /** Returns whether this Precondition is empty. */ + get isNone(): boolean; + isEqual(other: Precondition): boolean; +} +/** + * A mutation describes a self-contained change to a document. Mutations can + * create, replace, delete, and update subsets of documents. + * + * Mutations not only act on the value of the document but also its version. + * + * For local mutations (mutations that haven't been committed yet), we preserve + * the existing version for Set and Patch mutations. For Delete mutations, we + * reset the version to 0. + * + * Here's the expected transition table. + * + * MUTATION APPLIED TO RESULTS IN + * + * SetMutation Document(v3) Document(v3) + * SetMutation NoDocument(v3) Document(v0) + * SetMutation InvalidDocument(v0) Document(v0) + * PatchMutation Document(v3) Document(v3) + * PatchMutation NoDocument(v3) NoDocument(v3) + * PatchMutation InvalidDocument(v0) UnknownDocument(v3) + * DeleteMutation Document(v3) NoDocument(v0) + * DeleteMutation NoDocument(v3) NoDocument(v0) + * DeleteMutation InvalidDocument(v0) NoDocument(v0) + * + * For acknowledged mutations, we use the updateTime of the WriteResponse as + * the resulting version for Set and Patch mutations. As deletes have no + * explicit update time, we use the commitTime of the WriteResponse for + * Delete mutations. + * + * If a mutation is acknowledged by the backend but fails the precondition check + * locally, we transition to an `UnknownDocument` and rely on Watch to send us + * the updated version. + * + * Field transforms are used only with Patch and Set Mutations. We use the + * `updateTransforms` message to store transforms, rather than the `transforms`s + * messages. + * + * ## Subclassing Notes + * + * Every type of mutation needs to implement its own applyToRemoteDocument() and + * applyToLocalView() to implement the actual behavior of applying the mutation + * to some source document (see `setMutationApplyToRemoteDocument()` for an + * example). + */ +declare abstract class Mutation { + abstract readonly type: MutationType; + abstract readonly key: DocumentKey; + abstract readonly precondition: Precondition; + abstract readonly fieldTransforms: FieldTransform[]; + /** + * Returns a `FieldMask` representing the fields that will be changed by + * applying this mutation. Returns `null` if the mutation will overwrite the + * entire document. + */ + abstract getFieldMask(): FieldMask | null; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Represents a local view (overlay) of a document, and the fields that are + * locally mutated. + */ +declare class OverlayedDocument { + readonly overlayedDocument: Document; + /** + * The fields that are locally mutated by patch mutations. + * + * If the overlayed document is from set or delete mutations, this is `null`. + * If there is no overlay (mutation) for the document, this is an empty `FieldMask`. + */ + readonly mutatedFields: FieldMask | null; + constructor(overlayedDocument: Document, + /** + * The fields that are locally mutated by patch mutations. + * + * If the overlayed document is from set or delete mutations, this is `null`. + * If there is no overlay (mutation) for the document, this is an empty `FieldMask`. + */ + mutatedFields: FieldMask | null); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A map implementation that uses objects as keys. Objects must have an + * associated equals function and must be immutable. Entries in the map are + * stored together with the key being produced from the mapKeyFn. This map + * automatically handles collisions of keys. + */ +declare class ObjectMap { + private mapKeyFn; + private equalsFn; + /** + * The inner map for a key/value pair. Due to the possibility of collisions we + * keep a list of entries that we do a linear search through to find an actual + * match. Note that collisions should be rare, so we still expect near + * constant time lookups in practice. + */ + private inner; + /** The number of entries stored in the map */ + private innerSize; + constructor(mapKeyFn: (key: KeyType) => string, equalsFn: (l: KeyType, r: KeyType) => boolean); + /** Get a value for this key, or undefined if it does not exist. */ + get(key: KeyType): ValueType | undefined; + has(key: KeyType): boolean; + /** Put this key and value in the map. */ + set(key: KeyType, value: ValueType): void; + /** + * Remove this key from the map. Returns a boolean if anything was deleted. + */ + delete(key: KeyType): boolean; + forEach(fn: (key: KeyType, val: ValueType) => void): void; + isEmpty(): boolean; + size(): number; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Representation of an overlay computed by Firestore. + * + * Holds information about a mutation and the largest batch id in Firestore when + * the mutation was created. + */ +declare class Overlay { + readonly largestBatchId: number; + readonly mutation: Mutation; + constructor(largestBatchId: number, mutation: Mutation); + getKey(): DocumentKey; + isEqual(other: Overlay | null): boolean; + toString(): string; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** Miscellaneous collection types / constants. */ +type MutableDocumentMap = SortedMap; +type DocumentMap = SortedMap; +type OverlayedDocumentMap = DocumentKeyMap; +type OverlayMap = DocumentKeyMap; +type MutationMap = DocumentKeyMap; +type DocumentKeyMap = ObjectMap; +type DocumentVersionMap = SortedMap; +type DocumentKeySet = SortedSet; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * An event from the RemoteStore. It is split into targetChanges (changes to the + * state or the set of documents in our watched targets) and documentUpdates + * (changes to the actual documents). + */ +declare class RemoteEvent { + /** + * The snapshot version this event brings us up to, or MIN if not set. + */ + readonly snapshotVersion: SnapshotVersion; + /** + * A map from target to changes to the target. See TargetChange. + */ + readonly targetChanges: Map; + /** + * A map of targets that is known to be inconsistent, and the purpose for + * re-listening. Listens for these targets should be re-established without + * resume tokens. + */ + readonly targetMismatches: SortedMap; + /** + * A set of which documents have changed or been deleted, along with the + * doc's new values (if not deleted). + */ + readonly documentUpdates: MutableDocumentMap; + /** + * A set of which document updates are due only to limbo resolution targets. + */ + readonly resolvedLimboDocuments: DocumentKeySet; + constructor( + /** + * The snapshot version this event brings us up to, or MIN if not set. + */ + snapshotVersion: SnapshotVersion, + /** + * A map from target to changes to the target. See TargetChange. + */ + targetChanges: Map, + /** + * A map of targets that is known to be inconsistent, and the purpose for + * re-listening. Listens for these targets should be re-established without + * resume tokens. + */ + targetMismatches: SortedMap, + /** + * A set of which documents have changed or been deleted, along with the + * doc's new values (if not deleted). + */ + documentUpdates: MutableDocumentMap, + /** + * A set of which document updates are due only to limbo resolution targets. + */ + resolvedLimboDocuments: DocumentKeySet); + /** + * HACK: Views require RemoteEvents in order to determine whether the view is + * CURRENT, but secondary tabs don't receive remote events. So this method is + * used to create a synthesized RemoteEvent that can be used to apply a + * CURRENT status change to a View, for queries executed in a different tab. + */ + static createSynthesizedRemoteEventForCurrentChange(targetId: TargetId, current: boolean, resumeToken: ByteString): RemoteEvent; +} +/** + * A TargetChange specifies the set of changes for a specific target as part of + * a RemoteEvent. These changes track which documents are added, modified or + * removed, as well as the target's resume token and whether the target is + * marked CURRENT. + * The actual changes *to* documents are not part of the TargetChange since + * documents may be part of multiple targets. + */ +declare class TargetChange { + /** + * An opaque, server-assigned token that allows watching a query to be resumed + * after disconnecting without retransmitting all the data that matches the + * query. The resume token essentially identifies a point in time from which + * the server should resume sending results. + */ + readonly resumeToken: ByteString; + /** + * The "current" (synced) status of this target. Note that "current" + * has special meaning in the RPC protocol that implies that a target is + * both up-to-date and consistent with the rest of the watch stream. + */ + readonly current: boolean; + /** + * The set of documents that were newly assigned to this target as part of + * this remote event. + */ + readonly addedDocuments: DocumentKeySet; + /** + * The set of documents that were already assigned to this target but received + * an update during this remote event. + */ + readonly modifiedDocuments: DocumentKeySet; + /** + * The set of documents that were removed from this target as part of this + * remote event. + */ + readonly removedDocuments: DocumentKeySet; + constructor( + /** + * An opaque, server-assigned token that allows watching a query to be resumed + * after disconnecting without retransmitting all the data that matches the + * query. The resume token essentially identifies a point in time from which + * the server should resume sending results. + */ + resumeToken: ByteString, + /** + * The "current" (synced) status of this target. Note that "current" + * has special meaning in the RPC protocol that implies that a target is + * both up-to-date and consistent with the rest of the watch stream. + */ + current: boolean, + /** + * The set of documents that were newly assigned to this target as part of + * this remote event. + */ + addedDocuments: DocumentKeySet, + /** + * The set of documents that were already assigned to this target but received + * an update during this remote event. + */ + modifiedDocuments: DocumentKeySet, + /** + * The set of documents that were removed from this target as part of this + * remote event. + */ + removedDocuments: DocumentKeySet); + /** + * This method is used to create a synthesized TargetChanges that can be used to + * apply a CURRENT status change to a View (for queries executed in a different + * tab) or for new queries (to raise snapshots with correct CURRENT status). + */ + static createSynthesizedTargetChangeForCurrentChange(targetId: TargetId, current: boolean, resumeToken: ByteString): TargetChange; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * This class generates JsonObject values for the Datastore API suitable for + * sending to either GRPC stub methods or via the JSON/HTTP REST API. + * + * The serializer supports both Protobuf.js and Proto3 JSON formats. By + * setting `useProto3Json` to true, the serializer will use the Proto3 JSON + * format. + * + * For a description of the Proto3 JSON format check + * https://developers.google.com/protocol-buffers/docs/proto3#json + * + * TODO(klimt): We can remove the databaseId argument if we keep the full + * resource name in documents. + */ +declare class JsonProtoSerializer implements Serializer { + readonly databaseId: DatabaseId; + readonly useProto3Json: boolean; + constructor(databaseId: DatabaseId, useProto3Json: boolean); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +type DocumentData$1 = { [field: string]: any }; + +type UpdateData$1 = { [fieldPath: string]: any }; + +interface Settings { + host?: string; + ssl?: boolean; + cacheSizeBytes?: number; + experimentalForceLongPolling?: boolean; + experimentalAutoDetectLongPolling?: boolean; + ignoreUndefinedProperties?: boolean; + merge?: boolean; +} + +interface PersistenceSettings$1 { + synchronizeTabs?: boolean; + experimentalTabSynchronization?: boolean; + experimentalForceOwningTab?: boolean; +} + +interface FirestoreDataConverter$2 { + toFirestore(modelObject: T): DocumentData$1; + toFirestore(modelObject: Partial, options: SetOptions$1): DocumentData$1; + + fromFirestore(snapshot: QueryDocumentSnapshot$2, options: SnapshotOptions$1): T; +} + +declare class FirebaseFirestore { + private constructor(); + + settings(settings: Settings): void; + + useEmulator( + host: string, + port: number, + options?: { + mockUserToken?: EmulatorMockTokenOptions | string; + } + ): void; + + enablePersistence(settings?: PersistenceSettings$1): Promise; + + collection(collectionPath: string): CollectionReference$1; + + doc(documentPath: string): DocumentReference$1; + + collectionGroup(collectionId: string): Query$1; + + runTransaction( + updateFunction: (transaction: Transaction$3) => Promise + ): Promise; + + batch(): WriteBatch$1; + + app: any; + + clearPersistence(): Promise; + + enableNetwork(): Promise; + + disableNetwork(): Promise; + + waitForPendingWrites(): Promise; + + onSnapshotsInSync(observer: { + next?: (value: void) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; + }): () => void; + onSnapshotsInSync(onSync: () => void): () => void; + + terminate(): Promise; + + loadBundle( + bundleData: ArrayBuffer | ReadableStream | string + ): LoadBundleTask$1; + + namedQuery(name: string): Promise | null>; + + INTERNAL: { delete: () => Promise }; +} + +interface LoadBundleTask$1 extends PromiseLike { + onProgress( + next?: (progress: LoadBundleTaskProgress$1) => any, + error?: (error: Error) => any, + complete?: () => void + ): void; + + then( + onFulfilled?: (a: LoadBundleTaskProgress$1) => T | PromiseLike, + onRejected?: (a: Error) => R | PromiseLike + ): Promise; + + catch( + onRejected: (a: Error) => R | PromiseLike + ): Promise; +} + +interface LoadBundleTaskProgress$1 { + documentsLoaded: number; + totalDocuments: number; + bytesLoaded: number; + totalBytes: number; + taskState: TaskState$1; +} + +type TaskState$1 = 'Error' | 'Running' | 'Success'; + +declare class Transaction$3 { + private constructor(); + + get(documentRef: DocumentReference$1): Promise>; + + set( + documentRef: DocumentReference$1, + data: Partial, + options: SetOptions$1 + ): Transaction$3; + set(documentRef: DocumentReference$1, data: T): Transaction$3; + + update(documentRef: DocumentReference$1, data: UpdateData$1): Transaction$3; + update( + documentRef: DocumentReference$1, + field: string | FieldPath$1, + value: any, + ...moreFieldsAndValues: any[] + ): Transaction$3; + + delete(documentRef: DocumentReference$1): Transaction$3; +} + +declare class WriteBatch$1 { + private constructor(); + + set( + documentRef: DocumentReference$1, + data: Partial, + options: SetOptions$1 + ): WriteBatch$1; + set(documentRef: DocumentReference$1, data: T): WriteBatch$1; + + update(documentRef: DocumentReference$1, data: UpdateData$1): WriteBatch$1; + update( + documentRef: DocumentReference$1, + field: string | FieldPath$1, + value: any, + ...moreFieldsAndValues: any[] + ): WriteBatch$1; + + delete(documentRef: DocumentReference$1): WriteBatch$1; + + commit(): Promise; +} + +interface SnapshotListenOptions$1 { + readonly includeMetadataChanges?: boolean; +} + +interface SetOptions$1 { + readonly merge?: boolean; + readonly mergeFields?: (string | FieldPath$1)[]; +} + +interface GetOptions { + readonly source?: 'default' | 'server' | 'cache'; +} + +declare class DocumentReference$1< + T = DocumentData$1, + T2 extends DocumentData$1 = DocumentData$1 +> { + private constructor(); + + readonly id: string; + readonly firestore: FirebaseFirestore; + readonly parent: CollectionReference$1; + readonly path: string; + + collection(collectionPath: string): CollectionReference$1; + + isEqual(other: DocumentReference$1): boolean; + + set(data: Partial, options: SetOptions$1): Promise; + set(data: T): Promise; + + update(data: UpdateData$1): Promise; + update( + field: string | FieldPath$1, + value: any, + ...moreFieldsAndValues: any[] + ): Promise; + + delete(): Promise; + + get(options?: GetOptions): Promise>; + + onSnapshot(observer: { + next?: (snapshot: DocumentSnapshot$2) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; + }): () => void; + onSnapshot( + options: SnapshotListenOptions$1, + observer: { + next?: (snapshot: DocumentSnapshot$2) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; + } + ): () => void; + onSnapshot( + onNext: (snapshot: DocumentSnapshot$2) => void, + onError?: (error: FirestoreError) => void, + onCompletion?: () => void + ): () => void; + onSnapshot( + options: SnapshotListenOptions$1, + onNext: (snapshot: DocumentSnapshot$2) => void, + onError?: (error: FirestoreError) => void, + onCompletion?: () => void + ): () => void; + + withConverter(converter: null): DocumentReference$1; + withConverter(converter: FirestoreDataConverter$2): DocumentReference$1; +} + +interface SnapshotOptions$1 { + readonly serverTimestamps?: 'estimate' | 'previous' | 'none'; +} + +interface SnapshotMetadata$1 { + readonly hasPendingWrites: boolean; + readonly fromCache: boolean; + + isEqual(other: SnapshotMetadata$1): boolean; +} + +declare class DocumentSnapshot$2< + T = DocumentData$1, + T2 extends DocumentData$1 = DocumentData$1 +> { + protected constructor(); + + readonly exists: boolean; + readonly ref: DocumentReference$1; + readonly id: string; + readonly metadata: SnapshotMetadata$1; + + data(options?: SnapshotOptions$1): T | undefined; + + get(fieldPath: string | FieldPath$1, options?: SnapshotOptions$1): any; + + isEqual(other: DocumentSnapshot$2): boolean; +} + +declare class QueryDocumentSnapshot$2< + T = DocumentData$1, + T2 extends DocumentData$1 = DocumentData$1 +> extends DocumentSnapshot$2 { + private constructor(); + + data(options?: SnapshotOptions$1): T; +} + +type OrderByDirection$1 = 'desc' | 'asc'; + +type WhereFilterOp$1 = + | '<' + | '<=' + | '==' + | '!=' + | '>=' + | '>' + | 'array-contains' + | 'in' + | 'array-contains-any' + | 'not-in'; + +declare class Query$1 { + protected constructor(); + + readonly firestore: FirebaseFirestore; + + where( + fieldPath: string | FieldPath$1, + opStr: WhereFilterOp$1, + value: any + ): Query$1; + + orderBy( + fieldPath: string | FieldPath$1, + directionStr?: OrderByDirection$1 + ): Query$1; + + limit(limit: number): Query$1; + + limitToLast(limit: number): Query$1; + + startAt(snapshot: DocumentSnapshot$2): Query$1; + startAt(...fieldValues: any[]): Query$1; + + startAfter(snapshot: DocumentSnapshot$2): Query$1; + startAfter(...fieldValues: any[]): Query$1; + + endBefore(snapshot: DocumentSnapshot$2): Query$1; + endBefore(...fieldValues: any[]): Query$1; + + endAt(snapshot: DocumentSnapshot$2): Query$1; + endAt(...fieldValues: any[]): Query$1; + + isEqual(other: Query$1): boolean; + + get(options?: GetOptions): Promise>; + + onSnapshot(observer: { + next?: (snapshot: QuerySnapshot$1) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; + }): () => void; + onSnapshot( + options: SnapshotListenOptions$1, + observer: { + next?: (snapshot: QuerySnapshot$1) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; + } + ): () => void; + onSnapshot( + onNext: (snapshot: QuerySnapshot$1) => void, + onError?: (error: FirestoreError) => void, + onCompletion?: () => void + ): () => void; + onSnapshot( + options: SnapshotListenOptions$1, + onNext: (snapshot: QuerySnapshot$1) => void, + onError?: (error: FirestoreError) => void, + onCompletion?: () => void + ): () => void; + + withConverter(converter: null): Query$1; + withConverter(converter: FirestoreDataConverter$2): Query$1; +} + +declare class QuerySnapshot$1< + T = DocumentData$1, + T2 extends DocumentData$1 = DocumentData$1 +> { + private constructor(); + + readonly query: Query$1; + readonly metadata: SnapshotMetadata$1; + readonly docs: Array>; + readonly size: number; + readonly empty: boolean; + + docChanges(options?: SnapshotListenOptions$1): Array>; + + forEach( + callback: (result: QueryDocumentSnapshot$2) => void, + thisArg?: any + ): void; + + isEqual(other: QuerySnapshot$1): boolean; +} + +type DocumentChangeType$1 = 'added' | 'removed' | 'modified'; + +interface DocumentChange$1< + T = DocumentData$1, + T2 extends DocumentData$1 = DocumentData$1 +> { + readonly type: DocumentChangeType$1; + readonly doc: QueryDocumentSnapshot$2; + readonly oldIndex: number; + readonly newIndex: number; +} + +declare class CollectionReference$1< + T = DocumentData$1, + T2 extends DocumentData$1 = DocumentData$1 +> extends Query$1 { + private constructor(); + + readonly id: string; + readonly parent: DocumentReference$1 | null; + readonly path: string; + + doc(documentPath?: string): DocumentReference$1; + + add(data: T): Promise>; + + isEqual(other: CollectionReference$1): boolean; + + withConverter(converter: null): CollectionReference$1; + withConverter( + converter: FirestoreDataConverter$2 + ): CollectionReference$1; +} + +declare class FieldPath$1 { + constructor(...fieldNames: string[]); + + static documentId(): FieldPath$1; + + isEqual(other: FieldPath$1): boolean; +} + +type FirestoreErrorCode = + | 'cancelled' + | 'unknown' + | 'invalid-argument' + | 'deadline-exceeded' + | 'not-found' + | 'already-exists' + | 'permission-denied' + | 'resource-exhausted' + | 'failed-precondition' + | 'aborted' + | 'out-of-range' + | 'unimplemented' + | 'internal' + | 'unavailable' + | 'data-loss' + | 'unauthenticated'; + +interface FirestoreError { + code: FirestoreErrorCode; + message: string; + name: string; + stack?: string; +} + +declare module '@firebase/component' { + interface NameServiceMapping { + 'firestore-compat': FirebaseFirestore; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** Properties of a BundledQuery. */ +interface BundledQuery { + /** BundledQuery parent */ + parent?: string | null; + /** BundledQuery structuredQuery */ + structuredQuery?: StructuredQuery | null; + /** BundledQuery limitType */ + limitType?: LimitType | null; +} +/** LimitType enum. */ +type LimitType = 'FIRST' | 'LAST'; +/** Properties of a NamedQuery. */ +interface NamedQuery$1 { + /** NamedQuery name */ + name?: string | null; + /** NamedQuery bundledQuery */ + bundledQuery?: BundledQuery | null; + /** NamedQuery readTime */ + readTime?: Timestamp | null; +} +/** Properties of a BundleMetadata. */ +interface BundleMetadata$1 { + /** BundleMetadata id */ + id?: string | null; + /** BundleMetadata createTime */ + createTime?: Timestamp | null; + /** BundleMetadata version */ + version?: number | null; + /** BundleMetadata totalDocuments */ + totalDocuments?: number | null; + /** BundleMetadata totalBytes */ + totalBytes?: number | null; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Represents a Firestore bundle saved by the SDK in its local storage. + */ +interface BundleMetadata { + /** + * Id of the bundle. It is used together with `createTime` to determine if a + * bundle has been loaded by the SDK. + */ + readonly id: string; + /** Schema version of the bundle. */ + readonly version: number; + /** + * Set to the snapshot version of the bundle if created by the Server SDKs. + * Otherwise set to SnapshotVersion.MIN. + */ + readonly createTime: SnapshotVersion; +} +/** + * Represents a Query saved by the SDK in its local storage. + */ +interface NamedQuery { + /** The name of the query. */ + readonly name: string; + /** The underlying query associated with `name`. */ + readonly query: Query$2; + /** The time at which the results for this query were read. */ + readonly readTime: SnapshotVersion; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +type FulfilledHandler = ((result: T) => R | PersistencePromise) | null; +type RejectedHandler = ((reason: Error) => R | PersistencePromise) | null; +type Resolver = (value?: T) => void; +type Rejector = (error: Error) => void; +/** + * PersistencePromise is essentially a re-implementation of Promise except + * it has a .next() method instead of .then() and .next() and .catch() callbacks + * are executed synchronously when a PersistencePromise resolves rather than + * asynchronously (Promise implementations use setImmediate() or similar). + * + * This is necessary to interoperate with IndexedDB which will automatically + * commit transactions if control is returned to the event loop without + * synchronously initiating another operation on the transaction. + * + * NOTE: .then() and .catch() only allow a single consumer, unlike normal + * Promises. + */ +declare class PersistencePromise { + private nextCallback; + private catchCallback; + private result; + private error; + private isDone; + private callbackAttached; + constructor(callback: (resolve: Resolver, reject: Rejector) => void); + catch(fn: (error: Error) => R | PersistencePromise): PersistencePromise; + next(nextFn?: FulfilledHandler, catchFn?: RejectedHandler): PersistencePromise; + toPromise(): Promise; + private wrapUserFunction; + private wrapSuccess; + private wrapFailure; + static resolve(): PersistencePromise; + static resolve(result: R): PersistencePromise; + static reject(error: Error): PersistencePromise; + static waitFor(all: { + forEach: (cb: (el: PersistencePromise) => void) => void; + }): PersistencePromise; + /** + * Given an array of predicate functions that asynchronously evaluate to a + * boolean, implements a short-circuiting `or` between the results. Predicates + * will be evaluated until one of them returns `true`, then stop. The final + * result will be whether any of them returned `true`. + */ + static or(predicates: Array<() => PersistencePromise>): PersistencePromise; + /** + * Given an iterable, call the given function on each element in the + * collection and wait for all of the resulting concurrent PersistencePromises + * to resolve. + */ + static forEach(collection: { + forEach: (cb: (r: R, s: S) => void) => void; + }, f: ((r: R, s: S) => PersistencePromise) | ((r: R) => PersistencePromise)): PersistencePromise; + static forEach(collection: { + forEach: (cb: (r: R) => void) => void; + }, f: (r: R) => PersistencePromise): PersistencePromise; + /** + * Concurrently map all array elements through asynchronous function. + */ + static mapArray(array: T[], f: (t: T) => PersistencePromise): PersistencePromise; + /** + * An alternative to recursive PersistencePromise calls, that avoids + * potential memory problems from unbounded chains of promises. + * + * The `action` will be called repeatedly while `condition` is true. + */ + static doWhile(condition: () => boolean, action: () => PersistencePromise): PersistencePromise; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** The different modes supported by `Persistence.runTransaction()`. */ +type PersistenceTransactionMode = 'readonly' | 'readwrite' | 'readwrite-primary'; +/** + * A base class representing a persistence transaction, encapsulating both the + * transaction's sequence numbers as well as a list of onCommitted listeners. + * + * When you call Persistence.runTransaction(), it will create a transaction and + * pass it to your callback. You then pass it to any method that operates + * on persistence. + */ +declare abstract class PersistenceTransaction { + private readonly onCommittedListeners; + abstract readonly currentSequenceNumber: ListenSequenceNumber; + addOnCommittedListener(listener: () => void): void; + raiseOnCommittedEvent(): void; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Provides interfaces to save and read Firestore bundles. + */ +interface BundleCache { + /** + * Gets the saved `BundleMetadata` for a given `bundleId`, returns undefined + * if no bundle metadata is found under the given id. + */ + getBundleMetadata(transaction: PersistenceTransaction, bundleId: string): PersistencePromise; + /** + * Saves a `BundleMetadata` from a bundle into local storage, using its id as + * the persistent key. + */ + saveBundleMetadata(transaction: PersistenceTransaction, metadata: BundleMetadata$1): PersistencePromise; + /** + * Gets a saved `NamedQuery` for the given query name. Returns undefined if + * no queries are found under the given name. + */ + getNamedQuery(transaction: PersistenceTransaction, queryName: string): PersistencePromise; + /** + * Saves a `NamedQuery` from a bundle, using its name as the persistent key. + */ + saveNamedQuery(transaction: PersistenceTransaction, query: NamedQuery$1): PersistencePromise; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Provides methods to read and write document overlays. + * + * An overlay is a saved mutation, that gives a local view of a document when + * applied to the remote version of the document. + * + * Each overlay stores the largest batch ID that is included in the overlay, + * which allows us to remove the overlay once all batches leading up to it have + * been acknowledged. + */ +interface DocumentOverlayCache { + /** + * Gets the saved overlay mutation for the given document key. + * Returns null if there is no overlay for that key. + */ + getOverlay(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; + /** + * Gets the saved overlay mutation for the given document keys. Skips keys for + * which there are no overlays. + */ + getOverlays(transaction: PersistenceTransaction, keys: DocumentKey[]): PersistencePromise; + /** + * Saves the given document mutation map to persistence as overlays. + * All overlays will have their largest batch id set to `largestBatchId`. + */ + saveOverlays(transaction: PersistenceTransaction, largestBatchId: number, overlays: MutationMap): PersistencePromise; + /** Removes overlays for the given document keys and batch ID. */ + removeOverlaysForBatchId(transaction: PersistenceTransaction, documentKeys: DocumentKeySet, batchId: number): PersistencePromise; + /** + * Returns all saved overlays for the given collection. + * + * @param transaction - The persistence transaction to use for this operation. + * @param collection - The collection path to get the overlays for. + * @param sinceBatchId - The minimum batch ID to filter by (exclusive). + * Only overlays that contain a change past `sinceBatchId` are returned. + * @returns Mapping of each document key in the collection to its overlay. + */ + getOverlaysForCollection(transaction: PersistenceTransaction, collection: ResourcePath, sinceBatchId: number): PersistencePromise; + /** + * Returns `count` overlays with a batch ID higher than `sinceBatchId` for the + * provided collection group, processed by ascending batch ID. The method + * always returns all overlays for a batch even if the last batch contains + * more documents than the remaining limit. + * + * @param transaction - The persistence transaction used for this operation. + * @param collectionGroup - The collection group to get the overlays for. + * @param sinceBatchId - The minimum batch ID to filter by (exclusive). + * Only overlays that contain a change past `sinceBatchId` are returned. + * @param count - The number of overlays to return. Can be exceeded if the last + * batch contains more entries. + * @return Mapping of each document key in the collection group to its overlay. + */ + getOverlaysForCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, sinceBatchId: number, count: number): PersistencePromise; +} + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * General purpose cache for global values. + * + * Global state that cuts across components should be saved here. Following are contained herein: + * + * `sessionToken` tracks server interaction across Listen and Write streams. This facilitates cache + * synchronization and invalidation. + */ +interface GlobalsCache { + /** + * Gets session token. + */ + getSessionToken(transaction: PersistenceTransaction): PersistencePromise; + /** + * Sets session token. + * + * @param sessionToken - The new session token. + */ + setSessionToken(transaction: PersistenceTransaction, sessionToken: ByteString): PersistencePromise; +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** Represents the index state as it relates to a particular target. */ +declare const enum IndexType { + /** Indicates that no index could be found for serving the target. */ + NONE = 0, + /** + * Indicates that only a "partial index" could be found for serving the + * target. A partial index is one which does not have a segment for every + * filter/orderBy in the target. + */ + PARTIAL = 1, + /** + * Indicates that a "full index" could be found for serving the target. A full + * index is one which has a segment for every filter/orderBy in the target. + */ + FULL = 2 +} +/** + * Represents a set of indexes that are used to execute queries efficiently. + * + * Currently the only index is a [collection id] => [parent path] index, used + * to execute Collection Group queries. + */ +interface IndexManager { + /** + * Creates an index entry mapping the collectionId (last segment of the path) + * to the parent path (either the containing document location or the empty + * path for root-level collections). Index entries can be retrieved via + * getCollectionParents(). + * + * NOTE: Currently we don't remove index entries. If this ends up being an + * issue we can devise some sort of GC strategy. + */ + addToCollectionParentIndex(transaction: PersistenceTransaction, collectionPath: ResourcePath): PersistencePromise; + /** + * Retrieves all parent locations containing the given collectionId, as a + * list of paths (each path being either a document location or the empty + * path for a root-level collection). + */ + getCollectionParents(transaction: PersistenceTransaction, collectionId: string): PersistencePromise; + /** + * Adds a field path index. + * + * Values for this index are persisted via the index backfill, which runs + * asynchronously in the background. Once the first values are written, + * an index can be used to serve partial results for any matching queries. + * Any unindexed portion of the database will continue to be served via + * collection scons. + */ + addFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + /** Removes the given field index and deletes all index values. */ + deleteFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + /** Removes all field indexes and deletes all index values. */ + deleteAllFieldIndexes(transaction: PersistenceTransaction): PersistencePromise; + /** Creates a full matched field index which serves the given target. */ + createTargetIndexes(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Returns a list of field indexes that correspond to the specified collection + * group. + * + * @param collectionGroup The collection group to get matching field indexes + * for. + * @return A collection of field indexes for the specified collection group. + */ + getFieldIndexes(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise; + /** Returns all configured field indexes. */ + getFieldIndexes(transaction: PersistenceTransaction): PersistencePromise; + /** + * Returns the type of index (if any) that can be used to serve the given + * target. + */ + getIndexType(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Returns the documents that match the given target based on the provided + * index or `null` if the target does not have a matching index. + */ + getDocumentsMatchingTarget(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Returns the next collection group to update. Returns `null` if no group + * exists. + */ + getNextCollectionGroupToUpdate(transaction: PersistenceTransaction): PersistencePromise; + /** + * Sets the collection group's latest read time. + * + * This method updates the index offset for all field indices for the + * collection group and increments their sequence number. Subsequent calls to + * `getNextCollectionGroupToUpdate()` will return a different collection group + * (unless only one collection group is configured). + */ + updateCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset): PersistencePromise; + /** Updates the index entries for the provided documents. */ + updateIndexEntries(transaction: PersistenceTransaction, documents: DocumentMap): PersistencePromise; + /** + * Iterates over all field indexes that are used to serve the given target, + * and returns the minimum offset of them all. + */ + getMinOffset(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** Returns the minimum offset for the given collection group. */ + getMinOffsetFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise; +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Describes a map whose keys are active target ids. We do not care about the type of the + * values. + */ +type ActiveTargets = SortedMap; +declare class LruParams { + readonly cacheSizeCollectionThreshold: number; + readonly percentileToCollect: number; + readonly maximumSequenceNumbersToCollect: number; + private static readonly DEFAULT_COLLECTION_PERCENTILE; + private static readonly DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT; + static withCacheSize(cacheSize: number): LruParams; + static readonly DEFAULT: LruParams; + static readonly DISABLED: LruParams; + constructor(cacheSizeCollectionThreshold: number, percentileToCollect: number, maximumSequenceNumbersToCollect: number); +} +interface LruGarbageCollector { + readonly params: LruParams; + collect(txn: PersistenceTransaction, activeTargetIds: ActiveTargets): PersistencePromise; + /** Given a percentile of target to collect, returns the number of targets to collect. */ + calculateTargetCount(txn: PersistenceTransaction, percentile: number): PersistencePromise; + /** Returns the nth sequence number, counting in order from the smallest. */ + nthSequenceNumber(txn: PersistenceTransaction, n: number): PersistencePromise; + /** + * Removes documents that have a sequence number equal to or less than the + * upper bound and are not otherwise pinned. + */ + removeOrphanedDocuments(txn: PersistenceTransaction, upperBound: ListenSequenceNumber): PersistencePromise; + getCacheSize(txn: PersistenceTransaction): PersistencePromise; + /** + * Removes targets with a sequence number equal to or less than the given + * upper bound, and removes document associations with those targets. + */ + removeTargets(txn: PersistenceTransaction, upperBound: ListenSequenceNumber, activeTargetIds: ActiveTargets): PersistencePromise; +} +/** + * Describes the results of a garbage collection run. `didRun` will be set to + * `false` if collection was skipped (either it is disabled or the cache size + * has not hit the threshold). If collection ran, the other fields will be + * filled in with the details of the results. + */ +interface LruResults { + readonly didRun: boolean; + readonly sequenceNumbersCollected: number; + readonly targetsRemoved: number; + readonly documentsRemoved: number; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * A batch of mutations that will be sent as one unit to the backend. + */ +declare class MutationBatch { + batchId: BatchId; + localWriteTime: Timestamp$1; + baseMutations: Mutation[]; + mutations: Mutation[]; + /** + * @param batchId - The unique ID of this mutation batch. + * @param localWriteTime - The original write time of this mutation. + * @param baseMutations - Mutations that are used to populate the base + * values when this mutation is applied locally. This can be used to locally + * overwrite values that are persisted in the remote document cache. Base + * mutations are never sent to the backend. + * @param mutations - The user-provided mutations in this mutation batch. + * User-provided mutations are applied both locally and remotely on the + * backend. + */ + constructor(batchId: BatchId, localWriteTime: Timestamp$1, baseMutations: Mutation[], mutations: Mutation[]); + /** + * Applies all the mutations in this MutationBatch to the specified document + * to compute the state of the remote document + * + * @param document - The document to apply mutations to. + * @param batchResult - The result of applying the MutationBatch to the + * backend. + */ + applyToRemoteDocument(document: MutableDocument, batchResult: MutationBatchResult): void; + /** + * Computes the local view of a document given all the mutations in this + * batch. + * + * @param document - The document to apply mutations to. + * @param mutatedFields - Fields that have been updated before applying this mutation batch. + * @returns A `FieldMask` representing all the fields that are mutated. + */ + applyToLocalView(document: MutableDocument, mutatedFields: FieldMask | null): FieldMask | null; + /** + * Computes the local view for all provided documents given the mutations in + * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to + * replace all the mutation applications. + */ + applyToLocalDocumentSet(documentMap: OverlayedDocumentMap, documentsWithoutRemoteVersion: DocumentKeySet): MutationMap; + keys(): DocumentKeySet; + isEqual(other: MutationBatch): boolean; +} +/** The result of applying a mutation batch to the backend. */ +declare class MutationBatchResult { + readonly batch: MutationBatch; + readonly commitVersion: SnapshotVersion; + readonly mutationResults: MutationResult[]; + /** + * A pre-computed mapping from each mutated document to the resulting + * version. + */ + readonly docVersions: DocumentVersionMap; + private constructor(); + /** + * Creates a new MutationBatchResult for the given batch and results. There + * must be one result for each mutation in the batch. This static factory + * caches a document=>version mapping (docVersions). + */ + static from(batch: MutationBatch, commitVersion: SnapshotVersion, results: MutationResult[]): MutationBatchResult; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** A queue of mutations to apply to the remote store. */ +interface MutationQueue { + /** Returns true if this queue contains no mutation batches. */ + checkEmpty(transaction: PersistenceTransaction): PersistencePromise; + /** + * Creates a new mutation batch and adds it to this mutation queue. + * + * @param transaction - The transaction this operation is scoped to. + * @param localWriteTime - The original write time of this mutation. + * @param baseMutations - Mutations that are used to populate the base values + * when this mutation is applied locally. These mutations are used to locally + * overwrite values that are persisted in the remote document cache. + * @param mutations - The user-provided mutations in this mutation batch. + */ + addMutationBatch(transaction: PersistenceTransaction, localWriteTime: Timestamp$1, baseMutations: Mutation[], mutations: Mutation[]): PersistencePromise; + /** + * Loads the mutation batch with the given batchId. + */ + lookupMutationBatch(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + /** + * Gets the first unacknowledged mutation batch after the passed in batchId + * in the mutation queue or null if empty. + * + * @param batchId - The batch to search after, or BATCHID_UNKNOWN for the + * first mutation in the queue. + * + * @returns the next mutation or null if there wasn't one. + */ + getNextMutationBatchAfterBatchId(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + /** + * Gets the largest (latest) batch id in mutation queue for the current user + * that is pending server response, returns `BATCHID_UNKNOWN` if the queue is + * empty. + * + * @returns the largest batch id in the mutation queue that is not + * acknowledged. + */ + getHighestUnacknowledgedBatchId(transaction: PersistenceTransaction): PersistencePromise; + /** Gets all mutation batches in the mutation queue. */ + getAllMutationBatches(transaction: PersistenceTransaction): PersistencePromise; + /** + * Finds all mutation batches that could possibly affect the given + * document key. Not all mutations in a batch will necessarily affect the + * document key, so when looping through the batch you'll need to check that + * the mutation itself matches the key. + * + * Batches are guaranteed to be in sorted order. + * + * Note that because of this requirement implementations are free to return + * mutation batches that don't contain the document key at all if it's + * convenient. + */ + getAllMutationBatchesAffectingDocumentKey(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + /** + * Finds all mutation batches that could possibly affect the given set of + * document keys. Not all mutations in a batch will necessarily affect each + * key, so when looping through the batch you'll need to check that the + * mutation itself matches the key. + * + * Batches are guaranteed to be in sorted order. + * + * Note that because of this requirement implementations are free to return + * mutation batches that don't contain any of the document keys at all if it's + * convenient. + */ + getAllMutationBatchesAffectingDocumentKeys(transaction: PersistenceTransaction, documentKeys: SortedMap): PersistencePromise; + /** + * Finds all mutation batches that could affect the results for the given + * query. Not all mutations in a batch will necessarily affect the query, so + * when looping through the batch you'll need to check that the mutation + * itself matches the query. + * + * Batches are guaranteed to be in sorted order. + * + * Note that because of this requirement implementations are free to return + * mutation batches that don't match the query at all if it's convenient. + * + * NOTE: A PatchMutation does not need to include all fields in the query + * filter criteria in order to be a match (but any fields it does contain do + * need to match). + */ + getAllMutationBatchesAffectingQuery(transaction: PersistenceTransaction, query: Query$2): PersistencePromise; + /** + * Removes the given mutation batch from the queue. This is useful in two + * circumstances: + * + * + Removing an applied mutation from the head of the queue + * + Removing a rejected mutation from anywhere in the queue + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMutationBatch(transaction: PersistenceTransaction, batch: MutationBatch): PersistencePromise; + /** + * Performs a consistency check, examining the mutation queue for any + * leaks, if possible. + */ + performConsistencyCheck(transaction: PersistenceTransaction): PersistencePromise; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A tracker to keep a record of important details during database local query + * execution. + */ +declare class QueryContext { + /** + * Counts the number of documents passed through during local query execution. + */ + private _documentReadCount; + get documentReadCount(): number; + incrementDocumentReadCount(amount: number): void; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * An in-memory buffer of entries to be written to a RemoteDocumentCache. + * It can be used to batch up a set of changes to be written to the cache, but + * additionally supports reading entries back with the `getEntry()` method, + * falling back to the underlying RemoteDocumentCache if no entry is + * buffered. + * + * Entries added to the cache *must* be read first. This is to facilitate + * calculating the size delta of the pending changes. + * + * PORTING NOTE: This class was implemented then removed from other platforms. + * If byte-counting ends up being needed on the other platforms, consider + * porting this class as part of that implementation work. + */ +declare abstract class RemoteDocumentChangeBuffer { + protected changes: ObjectMap; + private changesApplied; + protected abstract getFromCache(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + protected abstract getAllFromCache(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise; + protected abstract applyChanges(transaction: PersistenceTransaction): PersistencePromise; + /** + * Buffers a `RemoteDocumentCache.addEntry()` call. + * + * You can only modify documents that have already been retrieved via + * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). + */ + addEntry(document: MutableDocument): void; + /** + * Buffers a `RemoteDocumentCache.removeEntry()` call. + * + * You can only remove documents that have already been retrieved via + * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). + */ + removeEntry(key: DocumentKey, readTime: SnapshotVersion): void; + /** + * Looks up an entry in the cache. The buffered changes will first be checked, + * and if no buffered change applies, this will forward to + * `RemoteDocumentCache.getEntry()`. + * + * @param transaction - The transaction in which to perform any persistence + * operations. + * @param documentKey - The key of the entry to look up. + * @returns The cached document or an invalid document if we have nothing + * cached. + */ + getEntry(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + /** + * Looks up several entries in the cache, forwarding to + * `RemoteDocumentCache.getEntry()`. + * + * @param transaction - The transaction in which to perform any persistence + * operations. + * @param documentKeys - The keys of the entries to look up. + * @returns A map of cached documents, indexed by key. If an entry cannot be + * found, the corresponding key will be mapped to an invalid document. + */ + getEntries(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise; + /** + * Applies buffered changes to the underlying RemoteDocumentCache, using + * the provided transaction. + */ + apply(transaction: PersistenceTransaction): PersistencePromise; + /** Helper to assert this.changes is not null */ + protected assertNotApplied(): void; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Represents cached documents received from the remote backend. + * + * The cache is keyed by DocumentKey and entries in the cache are + * MutableDocuments, meaning we can cache both actual documents as well as + * documents that are known to not exist. + */ +interface RemoteDocumentCache { + /** Sets the index manager to use for managing the collectionGroup index. */ + setIndexManager(indexManager: IndexManager): void; + /** + * Looks up an entry in the cache. + * + * @param documentKey - The key of the entry to look up.* + * @returns The cached document entry. Returns an invalid document if the + * document is not cached. + */ + getEntry(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + /** + * Looks up a set of entries in the cache. + * + * @param documentKeys - The keys of the entries to look up. + * @returns The cached document entries indexed by key. If an entry is not + * cached, the corresponding key will be mapped to an invalid document. + */ + getEntries(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise; + /** + * Returns the documents matching the given query + * + * @param query - The query to match documents against. + * @param offset - The offset to start the scan at (exclusive). + * @param context - A optional tracker to keep a record of important details + * during database local query execution. + * @returns The set of matching documents. + */ + getDocumentsMatchingQuery(transaction: PersistenceTransaction, query: Query$2, offset: IndexOffset, mutatedDocs: OverlayMap, context?: QueryContext): PersistencePromise; + /** + * Looks up the next `limit` documents for a collection group based on the + * provided offset. The ordering is based on the document's read time and key. + * + * @param collectionGroup - The collection group to scan. + * @param offset - The offset to start the scan at (exclusive). + * @param limit - The maximum number of results to return. + * @returns The set of matching documents. + */ + getAllFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset, limit: number): PersistencePromise; + /** + * Provides access to add or update the contents of the cache. The buffer + * handles proper size accounting for the change. + * + * Multi-Tab Note: This should only be called by the primary client. + * + * @param options - Specify `trackRemovals` to create sentinel entries for + * removed documents, which allows removals to be tracked by + * `getNewDocumentChanges()`. + */ + newChangeBuffer(options?: { + trackRemovals: boolean; + }): RemoteDocumentChangeBuffer; + /** + * Get an estimate of the size of the document cache. Note that for eager + * garbage collection, we don't track sizes so this will return 0. + */ + getSize(transaction: PersistenceTransaction): PersistencePromise; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Represents cached targets received from the remote backend. + * + * The cache is keyed by `Target` and entries in the cache are `TargetData` + * instances. + */ +interface TargetCache { + /** + * A global snapshot version representing the last consistent snapshot we + * received from the backend. This is monotonically increasing and any + * snapshots received from the backend prior to this version (e.g. for targets + * resumed with a resume_token) should be suppressed (buffered) until the + * backend has caught up to this snapshot version again. This prevents our + * cache from ever going backwards in time. + * + * This is updated whenever our we get a TargetChange with a read_time and + * empty target_ids. + */ + getLastRemoteSnapshotVersion(transaction: PersistenceTransaction): PersistencePromise; + /** + * @returns The highest sequence number observed, including any that might be + * persisted on-disk. + */ + getHighestSequenceNumber(transaction: PersistenceTransaction): PersistencePromise; + /** + * Call provided function with each `TargetData` that we have cached. + */ + forEachTarget(txn: PersistenceTransaction, f: (q: TargetData) => void): PersistencePromise; + /** + * Set the highest listen sequence number and optionally updates the + * snapshot version of the last consistent snapshot received from the backend + * (see getLastRemoteSnapshotVersion() for more details). + * + * @param highestListenSequenceNumber - The new maximum listen sequence number. + * @param lastRemoteSnapshotVersion - The new snapshot version. Optional. + */ + setTargetsMetadata(transaction: PersistenceTransaction, highestListenSequenceNumber: number, lastRemoteSnapshotVersion?: SnapshotVersion): PersistencePromise; + /** + * Adds an entry in the cache. + * + * The cache key is extracted from `targetData.target`. The key must not already + * exist in the cache. + * + * @param targetData - A TargetData instance to put in the cache. + */ + addTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Updates an entry in the cache. + * + * The cache key is extracted from `targetData.target`. The entry must already + * exist in the cache, and it will be replaced. + * @param targetData - The TargetData to be replaced into the cache. + */ + updateTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Removes the cached entry for the given target data. It is an error to remove + * a target data that does not exist. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * The number of targets currently in the cache. + */ + getTargetCount(transaction: PersistenceTransaction): PersistencePromise; + /** + * Looks up a TargetData entry by target. + * + * @param target - The query target corresponding to the entry to look up. + * @returns The cached TargetData entry, or null if the cache has no entry for + * the target. + */ + getTargetData(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Adds the given document keys to cached query results of the given target + * ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + addMatchingKeys(transaction: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + /** + * Removes the given document keys from the cached query results of the + * given target ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMatchingKeys(transaction: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + /** + * Removes all the keys in the query results of the given target ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMatchingKeysForTargetId(transaction: PersistenceTransaction, targetId: TargetId): PersistencePromise; + /** + * Returns the document keys that match the provided target ID. + */ + getMatchingKeysForTargetId(transaction: PersistenceTransaction, targetId: TargetId): PersistencePromise; + /** + * Returns a new target ID that is higher than any query in the cache. If + * there are no queries in the cache, returns the first valid target ID. + * Allocated target IDs are persisted and `allocateTargetId()` will never + * return the same ID twice. + */ + allocateTargetId(transaction: PersistenceTransaction): PersistencePromise; + containsKey(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * A ReferenceDelegate instance handles all of the hooks into the document-reference lifecycle. This + * includes being added to a target, being removed from a target, being subject to mutation, and + * being mutated by the user. + * + * Different implementations may do different things with each of these events. Not every + * implementation needs to do something with every lifecycle hook. + * + * PORTING NOTE: since sequence numbers are attached to transactions in this + * client, the ReferenceDelegate does not need to deal in transactional + * semantics (onTransactionStarted/Committed()), nor does it need to track and + * generate sequence numbers (getCurrentSequenceNumber()). + */ +interface ReferenceDelegate { + /** Notify the delegate that the given document was added to a target. */ + addReference(txn: PersistenceTransaction, targetId: TargetId, doc: DocumentKey): PersistencePromise; + /** Notify the delegate that the given document was removed from a target. */ + removeReference(txn: PersistenceTransaction, targetId: TargetId, doc: DocumentKey): PersistencePromise; + /** + * Notify the delegate that a target was removed. The delegate may, but is not obligated to, + * actually delete the target and associated data. + */ + removeTarget(txn: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Notify the delegate that a document may no longer be part of any views or + * have any mutations associated. + */ + markPotentiallyOrphaned(txn: PersistenceTransaction, doc: DocumentKey): PersistencePromise; + /** Notify the delegate that a limbo document was updated. */ + updateLimboDocument(txn: PersistenceTransaction, doc: DocumentKey): PersistencePromise; +} +/** + * Persistence is the lowest-level shared interface to persistent storage in + * Firestore. + * + * Persistence is used to create MutationQueue and RemoteDocumentCache + * instances backed by persistence (which might be in-memory or LevelDB). + * + * Persistence also exposes an API to create and run PersistenceTransactions + * against persistence. All read / write operations must be wrapped in a + * transaction. Implementations of PersistenceTransaction / Persistence only + * need to guarantee that writes made against the transaction are not made to + * durable storage until the transaction resolves its PersistencePromise. + * Since memory-only storage components do not alter durable storage, they are + * free to ignore the transaction. + * + * This contract is enough to allow the LocalStore be be written + * independently of whether or not the stored state actually is durably + * persisted. If persistent storage is enabled, writes are grouped together to + * avoid inconsistent state that could cause crashes. + * + * Concretely, when persistent storage is enabled, the persistent versions of + * MutationQueue, RemoteDocumentCache, and others (the mutators) will + * defer their writes into a transaction. Once the local store has completed + * one logical operation, it commits the transaction. + * + * When persistent storage is disabled, the non-persistent versions of the + * mutators ignore the transaction. This short-cut is allowed because + * memory-only storage leaves no state so it cannot be inconsistent. + * + * This simplifies the implementations of the mutators and allows memory-only + * implementations to supplement the persistent ones without requiring any + * special dual-store implementation of Persistence. The cost is that the + * LocalStore needs to be slightly careful about the order of its reads and + * writes in order to avoid relying on being able to read back uncommitted + * writes. + */ +interface Persistence { + /** + * Whether or not this persistence instance has been started. + */ + readonly started: boolean; + readonly referenceDelegate: ReferenceDelegate; + /** Starts persistence. */ + start(): Promise; + /** + * Releases any resources held during eager shutdown. + */ + shutdown(): Promise; + /** + * Registers a listener that gets called when the database receives a + * version change event indicating that it has deleted. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setDatabaseDeletedListener(databaseDeletedListener: () => Promise): void; + /** + * Adjusts the current network state in the client's metadata, potentially + * affecting the primary lease. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setNetworkEnabled(networkEnabled: boolean): void; + /** + * Returns GlobalCache representing a general purpose cache for global values. + */ + getGlobalsCache(): GlobalsCache; + /** + * Returns a MutationQueue representing the persisted mutations for the + * given user. + * + * Note: The implementation is free to return the same instance every time + * this is called for a given user. In particular, the memory-backed + * implementation does this to emulate the persisted implementation to the + * extent possible (e.g. in the case of uid switching from + * sally=>jack=>sally, sally's mutation queue will be preserved). + */ + getMutationQueue(user: User, indexManager: IndexManager): MutationQueue; + /** + * Returns a TargetCache representing the persisted cache of targets. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getTargetCache(): TargetCache; + /** + * Returns a RemoteDocumentCache representing the persisted cache of remote + * documents. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getRemoteDocumentCache(): RemoteDocumentCache; + /** + * Returns a BundleCache representing the persisted cache of loaded bundles. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getBundleCache(): BundleCache; + /** + * Returns an IndexManager instance that manages our persisted query indexes. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getIndexManager(user: User): IndexManager; + /** + * Returns a DocumentOverlayCache representing the documents that are mutated + * locally. + */ + getDocumentOverlayCache(user: User): DocumentOverlayCache; + /** + * Performs an operation inside a persistence transaction. Any reads or writes + * against persistence must be performed within a transaction. Writes will be + * committed atomically once the transaction completes. + * + * Persistence operations are asynchronous and therefore the provided + * transactionOperation must return a PersistencePromise. When it is resolved, + * the transaction will be committed and the Promise returned by this method + * will resolve. + * + * @param action - A description of the action performed by this transaction, + * used for logging. + * @param mode - The underlying mode of the IndexedDb transaction. Can be + * 'readonly', 'readwrite' or 'readwrite-primary'. Transactions marked + * 'readwrite-primary' can only be executed by the primary client. In this + * mode, the transactionOperation will not be run if the primary lease cannot + * be acquired and the returned promise will be rejected with a + * FAILED_PRECONDITION error. + * @param transactionOperation - The operation to run inside a transaction. + * @returns A `Promise` that is resolved once the transaction completes. + */ + runTransaction(action: string, mode: PersistenceTransactionMode, transactionOperation: (transaction: PersistenceTransaction) => PersistencePromise): Promise; +} +/** + * Interface to schedule periodic tasks within SDK. + */ +interface Scheduler { + readonly started: boolean; + start(): void; + stop(): void; +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** The different states of a watch target. */ +type QueryTargetState = 'not-current' | 'current' | 'rejected'; + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * A randomly-generated key assigned to each Firestore instance at startup. + */ +type ClientId = string; +/** + * A `SharedClientState` keeps track of the global state of the mutations + * and query targets for all active clients with the same persistence key (i.e. + * project ID and FirebaseApp name). It relays local changes to other clients + * and updates its local state as new state is observed. + * + * `SharedClientState` is primarily used for synchronization in Multi-Tab + * environments. Each tab is responsible for registering its active query + * targets and mutations. `SharedClientState` will then notify the listener + * assigned to `.syncEngine` for updates to mutations and queries that + * originated in other clients. + * + * To receive notifications, `.syncEngine` and `.onlineStateHandler` has to be + * assigned before calling `start()`. + */ +interface SharedClientState { + onlineStateHandler: ((onlineState: OnlineState) => void) | null; + sequenceNumberHandler: ((sequenceNumber: ListenSequenceNumber) => void) | null; + /** Registers the Mutation Batch ID of a newly pending mutation. */ + addPendingMutation(batchId: BatchId): void; + /** + * Records that a pending mutation has been acknowledged or rejected. + * Called by the primary client to notify secondary clients of mutation + * results as they come back from the backend. + */ + updateMutationState(batchId: BatchId, state: 'acknowledged' | 'rejected', error?: FirestoreError$1): void; + /** + * Associates a new Query Target ID with the local Firestore client. Returns + * the new query state for the query (which can be 'current' if the query is + * already associated with another tab). + * + * If the target id is already associated with local client, the method simply + * returns its `QueryTargetState`. + */ + addLocalQueryTarget(targetId: TargetId, addToActiveTargetIds?: boolean): QueryTargetState; + /** Removes the Query Target ID association from the local client. */ + removeLocalQueryTarget(targetId: TargetId): void; + /** Checks whether the target is associated with the local client. */ + isLocalQueryTarget(targetId: TargetId): boolean; + /** + * Processes an update to a query target. + * + * Called by the primary client to notify secondary clients of document + * changes or state transitions that affect the provided query target. + */ + updateQueryState(targetId: TargetId, state: QueryTargetState, error?: FirestoreError$1): void; + /** + * Removes the target's metadata entry. + * + * Called by the primary client when all clients stopped listening to a query + * target. + */ + clearQueryState(targetId: TargetId): void; + /** + * Gets the active Query Targets IDs for all active clients. + * + * The implementation for this may require O(n) runtime, where 'n' is the size + * of the result set. + */ + getAllActiveQueryTargets(): SortedSet; + /** + * Checks whether the provided target ID is currently being listened to by + * any of the active clients. + * + * The implementation may require O(n*log m) runtime, where 'n' is the number + * of clients and 'm' the number of targets. + */ + isActiveQueryTarget(targetId: TargetId): boolean; + /** + * Starts the SharedClientState, reads existing client data and registers + * listeners for updates to new and existing clients. + */ + start(): Promise; + /** Shuts down the `SharedClientState` and its listeners. */ + shutdown(): void; + /** + * Changes the active user and removes all existing user-specific data. The + * user change does not call back into SyncEngine (for example, no mutations + * will be marked as removed). + */ + handleUserChange(user: User, removedBatchIds: BatchId[], addedBatchIds: BatchId[]): void; + /** Changes the shared online state of all clients. */ + setOnlineState(onlineState: OnlineState): void; + writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void; + /** + * Notifies other clients when remote documents have changed due to loading + * a bundle. + * + * @param collectionGroups The collection groups affected by this bundle. + */ + notifyBundleLoaded(collectionGroups: Set): void; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +type DocumentComparator = (doc1: Document, doc2: Document) => number; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * DocumentSet is an immutable (copy-on-write) collection that holds documents + * in order specified by the provided comparator. We always add a document key + * comparator on top of what is provided to guarantee document equality based on + * the key. + */ +declare class DocumentSet { + /** + * Returns an empty copy of the existing DocumentSet, using the same + * comparator. + */ + static emptySet(oldSet: DocumentSet): DocumentSet; + private comparator; + private keyedMap; + private sortedSet; + /** The default ordering is by key if the comparator is omitted */ + constructor(comp?: DocumentComparator); + has(key: DocumentKey): boolean; + get(key: DocumentKey): Document | null; + first(): Document | null; + last(): Document | null; + isEmpty(): boolean; + /** + * Returns the index of the provided key in the document set, or -1 if the + * document key is not present in the set; + */ + indexOf(key: DocumentKey): number; + get size(): number; + /** Iterates documents in order defined by "comparator" */ + forEach(cb: (doc: Document) => void): void; + /** Inserts or updates a document with the same key */ + add(doc: Document): DocumentSet; + /** Deletes a document with a given key */ + delete(key: DocumentKey): DocumentSet; + isEqual(other: DocumentSet | null | undefined): boolean; + toString(): string; + private copy; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +declare const enum ChangeType { + Added = 0, + Removed = 1, + Modified = 2, + Metadata = 3 +} +interface DocumentViewChange { + type: ChangeType; + doc: Document; +} +declare class ViewSnapshot { + readonly query: Query$2; + readonly docs: DocumentSet; + readonly oldDocs: DocumentSet; + readonly docChanges: DocumentViewChange[]; + readonly mutatedKeys: DocumentKeySet; + readonly fromCache: boolean; + readonly syncStateChanged: boolean; + readonly excludesMetadataChanges: boolean; + readonly hasCachedResults: boolean; + constructor(query: Query$2, docs: DocumentSet, oldDocs: DocumentSet, docChanges: DocumentViewChange[], mutatedKeys: DocumentKeySet, fromCache: boolean, syncStateChanged: boolean, excludesMetadataChanges: boolean, hasCachedResults: boolean); + /** Returns a view snapshot as if all documents in the snapshot were added. */ + static fromInitialDocuments(query: Query$2, documents: DocumentSet, mutatedKeys: DocumentKeySet, fromCache: boolean, hasCachedResults: boolean): ViewSnapshot; + get hasPendingWrites(): boolean; + isEqual(other: ViewSnapshot): boolean; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** The result of a write to the local store. */ +interface LocalWriteResult { + batchId: BatchId; + changes: DocumentMap; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * A readonly view of the local state of all documents we're tracking (i.e. we + * have a cached version in remoteDocumentCache or local mutations for the + * document). The view is computed by applying the mutations in the + * MutationQueue to the RemoteDocumentCache. + */ +declare class LocalDocumentsView { + readonly remoteDocumentCache: RemoteDocumentCache; + readonly mutationQueue: MutationQueue; + readonly documentOverlayCache: DocumentOverlayCache; + readonly indexManager: IndexManager; + constructor(remoteDocumentCache: RemoteDocumentCache, mutationQueue: MutationQueue, documentOverlayCache: DocumentOverlayCache, indexManager: IndexManager); + /** + * Get the local view of the document identified by `key`. + * + * @returns Local view of the document or null if we don't have any cached + * state for it. + */ + getDocument(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; + /** + * Gets the local view of the documents identified by `keys`. + * + * If we don't have cached state for a document in `keys`, a NoDocument will + * be stored for that key in the resulting set. + */ + getDocuments(transaction: PersistenceTransaction, keys: DocumentKeySet): PersistencePromise; + /** + * Similar to `getDocuments`, but creates the local view from the given + * `baseDocs` without retrieving documents from the local store. + * + * @param transaction - The transaction this operation is scoped to. + * @param docs - The documents to apply local mutations to get the local views. + * @param existenceStateChanged - The set of document keys whose existence state + * is changed. This is useful to determine if some documents overlay needs + * to be recalculated. + */ + getLocalViewOfDocuments(transaction: PersistenceTransaction, docs: MutableDocumentMap, existenceStateChanged?: DocumentKeySet): PersistencePromise; + /** + * Gets the overlayed documents for the given document map, which will include + * the local view of those documents and a `FieldMask` indicating which fields + * are mutated locally, `null` if overlay is a Set or Delete mutation. + */ + getOverlayedDocuments(transaction: PersistenceTransaction, docs: MutableDocumentMap): PersistencePromise; + /** + * Fetches the overlays for {@code docs} and adds them to provided overlay map + * if the map does not already contain an entry for the given document key. + */ + private populateOverlays; + /** + * Computes the local view for the given documents. + * + * @param docs - The documents to compute views for. It also has the base + * version of the documents. + * @param overlays - The overlays that need to be applied to the given base + * version of the documents. + * @param existenceStateChanged - A set of documents whose existence states + * might have changed. This is used to determine if we need to re-calculate + * overlays from mutation queues. + * @return A map represents the local documents view. + */ + computeViews(transaction: PersistenceTransaction, docs: MutableDocumentMap, overlays: OverlayMap, existenceStateChanged: DocumentKeySet): PersistencePromise; + private recalculateAndSaveOverlays; + /** + * Recalculates overlays by reading the documents from remote document cache + * first, and saves them after they are calculated. + */ + recalculateAndSaveOverlaysForDocumentKeys(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise>; + /** + * Performs a query against the local view of all documents. + * + * @param transaction - The persistence transaction. + * @param query - The query to match documents against. + * @param offset - Read time and key to start scanning by (exclusive). + * @param context - A optional tracker to keep a record of important details + * during database local query execution. + */ + getDocumentsMatchingQuery(transaction: PersistenceTransaction, query: Query$2, offset: IndexOffset, context?: QueryContext): PersistencePromise; + /** + * Given a collection group, returns the next documents that follow the provided offset, along + * with an updated batch ID. + * + *

The documents returned by this method are ordered by remote version from the provided + * offset. If there are no more remote documents after the provided offset, documents with + * mutations in order of batch id from the offset are returned. Since all documents in a batch are + * returned together, the total number of documents returned can exceed {@code count}. + * + * @param transaction + * @param collectionGroup The collection group for the documents. + * @param offset The offset to index into. + * @param count The number of documents to return + * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id. + */ + getNextDocuments(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset, count: number): PersistencePromise; + private getDocumentsMatchingDocumentQuery; + private getDocumentsMatchingCollectionGroupQuery; + private getDocumentsMatchingCollectionQuery; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +interface LocalStore { + collectGarbage(garbageCollector: LruGarbageCollector): Promise; + /** Manages the list of active field and collection indices. */ + indexManager: IndexManager; + /** + * The "local" view of all documents (layering mutationQueue on top of + * remoteDocumentCache). + */ + localDocuments: LocalDocumentsView; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Datastore and its related methods are a wrapper around the external Google + * Cloud Datastore grpc API, which provides an interface that is more convenient + * for the rest of the client SDK architecture to consume. + */ +declare abstract class Datastore { + abstract terminate(): void; + abstract serializer: JsonProtoSerializer; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * An interface that describes the actions the RemoteStore needs to perform on + * a cooperating synchronization engine. + */ +interface RemoteSyncer { + /** + * Applies one remote event to the sync engine, notifying any views of the + * changes, and releasing any pending mutation batches that would become + * visible because of the snapshot version the remote event contains. + */ + applyRemoteEvent?(remoteEvent: RemoteEvent): Promise; + /** + * Rejects the listen for the given targetID. This can be triggered by the + * backend for any active target. + * + * @param targetId - The targetID corresponds to one previously initiated by + * the user as part of TargetData passed to listen() on RemoteStore. + * @param error - A description of the condition that has forced the rejection. + * Nearly always this will be an indication that the user is no longer + * authorized to see the data matching the target. + */ + rejectListen?(targetId: TargetId, error: FirestoreError$1): Promise; + /** + * Applies the result of a successful write of a mutation batch to the sync + * engine, emitting snapshots in any views that the mutation applies to, and + * removing the batch from the mutation queue. + */ + applySuccessfulWrite?(result: MutationBatchResult): Promise; + /** + * Rejects the batch, removing the batch from the mutation queue, recomputing + * the local view of any documents affected by the batch and then, emitting + * snapshots with the reverted value. + */ + rejectFailedWrite?(batchId: BatchId, error: FirestoreError$1): Promise; + /** + * Returns the set of remote document keys for the given target ID. This list + * includes the documents that were assigned to the target when we received + * the last snapshot. + */ + getRemoteKeysForTarget?(targetId: TargetId): DocumentKeySet; + /** + * Updates all local state to match the pending mutations for the given user. + * May be called repeatedly for the same user. + */ + handleCredentialChange?(user: User): Promise; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * RemoteStore - An interface to remotely stored data, basically providing a + * wrapper around the Datastore that is more reliable for the rest of the + * system. + * + * RemoteStore is responsible for maintaining the connection to the server. + * - maintaining a list of active listens. + * - reconnecting when the connection is dropped. + * - resuming all the active listens on reconnect. + * + * RemoteStore handles all incoming events from the Datastore. + * - listening to the watch stream and repackaging the events as RemoteEvents + * - notifying SyncEngine of any changes to the active listens. + * + * RemoteStore takes writes from other components and handles them reliably. + * - pulling pending mutations from LocalStore and sending them to Datastore. + * - retrying mutations that failed because of network problems. + * - acking mutations to the SyncEngine once they are accepted or rejected. + */ +interface RemoteStore { + /** + * SyncEngine to notify of watch and write events. This must be set + * immediately after construction. + */ + remoteSyncer: RemoteSyncer; +} + +/** + * A utility class for generating unique alphanumeric IDs of a specified length. + * + * @internal + * Exported internally for testing purposes. + */ +declare class AutoId { + static newId(): string; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * EventManager is responsible for mapping queries to query event emitters. + * It handles "fan-out". -- Identical queries will re-use the same watch on the + * backend. + * + * PORTING NOTE: On Web, EventManager `onListen` and `onUnlisten` need to be + * assigned to SyncEngine's `listen()` and `unlisten()` API before usage. This + * allows users to tree-shake the Watch logic. + */ +interface EventManager { + onListen?: (query: Query$2, enableRemoteListen: boolean) => Promise; + onUnlisten?: (query: Query$2, disableRemoteListen: boolean) => Promise; + onFirstRemoteStoreListen?: (query: Query$2) => Promise; + onLastRemoteStoreUnlisten?: (query: Query$2) => Promise; + terminate(): void; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * SyncEngine is the central controller in the client SDK architecture. It is + * the glue code between the EventManager, LocalStore, and RemoteStore. Some of + * SyncEngine's responsibilities include: + * 1. Coordinating client requests and remote events between the EventManager + * and the local and remote data stores. + * 2. Managing a View object for each query, providing the unified view between + * the local and remote data stores. + * 3. Notifying the RemoteStore when the LocalStore has new mutations in its + * queue that need sending to the backend. + * + * The SyncEngine’s methods should only ever be called by methods running in the + * global async queue. + * + * PORTING NOTE: On Web, SyncEngine does not have an explicit subscribe() + * function. Instead, it directly depends on EventManager's tree-shakeable API + * (via `ensureWatchStream()`). + */ +interface SyncEngine { + isPrimaryClient: boolean; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +type Kind = 'memory' | 'persistent'; +interface ComponentConfiguration { + asyncQueue: AsyncQueue; + databaseInfo: DatabaseInfo; + authCredentials: CredentialsProvider; + appCheckCredentials: CredentialsProvider; + clientId: ClientId; + initialUser: User; + maxConcurrentLimboResolutions: number; +} +interface OfflineComponentProviderFactory { + build(onlineComponents: OnlineComponentProvider): OfflineComponentProvider; +} +/** + * Initializes and wires components that are needed to interface with the local + * cache. Implementations override `initialize()` to provide all components. + */ +interface OfflineComponentProvider { + readonly kind: Kind; + persistence: Persistence; + sharedClientState: SharedClientState; + localStore: LocalStore; + gcScheduler: Scheduler | null; + indexBackfillerScheduler: Scheduler | null; + synchronizeTabs: boolean; + initialize(cfg: ComponentConfiguration): Promise; + terminate(): Promise; +} +interface OnlineComponentProviderFactory { + build(): OnlineComponentProvider; +} +/** + * Initializes and wires the components that are needed to interface with the + * network. + */ +declare class OnlineComponentProvider { + static readonly provider: OnlineComponentProviderFactory; + protected localStore: LocalStore; + protected sharedClientState: SharedClientState; + datastore: Datastore; + eventManager: EventManager; + remoteStore: RemoteStore; + syncEngine: SyncEngine; + initialize(offlineComponentProvider: OfflineComponentProvider, cfg: ComponentConfiguration): Promise; + createEventManager(cfg: ComponentConfiguration): EventManager; + createDatastore(cfg: ComponentConfiguration): Datastore; + createRemoteStore(cfg: ComponentConfiguration): RemoteStore; + createSyncEngine(cfg: ComponentConfiguration, startAsPrimary: boolean): SyncEngine; + terminate(): Promise; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Represents the state of bundle loading tasks. + * + * Both 'Error' and 'Success' are sinking state: task will abort or complete and there will + * be no more updates after they are reported. + */ +type TaskState = 'Error' | 'Running' | 'Success'; +/** + * Represents a progress update or a final state from loading bundles. + */ +interface LoadBundleTaskProgress { + /** How many documents have been loaded. */ + documentsLoaded: number; + /** How many documents are in the bundle being loaded. */ + totalDocuments: number; + /** How many bytes have been loaded. */ + bytesLoaded: number; + /** How many bytes are in the bundle being loaded. */ + totalBytes: number; + /** Current task state. */ + taskState: TaskState; +} +/** + * Represents the task of loading a Firestore bundle. It provides progress of bundle + * loading, as well as task completion and error events. + * + * The API is compatible with `Promise`. + */ +declare class LoadBundleTask implements PromiseLike { + private _progressObserver; + private _taskCompletionResolver; + private _lastProgress; + /** + * Registers functions to listen to bundle loading progress events. + * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur + * each time a Firestore document is loaded from the bundle. + * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the + * error, and there should be no more updates after this. + * @param complete - Called when the loading task is complete. + */ + onProgress(next?: (progress: LoadBundleTaskProgress) => unknown, error?: (err: Error) => unknown, complete?: () => void): void; + /** + * Implements the `Promise.catch` interface. + * + * @param onRejected - Called when an error occurs during bundle loading. + */ + catch(onRejected: (a: Error) => R | PromiseLike): Promise; + /** + * Implements the `Promise.then` interface. + * + * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update. + * The update will always have its `taskState` set to `"Success"`. + * @param onRejected - Called when an error occurs during bundle loading. + */ + then(onFulfilled?: (a: LoadBundleTaskProgress) => T | PromiseLike, onRejected?: (a: Error) => R | PromiseLike): Promise; + /** + * Notifies all observers that bundle loading has completed, with a provided + * `LoadBundleTaskProgress` object. + * + * @private + */ + _completeWith(progress: LoadBundleTaskProgress): void; + /** + * Notifies all observers that bundle loading has failed, with a provided + * `Error` as the reason. + * + * @private + */ + _failWith(error: FirestoreError$1): void; + /** + * Notifies a progress update of loading a bundle. + * @param progress - The new progress. + * + * @private + */ + _updateProgress(progress: LoadBundleTaskProgress): void; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +interface ParseContext { + readonly databaseId: DatabaseId; + readonly ignoreUndefinedProperties: boolean; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Provides an in-memory cache to the SDK. This is the default cache unless explicitly + * configured otherwise. + * + * To use, create an instance using the factory function {@link memoryLocalCache()}, then + * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using + * the settings object. + */ +type MemoryLocalCache = { + kind: 'memory'; + /** + * @internal + */ + _onlineComponentProvider: OnlineComponentProviderFactory; + /** + * @internal + */ + _offlineComponentProvider: OfflineComponentProviderFactory; +}; +/** + * Provides a persistent cache backed by IndexedDb to the SDK. + * + * To use, create an instance using the factory function {@link persistentLocalCache()}, then + * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using + * the settings object. + */ +type PersistentLocalCache = { + kind: 'persistent'; + /** + * @internal + */ + _onlineComponentProvider: OnlineComponentProviderFactory; + /** + * @internal + */ + _offlineComponentProvider: OfflineComponentProviderFactory; +}; +/** + * Union type from all supported SDK cache layer. + */ +type FirestoreLocalCache = MemoryLocalCache | PersistentLocalCache; +/** + * Union type from all support garbage collectors for memory local cache. + */ +type MemoryGarbageCollector = MemoryEagerGarbageCollector | MemoryLruGarbageCollector; +/** + * A garbage collector deletes documents whenever they are not part of any + * active queries, and have no local mutations attached to them. + * + * This collector tries to ensure lowest memory footprints from the SDK, + * at the risk of documents not being cached for offline queries or for + * direct queries to the cache. + * + * Use factory function {@link memoryEagerGarbageCollector()} to create an + * instance of this collector. + */ +type MemoryEagerGarbageCollector = { + kind: 'memoryEager'; + /** + * @internal + */ + _offlineComponentProvider: OfflineComponentProviderFactory; +}; +/** + * A garbage collector deletes Least-Recently-Used documents in multiple + * batches. + * + * This collector is configured with a target size, and will only perform + * collection when the cached documents exceed the target size. It avoids + * querying backend repeated for the same query or document, at the risk + * of having a larger memory footprint. + * + * Use factory function {@link memoryLruGarbageCollector()} to create a + * instance of this collector. + */ +type MemoryLruGarbageCollector = { + kind: 'memoryLru'; + /** + * @internal + */ + _offlineComponentProvider: OfflineComponentProviderFactory; +}; +/** + * Creates an instance of `MemoryEagerGarbageCollector`. This is also the + * default garbage collector unless it is explicitly specified otherwise. + */ +declare function memoryEagerGarbageCollector(): MemoryEagerGarbageCollector; +/** + * Creates an instance of `MemoryLruGarbageCollector`. + * + * A target size can be specified as part of the setting parameter. The + * collector will start deleting documents once the cache size exceeds + * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes). + */ +declare function memoryLruGarbageCollector(settings?: { + cacheSizeBytes?: number; +}): MemoryLruGarbageCollector; +/** + * An settings object to configure an `MemoryLocalCache` instance. + */ +type MemoryCacheSettings = { + /** + * The garbage collector to use, for the memory cache layer. + * A `MemoryEagerGarbageCollector` is used when this is undefined. + */ + garbageCollector?: MemoryGarbageCollector; +}; +/** + * Creates an instance of `MemoryLocalCache`. The instance can be set to + * `FirestoreSettings.cache` to tell the SDK which cache layer to use. + */ +declare function memoryLocalCache(settings?: MemoryCacheSettings): MemoryLocalCache; +/** + * An settings object to configure an `PersistentLocalCache` instance. + * + * Persistent cache cannot be used in a Node.js environment. + */ +type PersistentCacheSettings = { + /** + * An approximate cache size threshold for the on-disk data. If the cache + * grows beyond this size, Firestore will start removing data that hasn't been + * recently used. The SDK does not guarantee that the cache will stay below + * that size, only that if the cache exceeds the given size, cleanup will be + * attempted. + * + * The default value is 40 MB. The threshold must be set to at least 1 MB, and + * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection. + */ + cacheSizeBytes?: number; + /** + * Specifies how multiple tabs/windows will be managed by the SDK. + */ + tabManager?: PersistentTabManager; +}; +/** + * Creates an instance of `PersistentLocalCache`. The instance can be set to + * `FirestoreSettings.cache` to tell the SDK which cache layer to use. + * + * Persistent cache cannot be used in a Node.js environment. + */ +declare function persistentLocalCache(settings?: PersistentCacheSettings): PersistentLocalCache; +/** + * A tab manager supporting only one tab, no synchronization will be + * performed across tabs. + */ +type PersistentSingleTabManager = { + kind: 'persistentSingleTab'; + /** + * @internal + */ + _initialize: (settings: Omit | undefined) => void; + /** + * @internal + */ + _onlineComponentProvider?: OnlineComponentProviderFactory; + /** + * @internal + */ + _offlineComponentProvider?: OfflineComponentProviderFactory; +}; +/** + * A tab manager supporting multiple tabs. SDK will synchronize queries and + * mutations done across all tabs using the SDK. + */ +type PersistentMultipleTabManager = { + kind: 'PersistentMultipleTab'; + /** + * @internal + */ + _initialize: (settings: Omit) => void; + /** + * @internal + */ + _onlineComponentProvider?: OnlineComponentProviderFactory; + /** + * @internal + */ + _offlineComponentProvider?: OfflineComponentProviderFactory; +}; +/** + * A union of all available tab managers. + */ +type PersistentTabManager = PersistentSingleTabManager | PersistentMultipleTabManager; +/** + * Type to configure an `PersistentSingleTabManager` instance. + */ +type PersistentSingleTabManagerSettings = { + /** + * Whether to force-enable persistent (IndexedDB) cache for the client. This + * cannot be used with multi-tab synchronization and is primarily intended for + * use with Web Workers. Setting this to `true` will enable IndexedDB, but cause + * other tabs using IndexedDB cache to fail. + */ + forceOwnership?: boolean; +}; +/** + * Creates an instance of `PersistentSingleTabManager`. + * + * @param settings Configures the created tab manager. + */ +declare function persistentSingleTabManager(settings: PersistentSingleTabManagerSettings | undefined): PersistentSingleTabManager; +/** + * Creates an instance of `PersistentMultipleTabManager`. + */ +declare function persistentMultipleTabManager(): PersistentMultipleTabManager; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Specifies custom configurations for your Cloud Firestore instance. + * You must set these before invoking any other methods. + */ +interface FirestoreSettings$1 { + /** The hostname to connect to. */ + host?: string; + /** Whether to use SSL when connecting. */ + ssl?: boolean; + /** + * Whether to skip nested properties that are set to `undefined` during + * object serialization. If set to `true`, these properties are skipped + * and not written to Firestore. If set to `false` or omitted, the SDK + * throws an exception when it encounters properties of type `undefined`. + */ + ignoreUndefinedProperties?: boolean; +} +/** + * @internal + * Undocumented, private additional settings not exposed in our public API. + */ +interface PrivateSettings extends FirestoreSettings$1 { + credentials?: CredentialsSettings; + cacheSizeBytes?: number; + experimentalForceLongPolling?: boolean; + experimentalAutoDetectLongPolling?: boolean; + experimentalLongPollingOptions?: ExperimentalLongPollingOptions; + useFetchStreams?: boolean; + emulatorOptions?: { + mockUserToken?: EmulatorMockTokenOptions | string; + }; + localCache?: FirestoreLocalCache; +} +/** + * A concrete type describing all the values that can be applied via a + * user-supplied `FirestoreSettings` object. This is a separate type so that + * defaults can be supplied and the value can be checked for equality. + */ +declare class FirestoreSettingsImpl { + /** The hostname to connect to. */ + readonly host: string; + /** Whether to use SSL when connecting. */ + readonly ssl: boolean; + readonly cacheSizeBytes: number; + readonly experimentalForceLongPolling: boolean; + readonly experimentalAutoDetectLongPolling: boolean; + readonly experimentalLongPollingOptions: ExperimentalLongPollingOptions; + readonly ignoreUndefinedProperties: boolean; + readonly useFetchStreams: boolean; + readonly localCache?: FirestoreLocalCache; + readonly isUsingEmulator: boolean; + credentials?: any; + constructor(settings: PrivateSettings); + isEqual(other: FirestoreSettingsImpl): boolean; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * An interface implemented by FirebaseFirestore that provides compatibility + * with the usage in this file. + * + * This interface mainly exists to remove a cyclic dependency. + */ +interface FirestoreService extends _FirebaseService { + _authCredentials: CredentialsProvider; + _appCheckCredentials: CredentialsProvider; + _persistenceKey: string; + _databaseId: DatabaseId; + _terminated: boolean; + _freezeSettings(): FirestoreSettingsImpl; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +declare module '@firebase/component' { + interface NameServiceMapping { + 'firestore/lite': Firestore$1; + } +} +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ +declare class Firestore$1 implements FirestoreService { + _authCredentials: CredentialsProvider; + _appCheckCredentials: CredentialsProvider; + readonly _databaseId: DatabaseId; + readonly _app?: FirebaseApp | undefined; + /** + * Whether it's a Firestore or Firestore Lite instance. + */ + type: 'firestore-lite' | 'firestore'; + readonly _persistenceKey: string; + private _settings; + private _settingsFrozen; + private _emulatorOptions; + private _terminateTask; + /** @hideconstructor */ + constructor(_authCredentials: CredentialsProvider, _appCheckCredentials: CredentialsProvider, _databaseId: DatabaseId, _app?: FirebaseApp | undefined); + /** + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service + * instance. + */ + get app(): FirebaseApp; + get _initialized(): boolean; + get _terminated(): boolean; + _setSettings(settings: PrivateSettings): void; + _getSettings(): FirestoreSettingsImpl; + _getEmulatorOptions(): { + mockUserToken?: EmulatorMockTokenOptions | string; + }; + _freezeSettings(): FirestoreSettingsImpl; + _delete(): Promise; + _restart(): Promise; + /** Returns a JSON-serializable representation of this `Firestore` instance. */ + toJSON(): object; + /** + * Terminates all components used by this client. Subclasses can override + * this method to clean up their own dependencies, but must also call this + * method. + * + * Only ever called once. + */ + protected _terminate(): Promise; +} +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ +declare function connectFirestoreEmulator(firestore: Firestore$1, host: string, port: number, options?: { + mockUserToken?: EmulatorMockTokenOptions | string; +}): void; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Sentinel values that can be used when writing document fields with `set()` + * or `update()`. + */ +declare abstract class FieldValue { + _methodName: string; + /** + * @param _methodName - The public API endpoint that returns this class. + * @hideconstructor + */ + constructor(_methodName: string); + /** Compares `FieldValue`s for equality. */ + abstract isEqual(other: FieldValue): boolean; + abstract _toFieldTransform(context: ParseContext): FieldTransform | null; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * A `FieldPath` refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + * + * Create a `FieldPath` by providing field names. If more than one field + * name is provided, the path will point to a nested field in a document. + */ +declare class FieldPath { + /** Internal representation of a Firestore field path. */ + readonly _internalPath: FieldPath$2; + /** + * Creates a `FieldPath` from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames - A list of field names. + */ + constructor(...fieldNames: string[]); + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other - The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ + isEqual(other: FieldPath): boolean; +} +/** + * Returns a special sentinel `FieldPath` to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ +declare function documentId(): FieldPath; + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link vector}. + * + * @class VectorValue + */ +declare class VectorValue { + private readonly _values; + /** + * @private + * @internal + */ + constructor(values: number[] | undefined); + /** + * Returns a copy of the raw number array form of the vector. + */ + toArray(): number[]; + /** + * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise. + */ + isEqual(other: VectorValue): boolean; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + vectorValues: Property<"object">; + }; + /** + * Returns a JSON-serializable representation of this `VectorValue` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}. + * + * @param json a JSON object represention of a `VectorValue` instance. + * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): VectorValue; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +type ServerTimestampBehavior = 'estimate' | 'previous' | 'none'; +/** + * Converts Firestore's internal types to the JavaScript types that we expose + * to the user. + * + * @internal + */ +declare abstract class AbstractUserDataWriter { + convertValue(value: Value, serverTimestampBehavior?: ServerTimestampBehavior): unknown; + private convertObject; + /** + * @internal + */ + convertObjectMap(fields: ApiClientObjectMap | undefined, serverTimestampBehavior?: ServerTimestampBehavior): DocumentData$1; + /** + * @internal + */ + convertVectorValue(mapValue: MapValue): VectorValue; + private convertGeoPoint; + private convertArray; + private convertServerTimestamp; + private convertTimestamp; + protected convertDocumentKey(name: string, expectedDatabaseId: DatabaseId): DocumentKey; + protected abstract convertReference(name: string): unknown; + protected abstract convertBytes(bytes: ByteString): unknown; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Converter used by `withConverter()` to transform user objects of type + * `AppModelType` into Firestore data of type `DbModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * In this context, an "AppModel" is a class that is used in an application to + * package together related information and functionality. Such a class could, + * for example, have properties with complex, nested data types, properties used + * for memoization, properties of types not supported by Firestore (such as + * `symbol` and `bigint`), and helper functions that perform compound + * operations. Such classes are not suitable and/or possible to store into a + * Firestore database. Instead, instances of such classes need to be converted + * to "plain old JavaScript objects" (POJOs) with exclusively primitive + * properties, potentially nested inside other POJOs or arrays of POJOs. In this + * context, this type is referred to as the "DbModel" and would be an object + * suitable for persisting into Firestore. For convenience, applications can + * implement `FirestoreDataConverter` and register the converter with Firestore + * objects, such as `DocumentReference` or `Query`, to automatically convert + * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel` + * to `AppModel` when retrieving from Firestore. + * + * @example + * + * Simple Example + * + * ```typescript + * const numberConverter = { + * toFirestore(value: WithFieldValue) { + * return { value }; + * }, + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) { + * return snapshot.data(options).value as number; + * } + * }; + * + * async function simpleDemo(db: Firestore): Promise { + * const documentRef = doc(db, 'values/value123').withConverter(numberConverter); + * + * // converters are used with `setDoc`, `addDoc`, and `getDoc` + * await setDoc(documentRef, 42); + * const snapshot1 = await getDoc(documentRef); + * assertEqual(snapshot1.data(), 42); + * + * // converters are not used when writing data with `updateDoc` + * await updateDoc(documentRef, { value: 999 }); + * const snapshot2 = await getDoc(documentRef); + * assertEqual(snapshot2.data(), 999); + * } + * ``` + * + * Advanced Example + * + * ```typescript + * // The Post class is a model that is used by our application. + * // This class may have properties and methods that are specific + * // to our application execution, which do not need to be persisted + * // to Firestore. + * class Post { + * constructor( + * readonly title: string, + * readonly author: string, + * readonly lastUpdatedMillis: number + * ) {} + * toString(): string { + * return `${this.title} by ${this.author}`; + * } + * } + * + * // The PostDbModel represents how we want our posts to be stored + * // in Firestore. This DbModel has different properties (`ttl`, + * // `aut`, and `lut`) from the Post class we use in our application. + * interface PostDbModel { + * ttl: string; + * aut: { firstName: string; lastName: string }; + * lut: Timestamp; + * } + * + * // The `PostConverter` implements `FirestoreDataConverter` and specifies + * // how the Firestore SDK can convert `Post` objects to `PostDbModel` + * // objects and vice versa. + * class PostConverter implements FirestoreDataConverter { + * toFirestore(post: WithFieldValue): WithFieldValue { + * return { + * ttl: post.title, + * aut: this._autFromAuthor(post.author), + * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis) + * }; + * } + * + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post { + * const data = snapshot.data(options) as PostDbModel; + * const author = `${data.aut.firstName} ${data.aut.lastName}`; + * return new Post(data.ttl, author, data.lut.toMillis()); + * } + * + * _autFromAuthor( + * author: string | FieldValue + * ): { firstName: string; lastName: string } | FieldValue { + * if (typeof author !== 'string') { + * // `author` is a FieldValue, so just return it. + * return author; + * } + * const [firstName, lastName] = author.split(' '); + * return {firstName, lastName}; + * } + * + * _lutFromLastUpdatedMillis( + * lastUpdatedMillis: number | FieldValue + * ): Timestamp | FieldValue { + * if (typeof lastUpdatedMillis !== 'number') { + * // `lastUpdatedMillis` must be a FieldValue, so just return it. + * return lastUpdatedMillis; + * } + * return Timestamp.fromMillis(lastUpdatedMillis); + * } + * } + * + * async function advancedDemo(db: Firestore): Promise { + * // Create a `DocumentReference` with a `FirestoreDataConverter`. + * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter()); + * + * // The `data` argument specified to `setDoc()` is type checked by the + * // TypeScript compiler to be compatible with `Post`. Since the `data` + * // argument is typed as `WithFieldValue` rather than just `Post`, + * // this allows properties of the `data` argument to also be special + * // Firestore values that perform server-side mutations, such as + * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`. + * await setDoc(documentRef, { + * title: 'My Life', + * author: 'Foo Bar', + * lastUpdatedMillis: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `setDoc()` is _not_ compatible with `WithFieldValue`. This + * // type checking prevents the caller from specifying objects with incorrect + * // properties or property values. + * // @ts-expect-error "Argument of type { ttl: string; } is not assignable + * // to parameter of type WithFieldValue" + * await setDoc(documentRef, { ttl: 'The Title' }); + * + * // When retrieving a document with `getDoc()` the `DocumentSnapshot` + * // object's `data()` method returns a `Post`, rather than a generic object, + * // which would have been returned if the `DocumentReference` did _not_ have a + * // `FirestoreDataConverter` attached to it. + * const snapshot1: DocumentSnapshot = await getDoc(documentRef); + * const post1: Post = snapshot1.data()!; + * if (post1) { + * assertEqual(post1.title, 'My Life'); + * assertEqual(post1.author, 'Foo Bar'); + * } + * + * // The `data` argument specified to `updateDoc()` is type checked by the + * // TypeScript compiler to be compatible with `PostDbModel`. Note that + * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`, + * // the `data` argument to `updateDoc()` must be compatible with + * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed + * // as `WithFieldValue` rather than just `PostDbModel`, this + * // allows properties of the `data` argument to also be those special + * // Firestore values, like `arrayRemove()`, `deleteField()`, and + * // `serverTimestamp()`. + * await updateDoc(documentRef, { + * 'aut.firstName': 'NewFirstName', + * lut: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `updateDoc()` is _not_ compatible with `WithFieldValue`. + * // This type checking prevents the caller from specifying objects with + * // incorrect properties or property values. + * // @ts-expect-error "Argument of type { title: string; } is not assignable + * // to parameter of type WithFieldValue" + * await updateDoc(documentRef, { title: 'New Title' }); + * const snapshot2: DocumentSnapshot = await getDoc(documentRef); + * const post2: Post = snapshot2.data()!; + * if (post2) { + * assertEqual(post2.title, 'My Life'); + * assertEqual(post2.author, 'NewFirstName Bar'); + * } + * } + * ``` + */ +interface FirestoreDataConverter$1 { + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link @firebase/firestore/lite#(setDoc:1)}, + * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and + * {@link @firebase/firestore/lite#(Transaction.set:1)}. + * + * The `WithFieldValue` type extends `T` to also allow FieldValues such as + * {@link (deleteField:1)} to be used as property values. + */ + toFirestore(modelObject: WithFieldValue): WithFieldValue; + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link @firebase/firestore/lite#(setDoc:1)}, + * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and + * {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true` + * or `mergeFields`. + * + * The `PartialWithFieldValue` type extends `Partial` to allow + * FieldValues such as {@link (arrayUnion:1)} to be used as property values. + * It also supports nested `Partial` by allowing nested fields to be + * omitted. + */ + toFirestore(modelObject: PartialWithFieldValue, options: SetOptions): PartialWithFieldValue; + /** + * Called by the Firestore SDK to convert Firestore data into an object of + * type `AppModelType`. You can access your data by calling: + * `snapshot.data()`. + * + * + * Generally, the data returned from `snapshot.data()` can be cast to + * `DbModelType`; however, this is not guaranteed because Firestore does not + * enforce a schema on the database. For example, writes from a previous + * version of the application or writes from another client that did not use a + * type converter could have written data with different properties and/or + * property types. The implementation will need to choose whether to + * gracefully recover from non-conforming data or throw an error. + * + * @param snapshot - A `QueryDocumentSnapshot` containing your data and + * metadata. + */ + fromFirestore(snapshot: QueryDocumentSnapshot$1): AppModelType; +} +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ +declare class DocumentSnapshot$1 { + _firestore: Firestore$1; + _userDataWriter: AbstractUserDataWriter; + _key: DocumentKey; + _document: Document | null; + _converter: UntypedFirestoreDataConverter | null; + /** @hideconstructor protected */ + constructor(_firestore: Firestore$1, _userDataWriter: AbstractUserDataWriter, _key: DocumentKey, _document: Document | null, _converter: UntypedFirestoreDataConverter | null); + /** Property of the `DocumentSnapshot` that provides the document's ID. */ + get id(): string; + /** + * The `DocumentReference` for the document included in the `DocumentSnapshot`. + */ + get ref(): DocumentReference; + /** + * Signals whether or not the document at the snapshot's location exists. + * + * @returns true if the document exists. + */ + exists(): this is QueryDocumentSnapshot$1; + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * @returns An `Object` containing all fields in the document or `undefined` + * if the document doesn't exist. + */ + data(): AppModelType | undefined; + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + get(fieldPath: string | FieldPath): any; +} +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ +declare class QueryDocumentSnapshot$1 extends DocumentSnapshot$1 { + /** + * Retrieves all fields in the document as an `Object`. + * + * @override + * @returns An `Object` containing all fields in the document. + */ + data(): AppModelType; +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * These types primarily exist to support the `UpdateData`, + * `WithFieldValue`, and `PartialWithFieldValue` types and are not consumed + * directly by the end developer. + */ +/** Primitive types. */ +type Primitive = string | number | boolean | undefined | null; +/** + * For each field (e.g. 'bar'), find all nested keys (e.g. {'bar.baz': T1, + * 'bar.qux': T2}). Intersect them together to make a single map containing + * all possible keys that are all marked as optional + */ +type NestedUpdateFields> = UnionToIntersection<{ + [K in keyof T & string]: ChildUpdateFields; +}[keyof T & string]>; +/** + * Helper for calculating the nested fields for a given type T1. This is needed + * to distribute union types such as `undefined | {...}` (happens for optional + * props) or `{a: A} | {b: B}`. + * + * In this use case, `V` is used to distribute the union types of `T[K]` on + * `Record`, since `T[K]` is evaluated as an expression and not distributed. + * + * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types + */ +type ChildUpdateFields = V extends Record ? AddPrefixToKeys> : never; +/** + * Returns a new map where every key is prefixed with the outer key appended + * to a dot. + */ +type AddPrefixToKeys> = { + [K in keyof T & string as `${Prefix}.${K}`]+?: string extends K ? any : T[K]; +}; +/** + * Given a union type `U = T1 | T2 | ...`, returns an intersected type + * `(T1 & T2 & ...)`. + * + * Uses distributive conditional types and inference from conditional types. + * This works because multiple candidates for the same type variable in + * contra-variant positions causes an intersection type to be inferred. + * https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-inference-in-conditional-types + * https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type + */ +type UnionToIntersection = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to + * values. + */ +interface DocumentData { + /** A mapping between a field and its value. */ + [field: string]: any; +} +/** + * Similar to TypeScript's `Partial`, but allows nested fields to be + * omitted and FieldValues to be passed in as property values. + */ +type PartialWithFieldValue = Partial | (T extends Primitive ? T : T extends {} ? { + [K in keyof T]?: PartialWithFieldValue | FieldValue; +} : never); +/** + * Allows FieldValues to be passed in as a property value while maintaining + * type safety. + */ +type WithFieldValue = T | (T extends Primitive ? T : T extends {} ? { + [K in keyof T]: WithFieldValue | FieldValue; +} : never); +/** + * Update data (for use with {@link (updateDoc:1)}) that consists of field paths + * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots + * reference nested fields within the document. FieldValues can be passed in + * as property values. + */ +type UpdateData = T extends Primitive ? T : T extends {} ? { + [K in keyof T]?: UpdateData | FieldValue; +} & NestedUpdateFields : Partial; +/** + * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link + * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be + * configured to perform granular merges instead of overwriting the target + * documents in their entirety by providing a `SetOptions` with `merge: true`. + * + * @param merge - Changes the behavior of a `setDoc()` call to only replace the + * values specified in its data argument. Fields omitted from the `setDoc()` + * call remain untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace + * the specified field paths. Any field path that is not specified is ignored + * and remains untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + */ +type SetOptions = { + readonly merge?: boolean; +} | { + readonly mergeFields?: Array; +}; +/** + * A `Query` refers to a query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ +declare class Query { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter$1 | null; + readonly _query: Query$2; + /** The type of this Firestore reference. */ + readonly type: 'query' | 'collection'; + /** + * The `Firestore` instance for the Firestore database (useful for performing + * transactions, etc.). + */ + readonly firestore: Firestore$1; + /** @hideconstructor protected */ + constructor(firestore: Firestore$1, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter: FirestoreDataConverter$1 | null, _query: Query$2); + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `Query` that does not use a + * converter. + */ + withConverter(converter: null): Query; + /** + * Applies a custom data converter to this query, allowing you to use your own + * custom model objects with Firestore. When you call {@link getDocs} with + * the returned query, the provided converter will convert between Firestore + * data of type `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `Query` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter$1): Query; +} +/** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. + */ +declare class DocumentReference { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter$1 | null; + readonly _key: DocumentKey; + /** The type of this Firestore reference. */ + readonly type = "document"; + /** + * The {@link Firestore} instance the document is in. + * This is useful for performing transactions, for example. + */ + readonly firestore: Firestore$1; + /** @hideconstructor */ + constructor(firestore: Firestore$1, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter: FirestoreDataConverter$1 | null, _key: DocumentKey); + get _path(): ResourcePath; + /** + * The document's identifier within its collection. + */ + get id(): string; + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ + get path(): string; + /** + * The collection this `DocumentReference` belongs to. + */ + get parent(): CollectionReference; + /** + * Applies a custom data converter to this `DocumentReference`, allowing you + * to use your own custom model objects with Firestore. When you call {@link + * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference` + * instance, the provided converter will convert between Firestore data of + * type `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `DocumentReference` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter$1): DocumentReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `DocumentReference` that does not + * use a converter. + */ + withConverter(converter: null): DocumentReference; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + referencePath: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `DocumentReference` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `DocumentReference` instance from a JSON object created by + * {@link DocumentReference.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json a JSON object represention of a `DocumentReference` instance + * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(firestore: Firestore$1, json: object): DocumentReference; + /** + * Builds a `DocumentReference` instance from a JSON object created by + * {@link DocumentReference.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json a JSON object represention of a `DocumentReference` instance + * @param converter - Converts objects to and from Firestore. + * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(firestore: Firestore$1, json: object, converter: FirestoreDataConverter$1): DocumentReference; +} +/** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using {@link (query:1)}). + */ +declare class CollectionReference extends Query { + readonly _path: ResourcePath; + /** The type of this Firestore reference. */ + readonly type = "collection"; + /** @hideconstructor */ + constructor(firestore: Firestore$1, converter: FirestoreDataConverter$1 | null, _path: ResourcePath); + /** The collection's identifier. */ + get id(): string; + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ + get path(): string; + /** + * A reference to the containing `DocumentReference` if this is a + * subcollection. If this isn't a subcollection, the reference is null. + */ + get parent(): DocumentReference | null; + /** + * Applies a custom data converter to this `CollectionReference`, allowing you + * to use your own custom model objects with Firestore. When you call {@link + * addDoc} with the returned `CollectionReference` instance, the provided + * converter will convert between Firestore data of type `NewDbModelType` and + * your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `CollectionReference` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter$1): CollectionReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `CollectionReference` that does not + * use a converter. + */ + withConverter(converter: null): CollectionReference; +} +/** + * Gets a `CollectionReference` instance that refers to the collection at + * the specified absolute path. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments to apply relative to the first + * argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +declare function collection(firestore: Firestore$1, path: string, ...pathSegments: string[]): CollectionReference; +/** + * Gets a `CollectionReference` instance that refers to a subcollection of + * `reference` at the specified relative path. + * + * @param reference - A reference to a collection. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments to apply relative to the first + * argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +declare function collection(reference: CollectionReference, path: string, ...pathSegments: string[]): CollectionReference; +/** + * Gets a `CollectionReference` instance that refers to a subcollection of + * `reference` at the specified relative path. + * + * @param reference - A reference to a Firestore document. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +declare function collection(reference: DocumentReference, path: string, ...pathSegments: string[]): CollectionReference; +/** + * Creates and returns a new `Query` instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given `collectionId`. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param collectionId - Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `Query`. + */ +declare function collectionGroup(firestore: Firestore$1, collectionId: string): Query; +/** + * Gets a `DocumentReference` instance that refers to the document at the + * specified absolute path. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param path - A slash-separated path to a document. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +declare function doc(firestore: Firestore$1, path: string, ...pathSegments: string[]): DocumentReference; +/** + * Gets a `DocumentReference` instance that refers to a document within + * `reference` at the specified relative path. If no path is specified, an + * automatically-generated unique ID will be used for the returned + * `DocumentReference`. + * + * @param reference - A reference to a collection. + * @param path - A slash-separated path to a document. Has to be omitted to use + * auto-generated IDs. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +declare function doc(reference: CollectionReference, path?: string, ...pathSegments: string[]): DocumentReference; +/** + * Gets a `DocumentReference` instance that refers to a document within + * `reference` at the specified relative path. + * + * @param reference - A reference to a Firestore document. + * @param path - A slash-separated path to a document. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +declare function doc(reference: DocumentReference, path: string, ...pathSegments: string[]): DocumentReference; +/** + * Returns true if the provided references are equal. + * + * @param left - A reference to compare. + * @param right - A reference to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +declare function refEqual(left: DocumentReference | CollectionReference, right: DocumentReference | CollectionReference): boolean; +/** + * Returns true if the provided queries point to the same collection and apply + * the same constraints. + * + * @param left - A `Query` to compare. + * @param right - A `Query` to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +declare function queryEqual(left: Query, right: Query): boolean; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * An untyped Firestore Data Converter interface that is shared between the + * lite, firestore-exp and classic SDK. + */ +interface UntypedFirestoreDataConverter { + toFirestore(modelObject: WithFieldValue): WithFieldValue; + toFirestore(modelObject: PartialWithFieldValue, options: SetOptions$1): PartialWithFieldValue; + fromFirestore(snapshot: unknown, options?: unknown): AppModelType; +} +/** The result of parsing document data (e.g. for a setData call). */ +declare class ParsedSetData { + readonly data: ObjectValue; + readonly fieldMask: FieldMask | null; + readonly fieldTransforms: FieldTransform[]; + constructor(data: ObjectValue, fieldMask: FieldMask | null, fieldTransforms: FieldTransform[]); + toMutation(key: DocumentKey, precondition: Precondition): Mutation; +} +/** The result of parsing "update" data (i.e. for an updateData call). */ +declare class ParsedUpdateData { + readonly data: ObjectValue; + readonly fieldMask: FieldMask; + readonly fieldTransforms: FieldTransform[]; + constructor(data: ObjectValue, fieldMask: FieldMask, fieldTransforms: FieldTransform[]); + toMutation(key: DocumentKey, precondition: Precondition): Mutation; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Internal transaction object responsible for accumulating the mutations to + * perform and the base versions for any documents read. + */ +declare class Transaction$2 { + private datastore; + private readVersions; + private mutations; + private committed; + /** + * A deferred usage error that occurred previously in this transaction that + * will cause the transaction to fail once it actually commits. + */ + private lastTransactionError; + /** + * Set of documents that have been written in the transaction. + * + * When there's more than one write to the same key in a transaction, any + * writes after the first are handled differently. + */ + private writtenDocs; + constructor(datastore: Datastore); + lookup(keys: DocumentKey[]): Promise; + set(key: DocumentKey, data: ParsedSetData): void; + update(key: DocumentKey, data: ParsedUpdateData): void; + delete(key: DocumentKey): void; + commit(): Promise; + private recordVersion; + /** + * Returns the version of this document when it was read in this transaction, + * as a precondition, or no precondition if it was not read. + */ + private precondition; + /** + * Returns the precondition for a document if the operation is an update. + */ + private preconditionForUpdate; + private write; + private ensureCommitNotCalled; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * FirestoreClient is a top-level class that constructs and owns all of the // + * pieces of the client SDK architecture. It is responsible for creating the // + * async queue that is shared by all of the other components in the system. // + */ +declare class FirestoreClient { + private authCredentials; + private appCheckCredentials; + /** + * Asynchronous queue responsible for all of our internal processing. When + * we get incoming work from the user (via public API) or the network + * (incoming GRPC messages), we should always schedule onto this queue. + * This ensures all of our work is properly serialized (e.g. we don't + * start processing a new operation while the previous one is waiting for + * an async I/O to complete). + */ + asyncQueue: AsyncQueue; + private databaseInfo; + private user; + private readonly clientId; + private authCredentialListener; + private appCheckCredentialListener; + _uninitializedComponentsProvider?: { + _offline: OfflineComponentProvider; + _online: OnlineComponentProvider; + }; + _offlineComponents?: OfflineComponentProvider; + _onlineComponents?: OnlineComponentProvider; + constructor(authCredentials: CredentialsProvider, appCheckCredentials: CredentialsProvider, + /** + * Asynchronous queue responsible for all of our internal processing. When + * we get incoming work from the user (via public API) or the network + * (incoming GRPC messages), we should always schedule onto this queue. + * This ensures all of our work is properly serialized (e.g. we don't + * start processing a new operation while the previous one is waiting for + * an async I/O to complete). + */ + asyncQueue: AsyncQueue, databaseInfo: DatabaseInfo, componentProvider?: { + _offline: OfflineComponentProvider; + _online: OnlineComponentProvider; + }); + get configuration(): ComponentConfiguration; + setCredentialChangeListener(listener: (user: User) => Promise): void; + setAppCheckTokenChangeListener(listener: (appCheckToken: string, user: User) => Promise): void; + terminate(): Promise; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Settings that can be passed to `enableIndexedDbPersistence()` to configure + * Firestore persistence. + * + * Persistence cannot be used in a Node.js environment. + */ +interface PersistenceSettings { + /** + * Whether to force enable persistence for the client. This cannot be used + * with multi-tab synchronization and is primarily intended for use with Web + * Workers. Setting this to `true` will enable persistence, but cause other + * tabs using persistence to fail. + */ + forceOwnership?: boolean; +} +/** + * Specifies custom configurations for your Cloud Firestore instance. + * You must set these before invoking any other methods. + */ +interface FirestoreSettings extends FirestoreSettings$1 { + /** + * NOTE: This field will be deprecated in a future major release. Use `cache` field + * instead to specify cache size, and other cache configurations. + * + * An approximate cache size threshold for the on-disk data. If the cache + * grows beyond this size, Firestore will start removing data that hasn't been + * recently used. The size is not a guarantee that the cache will stay below + * that size, only that if the cache exceeds the given size, cleanup will be + * attempted. + * + * The default value is 40 MB. The threshold must be set to at least 1 MB, and + * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection. + */ + cacheSizeBytes?: number; + /** + * Specifies the cache used by the SDK. Available options are `MemoryLocalCache` + * and `PersistentLocalCache`, each with different configuration options. + * + * When unspecified, `MemoryLocalCache` will be used by default. + * + * NOTE: setting this field and `cacheSizeBytes` at the same time will throw + * exception during SDK initialization. Instead, using the configuration in + * the `FirestoreLocalCache` object to specify the cache size. + */ + localCache?: FirestoreLocalCache; + /** + * Forces the SDK’s underlying network transport (WebChannel) to use + * long-polling. Each response from the backend will be closed immediately + * after the backend sends data (by default responses are kept open in + * case the backend has more data to send). This avoids incompatibility + * issues with certain proxies, antivirus software, etc. that incorrectly + * buffer traffic indefinitely. Use of this option will cause some + * performance degradation though. + * + * This setting cannot be used with `experimentalAutoDetectLongPolling` and + * may be removed in a future release. If you find yourself using it to + * work around a specific network reliability issue, please tell us about + * it in https://github.com/firebase/firebase-js-sdk/issues/1674. + * + * This setting cannot be used in a Node.js environment. + */ + experimentalForceLongPolling?: boolean; + /** + * Configures the SDK's underlying transport (WebChannel) to automatically + * detect if long-polling should be used. This is very similar to + * `experimentalForceLongPolling`, but only uses long-polling if required. + * + * After having had a default value of `false` since its inception in 2019, + * the default value of this setting was changed in May 2023 to `true` in + * v9.22.0 of the Firebase JavaScript SDK. That is, auto-detection of long + * polling is now enabled by default. To disable it, set this setting to + * `false`, and please open a GitHub issue to share the problems that + * motivated you disabling long-polling auto-detection. + * + * This setting cannot be used in a Node.js environment. + */ + experimentalAutoDetectLongPolling?: boolean; + /** + * Options that configure the SDK’s underlying network transport (WebChannel) + * when long-polling is used. + * + * These options are only used if `experimentalForceLongPolling` is true or if + * `experimentalAutoDetectLongPolling` is true and the auto-detection + * determined that long-polling was needed. Otherwise, these options have no + * effect. + */ + experimentalLongPollingOptions?: ExperimentalLongPollingOptions; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +declare module '@firebase/component' { + interface NameServiceMapping { + 'firestore': Firestore; + } +} +/** + * Constant used to indicate the LRU garbage collection should be disabled. + * Set this value as the `cacheSizeBytes` on the settings passed to the + * {@link Firestore} instance. + */ +declare const CACHE_SIZE_UNLIMITED = -1; +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ +declare class Firestore extends Firestore$1 { + /** + * Whether it's a {@link Firestore} or Firestore Lite instance. + */ + type: 'firestore-lite' | 'firestore'; + _queue: AsyncQueue; + readonly _persistenceKey: string; + _firestoreClient: FirestoreClient | undefined; + _componentsProvider?: { + _offline: OfflineComponentProviderFactory; + _online: OnlineComponentProviderFactory; + }; + /** @hideconstructor */ + constructor(authCredentialsProvider: CredentialsProvider, appCheckCredentialsProvider: CredentialsProvider, databaseId: DatabaseId, app?: FirebaseApp); + protected _terminate(): Promise; +} +/** + * Initializes a new instance of {@link Firestore} with the provided settings. + * Can only be called before any other function, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will + * be associated. + * @param settings - A settings object to configure the {@link Firestore} instance. + * @param databaseId - The name of the database. + * @returns A newly initialized {@link Firestore} instance. + */ +declare function initializeFirestore(app: FirebaseApp, settings: FirestoreSettings, databaseId?: string): Firestore; +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @returns The default {@link Firestore} instance of the default app. + */ +declare function getFirestore(): Firestore; +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @returns The default {@link Firestore} instance of the provided app. + */ +declare function getFirestore(app: FirebaseApp): Firestore; +/** + * Returns the existing named {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param databaseId - The name of the database. + * @returns The named {@link Firestore} instance of the default app. + * @beta + */ +declare function getFirestore(databaseId: string): Firestore; +/** + * Returns the existing named {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @param databaseId - The name of the database. + * @returns The named {@link Firestore} instance of the provided app. + * @beta + */ +declare function getFirestore(app: FirebaseApp, databaseId: string): Firestore; +/** + * @internal + */ +declare function ensureFirestoreConfigured(firestore: Firestore): FirestoreClient; +/** + * Attempts to enable persistent storage, if possible. + * + * On failure, `enableIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. + * + * * failed-precondition: The app is already open in another browser tab. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. + * + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. + * + * Note: `enableIndexedDbPersistence()` must be called before any other functions + * (other than {@link initializeFirestore}, {@link (getFirestore:1)} or + * {@link clearIndexedDbPersistence}. + * + * Persistence cannot be used in a Node.js environment. + * + * @param firestore - The {@link Firestore} instance to enable persistence for. + * @param persistenceSettings - Optional settings object to configure + * persistence. + * @returns A `Promise` that represents successfully enabling persistent storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on IndexedDb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. + */ +declare function enableIndexedDbPersistence(firestore: Firestore, persistenceSettings?: PersistenceSettings): Promise; +/** + * Attempts to enable multi-tab persistent storage, if possible. If enabled + * across all tabs, all operations share access to local persistence, including + * shared execution of queries and latency-compensated local document updates + * across all connected instances. + * + * On failure, `enableMultiTabIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. + * + * * failed-precondition: The app is already open in another browser tab and + * multi-tab is not enabled. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. + * + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. + * + * @param firestore - The {@link Firestore} instance to enable persistence for. + * @returns A `Promise` that represents successfully enabling persistent + * storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on indexeddb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. + */ +declare function enableMultiTabIndexedDbPersistence(firestore: Firestore): Promise; +/** + * Clears the persistent storage. This includes pending writes and cached + * documents. + * + * Must be called while the {@link Firestore} instance is not started (after the app is + * terminated or when the app is first initialized). On startup, this function + * must be called before other functions (other than {@link + * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore} + * instance is still running, the promise will be rejected with the error code + * of `failed-precondition`. + * + * Note: `clearIndexedDbPersistence()` is primarily intended to help write + * reliable tests that use Cloud Firestore. It uses an efficient mechanism for + * dropping existing data but does not attempt to securely overwrite or + * otherwise make cached data unrecoverable. For applications that are sensitive + * to the disclosure of cached data in between user sessions, we strongly + * recommend not enabling persistence at all. + * + * @param firestore - The {@link Firestore} instance to clear persistence for. + * @returns A `Promise` that is resolved when the persistent storage is + * cleared. Otherwise, the promise is rejected with an error. + */ +declare function clearIndexedDbPersistence(firestore: Firestore): Promise; +/** + * Waits until all currently pending writes for the active user have been + * acknowledged by the backend. + * + * The returned promise resolves immediately if there are no outstanding writes. + * Otherwise, the promise waits for all previously issued writes (including + * those written in a previous app session), but it does not wait for writes + * that were added after the function is called. If you want to wait for + * additional writes, call `waitForPendingWrites()` again. + * + * Any outstanding `waitForPendingWrites()` promises are rejected during user + * changes. + * + * @returns A `Promise` which resolves when all currently pending writes have been + * acknowledged by the backend. + */ +declare function waitForPendingWrites(firestore: Firestore): Promise; +/** + * Re-enables use of the network for this {@link Firestore} instance after a prior + * call to {@link disableNetwork}. + * + * @returns A `Promise` that is resolved once the network has been enabled. + */ +declare function enableNetwork(firestore: Firestore): Promise; +/** + * Disables network usage for this instance. It can be re-enabled via {@link + * enableNetwork}. While the network is disabled, any snapshot listeners, + * `getDoc()` or `getDocs()` calls will return results from cache, and any write + * operations will be queued until the network is restored. + * + * @returns A `Promise` that is resolved once the network has been disabled. + */ +declare function disableNetwork(firestore: Firestore): Promise; +/** + * Terminates the provided {@link Firestore} instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` function + * may be used. Any other function will throw a `FirestoreError`. + * + * To restart after termination, create a new instance of FirebaseFirestore with + * {@link (getFirestore:1)}. + * + * Termination does not cancel any pending writes, and any promises that are + * awaiting a response from the server will not be resolved. If you have + * persistence enabled, the next time you start this instance, it will resume + * sending these writes to the server. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all + * of its resources or in combination with `clearIndexedDbPersistence()` to + * ensure that all local state is destroyed between test runs. + * + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ +declare function terminate(firestore: Firestore): Promise; +/** + * Loads a Firestore bundle into the local cache. + * + * @param firestore - The {@link Firestore} instance to load bundles for. + * @param bundleData - An object representing the bundle to be loaded. Valid + * objects are `ArrayBuffer`, `ReadableStream` or `string`. + * + * @returns A `LoadBundleTask` object, which notifies callers with progress + * updates, and completion or error events. It can be used as a + * `Promise`. + */ +declare function loadBundle(firestore: Firestore, bundleData: ReadableStream | ArrayBuffer | string): LoadBundleTask; +/** + * Reads a Firestore {@link Query} from local cache, identified by the given + * name. + * + * The named queries are packaged into bundles on the server side (along + * with resulting documents), and loaded to local cache using `loadBundle`. Once + * in local cache, use this method to extract a {@link Query} by name. + * + * @param firestore - The {@link Firestore} instance to read the query from. + * @param name - The name of the query. + * @returns A `Promise` that is resolved with the Query or `null`. + */ +declare function namedQuery(firestore: Firestore, name: string): Promise; + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ +declare function sum(field: string | FieldPath): AggregateField; +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ +declare function average(field: string | FieldPath): AggregateField; +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ +declare function count(): AggregateField; +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ +declare function aggregateFieldEqual(left: AggregateField, right: AggregateField): boolean; +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ +declare function aggregateQuerySnapshotEqual(left: AggregateQuerySnapshot, right: AggregateQuerySnapshot): boolean; + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Represents an aggregation that can be performed by Firestore. + */ +declare class AggregateField { + readonly _internalFieldPath?: FieldPath$2 | undefined; + /** A type string to uniquely identify instances of this class. */ + readonly type = "AggregateField"; + /** Indicates the aggregation operation of this AggregateField. */ + readonly aggregateType: AggregateType; + /** + * Create a new AggregateField + * @param aggregateType Specifies the type of aggregation operation to perform. + * @param _internalFieldPath Optionally specifies the field that is aggregated. + * @internal + */ + constructor(aggregateType?: AggregateType, _internalFieldPath?: FieldPath$2 | undefined); +} +/** + * The union of all `AggregateField` types that are supported by Firestore. + */ +type AggregateFieldType = ReturnType | ReturnType | ReturnType; +/** + * Specifies a set of aggregations and their aliases. + */ +interface AggregateSpec { + [field: string]: AggregateFieldType; +} +/** + * A type whose keys are taken from an `AggregateSpec`, and whose values are the + * result of the aggregation performed by the corresponding `AggregateField` + * from the input `AggregateSpec`. + */ +type AggregateSpecData = { + [P in keyof T]: T[P] extends AggregateField ? U : never; +}; +/** + * The results of executing an aggregation query. + */ +declare class AggregateQuerySnapshot { + private readonly _userDataWriter; + private readonly _data; + /** A type string to uniquely identify instances of this class. */ + readonly type = "AggregateQuerySnapshot"; + /** + * The underlying query over which the aggregations recorded in this + * `AggregateQuerySnapshot` were performed. + */ + readonly query: Query; + /** @hideconstructor */ + constructor(query: Query, _userDataWriter: AbstractUserDataWriter, _data: ApiClientObjectMap); + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ + data(): AggregateSpecData; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ +declare function getCountFromServer(query: Query): Promise; +}, AppModelType, DbModelType>>; +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregateFromServer(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ +declare function getAggregateFromServer(query: Query, aggregateSpec: AggregateSpecType): Promise>; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * An immutable object representing an array of bytes. + */ +declare class Bytes { + _byteString: ByteString; + /** @hideconstructor */ + constructor(byteString: ByteString); + /** + * Creates a new `Bytes` object from the given Base64 string, converting it to + * bytes. + * + * @param base64 - The Base64 string used to create the `Bytes` object. + */ + static fromBase64String(base64: string): Bytes; + /** + * Creates a new `Bytes` object from the given Uint8Array. + * + * @param array - The Uint8Array used to create the `Bytes` object. + */ + static fromUint8Array(array: Uint8Array): Bytes; + /** + * Returns the underlying bytes as a Base64-encoded string. + * + * @returns The Base64-encoded string created from the `Bytes` object. + */ + toBase64(): string; + /** + * Returns the underlying bytes in a new `Uint8Array`. + * + * @returns The Uint8Array created from the `Bytes` object. + */ + toUint8Array(): Uint8Array; + /** + * Returns a string representation of the `Bytes` object. + * + * @returns A string representation of the `Bytes` object. + */ + toString(): string; + /** + * Returns true if this `Bytes` object is equal to the provided one. + * + * @param other - The `Bytes` object to compare against. + * @returns true if this `Bytes` object is equal to the provided one. + */ + isEqual(other: Bytes): boolean; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + bytes: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `Bytes` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}. + * + * @param json a JSON object represention of a `Bytes` instance + * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): Bytes; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * An options object that can be passed to {@link (onSnapshot:1)} and {@link + * QuerySnapshot.docChanges} to control which types of changes to include in the + * result set. + */ +interface SnapshotListenOptions { + /** + * Include a change even if only the metadata of the query or of a document + * changed. Default is false. + */ + readonly includeMetadataChanges?: boolean; + /** + * Set the source the query listens to. Default to "default", which + * listens to both cache and server. + */ + readonly source?: ListenSource; +} +/** + * Describe the source a query listens to. + * + * Set to `default` to listen to both cache and server changes. Set to `cache` + * to listen to changes in cache only. + */ +type ListenSource = 'default' | 'cache'; +/** + * Reads the document referred to by this `DocumentReference`. + * + * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting + * for data from the server, but it may return cached data or fail if you are + * offline and the server cannot be reached. To specify this behavior, invoke + * {@link getDocFromCache} or {@link getDocFromServer}. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +declare function getDoc(reference: DocumentReference): Promise>; +/** + * Reads the document referred to by this `DocumentReference` from cache. + * Returns an error if the document is not currently cached. + * + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +declare function getDocFromCache(reference: DocumentReference): Promise>; +/** + * Reads the document referred to by this `DocumentReference` from the server. + * Returns an error if the network is not available. + * + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +declare function getDocFromServer(reference: DocumentReference): Promise>; +/** + * Executes the query and returns the results as a `QuerySnapshot`. + * + * Note: `getDocs()` attempts to provide up-to-date data when possible by + * waiting for data from the server, but it may return cached data or fail if + * you are offline and the server cannot be reached. To specify this behavior, + * invoke {@link getDocsFromCache} or {@link getDocsFromServer}. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +declare function getDocs(query: Query): Promise>; +/** + * Executes the query and returns the results as a `QuerySnapshot` from cache. + * Returns an empty result set if no documents matching the query are currently + * cached. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +declare function getDocsFromCache(query: Query): Promise>; +/** + * Executes the query and returns the results as a `QuerySnapshot` from the + * server. Returns an error if the network is not available. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +declare function getDocsFromServer(query: Query): Promise>; +/** + * Writes to the document referred to by this `DocumentReference`. If the + * document does not yet exist, it will be created. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +declare function setDoc(reference: DocumentReference, data: WithFieldValue): Promise; +/** + * Writes to the document referred to by the specified `DocumentReference`. If + * the document does not yet exist, it will be created. If you provide `merge` + * or `mergeFields`, the provided data can be merged into an existing document. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @returns A Promise resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +declare function setDoc(reference: DocumentReference, data: PartialWithFieldValue, options: SetOptions): Promise; +/** + * Updates fields in the document referred to by the specified + * `DocumentReference`. The update will fail if applied to a document that does + * not exist. + * + * @param reference - A reference to the document to update. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +declare function updateDoc(reference: DocumentReference, data: UpdateData): Promise; +/** + * Updates fields in the document referred to by the specified + * `DocumentReference` The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * @param reference - A reference to the document to update. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +declare function updateDoc(reference: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): Promise; +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * @param reference - A reference to the document to delete. + * @returns A Promise resolved once the document has been successfully + * deleted from the backend (note that it won't resolve while you're offline). + */ +declare function deleteDoc(reference: DocumentReference): Promise; +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend (Note that it + * won't resolve while you're offline). + */ +declare function addDoc(reference: CollectionReference, data: WithFieldValue): Promise>; +/** + * A function returned by `onSnapshot()` that removes the listener when invoked. + */ +interface Unsubscribe { + /** Removes the listener when invoked. */ + (): void; +} +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +declare function onSnapshot(reference: DocumentReference, observer: { + next?: (snapshot: DocumentSnapshot) => void; + error?: (error: FirestoreError$1) => void; + complete?: () => void; +}): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +declare function onSnapshot(reference: DocumentReference, options: SnapshotListenOptions, observer: { + next?: (snapshot: DocumentSnapshot) => void; + error?: (error: FirestoreError$1) => void; + complete?: () => void; +}): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +declare function onSnapshot(reference: DocumentReference, onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError$1) => void, onCompletion?: () => void): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param options - Options controlling the listen behavior. + * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +declare function onSnapshot(reference: DocumentReference, options: SnapshotListenOptions, onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError$1) => void, onCompletion?: () => void): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The + * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +declare function onSnapshot(query: Query, observer: { + next?: (snapshot: QuerySnapshot) => void; + error?: (error: FirestoreError$1) => void; + complete?: () => void; +}): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The + * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +declare function onSnapshot(query: Query, options: SnapshotListenOptions, observer: { + next?: (snapshot: QuerySnapshot) => void; + error?: (error: FirestoreError$1) => void; + complete?: () => void; +}): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The + * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +declare function onSnapshot(query: Query, onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError$1) => void, onCompletion?: () => void): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The + * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param options - Options controlling the listen behavior. + * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +declare function onSnapshot(query: Query, options: SnapshotListenOptions, onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError$1) => void, onCompletion?: () => void): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events based on data generated by invoking + * {@link QuerySnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. + * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError$1) => void, onCompletion?: () => void, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking + * {@link DocumentSnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. + * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are + * never ending. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError$1) => void, onCompletion?: () => void, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events based on data generated by invoking + * {@link QuerySnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, options: SnapshotListenOptions, onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError$1) => void, onCompletion?: () => void, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking + * {@link DocumentSnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks + * or pass a single observer object with `next` and `error` callbacks. The listener can be cancelled + * by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, options: SnapshotListenOptions, onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError$1) => void, onCompletion?: () => void, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events based on QuerySnapshot data generated by invoking + * {@link QuerySnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, observer: { + next: (snapshot: QuerySnapshot) => void; + error?: (error: FirestoreError$1) => void; + complete?: () => void; +}, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking + * {@link DocumentSnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks + * or pass a single observer object with `next` and `error` callbacks. The listener can be cancelled + * by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, observer: { + next: (snapshot: DocumentSnapshot) => void; + error?: (error: FirestoreError$1) => void; + complete?: () => void; +}, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events based on QuerySnapshot data generated by invoking + * {@link QuerySnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, options: SnapshotListenOptions, observer: { + next: (snapshot: QuerySnapshot) => void; + error?: (error: FirestoreError$1) => void; + complete?: () => void; +}, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events based on QuerySnapshot data generated by + * invoking {@link DocumentSnapshot.toJSON} You may either pass individual `onNext` and `onError` + * callbacks or pass a single observer object with `next` and `error` callbacks. The listener can be + * cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, options: SnapshotListenOptions, observer: { + next: (snapshot: DocumentSnapshot) => void; + error?: (error: FirestoreError$1) => void; + complete?: () => void; +}, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync + * event indicates that all listeners affected by a given change have fired, + * even if a single server-generated change affects multiple listeners. + * + * NOTE: The snapshots-in-sync event only indicates that listeners are in sync + * with each other, but does not relate to whether those snapshots are in sync + * with the server. Use SnapshotMetadata in the individual listeners to + * determine if a snapshot is from the cache or the server. + * + * @param firestore - The instance of Firestore for synchronizing snapshots. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel the snapshot + * listener. + */ +declare function onSnapshotsInSync(firestore: Firestore, observer: { + next?: (value: void) => void; + error?: (error: FirestoreError$1) => void; + complete?: () => void; +}): Unsubscribe; +/** + * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync + * event indicates that all listeners affected by a given change have fired, + * even if a single server-generated change affects multiple listeners. + * + * NOTE: The snapshots-in-sync event only indicates that listeners are in sync + * with each other, but does not relate to whether those snapshots are in sync + * with the server. Use `SnapshotMetadata` in the individual listeners to + * determine if a snapshot is from the cache or the server. + * + * @param firestore - The `Firestore` instance for synchronizing snapshots. + * @param onSync - A callback to be called every time all snapshot listeners are + * in sync with each other. + * @returns An unsubscribe function that can be called to cancel the snapshot + * listener. + */ +declare function onSnapshotsInSync(firestore: Firestore, onSync: () => void): Unsubscribe; +/** + * Locally writes `mutations` on the async queue. + * @internal + */ +declare function executeWrite(firestore: Firestore, mutations: Mutation[]): Promise; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Converter used by `withConverter()` to transform user objects of type + * `AppModelType` into Firestore data of type `DbModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * In this context, an "AppModel" is a class that is used in an application to + * package together related information and functionality. Such a class could, + * for example, have properties with complex, nested data types, properties used + * for memoization, properties of types not supported by Firestore (such as + * `symbol` and `bigint`), and helper functions that perform compound + * operations. Such classes are not suitable and/or possible to store into a + * Firestore database. Instead, instances of such classes need to be converted + * to "plain old JavaScript objects" (POJOs) with exclusively primitive + * properties, potentially nested inside other POJOs or arrays of POJOs. In this + * context, this type is referred to as the "DbModel" and would be an object + * suitable for persisting into Firestore. For convenience, applications can + * implement `FirestoreDataConverter` and register the converter with Firestore + * objects, such as `DocumentReference` or `Query`, to automatically convert + * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel` + * to `AppModel` when retrieving from Firestore. + * + * @example + * + * Simple Example + * + * ```typescript + * const numberConverter = { + * toFirestore(value: WithFieldValue) { + * return { value }; + * }, + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) { + * return snapshot.data(options).value as number; + * } + * }; + * + * async function simpleDemo(db: Firestore): Promise { + * const documentRef = doc(db, 'values/value123').withConverter(numberConverter); + * + * // converters are used with `setDoc`, `addDoc`, and `getDoc` + * await setDoc(documentRef, 42); + * const snapshot1 = await getDoc(documentRef); + * assertEqual(snapshot1.data(), 42); + * + * // converters are not used when writing data with `updateDoc` + * await updateDoc(documentRef, { value: 999 }); + * const snapshot2 = await getDoc(documentRef); + * assertEqual(snapshot2.data(), 999); + * } + * ``` + * + * Advanced Example + * + * ```typescript + * // The Post class is a model that is used by our application. + * // This class may have properties and methods that are specific + * // to our application execution, which do not need to be persisted + * // to Firestore. + * class Post { + * constructor( + * readonly title: string, + * readonly author: string, + * readonly lastUpdatedMillis: number + * ) {} + * toString(): string { + * return `${this.title} by ${this.author}`; + * } + * } + * + * // The PostDbModel represents how we want our posts to be stored + * // in Firestore. This DbModel has different properties (`ttl`, + * // `aut`, and `lut`) from the Post class we use in our application. + * interface PostDbModel { + * ttl: string; + * aut: { firstName: string; lastName: string }; + * lut: Timestamp; + * } + * + * // The `PostConverter` implements `FirestoreDataConverter` and specifies + * // how the Firestore SDK can convert `Post` objects to `PostDbModel` + * // objects and vice versa. + * class PostConverter implements FirestoreDataConverter { + * toFirestore(post: WithFieldValue): WithFieldValue { + * return { + * ttl: post.title, + * aut: this._autFromAuthor(post.author), + * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis) + * }; + * } + * + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post { + * const data = snapshot.data(options) as PostDbModel; + * const author = `${data.aut.firstName} ${data.aut.lastName}`; + * return new Post(data.ttl, author, data.lut.toMillis()); + * } + * + * _autFromAuthor( + * author: string | FieldValue + * ): { firstName: string; lastName: string } | FieldValue { + * if (typeof author !== 'string') { + * // `author` is a FieldValue, so just return it. + * return author; + * } + * const [firstName, lastName] = author.split(' '); + * return {firstName, lastName}; + * } + * + * _lutFromLastUpdatedMillis( + * lastUpdatedMillis: number | FieldValue + * ): Timestamp | FieldValue { + * if (typeof lastUpdatedMillis !== 'number') { + * // `lastUpdatedMillis` must be a FieldValue, so just return it. + * return lastUpdatedMillis; + * } + * return Timestamp.fromMillis(lastUpdatedMillis); + * } + * } + * + * async function advancedDemo(db: Firestore): Promise { + * // Create a `DocumentReference` with a `FirestoreDataConverter`. + * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter()); + * + * // The `data` argument specified to `setDoc()` is type checked by the + * // TypeScript compiler to be compatible with `Post`. Since the `data` + * // argument is typed as `WithFieldValue` rather than just `Post`, + * // this allows properties of the `data` argument to also be special + * // Firestore values that perform server-side mutations, such as + * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`. + * await setDoc(documentRef, { + * title: 'My Life', + * author: 'Foo Bar', + * lastUpdatedMillis: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `setDoc()` is _not_ compatible with `WithFieldValue`. This + * // type checking prevents the caller from specifying objects with incorrect + * // properties or property values. + * // @ts-expect-error "Argument of type { ttl: string; } is not assignable + * // to parameter of type WithFieldValue" + * await setDoc(documentRef, { ttl: 'The Title' }); + * + * // When retrieving a document with `getDoc()` the `DocumentSnapshot` + * // object's `data()` method returns a `Post`, rather than a generic object, + * // which would have been returned if the `DocumentReference` did _not_ have a + * // `FirestoreDataConverter` attached to it. + * const snapshot1: DocumentSnapshot = await getDoc(documentRef); + * const post1: Post = snapshot1.data()!; + * if (post1) { + * assertEqual(post1.title, 'My Life'); + * assertEqual(post1.author, 'Foo Bar'); + * } + * + * // The `data` argument specified to `updateDoc()` is type checked by the + * // TypeScript compiler to be compatible with `PostDbModel`. Note that + * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`, + * // the `data` argument to `updateDoc()` must be compatible with + * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed + * // as `WithFieldValue` rather than just `PostDbModel`, this + * // allows properties of the `data` argument to also be those special + * // Firestore values, like `arrayRemove()`, `deleteField()`, and + * // `serverTimestamp()`. + * await updateDoc(documentRef, { + * 'aut.firstName': 'NewFirstName', + * lut: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `updateDoc()` is _not_ compatible with `WithFieldValue`. + * // This type checking prevents the caller from specifying objects with + * // incorrect properties or property values. + * // @ts-expect-error "Argument of type { title: string; } is not assignable + * // to parameter of type WithFieldValue" + * await updateDoc(documentRef, { title: 'New Title' }); + * const snapshot2: DocumentSnapshot = await getDoc(documentRef); + * const post2: Post = snapshot2.data()!; + * if (post2) { + * assertEqual(post2.title, 'My Life'); + * assertEqual(post2.author, 'NewFirstName Bar'); + * } + * } + * ``` + */ +interface FirestoreDataConverter extends FirestoreDataConverter$1 { + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. To use `set()` + * with `merge` and `mergeFields`, `toFirestore()` must be defined with + * `PartialWithFieldValue`. + * + * The `WithFieldValue` type extends `T` to also allow FieldValues such as + * {@link (deleteField:1)} to be used as property values. + */ + toFirestore(modelObject: WithFieldValue): WithFieldValue; + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link (setDoc:1)}, {@link (WriteBatch.set:1)} and + * {@link (Transaction.set:1)} with `merge:true` or `mergeFields`. + * + * The `PartialWithFieldValue` type extends `Partial` to allow + * FieldValues such as {@link (arrayUnion:1)} to be used as property values. + * It also supports nested `Partial` by allowing nested fields to be + * omitted. + */ + toFirestore(modelObject: PartialWithFieldValue, options: SetOptions): PartialWithFieldValue; + /** + * Called by the Firestore SDK to convert Firestore data into an object of + * type `AppModelType`. You can access your data by calling: + * `snapshot.data(options)`. + * + * Generally, the data returned from `snapshot.data()` can be cast to + * `DbModelType`; however, this is not guaranteed because Firestore does not + * enforce a schema on the database. For example, writes from a previous + * version of the application or writes from another client that did not use a + * type converter could have written data with different properties and/or + * property types. The implementation will need to choose whether to + * gracefully recover from non-conforming data or throw an error. + * + * To override this method, see {@link (FirestoreDataConverter.fromFirestore:1)}. + * + * @param snapshot - A `QueryDocumentSnapshot` containing your data and metadata. + * @param options - The `SnapshotOptions` from the initial call to `data()`. + */ + fromFirestore(snapshot: QueryDocumentSnapshot, options?: SnapshotOptions): AppModelType; +} +/** + * Options that configure how data is retrieved from a `DocumentSnapshot` (for + * example the desired behavior for server timestamps that have not yet been set + * to their final value). + */ +interface SnapshotOptions { + /** + * If set, controls the return value for server timestamps that have not yet + * been set to their final value. + * + * By specifying 'estimate', pending server timestamps return an estimate + * based on the local clock. This estimate will differ from the final value + * and cause these values to change once the server result becomes available. + * + * By specifying 'previous', pending timestamps will be ignored and return + * their previous value instead. + * + * If omitted or set to 'none', `null` will be returned by default until the + * server value becomes available. + */ + readonly serverTimestamps?: 'estimate' | 'previous' | 'none'; +} +/** + * Metadata about a snapshot, describing the state of the snapshot. + */ +declare class SnapshotMetadata { + /** + * True if the snapshot contains the result of local writes (for example + * `set()` or `update()` calls) that have not yet been committed to the + * backend. If your listener has opted into metadata updates (via + * `SnapshotListenOptions`) you will receive another snapshot with + * `hasPendingWrites` equal to false once the writes have been committed to + * the backend. + */ + readonly hasPendingWrites: boolean; + /** + * True if the snapshot was created from cached data rather than guaranteed + * up-to-date server data. If your listener has opted into metadata updates + * (via `SnapshotListenOptions`) you will receive another snapshot with + * `fromCache` set to false once the client has received up-to-date data from + * the backend. + */ + readonly fromCache: boolean; + /** @hideconstructor */ + constructor(hasPendingWrites: boolean, fromCache: boolean); + /** + * Returns true if this `SnapshotMetadata` is equal to the provided one. + * + * @param other - The `SnapshotMetadata` to compare against. + * @returns true if this `SnapshotMetadata` is equal to the provided one. + */ + isEqual(other: SnapshotMetadata): boolean; +} +/** + * The type of a `DocumentChange` may be 'added', 'removed', or 'modified'. + */ +type DocumentChangeType = 'added' | 'removed' | 'modified'; +/** + * A `DocumentChange` represents a change to the documents matching a query. + * It contains the document affected and the type of change that occurred. + */ +interface DocumentChange { + /** The type of change ('added', 'modified', or 'removed'). */ + readonly type: DocumentChangeType; + /** The document affected by this change. */ + readonly doc: QueryDocumentSnapshot; + /** + * The index of the changed document in the result set immediately prior to + * this `DocumentChange` (i.e. supposing that all prior `DocumentChange` objects + * have been applied). Is `-1` for 'added' events. + */ + readonly oldIndex: number; + /** + * The index of the changed document in the result set immediately after + * this `DocumentChange` (i.e. supposing that all prior `DocumentChange` + * objects and the current `DocumentChange` object have been applied). + * Is -1 for 'removed' events. + */ + readonly newIndex: number; +} +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ +declare class DocumentSnapshot extends DocumentSnapshot$1 { + readonly _firestore: Firestore; + private readonly _firestoreImpl; + /** + * Metadata about the `DocumentSnapshot`, including information about its + * source and local modifications. + */ + readonly metadata: SnapshotMetadata; + /** @hideconstructor protected */ + constructor(_firestore: Firestore, userDataWriter: AbstractUserDataWriter, key: DocumentKey, document: Document | null, metadata: SnapshotMetadata, converter: UntypedFirestoreDataConverter | null); + /** + * Returns whether or not the data exists. True if the document exists. + */ + exists(): this is QueryDocumentSnapshot; + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * By default, `serverTimestamp()` values that have not yet been + * set to their final value will be returned as `null`. You can override + * this by passing an options object. + * + * @param options - An options object to configure how data is retrieved from + * the snapshot (for example the desired behavior for server timestamps that + * have not yet been set to their final value). + * @returns An `Object` containing all fields in the document or `undefined` if + * the document doesn't exist. + */ + data(options?: SnapshotOptions): AppModelType | undefined; + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * By default, a `serverTimestamp()` that has not yet been set to + * its final value will be returned as `null`. You can override this by + * passing an options object. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @param options - An options object to configure how the field is retrieved + * from the snapshot (for example the desired behavior for server timestamps + * that have not yet been set to their final value). + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + get(fieldPath: string | FieldPath, options?: SnapshotOptions): any; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + bundleSource: Property<"string">; + bundleName: Property<"string">; + bundle: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `DocumentSnapshot` instance. + * + * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this + * `DocumentSnapshot` has pending writes. + */ + toJSON(): object; +} +/** + * Builds a `DocumentSnapshot` instance from a JSON object created by + * {@link DocumentSnapshot.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json - a JSON object represention of a `DocumentSnapshot` instance. + * @returns an instance of {@link DocumentSnapshot} if the JSON object could be + * parsed. Throws a {@link FirestoreError} if an error occurs. + */ +declare function documentSnapshotFromJSON(db: Firestore, json: object): DocumentSnapshot; +/** + * Builds a `DocumentSnapshot` instance from a JSON object created by + * {@link DocumentSnapshot.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json - a JSON object represention of a `DocumentSnapshot` instance. + * @param converter - Converts objects to and from Firestore. + * @returns an instance of {@link DocumentSnapshot} if the JSON object could be + * parsed. Throws a {@link FirestoreError} if an error occurs. + */ +declare function documentSnapshotFromJSON(db: Firestore, json: object, converter: FirestoreDataConverter): DocumentSnapshot; +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ +declare class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * By default, `serverTimestamp()` values that have not yet been + * set to their final value will be returned as `null`. You can override + * this by passing an options object. + * + * @override + * @param options - An options object to configure how data is retrieved from + * the snapshot (for example the desired behavior for server timestamps that + * have not yet been set to their final value). + * @returns An `Object` containing all fields in the document. + */ + data(options?: SnapshotOptions): AppModelType; +} +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ +declare class QuerySnapshot { + readonly _firestore: Firestore; + readonly _userDataWriter: AbstractUserDataWriter; + readonly _snapshot: ViewSnapshot; + /** + * Metadata about this snapshot, concerning its source and if it has local + * modifications. + */ + readonly metadata: SnapshotMetadata; + /** + * The query on which you called `get` or `onSnapshot` in order to get this + * `QuerySnapshot`. + */ + readonly query: Query; + private _cachedChanges?; + private _cachedChangesIncludeMetadataChanges?; + /** @hideconstructor */ + constructor(_firestore: Firestore, _userDataWriter: AbstractUserDataWriter, query: Query, _snapshot: ViewSnapshot); + /** An array of all the documents in the `QuerySnapshot`. */ + get docs(): Array>; + /** The number of documents in the `QuerySnapshot`. */ + get size(): number; + /** True if there are no documents in the `QuerySnapshot`. */ + get empty(): boolean; + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ + forEach(callback: (result: QueryDocumentSnapshot) => void, thisArg?: unknown): void; + /** + * Returns an array of the documents changes since the last snapshot. If this + * is the first snapshot, all documents will be in the list as 'added' + * changes. + * + * @param options - `SnapshotListenOptions` that control whether metadata-only + * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger + * snapshot events. + */ + docChanges(options?: SnapshotListenOptions): Array>; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + bundleSource: Property<"string">; + bundleName: Property<"string">; + bundle: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `QuerySnapshot` instance. + * + * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this + * `QuerySnapshot` has pending writes. + */ + toJSON(): object; +} +/** + * Builds a `QuerySnapshot` instance from a JSON object created by + * {@link QuerySnapshot.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json - a JSON object represention of a `QuerySnapshot` instance. + * @returns an instance of {@link QuerySnapshot} if the JSON object could be + * parsed. Throws a {@link FirestoreError} if an error occurs. + */ +declare function querySnapshotFromJSON(db: Firestore, json: object): QuerySnapshot; +/** + * Builds a `QuerySnapshot` instance from a JSON object created by + * {@link QuerySnapshot.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json - a JSON object represention of a `QuerySnapshot` instance. + * @param converter - Converts objects to and from Firestore. + * @returns an instance of {@link QuerySnapshot} if the JSON object could be + * parsed. Throws a {@link FirestoreError} if an error occurs. + */ +declare function querySnapshotFromJSON(db: Firestore, json: object, converter: FirestoreDataConverter): QuerySnapshot; +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ +declare function snapshotEqual(left: DocumentSnapshot | QuerySnapshot, right: DocumentSnapshot | QuerySnapshot): boolean; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** Describes the different query constraints available in this SDK. */ +type QueryConstraintType = 'where' | 'orderBy' | 'limit' | 'limitToLast' | 'startAt' | 'startAfter' | 'endAt' | 'endBefore'; +/** + * An `AppliableConstraint` is an abstraction of a constraint that can be applied + * to a Firestore query. + */ +declare abstract class AppliableConstraint { + /** + * Takes the provided {@link Query} and returns a copy of the {@link Query} with this + * {@link AppliableConstraint} applied. + */ + abstract _apply(query: Query): Query; +} +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Firestore query. `QueryConstraint`s are created by invoking {@link where}, + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that + * also contains this `QueryConstraint`. + */ +declare abstract class QueryConstraint extends AppliableConstraint { + /** The type of this query constraint */ + abstract readonly type: QueryConstraintType; + /** + * Takes the provided {@link Query} and returns a copy of the {@link Query} with this + * {@link AppliableConstraint} applied. + */ + abstract _apply(query: Query): Query; +} +/** + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. + * + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to + * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or + * {@link or}. + * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to + * apply (e.g. {@link orderBy}, {@link limit}). + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +declare function query(query: Query, compositeFilter: QueryCompositeFilterConstraint, ...queryConstraints: QueryNonFilterConstraint[]): Query; +/** + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. + * + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param queryConstraints - The list of {@link QueryConstraint}s to apply. + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +declare function query(query: Query, ...queryConstraints: QueryConstraint[]): Query; +/** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ +declare class QueryFieldFilterConstraint extends QueryConstraint { + private readonly _field; + private _op; + private _value; + /** The type of this query constraint */ + readonly type = "where"; + /** + * @internal + */ + protected constructor(_field: FieldPath$2, _op: Operator, _value: unknown); + static _create(_field: FieldPath$2, _op: Operator, _value: unknown): QueryFieldFilterConstraint; + _apply(query: Query): Query; + _parse(query: Query): FieldFilter; +} +/** + * Filter conditions in a {@link where} clause are specified using the + * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in', + * 'array-contains-any', and 'not-in'. + */ +type WhereFilterOp = '<' | '<=' | '==' | '!=' | '>=' | '>' | 'array-contains' | 'in' | 'array-contains-any' | 'not-in'; +/** + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. + * + * @param fieldPath - The path to compare + * @param opStr - The operation string (e.g "<", "<=", "==", "<", + * "<=", "!="). + * @param value - The value for comparison + * @returns The created {@link QueryFieldFilterConstraint}. + */ +declare function where(fieldPath: string | FieldPath, opStr: WhereFilterOp, value: unknown): QueryFieldFilterConstraint; +/** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ +declare class QueryCompositeFilterConstraint extends AppliableConstraint { + /** The type of this query constraint */ + readonly type: 'or' | 'and'; + private readonly _queryConstraints; + /** + * @internal + */ + protected constructor( + /** The type of this query constraint */ + type: 'or' | 'and', _queryConstraints: QueryFilterConstraint[]); + static _create(type: 'or' | 'and', _queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; + _parse(query: Query): Filter; + _apply(query: Query): Query; + _getQueryConstraints(): readonly AppliableConstraint[]; + _getOperator(): CompositeOperator; +} +/** + * `QueryNonFilterConstraint` is a helper union type that represents + * QueryConstraints which are used to narrow or order the set of documents, + * but that do not explicitly filter on a document field. + * `QueryNonFilterConstraint`s are created by invoking {@link orderBy}, + * {@link (startAt:1)}, {@link (startAfter:1)}, {@link (endBefore:1)}, {@link (endAt:1)}, + * {@link limit} or {@link limitToLast} and can then be passed to {@link (query:1)} + * to create a new query instance that also contains the `QueryConstraint`. + */ +type QueryNonFilterConstraint = QueryOrderByConstraint | QueryLimitConstraint | QueryStartAtConstraint | QueryEndAtConstraint; +/** + * `QueryFilterConstraint` is a helper union type that represents + * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}. + */ +type QueryFilterConstraint = QueryFieldFilterConstraint | QueryCompositeFilterConstraint; +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +declare function or(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +declare function and(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; +/** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ +declare class QueryOrderByConstraint extends QueryConstraint { + private readonly _field; + private _direction; + /** The type of this query constraint */ + readonly type = "orderBy"; + /** + * @internal + */ + protected constructor(_field: FieldPath$2, _direction: Direction); + static _create(_field: FieldPath$2, _direction: Direction): QueryOrderByConstraint; + _apply(query: Query): Query; +} +/** + * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc' + * (descending or ascending). + */ +type OrderByDirection = 'desc' | 'asc'; +/** + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the + * specified field, optionally in descending order instead of ascending. + * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * + * @param fieldPath - The field to sort by. + * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @returns The created {@link QueryOrderByConstraint}. + */ +declare function orderBy(fieldPath: string | FieldPath, directionStr?: OrderByDirection): QueryOrderByConstraint; +/** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ +declare class QueryLimitConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'limit' | 'limitToLast'; + private readonly _limit; + private readonly _limitType; + /** + * @internal + */ + protected constructor( + /** The type of this query constraint */ + type: 'limit' | 'limitToLast', _limit: number, _limitType: LimitType$1); + static _create(type: 'limit' | 'limitToLast', _limit: number, _limitType: LimitType$1): QueryLimitConstraint; + _apply(query: Query): Query; +} +/** + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +declare function limit(limit: number): QueryLimitConstraint; +/** + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. + * + * You must specify at least one `orderBy` clause for `limitToLast` queries, + * otherwise an exception will be thrown during execution. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +declare function limitToLast(limit: number): QueryLimitConstraint; +/** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ +declare class QueryStartAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'startAt' | 'startAfter'; + private readonly _docOrFields; + private readonly _inclusive; + /** + * @internal + */ + protected constructor( + /** The type of this query constraint */ + type: 'startAt' | 'startAfter', _docOrFields: Array>, _inclusive: boolean); + static _create(type: 'startAt' | 'startAfter', _docOrFields: Array>, _inclusive: boolean): QueryStartAtConstraint; + _apply(query: Query): Query; +} +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided document (inclusive). The starting position is relative + * to the order of the query. The document must contain all of the fields + * provided in the `orderBy` of this query. + * + * @param snapshot - The snapshot of the document to start at. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. + */ +declare function startAt(snapshot: DocumentSnapshot$1): QueryStartAtConstraint; +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to start this query at, in order + * of the query's order by. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. + */ +declare function startAt(...fieldValues: unknown[]): QueryStartAtConstraint; +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided document (exclusive). The starting position is + * relative to the order of the query. The document must contain all of the + * fields provided in the orderBy of the query. + * + * @param snapshot - The snapshot of the document to start after. + * @returns A {@link QueryStartAtConstraint} to pass to `query()` + */ +declare function startAfter(snapshot: DocumentSnapshot$1): QueryStartAtConstraint; +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided fields relative to the order of the query. The order + * of the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to start this query after, in order + * of the query's order by. + * @returns A {@link QueryStartAtConstraint} to pass to `query()` + */ +declare function startAfter(...fieldValues: unknown[]): QueryStartAtConstraint; +/** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ +declare class QueryEndAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'endBefore' | 'endAt'; + private readonly _docOrFields; + private readonly _inclusive; + /** + * @internal + */ + protected constructor( + /** The type of this query constraint */ + type: 'endBefore' | 'endAt', _docOrFields: Array>, _inclusive: boolean); + static _create(type: 'endBefore' | 'endAt', _docOrFields: Array>, _inclusive: boolean): QueryEndAtConstraint; + _apply(query: Query): Query; +} +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided document (exclusive). The end position is relative to the + * order of the query. The document must contain all of the fields provided in + * the orderBy of the query. + * + * @param snapshot - The snapshot of the document to end before. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +declare function endBefore(snapshot: DocumentSnapshot$1): QueryEndAtConstraint; +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to end this query before, in order + * of the query's order by. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +declare function endBefore(...fieldValues: unknown[]): QueryEndAtConstraint; +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided document (inclusive). The end position is relative to the order + * of the query. The document must contain all of the fields provided in the + * orderBy of the query. + * + * @param snapshot - The snapshot of the document to end at. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +declare function endAt(snapshot: DocumentSnapshot$1): QueryEndAtConstraint; +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided fields relative to the order of the query. The order of the field + * values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to end this query at, in order + * of the query's order by. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +declare function endAt(...fieldValues: unknown[]): QueryEndAtConstraint; + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options to customize transaction behavior. + */ +declare interface TransactionOptions { + /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */ + readonly maxAttempts?: number; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ +declare class Transaction$1 { + protected readonly _firestore: Firestore$1; + private readonly _transaction; + private readonly _dataReader; + /** @hideconstructor */ + constructor(_firestore: Firestore$1, _transaction: Transaction$2); + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ + get(documentRef: DocumentReference): Promise>; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: WithFieldValue): this; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * If you provide `merge` or `mergeFields`, the provided data can be merged + * into an existing document. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: PartialWithFieldValue, options: SetOptions): this; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * @param documentRef - A reference to the document to be updated. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, data: UpdateData): this; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * @param documentRef - A reference to the document to be updated. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key/value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): this; + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + delete(documentRef: DocumentReference): this; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ +declare class Transaction extends Transaction$1 { + protected readonly _firestore: Firestore; + /** @hideconstructor */ + constructor(_firestore: Firestore, _transaction: Transaction$2); + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ + get(documentRef: DocumentReference): Promise>; +} +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ +declare function runTransaction(firestore: Firestore, updateFunction: (transaction: Transaction) => Promise, options?: TransactionOptions): Promise; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. + */ +declare function deleteField(): FieldValue; +/** + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to + * include a server-generated timestamp in the written data. + */ +declare function serverTimestamp(): FieldValue; +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array + * value that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements - The elements to union into the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()`. + */ +declare function arrayUnion(...elements: unknown[]): FieldValue; +/** + * Returns a special value that can be used with {@link (setDoc:1)} or {@link + * updateDoc:1} that tells the server to remove the given elements from any + * array value that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is not + * already an array it will be overwritten with an empty array. + * + * @param elements - The elements to remove from the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +declare function arrayRemove(...elements: unknown[]): FieldValue; +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by + * the given value. + * + * If either the operand or the current field value uses floating point + * precision, all arithmetic follows IEEE 754 semantics. If both values are + * integers, values outside of JavaScript's safe number range + * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to + * precision loss. Furthermore, once processed by the Firestore backend, all + * integer operations are capped between -2^63 and 2^63-1. + * + * If the current field value is not of type `number`, or if the field does not + * yet exist, the transformation sets the field to the given value. + * + * @param n - The value to increment by. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +declare function increment(n: number): FieldValue; +/** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ +declare function vector(values?: number[]): VectorValue; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). + * + * @param logLevel - The verbosity you set for activity and error logging. Can + * be any of the following values: + * + *

    + *
  • `debug` for the most verbose logging level, primarily for + * debugging.
  • + *
  • `error` to log errors only.
  • + *
  • `silent` to turn off logging.
  • + *
+ */ +declare function setLogLevel(logLevel: LogLevelString): void; +/** + * @internal + */ +declare function logWarn(msg: string, ...obj: unknown[]): void; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It + * provides methods for adding writes to the write batch. None of the writes + * will be committed (or visible locally) until {@link WriteBatch.commit} is + * called. + */ +declare class WriteBatch { + private readonly _firestore; + private readonly _commitHandler; + private readonly _dataReader; + private _mutations; + private _committed; + /** @hideconstructor */ + constructor(_firestore: Firestore$1, _commitHandler: (m: Mutation[]) => Promise); + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: WithFieldValue): WriteBatch; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * If you provide `merge` or `mergeFields`, the provided data can be merged + * into an existing document. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: PartialWithFieldValue, options: SetOptions): WriteBatch; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * @param documentRef - A reference to the document to be updated. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, data: UpdateData): WriteBatch; + /** + * Updates fields in the document referred to by this {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be update by providing dot-separated field path strings + * or by providing `FieldPath` objects. + * + * @param documentRef - A reference to the document to be updated. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): WriteBatch; + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + delete(documentRef: DocumentReference): WriteBatch; + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `Promise` resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit (note that it won't + * resolve while you're offline). + */ + commit(): Promise; + private _verifyNotCommitted; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch} + * is 500. + * + * Unlike transactions, write batches are persisted offline and therefore are + * preferable when you don't need to condition your writes on read data. + * + * @returns A {@link WriteBatch} that can be used to atomically execute multiple + * writes. + */ +declare function writeBatch(firestore: Firestore): WriteBatch; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ +declare class GeoPoint { + private _lat; + private _long; + /** + * Creates a new immutable `GeoPoint` object with the provided latitude and + * longitude values. + * @param latitude - The latitude as number between -90 and 90. + * @param longitude - The longitude as number between -180 and 180. + */ + constructor(latitude: number, longitude: number); + /** + * The latitude of this `GeoPoint` instance. + */ + get latitude(): number; + /** + * The longitude of this `GeoPoint` instance. + */ + get longitude(): number; + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other - The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ + isEqual(other: GeoPoint): boolean; + /** + * Actually private to JS consumers of our API, so this function is prefixed + * with an underscore. + */ + _compareTo(other: GeoPoint): number; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + latitude: Property<"number">; + longitude: Property<"number">; + }; + /** + * Returns a JSON-serializable representation of this `GeoPoint` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): { + latitude: number; + longitude: number; + type: string; + }; + /** + * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}. + * + * @param json a JSON object represention of a `GeoPoint` instance + * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): GeoPoint; +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * A single field element in an index configuration. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +interface IndexField { + /** The field path to index. */ + readonly fieldPath: string; + /** + * What type of array index to create. Set to `CONTAINS` for `array-contains` + * and `array-contains-any` indexes. + * + * Only one of `arrayConfig` or `order` should be set; + */ + readonly arrayConfig?: 'CONTAINS'; + /** + * What type of array index to create. Set to `ASCENDING` or 'DESCENDING` for + * `==`, `!=`, `<=`, `<=`, `in` and `not-in` filters. + * + * Only one of `arrayConfig` or `order` should be set. + */ + readonly order?: 'ASCENDING' | 'DESCENDING'; + [key: string]: unknown; +} +/** + * The SDK definition of a Firestore index. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +interface Index { + /** The ID of the collection to index. */ + readonly collectionGroup: string; + /** A list of fields to index. */ + readonly fields?: IndexField[]; + [key: string]: unknown; +} +/** + * A list of Firestore indexes to speed up local query execution. + * + * See {@link https://firebase.google.com/docs/reference/firestore/indexes/#json_format | JSON Format} + * for a description of the format of the index definition. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +interface IndexConfiguration { + /** A list of all Firestore indexes. */ + readonly indexes?: Index[]; + [key: string]: unknown; +} +/** + * Configures indexing for local query execution. Any previous index + * configuration is overridden. The `Promise` resolves once the index + * configuration has been persisted. + * + * The index entries themselves are created asynchronously. You can continue to + * use queries that require indexing even if the indices are not yet available. + * Query execution will automatically start using the index once the index + * entries have been written. + * + * Indexes are only supported with IndexedDb persistence. If IndexedDb is not + * enabled, any index configuration is ignored. + * + * @param firestore - The {@link Firestore} instance to configure indexes for. + * @param configuration -The index definition. + * @throws FirestoreError if the JSON format is invalid. + * @returns A `Promise` that resolves once all indices are successfully + * configured. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +declare function setIndexConfiguration(firestore: Firestore, configuration: IndexConfiguration): Promise; +/** + * Configures indexing for local query execution. Any previous index + * configuration is overridden. The `Promise` resolves once the index + * configuration has been persisted. + * + * The index entries themselves are created asynchronously. You can continue to + * use queries that require indexing even if the indices are not yet available. + * Query execution will automatically start using the index once the index + * entries have been written. + * + * Indexes are only supported with IndexedDb persistence. Invoke either + * `enableIndexedDbPersistence()` or `enableMultiTabIndexedDbPersistence()` + * before setting an index configuration. If IndexedDb is not enabled, any + * index configuration is ignored. + * + * The method accepts the JSON format exported by the Firebase CLI (`firebase + * firestore:indexes`). If the JSON format is invalid, this method throws an + * error. + * + * @param firestore - The {@link Firestore} instance to configure indexes for. + * @param json -The JSON format exported by the Firebase CLI. + * @throws FirestoreError if the JSON format is invalid. + * @returns A `Promise` that resolves once all indices are successfully + * configured. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +declare function setIndexConfiguration(firestore: Firestore, json: string): Promise; + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * A `PersistentCacheIndexManager` for configuring persistent cache indexes used + * for local query execution. + * + * To use, call `getPersistentCacheIndexManager()` to get an instance. + */ +declare class PersistentCacheIndexManager { + readonly _firestore: Firestore; + /** A type string to uniquely identify instances of this class. */ + readonly type: 'PersistentCacheIndexManager'; + /** @hideconstructor */ + constructor(_firestore: Firestore); +} +/** + * Returns the PersistentCache Index Manager used by the given `Firestore` + * object. + * + * @return The `PersistentCacheIndexManager` instance, or `null` if local + * persistent storage is not in use. + */ +declare function getPersistentCacheIndexManager(firestore: Firestore): PersistentCacheIndexManager | null; +/** + * Enables the SDK to create persistent cache indexes automatically for local + * query execution when the SDK believes cache indexes can help improve + * performance. + * + * This feature is disabled by default. + */ +declare function enablePersistentCacheIndexAutoCreation(indexManager: PersistentCacheIndexManager): void; +/** + * Stops creating persistent cache indexes automatically for local query + * execution. The indexes which have been created by calling + * `enablePersistentCacheIndexAutoCreation()` still take effect. + */ +declare function disablePersistentCacheIndexAutoCreation(indexManager: PersistentCacheIndexManager): void; +/** + * Removes all persistent cache indexes. + * + * Please note this function will also deletes indexes generated by + * `setIndexConfiguration()`, which is deprecated. + */ +declare function deleteAllPersistentCacheIndexes(indexManager: PersistentCacheIndexManager): void; + +/** + * True if and only if the Base64 conversion functions are available. + * @internal + */ +declare function isBase64Available(): boolean; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @internal + * @private + * + * This function is for internal use only. + * + * Returns the `QueryTarget` representation of the given query. Returns `null` + * if the Firestore client associated with the given query has not been + * initialized or has been terminated. + * + * @param query - The Query to convert to proto representation. + */ +declare function _internalQueryToProtoQueryTarget(query: Query): any; +/** + * @internal + * @private + * + * This function is for internal use only. + * + * Returns `RunAggregationQueryRequest` which contains the proto representation + * of the given aggregation query request. Returns null if the Firestore client + * associated with the given query has not been initialized or has been + * terminated. + * + * @param query - The Query to convert to proto representation. + * @param aggregateSpec - The set of aggregations and their aliases. + */ +declare function _internalAggregationQueryToProtoRunAggregationQueryRequest(query: Query, aggregateSpec: AggregateSpecType): any; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Validates that two boolean options are not set at the same time. + * @internal + */ +declare function validateIsNotUsedTogether(optionName1: string, argument1: boolean | undefined, optionName2: string, argument2: boolean | undefined): void; +/** + * Casts `obj` to `T`, optionally unwrapping Compat types to expose the + * underlying instance. Throws if `obj` is not an instance of `T`. + * + * This cast is used in the Lite and Full SDK to verify instance types for + * arguments passed to the public API. + * @internal + */ +declare function cast(obj: object, constructor: { + new (...args: any[]): T; +}): T | never; + +/** + * Fails if the given assertion condition is false, throwing an Error with the + * given message if it did. + * + * The code of callsites invoking this function are stripped out in production + * builds. Any side-effects of code within the debugAssert() invocation will not + * happen in this case. + * + * @internal + */ +declare function debugAssert(assertion: boolean, message: string): asserts assertion; + +/** + * Information about an existence filter mismatch. + * @internal + */ +interface ExistenceFilterMismatchInfo { + /** The number of documents that matched the query in the local cache. */ + localCacheCount: number; + /** + * The number of documents that matched the query on the server, as specified + * in the ExistenceFilter message's `count` field. + */ + existenceFilterCount: number; + /** + * The projectId used when checking documents for membership in the bloom + * filter. + */ + projectId: string; + /** + * The databaseId used when checking documents for membership in the bloom + * filter. + */ + databaseId: string; + /** + * Information about the bloom filter provided by Watch in the ExistenceFilter + * message's `unchangedNames` field. If this property is omitted or undefined + * then that means that Watch did _not_ provide a bloom filter. + */ + bloomFilter?: { + /** + * Whether a full requery was averted by using the bloom filter. If false, + * then something happened, such as a false positive, to prevent using the + * bloom filter to avoid a full requery. + */ + applied: boolean; + /** The number of hash functions used in the bloom filter. */ + hashCount: number; + /** The number of bytes in the bloom filter's bitmask. */ + bitmapLength: number; + /** The number of bits of padding in the last byte of the bloom filter. */ + padding: number; + /** + * Tests the given string for membership in the bloom filter created from + * the existence filter; will be undefined if creating the bloom filter + * failed. + */ + mightContain?: (value: string) => boolean; + }; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Testing hooks for use by Firestore's integration test suite to reach into the + * SDK internals to validate logic and behavior that is not visible from the + * public API surface. + * + * @internal + */ +declare class TestingHooks { + private constructor(); + /** + * Registers a callback to be notified when an existence filter mismatch + * occurs in the Watch listen stream. + * + * The relative order in which callbacks are notified is unspecified; do not + * rely on any particular ordering. If a given callback is registered multiple + * times then it will be notified multiple times, once per registration. + * + * @param callback the callback to invoke upon existence filter mismatch. + * + * @return a function that, when called, unregisters the given callback; only + * the first invocation of the returned function does anything; all subsequent + * invocations do nothing. + */ + static onExistenceFilterMismatch(callback: ExistenceFilterMismatchCallback): Unsubscribe; +} +/** + * The signature of callbacks registered with + * `TestingUtils.onExistenceFilterMismatch()`. + * + * The return value, if any, is ignored. + * + * @internal + */ +type ExistenceFilterMismatchCallback = (info: ExistenceFilterMismatchInfo) => unknown; + +/** + * Cloud Firestore + * + * @packageDocumentation + */ + +declare module '@firebase/component' { + interface NameServiceMapping { + 'firestore': Firestore; + } +} + +export { AbstractUserDataWriter, AddPrefixToKeys, AggregateField, AggregateFieldType, AggregateQuerySnapshot, AggregateSpec, AggregateSpecData, AggregateType, AuthTokenFactory, Bytes, CACHE_SIZE_UNLIMITED, ChildUpdateFields, CollectionReference, DocumentChange, DocumentChangeType, DocumentData, DocumentReference, DocumentSnapshot, EmulatorMockTokenOptions, ExperimentalLongPollingOptions, FieldPath, FieldValue, Firestore, FirestoreDataConverter, FirestoreError$1 as FirestoreError, FirestoreErrorCode$1 as FirestoreErrorCode, FirestoreLocalCache, FirestoreSettings, FirstPartyCredentialsSettings, GeoPoint, Index, IndexConfiguration, IndexField, ListenSource, LoadBundleTask, LoadBundleTaskProgress, LogLevelString as LogLevel, MemoryCacheSettings, MemoryEagerGarbageCollector, MemoryGarbageCollector, MemoryLocalCache, MemoryLruGarbageCollector, NestedUpdateFields, OrderByDirection, PartialWithFieldValue, PersistenceSettings, PersistentCacheIndexManager, PersistentCacheSettings, PersistentLocalCache, PersistentMultipleTabManager, PersistentSingleTabManager, PersistentSingleTabManagerSettings, PersistentTabManager, Primitive, PrivateSettings, Query, QueryCompositeFilterConstraint, QueryConstraint, QueryConstraintType, QueryDocumentSnapshot, QueryEndAtConstraint, QueryFieldFilterConstraint, QueryFilterConstraint, QueryLimitConstraint, QueryNonFilterConstraint, QueryOrderByConstraint, QuerySnapshot, QueryStartAtConstraint, SetOptions, SnapshotListenOptions, SnapshotMetadata, SnapshotOptions, TaskState, Timestamp$1 as Timestamp, Transaction, TransactionOptions, UnionToIntersection, Unsubscribe, UpdateData, VectorValue, WhereFilterOp, WithFieldValue, WriteBatch, AutoId as _AutoId, ByteString as _ByteString, DatabaseId as _DatabaseId, DocumentKey as _DocumentKey, EmptyAppCheckTokenProvider as _EmptyAppCheckTokenProvider, EmptyAuthCredentialsProvider as _EmptyAuthCredentialsProvider, FieldPath$2 as _FieldPath, ResourcePath as _ResourcePath, TestingHooks as _TestingHooks, ExistenceFilterMismatchCallback as _TestingHooksExistenceFilterMismatchCallback, ExistenceFilterMismatchInfo as _TestingHooksExistenceFilterMismatchInfo, cast as _cast, debugAssert as _debugAssert, _internalAggregationQueryToProtoRunAggregationQueryRequest, _internalQueryToProtoQueryTarget, isBase64Available as _isBase64Available, logWarn as _logWarn, validateIsNotUsedTogether as _validateIsNotUsedTogether, addDoc, aggregateFieldEqual, aggregateQuerySnapshotEqual, and, arrayRemove, arrayUnion, average, clearIndexedDbPersistence, collection, collectionGroup, connectFirestoreEmulator, count, deleteAllPersistentCacheIndexes, deleteDoc, deleteField, disableNetwork, disablePersistentCacheIndexAutoCreation, doc, documentId, documentSnapshotFromJSON, enableIndexedDbPersistence, enableMultiTabIndexedDbPersistence, enableNetwork, enablePersistentCacheIndexAutoCreation, endAt, endBefore, ensureFirestoreConfigured, executeWrite, getAggregateFromServer, getCountFromServer, getDoc, getDocFromCache, getDocFromServer, getDocs, getDocsFromCache, getDocsFromServer, getFirestore, getPersistentCacheIndexManager, increment, initializeFirestore, limit, limitToLast, loadBundle, memoryEagerGarbageCollector, memoryLocalCache, memoryLruGarbageCollector, namedQuery, onSnapshot, onSnapshotResume, onSnapshotsInSync, or, orderBy, persistentLocalCache, persistentMultipleTabManager, persistentSingleTabManager, query, queryEqual, querySnapshotFromJSON, refEqual, runTransaction, serverTimestamp, setDoc, setIndexConfiguration, setLogLevel, snapshotEqual, startAfter, startAt, sum, terminate, updateDoc, vector, waitForPendingWrites, where, writeBatch }; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index.d.ts new file mode 100644 index 0000000..0541f3f --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index.d.ts @@ -0,0 +1,28 @@ +/** + * Cloud Firestore + * + * @packageDocumentation + */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Firestore } from './api/database'; +export * from './api'; +declare module '@firebase/component' { + interface NameServiceMapping { + 'firestore': Firestore; + } +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index.node.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index.node.d.ts new file mode 100644 index 0000000..952da59 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index.node.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from './api'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index.rn.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index.rn.d.ts new file mode 100644 index 0000000..952da59 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index.rn.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from './api'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index/directional_index_byte_encoder.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index/directional_index_byte_encoder.d.ts new file mode 100644 index 0000000..0038f37 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index/directional_index_byte_encoder.d.ts @@ -0,0 +1,24 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ByteString } from '../util/byte_string'; +/** An index value encoder. */ +export interface DirectionalIndexByteEncoder { + writeBytes(value: ByteString): void; + writeString(value: string): void; + writeNumber(value: number): void; + writeInfinity(): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index/firestore_index_value_writer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index/firestore_index_value_writer.d.ts new file mode 100644 index 0000000..01298c6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index/firestore_index_value_writer.d.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Value } from '../protos/firestore_proto_api'; +import { DirectionalIndexByteEncoder } from './directional_index_byte_encoder'; +/** Firestore index value writer. */ +export declare class FirestoreIndexValueWriter { + static INSTANCE: FirestoreIndexValueWriter; + private constructor(); + /** Writes an index value. */ + writeIndexValue(value: Value, encoder: DirectionalIndexByteEncoder): void; + private writeIndexValueAux; + private writeIndexString; + private writeUnlabeledIndexString; + private writeIndexMap; + private writeIndexVector; + private writeIndexArray; + private writeIndexEntityRef; + private writeValueTypeLabel; + private writeTruncationMarker; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index/index_byte_encoder.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index/index_byte_encoder.d.ts new file mode 100644 index 0000000..dce4631 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index/index_byte_encoder.d.ts @@ -0,0 +1,31 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { IndexKind } from '../model/field_index'; +import { DirectionalIndexByteEncoder } from './directional_index_byte_encoder'; +/** + * Implements `DirectionalIndexByteEncoder` using `OrderedCodeWriter` for the + * actual encoding. + */ +export declare class IndexByteEncoder { + private orderedCode; + private ascending; + private descending; + seed(encodedBytes: Uint8Array): void; + forKind(kind: IndexKind): DirectionalIndexByteEncoder; + encodedBytes(): Uint8Array; + reset(): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index/index_entry.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index/index_entry.d.ts new file mode 100644 index 0000000..fe89202 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index/index_entry.d.ts @@ -0,0 +1,49 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DbIndexEntry } from '../local/indexeddb_schema'; +import { DbIndexEntryKey, KeySafeBytes } from '../local/indexeddb_sentinels'; +import { DocumentKey } from '../model/document_key'; +/** Represents an index entry saved by the SDK in persisted storage. */ +export declare class IndexEntry { + readonly _indexId: number; + readonly _documentKey: DocumentKey; + readonly _arrayValue: Uint8Array; + readonly _directionalValue: Uint8Array; + constructor(_indexId: number, _documentKey: DocumentKey, _arrayValue: Uint8Array, _directionalValue: Uint8Array); + /** + * Returns an IndexEntry entry that sorts immediately after the current + * directional value. + */ + successor(): IndexEntry; + dbIndexEntry(uid: string, orderedDocumentKey: Uint8Array, documentKey: DocumentKey): DbIndexEntry; + dbIndexEntryKey(uid: string, orderedDocumentKey: Uint8Array, documentKey: DocumentKey): DbIndexEntryKey; +} +export declare function indexEntryComparator(left: IndexEntry, right: IndexEntry): number; +export declare function compareByteArrays(left: Uint8Array, right: Uint8Array): number; +/** + * Workaround for WebKit bug: https://bugs.webkit.org/show_bug.cgi?id=292721 + * Create a key safe representation of Uint8Array values. + * If the browser is detected as Safari or WebKit, then + * the input array will be converted to "sortable byte string". + * Otherwise, the input array will be returned in its original type. + */ +export declare function encodeKeySafeBytes(array: Uint8Array): KeySafeBytes; +/** + * Reverts the key safe representation of Uint8Array (created by + * encodeKeySafeBytes) to a normal Uint8Array. + */ +export declare function decodeKeySafeBytes(input: KeySafeBytes): Uint8Array; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index/ordered_code_writer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index/ordered_code_writer.d.ts new file mode 100644 index 0000000..be345f7 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/index/ordered_code_writer.d.ts @@ -0,0 +1,60 @@ +import { ByteString } from '../util/byte_string'; +/** + * Counts the number of zeros in a byte. + * + * Visible for testing. + */ +export declare function numberOfLeadingZerosInByte(x: number): number; +/** + * OrderedCodeWriter is a minimal-allocation implementation of the writing + * behavior defined by the backend. + * + * The code is ported from its Java counterpart. + */ +export declare class OrderedCodeWriter { + buffer: Uint8Array; + position: number; + writeBytesAscending(value: ByteString): void; + writeBytesDescending(value: ByteString): void; + /** Writes utf8 bytes into this byte sequence, ascending. */ + writeUtf8Ascending(sequence: string): void; + /** Writes utf8 bytes into this byte sequence, descending */ + writeUtf8Descending(sequence: string): void; + writeNumberAscending(val: number): void; + writeNumberDescending(val: number): void; + /** + * Writes the "infinity" byte sequence that sorts after all other byte + * sequences written in ascending order. + */ + writeInfinityAscending(): void; + /** + * Writes the "infinity" byte sequence that sorts before all other byte + * sequences written in descending order. + */ + writeInfinityDescending(): void; + /** + * Resets the buffer such that it is the same as when it was newly + * constructed. + */ + reset(): void; + seed(encodedBytes: Uint8Array): void; + /** Makes a copy of the encoded bytes in this buffer. */ + encodedBytes(): Uint8Array; + /** + * Encodes `val` into an encoding so that the order matches the IEEE 754 + * floating-point comparison results with the following exceptions: + * -0.0 < 0.0 + * all non-NaN < NaN + * NaN = NaN + */ + private toOrderedBits; + /** Writes a single byte ascending to the buffer. */ + private writeByteAscending; + /** Writes a single byte descending to the buffer. */ + private writeByteDescending; + private writeSeparatorAscending; + private writeSeparatorDescending; + private writeEscapedByteAscending; + private writeEscapedByteDescending; + private ensureAvailable; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/aggregate.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/aggregate.d.ts new file mode 100644 index 0000000..3927021 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/aggregate.d.ts @@ -0,0 +1,100 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AggregateField, AggregateQuerySnapshot, AggregateSpec } from './aggregate_types'; +import { FieldPath } from './field_path'; +import { DocumentData, Query } from './reference'; +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ +export declare function getCount(query: Query): Promise; +}, AppModelType, DbModelType>>; +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregate(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ +export declare function getAggregate(query: Query, aggregateSpec: AggregateSpecType): Promise>; +/** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ +export declare function sum(field: string | FieldPath): AggregateField; +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ +export declare function average(field: string | FieldPath): AggregateField; +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ +export declare function count(): AggregateField; +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ +export declare function aggregateFieldEqual(left: AggregateField, right: AggregateField): boolean; +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ +export declare function aggregateQuerySnapshotEqual(left: AggregateQuerySnapshot, right: AggregateQuerySnapshot): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/aggregate_types.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/aggregate_types.d.ts new file mode 100644 index 0000000..453dff1 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/aggregate_types.d.ts @@ -0,0 +1,86 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AggregateType } from '../core/aggregate'; +import { FieldPath as InternalFieldPath } from '../model/path'; +import { ApiClientObjectMap, Value } from '../protos/firestore_proto_api'; +import { average, count, sum } from './aggregate'; +import { DocumentData, Query } from './reference'; +import { AbstractUserDataWriter } from './user_data_writer'; +export { AggregateType }; +/** + * Represents an aggregation that can be performed by Firestore. + */ +export declare class AggregateField { + readonly _internalFieldPath?: InternalFieldPath | undefined; + /** A type string to uniquely identify instances of this class. */ + readonly type = "AggregateField"; + /** Indicates the aggregation operation of this AggregateField. */ + readonly aggregateType: AggregateType; + /** + * Create a new AggregateField + * @param aggregateType Specifies the type of aggregation operation to perform. + * @param _internalFieldPath Optionally specifies the field that is aggregated. + * @internal + */ + constructor(aggregateType?: AggregateType, _internalFieldPath?: InternalFieldPath | undefined); +} +/** + * The union of all `AggregateField` types that are supported by Firestore. + */ +export type AggregateFieldType = ReturnType | ReturnType | ReturnType; +/** + * Specifies a set of aggregations and their aliases. + */ +export interface AggregateSpec { + [field: string]: AggregateFieldType; +} +/** + * A type whose keys are taken from an `AggregateSpec`, and whose values are the + * result of the aggregation performed by the corresponding `AggregateField` + * from the input `AggregateSpec`. + */ +export type AggregateSpecData = { + [P in keyof T]: T[P] extends AggregateField ? U : never; +}; +/** + * The results of executing an aggregation query. + */ +export declare class AggregateQuerySnapshot { + private readonly _userDataWriter; + private readonly _data; + /** A type string to uniquely identify instances of this class. */ + readonly type = "AggregateQuerySnapshot"; + /** + * The underlying query over which the aggregations recorded in this + * `AggregateQuerySnapshot` were performed. + */ + readonly query: Query; + /** @hideconstructor */ + constructor(query: Query, _userDataWriter: AbstractUserDataWriter, _data: ApiClientObjectMap); + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ + data(): AggregateSpecData; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/bytes.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/bytes.d.ts new file mode 100644 index 0000000..e4b8e09 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/bytes.d.ts @@ -0,0 +1,83 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ByteString } from '../util/byte_string'; +import { Property } from '../util/json_validation'; +/** + * An immutable object representing an array of bytes. + */ +export declare class Bytes { + _byteString: ByteString; + /** @hideconstructor */ + constructor(byteString: ByteString); + /** + * Creates a new `Bytes` object from the given Base64 string, converting it to + * bytes. + * + * @param base64 - The Base64 string used to create the `Bytes` object. + */ + static fromBase64String(base64: string): Bytes; + /** + * Creates a new `Bytes` object from the given Uint8Array. + * + * @param array - The Uint8Array used to create the `Bytes` object. + */ + static fromUint8Array(array: Uint8Array): Bytes; + /** + * Returns the underlying bytes as a Base64-encoded string. + * + * @returns The Base64-encoded string created from the `Bytes` object. + */ + toBase64(): string; + /** + * Returns the underlying bytes in a new `Uint8Array`. + * + * @returns The Uint8Array created from the `Bytes` object. + */ + toUint8Array(): Uint8Array; + /** + * Returns a string representation of the `Bytes` object. + * + * @returns A string representation of the `Bytes` object. + */ + toString(): string; + /** + * Returns true if this `Bytes` object is equal to the provided one. + * + * @param other - The `Bytes` object to compare against. + * @returns true if this `Bytes` object is equal to the provided one. + */ + isEqual(other: Bytes): boolean; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + bytes: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `Bytes` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}. + * + * @param json a JSON object represention of a `Bytes` instance + * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): Bytes; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/components.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/components.d.ts new file mode 100644 index 0000000..a710e68 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/components.d.ts @@ -0,0 +1,49 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { _FirebaseService } from '@firebase/app'; +import { CredentialsProvider } from '../api/credentials'; +import { User } from '../auth/user'; +import { DatabaseId, DatabaseInfo } from '../core/database_info'; +import { Datastore } from '../remote/datastore'; +import { FirestoreSettingsImpl } from './settings'; +export declare const LOG_TAG = "ComponentProvider"; +/** + * An interface implemented by FirebaseFirestore that provides compatibility + * with the usage in this file. + * + * This interface mainly exists to remove a cyclic dependency. + */ +export interface FirestoreService extends _FirebaseService { + _authCredentials: CredentialsProvider; + _appCheckCredentials: CredentialsProvider; + _persistenceKey: string; + _databaseId: DatabaseId; + _terminated: boolean; + _freezeSettings(): FirestoreSettingsImpl; +} +/** + * Returns an initialized and started Datastore for the given Firestore + * instance. Callers must invoke removeComponents() when the Firestore + * instance is terminated. + */ +export declare function getDatastore(firestore: FirestoreService): Datastore; +/** + * Removes all components associated with the provided instance. Must be called + * when the `Firestore` instance is terminated. + */ +export declare function removeComponents(firestore: FirestoreService): void; +export declare function makeDatabaseInfo(databaseId: DatabaseId, appId: string, persistenceKey: string, settings: FirestoreSettingsImpl): DatabaseInfo; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/database.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/database.d.ts new file mode 100644 index 0000000..988a791 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/database.d.ts @@ -0,0 +1,179 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseApp } from '@firebase/app'; +import { EmulatorMockTokenOptions } from '@firebase/util'; +import { CredentialsProvider } from '../api/credentials'; +import { User } from '../auth/user'; +import { DatabaseId } from '../core/database_info'; +import { FirestoreService } from './components'; +import { FirestoreSettingsImpl, PrivateSettings, FirestoreSettings } from './settings'; +export { EmulatorMockTokenOptions } from '@firebase/util'; +declare module '@firebase/component' { + interface NameServiceMapping { + 'firestore/lite': Firestore; + } +} +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ +export declare class Firestore implements FirestoreService { + _authCredentials: CredentialsProvider; + _appCheckCredentials: CredentialsProvider; + readonly _databaseId: DatabaseId; + readonly _app?: FirebaseApp | undefined; + /** + * Whether it's a Firestore or Firestore Lite instance. + */ + type: 'firestore-lite' | 'firestore'; + readonly _persistenceKey: string; + private _settings; + private _settingsFrozen; + private _emulatorOptions; + private _terminateTask; + /** @hideconstructor */ + constructor(_authCredentials: CredentialsProvider, _appCheckCredentials: CredentialsProvider, _databaseId: DatabaseId, _app?: FirebaseApp | undefined); + /** + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service + * instance. + */ + get app(): FirebaseApp; + get _initialized(): boolean; + get _terminated(): boolean; + _setSettings(settings: PrivateSettings): void; + _getSettings(): FirestoreSettingsImpl; + _getEmulatorOptions(): { + mockUserToken?: EmulatorMockTokenOptions | string; + }; + _freezeSettings(): FirestoreSettingsImpl; + _delete(): Promise; + _restart(): Promise; + /** Returns a JSON-serializable representation of this `Firestore` instance. */ + toJSON(): object; + /** + * Terminates all components used by this client. Subclasses can override + * this method to clean up their own dependencies, but must also call this + * method. + * + * Only ever called once. + */ + protected _terminate(): Promise; +} +/** + * Initializes a new instance of Cloud Firestore with the provided settings. + * Can only be called before any other functions, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will + * be associated. + * @param settings - A settings object to configure the `Firestore` instance. + * @returns A newly initialized `Firestore` instance. + */ +export declare function initializeFirestore(app: FirebaseApp, settings: FirestoreSettings): Firestore; +/** + * Initializes a new instance of Cloud Firestore with the provided settings. + * Can only be called before any other functions, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will + * be associated. + * @param settings - A settings object to configure the `Firestore` instance. + * @param databaseId - The name of the database. + * @returns A newly initialized `Firestore` instance. + * @beta + */ +export declare function initializeFirestore(app: FirebaseApp, settings: FirestoreSettings, databaseId?: string): Firestore; +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @returns The {@link Firestore} instance of the provided app. + */ +export declare function getFirestore(): Firestore; +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @returns The {@link Firestore} instance of the provided app. + */ +export declare function getFirestore(app: FirebaseApp): Firestore; +/** + * Returns the existing {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param databaseId - The name of the database. + * @returns The {@link Firestore} instance of the provided app. + * @beta + */ +export declare function getFirestore(databaseId: string): Firestore; +/** + * Returns the existing {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @param databaseId - The name of the database. + * @returns The {@link Firestore} instance of the provided app. + * @beta + */ +export declare function getFirestore(app: FirebaseApp, databaseId: string): Firestore; +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ +export declare function connectFirestoreEmulator(firestore: Firestore, host: string, port: number, options?: { + mockUserToken?: EmulatorMockTokenOptions | string; +}): void; +/** + * Terminates the provided `Firestore` instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` functions + * may be used. Any other function will throw a `FirestoreError`. Termination + * does not cancel any pending writes, and any promises that are awaiting a + * response from the server will not be resolved. + * + * To restart after termination, create a new instance of `Firestore` with + * {@link (getFirestore:1)}. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all of + * its resources or in combination with {@link clearIndexedDbPersistence} to + * ensure that all local state is destroyed between test runs. + * + * @param firestore - The `Firestore` instance to terminate. + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ +export declare function terminate(firestore: Firestore): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/field_path.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/field_path.d.ts new file mode 100644 index 0000000..38faa8f --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/field_path.d.ts @@ -0,0 +1,48 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FieldPath as InternalFieldPath } from '../model/path'; +/** + * A `FieldPath` refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + * + * Create a `FieldPath` by providing field names. If more than one field + * name is provided, the path will point to a nested field in a document. + */ +export declare class FieldPath { + /** Internal representation of a Firestore field path. */ + readonly _internalPath: InternalFieldPath; + /** + * Creates a `FieldPath` from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames - A list of field names. + */ + constructor(...fieldNames: string[]); + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other - The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ + isEqual(other: FieldPath): boolean; +} +/** + * Returns a special sentinel `FieldPath` to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ +export declare function documentId(): FieldPath; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/field_value.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/field_value.d.ts new file mode 100644 index 0000000..5e44c8e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/field_value.d.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ParseContext } from '../api/parse_context'; +import { FieldTransform } from '../model/mutation'; +/** + * Sentinel values that can be used when writing document fields with `set()` + * or `update()`. + */ +export declare abstract class FieldValue { + _methodName: string; + /** + * @param _methodName - The public API endpoint that returns this class. + * @hideconstructor + */ + constructor(_methodName: string); + /** Compares `FieldValue`s for equality. */ + abstract isEqual(other: FieldValue): boolean; + abstract _toFieldTransform(context: ParseContext): FieldTransform | null; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/field_value_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/field_value_impl.d.ts new file mode 100644 index 0000000..019e460 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/field_value_impl.d.ts @@ -0,0 +1,81 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FieldValue } from './field_value'; +import { VectorValue } from './vector_value'; +/** + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. + */ +export declare function deleteField(): FieldValue; +/** + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to + * include a server-generated timestamp in the written data. + */ +export declare function serverTimestamp(): FieldValue; +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array + * value that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements - The elements to union into the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()`. + */ +export declare function arrayUnion(...elements: unknown[]): FieldValue; +/** + * Returns a special value that can be used with {@link (setDoc:1)} or {@link + * updateDoc:1} that tells the server to remove the given elements from any + * array value that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is not + * already an array it will be overwritten with an empty array. + * + * @param elements - The elements to remove from the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +export declare function arrayRemove(...elements: unknown[]): FieldValue; +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by + * the given value. + * + * If either the operand or the current field value uses floating point + * precision, all arithmetic follows IEEE 754 semantics. If both values are + * integers, values outside of JavaScript's safe number range + * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to + * precision loss. Furthermore, once processed by the Firestore backend, all + * integer operations are capped between -2^63 and 2^63-1. + * + * If the current field value is not of type `number`, or if the field does not + * yet exist, the transformation sets the field to the given value. + * + * @param n - The value to increment by. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +export declare function increment(n: number): FieldValue; +/** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ +export declare function vector(values?: number[]): VectorValue; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/geo_point.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/geo_point.d.ts new file mode 100644 index 0000000..bfe8cd5 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/geo_point.d.ts @@ -0,0 +1,79 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Property } from '../util/json_validation'; +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ +export declare class GeoPoint { + private _lat; + private _long; + /** + * Creates a new immutable `GeoPoint` object with the provided latitude and + * longitude values. + * @param latitude - The latitude as number between -90 and 90. + * @param longitude - The longitude as number between -180 and 180. + */ + constructor(latitude: number, longitude: number); + /** + * The latitude of this `GeoPoint` instance. + */ + get latitude(): number; + /** + * The longitude of this `GeoPoint` instance. + */ + get longitude(): number; + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other - The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ + isEqual(other: GeoPoint): boolean; + /** + * Actually private to JS consumers of our API, so this function is prefixed + * with an underscore. + */ + _compareTo(other: GeoPoint): number; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + latitude: Property<"number">; + longitude: Property<"number">; + }; + /** + * Returns a JSON-serializable representation of this `GeoPoint` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): { + latitude: number; + longitude: number; + type: string; + }; + /** + * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}. + * + * @param json a JSON object represention of a `GeoPoint` instance + * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): GeoPoint; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/query.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/query.d.ts new file mode 100644 index 0000000..9053d9d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/query.d.ts @@ -0,0 +1,404 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Bound } from '../core/bound'; +import { DatabaseId } from '../core/database_info'; +import { CompositeOperator, FieldFilter, Filter, Operator } from '../core/filter'; +import { Direction, OrderBy } from '../core/order_by'; +import { LimitType, Query as InternalQuery } from '../core/query'; +import { Document } from '../model/document'; +import { FieldPath as InternalFieldPath } from '../model/path'; +import { FieldPath } from './field_path'; +import { DocumentData, Query } from './reference'; +import { DocumentSnapshot } from './snapshot'; +import { UserDataReader } from './user_data_reader'; +export declare function validateHasExplicitOrderByForLimitToLast(query: InternalQuery): void; +/** Describes the different query constraints available in this SDK. */ +export type QueryConstraintType = 'where' | 'orderBy' | 'limit' | 'limitToLast' | 'startAt' | 'startAfter' | 'endAt' | 'endBefore'; +/** + * An `AppliableConstraint` is an abstraction of a constraint that can be applied + * to a Firestore query. + */ +export declare abstract class AppliableConstraint { + /** + * Takes the provided {@link Query} and returns a copy of the {@link Query} with this + * {@link AppliableConstraint} applied. + */ + abstract _apply(query: Query): Query; +} +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Firestore query. `QueryConstraint`s are created by invoking {@link where}, + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that + * also contains this `QueryConstraint`. + */ +export declare abstract class QueryConstraint extends AppliableConstraint { + /** The type of this query constraint */ + abstract readonly type: QueryConstraintType; + /** + * Takes the provided {@link Query} and returns a copy of the {@link Query} with this + * {@link AppliableConstraint} applied. + */ + abstract _apply(query: Query): Query; +} +/** + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. + * + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to + * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or + * {@link or}. + * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to + * apply (e.g. {@link orderBy}, {@link limit}). + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query(query: Query, compositeFilter: QueryCompositeFilterConstraint, ...queryConstraints: QueryNonFilterConstraint[]): Query; +/** + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. + * + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param queryConstraints - The list of {@link QueryConstraint}s to apply. + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query(query: Query, ...queryConstraints: QueryConstraint[]): Query; +/** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ +export declare class QueryFieldFilterConstraint extends QueryConstraint { + private readonly _field; + private _op; + private _value; + /** The type of this query constraint */ + readonly type = "where"; + /** + * @internal + */ + protected constructor(_field: InternalFieldPath, _op: Operator, _value: unknown); + static _create(_field: InternalFieldPath, _op: Operator, _value: unknown): QueryFieldFilterConstraint; + _apply(query: Query): Query; + _parse(query: Query): FieldFilter; +} +/** + * Filter conditions in a {@link where} clause are specified using the + * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in', + * 'array-contains-any', and 'not-in'. + */ +export type WhereFilterOp = '<' | '<=' | '==' | '!=' | '>=' | '>' | 'array-contains' | 'in' | 'array-contains-any' | 'not-in'; +/** + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. + * + * @param fieldPath - The path to compare + * @param opStr - The operation string (e.g "<", "<=", "==", "<", + * "<=", "!="). + * @param value - The value for comparison + * @returns The created {@link QueryFieldFilterConstraint}. + */ +export declare function where(fieldPath: string | FieldPath, opStr: WhereFilterOp, value: unknown): QueryFieldFilterConstraint; +/** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ +export declare class QueryCompositeFilterConstraint extends AppliableConstraint { + /** The type of this query constraint */ + readonly type: 'or' | 'and'; + private readonly _queryConstraints; + /** + * @internal + */ + protected constructor( + /** The type of this query constraint */ + type: 'or' | 'and', _queryConstraints: QueryFilterConstraint[]); + static _create(type: 'or' | 'and', _queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; + _parse(query: Query): Filter; + _apply(query: Query): Query; + _getQueryConstraints(): readonly AppliableConstraint[]; + _getOperator(): CompositeOperator; +} +/** + * `QueryNonFilterConstraint` is a helper union type that represents + * QueryConstraints which are used to narrow or order the set of documents, + * but that do not explicitly filter on a document field. + * `QueryNonFilterConstraint`s are created by invoking {@link orderBy}, + * {@link (startAt:1)}, {@link (startAfter:1)}, {@link (endBefore:1)}, {@link (endAt:1)}, + * {@link limit} or {@link limitToLast} and can then be passed to {@link (query:1)} + * to create a new query instance that also contains the `QueryConstraint`. + */ +export type QueryNonFilterConstraint = QueryOrderByConstraint | QueryLimitConstraint | QueryStartAtConstraint | QueryEndAtConstraint; +/** + * `QueryFilterConstraint` is a helper union type that represents + * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}. + */ +export type QueryFilterConstraint = QueryFieldFilterConstraint | QueryCompositeFilterConstraint; +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +export declare function or(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +export declare function and(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; +/** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ +export declare class QueryOrderByConstraint extends QueryConstraint { + private readonly _field; + private _direction; + /** The type of this query constraint */ + readonly type = "orderBy"; + /** + * @internal + */ + protected constructor(_field: InternalFieldPath, _direction: Direction); + static _create(_field: InternalFieldPath, _direction: Direction): QueryOrderByConstraint; + _apply(query: Query): Query; +} +/** + * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc' + * (descending or ascending). + */ +export type OrderByDirection = 'desc' | 'asc'; +/** + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the + * specified field, optionally in descending order instead of ascending. + * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * + * @param fieldPath - The field to sort by. + * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @returns The created {@link QueryOrderByConstraint}. + */ +export declare function orderBy(fieldPath: string | FieldPath, directionStr?: OrderByDirection): QueryOrderByConstraint; +/** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ +export declare class QueryLimitConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'limit' | 'limitToLast'; + private readonly _limit; + private readonly _limitType; + /** + * @internal + */ + protected constructor( + /** The type of this query constraint */ + type: 'limit' | 'limitToLast', _limit: number, _limitType: LimitType); + static _create(type: 'limit' | 'limitToLast', _limit: number, _limitType: LimitType): QueryLimitConstraint; + _apply(query: Query): Query; +} +/** + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +export declare function limit(limit: number): QueryLimitConstraint; +/** + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. + * + * You must specify at least one `orderBy` clause for `limitToLast` queries, + * otherwise an exception will be thrown during execution. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +export declare function limitToLast(limit: number): QueryLimitConstraint; +/** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ +export declare class QueryStartAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'startAt' | 'startAfter'; + private readonly _docOrFields; + private readonly _inclusive; + /** + * @internal + */ + protected constructor( + /** The type of this query constraint */ + type: 'startAt' | 'startAfter', _docOrFields: Array>, _inclusive: boolean); + static _create(type: 'startAt' | 'startAfter', _docOrFields: Array>, _inclusive: boolean): QueryStartAtConstraint; + _apply(query: Query): Query; +} +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided document (inclusive). The starting position is relative + * to the order of the query. The document must contain all of the fields + * provided in the `orderBy` of this query. + * + * @param snapshot - The snapshot of the document to start at. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. + */ +export declare function startAt(snapshot: DocumentSnapshot): QueryStartAtConstraint; +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to start this query at, in order + * of the query's order by. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. + */ +export declare function startAt(...fieldValues: unknown[]): QueryStartAtConstraint; +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided document (exclusive). The starting position is + * relative to the order of the query. The document must contain all of the + * fields provided in the orderBy of the query. + * + * @param snapshot - The snapshot of the document to start after. + * @returns A {@link QueryStartAtConstraint} to pass to `query()` + */ +export declare function startAfter(snapshot: DocumentSnapshot): QueryStartAtConstraint; +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided fields relative to the order of the query. The order + * of the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to start this query after, in order + * of the query's order by. + * @returns A {@link QueryStartAtConstraint} to pass to `query()` + */ +export declare function startAfter(...fieldValues: unknown[]): QueryStartAtConstraint; +/** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ +export declare class QueryEndAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'endBefore' | 'endAt'; + private readonly _docOrFields; + private readonly _inclusive; + /** + * @internal + */ + protected constructor( + /** The type of this query constraint */ + type: 'endBefore' | 'endAt', _docOrFields: Array>, _inclusive: boolean); + static _create(type: 'endBefore' | 'endAt', _docOrFields: Array>, _inclusive: boolean): QueryEndAtConstraint; + _apply(query: Query): Query; +} +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided document (exclusive). The end position is relative to the + * order of the query. The document must contain all of the fields provided in + * the orderBy of the query. + * + * @param snapshot - The snapshot of the document to end before. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endBefore(snapshot: DocumentSnapshot): QueryEndAtConstraint; +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to end this query before, in order + * of the query's order by. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endBefore(...fieldValues: unknown[]): QueryEndAtConstraint; +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided document (inclusive). The end position is relative to the order + * of the query. The document must contain all of the fields provided in the + * orderBy of the query. + * + * @param snapshot - The snapshot of the document to end at. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endAt(snapshot: DocumentSnapshot): QueryEndAtConstraint; +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided fields relative to the order of the query. The order of the field + * values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to end this query at, in order + * of the query's order by. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endAt(...fieldValues: unknown[]): QueryEndAtConstraint; +export declare function newQueryFilter(query: InternalQuery, methodName: string, dataReader: UserDataReader, databaseId: DatabaseId, fieldPath: InternalFieldPath, op: Operator, value: unknown): FieldFilter; +export declare function newQueryOrderBy(query: InternalQuery, fieldPath: InternalFieldPath, direction: Direction): OrderBy; +/** + * Create a `Bound` from a query and a document. + * + * Note that the `Bound` will always include the key of the document + * and so only the provided document will compare equal to the returned + * position. + * + * Will throw if the document does not contain all fields of the order by + * of the query or if any of the fields in the order by are an uncommitted + * server timestamp. + */ +export declare function newQueryBoundFromDocument(query: InternalQuery, databaseId: DatabaseId, methodName: string, doc: Document | null, inclusive: boolean): Bound; +/** + * Converts a list of field values to a `Bound` for the given query. + */ +export declare function newQueryBoundFromFields(query: InternalQuery, databaseId: DatabaseId, dataReader: UserDataReader, methodName: string, values: unknown[], inclusive: boolean): Bound; +export declare function validateQueryFilterConstraint(functionName: string, queryConstraint: AppliableConstraint): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/reference.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/reference.d.ts new file mode 100644 index 0000000..fd89e5a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/reference.d.ts @@ -0,0 +1,362 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Query as InternalQuery } from '../core/query'; +import { DocumentKey } from '../model/document_key'; +import { ResourcePath } from '../model/path'; +import { Property } from '../util/json_validation'; +import { Firestore } from './database'; +import { FieldPath } from './field_path'; +import { FieldValue } from './field_value'; +import { FirestoreDataConverter } from './snapshot'; +import { NestedUpdateFields, Primitive } from './types'; +/** + * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to + * values. + */ +export interface DocumentData { + /** A mapping between a field and its value. */ + [field: string]: any; +} +/** + * Similar to TypeScript's `Partial`, but allows nested fields to be + * omitted and FieldValues to be passed in as property values. + */ +export type PartialWithFieldValue = Partial | (T extends Primitive ? T : T extends {} ? { + [K in keyof T]?: PartialWithFieldValue | FieldValue; +} : never); +/** + * Allows FieldValues to be passed in as a property value while maintaining + * type safety. + */ +export type WithFieldValue = T | (T extends Primitive ? T : T extends {} ? { + [K in keyof T]: WithFieldValue | FieldValue; +} : never); +/** + * Update data (for use with {@link (updateDoc:1)}) that consists of field paths + * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots + * reference nested fields within the document. FieldValues can be passed in + * as property values. + */ +export type UpdateData = T extends Primitive ? T : T extends {} ? { + [K in keyof T]?: UpdateData | FieldValue; +} & NestedUpdateFields : Partial; +/** + * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link + * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be + * configured to perform granular merges instead of overwriting the target + * documents in their entirety by providing a `SetOptions` with `merge: true`. + * + * @param merge - Changes the behavior of a `setDoc()` call to only replace the + * values specified in its data argument. Fields omitted from the `setDoc()` + * call remain untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace + * the specified field paths. Any field path that is not specified is ignored + * and remains untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + */ +export type SetOptions = { + readonly merge?: boolean; +} | { + readonly mergeFields?: Array; +}; +/** + * A `Query` refers to a query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ +export declare class Query { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter | null; + readonly _query: InternalQuery; + /** The type of this Firestore reference. */ + readonly type: 'query' | 'collection'; + /** + * The `Firestore` instance for the Firestore database (useful for performing + * transactions, etc.). + */ + readonly firestore: Firestore; + /** @hideconstructor protected */ + constructor(firestore: Firestore, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter: FirestoreDataConverter | null, _query: InternalQuery); + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `Query` that does not use a + * converter. + */ + withConverter(converter: null): Query; + /** + * Applies a custom data converter to this query, allowing you to use your own + * custom model objects with Firestore. When you call {@link getDocs} with + * the returned query, the provided converter will convert between Firestore + * data of type `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `Query` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter): Query; +} +/** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. + */ +export declare class DocumentReference { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter | null; + readonly _key: DocumentKey; + /** The type of this Firestore reference. */ + readonly type = "document"; + /** + * The {@link Firestore} instance the document is in. + * This is useful for performing transactions, for example. + */ + readonly firestore: Firestore; + /** @hideconstructor */ + constructor(firestore: Firestore, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter: FirestoreDataConverter | null, _key: DocumentKey); + get _path(): ResourcePath; + /** + * The document's identifier within its collection. + */ + get id(): string; + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ + get path(): string; + /** + * The collection this `DocumentReference` belongs to. + */ + get parent(): CollectionReference; + /** + * Applies a custom data converter to this `DocumentReference`, allowing you + * to use your own custom model objects with Firestore. When you call {@link + * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference` + * instance, the provided converter will convert between Firestore data of + * type `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `DocumentReference` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter): DocumentReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `DocumentReference` that does not + * use a converter. + */ + withConverter(converter: null): DocumentReference; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + referencePath: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `DocumentReference` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `DocumentReference` instance from a JSON object created by + * {@link DocumentReference.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json a JSON object represention of a `DocumentReference` instance + * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(firestore: Firestore, json: object): DocumentReference; + /** + * Builds a `DocumentReference` instance from a JSON object created by + * {@link DocumentReference.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json a JSON object represention of a `DocumentReference` instance + * @param converter - Converts objects to and from Firestore. + * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(firestore: Firestore, json: object, converter: FirestoreDataConverter): DocumentReference; +} +/** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using {@link (query:1)}). + */ +export declare class CollectionReference extends Query { + readonly _path: ResourcePath; + /** The type of this Firestore reference. */ + readonly type = "collection"; + /** @hideconstructor */ + constructor(firestore: Firestore, converter: FirestoreDataConverter | null, _path: ResourcePath); + /** The collection's identifier. */ + get id(): string; + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ + get path(): string; + /** + * A reference to the containing `DocumentReference` if this is a + * subcollection. If this isn't a subcollection, the reference is null. + */ + get parent(): DocumentReference | null; + /** + * Applies a custom data converter to this `CollectionReference`, allowing you + * to use your own custom model objects with Firestore. When you call {@link + * addDoc} with the returned `CollectionReference` instance, the provided + * converter will convert between Firestore data of type `NewDbModelType` and + * your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `CollectionReference` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter): CollectionReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `CollectionReference` that does not + * use a converter. + */ + withConverter(converter: null): CollectionReference; +} +/** + * Gets a `CollectionReference` instance that refers to the collection at + * the specified absolute path. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments to apply relative to the first + * argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(firestore: Firestore, path: string, ...pathSegments: string[]): CollectionReference; +/** + * Gets a `CollectionReference` instance that refers to a subcollection of + * `reference` at the specified relative path. + * + * @param reference - A reference to a collection. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments to apply relative to the first + * argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(reference: CollectionReference, path: string, ...pathSegments: string[]): CollectionReference; +/** + * Gets a `CollectionReference` instance that refers to a subcollection of + * `reference` at the specified relative path. + * + * @param reference - A reference to a Firestore document. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(reference: DocumentReference, path: string, ...pathSegments: string[]): CollectionReference; +/** + * Creates and returns a new `Query` instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given `collectionId`. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param collectionId - Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `Query`. + */ +export declare function collectionGroup(firestore: Firestore, collectionId: string): Query; +/** + * Gets a `DocumentReference` instance that refers to the document at the + * specified absolute path. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param path - A slash-separated path to a document. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(firestore: Firestore, path: string, ...pathSegments: string[]): DocumentReference; +/** + * Gets a `DocumentReference` instance that refers to a document within + * `reference` at the specified relative path. If no path is specified, an + * automatically-generated unique ID will be used for the returned + * `DocumentReference`. + * + * @param reference - A reference to a collection. + * @param path - A slash-separated path to a document. Has to be omitted to use + * auto-generated IDs. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(reference: CollectionReference, path?: string, ...pathSegments: string[]): DocumentReference; +/** + * Gets a `DocumentReference` instance that refers to a document within + * `reference` at the specified relative path. + * + * @param reference - A reference to a Firestore document. + * @param path - A slash-separated path to a document. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(reference: DocumentReference, path: string, ...pathSegments: string[]): DocumentReference; +/** + * Returns true if the provided references are equal. + * + * @param left - A reference to compare. + * @param right - A reference to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +export declare function refEqual(left: DocumentReference | CollectionReference, right: DocumentReference | CollectionReference): boolean; +/** + * Returns true if the provided queries point to the same collection and apply + * the same constraints. + * + * @param left - A `Query` to compare. + * @param right - A `Query` to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +export declare function queryEqual(left: Query, right: Query): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/reference_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/reference_impl.d.ts new file mode 100644 index 0000000..724ae99 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/reference_impl.d.ts @@ -0,0 +1,172 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentData as PublicDocumentData, SetOptions as PublicSetOptions } from '@firebase/firestore-types'; +import { ByteString } from '../util/byte_string'; +import { Bytes } from './bytes'; +import { Firestore } from './database'; +import { FieldPath } from './field_path'; +import { CollectionReference, DocumentData, DocumentReference, PartialWithFieldValue, Query, SetOptions, UpdateData, WithFieldValue } from './reference'; +import { DocumentSnapshot, QuerySnapshot } from './snapshot'; +import { UntypedFirestoreDataConverter } from './user_data_reader'; +import { AbstractUserDataWriter } from './user_data_writer'; +/** + * Converts custom model object of type T into `DocumentData` by applying the + * converter if it exists. + * + * This function is used when converting user objects to `DocumentData` + * because we want to provide the user with a more specific error message if + * their `set()` or fails due to invalid data originating from a `toFirestore()` + * call. + */ +export declare function applyFirestoreDataConverter(converter: UntypedFirestoreDataConverter | null, value: WithFieldValue | PartialWithFieldValue, options?: PublicSetOptions): PublicDocumentData; +export declare class LiteUserDataWriter extends AbstractUserDataWriter { + protected firestore: Firestore; + constructor(firestore: Firestore); + protected convertBytes(bytes: ByteString): Bytes; + protected convertReference(name: string): DocumentReference; +} +/** + * Reads the document referred to by the specified document reference. + * + * All documents are directly fetched from the server, even if the document was + * previously read or modified. Recent modifications are only reflected in the + * retrieved `DocumentSnapshot` if they have already been applied by the + * backend. If the client is offline, the read fails. If you like to use + * caching or see local modifications, please use the full Firestore SDK. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the current + * document contents. + */ +export declare function getDoc(reference: DocumentReference): Promise>; +/** + * Executes the query and returns the results as a {@link QuerySnapshot}. + * + * All queries are executed directly by the server, even if the query was + * previously executed. Recent modifications are only reflected in the retrieved + * results if they have already been applied by the backend. If the client is + * offline, the operation fails. To see previously cached result and local + * modifications, use the full Firestore SDK. + * + * @param query - The `Query` to execute. + * @returns A Promise that will be resolved with the results of the query. + */ +export declare function getDocs(query: Query): Promise>; +/** + * Writes to the document referred to by the specified `DocumentReference`. If + * the document does not yet exist, it will be created. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function setDoc(reference: DocumentReference, data: WithFieldValue): Promise; +/** + * Writes to the document referred to by the specified `DocumentReference`. If + * the document does not yet exist, it will be created. If you provide `merge` + * or `mergeFields`, the provided data can be merged into an existing document. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function setDoc(reference: DocumentReference, data: PartialWithFieldValue, options: SetOptions): Promise; +/** + * Updates fields in the document referred to by the specified + * `DocumentReference`. The update will fail if applied to a document that does + * not exist. + * + * The result of this update will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * update fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to update. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function updateDoc(reference: DocumentReference, data: UpdateData): Promise; +/** + * Updates fields in the document referred to by the specified + * `DocumentReference` The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * The result of this update will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * update fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to update. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function updateDoc(reference: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): Promise; +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * The deletion will only be reflected in document reads that occur after the + * returned promise resolves. If the client is offline, the + * delete fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to delete. + * @returns A `Promise` resolved once the document has been successfully + * deleted from the backend. + */ +export declare function deleteDoc(reference: DocumentReference): Promise; +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend. + */ +export declare function addDoc(reference: CollectionReference, data: WithFieldValue): Promise>; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/settings.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/settings.d.ts new file mode 100644 index 0000000..e86bdbe --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/settings.d.ts @@ -0,0 +1,77 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { EmulatorMockTokenOptions } from '@firebase/util'; +import { FirestoreLocalCache } from '../api/cache_config'; +import { CredentialsSettings } from '../api/credentials'; +import { ExperimentalLongPollingOptions } from '../api/long_polling_options'; +export declare const DEFAULT_HOST = "firestore.googleapis.com"; +export declare const DEFAULT_SSL = true; +/** + * Specifies custom configurations for your Cloud Firestore instance. + * You must set these before invoking any other methods. + */ +export interface FirestoreSettings { + /** The hostname to connect to. */ + host?: string; + /** Whether to use SSL when connecting. */ + ssl?: boolean; + /** + * Whether to skip nested properties that are set to `undefined` during + * object serialization. If set to `true`, these properties are skipped + * and not written to Firestore. If set to `false` or omitted, the SDK + * throws an exception when it encounters properties of type `undefined`. + */ + ignoreUndefinedProperties?: boolean; +} +/** + * @internal + * Undocumented, private additional settings not exposed in our public API. + */ +export interface PrivateSettings extends FirestoreSettings { + credentials?: CredentialsSettings; + cacheSizeBytes?: number; + experimentalForceLongPolling?: boolean; + experimentalAutoDetectLongPolling?: boolean; + experimentalLongPollingOptions?: ExperimentalLongPollingOptions; + useFetchStreams?: boolean; + emulatorOptions?: { + mockUserToken?: EmulatorMockTokenOptions | string; + }; + localCache?: FirestoreLocalCache; +} +/** + * A concrete type describing all the values that can be applied via a + * user-supplied `FirestoreSettings` object. This is a separate type so that + * defaults can be supplied and the value can be checked for equality. + */ +export declare class FirestoreSettingsImpl { + /** The hostname to connect to. */ + readonly host: string; + /** Whether to use SSL when connecting. */ + readonly ssl: boolean; + readonly cacheSizeBytes: number; + readonly experimentalForceLongPolling: boolean; + readonly experimentalAutoDetectLongPolling: boolean; + readonly experimentalLongPollingOptions: ExperimentalLongPollingOptions; + readonly ignoreUndefinedProperties: boolean; + readonly useFetchStreams: boolean; + readonly localCache?: FirestoreLocalCache; + readonly isUsingEmulator: boolean; + credentials?: any; + constructor(settings: PrivateSettings); + isEqual(other: FirestoreSettingsImpl): boolean; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/snapshot.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/snapshot.d.ts new file mode 100644 index 0000000..312e3f3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/snapshot.d.ts @@ -0,0 +1,367 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Compat } from '@firebase/util'; +import { Document } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { FieldPath as InternalFieldPath } from '../model/path'; +import { Firestore } from './database'; +import { FieldPath } from './field_path'; +import { DocumentData, DocumentReference, PartialWithFieldValue, Query, SetOptions, WithFieldValue } from './reference'; +import { UntypedFirestoreDataConverter } from './user_data_reader'; +import { AbstractUserDataWriter } from './user_data_writer'; +/** + * Converter used by `withConverter()` to transform user objects of type + * `AppModelType` into Firestore data of type `DbModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * In this context, an "AppModel" is a class that is used in an application to + * package together related information and functionality. Such a class could, + * for example, have properties with complex, nested data types, properties used + * for memoization, properties of types not supported by Firestore (such as + * `symbol` and `bigint`), and helper functions that perform compound + * operations. Such classes are not suitable and/or possible to store into a + * Firestore database. Instead, instances of such classes need to be converted + * to "plain old JavaScript objects" (POJOs) with exclusively primitive + * properties, potentially nested inside other POJOs or arrays of POJOs. In this + * context, this type is referred to as the "DbModel" and would be an object + * suitable for persisting into Firestore. For convenience, applications can + * implement `FirestoreDataConverter` and register the converter with Firestore + * objects, such as `DocumentReference` or `Query`, to automatically convert + * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel` + * to `AppModel` when retrieving from Firestore. + * + * @example + * + * Simple Example + * + * ```typescript + * const numberConverter = { + * toFirestore(value: WithFieldValue) { + * return { value }; + * }, + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) { + * return snapshot.data(options).value as number; + * } + * }; + * + * async function simpleDemo(db: Firestore): Promise { + * const documentRef = doc(db, 'values/value123').withConverter(numberConverter); + * + * // converters are used with `setDoc`, `addDoc`, and `getDoc` + * await setDoc(documentRef, 42); + * const snapshot1 = await getDoc(documentRef); + * assertEqual(snapshot1.data(), 42); + * + * // converters are not used when writing data with `updateDoc` + * await updateDoc(documentRef, { value: 999 }); + * const snapshot2 = await getDoc(documentRef); + * assertEqual(snapshot2.data(), 999); + * } + * ``` + * + * Advanced Example + * + * ```typescript + * // The Post class is a model that is used by our application. + * // This class may have properties and methods that are specific + * // to our application execution, which do not need to be persisted + * // to Firestore. + * class Post { + * constructor( + * readonly title: string, + * readonly author: string, + * readonly lastUpdatedMillis: number + * ) {} + * toString(): string { + * return `${this.title} by ${this.author}`; + * } + * } + * + * // The PostDbModel represents how we want our posts to be stored + * // in Firestore. This DbModel has different properties (`ttl`, + * // `aut`, and `lut`) from the Post class we use in our application. + * interface PostDbModel { + * ttl: string; + * aut: { firstName: string; lastName: string }; + * lut: Timestamp; + * } + * + * // The `PostConverter` implements `FirestoreDataConverter` and specifies + * // how the Firestore SDK can convert `Post` objects to `PostDbModel` + * // objects and vice versa. + * class PostConverter implements FirestoreDataConverter { + * toFirestore(post: WithFieldValue): WithFieldValue { + * return { + * ttl: post.title, + * aut: this._autFromAuthor(post.author), + * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis) + * }; + * } + * + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post { + * const data = snapshot.data(options) as PostDbModel; + * const author = `${data.aut.firstName} ${data.aut.lastName}`; + * return new Post(data.ttl, author, data.lut.toMillis()); + * } + * + * _autFromAuthor( + * author: string | FieldValue + * ): { firstName: string; lastName: string } | FieldValue { + * if (typeof author !== 'string') { + * // `author` is a FieldValue, so just return it. + * return author; + * } + * const [firstName, lastName] = author.split(' '); + * return {firstName, lastName}; + * } + * + * _lutFromLastUpdatedMillis( + * lastUpdatedMillis: number | FieldValue + * ): Timestamp | FieldValue { + * if (typeof lastUpdatedMillis !== 'number') { + * // `lastUpdatedMillis` must be a FieldValue, so just return it. + * return lastUpdatedMillis; + * } + * return Timestamp.fromMillis(lastUpdatedMillis); + * } + * } + * + * async function advancedDemo(db: Firestore): Promise { + * // Create a `DocumentReference` with a `FirestoreDataConverter`. + * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter()); + * + * // The `data` argument specified to `setDoc()` is type checked by the + * // TypeScript compiler to be compatible with `Post`. Since the `data` + * // argument is typed as `WithFieldValue` rather than just `Post`, + * // this allows properties of the `data` argument to also be special + * // Firestore values that perform server-side mutations, such as + * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`. + * await setDoc(documentRef, { + * title: 'My Life', + * author: 'Foo Bar', + * lastUpdatedMillis: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `setDoc()` is _not_ compatible with `WithFieldValue`. This + * // type checking prevents the caller from specifying objects with incorrect + * // properties or property values. + * // @ts-expect-error "Argument of type { ttl: string; } is not assignable + * // to parameter of type WithFieldValue" + * await setDoc(documentRef, { ttl: 'The Title' }); + * + * // When retrieving a document with `getDoc()` the `DocumentSnapshot` + * // object's `data()` method returns a `Post`, rather than a generic object, + * // which would have been returned if the `DocumentReference` did _not_ have a + * // `FirestoreDataConverter` attached to it. + * const snapshot1: DocumentSnapshot = await getDoc(documentRef); + * const post1: Post = snapshot1.data()!; + * if (post1) { + * assertEqual(post1.title, 'My Life'); + * assertEqual(post1.author, 'Foo Bar'); + * } + * + * // The `data` argument specified to `updateDoc()` is type checked by the + * // TypeScript compiler to be compatible with `PostDbModel`. Note that + * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`, + * // the `data` argument to `updateDoc()` must be compatible with + * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed + * // as `WithFieldValue` rather than just `PostDbModel`, this + * // allows properties of the `data` argument to also be those special + * // Firestore values, like `arrayRemove()`, `deleteField()`, and + * // `serverTimestamp()`. + * await updateDoc(documentRef, { + * 'aut.firstName': 'NewFirstName', + * lut: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `updateDoc()` is _not_ compatible with `WithFieldValue`. + * // This type checking prevents the caller from specifying objects with + * // incorrect properties or property values. + * // @ts-expect-error "Argument of type { title: string; } is not assignable + * // to parameter of type WithFieldValue" + * await updateDoc(documentRef, { title: 'New Title' }); + * const snapshot2: DocumentSnapshot = await getDoc(documentRef); + * const post2: Post = snapshot2.data()!; + * if (post2) { + * assertEqual(post2.title, 'My Life'); + * assertEqual(post2.author, 'NewFirstName Bar'); + * } + * } + * ``` + */ +export interface FirestoreDataConverter { + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link @firebase/firestore/lite#(setDoc:1)}, + * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and + * {@link @firebase/firestore/lite#(Transaction.set:1)}. + * + * The `WithFieldValue` type extends `T` to also allow FieldValues such as + * {@link (deleteField:1)} to be used as property values. + */ + toFirestore(modelObject: WithFieldValue): WithFieldValue; + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link @firebase/firestore/lite#(setDoc:1)}, + * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and + * {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true` + * or `mergeFields`. + * + * The `PartialWithFieldValue` type extends `Partial` to allow + * FieldValues such as {@link (arrayUnion:1)} to be used as property values. + * It also supports nested `Partial` by allowing nested fields to be + * omitted. + */ + toFirestore(modelObject: PartialWithFieldValue, options: SetOptions): PartialWithFieldValue; + /** + * Called by the Firestore SDK to convert Firestore data into an object of + * type `AppModelType`. You can access your data by calling: + * `snapshot.data()`. + * + * + * Generally, the data returned from `snapshot.data()` can be cast to + * `DbModelType`; however, this is not guaranteed because Firestore does not + * enforce a schema on the database. For example, writes from a previous + * version of the application or writes from another client that did not use a + * type converter could have written data with different properties and/or + * property types. The implementation will need to choose whether to + * gracefully recover from non-conforming data or throw an error. + * + * @param snapshot - A `QueryDocumentSnapshot` containing your data and + * metadata. + */ + fromFirestore(snapshot: QueryDocumentSnapshot): AppModelType; +} +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ +export declare class DocumentSnapshot { + _firestore: Firestore; + _userDataWriter: AbstractUserDataWriter; + _key: DocumentKey; + _document: Document | null; + _converter: UntypedFirestoreDataConverter | null; + /** @hideconstructor protected */ + constructor(_firestore: Firestore, _userDataWriter: AbstractUserDataWriter, _key: DocumentKey, _document: Document | null, _converter: UntypedFirestoreDataConverter | null); + /** Property of the `DocumentSnapshot` that provides the document's ID. */ + get id(): string; + /** + * The `DocumentReference` for the document included in the `DocumentSnapshot`. + */ + get ref(): DocumentReference; + /** + * Signals whether or not the document at the snapshot's location exists. + * + * @returns true if the document exists. + */ + exists(): this is QueryDocumentSnapshot; + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * @returns An `Object` containing all fields in the document or `undefined` + * if the document doesn't exist. + */ + data(): AppModelType | undefined; + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + get(fieldPath: string | FieldPath): any; +} +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ +export declare class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * @override + * @returns An `Object` containing all fields in the document. + */ + data(): AppModelType; +} +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ +export declare class QuerySnapshot { + readonly _docs: Array>; + /** + * The query on which you called {@link getDocs} in order to get this + * `QuerySnapshot`. + */ + readonly query: Query; + /** @hideconstructor */ + constructor(_query: Query, _docs: Array>); + /** An array of all the documents in the `QuerySnapshot`. */ + get docs(): Array>; + /** The number of documents in the `QuerySnapshot`. */ + get size(): number; + /** True if there are no documents in the `QuerySnapshot`. */ + get empty(): boolean; + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ + forEach(callback: (result: QueryDocumentSnapshot) => void, thisArg?: unknown): void; +} +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ +export declare function snapshotEqual(left: DocumentSnapshot | QuerySnapshot, right: DocumentSnapshot | QuerySnapshot): boolean; +/** + * Helper that calls `fromDotSeparatedString()` but wraps any error thrown. + */ +export declare function fieldPathFromArgument(methodName: string, arg: string | FieldPath | Compat): InternalFieldPath; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/timestamp.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/timestamp.d.ts new file mode 100644 index 0000000..6d14f82 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/timestamp.d.ts @@ -0,0 +1,134 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Property } from '../util/json_validation'; +/** + * A `Timestamp` represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. + * + * It is encoded using the Proleptic Gregorian Calendar which extends the + * Gregorian calendar backwards to year one. It is encoded assuming all minutes + * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59.999999999Z. + * + * For examples and further specifications, refer to the + * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. + */ +export declare class Timestamp { + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + readonly seconds: number; + /** + * The fractions of a second at nanosecond resolution.* + */ + readonly nanoseconds: number; + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns a new timestamp representing the current date. + */ + static now(): Timestamp; + /** + * Creates a new timestamp from the given date. + * + * @param date - The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the given + * date. + */ + static fromDate(date: Date): Timestamp; + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds - Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the given + * number of milliseconds. + */ + static fromMillis(milliseconds: number): Timestamp; + /** + * Creates a new timestamp. + * + * @param seconds - The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds - The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ + constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + seconds: number, + /** + * The fractions of a second at nanosecond resolution.* + */ + nanoseconds: number); + /** + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ + toDate(): Date; + /** + * Converts a `Timestamp` to a numeric timestamp (in milliseconds since + * epoch). This operation causes a loss of precision. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ + toMillis(): number; + _compareTo(other: Timestamp): number; + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other - The `Timestamp` to compare against. + * @returns true if this `Timestamp` is equal to the provided one. + */ + isEqual(other: Timestamp): boolean; + /** Returns a textual representation of this `Timestamp`. */ + toString(): string; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + seconds: Property<"number">; + nanoseconds: Property<"number">; + }; + /** + * Returns a JSON-serializable representation of this `Timestamp`. + */ + toJSON(): { + seconds: number; + nanoseconds: number; + type: string; + }; + /** + * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}. + */ + static fromJSON(json: object): Timestamp; + /** + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. + */ + valueOf(): string; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/transaction.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/transaction.d.ts new file mode 100644 index 0000000..eee3374 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/transaction.d.ts @@ -0,0 +1,122 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Transaction as InternalTransaction } from '../core/transaction'; +import { Firestore } from './database'; +import { FieldPath } from './field_path'; +import { DocumentData, DocumentReference, PartialWithFieldValue, SetOptions, UpdateData, WithFieldValue } from './reference'; +import { DocumentSnapshot } from './snapshot'; +import { TransactionOptions } from './transaction_options'; +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ +export declare class Transaction { + protected readonly _firestore: Firestore; + private readonly _transaction; + private readonly _dataReader; + /** @hideconstructor */ + constructor(_firestore: Firestore, _transaction: InternalTransaction); + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ + get(documentRef: DocumentReference): Promise>; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: WithFieldValue): this; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * If you provide `merge` or `mergeFields`, the provided data can be merged + * into an existing document. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: PartialWithFieldValue, options: SetOptions): this; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * @param documentRef - A reference to the document to be updated. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, data: UpdateData): this; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * @param documentRef - A reference to the document to be updated. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key/value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): this; + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + delete(documentRef: DocumentReference): this; +} +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ +export declare function runTransaction(firestore: Firestore, updateFunction: (transaction: Transaction) => Promise, options?: TransactionOptions): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/transaction_options.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/transaction_options.d.ts new file mode 100644 index 0000000..113fb49 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/transaction_options.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options to customize transaction behavior. + */ +export declare interface TransactionOptions { + /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */ + readonly maxAttempts?: number; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/types.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/types.d.ts new file mode 100644 index 0000000..5c56c2d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/types.d.ts @@ -0,0 +1,61 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { UpdateData } from './reference'; +/** + * These types primarily exist to support the `UpdateData`, + * `WithFieldValue`, and `PartialWithFieldValue` types and are not consumed + * directly by the end developer. + */ +/** Primitive types. */ +export type Primitive = string | number | boolean | undefined | null; +/** + * For each field (e.g. 'bar'), find all nested keys (e.g. {'bar.baz': T1, + * 'bar.qux': T2}). Intersect them together to make a single map containing + * all possible keys that are all marked as optional + */ +export type NestedUpdateFields> = UnionToIntersection<{ + [K in keyof T & string]: ChildUpdateFields; +}[keyof T & string]>; +/** + * Helper for calculating the nested fields for a given type T1. This is needed + * to distribute union types such as `undefined | {...}` (happens for optional + * props) or `{a: A} | {b: B}`. + * + * In this use case, `V` is used to distribute the union types of `T[K]` on + * `Record`, since `T[K]` is evaluated as an expression and not distributed. + * + * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types + */ +export type ChildUpdateFields = V extends Record ? AddPrefixToKeys> : never; +/** + * Returns a new map where every key is prefixed with the outer key appended + * to a dot. + */ +export type AddPrefixToKeys> = { + [K in keyof T & string as `${Prefix}.${K}`]+?: string extends K ? any : T[K]; +}; +/** + * Given a union type `U = T1 | T2 | ...`, returns an intersected type + * `(T1 & T2 & ...)`. + * + * Uses distributive conditional types and inference from conditional types. + * This works because multiple candidates for the same type variable in + * contra-variant positions causes an intersection type to be inferred. + * https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-inference-in-conditional-types + * https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type + */ +export type UnionToIntersection = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/user_data_reader.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/user_data_reader.d.ts new file mode 100644 index 0000000..821bb46 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/user_data_reader.d.ts @@ -0,0 +1,224 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentData, FieldPath as PublicFieldPath, SetOptions } from '@firebase/firestore-types'; +import { Compat } from '@firebase/util'; +import { ParseContext } from '../api/parse_context'; +import { DatabaseId } from '../core/database_info'; +import { DocumentKey } from '../model/document_key'; +import { FieldMask } from '../model/field_mask'; +import { FieldTransform, Mutation, Precondition } from '../model/mutation'; +import { ObjectValue } from '../model/object_value'; +import { FieldPath as InternalFieldPath } from '../model/path'; +import { MapValue as ProtoMapValue, Value as ProtoValue } from '../protos/firestore_proto_api'; +import { JsonProtoSerializer } from '../remote/serializer'; +import { FirestoreError } from '../util/error'; +import { Dict } from '../util/obj'; +import { Firestore } from './database'; +import { FieldValue } from './field_value'; +import { PartialWithFieldValue, WithFieldValue } from './reference'; +import { VectorValue } from './vector_value'; +/** + * An untyped Firestore Data Converter interface that is shared between the + * lite, firestore-exp and classic SDK. + */ +export interface UntypedFirestoreDataConverter { + toFirestore(modelObject: WithFieldValue): WithFieldValue; + toFirestore(modelObject: PartialWithFieldValue, options: SetOptions): PartialWithFieldValue; + fromFirestore(snapshot: unknown, options?: unknown): AppModelType; +} +/** The result of parsing document data (e.g. for a setData call). */ +export declare class ParsedSetData { + readonly data: ObjectValue; + readonly fieldMask: FieldMask | null; + readonly fieldTransforms: FieldTransform[]; + constructor(data: ObjectValue, fieldMask: FieldMask | null, fieldTransforms: FieldTransform[]); + toMutation(key: DocumentKey, precondition: Precondition): Mutation; +} +/** The result of parsing "update" data (i.e. for an updateData call). */ +export declare class ParsedUpdateData { + readonly data: ObjectValue; + readonly fieldMask: FieldMask; + readonly fieldTransforms: FieldTransform[]; + constructor(data: ObjectValue, fieldMask: FieldMask, fieldTransforms: FieldTransform[]); + toMutation(key: DocumentKey, precondition: Precondition): Mutation; +} +export declare const enum UserDataSource { + Set = 0, + Update = 1, + MergeSet = 2, + /** + * Indicates the source is a where clause, cursor bound, arrayUnion() + * element, etc. Of note, isWrite(source) will return false. + */ + Argument = 3, + /** + * Indicates that the source is an Argument that may directly contain nested + * arrays (e.g. the operand of an `in` query). + */ + ArrayArgument = 4 +} +/** Contains the settings that are mutated as we parse user data. */ +interface ContextSettings { + /** Indicates what kind of API method this data came from. */ + readonly dataSource: UserDataSource; + /** The name of the method the user called to create the ParseContext. */ + readonly methodName: string; + /** The document the user is attempting to modify, if that applies. */ + readonly targetDoc?: DocumentKey; + /** + * A path within the object being parsed. This could be an empty path (in + * which case the context represents the root of the data being parsed), or a + * nonempty path (indicating the context represents a nested location within + * the data). + */ + readonly path?: InternalFieldPath; + /** + * Whether or not this context corresponds to an element of an array. + * If not set, elements are treated as if they were outside of arrays. + */ + readonly arrayElement?: boolean; + /** + * Whether or not a converter was specified in this context. If true, error + * messages will reference the converter when invalid data is provided. + */ + readonly hasConverter?: boolean; +} +/** A "context" object passed around while parsing user data. */ +declare class ParseContextImpl implements ParseContext { + readonly settings: ContextSettings; + readonly databaseId: DatabaseId; + readonly serializer: JsonProtoSerializer; + readonly ignoreUndefinedProperties: boolean; + readonly fieldTransforms: FieldTransform[]; + readonly fieldMask: InternalFieldPath[]; + /** + * Initializes a ParseContext with the given source and path. + * + * @param settings - The settings for the parser. + * @param databaseId - The database ID of the Firestore instance. + * @param serializer - The serializer to use to generate the Value proto. + * @param ignoreUndefinedProperties - Whether to ignore undefined properties + * rather than throw. + * @param fieldTransforms - A mutable list of field transforms encountered + * while parsing the data. + * @param fieldMask - A mutable list of field paths encountered while parsing + * the data. + * + * TODO(b/34871131): We don't support array paths right now, so path can be + * null to indicate the context represents any location within an array (in + * which case certain features will not work and errors will be somewhat + * compromised). + */ + constructor(settings: ContextSettings, databaseId: DatabaseId, serializer: JsonProtoSerializer, ignoreUndefinedProperties: boolean, fieldTransforms?: FieldTransform[], fieldMask?: InternalFieldPath[]); + get path(): InternalFieldPath | undefined; + get dataSource(): UserDataSource; + /** Returns a new context with the specified settings overwritten. */ + contextWith(configuration: Partial): ParseContextImpl; + childContextForField(field: string): ParseContextImpl; + childContextForFieldPath(field: InternalFieldPath): ParseContextImpl; + childContextForArray(index: number): ParseContextImpl; + createError(reason: string): FirestoreError; + /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ + contains(fieldPath: InternalFieldPath): boolean; + private validatePath; + private validatePathSegment; +} +/** + * Helper for parsing raw user input (provided via the API) into internal model + * classes. + */ +export declare class UserDataReader { + private readonly databaseId; + private readonly ignoreUndefinedProperties; + private readonly serializer; + constructor(databaseId: DatabaseId, ignoreUndefinedProperties: boolean, serializer?: JsonProtoSerializer); + /** Creates a new top-level parse context. */ + createContext(dataSource: UserDataSource, methodName: string, targetDoc?: DocumentKey, hasConverter?: boolean): ParseContextImpl; +} +export declare function newUserDataReader(firestore: Firestore): UserDataReader; +/** Parse document data from a set() call. */ +export declare function parseSetData(userDataReader: UserDataReader, methodName: string, targetDoc: DocumentKey, input: unknown, hasConverter: boolean, options?: SetOptions): ParsedSetData; +export declare class DeleteFieldValueImpl extends FieldValue { + _toFieldTransform(context: ParseContextImpl): null; + isEqual(other: FieldValue): boolean; +} +export declare class ServerTimestampFieldValueImpl extends FieldValue { + _toFieldTransform(context: ParseContextImpl): FieldTransform; + isEqual(other: FieldValue): boolean; +} +export declare class ArrayUnionFieldValueImpl extends FieldValue { + private readonly _elements; + constructor(methodName: string, _elements: unknown[]); + _toFieldTransform(context: ParseContextImpl): FieldTransform; + isEqual(other: FieldValue): boolean; +} +export declare class ArrayRemoveFieldValueImpl extends FieldValue { + private readonly _elements; + constructor(methodName: string, _elements: unknown[]); + _toFieldTransform(context: ParseContextImpl): FieldTransform; + isEqual(other: FieldValue): boolean; +} +export declare class NumericIncrementFieldValueImpl extends FieldValue { + private readonly _operand; + constructor(methodName: string, _operand: number); + _toFieldTransform(context: ParseContextImpl): FieldTransform; + isEqual(other: FieldValue): boolean; +} +/** Parse update data from an update() call. */ +export declare function parseUpdateData(userDataReader: UserDataReader, methodName: string, targetDoc: DocumentKey, input: unknown): ParsedUpdateData; +/** Parse update data from a list of field/value arguments. */ +export declare function parseUpdateVarargs(userDataReader: UserDataReader, methodName: string, targetDoc: DocumentKey, field: string | PublicFieldPath | Compat, value: unknown, moreFieldsAndValues: unknown[]): ParsedUpdateData; +/** + * Parse a "query value" (e.g. value in a where filter or a value in a cursor + * bound). + * + * @param allowArrays - Whether the query value is an array that may directly + * contain additional arrays (e.g. the operand of an `in` query). + */ +export declare function parseQueryValue(userDataReader: UserDataReader, methodName: string, input: unknown, allowArrays?: boolean): ProtoValue; +/** + * Parses user data to Protobuf Values. + * + * @param input - Data to be parsed. + * @param context - A context object representing the current path being parsed, + * the source of the data being parsed, etc. + * @returns The parsed value, or null if the value was a FieldValue sentinel + * that should not be included in the resulting parsed data. + */ +export declare function parseData(input: unknown, context: ParseContextImpl): ProtoValue | null; +export declare function parseObject(obj: Dict, context: ParseContextImpl): { + mapValue: ProtoMapValue; +}; +/** + * Creates a new VectorValue proto value (using the internal format). + */ +export declare function parseVectorValue(value: VectorValue, context: ParseContextImpl): ProtoValue; +/** + * Helper that calls fromDotSeparatedString() but wraps any error thrown. + */ +export declare function fieldPathFromArgument(methodName: string, path: string | PublicFieldPath | Compat, targetDoc?: DocumentKey): InternalFieldPath; +/** + * Wraps fromDotSeparatedString with an error message about the method that + * was thrown. + * @param methodName - The publicly visible method name + * @param path - The dot-separated string form of a field path which will be + * split on dots. + * @param targetDoc - The document against which the field path will be + * evaluated. + */ +export declare function fieldPathFromDotSeparatedString(methodName: string, path: string, targetDoc?: DocumentKey): InternalFieldPath; +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/user_data_writer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/user_data_writer.d.ts new file mode 100644 index 0000000..391593a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/user_data_writer.d.ts @@ -0,0 +1,48 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentData } from '@firebase/firestore-types'; +import { DatabaseId } from '../core/database_info'; +import { DocumentKey } from '../model/document_key'; +import { ApiClientObjectMap, MapValue as ProtoMapValue, Value, Value as ProtoValue } from '../protos/firestore_proto_api'; +import { ByteString } from '../util/byte_string'; +import { VectorValue } from './vector_value'; +export type ServerTimestampBehavior = 'estimate' | 'previous' | 'none'; +/** + * Converts Firestore's internal types to the JavaScript types that we expose + * to the user. + * + * @internal + */ +export declare abstract class AbstractUserDataWriter { + convertValue(value: ProtoValue, serverTimestampBehavior?: ServerTimestampBehavior): unknown; + private convertObject; + /** + * @internal + */ + convertObjectMap(fields: ApiClientObjectMap | undefined, serverTimestampBehavior?: ServerTimestampBehavior): DocumentData; + /** + * @internal + */ + convertVectorValue(mapValue: ProtoMapValue): VectorValue; + private convertGeoPoint; + private convertArray; + private convertServerTimestamp; + private convertTimestamp; + protected convertDocumentKey(name: string, expectedDatabaseId: DatabaseId): DocumentKey; + protected abstract convertReference(name: string): unknown; + protected abstract convertBytes(bytes: ByteString): unknown; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/vector_value.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/vector_value.d.ts new file mode 100644 index 0000000..b4808e0 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/vector_value.d.ts @@ -0,0 +1,58 @@ +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Property } from '../util/json_validation'; +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link vector}. + * + * @class VectorValue + */ +export declare class VectorValue { + private readonly _values; + /** + * @private + * @internal + */ + constructor(values: number[] | undefined); + /** + * Returns a copy of the raw number array form of the vector. + */ + toArray(): number[]; + /** + * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise. + */ + isEqual(other: VectorValue): boolean; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + vectorValues: Property<"object">; + }; + /** + * Returns a JSON-serializable representation of this `VectorValue` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}. + * + * @param json a JSON object represention of a `VectorValue` instance. + * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): VectorValue; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/write_batch.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/write_batch.d.ts new file mode 100644 index 0000000..4835feb --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/lite-api/write_batch.d.ts @@ -0,0 +1,125 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Compat } from '@firebase/util'; +import { Mutation } from '../model/mutation'; +import { Firestore } from './database'; +import { FieldPath } from './field_path'; +import { DocumentData, DocumentReference, PartialWithFieldValue, SetOptions, UpdateData, WithFieldValue } from './reference'; +/** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It + * provides methods for adding writes to the write batch. None of the writes + * will be committed (or visible locally) until {@link WriteBatch.commit} is + * called. + */ +export declare class WriteBatch { + private readonly _firestore; + private readonly _commitHandler; + private readonly _dataReader; + private _mutations; + private _committed; + /** @hideconstructor */ + constructor(_firestore: Firestore, _commitHandler: (m: Mutation[]) => Promise); + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: WithFieldValue): WriteBatch; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * If you provide `merge` or `mergeFields`, the provided data can be merged + * into an existing document. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: PartialWithFieldValue, options: SetOptions): WriteBatch; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * @param documentRef - A reference to the document to be updated. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, data: UpdateData): WriteBatch; + /** + * Updates fields in the document referred to by this {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be update by providing dot-separated field path strings + * or by providing `FieldPath` objects. + * + * @param documentRef - A reference to the document to be updated. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): WriteBatch; + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + delete(documentRef: DocumentReference): WriteBatch; + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `Promise` resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit (note that it won't + * resolve while you're offline). + */ + commit(): Promise; + private _verifyNotCommitted; +} +export declare function validateReference(documentRef: DocumentReference | Compat>, firestore: Firestore): DocumentReference; +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single WriteBatch + * is 500. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `WriteBatch` that can be used to atomically execute multiple + * writes. + */ +export declare function writeBatch(firestore: Firestore): WriteBatch; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/bundle_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/bundle_cache.d.ts new file mode 100644 index 0000000..2949e55 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/bundle_cache.d.ts @@ -0,0 +1,44 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BundleMetadata, NamedQuery } from '../core/bundle'; +import { NamedQuery as ProtoNamedQuery, BundleMetadata as ProtoBundleMetadata } from '../protos/firestore_bundle_proto'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** + * Provides interfaces to save and read Firestore bundles. + */ +export interface BundleCache { + /** + * Gets the saved `BundleMetadata` for a given `bundleId`, returns undefined + * if no bundle metadata is found under the given id. + */ + getBundleMetadata(transaction: PersistenceTransaction, bundleId: string): PersistencePromise; + /** + * Saves a `BundleMetadata` from a bundle into local storage, using its id as + * the persistent key. + */ + saveBundleMetadata(transaction: PersistenceTransaction, metadata: ProtoBundleMetadata): PersistencePromise; + /** + * Gets a saved `NamedQuery` for the given query name. Returns undefined if + * no queries are found under the given name. + */ + getNamedQuery(transaction: PersistenceTransaction, queryName: string): PersistencePromise; + /** + * Saves a `NamedQuery` from a bundle, using its name as the persistent key. + */ + saveNamedQuery(transaction: PersistenceTransaction, query: ProtoNamedQuery): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/document_overlay_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/document_overlay_cache.d.ts new file mode 100644 index 0000000..e1f1f2a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/document_overlay_cache.d.ts @@ -0,0 +1,76 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentKeySet, MutationMap, OverlayMap } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { Overlay } from '../model/overlay'; +import { ResourcePath } from '../model/path'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** + * Provides methods to read and write document overlays. + * + * An overlay is a saved mutation, that gives a local view of a document when + * applied to the remote version of the document. + * + * Each overlay stores the largest batch ID that is included in the overlay, + * which allows us to remove the overlay once all batches leading up to it have + * been acknowledged. + */ +export interface DocumentOverlayCache { + /** + * Gets the saved overlay mutation for the given document key. + * Returns null if there is no overlay for that key. + */ + getOverlay(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; + /** + * Gets the saved overlay mutation for the given document keys. Skips keys for + * which there are no overlays. + */ + getOverlays(transaction: PersistenceTransaction, keys: DocumentKey[]): PersistencePromise; + /** + * Saves the given document mutation map to persistence as overlays. + * All overlays will have their largest batch id set to `largestBatchId`. + */ + saveOverlays(transaction: PersistenceTransaction, largestBatchId: number, overlays: MutationMap): PersistencePromise; + /** Removes overlays for the given document keys and batch ID. */ + removeOverlaysForBatchId(transaction: PersistenceTransaction, documentKeys: DocumentKeySet, batchId: number): PersistencePromise; + /** + * Returns all saved overlays for the given collection. + * + * @param transaction - The persistence transaction to use for this operation. + * @param collection - The collection path to get the overlays for. + * @param sinceBatchId - The minimum batch ID to filter by (exclusive). + * Only overlays that contain a change past `sinceBatchId` are returned. + * @returns Mapping of each document key in the collection to its overlay. + */ + getOverlaysForCollection(transaction: PersistenceTransaction, collection: ResourcePath, sinceBatchId: number): PersistencePromise; + /** + * Returns `count` overlays with a batch ID higher than `sinceBatchId` for the + * provided collection group, processed by ascending batch ID. The method + * always returns all overlays for a batch even if the last batch contains + * more documents than the remaining limit. + * + * @param transaction - The persistence transaction used for this operation. + * @param collectionGroup - The collection group to get the overlays for. + * @param sinceBatchId - The minimum batch ID to filter by (exclusive). + * Only overlays that contain a change past `sinceBatchId` are returned. + * @param count - The number of overlays to return. Can be exceeded if the last + * batch contains more entries. + * @return Mapping of each document key in the collection group to its overlay. + */ + getOverlaysForCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, sinceBatchId: number, count: number): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/encoded_resource_path.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/encoded_resource_path.d.ts new file mode 100644 index 0000000..73353db --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/encoded_resource_path.d.ts @@ -0,0 +1,73 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ResourcePath } from '../model/path'; +/** + * Helpers for dealing with resource paths stored in IndexedDB. + * + * Resource paths in their canonical string form do not sort as the server + * sorts them. Specifically the server splits paths into segments first and then + * sorts, putting end-of-segment before any character. In a UTF-8 string + * encoding the slash ('/') that denotes the end-of-segment naturally comes + * after other characters so the intent here is to encode the path delimiters in + * such a way that the resulting strings sort naturally. + * + * Resource paths are also used for prefix scans so it's important to + * distinguish whole segments from any longer segments of which they might be a + * prefix. For example, it's important to make it possible to scan documents in + * a collection "foo" without encountering documents in a collection "foobar". + * + * Separate from the concerns about resource path ordering and separation, + * On Android, SQLite imposes additional restrictions since it does not handle + * keys with embedded NUL bytes particularly well. Rather than change the + * implementation we keep the encoding identical to keep the ports similar. + * + * Taken together this means resource paths when encoded for storage in + * IndexedDB have the following characteristics: + * + * * Segment separators ("/") sort before everything else. + * * All paths have a trailing separator. + * * NUL bytes do not exist in the output, since IndexedDB doesn't treat them + * well. + * + * Therefore resource paths are encoded into string form using the following + * rules: + * + * * '\x01' is used as an escape character. + * * Path separators are encoded as "\x01\x01" + * * NUL bytes are encoded as "\x01\x10" + * * '\x01' is encoded as "\x01\x11" + * + * This encoding leaves some room between path separators and the NUL byte + * just in case we decide to support integer document ids after all. + * + * Note that characters treated specially by the backend ('.', '/', and '~') + * are not treated specially here. This class assumes that any unescaping of + * resource path strings into actual ResourcePath objects will handle these + * characters there. + */ +export type EncodedResourcePath = string; +/** + * Encodes a resource path into a IndexedDb-compatible string form. + */ +export declare function encodeResourcePath(path: ResourcePath): EncodedResourcePath; +/** + * Decodes the given IndexedDb-compatible string form of a resource path into + * a ResourcePath instance. Note that this method is not suitable for use with + * decoding resource names from the server; those are One Platform format + * strings. + */ +export declare function decodeResourcePath(path: EncodedResourcePath): ResourcePath; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/globals_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/globals_cache.d.ts new file mode 100644 index 0000000..a2a7ff6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/globals_cache.d.ts @@ -0,0 +1,39 @@ +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ByteString } from '../util/byte_string'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** + * General purpose cache for global values. + * + * Global state that cuts across components should be saved here. Following are contained herein: + * + * `sessionToken` tracks server interaction across Listen and Write streams. This facilitates cache + * synchronization and invalidation. + */ +export interface GlobalsCache { + /** + * Gets session token. + */ + getSessionToken(transaction: PersistenceTransaction): PersistencePromise; + /** + * Sets session token. + * + * @param sessionToken - The new session token. + */ + setSessionToken(transaction: PersistenceTransaction, sessionToken: ByteString): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/index_backfiller.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/index_backfiller.d.ts new file mode 100644 index 0000000..2abeb5f --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/index_backfiller.d.ts @@ -0,0 +1,44 @@ +import { AsyncQueue } from '../util/async_queue'; +import { LocalStore } from './local_store'; +import { Persistence, Scheduler } from './persistence'; +/** This class is responsible for the scheduling of Index Backfiller. */ +export declare class IndexBackfillerScheduler implements Scheduler { + private readonly asyncQueue; + private readonly backfiller; + private task; + constructor(asyncQueue: AsyncQueue, backfiller: IndexBackfiller); + start(): void; + stop(): void; + get started(): boolean; + private schedule; +} +/** Implements the steps for backfilling indexes. */ +export declare class IndexBackfiller { + /** + * LocalStore provides access to IndexManager and LocalDocumentView. + * These properties will update when the user changes. Consequently, + * making a local copy of IndexManager and LocalDocumentView will require + * updates over time. The simpler solution is to rely on LocalStore to have + * an up-to-date references to IndexManager and LocalDocumentStore. + */ + private readonly localStore; + private readonly persistence; + constructor( + /** + * LocalStore provides access to IndexManager and LocalDocumentView. + * These properties will update when the user changes. Consequently, + * making a local copy of IndexManager and LocalDocumentView will require + * updates over time. The simpler solution is to rely on LocalStore to have + * an up-to-date references to IndexManager and LocalDocumentStore. + */ + localStore: LocalStore, persistence: Persistence); + backfill(maxDocumentsToProcess?: number): Promise; + /** Writes index entries until the cap is reached. Returns the number of documents processed. */ + private writeIndexEntries; + /** + * Writes entries for the provided collection group. Returns the number of documents processed. + */ + private writeEntriesForCollectionGroup; + /** Returns the next offset based on the provided documents. */ + private getNewOffset; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/index_manager.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/index_manager.d.ts new file mode 100644 index 0000000..6a02ffc --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/index_manager.d.ts @@ -0,0 +1,124 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Target } from '../core/target'; +import { DocumentMap } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { FieldIndex, IndexOffset } from '../model/field_index'; +import { ResourcePath } from '../model/path'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** Represents the index state as it relates to a particular target. */ +export declare const enum IndexType { + /** Indicates that no index could be found for serving the target. */ + NONE = 0, + /** + * Indicates that only a "partial index" could be found for serving the + * target. A partial index is one which does not have a segment for every + * filter/orderBy in the target. + */ + PARTIAL = 1, + /** + * Indicates that a "full index" could be found for serving the target. A full + * index is one which has a segment for every filter/orderBy in the target. + */ + FULL = 2 +} +export declare function displayNameForIndexType(indexType: IndexType): string; +/** + * Represents a set of indexes that are used to execute queries efficiently. + * + * Currently the only index is a [collection id] => [parent path] index, used + * to execute Collection Group queries. + */ +export interface IndexManager { + /** + * Creates an index entry mapping the collectionId (last segment of the path) + * to the parent path (either the containing document location or the empty + * path for root-level collections). Index entries can be retrieved via + * getCollectionParents(). + * + * NOTE: Currently we don't remove index entries. If this ends up being an + * issue we can devise some sort of GC strategy. + */ + addToCollectionParentIndex(transaction: PersistenceTransaction, collectionPath: ResourcePath): PersistencePromise; + /** + * Retrieves all parent locations containing the given collectionId, as a + * list of paths (each path being either a document location or the empty + * path for a root-level collection). + */ + getCollectionParents(transaction: PersistenceTransaction, collectionId: string): PersistencePromise; + /** + * Adds a field path index. + * + * Values for this index are persisted via the index backfill, which runs + * asynchronously in the background. Once the first values are written, + * an index can be used to serve partial results for any matching queries. + * Any unindexed portion of the database will continue to be served via + * collection scons. + */ + addFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + /** Removes the given field index and deletes all index values. */ + deleteFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + /** Removes all field indexes and deletes all index values. */ + deleteAllFieldIndexes(transaction: PersistenceTransaction): PersistencePromise; + /** Creates a full matched field index which serves the given target. */ + createTargetIndexes(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Returns a list of field indexes that correspond to the specified collection + * group. + * + * @param collectionGroup The collection group to get matching field indexes + * for. + * @return A collection of field indexes for the specified collection group. + */ + getFieldIndexes(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise; + /** Returns all configured field indexes. */ + getFieldIndexes(transaction: PersistenceTransaction): PersistencePromise; + /** + * Returns the type of index (if any) that can be used to serve the given + * target. + */ + getIndexType(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Returns the documents that match the given target based on the provided + * index or `null` if the target does not have a matching index. + */ + getDocumentsMatchingTarget(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Returns the next collection group to update. Returns `null` if no group + * exists. + */ + getNextCollectionGroupToUpdate(transaction: PersistenceTransaction): PersistencePromise; + /** + * Sets the collection group's latest read time. + * + * This method updates the index offset for all field indices for the + * collection group and increments their sequence number. Subsequent calls to + * `getNextCollectionGroupToUpdate()` will return a different collection group + * (unless only one collection group is configured). + */ + updateCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset): PersistencePromise; + /** Updates the index entries for the provided documents. */ + updateIndexEntries(transaction: PersistenceTransaction, documents: DocumentMap): PersistencePromise; + /** + * Iterates over all field indexes that are used to serve the given target, + * and returns the minimum offset of them all. + */ + getMinOffset(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** Returns the minimum offset for the given collection group. */ + getMinOffsetFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_bundle_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_bundle_cache.d.ts new file mode 100644 index 0000000..60f49fc --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_bundle_cache.d.ts @@ -0,0 +1,27 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BundleMetadata, NamedQuery } from '../core/bundle'; +import { BundleMetadata as ProtoBundleMetadata, NamedQuery as ProtoNamedQuery } from '../protos/firestore_bundle_proto'; +import { BundleCache } from './bundle_cache'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +export declare class IndexedDbBundleCache implements BundleCache { + getBundleMetadata(transaction: PersistenceTransaction, bundleId: string): PersistencePromise; + saveBundleMetadata(transaction: PersistenceTransaction, bundleMetadata: ProtoBundleMetadata): PersistencePromise; + getNamedQuery(transaction: PersistenceTransaction, queryName: string): PersistencePromise; + saveNamedQuery(transaction: PersistenceTransaction, query: ProtoNamedQuery): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_document_overlay_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_document_overlay_cache.d.ts new file mode 100644 index 0000000..eda11b2 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_document_overlay_cache.d.ts @@ -0,0 +1,45 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { DocumentKeySet, MutationMap, OverlayMap } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { Overlay } from '../model/overlay'; +import { ResourcePath } from '../model/path'; +import { DocumentOverlayCache } from './document_overlay_cache'; +import { LocalSerializer } from './local_serializer'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** + * Implementation of DocumentOverlayCache using IndexedDb. + */ +export declare class IndexedDbDocumentOverlayCache implements DocumentOverlayCache { + private readonly serializer; + private readonly userId; + /** + * @param serializer - The document serializer. + * @param userId - The userId for which we are accessing overlays. + */ + constructor(serializer: LocalSerializer, userId: string); + static forUser(serializer: LocalSerializer, user: User): IndexedDbDocumentOverlayCache; + getOverlay(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; + getOverlays(transaction: PersistenceTransaction, keys: DocumentKey[]): PersistencePromise; + saveOverlays(transaction: PersistenceTransaction, largestBatchId: number, overlays: MutationMap): PersistencePromise; + removeOverlaysForBatchId(transaction: PersistenceTransaction, documentKeys: DocumentKeySet, batchId: number): PersistencePromise; + getOverlaysForCollection(transaction: PersistenceTransaction, collection: ResourcePath, sinceBatchId: number): PersistencePromise; + getOverlaysForCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, sinceBatchId: number, count: number): PersistencePromise; + private saveOverlay; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_globals_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_globals_cache.d.ts new file mode 100644 index 0000000..2f550f5 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_globals_cache.d.ts @@ -0,0 +1,25 @@ +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ByteString } from '../util/byte_string'; +import { GlobalsCache } from './globals_cache'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +export declare class IndexedDbGlobalsCache implements GlobalsCache { + private globalsStore; + getSessionToken(txn: PersistenceTransaction): PersistencePromise; + setSessionToken(txn: PersistenceTransaction, sessionToken: ByteString): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_index_manager.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_index_manager.d.ts new file mode 100644 index 0000000..8078d1c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_index_manager.d.ts @@ -0,0 +1,136 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { DatabaseId } from '../core/database_info'; +import { Target } from '../core/target'; +import { IndexEntry } from '../index/index_entry'; +import { DocumentMap } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { FieldIndex, IndexOffset } from '../model/field_index'; +import { ResourcePath } from '../model/path'; +import { IndexManager, IndexType } from './index_manager'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** + * A persisted implementation of IndexManager. + * + * PORTING NOTE: Unlike iOS and Android, the Web SDK does not memoize index + * data as it supports multi-tab access. + */ +export declare class IndexedDbIndexManager implements IndexManager { + private readonly databaseId; + /** + * An in-memory copy of the index entries we've already written since the SDK + * launched. Used to avoid re-writing the same entry repeatedly. + * + * This is *NOT* a complete cache of what's in persistence and so can never be + * used to satisfy reads. + */ + private collectionParentsCache; + private readonly uid; + /** + * Maps from a target to its equivalent list of sub-targets. Each sub-target + * contains only one term from the target's disjunctive normal form (DNF). + */ + private targetToDnfSubTargets; + constructor(user: User, databaseId: DatabaseId); + /** + * Adds a new entry to the collection parent index. + * + * Repeated calls for the same collectionPath should be avoided within a + * transaction as IndexedDbIndexManager only caches writes once a transaction + * has been committed. + */ + addToCollectionParentIndex(transaction: PersistenceTransaction, collectionPath: ResourcePath): PersistencePromise; + getCollectionParents(transaction: PersistenceTransaction, collectionId: string): PersistencePromise; + addFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + deleteFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + deleteAllFieldIndexes(transaction: PersistenceTransaction): PersistencePromise; + createTargetIndexes(transaction: PersistenceTransaction, target: Target): PersistencePromise; + getDocumentsMatchingTarget(transaction: PersistenceTransaction, target: Target): PersistencePromise; + private getSubTargets; + /** + * Constructs a key range query on `DbIndexEntryStore` that unions all + * bounds. + */ + private generateIndexRanges; + /** Generates the lower bound for `arrayValue` and `directionalValue`. */ + private generateLowerBound; + /** Generates the upper bound for `arrayValue` and `directionalValue`. */ + private generateUpperBound; + private getFieldIndex; + getIndexType(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Returns the byte encoded form of the directional values in the field index. + * Returns `null` if the document does not have all fields specified in the + * index. + */ + private encodeDirectionalElements; + /** Encodes a single value to the ascending index format. */ + private encodeSingleElement; + /** + * Returns an encoded form of the document key that sorts based on the key + * ordering of the field index. + */ + private encodeDirectionalKey; + /** + * Encodes the given field values according to the specification in `target`. + * For IN queries, a list of possible values is returned. + */ + private encodeValues; + /** + * Encodes the given bounds according to the specification in `target`. For IN + * queries, a list of possible values is returned. + */ + private encodeBound; + /** Returns the byte representation for the provided encoders. */ + private getEncodedBytes; + /** + * Creates a separate encoder for each element of an array. + * + * The method appends each value to all existing encoders (e.g. filter("a", + * "==", "a1").filter("b", "in", ["b1", "b2"]) becomes ["a1,b1", "a1,b2"]). A + * list of new encoders is returned. + */ + private expandIndexValues; + private isInFilter; + getFieldIndexes(transaction: PersistenceTransaction, collectionGroup?: string): PersistencePromise; + getNextCollectionGroupToUpdate(transaction: PersistenceTransaction): PersistencePromise; + updateCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset): PersistencePromise; + updateIndexEntries(transaction: PersistenceTransaction, documents: DocumentMap): PersistencePromise; + private addIndexEntry; + private deleteIndexEntry; + private getExistingIndexEntries; + /** Creates the index entries for the given document. */ + private computeIndexEntries; + /** + * Updates the index entries for the provided document by deleting entries + * that are no longer referenced in `newEntries` and adding all newly added + * entries. + */ + private updateEntries; + private getNextSequenceNumber; + /** + * Returns a new set of IDB ranges that splits the existing range and excludes + * any values that match the `notInValue` from these ranges. As an example, + * '[foo > 2 && foo != 3]` becomes `[foo > 2 && < 3, foo > 3]`. + */ + private createRange; + isRangeMatchable(lowerBound: IndexEntry, upperBound: IndexEntry): boolean; + getMinOffsetFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise; + getMinOffset(transaction: PersistenceTransaction, target: Target): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_lru_delegate.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_lru_delegate.d.ts new file mode 100644 index 0000000..fea8087 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_lru_delegate.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { LruDelegate, LruGarbageCollector } from './lru_garbage_collector'; +import { ReferenceDelegate } from './persistence'; +/** Provides LRU functionality for IndexedDB persistence. */ +export interface IndexedDbLruDelegate extends ReferenceDelegate, LruDelegate { + readonly garbageCollector: LruGarbageCollector; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_lru_delegate_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_lru_delegate_impl.d.ts new file mode 100644 index 0000000..56e5e6b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_lru_delegate_impl.d.ts @@ -0,0 +1,56 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ListenSequenceNumber, TargetId } from '../core/types'; +import { DocumentKey } from '../model/document_key'; +import { IndexedDbLruDelegate } from './indexeddb_lru_delegate'; +import { ActiveTargets, LruGarbageCollector, LruParams } from './lru_garbage_collector'; +import { Persistence } from './persistence'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +import { TargetData } from './target_data'; +/** Provides LRU functionality for IndexedDB persistence. */ +export declare class IndexedDbLruDelegateImpl implements IndexedDbLruDelegate { + private readonly db; + readonly garbageCollector: LruGarbageCollector; + constructor(db: Persistence, params: LruParams); + getSequenceNumberCount(txn: PersistenceTransaction): PersistencePromise; + private orphanedDocumentCount; + forEachTarget(txn: PersistenceTransaction, f: (q: TargetData) => void): PersistencePromise; + forEachOrphanedDocumentSequenceNumber(txn: PersistenceTransaction, f: (sequenceNumber: ListenSequenceNumber) => void): PersistencePromise; + addReference(txn: PersistenceTransaction, targetId: TargetId, key: DocumentKey): PersistencePromise; + removeReference(txn: PersistenceTransaction, targetId: TargetId, key: DocumentKey): PersistencePromise; + removeTargets(txn: PersistenceTransaction, upperBound: ListenSequenceNumber, activeTargetIds: ActiveTargets): PersistencePromise; + markPotentiallyOrphaned(txn: PersistenceTransaction, key: DocumentKey): PersistencePromise; + /** + * Returns true if anything would prevent this document from being garbage + * collected, given that the document in question is not present in any + * targets and has a sequence number less than or equal to the upper bound for + * the collection run. + */ + private isPinned; + removeOrphanedDocuments(txn: PersistenceTransaction, upperBound: ListenSequenceNumber): PersistencePromise; + removeTarget(txn: PersistenceTransaction, targetData: TargetData): PersistencePromise; + updateLimboDocument(txn: PersistenceTransaction, key: DocumentKey): PersistencePromise; + /** + * Call provided function for each document in the cache that is 'orphaned'. Orphaned + * means not a part of any target, so the only entry in the target-document index for + * that document will be the sentinel row (targetId 0), which will also have the sequence + * number for the last time the document was accessed. + */ + private forEachOrphanedDocument; + getCacheSize(txn: PersistenceTransaction): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_mutation_batch_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_mutation_batch_impl.d.ts new file mode 100644 index 0000000..b4f0ac4 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_mutation_batch_impl.d.ts @@ -0,0 +1,35 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentKey } from '../model/document_key'; +import { DbRemoteDocument } from './indexeddb_schema'; +import { DbRemoteDocument as DbRemoteDocumentLegacy } from './indexeddb_schema_legacy'; +import { PersistencePromise } from './persistence_promise'; +import { SimpleDbTransaction } from './simple_db'; +/** + * Delete a mutation batch and the associated document mutations. + * @returns A PersistencePromise of the document mutations that were removed. + */ +export declare function removeMutationBatch(txn: SimpleDbTransaction, userId: string, batch: { + batchId: number; + mutations: Array<{ + key: DocumentKey; + }>; +}): PersistencePromise; +/** + * Returns an approximate size for the given document. + */ +export declare function dbDocumentSize(doc: DbRemoteDocument | DbRemoteDocumentLegacy | null): number; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_mutation_queue.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_mutation_queue.d.ts new file mode 100644 index 0000000..ad62a1d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_mutation_queue.d.ts @@ -0,0 +1,99 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { Query } from '../core/query'; +import { BatchId } from '../core/types'; +import { Timestamp } from '../lite-api/timestamp'; +import { DocumentKeySet } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { Mutation } from '../model/mutation'; +import { MutationBatch } from '../model/mutation_batch'; +import { SortedMap } from '../util/sorted_map'; +import { IndexManager } from './index_manager'; +import { LocalSerializer } from './local_serializer'; +import { MutationQueue } from './mutation_queue'; +import { ReferenceDelegate } from './persistence'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** A mutation queue for a specific user, backed by IndexedDB. */ +export declare class IndexedDbMutationQueue implements MutationQueue { + /** + * The normalized userId (e.g. null UID => "" userId) used to store / + * retrieve mutations. + */ + private userId; + private readonly serializer; + private readonly indexManager; + private readonly referenceDelegate; + /** + * Caches the document keys for pending mutation batches. If the mutation + * has been removed from IndexedDb, the cached value may continue to + * be used to retrieve the batch's document keys. To remove a cached value + * locally, `removeCachedMutationKeys()` should be invoked either directly + * or through `removeMutationBatches()`. + * + * With multi-tab, when the primary client acknowledges or rejects a mutation, + * this cache is used by secondary clients to invalidate the local + * view of the documents that were previously affected by the mutation. + */ + private documentKeysByBatchId; + constructor( + /** + * The normalized userId (e.g. null UID => "" userId) used to store / + * retrieve mutations. + */ + userId: string, serializer: LocalSerializer, indexManager: IndexManager, referenceDelegate: ReferenceDelegate); + /** + * Creates a new mutation queue for the given user. + * @param user - The user for which to create a mutation queue. + * @param serializer - The serializer to use when persisting to IndexedDb. + */ + static forUser(user: User, serializer: LocalSerializer, indexManager: IndexManager, referenceDelegate: ReferenceDelegate): IndexedDbMutationQueue; + checkEmpty(transaction: PersistenceTransaction): PersistencePromise; + addMutationBatch(transaction: PersistenceTransaction, localWriteTime: Timestamp, baseMutations: Mutation[], mutations: Mutation[]): PersistencePromise; + lookupMutationBatch(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + /** + * Returns the document keys for the mutation batch with the given batchId. + * For primary clients, this method returns `null` after + * `removeMutationBatches()` has been called. Secondary clients return a + * cached result until `removeCachedMutationKeys()` is invoked. + */ + lookupMutationKeys(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + getNextMutationBatchAfterBatchId(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + getHighestUnacknowledgedBatchId(transaction: PersistenceTransaction): PersistencePromise; + getAllMutationBatches(transaction: PersistenceTransaction): PersistencePromise; + getAllMutationBatchesAffectingDocumentKey(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + getAllMutationBatchesAffectingDocumentKeys(transaction: PersistenceTransaction, documentKeys: SortedMap): PersistencePromise; + getAllMutationBatchesAffectingQuery(transaction: PersistenceTransaction, query: Query): PersistencePromise; + private lookupMutationBatches; + removeMutationBatch(transaction: PersistenceTransaction, batch: MutationBatch): PersistencePromise; + /** + * Clears the cached keys for a mutation batch. This method should be + * called by secondary clients after they process mutation updates. + * + * Note that this method does not have to be called from primary clients as + * the corresponding cache entries are cleared when an acknowledged or + * rejected batch is removed from the mutation queue. + */ + removeCachedMutationKeys(batchId: BatchId): void; + performConsistencyCheck(txn: PersistenceTransaction): PersistencePromise; + containsKey(txn: PersistenceTransaction, key: DocumentKey): PersistencePromise; + /** Returns the mutation queue's metadata from IndexedDb. */ + private getMutationQueueMetadata; +} +/** Returns true if any mutation queue contains the given document. */ +export declare function mutationQueuesContainKey(txn: PersistenceTransaction, docKey: DocumentKey): PersistencePromise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_persistence.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_persistence.d.ts new file mode 100644 index 0000000..f4cf7d8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_persistence.d.ts @@ -0,0 +1,270 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { DatabaseId } from '../core/database_info'; +import { SequenceNumberSyncer } from '../core/listen_sequence'; +import { JsonProtoSerializer } from '../remote/serializer'; +import { AsyncQueue } from '../util/async_queue'; +import { DocumentLike, WindowLike } from '../util/types'; +import { BundleCache } from './bundle_cache'; +import { DocumentOverlayCache } from './document_overlay_cache'; +import { GlobalsCache } from './globals_cache'; +import { IndexManager } from './index_manager'; +import { IndexedDbLruDelegateImpl } from './indexeddb_lru_delegate_impl'; +import { IndexedDbMutationQueue } from './indexeddb_mutation_queue'; +import { IndexedDbRemoteDocumentCache } from './indexeddb_remote_document_cache'; +import { IndexedDbTargetCache } from './indexeddb_target_cache'; +import { LruParams } from './lru_garbage_collector'; +import { Persistence, PrimaryStateListener } from './persistence'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction, PersistenceTransactionMode } from './persistence_transaction'; +import { ClientId } from './shared_client_state'; +/** + * The name of the main (and currently only) IndexedDB database. This name is + * appended to the prefix provided to the IndexedDbPersistence constructor. + */ +export declare const MAIN_DATABASE = "main"; +/** + * An IndexedDB-backed instance of Persistence. Data is stored persistently + * across sessions. + * + * On Web only, the Firestore SDKs support shared access to its persistence + * layer. This allows multiple browser tabs to read and write to IndexedDb and + * to synchronize state even without network connectivity. Shared access is + * currently optional and not enabled unless all clients invoke + * `enablePersistence()` with `{synchronizeTabs:true}`. + * + * In multi-tab mode, if multiple clients are active at the same time, the SDK + * will designate one client as the "primary client". An effort is made to pick + * a visible, network-connected and active client, and this client is + * responsible for letting other clients know about its presence. The primary + * client writes a unique client-generated identifier (the client ID) to + * IndexedDb’s "owner" store every 4 seconds. If the primary client fails to + * update this entry, another client can acquire the lease and take over as + * primary. + * + * Some persistence operations in the SDK are designated as primary-client only + * operations. This includes the acknowledgment of mutations and all updates of + * remote documents. The effects of these operations are written to persistence + * and then broadcast to other tabs via LocalStorage (see + * `WebStorageSharedClientState`), which then refresh their state from + * persistence. + * + * Similarly, the primary client listens to notifications sent by secondary + * clients to discover persistence changes written by secondary clients, such as + * the addition of new mutations and query targets. + * + * If multi-tab is not enabled and another tab already obtained the primary + * lease, IndexedDbPersistence enters a failed state and all subsequent + * operations will automatically fail. + * + * Additionally, there is an optimization so that when a tab is closed, the + * primary lease is released immediately (this is especially important to make + * sure that a refreshed tab is able to immediately re-acquire the primary + * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload + * since it is an asynchronous API. So in addition to attempting to give up the + * lease, the leaseholder writes its client ID to a "zombiedClient" entry in + * LocalStorage which acts as an indicator that another tab should go ahead and + * take the primary lease immediately regardless of the current lease timestamp. + * + * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no + * longer optional. + */ +export declare class IndexedDbPersistence implements Persistence { + /** + * Whether to synchronize the in-memory state of multiple tabs and share + * access to local persistence. + */ + private readonly allowTabSynchronization; + private readonly persistenceKey; + private readonly clientId; + private readonly queue; + private readonly window; + private readonly document; + private readonly sequenceNumberSyncer; + /** + * If set to true, forcefully obtains database access. Existing tabs will + * no longer be able to access IndexedDB. + */ + private readonly forceOwningTab; + private readonly schemaVersion; + private simpleDb; + private listenSequence; + private _started; + private isPrimary; + private networkEnabled; + private dbName; + /** Our window.unload handler, if registered. */ + private windowUnloadHandler; + private inForeground; + private serializer; + /** Our 'visibilitychange' listener if registered. */ + private documentVisibilityHandler; + /** The client metadata refresh task. */ + private clientMetadataRefresher; + /** The last time we garbage collected the client metadata object store. */ + private lastGarbageCollectionTime; + /** A listener to notify on primary state changes. */ + private primaryStateListener; + private readonly globalsCache; + private readonly targetCache; + private readonly remoteDocumentCache; + private readonly bundleCache; + private readonly webStorage; + readonly referenceDelegate: IndexedDbLruDelegateImpl; + constructor( + /** + * Whether to synchronize the in-memory state of multiple tabs and share + * access to local persistence. + */ + allowTabSynchronization: boolean, persistenceKey: string, clientId: ClientId, lruParams: LruParams, queue: AsyncQueue, window: WindowLike | null, document: DocumentLike | null, serializer: JsonProtoSerializer, sequenceNumberSyncer: SequenceNumberSyncer, + /** + * If set to true, forcefully obtains database access. Existing tabs will + * no longer be able to access IndexedDB. + */ + forceOwningTab: boolean, schemaVersion?: number); + /** + * Attempt to start IndexedDb persistence. + * + * @returns Whether persistence was enabled. + */ + start(): Promise; + /** + * Registers a listener that gets called when the primary state of the + * instance changes. Upon registering, this listener is invoked immediately + * with the current primary state. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setPrimaryStateListener(primaryStateListener: PrimaryStateListener): Promise; + /** + * Registers a listener that gets called when the database receives a + * version change event indicating that it has deleted. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setDatabaseDeletedListener(databaseDeletedListener: () => Promise): void; + /** + * Adjusts the current network state in the client's metadata, potentially + * affecting the primary lease. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setNetworkEnabled(networkEnabled: boolean): void; + /** + * Updates the client metadata in IndexedDb and attempts to either obtain or + * extend the primary lease for the local client. Asynchronously notifies the + * primary state listener if the client either newly obtained or released its + * primary lease. + */ + private updateClientMetadataAndTryBecomePrimary; + private verifyPrimaryLease; + private removeClientMetadata; + /** + * If the garbage collection threshold has passed, prunes the + * RemoteDocumentChanges and the ClientMetadata store based on the last update + * time of all clients. + */ + private maybeGarbageCollectMultiClientState; + /** + * Schedules a recurring timer to update the client metadata and to either + * extend or acquire the primary lease if the client is eligible. + */ + private scheduleClientMetadataAndPrimaryLeaseRefreshes; + /** Checks whether `client` is the local client. */ + private isLocalClient; + /** + * Evaluate the state of all active clients and determine whether the local + * client is or can act as the holder of the primary lease. Returns whether + * the client is eligible for the lease, but does not actually acquire it. + * May return 'false' even if there is no active leaseholder and another + * (foreground) client should become leaseholder instead. + */ + private canActAsPrimary; + shutdown(): Promise; + /** + * Returns clients that are not zombied and have an updateTime within the + * provided threshold. + */ + private filterActiveClients; + /** + * Returns the IDs of the clients that are currently active. If multi-tab + * is not supported, returns an array that only contains the local client's + * ID. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + getActiveClients(): Promise; + get started(): boolean; + getGlobalsCache(): GlobalsCache; + getMutationQueue(user: User, indexManager: IndexManager): IndexedDbMutationQueue; + getTargetCache(): IndexedDbTargetCache; + getRemoteDocumentCache(): IndexedDbRemoteDocumentCache; + getIndexManager(user: User): IndexManager; + getDocumentOverlayCache(user: User): DocumentOverlayCache; + getBundleCache(): BundleCache; + runTransaction(action: string, mode: PersistenceTransactionMode, transactionOperation: (transaction: PersistenceTransaction) => PersistencePromise): Promise; + /** + * Verifies that the current tab is the primary leaseholder or alternatively + * that the leaseholder has opted into multi-tab synchronization. + */ + private verifyAllowTabSynchronization; + /** + * Obtains or extends the new primary lease for the local client. This + * method does not verify that the client is eligible for this lease. + */ + private acquireOrExtendPrimaryLease; + static isAvailable(): boolean; + /** Checks the primary lease and removes it if we are the current primary. */ + private releasePrimaryLeaseIfHeld; + /** Verifies that `updateTimeMs` is within `maxAgeMs`. */ + private isWithinAge; + private attachVisibilityHandler; + private detachVisibilityHandler; + /** + * Attaches a window.unload handler that will synchronously write our + * clientId to a "zombie client id" location in LocalStorage. This can be used + * by tabs trying to acquire the primary lease to determine that the lease + * is no longer valid even if the timestamp is recent. This is particularly + * important for the refresh case (so the tab correctly re-acquires the + * primary lease). LocalStorage is used for this rather than IndexedDb because + * it is a synchronous API and so can be used reliably from an unload + * handler. + */ + private attachWindowUnloadHook; + private detachWindowUnloadHook; + /** + * Returns whether a client is "zombied" based on its LocalStorage entry. + * Clients become zombied when their tab closes without running all of the + * cleanup logic in `shutdown()`. + */ + private isClientZombied; + /** + * Record client as zombied (a client that had its tab closed). Zombied + * clients are ignored during primary tab selection. + */ + private markClientZombied; + /** Removes the zombied client entry if it exists. */ + private removeClientZombiedEntry; + private zombiedClientLocalStorageKey; +} +/** + * Generates a string used as a prefix when storing data in IndexedDB and + * LocalStorage. + */ +export declare function indexedDbStoragePrefix(databaseId: DatabaseId, persistenceKey: string): string; +export declare function indexedDbClearPersistence(persistenceKey: string): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_remote_document_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_remote_document_cache.d.ts new file mode 100644 index 0000000..14532c1 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_remote_document_cache.d.ts @@ -0,0 +1,36 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { MutableDocument } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { LocalSerializer } from './local_serializer'; +import { RemoteDocumentCache } from './remote_document_cache'; +export interface DocumentSizeEntry { + document: MutableDocument; + size: number; +} +export interface IndexedDbRemoteDocumentCache extends RemoteDocumentCache { +} +/** Creates a new IndexedDbRemoteDocumentCache. */ +export declare function newIndexedDbRemoteDocumentCache(serializer: LocalSerializer): IndexedDbRemoteDocumentCache; +/** + * Comparator that compares document keys according to the primary key sorting + * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id + * and then document ID). + * + * Visible for testing. + */ +export declare function dbKeyComparator(l: DocumentKey, r: DocumentKey): number; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_schema.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_schema.d.ts new file mode 100644 index 0000000..a88f237 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_schema.d.ts @@ -0,0 +1,509 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BatchId, ListenSequenceNumber, TargetId } from '../core/types'; +import { IndexKind } from '../model/field_index'; +import { BundledQuery } from '../protos/firestore_bundle_proto'; +import { Document as ProtoDocument, DocumentsTarget as ProtoDocumentsTarget, QueryTarget as ProtoQueryTarget, Write as ProtoWrite } from '../protos/firestore_proto_api'; +import { EncodedResourcePath } from './encoded_resource_path'; +import { DbTimestampKey, KeySafeBytes } from './indexeddb_sentinels'; +/** + * Schema Version for the Web client: + * 1. Initial version including Mutation Queue, Query Cache, and Remote + * Document Cache + * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No + * longer required because migration 3 unconditionally clears it. + * 3. Dropped and re-created Query Cache to deal with cache corruption related + * to limbo resolution. Addresses + * https://github.com/firebase/firebase-ios-sdk/issues/1548 + * 4. Multi-Tab Support. + * 5. Removal of held write acks. + * 6. Create document global for tracking document cache size. + * 7. Ensure every cached document has a sentinel row with a sequence number. + * 8. Add collection-parent index for Collection Group queries. + * 9. Change RemoteDocumentChanges store to be keyed by readTime rather than + * an auto-incrementing ID. This is required for Index-Free queries. + * 10. Rewrite the canonical IDs to the explicit Protobuf-based format. + * 11. Add bundles and named_queries for bundle support. + * 12. Add document overlays. + * 13. Rewrite the keys of the remote document cache to allow for efficient + * document lookup via `getAll()`. + * 14. Add overlays. + * 15. Add indexing support. + * 16. Parse timestamp strings before creating index entries. + * 17. TODO(tomandersen) + * 18. Encode key safe representations of IndexEntry in DbIndexEntryStore. + */ +export declare const SCHEMA_VERSION = 18; +/** + * Wrapper class to store timestamps (seconds and nanos) in IndexedDb objects. + */ +export interface DbTimestamp { + seconds: number; + nanoseconds: number; +} +/** + * A singleton object to be stored in the 'owner' store in IndexedDb. + * + * A given database can have a single primary tab assigned at a given time. That + * tab must validate that it is still holding the primary lease before every + * operation that requires locked access. The primary tab should regularly + * write an updated timestamp to this lease to prevent other tabs from + * "stealing" the primary lease + */ +export interface DbPrimaryClient { + ownerId: string; + /** Whether to allow shared access from multiple tabs. */ + allowTabSynchronization: boolean; + leaseTimestampMs: number; +} +/** + * An object to be stored in the 'mutationQueues' store in IndexedDb. + * + * Each user gets a single queue of MutationBatches to apply to the server. + * DbMutationQueue tracks the metadata about the queue. + */ +export interface DbMutationQueue { + /** + * The normalized user ID to which this queue belongs. + */ + userId: string; + /** + * An identifier for the highest numbered batch that has been acknowledged + * by the server. All MutationBatches in this queue with batchIds less + * than or equal to this value are considered to have been acknowledged by + * the server. + * + * NOTE: this is deprecated and no longer used by the code. + */ + lastAcknowledgedBatchId: number; + /** + * A stream token that was previously sent by the server. + * + * See StreamingWriteRequest in datastore.proto for more details about + * usage. + * + * After sending this token, earlier tokens may not be used anymore so + * only a single stream token is retained. + * + * NOTE: this is deprecated and no longer used by the code. + */ + lastStreamToken: string; +} +/** + * An object to be stored in the 'mutations' store in IndexedDb. + * + * Represents a batch of user-level mutations intended to be sent to the server + * in a single write. Each user-level batch gets a separate DbMutationBatch + * with a new batchId. + */ +export interface DbMutationBatch { + /** + * The normalized user ID to which this batch belongs. + */ + userId: string; + /** + * An identifier for this batch, allocated using an auto-generated key. + */ + batchId: BatchId; + /** + * The local write time of the batch, stored as milliseconds since the + * epoch. + */ + localWriteTimeMs: number; + /** + * A list of "mutations" that represent a partial base state from when this + * write batch was initially created. During local application of the write + * batch, these baseMutations are applied prior to the real writes in order + * to override certain document fields from the remote document cache. This + * is necessary in the case of non-idempotent writes (e.g. `increment()` + * transforms) to make sure that the local view of the modified documents + * doesn't flicker if the remote document cache receives the result of the + * non-idempotent write before the write is removed from the queue. + * + * These mutations are never sent to the backend. + */ + baseMutations?: ProtoWrite[]; + /** + * A list of mutations to apply. All mutations will be applied atomically. + * + * Mutations are serialized via toMutation(). + */ + mutations: ProtoWrite[]; +} +/** + * An object to be stored in the 'documentMutations' store in IndexedDb. + * + * A manually maintained index of all the mutation batches that affect a given + * document key. The rows in this table are references based on the contents of + * DbMutationBatch.mutations. + */ +export interface DbDocumentMutation { +} +/** + * Represents the known absence of a document at a particular version. + * Stored in IndexedDb as part of a DbRemoteDocument object. + */ +export interface DbNoDocument { + path: string[]; + readTime: DbTimestamp; +} +/** + * Represents a document that is known to exist but whose data is unknown. + * Stored in IndexedDb as part of a DbRemoteDocument object. + */ +export interface DbUnknownDocument { + path: string[]; + version: DbTimestamp; +} +/** + * An object to be stored in the 'remoteDocuments' store in IndexedDb. + * It represents either: + * + * - A complete document. + * - A "no document" representing a document that is known not to exist (at + * some version). + * - An "unknown document" representing a document that is known to exist (at + * some version) but whose contents are unknown. + * + * The document key is split up across `prefixPath`, `collectionGroup` and + * `documentId`. + * + * Note: This is the persisted equivalent of a MaybeDocument and could perhaps + * be made more general if necessary. + */ +export interface DbRemoteDocument { + /** The path to the document's collection (excluding). */ + prefixPath: string[]; + /** The collection ID the document is directly nested under. */ + collectionGroup: string; + /** The document ID. */ + documentId: string; + /** When the document was read from the backend. */ + readTime: DbTimestampKey; + /** + * Set to an instance of DbUnknownDocument if the data for a document is + * not known, but it is known that a document exists at the specified + * version (e.g. it had a successful update applied to it) + */ + unknownDocument?: DbUnknownDocument; + /** + * Set to an instance of a DbNoDocument if it is known that no document + * exists. + */ + noDocument?: DbNoDocument; + /** + * Set to an instance of a Document if there's a cached version of the + * document. + */ + document?: ProtoDocument; + /** + * Documents that were written to the remote document store based on + * a write acknowledgment are marked with `hasCommittedMutations`. These + * documents are potentially inconsistent with the backend's copy and use + * the write's commit version as their document version. + */ + hasCommittedMutations: boolean; +} +/** + * Contains a single entry that has metadata about the remote document cache. + */ +export interface DbRemoteDocumentGlobal { + /** + * Approximately the total size in bytes of all the + * documents in the document cache. + */ + byteSize: number; +} +/** + * The persisted type for a query nested with in the 'targets' store in + * IndexedDb. We use the proto definitions for these two kinds of queries in + * order to avoid writing extra serialization logic. + */ +export type DbQuery = ProtoQueryTarget | ProtoDocumentsTarget; +/** + * An object to be stored in the 'targets' store in IndexedDb. + * + * This is based on and should be kept in sync with the proto used in the iOS + * client. + * + * Each query the client listens to against the server is tracked on disk so + * that the query can be efficiently resumed on restart. + */ +export interface DbTarget { + /** + * An auto-generated sequential numeric identifier for the query. + * + * Queries are stored using their canonicalId as the key, but these + * canonicalIds can be quite long so we additionally assign a unique + * queryId which can be used by referenced data structures (e.g. + * indexes) to minimize the on-disk cost. + */ + targetId: TargetId; + /** + * The canonical string representing this query. This is not unique. + */ + canonicalId: string; + /** + * The last readTime received from the Watch Service for this query. + * + * This is the same value as TargetChange.read_time in the protos. + */ + readTime: DbTimestamp; + /** + * An opaque, server-assigned token that allows watching a query to be + * resumed after disconnecting without retransmitting all the data + * that matches the query. The resume token essentially identifies a + * point in time from which the server should resume sending results. + * + * This is related to the snapshotVersion in that the resumeToken + * effectively also encodes that value, but the resumeToken is opaque + * and sometimes encodes additional information. + * + * A consequence of this is that the resumeToken should be used when + * asking the server to reason about where this client is in the watch + * stream, but the client should use the snapshotVersion for its own + * purposes. + * + * This is the same value as TargetChange.resume_token in the protos. + */ + resumeToken: string; + /** + * A sequence number representing the last time this query was + * listened to, used for garbage collection purposes. + * + * Conventionally this would be a timestamp value, but device-local + * clocks are unreliable and they must be able to create new listens + * even while disconnected. Instead this should be a monotonically + * increasing number that's incremented on each listen call. + * + * This is different from the queryId since the queryId is an + * immutable identifier assigned to the Query on first use while + * lastListenSequenceNumber is updated every time the query is + * listened to. + */ + lastListenSequenceNumber: number; + /** + * Denotes the maximum snapshot version at which the associated query view + * contained no limbo documents. Undefined for data written prior to + * schema version 9. + */ + lastLimboFreeSnapshotVersion?: DbTimestamp; + /** + * The query for this target. + * + * Because canonical ids are not unique we must store the actual query. We + * use the proto to have an object we can persist without having to + * duplicate translation logic to and from a `Query` object. + */ + query: DbQuery; +} +/** + * An object representing an association between a target and a document, or a + * sentinel row marking the last sequence number at which a document was used. + * Each document cached must have a corresponding sentinel row before lru + * garbage collection is enabled. + * + * The target associations and sentinel rows are co-located so that orphaned + * documents and their sequence numbers can be identified efficiently via a scan + * of this store. + */ +export interface DbTargetDocument { + /** + * The targetId identifying a target or 0 for a sentinel row. + */ + targetId: TargetId; + /** + * The path to the document, as encoded in the key. + */ + path: EncodedResourcePath; + /** + * If this is a sentinel row, this should be the sequence number of the last + * time the document specified by `path` was used. Otherwise, it should be + * `undefined`. + */ + sequenceNumber?: ListenSequenceNumber; +} +/** + * A record of global state tracked across all Targets, tracked separately + * to avoid the need for extra indexes. + * + * This should be kept in-sync with the proto used in the iOS client. + */ +export interface DbTargetGlobal { + /** + * The highest numbered target id across all targets. + * + * See DbTarget.targetId. + */ + highestTargetId: TargetId; + /** + * The highest numbered lastListenSequenceNumber across all targets. + * + * See DbTarget.lastListenSequenceNumber. + */ + highestListenSequenceNumber: number; + /** + * A global snapshot version representing the last consistent snapshot we + * received from the backend. This is monotonically increasing and any + * snapshots received from the backend prior to this version (e.g. for + * targets resumed with a resumeToken) should be suppressed (buffered) + * until the backend has caught up to this snapshot version again. This + * prevents our cache from ever going backwards in time. + */ + lastRemoteSnapshotVersion: DbTimestamp; + /** + * The number of targets persisted. + */ + targetCount: number; +} +/** + * An object representing an association between a Collection id (e.g. 'messages') + * to a parent path (e.g. '/chats/123') that contains it as a (sub)collection. + * This is used to efficiently find all collections to query when performing + * a Collection Group query. + */ +export interface DbCollectionParent { + /** + * The collectionId (e.g. 'messages') + */ + collectionId: string; + /** + * The path to the parent (either a document location or an empty path for + * a root-level collection). + */ + parent: EncodedResourcePath; +} +/** + * A record of the metadata state of each client. + * + * PORTING NOTE: This is used to synchronize multi-tab state and does not need + * to be ported to iOS or Android. + */ +export interface DbClientMetadata { + /** The auto-generated client id assigned at client startup. */ + clientId: string; + /** The last time this state was updated. */ + updateTimeMs: number; + /** Whether the client's network connection is enabled. */ + networkEnabled: boolean; + /** Whether this client is running in a foreground tab. */ + inForeground: boolean; +} +/** An object representing a bundle loaded by the SDK. */ +export interface DbBundle { + /** The ID of the loaded bundle. */ + bundleId: string; + /** The create time of the loaded bundle. */ + createTime: DbTimestamp; + /** The schema version of the loaded bundle. */ + version: number; +} +/** An object representing a named query loaded by the SDK via a bundle. */ +export interface DbNamedQuery { + /** The name of the query. */ + name: string; + /** The read time of the results saved in the bundle from the named query. */ + readTime: DbTimestamp; + /** The query saved in the bundle. */ + bundledQuery: BundledQuery; +} +/** An object representing the global configuration for a field index. */ +export interface DbIndexConfiguration { + /** + * The index id for this entry. Undefined for indexes that are not yet + * persisted. + */ + indexId?: number; + /** The collection group this index belongs to. */ + collectionGroup: string; + /** The fields to index for this index. */ + fields: Array<[name: string, kind: IndexKind]>; +} +/** + * An object describing how up-to-date the index backfill is for each user and + * index. + */ +export interface DbIndexState { + /** The index id for this entry. */ + indexId: number; + /** The user id for this entry. */ + uid: string; + /** + * A number that indicates when the index was last updated (relative to + * other indexes). + */ + sequenceNumber: number; + /** + * The latest read time that has been indexed by Firestore for this field + * index. Set to `{seconds: 0, nanos: 0}` if no documents have been indexed. + */ + readTime: DbTimestamp; + /** + * The last document that has been indexed for this field index. Empty if + * no documents have been indexed. + */ + documentKey: EncodedResourcePath; + /** + * The largest mutation batch id that has been processed for this index. -1 + * if no mutations have been indexed. + */ + largestBatchId: number; +} +/** An object that stores the encoded entries for all documents and fields. */ +export interface DbIndexEntry { + /** The index id for this entry. */ + indexId: number; + /** The user id for this entry. */ + uid: string; + /** The encoded array index value for this entry. */ + arrayValue: KeySafeBytes; + /** The encoded directional value for equality and inequality filters. */ + directionalValue: KeySafeBytes; + /** + * The document key this entry points to. This entry is encoded by an ordered + * encoder to match the key order of the index. + */ + orderedDocumentKey: KeySafeBytes; + /** The segments of the document key this entry points to. */ + documentKey: string[]; +} +/** + * An object representing a document overlay. + */ +export interface DbDocumentOverlay { + /** The user ID to whom this overlay belongs. */ + userId: string; + /** The path to the collection that contains the document. */ + collectionPath: string; + /** The ID (key) of the document within the collection. */ + documentId: string; + /** The collection group to which the document belongs. */ + collectionGroup: string; + /** The largest batch ID that's been applied for this overlay. */ + largestBatchId: number; + /** The overlay mutation. */ + overlayMutation: ProtoWrite; +} +/** + * An object containing global name/value pair. + */ +export interface DbGlobals { + /** Name is a globally unique identifier for a value. */ + name: string; + /** Value is a general purpose storage for global data. */ + value: Uint8Array; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_schema_converter.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_schema_converter.d.ts new file mode 100644 index 0000000..0daedc5 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_schema_converter.d.ts @@ -0,0 +1,43 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { LocalSerializer } from './local_serializer'; +import { PersistencePromise } from './persistence_promise'; +import { SimpleDbSchemaConverter } from './simple_db'; +/** Performs database creation and schema upgrades. */ +export declare class SchemaConverter implements SimpleDbSchemaConverter { + private readonly serializer; + constructor(serializer: LocalSerializer); + /** + * Performs database creation and schema upgrades. + * + * Note that in production, this method is only ever used to upgrade the schema + * to SCHEMA_VERSION. Different values of toVersion are only used for testing + * and local feature development. + */ + createOrUpgrade(db: IDBDatabase, txn: IDBTransaction, fromVersion: number, toVersion: number): PersistencePromise; + private addDocumentGlobal; + private removeAcknowledgedMutations; + /** + * Ensures that every document in the remote document cache has a corresponding sentinel row + * with a sequence number. Missing rows are given the most recently used sequence number. + */ + private ensureSequenceNumbers; + private createCollectionParentIndex; + private rewriteCanonicalIds; + private rewriteRemoteDocumentCache; + private runOverlayMigration; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_schema_legacy.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_schema_legacy.d.ts new file mode 100644 index 0000000..51716a6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_schema_legacy.d.ts @@ -0,0 +1,29 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Document as ProtoDocument } from '../protos/firestore_proto_api'; +import { DbNoDocument, DbUnknownDocument } from './indexeddb_schema'; +import { DbTimestampKey } from './indexeddb_sentinels'; +export interface DbRemoteDocument { + unknownDocument?: DbUnknownDocument; + noDocument?: DbNoDocument; + document?: ProtoDocument; + hasCommittedMutations?: boolean; + readTime?: DbTimestampKey; + parentPath?: string[]; +} +export type DbRemoteDocumentKey = string[]; +export declare const DbRemoteDocumentStore = "remoteDocuments"; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_sentinels.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_sentinels.d.ts new file mode 100644 index 0000000..acd9785 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_sentinels.d.ts @@ -0,0 +1,267 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BatchId, TargetId } from '../core/types'; +import { ResourcePath } from '../model/path'; +import { EncodedResourcePath } from './encoded_resource_path'; +import { DbDocumentMutation } from './indexeddb_schema'; +/** A timestamp type that can be used in IndexedDb keys. */ +export type DbTimestampKey = [/* seconds */ number, /* nanos */ number]; +export type DbPrimaryClientKey = typeof DbPrimaryClientKey; +/** + * Name of the IndexedDb object store. + * + * Note that the name 'owner' is chosen to ensure backwards compatibility with + * older clients that only supported single locked access to the persistence + * layer. + */ +export declare const DbPrimaryClientStore = "owner"; +/** + * The key string used for the single object that exists in the + * DbPrimaryClient store. + */ +export declare const DbPrimaryClientKey = "owner"; +/** Object keys in the 'mutationQueues' store are userId strings. */ +export type DbMutationQueueKey = string; +/** Name of the IndexedDb object store. */ +export declare const DbMutationQueueStore = "mutationQueues"; +/** Keys are automatically assigned via the userId property. */ +export declare const DbMutationQueueKeyPath = "userId"; +/** The 'mutations' store is keyed by batch ID. */ +export type DbMutationBatchKey = BatchId; +/** Name of the IndexedDb object store. */ +export declare const DbMutationBatchStore = "mutations"; +/** Keys are automatically assigned via the userId, batchId properties. */ +export declare const DbMutationBatchKeyPath = "batchId"; +/** The index name for lookup of mutations by user. */ +export declare const DbMutationBatchUserMutationsIndex = "userMutationsIndex"; +/** The user mutations index is keyed by [userId, batchId] pairs. */ +export declare const DbMutationBatchUserMutationsKeyPath: string[]; +/** + * The key for a db document mutation, which is made up of a userID, path, and + * batchId. Note that the path must be serialized into a form that indexedDB can + * sort. + */ +export type DbDocumentMutationKey = [string, EncodedResourcePath, BatchId]; +/** + * Creates a [userId] key for use in the DbDocumentMutations index to iterate + * over all of a user's document mutations. + */ +export declare function newDbDocumentMutationPrefixForUser(userId: string): [string]; +/** + * Creates a [userId, encodedPath] key for use in the DbDocumentMutations + * index to iterate over all at document mutations for a given path or lower. + */ +export declare function newDbDocumentMutationPrefixForPath(userId: string, path: ResourcePath): [string, EncodedResourcePath]; +/** + * Creates a full index key of [userId, encodedPath, batchId] for inserting + * and deleting into the DbDocumentMutations index. + */ +export declare function newDbDocumentMutationKey(userId: string, path: ResourcePath, batchId: BatchId): DbDocumentMutationKey; +/** + * Because we store all the useful information for this store in the key, + * there is no useful information to store as the value. The raw (unencoded) + * path cannot be stored because IndexedDb doesn't store prototype + * information. + */ +export declare const DbDocumentMutationPlaceholder: DbDocumentMutation; +export declare const DbDocumentMutationStore = "documentMutations"; +export declare const DbRemoteDocumentStore = "remoteDocumentsV14"; +/** + * A key in the 'remoteDocumentsV14' object store is an array containing the + * collection path, the collection group, the read time and the document id. + */ +export type DbRemoteDocumentKey = [ + /** path to collection */ string[], + /** collection group */ string, + /** read time */ DbTimestampKey, + /** document ID */ string +]; +/** + * The primary key of the remote documents store, which allows for efficient + * access by collection path and read time. + */ +export declare const DbRemoteDocumentKeyPath: string[]; +/** An index that provides access to documents by key. */ +export declare const DbRemoteDocumentDocumentKeyIndex = "documentKeyIndex"; +export declare const DbRemoteDocumentDocumentKeyIndexPath: string[]; +/** + * An index that provides access to documents by collection group and read + * time. + * + * This index is used by the index backfiller. + */ +export declare const DbRemoteDocumentCollectionGroupIndex = "collectionGroupIndex"; +export declare const DbRemoteDocumentCollectionGroupIndexPath: string[]; +export declare const DbRemoteDocumentGlobalStore = "remoteDocumentGlobal"; +export declare const DbRemoteDocumentGlobalKey = "remoteDocumentGlobalKey"; +export type DbRemoteDocumentGlobalKey = typeof DbRemoteDocumentGlobalKey; +/** + * A key in the 'targets' object store is a targetId of the query. + */ +export type DbTargetKey = TargetId; +export declare const DbTargetStore = "targets"; +/** Keys are automatically assigned via the targetId property. */ +export declare const DbTargetKeyPath = "targetId"; +/** The name of the queryTargets index. */ +export declare const DbTargetQueryTargetsIndexName = "queryTargetsIndex"; +/** + * The index of all canonicalIds to the targets that they match. This is not + * a unique mapping because canonicalId does not promise a unique name for all + * possible queries, so we append the targetId to make the mapping unique. + */ +export declare const DbTargetQueryTargetsKeyPath: string[]; +/** + * The key for a DbTargetDocument, containing a targetId and an encoded resource + * path. + */ +export type DbTargetDocumentKey = [TargetId, EncodedResourcePath]; +/** Name of the IndexedDb object store. */ +export declare const DbTargetDocumentStore = "targetDocuments"; +/** Keys are automatically assigned via the targetId, path properties. */ +export declare const DbTargetDocumentKeyPath: string[]; +/** The index name for the reverse index. */ +export declare const DbTargetDocumentDocumentTargetsIndex = "documentTargetsIndex"; +/** We also need to create the reverse index for these properties. */ +export declare const DbTargetDocumentDocumentTargetsKeyPath: string[]; +/** + * The type to represent the single allowed key for the DbTargetGlobal store. + */ +export type DbTargetGlobalKey = typeof DbTargetGlobalKey; +/** + * The key string used for the single object that exists in the + * DbTargetGlobal store. + */ +export declare const DbTargetGlobalKey = "targetGlobalKey"; +export declare const DbTargetGlobalStore = "targetGlobal"; +/** + * The key for a DbCollectionParent entry, containing the collection ID + * and the parent path that contains it. Note that the parent path will be an + * empty path in the case of root-level collections. + */ +export type DbCollectionParentKey = [string, EncodedResourcePath]; +/** Name of the IndexedDb object store. */ +export declare const DbCollectionParentStore = "collectionParents"; +/** Keys are automatically assigned via the collectionId, parent properties. */ +export declare const DbCollectionParentKeyPath: string[]; +/** Name of the IndexedDb object store. */ +export declare const DbClientMetadataStore = "clientMetadata"; +/** Keys are automatically assigned via the clientId properties. */ +export declare const DbClientMetadataKeyPath = "clientId"; +/** Object keys in the 'clientMetadata' store are clientId strings. */ +export type DbClientMetadataKey = string; +export type DbBundlesKey = string; +/** Name of the IndexedDb object store. */ +export declare const DbBundleStore = "bundles"; +export declare const DbBundleKeyPath = "bundleId"; +export type DbNamedQueriesKey = string; +/** Name of the IndexedDb object store. */ +export declare const DbNamedQueryStore = "namedQueries"; +export declare const DbNamedQueryKeyPath = "name"; +/** The key for each index consisting of just the index id. */ +export type DbIndexConfigurationKey = number; +/** Name of the IndexedDb object store. */ +export declare const DbIndexConfigurationStore = "indexConfiguration"; +export declare const DbIndexConfigurationKeyPath = "indexId"; +/** + * An index that provides access to the index configurations by collection + * group. + * + * PORTING NOTE: iOS and Android maintain this index in-memory, but this is + * not possible here as the Web client supports concurrent access to + * persistence via multi-tab. + */ +export declare const DbIndexConfigurationCollectionGroupIndex = "collectionGroupIndex"; +export declare const DbIndexConfigurationCollectionGroupIndexPath = "collectionGroup"; +/** The key for each index state consisting of the index id and its user id. */ +export type DbIndexStateKey = [number, string]; +/** Name of the IndexedDb object store. */ +export declare const DbIndexStateStore = "indexState"; +export declare const DbIndexStateKeyPath: string[]; +/** + * An index that provides access to documents in a collection sorted by last + * update time. Used by the backfiller. + * + * PORTING NOTE: iOS and Android maintain this index in-memory, but this is + * not possible here as the Web client supports concurrent access to + * persistence via multi-tab. + */ +export declare const DbIndexStateSequenceNumberIndex = "sequenceNumberIndex"; +export declare const DbIndexStateSequenceNumberIndexPath: string[]; +/** + * Representation of a byte array that is safe for + * use in an IndexedDb key. The value is either + * a "sortable byte string", which is key safe in + * Safari/WebKit, or the value is a Uint8Array, + * which is key safe in other browsers. + */ +export type KeySafeBytes = Uint8Array | string; +/** + * The key for each index entry consists of the index id and its user id, + * the encoded array and directional value for the indexed fields as well as + * an ordered and an encoded document path for the indexed document. + */ +export type DbIndexEntryKey = [ + number, + string, + KeySafeBytes, + KeySafeBytes, + KeySafeBytes, + string[] +]; +/** Name of the IndexedDb object store. */ +export declare const DbIndexEntryStore = "indexEntries"; +export declare const DbIndexEntryKeyPath: string[]; +export declare const DbIndexEntryDocumentKeyIndex = "documentKeyIndex"; +export declare const DbIndexEntryDocumentKeyIndexPath: string[]; +export type DbDocumentOverlayKey = [ + string, + string, + string +]; +/** Name of the IndexedDb object store. */ +export declare const DbDocumentOverlayStore = "documentOverlays"; +export declare const DbDocumentOverlayKeyPath: string[]; +export declare const DbDocumentOverlayCollectionPathOverlayIndex = "collectionPathOverlayIndex"; +export declare const DbDocumentOverlayCollectionPathOverlayIndexPath: string[]; +export declare const DbDocumentOverlayCollectionGroupOverlayIndex = "collectionGroupOverlayIndex"; +export declare const DbDocumentOverlayCollectionGroupOverlayIndexPath: string[]; +/** Name of the IndexedDb object store. */ +export declare const DbGlobalsStore = "globals"; +export declare const DbGlobalsKeyPath = "name"; +/** Names of global values */ +export type DbGlobalsKey = 'sessionToken'; +export declare const V1_STORES: string[]; +export declare const V3_STORES: string[]; +export declare const V4_STORES: string[]; +export declare const V6_STORES: string[]; +export declare const V8_STORES: string[]; +export declare const V11_STORES: string[]; +export declare const V12_STORES: string[]; +export declare const V13_STORES: string[]; +export declare const V14_STORES: string[]; +export declare const V15_STORES: string[]; +export declare const V16_STORES: string[]; +export declare const V17_STORES: string[]; +export declare const V18_STORES: string[]; +/** + * The list of all default IndexedDB stores used throughout the SDK. This is + * used when creating transactions so that access across all stores is done + * atomically. + */ +export declare const ALL_STORES: string[]; +/** Returns the object stores for the provided schema. */ +export declare function getObjectStores(schemaVersion: number): string[]; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_target_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_target_cache.d.ts new file mode 100644 index 0000000..74654fe --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_target_cache.d.ts @@ -0,0 +1,81 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { Target } from '../core/target'; +import { ListenSequenceNumber, TargetId } from '../core/types'; +import { DocumentKeySet } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { IndexedDbLruDelegate } from './indexeddb_lru_delegate'; +import { DbTargetDocument } from './indexeddb_schema'; +import { DbTargetDocumentKey } from './indexeddb_sentinels'; +import { LocalSerializer } from './local_serializer'; +import { ActiveTargets } from './lru_garbage_collector'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +import { SimpleDbStore } from './simple_db'; +import { TargetCache } from './target_cache'; +import { TargetData } from './target_data'; +export declare class IndexedDbTargetCache implements TargetCache { + private readonly referenceDelegate; + private serializer; + constructor(referenceDelegate: IndexedDbLruDelegate, serializer: LocalSerializer); + allocateTargetId(transaction: PersistenceTransaction): PersistencePromise; + getLastRemoteSnapshotVersion(transaction: PersistenceTransaction): PersistencePromise; + getHighestSequenceNumber(transaction: PersistenceTransaction): PersistencePromise; + setTargetsMetadata(transaction: PersistenceTransaction, highestListenSequenceNumber: number, lastRemoteSnapshotVersion?: SnapshotVersion): PersistencePromise; + addTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + updateTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + removeTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Drops any targets with sequence number less than or equal to the upper bound, excepting those + * present in `activeTargetIds`. Document associations for the removed targets are also removed. + * Returns the number of targets removed. + */ + removeTargets(txn: PersistenceTransaction, upperBound: ListenSequenceNumber, activeTargetIds: ActiveTargets): PersistencePromise; + /** + * Call provided function with each `TargetData` that we have cached. + */ + forEachTarget(txn: PersistenceTransaction, f: (q: TargetData) => void): PersistencePromise; + private retrieveMetadata; + private saveMetadata; + private saveTargetData; + /** + * In-place updates the provided metadata to account for values in the given + * TargetData. Saving is done separately. Returns true if there were any + * changes to the metadata. + */ + private updateMetadataFromTargetData; + getTargetCount(transaction: PersistenceTransaction): PersistencePromise; + getTargetData(transaction: PersistenceTransaction, target: Target): PersistencePromise; + addMatchingKeys(txn: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + removeMatchingKeys(txn: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + removeMatchingKeysForTargetId(txn: PersistenceTransaction, targetId: TargetId): PersistencePromise; + getMatchingKeysForTargetId(txn: PersistenceTransaction, targetId: TargetId): PersistencePromise; + containsKey(txn: PersistenceTransaction, key: DocumentKey): PersistencePromise; + /** + * Looks up a TargetData entry by target ID. + * + * @param targetId - The target ID of the TargetData entry to look up. + * @returns The cached TargetData entry, or null if the cache has no entry for + * the target. + */ + getTargetDataForTarget(transaction: PersistenceTransaction, targetId: TargetId): PersistencePromise; +} +/** + * Helper to get a typed SimpleDbStore for the document target object store. + */ +export declare function documentTargetStore(txn: PersistenceTransaction): SimpleDbStore; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_transaction.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_transaction.d.ts new file mode 100644 index 0000000..4d1fc92 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/indexeddb_transaction.d.ts @@ -0,0 +1,25 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ListenSequenceNumber } from '../core/types'; +import { PersistenceTransaction } from './persistence_transaction'; +import { SimpleDbStore, SimpleDbTransaction } from './simple_db'; +export declare class IndexedDbTransaction extends PersistenceTransaction { + readonly simpleDbTransaction: SimpleDbTransaction; + readonly currentSequenceNumber: ListenSequenceNumber; + constructor(simpleDbTransaction: SimpleDbTransaction, currentSequenceNumber: ListenSequenceNumber); +} +export declare function getStore(txn: PersistenceTransaction, store: string): SimpleDbStore; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/local_documents_view.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/local_documents_view.d.ts new file mode 100644 index 0000000..8d276c3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/local_documents_view.d.ts @@ -0,0 +1,127 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Query } from '../core/query'; +import { DocumentKeySet, OverlayMap, DocumentMap, MutableDocumentMap, DocumentKeyMap, OverlayedDocumentMap } from '../model/collections'; +import { Document } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { IndexOffset } from '../model/field_index'; +import { FieldMask } from '../model/field_mask'; +import { DocumentOverlayCache } from './document_overlay_cache'; +import { IndexManager } from './index_manager'; +import { LocalWriteResult } from './local_store_impl'; +import { MutationQueue } from './mutation_queue'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +import { QueryContext } from './query_context'; +import { RemoteDocumentCache } from './remote_document_cache'; +/** + * A readonly view of the local state of all documents we're tracking (i.e. we + * have a cached version in remoteDocumentCache or local mutations for the + * document). The view is computed by applying the mutations in the + * MutationQueue to the RemoteDocumentCache. + */ +export declare class LocalDocumentsView { + readonly remoteDocumentCache: RemoteDocumentCache; + readonly mutationQueue: MutationQueue; + readonly documentOverlayCache: DocumentOverlayCache; + readonly indexManager: IndexManager; + constructor(remoteDocumentCache: RemoteDocumentCache, mutationQueue: MutationQueue, documentOverlayCache: DocumentOverlayCache, indexManager: IndexManager); + /** + * Get the local view of the document identified by `key`. + * + * @returns Local view of the document or null if we don't have any cached + * state for it. + */ + getDocument(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; + /** + * Gets the local view of the documents identified by `keys`. + * + * If we don't have cached state for a document in `keys`, a NoDocument will + * be stored for that key in the resulting set. + */ + getDocuments(transaction: PersistenceTransaction, keys: DocumentKeySet): PersistencePromise; + /** + * Similar to `getDocuments`, but creates the local view from the given + * `baseDocs` without retrieving documents from the local store. + * + * @param transaction - The transaction this operation is scoped to. + * @param docs - The documents to apply local mutations to get the local views. + * @param existenceStateChanged - The set of document keys whose existence state + * is changed. This is useful to determine if some documents overlay needs + * to be recalculated. + */ + getLocalViewOfDocuments(transaction: PersistenceTransaction, docs: MutableDocumentMap, existenceStateChanged?: DocumentKeySet): PersistencePromise; + /** + * Gets the overlayed documents for the given document map, which will include + * the local view of those documents and a `FieldMask` indicating which fields + * are mutated locally, `null` if overlay is a Set or Delete mutation. + */ + getOverlayedDocuments(transaction: PersistenceTransaction, docs: MutableDocumentMap): PersistencePromise; + /** + * Fetches the overlays for {@code docs} and adds them to provided overlay map + * if the map does not already contain an entry for the given document key. + */ + private populateOverlays; + /** + * Computes the local view for the given documents. + * + * @param docs - The documents to compute views for. It also has the base + * version of the documents. + * @param overlays - The overlays that need to be applied to the given base + * version of the documents. + * @param existenceStateChanged - A set of documents whose existence states + * might have changed. This is used to determine if we need to re-calculate + * overlays from mutation queues. + * @return A map represents the local documents view. + */ + computeViews(transaction: PersistenceTransaction, docs: MutableDocumentMap, overlays: OverlayMap, existenceStateChanged: DocumentKeySet): PersistencePromise; + private recalculateAndSaveOverlays; + /** + * Recalculates overlays by reading the documents from remote document cache + * first, and saves them after they are calculated. + */ + recalculateAndSaveOverlaysForDocumentKeys(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise>; + /** + * Performs a query against the local view of all documents. + * + * @param transaction - The persistence transaction. + * @param query - The query to match documents against. + * @param offset - Read time and key to start scanning by (exclusive). + * @param context - A optional tracker to keep a record of important details + * during database local query execution. + */ + getDocumentsMatchingQuery(transaction: PersistenceTransaction, query: Query, offset: IndexOffset, context?: QueryContext): PersistencePromise; + /** + * Given a collection group, returns the next documents that follow the provided offset, along + * with an updated batch ID. + * + *

The documents returned by this method are ordered by remote version from the provided + * offset. If there are no more remote documents after the provided offset, documents with + * mutations in order of batch id from the offset are returned. Since all documents in a batch are + * returned together, the total number of documents returned can exceed {@code count}. + * + * @param transaction + * @param collectionGroup The collection group for the documents. + * @param offset The offset to index into. + * @param count The number of documents to return + * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id. + */ + getNextDocuments(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset, count: number): PersistencePromise; + private getDocumentsMatchingDocumentQuery; + private getDocumentsMatchingCollectionGroupQuery; + private getDocumentsMatchingCollectionQuery; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/local_serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/local_serializer.d.ts new file mode 100644 index 0000000..88599b4 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/local_serializer.d.ts @@ -0,0 +1,80 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BundleMetadata, NamedQuery } from '../core/bundle'; +import { Query } from '../core/query'; +import { SnapshotVersion } from '../core/snapshot_version'; +import { MutableDocument } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { FieldIndex, IndexOffset } from '../model/field_index'; +import { MutationBatch } from '../model/mutation_batch'; +import { Overlay } from '../model/overlay'; +import { BundledQuery as ProtoBundledQuery, BundleMetadata as ProtoBundleMetadata, NamedQuery as ProtoNamedQuery } from '../protos/firestore_bundle_proto'; +import { JsonProtoSerializer } from '../remote/serializer'; +import { DbBundle, DbDocumentOverlay, DbIndexConfiguration, DbIndexState, DbMutationBatch, DbNamedQuery, DbRemoteDocument, DbTarget, DbTimestamp } from './indexeddb_schema'; +import { DbDocumentOverlayKey, DbTimestampKey } from './indexeddb_sentinels'; +import { TargetData } from './target_data'; +/** Serializer for values stored in the LocalStore. */ +export declare class LocalSerializer { + readonly remoteSerializer: JsonProtoSerializer; + constructor(remoteSerializer: JsonProtoSerializer); +} +/** Decodes a remote document from storage locally to a Document. */ +export declare function fromDbRemoteDocument(localSerializer: LocalSerializer, remoteDoc: DbRemoteDocument): MutableDocument; +/** Encodes a document for storage locally. */ +export declare function toDbRemoteDocument(localSerializer: LocalSerializer, document: MutableDocument): DbRemoteDocument; +export declare function toDbTimestampKey(snapshotVersion: SnapshotVersion): DbTimestampKey; +export declare function fromDbTimestampKey(dbTimestampKey: DbTimestampKey): SnapshotVersion; +export declare function toDbTimestamp(snapshotVersion: SnapshotVersion): DbTimestamp; +/** Encodes a batch of mutations into a DbMutationBatch for local storage. */ +export declare function toDbMutationBatch(localSerializer: LocalSerializer, userId: string, batch: MutationBatch): DbMutationBatch; +/** Decodes a DbMutationBatch into a MutationBatch */ +export declare function fromDbMutationBatch(localSerializer: LocalSerializer, dbBatch: DbMutationBatch): MutationBatch; +/** Decodes a DbTarget into TargetData */ +export declare function fromDbTarget(dbTarget: DbTarget): TargetData; +/** Encodes TargetData into a DbTarget for storage locally. */ +export declare function toDbTarget(localSerializer: LocalSerializer, targetData: TargetData): DbTarget; +/** Encodes a DbBundle to a BundleMetadata object. */ +export declare function fromDbBundle(dbBundle: DbBundle): BundleMetadata; +/** Encodes a BundleMetadata to a DbBundle. */ +export declare function toDbBundle(metadata: ProtoBundleMetadata): DbBundle; +/** Encodes a DbNamedQuery to a NamedQuery. */ +export declare function fromDbNamedQuery(dbNamedQuery: DbNamedQuery): NamedQuery; +/** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */ +export declare function toDbNamedQuery(query: ProtoNamedQuery): DbNamedQuery; +/** + * Encodes a `BundledQuery` from bundle proto to a Query object. + * + * This reconstructs the original query used to build the bundle being loaded, + * including features exists only in SDKs (for example: limit-to-last). + */ +export declare function fromBundledQuery(bundledQuery: ProtoBundledQuery): Query; +/** Encodes a NamedQuery proto object to a NamedQuery model object. */ +export declare function fromProtoNamedQuery(namedQuery: ProtoNamedQuery): NamedQuery; +/** Decodes a BundleMetadata proto into a BundleMetadata object. */ +export declare function fromBundleMetadata(metadata: ProtoBundleMetadata): BundleMetadata; +/** Encodes a DbDocumentOverlay object to an Overlay model object. */ +export declare function fromDbDocumentOverlay(localSerializer: LocalSerializer, dbDocumentOverlay: DbDocumentOverlay): Overlay; +/** Decodes an Overlay model object into a DbDocumentOverlay object. */ +export declare function toDbDocumentOverlay(localSerializer: LocalSerializer, userId: string, overlay: Overlay): DbDocumentOverlay; +/** + * Returns the DbDocumentOverlayKey corresponding to the given user and + * document key. + */ +export declare function toDbDocumentOverlayKey(userId: string, docKey: DocumentKey): DbDocumentOverlayKey; +export declare function toDbIndexConfiguration(index: FieldIndex): DbIndexConfiguration; +export declare function fromDbIndexConfiguration(index: DbIndexConfiguration, state: DbIndexState | null): FieldIndex; +export declare function toDbIndexState(indexId: number, uid: string, sequenceNumber: number, offset: IndexOffset): DbIndexState; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/local_store.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/local_store.d.ts new file mode 100644 index 0000000..2284d7d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/local_store.d.ts @@ -0,0 +1,41 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirestoreError } from '../util/error'; +import { IndexManager } from './index_manager'; +import { LocalDocumentsView } from './local_documents_view'; +import { LruGarbageCollector, LruResults } from './lru_garbage_collector'; +export interface LocalStore { + collectGarbage(garbageCollector: LruGarbageCollector): Promise; + /** Manages the list of active field and collection indices. */ + indexManager: IndexManager; + /** + * The "local" view of all documents (layering mutationQueue on top of + * remoteDocumentCache). + */ + localDocuments: LocalDocumentsView; +} +/** + * Verifies the error thrown by a LocalStore operation. If a LocalStore + * operation fails because the primary lease has been taken by another client, + * we ignore the error (the persistence layer will immediately call + * `applyPrimaryLease` to propagate the primary state change). All other errors + * are re-thrown. + * + * @param err - An error returned by a LocalStore operation. + * @returns A Promise that resolves after we recovered, or the original error. + */ +export declare function ignoreIfPrimaryLeaseLoss(err: FirestoreError): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/local_store_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/local_store_impl.d.ts new file mode 100644 index 0000000..1b86e0d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/local_store_impl.d.ts @@ -0,0 +1,208 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { BundleConverter, BundledDocuments, NamedQuery } from '../core/bundle'; +import { Query } from '../core/query'; +import { SnapshotVersion } from '../core/snapshot_version'; +import { Target } from '../core/target'; +import { BatchId, TargetId } from '../core/types'; +import { DocumentKeySet, DocumentMap } from '../model/collections'; +import { Document } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { FieldIndex } from '../model/field_index'; +import { Mutation } from '../model/mutation'; +import { MutationBatch, MutationBatchResult } from '../model/mutation_batch'; +import { BundleMetadata, NamedQuery as ProtoNamedQuery } from '../protos/firestore_bundle_proto'; +import { RemoteEvent } from '../remote/remote_event'; +import { JsonProtoSerializer } from '../remote/serializer'; +import { LocalStore } from './local_store'; +import { LocalViewChanges } from './local_view_changes'; +import { Persistence } from './persistence'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +import { QueryEngine } from './query_engine'; +import { ClientId } from './shared_client_state'; +import { TargetData } from './target_data'; +export declare const LOG_TAG = "LocalStore"; +/** The result of a write to the local store. */ +export interface LocalWriteResult { + batchId: BatchId; + changes: DocumentMap; +} +/** The result of a user-change operation in the local store. */ +export interface UserChangeResult { + readonly affectedDocuments: DocumentMap; + readonly removedBatchIds: BatchId[]; + readonly addedBatchIds: BatchId[]; +} +/** The result of executing a query against the local store. */ +export interface QueryResult { + readonly documents: DocumentMap; + readonly remoteKeys: DocumentKeySet; +} +export declare function newLocalStore( +/** Manages our in-memory or durable persistence. */ +persistence: Persistence, queryEngine: QueryEngine, initialUser: User, serializer: JsonProtoSerializer): LocalStore; +/** + * Tells the LocalStore that the currently authenticated user has changed. + * + * In response the local store switches the mutation queue to the new user and + * returns any resulting document changes. + */ +export declare function localStoreHandleUserChange(localStore: LocalStore, user: User): Promise; +export declare function localStoreWriteLocally(localStore: LocalStore, mutations: Mutation[]): Promise; +/** + * Acknowledges the given batch. + * + * On the happy path when a batch is acknowledged, the local store will + * + * + remove the batch from the mutation queue; + * + apply the changes to the remote document cache; + * + recalculate the latency compensated view implied by those changes (there + * may be mutations in the queue that affect the documents but haven't been + * acknowledged yet); and + * + give the changed documents back the sync engine + * + * @returns The resulting (modified) documents. + */ +export declare function localStoreAcknowledgeBatch(localStore: LocalStore, batchResult: MutationBatchResult): Promise; +/** + * Removes mutations from the MutationQueue for the specified batch; + * LocalDocuments will be recalculated. + * + * @returns The resulting modified documents. + */ +export declare function localStoreRejectBatch(localStore: LocalStore, batchId: BatchId): Promise; +/** + * Returns the largest (latest) batch id in mutation queue that is pending + * server response. + * + * Returns `BATCHID_UNKNOWN` if the queue is empty. + */ +export declare function localStoreGetHighestUnacknowledgedBatchId(localStore: LocalStore): Promise; +/** + * Returns the last consistent snapshot processed (used by the RemoteStore to + * determine whether to buffer incoming snapshots from the backend). + */ +export declare function localStoreGetLastRemoteSnapshotVersion(localStore: LocalStore): Promise; +/** + * Updates the "ground-state" (remote) documents. We assume that the remote + * event reflects any write batches that have been acknowledged or rejected + * (i.e. we do not re-apply local mutations to updates from this event). + * + * LocalDocuments are re-calculated if there are remaining mutations in the + * queue. + */ +export declare function localStoreApplyRemoteEventToLocalCache(localStore: LocalStore, remoteEvent: RemoteEvent): Promise; +/** + * Notifies local store of the changed views to locally pin documents. + */ +export declare function localStoreNotifyLocalViewChanges(localStore: LocalStore, viewChanges: LocalViewChanges[]): Promise; +/** + * Gets the mutation batch after the passed in batchId in the mutation queue + * or null if empty. + * @param afterBatchId - If provided, the batch to search after. + * @returns The next mutation or null if there wasn't one. + */ +export declare function localStoreGetNextMutationBatch(localStore: LocalStore, afterBatchId?: BatchId): Promise; +/** + * Reads the current value of a Document with a given key or null if not + * found - used for testing. + */ +export declare function localStoreReadDocument(localStore: LocalStore, key: DocumentKey): Promise; +/** + * Assigns the given target an internal ID so that its results can be pinned so + * they don't get GC'd. A target must be allocated in the local store before + * the store can be used to manage its view. + * + * Allocating an already allocated `Target` will return the existing `TargetData` + * for that `Target`. + */ +export declare function localStoreAllocateTarget(localStore: LocalStore, target: Target): Promise; +/** + * Returns the TargetData as seen by the LocalStore, including updates that may + * have not yet been persisted to the TargetCache. + */ +export declare function localStoreGetTargetData(localStore: LocalStore, transaction: PersistenceTransaction, target: Target): PersistencePromise; +/** + * Unpins all the documents associated with the given target. If + * `keepPersistedTargetData` is set to false and Eager GC enabled, the method + * directly removes the associated target data from the target cache. + * + * Releasing a non-existing `Target` is a no-op. + */ +export declare function localStoreReleaseTarget(localStore: LocalStore, targetId: number, keepPersistedTargetData: boolean): Promise; +/** + * Runs the specified query against the local store and returns the results, + * potentially taking advantage of query data from previous executions (such + * as the set of remote keys). + * + * @param usePreviousResults - Whether results from previous executions can + * be used to optimize this query execution. + */ +export declare function localStoreExecuteQuery(localStore: LocalStore, query: Query, usePreviousResults: boolean): Promise; +/** Returns the local view of the documents affected by a mutation batch. */ +export declare function localStoreLookupMutationDocuments(localStore: LocalStore, batchId: BatchId): Promise; +export declare function localStoreRemoveCachedMutationBatchMetadata(localStore: LocalStore, batchId: BatchId): void; +export declare function localStoreGetActiveClients(localStore: LocalStore): Promise; +export declare function localStoreGetCachedTarget(localStore: LocalStore, targetId: TargetId): Promise; +/** + * Returns the set of documents that have been updated since the last call. + * If this is the first call, returns the set of changes since client + * initialization. Further invocations will return document that have changed + * since the prior call. + */ +export declare function localStoreGetNewDocumentChanges(localStore: LocalStore, collectionGroup: string): Promise; +/** + * Applies the documents from a bundle to the "ground-state" (remote) + * documents. + * + * LocalDocuments are re-calculated if there are remaining mutations in the + * queue. + */ +export declare function localStoreApplyBundledDocuments(localStore: LocalStore, bundleConverter: BundleConverter, documents: BundledDocuments, bundleName: string): Promise; +/** + * Returns a promise of a boolean to indicate if the given bundle has already + * been loaded and the create time is newer than the current loading bundle. + */ +export declare function localStoreHasNewerBundle(localStore: LocalStore, bundleMetadata: BundleMetadata): Promise; +/** + * Saves the given `BundleMetadata` to local persistence. + */ +export declare function localStoreSaveBundle(localStore: LocalStore, bundleMetadata: BundleMetadata): Promise; +/** + * Returns a promise of a `NamedQuery` associated with given query name. Promise + * resolves to undefined if no persisted data can be found. + */ +export declare function localStoreGetNamedQuery(localStore: LocalStore, queryName: string): Promise; +/** + * Saves the given `NamedQuery` to local persistence. + */ +export declare function localStoreSaveNamedQuery(localStore: LocalStore, query: ProtoNamedQuery, documents?: DocumentKeySet): Promise; +export declare function localStoreConfigureFieldIndexes(localStore: LocalStore, newFieldIndexes: FieldIndex[]): Promise; +export declare function localStoreSetIndexAutoCreationEnabled(localStore: LocalStore, isEnabled: boolean): void; +export declare function localStoreDeleteAllFieldIndexes(localStore: LocalStore): Promise; +/** + * Test-only hooks into the SDK for use exclusively by tests. + */ +export declare class TestingHooks { + private constructor(); + static setIndexAutoCreationSettings(localStore: LocalStore, settings: { + indexAutoCreationMinCollectionSize?: number; + relativeIndexReadCostPerDocument?: number; + }): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/local_view_changes.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/local_view_changes.d.ts new file mode 100644 index 0000000..0448fb1 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/local_view_changes.d.ts @@ -0,0 +1,32 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { TargetId } from '../core/types'; +import { ViewSnapshot } from '../core/view_snapshot'; +import { DocumentKeySet } from '../model/collections'; +/** + * A set of changes to what documents are currently in view and out of view for + * a given query. These changes are sent to the LocalStore by the View (via + * the SyncEngine) and are used to pin / unpin documents as appropriate. + */ +export declare class LocalViewChanges { + readonly targetId: TargetId; + readonly fromCache: boolean; + readonly addedKeys: DocumentKeySet; + readonly removedKeys: DocumentKeySet; + constructor(targetId: TargetId, fromCache: boolean, addedKeys: DocumentKeySet, removedKeys: DocumentKeySet); + static fromSnapshot(targetId: TargetId, viewSnapshot: ViewSnapshot): LocalViewChanges; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/lru_garbage_collector.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/lru_garbage_collector.d.ts new file mode 100644 index 0000000..9ba755c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/lru_garbage_collector.d.ts @@ -0,0 +1,102 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ListenSequenceNumber, TargetId } from '../core/types'; +import { SortedMap } from '../util/sorted_map'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +import { TargetData } from './target_data'; +/** + * Describes a map whose keys are active target ids. We do not care about the type of the + * values. + */ +export type ActiveTargets = SortedMap; +export declare const GC_DID_NOT_RUN: LruResults; +export declare const LRU_COLLECTION_DISABLED = -1; +export declare const LRU_DEFAULT_CACHE_SIZE_BYTES: number; +export declare class LruParams { + readonly cacheSizeCollectionThreshold: number; + readonly percentileToCollect: number; + readonly maximumSequenceNumbersToCollect: number; + private static readonly DEFAULT_COLLECTION_PERCENTILE; + private static readonly DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT; + static withCacheSize(cacheSize: number): LruParams; + static readonly DEFAULT: LruParams; + static readonly DISABLED: LruParams; + constructor(cacheSizeCollectionThreshold: number, percentileToCollect: number, maximumSequenceNumbersToCollect: number); +} +export interface LruGarbageCollector { + readonly params: LruParams; + collect(txn: PersistenceTransaction, activeTargetIds: ActiveTargets): PersistencePromise; + /** Given a percentile of target to collect, returns the number of targets to collect. */ + calculateTargetCount(txn: PersistenceTransaction, percentile: number): PersistencePromise; + /** Returns the nth sequence number, counting in order from the smallest. */ + nthSequenceNumber(txn: PersistenceTransaction, n: number): PersistencePromise; + /** + * Removes documents that have a sequence number equal to or less than the + * upper bound and are not otherwise pinned. + */ + removeOrphanedDocuments(txn: PersistenceTransaction, upperBound: ListenSequenceNumber): PersistencePromise; + getCacheSize(txn: PersistenceTransaction): PersistencePromise; + /** + * Removes targets with a sequence number equal to or less than the given + * upper bound, and removes document associations with those targets. + */ + removeTargets(txn: PersistenceTransaction, upperBound: ListenSequenceNumber, activeTargetIds: ActiveTargets): PersistencePromise; +} +/** + * Describes the results of a garbage collection run. `didRun` will be set to + * `false` if collection was skipped (either it is disabled or the cache size + * has not hit the threshold). If collection ran, the other fields will be + * filled in with the details of the results. + */ +export interface LruResults { + readonly didRun: boolean; + readonly sequenceNumbersCollected: number; + readonly targetsRemoved: number; + readonly documentsRemoved: number; +} +/** + * Persistence layers intending to use LRU Garbage collection should have + * reference delegates that implement this interface. This interface defines the + * operations that the LRU garbage collector needs from the persistence layer. + */ +export interface LruDelegate { + readonly garbageCollector: LruGarbageCollector; + /** Enumerates all the targets in the TargetCache. */ + forEachTarget(txn: PersistenceTransaction, f: (target: TargetData) => void): PersistencePromise; + getSequenceNumberCount(txn: PersistenceTransaction): PersistencePromise; + /** + * Enumerates sequence numbers for documents not associated with a target. + * Note that this may include duplicate sequence numbers. + */ + forEachOrphanedDocumentSequenceNumber(txn: PersistenceTransaction, f: (sequenceNumber: ListenSequenceNumber) => void): PersistencePromise; + /** + * Removes all targets that have a sequence number less than or equal to + * `upperBound`, and are not present in the `activeTargetIds` set. + * + * @returns the number of targets removed. + */ + removeTargets(txn: PersistenceTransaction, upperBound: ListenSequenceNumber, activeTargetIds: ActiveTargets): PersistencePromise; + /** + * Removes all unreferenced documents from the cache that have a sequence + * number less than or equal to the given `upperBound`. + * + * @returns the number of documents removed. + */ + removeOrphanedDocuments(txn: PersistenceTransaction, upperBound: ListenSequenceNumber): PersistencePromise; + getCacheSize(txn: PersistenceTransaction): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/lru_garbage_collector_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/lru_garbage_collector_impl.d.ts new file mode 100644 index 0000000..f4ab1a5 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/lru_garbage_collector_impl.d.ts @@ -0,0 +1,37 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AsyncQueue } from '../util/async_queue'; +import { LocalStore } from './local_store'; +import { LruDelegate, LruGarbageCollector, LruParams } from './lru_garbage_collector'; +import { Scheduler } from './persistence'; +export declare const LRU_MINIMUM_CACHE_SIZE_BYTES: number; +/** + * This class is responsible for the scheduling of LRU garbage collection. It handles checking + * whether or not GC is enabled, as well as which delay to use before the next run. + */ +export declare class LruScheduler implements Scheduler { + private readonly garbageCollector; + private readonly asyncQueue; + private readonly localStore; + private gcTask; + constructor(garbageCollector: LruGarbageCollector, asyncQueue: AsyncQueue, localStore: LocalStore); + start(): void; + stop(): void; + get started(): boolean; + private scheduleGC; +} +export declare function newLruGarbageCollector(delegate: LruDelegate, params: LruParams): LruGarbageCollector; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_bundle_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_bundle_cache.d.ts new file mode 100644 index 0000000..972d4fc --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_bundle_cache.d.ts @@ -0,0 +1,32 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BundleMetadata, NamedQuery } from '../core/bundle'; +import { NamedQuery as ProtoNamedQuery, BundleMetadata as ProtoBundleMetadata } from '../protos/firestore_bundle_proto'; +import { BundleCache } from './bundle_cache'; +import { LocalSerializer } from './local_serializer'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +export declare class MemoryBundleCache implements BundleCache { + private serializer; + private bundles; + private namedQueries; + constructor(serializer: LocalSerializer); + getBundleMetadata(transaction: PersistenceTransaction, bundleId: string): PersistencePromise; + saveBundleMetadata(transaction: PersistenceTransaction, bundleMetadata: ProtoBundleMetadata): PersistencePromise; + getNamedQuery(transaction: PersistenceTransaction, queryName: string): PersistencePromise; + saveNamedQuery(transaction: PersistenceTransaction, query: ProtoNamedQuery): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_document_overlay_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_document_overlay_cache.d.ts new file mode 100644 index 0000000..b6ee945 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_document_overlay_cache.d.ts @@ -0,0 +1,37 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentKeySet, MutationMap, OverlayMap } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { Overlay } from '../model/overlay'; +import { ResourcePath } from '../model/path'; +import { DocumentOverlayCache } from './document_overlay_cache'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** + * An in-memory implementation of DocumentOverlayCache. + */ +export declare class MemoryDocumentOverlayCache implements DocumentOverlayCache { + private overlays; + private overlayByBatchId; + getOverlay(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; + getOverlays(transaction: PersistenceTransaction, keys: DocumentKey[]): PersistencePromise; + saveOverlays(transaction: PersistenceTransaction, largestBatchId: number, overlays: MutationMap): PersistencePromise; + removeOverlaysForBatchId(transaction: PersistenceTransaction, documentKeys: DocumentKeySet, batchId: number): PersistencePromise; + getOverlaysForCollection(transaction: PersistenceTransaction, collection: ResourcePath, sinceBatchId: number): PersistencePromise; + getOverlaysForCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, sinceBatchId: number, count: number): PersistencePromise; + private saveOverlay; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_globals_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_globals_cache.d.ts new file mode 100644 index 0000000..9877c67 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_globals_cache.d.ts @@ -0,0 +1,25 @@ +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ByteString } from '../util/byte_string'; +import { GlobalsCache } from './globals_cache'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +export declare class MemoryGlobalsCache implements GlobalsCache { + private sessionToken; + getSessionToken(transaction: PersistenceTransaction): PersistencePromise; + setSessionToken(transaction: PersistenceTransaction, sessionToken: ByteString): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_index_manager.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_index_manager.d.ts new file mode 100644 index 0000000..14ffd3d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_index_manager.d.ts @@ -0,0 +1,55 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Target } from '../core/target'; +import { DocumentMap } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { FieldIndex, IndexOffset } from '../model/field_index'; +import { ResourcePath } from '../model/path'; +import { IndexManager, IndexType } from './index_manager'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** + * An in-memory implementation of IndexManager. + */ +export declare class MemoryIndexManager implements IndexManager { + private collectionParentIndex; + addToCollectionParentIndex(transaction: PersistenceTransaction, collectionPath: ResourcePath): PersistencePromise; + getCollectionParents(transaction: PersistenceTransaction, collectionId: string): PersistencePromise; + addFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + deleteFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + deleteAllFieldIndexes(transaction: PersistenceTransaction): PersistencePromise; + createTargetIndexes(transaction: PersistenceTransaction, target: Target): PersistencePromise; + getDocumentsMatchingTarget(transaction: PersistenceTransaction, target: Target): PersistencePromise; + getIndexType(transaction: PersistenceTransaction, target: Target): PersistencePromise; + getFieldIndexes(transaction: PersistenceTransaction, collectionGroup?: string): PersistencePromise; + getNextCollectionGroupToUpdate(transaction: PersistenceTransaction): PersistencePromise; + getMinOffset(transaction: PersistenceTransaction, target: Target): PersistencePromise; + getMinOffsetFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise; + updateCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset): PersistencePromise; + updateIndexEntries(transaction: PersistenceTransaction, documents: DocumentMap): PersistencePromise; +} +/** + * Internal implementation of the collection-parent index exposed by MemoryIndexManager. + * Also used for in-memory caching by IndexedDbIndexManager and initial index population + * in indexeddb_schema.ts + */ +export declare class MemoryCollectionParentIndex { + private index; + add(collectionPath: ResourcePath): boolean; + has(collectionPath: ResourcePath): boolean; + getEntries(collectionId: string): ResourcePath[]; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_mutation_queue.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_mutation_queue.d.ts new file mode 100644 index 0000000..ad685f9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_mutation_queue.d.ts @@ -0,0 +1,80 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Query } from '../core/query'; +import { BatchId } from '../core/types'; +import { Timestamp } from '../lite-api/timestamp'; +import { DocumentKey } from '../model/document_key'; +import { Mutation } from '../model/mutation'; +import { MutationBatch } from '../model/mutation_batch'; +import { SortedMap } from '../util/sorted_map'; +import { IndexManager } from './index_manager'; +import { MutationQueue } from './mutation_queue'; +import { ReferenceDelegate } from './persistence'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +export declare class MemoryMutationQueue implements MutationQueue { + private readonly indexManager; + private readonly referenceDelegate; + /** + * The set of all mutations that have been sent but not yet been applied to + * the backend. + */ + private mutationQueue; + /** Next value to use when assigning sequential IDs to each mutation batch. */ + private nextBatchId; + /** An ordered mapping between documents and the mutations batch IDs. */ + private batchesByDocumentKey; + constructor(indexManager: IndexManager, referenceDelegate: ReferenceDelegate); + checkEmpty(transaction: PersistenceTransaction): PersistencePromise; + addMutationBatch(transaction: PersistenceTransaction, localWriteTime: Timestamp, baseMutations: Mutation[], mutations: Mutation[]): PersistencePromise; + lookupMutationBatch(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + getNextMutationBatchAfterBatchId(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + getHighestUnacknowledgedBatchId(): PersistencePromise; + getAllMutationBatches(transaction: PersistenceTransaction): PersistencePromise; + getAllMutationBatchesAffectingDocumentKey(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + getAllMutationBatchesAffectingDocumentKeys(transaction: PersistenceTransaction, documentKeys: SortedMap): PersistencePromise; + getAllMutationBatchesAffectingQuery(transaction: PersistenceTransaction, query: Query): PersistencePromise; + private findMutationBatches; + removeMutationBatch(transaction: PersistenceTransaction, batch: MutationBatch): PersistencePromise; + removeCachedMutationKeys(batchId: BatchId): void; + containsKey(txn: PersistenceTransaction, key: DocumentKey): PersistencePromise; + performConsistencyCheck(txn: PersistenceTransaction): PersistencePromise; + /** + * Finds the index of the given batchId in the mutation queue and asserts that + * the resulting index is within the bounds of the queue. + * + * @param batchId - The batchId to search for + * @param action - A description of what the caller is doing, phrased in passive + * form (e.g. "acknowledged" in a routine that acknowledges batches). + */ + private indexOfExistingBatchId; + /** + * Finds the index of the given batchId in the mutation queue. This operation + * is O(1). + * + * @returns The computed index of the batch with the given batchId, based on + * the state of the queue. Note this index can be negative if the requested + * batchId has already been removed from the queue or past the end of the + * queue if the batchId is larger than the last added batch. + */ + private indexOfBatchId; + /** + * A version of lookupMutationBatch that doesn't return a promise, this makes + * other functions that uses this code easier to read and more efficient. + */ + private findMutationBatch; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_persistence.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_persistence.d.ts new file mode 100644 index 0000000..051c94b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_persistence.d.ts @@ -0,0 +1,134 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { ListenSequenceNumber, TargetId } from '../core/types'; +import { Document } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { JsonProtoSerializer } from '../remote/serializer'; +import { DocumentOverlayCache } from './document_overlay_cache'; +import { GlobalsCache } from './globals_cache'; +import { IndexManager } from './index_manager'; +import { ActiveTargets, LruDelegate, LruGarbageCollector, LruParams } from './lru_garbage_collector'; +import { MemoryBundleCache } from './memory_bundle_cache'; +import { MemoryIndexManager } from './memory_index_manager'; +import { MemoryRemoteDocumentCache } from './memory_remote_document_cache'; +import { MemoryTargetCache } from './memory_target_cache'; +import { MutationQueue } from './mutation_queue'; +import { Persistence, ReferenceDelegate } from './persistence'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction, PersistenceTransactionMode } from './persistence_transaction'; +import { TargetData } from './target_data'; +/** + * A memory-backed instance of Persistence. Data is stored only in RAM and + * not persisted across sessions. + */ +export declare class MemoryPersistence implements Persistence { + /** + * Note that these are retained here to make it easier to write tests + * affecting both the in-memory and IndexedDB-backed persistence layers. Tests + * can create a new LocalStore wrapping this Persistence instance and this + * will make the in-memory persistence layer behave as if it were actually + * persisting values. + */ + private readonly indexManager; + private readonly globalsCache; + private mutationQueues; + private overlays; + private readonly remoteDocumentCache; + private readonly targetCache; + private readonly bundleCache; + private readonly listenSequence; + private serializer; + private _started; + readonly referenceDelegate: MemoryReferenceDelegate; + /** + * The constructor accepts a factory for creating a reference delegate. This + * allows both the delegate and this instance to have strong references to + * each other without having nullable fields that would then need to be + * checked or asserted on every access. + */ + constructor(referenceDelegateFactory: (p: MemoryPersistence) => MemoryReferenceDelegate, serializer: JsonProtoSerializer); + start(): Promise; + shutdown(): Promise; + get started(): boolean; + setDatabaseDeletedListener(): void; + setNetworkEnabled(): void; + getIndexManager(user: User): MemoryIndexManager; + getDocumentOverlayCache(user: User): DocumentOverlayCache; + getMutationQueue(user: User, indexManager: IndexManager): MutationQueue; + getGlobalsCache(): GlobalsCache; + getTargetCache(): MemoryTargetCache; + getRemoteDocumentCache(): MemoryRemoteDocumentCache; + getBundleCache(): MemoryBundleCache; + runTransaction(action: string, mode: PersistenceTransactionMode, transactionOperation: (transaction: PersistenceTransaction) => PersistencePromise): Promise; + mutationQueuesContainKey(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; +} +/** + * Memory persistence is not actually transactional, but future implementations + * may have transaction-scoped state. + */ +export declare class MemoryTransaction extends PersistenceTransaction { + readonly currentSequenceNumber: ListenSequenceNumber; + constructor(currentSequenceNumber: ListenSequenceNumber); +} +export interface MemoryReferenceDelegate extends ReferenceDelegate { + documentSize(doc: Document): number; + onTransactionStarted(): void; + onTransactionCommitted(txn: PersistenceTransaction): PersistencePromise; +} +export declare class MemoryEagerDelegate implements MemoryReferenceDelegate { + private readonly persistence; + /** Tracks all documents that are active in Query views. */ + private localViewReferences; + /** The list of documents that are potentially GCed after each transaction. */ + private _orphanedDocuments; + private constructor(); + static factory(persistence: MemoryPersistence): MemoryEagerDelegate; + private get orphanedDocuments(); + addReference(txn: PersistenceTransaction, targetId: TargetId, key: DocumentKey): PersistencePromise; + removeReference(txn: PersistenceTransaction, targetId: TargetId, key: DocumentKey): PersistencePromise; + markPotentiallyOrphaned(txn: PersistenceTransaction, key: DocumentKey): PersistencePromise; + removeTarget(txn: PersistenceTransaction, targetData: TargetData): PersistencePromise; + onTransactionStarted(): void; + onTransactionCommitted(txn: PersistenceTransaction): PersistencePromise; + updateLimboDocument(txn: PersistenceTransaction, key: DocumentKey): PersistencePromise; + documentSize(doc: Document): number; + private isReferenced; +} +export declare class MemoryLruDelegate implements ReferenceDelegate, LruDelegate { + private readonly persistence; + private orphanedSequenceNumbers; + readonly garbageCollector: LruGarbageCollector; + constructor(persistence: MemoryPersistence, lruParams: LruParams); + static factory(persistence: MemoryPersistence, lruParams: LruParams): MemoryLruDelegate; + onTransactionStarted(): void; + onTransactionCommitted(txn: PersistenceTransaction): PersistencePromise; + forEachTarget(txn: PersistenceTransaction, f: (q: TargetData) => void): PersistencePromise; + getSequenceNumberCount(txn: PersistenceTransaction): PersistencePromise; + private orphanedDocumentCount; + forEachOrphanedDocumentSequenceNumber(txn: PersistenceTransaction, f: (sequenceNumber: ListenSequenceNumber) => void): PersistencePromise; + removeTargets(txn: PersistenceTransaction, upperBound: ListenSequenceNumber, activeTargetIds: ActiveTargets): PersistencePromise; + removeOrphanedDocuments(txn: PersistenceTransaction, upperBound: ListenSequenceNumber): PersistencePromise; + markPotentiallyOrphaned(txn: PersistenceTransaction, key: DocumentKey): PersistencePromise; + removeTarget(txn: PersistenceTransaction, targetData: TargetData): PersistencePromise; + addReference(txn: PersistenceTransaction, targetId: TargetId, key: DocumentKey): PersistencePromise; + removeReference(txn: PersistenceTransaction, targetId: TargetId, key: DocumentKey): PersistencePromise; + updateLimboDocument(txn: PersistenceTransaction, key: DocumentKey): PersistencePromise; + documentSize(document: Document): number; + private isPinned; + getCacheSize(txn: PersistenceTransaction): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_remote_document_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_remote_document_cache.d.ts new file mode 100644 index 0000000..7752914 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_remote_document_cache.d.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Document } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +import { RemoteDocumentCache } from './remote_document_cache'; +export type DocumentSizer = (doc: Document) => number; +export interface MemoryRemoteDocumentCache extends RemoteDocumentCache { + forEachDocumentKey(transaction: PersistenceTransaction, f: (key: DocumentKey) => PersistencePromise): PersistencePromise; +} +/** + * Creates a new memory-only RemoteDocumentCache. + * + * @param sizer - Used to assess the size of a document. For eager GC, this is + * expected to just return 0 to avoid unnecessarily doing the work of + * calculating the size. + */ +export declare function newMemoryRemoteDocumentCache(sizer: DocumentSizer): MemoryRemoteDocumentCache; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_target_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_target_cache.d.ts new file mode 100644 index 0000000..4539d62 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/memory_target_cache.d.ts @@ -0,0 +1,65 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { Target } from '../core/target'; +import { ListenSequenceNumber, TargetId } from '../core/types'; +import { DocumentKeySet } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { ActiveTargets } from './lru_garbage_collector'; +import { Persistence } from './persistence'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +import { TargetCache } from './target_cache'; +import { TargetData } from './target_data'; +export declare class MemoryTargetCache implements TargetCache { + private readonly persistence; + /** + * Maps a target to the data about that target + */ + private targets; + /** The last received snapshot version. */ + private lastRemoteSnapshotVersion; + /** The highest numbered target ID encountered. */ + private highestTargetId; + /** The highest sequence number encountered. */ + private highestSequenceNumber; + /** + * A ordered bidirectional mapping between documents and the remote target + * IDs. + */ + private references; + private targetCount; + private targetIdGenerator; + constructor(persistence: Persistence); + forEachTarget(txn: PersistenceTransaction, f: (q: TargetData) => void): PersistencePromise; + getLastRemoteSnapshotVersion(transaction: PersistenceTransaction): PersistencePromise; + getHighestSequenceNumber(transaction: PersistenceTransaction): PersistencePromise; + allocateTargetId(transaction: PersistenceTransaction): PersistencePromise; + setTargetsMetadata(transaction: PersistenceTransaction, highestListenSequenceNumber: number, lastRemoteSnapshotVersion?: SnapshotVersion): PersistencePromise; + private saveTargetData; + addTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + updateTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + removeTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + removeTargets(transaction: PersistenceTransaction, upperBound: ListenSequenceNumber, activeTargetIds: ActiveTargets): PersistencePromise; + getTargetCount(transaction: PersistenceTransaction): PersistencePromise; + getTargetData(transaction: PersistenceTransaction, target: Target): PersistencePromise; + addMatchingKeys(txn: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + removeMatchingKeys(txn: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + removeMatchingKeysForTargetId(txn: PersistenceTransaction, targetId: TargetId): PersistencePromise; + getMatchingKeysForTargetId(txn: PersistenceTransaction, targetId: TargetId): PersistencePromise; + containsKey(txn: PersistenceTransaction, key: DocumentKey): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/mutation_queue.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/mutation_queue.d.ts new file mode 100644 index 0000000..2f7b2dd --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/mutation_queue.d.ts @@ -0,0 +1,123 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Query } from '../core/query'; +import { BatchId } from '../core/types'; +import { Timestamp } from '../lite-api/timestamp'; +import { DocumentKey } from '../model/document_key'; +import { Mutation } from '../model/mutation'; +import { MutationBatch } from '../model/mutation_batch'; +import { SortedMap } from '../util/sorted_map'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** A queue of mutations to apply to the remote store. */ +export interface MutationQueue { + /** Returns true if this queue contains no mutation batches. */ + checkEmpty(transaction: PersistenceTransaction): PersistencePromise; + /** + * Creates a new mutation batch and adds it to this mutation queue. + * + * @param transaction - The transaction this operation is scoped to. + * @param localWriteTime - The original write time of this mutation. + * @param baseMutations - Mutations that are used to populate the base values + * when this mutation is applied locally. These mutations are used to locally + * overwrite values that are persisted in the remote document cache. + * @param mutations - The user-provided mutations in this mutation batch. + */ + addMutationBatch(transaction: PersistenceTransaction, localWriteTime: Timestamp, baseMutations: Mutation[], mutations: Mutation[]): PersistencePromise; + /** + * Loads the mutation batch with the given batchId. + */ + lookupMutationBatch(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + /** + * Gets the first unacknowledged mutation batch after the passed in batchId + * in the mutation queue or null if empty. + * + * @param batchId - The batch to search after, or BATCHID_UNKNOWN for the + * first mutation in the queue. + * + * @returns the next mutation or null if there wasn't one. + */ + getNextMutationBatchAfterBatchId(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + /** + * Gets the largest (latest) batch id in mutation queue for the current user + * that is pending server response, returns `BATCHID_UNKNOWN` if the queue is + * empty. + * + * @returns the largest batch id in the mutation queue that is not + * acknowledged. + */ + getHighestUnacknowledgedBatchId(transaction: PersistenceTransaction): PersistencePromise; + /** Gets all mutation batches in the mutation queue. */ + getAllMutationBatches(transaction: PersistenceTransaction): PersistencePromise; + /** + * Finds all mutation batches that could possibly affect the given + * document key. Not all mutations in a batch will necessarily affect the + * document key, so when looping through the batch you'll need to check that + * the mutation itself matches the key. + * + * Batches are guaranteed to be in sorted order. + * + * Note that because of this requirement implementations are free to return + * mutation batches that don't contain the document key at all if it's + * convenient. + */ + getAllMutationBatchesAffectingDocumentKey(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + /** + * Finds all mutation batches that could possibly affect the given set of + * document keys. Not all mutations in a batch will necessarily affect each + * key, so when looping through the batch you'll need to check that the + * mutation itself matches the key. + * + * Batches are guaranteed to be in sorted order. + * + * Note that because of this requirement implementations are free to return + * mutation batches that don't contain any of the document keys at all if it's + * convenient. + */ + getAllMutationBatchesAffectingDocumentKeys(transaction: PersistenceTransaction, documentKeys: SortedMap): PersistencePromise; + /** + * Finds all mutation batches that could affect the results for the given + * query. Not all mutations in a batch will necessarily affect the query, so + * when looping through the batch you'll need to check that the mutation + * itself matches the query. + * + * Batches are guaranteed to be in sorted order. + * + * Note that because of this requirement implementations are free to return + * mutation batches that don't match the query at all if it's convenient. + * + * NOTE: A PatchMutation does not need to include all fields in the query + * filter criteria in order to be a match (but any fields it does contain do + * need to match). + */ + getAllMutationBatchesAffectingQuery(transaction: PersistenceTransaction, query: Query): PersistencePromise; + /** + * Removes the given mutation batch from the queue. This is useful in two + * circumstances: + * + * + Removing an applied mutation from the head of the queue + * + Removing a rejected mutation from anywhere in the queue + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMutationBatch(transaction: PersistenceTransaction, batch: MutationBatch): PersistencePromise; + /** + * Performs a consistency check, examining the mutation queue for any + * leaks, if possible. + */ + performConsistencyCheck(transaction: PersistenceTransaction): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/overlayed_document.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/overlayed_document.d.ts new file mode 100644 index 0000000..56a3286 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/overlayed_document.d.ts @@ -0,0 +1,40 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Document } from '../model/document'; +import { FieldMask } from '../model/field_mask'; +/** + * Represents a local view (overlay) of a document, and the fields that are + * locally mutated. + */ +export declare class OverlayedDocument { + readonly overlayedDocument: Document; + /** + * The fields that are locally mutated by patch mutations. + * + * If the overlayed document is from set or delete mutations, this is `null`. + * If there is no overlay (mutation) for the document, this is an empty `FieldMask`. + */ + readonly mutatedFields: FieldMask | null; + constructor(overlayedDocument: Document, + /** + * The fields that are locally mutated by patch mutations. + * + * If the overlayed document is from set or delete mutations, this is `null`. + * If there is no overlay (mutation) for the document, this is an empty `FieldMask`. + */ + mutatedFields: FieldMask | null); +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/persistence.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/persistence.d.ts new file mode 100644 index 0000000..0360173 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/persistence.d.ts @@ -0,0 +1,217 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { TargetId } from '../core/types'; +import { DocumentKey } from '../model/document_key'; +import { BundleCache } from './bundle_cache'; +import { DocumentOverlayCache } from './document_overlay_cache'; +import { GlobalsCache } from './globals_cache'; +import { IndexManager } from './index_manager'; +import { MutationQueue } from './mutation_queue'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction, PersistenceTransactionMode } from './persistence_transaction'; +import { RemoteDocumentCache } from './remote_document_cache'; +import { TargetCache } from './target_cache'; +import { TargetData } from './target_data'; +/** + * Callback type for primary state notifications. This callback can be + * registered with the persistence layer to get notified when we transition from + * primary to secondary state and vice versa. + * + * Note: Instances can only toggle between Primary and Secondary state if + * IndexedDB persistence is enabled and multiple clients are active. If this + * listener is registered with MemoryPersistence, the callback will be called + * exactly once marking the current instance as Primary. + */ +export type PrimaryStateListener = (isPrimary: boolean) => Promise; +/** + * A ReferenceDelegate instance handles all of the hooks into the document-reference lifecycle. This + * includes being added to a target, being removed from a target, being subject to mutation, and + * being mutated by the user. + * + * Different implementations may do different things with each of these events. Not every + * implementation needs to do something with every lifecycle hook. + * + * PORTING NOTE: since sequence numbers are attached to transactions in this + * client, the ReferenceDelegate does not need to deal in transactional + * semantics (onTransactionStarted/Committed()), nor does it need to track and + * generate sequence numbers (getCurrentSequenceNumber()). + */ +export interface ReferenceDelegate { + /** Notify the delegate that the given document was added to a target. */ + addReference(txn: PersistenceTransaction, targetId: TargetId, doc: DocumentKey): PersistencePromise; + /** Notify the delegate that the given document was removed from a target. */ + removeReference(txn: PersistenceTransaction, targetId: TargetId, doc: DocumentKey): PersistencePromise; + /** + * Notify the delegate that a target was removed. The delegate may, but is not obligated to, + * actually delete the target and associated data. + */ + removeTarget(txn: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Notify the delegate that a document may no longer be part of any views or + * have any mutations associated. + */ + markPotentiallyOrphaned(txn: PersistenceTransaction, doc: DocumentKey): PersistencePromise; + /** Notify the delegate that a limbo document was updated. */ + updateLimboDocument(txn: PersistenceTransaction, doc: DocumentKey): PersistencePromise; +} +/** + * Persistence is the lowest-level shared interface to persistent storage in + * Firestore. + * + * Persistence is used to create MutationQueue and RemoteDocumentCache + * instances backed by persistence (which might be in-memory or LevelDB). + * + * Persistence also exposes an API to create and run PersistenceTransactions + * against persistence. All read / write operations must be wrapped in a + * transaction. Implementations of PersistenceTransaction / Persistence only + * need to guarantee that writes made against the transaction are not made to + * durable storage until the transaction resolves its PersistencePromise. + * Since memory-only storage components do not alter durable storage, they are + * free to ignore the transaction. + * + * This contract is enough to allow the LocalStore be be written + * independently of whether or not the stored state actually is durably + * persisted. If persistent storage is enabled, writes are grouped together to + * avoid inconsistent state that could cause crashes. + * + * Concretely, when persistent storage is enabled, the persistent versions of + * MutationQueue, RemoteDocumentCache, and others (the mutators) will + * defer their writes into a transaction. Once the local store has completed + * one logical operation, it commits the transaction. + * + * When persistent storage is disabled, the non-persistent versions of the + * mutators ignore the transaction. This short-cut is allowed because + * memory-only storage leaves no state so it cannot be inconsistent. + * + * This simplifies the implementations of the mutators and allows memory-only + * implementations to supplement the persistent ones without requiring any + * special dual-store implementation of Persistence. The cost is that the + * LocalStore needs to be slightly careful about the order of its reads and + * writes in order to avoid relying on being able to read back uncommitted + * writes. + */ +export interface Persistence { + /** + * Whether or not this persistence instance has been started. + */ + readonly started: boolean; + readonly referenceDelegate: ReferenceDelegate; + /** Starts persistence. */ + start(): Promise; + /** + * Releases any resources held during eager shutdown. + */ + shutdown(): Promise; + /** + * Registers a listener that gets called when the database receives a + * version change event indicating that it has deleted. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setDatabaseDeletedListener(databaseDeletedListener: () => Promise): void; + /** + * Adjusts the current network state in the client's metadata, potentially + * affecting the primary lease. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setNetworkEnabled(networkEnabled: boolean): void; + /** + * Returns GlobalCache representing a general purpose cache for global values. + */ + getGlobalsCache(): GlobalsCache; + /** + * Returns a MutationQueue representing the persisted mutations for the + * given user. + * + * Note: The implementation is free to return the same instance every time + * this is called for a given user. In particular, the memory-backed + * implementation does this to emulate the persisted implementation to the + * extent possible (e.g. in the case of uid switching from + * sally=>jack=>sally, sally's mutation queue will be preserved). + */ + getMutationQueue(user: User, indexManager: IndexManager): MutationQueue; + /** + * Returns a TargetCache representing the persisted cache of targets. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getTargetCache(): TargetCache; + /** + * Returns a RemoteDocumentCache representing the persisted cache of remote + * documents. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getRemoteDocumentCache(): RemoteDocumentCache; + /** + * Returns a BundleCache representing the persisted cache of loaded bundles. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getBundleCache(): BundleCache; + /** + * Returns an IndexManager instance that manages our persisted query indexes. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getIndexManager(user: User): IndexManager; + /** + * Returns a DocumentOverlayCache representing the documents that are mutated + * locally. + */ + getDocumentOverlayCache(user: User): DocumentOverlayCache; + /** + * Performs an operation inside a persistence transaction. Any reads or writes + * against persistence must be performed within a transaction. Writes will be + * committed atomically once the transaction completes. + * + * Persistence operations are asynchronous and therefore the provided + * transactionOperation must return a PersistencePromise. When it is resolved, + * the transaction will be committed and the Promise returned by this method + * will resolve. + * + * @param action - A description of the action performed by this transaction, + * used for logging. + * @param mode - The underlying mode of the IndexedDb transaction. Can be + * 'readonly', 'readwrite' or 'readwrite-primary'. Transactions marked + * 'readwrite-primary' can only be executed by the primary client. In this + * mode, the transactionOperation will not be run if the primary lease cannot + * be acquired and the returned promise will be rejected with a + * FAILED_PRECONDITION error. + * @param transactionOperation - The operation to run inside a transaction. + * @returns A `Promise` that is resolved once the transaction completes. + */ + runTransaction(action: string, mode: PersistenceTransactionMode, transactionOperation: (transaction: PersistenceTransaction) => PersistencePromise): Promise; +} +/** + * Interface to schedule periodic tasks within SDK. + */ +export interface Scheduler { + readonly started: boolean; + start(): void; + stop(): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/persistence_promise.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/persistence_promise.d.ts new file mode 100644 index 0000000..3803123 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/persistence_promise.d.ts @@ -0,0 +1,83 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export type FulfilledHandler = ((result: T) => R | PersistencePromise) | null; +export type RejectedHandler = ((reason: Error) => R | PersistencePromise) | null; +export type Resolver = (value?: T) => void; +export type Rejector = (error: Error) => void; +/** + * PersistencePromise is essentially a re-implementation of Promise except + * it has a .next() method instead of .then() and .next() and .catch() callbacks + * are executed synchronously when a PersistencePromise resolves rather than + * asynchronously (Promise implementations use setImmediate() or similar). + * + * This is necessary to interoperate with IndexedDB which will automatically + * commit transactions if control is returned to the event loop without + * synchronously initiating another operation on the transaction. + * + * NOTE: .then() and .catch() only allow a single consumer, unlike normal + * Promises. + */ +export declare class PersistencePromise { + private nextCallback; + private catchCallback; + private result; + private error; + private isDone; + private callbackAttached; + constructor(callback: (resolve: Resolver, reject: Rejector) => void); + catch(fn: (error: Error) => R | PersistencePromise): PersistencePromise; + next(nextFn?: FulfilledHandler, catchFn?: RejectedHandler): PersistencePromise; + toPromise(): Promise; + private wrapUserFunction; + private wrapSuccess; + private wrapFailure; + static resolve(): PersistencePromise; + static resolve(result: R): PersistencePromise; + static reject(error: Error): PersistencePromise; + static waitFor(all: { + forEach: (cb: (el: PersistencePromise) => void) => void; + }): PersistencePromise; + /** + * Given an array of predicate functions that asynchronously evaluate to a + * boolean, implements a short-circuiting `or` between the results. Predicates + * will be evaluated until one of them returns `true`, then stop. The final + * result will be whether any of them returned `true`. + */ + static or(predicates: Array<() => PersistencePromise>): PersistencePromise; + /** + * Given an iterable, call the given function on each element in the + * collection and wait for all of the resulting concurrent PersistencePromises + * to resolve. + */ + static forEach(collection: { + forEach: (cb: (r: R, s: S) => void) => void; + }, f: ((r: R, s: S) => PersistencePromise) | ((r: R) => PersistencePromise)): PersistencePromise; + static forEach(collection: { + forEach: (cb: (r: R) => void) => void; + }, f: (r: R) => PersistencePromise): PersistencePromise; + /** + * Concurrently map all array elements through asynchronous function. + */ + static mapArray(array: T[], f: (t: T) => PersistencePromise): PersistencePromise; + /** + * An alternative to recursive PersistencePromise calls, that avoids + * potential memory problems from unbounded chains of promises. + * + * The `action` will be called repeatedly while `condition` is true. + */ + static doWhile(condition: () => boolean, action: () => PersistencePromise): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/persistence_transaction.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/persistence_transaction.d.ts new file mode 100644 index 0000000..d4da8b6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/persistence_transaction.d.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ListenSequenceNumber } from '../core/types'; +export declare const PRIMARY_LEASE_LOST_ERROR_MSG: string; +/** The different modes supported by `Persistence.runTransaction()`. */ +export type PersistenceTransactionMode = 'readonly' | 'readwrite' | 'readwrite-primary'; +/** + * A base class representing a persistence transaction, encapsulating both the + * transaction's sequence numbers as well as a list of onCommitted listeners. + * + * When you call Persistence.runTransaction(), it will create a transaction and + * pass it to your callback. You then pass it to any method that operates + * on persistence. + */ +export declare abstract class PersistenceTransaction { + private readonly onCommittedListeners; + abstract readonly currentSequenceNumber: ListenSequenceNumber; + addOnCommittedListener(listener: () => void): void; + raiseOnCommittedEvent(): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/query_context.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/query_context.d.ts new file mode 100644 index 0000000..aeff2fa --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/query_context.d.ts @@ -0,0 +1,28 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A tracker to keep a record of important details during database local query + * execution. + */ +export declare class QueryContext { + /** + * Counts the number of documents passed through during local query execution. + */ + private _documentReadCount; + get documentReadCount(): number; + incrementDocumentReadCount(amount: number): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/query_engine.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/query_engine.d.ts new file mode 100644 index 0000000..58148f1 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/query_engine.d.ts @@ -0,0 +1,110 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Query } from '../core/query'; +import { SnapshotVersion } from '../core/snapshot_version'; +import { DocumentKeySet, DocumentMap } from '../model/collections'; +import { IndexManager } from './index_manager'; +import { LocalDocumentsView } from './local_documents_view'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +import { QueryContext } from './query_context'; +/** + * The Firestore query engine. + * + * Firestore queries can be executed in three modes. The Query Engine determines + * what mode to use based on what data is persisted. The mode only determines + * the runtime complexity of the query - the result set is equivalent across all + * implementations. + * + * The Query engine will use indexed-based execution if a user has configured + * any index that can be used to execute query (via `setIndexConfiguration()`). + * Otherwise, the engine will try to optimize the query by re-using a previously + * persisted query result. If that is not possible, the query will be executed + * via a full collection scan. + * + * Index-based execution is the default when available. The query engine + * supports partial indexed execution and merges the result from the index + * lookup with documents that have not yet been indexed. The index evaluation + * matches the backend's format and as such, the SDK can use indexing for all + * queries that the backend supports. + * + * If no index exists, the query engine tries to take advantage of the target + * document mapping in the TargetCache. These mappings exists for all queries + * that have been synced with the backend at least once and allow the query + * engine to only read documents that previously matched a query plus any + * documents that were edited after the query was last listened to. + * + * There are some cases when this optimization is not guaranteed to produce + * the same results as full collection scans. In these cases, query + * processing falls back to full scans. These cases are: + * + * - Limit queries where a document that matched the query previously no longer + * matches the query. + * + * - Limit queries where a document edit may cause the document to sort below + * another document that is in the local cache. + * + * - Queries that have never been CURRENT or free of limbo documents. + */ +export declare class QueryEngine { + private localDocumentsView; + private indexManager; + private initialized; + indexAutoCreationEnabled: boolean; + /** + * SDK only decides whether it should create index when collection size is + * larger than this. + */ + indexAutoCreationMinCollectionSize: number; + relativeIndexReadCostPerDocument: number; + /** Sets the document view to query against. */ + initialize(localDocuments: LocalDocumentsView, indexManager: IndexManager): void; + /** Returns all local documents matching the specified query. */ + getDocumentsMatchingQuery(transaction: PersistenceTransaction, query: Query, lastLimboFreeSnapshotVersion: SnapshotVersion, remoteKeys: DocumentKeySet): PersistencePromise; + createCacheIndexes(transaction: PersistenceTransaction, query: Query, context: QueryContext, resultSize: number): PersistencePromise; + /** + * Performs an indexed query that evaluates the query based on a collection's + * persisted index values. Returns `null` if an index is not available. + */ + private performQueryUsingIndex; + /** + * Performs a query based on the target's persisted query mapping. Returns + * `null` if the mapping is not available or cannot be used. + */ + private performQueryUsingRemoteKeys; + /** Applies the query filter and sorting to the provided documents. */ + private applyQuery; + /** + * Determines if a limit query needs to be refilled from cache, making it + * ineligible for index-free execution. + * + * @param query - The query. + * @param sortedPreviousResults - The documents that matched the query when it + * was last synchronized, sorted by the query's comparator. + * @param remoteKeys - The document keys that matched the query at the last + * snapshot. + * @param limboFreeSnapshotVersion - The version of the snapshot when the + * query was last synchronized. + */ + private needsRefill; + private executeFullCollectionScan; + /** + * Combines the results from an indexed execution with the remaining documents + * that have not yet been indexed. + */ + private appendRemainingResults; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/reference_set.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/reference_set.d.ts new file mode 100644 index 0000000..5ff71dc --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/reference_set.d.ts @@ -0,0 +1,68 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BatchId, TargetId } from '../core/types'; +import { DocumentKeySet } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +/** + * A collection of references to a document from some kind of numbered entity + * (either a target ID or batch ID). As references are added to or removed from + * the set corresponding events are emitted to a registered garbage collector. + * + * Each reference is represented by a DocumentReference object. Each of them + * contains enough information to uniquely identify the reference. They are all + * stored primarily in a set sorted by key. A document is considered garbage if + * there's no references in that set (this can be efficiently checked thanks to + * sorting by key). + * + * ReferenceSet also keeps a secondary set that contains references sorted by + * IDs. This one is used to efficiently implement removal of all references by + * some target ID. + */ +export declare class ReferenceSet { + private refsByKey; + private refsByTarget; + /** Returns true if the reference set contains no references. */ + isEmpty(): boolean; + /** Adds a reference to the given document key for the given ID. */ + addReference(key: DocumentKey, id: TargetId | BatchId): void; + /** Add references to the given document keys for the given ID. */ + addReferences(keys: DocumentKeySet, id: TargetId | BatchId): void; + /** + * Removes a reference to the given document key for the given + * ID. + */ + removeReference(key: DocumentKey, id: TargetId | BatchId): void; + removeReferences(keys: DocumentKeySet, id: TargetId | BatchId): void; + /** + * Clears all references with a given ID. Calls removeRef() for each key + * removed. + */ + removeReferencesForId(id: TargetId | BatchId): DocumentKey[]; + removeAllReferences(): void; + private removeRef; + referencesForId(id: TargetId | BatchId): DocumentKeySet; + containsKey(key: DocumentKey): boolean; +} +export declare class DocReference { + key: DocumentKey; + targetOrBatchId: TargetId | BatchId; + constructor(key: DocumentKey, targetOrBatchId: TargetId | BatchId); + /** Compare by key then by ID */ + static compareByKey(left: DocReference, right: DocReference): number; + /** Compare by ID then by key */ + static compareByTargetId(left: DocReference, right: DocReference): number; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/remote_document_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/remote_document_cache.d.ts new file mode 100644 index 0000000..abb9f3b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/remote_document_cache.d.ts @@ -0,0 +1,91 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Query } from '../core/query'; +import { DocumentKeySet, MutableDocumentMap, OverlayMap } from '../model/collections'; +import { MutableDocument } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { IndexOffset } from '../model/field_index'; +import { IndexManager } from './index_manager'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +import { QueryContext } from './query_context'; +import { RemoteDocumentChangeBuffer } from './remote_document_change_buffer'; +/** + * Represents cached documents received from the remote backend. + * + * The cache is keyed by DocumentKey and entries in the cache are + * MutableDocuments, meaning we can cache both actual documents as well as + * documents that are known to not exist. + */ +export interface RemoteDocumentCache { + /** Sets the index manager to use for managing the collectionGroup index. */ + setIndexManager(indexManager: IndexManager): void; + /** + * Looks up an entry in the cache. + * + * @param documentKey - The key of the entry to look up.* + * @returns The cached document entry. Returns an invalid document if the + * document is not cached. + */ + getEntry(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + /** + * Looks up a set of entries in the cache. + * + * @param documentKeys - The keys of the entries to look up. + * @returns The cached document entries indexed by key. If an entry is not + * cached, the corresponding key will be mapped to an invalid document. + */ + getEntries(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise; + /** + * Returns the documents matching the given query + * + * @param query - The query to match documents against. + * @param offset - The offset to start the scan at (exclusive). + * @param context - A optional tracker to keep a record of important details + * during database local query execution. + * @returns The set of matching documents. + */ + getDocumentsMatchingQuery(transaction: PersistenceTransaction, query: Query, offset: IndexOffset, mutatedDocs: OverlayMap, context?: QueryContext): PersistencePromise; + /** + * Looks up the next `limit` documents for a collection group based on the + * provided offset. The ordering is based on the document's read time and key. + * + * @param collectionGroup - The collection group to scan. + * @param offset - The offset to start the scan at (exclusive). + * @param limit - The maximum number of results to return. + * @returns The set of matching documents. + */ + getAllFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset, limit: number): PersistencePromise; + /** + * Provides access to add or update the contents of the cache. The buffer + * handles proper size accounting for the change. + * + * Multi-Tab Note: This should only be called by the primary client. + * + * @param options - Specify `trackRemovals` to create sentinel entries for + * removed documents, which allows removals to be tracked by + * `getNewDocumentChanges()`. + */ + newChangeBuffer(options?: { + trackRemovals: boolean; + }): RemoteDocumentChangeBuffer; + /** + * Get an estimate of the size of the document cache. Note that for eager + * garbage collection, we don't track sizes so this will return 0. + */ + getSize(transaction: PersistenceTransaction): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/remote_document_change_buffer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/remote_document_change_buffer.d.ts new file mode 100644 index 0000000..3b8a1fa --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/remote_document_change_buffer.d.ts @@ -0,0 +1,88 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { DocumentKeySet, MutableDocumentMap } from '../model/collections'; +import { MutableDocument } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { ObjectMap } from '../util/obj_map'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** + * An in-memory buffer of entries to be written to a RemoteDocumentCache. + * It can be used to batch up a set of changes to be written to the cache, but + * additionally supports reading entries back with the `getEntry()` method, + * falling back to the underlying RemoteDocumentCache if no entry is + * buffered. + * + * Entries added to the cache *must* be read first. This is to facilitate + * calculating the size delta of the pending changes. + * + * PORTING NOTE: This class was implemented then removed from other platforms. + * If byte-counting ends up being needed on the other platforms, consider + * porting this class as part of that implementation work. + */ +export declare abstract class RemoteDocumentChangeBuffer { + protected changes: ObjectMap; + private changesApplied; + protected abstract getFromCache(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + protected abstract getAllFromCache(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise; + protected abstract applyChanges(transaction: PersistenceTransaction): PersistencePromise; + /** + * Buffers a `RemoteDocumentCache.addEntry()` call. + * + * You can only modify documents that have already been retrieved via + * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). + */ + addEntry(document: MutableDocument): void; + /** + * Buffers a `RemoteDocumentCache.removeEntry()` call. + * + * You can only remove documents that have already been retrieved via + * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). + */ + removeEntry(key: DocumentKey, readTime: SnapshotVersion): void; + /** + * Looks up an entry in the cache. The buffered changes will first be checked, + * and if no buffered change applies, this will forward to + * `RemoteDocumentCache.getEntry()`. + * + * @param transaction - The transaction in which to perform any persistence + * operations. + * @param documentKey - The key of the entry to look up. + * @returns The cached document or an invalid document if we have nothing + * cached. + */ + getEntry(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + /** + * Looks up several entries in the cache, forwarding to + * `RemoteDocumentCache.getEntry()`. + * + * @param transaction - The transaction in which to perform any persistence + * operations. + * @param documentKeys - The keys of the entries to look up. + * @returns A map of cached documents, indexed by key. If an entry cannot be + * found, the corresponding key will be mapped to an invalid document. + */ + getEntries(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise; + /** + * Applies buffered changes to the underlying RemoteDocumentCache, using + * the provided transaction. + */ + apply(transaction: PersistenceTransaction): PersistencePromise; + /** Helper to assert this.changes is not null */ + protected assertNotApplied(): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/shared_client_state.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/shared_client_state.d.ts new file mode 100644 index 0000000..98efa94 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/shared_client_state.d.ts @@ -0,0 +1,312 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { BatchId, ListenSequenceNumber, MutationBatchState, OnlineState, TargetId } from '../core/types'; +import { TargetIdSet } from '../model/collections'; +import { AsyncQueue } from '../util/async_queue'; +import { FirestoreError } from '../util/error'; +import { SortedSet } from '../util/sorted_set'; +import { WindowLike } from '../util/types'; +import { QueryTargetState, SharedClientStateSyncer } from './shared_client_state_syncer'; +/** + * A randomly-generated key assigned to each Firestore instance at startup. + */ +export type ClientId = string; +/** + * A `SharedClientState` keeps track of the global state of the mutations + * and query targets for all active clients with the same persistence key (i.e. + * project ID and FirebaseApp name). It relays local changes to other clients + * and updates its local state as new state is observed. + * + * `SharedClientState` is primarily used for synchronization in Multi-Tab + * environments. Each tab is responsible for registering its active query + * targets and mutations. `SharedClientState` will then notify the listener + * assigned to `.syncEngine` for updates to mutations and queries that + * originated in other clients. + * + * To receive notifications, `.syncEngine` and `.onlineStateHandler` has to be + * assigned before calling `start()`. + */ +export interface SharedClientState { + onlineStateHandler: ((onlineState: OnlineState) => void) | null; + sequenceNumberHandler: ((sequenceNumber: ListenSequenceNumber) => void) | null; + /** Registers the Mutation Batch ID of a newly pending mutation. */ + addPendingMutation(batchId: BatchId): void; + /** + * Records that a pending mutation has been acknowledged or rejected. + * Called by the primary client to notify secondary clients of mutation + * results as they come back from the backend. + */ + updateMutationState(batchId: BatchId, state: 'acknowledged' | 'rejected', error?: FirestoreError): void; + /** + * Associates a new Query Target ID with the local Firestore client. Returns + * the new query state for the query (which can be 'current' if the query is + * already associated with another tab). + * + * If the target id is already associated with local client, the method simply + * returns its `QueryTargetState`. + */ + addLocalQueryTarget(targetId: TargetId, addToActiveTargetIds?: boolean): QueryTargetState; + /** Removes the Query Target ID association from the local client. */ + removeLocalQueryTarget(targetId: TargetId): void; + /** Checks whether the target is associated with the local client. */ + isLocalQueryTarget(targetId: TargetId): boolean; + /** + * Processes an update to a query target. + * + * Called by the primary client to notify secondary clients of document + * changes or state transitions that affect the provided query target. + */ + updateQueryState(targetId: TargetId, state: QueryTargetState, error?: FirestoreError): void; + /** + * Removes the target's metadata entry. + * + * Called by the primary client when all clients stopped listening to a query + * target. + */ + clearQueryState(targetId: TargetId): void; + /** + * Gets the active Query Targets IDs for all active clients. + * + * The implementation for this may require O(n) runtime, where 'n' is the size + * of the result set. + */ + getAllActiveQueryTargets(): SortedSet; + /** + * Checks whether the provided target ID is currently being listened to by + * any of the active clients. + * + * The implementation may require O(n*log m) runtime, where 'n' is the number + * of clients and 'm' the number of targets. + */ + isActiveQueryTarget(targetId: TargetId): boolean; + /** + * Starts the SharedClientState, reads existing client data and registers + * listeners for updates to new and existing clients. + */ + start(): Promise; + /** Shuts down the `SharedClientState` and its listeners. */ + shutdown(): void; + /** + * Changes the active user and removes all existing user-specific data. The + * user change does not call back into SyncEngine (for example, no mutations + * will be marked as removed). + */ + handleUserChange(user: User, removedBatchIds: BatchId[], addedBatchIds: BatchId[]): void; + /** Changes the shared online state of all clients. */ + setOnlineState(onlineState: OnlineState): void; + writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void; + /** + * Notifies other clients when remote documents have changed due to loading + * a bundle. + * + * @param collectionGroups The collection groups affected by this bundle. + */ + notifyBundleLoaded(collectionGroups: Set): void; +} +/** + * Holds the state of a mutation batch, including its user ID, batch ID and + * whether the batch is 'pending', 'acknowledged' or 'rejected'. + */ +export declare class MutationMetadata { + readonly user: User; + readonly batchId: BatchId; + readonly state: MutationBatchState; + readonly error?: FirestoreError | undefined; + constructor(user: User, batchId: BatchId, state: MutationBatchState, error?: FirestoreError | undefined); + /** + * Parses a MutationMetadata from its JSON representation in WebStorage. + * Logs a warning and returns null if the format of the data is not valid. + */ + static fromWebStorageEntry(user: User, batchId: BatchId, value: string): MutationMetadata | null; + toWebStorageJSON(): string; +} +/** + * Holds the state of a query target, including its target ID and whether the + * target is 'not-current', 'current' or 'rejected'. + */ +export declare class QueryTargetMetadata { + readonly targetId: TargetId; + readonly state: QueryTargetState; + readonly error?: FirestoreError | undefined; + constructor(targetId: TargetId, state: QueryTargetState, error?: FirestoreError | undefined); + /** + * Parses a QueryTargetMetadata from its JSON representation in WebStorage. + * Logs a warning and returns null if the format of the data is not valid. + */ + static fromWebStorageEntry(targetId: TargetId, value: string): QueryTargetMetadata | null; + toWebStorageJSON(): string; +} +/** + * Metadata state of a single client denoting the query targets it is actively + * listening to the watch. + */ +export interface ClientState { + readonly activeTargetIds: TargetIdSet; +} +/** + * This class represents the online state for all clients participating in + * multi-tab. The online state is only written to by the primary client, and + * used in secondary clients to update their query views. + */ +export declare class SharedOnlineState { + readonly clientId: string; + readonly onlineState: OnlineState; + constructor(clientId: string, onlineState: OnlineState); + /** + * Parses a SharedOnlineState from its JSON representation in WebStorage. + * Logs a warning and returns null if the format of the data is not valid. + */ + static fromWebStorageEntry(value: string): SharedOnlineState | null; +} +/** + * Metadata state of the local client. Unlike `RemoteClientState`, this class is + * mutable and keeps track of all pending mutations, which allows us to + * update the range of pending mutation batch IDs as new mutations are added or + * removed. + * + * The data in `LocalClientState` is not read from WebStorage and instead + * updated via its instance methods. The updated state can be serialized via + * `toWebStorageJSON()`. + */ +export declare class LocalClientState implements ClientState { + activeTargetIds: SortedSet; + addQueryTarget(targetId: TargetId): void; + removeQueryTarget(targetId: TargetId): void; + /** + * Converts this entry into a JSON-encoded format we can use for WebStorage. + * Does not encode `clientId` as it is part of the key in WebStorage. + */ + toWebStorageJSON(): string; +} +/** + * `WebStorageSharedClientState` uses WebStorage (window.localStorage) as the + * backing store for the SharedClientState. It keeps track of all active + * clients and supports modifications of the local client's data. + */ +export declare class WebStorageSharedClientState implements SharedClientState { + private readonly window; + private readonly queue; + private readonly persistenceKey; + private readonly localClientId; + syncEngine: SharedClientStateSyncer | null; + onlineStateHandler: ((onlineState: OnlineState) => void) | null; + sequenceNumberHandler: ((sequenceNumber: ListenSequenceNumber) => void) | null; + private readonly storage; + private readonly localClientStorageKey; + private readonly sequenceNumberKey; + private readonly storageListener; + private readonly onlineStateKey; + private readonly bundleLoadedKey; + private readonly clientStateKeyRe; + private readonly mutationBatchKeyRe; + private readonly queryTargetKeyRe; + private activeClients; + private started; + private currentUser; + /** + * Captures WebStorage events that occur before `start()` is called. These + * events are replayed once `WebStorageSharedClientState` is started. + */ + private earlyEvents; + constructor(window: WindowLike, queue: AsyncQueue, persistenceKey: string, localClientId: ClientId, initialUser: User); + /** Returns 'true' if WebStorage is available in the current environment. */ + static isAvailable(window: WindowLike | null): window is WindowLike; + start(): Promise; + writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void; + getAllActiveQueryTargets(): TargetIdSet; + isActiveQueryTarget(targetId: TargetId): boolean; + addPendingMutation(batchId: BatchId): void; + updateMutationState(batchId: BatchId, state: 'acknowledged' | 'rejected', error?: FirestoreError): void; + addLocalQueryTarget(targetId: TargetId, addToActiveTargetIds?: boolean): QueryTargetState; + removeLocalQueryTarget(targetId: TargetId): void; + isLocalQueryTarget(targetId: TargetId): boolean; + clearQueryState(targetId: TargetId): void; + updateQueryState(targetId: TargetId, state: QueryTargetState, error?: FirestoreError): void; + handleUserChange(user: User, removedBatchIds: BatchId[], addedBatchIds: BatchId[]): void; + setOnlineState(onlineState: OnlineState): void; + notifyBundleLoaded(collectionGroups: Set): void; + shutdown(): void; + private getItem; + private setItem; + private removeItem; + private handleWebStorageEvent; + private get localClientState(); + private persistClientState; + private persistMutationState; + private removeMutationState; + private persistOnlineState; + private persistQueryTargetState; + private persistBundleLoadedState; + /** + * Parses a client state key in WebStorage. Returns null if the key does not + * match the expected key format. + */ + private fromWebStorageClientStateKey; + /** + * Parses a client state in WebStorage. Returns 'null' if the value could not + * be parsed. + */ + private fromWebStorageClientState; + /** + * Parses a mutation batch state in WebStorage. Returns 'null' if the value + * could not be parsed. + */ + private fromWebStorageMutationMetadata; + /** + * Parses a query target state from WebStorage. Returns 'null' if the value + * could not be parsed. + */ + private fromWebStorageQueryTargetMetadata; + /** + * Parses an online state from WebStorage. Returns 'null' if the value + * could not be parsed. + */ + private fromWebStorageOnlineState; + private fromWebStoreBundleLoadedState; + private handleMutationBatchEvent; + private handleQueryTargetEvent; + private handleClientStateEvent; + private handleOnlineStateEvent; + private extractActiveQueryTargets; +} +/** + * `MemorySharedClientState` is a simple implementation of SharedClientState for + * clients using memory persistence. The state in this class remains fully + * isolated and no synchronization is performed. + */ +export declare class MemorySharedClientState implements SharedClientState { + private localState; + private queryState; + onlineStateHandler: ((onlineState: OnlineState) => void) | null; + sequenceNumberHandler: ((sequenceNumber: ListenSequenceNumber) => void) | null; + addPendingMutation(batchId: BatchId): void; + updateMutationState(batchId: BatchId, state: 'acknowledged' | 'rejected', error?: FirestoreError): void; + addLocalQueryTarget(targetId: TargetId, addToActiveTargetIds?: boolean): QueryTargetState; + updateQueryState(targetId: TargetId, state: QueryTargetState, error?: FirestoreError): void; + removeLocalQueryTarget(targetId: TargetId): void; + isLocalQueryTarget(targetId: TargetId): boolean; + clearQueryState(targetId: TargetId): void; + getAllActiveQueryTargets(): TargetIdSet; + isActiveQueryTarget(targetId: TargetId): boolean; + start(): Promise; + handleUserChange(user: User, removedBatchIds: BatchId[], addedBatchIds: BatchId[]): void; + setOnlineState(onlineState: OnlineState): void; + shutdown(): void; + writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void; + notifyBundleLoaded(collectionGroups: Set): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/shared_client_state_schema.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/shared_client_state_schema.d.ts new file mode 100644 index 0000000..b856116 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/shared_client_state_schema.d.ts @@ -0,0 +1,84 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { BatchId, MutationBatchState, TargetId } from '../core/types'; +import { ClientId } from './shared_client_state'; +import { QueryTargetState } from './shared_client_state_syncer'; +export declare const CLIENT_STATE_KEY_PREFIX = "firestore_clients"; +/** Assembles the key for a client state in WebStorage */ +export declare function createWebStorageClientStateKey(persistenceKey: string, clientId: ClientId): string; +/** + * The JSON representation of a clients's metadata as used during WebStorage + * serialization. The ClientId is omitted here as it is encoded as part of the + * key. + */ +export interface ClientStateSchema { + activeTargetIds: number[]; + updateTimeMs: number; +} +export declare const MUTATION_BATCH_KEY_PREFIX = "firestore_mutations"; +/** Assembles the key for a mutation batch in WebStorage */ +export declare function createWebStorageMutationBatchKey(persistenceKey: string, user: User, batchId: BatchId): string; +/** + * The JSON representation of a mutation batch's metadata as used during + * WebStorage serialization. The UserId and BatchId is omitted as it is + * encoded as part of the key. + */ +export interface MutationMetadataSchema { + state: MutationBatchState; + error?: { + code: string; + message: string; + }; + updateTimeMs: number; +} +export declare const QUERY_TARGET_KEY_PREFIX = "firestore_targets"; +/** Assembles the key for a query state in WebStorage */ +export declare function createWebStorageQueryTargetMetadataKey(persistenceKey: string, targetId: TargetId): string; +/** + * The JSON representation of a query target's state as used during WebStorage + * serialization. The TargetId is omitted as it is encoded as part of the key. + */ +export interface QueryTargetStateSchema { + state: QueryTargetState; + error?: { + code: string; + message: string; + }; + updateTimeMs: number; +} +export declare const ONLINE_STATE_KEY_PREFIX = "firestore_online_state"; +/** Assembles the key for the online state of the primary tab. */ +export declare function createWebStorageOnlineStateKey(persistenceKey: string): string; +export declare const BUNDLE_LOADED_KEY_PREFIX = "firestore_bundle_loaded_v2"; +export declare function createBundleLoadedKey(persistenceKey: string): string; +/** + * The JSON representation of the system's online state, as written by the + * primary client. + */ +export interface SharedOnlineStateSchema { + /** + * The clientId of the client that wrote this onlineState value. Tracked so + * that on startup, clients can check if this client is still active when + * determining whether to apply this value or not. + */ + readonly clientId: string; + readonly onlineState: string; +} +export declare const SEQUENCE_NUMBER_KEY_PREFIX = "firestore_sequence_number"; +/** Assembles the key for the current sequence number. */ +export declare function createWebStorageSequenceNumberKey(persistenceKey: string): string; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/shared_client_state_syncer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/shared_client_state_syncer.d.ts new file mode 100644 index 0000000..edc4a1b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/shared_client_state_syncer.d.ts @@ -0,0 +1,40 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BatchId, MutationBatchState, TargetId } from '../core/types'; +import { FirestoreError } from '../util/error'; +import { ClientId } from './shared_client_state'; +/** The different states of a watch target. */ +export type QueryTargetState = 'not-current' | 'current' | 'rejected'; +/** + * An interface that describes the actions the SharedClientState class needs to + * perform on a cooperating synchronization engine. + */ +export interface SharedClientStateSyncer { + /** Applies a mutation state to an existing batch. */ + applyBatchState(batchId: BatchId, state: MutationBatchState, error?: FirestoreError): Promise; + /** Applies a query target change from a different tab. */ + applyTargetState(targetId: TargetId, state: QueryTargetState, error?: FirestoreError): Promise; + /** Adds or removes Watch targets for queries from different tabs. */ + applyActiveTargetsChange(added: TargetId[], removed: TargetId[]): Promise; + /** Returns the IDs of the clients that are currently active. */ + getActiveClients(): Promise; + /** + * Retrieves newly changed documents from remote document cache and raises + * snapshots if needed. + */ + synchronizeWithChangedDocuments(collectionGroup: string): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/simple_db.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/simple_db.d.ts new file mode 100644 index 0000000..edaef3b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/simple_db.d.ts @@ -0,0 +1,233 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirestoreError } from '../util/error'; +import { PersistencePromise } from './persistence_promise'; +type SimpleDbTransactionMode = 'readonly' | 'readwrite'; +export interface SimpleDbSchemaConverter { + createOrUpgrade(db: IDBDatabase, txn: IDBTransaction, fromVersion: number, toVersion: number): PersistencePromise; +} +/** + * Wraps an IDBTransaction and exposes a store() method to get a handle to a + * specific object store. + */ +export declare class SimpleDbTransaction { + private readonly action; + private readonly transaction; + private aborted; + /** + * A `Promise` that resolves with the result of the IndexedDb transaction. + */ + private readonly completionDeferred; + static open(db: IDBDatabase, action: string, mode: IDBTransactionMode, objectStoreNames: string[]): SimpleDbTransaction; + constructor(action: string, transaction: IDBTransaction); + get completionPromise(): Promise; + abort(error?: Error): void; + maybeCommit(): void; + /** + * Returns a SimpleDbStore for the specified store. All + * operations performed on the SimpleDbStore happen within the context of this + * transaction and it cannot be used anymore once the transaction is + * completed. + * + * Note that we can't actually enforce that the KeyType and ValueType are + * correct, but they allow type safety through the rest of the consuming code. + */ + store(storeName: string): SimpleDbStore; +} +/** + * Provides a wrapper around IndexedDb with a simplified interface that uses + * Promise-like return values to chain operations. Real promises cannot be used + * since .then() continuations are executed asynchronously (e.g. via + * .setImmediate), which would cause IndexedDB to end the transaction. + * See PersistencePromise for more details. + */ +export declare class SimpleDb { + private readonly name; + private readonly version; + private readonly schemaConverter; + private db?; + private lastClosedDbVersion; + private versionchangelistener?; + /** Deletes the specified database. */ + static delete(name: string): Promise; + /** Returns true if IndexedDB is available in the current environment. */ + static isAvailable(): boolean; + /** + * Returns true if the backing IndexedDB store is the Node IndexedDBShim + * (see https://github.com/axemclion/IndexedDBShim). + */ + static isMockPersistence(): boolean; + /** Helper to get a typed SimpleDbStore from a transaction. */ + static getStore(txn: SimpleDbTransaction, store: string): SimpleDbStore; + /** Parse User Agent to determine iOS version. Returns -1 if not found. */ + static getIOSVersion(ua: string): number; + constructor(name: string, version: number, schemaConverter: SimpleDbSchemaConverter); + /** + * Opens the specified database, creating or upgrading it if necessary. + */ + ensureDb(action: string): Promise; + setVersionChangeListener(versionChangeListener: (event: IDBVersionChangeEvent) => void): void; + runTransaction(action: string, mode: SimpleDbTransactionMode, objectStores: string[], transactionFn: (transaction: SimpleDbTransaction) => PersistencePromise): Promise; + close(): void; +} +/** Parse User Agent to determine Android version. Returns -1 if not found. */ +export declare function getAndroidVersion(ua: string): number; +/** + * A controller for iterating over a key range or index. It allows an iterate + * callback to delete the currently-referenced object, or jump to a new key + * within the key range or index. + */ +export declare class IterationController { + private dbCursor; + private shouldStop; + private nextKey; + constructor(dbCursor: IDBCursorWithValue); + get isDone(): boolean; + get skipToKey(): IDBValidKey | null; + set cursor(value: IDBCursorWithValue); + /** + * This function can be called to stop iteration at any point. + */ + done(): void; + /** + * This function can be called to skip to that next key, which could be + * an index or a primary key. + */ + skip(key: IDBValidKey): void; + /** + * Delete the current cursor value from the object store. + * + * NOTE: You CANNOT do this with a keysOnly query. + */ + delete(): PersistencePromise; +} +/** + * Callback used with iterate() method. + */ +export type IterateCallback = (key: KeyType, value: ValueType, control: IterationController) => void | PersistencePromise; +/** Options available to the iterate() method. */ +export interface IterateOptions { + /** Index to iterate over (else primary keys will be iterated) */ + index?: string; + /** IndexedDB Range to iterate over (else entire store will be iterated) */ + range?: IDBKeyRange; + /** If true, values aren't read while iterating. */ + keysOnly?: boolean; + /** If true, iterate over the store in reverse. */ + reverse?: boolean; +} +/** An error that wraps exceptions that thrown during IndexedDB execution. */ +export declare class IndexedDbTransactionError extends FirestoreError { + name: string; + constructor(actionName: string, cause: Error | string); +} +/** Verifies whether `e` is an IndexedDbTransactionError. */ +export declare function isIndexedDbTransactionError(e: Error): boolean; +/** + * A wrapper around an IDBObjectStore providing an API that: + * + * 1) Has generic KeyType / ValueType parameters to provide strongly-typed + * methods for acting against the object store. + * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every + * method return a PersistencePromise instead. + * 3) Provides a higher-level API to avoid needing to do excessive wrapping of + * intermediate IndexedDB types (IDBCursorWithValue, etc.) + */ +export declare class SimpleDbStore { + private store; + constructor(store: IDBObjectStore); + /** + * Writes a value into the Object Store. + * + * @param key - Optional explicit key to use when writing the object, else the + * key will be auto-assigned (e.g. via the defined keyPath for the store). + * @param value - The object to write. + */ + put(value: ValueType): PersistencePromise; + put(key: KeyType, value: ValueType): PersistencePromise; + /** + * Adds a new value into an Object Store and returns the new key. Similar to + * IndexedDb's `add()`, this method will fail on primary key collisions. + * + * @param value - The object to write. + * @returns The key of the value to add. + */ + add(value: ValueType): PersistencePromise; + /** + * Gets the object with the specified key from the specified store, or null + * if no object exists with the specified key. + * + * @key The key of the object to get. + * @returns The object with the specified key or null if no object exists. + */ + get(key: KeyType): PersistencePromise; + delete(key: KeyType | IDBKeyRange): PersistencePromise; + /** + * If we ever need more of the count variants, we can add overloads. For now, + * all we need is to count everything in a store. + * + * Returns the number of rows in the store. + */ + count(): PersistencePromise; + /** Loads all elements from the object store. */ + loadAll(): PersistencePromise; + /** Loads all elements for the index range from the object store. */ + loadAll(range: IDBKeyRange): PersistencePromise; + /** Loads all elements ordered by the given index. */ + loadAll(index: string): PersistencePromise; + /** + * Loads all elements from the object store that fall into the provided in the + * index range for the given index. + */ + loadAll(index: string, range: IDBKeyRange): PersistencePromise; + /** + * Loads the first `count` elements from the provided index range. Loads all + * elements if no limit is provided. + */ + loadFirst(range: IDBKeyRange, count: number | null): PersistencePromise; + deleteAll(): PersistencePromise; + deleteAll(range: IDBKeyRange): PersistencePromise; + deleteAll(index: string, range: IDBKeyRange): PersistencePromise; + /** + * Iterates over keys and values in an object store. + * + * @param options - Options specifying how to iterate the objects in the + * store. + * @param callback - will be called for each iterated object. Iteration can be + * canceled at any point by calling the doneFn passed to the callback. + * The callback can return a PersistencePromise if it performs async + * operations but note that iteration will continue without waiting for them + * to complete. + * @returns A PersistencePromise that resolves once all PersistencePromises + * returned by callbacks resolve. + */ + iterate(callback: IterateCallback): PersistencePromise; + iterate(options: IterateOptions, callback: IterateCallback): PersistencePromise; + /** + * Iterates over a store, but waits for the given callback to complete for + * each entry before iterating the next entry. This allows the callback to do + * asynchronous work to determine if this iteration should continue. + * + * The provided callback should return `true` to continue iteration, and + * `false` otherwise. + */ + iterateSerial(callback: (k: KeyType, v: ValueType) => PersistencePromise): PersistencePromise; + private iterateCursor; + private options; + private cursor; +} +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/target_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/target_cache.d.ts new file mode 100644 index 0000000..218c805 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/target_cache.d.ts @@ -0,0 +1,130 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { Target } from '../core/target'; +import { ListenSequenceNumber, TargetId } from '../core/types'; +import { DocumentKeySet } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +import { TargetData } from './target_data'; +/** + * Represents cached targets received from the remote backend. + * + * The cache is keyed by `Target` and entries in the cache are `TargetData` + * instances. + */ +export interface TargetCache { + /** + * A global snapshot version representing the last consistent snapshot we + * received from the backend. This is monotonically increasing and any + * snapshots received from the backend prior to this version (e.g. for targets + * resumed with a resume_token) should be suppressed (buffered) until the + * backend has caught up to this snapshot version again. This prevents our + * cache from ever going backwards in time. + * + * This is updated whenever our we get a TargetChange with a read_time and + * empty target_ids. + */ + getLastRemoteSnapshotVersion(transaction: PersistenceTransaction): PersistencePromise; + /** + * @returns The highest sequence number observed, including any that might be + * persisted on-disk. + */ + getHighestSequenceNumber(transaction: PersistenceTransaction): PersistencePromise; + /** + * Call provided function with each `TargetData` that we have cached. + */ + forEachTarget(txn: PersistenceTransaction, f: (q: TargetData) => void): PersistencePromise; + /** + * Set the highest listen sequence number and optionally updates the + * snapshot version of the last consistent snapshot received from the backend + * (see getLastRemoteSnapshotVersion() for more details). + * + * @param highestListenSequenceNumber - The new maximum listen sequence number. + * @param lastRemoteSnapshotVersion - The new snapshot version. Optional. + */ + setTargetsMetadata(transaction: PersistenceTransaction, highestListenSequenceNumber: number, lastRemoteSnapshotVersion?: SnapshotVersion): PersistencePromise; + /** + * Adds an entry in the cache. + * + * The cache key is extracted from `targetData.target`. The key must not already + * exist in the cache. + * + * @param targetData - A TargetData instance to put in the cache. + */ + addTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Updates an entry in the cache. + * + * The cache key is extracted from `targetData.target`. The entry must already + * exist in the cache, and it will be replaced. + * @param targetData - The TargetData to be replaced into the cache. + */ + updateTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Removes the cached entry for the given target data. It is an error to remove + * a target data that does not exist. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * The number of targets currently in the cache. + */ + getTargetCount(transaction: PersistenceTransaction): PersistencePromise; + /** + * Looks up a TargetData entry by target. + * + * @param target - The query target corresponding to the entry to look up. + * @returns The cached TargetData entry, or null if the cache has no entry for + * the target. + */ + getTargetData(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Adds the given document keys to cached query results of the given target + * ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + addMatchingKeys(transaction: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + /** + * Removes the given document keys from the cached query results of the + * given target ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMatchingKeys(transaction: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + /** + * Removes all the keys in the query results of the given target ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMatchingKeysForTargetId(transaction: PersistenceTransaction, targetId: TargetId): PersistencePromise; + /** + * Returns the document keys that match the provided target ID. + */ + getMatchingKeysForTargetId(transaction: PersistenceTransaction, targetId: TargetId): PersistencePromise; + /** + * Returns a new target ID that is higher than any query in the cache. If + * there are no queries in the cache, returns the first valid target ID. + * Allocated target IDs are persisted and `allocateTargetId()` will never + * return the same ID twice. + */ + allocateTargetId(transaction: PersistenceTransaction): PersistencePromise; + containsKey(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/target_data.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/target_data.d.ts new file mode 100644 index 0000000..595a334 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/local/target_data.d.ts @@ -0,0 +1,127 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { Target } from '../core/target'; +import { ListenSequenceNumber, TargetId } from '../core/types'; +import { ByteString } from '../util/byte_string'; +/** An enumeration of the different purposes we have for targets. */ +export declare const enum TargetPurpose { + /** A regular, normal query target. */ + Listen = "TargetPurposeListen", + /** + * The query target was used to refill a query after an existence filter + * mismatch. + */ + ExistenceFilterMismatch = "TargetPurposeExistenceFilterMismatch", + /** + * The query target was used if the query is the result of a false positive in + * the bloom filter. + */ + ExistenceFilterMismatchBloom = "TargetPurposeExistenceFilterMismatchBloom", + /** The query target was used to resolve a limbo document. */ + LimboResolution = "TargetPurposeLimboResolution" +} +/** + * An immutable set of metadata that the local store tracks for each target. + */ +export declare class TargetData { + /** The target being listened to. */ + readonly target: Target; + /** + * The target ID to which the target corresponds; Assigned by the + * LocalStore for user listens and by the SyncEngine for limbo watches. + */ + readonly targetId: TargetId; + /** The purpose of the target. */ + readonly purpose: TargetPurpose; + /** + * The sequence number of the last transaction during which this target data + * was modified. + */ + readonly sequenceNumber: ListenSequenceNumber; + /** The latest snapshot version seen for this target. */ + readonly snapshotVersion: SnapshotVersion; + /** + * The maximum snapshot version at which the associated view + * contained no limbo documents. + */ + readonly lastLimboFreeSnapshotVersion: SnapshotVersion; + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + readonly resumeToken: ByteString; + /** + * The number of documents that last matched the query at the resume token or + * read time. Documents are counted only when making a listen request with + * resume token or read time, otherwise, keep it null. + */ + readonly expectedCount: number | null; + constructor( + /** The target being listened to. */ + target: Target, + /** + * The target ID to which the target corresponds; Assigned by the + * LocalStore for user listens and by the SyncEngine for limbo watches. + */ + targetId: TargetId, + /** The purpose of the target. */ + purpose: TargetPurpose, + /** + * The sequence number of the last transaction during which this target data + * was modified. + */ + sequenceNumber: ListenSequenceNumber, + /** The latest snapshot version seen for this target. */ + snapshotVersion?: SnapshotVersion, + /** + * The maximum snapshot version at which the associated view + * contained no limbo documents. + */ + lastLimboFreeSnapshotVersion?: SnapshotVersion, + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + resumeToken?: ByteString, + /** + * The number of documents that last matched the query at the resume token or + * read time. Documents are counted only when making a listen request with + * resume token or read time, otherwise, keep it null. + */ + expectedCount?: number | null); + /** Creates a new target data instance with an updated sequence number. */ + withSequenceNumber(sequenceNumber: number): TargetData; + /** + * Creates a new target data instance with an updated resume token and + * snapshot version. + */ + withResumeToken(resumeToken: ByteString, snapshotVersion: SnapshotVersion): TargetData; + /** + * Creates a new target data instance with an updated expected count. + */ + withExpectedCount(expectedCount: number): TargetData; + /** + * Creates a new target data instance with an updated last limbo free + * snapshot version number. + */ + withLastLimboFreeSnapshotVersion(lastLimboFreeSnapshotVersion: SnapshotVersion): TargetData; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/collections.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/collections.d.ts new file mode 100644 index 0000000..999c4ea --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/collections.d.ts @@ -0,0 +1,50 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { TargetId } from '../core/types'; +import { OverlayedDocument } from '../local/overlayed_document'; +import { ObjectMap } from '../util/obj_map'; +import { SortedMap } from '../util/sorted_map'; +import { SortedSet } from '../util/sorted_set'; +import { Document, MutableDocument } from './document'; +import { DocumentKey } from './document_key'; +import { Mutation } from './mutation'; +import { Overlay } from './overlay'; +/** Miscellaneous collection types / constants. */ +export type MutableDocumentMap = SortedMap; +export declare function mutableDocumentMap(): MutableDocumentMap; +export interface DocumentSizeEntries { + documents: MutableDocumentMap; + sizeMap: SortedMap; +} +export type DocumentMap = SortedMap; +export declare function documentMap(...docs: Document[]): DocumentMap; +export type OverlayedDocumentMap = DocumentKeyMap; +export declare function newOverlayedDocumentMap(): OverlayedDocumentMap; +export declare function convertOverlayedDocumentMapToDocumentMap(collection: OverlayedDocumentMap): DocumentMap; +export type OverlayMap = DocumentKeyMap; +export declare function newOverlayMap(): OverlayMap; +export type MutationMap = DocumentKeyMap; +export declare function newMutationMap(): MutationMap; +export type DocumentKeyMap = ObjectMap; +export declare function newDocumentKeyMap(): DocumentKeyMap; +export type DocumentVersionMap = SortedMap; +export declare function documentVersionMap(): DocumentVersionMap; +export type DocumentKeySet = SortedSet; +export declare function documentKeySet(...keys: DocumentKey[]): DocumentKeySet; +export type TargetIdSet = SortedSet; +export declare function targetIdSet(): SortedSet; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/document.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/document.d.ts new file mode 100644 index 0000000..66ba3f3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/document.d.ts @@ -0,0 +1,150 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { DocumentKey } from './document_key'; +import { ObjectValue } from './object_value'; +import { FieldPath } from './path'; +/** + * Represents a document in Firestore with a key, version, data and whether the + * data has local mutations applied to it. + */ +export interface Document { + /** The key for this document */ + readonly key: DocumentKey; + /** + * The version of this document if it exists or a version at which this + * document was guaranteed to not exist. + */ + readonly version: SnapshotVersion; + /** + * The timestamp at which this document was read from the remote server. Uses + * `SnapshotVersion.min()` for documents created by the user. + */ + readonly readTime: SnapshotVersion; + /** + * The timestamp at which the document was created. This value increases + * monotonically when a document is deleted then recreated. It can also be + * compared to `createTime` of other documents and the `readTime` of a query. + */ + readonly createTime: SnapshotVersion; + /** The underlying data of this document or an empty value if no data exists. */ + readonly data: ObjectValue; + /** Returns whether local mutations were applied via the mutation queue. */ + readonly hasLocalMutations: boolean; + /** Returns whether mutations were applied based on a write acknowledgment. */ + readonly hasCommittedMutations: boolean; + /** + * Whether this document had a local mutation applied that has not yet been + * acknowledged by Watch. + */ + readonly hasPendingWrites: boolean; + /** + * Returns whether this document is valid (i.e. it is an entry in the + * RemoteDocumentCache, was created by a mutation or read from the backend). + */ + isValidDocument(): boolean; + /** + * Returns whether the document exists and its data is known at the current + * version. + */ + isFoundDocument(): boolean; + /** + * Returns whether the document is known to not exist at the current version. + */ + isNoDocument(): boolean; + /** + * Returns whether the document exists and its data is unknown at the current + * version. + */ + isUnknownDocument(): boolean; + isEqual(other: Document | null | undefined): boolean; + /** Creates a mutable copy of this document. */ + mutableCopy(): MutableDocument; + toString(): string; +} +/** + * Represents a document in Firestore with a key, version, data and whether it + * has local mutations applied to it. + * + * Documents can transition between states via `convertToFoundDocument()`, + * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does + * not transition to one of these states even after all mutations have been + * applied, `isValidDocument()` returns false and the document should be removed + * from all views. + */ +export declare class MutableDocument implements Document { + readonly key: DocumentKey; + private documentType; + version: SnapshotVersion; + readTime: SnapshotVersion; + createTime: SnapshotVersion; + data: ObjectValue; + private documentState; + private constructor(); + /** + * Creates a document with no known version or data, but which can serve as + * base document for mutations. + */ + static newInvalidDocument(documentKey: DocumentKey): MutableDocument; + /** + * Creates a new document that is known to exist with the given data at the + * given version. + */ + static newFoundDocument(documentKey: DocumentKey, version: SnapshotVersion, createTime: SnapshotVersion, value: ObjectValue): MutableDocument; + /** Creates a new document that is known to not exist at the given version. */ + static newNoDocument(documentKey: DocumentKey, version: SnapshotVersion): MutableDocument; + /** + * Creates a new document that is known to exist at the given version but + * whose data is not known (e.g. a document that was updated without a known + * base document). + */ + static newUnknownDocument(documentKey: DocumentKey, version: SnapshotVersion): MutableDocument; + /** + * Changes the document type to indicate that it exists and that its version + * and data are known. + */ + convertToFoundDocument(version: SnapshotVersion, value: ObjectValue): MutableDocument; + /** + * Changes the document type to indicate that it doesn't exist at the given + * version. + */ + convertToNoDocument(version: SnapshotVersion): MutableDocument; + /** + * Changes the document type to indicate that it exists at a given version but + * that its data is not known (e.g. a document that was updated without a known + * base document). + */ + convertToUnknownDocument(version: SnapshotVersion): MutableDocument; + setHasCommittedMutations(): MutableDocument; + setHasLocalMutations(): MutableDocument; + setReadTime(readTime: SnapshotVersion): MutableDocument; + get hasLocalMutations(): boolean; + get hasCommittedMutations(): boolean; + get hasPendingWrites(): boolean; + isValidDocument(): boolean; + isFoundDocument(): boolean; + isNoDocument(): boolean; + isUnknownDocument(): boolean; + isEqual(other: Document | null | undefined): boolean; + mutableCopy(): MutableDocument; + toString(): string; +} +/** + * Compares the value for field `field` in the provided documents. Throws if + * the field does not exist in both documents. + */ +export declare function compareDocumentsByField(field: FieldPath, d1: Document, d2: Document): number; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/document_comparator.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/document_comparator.d.ts new file mode 100644 index 0000000..100ed19 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/document_comparator.d.ts @@ -0,0 +1,19 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Document } from './document'; +export type DocumentComparator = (doc1: Document, doc2: Document) => number; +export declare function compareByKey(doc1: Document, doc2: Document): number; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/document_key.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/document_key.d.ts new file mode 100644 index 0000000..4c95b57 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/document_key.d.ts @@ -0,0 +1,45 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ResourcePath } from './path'; +/** + * @internal + */ +export declare class DocumentKey { + readonly path: ResourcePath; + constructor(path: ResourcePath); + static fromPath(path: string): DocumentKey; + static fromName(name: string): DocumentKey; + static empty(): DocumentKey; + get collectionGroup(): string; + /** Returns true if the document is in the specified collectionId. */ + hasCollectionId(collectionId: string): boolean; + /** Returns the collection group (i.e. the name of the parent collection) for this key. */ + getCollectionGroup(): string; + /** Returns the fully qualified path to the parent collection. */ + getCollectionPath(): ResourcePath; + isEqual(other: DocumentKey | null): boolean; + toString(): string; + static comparator(k1: DocumentKey, k2: DocumentKey): number; + static isDocumentKey(path: ResourcePath): boolean; + /** + * Creates and returns a new document key with the given segments. + * + * @param segments - The segments of the path to the document + * @returns A new instance of DocumentKey + */ + static fromSegments(segments: string[]): DocumentKey; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/document_set.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/document_set.d.ts new file mode 100644 index 0000000..5dc7ebd --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/document_set.d.ts @@ -0,0 +1,57 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Document } from './document'; +import { DocumentComparator } from './document_comparator'; +import { DocumentKey } from './document_key'; +/** + * DocumentSet is an immutable (copy-on-write) collection that holds documents + * in order specified by the provided comparator. We always add a document key + * comparator on top of what is provided to guarantee document equality based on + * the key. + */ +export declare class DocumentSet { + /** + * Returns an empty copy of the existing DocumentSet, using the same + * comparator. + */ + static emptySet(oldSet: DocumentSet): DocumentSet; + private comparator; + private keyedMap; + private sortedSet; + /** The default ordering is by key if the comparator is omitted */ + constructor(comp?: DocumentComparator); + has(key: DocumentKey): boolean; + get(key: DocumentKey): Document | null; + first(): Document | null; + last(): Document | null; + isEmpty(): boolean; + /** + * Returns the index of the provided key in the document set, or -1 if the + * document key is not present in the set; + */ + indexOf(key: DocumentKey): number; + get size(): number; + /** Iterates documents in order defined by "comparator" */ + forEach(cb: (doc: Document) => void): void; + /** Inserts or updates a document with the same key */ + add(doc: Document): DocumentSet; + /** Deletes a document with a given key */ + delete(key: DocumentKey): DocumentSet; + isEqual(other: DocumentSet | null | undefined): boolean; + toString(): string; + private copy; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/field_index.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/field_index.d.ts new file mode 100644 index 0000000..1f4ccb0 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/field_index.d.ts @@ -0,0 +1,171 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { Document } from './document'; +import { DocumentKey } from './document_key'; +import { FieldPath } from './path'; +/** + * The initial mutation batch id for each index. Gets updated during index + * backfill. + */ +export declare const INITIAL_LARGEST_BATCH_ID = -1; +/** + * The initial sequence number for each index. Gets updated during index + * backfill. + */ +export declare const INITIAL_SEQUENCE_NUMBER = 0; +/** + * An index definition for field indexes in Firestore. + * + * Every index is associated with a collection. The definition contains a list + * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or + * `CONTAINS` for ArrayContains/ArrayContainsAny queries). + * + * Unlike the backend, the SDK does not differentiate between collection or + * collection group-scoped indices. Every index can be used for both single + * collection and collection group queries. + */ +export declare class FieldIndex { + /** + * The index ID. Returns -1 if the index ID is not available (e.g. the index + * has not yet been persisted). + */ + readonly indexId: number; + /** The collection ID this index applies to. */ + readonly collectionGroup: string; + /** The field segments for this index. */ + readonly fields: IndexSegment[]; + /** Shows how up-to-date the index is for the current user. */ + readonly indexState: IndexState; + /** An ID for an index that has not yet been added to persistence. */ + static UNKNOWN_ID: number; + constructor( + /** + * The index ID. Returns -1 if the index ID is not available (e.g. the index + * has not yet been persisted). + */ + indexId: number, + /** The collection ID this index applies to. */ + collectionGroup: string, + /** The field segments for this index. */ + fields: IndexSegment[], + /** Shows how up-to-date the index is for the current user. */ + indexState: IndexState); +} +/** Returns the ArrayContains/ArrayContainsAny segment for this index. */ +export declare function fieldIndexGetArraySegment(fieldIndex: FieldIndex): IndexSegment | undefined; +/** Returns all directional (ascending/descending) segments for this index. */ +export declare function fieldIndexGetDirectionalSegments(fieldIndex: FieldIndex): IndexSegment[]; +/** + * Returns the order of the document key component for the given index. + * + * PORTING NOTE: This is only used in the Web IndexedDb implementation. + */ +export declare function fieldIndexGetKeyOrder(fieldIndex: FieldIndex): IndexKind; +/** + * Compares indexes by collection group and segments. Ignores update time and + * index ID. + */ +export declare function fieldIndexSemanticComparator(left: FieldIndex, right: FieldIndex): number; +/** Returns a debug representation of the field index */ +export declare function fieldIndexToString(fieldIndex: FieldIndex): string; +/** The type of the index, e.g. for which type of query it can be used. */ +export declare const enum IndexKind { + /** + * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries. + */ + ASCENDING = 0, + /** + * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries. + */ + DESCENDING = 1, + /** Contains index. Can be used for ArrayContains and ArrayContainsAny. */ + CONTAINS = 2 +} +/** An index component consisting of field path and index type. */ +export declare class IndexSegment { + /** The field path of the component. */ + readonly fieldPath: FieldPath; + /** The fields sorting order. */ + readonly kind: IndexKind; + constructor( + /** The field path of the component. */ + fieldPath: FieldPath, + /** The fields sorting order. */ + kind: IndexKind); +} +/** + * Stores the "high water mark" that indicates how updated the Index is for the + * current user. + */ +export declare class IndexState { + /** + * Indicates when the index was last updated (relative to other indexes). + */ + readonly sequenceNumber: number; + /** The the latest indexed read time, document and batch id. */ + readonly offset: IndexOffset; + constructor( + /** + * Indicates when the index was last updated (relative to other indexes). + */ + sequenceNumber: number, + /** The the latest indexed read time, document and batch id. */ + offset: IndexOffset); + /** The state of an index that has not yet been backfilled. */ + static empty(): IndexState; +} +/** + * Creates an offset that matches all documents with a read time higher than + * `readTime`. + */ +export declare function newIndexOffsetSuccessorFromReadTime(readTime: SnapshotVersion, largestBatchId: number): IndexOffset; +/** Creates a new offset based on the provided document. */ +export declare function newIndexOffsetFromDocument(document: Document): IndexOffset; +/** + * Stores the latest read time, document and batch ID that were processed for an + * index. + */ +export declare class IndexOffset { + /** + * The latest read time version that has been indexed by Firestore for this + * field index. + */ + readonly readTime: SnapshotVersion; + /** + * The key of the last document that was indexed for this query. Use + * `DocumentKey.empty()` if no document has been indexed. + */ + readonly documentKey: DocumentKey; + readonly largestBatchId: number; + constructor( + /** + * The latest read time version that has been indexed by Firestore for this + * field index. + */ + readTime: SnapshotVersion, + /** + * The key of the last document that was indexed for this query. Use + * `DocumentKey.empty()` if no document has been indexed. + */ + documentKey: DocumentKey, largestBatchId: number); + /** Returns an offset that sorts before all regular offsets. */ + static min(): IndexOffset; + /** Returns an offset that sorts after all regular offsets. */ + static max(): IndexOffset; +} +export declare function indexOffsetComparator(left: IndexOffset, right: IndexOffset): number; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/field_mask.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/field_mask.d.ts new file mode 100644 index 0000000..555ea0d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/field_mask.d.ts @@ -0,0 +1,45 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FieldPath } from './path'; +/** + * Provides a set of fields that can be used to partially patch a document. + * FieldMask is used in conjunction with ObjectValue. + * Examples: + * foo - Overwrites foo entirely with the provided value. If foo is not + * present in the companion ObjectValue, the field is deleted. + * foo.bar - Overwrites only the field bar of the object foo. + * If foo is not an object, foo is replaced with an object + * containing foo + */ +export declare class FieldMask { + readonly fields: FieldPath[]; + constructor(fields: FieldPath[]); + static empty(): FieldMask; + /** + * Returns a new FieldMask object that is the result of adding all the given + * fields paths to this field mask. + */ + unionWith(extraFields: FieldPath[]): FieldMask; + /** + * Verifies that `fieldPath` is included by at least one field in this field + * mask. + * + * This is an O(n) operation, where `n` is the size of the field mask. + */ + covers(fieldPath: FieldPath): boolean; + isEqual(other: FieldMask): boolean; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/mutation.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/mutation.d.ts new file mode 100644 index 0000000..9dd68b9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/mutation.d.ts @@ -0,0 +1,270 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { Timestamp } from '../lite-api/timestamp'; +import { Value as ProtoValue } from '../protos/firestore_proto_api'; +import { Document, MutableDocument } from './document'; +import { DocumentKey } from './document_key'; +import { FieldMask } from './field_mask'; +import { ObjectValue } from './object_value'; +import { FieldPath } from './path'; +import { TransformOperation } from './transform_operation'; +/** A field path and the TransformOperation to perform upon it. */ +export declare class FieldTransform { + readonly field: FieldPath; + readonly transform: TransformOperation; + constructor(field: FieldPath, transform: TransformOperation); +} +export declare function fieldTransformEquals(left: FieldTransform, right: FieldTransform): boolean; +export declare function fieldTransformsAreEqual(left?: FieldTransform[], right?: FieldTransform[]): boolean; +/** The result of successfully applying a mutation to the backend. */ +export declare class MutationResult { + /** + * The version at which the mutation was committed: + * + * - For most operations, this is the updateTime in the WriteResult. + * - For deletes, the commitTime of the WriteResponse (because deletes are + * not stored and have no updateTime). + * + * Note that these versions can be different: No-op writes will not change + * the updateTime even though the commitTime advances. + */ + readonly version: SnapshotVersion; + /** + * The resulting fields returned from the backend after a mutation + * containing field transforms has been committed. Contains one FieldValue + * for each FieldTransform that was in the mutation. + * + * Will be empty if the mutation did not contain any field transforms. + */ + readonly transformResults: Array; + constructor( + /** + * The version at which the mutation was committed: + * + * - For most operations, this is the updateTime in the WriteResult. + * - For deletes, the commitTime of the WriteResponse (because deletes are + * not stored and have no updateTime). + * + * Note that these versions can be different: No-op writes will not change + * the updateTime even though the commitTime advances. + */ + version: SnapshotVersion, + /** + * The resulting fields returned from the backend after a mutation + * containing field transforms has been committed. Contains one FieldValue + * for each FieldTransform that was in the mutation. + * + * Will be empty if the mutation did not contain any field transforms. + */ + transformResults: Array); +} +export declare const enum MutationType { + Set = 0, + Patch = 1, + Delete = 2, + Verify = 3 +} +/** + * Encodes a precondition for a mutation. This follows the model that the + * backend accepts with the special case of an explicit "empty" precondition + * (meaning no precondition). + */ +export declare class Precondition { + readonly updateTime?: SnapshotVersion | undefined; + readonly exists?: boolean | undefined; + private constructor(); + /** Creates a new empty Precondition. */ + static none(): Precondition; + /** Creates a new Precondition with an exists flag. */ + static exists(exists: boolean): Precondition; + /** Creates a new Precondition based on a version a document exists at. */ + static updateTime(version: SnapshotVersion): Precondition; + /** Returns whether this Precondition is empty. */ + get isNone(): boolean; + isEqual(other: Precondition): boolean; +} +/** Returns true if the preconditions is valid for the given document. */ +export declare function preconditionIsValidForDocument(precondition: Precondition, document: MutableDocument): boolean; +/** + * A mutation describes a self-contained change to a document. Mutations can + * create, replace, delete, and update subsets of documents. + * + * Mutations not only act on the value of the document but also its version. + * + * For local mutations (mutations that haven't been committed yet), we preserve + * the existing version for Set and Patch mutations. For Delete mutations, we + * reset the version to 0. + * + * Here's the expected transition table. + * + * MUTATION APPLIED TO RESULTS IN + * + * SetMutation Document(v3) Document(v3) + * SetMutation NoDocument(v3) Document(v0) + * SetMutation InvalidDocument(v0) Document(v0) + * PatchMutation Document(v3) Document(v3) + * PatchMutation NoDocument(v3) NoDocument(v3) + * PatchMutation InvalidDocument(v0) UnknownDocument(v3) + * DeleteMutation Document(v3) NoDocument(v0) + * DeleteMutation NoDocument(v3) NoDocument(v0) + * DeleteMutation InvalidDocument(v0) NoDocument(v0) + * + * For acknowledged mutations, we use the updateTime of the WriteResponse as + * the resulting version for Set and Patch mutations. As deletes have no + * explicit update time, we use the commitTime of the WriteResponse for + * Delete mutations. + * + * If a mutation is acknowledged by the backend but fails the precondition check + * locally, we transition to an `UnknownDocument` and rely on Watch to send us + * the updated version. + * + * Field transforms are used only with Patch and Set Mutations. We use the + * `updateTransforms` message to store transforms, rather than the `transforms`s + * messages. + * + * ## Subclassing Notes + * + * Every type of mutation needs to implement its own applyToRemoteDocument() and + * applyToLocalView() to implement the actual behavior of applying the mutation + * to some source document (see `setMutationApplyToRemoteDocument()` for an + * example). + */ +export declare abstract class Mutation { + abstract readonly type: MutationType; + abstract readonly key: DocumentKey; + abstract readonly precondition: Precondition; + abstract readonly fieldTransforms: FieldTransform[]; + /** + * Returns a `FieldMask` representing the fields that will be changed by + * applying this mutation. Returns `null` if the mutation will overwrite the + * entire document. + */ + abstract getFieldMask(): FieldMask | null; +} +/** + * A utility method to calculate a `Mutation` representing the overlay from the + * final state of the document, and a `FieldMask` representing the fields that + * are mutated by the local mutations. + */ +export declare function calculateOverlayMutation(doc: MutableDocument, mask: FieldMask | null): Mutation | null; +/** + * Applies this mutation to the given document for the purposes of computing a + * new remote document. If the input document doesn't match the expected state + * (e.g. it is invalid or outdated), the document type may transition to + * unknown. + * + * @param mutation - The mutation to apply. + * @param document - The document to mutate. The input document can be an + * invalid document if the client has no knowledge of the pre-mutation state + * of the document. + * @param mutationResult - The result of applying the mutation from the backend. + */ +export declare function mutationApplyToRemoteDocument(mutation: Mutation, document: MutableDocument, mutationResult: MutationResult): void; +/** + * Applies this mutation to the given document for the purposes of computing + * the new local view of a document. If the input document doesn't match the + * expected state, the document is not modified. + * + * @param mutation - The mutation to apply. + * @param document - The document to mutate. The input document can be an + * invalid document if the client has no knowledge of the pre-mutation state + * of the document. + * @param previousMask - The fields that have been updated before applying this mutation. + * @param localWriteTime - A timestamp indicating the local write time of the + * batch this mutation is a part of. + * @returns A `FieldMask` representing the fields that are changed by applying this mutation. + */ +export declare function mutationApplyToLocalView(mutation: Mutation, document: MutableDocument, previousMask: FieldMask | null, localWriteTime: Timestamp): FieldMask | null; +/** + * If this mutation is not idempotent, returns the base value to persist with + * this mutation. If a base value is returned, the mutation is always applied + * to this base value, even if document has already been updated. + * + * The base value is a sparse object that consists of only the document + * fields for which this mutation contains a non-idempotent transformation + * (e.g. a numeric increment). The provided value guarantees consistent + * behavior for non-idempotent transforms and allow us to return the same + * latency-compensated value even if the backend has already applied the + * mutation. The base value is null for idempotent mutations, as they can be + * re-played even if the backend has already applied them. + * + * @returns a base value to store along with the mutation, or null for + * idempotent mutations. + */ +export declare function mutationExtractBaseValue(mutation: Mutation, document: Document): ObjectValue | null; +export declare function mutationEquals(left: Mutation, right: Mutation): boolean; +/** + * A mutation that creates or replaces the document at the given key with the + * object value contents. + */ +export declare class SetMutation extends Mutation { + readonly key: DocumentKey; + readonly value: ObjectValue; + readonly precondition: Precondition; + readonly fieldTransforms: FieldTransform[]; + constructor(key: DocumentKey, value: ObjectValue, precondition: Precondition, fieldTransforms?: FieldTransform[]); + readonly type: MutationType; + getFieldMask(): FieldMask | null; +} +/** + * A mutation that modifies fields of the document at the given key with the + * given values. The values are applied through a field mask: + * + * * When a field is in both the mask and the values, the corresponding field + * is updated. + * * When a field is in neither the mask nor the values, the corresponding + * field is unmodified. + * * When a field is in the mask but not in the values, the corresponding field + * is deleted. + * * When a field is not in the mask but is in the values, the values map is + * ignored. + */ +export declare class PatchMutation extends Mutation { + readonly key: DocumentKey; + readonly data: ObjectValue; + readonly fieldMask: FieldMask; + readonly precondition: Precondition; + readonly fieldTransforms: FieldTransform[]; + constructor(key: DocumentKey, data: ObjectValue, fieldMask: FieldMask, precondition: Precondition, fieldTransforms?: FieldTransform[]); + readonly type: MutationType; + getFieldMask(): FieldMask | null; +} +/** A mutation that deletes the document at the given key. */ +export declare class DeleteMutation extends Mutation { + readonly key: DocumentKey; + readonly precondition: Precondition; + constructor(key: DocumentKey, precondition: Precondition); + readonly type: MutationType; + readonly fieldTransforms: FieldTransform[]; + getFieldMask(): FieldMask | null; +} +/** + * A mutation that verifies the existence of the document at the given key with + * the provided precondition. + * + * The `verify` operation is only used in Transactions, and this class serves + * primarily to facilitate serialization into protos. + */ +export declare class VerifyMutation extends Mutation { + readonly key: DocumentKey; + readonly precondition: Precondition; + constructor(key: DocumentKey, precondition: Precondition); + readonly type: MutationType; + readonly fieldTransforms: FieldTransform[]; + getFieldMask(): FieldMask | null; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/mutation_batch.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/mutation_batch.d.ts new file mode 100644 index 0000000..c05b01e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/mutation_batch.d.ts @@ -0,0 +1,88 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { BatchId } from '../core/types'; +import { Timestamp } from '../lite-api/timestamp'; +import { DocumentKeySet, MutationMap, DocumentVersionMap, OverlayedDocumentMap } from './collections'; +import { MutableDocument } from './document'; +import { FieldMask } from './field_mask'; +import { Mutation, MutationResult } from './mutation'; +/** + * A batch of mutations that will be sent as one unit to the backend. + */ +export declare class MutationBatch { + batchId: BatchId; + localWriteTime: Timestamp; + baseMutations: Mutation[]; + mutations: Mutation[]; + /** + * @param batchId - The unique ID of this mutation batch. + * @param localWriteTime - The original write time of this mutation. + * @param baseMutations - Mutations that are used to populate the base + * values when this mutation is applied locally. This can be used to locally + * overwrite values that are persisted in the remote document cache. Base + * mutations are never sent to the backend. + * @param mutations - The user-provided mutations in this mutation batch. + * User-provided mutations are applied both locally and remotely on the + * backend. + */ + constructor(batchId: BatchId, localWriteTime: Timestamp, baseMutations: Mutation[], mutations: Mutation[]); + /** + * Applies all the mutations in this MutationBatch to the specified document + * to compute the state of the remote document + * + * @param document - The document to apply mutations to. + * @param batchResult - The result of applying the MutationBatch to the + * backend. + */ + applyToRemoteDocument(document: MutableDocument, batchResult: MutationBatchResult): void; + /** + * Computes the local view of a document given all the mutations in this + * batch. + * + * @param document - The document to apply mutations to. + * @param mutatedFields - Fields that have been updated before applying this mutation batch. + * @returns A `FieldMask` representing all the fields that are mutated. + */ + applyToLocalView(document: MutableDocument, mutatedFields: FieldMask | null): FieldMask | null; + /** + * Computes the local view for all provided documents given the mutations in + * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to + * replace all the mutation applications. + */ + applyToLocalDocumentSet(documentMap: OverlayedDocumentMap, documentsWithoutRemoteVersion: DocumentKeySet): MutationMap; + keys(): DocumentKeySet; + isEqual(other: MutationBatch): boolean; +} +/** The result of applying a mutation batch to the backend. */ +export declare class MutationBatchResult { + readonly batch: MutationBatch; + readonly commitVersion: SnapshotVersion; + readonly mutationResults: MutationResult[]; + /** + * A pre-computed mapping from each mutated document to the resulting + * version. + */ + readonly docVersions: DocumentVersionMap; + private constructor(); + /** + * Creates a new MutationBatchResult for the given batch and results. There + * must be one result for each mutation in the batch. This static factory + * caches a document=>version mapping (docVersions). + */ + static from(batch: MutationBatch, commitVersion: SnapshotVersion, results: MutationResult[]): MutationBatchResult; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/normalize.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/normalize.d.ts new file mode 100644 index 0000000..c279ba7 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/normalize.d.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Timestamp } from '../protos/firestore_proto_api'; +import { ByteString } from '../util/byte_string'; +/** + * Converts the possible Proto values for a timestamp value into a "seconds and + * nanos" representation. + */ +export declare function normalizeTimestamp(date: Timestamp): { + seconds: number; + nanos: number; +}; +/** + * Converts the possible Proto types for numbers into a JavaScript number. + * Returns 0 if the value is not numeric. + */ +export declare function normalizeNumber(value: number | string | undefined): number; +/** Converts the possible Proto types for Blobs into a ByteString. */ +export declare function normalizeByteString(blob: string | Uint8Array): ByteString; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/object_value.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/object_value.d.ts new file mode 100644 index 0000000..d299e86 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/object_value.d.ts @@ -0,0 +1,78 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { MapValue as ProtoMapValue, Value as ProtoValue } from '../protos/firestore_proto_api'; +import { FieldMask } from './field_mask'; +import { FieldPath } from './path'; +export interface JsonObject { + [name: string]: T; +} +/** + * An ObjectValue represents a MapValue in the Firestore Proto and offers the + * ability to add and remove fields (via the ObjectValueBuilder). + */ +export declare class ObjectValue { + readonly value: { + mapValue: ProtoMapValue; + }; + constructor(value: { + mapValue: ProtoMapValue; + }); + static empty(): ObjectValue; + /** + * Returns the value at the given path or null. + * + * @param path - the path to search + * @returns The value at the path or null if the path is not set. + */ + field(path: FieldPath): ProtoValue | null; + /** + * Sets the field to the provided value. + * + * @param path - The field path to set. + * @param value - The value to set. + */ + set(path: FieldPath, value: ProtoValue): void; + /** + * Sets the provided fields to the provided values. + * + * @param data - A map of fields to values (or null for deletes). + */ + setAll(data: Map): void; + /** + * Removes the field at the specified path. If there is no field at the + * specified path, nothing is changed. + * + * @param path - The field path to remove. + */ + delete(path: FieldPath): void; + isEqual(other: ObjectValue): boolean; + /** + * Returns the map that contains the leaf element of `path`. If the parent + * entry does not yet exist, or if it is not a map, a new map will be created. + */ + private getFieldsMap; + /** + * Modifies `fieldsMap` by adding, replacing or deleting the specified + * entries. + */ + private applyChanges; + clone(): ObjectValue; +} +/** + * Returns a FieldMask built from all fields in a MapValue. + */ +export declare function extractFieldMask(value: ProtoMapValue): FieldMask; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/overlay.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/overlay.d.ts new file mode 100644 index 0000000..ef90621 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/overlay.d.ts @@ -0,0 +1,32 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentKey } from './document_key'; +import { Mutation } from './mutation'; +/** + * Representation of an overlay computed by Firestore. + * + * Holds information about a mutation and the largest batch id in Firestore when + * the mutation was created. + */ +export declare class Overlay { + readonly largestBatchId: number; + readonly mutation: Mutation; + constructor(largestBatchId: number, mutation: Mutation); + getKey(): DocumentKey; + isEqual(other: Overlay | null): boolean; + toString(): string; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/path.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/path.d.ts new file mode 100644 index 0000000..a33f0e8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/path.d.ts @@ -0,0 +1,121 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare const DOCUMENT_KEY_NAME = "__name__"; +/** + * Path represents an ordered sequence of string segments. + */ +declare abstract class BasePath> { + private segments; + private offset; + private len; + constructor(segments: string[], offset?: number, length?: number); + /** + * Abstract constructor method to construct an instance of B with the given + * parameters. + */ + protected abstract construct(segments: string[], offset?: number, length?: number): B; + /** + * Returns a String representation. + * + * Implementing classes are required to provide deterministic implementations as + * the String representation is used to obtain canonical Query IDs. + */ + abstract toString(): string; + get length(): number; + isEqual(other: B): boolean; + child(nameOrPath: string | B): B; + /** The index of one past the last segment of the path. */ + private limit; + popFirst(size?: number): B; + popLast(): B; + firstSegment(): string; + lastSegment(): string; + get(index: number): string; + isEmpty(): boolean; + isPrefixOf(other: this): boolean; + isImmediateParentOf(potentialChild: this): boolean; + forEach(fn: (segment: string) => void): void; + toArray(): string[]; + /** + * Compare 2 paths segment by segment, prioritizing numeric IDs + * (e.g., "__id123__") in numeric ascending order, followed by string + * segments in lexicographical order. + */ + static comparator>(p1: BasePath, p2: BasePath): number; + private static compareSegments; + private static isNumericId; + private static extractNumericId; +} +/** + * A slash-separated path for navigating resources (documents and collections) + * within Firestore. + * + * @internal + */ +export declare class ResourcePath extends BasePath { + protected construct(segments: string[], offset?: number, length?: number): ResourcePath; + canonicalString(): string; + toString(): string; + /** + * Returns a string representation of this path + * where each path segment has been encoded with + * `encodeURIComponent`. + */ + toUriEncodedString(): string; + /** + * Creates a resource path from the given slash-delimited string. If multiple + * arguments are provided, all components are combined. Leading and trailing + * slashes from all components are ignored. + */ + static fromString(...pathComponents: string[]): ResourcePath; + static emptyPath(): ResourcePath; +} +/** + * A dot-separated path for navigating sub-objects within a document. + * @internal + */ +export declare class FieldPath extends BasePath { + protected construct(segments: string[], offset?: number, length?: number): FieldPath; + /** + * Returns true if the string could be used as a segment in a field path + * without escaping. + */ + private static isValidIdentifier; + canonicalString(): string; + toString(): string; + /** + * Returns true if this field references the key of a document. + */ + isKeyField(): boolean; + /** + * The field designating the key of a document. + */ + static keyField(): FieldPath; + /** + * Parses a field string from the given server-formatted string. + * + * - Splitting the empty string is not allowed (for now at least). + * - Empty segments within the string (e.g. if there are two consecutive + * separators) are not allowed. + * + * TODO(b/37244157): we should make this more strict. Right now, it allows + * non-identifier path components, even if they aren't escaped. + */ + static fromServerFormat(path: string): FieldPath; + static emptyPath(): FieldPath; +} +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/server_timestamps.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/server_timestamps.d.ts new file mode 100644 index 0000000..d4e8c4a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/server_timestamps.d.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Timestamp } from '../lite-api/timestamp'; +import { Value as ProtoValue } from '../protos/firestore_proto_api'; +export declare function isServerTimestamp(value: ProtoValue | null): boolean; +/** + * Creates a new ServerTimestamp proto value (using the internal format). + */ +export declare function serverTimestamp(localWriteTime: Timestamp, previousValue: ProtoValue | null): ProtoValue; +/** + * Returns the value of the field before this ServerTimestamp was set. + * + * Preserving the previous values allows the user to display the last resoled + * value until the backend responds with the timestamp. + */ +export declare function getPreviousValue(value: ProtoValue): ProtoValue | null; +/** + * Returns the local time at which this timestamp was first set. + */ +export declare function getLocalWriteTime(value: ProtoValue): Timestamp; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/target_index_matcher.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/target_index_matcher.d.ts new file mode 100644 index 0000000..d313f1e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/target_index_matcher.d.ts @@ -0,0 +1,76 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Target } from '../core/target'; +import { FieldIndex } from './field_index'; +/** + * A light query planner for Firestore. + * + * This class matches a `FieldIndex` against a Firestore Query `Target`. It + * determines whether a given index can be used to serve the specified target. + * + * The following table showcases some possible index configurations: + * + * Query | Index + * ----------------------------------------------------------------------------- + * where('a', '==', 'a').where('b', '==', 'b') | a ASC, b DESC + * where('a', '==', 'a').where('b', '==', 'b') | a ASC + * where('a', '==', 'a').where('b', '==', 'b') | b DESC + * where('a', '>=', 'a').orderBy('a') | a ASC + * where('a', '>=', 'a').orderBy('a', 'desc') | a DESC + * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC, b ASC + * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC + * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS, b ASCENDING + * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS + */ +export declare class TargetIndexMatcher { + private readonly collectionId; + private inequalityFilters; + private readonly equalityFilters; + private readonly orderBys; + constructor(target: Target); + get hasMultipleInequality(): boolean; + /** + * Returns whether the index can be used to serve the TargetIndexMatcher's + * target. + * + * An index is considered capable of serving the target when: + * - The target uses all index segments for its filters and orderBy clauses. + * The target can have additional filter and orderBy clauses, but not + * fewer. + * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also + * have a corresponding `CONTAINS` segment. + * - All directional index segments can be mapped to the target as a series of + * equality filters, a single inequality filter and a series of orderBy + * clauses. + * - The segments that represent the equality filters may appear out of order. + * - The optional segment for the inequality filter must appear after all + * equality segments. + * - The segments that represent that orderBy clause of the target must appear + * in order after all equality and inequality segments. Single orderBy + * clauses cannot be skipped, but a continuous orderBy suffix may be + * omitted. + */ + servedByIndex(index: FieldIndex): boolean; + /** + * Returns a full matched field index for this target. Currently multiple + * inequality query is not supported so function returns null. + */ + buildTargetIndex(): FieldIndex | null; + private hasMatchingEqualityFilter; + private matchesFilter; + private matchesOrderBy; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/transform_operation.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/transform_operation.d.ts new file mode 100644 index 0000000..be1e0f3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/transform_operation.d.ts @@ -0,0 +1,75 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Timestamp } from '../lite-api/timestamp'; +import { Value as ProtoValue } from '../protos/firestore_proto_api'; +import { Serializer } from '../remote/number_serializer'; +/** Used to represent a field transform on a mutation. */ +export declare class TransformOperation { + private _; +} +/** + * Computes the local transform result against the provided `previousValue`, + * optionally using the provided localWriteTime. + */ +export declare function applyTransformOperationToLocalView(transform: TransformOperation, previousValue: ProtoValue | null, localWriteTime: Timestamp): ProtoValue; +/** + * Computes a final transform result after the transform has been acknowledged + * by the server, potentially using the server-provided transformResult. + */ +export declare function applyTransformOperationToRemoteDocument(transform: TransformOperation, previousValue: ProtoValue | null, transformResult: ProtoValue | null): ProtoValue; +/** + * If this transform operation is not idempotent, returns the base value to + * persist for this transform. If a base value is returned, the transform + * operation is always applied to this base value, even if document has + * already been updated. + * + * Base values provide consistent behavior for non-idempotent transforms and + * allow us to return the same latency-compensated value even if the backend + * has already applied the transform operation. The base value is null for + * idempotent transforms, as they can be re-played even if the backend has + * already applied them. + * + * @returns a base value to store along with the mutation, or null for + * idempotent transforms. + */ +export declare function computeTransformOperationBaseValue(transform: TransformOperation, previousValue: ProtoValue | null): ProtoValue | null; +export declare function transformOperationEquals(left: TransformOperation, right: TransformOperation): boolean; +/** Transforms a value into a server-generated timestamp. */ +export declare class ServerTimestampTransform extends TransformOperation { +} +/** Transforms an array value via a union operation. */ +export declare class ArrayUnionTransformOperation extends TransformOperation { + readonly elements: ProtoValue[]; + constructor(elements: ProtoValue[]); +} +/** Transforms an array value via a remove operation. */ +export declare class ArrayRemoveTransformOperation extends TransformOperation { + readonly elements: ProtoValue[]; + constructor(elements: ProtoValue[]); +} +/** + * Implements the backend semantics for locally computed NUMERIC_ADD (increment) + * transforms. Converts all field values to integers or doubles, but unlike the + * backend does not cap integer values at 2^63. Instead, JavaScript number + * arithmetic is used and precision loss can occur for values greater than 2^53. + */ +export declare class NumericIncrementTransformOperation extends TransformOperation { + readonly serializer: Serializer; + readonly operand: ProtoValue; + constructor(serializer: Serializer, operand: ProtoValue); +} +export declare function applyNumericIncrementTransformOperationToLocalView(transform: NumericIncrementTransformOperation, previousValue: ProtoValue | null): ProtoValue; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/type_order.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/type_order.d.ts new file mode 100644 index 0000000..bb09c39 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/type_order.d.ts @@ -0,0 +1,38 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * All the different kinds of values that can be stored in fields in + * a document. The types of the same comparison order should be defined + * together as a group. The order of each group is defined by the Firestore + * backend and is available at: + * https://firebase.google.com/docs/firestore/manage-data/data-types + */ +export declare const enum TypeOrder { + NullValue = 0, + BooleanValue = 1, + NumberValue = 2, + TimestampValue = 3, + ServerTimestampValue = 4, + StringValue = 5, + BlobValue = 6, + RefValue = 7, + GeoPointValue = 8, + ArrayValue = 9, + VectorValue = 10, + ObjectValue = 11, + MaxValue = 9007199254740991 +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/values.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/values.d.ts new file mode 100644 index 0000000..94b377f --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/model/values.d.ts @@ -0,0 +1,114 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseId } from '../core/database_info'; +import { ArrayValue, MapValue, Value as ProtoValue, Value } from '../protos/firestore_proto_api'; +import { DocumentKey } from './document_key'; +import { TypeOrder } from './type_order'; +export declare const TYPE_KEY = "__type__"; +export declare const MAX_VALUE: Value; +export declare const VECTOR_VALUE_SENTINEL = "__vector__"; +export declare const VECTOR_MAP_VECTORS_KEY = "value"; +export declare const MIN_VALUE: Value; +/** Extracts the backend's type order for the provided value. */ +export declare function typeOrder(value: Value): TypeOrder; +/** Tests `left` and `right` for equality based on the backend semantics. */ +export declare function valueEquals(left: Value, right: Value): boolean; +export declare function numberEquals(left: Value, right: Value): boolean; +/** Returns true if the ArrayValue contains the specified element. */ +export declare function arrayValueContains(haystack: ArrayValue, needle: Value): boolean; +export declare function valueCompare(left: Value, right: Value): number; +/** + * Generates the canonical ID for the provided field value (as used in Target + * serialization). + */ +export declare function canonicalId(value: Value): string; +/** + * Returns an approximate (and wildly inaccurate) in-memory size for the field + * value. + * + * The memory size takes into account only the actual user data as it resides + * in memory and ignores object overhead. + */ +export declare function estimateByteSize(value: Value): number; +/** Returns a reference value for the provided database and key. */ +export declare function refValue(databaseId: DatabaseId, key: DocumentKey): Value; +/** Returns true if `value` is an IntegerValue . */ +export declare function isInteger(value?: Value | null): value is { + integerValue: string | number; +}; +/** Returns true if `value` is a DoubleValue. */ +export declare function isDouble(value?: Value | null): value is { + doubleValue: string | number; +}; +/** Returns true if `value` is either an IntegerValue or a DoubleValue. */ +export declare function isNumber(value?: Value | null): boolean; +/** Returns true if `value` is an ArrayValue. */ +export declare function isArray(value?: Value | null): value is { + arrayValue: ArrayValue; +}; +/** Returns true if `value` is a ReferenceValue. */ +export declare function isReferenceValue(value?: Value | null): value is { + referenceValue: string; +}; +/** Returns true if `value` is a NullValue. */ +export declare function isNullValue(value?: Value | null): value is { + nullValue: 'NULL_VALUE'; +}; +/** Returns true if `value` is NaN. */ +export declare function isNanValue(value?: Value | null): value is { + doubleValue: 'NaN' | number; +}; +/** Returns true if `value` is a MapValue. */ +export declare function isMapValue(value?: Value | null): value is { + mapValue: MapValue; +}; +/** Returns true if `value` is a VetorValue. */ +export declare function isVectorValue(value: ProtoValue | null): boolean; +/** Creates a deep copy of `source`. */ +export declare function deepClone(source: Value): Value; +/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ +export declare function isMaxValue(value: Value): boolean; +export declare const MIN_VECTOR_VALUE: { + mapValue: { + fields: { + __type__: { + stringValue: string; + }; + value: { + arrayValue: {}; + }; + }; + }; +}; +/** Returns the lowest value for the given value type (inclusive). */ +export declare function valuesGetLowerBound(value: Value): Value; +/** Returns the largest value for the given value type (exclusive). */ +export declare function valuesGetUpperBound(value: Value): Value; +export declare function lowerBoundCompare(left: { + value: Value; + inclusive: boolean; +}, right: { + value: Value; + inclusive: boolean; +}): number; +export declare function upperBoundCompare(left: { + value: Value; + inclusive: boolean; +}, right: { + value: Value; + inclusive: boolean; +}): number; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/base64.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/base64.d.ts new file mode 100644 index 0000000..999f234 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/base64.d.ts @@ -0,0 +1,25 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Converts a Base64 encoded string to a binary string. */ +export declare function decodeBase64(encoded: string): string; +/** Converts a binary string to a Base64 encoded string. */ +export declare function encodeBase64(raw: string): string; +/** + * True if and only if the Base64 conversion functions are available. + * @internal + */ +export declare function isBase64Available(): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/base64.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/base64.d.ts new file mode 100644 index 0000000..9ea2985 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/base64.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Converts a Base64 encoded string to a binary string. */ +export declare function decodeBase64(encoded: string): string; +/** Converts a binary string to a Base64 encoded string. */ +export declare function encodeBase64(raw: string): string; +/** True if and only if the Base64 conversion functions are available. */ +export declare function isBase64Available(): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/byte_stream_reader.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/byte_stream_reader.d.ts new file mode 100644 index 0000000..2b95861 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/byte_stream_reader.d.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BundleSource } from '../../util/bundle_reader'; +/** + * On web, a `ReadableStream` is wrapped around by a `ByteStreamReader`. + */ +export declare function toByteStreamReader(source: BundleSource, bytesPerRead: number): ReadableStreamDefaultReader; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/connection.d.ts new file mode 100644 index 0000000..9e35cd8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/connection.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseInfo } from '../../core/database_info'; +import { Connection } from '../../remote/connection'; +import { ConnectivityMonitor } from '../../remote/connectivity_monitor'; +/** Initializes the WebChannelConnection for the browser. */ +export declare function newConnection(databaseInfo: DatabaseInfo): Connection; +/** Return the Platform-specific connectivity monitor. */ +export declare function newConnectivityMonitor(): ConnectivityMonitor; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/connectivity_monitor.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/connectivity_monitor.d.ts new file mode 100644 index 0000000..0f14bb7 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/connectivity_monitor.d.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ConnectivityMonitor, NetworkStatus } from '../../remote/connectivity_monitor'; +/** + * Browser implementation of ConnectivityMonitor. + */ +export declare class BrowserConnectivityMonitor implements ConnectivityMonitor { + private readonly networkAvailableListener; + private readonly networkUnavailableListener; + private callbacks; + constructor(); + addCallback(callback: (status: NetworkStatus) => void): void; + shutdown(): void; + private configureNetworkMonitoring; + private onNetworkAvailable; + private onNetworkUnavailable; + /** Checks that all used attributes of window are available. */ + static isAvailable(): boolean; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/dom.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/dom.d.ts new file mode 100644 index 0000000..d2a5319 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/dom.d.ts @@ -0,0 +1,20 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** The Platform's 'window' implementation or null if not available. */ +export declare function getWindow(): Window | null; +/** The Platform's 'document' implementation or null if not available. */ +export declare function getDocument(): Document | null; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/format_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/format_json.d.ts new file mode 100644 index 0000000..5e5f7ad --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/format_json.d.ts @@ -0,0 +1,18 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Formats an object as a JSON string, suitable for logging. */ +export declare function formatJSON(value: unknown): string; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/random_bytes.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/random_bytes.d.ts new file mode 100644 index 0000000..672e612 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/random_bytes.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Generates `nBytes` of random bytes. + * + * If `nBytes < 0` , an error will be thrown. + */ +export declare function randomBytes(nBytes: number): Uint8Array; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/serializer.d.ts new file mode 100644 index 0000000..839e680 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/serializer.d.ts @@ -0,0 +1,20 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Return the Platform-specific serializer monitor. */ +import { DatabaseId } from '../../core/database_info'; +import { JsonProtoSerializer } from '../../remote/serializer'; +export declare function newSerializer(databaseId: DatabaseId): JsonProtoSerializer; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/snapshot_to_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/snapshot_to_json.d.ts new file mode 100644 index 0000000..6a75f06 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/snapshot_to_json.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Return the Platform-specific build JSON bundle implementations. */ +import { Firestore } from '../../api/database'; +import { Query } from '../../core/query'; +import { DocumentData } from '../../lite-api/reference'; +import { Document } from '../../model/document'; +export declare function buildDocumentSnapshotJsonBundle(db: Firestore, document: Document, docData: DocumentData, path: string): string; +export declare function buildQuerySnapshotJsonBundle(db: Firestore, query: Query, bundleName: string, parent: string, paths: string[], docs: Document[], documentData: DocumentData[]): string; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/text_serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/text_serializer.d.ts new file mode 100644 index 0000000..47213fb --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/text_serializer.d.ts @@ -0,0 +1,24 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An instance of the Platform's 'TextEncoder' implementation. + */ +export declare function newTextEncoder(): TextEncoder; +/** + * An instance of the Platform's 'TextDecoder' implementation. + */ +export declare function newTextDecoder(): TextDecoder; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/webchannel_connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/webchannel_connection.d.ts new file mode 100644 index 0000000..79117f7 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser/webchannel_connection.d.ts @@ -0,0 +1,47 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { WebChannel } from '@firebase/webchannel-wrapper/webchannel-blob'; +import { Token } from '../../api/credentials'; +import { DatabaseInfo } from '../../core/database_info'; +import { Stream } from '../../remote/connection'; +import { RestConnection } from '../../remote/rest_connection'; +import { StringMap } from '../../util/types'; +export declare class WebChannelConnection extends RestConnection { + private readonly forceLongPolling; + private readonly autoDetectLongPolling; + private readonly useFetchStreams; + private readonly longPollingOptions; + /** A collection of open WebChannel instances */ + private openWebChannels; + constructor(info: DatabaseInfo); + protected performRPCRequest(rpcName: string, url: string, headers: StringMap, body: Req, _forwardCredentials: boolean): Promise; + openStream(rpcName: string, authToken: Token | null, appCheckToken: Token | null): Stream; + /** + * Closes and cleans up any resources associated with the connection. + */ + terminate(): void; + /** + * Add a WebChannel instance to the collection of open instances. + * @param webChannel + */ + addOpenWebChannel(webChannel: WebChannel): void; + /** + * Remove a WebChannel instance from the collection of open instances. + * @param webChannel + */ + removeOpenWebChannel(webChannel: WebChannel): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/base64.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/base64.d.ts new file mode 100644 index 0000000..ae35760 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/base64.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser/base64'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/byte_stream_reader.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/byte_stream_reader.d.ts new file mode 100644 index 0000000..c91280a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/byte_stream_reader.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser/byte_stream_reader'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/connection.d.ts new file mode 100644 index 0000000..b347f61 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/connection.d.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseInfo } from '../../core/database_info'; +import { Connection } from '../../remote/connection'; +export { newConnectivityMonitor } from '../browser/connection'; +/** Initializes the HTTP connection for the REST API. */ +export declare function newConnection(databaseInfo: DatabaseInfo): Connection; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/dom.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/dom.d.ts new file mode 100644 index 0000000..778555d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/dom.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser/dom'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/fetch_connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/fetch_connection.d.ts new file mode 100644 index 0000000..88105c0 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/fetch_connection.d.ts @@ -0,0 +1,28 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Token } from '../../api/credentials'; +import { Stream } from '../../remote/connection'; +import { RestConnection } from '../../remote/rest_connection'; +import { StringMap } from '../../util/types'; +/** + * A Rest-based connection that relies on the native HTTP stack + * (e.g. `fetch` or a polyfill). + */ +export declare class FetchConnection extends RestConnection { + openStream(rpcName: string, token: Token | null): Stream; + protected performRPCRequest(rpcName: string, url: string, headers: StringMap, body: Req, forwardCredentials: boolean): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/format_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/format_json.d.ts new file mode 100644 index 0000000..a9a0b71 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/format_json.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser/format_json'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/random_bytes.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/random_bytes.d.ts new file mode 100644 index 0000000..52e5798 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/random_bytes.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser/random_bytes'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/serializer.d.ts new file mode 100644 index 0000000..609f24f --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/serializer.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser/serializer'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/snapshot_to_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/snapshot_to_json.d.ts new file mode 100644 index 0000000..2ed408c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/snapshot_to_json.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser/snapshot_to_json'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/text_serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/text_serializer.d.ts new file mode 100644 index 0000000..a032af0 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/browser_lite/text_serializer.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser/text_serializer'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/byte_stream_reader.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/byte_stream_reader.d.ts new file mode 100644 index 0000000..566291c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/byte_stream_reader.d.ts @@ -0,0 +1,18 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BundleSource } from '../util/bundle_reader'; +export declare function toByteStreamReader(source: BundleSource, bytesPerRead?: number): ReadableStreamDefaultReader; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/connection.d.ts new file mode 100644 index 0000000..0fba574 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/connection.d.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseInfo } from '../core/database_info'; +import { Connection } from '../remote/connection'; +import { ConnectivityMonitor } from '../remote/connectivity_monitor'; +export declare function newConnectivityMonitor(): ConnectivityMonitor; +export declare function newConnection(databaseInfo: DatabaseInfo): Connection; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/dom.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/dom.d.ts new file mode 100644 index 0000000..d2a5319 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/dom.d.ts @@ -0,0 +1,20 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** The Platform's 'window' implementation or null if not available. */ +export declare function getWindow(): Window | null; +/** The Platform's 'document' implementation or null if not available. */ +export declare function getDocument(): Document | null; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/format_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/format_json.d.ts new file mode 100644 index 0000000..5e5f7ad --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/format_json.d.ts @@ -0,0 +1,18 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Formats an object as a JSON string, suitable for logging. */ +export declare function formatJSON(value: unknown): string; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/base64.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/base64.d.ts new file mode 100644 index 0000000..9ea2985 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/base64.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Converts a Base64 encoded string to a binary string. */ +export declare function decodeBase64(encoded: string): string; +/** Converts a binary string to a Base64 encoded string. */ +export declare function encodeBase64(raw: string): string; +/** True if and only if the Base64 conversion functions are available. */ +export declare function isBase64Available(): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/byte_stream_reader.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/byte_stream_reader.d.ts new file mode 100644 index 0000000..efbd79a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/byte_stream_reader.d.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BundleSource } from '../../util/bundle_reader'; +/** + * On Node, only supported data source is a `Uint8Array` for now. + */ +export declare function toByteStreamReader(source: BundleSource, bytesPerRead: number): ReadableStreamDefaultReader; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/connection.d.ts new file mode 100644 index 0000000..3be3c14 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/connection.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseInfo } from '../../core/database_info'; +import { Connection } from '../../remote/connection'; +import { ConnectivityMonitor } from '../../remote/connectivity_monitor'; +/** Loads the GRPC stack */ +export declare function newConnection(databaseInfo: DatabaseInfo): Connection; +/** Return the Platform-specific connectivity monitor. */ +export declare function newConnectivityMonitor(): ConnectivityMonitor; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/dom.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/dom.d.ts new file mode 100644 index 0000000..d2a5319 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/dom.d.ts @@ -0,0 +1,20 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** The Platform's 'window' implementation or null if not available. */ +export declare function getWindow(): Window | null; +/** The Platform's 'document' implementation or null if not available. */ +export declare function getDocument(): Document | null; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/format_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/format_json.d.ts new file mode 100644 index 0000000..5e5f7ad --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/format_json.d.ts @@ -0,0 +1,18 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Formats an object as a JSON string, suitable for logging. */ +export declare function formatJSON(value: unknown): string; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/grpc_connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/grpc_connection.d.ts new file mode 100644 index 0000000..30cd921 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/grpc_connection.d.ts @@ -0,0 +1,43 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as grpc from '@grpc/grpc-js'; +import { Token } from '../../api/credentials'; +import { DatabaseInfo } from '../../core/database_info'; +import { ResourcePath } from '../../model/path'; +import { Connection, Stream } from '../../remote/connection'; +/** + * A Connection implemented by GRPC-Node. + */ +export declare class GrpcConnection implements Connection { + private databaseInfo; + private readonly databasePath; + private readonly firestore; + private cachedStub; + get shouldResourcePathBeIncludedInRequest(): boolean; + constructor(protos: grpc.GrpcObject, databaseInfo: DatabaseInfo); + private ensureActiveStub; + invokeRPC(rpcName: string, path: ResourcePath, request: Req, authToken: Token | null, appCheckToken: Token | null): Promise; + invokeStreamingRPC(rpcName: string, path: ResourcePath, request: Req, authToken: Token | null, appCheckToken: Token | null, expectedResponseCount?: number): Promise; + openStream(rpcName: string, authToken: Token | null, appCheckToken: Token | null): Stream; + /** + * Closes and cleans up any resources associated with the GrpcConnection. + * If a gRPC client has been generated for this connection, the gRPC client + * is closed. Failure to call terminate on a GrpcConnection can result + * in leaked resources of the gRPC client. + */ + terminate(): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/load_protos.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/load_protos.d.ts new file mode 100644 index 0000000..f05a0e6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/load_protos.d.ts @@ -0,0 +1,28 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as grpc from '@grpc/grpc-js'; +import { IConversionOptions, Root } from 'protobufjs'; +/** Used by tests so we can match @grpc/proto-loader behavior. */ +export declare const protoLoaderOptions: IConversionOptions; +/** + * Loads the protocol buffer definitions for Firestore. + * + * @returns The GrpcObject representing our protos. + */ +export declare function loadProtos(): grpc.GrpcObject; +/** Used by tests so we can directly create ProtobufJS proto message objects from JSON protos. */ +export declare function loadRawProtos(): Root; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/random_bytes.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/random_bytes.d.ts new file mode 100644 index 0000000..672e612 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/random_bytes.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Generates `nBytes` of random bytes. + * + * If `nBytes < 0` , an error will be thrown. + */ +export declare function randomBytes(nBytes: number): Uint8Array; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/serializer.d.ts new file mode 100644 index 0000000..839e680 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/serializer.d.ts @@ -0,0 +1,20 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Return the Platform-specific serializer monitor. */ +import { DatabaseId } from '../../core/database_info'; +import { JsonProtoSerializer } from '../../remote/serializer'; +export declare function newSerializer(databaseId: DatabaseId): JsonProtoSerializer; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/snapshot_to_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/snapshot_to_json.d.ts new file mode 100644 index 0000000..6a75f06 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/snapshot_to_json.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Return the Platform-specific build JSON bundle implementations. */ +import { Firestore } from '../../api/database'; +import { Query } from '../../core/query'; +import { DocumentData } from '../../lite-api/reference'; +import { Document } from '../../model/document'; +export declare function buildDocumentSnapshotJsonBundle(db: Firestore, document: Document, docData: DocumentData, path: string): string; +export declare function buildQuerySnapshotJsonBundle(db: Firestore, query: Query, bundleName: string, parent: string, paths: string[], docs: Document[], documentData: DocumentData[]): string; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/text_serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/text_serializer.d.ts new file mode 100644 index 0000000..f88ff0c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node/text_serializer.d.ts @@ -0,0 +1,25 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { TextDecoder, TextEncoder } from 'util'; +/** + * An instance of the Platform's 'TextEncoder' implementation. + */ +export declare function newTextEncoder(): TextEncoder; +/** + * An instance of the Platform's 'TextDecoder' implementation. + */ +export declare function newTextDecoder(): TextDecoder; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/base64.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/base64.d.ts new file mode 100644 index 0000000..2d95aff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/base64.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../node/base64'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/byte_stream_reader.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/byte_stream_reader.d.ts new file mode 100644 index 0000000..543020e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/byte_stream_reader.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../node/byte_stream_reader'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/connection.d.ts new file mode 100644 index 0000000..b347f61 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/connection.d.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseInfo } from '../../core/database_info'; +import { Connection } from '../../remote/connection'; +export { newConnectivityMonitor } from '../browser/connection'; +/** Initializes the HTTP connection for the REST API. */ +export declare function newConnection(databaseInfo: DatabaseInfo): Connection; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/dom.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/dom.d.ts new file mode 100644 index 0000000..6c880e0 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/dom.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../node/dom'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/format_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/format_json.d.ts new file mode 100644 index 0000000..428b6d9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/format_json.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../node/format_json'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/random_bytes.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/random_bytes.d.ts new file mode 100644 index 0000000..132614e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/random_bytes.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../node/random_bytes'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/serializer.d.ts new file mode 100644 index 0000000..dcf50ac --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/serializer.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser_lite/serializer'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/snapshot_to_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/snapshot_to_json.d.ts new file mode 100644 index 0000000..c85016c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/snapshot_to_json.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../node/snapshot_to_json'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/text_serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/text_serializer.d.ts new file mode 100644 index 0000000..3a5069e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/node_lite/text_serializer.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser_lite/text_serializer'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/random_bytes.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/random_bytes.d.ts new file mode 100644 index 0000000..672e612 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/random_bytes.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Generates `nBytes` of random bytes. + * + * If `nBytes < 0` , an error will be thrown. + */ +export declare function randomBytes(nBytes: number): Uint8Array; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/base64.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/base64.d.ts new file mode 100644 index 0000000..9ea2985 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/base64.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Converts a Base64 encoded string to a binary string. */ +export declare function decodeBase64(encoded: string): string; +/** Converts a binary string to a Base64 encoded string. */ +export declare function encodeBase64(raw: string): string; +/** True if and only if the Base64 conversion functions are available. */ +export declare function isBase64Available(): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/byte_stream_reader.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/byte_stream_reader.d.ts new file mode 100644 index 0000000..939290b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/byte_stream_reader.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { toByteStreamReader } from '../browser/byte_stream_reader'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/connection.d.ts new file mode 100644 index 0000000..da831d6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/connection.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { newConnection, newConnectivityMonitor } from '../browser/connection'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/dom.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/dom.d.ts new file mode 100644 index 0000000..4c629fc --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/dom.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { getWindow, getDocument } from '../browser/dom'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/format_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/format_json.d.ts new file mode 100644 index 0000000..d1d3dc7 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/format_json.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { formatJSON } from '../browser/format_json'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/random_bytes.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/random_bytes.d.ts new file mode 100644 index 0000000..6774017 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/random_bytes.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { randomBytes } from '../browser/random_bytes'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/serializer.d.ts new file mode 100644 index 0000000..c7a81ae --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/serializer.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { newSerializer } from '../browser/serializer'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/snapshot_to_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/snapshot_to_json.d.ts new file mode 100644 index 0000000..8ab87f6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/snapshot_to_json.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { buildDocumentSnapshotJsonBundle, buildQuerySnapshotJsonBundle } from '../browser/snapshot_to_json'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/text_serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/text_serializer.d.ts new file mode 100644 index 0000000..efcbff3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn/text_serializer.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { newTextEncoder, newTextDecoder } from '../browser/text_serializer'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/base64.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/base64.d.ts new file mode 100644 index 0000000..3d236cd --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/base64.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../rn/base64'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/byte_stream_reader.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/byte_stream_reader.d.ts new file mode 100644 index 0000000..9206b65 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/byte_stream_reader.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../rn/byte_stream_reader'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/connection.d.ts new file mode 100644 index 0000000..6509c0c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/connection.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser_lite/connection'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/dom.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/dom.d.ts new file mode 100644 index 0000000..0469362 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/dom.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../rn/dom'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/format_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/format_json.d.ts new file mode 100644 index 0000000..0a17cf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/format_json.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../rn/format_json'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/random_bytes.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/random_bytes.d.ts new file mode 100644 index 0000000..8ca59f3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/random_bytes.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../rn/random_bytes'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/serializer.d.ts new file mode 100644 index 0000000..dcf50ac --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/serializer.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser_lite/serializer'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/snapshot_to_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/snapshot_to_json.d.ts new file mode 100644 index 0000000..939290b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/snapshot_to_json.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { toByteStreamReader } from '../browser/byte_stream_reader'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/text_serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/text_serializer.d.ts new file mode 100644 index 0000000..3a5069e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/rn_lite/text_serializer.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser_lite/text_serializer'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/serializer.d.ts new file mode 100644 index 0000000..25f5533 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/serializer.d.ts @@ -0,0 +1,19 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseId } from '../core/database_info'; +import { JsonProtoSerializer } from '../remote/serializer'; +export declare function newSerializer(databaseId: DatabaseId): JsonProtoSerializer; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/snapshot_to_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/snapshot_to_json.d.ts new file mode 100644 index 0000000..83eadf0 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/snapshot_to_json.d.ts @@ -0,0 +1,28 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Firestore } from '../api/database'; +import { Query } from '../core/query'; +import { DocumentData } from '../lite-api/reference'; +import { Document } from '../model/document'; +/** + * Constructs the bundle data for a DocumentSnapshot used in its toJSON serialization. + */ +export declare function buildDocumentSnapshotJsonBundle(db: Firestore, document: Document, docData: DocumentData, path: string): string; +/** + * Constructs the bundle data for a QuerySnapshot used in its toJSON serialization. + */ +export declare function buildQuerySnapshotJsonBundle(db: Firestore, query: Query, bundleName: string, parent: string, paths: string[], docs: Document[], documentData: DocumentData[]): string; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/text_serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/text_serializer.d.ts new file mode 100644 index 0000000..47213fb --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/platform/text_serializer.d.ts @@ -0,0 +1,24 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An instance of the Platform's 'TextEncoder' implementation. + */ +export declare function newTextEncoder(): TextEncoder; +/** + * An instance of the Platform's 'TextDecoder' implementation. + */ +export declare function newTextDecoder(): TextDecoder; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/protos/firestore_bundle_proto.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/protos/firestore_bundle_proto.d.ts new file mode 100644 index 0000000..e3f7740 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/protos/firestore_bundle_proto.d.ts @@ -0,0 +1,72 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { StructuredQuery, Timestamp, Document } from './firestore_proto_api'; +/** Properties of a BundledQuery. */ +export interface BundledQuery { + /** BundledQuery parent */ + parent?: string | null; + /** BundledQuery structuredQuery */ + structuredQuery?: StructuredQuery | null; + /** BundledQuery limitType */ + limitType?: LimitType | null; +} +/** LimitType enum. */ +export type LimitType = 'FIRST' | 'LAST'; +/** Properties of a NamedQuery. */ +export interface NamedQuery { + /** NamedQuery name */ + name?: string | null; + /** NamedQuery bundledQuery */ + bundledQuery?: BundledQuery | null; + /** NamedQuery readTime */ + readTime?: Timestamp | null; +} +/** Properties of a BundledDocumentMetadata. */ +export interface BundledDocumentMetadata { + /** BundledDocumentMetadata name */ + name?: string | null; + /** BundledDocumentMetadata readTime */ + readTime?: Timestamp | null; + /** BundledDocumentMetadata exists */ + exists?: boolean | null; + /** The names of the queries in this bundle that this document matches to. */ + queries?: string[]; +} +/** Properties of a BundleMetadata. */ +export interface BundleMetadata { + /** BundleMetadata id */ + id?: string | null; + /** BundleMetadata createTime */ + createTime?: Timestamp | null; + /** BundleMetadata version */ + version?: number | null; + /** BundleMetadata totalDocuments */ + totalDocuments?: number | null; + /** BundleMetadata totalBytes */ + totalBytes?: number | null; +} +/** Properties of a BundleElement. */ +export interface BundleElement { + /** BundleElement metadata */ + metadata?: BundleMetadata | null; + /** BundleElement namedQuery */ + namedQuery?: NamedQuery | null; + /** BundleElement documentMetadata */ + documentMetadata?: BundledDocumentMetadata | null; + /** BundleElement document */ + document?: Document | null; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/protos/firestore_proto_api.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/protos/firestore_proto_api.d.ts new file mode 100644 index 0000000..5f37ee6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/protos/firestore_proto_api.d.ts @@ -0,0 +1,836 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare type ApiClientHookFactory = any; +export declare type PromiseRequestService = any; +export interface ApiClientObjectMap { + [k: string]: T; +} +export declare type Timestamp = string | { + seconds?: string | number; + nanos?: number; +}; +export declare type CompositeFilterOp = 'OPERATOR_UNSPECIFIED' | 'AND' | 'OR'; +export interface ICompositeFilterOpEnum { + OPERATOR_UNSPECIFIED: CompositeFilterOp; + AND: CompositeFilterOp; + values(): CompositeFilterOp[]; +} +export declare const CompositeFilterOpEnum: ICompositeFilterOpEnum; +export declare type FieldFilterOp = 'OPERATOR_UNSPECIFIED' | 'LESS_THAN' | 'LESS_THAN_OR_EQUAL' | 'GREATER_THAN' | 'GREATER_THAN_OR_EQUAL' | 'EQUAL' | 'NOT_EQUAL' | 'ARRAY_CONTAINS' | 'IN' | 'ARRAY_CONTAINS_ANY' | 'NOT_IN'; +export interface IFieldFilterOpEnum { + OPERATOR_UNSPECIFIED: FieldFilterOp; + LESS_THAN: FieldFilterOp; + LESS_THAN_OR_EQUAL: FieldFilterOp; + GREATER_THAN: FieldFilterOp; + GREATER_THAN_OR_EQUAL: FieldFilterOp; + EQUAL: FieldFilterOp; + NOT_EQUAL: FieldFilterOp; + ARRAY_CONTAINS: FieldFilterOp; + IN: FieldFilterOp; + ARRAY_CONTAINS_ANY: FieldFilterOp; + NOT_IN: FieldFilterOp; + values(): FieldFilterOp[]; +} +export declare const FieldFilterOpEnum: IFieldFilterOpEnum; +export declare type FieldTransformSetToServerValue = 'SERVER_VALUE_UNSPECIFIED' | 'REQUEST_TIME'; +export interface IFieldTransformSetToServerValueEnum { + SERVER_VALUE_UNSPECIFIED: FieldTransformSetToServerValue; + REQUEST_TIME: FieldTransformSetToServerValue; + values(): FieldTransformSetToServerValue[]; +} +export declare const FieldTransformSetToServerValueEnum: IFieldTransformSetToServerValueEnum; +export declare type IndexFieldMode = 'MODE_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING'; +export interface IIndexFieldModeEnum { + MODE_UNSPECIFIED: IndexFieldMode; + ASCENDING: IndexFieldMode; + DESCENDING: IndexFieldMode; + values(): IndexFieldMode[]; +} +export declare const IndexFieldModeEnum: IIndexFieldModeEnum; +export declare type IndexState = 'STATE_UNSPECIFIED' | 'CREATING' | 'READY' | 'ERROR'; +export interface IIndexStateEnum { + STATE_UNSPECIFIED: IndexState; + CREATING: IndexState; + READY: IndexState; + ERROR: IndexState; + values(): IndexState[]; +} +export declare const IndexStateEnum: IIndexStateEnum; +export declare type OrderDirection = 'DIRECTION_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING'; +export interface IOrderDirectionEnum { + DIRECTION_UNSPECIFIED: OrderDirection; + ASCENDING: OrderDirection; + DESCENDING: OrderDirection; + values(): OrderDirection[]; +} +export declare const OrderDirectionEnum: IOrderDirectionEnum; +export declare type TargetChangeTargetChangeType = 'NO_CHANGE' | 'ADD' | 'REMOVE' | 'CURRENT' | 'RESET'; +export interface ITargetChangeTargetChangeTypeEnum { + NO_CHANGE: TargetChangeTargetChangeType; + ADD: TargetChangeTargetChangeType; + REMOVE: TargetChangeTargetChangeType; + CURRENT: TargetChangeTargetChangeType; + RESET: TargetChangeTargetChangeType; + values(): TargetChangeTargetChangeType[]; +} +export declare const TargetChangeTargetChangeTypeEnum: ITargetChangeTargetChangeTypeEnum; +export declare type UnaryFilterOp = 'OPERATOR_UNSPECIFIED' | 'IS_NAN' | 'IS_NULL' | 'IS_NOT_NAN' | 'IS_NOT_NULL'; +export interface IUnaryFilterOpEnum { + OPERATOR_UNSPECIFIED: UnaryFilterOp; + IS_NAN: UnaryFilterOp; + IS_NULL: UnaryFilterOp; + IS_NOT_NAN: UnaryFilterOp; + IS_NOT_NULL: UnaryFilterOp; + values(): UnaryFilterOp[]; +} +export declare const UnaryFilterOpEnum: IUnaryFilterOpEnum; +export declare type ValueNullValue = 'NULL_VALUE'; +export interface IValueNullValueEnum { + NULL_VALUE: ValueNullValue; + values(): ValueNullValue[]; +} +export declare const ValueNullValueEnum: IValueNullValueEnum; +export declare namespace firestoreV1ApiClientInterfaces { + interface ArrayValue { + values?: Value[]; + } + interface BatchGetDocumentsRequest { + database?: string; + documents?: string[]; + mask?: DocumentMask; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface BatchGetDocumentsResponse { + found?: Document; + missing?: string; + transaction?: string; + readTime?: string; + } + interface BeginTransactionRequest { + options?: TransactionOptions; + } + interface BeginTransactionResponse { + transaction?: string; + } + interface CollectionSelector { + collectionId?: string; + allDescendants?: boolean; + } + interface CommitRequest { + database?: string; + writes?: Write[]; + transaction?: string; + } + interface CommitResponse { + writeResults?: WriteResult[]; + commitTime?: string; + } + interface CompositeFilter { + op?: CompositeFilterOp; + filters?: Filter[]; + } + interface Cursor { + values?: Value[]; + before?: boolean; + } + interface Document { + name?: string; + fields?: ApiClientObjectMap; + createTime?: Timestamp; + updateTime?: Timestamp; + } + interface DocumentChange { + document?: Document; + targetIds?: number[]; + removedTargetIds?: number[]; + } + interface DocumentDelete { + document?: string; + removedTargetIds?: number[]; + readTime?: Timestamp; + } + interface DocumentMask { + fieldPaths?: string[]; + } + interface DocumentRemove { + document?: string; + removedTargetIds?: number[]; + readTime?: string; + } + interface DocumentTransform { + document?: string; + fieldTransforms?: FieldTransform[]; + } + interface DocumentsTarget { + documents?: string[]; + } + interface Empty { + } + interface ExistenceFilter { + targetId?: number; + count?: number; + unchangedNames?: BloomFilter; + } + interface BloomFilter { + bits?: BitSequence; + hashCount?: number; + } + interface BitSequence { + bitmap?: string | Uint8Array; + padding?: number; + } + interface FieldFilter { + field?: FieldReference; + op?: FieldFilterOp; + value?: Value; + } + interface FieldReference { + fieldPath?: string; + } + interface FieldTransform { + fieldPath?: string; + setToServerValue?: FieldTransformSetToServerValue; + appendMissingElements?: ArrayValue; + removeAllFromArray?: ArrayValue; + increment?: Value; + } + interface Filter { + compositeFilter?: CompositeFilter; + fieldFilter?: FieldFilter; + unaryFilter?: UnaryFilter; + } + interface Index { + name?: string; + collectionId?: string; + fields?: IndexField[]; + state?: IndexState; + } + interface IndexField { + fieldPath?: string; + mode?: IndexFieldMode; + } + interface LatLng { + latitude?: number; + longitude?: number; + } + interface ListCollectionIdsRequest { + pageSize?: number; + pageToken?: string; + } + interface ListCollectionIdsResponse { + collectionIds?: string[]; + nextPageToken?: string; + } + interface ListDocumentsResponse { + documents?: Document[]; + nextPageToken?: string; + } + interface ListIndexesResponse { + indexes?: Index[]; + nextPageToken?: string; + } + interface ListenRequest { + addTarget?: Target; + removeTarget?: number; + labels?: ApiClientObjectMap; + } + interface ListenResponse { + targetChange?: TargetChange; + documentChange?: DocumentChange; + documentDelete?: DocumentDelete; + documentRemove?: DocumentRemove; + filter?: ExistenceFilter; + } + interface MapValue { + fields?: ApiClientObjectMap; + } + interface Operation { + name?: string; + metadata?: ApiClientObjectMap; + done?: boolean; + error?: Status; + response?: ApiClientObjectMap; + } + interface Order { + field?: FieldReference; + direction?: OrderDirection; + } + interface Precondition { + exists?: boolean; + updateTime?: Timestamp; + } + interface Projection { + fields?: FieldReference[]; + } + interface QueryTarget { + parent?: string; + structuredQuery?: StructuredQuery; + } + interface ReadOnly { + readTime?: string; + } + interface ReadWrite { + retryTransaction?: string; + } + interface RollbackRequest { + transaction?: string; + } + interface RunQueryRequest { + parent?: string; + structuredQuery?: StructuredQuery; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface RunQueryResponse { + transaction?: string; + document?: Document; + readTime?: string; + skippedResults?: number; + } + interface RunAggregationQueryRequest { + parent?: string; + structuredAggregationQuery?: StructuredAggregationQuery; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface RunAggregationQueryResponse { + result?: AggregationResult; + transaction?: string; + readTime?: string; + } + interface AggregationResult { + aggregateFields?: ApiClientObjectMap; + } + interface StructuredAggregationQuery { + structuredQuery?: StructuredQuery; + aggregations?: Aggregation[]; + } + interface Aggregation { + count?: Count; + sum?: Sum; + avg?: Avg; + alias?: string; + } + interface Count { + upTo?: number; + } + interface Sum { + field?: FieldReference; + } + interface Avg { + field?: FieldReference; + } + interface Status { + code?: number; + message?: string; + details?: Array>; + } + interface StructuredQuery { + select?: Projection; + from?: CollectionSelector[]; + where?: Filter; + orderBy?: Order[]; + startAt?: Cursor; + endAt?: Cursor; + offset?: number; + limit?: number | { + value: number; + }; + } + interface Target { + query?: QueryTarget; + documents?: DocumentsTarget; + resumeToken?: string | Uint8Array; + readTime?: Timestamp; + targetId?: number; + once?: boolean; + expectedCount?: number | { + value: number; + }; + } + interface TargetChange { + targetChangeType?: TargetChangeTargetChangeType; + targetIds?: number[]; + cause?: Status; + resumeToken?: string | Uint8Array; + readTime?: Timestamp; + } + interface TransactionOptions { + readOnly?: ReadOnly; + readWrite?: ReadWrite; + } + interface UnaryFilter { + op?: UnaryFilterOp; + field?: FieldReference; + } + interface Value { + nullValue?: ValueNullValue; + booleanValue?: boolean; + integerValue?: string | number; + doubleValue?: string | number; + timestampValue?: Timestamp; + stringValue?: string; + bytesValue?: string | Uint8Array; + referenceValue?: string; + geoPointValue?: LatLng; + arrayValue?: ArrayValue; + mapValue?: MapValue; + } + interface Write { + update?: Document; + delete?: string; + verify?: string; + transform?: DocumentTransform; + updateMask?: DocumentMask; + updateTransforms?: FieldTransform[]; + currentDocument?: Precondition; + } + interface WriteRequest { + streamId?: string; + writes?: Write[]; + streamToken?: string | Uint8Array; + labels?: ApiClientObjectMap; + } + interface WriteResponse { + streamId?: string; + streamToken?: string | Uint8Array; + writeResults?: WriteResult[]; + commitTime?: Timestamp; + } + interface WriteResult { + updateTime?: Timestamp; + transformResults?: Value[]; + } +} +export declare type ArrayValue = firestoreV1ApiClientInterfaces.ArrayValue; +export declare type BatchGetDocumentsRequest = firestoreV1ApiClientInterfaces.BatchGetDocumentsRequest; +export declare type BatchGetDocumentsResponse = firestoreV1ApiClientInterfaces.BatchGetDocumentsResponse; +export declare type BeginTransactionRequest = firestoreV1ApiClientInterfaces.BeginTransactionRequest; +export declare type BeginTransactionResponse = firestoreV1ApiClientInterfaces.BeginTransactionResponse; +export declare type BloomFilter = firestoreV1ApiClientInterfaces.BloomFilter; +export declare type CollectionSelector = firestoreV1ApiClientInterfaces.CollectionSelector; +export declare type CommitRequest = firestoreV1ApiClientInterfaces.CommitRequest; +export declare type CommitResponse = firestoreV1ApiClientInterfaces.CommitResponse; +export declare type CompositeFilter = firestoreV1ApiClientInterfaces.CompositeFilter; +export declare type Cursor = firestoreV1ApiClientInterfaces.Cursor; +export declare type Document = firestoreV1ApiClientInterfaces.Document; +export declare type DocumentChange = firestoreV1ApiClientInterfaces.DocumentChange; +export declare type DocumentDelete = firestoreV1ApiClientInterfaces.DocumentDelete; +export declare type DocumentMask = firestoreV1ApiClientInterfaces.DocumentMask; +export declare type DocumentRemove = firestoreV1ApiClientInterfaces.DocumentRemove; +export declare type DocumentTransform = firestoreV1ApiClientInterfaces.DocumentTransform; +export declare type DocumentsTarget = firestoreV1ApiClientInterfaces.DocumentsTarget; +export declare type Empty = firestoreV1ApiClientInterfaces.Empty; +export declare type ExistenceFilter = firestoreV1ApiClientInterfaces.ExistenceFilter; +export declare type FieldFilter = firestoreV1ApiClientInterfaces.FieldFilter; +export declare type FieldReference = firestoreV1ApiClientInterfaces.FieldReference; +export declare type FieldTransform = firestoreV1ApiClientInterfaces.FieldTransform; +export declare type Filter = firestoreV1ApiClientInterfaces.Filter; +export declare type Index = firestoreV1ApiClientInterfaces.Index; +export declare type IndexField = firestoreV1ApiClientInterfaces.IndexField; +export declare type LatLng = firestoreV1ApiClientInterfaces.LatLng; +export declare type ListCollectionIdsRequest = firestoreV1ApiClientInterfaces.ListCollectionIdsRequest; +export declare type ListCollectionIdsResponse = firestoreV1ApiClientInterfaces.ListCollectionIdsResponse; +export declare type ListDocumentsResponse = firestoreV1ApiClientInterfaces.ListDocumentsResponse; +export declare type ListIndexesResponse = firestoreV1ApiClientInterfaces.ListIndexesResponse; +export declare type ListenRequest = firestoreV1ApiClientInterfaces.ListenRequest; +export declare type ListenResponse = firestoreV1ApiClientInterfaces.ListenResponse; +export declare type MapValue = firestoreV1ApiClientInterfaces.MapValue; +export declare type Operation = firestoreV1ApiClientInterfaces.Operation; +export declare type Order = firestoreV1ApiClientInterfaces.Order; +export declare type Precondition = firestoreV1ApiClientInterfaces.Precondition; +export declare type Projection = firestoreV1ApiClientInterfaces.Projection; +export declare type QueryTarget = firestoreV1ApiClientInterfaces.QueryTarget; +export declare type ReadOnly = firestoreV1ApiClientInterfaces.ReadOnly; +export declare type ReadWrite = firestoreV1ApiClientInterfaces.ReadWrite; +export declare type RollbackRequest = firestoreV1ApiClientInterfaces.RollbackRequest; +export declare type RunQueryRequest = firestoreV1ApiClientInterfaces.RunQueryRequest; +export declare type RunQueryResponse = firestoreV1ApiClientInterfaces.RunQueryResponse; +export declare type RunAggregationQueryRequest = firestoreV1ApiClientInterfaces.RunAggregationQueryRequest; +export declare type Aggregation = firestoreV1ApiClientInterfaces.Aggregation; +export declare type RunAggregationQueryResponse = firestoreV1ApiClientInterfaces.RunAggregationQueryResponse; +export declare type Status = firestoreV1ApiClientInterfaces.Status; +export declare type StructuredQuery = firestoreV1ApiClientInterfaces.StructuredQuery; +export declare type Target = firestoreV1ApiClientInterfaces.Target; +export declare type TargetChange = firestoreV1ApiClientInterfaces.TargetChange; +export declare type TransactionOptions = firestoreV1ApiClientInterfaces.TransactionOptions; +export declare type UnaryFilter = firestoreV1ApiClientInterfaces.UnaryFilter; +export declare type Value = firestoreV1ApiClientInterfaces.Value; +export declare type Write = firestoreV1ApiClientInterfaces.Write; +export declare type WriteRequest = firestoreV1ApiClientInterfaces.WriteRequest; +export declare type WriteResponse = firestoreV1ApiClientInterfaces.WriteResponse; +export declare type WriteResult = firestoreV1ApiClientInterfaces.WriteResult; +export declare type ProjectsDatabasesDocumentsApiClient$Xgafv = '1' | '2'; +export interface IProjectsDatabasesDocumentsApiClient$XgafvEnum { + 1: ProjectsDatabasesDocumentsApiClient$Xgafv; + 2: ProjectsDatabasesDocumentsApiClient$Xgafv; + values(): ProjectsDatabasesDocumentsApiClient$Xgafv[]; +} +export declare const ProjectsDatabasesDocumentsApiClient$XgafvEnum: IProjectsDatabasesDocumentsApiClient$XgafvEnum; +export declare type ProjectsDatabasesDocumentsApiClientAlt = 'json' | 'media' | 'proto'; +export interface IProjectsDatabasesDocumentsApiClientAltEnum { + JSON: ProjectsDatabasesDocumentsApiClientAlt; + MEDIA: ProjectsDatabasesDocumentsApiClientAlt; + PROTO: ProjectsDatabasesDocumentsApiClientAlt; + values(): ProjectsDatabasesDocumentsApiClientAlt[]; +} +export declare const ProjectsDatabasesDocumentsApiClientAltEnum: IProjectsDatabasesDocumentsApiClientAltEnum; +export interface ProjectsDatabasesDocumentsBatchGetNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; +} +export interface ProjectsDatabasesDocumentsBeginTransactionNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; +} +export interface ProjectsDatabasesDocumentsCommitNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; +} +export interface ProjectsDatabasesDocumentsCreateDocumentNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; + documentId?: string; + maskFieldPaths?: string[]; +} +export interface ProjectsDatabasesDocumentsDeleteNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; + currentDocumentExists?: boolean; + currentDocumentUpdateTime?: string; +} +export interface ProjectsDatabasesDocumentsGetNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; + maskFieldPaths?: string[]; + transaction?: string; + readTime?: string; +} +export interface ProjectsDatabasesDocumentsListCollectionIdsNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; +} +export interface ProjectsDatabasesDocumentsListNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; + pageSize?: number; + pageToken?: string; + orderBy?: string; + maskFieldPaths?: string[]; + transaction?: string; + readTime?: string; + showMissing?: boolean; +} +export interface ProjectsDatabasesDocumentsListenNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; +} +export interface ProjectsDatabasesDocumentsPatchNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; + updateMaskFieldPaths?: string[]; + maskFieldPaths?: string[]; + currentDocumentExists?: boolean; + currentDocumentUpdateTime?: string; +} +export interface ProjectsDatabasesDocumentsRollbackNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; +} +export interface ProjectsDatabasesDocumentsRunQueryNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; +} +export interface ProjectsDatabasesDocumentsWriteNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; +} +export declare abstract class ProjectsDatabasesDocumentsApiClient { + private constructor(); + abstract batchGet(database: string, $requestBody: BatchGetDocumentsRequest, __namedParams__?: ProjectsDatabasesDocumentsBatchGetNamedParameters & object): Promise; + abstract beginTransaction(database: string, $requestBody: BeginTransactionRequest, __namedParams__?: ProjectsDatabasesDocumentsBeginTransactionNamedParameters & object): Promise; + abstract commit(database: string, $requestBody: CommitRequest, __namedParams__?: ProjectsDatabasesDocumentsCommitNamedParameters & object): Promise; + abstract createDocument(parent: string, collectionId: string, $requestBody: Document, __namedParams__?: ProjectsDatabasesDocumentsCreateDocumentNamedParameters & object): Promise; + abstract delete(name: string, __namedParams__?: ProjectsDatabasesDocumentsDeleteNamedParameters & object): Promise; + abstract get(name: string, __namedParams__?: ProjectsDatabasesDocumentsGetNamedParameters & object): Promise; + abstract list(parent: string, collectionId: string, __namedParams__?: ProjectsDatabasesDocumentsListNamedParameters & object): Promise; + abstract listCollectionIds(parent: string, $requestBody: ListCollectionIdsRequest, __namedParams__?: ProjectsDatabasesDocumentsListCollectionIdsNamedParameters & object): Promise; + abstract listen(database: string, $requestBody: ListenRequest, __namedParams__?: ProjectsDatabasesDocumentsListenNamedParameters & object): Promise; + abstract patch(name: string, $requestBody: Document, __namedParams__?: ProjectsDatabasesDocumentsPatchNamedParameters & object): Promise; + abstract rollback(database: string, $requestBody: RollbackRequest, __namedParams__?: ProjectsDatabasesDocumentsRollbackNamedParameters & object): Promise; + abstract runQuery(parent: string, $requestBody: RunQueryRequest, __namedParams__?: ProjectsDatabasesDocumentsRunQueryNamedParameters & object): Promise; + abstract write(database: string, $requestBody: WriteRequest, __namedParams__?: ProjectsDatabasesDocumentsWriteNamedParameters & object): Promise; +} +export declare class ProjectsDatabasesDocumentsApiClientImpl implements ProjectsDatabasesDocumentsApiClient { + private gapiVersion; + private $apiClient; + constructor(gapiVersion: string, gapiRequestService: PromiseRequestService, apiClientHookFactory?: ApiClientHookFactory | null); + batchGet(database: string, $requestBody: BatchGetDocumentsRequest, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsBatchGetNamedParameters & object): Promise; + beginTransaction(database: string, $requestBody: BeginTransactionRequest, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsBeginTransactionNamedParameters & object): Promise; + commit(database: string, $requestBody: CommitRequest, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsCommitNamedParameters & object): Promise; + createDocument(parent: string, collectionId: string, $requestBody: Document, { $Xgafv, access_token, alt, bearer_token, callback, documentId, fields, key, maskFieldPaths, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsCreateDocumentNamedParameters & object): Promise; + delete(name: string, { $Xgafv, access_token, alt, bearer_token, callback, currentDocumentExists, currentDocumentUpdateTime, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsDeleteNamedParameters & object): Promise; + get(name: string, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, maskFieldPaths, oauth_token, pp, prettyPrint, quotaUser, readTime, transaction, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsGetNamedParameters & object): Promise; + list(parent: string, collectionId: string, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, maskFieldPaths, oauth_token, orderBy, pageSize, pageToken, pp, prettyPrint, quotaUser, readTime, showMissing, transaction, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsListNamedParameters & object): Promise; + listCollectionIds(parent: string, $requestBody: ListCollectionIdsRequest, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsListCollectionIdsNamedParameters & object): Promise; + listen(database: string, $requestBody: ListenRequest, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsListenNamedParameters & object): Promise; + patch(name: string, $requestBody: Document, { $Xgafv, access_token, alt, bearer_token, callback, currentDocumentExists, currentDocumentUpdateTime, fields, key, maskFieldPaths, oauth_token, pp, prettyPrint, quotaUser, updateMaskFieldPaths, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsPatchNamedParameters & object): Promise; + rollback(database: string, $requestBody: RollbackRequest, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsRollbackNamedParameters & object): Promise; + runQuery(parent: string, $requestBody: RunQueryRequest, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsRunQueryNamedParameters & object): Promise; + write(database: string, $requestBody: WriteRequest, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsWriteNamedParameters & object): Promise; +} +export declare type ProjectsDatabasesIndexesApiClient$Xgafv = '1' | '2'; +export interface IProjectsDatabasesIndexesApiClient$XgafvEnum { + 1: ProjectsDatabasesIndexesApiClient$Xgafv; + 2: ProjectsDatabasesIndexesApiClient$Xgafv; + values(): ProjectsDatabasesIndexesApiClient$Xgafv[]; +} +export declare const ProjectsDatabasesIndexesApiClient$XgafvEnum: IProjectsDatabasesIndexesApiClient$XgafvEnum; +export declare type ProjectsDatabasesIndexesApiClientAlt = 'json' | 'media' | 'proto'; +export interface IProjectsDatabasesIndexesApiClientAltEnum { + JSON: ProjectsDatabasesIndexesApiClientAlt; + MEDIA: ProjectsDatabasesIndexesApiClientAlt; + PROTO: ProjectsDatabasesIndexesApiClientAlt; + values(): ProjectsDatabasesIndexesApiClientAlt[]; +} +export declare const ProjectsDatabasesIndexesApiClientAltEnum: IProjectsDatabasesIndexesApiClientAltEnum; +export interface ProjectsDatabasesIndexesCreateNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesIndexesApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesIndexesApiClient$Xgafv; +} +export interface ProjectsDatabasesIndexesDeleteNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesIndexesApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesIndexesApiClient$Xgafv; +} +export interface ProjectsDatabasesIndexesGetNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesIndexesApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesIndexesApiClient$Xgafv; +} +export interface ProjectsDatabasesIndexesListNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesIndexesApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesIndexesApiClient$Xgafv; + filter?: string; + pageSize?: number; + pageToken?: string; +} +export declare abstract class ProjectsDatabasesIndexesApiClient { + private constructor(); + abstract create(parent: string, $requestBody: Index, __namedParams__?: ProjectsDatabasesIndexesCreateNamedParameters & object): Promise; + abstract delete(name: string, __namedParams__?: ProjectsDatabasesIndexesDeleteNamedParameters & object): Promise; + abstract get(name: string, __namedParams__?: ProjectsDatabasesIndexesGetNamedParameters & object): Promise; + abstract list(parent: string, __namedParams__?: ProjectsDatabasesIndexesListNamedParameters & object): Promise; +} +export declare class ProjectsDatabasesIndexesApiClientImpl implements ProjectsDatabasesIndexesApiClient { + private gapiVersion; + private $apiClient; + constructor(gapiVersion: string, gapiRequestService: PromiseRequestService, apiClientHookFactory?: ApiClientHookFactory | null); + create(parent: string, $requestBody: Index, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesIndexesCreateNamedParameters & object): Promise; + delete(name: string, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesIndexesDeleteNamedParameters & object): Promise; + get(name: string, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesIndexesGetNamedParameters & object): Promise; + list(parent: string, { $Xgafv, access_token, alt, bearer_token, callback, fields, filter, key, oauth_token, pageSize, pageToken, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesIndexesListNamedParameters & object): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/register.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/register.d.ts new file mode 100644 index 0000000..6f9da17 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/register.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare function registerFirestore(variant?: string, useFetchStreams?: boolean): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/backoff.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/backoff.d.ts new file mode 100644 index 0000000..cb0bc76 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/backoff.d.ts @@ -0,0 +1,106 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AsyncQueue, TimerId } from '../util/async_queue'; +/** + * A helper for running delayed tasks following an exponential backoff curve + * between attempts. + * + * Each delay is made up of a "base" delay which follows the exponential + * backoff curve, and a +/- 50% "jitter" that is calculated and added to the + * base delay. This prevents clients from accidentally synchronizing their + * delays causing spikes of load to the backend. + */ +export declare class ExponentialBackoff { + /** + * The AsyncQueue to run backoff operations on. + */ + private readonly queue; + /** + * The ID to use when scheduling backoff operations on the AsyncQueue. + */ + private readonly timerId; + /** + * The initial delay (used as the base delay on the first retry attempt). + * Note that jitter will still be applied, so the actual delay could be as + * little as 0.5*initialDelayMs. + */ + private readonly initialDelayMs; + /** + * The multiplier to use to determine the extended base delay after each + * attempt. + */ + private readonly backoffFactor; + /** + * The maximum base delay after which no further backoff is performed. + * Note that jitter will still be applied, so the actual delay could be as + * much as 1.5*maxDelayMs. + */ + private readonly maxDelayMs; + private currentBaseMs; + private timerPromise; + /** The last backoff attempt, as epoch milliseconds. */ + private lastAttemptTime; + constructor( + /** + * The AsyncQueue to run backoff operations on. + */ + queue: AsyncQueue, + /** + * The ID to use when scheduling backoff operations on the AsyncQueue. + */ + timerId: TimerId, + /** + * The initial delay (used as the base delay on the first retry attempt). + * Note that jitter will still be applied, so the actual delay could be as + * little as 0.5*initialDelayMs. + */ + initialDelayMs?: number, + /** + * The multiplier to use to determine the extended base delay after each + * attempt. + */ + backoffFactor?: number, + /** + * The maximum base delay after which no further backoff is performed. + * Note that jitter will still be applied, so the actual delay could be as + * much as 1.5*maxDelayMs. + */ + maxDelayMs?: number); + /** + * Resets the backoff delay. + * + * The very next backoffAndWait() will have no delay. If it is called again + * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and + * subsequent ones will increase according to the backoffFactor. + */ + reset(): void; + /** + * Resets the backoff delay to the maximum delay (e.g. for use after a + * RESOURCE_EXHAUSTED error). + */ + resetToMax(): void; + /** + * Returns a promise that resolves after currentDelayMs, and increases the + * delay for any subsequent attempts. If there was a pending backoff operation + * already, it will be canceled. + */ + backoffAndRun(op: () => Promise): void; + skipBackoff(): void; + cancel(): void; + /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ + private jitterDelayMs; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/bloom_filter.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/bloom_filter.d.ts new file mode 100644 index 0000000..d80eb83 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/bloom_filter.d.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare class BloomFilter { + readonly bitmap: Uint8Array; + readonly padding: number; + readonly hashCount: number; + readonly bitCount: number; + private readonly bitCountInInteger; + constructor(bitmap: Uint8Array, padding: number, hashCount: number); + private getBitIndex; + private isBitSet; + mightContain(value: string): boolean; + /** Create bloom filter for testing purposes only. */ + static create(bitCount: number, hashCount: number, contains: string[]): BloomFilter; + private insert; + private setBit; +} +export declare class BloomFilterError extends Error { + readonly name = "BloomFilterError"; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/connection.d.ts new file mode 100644 index 0000000..87afea6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/connection.d.ts @@ -0,0 +1,99 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Token } from '../api/credentials'; +import { ResourcePath } from '../model/path'; +import { FirestoreError } from '../util/error'; +/** + * A connected RPC interface to a remote Datastore. + * + * Responsible for maintaining a connection to the backend (and informing when + * that connection state changes via onConnectionStateChange) and sending RPCs + * when possible. + * + * The Connection is not responsible for queueing RPCs to the backend when + * the connection is down. + * + * RPC messages are expected to be JavaScript objects representing the JSON that + * would be sent over the REST/JSON API to Datastore or used as input to + * creating the equivalent protocol buffers for GRPC. + */ +export interface Connection { + /** + * Invokes an RPC by name, given a request message as a JavaScript object + * representing the JSON to send. + * + * @param rpcName - the name of the RPC to invoke + * @param path - the path to invoke this RPC on. An array of path segments + * that will be encoded and joined with path separators when required. + * @param request - the Raw JSON object encoding of the request message + * @param token - the Token to use for the RPC. + * @returns a Promise containing the JSON object encoding of the response + */ + invokeRPC(rpcName: string, path: ResourcePath, request: Req, authToken: Token | null, appCheckToken: Token | null): Promise; + /** + * Invokes a streaming RPC by name, given a request message as a JavaScript + * object representing the JSON to send. The responses will be consumed to + * completion and then returned as an array. + * + * @param rpcName - the name of the RPC to invoke + * @param path - the path to invoke this RPC on. An array of path segments + * that will be encoded and joined with path separators when required. + * @param request - the Raw JSON object encoding of the request message + * @param token - the Token to use for the RPC. + * @returns a Promise containing an array with the JSON object encodings of the + * responses + */ + invokeStreamingRPC(rpcName: string, path: ResourcePath, request: Req, authToken: Token | null, appCheckToken: Token | null, expectedResponseCount?: number): Promise; + /** + * Opens a stream to the given stream RPC endpoint. Returns a stream which + * will try to open itself. + * @param rpcName - the name of the RPC to open the stream on + * @param token - the Token to use for the RPC. + */ + openStream(rpcName: string, authToken: Token | null, appCheckToken: Token | null): Stream; + /** + * Returns whether or not the implementation requires that the "path" of the resource + * (a document or a collection) be present in the request message. If true, then the + * request message must include the path. If false, then the request message must NOT + * include the path. + */ + readonly shouldResourcePathBeIncludedInRequest: boolean; + /** + * Closes and cleans up any resources associated with the connection. Actual + * resources cleaned are implementation specific. Failure to call `terminate` + * on a connection may result in resource leaks. + */ + terminate(): void; +} +/** + * A bidirectional stream that can be used to send an receive messages. + * + * A stream can be closed locally with close() or can be closed remotely or + * through network errors. onClose is guaranteed to be called. onOpen will be + * called once the stream is ready to send messages (which may or may not be + * before an actual connection to the backend has been established). The + * onConnected event is called when an actual, physical connection with the + * backend has been established, and may occur before or after the onOpen event. + */ +export interface Stream { + onConnected(callback: () => void): void; + onOpen(callback: () => void): void; + onClose(callback: (err?: FirestoreError) => void): void; + onMessage(callback: (msg: O) => void): void; + send(msg: I): void; + close(): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/connectivity_monitor.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/connectivity_monitor.d.ts new file mode 100644 index 0000000..e02b7d2 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/connectivity_monitor.d.ts @@ -0,0 +1,47 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The set of network states is deliberately simplified -- we only care about + * states such that transition between them should break currently + * established connections. + */ +export declare const enum NetworkStatus { + AVAILABLE = 0, + UNAVAILABLE = 1 +} +export type ConnectivityMonitorCallback = (status: NetworkStatus) => void; +/** + * A base class for monitoring changes in network connectivity; it is expected + * that each platform will have its own system-dependent implementation. + */ +export interface ConnectivityMonitor { + /** + * Adds a callback to be called when connectivity changes. + * + * Callbacks are not made on the initial state of connectivity, since this + * monitor is primarily used for resetting backoff in the remote store when + * connectivity changes. As such, the initial connectivity state is + * irrelevant here. + */ + addCallback(callback: ConnectivityMonitorCallback): void; + /** + * Stops monitoring connectivity. After this call completes, no further + * callbacks will be triggered. After shutdown() is called, no further calls + * are allowed on this instance. + */ + shutdown(): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/connectivity_monitor_noop.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/connectivity_monitor_noop.d.ts new file mode 100644 index 0000000..42bb25c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/connectivity_monitor_noop.d.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ConnectivityMonitor, NetworkStatus } from './connectivity_monitor'; +export declare class NoopConnectivityMonitor implements ConnectivityMonitor { + addCallback(callback: (status: NetworkStatus) => void): void; + shutdown(): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/datastore.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/datastore.d.ts new file mode 100644 index 0000000..fe095c0 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/datastore.d.ts @@ -0,0 +1,44 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { CredentialsProvider } from '../api/credentials'; +import { User } from '../auth/user'; +import { Aggregate } from '../core/aggregate'; +import { Query } from '../core/query'; +import { Document } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { Mutation } from '../model/mutation'; +import { ApiClientObjectMap, Value } from '../protos/firestore_proto_api'; +import { AsyncQueue } from '../util/async_queue'; +import { Connection } from './connection'; +import { PersistentListenStream, PersistentWriteStream, WatchStreamListener, WriteStreamListener } from './persistent_stream'; +import { JsonProtoSerializer } from './serializer'; +/** + * Datastore and its related methods are a wrapper around the external Google + * Cloud Datastore grpc API, which provides an interface that is more convenient + * for the rest of the client SDK architecture to consume. + */ +export declare abstract class Datastore { + abstract terminate(): void; + abstract serializer: JsonProtoSerializer; +} +export declare function newDatastore(authCredentials: CredentialsProvider, appCheckCredentials: CredentialsProvider, connection: Connection, serializer: JsonProtoSerializer): Datastore; +export declare function invokeCommitRpc(datastore: Datastore, mutations: Mutation[]): Promise; +export declare function invokeBatchGetDocumentsRpc(datastore: Datastore, keys: DocumentKey[]): Promise; +export declare function invokeRunQueryRpc(datastore: Datastore, query: Query): Promise; +export declare function invokeRunAggregationQueryRpc(datastore: Datastore, query: Query, aggregates: Aggregate[]): Promise>; +export declare function newPersistentWriteStream(datastore: Datastore, queue: AsyncQueue, listener: WriteStreamListener): PersistentWriteStream; +export declare function newPersistentWatchStream(datastore: Datastore, queue: AsyncQueue, listener: WatchStreamListener): PersistentListenStream; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/existence_filter.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/existence_filter.d.ts new file mode 100644 index 0000000..10ed5e5 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/existence_filter.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BloomFilter as ProtoBloomFilter } from '../protos/firestore_proto_api'; +export declare class ExistenceFilter { + count: number; + unchangedNames?: ProtoBloomFilter | undefined; + constructor(count: number, unchangedNames?: ProtoBloomFilter | undefined); +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/internal_serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/internal_serializer.d.ts new file mode 100644 index 0000000..cd1f08d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/internal_serializer.d.ts @@ -0,0 +1,46 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AggregateSpec } from '../lite-api/aggregate_types'; +import { Query } from '../lite-api/reference'; +/** + * @internal + * @private + * + * This function is for internal use only. + * + * Returns the `QueryTarget` representation of the given query. Returns `null` + * if the Firestore client associated with the given query has not been + * initialized or has been terminated. + * + * @param query - The Query to convert to proto representation. + */ +export declare function _internalQueryToProtoQueryTarget(query: Query): any; +/** + * @internal + * @private + * + * This function is for internal use only. + * + * Returns `RunAggregationQueryRequest` which contains the proto representation + * of the given aggregation query request. Returns null if the Firestore client + * associated with the given query has not been initialized or has been + * terminated. + * + * @param query - The Query to convert to proto representation. + * @param aggregateSpec - The set of aggregations and their aliases. + */ +export declare function _internalAggregationQueryToProtoRunAggregationQueryRequest(query: Query, aggregateSpec: AggregateSpecType): any; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/number_serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/number_serializer.d.ts new file mode 100644 index 0000000..cec4398 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/number_serializer.d.ts @@ -0,0 +1,36 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Value as ProtoValue } from '../protos/firestore_proto_api'; +/** Base interface for the Serializer implementation. */ +export interface Serializer { + readonly useProto3Json: boolean; +} +/** + * Returns an DoubleValue for `value` that is encoded based the serializer's + * `useProto3Json` setting. + */ +export declare function toDouble(serializer: Serializer, value: number): ProtoValue; +/** + * Returns an IntegerValue for `value`. + */ +export declare function toInteger(value: number): ProtoValue; +/** + * Returns a value for a number that's appropriate to put into a proto. + * The return value is an IntegerValue if it can safely represent the value, + * otherwise a DoubleValue is returned. + */ +export declare function toNumber(serializer: Serializer, value: number): ProtoValue; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/online_state_tracker.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/online_state_tracker.d.ts new file mode 100644 index 0000000..8a9bf8d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/online_state_tracker.d.ts @@ -0,0 +1,81 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { OnlineState } from '../core/types'; +import { AsyncQueue } from '../util/async_queue'; +import { FirestoreError } from '../util/error'; +/** + * A component used by the RemoteStore to track the OnlineState (that is, + * whether or not the client as a whole should be considered to be online or + * offline), implementing the appropriate heuristics. + * + * In particular, when the client is trying to connect to the backend, we + * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for + * a connection to succeed. If we have too many failures or the timeout elapses, + * then we set the OnlineState to Offline, and the client will behave as if + * it is offline (get()s will return cached data, etc.). + */ +export declare class OnlineStateTracker { + private asyncQueue; + private onlineStateHandler; + /** The current OnlineState. */ + private state; + /** + * A count of consecutive failures to open the stream. If it reaches the + * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to + * Offline. + */ + private watchStreamFailures; + /** + * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we + * transition from OnlineState.Unknown to OnlineState.Offline without waiting + * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times). + */ + private onlineStateTimer; + /** + * Whether the client should log a warning message if it fails to connect to + * the backend (initially true, cleared after a successful stream, or if we've + * logged the message already). + */ + private shouldWarnClientIsOffline; + constructor(asyncQueue: AsyncQueue, onlineStateHandler: (onlineState: OnlineState) => void); + /** + * Called by RemoteStore when a watch stream is started (including on each + * backoff attempt). + * + * If this is the first attempt, it sets the OnlineState to Unknown and starts + * the onlineStateTimer. + */ + handleWatchStreamStart(): void; + /** + * Updates our OnlineState as appropriate after the watch stream reports a + * failure. The first failure moves us to the 'Unknown' state. We then may + * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we + * actually transition to the 'Offline' state. + */ + handleWatchStreamFailure(error: FirestoreError): void; + /** + * Explicitly sets the OnlineState to the specified state. + * + * Note that this resets our timers / failure counters, etc. used by our + * Offline heuristics, so must not be used in place of + * handleWatchStreamStart() and handleWatchStreamFailure(). + */ + set(newState: OnlineState): void; + private setAndBroadcast; + private logClientOfflineWarningIfNecessary; + private clearOnlineStateTimer; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/persistent_stream.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/persistent_stream.d.ts new file mode 100644 index 0000000..aacaf2d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/persistent_stream.d.ts @@ -0,0 +1,308 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { CredentialsProvider, Token } from '../api/credentials'; +import { User } from '../auth/user'; +import { SnapshotVersion } from '../core/snapshot_version'; +import { TargetId } from '../core/types'; +import { TargetData } from '../local/target_data'; +import { Mutation, MutationResult } from '../model/mutation'; +import { ListenRequest as ProtoListenRequest, ListenResponse as ProtoListenResponse, WriteRequest as ProtoWriteRequest, WriteResponse as ProtoWriteResponse } from '../protos/firestore_proto_api'; +import { AsyncQueue, TimerId } from '../util/async_queue'; +import { FirestoreError } from '../util/error'; +import { ExponentialBackoff } from './backoff'; +import { Connection, Stream } from './connection'; +import { JsonProtoSerializer } from './serializer'; +import { WatchChange } from './watch_change'; +export interface WriteRequest extends ProtoWriteRequest { + database?: string; +} +/** + * Provides a common interface that is shared by the listeners for stream + * events by the concrete implementation classes. + */ +export interface PersistentStreamListener { + /** + * Called after receiving an acknowledgement from the server, confirming that + * we are able to connect to it. + */ + onConnected: () => Promise; + /** + * Called after the stream was established and can accept outgoing + * messages + */ + onOpen: () => Promise; + /** + * Called after the stream has closed. If there was an error, the + * FirestoreError will be set. + */ + onClose: (err?: FirestoreError) => Promise; +} +/** + * A PersistentStream is an abstract base class that represents a streaming RPC + * to the Firestore backend. It's built on top of the connections own support + * for streaming RPCs, and adds several critical features for our clients: + * + * - Exponential backoff on failure + * - Authentication via CredentialsProvider + * - Dispatching all callbacks into the shared worker queue + * - Closing idle streams after 60 seconds of inactivity + * + * Subclasses of PersistentStream implement serialization of models to and + * from the JSON representation of the protocol buffers for a specific + * streaming RPC. + * + * ## Starting and Stopping + * + * Streaming RPCs are stateful and need to be start()ed before messages can + * be sent and received. The PersistentStream will call the onOpen() function + * of the listener once the stream is ready to accept requests. + * + * Should a start() fail, PersistentStream will call the registered onClose() + * listener with a FirestoreError indicating what went wrong. + * + * A PersistentStream can be started and stopped repeatedly. + * + * Generic types: + * SendType: The type of the outgoing message of the underlying + * connection stream + * ReceiveType: The type of the incoming message of the underlying + * connection stream + * ListenerType: The type of the listener that will be used for callbacks + */ +export declare abstract class PersistentStream { + private queue; + private idleTimerId; + private healthTimerId; + protected connection: Connection; + private authCredentialsProvider; + private appCheckCredentialsProvider; + protected listener: ListenerType; + private state; + /** + * A close count that's incremented every time the stream is closed; used by + * getCloseGuardedDispatcher() to invalidate callbacks that happen after + * close. + */ + private closeCount; + private idleTimer; + private healthCheck; + private stream; + protected backoff: ExponentialBackoff; + constructor(queue: AsyncQueue, connectionTimerId: TimerId, idleTimerId: TimerId, healthTimerId: TimerId, connection: Connection, authCredentialsProvider: CredentialsProvider, appCheckCredentialsProvider: CredentialsProvider, listener: ListenerType); + /** + * Count of response messages received. + */ + protected responseCount: number; + /** + * Returns true if start() has been called and no error has occurred. True + * indicates the stream is open or in the process of opening (which + * encompasses respecting backoff, getting auth tokens, and starting the + * actual RPC). Use isOpen() to determine if the stream is open and ready for + * outbound requests. + */ + isStarted(): boolean; + /** + * Returns true if the underlying RPC is open (the onOpen() listener has been + * called) and the stream is ready for outbound requests. + */ + isOpen(): boolean; + /** + * Starts the RPC. Only allowed if isStarted() returns false. The stream is + * not immediately ready for use: onOpen() will be invoked when the RPC is + * ready for outbound requests, at which point isOpen() will return true. + * + * When start returns, isStarted() will return true. + */ + start(): void; + /** + * Stops the RPC. This call is idempotent and allowed regardless of the + * current isStarted() state. + * + * When stop returns, isStarted() and isOpen() will both return false. + */ + stop(): Promise; + /** + * After an error the stream will usually back off on the next attempt to + * start it. If the error warrants an immediate restart of the stream, the + * sender can use this to indicate that the receiver should not back off. + * + * Each error will call the onClose() listener. That function can decide to + * inhibit backoff if required. + */ + inhibitBackoff(): void; + /** + * Marks this stream as idle. If no further actions are performed on the + * stream for one minute, the stream will automatically close itself and + * notify the stream's onClose() handler with Status.OK. The stream will then + * be in a !isStarted() state, requiring the caller to start the stream again + * before further use. + * + * Only streams that are in state 'Open' can be marked idle, as all other + * states imply pending network operations. + */ + markIdle(): void; + /** Sends a message to the underlying stream. */ + protected sendRequest(msg: SendType): void; + /** Called by the idle timer when the stream should close due to inactivity. */ + private handleIdleCloseTimer; + /** Marks the stream as active again. */ + private cancelIdleCheck; + /** Cancels the health check delayed operation. */ + private cancelHealthCheck; + /** + * Closes the stream and cleans up as necessary: + * + * * closes the underlying GRPC stream; + * * calls the onClose handler with the given 'error'; + * * sets internal stream state to 'finalState'; + * * adjusts the backoff timer based on the error + * + * A new stream can be opened by calling start(). + * + * @param finalState - the intended state of the stream after closing. + * @param error - the error the connection was closed with. + */ + private close; + /** + * Can be overridden to perform additional cleanup before the stream is closed. + * Calling super.tearDown() is not required. + */ + protected tearDown(): void; + /** + * Used by subclasses to start the concrete RPC and return the underlying + * connection stream. + */ + protected abstract startRpc(authToken: Token | null, appCheckToken: Token | null): Stream; + /** + * Called when the stream receives first message. + * The function will be called on the right queue and must return a Promise. + * @param message - The message received from the stream. + */ + protected abstract onFirst(message: ReceiveType): Promise; + /** + * Called on subsequent messages after the stream has received first message. + * The function will be called on the right queue and must return a Promise. + * @param message - The message received from the stream. + */ + protected abstract onNext(message: ReceiveType): Promise; + private auth; + private startStream; + private performBackoff; + handleStreamClose(error?: FirestoreError): Promise; + /** + * Returns a "dispatcher" function that dispatches operations onto the + * AsyncQueue but only runs them if closeCount remains unchanged. This allows + * us to turn auth / stream callbacks into no-ops if the stream is closed / + * re-opened, etc. + */ + private getCloseGuardedDispatcher; +} +/** Listener for the PersistentWatchStream */ +export interface WatchStreamListener extends PersistentStreamListener { + /** + * Called on a watchChange. The snapshot parameter will be MIN if the watch + * change did not have a snapshot associated with it. + */ + onWatchChange: (watchChange: WatchChange, snapshot: SnapshotVersion) => Promise; +} +/** + * A PersistentStream that implements the Listen RPC. + * + * Once the Listen stream has called the onOpen() listener, any number of + * listen() and unlisten() calls can be made to control what changes will be + * sent from the server for ListenResponses. + */ +export declare class PersistentListenStream extends PersistentStream { + private serializer; + constructor(queue: AsyncQueue, connection: Connection, authCredentials: CredentialsProvider, appCheckCredentials: CredentialsProvider, serializer: JsonProtoSerializer, listener: WatchStreamListener); + protected startRpc(authToken: Token | null, appCheckToken: Token | null): Stream; + protected onFirst(watchChangeProto: ProtoListenResponse): Promise; + protected onNext(watchChangeProto: ProtoListenResponse): Promise; + /** + * Registers interest in the results of the given target. If the target + * includes a resumeToken it will be included in the request. Results that + * affect the target will be streamed back as WatchChange messages that + * reference the targetId. + */ + watch(targetData: TargetData): void; + /** + * Unregisters interest in the results of the target associated with the + * given targetId. + */ + unwatch(targetId: TargetId): void; +} +/** Listener for the PersistentWriteStream */ +export interface WriteStreamListener extends PersistentStreamListener { + /** + * Called by the PersistentWriteStream upon a successful handshake response + * from the server, which is the receiver's cue to send any pending writes. + */ + onHandshakeComplete: () => Promise; + /** + * Called by the PersistentWriteStream upon receiving a StreamingWriteResponse + * from the server that contains a mutation result. + */ + onMutationResult: (commitVersion: SnapshotVersion, results: MutationResult[]) => Promise; +} +/** + * A Stream that implements the Write RPC. + * + * The Write RPC requires the caller to maintain special streamToken + * state in between calls, to help the server understand which responses the + * client has processed by the time the next request is made. Every response + * will contain a streamToken; this value must be passed to the next + * request. + * + * After calling start() on this stream, the next request must be a handshake, + * containing whatever streamToken is on hand. Once a response to this + * request is received, all pending mutations may be submitted. When + * submitting multiple batches of mutations at the same time, it's + * okay to use the same streamToken for the calls to writeMutations. + * + * TODO(b/33271235): Use proto types + */ +export declare class PersistentWriteStream extends PersistentStream { + private serializer; + constructor(queue: AsyncQueue, connection: Connection, authCredentials: CredentialsProvider, appCheckCredentials: CredentialsProvider, serializer: JsonProtoSerializer, listener: WriteStreamListener); + /** + * The last received stream token from the server, used to acknowledge which + * responses the client has processed. Stream tokens are opaque checkpoint + * markers whose only real value is their inclusion in the next request. + * + * PersistentWriteStream manages propagating this value from responses to the + * next request. + */ + private lastStreamToken; + /** + * Tracks whether or not a handshake has been successfully exchanged and + * the stream is ready to accept mutations. + */ + get handshakeComplete(): boolean; + start(): void; + protected tearDown(): void; + protected startRpc(authToken: Token | null, appCheckToken: Token | null): Stream; + protected onFirst(responseProto: ProtoWriteResponse): Promise; + protected onNext(responseProto: ProtoWriteResponse): Promise; + /** + * Sends an initial streamToken to the server, performing the handshake + * required to make the StreamingWrite RPC work. Subsequent + * calls should wait until onHandshakeComplete was called. + */ + writeHandshake(): void; + /** Sends a group of mutations to the Firestore backend to apply. */ + writeMutations(mutations: Mutation[]): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/remote_event.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/remote_event.d.ts new file mode 100644 index 0000000..9bafaf3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/remote_event.d.ts @@ -0,0 +1,156 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { TargetId } from '../core/types'; +import { TargetPurpose } from '../local/target_data'; +import { DocumentKeySet, MutableDocumentMap } from '../model/collections'; +import { ByteString } from '../util/byte_string'; +import { SortedMap } from '../util/sorted_map'; +/** + * An event from the RemoteStore. It is split into targetChanges (changes to the + * state or the set of documents in our watched targets) and documentUpdates + * (changes to the actual documents). + */ +export declare class RemoteEvent { + /** + * The snapshot version this event brings us up to, or MIN if not set. + */ + readonly snapshotVersion: SnapshotVersion; + /** + * A map from target to changes to the target. See TargetChange. + */ + readonly targetChanges: Map; + /** + * A map of targets that is known to be inconsistent, and the purpose for + * re-listening. Listens for these targets should be re-established without + * resume tokens. + */ + readonly targetMismatches: SortedMap; + /** + * A set of which documents have changed or been deleted, along with the + * doc's new values (if not deleted). + */ + readonly documentUpdates: MutableDocumentMap; + /** + * A set of which document updates are due only to limbo resolution targets. + */ + readonly resolvedLimboDocuments: DocumentKeySet; + constructor( + /** + * The snapshot version this event brings us up to, or MIN if not set. + */ + snapshotVersion: SnapshotVersion, + /** + * A map from target to changes to the target. See TargetChange. + */ + targetChanges: Map, + /** + * A map of targets that is known to be inconsistent, and the purpose for + * re-listening. Listens for these targets should be re-established without + * resume tokens. + */ + targetMismatches: SortedMap, + /** + * A set of which documents have changed or been deleted, along with the + * doc's new values (if not deleted). + */ + documentUpdates: MutableDocumentMap, + /** + * A set of which document updates are due only to limbo resolution targets. + */ + resolvedLimboDocuments: DocumentKeySet); + /** + * HACK: Views require RemoteEvents in order to determine whether the view is + * CURRENT, but secondary tabs don't receive remote events. So this method is + * used to create a synthesized RemoteEvent that can be used to apply a + * CURRENT status change to a View, for queries executed in a different tab. + */ + static createSynthesizedRemoteEventForCurrentChange(targetId: TargetId, current: boolean, resumeToken: ByteString): RemoteEvent; +} +/** + * A TargetChange specifies the set of changes for a specific target as part of + * a RemoteEvent. These changes track which documents are added, modified or + * removed, as well as the target's resume token and whether the target is + * marked CURRENT. + * The actual changes *to* documents are not part of the TargetChange since + * documents may be part of multiple targets. + */ +export declare class TargetChange { + /** + * An opaque, server-assigned token that allows watching a query to be resumed + * after disconnecting without retransmitting all the data that matches the + * query. The resume token essentially identifies a point in time from which + * the server should resume sending results. + */ + readonly resumeToken: ByteString; + /** + * The "current" (synced) status of this target. Note that "current" + * has special meaning in the RPC protocol that implies that a target is + * both up-to-date and consistent with the rest of the watch stream. + */ + readonly current: boolean; + /** + * The set of documents that were newly assigned to this target as part of + * this remote event. + */ + readonly addedDocuments: DocumentKeySet; + /** + * The set of documents that were already assigned to this target but received + * an update during this remote event. + */ + readonly modifiedDocuments: DocumentKeySet; + /** + * The set of documents that were removed from this target as part of this + * remote event. + */ + readonly removedDocuments: DocumentKeySet; + constructor( + /** + * An opaque, server-assigned token that allows watching a query to be resumed + * after disconnecting without retransmitting all the data that matches the + * query. The resume token essentially identifies a point in time from which + * the server should resume sending results. + */ + resumeToken: ByteString, + /** + * The "current" (synced) status of this target. Note that "current" + * has special meaning in the RPC protocol that implies that a target is + * both up-to-date and consistent with the rest of the watch stream. + */ + current: boolean, + /** + * The set of documents that were newly assigned to this target as part of + * this remote event. + */ + addedDocuments: DocumentKeySet, + /** + * The set of documents that were already assigned to this target but received + * an update during this remote event. + */ + modifiedDocuments: DocumentKeySet, + /** + * The set of documents that were removed from this target as part of this + * remote event. + */ + removedDocuments: DocumentKeySet); + /** + * This method is used to create a synthesized TargetChanges that can be used to + * apply a CURRENT status change to a View (for queries executed in a different + * tab) or for new queries (to raise snapshots with correct CURRENT status). + */ + static createSynthesizedTargetChangeForCurrentChange(targetId: TargetId, current: boolean, resumeToken: ByteString): TargetChange; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/remote_store.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/remote_store.d.ts new file mode 100644 index 0000000..c6c2416 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/remote_store.d.ts @@ -0,0 +1,85 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { OnlineState, TargetId } from '../core/types'; +import { LocalStore } from '../local/local_store'; +import { TargetData } from '../local/target_data'; +import { AsyncQueue } from '../util/async_queue'; +import { ConnectivityMonitor } from './connectivity_monitor'; +import { Datastore } from './datastore'; +import { RemoteSyncer } from './remote_syncer'; +/** + * RemoteStore - An interface to remotely stored data, basically providing a + * wrapper around the Datastore that is more reliable for the rest of the + * system. + * + * RemoteStore is responsible for maintaining the connection to the server. + * - maintaining a list of active listens. + * - reconnecting when the connection is dropped. + * - resuming all the active listens on reconnect. + * + * RemoteStore handles all incoming events from the Datastore. + * - listening to the watch stream and repackaging the events as RemoteEvents + * - notifying SyncEngine of any changes to the active listens. + * + * RemoteStore takes writes from other components and handles them reliably. + * - pulling pending mutations from LocalStore and sending them to Datastore. + * - retrying mutations that failed because of network problems. + * - acking mutations to the SyncEngine once they are accepted or rejected. + */ +export interface RemoteStore { + /** + * SyncEngine to notify of watch and write events. This must be set + * immediately after construction. + */ + remoteSyncer: RemoteSyncer; +} +export declare function newRemoteStore(localStore: LocalStore, datastore: Datastore, asyncQueue: AsyncQueue, onlineStateHandler: (onlineState: OnlineState) => void, connectivityMonitor: ConnectivityMonitor): RemoteStore; +/** Re-enables the network. Idempotent. */ +export declare function remoteStoreEnableNetwork(remoteStore: RemoteStore): Promise; +/** + * Temporarily disables the network. The network can be re-enabled using + * enableNetwork(). + */ +export declare function remoteStoreDisableNetwork(remoteStore: RemoteStore): Promise; +export declare function remoteStoreShutdown(remoteStore: RemoteStore): Promise; +/** + * Starts new listen for the given target. Uses resume token if provided. It + * is a no-op if the target of given `TargetData` is already being listened to. + */ +export declare function remoteStoreListen(remoteStore: RemoteStore, targetData: TargetData): void; +/** + * Removes the listen from server. It is a no-op if the given target id is + * not being listened to. + */ +export declare function remoteStoreUnlisten(remoteStore: RemoteStore, targetId: TargetId): void; +export declare function canUseNetwork(remoteStore: RemoteStore): boolean; +/** + * Attempts to fill our write pipeline with writes from the LocalStore. + * + * Called internally to bootstrap or refill the write pipeline and by + * SyncEngine whenever there are new mutations to process. + * + * Starts the write stream if necessary. + */ +export declare function fillWritePipeline(remoteStore: RemoteStore): Promise; +export declare function outstandingWrites(remoteStore: RemoteStore): number; +export declare function remoteStoreHandleCredentialChange(remoteStore: RemoteStore, user: User): Promise; +/** + * Toggles the network state when the client gains or loses its primary lease. + */ +export declare function remoteStoreApplyPrimaryState(remoteStore: RemoteStore, isPrimary: boolean): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/remote_syncer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/remote_syncer.d.ts new file mode 100644 index 0000000..949bc21 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/remote_syncer.d.ts @@ -0,0 +1,68 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { BatchId, TargetId } from '../core/types'; +import { DocumentKeySet } from '../model/collections'; +import { MutationBatchResult } from '../model/mutation_batch'; +import { FirestoreError } from '../util/error'; +import { RemoteEvent } from './remote_event'; +/** + * An interface that describes the actions the RemoteStore needs to perform on + * a cooperating synchronization engine. + */ +export interface RemoteSyncer { + /** + * Applies one remote event to the sync engine, notifying any views of the + * changes, and releasing any pending mutation batches that would become + * visible because of the snapshot version the remote event contains. + */ + applyRemoteEvent?(remoteEvent: RemoteEvent): Promise; + /** + * Rejects the listen for the given targetID. This can be triggered by the + * backend for any active target. + * + * @param targetId - The targetID corresponds to one previously initiated by + * the user as part of TargetData passed to listen() on RemoteStore. + * @param error - A description of the condition that has forced the rejection. + * Nearly always this will be an indication that the user is no longer + * authorized to see the data matching the target. + */ + rejectListen?(targetId: TargetId, error: FirestoreError): Promise; + /** + * Applies the result of a successful write of a mutation batch to the sync + * engine, emitting snapshots in any views that the mutation applies to, and + * removing the batch from the mutation queue. + */ + applySuccessfulWrite?(result: MutationBatchResult): Promise; + /** + * Rejects the batch, removing the batch from the mutation queue, recomputing + * the local view of any documents affected by the batch and then, emitting + * snapshots with the reverted value. + */ + rejectFailedWrite?(batchId: BatchId, error: FirestoreError): Promise; + /** + * Returns the set of remote document keys for the given target ID. This list + * includes the documents that were assigned to the target when we received + * the last snapshot. + */ + getRemoteKeysForTarget?(targetId: TargetId): DocumentKeySet; + /** + * Updates all local state to match the pending mutations for the given user. + * May be called repeatedly for the same user. + */ + handleCredentialChange?(user: User): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/rest_connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/rest_connection.d.ts new file mode 100644 index 0000000..1e58386 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/rest_connection.d.ts @@ -0,0 +1,53 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Token } from '../api/credentials'; +import { DatabaseId, DatabaseInfo } from '../core/database_info'; +import { ResourcePath } from '../model/path'; +import { StringMap } from '../util/types'; +import { Connection, Stream } from './connection'; +/** + * Base class for all Rest-based connections to the backend (WebChannel and + * HTTP). + */ +export declare abstract class RestConnection implements Connection { + private readonly databaseInfo; + protected readonly databaseId: DatabaseId; + protected readonly baseUrl: string; + private readonly databasePath; + private readonly requestParams; + get shouldResourcePathBeIncludedInRequest(): boolean; + constructor(databaseInfo: DatabaseInfo); + invokeRPC(rpcName: string, path: ResourcePath, req: Req, authToken: Token | null, appCheckToken: Token | null): Promise; + invokeStreamingRPC(rpcName: string, path: ResourcePath, request: Req, authToken: Token | null, appCheckToken: Token | null, expectedResponseCount?: number): Promise; + abstract openStream(rpcName: string, authToken: Token | null, appCheckToken: Token | null): Stream; + /** + * Modifies the headers for a request, adding any authorization token if + * present and any additional headers for the request. + */ + protected modifyHeadersForRequest(headers: StringMap, authToken: Token | null, appCheckToken: Token | null): void; + /** + * Performs an RPC request using an implementation specific networking layer. + */ + protected abstract performRPCRequest(rpcName: string, url: string, headers: StringMap, body: Req, _forwardCredentials: boolean): Promise; + private makeUrl; + /** + * Closes and cleans up any resources associated with the connection. This + * implementation is a no-op because there are no resources associated + * with the RestConnection that need to be cleaned up. + */ + terminate(): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/rpc_error.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/rpc_error.d.ts new file mode 100644 index 0000000..90d075c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/rpc_error.d.ts @@ -0,0 +1,74 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Code } from '../util/error'; +/** + * Determines whether an error code represents a permanent error when received + * in response to a non-write operation. + * + * See isPermanentWriteError for classifying write errors. + */ +export declare function isPermanentError(code: Code): boolean; +/** + * Determines whether an error code represents a permanent error when received + * in response to a write operation. + * + * Write operations must be handled specially because as of b/119437764, ABORTED + * errors on the write stream should be retried too (even though ABORTED errors + * are not generally retryable). + * + * Note that during the initial handshake on the write stream an ABORTED error + * signals that we should discard our stream token (i.e. it is permanent). This + * means a handshake error should be classified with isPermanentError, above. + */ +export declare function isPermanentWriteError(code: Code): boolean; +/** + * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'. + * + * @returns The Code equivalent to the given status string or undefined if + * there is no match. + */ +export declare function mapCodeFromRpcStatus(status: string): Code | undefined; +/** + * Maps an error Code from GRPC status code number, like 0, 1, or 14. These + * are not the same as HTTP status codes. + * + * @returns The Code equivalent to the given GRPC status code. Fails if there + * is no match. + */ +export declare function mapCodeFromRpcCode(code: number | undefined): Code; +/** + * Maps an RPC code from a Code. This is the reverse operation from + * mapCodeFromRpcCode and should really only be used in tests. + */ +export declare function mapRpcCodeFromCode(code: Code | undefined): number; +/** + * Converts an HTTP Status Code to the equivalent error code. + * + * @param status - An HTTP Status Code, like 200, 404, 503, etc. + * @returns The equivalent Code. Unknown status codes are mapped to + * Code.UNKNOWN. + */ +export declare function mapCodeFromHttpStatus(status?: number): Code; +/** + * Converts an HTTP response's error status to the equivalent error code. + * + * @param status - An HTTP error response status ("FAILED_PRECONDITION", + * "UNKNOWN", etc.) + * @returns The equivalent Code. Non-matching responses are mapped to + * Code.UNKNOWN. + */ +export declare function mapCodeFromHttpResponseErrorStatus(status: string): Code; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/serializer.d.ts new file mode 100644 index 0000000..bb1aeb9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/serializer.d.ts @@ -0,0 +1,124 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Aggregate } from '../core/aggregate'; +import { DatabaseId } from '../core/database_info'; +import { CompositeFilter, CompositeOperator, FieldFilter, Filter, Operator } from '../core/filter'; +import { Direction, OrderBy } from '../core/order_by'; +import { Query } from '../core/query'; +import { SnapshotVersion } from '../core/snapshot_version'; +import { Target } from '../core/target'; +import { Timestamp } from '../lite-api/timestamp'; +import { TargetData, TargetPurpose } from '../local/target_data'; +import { MutableDocument } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { FieldMask } from '../model/field_mask'; +import { Mutation, MutationResult } from '../model/mutation'; +import { ObjectValue } from '../model/object_value'; +import { FieldPath, ResourcePath } from '../model/path'; +import { ApiClientObjectMap as ProtoApiClientObjectMap, BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse, CompositeFilterOp as ProtoCompositeFilterOp, Document as ProtoDocument, DocumentMask as ProtoDocumentMask, DocumentsTarget as ProtoDocumentsTarget, FieldFilterOp as ProtoFieldFilterOp, FieldReference as ProtoFieldReference, Filter as ProtoFilter, ListenResponse as ProtoListenResponse, Order as ProtoOrder, OrderDirection as ProtoOrderDirection, QueryTarget as ProtoQueryTarget, RunAggregationQueryRequest as ProtoRunAggregationQueryRequest, Target as ProtoTarget, Timestamp as ProtoTimestamp, Write as ProtoWrite, WriteResult as ProtoWriteResult } from '../protos/firestore_proto_api'; +import { ByteString } from '../util/byte_string'; +import { Serializer } from './number_serializer'; +import { WatchChange } from './watch_change'; +/** + * This class generates JsonObject values for the Datastore API suitable for + * sending to either GRPC stub methods or via the JSON/HTTP REST API. + * + * The serializer supports both Protobuf.js and Proto3 JSON formats. By + * setting `useProto3Json` to true, the serializer will use the Proto3 JSON + * format. + * + * For a description of the Proto3 JSON format check + * https://developers.google.com/protocol-buffers/docs/proto3#json + * + * TODO(klimt): We can remove the databaseId argument if we keep the full + * resource name in documents. + */ +export declare class JsonProtoSerializer implements Serializer { + readonly databaseId: DatabaseId; + readonly useProto3Json: boolean; + constructor(databaseId: DatabaseId, useProto3Json: boolean); +} +/** + * Returns a value for a Date that's appropriate to put into a proto. + */ +export declare function toTimestamp(serializer: JsonProtoSerializer, timestamp: Timestamp): ProtoTimestamp; +/** + * Returns a Timestamp typed object given protobuf timestamp value. + */ +export declare function fromTimestamp(date: ProtoTimestamp): Timestamp; +/** + * Returns a value for bytes that's appropriate to put in a proto. + * + * Visible for testing. + */ +export declare function toBytes(serializer: JsonProtoSerializer, bytes: ByteString): string | Uint8Array; +/** + * Returns a ByteString based on the proto string value. + */ +export declare function fromBytes(serializer: JsonProtoSerializer, value: string | Uint8Array | undefined): ByteString; +export declare function toVersion(serializer: JsonProtoSerializer, version: SnapshotVersion): ProtoTimestamp; +export declare function fromVersion(version: ProtoTimestamp): SnapshotVersion; +export declare function toResourceName(databaseId: DatabaseId, path: ResourcePath): string; +export declare function toResourcePath(databaseId: DatabaseId, path?: ResourcePath): ResourcePath; +export declare function toName(serializer: JsonProtoSerializer, key: DocumentKey): string; +export declare function fromName(serializer: JsonProtoSerializer, name: string): DocumentKey; +export declare function getEncodedDatabaseId(serializer: JsonProtoSerializer): string; +/** Creates a Document proto from key and fields (but no create/update time) */ +export declare function toMutationDocument(serializer: JsonProtoSerializer, key: DocumentKey, fields: ObjectValue): ProtoDocument; +export declare function toDocument(serializer: JsonProtoSerializer, document: MutableDocument): ProtoDocument; +export declare function fromDocument(serializer: JsonProtoSerializer, document: ProtoDocument, hasCommittedMutations?: boolean): MutableDocument; +export declare function fromBatchGetDocumentsResponse(serializer: JsonProtoSerializer, result: ProtoBatchGetDocumentsResponse): MutableDocument; +export declare function fromWatchChange(serializer: JsonProtoSerializer, change: ProtoListenResponse): WatchChange; +export declare function versionFromListenResponse(change: ProtoListenResponse): SnapshotVersion; +export declare function toMutation(serializer: JsonProtoSerializer, mutation: Mutation): ProtoWrite; +export declare function fromMutation(serializer: JsonProtoSerializer, proto: ProtoWrite): Mutation; +export declare function fromWriteResults(protos: ProtoWriteResult[] | undefined, commitTime?: ProtoTimestamp): MutationResult[]; +export declare function toDocumentsTarget(serializer: JsonProtoSerializer, target: Target): ProtoDocumentsTarget; +export declare function fromDocumentsTarget(documentsTarget: ProtoDocumentsTarget): Target; +export declare function toQueryTarget(serializer: JsonProtoSerializer, target: Target): { + queryTarget: ProtoQueryTarget; + parent: ResourcePath; +}; +export declare function toRunAggregationQueryRequest(serializer: JsonProtoSerializer, target: Target, aggregates: Aggregate[], skipAliasing?: boolean): { + request: ProtoRunAggregationQueryRequest; + aliasMap: Record; + parent: ResourcePath; +}; +export declare function convertQueryTargetToQuery(target: ProtoQueryTarget): Query; +export declare function fromQueryTarget(target: ProtoQueryTarget): Target; +export declare function toListenRequestLabels(serializer: JsonProtoSerializer, targetData: TargetData): ProtoApiClientObjectMap | null; +export declare function toLabel(purpose: TargetPurpose): string | null; +export declare function toTarget(serializer: JsonProtoSerializer, targetData: TargetData): ProtoTarget; +export declare function toDirection(dir: Direction): ProtoOrderDirection; +export declare function fromDirection(dir: ProtoOrderDirection | undefined): Direction | undefined; +export declare function toOperatorName(op: Operator): ProtoFieldFilterOp; +export declare function toCompositeOperatorName(op: CompositeOperator): ProtoCompositeFilterOp; +export declare function fromOperatorName(op: ProtoFieldFilterOp): Operator; +export declare function fromCompositeOperatorName(op: ProtoCompositeFilterOp): CompositeOperator; +export declare function toFieldPathReference(path: FieldPath): ProtoFieldReference; +export declare function fromFieldPathReference(fieldReference: ProtoFieldReference): FieldPath; +export declare function toPropertyOrder(orderBy: OrderBy): ProtoOrder; +export declare function fromPropertyOrder(orderBy: ProtoOrder): OrderBy; +export declare function toFilter(filter: Filter): ProtoFilter; +export declare function toCompositeFilter(filter: CompositeFilter): ProtoFilter; +export declare function toUnaryOrFieldFilter(filter: FieldFilter): ProtoFilter; +export declare function fromUnaryFilter(filter: ProtoFilter): Filter; +export declare function fromFieldFilter(filter: ProtoFilter): FieldFilter; +export declare function fromCompositeFilter(filter: ProtoFilter): CompositeFilter; +export declare function toDocumentMask(fieldMask: FieldMask): ProtoDocumentMask; +export declare function fromDocumentMask(proto: ProtoDocumentMask): FieldMask; +export declare function isValidResourceName(path: ResourcePath): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/stream_bridge.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/stream_bridge.d.ts new file mode 100644 index 0000000..f17a080 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/stream_bridge.d.ts @@ -0,0 +1,45 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirestoreError } from '../util/error'; +import { Stream } from './connection'; +/** + * Provides a simple helper class that implements the Stream interface to + * bridge to other implementations that are streams but do not implement the + * interface. The stream callbacks are invoked with the callOn... methods. + */ +export declare class StreamBridge implements Stream { + private wrappedOnConnected; + private wrappedOnOpen; + private wrappedOnClose; + private wrappedOnMessage; + private sendFn; + private closeFn; + constructor(args: { + sendFn: (msg: I) => void; + closeFn: () => void; + }); + onConnected(callback: () => void): void; + onOpen(callback: () => void): void; + onClose(callback: (err?: FirestoreError) => void): void; + onMessage(callback: (msg: O) => void): void; + close(): void; + send(msg: I): void; + callOnConnected(): void; + callOnOpen(): void; + callOnClose(err?: FirestoreError): void; + callOnMessage(msg: O): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/watch_change.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/watch_change.d.ts new file mode 100644 index 0000000..1510515 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/remote/watch_change.d.ts @@ -0,0 +1,231 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseId } from '../core/database_info'; +import { SnapshotVersion } from '../core/snapshot_version'; +import { TargetId } from '../core/types'; +import { TargetData } from '../local/target_data'; +import { DocumentKeySet } from '../model/collections'; +import { MutableDocument } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { ByteString } from '../util/byte_string'; +import { FirestoreError } from '../util/error'; +import { ExistenceFilter } from './existence_filter'; +import { RemoteEvent } from './remote_event'; +/** + * Internal representation of the watcher API protocol buffers. + */ +export type WatchChange = DocumentWatchChange | WatchTargetChange | ExistenceFilterChange; +/** + * Represents a changed document and a list of target ids to which this change + * applies. + * + * If document has been deleted NoDocument will be provided. + */ +export declare class DocumentWatchChange { + /** The new document applies to all of these targets. */ + updatedTargetIds: TargetId[]; + /** The new document is removed from all of these targets. */ + removedTargetIds: TargetId[]; + /** The key of the document for this change. */ + key: DocumentKey; + /** + * The new document or NoDocument if it was deleted. Is null if the + * document went out of view without the server sending a new document. + */ + newDoc: MutableDocument | null; + constructor( + /** The new document applies to all of these targets. */ + updatedTargetIds: TargetId[], + /** The new document is removed from all of these targets. */ + removedTargetIds: TargetId[], + /** The key of the document for this change. */ + key: DocumentKey, + /** + * The new document or NoDocument if it was deleted. Is null if the + * document went out of view without the server sending a new document. + */ + newDoc: MutableDocument | null); +} +export declare class ExistenceFilterChange { + targetId: TargetId; + existenceFilter: ExistenceFilter; + constructor(targetId: TargetId, existenceFilter: ExistenceFilter); +} +export declare const enum WatchTargetChangeState { + NoChange = 0, + Added = 1, + Removed = 2, + Current = 3, + Reset = 4 +} +export declare class WatchTargetChange { + /** What kind of change occurred to the watch target. */ + state: WatchTargetChangeState; + /** The target IDs that were added/removed/set. */ + targetIds: TargetId[]; + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + resumeToken: ByteString; + /** An RPC error indicating why the watch failed. */ + cause: FirestoreError | null; + constructor( + /** What kind of change occurred to the watch target. */ + state: WatchTargetChangeState, + /** The target IDs that were added/removed/set. */ + targetIds: TargetId[], + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + resumeToken?: ByteString, + /** An RPC error indicating why the watch failed. */ + cause?: FirestoreError | null); +} +/** + * Interface implemented by RemoteStore to expose target metadata to the + * WatchChangeAggregator. + */ +export interface TargetMetadataProvider { + /** + * Returns the set of remote document keys for the given target ID as of the + * last raised snapshot. + */ + getRemoteKeysForTarget(targetId: TargetId): DocumentKeySet; + /** + * Returns the TargetData for an active target ID or 'null' if this target + * has become inactive + */ + getTargetDataForTarget(targetId: TargetId): TargetData | null; + /** + * Returns the database ID of the Firestore instance. + */ + getDatabaseId(): DatabaseId; +} +/** + * A helper class to accumulate watch changes into a RemoteEvent. + */ +export declare class WatchChangeAggregator { + private metadataProvider; + constructor(metadataProvider: TargetMetadataProvider); + /** The internal state of all tracked targets. */ + private targetStates; + /** Keeps track of the documents to update since the last raised snapshot. */ + private pendingDocumentUpdates; + private pendingDocumentUpdatesByTarget; + /** A mapping of document keys to their set of target IDs. */ + private pendingDocumentTargetMapping; + /** + * A map of targets with existence filter mismatches. These targets are + * known to be inconsistent and their listens needs to be re-established by + * RemoteStore. + */ + private pendingTargetResets; + /** + * Processes and adds the DocumentWatchChange to the current set of changes. + */ + handleDocumentChange(docChange: DocumentWatchChange): void; + /** Processes and adds the WatchTargetChange to the current set of changes. */ + handleTargetChange(targetChange: WatchTargetChange): void; + /** + * Iterates over all targetIds that the watch change applies to: either the + * targetIds explicitly listed in the change or the targetIds of all currently + * active targets. + */ + forEachTarget(targetChange: WatchTargetChange, fn: (targetId: TargetId) => void): void; + /** + * Handles existence filters and synthesizes deletes for filter mismatches. + * Targets that are invalidated by filter mismatches are added to + * `pendingTargetResets`. + */ + handleExistenceFilter(watchChange: ExistenceFilterChange): void; + /** + * Parse the bloom filter from the "unchanged_names" field of an existence + * filter. + */ + private parseBloomFilter; + /** + * Apply bloom filter to remove the deleted documents, and return the + * application status. + */ + private applyBloomFilter; + /** + * Filter out removed documents based on bloom filter membership result and + * return number of documents removed. + */ + private filterRemovedDocuments; + /** + * Converts the currently accumulated state into a remote event at the + * provided snapshot version. Resets the accumulated changes before returning. + */ + createRemoteEvent(snapshotVersion: SnapshotVersion): RemoteEvent; + /** + * Adds the provided document to the internal list of document updates and + * its document key to the given target's mapping. + */ + addDocumentToTarget(targetId: TargetId, document: MutableDocument): void; + /** + * Removes the provided document from the target mapping. If the + * document no longer matches the target, but the document's state is still + * known (e.g. we know that the document was deleted or we received the change + * that caused the filter mismatch), the new document can be provided + * to update the remote document cache. + */ + removeDocumentFromTarget(targetId: TargetId, key: DocumentKey, updatedDocument: MutableDocument | null): void; + removeTarget(targetId: TargetId): void; + /** + * Returns the current count of documents in the target. This includes both + * the number of documents that the LocalStore considers to be part of the + * target as well as any accumulated changes. + */ + private getCurrentDocumentCountForTarget; + /** + * Increment the number of acks needed from watch before we can consider the + * server to be 'in-sync' with the client's active targets. + */ + recordPendingTargetRequest(targetId: TargetId): void; + private ensureTargetState; + private ensureDocumentTargetMapping; + private ensureDocumentUpdateByTarget; + /** + * Verifies that the user is still interested in this target (by calling + * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs + * from watch. + */ + protected isActiveTarget(targetId: TargetId): boolean; + /** + * Returns the TargetData for an active target (i.e. a target that the user + * is still interested in that has no outstanding target change requests). + */ + protected targetDataForActiveTarget(targetId: TargetId): TargetData | null; + /** + * Resets the state of a Watch target to its initial state (e.g. sets + * 'current' to false, clears the resume token and removes its target mapping + * from all documents). + */ + private resetTarget; + /** + * Returns whether the LocalStore considers the document to be part of the + * specified target. + */ + private targetContainsDocument; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/tsdoc-metadata.json b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/tsdoc-metadata.json new file mode 100644 index 0000000..6af1f6a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/tsdoc-metadata.json @@ -0,0 +1,11 @@ +// This file is read by tools that parse documentation comments conforming to the TSDoc standard. +// It should be published with your NPM package. It should not be tracked by Git. +{ + "tsdocVersion": "0.12", + "toolPackages": [ + { + "packageName": "@microsoft/api-extractor", + "packageVersion": "0.1.2" + } + ] +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/array.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/array.d.ts new file mode 100644 index 0000000..8be6593 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/array.d.ts @@ -0,0 +1,70 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns true iff the array contains the value using strong equality. + */ +export declare function includes(array: T[], value: T): boolean; +/** + * Returns true iff the array contains any value matching the predicate + */ +export declare function some(array: T[], predicate: (t: T) => boolean): boolean; +/** + * Calls predicate function for each item in the array until the predicate + * returns true, at which point the index of that item is returned. If the + * predicate does not return true for any item, null is returned. + */ +export declare function findIndex(array: A[], predicate: (value: A) => boolean): number | null; +/** + * Compares two array for equality using comparator. The method computes the + * intersection and invokes `onAdd` for every element that is in `after` but not + * `before`. `onRemove` is invoked for every element in `before` but missing + * from `after`. + * + * The method creates a copy of both `before` and `after` and runs in O(n log + * n), where n is the size of the two lists. + * + * @param before - The elements that exist in the original array. + * @param after - The elements to diff against the original array. + * @param comparator - The comparator for the elements in before and after. + * @param onAdd - A function to invoke for every element that is part of ` + * after` but not `before`. + * @param onRemove - A function to invoke for every element that is part of + * `before` but not `after`. + */ +export declare function diffArrays(before: T[], after: T[], comparator: (l: T, r: T) => number, onAdd: (entry: T) => void, onRemove: (entry: T) => void): void; +/** + * Verifies equality for an array of objects using the `isEqual` interface. + * + * @private + * @internal + * @param left Array of objects supporting `isEqual`. + * @param right Array of objects supporting `isEqual`. + * @return True if arrays are equal. + */ +export declare function isArrayEqual boolean; +}>(left: T[], right: T[]): boolean; +/** + * Verifies equality for an array of primitives. + * + * @private + * @internal + * @param left Array of primitives. + * @param right Array of primitives. + * @return True if arrays are equal. + */ +export declare function isPrimitiveArrayEqual(left: T[], right: T[]): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/assert.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/assert.d.ts new file mode 100644 index 0000000..294b08a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/assert.d.ts @@ -0,0 +1,78 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Unconditionally fails, throwing an Error with the given message. + * Messages are stripped in production builds. + * + * Returns `never` and can be used in expressions: + * @example + * let futureVar = fail('not implemented yet'); + * + * @param code generate a new unique value with `yarn assertion-id:generate` + * Search for an existing value using `yarn assertion-id:find X` + */ +export declare function fail(code: number, message: string, context?: Record): never; +/** + * Unconditionally fails, throwing an Error with the given message. + * Messages are stripped in production builds. + * + * Returns `never` and can be used in expressions: + * @example + * let futureVar = fail('not implemented yet'); + * + * @param id generate a new unique value with `yarn assertion-id:generate` + * Search for an existing value using `yarn assertion-id:find X` + */ +export declare function fail(id: number, context?: Record): never; +/** + * Fails if the given assertion condition is false, throwing an Error with the + * given message if it did. + * + * Messages are stripped in production builds. + * + * @param id generate a new unique value with `yarn assertion-idgenerate`. + * Search for an existing value using `yarn assertion-id:find X` + */ +export declare function hardAssert(assertion: boolean, id: number, message: string, context?: Record): asserts assertion; +/** + * Fails if the given assertion condition is false, throwing an Error with the + * given message if it did. + * + * Messages are stripped in production builds. + * + * @param id generate a new unique value with `yarn assertion-id:generate`. + * Search for an existing value using `yarn assertion-id:find X` + */ +export declare function hardAssert(assertion: boolean, id: number, context?: Record): asserts assertion; +/** + * Fails if the given assertion condition is false, throwing an Error with the + * given message if it did. + * + * The code of callsites invoking this function are stripped out in production + * builds. Any side-effects of code within the debugAssert() invocation will not + * happen in this case. + * + * @internal + */ +export declare function debugAssert(assertion: boolean, message: string): asserts assertion; +/** + * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an + * instance of `T` before casting. + */ +export declare function debugCast(obj: object, constructor: { + new (...args: any[]): T; +}): T | never; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/async_observer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/async_observer.d.ts new file mode 100644 index 0000000..21a965e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/async_observer.d.ts @@ -0,0 +1,31 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Observer } from '../core/event_manager'; +import { FirestoreError } from './error'; +export declare class AsyncObserver implements Observer { + private observer; + /** + * When set to true, will not raise future events. Necessary to deal with + * async detachment of listener. + */ + private muted; + constructor(observer: Partial>); + next(value: T): void; + error(error: FirestoreError): void; + mute(): void; + private scheduleEvent; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/async_queue.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/async_queue.d.ts new file mode 100644 index 0000000..098746b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/async_queue.d.ts @@ -0,0 +1,180 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirestoreError } from './error'; +/** + * Wellknown "timer" IDs used when scheduling delayed operations on the + * AsyncQueue. These IDs can then be used from tests to check for the presence + * of operations or to run them early. + * + * The string values are used when encoding these timer IDs in JSON spec tests. + */ +export declare const enum TimerId { + /** All can be used with runDelayedOperationsEarly() to run all timers. */ + All = "all", + /** + * The following 5 timers are used in persistent_stream.ts for the listen and + * write streams. The "Idle" timer is used to close the stream due to + * inactivity. The "ConnectionBackoff" timer is used to restart a stream once + * the appropriate backoff delay has elapsed. The health check is used to mark + * a stream healthy if it has not received an error during its initial setup. + */ + ListenStreamIdle = "listen_stream_idle", + ListenStreamConnectionBackoff = "listen_stream_connection_backoff", + WriteStreamIdle = "write_stream_idle", + WriteStreamConnectionBackoff = "write_stream_connection_backoff", + HealthCheckTimeout = "health_check_timeout", + /** + * A timer used in online_state_tracker.ts to transition from + * OnlineState.Unknown to Offline after a set timeout, rather than waiting + * indefinitely for success or failure. + */ + OnlineStateTimeout = "online_state_timeout", + /** + * A timer used to update the client metadata in IndexedDb, which is used + * to determine the primary leaseholder. + */ + ClientMetadataRefresh = "client_metadata_refresh", + /** A timer used to periodically attempt LRU Garbage collection */ + LruGarbageCollection = "lru_garbage_collection", + /** + * A timer used to retry transactions. Since there can be multiple concurrent + * transactions, multiple of these may be in the queue at a given time. + */ + TransactionRetry = "transaction_retry", + /** + * A timer used to retry operations scheduled via retryable AsyncQueue + * operations. + */ + AsyncQueueRetry = "async_queue_retry", + /** + * A timer used to periodically attempt index backfill. + */ + IndexBackfill = "index_backfill" +} +/** + * Represents an operation scheduled to be run in the future on an AsyncQueue. + * + * It is created via DelayedOperation.createAndSchedule(). + * + * Supports cancellation (via cancel()) and early execution (via skipDelay()). + * + * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type + * in newer versions of TypeScript defines `finally`, which is not available in + * IE. + */ +export declare class DelayedOperation implements PromiseLike { + private readonly asyncQueue; + readonly timerId: TimerId; + readonly targetTimeMs: number; + private readonly op; + private readonly removalCallback; + private timerHandle; + private readonly deferred; + private constructor(); + get promise(): Promise; + /** + * Creates and returns a DelayedOperation that has been scheduled to be + * executed on the provided asyncQueue after the provided delayMs. + * + * @param asyncQueue - The queue to schedule the operation on. + * @param id - A Timer ID identifying the type of operation this is. + * @param delayMs - The delay (ms) before the operation should be scheduled. + * @param op - The operation to run. + * @param removalCallback - A callback to be called synchronously once the + * operation is executed or canceled, notifying the AsyncQueue to remove it + * from its delayedOperations list. + * PORTING NOTE: This exists to prevent making removeDelayedOperation() and + * the DelayedOperation class public. + */ + static createAndSchedule(asyncQueue: AsyncQueue, timerId: TimerId, delayMs: number, op: () => Promise, removalCallback: (op: DelayedOperation) => void): DelayedOperation; + /** + * Starts the timer. This is called immediately after construction by + * createAndSchedule(). + */ + private start; + /** + * Queues the operation to run immediately (if it hasn't already been run or + * canceled). + */ + skipDelay(): void; + /** + * Cancels the operation if it hasn't already been executed or canceled. The + * promise will be rejected. + * + * As long as the operation has not yet been run, calling cancel() provides a + * guarantee that the operation will not be run. + */ + cancel(reason?: string): void; + then: (onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined) => Promise; + private handleDelayElapsed; + private clearTimeout; +} +export interface AsyncQueue { + readonly isShuttingDown: boolean; + /** + * Adds a new operation to the queue without waiting for it to complete (i.e. + * we ignore the Promise result). + */ + enqueueAndForget(op: () => Promise): void; + /** + * Regardless if the queue has initialized shutdown, adds a new operation to the + * queue without waiting for it to complete (i.e. we ignore the Promise result). + */ + enqueueAndForgetEvenWhileRestricted(op: () => Promise): void; + /** + * Initialize the shutdown of this queue. Once this method is called, the + * only possible way to request running an operation is through + * `enqueueEvenWhileRestricted()`. + * + * @param purgeExistingTasks Whether already enqueued tasked should be + * rejected (unless enqueued with `enqueueEvenWhileRestricted()`). Defaults + * to false. + */ + enterRestrictedMode(purgeExistingTasks?: boolean): void; + /** + * Adds a new operation to the queue. Returns a promise that will be resolved + * when the promise returned by the new operation is (with its value). + */ + enqueue(op: () => Promise): Promise; + /** + * Enqueue a retryable operation. + * + * A retryable operation is rescheduled with backoff if it fails with a + * IndexedDbTransactionError (the error type used by SimpleDb). All + * retryable operations are executed in order and only run if all prior + * operations were retried successfully. + */ + enqueueRetryable(op: () => Promise): void; + /** + * Schedules an operation to be queued on the AsyncQueue once the specified + * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel + * or fast-forward the operation prior to its running. + */ + enqueueAfterDelay(timerId: TimerId, delayMs: number, op: () => Promise): DelayedOperation; + /** + * Verifies there's an operation currently in-progress on the AsyncQueue. + * Unfortunately we can't verify that the running code is in the promise chain + * of that operation, so this isn't a foolproof check, but it should be enough + * to catch some bugs. + */ + verifyOperationInProgress(): void; +} +/** + * Returns a FirestoreError that can be surfaced to the user if the provided + * error is an IndexedDbTransactionError. Re-throws the error otherwise. + */ +export declare function wrapInUserErrorIfRecoverable(e: Error, msg: string): FirestoreError; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/async_queue_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/async_queue_impl.d.ts new file mode 100644 index 0000000..6dedc85 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/async_queue_impl.d.ts @@ -0,0 +1,75 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AsyncQueue, DelayedOperation, TimerId } from './async_queue'; +import { FirestoreError } from './error'; +export declare class AsyncQueueImpl implements AsyncQueue { + private tail; + private retryableOps; + private _isShuttingDown; + private delayedOperations; + failure: FirestoreError | null; + private operationInProgress; + private skipNonRestrictedTasks; + private timerIdsToSkip; + private backoff; + private visibilityHandler; + constructor(tail?: Promise); + get isShuttingDown(): boolean; + /** + * Adds a new operation to the queue without waiting for it to complete (i.e. + * we ignore the Promise result). + */ + enqueueAndForget(op: () => Promise): void; + enqueueAndForgetEvenWhileRestricted(op: () => Promise): void; + enterRestrictedMode(purgeExistingTasks?: boolean): void; + enqueue(op: () => Promise): Promise; + enqueueRetryable(op: () => Promise): void; + /** + * Runs the next operation from the retryable queue. If the operation fails, + * reschedules with backoff. + */ + private retryNextOp; + private enqueueInternal; + enqueueAfterDelay(timerId: TimerId, delayMs: number, op: () => Promise): DelayedOperation; + private verifyNotFailed; + verifyOperationInProgress(): void; + /** + * Waits until all currently queued tasks are finished executing. Delayed + * operations are not run. + */ + drain(): Promise; + /** + * For Tests: Determine if a delayed operation with a particular TimerId + * exists. + */ + containsDelayedOperation(timerId: TimerId): boolean; + /** + * For Tests: Runs some or all delayed operations early. + * + * @param lastTimerId - Delayed operations up to and including this TimerId + * will be drained. Pass TimerId.All to run all delayed operations. + * @returns a Promise that resolves once all operations have been run. + */ + runAllDelayedOperationsUntil(lastTimerId: TimerId): Promise; + /** + * For Tests: Skip all subsequent delays for a timer id. + */ + skipDelaysForTimerId(timerId: TimerId): void; + /** Called once a DelayedOperation is run or canceled. */ + private removeDelayedOperation; +} +export declare function newAsyncQueue(): AsyncQueue; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/base64_decode_error.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/base64_decode_error.d.ts new file mode 100644 index 0000000..18800ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/base64_decode_error.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An error encountered while decoding base64 string. + */ +export declare class Base64DecodeError extends Error { + readonly name = "Base64DecodeError"; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/bundle_builder_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/bundle_builder_impl.d.ts new file mode 100644 index 0000000..57e978c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/bundle_builder_impl.d.ts @@ -0,0 +1,97 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Firestore } from '../api/database'; +import { Query } from '../core/query'; +import { DocumentData } from '../lite-api/reference'; +import { Timestamp } from '../lite-api/timestamp'; +import { DocumentKey } from '../model/document_key'; +/** + * Builds a Firestore data bundle with results from the given document and query snapshots. + */ +export declare class BundleBuilder { + private firestore; + readonly bundleId: string; + private documents; + private namedQueries; + private latestReadTime; + private databaseId; + private readonly serializer; + private readonly userDataReader; + constructor(firestore: Firestore, bundleId: string); + /** + * Adds data from a DocumentSnapshot to the bundle. + * @internal + * @param docBundleData A DocumentSnapshotBundleData containing information from the + * DocumentSnapshot. Note we cannot accept a DocumentSnapshot directly due to a circular + * dependency error. + * @param queryName The name of the QuerySnapshot if this document is part of a Query. + */ + addBundleDocument(docBundleData: DocumentSnapshotBundleData, queryName?: string): void; + /** + * Adds data from a QuerySnapshot to the bundle. + * @internal + * @param docBundleData A QuerySnapshotBundleData containing information from the + * QuerySnapshot. Note we cannot accept a QuerySnapshot directly due to a circular + * dependency error. + */ + addBundleQuery(queryBundleData: QuerySnapshotBundleData): void; + /** + * Convert data from a DocumentSnapshot into the serialized form within a bundle. + * @private + * @internal + * @param docBundleData a DocumentSnapshotBundleData containing the data required to + * serialize a document. + */ + private toBundleDocument; + /** + * Converts a IBundleElement to a Buffer whose content is the length prefixed JSON representation + * of the element. + * @private + * @internal + * @param bundleElement A ProtoBundleElement that is expected to be Proto3 JSON compatible. + */ + private lengthPrefixedString; + /** + * Construct a serialized string containing document and query information that has previously + * been added to the BundleBuilder through the addBundleDocument and addBundleQuery methods. + * @internal + */ + build(): string; +} +/** + * Interface for an object that contains data required to bundle a DocumentSnapshot. + * @internal + */ +export interface DocumentSnapshotBundleData { + documentData: DocumentData; + documentKey: DocumentKey; + documentPath: string; + documentExists: boolean; + createdTime: Timestamp; + readTime?: Timestamp; + versionTime: Timestamp; +} +/** + * Interface for an object that contains data required to bundle a QuerySnapshot. + * @internal + */ +export interface QuerySnapshotBundleData { + name: string; + query: Query; + parent: string; + docBundleDataArray: DocumentSnapshotBundleData[]; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/bundle_reader.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/bundle_reader.d.ts new file mode 100644 index 0000000..cfe6dbd --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/bundle_reader.d.ts @@ -0,0 +1,67 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BundleElement, BundleMetadata } from '../protos/firestore_bundle_proto'; +import { JsonProtoSerializer } from '../remote/serializer'; +/** + * A complete element in the bundle stream, together with the byte length it + * occupies in the stream. + */ +export declare class SizedBundleElement { + readonly payload: BundleElement; + readonly byteLength: number; + constructor(payload: BundleElement, byteLength: number); + isBundleMetadata(): boolean; +} +export type BundleSource = ReadableStream | ArrayBuffer | Uint8Array; +/** + * A class representing a bundle. + * + * Takes a bundle stream or buffer, and presents abstractions to read bundled + * elements out of the underlying content. + */ +export interface BundleReader { + serializer: JsonProtoSerializer; + close(): Promise; + /** + * Returns the metadata of the bundle. + */ + getMetadata(): Promise; + /** + * Returns the next BundleElement (together with its byte size in the bundle) + * that has not been read from underlying ReadableStream. Returns null if we + * have reached the end of the stream. + */ + nextElement(): Promise; +} +/** + * A class representing a synchronized bundle reader. + * + * Takes a bundle string buffer, parses the data, and provides accessors to the data contained + * within it. + */ +export interface BundleReaderSync { + serializer: JsonProtoSerializer; + /** + * Returns the metadata of the bundle. + */ + getMetadata(): BundleMetadata; + /** + * Returns BundleElements parsed from the bundle. Returns an empty array if no bundle elements + * exist. + */ + getElements(): SizedBundleElement[]; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/bundle_reader_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/bundle_reader_impl.d.ts new file mode 100644 index 0000000..0858a93 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/bundle_reader_impl.d.ts @@ -0,0 +1,19 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { JsonProtoSerializer } from '../remote/serializer'; +import { BundleReader } from './bundle_reader'; +export declare function newBundleReader(reader: ReadableStreamDefaultReader, serializer: JsonProtoSerializer): BundleReader; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/bundle_reader_sync_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/bundle_reader_sync_impl.d.ts new file mode 100644 index 0000000..638497f --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/bundle_reader_sync_impl.d.ts @@ -0,0 +1,59 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BundleMetadata } from '../protos/firestore_bundle_proto'; +import { JsonProtoSerializer } from '../remote/serializer'; +import { BundleReaderSync, SizedBundleElement } from './bundle_reader'; +/** + * A class that can parse a bundle form the string serialization of a bundle. + */ +export declare class BundleReaderSyncImpl implements BundleReaderSync { + private bundleData; + readonly serializer: JsonProtoSerializer; + private metadata; + private elements; + private cursor; + constructor(bundleData: string, serializer: JsonProtoSerializer); + getMetadata(): BundleMetadata; + getElements(): SizedBundleElement[]; + /** + * Parses the next element of the bundle. + * + * @returns a SizedBundleElement representation of the next element in the bundle, or null if + * no more elements exist. + */ + private nextElement; + /** + * Reads from a specified position from the bundleData string, for a specified + * number of bytes. + * + * @param length how many characters to read. + * @returns a string parsed from the bundle. + */ + private readJsonString; + /** + * Reads from the current cursor until the first '{'. + * + * @returns A string to integer represention of the parsed value. + * @throws An {@link Error} if the cursor has reached the end of the stream, since lengths + * prefix bundle objects. + */ + private readLength; +} +/** + * Creates an instance of BundleReader without exposing the BundleReaderSyncImpl class type. + */ +export declare function newBundleReaderSync(bundleData: string, serializer: JsonProtoSerializer): BundleReaderSync; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/byte_stream.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/byte_stream.d.ts new file mode 100644 index 0000000..72d8ed7 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/byte_stream.d.ts @@ -0,0 +1,29 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * How many bytes to read each time when `ReadableStreamReader.read()` is + * called. Only applicable for byte streams that we control (e.g. those backed + * by an UInt8Array). + */ +export declare const DEFAULT_BYTES_PER_READ = 10240; +/** + * Builds a `ByteStreamReader` from a UInt8Array. + * @param source - The data source to use. + * @param bytesPerRead - How many bytes each `read()` from the returned reader + * will read. + */ +export declare function toByteStreamReaderHelper(source: Uint8Array, bytesPerRead?: number): ReadableStreamDefaultReader; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/byte_string.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/byte_string.d.ts new file mode 100644 index 0000000..9aec389 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/byte_string.d.ts @@ -0,0 +1,46 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Immutable class that represents a "proto" byte string. + * + * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when + * sent on the wire. This class abstracts away this differentiation by holding + * the proto byte string in a common class that must be converted into a string + * before being sent as a proto. + * @internal + */ +export declare class ByteString { + private readonly binaryString; + static readonly EMPTY_BYTE_STRING: ByteString; + private constructor(); + static fromBase64String(base64: string): ByteString; + static fromUint8Array(array: Uint8Array): ByteString; + [Symbol.iterator](): Iterator; + toBase64(): string; + toUint8Array(): Uint8Array; + approximateByteSize(): number; + compareTo(other: ByteString): number; + isEqual(other: ByteString): boolean; +} +/** + * Helper function to convert an Uint8array to a binary string. + */ +export declare function binaryStringFromUint8Array(array: Uint8Array): string; +/** + * Helper function to convert a binary string to an Uint8Array. + */ +export declare function uint8ArrayFromBinaryString(binaryString: string): Uint8Array; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/debug_uid.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/debug_uid.d.ts new file mode 100644 index 0000000..b590233 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/debug_uid.d.ts @@ -0,0 +1,28 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Generates and returns a unique ID as a hexadecimal string. + * + * The returned ID is intended to be used in debug logging messages to help + * correlate log messages that may be spatially separated in the logs, but + * logically related. For example, a network connection could include the same + * "debug ID" string in all of its log messages to help trace a specific + * connection over time. + * + * @return the 10-character generated ID (e.g. "0xa1b2c3d4"). + */ +export declare function generateUniqueDebugId(): string; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/error.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/error.d.ts new file mode 100644 index 0000000..e49c172 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/error.d.ts @@ -0,0 +1,195 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseError } from '@firebase/util'; +/** + * The set of Firestore status codes. The codes are the same at the ones + * exposed by gRPC here: + * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md + * + * Possible values: + * - 'cancelled': The operation was cancelled (typically by the caller). + * - 'unknown': Unknown error or an error from a different error domain. + * - 'invalid-argument': Client specified an invalid argument. Note that this + * differs from 'failed-precondition'. 'invalid-argument' indicates + * arguments that are problematic regardless of the state of the system + * (e.g. an invalid field name). + * - 'deadline-exceeded': Deadline expired before operation could complete. + * For operations that change the state of the system, this error may be + * returned even if the operation has completed successfully. For example, + * a successful response from a server could have been delayed long enough + * for the deadline to expire. + * - 'not-found': Some requested document was not found. + * - 'already-exists': Some document that we attempted to create already + * exists. + * - 'permission-denied': The caller does not have permission to execute the + * specified operation. + * - 'resource-exhausted': Some resource has been exhausted, perhaps a + * per-user quota, or perhaps the entire file system is out of space. + * - 'failed-precondition': Operation was rejected because the system is not + * in a state required for the operation's execution. + * - 'aborted': The operation was aborted, typically due to a concurrency + * issue like transaction aborts, etc. + * - 'out-of-range': Operation was attempted past the valid range. + * - 'unimplemented': Operation is not implemented or not supported/enabled. + * - 'internal': Internal errors. Means some invariants expected by + * underlying system has been broken. If you see one of these errors, + * something is very broken. + * - 'unavailable': The service is currently unavailable. This is most likely + * a transient condition and may be corrected by retrying with a backoff. + * - 'data-loss': Unrecoverable data loss or corruption. + * - 'unauthenticated': The request does not have valid authentication + * credentials for the operation. + */ +export type FirestoreErrorCode = 'cancelled' | 'unknown' | 'invalid-argument' | 'deadline-exceeded' | 'not-found' | 'already-exists' | 'permission-denied' | 'resource-exhausted' | 'failed-precondition' | 'aborted' | 'out-of-range' | 'unimplemented' | 'internal' | 'unavailable' | 'data-loss' | 'unauthenticated'; +/** + * Error Codes describing the different ways Firestore can fail. These come + * directly from GRPC. + */ +export type Code = FirestoreErrorCode; +export declare const Code: { + /** Not an error; returned on success. */ + OK: FirestoreErrorCode; + /** The operation was cancelled (typically by the caller). */ + CANCELLED: FirestoreErrorCode; + /** Unknown error or an error from a different error domain. */ + UNKNOWN: FirestoreErrorCode; + /** + * Client specified an invalid argument. Note that this differs from + * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are + * problematic regardless of the state of the system (e.g., a malformed file + * name). + */ + INVALID_ARGUMENT: FirestoreErrorCode; + /** + * Deadline expired before operation could complete. For operations that + * change the state of the system, this error may be returned even if the + * operation has completed successfully. For example, a successful response + * from a server could have been delayed long enough for the deadline to + * expire. + */ + DEADLINE_EXCEEDED: FirestoreErrorCode; + /** Some requested entity (e.g., file or directory) was not found. */ + NOT_FOUND: FirestoreErrorCode; + /** + * Some entity that we attempted to create (e.g., file or directory) already + * exists. + */ + ALREADY_EXISTS: FirestoreErrorCode; + /** + * The caller does not have permission to execute the specified operation. + * PERMISSION_DENIED must not be used for rejections caused by exhausting + * some resource (use RESOURCE_EXHAUSTED instead for those errors). + * PERMISSION_DENIED must not be used if the caller cannot be identified + * (use UNAUTHENTICATED instead for those errors). + */ + PERMISSION_DENIED: FirestoreErrorCode; + /** + * The request does not have valid authentication credentials for the + * operation. + */ + UNAUTHENTICATED: FirestoreErrorCode; + /** + * Some resource has been exhausted, perhaps a per-user quota, or perhaps the + * entire file system is out of space. + */ + RESOURCE_EXHAUSTED: FirestoreErrorCode; + /** + * Operation was rejected because the system is not in a state required for + * the operation's execution. For example, directory to be deleted may be + * non-empty, an rmdir operation is applied to a non-directory, etc. + * + * A litmus test that may help a service implementor in deciding + * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: + * (a) Use UNAVAILABLE if the client can retry just the failing call. + * (b) Use ABORTED if the client should retry at a higher-level + * (e.g., restarting a read-modify-write sequence). + * (c) Use FAILED_PRECONDITION if the client should not retry until + * the system state has been explicitly fixed. E.g., if an "rmdir" + * fails because the directory is non-empty, FAILED_PRECONDITION + * should be returned since the client should not retry unless + * they have first fixed up the directory by deleting files from it. + * (d) Use FAILED_PRECONDITION if the client performs conditional + * REST Get/Update/Delete on a resource and the resource on the + * server does not match the condition. E.g., conflicting + * read-modify-write on the same resource. + */ + FAILED_PRECONDITION: FirestoreErrorCode; + /** + * The operation was aborted, typically due to a concurrency issue like + * sequencer check failures, transaction aborts, etc. + * + * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, + * and UNAVAILABLE. + */ + ABORTED: FirestoreErrorCode; + /** + * Operation was attempted past the valid range. E.g., seeking or reading + * past end of file. + * + * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed + * if the system state changes. For example, a 32-bit file system will + * generate INVALID_ARGUMENT if asked to read at an offset that is not in the + * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from + * an offset past the current file size. + * + * There is a fair bit of overlap between FAILED_PRECONDITION and + * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) + * when it applies so that callers who are iterating through a space can + * easily look for an OUT_OF_RANGE error to detect when they are done. + */ + OUT_OF_RANGE: FirestoreErrorCode; + /** Operation is not implemented or not supported/enabled in this service. */ + UNIMPLEMENTED: FirestoreErrorCode; + /** + * Internal errors. Means some invariants expected by underlying System has + * been broken. If you see one of these errors, Something is very broken. + */ + INTERNAL: FirestoreErrorCode; + /** + * The service is currently unavailable. This is a most likely a transient + * condition and may be corrected by retrying with a backoff. + * + * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, + * and UNAVAILABLE. + */ + UNAVAILABLE: FirestoreErrorCode; + /** Unrecoverable data loss or corruption. */ + DATA_LOSS: FirestoreErrorCode; +}; +/** An error returned by a Firestore operation. */ +export declare class FirestoreError extends FirebaseError { + /** + * The backend error code associated with this error. + */ + readonly code: FirestoreErrorCode; + /** + * A custom error description. + */ + readonly message: string; + /** The stack of the error. */ + readonly stack?: string; + /** @hideconstructor */ + constructor( + /** + * The backend error code associated with this error. + */ + code: FirestoreErrorCode, + /** + * A custom error description. + */ + message: string); +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/input_validation.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/input_validation.d.ts new file mode 100644 index 0000000..c62ae20 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/input_validation.d.ts @@ -0,0 +1,56 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ResourcePath } from '../model/path'; +/** Types accepted by validateType() and related methods for validation. */ +export type ValidationType = 'undefined' | 'object' | 'function' | 'boolean' | 'number' | 'string' | 'non-empty string'; +export declare function validateNonEmptyArgument(functionName: string, argumentName: string, argument?: string): asserts argument is string; +/** + * Validates that two boolean options are not set at the same time. + * @internal + */ +export declare function validateIsNotUsedTogether(optionName1: string, argument1: boolean | undefined, optionName2: string, argument2: boolean | undefined): void; +/** + * Validates that `path` refers to a document (indicated by the fact it contains + * an even numbers of segments). + */ +export declare function validateDocumentPath(path: ResourcePath): void; +/** + * Validates that `path` refers to a collection (indicated by the fact it + * contains an odd numbers of segments). + */ +export declare function validateCollectionPath(path: ResourcePath): void; +/** + * Returns true if it's a non-null object without a custom prototype + * (i.e. excludes Array, Date, etc.). + */ +export declare function isPlainObject(input: unknown): boolean; +/** Returns a string describing the type / value of the provided input. */ +export declare function valueDescription(input: unknown): string; +/** try to get the constructor name for an object. */ +export declare function tryGetCustomObjectType(input: object): string | null; +/** + * Casts `obj` to `T`, optionally unwrapping Compat types to expose the + * underlying instance. Throws if `obj` is not an instance of `T`. + * + * This cast is used in the Lite and Full SDK to verify instance types for + * arguments passed to the public API. + * @internal + */ +export declare function cast(obj: object, constructor: { + new (...args: any[]): T; +}): T | never; +export declare function validatePositiveNumber(functionName: string, n: number): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/json_validation.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/json_validation.d.ts new file mode 100644 index 0000000..df52006 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/json_validation.d.ts @@ -0,0 +1,70 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A list of data types Firestore objects may serialize in their toJSON implemenetations. + * @private + * @internal + */ +export type JsonTypeDesc = 'object' | 'string' | 'number' | 'boolean' | 'null' | 'undefined'; +/** + * An association of JsonTypeDesc values to their native types. + * @private + * @internal + */ +export type TSType = T extends 'object' ? object : T extends 'string' ? string : T extends 'number' ? number : T extends 'boolean' ? boolean : T extends 'null' ? null : T extends 'undefined' ? undefined : never; +/** + * The representation of a JSON object property name and its type value. + * @private + * @internal + */ +export interface Property { + value?: TSType; + typeString: JsonTypeDesc; +} +/** + * A type Firestore data types may use to define the fields used in their JSON serialization. + * @private + * @internal + */ +export interface JsonSchema { + [key: string]: Property; +} +/** + * Associates the JSON property type to the native type and sets them to be Required. + * @private + * @internal + */ +export type Json = { + [K in keyof T]: Required['value']; +}; +/** + * Helper function to define a JSON schema {@link Property}. + * @private + * @internal + */ +export declare function property(typeString: T, optionalValue?: TSType): Property; +/** + * Validates the JSON object based on the provided schema, and narrows the type to the provided + * JSON schema. + * @private + * @internal + * + * @param json A JSON object to validate. + * @param scheme a {@link JsonSchema} that defines the properties to validate. + * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise. + */ +export declare function validateJSON(json: object, schema: S): json is Json; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/log.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/log.d.ts new file mode 100644 index 0000000..f638baa --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/log.d.ts @@ -0,0 +1,39 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { LogLevel, LogLevelString } from '@firebase/logger'; +export { LogLevel, LogLevelString }; +export declare function getLogLevel(): LogLevel; +/** + * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). + * + * @param logLevel - The verbosity you set for activity and error logging. Can + * be any of the following values: + * + *

+ */ +export declare function setLogLevel(logLevel: LogLevelString): void; +export declare function logDebug(msg: string, ...obj: unknown[]): void; +export declare function logError(msg: string, ...obj: unknown[]): void; +/** + * @internal + */ +export declare function logWarn(msg: string, ...obj: unknown[]): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/logic_utils.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/logic_utils.d.ts new file mode 100644 index 0000000..2333586 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/logic_utils.d.ts @@ -0,0 +1,52 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { CompositeFilter, Filter } from '../core/filter'; +/** + * Provides utility functions that help with boolean logic transformations needed for handling + * complex filters used in queries. + */ +/** + * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in + * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given + * input into a disjunction of equality filters and returns the expanded filter. + */ +export declare function computeInExpansion(filter: Filter): Filter; +/** + * Given a composite filter, returns the list of terms in its disjunctive normal form. + * + *

Each element in the return value is one term of the resulting DNF. For instance: For the + * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list + * with two elements: a composite filter that performs (A && C), and a composite filter that + * performs (B && C). + * + * @param filter the composite filter to calculate DNF transform for. + * @return the terms in the DNF transform. + */ +export declare function getDnfTerms(filter: CompositeFilter): Filter[]; +export declare function computeDistributedNormalForm(filter: Filter): Filter; +export declare function applyDistribution(lhs: Filter, rhs: Filter): Filter; +/** + * Applies the associativity property to the given filter and returns the resulting filter. + * + *

    + *
  • A | (B | C) == (A | B) | C == (A | B | C) + *
  • A & (B & C) == (A & B) & C == (A & B & C) + *
+ * + *

For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic + */ +export declare function applyAssociation(filter: Filter): Filter; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/misc.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/misc.d.ts new file mode 100644 index 0000000..95d4d43 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/misc.d.ts @@ -0,0 +1,46 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export type EventHandler = (value: E) => void; +export interface Indexable { + [k: string]: unknown; +} +/** + * A utility class for generating unique alphanumeric IDs of a specified length. + * + * @internal + * Exported internally for testing purposes. + */ +export declare class AutoId { + static newId(): string; +} +export declare function primitiveComparator(left: T, right: T): number; +export interface Equatable { + isEqual(other: T): boolean; +} +/** Compare strings in UTF-8 encoded byte order */ +export declare function compareUtf8Strings(left: string, right: string): number; +export declare function isSurrogate(s: string): boolean; +export interface Iterable { + forEach: (cb: (v: V) => void) => void; +} +/** Helper to compare arrays using isEqual(). */ +export declare function arrayEquals(left: T[], right: T[], comparator: (l: T, r: T) => boolean): boolean; +/** + * Returns the immediate lexicographically-following string. This is useful to + * construct an inclusive range for indexeddb iterators. + */ +export declare function immediateSuccessor(s: string): string; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/node_api.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/node_api.d.ts new file mode 100644 index 0000000..2285e8e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/node_api.d.ts @@ -0,0 +1,58 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Creates a node-style callback that resolves or rejects a new Promise. The + * callback is passed to the given action which can then use the callback as + * a parameter to a node-style function. + * + * The intent is to directly bridge a node-style function (which takes a + * callback) into a Promise without manually converting between the node-style + * callback and the promise at each call. + * + * In effect it allows you to convert: + * + * @example + * new Promise((resolve: (value?: fs.Stats) => void, + * reject: (error?: any) => void) => { + * fs.stat(path, (error?: any, stat?: fs.Stats) => { + * if (error) { + * reject(error); + * } else { + * resolve(stat); + * } + * }); + * }); + * + * Into + * @example + * nodePromise((callback: NodeCallback) => { + * fs.stat(path, callback); + * }); + * + * @param action - a function that takes a node-style callback as an argument + * and then uses that callback to invoke some node-style API. + * @returns a new Promise which will be rejected if the callback is given the + * first Error parameter or will resolve to the value given otherwise. + */ +export declare function nodePromise(action: (callback: NodeCallback) => void): Promise; +/** + * A node-style callback which passes an Error as the first argument if there + * was an error, or passes null and a proper value + */ +export interface NodeCallback { + (error?: unknown, value?: R): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/obj.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/obj.d.ts new file mode 100644 index 0000000..90bf468 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/obj.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export interface Dict { + [stringKey: string]: V; +} +export declare function objectSize(obj: object): number; +export declare function forEach(obj: Dict | undefined, fn: (key: string, val: V) => void): void; +export declare function mapToArray(obj: Dict, fn: (element: V, key: string, obj: Dict) => R): R[]; +export declare function isEmpty(obj: Dict): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/obj_map.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/obj_map.d.ts new file mode 100644 index 0000000..f858bcf --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/obj_map.d.ts @@ -0,0 +1,48 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A map implementation that uses objects as keys. Objects must have an + * associated equals function and must be immutable. Entries in the map are + * stored together with the key being produced from the mapKeyFn. This map + * automatically handles collisions of keys. + */ +export declare class ObjectMap { + private mapKeyFn; + private equalsFn; + /** + * The inner map for a key/value pair. Due to the possibility of collisions we + * keep a list of entries that we do a linear search through to find an actual + * match. Note that collisions should be rare, so we still expect near + * constant time lookups in practice. + */ + private inner; + /** The number of entries stored in the map */ + private innerSize; + constructor(mapKeyFn: (key: KeyType) => string, equalsFn: (l: KeyType, r: KeyType) => boolean); + /** Get a value for this key, or undefined if it does not exist. */ + get(key: KeyType): ValueType | undefined; + has(key: KeyType): boolean; + /** Put this key and value in the map. */ + set(key: KeyType, value: ValueType): void; + /** + * Remove this key from the map. Returns a boolean if anything was deleted. + */ + delete(key: KeyType): boolean; + forEach(fn: (key: KeyType, val: ValueType) => void): void; + isEmpty(): boolean; + size(): number; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/promise.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/promise.d.ts new file mode 100644 index 0000000..f966068 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/promise.d.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export interface Resolver { + (value: R | Promise): void; +} +export interface Rejecter { + (reason?: Error): void; +} +export declare class Deferred { + promise: Promise; + resolve: Resolver; + reject: Rejecter; + constructor(); +} +/** + * Takes an array of values and a function from a value to a Promise. The function is run on each + * value sequentially, waiting for the previous promise to resolve before starting the next one. + * The returned promise resolves once the function has been run on all values. + */ +export declare function sequence(values: T[], fn: (value: T) => Promise): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/sorted_map.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/sorted_map.d.ts new file mode 100644 index 0000000..5060fa5 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/sorted_map.d.ts @@ -0,0 +1,100 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export type Comparator = (key1: K, key2: K) => number; +export interface Entry { + key: K; + value: V; +} +export declare class SortedMap { + comparator: Comparator; + root: LLRBNode | LLRBEmptyNode; + constructor(comparator: Comparator, root?: LLRBNode | LLRBEmptyNode); + insert(key: K, value: V): SortedMap; + remove(key: K): SortedMap; + get(key: K): V | null; + indexOf(key: K): number; + isEmpty(): boolean; + get size(): number; + minKey(): K | null; + maxKey(): K | null; + inorderTraversal(action: (k: K, v: V) => T): T; + forEach(fn: (k: K, v: V) => void): void; + toString(): string; + reverseTraversal(action: (k: K, v: V) => T): T; + getIterator(): SortedMapIterator; + getIteratorFrom(key: K): SortedMapIterator; + getReverseIterator(): SortedMapIterator; + getReverseIteratorFrom(key: K): SortedMapIterator; +} +export declare class SortedMapIterator { + private isReverse; + private nodeStack; + constructor(node: LLRBNode | LLRBEmptyNode, startKey: K | null, comparator: Comparator, isReverse: boolean); + getNext(): Entry; + hasNext(): boolean; + peek(): Entry | null; +} +export declare class LLRBNode { + key: K; + value: V; + readonly color: boolean; + readonly left: LLRBNode | LLRBEmptyNode; + readonly right: LLRBNode | LLRBEmptyNode; + readonly size: number; + static EMPTY: LLRBEmptyNode; + static RED: boolean; + static BLACK: boolean; + constructor(key: K, value: V, color?: boolean, left?: LLRBNode | LLRBEmptyNode, right?: LLRBNode | LLRBEmptyNode); + copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode | LLRBEmptyNode | null, right: LLRBNode | LLRBEmptyNode | null): LLRBNode; + isEmpty(): boolean; + inorderTraversal(action: (k: K, v: V) => T): T; + reverseTraversal(action: (k: K, v: V) => T): T; + private min; + minKey(): K | null; + maxKey(): K | null; + insert(key: K, value: V, comparator: Comparator): LLRBNode; + private removeMin; + remove(key: K, comparator: Comparator): LLRBNode | LLRBEmptyNode; + isRed(): boolean; + private fixUp; + private moveRedLeft; + private moveRedRight; + private rotateLeft; + private rotateRight; + private colorFlip; + checkMaxDepth(): boolean; + protected check(): number; +} +export declare class LLRBEmptyNode { + get key(): never; + get value(): never; + get color(): never; + get left(): never; + get right(): never; + size: number; + copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode | LLRBEmptyNode | null, right: LLRBNode | LLRBEmptyNode | null): LLRBEmptyNode; + insert(key: K, value: V, comparator: Comparator): LLRBNode; + remove(key: K, comparator: Comparator): LLRBEmptyNode; + isEmpty(): boolean; + inorderTraversal(action: (k: K, v: V) => boolean): boolean; + reverseTraversal(action: (k: K, v: V) => boolean): boolean; + minKey(): K | null; + maxKey(): K | null; + isRed(): boolean; + checkMaxDepth(): boolean; + protected check(): 0; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/sorted_set.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/sorted_set.d.ts new file mode 100644 index 0000000..ff6aedc --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/sorted_set.d.ts @@ -0,0 +1,80 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SortedMapIterator } from './sorted_map'; +/** + * SortedSet is an immutable (copy-on-write) collection that holds elements + * in order specified by the provided comparator. + * + * NOTE: if provided comparator returns 0 for two elements, we consider them to + * be equal! + */ +export declare class SortedSet { + private comparator; + private data; + constructor(comparator: (left: T, right: T) => number); + has(elem: T): boolean; + first(): T | null; + last(): T | null; + get size(): number; + indexOf(elem: T): number; + /** Iterates elements in order defined by "comparator" */ + forEach(cb: (elem: T) => void): void; + /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ + forEachInRange(range: [T, T], cb: (elem: T) => void): void; + /** + * Iterates over `elem`s such that: start <= elem until false is returned. + */ + forEachWhile(cb: (elem: T) => boolean, start?: T): void; + /** Finds the least element greater than or equal to `elem`. */ + firstAfterOrEqual(elem: T): T | null; + getIterator(): SortedSetIterator; + getIteratorFrom(key: T): SortedSetIterator; + /** Inserts or updates an element */ + add(elem: T): SortedSet; + /** Deletes an element */ + delete(elem: T): SortedSet; + isEmpty(): boolean; + unionWith(other: SortedSet): SortedSet; + isEqual(other: SortedSet): boolean; + toArray(): T[]; + toString(): string; + private copy; +} +export declare class SortedSetIterator { + private iter; + constructor(iter: SortedMapIterator); + getNext(): T; + hasNext(): boolean; +} +/** + * Compares two sorted sets for equality using their natural ordering. The + * method computes the intersection and invokes `onAdd` for every element that + * is in `after` but not `before`. `onRemove` is invoked for every element in + * `before` but missing from `after`. + * + * The method creates a copy of both `before` and `after` and runs in O(n log + * n), where n is the size of the two lists. + * + * @param before - The elements that exist in the original set. + * @param after - The elements to diff against the original set. + * @param comparator - The comparator for the elements in before and after. + * @param onAdd - A function to invoke for every element that is part of ` + * after` but not `before`. + * @param onRemove - A function to invoke for every element that is part of + * `before` but not `after`. + */ +export declare function diffSortedSets(before: SortedSet, after: SortedSet, comparator: (l: T, r: T) => number, onAdd: (entry: T) => void, onRemove: (entry: T) => void): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/testing_hooks.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/testing_hooks.d.ts new file mode 100644 index 0000000..90c6a65 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/testing_hooks.d.ts @@ -0,0 +1,52 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Unsubscribe } from '../api/reference_impl'; +import { ExistenceFilterMismatchInfo } from './testing_hooks_spi'; +/** + * Testing hooks for use by Firestore's integration test suite to reach into the + * SDK internals to validate logic and behavior that is not visible from the + * public API surface. + * + * @internal + */ +export declare class TestingHooks { + private constructor(); + /** + * Registers a callback to be notified when an existence filter mismatch + * occurs in the Watch listen stream. + * + * The relative order in which callbacks are notified is unspecified; do not + * rely on any particular ordering. If a given callback is registered multiple + * times then it will be notified multiple times, once per registration. + * + * @param callback the callback to invoke upon existence filter mismatch. + * + * @return a function that, when called, unregisters the given callback; only + * the first invocation of the returned function does anything; all subsequent + * invocations do nothing. + */ + static onExistenceFilterMismatch(callback: ExistenceFilterMismatchCallback): Unsubscribe; +} +/** + * The signature of callbacks registered with + * `TestingUtils.onExistenceFilterMismatch()`. + * + * The return value, if any, is ignored. + * + * @internal + */ +export type ExistenceFilterMismatchCallback = (info: ExistenceFilterMismatchInfo) => unknown; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/testing_hooks_spi.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/testing_hooks_spi.d.ts new file mode 100644 index 0000000..3d456e9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/testing_hooks_spi.d.ts @@ -0,0 +1,93 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The global, singleton instance of TestingHooksSpi. + * + * This variable will be `null` in all cases _except_ when running from + * integration tests that have registered callbacks to be notified of events + * that happen during the test execution. + */ +export declare let testingHooksSpi: TestingHooksSpi | null; +/** + * Sets the value of the `testingHooksSpi` object. + * @param instance the instance to set. + */ +export declare function setTestingHooksSpi(instance: TestingHooksSpi): void; +/** + * The "service provider interface" for the testing hooks. + * + * The implementation of this object will handle the callbacks made by the SDK + * to be handled by the integration tests. + * + * This "SPI" is separated from the implementation to avoid import cycles and + * to enable production builds to fully tree-shake away the testing hooks logic. + */ +export interface TestingHooksSpi { + /** + * Invokes all callbacks registered with + * `TestingHooks.onExistenceFilterMismatch()` with the given info. + */ + notifyOnExistenceFilterMismatch(info: ExistenceFilterMismatchInfo): void; +} +/** + * Information about an existence filter mismatch. + * @internal + */ +export interface ExistenceFilterMismatchInfo { + /** The number of documents that matched the query in the local cache. */ + localCacheCount: number; + /** + * The number of documents that matched the query on the server, as specified + * in the ExistenceFilter message's `count` field. + */ + existenceFilterCount: number; + /** + * The projectId used when checking documents for membership in the bloom + * filter. + */ + projectId: string; + /** + * The databaseId used when checking documents for membership in the bloom + * filter. + */ + databaseId: string; + /** + * Information about the bloom filter provided by Watch in the ExistenceFilter + * message's `unchangedNames` field. If this property is omitted or undefined + * then that means that Watch did _not_ provide a bloom filter. + */ + bloomFilter?: { + /** + * Whether a full requery was averted by using the bloom filter. If false, + * then something happened, such as a false positive, to prevent using the + * bloom filter to avoid a full requery. + */ + applied: boolean; + /** The number of hash functions used in the bloom filter. */ + hashCount: number; + /** The number of bytes in the bloom filter's bitmask. */ + bitmapLength: number; + /** The number of bits of padding in the last byte of the bloom filter. */ + padding: number; + /** + * Tests the given string for membership in the bloom filter created from + * the existence filter; will be undefined if creating the bloom filter + * failed. + */ + mightContain?: (value: string) => boolean; + }; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/types.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/types.d.ts new file mode 100644 index 0000000..a6842fe --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/src/util/types.d.ts @@ -0,0 +1,45 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Sentinel value that sorts before any Mutation Batch ID. */ +export declare const BATCHID_UNKNOWN = -1; +export interface StringMap { + [key: string]: string; +} +/** + * Returns whether a variable is either undefined or null. + */ +export declare function isNullOrUndefined(value: unknown): value is null | undefined; +/** Returns whether the value represents -0. */ +export declare function isNegativeZero(value: number): boolean; +/** + * Returns whether a value is an integer and in the safe integer range + * @param value - The value to test for being an integer and in the safe range + */ +export declare function isSafeInteger(value: unknown): boolean; +/** The subset of the browser's Window interface used by the SDK. */ +export interface WindowLike { + readonly localStorage: Storage; + readonly indexedDB: IDBFactory | null; + addEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: EventListener): void; +} +/** The subset of the browser's Document interface used by the SDK. */ +export interface DocumentLike { + readonly visibilityState: DocumentVisibilityState; + addEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: EventListener): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/aggregation.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/aggregation.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/aggregation.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/array_transforms.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/array_transforms.test.d.ts new file mode 100644 index 0000000..c53048a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/array_transforms.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/batch_writes.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/batch_writes.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/batch_writes.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/bundle.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/bundle.test.d.ts new file mode 100644 index 0000000..e2ec7a1 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/bundle.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare const encoder: TextEncoder; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/composite_index_query.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/composite_index_query.test.d.ts new file mode 100644 index 0000000..615869e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/composite_index_query.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/cursor.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/cursor.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/cursor.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/database.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/database.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/database.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/fields.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/fields.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/fields.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/get_options.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/get_options.test.d.ts new file mode 100644 index 0000000..c53048a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/get_options.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/index_configuration.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/index_configuration.test.d.ts new file mode 100644 index 0000000..daa6d5d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/index_configuration.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/numeric_transforms.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/numeric_transforms.test.d.ts new file mode 100644 index 0000000..c53048a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/numeric_transforms.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/persistent_cache_index_manager.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/persistent_cache_index_manager.test.d.ts new file mode 100644 index 0000000..615869e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/persistent_cache_index_manager.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/provider.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/provider.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/provider.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/query.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/query.test.d.ts new file mode 100644 index 0000000..777341d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/query.test.d.ts @@ -0,0 +1,18 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentChange, DocumentChangeType } from '../util/firebase_export'; +export declare function verifyDocumentChange(change: DocumentChange, id: string, oldIndex: number, newIndex: number, type: DocumentChangeType): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/server_timestamp.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/server_timestamp.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/server_timestamp.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/smoke.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/smoke.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/smoke.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/snapshot_listener_source.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/snapshot_listener_source.test.d.ts new file mode 100644 index 0000000..88c3c0e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/snapshot_listener_source.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/transactions.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/transactions.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/transactions.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/type.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/type.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/type.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/validation.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/validation.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api/validation.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api_internal/auth.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api_internal/auth.test.d.ts new file mode 100644 index 0000000..daa6d5d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api_internal/auth.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api_internal/database.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api_internal/database.test.d.ts new file mode 100644 index 0000000..1c93d90 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api_internal/database.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api_internal/idle_timeout.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api_internal/idle_timeout.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api_internal/idle_timeout.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api_internal/transaction.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api_internal/transaction.test.d.ts new file mode 100644 index 0000000..1c93d90 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/api_internal/transaction.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/bootstrap.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/bootstrap.d.ts new file mode 100644 index 0000000..1391c20 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/bootstrap.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import '../../src/index'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/browser/indexeddb.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/browser/indexeddb.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/browser/indexeddb.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/browser/webchannel.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/browser/webchannel.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/browser/webchannel.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/prime_backend.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/prime_backend.test.d.ts new file mode 100644 index 0000000..c53048a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/prime_backend.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/remote/remote.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/remote/remote.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/remote/remote.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/remote/stream.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/remote/stream.test.d.ts new file mode 100644 index 0000000..4f1864c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/remote/stream.test.d.ts @@ -0,0 +1,54 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { EmptyAuthCredentialsProvider } from '../../../src/api/credentials'; +import { SnapshotVersion } from '../../../src/core/snapshot_version'; +import { MutationResult } from '../../../src/model/mutation'; +import { PersistentListenStream, PersistentWriteStream, WatchStreamListener, WriteStreamListener } from '../../../src/remote/persistent_stream'; +import { DocumentWatchChange, ExistenceFilterChange, WatchTargetChange } from '../../../src/remote/watch_change'; +import { AsyncQueueImpl } from '../../../src/util/async_queue_impl'; +import { FirestoreError } from '../../../src/util/error'; +/** + * StreamEventType combines the events that can be observed by the + * WatchStreamListener and WriteStreamListener. + */ +type StreamEventType = 'handshakeComplete' | 'mutationResult' | 'watchChange' | 'open' | 'close' | 'connected'; +declare class StreamStatusListener implements WatchStreamListener, WriteStreamListener { + private pendingCallbacks; + private pendingPromises; + /** + * Returns a Promise that resolves when the next callback fires. Resolves the + * returned Promise immediately if there is already an unprocessed callback. + * + * This method asserts that the observed callback type matches + * `expectedCallback`. + */ + awaitCallback(expectedCallback: StreamEventType): Promise; + /** + * Verifies that we did not encounter any unexpected callbacks. + */ + verifyNoPendingCallbacks(): void; + onHandshakeComplete(): Promise; + onMutationResult(commitVersion: SnapshotVersion, results: MutationResult[]): Promise; + onWatchChange(watchChange: DocumentWatchChange | WatchTargetChange | ExistenceFilterChange, snapshot: SnapshotVersion): Promise; + onConnected(): Promise; + onOpen(): Promise; + onClose(err?: FirestoreError): Promise; + private resolvePending; +} +export declare function withTestWriteStream(fn: (writeStream: PersistentWriteStream, streamListener: StreamStatusListener, queue: AsyncQueueImpl) => Promise, credentialsProvider?: EmptyAuthCredentialsProvider): Promise; +export declare function withTestWatchStream(fn: (watchStream: PersistentListenStream, streamListener: StreamStatusListener) => Promise): Promise; +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/util/composite_index_test_helper.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/util/composite_index_test_helper.d.ts new file mode 100644 index 0000000..39316df --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/util/composite_index_test_helper.d.ts @@ -0,0 +1,41 @@ +import { CollectionReference, DocumentData, Firestore, Query, QueryConstraint, DocumentReference, QueryCompositeFilterConstraint, QueryNonFilterConstraint, DocumentSnapshot, UpdateData, QuerySnapshot } from './firebase_export'; +import { PERSISTENCE_MODE_UNSPECIFIED, PersistenceMode } from './helpers'; +/** + * This helper class is designed to facilitate integration testing of Firestore queries that + * require composite indexes within a controlled testing environment. + * + *

Key Features: + * + *

    + *
  • Runs tests against the dedicated test collection with predefined composite indexes. + *
  • Automatically associates a test ID with documents for data isolation. + *
  • Utilizes TTL policy for automatic test data cleanup. + *
  • Constructs Firestore queries with test ID filters. + *
+ */ +export declare class CompositeIndexTestHelper { + private readonly testId; + private readonly TEST_ID_FIELD; + private readonly TTL_FIELD; + constructor(); + withTestDocs(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, docs: { + [key: string]: DocumentData; + }, fn: (collection: CollectionReference, db: Firestore) => Promise): Promise; + withTestCollection(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, fn: (collection: CollectionReference, db: Firestore) => Promise): Promise; + private toHashedId; + private toHashedIds; + addTestSpecificFieldsToDoc(doc: DocumentData): DocumentData; + private removeTestSpecificFieldsFromDoc; + private prepareTestDocuments; + assertOnlineAndOfflineResultsMatch(collection: CollectionReference, query: Query, ...expectedDocs: string[]): Promise; + assertSnapshotResultIdsMatch(snapshot: QuerySnapshot, expectedIds: string[]): void; + query(query_: Query, ...queryConstraints: QueryConstraint[]): Query; + compositeQuery(query_: Query, compositeFilter: QueryCompositeFilterConstraint, ...queryConstraints: QueryNonFilterConstraint[]): Query; + getDocRef(coll: CollectionReference, docId: string): DocumentReference; + addDoc(reference: CollectionReference, data: object): Promise>; + setDoc(reference: DocumentReference, data: object): Promise; + updateDoc(reference: DocumentReference, data: UpdateData): Promise; + deleteDoc(reference: DocumentReference): Promise; + getDoc(docRef: DocumentReference): Promise>; + getDocs(query_: Query): Promise>; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/util/events_accumulator.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/util/events_accumulator.d.ts new file mode 100644 index 0000000..629d5a9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/util/events_accumulator.d.ts @@ -0,0 +1,39 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentSnapshot, QuerySnapshot } from './firebase_export'; +/** + * A helper object that can accumulate an arbitrary amount of events and resolve + * a promise when expected number has been emitted. + */ +export declare class EventsAccumulator { + private events; + private waitingFor; + private deferred; + private rejectAdditionalEvents; + storeEvent: (evt: T) => void; + awaitEvents(length: number): Promise; + awaitEvent(): Promise; + /** Waits for a latency compensated local snapshot. */ + awaitLocalEvent(): Promise; + /** Waits for multiple latency compensated local snapshot. */ + awaitLocalEvents(count: number): Promise; + /** Waits for a snapshot that has no pending writes */ + awaitRemoteEvent(): Promise; + assertNoAdditionalEvents(): Promise; + allowAdditionalEvents(): void; + private checkFulfilled; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/util/firebase_export.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/util/firebase_export.d.ts new file mode 100644 index 0000000..7d96efd --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/util/firebase_export.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseApp } from '@firebase/app'; +import { Firestore } from '../../../src'; +import { PrivateSettings } from '../../../src/lite-api/settings'; +export declare function newTestApp(projectId: string, appName?: string): FirebaseApp; +export declare function newTestFirestore(app: FirebaseApp, settings?: PrivateSettings, dbName?: string): Firestore; +export * from '../../../src'; +export { PrivateSettings }; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/util/helpers.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/util/helpers.d.ts new file mode 100644 index 0000000..731369e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/util/helpers.d.ts @@ -0,0 +1,138 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { CollectionReference, DocumentData, DocumentReference, Firestore, MemoryLocalCache, PersistentLocalCache, PrivateSettings, QuerySnapshot, SnapshotListenOptions, Query } from './firebase_export'; +export interface PersistenceMode { + readonly name: string; + readonly storage: 'memory' | 'indexeddb'; + readonly gc: 'eager' | 'lru'; + /** + * Creates and returns a new `PersistenceMode` object that is the nearest + * equivalent to this persistence mode but uses eager garbage collection. + */ + toEagerGc(): PersistenceMode; + /** + * Creates and returns a new `PersistenceMode` object that is the nearest + * equivalent to this persistence mode but uses LRU garbage collection. + */ + toLruGc(): PersistenceMode; + /** + * Creates and returns a new "local cache" object corresponding to this + * persistence type. + */ + asLocalCacheFirestoreSettings(): MemoryLocalCache | PersistentLocalCache; +} +export declare class MemoryEagerPersistenceMode implements PersistenceMode { + readonly name = "memory"; + readonly storage = "memory"; + readonly gc = "eager"; + toEagerGc(): MemoryEagerPersistenceMode; + toLruGc(): MemoryLruPersistenceMode; + asLocalCacheFirestoreSettings(): MemoryLocalCache; +} +export declare class MemoryLruPersistenceMode implements PersistenceMode { + readonly name = "memory_lru_gc"; + readonly storage = "memory"; + readonly gc = "lru"; + toEagerGc(): MemoryEagerPersistenceMode; + toLruGc(): MemoryLruPersistenceMode; + asLocalCacheFirestoreSettings(): MemoryLocalCache; +} +export declare class IndexedDbPersistenceMode implements PersistenceMode { + readonly name = "indexeddb"; + readonly storage = "indexeddb"; + readonly gc = "lru"; + toEagerGc(): MemoryEagerPersistenceMode; + toLruGc(): IndexedDbPersistenceMode; + asLocalCacheFirestoreSettings(): PersistentLocalCache; +} +export declare const PERSISTENCE_MODE_UNSPECIFIED: unique symbol; +export declare function isPersistenceAvailable(): boolean; +type ApiSuiteFunction = (message: string, testSuite: (persistence: PersistenceMode) => void) => void; +interface ApiDescribe { + (message: string, testSuite: (persistence: PersistenceMode) => void): void; + skip: ApiSuiteFunction; + only: ApiSuiteFunction; +} +export declare const apiDescribe: ApiDescribe; +/** Converts the documents in a QuerySnapshot to an array with the data of each document. */ +export declare function toDataArray(docSet: QuerySnapshot): DocumentData[]; +/** Converts the changes in a QuerySnapshot to an array with the data of each document. */ +export declare function toChangesArray(docSet: QuerySnapshot, options?: SnapshotListenOptions): DocumentData[]; +export declare function toDataMap(docSet: QuerySnapshot): { + [field: string]: DocumentData; +}; +/** Converts a DocumentSet to an array with the id of each document */ +export declare function toIds(docSet: QuerySnapshot): string[]; +export declare function withTestDb(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, fn: (db: Firestore) => Promise): Promise; +/** Runs provided fn with a db for an alternate project id. */ +export declare function withAlternateTestDb(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, fn: (db: Firestore) => Promise): Promise; +export declare function withTestDbs(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, numDbs: number, fn: (db: Firestore[]) => Promise): Promise; +export declare function withTestDbsSettings(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, projectId: string, settings: PrivateSettings, numDbs: number, fn: (db: Firestore[]) => Promise): Promise; +export declare function withNamedTestDbsOrSkipUnlessUsingEmulator(persistence: PersistenceMode, dbNames: string[], fn: (db: Firestore[]) => Promise): Promise; +export declare function withTestDoc(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, fn: (doc: DocumentReference, db: Firestore) => Promise): Promise; +export declare function withTestDocAndSettings(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, settings: PrivateSettings, fn: (doc: DocumentReference) => Promise): Promise; +export declare function withTestDocAndInitialData(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, initialData: DocumentData | null, fn: (doc: DocumentReference, db: Firestore) => Promise): Promise; +export declare class RetryError extends Error { + readonly name = "FirestoreIntegrationTestRetryError"; +} +export declare function withRetry(fn: (attemptNumber: number) => Promise): Promise; +export declare function withTestCollection(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, docs: { + [key: string]: DocumentData; +}, fn: (collection: CollectionReference, db: Firestore) => Promise): Promise; +export declare function withEmptyTestCollection(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, fn: (collection: CollectionReference, db: Firestore) => Promise): Promise; +export declare function withTestCollectionSettings(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, settings: PrivateSettings, docs: { + [key: string]: DocumentData; +}, fn: (collection: CollectionReference, db: Firestore) => Promise): Promise; +export declare function batchCommitDocsToCollection(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, settings: PrivateSettings, docs: { + [key: string]: DocumentData; +}, collectionId: string, fn: (collection: CollectionReference, db: Firestore) => Promise): Promise; +/** + * Creates a `docs` argument suitable for specifying to `withTestCollection()` + * that defines subsets of documents with different document data. + * + * This can be useful for pre-populating a collection with some documents that + * match a query and others that do _not_ match that query. + * + * Each key of the given `partitions` object will be considered a partition + * "name". The returned object will specify `documentCount` documents with the + * `documentData` whose document IDs are prefixed with the partition "name". + */ +export declare function partitionedTestDocs(partitions: { + [partitionName: string]: { + documentData: DocumentData; + documentCount: number; + }; +}): { + [key: string]: DocumentData; +}; +/** + * Checks that running the query while online (against the backend/emulator) results in the same + * documents as running the query while offline. If `expectedDocs` is provided, it also checks + * that both online and offline query result is equal to the expected documents. + * + * This function first performs a "get" for the entire COLLECTION from the server. + * It then performs the QUERY from CACHE which, results in `executeFullCollectionScan()` + * It then performs the QUERY from SERVER. + * It then performs the QUERY from CACHE again, which results in `performQueryUsingRemoteKeys()`. + * It then ensure that all the above QUERY results are the same. + * + * @param collection The collection on which the query is performed. + * @param query The query to check + * @param expectedDocs Ordered list of document keys that are expected to match the query + */ +export declare function checkOnlineAndOfflineResultsMatch(collection: Query, query: Query, ...expectedDocs: string[]): Promise; +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/util/internal_helpers.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/util/internal_helpers.d.ts new file mode 100644 index 0000000..cd23cb2 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/util/internal_helpers.d.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { CredentialChangeListener, CredentialsProvider, EmptyAuthCredentialsProvider } from '../../../src/api/credentials'; +import { User } from '../../../src/auth/user'; +import { DatabaseInfo } from '../../../src/core/database_info'; +import { Datastore } from '../../../src/remote/datastore'; +import { AsyncQueue } from '../../../src/util/async_queue'; +import { AsyncQueueImpl } from '../../../src/util/async_queue_impl'; +import { Firestore } from './firebase_export'; +import { PersistenceMode } from './helpers'; +export declare function asyncQueue(db: Firestore): AsyncQueueImpl; +export declare function getDefaultDatabaseInfo(): DatabaseInfo; +export declare function withTestDatastore(fn: (datastore: Datastore) => Promise, authCredentialsProvider?: CredentialsProvider, appCheckTokenProvider?: CredentialsProvider): Promise; +export declare class MockAuthCredentialsProvider extends EmptyAuthCredentialsProvider { + private listener; + private asyncQueue; + triggerUserChange(newUser: User): void; + start(asyncQueue: AsyncQueue, listener: CredentialChangeListener): void; +} +export declare function withMockCredentialProviderTestDb(persistence: PersistenceMode, fn: (db: Firestore, mockCredential: MockAuthCredentialsProvider) => Promise): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/util/settings.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/util/settings.d.ts new file mode 100644 index 0000000..850a5f2 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/util/settings.d.ts @@ -0,0 +1,24 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { PrivateSettings } from './firebase_export'; +export declare const TARGET_DB_ID: string | '(default)'; +export declare const USE_EMULATOR: boolean; +export declare const DEFAULT_SETTINGS: PrivateSettings; +export declare function getEmulatorPort(): number; +export declare const DEFAULT_PROJECT_ID: any; +export declare const ALT_PROJECT_ID = "test-db2"; +export declare const COMPOSITE_INDEX_TEST_COLLECTION = "composite-index-test-collection"; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/util/testing_hooks_util.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/util/testing_hooks_util.d.ts new file mode 100644 index 0000000..600f0fd --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/integration/util/testing_hooks_util.d.ts @@ -0,0 +1,44 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentReference } from './firebase_export'; +/** + * Captures all existence filter mismatches in the Watch 'Listen' stream that + * occur during the execution of the given code block. + * @param callback The callback to invoke; during the invocation of this + * callback all existence filter mismatches will be captured. + * @return the captured existence filter mismatches and the result of awaiting + * the given callback. + */ +export declare function captureExistenceFilterMismatches(callback: () => Promise): Promise<[ExistenceFilterMismatchInfo[], T]>; +/** + * Information about an existence filter mismatch, captured during an invocation + * of `captureExistenceFilterMismatches()`. + * + * See the documentation of `ExistenceFilterMismatchInfo` in + * `testing_hooks_spi.ts` for the meaning of these values. + */ +export interface ExistenceFilterMismatchInfo { + localCacheCount: number; + existenceFilterCount: number; + bloomFilter?: { + applied: boolean; + hashCount: number; + bitmapLength: number; + padding: number; + mightContain(documentRef: DocumentReference): boolean; + }; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/lite/bootstrap.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/lite/bootstrap.d.ts new file mode 100644 index 0000000..731d2d9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/lite/bootstrap.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/lite/helpers.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/lite/helpers.d.ts new file mode 100644 index 0000000..1033563 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/lite/helpers.d.ts @@ -0,0 +1,41 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Firestore } from '../../src/lite-api/database'; +import { DocumentData, CollectionReference, DocumentReference, SetOptions, PartialWithFieldValue } from '../../src/lite-api/reference'; +import { FirestoreSettings } from '../../src/lite-api/settings'; +import { QueryDocumentSnapshot } from '../../src/lite-api/snapshot'; +export declare function withTestDbSettings(projectId: string, settings: FirestoreSettings, fn: (db: Firestore) => void | Promise): Promise; +export declare function withTestDb(fn: (db: Firestore) => void | Promise): Promise; +export declare function withTestDoc(fn: (doc: DocumentReference) => void | Promise): Promise; +export declare function withTestDocAndInitialData(data: DocumentData, fn: (doc: DocumentReference) => void | Promise): Promise; +export declare function withTestCollectionAndInitialData(data: DocumentData[], fn: (collRef: CollectionReference) => void | Promise): Promise; +export declare function withTestCollection(fn: (collRef: CollectionReference) => void | Promise): Promise; +export declare class Post { + readonly title: string; + readonly author: string; + readonly id: number; + constructor(title: string, author: string, id?: number); + byline(): string; +} +export declare const postConverter: { + toFirestore(post: Post): DocumentData; + fromFirestore(snapshot: QueryDocumentSnapshot): Post; +}; +export declare const postConverterMerge: { + toFirestore(post: PartialWithFieldValue, options?: SetOptions): DocumentData; + fromFirestore(snapshot: QueryDocumentSnapshot): Post; +}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/lite/integration.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/lite/integration.test.d.ts new file mode 100644 index 0000000..731d2d9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/lite/integration.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/register.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/register.d.ts new file mode 100644 index 0000000..daa6d5d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/register.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/aggregate.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/aggregate.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/aggregate.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/bytes.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/bytes.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/bytes.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/database.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/database.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/database.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/document_change.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/document_change.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/document_change.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/field_path.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/field_path.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/field_path.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/field_value.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/field_value.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/field_value.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/geo_point.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/geo_point.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/geo_point.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/long_polling_options.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/long_polling_options.test.d.ts new file mode 100644 index 0000000..615869e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/long_polling_options.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/timestamp.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/timestamp.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/timestamp.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/vector_value.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/vector_value.test.d.ts new file mode 100644 index 0000000..1a6762b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/api/vector_value.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/bootstrap.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/bootstrap.d.ts new file mode 100644 index 0000000..6a6eae7 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/bootstrap.d.ts @@ -0,0 +1,24 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This will include all of the test files and compile them as needed + * + * Taken from karma-webpack source: + * https://github.com/webpack-contrib/karma-webpack#alternative-usage + */ +declare const testsContext: any; +declare const browserTests: any; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/core/event_manager.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/core/event_manager.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/core/event_manager.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/core/filter.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/core/filter.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/core/filter.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/core/listen_sequence.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/core/listen_sequence.test.d.ts new file mode 100644 index 0000000..c53048a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/core/listen_sequence.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/core/query.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/core/query.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/core/query.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/core/view.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/core/view.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/core/view.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/core/webchannel_wrapper.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/core/webchannel_wrapper.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/core/webchannel_wrapper.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/index/firestore_index_value_writer.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/index/firestore_index_value_writer.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/index/firestore_index_value_writer.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/index/ordered_code_writer.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/index/ordered_code_writer.test.d.ts new file mode 100644 index 0000000..23f261f --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/index/ordered_code_writer.test.d.ts @@ -0,0 +1 @@ +export declare function compare(left: Uint8Array, right: Uint8Array): number; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/lite-api/types.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/lite-api/types.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/lite-api/types.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/bundle_cache.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/bundle_cache.test.d.ts new file mode 100644 index 0000000..731d2d9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/bundle_cache.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/counting_query_engine.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/counting_query_engine.d.ts new file mode 100644 index 0000000..f2f4574 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/counting_query_engine.d.ts @@ -0,0 +1,60 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Query } from '../../../src/core/query'; +import { SnapshotVersion } from '../../../src/core/snapshot_version'; +import { IndexManager } from '../../../src/local/index_manager'; +import { LocalDocumentsView } from '../../../src/local/local_documents_view'; +import { PersistencePromise } from '../../../src/local/persistence_promise'; +import { PersistenceTransaction } from '../../../src/local/persistence_transaction'; +import { QueryEngine } from '../../../src/local/query_engine'; +import { DocumentKeySet, DocumentMap } from '../../../src/model/collections'; +import { MutationType } from '../../../src/model/mutation'; +/** + * A test-only query engine that forwards all API calls and exposes the number + * of documents and mutations read. + */ +export declare class CountingQueryEngine extends QueryEngine { + /** + * The number of overlays returned by the DocumentOverlayCache's + * `getOverlaysByCollection(Group)` API (since the last call to + * `resetCounts()`) + */ + overlaysReadByCollection: number; + /** + * The number of overlays returned by the DocumentOverlayCache's + * `getOverlay(s)` APIs (since the last call to `resetCounts()`) + */ + overlaysReadByKey: number; + overlayTypes: { + [k: string]: MutationType; + }; + /** + * The number of documents returned by the RemoteDocumentCache's + * `getAll()` API (since the last call to `resetCounts()`). + */ + documentsReadByCollection: number; + /** + * The number of documents returned by the RemoteDocumentCache's `getEntry()` + * and `getEntries()` APIs (since the last call to `resetCounts()`) + */ + documentsReadByKey: number; + resetCounts(): void; + getDocumentsMatchingQuery(transaction: PersistenceTransaction, query: Query, lastLimboFreeSnapshotVersion: SnapshotVersion, remoteKeys: DocumentKeySet): PersistencePromise; + initialize(localDocuments: LocalDocumentsView, indexManager: IndexManager): void; + private wrapRemoteDocumentCache; + private wrapOverlayCache; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/document_overlay_cache.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/document_overlay_cache.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/document_overlay_cache.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/encoded_resource_path.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/encoded_resource_path.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/encoded_resource_path.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/globals_cache.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/globals_cache.test.d.ts new file mode 100644 index 0000000..88c3c0e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/globals_cache.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/index_backfiller.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/index_backfiller.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/index_backfiller.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/index_manager.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/index_manager.test.d.ts new file mode 100644 index 0000000..1c93d90 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/index_manager.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/indexeddb_persistence.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/indexeddb_persistence.test.d.ts new file mode 100644 index 0000000..c53048a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/indexeddb_persistence.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/local_serializer.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/local_serializer.test.d.ts new file mode 100644 index 0000000..731d2d9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/local_serializer.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/local_store.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/local_store.test.d.ts new file mode 100644 index 0000000..2ec9c10 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/local_store.test.d.ts @@ -0,0 +1,24 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { LocalStore } from '../../../src/local/local_store'; +import { Persistence } from '../../../src/local/persistence'; +import { CountingQueryEngine } from './counting_query_engine'; +export interface LocalStoreComponents { + queryEngine: CountingQueryEngine; + persistence: Persistence; + localStore: LocalStore; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/local_store_indexeddb.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/local_store_indexeddb.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/local_store_indexeddb.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/lru_garbage_collector.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/lru_garbage_collector.test.d.ts new file mode 100644 index 0000000..c53048a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/lru_garbage_collector.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/mutation_queue.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/mutation_queue.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/mutation_queue.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/persistence_promise.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/persistence_promise.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/persistence_promise.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/persistence_test_helpers.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/persistence_test_helpers.d.ts new file mode 100644 index 0000000..bb4c627 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/persistence_test_helpers.d.ts @@ -0,0 +1,67 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../../../src/auth/user'; +import { DatabaseId } from '../../../src/core/database_info'; +import { SequenceNumberSyncer } from '../../../src/core/listen_sequence'; +import { BatchId, TargetId } from '../../../src/core/types'; +import { IndexedDbPersistence } from '../../../src/local/indexeddb_persistence'; +import { LocalSerializer } from '../../../src/local/local_serializer'; +import { LruParams } from '../../../src/local/lru_garbage_collector'; +import { MemoryPersistence } from '../../../src/local/memory_persistence'; +import { ClientId } from '../../../src/local/shared_client_state'; +import { JsonProtoSerializer } from '../../../src/remote/serializer'; +import { AsyncQueue } from '../../../src/util/async_queue'; +import { WindowLike } from '../../../src/util/types'; +export declare const MOCK_SEQUENCE_NUMBER_SYNCER: SequenceNumberSyncer; +/** The Database ID used by most tests that use a serializer. */ +export declare const TEST_PROJECT = "test-project"; +export declare const TEST_DATABASE_ID: DatabaseId; +export declare const TEST_PERSISTENCE_KEY = "[PersistenceTestHelpers]"; +export declare const TEST_APP_ID = "test-app-id"; +/** The persistence prefix used for testing in IndexedBD and LocalStorage. */ +export declare const TEST_PERSISTENCE_PREFIX: string; +/** + * The database name used by tests that access IndexedDb. To be used in + * conjunction with `TEST_DATABASE_INFO` and + * `TEST_DATABASE_ID`. + */ +export declare const INDEXEDDB_TEST_DATABASE_NAME: string; +export declare const JSON_SERIALIZER: JsonProtoSerializer; +/** + * IndexedDb serializer that uses `TEST_DATABASE_ID` as its database + * id. + */ +export declare const TEST_SERIALIZER: LocalSerializer; +/** + * Creates and starts an IndexedDbPersistence instance for testing, destroying + * any previous contents if they existed. + */ +export declare function testIndexedDbPersistence(options?: { + dontPurgeData?: boolean; + synchronizeTabs?: boolean; + queue?: AsyncQueue; + schemaVersion?: number; +}, lruParams?: LruParams): Promise; +/** Creates and starts a MemoryPersistence instance for testing. */ +export declare function testMemoryEagerPersistence(): Promise; +export declare function testMemoryLruPersistence(params?: LruParams): Promise; +/** Clears the persistence in tests */ +export declare function clearTestPersistence(): Promise; +/** + * Populates Web Storage with instance data from a preexisting client. + */ +export declare function populateWebStorage(user: User, window: WindowLike, existingClientId: ClientId, existingMutationBatchIds: BatchId[], existingQueryTargetIds: TargetId[]): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/persistence_transaction.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/persistence_transaction.test.d.ts new file mode 100644 index 0000000..1c93d90 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/persistence_transaction.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/query_engine.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/query_engine.test.d.ts new file mode 100644 index 0000000..1c93d90 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/query_engine.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/reference_set.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/reference_set.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/reference_set.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/remote_document_cache.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/remote_document_cache.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/remote_document_cache.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/remote_document_change_buffer.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/remote_document_change_buffer.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/remote_document_change_buffer.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/simple_db.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/simple_db.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/simple_db.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/target_cache.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/target_cache.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/target_cache.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_bundle_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_bundle_cache.d.ts new file mode 100644 index 0000000..faff4b4 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_bundle_cache.d.ts @@ -0,0 +1,32 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BundleMetadata, NamedQuery } from '../../../src/core/bundle'; +import { Persistence } from '../../../src/local/persistence'; +import { NamedQuery as ProtoNamedQuery, BundleMetadata as ProtoBundleMetadata } from '../../../src/protos/firestore_bundle_proto'; +/** + * A wrapper around a BundleCache that automatically creates a + * transaction around every operation to reduce test boilerplate. + */ +export declare class TestBundleCache { + private readonly persistence; + private readonly cache; + constructor(persistence: Persistence); + getBundleMetadata(bundleId: string): Promise; + saveBundleMetadata(metadata: ProtoBundleMetadata): Promise; + getNamedQuery(name: string): Promise; + setNamedQuery(query: ProtoNamedQuery): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_document_overlay_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_document_overlay_cache.d.ts new file mode 100644 index 0000000..c0d0c66 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_document_overlay_cache.d.ts @@ -0,0 +1,39 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentOverlayCache } from '../../../src/local/document_overlay_cache'; +import { Persistence } from '../../../src/local/persistence'; +import { DocumentKeySet, MutationMap, OverlayMap } from '../../../src/model/collections'; +import { DocumentKey } from '../../../src/model/document_key'; +import { Mutation } from '../../../src/model/mutation'; +import { Overlay } from '../../../src/model/overlay'; +import { ResourcePath } from '../../../src/model/path'; +/** + * A wrapper around a DocumentOverlayCache that automatically creates a + * transaction around every operation to reduce test boilerplate. + */ +export declare class TestDocumentOverlayCache { + private persistence; + private cache; + constructor(persistence: Persistence, cache: DocumentOverlayCache); + saveOverlays(largestBatch: number, data: MutationMap): Promise; + getOverlay(key: DocumentKey): Promise; + getOverlays(keys: DocumentKey[]): Promise; + getOverlayMutation(docKey: string): Promise; + getOverlaysForCollection(path: ResourcePath, sinceBatchId: number): Promise; + getOverlaysForCollectionGroup(collectionGroup: string, sinceBatchId: number, count: number): Promise; + removeOverlaysForBatchId(documentKeys: DocumentKeySet, batchId: number): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_globals_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_globals_cache.d.ts new file mode 100644 index 0000000..7388b22 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_globals_cache.d.ts @@ -0,0 +1,29 @@ +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Persistence } from '../../../src/local/persistence'; +import { ByteString } from '../../../src/util/byte_string'; +/** + * A wrapper around a GlobalsCache that automatically creates a + * transaction around every operation to reduce test boilerplate. + */ +export declare class TestGlobalsCache { + private readonly persistence; + private readonly cache; + constructor(persistence: Persistence); + getSessionToken(): Promise; + setSessionToken(sessionToken: ByteString): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_index_manager.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_index_manager.d.ts new file mode 100644 index 0000000..9cd64e1 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_index_manager.d.ts @@ -0,0 +1,44 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Target } from '../../../src/core/target'; +import { IndexManager, IndexType } from '../../../src/local/index_manager'; +import { Persistence } from '../../../src/local/persistence'; +import { DocumentMap } from '../../../src/model/collections'; +import { DocumentKey } from '../../../src/model/document_key'; +import { FieldIndex, IndexOffset } from '../../../src/model/field_index'; +import { ResourcePath } from '../../../src/model/path'; +/** + * A wrapper around IndexManager that automatically creates a + * transaction around every operation to reduce test boilerplate. + */ +export declare class TestIndexManager { + persistence: Persistence; + indexManager: IndexManager; + constructor(persistence: Persistence, indexManager: IndexManager); + addToCollectionParentIndex(collectionPath: ResourcePath): Promise; + getCollectionParents(collectionId: string): Promise; + addFieldIndex(index: FieldIndex): Promise; + deleteFieldIndex(index: FieldIndex): Promise; + createTargetIndexes(target: Target): Promise; + deleteAllFieldIndexes(): Promise; + getFieldIndexes(collectionGroup?: string): Promise; + getIndexType(target: Target): Promise; + getDocumentsMatchingTarget(target: Target): Promise; + getNextCollectionGroupToUpdate(): Promise; + updateCollectionGroup(collectionGroup: string, offset: IndexOffset): Promise; + updateIndexEntries(documents: DocumentMap): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_mutation_queue.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_mutation_queue.d.ts new file mode 100644 index 0000000..56dae50 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_mutation_queue.d.ts @@ -0,0 +1,43 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Query } from '../../../src/core/query'; +import { BatchId } from '../../../src/core/types'; +import { MutationQueue } from '../../../src/local/mutation_queue'; +import { Persistence } from '../../../src/local/persistence'; +import { DocumentKeySet } from '../../../src/model/collections'; +import { DocumentKey } from '../../../src/model/document_key'; +import { Mutation } from '../../../src/model/mutation'; +import { MutationBatch } from '../../../src/model/mutation_batch'; +/** + * A wrapper around a MutationQueue that automatically creates a + * transaction around every operation to reduce test boilerplate. + */ +export declare class TestMutationQueue { + persistence: Persistence; + queue: MutationQueue; + constructor(persistence: Persistence, queue: MutationQueue); + checkEmpty(): Promise; + countBatches(): Promise; + addMutationBatch(mutations: Mutation[]): Promise; + lookupMutationBatch(batchId: BatchId): Promise; + getNextMutationBatchAfterBatchId(batchId: BatchId): Promise; + getAllMutationBatches(): Promise; + getAllMutationBatchesAffectingDocumentKey(documentKey: DocumentKey): Promise; + getAllMutationBatchesAffectingDocumentKeys(documentKeys: DocumentKeySet): Promise; + getAllMutationBatchesAffectingQuery(query: Query): Promise; + removeMutationBatch(batch: MutationBatch): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_remote_document_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_remote_document_cache.d.ts new file mode 100644 index 0000000..67fda41 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_remote_document_cache.d.ts @@ -0,0 +1,54 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Query } from '../../../src/core/query'; +import { SnapshotVersion } from '../../../src/core/snapshot_version'; +import { IndexManager } from '../../../src/local/index_manager'; +import { Persistence } from '../../../src/local/persistence'; +import { RemoteDocumentChangeBuffer } from '../../../src/local/remote_document_change_buffer'; +import { DocumentKeySet, MutableDocumentMap, OverlayMap } from '../../../src/model/collections'; +import { MutableDocument } from '../../../src/model/document'; +import { DocumentKey } from '../../../src/model/document_key'; +import { IndexOffset } from '../../../src/model/field_index'; +/** + * A wrapper around a RemoteDocumentCache that automatically creates a + * transaction around every operation to reduce test boilerplate. + */ +export declare class TestRemoteDocumentCache { + private readonly persistence; + private readonly cache; + constructor(persistence: Persistence); + setIndexManager(indexManager: IndexManager): void; + /** + * Reads all of the documents first so we can safely add them and keep the size calculation in + * sync. + */ + addEntries(documents: MutableDocument[]): Promise; + /** + * Adds a single document using the document's version as its read time. + * Reads the document first to track the document size internally. + */ + addEntry(document: MutableDocument): Promise; + removeEntry(documentKey: DocumentKey, version?: SnapshotVersion): Promise; + getEntry(documentKey: DocumentKey): Promise; + getEntries(documentKeys: DocumentKeySet): Promise; + getDocumentsMatchingQuery(query: Query, offset: IndexOffset, mutatedDocs: OverlayMap): Promise; + getAllFromCollectionGroup(collectionGroup: string, offset: IndexOffset, limit: number): Promise; + getSize(): Promise; + newChangeBuffer(options?: { + trackRemovals: boolean; + }): RemoteDocumentChangeBuffer; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_remote_document_change_buffer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_remote_document_change_buffer.d.ts new file mode 100644 index 0000000..9abb942 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_remote_document_change_buffer.d.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../../../src/core/snapshot_version'; +import { Persistence } from '../../../src/local/persistence'; +import { RemoteDocumentChangeBuffer } from '../../../src/local/remote_document_change_buffer'; +import { MutableDocument } from '../../../src/model/document'; +import { DocumentKey } from '../../../src/model/document_key'; +/** + * A wrapper around a RemoteDocumentChangeBuffer that automatically creates a + * transaction around operations to reduce test boilerplate. + */ +export declare class TestRemoteDocumentChangeBuffer { + persistence: Persistence; + buffer: RemoteDocumentChangeBuffer; + constructor(persistence: Persistence, buffer: RemoteDocumentChangeBuffer); + addEntry(document: MutableDocument, readTime: SnapshotVersion): void; + removeEntry(key: DocumentKey, readTime: SnapshotVersion): void; + getEntry(documentKey: DocumentKey): Promise; + apply(): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_target_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_target_cache.d.ts new file mode 100644 index 0000000..590e9ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/test_target_cache.d.ts @@ -0,0 +1,46 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../../../src/core/snapshot_version'; +import { Target } from '../../../src/core/target'; +import { ListenSequenceNumber, TargetId } from '../../../src/core/types'; +import { Persistence } from '../../../src/local/persistence'; +import { TargetCache } from '../../../src/local/target_cache'; +import { TargetData } from '../../../src/local/target_data'; +import { DocumentKey } from '../../../src/model/document_key'; +/** + * A wrapper around a TargetCache that automatically creates a + * transaction around every operation to reduce test boilerplate. + */ +export declare class TestTargetCache { + persistence: Persistence; + cache: TargetCache; + constructor(persistence: Persistence, cache: TargetCache); + addTargetData(targetData: TargetData): Promise; + updateTargetData(targetData: TargetData): Promise; + getTargetCount(): Promise; + removeTargetData(targetData: TargetData): Promise; + getTargetData(target: Target): Promise; + getLastRemoteSnapshotVersion(): Promise; + getHighestSequenceNumber(): Promise; + allocateTargetId(): Promise; + addMatchingKeys(keys: DocumentKey[], targetId: TargetId): Promise; + removeMatchingKeys(keys: DocumentKey[], targetId: TargetId): Promise; + getMatchingKeysForTargetId(targetId: TargetId): Promise; + removeMatchingKeysForTargetId(targetId: TargetId): Promise; + containsKey(key: DocumentKey): Promise; + setTargetsMetadata(highestListenSequenceNumber: ListenSequenceNumber, lastRemoteSnapshotVersion?: SnapshotVersion): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/web_storage_shared_client_state.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/web_storage_shared_client_state.test.d.ts new file mode 100644 index 0000000..342959e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/local/web_storage_shared_client_state.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * withOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/document.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/document.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/document.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/document_set.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/document_set.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/document_set.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/field_index.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/field_index.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/field_index.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/mutation.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/mutation.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/mutation.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/object_value.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/object_value.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/object_value.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/object_value_builder.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/object_value_builder.test.d.ts new file mode 100644 index 0000000..731d2d9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/object_value_builder.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/path.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/path.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/path.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/target.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/target.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/target.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/target_index_matcher.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/target_index_matcher.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/target_index_matcher.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/values.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/values.test.d.ts new file mode 100644 index 0000000..731d2d9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/model/values.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/bloom_filter.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/bloom_filter.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/bloom_filter.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/bloom_filter_golden_test_data/index.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/bloom_filter_golden_test_data/index.d.ts new file mode 100644 index 0000000..fda7b1b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/bloom_filter_golden_test_data/index.d.ts @@ -0,0 +1,40 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { default as count1Rate1TestData } from './Validation_BloomFilterTest_MD5_1_1_bloom_filter_proto.json'; +export { default as count1Rate1TestResult } from './Validation_BloomFilterTest_MD5_1_1_membership_test_result.json'; +export { default as count1Rate01TestData } from './Validation_BloomFilterTest_MD5_1_01_bloom_filter_proto.json'; +export { default as count1Rate01TestResult } from './Validation_BloomFilterTest_MD5_1_01_membership_test_result.json'; +export { default as count1Rate0001TestData } from './Validation_BloomFilterTest_MD5_1_0001_bloom_filter_proto.json'; +export { default as count1Rate0001TestResult } from './Validation_BloomFilterTest_MD5_1_0001_membership_test_result.json'; +export { default as count500Rate1TestData } from './Validation_BloomFilterTest_MD5_500_1_bloom_filter_proto.json'; +export { default as count500Rate1TestResult } from './Validation_BloomFilterTest_MD5_500_1_membership_test_result.json'; +export { default as count500Rate01TestData } from './Validation_BloomFilterTest_MD5_500_01_bloom_filter_proto.json'; +export { default as count500Rate01TestResult } from './Validation_BloomFilterTest_MD5_500_01_membership_test_result.json'; +export { default as count500Rate0001TestData } from './Validation_BloomFilterTest_MD5_500_0001_bloom_filter_proto.json'; +export { default as count500Rate0001TestResult } from './Validation_BloomFilterTest_MD5_500_0001_membership_test_result.json'; +export { default as count5000Rate1TestData } from './Validation_BloomFilterTest_MD5_5000_1_bloom_filter_proto.json'; +export { default as count5000Rate1TestResult } from './Validation_BloomFilterTest_MD5_5000_1_membership_test_result.json'; +export { default as count5000Rate01TestData } from './Validation_BloomFilterTest_MD5_5000_01_bloom_filter_proto.json'; +export { default as count5000Rate01TestResult } from './Validation_BloomFilterTest_MD5_5000_01_membership_test_result.json'; +export { default as count5000Rate0001TestData } from './Validation_BloomFilterTest_MD5_5000_0001_bloom_filter_proto.json'; +export { default as count5000Rate0001TestResult } from './Validation_BloomFilterTest_MD5_5000_0001_membership_test_result.json'; +export { default as count50000Rate1TestData } from './Validation_BloomFilterTest_MD5_50000_1_bloom_filter_proto.json'; +export { default as count50000Rate1TestResult } from './Validation_BloomFilterTest_MD5_50000_1_membership_test_result.json'; +export { default as count50000Rate01TestData } from './Validation_BloomFilterTest_MD5_50000_01_bloom_filter_proto.json'; +export { default as count50000Rate01TestResult } from './Validation_BloomFilterTest_MD5_50000_01_membership_test_result.json'; +export { default as count50000Rate0001TestData } from './Validation_BloomFilterTest_MD5_50000_0001_bloom_filter_proto.json'; +export { default as count50000Rate0001TestResult } from './Validation_BloomFilterTest_MD5_50000_0001_membership_test_result.json'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/datastore.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/datastore.test.d.ts new file mode 100644 index 0000000..daa6d5d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/datastore.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/fetch_connection.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/fetch_connection.test.d.ts new file mode 100644 index 0000000..1a6762b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/fetch_connection.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/remote_event.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/remote_event.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/remote_event.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/rest_connection.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/rest_connection.test.d.ts new file mode 100644 index 0000000..a6fa156 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/rest_connection.test.d.ts @@ -0,0 +1,28 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Token } from '../../../src/api/credentials'; +import { Stream } from '../../../src/remote/connection'; +import { RestConnection } from '../../../src/remote/rest_connection'; +import { StringMap } from '../../../src/util/types'; +export declare class TestRestConnection extends RestConnection { + lastUrl: string; + lastHeaders: StringMap; + lastRequestBody: unknown; + nextResponse: Promise; + openStream(rpcName: string, authToken: Token | null, appCheckToken: Token | null): Stream; + protected performRPCRequest(rpcName: string, url: string, headers: StringMap, body: Req): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/serializer.browser.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/serializer.browser.test.d.ts new file mode 100644 index 0000000..731d2d9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/serializer.browser.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/serializer.helper.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/serializer.helper.d.ts new file mode 100644 index 0000000..238e66b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/serializer.helper.d.ts @@ -0,0 +1,25 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as api from '../../../src/protos/firestore_proto_api'; +/** + * Runs the serializer test with an optional ProtobufJS verification step + * (only provided in Node). + * + * These tests are initialized in 'serializer.browser.test.ts' and + * 'serializer.node.test.ts'. + */ +export declare function serializerTest(protobufJsVerifier?: (jsonValue: api.Value) => void): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/serializer.node.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/serializer.node.test.d.ts new file mode 100644 index 0000000..94e3acc --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/remote/serializer.node.test.d.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as api from '../../../src/protos/firestore_proto_api'; +/** + * Verifies full round-trip of JSON protos through ProtobufJs. + */ +export declare function verifyProtobufJsRoundTrip(jsonValue: api.Value): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/bundle_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/bundle_spec.test.d.ts new file mode 100644 index 0000000..18aa444 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/bundle_spec.test.d.ts @@ -0,0 +1,36 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Query } from '../../../src/core/query'; +import { DocumentKey } from '../../../src/model/document_key'; +import { JsonObject } from '../../../src/model/object_value'; +import { LimitType } from '../../../src/protos/firestore_bundle_proto'; +import { TestSnapshotVersion } from '../../util/helpers'; +interface TestBundleDocument { + key: DocumentKey; + readTime: TestSnapshotVersion; + createTime?: TestSnapshotVersion; + updateTime?: TestSnapshotVersion; + content?: JsonObject; +} +interface TestBundledQuery { + name: string; + readTime: TestSnapshotVersion; + query: Query; + limitType?: LimitType; +} +export declare function bundleWithDocumentAndQuery(testDoc: TestBundleDocument, testQuery?: TestBundledQuery): string; +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/collection_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/collection_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/collection_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/describe_spec.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/describe_spec.d.ts new file mode 100644 index 0000000..8804b64 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/describe_spec.d.ts @@ -0,0 +1,44 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SpecBuilder } from './spec_builder'; +export declare const MULTI_CLIENT_TAG = "multi-client"; +/** + * If you call this function before your describeSpec, then the spec test will + * be written using the given function instead of running as a normal test. + */ +export declare function setSpecJSONHandler(writer: (json: string) => void): void; +/** + * Like it(), but for spec tests. + * @param name - A name to give the test. + * @param tags - Tags to apply to the test (e.g. 'exclusive' to only run + * individual tests) + * @param builder - A function that returns a spec. + * If writeToJSONFile has been called, the spec will be stored in + * `specsInThisTest`. Otherwise, it will be run, just as it() would run it. + */ +export declare function specTest(name: string, tags: string[], builder: () => SpecBuilder): void; +export declare function specTest(name: string, tags: string[], comment: string, builder: () => SpecBuilder): void; +/** + * Like describe, but for spec tests. + * @param name - A name to give the test. + * @param tags - Tags to apply to all tests in the spec (e.g. 'exclusive' to + * only run individual tests) + * @param builder - A function that calls specTest for each test case. + * If writeToJSONFile has been called, the specs will be stored in + * that file. Otherwise, they will be run, just as describe would run. + */ +export declare function describeSpec(name: string, tags: string[], builder: () => void): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/existence_filter_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/existence_filter_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/existence_filter_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/garbage_collection_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/garbage_collection_spec.test.d.ts new file mode 100644 index 0000000..615869e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/garbage_collection_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/index_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/index_spec.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/index_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/limbo_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/limbo_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/limbo_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/limit_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/limit_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/limit_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/listen_source_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/listen_source_spec.test.d.ts new file mode 100644 index 0000000..88c3c0e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/listen_source_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/listen_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/listen_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/listen_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/offline_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/offline_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/offline_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/orderby_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/orderby_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/orderby_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/perf_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/perf_spec.test.d.ts new file mode 100644 index 0000000..c53048a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/perf_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/persistence_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/persistence_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/persistence_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/query_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/query_spec.test.d.ts new file mode 100644 index 0000000..1c93d90 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/query_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/recovery_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/recovery_spec.test.d.ts new file mode 100644 index 0000000..731d2d9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/recovery_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/remote_store_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/remote_store_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/remote_store_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/resume_token_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/resume_token_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/resume_token_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/spec_builder.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/spec_builder.d.ts new file mode 100644 index 0000000..00705ca --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/spec_builder.d.ts @@ -0,0 +1,287 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { IndexConfiguration } from '../../../src/api/index_configuration'; +import { Query } from '../../../src/core/query'; +import { Target } from '../../../src/core/target'; +import { TargetIdGenerator } from '../../../src/core/target_id_generator'; +import { TargetId } from '../../../src/core/types'; +import { TargetPurpose } from '../../../src/local/target_data'; +import { Document } from '../../../src/model/document'; +import { DocumentKey } from '../../../src/model/document_key'; +import { FieldIndex } from '../../../src/model/field_index'; +import { JsonObject } from '../../../src/model/object_value'; +import { BloomFilter as ProtoBloomFilter } from '../../../src/protos/firestore_proto_api'; +import { TimerId } from '../../../src/util/async_queue'; +import { Code } from '../../../src/util/error'; +import { ObjectMap } from '../../../src/util/obj_map'; +import { TestSnapshotVersion } from '../../util/helpers'; +import { RpcError } from './spec_rpc_error'; +import { PersistenceAction, SpecConfig, SpecQuery, SpecStep } from './spec_test_runner'; +export interface LimboMap { + [key: string]: TargetId; +} +export interface ActiveTargetSpec { + queries: SpecQuery[]; + targetPurpose?: TargetPurpose; + resumeToken?: string; + readTime?: TestSnapshotVersion; + expectedCount?: number; +} +export interface ActiveTargetMap { + [targetId: string]: ActiveTargetSpec; +} +export interface ResumeSpec { + resumeToken?: string; + readTime?: TestSnapshotVersion; + expectedCount?: number; +} +/** + * Tracks the expected memory state of a client (e.g. the expected active watch + * targets based on userListens(), userUnlistens(), and watchRemoves() + * as well as the expectActiveTargets() and expectLimboDocs() expectations). + * + * Automatically keeping track of the active targets makes writing tests + * much simpler and the tests much easier to follow. + * + * Whenever the map changes, the expected state is automatically encoded in + * the tests. + */ +export declare class ClientMemoryState { + activeTargets: ActiveTargetMap; + queryMapping: ObjectMap; + limboMapping: LimboMap; + limboIdGenerator: TargetIdGenerator; + injectFailures: boolean; + constructor(); + /** Reset all internal memory state (as done during a client restart). */ + reset(): void; + /** + * Reset the internal limbo mapping (as done during a primary lease failover). + */ + resetLimboMapping(): void; +} +/** + * Provides a high-level language to construct spec tests that can be exported + * to the spec JSON format or be run as a spec test directly. + * + * Exported JSON tests can be used in other clients without the need to + * duplicate tests in every client. + */ +export declare class SpecBuilder { + protected config: SpecConfig; + protected currentStep: SpecStep | null; + private steps; + private queryIdGenerator; + private readonly currentClientState; + protected get clientState(): ClientMemoryState; + private get limboIdGenerator(); + private get queryMapping(); + private get limboMapping(); + private get activeTargets(); + private get injectFailures(); + private set injectFailures(value); + /** + * Exports the spec steps as a JSON object that be used in the spec runner. + */ + toJSON(): { + config: SpecConfig; + steps: SpecStep[]; + }; + /** + * Run the spec as a test. If persistence is available it will run it with and + * without persistence enabled. + */ + runAsTest(name: string, tags: string[], usePersistence: boolean): Promise; + ensureManualLruGC(): this; + withMaxConcurrentLimboResolutions(value?: number): this; + private addUserListenStep; + userListens(query: Query, resume?: ResumeSpec): this; + /** Listen to query using the same options as executing a getDoc or getDocs */ + userListensForGet(query: Query, resume?: ResumeSpec): this; + userListensToCache(query: Query, resume?: ResumeSpec): this; + /** + * Registers a previously active target with the test expectations after a + * stream disconnect. + */ + restoreListen(query: Query, resumeToken: string, expectedCount?: number): this; + userUnlistens(query: Query, shouldRemoveWatchTarget?: boolean): this; + userUnlistensToCache(query: Query): this; + userSets(key: string, value: JsonObject): this; + userPatches(key: string, value: JsonObject): this; + userDeletes(key: string): this; + userAddsSnapshotsInSyncListener(): this; + userRemovesSnapshotsInSyncListener(): this; + loadBundle(bundleContent: string): this; + setIndexConfiguration(jsonOrConfiguration: string | IndexConfiguration): this; + becomeHidden(): this; + becomeVisible(): this; + runTimer(timerId: TimerId): this; + changeUser(uid: string | null): this; + disableNetwork(): this; + enableNetwork(): this; + clearPersistence(): this; + restart(): this; + shutdown(): this; + /** + * Fails the specified database transaction until `recoverDatabase()` is + * called. + */ + failDatabaseTransactions(...actions: PersistenceAction[]): this; + /** Stops failing database operations. */ + recoverDatabase(): this; + expectIsShutdown(): this; + /** Expects indexes to exist (in any order) */ + expectIndexes(indexes: FieldIndex[]): this; + /** Overrides the currently expected set of active targets. */ + expectActiveTargets(...targets: Array<{ + query: Query; + targetPurpose?: TargetPurpose; + resumeToken?: string; + readTime?: TestSnapshotVersion; + expectedCount?: number; + }>): this; + /** + * Expects a document to be in limbo. A targetId is assigned if it's not in + * limbo yet. + */ + expectLimboDocs(...keys: DocumentKey[]): this; + /** + * Expects a document to be in limbo, enqueued for limbo resolution, and + * therefore *without* an active targetId. + */ + expectEnqueuedLimboDocs(...keys: DocumentKey[]): this; + /** + * Special helper for limbo documents that acks with either a document or + * with no document for NoDocument. This is translated into normal watch + * messages. + */ + ackLimbo(version: TestSnapshotVersion, doc: Document): this; + /** + * Special helper for limbo documents that acks an unlisten for a limbo doc + * with either a document or with no document for NoDocument. This is + * translated into normal watch messages. + */ + watchRemovesLimboTarget(doc: Document): this; + /** + * Acks a write with a version and optional additional options. + * + * expectUserCallback defaults to true if omitted. + */ + writeAcks(doc: string, version: TestSnapshotVersion, options?: { + expectUserCallback?: boolean; + keepInQueue?: boolean; + }): this; + /** + * Fails a write with an error and optional additional options. + * + * expectUserCallback defaults to true if omitted. + */ + failWrite(doc: string, error: RpcError, options?: { + expectUserCallback?: boolean; + keepInQueue?: boolean; + }): this; + watchAcks(query: Query): this; + watchCurrents(query: Query, resumeToken: string): this; + watchRemoves(query: Query, cause?: RpcError): this; + watchSends(targets: { + affects?: Query[]; + removed?: Query[]; + }, ...docs: Document[]): this; + watchRemovesDoc(key: DocumentKey, ...targets: Query[]): this; + watchDeletesDoc(key: DocumentKey, version: TestSnapshotVersion, ...targets: Query[]): this; + watchFilters(queries: Query[], docs?: DocumentKey[], bloomFilter?: ProtoBloomFilter): this; + watchResets(...queries: Query[]): this; + watchSnapshots(version: TestSnapshotVersion, targets?: Query[], resumeToken?: string): this; + watchAcksFull(query: Query, version: TestSnapshotVersion, ...docs: Document[]): this; + watchStreamCloses(error: Code, opts?: { + runBackoffTimer: boolean; + }): this; + waitForPendingWrites(): this; + expectUserCallbacks(docs: { + acknowledged?: string[]; + rejected?: string[]; + }): this; + expectEvents(query: Query, events: { + fromCache?: boolean; + hasPendingWrites?: boolean; + added?: Document[]; + modified?: Document[]; + removed?: Document[]; + metadata?: Document[]; + errorCode?: Code; + }): this; + private registerQuery; + /** Registers a query that is active in another tab. */ + expectListen(query: Query, resume?: ResumeSpec): this; + /** Registers a query that is listening to cache and active in another tab. */ + expectListenToCache(query: Query, resume?: ResumeSpec): this; + removeQuery(query: Query, shouldRemoveWatchTarget?: boolean): this; + /** Removes a query that is no longer active in any tab. */ + expectUnlisten(query: Query): this; + /** Removes a query that is listening to cache and no longer active in any tab. */ + expectUnlistenToCache(query: Query): this; + /** + * Verifies the total number of requests sent to the write backend since test + * initialization. + */ + expectWriteStreamRequestCount(num: number): this; + /** + * Verifies the total number of requests sent to the watch backend since test + * initialization. + */ + expectWatchStreamRequestCount(num: number): this; + expectNumOutstandingWrites(num: number): this; + expectNumActiveClients(num: number): this; + expectPrimaryState(isPrimary: boolean): this; + expectSnapshotsInSyncEvent(count?: number): this; + expectWaitForPendingWritesEvent(count?: number): this; + triggerLruGC(cacheThreshold: number): this; + removeExpectedTargetMapping(query: Query): this; + private static queryToSpec; + private static docToSpec; + private static keyToSpec; + protected nextStep(): void; + /** + * Add the specified `Query` under give active targe id. If it is already + * added, this is a no-op. + */ + private addQueryToActiveTargets; + private removeQueryFromActiveTargets; + private assertStep; + private getTargetId; +} +/** + * SpecBuilder that supports serialized interactions between different clients. + * + * Use `client(clientIndex)` to switch between clients. + */ +export declare class MultiClientSpecBuilder extends SpecBuilder { + private activeClientIndex; + private clientStates; + protected get clientState(): ClientMemoryState; + client(clientIndex: number): MultiClientSpecBuilder; + /** + * Take the primary lease, even if another client has already obtained the + * lease. + */ + stealPrimaryLease(): this; + protected nextStep(): void; +} +/** Starts a new single-client SpecTest. */ +export declare function spec(): SpecBuilder; +/** Starts a new multi-client SpecTest. */ +export declare function client(num: number): MultiClientSpecBuilder; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/spec_rpc_error.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/spec_rpc_error.d.ts new file mode 100644 index 0000000..a104309 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/spec_rpc_error.d.ts @@ -0,0 +1,24 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Code } from '../../../src/util/error'; +/** + * An error encountered making RPCs. + */ +export declare class RpcError extends Error { + code: number; + constructor(code: Code | number, message: string); +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/spec_test_components.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/spec_test_components.d.ts new file mode 100644 index 0000000..0152128 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/spec_test_components.d.ts @@ -0,0 +1,156 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Token } from '../../../src/api/credentials'; +import { ComponentConfiguration, MemoryOfflineComponentProvider, OnlineComponentProvider, MultiTabOfflineComponentProvider } from '../../../src/core/component_provider'; +import { Observer } from '../../../src/core/event_manager'; +import { Query } from '../../../src/core/query'; +import { ViewSnapshot } from '../../../src/core/view_snapshot'; +import { IndexedDbPersistence } from '../../../src/local/indexeddb_persistence'; +import { LocalStore } from '../../../src/local/local_store'; +import { MemoryPersistence } from '../../../src/local/memory_persistence'; +import { Scheduler, Persistence } from '../../../src/local/persistence'; +import { PersistencePromise } from '../../../src/local/persistence_promise'; +import { PersistenceTransaction, PersistenceTransactionMode } from '../../../src/local/persistence_transaction'; +import { SharedClientState } from '../../../src/local/shared_client_state'; +import { Mutation } from '../../../src/model/mutation'; +import * as api from '../../../src/protos/firestore_proto_api'; +import { ApiClientObjectMap } from '../../../src/protos/firestore_proto_api'; +import { Connection, Stream } from '../../../src/remote/connection'; +import { Datastore } from '../../../src/remote/datastore'; +import { StreamBridge } from '../../../src/remote/stream_bridge'; +import { AsyncQueue } from '../../../src/util/async_queue'; +import { FirestoreError } from '../../../src/util/error'; +import { Deferred } from '../../../src/util/promise'; +import { WindowLike } from '../../../src/util/types'; +import { FakeDocument } from '../../util/test_platform'; +import { PersistenceAction } from './spec_test_runner'; +/** + * A test-only MemoryPersistence implementation that is able to inject + * transaction failures. + */ +export declare class MockMemoryPersistence extends MemoryPersistence { + injectFailures: PersistenceAction[]; + runTransaction(action: string, mode: PersistenceTransactionMode, transactionOperation: (transaction: PersistenceTransaction) => PersistencePromise): Promise; +} +/** + * A test-only IndexedDbPersistence implementation that is able to inject + * transaction failures. + */ +export declare class MockIndexedDbPersistence extends IndexedDbPersistence { + injectFailures: PersistenceAction[]; + runTransaction(action: string, mode: PersistenceTransactionMode, transactionOperation: (transaction: PersistenceTransaction) => PersistencePromise): Promise; +} +export declare class MockOnlineComponentProvider extends OnlineComponentProvider { + private readonly connection; + constructor(connection: MockConnection); + createDatastore(cfg: ComponentConfiguration): Datastore; +} +export declare class MockMultiTabOfflineComponentProvider extends MultiTabOfflineComponentProvider { + private readonly window; + private readonly document; + persistence: MockIndexedDbPersistence; + constructor(window: WindowLike, document: FakeDocument, onlineComponentProvider: OnlineComponentProvider); + createGarbageCollectionScheduler(cfg: ComponentConfiguration, localStore: LocalStore): Scheduler | null; + createIndexBackfillerScheduler(cfg: ComponentConfiguration, localStore: LocalStore): Scheduler | null; + createSharedClientState(cfg: ComponentConfiguration): SharedClientState; + createPersistence(cfg: ComponentConfiguration): MockIndexedDbPersistence; +} +export declare class MockMemoryOfflineComponentProvider extends MemoryOfflineComponentProvider { + private readonly eagerGCEnabled; + persistence: MockMemoryPersistence; + connection: MockConnection; + constructor(eagerGCEnabled: boolean); + createGarbageCollectionScheduler(cfg: ComponentConfiguration): Scheduler | null; + createPersistence(cfg: ComponentConfiguration): Persistence; +} +export declare class MockConnection implements Connection { + private queue; + watchStream: StreamBridge | null; + writeStream: StreamBridge | null; + /** + * Used to make sure a write was actually sent out on the network before the + * test runner continues. + */ + writeSendBarriers: Array>; + /** + * The set of mutations sent out before there was a corresponding + * writeSendBarrier. + */ + earlyWrites: api.WriteRequest[]; + /** The total number of requests sent to the watch stream. */ + watchStreamRequestCount: number; + /** The total number of requests sent to the write stream. */ + writeStreamRequestCount: number; + nextWriteStreamToken: number; + constructor(queue: AsyncQueue); + terminate(): void; + shouldResourcePathBeIncludedInRequest: boolean; + /** + * Tracks the currently active watch targets as detected by the mock watch // + * stream, as a mapping from target ID to query Target. // + */ + activeTargets: { + [targetId: number]: { + target: api.Target; + labels?: ApiClientObjectMap; + }; + }; + /** A Deferred that is resolved once watch opens. */ + watchOpen: Deferred; + /** Whether the Watch stream is open. */ + isWatchOpen: boolean; + invokeRPC(rpcName: string, request: Req): never; + invokeStreamingRPC(rpcName: string, request: Req): never; + waitForWriteRequest(): Promise; + waitForWatchOpen(): Promise; + ackWrite(commitTime?: api.Timestamp, mutationResults?: api.WriteResult[]): void; + failWrite(err: FirestoreError): void; + private resetAndCloseWriteStream; + failWatchStream(err?: FirestoreError): void; + private resetAndCloseWatchStream; + openStream(rpcName: string, token: Token | null): Stream; +} +/** + * An Observer that forwards events to the provided callback. + */ +export declare class EventAggregator implements Observer { + private query; + private pushEvent; + constructor(query: Query, pushEvent: (e: QueryEvent) => void); + next(view: ViewSnapshot): void; + error(error: Error): void; +} +/** + * FIFO queue that tracks all outstanding mutations for a single test run. + * As these mutations are shared among the set of active clients, any client can + * add or retrieve mutations. + */ +export declare class SharedWriteTracker { + private writes; + push(write: Mutation[]): void; + peek(): Mutation[]; + shift(): Mutation[]; +} +/** + * Interface used for object that contain exactly one of either a view snapshot + * or an error for the given query. + */ +export interface QueryEvent { + query: Query; + view?: ViewSnapshot; + error?: FirestoreError; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/spec_test_runner.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/spec_test_runner.d.ts new file mode 100644 index 0000000..50d1714 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/spec_test_runner.d.ts @@ -0,0 +1,323 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { IndexConfiguration } from '../../../src/api/index_configuration'; +import { ListenOptions } from '../../../src/core/event_manager'; +import { Query } from '../../../src/core/query'; +import { TargetId } from '../../../src/core/types'; +import { FieldIndex } from '../../../src/model/field_index'; +import { JsonObject } from '../../../src/model/object_value'; +import * as api from '../../../src/protos/firestore_proto_api'; +import { TestSnapshotVersion } from '../../util/helpers'; +import { ActiveTargetMap } from './spec_builder'; +interface DocumentOptions { + hasLocalMutations?: boolean; + hasCommittedMutations?: boolean; +} +export declare function parseQuery(querySpec: string | SpecQuery): Query; +/** + * Runs a spec test case. + * + * The spec consists of an array of individual steps to run in sequence. + */ +export declare function runSpec(name: string, tags: string[], usePersistence: boolean, config: SpecConfig, steps: SpecStep[]): Promise; +/** Specifies initial configuration information for the test. */ +export interface SpecConfig { + /** A boolean to enable / disable eager GC for memory persistence. */ + useEagerGCForMemory: boolean; + /** The number of active clients for this test run. */ + numClients: number; + /** + * The maximum number of concurrently-active listens for limbo resolutions. + * This value must be strictly greater than zero, or undefined to use the + * default value. + */ + maxConcurrentLimboResolutions?: number; +} +/** + * The cumulative list of actions run against Persistence. This is used by the + * Spec tests to fail specific types of actions. + */ +export type PersistenceAction = 'Get next mutation batch' | 'read document' | 'Allocate target' | 'Release target' | 'Execute query' | 'Handle user change' | 'Locally write mutations' | 'Acknowledge batch' | 'Reject batch' | 'Get highest unacknowledged batch id' | 'Get last stream token' | 'Set last stream token' | 'Get last remote snapshot version' | 'Set last remote snapshot version' | 'Apply remote event' | 'notifyLocalViewChanges' | 'Remote document keys' | 'Collect garbage' | 'maybeGarbageCollectMultiClientState' | 'Lookup mutation documents' | 'Get target data' | 'Get new document changes' | 'Synchronize last document change read time' | 'updateClientMetadataAndTryBecomePrimary' | 'getHighestListenSequenceNumber'; +/** + * Union type for each step. The step consists of exactly one `field` + * set and optionally expected events in the `expect` field. + */ +export interface SpecStep { + /** The index of the local client for multi-client spec tests. */ + clientIndex?: number; + /** Listen to a new query (must be unique) */ + userListen?: SpecUserListen; + /** Unlisten from a query (must be listened to) */ + userUnlisten?: SpecUserUnlisten; + /** Perform a user initiated set */ + userSet?: SpecUserSet; + /** Perform a user initiated patch */ + userPatch?: SpecUserPatch; + /** Perform a user initiated delete */ + userDelete?: SpecUserDelete; + /** Listens to a SnapshotsInSync event. */ + addSnapshotsInSyncListener?: true; + /** Unlistens from a SnapshotsInSync event. */ + removeSnapshotsInSyncListener?: true; + /** Loads a bundle from a string. */ + loadBundle?: string; + /** Ack for a query in the watch stream */ + watchAck?: SpecWatchAck; + /** Marks the query results as current */ + watchCurrent?: SpecWatchCurrent; + /** Reset the results of a query */ + watchReset?: SpecWatchReset; + /** Ack for remove or rejection of a query in the watch stream */ + watchRemove?: SpecWatchRemove; + /** Document update in the watch stream */ + watchEntity?: SpecWatchEntity; + /** Existence filter in the watch stream */ + watchFilter?: SpecWatchFilter; + /** Snapshot ("NO_CHANGE") event in the watch stream. */ + watchSnapshot?: SpecWatchSnapshot; + /** A step that the watch stream restarts. */ + watchStreamClose?: SpecWatchStreamClose; + /** Ack the last write */ + writeAck?: SpecWriteAck; + /** Fail a write */ + failWrite?: SpecWriteFailure; + /** Add a new `waitForPendingWrites` listener. */ + waitForPendingWrites?: true; + /** Fails the listed database actions. */ + failDatabase?: false | PersistenceAction[]; + /** + * Set Index Configuration + */ + setIndexConfiguration?: string | IndexConfiguration; + /** + * Run a queued timer task (without waiting for the delay to expire). See + * TimerId enum definition for possible values). + */ + runTimer?: string; + /** + * Process all events currently enqueued in the AsyncQueue. + */ + drainQueue?: true; + /** Enable or disable RemoteStore's network connection. */ + enableNetwork?: boolean; + /** Clears the persistent storage in IndexedDB. */ + clearPersistence?: true; + /** Changes the metadata state of a client instance. */ + applyClientState?: SpecClientState; + /** Change to a new active user (specified by uid or null for anonymous). */ + changeUser?: string | null; + /** Trigger a GC event with given cache threshold in bytes. */ + triggerLruGC?: number; + /** + * Restarts the SyncEngine from scratch, except re-uses persistence and auth + * components. This allows you to queue writes, get documents into cache, + * etc. and then simulate an app restart. + */ + restart?: true; + /** Shut down the client and close it network connection. */ + shutdown?: true; + /** + * Optional list of expected events. + * If not provided, the test will fail if the step causes events to be raised. + */ + expectedSnapshotEvents?: SnapshotEvent[]; + /** + * Optional dictionary of expected states. + */ + expectedState?: StateExpectation; + /** + * Optional expected number of onSnapshotsInSync callbacks to be called. + * If not provided, the test will fail if the step causes events to be raised. + */ + expectedSnapshotsInSyncEvents?: number; + /** + * Optional expected number of waitForPendingWrite callbacks to be called. + * If not provided, the test will fail if the step causes events to be raised. + */ + expectedWaitForPendingWritesEvents?: number; +} +export interface SpecUserListen { + targetId: TargetId; + query: string | SpecQuery; + options?: ListenOptions; +} +/** [, ] */ +export type SpecUserUnlisten = [TargetId, string | SpecQuery]; +/** [, ] */ +export type SpecUserSet = [string, JsonObject]; +/** [, ] */ +export type SpecUserPatch = [string, JsonObject]; +/** key */ +export type SpecUserDelete = string; +/** [, ...] */ +export type SpecWatchAck = TargetId[]; +/** [[, ...], ] */ +export type SpecWatchCurrent = [TargetId[], string]; +/** [, ...] */ +export type SpecWatchReset = TargetId[]; +export interface SpecError { + code: number; + message: string; +} +export interface SpecWatchRemove { + targetIds: TargetId[]; + cause?: SpecError; +} +export interface SpecWatchSnapshot { + version: TestSnapshotVersion; + targetIds: TargetId[]; + resumeToken?: string; +} +export interface SpecWatchStreamClose { + error: SpecError; + runBackoffTimer: boolean; +} +export interface SpecWriteAck { + /** The version the backend uses to ack the write. */ + version: TestSnapshotVersion; + /** + * Whether we should keep the write in our internal queue. This should only + * be set to 'true' if the client ignores the write (e.g. a secondary client + * which ignores write acknowledgments). + * + * Defaults to false. + */ + keepInQueue?: boolean; +} +export interface SpecWriteFailure { + /** The error the backend uses to fail the write. */ + error: SpecError; + /** + * Whether we should keep the write in our internal queue. This should be set + * to 'true' for transient errors or if the client ignores the failure + * (e.g. a secondary client which ignores write rejections). + * + * Defaults to false. + */ + keepInQueue?: boolean; +} +export interface SpecWatchEntity { + key?: string; + /** [, , ] */ + doc?: SpecDocument; + /** [, , ][] */ + docs?: SpecDocument[]; + /** [, ...] */ + targets?: TargetId[]; + /** [, ...] */ + removedTargets?: TargetId[]; +} +export interface SpecClientState { + /** The visibility state of the browser tab running the client. */ + visibility?: DocumentVisibilityState; + /** Whether this tab should try to forcefully become primary. */ + primary?: true; +} +/** + * The filter is based of a list of keys to match in the existence filter + */ +export interface SpecWatchFilter { + targetIds: TargetId[]; + keys: string[]; + bloomFilter?: api.BloomFilter; +} +export type SpecLimitType = 'LimitToFirst' | 'LimitToLast'; +/** + * [field, op, value] + * Op must be the `name` of an `Operator`. + */ +export type SpecQueryFilter = [string, string, unknown]; +/** + * [field, direction] + * Direction can be 'asc' or 'desc'. + */ +export type SpecQueryOrderBy = [string, string]; +/** + * A representation of a query. + */ +export interface SpecQuery { + path: string; + collectionGroup?: string; + limit?: number; + limitType?: SpecLimitType; + filters?: SpecQueryFilter[]; + orderBys?: SpecQueryOrderBy[]; +} +/** + * [, , , (optional), ...] + * Represents a document. is null for deleted documents. + * Doc options are: + * 'local': document has local modifications + */ +export interface SpecDocument { + key: string; + version: TestSnapshotVersion; + createTime: TestSnapshotVersion; + value: JsonObject | null; + options?: DocumentOptions; +} +export interface SnapshotEvent { + query: SpecQuery; + errorCode?: number; + fromCache?: boolean; + hasPendingWrites?: boolean; + added?: SpecDocument[]; + removed?: SpecDocument[]; + modified?: SpecDocument[]; + metadata?: SpecDocument[]; +} +export interface StateExpectation { + /** Number of outstanding writes in the datastore queue. */ + numOutstandingWrites?: number; + /** Number of clients currently marked active. Used in multi-client tests. */ + numActiveClients?: number; + /** Number of requests sent to the write stream. */ + writeStreamRequestCount?: number; + /** Number of requests sent to the watch stream. */ + watchStreamRequestCount?: number; + /** + * Current documents in limbo that have an active target. + * Verified in each step until overwritten. + */ + activeLimboDocs?: string[]; + /** + * Current documents in limbo that are enqueued and therefore do not have an + * active target. + * Verified in each step until overwritten. + */ + enqueuedLimboDocs?: string[]; + /** + * Whether the instance holds the primary lease. Used in multi-client tests. + */ + isPrimary?: boolean; + /** Whether the client is shutdown. */ + isShutdown?: boolean; + /** + * Current expected active targets. Verified in each step until overwritten. + */ + activeTargets?: ActiveTargetMap; + /** + * Expected set of callbacks for previously written docs. + */ + userCallbacks?: { + acknowledgedDocs: string[]; + rejectedDocs: string[]; + }; + /** Indexes */ + indexes?: FieldIndex[]; +} +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/write_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/write_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/specs/write_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/array.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/array.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/array.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/assert.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/assert.test.d.ts new file mode 100644 index 0000000..1a6762b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/assert.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/async_queue.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/async_queue.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/async_queue.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/base64.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/base64.test.d.ts new file mode 100644 index 0000000..731d2d9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/base64.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/bundle.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/bundle.test.d.ts new file mode 100644 index 0000000..56e142c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/bundle.test.d.ts @@ -0,0 +1,8 @@ +/** + * Create a `ReadableStream` from a string. + * + * @param content - Bundle in string. + * @param bytesPerRead - How many bytes to read from the underlying buffer from + * each read through the stream. + */ +export declare function byteStreamReaderFromString(content: string, bytesPerRead: number): ReadableStreamDefaultReader; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/bundle_data.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/bundle_data.d.ts new file mode 100644 index 0000000..de7a107 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/bundle_data.d.ts @@ -0,0 +1,50 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseId } from '../../../src/core/database_info'; +import { Query } from '../../../src/core/query'; +import { DocumentKey } from '../../../src/model/document_key'; +import { BundleElement } from '../../../src/protos/firestore_bundle_proto'; +import * as api from '../../../src/protos/firestore_proto_api'; +import { Value } from '../../../src/protos/firestore_proto_api'; +export declare const encoder: TextEncoder; +export declare class TestBundleBuilder { + private databaseId; + readonly elements: BundleElement[]; + private serializer; + constructor(databaseId: DatabaseId); + addDocumentMetadata(docKey: DocumentKey, readTime: api.Timestamp, exists: boolean): TestBundleBuilder; + addDocument(docKey: DocumentKey, createTime: api.Timestamp, updateTime: api.Timestamp, fields: api.ApiClientObjectMap): TestBundleBuilder; + addNamedQuery(name: string, readTime: api.Timestamp, query: Query): TestBundleBuilder; + getMetadataElement(id: string, createTime: api.Timestamp, version?: number): BundleElement; + build(id: string, createTime: api.Timestamp, version?: number): string; +} +export declare const meta: BundleElement; +export declare const metaString: string; +export declare const doc1Meta: BundleElement; +export declare const doc1MetaString: string; +export declare const doc1: BundleElement; +export declare const doc1String: string; +export declare const doc2Meta: BundleElement; +export declare const doc2MetaString: string; +export declare const doc2: BundleElement; +export declare const doc2String: string; +export declare const noDocMeta: BundleElement; +export declare const noDocMetaString: string; +export declare const limitQuery: BundleElement; +export declare const limitQueryString: string; +export declare const limitToLastQuery: BundleElement; +export declare const limitToLastQueryString: string; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/logic_utils.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/logic_utils.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/logic_utils.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/misc.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/misc.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/misc.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/node_api.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/node_api.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/node_api.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/obj_map.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/obj_map.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/obj_map.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/sorted_map.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/sorted_map.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/sorted_map.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/sorted_set.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/sorted_set.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/unit/util/sorted_set.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/util/api_helpers.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/util/api_helpers.d.ts new file mode 100644 index 0000000..a4a9b0c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/util/api_helpers.d.ts @@ -0,0 +1,49 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentReference, Firestore, Query, CollectionReference, QuerySnapshot, DocumentSnapshot } from '../../src'; +import { DocumentKeySet } from '../../src/model/collections'; +import { JsonObject } from '../../src/model/object_value'; +/** + * A mock Firestore. Will not work for integration test. + */ +export declare const FIRESTORE: Firestore; +export declare function firestore(): Firestore; +export declare function newTestFirestore(projectId?: string): Firestore; +export declare function collectionReference(path: string): CollectionReference; +export declare function documentReference(path: string): DocumentReference; +export declare function documentSnapshot(path: string, data: JsonObject | null, fromCache: boolean, hasPendingWrites?: boolean): DocumentSnapshot; +export declare function query(path: string): Query; +/** + * A convenience method for creating a particular query snapshot for tests. + * + * @param path - To be used in constructing the query. + * @param oldDocs - Provides the prior set of documents in the QuerySnapshot. + * Each entry maps to a document, with the key being the document id, and the + * value being the document contents. + * @param docsToAdd - Specifies data to be added into the query snapshot as of + * now. Each entry maps to a document, with the key being the document id, and + * the value being the document contents. + * @param mutatedKeys - The list of document with pending writes. + * @param fromCache - Whether the query snapshot is cache result. + * @param syncStateChanged - Whether the sync state has changed. + * @returns A query snapshot that consists of both sets of documents. + */ +export declare function querySnapshot(path: string, oldDocs: { + [key: string]: JsonObject; +}, docsToAdd: { + [key: string]: JsonObject; +}, mutatedKeys: DocumentKeySet, fromCache: boolean, syncStateChanged: boolean, hasCachedResults?: boolean): QuerySnapshot; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/util/equality_matcher.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/util/equality_matcher.d.ts new file mode 100644 index 0000000..d019ad2 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/util/equality_matcher.d.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Duck-typed interface for objects that have an isEqual() method. + * + * Note: This is copied from src/util/misc.ts to avoid importing private types. + */ +export interface Equatable { + isEqual(other: T): boolean; +} +/** + * Custom equals override for types that have a free-standing equals functions + * (such as `queryEquals()`). + */ +export interface CustomMatcher { + equalsFn: (left: T, right: T) => boolean; + forType: Function; +} +export declare function addEqualityMatcher(...customMatchers: Array>): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/util/helpers.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/util/helpers.d.ts new file mode 100644 index 0000000..c8acefd --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/util/helpers.d.ts @@ -0,0 +1,206 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Bytes, DocumentReference } from '../../src'; +import { Bound } from '../../src/core/bound'; +import { BundledDocuments } from '../../src/core/bundle'; +import { DatabaseId } from '../../src/core/database_info'; +import { FieldFilter, CompositeFilter, Filter } from '../../src/core/filter'; +import { OrderBy } from '../../src/core/order_by'; +import { Query } from '../../src/core/query'; +import { SnapshotVersion } from '../../src/core/snapshot_version'; +import { TargetId } from '../../src/core/types'; +import { LimboDocumentChange, View, ViewChange } from '../../src/core/view'; +import { UserDataReader } from '../../src/lite-api/user_data_reader'; +import { LocalViewChanges } from '../../src/local/local_view_changes'; +import { TargetData, TargetPurpose } from '../../src/local/target_data'; +import { DocumentKeySet, DocumentMap } from '../../src/model/collections'; +import { Document, MutableDocument } from '../../src/model/document'; +import { DocumentComparator } from '../../src/model/document_comparator'; +import { DocumentKey } from '../../src/model/document_key'; +import { DocumentSet } from '../../src/model/document_set'; +import { FieldIndex, IndexKind, IndexOffset } from '../../src/model/field_index'; +import { FieldMask } from '../../src/model/field_mask'; +import { DeleteMutation, MutationResult, PatchMutation, Precondition, SetMutation } from '../../src/model/mutation'; +import { JsonObject, ObjectValue } from '../../src/model/object_value'; +import { FieldPath, ResourcePath } from '../../src/model/path'; +import { NamedQuery as ProtoNamedQuery, BundleMetadata as ProtoBundleMetadata, LimitType as ProtoLimitType } from '../../src/protos/firestore_bundle_proto'; +import * as api from '../../src/protos/firestore_proto_api'; +import { RemoteEvent, TargetChange } from '../../src/remote/remote_event'; +import { ByteString } from '../../src/util/byte_string'; +import { Code } from '../../src/util/error'; +import { Dict } from '../../src/util/obj'; +import { SortedMap } from '../../src/util/sorted_map'; +import { SortedSet } from '../../src/util/sorted_set'; +export type TestSnapshotVersion = number; +export declare function testUserDataReader(useProto3Json?: boolean): UserDataReader; +export declare function version(v: TestSnapshotVersion): SnapshotVersion; +export declare function ref(key: string, offset?: number): DocumentReference; +export declare function doc(keyStr: string, ver: TestSnapshotVersion, jsonOrObjectValue: JsonObject | ObjectValue, createTime?: TestSnapshotVersion): MutableDocument; +export declare function deletedDoc(keyStrOrDocumentKey: string | DocumentKey, ver: TestSnapshotVersion): MutableDocument; +export declare function unknownDoc(keyStr: string, ver: TestSnapshotVersion): MutableDocument; +export declare function removedDoc(keyStr: string): MutableDocument; +export declare function invalidDoc(keyStr: string): MutableDocument; +export declare function wrap(value: unknown): api.Value; +export declare function wrapObject(obj: JsonObject): ObjectValue; +export declare function dbId(project: string, database?: string): DatabaseId; +export declare function key(path: string): DocumentKey; +export declare function keys(...documents: Array): DocumentKeySet; +export declare function path(path: string, offset?: number): ResourcePath; +export declare function field(path: string): FieldPath; +export declare function fieldIndex(collectionGroup: string, options?: { + id?: number; + fields?: Array<[field: string, kind: IndexKind]>; + offset?: IndexOffset; + sequenceNumber?: number; +}): FieldIndex; +export declare function mask(...paths: string[]): FieldMask; +export declare function blob(...bytes: number[]): Bytes; +export declare function filter(path: string, op: string, value: unknown): FieldFilter; +export declare function andFilter(...filters: Filter[]): CompositeFilter; +export declare function orFilter(...filters: Filter[]): CompositeFilter; +export declare function setMutation(keyStr: string, json: JsonObject): SetMutation; +export declare function patchMutation(keyStr: string, json: JsonObject, precondition?: Precondition): PatchMutation; +export declare function mergeMutation(keyStr: string, json: JsonObject, updateMask: FieldPath[]): PatchMutation; +export declare function deleteMutation(keyStr: string): DeleteMutation; +export declare function mutationResult(testVersion: TestSnapshotVersion): MutationResult; +export declare function bound(values: unknown[], inclusive: boolean): Bound; +export declare function query(resourcePath: string, ...constraints: Array): Query; +export declare function targetData(targetId: TargetId, queryPurpose: TargetPurpose, path: string): TargetData; +export declare function noChangeEvent(targetId: number, snapshotVersion: number, resumeToken?: ByteString): RemoteEvent; +export declare function existenceFilterEvent(targetId: number, syncedKeys: DocumentKeySet, remoteCount: number, snapshotVersion: number, bloomFilter?: api.BloomFilter): RemoteEvent; +export declare function docAddedRemoteEvent(docOrDocs: MutableDocument | MutableDocument[], updatedInTargets?: TargetId[], removedFromTargets?: TargetId[], activeTargets?: TargetId[]): RemoteEvent; +export declare function docUpdateRemoteEvent(doc: MutableDocument, updatedInTargets?: TargetId[], removedFromTargets?: TargetId[], limboTargets?: TargetId[]): RemoteEvent; +export declare class TestBundledDocuments { + documents: BundledDocuments; + bundleName: string; + constructor(documents: BundledDocuments, bundleName: string); +} +export declare function bundledDocuments(documents: MutableDocument[], queryNames?: string[][], bundleName?: string): TestBundledDocuments; +export declare class TestNamedQuery { + namedQuery: ProtoNamedQuery; + matchingDocuments: DocumentKeySet; + constructor(namedQuery: ProtoNamedQuery, matchingDocuments: DocumentKeySet); +} +export declare function namedQuery(name: string, query: Query, limitType: ProtoLimitType, readTime: SnapshotVersion, matchingDocuments?: DocumentKeySet): TestNamedQuery; +export declare function bundleMetadata(id: string, createTime: TestSnapshotVersion, version?: number, totalDocuments?: number, totalBytes?: number): ProtoBundleMetadata; +export declare function updateMapping(snapshotVersion: SnapshotVersion, added: Array, modified: Array, removed: Array, current?: boolean): TargetChange; +export declare function addTargetMapping(...docsOrKeys: Array): TargetChange; +export declare function ackTarget(...docsOrKeys: Array): TargetChange; +export declare function limboChanges(changes: { + added?: Document[]; + removed?: Document[]; +}): LimboDocumentChange[]; +export declare function localViewChanges(targetId: TargetId, fromCache: boolean, changes: { + added?: string[]; + removed?: string[]; +}): LocalViewChanges; +/** + * Returns a ByteString representation for the platform from the given string. + */ +export declare function byteStringFromString(value: string): ByteString; +/** + * Decodes a base 64 decoded string. + * + * Note that this is typed to accept Uint8Arrays to match the types used + * by the spec tests. Since the spec tests only use JSON strings, this method + * throws if an Uint8Array is passed. + */ +export declare function stringFromBase64String(value?: string | Uint8Array): string; +/** Creates a resume token to match the given snapshot version. */ +export declare function resumeTokenForSnapshot(snapshotVersion: SnapshotVersion): ByteString; +export declare function orderBy(path: string, op?: string): OrderBy; +/** + * Converts a sorted map to an array with inorder traversal + */ +export declare function mapAsArray(sortedMap: SortedMap): Array<{ + key: K; + value: V; +}>; +/** + * Converts a list of documents or document keys to a sorted map. A document + * key is used to represent a deletion and maps to null. + */ +export declare function documentUpdates(...docsOrKeys: Array): DocumentMap; +/** + * Short for view.applyChanges(view.computeDocChanges(documentUpdates(docs))). + */ +export declare function applyDocChanges(view: View, ...docsOrKeys: Array): ViewChange; +/** + * Constructs a document set. + */ +export declare function documentSet(comp: DocumentComparator, ...docs: Document[]): DocumentSet; +export declare function documentSet(...docs: Document[]): DocumentSet; +/** + * Constructs a document key set. + */ +export declare function keySet(...keys: DocumentKey[]): DocumentKeySet; +/** Converts a DocumentSet to an array. */ +export declare function documentSetAsArray(docs: DocumentSet): Document[]; +export declare class DocComparator { + static byField(...fields: string[]): DocumentComparator; +} +/** + * Two helper functions to simplify testing isEqual() method. + */ +export declare function expectEqual(left: any, right: any, message?: string): void; +export declare function expectNotEqual(left: any, right: any, message?: string): void; +export declare function expectEqualArrays(left: unknown[], right: unknown[], message?: string): void; +/** + * Checks that an ordered array of elements yields the correct pair-wise + * comparison result for the supplied comparator + */ +export declare function expectCorrectComparisons(array: T[], comp: (left: T, right: T) => number): void; +/** + * Takes an array of "equality group" arrays and asserts that the comparator + * returns the same as comparing the indexes of the "equality groups" + * (0 for items in the same group). + */ +export declare function expectCorrectComparisonGroups(groups: T[][], comp: (left: T, right: T) => number): void; +/** Compares SortedSet to an array */ +export declare function expectSetToEqual(set: SortedSet, arr: T[]): void; +/** + * Takes an array of array of elements and compares each of the elements + * to every other element. + * + * Elements in the same inner array are expect to be equal with regard to + * the provided equality function to all other elements from the same array + * (including itself) and unequal to all other elements from the other array + */ +export declare function expectEqualitySets(elems: T[][], equalityFn: (v1: T, v2: T) => boolean, stringifyFn?: (v: T) => string): void; +export declare function validateFirestoreError(expectedCode: Code, actualError: Error): void; +export declare function forEachNumber(obj: Dict, fn: (key: number, val: V) => void): void; +/** + * Returns all possible permutations of the given array. + * For `[a, b]`, this method returns `[[a, b], [b, a]]`. + */ +export declare function computePermutations(input: T[]): T[][]; +/** + * Returns all possible combinations of the given array, including an empty + * array. For `[a, b, c]` this method returns + * `[[], [a], [a, b], [a, c], [b, c], [a, b, c]`. + */ +export declare function computeCombinations(input: T[]): T[][]; +/** + * Helper method to generate bloom filter proto value for mocking watch + * existence filter response. + */ +export declare function generateBloomFilterProto(config: { + contains: MutableDocument[]; + notContains: MutableDocument[]; + hashCount?: number; + bitCount?: number; +}): api.BloomFilter; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/util/node_persistence.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/util/node_persistence.d.ts new file mode 100644 index 0000000..c53048a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/util/node_persistence.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/util/promise.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/util/promise.d.ts new file mode 100644 index 0000000..d3f8374 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/util/promise.d.ts @@ -0,0 +1,28 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export interface Resolver { + (value: R | Promise): void; +} +export interface Rejecter { + (reason?: Error): void; +} +export declare class Deferred { + promise: Promise; + resolve: Resolver; + reject: Rejecter; + constructor(); +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/util/spec_test_helpers.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/util/spec_test_helpers.d.ts new file mode 100644 index 0000000..1ae9b67 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/util/spec_test_helpers.d.ts @@ -0,0 +1,19 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as api from '../../src/protos/firestore_proto_api'; +import { WatchChange } from '../../src/remote/watch_change'; +export declare function encodeWatchChange(watchChange: WatchChange): api.ListenResponse; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/util/test_platform.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/util/test_platform.d.ts new file mode 100644 index 0000000..8417eb4 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/firestore/test/util/test_platform.d.ts @@ -0,0 +1,61 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentLike, WindowLike } from '../../src/util/types'; +/** + * `Window` fake that implements the event and storage API that is used by + * Firestore. + */ +export declare class FakeWindow implements WindowLike { + private readonly fakeStorageArea; + private readonly fakeIndexedDb; + private storageListeners; + constructor(sharedFakeStorage: SharedFakeWebStorage, fakeIndexedDb?: IDBFactory); + get localStorage(): Storage; + get indexedDB(): IDBFactory | null; + addEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: EventListener): void; +} +export declare function testWindow(sharedWebStorage?: SharedFakeWebStorage): FakeWindow; +/** + * `Document` fake that implements the `visibilitychange` API used by Firestore. + */ +export declare class FakeDocument implements DocumentLike { + private _visibilityState; + private visibilityListener; + get visibilityState(): DocumentVisibilityState; + addEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: EventListener): void; + raiseVisibilityEvent(visibility: DocumentVisibilityState): void; +} +export declare function testDocument(): FakeDocument; +/** + * `WebStorage` mock that implements the WebStorage behavior for multiple + * clients. To get a client-specific storage area that implements the WebStorage + * API, invoke `getStorageArea(storageListener)`. + */ +export declare class SharedFakeWebStorage { + private readonly data; + private readonly activeClients; + getStorageArea(storageListener: EventListener): Storage; + private clear; + private getItem; + private key; + private removeItem; + private setItem; + private get length(); + private raiseStorageEvent; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/index.cjs.js b/frontend-old/node_modules/@firebase/firestore/dist/index.cjs.js new file mode 100644 index 0000000..dbea5e0 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/index.cjs.js @@ -0,0 +1,23241 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var app = require('@firebase/app'); +var component = require('@firebase/component'); +var logger = require('@firebase/logger'); +var util = require('@firebase/util'); +var bloomBlob = require('@firebase/webchannel-wrapper/bloom-blob'); +var webchannelBlob = require('@firebase/webchannel-wrapper/webchannel-blob'); + +const F = "@firebase/firestore", M = "4.9.2"; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Simple wrapper around a nullable UID. Mostly exists to make code more + * readable. + */ +class User { + constructor(e) { + this.uid = e; + } + isAuthenticated() { + return null != this.uid; + } + /** + * Returns a key representing this user, suitable for inclusion in a + * dictionary. + */ toKey() { + return this.isAuthenticated() ? "uid:" + this.uid : "anonymous-user"; + } + isEqual(e) { + return e.uid === this.uid; + } +} + +/** A user with a null UID. */ User.UNAUTHENTICATED = new User(null), +// TODO(mikelehen): Look into getting a proper uid-equivalent for +// non-FirebaseAuth providers. +User.GOOGLE_CREDENTIALS = new User("google-credentials-uid"), User.FIRST_PARTY = new User("first-party-uid"), +User.MOCK_USER = new User("mock-user"); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let x = "12.3.0"; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const O = new logger.Logger("@firebase/firestore"); + +// Helper methods are needed because variables can't be exported as read/write +function __PRIVATE_getLogLevel() { + return O.logLevel; +} + +/** + * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). + * + * @param logLevel - The verbosity you set for activity and error logging. Can + * be any of the following values: + * + *
    + *
  • `debug` for the most verbose logging level, primarily for + * debugging.
  • + *
  • `error` to log errors only.
  • + *
  • `silent` to turn off logging.
  • + *
+ */ function setLogLevel(e) { + O.setLogLevel(e); +} + +function __PRIVATE_logDebug(e, ...t) { + if (O.logLevel <= logger.LogLevel.DEBUG) { + const n = t.map(__PRIVATE_argToString); + O.debug(`Firestore (${x}): ${e}`, ...n); + } +} + +function __PRIVATE_logError(e, ...t) { + if (O.logLevel <= logger.LogLevel.ERROR) { + const n = t.map(__PRIVATE_argToString); + O.error(`Firestore (${x}): ${e}`, ...n); + } +} + +/** + * @internal + */ function __PRIVATE_logWarn(e, ...t) { + if (O.logLevel <= logger.LogLevel.WARN) { + const n = t.map(__PRIVATE_argToString); + O.warn(`Firestore (${x}): ${e}`, ...n); + } +} + +/** + * Converts an additional log parameter to a string representation. + */ function __PRIVATE_argToString(e) { + if ("string" == typeof e) return e; + try { + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** Formats an object as a JSON string, suitable for logging. */ + return function __PRIVATE_formatJSON(e) { + return JSON.stringify(e); + }(e); + } catch (t) { + // Converting to JSON failed, just log the object directly + return e; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function fail(e, t, n) { + let r = "Unexpected state"; + "string" == typeof t ? r = t : n = t, __PRIVATE__fail(e, r, n); +} + +function __PRIVATE__fail(e, t, n) { + // Log the failure in addition to throw an exception, just in case the + // exception is swallowed. + let r = `FIRESTORE (${x}) INTERNAL ASSERTION FAILED: ${t} (ID: ${e.toString(16)})`; + if (void 0 !== n) try { + r += " CONTEXT: " + JSON.stringify(n); + } catch (e) { + r += " CONTEXT: " + n; + } + // NOTE: We don't use FirestoreError here because these are internal failures + // that cannot be handled by the user. (Also it would create a circular + // dependency between the error and assert modules which doesn't work.) + throw __PRIVATE_logError(r), new Error(r); +} + +function __PRIVATE_hardAssert(e, t, n, r) { + let i = "Unexpected state"; + "string" == typeof n ? i = n : r = n, e || __PRIVATE__fail(t, i, r); +} + +/** + * Fails if the given assertion condition is false, throwing an Error with the + * given message if it did. + * + * The code of callsites invoking this function are stripped out in production + * builds. Any side-effects of code within the debugAssert() invocation will not + * happen in this case. + * + * @internal + */ function __PRIVATE_debugAssert(e, t) { + e || fail(57014, t); +} + +/** + * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an + * instance of `T` before casting. + */ function __PRIVATE_debugCast(e, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +t) { + return e; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const N = { + // Causes are copied from: + // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h + /** Not an error; returned on success. */ + OK: "ok", + /** The operation was cancelled (typically by the caller). */ + CANCELLED: "cancelled", + /** Unknown error or an error from a different error domain. */ + UNKNOWN: "unknown", + /** + * Client specified an invalid argument. Note that this differs from + * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are + * problematic regardless of the state of the system (e.g., a malformed file + * name). + */ + INVALID_ARGUMENT: "invalid-argument", + /** + * Deadline expired before operation could complete. For operations that + * change the state of the system, this error may be returned even if the + * operation has completed successfully. For example, a successful response + * from a server could have been delayed long enough for the deadline to + * expire. + */ + DEADLINE_EXCEEDED: "deadline-exceeded", + /** Some requested entity (e.g., file or directory) was not found. */ + NOT_FOUND: "not-found", + /** + * Some entity that we attempted to create (e.g., file or directory) already + * exists. + */ + ALREADY_EXISTS: "already-exists", + /** + * The caller does not have permission to execute the specified operation. + * PERMISSION_DENIED must not be used for rejections caused by exhausting + * some resource (use RESOURCE_EXHAUSTED instead for those errors). + * PERMISSION_DENIED must not be used if the caller cannot be identified + * (use UNAUTHENTICATED instead for those errors). + */ + PERMISSION_DENIED: "permission-denied", + /** + * The request does not have valid authentication credentials for the + * operation. + */ + UNAUTHENTICATED: "unauthenticated", + /** + * Some resource has been exhausted, perhaps a per-user quota, or perhaps the + * entire file system is out of space. + */ + RESOURCE_EXHAUSTED: "resource-exhausted", + /** + * Operation was rejected because the system is not in a state required for + * the operation's execution. For example, directory to be deleted may be + * non-empty, an rmdir operation is applied to a non-directory, etc. + * + * A litmus test that may help a service implementor in deciding + * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: + * (a) Use UNAVAILABLE if the client can retry just the failing call. + * (b) Use ABORTED if the client should retry at a higher-level + * (e.g., restarting a read-modify-write sequence). + * (c) Use FAILED_PRECONDITION if the client should not retry until + * the system state has been explicitly fixed. E.g., if an "rmdir" + * fails because the directory is non-empty, FAILED_PRECONDITION + * should be returned since the client should not retry unless + * they have first fixed up the directory by deleting files from it. + * (d) Use FAILED_PRECONDITION if the client performs conditional + * REST Get/Update/Delete on a resource and the resource on the + * server does not match the condition. E.g., conflicting + * read-modify-write on the same resource. + */ + FAILED_PRECONDITION: "failed-precondition", + /** + * The operation was aborted, typically due to a concurrency issue like + * sequencer check failures, transaction aborts, etc. + * + * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, + * and UNAVAILABLE. + */ + ABORTED: "aborted", + /** + * Operation was attempted past the valid range. E.g., seeking or reading + * past end of file. + * + * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed + * if the system state changes. For example, a 32-bit file system will + * generate INVALID_ARGUMENT if asked to read at an offset that is not in the + * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from + * an offset past the current file size. + * + * There is a fair bit of overlap between FAILED_PRECONDITION and + * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) + * when it applies so that callers who are iterating through a space can + * easily look for an OUT_OF_RANGE error to detect when they are done. + */ + OUT_OF_RANGE: "out-of-range", + /** Operation is not implemented or not supported/enabled in this service. */ + UNIMPLEMENTED: "unimplemented", + /** + * Internal errors. Means some invariants expected by underlying System has + * been broken. If you see one of these errors, Something is very broken. + */ + INTERNAL: "internal", + /** + * The service is currently unavailable. This is a most likely a transient + * condition and may be corrected by retrying with a backoff. + * + * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, + * and UNAVAILABLE. + */ + UNAVAILABLE: "unavailable", + /** Unrecoverable data loss or corruption. */ + DATA_LOSS: "data-loss" +}; + +/** An error returned by a Firestore operation. */ class FirestoreError extends util.FirebaseError { + /** @hideconstructor */ + constructor( + /** + * The backend error code associated with this error. + */ + e, + /** + * A custom error description. + */ + t) { + super(e, t), this.code = e, this.message = t, + // HACK: We write a toString property directly because Error is not a real + // class and so inheritance does not work correctly. We could alternatively + // do the same "back-door inheritance" trick that FirebaseError does. + this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_Deferred { + constructor() { + this.promise = new Promise(((e, t) => { + this.resolve = e, this.reject = t; + })); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_OAuthToken { + constructor(e, t) { + this.user = t, this.type = "OAuth", this.headers = new Map, this.headers.set("Authorization", `Bearer ${e}`); + } +} + +/** + * A CredentialsProvider that always yields an empty token. + * @internal + */ class __PRIVATE_EmptyAuthCredentialsProvider { + getToken() { + return Promise.resolve(null); + } + invalidateToken() {} + start(e, t) { + // Fire with initial user. + e.enqueueRetryable((() => t(User.UNAUTHENTICATED))); + } + shutdown() {} +} + +/** + * A CredentialsProvider that always returns a constant token. Used for + * emulator token mocking. + */ class __PRIVATE_EmulatorAuthCredentialsProvider { + constructor(e) { + this.token = e, + /** + * Stores the listener registered with setChangeListener() + * This isn't actually necessary since the UID never changes, but we use this + * to verify the listen contract is adhered to in tests. + */ + this.changeListener = null; + } + getToken() { + return Promise.resolve(this.token); + } + invalidateToken() {} + start(e, t) { + this.changeListener = t, + // Fire with initial user. + e.enqueueRetryable((() => t(this.token.user))); + } + shutdown() { + this.changeListener = null; + } +} + +class __PRIVATE_FirebaseAuthCredentialsProvider { + constructor(e) { + this.t = e, + /** Tracks the current User. */ + this.currentUser = User.UNAUTHENTICATED, + /** + * Counter used to detect if the token changed while a getToken request was + * outstanding. + */ + this.i = 0, this.forceRefresh = !1, this.auth = null; + } + start(e, t) { + __PRIVATE_hardAssert(void 0 === this.o, 42304); + let n = this.i; + // A change listener that prevents double-firing for the same token change. + const __PRIVATE_guardedChangeListener = e => this.i !== n ? (n = this.i, + t(e)) : Promise.resolve(); + // A promise that can be waited on to block on the next token change. + // This promise is re-created after each change. + let r = new __PRIVATE_Deferred; + this.o = () => { + this.i++, this.currentUser = this.u(), r.resolve(), r = new __PRIVATE_Deferred, + e.enqueueRetryable((() => __PRIVATE_guardedChangeListener(this.currentUser))); + }; + const __PRIVATE_awaitNextToken = () => { + const t = r; + e.enqueueRetryable((async () => { + await t.promise, await __PRIVATE_guardedChangeListener(this.currentUser); + })); + }, __PRIVATE_registerAuth = e => { + __PRIVATE_logDebug("FirebaseAuthCredentialsProvider", "Auth detected"), this.auth = e, + this.o && (this.auth.addAuthTokenListener(this.o), __PRIVATE_awaitNextToken()); + }; + this.t.onInit((e => __PRIVATE_registerAuth(e))), + // Our users can initialize Auth right after Firestore, so we give it + // a chance to register itself with the component framework before we + // determine whether to start up in unauthenticated mode. + setTimeout((() => { + if (!this.auth) { + const e = this.t.getImmediate({ + optional: !0 + }); + e ? __PRIVATE_registerAuth(e) : ( + // If auth is still not available, proceed with `null` user + __PRIVATE_logDebug("FirebaseAuthCredentialsProvider", "Auth not yet detected"), + r.resolve(), r = new __PRIVATE_Deferred); + } + }), 0), __PRIVATE_awaitNextToken(); + } + getToken() { + // Take note of the current value of the tokenCounter so that this method + // can fail (with an ABORTED error) if there is a token change while the + // request is outstanding. + const e = this.i, t = this.forceRefresh; + return this.forceRefresh = !1, this.auth ? this.auth.getToken(t).then((t => + // Cancel the request since the token changed while the request was + // outstanding so the response is potentially for a previous user (which + // user, we can't be sure). + this.i !== e ? (__PRIVATE_logDebug("FirebaseAuthCredentialsProvider", "getToken aborted due to token change."), + this.getToken()) : t ? (__PRIVATE_hardAssert("string" == typeof t.accessToken, 31837, { + l: t + }), new __PRIVATE_OAuthToken(t.accessToken, this.currentUser)) : null)) : Promise.resolve(null); + } + invalidateToken() { + this.forceRefresh = !0; + } + shutdown() { + this.auth && this.o && this.auth.removeAuthTokenListener(this.o), this.o = void 0; + } + // Auth.getUid() can return null even with a user logged in. It is because + // getUid() is synchronous, but the auth code populating Uid is asynchronous. + // This method should only be called in the AuthTokenListener callback + // to guarantee to get the actual user. + u() { + const e = this.auth && this.auth.getUid(); + return __PRIVATE_hardAssert(null === e || "string" == typeof e, 2055, { + h: e + }), new User(e); + } +} + +/* + * FirstPartyToken provides a fresh token each time its value + * is requested, because if the token is too old, requests will be rejected. + * Technically this may no longer be necessary since the SDK should gracefully + * recover from unauthenticated errors (see b/33147818 for context), but it's + * safer to keep the implementation as-is. + */ class __PRIVATE_FirstPartyToken { + constructor(e, t, n) { + this.P = e, this.T = t, this.I = n, this.type = "FirstParty", this.user = User.FIRST_PARTY, + this.A = new Map; + } + /** + * Gets an authorization token, using a provided factory function, or return + * null. + */ R() { + return this.I ? this.I() : null; + } + get headers() { + this.A.set("X-Goog-AuthUser", this.P); + // Use array notation to prevent minification + const e = this.R(); + return e && this.A.set("Authorization", e), this.T && this.A.set("X-Goog-Iam-Authorization-Token", this.T), + this.A; + } +} + +/* + * Provides user credentials required for the Firestore JavaScript SDK + * to authenticate the user, using technique that is only available + * to applications hosted by Google. + */ class __PRIVATE_FirstPartyAuthCredentialsProvider { + constructor(e, t, n) { + this.P = e, this.T = t, this.I = n; + } + getToken() { + return Promise.resolve(new __PRIVATE_FirstPartyToken(this.P, this.T, this.I)); + } + start(e, t) { + // Fire with initial uid. + e.enqueueRetryable((() => t(User.FIRST_PARTY))); + } + shutdown() {} + invalidateToken() {} +} + +class AppCheckToken { + constructor(e) { + this.value = e, this.type = "AppCheck", this.headers = new Map, e && e.length > 0 && this.headers.set("x-firebase-appcheck", this.value); + } +} + +class __PRIVATE_FirebaseAppCheckTokenProvider { + constructor(t, n) { + this.V = n, this.forceRefresh = !1, this.appCheck = null, this.m = null, this.p = null, + app._isFirebaseServerApp(t) && t.settings.appCheckToken && (this.p = t.settings.appCheckToken); + } + start(e, t) { + __PRIVATE_hardAssert(void 0 === this.o, 3512); + const onTokenChanged = e => { + null != e.error && __PRIVATE_logDebug("FirebaseAppCheckTokenProvider", `Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`); + const n = e.token !== this.m; + return this.m = e.token, __PRIVATE_logDebug("FirebaseAppCheckTokenProvider", `Received ${n ? "new" : "existing"} token.`), + n ? t(e.token) : Promise.resolve(); + }; + this.o = t => { + e.enqueueRetryable((() => onTokenChanged(t))); + }; + const __PRIVATE_registerAppCheck = e => { + __PRIVATE_logDebug("FirebaseAppCheckTokenProvider", "AppCheck detected"), this.appCheck = e, + this.o && this.appCheck.addTokenListener(this.o); + }; + this.V.onInit((e => __PRIVATE_registerAppCheck(e))), + // Our users can initialize AppCheck after Firestore, so we give it + // a chance to register itself with the component framework. + setTimeout((() => { + if (!this.appCheck) { + const e = this.V.getImmediate({ + optional: !0 + }); + e ? __PRIVATE_registerAppCheck(e) : + // If AppCheck is still not available, proceed without it. + __PRIVATE_logDebug("FirebaseAppCheckTokenProvider", "AppCheck not yet detected"); + } + }), 0); + } + getToken() { + if (this.p) return Promise.resolve(new AppCheckToken(this.p)); + const e = this.forceRefresh; + return this.forceRefresh = !1, this.appCheck ? this.appCheck.getToken(e).then((e => e ? (__PRIVATE_hardAssert("string" == typeof e.token, 44558, { + tokenResult: e + }), this.m = e.token, new AppCheckToken(e.token)) : null)) : Promise.resolve(null); + } + invalidateToken() { + this.forceRefresh = !0; + } + shutdown() { + this.appCheck && this.o && this.appCheck.removeTokenListener(this.o), this.o = void 0; + } +} + +/** + * An AppCheck token provider that always yields an empty token. + * @internal + */ class __PRIVATE_EmptyAppCheckTokenProvider { + getToken() { + return Promise.resolve(new AppCheckToken("")); + } + invalidateToken() {} + start(e, t) {} + shutdown() {} +} + +/** + * Builds a CredentialsProvider depending on the type of + * the credentials passed in. + */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Generates `nBytes` of random bytes. + * + * If `nBytes < 0` , an error will be thrown. + */ +function __PRIVATE_randomBytes(e) { + // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available. + const t = + // eslint-disable-next-line @typescript-eslint/no-explicit-any + "undefined" != typeof self && (self.crypto || self.msCrypto), n = new Uint8Array(e); + if (t && "function" == typeof t.getRandomValues) t.getRandomValues(n); else + // Falls back to Math.random + for (let t = 0; t < e; t++) n[t] = Math.floor(256 * Math.random()); + return n; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A utility class for generating unique alphanumeric IDs of a specified length. + * + * @internal + * Exported internally for testing purposes. + */ class __PRIVATE_AutoId { + static newId() { + // Alphanumeric characters + const e = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", t = 62 * Math.floor(256 / 62); + // The largest byte value that is a multiple of `char.length`. + let n = ""; + for (;n.length < 20; ) { + const r = __PRIVATE_randomBytes(40); + for (let i = 0; i < r.length; ++i) + // Only accept values that are [0, maxMultiple), this ensures they can + // be evenly mapped to indices of `chars` via a modulo operation. + n.length < 20 && r[i] < t && (n += e.charAt(r[i] % 62)); + } + return n; + } +} + +function __PRIVATE_primitiveComparator(e, t) { + return e < t ? -1 : e > t ? 1 : 0; +} + +/** Compare strings in UTF-8 encoded byte order */ function __PRIVATE_compareUtf8Strings(e, t) { + // Find the first differing character (a.k.a. "UTF-16 code unit") in the two strings and, + // if found, use that character to determine the relative ordering of the two strings as a + // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by + // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8 + // and UTF-16 happen to represent Unicode code points. + // After finding the first pair of differing characters, there are two cases: + // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or + // both are surrogates from a surrogate pair (that collectively represent code points greater + // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the + // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is + // sufficient. + // Case 2: One character is a surrogate and the other is not. In this case the surrogate- + // containing string is always ordered after the non-surrogate. This is because surrogates are + // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations + // and are lexicographically greater than the 1, 2, or 3-byte representations of code points + // less than or equal to 0xFFFF. + // An example of why Case 2 is required is comparing the following two Unicode code points: + // |-----------------------|------------|---------------------|-----------------| + // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding | + // |-----------------------|------------|---------------------|-----------------| + // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD | + // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 | + // |-----------------------|------------|---------------------|-----------------| + // A lexicographical comparison of the UTF-8 encodings of these code points would order + // "Replacement Character" _before_ "Grinning Face" because 0xEF is less than 0xF0. However, a + // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously + // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out, + // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate + // pair with those that do not. + const n = Math.min(e.length, t.length); + for (let r = 0; r < n; r++) { + const n = e.charAt(r), i = t.charAt(r); + if (n !== i) return __PRIVATE_isSurrogate(n) === __PRIVATE_isSurrogate(i) ? __PRIVATE_primitiveComparator(n, i) : __PRIVATE_isSurrogate(n) ? 1 : -1; + } + // Use the lengths of the strings to determine the overall comparison result since either the + // strings were equal or one is a prefix of the other. + return __PRIVATE_primitiveComparator(e.length, t.length); +} + +const B = 55296, L = 57343; + +function __PRIVATE_isSurrogate(e) { + const t = e.charCodeAt(0); + return t >= B && t <= L; +} + +/** Helper to compare arrays using isEqual(). */ function __PRIVATE_arrayEquals(e, t, n) { + return e.length === t.length && e.every(((e, r) => n(e, t[r]))); +} + +/** + * Returns the immediate lexicographically-following string. This is useful to + * construct an inclusive range for indexeddb iterators. + */ function __PRIVATE_immediateSuccessor(e) { + // Return the input string, with an additional NUL byte appended. + return e + "\0"; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const k = "__name__"; + +/** + * Path represents an ordered sequence of string segments. + */ class BasePath { + constructor(e, t, n) { + void 0 === t ? t = 0 : t > e.length && fail(637, { + offset: t, + range: e.length + }), void 0 === n ? n = e.length - t : n > e.length - t && fail(1746, { + length: n, + range: e.length - t + }), this.segments = e, this.offset = t, this.len = n; + } + get length() { + return this.len; + } + isEqual(e) { + return 0 === BasePath.comparator(this, e); + } + child(e) { + const t = this.segments.slice(this.offset, this.limit()); + return e instanceof BasePath ? e.forEach((e => { + t.push(e); + })) : t.push(e), this.construct(t); + } + /** The index of one past the last segment of the path. */ limit() { + return this.offset + this.length; + } + popFirst(e) { + return e = void 0 === e ? 1 : e, this.construct(this.segments, this.offset + e, this.length - e); + } + popLast() { + return this.construct(this.segments, this.offset, this.length - 1); + } + firstSegment() { + return this.segments[this.offset]; + } + lastSegment() { + return this.get(this.length - 1); + } + get(e) { + return this.segments[this.offset + e]; + } + isEmpty() { + return 0 === this.length; + } + isPrefixOf(e) { + if (e.length < this.length) return !1; + for (let t = 0; t < this.length; t++) if (this.get(t) !== e.get(t)) return !1; + return !0; + } + isImmediateParentOf(e) { + if (this.length + 1 !== e.length) return !1; + for (let t = 0; t < this.length; t++) if (this.get(t) !== e.get(t)) return !1; + return !0; + } + forEach(e) { + for (let t = this.offset, n = this.limit(); t < n; t++) e(this.segments[t]); + } + toArray() { + return this.segments.slice(this.offset, this.limit()); + } + /** + * Compare 2 paths segment by segment, prioritizing numeric IDs + * (e.g., "__id123__") in numeric ascending order, followed by string + * segments in lexicographical order. + */ static comparator(e, t) { + const n = Math.min(e.length, t.length); + for (let r = 0; r < n; r++) { + const n = BasePath.compareSegments(e.get(r), t.get(r)); + if (0 !== n) return n; + } + return __PRIVATE_primitiveComparator(e.length, t.length); + } + static compareSegments(e, t) { + const n = BasePath.isNumericId(e), r = BasePath.isNumericId(t); + return n && !r ? -1 : !n && r ? 1 : n && r ? BasePath.extractNumericId(e).compare(BasePath.extractNumericId(t)) : __PRIVATE_compareUtf8Strings(e, t); + } + // Checks if a segment is a numeric ID (starts with "__id" and ends with "__"). + static isNumericId(e) { + return e.startsWith("__id") && e.endsWith("__"); + } + static extractNumericId(e) { + return bloomBlob.Integer.fromString(e.substring(4, e.length - 2)); + } +} + +/** + * A slash-separated path for navigating resources (documents and collections) + * within Firestore. + * + * @internal + */ class ResourcePath extends BasePath { + construct(e, t, n) { + return new ResourcePath(e, t, n); + } + canonicalString() { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + return this.toArray().join("/"); + } + toString() { + return this.canonicalString(); + } + /** + * Returns a string representation of this path + * where each path segment has been encoded with + * `encodeURIComponent`. + */ toUriEncodedString() { + return this.toArray().map(encodeURIComponent).join("/"); + } + /** + * Creates a resource path from the given slash-delimited string. If multiple + * arguments are provided, all components are combined. Leading and trailing + * slashes from all components are ignored. + */ static fromString(...e) { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + const t = []; + for (const n of e) { + if (n.indexOf("//") >= 0) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid segment (${n}). Paths must not contain // in them.`); + // Strip leading and trailing slashed. + t.push(...n.split("/").filter((e => e.length > 0))); + } + return new ResourcePath(t); + } + static emptyPath() { + return new ResourcePath([]); + } +} + +const q = /^[_a-zA-Z][_a-zA-Z0-9]*$/; + +/** + * A dot-separated path for navigating sub-objects within a document. + * @internal + */ class FieldPath$1 extends BasePath { + construct(e, t, n) { + return new FieldPath$1(e, t, n); + } + /** + * Returns true if the string could be used as a segment in a field path + * without escaping. + */ static isValidIdentifier(e) { + return q.test(e); + } + canonicalString() { + return this.toArray().map((e => (e = e.replace(/\\/g, "\\\\").replace(/`/g, "\\`"), + FieldPath$1.isValidIdentifier(e) || (e = "`" + e + "`"), e))).join("."); + } + toString() { + return this.canonicalString(); + } + /** + * Returns true if this field references the key of a document. + */ isKeyField() { + return 1 === this.length && this.get(0) === k; + } + /** + * The field designating the key of a document. + */ static keyField() { + return new FieldPath$1([ k ]); + } + /** + * Parses a field string from the given server-formatted string. + * + * - Splitting the empty string is not allowed (for now at least). + * - Empty segments within the string (e.g. if there are two consecutive + * separators) are not allowed. + * + * TODO(b/37244157): we should make this more strict. Right now, it allows + * non-identifier path components, even if they aren't escaped. + */ static fromServerFormat(e) { + const t = []; + let n = "", r = 0; + const __PRIVATE_addCurrentSegment = () => { + if (0 === n.length) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`); + t.push(n), n = ""; + }; + let i = !1; + for (;r < e.length; ) { + const t = e[r]; + if ("\\" === t) { + if (r + 1 === e.length) throw new FirestoreError(N.INVALID_ARGUMENT, "Path has trailing escape character: " + e); + const t = e[r + 1]; + if ("\\" !== t && "." !== t && "`" !== t) throw new FirestoreError(N.INVALID_ARGUMENT, "Path has invalid escape sequence: " + e); + n += t, r += 2; + } else "`" === t ? (i = !i, r++) : "." !== t || i ? (n += t, r++) : (__PRIVATE_addCurrentSegment(), + r++); + } + if (__PRIVATE_addCurrentSegment(), i) throw new FirestoreError(N.INVALID_ARGUMENT, "Unterminated ` in path: " + e); + return new FieldPath$1(t); + } + static emptyPath() { + return new FieldPath$1([]); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @internal + */ class DocumentKey { + constructor(e) { + this.path = e; + } + static fromPath(e) { + return new DocumentKey(ResourcePath.fromString(e)); + } + static fromName(e) { + return new DocumentKey(ResourcePath.fromString(e).popFirst(5)); + } + static empty() { + return new DocumentKey(ResourcePath.emptyPath()); + } + get collectionGroup() { + return this.path.popLast().lastSegment(); + } + /** Returns true if the document is in the specified collectionId. */ hasCollectionId(e) { + return this.path.length >= 2 && this.path.get(this.path.length - 2) === e; + } + /** Returns the collection group (i.e. the name of the parent collection) for this key. */ getCollectionGroup() { + return this.path.get(this.path.length - 2); + } + /** Returns the fully qualified path to the parent collection. */ getCollectionPath() { + return this.path.popLast(); + } + isEqual(e) { + return null !== e && 0 === ResourcePath.comparator(this.path, e.path); + } + toString() { + return this.path.toString(); + } + static comparator(e, t) { + return ResourcePath.comparator(e.path, t.path); + } + static isDocumentKey(e) { + return e.length % 2 == 0; + } + /** + * Creates and returns a new document key with the given segments. + * + * @param segments - The segments of the path to the document + * @returns A new instance of DocumentKey + */ static fromSegments(e) { + return new DocumentKey(new ResourcePath(e.slice())); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_validateNonEmptyArgument(e, t, n) { + if (!n) throw new FirestoreError(N.INVALID_ARGUMENT, `Function ${e}() cannot be called with an empty ${t}.`); +} + +/** + * Validates that two boolean options are not set at the same time. + * @internal + */ function __PRIVATE_validateIsNotUsedTogether(e, t, n, r) { + if (!0 === t && !0 === r) throw new FirestoreError(N.INVALID_ARGUMENT, `${e} and ${n} cannot be used together.`); +} + +/** + * Validates that `path` refers to a document (indicated by the fact it contains + * an even numbers of segments). + */ function __PRIVATE_validateDocumentPath(e) { + if (!DocumentKey.isDocumentKey(e)) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`); +} + +/** + * Validates that `path` refers to a collection (indicated by the fact it + * contains an odd numbers of segments). + */ function __PRIVATE_validateCollectionPath(e) { + if (DocumentKey.isDocumentKey(e)) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`); +} + +/** + * Returns true if it's a non-null object without a custom prototype + * (i.e. excludes Array, Date, etc.). + */ function __PRIVATE_isPlainObject(e) { + return "object" == typeof e && null !== e && (Object.getPrototypeOf(e) === Object.prototype || null === Object.getPrototypeOf(e)); +} + +/** Returns a string describing the type / value of the provided input. */ function __PRIVATE_valueDescription(e) { + if (void 0 === e) return "undefined"; + if (null === e) return "null"; + if ("string" == typeof e) return e.length > 20 && (e = `${e.substring(0, 20)}...`), + JSON.stringify(e); + if ("number" == typeof e || "boolean" == typeof e) return "" + e; + if ("object" == typeof e) { + if (e instanceof Array) return "an array"; + { + const t = + /** try to get the constructor name for an object. */ + function __PRIVATE_tryGetCustomObjectType(e) { + if (e.constructor) return e.constructor.name; + return null; + } + /** + * Casts `obj` to `T`, optionally unwrapping Compat types to expose the + * underlying instance. Throws if `obj` is not an instance of `T`. + * + * This cast is used in the Lite and Full SDK to verify instance types for + * arguments passed to the public API. + * @internal + */ (e); + return t ? `a custom ${t} object` : "an object"; + } + } + return "function" == typeof e ? "a function" : fail(12329, { + type: typeof e + }); +} + +function __PRIVATE_cast(e, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +t) { + if ("_delegate" in e && ( + // Unwrap Compat types + // eslint-disable-next-line @typescript-eslint/no-explicit-any + e = e._delegate), !(e instanceof t)) { + if (t.name === e.constructor.name) throw new FirestoreError(N.INVALID_ARGUMENT, "Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?"); + { + const n = __PRIVATE_valueDescription(e); + throw new FirestoreError(N.INVALID_ARGUMENT, `Expected type '${t.name}', but it was: ${n}`); + } + } + return e; +} + +function __PRIVATE_validatePositiveNumber(e, t) { + if (t <= 0) throw new FirestoreError(N.INVALID_ARGUMENT, `Function ${e}() requires a positive number, but it was: ${t}.`); +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Helper function to define a JSON schema {@link Property}. + * @private + * @internal + */ function property(e, t) { + const n = { + typeString: e + }; + return t && (n.value = t), n; +} + +/** + * Validates the JSON object based on the provided schema, and narrows the type to the provided + * JSON schema. + * @private + * @internal + * + * @param json A JSON object to validate. + * @param scheme a {@link JsonSchema} that defines the properties to validate. + * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise. + */ function __PRIVATE_validateJSON(e, t) { + if (!__PRIVATE_isPlainObject(e)) throw new FirestoreError(N.INVALID_ARGUMENT, "JSON must be an object"); + let n; + for (const r in t) if (t[r]) { + const i = t[r].typeString, s = "value" in t[r] ? { + value: t[r].value + } : void 0; + if (!(r in e)) { + n = `JSON missing required field: '${r}'`; + break; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const o = e[r]; + if (i && typeof o !== i) { + n = `JSON field '${r}' must be a ${i}.`; + break; + } + if (void 0 !== s && o !== s.value) { + n = `Expected '${r}' field to equal '${s.value}'`; + break; + } + } + if (n) throw new FirestoreError(N.INVALID_ARGUMENT, n); + return !0; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z). +const Q = -62135596800, $ = 1e6; + +// Number of nanoseconds in a millisecond. +/** + * A `Timestamp` represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. + * + * It is encoded using the Proleptic Gregorian Calendar which extends the + * Gregorian calendar backwards to year one. It is encoded assuming all minutes + * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59.999999999Z. + * + * For examples and further specifications, refer to the + * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. + */ +class Timestamp { + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns a new timestamp representing the current date. + */ + static now() { + return Timestamp.fromMillis(Date.now()); + } + /** + * Creates a new timestamp from the given date. + * + * @param date - The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the given + * date. + */ static fromDate(e) { + return Timestamp.fromMillis(e.getTime()); + } + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds - Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the given + * number of milliseconds. + */ static fromMillis(e) { + const t = Math.floor(e / 1e3), n = Math.floor((e - 1e3 * t) * $); + return new Timestamp(t, n); + } + /** + * Creates a new timestamp. + * + * @param seconds - The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds - The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + e, + /** + * The fractions of a second at nanosecond resolution.* + */ + t) { + if (this.seconds = e, this.nanoseconds = t, t < 0) throw new FirestoreError(N.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + t); + if (t >= 1e9) throw new FirestoreError(N.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + t); + if (e < Q) throw new FirestoreError(N.INVALID_ARGUMENT, "Timestamp seconds out of range: " + e); + // This will break in the year 10,000. + if (e >= 253402300800) throw new FirestoreError(N.INVALID_ARGUMENT, "Timestamp seconds out of range: " + e); + } + /** + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ toDate() { + return new Date(this.toMillis()); + } + /** + * Converts a `Timestamp` to a numeric timestamp (in milliseconds since + * epoch). This operation causes a loss of precision. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ toMillis() { + return 1e3 * this.seconds + this.nanoseconds / $; + } + _compareTo(e) { + return this.seconds === e.seconds ? __PRIVATE_primitiveComparator(this.nanoseconds, e.nanoseconds) : __PRIVATE_primitiveComparator(this.seconds, e.seconds); + } + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other - The `Timestamp` to compare against. + * @returns true if this `Timestamp` is equal to the provided one. + */ isEqual(e) { + return e.seconds === this.seconds && e.nanoseconds === this.nanoseconds; + } + /** Returns a textual representation of this `Timestamp`. */ toString() { + return "Timestamp(seconds=" + this.seconds + ", nanoseconds=" + this.nanoseconds + ")"; + } + /** + * Returns a JSON-serializable representation of this `Timestamp`. + */ toJSON() { + return { + type: Timestamp._jsonSchemaVersion, + seconds: this.seconds, + nanoseconds: this.nanoseconds + }; + } + /** + * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}. + */ static fromJSON(e) { + if (__PRIVATE_validateJSON(e, Timestamp._jsonSchema)) return new Timestamp(e.seconds, e.nanoseconds); + } + /** + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. + */ valueOf() { + // This method returns a string of the form . where + // is translated to have a non-negative value and both + // and are left-padded with zeroes to be a consistent length. + // Strings with this format then have a lexicographical ordering that matches + // the expected ordering. The translation is done to avoid having + // a leading negative sign (i.e. a leading '-' character) in its string + // representation, which would affect its lexicographical ordering. + const e = this.seconds - Q; + // Note: Up to 12 decimal digits are required to represent all valid + // 'seconds' values. + return String(e).padStart(12, "0") + "." + String(this.nanoseconds).padStart(9, "0"); + } +} + +Timestamp._jsonSchemaVersion = "firestore/timestamp/1.0", Timestamp._jsonSchema = { + type: property("string", Timestamp._jsonSchemaVersion), + seconds: property("number"), + nanoseconds: property("number") +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A version of a document in Firestore. This corresponds to the version + * timestamp, such as update_time or read_time. + */ +class SnapshotVersion { + static fromTimestamp(e) { + return new SnapshotVersion(e); + } + static min() { + return new SnapshotVersion(new Timestamp(0, 0)); + } + static max() { + return new SnapshotVersion(new Timestamp(253402300799, 999999999)); + } + constructor(e) { + this.timestamp = e; + } + compareTo(e) { + return this.timestamp._compareTo(e.timestamp); + } + isEqual(e) { + return this.timestamp.isEqual(e.timestamp); + } + /** Returns a number representation of the version for use in spec tests. */ toMicroseconds() { + // Convert to microseconds. + return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3; + } + toString() { + return "SnapshotVersion(" + this.timestamp.toString() + ")"; + } + toTimestamp() { + return this.timestamp; + } +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The initial mutation batch id for each index. Gets updated during index + * backfill. + */ const U = -1; + +/** + * The initial sequence number for each index. Gets updated during index + * backfill. + */ +/** + * An index definition for field indexes in Firestore. + * + * Every index is associated with a collection. The definition contains a list + * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or + * `CONTAINS` for ArrayContains/ArrayContainsAny queries). + * + * Unlike the backend, the SDK does not differentiate between collection or + * collection group-scoped indices. Every index can be used for both single + * collection and collection group queries. + */ +class FieldIndex { + constructor( + /** + * The index ID. Returns -1 if the index ID is not available (e.g. the index + * has not yet been persisted). + */ + e, + /** The collection ID this index applies to. */ + t, + /** The field segments for this index. */ + n, + /** Shows how up-to-date the index is for the current user. */ + r) { + this.indexId = e, this.collectionGroup = t, this.fields = n, this.indexState = r; + } +} + +/** An ID for an index that has not yet been added to persistence. */ +/** Returns the ArrayContains/ArrayContainsAny segment for this index. */ +function __PRIVATE_fieldIndexGetArraySegment(e) { + return e.fields.find((e => 2 /* IndexKind.CONTAINS */ === e.kind)); +} + +/** Returns all directional (ascending/descending) segments for this index. */ function __PRIVATE_fieldIndexGetDirectionalSegments(e) { + return e.fields.filter((e => 2 /* IndexKind.CONTAINS */ !== e.kind)); +} + +/** + * Returns the order of the document key component for the given index. + * + * PORTING NOTE: This is only used in the Web IndexedDb implementation. + */ +/** + * Compares indexes by collection group and segments. Ignores update time and + * index ID. + */ +function __PRIVATE_fieldIndexSemanticComparator(e, t) { + let n = __PRIVATE_primitiveComparator(e.collectionGroup, t.collectionGroup); + if (0 !== n) return n; + for (let r = 0; r < Math.min(e.fields.length, t.fields.length); ++r) if (n = __PRIVATE_indexSegmentComparator(e.fields[r], t.fields[r]), + 0 !== n) return n; + return __PRIVATE_primitiveComparator(e.fields.length, t.fields.length); +} + +/** Returns a debug representation of the field index */ FieldIndex.UNKNOWN_ID = -1; + +/** An index component consisting of field path and index type. */ +class IndexSegment { + constructor( + /** The field path of the component. */ + e, + /** The fields sorting order. */ + t) { + this.fieldPath = e, this.kind = t; + } +} + +function __PRIVATE_indexSegmentComparator(e, t) { + const n = FieldPath$1.comparator(e.fieldPath, t.fieldPath); + return 0 !== n ? n : __PRIVATE_primitiveComparator(e.kind, t.kind); +} + +/** + * Stores the "high water mark" that indicates how updated the Index is for the + * current user. + */ class IndexState { + constructor( + /** + * Indicates when the index was last updated (relative to other indexes). + */ + e, + /** The the latest indexed read time, document and batch id. */ + t) { + this.sequenceNumber = e, this.offset = t; + } + /** The state of an index that has not yet been backfilled. */ static empty() { + return new IndexState(0, IndexOffset.min()); + } +} + +/** + * Creates an offset that matches all documents with a read time higher than + * `readTime`. + */ function __PRIVATE_newIndexOffsetSuccessorFromReadTime(e, t) { + // We want to create an offset that matches all documents with a read time + // greater than the provided read time. To do so, we technically need to + // create an offset for `(readTime, MAX_DOCUMENT_KEY)`. While we could use + // Unicode codepoints to generate MAX_DOCUMENT_KEY, it is much easier to use + // `(readTime + 1, DocumentKey.empty())` since `> DocumentKey.empty()` matches + // all valid document IDs. + const n = e.toTimestamp().seconds, r = e.toTimestamp().nanoseconds + 1, i = SnapshotVersion.fromTimestamp(1e9 === r ? new Timestamp(n + 1, 0) : new Timestamp(n, r)); + return new IndexOffset(i, DocumentKey.empty(), t); +} + +/** Creates a new offset based on the provided document. */ function __PRIVATE_newIndexOffsetFromDocument(e) { + return new IndexOffset(e.readTime, e.key, U); +} + +/** + * Stores the latest read time, document and batch ID that were processed for an + * index. + */ class IndexOffset { + constructor( + /** + * The latest read time version that has been indexed by Firestore for this + * field index. + */ + e, + /** + * The key of the last document that was indexed for this query. Use + * `DocumentKey.empty()` if no document has been indexed. + */ + t, + /* + * The largest mutation batch id that's been processed by Firestore. + */ + n) { + this.readTime = e, this.documentKey = t, this.largestBatchId = n; + } + /** Returns an offset that sorts before all regular offsets. */ static min() { + return new IndexOffset(SnapshotVersion.min(), DocumentKey.empty(), U); + } + /** Returns an offset that sorts after all regular offsets. */ static max() { + return new IndexOffset(SnapshotVersion.max(), DocumentKey.empty(), U); + } +} + +function __PRIVATE_indexOffsetComparator(e, t) { + let n = e.readTime.compareTo(t.readTime); + return 0 !== n ? n : (n = DocumentKey.comparator(e.documentKey, t.documentKey), + 0 !== n ? n : __PRIVATE_primitiveComparator(e.largestBatchId, t.largestBatchId)); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const K = "The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab."; + +/** + * A base class representing a persistence transaction, encapsulating both the + * transaction's sequence numbers as well as a list of onCommitted listeners. + * + * When you call Persistence.runTransaction(), it will create a transaction and + * pass it to your callback. You then pass it to any method that operates + * on persistence. + */ class PersistenceTransaction { + constructor() { + this.onCommittedListeners = []; + } + addOnCommittedListener(e) { + this.onCommittedListeners.push(e); + } + raiseOnCommittedEvent() { + this.onCommittedListeners.forEach((e => e())); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Verifies the error thrown by a LocalStore operation. If a LocalStore + * operation fails because the primary lease has been taken by another client, + * we ignore the error (the persistence layer will immediately call + * `applyPrimaryLease` to propagate the primary state change). All other errors + * are re-thrown. + * + * @param err - An error returned by a LocalStore operation. + * @returns A Promise that resolves after we recovered, or the original error. + */ async function __PRIVATE_ignoreIfPrimaryLeaseLoss(e) { + if (e.code !== N.FAILED_PRECONDITION || e.message !== K) throw e; + __PRIVATE_logDebug("LocalStore", "Unexpectedly lost primary lease"); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * PersistencePromise is essentially a re-implementation of Promise except + * it has a .next() method instead of .then() and .next() and .catch() callbacks + * are executed synchronously when a PersistencePromise resolves rather than + * asynchronously (Promise implementations use setImmediate() or similar). + * + * This is necessary to interoperate with IndexedDB which will automatically + * commit transactions if control is returned to the event loop without + * synchronously initiating another operation on the transaction. + * + * NOTE: .then() and .catch() only allow a single consumer, unlike normal + * Promises. + */ class PersistencePromise { + constructor(e) { + // NOTE: next/catchCallback will always point to our own wrapper functions, + // not the user's raw next() or catch() callbacks. + this.nextCallback = null, this.catchCallback = null, + // When the operation resolves, we'll set result or error and mark isDone. + this.result = void 0, this.error = void 0, this.isDone = !1, + // Set to true when .then() or .catch() are called and prevents additional + // chaining. + this.callbackAttached = !1, e((e => { + this.isDone = !0, this.result = e, this.nextCallback && + // value should be defined unless T is Void, but we can't express + // that in the type system. + this.nextCallback(e); + }), (e => { + this.isDone = !0, this.error = e, this.catchCallback && this.catchCallback(e); + })); + } + catch(e) { + return this.next(void 0, e); + } + next(e, t) { + return this.callbackAttached && fail(59440), this.callbackAttached = !0, this.isDone ? this.error ? this.wrapFailure(t, this.error) : this.wrapSuccess(e, this.result) : new PersistencePromise(((n, r) => { + this.nextCallback = t => { + this.wrapSuccess(e, t).next(n, r); + }, this.catchCallback = e => { + this.wrapFailure(t, e).next(n, r); + }; + })); + } + toPromise() { + return new Promise(((e, t) => { + this.next(e, t); + })); + } + wrapUserFunction(e) { + try { + const t = e(); + return t instanceof PersistencePromise ? t : PersistencePromise.resolve(t); + } catch (e) { + return PersistencePromise.reject(e); + } + } + wrapSuccess(e, t) { + return e ? this.wrapUserFunction((() => e(t))) : PersistencePromise.resolve(t); + } + wrapFailure(e, t) { + return e ? this.wrapUserFunction((() => e(t))) : PersistencePromise.reject(t); + } + static resolve(e) { + return new PersistencePromise(((t, n) => { + t(e); + })); + } + static reject(e) { + return new PersistencePromise(((t, n) => { + n(e); + })); + } + static waitFor( + // Accept all Promise types in waitFor(). + // eslint-disable-next-line @typescript-eslint/no-explicit-any + e) { + return new PersistencePromise(((t, n) => { + let r = 0, i = 0, s = !1; + e.forEach((e => { + ++r, e.next((() => { + ++i, s && i === r && t(); + }), (e => n(e))); + })), s = !0, i === r && t(); + })); + } + /** + * Given an array of predicate functions that asynchronously evaluate to a + * boolean, implements a short-circuiting `or` between the results. Predicates + * will be evaluated until one of them returns `true`, then stop. The final + * result will be whether any of them returned `true`. + */ static or(e) { + let t = PersistencePromise.resolve(!1); + for (const n of e) t = t.next((e => e ? PersistencePromise.resolve(e) : n())); + return t; + } + static forEach(e, t) { + const n = []; + return e.forEach(((e, r) => { + n.push(t.call(this, e, r)); + })), this.waitFor(n); + } + /** + * Concurrently map all array elements through asynchronous function. + */ static mapArray(e, t) { + return new PersistencePromise(((n, r) => { + const i = e.length, s = new Array(i); + let o = 0; + for (let _ = 0; _ < i; _++) { + const a = _; + t(e[a]).next((e => { + s[a] = e, ++o, o === i && n(s); + }), (e => r(e))); + } + })); + } + /** + * An alternative to recursive PersistencePromise calls, that avoids + * potential memory problems from unbounded chains of promises. + * + * The `action` will be called repeatedly while `condition` is true. + */ static doWhile(e, t) { + return new PersistencePromise(((n, r) => { + const process = () => { + !0 === e() ? t().next((() => { + process(); + }), r) : n(); + }; + process(); + })); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// References to `indexedDB` are guarded by SimpleDb.isAvailable() and getGlobal() +/* eslint-disable no-restricted-globals */ const W = "SimpleDb"; + +/** + * The maximum number of retry attempts for an IndexedDb transaction that fails + * with a DOMException. + */ +/** + * Wraps an IDBTransaction and exposes a store() method to get a handle to a + * specific object store. + */ +class __PRIVATE_SimpleDbTransaction { + static open(e, t, n, r) { + try { + return new __PRIVATE_SimpleDbTransaction(t, e.transaction(r, n)); + } catch (e) { + throw new __PRIVATE_IndexedDbTransactionError(t, e); + } + } + constructor(e, t) { + this.action = e, this.transaction = t, this.aborted = !1, + /** + * A `Promise` that resolves with the result of the IndexedDb transaction. + */ + this.S = new __PRIVATE_Deferred, this.transaction.oncomplete = () => { + this.S.resolve(); + }, this.transaction.onabort = () => { + t.error ? this.S.reject(new __PRIVATE_IndexedDbTransactionError(e, t.error)) : this.S.resolve(); + }, this.transaction.onerror = t => { + const n = __PRIVATE_checkForAndReportiOSError(t.target.error); + this.S.reject(new __PRIVATE_IndexedDbTransactionError(e, n)); + }; + } + get D() { + return this.S.promise; + } + abort(e) { + e && this.S.reject(e), this.aborted || (__PRIVATE_logDebug(W, "Aborting transaction:", e ? e.message : "Client-initiated abort"), + this.aborted = !0, this.transaction.abort()); + } + C() { + // If the browser supports V3 IndexedDB, we invoke commit() explicitly to + // speed up index DB processing if the event loop remains blocks. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const e = this.transaction; + this.aborted || "function" != typeof e.commit || e.commit(); + } + /** + * Returns a SimpleDbStore for the specified store. All + * operations performed on the SimpleDbStore happen within the context of this + * transaction and it cannot be used anymore once the transaction is + * completed. + * + * Note that we can't actually enforce that the KeyType and ValueType are + * correct, but they allow type safety through the rest of the consuming code. + */ store(e) { + const t = this.transaction.objectStore(e); + return new __PRIVATE_SimpleDbStore(t); + } +} + +/** + * Provides a wrapper around IndexedDb with a simplified interface that uses + * Promise-like return values to chain operations. Real promises cannot be used + * since .then() continuations are executed asynchronously (e.g. via + * .setImmediate), which would cause IndexedDB to end the transaction. + * See PersistencePromise for more details. + */ class __PRIVATE_SimpleDb { + /** Deletes the specified database. */ + static delete(e) { + __PRIVATE_logDebug(W, "Removing database:", e); + return __PRIVATE_wrapRequest(util.getGlobal().indexedDB.deleteDatabase(e)).toPromise(); + } + /** Returns true if IndexedDB is available in the current environment. */ static v() { + if (!util.isIndexedDBAvailable()) return !1; + if (__PRIVATE_SimpleDb.F()) return !0; + // We extensively use indexed array values and compound keys, + // which IE and Edge do not support. However, they still have indexedDB + // defined on the window, so we need to check for them here and make sure + // to return that persistence is not enabled for those browsers. + // For tracking support of this feature, see here: + // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/ + // Check the UA string to find out the browser. + const e = util.getUA(), t = __PRIVATE_SimpleDb.M(e), n = 0 < t && t < 10, r = __PRIVATE_getAndroidVersion(e), i = 0 < r && r < 4.5; + // IE 10 + // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)'; + // IE 11 + // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko'; + // Edge + // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, + // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0'; + // iOS Safari: Disable for users running iOS version < 10. + return !(e.indexOf("MSIE ") > 0 || e.indexOf("Trident/") > 0 || e.indexOf("Edge/") > 0 || n || i); + } + /** + * Returns true if the backing IndexedDB store is the Node IndexedDBShim + * (see https://github.com/axemclion/IndexedDBShim). + */ static F() { + return "undefined" != typeof process && "YES" === process.__PRIVATE_env?.__PRIVATE_USE_MOCK_PERSISTENCE; + } + /** Helper to get a typed SimpleDbStore from a transaction. */ static O(e, t) { + return e.store(t); + } + // visible for testing + /** Parse User Agent to determine iOS version. Returns -1 if not found. */ + static M(e) { + const t = e.match(/i(?:phone|pad|pod) os ([\d_]+)/i), n = t ? t[1].split("_").slice(0, 2).join(".") : "-1"; + return Number(n); + } + /* + * Creates a new SimpleDb wrapper for IndexedDb database `name`. + * + * Note that `version` must not be a downgrade. IndexedDB does not support + * downgrading the schema version. We currently do not support any way to do + * versioning outside of IndexedDB's versioning mechanism, as only + * version-upgrade transactions are allowed to do things like create + * objectstores. + */ constructor(e, t, n) { + this.name = e, this.version = t, this.N = n, this.B = null; + // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the + // bug we're checking for should exist in iOS >= 12.2 and < 13, but for + // whatever reason it's much harder to hit after 12.2 so we only proactively + // log on 12.2. + 12.2 === __PRIVATE_SimpleDb.M(util.getUA()) && __PRIVATE_logError("Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround."); + } + /** + * Opens the specified database, creating or upgrading it if necessary. + */ async L(e) { + return this.db || (__PRIVATE_logDebug(W, "Opening database:", this.name), this.db = await new Promise(((t, n) => { + // TODO(mikelehen): Investigate browser compatibility. + // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB + // suggests IE9 and older WebKit browsers handle upgrade + // differently. They expect setVersion, as described here: + // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion + const r = indexedDB.open(this.name, this.version); + r.onsuccess = e => { + const n = e.target.result; + t(n); + }, r.onblocked = () => { + n(new __PRIVATE_IndexedDbTransactionError(e, "Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed.")); + }, r.onerror = t => { + const r = t.target.error; + "VersionError" === r.name ? n(new FirestoreError(N.FAILED_PRECONDITION, "A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")) : "InvalidStateError" === r.name ? n(new FirestoreError(N.FAILED_PRECONDITION, "Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: " + r)) : n(new __PRIVATE_IndexedDbTransactionError(e, r)); + }, r.onupgradeneeded = e => { + __PRIVATE_logDebug(W, 'Database "' + this.name + '" requires upgrade from version:', e.oldVersion); + const t = e.target.result; + this.N.k(t, r.transaction, e.oldVersion, this.version).next((() => { + __PRIVATE_logDebug(W, "Database upgrade to version " + this.version + " complete"); + })); + }; + }))), this.q && (this.db.onversionchange = e => this.q(e)), this.db; + } + $(e) { + this.q = e, this.db && (this.db.onversionchange = t => e(t)); + } + async runTransaction(e, t, n, r) { + const i = "readonly" === t; + let s = 0; + for (;;) { + ++s; + try { + this.db = await this.L(e); + const t = __PRIVATE_SimpleDbTransaction.open(this.db, e, i ? "readonly" : "readwrite", n), s = r(t).next((e => (t.C(), + e))).catch((e => ( + // Abort the transaction if there was an error. + t.abort(e), PersistencePromise.reject(e)))).toPromise(); + // As noted above, errors are propagated by aborting the transaction. So + // we swallow any error here to avoid the browser logging it as unhandled. + return s.catch((() => {})), + // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to + // fire), but still return the original transactionFnResult back to the + // caller. + await t.D, s; + } catch (e) { + const t = e, n = "FirebaseError" !== t.name && s < 3; + // TODO(schmidt-sebastian): We could probably be smarter about this and + // not retry exceptions that are likely unrecoverable (such as quota + // exceeded errors). + // Note: We cannot use an instanceof check for FirestoreException, since the + // exception is wrapped in a generic error by our async/await handling. + if (__PRIVATE_logDebug(W, "Transaction failed with error:", t.message, "Retrying:", n), + this.close(), !n) return Promise.reject(t); + } + } + } + close() { + this.db && this.db.close(), this.db = void 0; + } +} + +/** Parse User Agent to determine Android version. Returns -1 if not found. */ function __PRIVATE_getAndroidVersion(e) { + const t = e.match(/Android ([\d.]+)/i), n = t ? t[1].split(".").slice(0, 2).join(".") : "-1"; + return Number(n); +} + +/** + * A controller for iterating over a key range or index. It allows an iterate + * callback to delete the currently-referenced object, or jump to a new key + * within the key range or index. + */ class __PRIVATE_IterationController { + constructor(e) { + this.U = e, this.K = !1, this.W = null; + } + get isDone() { + return this.K; + } + get G() { + return this.W; + } + set cursor(e) { + this.U = e; + } + /** + * This function can be called to stop iteration at any point. + */ done() { + this.K = !0; + } + /** + * This function can be called to skip to that next key, which could be + * an index or a primary key. + */ j(e) { + this.W = e; + } + /** + * Delete the current cursor value from the object store. + * + * NOTE: You CANNOT do this with a keysOnly query. + */ delete() { + return __PRIVATE_wrapRequest(this.U.delete()); + } +} + +/** An error that wraps exceptions that thrown during IndexedDB execution. */ class __PRIVATE_IndexedDbTransactionError extends FirestoreError { + constructor(e, t) { + super(N.UNAVAILABLE, `IndexedDB transaction '${e}' failed: ${t}`), this.name = "IndexedDbTransactionError"; + } +} + +/** Verifies whether `e` is an IndexedDbTransactionError. */ function __PRIVATE_isIndexedDbTransactionError(e) { + // Use name equality, as instanceof checks on errors don't work with errors + // that wrap other errors. + return "IndexedDbTransactionError" === e.name; +} + +/** + * A wrapper around an IDBObjectStore providing an API that: + * + * 1) Has generic KeyType / ValueType parameters to provide strongly-typed + * methods for acting against the object store. + * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every + * method return a PersistencePromise instead. + * 3) Provides a higher-level API to avoid needing to do excessive wrapping of + * intermediate IndexedDB types (IDBCursorWithValue, etc.) + */ class __PRIVATE_SimpleDbStore { + constructor(e) { + this.store = e; + } + put(e, t) { + let n; + return void 0 !== t ? (__PRIVATE_logDebug(W, "PUT", this.store.name, e, t), n = this.store.put(t, e)) : (__PRIVATE_logDebug(W, "PUT", this.store.name, "", e), + n = this.store.put(e)), __PRIVATE_wrapRequest(n); + } + /** + * Adds a new value into an Object Store and returns the new key. Similar to + * IndexedDb's `add()`, this method will fail on primary key collisions. + * + * @param value - The object to write. + * @returns The key of the value to add. + */ add(e) { + __PRIVATE_logDebug(W, "ADD", this.store.name, e, e); + return __PRIVATE_wrapRequest(this.store.add(e)); + } + /** + * Gets the object with the specified key from the specified store, or null + * if no object exists with the specified key. + * + * @key The key of the object to get. + * @returns The object with the specified key or null if no object exists. + */ get(e) { + // We're doing an unsafe cast to ValueType. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return __PRIVATE_wrapRequest(this.store.get(e)).next((t => ( + // Normalize nonexistence to null. + void 0 === t && (t = null), __PRIVATE_logDebug(W, "GET", this.store.name, e, t), + t))); + } + delete(e) { + __PRIVATE_logDebug(W, "DELETE", this.store.name, e); + return __PRIVATE_wrapRequest(this.store.delete(e)); + } + /** + * If we ever need more of the count variants, we can add overloads. For now, + * all we need is to count everything in a store. + * + * Returns the number of rows in the store. + */ count() { + __PRIVATE_logDebug(W, "COUNT", this.store.name); + return __PRIVATE_wrapRequest(this.store.count()); + } + J(e, t) { + const n = this.options(e, t), r = n.index ? this.store.index(n.index) : this.store; + // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly + // 20% faster. + if ("function" == typeof r.getAll) { + const e = r.getAll(n.range); + return new PersistencePromise(((t, n) => { + e.onerror = e => { + n(e.target.error); + }, e.onsuccess = e => { + t(e.target.result); + }; + })); + } + { + const e = this.cursor(n), t = []; + return this.H(e, ((e, n) => { + t.push(n); + })).next((() => t)); + } + } + /** + * Loads the first `count` elements from the provided index range. Loads all + * elements if no limit is provided. + */ Y(e, t) { + const n = this.store.getAll(e, null === t ? void 0 : t); + return new PersistencePromise(((e, t) => { + n.onerror = e => { + t(e.target.error); + }, n.onsuccess = t => { + e(t.target.result); + }; + })); + } + Z(e, t) { + __PRIVATE_logDebug(W, "DELETE ALL", this.store.name); + const n = this.options(e, t); + n.X = !1; + const r = this.cursor(n); + return this.H(r, ((e, t, n) => n.delete())); + } + ee(e, t) { + let n; + t ? n = e : (n = {}, t = e); + const r = this.cursor(n); + return this.H(r, t); + } + /** + * Iterates over a store, but waits for the given callback to complete for + * each entry before iterating the next entry. This allows the callback to do + * asynchronous work to determine if this iteration should continue. + * + * The provided callback should return `true` to continue iteration, and + * `false` otherwise. + */ te(e) { + const t = this.cursor({}); + return new PersistencePromise(((n, r) => { + t.onerror = e => { + const t = __PRIVATE_checkForAndReportiOSError(e.target.error); + r(t); + }, t.onsuccess = t => { + const r = t.target.result; + r ? e(r.primaryKey, r.value).next((e => { + e ? r.continue() : n(); + })) : n(); + }; + })); + } + H(e, t) { + const n = []; + return new PersistencePromise(((r, i) => { + e.onerror = e => { + i(e.target.error); + }, e.onsuccess = e => { + const i = e.target.result; + if (!i) return void r(); + const s = new __PRIVATE_IterationController(i), o = t(i.primaryKey, i.value, s); + if (o instanceof PersistencePromise) { + const e = o.catch((e => (s.done(), PersistencePromise.reject(e)))); + n.push(e); + } + s.isDone ? r() : null === s.G ? i.continue() : i.continue(s.G); + }; + })).next((() => PersistencePromise.waitFor(n))); + } + options(e, t) { + let n; + return void 0 !== e && ("string" == typeof e ? n = e : t = e), { + index: n, + range: t + }; + } + cursor(e) { + let t = "next"; + if (e.reverse && (t = "prev"), e.index) { + const n = this.store.index(e.index); + return e.X ? n.openKeyCursor(e.range, t) : n.openCursor(e.range, t); + } + return this.store.openCursor(e.range, t); + } +} + +/** + * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror + * handlers to resolve / reject the PersistencePromise as appropriate. + */ function __PRIVATE_wrapRequest(e) { + return new PersistencePromise(((t, n) => { + e.onsuccess = e => { + const n = e.target.result; + t(n); + }, e.onerror = e => { + const t = __PRIVATE_checkForAndReportiOSError(e.target.error); + n(t); + }; + })); +} + +// Guard so we only report the error once. +let G = !1; + +function __PRIVATE_checkForAndReportiOSError(e) { + const t = __PRIVATE_SimpleDb.M(util.getUA()); + if (t >= 12.2 && t < 13) { + const t = "An internal error was encountered in the Indexed Database server"; + if (e.message.indexOf(t) >= 0) { + // Wrap error in a more descriptive one. + const e = new FirestoreError("internal", `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${t}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`); + return G || (G = !0, + // Throw a global exception outside of this promise chain, for the user to + // potentially catch. + setTimeout((() => { + throw e; + }), 0)), e; + } + } + return e; +} + +const z = "IndexBackfiller"; + +/** How long we wait to try running index backfill after SDK initialization. */ +/** This class is responsible for the scheduling of Index Backfiller. */ +class __PRIVATE_IndexBackfillerScheduler { + constructor(e, t) { + this.asyncQueue = e, this.ne = t, this.task = null; + } + start() { + this.re(15e3); + } + stop() { + this.task && (this.task.cancel(), this.task = null); + } + get started() { + return null !== this.task; + } + re(e) { + __PRIVATE_logDebug(z, `Scheduled in ${e}ms`), this.task = this.asyncQueue.enqueueAfterDelay("index_backfill" /* TimerId.IndexBackfill */ , e, (async () => { + this.task = null; + try { + const e = await this.ne.ie(); + __PRIVATE_logDebug(z, `Documents written: ${e}`); + } catch (e) { + __PRIVATE_isIndexedDbTransactionError(e) ? __PRIVATE_logDebug(z, "Ignoring IndexedDB error during index backfill: ", e) : await __PRIVATE_ignoreIfPrimaryLeaseLoss(e); + } + await this.re(6e4); + })); + } +} + +/** Implements the steps for backfilling indexes. */ class __PRIVATE_IndexBackfiller { + constructor( + /** + * LocalStore provides access to IndexManager and LocalDocumentView. + * These properties will update when the user changes. Consequently, + * making a local copy of IndexManager and LocalDocumentView will require + * updates over time. The simpler solution is to rely on LocalStore to have + * an up-to-date references to IndexManager and LocalDocumentStore. + */ + e, t) { + this.localStore = e, this.persistence = t; + } + async ie(e = 50) { + return this.persistence.runTransaction("Backfill Indexes", "readwrite-primary", (t => this.se(t, e))); + } + /** Writes index entries until the cap is reached. Returns the number of documents processed. */ se(e, t) { + const n = new Set; + let r = t, i = !0; + return PersistencePromise.doWhile((() => !0 === i && r > 0), (() => this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next((t => { + if (null !== t && !n.has(t)) return __PRIVATE_logDebug(z, `Processing collection: ${t}`), + this.oe(e, t, r).next((e => { + r -= e, n.add(t); + })); + i = !1; + })))).next((() => t - r)); + } + /** + * Writes entries for the provided collection group. Returns the number of documents processed. + */ oe(e, t, n) { + // Use the earliest offset of all field indexes to query the local cache. + return this.localStore.indexManager.getMinOffsetFromCollectionGroup(e, t).next((r => this.localStore.localDocuments.getNextDocuments(e, t, r, n).next((n => { + const i = n.changes; + return this.localStore.indexManager.updateIndexEntries(e, i).next((() => this._e(r, n))).next((n => (__PRIVATE_logDebug(z, `Updating offset: ${n}`), + this.localStore.indexManager.updateCollectionGroup(e, t, n)))).next((() => i.size)); + })))); + } + /** Returns the next offset based on the provided documents. */ _e(e, t) { + let n = e; + return t.changes.forEach(((e, t) => { + const r = __PRIVATE_newIndexOffsetFromDocument(t); + __PRIVATE_indexOffsetComparator(r, n) > 0 && (n = r); + })), new IndexOffset(n.readTime, n.documentKey, Math.max(t.batchId, e.largestBatchId)); + } +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to + * exceed. All subsequent calls to next will return increasing values. If provided with a + * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as + * well as write out sequence numbers that it produces via `next()`. + */ class __PRIVATE_ListenSequence { + constructor(e, t) { + this.previousValue = e, t && (t.sequenceNumberHandler = e => this.ae(e), this.ue = e => t.writeSequenceNumber(e)); + } + ae(e) { + return this.previousValue = Math.max(e, this.previousValue), this.previousValue; + } + next() { + const e = ++this.previousValue; + return this.ue && this.ue(e), e; + } +} + +__PRIVATE_ListenSequence.ce = -1; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Sentinel value that sorts before any Mutation Batch ID. */ +const j = -1; + +/** + * Returns whether a variable is either undefined or null. + */ function __PRIVATE_isNullOrUndefined(e) { + return null == e; +} + +/** Returns whether the value represents -0. */ function __PRIVATE_isNegativeZero(e) { + // Detect if the value is -0.0. Based on polyfill from + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is + return 0 === e && 1 / e == -1 / 0; +} + +/** + * Returns whether a value is an integer and in the safe integer range + * @param value - The value to test for being an integer and in the safe range + */ function isSafeInteger(e) { + return "number" == typeof e && Number.isInteger(e) && !__PRIVATE_isNegativeZero(e) && e <= Number.MAX_SAFE_INTEGER && e >= Number.MIN_SAFE_INTEGER; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const J = ""; + +/** + * Encodes a resource path into a IndexedDb-compatible string form. + */ +function __PRIVATE_encodeResourcePath(e) { + let t = ""; + for (let n = 0; n < e.length; n++) t.length > 0 && (t = __PRIVATE_encodeSeparator(t)), + t = __PRIVATE_encodeSegment(e.get(n), t); + return __PRIVATE_encodeSeparator(t); +} + +/** Encodes a single segment of a resource path into the given result */ function __PRIVATE_encodeSegment(e, t) { + let n = t; + const r = e.length; + for (let t = 0; t < r; t++) { + const r = e.charAt(t); + switch (r) { + case "\0": + n += ""; + break; + + case J: + n += ""; + break; + + default: + n += r; + } + } + return n; +} + +/** Encodes a path separator into the given result */ function __PRIVATE_encodeSeparator(e) { + return e + J + ""; +} + +/** + * Decodes the given IndexedDb-compatible string form of a resource path into + * a ResourcePath instance. Note that this method is not suitable for use with + * decoding resource names from the server; those are One Platform format + * strings. + */ function __PRIVATE_decodeResourcePath(e) { + // Event the empty path must encode as a path of at least length 2. A path + // with exactly 2 must be the empty path. + const t = e.length; + if (__PRIVATE_hardAssert(t >= 2, 64408, { + path: e + }), 2 === t) return __PRIVATE_hardAssert(e.charAt(0) === J && "" === e.charAt(1), 56145, { + path: e + }), ResourcePath.emptyPath(); + // Escape characters cannot exist past the second-to-last position in the + // source value. + const __PRIVATE_lastReasonableEscapeIndex = t - 2, n = []; + let r = ""; + for (let i = 0; i < t; ) { + // The last two characters of a valid encoded path must be a separator, so + // there must be an end to this segment. + const t = e.indexOf(J, i); + (t < 0 || t > __PRIVATE_lastReasonableEscapeIndex) && fail(50515, { + path: e + }); + switch (e.charAt(t + 1)) { + case "": + const s = e.substring(i, t); + let o; + 0 === r.length ? + // Avoid copying for the common case of a segment that excludes \0 + // and \001 + o = s : (r += s, o = r, r = ""), n.push(o); + break; + + case "": + r += e.substring(i, t), r += "\0"; + break; + + case "": + // The escape character can be used in the output to encode itself. + r += e.substring(i, t + 1); + break; + + default: + fail(61167, { + path: e + }); + } + i = t + 2; + } + return new ResourcePath(n); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const H = "remoteDocuments", Y = "owner", Z = "owner", X = "mutationQueues", ee = "userId", te = "mutations", ne = "batchId", re = "userMutationsIndex", ie = [ "userId", "batchId" ]; + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Name of the IndexedDb object store. + * + * Note that the name 'owner' is chosen to ensure backwards compatibility with + * older clients that only supported single locked access to the persistence + * layer. + */ +/** + * Creates a [userId, encodedPath] key for use in the DbDocumentMutations + * index to iterate over all at document mutations for a given path or lower. + */ +function __PRIVATE_newDbDocumentMutationPrefixForPath(e, t) { + return [ e, __PRIVATE_encodeResourcePath(t) ]; +} + +/** + * Creates a full index key of [userId, encodedPath, batchId] for inserting + * and deleting into the DbDocumentMutations index. + */ function __PRIVATE_newDbDocumentMutationKey(e, t, n) { + return [ e, __PRIVATE_encodeResourcePath(t), n ]; +} + +/** + * Because we store all the useful information for this store in the key, + * there is no useful information to store as the value. The raw (unencoded) + * path cannot be stored because IndexedDb doesn't store prototype + * information. + */ const se = {}, oe = "documentMutations", _e = "remoteDocumentsV14", ae = [ "prefixPath", "collectionGroup", "readTime", "documentId" ], ue = "documentKeyIndex", ce = [ "prefixPath", "collectionGroup", "documentId" ], le = "collectionGroupIndex", he = [ "collectionGroup", "readTime", "prefixPath", "documentId" ], Pe = "remoteDocumentGlobal", Te = "remoteDocumentGlobalKey", Ie = "targets", Ee = "queryTargetsIndex", de = [ "canonicalId", "targetId" ], Ae = "targetDocuments", Re = [ "targetId", "path" ], Ve = "documentTargetsIndex", me = [ "path", "targetId" ], fe = "targetGlobalKey", ge = "targetGlobal", pe = "collectionParents", ye = [ "collectionId", "parent" ], we = "clientMetadata", Se = "clientId", be = "bundles", De = "bundleId", Ce = "namedQueries", ve = "name", Fe = "indexConfiguration", Me = "indexId", xe = "collectionGroupIndex", Oe = "collectionGroup", Ne = "indexState", Be = [ "indexId", "uid" ], Le = "sequenceNumberIndex", ke = [ "uid", "sequenceNumber" ], qe = "indexEntries", Qe = [ "indexId", "uid", "arrayValue", "directionalValue", "orderedDocumentKey", "documentKey" ], $e = "documentKeyIndex", Ue = [ "indexId", "uid", "orderedDocumentKey" ], Ke = "documentOverlays", We = [ "userId", "collectionPath", "documentId" ], Ge = "collectionPathOverlayIndex", ze = [ "userId", "collectionPath", "largestBatchId" ], je = "collectionGroupOverlayIndex", Je = [ "userId", "collectionGroup", "largestBatchId" ], He = "globals", Ye = "name", Ze = [ ...[ ...[ ...[ ...[ X, te, oe, H, Ie, Y, ge, Ae ], we ], Pe ], pe ], be, Ce ], Xe = [ ...Ze, Ke ], et = [ X, te, oe, _e, Ie, Y, ge, Ae, we, Pe, pe, be, Ce, Ke ], tt = et, nt = [ ...tt, Fe, Ne, qe ], rt = nt, it = [ ...nt, He ], st = it; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class __PRIVATE_IndexedDbTransaction extends PersistenceTransaction { + constructor(e, t) { + super(), this.le = e, this.currentSequenceNumber = t; + } +} + +function __PRIVATE_getStore(e, t) { + const n = __PRIVATE_debugCast(e); + return __PRIVATE_SimpleDb.O(n.le, t); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_objectSize(e) { + let t = 0; + for (const n in e) Object.prototype.hasOwnProperty.call(e, n) && t++; + return t; +} + +function forEach(e, t) { + for (const n in e) Object.prototype.hasOwnProperty.call(e, n) && t(n, e[n]); +} + +function __PRIVATE_mapToArray(e, t) { + const n = []; + for (const r in e) Object.prototype.hasOwnProperty.call(e, r) && n.push(t(e[r], r, e)); + return n; +} + +function isEmpty(e) { + for (const t in e) if (Object.prototype.hasOwnProperty.call(e, t)) return !1; + return !0; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// An immutable sorted map implementation, based on a Left-leaning Red-Black +// tree. +class SortedMap { + constructor(e, t) { + this.comparator = e, this.root = t || LLRBNode.EMPTY; + } + // Returns a copy of the map, with the specified key/value added or replaced. + insert(e, t) { + return new SortedMap(this.comparator, this.root.insert(e, t, this.comparator).copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns a copy of the map, with the specified key removed. + remove(e) { + return new SortedMap(this.comparator, this.root.remove(e, this.comparator).copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns the value of the node with the given key, or null. + get(e) { + let t = this.root; + for (;!t.isEmpty(); ) { + const n = this.comparator(e, t.key); + if (0 === n) return t.value; + n < 0 ? t = t.left : n > 0 && (t = t.right); + } + return null; + } + // Returns the index of the element in this sorted map, or -1 if it doesn't + // exist. + indexOf(e) { + // Number of nodes that were pruned when descending right + let t = 0, n = this.root; + for (;!n.isEmpty(); ) { + const r = this.comparator(e, n.key); + if (0 === r) return t + n.left.size; + r < 0 ? n = n.left : ( + // Count all nodes left of the node plus the node itself + t += n.left.size + 1, n = n.right); + } + // Node not found + return -1; + } + isEmpty() { + return this.root.isEmpty(); + } + // Returns the total number of nodes in the map. + get size() { + return this.root.size; + } + // Returns the minimum key in the map. + minKey() { + return this.root.minKey(); + } + // Returns the maximum key in the map. + maxKey() { + return this.root.maxKey(); + } + // Traverses the map in key order and calls the specified action function + // for each key/value pair. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(e) { + return this.root.inorderTraversal(e); + } + forEach(e) { + this.inorderTraversal(((t, n) => (e(t, n), !1))); + } + toString() { + const e = []; + return this.inorderTraversal(((t, n) => (e.push(`${t}:${n}`), !1))), `{${e.join(", ")}}`; + } + // Traverses the map in reverse key order and calls the specified action + // function for each key/value pair. If action returns true, traversal is + // aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(e) { + return this.root.reverseTraversal(e); + } + // Returns an iterator over the SortedMap. + getIterator() { + return new SortedMapIterator(this.root, null, this.comparator, !1); + } + getIteratorFrom(e) { + return new SortedMapIterator(this.root, e, this.comparator, !1); + } + getReverseIterator() { + return new SortedMapIterator(this.root, null, this.comparator, !0); + } + getReverseIteratorFrom(e) { + return new SortedMapIterator(this.root, e, this.comparator, !0); + } +} + + // end SortedMap +// An iterator over an LLRBNode. +class SortedMapIterator { + constructor(e, t, n, r) { + this.isReverse = r, this.nodeStack = []; + let i = 1; + for (;!e.isEmpty(); ) if (i = t ? n(e.key, t) : 1, + // flip the comparison if we're going in reverse + t && r && (i *= -1), i < 0) + // This node is less than our start key. ignore it + e = this.isReverse ? e.left : e.right; else { + if (0 === i) { + // This node is exactly equal to our start key. Push it on the stack, + // but stop iterating; + this.nodeStack.push(e); + break; + } + // This node is greater than our start key, add it to the stack and move + // to the next one + this.nodeStack.push(e), e = this.isReverse ? e.right : e.left; + } + } + getNext() { + let e = this.nodeStack.pop(); + const t = { + key: e.key, + value: e.value + }; + if (this.isReverse) for (e = e.left; !e.isEmpty(); ) this.nodeStack.push(e), e = e.right; else for (e = e.right; !e.isEmpty(); ) this.nodeStack.push(e), + e = e.left; + return t; + } + hasNext() { + return this.nodeStack.length > 0; + } + peek() { + if (0 === this.nodeStack.length) return null; + const e = this.nodeStack[this.nodeStack.length - 1]; + return { + key: e.key, + value: e.value + }; + } +} + + // end SortedMapIterator +// Represents a node in a Left-leaning Red-Black tree. +class LLRBNode { + constructor(e, t, n, r, i) { + this.key = e, this.value = t, this.color = null != n ? n : LLRBNode.RED, this.left = null != r ? r : LLRBNode.EMPTY, + this.right = null != i ? i : LLRBNode.EMPTY, this.size = this.left.size + 1 + this.right.size; + } + // Returns a copy of the current node, optionally replacing pieces of it. + copy(e, t, n, r, i) { + return new LLRBNode(null != e ? e : this.key, null != t ? t : this.value, null != n ? n : this.color, null != r ? r : this.left, null != i ? i : this.right); + } + isEmpty() { + return !1; + } + // Traverses the tree in key order and calls the specified action function + // for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(e) { + return this.left.inorderTraversal(e) || e(this.key, this.value) || this.right.inorderTraversal(e); + } + // Traverses the tree in reverse key order and calls the specified action + // function for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(e) { + return this.right.reverseTraversal(e) || e(this.key, this.value) || this.left.reverseTraversal(e); + } + // Returns the minimum node in the tree. + min() { + return this.left.isEmpty() ? this : this.left.min(); + } + // Returns the maximum key in the tree. + minKey() { + return this.min().key; + } + // Returns the maximum key in the tree. + maxKey() { + return this.right.isEmpty() ? this.key : this.right.maxKey(); + } + // Returns new tree, with the key/value added. + insert(e, t, n) { + let r = this; + const i = n(e, r.key); + return r = i < 0 ? r.copy(null, null, null, r.left.insert(e, t, n), null) : 0 === i ? r.copy(null, t, null, null, null) : r.copy(null, null, null, null, r.right.insert(e, t, n)), + r.fixUp(); + } + removeMin() { + if (this.left.isEmpty()) return LLRBNode.EMPTY; + let e = this; + return e.left.isRed() || e.left.left.isRed() || (e = e.moveRedLeft()), e = e.copy(null, null, null, e.left.removeMin(), null), + e.fixUp(); + } + // Returns new tree, with the specified item removed. + remove(e, t) { + let n, r = this; + if (t(e, r.key) < 0) r.left.isEmpty() || r.left.isRed() || r.left.left.isRed() || (r = r.moveRedLeft()), + r = r.copy(null, null, null, r.left.remove(e, t), null); else { + if (r.left.isRed() && (r = r.rotateRight()), r.right.isEmpty() || r.right.isRed() || r.right.left.isRed() || (r = r.moveRedRight()), + 0 === t(e, r.key)) { + if (r.right.isEmpty()) return LLRBNode.EMPTY; + n = r.right.min(), r = r.copy(n.key, n.value, null, null, r.right.removeMin()); + } + r = r.copy(null, null, null, null, r.right.remove(e, t)); + } + return r.fixUp(); + } + isRed() { + return this.color; + } + // Returns new tree after performing any needed rotations. + fixUp() { + let e = this; + return e.right.isRed() && !e.left.isRed() && (e = e.rotateLeft()), e.left.isRed() && e.left.left.isRed() && (e = e.rotateRight()), + e.left.isRed() && e.right.isRed() && (e = e.colorFlip()), e; + } + moveRedLeft() { + let e = this.colorFlip(); + return e.right.left.isRed() && (e = e.copy(null, null, null, null, e.right.rotateRight()), + e = e.rotateLeft(), e = e.colorFlip()), e; + } + moveRedRight() { + let e = this.colorFlip(); + return e.left.left.isRed() && (e = e.rotateRight(), e = e.colorFlip()), e; + } + rotateLeft() { + const e = this.copy(null, null, LLRBNode.RED, null, this.right.left); + return this.right.copy(null, null, this.color, e, null); + } + rotateRight() { + const e = this.copy(null, null, LLRBNode.RED, this.left.right, null); + return this.left.copy(null, null, this.color, null, e); + } + colorFlip() { + const e = this.left.copy(null, null, !this.left.color, null, null), t = this.right.copy(null, null, !this.right.color, null, null); + return this.copy(null, null, !this.color, e, t); + } + // For testing. + checkMaxDepth() { + const e = this.check(); + return Math.pow(2, e) <= this.size + 1; + } + // In a balanced RB tree, the black-depth (number of black nodes) from root to + // leaves is equal on both sides. This function verifies that or asserts. + check() { + if (this.isRed() && this.left.isRed()) throw fail(43730, { + key: this.key, + value: this.value + }); + if (this.right.isRed()) throw fail(14113, { + key: this.key, + value: this.value + }); + const e = this.left.check(); + if (e !== this.right.check()) throw fail(27949); + return e + (this.isRed() ? 0 : 1); + } +} + + // end LLRBNode +// Empty node is shared between all LLRB trees. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +LLRBNode.EMPTY = null, LLRBNode.RED = !0, LLRBNode.BLACK = !1; + +// end LLRBEmptyNode +LLRBNode.EMPTY = new +// Represents an empty node (a leaf node in the Red-Black Tree). +class LLRBEmptyNode { + constructor() { + this.size = 0; + } + get key() { + throw fail(57766); + } + get value() { + throw fail(16141); + } + get color() { + throw fail(16727); + } + get left() { + throw fail(29726); + } + get right() { + throw fail(36894); + } + // Returns a copy of the current node. + copy(e, t, n, r, i) { + return this; + } + // Returns a copy of the tree, with the specified key/value added. + insert(e, t, n) { + return new LLRBNode(e, t); + } + // Returns a copy of the tree, with the specified key removed. + remove(e, t) { + return this; + } + isEmpty() { + return !0; + } + inorderTraversal(e) { + return !1; + } + reverseTraversal(e) { + return !1; + } + minKey() { + return null; + } + maxKey() { + return null; + } + isRed() { + return !1; + } + // For testing. + checkMaxDepth() { + return !0; + } + check() { + return 0; + } +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * SortedSet is an immutable (copy-on-write) collection that holds elements + * in order specified by the provided comparator. + * + * NOTE: if provided comparator returns 0 for two elements, we consider them to + * be equal! + */ +class SortedSet { + constructor(e) { + this.comparator = e, this.data = new SortedMap(this.comparator); + } + has(e) { + return null !== this.data.get(e); + } + first() { + return this.data.minKey(); + } + last() { + return this.data.maxKey(); + } + get size() { + return this.data.size; + } + indexOf(e) { + return this.data.indexOf(e); + } + /** Iterates elements in order defined by "comparator" */ forEach(e) { + this.data.inorderTraversal(((t, n) => (e(t), !1))); + } + /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ forEachInRange(e, t) { + const n = this.data.getIteratorFrom(e[0]); + for (;n.hasNext(); ) { + const r = n.getNext(); + if (this.comparator(r.key, e[1]) >= 0) return; + t(r.key); + } + } + /** + * Iterates over `elem`s such that: start <= elem until false is returned. + */ forEachWhile(e, t) { + let n; + for (n = void 0 !== t ? this.data.getIteratorFrom(t) : this.data.getIterator(); n.hasNext(); ) { + if (!e(n.getNext().key)) return; + } + } + /** Finds the least element greater than or equal to `elem`. */ firstAfterOrEqual(e) { + const t = this.data.getIteratorFrom(e); + return t.hasNext() ? t.getNext().key : null; + } + getIterator() { + return new SortedSetIterator(this.data.getIterator()); + } + getIteratorFrom(e) { + return new SortedSetIterator(this.data.getIteratorFrom(e)); + } + /** Inserts or updates an element */ add(e) { + return this.copy(this.data.remove(e).insert(e, !0)); + } + /** Deletes an element */ delete(e) { + return this.has(e) ? this.copy(this.data.remove(e)) : this; + } + isEmpty() { + return this.data.isEmpty(); + } + unionWith(e) { + let t = this; + // Make sure `result` always refers to the larger one of the two sets. + return t.size < e.size && (t = e, e = this), e.forEach((e => { + t = t.add(e); + })), t; + } + isEqual(e) { + if (!(e instanceof SortedSet)) return !1; + if (this.size !== e.size) return !1; + const t = this.data.getIterator(), n = e.data.getIterator(); + for (;t.hasNext(); ) { + const e = t.getNext().key, r = n.getNext().key; + if (0 !== this.comparator(e, r)) return !1; + } + return !0; + } + toArray() { + const e = []; + return this.forEach((t => { + e.push(t); + })), e; + } + toString() { + const e = []; + return this.forEach((t => e.push(t))), "SortedSet(" + e.toString() + ")"; + } + copy(e) { + const t = new SortedSet(this.comparator); + return t.data = e, t; + } +} + +class SortedSetIterator { + constructor(e) { + this.iter = e; + } + getNext() { + return this.iter.getNext().key; + } + hasNext() { + return this.iter.hasNext(); + } +} + +/** + * Compares two sorted sets for equality using their natural ordering. The + * method computes the intersection and invokes `onAdd` for every element that + * is in `after` but not `before`. `onRemove` is invoked for every element in + * `before` but missing from `after`. + * + * The method creates a copy of both `before` and `after` and runs in O(n log + * n), where n is the size of the two lists. + * + * @param before - The elements that exist in the original set. + * @param after - The elements to diff against the original set. + * @param comparator - The comparator for the elements in before and after. + * @param onAdd - A function to invoke for every element that is part of ` + * after` but not `before`. + * @param onRemove - A function to invoke for every element that is part of + * `before` but not `after`. + */ +/** + * Returns the next element from the iterator or `undefined` if none available. + */ +function __PRIVATE_advanceIterator(e) { + return e.hasNext() ? e.getNext() : void 0; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provides a set of fields that can be used to partially patch a document. + * FieldMask is used in conjunction with ObjectValue. + * Examples: + * foo - Overwrites foo entirely with the provided value. If foo is not + * present in the companion ObjectValue, the field is deleted. + * foo.bar - Overwrites only the field bar of the object foo. + * If foo is not an object, foo is replaced with an object + * containing foo + */ class FieldMask { + constructor(e) { + this.fields = e, + // TODO(dimond): validation of FieldMask + // Sort the field mask to support `FieldMask.isEqual()` and assert below. + e.sort(FieldPath$1.comparator); + } + static empty() { + return new FieldMask([]); + } + /** + * Returns a new FieldMask object that is the result of adding all the given + * fields paths to this field mask. + */ unionWith(e) { + let t = new SortedSet(FieldPath$1.comparator); + for (const e of this.fields) t = t.add(e); + for (const n of e) t = t.add(n); + return new FieldMask(t.toArray()); + } + /** + * Verifies that `fieldPath` is included by at least one field in this field + * mask. + * + * This is an O(n) operation, where `n` is the size of the field mask. + */ covers(e) { + for (const t of this.fields) if (t.isPrefixOf(e)) return !0; + return !1; + } + isEqual(e) { + return __PRIVATE_arrayEquals(this.fields, e.fields, ((e, t) => e.isEqual(t))); + } +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An error encountered while decoding base64 string. + */ class __PRIVATE_Base64DecodeError extends Error { + constructor() { + super(...arguments), this.name = "Base64DecodeError"; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Converts a Base64 encoded string to a binary string. */ +/** True if and only if the Base64 conversion functions are available. */ +function __PRIVATE_isBase64Available() { + return "undefined" != typeof atob; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Immutable class that represents a "proto" byte string. + * + * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when + * sent on the wire. This class abstracts away this differentiation by holding + * the proto byte string in a common class that must be converted into a string + * before being sent as a proto. + * @internal + */ class ByteString { + constructor(e) { + this.binaryString = e; + } + static fromBase64String(e) { + const t = function __PRIVATE_decodeBase64(e) { + try { + return atob(e); + } catch (e) { + // Check that `DOMException` is defined before using it to avoid + // "ReferenceError: Property 'DOMException' doesn't exist" in react-native. + // (https://github.com/firebase/firebase-js-sdk/issues/7115) + throw "undefined" != typeof DOMException && e instanceof DOMException ? new __PRIVATE_Base64DecodeError("Invalid base64 string: " + e) : e; + } + } + /** Converts a binary string to a Base64 encoded string. */ (e); + return new ByteString(t); + } + static fromUint8Array(e) { + // TODO(indexing); Remove the copy of the byte string here as this method + // is frequently called during indexing. + const t = + /** + * Helper function to convert an Uint8array to a binary string. + */ + function __PRIVATE_binaryStringFromUint8Array(e) { + let t = ""; + for (let n = 0; n < e.length; ++n) t += String.fromCharCode(e[n]); + return t; + } + /** + * Helper function to convert a binary string to an Uint8Array. + */ (e); + return new ByteString(t); + } + [Symbol.iterator]() { + let e = 0; + return { + next: () => e < this.binaryString.length ? { + value: this.binaryString.charCodeAt(e++), + done: !1 + } : { + value: void 0, + done: !0 + } + }; + } + toBase64() { + return function __PRIVATE_encodeBase64(e) { + return btoa(e); + }(this.binaryString); + } + toUint8Array() { + return function __PRIVATE_uint8ArrayFromBinaryString(e) { + const t = new Uint8Array(e.length); + for (let n = 0; n < e.length; n++) t[n] = e.charCodeAt(n); + return t; + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + // A RegExp matching ISO 8601 UTC timestamps with optional fraction. + (this.binaryString); + } + approximateByteSize() { + return 2 * this.binaryString.length; + } + compareTo(e) { + return __PRIVATE_primitiveComparator(this.binaryString, e.binaryString); + } + isEqual(e) { + return this.binaryString === e.binaryString; + } +} + +ByteString.EMPTY_BYTE_STRING = new ByteString(""); + +const ot = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/); + +/** + * Converts the possible Proto values for a timestamp value into a "seconds and + * nanos" representation. + */ function __PRIVATE_normalizeTimestamp(e) { + // The json interface (for the browser) will return an iso timestamp string, + // while the proto js library (for node) will return a + // google.protobuf.Timestamp instance. + if (__PRIVATE_hardAssert(!!e, 39018), "string" == typeof e) { + // The date string can have higher precision (nanos) than the Date class + // (millis), so we do some custom parsing here. + // Parse the nanos right out of the string. + let t = 0; + const n = ot.exec(e); + if (__PRIVATE_hardAssert(!!n, 46558, { + timestamp: e + }), n[1]) { + // Pad the fraction out to 9 digits (nanos). + let e = n[1]; + e = (e + "000000000").substr(0, 9), t = Number(e); + } + // Parse the date to get the seconds. + const r = new Date(e); + return { + seconds: Math.floor(r.getTime() / 1e3), + nanos: t + }; + } + return { + seconds: __PRIVATE_normalizeNumber(e.seconds), + nanos: __PRIVATE_normalizeNumber(e.nanos) + }; +} + +/** + * Converts the possible Proto types for numbers into a JavaScript number. + * Returns 0 if the value is not numeric. + */ function __PRIVATE_normalizeNumber(e) { + // TODO(bjornick): Handle int64 greater than 53 bits. + return "number" == typeof e ? e : "string" == typeof e ? Number(e) : 0; +} + +/** Converts the possible Proto types for Blobs into a ByteString. */ function __PRIVATE_normalizeByteString(e) { + return "string" == typeof e ? ByteString.fromBase64String(e) : ByteString.fromUint8Array(e); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a locally-applied ServerTimestamp. + * + * Server Timestamps are backed by MapValues that contain an internal field + * `__type__` with a value of `server_timestamp`. The previous value and local + * write time are stored in its `__previous_value__` and `__local_write_time__` + * fields respectively. + * + * Notes: + * - ServerTimestampValue instances are created as the result of applying a + * transform. They can only exist in the local view of a document. Therefore + * they do not need to be parsed or serialized. + * - When evaluated locally (e.g. for snapshot.data()), they by default + * evaluate to `null`. This behavior can be configured by passing custom + * FieldValueOptions to value(). + * - With respect to other ServerTimestampValues, they sort by their + * localWriteTime. + */ const _t = "server_timestamp", at = "__type__", ut = "__previous_value__", ct = "__local_write_time__"; + +function __PRIVATE_isServerTimestamp(e) { + const t = (e?.mapValue?.fields || {})[at]?.stringValue; + return t === _t; +} + +/** + * Creates a new ServerTimestamp proto value (using the internal format). + */ +/** + * Returns the value of the field before this ServerTimestamp was set. + * + * Preserving the previous values allows the user to display the last resoled + * value until the backend responds with the timestamp. + */ +function __PRIVATE_getPreviousValue(e) { + const t = e.mapValue.fields[ut]; + return __PRIVATE_isServerTimestamp(t) ? __PRIVATE_getPreviousValue(t) : t; +} + +/** + * Returns the local time at which this timestamp was first set. + */ function __PRIVATE_getLocalWriteTime(e) { + const t = __PRIVATE_normalizeTimestamp(e.mapValue.fields[ct].timestampValue); + return new Timestamp(t.seconds, t.nanos); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class DatabaseInfo { + /** + * Constructs a DatabaseInfo using the provided host, databaseId and + * persistenceKey. + * + * @param databaseId - The database to use. + * @param appId - The Firebase App Id. + * @param persistenceKey - A unique identifier for this Firestore's local + * storage (used in conjunction with the databaseId). + * @param host - The Firestore backend host to connect to. + * @param ssl - Whether to use SSL when connecting. + * @param forceLongPolling - Whether to use the forceLongPolling option + * when using WebChannel as the network transport. + * @param autoDetectLongPolling - Whether to use the detectBufferingProxy + * option when using WebChannel as the network transport. + * @param longPollingOptions Options that configure long-polling. + * @param useFetchStreams Whether to use the Fetch API instead of + * XMLHTTPRequest + */ + constructor(e, t, n, r, i, s, o, _, a, u) { + this.databaseId = e, this.appId = t, this.persistenceKey = n, this.host = r, this.ssl = i, + this.forceLongPolling = s, this.autoDetectLongPolling = o, this.longPollingOptions = _, + this.useFetchStreams = a, this.isUsingEmulator = u; + } +} + +/** The default database name for a project. */ const lt = "(default)"; + +/** + * Represents the database ID a Firestore client is associated with. + * @internal + */ class DatabaseId { + constructor(e, t) { + this.projectId = e, this.database = t || lt; + } + static empty() { + return new DatabaseId("", ""); + } + get isDefaultDatabase() { + return this.database === lt; + } + isEqual(e) { + return e instanceof DatabaseId && e.projectId === this.projectId && e.database === this.database; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const ht = "__type__", Pt = "__max__", Tt = { + mapValue: { + fields: { + __type__: { + stringValue: Pt + } + } + } +}, It = "__vector__", Et = "value", dt = { + nullValue: "NULL_VALUE" +}; + +/** Extracts the backend's type order for the provided value. */ +function __PRIVATE_typeOrder(e) { + return "nullValue" in e ? 0 /* TypeOrder.NullValue */ : "booleanValue" in e ? 1 /* TypeOrder.BooleanValue */ : "integerValue" in e || "doubleValue" in e ? 2 /* TypeOrder.NumberValue */ : "timestampValue" in e ? 3 /* TypeOrder.TimestampValue */ : "stringValue" in e ? 5 /* TypeOrder.StringValue */ : "bytesValue" in e ? 6 /* TypeOrder.BlobValue */ : "referenceValue" in e ? 7 /* TypeOrder.RefValue */ : "geoPointValue" in e ? 8 /* TypeOrder.GeoPointValue */ : "arrayValue" in e ? 9 /* TypeOrder.ArrayValue */ : "mapValue" in e ? __PRIVATE_isServerTimestamp(e) ? 4 /* TypeOrder.ServerTimestampValue */ : __PRIVATE_isMaxValue(e) ? 9007199254740991 /* TypeOrder.MaxValue */ : __PRIVATE_isVectorValue(e) ? 10 /* TypeOrder.VectorValue */ : 11 /* TypeOrder.ObjectValue */ : fail(28295, { + value: e + }); +} + +/** Tests `left` and `right` for equality based on the backend semantics. */ function __PRIVATE_valueEquals(e, t) { + if (e === t) return !0; + const n = __PRIVATE_typeOrder(e); + if (n !== __PRIVATE_typeOrder(t)) return !1; + switch (n) { + case 0 /* TypeOrder.NullValue */ : + case 9007199254740991 /* TypeOrder.MaxValue */ : + return !0; + + case 1 /* TypeOrder.BooleanValue */ : + return e.booleanValue === t.booleanValue; + + case 4 /* TypeOrder.ServerTimestampValue */ : + return __PRIVATE_getLocalWriteTime(e).isEqual(__PRIVATE_getLocalWriteTime(t)); + + case 3 /* TypeOrder.TimestampValue */ : + return function __PRIVATE_timestampEquals(e, t) { + if ("string" == typeof e.timestampValue && "string" == typeof t.timestampValue && e.timestampValue.length === t.timestampValue.length) + // Use string equality for ISO 8601 timestamps + return e.timestampValue === t.timestampValue; + const n = __PRIVATE_normalizeTimestamp(e.timestampValue), r = __PRIVATE_normalizeTimestamp(t.timestampValue); + return n.seconds === r.seconds && n.nanos === r.nanos; + }(e, t); + + case 5 /* TypeOrder.StringValue */ : + return e.stringValue === t.stringValue; + + case 6 /* TypeOrder.BlobValue */ : + return function __PRIVATE_blobEquals(e, t) { + return __PRIVATE_normalizeByteString(e.bytesValue).isEqual(__PRIVATE_normalizeByteString(t.bytesValue)); + }(e, t); + + case 7 /* TypeOrder.RefValue */ : + return e.referenceValue === t.referenceValue; + + case 8 /* TypeOrder.GeoPointValue */ : + return function __PRIVATE_geoPointEquals(e, t) { + return __PRIVATE_normalizeNumber(e.geoPointValue.latitude) === __PRIVATE_normalizeNumber(t.geoPointValue.latitude) && __PRIVATE_normalizeNumber(e.geoPointValue.longitude) === __PRIVATE_normalizeNumber(t.geoPointValue.longitude); + }(e, t); + + case 2 /* TypeOrder.NumberValue */ : + return function __PRIVATE_numberEquals(e, t) { + if ("integerValue" in e && "integerValue" in t) return __PRIVATE_normalizeNumber(e.integerValue) === __PRIVATE_normalizeNumber(t.integerValue); + if ("doubleValue" in e && "doubleValue" in t) { + const n = __PRIVATE_normalizeNumber(e.doubleValue), r = __PRIVATE_normalizeNumber(t.doubleValue); + return n === r ? __PRIVATE_isNegativeZero(n) === __PRIVATE_isNegativeZero(r) : isNaN(n) && isNaN(r); + } + return !1; + }(e, t); + + case 9 /* TypeOrder.ArrayValue */ : + return __PRIVATE_arrayEquals(e.arrayValue.values || [], t.arrayValue.values || [], __PRIVATE_valueEquals); + + case 10 /* TypeOrder.VectorValue */ : + case 11 /* TypeOrder.ObjectValue */ : + return function __PRIVATE_objectEquals(e, t) { + const n = e.mapValue.fields || {}, r = t.mapValue.fields || {}; + if (__PRIVATE_objectSize(n) !== __PRIVATE_objectSize(r)) return !1; + for (const e in n) if (n.hasOwnProperty(e) && (void 0 === r[e] || !__PRIVATE_valueEquals(n[e], r[e]))) return !1; + return !0; + } + /** Returns true if the ArrayValue contains the specified element. */ (e, t); + + default: + return fail(52216, { + left: e + }); + } +} + +function __PRIVATE_arrayValueContains(e, t) { + return void 0 !== (e.values || []).find((e => __PRIVATE_valueEquals(e, t))); +} + +function __PRIVATE_valueCompare(e, t) { + if (e === t) return 0; + const n = __PRIVATE_typeOrder(e), r = __PRIVATE_typeOrder(t); + if (n !== r) return __PRIVATE_primitiveComparator(n, r); + switch (n) { + case 0 /* TypeOrder.NullValue */ : + case 9007199254740991 /* TypeOrder.MaxValue */ : + return 0; + + case 1 /* TypeOrder.BooleanValue */ : + return __PRIVATE_primitiveComparator(e.booleanValue, t.booleanValue); + + case 2 /* TypeOrder.NumberValue */ : + return function __PRIVATE_compareNumbers(e, t) { + const n = __PRIVATE_normalizeNumber(e.integerValue || e.doubleValue), r = __PRIVATE_normalizeNumber(t.integerValue || t.doubleValue); + return n < r ? -1 : n > r ? 1 : n === r ? 0 : + // one or both are NaN. + isNaN(n) ? isNaN(r) ? 0 : -1 : 1; + }(e, t); + + case 3 /* TypeOrder.TimestampValue */ : + return __PRIVATE_compareTimestamps(e.timestampValue, t.timestampValue); + + case 4 /* TypeOrder.ServerTimestampValue */ : + return __PRIVATE_compareTimestamps(__PRIVATE_getLocalWriteTime(e), __PRIVATE_getLocalWriteTime(t)); + + case 5 /* TypeOrder.StringValue */ : + return __PRIVATE_compareUtf8Strings(e.stringValue, t.stringValue); + + case 6 /* TypeOrder.BlobValue */ : + return function __PRIVATE_compareBlobs(e, t) { + const n = __PRIVATE_normalizeByteString(e), r = __PRIVATE_normalizeByteString(t); + return n.compareTo(r); + }(e.bytesValue, t.bytesValue); + + case 7 /* TypeOrder.RefValue */ : + return function __PRIVATE_compareReferences(e, t) { + const n = e.split("/"), r = t.split("/"); + for (let e = 0; e < n.length && e < r.length; e++) { + const t = __PRIVATE_primitiveComparator(n[e], r[e]); + if (0 !== t) return t; + } + return __PRIVATE_primitiveComparator(n.length, r.length); + }(e.referenceValue, t.referenceValue); + + case 8 /* TypeOrder.GeoPointValue */ : + return function __PRIVATE_compareGeoPoints(e, t) { + const n = __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(e.latitude), __PRIVATE_normalizeNumber(t.latitude)); + if (0 !== n) return n; + return __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(e.longitude), __PRIVATE_normalizeNumber(t.longitude)); + }(e.geoPointValue, t.geoPointValue); + + case 9 /* TypeOrder.ArrayValue */ : + return __PRIVATE_compareArrays(e.arrayValue, t.arrayValue); + + case 10 /* TypeOrder.VectorValue */ : + return function __PRIVATE_compareVectors(e, t) { + const n = e.fields || {}, r = t.fields || {}, i = n[Et]?.arrayValue, s = r[Et]?.arrayValue, o = __PRIVATE_primitiveComparator(i?.values?.length || 0, s?.values?.length || 0); + if (0 !== o) return o; + return __PRIVATE_compareArrays(i, s); + }(e.mapValue, t.mapValue); + + case 11 /* TypeOrder.ObjectValue */ : + return function __PRIVATE_compareMaps(e, t) { + if (e === Tt.mapValue && t === Tt.mapValue) return 0; + if (e === Tt.mapValue) return 1; + if (t === Tt.mapValue) return -1; + const n = e.fields || {}, r = Object.keys(n), i = t.fields || {}, s = Object.keys(i); + // Even though MapValues are likely sorted correctly based on their insertion + // order (e.g. when received from the backend), local modifications can bring + // elements out of order. We need to re-sort the elements to ensure that + // canonical IDs are independent of insertion order. + r.sort(), s.sort(); + for (let e = 0; e < r.length && e < s.length; ++e) { + const t = __PRIVATE_compareUtf8Strings(r[e], s[e]); + if (0 !== t) return t; + const o = __PRIVATE_valueCompare(n[r[e]], i[s[e]]); + if (0 !== o) return o; + } + return __PRIVATE_primitiveComparator(r.length, s.length); + } + /** + * Generates the canonical ID for the provided field value (as used in Target + * serialization). + */ (e.mapValue, t.mapValue); + + default: + throw fail(23264, { + he: n + }); + } +} + +function __PRIVATE_compareTimestamps(e, t) { + if ("string" == typeof e && "string" == typeof t && e.length === t.length) return __PRIVATE_primitiveComparator(e, t); + const n = __PRIVATE_normalizeTimestamp(e), r = __PRIVATE_normalizeTimestamp(t), i = __PRIVATE_primitiveComparator(n.seconds, r.seconds); + return 0 !== i ? i : __PRIVATE_primitiveComparator(n.nanos, r.nanos); +} + +function __PRIVATE_compareArrays(e, t) { + const n = e.values || [], r = t.values || []; + for (let e = 0; e < n.length && e < r.length; ++e) { + const t = __PRIVATE_valueCompare(n[e], r[e]); + if (t) return t; + } + return __PRIVATE_primitiveComparator(n.length, r.length); +} + +function canonicalId(e) { + return __PRIVATE_canonifyValue(e); +} + +function __PRIVATE_canonifyValue(e) { + return "nullValue" in e ? "null" : "booleanValue" in e ? "" + e.booleanValue : "integerValue" in e ? "" + e.integerValue : "doubleValue" in e ? "" + e.doubleValue : "timestampValue" in e ? function __PRIVATE_canonifyTimestamp(e) { + const t = __PRIVATE_normalizeTimestamp(e); + return `time(${t.seconds},${t.nanos})`; + }(e.timestampValue) : "stringValue" in e ? e.stringValue : "bytesValue" in e ? function __PRIVATE_canonifyByteString(e) { + return __PRIVATE_normalizeByteString(e).toBase64(); + }(e.bytesValue) : "referenceValue" in e ? function __PRIVATE_canonifyReference(e) { + return DocumentKey.fromName(e).toString(); + }(e.referenceValue) : "geoPointValue" in e ? function __PRIVATE_canonifyGeoPoint(e) { + return `geo(${e.latitude},${e.longitude})`; + }(e.geoPointValue) : "arrayValue" in e ? function __PRIVATE_canonifyArray(e) { + let t = "[", n = !0; + for (const r of e.values || []) n ? n = !1 : t += ",", t += __PRIVATE_canonifyValue(r); + return t + "]"; + } + /** + * Returns an approximate (and wildly inaccurate) in-memory size for the field + * value. + * + * The memory size takes into account only the actual user data as it resides + * in memory and ignores object overhead. + */ (e.arrayValue) : "mapValue" in e ? function __PRIVATE_canonifyMap(e) { + // Iteration order in JavaScript is not guaranteed. To ensure that we generate + // matching canonical IDs for identical maps, we need to sort the keys. + const t = Object.keys(e.fields || {}).sort(); + let n = "{", r = !0; + for (const i of t) r ? r = !1 : n += ",", n += `${i}:${__PRIVATE_canonifyValue(e.fields[i])}`; + return n + "}"; + }(e.mapValue) : fail(61005, { + value: e + }); +} + +function __PRIVATE_estimateByteSize(e) { + switch (__PRIVATE_typeOrder(e)) { + case 0 /* TypeOrder.NullValue */ : + case 1 /* TypeOrder.BooleanValue */ : + return 4; + + case 2 /* TypeOrder.NumberValue */ : + return 8; + + case 3 /* TypeOrder.TimestampValue */ : + case 8 /* TypeOrder.GeoPointValue */ : + // GeoPoints are made up of two distinct numbers (latitude + longitude) + return 16; + + case 4 /* TypeOrder.ServerTimestampValue */ : + const t = __PRIVATE_getPreviousValue(e); + return t ? 16 + __PRIVATE_estimateByteSize(t) : 16; + + case 5 /* TypeOrder.StringValue */ : + // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures: + // "JavaScript's String type is [...] a set of elements of 16-bit unsigned + // integer values" + return 2 * e.stringValue.length; + + case 6 /* TypeOrder.BlobValue */ : + return __PRIVATE_normalizeByteString(e.bytesValue).approximateByteSize(); + + case 7 /* TypeOrder.RefValue */ : + return e.referenceValue.length; + + case 9 /* TypeOrder.ArrayValue */ : + return function __PRIVATE_estimateArrayByteSize(e) { + return (e.values || []).reduce(((e, t) => e + __PRIVATE_estimateByteSize(t)), 0); + } + /** Returns a reference value for the provided database and key. */ (e.arrayValue); + + case 10 /* TypeOrder.VectorValue */ : + case 11 /* TypeOrder.ObjectValue */ : + return function __PRIVATE_estimateMapByteSize(e) { + let t = 0; + return forEach(e.fields, ((e, n) => { + t += e.length + __PRIVATE_estimateByteSize(n); + })), t; + }(e.mapValue); + + default: + throw fail(13486, { + value: e + }); + } +} + +function __PRIVATE_refValue(e, t) { + return { + referenceValue: `projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}` + }; +} + +/** Returns true if `value` is an IntegerValue . */ function isInteger(e) { + return !!e && "integerValue" in e; +} + +/** Returns true if `value` is a DoubleValue. */ +/** Returns true if `value` is an ArrayValue. */ +function isArray(e) { + return !!e && "arrayValue" in e; +} + +/** Returns true if `value` is a NullValue. */ function __PRIVATE_isNullValue(e) { + return !!e && "nullValue" in e; +} + +/** Returns true if `value` is NaN. */ function __PRIVATE_isNanValue(e) { + return !!e && "doubleValue" in e && isNaN(Number(e.doubleValue)); +} + +/** Returns true if `value` is a MapValue. */ function __PRIVATE_isMapValue(e) { + return !!e && "mapValue" in e; +} + +/** Returns true if `value` is a VetorValue. */ function __PRIVATE_isVectorValue(e) { + const t = (e?.mapValue?.fields || {})[ht]?.stringValue; + return t === It; +} + +/** Creates a deep copy of `source`. */ function __PRIVATE_deepClone(e) { + if (e.geoPointValue) return { + geoPointValue: { + ...e.geoPointValue + } + }; + if (e.timestampValue && "object" == typeof e.timestampValue) return { + timestampValue: { + ...e.timestampValue + } + }; + if (e.mapValue) { + const t = { + mapValue: { + fields: {} + } + }; + return forEach(e.mapValue.fields, ((e, n) => t.mapValue.fields[e] = __PRIVATE_deepClone(n))), + t; + } + if (e.arrayValue) { + const t = { + arrayValue: { + values: [] + } + }; + for (let n = 0; n < (e.arrayValue.values || []).length; ++n) t.arrayValue.values[n] = __PRIVATE_deepClone(e.arrayValue.values[n]); + return t; + } + return { + ...e + }; +} + +/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ function __PRIVATE_isMaxValue(e) { + return (((e.mapValue || {}).fields || {}).__type__ || {}).stringValue === Pt; +} + +const At = { + mapValue: { + fields: { + [ht]: { + stringValue: It + }, + [Et]: { + arrayValue: {} + } + } + } +}; + +/** Returns the lowest value for the given value type (inclusive). */ function __PRIVATE_valuesGetLowerBound(e) { + return "nullValue" in e ? dt : "booleanValue" in e ? { + booleanValue: !1 + } : "integerValue" in e || "doubleValue" in e ? { + doubleValue: NaN + } : "timestampValue" in e ? { + timestampValue: { + seconds: Number.MIN_SAFE_INTEGER + } + } : "stringValue" in e ? { + stringValue: "" + } : "bytesValue" in e ? { + bytesValue: "" + } : "referenceValue" in e ? __PRIVATE_refValue(DatabaseId.empty(), DocumentKey.empty()) : "geoPointValue" in e ? { + geoPointValue: { + latitude: -90, + longitude: -180 + } + } : "arrayValue" in e ? { + arrayValue: {} + } : "mapValue" in e ? __PRIVATE_isVectorValue(e) ? At : { + mapValue: {} + } : fail(35942, { + value: e + }); +} + +/** Returns the largest value for the given value type (exclusive). */ function __PRIVATE_valuesGetUpperBound(e) { + return "nullValue" in e ? { + booleanValue: !1 + } : "booleanValue" in e ? { + doubleValue: NaN + } : "integerValue" in e || "doubleValue" in e ? { + timestampValue: { + seconds: Number.MIN_SAFE_INTEGER + } + } : "timestampValue" in e ? { + stringValue: "" + } : "stringValue" in e ? { + bytesValue: "" + } : "bytesValue" in e ? __PRIVATE_refValue(DatabaseId.empty(), DocumentKey.empty()) : "referenceValue" in e ? { + geoPointValue: { + latitude: -90, + longitude: -180 + } + } : "geoPointValue" in e ? { + arrayValue: {} + } : "arrayValue" in e ? At : "mapValue" in e ? __PRIVATE_isVectorValue(e) ? { + mapValue: {} + } : Tt : fail(61959, { + value: e + }); +} + +function __PRIVATE_lowerBoundCompare(e, t) { + const n = __PRIVATE_valueCompare(e.value, t.value); + return 0 !== n ? n : e.inclusive && !t.inclusive ? -1 : !e.inclusive && t.inclusive ? 1 : 0; +} + +function __PRIVATE_upperBoundCompare(e, t) { + const n = __PRIVATE_valueCompare(e.value, t.value); + return 0 !== n ? n : e.inclusive && !t.inclusive ? 1 : !e.inclusive && t.inclusive ? -1 : 0; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An ObjectValue represents a MapValue in the Firestore Proto and offers the + * ability to add and remove fields (via the ObjectValueBuilder). + */ class ObjectValue { + constructor(e) { + this.value = e; + } + static empty() { + return new ObjectValue({ + mapValue: {} + }); + } + /** + * Returns the value at the given path or null. + * + * @param path - the path to search + * @returns The value at the path or null if the path is not set. + */ field(e) { + if (e.isEmpty()) return this.value; + { + let t = this.value; + for (let n = 0; n < e.length - 1; ++n) if (t = (t.mapValue.fields || {})[e.get(n)], + !__PRIVATE_isMapValue(t)) return null; + return t = (t.mapValue.fields || {})[e.lastSegment()], t || null; + } + } + /** + * Sets the field to the provided value. + * + * @param path - The field path to set. + * @param value - The value to set. + */ set(e, t) { + this.getFieldsMap(e.popLast())[e.lastSegment()] = __PRIVATE_deepClone(t); + } + /** + * Sets the provided fields to the provided values. + * + * @param data - A map of fields to values (or null for deletes). + */ setAll(e) { + let t = FieldPath$1.emptyPath(), n = {}, r = []; + e.forEach(((e, i) => { + if (!t.isImmediateParentOf(i)) { + // Insert the accumulated changes at this parent location + const e = this.getFieldsMap(t); + this.applyChanges(e, n, r), n = {}, r = [], t = i.popLast(); + } + e ? n[i.lastSegment()] = __PRIVATE_deepClone(e) : r.push(i.lastSegment()); + })); + const i = this.getFieldsMap(t); + this.applyChanges(i, n, r); + } + /** + * Removes the field at the specified path. If there is no field at the + * specified path, nothing is changed. + * + * @param path - The field path to remove. + */ delete(e) { + const t = this.field(e.popLast()); + __PRIVATE_isMapValue(t) && t.mapValue.fields && delete t.mapValue.fields[e.lastSegment()]; + } + isEqual(e) { + return __PRIVATE_valueEquals(this.value, e.value); + } + /** + * Returns the map that contains the leaf element of `path`. If the parent + * entry does not yet exist, or if it is not a map, a new map will be created. + */ getFieldsMap(e) { + let t = this.value; + t.mapValue.fields || (t.mapValue = { + fields: {} + }); + for (let n = 0; n < e.length; ++n) { + let r = t.mapValue.fields[e.get(n)]; + __PRIVATE_isMapValue(r) && r.mapValue.fields || (r = { + mapValue: { + fields: {} + } + }, t.mapValue.fields[e.get(n)] = r), t = r; + } + return t.mapValue.fields; + } + /** + * Modifies `fieldsMap` by adding, replacing or deleting the specified + * entries. + */ applyChanges(e, t, n) { + forEach(t, ((t, n) => e[t] = n)); + for (const t of n) delete e[t]; + } + clone() { + return new ObjectValue(__PRIVATE_deepClone(this.value)); + } +} + +/** + * Returns a FieldMask built from all fields in a MapValue. + */ function __PRIVATE_extractFieldMask(e) { + const t = []; + return forEach(e.fields, ((e, n) => { + const r = new FieldPath$1([ e ]); + if (__PRIVATE_isMapValue(n)) { + const e = __PRIVATE_extractFieldMask(n.mapValue).fields; + if (0 === e.length) + // Preserve the empty map by adding it to the FieldMask. + t.push(r); else + // For nested and non-empty ObjectValues, add the FieldPath of the + // leaf nodes. + for (const n of e) t.push(r.child(n)); + } else + // For nested and non-empty ObjectValues, add the FieldPath of the leaf + // nodes. + t.push(r); + })), new FieldMask(t); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a document in Firestore with a key, version, data and whether it + * has local mutations applied to it. + * + * Documents can transition between states via `convertToFoundDocument()`, + * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does + * not transition to one of these states even after all mutations have been + * applied, `isValidDocument()` returns false and the document should be removed + * from all views. + */ class MutableDocument { + constructor(e, t, n, r, i, s, o) { + this.key = e, this.documentType = t, this.version = n, this.readTime = r, this.createTime = i, + this.data = s, this.documentState = o; + } + /** + * Creates a document with no known version or data, but which can serve as + * base document for mutations. + */ static newInvalidDocument(e) { + return new MutableDocument(e, 0 /* DocumentType.INVALID */ , + /* version */ SnapshotVersion.min(), + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist with the given data at the + * given version. + */ static newFoundDocument(e, t, n, r) { + return new MutableDocument(e, 1 /* DocumentType.FOUND_DOCUMENT */ , + /* version */ t, + /* readTime */ SnapshotVersion.min(), + /* createTime */ n, r, 0 /* DocumentState.SYNCED */); + } + /** Creates a new document that is known to not exist at the given version. */ static newNoDocument(e, t) { + return new MutableDocument(e, 2 /* DocumentType.NO_DOCUMENT */ , + /* version */ t, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist at the given version but + * whose data is not known (e.g. a document that was updated without a known + * base document). + */ static newUnknownDocument(e, t) { + return new MutableDocument(e, 3 /* DocumentType.UNKNOWN_DOCUMENT */ , + /* version */ t, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */); + } + /** + * Changes the document type to indicate that it exists and that its version + * and data are known. + */ convertToFoundDocument(e, t) { + // If a document is switching state from being an invalid or deleted + // document to a valid (FOUND_DOCUMENT) document, either due to receiving an + // update from Watch or due to applying a local set mutation on top + // of a deleted document, our best guess about its createTime would be the + // version at which the document transitioned to a FOUND_DOCUMENT. + return !this.createTime.isEqual(SnapshotVersion.min()) || 2 /* DocumentType.NO_DOCUMENT */ !== this.documentType && 0 /* DocumentType.INVALID */ !== this.documentType || (this.createTime = e), + this.version = e, this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */ , this.data = t, + this.documentState = 0 /* DocumentState.SYNCED */ , this; + } + /** + * Changes the document type to indicate that it doesn't exist at the given + * version. + */ convertToNoDocument(e) { + return this.version = e, this.documentType = 2 /* DocumentType.NO_DOCUMENT */ , + this.data = ObjectValue.empty(), this.documentState = 0 /* DocumentState.SYNCED */ , + this; + } + /** + * Changes the document type to indicate that it exists at a given version but + * that its data is not known (e.g. a document that was updated without a known + * base document). + */ convertToUnknownDocument(e) { + return this.version = e, this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */ , + this.data = ObjectValue.empty(), this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , + this; + } + setHasCommittedMutations() { + return this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , this; + } + setHasLocalMutations() { + return this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ , this.version = SnapshotVersion.min(), + this; + } + setReadTime(e) { + return this.readTime = e, this; + } + get hasLocalMutations() { + return 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ === this.documentState; + } + get hasCommittedMutations() { + return 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ === this.documentState; + } + get hasPendingWrites() { + return this.hasLocalMutations || this.hasCommittedMutations; + } + isValidDocument() { + return 0 /* DocumentType.INVALID */ !== this.documentType; + } + isFoundDocument() { + return 1 /* DocumentType.FOUND_DOCUMENT */ === this.documentType; + } + isNoDocument() { + return 2 /* DocumentType.NO_DOCUMENT */ === this.documentType; + } + isUnknownDocument() { + return 3 /* DocumentType.UNKNOWN_DOCUMENT */ === this.documentType; + } + isEqual(e) { + return e instanceof MutableDocument && this.key.isEqual(e.key) && this.version.isEqual(e.version) && this.documentType === e.documentType && this.documentState === e.documentState && this.data.isEqual(e.data); + } + mutableCopy() { + return new MutableDocument(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState); + } + toString() { + return `Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`; + } +} + +/** + * Compares the value for field `field` in the provided documents. Throws if + * the field does not exist in both documents. + */ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a bound of a query. + * + * The bound is specified with the given components representing a position and + * whether it's just before or just after the position (relative to whatever the + * query order is). + * + * The position represents a logical index position for a query. It's a prefix + * of values for the (potentially implicit) order by clauses of a query. + * + * Bound provides a function to determine whether a document comes before or + * after a bound. This is influenced by whether the position is just before or + * just after the provided values. + */ +class Bound { + constructor(e, t) { + this.position = e, this.inclusive = t; + } +} + +function __PRIVATE_boundCompareToDocument(e, t, n) { + let r = 0; + for (let i = 0; i < e.position.length; i++) { + const s = t[i], o = e.position[i]; + if (s.field.isKeyField()) r = DocumentKey.comparator(DocumentKey.fromName(o.referenceValue), n.key); else { + r = __PRIVATE_valueCompare(o, n.data.field(s.field)); + } + if ("desc" /* Direction.DESCENDING */ === s.dir && (r *= -1), 0 !== r) break; + } + return r; +} + +/** + * Returns true if a document sorts after a bound using the provided sort + * order. + */ function __PRIVATE_boundEquals(e, t) { + if (null === e) return null === t; + if (null === t) return !1; + if (e.inclusive !== t.inclusive || e.position.length !== t.position.length) return !1; + for (let n = 0; n < e.position.length; n++) { + if (!__PRIVATE_valueEquals(e.position[n], t.position[n])) return !1; + } + return !0; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An ordering on a field, in some Direction. Direction defaults to ASCENDING. + */ class OrderBy { + constructor(e, t = "asc" /* Direction.ASCENDING */) { + this.field = e, this.dir = t; + } +} + +function __PRIVATE_orderByEquals(e, t) { + return e.dir === t.dir && e.field.isEqual(t.field); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class Filter {} + +class FieldFilter extends Filter { + constructor(e, t, n) { + super(), this.field = e, this.op = t, this.value = n; + } + /** + * Creates a filter based on the provided arguments. + */ static create(e, t, n) { + return e.isKeyField() ? "in" /* Operator.IN */ === t || "not-in" /* Operator.NOT_IN */ === t ? this.createKeyFieldInFilter(e, t, n) : new __PRIVATE_KeyFieldFilter(e, t, n) : "array-contains" /* Operator.ARRAY_CONTAINS */ === t ? new __PRIVATE_ArrayContainsFilter(e, n) : "in" /* Operator.IN */ === t ? new __PRIVATE_InFilter(e, n) : "not-in" /* Operator.NOT_IN */ === t ? new __PRIVATE_NotInFilter(e, n) : "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === t ? new __PRIVATE_ArrayContainsAnyFilter(e, n) : new FieldFilter(e, t, n); + } + static createKeyFieldInFilter(e, t, n) { + return "in" /* Operator.IN */ === t ? new __PRIVATE_KeyFieldInFilter(e, n) : new __PRIVATE_KeyFieldNotInFilter(e, n); + } + matches(e) { + const t = e.data.field(this.field); + // Types do not have to match in NOT_EQUAL filters. + return "!=" /* Operator.NOT_EQUAL */ === this.op ? null !== t && void 0 === t.nullValue && this.matchesComparison(__PRIVATE_valueCompare(t, this.value)) : null !== t && __PRIVATE_typeOrder(this.value) === __PRIVATE_typeOrder(t) && this.matchesComparison(__PRIVATE_valueCompare(t, this.value)); + // Only compare types with matching backend order (such as double and int). + } + matchesComparison(e) { + switch (this.op) { + case "<" /* Operator.LESS_THAN */ : + return e < 0; + + case "<=" /* Operator.LESS_THAN_OR_EQUAL */ : + return e <= 0; + + case "==" /* Operator.EQUAL */ : + return 0 === e; + + case "!=" /* Operator.NOT_EQUAL */ : + return 0 !== e; + + case ">" /* Operator.GREATER_THAN */ : + return e > 0; + + case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ : + return e >= 0; + + default: + return fail(47266, { + operator: this.op + }); + } + } + isInequality() { + return [ "<" /* Operator.LESS_THAN */ , "<=" /* Operator.LESS_THAN_OR_EQUAL */ , ">" /* Operator.GREATER_THAN */ , ">=" /* Operator.GREATER_THAN_OR_EQUAL */ , "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ].indexOf(this.op) >= 0; + } + getFlattenedFilters() { + return [ this ]; + } + getFilters() { + return [ this ]; + } +} + +class CompositeFilter extends Filter { + constructor(e, t) { + super(), this.filters = e, this.op = t, this.Pe = null; + } + /** + * Creates a filter based on the provided arguments. + */ static create(e, t) { + return new CompositeFilter(e, t); + } + matches(e) { + return __PRIVATE_compositeFilterIsConjunction(this) ? void 0 === this.filters.find((t => !t.matches(e))) : void 0 !== this.filters.find((t => t.matches(e))); + } + getFlattenedFilters() { + return null !== this.Pe || (this.Pe = this.filters.reduce(((e, t) => e.concat(t.getFlattenedFilters())), [])), + this.Pe; + } + // Returns a mutable copy of `this.filters` + getFilters() { + return Object.assign([], this.filters); + } +} + +function __PRIVATE_compositeFilterIsConjunction(e) { + return "and" /* CompositeOperator.AND */ === e.op; +} + +function __PRIVATE_compositeFilterIsDisjunction(e) { + return "or" /* CompositeOperator.OR */ === e.op; +} + +/** + * Returns true if this filter is a conjunction of field filters only. Returns false otherwise. + */ function __PRIVATE_compositeFilterIsFlatConjunction(e) { + return __PRIVATE_compositeFilterIsFlat(e) && __PRIVATE_compositeFilterIsConjunction(e); +} + +/** + * Returns true if this filter does not contain any composite filters. Returns false otherwise. + */ function __PRIVATE_compositeFilterIsFlat(e) { + for (const t of e.filters) if (t instanceof CompositeFilter) return !1; + return !0; +} + +function __PRIVATE_canonifyFilter(e) { + if (e instanceof FieldFilter) + // TODO(b/29183165): Technically, this won't be unique if two values have + // the same description, such as the int 3 and the string "3". So we should + // add the types in here somehow, too. + return e.field.canonicalString() + e.op.toString() + canonicalId(e.value); + if (__PRIVATE_compositeFilterIsFlatConjunction(e)) + // Older SDK versions use an implicit AND operation between their filters. + // In the new SDK versions, the developer may use an explicit AND filter. + // To stay consistent with the old usages, we add a special case to ensure + // the canonical ID for these two are the same. For example: + // `col.whereEquals("a", 1).whereEquals("b", 2)` should have the same + // canonical ID as `col.where(and(equals("a",1), equals("b",2)))`. + return e.filters.map((e => __PRIVATE_canonifyFilter(e))).join(","); + { + // filter instanceof CompositeFilter + const t = e.filters.map((e => __PRIVATE_canonifyFilter(e))).join(","); + return `${e.op}(${t})`; + } +} + +function __PRIVATE_filterEquals(e, t) { + return e instanceof FieldFilter ? function __PRIVATE_fieldFilterEquals(e, t) { + return t instanceof FieldFilter && e.op === t.op && e.field.isEqual(t.field) && __PRIVATE_valueEquals(e.value, t.value); + }(e, t) : e instanceof CompositeFilter ? function __PRIVATE_compositeFilterEquals(e, t) { + if (t instanceof CompositeFilter && e.op === t.op && e.filters.length === t.filters.length) { + return e.filters.reduce(((e, n, r) => e && __PRIVATE_filterEquals(n, t.filters[r])), !0); + } + return !1; + } + /** + * Returns a new composite filter that contains all filter from + * `compositeFilter` plus all the given filters in `otherFilters`. + */ (e, t) : void fail(19439); +} + +function __PRIVATE_compositeFilterWithAddedFilters(e, t) { + const n = e.filters.concat(t); + return CompositeFilter.create(n, e.op); +} + +/** Returns a debug description for `filter`. */ function __PRIVATE_stringifyFilter(e) { + return e instanceof FieldFilter ? function __PRIVATE_stringifyFieldFilter(e) { + return `${e.field.canonicalString()} ${e.op} ${canonicalId(e.value)}`; + } + /** Filter that matches on key fields (i.e. '__name__'). */ (e) : e instanceof CompositeFilter ? function __PRIVATE_stringifyCompositeFilter(e) { + return e.op.toString() + " {" + e.getFilters().map(__PRIVATE_stringifyFilter).join(" ,") + "}"; + }(e) : "Filter"; +} + +class __PRIVATE_KeyFieldFilter extends FieldFilter { + constructor(e, t, n) { + super(e, t, n), this.key = DocumentKey.fromName(n.referenceValue); + } + matches(e) { + const t = DocumentKey.comparator(e.key, this.key); + return this.matchesComparison(t); + } +} + +/** Filter that matches on key fields within an array. */ class __PRIVATE_KeyFieldInFilter extends FieldFilter { + constructor(e, t) { + super(e, "in" /* Operator.IN */ , t), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue("in" /* Operator.IN */ , t); + } + matches(e) { + return this.keys.some((t => t.isEqual(e.key))); + } +} + +/** Filter that matches on key fields not present within an array. */ class __PRIVATE_KeyFieldNotInFilter extends FieldFilter { + constructor(e, t) { + super(e, "not-in" /* Operator.NOT_IN */ , t), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue("not-in" /* Operator.NOT_IN */ , t); + } + matches(e) { + return !this.keys.some((t => t.isEqual(e.key))); + } +} + +function __PRIVATE_extractDocumentKeysFromArrayValue(e, t) { + return (t.arrayValue?.values || []).map((e => DocumentKey.fromName(e.referenceValue))); +} + +/** A Filter that implements the array-contains operator. */ class __PRIVATE_ArrayContainsFilter extends FieldFilter { + constructor(e, t) { + super(e, "array-contains" /* Operator.ARRAY_CONTAINS */ , t); + } + matches(e) { + const t = e.data.field(this.field); + return isArray(t) && __PRIVATE_arrayValueContains(t.arrayValue, this.value); + } +} + +/** A Filter that implements the IN operator. */ class __PRIVATE_InFilter extends FieldFilter { + constructor(e, t) { + super(e, "in" /* Operator.IN */ , t); + } + matches(e) { + const t = e.data.field(this.field); + return null !== t && __PRIVATE_arrayValueContains(this.value.arrayValue, t); + } +} + +/** A Filter that implements the not-in operator. */ class __PRIVATE_NotInFilter extends FieldFilter { + constructor(e, t) { + super(e, "not-in" /* Operator.NOT_IN */ , t); + } + matches(e) { + if (__PRIVATE_arrayValueContains(this.value.arrayValue, { + nullValue: "NULL_VALUE" + })) return !1; + const t = e.data.field(this.field); + return null !== t && void 0 === t.nullValue && !__PRIVATE_arrayValueContains(this.value.arrayValue, t); + } +} + +/** A Filter that implements the array-contains-any operator. */ class __PRIVATE_ArrayContainsAnyFilter extends FieldFilter { + constructor(e, t) { + super(e, "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , t); + } + matches(e) { + const t = e.data.field(this.field); + return !(!isArray(t) || !t.arrayValue.values) && t.arrayValue.values.some((e => __PRIVATE_arrayValueContains(this.value.arrayValue, e))); + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Visible for testing +class __PRIVATE_TargetImpl { + constructor(e, t = null, n = [], r = [], i = null, s = null, o = null) { + this.path = e, this.collectionGroup = t, this.orderBy = n, this.filters = r, this.limit = i, + this.startAt = s, this.endAt = o, this.Te = null; + } +} + +/** + * Initializes a Target with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + * + * NOTE: you should always construct `Target` from `Query.toTarget` instead of + * using this factory method, because `Query` provides an implicit `orderBy` + * property. + */ function __PRIVATE_newTarget(e, t = null, n = [], r = [], i = null, s = null, o = null) { + return new __PRIVATE_TargetImpl(e, t, n, r, i, s, o); +} + +function __PRIVATE_canonifyTarget(e) { + const t = __PRIVATE_debugCast(e); + if (null === t.Te) { + let e = t.path.canonicalString(); + null !== t.collectionGroup && (e += "|cg:" + t.collectionGroup), e += "|f:", e += t.filters.map((e => __PRIVATE_canonifyFilter(e))).join(","), + e += "|ob:", e += t.orderBy.map((e => function __PRIVATE_canonifyOrderBy(e) { + // TODO(b/29183165): Make this collision robust. + return e.field.canonicalString() + e.dir; + }(e))).join(","), __PRIVATE_isNullOrUndefined(t.limit) || (e += "|l:", e += t.limit), + t.startAt && (e += "|lb:", e += t.startAt.inclusive ? "b:" : "a:", e += t.startAt.position.map((e => canonicalId(e))).join(",")), + t.endAt && (e += "|ub:", e += t.endAt.inclusive ? "a:" : "b:", e += t.endAt.position.map((e => canonicalId(e))).join(",")), + t.Te = e; + } + return t.Te; +} + +function __PRIVATE_targetEquals(e, t) { + if (e.limit !== t.limit) return !1; + if (e.orderBy.length !== t.orderBy.length) return !1; + for (let n = 0; n < e.orderBy.length; n++) if (!__PRIVATE_orderByEquals(e.orderBy[n], t.orderBy[n])) return !1; + if (e.filters.length !== t.filters.length) return !1; + for (let n = 0; n < e.filters.length; n++) if (!__PRIVATE_filterEquals(e.filters[n], t.filters[n])) return !1; + return e.collectionGroup === t.collectionGroup && (!!e.path.isEqual(t.path) && (!!__PRIVATE_boundEquals(e.startAt, t.startAt) && __PRIVATE_boundEquals(e.endAt, t.endAt))); +} + +function __PRIVATE_targetIsDocumentTarget(e) { + return DocumentKey.isDocumentKey(e.path) && null === e.collectionGroup && 0 === e.filters.length; +} + +/** Returns the field filters that target the given field path. */ function __PRIVATE_targetGetFieldFiltersForPath(e, t) { + return e.filters.filter((e => e instanceof FieldFilter && e.field.isEqual(t))); +} + +/** + * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY + * filters. Returns `null` if there are no such filters. + */ +/** + * Returns the value to use as the lower bound for ascending index segment at + * the provided `fieldPath` (or the upper bound for an descending segment). + */ +function __PRIVATE_targetGetAscendingBound(e, t, n) { + let r = dt, i = !0; + // Process all filters to find a value for the current field segment + for (const n of __PRIVATE_targetGetFieldFiltersForPath(e, t)) { + let e = dt, t = !0; + switch (n.op) { + case "<" /* Operator.LESS_THAN */ : + case "<=" /* Operator.LESS_THAN_OR_EQUAL */ : + e = __PRIVATE_valuesGetLowerBound(n.value); + break; + + case "==" /* Operator.EQUAL */ : + case "in" /* Operator.IN */ : + case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ : + e = n.value; + break; + + case ">" /* Operator.GREATER_THAN */ : + e = n.value, t = !1; + break; + + case "!=" /* Operator.NOT_EQUAL */ : + case "not-in" /* Operator.NOT_IN */ : + e = dt; + // Remaining filters cannot be used as lower bounds. + } + __PRIVATE_lowerBoundCompare({ + value: r, + inclusive: i + }, { + value: e, + inclusive: t + }) < 0 && (r = e, i = t); + } + // If there is an additional bound, compare the values against the existing + // range to see if we can narrow the scope. + if (null !== n) for (let s = 0; s < e.orderBy.length; ++s) { + if (e.orderBy[s].field.isEqual(t)) { + const e = n.position[s]; + __PRIVATE_lowerBoundCompare({ + value: r, + inclusive: i + }, { + value: e, + inclusive: n.inclusive + }) < 0 && (r = e, i = n.inclusive); + break; + } + } + return { + value: r, + inclusive: i + }; +} + +/** + * Returns the value to use as the upper bound for ascending index segment at + * the provided `fieldPath` (or the lower bound for a descending segment). + */ function __PRIVATE_targetGetDescendingBound(e, t, n) { + let r = Tt, i = !0; + // Process all filters to find a value for the current field segment + for (const n of __PRIVATE_targetGetFieldFiltersForPath(e, t)) { + let e = Tt, t = !0; + switch (n.op) { + case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ : + case ">" /* Operator.GREATER_THAN */ : + e = __PRIVATE_valuesGetUpperBound(n.value), t = !1; + break; + + case "==" /* Operator.EQUAL */ : + case "in" /* Operator.IN */ : + case "<=" /* Operator.LESS_THAN_OR_EQUAL */ : + e = n.value; + break; + + case "<" /* Operator.LESS_THAN */ : + e = n.value, t = !1; + break; + + case "!=" /* Operator.NOT_EQUAL */ : + case "not-in" /* Operator.NOT_IN */ : + e = Tt; + // Remaining filters cannot be used as upper bounds. + } + __PRIVATE_upperBoundCompare({ + value: r, + inclusive: i + }, { + value: e, + inclusive: t + }) > 0 && (r = e, i = t); + } + // If there is an additional bound, compare the values against the existing + // range to see if we can narrow the scope. + if (null !== n) for (let s = 0; s < e.orderBy.length; ++s) { + if (e.orderBy[s].field.isEqual(t)) { + const e = n.position[s]; + __PRIVATE_upperBoundCompare({ + value: r, + inclusive: i + }, { + value: e, + inclusive: n.inclusive + }) > 0 && (r = e, i = n.inclusive); + break; + } + } + return { + value: r, + inclusive: i + }; +} + +/** Returns the number of segments of a perfect index for this target. */ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Query encapsulates all the query attributes we support in the SDK. It can + * be run against the LocalStore, as well as be converted to a `Target` to + * query the RemoteStore results. + * + * Visible for testing. + */ +class __PRIVATE_QueryImpl { + /** + * Initializes a Query with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + */ + constructor(e, t = null, n = [], r = [], i = null, s = "F" /* LimitType.First */ , o = null, _ = null) { + this.path = e, this.collectionGroup = t, this.explicitOrderBy = n, this.filters = r, + this.limit = i, this.limitType = s, this.startAt = o, this.endAt = _, this.Ie = null, + // The corresponding `Target` of this `Query` instance, for use with + // non-aggregate queries. + this.Ee = null, + // The corresponding `Target` of this `Query` instance, for use with + // aggregate queries. Unlike targets for non-aggregate queries, + // aggregate query targets do not contain normalized order-bys, they only + // contain explicit order-bys. + this.de = null, this.startAt, this.endAt; + } +} + +/** Creates a new Query instance with the options provided. */ function __PRIVATE_newQuery(e, t, n, r, i, s, o, _) { + return new __PRIVATE_QueryImpl(e, t, n, r, i, s, o, _); +} + +/** Creates a new Query for a query that matches all documents at `path` */ function __PRIVATE_newQueryForPath(e) { + return new __PRIVATE_QueryImpl(e); +} + +/** + * Helper to convert a collection group query into a collection query at a + * specific path. This is used when executing collection group queries, since + * we have to split the query into a set of collection queries at multiple + * paths. + */ +/** + * Returns true if this query does not specify any query constraints that + * could remove results. + */ +function __PRIVATE_queryMatchesAllDocuments(e) { + return 0 === e.filters.length && null === e.limit && null == e.startAt && null == e.endAt && (0 === e.explicitOrderBy.length || 1 === e.explicitOrderBy.length && e.explicitOrderBy[0].field.isKeyField()); +} + +// Returns the sorted set of inequality filter fields used in this query. +/** + * Returns whether the query matches a collection group rather than a specific + * collection. + */ +function __PRIVATE_isCollectionGroupQuery(e) { + return null !== e.collectionGroup; +} + +/** + * Returns the normalized order-by constraint that is used to execute the Query, + * which can be different from the order-by constraints the user provided (e.g. + * the SDK and backend always orders by `__name__`). The normalized order-by + * includes implicit order-bys in addition to the explicit user provided + * order-bys. + */ function __PRIVATE_queryNormalizedOrderBy(e) { + const t = __PRIVATE_debugCast(e); + if (null === t.Ie) { + t.Ie = []; + const e = new Set; + // Any explicit order by fields should be added as is. + for (const n of t.explicitOrderBy) t.Ie.push(n), e.add(n.field.canonicalString()); + // The order of the implicit ordering always matches the last explicit order by. + const n = t.explicitOrderBy.length > 0 ? t.explicitOrderBy[t.explicitOrderBy.length - 1].dir : "asc" /* Direction.ASCENDING */ , r = function __PRIVATE_getInequalityFilterFields(e) { + let t = new SortedSet(FieldPath$1.comparator); + return e.filters.forEach((e => { + e.getFlattenedFilters().forEach((e => { + e.isInequality() && (t = t.add(e.field)); + })); + })), t; + } + /** + * Creates a new Query for a collection group query that matches all documents + * within the provided collection group. + */ (t); + // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical + // order. When there are multiple inequality filters on the same field, the field should be added + // only once. + // Note: `SortedSet` sorts the key field before other fields. However, we want the key + // field to be sorted last. + r.forEach((r => { + e.has(r.canonicalString()) || r.isKeyField() || t.Ie.push(new OrderBy(r, n)); + })), + // Add the document key field to the last if it is not explicitly ordered. + e.has(FieldPath$1.keyField().canonicalString()) || t.Ie.push(new OrderBy(FieldPath$1.keyField(), n)); + } + return t.Ie; +} + +/** + * Converts this `Query` instance to its corresponding `Target` representation. + */ function __PRIVATE_queryToTarget(e) { + const t = __PRIVATE_debugCast(e); + return t.Ee || (t.Ee = __PRIVATE__queryToTarget(t, __PRIVATE_queryNormalizedOrderBy(e))), + t.Ee; +} + +/** + * Converts this `Query` instance to its corresponding `Target` representation, + * for use within an aggregate query. Unlike targets for non-aggregate queries, + * aggregate query targets do not contain normalized order-bys, they only + * contain explicit order-bys. + */ function __PRIVATE_queryToAggregateTarget(e) { + const t = __PRIVATE_debugCast(e); + return t.de || ( + // Do not include implicit order-bys for aggregate queries. + t.de = __PRIVATE__queryToTarget(t, e.explicitOrderBy)), t.de; +} + +function __PRIVATE__queryToTarget(e, t) { + if ("F" /* LimitType.First */ === e.limitType) return __PRIVATE_newTarget(e.path, e.collectionGroup, t, e.filters, e.limit, e.startAt, e.endAt); + { + // Flip the orderBy directions since we want the last results + t = t.map((e => { + const t = "desc" /* Direction.DESCENDING */ === e.dir ? "asc" /* Direction.ASCENDING */ : "desc" /* Direction.DESCENDING */; + return new OrderBy(e.field, t); + })); + // We need to swap the cursors to match the now-flipped query ordering. + const n = e.endAt ? new Bound(e.endAt.position, e.endAt.inclusive) : null, r = e.startAt ? new Bound(e.startAt.position, e.startAt.inclusive) : null; + // Now return as a LimitType.First query. + return __PRIVATE_newTarget(e.path, e.collectionGroup, t, e.filters, e.limit, n, r); + } +} + +function __PRIVATE_queryWithAddedFilter(e, t) { + const n = e.filters.concat([ t ]); + return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, e.explicitOrderBy.slice(), n, e.limit, e.limitType, e.startAt, e.endAt); +} + +function __PRIVATE_queryWithLimit(e, t, n) { + return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, e.explicitOrderBy.slice(), e.filters.slice(), t, n, e.startAt, e.endAt); +} + +function __PRIVATE_queryEquals(e, t) { + return __PRIVATE_targetEquals(__PRIVATE_queryToTarget(e), __PRIVATE_queryToTarget(t)) && e.limitType === t.limitType; +} + +// TODO(b/29183165): This is used to get a unique string from a query to, for +// example, use as a dictionary key, but the implementation is subject to +// collisions. Make it collision-free. +function __PRIVATE_canonifyQuery(e) { + return `${__PRIVATE_canonifyTarget(__PRIVATE_queryToTarget(e))}|lt:${e.limitType}`; +} + +function __PRIVATE_stringifyQuery(e) { + return `Query(target=${function __PRIVATE_stringifyTarget(e) { + let t = e.path.canonicalString(); + return null !== e.collectionGroup && (t += " collectionGroup=" + e.collectionGroup), + e.filters.length > 0 && (t += `, filters: [${e.filters.map((e => __PRIVATE_stringifyFilter(e))).join(", ")}]`), + __PRIVATE_isNullOrUndefined(e.limit) || (t += ", limit: " + e.limit), e.orderBy.length > 0 && (t += `, orderBy: [${e.orderBy.map((e => function __PRIVATE_stringifyOrderBy(e) { + return `${e.field.canonicalString()} (${e.dir})`; + }(e))).join(", ")}]`), e.startAt && (t += ", startAt: ", t += e.startAt.inclusive ? "b:" : "a:", + t += e.startAt.position.map((e => canonicalId(e))).join(",")), e.endAt && (t += ", endAt: ", + t += e.endAt.inclusive ? "a:" : "b:", t += e.endAt.position.map((e => canonicalId(e))).join(",")), + `Target(${t})`; + }(__PRIVATE_queryToTarget(e))}; limitType=${e.limitType})`; +} + +/** Returns whether `doc` matches the constraints of `query`. */ function __PRIVATE_queryMatches(e, t) { + return t.isFoundDocument() && function __PRIVATE_queryMatchesPathAndCollectionGroup(e, t) { + const n = t.key.path; + return null !== e.collectionGroup ? t.key.hasCollectionId(e.collectionGroup) && e.path.isPrefixOf(n) : DocumentKey.isDocumentKey(e.path) ? e.path.isEqual(n) : e.path.isImmediateParentOf(n); + } + /** + * A document must have a value for every ordering clause in order to show up + * in the results. + */ (e, t) && function __PRIVATE_queryMatchesOrderBy(e, t) { + // We must use `queryNormalizedOrderBy()` to get the list of all orderBys (both implicit and explicit). + // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must + // be taken into account. For example, the query "a > 1 || b==1" has an implicit "orderBy a" due + // to the inequality, and is evaluated as "a > 1 orderBy a || b==1 orderBy a". + // A document with content of {b:1} matches the filters, but does not match the orderBy because + // it's missing the field 'a'. + for (const n of __PRIVATE_queryNormalizedOrderBy(e)) + // order-by key always matches + if (!n.field.isKeyField() && null === t.data.field(n.field)) return !1; + return !0; + }(e, t) && function __PRIVATE_queryMatchesFilters(e, t) { + for (const n of e.filters) if (!n.matches(t)) return !1; + return !0; + } + /** Makes sure a document is within the bounds, if provided. */ (e, t) && function __PRIVATE_queryMatchesBounds(e, t) { + if (e.startAt && ! + /** + * Returns true if a document sorts before a bound using the provided sort + * order. + */ + function __PRIVATE_boundSortsBeforeDocument(e, t, n) { + const r = __PRIVATE_boundCompareToDocument(e, t, n); + return e.inclusive ? r <= 0 : r < 0; + }(e.startAt, __PRIVATE_queryNormalizedOrderBy(e), t)) return !1; + if (e.endAt && !function __PRIVATE_boundSortsAfterDocument(e, t, n) { + const r = __PRIVATE_boundCompareToDocument(e, t, n); + return e.inclusive ? r >= 0 : r > 0; + }(e.endAt, __PRIVATE_queryNormalizedOrderBy(e), t)) return !1; + return !0; + } + /** + * Returns the collection group that this query targets. + * + * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab + * synchronization for query results. + */ (e, t); +} + +function __PRIVATE_queryCollectionGroup(e) { + return e.collectionGroup || (e.path.length % 2 == 1 ? e.path.lastSegment() : e.path.get(e.path.length - 2)); +} + +/** + * Returns a new comparator function that can be used to compare two documents + * based on the Query's ordering constraint. + */ function __PRIVATE_newQueryComparator(e) { + return (t, n) => { + let r = !1; + for (const i of __PRIVATE_queryNormalizedOrderBy(e)) { + const e = __PRIVATE_compareDocs(i, t, n); + if (0 !== e) return e; + r = r || i.field.isKeyField(); + } + return 0; + }; +} + +function __PRIVATE_compareDocs(e, t, n) { + const r = e.field.isKeyField() ? DocumentKey.comparator(t.key, n.key) : function __PRIVATE_compareDocumentsByField(e, t, n) { + const r = t.data.field(e), i = n.data.field(e); + return null !== r && null !== i ? __PRIVATE_valueCompare(r, i) : fail(42886); + }(e.field, t, n); + switch (e.dir) { + case "asc" /* Direction.ASCENDING */ : + return r; + + case "desc" /* Direction.DESCENDING */ : + return -1 * r; + + default: + return fail(19790, { + direction: e.dir + }); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A map implementation that uses objects as keys. Objects must have an + * associated equals function and must be immutable. Entries in the map are + * stored together with the key being produced from the mapKeyFn. This map + * automatically handles collisions of keys. + */ class ObjectMap { + constructor(e, t) { + this.mapKeyFn = e, this.equalsFn = t, + /** + * The inner map for a key/value pair. Due to the possibility of collisions we + * keep a list of entries that we do a linear search through to find an actual + * match. Note that collisions should be rare, so we still expect near + * constant time lookups in practice. + */ + this.inner = {}, + /** The number of entries stored in the map */ + this.innerSize = 0; + } + /** Get a value for this key, or undefined if it does not exist. */ get(e) { + const t = this.mapKeyFn(e), n = this.inner[t]; + if (void 0 !== n) for (const [t, r] of n) if (this.equalsFn(t, e)) return r; + } + has(e) { + return void 0 !== this.get(e); + } + /** Put this key and value in the map. */ set(e, t) { + const n = this.mapKeyFn(e), r = this.inner[n]; + if (void 0 === r) return this.inner[n] = [ [ e, t ] ], void this.innerSize++; + for (let n = 0; n < r.length; n++) if (this.equalsFn(r[n][0], e)) + // This is updating an existing entry and does not increase `innerSize`. + return void (r[n] = [ e, t ]); + r.push([ e, t ]), this.innerSize++; + } + /** + * Remove this key from the map. Returns a boolean if anything was deleted. + */ delete(e) { + const t = this.mapKeyFn(e), n = this.inner[t]; + if (void 0 === n) return !1; + for (let r = 0; r < n.length; r++) if (this.equalsFn(n[r][0], e)) return 1 === n.length ? delete this.inner[t] : n.splice(r, 1), + this.innerSize--, !0; + return !1; + } + forEach(e) { + forEach(this.inner, ((t, n) => { + for (const [t, r] of n) e(t, r); + })); + } + isEmpty() { + return isEmpty(this.inner); + } + size() { + return this.innerSize; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const Rt = new SortedMap(DocumentKey.comparator); + +function __PRIVATE_mutableDocumentMap() { + return Rt; +} + +const Vt = new SortedMap(DocumentKey.comparator); + +function documentMap(...e) { + let t = Vt; + for (const n of e) t = t.insert(n.key, n); + return t; +} + +function __PRIVATE_convertOverlayedDocumentMapToDocumentMap(e) { + let t = Vt; + return e.forEach(((e, n) => t = t.insert(e, n.overlayedDocument))), t; +} + +function __PRIVATE_newOverlayMap() { + return __PRIVATE_newDocumentKeyMap(); +} + +function __PRIVATE_newMutationMap() { + return __PRIVATE_newDocumentKeyMap(); +} + +function __PRIVATE_newDocumentKeyMap() { + return new ObjectMap((e => e.toString()), ((e, t) => e.isEqual(t))); +} + +const mt = new SortedMap(DocumentKey.comparator); + +const ft = new SortedSet(DocumentKey.comparator); + +function __PRIVATE_documentKeySet(...e) { + let t = ft; + for (const n of e) t = t.add(n); + return t; +} + +const gt = new SortedSet(__PRIVATE_primitiveComparator); + +function __PRIVATE_targetIdSet() { + return gt; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns an DoubleValue for `value` that is encoded based the serializer's + * `useProto3Json` setting. + */ function __PRIVATE_toDouble(e, t) { + if (e.useProto3Json) { + if (isNaN(t)) return { + doubleValue: "NaN" + }; + if (t === 1 / 0) return { + doubleValue: "Infinity" + }; + if (t === -1 / 0) return { + doubleValue: "-Infinity" + }; + } + return { + doubleValue: __PRIVATE_isNegativeZero(t) ? "-0" : t + }; +} + +/** + * Returns an IntegerValue for `value`. + */ function __PRIVATE_toInteger(e) { + return { + integerValue: "" + e + }; +} + +/** + * Returns a value for a number that's appropriate to put into a proto. + * The return value is an IntegerValue if it can safely represent the value, + * otherwise a DoubleValue is returned. + */ function toNumber(e, t) { + return isSafeInteger(t) ? __PRIVATE_toInteger(t) : __PRIVATE_toDouble(e, t); +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Used to represent a field transform on a mutation. */ class TransformOperation { + constructor() { + // Make sure that the structural type of `TransformOperation` is unique. + // See https://github.com/microsoft/TypeScript/issues/5451 + this._ = void 0; + } +} + +/** + * Computes the local transform result against the provided `previousValue`, + * optionally using the provided localWriteTime. + */ function __PRIVATE_applyTransformOperationToLocalView(e, t, n) { + return e instanceof __PRIVATE_ServerTimestampTransform ? function serverTimestamp$1(e, t) { + const n = { + fields: { + [at]: { + stringValue: _t + }, + [ct]: { + timestampValue: { + seconds: e.seconds, + nanos: e.nanoseconds + } + } + } + }; + // We should avoid storing deeply nested server timestamp map values + // because we never use the intermediate "previous values". + // For example: + // previous: 42L, add: t1, result: t1 -> 42L + // previous: t1, add: t2, result: t2 -> 42L (NOT t2 -> t1 -> 42L) + // previous: t2, add: t3, result: t3 -> 42L (NOT t3 -> t2 -> t1 -> 42L) + // `getPreviousValue` recursively traverses server timestamps to find the + // least recent Value. + return t && __PRIVATE_isServerTimestamp(t) && (t = __PRIVATE_getPreviousValue(t)), + t && (n.fields[ut] = t), { + mapValue: n + }; + }(n, t) : e instanceof __PRIVATE_ArrayUnionTransformOperation ? __PRIVATE_applyArrayUnionTransformOperation(e, t) : e instanceof __PRIVATE_ArrayRemoveTransformOperation ? __PRIVATE_applyArrayRemoveTransformOperation(e, t) : function __PRIVATE_applyNumericIncrementTransformOperationToLocalView(e, t) { + // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit + // precision and resolves overflows by reducing precision, we do not + // manually cap overflows at 2^63. + const n = __PRIVATE_computeTransformOperationBaseValue(e, t), r = asNumber(n) + asNumber(e.Ae); + return isInteger(n) && isInteger(e.Ae) ? __PRIVATE_toInteger(r) : __PRIVATE_toDouble(e.serializer, r); + }(e, t); +} + +/** + * Computes a final transform result after the transform has been acknowledged + * by the server, potentially using the server-provided transformResult. + */ function __PRIVATE_applyTransformOperationToRemoteDocument(e, t, n) { + // The server just sends null as the transform result for array operations, + // so we have to calculate a result the same as we do for local + // applications. + return e instanceof __PRIVATE_ArrayUnionTransformOperation ? __PRIVATE_applyArrayUnionTransformOperation(e, t) : e instanceof __PRIVATE_ArrayRemoveTransformOperation ? __PRIVATE_applyArrayRemoveTransformOperation(e, t) : n; +} + +/** + * If this transform operation is not idempotent, returns the base value to + * persist for this transform. If a base value is returned, the transform + * operation is always applied to this base value, even if document has + * already been updated. + * + * Base values provide consistent behavior for non-idempotent transforms and + * allow us to return the same latency-compensated value even if the backend + * has already applied the transform operation. The base value is null for + * idempotent transforms, as they can be re-played even if the backend has + * already applied them. + * + * @returns a base value to store along with the mutation, or null for + * idempotent transforms. + */ function __PRIVATE_computeTransformOperationBaseValue(e, t) { + return e instanceof __PRIVATE_NumericIncrementTransformOperation ? + /** Returns true if `value` is either an IntegerValue or a DoubleValue. */ + function __PRIVATE_isNumber(e) { + return isInteger(e) || function __PRIVATE_isDouble(e) { + return !!e && "doubleValue" in e; + }(e); + }(t) ? t : { + integerValue: 0 + } : null; +} + +/** Transforms a value into a server-generated timestamp. */ +class __PRIVATE_ServerTimestampTransform extends TransformOperation {} + +/** Transforms an array value via a union operation. */ class __PRIVATE_ArrayUnionTransformOperation extends TransformOperation { + constructor(e) { + super(), this.elements = e; + } +} + +function __PRIVATE_applyArrayUnionTransformOperation(e, t) { + const n = __PRIVATE_coercedFieldValuesArray(t); + for (const t of e.elements) n.some((e => __PRIVATE_valueEquals(e, t))) || n.push(t); + return { + arrayValue: { + values: n + } + }; +} + +/** Transforms an array value via a remove operation. */ class __PRIVATE_ArrayRemoveTransformOperation extends TransformOperation { + constructor(e) { + super(), this.elements = e; + } +} + +function __PRIVATE_applyArrayRemoveTransformOperation(e, t) { + let n = __PRIVATE_coercedFieldValuesArray(t); + for (const t of e.elements) n = n.filter((e => !__PRIVATE_valueEquals(e, t))); + return { + arrayValue: { + values: n + } + }; +} + +/** + * Implements the backend semantics for locally computed NUMERIC_ADD (increment) + * transforms. Converts all field values to integers or doubles, but unlike the + * backend does not cap integer values at 2^63. Instead, JavaScript number + * arithmetic is used and precision loss can occur for values greater than 2^53. + */ class __PRIVATE_NumericIncrementTransformOperation extends TransformOperation { + constructor(e, t) { + super(), this.serializer = e, this.Ae = t; + } +} + +function asNumber(e) { + return __PRIVATE_normalizeNumber(e.integerValue || e.doubleValue); +} + +function __PRIVATE_coercedFieldValuesArray(e) { + return isArray(e) && e.arrayValue.values ? e.arrayValue.values.slice() : []; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** A field path and the TransformOperation to perform upon it. */ class FieldTransform { + constructor(e, t) { + this.field = e, this.transform = t; + } +} + +function __PRIVATE_fieldTransformEquals(e, t) { + return e.field.isEqual(t.field) && function __PRIVATE_transformOperationEquals(e, t) { + return e instanceof __PRIVATE_ArrayUnionTransformOperation && t instanceof __PRIVATE_ArrayUnionTransformOperation || e instanceof __PRIVATE_ArrayRemoveTransformOperation && t instanceof __PRIVATE_ArrayRemoveTransformOperation ? __PRIVATE_arrayEquals(e.elements, t.elements, __PRIVATE_valueEquals) : e instanceof __PRIVATE_NumericIncrementTransformOperation && t instanceof __PRIVATE_NumericIncrementTransformOperation ? __PRIVATE_valueEquals(e.Ae, t.Ae) : e instanceof __PRIVATE_ServerTimestampTransform && t instanceof __PRIVATE_ServerTimestampTransform; + }(e.transform, t.transform); +} + +/** The result of successfully applying a mutation to the backend. */ +class MutationResult { + constructor( + /** + * The version at which the mutation was committed: + * + * - For most operations, this is the updateTime in the WriteResult. + * - For deletes, the commitTime of the WriteResponse (because deletes are + * not stored and have no updateTime). + * + * Note that these versions can be different: No-op writes will not change + * the updateTime even though the commitTime advances. + */ + e, + /** + * The resulting fields returned from the backend after a mutation + * containing field transforms has been committed. Contains one FieldValue + * for each FieldTransform that was in the mutation. + * + * Will be empty if the mutation did not contain any field transforms. + */ + t) { + this.version = e, this.transformResults = t; + } +} + +/** + * Encodes a precondition for a mutation. This follows the model that the + * backend accepts with the special case of an explicit "empty" precondition + * (meaning no precondition). + */ class Precondition { + constructor(e, t) { + this.updateTime = e, this.exists = t; + } + /** Creates a new empty Precondition. */ static none() { + return new Precondition; + } + /** Creates a new Precondition with an exists flag. */ static exists(e) { + return new Precondition(void 0, e); + } + /** Creates a new Precondition based on a version a document exists at. */ static updateTime(e) { + return new Precondition(e); + } + /** Returns whether this Precondition is empty. */ get isNone() { + return void 0 === this.updateTime && void 0 === this.exists; + } + isEqual(e) { + return this.exists === e.exists && (this.updateTime ? !!e.updateTime && this.updateTime.isEqual(e.updateTime) : !e.updateTime); + } +} + +/** Returns true if the preconditions is valid for the given document. */ function __PRIVATE_preconditionIsValidForDocument(e, t) { + return void 0 !== e.updateTime ? t.isFoundDocument() && t.version.isEqual(e.updateTime) : void 0 === e.exists || e.exists === t.isFoundDocument(); +} + +/** + * A mutation describes a self-contained change to a document. Mutations can + * create, replace, delete, and update subsets of documents. + * + * Mutations not only act on the value of the document but also its version. + * + * For local mutations (mutations that haven't been committed yet), we preserve + * the existing version for Set and Patch mutations. For Delete mutations, we + * reset the version to 0. + * + * Here's the expected transition table. + * + * MUTATION APPLIED TO RESULTS IN + * + * SetMutation Document(v3) Document(v3) + * SetMutation NoDocument(v3) Document(v0) + * SetMutation InvalidDocument(v0) Document(v0) + * PatchMutation Document(v3) Document(v3) + * PatchMutation NoDocument(v3) NoDocument(v3) + * PatchMutation InvalidDocument(v0) UnknownDocument(v3) + * DeleteMutation Document(v3) NoDocument(v0) + * DeleteMutation NoDocument(v3) NoDocument(v0) + * DeleteMutation InvalidDocument(v0) NoDocument(v0) + * + * For acknowledged mutations, we use the updateTime of the WriteResponse as + * the resulting version for Set and Patch mutations. As deletes have no + * explicit update time, we use the commitTime of the WriteResponse for + * Delete mutations. + * + * If a mutation is acknowledged by the backend but fails the precondition check + * locally, we transition to an `UnknownDocument` and rely on Watch to send us + * the updated version. + * + * Field transforms are used only with Patch and Set Mutations. We use the + * `updateTransforms` message to store transforms, rather than the `transforms`s + * messages. + * + * ## Subclassing Notes + * + * Every type of mutation needs to implement its own applyToRemoteDocument() and + * applyToLocalView() to implement the actual behavior of applying the mutation + * to some source document (see `setMutationApplyToRemoteDocument()` for an + * example). + */ class Mutation {} + +/** + * A utility method to calculate a `Mutation` representing the overlay from the + * final state of the document, and a `FieldMask` representing the fields that + * are mutated by the local mutations. + */ function __PRIVATE_calculateOverlayMutation(e, t) { + if (!e.hasLocalMutations || t && 0 === t.fields.length) return null; + // mask is null when sets or deletes are applied to the current document. + if (null === t) return e.isNoDocument() ? new __PRIVATE_DeleteMutation(e.key, Precondition.none()) : new __PRIVATE_SetMutation(e.key, e.data, Precondition.none()); + { + const n = e.data, r = ObjectValue.empty(); + let i = new SortedSet(FieldPath$1.comparator); + for (let e of t.fields) if (!i.has(e)) { + let t = n.field(e); + // If we are deleting a nested field, we take the immediate parent as + // the mask used to construct the resulting mutation. + // Justification: Nested fields can create parent fields implicitly. If + // only a leaf entry is deleted in later mutations, the parent field + // should still remain, but we may have lost this information. + // Consider mutation (foo.bar 1), then mutation (foo.bar delete()). + // This leaves the final result (foo, {}). Despite the fact that `doc` + // has the correct result, `foo` is not in `mask`, and the resulting + // mutation would miss `foo`. + null === t && e.length > 1 && (e = e.popLast(), t = n.field(e)), null === t ? r.delete(e) : r.set(e, t), + i = i.add(e); + } + return new __PRIVATE_PatchMutation(e.key, r, new FieldMask(i.toArray()), Precondition.none()); + } +} + +/** + * Applies this mutation to the given document for the purposes of computing a + * new remote document. If the input document doesn't match the expected state + * (e.g. it is invalid or outdated), the document type may transition to + * unknown. + * + * @param mutation - The mutation to apply. + * @param document - The document to mutate. The input document can be an + * invalid document if the client has no knowledge of the pre-mutation state + * of the document. + * @param mutationResult - The result of applying the mutation from the backend. + */ function __PRIVATE_mutationApplyToRemoteDocument(e, t, n) { + e instanceof __PRIVATE_SetMutation ? function __PRIVATE_setMutationApplyToRemoteDocument(e, t, n) { + // Unlike setMutationApplyToLocalView, if we're applying a mutation to a + // remote document the server has accepted the mutation so the precondition + // must have held. + const r = e.value.clone(), i = __PRIVATE_serverTransformResults(e.fieldTransforms, t, n.transformResults); + r.setAll(i), t.convertToFoundDocument(n.version, r).setHasCommittedMutations(); + }(e, t, n) : e instanceof __PRIVATE_PatchMutation ? function __PRIVATE_patchMutationApplyToRemoteDocument(e, t, n) { + if (!__PRIVATE_preconditionIsValidForDocument(e.precondition, t)) + // Since the mutation was not rejected, we know that the precondition + // matched on the backend. We therefore must not have the expected version + // of the document in our cache and convert to an UnknownDocument with a + // known updateTime. + return void t.convertToUnknownDocument(n.version); + const r = __PRIVATE_serverTransformResults(e.fieldTransforms, t, n.transformResults), i = t.data; + i.setAll(__PRIVATE_getPatch(e)), i.setAll(r), t.convertToFoundDocument(n.version, i).setHasCommittedMutations(); + }(e, t, n) : function __PRIVATE_deleteMutationApplyToRemoteDocument(e, t, n) { + // Unlike applyToLocalView, if we're applying a mutation to a remote + // document the server has accepted the mutation so the precondition must + // have held. + t.convertToNoDocument(n.version).setHasCommittedMutations(); + }(0, t, n); +} + +/** + * Applies this mutation to the given document for the purposes of computing + * the new local view of a document. If the input document doesn't match the + * expected state, the document is not modified. + * + * @param mutation - The mutation to apply. + * @param document - The document to mutate. The input document can be an + * invalid document if the client has no knowledge of the pre-mutation state + * of the document. + * @param previousMask - The fields that have been updated before applying this mutation. + * @param localWriteTime - A timestamp indicating the local write time of the + * batch this mutation is a part of. + * @returns A `FieldMask` representing the fields that are changed by applying this mutation. + */ function __PRIVATE_mutationApplyToLocalView(e, t, n, r) { + return e instanceof __PRIVATE_SetMutation ? function __PRIVATE_setMutationApplyToLocalView(e, t, n, r) { + if (!__PRIVATE_preconditionIsValidForDocument(e.precondition, t)) + // The mutation failed to apply (e.g. a document ID created with add() + // caused a name collision). + return n; + const i = e.value.clone(), s = __PRIVATE_localTransformResults(e.fieldTransforms, r, t); + return i.setAll(s), t.convertToFoundDocument(t.version, i).setHasLocalMutations(), + null; + // SetMutation overwrites all fields. + } + /** + * A mutation that modifies fields of the document at the given key with the + * given values. The values are applied through a field mask: + * + * * When a field is in both the mask and the values, the corresponding field + * is updated. + * * When a field is in neither the mask nor the values, the corresponding + * field is unmodified. + * * When a field is in the mask but not in the values, the corresponding field + * is deleted. + * * When a field is not in the mask but is in the values, the values map is + * ignored. + */ (e, t, n, r) : e instanceof __PRIVATE_PatchMutation ? function __PRIVATE_patchMutationApplyToLocalView(e, t, n, r) { + if (!__PRIVATE_preconditionIsValidForDocument(e.precondition, t)) return n; + const i = __PRIVATE_localTransformResults(e.fieldTransforms, r, t), s = t.data; + if (s.setAll(__PRIVATE_getPatch(e)), s.setAll(i), t.convertToFoundDocument(t.version, s).setHasLocalMutations(), + null === n) return null; + return n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map((e => e.field))); + } + /** + * Returns a FieldPath/Value map with the content of the PatchMutation. + */ (e, t, n, r) : function __PRIVATE_deleteMutationApplyToLocalView(e, t, n) { + if (__PRIVATE_preconditionIsValidForDocument(e.precondition, t)) return t.convertToNoDocument(t.version).setHasLocalMutations(), + null; + return n; + } + /** + * A mutation that verifies the existence of the document at the given key with + * the provided precondition. + * + * The `verify` operation is only used in Transactions, and this class serves + * primarily to facilitate serialization into protos. + */ (e, t, n); +} + +/** + * If this mutation is not idempotent, returns the base value to persist with + * this mutation. If a base value is returned, the mutation is always applied + * to this base value, even if document has already been updated. + * + * The base value is a sparse object that consists of only the document + * fields for which this mutation contains a non-idempotent transformation + * (e.g. a numeric increment). The provided value guarantees consistent + * behavior for non-idempotent transforms and allow us to return the same + * latency-compensated value even if the backend has already applied the + * mutation. The base value is null for idempotent mutations, as they can be + * re-played even if the backend has already applied them. + * + * @returns a base value to store along with the mutation, or null for + * idempotent mutations. + */ function __PRIVATE_mutationExtractBaseValue(e, t) { + let n = null; + for (const r of e.fieldTransforms) { + const e = t.data.field(r.field), i = __PRIVATE_computeTransformOperationBaseValue(r.transform, e || null); + null != i && (null === n && (n = ObjectValue.empty()), n.set(r.field, i)); + } + return n || null; +} + +function __PRIVATE_mutationEquals(e, t) { + return e.type === t.type && (!!e.key.isEqual(t.key) && (!!e.precondition.isEqual(t.precondition) && (!!function __PRIVATE_fieldTransformsAreEqual(e, t) { + return void 0 === e && void 0 === t || !(!e || !t) && __PRIVATE_arrayEquals(e, t, ((e, t) => __PRIVATE_fieldTransformEquals(e, t))); + }(e.fieldTransforms, t.fieldTransforms) && (0 /* MutationType.Set */ === e.type ? e.value.isEqual(t.value) : 1 /* MutationType.Patch */ !== e.type || e.data.isEqual(t.data) && e.fieldMask.isEqual(t.fieldMask))))); +} + +/** + * A mutation that creates or replaces the document at the given key with the + * object value contents. + */ class __PRIVATE_SetMutation extends Mutation { + constructor(e, t, n, r = []) { + super(), this.key = e, this.value = t, this.precondition = n, this.fieldTransforms = r, + this.type = 0 /* MutationType.Set */; + } + getFieldMask() { + return null; + } +} + +class __PRIVATE_PatchMutation extends Mutation { + constructor(e, t, n, r, i = []) { + super(), this.key = e, this.data = t, this.fieldMask = n, this.precondition = r, + this.fieldTransforms = i, this.type = 1 /* MutationType.Patch */; + } + getFieldMask() { + return this.fieldMask; + } +} + +function __PRIVATE_getPatch(e) { + const t = new Map; + return e.fieldMask.fields.forEach((n => { + if (!n.isEmpty()) { + const r = e.data.field(n); + t.set(n, r); + } + })), t; +} + +/** + * Creates a list of "transform results" (a transform result is a field value + * representing the result of applying a transform) for use after a mutation + * containing transforms has been acknowledged by the server. + * + * @param fieldTransforms - The field transforms to apply the result to. + * @param mutableDocument - The current state of the document after applying all + * previous mutations. + * @param serverTransformResults - The transform results received by the server. + * @returns The transform results list. + */ function __PRIVATE_serverTransformResults(e, t, n) { + const r = new Map; + __PRIVATE_hardAssert(e.length === n.length, 32656, { + Re: n.length, + Ve: e.length + }); + for (let i = 0; i < n.length; i++) { + const s = e[i], o = s.transform, _ = t.data.field(s.field); + r.set(s.field, __PRIVATE_applyTransformOperationToRemoteDocument(o, _, n[i])); + } + return r; +} + +/** + * Creates a list of "transform results" (a transform result is a field value + * representing the result of applying a transform) for use when applying a + * transform locally. + * + * @param fieldTransforms - The field transforms to apply the result to. + * @param localWriteTime - The local time of the mutation (used to + * generate ServerTimestampValues). + * @param mutableDocument - The document to apply transforms on. + * @returns The transform results list. + */ function __PRIVATE_localTransformResults(e, t, n) { + const r = new Map; + for (const i of e) { + const e = i.transform, s = n.data.field(i.field); + r.set(i.field, __PRIVATE_applyTransformOperationToLocalView(e, s, t)); + } + return r; +} + +/** A mutation that deletes the document at the given key. */ class __PRIVATE_DeleteMutation extends Mutation { + constructor(e, t) { + super(), this.key = e, this.precondition = t, this.type = 2 /* MutationType.Delete */ , + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } +} + +class __PRIVATE_VerifyMutation extends Mutation { + constructor(e, t) { + super(), this.key = e, this.precondition = t, this.type = 3 /* MutationType.Verify */ , + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A batch of mutations that will be sent as one unit to the backend. + */ class MutationBatch { + /** + * @param batchId - The unique ID of this mutation batch. + * @param localWriteTime - The original write time of this mutation. + * @param baseMutations - Mutations that are used to populate the base + * values when this mutation is applied locally. This can be used to locally + * overwrite values that are persisted in the remote document cache. Base + * mutations are never sent to the backend. + * @param mutations - The user-provided mutations in this mutation batch. + * User-provided mutations are applied both locally and remotely on the + * backend. + */ + constructor(e, t, n, r) { + this.batchId = e, this.localWriteTime = t, this.baseMutations = n, this.mutations = r; + } + /** + * Applies all the mutations in this MutationBatch to the specified document + * to compute the state of the remote document + * + * @param document - The document to apply mutations to. + * @param batchResult - The result of applying the MutationBatch to the + * backend. + */ applyToRemoteDocument(e, t) { + const n = t.mutationResults; + for (let t = 0; t < this.mutations.length; t++) { + const r = this.mutations[t]; + if (r.key.isEqual(e.key)) { + __PRIVATE_mutationApplyToRemoteDocument(r, e, n[t]); + } + } + } + /** + * Computes the local view of a document given all the mutations in this + * batch. + * + * @param document - The document to apply mutations to. + * @param mutatedFields - Fields that have been updated before applying this mutation batch. + * @returns A `FieldMask` representing all the fields that are mutated. + */ applyToLocalView(e, t) { + // First, apply the base state. This allows us to apply non-idempotent + // transform against a consistent set of values. + for (const n of this.baseMutations) n.key.isEqual(e.key) && (t = __PRIVATE_mutationApplyToLocalView(n, e, t, this.localWriteTime)); + // Second, apply all user-provided mutations. + for (const n of this.mutations) n.key.isEqual(e.key) && (t = __PRIVATE_mutationApplyToLocalView(n, e, t, this.localWriteTime)); + return t; + } + /** + * Computes the local view for all provided documents given the mutations in + * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to + * replace all the mutation applications. + */ applyToLocalDocumentSet(e, t) { + // TODO(mrschmidt): This implementation is O(n^2). If we apply the mutations + // directly (as done in `applyToLocalView()`), we can reduce the complexity + // to O(n). + const n = __PRIVATE_newMutationMap(); + return this.mutations.forEach((r => { + const i = e.get(r.key), s = i.overlayedDocument; + // TODO(mutabledocuments): This method should take a MutableDocumentMap + // and we should remove this cast. + let o = this.applyToLocalView(s, i.mutatedFields); + // Set mutatedFields to null if the document is only from local mutations. + // This creates a Set or Delete mutation, instead of trying to create a + // patch mutation as the overlay. + o = t.has(r.key) ? null : o; + const _ = __PRIVATE_calculateOverlayMutation(s, o); + null !== _ && n.set(r.key, _), s.isValidDocument() || s.convertToNoDocument(SnapshotVersion.min()); + })), n; + } + keys() { + return this.mutations.reduce(((e, t) => e.add(t.key)), __PRIVATE_documentKeySet()); + } + isEqual(e) { + return this.batchId === e.batchId && __PRIVATE_arrayEquals(this.mutations, e.mutations, ((e, t) => __PRIVATE_mutationEquals(e, t))) && __PRIVATE_arrayEquals(this.baseMutations, e.baseMutations, ((e, t) => __PRIVATE_mutationEquals(e, t))); + } +} + +/** The result of applying a mutation batch to the backend. */ class MutationBatchResult { + constructor(e, t, n, + /** + * A pre-computed mapping from each mutated document to the resulting + * version. + */ + r) { + this.batch = e, this.commitVersion = t, this.mutationResults = n, this.docVersions = r; + } + /** + * Creates a new MutationBatchResult for the given batch and results. There + * must be one result for each mutation in the batch. This static factory + * caches a document=>version mapping (docVersions). + */ static from(e, t, n) { + __PRIVATE_hardAssert(e.mutations.length === n.length, 58842, { + me: e.mutations.length, + fe: n.length + }); + let r = function __PRIVATE_documentVersionMap() { + return mt; + }(); + const i = e.mutations; + for (let e = 0; e < i.length; e++) r = r.insert(i[e].key, n[e].version); + return new MutationBatchResult(e, t, n, r); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Representation of an overlay computed by Firestore. + * + * Holds information about a mutation and the largest batch id in Firestore when + * the mutation was created. + */ class Overlay { + constructor(e, t) { + this.largestBatchId = e, this.mutation = t; + } + getKey() { + return this.mutation.key; + } + isEqual(e) { + return null !== e && this.mutation === e.mutation; + } + toString() { + return `Overlay{\n largestBatchId: ${this.largestBatchId},\n mutation: ${this.mutation.toString()}\n }`; + } +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Concrete implementation of the Aggregate type. + */ class __PRIVATE_AggregateImpl { + constructor(e, t, n) { + this.alias = e, this.aggregateType = t, this.fieldPath = n; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class ExistenceFilter { + constructor(e, t) { + this.count = e, this.unchangedNames = t; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Error Codes describing the different ways GRPC can fail. These are copied + * directly from GRPC's sources here: + * + * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h + * + * Important! The names of these identifiers matter because the string forms + * are used for reverse lookups from the webchannel stream. Do NOT change the + * names of these identifiers or change this into a const enum. + */ var pt, yt; + +/** + * Determines whether an error code represents a permanent error when received + * in response to a non-write operation. + * + * See isPermanentWriteError for classifying write errors. + */ +function __PRIVATE_isPermanentError(e) { + switch (e) { + case N.OK: + return fail(64938); + + case N.CANCELLED: + case N.UNKNOWN: + case N.DEADLINE_EXCEEDED: + case N.RESOURCE_EXHAUSTED: + case N.INTERNAL: + case N.UNAVAILABLE: + // Unauthenticated means something went wrong with our token and we need + // to retry with new credentials which will happen automatically. + case N.UNAUTHENTICATED: + return !1; + + case N.INVALID_ARGUMENT: + case N.NOT_FOUND: + case N.ALREADY_EXISTS: + case N.PERMISSION_DENIED: + case N.FAILED_PRECONDITION: + // Aborted might be retried in some scenarios, but that is dependent on + // the context and should handled individually by the calling code. + // See https://cloud.google.com/apis/design/errors. + case N.ABORTED: + case N.OUT_OF_RANGE: + case N.UNIMPLEMENTED: + case N.DATA_LOSS: + return !0; + + default: + return fail(15467, { + code: e + }); + } +} + +/** + * Determines whether an error code represents a permanent error when received + * in response to a write operation. + * + * Write operations must be handled specially because as of b/119437764, ABORTED + * errors on the write stream should be retried too (even though ABORTED errors + * are not generally retryable). + * + * Note that during the initial handshake on the write stream an ABORTED error + * signals that we should discard our stream token (i.e. it is permanent). This + * means a handshake error should be classified with isPermanentError, above. + */ +/** + * Maps an error Code from GRPC status code number, like 0, 1, or 14. These + * are not the same as HTTP status codes. + * + * @returns The Code equivalent to the given GRPC status code. Fails if there + * is no match. + */ +function __PRIVATE_mapCodeFromRpcCode(e) { + if (void 0 === e) + // This shouldn't normally happen, but in certain error cases (like trying + // to send invalid proto messages) we may get an error with no GRPC code. + return __PRIVATE_logError("GRPC error has no .code"), N.UNKNOWN; + switch (e) { + case pt.OK: + return N.OK; + + case pt.CANCELLED: + return N.CANCELLED; + + case pt.UNKNOWN: + return N.UNKNOWN; + + case pt.DEADLINE_EXCEEDED: + return N.DEADLINE_EXCEEDED; + + case pt.RESOURCE_EXHAUSTED: + return N.RESOURCE_EXHAUSTED; + + case pt.INTERNAL: + return N.INTERNAL; + + case pt.UNAVAILABLE: + return N.UNAVAILABLE; + + case pt.UNAUTHENTICATED: + return N.UNAUTHENTICATED; + + case pt.INVALID_ARGUMENT: + return N.INVALID_ARGUMENT; + + case pt.NOT_FOUND: + return N.NOT_FOUND; + + case pt.ALREADY_EXISTS: + return N.ALREADY_EXISTS; + + case pt.PERMISSION_DENIED: + return N.PERMISSION_DENIED; + + case pt.FAILED_PRECONDITION: + return N.FAILED_PRECONDITION; + + case pt.ABORTED: + return N.ABORTED; + + case pt.OUT_OF_RANGE: + return N.OUT_OF_RANGE; + + case pt.UNIMPLEMENTED: + return N.UNIMPLEMENTED; + + case pt.DATA_LOSS: + return N.DATA_LOSS; + + default: + return fail(39323, { + code: e + }); + } +} + +/** + * Converts an HTTP response's error status to the equivalent error code. + * + * @param status - An HTTP error response status ("FAILED_PRECONDITION", + * "UNKNOWN", etc.) + * @returns The equivalent Code. Non-matching responses are mapped to + * Code.UNKNOWN. + */ (yt = pt || (pt = {}))[yt.OK = 0] = "OK", yt[yt.CANCELLED = 1] = "CANCELLED", +yt[yt.UNKNOWN = 2] = "UNKNOWN", yt[yt.INVALID_ARGUMENT = 3] = "INVALID_ARGUMENT", +yt[yt.DEADLINE_EXCEEDED = 4] = "DEADLINE_EXCEEDED", yt[yt.NOT_FOUND = 5] = "NOT_FOUND", +yt[yt.ALREADY_EXISTS = 6] = "ALREADY_EXISTS", yt[yt.PERMISSION_DENIED = 7] = "PERMISSION_DENIED", +yt[yt.UNAUTHENTICATED = 16] = "UNAUTHENTICATED", yt[yt.RESOURCE_EXHAUSTED = 8] = "RESOURCE_EXHAUSTED", +yt[yt.FAILED_PRECONDITION = 9] = "FAILED_PRECONDITION", yt[yt.ABORTED = 10] = "ABORTED", +yt[yt.OUT_OF_RANGE = 11] = "OUT_OF_RANGE", yt[yt.UNIMPLEMENTED = 12] = "UNIMPLEMENTED", +yt[yt.INTERNAL = 13] = "INTERNAL", yt[yt.UNAVAILABLE = 14] = "UNAVAILABLE", yt[yt.DATA_LOSS = 15] = "DATA_LOSS"; + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The global, singleton instance of TestingHooksSpi. + * + * This variable will be `null` in all cases _except_ when running from + * integration tests that have registered callbacks to be notified of events + * that happen during the test execution. + */ +let wt = null; + +/** + * Sets the value of the `testingHooksSpi` object. + * @param instance the instance to set. + */ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An instance of the Platform's 'TextEncoder' implementation. + */ +function __PRIVATE_newTextEncoder() { + return new TextEncoder; +} + +/** + * An instance of the Platform's 'TextDecoder' implementation. + */ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const St = new bloomBlob.Integer([ 4294967295, 4294967295 ], 0); + +// Hash a string using md5 hashing algorithm. +function __PRIVATE_getMd5HashValue(e) { + const t = __PRIVATE_newTextEncoder().encode(e), n = new bloomBlob.Md5; + return n.update(t), new Uint8Array(n.digest()); +} + +// Interpret the 16 bytes array as two 64-bit unsigned integers, encoded using +// 2’s complement using little endian. +function __PRIVATE_get64BitUints(e) { + const t = new DataView(e.buffer), n = t.getUint32(0, /* littleEndian= */ !0), r = t.getUint32(4, /* littleEndian= */ !0), i = t.getUint32(8, /* littleEndian= */ !0), s = t.getUint32(12, /* littleEndian= */ !0); + return [ new bloomBlob.Integer([ n, r ], 0), new bloomBlob.Integer([ i, s ], 0) ]; +} + +class BloomFilter { + constructor(e, t, n) { + if (this.bitmap = e, this.padding = t, this.hashCount = n, t < 0 || t >= 8) throw new __PRIVATE_BloomFilterError(`Invalid padding: ${t}`); + if (n < 0) throw new __PRIVATE_BloomFilterError(`Invalid hash count: ${n}`); + if (e.length > 0 && 0 === this.hashCount) + // Only empty bloom filter can have 0 hash count. + throw new __PRIVATE_BloomFilterError(`Invalid hash count: ${n}`); + if (0 === e.length && 0 !== t) + // Empty bloom filter should have 0 padding. + throw new __PRIVATE_BloomFilterError(`Invalid padding when bitmap length is 0: ${t}`); + this.ge = 8 * e.length - t, + // Set the bit count in Integer to avoid repetition in mightContain(). + this.pe = bloomBlob.Integer.fromNumber(this.ge); + } + // Calculate the ith hash value based on the hashed 64bit integers, + // and calculate its corresponding bit index in the bitmap to be checked. + ye(e, t, n) { + // Calculate hashed value h(i) = h1 + (i * h2). + let r = e.add(t.multiply(bloomBlob.Integer.fromNumber(n))); + // Wrap if hash value overflow 64bit. + return 1 === r.compare(St) && (r = new bloomBlob.Integer([ r.getBits(0), r.getBits(1) ], 0)), + r.modulo(this.pe).toNumber(); + } + // Return whether the bit on the given index in the bitmap is set to 1. + we(e) { + return !!(this.bitmap[Math.floor(e / 8)] & 1 << e % 8); + } + mightContain(e) { + // Empty bitmap should always return false on membership check. + if (0 === this.ge) return !1; + const t = __PRIVATE_getMd5HashValue(e), [n, r] = __PRIVATE_get64BitUints(t); + for (let e = 0; e < this.hashCount; e++) { + const t = this.ye(n, r, e); + if (!this.we(t)) return !1; + } + return !0; + } + /** Create bloom filter for testing purposes only. */ static create(e, t, n) { + const r = e % 8 == 0 ? 0 : 8 - e % 8, i = new Uint8Array(Math.ceil(e / 8)), s = new BloomFilter(i, r, t); + return n.forEach((e => s.insert(e))), s; + } + insert(e) { + if (0 === this.ge) return; + const t = __PRIVATE_getMd5HashValue(e), [n, r] = __PRIVATE_get64BitUints(t); + for (let e = 0; e < this.hashCount; e++) { + const t = this.ye(n, r, e); + this.Se(t); + } + } + Se(e) { + const t = Math.floor(e / 8), n = e % 8; + this.bitmap[t] |= 1 << n; + } +} + +class __PRIVATE_BloomFilterError extends Error { + constructor() { + super(...arguments), this.name = "BloomFilterError"; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An event from the RemoteStore. It is split into targetChanges (changes to the + * state or the set of documents in our watched targets) and documentUpdates + * (changes to the actual documents). + */ class RemoteEvent { + constructor( + /** + * The snapshot version this event brings us up to, or MIN if not set. + */ + e, + /** + * A map from target to changes to the target. See TargetChange. + */ + t, + /** + * A map of targets that is known to be inconsistent, and the purpose for + * re-listening. Listens for these targets should be re-established without + * resume tokens. + */ + n, + /** + * A set of which documents have changed or been deleted, along with the + * doc's new values (if not deleted). + */ + r, + /** + * A set of which document updates are due only to limbo resolution targets. + */ + i) { + this.snapshotVersion = e, this.targetChanges = t, this.targetMismatches = n, this.documentUpdates = r, + this.resolvedLimboDocuments = i; + } + /** + * HACK: Views require RemoteEvents in order to determine whether the view is + * CURRENT, but secondary tabs don't receive remote events. So this method is + * used to create a synthesized RemoteEvent that can be used to apply a + * CURRENT status change to a View, for queries executed in a different tab. + */ + // PORTING NOTE: Multi-tab only + static createSynthesizedRemoteEventForCurrentChange(e, t, n) { + const r = new Map; + return r.set(e, TargetChange.createSynthesizedTargetChangeForCurrentChange(e, t, n)), + new RemoteEvent(SnapshotVersion.min(), r, new SortedMap(__PRIVATE_primitiveComparator), __PRIVATE_mutableDocumentMap(), __PRIVATE_documentKeySet()); + } +} + +/** + * A TargetChange specifies the set of changes for a specific target as part of + * a RemoteEvent. These changes track which documents are added, modified or + * removed, as well as the target's resume token and whether the target is + * marked CURRENT. + * The actual changes *to* documents are not part of the TargetChange since + * documents may be part of multiple targets. + */ class TargetChange { + constructor( + /** + * An opaque, server-assigned token that allows watching a query to be resumed + * after disconnecting without retransmitting all the data that matches the + * query. The resume token essentially identifies a point in time from which + * the server should resume sending results. + */ + e, + /** + * The "current" (synced) status of this target. Note that "current" + * has special meaning in the RPC protocol that implies that a target is + * both up-to-date and consistent with the rest of the watch stream. + */ + t, + /** + * The set of documents that were newly assigned to this target as part of + * this remote event. + */ + n, + /** + * The set of documents that were already assigned to this target but received + * an update during this remote event. + */ + r, + /** + * The set of documents that were removed from this target as part of this + * remote event. + */ + i) { + this.resumeToken = e, this.current = t, this.addedDocuments = n, this.modifiedDocuments = r, + this.removedDocuments = i; + } + /** + * This method is used to create a synthesized TargetChanges that can be used to + * apply a CURRENT status change to a View (for queries executed in a different + * tab) or for new queries (to raise snapshots with correct CURRENT status). + */ static createSynthesizedTargetChangeForCurrentChange(e, t, n) { + return new TargetChange(n, t, __PRIVATE_documentKeySet(), __PRIVATE_documentKeySet(), __PRIVATE_documentKeySet()); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a changed document and a list of target ids to which this change + * applies. + * + * If document has been deleted NoDocument will be provided. + */ class __PRIVATE_DocumentWatchChange { + constructor( + /** The new document applies to all of these targets. */ + e, + /** The new document is removed from all of these targets. */ + t, + /** The key of the document for this change. */ + n, + /** + * The new document or NoDocument if it was deleted. Is null if the + * document went out of view without the server sending a new document. + */ + r) { + this.be = e, this.removedTargetIds = t, this.key = n, this.De = r; + } +} + +class __PRIVATE_ExistenceFilterChange { + constructor(e, t) { + this.targetId = e, this.Ce = t; + } +} + +class __PRIVATE_WatchTargetChange { + constructor( + /** What kind of change occurred to the watch target. */ + e, + /** The target IDs that were added/removed/set. */ + t, + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + n = ByteString.EMPTY_BYTE_STRING + /** An RPC error indicating why the watch failed. */ , r = null) { + this.state = e, this.targetIds = t, this.resumeToken = n, this.cause = r; + } +} + +/** Tracks the internal state of a Watch target. */ class __PRIVATE_TargetState { + constructor() { + /** + * The number of pending responses (adds or removes) that we are waiting on. + * We only consider targets active that have no pending responses. + */ + this.ve = 0, + /** + * Keeps track of the document changes since the last raised snapshot. + * + * These changes are continuously updated as we receive document updates and + * always reflect the current set of changes against the last issued snapshot. + */ + this.Fe = __PRIVATE_snapshotChangesMap(), + /** See public getters for explanations of these fields. */ + this.Me = ByteString.EMPTY_BYTE_STRING, this.xe = !1, + /** + * Whether this target state should be included in the next snapshot. We + * initialize to true so that newly-added targets are included in the next + * RemoteEvent. + */ + this.Oe = !0; + } + /** + * Whether this target has been marked 'current'. + * + * 'Current' has special meaning in the RPC protocol: It implies that the + * Watch backend has sent us all changes up to the point at which the target + * was added and that the target is consistent with the rest of the watch + * stream. + */ get current() { + return this.xe; + } + /** The last resume token sent to us for this target. */ get resumeToken() { + return this.Me; + } + /** Whether this target has pending target adds or target removes. */ get Ne() { + return 0 !== this.ve; + } + /** Whether we have modified any state that should trigger a snapshot. */ get Be() { + return this.Oe; + } + /** + * Applies the resume token to the TargetChange, but only when it has a new + * value. Empty resumeTokens are discarded. + */ Le(e) { + e.approximateByteSize() > 0 && (this.Oe = !0, this.Me = e); + } + /** + * Creates a target change from the current set of changes. + * + * To reset the document changes after raising this snapshot, call + * `clearPendingChanges()`. + */ ke() { + let e = __PRIVATE_documentKeySet(), t = __PRIVATE_documentKeySet(), n = __PRIVATE_documentKeySet(); + return this.Fe.forEach(((r, i) => { + switch (i) { + case 0 /* ChangeType.Added */ : + e = e.add(r); + break; + + case 2 /* ChangeType.Modified */ : + t = t.add(r); + break; + + case 1 /* ChangeType.Removed */ : + n = n.add(r); + break; + + default: + fail(38017, { + changeType: i + }); + } + })), new TargetChange(this.Me, this.xe, e, t, n); + } + /** + * Resets the document changes and sets `hasPendingChanges` to false. + */ qe() { + this.Oe = !1, this.Fe = __PRIVATE_snapshotChangesMap(); + } + Qe(e, t) { + this.Oe = !0, this.Fe = this.Fe.insert(e, t); + } + $e(e) { + this.Oe = !0, this.Fe = this.Fe.remove(e); + } + Ue() { + this.ve += 1; + } + Ke() { + this.ve -= 1, __PRIVATE_hardAssert(this.ve >= 0, 3241, { + ve: this.ve + }); + } + We() { + this.Oe = !0, this.xe = !0; + } +} + +/** + * A helper class to accumulate watch changes into a RemoteEvent. + */ +class __PRIVATE_WatchChangeAggregator { + constructor(e) { + this.Ge = e, + /** The internal state of all tracked targets. */ + this.ze = new Map, + /** Keeps track of the documents to update since the last raised snapshot. */ + this.je = __PRIVATE_mutableDocumentMap(), this.Je = __PRIVATE_documentTargetMap(), + /** A mapping of document keys to their set of target IDs. */ + this.He = __PRIVATE_documentTargetMap(), + /** + * A map of targets with existence filter mismatches. These targets are + * known to be inconsistent and their listens needs to be re-established by + * RemoteStore. + */ + this.Ye = new SortedMap(__PRIVATE_primitiveComparator); + } + /** + * Processes and adds the DocumentWatchChange to the current set of changes. + */ Ze(e) { + for (const t of e.be) e.De && e.De.isFoundDocument() ? this.Xe(t, e.De) : this.et(t, e.key, e.De); + for (const t of e.removedTargetIds) this.et(t, e.key, e.De); + } + /** Processes and adds the WatchTargetChange to the current set of changes. */ tt(e) { + this.forEachTarget(e, (t => { + const n = this.nt(t); + switch (e.state) { + case 0 /* WatchTargetChangeState.NoChange */ : + this.rt(t) && n.Le(e.resumeToken); + break; + + case 1 /* WatchTargetChangeState.Added */ : + // We need to decrement the number of pending acks needed from watch + // for this targetId. + n.Ke(), n.Ne || + // We have a freshly added target, so we need to reset any state + // that we had previously. This can happen e.g. when remove and add + // back a target for existence filter mismatches. + n.qe(), n.Le(e.resumeToken); + break; + + case 2 /* WatchTargetChangeState.Removed */ : + // We need to keep track of removed targets to we can post-filter and + // remove any target changes. + // We need to decrement the number of pending acks needed from watch + // for this targetId. + n.Ke(), n.Ne || this.removeTarget(t); + break; + + case 3 /* WatchTargetChangeState.Current */ : + this.rt(t) && (n.We(), n.Le(e.resumeToken)); + break; + + case 4 /* WatchTargetChangeState.Reset */ : + this.rt(t) && ( + // Reset the target and synthesizes removes for all existing + // documents. The backend will re-add any documents that still + // match the target before it sends the next global snapshot. + this.it(t), n.Le(e.resumeToken)); + break; + + default: + fail(56790, { + state: e.state + }); + } + })); + } + /** + * Iterates over all targetIds that the watch change applies to: either the + * targetIds explicitly listed in the change or the targetIds of all currently + * active targets. + */ forEachTarget(e, t) { + e.targetIds.length > 0 ? e.targetIds.forEach(t) : this.ze.forEach(((e, n) => { + this.rt(n) && t(n); + })); + } + /** + * Handles existence filters and synthesizes deletes for filter mismatches. + * Targets that are invalidated by filter mismatches are added to + * `pendingTargetResets`. + */ st(e) { + const t = e.targetId, n = e.Ce.count, r = this.ot(t); + if (r) { + const i = r.target; + if (__PRIVATE_targetIsDocumentTarget(i)) if (0 === n) { + // The existence filter told us the document does not exist. We deduce + // that this document does not exist and apply a deleted document to + // our updates. Without applying this deleted document there might be + // another query that will raise this document as part of a snapshot + // until it is resolved, essentially exposing inconsistency between + // queries. + const e = new DocumentKey(i.path); + this.et(t, e, MutableDocument.newNoDocument(e, SnapshotVersion.min())); + } else __PRIVATE_hardAssert(1 === n, 20013, { + expectedCount: n + }); else { + const r = this._t(t); + // Existence filter mismatch. Mark the documents as being in limbo, and + // raise a snapshot with `isFromCache:true`. + if (r !== n) { + // Apply bloom filter to identify and mark removed documents. + const n = this.ut(e), i = n ? this.ct(n, e, r) : 1 /* BloomFilterApplicationStatus.Skipped */; + if (0 /* BloomFilterApplicationStatus.Success */ !== i) { + // If bloom filter application fails, we reset the mapping and + // trigger re-run of the query. + this.it(t); + const e = 2 /* BloomFilterApplicationStatus.FalsePositive */ === i ? "TargetPurposeExistenceFilterMismatchBloom" /* TargetPurpose.ExistenceFilterMismatchBloom */ : "TargetPurposeExistenceFilterMismatch" /* TargetPurpose.ExistenceFilterMismatch */; + this.Ye = this.Ye.insert(t, e); + } + wt?.lt(function __PRIVATE_createExistenceFilterMismatchInfoForTestingHooks(e, t, n, r, i) { + const s = { + localCacheCount: e, + existenceFilterCount: t.count, + databaseId: n.database, + projectId: n.projectId + }, o = t.unchangedNames; + o && (s.bloomFilter = { + applied: 0 /* BloomFilterApplicationStatus.Success */ === i, + hashCount: o?.hashCount ?? 0, + bitmapLength: o?.bits?.bitmap?.length ?? 0, + padding: o?.bits?.padding ?? 0, + mightContain: e => r?.mightContain(e) ?? !1 + }); + return s; + } + /** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ (r, e.Ce, this.Ge.ht(), n, i)); + } + } + } + } + /** + * Parse the bloom filter from the "unchanged_names" field of an existence + * filter. + */ ut(e) { + const t = e.Ce.unchangedNames; + if (!t || !t.bits) return null; + const {bits: {bitmap: n = "", padding: r = 0}, hashCount: i = 0} = t; + let s, o; + try { + s = __PRIVATE_normalizeByteString(n).toUint8Array(); + } catch (e) { + if (e instanceof __PRIVATE_Base64DecodeError) return __PRIVATE_logWarn("Decoding the base64 bloom filter in existence filter failed (" + e.message + "); ignoring the bloom filter and falling back to full re-query."), + null; + throw e; + } + try { + // BloomFilter throws error if the inputs are invalid. + o = new BloomFilter(s, r, i); + } catch (e) { + return __PRIVATE_logWarn(e instanceof __PRIVATE_BloomFilterError ? "BloomFilter error: " : "Applying bloom filter failed: ", e), + null; + } + return 0 === o.ge ? null : o; + } + /** + * Apply bloom filter to remove the deleted documents, and return the + * application status. + */ ct(e, t, n) { + return t.Ce.count === n - this.Pt(e, t.targetId) ? 0 /* BloomFilterApplicationStatus.Success */ : 2 /* BloomFilterApplicationStatus.FalsePositive */; + } + /** + * Filter out removed documents based on bloom filter membership result and + * return number of documents removed. + */ Pt(e, t) { + const n = this.Ge.getRemoteKeysForTarget(t); + let r = 0; + return n.forEach((n => { + const i = this.Ge.ht(), s = `projects/${i.projectId}/databases/${i.database}/documents/${n.path.canonicalString()}`; + e.mightContain(s) || (this.et(t, n, /*updatedDocument=*/ null), r++); + })), r; + } + /** + * Converts the currently accumulated state into a remote event at the + * provided snapshot version. Resets the accumulated changes before returning. + */ Tt(e) { + const t = new Map; + this.ze.forEach(((n, r) => { + const i = this.ot(r); + if (i) { + if (n.current && __PRIVATE_targetIsDocumentTarget(i.target)) { + // Document queries for document that don't exist can produce an empty + // result set. To update our local cache, we synthesize a document + // delete if we have not previously received the document for this + // target. This resolves the limbo state of the document, removing it + // from limboDocumentRefs. + // TODO(dimond): Ideally we would have an explicit lookup target + // instead resulting in an explicit delete message and we could + // remove this special logic. + const t = new DocumentKey(i.target.path); + this.It(t).has(r) || this.Et(r, t) || this.et(r, t, MutableDocument.newNoDocument(t, e)); + } + n.Be && (t.set(r, n.ke()), n.qe()); + } + })); + let n = __PRIVATE_documentKeySet(); + // We extract the set of limbo-only document updates as the GC logic + // special-cases documents that do not appear in the target cache. + + // TODO(gsoltis): Expand on this comment once GC is available in the JS + // client. + this.He.forEach(((e, t) => { + let r = !0; + t.forEachWhile((e => { + const t = this.ot(e); + return !t || "TargetPurposeLimboResolution" /* TargetPurpose.LimboResolution */ === t.purpose || (r = !1, + !1); + })), r && (n = n.add(e)); + })), this.je.forEach(((t, n) => n.setReadTime(e))); + const r = new RemoteEvent(e, t, this.Ye, this.je, n); + return this.je = __PRIVATE_mutableDocumentMap(), this.Je = __PRIVATE_documentTargetMap(), + this.He = __PRIVATE_documentTargetMap(), this.Ye = new SortedMap(__PRIVATE_primitiveComparator), + r; + } + /** + * Adds the provided document to the internal list of document updates and + * its document key to the given target's mapping. + */ + // Visible for testing. + Xe(e, t) { + if (!this.rt(e)) return; + const n = this.Et(e, t.key) ? 2 /* ChangeType.Modified */ : 0 /* ChangeType.Added */; + this.nt(e).Qe(t.key, n), this.je = this.je.insert(t.key, t), this.Je = this.Je.insert(t.key, this.It(t.key).add(e)), + this.He = this.He.insert(t.key, this.dt(t.key).add(e)); + } + /** + * Removes the provided document from the target mapping. If the + * document no longer matches the target, but the document's state is still + * known (e.g. we know that the document was deleted or we received the change + * that caused the filter mismatch), the new document can be provided + * to update the remote document cache. + */ + // Visible for testing. + et(e, t, n) { + if (!this.rt(e)) return; + const r = this.nt(e); + this.Et(e, t) ? r.Qe(t, 1 /* ChangeType.Removed */) : + // The document may have entered and left the target before we raised a + // snapshot, so we can just ignore the change. + r.$e(t), this.He = this.He.insert(t, this.dt(t).delete(e)), this.He = this.He.insert(t, this.dt(t).add(e)), + n && (this.je = this.je.insert(t, n)); + } + removeTarget(e) { + this.ze.delete(e); + } + /** + * Returns the current count of documents in the target. This includes both + * the number of documents that the LocalStore considers to be part of the + * target as well as any accumulated changes. + */ _t(e) { + const t = this.nt(e).ke(); + return this.Ge.getRemoteKeysForTarget(e).size + t.addedDocuments.size - t.removedDocuments.size; + } + /** + * Increment the number of acks needed from watch before we can consider the + * server to be 'in-sync' with the client's active targets. + */ Ue(e) { + this.nt(e).Ue(); + } + nt(e) { + let t = this.ze.get(e); + return t || (t = new __PRIVATE_TargetState, this.ze.set(e, t)), t; + } + dt(e) { + let t = this.He.get(e); + return t || (t = new SortedSet(__PRIVATE_primitiveComparator), this.He = this.He.insert(e, t)), + t; + } + It(e) { + let t = this.Je.get(e); + return t || (t = new SortedSet(__PRIVATE_primitiveComparator), this.Je = this.Je.insert(e, t)), + t; + } + /** + * Verifies that the user is still interested in this target (by calling + * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs + * from watch. + */ rt(e) { + const t = null !== this.ot(e); + return t || __PRIVATE_logDebug("WatchChangeAggregator", "Detected inactive target", e), + t; + } + /** + * Returns the TargetData for an active target (i.e. a target that the user + * is still interested in that has no outstanding target change requests). + */ ot(e) { + const t = this.ze.get(e); + return t && t.Ne ? null : this.Ge.At(e); + } + /** + * Resets the state of a Watch target to its initial state (e.g. sets + * 'current' to false, clears the resume token and removes its target mapping + * from all documents). + */ it(e) { + this.ze.set(e, new __PRIVATE_TargetState); + this.Ge.getRemoteKeysForTarget(e).forEach((t => { + this.et(e, t, /*updatedDocument=*/ null); + })); + } + /** + * Returns whether the LocalStore considers the document to be part of the + * specified target. + */ Et(e, t) { + return this.Ge.getRemoteKeysForTarget(e).has(t); + } +} + +function __PRIVATE_documentTargetMap() { + return new SortedMap(DocumentKey.comparator); +} + +function __PRIVATE_snapshotChangesMap() { + return new SortedMap(DocumentKey.comparator); +} + +const bt = (() => { + const e = { + asc: "ASCENDING", + desc: "DESCENDING" + }; + return e; +})(), Dt = (() => { + const e = { + "<": "LESS_THAN", + "<=": "LESS_THAN_OR_EQUAL", + ">": "GREATER_THAN", + ">=": "GREATER_THAN_OR_EQUAL", + "==": "EQUAL", + "!=": "NOT_EQUAL", + "array-contains": "ARRAY_CONTAINS", + in: "IN", + "not-in": "NOT_IN", + "array-contains-any": "ARRAY_CONTAINS_ANY" + }; + return e; +})(), Ct = (() => { + const e = { + and: "AND", + or: "OR" + }; + return e; +})(); + +/** + * This class generates JsonObject values for the Datastore API suitable for + * sending to either GRPC stub methods or via the JSON/HTTP REST API. + * + * The serializer supports both Protobuf.js and Proto3 JSON formats. By + * setting `useProto3Json` to true, the serializer will use the Proto3 JSON + * format. + * + * For a description of the Proto3 JSON format check + * https://developers.google.com/protocol-buffers/docs/proto3#json + * + * TODO(klimt): We can remove the databaseId argument if we keep the full + * resource name in documents. + */ +class JsonProtoSerializer { + constructor(e, t) { + this.databaseId = e, this.useProto3Json = t; + } +} + +/** + * Returns a value for a number (or null) that's appropriate to put into + * a google.protobuf.Int32Value proto. + * DO NOT USE THIS FOR ANYTHING ELSE. + * This method cheats. It's typed as returning "number" because that's what + * our generated proto interfaces say Int32Value must be. But GRPC actually + * expects a { value: } struct. + */ +function __PRIVATE_toInt32Proto(e, t) { + return e.useProto3Json || __PRIVATE_isNullOrUndefined(t) ? t : { + value: t + }; +} + +/** + * Returns a number (or null) from a google.protobuf.Int32Value proto. + */ +/** + * Returns a value for a Date that's appropriate to put into a proto. + */ +function toTimestamp(e, t) { + if (e.useProto3Json) { + return `${new Date(1e3 * t.seconds).toISOString().replace(/\.\d*/, "").replace("Z", "")}.${("000000000" + t.nanoseconds).slice(-9)}Z`; + } + return { + seconds: "" + t.seconds, + nanos: t.nanoseconds + }; +} + +/** + * Returns a Timestamp typed object given protobuf timestamp value. + */ +/** + * Returns a value for bytes that's appropriate to put in a proto. + * + * Visible for testing. + */ +function __PRIVATE_toBytes(e, t) { + return e.useProto3Json ? t.toBase64() : t.toUint8Array(); +} + +/** + * Returns a ByteString based on the proto string value. + */ function __PRIVATE_toVersion(e, t) { + return toTimestamp(e, t.toTimestamp()); +} + +function __PRIVATE_fromVersion(e) { + return __PRIVATE_hardAssert(!!e, 49232), SnapshotVersion.fromTimestamp(function fromTimestamp(e) { + const t = __PRIVATE_normalizeTimestamp(e); + return new Timestamp(t.seconds, t.nanos); + }(e)); +} + +function __PRIVATE_toResourceName(e, t) { + return __PRIVATE_toResourcePath(e, t).canonicalString(); +} + +function __PRIVATE_toResourcePath(e, t) { + const n = function __PRIVATE_fullyQualifiedPrefixPath(e) { + return new ResourcePath([ "projects", e.projectId, "databases", e.database ]); + }(e).child("documents"); + return void 0 === t ? n : n.child(t); +} + +function __PRIVATE_fromResourceName(e) { + const t = ResourcePath.fromString(e); + return __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(t), 10190, { + key: t.toString() + }), t; +} + +function __PRIVATE_toName(e, t) { + return __PRIVATE_toResourceName(e.databaseId, t.path); +} + +function fromName(e, t) { + const n = __PRIVATE_fromResourceName(t); + if (n.get(1) !== e.databaseId.projectId) throw new FirestoreError(N.INVALID_ARGUMENT, "Tried to deserialize key from different project: " + n.get(1) + " vs " + e.databaseId.projectId); + if (n.get(3) !== e.databaseId.database) throw new FirestoreError(N.INVALID_ARGUMENT, "Tried to deserialize key from different database: " + n.get(3) + " vs " + e.databaseId.database); + return new DocumentKey(__PRIVATE_extractLocalPathFromResourceName(n)); +} + +function __PRIVATE_toQueryPath(e, t) { + return __PRIVATE_toResourceName(e.databaseId, t); +} + +function __PRIVATE_fromQueryPath(e) { + const t = __PRIVATE_fromResourceName(e); + // In v1beta1 queries for collections at the root did not have a trailing + // "/documents". In v1 all resource paths contain "/documents". Preserve the + // ability to read the v1beta1 form for compatibility with queries persisted + // in the local target cache. + return 4 === t.length ? ResourcePath.emptyPath() : __PRIVATE_extractLocalPathFromResourceName(t); +} + +function __PRIVATE_getEncodedDatabaseId(e) { + return new ResourcePath([ "projects", e.databaseId.projectId, "databases", e.databaseId.database ]).canonicalString(); +} + +function __PRIVATE_extractLocalPathFromResourceName(e) { + return __PRIVATE_hardAssert(e.length > 4 && "documents" === e.get(4), 29091, { + key: e.toString() + }), e.popFirst(5); +} + +/** Creates a Document proto from key and fields (but no create/update time) */ function __PRIVATE_toMutationDocument(e, t, n) { + return { + name: __PRIVATE_toName(e, t), + fields: n.value.mapValue.fields + }; +} + +function __PRIVATE_fromDocument(e, t, n) { + const r = fromName(e, t.name), i = __PRIVATE_fromVersion(t.updateTime), s = t.createTime ? __PRIVATE_fromVersion(t.createTime) : SnapshotVersion.min(), o = new ObjectValue({ + mapValue: { + fields: t.fields + } + }), _ = MutableDocument.newFoundDocument(r, i, s, o); + return n && _.setHasCommittedMutations(), n ? _.setHasCommittedMutations() : _; +} + +function __PRIVATE_fromBatchGetDocumentsResponse(e, t) { + return "found" in t ? function __PRIVATE_fromFound(e, t) { + __PRIVATE_hardAssert(!!t.found, 43571), t.found.name, t.found.updateTime; + const n = fromName(e, t.found.name), r = __PRIVATE_fromVersion(t.found.updateTime), i = t.found.createTime ? __PRIVATE_fromVersion(t.found.createTime) : SnapshotVersion.min(), s = new ObjectValue({ + mapValue: { + fields: t.found.fields + } + }); + return MutableDocument.newFoundDocument(n, r, i, s); + }(e, t) : "missing" in t ? function __PRIVATE_fromMissing(e, t) { + __PRIVATE_hardAssert(!!t.missing, 3894), __PRIVATE_hardAssert(!!t.readTime, 22933); + const n = fromName(e, t.missing), r = __PRIVATE_fromVersion(t.readTime); + return MutableDocument.newNoDocument(n, r); + }(e, t) : fail(7234, { + result: t + }); +} + +function __PRIVATE_fromWatchChange(e, t) { + let n; + if ("targetChange" in t) { + t.targetChange; + // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE' + // if unset + const r = function __PRIVATE_fromWatchTargetChangeState(e) { + return "NO_CHANGE" === e ? 0 /* WatchTargetChangeState.NoChange */ : "ADD" === e ? 1 /* WatchTargetChangeState.Added */ : "REMOVE" === e ? 2 /* WatchTargetChangeState.Removed */ : "CURRENT" === e ? 3 /* WatchTargetChangeState.Current */ : "RESET" === e ? 4 /* WatchTargetChangeState.Reset */ : fail(39313, { + state: e + }); + }(t.targetChange.targetChangeType || "NO_CHANGE"), i = t.targetChange.targetIds || [], s = function __PRIVATE_fromBytes(e, t) { + return e.useProto3Json ? (__PRIVATE_hardAssert(void 0 === t || "string" == typeof t, 58123), + ByteString.fromBase64String(t || "")) : (__PRIVATE_hardAssert(void 0 === t || + // Check if the value is an instance of both Buffer and Uint8Array, + // despite the fact that Buffer extends Uint8Array. In some + // environments, such as jsdom, the prototype chain of Buffer + // does not indicate that it extends Uint8Array. + t instanceof Buffer || t instanceof Uint8Array, 16193), ByteString.fromUint8Array(t || new Uint8Array)); + }(e, t.targetChange.resumeToken), o = t.targetChange.cause, _ = o && function __PRIVATE_fromRpcStatus(e) { + const t = void 0 === e.code ? N.UNKNOWN : __PRIVATE_mapCodeFromRpcCode(e.code); + return new FirestoreError(t, e.message || ""); + }(o); + n = new __PRIVATE_WatchTargetChange(r, i, s, _ || null); + } else if ("documentChange" in t) { + t.documentChange; + const r = t.documentChange; + r.document, r.document.name, r.document.updateTime; + const i = fromName(e, r.document.name), s = __PRIVATE_fromVersion(r.document.updateTime), o = r.document.createTime ? __PRIVATE_fromVersion(r.document.createTime) : SnapshotVersion.min(), _ = new ObjectValue({ + mapValue: { + fields: r.document.fields + } + }), a = MutableDocument.newFoundDocument(i, s, o, _), u = r.targetIds || [], c = r.removedTargetIds || []; + n = new __PRIVATE_DocumentWatchChange(u, c, a.key, a); + } else if ("documentDelete" in t) { + t.documentDelete; + const r = t.documentDelete; + r.document; + const i = fromName(e, r.document), s = r.readTime ? __PRIVATE_fromVersion(r.readTime) : SnapshotVersion.min(), o = MutableDocument.newNoDocument(i, s), _ = r.removedTargetIds || []; + n = new __PRIVATE_DocumentWatchChange([], _, o.key, o); + } else if ("documentRemove" in t) { + t.documentRemove; + const r = t.documentRemove; + r.document; + const i = fromName(e, r.document), s = r.removedTargetIds || []; + n = new __PRIVATE_DocumentWatchChange([], s, i, null); + } else { + if (!("filter" in t)) return fail(11601, { + Rt: t + }); + { + t.filter; + const e = t.filter; + e.targetId; + const {count: r = 0, unchangedNames: i} = e, s = new ExistenceFilter(r, i), o = e.targetId; + n = new __PRIVATE_ExistenceFilterChange(o, s); + } + } + return n; +} + +function toMutation(e, t) { + let n; + if (t instanceof __PRIVATE_SetMutation) n = { + update: __PRIVATE_toMutationDocument(e, t.key, t.value) + }; else if (t instanceof __PRIVATE_DeleteMutation) n = { + delete: __PRIVATE_toName(e, t.key) + }; else if (t instanceof __PRIVATE_PatchMutation) n = { + update: __PRIVATE_toMutationDocument(e, t.key, t.data), + updateMask: __PRIVATE_toDocumentMask(t.fieldMask) + }; else { + if (!(t instanceof __PRIVATE_VerifyMutation)) return fail(16599, { + Vt: t.type + }); + n = { + verify: __PRIVATE_toName(e, t.key) + }; + } + return t.fieldTransforms.length > 0 && (n.updateTransforms = t.fieldTransforms.map((e => function __PRIVATE_toFieldTransform(e, t) { + const n = t.transform; + if (n instanceof __PRIVATE_ServerTimestampTransform) return { + fieldPath: t.field.canonicalString(), + setToServerValue: "REQUEST_TIME" + }; + if (n instanceof __PRIVATE_ArrayUnionTransformOperation) return { + fieldPath: t.field.canonicalString(), + appendMissingElements: { + values: n.elements + } + }; + if (n instanceof __PRIVATE_ArrayRemoveTransformOperation) return { + fieldPath: t.field.canonicalString(), + removeAllFromArray: { + values: n.elements + } + }; + if (n instanceof __PRIVATE_NumericIncrementTransformOperation) return { + fieldPath: t.field.canonicalString(), + increment: n.Ae + }; + throw fail(20930, { + transform: t.transform + }); + }(0, e)))), t.precondition.isNone || (n.currentDocument = function __PRIVATE_toPrecondition(e, t) { + return void 0 !== t.updateTime ? { + updateTime: __PRIVATE_toVersion(e, t.updateTime) + } : void 0 !== t.exists ? { + exists: t.exists + } : fail(27497); + }(e, t.precondition)), n; +} + +function __PRIVATE_fromMutation(e, t) { + const n = t.currentDocument ? function __PRIVATE_fromPrecondition(e) { + return void 0 !== e.updateTime ? Precondition.updateTime(__PRIVATE_fromVersion(e.updateTime)) : void 0 !== e.exists ? Precondition.exists(e.exists) : Precondition.none(); + }(t.currentDocument) : Precondition.none(), r = t.updateTransforms ? t.updateTransforms.map((t => function __PRIVATE_fromFieldTransform(e, t) { + let n = null; + if ("setToServerValue" in t) __PRIVATE_hardAssert("REQUEST_TIME" === t.setToServerValue, 16630, { + proto: t + }), n = new __PRIVATE_ServerTimestampTransform; else if ("appendMissingElements" in t) { + const e = t.appendMissingElements.values || []; + n = new __PRIVATE_ArrayUnionTransformOperation(e); + } else if ("removeAllFromArray" in t) { + const e = t.removeAllFromArray.values || []; + n = new __PRIVATE_ArrayRemoveTransformOperation(e); + } else "increment" in t ? n = new __PRIVATE_NumericIncrementTransformOperation(e, t.increment) : fail(16584, { + proto: t + }); + const r = FieldPath$1.fromServerFormat(t.fieldPath); + return new FieldTransform(r, n); + }(e, t))) : []; + if (t.update) { + t.update.name; + const i = fromName(e, t.update.name), s = new ObjectValue({ + mapValue: { + fields: t.update.fields + } + }); + if (t.updateMask) { + const e = function __PRIVATE_fromDocumentMask(e) { + const t = e.fieldPaths || []; + return new FieldMask(t.map((e => FieldPath$1.fromServerFormat(e)))); + }(t.updateMask); + return new __PRIVATE_PatchMutation(i, s, e, n, r); + } + return new __PRIVATE_SetMutation(i, s, n, r); + } + if (t.delete) { + const r = fromName(e, t.delete); + return new __PRIVATE_DeleteMutation(r, n); + } + if (t.verify) { + const r = fromName(e, t.verify); + return new __PRIVATE_VerifyMutation(r, n); + } + return fail(1463, { + proto: t + }); +} + +function __PRIVATE_fromWriteResults(e, t) { + return e && e.length > 0 ? (__PRIVATE_hardAssert(void 0 !== t, 14353), e.map((e => function __PRIVATE_fromWriteResult(e, t) { + // NOTE: Deletes don't have an updateTime. + let n = e.updateTime ? __PRIVATE_fromVersion(e.updateTime) : __PRIVATE_fromVersion(t); + return n.isEqual(SnapshotVersion.min()) && ( + // The Firestore Emulator currently returns an update time of 0 for + // deletes of non-existing documents (rather than null). This breaks the + // test "get deleted doc while offline with source=cache" as NoDocuments + // with version 0 are filtered by IndexedDb's RemoteDocumentCache. + // TODO(#2149): Remove this when Emulator is fixed + n = __PRIVATE_fromVersion(t)), new MutationResult(n, e.transformResults || []); + }(e, t)))) : []; +} + +function __PRIVATE_toDocumentsTarget(e, t) { + return { + documents: [ __PRIVATE_toQueryPath(e, t.path) ] + }; +} + +function __PRIVATE_toQueryTarget(e, t) { + // Dissect the path into parent, collectionId, and optional key filter. + const n = { + structuredQuery: {} + }, r = t.path; + let i; + null !== t.collectionGroup ? (i = r, n.structuredQuery.from = [ { + collectionId: t.collectionGroup, + allDescendants: !0 + } ]) : (i = r.popLast(), n.structuredQuery.from = [ { + collectionId: r.lastSegment() + } ]), n.parent = __PRIVATE_toQueryPath(e, i); + const s = function __PRIVATE_toFilters(e) { + if (0 === e.length) return; + return __PRIVATE_toFilter(CompositeFilter.create(e, "and" /* CompositeOperator.AND */)); + }(t.filters); + s && (n.structuredQuery.where = s); + const o = function __PRIVATE_toOrder(e) { + if (0 === e.length) return; + return e.map((e => + // visible for testing + function __PRIVATE_toPropertyOrder(e) { + return { + field: __PRIVATE_toFieldPathReference(e.field), + direction: __PRIVATE_toDirection(e.dir) + }; + }(e))); + }(t.orderBy); + o && (n.structuredQuery.orderBy = o); + const _ = __PRIVATE_toInt32Proto(e, t.limit); + return null !== _ && (n.structuredQuery.limit = _), t.startAt && (n.structuredQuery.startAt = function __PRIVATE_toStartAtCursor(e) { + return { + before: e.inclusive, + values: e.position + }; + }(t.startAt)), t.endAt && (n.structuredQuery.endAt = function __PRIVATE_toEndAtCursor(e) { + return { + before: !e.inclusive, + values: e.position + }; + }(t.endAt)), { + ft: n, + parent: i + }; +} + +function __PRIVATE_toRunAggregationQueryRequest(e, t, n, r) { + const {ft: i, parent: s} = __PRIVATE_toQueryTarget(e, t), o = {}, _ = []; + let a = 0; + return n.forEach((e => { + // Map all client-side aliases to a unique short-form + // alias. This avoids issues with client-side aliases that + // exceed the 1500-byte string size limit. + const t = r ? e.alias : "aggregate_" + a++; + o[t] = e.alias, "count" === e.aggregateType ? _.push({ + alias: t, + count: {} + }) : "avg" === e.aggregateType ? _.push({ + alias: t, + avg: { + field: __PRIVATE_toFieldPathReference(e.fieldPath) + } + }) : "sum" === e.aggregateType && _.push({ + alias: t, + sum: { + field: __PRIVATE_toFieldPathReference(e.fieldPath) + } + }); + })), { + request: { + structuredAggregationQuery: { + aggregations: _, + structuredQuery: i.structuredQuery + }, + parent: i.parent + }, + gt: o, + parent: s + }; +} + +function __PRIVATE_convertQueryTargetToQuery(e) { + let t = __PRIVATE_fromQueryPath(e.parent); + const n = e.structuredQuery, r = n.from ? n.from.length : 0; + let i = null; + if (r > 0) { + __PRIVATE_hardAssert(1 === r, 65062); + const e = n.from[0]; + e.allDescendants ? i = e.collectionId : t = t.child(e.collectionId); + } + let s = []; + n.where && (s = function __PRIVATE_fromFilters(e) { + const t = __PRIVATE_fromFilter(e); + if (t instanceof CompositeFilter && __PRIVATE_compositeFilterIsFlatConjunction(t)) return t.getFilters(); + return [ t ]; + }(n.where)); + let o = []; + n.orderBy && (o = function __PRIVATE_fromOrder(e) { + return e.map((e => function __PRIVATE_fromPropertyOrder(e) { + return new OrderBy(__PRIVATE_fromFieldPathReference(e.field), + // visible for testing + function __PRIVATE_fromDirection(e) { + switch (e) { + case "ASCENDING": + return "asc" /* Direction.ASCENDING */; + + case "DESCENDING": + return "desc" /* Direction.DESCENDING */; + + default: + return; + } + } + // visible for testing + (e.direction)); + } + // visible for testing + (e))); + }(n.orderBy)); + let _ = null; + n.limit && (_ = function __PRIVATE_fromInt32Proto(e) { + let t; + return t = "object" == typeof e ? e.value : e, __PRIVATE_isNullOrUndefined(t) ? null : t; + }(n.limit)); + let a = null; + n.startAt && (a = function __PRIVATE_fromStartAtCursor(e) { + const t = !!e.before, n = e.values || []; + return new Bound(n, t); + }(n.startAt)); + let u = null; + return n.endAt && (u = function __PRIVATE_fromEndAtCursor(e) { + const t = !e.before, n = e.values || []; + return new Bound(n, t); + } + // visible for testing + (n.endAt)), __PRIVATE_newQuery(t, i, o, s, _, "F" /* LimitType.First */ , a, u); +} + +function __PRIVATE_toListenRequestLabels(e, t) { + const n = function __PRIVATE_toLabel(e) { + switch (e) { + case "TargetPurposeListen" /* TargetPurpose.Listen */ : + return null; + + case "TargetPurposeExistenceFilterMismatch" /* TargetPurpose.ExistenceFilterMismatch */ : + return "existence-filter-mismatch"; + + case "TargetPurposeExistenceFilterMismatchBloom" /* TargetPurpose.ExistenceFilterMismatchBloom */ : + return "existence-filter-mismatch-bloom"; + + case "TargetPurposeLimboResolution" /* TargetPurpose.LimboResolution */ : + return "limbo-document"; + + default: + return fail(28987, { + purpose: e + }); + } + }(t.purpose); + return null == n ? null : { + "goog-listen-tags": n + }; +} + +function __PRIVATE_fromFilter(e) { + return void 0 !== e.unaryFilter ? function __PRIVATE_fromUnaryFilter(e) { + switch (e.unaryFilter.op) { + case "IS_NAN": + const t = __PRIVATE_fromFieldPathReference(e.unaryFilter.field); + return FieldFilter.create(t, "==" /* Operator.EQUAL */ , { + doubleValue: NaN + }); + + case "IS_NULL": + const n = __PRIVATE_fromFieldPathReference(e.unaryFilter.field); + return FieldFilter.create(n, "==" /* Operator.EQUAL */ , { + nullValue: "NULL_VALUE" + }); + + case "IS_NOT_NAN": + const r = __PRIVATE_fromFieldPathReference(e.unaryFilter.field); + return FieldFilter.create(r, "!=" /* Operator.NOT_EQUAL */ , { + doubleValue: NaN + }); + + case "IS_NOT_NULL": + const i = __PRIVATE_fromFieldPathReference(e.unaryFilter.field); + return FieldFilter.create(i, "!=" /* Operator.NOT_EQUAL */ , { + nullValue: "NULL_VALUE" + }); + + case "OPERATOR_UNSPECIFIED": + return fail(61313); + + default: + return fail(60726); + } + }(e) : void 0 !== e.fieldFilter ? function __PRIVATE_fromFieldFilter(e) { + return FieldFilter.create(__PRIVATE_fromFieldPathReference(e.fieldFilter.field), function __PRIVATE_fromOperatorName(e) { + switch (e) { + case "EQUAL": + return "==" /* Operator.EQUAL */; + + case "NOT_EQUAL": + return "!=" /* Operator.NOT_EQUAL */; + + case "GREATER_THAN": + return ">" /* Operator.GREATER_THAN */; + + case "GREATER_THAN_OR_EQUAL": + return ">=" /* Operator.GREATER_THAN_OR_EQUAL */; + + case "LESS_THAN": + return "<" /* Operator.LESS_THAN */; + + case "LESS_THAN_OR_EQUAL": + return "<=" /* Operator.LESS_THAN_OR_EQUAL */; + + case "ARRAY_CONTAINS": + return "array-contains" /* Operator.ARRAY_CONTAINS */; + + case "IN": + return "in" /* Operator.IN */; + + case "NOT_IN": + return "not-in" /* Operator.NOT_IN */; + + case "ARRAY_CONTAINS_ANY": + return "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */; + + case "OPERATOR_UNSPECIFIED": + return fail(58110); + + default: + return fail(50506); + } + }(e.fieldFilter.op), e.fieldFilter.value); + }(e) : void 0 !== e.compositeFilter ? function __PRIVATE_fromCompositeFilter(e) { + return CompositeFilter.create(e.compositeFilter.filters.map((e => __PRIVATE_fromFilter(e))), function __PRIVATE_fromCompositeOperatorName(e) { + switch (e) { + case "AND": + return "and" /* CompositeOperator.AND */; + + case "OR": + return "or" /* CompositeOperator.OR */; + + default: + return fail(1026); + } + }(e.compositeFilter.op)); + }(e) : fail(30097, { + filter: e + }); +} + +function __PRIVATE_toDirection(e) { + return bt[e]; +} + +function __PRIVATE_toOperatorName(e) { + return Dt[e]; +} + +function __PRIVATE_toCompositeOperatorName(e) { + return Ct[e]; +} + +function __PRIVATE_toFieldPathReference(e) { + return { + fieldPath: e.canonicalString() + }; +} + +function __PRIVATE_fromFieldPathReference(e) { + return FieldPath$1.fromServerFormat(e.fieldPath); +} + +function __PRIVATE_toFilter(e) { + return e instanceof FieldFilter ? function __PRIVATE_toUnaryOrFieldFilter(e) { + if ("==" /* Operator.EQUAL */ === e.op) { + if (__PRIVATE_isNanValue(e.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(e.field), + op: "IS_NAN" + } + }; + if (__PRIVATE_isNullValue(e.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(e.field), + op: "IS_NULL" + } + }; + } else if ("!=" /* Operator.NOT_EQUAL */ === e.op) { + if (__PRIVATE_isNanValue(e.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(e.field), + op: "IS_NOT_NAN" + } + }; + if (__PRIVATE_isNullValue(e.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(e.field), + op: "IS_NOT_NULL" + } + }; + } + return { + fieldFilter: { + field: __PRIVATE_toFieldPathReference(e.field), + op: __PRIVATE_toOperatorName(e.op), + value: e.value + } + }; + }(e) : e instanceof CompositeFilter ? function __PRIVATE_toCompositeFilter(e) { + const t = e.getFilters().map((e => __PRIVATE_toFilter(e))); + if (1 === t.length) return t[0]; + return { + compositeFilter: { + op: __PRIVATE_toCompositeOperatorName(e.op), + filters: t + } + }; + }(e) : fail(54877, { + filter: e + }); +} + +function __PRIVATE_toDocumentMask(e) { + const t = []; + return e.fields.forEach((e => t.push(e.canonicalString()))), { + fieldPaths: t + }; +} + +function __PRIVATE_isValidResourceName(e) { + // Resource names have at least 4 components (project ID, database ID) + return e.length >= 4 && "projects" === e.get(0) && "databases" === e.get(2); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable set of metadata that the local store tracks for each target. + */ class TargetData { + constructor( + /** The target being listened to. */ + e, + /** + * The target ID to which the target corresponds; Assigned by the + * LocalStore for user listens and by the SyncEngine for limbo watches. + */ + t, + /** The purpose of the target. */ + n, + /** + * The sequence number of the last transaction during which this target data + * was modified. + */ + r, + /** The latest snapshot version seen for this target. */ + i = SnapshotVersion.min() + /** + * The maximum snapshot version at which the associated view + * contained no limbo documents. + */ , s = SnapshotVersion.min() + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ , o = ByteString.EMPTY_BYTE_STRING + /** + * The number of documents that last matched the query at the resume token or + * read time. Documents are counted only when making a listen request with + * resume token or read time, otherwise, keep it null. + */ , _ = null) { + this.target = e, this.targetId = t, this.purpose = n, this.sequenceNumber = r, this.snapshotVersion = i, + this.lastLimboFreeSnapshotVersion = s, this.resumeToken = o, this.expectedCount = _; + } + /** Creates a new target data instance with an updated sequence number. */ withSequenceNumber(e) { + return new TargetData(this.target, this.targetId, this.purpose, e, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, this.expectedCount); + } + /** + * Creates a new target data instance with an updated resume token and + * snapshot version. + */ withResumeToken(e, t) { + return new TargetData(this.target, this.targetId, this.purpose, this.sequenceNumber, t, this.lastLimboFreeSnapshotVersion, e, + /* expectedCount= */ null); + } + /** + * Creates a new target data instance with an updated expected count. + */ withExpectedCount(e) { + return new TargetData(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, e); + } + /** + * Creates a new target data instance with an updated last limbo free + * snapshot version number. + */ withLastLimboFreeSnapshotVersion(e) { + return new TargetData(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, e, this.resumeToken, this.expectedCount); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Serializer for values stored in the LocalStore. */ class __PRIVATE_LocalSerializer { + constructor(e) { + this.yt = e; + } +} + +/** Decodes a remote document from storage locally to a Document. */ function __PRIVATE_fromDbRemoteDocument(e, t) { + let n; + if (t.document) n = __PRIVATE_fromDocument(e.yt, t.document, !!t.hasCommittedMutations); else if (t.noDocument) { + const e = DocumentKey.fromSegments(t.noDocument.path), r = __PRIVATE_fromDbTimestamp(t.noDocument.readTime); + n = MutableDocument.newNoDocument(e, r), t.hasCommittedMutations && n.setHasCommittedMutations(); + } else { + if (!t.unknownDocument) return fail(56709); + { + const e = DocumentKey.fromSegments(t.unknownDocument.path), r = __PRIVATE_fromDbTimestamp(t.unknownDocument.version); + n = MutableDocument.newUnknownDocument(e, r); + } + } + return t.readTime && n.setReadTime(function __PRIVATE_fromDbTimestampKey(e) { + const t = new Timestamp(e[0], e[1]); + return SnapshotVersion.fromTimestamp(t); + }(t.readTime)), n; +} + +/** Encodes a document for storage locally. */ function __PRIVATE_toDbRemoteDocument(e, t) { + const n = t.key, r = { + prefixPath: n.getCollectionPath().popLast().toArray(), + collectionGroup: n.collectionGroup, + documentId: n.path.lastSegment(), + readTime: __PRIVATE_toDbTimestampKey(t.readTime), + hasCommittedMutations: t.hasCommittedMutations + }; + if (t.isFoundDocument()) r.document = function __PRIVATE_toDocument(e, t) { + return { + name: __PRIVATE_toName(e, t.key), + fields: t.data.value.mapValue.fields, + updateTime: toTimestamp(e, t.version.toTimestamp()), + createTime: toTimestamp(e, t.createTime.toTimestamp()) + }; + }(e.yt, t); else if (t.isNoDocument()) r.noDocument = { + path: n.path.toArray(), + readTime: __PRIVATE_toDbTimestamp(t.version) + }; else { + if (!t.isUnknownDocument()) return fail(57904, { + document: t + }); + r.unknownDocument = { + path: n.path.toArray(), + version: __PRIVATE_toDbTimestamp(t.version) + }; + } + return r; +} + +function __PRIVATE_toDbTimestampKey(e) { + const t = e.toTimestamp(); + return [ t.seconds, t.nanoseconds ]; +} + +function __PRIVATE_toDbTimestamp(e) { + const t = e.toTimestamp(); + return { + seconds: t.seconds, + nanoseconds: t.nanoseconds + }; +} + +function __PRIVATE_fromDbTimestamp(e) { + const t = new Timestamp(e.seconds, e.nanoseconds); + return SnapshotVersion.fromTimestamp(t); +} + +/** Encodes a batch of mutations into a DbMutationBatch for local storage. */ +/** Decodes a DbMutationBatch into a MutationBatch */ +function __PRIVATE_fromDbMutationBatch(e, t) { + const n = (t.baseMutations || []).map((t => __PRIVATE_fromMutation(e.yt, t))); + // Squash old transform mutations into existing patch or set mutations. + // The replacement of representing `transforms` with `update_transforms` + // on the SDK means that old `transform` mutations stored in IndexedDB need + // to be updated to `update_transforms`. + // TODO(b/174608374): Remove this code once we perform a schema migration. + for (let e = 0; e < t.mutations.length - 1; ++e) { + const n = t.mutations[e]; + if (e + 1 < t.mutations.length && void 0 !== t.mutations[e + 1].transform) { + const r = t.mutations[e + 1]; + n.updateTransforms = r.transform.fieldTransforms, t.mutations.splice(e + 1, 1), + ++e; + } + } + const r = t.mutations.map((t => __PRIVATE_fromMutation(e.yt, t))), i = Timestamp.fromMillis(t.localWriteTimeMs); + return new MutationBatch(t.batchId, i, n, r); +} + +/** Decodes a DbTarget into TargetData */ function __PRIVATE_fromDbTarget(e) { + const t = __PRIVATE_fromDbTimestamp(e.readTime), n = void 0 !== e.lastLimboFreeSnapshotVersion ? __PRIVATE_fromDbTimestamp(e.lastLimboFreeSnapshotVersion) : SnapshotVersion.min(); + let r; + return r = + /** + * A helper function for figuring out what kind of query has been stored. + */ + function __PRIVATE_isDocumentQuery(e) { + return void 0 !== e.documents; + } + /** Encodes a DbBundle to a BundleMetadata object. */ (e.query) ? function __PRIVATE_fromDocumentsTarget(e) { + const t = e.documents.length; + return __PRIVATE_hardAssert(1 === t, 1966, { + count: t + }), __PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(__PRIVATE_fromQueryPath(e.documents[0]))); + }(e.query) : function __PRIVATE_fromQueryTarget(e) { + return __PRIVATE_queryToTarget(__PRIVATE_convertQueryTargetToQuery(e)); + }(e.query), new TargetData(r, e.targetId, "TargetPurposeListen" /* TargetPurpose.Listen */ , e.lastListenSequenceNumber, t, n, ByteString.fromBase64String(e.resumeToken)); +} + +/** Encodes TargetData into a DbTarget for storage locally. */ function __PRIVATE_toDbTarget(e, t) { + const n = __PRIVATE_toDbTimestamp(t.snapshotVersion), r = __PRIVATE_toDbTimestamp(t.lastLimboFreeSnapshotVersion); + let i; + i = __PRIVATE_targetIsDocumentTarget(t.target) ? __PRIVATE_toDocumentsTarget(e.yt, t.target) : __PRIVATE_toQueryTarget(e.yt, t.target).ft; + // We can't store the resumeToken as a ByteString in IndexedDb, so we + // convert it to a base64 string for storage. + const s = t.resumeToken.toBase64(); + // lastListenSequenceNumber is always 0 until we do real GC. + return { + targetId: t.targetId, + canonicalId: __PRIVATE_canonifyTarget(t.target), + readTime: n, + resumeToken: s, + lastListenSequenceNumber: t.sequenceNumber, + lastLimboFreeSnapshotVersion: r, + query: i + }; +} + +/** + * Encodes a `BundledQuery` from bundle proto to a Query object. + * + * This reconstructs the original query used to build the bundle being loaded, + * including features exists only in SDKs (for example: limit-to-last). + */ +function __PRIVATE_fromBundledQuery(e) { + const t = __PRIVATE_convertQueryTargetToQuery({ + parent: e.parent, + structuredQuery: e.structuredQuery + }); + return "LAST" === e.limitType ? __PRIVATE_queryWithLimit(t, t.limit, "L" /* LimitType.Last */) : t; +} + +/** Encodes a NamedQuery proto object to a NamedQuery model object. */ +/** Encodes a DbDocumentOverlay object to an Overlay model object. */ +function __PRIVATE_fromDbDocumentOverlay(e, t) { + return new Overlay(t.largestBatchId, __PRIVATE_fromMutation(e.yt, t.overlayMutation)); +} + +/** Decodes an Overlay model object into a DbDocumentOverlay object. */ +/** + * Returns the DbDocumentOverlayKey corresponding to the given user and + * document key. + */ +function __PRIVATE_toDbDocumentOverlayKey(e, t) { + const n = t.path.lastSegment(); + return [ e, __PRIVATE_encodeResourcePath(t.path.popLast()), n ]; +} + +function __PRIVATE_toDbIndexState(e, t, n, r) { + return { + indexId: e, + uid: t, + sequenceNumber: n, + readTime: __PRIVATE_toDbTimestamp(r.readTime), + documentKey: __PRIVATE_encodeResourcePath(r.documentKey.path), + largestBatchId: r.largestBatchId + }; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_IndexedDbBundleCache { + getBundleMetadata(e, t) { + return __PRIVATE_bundlesStore(e).get(t).next((e => { + if (e) return function __PRIVATE_fromDbBundle(e) { + return { + id: e.bundleId, + createTime: __PRIVATE_fromDbTimestamp(e.createTime), + version: e.version + }; + } + /** Encodes a BundleMetadata to a DbBundle. */ (e); + })); + } + saveBundleMetadata(e, t) { + return __PRIVATE_bundlesStore(e).put(function __PRIVATE_toDbBundle(e) { + return { + bundleId: e.id, + createTime: __PRIVATE_toDbTimestamp(__PRIVATE_fromVersion(e.createTime)), + version: e.version + }; + } + /** Encodes a DbNamedQuery to a NamedQuery. */ (t)); + } + getNamedQuery(e, t) { + return __PRIVATE_namedQueriesStore(e).get(t).next((e => { + if (e) return function __PRIVATE_fromDbNamedQuery(e) { + return { + name: e.name, + query: __PRIVATE_fromBundledQuery(e.bundledQuery), + readTime: __PRIVATE_fromDbTimestamp(e.readTime) + }; + } + /** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */ (e); + })); + } + saveNamedQuery(e, t) { + return __PRIVATE_namedQueriesStore(e).put(function __PRIVATE_toDbNamedQuery(e) { + return { + name: e.name, + readTime: __PRIVATE_toDbTimestamp(__PRIVATE_fromVersion(e.readTime)), + bundledQuery: e.bundledQuery + }; + }(t)); + } +} + +/** + * Helper to get a typed SimpleDbStore for the bundles object store. + */ function __PRIVATE_bundlesStore(e) { + return __PRIVATE_getStore(e, be); +} + +/** + * Helper to get a typed SimpleDbStore for the namedQueries object store. + */ function __PRIVATE_namedQueriesStore(e) { + return __PRIVATE_getStore(e, Ce); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Implementation of DocumentOverlayCache using IndexedDb. + */ class __PRIVATE_IndexedDbDocumentOverlayCache { + /** + * @param serializer - The document serializer. + * @param userId - The userId for which we are accessing overlays. + */ + constructor(e, t) { + this.serializer = e, this.userId = t; + } + static wt(e, t) { + const n = t.uid || ""; + return new __PRIVATE_IndexedDbDocumentOverlayCache(e, n); + } + getOverlay(e, t) { + return __PRIVATE_documentOverlayStore(e).get(__PRIVATE_toDbDocumentOverlayKey(this.userId, t)).next((e => e ? __PRIVATE_fromDbDocumentOverlay(this.serializer, e) : null)); + } + getOverlays(e, t) { + const n = __PRIVATE_newOverlayMap(); + return PersistencePromise.forEach(t, (t => this.getOverlay(e, t).next((e => { + null !== e && n.set(t, e); + })))).next((() => n)); + } + saveOverlays(e, t, n) { + const r = []; + return n.forEach(((n, i) => { + const s = new Overlay(t, i); + r.push(this.St(e, s)); + })), PersistencePromise.waitFor(r); + } + removeOverlaysForBatchId(e, t, n) { + const r = new Set; + // Get the set of unique collection paths. + t.forEach((e => r.add(__PRIVATE_encodeResourcePath(e.getCollectionPath())))); + const i = []; + return r.forEach((t => { + const r = IDBKeyRange.bound([ this.userId, t, n ], [ this.userId, t, n + 1 ], + /*lowerOpen=*/ !1, + /*upperOpen=*/ !0); + i.push(__PRIVATE_documentOverlayStore(e).Z(Ge, r)); + })), PersistencePromise.waitFor(i); + } + getOverlaysForCollection(e, t, n) { + const r = __PRIVATE_newOverlayMap(), i = __PRIVATE_encodeResourcePath(t), s = IDBKeyRange.bound([ this.userId, i, n ], [ this.userId, i, Number.POSITIVE_INFINITY ], + /*lowerOpen=*/ !0); + return __PRIVATE_documentOverlayStore(e).J(Ge, s).next((e => { + for (const t of e) { + const e = __PRIVATE_fromDbDocumentOverlay(this.serializer, t); + r.set(e.getKey(), e); + } + return r; + })); + } + getOverlaysForCollectionGroup(e, t, n, r) { + const i = __PRIVATE_newOverlayMap(); + let s; + // We want batch IDs larger than `sinceBatchId`, and so the lower bound + // is not inclusive. + const o = IDBKeyRange.bound([ this.userId, t, n ], [ this.userId, t, Number.POSITIVE_INFINITY ], + /*lowerOpen=*/ !0); + return __PRIVATE_documentOverlayStore(e).ee({ + index: je, + range: o + }, ((e, t, n) => { + // We do not want to return partial batch overlays, even if the size + // of the result set exceeds the given `count` argument. Therefore, we + // continue to aggregate results even after the result size exceeds + // `count` if there are more overlays from the `currentBatchId`. + const o = __PRIVATE_fromDbDocumentOverlay(this.serializer, t); + i.size() < r || o.largestBatchId === s ? (i.set(o.getKey(), o), s = o.largestBatchId) : n.done(); + })).next((() => i)); + } + St(e, t) { + return __PRIVATE_documentOverlayStore(e).put(function __PRIVATE_toDbDocumentOverlay(e, t, n) { + const [r, i, s] = __PRIVATE_toDbDocumentOverlayKey(t, n.mutation.key); + return { + userId: t, + collectionPath: i, + documentId: s, + collectionGroup: n.mutation.key.getCollectionGroup(), + largestBatchId: n.largestBatchId, + overlayMutation: toMutation(e.yt, n.mutation) + }; + }(this.serializer, this.userId, t)); + } +} + +/** + * Helper to get a typed SimpleDbStore for the document overlay object store. + */ function __PRIVATE_documentOverlayStore(e) { + return __PRIVATE_getStore(e, Ke); +} + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_IndexedDbGlobalsCache { + bt(e) { + return __PRIVATE_getStore(e, He); + } + getSessionToken(e) { + return this.bt(e).get("sessionToken").next((e => { + const t = e?.value; + return t ? ByteString.fromUint8Array(t) : ByteString.EMPTY_BYTE_STRING; + })); + } + setSessionToken(e, t) { + return this.bt(e).put({ + name: "sessionToken", + value: t.toUint8Array() + }); + } +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Note: This code is copied from the backend. Code that is not used by +// Firestore was removed. +/** Firestore index value writer. */ +class __PRIVATE_FirestoreIndexValueWriter { + constructor() {} + // The write methods below short-circuit writing terminators for values + // containing a (terminating) truncated value. + // As an example, consider the resulting encoding for: + // ["bar", [2, "foo"]] -> (STRING, "bar", TERM, ARRAY, NUMBER, 2, STRING, "foo", TERM, TERM, TERM) + // ["bar", [2, truncated("foo")]] -> (STRING, "bar", TERM, ARRAY, NUMBER, 2, STRING, "foo", TRUNC) + // ["bar", truncated(["foo"])] -> (STRING, "bar", TERM, ARRAY. STRING, "foo", TERM, TRUNC) + /** Writes an index value. */ + Dt(e, t) { + this.Ct(e, t), + // Write separator to split index values + // (see go/firestore-storage-format#encodings). + t.vt(); + } + Ct(e, t) { + if ("nullValue" in e) this.Ft(t, 5); else if ("booleanValue" in e) this.Ft(t, 10), + t.Mt(e.booleanValue ? 1 : 0); else if ("integerValue" in e) this.Ft(t, 15), t.Mt(__PRIVATE_normalizeNumber(e.integerValue)); else if ("doubleValue" in e) { + const n = __PRIVATE_normalizeNumber(e.doubleValue); + isNaN(n) ? this.Ft(t, 13) : (this.Ft(t, 15), __PRIVATE_isNegativeZero(n) ? + // -0.0, 0 and 0.0 are all considered the same + t.Mt(0) : t.Mt(n)); + } else if ("timestampValue" in e) { + let n = e.timestampValue; + this.Ft(t, 20), "string" == typeof n && (n = __PRIVATE_normalizeTimestamp(n)), t.xt(`${n.seconds || ""}`), + t.Mt(n.nanos || 0); + } else if ("stringValue" in e) this.Ot(e.stringValue, t), this.Nt(t); else if ("bytesValue" in e) this.Ft(t, 30), + t.Bt(__PRIVATE_normalizeByteString(e.bytesValue)), this.Nt(t); else if ("referenceValue" in e) this.Lt(e.referenceValue, t); else if ("geoPointValue" in e) { + const n = e.geoPointValue; + this.Ft(t, 45), t.Mt(n.latitude || 0), t.Mt(n.longitude || 0); + } else "mapValue" in e ? __PRIVATE_isMaxValue(e) ? this.Ft(t, Number.MAX_SAFE_INTEGER) : __PRIVATE_isVectorValue(e) ? this.kt(e.mapValue, t) : (this.qt(e.mapValue, t), + this.Nt(t)) : "arrayValue" in e ? (this.Qt(e.arrayValue, t), this.Nt(t)) : fail(19022, { + $t: e + }); + } + Ot(e, t) { + this.Ft(t, 25), this.Ut(e, t); + } + Ut(e, t) { + t.xt(e); + } + qt(e, t) { + const n = e.fields || {}; + this.Ft(t, 55); + for (const e of Object.keys(n)) this.Ot(e, t), this.Ct(n[e], t); + } + kt(e, t) { + const n = e.fields || {}; + this.Ft(t, 53); + // Vectors sort first by length + const r = Et, i = n[r].arrayValue?.values?.length || 0; + this.Ft(t, 15), t.Mt(__PRIVATE_normalizeNumber(i)), + // Vectors then sort by position value + this.Ot(r, t), this.Ct(n[r], t); + } + Qt(e, t) { + const n = e.values || []; + this.Ft(t, 50); + for (const e of n) this.Ct(e, t); + } + Lt(e, t) { + this.Ft(t, 37); + DocumentKey.fromName(e).path.forEach((e => { + this.Ft(t, 60), this.Ut(e, t); + })); + } + Ft(e, t) { + e.Mt(t); + } + Nt(e) { + // While the SDK does not implement truncation, the truncation marker is + // used to terminate all variable length values (which are strings, bytes, + // references, arrays and maps). + e.Mt(2); + } +} + +__PRIVATE_FirestoreIndexValueWriter.Kt = new __PRIVATE_FirestoreIndexValueWriter; + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law | agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES | CONDITIONS OF ANY KIND, either express | implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** These constants are taken from the backend. */ +const vt = 255; + +/** + * Counts the number of zeros in a byte. + * + * Visible for testing. + */ +function __PRIVATE_numberOfLeadingZerosInByte(e) { + if (0 === e) return 8; + let t = 0; + return e >> 4 || ( + // Test if the first four bits are zero. + t += 4, e <<= 4), e >> 6 || ( + // Test if the first two (or next two) bits are zero. + t += 2, e <<= 2), e >> 7 || ( + // Test if the remaining bit is zero. + t += 1), t; +} + +/** Counts the number of leading zeros in the given byte array. */ +/** + * Returns the number of bytes required to store "value". Leading zero bytes + * are skipped. + */ +function __PRIVATE_unsignedNumLength(e) { + // This is just the number of bytes for the unsigned representation of the number. + const t = 64 - function __PRIVATE_numberOfLeadingZeros(e) { + let t = 0; + for (let n = 0; n < 8; ++n) { + const r = __PRIVATE_numberOfLeadingZerosInByte(255 & e[n]); + if (t += r, 8 !== r) break; + } + return t; + }(e); + return Math.ceil(t / 8); +} + +/** + * OrderedCodeWriter is a minimal-allocation implementation of the writing + * behavior defined by the backend. + * + * The code is ported from its Java counterpart. + */ class __PRIVATE_OrderedCodeWriter { + constructor() { + this.buffer = new Uint8Array(1024), this.position = 0; + } + Wt(e) { + const t = e[Symbol.iterator](); + let n = t.next(); + for (;!n.done; ) this.Gt(n.value), n = t.next(); + this.zt(); + } + jt(e) { + const t = e[Symbol.iterator](); + let n = t.next(); + for (;!n.done; ) this.Jt(n.value), n = t.next(); + this.Ht(); + } + /** Writes utf8 bytes into this byte sequence, ascending. */ Yt(e) { + for (const t of e) { + const e = t.charCodeAt(0); + if (e < 128) this.Gt(e); else if (e < 2048) this.Gt(960 | e >>> 6), this.Gt(128 | 63 & e); else if (t < "\ud800" || "\udbff" < t) this.Gt(480 | e >>> 12), + this.Gt(128 | 63 & e >>> 6), this.Gt(128 | 63 & e); else { + const e = t.codePointAt(0); + this.Gt(240 | e >>> 18), this.Gt(128 | 63 & e >>> 12), this.Gt(128 | 63 & e >>> 6), + this.Gt(128 | 63 & e); + } + } + this.zt(); + } + /** Writes utf8 bytes into this byte sequence, descending */ Zt(e) { + for (const t of e) { + const e = t.charCodeAt(0); + if (e < 128) this.Jt(e); else if (e < 2048) this.Jt(960 | e >>> 6), this.Jt(128 | 63 & e); else if (t < "\ud800" || "\udbff" < t) this.Jt(480 | e >>> 12), + this.Jt(128 | 63 & e >>> 6), this.Jt(128 | 63 & e); else { + const e = t.codePointAt(0); + this.Jt(240 | e >>> 18), this.Jt(128 | 63 & e >>> 12), this.Jt(128 | 63 & e >>> 6), + this.Jt(128 | 63 & e); + } + } + this.Ht(); + } + Xt(e) { + // Values are encoded with a single byte length prefix, followed by the + // actual value in big-endian format with leading 0 bytes dropped. + const t = this.en(e), n = __PRIVATE_unsignedNumLength(t); + this.tn(1 + n), this.buffer[this.position++] = 255 & n; + // Write the length + for (let e = t.length - n; e < t.length; ++e) this.buffer[this.position++] = 255 & t[e]; + } + nn(e) { + // Values are encoded with a single byte length prefix, followed by the + // inverted value in big-endian format with leading 0 bytes dropped. + const t = this.en(e), n = __PRIVATE_unsignedNumLength(t); + this.tn(1 + n), this.buffer[this.position++] = ~(255 & n); + // Write the length + for (let e = t.length - n; e < t.length; ++e) this.buffer[this.position++] = ~(255 & t[e]); + } + /** + * Writes the "infinity" byte sequence that sorts after all other byte + * sequences written in ascending order. + */ rn() { + this.sn(vt), this.sn(255); + } + /** + * Writes the "infinity" byte sequence that sorts before all other byte + * sequences written in descending order. + */ _n() { + this.an(vt), this.an(255); + } + /** + * Resets the buffer such that it is the same as when it was newly + * constructed. + */ reset() { + this.position = 0; + } + seed(e) { + this.tn(e.length), this.buffer.set(e, this.position), this.position += e.length; + } + /** Makes a copy of the encoded bytes in this buffer. */ un() { + return this.buffer.slice(0, this.position); + } + /** + * Encodes `val` into an encoding so that the order matches the IEEE 754 + * floating-point comparison results with the following exceptions: + * -0.0 < 0.0 + * all non-NaN < NaN + * NaN = NaN + */ en(e) { + const t = + /** Converts a JavaScript number to a byte array (using big endian encoding). */ + function __PRIVATE_doubleToLongBits(e) { + const t = new DataView(new ArrayBuffer(8)); + return t.setFloat64(0, e, /* littleEndian= */ !1), new Uint8Array(t.buffer); + }(e), n = !!(128 & t[0]); + // Check if the first bit is set. We use a bit mask since value[0] is + // encoded as a number from 0 to 255. + // Revert the two complement to get natural ordering + t[0] ^= n ? 255 : 128; + for (let e = 1; e < t.length; ++e) t[e] ^= n ? 255 : 0; + return t; + } + /** Writes a single byte ascending to the buffer. */ Gt(e) { + const t = 255 & e; + 0 === t ? (this.sn(0), this.sn(255)) : t === vt ? (this.sn(vt), this.sn(0)) : this.sn(t); + } + /** Writes a single byte descending to the buffer. */ Jt(e) { + const t = 255 & e; + 0 === t ? (this.an(0), this.an(255)) : t === vt ? (this.an(vt), this.an(0)) : this.an(e); + } + zt() { + this.sn(0), this.sn(1); + } + Ht() { + this.an(0), this.an(1); + } + sn(e) { + this.tn(1), this.buffer[this.position++] = e; + } + an(e) { + this.tn(1), this.buffer[this.position++] = ~e; + } + tn(e) { + const t = e + this.position; + if (t <= this.buffer.length) return; + // Try doubling. + let n = 2 * this.buffer.length; + // Still not big enough? Just allocate the right size. + n < t && (n = t); + // Create the new buffer. + const r = new Uint8Array(n); + r.set(this.buffer), // copy old data + this.buffer = r; + } +} + +class __PRIVATE_AscendingIndexByteEncoder { + constructor(e) { + this.cn = e; + } + Bt(e) { + this.cn.Wt(e); + } + xt(e) { + this.cn.Yt(e); + } + Mt(e) { + this.cn.Xt(e); + } + vt() { + this.cn.rn(); + } +} + +class __PRIVATE_DescendingIndexByteEncoder { + constructor(e) { + this.cn = e; + } + Bt(e) { + this.cn.jt(e); + } + xt(e) { + this.cn.Zt(e); + } + Mt(e) { + this.cn.nn(e); + } + vt() { + this.cn._n(); + } +} + +/** + * Implements `DirectionalIndexByteEncoder` using `OrderedCodeWriter` for the + * actual encoding. + */ class __PRIVATE_IndexByteEncoder { + constructor() { + this.cn = new __PRIVATE_OrderedCodeWriter, this.ln = new __PRIVATE_AscendingIndexByteEncoder(this.cn), + this.hn = new __PRIVATE_DescendingIndexByteEncoder(this.cn); + } + seed(e) { + this.cn.seed(e); + } + Pn(e) { + return 0 /* IndexKind.ASCENDING */ === e ? this.ln : this.hn; + } + un() { + return this.cn.un(); + } + reset() { + this.cn.reset(); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Represents an index entry saved by the SDK in persisted storage. */ class __PRIVATE_IndexEntry { + constructor(e, t, n, r) { + this.Tn = e, this.In = t, this.En = n, this.dn = r; + } + /** + * Returns an IndexEntry entry that sorts immediately after the current + * directional value. + */ An() { + const e = this.dn.length, t = 0 === e || 255 === this.dn[e - 1] ? e + 1 : e, n = new Uint8Array(t); + return n.set(this.dn, 0), t !== e ? n.set([ 0 ], this.dn.length) : ++n[n.length - 1], + new __PRIVATE_IndexEntry(this.Tn, this.In, this.En, n); + } + // Create a representation of the Index Entry as a DbIndexEntry + Rn(e, t, n) { + return { + indexId: this.Tn, + uid: e, + arrayValue: __PRIVATE_encodeKeySafeBytes(this.En), + directionalValue: __PRIVATE_encodeKeySafeBytes(this.dn), + orderedDocumentKey: __PRIVATE_encodeKeySafeBytes(t), + documentKey: n.path.toArray() + }; + } + // Create a representation of the Index Entry as a DbIndexEntryKey + Vn(e, t, n) { + const r = this.Rn(e, t, n); + return [ r.indexId, r.uid, r.arrayValue, r.directionalValue, r.orderedDocumentKey, r.documentKey ]; + } +} + +function __PRIVATE_indexEntryComparator(e, t) { + let n = e.Tn - t.Tn; + return 0 !== n ? n : (n = __PRIVATE_compareByteArrays(e.En, t.En), 0 !== n ? n : (n = __PRIVATE_compareByteArrays(e.dn, t.dn), + 0 !== n ? n : DocumentKey.comparator(e.In, t.In))); +} + +function __PRIVATE_compareByteArrays(e, t) { + for (let n = 0; n < e.length && n < t.length; ++n) { + const r = e[n] - t[n]; + if (0 !== r) return r; + } + return e.length - t.length; +} + +/** + * Workaround for WebKit bug: https://bugs.webkit.org/show_bug.cgi?id=292721 + * Create a key safe representation of Uint8Array values. + * If the browser is detected as Safari or WebKit, then + * the input array will be converted to "sortable byte string". + * Otherwise, the input array will be returned in its original type. + */ function __PRIVATE_encodeKeySafeBytes(e) { + return util.isSafariOrWebkit() ? + /** + * Encodes a Uint8Array into a "sortable byte string". + * A "sortable byte string" sorts in the same order as the Uint8Array. + * This works because JS string comparison sorts strings based on code points. + */ + function __PRIVATE_encodeUint8ArrayToSortableString(e) { + let t = ""; + for (let n = 0; n < e.length; n++) t += String.fromCharCode(e[n]); + return t; + } + /** + * Decodes a "sortable byte string" back into a Uint8Array. + * A "sortable byte string" is assumed to be created where each character's + * Unicode code point directly corresponds to a single byte value (0-255). + */ (e) : e; +} + +/** + * Reverts the key safe representation of Uint8Array (created by + * encodeKeySafeBytes) to a normal Uint8Array. + */ function __PRIVATE_decodeKeySafeBytes(e) { + return "string" != typeof e ? e : function __PRIVATE_decodeSortableStringToUint8Array(e) { + const t = new Uint8Array(e.length); + for (let n = 0; n < e.length; n++) t[n] = e.charCodeAt(n); + return t; + } + /** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * A light query planner for Firestore. + * + * This class matches a `FieldIndex` against a Firestore Query `Target`. It + * determines whether a given index can be used to serve the specified target. + * + * The following table showcases some possible index configurations: + * + * Query | Index + * ----------------------------------------------------------------------------- + * where('a', '==', 'a').where('b', '==', 'b') | a ASC, b DESC + * where('a', '==', 'a').where('b', '==', 'b') | a ASC + * where('a', '==', 'a').where('b', '==', 'b') | b DESC + * where('a', '>=', 'a').orderBy('a') | a ASC + * where('a', '>=', 'a').orderBy('a', 'desc') | a DESC + * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC, b ASC + * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC + * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS, b ASCENDING + * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS + */ (e); +} + +class __PRIVATE_TargetIndexMatcher { + constructor(e) { + // The inequality filters of the target (if it exists). + // Note: The sort on FieldFilters is not required. Using SortedSet here just to utilize the custom + // comparator. + this.mn = new SortedSet(((e, t) => FieldPath$1.comparator(e.field, t.field))), this.collectionId = null != e.collectionGroup ? e.collectionGroup : e.path.lastSegment(), + this.fn = e.orderBy, this.gn = []; + for (const t of e.filters) { + const e = t; + e.isInequality() ? this.mn = this.mn.add(e) : this.gn.push(e); + } + } + get pn() { + return this.mn.size > 1; + } + /** + * Returns whether the index can be used to serve the TargetIndexMatcher's + * target. + * + * An index is considered capable of serving the target when: + * - The target uses all index segments for its filters and orderBy clauses. + * The target can have additional filter and orderBy clauses, but not + * fewer. + * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also + * have a corresponding `CONTAINS` segment. + * - All directional index segments can be mapped to the target as a series of + * equality filters, a single inequality filter and a series of orderBy + * clauses. + * - The segments that represent the equality filters may appear out of order. + * - The optional segment for the inequality filter must appear after all + * equality segments. + * - The segments that represent that orderBy clause of the target must appear + * in order after all equality and inequality segments. Single orderBy + * clauses cannot be skipped, but a continuous orderBy suffix may be + * omitted. + */ yn(e) { + if (__PRIVATE_hardAssert(e.collectionGroup === this.collectionId, 49279), this.pn) + // Only single inequality is supported for now. + // TODO(Add support for multiple inequality query): b/298441043 + return !1; + // If there is an array element, find a matching filter. + const t = __PRIVATE_fieldIndexGetArraySegment(e); + if (void 0 !== t && !this.wn(t)) return !1; + const n = __PRIVATE_fieldIndexGetDirectionalSegments(e); + let r = new Set, i = 0, s = 0; + // Process all equalities first. Equalities can appear out of order. + for (;i < n.length && this.wn(n[i]); ++i) r = r.add(n[i].fieldPath.canonicalString()); + // If we already have processed all segments, all segments are used to serve + // the equality filters and we do not need to map any segments to the + // target's inequality and orderBy clauses. + if (i === n.length) return !0; + if (this.mn.size > 0) { + // Only a single inequality is currently supported. Get the only entry in the set. + const e = this.mn.getIterator().getNext(); + // If there is an inequality filter and the field was not in one of the + // equality filters above, the next segment must match both the filter + // and the first orderBy clause. + if (!r.has(e.field.canonicalString())) { + const t = n[i]; + if (!this.Sn(e, t) || !this.bn(this.fn[s++], t)) return !1; + } + ++i; + } + // All remaining segments need to represent the prefix of the target's + // orderBy. + for (;i < n.length; ++i) { + const e = n[i]; + if (s >= this.fn.length || !this.bn(this.fn[s++], e)) return !1; + } + return !0; + } + /** + * Returns a full matched field index for this target. Currently multiple + * inequality query is not supported so function returns null. + */ Dn() { + if (this.pn) return null; + // We want to make sure only one segment created for one field. For example, + // in case like a == 3 and a > 2, Index {a ASCENDING} will only be created + // once. + let e = new SortedSet(FieldPath$1.comparator); + const t = []; + for (const n of this.gn) { + if (n.field.isKeyField()) continue; + if ("array-contains" /* Operator.ARRAY_CONTAINS */ === n.op || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === n.op) t.push(new IndexSegment(n.field, 2 /* IndexKind.CONTAINS */)); else { + if (e.has(n.field)) continue; + e = e.add(n.field), t.push(new IndexSegment(n.field, 0 /* IndexKind.ASCENDING */)); + } + } + // Note: We do not explicitly check `this.inequalityFilter` but rather rely + // on the target defining an appropriate "order by" to ensure that the + // required index segment is added. The query engine would reject a query + // with an inequality filter that lacks the required order-by clause. + for (const n of this.fn) + // Stop adding more segments if we see a order-by on key. Typically this + // is the default implicit order-by which is covered in the index_entry + // table as a separate column. If it is not the default order-by, the + // generated index will be missing some segments optimized for order-bys, + // which is probably fine. + n.field.isKeyField() || e.has(n.field) || (e = e.add(n.field), t.push(new IndexSegment(n.field, "asc" /* Direction.ASCENDING */ === n.dir ? 0 /* IndexKind.ASCENDING */ : 1 /* IndexKind.DESCENDING */))); + return new FieldIndex(FieldIndex.UNKNOWN_ID, this.collectionId, t, IndexState.empty()); + } + wn(e) { + for (const t of this.gn) if (this.Sn(t, e)) return !0; + return !1; + } + Sn(e, t) { + if (void 0 === e || !e.field.isEqual(t.fieldPath)) return !1; + const n = "array-contains" /* Operator.ARRAY_CONTAINS */ === e.op || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === e.op; + return 2 /* IndexKind.CONTAINS */ === t.kind === n; + } + bn(e, t) { + return !!e.field.isEqual(t.fieldPath) && (0 /* IndexKind.ASCENDING */ === t.kind && "asc" /* Direction.ASCENDING */ === e.dir || 1 /* IndexKind.DESCENDING */ === t.kind && "desc" /* Direction.DESCENDING */ === e.dir); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provides utility functions that help with boolean logic transformations needed for handling + * complex filters used in queries. + */ +/** + * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in + * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given + * input into a disjunction of equality filters and returns the expanded filter. + */ function __PRIVATE_computeInExpansion(e) { + if (__PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter, 20012), + e instanceof FieldFilter) { + if (e instanceof __PRIVATE_InFilter) { + const t = e.value.arrayValue?.values?.map((t => FieldFilter.create(e.field, "==" /* Operator.EQUAL */ , t))) || []; + return CompositeFilter.create(t, "or" /* CompositeOperator.OR */); + } + // We have reached other kinds of field filters. + return e; + } + // We have a composite filter. + const t = e.filters.map((e => __PRIVATE_computeInExpansion(e))); + return CompositeFilter.create(t, e.op); +} + +/** + * Given a composite filter, returns the list of terms in its disjunctive normal form. + * + *

Each element in the return value is one term of the resulting DNF. For instance: For the + * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list + * with two elements: a composite filter that performs (A && C), and a composite filter that + * performs (B && C). + * + * @param filter the composite filter to calculate DNF transform for. + * @return the terms in the DNF transform. + */ function __PRIVATE_getDnfTerms(e) { + if (0 === e.getFilters().length) return []; + const t = __PRIVATE_computeDistributedNormalForm(__PRIVATE_computeInExpansion(e)); + return __PRIVATE_hardAssert(__PRIVATE_isDisjunctiveNormalForm(t), 7391), __PRIVATE_isSingleFieldFilter(t) || __PRIVATE_isFlatConjunction(t) ? [ t ] : t.getFilters(); +} + +/** Returns true if the given filter is a single field filter. e.g. (a == 10). */ function __PRIVATE_isSingleFieldFilter(e) { + return e instanceof FieldFilter; +} + +/** + * Returns true if the given filter is the conjunction of one or more field filters. e.g. (a == 10 + * && b == 20) + */ function __PRIVATE_isFlatConjunction(e) { + return e instanceof CompositeFilter && __PRIVATE_compositeFilterIsFlatConjunction(e); +} + +/** + * Returns whether or not the given filter is in disjunctive normal form (DNF). + * + *

In boolean logic, a disjunctive normal form (DNF) is a canonical normal form of a logical + * formula consisting of a disjunction of conjunctions; it can also be described as an OR of ANDs. + * + *

For more info, visit: https://en.wikipedia.org/wiki/Disjunctive_normal_form + */ function __PRIVATE_isDisjunctiveNormalForm(e) { + return __PRIVATE_isSingleFieldFilter(e) || __PRIVATE_isFlatConjunction(e) || + /** + * Returns true if the given filter is the disjunction of one or more "flat conjunctions" and + * field filters. e.g. (a == 10) || (b==20 && c==30) + */ + function __PRIVATE_isDisjunctionOfFieldFiltersAndFlatConjunctions(e) { + if (e instanceof CompositeFilter && __PRIVATE_compositeFilterIsDisjunction(e)) { + for (const t of e.getFilters()) if (!__PRIVATE_isSingleFieldFilter(t) && !__PRIVATE_isFlatConjunction(t)) return !1; + return !0; + } + return !1; + }(e); +} + +function __PRIVATE_computeDistributedNormalForm(e) { + if (__PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter, 34018), + e instanceof FieldFilter) return e; + if (1 === e.filters.length) return __PRIVATE_computeDistributedNormalForm(e.filters[0]); + // Compute DNF for each of the subfilters first + const t = e.filters.map((e => __PRIVATE_computeDistributedNormalForm(e))); + let n = CompositeFilter.create(t, e.op); + return n = __PRIVATE_applyAssociation(n), __PRIVATE_isDisjunctiveNormalForm(n) ? n : (__PRIVATE_hardAssert(n instanceof CompositeFilter, 64498), + __PRIVATE_hardAssert(__PRIVATE_compositeFilterIsConjunction(n), 40251), __PRIVATE_hardAssert(n.filters.length > 1, 57927), + n.filters.reduce(((e, t) => __PRIVATE_applyDistribution(e, t)))); +} + +function __PRIVATE_applyDistribution(e, t) { + let n; + return __PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter, 38388), + __PRIVATE_hardAssert(t instanceof FieldFilter || t instanceof CompositeFilter, 25473), + // FieldFilter FieldFilter + n = e instanceof FieldFilter ? t instanceof FieldFilter ? function __PRIVATE_applyDistributionFieldFilters(e, t) { + // Conjunction distribution for two field filters is the conjunction of them. + return CompositeFilter.create([ e, t ], "and" /* CompositeOperator.AND */); + }(e, t) : __PRIVATE_applyDistributionFieldAndCompositeFilters(e, t) : t instanceof FieldFilter ? __PRIVATE_applyDistributionFieldAndCompositeFilters(t, e) : function __PRIVATE_applyDistributionCompositeFilters(e, t) { + // There are four cases: + // (A & B) & (C & D) --> (A & B & C & D) + // (A & B) & (C | D) --> (A & B & C) | (A & B & D) + // (A | B) & (C & D) --> (C & D & A) | (C & D & B) + // (A | B) & (C | D) --> (A & C) | (A & D) | (B & C) | (B & D) + // Case 1 is a merge. + if (__PRIVATE_hardAssert(e.filters.length > 0 && t.filters.length > 0, 48005), __PRIVATE_compositeFilterIsConjunction(e) && __PRIVATE_compositeFilterIsConjunction(t)) return __PRIVATE_compositeFilterWithAddedFilters(e, t.getFilters()); + // Case 2,3,4 all have at least one side (lhs or rhs) that is a disjunction. In all three cases + // we should take each element of the disjunction and distribute it over the other side, and + // return the disjunction of the distribution results. + const n = __PRIVATE_compositeFilterIsDisjunction(e) ? e : t, r = __PRIVATE_compositeFilterIsDisjunction(e) ? t : e, i = n.filters.map((e => __PRIVATE_applyDistribution(e, r))); + return CompositeFilter.create(i, "or" /* CompositeOperator.OR */); + }(e, t), __PRIVATE_applyAssociation(n); +} + +function __PRIVATE_applyDistributionFieldAndCompositeFilters(e, t) { + // There are two cases: + // A & (B & C) --> (A & B & C) + // A & (B | C) --> (A & B) | (A & C) + if (__PRIVATE_compositeFilterIsConjunction(t)) + // Case 1 + return __PRIVATE_compositeFilterWithAddedFilters(t, e.getFilters()); + { + // Case 2 + const n = t.filters.map((t => __PRIVATE_applyDistribution(e, t))); + return CompositeFilter.create(n, "or" /* CompositeOperator.OR */); + } +} + +/** + * Applies the associativity property to the given filter and returns the resulting filter. + * + *

    + *
  • A | (B | C) == (A | B) | C == (A | B | C) + *
  • A & (B & C) == (A & B) & C == (A & B & C) + *
+ * + *

For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic + */ function __PRIVATE_applyAssociation(e) { + if (__PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter, 11850), + e instanceof FieldFilter) return e; + const t = e.getFilters(); + // If the composite filter only contains 1 filter, apply associativity to it. + if (1 === t.length) return __PRIVATE_applyAssociation(t[0]); + // Associativity applied to a flat composite filter results is itself. + if (__PRIVATE_compositeFilterIsFlat(e)) return e; + // First apply associativity to all subfilters. This will in turn recursively apply + // associativity to all nested composite filters and field filters. + const n = t.map((e => __PRIVATE_applyAssociation(e))), r = []; + // For composite subfilters that perform the same kind of logical operation as `compositeFilter` + // take out their filters and add them to `compositeFilter`. For example: + // compositeFilter = (A | (B | C | D)) + // compositeSubfilter = (B | C | D) + // Result: (A | B | C | D) + // Note that the `compositeSubfilter` has been eliminated, and its filters (B, C, D) have been + // added to the top-level "compositeFilter". + return n.forEach((t => { + t instanceof FieldFilter ? r.push(t) : t instanceof CompositeFilter && (t.op === e.op ? + // compositeFilter: (A | (B | C)) + // compositeSubfilter: (B | C) + // Result: (A | B | C) + r.push(...t.filters) : + // compositeFilter: (A | (B & C)) + // compositeSubfilter: (B & C) + // Result: (A | (B & C)) + r.push(t)); + })), 1 === r.length ? r[0] : CompositeFilter.create(r, e.op); +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An in-memory implementation of IndexManager. + */ class __PRIVATE_MemoryIndexManager { + constructor() { + this.Cn = new __PRIVATE_MemoryCollectionParentIndex; + } + addToCollectionParentIndex(e, t) { + return this.Cn.add(t), PersistencePromise.resolve(); + } + getCollectionParents(e, t) { + return PersistencePromise.resolve(this.Cn.getEntries(t)); + } + addFieldIndex(e, t) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(); + } + deleteFieldIndex(e, t) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(); + } + deleteAllFieldIndexes(e) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(); + } + createTargetIndexes(e, t) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(); + } + getDocumentsMatchingTarget(e, t) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(null); + } + getIndexType(e, t) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(0 /* IndexType.NONE */); + } + getFieldIndexes(e, t) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve([]); + } + getNextCollectionGroupToUpdate(e) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(null); + } + getMinOffset(e, t) { + return PersistencePromise.resolve(IndexOffset.min()); + } + getMinOffsetFromCollectionGroup(e, t) { + return PersistencePromise.resolve(IndexOffset.min()); + } + updateCollectionGroup(e, t, n) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(); + } + updateIndexEntries(e, t) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(); + } +} + +/** + * Internal implementation of the collection-parent index exposed by MemoryIndexManager. + * Also used for in-memory caching by IndexedDbIndexManager and initial index population + * in indexeddb_schema.ts + */ class __PRIVATE_MemoryCollectionParentIndex { + constructor() { + this.index = {}; + } + // Returns false if the entry already existed. + add(e) { + const t = e.lastSegment(), n = e.popLast(), r = this.index[t] || new SortedSet(ResourcePath.comparator), i = !r.has(n); + return this.index[t] = r.add(n), i; + } + has(e) { + const t = e.lastSegment(), n = e.popLast(), r = this.index[t]; + return r && r.has(n); + } + getEntries(e) { + return (this.index[e] || new SortedSet(ResourcePath.comparator)).toArray(); + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const Ft = "IndexedDbIndexManager", Mt = new Uint8Array(0); + +/** + * A persisted implementation of IndexManager. + * + * PORTING NOTE: Unlike iOS and Android, the Web SDK does not memoize index + * data as it supports multi-tab access. + */ +class __PRIVATE_IndexedDbIndexManager { + constructor(e, t) { + this.databaseId = t, + /** + * An in-memory copy of the index entries we've already written since the SDK + * launched. Used to avoid re-writing the same entry repeatedly. + * + * This is *NOT* a complete cache of what's in persistence and so can never be + * used to satisfy reads. + */ + this.vn = new __PRIVATE_MemoryCollectionParentIndex, + /** + * Maps from a target to its equivalent list of sub-targets. Each sub-target + * contains only one term from the target's disjunctive normal form (DNF). + */ + this.Fn = new ObjectMap((e => __PRIVATE_canonifyTarget(e)), ((e, t) => __PRIVATE_targetEquals(e, t))), + this.uid = e.uid || ""; + } + /** + * Adds a new entry to the collection parent index. + * + * Repeated calls for the same collectionPath should be avoided within a + * transaction as IndexedDbIndexManager only caches writes once a transaction + * has been committed. + */ addToCollectionParentIndex(e, t) { + if (!this.vn.has(t)) { + const n = t.lastSegment(), r = t.popLast(); + e.addOnCommittedListener((() => { + // Add the collection to the in memory cache only if the transaction was + // successfully committed. + this.vn.add(t); + })); + const i = { + collectionId: n, + parent: __PRIVATE_encodeResourcePath(r) + }; + return __PRIVATE_collectionParentsStore(e).put(i); + } + return PersistencePromise.resolve(); + } + getCollectionParents(e, t) { + const n = [], r = IDBKeyRange.bound([ t, "" ], [ __PRIVATE_immediateSuccessor(t), "" ], + /*lowerOpen=*/ !1, + /*upperOpen=*/ !0); + return __PRIVATE_collectionParentsStore(e).J(r).next((e => { + for (const r of e) { + // This collectionId guard shouldn't be necessary (and isn't as long + // as we're running in a real browser), but there's a bug in + // indexeddbshim that breaks our range in our tests running in node: + // https://github.com/axemclion/IndexedDBShim/issues/334 + if (r.collectionId !== t) break; + n.push(__PRIVATE_decodeResourcePath(r.parent)); + } + return n; + })); + } + addFieldIndex(e, t) { + // TODO(indexing): Verify that the auto-incrementing index ID works in + // Safari & Firefox. + const n = __PRIVATE_indexConfigurationStore(e), r = function __PRIVATE_toDbIndexConfiguration(e) { + return { + indexId: e.indexId, + collectionGroup: e.collectionGroup, + fields: e.fields.map((e => [ e.fieldPath.canonicalString(), e.kind ])) + }; + }(t); + delete r.indexId; + // `indexId` is auto-populated by IndexedDb + const i = n.add(r); + if (t.indexState) { + const n = __PRIVATE_indexStateStore(e); + return i.next((e => { + n.put(__PRIVATE_toDbIndexState(e, this.uid, t.indexState.sequenceNumber, t.indexState.offset)); + })); + } + return i.next(); + } + deleteFieldIndex(e, t) { + const n = __PRIVATE_indexConfigurationStore(e), r = __PRIVATE_indexStateStore(e), i = __PRIVATE_indexEntriesStore(e); + return n.delete(t.indexId).next((() => r.delete(IDBKeyRange.bound([ t.indexId ], [ t.indexId + 1 ], + /*lowerOpen=*/ !1, + /*upperOpen=*/ !0)))).next((() => i.delete(IDBKeyRange.bound([ t.indexId ], [ t.indexId + 1 ], + /*lowerOpen=*/ !1, + /*upperOpen=*/ !0)))); + } + deleteAllFieldIndexes(e) { + const t = __PRIVATE_indexConfigurationStore(e), n = __PRIVATE_indexEntriesStore(e), r = __PRIVATE_indexStateStore(e); + return t.Z().next((() => n.Z())).next((() => r.Z())); + } + createTargetIndexes(e, t) { + return PersistencePromise.forEach(this.Mn(t), (t => this.getIndexType(e, t).next((n => { + if (0 /* IndexType.NONE */ === n || 1 /* IndexType.PARTIAL */ === n) { + const n = new __PRIVATE_TargetIndexMatcher(t).Dn(); + if (null != n) return this.addFieldIndex(e, n); + } + })))); + } + getDocumentsMatchingTarget(e, t) { + const n = __PRIVATE_indexEntriesStore(e); + let r = !0; + const i = new Map; + return PersistencePromise.forEach(this.Mn(t), (t => this.xn(e, t).next((e => { + r && (r = !!e), i.set(t, e); + })))).next((() => { + if (r) { + let e = __PRIVATE_documentKeySet(); + const r = []; + return PersistencePromise.forEach(i, ((i, s) => { + __PRIVATE_logDebug(Ft, `Using index ${function __PRIVATE_fieldIndexToString(e) { + return `id=${e.indexId}|cg=${e.collectionGroup}|f=${e.fields.map((e => `${e.fieldPath}:${e.kind}`)).join(",")}`; + }(i)} to execute ${__PRIVATE_canonifyTarget(t)}`); + const o = function __PRIVATE_targetGetArrayValues(e, t) { + const n = __PRIVATE_fieldIndexGetArraySegment(t); + if (void 0 === n) return null; + for (const t of __PRIVATE_targetGetFieldFiltersForPath(e, n.fieldPath)) switch (t.op) { + case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ : + return t.value.arrayValue.values || []; + + case "array-contains" /* Operator.ARRAY_CONTAINS */ : + return [ t.value ]; + // Remaining filters are not array filters. + } + return null; + } + /** + * Returns the list of values that are used in != or NOT_IN filters. Returns + * `null` if there are no such filters. + */ (s, i), _ = function __PRIVATE_targetGetNotInValues(e, t) { + const n = new Map; + for (const r of __PRIVATE_fieldIndexGetDirectionalSegments(t)) for (const t of __PRIVATE_targetGetFieldFiltersForPath(e, r.fieldPath)) switch (t.op) { + case "==" /* Operator.EQUAL */ : + case "in" /* Operator.IN */ : + // Encode equality prefix, which is encoded in the index value before + // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to + // `value != 'ab'`). + n.set(r.fieldPath.canonicalString(), t.value); + break; + + case "not-in" /* Operator.NOT_IN */ : + case "!=" /* Operator.NOT_EQUAL */ : + // NotIn/NotEqual is always a suffix. There cannot be any remaining + // segments and hence we can return early here. + return n.set(r.fieldPath.canonicalString(), t.value), Array.from(n.values()); + // Remaining filters cannot be used as notIn bounds. + } + return null; + } + /** + * Returns a lower bound of field values that can be used as a starting point to + * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound + * exists. + */ (s, i), a = function __PRIVATE_targetGetLowerBound(e, t) { + const n = []; + let r = !0; + // For each segment, retrieve a lower bound if there is a suitable filter or + // startAt. + for (const i of __PRIVATE_fieldIndexGetDirectionalSegments(t)) { + const t = 0 /* IndexKind.ASCENDING */ === i.kind ? __PRIVATE_targetGetAscendingBound(e, i.fieldPath, e.startAt) : __PRIVATE_targetGetDescendingBound(e, i.fieldPath, e.startAt); + n.push(t.value), r && (r = t.inclusive); + } + return new Bound(n, r); + } + /** + * Returns an upper bound of field values that can be used as an ending point + * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no + * upper bound exists. + */ (s, i), u = function __PRIVATE_targetGetUpperBound(e, t) { + const n = []; + let r = !0; + // For each segment, retrieve an upper bound if there is a suitable filter or + // endAt. + for (const i of __PRIVATE_fieldIndexGetDirectionalSegments(t)) { + const t = 0 /* IndexKind.ASCENDING */ === i.kind ? __PRIVATE_targetGetDescendingBound(e, i.fieldPath, e.endAt) : __PRIVATE_targetGetAscendingBound(e, i.fieldPath, e.endAt); + n.push(t.value), r && (r = t.inclusive); + } + return new Bound(n, r); + }(s, i), c = this.On(i, s, a), l = this.On(i, s, u), h = this.Nn(i, s, _), P = this.Bn(i.indexId, o, c, a.inclusive, l, u.inclusive, h); + return PersistencePromise.forEach(P, (i => n.Y(i, t.limit).next((t => { + t.forEach((t => { + const n = DocumentKey.fromSegments(t.documentKey); + e.has(n) || (e = e.add(n), r.push(n)); + })); + })))); + })).next((() => r)); + } + return PersistencePromise.resolve(null); + })); + } + Mn(e) { + let t = this.Fn.get(e); + if (t) return t; + if (0 === e.filters.length) t = [ e ]; else { + t = __PRIVATE_getDnfTerms(CompositeFilter.create(e.filters, "and" /* CompositeOperator.AND */)).map((t => __PRIVATE_newTarget(e.path, e.collectionGroup, e.orderBy, t.getFilters(), e.limit, e.startAt, e.endAt))); + } + return this.Fn.set(e, t), t; + } + /** + * Constructs a key range query on `DbIndexEntryStore` that unions all + * bounds. + */ Bn(e, t, n, r, i, s, o) { + // The number of total index scans we union together. This is similar to a + // distributed normal form, but adapted for array values. We create a single + // index range per value in an ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filter + // combined with the values from the query bounds. + const _ = (null != t ? t.length : 1) * Math.max(n.length, i.length), a = _ / (null != t ? t.length : 1), u = []; + for (let c = 0; c < _; ++c) { + const _ = t ? this.Ln(t[c / a]) : Mt, l = this.kn(e, _, n[c % a], r), h = this.qn(e, _, i[c % a], s), P = o.map((t => this.kn(e, _, t, + /* inclusive= */ !0))); + u.push(...this.createRange(l, h, P)); + } + return u; + } + /** Generates the lower bound for `arrayValue` and `directionalValue`. */ kn(e, t, n, r) { + const i = new __PRIVATE_IndexEntry(e, DocumentKey.empty(), t, n); + return r ? i : i.An(); + } + /** Generates the upper bound for `arrayValue` and `directionalValue`. */ qn(e, t, n, r) { + const i = new __PRIVATE_IndexEntry(e, DocumentKey.empty(), t, n); + return r ? i.An() : i; + } + xn(e, t) { + const n = new __PRIVATE_TargetIndexMatcher(t), r = null != t.collectionGroup ? t.collectionGroup : t.path.lastSegment(); + return this.getFieldIndexes(e, r).next((e => { + // Return the index with the most number of segments. + let t = null; + for (const r of e) { + n.yn(r) && (!t || r.fields.length > t.fields.length) && (t = r); + } + return t; + })); + } + getIndexType(e, t) { + let n = 2 /* IndexType.FULL */; + const r = this.Mn(t); + return PersistencePromise.forEach(r, (t => this.xn(e, t).next((e => { + e ? 0 /* IndexType.NONE */ !== n && e.fields.length < function __PRIVATE_targetGetSegmentCount(e) { + let t = new SortedSet(FieldPath$1.comparator), n = !1; + for (const r of e.filters) for (const e of r.getFlattenedFilters()) + // __name__ is not an explicit segment of any index, so we don't need to + // count it. + e.field.isKeyField() || ( + // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately. + // For instance, it is possible to have an index for "a ARRAY a ASC". Even + // though these are on the same field, they should be counted as two + // separate segments in an index. + "array-contains" /* Operator.ARRAY_CONTAINS */ === e.op || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === e.op ? n = !0 : t = t.add(e.field)); + for (const n of e.orderBy) + // __name__ is not an explicit segment of any index, so we don't need to + // count it. + n.field.isKeyField() || (t = t.add(n.field)); + return t.size + (n ? 1 : 0); + }(t) && (n = 1 /* IndexType.PARTIAL */) : n = 0 /* IndexType.NONE */; + })))).next((() => + // OR queries have more than one sub-target (one sub-target per DNF term). We currently consider + // OR queries that have a `limit` to have a partial index. For such queries we perform sorting + // and apply the limit in memory as a post-processing step. + function __PRIVATE_targetHasLimit(e) { + return null !== e.limit; + }(t) && r.length > 1 && 2 /* IndexType.FULL */ === n ? 1 /* IndexType.PARTIAL */ : n)); + } + /** + * Returns the byte encoded form of the directional values in the field index. + * Returns `null` if the document does not have all fields specified in the + * index. + */ Qn(e, t) { + const n = new __PRIVATE_IndexByteEncoder; + for (const r of __PRIVATE_fieldIndexGetDirectionalSegments(e)) { + const e = t.data.field(r.fieldPath); + if (null == e) return null; + const i = n.Pn(r.kind); + __PRIVATE_FirestoreIndexValueWriter.Kt.Dt(e, i); + } + return n.un(); + } + /** Encodes a single value to the ascending index format. */ Ln(e) { + const t = new __PRIVATE_IndexByteEncoder; + return __PRIVATE_FirestoreIndexValueWriter.Kt.Dt(e, t.Pn(0 /* IndexKind.ASCENDING */)), + t.un(); + } + /** + * Returns an encoded form of the document key that sorts based on the key + * ordering of the field index. + */ $n(e, t) { + const n = new __PRIVATE_IndexByteEncoder; + return __PRIVATE_FirestoreIndexValueWriter.Kt.Dt(__PRIVATE_refValue(this.databaseId, t), n.Pn(function __PRIVATE_fieldIndexGetKeyOrder(e) { + const t = __PRIVATE_fieldIndexGetDirectionalSegments(e); + return 0 === t.length ? 0 /* IndexKind.ASCENDING */ : t[t.length - 1].kind; + }(e))), n.un(); + } + /** + * Encodes the given field values according to the specification in `target`. + * For IN queries, a list of possible values is returned. + */ Nn(e, t, n) { + if (null === n) return []; + let r = []; + r.push(new __PRIVATE_IndexByteEncoder); + let i = 0; + for (const s of __PRIVATE_fieldIndexGetDirectionalSegments(e)) { + const e = n[i++]; + for (const n of r) if (this.Un(t, s.fieldPath) && isArray(e)) r = this.Kn(r, s, e); else { + const t = n.Pn(s.kind); + __PRIVATE_FirestoreIndexValueWriter.Kt.Dt(e, t); + } + } + return this.Wn(r); + } + /** + * Encodes the given bounds according to the specification in `target`. For IN + * queries, a list of possible values is returned. + */ On(e, t, n) { + return this.Nn(e, t, n.position); + } + /** Returns the byte representation for the provided encoders. */ Wn(e) { + const t = []; + for (let n = 0; n < e.length; ++n) t[n] = e[n].un(); + return t; + } + /** + * Creates a separate encoder for each element of an array. + * + * The method appends each value to all existing encoders (e.g. filter("a", + * "==", "a1").filter("b", "in", ["b1", "b2"]) becomes ["a1,b1", "a1,b2"]). A + * list of new encoders is returned. + */ Kn(e, t, n) { + const r = [ ...e ], i = []; + for (const e of n.arrayValue.values || []) for (const n of r) { + const r = new __PRIVATE_IndexByteEncoder; + r.seed(n.un()), __PRIVATE_FirestoreIndexValueWriter.Kt.Dt(e, r.Pn(t.kind)), i.push(r); + } + return i; + } + Un(e, t) { + return !!e.filters.find((e => e instanceof FieldFilter && e.field.isEqual(t) && ("in" /* Operator.IN */ === e.op || "not-in" /* Operator.NOT_IN */ === e.op))); + } + getFieldIndexes(e, t) { + const n = __PRIVATE_indexConfigurationStore(e), r = __PRIVATE_indexStateStore(e); + return (t ? n.J(xe, IDBKeyRange.bound(t, t)) : n.J()).next((e => { + const t = []; + return PersistencePromise.forEach(e, (e => r.get([ e.indexId, this.uid ]).next((n => { + t.push(function __PRIVATE_fromDbIndexConfiguration(e, t) { + const n = t ? new IndexState(t.sequenceNumber, new IndexOffset(__PRIVATE_fromDbTimestamp(t.readTime), new DocumentKey(__PRIVATE_decodeResourcePath(t.documentKey)), t.largestBatchId)) : IndexState.empty(), r = e.fields.map((([e, t]) => new IndexSegment(FieldPath$1.fromServerFormat(e), t))); + return new FieldIndex(e.indexId, e.collectionGroup, r, n); + }(e, n)); + })))).next((() => t)); + })); + } + getNextCollectionGroupToUpdate(e) { + return this.getFieldIndexes(e).next((e => 0 === e.length ? null : (e.sort(((e, t) => { + const n = e.indexState.sequenceNumber - t.indexState.sequenceNumber; + return 0 !== n ? n : __PRIVATE_primitiveComparator(e.collectionGroup, t.collectionGroup); + })), e[0].collectionGroup))); + } + updateCollectionGroup(e, t, n) { + const r = __PRIVATE_indexConfigurationStore(e), i = __PRIVATE_indexStateStore(e); + return this.Gn(e).next((e => r.J(xe, IDBKeyRange.bound(t, t)).next((t => PersistencePromise.forEach(t, (t => i.put(__PRIVATE_toDbIndexState(t.indexId, this.uid, e, n)))))))); + } + updateIndexEntries(e, t) { + // Porting Note: `getFieldIndexes()` on Web does not cache index lookups as + // it could be used across different IndexedDB transactions. As any cached + // data might be invalidated by other multi-tab clients, we can only trust + // data within a single IndexedDB transaction. We therefore add a cache + // here. + const n = new Map; + return PersistencePromise.forEach(t, ((t, r) => { + const i = n.get(t.collectionGroup); + return (i ? PersistencePromise.resolve(i) : this.getFieldIndexes(e, t.collectionGroup)).next((i => (n.set(t.collectionGroup, i), + PersistencePromise.forEach(i, (n => this.zn(e, t, n).next((t => { + const i = this.jn(r, n); + return t.isEqual(i) ? PersistencePromise.resolve() : this.Jn(e, r, n, t, i); + }))))))); + })); + } + Hn(e, t, n, r) { + return __PRIVATE_indexEntriesStore(e).put(r.Rn(this.uid, this.$n(n, t.key), t.key)); + } + Yn(e, t, n, r) { + return __PRIVATE_indexEntriesStore(e).delete(r.Vn(this.uid, this.$n(n, t.key), t.key)); + } + zn(e, t, n) { + const r = __PRIVATE_indexEntriesStore(e); + let i = new SortedSet(__PRIVATE_indexEntryComparator); + return r.ee({ + index: $e, + range: IDBKeyRange.only([ n.indexId, this.uid, __PRIVATE_encodeKeySafeBytes(this.$n(n, t)) ]) + }, ((e, r) => { + i = i.add(new __PRIVATE_IndexEntry(n.indexId, t, __PRIVATE_decodeKeySafeBytes(r.arrayValue), __PRIVATE_decodeKeySafeBytes(r.directionalValue))); + })).next((() => i)); + } + /** Creates the index entries for the given document. */ jn(e, t) { + let n = new SortedSet(__PRIVATE_indexEntryComparator); + const r = this.Qn(t, e); + if (null == r) return n; + const i = __PRIVATE_fieldIndexGetArraySegment(t); + if (null != i) { + const s = e.data.field(i.fieldPath); + if (isArray(s)) for (const i of s.arrayValue.values || []) n = n.add(new __PRIVATE_IndexEntry(t.indexId, e.key, this.Ln(i), r)); + } else n = n.add(new __PRIVATE_IndexEntry(t.indexId, e.key, Mt, r)); + return n; + } + /** + * Updates the index entries for the provided document by deleting entries + * that are no longer referenced in `newEntries` and adding all newly added + * entries. + */ Jn(e, t, n, r, i) { + __PRIVATE_logDebug(Ft, "Updating index entries for document '%s'", t.key); + const s = []; + return function __PRIVATE_diffSortedSets(e, t, n, r, i) { + const s = e.getIterator(), o = t.getIterator(); + let _ = __PRIVATE_advanceIterator(s), a = __PRIVATE_advanceIterator(o); + // Walk through the two sets at the same time, using the ordering defined by + // `comparator`. + for (;_ || a; ) { + let e = !1, t = !1; + if (_ && a) { + const r = n(_, a); + r < 0 ? + // The element was removed if the next element in our ordered + // walkthrough is only in `before`. + t = !0 : r > 0 && ( + // The element was added if the next element in our ordered walkthrough + // is only in `after`. + e = !0); + } else null != _ ? t = !0 : e = !0; + e ? (r(a), a = __PRIVATE_advanceIterator(o)) : t ? (i(_), _ = __PRIVATE_advanceIterator(s)) : (_ = __PRIVATE_advanceIterator(s), + a = __PRIVATE_advanceIterator(o)); + } + }(r, i, __PRIVATE_indexEntryComparator, ( + /* onAdd= */ r => { + s.push(this.Hn(e, t, n, r)); + }), ( + /* onRemove= */ r => { + s.push(this.Yn(e, t, n, r)); + })), PersistencePromise.waitFor(s); + } + Gn(e) { + let t = 1; + return __PRIVATE_indexStateStore(e).ee({ + index: Le, + reverse: !0, + range: IDBKeyRange.upperBound([ this.uid, Number.MAX_SAFE_INTEGER ]) + }, ((e, n, r) => { + r.done(), t = n.sequenceNumber + 1; + })).next((() => t)); + } + /** + * Returns a new set of IDB ranges that splits the existing range and excludes + * any values that match the `notInValue` from these ranges. As an example, + * '[foo > 2 && foo != 3]` becomes `[foo > 2 && < 3, foo > 3]`. + */ createRange(e, t, n) { + // The notIn values need to be sorted and unique so that we can return a + // sorted set of non-overlapping ranges. + n = n.sort(((e, t) => __PRIVATE_indexEntryComparator(e, t))).filter(((e, t, n) => !t || 0 !== __PRIVATE_indexEntryComparator(e, n[t - 1]))); + const r = []; + r.push(e); + for (const i of n) { + const n = __PRIVATE_indexEntryComparator(i, e), s = __PRIVATE_indexEntryComparator(i, t); + if (0 === n) + // `notInValue` is the lower bound. We therefore need to raise the bound + // to the next value. + r[0] = e.An(); else if (n > 0 && s < 0) + // `notInValue` is in the middle of the range + r.push(i), r.push(i.An()); else if (s > 0) + // `notInValue` (and all following values) are out of the range + break; + } + r.push(t); + const i = []; + for (let e = 0; e < r.length; e += 2) { + // If we encounter two bounds that will create an unmatchable key range, + // then we return an empty set of key ranges. + if (this.Zn(r[e], r[e + 1])) return []; + const t = r[e].Vn(this.uid, Mt, DocumentKey.empty()), n = r[e + 1].Vn(this.uid, Mt, DocumentKey.empty()); + i.push(IDBKeyRange.bound(t, n)); + } + return i; + } + Zn(e, t) { + // If lower bound is greater than the upper bound, then the key + // range can never be matched. + return __PRIVATE_indexEntryComparator(e, t) > 0; + } + getMinOffsetFromCollectionGroup(e, t) { + return this.getFieldIndexes(e, t).next(__PRIVATE_getMinOffsetFromFieldIndexes); + } + getMinOffset(e, t) { + return PersistencePromise.mapArray(this.Mn(t), (t => this.xn(e, t).next((e => e || fail(44426))))).next(__PRIVATE_getMinOffsetFromFieldIndexes); + } +} + +/** + * Helper to get a typed SimpleDbStore for the collectionParents + * document store. + */ function __PRIVATE_collectionParentsStore(e) { + return __PRIVATE_getStore(e, pe); +} + +/** + * Helper to get a typed SimpleDbStore for the index entry object store. + */ function __PRIVATE_indexEntriesStore(e) { + return __PRIVATE_getStore(e, qe); +} + +/** + * Helper to get a typed SimpleDbStore for the index configuration object store. + */ function __PRIVATE_indexConfigurationStore(e) { + return __PRIVATE_getStore(e, Fe); +} + +/** + * Helper to get a typed SimpleDbStore for the index state object store. + */ function __PRIVATE_indexStateStore(e) { + return __PRIVATE_getStore(e, Ne); +} + +function __PRIVATE_getMinOffsetFromFieldIndexes(e) { + __PRIVATE_hardAssert(0 !== e.length, 28825); + let t = e[0].indexState.offset, n = t.largestBatchId; + for (let r = 1; r < e.length; r++) { + const i = e[r].indexState.offset; + __PRIVATE_indexOffsetComparator(i, t) < 0 && (t = i), n < i.largestBatchId && (n = i.largestBatchId); + } + return new IndexOffset(t.readTime, t.documentKey, n); +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const xt = { + didRun: !1, + sequenceNumbersCollected: 0, + targetsRemoved: 0, + documentsRemoved: 0 +}, Ot = 41943040; + +class LruParams { + static withCacheSize(e) { + return new LruParams(e, LruParams.DEFAULT_COLLECTION_PERCENTILE, LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT); + } + constructor( + // When we attempt to collect, we will only do so if the cache size is greater than this + // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped. + e, + // The percentage of sequence numbers that we will attempt to collect + t, + // A cap on the total number of sequence numbers that will be collected. This prevents + // us from collecting a huge number of sequence numbers if the cache has grown very large. + n) { + this.cacheSizeCollectionThreshold = e, this.percentileToCollect = t, this.maximumSequenceNumbersToCollect = n; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Delete a mutation batch and the associated document mutations. + * @returns A PersistencePromise of the document mutations that were removed. + */ +function removeMutationBatch(e, t, n) { + const r = e.store(te), i = e.store(oe), s = [], o = IDBKeyRange.only(n.batchId); + let _ = 0; + const a = r.ee({ + range: o + }, ((e, t, n) => (_++, n.delete()))); + s.push(a.next((() => { + __PRIVATE_hardAssert(1 === _, 47070, { + batchId: n.batchId + }); + }))); + const u = []; + for (const e of n.mutations) { + const r = __PRIVATE_newDbDocumentMutationKey(t, e.key.path, n.batchId); + s.push(i.delete(r)), u.push(e.key); + } + return PersistencePromise.waitFor(s).next((() => u)); +} + +/** + * Returns an approximate size for the given document. + */ function __PRIVATE_dbDocumentSize(e) { + if (!e) return 0; + let t; + if (e.document) t = e.document; else if (e.unknownDocument) t = e.unknownDocument; else { + if (!e.noDocument) throw fail(14731); + t = e.noDocument; + } + return JSON.stringify(t).length; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** A mutation queue for a specific user, backed by IndexedDB. */ LruParams.DEFAULT_COLLECTION_PERCENTILE = 10, +LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1e3, LruParams.DEFAULT = new LruParams(Ot, LruParams.DEFAULT_COLLECTION_PERCENTILE, LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT), +LruParams.DISABLED = new LruParams(-1, 0, 0); + +class __PRIVATE_IndexedDbMutationQueue { + constructor( + /** + * The normalized userId (e.g. null UID => "" userId) used to store / + * retrieve mutations. + */ + e, t, n, r) { + this.userId = e, this.serializer = t, this.indexManager = n, this.referenceDelegate = r, + /** + * Caches the document keys for pending mutation batches. If the mutation + * has been removed from IndexedDb, the cached value may continue to + * be used to retrieve the batch's document keys. To remove a cached value + * locally, `removeCachedMutationKeys()` should be invoked either directly + * or through `removeMutationBatches()`. + * + * With multi-tab, when the primary client acknowledges or rejects a mutation, + * this cache is used by secondary clients to invalidate the local + * view of the documents that were previously affected by the mutation. + */ + // PORTING NOTE: Multi-tab only. + this.Xn = {}; + } + /** + * Creates a new mutation queue for the given user. + * @param user - The user for which to create a mutation queue. + * @param serializer - The serializer to use when persisting to IndexedDb. + */ static wt(e, t, n, r) { + // TODO(mcg): Figure out what constraints there are on userIDs + // In particular, are there any reserved characters? are empty ids allowed? + // For the moment store these together in the same mutations table assuming + // that empty userIDs aren't allowed. + __PRIVATE_hardAssert("" !== e.uid, 64387); + const i = e.isAuthenticated() ? e.uid : ""; + return new __PRIVATE_IndexedDbMutationQueue(i, t, n, r); + } + checkEmpty(e) { + let t = !0; + const n = IDBKeyRange.bound([ this.userId, Number.NEGATIVE_INFINITY ], [ this.userId, Number.POSITIVE_INFINITY ]); + return __PRIVATE_mutationsStore(e).ee({ + index: re, + range: n + }, ((e, n, r) => { + t = !1, r.done(); + })).next((() => t)); + } + addMutationBatch(e, t, n, r) { + const i = __PRIVATE_documentMutationsStore(e), s = __PRIVATE_mutationsStore(e); + // The IndexedDb implementation in Chrome (and Firefox) does not handle + // compound indices that include auto-generated keys correctly. To ensure + // that the index entry is added correctly in all browsers, we perform two + // writes: The first write is used to retrieve the next auto-generated Batch + // ID, and the second write populates the index and stores the actual + // mutation batch. + // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972 + // We write an empty object to obtain key + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return s.add({}).next((o => { + __PRIVATE_hardAssert("number" == typeof o, 49019); + const _ = new MutationBatch(o, t, n, r), a = function __PRIVATE_toDbMutationBatch(e, t, n) { + const r = n.baseMutations.map((t => toMutation(e.yt, t))), i = n.mutations.map((t => toMutation(e.yt, t))); + return { + userId: t, + batchId: n.batchId, + localWriteTimeMs: n.localWriteTime.toMillis(), + baseMutations: r, + mutations: i + }; + }(this.serializer, this.userId, _), u = []; + let c = new SortedSet(((e, t) => __PRIVATE_primitiveComparator(e.canonicalString(), t.canonicalString()))); + for (const e of r) { + const t = __PRIVATE_newDbDocumentMutationKey(this.userId, e.key.path, o); + c = c.add(e.key.path.popLast()), u.push(s.put(a)), u.push(i.put(t, se)); + } + return c.forEach((t => { + u.push(this.indexManager.addToCollectionParentIndex(e, t)); + })), e.addOnCommittedListener((() => { + this.Xn[o] = _.keys(); + })), PersistencePromise.waitFor(u).next((() => _)); + })); + } + lookupMutationBatch(e, t) { + return __PRIVATE_mutationsStore(e).get(t).next((e => e ? (__PRIVATE_hardAssert(e.userId === this.userId, 48, "Unexpected user for mutation batch", { + userId: e.userId, + batchId: t + }), __PRIVATE_fromDbMutationBatch(this.serializer, e)) : null)); + } + /** + * Returns the document keys for the mutation batch with the given batchId. + * For primary clients, this method returns `null` after + * `removeMutationBatches()` has been called. Secondary clients return a + * cached result until `removeCachedMutationKeys()` is invoked. + */ + // PORTING NOTE: Multi-tab only. + er(e, t) { + return this.Xn[t] ? PersistencePromise.resolve(this.Xn[t]) : this.lookupMutationBatch(e, t).next((e => { + if (e) { + const n = e.keys(); + return this.Xn[t] = n, n; + } + return null; + })); + } + getNextMutationBatchAfterBatchId(e, t) { + const n = t + 1, r = IDBKeyRange.lowerBound([ this.userId, n ]); + let i = null; + return __PRIVATE_mutationsStore(e).ee({ + index: re, + range: r + }, ((e, t, r) => { + t.userId === this.userId && (__PRIVATE_hardAssert(t.batchId >= n, 47524, { + tr: n + }), i = __PRIVATE_fromDbMutationBatch(this.serializer, t)), r.done(); + })).next((() => i)); + } + getHighestUnacknowledgedBatchId(e) { + const t = IDBKeyRange.upperBound([ this.userId, Number.POSITIVE_INFINITY ]); + let n = j; + return __PRIVATE_mutationsStore(e).ee({ + index: re, + range: t, + reverse: !0 + }, ((e, t, r) => { + n = t.batchId, r.done(); + })).next((() => n)); + } + getAllMutationBatches(e) { + const t = IDBKeyRange.bound([ this.userId, j ], [ this.userId, Number.POSITIVE_INFINITY ]); + return __PRIVATE_mutationsStore(e).J(re, t).next((e => e.map((e => __PRIVATE_fromDbMutationBatch(this.serializer, e))))); + } + getAllMutationBatchesAffectingDocumentKey(e, t) { + // Scan the document-mutation index starting with a prefix starting with + // the given documentKey. + const n = __PRIVATE_newDbDocumentMutationPrefixForPath(this.userId, t.path), r = IDBKeyRange.lowerBound(n), i = []; + return __PRIVATE_documentMutationsStore(e).ee({ + range: r + }, ((n, r, s) => { + const [o, _, a] = n, u = __PRIVATE_decodeResourcePath(_); + // Only consider rows matching exactly the specific key of + // interest. Note that because we order by path first, and we + // order terminators before path separators, we'll encounter all + // the index rows for documentKey contiguously. In particular, all + // the rows for documentKey will occur before any rows for + // documents nested in a subcollection beneath documentKey so we + // can stop as soon as we hit any such row. + if (o === this.userId && t.path.isEqual(u)) + // Look up the mutation batch in the store. + return __PRIVATE_mutationsStore(e).get(a).next((e => { + if (!e) throw fail(61480, { + nr: n, + batchId: a + }); + __PRIVATE_hardAssert(e.userId === this.userId, 10503, "Unexpected user for mutation batch", { + userId: e.userId, + batchId: a + }), i.push(__PRIVATE_fromDbMutationBatch(this.serializer, e)); + })); + s.done(); + })).next((() => i)); + } + getAllMutationBatchesAffectingDocumentKeys(e, t) { + let n = new SortedSet(__PRIVATE_primitiveComparator); + const r = []; + return t.forEach((t => { + const i = __PRIVATE_newDbDocumentMutationPrefixForPath(this.userId, t.path), s = IDBKeyRange.lowerBound(i), o = __PRIVATE_documentMutationsStore(e).ee({ + range: s + }, ((e, r, i) => { + const [s, o, _] = e, a = __PRIVATE_decodeResourcePath(o); + // Only consider rows matching exactly the specific key of + // interest. Note that because we order by path first, and we + // order terminators before path separators, we'll encounter all + // the index rows for documentKey contiguously. In particular, all + // the rows for documentKey will occur before any rows for + // documents nested in a subcollection beneath documentKey so we + // can stop as soon as we hit any such row. + s === this.userId && t.path.isEqual(a) ? n = n.add(_) : i.done(); + })); + r.push(o); + })), PersistencePromise.waitFor(r).next((() => this.rr(e, n))); + } + getAllMutationBatchesAffectingQuery(e, t) { + const n = t.path, r = n.length + 1, i = __PRIVATE_newDbDocumentMutationPrefixForPath(this.userId, n), s = IDBKeyRange.lowerBound(i); + // Collect up unique batchIDs encountered during a scan of the index. Use a + // SortedSet to accumulate batch IDs so they can be traversed in order in a + // scan of the main table. + let o = new SortedSet(__PRIVATE_primitiveComparator); + return __PRIVATE_documentMutationsStore(e).ee({ + range: s + }, ((e, t, i) => { + const [s, _, a] = e, u = __PRIVATE_decodeResourcePath(_); + s === this.userId && n.isPrefixOf(u) ? + // Rows with document keys more than one segment longer than the + // query path can't be matches. For example, a query on 'rooms' + // can't match the document /rooms/abc/messages/xyx. + // TODO(mcg): we'll need a different scanner when we implement + // ancestor queries. + u.length === r && (o = o.add(a)) : i.done(); + })).next((() => this.rr(e, o))); + } + rr(e, t) { + const n = [], r = []; + // TODO(rockwood): Implement this using iterate. + return t.forEach((t => { + r.push(__PRIVATE_mutationsStore(e).get(t).next((e => { + if (null === e) throw fail(35274, { + batchId: t + }); + __PRIVATE_hardAssert(e.userId === this.userId, 9748, "Unexpected user for mutation batch", { + userId: e.userId, + batchId: t + }), n.push(__PRIVATE_fromDbMutationBatch(this.serializer, e)); + }))); + })), PersistencePromise.waitFor(r).next((() => n)); + } + removeMutationBatch(e, t) { + return removeMutationBatch(e.le, this.userId, t).next((n => (e.addOnCommittedListener((() => { + this.ir(t.batchId); + })), PersistencePromise.forEach(n, (t => this.referenceDelegate.markPotentiallyOrphaned(e, t)))))); + } + /** + * Clears the cached keys for a mutation batch. This method should be + * called by secondary clients after they process mutation updates. + * + * Note that this method does not have to be called from primary clients as + * the corresponding cache entries are cleared when an acknowledged or + * rejected batch is removed from the mutation queue. + */ + // PORTING NOTE: Multi-tab only + ir(e) { + delete this.Xn[e]; + } + performConsistencyCheck(e) { + return this.checkEmpty(e).next((t => { + if (!t) return PersistencePromise.resolve(); + // Verify that there are no entries in the documentMutations index if + // the queue is empty. + const n = IDBKeyRange.lowerBound( + /** + * Creates a [userId] key for use in the DbDocumentMutations index to iterate + * over all of a user's document mutations. + */ + function __PRIVATE_newDbDocumentMutationPrefixForUser(e) { + return [ e ]; + }(this.userId)), r = []; + return __PRIVATE_documentMutationsStore(e).ee({ + range: n + }, ((e, t, n) => { + if (e[0] === this.userId) { + const t = __PRIVATE_decodeResourcePath(e[1]); + r.push(t); + } else n.done(); + })).next((() => { + __PRIVATE_hardAssert(0 === r.length, 56720, { + sr: r.map((e => e.canonicalString())) + }); + })); + })); + } + containsKey(e, t) { + return __PRIVATE_mutationQueueContainsKey(e, this.userId, t); + } + // PORTING NOTE: Multi-tab only (state is held in memory in other clients). + /** Returns the mutation queue's metadata from IndexedDb. */ + _r(e) { + return __PRIVATE_mutationQueuesStore(e).get(this.userId).next((e => e || { + userId: this.userId, + lastAcknowledgedBatchId: j, + lastStreamToken: "" + })); + } +} + +/** + * @returns true if the mutation queue for the given user contains a pending + * mutation for the given key. + */ function __PRIVATE_mutationQueueContainsKey(e, t, n) { + const r = __PRIVATE_newDbDocumentMutationPrefixForPath(t, n.path), i = r[1], s = IDBKeyRange.lowerBound(r); + let o = !1; + return __PRIVATE_documentMutationsStore(e).ee({ + range: s, + X: !0 + }, ((e, n, r) => { + const [s, _, /*batchID*/ a] = e; + s === t && _ === i && (o = !0), r.done(); + })).next((() => o)); +} + +/** Returns true if any mutation queue contains the given document. */ +/** + * Helper to get a typed SimpleDbStore for the mutations object store. + */ +function __PRIVATE_mutationsStore(e) { + return __PRIVATE_getStore(e, te); +} + +/** + * Helper to get a typed SimpleDbStore for the mutationQueues object store. + */ function __PRIVATE_documentMutationsStore(e) { + return __PRIVATE_getStore(e, oe); +} + +/** + * Helper to get a typed SimpleDbStore for the mutationQueues object store. + */ function __PRIVATE_mutationQueuesStore(e) { + return __PRIVATE_getStore(e, X); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Offset to ensure non-overlapping target ids. */ +/** + * Generates monotonically increasing target IDs for sending targets to the + * watch stream. + * + * The client constructs two generators, one for the target cache, and one for + * for the sync engine (to generate limbo documents targets). These + * generators produce non-overlapping IDs (by using even and odd IDs + * respectively). + * + * By separating the target ID space, the query cache can generate target IDs + * that persist across client restarts, while sync engine can independently + * generate in-memory target IDs that are transient and can be reused after a + * restart. + */ +class __PRIVATE_TargetIdGenerator { + constructor(e) { + this.ar = e; + } + next() { + return this.ar += 2, this.ar; + } + static ur() { + // The target cache generator must return '2' in its first call to `next()` + // as there is no differentiation in the protocol layer between an unset + // number and the number '0'. If we were to sent a target with target ID + // '0', the backend would consider it unset and replace it with its own ID. + return new __PRIVATE_TargetIdGenerator(0); + } + static cr() { + // Sync engine assigns target IDs for limbo document detection. + return new __PRIVATE_TargetIdGenerator(-1); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_IndexedDbTargetCache { + constructor(e, t) { + this.referenceDelegate = e, this.serializer = t; + } + // PORTING NOTE: We don't cache global metadata for the target cache, since + // some of it (in particular `highestTargetId`) can be modified by secondary + // tabs. We could perhaps be more granular (and e.g. still cache + // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go + // to IndexedDb whenever we need to read metadata. We can revisit if it turns + // out to have a meaningful performance impact. + allocateTargetId(e) { + return this.lr(e).next((t => { + const n = new __PRIVATE_TargetIdGenerator(t.highestTargetId); + return t.highestTargetId = n.next(), this.hr(e, t).next((() => t.highestTargetId)); + })); + } + getLastRemoteSnapshotVersion(e) { + return this.lr(e).next((e => SnapshotVersion.fromTimestamp(new Timestamp(e.lastRemoteSnapshotVersion.seconds, e.lastRemoteSnapshotVersion.nanoseconds)))); + } + getHighestSequenceNumber(e) { + return this.lr(e).next((e => e.highestListenSequenceNumber)); + } + setTargetsMetadata(e, t, n) { + return this.lr(e).next((r => (r.highestListenSequenceNumber = t, n && (r.lastRemoteSnapshotVersion = n.toTimestamp()), + t > r.highestListenSequenceNumber && (r.highestListenSequenceNumber = t), this.hr(e, r)))); + } + addTargetData(e, t) { + return this.Pr(e, t).next((() => this.lr(e).next((n => (n.targetCount += 1, this.Tr(t, n), + this.hr(e, n)))))); + } + updateTargetData(e, t) { + return this.Pr(e, t); + } + removeTargetData(e, t) { + return this.removeMatchingKeysForTargetId(e, t.targetId).next((() => __PRIVATE_targetsStore(e).delete(t.targetId))).next((() => this.lr(e))).next((t => (__PRIVATE_hardAssert(t.targetCount > 0, 8065), + t.targetCount -= 1, this.hr(e, t)))); + } + /** + * Drops any targets with sequence number less than or equal to the upper bound, excepting those + * present in `activeTargetIds`. Document associations for the removed targets are also removed. + * Returns the number of targets removed. + */ removeTargets(e, t, n) { + let r = 0; + const i = []; + return __PRIVATE_targetsStore(e).ee(((s, o) => { + const _ = __PRIVATE_fromDbTarget(o); + _.sequenceNumber <= t && null === n.get(_.targetId) && (r++, i.push(this.removeTargetData(e, _))); + })).next((() => PersistencePromise.waitFor(i))).next((() => r)); + } + /** + * Call provided function with each `TargetData` that we have cached. + */ forEachTarget(e, t) { + return __PRIVATE_targetsStore(e).ee(((e, n) => { + const r = __PRIVATE_fromDbTarget(n); + t(r); + })); + } + lr(e) { + return __PRIVATE_globalTargetStore(e).get(fe).next((e => (__PRIVATE_hardAssert(null !== e, 2888), + e))); + } + hr(e, t) { + return __PRIVATE_globalTargetStore(e).put(fe, t); + } + Pr(e, t) { + return __PRIVATE_targetsStore(e).put(__PRIVATE_toDbTarget(this.serializer, t)); + } + /** + * In-place updates the provided metadata to account for values in the given + * TargetData. Saving is done separately. Returns true if there were any + * changes to the metadata. + */ Tr(e, t) { + let n = !1; + return e.targetId > t.highestTargetId && (t.highestTargetId = e.targetId, n = !0), + e.sequenceNumber > t.highestListenSequenceNumber && (t.highestListenSequenceNumber = e.sequenceNumber, + n = !0), n; + } + getTargetCount(e) { + return this.lr(e).next((e => e.targetCount)); + } + getTargetData(e, t) { + // Iterating by the canonicalId may yield more than one result because + // canonicalId values are not required to be unique per target. This query + // depends on the queryTargets index to be efficient. + const n = __PRIVATE_canonifyTarget(t), r = IDBKeyRange.bound([ n, Number.NEGATIVE_INFINITY ], [ n, Number.POSITIVE_INFINITY ]); + let i = null; + return __PRIVATE_targetsStore(e).ee({ + range: r, + index: Ee + }, ((e, n, r) => { + const s = __PRIVATE_fromDbTarget(n); + // After finding a potential match, check that the target is + // actually equal to the requested target. + __PRIVATE_targetEquals(t, s.target) && (i = s, r.done()); + })).next((() => i)); + } + addMatchingKeys(e, t, n) { + // PORTING NOTE: The reverse index (documentsTargets) is maintained by + // IndexedDb. + const r = [], i = __PRIVATE_documentTargetStore(e); + return t.forEach((t => { + const s = __PRIVATE_encodeResourcePath(t.path); + r.push(i.put({ + targetId: n, + path: s + })), r.push(this.referenceDelegate.addReference(e, n, t)); + })), PersistencePromise.waitFor(r); + } + removeMatchingKeys(e, t, n) { + // PORTING NOTE: The reverse index (documentsTargets) is maintained by + // IndexedDb. + const r = __PRIVATE_documentTargetStore(e); + return PersistencePromise.forEach(t, (t => { + const i = __PRIVATE_encodeResourcePath(t.path); + return PersistencePromise.waitFor([ r.delete([ n, i ]), this.referenceDelegate.removeReference(e, n, t) ]); + })); + } + removeMatchingKeysForTargetId(e, t) { + const n = __PRIVATE_documentTargetStore(e), r = IDBKeyRange.bound([ t ], [ t + 1 ], + /*lowerOpen=*/ !1, + /*upperOpen=*/ !0); + return n.delete(r); + } + getMatchingKeysForTargetId(e, t) { + const n = IDBKeyRange.bound([ t ], [ t + 1 ], + /*lowerOpen=*/ !1, + /*upperOpen=*/ !0), r = __PRIVATE_documentTargetStore(e); + let i = __PRIVATE_documentKeySet(); + return r.ee({ + range: n, + X: !0 + }, ((e, t, n) => { + const r = __PRIVATE_decodeResourcePath(e[1]), s = new DocumentKey(r); + i = i.add(s); + })).next((() => i)); + } + containsKey(e, t) { + const n = __PRIVATE_encodeResourcePath(t.path), r = IDBKeyRange.bound([ n ], [ __PRIVATE_immediateSuccessor(n) ], + /*lowerOpen=*/ !1, + /*upperOpen=*/ !0); + let i = 0; + return __PRIVATE_documentTargetStore(e).ee({ + index: Ve, + X: !0, + range: r + }, (([e, t], n, r) => { + // Having a sentinel row for a document does not count as containing that document; + // For the target cache, containing the document means the document is part of some + // target. + 0 !== e && (i++, r.done()); + })).next((() => i > 0)); + } + /** + * Looks up a TargetData entry by target ID. + * + * @param targetId - The target ID of the TargetData entry to look up. + * @returns The cached TargetData entry, or null if the cache has no entry for + * the target. + */ + // PORTING NOTE: Multi-tab only. + At(e, t) { + return __PRIVATE_targetsStore(e).get(t).next((e => e ? __PRIVATE_fromDbTarget(e) : null)); + } +} + +/** + * Helper to get a typed SimpleDbStore for the queries object store. + */ function __PRIVATE_targetsStore(e) { + return __PRIVATE_getStore(e, Ie); +} + +/** + * Helper to get a typed SimpleDbStore for the target globals object store. + */ function __PRIVATE_globalTargetStore(e) { + return __PRIVATE_getStore(e, ge); +} + +/** + * Helper to get a typed SimpleDbStore for the document target object store. + */ function __PRIVATE_documentTargetStore(e) { + return __PRIVATE_getStore(e, Ae); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const Nt = "LruGarbageCollector", Bt = 1048576; + +function __PRIVATE_bufferEntryComparator([e, t], [n, r]) { + const i = __PRIVATE_primitiveComparator(e, n); + return 0 === i ? __PRIVATE_primitiveComparator(t, r) : i; +} + +/** + * Used to calculate the nth sequence number. Keeps a rolling buffer of the + * lowest n values passed to `addElement`, and finally reports the largest of + * them in `maxValue`. + */ class __PRIVATE_RollingSequenceNumberBuffer { + constructor(e) { + this.Ir = e, this.buffer = new SortedSet(__PRIVATE_bufferEntryComparator), this.Er = 0; + } + dr() { + return ++this.Er; + } + Ar(e) { + const t = [ e, this.dr() ]; + if (this.buffer.size < this.Ir) this.buffer = this.buffer.add(t); else { + const e = this.buffer.last(); + __PRIVATE_bufferEntryComparator(t, e) < 0 && (this.buffer = this.buffer.delete(e).add(t)); + } + } + get maxValue() { + // Guaranteed to be non-empty. If we decide we are not collecting any + // sequence numbers, nthSequenceNumber below short-circuits. If we have + // decided that we are collecting n sequence numbers, it's because n is some + // percentage of the existing sequence numbers. That means we should never + // be in a situation where we are collecting sequence numbers but don't + // actually have any. + return this.buffer.last()[0]; + } +} + +/** + * This class is responsible for the scheduling of LRU garbage collection. It handles checking + * whether or not GC is enabled, as well as which delay to use before the next run. + */ class __PRIVATE_LruScheduler { + constructor(e, t, n) { + this.garbageCollector = e, this.asyncQueue = t, this.localStore = n, this.Rr = null; + } + start() { + -1 !== this.garbageCollector.params.cacheSizeCollectionThreshold && this.Vr(6e4); + } + stop() { + this.Rr && (this.Rr.cancel(), this.Rr = null); + } + get started() { + return null !== this.Rr; + } + Vr(e) { + __PRIVATE_logDebug(Nt, `Garbage collection scheduled in ${e}ms`), this.Rr = this.asyncQueue.enqueueAfterDelay("lru_garbage_collection" /* TimerId.LruGarbageCollection */ , e, (async () => { + this.Rr = null; + try { + await this.localStore.collectGarbage(this.garbageCollector); + } catch (e) { + __PRIVATE_isIndexedDbTransactionError(e) ? __PRIVATE_logDebug(Nt, "Ignoring IndexedDB error during garbage collection: ", e) : await __PRIVATE_ignoreIfPrimaryLeaseLoss(e); + } + await this.Vr(3e5); + })); + } +} + +/** + * Implements the steps for LRU garbage collection. + */ class __PRIVATE_LruGarbageCollectorImpl { + constructor(e, t) { + this.mr = e, this.params = t; + } + calculateTargetCount(e, t) { + return this.mr.gr(e).next((e => Math.floor(t / 100 * e))); + } + nthSequenceNumber(e, t) { + if (0 === t) return PersistencePromise.resolve(__PRIVATE_ListenSequence.ce); + const n = new __PRIVATE_RollingSequenceNumberBuffer(t); + return this.mr.forEachTarget(e, (e => n.Ar(e.sequenceNumber))).next((() => this.mr.pr(e, (e => n.Ar(e))))).next((() => n.maxValue)); + } + removeTargets(e, t, n) { + return this.mr.removeTargets(e, t, n); + } + removeOrphanedDocuments(e, t) { + return this.mr.removeOrphanedDocuments(e, t); + } + collect(e, t) { + return -1 === this.params.cacheSizeCollectionThreshold ? (__PRIVATE_logDebug("LruGarbageCollector", "Garbage collection skipped; disabled"), + PersistencePromise.resolve(xt)) : this.getCacheSize(e).next((n => n < this.params.cacheSizeCollectionThreshold ? (__PRIVATE_logDebug("LruGarbageCollector", `Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`), + xt) : this.yr(e, t))); + } + getCacheSize(e) { + return this.mr.getCacheSize(e); + } + yr(e, t) { + let n, r, i, s, o, _, u; + const c = Date.now(); + return this.calculateTargetCount(e, this.params.percentileToCollect).next((t => ( + // Cap at the configured max + t > this.params.maximumSequenceNumbersToCollect ? (__PRIVATE_logDebug("LruGarbageCollector", `Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${t}`), + r = this.params.maximumSequenceNumbersToCollect) : r = t, s = Date.now(), this.nthSequenceNumber(e, r)))).next((r => (n = r, + o = Date.now(), this.removeTargets(e, n, t)))).next((t => (i = t, _ = Date.now(), + this.removeOrphanedDocuments(e, n)))).next((e => { + if (u = Date.now(), __PRIVATE_getLogLevel() <= logger.LogLevel.DEBUG) { + __PRIVATE_logDebug("LruGarbageCollector", `LRU Garbage Collection\n\tCounted targets in ${s - c}ms\n\tDetermined least recently used ${r} in ` + (o - s) + "ms\n" + `\tRemoved ${i} targets in ` + (_ - o) + "ms\n" + `\tRemoved ${e} documents in ` + (u - _) + "ms\n" + `Total Duration: ${u - c}ms`); + } + return PersistencePromise.resolve({ + didRun: !0, + sequenceNumbersCollected: r, + targetsRemoved: i, + documentsRemoved: e + }); + })); + } +} + +function __PRIVATE_newLruGarbageCollector(e, t) { + return new __PRIVATE_LruGarbageCollectorImpl(e, t); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Provides LRU functionality for IndexedDB persistence. */ class __PRIVATE_IndexedDbLruDelegateImpl { + constructor(e, t) { + this.db = e, this.garbageCollector = __PRIVATE_newLruGarbageCollector(this, t); + } + gr(e) { + const t = this.wr(e); + return this.db.getTargetCache().getTargetCount(e).next((e => t.next((t => e + t)))); + } + wr(e) { + let t = 0; + return this.pr(e, (e => { + t++; + })).next((() => t)); + } + forEachTarget(e, t) { + return this.db.getTargetCache().forEachTarget(e, t); + } + pr(e, t) { + return this.Sr(e, ((e, n) => t(n))); + } + addReference(e, t, n) { + return __PRIVATE_writeSentinelKey(e, n); + } + removeReference(e, t, n) { + return __PRIVATE_writeSentinelKey(e, n); + } + removeTargets(e, t, n) { + return this.db.getTargetCache().removeTargets(e, t, n); + } + markPotentiallyOrphaned(e, t) { + return __PRIVATE_writeSentinelKey(e, t); + } + /** + * Returns true if anything would prevent this document from being garbage + * collected, given that the document in question is not present in any + * targets and has a sequence number less than or equal to the upper bound for + * the collection run. + */ br(e, t) { + return function __PRIVATE_mutationQueuesContainKey(e, t) { + let n = !1; + return __PRIVATE_mutationQueuesStore(e).te((r => __PRIVATE_mutationQueueContainsKey(e, r, t).next((e => (e && (n = !0), + PersistencePromise.resolve(!e)))))).next((() => n)); + }(e, t); + } + removeOrphanedDocuments(e, t) { + const n = this.db.getRemoteDocumentCache().newChangeBuffer(), r = []; + let i = 0; + return this.Sr(e, ((s, o) => { + if (o <= t) { + const t = this.br(e, s).next((t => { + if (!t) + // Our size accounting requires us to read all documents before + // removing them. + return i++, n.getEntry(e, s).next((() => (n.removeEntry(s, SnapshotVersion.min()), + __PRIVATE_documentTargetStore(e).delete(function __PRIVATE_sentinelKey$1(e) { + return [ 0, __PRIVATE_encodeResourcePath(e.path) ]; + } + /** + * @returns A value suitable for writing a sentinel row in the target-document + * store. + */ (s))))); + })); + r.push(t); + } + })).next((() => PersistencePromise.waitFor(r))).next((() => n.apply(e))).next((() => i)); + } + removeTarget(e, t) { + const n = t.withSequenceNumber(e.currentSequenceNumber); + return this.db.getTargetCache().updateTargetData(e, n); + } + updateLimboDocument(e, t) { + return __PRIVATE_writeSentinelKey(e, t); + } + /** + * Call provided function for each document in the cache that is 'orphaned'. Orphaned + * means not a part of any target, so the only entry in the target-document index for + * that document will be the sentinel row (targetId 0), which will also have the sequence + * number for the last time the document was accessed. + */ Sr(e, t) { + const n = __PRIVATE_documentTargetStore(e); + let r, i = __PRIVATE_ListenSequence.ce; + return n.ee({ + index: Ve + }, (([e, n], {path: s, sequenceNumber: o}) => { + 0 === e ? ( + // if nextToReport is valid, report it, this is a new key so the + // last one must not be a member of any targets. + i !== __PRIVATE_ListenSequence.ce && t(new DocumentKey(__PRIVATE_decodeResourcePath(r)), i), + // set nextToReport to be this sequence number. It's the next one we + // might report, if we don't find any targets for this document. + // Note that the sequence number must be defined when the targetId + // is 0. + i = o, r = s) : + // set nextToReport to be invalid, we know we don't need to report + // this one since we found a target for it. + i = __PRIVATE_ListenSequence.ce; + })).next((() => { + // Since we report sequence numbers after getting to the next key, we + // need to check if the last key we iterated over was an orphaned + // document and report it. + i !== __PRIVATE_ListenSequence.ce && t(new DocumentKey(__PRIVATE_decodeResourcePath(r)), i); + })); + } + getCacheSize(e) { + return this.db.getRemoteDocumentCache().getSize(e); + } +} + +function __PRIVATE_writeSentinelKey(e, t) { + return __PRIVATE_documentTargetStore(e).put(function __PRIVATE_sentinelRow(e, t) { + return { + targetId: 0, + path: __PRIVATE_encodeResourcePath(e.path), + sequenceNumber: t + }; + }(t, e.currentSequenceNumber)); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An in-memory buffer of entries to be written to a RemoteDocumentCache. + * It can be used to batch up a set of changes to be written to the cache, but + * additionally supports reading entries back with the `getEntry()` method, + * falling back to the underlying RemoteDocumentCache if no entry is + * buffered. + * + * Entries added to the cache *must* be read first. This is to facilitate + * calculating the size delta of the pending changes. + * + * PORTING NOTE: This class was implemented then removed from other platforms. + * If byte-counting ends up being needed on the other platforms, consider + * porting this class as part of that implementation work. + */ class RemoteDocumentChangeBuffer { + constructor() { + // A mapping of document key to the new cache entry that should be written. + this.changes = new ObjectMap((e => e.toString()), ((e, t) => e.isEqual(t))), this.changesApplied = !1; + } + /** + * Buffers a `RemoteDocumentCache.addEntry()` call. + * + * You can only modify documents that have already been retrieved via + * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). + */ addEntry(e) { + this.assertNotApplied(), this.changes.set(e.key, e); + } + /** + * Buffers a `RemoteDocumentCache.removeEntry()` call. + * + * You can only remove documents that have already been retrieved via + * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). + */ removeEntry(e, t) { + this.assertNotApplied(), this.changes.set(e, MutableDocument.newInvalidDocument(e).setReadTime(t)); + } + /** + * Looks up an entry in the cache. The buffered changes will first be checked, + * and if no buffered change applies, this will forward to + * `RemoteDocumentCache.getEntry()`. + * + * @param transaction - The transaction in which to perform any persistence + * operations. + * @param documentKey - The key of the entry to look up. + * @returns The cached document or an invalid document if we have nothing + * cached. + */ getEntry(e, t) { + this.assertNotApplied(); + const n = this.changes.get(t); + return void 0 !== n ? PersistencePromise.resolve(n) : this.getFromCache(e, t); + } + /** + * Looks up several entries in the cache, forwarding to + * `RemoteDocumentCache.getEntry()`. + * + * @param transaction - The transaction in which to perform any persistence + * operations. + * @param documentKeys - The keys of the entries to look up. + * @returns A map of cached documents, indexed by key. If an entry cannot be + * found, the corresponding key will be mapped to an invalid document. + */ getEntries(e, t) { + return this.getAllFromCache(e, t); + } + /** + * Applies buffered changes to the underlying RemoteDocumentCache, using + * the provided transaction. + */ apply(e) { + return this.assertNotApplied(), this.changesApplied = !0, this.applyChanges(e); + } + /** Helper to assert this.changes is not null */ assertNotApplied() {} +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The RemoteDocumentCache for IndexedDb. To construct, invoke + * `newIndexedDbRemoteDocumentCache()`. + */ class __PRIVATE_IndexedDbRemoteDocumentCacheImpl { + constructor(e) { + this.serializer = e; + } + setIndexManager(e) { + this.indexManager = e; + } + /** + * Adds the supplied entries to the cache. + * + * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer + * returned by `newChangeBuffer()` to ensure proper accounting of metadata. + */ addEntry(e, t, n) { + return __PRIVATE_remoteDocumentsStore(e).put(n); + } + /** + * Removes a document from the cache. + * + * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer + * returned by `newChangeBuffer()` to ensure proper accounting of metadata. + */ removeEntry(e, t, n) { + return __PRIVATE_remoteDocumentsStore(e).delete( + /** + * Returns a key that can be used for document lookups via the primary key of + * the DbRemoteDocument object store. + */ + function __PRIVATE_dbReadTimeKey(e, t) { + const n = e.path.toArray(); + return [ + /* prefix path */ n.slice(0, n.length - 2), + /* collection id */ n[n.length - 2], __PRIVATE_toDbTimestampKey(t), + /* document id */ n[n.length - 1] ]; + } + /** + * Returns a key that can be used for document lookups on the + * `DbRemoteDocumentDocumentCollectionGroupIndex` index. + */ (t, n)); + } + /** + * Updates the current cache size. + * + * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the + * cache's metadata. + */ updateMetadata(e, t) { + return this.getMetadata(e).next((n => (n.byteSize += t, this.Dr(e, n)))); + } + getEntry(e, t) { + let n = MutableDocument.newInvalidDocument(t); + return __PRIVATE_remoteDocumentsStore(e).ee({ + index: ue, + range: IDBKeyRange.only(__PRIVATE_dbKey(t)) + }, ((e, r) => { + n = this.Cr(t, r); + })).next((() => n)); + } + /** + * Looks up an entry in the cache. + * + * @param documentKey - The key of the entry to look up. + * @returns The cached document entry and its size. + */ vr(e, t) { + let n = { + size: 0, + document: MutableDocument.newInvalidDocument(t) + }; + return __PRIVATE_remoteDocumentsStore(e).ee({ + index: ue, + range: IDBKeyRange.only(__PRIVATE_dbKey(t)) + }, ((e, r) => { + n = { + document: this.Cr(t, r), + size: __PRIVATE_dbDocumentSize(r) + }; + })).next((() => n)); + } + getEntries(e, t) { + let n = __PRIVATE_mutableDocumentMap(); + return this.Fr(e, t, ((e, t) => { + const r = this.Cr(e, t); + n = n.insert(e, r); + })).next((() => n)); + } + /** + * Looks up several entries in the cache. + * + * @param documentKeys - The set of keys entries to look up. + * @returns A map of documents indexed by key and a map of sizes indexed by + * key (zero if the document does not exist). + */ Mr(e, t) { + let n = __PRIVATE_mutableDocumentMap(), r = new SortedMap(DocumentKey.comparator); + return this.Fr(e, t, ((e, t) => { + const i = this.Cr(e, t); + n = n.insert(e, i), r = r.insert(e, __PRIVATE_dbDocumentSize(t)); + })).next((() => ({ + documents: n, + Or: r + }))); + } + Fr(e, t, n) { + if (t.isEmpty()) return PersistencePromise.resolve(); + let r = new SortedSet(__PRIVATE_dbKeyComparator); + t.forEach((e => r = r.add(e))); + const i = IDBKeyRange.bound(__PRIVATE_dbKey(r.first()), __PRIVATE_dbKey(r.last())), s = r.getIterator(); + let o = s.getNext(); + return __PRIVATE_remoteDocumentsStore(e).ee({ + index: ue, + range: i + }, ((e, t, r) => { + const i = DocumentKey.fromSegments([ ...t.prefixPath, t.collectionGroup, t.documentId ]); + // Go through keys not found in cache. + for (;o && __PRIVATE_dbKeyComparator(o, i) < 0; ) n(o, null), o = s.getNext(); + o && o.isEqual(i) && ( + // Key found in cache. + n(o, t), o = s.hasNext() ? s.getNext() : null), + // Skip to the next key (if there is one). + o ? r.j(__PRIVATE_dbKey(o)) : r.done(); + })).next((() => { + // The rest of the keys are not in the cache. One case where `iterate` + // above won't go through them is when the cache is empty. + for (;o; ) n(o, null), o = s.hasNext() ? s.getNext() : null; + })); + } + getDocumentsMatchingQuery(e, t, n, r, i) { + const s = t.path, o = [ s.popLast().toArray(), s.lastSegment(), __PRIVATE_toDbTimestampKey(n.readTime), n.documentKey.path.isEmpty() ? "" : n.documentKey.path.lastSegment() ], _ = [ s.popLast().toArray(), s.lastSegment(), [ Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER ], "" ]; + return __PRIVATE_remoteDocumentsStore(e).J(IDBKeyRange.bound(o, _, !0)).next((e => { + i?.incrementDocumentReadCount(e.length); + let n = __PRIVATE_mutableDocumentMap(); + for (const i of e) { + const e = this.Cr(DocumentKey.fromSegments(i.prefixPath.concat(i.collectionGroup, i.documentId)), i); + e.isFoundDocument() && (__PRIVATE_queryMatches(t, e) || r.has(e.key)) && ( + // Either the document matches the given query, or it is mutated. + n = n.insert(e.key, e)); + } + return n; + })); + } + getAllFromCollectionGroup(e, t, n, r) { + let i = __PRIVATE_mutableDocumentMap(); + const s = __PRIVATE_dbCollectionGroupKey(t, n), o = __PRIVATE_dbCollectionGroupKey(t, IndexOffset.max()); + return __PRIVATE_remoteDocumentsStore(e).ee({ + index: le, + range: IDBKeyRange.bound(s, o, !0) + }, ((e, t, n) => { + const s = this.Cr(DocumentKey.fromSegments(t.prefixPath.concat(t.collectionGroup, t.documentId)), t); + i = i.insert(s.key, s), i.size === r && n.done(); + })).next((() => i)); + } + newChangeBuffer(e) { + return new __PRIVATE_IndexedDbRemoteDocumentChangeBuffer(this, !!e && e.trackRemovals); + } + getSize(e) { + return this.getMetadata(e).next((e => e.byteSize)); + } + getMetadata(e) { + return __PRIVATE_documentGlobalStore(e).get(Te).next((e => (__PRIVATE_hardAssert(!!e, 20021), + e))); + } + Dr(e, t) { + return __PRIVATE_documentGlobalStore(e).put(Te, t); + } + /** + * Decodes `dbRemoteDoc` and returns the document (or an invalid document if + * the document corresponds to the format used for sentinel deletes). + */ Cr(e, t) { + if (t) { + const e = __PRIVATE_fromDbRemoteDocument(this.serializer, t); + // Whether the document is a sentinel removal and should only be used in the + // `getNewDocumentChanges()` + if (!(e.isNoDocument() && e.version.isEqual(SnapshotVersion.min()))) return e; + } + return MutableDocument.newInvalidDocument(e); + } +} + +/** Creates a new IndexedDbRemoteDocumentCache. */ function __PRIVATE_newIndexedDbRemoteDocumentCache(e) { + return new __PRIVATE_IndexedDbRemoteDocumentCacheImpl(e); +} + +/** + * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache. + * + * Unlike the MemoryRemoteDocumentChangeBuffer, the IndexedDb implementation computes the size + * delta for all submitted changes. This avoids having to re-read all documents from IndexedDb + * when we apply the changes. + */ class __PRIVATE_IndexedDbRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer { + /** + * @param documentCache - The IndexedDbRemoteDocumentCache to apply the changes to. + * @param trackRemovals - Whether to create sentinel deletes that can be tracked by + * `getNewDocumentChanges()`. + */ + constructor(e, t) { + super(), this.Nr = e, this.trackRemovals = t, + // A map of document sizes and read times prior to applying the changes in + // this buffer. + this.Br = new ObjectMap((e => e.toString()), ((e, t) => e.isEqual(t))); + } + applyChanges(e) { + const t = []; + let n = 0, r = new SortedSet(((e, t) => __PRIVATE_primitiveComparator(e.canonicalString(), t.canonicalString()))); + return this.changes.forEach(((i, s) => { + const o = this.Br.get(i); + if (t.push(this.Nr.removeEntry(e, i, o.readTime)), s.isValidDocument()) { + const _ = __PRIVATE_toDbRemoteDocument(this.Nr.serializer, s); + r = r.add(i.path.popLast()); + const a = __PRIVATE_dbDocumentSize(_); + n += a - o.size, t.push(this.Nr.addEntry(e, i, _)); + } else if (n -= o.size, this.trackRemovals) { + // In order to track removals, we store a "sentinel delete" in the + // RemoteDocumentCache. This entry is represented by a NoDocument + // with a version of 0 and ignored by `maybeDecodeDocument()` but + // preserved in `getNewDocumentChanges()`. + const n = __PRIVATE_toDbRemoteDocument(this.Nr.serializer, s.convertToNoDocument(SnapshotVersion.min())); + t.push(this.Nr.addEntry(e, i, n)); + } + })), r.forEach((n => { + t.push(this.Nr.indexManager.addToCollectionParentIndex(e, n)); + })), t.push(this.Nr.updateMetadata(e, n)), PersistencePromise.waitFor(t); + } + getFromCache(e, t) { + // Record the size of everything we load from the cache so we can compute a delta later. + return this.Nr.vr(e, t).next((e => (this.Br.set(t, { + size: e.size, + readTime: e.document.readTime + }), e.document))); + } + getAllFromCache(e, t) { + // Record the size of everything we load from the cache so we can compute + // a delta later. + return this.Nr.Mr(e, t).next((({documents: e, Or: t}) => ( + // Note: `getAllFromCache` returns two maps instead of a single map from + // keys to `DocumentSizeEntry`s. This is to allow returning the + // `MutableDocumentMap` directly, without a conversion. + t.forEach(((t, n) => { + this.Br.set(t, { + size: n, + readTime: e.get(t).readTime + }); + })), e))); + } +} + +function __PRIVATE_documentGlobalStore(e) { + return __PRIVATE_getStore(e, Pe); +} + +/** + * Helper to get a typed SimpleDbStore for the remoteDocuments object store. + */ function __PRIVATE_remoteDocumentsStore(e) { + return __PRIVATE_getStore(e, _e); +} + +/** + * Returns a key that can be used for document lookups on the + * `DbRemoteDocumentDocumentKeyIndex` index. + */ function __PRIVATE_dbKey(e) { + const t = e.path.toArray(); + return [ + /* prefix path */ t.slice(0, t.length - 2), + /* collection id */ t[t.length - 2], + /* document id */ t[t.length - 1] ]; +} + +function __PRIVATE_dbCollectionGroupKey(e, t) { + const n = t.documentKey.path.toArray(); + return [ + /* collection id */ e, __PRIVATE_toDbTimestampKey(t.readTime), + /* prefix path */ n.slice(0, n.length - 2), + /* document id */ n.length > 0 ? n[n.length - 1] : "" ]; +} + +/** + * Comparator that compares document keys according to the primary key sorting + * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id + * and then document ID). + * + * Visible for testing. + */ function __PRIVATE_dbKeyComparator(e, t) { + const n = e.path.toArray(), r = t.path.toArray(); + // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74 + let i = 0; + for (let e = 0; e < n.length - 2 && e < r.length - 2; ++e) if (i = __PRIVATE_primitiveComparator(n[e], r[e]), + i) return i; + return i = __PRIVATE_primitiveComparator(n.length, r.length), i || (i = __PRIVATE_primitiveComparator(n[n.length - 2], r[r.length - 2]), + i || __PRIVATE_primitiveComparator(n[n.length - 1], r[r.length - 1])); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Schema Version for the Web client: + * 1. Initial version including Mutation Queue, Query Cache, and Remote + * Document Cache + * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No + * longer required because migration 3 unconditionally clears it. + * 3. Dropped and re-created Query Cache to deal with cache corruption related + * to limbo resolution. Addresses + * https://github.com/firebase/firebase-ios-sdk/issues/1548 + * 4. Multi-Tab Support. + * 5. Removal of held write acks. + * 6. Create document global for tracking document cache size. + * 7. Ensure every cached document has a sentinel row with a sequence number. + * 8. Add collection-parent index for Collection Group queries. + * 9. Change RemoteDocumentChanges store to be keyed by readTime rather than + * an auto-incrementing ID. This is required for Index-Free queries. + * 10. Rewrite the canonical IDs to the explicit Protobuf-based format. + * 11. Add bundles and named_queries for bundle support. + * 12. Add document overlays. + * 13. Rewrite the keys of the remote document cache to allow for efficient + * document lookup via `getAll()`. + * 14. Add overlays. + * 15. Add indexing support. + * 16. Parse timestamp strings before creating index entries. + * 17. TODO(tomandersen) + * 18. Encode key safe representations of IndexEntry in DbIndexEntryStore. + */ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a local view (overlay) of a document, and the fields that are + * locally mutated. + */ +class OverlayedDocument { + constructor(e, + /** + * The fields that are locally mutated by patch mutations. + * + * If the overlayed document is from set or delete mutations, this is `null`. + * If there is no overlay (mutation) for the document, this is an empty `FieldMask`. + */ + t) { + this.overlayedDocument = e, this.mutatedFields = t; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A readonly view of the local state of all documents we're tracking (i.e. we + * have a cached version in remoteDocumentCache or local mutations for the + * document). The view is computed by applying the mutations in the + * MutationQueue to the RemoteDocumentCache. + */ class LocalDocumentsView { + constructor(e, t, n, r) { + this.remoteDocumentCache = e, this.mutationQueue = t, this.documentOverlayCache = n, + this.indexManager = r; + } + /** + * Get the local view of the document identified by `key`. + * + * @returns Local view of the document or null if we don't have any cached + * state for it. + */ getDocument(e, t) { + let n = null; + return this.documentOverlayCache.getOverlay(e, t).next((r => (n = r, this.remoteDocumentCache.getEntry(e, t)))).next((e => (null !== n && __PRIVATE_mutationApplyToLocalView(n.mutation, e, FieldMask.empty(), Timestamp.now()), + e))); + } + /** + * Gets the local view of the documents identified by `keys`. + * + * If we don't have cached state for a document in `keys`, a NoDocument will + * be stored for that key in the resulting set. + */ getDocuments(e, t) { + return this.remoteDocumentCache.getEntries(e, t).next((t => this.getLocalViewOfDocuments(e, t, __PRIVATE_documentKeySet()).next((() => t)))); + } + /** + * Similar to `getDocuments`, but creates the local view from the given + * `baseDocs` without retrieving documents from the local store. + * + * @param transaction - The transaction this operation is scoped to. + * @param docs - The documents to apply local mutations to get the local views. + * @param existenceStateChanged - The set of document keys whose existence state + * is changed. This is useful to determine if some documents overlay needs + * to be recalculated. + */ getLocalViewOfDocuments(e, t, n = __PRIVATE_documentKeySet()) { + const r = __PRIVATE_newOverlayMap(); + return this.populateOverlays(e, r, t).next((() => this.computeViews(e, t, r, n).next((e => { + let t = documentMap(); + return e.forEach(((e, n) => { + t = t.insert(e, n.overlayedDocument); + })), t; + })))); + } + /** + * Gets the overlayed documents for the given document map, which will include + * the local view of those documents and a `FieldMask` indicating which fields + * are mutated locally, `null` if overlay is a Set or Delete mutation. + */ getOverlayedDocuments(e, t) { + const n = __PRIVATE_newOverlayMap(); + return this.populateOverlays(e, n, t).next((() => this.computeViews(e, t, n, __PRIVATE_documentKeySet()))); + } + /** + * Fetches the overlays for {@code docs} and adds them to provided overlay map + * if the map does not already contain an entry for the given document key. + */ populateOverlays(e, t, n) { + const r = []; + return n.forEach((e => { + t.has(e) || r.push(e); + })), this.documentOverlayCache.getOverlays(e, r).next((e => { + e.forEach(((e, n) => { + t.set(e, n); + })); + })); + } + /** + * Computes the local view for the given documents. + * + * @param docs - The documents to compute views for. It also has the base + * version of the documents. + * @param overlays - The overlays that need to be applied to the given base + * version of the documents. + * @param existenceStateChanged - A set of documents whose existence states + * might have changed. This is used to determine if we need to re-calculate + * overlays from mutation queues. + * @return A map represents the local documents view. + */ computeViews(e, t, n, r) { + let i = __PRIVATE_mutableDocumentMap(); + const s = __PRIVATE_newDocumentKeyMap(), o = function __PRIVATE_newOverlayedDocumentMap() { + return __PRIVATE_newDocumentKeyMap(); + }(); + return t.forEach(((e, t) => { + const o = n.get(t.key); + // Recalculate an overlay if the document's existence state changed due to + // a remote event *and* the overlay is a PatchMutation. This is because + // document existence state can change if some patch mutation's + // preconditions are met. + // NOTE: we recalculate when `overlay` is undefined as well, because there + // might be a patch mutation whose precondition does not match before the + // change (hence overlay is undefined), but would now match. + r.has(t.key) && (void 0 === o || o.mutation instanceof __PRIVATE_PatchMutation) ? i = i.insert(t.key, t) : void 0 !== o ? (s.set(t.key, o.mutation.getFieldMask()), + __PRIVATE_mutationApplyToLocalView(o.mutation, t, o.mutation.getFieldMask(), Timestamp.now())) : + // no overlay exists + // Using EMPTY to indicate there is no overlay for the document. + s.set(t.key, FieldMask.empty()); + })), this.recalculateAndSaveOverlays(e, i).next((e => (e.forEach(((e, t) => s.set(e, t))), + t.forEach(((e, t) => o.set(e, new OverlayedDocument(t, s.get(e) ?? null)))), o))); + } + recalculateAndSaveOverlays(e, t) { + const n = __PRIVATE_newDocumentKeyMap(); + // A reverse lookup map from batch id to the documents within that batch. + let r = new SortedMap(((e, t) => e - t)), i = __PRIVATE_documentKeySet(); + return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e, t).next((e => { + for (const i of e) i.keys().forEach((e => { + const s = t.get(e); + if (null === s) return; + let o = n.get(e) || FieldMask.empty(); + o = i.applyToLocalView(s, o), n.set(e, o); + const _ = (r.get(i.batchId) || __PRIVATE_documentKeySet()).add(e); + r = r.insert(i.batchId, _); + })); + })).next((() => { + const s = [], o = r.getReverseIterator(); + // Iterate in descending order of batch IDs, and skip documents that are + // already saved. + for (;o.hasNext(); ) { + const r = o.getNext(), _ = r.key, a = r.value, u = __PRIVATE_newMutationMap(); + a.forEach((e => { + if (!i.has(e)) { + const r = __PRIVATE_calculateOverlayMutation(t.get(e), n.get(e)); + null !== r && u.set(e, r), i = i.add(e); + } + })), s.push(this.documentOverlayCache.saveOverlays(e, _, u)); + } + return PersistencePromise.waitFor(s); + })).next((() => n)); + } + /** + * Recalculates overlays by reading the documents from remote document cache + * first, and saves them after they are calculated. + */ recalculateAndSaveOverlaysForDocumentKeys(e, t) { + return this.remoteDocumentCache.getEntries(e, t).next((t => this.recalculateAndSaveOverlays(e, t))); + } + /** + * Performs a query against the local view of all documents. + * + * @param transaction - The persistence transaction. + * @param query - The query to match documents against. + * @param offset - Read time and key to start scanning by (exclusive). + * @param context - A optional tracker to keep a record of important details + * during database local query execution. + */ getDocumentsMatchingQuery(e, t, n, r) { + /** + * Returns whether the query matches a single document by path (rather than a + * collection). + */ + return function __PRIVATE_isDocumentQuery$1(e) { + return DocumentKey.isDocumentKey(e.path) && null === e.collectionGroup && 0 === e.filters.length; + }(t) ? this.getDocumentsMatchingDocumentQuery(e, t.path) : __PRIVATE_isCollectionGroupQuery(t) ? this.getDocumentsMatchingCollectionGroupQuery(e, t, n, r) : this.getDocumentsMatchingCollectionQuery(e, t, n, r); + } + /** + * Given a collection group, returns the next documents that follow the provided offset, along + * with an updated batch ID. + * + *

The documents returned by this method are ordered by remote version from the provided + * offset. If there are no more remote documents after the provided offset, documents with + * mutations in order of batch id from the offset are returned. Since all documents in a batch are + * returned together, the total number of documents returned can exceed {@code count}. + * + * @param transaction + * @param collectionGroup The collection group for the documents. + * @param offset The offset to index into. + * @param count The number of documents to return + * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id. + */ getNextDocuments(e, t, n, r) { + return this.remoteDocumentCache.getAllFromCollectionGroup(e, t, n, r).next((i => { + const s = r - i.size > 0 ? this.documentOverlayCache.getOverlaysForCollectionGroup(e, t, n.largestBatchId, r - i.size) : PersistencePromise.resolve(__PRIVATE_newOverlayMap()); + // The callsite will use the largest batch ID together with the latest read time to create + // a new index offset. Since we only process batch IDs if all remote documents have been read, + // no overlay will increase the overall read time. This is why we only need to special case + // the batch id. + let o = U, _ = i; + return s.next((t => PersistencePromise.forEach(t, ((t, n) => (o < n.largestBatchId && (o = n.largestBatchId), + i.get(t) ? PersistencePromise.resolve() : this.remoteDocumentCache.getEntry(e, t).next((e => { + _ = _.insert(t, e); + }))))).next((() => this.populateOverlays(e, t, i))).next((() => this.computeViews(e, _, t, __PRIVATE_documentKeySet()))).next((e => ({ + batchId: o, + changes: __PRIVATE_convertOverlayedDocumentMapToDocumentMap(e) + }))))); + })); + } + getDocumentsMatchingDocumentQuery(e, t) { + // Just do a simple document lookup. + return this.getDocument(e, new DocumentKey(t)).next((e => { + let t = documentMap(); + return e.isFoundDocument() && (t = t.insert(e.key, e)), t; + })); + } + getDocumentsMatchingCollectionGroupQuery(e, t, n, r) { + const i = t.collectionGroup; + let s = documentMap(); + return this.indexManager.getCollectionParents(e, i).next((o => PersistencePromise.forEach(o, (o => { + const _ = function __PRIVATE_asCollectionQueryAtPath(e, t) { + return new __PRIVATE_QueryImpl(t, + /*collectionGroup=*/ null, e.explicitOrderBy.slice(), e.filters.slice(), e.limit, e.limitType, e.startAt, e.endAt); + }(t, o.child(i)); + return this.getDocumentsMatchingCollectionQuery(e, _, n, r).next((e => { + e.forEach(((e, t) => { + s = s.insert(e, t); + })); + })); + })).next((() => s)))); + } + getDocumentsMatchingCollectionQuery(e, t, n, r) { + // Query the remote documents and overlay mutations. + let i; + return this.documentOverlayCache.getOverlaysForCollection(e, t.path, n.largestBatchId).next((s => (i = s, + this.remoteDocumentCache.getDocumentsMatchingQuery(e, t, n, i, r)))).next((e => { + // As documents might match the query because of their overlay we need to + // include documents for all overlays in the initial document set. + i.forEach(((t, n) => { + const r = n.getKey(); + null === e.get(r) && (e = e.insert(r, MutableDocument.newInvalidDocument(r))); + })); + // Apply the overlays and match against the query. + let n = documentMap(); + return e.forEach(((e, r) => { + const s = i.get(e); + void 0 !== s && __PRIVATE_mutationApplyToLocalView(s.mutation, r, FieldMask.empty(), Timestamp.now()), + // Finally, insert the documents that still match the query + __PRIVATE_queryMatches(t, r) && (n = n.insert(e, r)); + })), n; + })); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_MemoryBundleCache { + constructor(e) { + this.serializer = e, this.Lr = new Map, this.kr = new Map; + } + getBundleMetadata(e, t) { + return PersistencePromise.resolve(this.Lr.get(t)); + } + saveBundleMetadata(e, t) { + return this.Lr.set(t.id, + /** Decodes a BundleMetadata proto into a BundleMetadata object. */ + function __PRIVATE_fromBundleMetadata(e) { + return { + id: e.id, + version: e.version, + createTime: __PRIVATE_fromVersion(e.createTime) + }; + }(t)), PersistencePromise.resolve(); + } + getNamedQuery(e, t) { + return PersistencePromise.resolve(this.kr.get(t)); + } + saveNamedQuery(e, t) { + return this.kr.set(t.name, function __PRIVATE_fromProtoNamedQuery(e) { + return { + name: e.name, + query: __PRIVATE_fromBundledQuery(e.bundledQuery), + readTime: __PRIVATE_fromVersion(e.readTime) + }; + }(t)), PersistencePromise.resolve(); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An in-memory implementation of DocumentOverlayCache. + */ class __PRIVATE_MemoryDocumentOverlayCache { + constructor() { + // A map sorted by DocumentKey, whose value is a pair of the largest batch id + // for the overlay and the overlay itself. + this.overlays = new SortedMap(DocumentKey.comparator), this.qr = new Map; + } + getOverlay(e, t) { + return PersistencePromise.resolve(this.overlays.get(t)); + } + getOverlays(e, t) { + const n = __PRIVATE_newOverlayMap(); + return PersistencePromise.forEach(t, (t => this.getOverlay(e, t).next((e => { + null !== e && n.set(t, e); + })))).next((() => n)); + } + saveOverlays(e, t, n) { + return n.forEach(((n, r) => { + this.St(e, t, r); + })), PersistencePromise.resolve(); + } + removeOverlaysForBatchId(e, t, n) { + const r = this.qr.get(n); + return void 0 !== r && (r.forEach((e => this.overlays = this.overlays.remove(e))), + this.qr.delete(n)), PersistencePromise.resolve(); + } + getOverlaysForCollection(e, t, n) { + const r = __PRIVATE_newOverlayMap(), i = t.length + 1, s = new DocumentKey(t.child("")), o = this.overlays.getIteratorFrom(s); + for (;o.hasNext(); ) { + const e = o.getNext().value, s = e.getKey(); + if (!t.isPrefixOf(s.path)) break; + // Documents from sub-collections + s.path.length === i && (e.largestBatchId > n && r.set(e.getKey(), e)); + } + return PersistencePromise.resolve(r); + } + getOverlaysForCollectionGroup(e, t, n, r) { + let i = new SortedMap(((e, t) => e - t)); + const s = this.overlays.getIterator(); + for (;s.hasNext(); ) { + const e = s.getNext().value; + if (e.getKey().getCollectionGroup() === t && e.largestBatchId > n) { + let t = i.get(e.largestBatchId); + null === t && (t = __PRIVATE_newOverlayMap(), i = i.insert(e.largestBatchId, t)), + t.set(e.getKey(), e); + } + } + const o = __PRIVATE_newOverlayMap(), _ = i.getIterator(); + for (;_.hasNext(); ) { + if (_.getNext().value.forEach(((e, t) => o.set(e, t))), o.size() >= r) break; + } + return PersistencePromise.resolve(o); + } + St(e, t, n) { + // Remove the association of the overlay to its batch id. + const r = this.overlays.get(n.key); + if (null !== r) { + const e = this.qr.get(r.largestBatchId).delete(n.key); + this.qr.set(r.largestBatchId, e); + } + this.overlays = this.overlays.insert(n.key, new Overlay(t, n)); + // Create the association of this overlay to the given largestBatchId. + let i = this.qr.get(t); + void 0 === i && (i = __PRIVATE_documentKeySet(), this.qr.set(t, i)), this.qr.set(t, i.add(n.key)); + } +} + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_MemoryGlobalsCache { + constructor() { + this.sessionToken = ByteString.EMPTY_BYTE_STRING; + } + getSessionToken(e) { + return PersistencePromise.resolve(this.sessionToken); + } + setSessionToken(e, t) { + return this.sessionToken = t, PersistencePromise.resolve(); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A collection of references to a document from some kind of numbered entity + * (either a target ID or batch ID). As references are added to or removed from + * the set corresponding events are emitted to a registered garbage collector. + * + * Each reference is represented by a DocumentReference object. Each of them + * contains enough information to uniquely identify the reference. They are all + * stored primarily in a set sorted by key. A document is considered garbage if + * there's no references in that set (this can be efficiently checked thanks to + * sorting by key). + * + * ReferenceSet also keeps a secondary set that contains references sorted by + * IDs. This one is used to efficiently implement removal of all references by + * some target ID. + */ class __PRIVATE_ReferenceSet { + constructor() { + // A set of outstanding references to a document sorted by key. + this.Qr = new SortedSet(__PRIVATE_DocReference.$r), + // A set of outstanding references to a document sorted by target id. + this.Ur = new SortedSet(__PRIVATE_DocReference.Kr); + } + /** Returns true if the reference set contains no references. */ isEmpty() { + return this.Qr.isEmpty(); + } + /** Adds a reference to the given document key for the given ID. */ addReference(e, t) { + const n = new __PRIVATE_DocReference(e, t); + this.Qr = this.Qr.add(n), this.Ur = this.Ur.add(n); + } + /** Add references to the given document keys for the given ID. */ Wr(e, t) { + e.forEach((e => this.addReference(e, t))); + } + /** + * Removes a reference to the given document key for the given + * ID. + */ removeReference(e, t) { + this.Gr(new __PRIVATE_DocReference(e, t)); + } + zr(e, t) { + e.forEach((e => this.removeReference(e, t))); + } + /** + * Clears all references with a given ID. Calls removeRef() for each key + * removed. + */ jr(e) { + const t = new DocumentKey(new ResourcePath([])), n = new __PRIVATE_DocReference(t, e), r = new __PRIVATE_DocReference(t, e + 1), i = []; + return this.Ur.forEachInRange([ n, r ], (e => { + this.Gr(e), i.push(e.key); + })), i; + } + Jr() { + this.Qr.forEach((e => this.Gr(e))); + } + Gr(e) { + this.Qr = this.Qr.delete(e), this.Ur = this.Ur.delete(e); + } + Hr(e) { + const t = new DocumentKey(new ResourcePath([])), n = new __PRIVATE_DocReference(t, e), r = new __PRIVATE_DocReference(t, e + 1); + let i = __PRIVATE_documentKeySet(); + return this.Ur.forEachInRange([ n, r ], (e => { + i = i.add(e.key); + })), i; + } + containsKey(e) { + const t = new __PRIVATE_DocReference(e, 0), n = this.Qr.firstAfterOrEqual(t); + return null !== n && e.isEqual(n.key); + } +} + +class __PRIVATE_DocReference { + constructor(e, t) { + this.key = e, this.Yr = t; + } + /** Compare by key then by ID */ static $r(e, t) { + return DocumentKey.comparator(e.key, t.key) || __PRIVATE_primitiveComparator(e.Yr, t.Yr); + } + /** Compare by ID then by key */ static Kr(e, t) { + return __PRIVATE_primitiveComparator(e.Yr, t.Yr) || DocumentKey.comparator(e.key, t.key); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_MemoryMutationQueue { + constructor(e, t) { + this.indexManager = e, this.referenceDelegate = t, + /** + * The set of all mutations that have been sent but not yet been applied to + * the backend. + */ + this.mutationQueue = [], + /** Next value to use when assigning sequential IDs to each mutation batch. */ + this.tr = 1, + /** An ordered mapping between documents and the mutations batch IDs. */ + this.Zr = new SortedSet(__PRIVATE_DocReference.$r); + } + checkEmpty(e) { + return PersistencePromise.resolve(0 === this.mutationQueue.length); + } + addMutationBatch(e, t, n, r) { + const i = this.tr; + this.tr++, this.mutationQueue.length > 0 && this.mutationQueue[this.mutationQueue.length - 1]; + const s = new MutationBatch(i, t, n, r); + this.mutationQueue.push(s); + // Track references by document key and index collection parents. + for (const t of r) this.Zr = this.Zr.add(new __PRIVATE_DocReference(t.key, i)), + this.indexManager.addToCollectionParentIndex(e, t.key.path.popLast()); + return PersistencePromise.resolve(s); + } + lookupMutationBatch(e, t) { + return PersistencePromise.resolve(this.Xr(t)); + } + getNextMutationBatchAfterBatchId(e, t) { + const n = t + 1, r = this.ei(n), i = r < 0 ? 0 : r; + // The requested batchId may still be out of range so normalize it to the + // start of the queue. + return PersistencePromise.resolve(this.mutationQueue.length > i ? this.mutationQueue[i] : null); + } + getHighestUnacknowledgedBatchId() { + return PersistencePromise.resolve(0 === this.mutationQueue.length ? j : this.tr - 1); + } + getAllMutationBatches(e) { + return PersistencePromise.resolve(this.mutationQueue.slice()); + } + getAllMutationBatchesAffectingDocumentKey(e, t) { + const n = new __PRIVATE_DocReference(t, 0), r = new __PRIVATE_DocReference(t, Number.POSITIVE_INFINITY), i = []; + return this.Zr.forEachInRange([ n, r ], (e => { + const t = this.Xr(e.Yr); + i.push(t); + })), PersistencePromise.resolve(i); + } + getAllMutationBatchesAffectingDocumentKeys(e, t) { + let n = new SortedSet(__PRIVATE_primitiveComparator); + return t.forEach((e => { + const t = new __PRIVATE_DocReference(e, 0), r = new __PRIVATE_DocReference(e, Number.POSITIVE_INFINITY); + this.Zr.forEachInRange([ t, r ], (e => { + n = n.add(e.Yr); + })); + })), PersistencePromise.resolve(this.ti(n)); + } + getAllMutationBatchesAffectingQuery(e, t) { + // Use the query path as a prefix for testing if a document matches the + // query. + const n = t.path, r = n.length + 1; + // Construct a document reference for actually scanning the index. Unlike + // the prefix the document key in this reference must have an even number of + // segments. The empty segment can be used a suffix of the query path + // because it precedes all other segments in an ordered traversal. + let i = n; + DocumentKey.isDocumentKey(i) || (i = i.child("")); + const s = new __PRIVATE_DocReference(new DocumentKey(i), 0); + // Find unique batchIDs referenced by all documents potentially matching the + // query. + let o = new SortedSet(__PRIVATE_primitiveComparator); + return this.Zr.forEachWhile((e => { + const t = e.key.path; + return !!n.isPrefixOf(t) && ( + // Rows with document keys more than one segment longer than the query + // path can't be matches. For example, a query on 'rooms' can't match + // the document /rooms/abc/messages/xyx. + // TODO(mcg): we'll need a different scanner when we implement + // ancestor queries. + t.length === r && (o = o.add(e.Yr)), !0); + }), s), PersistencePromise.resolve(this.ti(o)); + } + ti(e) { + // Construct an array of matching batches, sorted by batchID to ensure that + // multiple mutations affecting the same document key are applied in order. + const t = []; + return e.forEach((e => { + const n = this.Xr(e); + null !== n && t.push(n); + })), t; + } + removeMutationBatch(e, t) { + __PRIVATE_hardAssert(0 === this.ni(t.batchId, "removed"), 55003), this.mutationQueue.shift(); + let n = this.Zr; + return PersistencePromise.forEach(t.mutations, (r => { + const i = new __PRIVATE_DocReference(r.key, t.batchId); + return n = n.delete(i), this.referenceDelegate.markPotentiallyOrphaned(e, r.key); + })).next((() => { + this.Zr = n; + })); + } + ir(e) { + // No-op since the memory mutation queue does not maintain a separate cache. + } + containsKey(e, t) { + const n = new __PRIVATE_DocReference(t, 0), r = this.Zr.firstAfterOrEqual(n); + return PersistencePromise.resolve(t.isEqual(r && r.key)); + } + performConsistencyCheck(e) { + return this.mutationQueue.length, PersistencePromise.resolve(); + } + /** + * Finds the index of the given batchId in the mutation queue and asserts that + * the resulting index is within the bounds of the queue. + * + * @param batchId - The batchId to search for + * @param action - A description of what the caller is doing, phrased in passive + * form (e.g. "acknowledged" in a routine that acknowledges batches). + */ ni(e, t) { + return this.ei(e); + } + /** + * Finds the index of the given batchId in the mutation queue. This operation + * is O(1). + * + * @returns The computed index of the batch with the given batchId, based on + * the state of the queue. Note this index can be negative if the requested + * batchId has already been removed from the queue or past the end of the + * queue if the batchId is larger than the last added batch. + */ ei(e) { + if (0 === this.mutationQueue.length) + // As an index this is past the end of the queue + return 0; + // Examine the front of the queue to figure out the difference between the + // batchId and indexes in the array. Note that since the queue is ordered + // by batchId, if the first batch has a larger batchId then the requested + // batchId doesn't exist in the queue. + return e - this.mutationQueue[0].batchId; + } + /** + * A version of lookupMutationBatch that doesn't return a promise, this makes + * other functions that uses this code easier to read and more efficient. + */ Xr(e) { + const t = this.ei(e); + if (t < 0 || t >= this.mutationQueue.length) return null; + return this.mutationQueue[t]; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The smallest value representable by a 64-bit signed integer (long). + */ +/** + * The memory-only RemoteDocumentCache for IndexedDb. To construct, invoke + * `newMemoryRemoteDocumentCache()`. + */ +class __PRIVATE_MemoryRemoteDocumentCacheImpl { + /** + * @param sizer - Used to assess the size of a document. For eager GC, this is + * expected to just return 0 to avoid unnecessarily doing the work of + * calculating the size. + */ + constructor(e) { + this.ri = e, + /** Underlying cache of documents and their read times. */ + this.docs = function __PRIVATE_documentEntryMap() { + return new SortedMap(DocumentKey.comparator); + }(), + /** Size of all cached documents. */ + this.size = 0; + } + setIndexManager(e) { + this.indexManager = e; + } + /** + * Adds the supplied entry to the cache and updates the cache size as appropriate. + * + * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer + * returned by `newChangeBuffer()`. + */ addEntry(e, t) { + const n = t.key, r = this.docs.get(n), i = r ? r.size : 0, s = this.ri(t); + return this.docs = this.docs.insert(n, { + document: t.mutableCopy(), + size: s + }), this.size += s - i, this.indexManager.addToCollectionParentIndex(e, n.path.popLast()); + } + /** + * Removes the specified entry from the cache and updates the cache size as appropriate. + * + * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer + * returned by `newChangeBuffer()`. + */ removeEntry(e) { + const t = this.docs.get(e); + t && (this.docs = this.docs.remove(e), this.size -= t.size); + } + getEntry(e, t) { + const n = this.docs.get(t); + return PersistencePromise.resolve(n ? n.document.mutableCopy() : MutableDocument.newInvalidDocument(t)); + } + getEntries(e, t) { + let n = __PRIVATE_mutableDocumentMap(); + return t.forEach((e => { + const t = this.docs.get(e); + n = n.insert(e, t ? t.document.mutableCopy() : MutableDocument.newInvalidDocument(e)); + })), PersistencePromise.resolve(n); + } + getDocumentsMatchingQuery(e, t, n, r) { + let i = __PRIVATE_mutableDocumentMap(); + // Documents are ordered by key, so we can use a prefix scan to narrow down + // the documents we need to match the query against. + const s = t.path, o = new DocumentKey(s.child("__id-9223372036854775808__")), _ = this.docs.getIteratorFrom(o); + // Document keys are ordered first by numeric value ("__id__"), + // then lexicographically by string value. Start the iterator at the minimum + // possible Document key value. + for (;_.hasNext(); ) { + const {key: e, value: {document: o}} = _.getNext(); + if (!s.isPrefixOf(e.path)) break; + e.path.length > s.length + 1 || (__PRIVATE_indexOffsetComparator(__PRIVATE_newIndexOffsetFromDocument(o), n) <= 0 || (r.has(o.key) || __PRIVATE_queryMatches(t, o)) && (i = i.insert(o.key, o.mutableCopy()))); + } + return PersistencePromise.resolve(i); + } + getAllFromCollectionGroup(e, t, n, r) { + // This method should only be called from the IndexBackfiller if persistence + // is enabled. + fail(9500); + } + ii(e, t) { + return PersistencePromise.forEach(this.docs, (e => t(e))); + } + newChangeBuffer(e) { + // `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps + // a separate changelog and does not need special handling for removals. + return new __PRIVATE_MemoryRemoteDocumentChangeBuffer(this); + } + getSize(e) { + return PersistencePromise.resolve(this.size); + } +} + +/** + * Creates a new memory-only RemoteDocumentCache. + * + * @param sizer - Used to assess the size of a document. For eager GC, this is + * expected to just return 0 to avoid unnecessarily doing the work of + * calculating the size. + */ +/** + * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache. + */ +class __PRIVATE_MemoryRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer { + constructor(e) { + super(), this.Nr = e; + } + applyChanges(e) { + const t = []; + return this.changes.forEach(((n, r) => { + r.isValidDocument() ? t.push(this.Nr.addEntry(e, r)) : this.Nr.removeEntry(n); + })), PersistencePromise.waitFor(t); + } + getFromCache(e, t) { + return this.Nr.getEntry(e, t); + } + getAllFromCache(e, t) { + return this.Nr.getEntries(e, t); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_MemoryTargetCache { + constructor(e) { + this.persistence = e, + /** + * Maps a target to the data about that target + */ + this.si = new ObjectMap((e => __PRIVATE_canonifyTarget(e)), __PRIVATE_targetEquals), + /** The last received snapshot version. */ + this.lastRemoteSnapshotVersion = SnapshotVersion.min(), + /** The highest numbered target ID encountered. */ + this.highestTargetId = 0, + /** The highest sequence number encountered. */ + this.oi = 0, + /** + * A ordered bidirectional mapping between documents and the remote target + * IDs. + */ + this._i = new __PRIVATE_ReferenceSet, this.targetCount = 0, this.ai = __PRIVATE_TargetIdGenerator.ur(); + } + forEachTarget(e, t) { + return this.si.forEach(((e, n) => t(n))), PersistencePromise.resolve(); + } + getLastRemoteSnapshotVersion(e) { + return PersistencePromise.resolve(this.lastRemoteSnapshotVersion); + } + getHighestSequenceNumber(e) { + return PersistencePromise.resolve(this.oi); + } + allocateTargetId(e) { + return this.highestTargetId = this.ai.next(), PersistencePromise.resolve(this.highestTargetId); + } + setTargetsMetadata(e, t, n) { + return n && (this.lastRemoteSnapshotVersion = n), t > this.oi && (this.oi = t), + PersistencePromise.resolve(); + } + Pr(e) { + this.si.set(e.target, e); + const t = e.targetId; + t > this.highestTargetId && (this.ai = new __PRIVATE_TargetIdGenerator(t), this.highestTargetId = t), + e.sequenceNumber > this.oi && (this.oi = e.sequenceNumber); + } + addTargetData(e, t) { + return this.Pr(t), this.targetCount += 1, PersistencePromise.resolve(); + } + updateTargetData(e, t) { + return this.Pr(t), PersistencePromise.resolve(); + } + removeTargetData(e, t) { + return this.si.delete(t.target), this._i.jr(t.targetId), this.targetCount -= 1, + PersistencePromise.resolve(); + } + removeTargets(e, t, n) { + let r = 0; + const i = []; + return this.si.forEach(((s, o) => { + o.sequenceNumber <= t && null === n.get(o.targetId) && (this.si.delete(s), i.push(this.removeMatchingKeysForTargetId(e, o.targetId)), + r++); + })), PersistencePromise.waitFor(i).next((() => r)); + } + getTargetCount(e) { + return PersistencePromise.resolve(this.targetCount); + } + getTargetData(e, t) { + const n = this.si.get(t) || null; + return PersistencePromise.resolve(n); + } + addMatchingKeys(e, t, n) { + return this._i.Wr(t, n), PersistencePromise.resolve(); + } + removeMatchingKeys(e, t, n) { + this._i.zr(t, n); + const r = this.persistence.referenceDelegate, i = []; + return r && t.forEach((t => { + i.push(r.markPotentiallyOrphaned(e, t)); + })), PersistencePromise.waitFor(i); + } + removeMatchingKeysForTargetId(e, t) { + return this._i.jr(t), PersistencePromise.resolve(); + } + getMatchingKeysForTargetId(e, t) { + const n = this._i.Hr(t); + return PersistencePromise.resolve(n); + } + containsKey(e, t) { + return PersistencePromise.resolve(this._i.containsKey(t)); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A memory-backed instance of Persistence. Data is stored only in RAM and + * not persisted across sessions. + */ +class __PRIVATE_MemoryPersistence { + /** + * The constructor accepts a factory for creating a reference delegate. This + * allows both the delegate and this instance to have strong references to + * each other without having nullable fields that would then need to be + * checked or asserted on every access. + */ + constructor(e, t) { + this.ui = {}, this.overlays = {}, this.ci = new __PRIVATE_ListenSequence(0), this.li = !1, + this.li = !0, this.hi = new __PRIVATE_MemoryGlobalsCache, this.referenceDelegate = e(this), + this.Pi = new __PRIVATE_MemoryTargetCache(this); + this.indexManager = new __PRIVATE_MemoryIndexManager, this.remoteDocumentCache = function __PRIVATE_newMemoryRemoteDocumentCache(e) { + return new __PRIVATE_MemoryRemoteDocumentCacheImpl(e); + }((e => this.referenceDelegate.Ti(e))), this.serializer = new __PRIVATE_LocalSerializer(t), + this.Ii = new __PRIVATE_MemoryBundleCache(this.serializer); + } + start() { + return Promise.resolve(); + } + shutdown() { + // No durable state to ensure is closed on shutdown. + return this.li = !1, Promise.resolve(); + } + get started() { + return this.li; + } + setDatabaseDeletedListener() { + // No op. + } + setNetworkEnabled() { + // No op. + } + getIndexManager(e) { + // We do not currently support indices for memory persistence, so we can + // return the same shared instance of the memory index manager. + return this.indexManager; + } + getDocumentOverlayCache(e) { + let t = this.overlays[e.toKey()]; + return t || (t = new __PRIVATE_MemoryDocumentOverlayCache, this.overlays[e.toKey()] = t), + t; + } + getMutationQueue(e, t) { + let n = this.ui[e.toKey()]; + return n || (n = new __PRIVATE_MemoryMutationQueue(t, this.referenceDelegate), this.ui[e.toKey()] = n), + n; + } + getGlobalsCache() { + return this.hi; + } + getTargetCache() { + return this.Pi; + } + getRemoteDocumentCache() { + return this.remoteDocumentCache; + } + getBundleCache() { + return this.Ii; + } + runTransaction(e, t, n) { + __PRIVATE_logDebug("MemoryPersistence", "Starting transaction:", e); + const r = new __PRIVATE_MemoryTransaction(this.ci.next()); + return this.referenceDelegate.Ei(), n(r).next((e => this.referenceDelegate.di(r).next((() => e)))).toPromise().then((e => (r.raiseOnCommittedEvent(), + e))); + } + Ai(e, t) { + return PersistencePromise.or(Object.values(this.ui).map((n => () => n.containsKey(e, t)))); + } +} + +/** + * Memory persistence is not actually transactional, but future implementations + * may have transaction-scoped state. + */ class __PRIVATE_MemoryTransaction extends PersistenceTransaction { + constructor(e) { + super(), this.currentSequenceNumber = e; + } +} + +class __PRIVATE_MemoryEagerDelegate { + constructor(e) { + this.persistence = e, + /** Tracks all documents that are active in Query views. */ + this.Ri = new __PRIVATE_ReferenceSet, + /** The list of documents that are potentially GCed after each transaction. */ + this.Vi = null; + } + static mi(e) { + return new __PRIVATE_MemoryEagerDelegate(e); + } + get fi() { + if (this.Vi) return this.Vi; + throw fail(60996); + } + addReference(e, t, n) { + return this.Ri.addReference(n, t), this.fi.delete(n.toString()), PersistencePromise.resolve(); + } + removeReference(e, t, n) { + return this.Ri.removeReference(n, t), this.fi.add(n.toString()), PersistencePromise.resolve(); + } + markPotentiallyOrphaned(e, t) { + return this.fi.add(t.toString()), PersistencePromise.resolve(); + } + removeTarget(e, t) { + this.Ri.jr(t.targetId).forEach((e => this.fi.add(e.toString()))); + const n = this.persistence.getTargetCache(); + return n.getMatchingKeysForTargetId(e, t.targetId).next((e => { + e.forEach((e => this.fi.add(e.toString()))); + })).next((() => n.removeTargetData(e, t))); + } + Ei() { + this.Vi = new Set; + } + di(e) { + // Remove newly orphaned documents. + const t = this.persistence.getRemoteDocumentCache().newChangeBuffer(); + return PersistencePromise.forEach(this.fi, (n => { + const r = DocumentKey.fromPath(n); + return this.gi(e, r).next((e => { + e || t.removeEntry(r, SnapshotVersion.min()); + })); + })).next((() => (this.Vi = null, t.apply(e)))); + } + updateLimboDocument(e, t) { + return this.gi(e, t).next((e => { + e ? this.fi.delete(t.toString()) : this.fi.add(t.toString()); + })); + } + Ti(e) { + // For eager GC, we don't care about the document size, there are no size thresholds. + return 0; + } + gi(e, t) { + return PersistencePromise.or([ () => PersistencePromise.resolve(this.Ri.containsKey(t)), () => this.persistence.getTargetCache().containsKey(e, t), () => this.persistence.Ai(e, t) ]); + } +} + +class __PRIVATE_MemoryLruDelegate { + constructor(e, t) { + this.persistence = e, this.pi = new ObjectMap((e => __PRIVATE_encodeResourcePath(e.path)), ((e, t) => e.isEqual(t))), + this.garbageCollector = __PRIVATE_newLruGarbageCollector(this, t); + } + static mi(e, t) { + return new __PRIVATE_MemoryLruDelegate(e, t); + } + // No-ops, present so memory persistence doesn't have to care which delegate + // it has. + Ei() {} + di(e) { + return PersistencePromise.resolve(); + } + forEachTarget(e, t) { + return this.persistence.getTargetCache().forEachTarget(e, t); + } + gr(e) { + const t = this.wr(e); + return this.persistence.getTargetCache().getTargetCount(e).next((e => t.next((t => e + t)))); + } + wr(e) { + let t = 0; + return this.pr(e, (e => { + t++; + })).next((() => t)); + } + pr(e, t) { + return PersistencePromise.forEach(this.pi, ((n, r) => this.br(e, n, r).next((e => e ? PersistencePromise.resolve() : t(r))))); + } + removeTargets(e, t, n) { + return this.persistence.getTargetCache().removeTargets(e, t, n); + } + removeOrphanedDocuments(e, t) { + let n = 0; + const r = this.persistence.getRemoteDocumentCache(), i = r.newChangeBuffer(); + return r.ii(e, (r => this.br(e, r, t).next((e => { + e || (n++, i.removeEntry(r, SnapshotVersion.min())); + })))).next((() => i.apply(e))).next((() => n)); + } + markPotentiallyOrphaned(e, t) { + return this.pi.set(t, e.currentSequenceNumber), PersistencePromise.resolve(); + } + removeTarget(e, t) { + const n = t.withSequenceNumber(e.currentSequenceNumber); + return this.persistence.getTargetCache().updateTargetData(e, n); + } + addReference(e, t, n) { + return this.pi.set(n, e.currentSequenceNumber), PersistencePromise.resolve(); + } + removeReference(e, t, n) { + return this.pi.set(n, e.currentSequenceNumber), PersistencePromise.resolve(); + } + updateLimboDocument(e, t) { + return this.pi.set(t, e.currentSequenceNumber), PersistencePromise.resolve(); + } + Ti(e) { + let t = e.key.toString().length; + return e.isFoundDocument() && (t += __PRIVATE_estimateByteSize(e.data.value)), t; + } + br(e, t, n) { + return PersistencePromise.or([ () => this.persistence.Ai(e, t), () => this.persistence.getTargetCache().containsKey(e, t), () => { + const e = this.pi.get(t); + return PersistencePromise.resolve(void 0 !== e && e > n); + } ]); + } + getCacheSize(e) { + return this.persistence.getRemoteDocumentCache().getSize(e); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Performs database creation and schema upgrades. */ class __PRIVATE_SchemaConverter { + constructor(e) { + this.serializer = e; + } + /** + * Performs database creation and schema upgrades. + * + * Note that in production, this method is only ever used to upgrade the schema + * to SCHEMA_VERSION. Different values of toVersion are only used for testing + * and local feature development. + */ k(e, t, n, r) { + const i = new __PRIVATE_SimpleDbTransaction("createOrUpgrade", t); + n < 1 && r >= 1 && (!function __PRIVATE_createPrimaryClientStore(e) { + e.createObjectStore(Y); + }(e), function __PRIVATE_createMutationQueue(e) { + e.createObjectStore(X, { + keyPath: ee + }); + const t = e.createObjectStore(te, { + keyPath: ne, + autoIncrement: !0 + }); + t.createIndex(re, ie, { + unique: !0 + }), e.createObjectStore(oe); + } + /** + * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads + * and rewrites all data. + */ (e), __PRIVATE_createQueryCache(e), function __PRIVATE_createLegacyRemoteDocumentCache(e) { + e.createObjectStore(H); + }(e)); + // Migration 2 to populate the targetGlobal object no longer needed since + // migration 3 unconditionally clears it. + let s = PersistencePromise.resolve(); + return n < 3 && r >= 3 && ( + // Brand new clients don't need to drop and recreate--only clients that + // potentially have corrupt data. + 0 !== n && (!function __PRIVATE_dropQueryCache(e) { + e.deleteObjectStore(Ae), e.deleteObjectStore(Ie), e.deleteObjectStore(ge); + }(e), __PRIVATE_createQueryCache(e)), s = s.next((() => + /** + * Creates the target global singleton row. + * + * @param txn - The version upgrade transaction for indexeddb + */ + function __PRIVATE_writeEmptyTargetGlobalEntry(e) { + const t = e.store(ge), n = { + highestTargetId: 0, + highestListenSequenceNumber: 0, + lastRemoteSnapshotVersion: SnapshotVersion.min().toTimestamp(), + targetCount: 0 + }; + return t.put(fe, n); + }(i)))), n < 4 && r >= 4 && (0 !== n && ( + // Schema version 3 uses auto-generated keys to generate globally unique + // mutation batch IDs (this was previously ensured internally by the + // client). To migrate to the new schema, we have to read all mutations + // and write them back out. We preserve the existing batch IDs to guarantee + // consistency with other object stores. Any further mutation batch IDs will + // be auto-generated. + s = s.next((() => function __PRIVATE_upgradeMutationBatchSchemaAndMigrateData(e, t) { + const n = t.store(te); + return n.J().next((n => { + e.deleteObjectStore(te); + e.createObjectStore(te, { + keyPath: ne, + autoIncrement: !0 + }).createIndex(re, ie, { + unique: !0 + }); + const r = t.store(te), i = n.map((e => r.put(e))); + return PersistencePromise.waitFor(i); + })); + }(e, i)))), s = s.next((() => { + !function __PRIVATE_createClientMetadataStore(e) { + e.createObjectStore(we, { + keyPath: Se + }); + }(e); + }))), n < 5 && r >= 5 && (s = s.next((() => this.yi(i)))), n < 6 && r >= 6 && (s = s.next((() => (function __PRIVATE_createDocumentGlobalStore(e) { + e.createObjectStore(Pe); + }(e), this.wi(i))))), n < 7 && r >= 7 && (s = s.next((() => this.Si(i)))), n < 8 && r >= 8 && (s = s.next((() => this.bi(e, i)))), + n < 9 && r >= 9 && (s = s.next((() => { + // Multi-Tab used to manage its own changelog, but this has been moved + // to the DbRemoteDocument object store itself. Since the previous change + // log only contained transient data, we can drop its object store. + !function __PRIVATE_dropRemoteDocumentChangesStore(e) { + e.objectStoreNames.contains("remoteDocumentChanges") && e.deleteObjectStore("remoteDocumentChanges"); + }(e); + // Note: Schema version 9 used to create a read time index for the + // RemoteDocumentCache. This is now done with schema version 13. + }))), n < 10 && r >= 10 && (s = s.next((() => this.Di(i)))), n < 11 && r >= 11 && (s = s.next((() => { + !function __PRIVATE_createBundlesStore(e) { + e.createObjectStore(be, { + keyPath: De + }); + }(e), function __PRIVATE_createNamedQueriesStore(e) { + e.createObjectStore(Ce, { + keyPath: ve + }); + }(e); + }))), n < 12 && r >= 12 && (s = s.next((() => { + !function __PRIVATE_createDocumentOverlayStore(e) { + const t = e.createObjectStore(Ke, { + keyPath: We + }); + t.createIndex(Ge, ze, { + unique: !1 + }), t.createIndex(je, Je, { + unique: !1 + }); + }(e); + }))), n < 13 && r >= 13 && (s = s.next((() => function __PRIVATE_createRemoteDocumentCache(e) { + const t = e.createObjectStore(_e, { + keyPath: ae + }); + t.createIndex(ue, ce), t.createIndex(le, he); + }(e))).next((() => this.Ci(e, i))).next((() => e.deleteObjectStore(H)))), n < 14 && r >= 14 && (s = s.next((() => this.Fi(e, i)))), + n < 15 && r >= 15 && (s = s.next((() => function __PRIVATE_createFieldIndex(e) { + const t = e.createObjectStore(Fe, { + keyPath: Me, + autoIncrement: !0 + }); + t.createIndex(xe, Oe, { + unique: !1 + }); + const n = e.createObjectStore(Ne, { + keyPath: Be + }); + n.createIndex(Le, ke, { + unique: !1 + }); + const r = e.createObjectStore(qe, { + keyPath: Qe + }); + r.createIndex($e, Ue, { + unique: !1 + }); + }(e)))), n < 16 && r >= 16 && ( + // Clear the object stores to remove possibly corrupted index entries + s = s.next((() => { + t.objectStore(Ne).clear(); + })).next((() => { + t.objectStore(qe).clear(); + }))), n < 17 && r >= 17 && (s = s.next((() => { + !function __PRIVATE_createGlobalsStore(e) { + e.createObjectStore(He, { + keyPath: Ye + }); + }(e); + }))), n < 18 && r >= 18 && util.isSafariOrWebkit() && (s = s.next((() => { + t.objectStore(Ne).clear(); + })).next((() => { + t.objectStore(qe).clear(); + }))), s; + } + wi(e) { + let t = 0; + return e.store(H).ee(((e, n) => { + t += __PRIVATE_dbDocumentSize(n); + })).next((() => { + const n = { + byteSize: t + }; + return e.store(Pe).put(Te, n); + })); + } + yi(e) { + const t = e.store(X), n = e.store(te); + return t.J().next((t => PersistencePromise.forEach(t, (t => { + const r = IDBKeyRange.bound([ t.userId, j ], [ t.userId, t.lastAcknowledgedBatchId ]); + return n.J(re, r).next((n => PersistencePromise.forEach(n, (n => { + __PRIVATE_hardAssert(n.userId === t.userId, 18650, "Cannot process batch from unexpected user", { + batchId: n.batchId + }); + const r = __PRIVATE_fromDbMutationBatch(this.serializer, n); + return removeMutationBatch(e, t.userId, r).next((() => {})); + })))); + })))); + } + /** + * Ensures that every document in the remote document cache has a corresponding sentinel row + * with a sequence number. Missing rows are given the most recently used sequence number. + */ Si(e) { + const t = e.store(Ae), n = e.store(H); + return e.store(ge).get(fe).next((e => { + const r = []; + return n.ee(((n, i) => { + const s = new ResourcePath(n), o = function __PRIVATE_sentinelKey(e) { + return [ 0, __PRIVATE_encodeResourcePath(e) ]; + }(s); + r.push(t.get(o).next((n => n ? PersistencePromise.resolve() : (n => t.put({ + targetId: 0, + path: __PRIVATE_encodeResourcePath(n), + sequenceNumber: e.highestListenSequenceNumber + }))(s)))); + })).next((() => PersistencePromise.waitFor(r))); + })); + } + bi(e, t) { + // Create the index. + e.createObjectStore(pe, { + keyPath: ye + }); + const n = t.store(pe), r = new __PRIVATE_MemoryCollectionParentIndex, addEntry = e => { + if (r.add(e)) { + const t = e.lastSegment(), r = e.popLast(); + return n.put({ + collectionId: t, + parent: __PRIVATE_encodeResourcePath(r) + }); + } + }; + // Helper to add an index entry iff we haven't already written it. + // Index existing remote documents. + return t.store(H).ee({ + X: !0 + }, ((e, t) => { + const n = new ResourcePath(e); + return addEntry(n.popLast()); + })).next((() => t.store(oe).ee({ + X: !0 + }, (([e, t, n], r) => { + const i = __PRIVATE_decodeResourcePath(t); + return addEntry(i.popLast()); + })))); + } + Di(e) { + const t = e.store(Ie); + return t.ee(((e, n) => { + const r = __PRIVATE_fromDbTarget(n), i = __PRIVATE_toDbTarget(this.serializer, r); + return t.put(i); + })); + } + Ci(e, t) { + const n = t.store(H), r = []; + return n.ee(((e, n) => { + const i = t.store(_e), s = function __PRIVATE_extractKey(e) { + return e.document ? new DocumentKey(ResourcePath.fromString(e.document.name).popFirst(5)) : e.noDocument ? DocumentKey.fromSegments(e.noDocument.path) : e.unknownDocument ? DocumentKey.fromSegments(e.unknownDocument.path) : fail(36783); + } + /** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ (n).path.toArray(), o = { + prefixPath: s.slice(0, s.length - 2), + collectionGroup: s[s.length - 2], + documentId: s[s.length - 1], + readTime: n.readTime || [ 0, 0 ], + unknownDocument: n.unknownDocument, + noDocument: n.noDocument, + document: n.document, + hasCommittedMutations: !!n.hasCommittedMutations + }; + r.push(i.put(o)); + })).next((() => PersistencePromise.waitFor(r))); + } + Fi(e, t) { + const n = t.store(te), r = __PRIVATE_newIndexedDbRemoteDocumentCache(this.serializer), i = new __PRIVATE_MemoryPersistence(__PRIVATE_MemoryEagerDelegate.mi, this.serializer.yt); + return n.J().next((e => { + const n = new Map; + return e.forEach((e => { + let t = n.get(e.userId) ?? __PRIVATE_documentKeySet(); + __PRIVATE_fromDbMutationBatch(this.serializer, e).keys().forEach((e => t = t.add(e))), + n.set(e.userId, t); + })), PersistencePromise.forEach(n, ((e, n) => { + const s = new User(n), o = __PRIVATE_IndexedDbDocumentOverlayCache.wt(this.serializer, s), _ = i.getIndexManager(s), a = __PRIVATE_IndexedDbMutationQueue.wt(s, this.serializer, _, i.referenceDelegate); + return new LocalDocumentsView(r, a, o, _).recalculateAndSaveOverlaysForDocumentKeys(new __PRIVATE_IndexedDbTransaction(t, __PRIVATE_ListenSequence.ce), e).next(); + })); + })); + } +} + +function __PRIVATE_createQueryCache(e) { + e.createObjectStore(Ae, { + keyPath: Re + }).createIndex(Ve, me, { + unique: !0 + }); + // NOTE: This is unique only because the TargetId is the suffix. + e.createObjectStore(Ie, { + keyPath: "targetId" + }).createIndex(Ee, de, { + unique: !0 + }), e.createObjectStore(ge); +} + +const Lt = "IndexedDbPersistence", kt = 18e5, qt = 5e3, Qt = "Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.", $t = "main"; + +/** + * Oldest acceptable age in milliseconds for client metadata before the client + * is considered inactive and its associated data is garbage collected. + */ +/** + * An IndexedDB-backed instance of Persistence. Data is stored persistently + * across sessions. + * + * On Web only, the Firestore SDKs support shared access to its persistence + * layer. This allows multiple browser tabs to read and write to IndexedDb and + * to synchronize state even without network connectivity. Shared access is + * currently optional and not enabled unless all clients invoke + * `enablePersistence()` with `{synchronizeTabs:true}`. + * + * In multi-tab mode, if multiple clients are active at the same time, the SDK + * will designate one client as the "primary client". An effort is made to pick + * a visible, network-connected and active client, and this client is + * responsible for letting other clients know about its presence. The primary + * client writes a unique client-generated identifier (the client ID) to + * IndexedDb’s "owner" store every 4 seconds. If the primary client fails to + * update this entry, another client can acquire the lease and take over as + * primary. + * + * Some persistence operations in the SDK are designated as primary-client only + * operations. This includes the acknowledgment of mutations and all updates of + * remote documents. The effects of these operations are written to persistence + * and then broadcast to other tabs via LocalStorage (see + * `WebStorageSharedClientState`), which then refresh their state from + * persistence. + * + * Similarly, the primary client listens to notifications sent by secondary + * clients to discover persistence changes written by secondary clients, such as + * the addition of new mutations and query targets. + * + * If multi-tab is not enabled and another tab already obtained the primary + * lease, IndexedDbPersistence enters a failed state and all subsequent + * operations will automatically fail. + * + * Additionally, there is an optimization so that when a tab is closed, the + * primary lease is released immediately (this is especially important to make + * sure that a refreshed tab is able to immediately re-acquire the primary + * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload + * since it is an asynchronous API. So in addition to attempting to give up the + * lease, the leaseholder writes its client ID to a "zombiedClient" entry in + * LocalStorage which acts as an indicator that another tab should go ahead and + * take the primary lease immediately regardless of the current lease timestamp. + * + * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no + * longer optional. + */ +class __PRIVATE_IndexedDbPersistence { + constructor( + /** + * Whether to synchronize the in-memory state of multiple tabs and share + * access to local persistence. + */ + e, t, n, r, i, s, o, _, a, + /** + * If set to true, forcefully obtains database access. Existing tabs will + * no longer be able to access IndexedDB. + */ + u, c = 18) { + if (this.allowTabSynchronization = e, this.persistenceKey = t, this.clientId = n, + this.Mi = i, this.window = s, this.document = o, this.xi = a, this.Oi = u, this.Ni = c, + this.ci = null, this.li = !1, this.isPrimary = !1, this.networkEnabled = !0, + /** Our window.unload handler, if registered. */ + this.Bi = null, this.inForeground = !1, + /** Our 'visibilitychange' listener if registered. */ + this.Li = null, + /** The client metadata refresh task. */ + this.ki = null, + /** The last time we garbage collected the client metadata object store. */ + this.qi = Number.NEGATIVE_INFINITY, + /** A listener to notify on primary state changes. */ + this.Qi = e => Promise.resolve(), !__PRIVATE_IndexedDbPersistence.v()) throw new FirestoreError(N.UNIMPLEMENTED, "This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled."); + this.referenceDelegate = new __PRIVATE_IndexedDbLruDelegateImpl(this, r), this.$i = t + $t, + this.serializer = new __PRIVATE_LocalSerializer(_), this.Ui = new __PRIVATE_SimpleDb(this.$i, this.Ni, new __PRIVATE_SchemaConverter(this.serializer)), + this.hi = new __PRIVATE_IndexedDbGlobalsCache, this.Pi = new __PRIVATE_IndexedDbTargetCache(this.referenceDelegate, this.serializer), + this.remoteDocumentCache = __PRIVATE_newIndexedDbRemoteDocumentCache(this.serializer), + this.Ii = new __PRIVATE_IndexedDbBundleCache, this.window && this.window.localStorage ? this.Ki = this.window.localStorage : (this.Ki = null, + !1 === u && __PRIVATE_logError(Lt, "LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page.")); + } + /** + * Attempt to start IndexedDb persistence. + * + * @returns Whether persistence was enabled. + */ start() { + // NOTE: This is expected to fail sometimes (in the case of another tab + // already having the persistence lock), so it's the first thing we should + // do. + return this.Wi().then((() => { + if (!this.isPrimary && !this.allowTabSynchronization) + // Fail `start()` if `synchronizeTabs` is disabled and we cannot + // obtain the primary lease. + throw new FirestoreError(N.FAILED_PRECONDITION, Qt); + return this.Gi(), this.zi(), this.ji(), this.runTransaction("getHighestListenSequenceNumber", "readonly", (e => this.Pi.getHighestSequenceNumber(e))); + })).then((e => { + this.ci = new __PRIVATE_ListenSequence(e, this.xi); + })).then((() => { + this.li = !0; + })).catch((e => (this.Ui && this.Ui.close(), Promise.reject(e)))); + } + /** + * Registers a listener that gets called when the primary state of the + * instance changes. Upon registering, this listener is invoked immediately + * with the current primary state. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ Ji(e) { + return this.Qi = async t => { + if (this.started) return e(t); + }, e(this.isPrimary); + } + /** + * Registers a listener that gets called when the database receives a + * version change event indicating that it has deleted. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ setDatabaseDeletedListener(e) { + this.Ui.$((async t => { + // Check if an attempt is made to delete IndexedDB. + null === t.newVersion && await e(); + })); + } + /** + * Adjusts the current network state in the client's metadata, potentially + * affecting the primary lease. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ setNetworkEnabled(e) { + this.networkEnabled !== e && (this.networkEnabled = e, + // Schedule a primary lease refresh for immediate execution. The eventual + // lease update will be propagated via `primaryStateListener`. + this.Mi.enqueueAndForget((async () => { + this.started && await this.Wi(); + }))); + } + /** + * Updates the client metadata in IndexedDb and attempts to either obtain or + * extend the primary lease for the local client. Asynchronously notifies the + * primary state listener if the client either newly obtained or released its + * primary lease. + */ Wi() { + return this.runTransaction("updateClientMetadataAndTryBecomePrimary", "readwrite", (e => __PRIVATE_clientMetadataStore(e).put({ + clientId: this.clientId, + updateTimeMs: Date.now(), + networkEnabled: this.networkEnabled, + inForeground: this.inForeground + }).next((() => { + if (this.isPrimary) return this.Hi(e).next((e => { + e || (this.isPrimary = !1, this.Mi.enqueueRetryable((() => this.Qi(!1)))); + })); + })).next((() => this.Yi(e))).next((t => this.isPrimary && !t ? this.Zi(e).next((() => !1)) : !!t && this.Xi(e).next((() => !0)))))).catch((e => { + if (__PRIVATE_isIndexedDbTransactionError(e)) + // Proceed with the existing state. Any subsequent access to + // IndexedDB will verify the lease. + return __PRIVATE_logDebug(Lt, "Failed to extend owner lease: ", e), this.isPrimary; + if (!this.allowTabSynchronization) throw e; + return __PRIVATE_logDebug(Lt, "Releasing owner lease after error during lease refresh", e), + /* isPrimary= */ !1; + })).then((e => { + this.isPrimary !== e && this.Mi.enqueueRetryable((() => this.Qi(e))), this.isPrimary = e; + })); + } + Hi(e) { + return __PRIVATE_primaryClientStore(e).get(Z).next((e => PersistencePromise.resolve(this.es(e)))); + } + ts(e) { + return __PRIVATE_clientMetadataStore(e).delete(this.clientId); + } + /** + * If the garbage collection threshold has passed, prunes the + * RemoteDocumentChanges and the ClientMetadata store based on the last update + * time of all clients. + */ async ns() { + if (this.isPrimary && !this.rs(this.qi, kt)) { + this.qi = Date.now(); + const e = await this.runTransaction("maybeGarbageCollectMultiClientState", "readwrite-primary", (e => { + const t = __PRIVATE_getStore(e, we); + return t.J().next((e => { + const n = this.ss(e, kt), r = e.filter((e => -1 === n.indexOf(e))); + // Delete metadata for clients that are no longer considered active. + return PersistencePromise.forEach(r, (e => t.delete(e.clientId))).next((() => r)); + })); + })).catch((() => [])); + // Delete potential leftover entries that may continue to mark the + // inactive clients as zombied in LocalStorage. + // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for + // the client atomically, but we can't. So we opt to delete the IndexedDb + // entries first to avoid potentially reviving a zombied client. + if (this.Ki) for (const t of e) this.Ki.removeItem(this._s(t.clientId)); + } + } + /** + * Schedules a recurring timer to update the client metadata and to either + * extend or acquire the primary lease if the client is eligible. + */ ji() { + this.ki = this.Mi.enqueueAfterDelay("client_metadata_refresh" /* TimerId.ClientMetadataRefresh */ , 4e3, (() => this.Wi().then((() => this.ns())).then((() => this.ji())))); + } + /** Checks whether `client` is the local client. */ es(e) { + return !!e && e.ownerId === this.clientId; + } + /** + * Evaluate the state of all active clients and determine whether the local + * client is or can act as the holder of the primary lease. Returns whether + * the client is eligible for the lease, but does not actually acquire it. + * May return 'false' even if there is no active leaseholder and another + * (foreground) client should become leaseholder instead. + */ Yi(e) { + if (this.Oi) return PersistencePromise.resolve(!0); + return __PRIVATE_primaryClientStore(e).get(Z).next((t => { + // A client is eligible for the primary lease if: + // - its network is enabled and the client's tab is in the foreground. + // - its network is enabled and no other client's tab is in the + // foreground. + // - every clients network is disabled and the client's tab is in the + // foreground. + // - every clients network is disabled and no other client's tab is in + // the foreground. + // - the `forceOwningTab` setting was passed in. + if (null !== t && this.rs(t.leaseTimestampMs, qt) && !this.us(t.ownerId)) { + if (this.es(t) && this.networkEnabled) return !0; + if (!this.es(t)) { + if (!t.allowTabSynchronization) + // Fail the `canActAsPrimary` check if the current leaseholder has + // not opted into multi-tab synchronization. If this happens at + // client startup, we reject the Promise returned by + // `enablePersistence()` and the user can continue to use Firestore + // with in-memory persistence. + // If this fails during a lease refresh, we will instead block the + // AsyncQueue from executing further operations. Note that this is + // acceptable since mixing & matching different `synchronizeTabs` + // settings is not supported. + // TODO(b/114226234): Remove this check when `synchronizeTabs` can + // no longer be turned off. + throw new FirestoreError(N.FAILED_PRECONDITION, Qt); + return !1; + } + } + return !(!this.networkEnabled || !this.inForeground) || __PRIVATE_clientMetadataStore(e).J().next((e => void 0 === this.ss(e, qt).find((e => { + if (this.clientId !== e.clientId) { + const t = !this.networkEnabled && e.networkEnabled, n = !this.inForeground && e.inForeground, r = this.networkEnabled === e.networkEnabled; + if (t || n && r) return !0; + } + return !1; + })))); + })).next((e => (this.isPrimary !== e && __PRIVATE_logDebug(Lt, `Client ${e ? "is" : "is not"} eligible for a primary lease.`), + e))); + } + async shutdown() { + // The shutdown() operations are idempotent and can be called even when + // start() aborted (e.g. because it couldn't acquire the persistence lease). + this.li = !1, this.cs(), this.ki && (this.ki.cancel(), this.ki = null), this.ls(), + this.hs(), + // Use `SimpleDb.runTransaction` directly to avoid failing if another tab + // has obtained the primary lease. + await this.Ui.runTransaction("shutdown", "readwrite", [ Y, we ], (e => { + const t = new __PRIVATE_IndexedDbTransaction(e, __PRIVATE_ListenSequence.ce); + return this.Zi(t).next((() => this.ts(t))); + })), this.Ui.close(), + // Remove the entry marking the client as zombied from LocalStorage since + // we successfully deleted its metadata from IndexedDb. + this.Ps(); + } + /** + * Returns clients that are not zombied and have an updateTime within the + * provided threshold. + */ ss(e, t) { + return e.filter((e => this.rs(e.updateTimeMs, t) && !this.us(e.clientId))); + } + /** + * Returns the IDs of the clients that are currently active. If multi-tab + * is not supported, returns an array that only contains the local client's + * ID. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ Ts() { + return this.runTransaction("getActiveClients", "readonly", (e => __PRIVATE_clientMetadataStore(e).J().next((e => this.ss(e, kt).map((e => e.clientId)))))); + } + get started() { + return this.li; + } + getGlobalsCache() { + return this.hi; + } + getMutationQueue(e, t) { + return __PRIVATE_IndexedDbMutationQueue.wt(e, this.serializer, t, this.referenceDelegate); + } + getTargetCache() { + return this.Pi; + } + getRemoteDocumentCache() { + return this.remoteDocumentCache; + } + getIndexManager(e) { + return new __PRIVATE_IndexedDbIndexManager(e, this.serializer.yt.databaseId); + } + getDocumentOverlayCache(e) { + return __PRIVATE_IndexedDbDocumentOverlayCache.wt(this.serializer, e); + } + getBundleCache() { + return this.Ii; + } + runTransaction(e, t, n) { + __PRIVATE_logDebug(Lt, "Starting transaction:", e); + const r = "readonly" === t ? "readonly" : "readwrite", i = + /** Returns the object stores for the provided schema. */ + function __PRIVATE_getObjectStores(e) { + return 18 === e ? st : 17 === e ? it : 16 === e ? rt : 15 === e ? nt : 14 === e ? tt : 13 === e ? et : 12 === e ? Xe : 11 === e ? Ze : void fail(60245); + }(this.Ni); + let s; + // Do all transactions as readwrite against all object stores, since we + // are the only reader/writer. + return this.Ui.runTransaction(e, r, i, (r => (s = new __PRIVATE_IndexedDbTransaction(r, this.ci ? this.ci.next() : __PRIVATE_ListenSequence.ce), + "readwrite-primary" === t ? this.Hi(s).next((e => !!e || this.Yi(s))).next((t => { + if (!t) throw __PRIVATE_logError(`Failed to obtain primary lease for action '${e}'.`), + this.isPrimary = !1, this.Mi.enqueueRetryable((() => this.Qi(!1))), new FirestoreError(N.FAILED_PRECONDITION, K); + return n(s); + })).next((e => this.Xi(s).next((() => e)))) : this.Is(s).next((() => n(s)))))).then((e => (s.raiseOnCommittedEvent(), + e))); + } + /** + * Verifies that the current tab is the primary leaseholder or alternatively + * that the leaseholder has opted into multi-tab synchronization. + */ + // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer + // be turned off. + Is(e) { + return __PRIVATE_primaryClientStore(e).get(Z).next((e => { + if (null !== e && this.rs(e.leaseTimestampMs, qt) && !this.us(e.ownerId) && !this.es(e) && !(this.Oi || this.allowTabSynchronization && e.allowTabSynchronization)) throw new FirestoreError(N.FAILED_PRECONDITION, Qt); + })); + } + /** + * Obtains or extends the new primary lease for the local client. This + * method does not verify that the client is eligible for this lease. + */ Xi(e) { + const t = { + ownerId: this.clientId, + allowTabSynchronization: this.allowTabSynchronization, + leaseTimestampMs: Date.now() + }; + return __PRIVATE_primaryClientStore(e).put(Z, t); + } + static v() { + return __PRIVATE_SimpleDb.v(); + } + /** Checks the primary lease and removes it if we are the current primary. */ Zi(e) { + const t = __PRIVATE_primaryClientStore(e); + return t.get(Z).next((e => this.es(e) ? (__PRIVATE_logDebug(Lt, "Releasing primary lease."), + t.delete(Z)) : PersistencePromise.resolve())); + } + /** Verifies that `updateTimeMs` is within `maxAgeMs`. */ rs(e, t) { + const n = Date.now(); + return !(e < n - t) && (!(e > n) || (__PRIVATE_logError(`Detected an update time that is in the future: ${e} > ${n}`), + !1)); + } + Gi() { + null !== this.document && "function" == typeof this.document.addEventListener && (this.Li = () => { + this.Mi.enqueueAndForget((() => (this.inForeground = "visible" === this.document.visibilityState, + this.Wi()))); + }, this.document.addEventListener("visibilitychange", this.Li), this.inForeground = "visible" === this.document.visibilityState); + } + ls() { + this.Li && (this.document.removeEventListener("visibilitychange", this.Li), this.Li = null); + } + /** + * Attaches a window.unload handler that will synchronously write our + * clientId to a "zombie client id" location in LocalStorage. This can be used + * by tabs trying to acquire the primary lease to determine that the lease + * is no longer valid even if the timestamp is recent. This is particularly + * important for the refresh case (so the tab correctly re-acquires the + * primary lease). LocalStorage is used for this rather than IndexedDb because + * it is a synchronous API and so can be used reliably from an unload + * handler. + */ zi() { + "function" == typeof this.window?.addEventListener && (this.Bi = () => { + // Note: In theory, this should be scheduled on the AsyncQueue since it + // accesses internal state. We execute this code directly during shutdown + // to make sure it gets a chance to run. + this.cs(); + const e = /(?:Version|Mobile)\/1[456]/; + util.isSafari() && (navigator.appVersion.match(e) || navigator.userAgent.match(e)) && + // On Safari 14, 15, and 16, we do not run any cleanup actions as it might + // trigger a bug that prevents Safari from re-opening IndexedDB during + // the next page load. + // See https://bugs.webkit.org/show_bug.cgi?id=226547 + this.Mi.enterRestrictedMode(/* purgeExistingTasks= */ !0), this.Mi.enqueueAndForget((() => this.shutdown())); + }, this.window.addEventListener("pagehide", this.Bi)); + } + hs() { + this.Bi && (this.window.removeEventListener("pagehide", this.Bi), this.Bi = null); + } + /** + * Returns whether a client is "zombied" based on its LocalStorage entry. + * Clients become zombied when their tab closes without running all of the + * cleanup logic in `shutdown()`. + */ us(e) { + try { + const t = null !== this.Ki?.getItem(this._s(e)); + return __PRIVATE_logDebug(Lt, `Client '${e}' ${t ? "is" : "is not"} zombied in LocalStorage`), + t; + } catch (e) { + // Gracefully handle if LocalStorage isn't working. + return __PRIVATE_logError(Lt, "Failed to get zombied client id.", e), !1; + } + } + /** + * Record client as zombied (a client that had its tab closed). Zombied + * clients are ignored during primary tab selection. + */ cs() { + if (this.Ki) try { + this.Ki.setItem(this._s(this.clientId), String(Date.now())); + } catch (e) { + // Gracefully handle if LocalStorage isn't available / working. + __PRIVATE_logError("Failed to set zombie client id.", e); + } + } + /** Removes the zombied client entry if it exists. */ Ps() { + if (this.Ki) try { + this.Ki.removeItem(this._s(this.clientId)); + } catch (e) { + // Ignore + } + } + _s(e) { + return `firestore_zombie_${this.persistenceKey}_${e}`; + } +} + +/** + * Helper to get a typed SimpleDbStore for the primary client object store. + */ function __PRIVATE_primaryClientStore(e) { + return __PRIVATE_getStore(e, Y); +} + +/** + * Helper to get a typed SimpleDbStore for the client metadata object store. + */ function __PRIVATE_clientMetadataStore(e) { + return __PRIVATE_getStore(e, we); +} + +/** + * Generates a string used as a prefix when storing data in IndexedDB and + * LocalStorage. + */ function __PRIVATE_indexedDbStoragePrefix(e, t) { + // Use two different prefix formats: + // * firestore / persistenceKey / projectID . databaseID / ... + // * firestore / persistenceKey / projectID / ... + // projectIDs are DNS-compatible names and cannot contain dots + // so there's no danger of collisions. + let n = e.projectId; + return e.isDefaultDatabase || (n += "." + e.database), "firestore/" + t + "/" + n + "/"; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A set of changes to what documents are currently in view and out of view for + * a given query. These changes are sent to the LocalStore by the View (via + * the SyncEngine) and are used to pin / unpin documents as appropriate. + */ +class __PRIVATE_LocalViewChanges { + constructor(e, t, n, r) { + this.targetId = e, this.fromCache = t, this.Es = n, this.ds = r; + } + static As(e, t) { + let n = __PRIVATE_documentKeySet(), r = __PRIVATE_documentKeySet(); + for (const e of t.docChanges) switch (e.type) { + case 0 /* ChangeType.Added */ : + n = n.add(e.doc.key); + break; + + case 1 /* ChangeType.Removed */ : + r = r.add(e.doc.key); + // do nothing + } + return new __PRIVATE_LocalViewChanges(e, t.fromCache, n, r); + } +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A tracker to keep a record of important details during database local query + * execution. + */ class QueryContext { + constructor() { + /** + * Counts the number of documents passed through during local query execution. + */ + this._documentReadCount = 0; + } + get documentReadCount() { + return this._documentReadCount; + } + incrementDocumentReadCount(e) { + this._documentReadCount += e; + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The Firestore query engine. + * + * Firestore queries can be executed in three modes. The Query Engine determines + * what mode to use based on what data is persisted. The mode only determines + * the runtime complexity of the query - the result set is equivalent across all + * implementations. + * + * The Query engine will use indexed-based execution if a user has configured + * any index that can be used to execute query (via `setIndexConfiguration()`). + * Otherwise, the engine will try to optimize the query by re-using a previously + * persisted query result. If that is not possible, the query will be executed + * via a full collection scan. + * + * Index-based execution is the default when available. The query engine + * supports partial indexed execution and merges the result from the index + * lookup with documents that have not yet been indexed. The index evaluation + * matches the backend's format and as such, the SDK can use indexing for all + * queries that the backend supports. + * + * If no index exists, the query engine tries to take advantage of the target + * document mapping in the TargetCache. These mappings exists for all queries + * that have been synced with the backend at least once and allow the query + * engine to only read documents that previously matched a query plus any + * documents that were edited after the query was last listened to. + * + * There are some cases when this optimization is not guaranteed to produce + * the same results as full collection scans. In these cases, query + * processing falls back to full scans. These cases are: + * + * - Limit queries where a document that matched the query previously no longer + * matches the query. + * + * - Limit queries where a document edit may cause the document to sort below + * another document that is in the local cache. + * + * - Queries that have never been CURRENT or free of limbo documents. + */ +class __PRIVATE_QueryEngine { + constructor() { + this.Rs = !1, this.Vs = !1, + /** + * SDK only decides whether it should create index when collection size is + * larger than this. + */ + this.fs = 100, this.gs = + /** + * This cost represents the evaluation result of + * (([index, docKey] + [docKey, docContent]) per document in the result set) + * / ([docKey, docContent] per documents in full collection scan) coming from + * experiment [enter PR experiment URL here]. + */ + function __PRIVATE_getDefaultRelativeIndexReadCostPerDocument() { + // These values were derived from an experiment where several members of the + // Firestore SDK team ran a performance test in various environments. + // Googlers can see b/299284287 for details. + return util.isSafari() ? 8 : __PRIVATE_getAndroidVersion(util.getUA()) > 0 ? 6 : 4; + }(); + } + /** Sets the document view to query against. */ initialize(e, t) { + this.ps = e, this.indexManager = t, this.Rs = !0; + } + /** Returns all local documents matching the specified query. */ getDocumentsMatchingQuery(e, t, n, r) { + // Stores the result from executing the query; using this object is more + // convenient than passing the result between steps of the persistence + // transaction and improves readability comparatively. + const i = { + result: null + }; + return this.ys(e, t).next((e => { + i.result = e; + })).next((() => { + if (!i.result) return this.ws(e, t, r, n).next((e => { + i.result = e; + })); + })).next((() => { + if (i.result) return; + const n = new QueryContext; + return this.Ss(e, t, n).next((r => { + if (i.result = r, this.Vs) return this.bs(e, t, n, r.size); + })); + })).next((() => i.result)); + } + bs(e, t, n, r) { + return n.documentReadCount < this.fs ? (__PRIVATE_getLogLevel() <= logger.LogLevel.DEBUG && __PRIVATE_logDebug("QueryEngine", "SDK will not create cache indexes for query:", __PRIVATE_stringifyQuery(t), "since it only creates cache indexes for collection contains", "more than or equal to", this.fs, "documents"), + PersistencePromise.resolve()) : (__PRIVATE_getLogLevel() <= logger.LogLevel.DEBUG && __PRIVATE_logDebug("QueryEngine", "Query:", __PRIVATE_stringifyQuery(t), "scans", n.documentReadCount, "local documents and returns", r, "documents as results."), + n.documentReadCount > this.gs * r ? (__PRIVATE_getLogLevel() <= logger.LogLevel.DEBUG && __PRIVATE_logDebug("QueryEngine", "The SDK decides to create cache indexes for query:", __PRIVATE_stringifyQuery(t), "as using cache indexes may help improve performance."), + this.indexManager.createTargetIndexes(e, __PRIVATE_queryToTarget(t))) : PersistencePromise.resolve()); + } + /** + * Performs an indexed query that evaluates the query based on a collection's + * persisted index values. Returns `null` if an index is not available. + */ ys(e, t) { + if (__PRIVATE_queryMatchesAllDocuments(t)) + // Queries that match all documents don't benefit from using + // key-based lookups. It is more efficient to scan all documents in a + // collection, rather than to perform individual lookups. + return PersistencePromise.resolve(null); + let n = __PRIVATE_queryToTarget(t); + return this.indexManager.getIndexType(e, n).next((r => 0 /* IndexType.NONE */ === r ? null : (null !== t.limit && 1 /* IndexType.PARTIAL */ === r && ( + // We cannot apply a limit for targets that are served using a partial + // index. If a partial index will be used to serve the target, the + // query may return a superset of documents that match the target + // (e.g. if the index doesn't include all the target's filters), or + // may return the correct set of documents in the wrong order (e.g. if + // the index doesn't include a segment for one of the orderBys). + // Therefore, a limit should not be applied in such cases. + t = __PRIVATE_queryWithLimit(t, null, "F" /* LimitType.First */), n = __PRIVATE_queryToTarget(t)), + this.indexManager.getDocumentsMatchingTarget(e, n).next((r => { + const i = __PRIVATE_documentKeySet(...r); + return this.ps.getDocuments(e, i).next((r => this.indexManager.getMinOffset(e, n).next((n => { + const s = this.Ds(t, r); + return this.Cs(t, s, i, n.readTime) ? this.ys(e, __PRIVATE_queryWithLimit(t, null, "F" /* LimitType.First */)) : this.vs(e, s, t, n); + })))); + }))))); + } + /** + * Performs a query based on the target's persisted query mapping. Returns + * `null` if the mapping is not available or cannot be used. + */ ws(e, t, n, r) { + return __PRIVATE_queryMatchesAllDocuments(t) || r.isEqual(SnapshotVersion.min()) ? PersistencePromise.resolve(null) : this.ps.getDocuments(e, n).next((i => { + const s = this.Ds(t, i); + return this.Cs(t, s, n, r) ? PersistencePromise.resolve(null) : (__PRIVATE_getLogLevel() <= logger.LogLevel.DEBUG && __PRIVATE_logDebug("QueryEngine", "Re-using previous result from %s to execute query: %s", r.toString(), __PRIVATE_stringifyQuery(t)), + this.vs(e, s, t, __PRIVATE_newIndexOffsetSuccessorFromReadTime(r, U)).next((e => e))); + })); + // Queries that have never seen a snapshot without limbo free documents + // should also be run as a full collection scan. + } + /** Applies the query filter and sorting to the provided documents. */ Ds(e, t) { + // Sort the documents and re-apply the query filter since previously + // matching documents do not necessarily still match the query. + let n = new SortedSet(__PRIVATE_newQueryComparator(e)); + return t.forEach(((t, r) => { + __PRIVATE_queryMatches(e, r) && (n = n.add(r)); + })), n; + } + /** + * Determines if a limit query needs to be refilled from cache, making it + * ineligible for index-free execution. + * + * @param query - The query. + * @param sortedPreviousResults - The documents that matched the query when it + * was last synchronized, sorted by the query's comparator. + * @param remoteKeys - The document keys that matched the query at the last + * snapshot. + * @param limboFreeSnapshotVersion - The version of the snapshot when the + * query was last synchronized. + */ Cs(e, t, n, r) { + if (null === e.limit) + // Queries without limits do not need to be refilled. + return !1; + if (n.size !== t.size) + // The query needs to be refilled if a previously matching document no + // longer matches. + return !0; + // Limit queries are not eligible for index-free query execution if there is + // a potential that an older document from cache now sorts before a document + // that was previously part of the limit. This, however, can only happen if + // the document at the edge of the limit goes out of limit. + // If a document that is not the limit boundary sorts differently, + // the boundary of the limit itself did not change and documents from cache + // will continue to be "rejected" by this boundary. Therefore, we can ignore + // any modifications that don't affect the last document. + const i = "F" /* LimitType.First */ === e.limitType ? t.last() : t.first(); + return !!i && (i.hasPendingWrites || i.version.compareTo(r) > 0); + } + Ss(e, t, n) { + return __PRIVATE_getLogLevel() <= logger.LogLevel.DEBUG && __PRIVATE_logDebug("QueryEngine", "Using full collection scan to execute query:", __PRIVATE_stringifyQuery(t)), + this.ps.getDocumentsMatchingQuery(e, t, IndexOffset.min(), n); + } + /** + * Combines the results from an indexed execution with the remaining documents + * that have not yet been indexed. + */ vs(e, t, n, r) { + // Retrieve all results for documents that were updated since the offset. + return this.ps.getDocumentsMatchingQuery(e, n, r).next((e => ( + // Merge with existing results + t.forEach((t => { + e = e.insert(t.key, t); + })), e))); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const Ut = "LocalStore", Kt = 3e8; + +/** + * The maximum time to leave a resume token buffered without writing it out. + * This value is arbitrary: it's long enough to avoid several writes + * (possibly indefinitely if updates come more frequently than this) but + * short enough that restarting after crashing will still have a pretty + * recent resume token. + */ +/** + * Implements `LocalStore` interface. + * + * Note: some field defined in this class might have public access level, but + * the class is not exported so they are only accessible from this module. + * This is useful to implement optional features (like bundles) in free + * functions, such that they are tree-shakeable. + */ +class __PRIVATE_LocalStoreImpl { + constructor( + /** Manages our in-memory or durable persistence. */ + e, t, n, r) { + this.persistence = e, this.Fs = t, this.serializer = r, + /** + * Maps a targetID to data about its target. + * + * PORTING NOTE: We are using an immutable data structure on Web to make re-runs + * of `applyRemoteEvent()` idempotent. + */ + this.Ms = new SortedMap(__PRIVATE_primitiveComparator), + /** Maps a target to its targetID. */ + // TODO(wuandy): Evaluate if TargetId can be part of Target. + this.xs = new ObjectMap((e => __PRIVATE_canonifyTarget(e)), __PRIVATE_targetEquals), + /** + * A per collection group index of the last read time processed by + * `getNewDocumentChanges()`. + * + * PORTING NOTE: This is only used for multi-tab synchronization. + */ + this.Os = new Map, this.Ns = e.getRemoteDocumentCache(), this.Pi = e.getTargetCache(), + this.Ii = e.getBundleCache(), this.Bs(n); + } + Bs(e) { + // TODO(indexing): Add spec tests that test these components change after a + // user change + this.documentOverlayCache = this.persistence.getDocumentOverlayCache(e), this.indexManager = this.persistence.getIndexManager(e), + this.mutationQueue = this.persistence.getMutationQueue(e, this.indexManager), this.localDocuments = new LocalDocumentsView(this.Ns, this.mutationQueue, this.documentOverlayCache, this.indexManager), + this.Ns.setIndexManager(this.indexManager), this.Fs.initialize(this.localDocuments, this.indexManager); + } + collectGarbage(e) { + return this.persistence.runTransaction("Collect garbage", "readwrite-primary", (t => e.collect(t, this.Ms))); + } +} + +function __PRIVATE_newLocalStore( +/** Manages our in-memory or durable persistence. */ +e, t, n, r) { + return new __PRIVATE_LocalStoreImpl(e, t, n, r); +} + +/** + * Tells the LocalStore that the currently authenticated user has changed. + * + * In response the local store switches the mutation queue to the new user and + * returns any resulting document changes. + */ +// PORTING NOTE: Android and iOS only return the documents affected by the +// change. +async function __PRIVATE_localStoreHandleUserChange(e, t) { + const n = __PRIVATE_debugCast(e); + return await n.persistence.runTransaction("Handle user change", "readonly", (e => { + // Swap out the mutation queue, grabbing the pending mutation batches + // before and after. + let r; + return n.mutationQueue.getAllMutationBatches(e).next((i => (r = i, n.Bs(t), n.mutationQueue.getAllMutationBatches(e)))).next((t => { + const i = [], s = []; + // Union the old/new changed keys. + let o = __PRIVATE_documentKeySet(); + for (const e of r) { + i.push(e.batchId); + for (const t of e.mutations) o = o.add(t.key); + } + for (const e of t) { + s.push(e.batchId); + for (const t of e.mutations) o = o.add(t.key); + } + // Return the set of all (potentially) changed documents and the list + // of mutation batch IDs that were affected by change. + return n.localDocuments.getDocuments(e, o).next((e => ({ + Ls: e, + removedBatchIds: i, + addedBatchIds: s + }))); + })); + })); +} + +/* Accepts locally generated Mutations and commit them to storage. */ +/** + * Acknowledges the given batch. + * + * On the happy path when a batch is acknowledged, the local store will + * + * + remove the batch from the mutation queue; + * + apply the changes to the remote document cache; + * + recalculate the latency compensated view implied by those changes (there + * may be mutations in the queue that affect the documents but haven't been + * acknowledged yet); and + * + give the changed documents back the sync engine + * + * @returns The resulting (modified) documents. + */ +function __PRIVATE_localStoreAcknowledgeBatch(e, t) { + const n = __PRIVATE_debugCast(e); + return n.persistence.runTransaction("Acknowledge batch", "readwrite-primary", (e => { + const r = t.batch.keys(), i = n.Ns.newChangeBuffer({ + trackRemovals: !0 + }); + return function __PRIVATE_applyWriteToRemoteDocuments(e, t, n, r) { + const i = n.batch, s = i.keys(); + let o = PersistencePromise.resolve(); + return s.forEach((e => { + o = o.next((() => r.getEntry(t, e))).next((t => { + const s = n.docVersions.get(e); + __PRIVATE_hardAssert(null !== s, 48541), t.version.compareTo(s) < 0 && (i.applyToRemoteDocument(t, n), + t.isValidDocument() && ( + // We use the commitVersion as the readTime rather than the + // document's updateTime since the updateTime is not advanced + // for updates that do not modify the underlying document. + t.setReadTime(n.commitVersion), r.addEntry(t))); + })); + })), o.next((() => e.mutationQueue.removeMutationBatch(t, i))); + } + /** Returns the local view of the documents affected by a mutation batch. */ + // PORTING NOTE: Multi-Tab only. + (n, e, t, i).next((() => i.apply(e))).next((() => n.mutationQueue.performConsistencyCheck(e))).next((() => n.documentOverlayCache.removeOverlaysForBatchId(e, r, t.batch.batchId))).next((() => n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e, function __PRIVATE_getKeysWithTransformResults(e) { + let t = __PRIVATE_documentKeySet(); + for (let n = 0; n < e.mutationResults.length; ++n) { + e.mutationResults[n].transformResults.length > 0 && (t = t.add(e.batch.mutations[n].key)); + } + return t; + } + /** + * Removes mutations from the MutationQueue for the specified batch; + * LocalDocuments will be recalculated. + * + * @returns The resulting modified documents. + */ (t)))).next((() => n.localDocuments.getDocuments(e, r))); + })); +} + +/** + * Returns the last consistent snapshot processed (used by the RemoteStore to + * determine whether to buffer incoming snapshots from the backend). + */ +function __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e) { + const t = __PRIVATE_debugCast(e); + return t.persistence.runTransaction("Get last remote snapshot version", "readonly", (e => t.Pi.getLastRemoteSnapshotVersion(e))); +} + +/** + * Updates the "ground-state" (remote) documents. We assume that the remote + * event reflects any write batches that have been acknowledged or rejected + * (i.e. we do not re-apply local mutations to updates from this event). + * + * LocalDocuments are re-calculated if there are remaining mutations in the + * queue. + */ function __PRIVATE_localStoreApplyRemoteEventToLocalCache(e, t) { + const n = __PRIVATE_debugCast(e), r = t.snapshotVersion; + let i = n.Ms; + return n.persistence.runTransaction("Apply remote event", "readwrite-primary", (e => { + const s = n.Ns.newChangeBuffer({ + trackRemovals: !0 + }); + // Reset newTargetDataByTargetMap in case this transaction gets re-run. + i = n.Ms; + const o = []; + t.targetChanges.forEach(((s, _) => { + const a = i.get(_); + if (!a) return; + // Only update the remote keys if the target is still active. This + // ensures that we can persist the updated target data along with + // the updated assignment. + o.push(n.Pi.removeMatchingKeys(e, s.removedDocuments, _).next((() => n.Pi.addMatchingKeys(e, s.addedDocuments, _)))); + let u = a.withSequenceNumber(e.currentSequenceNumber); + null !== t.targetMismatches.get(_) ? u = u.withResumeToken(ByteString.EMPTY_BYTE_STRING, SnapshotVersion.min()).withLastLimboFreeSnapshotVersion(SnapshotVersion.min()) : s.resumeToken.approximateByteSize() > 0 && (u = u.withResumeToken(s.resumeToken, r)), + i = i.insert(_, u), + // Update the target data if there are target changes (or if + // sufficient time has passed since the last update). + /** + * Returns true if the newTargetData should be persisted during an update of + * an active target. TargetData should always be persisted when a target is + * being released and should not call this function. + * + * While the target is active, TargetData updates can be omitted when nothing + * about the target has changed except metadata like the resume token or + * snapshot version. Occasionally it's worth the extra write to prevent these + * values from getting too stale after a crash, but this doesn't have to be + * too frequent. + */ + function __PRIVATE_shouldPersistTargetData(e, t, n) { + // Always persist target data if we don't already have a resume token. + if (0 === e.resumeToken.approximateByteSize()) return !0; + // Don't allow resume token changes to be buffered indefinitely. This + // allows us to be reasonably up-to-date after a crash and avoids needing + // to loop over all active queries on shutdown. Especially in the browser + // we may not get time to do anything interesting while the current tab is + // closing. + const r = t.snapshotVersion.toMicroseconds() - e.snapshotVersion.toMicroseconds(); + if (r >= Kt) return !0; + // Otherwise if the only thing that has changed about a target is its resume + // token it's not worth persisting. Note that the RemoteStore keeps an + // in-memory view of the currently active targets which includes the current + // resume token, so stream failure or user changes will still use an + // up-to-date resume token regardless of what we do here. + const i = n.addedDocuments.size + n.modifiedDocuments.size + n.removedDocuments.size; + return i > 0; + } + /** + * Notifies local store of the changed views to locally pin documents. + */ (a, u, s) && o.push(n.Pi.updateTargetData(e, u)); + })); + let _ = __PRIVATE_mutableDocumentMap(), a = __PRIVATE_documentKeySet(); + // HACK: The only reason we allow a null snapshot version is so that we + // can synthesize remote events when we get permission denied errors while + // trying to resolve the state of a locally cached document that is in + // limbo. + if (t.documentUpdates.forEach((r => { + t.resolvedLimboDocuments.has(r) && o.push(n.persistence.referenceDelegate.updateLimboDocument(e, r)); + })), + // Each loop iteration only affects its "own" doc, so it's safe to get all + // the remote documents in advance in a single call. + o.push(__PRIVATE_populateDocumentChangeBuffer(e, s, t.documentUpdates).next((e => { + _ = e.ks, a = e.qs; + }))), !r.isEqual(SnapshotVersion.min())) { + const t = n.Pi.getLastRemoteSnapshotVersion(e).next((t => n.Pi.setTargetsMetadata(e, e.currentSequenceNumber, r))); + o.push(t); + } + return PersistencePromise.waitFor(o).next((() => s.apply(e))).next((() => n.localDocuments.getLocalViewOfDocuments(e, _, a))).next((() => _)); + })).then((e => (n.Ms = i, e))); +} + +/** + * Populates document change buffer with documents from backend or a bundle. + * Returns the document changes resulting from applying those documents, and + * also a set of documents whose existence state are changed as a result. + * + * @param txn - Transaction to use to read existing documents from storage. + * @param documentBuffer - Document buffer to collect the resulted changes to be + * applied to storage. + * @param documents - Documents to be applied. + */ function __PRIVATE_populateDocumentChangeBuffer(e, t, n) { + let r = __PRIVATE_documentKeySet(), i = __PRIVATE_documentKeySet(); + return n.forEach((e => r = r.add(e))), t.getEntries(e, r).next((e => { + let r = __PRIVATE_mutableDocumentMap(); + return n.forEach(((n, s) => { + const o = e.get(n); + // Check if see if there is a existence state change for this document. + s.isFoundDocument() !== o.isFoundDocument() && (i = i.add(n)), + // Note: The order of the steps below is important, since we want + // to ensure that rejected limbo resolutions (which fabricate + // NoDocuments with SnapshotVersion.min()) never add documents to + // cache. + s.isNoDocument() && s.version.isEqual(SnapshotVersion.min()) ? ( + // NoDocuments with SnapshotVersion.min() are used in manufactured + // events. We remove these documents from cache since we lost + // access. + t.removeEntry(n, s.readTime), r = r.insert(n, s)) : !o.isValidDocument() || s.version.compareTo(o.version) > 0 || 0 === s.version.compareTo(o.version) && o.hasPendingWrites ? (t.addEntry(s), + r = r.insert(n, s)) : __PRIVATE_logDebug(Ut, "Ignoring outdated watch update for ", n, ". Current version:", o.version, " Watch version:", s.version); + })), { + ks: r, + qs: i + }; + })); +} + +/** + * Gets the mutation batch after the passed in batchId in the mutation queue + * or null if empty. + * @param afterBatchId - If provided, the batch to search after. + * @returns The next mutation or null if there wasn't one. + */ +function __PRIVATE_localStoreGetNextMutationBatch(e, t) { + const n = __PRIVATE_debugCast(e); + return n.persistence.runTransaction("Get next mutation batch", "readonly", (e => (void 0 === t && (t = j), + n.mutationQueue.getNextMutationBatchAfterBatchId(e, t)))); +} + +/** + * Reads the current value of a Document with a given key or null if not + * found - used for testing. + */ +/** + * Assigns the given target an internal ID so that its results can be pinned so + * they don't get GC'd. A target must be allocated in the local store before + * the store can be used to manage its view. + * + * Allocating an already allocated `Target` will return the existing `TargetData` + * for that `Target`. + */ +function __PRIVATE_localStoreAllocateTarget(e, t) { + const n = __PRIVATE_debugCast(e); + return n.persistence.runTransaction("Allocate target", "readwrite", (e => { + let r; + return n.Pi.getTargetData(e, t).next((i => i ? ( + // This target has been listened to previously, so reuse the + // previous targetID. + // TODO(mcg): freshen last accessed date? + r = i, PersistencePromise.resolve(r)) : n.Pi.allocateTargetId(e).next((i => (r = new TargetData(t, i, "TargetPurposeListen" /* TargetPurpose.Listen */ , e.currentSequenceNumber), + n.Pi.addTargetData(e, r).next((() => r))))))); + })).then((e => { + // If Multi-Tab is enabled, the existing target data may be newer than + // the in-memory data + const r = n.Ms.get(e.targetId); + return (null === r || e.snapshotVersion.compareTo(r.snapshotVersion) > 0) && (n.Ms = n.Ms.insert(e.targetId, e), + n.xs.set(t, e.targetId)), e; + })); +} + +/** + * Returns the TargetData as seen by the LocalStore, including updates that may + * have not yet been persisted to the TargetCache. + */ +// Visible for testing. +/** + * Unpins all the documents associated with the given target. If + * `keepPersistedTargetData` is set to false and Eager GC enabled, the method + * directly removes the associated target data from the target cache. + * + * Releasing a non-existing `Target` is a no-op. + */ +// PORTING NOTE: `keepPersistedTargetData` is multi-tab only. +async function __PRIVATE_localStoreReleaseTarget(e, t, n) { + const r = __PRIVATE_debugCast(e), i = r.Ms.get(t), s = n ? "readwrite" : "readwrite-primary"; + try { + n || await r.persistence.runTransaction("Release target", s, (e => r.persistence.referenceDelegate.removeTarget(e, i))); + } catch (e) { + if (!__PRIVATE_isIndexedDbTransactionError(e)) throw e; + // All `releaseTarget` does is record the final metadata state for the + // target, but we've been recording this periodically during target + // activity. If we lose this write this could cause a very slight + // difference in the order of target deletion during GC, but we + // don't define exact LRU semantics so this is acceptable. + __PRIVATE_logDebug(Ut, `Failed to update sequence numbers for target ${t}: ${e}`); + } + r.Ms = r.Ms.remove(t), r.xs.delete(i.target); +} + +/** + * Runs the specified query against the local store and returns the results, + * potentially taking advantage of query data from previous executions (such + * as the set of remote keys). + * + * @param usePreviousResults - Whether results from previous executions can + * be used to optimize this query execution. + */ function __PRIVATE_localStoreExecuteQuery(e, t, n) { + const r = __PRIVATE_debugCast(e); + let i = SnapshotVersion.min(), s = __PRIVATE_documentKeySet(); + return r.persistence.runTransaction("Execute query", "readwrite", (// Use readwrite instead of readonly so indexes can be created + // Use readwrite instead of readonly so indexes can be created + e => function __PRIVATE_localStoreGetTargetData(e, t, n) { + const r = __PRIVATE_debugCast(e), i = r.xs.get(n); + return void 0 !== i ? PersistencePromise.resolve(r.Ms.get(i)) : r.Pi.getTargetData(t, n); + }(r, e, __PRIVATE_queryToTarget(t)).next((t => { + if (t) return i = t.lastLimboFreeSnapshotVersion, r.Pi.getMatchingKeysForTargetId(e, t.targetId).next((e => { + s = e; + })); + })).next((() => r.Fs.getDocumentsMatchingQuery(e, t, n ? i : SnapshotVersion.min(), n ? s : __PRIVATE_documentKeySet()))).next((e => (__PRIVATE_setMaxReadTime(r, __PRIVATE_queryCollectionGroup(t), e), + { + documents: e, + Qs: s + }))))); +} + +// PORTING NOTE: Multi-Tab only. +function __PRIVATE_localStoreGetCachedTarget(e, t) { + const n = __PRIVATE_debugCast(e), r = __PRIVATE_debugCast(n.Pi), i = n.Ms.get(t); + return i ? Promise.resolve(i.target) : n.persistence.runTransaction("Get target data", "readonly", (e => r.At(e, t).next((e => e ? e.target : null)))); +} + +/** + * Returns the set of documents that have been updated since the last call. + * If this is the first call, returns the set of changes since client + * initialization. Further invocations will return document that have changed + * since the prior call. + */ +// PORTING NOTE: Multi-Tab only. +function __PRIVATE_localStoreGetNewDocumentChanges(e, t) { + const n = __PRIVATE_debugCast(e), r = n.Os.get(t) || SnapshotVersion.min(); + // Get the current maximum read time for the collection. This should always + // exist, but to reduce the chance for regressions we default to + // SnapshotVersion.Min() + // TODO(indexing): Consider removing the default value. + return n.persistence.runTransaction("Get new document changes", "readonly", (e => n.Ns.getAllFromCollectionGroup(e, t, __PRIVATE_newIndexOffsetSuccessorFromReadTime(r, U), + /* limit= */ Number.MAX_SAFE_INTEGER))).then((e => (__PRIVATE_setMaxReadTime(n, t, e), + e))); +} + +/** Sets the collection group's maximum read time from the given documents. */ +// PORTING NOTE: Multi-Tab only. +function __PRIVATE_setMaxReadTime(e, t, n) { + let r = e.Os.get(t) || SnapshotVersion.min(); + n.forEach(((e, t) => { + t.readTime.compareTo(r) > 0 && (r = t.readTime); + })), e.Os.set(t, r); +} + +/** + * Creates a new target using the given bundle name, which will be used to + * hold the keys of all documents from the bundle in query-document mappings. + * This ensures that the loaded documents do not get garbage collected + * right away. + */ +/** + * Applies the documents from a bundle to the "ground-state" (remote) + * documents. + * + * LocalDocuments are re-calculated if there are remaining mutations in the + * queue. + */ +async function __PRIVATE_localStoreApplyBundledDocuments(e, t, n, r) { + const i = __PRIVATE_debugCast(e); + let s = __PRIVATE_documentKeySet(), o = __PRIVATE_mutableDocumentMap(); + for (const e of n) { + const n = t.$s(e.metadata.name); + e.document && (s = s.add(n)); + const r = t.Us(e); + r.setReadTime(t.Ks(e.metadata.readTime)), o = o.insert(n, r); + } + const _ = i.Ns.newChangeBuffer({ + trackRemovals: !0 + }), a = await __PRIVATE_localStoreAllocateTarget(i, function __PRIVATE_umbrellaTarget(e) { + // It is OK that the path used for the query is not valid, because this will + // not be read and queried. + return __PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(ResourcePath.fromString(`__bundle__/docs/${e}`))); + }(r)); + // Allocates a target to hold all document keys from the bundle, such that + // they will not get garbage collected right away. + return i.persistence.runTransaction("Apply bundle documents", "readwrite", (e => __PRIVATE_populateDocumentChangeBuffer(e, _, o).next((t => (_.apply(e), + t))).next((t => i.Pi.removeMatchingKeysForTargetId(e, a.targetId).next((() => i.Pi.addMatchingKeys(e, s, a.targetId))).next((() => i.localDocuments.getLocalViewOfDocuments(e, t.ks, t.qs))).next((() => t.ks)))))); +} + +/** + * Returns a promise of a boolean to indicate if the given bundle has already + * been loaded and the create time is newer than the current loading bundle. + */ +/** + * Saves the given `NamedQuery` to local persistence. + */ +async function __PRIVATE_localStoreSaveNamedQuery(e, t, n = __PRIVATE_documentKeySet()) { + // Allocate a target for the named query such that it can be resumed + // from associated read time if users use it to listen. + // NOTE: this also means if no corresponding target exists, the new target + // will remain active and will not get collected, unless users happen to + // unlisten the query somehow. + const r = await __PRIVATE_localStoreAllocateTarget(e, __PRIVATE_queryToTarget(__PRIVATE_fromBundledQuery(t.bundledQuery))), i = __PRIVATE_debugCast(e); + return i.persistence.runTransaction("Save named query", "readwrite", (e => { + const s = __PRIVATE_fromVersion(t.readTime); + // Simply save the query itself if it is older than what the SDK already + // has. + if (r.snapshotVersion.compareTo(s) >= 0) return i.Ii.saveNamedQuery(e, t); + // Update existing target data because the query from the bundle is newer. + const o = r.withResumeToken(ByteString.EMPTY_BYTE_STRING, s); + return i.Ms = i.Ms.insert(o.targetId, o), i.Pi.updateTargetData(e, o).next((() => i.Pi.removeMatchingKeysForTargetId(e, r.targetId))).next((() => i.Pi.addMatchingKeys(e, n, r.targetId))).next((() => i.Ii.saveNamedQuery(e, t))); + })); +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// The format of the LocalStorage key that stores the client state is: +// firestore_clients__ +const Wt = "firestore_clients"; + +/** Assembles the key for a client state in WebStorage */ function createWebStorageClientStateKey(e, t) { + return `${Wt}_${e}_${t}`; +} + +// The format of the WebStorage key that stores the mutation state is: +// firestore_mutations__ +// (for unauthenticated users) +// or: firestore_mutations___ + +// 'user_uid' is last to avoid needing to escape '_' characters that it might +// contain. +const Gt = "firestore_mutations"; + +/** Assembles the key for a mutation batch in WebStorage */ function createWebStorageMutationBatchKey(e, t, n) { + let r = `${Gt}_${e}_${n}`; + return t.isAuthenticated() && (r += `_${t.uid}`), r; +} + +// The format of the WebStorage key that stores a query target's metadata is: +// firestore_targets__ +const zt = "firestore_targets"; + +/** Assembles the key for a query state in WebStorage */ function createWebStorageQueryTargetMetadataKey(e, t) { + return `${zt}_${e}_${t}`; +} + +// The WebStorage prefix that stores the primary tab's online state. The +// format of the key is: +// firestore_online_state_ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const jt = "SharedClientState"; + +/** + * Holds the state of a mutation batch, including its user ID, batch ID and + * whether the batch is 'pending', 'acknowledged' or 'rejected'. + */ +// Visible for testing +class __PRIVATE_MutationMetadata { + constructor(e, t, n, r) { + this.user = e, this.batchId = t, this.state = n, this.error = r; + } + /** + * Parses a MutationMetadata from its JSON representation in WebStorage. + * Logs a warning and returns null if the format of the data is not valid. + */ static Ws(e, t, n) { + const r = JSON.parse(n); + let i, s = "object" == typeof r && -1 !== [ "pending", "acknowledged", "rejected" ].indexOf(r.state) && (void 0 === r.error || "object" == typeof r.error); + return s && r.error && (s = "string" == typeof r.error.message && "string" == typeof r.error.code, + s && (i = new FirestoreError(r.error.code, r.error.message))), s ? new __PRIVATE_MutationMetadata(e, t, r.state, i) : (__PRIVATE_logError(jt, `Failed to parse mutation state for ID '${t}': ${n}`), + null); + } + Gs() { + const e = { + state: this.state, + updateTimeMs: Date.now() + }; + return this.error && (e.error = { + code: this.error.code, + message: this.error.message + }), JSON.stringify(e); + } +} + +/** + * Holds the state of a query target, including its target ID and whether the + * target is 'not-current', 'current' or 'rejected'. + */ +// Visible for testing +class __PRIVATE_QueryTargetMetadata { + constructor(e, t, n) { + this.targetId = e, this.state = t, this.error = n; + } + /** + * Parses a QueryTargetMetadata from its JSON representation in WebStorage. + * Logs a warning and returns null if the format of the data is not valid. + */ static Ws(e, t) { + const n = JSON.parse(t); + let r, i = "object" == typeof n && -1 !== [ "not-current", "current", "rejected" ].indexOf(n.state) && (void 0 === n.error || "object" == typeof n.error); + return i && n.error && (i = "string" == typeof n.error.message && "string" == typeof n.error.code, + i && (r = new FirestoreError(n.error.code, n.error.message))), i ? new __PRIVATE_QueryTargetMetadata(e, n.state, r) : (__PRIVATE_logError(jt, `Failed to parse target state for ID '${e}': ${t}`), + null); + } + Gs() { + const e = { + state: this.state, + updateTimeMs: Date.now() + }; + return this.error && (e.error = { + code: this.error.code, + message: this.error.message + }), JSON.stringify(e); + } +} + +/** + * This class represents the immutable ClientState for a client read from + * WebStorage, containing the list of active query targets. + */ class __PRIVATE_RemoteClientState { + constructor(e, t) { + this.clientId = e, this.activeTargetIds = t; + } + /** + * Parses a RemoteClientState from the JSON representation in WebStorage. + * Logs a warning and returns null if the format of the data is not valid. + */ static Ws(e, t) { + const n = JSON.parse(t); + let r = "object" == typeof n && n.activeTargetIds instanceof Array, i = __PRIVATE_targetIdSet(); + for (let e = 0; r && e < n.activeTargetIds.length; ++e) r = isSafeInteger(n.activeTargetIds[e]), + i = i.add(n.activeTargetIds[e]); + return r ? new __PRIVATE_RemoteClientState(e, i) : (__PRIVATE_logError(jt, `Failed to parse client data for instance '${e}': ${t}`), + null); + } +} + +/** + * This class represents the online state for all clients participating in + * multi-tab. The online state is only written to by the primary client, and + * used in secondary clients to update their query views. + */ class __PRIVATE_SharedOnlineState { + constructor(e, t) { + this.clientId = e, this.onlineState = t; + } + /** + * Parses a SharedOnlineState from its JSON representation in WebStorage. + * Logs a warning and returns null if the format of the data is not valid. + */ static Ws(e) { + const t = JSON.parse(e); + return "object" == typeof t && -1 !== [ "Unknown", "Online", "Offline" ].indexOf(t.onlineState) && "string" == typeof t.clientId ? new __PRIVATE_SharedOnlineState(t.clientId, t.onlineState) : (__PRIVATE_logError(jt, `Failed to parse online state: ${e}`), + null); + } +} + +/** + * Metadata state of the local client. Unlike `RemoteClientState`, this class is + * mutable and keeps track of all pending mutations, which allows us to + * update the range of pending mutation batch IDs as new mutations are added or + * removed. + * + * The data in `LocalClientState` is not read from WebStorage and instead + * updated via its instance methods. The updated state can be serialized via + * `toWebStorageJSON()`. + */ +// Visible for testing. +class __PRIVATE_LocalClientState { + constructor() { + this.activeTargetIds = __PRIVATE_targetIdSet(); + } + zs(e) { + this.activeTargetIds = this.activeTargetIds.add(e); + } + js(e) { + this.activeTargetIds = this.activeTargetIds.delete(e); + } + /** + * Converts this entry into a JSON-encoded format we can use for WebStorage. + * Does not encode `clientId` as it is part of the key in WebStorage. + */ Gs() { + const e = { + activeTargetIds: this.activeTargetIds.toArray(), + updateTimeMs: Date.now() + }; + return JSON.stringify(e); + } +} + +/** + * `WebStorageSharedClientState` uses WebStorage (window.localStorage) as the + * backing store for the SharedClientState. It keeps track of all active + * clients and supports modifications of the local client's data. + */ class __PRIVATE_WebStorageSharedClientState { + constructor(e, t, n, r, i) { + this.window = e, this.Mi = t, this.persistenceKey = n, this.Js = r, this.syncEngine = null, + this.onlineStateHandler = null, this.sequenceNumberHandler = null, this.Hs = this.Ys.bind(this), + this.Zs = new SortedMap(__PRIVATE_primitiveComparator), this.started = !1, + /** + * Captures WebStorage events that occur before `start()` is called. These + * events are replayed once `WebStorageSharedClientState` is started. + */ + this.Xs = []; + // Escape the special characters mentioned here: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions + const s = n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + this.storage = this.window.localStorage, this.currentUser = i, this.eo = createWebStorageClientStateKey(this.persistenceKey, this.Js), + this.no = + /** Assembles the key for the current sequence number. */ + function createWebStorageSequenceNumberKey(e) { + return `firestore_sequence_number_${e}`; + }(this.persistenceKey), this.Zs = this.Zs.insert(this.Js, new __PRIVATE_LocalClientState), + this.ro = new RegExp(`^${Wt}_${s}_([^_]*)$`), this.io = new RegExp(`^${Gt}_${s}_(\\d+)(?:_(.*))?$`), + this.so = new RegExp(`^${zt}_${s}_(\\d+)$`), this.oo = + /** Assembles the key for the online state of the primary tab. */ + function createWebStorageOnlineStateKey(e) { + return `firestore_online_state_${e}`; + } + // The WebStorage prefix that plays as a event to indicate the remote documents + // might have changed due to some secondary tabs loading a bundle. + // format of the key is: + // firestore_bundle_loaded_v2_ + // The version ending with "v2" stores the list of modified collection groups. + (this.persistenceKey), this._o = function createBundleLoadedKey(e) { + return `firestore_bundle_loaded_v2_${e}`; + } + // The WebStorage key prefix for the key that stores the last sequence number allocated. The key + // looks like 'firestore_sequence_number_'. + (this.persistenceKey), + // Rather than adding the storage observer during start(), we add the + // storage observer during initialization. This ensures that we collect + // events before other components populate their initial state (during their + // respective start() calls). Otherwise, we might for example miss a + // mutation that is added after LocalStore's start() processed the existing + // mutations but before we observe WebStorage events. + this.window.addEventListener("storage", this.Hs); + } + /** Returns 'true' if WebStorage is available in the current environment. */ static v(e) { + return !(!e || !e.localStorage); + } + async start() { + // Retrieve the list of existing clients to backfill the data in + // SharedClientState. + const e = await this.syncEngine.Ts(); + for (const t of e) { + if (t === this.Js) continue; + const e = this.getItem(createWebStorageClientStateKey(this.persistenceKey, t)); + if (e) { + const n = __PRIVATE_RemoteClientState.Ws(t, e); + n && (this.Zs = this.Zs.insert(n.clientId, n)); + } + } + this.ao(); + // Check if there is an existing online state and call the callback handler + // if applicable. + const t = this.storage.getItem(this.oo); + if (t) { + const e = this.uo(t); + e && this.co(e); + } + for (const e of this.Xs) this.Ys(e); + this.Xs = [], + // Register a window unload hook to remove the client metadata entry from + // WebStorage even if `shutdown()` was not called. + this.window.addEventListener("pagehide", (() => this.shutdown())), this.started = !0; + } + writeSequenceNumber(e) { + this.setItem(this.no, JSON.stringify(e)); + } + getAllActiveQueryTargets() { + return this.lo(this.Zs); + } + isActiveQueryTarget(e) { + let t = !1; + return this.Zs.forEach(((n, r) => { + r.activeTargetIds.has(e) && (t = !0); + })), t; + } + addPendingMutation(e) { + this.ho(e, "pending"); + } + updateMutationState(e, t, n) { + this.ho(e, t, n), + // Once a final mutation result is observed by other clients, they no longer + // access the mutation's metadata entry. Since WebStorage replays events + // in order, it is safe to delete the entry right after updating it. + this.Po(e); + } + addLocalQueryTarget(e, t = !0) { + let n = "not-current"; + // Lookup an existing query state if the target ID was already registered + // by another tab + if (this.isActiveQueryTarget(e)) { + const t = this.storage.getItem(createWebStorageQueryTargetMetadataKey(this.persistenceKey, e)); + if (t) { + const r = __PRIVATE_QueryTargetMetadata.Ws(e, t); + r && (n = r.state); + } + } + // If the query is listening to cache only, the target ID should not be registered with the + // local Firestore client as an active watch target. + return t && this.To.zs(e), this.ao(), n; + } + removeLocalQueryTarget(e) { + this.To.js(e), this.ao(); + } + isLocalQueryTarget(e) { + return this.To.activeTargetIds.has(e); + } + clearQueryState(e) { + this.removeItem(createWebStorageQueryTargetMetadataKey(this.persistenceKey, e)); + } + updateQueryState(e, t, n) { + this.Io(e, t, n); + } + handleUserChange(e, t, n) { + t.forEach((e => { + this.Po(e); + })), this.currentUser = e, n.forEach((e => { + this.addPendingMutation(e); + })); + } + setOnlineState(e) { + this.Eo(e); + } + notifyBundleLoaded(e) { + this.Ao(e); + } + shutdown() { + this.started && (this.window.removeEventListener("storage", this.Hs), this.removeItem(this.eo), + this.started = !1); + } + getItem(e) { + const t = this.storage.getItem(e); + return __PRIVATE_logDebug(jt, "READ", e, t), t; + } + setItem(e, t) { + __PRIVATE_logDebug(jt, "SET", e, t), this.storage.setItem(e, t); + } + removeItem(e) { + __PRIVATE_logDebug(jt, "REMOVE", e), this.storage.removeItem(e); + } + Ys(e) { + // Note: The function is typed to take Event to be interface-compatible with + // `Window.addEventListener`. + const t = e; + if (t.storageArea === this.storage) { + if (__PRIVATE_logDebug(jt, "EVENT", t.key, t.newValue), t.key === this.eo) return void __PRIVATE_logError("Received WebStorage notification for local change. Another client might have garbage-collected our state"); + this.Mi.enqueueRetryable((async () => { + if (this.started) { + if (null !== t.key) if (this.ro.test(t.key)) { + if (null == t.newValue) { + const e = this.Ro(t.key); + return this.Vo(e, null); + } + { + const e = this.mo(t.key, t.newValue); + if (e) return this.Vo(e.clientId, e); + } + } else if (this.io.test(t.key)) { + if (null !== t.newValue) { + const e = this.fo(t.key, t.newValue); + if (e) return this.po(e); + } + } else if (this.so.test(t.key)) { + if (null !== t.newValue) { + const e = this.yo(t.key, t.newValue); + if (e) return this.wo(e); + } + } else if (t.key === this.oo) { + if (null !== t.newValue) { + const e = this.uo(t.newValue); + if (e) return this.co(e); + } + } else if (t.key === this.no) { + const e = function __PRIVATE_fromWebStorageSequenceNumber(e) { + let t = __PRIVATE_ListenSequence.ce; + if (null != e) try { + const n = JSON.parse(e); + __PRIVATE_hardAssert("number" == typeof n, 30636, { + So: e + }), t = n; + } catch (e) { + __PRIVATE_logError(jt, "Failed to read sequence number from WebStorage", e); + } + return t; + } + /** + * `MemorySharedClientState` is a simple implementation of SharedClientState for + * clients using memory persistence. The state in this class remains fully + * isolated and no synchronization is performed. + */ (t.newValue); + e !== __PRIVATE_ListenSequence.ce && this.sequenceNumberHandler(e); + } else if (t.key === this._o) { + const e = this.bo(t.newValue); + await Promise.all(e.map((e => this.syncEngine.Do(e)))); + } + } else this.Xs.push(t); + })); + } + } + get To() { + return this.Zs.get(this.Js); + } + ao() { + this.setItem(this.eo, this.To.Gs()); + } + ho(e, t, n) { + const r = new __PRIVATE_MutationMetadata(this.currentUser, e, t, n), i = createWebStorageMutationBatchKey(this.persistenceKey, this.currentUser, e); + this.setItem(i, r.Gs()); + } + Po(e) { + const t = createWebStorageMutationBatchKey(this.persistenceKey, this.currentUser, e); + this.removeItem(t); + } + Eo(e) { + const t = { + clientId: this.Js, + onlineState: e + }; + this.storage.setItem(this.oo, JSON.stringify(t)); + } + Io(e, t, n) { + const r = createWebStorageQueryTargetMetadataKey(this.persistenceKey, e), i = new __PRIVATE_QueryTargetMetadata(e, t, n); + this.setItem(r, i.Gs()); + } + Ao(e) { + const t = JSON.stringify(Array.from(e)); + this.setItem(this._o, t); + } + /** + * Parses a client state key in WebStorage. Returns null if the key does not + * match the expected key format. + */ Ro(e) { + const t = this.ro.exec(e); + return t ? t[1] : null; + } + /** + * Parses a client state in WebStorage. Returns 'null' if the value could not + * be parsed. + */ mo(e, t) { + const n = this.Ro(e); + return __PRIVATE_RemoteClientState.Ws(n, t); + } + /** + * Parses a mutation batch state in WebStorage. Returns 'null' if the value + * could not be parsed. + */ fo(e, t) { + const n = this.io.exec(e), r = Number(n[1]), i = void 0 !== n[2] ? n[2] : null; + return __PRIVATE_MutationMetadata.Ws(new User(i), r, t); + } + /** + * Parses a query target state from WebStorage. Returns 'null' if the value + * could not be parsed. + */ yo(e, t) { + const n = this.so.exec(e), r = Number(n[1]); + return __PRIVATE_QueryTargetMetadata.Ws(r, t); + } + /** + * Parses an online state from WebStorage. Returns 'null' if the value + * could not be parsed. + */ uo(e) { + return __PRIVATE_SharedOnlineState.Ws(e); + } + bo(e) { + return JSON.parse(e); + } + async po(e) { + if (e.user.uid === this.currentUser.uid) return this.syncEngine.Co(e.batchId, e.state, e.error); + __PRIVATE_logDebug(jt, `Ignoring mutation for non-active user ${e.user.uid}`); + } + wo(e) { + return this.syncEngine.vo(e.targetId, e.state, e.error); + } + Vo(e, t) { + const n = t ? this.Zs.insert(e, t) : this.Zs.remove(e), r = this.lo(this.Zs), i = this.lo(n), s = [], o = []; + return i.forEach((e => { + r.has(e) || s.push(e); + })), r.forEach((e => { + i.has(e) || o.push(e); + })), this.syncEngine.Fo(s, o).then((() => { + this.Zs = n; + })); + } + co(e) { + // We check whether the client that wrote this online state is still active + // by comparing its client ID to the list of clients kept active in + // IndexedDb. If a client does not update their IndexedDb client state + // within 5 seconds, it is considered inactive and we don't emit an online + // state event. + this.Zs.get(e.clientId) && this.onlineStateHandler(e.onlineState); + } + lo(e) { + let t = __PRIVATE_targetIdSet(); + return e.forEach(((e, n) => { + t = t.unionWith(n.activeTargetIds); + })), t; + } +} + +class __PRIVATE_MemorySharedClientState { + constructor() { + this.Mo = new __PRIVATE_LocalClientState, this.xo = {}, this.onlineStateHandler = null, + this.sequenceNumberHandler = null; + } + addPendingMutation(e) { + // No op. + } + updateMutationState(e, t, n) { + // No op. + } + addLocalQueryTarget(e, t = !0) { + return t && this.Mo.zs(e), this.xo[e] || "not-current"; + } + updateQueryState(e, t, n) { + this.xo[e] = t; + } + removeLocalQueryTarget(e) { + this.Mo.js(e); + } + isLocalQueryTarget(e) { + return this.Mo.activeTargetIds.has(e); + } + clearQueryState(e) { + delete this.xo[e]; + } + getAllActiveQueryTargets() { + return this.Mo.activeTargetIds; + } + isActiveQueryTarget(e) { + return this.Mo.activeTargetIds.has(e); + } + start() { + return this.Mo = new __PRIVATE_LocalClientState, Promise.resolve(); + } + handleUserChange(e, t, n) { + // No op. + } + setOnlineState(e) { + // No op. + } + shutdown() {} + writeSequenceNumber(e) {} + notifyBundleLoaded(e) { + // No op. + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_NoopConnectivityMonitor { + Oo(e) { + // No-op. + } + shutdown() { + // No-op. + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// References to `window` are guarded by BrowserConnectivityMonitor.isAvailable() +/* eslint-disable no-restricted-globals */ const Jt = "ConnectivityMonitor"; + +/** + * Browser implementation of ConnectivityMonitor. + */ class __PRIVATE_BrowserConnectivityMonitor { + constructor() { + this.No = () => this.Bo(), this.Lo = () => this.ko(), this.qo = [], this.Qo(); + } + Oo(e) { + this.qo.push(e); + } + shutdown() { + window.removeEventListener("online", this.No), window.removeEventListener("offline", this.Lo); + } + Qo() { + window.addEventListener("online", this.No), window.addEventListener("offline", this.Lo); + } + Bo() { + __PRIVATE_logDebug(Jt, "Network connectivity changed: AVAILABLE"); + for (const e of this.qo) e(0 /* NetworkStatus.AVAILABLE */); + } + ko() { + __PRIVATE_logDebug(Jt, "Network connectivity changed: UNAVAILABLE"); + for (const e of this.qo) e(1 /* NetworkStatus.UNAVAILABLE */); + } + // TODO(chenbrian): Consider passing in window either into this component or + // here for testing via FakeWindow. + /** Checks that all used attributes of window are available. */ + static v() { + return "undefined" != typeof window && void 0 !== window.addEventListener && void 0 !== window.removeEventListener; + } +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The value returned from the most recent invocation of + * `generateUniqueDebugId()`, or null if it has never been invoked. + */ let Ht = null; + +/** + * Generates and returns an initial value for `lastUniqueDebugId`. + * + * The returned value is randomly selected from a range of integers that are + * represented as 8 hexadecimal digits. This means that (within reason) any + * numbers generated by incrementing the returned number by 1 will also be + * represented by 8 hexadecimal digits. This leads to all "IDs" having the same + * length when converted to a hexadecimal string, making reading logs containing + * these IDs easier to follow. And since the return value is randomly selected + * it will help to differentiate between logs from different executions. + */ +/** + * Generates and returns a unique ID as a hexadecimal string. + * + * The returned ID is intended to be used in debug logging messages to help + * correlate log messages that may be spatially separated in the logs, but + * logically related. For example, a network connection could include the same + * "debug ID" string in all of its log messages to help trace a specific + * connection over time. + * + * @return the 10-character generated ID (e.g. "0xa1b2c3d4"). + */ +function __PRIVATE_generateUniqueDebugId() { + return null === Ht ? Ht = function __PRIVATE_generateInitialUniqueDebugId() { + return 268435456 + Math.round(2147483648 * Math.random()); + }() : Ht++, "0x" + Ht.toString(16); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const Yt = "RestConnection", Zt = { + BatchGetDocuments: "batchGet", + Commit: "commit", + RunQuery: "runQuery", + RunAggregationQuery: "runAggregationQuery" +}; + +/** + * Maps RPC names to the corresponding REST endpoint name. + * + * We use array notation to avoid mangling. + */ +/** + * Base class for all Rest-based connections to the backend (WebChannel and + * HTTP). + */ +class __PRIVATE_RestConnection { + get $o() { + // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine + // where to run the query, and expect the `request` to NOT specify the "path". + return !1; + } + constructor(e) { + this.databaseInfo = e, this.databaseId = e.databaseId; + const t = e.ssl ? "https" : "http", n = encodeURIComponent(this.databaseId.projectId), r = encodeURIComponent(this.databaseId.database); + this.Uo = t + "://" + e.host, this.Ko = `projects/${n}/databases/${r}`, this.Wo = this.databaseId.database === lt ? `project_id=${n}` : `project_id=${n}&database_id=${r}`; + } + Go(e, t, n, r, i) { + const s = __PRIVATE_generateUniqueDebugId(), o = this.zo(e, t.toUriEncodedString()); + __PRIVATE_logDebug(Yt, `Sending RPC '${e}' ${s}:`, o, n); + const _ = { + "google-cloud-resource-prefix": this.Ko, + "x-goog-request-params": this.Wo + }; + this.jo(_, r, i); + const {host: a} = new URL(o), u = util.isCloudWorkstation(a); + return this.Jo(e, o, _, n, u).then((t => (__PRIVATE_logDebug(Yt, `Received RPC '${e}' ${s}: `, t), + t)), (t => { + throw __PRIVATE_logWarn(Yt, `RPC '${e}' ${s} failed with error: `, t, "url: ", o, "request:", n), + t; + })); + } + Ho(e, t, n, r, i, s) { + // The REST API automatically aggregates all of the streamed results, so we + // can just use the normal invoke() method. + return this.Go(e, t, n, r, i); + } + /** + * Modifies the headers for a request, adding any authorization token if + * present and any additional headers for the request. + */ jo(e, t, n) { + e["X-Goog-Api-Client"] = + // SDK_VERSION is updated to different value at runtime depending on the entry point, + // so we need to get its value when we need it in a function. + function __PRIVATE_getGoogApiClientValue() { + return "gl-js/ fire/" + x; + }(), + // Content-Type: text/plain will avoid preflight requests which might + // mess with CORS and redirects by proxies. If we add custom headers + // we will need to change this code to potentially use the $httpOverwrite + // parameter supported by ESF to avoid triggering preflight requests. + e["Content-Type"] = "text/plain", this.databaseInfo.appId && (e["X-Firebase-GMPID"] = this.databaseInfo.appId), + t && t.headers.forEach(((t, n) => e[n] = t)), n && n.headers.forEach(((t, n) => e[n] = t)); + } + zo(e, t) { + const n = Zt[e]; + return `${this.Uo}/v1/${t}:${n}`; + } + /** + * Closes and cleans up any resources associated with the connection. This + * implementation is a no-op because there are no resources associated + * with the RestConnection that need to be cleaned up. + */ terminate() { + // No-op + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provides a simple helper class that implements the Stream interface to + * bridge to other implementations that are streams but do not implement the + * interface. The stream callbacks are invoked with the callOn... methods. + */ class __PRIVATE_StreamBridge { + constructor(e) { + this.Yo = e.Yo, this.Zo = e.Zo; + } + Xo(e) { + this.e_ = e; + } + t_(e) { + this.n_ = e; + } + r_(e) { + this.i_ = e; + } + onMessage(e) { + this.s_ = e; + } + close() { + this.Zo(); + } + send(e) { + this.Yo(e); + } + o_() { + this.e_(); + } + __() { + this.n_(); + } + a_(e) { + this.i_(e); + } + u_(e) { + this.s_(e); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const Xt = "WebChannelConnection"; + +class __PRIVATE_WebChannelConnection extends __PRIVATE_RestConnection { + constructor(e) { + super(e), + /** A collection of open WebChannel instances */ + this.c_ = [], this.forceLongPolling = e.forceLongPolling, this.autoDetectLongPolling = e.autoDetectLongPolling, + this.useFetchStreams = e.useFetchStreams, this.longPollingOptions = e.longPollingOptions; + } + Jo(e, t, n, r, i) { + const s = __PRIVATE_generateUniqueDebugId(); + return new Promise(((i, o) => { + const _ = new webchannelBlob.XhrIo; + _.setWithCredentials(!0), _.listenOnce(webchannelBlob.EventType.COMPLETE, (() => { + try { + switch (_.getLastErrorCode()) { + case webchannelBlob.ErrorCode.NO_ERROR: + const t = _.getResponseJson(); + __PRIVATE_logDebug(Xt, `XHR for RPC '${e}' ${s} received:`, JSON.stringify(t)), + i(t); + break; + + case webchannelBlob.ErrorCode.TIMEOUT: + __PRIVATE_logDebug(Xt, `RPC '${e}' ${s} timed out`), o(new FirestoreError(N.DEADLINE_EXCEEDED, "Request time out")); + break; + + case webchannelBlob.ErrorCode.HTTP_ERROR: + const n = _.getStatus(); + if (__PRIVATE_logDebug(Xt, `RPC '${e}' ${s} failed with status:`, n, "response text:", _.getResponseText()), + n > 0) { + let e = _.getResponseJson(); + Array.isArray(e) && (e = e[0]); + const t = e?.error; + if (t && t.status && t.message) { + const e = function __PRIVATE_mapCodeFromHttpResponseErrorStatus(e) { + const t = e.toLowerCase().replace(/_/g, "-"); + return Object.values(N).indexOf(t) >= 0 ? t : N.UNKNOWN; + }(t.status); + o(new FirestoreError(e, t.message)); + } else o(new FirestoreError(N.UNKNOWN, "Server responded with status " + _.getStatus())); + } else + // If we received an HTTP_ERROR but there's no status code, + // it's most probably a connection issue + o(new FirestoreError(N.UNAVAILABLE, "Connection failed.")); + break; + + default: + fail(9055, { + l_: e, + streamId: s, + h_: _.getLastErrorCode(), + P_: _.getLastError() + }); + } + } finally { + __PRIVATE_logDebug(Xt, `RPC '${e}' ${s} completed.`); + } + })); + const a = JSON.stringify(r); + __PRIVATE_logDebug(Xt, `RPC '${e}' ${s} sending request:`, r), _.send(t, "POST", a, n, 15); + })); + } + T_(e, t, n) { + const r = __PRIVATE_generateUniqueDebugId(), i = [ this.Uo, "/", "google.firestore.v1.Firestore", "/", e, "/channel" ], s = webchannelBlob.createWebChannelTransport(), o = webchannelBlob.getStatEventTarget(), _ = { + // Required for backend stickiness, routing behavior is based on this + // parameter. + httpSessionIdParam: "gsessionid", + initMessageHeaders: {}, + messageUrlParams: { + // This param is used to improve routing and project isolation by the + // backend and must be included in every request. + database: `projects/${this.databaseId.projectId}/databases/${this.databaseId.database}` + }, + sendRawJson: !0, + supportsCrossDomainXhr: !0, + internalChannelParams: { + // Override the default timeout (randomized between 10-20 seconds) since + // a large write batch on a slow internet connection may take a long + // time to send to the backend. Rather than have WebChannel impose a + // tight timeout which could lead to infinite timeouts and retries, we + // set it very large (5-10 minutes) and rely on the browser's builtin + // timeouts to kick in if the request isn't working. + forwardChannelRequestTimeoutMs: 6e5 + }, + forceLongPolling: this.forceLongPolling, + detectBufferingProxy: this.autoDetectLongPolling + }, a = this.longPollingOptions.timeoutSeconds; + void 0 !== a && (_.longPollingTimeout = Math.round(1e3 * a)), this.useFetchStreams && (_.useFetchStreams = !0), + this.jo(_.initMessageHeaders, t, n), + // Sending the custom headers we just added to request.initMessageHeaders + // (Authorization, etc.) will trigger the browser to make a CORS preflight + // request because the XHR will no longer meet the criteria for a "simple" + // CORS request: + // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests + // Therefore to avoid the CORS preflight request (an extra network + // roundtrip), we use the encodeInitMessageHeaders option to specify that + // the headers should instead be encoded in the request's POST payload, + // which is recognized by the webchannel backend. + _.encodeInitMessageHeaders = !0; + const u = i.join(""); + __PRIVATE_logDebug(Xt, `Creating RPC '${e}' stream ${r}: ${u}`, _); + const c = s.createWebChannel(u, _); + this.I_(c); + // WebChannel supports sending the first message with the handshake - saving + // a network round trip. However, it will have to call send in the same + // JS event loop as open. In order to enforce this, we delay actually + // opening the WebChannel until send is called. Whether we have called + // open is tracked with this variable. + let l = !1, h = !1; + // A flag to determine whether the stream was closed (by us or through an + // error/close event) to avoid delivering multiple close events or sending + // on a closed stream + const P = new __PRIVATE_StreamBridge({ + Yo: t => { + h ? __PRIVATE_logDebug(Xt, `Not sending because RPC '${e}' stream ${r} is closed:`, t) : (l || (__PRIVATE_logDebug(Xt, `Opening RPC '${e}' stream ${r} transport.`), + c.open(), l = !0), __PRIVATE_logDebug(Xt, `RPC '${e}' stream ${r} sending:`, t), + c.send(t)); + }, + Zo: () => c.close() + }), __PRIVATE_unguardedEventListen = (e, t, n) => { + // TODO(dimond): closure typing seems broken because WebChannel does + // not implement goog.events.Listenable + e.listen(t, (e => { + try { + n(e); + } catch (e) { + setTimeout((() => { + throw e; + }), 0); + } + })); + }; + // Closure events are guarded and exceptions are swallowed, so catch any + // exception and rethrow using a setTimeout so they become visible again. + // Note that eventually this function could go away if we are confident + // enough the code is exception free. + return __PRIVATE_unguardedEventListen(c, webchannelBlob.WebChannel.EventType.OPEN, (() => { + h || (__PRIVATE_logDebug(Xt, `RPC '${e}' stream ${r} transport opened.`), P.o_()); + })), __PRIVATE_unguardedEventListen(c, webchannelBlob.WebChannel.EventType.CLOSE, (() => { + h || (h = !0, __PRIVATE_logDebug(Xt, `RPC '${e}' stream ${r} transport closed`), + P.a_(), this.E_(c)); + })), __PRIVATE_unguardedEventListen(c, webchannelBlob.WebChannel.EventType.ERROR, (t => { + h || (h = !0, __PRIVATE_logWarn(Xt, `RPC '${e}' stream ${r} transport errored. Name:`, t.name, "Message:", t.message), + P.a_(new FirestoreError(N.UNAVAILABLE, "The operation could not be completed"))); + })), __PRIVATE_unguardedEventListen(c, webchannelBlob.WebChannel.EventType.MESSAGE, (t => { + if (!h) { + const n = t.data[0]; + __PRIVATE_hardAssert(!!n, 16349); + // TODO(b/35143891): There is a bug in One Platform that caused errors + // (and only errors) to be wrapped in an extra array. To be forward + // compatible with the bug we need to check either condition. The latter + // can be removed once the fix has been rolled out. + // Use any because msgData.error is not typed. + const i = n, s = i?.error || i[0]?.error; + if (s) { + __PRIVATE_logDebug(Xt, `RPC '${e}' stream ${r} received error:`, s); + // error.status will be a string like 'OK' or 'NOT_FOUND'. + const t = s.status; + let n = + /** + * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'. + * + * @returns The Code equivalent to the given status string or undefined if + * there is no match. + */ + function __PRIVATE_mapCodeFromRpcStatus(e) { + // lookup by string + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const t = pt[e]; + if (void 0 !== t) return __PRIVATE_mapCodeFromRpcCode(t); + }(t), i = s.message; + void 0 === n && (n = N.INTERNAL, i = "Unknown error status: " + t + " with message " + s.message), + // Mark closed so no further events are propagated + h = !0, P.a_(new FirestoreError(n, i)), c.close(); + } else __PRIVATE_logDebug(Xt, `RPC '${e}' stream ${r} received:`, n), P.u_(n); + } + })), __PRIVATE_unguardedEventListen(o, webchannelBlob.Event.STAT_EVENT, (t => { + t.stat === webchannelBlob.Stat.PROXY ? __PRIVATE_logDebug(Xt, `RPC '${e}' stream ${r} detected buffering proxy`) : t.stat === webchannelBlob.Stat.NOPROXY && __PRIVATE_logDebug(Xt, `RPC '${e}' stream ${r} detected no buffering proxy`); + })), setTimeout((() => { + // Technically we could/should wait for the WebChannel opened event, + // but because we want to send the first message with the WebChannel + // handshake we pretend the channel opened here (asynchronously), and + // then delay the actual open until the first message is sent. + P.__(); + }), 0), P; + } + /** + * Closes and cleans up any resources associated with the connection. + */ terminate() { + // If the Firestore instance is terminated, we will explicitly + // close any remaining open WebChannel instances. + this.c_.forEach((e => e.close())), this.c_ = []; + } + /** + * Add a WebChannel instance to the collection of open instances. + * @param webChannel + */ I_(e) { + this.c_.push(e); + } + /** + * Remove a WebChannel instance from the collection of open instances. + * @param webChannel + */ E_(e) { + this.c_ = this.c_.filter((t => t === e)); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Initializes the WebChannelConnection for the browser. */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** The Platform's 'window' implementation or null if not available. */ +function __PRIVATE_getWindow() { + // `window` is not always available, e.g. in ReactNative and WebWorkers. + // eslint-disable-next-line no-restricted-globals + return "undefined" != typeof window ? window : null; +} + +/** The Platform's 'document' implementation or null if not available. */ function getDocument() { + // `document` is not always available, e.g. in ReactNative and WebWorkers. + // eslint-disable-next-line no-restricted-globals + return "undefined" != typeof document ? document : null; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_newSerializer(e) { + return new JsonProtoSerializer(e, /* useProto3Json= */ !0); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A helper for running delayed tasks following an exponential backoff curve + * between attempts. + * + * Each delay is made up of a "base" delay which follows the exponential + * backoff curve, and a +/- 50% "jitter" that is calculated and added to the + * base delay. This prevents clients from accidentally synchronizing their + * delays causing spikes of load to the backend. + */ +class __PRIVATE_ExponentialBackoff { + constructor( + /** + * The AsyncQueue to run backoff operations on. + */ + e, + /** + * The ID to use when scheduling backoff operations on the AsyncQueue. + */ + t, + /** + * The initial delay (used as the base delay on the first retry attempt). + * Note that jitter will still be applied, so the actual delay could be as + * little as 0.5*initialDelayMs. + */ + n = 1e3 + /** + * The multiplier to use to determine the extended base delay after each + * attempt. + */ , r = 1.5 + /** + * The maximum base delay after which no further backoff is performed. + * Note that jitter will still be applied, so the actual delay could be as + * much as 1.5*maxDelayMs. + */ , i = 6e4) { + this.Mi = e, this.timerId = t, this.d_ = n, this.A_ = r, this.R_ = i, this.V_ = 0, + this.m_ = null, + /** The last backoff attempt, as epoch milliseconds. */ + this.f_ = Date.now(), this.reset(); + } + /** + * Resets the backoff delay. + * + * The very next backoffAndWait() will have no delay. If it is called again + * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and + * subsequent ones will increase according to the backoffFactor. + */ reset() { + this.V_ = 0; + } + /** + * Resets the backoff delay to the maximum delay (e.g. for use after a + * RESOURCE_EXHAUSTED error). + */ g_() { + this.V_ = this.R_; + } + /** + * Returns a promise that resolves after currentDelayMs, and increases the + * delay for any subsequent attempts. If there was a pending backoff operation + * already, it will be canceled. + */ p_(e) { + // Cancel any pending backoff operation. + this.cancel(); + // First schedule using the current base (which may be 0 and should be + // honored as such). + const t = Math.floor(this.V_ + this.y_()), n = Math.max(0, Date.now() - this.f_), r = Math.max(0, t - n); + // Guard against lastAttemptTime being in the future due to a clock change. + r > 0 && __PRIVATE_logDebug("ExponentialBackoff", `Backing off for ${r} ms (base delay: ${this.V_} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`), + this.m_ = this.Mi.enqueueAfterDelay(this.timerId, r, (() => (this.f_ = Date.now(), + e()))), + // Apply backoff factor to determine next delay and ensure it is within + // bounds. + this.V_ *= this.A_, this.V_ < this.d_ && (this.V_ = this.d_), this.V_ > this.R_ && (this.V_ = this.R_); + } + w_() { + null !== this.m_ && (this.m_.skipDelay(), this.m_ = null); + } + cancel() { + null !== this.m_ && (this.m_.cancel(), this.m_ = null); + } + /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ y_() { + return (Math.random() - .5) * this.V_; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const en = "PersistentStream"; + +/** The time a stream stays open after it is marked idle. */ +/** + * A PersistentStream is an abstract base class that represents a streaming RPC + * to the Firestore backend. It's built on top of the connections own support + * for streaming RPCs, and adds several critical features for our clients: + * + * - Exponential backoff on failure + * - Authentication via CredentialsProvider + * - Dispatching all callbacks into the shared worker queue + * - Closing idle streams after 60 seconds of inactivity + * + * Subclasses of PersistentStream implement serialization of models to and + * from the JSON representation of the protocol buffers for a specific + * streaming RPC. + * + * ## Starting and Stopping + * + * Streaming RPCs are stateful and need to be start()ed before messages can + * be sent and received. The PersistentStream will call the onOpen() function + * of the listener once the stream is ready to accept requests. + * + * Should a start() fail, PersistentStream will call the registered onClose() + * listener with a FirestoreError indicating what went wrong. + * + * A PersistentStream can be started and stopped repeatedly. + * + * Generic types: + * SendType: The type of the outgoing message of the underlying + * connection stream + * ReceiveType: The type of the incoming message of the underlying + * connection stream + * ListenerType: The type of the listener that will be used for callbacks + */ +class __PRIVATE_PersistentStream { + constructor(e, t, n, r, i, s, o, _) { + this.Mi = e, this.S_ = n, this.b_ = r, this.connection = i, this.authCredentialsProvider = s, + this.appCheckCredentialsProvider = o, this.listener = _, this.state = 0 /* PersistentStreamState.Initial */ , + /** + * A close count that's incremented every time the stream is closed; used by + * getCloseGuardedDispatcher() to invalidate callbacks that happen after + * close. + */ + this.D_ = 0, this.C_ = null, this.v_ = null, this.stream = null, + /** + * Count of response messages received. + */ + this.F_ = 0, this.M_ = new __PRIVATE_ExponentialBackoff(e, t); + } + /** + * Returns true if start() has been called and no error has occurred. True + * indicates the stream is open or in the process of opening (which + * encompasses respecting backoff, getting auth tokens, and starting the + * actual RPC). Use isOpen() to determine if the stream is open and ready for + * outbound requests. + */ x_() { + return 1 /* PersistentStreamState.Starting */ === this.state || 5 /* PersistentStreamState.Backoff */ === this.state || this.O_(); + } + /** + * Returns true if the underlying RPC is open (the onOpen() listener has been + * called) and the stream is ready for outbound requests. + */ O_() { + return 2 /* PersistentStreamState.Open */ === this.state || 3 /* PersistentStreamState.Healthy */ === this.state; + } + /** + * Starts the RPC. Only allowed if isStarted() returns false. The stream is + * not immediately ready for use: onOpen() will be invoked when the RPC is + * ready for outbound requests, at which point isOpen() will return true. + * + * When start returns, isStarted() will return true. + */ start() { + this.F_ = 0, 4 /* PersistentStreamState.Error */ !== this.state ? this.auth() : this.N_(); + } + /** + * Stops the RPC. This call is idempotent and allowed regardless of the + * current isStarted() state. + * + * When stop returns, isStarted() and isOpen() will both return false. + */ async stop() { + this.x_() && await this.close(0 /* PersistentStreamState.Initial */); + } + /** + * After an error the stream will usually back off on the next attempt to + * start it. If the error warrants an immediate restart of the stream, the + * sender can use this to indicate that the receiver should not back off. + * + * Each error will call the onClose() listener. That function can decide to + * inhibit backoff if required. + */ B_() { + this.state = 0 /* PersistentStreamState.Initial */ , this.M_.reset(); + } + /** + * Marks this stream as idle. If no further actions are performed on the + * stream for one minute, the stream will automatically close itself and + * notify the stream's onClose() handler with Status.OK. The stream will then + * be in a !isStarted() state, requiring the caller to start the stream again + * before further use. + * + * Only streams that are in state 'Open' can be marked idle, as all other + * states imply pending network operations. + */ L_() { + // Starts the idle time if we are in state 'Open' and are not yet already + // running a timer (in which case the previous idle timeout still applies). + this.O_() && null === this.C_ && (this.C_ = this.Mi.enqueueAfterDelay(this.S_, 6e4, (() => this.k_()))); + } + /** Sends a message to the underlying stream. */ q_(e) { + this.Q_(), this.stream.send(e); + } + /** Called by the idle timer when the stream should close due to inactivity. */ async k_() { + if (this.O_()) + // When timing out an idle stream there's no reason to force the stream into backoff when + // it restarts so set the stream state to Initial instead of Error. + return this.close(0 /* PersistentStreamState.Initial */); + } + /** Marks the stream as active again. */ Q_() { + this.C_ && (this.C_.cancel(), this.C_ = null); + } + /** Cancels the health check delayed operation. */ U_() { + this.v_ && (this.v_.cancel(), this.v_ = null); + } + /** + * Closes the stream and cleans up as necessary: + * + * * closes the underlying GRPC stream; + * * calls the onClose handler with the given 'error'; + * * sets internal stream state to 'finalState'; + * * adjusts the backoff timer based on the error + * + * A new stream can be opened by calling start(). + * + * @param finalState - the intended state of the stream after closing. + * @param error - the error the connection was closed with. + */ async close(e, t) { + // Cancel any outstanding timers (they're guaranteed not to execute). + this.Q_(), this.U_(), this.M_.cancel(), + // Invalidates any stream-related callbacks (e.g. from auth or the + // underlying stream), guaranteeing they won't execute. + this.D_++, 4 /* PersistentStreamState.Error */ !== e ? + // If this is an intentional close ensure we don't delay our next connection attempt. + this.M_.reset() : t && t.code === N.RESOURCE_EXHAUSTED ? ( + // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.) + __PRIVATE_logError(t.toString()), __PRIVATE_logError("Using maximum backoff delay to prevent overloading the backend."), + this.M_.g_()) : t && t.code === N.UNAUTHENTICATED && 3 /* PersistentStreamState.Healthy */ !== this.state && ( + // "unauthenticated" error means the token was rejected. This should rarely + // happen since both Auth and AppCheck ensure a sufficient TTL when we + // request a token. If a user manually resets their system clock this can + // fail, however. In this case, we should get a Code.UNAUTHENTICATED error + // before we received the first message and we need to invalidate the token + // to ensure that we fetch a new token. + this.authCredentialsProvider.invalidateToken(), this.appCheckCredentialsProvider.invalidateToken()), + // Clean up the underlying stream because we are no longer interested in events. + null !== this.stream && (this.K_(), this.stream.close(), this.stream = null), + // This state must be assigned before calling onClose() to allow the callback to + // inhibit backoff or otherwise manipulate the state in its non-started state. + this.state = e, + // Notify the listener that the stream closed. + await this.listener.r_(t); + } + /** + * Can be overridden to perform additional cleanup before the stream is closed. + * Calling super.tearDown() is not required. + */ K_() {} + auth() { + this.state = 1 /* PersistentStreamState.Starting */; + const e = this.W_(this.D_), t = this.D_; + // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below. + Promise.all([ this.authCredentialsProvider.getToken(), this.appCheckCredentialsProvider.getToken() ]).then((([e, n]) => { + // Stream can be stopped while waiting for authentication. + // TODO(mikelehen): We really should just use dispatchIfNotClosed + // and let this dispatch onto the queue, but that opened a spec test can + // of worms that I don't want to deal with in this PR. + this.D_ === t && + // Normally we'd have to schedule the callback on the AsyncQueue. + // However, the following calls are safe to be called outside the + // AsyncQueue since they don't chain asynchronous calls + this.G_(e, n); + }), (t => { + e((() => { + const e = new FirestoreError(N.UNKNOWN, "Fetching auth token failed: " + t.message); + return this.z_(e); + })); + })); + } + G_(e, t) { + const n = this.W_(this.D_); + this.stream = this.j_(e, t), this.stream.Xo((() => { + n((() => this.listener.Xo())); + })), this.stream.t_((() => { + n((() => (this.state = 2 /* PersistentStreamState.Open */ , this.v_ = this.Mi.enqueueAfterDelay(this.b_, 1e4, (() => (this.O_() && (this.state = 3 /* PersistentStreamState.Healthy */), + Promise.resolve()))), this.listener.t_()))); + })), this.stream.r_((e => { + n((() => this.z_(e))); + })), this.stream.onMessage((e => { + n((() => 1 == ++this.F_ ? this.J_(e) : this.onNext(e))); + })); + } + N_() { + this.state = 5 /* PersistentStreamState.Backoff */ , this.M_.p_((async () => { + this.state = 0 /* PersistentStreamState.Initial */ , this.start(); + })); + } + // Visible for tests + z_(e) { + // In theory the stream could close cleanly, however, in our current model + // we never expect this to happen because if we stop a stream ourselves, + // this callback will never be called. To prevent cases where we retry + // without a backoff accidentally, we set the stream to error in all cases. + return __PRIVATE_logDebug(en, `close with error: ${e}`), this.stream = null, this.close(4 /* PersistentStreamState.Error */ , e); + } + /** + * Returns a "dispatcher" function that dispatches operations onto the + * AsyncQueue but only runs them if closeCount remains unchanged. This allows + * us to turn auth / stream callbacks into no-ops if the stream is closed / + * re-opened, etc. + */ W_(e) { + return t => { + this.Mi.enqueueAndForget((() => this.D_ === e ? t() : (__PRIVATE_logDebug(en, "stream callback skipped by getCloseGuardedDispatcher."), + Promise.resolve()))); + }; + } +} + +/** + * A PersistentStream that implements the Listen RPC. + * + * Once the Listen stream has called the onOpen() listener, any number of + * listen() and unlisten() calls can be made to control what changes will be + * sent from the server for ListenResponses. + */ class __PRIVATE_PersistentListenStream extends __PRIVATE_PersistentStream { + constructor(e, t, n, r, i, s) { + super(e, "listen_stream_connection_backoff" /* TimerId.ListenStreamConnectionBackoff */ , "listen_stream_idle" /* TimerId.ListenStreamIdle */ , "health_check_timeout" /* TimerId.HealthCheckTimeout */ , t, n, r, s), + this.serializer = i; + } + j_(e, t) { + return this.connection.T_("Listen", e, t); + } + J_(e) { + return this.onNext(e); + } + onNext(e) { + // A successful response means the stream is healthy + this.M_.reset(); + const t = __PRIVATE_fromWatchChange(this.serializer, e), n = function __PRIVATE_versionFromListenResponse(e) { + // We have only reached a consistent snapshot for the entire stream if there + // is a read_time set and it applies to all targets (i.e. the list of + // targets is empty). The backend is guaranteed to send such responses. + if (!("targetChange" in e)) return SnapshotVersion.min(); + const t = e.targetChange; + return t.targetIds && t.targetIds.length ? SnapshotVersion.min() : t.readTime ? __PRIVATE_fromVersion(t.readTime) : SnapshotVersion.min(); + }(e); + return this.listener.H_(t, n); + } + /** + * Registers interest in the results of the given target. If the target + * includes a resumeToken it will be included in the request. Results that + * affect the target will be streamed back as WatchChange messages that + * reference the targetId. + */ Y_(e) { + const t = {}; + t.database = __PRIVATE_getEncodedDatabaseId(this.serializer), t.addTarget = function __PRIVATE_toTarget(e, t) { + let n; + const r = t.target; + if (n = __PRIVATE_targetIsDocumentTarget(r) ? { + documents: __PRIVATE_toDocumentsTarget(e, r) + } : { + query: __PRIVATE_toQueryTarget(e, r).ft + }, n.targetId = t.targetId, t.resumeToken.approximateByteSize() > 0) { + n.resumeToken = __PRIVATE_toBytes(e, t.resumeToken); + const r = __PRIVATE_toInt32Proto(e, t.expectedCount); + null !== r && (n.expectedCount = r); + } else if (t.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) { + // TODO(wuandy): Consider removing above check because it is most likely true. + // Right now, many tests depend on this behaviour though (leaving min() out + // of serialization). + n.readTime = toTimestamp(e, t.snapshotVersion.toTimestamp()); + const r = __PRIVATE_toInt32Proto(e, t.expectedCount); + null !== r && (n.expectedCount = r); + } + return n; + }(this.serializer, e); + const n = __PRIVATE_toListenRequestLabels(this.serializer, e); + n && (t.labels = n), this.q_(t); + } + /** + * Unregisters interest in the results of the target associated with the + * given targetId. + */ Z_(e) { + const t = {}; + t.database = __PRIVATE_getEncodedDatabaseId(this.serializer), t.removeTarget = e, + this.q_(t); + } +} + +/** + * A Stream that implements the Write RPC. + * + * The Write RPC requires the caller to maintain special streamToken + * state in between calls, to help the server understand which responses the + * client has processed by the time the next request is made. Every response + * will contain a streamToken; this value must be passed to the next + * request. + * + * After calling start() on this stream, the next request must be a handshake, + * containing whatever streamToken is on hand. Once a response to this + * request is received, all pending mutations may be submitted. When + * submitting multiple batches of mutations at the same time, it's + * okay to use the same streamToken for the calls to writeMutations. + * + * TODO(b/33271235): Use proto types + */ class __PRIVATE_PersistentWriteStream extends __PRIVATE_PersistentStream { + constructor(e, t, n, r, i, s) { + super(e, "write_stream_connection_backoff" /* TimerId.WriteStreamConnectionBackoff */ , "write_stream_idle" /* TimerId.WriteStreamIdle */ , "health_check_timeout" /* TimerId.HealthCheckTimeout */ , t, n, r, s), + this.serializer = i; + } + /** + * Tracks whether or not a handshake has been successfully exchanged and + * the stream is ready to accept mutations. + */ get X_() { + return this.F_ > 0; + } + // Override of PersistentStream.start + start() { + this.lastStreamToken = void 0, super.start(); + } + K_() { + this.X_ && this.ea([]); + } + j_(e, t) { + return this.connection.T_("Write", e, t); + } + J_(e) { + // Always capture the last stream token. + return __PRIVATE_hardAssert(!!e.streamToken, 31322), this.lastStreamToken = e.streamToken, + // The first response is always the handshake response + __PRIVATE_hardAssert(!e.writeResults || 0 === e.writeResults.length, 55816), this.listener.ta(); + } + onNext(e) { + // Always capture the last stream token. + __PRIVATE_hardAssert(!!e.streamToken, 12678), this.lastStreamToken = e.streamToken, + // A successful first write response means the stream is healthy, + // Note, that we could consider a successful handshake healthy, however, + // the write itself might be causing an error we want to back off from. + this.M_.reset(); + const t = __PRIVATE_fromWriteResults(e.writeResults, e.commitTime), n = __PRIVATE_fromVersion(e.commitTime); + return this.listener.na(n, t); + } + /** + * Sends an initial streamToken to the server, performing the handshake + * required to make the StreamingWrite RPC work. Subsequent + * calls should wait until onHandshakeComplete was called. + */ ra() { + // TODO(dimond): Support stream resumption. We intentionally do not set the + // stream token on the handshake, ignoring any stream token we might have. + const e = {}; + e.database = __PRIVATE_getEncodedDatabaseId(this.serializer), this.q_(e); + } + /** Sends a group of mutations to the Firestore backend to apply. */ ea(e) { + const t = { + streamToken: this.lastStreamToken, + writes: e.map((e => toMutation(this.serializer, e))) + }; + this.q_(t); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Datastore and its related methods are a wrapper around the external Google + * Cloud Datastore grpc API, which provides an interface that is more convenient + * for the rest of the client SDK architecture to consume. + */ class Datastore {} + +/** + * An implementation of Datastore that exposes additional state for internal + * consumption. + */ class __PRIVATE_DatastoreImpl extends Datastore { + constructor(e, t, n, r) { + super(), this.authCredentials = e, this.appCheckCredentials = t, this.connection = n, + this.serializer = r, this.ia = !1; + } + sa() { + if (this.ia) throw new FirestoreError(N.FAILED_PRECONDITION, "The client has already been terminated."); + } + /** Invokes the provided RPC with auth and AppCheck tokens. */ Go(e, t, n, r) { + return this.sa(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([i, s]) => this.connection.Go(e, __PRIVATE_toResourcePath(t, n), r, i, s))).catch((e => { + throw "FirebaseError" === e.name ? (e.code === N.UNAUTHENTICATED && (this.authCredentials.invalidateToken(), + this.appCheckCredentials.invalidateToken()), e) : new FirestoreError(N.UNKNOWN, e.toString()); + })); + } + /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ Ho(e, t, n, r, i) { + return this.sa(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([s, o]) => this.connection.Ho(e, __PRIVATE_toResourcePath(t, n), r, s, o, i))).catch((e => { + throw "FirebaseError" === e.name ? (e.code === N.UNAUTHENTICATED && (this.authCredentials.invalidateToken(), + this.appCheckCredentials.invalidateToken()), e) : new FirestoreError(N.UNKNOWN, e.toString()); + })); + } + terminate() { + this.ia = !0, this.connection.terminate(); + } +} + +// TODO(firestorexp): Make sure there is only one Datastore instance per +// firestore-exp client. +/** + * A component used by the RemoteStore to track the OnlineState (that is, + * whether or not the client as a whole should be considered to be online or + * offline), implementing the appropriate heuristics. + * + * In particular, when the client is trying to connect to the backend, we + * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for + * a connection to succeed. If we have too many failures or the timeout elapses, + * then we set the OnlineState to Offline, and the client will behave as if + * it is offline (get()s will return cached data, etc.). + */ +class __PRIVATE_OnlineStateTracker { + constructor(e, t) { + this.asyncQueue = e, this.onlineStateHandler = t, + /** The current OnlineState. */ + this.state = "Unknown" /* OnlineState.Unknown */ , + /** + * A count of consecutive failures to open the stream. If it reaches the + * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to + * Offline. + */ + this.oa = 0, + /** + * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we + * transition from OnlineState.Unknown to OnlineState.Offline without waiting + * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times). + */ + this._a = null, + /** + * Whether the client should log a warning message if it fails to connect to + * the backend (initially true, cleared after a successful stream, or if we've + * logged the message already). + */ + this.aa = !0; + } + /** + * Called by RemoteStore when a watch stream is started (including on each + * backoff attempt). + * + * If this is the first attempt, it sets the OnlineState to Unknown and starts + * the onlineStateTimer. + */ ua() { + 0 === this.oa && (this.ca("Unknown" /* OnlineState.Unknown */), this._a = this.asyncQueue.enqueueAfterDelay("online_state_timeout" /* TimerId.OnlineStateTimeout */ , 1e4, (() => (this._a = null, + this.la("Backend didn't respond within 10 seconds."), this.ca("Offline" /* OnlineState.Offline */), + Promise.resolve())))); + } + /** + * Updates our OnlineState as appropriate after the watch stream reports a + * failure. The first failure moves us to the 'Unknown' state. We then may + * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we + * actually transition to the 'Offline' state. + */ ha(e) { + "Online" /* OnlineState.Online */ === this.state ? this.ca("Unknown" /* OnlineState.Unknown */) : (this.oa++, + this.oa >= 1 && (this.Pa(), this.la(`Connection failed 1 times. Most recent error: ${e.toString()}`), + this.ca("Offline" /* OnlineState.Offline */))); + } + /** + * Explicitly sets the OnlineState to the specified state. + * + * Note that this resets our timers / failure counters, etc. used by our + * Offline heuristics, so must not be used in place of + * handleWatchStreamStart() and handleWatchStreamFailure(). + */ set(e) { + this.Pa(), this.oa = 0, "Online" /* OnlineState.Online */ === e && ( + // We've connected to watch at least once. Don't warn the developer + // about being offline going forward. + this.aa = !1), this.ca(e); + } + ca(e) { + e !== this.state && (this.state = e, this.onlineStateHandler(e)); + } + la(e) { + const t = `Could not reach Cloud Firestore backend. ${e}\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`; + this.aa ? (__PRIVATE_logError(t), this.aa = !1) : __PRIVATE_logDebug("OnlineStateTracker", t); + } + Pa() { + null !== this._a && (this._a.cancel(), this._a = null); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const tn = "RemoteStore"; + +// TODO(b/35853402): Negotiate this with the stream. +class __PRIVATE_RemoteStoreImpl { + constructor( + /** + * The local store, used to fill the write pipeline with outbound mutations. + */ + e, + /** The client-side proxy for interacting with the backend. */ + t, n, r, i) { + this.localStore = e, this.datastore = t, this.asyncQueue = n, this.remoteSyncer = {}, + /** + * A list of up to MAX_PENDING_WRITES writes that we have fetched from the + * LocalStore via fillWritePipeline() and have or will send to the write + * stream. + * + * Whenever writePipeline.length > 0 the RemoteStore will attempt to start or + * restart the write stream. When the stream is established the writes in the + * pipeline will be sent in order. + * + * Writes remain in writePipeline until they are acknowledged by the backend + * and thus will automatically be re-sent if the stream is interrupted / + * restarted before they're acknowledged. + * + * Write responses from the backend are linked to their originating request + * purely based on order, and so we can just shift() writes from the front of + * the writePipeline as we receive responses. + */ + this.Ta = [], + /** + * A mapping of watched targets that the client cares about tracking and the + * user has explicitly called a 'listen' for this target. + * + * These targets may or may not have been sent to or acknowledged by the + * server. On re-establishing the listen stream, these targets should be sent + * to the server. The targets removed with unlistens are removed eagerly + * without waiting for confirmation from the listen stream. + */ + this.Ia = new Map, + /** + * A set of reasons for why the RemoteStore may be offline. If empty, the + * RemoteStore may start its network connections. + */ + this.Ea = new Set, + /** + * Event handlers that get called when the network is disabled or enabled. + * + * PORTING NOTE: These functions are used on the Web client to create the + * underlying streams (to support tree-shakeable streams). On Android and iOS, + * the streams are created during construction of RemoteStore. + */ + this.da = [], this.Aa = i, this.Aa.Oo((e => { + n.enqueueAndForget((async () => { + // Porting Note: Unlike iOS, `restartNetwork()` is called even when the + // network becomes unreachable as we don't have any other way to tear + // down our streams. + __PRIVATE_canUseNetwork(this) && (__PRIVATE_logDebug(tn, "Restarting streams for network reachability change."), + await async function __PRIVATE_restartNetwork(e) { + const t = __PRIVATE_debugCast(e); + t.Ea.add(4 /* OfflineCause.ConnectivityChange */), await __PRIVATE_disableNetworkInternal(t), + t.Ra.set("Unknown" /* OnlineState.Unknown */), t.Ea.delete(4 /* OfflineCause.ConnectivityChange */), + await __PRIVATE_enableNetworkInternal(t); + }(this)); + })); + })), this.Ra = new __PRIVATE_OnlineStateTracker(n, r); + } +} + +async function __PRIVATE_enableNetworkInternal(e) { + if (__PRIVATE_canUseNetwork(e)) for (const t of e.da) await t(/* enabled= */ !0); +} + +/** + * Temporarily disables the network. The network can be re-enabled using + * enableNetwork(). + */ async function __PRIVATE_disableNetworkInternal(e) { + for (const t of e.da) await t(/* enabled= */ !1); +} + +/** + * Starts new listen for the given target. Uses resume token if provided. It + * is a no-op if the target of given `TargetData` is already being listened to. + */ +function __PRIVATE_remoteStoreListen(e, t) { + const n = __PRIVATE_debugCast(e); + n.Ia.has(t.targetId) || ( + // Mark this as something the client is currently listening for. + n.Ia.set(t.targetId, t), __PRIVATE_shouldStartWatchStream(n) ? + // The listen will be sent in onWatchStreamOpen + __PRIVATE_startWatchStream(n) : __PRIVATE_ensureWatchStream(n).O_() && __PRIVATE_sendWatchRequest(n, t)); +} + +/** + * Removes the listen from server. It is a no-op if the given target id is + * not being listened to. + */ function __PRIVATE_remoteStoreUnlisten(e, t) { + const n = __PRIVATE_debugCast(e), r = __PRIVATE_ensureWatchStream(n); + n.Ia.delete(t), r.O_() && __PRIVATE_sendUnwatchRequest(n, t), 0 === n.Ia.size && (r.O_() ? r.L_() : __PRIVATE_canUseNetwork(n) && + // Revert to OnlineState.Unknown if the watch stream is not open and we + // have no listeners, since without any listens to send we cannot + // confirm if the stream is healthy and upgrade to OnlineState.Online. + n.Ra.set("Unknown" /* OnlineState.Unknown */)); +} + +/** + * We need to increment the expected number of pending responses we're due + * from watch so we wait for the ack to process any messages from this target. + */ function __PRIVATE_sendWatchRequest(e, t) { + if (e.Va.Ue(t.targetId), t.resumeToken.approximateByteSize() > 0 || t.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) { + const n = e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size; + t = t.withExpectedCount(n); + } + __PRIVATE_ensureWatchStream(e).Y_(t); +} + +/** + * We need to increment the expected number of pending responses we're due + * from watch so we wait for the removal on the server before we process any + * messages from this target. + */ function __PRIVATE_sendUnwatchRequest(e, t) { + e.Va.Ue(t), __PRIVATE_ensureWatchStream(e).Z_(t); +} + +function __PRIVATE_startWatchStream(e) { + e.Va = new __PRIVATE_WatchChangeAggregator({ + getRemoteKeysForTarget: t => e.remoteSyncer.getRemoteKeysForTarget(t), + At: t => e.Ia.get(t) || null, + ht: () => e.datastore.serializer.databaseId + }), __PRIVATE_ensureWatchStream(e).start(), e.Ra.ua(); +} + +/** + * Returns whether the watch stream should be started because it's necessary + * and has not yet been started. + */ function __PRIVATE_shouldStartWatchStream(e) { + return __PRIVATE_canUseNetwork(e) && !__PRIVATE_ensureWatchStream(e).x_() && e.Ia.size > 0; +} + +function __PRIVATE_canUseNetwork(e) { + return 0 === __PRIVATE_debugCast(e).Ea.size; +} + +function __PRIVATE_cleanUpWatchStreamState(e) { + e.Va = void 0; +} + +async function __PRIVATE_onWatchStreamConnected(e) { + // Mark the client as online since we got a "connected" notification. + e.Ra.set("Online" /* OnlineState.Online */); +} + +async function __PRIVATE_onWatchStreamOpen(e) { + e.Ia.forEach(((t, n) => { + __PRIVATE_sendWatchRequest(e, t); + })); +} + +async function __PRIVATE_onWatchStreamClose(e, t) { + __PRIVATE_cleanUpWatchStreamState(e), + // If we still need the watch stream, retry the connection. + __PRIVATE_shouldStartWatchStream(e) ? (e.Ra.ha(t), __PRIVATE_startWatchStream(e)) : + // No need to restart watch stream because there are no active targets. + // The online state is set to unknown because there is no active attempt + // at establishing a connection + e.Ra.set("Unknown" /* OnlineState.Unknown */); +} + +async function __PRIVATE_onWatchStreamChange(e, t, n) { + if ( + // Mark the client as online since we got a message from the server + e.Ra.set("Online" /* OnlineState.Online */), t instanceof __PRIVATE_WatchTargetChange && 2 /* WatchTargetChangeState.Removed */ === t.state && t.cause) + // There was an error on a target, don't wait for a consistent snapshot + // to raise events + try { + /** Handles an error on a target */ + await async function __PRIVATE_handleTargetError(e, t) { + const n = t.cause; + for (const r of t.targetIds) + // A watched target might have been removed already. + e.Ia.has(r) && (await e.remoteSyncer.rejectListen(r, n), e.Ia.delete(r), e.Va.removeTarget(r)); + } + /** + * Attempts to fill our write pipeline with writes from the LocalStore. + * + * Called internally to bootstrap or refill the write pipeline and by + * SyncEngine whenever there are new mutations to process. + * + * Starts the write stream if necessary. + */ (e, t); + } catch (n) { + __PRIVATE_logDebug(tn, "Failed to remove targets %s: %s ", t.targetIds.join(","), n), + await __PRIVATE_disableNetworkUntilRecovery(e, n); + } else if (t instanceof __PRIVATE_DocumentWatchChange ? e.Va.Ze(t) : t instanceof __PRIVATE_ExistenceFilterChange ? e.Va.st(t) : e.Va.tt(t), + !n.isEqual(SnapshotVersion.min())) try { + const t = await __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e.localStore); + n.compareTo(t) >= 0 && + // We have received a target change with a global snapshot if the snapshot + // version is not equal to SnapshotVersion.min(). + /** + * Takes a batch of changes from the Datastore, repackages them as a + * RemoteEvent, and passes that on to the listener, which is typically the + * SyncEngine. + */ + await function __PRIVATE_raiseWatchSnapshot(e, t) { + const n = e.Va.Tt(t); + // Update in-memory resume tokens. LocalStore will update the + // persistent view of these when applying the completed RemoteEvent. + return n.targetChanges.forEach(((n, r) => { + if (n.resumeToken.approximateByteSize() > 0) { + const i = e.Ia.get(r); + // A watched target might have been removed already. + i && e.Ia.set(r, i.withResumeToken(n.resumeToken, t)); + } + })), + // Re-establish listens for the targets that have been invalidated by + // existence filter mismatches. + n.targetMismatches.forEach(((t, n) => { + const r = e.Ia.get(t); + if (!r) + // A watched target might have been removed already. + return; + // Clear the resume token for the target, since we're in a known mismatch + // state. + e.Ia.set(t, r.withResumeToken(ByteString.EMPTY_BYTE_STRING, r.snapshotVersion)), + // Cause a hard reset by unwatching and rewatching immediately, but + // deliberately don't send a resume token so that we get a full update. + __PRIVATE_sendUnwatchRequest(e, t); + // Mark the target we send as being on behalf of an existence filter + // mismatch, but don't actually retain that in listenTargets. This ensures + // that we flag the first re-listen this way without impacting future + // listens of this target (that might happen e.g. on reconnect). + const i = new TargetData(r.target, t, n, r.sequenceNumber); + __PRIVATE_sendWatchRequest(e, i); + })), e.remoteSyncer.applyRemoteEvent(n); + }(e, n); + } catch (t) { + __PRIVATE_logDebug(tn, "Failed to raise snapshot:", t), await __PRIVATE_disableNetworkUntilRecovery(e, t); + } +} + +/** + * Recovery logic for IndexedDB errors that takes the network offline until + * `op` succeeds. Retries are scheduled with backoff using + * `enqueueRetryable()`. If `op()` is not provided, IndexedDB access is + * validated via a generic operation. + * + * The returned Promise is resolved once the network is disabled and before + * any retry attempt. + */ async function __PRIVATE_disableNetworkUntilRecovery(e, t, n) { + if (!__PRIVATE_isIndexedDbTransactionError(t)) throw t; + e.Ea.add(1 /* OfflineCause.IndexedDbFailed */), + // Disable network and raise offline snapshots + await __PRIVATE_disableNetworkInternal(e), e.Ra.set("Offline" /* OnlineState.Offline */), + n || ( + // Use a simple read operation to determine if IndexedDB recovered. + // Ideally, we would expose a health check directly on SimpleDb, but + // RemoteStore only has access to persistence through LocalStore. + n = () => __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e.localStore)), + // Probe IndexedDB periodically and re-enable network + e.asyncQueue.enqueueRetryable((async () => { + __PRIVATE_logDebug(tn, "Retrying IndexedDB access"), await n(), e.Ea.delete(1 /* OfflineCause.IndexedDbFailed */), + await __PRIVATE_enableNetworkInternal(e); + })); +} + +/** + * Executes `op`. If `op` fails, takes the network offline until `op` + * succeeds. Returns after the first attempt. + */ function __PRIVATE_executeWithRecovery(e, t) { + return t().catch((n => __PRIVATE_disableNetworkUntilRecovery(e, n, t))); +} + +async function __PRIVATE_fillWritePipeline(e) { + const t = __PRIVATE_debugCast(e), n = __PRIVATE_ensureWriteStream(t); + let r = t.Ta.length > 0 ? t.Ta[t.Ta.length - 1].batchId : j; + for (;__PRIVATE_canAddToWritePipeline(t); ) try { + const e = await __PRIVATE_localStoreGetNextMutationBatch(t.localStore, r); + if (null === e) { + 0 === t.Ta.length && n.L_(); + break; + } + r = e.batchId, __PRIVATE_addToWritePipeline(t, e); + } catch (e) { + await __PRIVATE_disableNetworkUntilRecovery(t, e); + } + __PRIVATE_shouldStartWriteStream(t) && __PRIVATE_startWriteStream(t); +} + +/** + * Returns true if we can add to the write pipeline (i.e. the network is + * enabled and the write pipeline is not full). + */ function __PRIVATE_canAddToWritePipeline(e) { + return __PRIVATE_canUseNetwork(e) && e.Ta.length < 10; +} + +/** + * Queues additional writes to be sent to the write stream, sending them + * immediately if the write stream is established. + */ function __PRIVATE_addToWritePipeline(e, t) { + e.Ta.push(t); + const n = __PRIVATE_ensureWriteStream(e); + n.O_() && n.X_ && n.ea(t.mutations); +} + +function __PRIVATE_shouldStartWriteStream(e) { + return __PRIVATE_canUseNetwork(e) && !__PRIVATE_ensureWriteStream(e).x_() && e.Ta.length > 0; +} + +function __PRIVATE_startWriteStream(e) { + __PRIVATE_ensureWriteStream(e).start(); +} + +async function __PRIVATE_onWriteStreamOpen(e) { + __PRIVATE_ensureWriteStream(e).ra(); +} + +async function __PRIVATE_onWriteHandshakeComplete(e) { + const t = __PRIVATE_ensureWriteStream(e); + // Send the write pipeline now that the stream is established. + for (const n of e.Ta) t.ea(n.mutations); +} + +async function __PRIVATE_onMutationResult(e, t, n) { + const r = e.Ta.shift(), i = MutationBatchResult.from(r, t, n); + await __PRIVATE_executeWithRecovery(e, (() => e.remoteSyncer.applySuccessfulWrite(i))), + // It's possible that with the completion of this mutation another + // slot has freed up. + await __PRIVATE_fillWritePipeline(e); +} + +async function __PRIVATE_onWriteStreamClose(e, t) { + // If the write stream closed after the write handshake completes, a write + // operation failed and we fail the pending operation. + t && __PRIVATE_ensureWriteStream(e).X_ && + // This error affects the actual write. + await async function __PRIVATE_handleWriteError(e, t) { + // Only handle permanent errors here. If it's transient, just let the retry + // logic kick in. + if (function __PRIVATE_isPermanentWriteError(e) { + return __PRIVATE_isPermanentError(e) && e !== N.ABORTED; + }(t.code)) { + // This was a permanent error, the request itself was the problem + // so it's not going to succeed if we resend it. + const n = e.Ta.shift(); + // In this case it's also unlikely that the server itself is melting + // down -- this was just a bad request so inhibit backoff on the next + // restart. + __PRIVATE_ensureWriteStream(e).B_(), await __PRIVATE_executeWithRecovery(e, (() => e.remoteSyncer.rejectFailedWrite(n.batchId, t))), + // It's possible that with the completion of this mutation + // another slot has freed up. + await __PRIVATE_fillWritePipeline(e); + } + }(e, t), + // The write stream might have been started by refilling the write + // pipeline for failed writes + __PRIVATE_shouldStartWriteStream(e) && __PRIVATE_startWriteStream(e); +} + +async function __PRIVATE_remoteStoreHandleCredentialChange(e, t) { + const n = __PRIVATE_debugCast(e); + n.asyncQueue.verifyOperationInProgress(), __PRIVATE_logDebug(tn, "RemoteStore received new credentials"); + const r = __PRIVATE_canUseNetwork(n); + // Tear down and re-create our network streams. This will ensure we get a + // fresh auth token for the new user and re-fill the write pipeline with + // new mutations from the LocalStore (since mutations are per-user). + n.Ea.add(3 /* OfflineCause.CredentialChange */), await __PRIVATE_disableNetworkInternal(n), + r && + // Don't set the network status to Unknown if we are offline. + n.Ra.set("Unknown" /* OnlineState.Unknown */), await n.remoteSyncer.handleCredentialChange(t), + n.Ea.delete(3 /* OfflineCause.CredentialChange */), await __PRIVATE_enableNetworkInternal(n); +} + +/** + * Toggles the network state when the client gains or loses its primary lease. + */ async function __PRIVATE_remoteStoreApplyPrimaryState(e, t) { + const n = __PRIVATE_debugCast(e); + t ? (n.Ea.delete(2 /* OfflineCause.IsSecondary */), await __PRIVATE_enableNetworkInternal(n)) : t || (n.Ea.add(2 /* OfflineCause.IsSecondary */), + await __PRIVATE_disableNetworkInternal(n), n.Ra.set("Unknown" /* OnlineState.Unknown */)); +} + +/** + * If not yet initialized, registers the WatchStream and its network state + * callback with `remoteStoreImpl`. Returns the existing stream if one is + * already available. + * + * PORTING NOTE: On iOS and Android, the WatchStream gets registered on startup. + * This is not done on Web to allow it to be tree-shaken. + */ function __PRIVATE_ensureWatchStream(e) { + return e.ma || ( + // Create stream (but note that it is not started yet). + e.ma = function __PRIVATE_newPersistentWatchStream(e, t, n) { + const r = __PRIVATE_debugCast(e); + return r.sa(), new __PRIVATE_PersistentListenStream(t, r.connection, r.authCredentials, r.appCheckCredentials, r.serializer, n); + } + /** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ (e.datastore, e.asyncQueue, { + Xo: __PRIVATE_onWatchStreamConnected.bind(null, e), + t_: __PRIVATE_onWatchStreamOpen.bind(null, e), + r_: __PRIVATE_onWatchStreamClose.bind(null, e), + H_: __PRIVATE_onWatchStreamChange.bind(null, e) + }), e.da.push((async t => { + t ? (e.ma.B_(), __PRIVATE_shouldStartWatchStream(e) ? __PRIVATE_startWatchStream(e) : e.Ra.set("Unknown" /* OnlineState.Unknown */)) : (await e.ma.stop(), + __PRIVATE_cleanUpWatchStreamState(e)); + }))), e.ma; +} + +/** + * If not yet initialized, registers the WriteStream and its network state + * callback with `remoteStoreImpl`. Returns the existing stream if one is + * already available. + * + * PORTING NOTE: On iOS and Android, the WriteStream gets registered on startup. + * This is not done on Web to allow it to be tree-shaken. + */ function __PRIVATE_ensureWriteStream(e) { + return e.fa || ( + // Create stream (but note that it is not started yet). + e.fa = function __PRIVATE_newPersistentWriteStream(e, t, n) { + const r = __PRIVATE_debugCast(e); + return r.sa(), new __PRIVATE_PersistentWriteStream(t, r.connection, r.authCredentials, r.appCheckCredentials, r.serializer, n); + }(e.datastore, e.asyncQueue, { + Xo: () => Promise.resolve(), + t_: __PRIVATE_onWriteStreamOpen.bind(null, e), + r_: __PRIVATE_onWriteStreamClose.bind(null, e), + ta: __PRIVATE_onWriteHandshakeComplete.bind(null, e), + na: __PRIVATE_onMutationResult.bind(null, e) + }), e.da.push((async t => { + t ? (e.fa.B_(), + // This will start the write stream if necessary. + await __PRIVATE_fillWritePipeline(e)) : (await e.fa.stop(), e.Ta.length > 0 && (__PRIVATE_logDebug(tn, `Stopping write stream with ${e.Ta.length} pending writes`), + e.Ta = [])); + }))), e.fa; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents an operation scheduled to be run in the future on an AsyncQueue. + * + * It is created via DelayedOperation.createAndSchedule(). + * + * Supports cancellation (via cancel()) and early execution (via skipDelay()). + * + * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type + * in newer versions of TypeScript defines `finally`, which is not available in + * IE. + */ +class DelayedOperation { + constructor(e, t, n, r, i) { + this.asyncQueue = e, this.timerId = t, this.targetTimeMs = n, this.op = r, this.removalCallback = i, + this.deferred = new __PRIVATE_Deferred, this.then = this.deferred.promise.then.bind(this.deferred.promise), + // It's normal for the deferred promise to be canceled (due to cancellation) + // and so we attach a dummy catch callback to avoid + // 'UnhandledPromiseRejectionWarning' log spam. + this.deferred.promise.catch((e => {})); + } + get promise() { + return this.deferred.promise; + } + /** + * Creates and returns a DelayedOperation that has been scheduled to be + * executed on the provided asyncQueue after the provided delayMs. + * + * @param asyncQueue - The queue to schedule the operation on. + * @param id - A Timer ID identifying the type of operation this is. + * @param delayMs - The delay (ms) before the operation should be scheduled. + * @param op - The operation to run. + * @param removalCallback - A callback to be called synchronously once the + * operation is executed or canceled, notifying the AsyncQueue to remove it + * from its delayedOperations list. + * PORTING NOTE: This exists to prevent making removeDelayedOperation() and + * the DelayedOperation class public. + */ static createAndSchedule(e, t, n, r, i) { + const s = Date.now() + n, o = new DelayedOperation(e, t, s, r, i); + return o.start(n), o; + } + /** + * Starts the timer. This is called immediately after construction by + * createAndSchedule(). + */ start(e) { + this.timerHandle = setTimeout((() => this.handleDelayElapsed()), e); + } + /** + * Queues the operation to run immediately (if it hasn't already been run or + * canceled). + */ skipDelay() { + return this.handleDelayElapsed(); + } + /** + * Cancels the operation if it hasn't already been executed or canceled. The + * promise will be rejected. + * + * As long as the operation has not yet been run, calling cancel() provides a + * guarantee that the operation will not be run. + */ cancel(e) { + null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new FirestoreError(N.CANCELLED, "Operation cancelled" + (e ? ": " + e : "")))); + } + handleDelayElapsed() { + this.asyncQueue.enqueueAndForget((() => null !== this.timerHandle ? (this.clearTimeout(), + this.op().then((e => this.deferred.resolve(e)))) : Promise.resolve())); + } + clearTimeout() { + null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle), + this.timerHandle = null); + } +} + +/** + * Returns a FirestoreError that can be surfaced to the user if the provided + * error is an IndexedDbTransactionError. Re-throws the error otherwise. + */ function __PRIVATE_wrapInUserErrorIfRecoverable(e, t) { + if (__PRIVATE_logError("AsyncQueue", `${t}: ${e}`), __PRIVATE_isIndexedDbTransactionError(e)) return new FirestoreError(N.UNAVAILABLE, `${t}: ${e}`); + throw e; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * DocumentSet is an immutable (copy-on-write) collection that holds documents + * in order specified by the provided comparator. We always add a document key + * comparator on top of what is provided to guarantee document equality based on + * the key. + */ class DocumentSet { + /** + * Returns an empty copy of the existing DocumentSet, using the same + * comparator. + */ + static emptySet(e) { + return new DocumentSet(e.comparator); + } + /** The default ordering is by key if the comparator is omitted */ constructor(e) { + // We are adding document key comparator to the end as it's the only + // guaranteed unique property of a document. + this.comparator = e ? (t, n) => e(t, n) || DocumentKey.comparator(t.key, n.key) : (e, t) => DocumentKey.comparator(e.key, t.key), + this.keyedMap = documentMap(), this.sortedSet = new SortedMap(this.comparator); + } + has(e) { + return null != this.keyedMap.get(e); + } + get(e) { + return this.keyedMap.get(e); + } + first() { + return this.sortedSet.minKey(); + } + last() { + return this.sortedSet.maxKey(); + } + isEmpty() { + return this.sortedSet.isEmpty(); + } + /** + * Returns the index of the provided key in the document set, or -1 if the + * document key is not present in the set; + */ indexOf(e) { + const t = this.keyedMap.get(e); + return t ? this.sortedSet.indexOf(t) : -1; + } + get size() { + return this.sortedSet.size; + } + /** Iterates documents in order defined by "comparator" */ forEach(e) { + this.sortedSet.inorderTraversal(((t, n) => (e(t), !1))); + } + /** Inserts or updates a document with the same key */ add(e) { + // First remove the element if we have it. + const t = this.delete(e.key); + return t.copy(t.keyedMap.insert(e.key, e), t.sortedSet.insert(e, null)); + } + /** Deletes a document with a given key */ delete(e) { + const t = this.get(e); + return t ? this.copy(this.keyedMap.remove(e), this.sortedSet.remove(t)) : this; + } + isEqual(e) { + if (!(e instanceof DocumentSet)) return !1; + if (this.size !== e.size) return !1; + const t = this.sortedSet.getIterator(), n = e.sortedSet.getIterator(); + for (;t.hasNext(); ) { + const e = t.getNext().key, r = n.getNext().key; + if (!e.isEqual(r)) return !1; + } + return !0; + } + toString() { + const e = []; + return this.forEach((t => { + e.push(t.toString()); + })), 0 === e.length ? "DocumentSet ()" : "DocumentSet (\n " + e.join(" \n") + "\n)"; + } + copy(e, t) { + const n = new DocumentSet; + return n.comparator = this.comparator, n.keyedMap = e, n.sortedSet = t, n; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * DocumentChangeSet keeps track of a set of changes to docs in a query, merging + * duplicate events for the same doc. + */ class __PRIVATE_DocumentChangeSet { + constructor() { + this.ga = new SortedMap(DocumentKey.comparator); + } + track(e) { + const t = e.doc.key, n = this.ga.get(t); + n ? + // Merge the new change with the existing change. + 0 /* ChangeType.Added */ !== e.type && 3 /* ChangeType.Metadata */ === n.type ? this.ga = this.ga.insert(t, e) : 3 /* ChangeType.Metadata */ === e.type && 1 /* ChangeType.Removed */ !== n.type ? this.ga = this.ga.insert(t, { + type: n.type, + doc: e.doc + }) : 2 /* ChangeType.Modified */ === e.type && 2 /* ChangeType.Modified */ === n.type ? this.ga = this.ga.insert(t, { + type: 2 /* ChangeType.Modified */ , + doc: e.doc + }) : 2 /* ChangeType.Modified */ === e.type && 0 /* ChangeType.Added */ === n.type ? this.ga = this.ga.insert(t, { + type: 0 /* ChangeType.Added */ , + doc: e.doc + }) : 1 /* ChangeType.Removed */ === e.type && 0 /* ChangeType.Added */ === n.type ? this.ga = this.ga.remove(t) : 1 /* ChangeType.Removed */ === e.type && 2 /* ChangeType.Modified */ === n.type ? this.ga = this.ga.insert(t, { + type: 1 /* ChangeType.Removed */ , + doc: n.doc + }) : 0 /* ChangeType.Added */ === e.type && 1 /* ChangeType.Removed */ === n.type ? this.ga = this.ga.insert(t, { + type: 2 /* ChangeType.Modified */ , + doc: e.doc + }) : + // This includes these cases, which don't make sense: + // Added->Added + // Removed->Removed + // Modified->Added + // Removed->Modified + // Metadata->Added + // Removed->Metadata + fail(63341, { + Rt: e, + pa: n + }) : this.ga = this.ga.insert(t, e); + } + ya() { + const e = []; + return this.ga.inorderTraversal(((t, n) => { + e.push(n); + })), e; + } +} + +class ViewSnapshot { + constructor(e, t, n, r, i, s, o, _, a) { + this.query = e, this.docs = t, this.oldDocs = n, this.docChanges = r, this.mutatedKeys = i, + this.fromCache = s, this.syncStateChanged = o, this.excludesMetadataChanges = _, + this.hasCachedResults = a; + } + /** Returns a view snapshot as if all documents in the snapshot were added. */ static fromInitialDocuments(e, t, n, r, i) { + const s = []; + return t.forEach((e => { + s.push({ + type: 0 /* ChangeType.Added */ , + doc: e + }); + })), new ViewSnapshot(e, t, DocumentSet.emptySet(t), s, n, r, + /* syncStateChanged= */ !0, + /* excludesMetadataChanges= */ !1, i); + } + get hasPendingWrites() { + return !this.mutatedKeys.isEmpty(); + } + isEqual(e) { + if (!(this.fromCache === e.fromCache && this.hasCachedResults === e.hasCachedResults && this.syncStateChanged === e.syncStateChanged && this.mutatedKeys.isEqual(e.mutatedKeys) && __PRIVATE_queryEquals(this.query, e.query) && this.docs.isEqual(e.docs) && this.oldDocs.isEqual(e.oldDocs))) return !1; + const t = this.docChanges, n = e.docChanges; + if (t.length !== n.length) return !1; + for (let e = 0; e < t.length; e++) if (t[e].type !== n[e].type || !t[e].doc.isEqual(n[e].doc)) return !1; + return !0; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Holds the listeners and the last received ViewSnapshot for a query being + * tracked by EventManager. + */ class __PRIVATE_QueryListenersInfo { + constructor() { + this.wa = void 0, this.Sa = []; + } + // Helper methods that checks if the query has listeners that listening to remote store + ba() { + return this.Sa.some((e => e.Da())); + } +} + +class __PRIVATE_EventManagerImpl { + constructor() { + this.queries = __PRIVATE_newQueriesObjectMap(), this.onlineState = "Unknown" /* OnlineState.Unknown */ , + this.Ca = new Set; + } + terminate() { + !function __PRIVATE_errorAllTargets(e, t) { + const n = __PRIVATE_debugCast(e), r = n.queries; + // Prevent further access by clearing ObjectMap. + n.queries = __PRIVATE_newQueriesObjectMap(), r.forEach(((e, n) => { + for (const e of n.Sa) e.onError(t); + })); + } + // Call all global snapshot listeners that have been set. + (this, new FirestoreError(N.ABORTED, "Firestore shutting down")); + } +} + +function __PRIVATE_newQueriesObjectMap() { + return new ObjectMap((e => __PRIVATE_canonifyQuery(e)), __PRIVATE_queryEquals); +} + +async function __PRIVATE_eventManagerListen(e, t) { + const n = __PRIVATE_debugCast(e); + let r = 3 /* ListenerSetupAction.NoActionRequired */; + const i = t.query; + let s = n.queries.get(i); + s ? !s.ba() && t.Da() && ( + // Query has been listening to local cache, and tries to add a new listener sourced from watch. + r = 2 /* ListenerSetupAction.RequireWatchConnectionOnly */) : (s = new __PRIVATE_QueryListenersInfo, + r = t.Da() ? 0 /* ListenerSetupAction.InitializeLocalListenAndRequireWatchConnection */ : 1 /* ListenerSetupAction.InitializeLocalListenOnly */); + try { + switch (r) { + case 0 /* ListenerSetupAction.InitializeLocalListenAndRequireWatchConnection */ : + s.wa = await n.onListen(i, + /** enableRemoteListen= */ !0); + break; + + case 1 /* ListenerSetupAction.InitializeLocalListenOnly */ : + s.wa = await n.onListen(i, + /** enableRemoteListen= */ !1); + break; + + case 2 /* ListenerSetupAction.RequireWatchConnectionOnly */ : + await n.onFirstRemoteStoreListen(i); + } + } catch (e) { + const n = __PRIVATE_wrapInUserErrorIfRecoverable(e, `Initialization of query '${__PRIVATE_stringifyQuery(t.query)}' failed`); + return void t.onError(n); + } + if (n.queries.set(i, s), s.Sa.push(t), + // Run global snapshot listeners if a consistent snapshot has been emitted. + t.va(n.onlineState), s.wa) { + t.Fa(s.wa) && __PRIVATE_raiseSnapshotsInSyncEvent(n); + } +} + +async function __PRIVATE_eventManagerUnlisten(e, t) { + const n = __PRIVATE_debugCast(e), r = t.query; + let i = 3 /* ListenerRemovalAction.NoActionRequired */; + const s = n.queries.get(r); + if (s) { + const e = s.Sa.indexOf(t); + e >= 0 && (s.Sa.splice(e, 1), 0 === s.Sa.length ? i = t.Da() ? 0 /* ListenerRemovalAction.TerminateLocalListenAndRequireWatchDisconnection */ : 1 /* ListenerRemovalAction.TerminateLocalListenOnly */ : !s.ba() && t.Da() && ( + // The removed listener is the last one that sourced from watch. + i = 2 /* ListenerRemovalAction.RequireWatchDisconnectionOnly */)); + } + switch (i) { + case 0 /* ListenerRemovalAction.TerminateLocalListenAndRequireWatchDisconnection */ : + return n.queries.delete(r), n.onUnlisten(r, + /** disableRemoteListen= */ !0); + + case 1 /* ListenerRemovalAction.TerminateLocalListenOnly */ : + return n.queries.delete(r), n.onUnlisten(r, + /** disableRemoteListen= */ !1); + + case 2 /* ListenerRemovalAction.RequireWatchDisconnectionOnly */ : + return n.onLastRemoteStoreUnlisten(r); + + default: + return; + } +} + +function __PRIVATE_eventManagerOnWatchChange(e, t) { + const n = __PRIVATE_debugCast(e); + let r = !1; + for (const e of t) { + const t = e.query, i = n.queries.get(t); + if (i) { + for (const t of i.Sa) t.Fa(e) && (r = !0); + i.wa = e; + } + } + r && __PRIVATE_raiseSnapshotsInSyncEvent(n); +} + +function __PRIVATE_eventManagerOnWatchError(e, t, n) { + const r = __PRIVATE_debugCast(e), i = r.queries.get(t); + if (i) for (const e of i.Sa) e.onError(n); + // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten() + // after an error. + r.queries.delete(t); +} + +function __PRIVATE_raiseSnapshotsInSyncEvent(e) { + e.Ca.forEach((e => { + e.next(); + })); +} + +var nn, rn; + +/** Listen to both cache and server changes */ +(rn = nn || (nn = {})).Ma = "default", +/** Listen to changes in cache only */ +rn.Cache = "cache"; + +/** + * QueryListener takes a series of internal view snapshots and determines + * when to raise the event. + * + * It uses an Observer to dispatch events. + */ +class __PRIVATE_QueryListener { + constructor(e, t, n) { + this.query = e, this.xa = t, + /** + * Initial snapshots (e.g. from cache) may not be propagated to the wrapped + * observer. This flag is set to true once we've actually raised an event. + */ + this.Oa = !1, this.Na = null, this.onlineState = "Unknown" /* OnlineState.Unknown */ , + this.options = n || {}; + } + /** + * Applies the new ViewSnapshot to this listener, raising a user-facing event + * if applicable (depending on what changed, whether the user has opted into + * metadata-only changes, etc.). Returns true if a user-facing event was + * indeed raised. + */ Fa(e) { + if (!this.options.includeMetadataChanges) { + // Remove the metadata only changes. + const t = []; + for (const n of e.docChanges) 3 /* ChangeType.Metadata */ !== n.type && t.push(n); + e = new ViewSnapshot(e.query, e.docs, e.oldDocs, t, e.mutatedKeys, e.fromCache, e.syncStateChanged, + /* excludesMetadataChanges= */ !0, e.hasCachedResults); + } + let t = !1; + return this.Oa ? this.Ba(e) && (this.xa.next(e), t = !0) : this.La(e, this.onlineState) && (this.ka(e), + t = !0), this.Na = e, t; + } + onError(e) { + this.xa.error(e); + } + /** Returns whether a snapshot was raised. */ va(e) { + this.onlineState = e; + let t = !1; + return this.Na && !this.Oa && this.La(this.Na, e) && (this.ka(this.Na), t = !0), + t; + } + La(e, t) { + // Always raise the first event when we're synced + if (!e.fromCache) return !0; + // Always raise event if listening to cache + if (!this.Da()) return !0; + // NOTE: We consider OnlineState.Unknown as online (it should become Offline + // or Online if we wait long enough). + const n = "Offline" /* OnlineState.Offline */ !== t; + // Don't raise the event if we're online, aren't synced yet (checked + // above) and are waiting for a sync. + return (!this.options.qa || !n) && (!e.docs.isEmpty() || e.hasCachedResults || "Offline" /* OnlineState.Offline */ === t); + // Raise data from cache if we have any documents, have cached results before, + // or we are offline. + } + Ba(e) { + // We don't need to handle includeDocumentMetadataChanges here because + // the Metadata only changes have already been stripped out if needed. + // At this point the only changes we will see are the ones we should + // propagate. + if (e.docChanges.length > 0) return !0; + const t = this.Na && this.Na.hasPendingWrites !== e.hasPendingWrites; + return !(!e.syncStateChanged && !t) && !0 === this.options.includeMetadataChanges; + // Generally we should have hit one of the cases above, but it's possible + // to get here if there were only metadata docChanges and they got + // stripped out. + } + ka(e) { + e = ViewSnapshot.fromInitialDocuments(e.query, e.docs, e.mutatedKeys, e.fromCache, e.hasCachedResults), + this.Oa = !0, this.xa.next(e); + } + Da() { + return this.options.source !== nn.Cache; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A complete element in the bundle stream, together with the byte length it + * occupies in the stream. + */ class __PRIVATE_SizedBundleElement { + constructor(e, + // How many bytes this element takes to store in the bundle. + t) { + this.Qa = e, this.byteLength = t; + } + $a() { + return "metadata" in this.Qa; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Helper to convert objects from bundles to model objects in the SDK. + */ class __PRIVATE_BundleConverterImpl { + constructor(e) { + this.serializer = e; + } + $s(e) { + return fromName(this.serializer, e); + } + /** + * Converts a BundleDocument to a MutableDocument. + */ Us(e) { + return e.metadata.exists ? __PRIVATE_fromDocument(this.serializer, e.document, !1) : MutableDocument.newNoDocument(this.$s(e.metadata.name), this.Ks(e.metadata.readTime)); + } + Ks(e) { + return __PRIVATE_fromVersion(e); + } +} + +/** + * A class to process the elements from a bundle, and optionally load them into local + * storage and provide progress update while loading. + */ class __PRIVATE_BundleLoader { + constructor(e, t) { + this.Ua = e, this.serializer = t, + /** Batched queries to be saved into storage */ + this.Ka = [], + /** Batched documents to be saved into storage */ + this.Wa = [], + /** The collection groups affected by this bundle. */ + this.collectionGroups = new Set, this.progress = __PRIVATE_bundleInitialProgress(e); + } + /** + * Returns the named queries that have been parsed from the SizeBundleElements added by + * calling {@link adSizedElement}. + */ get queries() { + return this.Ka; + } + /** + * Returns the BundledDocuments that have been parsed from the SizeBundleElements added by + * calling {@link addSizedElement}. + */ get documents() { + return this.Wa; + } + /** + * Adds an element from the bundle to the loader. + * + * Returns a new progress if adding the element leads to a new progress, + * otherwise returns null. + */ Ga(e) { + this.progress.bytesLoaded += e.byteLength; + let t = this.progress.documentsLoaded; + if (e.Qa.namedQuery) this.Ka.push(e.Qa.namedQuery); else if (e.Qa.documentMetadata) { + this.Wa.push({ + metadata: e.Qa.documentMetadata + }), e.Qa.documentMetadata.exists || ++t; + const n = ResourcePath.fromString(e.Qa.documentMetadata.name); + this.collectionGroups.add(n.get(n.length - 2)); + } else e.Qa.document && (this.Wa[this.Wa.length - 1].document = e.Qa.document, ++t); + return t !== this.progress.documentsLoaded ? (this.progress.documentsLoaded = t, + { + ...this.progress + }) : null; + } + za(e) { + const t = new Map, n = new __PRIVATE_BundleConverterImpl(this.serializer); + for (const r of e) if (r.metadata.queries) { + const e = n.$s(r.metadata.name); + for (const n of r.metadata.queries) { + const r = (t.get(n) || __PRIVATE_documentKeySet()).add(e); + t.set(n, r); + } + } + return t; + } + /** + * Update the progress to 'Success' and return the updated progress. + */ async ja(e) { + const t = await __PRIVATE_localStoreApplyBundledDocuments(e, new __PRIVATE_BundleConverterImpl(this.serializer), this.Wa, this.Ua.id), n = this.za(this.documents); + for (const t of this.Ka) await __PRIVATE_localStoreSaveNamedQuery(e, t, n.get(t.name)); + return this.progress.taskState = "Success", { + progress: this.progress, + Ja: this.collectionGroups, + Ha: t + }; + } +} + +/** + * Returns a `LoadBundleTaskProgress` representing the initial progress of + * loading a bundle. + */ function __PRIVATE_bundleInitialProgress(e) { + return { + taskState: "Running", + documentsLoaded: 0, + bytesLoaded: 0, + totalDocuments: e.totalDocuments, + totalBytes: e.totalBytes + }; +} + +/** + * Returns a `LoadBundleTaskProgress` representing the progress that the loading + * has succeeded. + */ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class __PRIVATE_AddedLimboDocument { + constructor(e) { + this.key = e; + } +} + +class __PRIVATE_RemovedLimboDocument { + constructor(e) { + this.key = e; + } +} + +/** + * View is responsible for computing the final merged truth of what docs are in + * a query. It gets notified of local and remote changes to docs, and applies + * the query filters and limits to determine the most correct possible results. + */ class __PRIVATE_View { + constructor(e, + /** Documents included in the remote target */ + t) { + this.query = e, this.Ya = t, this.Za = null, this.hasCachedResults = !1, + /** + * A flag whether the view is current with the backend. A view is considered + * current after it has seen the current flag from the backend and did not + * lose consistency within the watch stream (e.g. because of an existence + * filter mismatch). + */ + this.current = !1, + /** Documents in the view but not in the remote target */ + this.Xa = __PRIVATE_documentKeySet(), + /** Document Keys that have local changes */ + this.mutatedKeys = __PRIVATE_documentKeySet(), this.eu = __PRIVATE_newQueryComparator(e), + this.tu = new DocumentSet(this.eu); + } + /** + * The set of remote documents that the server has told us belongs to the target associated with + * this view. + */ get nu() { + return this.Ya; + } + /** + * Iterates over a set of doc changes, applies the query limit, and computes + * what the new results should be, what the changes were, and whether we may + * need to go back to the local cache for more results. Does not make any + * changes to the view. + * @param docChanges - The doc changes to apply to this view. + * @param previousChanges - If this is being called with a refill, then start + * with this set of docs and changes instead of the current view. + * @returns a new set of docs, changes, and refill flag. + */ ru(e, t) { + const n = t ? t.iu : new __PRIVATE_DocumentChangeSet, r = t ? t.tu : this.tu; + let i = t ? t.mutatedKeys : this.mutatedKeys, s = r, o = !1; + // Track the last doc in a (full) limit. This is necessary, because some + // update (a delete, or an update moving a doc past the old limit) might + // mean there is some other document in the local cache that either should + // come (1) between the old last limit doc and the new last document, in the + // case of updates, or (2) after the new last document, in the case of + // deletes. So we keep this doc at the old limit to compare the updates to. + // Note that this should never get used in a refill (when previousChanges is + // set), because there will only be adds -- no deletes or updates. + const _ = "F" /* LimitType.First */ === this.query.limitType && r.size === this.query.limit ? r.last() : null, a = "L" /* LimitType.Last */ === this.query.limitType && r.size === this.query.limit ? r.first() : null; + // Drop documents out to meet limit/limitToLast requirement. + if (e.inorderTraversal(((e, t) => { + const u = r.get(e), c = __PRIVATE_queryMatches(this.query, t) ? t : null, l = !!u && this.mutatedKeys.has(u.key), h = !!c && (c.hasLocalMutations || + // We only consider committed mutations for documents that were + // mutated during the lifetime of the view. + this.mutatedKeys.has(c.key) && c.hasCommittedMutations); + let P = !1; + // Calculate change + if (u && c) { + u.data.isEqual(c.data) ? l !== h && (n.track({ + type: 3 /* ChangeType.Metadata */ , + doc: c + }), P = !0) : this.su(u, c) || (n.track({ + type: 2 /* ChangeType.Modified */ , + doc: c + }), P = !0, (_ && this.eu(c, _) > 0 || a && this.eu(c, a) < 0) && ( + // This doc moved from inside the limit to outside the limit. + // That means there may be some other doc in the local cache + // that should be included instead. + o = !0)); + } else !u && c ? (n.track({ + type: 0 /* ChangeType.Added */ , + doc: c + }), P = !0) : u && !c && (n.track({ + type: 1 /* ChangeType.Removed */ , + doc: u + }), P = !0, (_ || a) && ( + // A doc was removed from a full limit query. We'll need to + // requery from the local cache to see if we know about some other + // doc that should be in the results. + o = !0)); + P && (c ? (s = s.add(c), i = h ? i.add(e) : i.delete(e)) : (s = s.delete(e), i = i.delete(e))); + })), null !== this.query.limit) for (;s.size > this.query.limit; ) { + const e = "F" /* LimitType.First */ === this.query.limitType ? s.last() : s.first(); + s = s.delete(e.key), i = i.delete(e.key), n.track({ + type: 1 /* ChangeType.Removed */ , + doc: e + }); + } + return { + tu: s, + iu: n, + Cs: o, + mutatedKeys: i + }; + } + su(e, t) { + // We suppress the initial change event for documents that were modified as + // part of a write acknowledgment (e.g. when the value of a server transform + // is applied) as Watch will send us the same document again. + // By suppressing the event, we only raise two user visible events (one with + // `hasPendingWrites` and the final state of the document) instead of three + // (one with `hasPendingWrites`, the modified document with + // `hasPendingWrites` and the final state of the document). + return e.hasLocalMutations && t.hasCommittedMutations && !t.hasLocalMutations; + } + /** + * Updates the view with the given ViewDocumentChanges and optionally updates + * limbo docs and sync state from the provided target change. + * @param docChanges - The set of changes to make to the view's docs. + * @param limboResolutionEnabled - Whether to update limbo documents based on + * this change. + * @param targetChange - A target change to apply for computing limbo docs and + * sync state. + * @param targetIsPendingReset - Whether the target is pending to reset due to + * existence filter mismatch. If not explicitly specified, it is treated + * equivalently to `false`. + * @returns A new ViewChange with the given docs, changes, and sync state. + */ + // PORTING NOTE: The iOS/Android clients always compute limbo document changes. + applyChanges(e, t, n, r) { + const i = this.tu; + this.tu = e.tu, this.mutatedKeys = e.mutatedKeys; + // Sort changes based on type and query comparator + const s = e.iu.ya(); + s.sort(((e, t) => function __PRIVATE_compareChangeType(e, t) { + const order = e => { + switch (e) { + case 0 /* ChangeType.Added */ : + return 1; + + case 2 /* ChangeType.Modified */ : + case 3 /* ChangeType.Metadata */ : + // A metadata change is converted to a modified change at the public + // api layer. Since we sort by document key and then change type, + // metadata and modified changes must be sorted equivalently. + return 2; + + case 1 /* ChangeType.Removed */ : + return 0; + + default: + return fail(20277, { + Rt: e + }); + } + }; + return order(e) - order(t); + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ (e.type, t.type) || this.eu(e.doc, t.doc))), this.ou(n), r = r ?? !1; + const o = t && !r ? this._u() : [], _ = 0 === this.Xa.size && this.current && !r ? 1 /* SyncState.Synced */ : 0 /* SyncState.Local */ , a = _ !== this.Za; + // We are at synced state if there is no limbo docs are waiting to be resolved, view is current + // with the backend, and the query is not pending to reset due to existence filter mismatch. + if (this.Za = _, 0 !== s.length || a) { + return { + snapshot: new ViewSnapshot(this.query, e.tu, i, s, e.mutatedKeys, 0 /* SyncState.Local */ === _, a, + /* excludesMetadataChanges= */ !1, !!n && n.resumeToken.approximateByteSize() > 0), + au: o + }; + } + // no changes + return { + au: o + }; + } + /** + * Applies an OnlineState change to the view, potentially generating a + * ViewChange if the view's syncState changes as a result. + */ va(e) { + return this.current && "Offline" /* OnlineState.Offline */ === e ? ( + // If we're offline, set `current` to false and then call applyChanges() + // to refresh our syncState and generate a ViewChange as appropriate. We + // are guaranteed to get a new TargetChange that sets `current` back to + // true once the client is back online. + this.current = !1, this.applyChanges({ + tu: this.tu, + iu: new __PRIVATE_DocumentChangeSet, + mutatedKeys: this.mutatedKeys, + Cs: !1 + }, + /* limboResolutionEnabled= */ !1)) : { + au: [] + }; + } + /** + * Returns whether the doc for the given key should be in limbo. + */ uu(e) { + // If the remote end says it's part of this query, it's not in limbo. + return !this.Ya.has(e) && ( + // The local store doesn't think it's a result, so it shouldn't be in limbo. + !!this.tu.has(e) && !this.tu.get(e).hasLocalMutations); + } + /** + * Updates syncedDocuments, current, and limbo docs based on the given change. + * Returns the list of changes to which docs are in limbo. + */ ou(e) { + e && (e.addedDocuments.forEach((e => this.Ya = this.Ya.add(e))), e.modifiedDocuments.forEach((e => {})), + e.removedDocuments.forEach((e => this.Ya = this.Ya.delete(e))), this.current = e.current); + } + _u() { + // We can only determine limbo documents when we're in-sync with the server. + if (!this.current) return []; + // TODO(klimt): Do this incrementally so that it's not quadratic when + // updating many documents. + const e = this.Xa; + this.Xa = __PRIVATE_documentKeySet(), this.tu.forEach((e => { + this.uu(e.key) && (this.Xa = this.Xa.add(e.key)); + })); + // Diff the new limbo docs with the old limbo docs. + const t = []; + return e.forEach((e => { + this.Xa.has(e) || t.push(new __PRIVATE_RemovedLimboDocument(e)); + })), this.Xa.forEach((n => { + e.has(n) || t.push(new __PRIVATE_AddedLimboDocument(n)); + })), t; + } + /** + * Update the in-memory state of the current view with the state read from + * persistence. + * + * We update the query view whenever a client's primary status changes: + * - When a client transitions from primary to secondary, it can miss + * LocalStorage updates and its query views may temporarily not be + * synchronized with the state on disk. + * - For secondary to primary transitions, the client needs to update the list + * of `syncedDocuments` since secondary clients update their query views + * based purely on synthesized RemoteEvents. + * + * @param queryResult.documents - The documents that match the query according + * to the LocalStore. + * @param queryResult.remoteKeys - The keys of the documents that match the + * query according to the backend. + * + * @returns The ViewChange that resulted from this synchronization. + */ + // PORTING NOTE: Multi-tab only. + cu(e) { + this.Ya = e.Qs, this.Xa = __PRIVATE_documentKeySet(); + const t = this.ru(e.documents); + return this.applyChanges(t, /* limboResolutionEnabled= */ !0); + } + /** + * Returns a view snapshot as if this query was just listened to. Contains + * a document add for every existing document and the `fromCache` and + * `hasPendingWrites` status of the already established view. + */ + // PORTING NOTE: Multi-tab only. + lu() { + return ViewSnapshot.fromInitialDocuments(this.query, this.tu, this.mutatedKeys, 0 /* SyncState.Local */ === this.Za, this.hasCachedResults); + } +} + +const sn = "SyncEngine"; + +/** + * QueryView contains all of the data that SyncEngine needs to keep track of for + * a particular query. + */ class __PRIVATE_QueryView { + constructor( + /** + * The query itself. + */ + e, + /** + * The target number created by the client that is used in the watch + * stream to identify this query. + */ + t, + /** + * The view is responsible for computing the final merged truth of what + * docs are in the query. It gets notified of local and remote changes, + * and applies the query filters and limits to determine the most correct + * possible results. + */ + n) { + this.query = e, this.targetId = t, this.view = n; + } +} + +/** Tracks a limbo resolution. */ class LimboResolution { + constructor(e) { + this.key = e, + /** + * Set to true once we've received a document. This is used in + * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to + * decide whether it needs to manufacture a delete event for the target once + * the target is CURRENT. + */ + this.hu = !1; + } +} + +/** + * An implementation of `SyncEngine` coordinating with other parts of SDK. + * + * The parts of SyncEngine that act as a callback to RemoteStore need to be + * registered individually. This is done in `syncEngineWrite()` and + * `syncEngineListen()` (as well as `applyPrimaryState()`) as these methods + * serve as entry points to RemoteStore's functionality. + * + * Note: some field defined in this class might have public access level, but + * the class is not exported so they are only accessible from this module. + * This is useful to implement optional features (like bundles) in free + * functions, such that they are tree-shakeable. + */ class __PRIVATE_SyncEngineImpl { + constructor(e, t, n, + // PORTING NOTE: Manages state synchronization in multi-tab environments. + r, i, s) { + this.localStore = e, this.remoteStore = t, this.eventManager = n, this.sharedClientState = r, + this.currentUser = i, this.maxConcurrentLimboResolutions = s, this.Pu = {}, this.Tu = new ObjectMap((e => __PRIVATE_canonifyQuery(e)), __PRIVATE_queryEquals), + this.Iu = new Map, + /** + * The keys of documents that are in limbo for which we haven't yet started a + * limbo resolution query. The strings in this set are the result of calling + * `key.path.canonicalString()` where `key` is a `DocumentKey` object. + * + * The `Set` type was chosen because it provides efficient lookup and removal + * of arbitrary elements and it also maintains insertion order, providing the + * desired queue-like FIFO semantics. + */ + this.Eu = new Set, + /** + * Keeps track of the target ID for each document that is in limbo with an + * active target. + */ + this.du = new SortedMap(DocumentKey.comparator), + /** + * Keeps track of the information about an active limbo resolution for each + * active target ID that was started for the purpose of limbo resolution. + */ + this.Au = new Map, this.Ru = new __PRIVATE_ReferenceSet, + /** Stores user completion handlers, indexed by User and BatchId. */ + this.Vu = {}, + /** Stores user callbacks waiting for all pending writes to be acknowledged. */ + this.mu = new Map, this.fu = __PRIVATE_TargetIdGenerator.cr(), this.onlineState = "Unknown" /* OnlineState.Unknown */ , + // The primary state is set to `true` or `false` immediately after Firestore + // startup. In the interim, a client should only be considered primary if + // `isPrimary` is true. + this.gu = void 0; + } + get isPrimaryClient() { + return !0 === this.gu; + } +} + +/** + * Initiates the new listen, resolves promise when listen enqueued to the + * server. All the subsequent view snapshots or errors are sent to the + * subscribed handlers. Returns the initial snapshot. + */ +async function __PRIVATE_syncEngineListen(e, t, n = !0) { + const r = __PRIVATE_ensureWatchCallbacks(e); + let i; + const s = r.Tu.get(t); + return s ? ( + // PORTING NOTE: With Multi-Tab Web, it is possible that a query view + // already exists when EventManager calls us for the first time. This + // happens when the primary tab is already listening to this query on + // behalf of another tab and the user of the primary also starts listening + // to the query. EventManager will not have an assigned target ID in this + // case and calls `listen` to obtain this ID. + r.sharedClientState.addLocalQueryTarget(s.targetId), i = s.view.lu()) : i = await __PRIVATE_allocateTargetAndMaybeListen(r, t, n, + /** shouldInitializeView= */ !0), i; +} + +/** Query has been listening to the cache, and tries to initiate the remote store listen */ async function __PRIVATE_triggerRemoteStoreListen(e, t) { + const n = __PRIVATE_ensureWatchCallbacks(e); + await __PRIVATE_allocateTargetAndMaybeListen(n, t, + /** shouldListenToRemote= */ !0, + /** shouldInitializeView= */ !1); +} + +async function __PRIVATE_allocateTargetAndMaybeListen(e, t, n, r) { + const i = await __PRIVATE_localStoreAllocateTarget(e.localStore, __PRIVATE_queryToTarget(t)), s = i.targetId, o = e.sharedClientState.addLocalQueryTarget(s, n); + let _; + return r && (_ = await __PRIVATE_initializeViewAndComputeSnapshot(e, t, s, "current" === o, i.resumeToken)), + e.isPrimaryClient && n && __PRIVATE_remoteStoreListen(e.remoteStore, i), _; +} + +/** + * Registers a view for a previously unknown query and computes its initial + * snapshot. + */ async function __PRIVATE_initializeViewAndComputeSnapshot(e, t, n, r, i) { + // PORTING NOTE: On Web only, we inject the code that registers new Limbo + // targets based on view changes. This allows us to only depend on Limbo + // changes when user code includes queries. + e.pu = (t, n, r) => async function __PRIVATE_applyDocChanges(e, t, n, r) { + let i = t.view.ru(n); + i.Cs && ( + // The query has a limit and some docs were removed, so we need + // to re-run the query against the local store to make sure we + // didn't lose any good docs that had been past the limit. + i = await __PRIVATE_localStoreExecuteQuery(e.localStore, t.query, + /* usePreviousResults= */ !1).then((({documents: e}) => t.view.ru(e, i)))); + const s = r && r.targetChanges.get(t.targetId), o = r && null != r.targetMismatches.get(t.targetId), _ = t.view.applyChanges(i, + /* limboResolutionEnabled= */ e.isPrimaryClient, s, o); + return __PRIVATE_updateTrackedLimbos(e, t.targetId, _.au), _.snapshot; + }(e, t, n, r); + const s = await __PRIVATE_localStoreExecuteQuery(e.localStore, t, + /* usePreviousResults= */ !0), o = new __PRIVATE_View(t, s.Qs), _ = o.ru(s.documents), a = TargetChange.createSynthesizedTargetChangeForCurrentChange(n, r && "Offline" /* OnlineState.Offline */ !== e.onlineState, i), u = o.applyChanges(_, + /* limboResolutionEnabled= */ e.isPrimaryClient, a); + __PRIVATE_updateTrackedLimbos(e, n, u.au); + const c = new __PRIVATE_QueryView(t, n, o); + return e.Tu.set(t, c), e.Iu.has(n) ? e.Iu.get(n).push(t) : e.Iu.set(n, [ t ]), u.snapshot; +} + +/** Stops listening to the query. */ async function __PRIVATE_syncEngineUnlisten(e, t, n) { + const r = __PRIVATE_debugCast(e), i = r.Tu.get(t), s = r.Iu.get(i.targetId); + if (s.length > 1) return r.Iu.set(i.targetId, s.filter((e => !__PRIVATE_queryEquals(e, t)))), + void r.Tu.delete(t); + // No other queries are mapped to the target, clean up the query and the target. + if (r.isPrimaryClient) { + // We need to remove the local query target first to allow us to verify + // whether any other client is still interested in this target. + r.sharedClientState.removeLocalQueryTarget(i.targetId); + r.sharedClientState.isActiveQueryTarget(i.targetId) || await __PRIVATE_localStoreReleaseTarget(r.localStore, i.targetId, + /*keepPersistedTargetData=*/ !1).then((() => { + r.sharedClientState.clearQueryState(i.targetId), n && __PRIVATE_remoteStoreUnlisten(r.remoteStore, i.targetId), + __PRIVATE_removeAndCleanupTarget(r, i.targetId); + })).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss); + } else __PRIVATE_removeAndCleanupTarget(r, i.targetId), await __PRIVATE_localStoreReleaseTarget(r.localStore, i.targetId, + /*keepPersistedTargetData=*/ !0); +} + +/** Unlistens to the remote store while still listening to the cache. */ async function __PRIVATE_triggerRemoteStoreUnlisten(e, t) { + const n = __PRIVATE_debugCast(e), r = n.Tu.get(t), i = n.Iu.get(r.targetId); + n.isPrimaryClient && 1 === i.length && ( + // PORTING NOTE: Unregister the target ID with local Firestore client as + // watch target. + n.sharedClientState.removeLocalQueryTarget(r.targetId), __PRIVATE_remoteStoreUnlisten(n.remoteStore, r.targetId)); +} + +/** + * Initiates the write of local mutation batch which involves adding the + * writes to the mutation queue, notifying the remote store about new + * mutations and raising events for any changes this write caused. + * + * The promise returned by this call is resolved when the above steps + * have completed, *not* when the write was acked by the backend. The + * userCallback is resolved once the write was acked/rejected by the + * backend (or failed locally for any other reason). + */ async function __PRIVATE_syncEngineWrite(e, t, n) { + const r = __PRIVATE_syncEngineEnsureWriteCallbacks(e); + try { + const e = await function __PRIVATE_localStoreWriteLocally(e, t) { + const n = __PRIVATE_debugCast(e), r = Timestamp.now(), i = t.reduce(((e, t) => e.add(t.key)), __PRIVATE_documentKeySet()); + let s, o; + return n.persistence.runTransaction("Locally write mutations", "readwrite", (e => { + // Figure out which keys do not have a remote version in the cache, this + // is needed to create the right overlay mutation: if no remote version + // presents, we do not need to create overlays as patch mutations. + // TODO(Overlay): Is there a better way to determine this? Using the + // document version does not work because local mutations set them back + // to 0. + let _ = __PRIVATE_mutableDocumentMap(), a = __PRIVATE_documentKeySet(); + return n.Ns.getEntries(e, i).next((e => { + _ = e, _.forEach(((e, t) => { + t.isValidDocument() || (a = a.add(e)); + })); + })).next((() => n.localDocuments.getOverlayedDocuments(e, _))).next((i => { + s = i; + // For non-idempotent mutations (such as `FieldValue.increment()`), + // we record the base state in a separate patch mutation. This is + // later used to guarantee consistent values and prevents flicker + // even if the backend sends us an update that already includes our + // transform. + const o = []; + for (const e of t) { + const t = __PRIVATE_mutationExtractBaseValue(e, s.get(e.key).overlayedDocument); + null != t && + // NOTE: The base state should only be applied if there's some + // existing document to override, so use a Precondition of + // exists=true + o.push(new __PRIVATE_PatchMutation(e.key, t, __PRIVATE_extractFieldMask(t.value.mapValue), Precondition.exists(!0))); + } + return n.mutationQueue.addMutationBatch(e, r, o, t); + })).next((t => { + o = t; + const r = t.applyToLocalDocumentSet(s, a); + return n.documentOverlayCache.saveOverlays(e, t.batchId, r); + })); + })).then((() => ({ + batchId: o.batchId, + changes: __PRIVATE_convertOverlayedDocumentMapToDocumentMap(s) + }))); + }(r.localStore, t); + r.sharedClientState.addPendingMutation(e.batchId), function __PRIVATE_addMutationCallback(e, t, n) { + let r = e.Vu[e.currentUser.toKey()]; + r || (r = new SortedMap(__PRIVATE_primitiveComparator)); + r = r.insert(t, n), e.Vu[e.currentUser.toKey()] = r; + } + /** + * Resolves or rejects the user callback for the given batch and then discards + * it. + */ (r, e.batchId, n), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(r, e.changes), + await __PRIVATE_fillWritePipeline(r.remoteStore); + } catch (e) { + // If we can't persist the mutation, we reject the user callback and + // don't send the mutation. The user can then retry the write. + const t = __PRIVATE_wrapInUserErrorIfRecoverable(e, "Failed to persist write"); + n.reject(t); + } +} + +/** + * Applies one remote event to the sync engine, notifying any views of the + * changes, and releasing any pending mutation batches that would become + * visible because of the snapshot version the remote event contains. + */ async function __PRIVATE_syncEngineApplyRemoteEvent(e, t) { + const n = __PRIVATE_debugCast(e); + try { + const e = await __PRIVATE_localStoreApplyRemoteEventToLocalCache(n.localStore, t); + // Update `receivedDocument` as appropriate for any limbo targets. + t.targetChanges.forEach(((e, t) => { + const r = n.Au.get(t); + r && ( + // Since this is a limbo resolution lookup, it's for a single document + // and it could be added, modified, or removed, but not a combination. + __PRIVATE_hardAssert(e.addedDocuments.size + e.modifiedDocuments.size + e.removedDocuments.size <= 1, 22616), + e.addedDocuments.size > 0 ? r.hu = !0 : e.modifiedDocuments.size > 0 ? __PRIVATE_hardAssert(r.hu, 14607) : e.removedDocuments.size > 0 && (__PRIVATE_hardAssert(r.hu, 42227), + r.hu = !1)); + })), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e, t); + } catch (e) { + await __PRIVATE_ignoreIfPrimaryLeaseLoss(e); + } +} + +/** + * Applies an OnlineState change to the sync engine and notifies any views of + * the change. + */ function __PRIVATE_syncEngineApplyOnlineStateChange(e, t, n) { + const r = __PRIVATE_debugCast(e); + // If we are the secondary client, we explicitly ignore the remote store's + // online state (the local client may go offline, even though the primary + // tab remains online) and only apply the primary tab's online state from + // SharedClientState. + if (r.isPrimaryClient && 0 /* OnlineStateSource.RemoteStore */ === n || !r.isPrimaryClient && 1 /* OnlineStateSource.SharedClientState */ === n) { + const e = []; + r.Tu.forEach(((n, r) => { + const i = r.view.va(t); + i.snapshot && e.push(i.snapshot); + })), function __PRIVATE_eventManagerOnOnlineStateChange(e, t) { + const n = __PRIVATE_debugCast(e); + n.onlineState = t; + let r = !1; + n.queries.forEach(((e, n) => { + for (const e of n.Sa) + // Run global snapshot listeners if a consistent snapshot has been emitted. + e.va(t) && (r = !0); + })), r && __PRIVATE_raiseSnapshotsInSyncEvent(n); + }(r.eventManager, t), e.length && r.Pu.H_(e), r.onlineState = t, r.isPrimaryClient && r.sharedClientState.setOnlineState(t); + } +} + +/** + * Rejects the listen for the given targetID. This can be triggered by the + * backend for any active target. + * + * @param syncEngine - The sync engine implementation. + * @param targetId - The targetID corresponds to one previously initiated by the + * user as part of TargetData passed to listen() on RemoteStore. + * @param err - A description of the condition that has forced the rejection. + * Nearly always this will be an indication that the user is no longer + * authorized to see the data matching the target. + */ async function __PRIVATE_syncEngineRejectListen(e, t, n) { + const r = __PRIVATE_debugCast(e); + // PORTING NOTE: Multi-tab only. + r.sharedClientState.updateQueryState(t, "rejected", n); + const i = r.Au.get(t), s = i && i.key; + if (s) { + // TODO(klimt): We really only should do the following on permission + // denied errors, but we don't have the cause code here. + // It's a limbo doc. Create a synthetic event saying it was deleted. + // This is kind of a hack. Ideally, we would have a method in the local + // store to purge a document. However, it would be tricky to keep all of + // the local store's invariants with another method. + let e = new SortedMap(DocumentKey.comparator); + // TODO(b/217189216): This limbo document should ideally have a read time, + // so that it is picked up by any read-time based scans. The backend, + // however, does not send a read time for target removals. + e = e.insert(s, MutableDocument.newNoDocument(s, SnapshotVersion.min())); + const n = __PRIVATE_documentKeySet().add(s), i = new RemoteEvent(SnapshotVersion.min(), + /* targetChanges= */ new Map, + /* targetMismatches= */ new SortedMap(__PRIVATE_primitiveComparator), e, n); + await __PRIVATE_syncEngineApplyRemoteEvent(r, i), + // Since this query failed, we won't want to manually unlisten to it. + // We only remove it from bookkeeping after we successfully applied the + // RemoteEvent. If `applyRemoteEvent()` throws, we want to re-listen to + // this query when the RemoteStore restarts the Watch stream, which should + // re-trigger the target failure. + r.du = r.du.remove(s), r.Au.delete(t), __PRIVATE_pumpEnqueuedLimboResolutions(r); + } else await __PRIVATE_localStoreReleaseTarget(r.localStore, t, + /* keepPersistedTargetData */ !1).then((() => __PRIVATE_removeAndCleanupTarget(r, t, n))).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss); +} + +async function __PRIVATE_syncEngineApplySuccessfulWrite(e, t) { + const n = __PRIVATE_debugCast(e), r = t.batch.batchId; + try { + const e = await __PRIVATE_localStoreAcknowledgeBatch(n.localStore, t); + // The local store may or may not be able to apply the write result and + // raise events immediately (depending on whether the watcher is caught + // up), so we raise user callbacks first so that they consistently happen + // before listen events. + __PRIVATE_processUserCallback(n, r, /*error=*/ null), __PRIVATE_triggerPendingWritesCallbacks(n, r), + n.sharedClientState.updateMutationState(r, "acknowledged"), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e); + } catch (e) { + await __PRIVATE_ignoreIfPrimaryLeaseLoss(e); + } +} + +async function __PRIVATE_syncEngineRejectFailedWrite(e, t, n) { + const r = __PRIVATE_debugCast(e); + try { + const e = await function __PRIVATE_localStoreRejectBatch(e, t) { + const n = __PRIVATE_debugCast(e); + return n.persistence.runTransaction("Reject batch", "readwrite-primary", (e => { + let r; + return n.mutationQueue.lookupMutationBatch(e, t).next((t => (__PRIVATE_hardAssert(null !== t, 37113), + r = t.keys(), n.mutationQueue.removeMutationBatch(e, t)))).next((() => n.mutationQueue.performConsistencyCheck(e))).next((() => n.documentOverlayCache.removeOverlaysForBatchId(e, r, t))).next((() => n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e, r))).next((() => n.localDocuments.getDocuments(e, r))); + })); + } + /** + * Returns the largest (latest) batch id in mutation queue that is pending + * server response. + * + * Returns `BATCHID_UNKNOWN` if the queue is empty. + */ (r.localStore, t); + // The local store may or may not be able to apply the write result and + // raise events immediately (depending on whether the watcher is caught up), + // so we raise user callbacks first so that they consistently happen before + // listen events. + __PRIVATE_processUserCallback(r, t, n), __PRIVATE_triggerPendingWritesCallbacks(r, t), + r.sharedClientState.updateMutationState(t, "rejected", n), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(r, e); + } catch (n) { + await __PRIVATE_ignoreIfPrimaryLeaseLoss(n); + } +} + +/** + * Registers a user callback that resolves when all pending mutations at the moment of calling + * are acknowledged . + */ async function __PRIVATE_syncEngineRegisterPendingWritesCallback(e, t) { + const n = __PRIVATE_debugCast(e); + __PRIVATE_canUseNetwork(n.remoteStore) || __PRIVATE_logDebug(sn, "The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled."); + try { + const e = await function __PRIVATE_localStoreGetHighestUnacknowledgedBatchId(e) { + const t = __PRIVATE_debugCast(e); + return t.persistence.runTransaction("Get highest unacknowledged batch id", "readonly", (e => t.mutationQueue.getHighestUnacknowledgedBatchId(e))); + }(n.localStore); + if (e === j) + // Trigger the callback right away if there is no pending writes at the moment. + return void t.resolve(); + const r = n.mu.get(e) || []; + r.push(t), n.mu.set(e, r); + } catch (e) { + const n = __PRIVATE_wrapInUserErrorIfRecoverable(e, "Initialization of waitForPendingWrites() operation failed"); + t.reject(n); + } +} + +/** + * Triggers the callbacks that are waiting for this batch id to get acknowledged by server, + * if there are any. + */ function __PRIVATE_triggerPendingWritesCallbacks(e, t) { + (e.mu.get(t) || []).forEach((e => { + e.resolve(); + })), e.mu.delete(t); +} + +/** Reject all outstanding callbacks waiting for pending writes to complete. */ function __PRIVATE_processUserCallback(e, t, n) { + const r = __PRIVATE_debugCast(e); + let i = r.Vu[r.currentUser.toKey()]; + // NOTE: Mutations restored from persistence won't have callbacks, so it's + // okay for there to be no callback for this ID. + if (i) { + const e = i.get(t); + e && (n ? e.reject(n) : e.resolve(), i = i.remove(t)), r.Vu[r.currentUser.toKey()] = i; + } +} + +function __PRIVATE_removeAndCleanupTarget(e, t, n = null) { + e.sharedClientState.removeLocalQueryTarget(t); + for (const r of e.Iu.get(t)) e.Tu.delete(r), n && e.Pu.yu(r, n); + if (e.Iu.delete(t), e.isPrimaryClient) { + e.Ru.jr(t).forEach((t => { + e.Ru.containsKey(t) || + // We removed the last reference for this key + __PRIVATE_removeLimboTarget(e, t); + })); + } +} + +function __PRIVATE_removeLimboTarget(e, t) { + e.Eu.delete(t.path.canonicalString()); + // It's possible that the target already got removed because the query failed. In that case, + // the key won't exist in `limboTargetsByKey`. Only do the cleanup if we still have the target. + const n = e.du.get(t); + null !== n && (__PRIVATE_remoteStoreUnlisten(e.remoteStore, n), e.du = e.du.remove(t), + e.Au.delete(n), __PRIVATE_pumpEnqueuedLimboResolutions(e)); +} + +function __PRIVATE_updateTrackedLimbos(e, t, n) { + for (const r of n) if (r instanceof __PRIVATE_AddedLimboDocument) e.Ru.addReference(r.key, t), + __PRIVATE_trackLimboChange(e, r); else if (r instanceof __PRIVATE_RemovedLimboDocument) { + __PRIVATE_logDebug(sn, "Document no longer in limbo: " + r.key), e.Ru.removeReference(r.key, t); + e.Ru.containsKey(r.key) || + // We removed the last reference for this key + __PRIVATE_removeLimboTarget(e, r.key); + } else fail(19791, { + wu: r + }); +} + +function __PRIVATE_trackLimboChange(e, t) { + const n = t.key, r = n.path.canonicalString(); + e.du.get(n) || e.Eu.has(r) || (__PRIVATE_logDebug(sn, "New document in limbo: " + n), + e.Eu.add(r), __PRIVATE_pumpEnqueuedLimboResolutions(e)); +} + +/** + * Starts listens for documents in limbo that are enqueued for resolution, + * subject to a maximum number of concurrent resolutions. + * + * Without bounding the number of concurrent resolutions, the server can fail + * with "resource exhausted" errors which can lead to pathological client + * behavior as seen in https://github.com/firebase/firebase-js-sdk/issues/2683. + */ function __PRIVATE_pumpEnqueuedLimboResolutions(e) { + for (;e.Eu.size > 0 && e.du.size < e.maxConcurrentLimboResolutions; ) { + const t = e.Eu.values().next().value; + e.Eu.delete(t); + const n = new DocumentKey(ResourcePath.fromString(t)), r = e.fu.next(); + e.Au.set(r, new LimboResolution(n)), e.du = e.du.insert(n, r), __PRIVATE_remoteStoreListen(e.remoteStore, new TargetData(__PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(n.path)), r, "TargetPurposeLimboResolution" /* TargetPurpose.LimboResolution */ , __PRIVATE_ListenSequence.ce)); + } +} + +async function __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(e, t, n) { + const r = __PRIVATE_debugCast(e), i = [], s = [], o = []; + r.Tu.isEmpty() || (r.Tu.forEach(((e, _) => { + o.push(r.pu(_, t, n).then((e => { + // If there are changes, or we are handling a global snapshot, notify + // secondary clients to update query state. + if ((e || n) && r.isPrimaryClient) { + // Query state is set to `current` if: + // - There is a view change and it is up-to-date, or, + // - There is a global snapshot, the Target is current, and no changes to be resolved + const t = e ? !e.fromCache : n?.targetChanges.get(_.targetId)?.current; + r.sharedClientState.updateQueryState(_.targetId, t ? "current" : "not-current"); + } + // Update views if there are actual changes. + if (e) { + i.push(e); + const t = __PRIVATE_LocalViewChanges.As(_.targetId, e); + s.push(t); + } + }))); + })), await Promise.all(o), r.Pu.H_(i), await async function __PRIVATE_localStoreNotifyLocalViewChanges(e, t) { + const n = __PRIVATE_debugCast(e); + try { + await n.persistence.runTransaction("notifyLocalViewChanges", "readwrite", (e => PersistencePromise.forEach(t, (t => PersistencePromise.forEach(t.Es, (r => n.persistence.referenceDelegate.addReference(e, t.targetId, r))).next((() => PersistencePromise.forEach(t.ds, (r => n.persistence.referenceDelegate.removeReference(e, t.targetId, r))))))))); + } catch (e) { + if (!__PRIVATE_isIndexedDbTransactionError(e)) throw e; + // If `notifyLocalViewChanges` fails, we did not advance the sequence + // number for the documents that were included in this transaction. + // This might trigger them to be deleted earlier than they otherwise + // would have, but it should not invalidate the integrity of the data. + __PRIVATE_logDebug(Ut, "Failed to update sequence numbers: " + e); + } + for (const e of t) { + const t = e.targetId; + if (!e.fromCache) { + const e = n.Ms.get(t), r = e.snapshotVersion, i = e.withLastLimboFreeSnapshotVersion(r); + // Advance the last limbo free snapshot version + n.Ms = n.Ms.insert(t, i); + } + } + }(r.localStore, s)); +} + +async function __PRIVATE_syncEngineHandleCredentialChange(e, t) { + const n = __PRIVATE_debugCast(e); + if (!n.currentUser.isEqual(t)) { + __PRIVATE_logDebug(sn, "User change. New user:", t.toKey()); + const e = await __PRIVATE_localStoreHandleUserChange(n.localStore, t); + n.currentUser = t, + // Fails tasks waiting for pending writes requested by previous user. + function __PRIVATE_rejectOutstandingPendingWritesCallbacks(e, t) { + e.mu.forEach((e => { + e.forEach((e => { + e.reject(new FirestoreError(N.CANCELLED, t)); + })); + })), e.mu.clear(); + }(n, "'waitForPendingWrites' promise is rejected due to a user change."), + // TODO(b/114226417): Consider calling this only in the primary tab. + n.sharedClientState.handleUserChange(t, e.removedBatchIds, e.addedBatchIds), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e.Ls); + } +} + +function __PRIVATE_syncEngineGetRemoteKeysForTarget(e, t) { + const n = __PRIVATE_debugCast(e), r = n.Au.get(t); + if (r && r.hu) return __PRIVATE_documentKeySet().add(r.key); + { + let e = __PRIVATE_documentKeySet(); + const r = n.Iu.get(t); + if (!r) return e; + for (const t of r) { + const r = n.Tu.get(t); + e = e.unionWith(r.view.nu); + } + return e; + } +} + +/** + * Reconcile the list of synced documents in an existing view with those + * from persistence. + */ async function __PRIVATE_synchronizeViewAndComputeSnapshot(e, t) { + const n = __PRIVATE_debugCast(e), r = await __PRIVATE_localStoreExecuteQuery(n.localStore, t.query, + /* usePreviousResults= */ !0), i = t.view.cu(r); + return n.isPrimaryClient && __PRIVATE_updateTrackedLimbos(n, t.targetId, i.au), + i; +} + +/** + * Retrieves newly changed documents from remote document cache and raises + * snapshots if needed. + */ +// PORTING NOTE: Multi-Tab only. +async function __PRIVATE_syncEngineSynchronizeWithChangedDocuments(e, t) { + const n = __PRIVATE_debugCast(e); + return __PRIVATE_localStoreGetNewDocumentChanges(n.localStore, t).then((e => __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e))); +} + +/** Applies a mutation state to an existing batch. */ +// PORTING NOTE: Multi-Tab only. +async function __PRIVATE_syncEngineApplyBatchState(e, t, n, r) { + const i = __PRIVATE_debugCast(e), s = await function __PRIVATE_localStoreLookupMutationDocuments(e, t) { + const n = __PRIVATE_debugCast(e), r = __PRIVATE_debugCast(n.mutationQueue); + return n.persistence.runTransaction("Lookup mutation documents", "readonly", (e => r.er(e, t).next((t => t ? n.localDocuments.getDocuments(e, t) : PersistencePromise.resolve(null))))); + } + // PORTING NOTE: Multi-Tab only. + (i.localStore, t); + null !== s ? ("pending" === n ? + // If we are the primary client, we need to send this write to the + // backend. Secondary clients will ignore these writes since their remote + // connection is disabled. + await __PRIVATE_fillWritePipeline(i.remoteStore) : "acknowledged" === n || "rejected" === n ? ( + // NOTE: Both these methods are no-ops for batches that originated from + // other clients. + __PRIVATE_processUserCallback(i, t, r || null), __PRIVATE_triggerPendingWritesCallbacks(i, t), + function __PRIVATE_localStoreRemoveCachedMutationBatchMetadata(e, t) { + __PRIVATE_debugCast(__PRIVATE_debugCast(e).mutationQueue).ir(t); + } + // PORTING NOTE: Multi-Tab only. + (i.localStore, t)) : fail(6720, "Unknown batchState", { + Su: n + }), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(i, s)) : + // A throttled tab may not have seen the mutation before it was completed + // and removed from the mutation queue, in which case we won't have cached + // the affected documents. In this case we can safely ignore the update + // since that means we didn't apply the mutation locally at all (if we + // had, we would have cached the affected documents), and so we will just + // see any resulting document changes via normal remote document updates + // as applicable. + __PRIVATE_logDebug(sn, "Cannot apply mutation batch with id: " + t); +} + +/** Applies a query target change from a different tab. */ +// PORTING NOTE: Multi-Tab only. +async function __PRIVATE_syncEngineApplyPrimaryState(e, t) { + const n = __PRIVATE_debugCast(e); + if (__PRIVATE_ensureWatchCallbacks(n), __PRIVATE_syncEngineEnsureWriteCallbacks(n), + !0 === t && !0 !== n.gu) { + // Secondary tabs only maintain Views for their local listeners and the + // Views internal state may not be 100% populated (in particular + // secondary tabs don't track syncedDocuments, the set of documents the + // server considers to be in the target). So when a secondary becomes + // primary, we need to need to make sure that all views for all targets + // match the state on disk. + const e = n.sharedClientState.getAllActiveQueryTargets(), t = await __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(n, e.toArray()); + n.gu = !0, await __PRIVATE_remoteStoreApplyPrimaryState(n.remoteStore, !0); + for (const e of t) __PRIVATE_remoteStoreListen(n.remoteStore, e); + } else if (!1 === t && !1 !== n.gu) { + const e = []; + let t = Promise.resolve(); + n.Iu.forEach(((r, i) => { + n.sharedClientState.isLocalQueryTarget(i) ? e.push(i) : t = t.then((() => (__PRIVATE_removeAndCleanupTarget(n, i), + __PRIVATE_localStoreReleaseTarget(n.localStore, i, + /*keepPersistedTargetData=*/ !0)))), __PRIVATE_remoteStoreUnlisten(n.remoteStore, i); + })), await t, await __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(n, e), + // PORTING NOTE: Multi-Tab only. + function __PRIVATE_resetLimboDocuments(e) { + const t = __PRIVATE_debugCast(e); + t.Au.forEach(((e, n) => { + __PRIVATE_remoteStoreUnlisten(t.remoteStore, n); + })), t.Ru.Jr(), t.Au = new Map, t.du = new SortedMap(DocumentKey.comparator); + } + /** + * Reconcile the query views of the provided query targets with the state from + * persistence. Raises snapshots for any changes that affect the local + * client and returns the updated state of all target's query data. + * + * @param syncEngine - The sync engine implementation + * @param targets - the list of targets with views that need to be recomputed + * @param transitionToPrimary - `true` iff the tab transitions from a secondary + * tab to a primary tab + */ + // PORTING NOTE: Multi-Tab only. + (n), n.gu = !1, await __PRIVATE_remoteStoreApplyPrimaryState(n.remoteStore, !1); + } +} + +async function __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(e, t, n) { + const r = __PRIVATE_debugCast(e), i = [], s = []; + for (const e of t) { + let t; + const n = r.Iu.get(e); + if (n && 0 !== n.length) { + // For queries that have a local View, we fetch their current state + // from LocalStore (as the resume token and the snapshot version + // might have changed) and reconcile their views with the persisted + // state (the list of syncedDocuments may have gotten out of sync). + t = await __PRIVATE_localStoreAllocateTarget(r.localStore, __PRIVATE_queryToTarget(n[0])); + for (const e of n) { + const t = r.Tu.get(e), n = await __PRIVATE_synchronizeViewAndComputeSnapshot(r, t); + n.snapshot && s.push(n.snapshot); + } + } else { + // For queries that never executed on this client, we need to + // allocate the target in LocalStore and initialize a new View. + const n = await __PRIVATE_localStoreGetCachedTarget(r.localStore, e); + t = await __PRIVATE_localStoreAllocateTarget(r.localStore, n), await __PRIVATE_initializeViewAndComputeSnapshot(r, __PRIVATE_synthesizeTargetToQuery(n), e, + /*current=*/ !1, t.resumeToken); + } + i.push(t); + } + return r.Pu.H_(s), i; +} + +/** + * Creates a `Query` object from the specified `Target`. There is no way to + * obtain the original `Query`, so we synthesize a `Query` from the `Target` + * object. + * + * The synthesized result might be different from the original `Query`, but + * since the synthesized `Query` should return the same results as the + * original one (only the presentation of results might differ), the potential + * difference will not cause issues. + */ +// PORTING NOTE: Multi-Tab only. +function __PRIVATE_synthesizeTargetToQuery(e) { + return __PRIVATE_newQuery(e.path, e.collectionGroup, e.orderBy, e.filters, e.limit, "F" /* LimitType.First */ , e.startAt, e.endAt); +} + +/** Returns the IDs of the clients that are currently active. */ +// PORTING NOTE: Multi-Tab only. +function __PRIVATE_syncEngineGetActiveClients(e) { + return function __PRIVATE_localStoreGetActiveClients(e) { + return __PRIVATE_debugCast(__PRIVATE_debugCast(e).persistence).Ts(); + }(__PRIVATE_debugCast(e).localStore); +} + +/** Applies a query target change from a different tab. */ +// PORTING NOTE: Multi-Tab only. +async function __PRIVATE_syncEngineApplyTargetState(e, t, n, r) { + const i = __PRIVATE_debugCast(e); + if (i.gu) + // If we receive a target state notification via WebStorage, we are + // either already secondary or another tab has taken the primary lease. + return void __PRIVATE_logDebug(sn, "Ignoring unexpected query state notification."); + const s = i.Iu.get(t); + if (s && s.length > 0) switch (n) { + case "current": + case "not-current": + { + const e = await __PRIVATE_localStoreGetNewDocumentChanges(i.localStore, __PRIVATE_queryCollectionGroup(s[0])), r = RemoteEvent.createSynthesizedRemoteEventForCurrentChange(t, "current" === n, ByteString.EMPTY_BYTE_STRING); + await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(i, e, r); + break; + } + + case "rejected": + await __PRIVATE_localStoreReleaseTarget(i.localStore, t, + /* keepPersistedTargetData */ !0), __PRIVATE_removeAndCleanupTarget(i, t, r); + break; + + default: + fail(64155, n); + } +} + +/** Adds or removes Watch targets for queries from different tabs. */ async function __PRIVATE_syncEngineApplyActiveTargetsChange(e, t, n) { + const r = __PRIVATE_ensureWatchCallbacks(e); + if (r.gu) { + for (const e of t) { + if (r.Iu.has(e) && r.sharedClientState.isActiveQueryTarget(e)) { + __PRIVATE_logDebug(sn, "Adding an already active target " + e); + continue; + } + const t = await __PRIVATE_localStoreGetCachedTarget(r.localStore, e), n = await __PRIVATE_localStoreAllocateTarget(r.localStore, t); + await __PRIVATE_initializeViewAndComputeSnapshot(r, __PRIVATE_synthesizeTargetToQuery(t), n.targetId, + /*current=*/ !1, n.resumeToken), __PRIVATE_remoteStoreListen(r.remoteStore, n); + } + for (const e of n) + // Check that the target is still active since the target might have been + // removed if it has been rejected by the backend. + r.Iu.has(e) && + // Release queries that are still active. + await __PRIVATE_localStoreReleaseTarget(r.localStore, e, + /* keepPersistedTargetData */ !1).then((() => { + __PRIVATE_remoteStoreUnlisten(r.remoteStore, e), __PRIVATE_removeAndCleanupTarget(r, e); + })).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss); + } +} + +function __PRIVATE_ensureWatchCallbacks(e) { + const t = __PRIVATE_debugCast(e); + return t.remoteStore.remoteSyncer.applyRemoteEvent = __PRIVATE_syncEngineApplyRemoteEvent.bind(null, t), + t.remoteStore.remoteSyncer.getRemoteKeysForTarget = __PRIVATE_syncEngineGetRemoteKeysForTarget.bind(null, t), + t.remoteStore.remoteSyncer.rejectListen = __PRIVATE_syncEngineRejectListen.bind(null, t), + t.Pu.H_ = __PRIVATE_eventManagerOnWatchChange.bind(null, t.eventManager), t.Pu.yu = __PRIVATE_eventManagerOnWatchError.bind(null, t.eventManager), + t; +} + +function __PRIVATE_syncEngineEnsureWriteCallbacks(e) { + const t = __PRIVATE_debugCast(e); + return t.remoteStore.remoteSyncer.applySuccessfulWrite = __PRIVATE_syncEngineApplySuccessfulWrite.bind(null, t), + t.remoteStore.remoteSyncer.rejectFailedWrite = __PRIVATE_syncEngineRejectFailedWrite.bind(null, t), + t; +} + +/** + * Loads a Firestore bundle into the SDK. The returned promise resolves when + * the bundle finished loading. + * + * @param syncEngine - SyncEngine to use. + * @param bundleReader - Bundle to load into the SDK. + * @param task - LoadBundleTask used to update the loading progress to public API. + */ function __PRIVATE_syncEngineLoadBundle(e, t, n) { + const r = __PRIVATE_debugCast(e); + // eslint-disable-next-line @typescript-eslint/no-floating-promises + ( + /** Loads a bundle and returns the list of affected collection groups. */ + async function __PRIVATE_loadBundleImpl(e, t, n) { + try { + const r = await t.getMetadata(); + if (await function __PRIVATE_localStoreHasNewerBundle(e, t) { + const n = __PRIVATE_debugCast(e), r = __PRIVATE_fromVersion(t.createTime); + return n.persistence.runTransaction("hasNewerBundle", "readonly", (e => n.Ii.getBundleMetadata(e, t.id))).then((e => !!e && e.createTime.compareTo(r) >= 0)); + } + /** + * Saves the given `BundleMetadata` to local persistence. + */ (e.localStore, r)) return await t.close(), n._completeWith(function __PRIVATE_bundleSuccessProgress(e) { + return { + taskState: "Success", + documentsLoaded: e.totalDocuments, + bytesLoaded: e.totalBytes, + totalDocuments: e.totalDocuments, + totalBytes: e.totalBytes + }; + }(r)), Promise.resolve(new Set); + n._updateProgress(__PRIVATE_bundleInitialProgress(r)); + const i = new __PRIVATE_BundleLoader(r, t.serializer); + let s = await t.bu(); + for (;s; ) { + const e = await i.Ga(s); + e && n._updateProgress(e), s = await t.bu(); + } + const o = await i.ja(e.localStore); + return await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(e, o.Ha, + /* remoteEvent */ void 0), + // Save metadata, so loading the same bundle will skip. + await function __PRIVATE_localStoreSaveBundle(e, t) { + const n = __PRIVATE_debugCast(e); + return n.persistence.runTransaction("Save bundle", "readwrite", (e => n.Ii.saveBundleMetadata(e, t))); + } + /** + * Returns a promise of a `NamedQuery` associated with given query name. Promise + * resolves to undefined if no persisted data can be found. + */ (e.localStore, r), n._completeWith(o.progress), Promise.resolve(o.Ja); + } catch (e) { + return __PRIVATE_logWarn(sn, `Loading bundle failed with ${e}`), n._failWith(e), + Promise.resolve(new Set); + } + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Provides all components needed for Firestore with in-memory persistence. + * Uses EagerGC garbage collection. + */)(r, t, n).then((e => { + r.sharedClientState.notifyBundleLoaded(e); + })); +} + +class __PRIVATE_MemoryOfflineComponentProvider { + constructor() { + this.kind = "memory", this.synchronizeTabs = !1; + } + async initialize(e) { + this.serializer = __PRIVATE_newSerializer(e.databaseInfo.databaseId), this.sharedClientState = this.Du(e), + this.persistence = this.Cu(e), await this.persistence.start(), this.localStore = this.vu(e), + this.gcScheduler = this.Fu(e, this.localStore), this.indexBackfillerScheduler = this.Mu(e, this.localStore); + } + Fu(e, t) { + return null; + } + Mu(e, t) { + return null; + } + vu(e) { + return __PRIVATE_newLocalStore(this.persistence, new __PRIVATE_QueryEngine, e.initialUser, this.serializer); + } + Cu(e) { + return new __PRIVATE_MemoryPersistence(__PRIVATE_MemoryEagerDelegate.mi, this.serializer); + } + Du(e) { + return new __PRIVATE_MemorySharedClientState; + } + async terminate() { + this.gcScheduler?.stop(), this.indexBackfillerScheduler?.stop(), this.sharedClientState.shutdown(), + await this.persistence.shutdown(); + } +} + +__PRIVATE_MemoryOfflineComponentProvider.provider = { + build: () => new __PRIVATE_MemoryOfflineComponentProvider +}; + +class __PRIVATE_LruGcMemoryOfflineComponentProvider extends __PRIVATE_MemoryOfflineComponentProvider { + constructor(e) { + super(), this.cacheSizeBytes = e; + } + Fu(e, t) { + __PRIVATE_hardAssert(this.persistence.referenceDelegate instanceof __PRIVATE_MemoryLruDelegate, 46915); + const n = this.persistence.referenceDelegate.garbageCollector; + return new __PRIVATE_LruScheduler(n, e.asyncQueue, t); + } + Cu(e) { + const t = void 0 !== this.cacheSizeBytes ? LruParams.withCacheSize(this.cacheSizeBytes) : LruParams.DEFAULT; + return new __PRIVATE_MemoryPersistence((e => __PRIVATE_MemoryLruDelegate.mi(e, t)), this.serializer); + } +} + +/** + * Provides all components needed for Firestore with IndexedDB persistence. + */ class __PRIVATE_IndexedDbOfflineComponentProvider extends __PRIVATE_MemoryOfflineComponentProvider { + constructor(e, t, n) { + super(), this.xu = e, this.cacheSizeBytes = t, this.forceOwnership = n, this.kind = "persistent", + this.synchronizeTabs = !1; + } + async initialize(e) { + await super.initialize(e), await this.xu.initialize(this, e), + // Enqueue writes from a previous session + await __PRIVATE_syncEngineEnsureWriteCallbacks(this.xu.syncEngine), await __PRIVATE_fillWritePipeline(this.xu.remoteStore), + // NOTE: This will immediately call the listener, so we make sure to + // set it after localStore / remoteStore are started. + await this.persistence.Ji((() => (this.gcScheduler && !this.gcScheduler.started && this.gcScheduler.start(), + this.indexBackfillerScheduler && !this.indexBackfillerScheduler.started && this.indexBackfillerScheduler.start(), + Promise.resolve()))); + } + vu(e) { + return __PRIVATE_newLocalStore(this.persistence, new __PRIVATE_QueryEngine, e.initialUser, this.serializer); + } + Fu(e, t) { + const n = this.persistence.referenceDelegate.garbageCollector; + return new __PRIVATE_LruScheduler(n, e.asyncQueue, t); + } + Mu(e, t) { + const n = new __PRIVATE_IndexBackfiller(t, this.persistence); + return new __PRIVATE_IndexBackfillerScheduler(e.asyncQueue, n); + } + Cu(e) { + const t = __PRIVATE_indexedDbStoragePrefix(e.databaseInfo.databaseId, e.databaseInfo.persistenceKey), n = void 0 !== this.cacheSizeBytes ? LruParams.withCacheSize(this.cacheSizeBytes) : LruParams.DEFAULT; + return new __PRIVATE_IndexedDbPersistence(this.synchronizeTabs, t, e.clientId, n, e.asyncQueue, __PRIVATE_getWindow(), getDocument(), this.serializer, this.sharedClientState, !!this.forceOwnership); + } + Du(e) { + return new __PRIVATE_MemorySharedClientState; + } +} + +/** + * Provides all components needed for Firestore with multi-tab IndexedDB + * persistence. + * + * In the legacy client, this provider is used to provide both multi-tab and + * non-multi-tab persistence since we cannot tell at build time whether + * `synchronizeTabs` will be enabled. + */ class __PRIVATE_MultiTabOfflineComponentProvider extends __PRIVATE_IndexedDbOfflineComponentProvider { + constructor(e, t) { + super(e, t, /* forceOwnership= */ !1), this.xu = e, this.cacheSizeBytes = t, this.synchronizeTabs = !0; + } + async initialize(e) { + await super.initialize(e); + const t = this.xu.syncEngine; + this.sharedClientState instanceof __PRIVATE_WebStorageSharedClientState && (this.sharedClientState.syncEngine = { + Co: __PRIVATE_syncEngineApplyBatchState.bind(null, t), + vo: __PRIVATE_syncEngineApplyTargetState.bind(null, t), + Fo: __PRIVATE_syncEngineApplyActiveTargetsChange.bind(null, t), + Ts: __PRIVATE_syncEngineGetActiveClients.bind(null, t), + Do: __PRIVATE_syncEngineSynchronizeWithChangedDocuments.bind(null, t) + }, await this.sharedClientState.start()), + // NOTE: This will immediately call the listener, so we make sure to + // set it after localStore / remoteStore are started. + await this.persistence.Ji((async e => { + await __PRIVATE_syncEngineApplyPrimaryState(this.xu.syncEngine, e), this.gcScheduler && (e && !this.gcScheduler.started ? this.gcScheduler.start() : e || this.gcScheduler.stop()), + this.indexBackfillerScheduler && (e && !this.indexBackfillerScheduler.started ? this.indexBackfillerScheduler.start() : e || this.indexBackfillerScheduler.stop()); + })); + } + Du(e) { + const t = __PRIVATE_getWindow(); + if (!__PRIVATE_WebStorageSharedClientState.v(t)) throw new FirestoreError(N.UNIMPLEMENTED, "IndexedDB persistence is only available on platforms that support LocalStorage."); + const n = __PRIVATE_indexedDbStoragePrefix(e.databaseInfo.databaseId, e.databaseInfo.persistenceKey); + return new __PRIVATE_WebStorageSharedClientState(t, e.asyncQueue, n, e.clientId, e.initialUser); + } +} + +/** + * Initializes and wires the components that are needed to interface with the + * network. + */ class OnlineComponentProvider { + async initialize(e, t) { + this.localStore || (this.localStore = e.localStore, this.sharedClientState = e.sharedClientState, + this.datastore = this.createDatastore(t), this.remoteStore = this.createRemoteStore(t), + this.eventManager = this.createEventManager(t), this.syncEngine = this.createSyncEngine(t, + /* startAsPrimary=*/ !e.synchronizeTabs), this.sharedClientState.onlineStateHandler = e => __PRIVATE_syncEngineApplyOnlineStateChange(this.syncEngine, e, 1 /* OnlineStateSource.SharedClientState */), + this.remoteStore.remoteSyncer.handleCredentialChange = __PRIVATE_syncEngineHandleCredentialChange.bind(null, this.syncEngine), + await __PRIVATE_remoteStoreApplyPrimaryState(this.remoteStore, this.syncEngine.isPrimaryClient)); + } + createEventManager(e) { + return function __PRIVATE_newEventManager() { + return new __PRIVATE_EventManagerImpl; + }(); + } + createDatastore(e) { + const t = __PRIVATE_newSerializer(e.databaseInfo.databaseId), n = function __PRIVATE_newConnection(e) { + return new __PRIVATE_WebChannelConnection(e); + } + /** Return the Platform-specific connectivity monitor. */ (e.databaseInfo); + return function __PRIVATE_newDatastore(e, t, n, r) { + return new __PRIVATE_DatastoreImpl(e, t, n, r); + }(e.authCredentials, e.appCheckCredentials, n, t); + } + createRemoteStore(e) { + return function __PRIVATE_newRemoteStore(e, t, n, r, i) { + return new __PRIVATE_RemoteStoreImpl(e, t, n, r, i); + } + /** Re-enables the network. Idempotent. */ (this.localStore, this.datastore, e.asyncQueue, (e => __PRIVATE_syncEngineApplyOnlineStateChange(this.syncEngine, e, 0 /* OnlineStateSource.RemoteStore */)), function __PRIVATE_newConnectivityMonitor() { + return __PRIVATE_BrowserConnectivityMonitor.v() ? new __PRIVATE_BrowserConnectivityMonitor : new __PRIVATE_NoopConnectivityMonitor; + }()); + } + createSyncEngine(e, t) { + return function __PRIVATE_newSyncEngine(e, t, n, + // PORTING NOTE: Manages state synchronization in multi-tab environments. + r, i, s, o) { + const _ = new __PRIVATE_SyncEngineImpl(e, t, n, r, i, s); + return o && (_.gu = !0), _; + }(this.localStore, this.remoteStore, this.eventManager, this.sharedClientState, e.initialUser, e.maxConcurrentLimboResolutions, t); + } + async terminate() { + await async function __PRIVATE_remoteStoreShutdown(e) { + const t = __PRIVATE_debugCast(e); + __PRIVATE_logDebug(tn, "RemoteStore shutting down."), t.Ea.add(5 /* OfflineCause.Shutdown */), + await __PRIVATE_disableNetworkInternal(t), t.Aa.shutdown(), + // Set the OnlineState to Unknown (rather than Offline) to avoid potentially + // triggering spurious listener events with cached data, etc. + t.Ra.set("Unknown" /* OnlineState.Unknown */); + }(this.remoteStore), this.datastore?.terminate(), this.eventManager?.terminate(); + } +} + +OnlineComponentProvider.provider = { + build: () => new OnlineComponentProvider +}; + +/** + * Builds a `ByteStreamReader` from a UInt8Array. + * @param source - The data source to use. + * @param bytesPerRead - How many bytes each `read()` from the returned reader + * will read. + */ +function __PRIVATE_toByteStreamReaderHelper(e, t = 10240) { + let n = 0; + // The TypeScript definition for ReadableStreamReader changed. We use + // `any` here to allow this code to compile with different versions. + // See https://github.com/microsoft/TypeScript/issues/42970 + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + async read() { + if (n < e.byteLength) { + const r = { + value: e.slice(n, n + t), + done: !1 + }; + return n += t, r; + } + return { + done: !0 + }; + }, + async cancel() {}, + releaseLock() {}, + closed: Promise.resolve() + }; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * On web, a `ReadableStream` is wrapped around by a `ByteStreamReader`. + */ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * A wrapper implementation of Observer that will dispatch events + * asynchronously. To allow immediate silencing, a mute call is added which + * causes events scheduled to no longer be raised. + */ +class __PRIVATE_AsyncObserver { + constructor(e) { + this.observer = e, + /** + * When set to true, will not raise future events. Necessary to deal with + * async detachment of listener. + */ + this.muted = !1; + } + next(e) { + this.muted || this.observer.next && this.Ou(this.observer.next, e); + } + error(e) { + this.muted || (this.observer.error ? this.Ou(this.observer.error, e) : __PRIVATE_logError("Uncaught Error in snapshot listener:", e.toString())); + } + Nu() { + this.muted = !0; + } + Ou(e, t) { + setTimeout((() => { + this.muted || e(t); + }), 0); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A class representing a bundle. + * + * Takes a bundle stream or buffer, and presents abstractions to read bundled + * elements out of the underlying content. + */ class __PRIVATE_BundleReaderImpl { + constructor( + /** The reader to read from underlying binary bundle data source. */ + e, t) { + this.Bu = e, this.serializer = t, + /** Cached bundle metadata. */ + this.metadata = new __PRIVATE_Deferred, + /** + * Internal buffer to hold bundle content, accumulating incomplete element + * content. + */ + this.buffer = new Uint8Array, this.Lu = function __PRIVATE_newTextDecoder() { + return new TextDecoder("utf-8"); + }(), + // Read the metadata (which is the first element). + this.ku().then((e => { + e && e.$a() ? this.metadata.resolve(e.Qa.metadata) : this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\n ${JSON.stringify(e?.Qa)}`)); + }), (e => this.metadata.reject(e))); + } + close() { + return this.Bu.cancel(); + } + async getMetadata() { + return this.metadata.promise; + } + async bu() { + // Makes sure metadata is read before proceeding. + return await this.getMetadata(), this.ku(); + } + /** + * Reads from the head of internal buffer, and pulling more data from + * underlying stream if a complete element cannot be found, until an + * element(including the prefixed length and the JSON string) is found. + * + * Once a complete element is read, it is dropped from internal buffer. + * + * Returns either the bundled element, or null if we have reached the end of + * the stream. + */ async ku() { + const e = await this.qu(); + if (null === e) return null; + const t = this.Lu.decode(e), n = Number(t); + isNaN(n) && this.Qu(`length string (${t}) is not valid number`); + const r = await this.$u(n); + return new __PRIVATE_SizedBundleElement(JSON.parse(r), e.length + n); + } + /** First index of '{' from the underlying buffer. */ Uu() { + return this.buffer.findIndex((e => e === "{".charCodeAt(0))); + } + /** + * Reads from the beginning of the internal buffer, until the first '{', and + * return the content. + * + * If reached end of the stream, returns a null. + */ async qu() { + for (;this.Uu() < 0; ) { + if (await this.Ku()) break; + } + // Broke out of the loop because underlying stream is closed, and there + // happens to be no more data to process. + if (0 === this.buffer.length) return null; + const e = this.Uu(); + // Broke out of the loop because underlying stream is closed, but still + // cannot find an open bracket. + e < 0 && this.Qu("Reached the end of bundle when a length string is expected."); + const t = this.buffer.slice(0, e); + // Update the internal buffer to drop the read length. + return this.buffer = this.buffer.slice(e), t; + } + /** + * Reads from a specified position from the internal buffer, for a specified + * number of bytes, pulling more data from the underlying stream if needed. + * + * Returns a string decoded from the read bytes. + */ async $u(e) { + for (;this.buffer.length < e; ) { + await this.Ku() && this.Qu("Reached the end of bundle when more is expected."); + } + const t = this.Lu.decode(this.buffer.slice(0, e)); + // Update the internal buffer to drop the read json string. + return this.buffer = this.buffer.slice(e), t; + } + Qu(e) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + throw this.Bu.cancel(), new Error(`Invalid bundle format: ${e}`); + } + /** + * Pulls more data from underlying stream to internal buffer. + * Returns a boolean indicating whether the stream is finished. + */ async Ku() { + const e = await this.Bu.read(); + if (!e.done) { + const t = new Uint8Array(this.buffer.length + e.value.length); + t.set(this.buffer), t.set(e.value, this.buffer.length), this.buffer = t; + } + return e.done; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A class that can parse a bundle form the string serialization of a bundle. + */ +class __PRIVATE_BundleReaderSyncImpl { + constructor(e, t) { + this.bundleData = e, this.serializer = t, this.cursor = 0, this.elements = []; + let n = this.bu(); + if (!n || !n.$a()) throw new Error(`The first element of the bundle is not a metadata object, it is\n ${JSON.stringify(n?.Qa)}`); + this.metadata = n; + do { + n = this.bu(), null !== n && this.elements.push(n); + } while (null !== n); + } + /* Returns the parsed metadata of the bundle. */ getMetadata() { + return this.metadata; + } + /* Returns the DocumentSnapshot or NamedQuery elements of the bundle. */ Wu() { + return this.elements; + } + /** + * Parses the next element of the bundle. + * + * @returns a SizedBundleElement representation of the next element in the bundle, or null if + * no more elements exist. + */ bu() { + if (this.cursor === this.bundleData.length) return null; + const e = this.qu(), t = this.$u(e); + return new __PRIVATE_SizedBundleElement(JSON.parse(t), e); + } + /** + * Reads from a specified position from the bundleData string, for a specified + * number of bytes. + * + * @param length how many characters to read. + * @returns a string parsed from the bundle. + */ $u(e) { + if (this.cursor + e > this.bundleData.length) throw new FirestoreError(N.INTERNAL, "Reached the end of bundle when more is expected."); + return this.bundleData.slice(this.cursor, this.cursor += e); + } + /** + * Reads from the current cursor until the first '{'. + * + * @returns A string to integer represention of the parsed value. + * @throws An {@link Error} if the cursor has reached the end of the stream, since lengths + * prefix bundle objects. + */ qu() { + const e = this.cursor; + let t = this.cursor; + for (;t < this.bundleData.length; ) { + if ("{" === this.bundleData[t]) { + if (t === e) throw new Error("First character is a bracket and not a number"); + return this.cursor = t, Number(this.bundleData.slice(e, t)); + } + t++; + } + throw new Error("Reached the end of bundle when more is expected."); + } +} + +/** + * Creates an instance of BundleReader without exposing the BundleReaderSyncImpl class type. + */ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Internal transaction object responsible for accumulating the mutations to + * perform and the base versions for any documents read. + */ +class Transaction$2 { + constructor(e) { + this.datastore = e, + // The version of each document that was read during this transaction. + this.readVersions = new Map, this.mutations = [], this.committed = !1, + /** + * A deferred usage error that occurred previously in this transaction that + * will cause the transaction to fail once it actually commits. + */ + this.lastTransactionError = null, + /** + * Set of documents that have been written in the transaction. + * + * When there's more than one write to the same key in a transaction, any + * writes after the first are handled differently. + */ + this.writtenDocs = new Set; + } + async lookup(e) { + if (this.ensureCommitNotCalled(), this.mutations.length > 0) throw this.lastTransactionError = new FirestoreError(N.INVALID_ARGUMENT, "Firestore transactions require all reads to be executed before all writes."), + this.lastTransactionError; + const t = await async function __PRIVATE_invokeBatchGetDocumentsRpc(e, t) { + const n = __PRIVATE_debugCast(e), r = { + documents: t.map((e => __PRIVATE_toName(n.serializer, e))) + }, i = await n.Ho("BatchGetDocuments", n.serializer.databaseId, ResourcePath.emptyPath(), r, t.length), s = new Map; + i.forEach((e => { + const t = __PRIVATE_fromBatchGetDocumentsResponse(n.serializer, e); + s.set(t.key.toString(), t); + })); + const o = []; + return t.forEach((e => { + const t = s.get(e.toString()); + __PRIVATE_hardAssert(!!t, 55234, { + key: e + }), o.push(t); + })), o; + }(this.datastore, e); + return t.forEach((e => this.recordVersion(e))), t; + } + set(e, t) { + this.write(t.toMutation(e, this.precondition(e))), this.writtenDocs.add(e.toString()); + } + update(e, t) { + try { + this.write(t.toMutation(e, this.preconditionForUpdate(e))); + } catch (e) { + this.lastTransactionError = e; + } + this.writtenDocs.add(e.toString()); + } + delete(e) { + this.write(new __PRIVATE_DeleteMutation(e, this.precondition(e))), this.writtenDocs.add(e.toString()); + } + async commit() { + if (this.ensureCommitNotCalled(), this.lastTransactionError) throw this.lastTransactionError; + const e = this.readVersions; + // For each mutation, note that the doc was written. + this.mutations.forEach((t => { + e.delete(t.key.toString()); + })), + // For each document that was read but not written to, we want to perform + // a `verify` operation. + e.forEach(((e, t) => { + const n = DocumentKey.fromPath(t); + this.mutations.push(new __PRIVATE_VerifyMutation(n, this.precondition(n))); + })), await async function __PRIVATE_invokeCommitRpc(e, t) { + const n = __PRIVATE_debugCast(e), r = { + writes: t.map((e => toMutation(n.serializer, e))) + }; + await n.Go("Commit", n.serializer.databaseId, ResourcePath.emptyPath(), r); + }(this.datastore, this.mutations), this.committed = !0; + } + recordVersion(e) { + let t; + if (e.isFoundDocument()) t = e.version; else { + if (!e.isNoDocument()) throw fail(50498, { + Gu: e.constructor.name + }); + // Represent a deleted doc using SnapshotVersion.min(). + t = SnapshotVersion.min(); + } + const n = this.readVersions.get(e.key.toString()); + if (n) { + if (!t.isEqual(n)) + // This transaction will fail no matter what. + throw new FirestoreError(N.ABORTED, "Document version changed between two reads."); + } else this.readVersions.set(e.key.toString(), t); + } + /** + * Returns the version of this document when it was read in this transaction, + * as a precondition, or no precondition if it was not read. + */ precondition(e) { + const t = this.readVersions.get(e.toString()); + return !this.writtenDocs.has(e.toString()) && t ? t.isEqual(SnapshotVersion.min()) ? Precondition.exists(!1) : Precondition.updateTime(t) : Precondition.none(); + } + /** + * Returns the precondition for a document if the operation is an update. + */ preconditionForUpdate(e) { + const t = this.readVersions.get(e.toString()); + // The first time a document is written, we want to take into account the + // read time and existence + if (!this.writtenDocs.has(e.toString()) && t) { + if (t.isEqual(SnapshotVersion.min())) + // The document doesn't exist, so fail the transaction. + // This has to be validated locally because you can't send a + // precondition that a document does not exist without changing the + // semantics of the backend write to be an insert. This is the reverse + // of what we want, since we want to assert that the document doesn't + // exist but then send the update and have it fail. Since we can't + // express that to the backend, we have to validate locally. + // Note: this can change once we can send separate verify writes in the + // transaction. + throw new FirestoreError(N.INVALID_ARGUMENT, "Can't update a document that doesn't exist."); + // Document exists, base precondition on document update time. + return Precondition.updateTime(t); + } + // Document was not read, so we just use the preconditions for a blind + // update. + return Precondition.exists(!0); + } + write(e) { + this.ensureCommitNotCalled(), this.mutations.push(e); + } + ensureCommitNotCalled() {} +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * TransactionRunner encapsulates the logic needed to run and retry transactions + * with backoff. + */ class __PRIVATE_TransactionRunner { + constructor(e, t, n, r, i) { + this.asyncQueue = e, this.datastore = t, this.options = n, this.updateFunction = r, + this.deferred = i, this.zu = n.maxAttempts, this.M_ = new __PRIVATE_ExponentialBackoff(this.asyncQueue, "transaction_retry" /* TimerId.TransactionRetry */); + } + /** Runs the transaction and sets the result on deferred. */ ju() { + this.zu -= 1, this.Ju(); + } + Ju() { + this.M_.p_((async () => { + const e = new Transaction$2(this.datastore), t = this.Hu(e); + t && t.then((t => { + this.asyncQueue.enqueueAndForget((() => e.commit().then((() => { + this.deferred.resolve(t); + })).catch((e => { + this.Yu(e); + })))); + })).catch((e => { + this.Yu(e); + })); + })); + } + Hu(e) { + try { + const t = this.updateFunction(e); + return !__PRIVATE_isNullOrUndefined(t) && t.catch && t.then ? t : (this.deferred.reject(Error("Transaction callback must return a Promise")), + null); + } catch (e) { + // Do not retry errors thrown by user provided updateFunction. + return this.deferred.reject(e), null; + } + } + Yu(e) { + this.zu > 0 && this.Zu(e) ? (this.zu -= 1, this.asyncQueue.enqueueAndForget((() => (this.Ju(), + Promise.resolve())))) : this.deferred.reject(e); + } + Zu(e) { + if ("FirebaseError" === e?.name) { + // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and + // non-matching document versions with ABORTED. These errors should be retried. + const t = e.code; + return "aborted" === t || "failed-precondition" === t || "already-exists" === t || !__PRIVATE_isPermanentError(t); + } + return !1; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const on = "FirestoreClient"; + +/** + * FirestoreClient is a top-level class that constructs and owns all of the // + * pieces of the client SDK architecture. It is responsible for creating the // + * async queue that is shared by all of the other components in the system. // + */ +class FirestoreClient { + constructor(e, t, + /** + * Asynchronous queue responsible for all of our internal processing. When + * we get incoming work from the user (via public API) or the network + * (incoming GRPC messages), we should always schedule onto this queue. + * This ensures all of our work is properly serialized (e.g. we don't + * start processing a new operation while the previous one is waiting for + * an async I/O to complete). + */ + n, r, i) { + this.authCredentials = e, this.appCheckCredentials = t, this.asyncQueue = n, this.databaseInfo = r, + this.user = User.UNAUTHENTICATED, this.clientId = __PRIVATE_AutoId.newId(), this.authCredentialListener = () => Promise.resolve(), + this.appCheckCredentialListener = () => Promise.resolve(), this._uninitializedComponentsProvider = i, + this.authCredentials.start(n, (async e => { + __PRIVATE_logDebug(on, "Received user=", e.uid), await this.authCredentialListener(e), + this.user = e; + })), this.appCheckCredentials.start(n, (e => (__PRIVATE_logDebug(on, "Received new app check token=", e), + this.appCheckCredentialListener(e, this.user)))); + } + get configuration() { + return { + asyncQueue: this.asyncQueue, + databaseInfo: this.databaseInfo, + clientId: this.clientId, + authCredentials: this.authCredentials, + appCheckCredentials: this.appCheckCredentials, + initialUser: this.user, + maxConcurrentLimboResolutions: 100 + }; + } + setCredentialChangeListener(e) { + this.authCredentialListener = e; + } + setAppCheckTokenChangeListener(e) { + this.appCheckCredentialListener = e; + } + terminate() { + this.asyncQueue.enterRestrictedMode(); + const e = new __PRIVATE_Deferred; + return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((async () => { + try { + this._onlineComponents && await this._onlineComponents.terminate(), this._offlineComponents && await this._offlineComponents.terminate(), + // The credentials provider must be terminated after shutting down the + // RemoteStore as it will prevent the RemoteStore from retrieving auth + // tokens. + this.authCredentials.shutdown(), this.appCheckCredentials.shutdown(), e.resolve(); + } catch (t) { + const n = __PRIVATE_wrapInUserErrorIfRecoverable(t, "Failed to shutdown persistence"); + e.reject(n); + } + })), e.promise; + } +} + +async function __PRIVATE_setOfflineComponentProvider(e, t) { + e.asyncQueue.verifyOperationInProgress(), __PRIVATE_logDebug(on, "Initializing OfflineComponentProvider"); + const n = e.configuration; + await t.initialize(n); + let r = n.initialUser; + e.setCredentialChangeListener((async e => { + r.isEqual(e) || (await __PRIVATE_localStoreHandleUserChange(t.localStore, e), r = e); + })), + // When a user calls clearPersistence() in one client, all other clients + // need to be terminated to allow the delete to succeed. + t.persistence.setDatabaseDeletedListener((() => e.terminate())), e._offlineComponents = t; +} + +async function __PRIVATE_setOnlineComponentProvider(e, t) { + e.asyncQueue.verifyOperationInProgress(); + const n = await __PRIVATE_ensureOfflineComponents(e); + __PRIVATE_logDebug(on, "Initializing OnlineComponentProvider"), await t.initialize(n, e.configuration), + // The CredentialChangeListener of the online component provider takes + // precedence over the offline component provider. + e.setCredentialChangeListener((e => __PRIVATE_remoteStoreHandleCredentialChange(t.remoteStore, e))), + e.setAppCheckTokenChangeListener(((e, n) => __PRIVATE_remoteStoreHandleCredentialChange(t.remoteStore, n))), + e._onlineComponents = t; +} + +/** + * Decides whether the provided error allows us to gracefully disable + * persistence (as opposed to crashing the client). + */ async function __PRIVATE_ensureOfflineComponents(e) { + if (!e._offlineComponents) if (e._uninitializedComponentsProvider) { + __PRIVATE_logDebug(on, "Using user provided OfflineComponentProvider"); + try { + await __PRIVATE_setOfflineComponentProvider(e, e._uninitializedComponentsProvider._offline); + } catch (t) { + const n = t; + if (!function __PRIVATE_canFallbackFromIndexedDbError(e) { + return "FirebaseError" === e.name ? e.code === N.FAILED_PRECONDITION || e.code === N.UNIMPLEMENTED : !("undefined" != typeof DOMException && e instanceof DOMException) || + // When the browser is out of quota we could get either quota exceeded + // or an aborted error depending on whether the error happened during + // schema migration. + 22 === e.code || 20 === e.code || + // Firefox Private Browsing mode disables IndexedDb and returns + // INVALID_STATE for any usage. + 11 === e.code; + }(n)) throw n; + __PRIVATE_logWarn("Error using user provided cache. Falling back to memory cache: " + n), + await __PRIVATE_setOfflineComponentProvider(e, new __PRIVATE_MemoryOfflineComponentProvider); + } + } else __PRIVATE_logDebug(on, "Using default OfflineComponentProvider"), await __PRIVATE_setOfflineComponentProvider(e, new __PRIVATE_LruGcMemoryOfflineComponentProvider(void 0)); + return e._offlineComponents; +} + +async function __PRIVATE_ensureOnlineComponents(e) { + return e._onlineComponents || (e._uninitializedComponentsProvider ? (__PRIVATE_logDebug(on, "Using user provided OnlineComponentProvider"), + await __PRIVATE_setOnlineComponentProvider(e, e._uninitializedComponentsProvider._online)) : (__PRIVATE_logDebug(on, "Using default OnlineComponentProvider"), + await __PRIVATE_setOnlineComponentProvider(e, new OnlineComponentProvider))), e._onlineComponents; +} + +function __PRIVATE_getPersistence(e) { + return __PRIVATE_ensureOfflineComponents(e).then((e => e.persistence)); +} + +function __PRIVATE_getLocalStore(e) { + return __PRIVATE_ensureOfflineComponents(e).then((e => e.localStore)); +} + +function __PRIVATE_getRemoteStore(e) { + return __PRIVATE_ensureOnlineComponents(e).then((e => e.remoteStore)); +} + +function __PRIVATE_getSyncEngine(e) { + return __PRIVATE_ensureOnlineComponents(e).then((e => e.syncEngine)); +} + +function __PRIVATE_getDatastore(e) { + return __PRIVATE_ensureOnlineComponents(e).then((e => e.datastore)); +} + +async function __PRIVATE_getEventManager(e) { + const t = await __PRIVATE_ensureOnlineComponents(e), n = t.eventManager; + return n.onListen = __PRIVATE_syncEngineListen.bind(null, t.syncEngine), n.onUnlisten = __PRIVATE_syncEngineUnlisten.bind(null, t.syncEngine), + n.onFirstRemoteStoreListen = __PRIVATE_triggerRemoteStoreListen.bind(null, t.syncEngine), + n.onLastRemoteStoreUnlisten = __PRIVATE_triggerRemoteStoreUnlisten.bind(null, t.syncEngine), + n; +} + +/** Enables the network connection and re-enqueues all pending operations. */ function __PRIVATE_firestoreClientEnableNetwork(e) { + return e.asyncQueue.enqueue((async () => { + const t = await __PRIVATE_getPersistence(e), n = await __PRIVATE_getRemoteStore(e); + return t.setNetworkEnabled(!0), function __PRIVATE_remoteStoreEnableNetwork(e) { + const t = __PRIVATE_debugCast(e); + return t.Ea.delete(0 /* OfflineCause.UserDisabled */), __PRIVATE_enableNetworkInternal(t); + }(n); + })); +} + +/** Disables the network connection. Pending operations will not complete. */ function __PRIVATE_firestoreClientDisableNetwork(e) { + return e.asyncQueue.enqueue((async () => { + const t = await __PRIVATE_getPersistence(e), n = await __PRIVATE_getRemoteStore(e); + return t.setNetworkEnabled(!1), async function __PRIVATE_remoteStoreDisableNetwork(e) { + const t = __PRIVATE_debugCast(e); + t.Ea.add(0 /* OfflineCause.UserDisabled */), await __PRIVATE_disableNetworkInternal(t), + // Set the OnlineState to Offline so get()s return from cache, etc. + t.Ra.set("Offline" /* OnlineState.Offline */); + }(n); + })); +} + +/** + * Returns a Promise that resolves when all writes that were pending at the time + * this method was called received server acknowledgement. An acknowledgement + * can be either acceptance or rejection. + */ function __PRIVATE_firestoreClientGetDocumentFromLocalCache(e, t) { + const n = new __PRIVATE_Deferred; + return e.asyncQueue.enqueueAndForget((async () => async function __PRIVATE_readDocumentFromCache(e, t, n) { + try { + const r = await function __PRIVATE_localStoreReadDocument(e, t) { + const n = __PRIVATE_debugCast(e); + return n.persistence.runTransaction("read document", "readonly", (e => n.localDocuments.getDocument(e, t))); + }(e, t); + r.isFoundDocument() ? n.resolve(r) : r.isNoDocument() ? n.resolve(null) : n.reject(new FirestoreError(N.UNAVAILABLE, "Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)")); + } catch (e) { + const r = __PRIVATE_wrapInUserErrorIfRecoverable(e, `Failed to get document '${t} from cache`); + n.reject(r); + } + } + /** + * Retrieves a latency-compensated document from the backend via a + * SnapshotListener. + */ (await __PRIVATE_getLocalStore(e), t, n))), n.promise; +} + +function __PRIVATE_firestoreClientGetDocumentViaSnapshotListener(e, t, n = {}) { + const r = new __PRIVATE_Deferred; + return e.asyncQueue.enqueueAndForget((async () => function __PRIVATE_readDocumentViaSnapshotListener(e, t, n, r, i) { + const s = new __PRIVATE_AsyncObserver({ + next: _ => { + // Mute and remove query first before passing event to user to avoid + // user actions affecting the now stale query. + s.Nu(), t.enqueueAndForget((() => __PRIVATE_eventManagerUnlisten(e, o))); + const a = _.docs.has(n); + !a && _.fromCache ? + // TODO(dimond): If we're online and the document doesn't + // exist then we resolve with a doc.exists set to false. If + // we're offline however, we reject the Promise in this + // case. Two options: 1) Cache the negative response from + // the server so we can deliver that even when you're + // offline 2) Actually reject the Promise in the online case + // if the document doesn't exist. + i.reject(new FirestoreError(N.UNAVAILABLE, "Failed to get document because the client is offline.")) : a && _.fromCache && r && "server" === r.source ? i.reject(new FirestoreError(N.UNAVAILABLE, 'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')) : i.resolve(_); + }, + error: e => i.reject(e) + }), o = new __PRIVATE_QueryListener(__PRIVATE_newQueryForPath(n.path), s, { + includeMetadataChanges: !0, + qa: !0 + }); + return __PRIVATE_eventManagerListen(e, o); + }(await __PRIVATE_getEventManager(e), e.asyncQueue, t, n, r))), r.promise; +} + +function __PRIVATE_firestoreClientGetDocumentsFromLocalCache(e, t) { + const n = new __PRIVATE_Deferred; + return e.asyncQueue.enqueueAndForget((async () => async function __PRIVATE_executeQueryFromCache(e, t, n) { + try { + const r = await __PRIVATE_localStoreExecuteQuery(e, t, + /* usePreviousResults= */ !0), i = new __PRIVATE_View(t, r.Qs), s = i.ru(r.documents), o = i.applyChanges(s, + /* limboResolutionEnabled= */ !1); + n.resolve(o.snapshot); + } catch (e) { + const r = __PRIVATE_wrapInUserErrorIfRecoverable(e, `Failed to execute query '${t} against cache`); + n.reject(r); + } + } + /** + * Retrieves a latency-compensated query snapshot from the backend via a + * SnapshotListener. + */ (await __PRIVATE_getLocalStore(e), t, n))), n.promise; +} + +function __PRIVATE_firestoreClientGetDocumentsViaSnapshotListener(e, t, n = {}) { + const r = new __PRIVATE_Deferred; + return e.asyncQueue.enqueueAndForget((async () => function __PRIVATE_executeQueryViaSnapshotListener(e, t, n, r, i) { + const s = new __PRIVATE_AsyncObserver({ + next: n => { + // Mute and remove query first before passing event to user to avoid + // user actions affecting the now stale query. + s.Nu(), t.enqueueAndForget((() => __PRIVATE_eventManagerUnlisten(e, o))), n.fromCache && "server" === r.source ? i.reject(new FirestoreError(N.UNAVAILABLE, 'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')) : i.resolve(n); + }, + error: e => i.reject(e) + }), o = new __PRIVATE_QueryListener(n, s, { + includeMetadataChanges: !0, + qa: !0 + }); + return __PRIVATE_eventManagerListen(e, o); + }(await __PRIVATE_getEventManager(e), e.asyncQueue, t, n, r))), r.promise; +} + +function __PRIVATE_firestoreClientRunAggregateQuery(e, t, n) { + const r = new __PRIVATE_Deferred; + return e.asyncQueue.enqueueAndForget((async () => { + // Implement and call executeAggregateQueryViaSnapshotListener, similar + // to the implementation in firestoreClientGetDocumentsViaSnapshotListener + // above + try { + // TODO(b/277628384): check `canUseNetwork()` and handle multi-tab. + const i = await __PRIVATE_getDatastore(e); + r.resolve(async function __PRIVATE_invokeRunAggregationQueryRpc(e, t, n) { + const r = __PRIVATE_debugCast(e), {request: i, gt: s, parent: o} = __PRIVATE_toRunAggregationQueryRequest(r.serializer, __PRIVATE_queryToAggregateTarget(t), n); + r.connection.$o || delete i.parent; + const _ = (await r.Ho("RunAggregationQuery", r.serializer.databaseId, o, i, + /*expectedResponseCount=*/ 1)).filter((e => !!e.result)); + // Omit RunAggregationQueryResponse that only contain readTimes. + __PRIVATE_hardAssert(1 === _.length, 64727); + // Remap the short-form aliases that were sent to the server + // to the client-side aliases. Users will access the results + // using the client-side alias. + const a = _[0].result?.aggregateFields; + return Object.keys(a).reduce(((e, t) => (e[s[t]] = a[t], e)), {}); + }(i, t, n)); + } catch (e) { + r.reject(e); + } + })), r.promise; +} + +function __PRIVATE_firestoreClientAddSnapshotsInSyncListener(e, t) { + const n = new __PRIVATE_AsyncObserver(t); + return e.asyncQueue.enqueueAndForget((async () => function __PRIVATE_addSnapshotsInSyncListener(e, t) { + __PRIVATE_debugCast(e).Ca.add(t), + // Immediately fire an initial event, indicating all existing listeners + // are in-sync. + t.next(); + }(await __PRIVATE_getEventManager(e), n))), () => { + n.Nu(), e.asyncQueue.enqueueAndForget((async () => function __PRIVATE_removeSnapshotsInSyncListener(e, t) { + __PRIVATE_debugCast(e).Ca.delete(t); + }(await __PRIVATE_getEventManager(e), n))); + }; +} + +/** + * Takes an updateFunction in which a set of reads and writes can be performed + * atomically. In the updateFunction, the client can read and write values + * using the supplied transaction object. After the updateFunction, all + * changes will be committed. If a retryable error occurs (ex: some other + * client has changed any of the data referenced), then the updateFunction + * will be called again after a backoff. If the updateFunction still fails + * after all retries, then the transaction will be rejected. + * + * The transaction object passed to the updateFunction contains methods for + * accessing documents and collections. Unlike other datastore access, data + * accessed with the transaction will not reflect local changes that have not + * been committed. For this reason, it is required that all reads are + * performed before any writes. Transactions must be performed while online. + */ function __PRIVATE_firestoreClientLoadBundle(e, t, n, r) { + const i = function __PRIVATE_createBundleReader(e, t) { + let n; + n = "string" == typeof e ? __PRIVATE_newTextEncoder().encode(e) : e; + return function __PRIVATE_newBundleReader(e, t) { + return new __PRIVATE_BundleReaderImpl(e, t); + }(function __PRIVATE_toByteStreamReader(e, t) { + if (e instanceof Uint8Array) return __PRIVATE_toByteStreamReaderHelper(e, t); + if (e instanceof ArrayBuffer) return __PRIVATE_toByteStreamReaderHelper(new Uint8Array(e), t); + if (e instanceof ReadableStream) return e.getReader(); + throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream"); + }(n), t); + }(n, __PRIVATE_newSerializer(t)); + e.asyncQueue.enqueueAndForget((async () => { + __PRIVATE_syncEngineLoadBundle(await __PRIVATE_getSyncEngine(e), i, r); + })); +} + +function __PRIVATE_firestoreClientGetNamedQuery(e, t) { + return e.asyncQueue.enqueue((async () => function __PRIVATE_localStoreGetNamedQuery(e, t) { + const n = __PRIVATE_debugCast(e); + return n.persistence.runTransaction("Get named query", "readonly", (e => n.Ii.getNamedQuery(e, t))); + }(await __PRIVATE_getLocalStore(e), t))); +} + +function __PRIVATE_createBundleReaderSync(e, t) { + return function __PRIVATE_newBundleReaderSync(e, t) { + return new __PRIVATE_BundleReaderSyncImpl(e, t); + }(e, t); +} + +function __PRIVATE_firestoreClientSetIndexConfiguration(e, t) { + return e.asyncQueue.enqueue((async () => async function __PRIVATE_localStoreConfigureFieldIndexes(e, t) { + const n = __PRIVATE_debugCast(e), r = n.indexManager, i = []; + return n.persistence.runTransaction("Configure indexes", "readwrite", (e => r.getFieldIndexes(e).next((n => + /** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Compares two array for equality using comparator. The method computes the + * intersection and invokes `onAdd` for every element that is in `after` but not + * `before`. `onRemove` is invoked for every element in `before` but missing + * from `after`. + * + * The method creates a copy of both `before` and `after` and runs in O(n log + * n), where n is the size of the two lists. + * + * @param before - The elements that exist in the original array. + * @param after - The elements to diff against the original array. + * @param comparator - The comparator for the elements in before and after. + * @param onAdd - A function to invoke for every element that is part of ` + * after` but not `before`. + * @param onRemove - A function to invoke for every element that is part of + * `before` but not `after`. + */ + function __PRIVATE_diffArrays(e, t, n, r, i) { + e = [ ...e ], t = [ ...t ], e.sort(n), t.sort(n); + const s = e.length, o = t.length; + let _ = 0, a = 0; + for (;_ < o && a < s; ) { + const s = n(e[a], t[_]); + s < 0 ? + // The element was removed if the next element in our ordered + // walkthrough is only in `before`. + i(e[a++]) : s > 0 ? + // The element was added if the next element in our ordered walkthrough + // is only in `after`. + r(t[_++]) : (_++, a++); + } + for (;_ < o; ) r(t[_++]); + for (;a < s; ) i(e[a++]); + } + /** + * Verifies equality for an array of primitives. + * + * @private + * @internal + * @param left Array of primitives. + * @param right Array of primitives. + * @return True if arrays are equal. + */ (n, t, __PRIVATE_fieldIndexSemanticComparator, (t => { + i.push(r.addFieldIndex(e, t)); + }), (t => { + i.push(r.deleteFieldIndex(e, t)); + })))).next((() => PersistencePromise.waitFor(i))))); + }(await __PRIVATE_getLocalStore(e), t))); +} + +function __PRIVATE_firestoreClientSetPersistentCacheIndexAutoCreationEnabled(e, t) { + return e.asyncQueue.enqueue((async () => function __PRIVATE_localStoreSetIndexAutoCreationEnabled(e, t) { + __PRIVATE_debugCast(e).Fs.Vs = t; + }(await __PRIVATE_getLocalStore(e), t))); +} + +function __PRIVATE_firestoreClientDeleteAllFieldIndexes(e) { + return e.asyncQueue.enqueue((async () => function __PRIVATE_localStoreDeleteAllFieldIndexes(e) { + const t = __PRIVATE_debugCast(e), n = t.indexManager; + return t.persistence.runTransaction("Delete All Indexes", "readwrite", (e => n.deleteAllFieldIndexes(e))); + }(await __PRIVATE_getLocalStore(e)))); +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Compares two `ExperimentalLongPollingOptions` objects for equality. + */ +/** + * Creates and returns a new `ExperimentalLongPollingOptions` with the same + * option values as the given instance. + */ +function __PRIVATE_cloneLongPollingOptions(e) { + const t = {}; + return void 0 !== e.timeoutSeconds && (t.timeoutSeconds = e.timeoutSeconds), t; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const _n = new Map; + +/** + * An instance map that ensures only one Datastore exists per Firestore + * instance. + */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// settings() defaults: +const an = "firestore.googleapis.com", un = !0; + +/** + * A concrete type describing all the values that can be applied via a + * user-supplied `FirestoreSettings` object. This is a separate type so that + * defaults can be supplied and the value can be checked for equality. + */ +class FirestoreSettingsImpl { + constructor(e) { + if (void 0 === e.host) { + if (void 0 !== e.ssl) throw new FirestoreError(N.INVALID_ARGUMENT, "Can't provide ssl option if host option is not set"); + this.host = an, this.ssl = un; + } else this.host = e.host, this.ssl = e.ssl ?? un; + if (this.isUsingEmulator = void 0 !== e.emulatorOptions, this.credentials = e.credentials, + this.ignoreUndefinedProperties = !!e.ignoreUndefinedProperties, this.localCache = e.localCache, + void 0 === e.cacheSizeBytes) this.cacheSizeBytes = Ot; else { + if (-1 !== e.cacheSizeBytes && e.cacheSizeBytes < Bt) throw new FirestoreError(N.INVALID_ARGUMENT, "cacheSizeBytes must be at least 1048576"); + this.cacheSizeBytes = e.cacheSizeBytes; + } + __PRIVATE_validateIsNotUsedTogether("experimentalForceLongPolling", e.experimentalForceLongPolling, "experimentalAutoDetectLongPolling", e.experimentalAutoDetectLongPolling), + this.experimentalForceLongPolling = !!e.experimentalForceLongPolling, this.experimentalForceLongPolling ? this.experimentalAutoDetectLongPolling = !1 : void 0 === e.experimentalAutoDetectLongPolling ? this.experimentalAutoDetectLongPolling = true : + // For backwards compatibility, coerce the value to boolean even though + // the TypeScript compiler has narrowed the type to boolean already. + // noinspection PointlessBooleanExpressionJS + this.experimentalAutoDetectLongPolling = !!e.experimentalAutoDetectLongPolling, + this.experimentalLongPollingOptions = __PRIVATE_cloneLongPollingOptions(e.experimentalLongPollingOptions ?? {}), + function __PRIVATE_validateLongPollingOptions(e) { + if (void 0 !== e.timeoutSeconds) { + if (isNaN(e.timeoutSeconds)) throw new FirestoreError(N.INVALID_ARGUMENT, `invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`); + if (e.timeoutSeconds < 5) throw new FirestoreError(N.INVALID_ARGUMENT, `invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`); + if (e.timeoutSeconds > 30) throw new FirestoreError(N.INVALID_ARGUMENT, `invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`); + } + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ (this.experimentalLongPollingOptions), this.useFetchStreams = !!e.useFetchStreams; + } + isEqual(e) { + return this.host === e.host && this.ssl === e.ssl && this.credentials === e.credentials && this.cacheSizeBytes === e.cacheSizeBytes && this.experimentalForceLongPolling === e.experimentalForceLongPolling && this.experimentalAutoDetectLongPolling === e.experimentalAutoDetectLongPolling && function __PRIVATE_longPollingOptionsEqual(e, t) { + return e.timeoutSeconds === t.timeoutSeconds; + }(this.experimentalLongPollingOptions, e.experimentalLongPollingOptions) && this.ignoreUndefinedProperties === e.ignoreUndefinedProperties && this.useFetchStreams === e.useFetchStreams; + } +} + +class Firestore$1 { + /** @hideconstructor */ + constructor(e, t, n, r) { + this._authCredentials = e, this._appCheckCredentials = t, this._databaseId = n, + this._app = r, + /** + * Whether it's a Firestore or Firestore Lite instance. + */ + this.type = "firestore-lite", this._persistenceKey = "(lite)", this._settings = new FirestoreSettingsImpl({}), + this._settingsFrozen = !1, this._emulatorOptions = {}, + // A task that is assigned when the terminate() is invoked and resolved when + // all components have shut down. Otherwise, Firestore is not terminated, + // which can mean either the FirestoreClient is in the process of starting, + // or restarting. + this._terminateTask = "notTerminated"; + } + /** + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service + * instance. + */ get app() { + if (!this._app) throw new FirestoreError(N.FAILED_PRECONDITION, "Firestore was not initialized using the Firebase SDK. 'app' is not available"); + return this._app; + } + get _initialized() { + return this._settingsFrozen; + } + get _terminated() { + return "notTerminated" !== this._terminateTask; + } + _setSettings(e) { + if (this._settingsFrozen) throw new FirestoreError(N.FAILED_PRECONDITION, "Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object."); + this._settings = new FirestoreSettingsImpl(e), this._emulatorOptions = e.emulatorOptions || {}, + void 0 !== e.credentials && (this._authCredentials = function __PRIVATE_makeAuthCredentialsProvider(e) { + if (!e) return new __PRIVATE_EmptyAuthCredentialsProvider; + switch (e.type) { + case "firstParty": + return new __PRIVATE_FirstPartyAuthCredentialsProvider(e.sessionIndex || "0", e.iamToken || null, e.authTokenFactory || null); + + case "provider": + return e.client; + + default: + throw new FirestoreError(N.INVALID_ARGUMENT, "makeAuthCredentialsProvider failed due to invalid credential type"); + } + }(e.credentials)); + } + _getSettings() { + return this._settings; + } + _getEmulatorOptions() { + return this._emulatorOptions; + } + _freezeSettings() { + return this._settingsFrozen = !0, this._settings; + } + _delete() { + // The `_terminateTask` must be assigned future that completes when + // terminate is complete. The existence of this future puts SDK in state + // that will not accept further API interaction. + return "notTerminated" === this._terminateTask && (this._terminateTask = this._terminate()), + this._terminateTask; + } + async _restart() { + // The `_terminateTask` must equal 'notTerminated' after restart to + // signal that client is in a state that accepts API calls. + "notTerminated" === this._terminateTask ? await this._terminate() : this._terminateTask = "notTerminated"; + } + /** Returns a JSON-serializable representation of this `Firestore` instance. */ toJSON() { + return { + app: this._app, + databaseId: this._databaseId, + settings: this._settings + }; + } + /** + * Terminates all components used by this client. Subclasses can override + * this method to clean up their own dependencies, but must also call this + * method. + * + * Only ever called once. + */ _terminate() { + /** + * Removes all components associated with the provided instance. Must be called + * when the `Firestore` instance is terminated. + */ + return function __PRIVATE_removeComponents(e) { + const t = _n.get(e); + t && (__PRIVATE_logDebug("ComponentProvider", "Removing Datastore"), _n.delete(e), + t.terminate()); + }(this), Promise.resolve(); + } +} + +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ function connectFirestoreEmulator(e, t, n, r = {}) { + e = __PRIVATE_cast(e, Firestore$1); + const i = util.isCloudWorkstation(t), s = e._getSettings(), o = { + ...s, + emulatorOptions: e._getEmulatorOptions() + }, _ = `${t}:${n}`; + i && (util.pingServer(`https://${_}`), util.updateEmulatorBanner("Firestore", !0)), s.host !== an && s.host !== _ && __PRIVATE_logWarn("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."); + const a = { + ...s, + host: _, + ssl: i, + emulatorOptions: r + }; + // No-op if the new configuration matches the current configuration. This supports SSR + // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice. + if (!util.deepEqual(a, o) && (e._setSettings(a), r.mockUserToken)) { + let t, n; + if ("string" == typeof r.mockUserToken) t = r.mockUserToken, n = User.MOCK_USER; else { + // Let createMockUserToken validate first (catches common mistakes like + // invalid field "uid" and missing field "sub" / "user_id".) + t = util.createMockUserToken(r.mockUserToken, e._app?.options.projectId); + const i = r.mockUserToken.sub || r.mockUserToken.user_id; + if (!i) throw new FirestoreError(N.INVALID_ARGUMENT, "mockUserToken must contain 'sub' or 'user_id' field!"); + n = new User(i); + } + e._authCredentials = new __PRIVATE_EmulatorAuthCredentialsProvider(new __PRIVATE_OAuthToken(t, n)); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `Query` refers to a query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ class Query { + // This is the lite version of the Query class in the main SDK. + /** @hideconstructor protected */ + constructor(e, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + t, n) { + this.converter = t, this._query = n, + /** The type of this Firestore reference. */ + this.type = "query", this.firestore = e; + } + withConverter(e) { + return new Query(this.firestore, e, this._query); + } +} + +/** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. + */ class DocumentReference { + /** @hideconstructor */ + constructor(e, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + t, n) { + this.converter = t, this._key = n, + /** The type of this Firestore reference. */ + this.type = "document", this.firestore = e; + } + get _path() { + return this._key.path; + } + /** + * The document's identifier within its collection. + */ get id() { + return this._key.path.lastSegment(); + } + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ get path() { + return this._key.path.canonicalString(); + } + /** + * The collection this `DocumentReference` belongs to. + */ get parent() { + return new CollectionReference(this.firestore, this.converter, this._key.path.popLast()); + } + withConverter(e) { + return new DocumentReference(this.firestore, e, this._key); + } + /** + * Returns a JSON-serializable representation of this `DocumentReference` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + type: DocumentReference._jsonSchemaVersion, + referencePath: this._key.toString() + }; + } + static fromJSON(e, t, n) { + if (__PRIVATE_validateJSON(t, DocumentReference._jsonSchema)) return new DocumentReference(e, n || null, new DocumentKey(ResourcePath.fromString(t.referencePath))); + } +} + +DocumentReference._jsonSchemaVersion = "firestore/documentReference/1.0", DocumentReference._jsonSchema = { + type: property("string", DocumentReference._jsonSchemaVersion), + referencePath: property("string") +}; + +/** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using {@link (query:1)}). + */ +class CollectionReference extends Query { + /** @hideconstructor */ + constructor(e, t, n) { + super(e, t, __PRIVATE_newQueryForPath(n)), this._path = n, + /** The type of this Firestore reference. */ + this.type = "collection"; + } + /** The collection's identifier. */ get id() { + return this._query.path.lastSegment(); + } + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ get path() { + return this._query.path.canonicalString(); + } + /** + * A reference to the containing `DocumentReference` if this is a + * subcollection. If this isn't a subcollection, the reference is null. + */ get parent() { + const e = this._path.popLast(); + return e.isEmpty() ? null : new DocumentReference(this.firestore, + /* converter= */ null, new DocumentKey(e)); + } + withConverter(e) { + return new CollectionReference(this.firestore, e, this._path); + } +} + +function collection(e, t, ...n) { + if (e = util.getModularInstance(e), __PRIVATE_validateNonEmptyArgument("collection", "path", t), e instanceof Firestore$1) { + const r = ResourcePath.fromString(t, ...n); + return __PRIVATE_validateCollectionPath(r), new CollectionReference(e, /* converter= */ null, r); + } + { + if (!(e instanceof DocumentReference || e instanceof CollectionReference)) throw new FirestoreError(N.INVALID_ARGUMENT, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore"); + const r = e._path.child(ResourcePath.fromString(t, ...n)); + return __PRIVATE_validateCollectionPath(r), new CollectionReference(e.firestore, + /* converter= */ null, r); + } +} + +// TODO(firestorelite): Consider using ErrorFactory - +// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106 +/** + * Creates and returns a new `Query` instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given `collectionId`. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param collectionId - Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `Query`. + */ function collectionGroup(e, t) { + if (e = __PRIVATE_cast(e, Firestore$1), __PRIVATE_validateNonEmptyArgument("collectionGroup", "collection id", t), + t.indexOf("/") >= 0) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`); + return new Query(e, + /* converter= */ null, function __PRIVATE_newQueryForCollectionGroup(e) { + return new __PRIVATE_QueryImpl(ResourcePath.emptyPath(), e); + }(t)); +} + +function doc(e, t, ...n) { + if (e = util.getModularInstance(e), + // We allow omission of 'pathString' but explicitly prohibit passing in both + // 'undefined' and 'null'. + 1 === arguments.length && (t = __PRIVATE_AutoId.newId()), __PRIVATE_validateNonEmptyArgument("doc", "path", t), + e instanceof Firestore$1) { + const r = ResourcePath.fromString(t, ...n); + return __PRIVATE_validateDocumentPath(r), new DocumentReference(e, + /* converter= */ null, new DocumentKey(r)); + } + { + if (!(e instanceof DocumentReference || e instanceof CollectionReference)) throw new FirestoreError(N.INVALID_ARGUMENT, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore"); + const r = e._path.child(ResourcePath.fromString(t, ...n)); + return __PRIVATE_validateDocumentPath(r), new DocumentReference(e.firestore, e instanceof CollectionReference ? e.converter : null, new DocumentKey(r)); + } +} + +/** + * Returns true if the provided references are equal. + * + * @param left - A reference to compare. + * @param right - A reference to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ function refEqual(e, t) { + return e = util.getModularInstance(e), t = util.getModularInstance(t), (e instanceof DocumentReference || e instanceof CollectionReference) && (t instanceof DocumentReference || t instanceof CollectionReference) && (e.firestore === t.firestore && e.path === t.path && e.converter === t.converter); +} + +/** + * Returns true if the provided queries point to the same collection and apply + * the same constraints. + * + * @param left - A `Query` to compare. + * @param right - A `Query` to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ function queryEqual(e, t) { + return e = util.getModularInstance(e), t = util.getModularInstance(t), e instanceof Query && t instanceof Query && (e.firestore === t.firestore && __PRIVATE_queryEquals(e._query, t._query) && e.converter === t.converter); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const cn = "AsyncQueue"; + +class __PRIVATE_AsyncQueueImpl { + constructor(e = Promise.resolve()) { + // A list of retryable operations. Retryable operations are run in order and + // retried with backoff. + this.Xu = [], + // Is this AsyncQueue being shut down? Once it is set to true, it will not + // be changed again. + this.ec = !1, + // Operations scheduled to be queued in the future. Operations are + // automatically removed after they are run or canceled. + this.tc = [], + // visible for testing + this.nc = null, + // Flag set while there's an outstanding AsyncQueue operation, used for + // assertion sanity-checks. + this.rc = !1, + // Enabled during shutdown on Safari to prevent future access to IndexedDB. + this.sc = !1, + // List of TimerIds to fast-forward delays for. + this.oc = [], + // Backoff timer used to schedule retries for retryable operations + this.M_ = new __PRIVATE_ExponentialBackoff(this, "async_queue_retry" /* TimerId.AsyncQueueRetry */), + // Visibility handler that triggers an immediate retry of all retryable + // operations. Meant to speed up recovery when we regain file system access + // after page comes into foreground. + this._c = () => { + const e = getDocument(); + e && __PRIVATE_logDebug(cn, "Visibility state changed to " + e.visibilityState), + this.M_.w_(); + }, this.ac = e; + const t = getDocument(); + t && "function" == typeof t.addEventListener && t.addEventListener("visibilitychange", this._c); + } + get isShuttingDown() { + return this.ec; + } + /** + * Adds a new operation to the queue without waiting for it to complete (i.e. + * we ignore the Promise result). + */ enqueueAndForget(e) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.enqueue(e); + } + enqueueAndForgetEvenWhileRestricted(e) { + this.uc(), + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.cc(e); + } + enterRestrictedMode(e) { + if (!this.ec) { + this.ec = !0, this.sc = e || !1; + const t = getDocument(); + t && "function" == typeof t.removeEventListener && t.removeEventListener("visibilitychange", this._c); + } + } + enqueue(e) { + if (this.uc(), this.ec) + // Return a Promise which never resolves. + return new Promise((() => {})); + // Create a deferred Promise that we can return to the callee. This + // allows us to return a "hanging Promise" only to the callee and still + // advance the queue even when the operation is not run. + const t = new __PRIVATE_Deferred; + return this.cc((() => this.ec && this.sc ? Promise.resolve() : (e().then(t.resolve, t.reject), + t.promise))).then((() => t.promise)); + } + enqueueRetryable(e) { + this.enqueueAndForget((() => (this.Xu.push(e), this.lc()))); + } + /** + * Runs the next operation from the retryable queue. If the operation fails, + * reschedules with backoff. + */ async lc() { + if (0 !== this.Xu.length) { + try { + await this.Xu[0](), this.Xu.shift(), this.M_.reset(); + } catch (e) { + if (!__PRIVATE_isIndexedDbTransactionError(e)) throw e; + // Failure will be handled by AsyncQueue + __PRIVATE_logDebug(cn, "Operation failed with retryable error: " + e); + } + this.Xu.length > 0 && + // If there are additional operations, we re-schedule `retryNextOp()`. + // This is necessary to run retryable operations that failed during + // their initial attempt since we don't know whether they are already + // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1` + // needs to be re-run, we will run `op1`, `op1`, `op2` using the + // already enqueued calls to `retryNextOp()`. `op3()` will then run in the + // call scheduled here. + // Since `backoffAndRun()` cancels an existing backoff and schedules a + // new backoff on every call, there is only ever a single additional + // operation in the queue. + this.M_.p_((() => this.lc())); + } + } + cc(e) { + const t = this.ac.then((() => (this.rc = !0, e().catch((e => { + this.nc = e, this.rc = !1; + // Re-throw the error so that this.tail becomes a rejected Promise and + // all further attempts to chain (via .then) will just short-circuit + // and return the rejected Promise. + throw __PRIVATE_logError("INTERNAL UNHANDLED ERROR: ", __PRIVATE_getMessageOrStack(e)), + e; + })).then((e => (this.rc = !1, e)))))); + return this.ac = t, t; + } + enqueueAfterDelay(e, t, n) { + this.uc(), + // Fast-forward delays for timerIds that have been overridden. + this.oc.indexOf(e) > -1 && (t = 0); + const r = DelayedOperation.createAndSchedule(this, e, t, n, (e => this.hc(e))); + return this.tc.push(r), r; + } + uc() { + this.nc && fail(47125, { + Pc: __PRIVATE_getMessageOrStack(this.nc) + }); + } + verifyOperationInProgress() {} + /** + * Waits until all currently queued tasks are finished executing. Delayed + * operations are not run. + */ async Tc() { + // Operations in the queue prior to draining may have enqueued additional + // operations. Keep draining the queue until the tail is no longer advanced, + // which indicates that no more new operations were enqueued and that all + // operations were executed. + let e; + do { + e = this.ac, await e; + } while (e !== this.ac); + } + /** + * For Tests: Determine if a delayed operation with a particular TimerId + * exists. + */ Ic(e) { + for (const t of this.tc) if (t.timerId === e) return !0; + return !1; + } + /** + * For Tests: Runs some or all delayed operations early. + * + * @param lastTimerId - Delayed operations up to and including this TimerId + * will be drained. Pass TimerId.All to run all delayed operations. + * @returns a Promise that resolves once all operations have been run. + */ Ec(e) { + // Note that draining may generate more delayed ops, so we do that first. + return this.Tc().then((() => { + // Run ops in the same order they'd run if they ran naturally. + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ + this.tc.sort(((e, t) => e.targetTimeMs - t.targetTimeMs)); + for (const t of this.tc) if (t.skipDelay(), "all" /* TimerId.All */ !== e && t.timerId === e) break; + return this.Tc(); + })); + } + /** + * For Tests: Skip all subsequent delays for a timer id. + */ dc(e) { + this.oc.push(e); + } + /** Called once a DelayedOperation is run or canceled. */ hc(e) { + // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small. + const t = this.tc.indexOf(e); + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ this.tc.splice(t, 1); + } +} + +/** + * Chrome includes Error.message in Error.stack. Other browsers do not. + * This returns expected output of message + stack when available. + * @param error - Error or FirestoreError + */ function __PRIVATE_getMessageOrStack(e) { + let t = e.message || ""; + return e.stack && (t = e.stack.includes(e.message) ? e.stack : e.message + "\n" + e.stack), + t; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_isPartialObserver(e) { + /** + * Returns true if obj is an object and contains at least one of the specified + * methods. + */ + return function __PRIVATE_implementsAnyMethods(e, t) { + if ("object" != typeof e || null === e) return !1; + const n = e; + for (const e of t) if (e in n && "function" == typeof n[e]) return !0; + return !1; + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Represents the task of loading a Firestore bundle. It provides progress of bundle + * loading, as well as task completion and error events. + * + * The API is compatible with `Promise`. + */ (e, [ "next", "error", "complete" ]); +} + +class LoadBundleTask { + constructor() { + this._progressObserver = {}, this._taskCompletionResolver = new __PRIVATE_Deferred, + this._lastProgress = { + taskState: "Running", + totalBytes: 0, + totalDocuments: 0, + bytesLoaded: 0, + documentsLoaded: 0 + }; + } + /** + * Registers functions to listen to bundle loading progress events. + * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur + * each time a Firestore document is loaded from the bundle. + * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the + * error, and there should be no more updates after this. + * @param complete - Called when the loading task is complete. + */ onProgress(e, t, n) { + this._progressObserver = { + next: e, + error: t, + complete: n + }; + } + /** + * Implements the `Promise.catch` interface. + * + * @param onRejected - Called when an error occurs during bundle loading. + */ catch(e) { + return this._taskCompletionResolver.promise.catch(e); + } + /** + * Implements the `Promise.then` interface. + * + * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update. + * The update will always have its `taskState` set to `"Success"`. + * @param onRejected - Called when an error occurs during bundle loading. + */ then(e, t) { + return this._taskCompletionResolver.promise.then(e, t); + } + /** + * Notifies all observers that bundle loading has completed, with a provided + * `LoadBundleTaskProgress` object. + * + * @private + */ _completeWith(e) { + this._updateProgress(e), this._progressObserver.complete && this._progressObserver.complete(), + this._taskCompletionResolver.resolve(e); + } + /** + * Notifies all observers that bundle loading has failed, with a provided + * `Error` as the reason. + * + * @private + */ _failWith(e) { + this._lastProgress.taskState = "Error", this._progressObserver.next && this._progressObserver.next(this._lastProgress), + this._progressObserver.error && this._progressObserver.error(e), this._taskCompletionResolver.reject(e); + } + /** + * Notifies a progress update of loading a bundle. + * @param progress - The new progress. + * + * @private + */ _updateProgress(e) { + this._lastProgress = e, this._progressObserver.next && this._progressObserver.next(e); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Constant used to indicate the LRU garbage collection should be disabled. + * Set this value as the `cacheSizeBytes` on the settings passed to the + * {@link Firestore} instance. + */ const ln = -1; + +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ class Firestore extends Firestore$1 { + /** @hideconstructor */ + constructor(e, t, n, r) { + super(e, t, n, r), + /** + * Whether it's a {@link Firestore} or Firestore Lite instance. + */ + this.type = "firestore", this._queue = new __PRIVATE_AsyncQueueImpl, this._persistenceKey = r?.name || "[DEFAULT]"; + } + async _terminate() { + if (this._firestoreClient) { + const e = this._firestoreClient.terminate(); + this._queue = new __PRIVATE_AsyncQueueImpl(e), this._firestoreClient = void 0, await e; + } + } +} + +/** + * Initializes a new instance of {@link Firestore} with the provided settings. + * Can only be called before any other function, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will + * be associated. + * @param settings - A settings object to configure the {@link Firestore} instance. + * @param databaseId - The name of the database. + * @returns A newly initialized {@link Firestore} instance. + */ function initializeFirestore(e, t, n) { + n || (n = lt); + const r = app._getProvider(e, "firestore"); + if (r.isInitialized(n)) { + const e = r.getImmediate({ + identifier: n + }), i = r.getOptions(n); + if (util.deepEqual(i, t)) return e; + throw new FirestoreError(N.FAILED_PRECONDITION, "initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance."); + } + if (void 0 !== t.cacheSizeBytes && void 0 !== t.localCache) throw new FirestoreError(N.INVALID_ARGUMENT, "cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes willbe deprecated. Instead, specify the cache size in the cache object"); + if (void 0 !== t.cacheSizeBytes && -1 !== t.cacheSizeBytes && t.cacheSizeBytes < Bt) throw new FirestoreError(N.INVALID_ARGUMENT, "cacheSizeBytes must be at least 1048576"); + // Workaround to get cookies in Firebase Studio + return t.host && util.isCloudWorkstation(t.host) && util.pingServer(t.host), r.initialize({ + options: t, + instanceIdentifier: n + }); +} + +function getFirestore(e, n) { + const r = "object" == typeof e ? e : app.getApp(), i = "string" == typeof e ? e : n || lt, s = app._getProvider(r, "firestore").getImmediate({ + identifier: i + }); + if (!s._initialized) { + const e = util.getDefaultEmulatorHostnameAndPort("firestore"); + e && connectFirestoreEmulator(s, ...e); + } + return s; +} + +/** + * @internal + */ function ensureFirestoreConfigured(e) { + if (e._terminated) throw new FirestoreError(N.FAILED_PRECONDITION, "The client has already been terminated."); + return e._firestoreClient || __PRIVATE_configureFirestore(e), e._firestoreClient; +} + +function __PRIVATE_configureFirestore(e) { + const t = e._freezeSettings(), n = function __PRIVATE_makeDatabaseInfo(e, t, n, r) { + return new DatabaseInfo(e, t, n, r.host, r.ssl, r.experimentalForceLongPolling, r.experimentalAutoDetectLongPolling, __PRIVATE_cloneLongPollingOptions(r.experimentalLongPollingOptions), r.useFetchStreams, r.isUsingEmulator); + }(e._databaseId, e._app?.options.appId || "", e._persistenceKey, t); + e._componentsProvider || t.localCache?._offlineComponentProvider && t.localCache?._onlineComponentProvider && (e._componentsProvider = { + _offline: t.localCache._offlineComponentProvider, + _online: t.localCache._onlineComponentProvider + }), e._firestoreClient = new FirestoreClient(e._authCredentials, e._appCheckCredentials, e._queue, n, e._componentsProvider && function __PRIVATE_buildComponentProvider(e) { + const t = e?._online.build(); + return { + _offline: e?._offline.build(t), + _online: t + }; + } + /** + * Attempts to enable persistent storage, if possible. + * + * On failure, `enableIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. + * + * * failed-precondition: The app is already open in another browser tab. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. + * + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. + * + * Note: `enableIndexedDbPersistence()` must be called before any other functions + * (other than {@link initializeFirestore}, {@link (getFirestore:1)} or + * {@link clearIndexedDbPersistence}. + * + * Persistence cannot be used in a Node.js environment. + * + * @param firestore - The {@link Firestore} instance to enable persistence for. + * @param persistenceSettings - Optional settings object to configure + * persistence. + * @returns A `Promise` that represents successfully enabling persistent storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on IndexedDb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. + */ (e._componentsProvider)); +} + +function enableIndexedDbPersistence(e, t) { + __PRIVATE_logWarn("enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead."); + const n = e._freezeSettings(); + return __PRIVATE_setPersistenceProviders(e, OnlineComponentProvider.provider, { + build: e => new __PRIVATE_IndexedDbOfflineComponentProvider(e, n.cacheSizeBytes, t?.forceOwnership) + }), Promise.resolve(); +} + +/** + * Attempts to enable multi-tab persistent storage, if possible. If enabled + * across all tabs, all operations share access to local persistence, including + * shared execution of queries and latency-compensated local document updates + * across all connected instances. + * + * On failure, `enableMultiTabIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. + * + * * failed-precondition: The app is already open in another browser tab and + * multi-tab is not enabled. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. + * + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. + * + * @param firestore - The {@link Firestore} instance to enable persistence for. + * @returns A `Promise` that represents successfully enabling persistent + * storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on indexeddb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. + */ async function enableMultiTabIndexedDbPersistence(e) { + __PRIVATE_logWarn("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead."); + const t = e._freezeSettings(); + __PRIVATE_setPersistenceProviders(e, OnlineComponentProvider.provider, { + build: e => new __PRIVATE_MultiTabOfflineComponentProvider(e, t.cacheSizeBytes) + }); +} + +/** + * Registers both the `OfflineComponentProvider` and `OnlineComponentProvider`. + * If the operation fails with a recoverable error (see + * `canRecoverFromIndexedDbError()` below), the returned Promise is rejected + * but the client remains usable. + */ function __PRIVATE_setPersistenceProviders(e, t, n) { + if ((e = __PRIVATE_cast(e, Firestore))._firestoreClient || e._terminated) throw new FirestoreError(N.FAILED_PRECONDITION, "Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object."); + if (e._componentsProvider || e._getSettings().localCache) throw new FirestoreError(N.FAILED_PRECONDITION, "SDK cache is already specified."); + e._componentsProvider = { + _online: t, + _offline: n + }, __PRIVATE_configureFirestore(e); +} + +/** + * Clears the persistent storage. This includes pending writes and cached + * documents. + * + * Must be called while the {@link Firestore} instance is not started (after the app is + * terminated or when the app is first initialized). On startup, this function + * must be called before other functions (other than {@link + * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore} + * instance is still running, the promise will be rejected with the error code + * of `failed-precondition`. + * + * Note: `clearIndexedDbPersistence()` is primarily intended to help write + * reliable tests that use Cloud Firestore. It uses an efficient mechanism for + * dropping existing data but does not attempt to securely overwrite or + * otherwise make cached data unrecoverable. For applications that are sensitive + * to the disclosure of cached data in between user sessions, we strongly + * recommend not enabling persistence at all. + * + * @param firestore - The {@link Firestore} instance to clear persistence for. + * @returns A `Promise` that is resolved when the persistent storage is + * cleared. Otherwise, the promise is rejected with an error. + */ function clearIndexedDbPersistence(e) { + if (e._initialized && !e._terminated) throw new FirestoreError(N.FAILED_PRECONDITION, "Persistence can only be cleared before a Firestore instance is initialized or after it is terminated."); + const t = new __PRIVATE_Deferred; + return e._queue.enqueueAndForgetEvenWhileRestricted((async () => { + try { + await async function __PRIVATE_indexedDbClearPersistence(e) { + if (!__PRIVATE_SimpleDb.v()) return Promise.resolve(); + const t = e + $t; + await __PRIVATE_SimpleDb.delete(t); + }(__PRIVATE_indexedDbStoragePrefix(e._databaseId, e._persistenceKey)), t.resolve(); + } catch (e) { + t.reject(e); + } + })), t.promise; +} + +/** + * Waits until all currently pending writes for the active user have been + * acknowledged by the backend. + * + * The returned promise resolves immediately if there are no outstanding writes. + * Otherwise, the promise waits for all previously issued writes (including + * those written in a previous app session), but it does not wait for writes + * that were added after the function is called. If you want to wait for + * additional writes, call `waitForPendingWrites()` again. + * + * Any outstanding `waitForPendingWrites()` promises are rejected during user + * changes. + * + * @returns A `Promise` which resolves when all currently pending writes have been + * acknowledged by the backend. + */ function waitForPendingWrites(e) { + return function __PRIVATE_firestoreClientWaitForPendingWrites(e) { + const t = new __PRIVATE_Deferred; + return e.asyncQueue.enqueueAndForget((async () => __PRIVATE_syncEngineRegisterPendingWritesCallback(await __PRIVATE_getSyncEngine(e), t))), + t.promise; + }(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore))); +} + +/** + * Re-enables use of the network for this {@link Firestore} instance after a prior + * call to {@link disableNetwork}. + * + * @returns A `Promise` that is resolved once the network has been enabled. + */ function enableNetwork(e) { + return __PRIVATE_firestoreClientEnableNetwork(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore))); +} + +/** + * Disables network usage for this instance. It can be re-enabled via {@link + * enableNetwork}. While the network is disabled, any snapshot listeners, + * `getDoc()` or `getDocs()` calls will return results from cache, and any write + * operations will be queued until the network is restored. + * + * @returns A `Promise` that is resolved once the network has been disabled. + */ function disableNetwork(e) { + return __PRIVATE_firestoreClientDisableNetwork(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore))); +} + +/** + * Terminates the provided {@link Firestore} instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` function + * may be used. Any other function will throw a `FirestoreError`. + * + * To restart after termination, create a new instance of FirebaseFirestore with + * {@link (getFirestore:1)}. + * + * Termination does not cancel any pending writes, and any promises that are + * awaiting a response from the server will not be resolved. If you have + * persistence enabled, the next time you start this instance, it will resume + * sending these writes to the server. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all + * of its resources or in combination with `clearIndexedDbPersistence()` to + * ensure that all local state is destroyed between test runs. + * + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ function terminate(e) { + return app._removeServiceInstance(e.app, "firestore", e._databaseId.database), e._delete(); +} + +/** + * Loads a Firestore bundle into the local cache. + * + * @param firestore - The {@link Firestore} instance to load bundles for. + * @param bundleData - An object representing the bundle to be loaded. Valid + * objects are `ArrayBuffer`, `ReadableStream` or `string`. + * + * @returns A `LoadBundleTask` object, which notifies callers with progress + * updates, and completion or error events. It can be used as a + * `Promise`. + */ function loadBundle(e, t) { + const n = ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)), r = new LoadBundleTask; + return __PRIVATE_firestoreClientLoadBundle(n, e._databaseId, t, r), r; +} + +/** + * Reads a Firestore {@link Query} from local cache, identified by the given + * name. + * + * The named queries are packaged into bundles on the server side (along + * with resulting documents), and loaded to local cache using `loadBundle`. Once + * in local cache, use this method to extract a {@link Query} by name. + * + * @param firestore - The {@link Firestore} instance to read the query from. + * @param name - The name of the query. + * @returns A `Promise` that is resolved with the Query or `null`. + */ function namedQuery(e, t) { + return __PRIVATE_firestoreClientGetNamedQuery(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)), t).then((t => t ? new Query(e, null, t.query) : null)); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents an aggregation that can be performed by Firestore. + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +class AggregateField { + /** + * Create a new AggregateField + * @param aggregateType Specifies the type of aggregation operation to perform. + * @param _internalFieldPath Optionally specifies the field that is aggregated. + * @internal + */ + constructor(e = "count", t) { + this._internalFieldPath = t, + /** A type string to uniquely identify instances of this class. */ + this.type = "AggregateField", this.aggregateType = e; + } +} + +/** + * The results of executing an aggregation query. + */ class AggregateQuerySnapshot { + /** @hideconstructor */ + constructor(e, t, n) { + this._userDataWriter = t, this._data = n, + /** A type string to uniquely identify instances of this class. */ + this.type = "AggregateQuerySnapshot", this.query = e; + } + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ data() { + return this._userDataWriter.convertObjectMap(this._data); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing an array of bytes. + */ class Bytes { + /** @hideconstructor */ + constructor(e) { + this._byteString = e; + } + /** + * Creates a new `Bytes` object from the given Base64 string, converting it to + * bytes. + * + * @param base64 - The Base64 string used to create the `Bytes` object. + */ static fromBase64String(e) { + try { + return new Bytes(ByteString.fromBase64String(e)); + } catch (e) { + throw new FirestoreError(N.INVALID_ARGUMENT, "Failed to construct data from Base64 string: " + e); + } + } + /** + * Creates a new `Bytes` object from the given Uint8Array. + * + * @param array - The Uint8Array used to create the `Bytes` object. + */ static fromUint8Array(e) { + return new Bytes(ByteString.fromUint8Array(e)); + } + /** + * Returns the underlying bytes as a Base64-encoded string. + * + * @returns The Base64-encoded string created from the `Bytes` object. + */ toBase64() { + return this._byteString.toBase64(); + } + /** + * Returns the underlying bytes in a new `Uint8Array`. + * + * @returns The Uint8Array created from the `Bytes` object. + */ toUint8Array() { + return this._byteString.toUint8Array(); + } + /** + * Returns a string representation of the `Bytes` object. + * + * @returns A string representation of the `Bytes` object. + */ toString() { + return "Bytes(base64: " + this.toBase64() + ")"; + } + /** + * Returns true if this `Bytes` object is equal to the provided one. + * + * @param other - The `Bytes` object to compare against. + * @returns true if this `Bytes` object is equal to the provided one. + */ isEqual(e) { + return this._byteString.isEqual(e._byteString); + } + /** + * Returns a JSON-serializable representation of this `Bytes` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + type: Bytes._jsonSchemaVersion, + bytes: this.toBase64() + }; + } + /** + * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}. + * + * @param json a JSON object represention of a `Bytes` instance + * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ static fromJSON(e) { + if (__PRIVATE_validateJSON(e, Bytes._jsonSchema)) return Bytes.fromBase64String(e.bytes); + } +} + +Bytes._jsonSchemaVersion = "firestore/bytes/1.0", Bytes._jsonSchema = { + type: property("string", Bytes._jsonSchemaVersion), + bytes: property("string") +}; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `FieldPath` refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + * + * Create a `FieldPath` by providing field names. If more than one field + * name is provided, the path will point to a nested field in a document. + */ +class FieldPath { + /** + * Creates a `FieldPath` from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames - A list of field names. + */ + constructor(...e) { + for (let t = 0; t < e.length; ++t) if (0 === e[t].length) throw new FirestoreError(N.INVALID_ARGUMENT, "Invalid field name at argument $(i + 1). Field names must not be empty."); + this._internalPath = new FieldPath$1(e); + } + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other - The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ isEqual(e) { + return this._internalPath.isEqual(e._internalPath); + } +} + +/** + * Returns a special sentinel `FieldPath` to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ function documentId() { + return new FieldPath(k); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Sentinel values that can be used when writing document fields with `set()` + * or `update()`. + */ class FieldValue { + /** + * @param _methodName - The public API endpoint that returns this class. + * @hideconstructor + */ + constructor(e) { + this._methodName = e; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ class GeoPoint { + /** + * Creates a new immutable `GeoPoint` object with the provided latitude and + * longitude values. + * @param latitude - The latitude as number between -90 and 90. + * @param longitude - The longitude as number between -180 and 180. + */ + constructor(e, t) { + if (!isFinite(e) || e < -90 || e > 90) throw new FirestoreError(N.INVALID_ARGUMENT, "Latitude must be a number between -90 and 90, but was: " + e); + if (!isFinite(t) || t < -180 || t > 180) throw new FirestoreError(N.INVALID_ARGUMENT, "Longitude must be a number between -180 and 180, but was: " + t); + this._lat = e, this._long = t; + } + /** + * The latitude of this `GeoPoint` instance. + */ get latitude() { + return this._lat; + } + /** + * The longitude of this `GeoPoint` instance. + */ get longitude() { + return this._long; + } + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other - The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ isEqual(e) { + return this._lat === e._lat && this._long === e._long; + } + /** + * Actually private to JS consumers of our API, so this function is prefixed + * with an underscore. + */ _compareTo(e) { + return __PRIVATE_primitiveComparator(this._lat, e._lat) || __PRIVATE_primitiveComparator(this._long, e._long); + } + /** + * Returns a JSON-serializable representation of this `GeoPoint` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + latitude: this._lat, + longitude: this._long, + type: GeoPoint._jsonSchemaVersion + }; + } + /** + * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}. + * + * @param json a JSON object represention of a `GeoPoint` instance + * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ static fromJSON(e) { + if (__PRIVATE_validateJSON(e, GeoPoint._jsonSchema)) return new GeoPoint(e.latitude, e.longitude); + } +} + +GeoPoint._jsonSchemaVersion = "firestore/geoPoint/1.0", GeoPoint._jsonSchema = { + type: property("string", GeoPoint._jsonSchemaVersion), + latitude: property("number"), + longitude: property("number") +}; + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link vector}. + * + * @class VectorValue + */ +class VectorValue { + /** + * @private + * @internal + */ + constructor(e) { + // Making a copy of the parameter. + this._values = (e || []).map((e => e)); + } + /** + * Returns a copy of the raw number array form of the vector. + */ toArray() { + return this._values.map((e => e)); + } + /** + * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise. + */ isEqual(e) { + return function __PRIVATE_isPrimitiveArrayEqual(e, t) { + if (e.length !== t.length) return !1; + for (let n = 0; n < e.length; ++n) if (e[n] !== t[n]) return !1; + return !0; + }(this._values, e._values); + } + /** + * Returns a JSON-serializable representation of this `VectorValue` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + type: VectorValue._jsonSchemaVersion, + vectorValues: this._values + }; + } + /** + * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}. + * + * @param json a JSON object represention of a `VectorValue` instance. + * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ static fromJSON(e) { + if (__PRIVATE_validateJSON(e, VectorValue._jsonSchema)) { + if (Array.isArray(e.vectorValues) && e.vectorValues.every((e => "number" == typeof e))) return new VectorValue(e.vectorValues); + throw new FirestoreError(N.INVALID_ARGUMENT, "Expected 'vectorValues' field to be a number array"); + } + } +} + +VectorValue._jsonSchemaVersion = "firestore/vectorValue/1.0", VectorValue._jsonSchema = { + type: property("string", VectorValue._jsonSchemaVersion), + vectorValues: property("object") +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const hn = /^__.*__$/; + +/** The result of parsing document data (e.g. for a setData call). */ class ParsedSetData { + constructor(e, t, n) { + this.data = e, this.fieldMask = t, this.fieldTransforms = n; + } + toMutation(e, t) { + return null !== this.fieldMask ? new __PRIVATE_PatchMutation(e, this.data, this.fieldMask, t, this.fieldTransforms) : new __PRIVATE_SetMutation(e, this.data, t, this.fieldTransforms); + } +} + +/** The result of parsing "update" data (i.e. for an updateData call). */ class ParsedUpdateData { + constructor(e, + // The fieldMask does not include document transforms. + t, n) { + this.data = e, this.fieldMask = t, this.fieldTransforms = n; + } + toMutation(e, t) { + return new __PRIVATE_PatchMutation(e, this.data, this.fieldMask, t, this.fieldTransforms); + } +} + +function __PRIVATE_isWrite(e) { + switch (e) { + case 0 /* UserDataSource.Set */ : + // fall through + case 2 /* UserDataSource.MergeSet */ : + // fall through + case 1 /* UserDataSource.Update */ : + return !0; + + case 3 /* UserDataSource.Argument */ : + case 4 /* UserDataSource.ArrayArgument */ : + return !1; + + default: + throw fail(40011, { + Ac: e + }); + } +} + +/** A "context" object passed around while parsing user data. */ class __PRIVATE_ParseContextImpl { + /** + * Initializes a ParseContext with the given source and path. + * + * @param settings - The settings for the parser. + * @param databaseId - The database ID of the Firestore instance. + * @param serializer - The serializer to use to generate the Value proto. + * @param ignoreUndefinedProperties - Whether to ignore undefined properties + * rather than throw. + * @param fieldTransforms - A mutable list of field transforms encountered + * while parsing the data. + * @param fieldMask - A mutable list of field paths encountered while parsing + * the data. + * + * TODO(b/34871131): We don't support array paths right now, so path can be + * null to indicate the context represents any location within an array (in + * which case certain features will not work and errors will be somewhat + * compromised). + */ + constructor(e, t, n, r, i, s) { + this.settings = e, this.databaseId = t, this.serializer = n, this.ignoreUndefinedProperties = r, + // Minor hack: If fieldTransforms is undefined, we assume this is an + // external call and we need to validate the entire path. + void 0 === i && this.Rc(), this.fieldTransforms = i || [], this.fieldMask = s || []; + } + get path() { + return this.settings.path; + } + get Ac() { + return this.settings.Ac; + } + /** Returns a new context with the specified settings overwritten. */ Vc(e) { + return new __PRIVATE_ParseContextImpl({ + ...this.settings, + ...e + }, this.databaseId, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask); + } + mc(e) { + const t = this.path?.child(e), n = this.Vc({ + path: t, + fc: !1 + }); + return n.gc(e), n; + } + yc(e) { + const t = this.path?.child(e), n = this.Vc({ + path: t, + fc: !1 + }); + return n.Rc(), n; + } + wc(e) { + // TODO(b/34871131): We don't support array paths right now; so make path + // undefined. + return this.Vc({ + path: void 0, + fc: !0 + }); + } + Sc(e) { + return __PRIVATE_createError(e, this.settings.methodName, this.settings.bc || !1, this.path, this.settings.Dc); + } + /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ contains(e) { + return void 0 !== this.fieldMask.find((t => e.isPrefixOf(t))) || void 0 !== this.fieldTransforms.find((t => e.isPrefixOf(t.field))); + } + Rc() { + // TODO(b/34871131): Remove null check once we have proper paths for fields + // within arrays. + if (this.path) for (let e = 0; e < this.path.length; e++) this.gc(this.path.get(e)); + } + gc(e) { + if (0 === e.length) throw this.Sc("Document fields must not be empty"); + if (__PRIVATE_isWrite(this.Ac) && hn.test(e)) throw this.Sc('Document fields cannot begin and end with "__"'); + } +} + +/** + * Helper for parsing raw user input (provided via the API) into internal model + * classes. + */ class __PRIVATE_UserDataReader { + constructor(e, t, n) { + this.databaseId = e, this.ignoreUndefinedProperties = t, this.serializer = n || __PRIVATE_newSerializer(e); + } + /** Creates a new top-level parse context. */ Cc(e, t, n, r = !1) { + return new __PRIVATE_ParseContextImpl({ + Ac: e, + methodName: t, + Dc: n, + path: FieldPath$1.emptyPath(), + fc: !1, + bc: r + }, this.databaseId, this.serializer, this.ignoreUndefinedProperties); + } +} + +function __PRIVATE_newUserDataReader(e) { + const t = e._freezeSettings(), n = __PRIVATE_newSerializer(e._databaseId); + return new __PRIVATE_UserDataReader(e._databaseId, !!t.ignoreUndefinedProperties, n); +} + +/** Parse document data from a set() call. */ function __PRIVATE_parseSetData(e, t, n, r, i, s = {}) { + const o = e.Cc(s.merge || s.mergeFields ? 2 /* UserDataSource.MergeSet */ : 0 /* UserDataSource.Set */ , t, n, i); + __PRIVATE_validatePlainObject("Data must be an object, but it was:", o, r); + const _ = __PRIVATE_parseObject(r, o); + let a, u; + if (s.merge) a = new FieldMask(o.fieldMask), u = o.fieldTransforms; else if (s.mergeFields) { + const e = []; + for (const r of s.mergeFields) { + const i = __PRIVATE_fieldPathFromArgument$1(t, r, n); + if (!o.contains(i)) throw new FirestoreError(N.INVALID_ARGUMENT, `Field '${i}' is specified in your field mask but missing from your input data.`); + __PRIVATE_fieldMaskContains(e, i) || e.push(i); + } + a = new FieldMask(e), u = o.fieldTransforms.filter((e => a.covers(e.field))); + } else a = null, u = o.fieldTransforms; + return new ParsedSetData(new ObjectValue(_), a, u); +} + +class __PRIVATE_DeleteFieldValueImpl extends FieldValue { + _toFieldTransform(e) { + if (2 /* UserDataSource.MergeSet */ !== e.Ac) throw 1 /* UserDataSource.Update */ === e.Ac ? e.Sc(`${this._methodName}() can only appear at the top level of your update data`) : e.Sc(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`); + // No transform to add for a delete, but we need to add it to our + // fieldMask so it gets deleted. + return e.fieldMask.push(e.path), null; + } + isEqual(e) { + return e instanceof __PRIVATE_DeleteFieldValueImpl; + } +} + +/** + * Creates a child context for parsing SerializableFieldValues. + * + * This is different than calling `ParseContext.contextWith` because it keeps + * the fieldTransforms and fieldMask separate. + * + * The created context has its `dataSource` set to `UserDataSource.Argument`. + * Although these values are used with writes, any elements in these FieldValues + * are not considered writes since they cannot contain any FieldValue sentinels, + * etc. + * + * @param fieldValue - The sentinel FieldValue for which to create a child + * context. + * @param context - The parent context. + * @param arrayElement - Whether or not the FieldValue has an array. + */ function __PRIVATE_createSentinelChildContext(e, t, n) { + return new __PRIVATE_ParseContextImpl({ + Ac: 3 /* UserDataSource.Argument */ , + Dc: t.settings.Dc, + methodName: e._methodName, + fc: n + }, t.databaseId, t.serializer, t.ignoreUndefinedProperties); +} + +class __PRIVATE_ServerTimestampFieldValueImpl extends FieldValue { + _toFieldTransform(e) { + return new FieldTransform(e.path, new __PRIVATE_ServerTimestampTransform); + } + isEqual(e) { + return e instanceof __PRIVATE_ServerTimestampFieldValueImpl; + } +} + +class __PRIVATE_ArrayUnionFieldValueImpl extends FieldValue { + constructor(e, t) { + super(e), this.vc = t; + } + _toFieldTransform(e) { + const t = __PRIVATE_createSentinelChildContext(this, e, + /*array=*/ !0), n = this.vc.map((e => __PRIVATE_parseData(e, t))), r = new __PRIVATE_ArrayUnionTransformOperation(n); + return new FieldTransform(e.path, r); + } + isEqual(e) { + return e instanceof __PRIVATE_ArrayUnionFieldValueImpl && util.deepEqual(this.vc, e.vc); + } +} + +class __PRIVATE_ArrayRemoveFieldValueImpl extends FieldValue { + constructor(e, t) { + super(e), this.vc = t; + } + _toFieldTransform(e) { + const t = __PRIVATE_createSentinelChildContext(this, e, + /*array=*/ !0), n = this.vc.map((e => __PRIVATE_parseData(e, t))), r = new __PRIVATE_ArrayRemoveTransformOperation(n); + return new FieldTransform(e.path, r); + } + isEqual(e) { + return e instanceof __PRIVATE_ArrayRemoveFieldValueImpl && util.deepEqual(this.vc, e.vc); + } +} + +class __PRIVATE_NumericIncrementFieldValueImpl extends FieldValue { + constructor(e, t) { + super(e), this.Fc = t; + } + _toFieldTransform(e) { + const t = new __PRIVATE_NumericIncrementTransformOperation(e.serializer, toNumber(e.serializer, this.Fc)); + return new FieldTransform(e.path, t); + } + isEqual(e) { + return e instanceof __PRIVATE_NumericIncrementFieldValueImpl && this.Fc === e.Fc; + } +} + +/** Parse update data from an update() call. */ function __PRIVATE_parseUpdateData(e, t, n, r) { + const i = e.Cc(1 /* UserDataSource.Update */ , t, n); + __PRIVATE_validatePlainObject("Data must be an object, but it was:", i, r); + const s = [], o = ObjectValue.empty(); + forEach(r, ((e, r) => { + const _ = __PRIVATE_fieldPathFromDotSeparatedString(t, e, n); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + r = util.getModularInstance(r); + const a = i.yc(_); + if (r instanceof __PRIVATE_DeleteFieldValueImpl) + // Add it to the field mask, but don't add anything to updateData. + s.push(_); else { + const e = __PRIVATE_parseData(r, a); + null != e && (s.push(_), o.set(_, e)); + } + })); + const _ = new FieldMask(s); + return new ParsedUpdateData(o, _, i.fieldTransforms); +} + +/** Parse update data from a list of field/value arguments. */ function __PRIVATE_parseUpdateVarargs(e, t, n, r, i, s) { + const o = e.Cc(1 /* UserDataSource.Update */ , t, n), _ = [ __PRIVATE_fieldPathFromArgument$1(t, r, n) ], a = [ i ]; + if (s.length % 2 != 0) throw new FirestoreError(N.INVALID_ARGUMENT, `Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`); + for (let e = 0; e < s.length; e += 2) _.push(__PRIVATE_fieldPathFromArgument$1(t, s[e])), + a.push(s[e + 1]); + const u = [], c = ObjectValue.empty(); + // We iterate in reverse order to pick the last value for a field if the + // user specified the field multiple times. + for (let e = _.length - 1; e >= 0; --e) if (!__PRIVATE_fieldMaskContains(u, _[e])) { + const t = _[e]; + let n = a[e]; + // For Compat types, we have to "extract" the underlying types before + // performing validation. + n = util.getModularInstance(n); + const r = o.yc(t); + if (n instanceof __PRIVATE_DeleteFieldValueImpl) + // Add it to the field mask, but don't add anything to updateData. + u.push(t); else { + const e = __PRIVATE_parseData(n, r); + null != e && (u.push(t), c.set(t, e)); + } + } + const l = new FieldMask(u); + return new ParsedUpdateData(c, l, o.fieldTransforms); +} + +/** + * Parse a "query value" (e.g. value in a where filter or a value in a cursor + * bound). + * + * @param allowArrays - Whether the query value is an array that may directly + * contain additional arrays (e.g. the operand of an `in` query). + */ function __PRIVATE_parseQueryValue(e, t, n, r = !1) { + return __PRIVATE_parseData(n, e.Cc(r ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */ , t)); +} + +/** + * Parses user data to Protobuf Values. + * + * @param input - Data to be parsed. + * @param context - A context object representing the current path being parsed, + * the source of the data being parsed, etc. + * @returns The parsed value, or null if the value was a FieldValue sentinel + * that should not be included in the resulting parsed data. + */ function __PRIVATE_parseData(e, t) { + if (__PRIVATE_looksLikeJsonObject( + // Unwrap the API type from the Compat SDK. This will return the API type + // from firestore-exp. + e = util.getModularInstance(e))) return __PRIVATE_validatePlainObject("Unsupported field value:", t, e), + __PRIVATE_parseObject(e, t); + if (e instanceof FieldValue) + // FieldValues usually parse into transforms (except deleteField()) + // in which case we do not want to include this field in our parsed data + // (as doing so will overwrite the field directly prior to the transform + // trying to transform it). So we don't add this location to + // context.fieldMask and we return null as our parsing result. + /** + * "Parses" the provided FieldValueImpl, adding any necessary transforms to + * context.fieldTransforms. + */ + return function __PRIVATE_parseSentinelFieldValue(e, t) { + // Sentinels are only supported with writes, and not within arrays. + if (!__PRIVATE_isWrite(t.Ac)) throw t.Sc(`${e._methodName}() can only be used with update() and set()`); + if (!t.path) throw t.Sc(`${e._methodName}() is not currently supported inside arrays`); + const n = e._toFieldTransform(t); + n && t.fieldTransforms.push(n); + } + /** + * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue) + * + * @returns The parsed value + */ (e, t), null; + if (void 0 === e && t.ignoreUndefinedProperties) + // If the input is undefined it can never participate in the fieldMask, so + // don't handle this below. If `ignoreUndefinedProperties` is false, + // `parseScalarValue` will reject an undefined value. + return null; + if ( + // If context.path is null we are inside an array and we don't support + // field mask paths more granular than the top-level array. + t.path && t.fieldMask.push(t.path), e instanceof Array) { + // TODO(b/34871131): Include the path containing the array in the error + // message. + // In the case of IN queries, the parsed data is an array (representing + // the set of values to be included for the IN query) that may directly + // contain additional arrays (each representing an individual field + // value), so we disable this validation. + if (t.settings.fc && 4 /* UserDataSource.ArrayArgument */ !== t.Ac) throw t.Sc("Nested arrays are not supported"); + return function __PRIVATE_parseArray(e, t) { + const n = []; + let r = 0; + for (const i of e) { + let e = __PRIVATE_parseData(i, t.wc(r)); + null == e && ( + // Just include nulls in the array for fields being replaced with a + // sentinel. + e = { + nullValue: "NULL_VALUE" + }), n.push(e), r++; + } + return { + arrayValue: { + values: n + } + }; + }(e, t); + } + return function __PRIVATE_parseScalarValue(e, t) { + if (null === (e = util.getModularInstance(e))) return { + nullValue: "NULL_VALUE" + }; + if ("number" == typeof e) return toNumber(t.serializer, e); + if ("boolean" == typeof e) return { + booleanValue: e + }; + if ("string" == typeof e) return { + stringValue: e + }; + if (e instanceof Date) { + const n = Timestamp.fromDate(e); + return { + timestampValue: toTimestamp(t.serializer, n) + }; + } + if (e instanceof Timestamp) { + // Firestore backend truncates precision down to microseconds. To ensure + // offline mode works the same with regards to truncation, perform the + // truncation immediately without waiting for the backend to do that. + const n = new Timestamp(e.seconds, 1e3 * Math.floor(e.nanoseconds / 1e3)); + return { + timestampValue: toTimestamp(t.serializer, n) + }; + } + if (e instanceof GeoPoint) return { + geoPointValue: { + latitude: e.latitude, + longitude: e.longitude + } + }; + if (e instanceof Bytes) return { + bytesValue: __PRIVATE_toBytes(t.serializer, e._byteString) + }; + if (e instanceof DocumentReference) { + const n = t.databaseId, r = e.firestore._databaseId; + if (!r.isEqual(n)) throw t.Sc(`Document reference is for database ${r.projectId}/${r.database} but should be for database ${n.projectId}/${n.database}`); + return { + referenceValue: __PRIVATE_toResourceName(e.firestore._databaseId || t.databaseId, e._key.path) + }; + } + if (e instanceof VectorValue) + /** + * Creates a new VectorValue proto value (using the internal format). + */ + return function __PRIVATE_parseVectorValue(e, t) { + const n = { + fields: { + [ht]: { + stringValue: It + }, + [Et]: { + arrayValue: { + values: e.toArray().map((e => { + if ("number" != typeof e) throw t.Sc("VectorValues must only contain numeric values."); + return __PRIVATE_toDouble(t.serializer, e); + })) + } + } + } + }; + return { + mapValue: n + }; + } + /** + * Checks whether an object looks like a JSON object that should be converted + * into a struct. Normal class/prototype instances are considered to look like + * JSON objects since they should be converted to a struct value. Arrays, Dates, + * GeoPoints, etc. are not considered to look like JSON objects since they map + * to specific FieldValue types other than ObjectValue. + */ (e, t); + throw t.Sc(`Unsupported field value: ${__PRIVATE_valueDescription(e)}`); + }(e, t); +} + +function __PRIVATE_parseObject(e, t) { + const n = {}; + return isEmpty(e) ? + // If we encounter an empty object, we explicitly add it to the update + // mask to ensure that the server creates a map entry. + t.path && t.path.length > 0 && t.fieldMask.push(t.path) : forEach(e, ((e, r) => { + const i = __PRIVATE_parseData(r, t.mc(e)); + null != i && (n[e] = i); + })), { + mapValue: { + fields: n + } + }; +} + +function __PRIVATE_looksLikeJsonObject(e) { + return !("object" != typeof e || null === e || e instanceof Array || e instanceof Date || e instanceof Timestamp || e instanceof GeoPoint || e instanceof Bytes || e instanceof DocumentReference || e instanceof FieldValue || e instanceof VectorValue); +} + +function __PRIVATE_validatePlainObject(e, t, n) { + if (!__PRIVATE_looksLikeJsonObject(n) || !__PRIVATE_isPlainObject(n)) { + const r = __PRIVATE_valueDescription(n); + throw "an object" === r ? t.Sc(e + " a custom object") : t.Sc(e + " " + r); + } +} + +/** + * Helper that calls fromDotSeparatedString() but wraps any error thrown. + */ function __PRIVATE_fieldPathFromArgument$1(e, t, n) { + if (( + // If required, replace the FieldPath Compat class with the firestore-exp + // FieldPath. + t = util.getModularInstance(t)) instanceof FieldPath) return t._internalPath; + if ("string" == typeof t) return __PRIVATE_fieldPathFromDotSeparatedString(e, t); + throw __PRIVATE_createError("Field path arguments must be of type string or ", e, + /* hasConverter= */ !1, + /* path= */ void 0, n); +} + +/** + * Matches any characters in a field path string that are reserved. + */ const Pn = new RegExp("[~\\*/\\[\\]]"); + +/** + * Wraps fromDotSeparatedString with an error message about the method that + * was thrown. + * @param methodName - The publicly visible method name + * @param path - The dot-separated string form of a field path which will be + * split on dots. + * @param targetDoc - The document against which the field path will be + * evaluated. + */ function __PRIVATE_fieldPathFromDotSeparatedString(e, t, n) { + if (t.search(Pn) >= 0) throw __PRIVATE_createError(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`, e, + /* hasConverter= */ !1, + /* path= */ void 0, n); + try { + return new FieldPath(...t.split("."))._internalPath; + } catch (r) { + throw __PRIVATE_createError(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`, e, + /* hasConverter= */ !1, + /* path= */ void 0, n); + } +} + +function __PRIVATE_createError(e, t, n, r, i) { + const s = r && !r.isEmpty(), o = void 0 !== i; + let _ = `Function ${t}() called with invalid data`; + n && (_ += " (via `toFirestore()`)"), _ += ". "; + let a = ""; + return (s || o) && (a += " (found", s && (a += ` in field ${r}`), o && (a += ` in document ${i}`), + a += ")"), new FirestoreError(N.INVALID_ARGUMENT, _ + e + a); +} + +/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ function __PRIVATE_fieldMaskContains(e, t) { + return e.some((e => e.isEqual(t))); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ class DocumentSnapshot$1 { + // Note: This class is stripped down version of the DocumentSnapshot in + // the legacy SDK. The changes are: + // - No support for SnapshotMetadata. + // - No support for SnapshotOptions. + /** @hideconstructor protected */ + constructor(e, t, n, r, i) { + this._firestore = e, this._userDataWriter = t, this._key = n, this._document = r, + this._converter = i; + } + /** Property of the `DocumentSnapshot` that provides the document's ID. */ get id() { + return this._key.path.lastSegment(); + } + /** + * The `DocumentReference` for the document included in the `DocumentSnapshot`. + */ get ref() { + return new DocumentReference(this._firestore, this._converter, this._key); + } + /** + * Signals whether or not the document at the snapshot's location exists. + * + * @returns true if the document exists. + */ exists() { + return null !== this._document; + } + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * @returns An `Object` containing all fields in the document or `undefined` + * if the document doesn't exist. + */ data() { + if (this._document) { + if (this._converter) { + // We only want to use the converter and create a new DocumentSnapshot + // if a converter has been provided. + const e = new QueryDocumentSnapshot$1(this._firestore, this._userDataWriter, this._key, this._document, + /* converter= */ null); + return this._converter.fromFirestore(e); + } + return this._userDataWriter.convertValue(this._document.data.value); + } + } + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + // We are using `any` here to avoid an explicit cast by our users. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get(e) { + if (this._document) { + const t = this._document.data.field(__PRIVATE_fieldPathFromArgument("DocumentSnapshot.get", e)); + if (null !== t) return this._userDataWriter.convertValue(t); + } + } +} + +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ class QueryDocumentSnapshot$1 extends DocumentSnapshot$1 { + /** + * Retrieves all fields in the document as an `Object`. + * + * @override + * @returns An `Object` containing all fields in the document. + */ + data() { + return super.data(); + } +} + +/** + * Helper that calls `fromDotSeparatedString()` but wraps any error thrown. + */ function __PRIVATE_fieldPathFromArgument(e, t) { + return "string" == typeof t ? __PRIVATE_fieldPathFromDotSeparatedString(e, t) : t instanceof FieldPath ? t._internalPath : t._delegate._internalPath; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_validateHasExplicitOrderByForLimitToLast(e) { + if ("L" /* LimitType.Last */ === e.limitType && 0 === e.explicitOrderBy.length) throw new FirestoreError(N.UNIMPLEMENTED, "limitToLast() queries require specifying at least one orderBy() clause"); +} + +/** + * An `AppliableConstraint` is an abstraction of a constraint that can be applied + * to a Firestore query. + */ class AppliableConstraint {} + +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Firestore query. `QueryConstraint`s are created by invoking {@link where}, + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that + * also contains this `QueryConstraint`. + */ class QueryConstraint extends AppliableConstraint {} + +function query(e, t, ...n) { + let r = []; + t instanceof AppliableConstraint && r.push(t), r = r.concat(n), function __PRIVATE_validateQueryConstraintArray(e) { + const t = e.filter((e => e instanceof QueryCompositeFilterConstraint)).length, n = e.filter((e => e instanceof QueryFieldFilterConstraint)).length; + if (t > 1 || t > 0 && n > 0) throw new FirestoreError(N.INVALID_ARGUMENT, "InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`."); + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Converts Firestore's internal types to the JavaScript types that we expose + * to the user. + * + * @internal + */ (r); + for (const t of r) e = t._apply(e); + return e; +} + +/** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ class QueryFieldFilterConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(e, t, n) { + super(), this._field = e, this._op = t, this._value = n, + /** The type of this query constraint */ + this.type = "where"; + } + static _create(e, t, n) { + return new QueryFieldFilterConstraint(e, t, n); + } + _apply(e) { + const t = this._parse(e); + return __PRIVATE_validateNewFieldFilter(e._query, t), new Query(e.firestore, e.converter, __PRIVATE_queryWithAddedFilter(e._query, t)); + } + _parse(e) { + const t = __PRIVATE_newUserDataReader(e.firestore), n = function __PRIVATE_newQueryFilter(e, t, n, r, i, s, o) { + let _; + if (i.isKeyField()) { + if ("array-contains" /* Operator.ARRAY_CONTAINS */ === s || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === s) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid Query. You can't perform '${s}' queries on documentId().`); + if ("in" /* Operator.IN */ === s || "not-in" /* Operator.NOT_IN */ === s) { + __PRIVATE_validateDisjunctiveFilterElements(o, s); + const t = []; + for (const n of o) t.push(__PRIVATE_parseDocumentIdValue(r, e, n)); + _ = { + arrayValue: { + values: t + } + }; + } else _ = __PRIVATE_parseDocumentIdValue(r, e, o); + } else "in" /* Operator.IN */ !== s && "not-in" /* Operator.NOT_IN */ !== s && "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ !== s || __PRIVATE_validateDisjunctiveFilterElements(o, s), + _ = __PRIVATE_parseQueryValue(n, t, o, + /* allowArrays= */ "in" /* Operator.IN */ === s || "not-in" /* Operator.NOT_IN */ === s); + const a = FieldFilter.create(i, s, _); + return a; + }(e._query, "where", t, e.firestore._databaseId, this._field, this._op, this._value); + return n; + } +} + +/** + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. + * + * @param fieldPath - The path to compare + * @param opStr - The operation string (e.g "<", "<=", "==", "<", + * "<=", "!="). + * @param value - The value for comparison + * @returns The created {@link QueryFieldFilterConstraint}. + */ function where(e, t, n) { + const r = t, i = __PRIVATE_fieldPathFromArgument("where", e); + return QueryFieldFilterConstraint._create(i, r, n); +} + +/** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ class QueryCompositeFilterConstraint extends AppliableConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + e, t) { + super(), this.type = e, this._queryConstraints = t; + } + static _create(e, t) { + return new QueryCompositeFilterConstraint(e, t); + } + _parse(e) { + const t = this._queryConstraints.map((t => t._parse(e))).filter((e => e.getFilters().length > 0)); + return 1 === t.length ? t[0] : CompositeFilter.create(t, this._getOperator()); + } + _apply(e) { + const t = this._parse(e); + return 0 === t.getFilters().length ? e : (function __PRIVATE_validateNewFilter(e, t) { + let n = e; + const r = t.getFlattenedFilters(); + for (const e of r) __PRIVATE_validateNewFieldFilter(n, e), n = __PRIVATE_queryWithAddedFilter(n, e); + } + // Checks if any of the provided filter operators are included in the given list of filters and + // returns the first one that is, or null if none are. + (e._query, t), new Query(e.firestore, e.converter, __PRIVATE_queryWithAddedFilter(e._query, t))); + } + _getQueryConstraints() { + return this._queryConstraints; + } + _getOperator() { + return "and" === this.type ? "and" /* CompositeOperator.AND */ : "or" /* CompositeOperator.OR */; + } +} + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ function or(...e) { + // Only support QueryFilterConstraints + return e.forEach((e => __PRIVATE_validateQueryFilterConstraint("or", e))), QueryCompositeFilterConstraint._create("or" /* CompositeOperator.OR */ , e); +} + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ function and(...e) { + // Only support QueryFilterConstraints + return e.forEach((e => __PRIVATE_validateQueryFilterConstraint("and", e))), QueryCompositeFilterConstraint._create("and" /* CompositeOperator.AND */ , e); +} + +/** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ class QueryOrderByConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(e, t) { + super(), this._field = e, this._direction = t, + /** The type of this query constraint */ + this.type = "orderBy"; + } + static _create(e, t) { + return new QueryOrderByConstraint(e, t); + } + _apply(e) { + const t = function __PRIVATE_newQueryOrderBy(e, t, n) { + if (null !== e.startAt) throw new FirestoreError(N.INVALID_ARGUMENT, "Invalid query. You must not call startAt() or startAfter() before calling orderBy()."); + if (null !== e.endAt) throw new FirestoreError(N.INVALID_ARGUMENT, "Invalid query. You must not call endAt() or endBefore() before calling orderBy()."); + const r = new OrderBy(t, n); + return r; + } + /** + * Create a `Bound` from a query and a document. + * + * Note that the `Bound` will always include the key of the document + * and so only the provided document will compare equal to the returned + * position. + * + * Will throw if the document does not contain all fields of the order by + * of the query or if any of the fields in the order by are an uncommitted + * server timestamp. + */ (e._query, this._field, this._direction); + return new Query(e.firestore, e.converter, function __PRIVATE_queryWithAddedOrderBy(e, t) { + // TODO(dimond): validate that orderBy does not list the same key twice. + const n = e.explicitOrderBy.concat([ t ]); + return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, n, e.filters.slice(), e.limit, e.limitType, e.startAt, e.endAt); + }(e._query, t)); + } +} + +/** + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the + * specified field, optionally in descending order instead of ascending. + * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * + * @param fieldPath - The field to sort by. + * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @returns The created {@link QueryOrderByConstraint}. + */ function orderBy(e, t = "asc") { + const n = t, r = __PRIVATE_fieldPathFromArgument("orderBy", e); + return QueryOrderByConstraint._create(r, n); +} + +/** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ class QueryLimitConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + e, t, n) { + super(), this.type = e, this._limit = t, this._limitType = n; + } + static _create(e, t, n) { + return new QueryLimitConstraint(e, t, n); + } + _apply(e) { + return new Query(e.firestore, e.converter, __PRIVATE_queryWithLimit(e._query, this._limit, this._limitType)); + } +} + +/** + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ function limit(e) { + return __PRIVATE_validatePositiveNumber("limit", e), QueryLimitConstraint._create("limit", e, "F" /* LimitType.First */); +} + +/** + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. + * + * You must specify at least one `orderBy` clause for `limitToLast` queries, + * otherwise an exception will be thrown during execution. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ function limitToLast(e) { + return __PRIVATE_validatePositiveNumber("limitToLast", e), QueryLimitConstraint._create("limitToLast", e, "L" /* LimitType.Last */); +} + +/** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ class QueryStartAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + e, t, n) { + super(), this.type = e, this._docOrFields = t, this._inclusive = n; + } + static _create(e, t, n) { + return new QueryStartAtConstraint(e, t, n); + } + _apply(e) { + const t = __PRIVATE_newQueryBoundFromDocOrFields(e, this.type, this._docOrFields, this._inclusive); + return new Query(e.firestore, e.converter, function __PRIVATE_queryWithStartAt(e, t) { + return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, e.explicitOrderBy.slice(), e.filters.slice(), e.limit, e.limitType, t, e.endAt); + }(e._query, t)); + } +} + +function startAt(...e) { + return QueryStartAtConstraint._create("startAt", e, + /*inclusive=*/ !0); +} + +function startAfter(...e) { + return QueryStartAtConstraint._create("startAfter", e, + /*inclusive=*/ !1); +} + +/** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ class QueryEndAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + e, t, n) { + super(), this.type = e, this._docOrFields = t, this._inclusive = n; + } + static _create(e, t, n) { + return new QueryEndAtConstraint(e, t, n); + } + _apply(e) { + const t = __PRIVATE_newQueryBoundFromDocOrFields(e, this.type, this._docOrFields, this._inclusive); + return new Query(e.firestore, e.converter, function __PRIVATE_queryWithEndAt(e, t) { + return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, e.explicitOrderBy.slice(), e.filters.slice(), e.limit, e.limitType, e.startAt, t); + }(e._query, t)); + } +} + +function endBefore(...e) { + return QueryEndAtConstraint._create("endBefore", e, + /*inclusive=*/ !1); +} + +function endAt(...e) { + return QueryEndAtConstraint._create("endAt", e, + /*inclusive=*/ !0); +} + +/** Helper function to create a bound from a document or fields */ function __PRIVATE_newQueryBoundFromDocOrFields(e, t, n, r) { + if (n[0] = util.getModularInstance(n[0]), n[0] instanceof DocumentSnapshot$1) return function __PRIVATE_newQueryBoundFromDocument(e, t, n, r, i) { + if (!r) throw new FirestoreError(N.NOT_FOUND, `Can't use a DocumentSnapshot that doesn't exist for ${n}().`); + const s = []; + // Because people expect to continue/end a query at the exact document + // provided, we need to use the implicit sort order rather than the explicit + // sort order, because it's guaranteed to contain the document key. That way + // the position becomes unambiguous and the query continues/ends exactly at + // the provided document. Without the key (by using the explicit sort + // orders), multiple documents could match the position, yielding duplicate + // results. + for (const n of __PRIVATE_queryNormalizedOrderBy(e)) if (n.field.isKeyField()) s.push(__PRIVATE_refValue(t, r.key)); else { + const e = r.data.field(n.field); + if (__PRIVATE_isServerTimestamp(e)) throw new FirestoreError(N.INVALID_ARGUMENT, 'Invalid query. You are trying to start or end a query using a document for which the field "' + n.field + '" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)'); + if (null === e) { + const e = n.field.canonicalString(); + throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid query. You are trying to start or end a query using a document for which the field '${e}' (used as the orderBy) does not exist.`); + } + s.push(e); + } + return new Bound(s, i); + } + /** + * Converts a list of field values to a `Bound` for the given query. + */ (e._query, e.firestore._databaseId, t, n[0]._document, r); + { + const i = __PRIVATE_newUserDataReader(e.firestore); + return function __PRIVATE_newQueryBoundFromFields(e, t, n, r, i, s) { + // Use explicit order by's because it has to match the query the user made + const o = e.explicitOrderBy; + if (i.length > o.length) throw new FirestoreError(N.INVALID_ARGUMENT, `Too many arguments provided to ${r}(). The number of arguments must be less than or equal to the number of orderBy() clauses`); + const _ = []; + for (let s = 0; s < i.length; s++) { + const a = i[s]; + if (o[s].field.isKeyField()) { + if ("string" != typeof a) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof a}`); + if (!__PRIVATE_isCollectionGroupQuery(e) && -1 !== a.indexOf("/")) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r}() must be a plain document ID, but '${a}' contains a slash.`); + const n = e.path.child(ResourcePath.fromString(a)); + if (!DocumentKey.isDocumentKey(n)) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${r}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`); + const i = new DocumentKey(n); + _.push(__PRIVATE_refValue(t, i)); + } else { + const e = __PRIVATE_parseQueryValue(n, r, a); + _.push(e); + } + } + return new Bound(_, s); + } + /** + * Parses the given `documentIdValue` into a `ReferenceValue`, throwing + * appropriate errors if the value is anything other than a `DocumentReference` + * or `string`, or if the string is malformed. + */ (e._query, e.firestore._databaseId, i, t, n, r); + } +} + +function __PRIVATE_parseDocumentIdValue(e, t, n) { + if ("string" == typeof (n = util.getModularInstance(n))) { + if ("" === n) throw new FirestoreError(N.INVALID_ARGUMENT, "Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string."); + if (!__PRIVATE_isCollectionGroupQuery(t) && -1 !== n.indexOf("/")) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`); + const r = t.path.child(ResourcePath.fromString(n)); + if (!DocumentKey.isDocumentKey(r)) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${r}' is not because it has an odd number of segments (${r.length}).`); + return __PRIVATE_refValue(e, new DocumentKey(r)); + } + if (n instanceof DocumentReference) return __PRIVATE_refValue(e, n._key); + throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${__PRIVATE_valueDescription(n)}.`); +} + +/** + * Validates that the value passed into a disjunctive filter satisfies all + * array requirements. + */ function __PRIVATE_validateDisjunctiveFilterElements(e, t) { + if (!Array.isArray(e) || 0 === e.length) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid Query. A non-empty array is required for '${t.toString()}' filters.`); +} + +/** + * Given an operator, returns the set of operators that cannot be used with it. + * + * This is not a comprehensive check, and this function should be removed in the + * long term. Validations should occur in the Firestore backend. + * + * Operators in a query must adhere to the following set of rules: + * 1. Only one inequality per query. + * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators. + */ function __PRIVATE_validateNewFieldFilter(e, t) { + const n = function __PRIVATE_findOpInsideFilters(e, t) { + for (const n of e) for (const e of n.getFlattenedFilters()) if (t.indexOf(e.op) >= 0) return e.op; + return null; + }(e.filters, function __PRIVATE_conflictingOps(e) { + switch (e) { + case "!=" /* Operator.NOT_EQUAL */ : + return [ "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ]; + + case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ : + case "in" /* Operator.IN */ : + return [ "not-in" /* Operator.NOT_IN */ ]; + + case "not-in" /* Operator.NOT_IN */ : + return [ "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , "in" /* Operator.IN */ , "not-in" /* Operator.NOT_IN */ , "!=" /* Operator.NOT_EQUAL */ ]; + + default: + return []; + } + }(t.op)); + if (null !== n) + // Special case when it's a duplicate op to give a slightly clearer error message. + throw n === t.op ? new FirestoreError(N.INVALID_ARGUMENT, `Invalid query. You cannot use more than one '${t.op.toString()}' filter.`) : new FirestoreError(N.INVALID_ARGUMENT, `Invalid query. You cannot use '${t.op.toString()}' filters with '${n.toString()}' filters.`); +} + +function __PRIVATE_validateQueryFilterConstraint(e, t) { + if (!(t instanceof QueryFieldFilterConstraint || t instanceof QueryCompositeFilterConstraint)) throw new FirestoreError(N.INVALID_ARGUMENT, `Function ${e}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`); +} + +class AbstractUserDataWriter { + convertValue(e, t = "none") { + switch (__PRIVATE_typeOrder(e)) { + case 0 /* TypeOrder.NullValue */ : + return null; + + case 1 /* TypeOrder.BooleanValue */ : + return e.booleanValue; + + case 2 /* TypeOrder.NumberValue */ : + return __PRIVATE_normalizeNumber(e.integerValue || e.doubleValue); + + case 3 /* TypeOrder.TimestampValue */ : + return this.convertTimestamp(e.timestampValue); + + case 4 /* TypeOrder.ServerTimestampValue */ : + return this.convertServerTimestamp(e, t); + + case 5 /* TypeOrder.StringValue */ : + return e.stringValue; + + case 6 /* TypeOrder.BlobValue */ : + return this.convertBytes(__PRIVATE_normalizeByteString(e.bytesValue)); + + case 7 /* TypeOrder.RefValue */ : + return this.convertReference(e.referenceValue); + + case 8 /* TypeOrder.GeoPointValue */ : + return this.convertGeoPoint(e.geoPointValue); + + case 9 /* TypeOrder.ArrayValue */ : + return this.convertArray(e.arrayValue, t); + + case 11 /* TypeOrder.ObjectValue */ : + return this.convertObject(e.mapValue, t); + + case 10 /* TypeOrder.VectorValue */ : + return this.convertVectorValue(e.mapValue); + + default: + throw fail(62114, { + value: e + }); + } + } + convertObject(e, t) { + return this.convertObjectMap(e.fields, t); + } + /** + * @internal + */ convertObjectMap(e, t = "none") { + const n = {}; + return forEach(e, ((e, r) => { + n[e] = this.convertValue(r, t); + })), n; + } + /** + * @internal + */ convertVectorValue(e) { + const t = e.fields?.[Et].arrayValue?.values?.map((e => __PRIVATE_normalizeNumber(e.doubleValue))); + return new VectorValue(t); + } + convertGeoPoint(e) { + return new GeoPoint(__PRIVATE_normalizeNumber(e.latitude), __PRIVATE_normalizeNumber(e.longitude)); + } + convertArray(e, t) { + return (e.values || []).map((e => this.convertValue(e, t))); + } + convertServerTimestamp(e, t) { + switch (t) { + case "previous": + const n = __PRIVATE_getPreviousValue(e); + return null == n ? null : this.convertValue(n, t); + + case "estimate": + return this.convertTimestamp(__PRIVATE_getLocalWriteTime(e)); + + default: + return null; + } + } + convertTimestamp(e) { + const t = __PRIVATE_normalizeTimestamp(e); + return new Timestamp(t.seconds, t.nanos); + } + convertDocumentKey(e, t) { + const n = ResourcePath.fromString(e); + __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(n), 9688, { + name: e + }); + const r = new DatabaseId(n.get(1), n.get(3)), i = new DocumentKey(n.popFirst(5)); + return r.isEqual(t) || + // TODO(b/64130202): Somehow support foreign references. + __PRIVATE_logError(`Document ${i} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`), + i; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Converts custom model object of type T into `DocumentData` by applying the + * converter if it exists. + * + * This function is used when converting user objects to `DocumentData` + * because we want to provide the user with a more specific error message if + * their `set()` or fails due to invalid data originating from a `toFirestore()` + * call. + */ function __PRIVATE_applyFirestoreDataConverter(e, t, n) { + let r; + // Cast to `any` in order to satisfy the union type constraint on + // toFirestore(). + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return r = e ? n && (n.merge || n.mergeFields) ? e.toFirestore(t, n) : e.toFirestore(t) : t, + r; +} + +class __PRIVATE_LiteUserDataWriter extends AbstractUserDataWriter { + constructor(e) { + super(), this.firestore = e; + } + convertBytes(e) { + return new Bytes(e); + } + convertReference(e) { + const t = this.convertDocumentKey(e, this.firestore._databaseId); + return new DocumentReference(this.firestore, /* converter= */ null, t); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ function sum(e) { + return new AggregateField("sum", __PRIVATE_fieldPathFromArgument$1("sum", e)); +} + +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ function average(e) { + return new AggregateField("avg", __PRIVATE_fieldPathFromArgument$1("average", e)); +} + +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ function count() { + return new AggregateField("count"); +} + +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ function aggregateFieldEqual(e, t) { + return e instanceof AggregateField && t instanceof AggregateField && e.aggregateType === t.aggregateType && e._internalFieldPath?.canonicalString() === t._internalFieldPath?.canonicalString(); +} + +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ function aggregateQuerySnapshotEqual(e, t) { + return queryEqual(e.query, t.query) && util.deepEqual(e.data(), t.data()); +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const Tn = "NOT SUPPORTED"; + +/** + * Metadata about a snapshot, describing the state of the snapshot. + */ class SnapshotMetadata { + /** @hideconstructor */ + constructor(e, t) { + this.hasPendingWrites = e, this.fromCache = t; + } + /** + * Returns true if this `SnapshotMetadata` is equal to the provided one. + * + * @param other - The `SnapshotMetadata` to compare against. + * @returns true if this `SnapshotMetadata` is equal to the provided one. + */ isEqual(e) { + return this.hasPendingWrites === e.hasPendingWrites && this.fromCache === e.fromCache; + } +} + +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ class DocumentSnapshot extends DocumentSnapshot$1 { + /** @hideconstructor protected */ + constructor(e, t, n, r, i, s) { + super(e, t, n, r, s), this._firestore = e, this._firestoreImpl = e, this.metadata = i; + } + /** + * Returns whether or not the data exists. True if the document exists. + */ exists() { + return super.exists(); + } + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * By default, `serverTimestamp()` values that have not yet been + * set to their final value will be returned as `null`. You can override + * this by passing an options object. + * + * @param options - An options object to configure how data is retrieved from + * the snapshot (for example the desired behavior for server timestamps that + * have not yet been set to their final value). + * @returns An `Object` containing all fields in the document or `undefined` if + * the document doesn't exist. + */ data(e = {}) { + if (this._document) { + if (this._converter) { + // We only want to use the converter and create a new DocumentSnapshot + // if a converter has been provided. + const t = new QueryDocumentSnapshot(this._firestore, this._userDataWriter, this._key, this._document, this.metadata, + /* converter= */ null); + return this._converter.fromFirestore(t, e); + } + return this._userDataWriter.convertValue(this._document.data.value, e.serverTimestamps); + } + } + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * By default, a `serverTimestamp()` that has not yet been set to + * its final value will be returned as `null`. You can override this by + * passing an options object. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @param options - An options object to configure how the field is retrieved + * from the snapshot (for example the desired behavior for server timestamps + * that have not yet been set to their final value). + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + // We are using `any` here to avoid an explicit cast by our users. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get(e, t = {}) { + if (this._document) { + const n = this._document.data.field(__PRIVATE_fieldPathFromArgument("DocumentSnapshot.get", e)); + if (null !== n) return this._userDataWriter.convertValue(n, t.serverTimestamps); + } + } + /** + * Returns a JSON-serializable representation of this `DocumentSnapshot` instance. + * + * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this + * `DocumentSnapshot` has pending writes. + */ toJSON() { + if (this.metadata.hasPendingWrites) throw new FirestoreError(N.FAILED_PRECONDITION, "DocumentSnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON()."); + const e = this._document, t = {}; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (t.type = DocumentSnapshot._jsonSchemaVersion, t.bundle = "", t.bundleSource = "DocumentSnapshot", + t.bundleName = this._key.toString(), !e || !e.isValidDocument() || !e.isFoundDocument()) return t; + this._userDataWriter.convertObjectMap(e.data.value.mapValue.fields, "previous"); + return t.bundle = (this._firestore, this.ref.path, "NOT SUPPORTED"), t; + } +} + +function documentSnapshotFromJSON(e, t, n) { + if (__PRIVATE_validateJSON(t, DocumentSnapshot._jsonSchema)) { + if (t.bundle === Tn) throw new FirestoreError(N.INVALID_ARGUMENT, "The provided JSON object was created in a client environment, which is not supported."); + // Parse the bundle data. + const r = __PRIVATE_newSerializer(e._databaseId), i = __PRIVATE_createBundleReaderSync(t.bundle, r), s = i.Wu(), o = new __PRIVATE_BundleLoader(i.getMetadata(), r); + for (const e of s) o.Ga(e); + // Ensure that we have the correct number of documents in the bundle. + const _ = o.documents; + if (1 !== _.length) throw new FirestoreError(N.INVALID_ARGUMENT, `Expected bundle data to contain 1 document, but it contains ${_.length} documents.`); + // Build out the internal document data. + const a = __PRIVATE_fromDocument(r, _[0].document), u = new DocumentKey(ResourcePath.fromString(t.bundleName)); + // Return the external facing DocumentSnapshot. + return new DocumentSnapshot(e, new __PRIVATE_LiteUserDataWriter(e), u, a, new SnapshotMetadata( + /* hasPendingWrites= */ !1, + /* fromCache= */ !1), n || null); + } +} + +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ DocumentSnapshot._jsonSchemaVersion = "firestore/documentSnapshot/1.0", DocumentSnapshot._jsonSchema = { + type: property("string", DocumentSnapshot._jsonSchemaVersion), + bundleSource: property("string", "DocumentSnapshot"), + bundleName: property("string"), + bundle: property("string") +}; + +class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * By default, `serverTimestamp()` values that have not yet been + * set to their final value will be returned as `null`. You can override + * this by passing an options object. + * + * @override + * @param options - An options object to configure how data is retrieved from + * the snapshot (for example the desired behavior for server timestamps that + * have not yet been set to their final value). + * @returns An `Object` containing all fields in the document. + */ + data(e = {}) { + return super.data(e); + } +} + +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ class QuerySnapshot { + /** @hideconstructor */ + constructor(e, t, n, r) { + this._firestore = e, this._userDataWriter = t, this._snapshot = r, this.metadata = new SnapshotMetadata(r.hasPendingWrites, r.fromCache), + this.query = n; + } + /** An array of all the documents in the `QuerySnapshot`. */ get docs() { + const e = []; + return this.forEach((t => e.push(t))), e; + } + /** The number of documents in the `QuerySnapshot`. */ get size() { + return this._snapshot.docs.size; + } + /** True if there are no documents in the `QuerySnapshot`. */ get empty() { + return 0 === this.size; + } + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ forEach(e, t) { + this._snapshot.docs.forEach((n => { + e.call(t, new QueryDocumentSnapshot(this._firestore, this._userDataWriter, n.key, n, new SnapshotMetadata(this._snapshot.mutatedKeys.has(n.key), this._snapshot.fromCache), this.query.converter)); + })); + } + /** + * Returns an array of the documents changes since the last snapshot. If this + * is the first snapshot, all documents will be in the list as 'added' + * changes. + * + * @param options - `SnapshotListenOptions` that control whether metadata-only + * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger + * snapshot events. + */ docChanges(e = {}) { + const t = !!e.includeMetadataChanges; + if (t && this._snapshot.excludesMetadataChanges) throw new FirestoreError(N.INVALID_ARGUMENT, "To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot()."); + return this._cachedChanges && this._cachedChangesIncludeMetadataChanges === t || (this._cachedChanges = + /** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */ + function __PRIVATE_changesFromSnapshot(e, t) { + if (e._snapshot.oldDocs.isEmpty()) { + let t = 0; + return e._snapshot.docChanges.map((n => { + const r = new QueryDocumentSnapshot(e._firestore, e._userDataWriter, n.doc.key, n.doc, new SnapshotMetadata(e._snapshot.mutatedKeys.has(n.doc.key), e._snapshot.fromCache), e.query.converter); + return n.doc, { + type: "added", + doc: r, + oldIndex: -1, + newIndex: t++ + }; + })); + } + { + // A `DocumentSet` that is updated incrementally as changes are applied to use + // to lookup the index of a document. + let n = e._snapshot.oldDocs; + return e._snapshot.docChanges.filter((e => t || 3 /* ChangeType.Metadata */ !== e.type)).map((t => { + const r = new QueryDocumentSnapshot(e._firestore, e._userDataWriter, t.doc.key, t.doc, new SnapshotMetadata(e._snapshot.mutatedKeys.has(t.doc.key), e._snapshot.fromCache), e.query.converter); + let i = -1, s = -1; + return 0 /* ChangeType.Added */ !== t.type && (i = n.indexOf(t.doc.key), n = n.delete(t.doc.key)), + 1 /* ChangeType.Removed */ !== t.type && (n = n.add(t.doc), s = n.indexOf(t.doc.key)), + { + type: __PRIVATE_resultChangeType(t.type), + doc: r, + oldIndex: i, + newIndex: s + }; + })); + } + }(this, t), this._cachedChangesIncludeMetadataChanges = t), this._cachedChanges; + } + /** + * Returns a JSON-serializable representation of this `QuerySnapshot` instance. + * + * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this + * `QuerySnapshot` has pending writes. + */ toJSON() { + if (this.metadata.hasPendingWrites) throw new FirestoreError(N.FAILED_PRECONDITION, "QuerySnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON()."); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const e = {}; + e.type = QuerySnapshot._jsonSchemaVersion, e.bundleSource = "QuerySnapshot", e.bundleName = __PRIVATE_AutoId.newId(), + this._firestore._databaseId.database, this._firestore._databaseId.projectId; + const t = [], n = [], r = []; + return this.docs.forEach((e => { + null !== e._document && (t.push(e._document), n.push(this._userDataWriter.convertObjectMap(e._document.data.value.mapValue.fields, "previous")), + r.push(e.ref.path)); + })), e.bundle = (this._firestore, this.query._query, e.bundleName, "NOT SUPPORTED"), + e; + } +} + +function querySnapshotFromJSON(e, t, n) { + if (__PRIVATE_validateJSON(t, QuerySnapshot._jsonSchema)) { + if (t.bundle === Tn) throw new FirestoreError(N.INVALID_ARGUMENT, "The provided JSON object was created in a client environment, which is not supported."); + // Parse the bundle data. + const r = __PRIVATE_newSerializer(e._databaseId), i = __PRIVATE_createBundleReaderSync(t.bundle, r), s = i.Wu(), o = new __PRIVATE_BundleLoader(i.getMetadata(), r); + for (const e of s) o.Ga(e); + if (1 !== o.queries.length) throw new FirestoreError(N.INVALID_ARGUMENT, `Snapshot data expected 1 query but found ${o.queries.length} queries.`); + // Create an internal Query object from the named query in the bundle. + const _ = __PRIVATE_fromBundledQuery(o.queries[0].bundledQuery), a = o.documents; + // Construct the arrays of document data for the query. + let u = new DocumentSet; + a.map((e => { + const t = __PRIVATE_fromDocument(r, e.document); + u = u.add(t); + })); + // Create a view snapshot of the query and documents. + const c = ViewSnapshot.fromInitialDocuments(_, u, __PRIVATE_documentKeySet() /* Zero mutated keys signifies no pending writes. */ , + /* fromCache= */ !1, + /* hasCachedResults= */ !1), l = new Query(e, n || null, _); + // Create an external Query object, required to construct the QuerySnapshot. + // Return a new QuerySnapshot with all of the collected data. + return new QuerySnapshot(e, new __PRIVATE_LiteUserDataWriter(e), l, c); + } +} + +function __PRIVATE_resultChangeType(e) { + switch (e) { + case 0 /* ChangeType.Added */ : + return "added"; + + case 2 /* ChangeType.Modified */ : + case 3 /* ChangeType.Metadata */ : + return "modified"; + + case 1 /* ChangeType.Removed */ : + return "removed"; + + default: + return fail(61501, { + type: e + }); + } +} + +// TODO(firestoreexp): Add tests for snapshotEqual with different snapshot +// metadata +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ function snapshotEqual(e, t) { + return e instanceof DocumentSnapshot && t instanceof DocumentSnapshot ? e._firestore === t._firestore && e._key.isEqual(t._key) && (null === e._document ? null === t._document : e._document.isEqual(t._document)) && e._converter === t._converter : e instanceof QuerySnapshot && t instanceof QuerySnapshot && (e._firestore === t._firestore && queryEqual(e.query, t.query) && e.metadata.isEqual(t.metadata) && e._snapshot.isEqual(t._snapshot)); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Reads the document referred to by this `DocumentReference`. + * + * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting + * for data from the server, but it may return cached data or fail if you are + * offline and the server cannot be reached. To specify this behavior, invoke + * {@link getDocFromCache} or {@link getDocFromServer}. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the + * current document contents. + */ function getDoc(e) { + e = __PRIVATE_cast(e, DocumentReference); + const t = __PRIVATE_cast(e.firestore, Firestore); + return __PRIVATE_firestoreClientGetDocumentViaSnapshotListener(ensureFirestoreConfigured(t), e._key).then((n => __PRIVATE_convertToDocSnapshot(t, e, n))); +} + +QuerySnapshot._jsonSchemaVersion = "firestore/querySnapshot/1.0", QuerySnapshot._jsonSchema = { + type: property("string", QuerySnapshot._jsonSchemaVersion), + bundleSource: property("string", "QuerySnapshot"), + bundleName: property("string"), + bundle: property("string") +}; + +class __PRIVATE_ExpUserDataWriter extends AbstractUserDataWriter { + constructor(e) { + super(), this.firestore = e; + } + convertBytes(e) { + return new Bytes(e); + } + convertReference(e) { + const t = this.convertDocumentKey(e, this.firestore._databaseId); + return new DocumentReference(this.firestore, /* converter= */ null, t); + } +} + +/** + * Reads the document referred to by this `DocumentReference` from cache. + * Returns an error if the document is not currently cached. + * + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the + * current document contents. + */ function getDocFromCache(e) { + e = __PRIVATE_cast(e, DocumentReference); + const t = __PRIVATE_cast(e.firestore, Firestore), n = ensureFirestoreConfigured(t), r = new __PRIVATE_ExpUserDataWriter(t); + return __PRIVATE_firestoreClientGetDocumentFromLocalCache(n, e._key).then((n => new DocumentSnapshot(t, r, e._key, n, new SnapshotMetadata(null !== n && n.hasLocalMutations, + /* fromCache= */ !0), e.converter))); +} + +/** + * Reads the document referred to by this `DocumentReference` from the server. + * Returns an error if the network is not available. + * + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the + * current document contents. + */ function getDocFromServer(e) { + e = __PRIVATE_cast(e, DocumentReference); + const t = __PRIVATE_cast(e.firestore, Firestore); + return __PRIVATE_firestoreClientGetDocumentViaSnapshotListener(ensureFirestoreConfigured(t), e._key, { + source: "server" + }).then((n => __PRIVATE_convertToDocSnapshot(t, e, n))); +} + +/** + * Executes the query and returns the results as a `QuerySnapshot`. + * + * Note: `getDocs()` attempts to provide up-to-date data when possible by + * waiting for data from the server, but it may return cached data or fail if + * you are offline and the server cannot be reached. To specify this behavior, + * invoke {@link getDocsFromCache} or {@link getDocsFromServer}. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ function getDocs(e) { + e = __PRIVATE_cast(e, Query); + const t = __PRIVATE_cast(e.firestore, Firestore), n = ensureFirestoreConfigured(t), r = new __PRIVATE_ExpUserDataWriter(t); + return __PRIVATE_validateHasExplicitOrderByForLimitToLast(e._query), __PRIVATE_firestoreClientGetDocumentsViaSnapshotListener(n, e._query).then((n => new QuerySnapshot(t, r, e, n))); +} + +/** + * Executes the query and returns the results as a `QuerySnapshot` from cache. + * Returns an empty result set if no documents matching the query are currently + * cached. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ function getDocsFromCache(e) { + e = __PRIVATE_cast(e, Query); + const t = __PRIVATE_cast(e.firestore, Firestore), n = ensureFirestoreConfigured(t), r = new __PRIVATE_ExpUserDataWriter(t); + return __PRIVATE_firestoreClientGetDocumentsFromLocalCache(n, e._query).then((n => new QuerySnapshot(t, r, e, n))); +} + +/** + * Executes the query and returns the results as a `QuerySnapshot` from the + * server. Returns an error if the network is not available. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ function getDocsFromServer(e) { + e = __PRIVATE_cast(e, Query); + const t = __PRIVATE_cast(e.firestore, Firestore), n = ensureFirestoreConfigured(t), r = new __PRIVATE_ExpUserDataWriter(t); + return __PRIVATE_firestoreClientGetDocumentsViaSnapshotListener(n, e._query, { + source: "server" + }).then((n => new QuerySnapshot(t, r, e, n))); +} + +function setDoc(e, t, n) { + e = __PRIVATE_cast(e, DocumentReference); + const r = __PRIVATE_cast(e.firestore, Firestore), i = __PRIVATE_applyFirestoreDataConverter(e.converter, t, n); + return executeWrite(r, [ __PRIVATE_parseSetData(__PRIVATE_newUserDataReader(r), "setDoc", e._key, i, null !== e.converter, n).toMutation(e._key, Precondition.none()) ]); +} + +function updateDoc(e, t, n, ...r) { + e = __PRIVATE_cast(e, DocumentReference); + const i = __PRIVATE_cast(e.firestore, Firestore), s = __PRIVATE_newUserDataReader(i); + let o; + o = "string" == typeof ( + // For Compat types, we have to "extract" the underlying types before + // performing validation. + t = util.getModularInstance(t)) || t instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(s, "updateDoc", e._key, t, n, r) : __PRIVATE_parseUpdateData(s, "updateDoc", e._key, t); + return executeWrite(i, [ o.toMutation(e._key, Precondition.exists(!0)) ]); +} + +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * @param reference - A reference to the document to delete. + * @returns A Promise resolved once the document has been successfully + * deleted from the backend (note that it won't resolve while you're offline). + */ function deleteDoc(e) { + return executeWrite(__PRIVATE_cast(e.firestore, Firestore), [ new __PRIVATE_DeleteMutation(e._key, Precondition.none()) ]); +} + +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend (Note that it + * won't resolve while you're offline). + */ function addDoc(e, t) { + const n = __PRIVATE_cast(e.firestore, Firestore), r = doc(e), i = __PRIVATE_applyFirestoreDataConverter(e.converter, t); + return executeWrite(n, [ __PRIVATE_parseSetData(__PRIVATE_newUserDataReader(e.firestore), "addDoc", r._key, i, null !== e.converter, {}).toMutation(r._key, Precondition.exists(!1)) ]).then((() => r)); +} + +function onSnapshot(e, ...t) { + // onSnapshot for Query or Document. + e = util.getModularInstance(e); + let n = { + includeMetadataChanges: !1, + source: "default" + }, r = 0; + "object" != typeof t[r] || __PRIVATE_isPartialObserver(t[r]) || (n = t[r++]); + const i = { + includeMetadataChanges: n.includeMetadataChanges, + source: n.source + }; + if (__PRIVATE_isPartialObserver(t[r])) { + const e = t[r]; + t[r] = e.next?.bind(e), t[r + 1] = e.error?.bind(e), t[r + 2] = e.complete?.bind(e); + } + let s, o, _; + if (e instanceof DocumentReference) o = __PRIVATE_cast(e.firestore, Firestore), + _ = __PRIVATE_newQueryForPath(e._key.path), s = { + next: n => { + t[r] && t[r](__PRIVATE_convertToDocSnapshot(o, e, n)); + }, + error: t[r + 1], + complete: t[r + 2] + }; else { + const n = __PRIVATE_cast(e, Query); + o = __PRIVATE_cast(n.firestore, Firestore), _ = n._query; + const i = new __PRIVATE_ExpUserDataWriter(o); + s = { + next: e => { + t[r] && t[r](new QuerySnapshot(o, i, n, e)); + }, + error: t[r + 1], + complete: t[r + 2] + }, __PRIVATE_validateHasExplicitOrderByForLimitToLast(e._query); + } + return function __PRIVATE_firestoreClientListen(e, t, n, r) { + const i = new __PRIVATE_AsyncObserver(r), s = new __PRIVATE_QueryListener(t, i, n); + return e.asyncQueue.enqueueAndForget((async () => __PRIVATE_eventManagerListen(await __PRIVATE_getEventManager(e), s))), + () => { + i.Nu(), e.asyncQueue.enqueueAndForget((async () => __PRIVATE_eventManagerUnlisten(await __PRIVATE_getEventManager(e), s))); + }; + }(ensureFirestoreConfigured(o), _, i, s); +} + +function onSnapshotResume(e, t, ...n) { + const r = util.getModularInstance(e), i = + /** + * Ensures the data required to construct an {@link onSnapshot} listener exist in a `snapshotJson` + * object that originates from {@link DocumentSnapshot.toJSON} or {@link Querysnapshot.toJSON}. The + * data is normalized into a typed object. + * + * @param snapshotJson - The JSON object that the app provided to {@link onSnapshot}. + * @returns A normalized object that contains all of the required bundle JSON fields. If + * {@link snapshotJson} doesn't contain the required fields, or if the fields exist as empty + * strings, then the {@link snapshotJson.error} field will be a non empty string. + * + * @internal + */ + function __PRIVATE_normalizeSnapshotJsonFields(e) { + const t = { + bundle: "", + bundleName: "", + bundleSource: "" + }, n = [ "bundle", "bundleName", "bundleSource" ]; + for (const r of n) { + if (!(r in e)) { + t.error = `snapshotJson missing required field: ${r}`; + break; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const n = e[r]; + if ("string" != typeof n) { + t.error = `snapshotJson field '${r}' must be a string.`; + break; + } + if (0 === n.length) { + t.error = `snapshotJson field '${r}' cannot be an empty string.`; + break; + } + "bundle" === r ? t.bundle = n : "bundleName" === r ? t.bundleName = n : "bundleSource" === r && (t.bundleSource = n); + } + return t; + } + /** + * Loads the bundle in a separate task and then invokes {@link onSnapshot} with a + * {@link DocumentReference} for the document in the bundle. + * + * @param firestore - The {@link Firestore} instance for the {@link onSnapshot} operation request. + * @param json - The JSON bundle to load, produced by {@link DocumentSnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot + * listener. + * + * @internal + */ (t); + if (i.error) throw new FirestoreError(N.INVALID_ARGUMENT, i.error); + let s, o = 0; + if ("object" != typeof n[o] || __PRIVATE_isPartialObserver(n[o]) || (s = n[o++]), + "QuerySnapshot" === i.bundleSource) { + let e = null; + if ("object" == typeof n[o] && __PRIVATE_isPartialObserver(n[o])) { + const t = n[o++]; + e = { + next: t.next, + error: t.error, + complete: t.complete + }; + } else e = { + next: n[o++], + error: n[o++], + complete: n[o++] + }; + /** + * Loads the bundle in a separate task and then invokes {@link onSnapshot} with a + * {@link Query} that represents the Query in the bundle. + * + * @param firestore - The {@link Firestore} instance for the {@link onSnapshot} operation request. + * @param json - The JSON bundle to load, produced by {@link QuerySnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot + * listener. + * + * @internal + */ + return function __PRIVATE_onSnapshotQuerySnapshotBundle(e, t, n, r, i) { + let s, o = !1; + const _ = loadBundle(e, t.bundle); + return _.then((() => namedQuery(e, t.bundleName))).then((e => { + if (e && !o) { + i && e.withConverter(i), s = onSnapshot(e, n || {}, r); + } + })).catch((e => (r.error && r.error(e), () => {}))), () => { + o || (o = !0, s && s()); + }; + } + /** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ (r, i, s, e, n[o]); + } + if ("DocumentSnapshot" === i.bundleSource) { + let e = null; + if ("object" == typeof n[o] && __PRIVATE_isPartialObserver(n[o])) { + const t = n[o++]; + e = { + next: t.next, + error: t.error, + complete: t.complete + }; + } else e = { + next: n[o++], + error: n[o++], + complete: n[o++] + }; + return function __PRIVATE_onSnapshotDocumentSnapshotBundle(e, t, n, r, i) { + let s, o = !1; + const _ = loadBundle(e, t.bundle); + return _.then((() => { + if (!o) { + const o = new DocumentReference(e, i || null, DocumentKey.fromPath(t.bundleName)); + s = onSnapshot(o, n || {}, r); + } + })).catch((e => (r.error && r.error(e), () => {}))), () => { + o || (o = !0, s && s()); + }; + }(r, i, s, e, n[o]); + } + throw new FirestoreError(N.INVALID_ARGUMENT, `unsupported bundle source: ${i.bundleSource}`); +} + +function onSnapshotsInSync(e, t) { + return __PRIVATE_firestoreClientAddSnapshotsInSyncListener(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)), __PRIVATE_isPartialObserver(t) ? t : { + next: t + }); +} + +/** + * Locally writes `mutations` on the async queue. + * @internal + */ function executeWrite(e, t) { + return function __PRIVATE_firestoreClientWrite(e, t) { + const n = new __PRIVATE_Deferred; + return e.asyncQueue.enqueueAndForget((async () => __PRIVATE_syncEngineWrite(await __PRIVATE_getSyncEngine(e), t, n))), + n.promise; + }(ensureFirestoreConfigured(e), t); +} + +/** + * Converts a {@link ViewSnapshot} that contains the single document specified by `ref` + * to a {@link DocumentSnapshot}. + */ function __PRIVATE_convertToDocSnapshot(e, t, n) { + const r = n.docs.get(t._key), i = new __PRIVATE_ExpUserDataWriter(e); + return new DocumentSnapshot(e, i, t._key, r, new SnapshotMetadata(n.hasPendingWrites, n.fromCache), t.converter); +} + +function getCountFromServer(e) { + return getAggregateFromServer(e, { + count: count() + }); +} + +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregateFromServer(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ function getAggregateFromServer(e, t) { + const n = __PRIVATE_cast(e.firestore, Firestore), r = ensureFirestoreConfigured(n), i = __PRIVATE_mapToArray(t, ((e, t) => new __PRIVATE_AggregateImpl(t, e.aggregateType, e._internalFieldPath))); + // Run the aggregation and convert the results + return __PRIVATE_firestoreClientRunAggregateQuery(r, e._query, i).then((t => + /** + * Converts the core aggregation result to an `AggregateQuerySnapshot` + * that can be returned to the consumer. + * @param query + * @param aggregateResult Core aggregation result + * @internal + */ + function __PRIVATE_convertToAggregateQuerySnapshot(e, t, n) { + const r = new __PRIVATE_ExpUserDataWriter(e), i = new AggregateQuerySnapshot(t, r, n); + return i; + } + /** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ (n, e, t))); +} + +class __PRIVATE_MemoryLocalCacheImpl { + constructor(e) { + this.kind = "memory", this._onlineComponentProvider = OnlineComponentProvider.provider, + this._offlineComponentProvider = e?.garbageCollector ? e.garbageCollector._offlineComponentProvider : { + build: () => new __PRIVATE_LruGcMemoryOfflineComponentProvider(void 0) + }; + } + toJSON() { + return { + kind: this.kind + }; + } +} + +class __PRIVATE_PersistentLocalCacheImpl { + constructor(e) { + let t; + this.kind = "persistent", e?.tabManager ? (e.tabManager._initialize(e), t = e.tabManager) : (t = persistentSingleTabManager(void 0), + t._initialize(e)), this._onlineComponentProvider = t._onlineComponentProvider, this._offlineComponentProvider = t._offlineComponentProvider; + } + toJSON() { + return { + kind: this.kind + }; + } +} + +class __PRIVATE_MemoryEagerGarbageCollectorImpl { + constructor() { + this.kind = "memoryEager", this._offlineComponentProvider = __PRIVATE_MemoryOfflineComponentProvider.provider; + } + toJSON() { + return { + kind: this.kind + }; + } +} + +class __PRIVATE_MemoryLruGarbageCollectorImpl { + constructor(e) { + this.kind = "memoryLru", this._offlineComponentProvider = { + build: () => new __PRIVATE_LruGcMemoryOfflineComponentProvider(e) + }; + } + toJSON() { + return { + kind: this.kind + }; + } +} + +/** + * Creates an instance of `MemoryEagerGarbageCollector`. This is also the + * default garbage collector unless it is explicitly specified otherwise. + */ function memoryEagerGarbageCollector() { + return new __PRIVATE_MemoryEagerGarbageCollectorImpl; +} + +/** + * Creates an instance of `MemoryLruGarbageCollector`. + * + * A target size can be specified as part of the setting parameter. The + * collector will start deleting documents once the cache size exceeds + * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes). + */ function memoryLruGarbageCollector(e) { + return new __PRIVATE_MemoryLruGarbageCollectorImpl(e?.cacheSizeBytes); +} + +/** + * Creates an instance of `MemoryLocalCache`. The instance can be set to + * `FirestoreSettings.cache` to tell the SDK which cache layer to use. + */ function memoryLocalCache(e) { + return new __PRIVATE_MemoryLocalCacheImpl(e); +} + +/** + * Creates an instance of `PersistentLocalCache`. The instance can be set to + * `FirestoreSettings.cache` to tell the SDK which cache layer to use. + * + * Persistent cache cannot be used in a Node.js environment. + */ function persistentLocalCache(e) { + return new __PRIVATE_PersistentLocalCacheImpl(e); +} + +class __PRIVATE_SingleTabManagerImpl { + constructor(e) { + this.forceOwnership = e, this.kind = "persistentSingleTab"; + } + toJSON() { + return { + kind: this.kind + }; + } + /** + * @internal + */ _initialize(e) { + this._onlineComponentProvider = OnlineComponentProvider.provider, this._offlineComponentProvider = { + build: t => new __PRIVATE_IndexedDbOfflineComponentProvider(t, e?.cacheSizeBytes, this.forceOwnership) + }; + } +} + +class __PRIVATE_MultiTabManagerImpl { + constructor() { + this.kind = "PersistentMultipleTab"; + } + toJSON() { + return { + kind: this.kind + }; + } + /** + * @internal + */ _initialize(e) { + this._onlineComponentProvider = OnlineComponentProvider.provider, this._offlineComponentProvider = { + build: t => new __PRIVATE_MultiTabOfflineComponentProvider(t, e?.cacheSizeBytes) + }; + } +} + +/** + * Creates an instance of `PersistentSingleTabManager`. + * + * @param settings Configures the created tab manager. + */ function persistentSingleTabManager(e) { + return new __PRIVATE_SingleTabManagerImpl(e?.forceOwnership); +} + +/** + * Creates an instance of `PersistentMultipleTabManager`. + */ function persistentMultipleTabManager() { + return new __PRIVATE_MultiTabManagerImpl; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const In = { + maxAttempts: 5 +}; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It + * provides methods for adding writes to the write batch. None of the writes + * will be committed (or visible locally) until {@link WriteBatch.commit} is + * called. + */ +class WriteBatch { + /** @hideconstructor */ + constructor(e, t) { + this._firestore = e, this._commitHandler = t, this._mutations = [], this._committed = !1, + this._dataReader = __PRIVATE_newUserDataReader(e); + } + set(e, t, n) { + this._verifyNotCommitted(); + const r = __PRIVATE_validateReference(e, this._firestore), i = __PRIVATE_applyFirestoreDataConverter(r.converter, t, n), s = __PRIVATE_parseSetData(this._dataReader, "WriteBatch.set", r._key, i, null !== r.converter, n); + return this._mutations.push(s.toMutation(r._key, Precondition.none())), this; + } + update(e, t, n, ...r) { + this._verifyNotCommitted(); + const i = __PRIVATE_validateReference(e, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + let s; + return s = "string" == typeof (t = util.getModularInstance(t)) || t instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(this._dataReader, "WriteBatch.update", i._key, t, n, r) : __PRIVATE_parseUpdateData(this._dataReader, "WriteBatch.update", i._key, t), + this._mutations.push(s.toMutation(i._key, Precondition.exists(!0))), this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ delete(e) { + this._verifyNotCommitted(); + const t = __PRIVATE_validateReference(e, this._firestore); + return this._mutations = this._mutations.concat(new __PRIVATE_DeleteMutation(t._key, Precondition.none())), + this; + } + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `Promise` resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit (note that it won't + * resolve while you're offline). + */ commit() { + return this._verifyNotCommitted(), this._committed = !0, this._mutations.length > 0 ? this._commitHandler(this._mutations) : Promise.resolve(); + } + _verifyNotCommitted() { + if (this._committed) throw new FirestoreError(N.FAILED_PRECONDITION, "A write batch can no longer be used after commit() has been called."); + } +} + +function __PRIVATE_validateReference(e, t) { + if ((e = util.getModularInstance(e)).firestore !== t) throw new FirestoreError(N.INVALID_ARGUMENT, "Provided document reference is from a different Firestore instance."); + return e; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the +// legacy SDK. +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ class Transaction$1 { + /** @hideconstructor */ + constructor(e, t) { + this._firestore = e, this._transaction = t, this._dataReader = __PRIVATE_newUserDataReader(e); + } + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ get(e) { + const t = __PRIVATE_validateReference(e, this._firestore), n = new __PRIVATE_LiteUserDataWriter(this._firestore); + return this._transaction.lookup([ t._key ]).then((e => { + if (!e || 1 !== e.length) return fail(24041); + const r = e[0]; + if (r.isFoundDocument()) return new DocumentSnapshot$1(this._firestore, n, r.key, r, t.converter); + if (r.isNoDocument()) return new DocumentSnapshot$1(this._firestore, n, t._key, null, t.converter); + throw fail(18433, { + doc: r + }); + })); + } + set(e, t, n) { + const r = __PRIVATE_validateReference(e, this._firestore), i = __PRIVATE_applyFirestoreDataConverter(r.converter, t, n), s = __PRIVATE_parseSetData(this._dataReader, "Transaction.set", r._key, i, null !== r.converter, n); + return this._transaction.set(r._key, s), this; + } + update(e, t, n, ...r) { + const i = __PRIVATE_validateReference(e, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + let s; + return s = "string" == typeof (t = util.getModularInstance(t)) || t instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(this._dataReader, "Transaction.update", i._key, t, n, r) : __PRIVATE_parseUpdateData(this._dataReader, "Transaction.update", i._key, t), + this._transaction.update(i._key, s), this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `Transaction` instance. Used for chaining method calls. + */ delete(e) { + const t = __PRIVATE_validateReference(e, this._firestore); + return this._transaction.delete(t._key), this; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ class Transaction extends Transaction$1 { + // This class implements the same logic as the Transaction API in the Lite SDK + // but is subclassed in order to return its own DocumentSnapshot types. + /** @hideconstructor */ + constructor(e, t) { + super(e, t), this._firestore = e; + } + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ get(e) { + const t = __PRIVATE_validateReference(e, this._firestore), n = new __PRIVATE_ExpUserDataWriter(this._firestore); + return super.get(e).then((e => new DocumentSnapshot(this._firestore, n, t._key, e._document, new SnapshotMetadata( + /* hasPendingWrites= */ !1, + /* fromCache= */ !1), t.converter))); + } +} + +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ function runTransaction(e, t, n) { + e = __PRIVATE_cast(e, Firestore); + const r = { + ...In, + ...n + }; + !function __PRIVATE_validateTransactionOptions(e) { + if (e.maxAttempts < 1) throw new FirestoreError(N.INVALID_ARGUMENT, "Max attempts must be at least 1"); + }(r); + return function __PRIVATE_firestoreClientTransaction(e, t, n) { + const r = new __PRIVATE_Deferred; + return e.asyncQueue.enqueueAndForget((async () => { + const i = await __PRIVATE_getDatastore(e); + new __PRIVATE_TransactionRunner(e.asyncQueue, i, n, t, r).ju(); + })), r.promise; + }(ensureFirestoreConfigured(e), (n => t(new Transaction(e, n))), r); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. + */ function deleteField() { + return new __PRIVATE_DeleteFieldValueImpl("deleteField"); +} + +/** + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to + * include a server-generated timestamp in the written data. + */ function serverTimestamp() { + return new __PRIVATE_ServerTimestampFieldValueImpl("serverTimestamp"); +} + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array + * value that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements - The elements to union into the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()`. + */ function arrayUnion(...e) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new __PRIVATE_ArrayUnionFieldValueImpl("arrayUnion", e); +} + +/** + * Returns a special value that can be used with {@link (setDoc:1)} or {@link + * updateDoc:1} that tells the server to remove the given elements from any + * array value that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is not + * already an array it will be overwritten with an empty array. + * + * @param elements - The elements to remove from the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ function arrayRemove(...e) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new __PRIVATE_ArrayRemoveFieldValueImpl("arrayRemove", e); +} + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by + * the given value. + * + * If either the operand or the current field value uses floating point + * precision, all arithmetic follows IEEE 754 semantics. If both values are + * integers, values outside of JavaScript's safe number range + * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to + * precision loss. Furthermore, once processed by the Firestore backend, all + * integer operations are capped between -2^63 and 2^63-1. + * + * If the current field value is not of type `number`, or if the field does not + * yet exist, the transformation sets the field to the given value. + * + * @param n - The value to increment by. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ function increment(e) { + return new __PRIVATE_NumericIncrementFieldValueImpl("increment", e); +} + +/** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ function vector(e) { + return new VectorValue(e); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch} + * is 500. + * + * Unlike transactions, write batches are persisted offline and therefore are + * preferable when you don't need to condition your writes on read data. + * + * @returns A {@link WriteBatch} that can be used to atomically execute multiple + * writes. + */ function writeBatch(e) { + return ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)), new WriteBatch(e, (t => executeWrite(e, t))); +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function setIndexConfiguration(e, t) { + const n = ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)); + if (!n._uninitializedComponentsProvider || "memory" === n._uninitializedComponentsProvider._offline.kind) + // PORTING NOTE: We don't return an error if the user has not enabled + // persistence since `enableIndexeddbPersistence()` can fail on the Web. + return __PRIVATE_logWarn("Cannot enable indexes when persistence is disabled"), + Promise.resolve(); + const r = function __PRIVATE_parseIndexes(e) { + const t = "string" == typeof e ? function __PRIVATE_tryParseJson(e) { + try { + return JSON.parse(e); + } catch (e) { + throw new FirestoreError(N.INVALID_ARGUMENT, "Failed to parse JSON: " + e?.message); + } + }(e) : e, n = []; + if (Array.isArray(t.indexes)) for (const e of t.indexes) { + const t = __PRIVATE_tryGetString(e, "collectionGroup"), r = []; + if (Array.isArray(e.fields)) for (const t of e.fields) { + const e = __PRIVATE_fieldPathFromDotSeparatedString("setIndexConfiguration", __PRIVATE_tryGetString(t, "fieldPath")); + "CONTAINS" === t.arrayConfig ? r.push(new IndexSegment(e, 2 /* IndexKind.CONTAINS */)) : "ASCENDING" === t.order ? r.push(new IndexSegment(e, 0 /* IndexKind.ASCENDING */)) : "DESCENDING" === t.order && r.push(new IndexSegment(e, 1 /* IndexKind.DESCENDING */)); + } + n.push(new FieldIndex(FieldIndex.UNKNOWN_ID, t, r, IndexState.empty())); + } + return n; + }(t); + return __PRIVATE_firestoreClientSetIndexConfiguration(n, r); +} + +function __PRIVATE_tryGetString(e, t) { + if ("string" != typeof e[t]) throw new FirestoreError(N.INVALID_ARGUMENT, "Missing string value for: " + t); + return e[t]; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `PersistentCacheIndexManager` for configuring persistent cache indexes used + * for local query execution. + * + * To use, call `getPersistentCacheIndexManager()` to get an instance. + */ class PersistentCacheIndexManager { + /** @hideconstructor */ + constructor(e) { + this._firestore = e, + /** A type string to uniquely identify instances of this class. */ + this.type = "PersistentCacheIndexManager"; + } +} + +/** + * Returns the PersistentCache Index Manager used by the given `Firestore` + * object. + * + * @return The `PersistentCacheIndexManager` instance, or `null` if local + * persistent storage is not in use. + */ function getPersistentCacheIndexManager(e) { + e = __PRIVATE_cast(e, Firestore); + const t = En.get(e); + if (t) return t; + const n = ensureFirestoreConfigured(e); + if ("persistent" !== n._uninitializedComponentsProvider?._offline.kind) return null; + const r = new PersistentCacheIndexManager(e); + return En.set(e, r), r; +} + +/** + * Enables the SDK to create persistent cache indexes automatically for local + * query execution when the SDK believes cache indexes can help improve + * performance. + * + * This feature is disabled by default. + */ function enablePersistentCacheIndexAutoCreation(e) { + __PRIVATE_setPersistentCacheIndexAutoCreationEnabled(e, !0); +} + +/** + * Stops creating persistent cache indexes automatically for local query + * execution. The indexes which have been created by calling + * `enablePersistentCacheIndexAutoCreation()` still take effect. + */ function disablePersistentCacheIndexAutoCreation(e) { + __PRIVATE_setPersistentCacheIndexAutoCreationEnabled(e, !1); +} + +/** + * Removes all persistent cache indexes. + * + * Please note this function will also deletes indexes generated by + * `setIndexConfiguration()`, which is deprecated. + */ function deleteAllPersistentCacheIndexes(e) { + __PRIVATE_firestoreClientDeleteAllFieldIndexes(ensureFirestoreConfigured(e._firestore)).then((e => __PRIVATE_logDebug("deleting all persistent cache indexes succeeded"))).catch((e => __PRIVATE_logWarn("deleting all persistent cache indexes failed", e))); +} + +function __PRIVATE_setPersistentCacheIndexAutoCreationEnabled(e, t) { + __PRIVATE_firestoreClientSetPersistentCacheIndexAutoCreationEnabled(ensureFirestoreConfigured(e._firestore), t).then((e => __PRIVATE_logDebug(`setting persistent cache index auto creation isEnabled=${t} succeeded`))).catch((e => __PRIVATE_logWarn(`setting persistent cache index auto creation isEnabled=${t} failed`, e))); +} + +/** + * Maps `Firestore` instances to their corresponding + * `PersistentCacheIndexManager` instances. + * + * Use a `WeakMap` so that the mapping will be automatically dropped when the + * `Firestore` instance is garbage collected. This emulates a private member + * as described in https://goo.gle/454yvug. + */ const En = new WeakMap; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @internal + * @private + * + * This function is for internal use only. + * + * Returns the `QueryTarget` representation of the given query. Returns `null` + * if the Firestore client associated with the given query has not been + * initialized or has been terminated. + * + * @param query - The Query to convert to proto representation. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function _internalQueryToProtoQueryTarget(e) { + const t = ensureFirestoreConfigured(__PRIVATE_cast(e.firestore, Firestore)), n = t._onlineComponents?.datastore.serializer; + return void 0 === n ? null : __PRIVATE_toQueryTarget(n, __PRIVATE_queryToTarget(e._query)).ft; +} + +/** + * @internal + * @private + * + * This function is for internal use only. + * + * Returns `RunAggregationQueryRequest` which contains the proto representation + * of the given aggregation query request. Returns null if the Firestore client + * associated with the given query has not been initialized or has been + * terminated. + * + * @param query - The Query to convert to proto representation. + * @param aggregateSpec - The set of aggregations and their aliases. + */ function _internalAggregationQueryToProtoRunAggregationQueryRequest(e, t) { + const n = __PRIVATE_mapToArray(t, ((e, t) => new __PRIVATE_AggregateImpl(t, e.aggregateType, e._internalFieldPath))), r = ensureFirestoreConfigured(__PRIVATE_cast(e.firestore, Firestore)), i = r._onlineComponents?.datastore.serializer; + return void 0 === i ? null : __PRIVATE_toRunAggregationQueryRequest(i, __PRIVATE_queryToAggregateTarget(e._query), n, + /* skipAliasing= */ !0).request; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Testing hooks for use by Firestore's integration test suite to reach into the + * SDK internals to validate logic and behavior that is not visible from the + * public API surface. + * + * @internal + */ class TestingHooks { + constructor() { + throw new Error("instances of this class should not be created"); + } + /** + * Registers a callback to be notified when an existence filter mismatch + * occurs in the Watch listen stream. + * + * The relative order in which callbacks are notified is unspecified; do not + * rely on any particular ordering. If a given callback is registered multiple + * times then it will be notified multiple times, once per registration. + * + * @param callback the callback to invoke upon existence filter mismatch. + * + * @return a function that, when called, unregisters the given callback; only + * the first invocation of the returned function does anything; all subsequent + * invocations do nothing. + */ static onExistenceFilterMismatch(e) { + return __PRIVATE_TestingHooksSpiImpl.instance.onExistenceFilterMismatch(e); + } +} + +/** + * The implementation of `TestingHooksSpi`. + */ class __PRIVATE_TestingHooksSpiImpl { + constructor() { + this.Mc = new Map; + } + static get instance() { + return dn || (dn = new __PRIVATE_TestingHooksSpiImpl, function __PRIVATE_setTestingHooksSpi(e) { + if (wt) throw new Error("a TestingHooksSpi instance is already set"); + wt = e; + }(dn)), dn; + } + lt(e) { + this.Mc.forEach((t => t(e))); + } + onExistenceFilterMismatch(e) { + const t = Symbol(), n = this.Mc; + return n.set(t, e), () => n.delete(t); + } +} + +let dn = null; + +/** + * Cloud Firestore + * + * @packageDocumentation + */ !function __PRIVATE_registerFirestore(e, t = !0) { + !function __PRIVATE_setSDKVersion(e) { + x = e; + }(app.SDK_VERSION), app._registerComponent(new component.Component("firestore", ((e, {instanceIdentifier: n, options: r}) => { + const i = e.getProvider("app").getImmediate(), s = new Firestore(new __PRIVATE_FirebaseAuthCredentialsProvider(e.getProvider("auth-internal")), new __PRIVATE_FirebaseAppCheckTokenProvider(i, e.getProvider("app-check-internal")), function __PRIVATE_databaseIdFromApp(e, t) { + if (!Object.prototype.hasOwnProperty.apply(e.options, [ "projectId" ])) throw new FirestoreError(N.INVALID_ARGUMENT, '"projectId" not provided in firebase.initializeApp.'); + return new DatabaseId(e.options.projectId, t); + }(i, n), i); + return r = { + useFetchStreams: t, + ...r + }, s._setSettings(r), s; + }), "PUBLIC").setMultipleInstances(!0)), app.registerVersion(F, M, e), + // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation + app.registerVersion(F, M, "cjs2020"); +}(); + +exports.AbstractUserDataWriter = AbstractUserDataWriter; +exports.AggregateField = AggregateField; +exports.AggregateQuerySnapshot = AggregateQuerySnapshot; +exports.Bytes = Bytes; +exports.CACHE_SIZE_UNLIMITED = ln; +exports.CollectionReference = CollectionReference; +exports.DocumentReference = DocumentReference; +exports.DocumentSnapshot = DocumentSnapshot; +exports.FieldPath = FieldPath; +exports.FieldValue = FieldValue; +exports.Firestore = Firestore; +exports.FirestoreError = FirestoreError; +exports.GeoPoint = GeoPoint; +exports.LoadBundleTask = LoadBundleTask; +exports.PersistentCacheIndexManager = PersistentCacheIndexManager; +exports.Query = Query; +exports.QueryCompositeFilterConstraint = QueryCompositeFilterConstraint; +exports.QueryConstraint = QueryConstraint; +exports.QueryDocumentSnapshot = QueryDocumentSnapshot; +exports.QueryEndAtConstraint = QueryEndAtConstraint; +exports.QueryFieldFilterConstraint = QueryFieldFilterConstraint; +exports.QueryLimitConstraint = QueryLimitConstraint; +exports.QueryOrderByConstraint = QueryOrderByConstraint; +exports.QuerySnapshot = QuerySnapshot; +exports.QueryStartAtConstraint = QueryStartAtConstraint; +exports.SnapshotMetadata = SnapshotMetadata; +exports.Timestamp = Timestamp; +exports.Transaction = Transaction; +exports.VectorValue = VectorValue; +exports.WriteBatch = WriteBatch; +exports._AutoId = __PRIVATE_AutoId; +exports._ByteString = ByteString; +exports._DatabaseId = DatabaseId; +exports._DocumentKey = DocumentKey; +exports._EmptyAppCheckTokenProvider = __PRIVATE_EmptyAppCheckTokenProvider; +exports._EmptyAuthCredentialsProvider = __PRIVATE_EmptyAuthCredentialsProvider; +exports._FieldPath = FieldPath$1; +exports._TestingHooks = TestingHooks; +exports._cast = __PRIVATE_cast; +exports._debugAssert = __PRIVATE_debugAssert; +exports._internalAggregationQueryToProtoRunAggregationQueryRequest = _internalAggregationQueryToProtoRunAggregationQueryRequest; +exports._internalQueryToProtoQueryTarget = _internalQueryToProtoQueryTarget; +exports._isBase64Available = __PRIVATE_isBase64Available; +exports._logWarn = __PRIVATE_logWarn; +exports._validateIsNotUsedTogether = __PRIVATE_validateIsNotUsedTogether; +exports.addDoc = addDoc; +exports.aggregateFieldEqual = aggregateFieldEqual; +exports.aggregateQuerySnapshotEqual = aggregateQuerySnapshotEqual; +exports.and = and; +exports.arrayRemove = arrayRemove; +exports.arrayUnion = arrayUnion; +exports.average = average; +exports.clearIndexedDbPersistence = clearIndexedDbPersistence; +exports.collection = collection; +exports.collectionGroup = collectionGroup; +exports.connectFirestoreEmulator = connectFirestoreEmulator; +exports.count = count; +exports.deleteAllPersistentCacheIndexes = deleteAllPersistentCacheIndexes; +exports.deleteDoc = deleteDoc; +exports.deleteField = deleteField; +exports.disableNetwork = disableNetwork; +exports.disablePersistentCacheIndexAutoCreation = disablePersistentCacheIndexAutoCreation; +exports.doc = doc; +exports.documentId = documentId; +exports.documentSnapshotFromJSON = documentSnapshotFromJSON; +exports.enableIndexedDbPersistence = enableIndexedDbPersistence; +exports.enableMultiTabIndexedDbPersistence = enableMultiTabIndexedDbPersistence; +exports.enableNetwork = enableNetwork; +exports.enablePersistentCacheIndexAutoCreation = enablePersistentCacheIndexAutoCreation; +exports.endAt = endAt; +exports.endBefore = endBefore; +exports.ensureFirestoreConfigured = ensureFirestoreConfigured; +exports.executeWrite = executeWrite; +exports.getAggregateFromServer = getAggregateFromServer; +exports.getCountFromServer = getCountFromServer; +exports.getDoc = getDoc; +exports.getDocFromCache = getDocFromCache; +exports.getDocFromServer = getDocFromServer; +exports.getDocs = getDocs; +exports.getDocsFromCache = getDocsFromCache; +exports.getDocsFromServer = getDocsFromServer; +exports.getFirestore = getFirestore; +exports.getPersistentCacheIndexManager = getPersistentCacheIndexManager; +exports.increment = increment; +exports.initializeFirestore = initializeFirestore; +exports.limit = limit; +exports.limitToLast = limitToLast; +exports.loadBundle = loadBundle; +exports.memoryEagerGarbageCollector = memoryEagerGarbageCollector; +exports.memoryLocalCache = memoryLocalCache; +exports.memoryLruGarbageCollector = memoryLruGarbageCollector; +exports.namedQuery = namedQuery; +exports.onSnapshot = onSnapshot; +exports.onSnapshotResume = onSnapshotResume; +exports.onSnapshotsInSync = onSnapshotsInSync; +exports.or = or; +exports.orderBy = orderBy; +exports.persistentLocalCache = persistentLocalCache; +exports.persistentMultipleTabManager = persistentMultipleTabManager; +exports.persistentSingleTabManager = persistentSingleTabManager; +exports.query = query; +exports.queryEqual = queryEqual; +exports.querySnapshotFromJSON = querySnapshotFromJSON; +exports.refEqual = refEqual; +exports.runTransaction = runTransaction; +exports.serverTimestamp = serverTimestamp; +exports.setDoc = setDoc; +exports.setIndexConfiguration = setIndexConfiguration; +exports.setLogLevel = setLogLevel; +exports.snapshotEqual = snapshotEqual; +exports.startAfter = startAfter; +exports.startAt = startAt; +exports.sum = sum; +exports.terminate = terminate; +exports.updateDoc = updateDoc; +exports.vector = vector; +exports.waitForPendingWrites = waitForPendingWrites; +exports.where = where; +exports.writeBatch = writeBatch; +//# sourceMappingURL=index.cjs.js.map diff --git a/frontend-old/node_modules/@firebase/firestore/dist/index.cjs.js.map b/frontend-old/node_modules/@firebase/firestore/dist/index.cjs.js.map new file mode 100644 index 0000000..c76a4ac --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/index.cjs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.cjs.js","sources":["../src/auth/user.ts","../src/core/version.ts","../src/util/log.ts","../src/platform/browser/format_json.ts","../src/util/assert.ts","../src/util/error.ts","../src/util/promise.ts","../src/api/credentials.ts","../src/platform/browser/random_bytes.ts","../src/util/misc.ts","../src/model/path.ts","../src/model/document_key.ts","../src/util/input_validation.ts","../src/util/json_validation.ts","../src/lite-api/timestamp.ts","../src/core/snapshot_version.ts","../src/model/field_index.ts","../src/local/persistence_transaction.ts","../src/local/local_store.ts","../src/local/persistence_promise.ts","../src/local/simple_db.ts","../src/local/index_backfiller.ts","../src/core/listen_sequence.ts","../src/util/types.ts","../src/local/encoded_resource_path.ts","../src/local/indexeddb_schema_legacy.ts","../src/local/indexeddb_sentinels.ts","../src/local/indexeddb_transaction.ts","../src/util/obj.ts","../src/util/sorted_map.ts","../src/util/sorted_set.ts","../src/model/field_mask.ts","../src/util/base64_decode_error.ts","../src/platform/browser/base64.ts","../src/util/byte_string.ts","../src/model/normalize.ts","../src/model/server_timestamps.ts","../src/core/database_info.ts","../src/model/values.ts","../src/model/object_value.ts","../src/model/document.ts","../src/core/bound.ts","../src/core/order_by.ts","../src/core/filter.ts","../src/core/target.ts","../src/core/query.ts","../src/util/obj_map.ts","../src/model/collections.ts","../src/remote/number_serializer.ts","../src/model/transform_operation.ts","../src/model/mutation.ts","../src/model/mutation_batch.ts","../src/model/overlay.ts","../src/core/aggregate.ts","../src/remote/existence_filter.ts","../src/remote/rpc_error.ts","../src/util/testing_hooks_spi.ts","../src/platform/browser/text_serializer.ts","../src/remote/bloom_filter.ts","../src/remote/remote_event.ts","../src/remote/watch_change.ts","../src/remote/serializer.ts","../src/local/target_data.ts","../src/local/local_serializer.ts","../src/local/indexeddb_bundle_cache.ts","../src/local/indexeddb_document_overlay_cache.ts","../src/local/indexeddb_globals_cache.ts","../src/index/firestore_index_value_writer.ts","../src/index/ordered_code_writer.ts","../src/index/index_byte_encoder.ts","../src/index/index_entry.ts","../src/model/target_index_matcher.ts","../src/util/logic_utils.ts","../src/local/memory_index_manager.ts","../src/local/indexeddb_index_manager.ts","../src/local/lru_garbage_collector.ts","../src/local/indexeddb_mutation_batch_impl.ts","../src/local/indexeddb_mutation_queue.ts","../src/core/target_id_generator.ts","../src/local/indexeddb_target_cache.ts","../src/local/lru_garbage_collector_impl.ts","../src/local/indexeddb_lru_delegate_impl.ts","../src/local/remote_document_change_buffer.ts","../src/local/indexeddb_remote_document_cache.ts","../src/local/overlayed_document.ts","../src/local/local_documents_view.ts","../src/local/memory_bundle_cache.ts","../src/local/memory_document_overlay_cache.ts","../src/local/memory_globals_cache.ts","../src/local/reference_set.ts","../src/local/memory_mutation_queue.ts","../src/local/memory_remote_document_cache.ts","../src/local/memory_target_cache.ts","../src/local/memory_persistence.ts","../src/local/indexeddb_schema_converter.ts","../src/local/indexeddb_persistence.ts","../src/local/indexeddb_schema.ts","../src/local/local_view_changes.ts","../src/local/query_context.ts","../src/local/query_engine.ts","../src/local/local_store_impl.ts","../src/local/shared_client_state_schema.ts","../src/local/shared_client_state.ts","../src/remote/connectivity_monitor_noop.ts","../src/platform/browser/connectivity_monitor.ts","../src/util/debug_uid.ts","../src/remote/rest_connection.ts","../src/remote/stream_bridge.ts","../src/platform/browser/webchannel_connection.ts","../src/platform/browser/dom.ts","../src/platform/browser/serializer.ts","../src/remote/backoff.ts","../src/remote/persistent_stream.ts","../src/remote/datastore.ts","../src/remote/online_state_tracker.ts","../src/remote/remote_store.ts","../src/util/async_queue.ts","../src/model/document_set.ts","../src/core/view_snapshot.ts","../src/core/event_manager.ts","../src/util/bundle_reader.ts","../src/core/bundle_impl.ts","../src/core/view.ts","../src/core/sync_engine_impl.ts","../src/core/component_provider.ts","../src/platform/browser/connection.ts","../src/util/byte_stream.ts","../src/util/async_observer.ts","../src/util/bundle_reader_impl.ts","../src/util/bundle_reader_sync_impl.ts","../src/core/transaction.ts","../src/core/transaction_runner.ts","../src/core/firestore_client.ts","../src/platform/browser/byte_stream_reader.ts","../src/util/array.ts","../src/api/long_polling_options.ts","../src/lite-api/components.ts","../src/lite-api/settings.ts","../src/lite-api/database.ts","../src/lite-api/reference.ts","../src/util/async_queue_impl.ts","../src/api/observer.ts","../src/api/bundle.ts","../src/api/database.ts","../src/lite-api/aggregate_types.ts","../src/lite-api/bytes.ts","../src/lite-api/field_path.ts","../src/lite-api/field_value.ts","../src/lite-api/geo_point.ts","../src/lite-api/vector_value.ts","../src/lite-api/user_data_reader.ts","../src/lite-api/snapshot.ts","../src/lite-api/query.ts","../src/lite-api/user_data_writer.ts","../src/lite-api/reference_impl.ts","../src/lite-api/aggregate.ts","../src/api/snapshot.ts","../src/platform/browser/snapshot_to_json.ts","../src/api/reference_impl.ts","../src/api/aggregate.ts","../src/api/cache_config.ts","../src/core/transaction_options.ts","../src/lite-api/write_batch.ts","../src/lite-api/transaction.ts","../src/api/transaction.ts","../src/lite-api/field_value_impl.ts","../src/api/write_batch.ts","../src/api/index_configuration.ts","../src/api/persistent_cache_index_manager.ts","../src/remote/internal_serializer.ts","../src/util/testing_hooks.ts","../src/register.ts","../src/index.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Simple wrapper around a nullable UID. Mostly exists to make code more\n * readable.\n */\nexport class User {\n /** A user with a null UID. */\n static readonly UNAUTHENTICATED = new User(null);\n\n // TODO(mikelehen): Look into getting a proper uid-equivalent for\n // non-FirebaseAuth providers.\n static readonly GOOGLE_CREDENTIALS = new User('google-credentials-uid');\n static readonly FIRST_PARTY = new User('first-party-uid');\n static readonly MOCK_USER = new User('mock-user');\n\n constructor(readonly uid: string | null) {}\n\n isAuthenticated(): boolean {\n return this.uid != null;\n }\n\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */\n toKey(): string {\n if (this.isAuthenticated()) {\n return 'uid:' + this.uid;\n } else {\n return 'anonymous-user';\n }\n }\n\n isEqual(otherUser: User): boolean {\n return otherUser.uid === this.uid;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The semver (www.semver.org) version of the SDK. */\nimport { version } from '../../../firebase/package.json';\nexport let SDK_VERSION = version;\nexport function setSDKVersion(version: string): void {\n SDK_VERSION = version;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel, LogLevelString } from '@firebase/logger';\n\nimport { SDK_VERSION } from '../core/version';\nimport { formatJSON } from '../platform/format_json';\n\nexport { LogLevel, LogLevelString };\n\nconst logClient = new Logger('@firebase/firestore');\n\n// Helper methods are needed because variables can't be exported as read/write\nexport function getLogLevel(): LogLevel {\n return logClient.logLevel;\n}\n\n/**\n * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).\n *\n * @param logLevel - The verbosity you set for activity and error logging. Can\n * be any of the following values:\n *\n *

    \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 *\n * @param code generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(\n code: number,\n message: string,\n context?: Record\n): never;\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 *\n * @param id generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(id: number, context?: Record): never;\n\nexport function fail(\n id: number,\n messageOrContext?: string | Record,\n context?: Record\n): never {\n let message = 'Unexpected state';\n if (typeof messageOrContext === 'string') {\n message = messageOrContext;\n } else {\n context = messageOrContext;\n }\n _fail(id, message, context);\n}\n\nfunction _fail(\n id: number,\n failure: string,\n context?: Record\n): never {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n let message = `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ${failure} (ID: ${id.toString(\n 16\n )})`;\n if (context !== undefined) {\n try {\n const stringContext = JSON.stringify(context);\n message += ' CONTEXT: ' + stringContext;\n } catch (e) {\n message += ' CONTEXT: ' + context;\n }\n }\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 *\n * @param id generate a new unique value with `yarn assertion-idgenerate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n assertion: boolean,\n id: number,\n message: string,\n context?: Record\n): asserts assertion;\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 *\n * @param id generate a new unique value with `yarn assertion-id:generate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n assertion: boolean,\n id: number,\n context?: Record\n): asserts assertion;\n\nexport function hardAssert(\n assertion: boolean,\n id: number,\n messageOrContext?: string | Record,\n context?: Record\n): asserts assertion {\n let message = 'Unexpected state';\n if (typeof messageOrContext === 'string') {\n message = messageOrContext;\n } else {\n context = messageOrContext;\n }\n\n if (!assertion) {\n _fail(id, message, context);\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(0xdeb6, 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 { FirebaseApp, _isFirebaseServerApp } from '@firebase/app';\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 0xa539,\n 'Invalid tokenData returned from getToken()',\n { 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 0xa540,\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 0x7c5d,\n 'Invalid tokenData returned from getToken()',\n { 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 0x0807,\n 'Received invalid UID',\n { 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 private serverAppAppCheckToken: string | null = null;\n\n constructor(\n app: FirebaseApp,\n private appCheckProvider: Provider\n ) {\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n }\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n hardAssert(\n this.tokenListener === undefined,\n 0x0db8,\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 if (this.serverAppAppCheckToken) {\n return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n }\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 0xae0e,\n 'Invalid tokenResult returned from getToken()',\n { 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 private serverAppAppCheckToken: string | null = null;\n\n constructor(\n app: FirebaseApp,\n private appCheckProvider: Provider\n ) {\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n appCheckProvider.onInit(appCheck => {\n this.appCheck = appCheck;\n });\n }\n\n getToken(): Promise {\n if (this.serverAppAppCheckToken) {\n return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n }\n\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 0x0d8e,\n 'Invalid tokenResult returned from getToken()',\n { 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\n/** Compare strings in UTF-8 encoded byte order */\nexport function compareUtf8Strings(left: string, right: string): number {\n // Find the first differing character (a.k.a. \"UTF-16 code unit\") in the two strings and,\n // if found, use that character to determine the relative ordering of the two strings as a\n // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by\n // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8\n // and UTF-16 happen to represent Unicode code points.\n //\n // After finding the first pair of differing characters, there are two cases:\n //\n // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or\n // both are surrogates from a surrogate pair (that collectively represent code points greater\n // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the\n // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is\n // sufficient.\n //\n // Case 2: One character is a surrogate and the other is not. In this case the surrogate-\n // containing string is always ordered after the non-surrogate. This is because surrogates are\n // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations\n // and are lexicographically greater than the 1, 2, or 3-byte representations of code points\n // less than or equal to 0xFFFF.\n //\n // An example of why Case 2 is required is comparing the following two Unicode code points:\n //\n // |-----------------------|------------|---------------------|-----------------|\n // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding |\n // |-----------------------|------------|---------------------|-----------------|\n // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD |\n // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 |\n // |-----------------------|------------|---------------------|-----------------|\n //\n // A lexicographical comparison of the UTF-8 encodings of these code points would order\n // \"Replacement Character\" _before_ \"Grinning Face\" because 0xEF is less than 0xF0. However, a\n // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously\n // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out,\n // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate\n // pair with those that do not.\n const length = Math.min(left.length, right.length);\n for (let i = 0; i < length; i++) {\n const leftChar = left.charAt(i);\n const rightChar = right.charAt(i);\n if (leftChar !== rightChar) {\n return isSurrogate(leftChar) === isSurrogate(rightChar)\n ? primitiveComparator(leftChar, rightChar)\n : isSurrogate(leftChar)\n ? 1\n : -1;\n }\n }\n\n // Use the lengths of the strings to determine the overall comparison result since either the\n // strings were equal or one is a prefix of the other.\n return primitiveComparator(left.length, right.length);\n}\n\nconst MIN_SURROGATE = 0xd800;\nconst MAX_SURROGATE = 0xdfff;\n\nexport function isSurrogate(s: string): boolean {\n debugAssert(s.length === 1, `s.length == ${s.length}, but expected 1`);\n const c = s.charCodeAt(0);\n return c >= MIN_SURROGATE && c <= MAX_SURROGATE;\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 { Integer } from '@firebase/webchannel-wrapper/bloom-blob';\n\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { compareUtf8Strings, primitiveComparator } from '../util/misc';\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(0x027d, 'offset out of range', {\n offset,\n range: segments.length\n });\n }\n\n if (length === undefined) {\n length = segments.length - offset;\n } else if (length > segments.length - offset) {\n fail(0x06d2, 'length out of range', {\n length,\n range: segments.length - offset\n });\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 /**\n * Compare 2 paths segment by segment, prioritizing numeric IDs\n * (e.g., \"__id123__\") in numeric ascending order, followed by string\n * segments in lexicographical order.\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 comparison = BasePath.compareSegments(p1.get(i), p2.get(i));\n if (comparison !== 0) {\n return comparison;\n }\n }\n return primitiveComparator(p1.length, p2.length);\n }\n\n private static compareSegments(lhs: string, rhs: string): number {\n const isLhsNumeric = BasePath.isNumericId(lhs);\n const isRhsNumeric = BasePath.isNumericId(rhs);\n\n if (isLhsNumeric && !isRhsNumeric) {\n // Only lhs is numeric\n return -1;\n } else if (!isLhsNumeric && isRhsNumeric) {\n // Only rhs is numeric\n return 1;\n } else if (isLhsNumeric && isRhsNumeric) {\n // both numeric\n return BasePath.extractNumericId(lhs).compare(\n BasePath.extractNumericId(rhs)\n );\n } else {\n // both non-numeric\n return compareUtf8Strings(lhs, rhs);\n }\n }\n\n // Checks if a segment is a numeric ID (starts with \"__id\" and ends with \"__\").\n private static isNumericId(segment: string): boolean {\n return segment.startsWith('__id') && segment.endsWith('__');\n }\n\n private static extractNumericId(segment: string): Integer {\n return Integer.fromString(segment.substring(4, segment.length - 2));\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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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(0x3029, 'Unknown wrong type', { 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 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isPlainObject } from '../util/input_validation';\n\nimport { Code, FirestoreError } from './error';\n\n/**\n * A list of data types Firestore objects may serialize in their toJSON implemenetations.\n * @private\n * @internal\n */\nexport type JsonTypeDesc =\n | 'object'\n | 'string'\n | 'number'\n | 'boolean'\n | 'null'\n | 'undefined';\n\n/**\n * An association of JsonTypeDesc values to their native types.\n * @private\n * @internal\n */\nexport type TSType = T extends 'object'\n ? object\n : T extends 'string'\n ? string\n : T extends 'number'\n ? number\n : T extends 'boolean'\n ? boolean\n : T extends 'null'\n ? null\n : T extends 'undefined'\n ? undefined\n : never;\n\n/**\n * The representation of a JSON object property name and its type value.\n * @private\n * @internal\n */\nexport interface Property {\n value?: TSType;\n typeString: JsonTypeDesc;\n}\n\n/**\n * A type Firestore data types may use to define the fields used in their JSON serialization.\n * @private\n * @internal\n */\nexport interface JsonSchema {\n [key: string]: Property;\n}\n\n/**\n * Associates the JSON property type to the native type and sets them to be Required.\n * @private\n * @internal\n */\nexport type Json = {\n [K in keyof T]: Required['value'];\n};\n\n/**\n * Helper function to define a JSON schema {@link Property}.\n * @private\n * @internal\n */\nexport function property(\n typeString: T,\n optionalValue?: TSType\n): Property {\n const result: Property = {\n typeString\n };\n if (optionalValue) {\n result.value = optionalValue;\n }\n return result;\n}\n\n/**\n * Validates the JSON object based on the provided schema, and narrows the type to the provided\n * JSON schema.\n * @private\n * @internal\n *\n * @param json A JSON object to validate.\n * @param scheme a {@link JsonSchema} that defines the properties to validate.\n * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise.\n */\nexport function validateJSON(\n json: object,\n schema: S\n): json is Json {\n if (!isPlainObject(json)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'JSON must be an object');\n }\n let error: string | undefined = undefined;\n for (const key in schema) {\n if (schema[key]) {\n const typeString = schema[key].typeString;\n const value: { value: unknown } | undefined =\n 'value' in schema[key] ? { value: schema[key].value } : undefined;\n if (!(key in json)) {\n error = `JSON missing required field: '${key}'`;\n break;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const fieldValue = (json as any)[key];\n if (typeString && typeof fieldValue !== typeString) {\n error = `JSON field '${key}' must be a ${typeString}.`;\n break;\n } else if (value !== undefined && fieldValue !== value.value) {\n error = `Expected '${key}' field to equal '${value.value}'`;\n break;\n }\n }\n }\n if (error) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, error);\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 { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\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 static _jsonSchemaVersion: string = 'firestore/timestamp/1.0';\n static _jsonSchema = {\n type: property('string', Timestamp._jsonSchemaVersion),\n seconds: property('number'),\n nanoseconds: property('number')\n };\n\n /**\n * Returns a JSON-serializable representation of this `Timestamp`.\n */\n toJSON(): { seconds: number; nanoseconds: number; type: string } {\n return {\n type: Timestamp._jsonSchemaVersion,\n seconds: this.seconds,\n nanoseconds: this.nanoseconds\n };\n }\n\n /**\n * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}.\n */\n static fromJSON(json: object): Timestamp {\n if (validateJSON(json, Timestamp._jsonSchema)) {\n return new Timestamp(json.seconds, json.nanoseconds);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Timestamp from JSON.'\n );\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 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(0xe830, '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 { getGlobal, 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 `indexedDB` are guarded by SimpleDb.isAvailable() and getGlobal()\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 lastClosedDbVersion: number | null = null;\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 const globals = getGlobal();\n return wrapRequest(\n globals.indexedDB.deleteDatabase(name)\n ).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\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 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { FirestoreError } from '../api';\nimport { DocumentMap } from '../model/collections';\nimport {\n IndexOffset,\n indexOffsetComparator,\n newIndexOffsetFromDocument\n} from '../model/field_index';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { logDebug } from '../util/log';\n\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from './local_store';\nimport { LocalWriteResult } from './local_store_impl';\nimport { Persistence, Scheduler } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { isIndexedDbTransactionError } from './simple_db';\n\nconst LOG_TAG = 'IndexBackfiller';\n\n/** How long we wait to try running index backfill after SDK initialization. */\nconst INITIAL_BACKFILL_DELAY_MS = 15 * 1000;\n\n/** Minimum amount of time between backfill checks, after the first one. */\nconst REGULAR_BACKFILL_DELAY_MS = 60 * 1000;\n\n/** The maximum number of documents to process each time backfill() is called. */\nconst MAX_DOCUMENTS_TO_PROCESS = 50;\n\n/** This class is responsible for the scheduling of Index Backfiller. */\nexport class IndexBackfillerScheduler implements Scheduler {\n private task: DelayedOperation | null;\n\n constructor(\n private readonly asyncQueue: AsyncQueue,\n private readonly backfiller: IndexBackfiller\n ) {\n this.task = null;\n }\n\n start(): void {\n debugAssert(\n this.task === null,\n 'Cannot start an already started IndexBackfillerScheduler'\n );\n this.schedule(INITIAL_BACKFILL_DELAY_MS);\n }\n\n stop(): void {\n if (this.task) {\n this.task.cancel();\n this.task = null;\n }\n }\n\n get started(): boolean {\n return this.task !== null;\n }\n\n private schedule(delay: number): void {\n debugAssert(\n this.task === null,\n 'Cannot schedule IndexBackfiller while a task is pending'\n );\n logDebug(LOG_TAG, `Scheduled in ${delay}ms`);\n this.task = this.asyncQueue.enqueueAfterDelay(\n TimerId.IndexBackfill,\n delay,\n async () => {\n this.task = null;\n try {\n const documentsProcessed = await this.backfiller.backfill();\n logDebug(LOG_TAG, `Documents written: ${documentsProcessed}`);\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(\n LOG_TAG,\n 'Ignoring IndexedDB error during index backfill: ',\n e\n );\n } else {\n await ignoreIfPrimaryLeaseLoss(e as FirestoreError);\n }\n }\n await this.schedule(REGULAR_BACKFILL_DELAY_MS);\n }\n );\n }\n}\n\n/** Implements the steps for backfilling indexes. */\nexport class IndexBackfiller {\n constructor(\n /**\n * LocalStore provides access to IndexManager and LocalDocumentView.\n * These properties will update when the user changes. Consequently,\n * making a local copy of IndexManager and LocalDocumentView will require\n * updates over time. The simpler solution is to rely on LocalStore to have\n * an up-to-date references to IndexManager and LocalDocumentStore.\n */\n private readonly localStore: LocalStore,\n private readonly persistence: Persistence\n ) {}\n\n async backfill(\n maxDocumentsToProcess: number = MAX_DOCUMENTS_TO_PROCESS\n ): Promise {\n return this.persistence.runTransaction(\n 'Backfill Indexes',\n 'readwrite-primary',\n txn => this.writeIndexEntries(txn, maxDocumentsToProcess)\n );\n }\n\n /** Writes index entries until the cap is reached. Returns the number of documents processed. */\n private writeIndexEntries(\n transaction: PersistenceTransaction,\n maxDocumentsToProcess: number\n ): PersistencePromise {\n const processedCollectionGroups = new Set();\n let documentsRemaining = maxDocumentsToProcess;\n let continueLoop = true;\n return PersistencePromise.doWhile(\n () => continueLoop === true && documentsRemaining > 0,\n () => {\n return this.localStore.indexManager\n .getNextCollectionGroupToUpdate(transaction)\n .next((collectionGroup: string | null) => {\n if (\n collectionGroup === null ||\n processedCollectionGroups.has(collectionGroup)\n ) {\n continueLoop = false;\n } else {\n logDebug(LOG_TAG, `Processing collection: ${collectionGroup}`);\n return this.writeEntriesForCollectionGroup(\n transaction,\n collectionGroup,\n documentsRemaining\n ).next(documentsProcessed => {\n documentsRemaining -= documentsProcessed;\n processedCollectionGroups.add(collectionGroup);\n });\n }\n });\n }\n ).next(() => maxDocumentsToProcess - documentsRemaining);\n }\n\n /**\n * Writes entries for the provided collection group. Returns the number of documents processed.\n */\n private writeEntriesForCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n documentsRemainingUnderCap: number\n ): PersistencePromise {\n // Use the earliest offset of all field indexes to query the local cache.\n return this.localStore.indexManager\n .getMinOffsetFromCollectionGroup(transaction, collectionGroup)\n .next(existingOffset =>\n this.localStore.localDocuments\n .getNextDocuments(\n transaction,\n collectionGroup,\n existingOffset,\n documentsRemainingUnderCap\n )\n .next(nextBatch => {\n const docs: DocumentMap = nextBatch.changes;\n return this.localStore.indexManager\n .updateIndexEntries(transaction, docs)\n .next(() => this.getNewOffset(existingOffset, nextBatch))\n .next(newOffset => {\n logDebug(LOG_TAG, `Updating offset: ${newOffset}`);\n return this.localStore.indexManager.updateCollectionGroup(\n transaction,\n collectionGroup,\n newOffset\n );\n })\n .next(() => docs.size);\n })\n );\n }\n\n /** Returns the next offset based on the provided documents. */\n private getNewOffset(\n existingOffset: IndexOffset,\n lookupResult: LocalWriteResult\n ): IndexOffset {\n let maxOffset: IndexOffset = existingOffset;\n lookupResult.changes.forEach((key, document) => {\n const newOffset: IndexOffset = newIndexOffsetFromDocument(document);\n if (indexOffsetComparator(newOffset, maxOffset) > 0) {\n maxOffset = newOffset;\n }\n });\n return new IndexOffset(\n maxOffset.readTime,\n maxOffset.documentKey,\n Math.max(lookupResult.batchId, existingOffset.largestBatchId)\n );\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequenceNumber } from './types';\n\n/**\n * `SequenceNumberSyncer` defines the methods required to keep multiple instances of a\n * `ListenSequence` in sync.\n */\nexport interface SequenceNumberSyncer {\n // Notify the syncer that a new sequence number has been used.\n writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void;\n // Setting this property allows the syncer to notify when a sequence number has been used, and\n // and lets the ListenSequence adjust its internal previous value accordingly.\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null;\n}\n\n/**\n * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to\n * exceed. All subsequent calls to next will return increasing values. If provided with a\n * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as\n * well as write out sequence numbers that it produces via `next()`.\n */\nexport class ListenSequence {\n static readonly INVALID: ListenSequenceNumber = -1;\n\n private writeNewSequenceNumber?: (\n newSequenceNumber: ListenSequenceNumber\n ) => void;\n\n constructor(\n private previousValue: ListenSequenceNumber,\n sequenceNumberSyncer?: SequenceNumberSyncer\n ) {\n if (sequenceNumberSyncer) {\n sequenceNumberSyncer.sequenceNumberHandler = sequenceNumber =>\n this.setPreviousValue(sequenceNumber);\n this.writeNewSequenceNumber = sequenceNumber =>\n sequenceNumberSyncer.writeSequenceNumber(sequenceNumber);\n }\n }\n\n private setPreviousValue(\n externalPreviousValue: ListenSequenceNumber\n ): ListenSequenceNumber {\n this.previousValue = Math.max(externalPreviousValue, this.previousValue);\n return this.previousValue;\n }\n\n next(): ListenSequenceNumber {\n const nextValue = ++this.previousValue;\n if (this.writeNewSequenceNumber) {\n this.writeNewSequenceNumber(nextValue);\n }\n return nextValue;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Sentinel value that sorts before any Mutation Batch ID. */\nexport const BATCHID_UNKNOWN = -1;\n\n// An Object whose keys and values are strings.\nexport interface StringMap {\n [key: string]: string;\n}\n\n/**\n * Returns whether a variable is either undefined or null.\n */\nexport function isNullOrUndefined(value: unknown): value is null | undefined {\n return value === null || value === undefined;\n}\n\n/** Returns whether the value represents -0. */\nexport function isNegativeZero(value: number): boolean {\n // Detect if the value is -0.0. Based on polyfill from\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n return value === 0 && 1 / value === 1 / -0;\n}\n\n/**\n * Returns whether a value is an integer and in the safe integer range\n * @param value - The value to test for being an integer and in the safe range\n */\nexport function isSafeInteger(value: unknown): boolean {\n return (\n typeof value === 'number' &&\n Number.isInteger(value) &&\n !isNegativeZero(value) &&\n value <= Number.MAX_SAFE_INTEGER &&\n value >= Number.MIN_SAFE_INTEGER\n );\n}\n\n/** The subset of the browser's Window interface used by the SDK. */\nexport interface WindowLike {\n readonly localStorage: Storage;\n readonly indexedDB: IDBFactory | null;\n addEventListener(type: string, listener: EventListener): void;\n removeEventListener(type: string, listener: EventListener): void;\n}\n\n/** The subset of the browser's Document interface used by the SDK. */\nexport interface DocumentLike {\n readonly visibilityState: DocumentVisibilityState;\n addEventListener(type: string, listener: EventListener): void;\n removeEventListener(type: string, listener: EventListener): void;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ResourcePath } from '../model/path';\nimport { fail, hardAssert } from '../util/assert';\n\n/**\n * Helpers for dealing with resource paths stored in IndexedDB.\n *\n * Resource paths in their canonical string form do not sort as the server\n * sorts them. Specifically the server splits paths into segments first and then\n * sorts, putting end-of-segment before any character. In a UTF-8 string\n * encoding the slash ('/') that denotes the end-of-segment naturally comes\n * after other characters so the intent here is to encode the path delimiters in\n * such a way that the resulting strings sort naturally.\n *\n * Resource paths are also used for prefix scans so it's important to\n * distinguish whole segments from any longer segments of which they might be a\n * prefix. For example, it's important to make it possible to scan documents in\n * a collection \"foo\" without encountering documents in a collection \"foobar\".\n *\n * Separate from the concerns about resource path ordering and separation,\n * On Android, SQLite imposes additional restrictions since it does not handle\n * keys with embedded NUL bytes particularly well. Rather than change the\n * implementation we keep the encoding identical to keep the ports similar.\n *\n * Taken together this means resource paths when encoded for storage in\n * IndexedDB have the following characteristics:\n *\n * * Segment separators (\"/\") sort before everything else.\n * * All paths have a trailing separator.\n * * NUL bytes do not exist in the output, since IndexedDB doesn't treat them\n * well.\n *\n * Therefore resource paths are encoded into string form using the following\n * rules:\n *\n * * '\\x01' is used as an escape character.\n * * Path separators are encoded as \"\\x01\\x01\"\n * * NUL bytes are encoded as \"\\x01\\x10\"\n * * '\\x01' is encoded as \"\\x01\\x11\"\n *\n * This encoding leaves some room between path separators and the NUL byte\n * just in case we decide to support integer document ids after all.\n *\n * Note that characters treated specially by the backend ('.', '/', and '~')\n * are not treated specially here. This class assumes that any unescaping of\n * resource path strings into actual ResourcePath objects will handle these\n * characters there.\n */\nexport type EncodedResourcePath = string;\n\nconst escapeChar = '\\u0001';\nconst encodedSeparatorChar = '\\u0001';\nconst encodedNul = '\\u0010';\nconst encodedEscape = '\\u0011';\n\n/**\n * Encodes a resource path into a IndexedDb-compatible string form.\n */\nexport function encodeResourcePath(path: ResourcePath): EncodedResourcePath {\n let result = '';\n for (let i = 0; i < path.length; i++) {\n if (result.length > 0) {\n result = encodeSeparator(result);\n }\n result = encodeSegment(path.get(i), result);\n }\n return encodeSeparator(result);\n}\n\n/** Encodes a single segment of a resource path into the given result */\nfunction encodeSegment(segment: string, resultBuf: string): string {\n let result = resultBuf;\n const length = segment.length;\n for (let i = 0; i < length; i++) {\n const c = segment.charAt(i);\n switch (c) {\n case '\\0':\n result += escapeChar + encodedNul;\n break;\n case escapeChar:\n result += escapeChar + encodedEscape;\n break;\n default:\n result += c;\n }\n }\n return result;\n}\n\n/** Encodes a path separator into the given result */\nfunction encodeSeparator(result: string): string {\n return result + escapeChar + encodedSeparatorChar;\n}\n\n/**\n * Decodes the given IndexedDb-compatible string form of a resource path into\n * a ResourcePath instance. Note that this method is not suitable for use with\n * decoding resource names from the server; those are One Platform format\n * strings.\n */\nexport function decodeResourcePath(path: EncodedResourcePath): ResourcePath {\n // Event the empty path must encode as a path of at least length 2. A path\n // with exactly 2 must be the empty path.\n const length = path.length;\n hardAssert(length >= 2, 0xfb98, 'Invalid path', { path });\n if (length === 2) {\n hardAssert(\n path.charAt(0) === escapeChar && path.charAt(1) === encodedSeparatorChar,\n 0xdb51,\n 'Non-empty path had length 2',\n { path }\n );\n return ResourcePath.emptyPath();\n }\n\n // Escape characters cannot exist past the second-to-last position in the\n // source value.\n const lastReasonableEscapeIndex = length - 2;\n\n const segments: string[] = [];\n let segmentBuilder = '';\n\n for (let start = 0; start < length; ) {\n // The last two characters of a valid encoded path must be a separator, so\n // there must be an end to this segment.\n const end = path.indexOf(escapeChar, start);\n if (end < 0 || end > lastReasonableEscapeIndex) {\n fail(0xc553, 'Invalid encoded resource path', { path });\n }\n\n const next = path.charAt(end + 1);\n switch (next) {\n case encodedSeparatorChar:\n const currentPiece = path.substring(start, end);\n let segment;\n if (segmentBuilder.length === 0) {\n // Avoid copying for the common case of a segment that excludes \\0\n // and \\001\n segment = currentPiece;\n } else {\n segmentBuilder += currentPiece;\n segment = segmentBuilder;\n segmentBuilder = '';\n }\n segments.push(segment);\n break;\n case encodedNul:\n segmentBuilder += path.substring(start, end);\n segmentBuilder += '\\0';\n break;\n case encodedEscape:\n // The escape character can be used in the output to encode itself.\n segmentBuilder += path.substring(start, end + 1);\n break;\n default:\n fail(0xeeef, 'Invalid encoded resource path', { path });\n }\n\n start = end + 2;\n }\n\n return new ResourcePath(segments);\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 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 * Representation of a byte array that is safe for\n * use in an IndexedDb key. The value is either\n * a \"sortable byte string\", which is key safe in\n * Safari/WebKit, or the value is a Uint8Array,\n * which is key safe in other browsers.\n */\nexport type KeySafeBytes = Uint8Array | string;\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 KeySafeBytes,\n KeySafeBytes,\n KeySafeBytes,\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];\nexport const V18_STORES = V17_STORES;\n\n/**\n * The list of all default IndexedDB stores used throughout the SDK. This is\n * used when creating transactions so that access across all stores is done\n * atomically.\n */\nexport const ALL_STORES = V12_STORES;\n\n/** Returns the object stores for the provided schema. */\nexport function getObjectStores(schemaVersion: number): string[] {\n if (schemaVersion === 18) {\n return V18_STORES;\n } else 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(0xeb55, 'Only schema versions >11 are supported');\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 { ListenSequenceNumber } from '../core/types';\nimport { debugCast } from '../util/assert';\n\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDb, SimpleDbStore, SimpleDbTransaction } from './simple_db';\n\nexport class IndexedDbTransaction extends PersistenceTransaction {\n constructor(\n readonly simpleDbTransaction: SimpleDbTransaction,\n readonly currentSequenceNumber: ListenSequenceNumber\n ) {\n super();\n }\n}\n\nexport function getStore(\n txn: PersistenceTransaction,\n store: string\n): SimpleDbStore {\n const indexedDbTransaction = debugCast(txn, IndexedDbTransaction);\n return SimpleDb.getStore(\n indexedDbTransaction.simpleDbTransaction,\n store\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from './assert';\n\nexport interface Dict {\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(0xaad2, 'Red node has red child', {\n key: this.key,\n value: this.value\n });\n }\n if (this.right.isRed()) {\n throw fail(0x3721, 'Right child of (`key`, `value`) is red', {\n key: this.key,\n value: this.value\n });\n }\n const blackDepth = (this.left as LLRBNode).check();\n if (blackDepth !== (this.right as LLRBNode).check()) {\n throw fail(0x6d2d, '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(0xe1a6, 'LLRBEmptyNode has no key.');\n }\n get value(): never {\n throw fail(0x3f0d, 'LLRBEmptyNode has no value.');\n }\n get color(): never {\n throw fail(0x4157, 'LLRBEmptyNode has no color.');\n }\n get left(): never {\n throw fail(0x741e, 'LLRBEmptyNode has no left child.');\n }\n get right(): never {\n throw fail(0x901e, '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 { 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 { 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 { 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, 0x986a, '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, 0xb5de, 'invalid timestamp', {\n timestamp: date\n });\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 readonly isUsingEmulator: 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 {\n arrayEquals,\n compareUtf8Strings,\n primitiveComparator\n} 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(0x6e87, 'Invalid value type', { 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(0xcbf8, 'Unexpected value type', { 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 compareUtf8Strings(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(0x5ae0, '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 = compareUtf8Strings(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(0xee4d, 'Invalid value type', { 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(0x34ae, 'Invalid value type', { 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(0x8c66, 'Invalid value type', { 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(0xf207, 'Invalid value type', { 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(\n 0xa786,\n \"Trying to compare documents on fields that don't exist\"\n );\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 other.nullValue === undefined &&\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(0xb8a2, 'Unknown FieldFilter operator', {\n operator: this.op\n });\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(0x4bef, '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 (\n other !== null &&\n other.nullValue === undefined &&\n !arrayValueContains(this.value.arrayValue!, other)\n );\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(0x4d4e, 'Unknown direction', { 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 0x7f90,\n 'server transform result count should match field transform count',\n {\n serverTransformResultCount: serverTransformResults.length,\n fieldTransformCount: fieldTransforms.length\n }\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 0xe5da,\n 'Mutations sent must equal results received',\n {\n mutationsSent: batch.mutations.length,\n resultsReceived: results.length\n }\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 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 { FieldPath } from '../model/path';\n\n/**\n * Union type representing the aggregate type to be performed.\n */\nexport type AggregateType = 'count' | 'avg' | 'sum';\n\n/**\n * Represents an Aggregate to be performed over a query result set.\n */\nexport interface Aggregate {\n readonly fieldPath?: FieldPath;\n readonly alias: string;\n readonly aggregateType: AggregateType;\n}\n\n/**\n * Concrete implementation of the Aggregate type.\n */\nexport class AggregateImpl implements Aggregate {\n constructor(\n readonly alias: string,\n readonly aggregateType: AggregateType,\n readonly fieldPath?: 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 { 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(0xfdaa, '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(0x3c6b, '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(0x999b, '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(0x3019, '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(0x9481, '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 0x0ca9,\n '`pendingResponses` is less than 0. This indicates that the SDK received more target acks from the server than expected. The SDK should not continue to operate.',\n { pendingResponses: this.pendingResponses }\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 private pendingDocumentUpdatesByTarget = documentTargetMap();\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(0xddd6, 'Unknown target watch change state', {\n state: targetChange.state\n });\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 0x4e2d,\n 'Single document existence filter with count',\n { 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 for this\n // target. This resolves the limbo state of the document, removing it\n // from 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.ensureDocumentUpdateByTarget(key).has(targetId) &&\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.pendingDocumentUpdatesByTarget = documentTargetMap();\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.pendingDocumentUpdatesByTarget =\n this.pendingDocumentUpdatesByTarget.insert(\n document.key,\n this.ensureDocumentUpdateByTarget(document.key).add(targetId)\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 this.pendingDocumentTargetMapping =\n this.pendingDocumentTargetMapping.insert(\n key,\n this.ensureDocumentTargetMapping(key).add(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 private ensureDocumentUpdateByTarget(key: DocumentKey): SortedSet {\n let targetMapping = this.pendingDocumentUpdatesByTarget.get(key);\n\n if (!targetMapping) {\n targetMapping = new SortedSet(primitiveComparator);\n this.pendingDocumentUpdatesByTarget =\n this.pendingDocumentUpdatesByTarget.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\n/**\n * Returns a Timestamp typed object given protobuf timestamp value.\n */\nexport function 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 0xe30b,\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 0x3f41,\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, 0xc050, \"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 0x27ce,\n 'Tried to deserialize invalid key',\n { 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 0x71a3,\n 'tried to deserialize invalid key',\n { 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 0xaa33,\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 0x0f36,\n 'Tried to deserialize a missing document from a found document.'\n );\n hardAssert(\n !!result.readTime,\n 0x5995,\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(0x1c42, 'invalid batch get response', { 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(0x2d51, 'Unknown change type', { 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(0x9991, '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(0x40d7, 'Unknown mutation type', {\n mutationType: mutation.type\n });\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(0x05b7, 'unknown mutation proto', { 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(0x6b69, '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 0x3811,\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(0x51c2, 'Unknown transform', {\n transform: fieldTransform.transform\n });\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 0x40f6,\n 'Unknown server value transform proto',\n { 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(0x40c8, 'Unknown transform proto', { 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 0x07ae,\n 'DocumentsTarget contained other than 1 document',\n {\n count\n }\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 0xfe26,\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(0x713b, '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(0x7591, 'Unknown filter', { 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(0xe2fe, 'Unspecified operator');\n default:\n return fail(0xc54a, '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(0x0402, '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(0xd65d, 'Unrecognized filter type', { 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(0xef81, 'Unspecified filter');\n default:\n return fail(0xed36, '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(0xdd85, '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(0xe230, 'Unexpected Document', { document });\n }\n return remoteDoc;\n}\n\nexport function toDbTimestampKey(\n snapshotVersion: SnapshotVersion\n): DbTimestampKey {\n const timestamp = snapshotVersion.toTimestamp();\n return [timestamp.seconds, timestamp.nanoseconds];\n}\n\nexport function fromDbTimestampKey(\n dbTimestampKey: DbTimestampKey\n): SnapshotVersion {\n const timestamp = new Timestamp(dbTimestampKey[0], dbTimestampKey[1]);\n return SnapshotVersion.fromTimestamp(timestamp);\n}\n\nexport function toDbTimestamp(snapshotVersion: SnapshotVersion): DbTimestamp {\n const timestamp = snapshotVersion.toTimestamp();\n return { seconds: timestamp.seconds, nanoseconds: timestamp.nanoseconds };\n}\n\nfunction fromDbTimestamp(dbTimestamp: DbTimestamp): SnapshotVersion {\n const timestamp = new Timestamp(dbTimestamp.seconds, dbTimestamp.nanoseconds);\n return SnapshotVersion.fromTimestamp(timestamp);\n}\n\n/** Encodes a batch of mutations into a DbMutationBatch for local storage. */\nexport function toDbMutationBatch(\n localSerializer: LocalSerializer,\n userId: string,\n batch: MutationBatch\n): DbMutationBatch {\n const serializedBaseMutations = batch.baseMutations.map(m =>\n toMutation(localSerializer.remoteSerializer, m)\n );\n const serializedMutations = batch.mutations.map(m =>\n toMutation(localSerializer.remoteSerializer, m)\n );\n return {\n userId,\n batchId: batch.batchId,\n localWriteTimeMs: batch.localWriteTime.toMillis(),\n baseMutations: serializedBaseMutations,\n mutations: serializedMutations\n };\n}\n\n/** Decodes a DbMutationBatch into a MutationBatch */\nexport function fromDbMutationBatch(\n localSerializer: LocalSerializer,\n dbBatch: DbMutationBatch\n): MutationBatch {\n const baseMutations = (dbBatch.baseMutations || []).map(m =>\n fromMutation(localSerializer.remoteSerializer, m)\n );\n\n // Squash old transform mutations into existing patch or set mutations.\n // The replacement of representing `transforms` with `update_transforms`\n // on the SDK means that old `transform` mutations stored in IndexedDB need\n // to be updated to `update_transforms`.\n // TODO(b/174608374): Remove this code once we perform a schema migration.\n for (let i = 0; i < dbBatch.mutations.length - 1; ++i) {\n const currentMutation = dbBatch.mutations[i];\n const hasTransform =\n i + 1 < dbBatch.mutations.length &&\n dbBatch.mutations[i + 1].transform !== undefined;\n if (hasTransform) {\n debugAssert(\n dbBatch.mutations[i].transform === undefined &&\n dbBatch.mutations[i].update !== undefined,\n 'TransformMutation should be preceded by a patch or set mutation'\n );\n const transformMutation = dbBatch.mutations[i + 1];\n currentMutation.updateTransforms =\n transformMutation.transform!.fieldTransforms;\n dbBatch.mutations.splice(i + 1, 1);\n ++i;\n }\n }\n\n const mutations = dbBatch.mutations.map(m =>\n fromMutation(localSerializer.remoteSerializer, m)\n );\n const timestamp = Timestamp.fromMillis(dbBatch.localWriteTimeMs);\n return new MutationBatch(\n dbBatch.batchId,\n timestamp,\n baseMutations,\n mutations\n );\n}\n\n/** Decodes a DbTarget into TargetData */\nexport function fromDbTarget(dbTarget: DbTarget): TargetData {\n const version = fromDbTimestamp(dbTarget.readTime);\n const lastLimboFreeSnapshotVersion =\n dbTarget.lastLimboFreeSnapshotVersion !== undefined\n ? fromDbTimestamp(dbTarget.lastLimboFreeSnapshotVersion)\n : SnapshotVersion.min();\n\n let target: Target;\n if (isDocumentQuery(dbTarget.query)) {\n target = fromDocumentsTarget(dbTarget.query);\n } else {\n target = fromQueryTarget(dbTarget.query);\n }\n return new TargetData(\n target,\n dbTarget.targetId,\n TargetPurpose.Listen,\n dbTarget.lastListenSequenceNumber,\n version,\n lastLimboFreeSnapshotVersion,\n ByteString.fromBase64String(dbTarget.resumeToken)\n );\n}\n\n/** Encodes TargetData into a DbTarget for storage locally. */\nexport function toDbTarget(\n localSerializer: LocalSerializer,\n targetData: TargetData\n): DbTarget {\n debugAssert(\n TargetPurpose.Listen === targetData.purpose,\n 'Only queries with purpose ' +\n TargetPurpose.Listen +\n ' may be stored, got ' +\n targetData.purpose\n );\n const dbTimestamp = toDbTimestamp(targetData.snapshotVersion);\n const dbLastLimboFreeTimestamp = toDbTimestamp(\n targetData.lastLimboFreeSnapshotVersion\n );\n let queryProto: DbQuery;\n if (targetIsDocumentTarget(targetData.target)) {\n queryProto = toDocumentsTarget(\n localSerializer.remoteSerializer,\n targetData.target\n );\n } else {\n queryProto = toQueryTarget(\n localSerializer.remoteSerializer,\n targetData.target\n ).queryTarget;\n }\n\n // We can't store the resumeToken as a ByteString in IndexedDb, so we\n // convert it to a base64 string for storage.\n const resumeToken = targetData.resumeToken.toBase64();\n\n // lastListenSequenceNumber is always 0 until we do real GC.\n return {\n targetId: targetData.targetId,\n canonicalId: canonifyTarget(targetData.target),\n readTime: dbTimestamp,\n resumeToken,\n lastListenSequenceNumber: targetData.sequenceNumber,\n lastLimboFreeSnapshotVersion: dbLastLimboFreeTimestamp,\n query: queryProto\n };\n}\n\n/**\n * A helper function for figuring out what kind of query has been stored.\n */\nfunction isDocumentQuery(dbQuery: DbQuery): dbQuery is PublicDocumentsTarget {\n return (dbQuery as PublicDocumentsTarget).documents !== undefined;\n}\n\n/** Encodes a DbBundle to a BundleMetadata object. */\nexport function fromDbBundle(dbBundle: DbBundle): BundleMetadata {\n return {\n id: dbBundle.bundleId,\n createTime: fromDbTimestamp(dbBundle.createTime),\n version: dbBundle.version\n };\n}\n\n/** Encodes a BundleMetadata to a DbBundle. */\nexport function toDbBundle(metadata: ProtoBundleMetadata): DbBundle {\n return {\n bundleId: metadata.id!,\n createTime: toDbTimestamp(fromVersion(metadata.createTime!)),\n version: metadata.version!\n };\n}\n\n/** Encodes a DbNamedQuery to a NamedQuery. */\nexport function fromDbNamedQuery(dbNamedQuery: DbNamedQuery): NamedQuery {\n return {\n name: dbNamedQuery.name,\n query: fromBundledQuery(dbNamedQuery.bundledQuery),\n readTime: fromDbTimestamp(dbNamedQuery.readTime)\n };\n}\n\n/** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */\nexport function toDbNamedQuery(query: ProtoNamedQuery): DbNamedQuery {\n return {\n name: query.name!,\n readTime: toDbTimestamp(fromVersion(query.readTime!)),\n bundledQuery: query.bundledQuery!\n };\n}\n\n/**\n * Encodes a `BundledQuery` from bundle proto to a Query object.\n *\n * This reconstructs the original query used to build the bundle being loaded,\n * including features exists only in SDKs (for example: limit-to-last).\n */\nexport function fromBundledQuery(bundledQuery: ProtoBundledQuery): Query {\n const query = convertQueryTargetToQuery({\n parent: bundledQuery.parent!,\n structuredQuery: bundledQuery.structuredQuery!\n });\n if (bundledQuery.limitType === 'LAST') {\n debugAssert(\n !!query.limit,\n 'Bundled query has limitType LAST, but limit is null'\n );\n return queryWithLimit(query, query.limit, LimitType.Last);\n }\n return query;\n}\n\n/** Encodes a NamedQuery proto object to a NamedQuery model object. */\nexport function fromProtoNamedQuery(namedQuery: ProtoNamedQuery): NamedQuery {\n return {\n name: namedQuery.name!,\n query: fromBundledQuery(namedQuery.bundledQuery!),\n readTime: fromVersion(namedQuery.readTime!)\n };\n}\n\n/** Decodes a BundleMetadata proto into a BundleMetadata object. */\nexport function fromBundleMetadata(\n metadata: ProtoBundleMetadata\n): BundleMetadata {\n return {\n id: metadata.id!,\n version: metadata.version!,\n createTime: fromVersion(metadata.createTime!)\n };\n}\n\n/** Encodes a DbDocumentOverlay object to an Overlay model object. */\nexport function fromDbDocumentOverlay(\n localSerializer: LocalSerializer,\n dbDocumentOverlay: DbDocumentOverlay\n): Overlay {\n return new Overlay(\n dbDocumentOverlay.largestBatchId,\n fromMutation(\n localSerializer.remoteSerializer,\n dbDocumentOverlay.overlayMutation\n )\n );\n}\n\n/** Decodes an Overlay model object into a DbDocumentOverlay object. */\nexport function toDbDocumentOverlay(\n localSerializer: LocalSerializer,\n userId: string,\n overlay: Overlay\n): DbDocumentOverlay {\n const [_, collectionPath, documentId] = toDbDocumentOverlayKey(\n userId,\n overlay.mutation.key\n );\n return {\n userId,\n collectionPath,\n documentId,\n collectionGroup: overlay.mutation.key.getCollectionGroup(),\n largestBatchId: overlay.largestBatchId,\n overlayMutation: toMutation(\n localSerializer.remoteSerializer,\n overlay.mutation\n )\n };\n}\n\n/**\n * Returns the DbDocumentOverlayKey corresponding to the given user and\n * document key.\n */\nexport function toDbDocumentOverlayKey(\n userId: string,\n docKey: DocumentKey\n): DbDocumentOverlayKey {\n const docId = docKey.path.lastSegment();\n const collectionPath = encodeResourcePath(docKey.path.popLast());\n return [userId, collectionPath, docId];\n}\n\nexport function toDbIndexConfiguration(\n index: FieldIndex\n): DbIndexConfiguration {\n return {\n indexId: index.indexId,\n collectionGroup: index.collectionGroup,\n fields: index.fields.map(s => [s.fieldPath.canonicalString(), s.kind])\n };\n}\n\nexport function fromDbIndexConfiguration(\n index: DbIndexConfiguration,\n state: DbIndexState | null\n): FieldIndex {\n const decodedState = state\n ? new IndexState(\n state.sequenceNumber,\n new IndexOffset(\n fromDbTimestamp(state.readTime),\n new DocumentKey(decodeResourcePath(state.documentKey)),\n state.largestBatchId\n )\n )\n : IndexState.empty();\n const decodedSegments = index.fields.map(\n ([fieldPath, kind]) =>\n new IndexSegment(FieldPath.fromServerFormat(fieldPath), kind)\n );\n return new FieldIndex(\n index.indexId!,\n index.collectionGroup,\n decodedSegments,\n decodedState\n );\n}\n\nexport function toDbIndexState(\n indexId: number,\n uid: string,\n sequenceNumber: number,\n offset: IndexOffset\n): DbIndexState {\n return {\n indexId,\n uid,\n sequenceNumber,\n readTime: toDbTimestamp(offset.readTime),\n documentKey: encodeResourcePath(offset.documentKey.path),\n largestBatchId: offset.largestBatchId\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BundleMetadata, NamedQuery } from '../core/bundle';\nimport {\n BundleMetadata as ProtoBundleMetadata,\n NamedQuery as ProtoNamedQuery\n} from '../protos/firestore_bundle_proto';\n\nimport { BundleCache } from './bundle_cache';\nimport { DbBundle, DbNamedQuery } from './indexeddb_schema';\nimport {\n DbBundlesKey,\n DbBundleStore,\n DbNamedQueriesKey,\n DbNamedQueryStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n fromDbBundle,\n fromDbNamedQuery,\n toDbBundle,\n toDbNamedQuery\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\nexport class IndexedDbBundleCache implements BundleCache {\n getBundleMetadata(\n transaction: PersistenceTransaction,\n bundleId: string\n ): PersistencePromise {\n return bundlesStore(transaction)\n .get(bundleId)\n .next(bundle => {\n if (bundle) {\n return fromDbBundle(bundle);\n }\n return undefined;\n });\n }\n\n saveBundleMetadata(\n transaction: PersistenceTransaction,\n bundleMetadata: ProtoBundleMetadata\n ): PersistencePromise {\n return bundlesStore(transaction).put(toDbBundle(bundleMetadata));\n }\n\n getNamedQuery(\n transaction: PersistenceTransaction,\n queryName: string\n ): PersistencePromise {\n return namedQueriesStore(transaction)\n .get(queryName)\n .next(query => {\n if (query) {\n return fromDbNamedQuery(query);\n }\n return undefined;\n });\n }\n\n saveNamedQuery(\n transaction: PersistenceTransaction,\n query: ProtoNamedQuery\n ): PersistencePromise {\n return namedQueriesStore(transaction).put(toDbNamedQuery(query));\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the bundles object store.\n */\nfunction bundlesStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbBundleStore);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the namedQueries object store.\n */\nfunction namedQueriesStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbNamedQueryStore);\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport {\n DocumentKeySet,\n MutationMap,\n OverlayMap,\n newOverlayMap\n} from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { Overlay } from '../model/overlay';\nimport { ResourcePath } from '../model/path';\n\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { encodeResourcePath } from './encoded_resource_path';\nimport { DbDocumentOverlay } from './indexeddb_schema';\nimport {\n DbDocumentOverlayCollectionGroupOverlayIndex,\n DbDocumentOverlayCollectionPathOverlayIndex,\n DbDocumentOverlayKey,\n DbDocumentOverlayStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n fromDbDocumentOverlay,\n LocalSerializer,\n toDbDocumentOverlay,\n toDbDocumentOverlayKey\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\n/**\n * Implementation of DocumentOverlayCache using IndexedDb.\n */\nexport class IndexedDbDocumentOverlayCache implements DocumentOverlayCache {\n /**\n * @param serializer - The document serializer.\n * @param userId - The userId for which we are accessing overlays.\n */\n constructor(\n private readonly serializer: LocalSerializer,\n private readonly userId: string\n ) {}\n\n static forUser(\n serializer: LocalSerializer,\n user: User\n ): IndexedDbDocumentOverlayCache {\n const userId = user.uid || '';\n return new IndexedDbDocumentOverlayCache(serializer, userId);\n }\n\n getOverlay(\n transaction: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return documentOverlayStore(transaction)\n .get(toDbDocumentOverlayKey(this.userId, key))\n .next(dbOverlay => {\n if (dbOverlay) {\n return fromDbDocumentOverlay(this.serializer, dbOverlay);\n }\n return null;\n });\n }\n\n getOverlays(\n transaction: PersistenceTransaction,\n keys: DocumentKey[]\n ): PersistencePromise {\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 const promises: Array> = [];\n overlays.forEach((_, mutation) => {\n const overlay = new Overlay(largestBatchId, mutation);\n promises.push(this.saveOverlay(transaction, overlay));\n });\n return PersistencePromise.waitFor(promises);\n }\n\n removeOverlaysForBatchId(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet,\n batchId: number\n ): PersistencePromise {\n const collectionPaths = new Set();\n\n // Get the set of unique collection paths.\n documentKeys.forEach(key =>\n collectionPaths.add(encodeResourcePath(key.getCollectionPath()))\n );\n\n const promises: Array> = [];\n collectionPaths.forEach(collectionPath => {\n const range = IDBKeyRange.bound(\n [this.userId, collectionPath, batchId],\n [this.userId, collectionPath, batchId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n promises.push(\n documentOverlayStore(transaction).deleteAll(\n DbDocumentOverlayCollectionPathOverlayIndex,\n range\n )\n );\n });\n return PersistencePromise.waitFor(promises);\n }\n\n getOverlaysForCollection(\n transaction: PersistenceTransaction,\n collection: ResourcePath,\n sinceBatchId: number\n ): PersistencePromise {\n const result = newOverlayMap();\n const collectionPath = encodeResourcePath(collection);\n // We want batch IDs larger than `sinceBatchId`, and so the lower bound\n // is not inclusive.\n const range = IDBKeyRange.bound(\n [this.userId, collectionPath, sinceBatchId],\n [this.userId, collectionPath, Number.POSITIVE_INFINITY],\n /*lowerOpen=*/ true\n );\n return documentOverlayStore(transaction)\n .loadAll(DbDocumentOverlayCollectionPathOverlayIndex, range)\n .next(dbOverlays => {\n for (const dbOverlay of dbOverlays) {\n const overlay = fromDbDocumentOverlay(this.serializer, dbOverlay);\n result.set(overlay.getKey(), overlay);\n }\n return result;\n });\n }\n\n getOverlaysForCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n sinceBatchId: number,\n count: number\n ): PersistencePromise {\n const result = newOverlayMap();\n let currentBatchId: number | undefined = undefined;\n // We want batch IDs larger than `sinceBatchId`, and so the lower bound\n // is not inclusive.\n const range = IDBKeyRange.bound(\n [this.userId, collectionGroup, sinceBatchId],\n [this.userId, collectionGroup, Number.POSITIVE_INFINITY],\n /*lowerOpen=*/ true\n );\n return documentOverlayStore(transaction)\n .iterate(\n {\n index: DbDocumentOverlayCollectionGroupOverlayIndex,\n range\n },\n (_, dbOverlay, control) => {\n // We do not want to return partial batch overlays, even if the size\n // of the result set exceeds the given `count` argument. Therefore, we\n // continue to aggregate results even after the result size exceeds\n // `count` if there are more overlays from the `currentBatchId`.\n const overlay = fromDbDocumentOverlay(this.serializer, dbOverlay);\n if (\n result.size() < count ||\n overlay.largestBatchId === currentBatchId\n ) {\n result.set(overlay.getKey(), overlay);\n currentBatchId = overlay.largestBatchId;\n } else {\n control.done();\n }\n }\n )\n .next(() => result);\n }\n\n private saveOverlay(\n transaction: PersistenceTransaction,\n overlay: Overlay\n ): PersistencePromise {\n return documentOverlayStore(transaction).put(\n toDbDocumentOverlay(this.serializer, this.userId, overlay)\n );\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document overlay object store.\n */\nfunction documentOverlayStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbDocumentOverlayStore\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 { DbGlobals } from './indexeddb_schema';\nimport { DbGlobalsStore, DbGlobalsKey } from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\nexport class IndexedDbGlobalsCache implements GlobalsCache {\n private globalsStore(\n txn: PersistenceTransaction\n ): SimpleDbStore {\n return getStore(txn, DbGlobalsStore);\n }\n\n getSessionToken(txn: PersistenceTransaction): PersistencePromise {\n const globals = this.globalsStore(txn);\n return globals.get('sessionToken').next(global => {\n const value = global?.value;\n return value\n ? ByteString.fromUint8Array(value)\n : ByteString.EMPTY_BYTE_STRING;\n });\n }\n\n setSessionToken(\n txn: PersistenceTransaction,\n sessionToken: ByteString\n ): PersistencePromise {\n const globals = this.globalsStore(txn);\n return globals.put({\n name: 'sessionToken',\n value: sessionToken.toUint8Array()\n });\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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(0x4a4e, '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 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law | agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES | CONDITIONS OF ANY KIND, either express | implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { debugAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\n\n/** These constants are taken from the backend. */\nconst MIN_SURROGATE = '\\uD800';\nconst MAX_SURROGATE = '\\uDBFF';\n\nconst ESCAPE1 = 0x00;\nconst NULL_BYTE = 0xff; // Combined with ESCAPE1\nconst SEPARATOR = 0x01; // Combined with ESCAPE1\n\nconst ESCAPE2 = 0xff;\nconst INFINITY = 0xff; // Combined with ESCAPE2\nconst FF_BYTE = 0x00; // Combined with ESCAPE2\n\nconst LONG_SIZE = 64;\nconst BYTE_SIZE = 8;\n\n/**\n * The default size of the buffer. This is arbitrary, but likely larger than\n * most index values so that less copies of the underlying buffer will be made.\n * For large values, a single copy will made to double the buffer length.\n */\nconst DEFAULT_BUFFER_SIZE = 1024;\n\n/** Converts a JavaScript number to a byte array (using big endian encoding). */\nfunction doubleToLongBits(value: number): Uint8Array {\n const dv = new DataView(new ArrayBuffer(8));\n dv.setFloat64(0, value, /* littleEndian= */ false);\n return new Uint8Array(dv.buffer);\n}\n\n/**\n * Counts the number of zeros in a byte.\n *\n * Visible for testing.\n */\nexport function numberOfLeadingZerosInByte(x: number): number {\n debugAssert(x < 256, 'Provided value is not a byte: ' + x);\n if (x === 0) {\n return 8;\n }\n\n let zeros = 0;\n if (x >> 4 === 0) {\n // Test if the first four bits are zero.\n zeros += 4;\n x = x << 4;\n }\n if (x >> 6 === 0) {\n // Test if the first two (or next two) bits are zero.\n zeros += 2;\n x = x << 2;\n }\n if (x >> 7 === 0) {\n // Test if the remaining bit is zero.\n zeros += 1;\n }\n return zeros;\n}\n\n/** Counts the number of leading zeros in the given byte array. */\nfunction numberOfLeadingZeros(bytes: Uint8Array): number {\n debugAssert(\n bytes.length === 8,\n 'Can only count leading zeros in 64-bit numbers'\n );\n let leadingZeros = 0;\n for (let i = 0; i < 8; ++i) {\n const zeros = numberOfLeadingZerosInByte(bytes[i] & 0xff);\n leadingZeros += zeros;\n if (zeros !== 8) {\n break;\n }\n }\n return leadingZeros;\n}\n\n/**\n * Returns the number of bytes required to store \"value\". Leading zero bytes\n * are skipped.\n */\nfunction unsignedNumLength(value: Uint8Array): number {\n // This is just the number of bytes for the unsigned representation of the number.\n const numBits = LONG_SIZE - numberOfLeadingZeros(value);\n return Math.ceil(numBits / BYTE_SIZE);\n}\n\n/**\n * OrderedCodeWriter is a minimal-allocation implementation of the writing\n * behavior defined by the backend.\n *\n * The code is ported from its Java counterpart.\n */\nexport class OrderedCodeWriter {\n buffer = new Uint8Array(DEFAULT_BUFFER_SIZE);\n position = 0;\n\n writeBytesAscending(value: ByteString): void {\n const it = value[Symbol.iterator]();\n let byte = it.next();\n while (!byte.done) {\n this.writeByteAscending(byte.value);\n byte = it.next();\n }\n this.writeSeparatorAscending();\n }\n\n writeBytesDescending(value: ByteString): void {\n const it = value[Symbol.iterator]();\n let byte = it.next();\n while (!byte.done) {\n this.writeByteDescending(byte.value);\n byte = it.next();\n }\n this.writeSeparatorDescending();\n }\n\n /** Writes utf8 bytes into this byte sequence, ascending. */\n writeUtf8Ascending(sequence: string): void {\n for (const c of sequence) {\n const charCode = c.charCodeAt(0);\n if (charCode < 0x80) {\n this.writeByteAscending(charCode);\n } else if (charCode < 0x800) {\n this.writeByteAscending((0x0f << 6) | (charCode >>> 6));\n this.writeByteAscending(0x80 | (0x3f & charCode));\n } else if (c < MIN_SURROGATE || MAX_SURROGATE < c) {\n this.writeByteAscending((0x0f << 5) | (charCode >>> 12));\n this.writeByteAscending(0x80 | (0x3f & (charCode >>> 6)));\n this.writeByteAscending(0x80 | (0x3f & charCode));\n } else {\n const codePoint = c.codePointAt(0)!;\n this.writeByteAscending((0x0f << 4) | (codePoint >>> 18));\n this.writeByteAscending(0x80 | (0x3f & (codePoint >>> 12)));\n this.writeByteAscending(0x80 | (0x3f & (codePoint >>> 6)));\n this.writeByteAscending(0x80 | (0x3f & codePoint));\n }\n }\n this.writeSeparatorAscending();\n }\n\n /** Writes utf8 bytes into this byte sequence, descending */\n writeUtf8Descending(sequence: string): void {\n for (const c of sequence) {\n const charCode = c.charCodeAt(0);\n if (charCode < 0x80) {\n this.writeByteDescending(charCode);\n } else if (charCode < 0x800) {\n this.writeByteDescending((0x0f << 6) | (charCode >>> 6));\n this.writeByteDescending(0x80 | (0x3f & charCode));\n } else if (c < MIN_SURROGATE || MAX_SURROGATE < c) {\n this.writeByteDescending((0x0f << 5) | (charCode >>> 12));\n this.writeByteDescending(0x80 | (0x3f & (charCode >>> 6)));\n this.writeByteDescending(0x80 | (0x3f & charCode));\n } else {\n const codePoint = c.codePointAt(0)!;\n this.writeByteDescending((0x0f << 4) | (codePoint >>> 18));\n this.writeByteDescending(0x80 | (0x3f & (codePoint >>> 12)));\n this.writeByteDescending(0x80 | (0x3f & (codePoint >>> 6)));\n this.writeByteDescending(0x80 | (0x3f & codePoint));\n }\n }\n this.writeSeparatorDescending();\n }\n\n writeNumberAscending(val: number): void {\n // Values are encoded with a single byte length prefix, followed by the\n // actual value in big-endian format with leading 0 bytes dropped.\n const value = this.toOrderedBits(val);\n const len = unsignedNumLength(value);\n this.ensureAvailable(1 + len);\n this.buffer[this.position++] = len & 0xff; // Write the length\n for (let i = value.length - len; i < value.length; ++i) {\n this.buffer[this.position++] = value[i] & 0xff;\n }\n }\n\n writeNumberDescending(val: number): void {\n // Values are encoded with a single byte length prefix, followed by the\n // inverted value in big-endian format with leading 0 bytes dropped.\n const value = this.toOrderedBits(val);\n const len = unsignedNumLength(value);\n this.ensureAvailable(1 + len);\n this.buffer[this.position++] = ~(len & 0xff); // Write the length\n for (let i = value.length - len; i < value.length; ++i) {\n this.buffer[this.position++] = ~(value[i] & 0xff);\n }\n }\n\n /**\n * Writes the \"infinity\" byte sequence that sorts after all other byte\n * sequences written in ascending order.\n */\n writeInfinityAscending(): void {\n this.writeEscapedByteAscending(ESCAPE2);\n this.writeEscapedByteAscending(INFINITY);\n }\n\n /**\n * Writes the \"infinity\" byte sequence that sorts before all other byte\n * sequences written in descending order.\n */\n writeInfinityDescending(): void {\n this.writeEscapedByteDescending(ESCAPE2);\n this.writeEscapedByteDescending(INFINITY);\n }\n\n /**\n * Resets the buffer such that it is the same as when it was newly\n * constructed.\n */\n reset(): void {\n this.position = 0;\n }\n\n seed(encodedBytes: Uint8Array): void {\n this.ensureAvailable(encodedBytes.length);\n this.buffer.set(encodedBytes, this.position);\n this.position += encodedBytes.length;\n }\n\n /** Makes a copy of the encoded bytes in this buffer. */\n encodedBytes(): Uint8Array {\n return this.buffer.slice(0, this.position);\n }\n\n /**\n * Encodes `val` into an encoding so that the order matches the IEEE 754\n * floating-point comparison results with the following exceptions:\n * -0.0 < 0.0\n * all non-NaN < NaN\n * NaN = NaN\n */\n private toOrderedBits(val: number): Uint8Array {\n const value = doubleToLongBits(val);\n // Check if the first bit is set. We use a bit mask since value[0] is\n // encoded as a number from 0 to 255.\n const isNegative = (value[0] & 0x80) !== 0;\n\n // Revert the two complement to get natural ordering\n value[0] ^= isNegative ? 0xff : 0x80;\n for (let i = 1; i < value.length; ++i) {\n value[i] ^= isNegative ? 0xff : 0x00;\n }\n return value;\n }\n\n /** Writes a single byte ascending to the buffer. */\n private writeByteAscending(b: number): void {\n const masked = b & 0xff;\n if (masked === ESCAPE1) {\n this.writeEscapedByteAscending(ESCAPE1);\n this.writeEscapedByteAscending(NULL_BYTE);\n } else if (masked === ESCAPE2) {\n this.writeEscapedByteAscending(ESCAPE2);\n this.writeEscapedByteAscending(FF_BYTE);\n } else {\n this.writeEscapedByteAscending(masked);\n }\n }\n\n /** Writes a single byte descending to the buffer. */\n private writeByteDescending(b: number): void {\n const masked = b & 0xff;\n if (masked === ESCAPE1) {\n this.writeEscapedByteDescending(ESCAPE1);\n this.writeEscapedByteDescending(NULL_BYTE);\n } else if (masked === ESCAPE2) {\n this.writeEscapedByteDescending(ESCAPE2);\n this.writeEscapedByteDescending(FF_BYTE);\n } else {\n this.writeEscapedByteDescending(b);\n }\n }\n\n private writeSeparatorAscending(): void {\n this.writeEscapedByteAscending(ESCAPE1);\n this.writeEscapedByteAscending(SEPARATOR);\n }\n\n private writeSeparatorDescending(): void {\n this.writeEscapedByteDescending(ESCAPE1);\n this.writeEscapedByteDescending(SEPARATOR);\n }\n\n private writeEscapedByteAscending(b: number): void {\n this.ensureAvailable(1);\n this.buffer[this.position++] = b;\n }\n\n private writeEscapedByteDescending(b: number): void {\n this.ensureAvailable(1);\n this.buffer[this.position++] = ~b;\n }\n\n private ensureAvailable(bytes: number): void {\n const minCapacity = bytes + this.position;\n if (minCapacity <= this.buffer.length) {\n return;\n }\n // Try doubling.\n let newLength = this.buffer.length * 2;\n // Still not big enough? Just allocate the right size.\n if (newLength < minCapacity) {\n newLength = minCapacity;\n }\n // Create the new buffer.\n const newBuffer = new Uint8Array(newLength);\n newBuffer.set(this.buffer); // copy old data\n this.buffer = newBuffer;\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { IndexKind } from '../model/field_index';\nimport { ByteString } from '../util/byte_string';\n\nimport { DirectionalIndexByteEncoder } from './directional_index_byte_encoder';\nimport { OrderedCodeWriter } from './ordered_code_writer';\n\nclass AscendingIndexByteEncoder implements DirectionalIndexByteEncoder {\n constructor(private orderedCode: OrderedCodeWriter) {}\n writeBytes(value: ByteString): void {\n this.orderedCode.writeBytesAscending(value);\n }\n\n writeString(value: string): void {\n this.orderedCode.writeUtf8Ascending(value);\n }\n\n writeNumber(value: number): void {\n this.orderedCode.writeNumberAscending(value);\n }\n\n writeInfinity(): void {\n this.orderedCode.writeInfinityAscending();\n }\n}\n\nclass DescendingIndexByteEncoder implements DirectionalIndexByteEncoder {\n constructor(private orderedCode: OrderedCodeWriter) {}\n writeBytes(value: ByteString): void {\n this.orderedCode.writeBytesDescending(value);\n }\n\n writeString(value: string): void {\n this.orderedCode.writeUtf8Descending(value);\n }\n\n writeNumber(value: number): void {\n this.orderedCode.writeNumberDescending(value);\n }\n\n writeInfinity(): void {\n this.orderedCode.writeInfinityDescending();\n }\n}\n/**\n * Implements `DirectionalIndexByteEncoder` using `OrderedCodeWriter` for the\n * actual encoding.\n */\nexport class IndexByteEncoder {\n private orderedCode = new OrderedCodeWriter();\n private ascending = new AscendingIndexByteEncoder(this.orderedCode);\n private descending = new DescendingIndexByteEncoder(this.orderedCode);\n\n seed(encodedBytes: Uint8Array): void {\n this.orderedCode.seed(encodedBytes);\n }\n\n forKind(kind: IndexKind): DirectionalIndexByteEncoder {\n return kind === IndexKind.ASCENDING ? this.ascending : this.descending;\n }\n\n encodedBytes(): Uint8Array {\n return this.orderedCode.encodedBytes();\n }\n\n reset(): void {\n this.orderedCode.reset();\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isSafariOrWebkit } from '@firebase/util';\n\nimport { DbIndexEntry } from '../local/indexeddb_schema';\nimport { DbIndexEntryKey, KeySafeBytes } from '../local/indexeddb_sentinels';\nimport { DocumentKey } from '../model/document_key';\n\n/** Represents an index entry saved by the SDK in persisted storage. */\nexport class IndexEntry {\n constructor(\n readonly _indexId: number,\n readonly _documentKey: DocumentKey,\n readonly _arrayValue: Uint8Array,\n readonly _directionalValue: Uint8Array\n ) {}\n\n /**\n * Returns an IndexEntry entry that sorts immediately after the current\n * directional value.\n */\n successor(): IndexEntry {\n const currentLength = this._directionalValue.length;\n const newLength =\n currentLength === 0 || this._directionalValue[currentLength - 1] === 255\n ? currentLength + 1\n : currentLength;\n\n const successor = new Uint8Array(newLength);\n successor.set(this._directionalValue, 0);\n if (newLength !== currentLength) {\n successor.set([0], this._directionalValue.length);\n } else {\n ++successor[successor.length - 1];\n }\n\n return new IndexEntry(\n this._indexId,\n this._documentKey,\n this._arrayValue,\n successor\n );\n }\n\n // Create a representation of the Index Entry as a DbIndexEntry\n dbIndexEntry(\n uid: string,\n orderedDocumentKey: Uint8Array,\n documentKey: DocumentKey\n ): DbIndexEntry {\n return {\n indexId: this._indexId,\n uid,\n arrayValue: encodeKeySafeBytes(this._arrayValue),\n directionalValue: encodeKeySafeBytes(this._directionalValue),\n orderedDocumentKey: encodeKeySafeBytes(orderedDocumentKey),\n documentKey: documentKey.path.toArray()\n };\n }\n\n // Create a representation of the Index Entry as a DbIndexEntryKey\n dbIndexEntryKey(\n uid: string,\n orderedDocumentKey: Uint8Array,\n documentKey: DocumentKey\n ): DbIndexEntryKey {\n const entry = this.dbIndexEntry(uid, orderedDocumentKey, documentKey);\n return [\n entry.indexId,\n entry.uid,\n entry.arrayValue,\n entry.directionalValue,\n entry.orderedDocumentKey,\n entry.documentKey\n ];\n }\n}\n\nexport function indexEntryComparator(\n left: IndexEntry,\n right: IndexEntry\n): number {\n let cmp = left._indexId - right._indexId;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = compareByteArrays(left._arrayValue, right._arrayValue);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = compareByteArrays(left._directionalValue, right._directionalValue);\n if (cmp !== 0) {\n return cmp;\n }\n\n return DocumentKey.comparator(left._documentKey, right._documentKey);\n}\n\nexport function compareByteArrays(left: Uint8Array, right: Uint8Array): number {\n for (let i = 0; i < left.length && i < right.length; ++i) {\n const compare = left[i] - right[i];\n if (compare !== 0) {\n return compare;\n }\n }\n return left.length - right.length;\n}\n\n/**\n * Workaround for WebKit bug: https://bugs.webkit.org/show_bug.cgi?id=292721\n * Create a key safe representation of Uint8Array values.\n * If the browser is detected as Safari or WebKit, then\n * the input array will be converted to \"sortable byte string\".\n * Otherwise, the input array will be returned in its original type.\n */\nexport function encodeKeySafeBytes(array: Uint8Array): KeySafeBytes {\n if (isSafariOrWebkit()) {\n return encodeUint8ArrayToSortableString(array);\n }\n return array;\n}\n\n/**\n * Reverts the key safe representation of Uint8Array (created by\n * encodeKeySafeBytes) to a normal Uint8Array.\n */\nexport function decodeKeySafeBytes(input: KeySafeBytes): Uint8Array {\n if (typeof input !== 'string') {\n return input;\n }\n return decodeSortableStringToUint8Array(input);\n}\n\n/**\n * Encodes a Uint8Array into a \"sortable byte string\".\n * A \"sortable byte string\" sorts in the same order as the Uint8Array.\n * This works because JS string comparison sorts strings based on code points.\n */\nfunction encodeUint8ArrayToSortableString(array: Uint8Array): string {\n let byteString = '';\n for (let i = 0; i < array.length; i++) {\n byteString += String.fromCharCode(array[i]);\n }\n\n return byteString;\n}\n\n/**\n * Decodes a \"sortable byte string\" back into a Uint8Array.\n * A \"sortable byte string\" is assumed to be created where each character's\n * Unicode code point directly corresponds to a single byte value (0-255).\n */\nfunction decodeSortableStringToUint8Array(byteString: string): Uint8Array {\n const uint8array = new Uint8Array(byteString.length);\n\n for (let i = 0; i < byteString.length; i++) {\n uint8array[i] = byteString.charCodeAt(i);\n }\n\n return uint8array;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldFilter, Operator } from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport { Target } from '../core/target';\nimport { hardAssert } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport {\n FieldIndex,\n fieldIndexGetArraySegment,\n fieldIndexGetDirectionalSegments,\n IndexKind,\n IndexSegment,\n IndexState\n} from './field_index';\nimport { FieldPath } from './path';\n\n/**\n * A light query planner for Firestore.\n *\n * This class matches a `FieldIndex` against a Firestore Query `Target`. It\n * determines whether a given index can be used to serve the specified target.\n *\n * The following table showcases some possible index configurations:\n *\n * Query | Index\n * -----------------------------------------------------------------------------\n * where('a', '==', 'a').where('b', '==', 'b') | a ASC, b DESC\n * where('a', '==', 'a').where('b', '==', 'b') | a ASC\n * where('a', '==', 'a').where('b', '==', 'b') | b DESC\n * where('a', '>=', 'a').orderBy('a') | a ASC\n * where('a', '>=', 'a').orderBy('a', 'desc') | a DESC\n * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC, b ASC\n * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC\n * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS, b ASCENDING\n * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS\n */\nexport class TargetIndexMatcher {\n // The collection ID (or collection group) of the query target.\n private readonly collectionId: string;\n // The inequality filters of the target (if it exists).\n // Note: The sort on FieldFilters is not required. Using SortedSet here just to utilize the custom\n // comparator.\n private inequalityFilters = new SortedSet((lhs, rhs) =>\n FieldPath.comparator(lhs.field, rhs.field)\n );\n\n // The list of equality filters of the target.\n private readonly equalityFilters: FieldFilter[];\n // The list of orderBys of the target.\n private readonly orderBys: OrderBy[];\n\n constructor(target: Target) {\n this.collectionId =\n target.collectionGroup != null\n ? target.collectionGroup\n : target.path.lastSegment();\n this.orderBys = target.orderBy;\n this.equalityFilters = [];\n for (const filter of target.filters) {\n const fieldFilter = filter as FieldFilter;\n if (fieldFilter.isInequality()) {\n this.inequalityFilters = this.inequalityFilters.add(fieldFilter);\n } else {\n this.equalityFilters.push(fieldFilter);\n }\n }\n }\n\n get hasMultipleInequality(): boolean {\n return this.inequalityFilters.size > 1;\n }\n\n /**\n * Returns whether the index can be used to serve the TargetIndexMatcher's\n * target.\n *\n * An index is considered capable of serving the target when:\n * - The target uses all index segments for its filters and orderBy clauses.\n * The target can have additional filter and orderBy clauses, but not\n * fewer.\n * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also\n * have a corresponding `CONTAINS` segment.\n * - All directional index segments can be mapped to the target as a series of\n * equality filters, a single inequality filter and a series of orderBy\n * clauses.\n * - The segments that represent the equality filters may appear out of order.\n * - The optional segment for the inequality filter must appear after all\n * equality segments.\n * - The segments that represent that orderBy clause of the target must appear\n * in order after all equality and inequality segments. Single orderBy\n * clauses cannot be skipped, but a continuous orderBy suffix may be\n * omitted.\n */\n servedByIndex(index: FieldIndex): boolean {\n hardAssert(\n index.collectionGroup === this.collectionId,\n 0xc07f,\n 'Collection IDs do not match'\n );\n\n if (this.hasMultipleInequality) {\n // Only single inequality is supported for now.\n // TODO(Add support for multiple inequality query): b/298441043\n return false;\n }\n\n // If there is an array element, find a matching filter.\n const arraySegment = fieldIndexGetArraySegment(index);\n if (\n arraySegment !== undefined &&\n !this.hasMatchingEqualityFilter(arraySegment)\n ) {\n return false;\n }\n\n const segments = fieldIndexGetDirectionalSegments(index);\n let equalitySegments = new Set();\n let segmentIndex = 0;\n let orderBysIndex = 0;\n\n // Process all equalities first. Equalities can appear out of order.\n for (; segmentIndex < segments.length; ++segmentIndex) {\n // We attempt to greedily match all segments to equality filters. If a\n // filter matches an index segment, we can mark the segment as used.\n if (this.hasMatchingEqualityFilter(segments[segmentIndex])) {\n equalitySegments = equalitySegments.add(\n segments[segmentIndex].fieldPath.canonicalString()\n );\n } else {\n // If we cannot find a matching filter, we need to verify whether the\n // remaining segments map to the target's inequality and its orderBy\n // clauses.\n break;\n }\n }\n\n // If we already have processed all segments, all segments are used to serve\n // the equality filters and we do not need to map any segments to the\n // target's inequality and orderBy clauses.\n if (segmentIndex === segments.length) {\n return true;\n }\n\n if (this.inequalityFilters.size > 0) {\n // Only a single inequality is currently supported. Get the only entry in the set.\n const inequalityFilter = this.inequalityFilters.getIterator().getNext();\n // If there is an inequality filter and the field was not in one of the\n // equality filters above, the next segment must match both the filter\n // and the first orderBy clause.\n if (!equalitySegments.has(inequalityFilter.field.canonicalString())) {\n const segment = segments[segmentIndex];\n\n if (\n !this.matchesFilter(inequalityFilter, segment) ||\n !this.matchesOrderBy(this.orderBys[orderBysIndex++], segment)\n ) {\n return false;\n }\n }\n\n ++segmentIndex;\n }\n\n // All remaining segments need to represent the prefix of the target's\n // orderBy.\n for (; segmentIndex < segments.length; ++segmentIndex) {\n const segment = segments[segmentIndex];\n if (\n orderBysIndex >= this.orderBys.length ||\n !this.matchesOrderBy(this.orderBys[orderBysIndex++], segment)\n ) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Returns a full matched field index for this target. Currently multiple\n * inequality query is not supported so function returns null.\n */\n buildTargetIndex(): FieldIndex | null {\n if (this.hasMultipleInequality) {\n return null;\n }\n\n // We want to make sure only one segment created for one field. For example,\n // in case like a == 3 and a > 2, Index {a ASCENDING} will only be created\n // once.\n let uniqueFields = new SortedSet(FieldPath.comparator);\n const segments: IndexSegment[] = [];\n\n for (const filter of this.equalityFilters) {\n if (filter.field.isKeyField()) {\n continue;\n }\n const isArrayOperator =\n filter.op === Operator.ARRAY_CONTAINS ||\n filter.op === Operator.ARRAY_CONTAINS_ANY;\n if (isArrayOperator) {\n segments.push(new IndexSegment(filter.field, IndexKind.CONTAINS));\n } else {\n if (uniqueFields.has(filter.field)) {\n continue;\n }\n uniqueFields = uniqueFields.add(filter.field);\n segments.push(new IndexSegment(filter.field, IndexKind.ASCENDING));\n }\n }\n\n // Note: We do not explicitly check `this.inequalityFilter` but rather rely\n // on the target defining an appropriate \"order by\" to ensure that the\n // required index segment is added. The query engine would reject a query\n // with an inequality filter that lacks the required order-by clause.\n for (const orderBy of this.orderBys) {\n // Stop adding more segments if we see a order-by on key. Typically this\n // is the default implicit order-by which is covered in the index_entry\n // table as a separate column. If it is not the default order-by, the\n // generated index will be missing some segments optimized for order-bys,\n // which is probably fine.\n if (orderBy.field.isKeyField()) {\n continue;\n }\n\n if (uniqueFields.has(orderBy.field)) {\n continue;\n }\n uniqueFields = uniqueFields.add(orderBy.field);\n\n segments.push(\n new IndexSegment(\n orderBy.field,\n orderBy.dir === Direction.ASCENDING\n ? IndexKind.ASCENDING\n : IndexKind.DESCENDING\n )\n );\n }\n\n return new FieldIndex(\n FieldIndex.UNKNOWN_ID,\n this.collectionId,\n segments,\n IndexState.empty()\n );\n }\n\n private hasMatchingEqualityFilter(segment: IndexSegment): boolean {\n for (const filter of this.equalityFilters) {\n if (this.matchesFilter(filter, segment)) {\n return true;\n }\n }\n return false;\n }\n\n private matchesFilter(\n filter: FieldFilter | undefined,\n segment: IndexSegment\n ): boolean {\n if (filter === undefined || !filter.field.isEqual(segment.fieldPath)) {\n return false;\n }\n const isArrayOperator =\n filter.op === Operator.ARRAY_CONTAINS ||\n filter.op === Operator.ARRAY_CONTAINS_ANY;\n return (segment.kind === IndexKind.CONTAINS) === isArrayOperator;\n }\n\n private matchesOrderBy(orderBy: OrderBy, segment: IndexSegment): boolean {\n if (!orderBy.field.isEqual(segment.fieldPath)) {\n return false;\n }\n return (\n (segment.kind === IndexKind.ASCENDING &&\n orderBy.dir === Direction.ASCENDING) ||\n (segment.kind === IndexKind.DESCENDING &&\n orderBy.dir === Direction.DESCENDING)\n );\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n CompositeFilter,\n compositeFilterIsConjunction,\n compositeFilterIsDisjunction,\n compositeFilterIsFlat,\n compositeFilterIsFlatConjunction,\n compositeFilterWithAddedFilters,\n CompositeOperator,\n FieldFilter,\n Filter,\n InFilter,\n Operator\n} from '../core/filter';\n\nimport { hardAssert } from './assert';\n\n/**\n * Provides utility functions that help with boolean logic transformations needed for handling\n * complex filters used in queries.\n */\n\n/**\n * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in\n * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given\n * input into a disjunction of equality filters and returns the expanded filter.\n */\nexport function computeInExpansion(filter: Filter): Filter {\n hardAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 0x4e2c,\n 'Only field filters and composite filters are accepted.'\n );\n\n if (filter instanceof FieldFilter) {\n if (filter instanceof InFilter) {\n const expandedFilters =\n filter.value.arrayValue?.values?.map(value =>\n FieldFilter.create(filter.field, Operator.EQUAL, value)\n ) || [];\n\n return CompositeFilter.create(expandedFilters, CompositeOperator.OR);\n } else {\n // We have reached other kinds of field filters.\n return filter;\n }\n }\n\n // We have a composite filter.\n const expandedFilters = filter.filters.map(subfilter =>\n computeInExpansion(subfilter)\n );\n return CompositeFilter.create(expandedFilters, filter.op);\n}\n\n/**\n * Given a composite filter, returns the list of terms in its disjunctive normal form.\n *\n *

Each element in the return value is one term of the resulting DNF. For instance: For the\n * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list\n * with two elements: a composite filter that performs (A && C), and a composite filter that\n * performs (B && C).\n *\n * @param filter the composite filter to calculate DNF transform for.\n * @return the terms in the DNF transform.\n */\nexport function getDnfTerms(filter: CompositeFilter): Filter[] {\n if (filter.getFilters().length === 0) {\n return [];\n }\n\n const result: Filter = computeDistributedNormalForm(\n computeInExpansion(filter)\n );\n\n hardAssert(\n isDisjunctiveNormalForm(result),\n 0x1cdf,\n 'computeDistributedNormalForm did not result in disjunctive normal form'\n );\n\n if (isSingleFieldFilter(result) || isFlatConjunction(result)) {\n return [result];\n }\n\n return result.getFilters();\n}\n\n/** Returns true if the given filter is a single field filter. e.g. (a == 10). */\nfunction isSingleFieldFilter(filter: Filter): boolean {\n return filter instanceof FieldFilter;\n}\n\n/**\n * Returns true if the given filter is the conjunction of one or more field filters. e.g. (a == 10\n * && b == 20)\n */\nfunction isFlatConjunction(filter: Filter): boolean {\n return (\n filter instanceof CompositeFilter &&\n compositeFilterIsFlatConjunction(filter)\n );\n}\n\n/**\n * Returns whether or not the given filter is in disjunctive normal form (DNF).\n *\n *

In boolean logic, a disjunctive normal form (DNF) is a canonical normal form of a logical\n * formula consisting of a disjunction of conjunctions; it can also be described as an OR of ANDs.\n *\n *

For more info, visit: https://en.wikipedia.org/wiki/Disjunctive_normal_form\n */\nfunction isDisjunctiveNormalForm(filter: Filter): boolean {\n return (\n isSingleFieldFilter(filter) ||\n isFlatConjunction(filter) ||\n isDisjunctionOfFieldFiltersAndFlatConjunctions(filter)\n );\n}\n\n/**\n * Returns true if the given filter is the disjunction of one or more \"flat conjunctions\" and\n * field filters. e.g. (a == 10) || (b==20 && c==30)\n */\nfunction isDisjunctionOfFieldFiltersAndFlatConjunctions(\n filter: Filter\n): boolean {\n if (filter instanceof CompositeFilter) {\n if (compositeFilterIsDisjunction(filter)) {\n for (const subFilter of filter.getFilters()) {\n if (!isSingleFieldFilter(subFilter) && !isFlatConjunction(subFilter)) {\n return false;\n }\n }\n\n return true;\n }\n }\n\n return false;\n}\n\nexport function computeDistributedNormalForm(filter: Filter): Filter {\n hardAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 0x84e2,\n 'Only field filters and composite filters are accepted.'\n );\n\n if (filter instanceof FieldFilter) {\n return filter;\n }\n\n if (filter.filters.length === 1) {\n return computeDistributedNormalForm(filter.filters[0]);\n }\n\n // Compute DNF for each of the subfilters first\n const result = filter.filters.map(subfilter =>\n computeDistributedNormalForm(subfilter)\n );\n\n let newFilter: Filter = CompositeFilter.create(result, filter.op);\n newFilter = applyAssociation(newFilter);\n\n if (isDisjunctiveNormalForm(newFilter)) {\n return newFilter;\n }\n\n hardAssert(\n newFilter instanceof CompositeFilter,\n 0xfbf2,\n 'field filters are already in DNF form'\n );\n hardAssert(\n compositeFilterIsConjunction(newFilter),\n 0x9d3b,\n 'Disjunction of filters all of which are already in DNF form is itself in DNF form.'\n );\n hardAssert(\n newFilter.filters.length > 1,\n 0xe247,\n 'Single-filter composite filters are already in DNF form.'\n );\n\n return newFilter.filters.reduce((runningResult, filter) =>\n applyDistribution(runningResult, filter)\n );\n}\n\nexport function applyDistribution(lhs: Filter, rhs: Filter): Filter {\n hardAssert(\n lhs instanceof FieldFilter || lhs instanceof CompositeFilter,\n 0x95f4,\n 'Only field filters and composite filters are accepted.'\n );\n hardAssert(\n rhs instanceof FieldFilter || rhs instanceof CompositeFilter,\n 0x6381,\n 'Only field filters and composite filters are accepted.'\n );\n\n let result: Filter;\n\n if (lhs instanceof FieldFilter) {\n if (rhs instanceof FieldFilter) {\n // FieldFilter FieldFilter\n result = applyDistributionFieldFilters(lhs, rhs);\n } else {\n // FieldFilter CompositeFilter\n result = applyDistributionFieldAndCompositeFilters(lhs, rhs);\n }\n } else {\n if (rhs instanceof FieldFilter) {\n // CompositeFilter FieldFilter\n result = applyDistributionFieldAndCompositeFilters(rhs, lhs);\n } else {\n // CompositeFilter CompositeFilter\n result = applyDistributionCompositeFilters(lhs, rhs);\n }\n }\n\n return applyAssociation(result);\n}\n\nfunction applyDistributionFieldFilters(\n lhs: FieldFilter,\n rhs: FieldFilter\n): Filter {\n // Conjunction distribution for two field filters is the conjunction of them.\n return CompositeFilter.create([lhs, rhs], CompositeOperator.AND);\n}\n\nfunction applyDistributionCompositeFilters(\n lhs: CompositeFilter,\n rhs: CompositeFilter\n): Filter {\n hardAssert(\n lhs.filters.length > 0 && rhs.filters.length > 0,\n 0xbb85,\n 'Found an empty composite filter'\n );\n\n // There are four cases:\n // (A & B) & (C & D) --> (A & B & C & D)\n // (A & B) & (C | D) --> (A & B & C) | (A & B & D)\n // (A | B) & (C & D) --> (C & D & A) | (C & D & B)\n // (A | B) & (C | D) --> (A & C) | (A & D) | (B & C) | (B & D)\n\n // Case 1 is a merge.\n if (compositeFilterIsConjunction(lhs) && compositeFilterIsConjunction(rhs)) {\n return compositeFilterWithAddedFilters(lhs, rhs.getFilters());\n }\n\n // Case 2,3,4 all have at least one side (lhs or rhs) that is a disjunction. In all three cases\n // we should take each element of the disjunction and distribute it over the other side, and\n // return the disjunction of the distribution results.\n const disjunctionSide = compositeFilterIsDisjunction(lhs) ? lhs : rhs;\n const otherSide = compositeFilterIsDisjunction(lhs) ? rhs : lhs;\n const results = disjunctionSide.filters.map(subfilter =>\n applyDistribution(subfilter, otherSide)\n );\n return CompositeFilter.create(results, CompositeOperator.OR);\n}\n\nfunction applyDistributionFieldAndCompositeFilters(\n fieldFilter: FieldFilter,\n compositeFilter: CompositeFilter\n): Filter {\n // There are two cases:\n // A & (B & C) --> (A & B & C)\n // A & (B | C) --> (A & B) | (A & C)\n if (compositeFilterIsConjunction(compositeFilter)) {\n // Case 1\n return compositeFilterWithAddedFilters(\n compositeFilter,\n fieldFilter.getFilters()\n );\n } else {\n // Case 2\n const newFilters = compositeFilter.filters.map(subfilter =>\n applyDistribution(fieldFilter, subfilter)\n );\n\n return CompositeFilter.create(newFilters, CompositeOperator.OR);\n }\n}\n\n/**\n * Applies the associativity property to the given filter and returns the resulting filter.\n *\n *

    \n *
  • A | (B | C) == (A | B) | C == (A | B | C)\n *
  • A & (B & C) == (A & B) & C == (A & B & C)\n *
\n *\n *

For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic\n */\nexport function applyAssociation(filter: Filter): Filter {\n hardAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 0x2e4a,\n 'Only field filters and composite filters are accepted.'\n );\n\n if (filter instanceof FieldFilter) {\n return filter;\n }\n\n const filters = filter.getFilters();\n\n // If the composite filter only contains 1 filter, apply associativity to it.\n if (filters.length === 1) {\n return applyAssociation(filters[0]);\n }\n\n // Associativity applied to a flat composite filter results is itself.\n if (compositeFilterIsFlat(filter)) {\n return filter;\n }\n\n // First apply associativity to all subfilters. This will in turn recursively apply\n // associativity to all nested composite filters and field filters.\n const updatedFilters = filters.map(subfilter => applyAssociation(subfilter));\n\n // For composite subfilters that perform the same kind of logical operation as `compositeFilter`\n // take out their filters and add them to `compositeFilter`. For example:\n // compositeFilter = (A | (B | C | D))\n // compositeSubfilter = (B | C | D)\n // Result: (A | B | C | D)\n // Note that the `compositeSubfilter` has been eliminated, and its filters (B, C, D) have been\n // added to the top-level \"compositeFilter\".\n const newSubfilters: Filter[] = [];\n updatedFilters.forEach(subfilter => {\n if (subfilter instanceof FieldFilter) {\n newSubfilters.push(subfilter);\n } else if (subfilter instanceof CompositeFilter) {\n if (subfilter.op === filter.op) {\n // compositeFilter: (A | (B | C))\n // compositeSubfilter: (B | C)\n // Result: (A | B | C)\n newSubfilters.push(...subfilter.filters);\n } else {\n // compositeFilter: (A | (B & C))\n // compositeSubfilter: (B & C)\n // Result: (A | (B & C))\n newSubfilters.push(subfilter);\n }\n }\n });\n\n if (newSubfilters.length === 1) {\n return newSubfilters[0];\n }\n\n return CompositeFilter.create(newSubfilters, filter.op);\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Target } from '../core/target';\nimport { DocumentMap } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldIndex, IndexOffset } from '../model/field_index';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { IndexManager, IndexType } from './index_manager';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\n/**\n * An in-memory implementation of IndexManager.\n */\nexport class MemoryIndexManager implements IndexManager {\n private collectionParentIndex = new MemoryCollectionParentIndex();\n\n addToCollectionParentIndex(\n transaction: PersistenceTransaction,\n collectionPath: ResourcePath\n ): PersistencePromise {\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 {\n IndexEntry,\n indexEntryComparator,\n encodeKeySafeBytes,\n decodeKeySafeBytes\n} 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 indexEntry.dbIndexEntry(\n this.uid,\n this.encodeDirectionalKey(fieldIndex, document.key),\n document.key\n )\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.dbIndexEntryKey(\n this.uid,\n this.encodeDirectionalKey(fieldIndex, document.key),\n document.key\n )\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 encodeKeySafeBytes(\n this.encodeDirectionalKey(fieldIndex, documentKey)\n )\n ])\n },\n (_, entry) => {\n results = results.add(\n new IndexEntry(\n fieldIndex.indexId,\n documentKey,\n decodeKeySafeBytes(entry.arrayValue),\n decodeKeySafeBytes(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 = bounds[i].dbIndexEntryKey(\n this.uid,\n EMPTY_VALUE,\n DocumentKey.empty()\n );\n const upperBound = bounds[i + 1].dbIndexEntryKey(\n this.uid,\n EMPTY_VALUE,\n DocumentKey.empty()\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(0xad8a, '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 0x7099,\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from '../model/document_key';\nimport { fail, hardAssert } from '../util/assert';\n\nimport {\n DbDocumentMutation,\n DbMutationBatch,\n DbRemoteDocument\n} from './indexeddb_schema';\nimport { DbRemoteDocument as DbRemoteDocumentLegacy } from './indexeddb_schema_legacy';\nimport {\n DbDocumentMutationKey,\n DbDocumentMutationStore,\n DbMutationBatchKey,\n DbMutationBatchStore,\n newDbDocumentMutationKey\n} from './indexeddb_sentinels';\nimport { PersistencePromise } from './persistence_promise';\nimport { SimpleDbTransaction } from './simple_db';\n\n/**\n * Delete a mutation batch and the associated document mutations.\n * @returns A PersistencePromise of the document mutations that were removed.\n */\nexport function removeMutationBatch(\n txn: SimpleDbTransaction,\n userId: string,\n batch: { batchId: number; mutations: Array<{ key: DocumentKey }> }\n): PersistencePromise {\n const mutationStore = txn.store(\n DbMutationBatchStore\n );\n const indexTxn = txn.store(\n DbDocumentMutationStore\n );\n const promises: Array> = [];\n\n const range = IDBKeyRange.only(batch.batchId);\n let numDeleted = 0;\n const removePromise = mutationStore.iterate(\n { range },\n (key, value, control) => {\n numDeleted++;\n return control.delete();\n }\n );\n promises.push(\n removePromise.next(() => {\n hardAssert(\n numDeleted === 1,\n 0xb7de,\n 'Dangling document-mutation reference found: Missing batch',\n { batchId: batch.batchId }\n );\n })\n );\n const removedDocuments: DocumentKey[] = [];\n for (const mutation of batch.mutations) {\n const indexKey = newDbDocumentMutationKey(\n userId,\n mutation.key.path,\n batch.batchId\n );\n promises.push(indexTxn.delete(indexKey));\n removedDocuments.push(mutation.key);\n }\n return PersistencePromise.waitFor(promises).next(() => removedDocuments);\n}\n\n/**\n * Returns an approximate size for the given document.\n */\nexport function dbDocumentSize(\n doc: DbRemoteDocument | DbRemoteDocumentLegacy | null\n): number {\n if (!doc) {\n return 0;\n }\n\n let value: unknown;\n if (doc.document) {\n value = doc.document;\n } else if (doc.unknownDocument) {\n value = doc.unknownDocument;\n } else if (doc.noDocument) {\n value = doc.noDocument;\n } else {\n throw fail(0x398b, 'Unknown remote document type');\n }\n return JSON.stringify(value).length;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { isCollectionGroupQuery, isDocumentQuery, Query } from '../core/query';\nimport { BatchId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { DocumentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { MutationBatch } from '../model/mutation_batch';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport { decodeResourcePath } from './encoded_resource_path';\nimport { IndexManager } from './index_manager';\nimport { removeMutationBatch } from './indexeddb_mutation_batch_impl';\nimport {\n DbDocumentMutation,\n DbMutationBatch,\n DbMutationQueue\n} from './indexeddb_schema';\nimport {\n DbDocumentMutationKey,\n DbDocumentMutationPlaceholder,\n DbDocumentMutationStore,\n DbMutationBatchKey,\n DbMutationBatchStore,\n DbMutationBatchUserMutationsIndex,\n DbMutationQueueKey,\n DbMutationQueueStore,\n newDbDocumentMutationKey,\n newDbDocumentMutationPrefixForPath,\n newDbDocumentMutationPrefixForUser\n} from './indexeddb_sentinels';\nimport { IndexedDbTransaction, getStore } from './indexeddb_transaction';\nimport {\n fromDbMutationBatch,\n LocalSerializer,\n toDbMutationBatch\n} from './local_serializer';\nimport { MutationQueue } from './mutation_queue';\nimport { ReferenceDelegate } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\n/** A mutation queue for a specific user, backed by IndexedDB. */\nexport class IndexedDbMutationQueue implements MutationQueue {\n /**\n * Caches the document keys for pending mutation batches. If the mutation\n * has been removed from IndexedDb, the cached value may continue to\n * be used to retrieve the batch's document keys. To remove a cached value\n * locally, `removeCachedMutationKeys()` should be invoked either directly\n * or through `removeMutationBatches()`.\n *\n * With multi-tab, when the primary client acknowledges or rejects a mutation,\n * this cache is used by secondary clients to invalidate the local\n * view of the documents that were previously affected by the mutation.\n */\n // PORTING NOTE: Multi-tab only.\n private documentKeysByBatchId = {} as { [batchId: number]: DocumentKeySet };\n\n constructor(\n /**\n * The normalized userId (e.g. null UID => \"\" userId) used to store /\n * retrieve mutations.\n */\n private userId: string,\n private readonly serializer: LocalSerializer,\n private readonly indexManager: IndexManager,\n private readonly referenceDelegate: ReferenceDelegate\n ) {}\n\n /**\n * Creates a new mutation queue for the given user.\n * @param user - The user for which to create a mutation queue.\n * @param serializer - The serializer to use when persisting to IndexedDb.\n */\n static forUser(\n user: User,\n serializer: LocalSerializer,\n indexManager: IndexManager,\n referenceDelegate: ReferenceDelegate\n ): IndexedDbMutationQueue {\n // TODO(mcg): Figure out what constraints there are on userIDs\n // In particular, are there any reserved characters? are empty ids allowed?\n // For the moment store these together in the same mutations table assuming\n // that empty userIDs aren't allowed.\n hardAssert(user.uid !== '', 0xfb83, 'UserID must not be an empty string.');\n const userId = user.isAuthenticated() ? user.uid! : '';\n return new IndexedDbMutationQueue(\n userId,\n serializer,\n indexManager,\n referenceDelegate\n );\n }\n\n checkEmpty(transaction: PersistenceTransaction): PersistencePromise {\n let empty = true;\n const range = IDBKeyRange.bound(\n [this.userId, Number.NEGATIVE_INFINITY],\n [this.userId, Number.POSITIVE_INFINITY]\n );\n return mutationsStore(transaction)\n .iterate(\n { index: DbMutationBatchUserMutationsIndex, range },\n (key, value, control) => {\n empty = false;\n control.done();\n }\n )\n .next(() => empty);\n }\n\n addMutationBatch(\n transaction: PersistenceTransaction,\n localWriteTime: Timestamp,\n baseMutations: Mutation[],\n mutations: Mutation[]\n ): PersistencePromise {\n const documentStore = documentMutationsStore(transaction);\n const mutationStore = mutationsStore(transaction);\n\n // The IndexedDb implementation in Chrome (and Firefox) does not handle\n // compound indices that include auto-generated keys correctly. To ensure\n // that the index entry is added correctly in all browsers, we perform two\n // writes: The first write is used to retrieve the next auto-generated Batch\n // ID, and the second write populates the index and stores the actual\n // mutation batch.\n // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972\n\n // We write an empty object to obtain key\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return mutationStore.add({} as any).next(batchId => {\n hardAssert(\n typeof batchId === 'number',\n 0xbf7b,\n 'Auto-generated key is not a number'\n );\n\n const batch = new MutationBatch(\n batchId,\n localWriteTime,\n baseMutations,\n mutations\n );\n const dbBatch = toDbMutationBatch(this.serializer, this.userId, batch);\n\n const promises: Array> = [];\n let collectionParents = new SortedSet((l, r) =>\n primitiveComparator(l.canonicalString(), r.canonicalString())\n );\n for (const mutation of mutations) {\n const indexKey = newDbDocumentMutationKey(\n this.userId,\n mutation.key.path,\n batchId\n );\n collectionParents = collectionParents.add(mutation.key.path.popLast());\n promises.push(mutationStore.put(dbBatch));\n promises.push(\n documentStore.put(indexKey, DbDocumentMutationPlaceholder)\n );\n }\n\n collectionParents.forEach(parent => {\n promises.push(\n this.indexManager.addToCollectionParentIndex(transaction, parent)\n );\n });\n\n transaction.addOnCommittedListener(() => {\n this.documentKeysByBatchId[batchId] = batch.keys();\n });\n\n return PersistencePromise.waitFor(promises).next(() => batch);\n });\n }\n\n lookupMutationBatch(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise {\n return mutationsStore(transaction)\n .get(batchId)\n .next(dbBatch => {\n if (dbBatch) {\n hardAssert(\n dbBatch.userId === this.userId,\n 0x0030,\n `Unexpected user for mutation batch`,\n {\n userId: dbBatch.userId,\n batchId\n }\n );\n return fromDbMutationBatch(this.serializer, dbBatch);\n }\n return null;\n });\n }\n\n /**\n * Returns the document keys for the mutation batch with the given batchId.\n * For primary clients, this method returns `null` after\n * `removeMutationBatches()` has been called. Secondary clients return a\n * cached result until `removeCachedMutationKeys()` is invoked.\n */\n // PORTING NOTE: Multi-tab only.\n lookupMutationKeys(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise {\n if (this.documentKeysByBatchId[batchId]) {\n return PersistencePromise.resolve(\n this.documentKeysByBatchId[batchId]\n );\n } else {\n return this.lookupMutationBatch(transaction, batchId).next(batch => {\n if (batch) {\n const keys = batch.keys();\n this.documentKeysByBatchId[batchId] = keys;\n return keys;\n } else {\n return null;\n }\n });\n }\n }\n\n getNextMutationBatchAfterBatchId(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise {\n const nextBatchId = batchId + 1;\n\n const range = IDBKeyRange.lowerBound([this.userId, nextBatchId]);\n let foundBatch: MutationBatch | null = null;\n return mutationsStore(transaction)\n .iterate(\n { index: DbMutationBatchUserMutationsIndex, range },\n (key, dbBatch, control) => {\n if (dbBatch.userId === this.userId) {\n hardAssert(\n dbBatch.batchId >= nextBatchId,\n 0xb9a4,\n 'Should have found mutation after `nextBatchId`',\n { nextBatchId }\n );\n foundBatch = fromDbMutationBatch(this.serializer, dbBatch);\n }\n control.done();\n }\n )\n .next(() => foundBatch);\n }\n\n getHighestUnacknowledgedBatchId(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n const range = IDBKeyRange.upperBound([\n this.userId,\n Number.POSITIVE_INFINITY\n ]);\n\n let batchId = BATCHID_UNKNOWN;\n return mutationsStore(transaction)\n .iterate(\n { index: DbMutationBatchUserMutationsIndex, range, reverse: true },\n (key, dbBatch, control) => {\n batchId = dbBatch.batchId;\n control.done();\n }\n )\n .next(() => batchId);\n }\n\n getAllMutationBatches(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n const range = IDBKeyRange.bound(\n [this.userId, BATCHID_UNKNOWN],\n [this.userId, Number.POSITIVE_INFINITY]\n );\n return mutationsStore(transaction)\n .loadAll(DbMutationBatchUserMutationsIndex, range)\n .next(dbBatches =>\n dbBatches.map(dbBatch => fromDbMutationBatch(this.serializer, dbBatch))\n );\n }\n\n getAllMutationBatchesAffectingDocumentKey(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n // Scan the document-mutation index starting with a prefix starting with\n // the given documentKey.\n const indexPrefix = newDbDocumentMutationPrefixForPath(\n this.userId,\n documentKey.path\n );\n const indexStart = IDBKeyRange.lowerBound(indexPrefix);\n\n const results: MutationBatch[] = [];\n return documentMutationsStore(transaction)\n .iterate({ range: indexStart }, (indexKey, _, control) => {\n const [userID, encodedPath, batchId] = indexKey;\n\n // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n const path = decodeResourcePath(encodedPath);\n if (userID !== this.userId || !documentKey.path.isEqual(path)) {\n control.done();\n return;\n }\n // Look up the mutation batch in the store.\n return mutationsStore(transaction)\n .get(batchId)\n .next(mutation => {\n if (!mutation) {\n throw fail(\n 0xf028,\n 'Dangling document-mutation reference found: `indexKey` which points to `batchId`',\n {\n indexKey,\n batchId\n }\n );\n }\n hardAssert(\n mutation.userId === this.userId,\n 0x2907,\n `Unexpected user for mutation batch`,\n {\n userId: mutation.userId,\n batchId\n }\n );\n results.push(fromDbMutationBatch(this.serializer, mutation));\n });\n })\n .next(() => results);\n }\n\n getAllMutationBatchesAffectingDocumentKeys(\n transaction: PersistenceTransaction,\n documentKeys: SortedMap\n ): PersistencePromise {\n let uniqueBatchIDs = new SortedSet(primitiveComparator);\n\n const promises: Array> = [];\n documentKeys.forEach(documentKey => {\n const indexStart = newDbDocumentMutationPrefixForPath(\n this.userId,\n documentKey.path\n );\n const range = IDBKeyRange.lowerBound(indexStart);\n\n const promise = documentMutationsStore(transaction).iterate(\n { range },\n (indexKey, _, control) => {\n const [userID, encodedPath, batchID] = indexKey;\n\n // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n const path = decodeResourcePath(encodedPath);\n if (userID !== this.userId || !documentKey.path.isEqual(path)) {\n control.done();\n return;\n }\n\n uniqueBatchIDs = uniqueBatchIDs.add(batchID);\n }\n );\n\n promises.push(promise);\n });\n\n return PersistencePromise.waitFor(promises).next(() =>\n this.lookupMutationBatches(transaction, uniqueBatchIDs)\n );\n }\n\n getAllMutationBatchesAffectingQuery(\n transaction: PersistenceTransaction,\n query: Query\n ): PersistencePromise {\n debugAssert(\n !isDocumentQuery(query),\n \"Document queries shouldn't go down this path\"\n );\n debugAssert(\n !isCollectionGroupQuery(query),\n 'CollectionGroup queries should be handled in LocalDocumentsView'\n );\n\n const queryPath = query.path;\n const immediateChildrenLength = queryPath.length + 1;\n\n // TODO(mcg): Actually implement a single-collection query\n //\n // This is actually executing an ancestor query, traversing the whole\n // subtree below the collection which can be horrifically inefficient for\n // some structures. The right way to solve this is to implement the full\n // value index, but that's not in the cards in the near future so this is\n // the best we can do for the moment.\n //\n // Since we don't yet index the actual properties in the mutations, our\n // current approach is to just return all mutation batches that affect\n // documents in the collection being queried.\n const indexPrefix = newDbDocumentMutationPrefixForPath(\n this.userId,\n queryPath\n );\n const indexStart = IDBKeyRange.lowerBound(indexPrefix);\n\n // Collect up unique batchIDs encountered during a scan of the index. Use a\n // SortedSet to accumulate batch IDs so they can be traversed in order in a\n // scan of the main table.\n let uniqueBatchIDs = new SortedSet(primitiveComparator);\n return documentMutationsStore(transaction)\n .iterate({ range: indexStart }, (indexKey, _, control) => {\n const [userID, encodedPath, batchID] = indexKey;\n const path = decodeResourcePath(encodedPath);\n if (userID !== this.userId || !queryPath.isPrefixOf(path)) {\n control.done();\n return;\n }\n // Rows with document keys more than one segment longer than the\n // query path can't be matches. For example, a query on 'rooms'\n // can't match the document /rooms/abc/messages/xyx.\n // TODO(mcg): we'll need a different scanner when we implement\n // ancestor queries.\n if (path.length !== immediateChildrenLength) {\n return;\n }\n uniqueBatchIDs = uniqueBatchIDs.add(batchID);\n })\n .next(() => this.lookupMutationBatches(transaction, uniqueBatchIDs));\n }\n\n private lookupMutationBatches(\n transaction: PersistenceTransaction,\n batchIDs: SortedSet\n ): PersistencePromise {\n const results: MutationBatch[] = [];\n const promises: Array> = [];\n // TODO(rockwood): Implement this using iterate.\n batchIDs.forEach(batchId => {\n promises.push(\n mutationsStore(transaction)\n .get(batchId)\n .next(mutation => {\n if (mutation === null) {\n throw fail(\n 0x89ca,\n 'Dangling document-mutation reference found, which points to `batchId`',\n {\n batchId\n }\n );\n }\n hardAssert(\n mutation.userId === this.userId,\n 0x2614,\n `Unexpected user for mutation batch`,\n { userId: mutation.userId, batchId }\n );\n results.push(fromDbMutationBatch(this.serializer, mutation));\n })\n );\n });\n return PersistencePromise.waitFor(promises).next(() => results);\n }\n\n removeMutationBatch(\n transaction: PersistenceTransaction,\n batch: MutationBatch\n ): PersistencePromise {\n return removeMutationBatch(\n (transaction as IndexedDbTransaction).simpleDbTransaction,\n this.userId,\n batch\n ).next(removedDocuments => {\n transaction.addOnCommittedListener(() => {\n this.removeCachedMutationKeys(batch.batchId);\n });\n return PersistencePromise.forEach(\n removedDocuments,\n (key: DocumentKey) => {\n return this.referenceDelegate.markPotentiallyOrphaned(\n transaction,\n key\n );\n }\n );\n });\n }\n\n /**\n * Clears the cached keys for a mutation batch. This method should be\n * called by secondary clients after they process mutation updates.\n *\n * Note that this method does not have to be called from primary clients as\n * the corresponding cache entries are cleared when an acknowledged or\n * rejected batch is removed from the mutation queue.\n */\n // PORTING NOTE: Multi-tab only\n removeCachedMutationKeys(batchId: BatchId): void {\n delete this.documentKeysByBatchId[batchId];\n }\n\n performConsistencyCheck(\n txn: PersistenceTransaction\n ): PersistencePromise {\n return this.checkEmpty(txn).next(empty => {\n if (!empty) {\n return PersistencePromise.resolve();\n }\n\n // Verify that there are no entries in the documentMutations index if\n // the queue is empty.\n const startRange = IDBKeyRange.lowerBound(\n newDbDocumentMutationPrefixForUser(this.userId)\n );\n const danglingMutationReferences: ResourcePath[] = [];\n return documentMutationsStore(txn)\n .iterate({ range: startRange }, (key, _, control) => {\n const userID = key[0];\n if (userID !== this.userId) {\n control.done();\n return;\n } else {\n const path = decodeResourcePath(key[1]);\n danglingMutationReferences.push(path);\n }\n })\n .next(() => {\n hardAssert(\n danglingMutationReferences.length === 0,\n 0xdd90,\n 'Document leak -- detected dangling mutation references when queue is empty.',\n {\n danglingKeys: danglingMutationReferences.map(p =>\n p.canonicalString()\n )\n }\n );\n });\n });\n }\n\n containsKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return mutationQueueContainsKey(txn, this.userId, key);\n }\n\n // PORTING NOTE: Multi-tab only (state is held in memory in other clients).\n /** Returns the mutation queue's metadata from IndexedDb. */\n private getMutationQueueMetadata(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return mutationQueuesStore(transaction)\n .get(this.userId)\n .next((metadata: DbMutationQueue | null) => {\n return (\n metadata || {\n userId: this.userId,\n lastAcknowledgedBatchId: BATCHID_UNKNOWN,\n lastStreamToken: ''\n }\n );\n });\n }\n}\n\n/**\n * @returns true if the mutation queue for the given user contains a pending\n * mutation for the given key.\n */\nfunction mutationQueueContainsKey(\n txn: PersistenceTransaction,\n userId: string,\n key: DocumentKey\n): PersistencePromise {\n const indexKey = newDbDocumentMutationPrefixForPath(userId, key.path);\n const encodedPath = indexKey[1];\n const startRange = IDBKeyRange.lowerBound(indexKey);\n let containsKey = false;\n return documentMutationsStore(txn)\n .iterate({ range: startRange, keysOnly: true }, (key, value, control) => {\n const [userID, keyPath, /*batchID*/ _] = key;\n if (userID === userId && keyPath === encodedPath) {\n containsKey = true;\n }\n control.done();\n })\n .next(() => containsKey);\n}\n\n/** Returns true if any mutation queue contains the given document. */\nexport function mutationQueuesContainKey(\n txn: PersistenceTransaction,\n docKey: DocumentKey\n): PersistencePromise {\n let found = false;\n return mutationQueuesStore(txn)\n .iterateSerial(userId => {\n return mutationQueueContainsKey(txn, userId, docKey).next(containsKey => {\n if (containsKey) {\n found = true;\n }\n return PersistencePromise.resolve(!containsKey);\n });\n })\n .next(() => found);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutations object store.\n */\nfunction mutationsStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbMutationBatchStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction documentMutationsStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbDocumentMutationStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction mutationQueuesStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbMutationQueueStore\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TargetId } from './types';\n\n/** Offset to ensure non-overlapping target ids. */\nconst OFFSET = 2;\n\n/**\n * Generates monotonically increasing target IDs for sending targets to the\n * watch stream.\n *\n * The client constructs two generators, one for the target cache, and one for\n * for the sync engine (to generate limbo documents targets). These\n * generators produce non-overlapping IDs (by using even and odd IDs\n * respectively).\n *\n * By separating the target ID space, the query cache can generate target IDs\n * that persist across client restarts, while sync engine can independently\n * generate in-memory target IDs that are transient and can be reused after a\n * restart.\n */\nexport class TargetIdGenerator {\n constructor(private lastId: number) {}\n\n next(): TargetId {\n this.lastId += OFFSET;\n return this.lastId;\n }\n\n static forTargetCache(): TargetIdGenerator {\n // The target cache generator must return '2' in its first call to `next()`\n // as there is no differentiation in the protocol layer between an unset\n // number and the number '0'. If we were to sent a target with target ID\n // '0', the backend would consider it unset and replace it with its own ID.\n return new TargetIdGenerator(2 - OFFSET);\n }\n\n static forSyncEngine(): TargetIdGenerator {\n // Sync engine assigns target IDs for limbo document detection.\n return new TargetIdGenerator(1 - OFFSET);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { canonifyTarget, Target, targetEquals } from '../core/target';\nimport { TargetIdGenerator } from '../core/target_id_generator';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { DocumentKeySet, documentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { hardAssert } from '../util/assert';\nimport { immediateSuccessor } from '../util/misc';\n\nimport {\n decodeResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { IndexedDbLruDelegate } from './indexeddb_lru_delegate';\nimport { DbTarget, DbTargetDocument, DbTargetGlobal } from './indexeddb_schema';\nimport {\n DbTargetDocumentDocumentTargetsIndex,\n DbTargetDocumentKey,\n DbTargetDocumentStore,\n DbTargetGlobalKey,\n DbTargetGlobalStore,\n DbTargetKey,\n DbTargetQueryTargetsIndexName,\n DbTargetStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport { fromDbTarget, LocalSerializer, toDbTarget } from './local_serializer';\nimport { ActiveTargets } from './lru_garbage_collector';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\nimport { TargetCache } from './target_cache';\nimport { TargetData } from './target_data';\n\nexport class IndexedDbTargetCache implements TargetCache {\n constructor(\n private readonly referenceDelegate: IndexedDbLruDelegate,\n private serializer: LocalSerializer\n ) {}\n\n // PORTING NOTE: We don't cache global metadata for the target cache, since\n // some of it (in particular `highestTargetId`) can be modified by secondary\n // tabs. We could perhaps be more granular (and e.g. still cache\n // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go\n // to IndexedDb whenever we need to read metadata. We can revisit if it turns\n // out to have a meaningful performance impact.\n\n allocateTargetId(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(metadata => {\n const targetIdGenerator = new TargetIdGenerator(metadata.highestTargetId);\n metadata.highestTargetId = targetIdGenerator.next();\n return this.saveMetadata(transaction, metadata).next(\n () => metadata.highestTargetId\n );\n });\n }\n\n getLastRemoteSnapshotVersion(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(metadata => {\n return SnapshotVersion.fromTimestamp(\n new Timestamp(\n metadata.lastRemoteSnapshotVersion.seconds,\n metadata.lastRemoteSnapshotVersion.nanoseconds\n )\n );\n });\n }\n\n getHighestSequenceNumber(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(\n targetGlobal => targetGlobal.highestListenSequenceNumber\n );\n }\n\n setTargetsMetadata(\n transaction: PersistenceTransaction,\n highestListenSequenceNumber: number,\n lastRemoteSnapshotVersion?: SnapshotVersion\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(metadata => {\n metadata.highestListenSequenceNumber = highestListenSequenceNumber;\n if (lastRemoteSnapshotVersion) {\n metadata.lastRemoteSnapshotVersion =\n lastRemoteSnapshotVersion.toTimestamp();\n }\n if (highestListenSequenceNumber > metadata.highestListenSequenceNumber) {\n metadata.highestListenSequenceNumber = highestListenSequenceNumber;\n }\n return this.saveMetadata(transaction, metadata);\n });\n }\n\n addTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n return this.saveTargetData(transaction, targetData).next(() => {\n return this.retrieveMetadata(transaction).next(metadata => {\n metadata.targetCount += 1;\n this.updateMetadataFromTargetData(targetData, metadata);\n return this.saveMetadata(transaction, metadata);\n });\n });\n }\n\n updateTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n return this.saveTargetData(transaction, targetData);\n }\n\n removeTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n return this.removeMatchingKeysForTargetId(transaction, targetData.targetId)\n .next(() => targetsStore(transaction).delete(targetData.targetId))\n .next(() => this.retrieveMetadata(transaction))\n .next(metadata => {\n hardAssert(\n metadata.targetCount > 0,\n 0x1f81,\n 'Removing from an empty target cache'\n );\n metadata.targetCount -= 1;\n return this.saveMetadata(transaction, metadata);\n });\n }\n\n /**\n * Drops any targets with sequence number less than or equal to the upper bound, excepting those\n * present in `activeTargetIds`. Document associations for the removed targets are also removed.\n * Returns the number of targets removed.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n let count = 0;\n const promises: Array> = [];\n return targetsStore(txn)\n .iterate((key, value) => {\n const targetData = fromDbTarget(value);\n if (\n targetData.sequenceNumber <= upperBound &&\n activeTargetIds.get(targetData.targetId) === null\n ) {\n count++;\n promises.push(this.removeTargetData(txn, targetData));\n }\n })\n .next(() => PersistencePromise.waitFor(promises))\n .next(() => count);\n }\n\n /**\n * Call provided function with each `TargetData` that we have cached.\n */\n forEachTarget(\n txn: PersistenceTransaction,\n f: (q: TargetData) => void\n ): PersistencePromise {\n return targetsStore(txn).iterate((key, value) => {\n const targetData = fromDbTarget(value);\n f(targetData);\n });\n }\n\n private retrieveMetadata(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return globalTargetStore(transaction)\n .get(DbTargetGlobalKey)\n .next(metadata => {\n hardAssert(metadata !== null, 0x0b48, 'Missing metadata row.');\n return metadata;\n });\n }\n\n private saveMetadata(\n transaction: PersistenceTransaction,\n metadata: DbTargetGlobal\n ): PersistencePromise {\n return globalTargetStore(transaction).put(DbTargetGlobalKey, metadata);\n }\n\n private saveTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n return targetsStore(transaction).put(\n toDbTarget(this.serializer, targetData)\n );\n }\n\n /**\n * In-place updates the provided metadata to account for values in the given\n * TargetData. Saving is done separately. Returns true if there were any\n * changes to the metadata.\n */\n private updateMetadataFromTargetData(\n targetData: TargetData,\n metadata: DbTargetGlobal\n ): boolean {\n let updated = false;\n if (targetData.targetId > metadata.highestTargetId) {\n metadata.highestTargetId = targetData.targetId;\n updated = true;\n }\n\n if (targetData.sequenceNumber > metadata.highestListenSequenceNumber) {\n metadata.highestListenSequenceNumber = targetData.sequenceNumber;\n updated = true;\n }\n return updated;\n }\n\n getTargetCount(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(\n metadata => metadata.targetCount\n );\n }\n\n getTargetData(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise {\n // Iterating by the canonicalId may yield more than one result because\n // canonicalId values are not required to be unique per target. This query\n // depends on the queryTargets index to be efficient.\n const canonicalId = canonifyTarget(target);\n const range = IDBKeyRange.bound(\n [canonicalId, Number.NEGATIVE_INFINITY],\n [canonicalId, Number.POSITIVE_INFINITY]\n );\n let result: TargetData | null = null;\n return targetsStore(transaction)\n .iterate(\n { range, index: DbTargetQueryTargetsIndexName },\n (key, value, control) => {\n const found = fromDbTarget(value);\n // After finding a potential match, check that the target is\n // actually equal to the requested target.\n if (targetEquals(target, found.target)) {\n result = found;\n control.done();\n }\n }\n )\n .next(() => result);\n }\n\n addMatchingKeys(\n txn: PersistenceTransaction,\n keys: DocumentKeySet,\n targetId: TargetId\n ): PersistencePromise {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n const promises: Array> = [];\n const store = documentTargetStore(txn);\n keys.forEach(key => {\n const path = encodeResourcePath(key.path);\n promises.push(store.put({ targetId, path }));\n promises.push(this.referenceDelegate.addReference(txn, targetId, key));\n });\n return PersistencePromise.waitFor(promises);\n }\n\n removeMatchingKeys(\n txn: PersistenceTransaction,\n keys: DocumentKeySet,\n targetId: TargetId\n ): PersistencePromise {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n const store = documentTargetStore(txn);\n return PersistencePromise.forEach(keys, (key: DocumentKey) => {\n const path = encodeResourcePath(key.path);\n return PersistencePromise.waitFor([\n store.delete([targetId, path]),\n this.referenceDelegate.removeReference(txn, targetId, key)\n ]);\n });\n }\n\n removeMatchingKeysForTargetId(\n txn: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise {\n const store = documentTargetStore(txn);\n const range = IDBKeyRange.bound(\n [targetId],\n [targetId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n return store.delete(range);\n }\n\n getMatchingKeysForTargetId(\n txn: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise {\n const range = IDBKeyRange.bound(\n [targetId],\n [targetId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n const store = documentTargetStore(txn);\n let result = documentKeySet();\n\n return store\n .iterate({ range, keysOnly: true }, (key, _, control) => {\n const path = decodeResourcePath(key[1]);\n const docKey = new DocumentKey(path);\n result = result.add(docKey);\n })\n .next(() => result);\n }\n\n containsKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n const path = encodeResourcePath(key.path);\n const range = IDBKeyRange.bound(\n [path],\n [immediateSuccessor(path)],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n let count = 0;\n return documentTargetStore(txn!)\n .iterate(\n {\n index: DbTargetDocumentDocumentTargetsIndex,\n keysOnly: true,\n range\n },\n ([targetId, path], _, control) => {\n // Having a sentinel row for a document does not count as containing that document;\n // For the target cache, containing the document means the document is part of some\n // target.\n if (targetId !== 0) {\n count++;\n control.done();\n }\n }\n )\n .next(() => count > 0);\n }\n\n /**\n * Looks up a TargetData entry by target ID.\n *\n * @param targetId - The target ID of the TargetData entry to look up.\n * @returns The cached TargetData entry, or null if the cache has no entry for\n * the target.\n */\n // PORTING NOTE: Multi-tab only.\n getTargetDataForTarget(\n transaction: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise {\n return targetsStore(transaction)\n .get(targetId)\n .next(found => {\n if (found) {\n return fromDbTarget(found);\n } else {\n return null;\n }\n });\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the queries object store.\n */\nfunction targetsStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbTargetStore);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the target globals object store.\n */\nfunction globalTargetStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbTargetGlobalStore);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document target object store.\n */\nexport function documentTargetStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbTargetDocumentStore\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirestoreError } from '../api';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { ListenSequenceNumber } from '../core/types';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { getLogLevel, logDebug, LogLevel } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from './local_store';\nimport {\n ActiveTargets,\n GC_DID_NOT_RUN,\n LRU_COLLECTION_DISABLED,\n LruDelegate,\n LruGarbageCollector,\n LruParams,\n LruResults\n} from './lru_garbage_collector';\nimport { Scheduler } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { isIndexedDbTransactionError } from './simple_db';\n\nconst LOG_TAG = 'LruGarbageCollector';\n\nexport const LRU_MINIMUM_CACHE_SIZE_BYTES = 1 * 1024 * 1024;\n\n/** How long we wait to try running LRU GC after SDK initialization. */\nconst INITIAL_GC_DELAY_MS = 1 * 60 * 1000;\n/** Minimum amount of time between GC checks, after the first one. */\nconst REGULAR_GC_DELAY_MS = 5 * 60 * 1000;\n\n// The type and comparator for the items contained in the SortedSet used in\n// place of a priority queue for the RollingSequenceNumberBuffer.\ntype BufferEntry = [ListenSequenceNumber, number];\n\nfunction bufferEntryComparator(\n [aSequence, aIndex]: BufferEntry,\n [bSequence, bIndex]: BufferEntry\n): number {\n const seqCmp = primitiveComparator(aSequence, bSequence);\n if (seqCmp === 0) {\n // This order doesn't matter, but we can bias against churn by sorting\n // entries created earlier as less than newer entries.\n return primitiveComparator(aIndex, bIndex);\n } else {\n return seqCmp;\n }\n}\n\n/**\n * Used to calculate the nth sequence number. Keeps a rolling buffer of the\n * lowest n values passed to `addElement`, and finally reports the largest of\n * them in `maxValue`.\n */\nclass RollingSequenceNumberBuffer {\n private buffer: SortedSet = 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\nimport { ListenSequence } from '../core/listen_sequence';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { DocumentKey } from '../model/document_key';\n\nimport {\n decodeResourcePath,\n EncodedResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { IndexedDbLruDelegate } from './indexeddb_lru_delegate';\nimport { mutationQueuesContainKey } from './indexeddb_mutation_queue';\nimport { DbTargetDocument } from './indexeddb_schema';\nimport { DbTargetDocumentDocumentTargetsIndex } from './indexeddb_sentinels';\nimport {\n documentTargetStore,\n IndexedDbTargetCache\n} from './indexeddb_target_cache';\nimport {\n ActiveTargets,\n LruGarbageCollector,\n LruParams\n} from './lru_garbage_collector';\nimport { newLruGarbageCollector } from './lru_garbage_collector_impl';\nimport { Persistence } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { TargetData } from './target_data';\n\n/** Provides LRU functionality for IndexedDB persistence. */\nexport class IndexedDbLruDelegateImpl implements IndexedDbLruDelegate {\n readonly garbageCollector: LruGarbageCollector;\n\n constructor(private readonly db: Persistence, params: LruParams) {\n this.garbageCollector = newLruGarbageCollector(this, params);\n }\n\n getSequenceNumberCount(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const docCountPromise = this.orphanedDocumentCount(txn);\n const targetCountPromise = this.db.getTargetCache().getTargetCount(txn);\n return targetCountPromise.next(targetCount =>\n docCountPromise.next(docCount => targetCount + docCount)\n );\n }\n\n private orphanedDocumentCount(\n txn: PersistenceTransaction\n ): PersistencePromise {\n let orphanedCount = 0;\n return this.forEachOrphanedDocumentSequenceNumber(txn, _ => {\n orphanedCount++;\n }).next(() => orphanedCount);\n }\n\n forEachTarget(\n txn: PersistenceTransaction,\n f: (q: TargetData) => void\n ): PersistencePromise {\n return this.db.getTargetCache().forEachTarget(txn, f);\n }\n\n forEachOrphanedDocumentSequenceNumber(\n txn: PersistenceTransaction,\n f: (sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise {\n return this.forEachOrphanedDocument(txn, (docKey, sequenceNumber) =>\n f(sequenceNumber)\n );\n }\n\n addReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise {\n return writeSentinelKey(txn, key);\n }\n\n removeReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise {\n return writeSentinelKey(txn, key);\n }\n\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n return (this.db.getTargetCache() as IndexedDbTargetCache).removeTargets(\n txn,\n upperBound,\n activeTargetIds\n );\n }\n\n markPotentiallyOrphaned(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return writeSentinelKey(txn, key);\n }\n\n /**\n * Returns true if anything would prevent this document from being garbage\n * collected, given that the document in question is not present in any\n * targets and has a sequence number less than or equal to the upper bound for\n * the collection run.\n */\n private isPinned(\n txn: PersistenceTransaction,\n docKey: DocumentKey\n ): PersistencePromise {\n return mutationQueuesContainKey(txn, docKey);\n }\n\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise {\n const documentCache = this.db.getRemoteDocumentCache();\n const changeBuffer = documentCache.newChangeBuffer();\n\n const promises: Array> = [];\n let documentCount = 0;\n\n const iteration = this.forEachOrphanedDocument(\n txn,\n (docKey, sequenceNumber) => {\n if (sequenceNumber <= upperBound) {\n const p = this.isPinned(txn, docKey).next(isPinned => {\n if (!isPinned) {\n documentCount++;\n // Our size accounting requires us to read all documents before\n // removing them.\n return changeBuffer.getEntry(txn, docKey).next(() => {\n changeBuffer.removeEntry(docKey, SnapshotVersion.min());\n return documentTargetStore(txn).delete(sentinelKey(docKey));\n });\n }\n });\n promises.push(p);\n }\n }\n );\n\n return iteration\n .next(() => PersistencePromise.waitFor(promises))\n .next(() => changeBuffer.apply(txn))\n .next(() => documentCount);\n }\n\n removeTarget(\n txn: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n const updated = targetData.withSequenceNumber(txn.currentSequenceNumber);\n return this.db.getTargetCache().updateTargetData(txn, updated);\n }\n\n updateLimboDocument(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return writeSentinelKey(txn, key);\n }\n\n /**\n * Call provided function for each document in the cache that is 'orphaned'. Orphaned\n * means not a part of any target, so the only entry in the target-document index for\n * that document will be the sentinel row (targetId 0), which will also have the sequence\n * number for the last time the document was accessed.\n */\n private forEachOrphanedDocument(\n txn: PersistenceTransaction,\n f: (docKey: DocumentKey, sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise {\n const store = documentTargetStore(txn);\n let nextToReport: ListenSequenceNumber = ListenSequence.INVALID;\n let nextPath: EncodedResourcePath;\n return store\n .iterate(\n {\n index: DbTargetDocumentDocumentTargetsIndex\n },\n ([targetId, docKey], { path, sequenceNumber }) => {\n if (targetId === 0) {\n // if nextToReport is valid, report it, this is a new key so the\n // last one must not be a member of any targets.\n if (nextToReport !== ListenSequence.INVALID) {\n f(new DocumentKey(decodeResourcePath(nextPath)), nextToReport);\n }\n // set nextToReport to be this sequence number. It's the next one we\n // might report, if we don't find any targets for this document.\n // Note that the sequence number must be defined when the targetId\n // is 0.\n nextToReport = sequenceNumber!;\n nextPath = path;\n } else {\n // set nextToReport to be invalid, we know we don't need to report\n // this one since we found a target for it.\n nextToReport = ListenSequence.INVALID;\n }\n }\n )\n .next(() => {\n // Since we report sequence numbers after getting to the next key, we\n // need to check if the last key we iterated over was an orphaned\n // document and report it.\n if (nextToReport !== ListenSequence.INVALID) {\n f(new DocumentKey(decodeResourcePath(nextPath)), nextToReport);\n }\n });\n }\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise {\n return this.db.getRemoteDocumentCache().getSize(txn);\n }\n}\n\nfunction sentinelKey(key: DocumentKey): [TargetId, EncodedResourcePath] {\n return [0, encodeResourcePath(key.path)];\n}\n\n/**\n * @returns A value suitable for writing a sentinel row in the target-document\n * store.\n */\nfunction sentinelRow(\n key: DocumentKey,\n sequenceNumber: ListenSequenceNumber\n): DbTargetDocument {\n return { targetId: 0, path: encodeResourcePath(key.path), sequenceNumber };\n}\n\nfunction writeSentinelKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n): PersistencePromise {\n return documentTargetStore(txn).put(\n sentinelRow(key, txn.currentSequenceNumber)\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { DocumentKeySet, MutableDocumentMap } from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { debugAssert } from '../util/assert';\nimport { ObjectMap } from '../util/obj_map';\n\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\n/**\n * An in-memory buffer of entries to be written to a RemoteDocumentCache.\n * It can be used to batch up a set of changes to be written to the cache, but\n * additionally supports reading entries back with the `getEntry()` method,\n * falling back to the underlying RemoteDocumentCache if no entry is\n * buffered.\n *\n * Entries added to the cache *must* be read first. This is to facilitate\n * calculating the size delta of the pending changes.\n *\n * PORTING NOTE: This class was implemented then removed from other platforms.\n * If byte-counting ends up being needed on the other platforms, consider\n * porting this class as part of that implementation work.\n */\nexport abstract class RemoteDocumentChangeBuffer {\n // A mapping of document key to the new cache entry that should be written.\n protected changes: ObjectMap = 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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Query, queryMatches } from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport {\n DocumentKeySet,\n DocumentSizeEntries,\n MutableDocumentMap,\n mutableDocumentMap,\n OverlayMap\n} from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { IndexOffset } from '../model/field_index';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { IndexManager } from './index_manager';\nimport { dbDocumentSize } from './indexeddb_mutation_batch_impl';\nimport { DbRemoteDocument, DbRemoteDocumentGlobal } from './indexeddb_schema';\nimport {\n DbRemoteDocumentCollectionGroupIndex,\n DbRemoteDocumentDocumentKeyIndex,\n DbRemoteDocumentGlobalKey,\n DbRemoteDocumentGlobalStore,\n DbRemoteDocumentKey,\n DbRemoteDocumentStore,\n DbTimestampKey\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n fromDbRemoteDocument,\n LocalSerializer,\n toDbRemoteDocument,\n toDbTimestampKey\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { QueryContext } from './query_context';\nimport { RemoteDocumentCache } from './remote_document_cache';\nimport { RemoteDocumentChangeBuffer } from './remote_document_change_buffer';\nimport { SimpleDbStore } from './simple_db';\n\nexport interface DocumentSizeEntry {\n document: MutableDocument;\n size: number;\n}\n\nexport interface IndexedDbRemoteDocumentCache extends RemoteDocumentCache {\n // The IndexedDbRemoteDocumentCache doesn't implement any methods on top\n // of RemoteDocumentCache. This class exists for consistency.\n}\n\n/**\n * The RemoteDocumentCache for IndexedDb. To construct, invoke\n * `newIndexedDbRemoteDocumentCache()`.\n */\nclass IndexedDbRemoteDocumentCacheImpl implements IndexedDbRemoteDocumentCache {\n indexManager!: IndexManager;\n\n constructor(readonly serializer: LocalSerializer) {}\n\n setIndexManager(indexManager: IndexManager): void {\n this.indexManager = indexManager;\n }\n\n /**\n * Adds the supplied entries to the cache.\n *\n * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n */\n addEntry(\n transaction: PersistenceTransaction,\n key: DocumentKey,\n doc: DbRemoteDocument\n ): PersistencePromise {\n const documentStore = remoteDocumentsStore(transaction);\n return documentStore.put(doc);\n }\n\n /**\n * Removes a document from the cache.\n *\n * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n */\n removeEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey,\n readTime: SnapshotVersion\n ): PersistencePromise {\n const store = remoteDocumentsStore(transaction);\n return store.delete(dbReadTimeKey(documentKey, readTime));\n }\n\n /**\n * Updates the current cache size.\n *\n * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the\n * cache's metadata.\n */\n updateMetadata(\n transaction: PersistenceTransaction,\n sizeDelta: number\n ): PersistencePromise {\n return this.getMetadata(transaction).next(metadata => {\n metadata.byteSize += sizeDelta;\n return this.setMetadata(transaction, metadata);\n });\n }\n\n getEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n let doc = MutableDocument.newInvalidDocument(documentKey);\n return remoteDocumentsStore(transaction)\n .iterate(\n {\n index: DbRemoteDocumentDocumentKeyIndex,\n range: IDBKeyRange.only(dbKey(documentKey))\n },\n (_, dbRemoteDoc) => {\n doc = this.maybeDecodeDocument(documentKey, dbRemoteDoc);\n }\n )\n .next(() => doc);\n }\n\n /**\n * Looks up an entry in the cache.\n *\n * @param documentKey - The key of the entry to look up.\n * @returns The cached document entry and its size.\n */\n getSizedEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n let result = {\n size: 0,\n document: MutableDocument.newInvalidDocument(documentKey)\n };\n return remoteDocumentsStore(transaction)\n .iterate(\n {\n index: DbRemoteDocumentDocumentKeyIndex,\n range: IDBKeyRange.only(dbKey(documentKey))\n },\n (_, dbRemoteDoc) => {\n result = {\n document: this.maybeDecodeDocument(documentKey, dbRemoteDoc),\n size: dbDocumentSize(dbRemoteDoc)\n };\n }\n )\n .next(() => result);\n }\n\n getEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise {\n let results = mutableDocumentMap();\n return this.forEachDbEntry(\n transaction,\n documentKeys,\n (key, dbRemoteDoc) => {\n const doc = this.maybeDecodeDocument(key, dbRemoteDoc);\n results = results.insert(key, doc);\n }\n ).next(() => results);\n }\n\n /**\n * Looks up several entries in the cache.\n *\n * @param documentKeys - The set of keys entries to look up.\n * @returns A map of documents indexed by key and a map of sizes indexed by\n * key (zero if the document does not exist).\n */\n getSizedEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise {\n let results = mutableDocumentMap();\n let sizeMap = new SortedMap(DocumentKey.comparator);\n return this.forEachDbEntry(\n transaction,\n documentKeys,\n (key, dbRemoteDoc) => {\n const doc = this.maybeDecodeDocument(key, dbRemoteDoc);\n results = results.insert(key, doc);\n sizeMap = sizeMap.insert(key, dbDocumentSize(dbRemoteDoc));\n }\n ).next(() => {\n return { documents: results, sizeMap };\n });\n }\n\n private forEachDbEntry(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet,\n callback: (key: DocumentKey, doc: DbRemoteDocument | null) => void\n ): PersistencePromise {\n if (documentKeys.isEmpty()) {\n return PersistencePromise.resolve();\n }\n\n let sortedKeys = new SortedSet(dbKeyComparator);\n documentKeys.forEach(e => (sortedKeys = sortedKeys.add(e)));\n const range = IDBKeyRange.bound(\n dbKey(sortedKeys.first()!),\n dbKey(sortedKeys.last()!)\n );\n const keyIter = sortedKeys.getIterator();\n let nextKey: DocumentKey | null = keyIter.getNext();\n\n return remoteDocumentsStore(transaction)\n .iterate(\n { index: DbRemoteDocumentDocumentKeyIndex, range },\n (_, dbRemoteDoc, control) => {\n const potentialKey = DocumentKey.fromSegments([\n ...dbRemoteDoc.prefixPath,\n dbRemoteDoc.collectionGroup,\n dbRemoteDoc.documentId\n ]);\n\n // Go through keys not found in cache.\n while (nextKey && dbKeyComparator(nextKey!, potentialKey) < 0) {\n callback(nextKey!, null);\n nextKey = keyIter.getNext();\n }\n\n if (nextKey && nextKey!.isEqual(potentialKey)) {\n // Key found in cache.\n callback(nextKey!, dbRemoteDoc);\n nextKey = keyIter.hasNext() ? keyIter.getNext() : null;\n }\n\n // Skip to the next key (if there is one).\n if (nextKey) {\n control.skip(dbKey(nextKey));\n } else {\n control.done();\n }\n }\n )\n .next(() => {\n // The rest of the keys are not in the cache. One case where `iterate`\n // above won't go through them is when the cache is empty.\n while (nextKey) {\n callback(nextKey!, null);\n nextKey = keyIter.hasNext() ? keyIter.getNext() : null;\n }\n });\n }\n\n getDocumentsMatchingQuery(\n transaction: PersistenceTransaction,\n query: Query,\n offset: IndexOffset,\n mutatedDocs: OverlayMap,\n context?: QueryContext\n ): PersistencePromise {\n const collection = query.path;\n const startKey = [\n collection.popLast().toArray(),\n collection.lastSegment(),\n toDbTimestampKey(offset.readTime),\n offset.documentKey.path.isEmpty()\n ? ''\n : offset.documentKey.path.lastSegment()\n ];\n const endKey: DbRemoteDocumentKey = [\n collection.popLast().toArray(),\n collection.lastSegment(),\n [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n ''\n ];\n\n return remoteDocumentsStore(transaction)\n .loadAll(IDBKeyRange.bound(startKey, endKey, true))\n .next(dbRemoteDocs => {\n context?.incrementDocumentReadCount(dbRemoteDocs.length);\n let results = mutableDocumentMap();\n for (const dbRemoteDoc of dbRemoteDocs) {\n const document = this.maybeDecodeDocument(\n DocumentKey.fromSegments(\n dbRemoteDoc.prefixPath.concat(\n dbRemoteDoc.collectionGroup,\n dbRemoteDoc.documentId\n )\n ),\n dbRemoteDoc\n );\n if (\n document.isFoundDocument() &&\n (queryMatches(query, document) || mutatedDocs.has(document.key))\n ) {\n // Either the document matches the given query, or it is mutated.\n results = results.insert(document.key, document);\n }\n }\n return results;\n });\n }\n\n getAllFromCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n offset: IndexOffset,\n limit: number\n ): PersistencePromise {\n debugAssert(limit > 0, 'Limit should be at least 1');\n let results = mutableDocumentMap();\n\n const startKey = dbCollectionGroupKey(collectionGroup, offset);\n const endKey = dbCollectionGroupKey(collectionGroup, IndexOffset.max());\n return remoteDocumentsStore(transaction)\n .iterate(\n {\n index: DbRemoteDocumentCollectionGroupIndex,\n range: IDBKeyRange.bound(startKey, endKey, true)\n },\n (_, dbRemoteDoc, control) => {\n const document = this.maybeDecodeDocument(\n DocumentKey.fromSegments(\n dbRemoteDoc.prefixPath.concat(\n dbRemoteDoc.collectionGroup,\n dbRemoteDoc.documentId\n )\n ),\n dbRemoteDoc\n );\n results = results.insert(document.key, document);\n if (results.size === limit) {\n control.done();\n }\n }\n )\n .next(() => results);\n }\n\n newChangeBuffer(options?: {\n trackRemovals: boolean;\n }): RemoteDocumentChangeBuffer {\n return new IndexedDbRemoteDocumentChangeBuffer(\n this,\n !!options && options.trackRemovals\n );\n }\n\n getSize(txn: PersistenceTransaction): PersistencePromise {\n return this.getMetadata(txn).next(metadata => metadata.byteSize);\n }\n\n private getMetadata(\n txn: PersistenceTransaction\n ): PersistencePromise {\n return documentGlobalStore(txn)\n .get(DbRemoteDocumentGlobalKey)\n .next(metadata => {\n hardAssert(!!metadata, 0x4e35, 'Missing document cache metadata');\n return metadata!;\n });\n }\n\n private setMetadata(\n txn: PersistenceTransaction,\n metadata: DbRemoteDocumentGlobal\n ): PersistencePromise {\n return documentGlobalStore(txn).put(DbRemoteDocumentGlobalKey, metadata);\n }\n\n /**\n * Decodes `dbRemoteDoc` and returns the document (or an invalid document if\n * the document corresponds to the format used for sentinel deletes).\n */\n private maybeDecodeDocument(\n documentKey: DocumentKey,\n dbRemoteDoc: DbRemoteDocument | null\n ): MutableDocument {\n if (dbRemoteDoc) {\n const doc = fromDbRemoteDocument(this.serializer, dbRemoteDoc);\n // Whether the document is a sentinel removal and should only be used in the\n // `getNewDocumentChanges()`\n const isSentinelRemoval =\n doc.isNoDocument() && doc.version.isEqual(SnapshotVersion.min());\n if (!isSentinelRemoval) {\n return doc;\n }\n }\n return MutableDocument.newInvalidDocument(documentKey);\n }\n}\n\n/** Creates a new IndexedDbRemoteDocumentCache. */\nexport function newIndexedDbRemoteDocumentCache(\n serializer: LocalSerializer\n): IndexedDbRemoteDocumentCache {\n return new IndexedDbRemoteDocumentCacheImpl(serializer);\n}\n\n/**\n * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache.\n *\n * Unlike the MemoryRemoteDocumentChangeBuffer, the IndexedDb implementation computes the size\n * delta for all submitted changes. This avoids having to re-read all documents from IndexedDb\n * when we apply the changes.\n */\nclass IndexedDbRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer {\n // A map of document sizes and read times prior to applying the changes in\n // this buffer.\n protected documentStates: ObjectMap<\n DocumentKey,\n { size: number; readTime: SnapshotVersion }\n > = new ObjectMap(\n key => key.toString(),\n (l, r) => l.isEqual(r)\n );\n\n /**\n * @param documentCache - The IndexedDbRemoteDocumentCache to apply the changes to.\n * @param trackRemovals - Whether to create sentinel deletes that can be tracked by\n * `getNewDocumentChanges()`.\n */\n constructor(\n private readonly documentCache: IndexedDbRemoteDocumentCacheImpl,\n private readonly trackRemovals: boolean\n ) {\n super();\n }\n\n protected applyChanges(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n const promises: Array> = [];\n\n let sizeDelta = 0;\n\n let collectionParents = new SortedSet((l, r) =>\n primitiveComparator(l.canonicalString(), r.canonicalString())\n );\n\n this.changes.forEach((key, documentChange) => {\n const previousDoc = this.documentStates.get(key);\n debugAssert(\n previousDoc !== undefined,\n `Cannot modify a document that wasn't read (for ${key})`\n );\n promises.push(\n this.documentCache.removeEntry(transaction, key, previousDoc.readTime)\n );\n if (documentChange.isValidDocument()) {\n debugAssert(\n !documentChange.readTime.isEqual(SnapshotVersion.min()),\n 'Cannot add a document with a read time of zero'\n );\n const doc = toDbRemoteDocument(\n this.documentCache.serializer,\n documentChange\n );\n collectionParents = collectionParents.add(key.path.popLast());\n\n const size = dbDocumentSize(doc);\n sizeDelta += size - previousDoc.size;\n promises.push(this.documentCache.addEntry(transaction, key, doc));\n } else {\n sizeDelta -= previousDoc.size;\n if (this.trackRemovals) {\n // In order to track removals, we store a \"sentinel delete\" in the\n // RemoteDocumentCache. This entry is represented by a NoDocument\n // with a version of 0 and ignored by `maybeDecodeDocument()` but\n // preserved in `getNewDocumentChanges()`.\n const deletedDoc = toDbRemoteDocument(\n this.documentCache.serializer,\n documentChange.convertToNoDocument(SnapshotVersion.min())\n );\n promises.push(\n this.documentCache.addEntry(transaction, key, deletedDoc)\n );\n }\n }\n });\n\n collectionParents.forEach(parent => {\n promises.push(\n this.documentCache.indexManager.addToCollectionParentIndex(\n transaction,\n parent\n )\n );\n });\n\n promises.push(this.documentCache.updateMetadata(transaction, sizeDelta));\n\n return PersistencePromise.waitFor(promises);\n }\n\n protected getFromCache(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n // Record the size of everything we load from the cache so we can compute a delta later.\n return this.documentCache\n .getSizedEntry(transaction, documentKey)\n .next(getResult => {\n this.documentStates.set(documentKey, {\n size: getResult.size,\n readTime: getResult.document.readTime\n });\n return getResult.document;\n });\n }\n\n protected getAllFromCache(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise {\n // Record the size of everything we load from the cache so we can compute\n // a delta later.\n return this.documentCache\n .getSizedEntries(transaction, documentKeys)\n .next(({ documents, sizeMap }) => {\n // Note: `getAllFromCache` returns two maps instead of a single map from\n // keys to `DocumentSizeEntry`s. This is to allow returning the\n // `MutableDocumentMap` directly, without a conversion.\n sizeMap.forEach((documentKey, size) => {\n this.documentStates.set(documentKey, {\n size,\n readTime: documents.get(documentKey)!.readTime\n });\n });\n return documents;\n });\n }\n}\n\nfunction documentGlobalStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbRemoteDocumentGlobalStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the remoteDocuments object store.\n */\nfunction remoteDocumentsStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbRemoteDocumentStore\n );\n}\n\n/**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentKeyIndex` index.\n */\nfunction dbKey(documentKey: DocumentKey): [string[], string, string] {\n const path = documentKey.path.toArray();\n return [\n /* prefix path */ path.slice(0, path.length - 2),\n /* collection id */ path[path.length - 2],\n /* document id */ path[path.length - 1]\n ];\n}\n\n/**\n * Returns a key that can be used for document lookups via the primary key of\n * the DbRemoteDocument object store.\n */\nfunction dbReadTimeKey(\n documentKey: DocumentKey,\n readTime: SnapshotVersion\n): DbRemoteDocumentKey {\n const path = documentKey.path.toArray();\n return [\n /* prefix path */ path.slice(0, path.length - 2),\n /* collection id */ path[path.length - 2],\n toDbTimestampKey(readTime),\n /* document id */ path[path.length - 1]\n ];\n}\n\n/**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentCollectionGroupIndex` index.\n */\nfunction dbCollectionGroupKey(\n collectionGroup: string,\n offset: IndexOffset\n): [string, DbTimestampKey, string[], string] {\n const path = offset.documentKey.path.toArray();\n return [\n /* collection id */ collectionGroup,\n toDbTimestampKey(offset.readTime),\n /* prefix path */ path.slice(0, path.length - 2),\n /* document id */ path.length > 0 ? path[path.length - 1] : ''\n ];\n}\n\n/**\n * Comparator that compares document keys according to the primary key sorting\n * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id\n * and then document ID).\n *\n * Visible for testing.\n */\nexport function dbKeyComparator(l: DocumentKey, r: DocumentKey): number {\n const left = l.path.toArray();\n const right = r.path.toArray();\n\n // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74\n let cmp = 0;\n for (let i = 0; i < left.length - 2 && i < right.length - 2; ++i) {\n cmp = primitiveComparator(left[i], right[i]);\n if (cmp) {\n return cmp;\n }\n }\n\n cmp = primitiveComparator(left.length, right.length);\n if (cmp) {\n return cmp;\n }\n\n cmp = primitiveComparator(left[left.length - 2], right[right.length - 2]);\n if (cmp) {\n return cmp;\n }\n\n // TODO(b/329441702): Document IDs should be sorted by UTF-8 encoded byte\n // order, but IndexedDB sorts strings lexicographically. Document ID\n // comparison here still relies on primitive comparison to avoid mismatches\n // observed in snapshot listeners with Unicode characters in documentIds\n return primitiveComparator(left[left.length - 1], right[right.length - 1]);\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Document } from '../model/document';\nimport { FieldMask } from '../model/field_mask';\n\n/**\n * Represents a local view (overlay) of a document, and the fields that are\n * locally mutated.\n */\nexport class OverlayedDocument {\n constructor(\n readonly overlayedDocument: Document,\n\n /**\n * The fields that are locally mutated by patch mutations.\n *\n * If the overlayed\tdocument is from set or delete mutations, this is `null`.\n * If there is no overlay (mutation) for the document, this is an empty `FieldMask`.\n */\n readonly mutatedFields: FieldMask | null\n ) {}\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n asCollectionQueryAtPath,\n isCollectionGroupQuery,\n isDocumentQuery,\n Query,\n queryMatches\n} from '../core/query';\nimport { Timestamp } from '../lite-api/timestamp';\nimport {\n DocumentKeySet,\n OverlayMap,\n DocumentMap,\n MutableDocumentMap,\n newDocumentKeyMap,\n newMutationMap,\n newOverlayMap,\n documentMap,\n mutableDocumentMap,\n documentKeySet,\n DocumentKeyMap,\n convertOverlayedDocumentMapToDocumentMap,\n OverlayedDocumentMap,\n newOverlayedDocumentMap\n} from '../model/collections';\nimport { Document, MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { IndexOffset, INITIAL_LARGEST_BATCH_ID } from '../model/field_index';\nimport { FieldMask } from '../model/field_mask';\nimport {\n calculateOverlayMutation,\n mutationApplyToLocalView,\n PatchMutation\n} from '../model/mutation';\nimport { Overlay } from '../model/overlay';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert } from '../util/assert';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { IndexManager } from './index_manager';\nimport { LocalWriteResult } from './local_store_impl';\nimport { MutationQueue } from './mutation_queue';\nimport { OverlayedDocument } from './overlayed_document';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { QueryContext } from './query_context';\nimport { RemoteDocumentCache } from './remote_document_cache';\n\n/**\n * A readonly view of the local state of all documents we're tracking (i.e. we\n * have a cached version in remoteDocumentCache or local mutations for the\n * document). The view is computed by applying the mutations in the\n * MutationQueue to the RemoteDocumentCache.\n */\nexport class LocalDocumentsView {\n constructor(\n readonly remoteDocumentCache: RemoteDocumentCache,\n readonly mutationQueue: MutationQueue,\n readonly documentOverlayCache: DocumentOverlayCache,\n readonly indexManager: IndexManager\n ) {}\n\n /**\n * Get the local view of the document identified by `key`.\n *\n * @returns Local view of the document or null if we don't have any cached\n * state for it.\n */\n getDocument(\n transaction: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\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 *

+ */ +export declare function setLogLevel(logLevel: LogLevel): void; +/** + * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link + * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be + * configured to perform granular merges instead of overwriting the target + * documents in their entirety by providing a `SetOptions` with `merge: true`. + * + * @param merge - Changes the behavior of a `setDoc()` call to only replace the + * values specified in its data argument. Fields omitted from the `setDoc()` + * call remain untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace + * the specified field paths. Any field path that is not specified is ignored + * and remains untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + */ +export declare type SetOptions = { + readonly merge?: boolean; +} | { + readonly mergeFields?: Array; +}; +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ +export declare function snapshotEqual(left: DocumentSnapshot | QuerySnapshot, right: DocumentSnapshot | QuerySnapshot): boolean; +/** + * An options object that can be passed to {@link (onSnapshot:1)} and {@link + * QuerySnapshot.docChanges} to control which types of changes to include in the + * result set. + */ +export declare interface SnapshotListenOptions { + /** + * Include a change even if only the metadata of the query or of a document + * changed. Default is false. + */ + readonly includeMetadataChanges?: boolean; + /** + * Set the source the query listens to. Default to "default", which + * listens to both cache and server. + */ + readonly source?: ListenSource; +} +/** + * Metadata about a snapshot, describing the state of the snapshot. + */ +export declare class SnapshotMetadata { + /** + * True if the snapshot contains the result of local writes (for example + * `set()` or `update()` calls) that have not yet been committed to the + * backend. If your listener has opted into metadata updates (via + * `SnapshotListenOptions`) you will receive another snapshot with + * `hasPendingWrites` equal to false once the writes have been committed to + * the backend. + */ + readonly hasPendingWrites: boolean; + /** + * True if the snapshot was created from cached data rather than guaranteed + * up-to-date server data. If your listener has opted into metadata updates + * (via `SnapshotListenOptions`) you will receive another snapshot with + * `fromCache` set to false once the client has received up-to-date data from + * the backend. + */ + readonly fromCache: boolean; + private constructor(); + /** + * Returns true if this `SnapshotMetadata` is equal to the provided one. + * + * @param other - The `SnapshotMetadata` to compare against. + * @returns true if this `SnapshotMetadata` is equal to the provided one. + */ + isEqual(other: SnapshotMetadata): boolean; +} +/** + * Options that configure how data is retrieved from a `DocumentSnapshot` (for + * example the desired behavior for server timestamps that have not yet been set + * to their final value). + */ +export declare interface SnapshotOptions { + /** + * If set, controls the return value for server timestamps that have not yet + * been set to their final value. + * + * By specifying 'estimate', pending server timestamps return an estimate + * based on the local clock. This estimate will differ from the final value + * and cause these values to change once the server result becomes available. + * + * By specifying 'previous', pending timestamps will be ignored and return + * their previous value instead. + * + * If omitted or set to 'none', `null` will be returned by default until the + * server value becomes available. + */ + readonly serverTimestamps?: 'estimate' | 'previous' | 'none'; +} +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided document (exclusive). The starting position is + * relative to the order of the query. The document must contain all of the + * fields provided in the orderBy of the query. + * + * @param snapshot - The snapshot of the document to start after. + * @returns A {@link QueryStartAtConstraint} to pass to `query()` + */ +export declare function startAfter(snapshot: DocumentSnapshot): QueryStartAtConstraint; +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided fields relative to the order of the query. The order + * of the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to start this query after, in order + * of the query's order by. + * @returns A {@link QueryStartAtConstraint} to pass to `query()` + */ +export declare function startAfter(...fieldValues: unknown[]): QueryStartAtConstraint; +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided document (inclusive). The starting position is relative + * to the order of the query. The document must contain all of the fields + * provided in the `orderBy` of this query. + * + * @param snapshot - The snapshot of the document to start at. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. + */ +export declare function startAt(snapshot: DocumentSnapshot): QueryStartAtConstraint; +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to start this query at, in order + * of the query's order by. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. + */ +export declare function startAt(...fieldValues: unknown[]): QueryStartAtConstraint; +/** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ +export declare function sum(field: string | FieldPath): AggregateField; +/** + * Represents the state of bundle loading tasks. + * + * Both 'Error' and 'Success' are sinking state: task will abort or complete and there will + * be no more updates after they are reported. + */ +export declare type TaskState = 'Error' | 'Running' | 'Success'; +/** + * Terminates the provided {@link Firestore} instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` function + * may be used. Any other function will throw a `FirestoreError`. + * + * To restart after termination, create a new instance of FirebaseFirestore with + * {@link (getFirestore:1)}. + * + * Termination does not cancel any pending writes, and any promises that are + * awaiting a response from the server will not be resolved. If you have + * persistence enabled, the next time you start this instance, it will resume + * sending these writes to the server. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all + * of its resources or in combination with `clearIndexedDbPersistence()` to + * ensure that all local state is destroyed between test runs. + * + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ +export declare function terminate(firestore: Firestore): Promise; +/** + * A `Timestamp` represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. + * + * It is encoded using the Proleptic Gregorian Calendar which extends the + * Gregorian calendar backwards to year one. It is encoded assuming all minutes + * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59.999999999Z. + * + * For examples and further specifications, refer to the + * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. + */ +export declare class Timestamp { + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + readonly seconds: number; + /** + * The fractions of a second at nanosecond resolution.* + */ + readonly nanoseconds: number; + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns a new timestamp representing the current date. + */ + static now(): Timestamp; + /** + * Creates a new timestamp from the given date. + * + * @param date - The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the given + * date. + */ + static fromDate(date: Date): Timestamp; + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds - Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the given + * number of milliseconds. + */ + static fromMillis(milliseconds: number): Timestamp; + /** + * Creates a new timestamp. + * + * @param seconds - The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds - The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ + constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + seconds: number, + /** + * The fractions of a second at nanosecond resolution.* + */ + nanoseconds: number); + /** + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ + toDate(): Date; + /** + * Converts a `Timestamp` to a numeric timestamp (in milliseconds since + * epoch). This operation causes a loss of precision. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ + toMillis(): number; + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other - The `Timestamp` to compare against. + * @returns true if this `Timestamp` is equal to the provided one. + */ + isEqual(other: Timestamp): boolean; + /** Returns a textual representation of this `Timestamp`. */ + toString(): string; + /** + * Returns a JSON-serializable representation of this `Timestamp`. + */ + toJSON(): { + seconds: number; + nanoseconds: number; + type: string; + }; + /** + * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}. + */ + static fromJSON(json: object): Timestamp; + /** + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. + */ + valueOf(): string; +} +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ +export declare class Transaction { + private constructor(); + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ + get(documentRef: DocumentReference): Promise>; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: WithFieldValue): this; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * If you provide `merge` or `mergeFields`, the provided data can be merged + * into an existing document. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: PartialWithFieldValue, options: SetOptions): this; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * @param documentRef - A reference to the document to be updated. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, data: UpdateData): this; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * @param documentRef - A reference to the document to be updated. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key/value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): this; + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + delete(documentRef: DocumentReference): this; +} +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options to customize transaction behavior. + */ +export declare interface TransactionOptions { + /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */ + readonly maxAttempts?: number; +} +/** + * Given a union type `U = T1 | T2 | ...`, returns an intersected type + * `(T1 & T2 & ...)`. + * + * Uses distributive conditional types and inference from conditional types. + * This works because multiple candidates for the same type variable in + * contra-variant positions causes an intersection type to be inferred. + * https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-inference-in-conditional-types + * https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type + */ +export declare type UnionToIntersection = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never; +/** + * A function returned by `onSnapshot()` that removes the listener when invoked. + */ +export declare interface Unsubscribe { + /** Removes the listener when invoked. */ + (): void; +} +/** + * Update data (for use with {@link (updateDoc:1)}) that consists of field paths + * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots + * reference nested fields within the document. FieldValues can be passed in + * as property values. + */ +export declare type UpdateData = T extends Primitive ? T : T extends {} ? { + [K in keyof T]?: UpdateData | FieldValue; +} & NestedUpdateFields : Partial; +/** + * Updates fields in the document referred to by the specified + * `DocumentReference`. The update will fail if applied to a document that does + * not exist. + * + * @param reference - A reference to the document to update. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +export declare function updateDoc(reference: DocumentReference, data: UpdateData): Promise; +/** + * Updates fields in the document referred to by the specified + * `DocumentReference` The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * @param reference - A reference to the document to update. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +export declare function updateDoc(reference: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): Promise; +/** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ +export declare function vector(values?: number[]): VectorValue; +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link vector}. + * + * @class VectorValue + */ +export declare class VectorValue { + /* Excluded from this release type: __constructor */ + /** + * Returns a copy of the raw number array form of the vector. + */ + toArray(): number[]; + /** + * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise. + */ + isEqual(other: VectorValue): boolean; + /** + * Returns a JSON-serializable representation of this `VectorValue` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}. + * + * @param json a JSON object represention of a `VectorValue` instance. + * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): VectorValue; +} +/** + * Waits until all currently pending writes for the active user have been + * acknowledged by the backend. + * + * The returned promise resolves immediately if there are no outstanding writes. + * Otherwise, the promise waits for all previously issued writes (including + * those written in a previous app session), but it does not wait for writes + * that were added after the function is called. If you want to wait for + * additional writes, call `waitForPendingWrites()` again. + * + * Any outstanding `waitForPendingWrites()` promises are rejected during user + * changes. + * + * @returns A `Promise` which resolves when all currently pending writes have been + * acknowledged by the backend. + */ +export declare function waitForPendingWrites(firestore: Firestore): Promise; +/** + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. + * + * @param fieldPath - The path to compare + * @param opStr - The operation string (e.g "<", "<=", "==", "<", + * "<=", "!="). + * @param value - The value for comparison + * @returns The created {@link QueryFieldFilterConstraint}. + */ +export declare function where(fieldPath: string | FieldPath, opStr: WhereFilterOp, value: unknown): QueryFieldFilterConstraint; +/** + * Filter conditions in a {@link where} clause are specified using the + * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in', + * 'array-contains-any', and 'not-in'. + */ +export declare type WhereFilterOp = '<' | '<=' | '==' | '!=' | '>=' | '>' | 'array-contains' | 'in' | 'array-contains-any' | 'not-in'; +/** + * Allows FieldValues to be passed in as a property value while maintaining + * type safety. + */ +export declare type WithFieldValue = T | (T extends Primitive ? T : T extends {} ? { + [K in keyof T]: WithFieldValue | FieldValue; +} : never); +/** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It + * provides methods for adding writes to the write batch. None of the writes + * will be committed (or visible locally) until {@link WriteBatch.commit} is + * called. + */ +export declare class WriteBatch { + private constructor(); + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: WithFieldValue): WriteBatch; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * If you provide `merge` or `mergeFields`, the provided data can be merged + * into an existing document. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: PartialWithFieldValue, options: SetOptions): WriteBatch; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * @param documentRef - A reference to the document to be updated. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, data: UpdateData): WriteBatch; + /** + * Updates fields in the document referred to by this {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be update by providing dot-separated field path strings + * or by providing `FieldPath` objects. + * + * @param documentRef - A reference to the document to be updated. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): WriteBatch; + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + delete(documentRef: DocumentReference): WriteBatch; + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `Promise` resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit (note that it won't + * resolve while you're offline). + */ + commit(): Promise; +} +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch} + * is 500. + * + * Unlike transactions, write batches are persisted offline and therefore are + * preferable when you don't need to condition your writes on read data. + * + * @returns A {@link WriteBatch} that can be used to atomically execute multiple + * writes. + */ +export declare function writeBatch(firestore: Firestore): WriteBatch; +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/index.esm.js b/frontend-old/node_modules/@firebase/firestore/dist/index.esm.js new file mode 100644 index 0000000..afc885a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/index.esm.js @@ -0,0 +1,23119 @@ +import { _registerComponent, registerVersion, _isFirebaseServerApp, _getProvider, getApp, _removeServiceInstance, SDK_VERSION } from '@firebase/app'; +import { Component } from '@firebase/component'; +import { Logger, LogLevel } from '@firebase/logger'; +import { FirebaseError, isCloudWorkstation, pingServer, updateEmulatorBanner, deepEqual, createMockUserToken, getModularInstance, getDefaultEmulatorHostnameAndPort, getGlobal, isIndexedDBAvailable, getUA, isSafari, isSafariOrWebkit } from '@firebase/util'; +import { Integer, Md5 } from '@firebase/webchannel-wrapper/bloom-blob'; +import { XhrIo, EventType, ErrorCode, createWebChannelTransport, getStatEventTarget, WebChannel, Event, Stat } from '@firebase/webchannel-wrapper/webchannel-blob'; + +const F = "@firebase/firestore", M = "4.9.2"; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Simple wrapper around a nullable UID. Mostly exists to make code more + * readable. + */ +class User { + constructor(e) { + this.uid = e; + } + isAuthenticated() { + return null != this.uid; + } + /** + * Returns a key representing this user, suitable for inclusion in a + * dictionary. + */ toKey() { + return this.isAuthenticated() ? "uid:" + this.uid : "anonymous-user"; + } + isEqual(e) { + return e.uid === this.uid; + } +} + +/** A user with a null UID. */ User.UNAUTHENTICATED = new User(null), +// TODO(mikelehen): Look into getting a proper uid-equivalent for +// non-FirebaseAuth providers. +User.GOOGLE_CREDENTIALS = new User("google-credentials-uid"), User.FIRST_PARTY = new User("first-party-uid"), +User.MOCK_USER = new User("mock-user"); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let x = "12.3.0"; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const O = new Logger("@firebase/firestore"); + +// Helper methods are needed because variables can't be exported as read/write +function __PRIVATE_getLogLevel() { + return O.logLevel; +} + +/** + * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). + * + * @param logLevel - The verbosity you set for activity and error logging. Can + * be any of the following values: + * + *
    + *
  • `debug` for the most verbose logging level, primarily for + * debugging.
  • + *
  • `error` to log errors only.
  • + *
  • `silent` to turn off logging.
  • + *
+ */ function setLogLevel(e) { + O.setLogLevel(e); +} + +function __PRIVATE_logDebug(e, ...t) { + if (O.logLevel <= LogLevel.DEBUG) { + const n = t.map(__PRIVATE_argToString); + O.debug(`Firestore (${x}): ${e}`, ...n); + } +} + +function __PRIVATE_logError(e, ...t) { + if (O.logLevel <= LogLevel.ERROR) { + const n = t.map(__PRIVATE_argToString); + O.error(`Firestore (${x}): ${e}`, ...n); + } +} + +/** + * @internal + */ function __PRIVATE_logWarn(e, ...t) { + if (O.logLevel <= LogLevel.WARN) { + const n = t.map(__PRIVATE_argToString); + O.warn(`Firestore (${x}): ${e}`, ...n); + } +} + +/** + * Converts an additional log parameter to a string representation. + */ function __PRIVATE_argToString(e) { + if ("string" == typeof e) return e; + try { + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** Formats an object as a JSON string, suitable for logging. */ + return function __PRIVATE_formatJSON(e) { + return JSON.stringify(e); + }(e); + } catch (t) { + // Converting to JSON failed, just log the object directly + return e; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function fail(e, t, n) { + let r = "Unexpected state"; + "string" == typeof t ? r = t : n = t, __PRIVATE__fail(e, r, n); +} + +function __PRIVATE__fail(e, t, n) { + // Log the failure in addition to throw an exception, just in case the + // exception is swallowed. + let r = `FIRESTORE (${x}) INTERNAL ASSERTION FAILED: ${t} (ID: ${e.toString(16)})`; + if (void 0 !== n) try { + r += " CONTEXT: " + JSON.stringify(n); + } catch (e) { + r += " CONTEXT: " + n; + } + // NOTE: We don't use FirestoreError here because these are internal failures + // that cannot be handled by the user. (Also it would create a circular + // dependency between the error and assert modules which doesn't work.) + throw __PRIVATE_logError(r), new Error(r); +} + +function __PRIVATE_hardAssert(e, t, n, r) { + let i = "Unexpected state"; + "string" == typeof n ? i = n : r = n, e || __PRIVATE__fail(t, i, r); +} + +/** + * Fails if the given assertion condition is false, throwing an Error with the + * given message if it did. + * + * The code of callsites invoking this function are stripped out in production + * builds. Any side-effects of code within the debugAssert() invocation will not + * happen in this case. + * + * @internal + */ function __PRIVATE_debugAssert(e, t) { + e || fail(57014, t); +} + +/** + * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an + * instance of `T` before casting. + */ function __PRIVATE_debugCast(e, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +t) { + return e; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const N = { + // Causes are copied from: + // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h + /** Not an error; returned on success. */ + OK: "ok", + /** The operation was cancelled (typically by the caller). */ + CANCELLED: "cancelled", + /** Unknown error or an error from a different error domain. */ + UNKNOWN: "unknown", + /** + * Client specified an invalid argument. Note that this differs from + * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are + * problematic regardless of the state of the system (e.g., a malformed file + * name). + */ + INVALID_ARGUMENT: "invalid-argument", + /** + * Deadline expired before operation could complete. For operations that + * change the state of the system, this error may be returned even if the + * operation has completed successfully. For example, a successful response + * from a server could have been delayed long enough for the deadline to + * expire. + */ + DEADLINE_EXCEEDED: "deadline-exceeded", + /** Some requested entity (e.g., file or directory) was not found. */ + NOT_FOUND: "not-found", + /** + * Some entity that we attempted to create (e.g., file or directory) already + * exists. + */ + ALREADY_EXISTS: "already-exists", + /** + * The caller does not have permission to execute the specified operation. + * PERMISSION_DENIED must not be used for rejections caused by exhausting + * some resource (use RESOURCE_EXHAUSTED instead for those errors). + * PERMISSION_DENIED must not be used if the caller cannot be identified + * (use UNAUTHENTICATED instead for those errors). + */ + PERMISSION_DENIED: "permission-denied", + /** + * The request does not have valid authentication credentials for the + * operation. + */ + UNAUTHENTICATED: "unauthenticated", + /** + * Some resource has been exhausted, perhaps a per-user quota, or perhaps the + * entire file system is out of space. + */ + RESOURCE_EXHAUSTED: "resource-exhausted", + /** + * Operation was rejected because the system is not in a state required for + * the operation's execution. For example, directory to be deleted may be + * non-empty, an rmdir operation is applied to a non-directory, etc. + * + * A litmus test that may help a service implementor in deciding + * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: + * (a) Use UNAVAILABLE if the client can retry just the failing call. + * (b) Use ABORTED if the client should retry at a higher-level + * (e.g., restarting a read-modify-write sequence). + * (c) Use FAILED_PRECONDITION if the client should not retry until + * the system state has been explicitly fixed. E.g., if an "rmdir" + * fails because the directory is non-empty, FAILED_PRECONDITION + * should be returned since the client should not retry unless + * they have first fixed up the directory by deleting files from it. + * (d) Use FAILED_PRECONDITION if the client performs conditional + * REST Get/Update/Delete on a resource and the resource on the + * server does not match the condition. E.g., conflicting + * read-modify-write on the same resource. + */ + FAILED_PRECONDITION: "failed-precondition", + /** + * The operation was aborted, typically due to a concurrency issue like + * sequencer check failures, transaction aborts, etc. + * + * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, + * and UNAVAILABLE. + */ + ABORTED: "aborted", + /** + * Operation was attempted past the valid range. E.g., seeking or reading + * past end of file. + * + * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed + * if the system state changes. For example, a 32-bit file system will + * generate INVALID_ARGUMENT if asked to read at an offset that is not in the + * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from + * an offset past the current file size. + * + * There is a fair bit of overlap between FAILED_PRECONDITION and + * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) + * when it applies so that callers who are iterating through a space can + * easily look for an OUT_OF_RANGE error to detect when they are done. + */ + OUT_OF_RANGE: "out-of-range", + /** Operation is not implemented or not supported/enabled in this service. */ + UNIMPLEMENTED: "unimplemented", + /** + * Internal errors. Means some invariants expected by underlying System has + * been broken. If you see one of these errors, Something is very broken. + */ + INTERNAL: "internal", + /** + * The service is currently unavailable. This is a most likely a transient + * condition and may be corrected by retrying with a backoff. + * + * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, + * and UNAVAILABLE. + */ + UNAVAILABLE: "unavailable", + /** Unrecoverable data loss or corruption. */ + DATA_LOSS: "data-loss" +}; + +/** An error returned by a Firestore operation. */ class FirestoreError extends FirebaseError { + /** @hideconstructor */ + constructor( + /** + * The backend error code associated with this error. + */ + e, + /** + * A custom error description. + */ + t) { + super(e, t), this.code = e, this.message = t, + // HACK: We write a toString property directly because Error is not a real + // class and so inheritance does not work correctly. We could alternatively + // do the same "back-door inheritance" trick that FirebaseError does. + this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_Deferred { + constructor() { + this.promise = new Promise(((e, t) => { + this.resolve = e, this.reject = t; + })); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_OAuthToken { + constructor(e, t) { + this.user = t, this.type = "OAuth", this.headers = new Map, this.headers.set("Authorization", `Bearer ${e}`); + } +} + +/** + * A CredentialsProvider that always yields an empty token. + * @internal + */ class __PRIVATE_EmptyAuthCredentialsProvider { + getToken() { + return Promise.resolve(null); + } + invalidateToken() {} + start(e, t) { + // Fire with initial user. + e.enqueueRetryable((() => t(User.UNAUTHENTICATED))); + } + shutdown() {} +} + +/** + * A CredentialsProvider that always returns a constant token. Used for + * emulator token mocking. + */ class __PRIVATE_EmulatorAuthCredentialsProvider { + constructor(e) { + this.token = e, + /** + * Stores the listener registered with setChangeListener() + * This isn't actually necessary since the UID never changes, but we use this + * to verify the listen contract is adhered to in tests. + */ + this.changeListener = null; + } + getToken() { + return Promise.resolve(this.token); + } + invalidateToken() {} + start(e, t) { + this.changeListener = t, + // Fire with initial user. + e.enqueueRetryable((() => t(this.token.user))); + } + shutdown() { + this.changeListener = null; + } +} + +class __PRIVATE_FirebaseAuthCredentialsProvider { + constructor(e) { + this.t = e, + /** Tracks the current User. */ + this.currentUser = User.UNAUTHENTICATED, + /** + * Counter used to detect if the token changed while a getToken request was + * outstanding. + */ + this.i = 0, this.forceRefresh = !1, this.auth = null; + } + start(e, t) { + __PRIVATE_hardAssert(void 0 === this.o, 42304); + let n = this.i; + // A change listener that prevents double-firing for the same token change. + const __PRIVATE_guardedChangeListener = e => this.i !== n ? (n = this.i, + t(e)) : Promise.resolve(); + // A promise that can be waited on to block on the next token change. + // This promise is re-created after each change. + let r = new __PRIVATE_Deferred; + this.o = () => { + this.i++, this.currentUser = this.u(), r.resolve(), r = new __PRIVATE_Deferred, + e.enqueueRetryable((() => __PRIVATE_guardedChangeListener(this.currentUser))); + }; + const __PRIVATE_awaitNextToken = () => { + const t = r; + e.enqueueRetryable((async () => { + await t.promise, await __PRIVATE_guardedChangeListener(this.currentUser); + })); + }, __PRIVATE_registerAuth = e => { + __PRIVATE_logDebug("FirebaseAuthCredentialsProvider", "Auth detected"), this.auth = e, + this.o && (this.auth.addAuthTokenListener(this.o), __PRIVATE_awaitNextToken()); + }; + this.t.onInit((e => __PRIVATE_registerAuth(e))), + // Our users can initialize Auth right after Firestore, so we give it + // a chance to register itself with the component framework before we + // determine whether to start up in unauthenticated mode. + setTimeout((() => { + if (!this.auth) { + const e = this.t.getImmediate({ + optional: !0 + }); + e ? __PRIVATE_registerAuth(e) : ( + // If auth is still not available, proceed with `null` user + __PRIVATE_logDebug("FirebaseAuthCredentialsProvider", "Auth not yet detected"), + r.resolve(), r = new __PRIVATE_Deferred); + } + }), 0), __PRIVATE_awaitNextToken(); + } + getToken() { + // Take note of the current value of the tokenCounter so that this method + // can fail (with an ABORTED error) if there is a token change while the + // request is outstanding. + const e = this.i, t = this.forceRefresh; + return this.forceRefresh = !1, this.auth ? this.auth.getToken(t).then((t => + // Cancel the request since the token changed while the request was + // outstanding so the response is potentially for a previous user (which + // user, we can't be sure). + this.i !== e ? (__PRIVATE_logDebug("FirebaseAuthCredentialsProvider", "getToken aborted due to token change."), + this.getToken()) : t ? (__PRIVATE_hardAssert("string" == typeof t.accessToken, 31837, { + l: t + }), new __PRIVATE_OAuthToken(t.accessToken, this.currentUser)) : null)) : Promise.resolve(null); + } + invalidateToken() { + this.forceRefresh = !0; + } + shutdown() { + this.auth && this.o && this.auth.removeAuthTokenListener(this.o), this.o = void 0; + } + // Auth.getUid() can return null even with a user logged in. It is because + // getUid() is synchronous, but the auth code populating Uid is asynchronous. + // This method should only be called in the AuthTokenListener callback + // to guarantee to get the actual user. + u() { + const e = this.auth && this.auth.getUid(); + return __PRIVATE_hardAssert(null === e || "string" == typeof e, 2055, { + h: e + }), new User(e); + } +} + +/* + * FirstPartyToken provides a fresh token each time its value + * is requested, because if the token is too old, requests will be rejected. + * Technically this may no longer be necessary since the SDK should gracefully + * recover from unauthenticated errors (see b/33147818 for context), but it's + * safer to keep the implementation as-is. + */ class __PRIVATE_FirstPartyToken { + constructor(e, t, n) { + this.P = e, this.T = t, this.I = n, this.type = "FirstParty", this.user = User.FIRST_PARTY, + this.A = new Map; + } + /** + * Gets an authorization token, using a provided factory function, or return + * null. + */ R() { + return this.I ? this.I() : null; + } + get headers() { + this.A.set("X-Goog-AuthUser", this.P); + // Use array notation to prevent minification + const e = this.R(); + return e && this.A.set("Authorization", e), this.T && this.A.set("X-Goog-Iam-Authorization-Token", this.T), + this.A; + } +} + +/* + * Provides user credentials required for the Firestore JavaScript SDK + * to authenticate the user, using technique that is only available + * to applications hosted by Google. + */ class __PRIVATE_FirstPartyAuthCredentialsProvider { + constructor(e, t, n) { + this.P = e, this.T = t, this.I = n; + } + getToken() { + return Promise.resolve(new __PRIVATE_FirstPartyToken(this.P, this.T, this.I)); + } + start(e, t) { + // Fire with initial uid. + e.enqueueRetryable((() => t(User.FIRST_PARTY))); + } + shutdown() {} + invalidateToken() {} +} + +class AppCheckToken { + constructor(e) { + this.value = e, this.type = "AppCheck", this.headers = new Map, e && e.length > 0 && this.headers.set("x-firebase-appcheck", this.value); + } +} + +class __PRIVATE_FirebaseAppCheckTokenProvider { + constructor(t, n) { + this.V = n, this.forceRefresh = !1, this.appCheck = null, this.m = null, this.p = null, + _isFirebaseServerApp(t) && t.settings.appCheckToken && (this.p = t.settings.appCheckToken); + } + start(e, t) { + __PRIVATE_hardAssert(void 0 === this.o, 3512); + const onTokenChanged = e => { + null != e.error && __PRIVATE_logDebug("FirebaseAppCheckTokenProvider", `Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`); + const n = e.token !== this.m; + return this.m = e.token, __PRIVATE_logDebug("FirebaseAppCheckTokenProvider", `Received ${n ? "new" : "existing"} token.`), + n ? t(e.token) : Promise.resolve(); + }; + this.o = t => { + e.enqueueRetryable((() => onTokenChanged(t))); + }; + const __PRIVATE_registerAppCheck = e => { + __PRIVATE_logDebug("FirebaseAppCheckTokenProvider", "AppCheck detected"), this.appCheck = e, + this.o && this.appCheck.addTokenListener(this.o); + }; + this.V.onInit((e => __PRIVATE_registerAppCheck(e))), + // Our users can initialize AppCheck after Firestore, so we give it + // a chance to register itself with the component framework. + setTimeout((() => { + if (!this.appCheck) { + const e = this.V.getImmediate({ + optional: !0 + }); + e ? __PRIVATE_registerAppCheck(e) : + // If AppCheck is still not available, proceed without it. + __PRIVATE_logDebug("FirebaseAppCheckTokenProvider", "AppCheck not yet detected"); + } + }), 0); + } + getToken() { + if (this.p) return Promise.resolve(new AppCheckToken(this.p)); + const e = this.forceRefresh; + return this.forceRefresh = !1, this.appCheck ? this.appCheck.getToken(e).then((e => e ? (__PRIVATE_hardAssert("string" == typeof e.token, 44558, { + tokenResult: e + }), this.m = e.token, new AppCheckToken(e.token)) : null)) : Promise.resolve(null); + } + invalidateToken() { + this.forceRefresh = !0; + } + shutdown() { + this.appCheck && this.o && this.appCheck.removeTokenListener(this.o), this.o = void 0; + } +} + +/** + * An AppCheck token provider that always yields an empty token. + * @internal + */ class __PRIVATE_EmptyAppCheckTokenProvider { + getToken() { + return Promise.resolve(new AppCheckToken("")); + } + invalidateToken() {} + start(e, t) {} + shutdown() {} +} + +/** + * Builds a CredentialsProvider depending on the type of + * the credentials passed in. + */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Generates `nBytes` of random bytes. + * + * If `nBytes < 0` , an error will be thrown. + */ +function __PRIVATE_randomBytes(e) { + // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available. + const t = + // eslint-disable-next-line @typescript-eslint/no-explicit-any + "undefined" != typeof self && (self.crypto || self.msCrypto), n = new Uint8Array(e); + if (t && "function" == typeof t.getRandomValues) t.getRandomValues(n); else + // Falls back to Math.random + for (let t = 0; t < e; t++) n[t] = Math.floor(256 * Math.random()); + return n; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A utility class for generating unique alphanumeric IDs of a specified length. + * + * @internal + * Exported internally for testing purposes. + */ class __PRIVATE_AutoId { + static newId() { + // Alphanumeric characters + const e = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", t = 62 * Math.floor(256 / 62); + // The largest byte value that is a multiple of `char.length`. + let n = ""; + for (;n.length < 20; ) { + const r = __PRIVATE_randomBytes(40); + for (let i = 0; i < r.length; ++i) + // Only accept values that are [0, maxMultiple), this ensures they can + // be evenly mapped to indices of `chars` via a modulo operation. + n.length < 20 && r[i] < t && (n += e.charAt(r[i] % 62)); + } + return n; + } +} + +function __PRIVATE_primitiveComparator(e, t) { + return e < t ? -1 : e > t ? 1 : 0; +} + +/** Compare strings in UTF-8 encoded byte order */ function __PRIVATE_compareUtf8Strings(e, t) { + // Find the first differing character (a.k.a. "UTF-16 code unit") in the two strings and, + // if found, use that character to determine the relative ordering of the two strings as a + // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by + // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8 + // and UTF-16 happen to represent Unicode code points. + // After finding the first pair of differing characters, there are two cases: + // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or + // both are surrogates from a surrogate pair (that collectively represent code points greater + // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the + // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is + // sufficient. + // Case 2: One character is a surrogate and the other is not. In this case the surrogate- + // containing string is always ordered after the non-surrogate. This is because surrogates are + // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations + // and are lexicographically greater than the 1, 2, or 3-byte representations of code points + // less than or equal to 0xFFFF. + // An example of why Case 2 is required is comparing the following two Unicode code points: + // |-----------------------|------------|---------------------|-----------------| + // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding | + // |-----------------------|------------|---------------------|-----------------| + // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD | + // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 | + // |-----------------------|------------|---------------------|-----------------| + // A lexicographical comparison of the UTF-8 encodings of these code points would order + // "Replacement Character" _before_ "Grinning Face" because 0xEF is less than 0xF0. However, a + // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously + // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out, + // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate + // pair with those that do not. + const n = Math.min(e.length, t.length); + for (let r = 0; r < n; r++) { + const n = e.charAt(r), i = t.charAt(r); + if (n !== i) return __PRIVATE_isSurrogate(n) === __PRIVATE_isSurrogate(i) ? __PRIVATE_primitiveComparator(n, i) : __PRIVATE_isSurrogate(n) ? 1 : -1; + } + // Use the lengths of the strings to determine the overall comparison result since either the + // strings were equal or one is a prefix of the other. + return __PRIVATE_primitiveComparator(e.length, t.length); +} + +const B = 55296, L = 57343; + +function __PRIVATE_isSurrogate(e) { + const t = e.charCodeAt(0); + return t >= B && t <= L; +} + +/** Helper to compare arrays using isEqual(). */ function __PRIVATE_arrayEquals(e, t, n) { + return e.length === t.length && e.every(((e, r) => n(e, t[r]))); +} + +/** + * Returns the immediate lexicographically-following string. This is useful to + * construct an inclusive range for indexeddb iterators. + */ function __PRIVATE_immediateSuccessor(e) { + // Return the input string, with an additional NUL byte appended. + return e + "\0"; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const k = "__name__"; + +/** + * Path represents an ordered sequence of string segments. + */ class BasePath { + constructor(e, t, n) { + void 0 === t ? t = 0 : t > e.length && fail(637, { + offset: t, + range: e.length + }), void 0 === n ? n = e.length - t : n > e.length - t && fail(1746, { + length: n, + range: e.length - t + }), this.segments = e, this.offset = t, this.len = n; + } + get length() { + return this.len; + } + isEqual(e) { + return 0 === BasePath.comparator(this, e); + } + child(e) { + const t = this.segments.slice(this.offset, this.limit()); + return e instanceof BasePath ? e.forEach((e => { + t.push(e); + })) : t.push(e), this.construct(t); + } + /** The index of one past the last segment of the path. */ limit() { + return this.offset + this.length; + } + popFirst(e) { + return e = void 0 === e ? 1 : e, this.construct(this.segments, this.offset + e, this.length - e); + } + popLast() { + return this.construct(this.segments, this.offset, this.length - 1); + } + firstSegment() { + return this.segments[this.offset]; + } + lastSegment() { + return this.get(this.length - 1); + } + get(e) { + return this.segments[this.offset + e]; + } + isEmpty() { + return 0 === this.length; + } + isPrefixOf(e) { + if (e.length < this.length) return !1; + for (let t = 0; t < this.length; t++) if (this.get(t) !== e.get(t)) return !1; + return !0; + } + isImmediateParentOf(e) { + if (this.length + 1 !== e.length) return !1; + for (let t = 0; t < this.length; t++) if (this.get(t) !== e.get(t)) return !1; + return !0; + } + forEach(e) { + for (let t = this.offset, n = this.limit(); t < n; t++) e(this.segments[t]); + } + toArray() { + return this.segments.slice(this.offset, this.limit()); + } + /** + * Compare 2 paths segment by segment, prioritizing numeric IDs + * (e.g., "__id123__") in numeric ascending order, followed by string + * segments in lexicographical order. + */ static comparator(e, t) { + const n = Math.min(e.length, t.length); + for (let r = 0; r < n; r++) { + const n = BasePath.compareSegments(e.get(r), t.get(r)); + if (0 !== n) return n; + } + return __PRIVATE_primitiveComparator(e.length, t.length); + } + static compareSegments(e, t) { + const n = BasePath.isNumericId(e), r = BasePath.isNumericId(t); + return n && !r ? -1 : !n && r ? 1 : n && r ? BasePath.extractNumericId(e).compare(BasePath.extractNumericId(t)) : __PRIVATE_compareUtf8Strings(e, t); + } + // Checks if a segment is a numeric ID (starts with "__id" and ends with "__"). + static isNumericId(e) { + return e.startsWith("__id") && e.endsWith("__"); + } + static extractNumericId(e) { + return Integer.fromString(e.substring(4, e.length - 2)); + } +} + +/** + * A slash-separated path for navigating resources (documents and collections) + * within Firestore. + * + * @internal + */ class ResourcePath extends BasePath { + construct(e, t, n) { + return new ResourcePath(e, t, n); + } + canonicalString() { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + return this.toArray().join("/"); + } + toString() { + return this.canonicalString(); + } + /** + * Returns a string representation of this path + * where each path segment has been encoded with + * `encodeURIComponent`. + */ toUriEncodedString() { + return this.toArray().map(encodeURIComponent).join("/"); + } + /** + * Creates a resource path from the given slash-delimited string. If multiple + * arguments are provided, all components are combined. Leading and trailing + * slashes from all components are ignored. + */ static fromString(...e) { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + const t = []; + for (const n of e) { + if (n.indexOf("//") >= 0) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid segment (${n}). Paths must not contain // in them.`); + // Strip leading and trailing slashed. + t.push(...n.split("/").filter((e => e.length > 0))); + } + return new ResourcePath(t); + } + static emptyPath() { + return new ResourcePath([]); + } +} + +const q = /^[_a-zA-Z][_a-zA-Z0-9]*$/; + +/** + * A dot-separated path for navigating sub-objects within a document. + * @internal + */ class FieldPath$1 extends BasePath { + construct(e, t, n) { + return new FieldPath$1(e, t, n); + } + /** + * Returns true if the string could be used as a segment in a field path + * without escaping. + */ static isValidIdentifier(e) { + return q.test(e); + } + canonicalString() { + return this.toArray().map((e => (e = e.replace(/\\/g, "\\\\").replace(/`/g, "\\`"), + FieldPath$1.isValidIdentifier(e) || (e = "`" + e + "`"), e))).join("."); + } + toString() { + return this.canonicalString(); + } + /** + * Returns true if this field references the key of a document. + */ isKeyField() { + return 1 === this.length && this.get(0) === k; + } + /** + * The field designating the key of a document. + */ static keyField() { + return new FieldPath$1([ k ]); + } + /** + * Parses a field string from the given server-formatted string. + * + * - Splitting the empty string is not allowed (for now at least). + * - Empty segments within the string (e.g. if there are two consecutive + * separators) are not allowed. + * + * TODO(b/37244157): we should make this more strict. Right now, it allows + * non-identifier path components, even if they aren't escaped. + */ static fromServerFormat(e) { + const t = []; + let n = "", r = 0; + const __PRIVATE_addCurrentSegment = () => { + if (0 === n.length) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`); + t.push(n), n = ""; + }; + let i = !1; + for (;r < e.length; ) { + const t = e[r]; + if ("\\" === t) { + if (r + 1 === e.length) throw new FirestoreError(N.INVALID_ARGUMENT, "Path has trailing escape character: " + e); + const t = e[r + 1]; + if ("\\" !== t && "." !== t && "`" !== t) throw new FirestoreError(N.INVALID_ARGUMENT, "Path has invalid escape sequence: " + e); + n += t, r += 2; + } else "`" === t ? (i = !i, r++) : "." !== t || i ? (n += t, r++) : (__PRIVATE_addCurrentSegment(), + r++); + } + if (__PRIVATE_addCurrentSegment(), i) throw new FirestoreError(N.INVALID_ARGUMENT, "Unterminated ` in path: " + e); + return new FieldPath$1(t); + } + static emptyPath() { + return new FieldPath$1([]); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @internal + */ class DocumentKey { + constructor(e) { + this.path = e; + } + static fromPath(e) { + return new DocumentKey(ResourcePath.fromString(e)); + } + static fromName(e) { + return new DocumentKey(ResourcePath.fromString(e).popFirst(5)); + } + static empty() { + return new DocumentKey(ResourcePath.emptyPath()); + } + get collectionGroup() { + return this.path.popLast().lastSegment(); + } + /** Returns true if the document is in the specified collectionId. */ hasCollectionId(e) { + return this.path.length >= 2 && this.path.get(this.path.length - 2) === e; + } + /** Returns the collection group (i.e. the name of the parent collection) for this key. */ getCollectionGroup() { + return this.path.get(this.path.length - 2); + } + /** Returns the fully qualified path to the parent collection. */ getCollectionPath() { + return this.path.popLast(); + } + isEqual(e) { + return null !== e && 0 === ResourcePath.comparator(this.path, e.path); + } + toString() { + return this.path.toString(); + } + static comparator(e, t) { + return ResourcePath.comparator(e.path, t.path); + } + static isDocumentKey(e) { + return e.length % 2 == 0; + } + /** + * Creates and returns a new document key with the given segments. + * + * @param segments - The segments of the path to the document + * @returns A new instance of DocumentKey + */ static fromSegments(e) { + return new DocumentKey(new ResourcePath(e.slice())); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_validateNonEmptyArgument(e, t, n) { + if (!n) throw new FirestoreError(N.INVALID_ARGUMENT, `Function ${e}() cannot be called with an empty ${t}.`); +} + +/** + * Validates that two boolean options are not set at the same time. + * @internal + */ function __PRIVATE_validateIsNotUsedTogether(e, t, n, r) { + if (!0 === t && !0 === r) throw new FirestoreError(N.INVALID_ARGUMENT, `${e} and ${n} cannot be used together.`); +} + +/** + * Validates that `path` refers to a document (indicated by the fact it contains + * an even numbers of segments). + */ function __PRIVATE_validateDocumentPath(e) { + if (!DocumentKey.isDocumentKey(e)) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`); +} + +/** + * Validates that `path` refers to a collection (indicated by the fact it + * contains an odd numbers of segments). + */ function __PRIVATE_validateCollectionPath(e) { + if (DocumentKey.isDocumentKey(e)) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`); +} + +/** + * Returns true if it's a non-null object without a custom prototype + * (i.e. excludes Array, Date, etc.). + */ function __PRIVATE_isPlainObject(e) { + return "object" == typeof e && null !== e && (Object.getPrototypeOf(e) === Object.prototype || null === Object.getPrototypeOf(e)); +} + +/** Returns a string describing the type / value of the provided input. */ function __PRIVATE_valueDescription(e) { + if (void 0 === e) return "undefined"; + if (null === e) return "null"; + if ("string" == typeof e) return e.length > 20 && (e = `${e.substring(0, 20)}...`), + JSON.stringify(e); + if ("number" == typeof e || "boolean" == typeof e) return "" + e; + if ("object" == typeof e) { + if (e instanceof Array) return "an array"; + { + const t = + /** try to get the constructor name for an object. */ + function __PRIVATE_tryGetCustomObjectType(e) { + if (e.constructor) return e.constructor.name; + return null; + } + /** + * Casts `obj` to `T`, optionally unwrapping Compat types to expose the + * underlying instance. Throws if `obj` is not an instance of `T`. + * + * This cast is used in the Lite and Full SDK to verify instance types for + * arguments passed to the public API. + * @internal + */ (e); + return t ? `a custom ${t} object` : "an object"; + } + } + return "function" == typeof e ? "a function" : fail(12329, { + type: typeof e + }); +} + +function __PRIVATE_cast(e, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +t) { + if ("_delegate" in e && ( + // Unwrap Compat types + // eslint-disable-next-line @typescript-eslint/no-explicit-any + e = e._delegate), !(e instanceof t)) { + if (t.name === e.constructor.name) throw new FirestoreError(N.INVALID_ARGUMENT, "Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?"); + { + const n = __PRIVATE_valueDescription(e); + throw new FirestoreError(N.INVALID_ARGUMENT, `Expected type '${t.name}', but it was: ${n}`); + } + } + return e; +} + +function __PRIVATE_validatePositiveNumber(e, t) { + if (t <= 0) throw new FirestoreError(N.INVALID_ARGUMENT, `Function ${e}() requires a positive number, but it was: ${t}.`); +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Helper function to define a JSON schema {@link Property}. + * @private + * @internal + */ function property(e, t) { + const n = { + typeString: e + }; + return t && (n.value = t), n; +} + +/** + * Validates the JSON object based on the provided schema, and narrows the type to the provided + * JSON schema. + * @private + * @internal + * + * @param json A JSON object to validate. + * @param scheme a {@link JsonSchema} that defines the properties to validate. + * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise. + */ function __PRIVATE_validateJSON(e, t) { + if (!__PRIVATE_isPlainObject(e)) throw new FirestoreError(N.INVALID_ARGUMENT, "JSON must be an object"); + let n; + for (const r in t) if (t[r]) { + const i = t[r].typeString, s = "value" in t[r] ? { + value: t[r].value + } : void 0; + if (!(r in e)) { + n = `JSON missing required field: '${r}'`; + break; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const o = e[r]; + if (i && typeof o !== i) { + n = `JSON field '${r}' must be a ${i}.`; + break; + } + if (void 0 !== s && o !== s.value) { + n = `Expected '${r}' field to equal '${s.value}'`; + break; + } + } + if (n) throw new FirestoreError(N.INVALID_ARGUMENT, n); + return !0; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z). +const Q = -62135596800, $ = 1e6; + +// Number of nanoseconds in a millisecond. +/** + * A `Timestamp` represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. + * + * It is encoded using the Proleptic Gregorian Calendar which extends the + * Gregorian calendar backwards to year one. It is encoded assuming all minutes + * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59.999999999Z. + * + * For examples and further specifications, refer to the + * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. + */ +class Timestamp { + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns a new timestamp representing the current date. + */ + static now() { + return Timestamp.fromMillis(Date.now()); + } + /** + * Creates a new timestamp from the given date. + * + * @param date - The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the given + * date. + */ static fromDate(e) { + return Timestamp.fromMillis(e.getTime()); + } + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds - Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the given + * number of milliseconds. + */ static fromMillis(e) { + const t = Math.floor(e / 1e3), n = Math.floor((e - 1e3 * t) * $); + return new Timestamp(t, n); + } + /** + * Creates a new timestamp. + * + * @param seconds - The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds - The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + e, + /** + * The fractions of a second at nanosecond resolution.* + */ + t) { + if (this.seconds = e, this.nanoseconds = t, t < 0) throw new FirestoreError(N.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + t); + if (t >= 1e9) throw new FirestoreError(N.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + t); + if (e < Q) throw new FirestoreError(N.INVALID_ARGUMENT, "Timestamp seconds out of range: " + e); + // This will break in the year 10,000. + if (e >= 253402300800) throw new FirestoreError(N.INVALID_ARGUMENT, "Timestamp seconds out of range: " + e); + } + /** + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ toDate() { + return new Date(this.toMillis()); + } + /** + * Converts a `Timestamp` to a numeric timestamp (in milliseconds since + * epoch). This operation causes a loss of precision. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ toMillis() { + return 1e3 * this.seconds + this.nanoseconds / $; + } + _compareTo(e) { + return this.seconds === e.seconds ? __PRIVATE_primitiveComparator(this.nanoseconds, e.nanoseconds) : __PRIVATE_primitiveComparator(this.seconds, e.seconds); + } + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other - The `Timestamp` to compare against. + * @returns true if this `Timestamp` is equal to the provided one. + */ isEqual(e) { + return e.seconds === this.seconds && e.nanoseconds === this.nanoseconds; + } + /** Returns a textual representation of this `Timestamp`. */ toString() { + return "Timestamp(seconds=" + this.seconds + ", nanoseconds=" + this.nanoseconds + ")"; + } + /** + * Returns a JSON-serializable representation of this `Timestamp`. + */ toJSON() { + return { + type: Timestamp._jsonSchemaVersion, + seconds: this.seconds, + nanoseconds: this.nanoseconds + }; + } + /** + * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}. + */ static fromJSON(e) { + if (__PRIVATE_validateJSON(e, Timestamp._jsonSchema)) return new Timestamp(e.seconds, e.nanoseconds); + } + /** + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. + */ valueOf() { + // This method returns a string of the form . where + // is translated to have a non-negative value and both + // and are left-padded with zeroes to be a consistent length. + // Strings with this format then have a lexicographical ordering that matches + // the expected ordering. The translation is done to avoid having + // a leading negative sign (i.e. a leading '-' character) in its string + // representation, which would affect its lexicographical ordering. + const e = this.seconds - Q; + // Note: Up to 12 decimal digits are required to represent all valid + // 'seconds' values. + return String(e).padStart(12, "0") + "." + String(this.nanoseconds).padStart(9, "0"); + } +} + +Timestamp._jsonSchemaVersion = "firestore/timestamp/1.0", Timestamp._jsonSchema = { + type: property("string", Timestamp._jsonSchemaVersion), + seconds: property("number"), + nanoseconds: property("number") +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A version of a document in Firestore. This corresponds to the version + * timestamp, such as update_time or read_time. + */ +class SnapshotVersion { + static fromTimestamp(e) { + return new SnapshotVersion(e); + } + static min() { + return new SnapshotVersion(new Timestamp(0, 0)); + } + static max() { + return new SnapshotVersion(new Timestamp(253402300799, 999999999)); + } + constructor(e) { + this.timestamp = e; + } + compareTo(e) { + return this.timestamp._compareTo(e.timestamp); + } + isEqual(e) { + return this.timestamp.isEqual(e.timestamp); + } + /** Returns a number representation of the version for use in spec tests. */ toMicroseconds() { + // Convert to microseconds. + return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3; + } + toString() { + return "SnapshotVersion(" + this.timestamp.toString() + ")"; + } + toTimestamp() { + return this.timestamp; + } +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The initial mutation batch id for each index. Gets updated during index + * backfill. + */ const U = -1; + +/** + * The initial sequence number for each index. Gets updated during index + * backfill. + */ +/** + * An index definition for field indexes in Firestore. + * + * Every index is associated with a collection. The definition contains a list + * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or + * `CONTAINS` for ArrayContains/ArrayContainsAny queries). + * + * Unlike the backend, the SDK does not differentiate between collection or + * collection group-scoped indices. Every index can be used for both single + * collection and collection group queries. + */ +class FieldIndex { + constructor( + /** + * The index ID. Returns -1 if the index ID is not available (e.g. the index + * has not yet been persisted). + */ + e, + /** The collection ID this index applies to. */ + t, + /** The field segments for this index. */ + n, + /** Shows how up-to-date the index is for the current user. */ + r) { + this.indexId = e, this.collectionGroup = t, this.fields = n, this.indexState = r; + } +} + +/** An ID for an index that has not yet been added to persistence. */ +/** Returns the ArrayContains/ArrayContainsAny segment for this index. */ +function __PRIVATE_fieldIndexGetArraySegment(e) { + return e.fields.find((e => 2 /* IndexKind.CONTAINS */ === e.kind)); +} + +/** Returns all directional (ascending/descending) segments for this index. */ function __PRIVATE_fieldIndexGetDirectionalSegments(e) { + return e.fields.filter((e => 2 /* IndexKind.CONTAINS */ !== e.kind)); +} + +/** + * Returns the order of the document key component for the given index. + * + * PORTING NOTE: This is only used in the Web IndexedDb implementation. + */ +/** + * Compares indexes by collection group and segments. Ignores update time and + * index ID. + */ +function __PRIVATE_fieldIndexSemanticComparator(e, t) { + let n = __PRIVATE_primitiveComparator(e.collectionGroup, t.collectionGroup); + if (0 !== n) return n; + for (let r = 0; r < Math.min(e.fields.length, t.fields.length); ++r) if (n = __PRIVATE_indexSegmentComparator(e.fields[r], t.fields[r]), + 0 !== n) return n; + return __PRIVATE_primitiveComparator(e.fields.length, t.fields.length); +} + +/** Returns a debug representation of the field index */ FieldIndex.UNKNOWN_ID = -1; + +/** An index component consisting of field path and index type. */ +class IndexSegment { + constructor( + /** The field path of the component. */ + e, + /** The fields sorting order. */ + t) { + this.fieldPath = e, this.kind = t; + } +} + +function __PRIVATE_indexSegmentComparator(e, t) { + const n = FieldPath$1.comparator(e.fieldPath, t.fieldPath); + return 0 !== n ? n : __PRIVATE_primitiveComparator(e.kind, t.kind); +} + +/** + * Stores the "high water mark" that indicates how updated the Index is for the + * current user. + */ class IndexState { + constructor( + /** + * Indicates when the index was last updated (relative to other indexes). + */ + e, + /** The the latest indexed read time, document and batch id. */ + t) { + this.sequenceNumber = e, this.offset = t; + } + /** The state of an index that has not yet been backfilled. */ static empty() { + return new IndexState(0, IndexOffset.min()); + } +} + +/** + * Creates an offset that matches all documents with a read time higher than + * `readTime`. + */ function __PRIVATE_newIndexOffsetSuccessorFromReadTime(e, t) { + // We want to create an offset that matches all documents with a read time + // greater than the provided read time. To do so, we technically need to + // create an offset for `(readTime, MAX_DOCUMENT_KEY)`. While we could use + // Unicode codepoints to generate MAX_DOCUMENT_KEY, it is much easier to use + // `(readTime + 1, DocumentKey.empty())` since `> DocumentKey.empty()` matches + // all valid document IDs. + const n = e.toTimestamp().seconds, r = e.toTimestamp().nanoseconds + 1, i = SnapshotVersion.fromTimestamp(1e9 === r ? new Timestamp(n + 1, 0) : new Timestamp(n, r)); + return new IndexOffset(i, DocumentKey.empty(), t); +} + +/** Creates a new offset based on the provided document. */ function __PRIVATE_newIndexOffsetFromDocument(e) { + return new IndexOffset(e.readTime, e.key, U); +} + +/** + * Stores the latest read time, document and batch ID that were processed for an + * index. + */ class IndexOffset { + constructor( + /** + * The latest read time version that has been indexed by Firestore for this + * field index. + */ + e, + /** + * The key of the last document that was indexed for this query. Use + * `DocumentKey.empty()` if no document has been indexed. + */ + t, + /* + * The largest mutation batch id that's been processed by Firestore. + */ + n) { + this.readTime = e, this.documentKey = t, this.largestBatchId = n; + } + /** Returns an offset that sorts before all regular offsets. */ static min() { + return new IndexOffset(SnapshotVersion.min(), DocumentKey.empty(), U); + } + /** Returns an offset that sorts after all regular offsets. */ static max() { + return new IndexOffset(SnapshotVersion.max(), DocumentKey.empty(), U); + } +} + +function __PRIVATE_indexOffsetComparator(e, t) { + let n = e.readTime.compareTo(t.readTime); + return 0 !== n ? n : (n = DocumentKey.comparator(e.documentKey, t.documentKey), + 0 !== n ? n : __PRIVATE_primitiveComparator(e.largestBatchId, t.largestBatchId)); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const K = "The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab."; + +/** + * A base class representing a persistence transaction, encapsulating both the + * transaction's sequence numbers as well as a list of onCommitted listeners. + * + * When you call Persistence.runTransaction(), it will create a transaction and + * pass it to your callback. You then pass it to any method that operates + * on persistence. + */ class PersistenceTransaction { + constructor() { + this.onCommittedListeners = []; + } + addOnCommittedListener(e) { + this.onCommittedListeners.push(e); + } + raiseOnCommittedEvent() { + this.onCommittedListeners.forEach((e => e())); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Verifies the error thrown by a LocalStore operation. If a LocalStore + * operation fails because the primary lease has been taken by another client, + * we ignore the error (the persistence layer will immediately call + * `applyPrimaryLease` to propagate the primary state change). All other errors + * are re-thrown. + * + * @param err - An error returned by a LocalStore operation. + * @returns A Promise that resolves after we recovered, or the original error. + */ async function __PRIVATE_ignoreIfPrimaryLeaseLoss(e) { + if (e.code !== N.FAILED_PRECONDITION || e.message !== K) throw e; + __PRIVATE_logDebug("LocalStore", "Unexpectedly lost primary lease"); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * PersistencePromise is essentially a re-implementation of Promise except + * it has a .next() method instead of .then() and .next() and .catch() callbacks + * are executed synchronously when a PersistencePromise resolves rather than + * asynchronously (Promise implementations use setImmediate() or similar). + * + * This is necessary to interoperate with IndexedDB which will automatically + * commit transactions if control is returned to the event loop without + * synchronously initiating another operation on the transaction. + * + * NOTE: .then() and .catch() only allow a single consumer, unlike normal + * Promises. + */ class PersistencePromise { + constructor(e) { + // NOTE: next/catchCallback will always point to our own wrapper functions, + // not the user's raw next() or catch() callbacks. + this.nextCallback = null, this.catchCallback = null, + // When the operation resolves, we'll set result or error and mark isDone. + this.result = void 0, this.error = void 0, this.isDone = !1, + // Set to true when .then() or .catch() are called and prevents additional + // chaining. + this.callbackAttached = !1, e((e => { + this.isDone = !0, this.result = e, this.nextCallback && + // value should be defined unless T is Void, but we can't express + // that in the type system. + this.nextCallback(e); + }), (e => { + this.isDone = !0, this.error = e, this.catchCallback && this.catchCallback(e); + })); + } + catch(e) { + return this.next(void 0, e); + } + next(e, t) { + return this.callbackAttached && fail(59440), this.callbackAttached = !0, this.isDone ? this.error ? this.wrapFailure(t, this.error) : this.wrapSuccess(e, this.result) : new PersistencePromise(((n, r) => { + this.nextCallback = t => { + this.wrapSuccess(e, t).next(n, r); + }, this.catchCallback = e => { + this.wrapFailure(t, e).next(n, r); + }; + })); + } + toPromise() { + return new Promise(((e, t) => { + this.next(e, t); + })); + } + wrapUserFunction(e) { + try { + const t = e(); + return t instanceof PersistencePromise ? t : PersistencePromise.resolve(t); + } catch (e) { + return PersistencePromise.reject(e); + } + } + wrapSuccess(e, t) { + return e ? this.wrapUserFunction((() => e(t))) : PersistencePromise.resolve(t); + } + wrapFailure(e, t) { + return e ? this.wrapUserFunction((() => e(t))) : PersistencePromise.reject(t); + } + static resolve(e) { + return new PersistencePromise(((t, n) => { + t(e); + })); + } + static reject(e) { + return new PersistencePromise(((t, n) => { + n(e); + })); + } + static waitFor( + // Accept all Promise types in waitFor(). + // eslint-disable-next-line @typescript-eslint/no-explicit-any + e) { + return new PersistencePromise(((t, n) => { + let r = 0, i = 0, s = !1; + e.forEach((e => { + ++r, e.next((() => { + ++i, s && i === r && t(); + }), (e => n(e))); + })), s = !0, i === r && t(); + })); + } + /** + * Given an array of predicate functions that asynchronously evaluate to a + * boolean, implements a short-circuiting `or` between the results. Predicates + * will be evaluated until one of them returns `true`, then stop. The final + * result will be whether any of them returned `true`. + */ static or(e) { + let t = PersistencePromise.resolve(!1); + for (const n of e) t = t.next((e => e ? PersistencePromise.resolve(e) : n())); + return t; + } + static forEach(e, t) { + const n = []; + return e.forEach(((e, r) => { + n.push(t.call(this, e, r)); + })), this.waitFor(n); + } + /** + * Concurrently map all array elements through asynchronous function. + */ static mapArray(e, t) { + return new PersistencePromise(((n, r) => { + const i = e.length, s = new Array(i); + let o = 0; + for (let _ = 0; _ < i; _++) { + const a = _; + t(e[a]).next((e => { + s[a] = e, ++o, o === i && n(s); + }), (e => r(e))); + } + })); + } + /** + * An alternative to recursive PersistencePromise calls, that avoids + * potential memory problems from unbounded chains of promises. + * + * The `action` will be called repeatedly while `condition` is true. + */ static doWhile(e, t) { + return new PersistencePromise(((n, r) => { + const process = () => { + !0 === e() ? t().next((() => { + process(); + }), r) : n(); + }; + process(); + })); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// References to `indexedDB` are guarded by SimpleDb.isAvailable() and getGlobal() +/* eslint-disable no-restricted-globals */ const W = "SimpleDb"; + +/** + * The maximum number of retry attempts for an IndexedDb transaction that fails + * with a DOMException. + */ +/** + * Wraps an IDBTransaction and exposes a store() method to get a handle to a + * specific object store. + */ +class __PRIVATE_SimpleDbTransaction { + static open(e, t, n, r) { + try { + return new __PRIVATE_SimpleDbTransaction(t, e.transaction(r, n)); + } catch (e) { + throw new __PRIVATE_IndexedDbTransactionError(t, e); + } + } + constructor(e, t) { + this.action = e, this.transaction = t, this.aborted = !1, + /** + * A `Promise` that resolves with the result of the IndexedDb transaction. + */ + this.S = new __PRIVATE_Deferred, this.transaction.oncomplete = () => { + this.S.resolve(); + }, this.transaction.onabort = () => { + t.error ? this.S.reject(new __PRIVATE_IndexedDbTransactionError(e, t.error)) : this.S.resolve(); + }, this.transaction.onerror = t => { + const n = __PRIVATE_checkForAndReportiOSError(t.target.error); + this.S.reject(new __PRIVATE_IndexedDbTransactionError(e, n)); + }; + } + get D() { + return this.S.promise; + } + abort(e) { + e && this.S.reject(e), this.aborted || (__PRIVATE_logDebug(W, "Aborting transaction:", e ? e.message : "Client-initiated abort"), + this.aborted = !0, this.transaction.abort()); + } + C() { + // If the browser supports V3 IndexedDB, we invoke commit() explicitly to + // speed up index DB processing if the event loop remains blocks. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const e = this.transaction; + this.aborted || "function" != typeof e.commit || e.commit(); + } + /** + * Returns a SimpleDbStore for the specified store. All + * operations performed on the SimpleDbStore happen within the context of this + * transaction and it cannot be used anymore once the transaction is + * completed. + * + * Note that we can't actually enforce that the KeyType and ValueType are + * correct, but they allow type safety through the rest of the consuming code. + */ store(e) { + const t = this.transaction.objectStore(e); + return new __PRIVATE_SimpleDbStore(t); + } +} + +/** + * Provides a wrapper around IndexedDb with a simplified interface that uses + * Promise-like return values to chain operations. Real promises cannot be used + * since .then() continuations are executed asynchronously (e.g. via + * .setImmediate), which would cause IndexedDB to end the transaction. + * See PersistencePromise for more details. + */ class __PRIVATE_SimpleDb { + /** Deletes the specified database. */ + static delete(e) { + __PRIVATE_logDebug(W, "Removing database:", e); + return __PRIVATE_wrapRequest(getGlobal().indexedDB.deleteDatabase(e)).toPromise(); + } + /** Returns true if IndexedDB is available in the current environment. */ static v() { + if (!isIndexedDBAvailable()) return !1; + if (__PRIVATE_SimpleDb.F()) return !0; + // We extensively use indexed array values and compound keys, + // which IE and Edge do not support. However, they still have indexedDB + // defined on the window, so we need to check for them here and make sure + // to return that persistence is not enabled for those browsers. + // For tracking support of this feature, see here: + // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/ + // Check the UA string to find out the browser. + const e = getUA(), t = __PRIVATE_SimpleDb.M(e), n = 0 < t && t < 10, r = __PRIVATE_getAndroidVersion(e), i = 0 < r && r < 4.5; + // IE 10 + // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)'; + // IE 11 + // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko'; + // Edge + // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, + // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0'; + // iOS Safari: Disable for users running iOS version < 10. + return !(e.indexOf("MSIE ") > 0 || e.indexOf("Trident/") > 0 || e.indexOf("Edge/") > 0 || n || i); + } + /** + * Returns true if the backing IndexedDB store is the Node IndexedDBShim + * (see https://github.com/axemclion/IndexedDBShim). + */ static F() { + return "undefined" != typeof process && "YES" === process.__PRIVATE_env?.__PRIVATE_USE_MOCK_PERSISTENCE; + } + /** Helper to get a typed SimpleDbStore from a transaction. */ static O(e, t) { + return e.store(t); + } + // visible for testing + /** Parse User Agent to determine iOS version. Returns -1 if not found. */ + static M(e) { + const t = e.match(/i(?:phone|pad|pod) os ([\d_]+)/i), n = t ? t[1].split("_").slice(0, 2).join(".") : "-1"; + return Number(n); + } + /* + * Creates a new SimpleDb wrapper for IndexedDb database `name`. + * + * Note that `version` must not be a downgrade. IndexedDB does not support + * downgrading the schema version. We currently do not support any way to do + * versioning outside of IndexedDB's versioning mechanism, as only + * version-upgrade transactions are allowed to do things like create + * objectstores. + */ constructor(e, t, n) { + this.name = e, this.version = t, this.N = n, this.B = null; + // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the + // bug we're checking for should exist in iOS >= 12.2 and < 13, but for + // whatever reason it's much harder to hit after 12.2 so we only proactively + // log on 12.2. + 12.2 === __PRIVATE_SimpleDb.M(getUA()) && __PRIVATE_logError("Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround."); + } + /** + * Opens the specified database, creating or upgrading it if necessary. + */ async L(e) { + return this.db || (__PRIVATE_logDebug(W, "Opening database:", this.name), this.db = await new Promise(((t, n) => { + // TODO(mikelehen): Investigate browser compatibility. + // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB + // suggests IE9 and older WebKit browsers handle upgrade + // differently. They expect setVersion, as described here: + // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion + const r = indexedDB.open(this.name, this.version); + r.onsuccess = e => { + const n = e.target.result; + t(n); + }, r.onblocked = () => { + n(new __PRIVATE_IndexedDbTransactionError(e, "Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed.")); + }, r.onerror = t => { + const r = t.target.error; + "VersionError" === r.name ? n(new FirestoreError(N.FAILED_PRECONDITION, "A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")) : "InvalidStateError" === r.name ? n(new FirestoreError(N.FAILED_PRECONDITION, "Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: " + r)) : n(new __PRIVATE_IndexedDbTransactionError(e, r)); + }, r.onupgradeneeded = e => { + __PRIVATE_logDebug(W, 'Database "' + this.name + '" requires upgrade from version:', e.oldVersion); + const t = e.target.result; + this.N.k(t, r.transaction, e.oldVersion, this.version).next((() => { + __PRIVATE_logDebug(W, "Database upgrade to version " + this.version + " complete"); + })); + }; + }))), this.q && (this.db.onversionchange = e => this.q(e)), this.db; + } + $(e) { + this.q = e, this.db && (this.db.onversionchange = t => e(t)); + } + async runTransaction(e, t, n, r) { + const i = "readonly" === t; + let s = 0; + for (;;) { + ++s; + try { + this.db = await this.L(e); + const t = __PRIVATE_SimpleDbTransaction.open(this.db, e, i ? "readonly" : "readwrite", n), s = r(t).next((e => (t.C(), + e))).catch((e => ( + // Abort the transaction if there was an error. + t.abort(e), PersistencePromise.reject(e)))).toPromise(); + // As noted above, errors are propagated by aborting the transaction. So + // we swallow any error here to avoid the browser logging it as unhandled. + return s.catch((() => {})), + // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to + // fire), but still return the original transactionFnResult back to the + // caller. + await t.D, s; + } catch (e) { + const t = e, n = "FirebaseError" !== t.name && s < 3; + // TODO(schmidt-sebastian): We could probably be smarter about this and + // not retry exceptions that are likely unrecoverable (such as quota + // exceeded errors). + // Note: We cannot use an instanceof check for FirestoreException, since the + // exception is wrapped in a generic error by our async/await handling. + if (__PRIVATE_logDebug(W, "Transaction failed with error:", t.message, "Retrying:", n), + this.close(), !n) return Promise.reject(t); + } + } + } + close() { + this.db && this.db.close(), this.db = void 0; + } +} + +/** Parse User Agent to determine Android version. Returns -1 if not found. */ function __PRIVATE_getAndroidVersion(e) { + const t = e.match(/Android ([\d.]+)/i), n = t ? t[1].split(".").slice(0, 2).join(".") : "-1"; + return Number(n); +} + +/** + * A controller for iterating over a key range or index. It allows an iterate + * callback to delete the currently-referenced object, or jump to a new key + * within the key range or index. + */ class __PRIVATE_IterationController { + constructor(e) { + this.U = e, this.K = !1, this.W = null; + } + get isDone() { + return this.K; + } + get G() { + return this.W; + } + set cursor(e) { + this.U = e; + } + /** + * This function can be called to stop iteration at any point. + */ done() { + this.K = !0; + } + /** + * This function can be called to skip to that next key, which could be + * an index or a primary key. + */ j(e) { + this.W = e; + } + /** + * Delete the current cursor value from the object store. + * + * NOTE: You CANNOT do this with a keysOnly query. + */ delete() { + return __PRIVATE_wrapRequest(this.U.delete()); + } +} + +/** An error that wraps exceptions that thrown during IndexedDB execution. */ class __PRIVATE_IndexedDbTransactionError extends FirestoreError { + constructor(e, t) { + super(N.UNAVAILABLE, `IndexedDB transaction '${e}' failed: ${t}`), this.name = "IndexedDbTransactionError"; + } +} + +/** Verifies whether `e` is an IndexedDbTransactionError. */ function __PRIVATE_isIndexedDbTransactionError(e) { + // Use name equality, as instanceof checks on errors don't work with errors + // that wrap other errors. + return "IndexedDbTransactionError" === e.name; +} + +/** + * A wrapper around an IDBObjectStore providing an API that: + * + * 1) Has generic KeyType / ValueType parameters to provide strongly-typed + * methods for acting against the object store. + * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every + * method return a PersistencePromise instead. + * 3) Provides a higher-level API to avoid needing to do excessive wrapping of + * intermediate IndexedDB types (IDBCursorWithValue, etc.) + */ class __PRIVATE_SimpleDbStore { + constructor(e) { + this.store = e; + } + put(e, t) { + let n; + return void 0 !== t ? (__PRIVATE_logDebug(W, "PUT", this.store.name, e, t), n = this.store.put(t, e)) : (__PRIVATE_logDebug(W, "PUT", this.store.name, "", e), + n = this.store.put(e)), __PRIVATE_wrapRequest(n); + } + /** + * Adds a new value into an Object Store and returns the new key. Similar to + * IndexedDb's `add()`, this method will fail on primary key collisions. + * + * @param value - The object to write. + * @returns The key of the value to add. + */ add(e) { + __PRIVATE_logDebug(W, "ADD", this.store.name, e, e); + return __PRIVATE_wrapRequest(this.store.add(e)); + } + /** + * Gets the object with the specified key from the specified store, or null + * if no object exists with the specified key. + * + * @key The key of the object to get. + * @returns The object with the specified key or null if no object exists. + */ get(e) { + // We're doing an unsafe cast to ValueType. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return __PRIVATE_wrapRequest(this.store.get(e)).next((t => ( + // Normalize nonexistence to null. + void 0 === t && (t = null), __PRIVATE_logDebug(W, "GET", this.store.name, e, t), + t))); + } + delete(e) { + __PRIVATE_logDebug(W, "DELETE", this.store.name, e); + return __PRIVATE_wrapRequest(this.store.delete(e)); + } + /** + * If we ever need more of the count variants, we can add overloads. For now, + * all we need is to count everything in a store. + * + * Returns the number of rows in the store. + */ count() { + __PRIVATE_logDebug(W, "COUNT", this.store.name); + return __PRIVATE_wrapRequest(this.store.count()); + } + J(e, t) { + const n = this.options(e, t), r = n.index ? this.store.index(n.index) : this.store; + // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly + // 20% faster. + if ("function" == typeof r.getAll) { + const e = r.getAll(n.range); + return new PersistencePromise(((t, n) => { + e.onerror = e => { + n(e.target.error); + }, e.onsuccess = e => { + t(e.target.result); + }; + })); + } + { + const e = this.cursor(n), t = []; + return this.H(e, ((e, n) => { + t.push(n); + })).next((() => t)); + } + } + /** + * Loads the first `count` elements from the provided index range. Loads all + * elements if no limit is provided. + */ Y(e, t) { + const n = this.store.getAll(e, null === t ? void 0 : t); + return new PersistencePromise(((e, t) => { + n.onerror = e => { + t(e.target.error); + }, n.onsuccess = t => { + e(t.target.result); + }; + })); + } + Z(e, t) { + __PRIVATE_logDebug(W, "DELETE ALL", this.store.name); + const n = this.options(e, t); + n.X = !1; + const r = this.cursor(n); + return this.H(r, ((e, t, n) => n.delete())); + } + ee(e, t) { + let n; + t ? n = e : (n = {}, t = e); + const r = this.cursor(n); + return this.H(r, t); + } + /** + * Iterates over a store, but waits for the given callback to complete for + * each entry before iterating the next entry. This allows the callback to do + * asynchronous work to determine if this iteration should continue. + * + * The provided callback should return `true` to continue iteration, and + * `false` otherwise. + */ te(e) { + const t = this.cursor({}); + return new PersistencePromise(((n, r) => { + t.onerror = e => { + const t = __PRIVATE_checkForAndReportiOSError(e.target.error); + r(t); + }, t.onsuccess = t => { + const r = t.target.result; + r ? e(r.primaryKey, r.value).next((e => { + e ? r.continue() : n(); + })) : n(); + }; + })); + } + H(e, t) { + const n = []; + return new PersistencePromise(((r, i) => { + e.onerror = e => { + i(e.target.error); + }, e.onsuccess = e => { + const i = e.target.result; + if (!i) return void r(); + const s = new __PRIVATE_IterationController(i), o = t(i.primaryKey, i.value, s); + if (o instanceof PersistencePromise) { + const e = o.catch((e => (s.done(), PersistencePromise.reject(e)))); + n.push(e); + } + s.isDone ? r() : null === s.G ? i.continue() : i.continue(s.G); + }; + })).next((() => PersistencePromise.waitFor(n))); + } + options(e, t) { + let n; + return void 0 !== e && ("string" == typeof e ? n = e : t = e), { + index: n, + range: t + }; + } + cursor(e) { + let t = "next"; + if (e.reverse && (t = "prev"), e.index) { + const n = this.store.index(e.index); + return e.X ? n.openKeyCursor(e.range, t) : n.openCursor(e.range, t); + } + return this.store.openCursor(e.range, t); + } +} + +/** + * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror + * handlers to resolve / reject the PersistencePromise as appropriate. + */ function __PRIVATE_wrapRequest(e) { + return new PersistencePromise(((t, n) => { + e.onsuccess = e => { + const n = e.target.result; + t(n); + }, e.onerror = e => { + const t = __PRIVATE_checkForAndReportiOSError(e.target.error); + n(t); + }; + })); +} + +// Guard so we only report the error once. +let G = !1; + +function __PRIVATE_checkForAndReportiOSError(e) { + const t = __PRIVATE_SimpleDb.M(getUA()); + if (t >= 12.2 && t < 13) { + const t = "An internal error was encountered in the Indexed Database server"; + if (e.message.indexOf(t) >= 0) { + // Wrap error in a more descriptive one. + const e = new FirestoreError("internal", `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${t}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`); + return G || (G = !0, + // Throw a global exception outside of this promise chain, for the user to + // potentially catch. + setTimeout((() => { + throw e; + }), 0)), e; + } + } + return e; +} + +const z = "IndexBackfiller"; + +/** How long we wait to try running index backfill after SDK initialization. */ +/** This class is responsible for the scheduling of Index Backfiller. */ +class __PRIVATE_IndexBackfillerScheduler { + constructor(e, t) { + this.asyncQueue = e, this.ne = t, this.task = null; + } + start() { + this.re(15e3); + } + stop() { + this.task && (this.task.cancel(), this.task = null); + } + get started() { + return null !== this.task; + } + re(e) { + __PRIVATE_logDebug(z, `Scheduled in ${e}ms`), this.task = this.asyncQueue.enqueueAfterDelay("index_backfill" /* TimerId.IndexBackfill */ , e, (async () => { + this.task = null; + try { + const e = await this.ne.ie(); + __PRIVATE_logDebug(z, `Documents written: ${e}`); + } catch (e) { + __PRIVATE_isIndexedDbTransactionError(e) ? __PRIVATE_logDebug(z, "Ignoring IndexedDB error during index backfill: ", e) : await __PRIVATE_ignoreIfPrimaryLeaseLoss(e); + } + await this.re(6e4); + })); + } +} + +/** Implements the steps for backfilling indexes. */ class __PRIVATE_IndexBackfiller { + constructor( + /** + * LocalStore provides access to IndexManager and LocalDocumentView. + * These properties will update when the user changes. Consequently, + * making a local copy of IndexManager and LocalDocumentView will require + * updates over time. The simpler solution is to rely on LocalStore to have + * an up-to-date references to IndexManager and LocalDocumentStore. + */ + e, t) { + this.localStore = e, this.persistence = t; + } + async ie(e = 50) { + return this.persistence.runTransaction("Backfill Indexes", "readwrite-primary", (t => this.se(t, e))); + } + /** Writes index entries until the cap is reached. Returns the number of documents processed. */ se(e, t) { + const n = new Set; + let r = t, i = !0; + return PersistencePromise.doWhile((() => !0 === i && r > 0), (() => this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next((t => { + if (null !== t && !n.has(t)) return __PRIVATE_logDebug(z, `Processing collection: ${t}`), + this.oe(e, t, r).next((e => { + r -= e, n.add(t); + })); + i = !1; + })))).next((() => t - r)); + } + /** + * Writes entries for the provided collection group. Returns the number of documents processed. + */ oe(e, t, n) { + // Use the earliest offset of all field indexes to query the local cache. + return this.localStore.indexManager.getMinOffsetFromCollectionGroup(e, t).next((r => this.localStore.localDocuments.getNextDocuments(e, t, r, n).next((n => { + const i = n.changes; + return this.localStore.indexManager.updateIndexEntries(e, i).next((() => this._e(r, n))).next((n => (__PRIVATE_logDebug(z, `Updating offset: ${n}`), + this.localStore.indexManager.updateCollectionGroup(e, t, n)))).next((() => i.size)); + })))); + } + /** Returns the next offset based on the provided documents. */ _e(e, t) { + let n = e; + return t.changes.forEach(((e, t) => { + const r = __PRIVATE_newIndexOffsetFromDocument(t); + __PRIVATE_indexOffsetComparator(r, n) > 0 && (n = r); + })), new IndexOffset(n.readTime, n.documentKey, Math.max(t.batchId, e.largestBatchId)); + } +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to + * exceed. All subsequent calls to next will return increasing values. If provided with a + * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as + * well as write out sequence numbers that it produces via `next()`. + */ class __PRIVATE_ListenSequence { + constructor(e, t) { + this.previousValue = e, t && (t.sequenceNumberHandler = e => this.ae(e), this.ue = e => t.writeSequenceNumber(e)); + } + ae(e) { + return this.previousValue = Math.max(e, this.previousValue), this.previousValue; + } + next() { + const e = ++this.previousValue; + return this.ue && this.ue(e), e; + } +} + +__PRIVATE_ListenSequence.ce = -1; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Sentinel value that sorts before any Mutation Batch ID. */ +const j = -1; + +/** + * Returns whether a variable is either undefined or null. + */ function __PRIVATE_isNullOrUndefined(e) { + return null == e; +} + +/** Returns whether the value represents -0. */ function __PRIVATE_isNegativeZero(e) { + // Detect if the value is -0.0. Based on polyfill from + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is + return 0 === e && 1 / e == -1 / 0; +} + +/** + * Returns whether a value is an integer and in the safe integer range + * @param value - The value to test for being an integer and in the safe range + */ function isSafeInteger(e) { + return "number" == typeof e && Number.isInteger(e) && !__PRIVATE_isNegativeZero(e) && e <= Number.MAX_SAFE_INTEGER && e >= Number.MIN_SAFE_INTEGER; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const J = ""; + +/** + * Encodes a resource path into a IndexedDb-compatible string form. + */ +function __PRIVATE_encodeResourcePath(e) { + let t = ""; + for (let n = 0; n < e.length; n++) t.length > 0 && (t = __PRIVATE_encodeSeparator(t)), + t = __PRIVATE_encodeSegment(e.get(n), t); + return __PRIVATE_encodeSeparator(t); +} + +/** Encodes a single segment of a resource path into the given result */ function __PRIVATE_encodeSegment(e, t) { + let n = t; + const r = e.length; + for (let t = 0; t < r; t++) { + const r = e.charAt(t); + switch (r) { + case "\0": + n += ""; + break; + + case J: + n += ""; + break; + + default: + n += r; + } + } + return n; +} + +/** Encodes a path separator into the given result */ function __PRIVATE_encodeSeparator(e) { + return e + J + ""; +} + +/** + * Decodes the given IndexedDb-compatible string form of a resource path into + * a ResourcePath instance. Note that this method is not suitable for use with + * decoding resource names from the server; those are One Platform format + * strings. + */ function __PRIVATE_decodeResourcePath(e) { + // Event the empty path must encode as a path of at least length 2. A path + // with exactly 2 must be the empty path. + const t = e.length; + if (__PRIVATE_hardAssert(t >= 2, 64408, { + path: e + }), 2 === t) return __PRIVATE_hardAssert(e.charAt(0) === J && "" === e.charAt(1), 56145, { + path: e + }), ResourcePath.emptyPath(); + // Escape characters cannot exist past the second-to-last position in the + // source value. + const __PRIVATE_lastReasonableEscapeIndex = t - 2, n = []; + let r = ""; + for (let i = 0; i < t; ) { + // The last two characters of a valid encoded path must be a separator, so + // there must be an end to this segment. + const t = e.indexOf(J, i); + (t < 0 || t > __PRIVATE_lastReasonableEscapeIndex) && fail(50515, { + path: e + }); + switch (e.charAt(t + 1)) { + case "": + const s = e.substring(i, t); + let o; + 0 === r.length ? + // Avoid copying for the common case of a segment that excludes \0 + // and \001 + o = s : (r += s, o = r, r = ""), n.push(o); + break; + + case "": + r += e.substring(i, t), r += "\0"; + break; + + case "": + // The escape character can be used in the output to encode itself. + r += e.substring(i, t + 1); + break; + + default: + fail(61167, { + path: e + }); + } + i = t + 2; + } + return new ResourcePath(n); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const H = "remoteDocuments", Y = "owner", Z = "owner", X = "mutationQueues", ee = "userId", te = "mutations", ne = "batchId", re = "userMutationsIndex", ie = [ "userId", "batchId" ]; + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Name of the IndexedDb object store. + * + * Note that the name 'owner' is chosen to ensure backwards compatibility with + * older clients that only supported single locked access to the persistence + * layer. + */ +/** + * Creates a [userId, encodedPath] key for use in the DbDocumentMutations + * index to iterate over all at document mutations for a given path or lower. + */ +function __PRIVATE_newDbDocumentMutationPrefixForPath(e, t) { + return [ e, __PRIVATE_encodeResourcePath(t) ]; +} + +/** + * Creates a full index key of [userId, encodedPath, batchId] for inserting + * and deleting into the DbDocumentMutations index. + */ function __PRIVATE_newDbDocumentMutationKey(e, t, n) { + return [ e, __PRIVATE_encodeResourcePath(t), n ]; +} + +/** + * Because we store all the useful information for this store in the key, + * there is no useful information to store as the value. The raw (unencoded) + * path cannot be stored because IndexedDb doesn't store prototype + * information. + */ const se = {}, oe = "documentMutations", _e = "remoteDocumentsV14", ae = [ "prefixPath", "collectionGroup", "readTime", "documentId" ], ue = "documentKeyIndex", ce = [ "prefixPath", "collectionGroup", "documentId" ], le = "collectionGroupIndex", he = [ "collectionGroup", "readTime", "prefixPath", "documentId" ], Pe = "remoteDocumentGlobal", Te = "remoteDocumentGlobalKey", Ie = "targets", Ee = "queryTargetsIndex", de = [ "canonicalId", "targetId" ], Ae = "targetDocuments", Re = [ "targetId", "path" ], Ve = "documentTargetsIndex", me = [ "path", "targetId" ], fe = "targetGlobalKey", ge = "targetGlobal", pe = "collectionParents", ye = [ "collectionId", "parent" ], we = "clientMetadata", Se = "clientId", be = "bundles", De = "bundleId", Ce = "namedQueries", ve = "name", Fe = "indexConfiguration", Me = "indexId", xe = "collectionGroupIndex", Oe = "collectionGroup", Ne = "indexState", Be = [ "indexId", "uid" ], Le = "sequenceNumberIndex", ke = [ "uid", "sequenceNumber" ], qe = "indexEntries", Qe = [ "indexId", "uid", "arrayValue", "directionalValue", "orderedDocumentKey", "documentKey" ], $e = "documentKeyIndex", Ue = [ "indexId", "uid", "orderedDocumentKey" ], Ke = "documentOverlays", We = [ "userId", "collectionPath", "documentId" ], Ge = "collectionPathOverlayIndex", ze = [ "userId", "collectionPath", "largestBatchId" ], je = "collectionGroupOverlayIndex", Je = [ "userId", "collectionGroup", "largestBatchId" ], He = "globals", Ye = "name", Ze = [ ...[ ...[ ...[ ...[ X, te, oe, H, Ie, Y, ge, Ae ], we ], Pe ], pe ], be, Ce ], Xe = [ ...Ze, Ke ], et = [ X, te, oe, _e, Ie, Y, ge, Ae, we, Pe, pe, be, Ce, Ke ], tt = et, nt = [ ...tt, Fe, Ne, qe ], rt = nt, it = [ ...nt, He ], st = it; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class __PRIVATE_IndexedDbTransaction extends PersistenceTransaction { + constructor(e, t) { + super(), this.le = e, this.currentSequenceNumber = t; + } +} + +function __PRIVATE_getStore(e, t) { + const n = __PRIVATE_debugCast(e); + return __PRIVATE_SimpleDb.O(n.le, t); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_objectSize(e) { + let t = 0; + for (const n in e) Object.prototype.hasOwnProperty.call(e, n) && t++; + return t; +} + +function forEach(e, t) { + for (const n in e) Object.prototype.hasOwnProperty.call(e, n) && t(n, e[n]); +} + +function __PRIVATE_mapToArray(e, t) { + const n = []; + for (const r in e) Object.prototype.hasOwnProperty.call(e, r) && n.push(t(e[r], r, e)); + return n; +} + +function isEmpty(e) { + for (const t in e) if (Object.prototype.hasOwnProperty.call(e, t)) return !1; + return !0; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// An immutable sorted map implementation, based on a Left-leaning Red-Black +// tree. +class SortedMap { + constructor(e, t) { + this.comparator = e, this.root = t || LLRBNode.EMPTY; + } + // Returns a copy of the map, with the specified key/value added or replaced. + insert(e, t) { + return new SortedMap(this.comparator, this.root.insert(e, t, this.comparator).copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns a copy of the map, with the specified key removed. + remove(e) { + return new SortedMap(this.comparator, this.root.remove(e, this.comparator).copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns the value of the node with the given key, or null. + get(e) { + let t = this.root; + for (;!t.isEmpty(); ) { + const n = this.comparator(e, t.key); + if (0 === n) return t.value; + n < 0 ? t = t.left : n > 0 && (t = t.right); + } + return null; + } + // Returns the index of the element in this sorted map, or -1 if it doesn't + // exist. + indexOf(e) { + // Number of nodes that were pruned when descending right + let t = 0, n = this.root; + for (;!n.isEmpty(); ) { + const r = this.comparator(e, n.key); + if (0 === r) return t + n.left.size; + r < 0 ? n = n.left : ( + // Count all nodes left of the node plus the node itself + t += n.left.size + 1, n = n.right); + } + // Node not found + return -1; + } + isEmpty() { + return this.root.isEmpty(); + } + // Returns the total number of nodes in the map. + get size() { + return this.root.size; + } + // Returns the minimum key in the map. + minKey() { + return this.root.minKey(); + } + // Returns the maximum key in the map. + maxKey() { + return this.root.maxKey(); + } + // Traverses the map in key order and calls the specified action function + // for each key/value pair. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(e) { + return this.root.inorderTraversal(e); + } + forEach(e) { + this.inorderTraversal(((t, n) => (e(t, n), !1))); + } + toString() { + const e = []; + return this.inorderTraversal(((t, n) => (e.push(`${t}:${n}`), !1))), `{${e.join(", ")}}`; + } + // Traverses the map in reverse key order and calls the specified action + // function for each key/value pair. If action returns true, traversal is + // aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(e) { + return this.root.reverseTraversal(e); + } + // Returns an iterator over the SortedMap. + getIterator() { + return new SortedMapIterator(this.root, null, this.comparator, !1); + } + getIteratorFrom(e) { + return new SortedMapIterator(this.root, e, this.comparator, !1); + } + getReverseIterator() { + return new SortedMapIterator(this.root, null, this.comparator, !0); + } + getReverseIteratorFrom(e) { + return new SortedMapIterator(this.root, e, this.comparator, !0); + } +} + + // end SortedMap +// An iterator over an LLRBNode. +class SortedMapIterator { + constructor(e, t, n, r) { + this.isReverse = r, this.nodeStack = []; + let i = 1; + for (;!e.isEmpty(); ) if (i = t ? n(e.key, t) : 1, + // flip the comparison if we're going in reverse + t && r && (i *= -1), i < 0) + // This node is less than our start key. ignore it + e = this.isReverse ? e.left : e.right; else { + if (0 === i) { + // This node is exactly equal to our start key. Push it on the stack, + // but stop iterating; + this.nodeStack.push(e); + break; + } + // This node is greater than our start key, add it to the stack and move + // to the next one + this.nodeStack.push(e), e = this.isReverse ? e.right : e.left; + } + } + getNext() { + let e = this.nodeStack.pop(); + const t = { + key: e.key, + value: e.value + }; + if (this.isReverse) for (e = e.left; !e.isEmpty(); ) this.nodeStack.push(e), e = e.right; else for (e = e.right; !e.isEmpty(); ) this.nodeStack.push(e), + e = e.left; + return t; + } + hasNext() { + return this.nodeStack.length > 0; + } + peek() { + if (0 === this.nodeStack.length) return null; + const e = this.nodeStack[this.nodeStack.length - 1]; + return { + key: e.key, + value: e.value + }; + } +} + + // end SortedMapIterator +// Represents a node in a Left-leaning Red-Black tree. +class LLRBNode { + constructor(e, t, n, r, i) { + this.key = e, this.value = t, this.color = null != n ? n : LLRBNode.RED, this.left = null != r ? r : LLRBNode.EMPTY, + this.right = null != i ? i : LLRBNode.EMPTY, this.size = this.left.size + 1 + this.right.size; + } + // Returns a copy of the current node, optionally replacing pieces of it. + copy(e, t, n, r, i) { + return new LLRBNode(null != e ? e : this.key, null != t ? t : this.value, null != n ? n : this.color, null != r ? r : this.left, null != i ? i : this.right); + } + isEmpty() { + return !1; + } + // Traverses the tree in key order and calls the specified action function + // for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(e) { + return this.left.inorderTraversal(e) || e(this.key, this.value) || this.right.inorderTraversal(e); + } + // Traverses the tree in reverse key order and calls the specified action + // function for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(e) { + return this.right.reverseTraversal(e) || e(this.key, this.value) || this.left.reverseTraversal(e); + } + // Returns the minimum node in the tree. + min() { + return this.left.isEmpty() ? this : this.left.min(); + } + // Returns the maximum key in the tree. + minKey() { + return this.min().key; + } + // Returns the maximum key in the tree. + maxKey() { + return this.right.isEmpty() ? this.key : this.right.maxKey(); + } + // Returns new tree, with the key/value added. + insert(e, t, n) { + let r = this; + const i = n(e, r.key); + return r = i < 0 ? r.copy(null, null, null, r.left.insert(e, t, n), null) : 0 === i ? r.copy(null, t, null, null, null) : r.copy(null, null, null, null, r.right.insert(e, t, n)), + r.fixUp(); + } + removeMin() { + if (this.left.isEmpty()) return LLRBNode.EMPTY; + let e = this; + return e.left.isRed() || e.left.left.isRed() || (e = e.moveRedLeft()), e = e.copy(null, null, null, e.left.removeMin(), null), + e.fixUp(); + } + // Returns new tree, with the specified item removed. + remove(e, t) { + let n, r = this; + if (t(e, r.key) < 0) r.left.isEmpty() || r.left.isRed() || r.left.left.isRed() || (r = r.moveRedLeft()), + r = r.copy(null, null, null, r.left.remove(e, t), null); else { + if (r.left.isRed() && (r = r.rotateRight()), r.right.isEmpty() || r.right.isRed() || r.right.left.isRed() || (r = r.moveRedRight()), + 0 === t(e, r.key)) { + if (r.right.isEmpty()) return LLRBNode.EMPTY; + n = r.right.min(), r = r.copy(n.key, n.value, null, null, r.right.removeMin()); + } + r = r.copy(null, null, null, null, r.right.remove(e, t)); + } + return r.fixUp(); + } + isRed() { + return this.color; + } + // Returns new tree after performing any needed rotations. + fixUp() { + let e = this; + return e.right.isRed() && !e.left.isRed() && (e = e.rotateLeft()), e.left.isRed() && e.left.left.isRed() && (e = e.rotateRight()), + e.left.isRed() && e.right.isRed() && (e = e.colorFlip()), e; + } + moveRedLeft() { + let e = this.colorFlip(); + return e.right.left.isRed() && (e = e.copy(null, null, null, null, e.right.rotateRight()), + e = e.rotateLeft(), e = e.colorFlip()), e; + } + moveRedRight() { + let e = this.colorFlip(); + return e.left.left.isRed() && (e = e.rotateRight(), e = e.colorFlip()), e; + } + rotateLeft() { + const e = this.copy(null, null, LLRBNode.RED, null, this.right.left); + return this.right.copy(null, null, this.color, e, null); + } + rotateRight() { + const e = this.copy(null, null, LLRBNode.RED, this.left.right, null); + return this.left.copy(null, null, this.color, null, e); + } + colorFlip() { + const e = this.left.copy(null, null, !this.left.color, null, null), t = this.right.copy(null, null, !this.right.color, null, null); + return this.copy(null, null, !this.color, e, t); + } + // For testing. + checkMaxDepth() { + const e = this.check(); + return Math.pow(2, e) <= this.size + 1; + } + // In a balanced RB tree, the black-depth (number of black nodes) from root to + // leaves is equal on both sides. This function verifies that or asserts. + check() { + if (this.isRed() && this.left.isRed()) throw fail(43730, { + key: this.key, + value: this.value + }); + if (this.right.isRed()) throw fail(14113, { + key: this.key, + value: this.value + }); + const e = this.left.check(); + if (e !== this.right.check()) throw fail(27949); + return e + (this.isRed() ? 0 : 1); + } +} + + // end LLRBNode +// Empty node is shared between all LLRB trees. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +LLRBNode.EMPTY = null, LLRBNode.RED = !0, LLRBNode.BLACK = !1; + +// end LLRBEmptyNode +LLRBNode.EMPTY = new +// Represents an empty node (a leaf node in the Red-Black Tree). +class LLRBEmptyNode { + constructor() { + this.size = 0; + } + get key() { + throw fail(57766); + } + get value() { + throw fail(16141); + } + get color() { + throw fail(16727); + } + get left() { + throw fail(29726); + } + get right() { + throw fail(36894); + } + // Returns a copy of the current node. + copy(e, t, n, r, i) { + return this; + } + // Returns a copy of the tree, with the specified key/value added. + insert(e, t, n) { + return new LLRBNode(e, t); + } + // Returns a copy of the tree, with the specified key removed. + remove(e, t) { + return this; + } + isEmpty() { + return !0; + } + inorderTraversal(e) { + return !1; + } + reverseTraversal(e) { + return !1; + } + minKey() { + return null; + } + maxKey() { + return null; + } + isRed() { + return !1; + } + // For testing. + checkMaxDepth() { + return !0; + } + check() { + return 0; + } +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * SortedSet is an immutable (copy-on-write) collection that holds elements + * in order specified by the provided comparator. + * + * NOTE: if provided comparator returns 0 for two elements, we consider them to + * be equal! + */ +class SortedSet { + constructor(e) { + this.comparator = e, this.data = new SortedMap(this.comparator); + } + has(e) { + return null !== this.data.get(e); + } + first() { + return this.data.minKey(); + } + last() { + return this.data.maxKey(); + } + get size() { + return this.data.size; + } + indexOf(e) { + return this.data.indexOf(e); + } + /** Iterates elements in order defined by "comparator" */ forEach(e) { + this.data.inorderTraversal(((t, n) => (e(t), !1))); + } + /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ forEachInRange(e, t) { + const n = this.data.getIteratorFrom(e[0]); + for (;n.hasNext(); ) { + const r = n.getNext(); + if (this.comparator(r.key, e[1]) >= 0) return; + t(r.key); + } + } + /** + * Iterates over `elem`s such that: start <= elem until false is returned. + */ forEachWhile(e, t) { + let n; + for (n = void 0 !== t ? this.data.getIteratorFrom(t) : this.data.getIterator(); n.hasNext(); ) { + if (!e(n.getNext().key)) return; + } + } + /** Finds the least element greater than or equal to `elem`. */ firstAfterOrEqual(e) { + const t = this.data.getIteratorFrom(e); + return t.hasNext() ? t.getNext().key : null; + } + getIterator() { + return new SortedSetIterator(this.data.getIterator()); + } + getIteratorFrom(e) { + return new SortedSetIterator(this.data.getIteratorFrom(e)); + } + /** Inserts or updates an element */ add(e) { + return this.copy(this.data.remove(e).insert(e, !0)); + } + /** Deletes an element */ delete(e) { + return this.has(e) ? this.copy(this.data.remove(e)) : this; + } + isEmpty() { + return this.data.isEmpty(); + } + unionWith(e) { + let t = this; + // Make sure `result` always refers to the larger one of the two sets. + return t.size < e.size && (t = e, e = this), e.forEach((e => { + t = t.add(e); + })), t; + } + isEqual(e) { + if (!(e instanceof SortedSet)) return !1; + if (this.size !== e.size) return !1; + const t = this.data.getIterator(), n = e.data.getIterator(); + for (;t.hasNext(); ) { + const e = t.getNext().key, r = n.getNext().key; + if (0 !== this.comparator(e, r)) return !1; + } + return !0; + } + toArray() { + const e = []; + return this.forEach((t => { + e.push(t); + })), e; + } + toString() { + const e = []; + return this.forEach((t => e.push(t))), "SortedSet(" + e.toString() + ")"; + } + copy(e) { + const t = new SortedSet(this.comparator); + return t.data = e, t; + } +} + +class SortedSetIterator { + constructor(e) { + this.iter = e; + } + getNext() { + return this.iter.getNext().key; + } + hasNext() { + return this.iter.hasNext(); + } +} + +/** + * Compares two sorted sets for equality using their natural ordering. The + * method computes the intersection and invokes `onAdd` for every element that + * is in `after` but not `before`. `onRemove` is invoked for every element in + * `before` but missing from `after`. + * + * The method creates a copy of both `before` and `after` and runs in O(n log + * n), where n is the size of the two lists. + * + * @param before - The elements that exist in the original set. + * @param after - The elements to diff against the original set. + * @param comparator - The comparator for the elements in before and after. + * @param onAdd - A function to invoke for every element that is part of ` + * after` but not `before`. + * @param onRemove - A function to invoke for every element that is part of + * `before` but not `after`. + */ +/** + * Returns the next element from the iterator or `undefined` if none available. + */ +function __PRIVATE_advanceIterator(e) { + return e.hasNext() ? e.getNext() : void 0; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provides a set of fields that can be used to partially patch a document. + * FieldMask is used in conjunction with ObjectValue. + * Examples: + * foo - Overwrites foo entirely with the provided value. If foo is not + * present in the companion ObjectValue, the field is deleted. + * foo.bar - Overwrites only the field bar of the object foo. + * If foo is not an object, foo is replaced with an object + * containing foo + */ class FieldMask { + constructor(e) { + this.fields = e, + // TODO(dimond): validation of FieldMask + // Sort the field mask to support `FieldMask.isEqual()` and assert below. + e.sort(FieldPath$1.comparator); + } + static empty() { + return new FieldMask([]); + } + /** + * Returns a new FieldMask object that is the result of adding all the given + * fields paths to this field mask. + */ unionWith(e) { + let t = new SortedSet(FieldPath$1.comparator); + for (const e of this.fields) t = t.add(e); + for (const n of e) t = t.add(n); + return new FieldMask(t.toArray()); + } + /** + * Verifies that `fieldPath` is included by at least one field in this field + * mask. + * + * This is an O(n) operation, where `n` is the size of the field mask. + */ covers(e) { + for (const t of this.fields) if (t.isPrefixOf(e)) return !0; + return !1; + } + isEqual(e) { + return __PRIVATE_arrayEquals(this.fields, e.fields, ((e, t) => e.isEqual(t))); + } +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An error encountered while decoding base64 string. + */ class __PRIVATE_Base64DecodeError extends Error { + constructor() { + super(...arguments), this.name = "Base64DecodeError"; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Converts a Base64 encoded string to a binary string. */ +/** True if and only if the Base64 conversion functions are available. */ +function __PRIVATE_isBase64Available() { + return "undefined" != typeof atob; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Immutable class that represents a "proto" byte string. + * + * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when + * sent on the wire. This class abstracts away this differentiation by holding + * the proto byte string in a common class that must be converted into a string + * before being sent as a proto. + * @internal + */ class ByteString { + constructor(e) { + this.binaryString = e; + } + static fromBase64String(e) { + const t = function __PRIVATE_decodeBase64(e) { + try { + return atob(e); + } catch (e) { + // Check that `DOMException` is defined before using it to avoid + // "ReferenceError: Property 'DOMException' doesn't exist" in react-native. + // (https://github.com/firebase/firebase-js-sdk/issues/7115) + throw "undefined" != typeof DOMException && e instanceof DOMException ? new __PRIVATE_Base64DecodeError("Invalid base64 string: " + e) : e; + } + } + /** Converts a binary string to a Base64 encoded string. */ (e); + return new ByteString(t); + } + static fromUint8Array(e) { + // TODO(indexing); Remove the copy of the byte string here as this method + // is frequently called during indexing. + const t = + /** + * Helper function to convert an Uint8array to a binary string. + */ + function __PRIVATE_binaryStringFromUint8Array(e) { + let t = ""; + for (let n = 0; n < e.length; ++n) t += String.fromCharCode(e[n]); + return t; + } + /** + * Helper function to convert a binary string to an Uint8Array. + */ (e); + return new ByteString(t); + } + [Symbol.iterator]() { + let e = 0; + return { + next: () => e < this.binaryString.length ? { + value: this.binaryString.charCodeAt(e++), + done: !1 + } : { + value: void 0, + done: !0 + } + }; + } + toBase64() { + return function __PRIVATE_encodeBase64(e) { + return btoa(e); + }(this.binaryString); + } + toUint8Array() { + return function __PRIVATE_uint8ArrayFromBinaryString(e) { + const t = new Uint8Array(e.length); + for (let n = 0; n < e.length; n++) t[n] = e.charCodeAt(n); + return t; + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + // A RegExp matching ISO 8601 UTC timestamps with optional fraction. + (this.binaryString); + } + approximateByteSize() { + return 2 * this.binaryString.length; + } + compareTo(e) { + return __PRIVATE_primitiveComparator(this.binaryString, e.binaryString); + } + isEqual(e) { + return this.binaryString === e.binaryString; + } +} + +ByteString.EMPTY_BYTE_STRING = new ByteString(""); + +const ot = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/); + +/** + * Converts the possible Proto values for a timestamp value into a "seconds and + * nanos" representation. + */ function __PRIVATE_normalizeTimestamp(e) { + // The json interface (for the browser) will return an iso timestamp string, + // while the proto js library (for node) will return a + // google.protobuf.Timestamp instance. + if (__PRIVATE_hardAssert(!!e, 39018), "string" == typeof e) { + // The date string can have higher precision (nanos) than the Date class + // (millis), so we do some custom parsing here. + // Parse the nanos right out of the string. + let t = 0; + const n = ot.exec(e); + if (__PRIVATE_hardAssert(!!n, 46558, { + timestamp: e + }), n[1]) { + // Pad the fraction out to 9 digits (nanos). + let e = n[1]; + e = (e + "000000000").substr(0, 9), t = Number(e); + } + // Parse the date to get the seconds. + const r = new Date(e); + return { + seconds: Math.floor(r.getTime() / 1e3), + nanos: t + }; + } + return { + seconds: __PRIVATE_normalizeNumber(e.seconds), + nanos: __PRIVATE_normalizeNumber(e.nanos) + }; +} + +/** + * Converts the possible Proto types for numbers into a JavaScript number. + * Returns 0 if the value is not numeric. + */ function __PRIVATE_normalizeNumber(e) { + // TODO(bjornick): Handle int64 greater than 53 bits. + return "number" == typeof e ? e : "string" == typeof e ? Number(e) : 0; +} + +/** Converts the possible Proto types for Blobs into a ByteString. */ function __PRIVATE_normalizeByteString(e) { + return "string" == typeof e ? ByteString.fromBase64String(e) : ByteString.fromUint8Array(e); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a locally-applied ServerTimestamp. + * + * Server Timestamps are backed by MapValues that contain an internal field + * `__type__` with a value of `server_timestamp`. The previous value and local + * write time are stored in its `__previous_value__` and `__local_write_time__` + * fields respectively. + * + * Notes: + * - ServerTimestampValue instances are created as the result of applying a + * transform. They can only exist in the local view of a document. Therefore + * they do not need to be parsed or serialized. + * - When evaluated locally (e.g. for snapshot.data()), they by default + * evaluate to `null`. This behavior can be configured by passing custom + * FieldValueOptions to value(). + * - With respect to other ServerTimestampValues, they sort by their + * localWriteTime. + */ const _t = "server_timestamp", at = "__type__", ut = "__previous_value__", ct = "__local_write_time__"; + +function __PRIVATE_isServerTimestamp(e) { + const t = (e?.mapValue?.fields || {})[at]?.stringValue; + return t === _t; +} + +/** + * Creates a new ServerTimestamp proto value (using the internal format). + */ +/** + * Returns the value of the field before this ServerTimestamp was set. + * + * Preserving the previous values allows the user to display the last resoled + * value until the backend responds with the timestamp. + */ +function __PRIVATE_getPreviousValue(e) { + const t = e.mapValue.fields[ut]; + return __PRIVATE_isServerTimestamp(t) ? __PRIVATE_getPreviousValue(t) : t; +} + +/** + * Returns the local time at which this timestamp was first set. + */ function __PRIVATE_getLocalWriteTime(e) { + const t = __PRIVATE_normalizeTimestamp(e.mapValue.fields[ct].timestampValue); + return new Timestamp(t.seconds, t.nanos); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class DatabaseInfo { + /** + * Constructs a DatabaseInfo using the provided host, databaseId and + * persistenceKey. + * + * @param databaseId - The database to use. + * @param appId - The Firebase App Id. + * @param persistenceKey - A unique identifier for this Firestore's local + * storage (used in conjunction with the databaseId). + * @param host - The Firestore backend host to connect to. + * @param ssl - Whether to use SSL when connecting. + * @param forceLongPolling - Whether to use the forceLongPolling option + * when using WebChannel as the network transport. + * @param autoDetectLongPolling - Whether to use the detectBufferingProxy + * option when using WebChannel as the network transport. + * @param longPollingOptions Options that configure long-polling. + * @param useFetchStreams Whether to use the Fetch API instead of + * XMLHTTPRequest + */ + constructor(e, t, n, r, i, s, o, _, a, u) { + this.databaseId = e, this.appId = t, this.persistenceKey = n, this.host = r, this.ssl = i, + this.forceLongPolling = s, this.autoDetectLongPolling = o, this.longPollingOptions = _, + this.useFetchStreams = a, this.isUsingEmulator = u; + } +} + +/** The default database name for a project. */ const lt = "(default)"; + +/** + * Represents the database ID a Firestore client is associated with. + * @internal + */ class DatabaseId { + constructor(e, t) { + this.projectId = e, this.database = t || lt; + } + static empty() { + return new DatabaseId("", ""); + } + get isDefaultDatabase() { + return this.database === lt; + } + isEqual(e) { + return e instanceof DatabaseId && e.projectId === this.projectId && e.database === this.database; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const ht = "__type__", Pt = "__max__", Tt = { + mapValue: { + fields: { + __type__: { + stringValue: Pt + } + } + } +}, It = "__vector__", Et = "value", dt = { + nullValue: "NULL_VALUE" +}; + +/** Extracts the backend's type order for the provided value. */ +function __PRIVATE_typeOrder(e) { + return "nullValue" in e ? 0 /* TypeOrder.NullValue */ : "booleanValue" in e ? 1 /* TypeOrder.BooleanValue */ : "integerValue" in e || "doubleValue" in e ? 2 /* TypeOrder.NumberValue */ : "timestampValue" in e ? 3 /* TypeOrder.TimestampValue */ : "stringValue" in e ? 5 /* TypeOrder.StringValue */ : "bytesValue" in e ? 6 /* TypeOrder.BlobValue */ : "referenceValue" in e ? 7 /* TypeOrder.RefValue */ : "geoPointValue" in e ? 8 /* TypeOrder.GeoPointValue */ : "arrayValue" in e ? 9 /* TypeOrder.ArrayValue */ : "mapValue" in e ? __PRIVATE_isServerTimestamp(e) ? 4 /* TypeOrder.ServerTimestampValue */ : __PRIVATE_isMaxValue(e) ? 9007199254740991 /* TypeOrder.MaxValue */ : __PRIVATE_isVectorValue(e) ? 10 /* TypeOrder.VectorValue */ : 11 /* TypeOrder.ObjectValue */ : fail(28295, { + value: e + }); +} + +/** Tests `left` and `right` for equality based on the backend semantics. */ function __PRIVATE_valueEquals(e, t) { + if (e === t) return !0; + const n = __PRIVATE_typeOrder(e); + if (n !== __PRIVATE_typeOrder(t)) return !1; + switch (n) { + case 0 /* TypeOrder.NullValue */ : + case 9007199254740991 /* TypeOrder.MaxValue */ : + return !0; + + case 1 /* TypeOrder.BooleanValue */ : + return e.booleanValue === t.booleanValue; + + case 4 /* TypeOrder.ServerTimestampValue */ : + return __PRIVATE_getLocalWriteTime(e).isEqual(__PRIVATE_getLocalWriteTime(t)); + + case 3 /* TypeOrder.TimestampValue */ : + return function __PRIVATE_timestampEquals(e, t) { + if ("string" == typeof e.timestampValue && "string" == typeof t.timestampValue && e.timestampValue.length === t.timestampValue.length) + // Use string equality for ISO 8601 timestamps + return e.timestampValue === t.timestampValue; + const n = __PRIVATE_normalizeTimestamp(e.timestampValue), r = __PRIVATE_normalizeTimestamp(t.timestampValue); + return n.seconds === r.seconds && n.nanos === r.nanos; + }(e, t); + + case 5 /* TypeOrder.StringValue */ : + return e.stringValue === t.stringValue; + + case 6 /* TypeOrder.BlobValue */ : + return function __PRIVATE_blobEquals(e, t) { + return __PRIVATE_normalizeByteString(e.bytesValue).isEqual(__PRIVATE_normalizeByteString(t.bytesValue)); + }(e, t); + + case 7 /* TypeOrder.RefValue */ : + return e.referenceValue === t.referenceValue; + + case 8 /* TypeOrder.GeoPointValue */ : + return function __PRIVATE_geoPointEquals(e, t) { + return __PRIVATE_normalizeNumber(e.geoPointValue.latitude) === __PRIVATE_normalizeNumber(t.geoPointValue.latitude) && __PRIVATE_normalizeNumber(e.geoPointValue.longitude) === __PRIVATE_normalizeNumber(t.geoPointValue.longitude); + }(e, t); + + case 2 /* TypeOrder.NumberValue */ : + return function __PRIVATE_numberEquals(e, t) { + if ("integerValue" in e && "integerValue" in t) return __PRIVATE_normalizeNumber(e.integerValue) === __PRIVATE_normalizeNumber(t.integerValue); + if ("doubleValue" in e && "doubleValue" in t) { + const n = __PRIVATE_normalizeNumber(e.doubleValue), r = __PRIVATE_normalizeNumber(t.doubleValue); + return n === r ? __PRIVATE_isNegativeZero(n) === __PRIVATE_isNegativeZero(r) : isNaN(n) && isNaN(r); + } + return !1; + }(e, t); + + case 9 /* TypeOrder.ArrayValue */ : + return __PRIVATE_arrayEquals(e.arrayValue.values || [], t.arrayValue.values || [], __PRIVATE_valueEquals); + + case 10 /* TypeOrder.VectorValue */ : + case 11 /* TypeOrder.ObjectValue */ : + return function __PRIVATE_objectEquals(e, t) { + const n = e.mapValue.fields || {}, r = t.mapValue.fields || {}; + if (__PRIVATE_objectSize(n) !== __PRIVATE_objectSize(r)) return !1; + for (const e in n) if (n.hasOwnProperty(e) && (void 0 === r[e] || !__PRIVATE_valueEquals(n[e], r[e]))) return !1; + return !0; + } + /** Returns true if the ArrayValue contains the specified element. */ (e, t); + + default: + return fail(52216, { + left: e + }); + } +} + +function __PRIVATE_arrayValueContains(e, t) { + return void 0 !== (e.values || []).find((e => __PRIVATE_valueEquals(e, t))); +} + +function __PRIVATE_valueCompare(e, t) { + if (e === t) return 0; + const n = __PRIVATE_typeOrder(e), r = __PRIVATE_typeOrder(t); + if (n !== r) return __PRIVATE_primitiveComparator(n, r); + switch (n) { + case 0 /* TypeOrder.NullValue */ : + case 9007199254740991 /* TypeOrder.MaxValue */ : + return 0; + + case 1 /* TypeOrder.BooleanValue */ : + return __PRIVATE_primitiveComparator(e.booleanValue, t.booleanValue); + + case 2 /* TypeOrder.NumberValue */ : + return function __PRIVATE_compareNumbers(e, t) { + const n = __PRIVATE_normalizeNumber(e.integerValue || e.doubleValue), r = __PRIVATE_normalizeNumber(t.integerValue || t.doubleValue); + return n < r ? -1 : n > r ? 1 : n === r ? 0 : + // one or both are NaN. + isNaN(n) ? isNaN(r) ? 0 : -1 : 1; + }(e, t); + + case 3 /* TypeOrder.TimestampValue */ : + return __PRIVATE_compareTimestamps(e.timestampValue, t.timestampValue); + + case 4 /* TypeOrder.ServerTimestampValue */ : + return __PRIVATE_compareTimestamps(__PRIVATE_getLocalWriteTime(e), __PRIVATE_getLocalWriteTime(t)); + + case 5 /* TypeOrder.StringValue */ : + return __PRIVATE_compareUtf8Strings(e.stringValue, t.stringValue); + + case 6 /* TypeOrder.BlobValue */ : + return function __PRIVATE_compareBlobs(e, t) { + const n = __PRIVATE_normalizeByteString(e), r = __PRIVATE_normalizeByteString(t); + return n.compareTo(r); + }(e.bytesValue, t.bytesValue); + + case 7 /* TypeOrder.RefValue */ : + return function __PRIVATE_compareReferences(e, t) { + const n = e.split("/"), r = t.split("/"); + for (let e = 0; e < n.length && e < r.length; e++) { + const t = __PRIVATE_primitiveComparator(n[e], r[e]); + if (0 !== t) return t; + } + return __PRIVATE_primitiveComparator(n.length, r.length); + }(e.referenceValue, t.referenceValue); + + case 8 /* TypeOrder.GeoPointValue */ : + return function __PRIVATE_compareGeoPoints(e, t) { + const n = __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(e.latitude), __PRIVATE_normalizeNumber(t.latitude)); + if (0 !== n) return n; + return __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(e.longitude), __PRIVATE_normalizeNumber(t.longitude)); + }(e.geoPointValue, t.geoPointValue); + + case 9 /* TypeOrder.ArrayValue */ : + return __PRIVATE_compareArrays(e.arrayValue, t.arrayValue); + + case 10 /* TypeOrder.VectorValue */ : + return function __PRIVATE_compareVectors(e, t) { + const n = e.fields || {}, r = t.fields || {}, i = n[Et]?.arrayValue, s = r[Et]?.arrayValue, o = __PRIVATE_primitiveComparator(i?.values?.length || 0, s?.values?.length || 0); + if (0 !== o) return o; + return __PRIVATE_compareArrays(i, s); + }(e.mapValue, t.mapValue); + + case 11 /* TypeOrder.ObjectValue */ : + return function __PRIVATE_compareMaps(e, t) { + if (e === Tt.mapValue && t === Tt.mapValue) return 0; + if (e === Tt.mapValue) return 1; + if (t === Tt.mapValue) return -1; + const n = e.fields || {}, r = Object.keys(n), i = t.fields || {}, s = Object.keys(i); + // Even though MapValues are likely sorted correctly based on their insertion + // order (e.g. when received from the backend), local modifications can bring + // elements out of order. We need to re-sort the elements to ensure that + // canonical IDs are independent of insertion order. + r.sort(), s.sort(); + for (let e = 0; e < r.length && e < s.length; ++e) { + const t = __PRIVATE_compareUtf8Strings(r[e], s[e]); + if (0 !== t) return t; + const o = __PRIVATE_valueCompare(n[r[e]], i[s[e]]); + if (0 !== o) return o; + } + return __PRIVATE_primitiveComparator(r.length, s.length); + } + /** + * Generates the canonical ID for the provided field value (as used in Target + * serialization). + */ (e.mapValue, t.mapValue); + + default: + throw fail(23264, { + he: n + }); + } +} + +function __PRIVATE_compareTimestamps(e, t) { + if ("string" == typeof e && "string" == typeof t && e.length === t.length) return __PRIVATE_primitiveComparator(e, t); + const n = __PRIVATE_normalizeTimestamp(e), r = __PRIVATE_normalizeTimestamp(t), i = __PRIVATE_primitiveComparator(n.seconds, r.seconds); + return 0 !== i ? i : __PRIVATE_primitiveComparator(n.nanos, r.nanos); +} + +function __PRIVATE_compareArrays(e, t) { + const n = e.values || [], r = t.values || []; + for (let e = 0; e < n.length && e < r.length; ++e) { + const t = __PRIVATE_valueCompare(n[e], r[e]); + if (t) return t; + } + return __PRIVATE_primitiveComparator(n.length, r.length); +} + +function canonicalId(e) { + return __PRIVATE_canonifyValue(e); +} + +function __PRIVATE_canonifyValue(e) { + return "nullValue" in e ? "null" : "booleanValue" in e ? "" + e.booleanValue : "integerValue" in e ? "" + e.integerValue : "doubleValue" in e ? "" + e.doubleValue : "timestampValue" in e ? function __PRIVATE_canonifyTimestamp(e) { + const t = __PRIVATE_normalizeTimestamp(e); + return `time(${t.seconds},${t.nanos})`; + }(e.timestampValue) : "stringValue" in e ? e.stringValue : "bytesValue" in e ? function __PRIVATE_canonifyByteString(e) { + return __PRIVATE_normalizeByteString(e).toBase64(); + }(e.bytesValue) : "referenceValue" in e ? function __PRIVATE_canonifyReference(e) { + return DocumentKey.fromName(e).toString(); + }(e.referenceValue) : "geoPointValue" in e ? function __PRIVATE_canonifyGeoPoint(e) { + return `geo(${e.latitude},${e.longitude})`; + }(e.geoPointValue) : "arrayValue" in e ? function __PRIVATE_canonifyArray(e) { + let t = "[", n = !0; + for (const r of e.values || []) n ? n = !1 : t += ",", t += __PRIVATE_canonifyValue(r); + return t + "]"; + } + /** + * Returns an approximate (and wildly inaccurate) in-memory size for the field + * value. + * + * The memory size takes into account only the actual user data as it resides + * in memory and ignores object overhead. + */ (e.arrayValue) : "mapValue" in e ? function __PRIVATE_canonifyMap(e) { + // Iteration order in JavaScript is not guaranteed. To ensure that we generate + // matching canonical IDs for identical maps, we need to sort the keys. + const t = Object.keys(e.fields || {}).sort(); + let n = "{", r = !0; + for (const i of t) r ? r = !1 : n += ",", n += `${i}:${__PRIVATE_canonifyValue(e.fields[i])}`; + return n + "}"; + }(e.mapValue) : fail(61005, { + value: e + }); +} + +function __PRIVATE_estimateByteSize(e) { + switch (__PRIVATE_typeOrder(e)) { + case 0 /* TypeOrder.NullValue */ : + case 1 /* TypeOrder.BooleanValue */ : + return 4; + + case 2 /* TypeOrder.NumberValue */ : + return 8; + + case 3 /* TypeOrder.TimestampValue */ : + case 8 /* TypeOrder.GeoPointValue */ : + // GeoPoints are made up of two distinct numbers (latitude + longitude) + return 16; + + case 4 /* TypeOrder.ServerTimestampValue */ : + const t = __PRIVATE_getPreviousValue(e); + return t ? 16 + __PRIVATE_estimateByteSize(t) : 16; + + case 5 /* TypeOrder.StringValue */ : + // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures: + // "JavaScript's String type is [...] a set of elements of 16-bit unsigned + // integer values" + return 2 * e.stringValue.length; + + case 6 /* TypeOrder.BlobValue */ : + return __PRIVATE_normalizeByteString(e.bytesValue).approximateByteSize(); + + case 7 /* TypeOrder.RefValue */ : + return e.referenceValue.length; + + case 9 /* TypeOrder.ArrayValue */ : + return function __PRIVATE_estimateArrayByteSize(e) { + return (e.values || []).reduce(((e, t) => e + __PRIVATE_estimateByteSize(t)), 0); + } + /** Returns a reference value for the provided database and key. */ (e.arrayValue); + + case 10 /* TypeOrder.VectorValue */ : + case 11 /* TypeOrder.ObjectValue */ : + return function __PRIVATE_estimateMapByteSize(e) { + let t = 0; + return forEach(e.fields, ((e, n) => { + t += e.length + __PRIVATE_estimateByteSize(n); + })), t; + }(e.mapValue); + + default: + throw fail(13486, { + value: e + }); + } +} + +function __PRIVATE_refValue(e, t) { + return { + referenceValue: `projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}` + }; +} + +/** Returns true if `value` is an IntegerValue . */ function isInteger(e) { + return !!e && "integerValue" in e; +} + +/** Returns true if `value` is a DoubleValue. */ +/** Returns true if `value` is an ArrayValue. */ +function isArray(e) { + return !!e && "arrayValue" in e; +} + +/** Returns true if `value` is a NullValue. */ function __PRIVATE_isNullValue(e) { + return !!e && "nullValue" in e; +} + +/** Returns true if `value` is NaN. */ function __PRIVATE_isNanValue(e) { + return !!e && "doubleValue" in e && isNaN(Number(e.doubleValue)); +} + +/** Returns true if `value` is a MapValue. */ function __PRIVATE_isMapValue(e) { + return !!e && "mapValue" in e; +} + +/** Returns true if `value` is a VetorValue. */ function __PRIVATE_isVectorValue(e) { + const t = (e?.mapValue?.fields || {})[ht]?.stringValue; + return t === It; +} + +/** Creates a deep copy of `source`. */ function __PRIVATE_deepClone(e) { + if (e.geoPointValue) return { + geoPointValue: { + ...e.geoPointValue + } + }; + if (e.timestampValue && "object" == typeof e.timestampValue) return { + timestampValue: { + ...e.timestampValue + } + }; + if (e.mapValue) { + const t = { + mapValue: { + fields: {} + } + }; + return forEach(e.mapValue.fields, ((e, n) => t.mapValue.fields[e] = __PRIVATE_deepClone(n))), + t; + } + if (e.arrayValue) { + const t = { + arrayValue: { + values: [] + } + }; + for (let n = 0; n < (e.arrayValue.values || []).length; ++n) t.arrayValue.values[n] = __PRIVATE_deepClone(e.arrayValue.values[n]); + return t; + } + return { + ...e + }; +} + +/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ function __PRIVATE_isMaxValue(e) { + return (((e.mapValue || {}).fields || {}).__type__ || {}).stringValue === Pt; +} + +const At = { + mapValue: { + fields: { + [ht]: { + stringValue: It + }, + [Et]: { + arrayValue: {} + } + } + } +}; + +/** Returns the lowest value for the given value type (inclusive). */ function __PRIVATE_valuesGetLowerBound(e) { + return "nullValue" in e ? dt : "booleanValue" in e ? { + booleanValue: !1 + } : "integerValue" in e || "doubleValue" in e ? { + doubleValue: NaN + } : "timestampValue" in e ? { + timestampValue: { + seconds: Number.MIN_SAFE_INTEGER + } + } : "stringValue" in e ? { + stringValue: "" + } : "bytesValue" in e ? { + bytesValue: "" + } : "referenceValue" in e ? __PRIVATE_refValue(DatabaseId.empty(), DocumentKey.empty()) : "geoPointValue" in e ? { + geoPointValue: { + latitude: -90, + longitude: -180 + } + } : "arrayValue" in e ? { + arrayValue: {} + } : "mapValue" in e ? __PRIVATE_isVectorValue(e) ? At : { + mapValue: {} + } : fail(35942, { + value: e + }); +} + +/** Returns the largest value for the given value type (exclusive). */ function __PRIVATE_valuesGetUpperBound(e) { + return "nullValue" in e ? { + booleanValue: !1 + } : "booleanValue" in e ? { + doubleValue: NaN + } : "integerValue" in e || "doubleValue" in e ? { + timestampValue: { + seconds: Number.MIN_SAFE_INTEGER + } + } : "timestampValue" in e ? { + stringValue: "" + } : "stringValue" in e ? { + bytesValue: "" + } : "bytesValue" in e ? __PRIVATE_refValue(DatabaseId.empty(), DocumentKey.empty()) : "referenceValue" in e ? { + geoPointValue: { + latitude: -90, + longitude: -180 + } + } : "geoPointValue" in e ? { + arrayValue: {} + } : "arrayValue" in e ? At : "mapValue" in e ? __PRIVATE_isVectorValue(e) ? { + mapValue: {} + } : Tt : fail(61959, { + value: e + }); +} + +function __PRIVATE_lowerBoundCompare(e, t) { + const n = __PRIVATE_valueCompare(e.value, t.value); + return 0 !== n ? n : e.inclusive && !t.inclusive ? -1 : !e.inclusive && t.inclusive ? 1 : 0; +} + +function __PRIVATE_upperBoundCompare(e, t) { + const n = __PRIVATE_valueCompare(e.value, t.value); + return 0 !== n ? n : e.inclusive && !t.inclusive ? 1 : !e.inclusive && t.inclusive ? -1 : 0; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An ObjectValue represents a MapValue in the Firestore Proto and offers the + * ability to add and remove fields (via the ObjectValueBuilder). + */ class ObjectValue { + constructor(e) { + this.value = e; + } + static empty() { + return new ObjectValue({ + mapValue: {} + }); + } + /** + * Returns the value at the given path or null. + * + * @param path - the path to search + * @returns The value at the path or null if the path is not set. + */ field(e) { + if (e.isEmpty()) return this.value; + { + let t = this.value; + for (let n = 0; n < e.length - 1; ++n) if (t = (t.mapValue.fields || {})[e.get(n)], + !__PRIVATE_isMapValue(t)) return null; + return t = (t.mapValue.fields || {})[e.lastSegment()], t || null; + } + } + /** + * Sets the field to the provided value. + * + * @param path - The field path to set. + * @param value - The value to set. + */ set(e, t) { + this.getFieldsMap(e.popLast())[e.lastSegment()] = __PRIVATE_deepClone(t); + } + /** + * Sets the provided fields to the provided values. + * + * @param data - A map of fields to values (or null for deletes). + */ setAll(e) { + let t = FieldPath$1.emptyPath(), n = {}, r = []; + e.forEach(((e, i) => { + if (!t.isImmediateParentOf(i)) { + // Insert the accumulated changes at this parent location + const e = this.getFieldsMap(t); + this.applyChanges(e, n, r), n = {}, r = [], t = i.popLast(); + } + e ? n[i.lastSegment()] = __PRIVATE_deepClone(e) : r.push(i.lastSegment()); + })); + const i = this.getFieldsMap(t); + this.applyChanges(i, n, r); + } + /** + * Removes the field at the specified path. If there is no field at the + * specified path, nothing is changed. + * + * @param path - The field path to remove. + */ delete(e) { + const t = this.field(e.popLast()); + __PRIVATE_isMapValue(t) && t.mapValue.fields && delete t.mapValue.fields[e.lastSegment()]; + } + isEqual(e) { + return __PRIVATE_valueEquals(this.value, e.value); + } + /** + * Returns the map that contains the leaf element of `path`. If the parent + * entry does not yet exist, or if it is not a map, a new map will be created. + */ getFieldsMap(e) { + let t = this.value; + t.mapValue.fields || (t.mapValue = { + fields: {} + }); + for (let n = 0; n < e.length; ++n) { + let r = t.mapValue.fields[e.get(n)]; + __PRIVATE_isMapValue(r) && r.mapValue.fields || (r = { + mapValue: { + fields: {} + } + }, t.mapValue.fields[e.get(n)] = r), t = r; + } + return t.mapValue.fields; + } + /** + * Modifies `fieldsMap` by adding, replacing or deleting the specified + * entries. + */ applyChanges(e, t, n) { + forEach(t, ((t, n) => e[t] = n)); + for (const t of n) delete e[t]; + } + clone() { + return new ObjectValue(__PRIVATE_deepClone(this.value)); + } +} + +/** + * Returns a FieldMask built from all fields in a MapValue. + */ function __PRIVATE_extractFieldMask(e) { + const t = []; + return forEach(e.fields, ((e, n) => { + const r = new FieldPath$1([ e ]); + if (__PRIVATE_isMapValue(n)) { + const e = __PRIVATE_extractFieldMask(n.mapValue).fields; + if (0 === e.length) + // Preserve the empty map by adding it to the FieldMask. + t.push(r); else + // For nested and non-empty ObjectValues, add the FieldPath of the + // leaf nodes. + for (const n of e) t.push(r.child(n)); + } else + // For nested and non-empty ObjectValues, add the FieldPath of the leaf + // nodes. + t.push(r); + })), new FieldMask(t); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a document in Firestore with a key, version, data and whether it + * has local mutations applied to it. + * + * Documents can transition between states via `convertToFoundDocument()`, + * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does + * not transition to one of these states even after all mutations have been + * applied, `isValidDocument()` returns false and the document should be removed + * from all views. + */ class MutableDocument { + constructor(e, t, n, r, i, s, o) { + this.key = e, this.documentType = t, this.version = n, this.readTime = r, this.createTime = i, + this.data = s, this.documentState = o; + } + /** + * Creates a document with no known version or data, but which can serve as + * base document for mutations. + */ static newInvalidDocument(e) { + return new MutableDocument(e, 0 /* DocumentType.INVALID */ , + /* version */ SnapshotVersion.min(), + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist with the given data at the + * given version. + */ static newFoundDocument(e, t, n, r) { + return new MutableDocument(e, 1 /* DocumentType.FOUND_DOCUMENT */ , + /* version */ t, + /* readTime */ SnapshotVersion.min(), + /* createTime */ n, r, 0 /* DocumentState.SYNCED */); + } + /** Creates a new document that is known to not exist at the given version. */ static newNoDocument(e, t) { + return new MutableDocument(e, 2 /* DocumentType.NO_DOCUMENT */ , + /* version */ t, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist at the given version but + * whose data is not known (e.g. a document that was updated without a known + * base document). + */ static newUnknownDocument(e, t) { + return new MutableDocument(e, 3 /* DocumentType.UNKNOWN_DOCUMENT */ , + /* version */ t, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */); + } + /** + * Changes the document type to indicate that it exists and that its version + * and data are known. + */ convertToFoundDocument(e, t) { + // If a document is switching state from being an invalid or deleted + // document to a valid (FOUND_DOCUMENT) document, either due to receiving an + // update from Watch or due to applying a local set mutation on top + // of a deleted document, our best guess about its createTime would be the + // version at which the document transitioned to a FOUND_DOCUMENT. + return !this.createTime.isEqual(SnapshotVersion.min()) || 2 /* DocumentType.NO_DOCUMENT */ !== this.documentType && 0 /* DocumentType.INVALID */ !== this.documentType || (this.createTime = e), + this.version = e, this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */ , this.data = t, + this.documentState = 0 /* DocumentState.SYNCED */ , this; + } + /** + * Changes the document type to indicate that it doesn't exist at the given + * version. + */ convertToNoDocument(e) { + return this.version = e, this.documentType = 2 /* DocumentType.NO_DOCUMENT */ , + this.data = ObjectValue.empty(), this.documentState = 0 /* DocumentState.SYNCED */ , + this; + } + /** + * Changes the document type to indicate that it exists at a given version but + * that its data is not known (e.g. a document that was updated without a known + * base document). + */ convertToUnknownDocument(e) { + return this.version = e, this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */ , + this.data = ObjectValue.empty(), this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , + this; + } + setHasCommittedMutations() { + return this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , this; + } + setHasLocalMutations() { + return this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ , this.version = SnapshotVersion.min(), + this; + } + setReadTime(e) { + return this.readTime = e, this; + } + get hasLocalMutations() { + return 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ === this.documentState; + } + get hasCommittedMutations() { + return 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ === this.documentState; + } + get hasPendingWrites() { + return this.hasLocalMutations || this.hasCommittedMutations; + } + isValidDocument() { + return 0 /* DocumentType.INVALID */ !== this.documentType; + } + isFoundDocument() { + return 1 /* DocumentType.FOUND_DOCUMENT */ === this.documentType; + } + isNoDocument() { + return 2 /* DocumentType.NO_DOCUMENT */ === this.documentType; + } + isUnknownDocument() { + return 3 /* DocumentType.UNKNOWN_DOCUMENT */ === this.documentType; + } + isEqual(e) { + return e instanceof MutableDocument && this.key.isEqual(e.key) && this.version.isEqual(e.version) && this.documentType === e.documentType && this.documentState === e.documentState && this.data.isEqual(e.data); + } + mutableCopy() { + return new MutableDocument(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState); + } + toString() { + return `Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`; + } +} + +/** + * Compares the value for field `field` in the provided documents. Throws if + * the field does not exist in both documents. + */ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a bound of a query. + * + * The bound is specified with the given components representing a position and + * whether it's just before or just after the position (relative to whatever the + * query order is). + * + * The position represents a logical index position for a query. It's a prefix + * of values for the (potentially implicit) order by clauses of a query. + * + * Bound provides a function to determine whether a document comes before or + * after a bound. This is influenced by whether the position is just before or + * just after the provided values. + */ +class Bound { + constructor(e, t) { + this.position = e, this.inclusive = t; + } +} + +function __PRIVATE_boundCompareToDocument(e, t, n) { + let r = 0; + for (let i = 0; i < e.position.length; i++) { + const s = t[i], o = e.position[i]; + if (s.field.isKeyField()) r = DocumentKey.comparator(DocumentKey.fromName(o.referenceValue), n.key); else { + r = __PRIVATE_valueCompare(o, n.data.field(s.field)); + } + if ("desc" /* Direction.DESCENDING */ === s.dir && (r *= -1), 0 !== r) break; + } + return r; +} + +/** + * Returns true if a document sorts after a bound using the provided sort + * order. + */ function __PRIVATE_boundEquals(e, t) { + if (null === e) return null === t; + if (null === t) return !1; + if (e.inclusive !== t.inclusive || e.position.length !== t.position.length) return !1; + for (let n = 0; n < e.position.length; n++) { + if (!__PRIVATE_valueEquals(e.position[n], t.position[n])) return !1; + } + return !0; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An ordering on a field, in some Direction. Direction defaults to ASCENDING. + */ class OrderBy { + constructor(e, t = "asc" /* Direction.ASCENDING */) { + this.field = e, this.dir = t; + } +} + +function __PRIVATE_orderByEquals(e, t) { + return e.dir === t.dir && e.field.isEqual(t.field); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class Filter {} + +class FieldFilter extends Filter { + constructor(e, t, n) { + super(), this.field = e, this.op = t, this.value = n; + } + /** + * Creates a filter based on the provided arguments. + */ static create(e, t, n) { + return e.isKeyField() ? "in" /* Operator.IN */ === t || "not-in" /* Operator.NOT_IN */ === t ? this.createKeyFieldInFilter(e, t, n) : new __PRIVATE_KeyFieldFilter(e, t, n) : "array-contains" /* Operator.ARRAY_CONTAINS */ === t ? new __PRIVATE_ArrayContainsFilter(e, n) : "in" /* Operator.IN */ === t ? new __PRIVATE_InFilter(e, n) : "not-in" /* Operator.NOT_IN */ === t ? new __PRIVATE_NotInFilter(e, n) : "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === t ? new __PRIVATE_ArrayContainsAnyFilter(e, n) : new FieldFilter(e, t, n); + } + static createKeyFieldInFilter(e, t, n) { + return "in" /* Operator.IN */ === t ? new __PRIVATE_KeyFieldInFilter(e, n) : new __PRIVATE_KeyFieldNotInFilter(e, n); + } + matches(e) { + const t = e.data.field(this.field); + // Types do not have to match in NOT_EQUAL filters. + return "!=" /* Operator.NOT_EQUAL */ === this.op ? null !== t && void 0 === t.nullValue && this.matchesComparison(__PRIVATE_valueCompare(t, this.value)) : null !== t && __PRIVATE_typeOrder(this.value) === __PRIVATE_typeOrder(t) && this.matchesComparison(__PRIVATE_valueCompare(t, this.value)); + // Only compare types with matching backend order (such as double and int). + } + matchesComparison(e) { + switch (this.op) { + case "<" /* Operator.LESS_THAN */ : + return e < 0; + + case "<=" /* Operator.LESS_THAN_OR_EQUAL */ : + return e <= 0; + + case "==" /* Operator.EQUAL */ : + return 0 === e; + + case "!=" /* Operator.NOT_EQUAL */ : + return 0 !== e; + + case ">" /* Operator.GREATER_THAN */ : + return e > 0; + + case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ : + return e >= 0; + + default: + return fail(47266, { + operator: this.op + }); + } + } + isInequality() { + return [ "<" /* Operator.LESS_THAN */ , "<=" /* Operator.LESS_THAN_OR_EQUAL */ , ">" /* Operator.GREATER_THAN */ , ">=" /* Operator.GREATER_THAN_OR_EQUAL */ , "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ].indexOf(this.op) >= 0; + } + getFlattenedFilters() { + return [ this ]; + } + getFilters() { + return [ this ]; + } +} + +class CompositeFilter extends Filter { + constructor(e, t) { + super(), this.filters = e, this.op = t, this.Pe = null; + } + /** + * Creates a filter based on the provided arguments. + */ static create(e, t) { + return new CompositeFilter(e, t); + } + matches(e) { + return __PRIVATE_compositeFilterIsConjunction(this) ? void 0 === this.filters.find((t => !t.matches(e))) : void 0 !== this.filters.find((t => t.matches(e))); + } + getFlattenedFilters() { + return null !== this.Pe || (this.Pe = this.filters.reduce(((e, t) => e.concat(t.getFlattenedFilters())), [])), + this.Pe; + } + // Returns a mutable copy of `this.filters` + getFilters() { + return Object.assign([], this.filters); + } +} + +function __PRIVATE_compositeFilterIsConjunction(e) { + return "and" /* CompositeOperator.AND */ === e.op; +} + +function __PRIVATE_compositeFilterIsDisjunction(e) { + return "or" /* CompositeOperator.OR */ === e.op; +} + +/** + * Returns true if this filter is a conjunction of field filters only. Returns false otherwise. + */ function __PRIVATE_compositeFilterIsFlatConjunction(e) { + return __PRIVATE_compositeFilterIsFlat(e) && __PRIVATE_compositeFilterIsConjunction(e); +} + +/** + * Returns true if this filter does not contain any composite filters. Returns false otherwise. + */ function __PRIVATE_compositeFilterIsFlat(e) { + for (const t of e.filters) if (t instanceof CompositeFilter) return !1; + return !0; +} + +function __PRIVATE_canonifyFilter(e) { + if (e instanceof FieldFilter) + // TODO(b/29183165): Technically, this won't be unique if two values have + // the same description, such as the int 3 and the string "3". So we should + // add the types in here somehow, too. + return e.field.canonicalString() + e.op.toString() + canonicalId(e.value); + if (__PRIVATE_compositeFilterIsFlatConjunction(e)) + // Older SDK versions use an implicit AND operation between their filters. + // In the new SDK versions, the developer may use an explicit AND filter. + // To stay consistent with the old usages, we add a special case to ensure + // the canonical ID for these two are the same. For example: + // `col.whereEquals("a", 1).whereEquals("b", 2)` should have the same + // canonical ID as `col.where(and(equals("a",1), equals("b",2)))`. + return e.filters.map((e => __PRIVATE_canonifyFilter(e))).join(","); + { + // filter instanceof CompositeFilter + const t = e.filters.map((e => __PRIVATE_canonifyFilter(e))).join(","); + return `${e.op}(${t})`; + } +} + +function __PRIVATE_filterEquals(e, t) { + return e instanceof FieldFilter ? function __PRIVATE_fieldFilterEquals(e, t) { + return t instanceof FieldFilter && e.op === t.op && e.field.isEqual(t.field) && __PRIVATE_valueEquals(e.value, t.value); + }(e, t) : e instanceof CompositeFilter ? function __PRIVATE_compositeFilterEquals(e, t) { + if (t instanceof CompositeFilter && e.op === t.op && e.filters.length === t.filters.length) { + return e.filters.reduce(((e, n, r) => e && __PRIVATE_filterEquals(n, t.filters[r])), !0); + } + return !1; + } + /** + * Returns a new composite filter that contains all filter from + * `compositeFilter` plus all the given filters in `otherFilters`. + */ (e, t) : void fail(19439); +} + +function __PRIVATE_compositeFilterWithAddedFilters(e, t) { + const n = e.filters.concat(t); + return CompositeFilter.create(n, e.op); +} + +/** Returns a debug description for `filter`. */ function __PRIVATE_stringifyFilter(e) { + return e instanceof FieldFilter ? function __PRIVATE_stringifyFieldFilter(e) { + return `${e.field.canonicalString()} ${e.op} ${canonicalId(e.value)}`; + } + /** Filter that matches on key fields (i.e. '__name__'). */ (e) : e instanceof CompositeFilter ? function __PRIVATE_stringifyCompositeFilter(e) { + return e.op.toString() + " {" + e.getFilters().map(__PRIVATE_stringifyFilter).join(" ,") + "}"; + }(e) : "Filter"; +} + +class __PRIVATE_KeyFieldFilter extends FieldFilter { + constructor(e, t, n) { + super(e, t, n), this.key = DocumentKey.fromName(n.referenceValue); + } + matches(e) { + const t = DocumentKey.comparator(e.key, this.key); + return this.matchesComparison(t); + } +} + +/** Filter that matches on key fields within an array. */ class __PRIVATE_KeyFieldInFilter extends FieldFilter { + constructor(e, t) { + super(e, "in" /* Operator.IN */ , t), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue("in" /* Operator.IN */ , t); + } + matches(e) { + return this.keys.some((t => t.isEqual(e.key))); + } +} + +/** Filter that matches on key fields not present within an array. */ class __PRIVATE_KeyFieldNotInFilter extends FieldFilter { + constructor(e, t) { + super(e, "not-in" /* Operator.NOT_IN */ , t), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue("not-in" /* Operator.NOT_IN */ , t); + } + matches(e) { + return !this.keys.some((t => t.isEqual(e.key))); + } +} + +function __PRIVATE_extractDocumentKeysFromArrayValue(e, t) { + return (t.arrayValue?.values || []).map((e => DocumentKey.fromName(e.referenceValue))); +} + +/** A Filter that implements the array-contains operator. */ class __PRIVATE_ArrayContainsFilter extends FieldFilter { + constructor(e, t) { + super(e, "array-contains" /* Operator.ARRAY_CONTAINS */ , t); + } + matches(e) { + const t = e.data.field(this.field); + return isArray(t) && __PRIVATE_arrayValueContains(t.arrayValue, this.value); + } +} + +/** A Filter that implements the IN operator. */ class __PRIVATE_InFilter extends FieldFilter { + constructor(e, t) { + super(e, "in" /* Operator.IN */ , t); + } + matches(e) { + const t = e.data.field(this.field); + return null !== t && __PRIVATE_arrayValueContains(this.value.arrayValue, t); + } +} + +/** A Filter that implements the not-in operator. */ class __PRIVATE_NotInFilter extends FieldFilter { + constructor(e, t) { + super(e, "not-in" /* Operator.NOT_IN */ , t); + } + matches(e) { + if (__PRIVATE_arrayValueContains(this.value.arrayValue, { + nullValue: "NULL_VALUE" + })) return !1; + const t = e.data.field(this.field); + return null !== t && void 0 === t.nullValue && !__PRIVATE_arrayValueContains(this.value.arrayValue, t); + } +} + +/** A Filter that implements the array-contains-any operator. */ class __PRIVATE_ArrayContainsAnyFilter extends FieldFilter { + constructor(e, t) { + super(e, "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , t); + } + matches(e) { + const t = e.data.field(this.field); + return !(!isArray(t) || !t.arrayValue.values) && t.arrayValue.values.some((e => __PRIVATE_arrayValueContains(this.value.arrayValue, e))); + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Visible for testing +class __PRIVATE_TargetImpl { + constructor(e, t = null, n = [], r = [], i = null, s = null, o = null) { + this.path = e, this.collectionGroup = t, this.orderBy = n, this.filters = r, this.limit = i, + this.startAt = s, this.endAt = o, this.Te = null; + } +} + +/** + * Initializes a Target with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + * + * NOTE: you should always construct `Target` from `Query.toTarget` instead of + * using this factory method, because `Query` provides an implicit `orderBy` + * property. + */ function __PRIVATE_newTarget(e, t = null, n = [], r = [], i = null, s = null, o = null) { + return new __PRIVATE_TargetImpl(e, t, n, r, i, s, o); +} + +function __PRIVATE_canonifyTarget(e) { + const t = __PRIVATE_debugCast(e); + if (null === t.Te) { + let e = t.path.canonicalString(); + null !== t.collectionGroup && (e += "|cg:" + t.collectionGroup), e += "|f:", e += t.filters.map((e => __PRIVATE_canonifyFilter(e))).join(","), + e += "|ob:", e += t.orderBy.map((e => function __PRIVATE_canonifyOrderBy(e) { + // TODO(b/29183165): Make this collision robust. + return e.field.canonicalString() + e.dir; + }(e))).join(","), __PRIVATE_isNullOrUndefined(t.limit) || (e += "|l:", e += t.limit), + t.startAt && (e += "|lb:", e += t.startAt.inclusive ? "b:" : "a:", e += t.startAt.position.map((e => canonicalId(e))).join(",")), + t.endAt && (e += "|ub:", e += t.endAt.inclusive ? "a:" : "b:", e += t.endAt.position.map((e => canonicalId(e))).join(",")), + t.Te = e; + } + return t.Te; +} + +function __PRIVATE_targetEquals(e, t) { + if (e.limit !== t.limit) return !1; + if (e.orderBy.length !== t.orderBy.length) return !1; + for (let n = 0; n < e.orderBy.length; n++) if (!__PRIVATE_orderByEquals(e.orderBy[n], t.orderBy[n])) return !1; + if (e.filters.length !== t.filters.length) return !1; + for (let n = 0; n < e.filters.length; n++) if (!__PRIVATE_filterEquals(e.filters[n], t.filters[n])) return !1; + return e.collectionGroup === t.collectionGroup && (!!e.path.isEqual(t.path) && (!!__PRIVATE_boundEquals(e.startAt, t.startAt) && __PRIVATE_boundEquals(e.endAt, t.endAt))); +} + +function __PRIVATE_targetIsDocumentTarget(e) { + return DocumentKey.isDocumentKey(e.path) && null === e.collectionGroup && 0 === e.filters.length; +} + +/** Returns the field filters that target the given field path. */ function __PRIVATE_targetGetFieldFiltersForPath(e, t) { + return e.filters.filter((e => e instanceof FieldFilter && e.field.isEqual(t))); +} + +/** + * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY + * filters. Returns `null` if there are no such filters. + */ +/** + * Returns the value to use as the lower bound for ascending index segment at + * the provided `fieldPath` (or the upper bound for an descending segment). + */ +function __PRIVATE_targetGetAscendingBound(e, t, n) { + let r = dt, i = !0; + // Process all filters to find a value for the current field segment + for (const n of __PRIVATE_targetGetFieldFiltersForPath(e, t)) { + let e = dt, t = !0; + switch (n.op) { + case "<" /* Operator.LESS_THAN */ : + case "<=" /* Operator.LESS_THAN_OR_EQUAL */ : + e = __PRIVATE_valuesGetLowerBound(n.value); + break; + + case "==" /* Operator.EQUAL */ : + case "in" /* Operator.IN */ : + case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ : + e = n.value; + break; + + case ">" /* Operator.GREATER_THAN */ : + e = n.value, t = !1; + break; + + case "!=" /* Operator.NOT_EQUAL */ : + case "not-in" /* Operator.NOT_IN */ : + e = dt; + // Remaining filters cannot be used as lower bounds. + } + __PRIVATE_lowerBoundCompare({ + value: r, + inclusive: i + }, { + value: e, + inclusive: t + }) < 0 && (r = e, i = t); + } + // If there is an additional bound, compare the values against the existing + // range to see if we can narrow the scope. + if (null !== n) for (let s = 0; s < e.orderBy.length; ++s) { + if (e.orderBy[s].field.isEqual(t)) { + const e = n.position[s]; + __PRIVATE_lowerBoundCompare({ + value: r, + inclusive: i + }, { + value: e, + inclusive: n.inclusive + }) < 0 && (r = e, i = n.inclusive); + break; + } + } + return { + value: r, + inclusive: i + }; +} + +/** + * Returns the value to use as the upper bound for ascending index segment at + * the provided `fieldPath` (or the lower bound for a descending segment). + */ function __PRIVATE_targetGetDescendingBound(e, t, n) { + let r = Tt, i = !0; + // Process all filters to find a value for the current field segment + for (const n of __PRIVATE_targetGetFieldFiltersForPath(e, t)) { + let e = Tt, t = !0; + switch (n.op) { + case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ : + case ">" /* Operator.GREATER_THAN */ : + e = __PRIVATE_valuesGetUpperBound(n.value), t = !1; + break; + + case "==" /* Operator.EQUAL */ : + case "in" /* Operator.IN */ : + case "<=" /* Operator.LESS_THAN_OR_EQUAL */ : + e = n.value; + break; + + case "<" /* Operator.LESS_THAN */ : + e = n.value, t = !1; + break; + + case "!=" /* Operator.NOT_EQUAL */ : + case "not-in" /* Operator.NOT_IN */ : + e = Tt; + // Remaining filters cannot be used as upper bounds. + } + __PRIVATE_upperBoundCompare({ + value: r, + inclusive: i + }, { + value: e, + inclusive: t + }) > 0 && (r = e, i = t); + } + // If there is an additional bound, compare the values against the existing + // range to see if we can narrow the scope. + if (null !== n) for (let s = 0; s < e.orderBy.length; ++s) { + if (e.orderBy[s].field.isEqual(t)) { + const e = n.position[s]; + __PRIVATE_upperBoundCompare({ + value: r, + inclusive: i + }, { + value: e, + inclusive: n.inclusive + }) > 0 && (r = e, i = n.inclusive); + break; + } + } + return { + value: r, + inclusive: i + }; +} + +/** Returns the number of segments of a perfect index for this target. */ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Query encapsulates all the query attributes we support in the SDK. It can + * be run against the LocalStore, as well as be converted to a `Target` to + * query the RemoteStore results. + * + * Visible for testing. + */ +class __PRIVATE_QueryImpl { + /** + * Initializes a Query with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + */ + constructor(e, t = null, n = [], r = [], i = null, s = "F" /* LimitType.First */ , o = null, _ = null) { + this.path = e, this.collectionGroup = t, this.explicitOrderBy = n, this.filters = r, + this.limit = i, this.limitType = s, this.startAt = o, this.endAt = _, this.Ie = null, + // The corresponding `Target` of this `Query` instance, for use with + // non-aggregate queries. + this.Ee = null, + // The corresponding `Target` of this `Query` instance, for use with + // aggregate queries. Unlike targets for non-aggregate queries, + // aggregate query targets do not contain normalized order-bys, they only + // contain explicit order-bys. + this.de = null, this.startAt, this.endAt; + } +} + +/** Creates a new Query instance with the options provided. */ function __PRIVATE_newQuery(e, t, n, r, i, s, o, _) { + return new __PRIVATE_QueryImpl(e, t, n, r, i, s, o, _); +} + +/** Creates a new Query for a query that matches all documents at `path` */ function __PRIVATE_newQueryForPath(e) { + return new __PRIVATE_QueryImpl(e); +} + +/** + * Helper to convert a collection group query into a collection query at a + * specific path. This is used when executing collection group queries, since + * we have to split the query into a set of collection queries at multiple + * paths. + */ +/** + * Returns true if this query does not specify any query constraints that + * could remove results. + */ +function __PRIVATE_queryMatchesAllDocuments(e) { + return 0 === e.filters.length && null === e.limit && null == e.startAt && null == e.endAt && (0 === e.explicitOrderBy.length || 1 === e.explicitOrderBy.length && e.explicitOrderBy[0].field.isKeyField()); +} + +// Returns the sorted set of inequality filter fields used in this query. +/** + * Returns whether the query matches a collection group rather than a specific + * collection. + */ +function __PRIVATE_isCollectionGroupQuery(e) { + return null !== e.collectionGroup; +} + +/** + * Returns the normalized order-by constraint that is used to execute the Query, + * which can be different from the order-by constraints the user provided (e.g. + * the SDK and backend always orders by `__name__`). The normalized order-by + * includes implicit order-bys in addition to the explicit user provided + * order-bys. + */ function __PRIVATE_queryNormalizedOrderBy(e) { + const t = __PRIVATE_debugCast(e); + if (null === t.Ie) { + t.Ie = []; + const e = new Set; + // Any explicit order by fields should be added as is. + for (const n of t.explicitOrderBy) t.Ie.push(n), e.add(n.field.canonicalString()); + // The order of the implicit ordering always matches the last explicit order by. + const n = t.explicitOrderBy.length > 0 ? t.explicitOrderBy[t.explicitOrderBy.length - 1].dir : "asc" /* Direction.ASCENDING */ , r = function __PRIVATE_getInequalityFilterFields(e) { + let t = new SortedSet(FieldPath$1.comparator); + return e.filters.forEach((e => { + e.getFlattenedFilters().forEach((e => { + e.isInequality() && (t = t.add(e.field)); + })); + })), t; + } + /** + * Creates a new Query for a collection group query that matches all documents + * within the provided collection group. + */ (t); + // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical + // order. When there are multiple inequality filters on the same field, the field should be added + // only once. + // Note: `SortedSet` sorts the key field before other fields. However, we want the key + // field to be sorted last. + r.forEach((r => { + e.has(r.canonicalString()) || r.isKeyField() || t.Ie.push(new OrderBy(r, n)); + })), + // Add the document key field to the last if it is not explicitly ordered. + e.has(FieldPath$1.keyField().canonicalString()) || t.Ie.push(new OrderBy(FieldPath$1.keyField(), n)); + } + return t.Ie; +} + +/** + * Converts this `Query` instance to its corresponding `Target` representation. + */ function __PRIVATE_queryToTarget(e) { + const t = __PRIVATE_debugCast(e); + return t.Ee || (t.Ee = __PRIVATE__queryToTarget(t, __PRIVATE_queryNormalizedOrderBy(e))), + t.Ee; +} + +/** + * Converts this `Query` instance to its corresponding `Target` representation, + * for use within an aggregate query. Unlike targets for non-aggregate queries, + * aggregate query targets do not contain normalized order-bys, they only + * contain explicit order-bys. + */ function __PRIVATE_queryToAggregateTarget(e) { + const t = __PRIVATE_debugCast(e); + return t.de || ( + // Do not include implicit order-bys for aggregate queries. + t.de = __PRIVATE__queryToTarget(t, e.explicitOrderBy)), t.de; +} + +function __PRIVATE__queryToTarget(e, t) { + if ("F" /* LimitType.First */ === e.limitType) return __PRIVATE_newTarget(e.path, e.collectionGroup, t, e.filters, e.limit, e.startAt, e.endAt); + { + // Flip the orderBy directions since we want the last results + t = t.map((e => { + const t = "desc" /* Direction.DESCENDING */ === e.dir ? "asc" /* Direction.ASCENDING */ : "desc" /* Direction.DESCENDING */; + return new OrderBy(e.field, t); + })); + // We need to swap the cursors to match the now-flipped query ordering. + const n = e.endAt ? new Bound(e.endAt.position, e.endAt.inclusive) : null, r = e.startAt ? new Bound(e.startAt.position, e.startAt.inclusive) : null; + // Now return as a LimitType.First query. + return __PRIVATE_newTarget(e.path, e.collectionGroup, t, e.filters, e.limit, n, r); + } +} + +function __PRIVATE_queryWithAddedFilter(e, t) { + const n = e.filters.concat([ t ]); + return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, e.explicitOrderBy.slice(), n, e.limit, e.limitType, e.startAt, e.endAt); +} + +function __PRIVATE_queryWithLimit(e, t, n) { + return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, e.explicitOrderBy.slice(), e.filters.slice(), t, n, e.startAt, e.endAt); +} + +function __PRIVATE_queryEquals(e, t) { + return __PRIVATE_targetEquals(__PRIVATE_queryToTarget(e), __PRIVATE_queryToTarget(t)) && e.limitType === t.limitType; +} + +// TODO(b/29183165): This is used to get a unique string from a query to, for +// example, use as a dictionary key, but the implementation is subject to +// collisions. Make it collision-free. +function __PRIVATE_canonifyQuery(e) { + return `${__PRIVATE_canonifyTarget(__PRIVATE_queryToTarget(e))}|lt:${e.limitType}`; +} + +function __PRIVATE_stringifyQuery(e) { + return `Query(target=${function __PRIVATE_stringifyTarget(e) { + let t = e.path.canonicalString(); + return null !== e.collectionGroup && (t += " collectionGroup=" + e.collectionGroup), + e.filters.length > 0 && (t += `, filters: [${e.filters.map((e => __PRIVATE_stringifyFilter(e))).join(", ")}]`), + __PRIVATE_isNullOrUndefined(e.limit) || (t += ", limit: " + e.limit), e.orderBy.length > 0 && (t += `, orderBy: [${e.orderBy.map((e => function __PRIVATE_stringifyOrderBy(e) { + return `${e.field.canonicalString()} (${e.dir})`; + }(e))).join(", ")}]`), e.startAt && (t += ", startAt: ", t += e.startAt.inclusive ? "b:" : "a:", + t += e.startAt.position.map((e => canonicalId(e))).join(",")), e.endAt && (t += ", endAt: ", + t += e.endAt.inclusive ? "a:" : "b:", t += e.endAt.position.map((e => canonicalId(e))).join(",")), + `Target(${t})`; + }(__PRIVATE_queryToTarget(e))}; limitType=${e.limitType})`; +} + +/** Returns whether `doc` matches the constraints of `query`. */ function __PRIVATE_queryMatches(e, t) { + return t.isFoundDocument() && function __PRIVATE_queryMatchesPathAndCollectionGroup(e, t) { + const n = t.key.path; + return null !== e.collectionGroup ? t.key.hasCollectionId(e.collectionGroup) && e.path.isPrefixOf(n) : DocumentKey.isDocumentKey(e.path) ? e.path.isEqual(n) : e.path.isImmediateParentOf(n); + } + /** + * A document must have a value for every ordering clause in order to show up + * in the results. + */ (e, t) && function __PRIVATE_queryMatchesOrderBy(e, t) { + // We must use `queryNormalizedOrderBy()` to get the list of all orderBys (both implicit and explicit). + // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must + // be taken into account. For example, the query "a > 1 || b==1" has an implicit "orderBy a" due + // to the inequality, and is evaluated as "a > 1 orderBy a || b==1 orderBy a". + // A document with content of {b:1} matches the filters, but does not match the orderBy because + // it's missing the field 'a'. + for (const n of __PRIVATE_queryNormalizedOrderBy(e)) + // order-by key always matches + if (!n.field.isKeyField() && null === t.data.field(n.field)) return !1; + return !0; + }(e, t) && function __PRIVATE_queryMatchesFilters(e, t) { + for (const n of e.filters) if (!n.matches(t)) return !1; + return !0; + } + /** Makes sure a document is within the bounds, if provided. */ (e, t) && function __PRIVATE_queryMatchesBounds(e, t) { + if (e.startAt && ! + /** + * Returns true if a document sorts before a bound using the provided sort + * order. + */ + function __PRIVATE_boundSortsBeforeDocument(e, t, n) { + const r = __PRIVATE_boundCompareToDocument(e, t, n); + return e.inclusive ? r <= 0 : r < 0; + }(e.startAt, __PRIVATE_queryNormalizedOrderBy(e), t)) return !1; + if (e.endAt && !function __PRIVATE_boundSortsAfterDocument(e, t, n) { + const r = __PRIVATE_boundCompareToDocument(e, t, n); + return e.inclusive ? r >= 0 : r > 0; + }(e.endAt, __PRIVATE_queryNormalizedOrderBy(e), t)) return !1; + return !0; + } + /** + * Returns the collection group that this query targets. + * + * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab + * synchronization for query results. + */ (e, t); +} + +function __PRIVATE_queryCollectionGroup(e) { + return e.collectionGroup || (e.path.length % 2 == 1 ? e.path.lastSegment() : e.path.get(e.path.length - 2)); +} + +/** + * Returns a new comparator function that can be used to compare two documents + * based on the Query's ordering constraint. + */ function __PRIVATE_newQueryComparator(e) { + return (t, n) => { + let r = !1; + for (const i of __PRIVATE_queryNormalizedOrderBy(e)) { + const e = __PRIVATE_compareDocs(i, t, n); + if (0 !== e) return e; + r = r || i.field.isKeyField(); + } + return 0; + }; +} + +function __PRIVATE_compareDocs(e, t, n) { + const r = e.field.isKeyField() ? DocumentKey.comparator(t.key, n.key) : function __PRIVATE_compareDocumentsByField(e, t, n) { + const r = t.data.field(e), i = n.data.field(e); + return null !== r && null !== i ? __PRIVATE_valueCompare(r, i) : fail(42886); + }(e.field, t, n); + switch (e.dir) { + case "asc" /* Direction.ASCENDING */ : + return r; + + case "desc" /* Direction.DESCENDING */ : + return -1 * r; + + default: + return fail(19790, { + direction: e.dir + }); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A map implementation that uses objects as keys. Objects must have an + * associated equals function and must be immutable. Entries in the map are + * stored together with the key being produced from the mapKeyFn. This map + * automatically handles collisions of keys. + */ class ObjectMap { + constructor(e, t) { + this.mapKeyFn = e, this.equalsFn = t, + /** + * The inner map for a key/value pair. Due to the possibility of collisions we + * keep a list of entries that we do a linear search through to find an actual + * match. Note that collisions should be rare, so we still expect near + * constant time lookups in practice. + */ + this.inner = {}, + /** The number of entries stored in the map */ + this.innerSize = 0; + } + /** Get a value for this key, or undefined if it does not exist. */ get(e) { + const t = this.mapKeyFn(e), n = this.inner[t]; + if (void 0 !== n) for (const [t, r] of n) if (this.equalsFn(t, e)) return r; + } + has(e) { + return void 0 !== this.get(e); + } + /** Put this key and value in the map. */ set(e, t) { + const n = this.mapKeyFn(e), r = this.inner[n]; + if (void 0 === r) return this.inner[n] = [ [ e, t ] ], void this.innerSize++; + for (let n = 0; n < r.length; n++) if (this.equalsFn(r[n][0], e)) + // This is updating an existing entry and does not increase `innerSize`. + return void (r[n] = [ e, t ]); + r.push([ e, t ]), this.innerSize++; + } + /** + * Remove this key from the map. Returns a boolean if anything was deleted. + */ delete(e) { + const t = this.mapKeyFn(e), n = this.inner[t]; + if (void 0 === n) return !1; + for (let r = 0; r < n.length; r++) if (this.equalsFn(n[r][0], e)) return 1 === n.length ? delete this.inner[t] : n.splice(r, 1), + this.innerSize--, !0; + return !1; + } + forEach(e) { + forEach(this.inner, ((t, n) => { + for (const [t, r] of n) e(t, r); + })); + } + isEmpty() { + return isEmpty(this.inner); + } + size() { + return this.innerSize; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const Rt = new SortedMap(DocumentKey.comparator); + +function __PRIVATE_mutableDocumentMap() { + return Rt; +} + +const Vt = new SortedMap(DocumentKey.comparator); + +function documentMap(...e) { + let t = Vt; + for (const n of e) t = t.insert(n.key, n); + return t; +} + +function __PRIVATE_convertOverlayedDocumentMapToDocumentMap(e) { + let t = Vt; + return e.forEach(((e, n) => t = t.insert(e, n.overlayedDocument))), t; +} + +function __PRIVATE_newOverlayMap() { + return __PRIVATE_newDocumentKeyMap(); +} + +function __PRIVATE_newMutationMap() { + return __PRIVATE_newDocumentKeyMap(); +} + +function __PRIVATE_newDocumentKeyMap() { + return new ObjectMap((e => e.toString()), ((e, t) => e.isEqual(t))); +} + +const mt = new SortedMap(DocumentKey.comparator); + +const ft = new SortedSet(DocumentKey.comparator); + +function __PRIVATE_documentKeySet(...e) { + let t = ft; + for (const n of e) t = t.add(n); + return t; +} + +const gt = new SortedSet(__PRIVATE_primitiveComparator); + +function __PRIVATE_targetIdSet() { + return gt; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns an DoubleValue for `value` that is encoded based the serializer's + * `useProto3Json` setting. + */ function __PRIVATE_toDouble(e, t) { + if (e.useProto3Json) { + if (isNaN(t)) return { + doubleValue: "NaN" + }; + if (t === 1 / 0) return { + doubleValue: "Infinity" + }; + if (t === -1 / 0) return { + doubleValue: "-Infinity" + }; + } + return { + doubleValue: __PRIVATE_isNegativeZero(t) ? "-0" : t + }; +} + +/** + * Returns an IntegerValue for `value`. + */ function __PRIVATE_toInteger(e) { + return { + integerValue: "" + e + }; +} + +/** + * Returns a value for a number that's appropriate to put into a proto. + * The return value is an IntegerValue if it can safely represent the value, + * otherwise a DoubleValue is returned. + */ function toNumber(e, t) { + return isSafeInteger(t) ? __PRIVATE_toInteger(t) : __PRIVATE_toDouble(e, t); +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Used to represent a field transform on a mutation. */ class TransformOperation { + constructor() { + // Make sure that the structural type of `TransformOperation` is unique. + // See https://github.com/microsoft/TypeScript/issues/5451 + this._ = void 0; + } +} + +/** + * Computes the local transform result against the provided `previousValue`, + * optionally using the provided localWriteTime. + */ function __PRIVATE_applyTransformOperationToLocalView(e, t, n) { + return e instanceof __PRIVATE_ServerTimestampTransform ? function serverTimestamp$1(e, t) { + const n = { + fields: { + [at]: { + stringValue: _t + }, + [ct]: { + timestampValue: { + seconds: e.seconds, + nanos: e.nanoseconds + } + } + } + }; + // We should avoid storing deeply nested server timestamp map values + // because we never use the intermediate "previous values". + // For example: + // previous: 42L, add: t1, result: t1 -> 42L + // previous: t1, add: t2, result: t2 -> 42L (NOT t2 -> t1 -> 42L) + // previous: t2, add: t3, result: t3 -> 42L (NOT t3 -> t2 -> t1 -> 42L) + // `getPreviousValue` recursively traverses server timestamps to find the + // least recent Value. + return t && __PRIVATE_isServerTimestamp(t) && (t = __PRIVATE_getPreviousValue(t)), + t && (n.fields[ut] = t), { + mapValue: n + }; + }(n, t) : e instanceof __PRIVATE_ArrayUnionTransformOperation ? __PRIVATE_applyArrayUnionTransformOperation(e, t) : e instanceof __PRIVATE_ArrayRemoveTransformOperation ? __PRIVATE_applyArrayRemoveTransformOperation(e, t) : function __PRIVATE_applyNumericIncrementTransformOperationToLocalView(e, t) { + // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit + // precision and resolves overflows by reducing precision, we do not + // manually cap overflows at 2^63. + const n = __PRIVATE_computeTransformOperationBaseValue(e, t), r = asNumber(n) + asNumber(e.Ae); + return isInteger(n) && isInteger(e.Ae) ? __PRIVATE_toInteger(r) : __PRIVATE_toDouble(e.serializer, r); + }(e, t); +} + +/** + * Computes a final transform result after the transform has been acknowledged + * by the server, potentially using the server-provided transformResult. + */ function __PRIVATE_applyTransformOperationToRemoteDocument(e, t, n) { + // The server just sends null as the transform result for array operations, + // so we have to calculate a result the same as we do for local + // applications. + return e instanceof __PRIVATE_ArrayUnionTransformOperation ? __PRIVATE_applyArrayUnionTransformOperation(e, t) : e instanceof __PRIVATE_ArrayRemoveTransformOperation ? __PRIVATE_applyArrayRemoveTransformOperation(e, t) : n; +} + +/** + * If this transform operation is not idempotent, returns the base value to + * persist for this transform. If a base value is returned, the transform + * operation is always applied to this base value, even if document has + * already been updated. + * + * Base values provide consistent behavior for non-idempotent transforms and + * allow us to return the same latency-compensated value even if the backend + * has already applied the transform operation. The base value is null for + * idempotent transforms, as they can be re-played even if the backend has + * already applied them. + * + * @returns a base value to store along with the mutation, or null for + * idempotent transforms. + */ function __PRIVATE_computeTransformOperationBaseValue(e, t) { + return e instanceof __PRIVATE_NumericIncrementTransformOperation ? + /** Returns true if `value` is either an IntegerValue or a DoubleValue. */ + function __PRIVATE_isNumber(e) { + return isInteger(e) || function __PRIVATE_isDouble(e) { + return !!e && "doubleValue" in e; + }(e); + }(t) ? t : { + integerValue: 0 + } : null; +} + +/** Transforms a value into a server-generated timestamp. */ +class __PRIVATE_ServerTimestampTransform extends TransformOperation {} + +/** Transforms an array value via a union operation. */ class __PRIVATE_ArrayUnionTransformOperation extends TransformOperation { + constructor(e) { + super(), this.elements = e; + } +} + +function __PRIVATE_applyArrayUnionTransformOperation(e, t) { + const n = __PRIVATE_coercedFieldValuesArray(t); + for (const t of e.elements) n.some((e => __PRIVATE_valueEquals(e, t))) || n.push(t); + return { + arrayValue: { + values: n + } + }; +} + +/** Transforms an array value via a remove operation. */ class __PRIVATE_ArrayRemoveTransformOperation extends TransformOperation { + constructor(e) { + super(), this.elements = e; + } +} + +function __PRIVATE_applyArrayRemoveTransformOperation(e, t) { + let n = __PRIVATE_coercedFieldValuesArray(t); + for (const t of e.elements) n = n.filter((e => !__PRIVATE_valueEquals(e, t))); + return { + arrayValue: { + values: n + } + }; +} + +/** + * Implements the backend semantics for locally computed NUMERIC_ADD (increment) + * transforms. Converts all field values to integers or doubles, but unlike the + * backend does not cap integer values at 2^63. Instead, JavaScript number + * arithmetic is used and precision loss can occur for values greater than 2^53. + */ class __PRIVATE_NumericIncrementTransformOperation extends TransformOperation { + constructor(e, t) { + super(), this.serializer = e, this.Ae = t; + } +} + +function asNumber(e) { + return __PRIVATE_normalizeNumber(e.integerValue || e.doubleValue); +} + +function __PRIVATE_coercedFieldValuesArray(e) { + return isArray(e) && e.arrayValue.values ? e.arrayValue.values.slice() : []; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** A field path and the TransformOperation to perform upon it. */ class FieldTransform { + constructor(e, t) { + this.field = e, this.transform = t; + } +} + +function __PRIVATE_fieldTransformEquals(e, t) { + return e.field.isEqual(t.field) && function __PRIVATE_transformOperationEquals(e, t) { + return e instanceof __PRIVATE_ArrayUnionTransformOperation && t instanceof __PRIVATE_ArrayUnionTransformOperation || e instanceof __PRIVATE_ArrayRemoveTransformOperation && t instanceof __PRIVATE_ArrayRemoveTransformOperation ? __PRIVATE_arrayEquals(e.elements, t.elements, __PRIVATE_valueEquals) : e instanceof __PRIVATE_NumericIncrementTransformOperation && t instanceof __PRIVATE_NumericIncrementTransformOperation ? __PRIVATE_valueEquals(e.Ae, t.Ae) : e instanceof __PRIVATE_ServerTimestampTransform && t instanceof __PRIVATE_ServerTimestampTransform; + }(e.transform, t.transform); +} + +/** The result of successfully applying a mutation to the backend. */ +class MutationResult { + constructor( + /** + * The version at which the mutation was committed: + * + * - For most operations, this is the updateTime in the WriteResult. + * - For deletes, the commitTime of the WriteResponse (because deletes are + * not stored and have no updateTime). + * + * Note that these versions can be different: No-op writes will not change + * the updateTime even though the commitTime advances. + */ + e, + /** + * The resulting fields returned from the backend after a mutation + * containing field transforms has been committed. Contains one FieldValue + * for each FieldTransform that was in the mutation. + * + * Will be empty if the mutation did not contain any field transforms. + */ + t) { + this.version = e, this.transformResults = t; + } +} + +/** + * Encodes a precondition for a mutation. This follows the model that the + * backend accepts with the special case of an explicit "empty" precondition + * (meaning no precondition). + */ class Precondition { + constructor(e, t) { + this.updateTime = e, this.exists = t; + } + /** Creates a new empty Precondition. */ static none() { + return new Precondition; + } + /** Creates a new Precondition with an exists flag. */ static exists(e) { + return new Precondition(void 0, e); + } + /** Creates a new Precondition based on a version a document exists at. */ static updateTime(e) { + return new Precondition(e); + } + /** Returns whether this Precondition is empty. */ get isNone() { + return void 0 === this.updateTime && void 0 === this.exists; + } + isEqual(e) { + return this.exists === e.exists && (this.updateTime ? !!e.updateTime && this.updateTime.isEqual(e.updateTime) : !e.updateTime); + } +} + +/** Returns true if the preconditions is valid for the given document. */ function __PRIVATE_preconditionIsValidForDocument(e, t) { + return void 0 !== e.updateTime ? t.isFoundDocument() && t.version.isEqual(e.updateTime) : void 0 === e.exists || e.exists === t.isFoundDocument(); +} + +/** + * A mutation describes a self-contained change to a document. Mutations can + * create, replace, delete, and update subsets of documents. + * + * Mutations not only act on the value of the document but also its version. + * + * For local mutations (mutations that haven't been committed yet), we preserve + * the existing version for Set and Patch mutations. For Delete mutations, we + * reset the version to 0. + * + * Here's the expected transition table. + * + * MUTATION APPLIED TO RESULTS IN + * + * SetMutation Document(v3) Document(v3) + * SetMutation NoDocument(v3) Document(v0) + * SetMutation InvalidDocument(v0) Document(v0) + * PatchMutation Document(v3) Document(v3) + * PatchMutation NoDocument(v3) NoDocument(v3) + * PatchMutation InvalidDocument(v0) UnknownDocument(v3) + * DeleteMutation Document(v3) NoDocument(v0) + * DeleteMutation NoDocument(v3) NoDocument(v0) + * DeleteMutation InvalidDocument(v0) NoDocument(v0) + * + * For acknowledged mutations, we use the updateTime of the WriteResponse as + * the resulting version for Set and Patch mutations. As deletes have no + * explicit update time, we use the commitTime of the WriteResponse for + * Delete mutations. + * + * If a mutation is acknowledged by the backend but fails the precondition check + * locally, we transition to an `UnknownDocument` and rely on Watch to send us + * the updated version. + * + * Field transforms are used only with Patch and Set Mutations. We use the + * `updateTransforms` message to store transforms, rather than the `transforms`s + * messages. + * + * ## Subclassing Notes + * + * Every type of mutation needs to implement its own applyToRemoteDocument() and + * applyToLocalView() to implement the actual behavior of applying the mutation + * to some source document (see `setMutationApplyToRemoteDocument()` for an + * example). + */ class Mutation {} + +/** + * A utility method to calculate a `Mutation` representing the overlay from the + * final state of the document, and a `FieldMask` representing the fields that + * are mutated by the local mutations. + */ function __PRIVATE_calculateOverlayMutation(e, t) { + if (!e.hasLocalMutations || t && 0 === t.fields.length) return null; + // mask is null when sets or deletes are applied to the current document. + if (null === t) return e.isNoDocument() ? new __PRIVATE_DeleteMutation(e.key, Precondition.none()) : new __PRIVATE_SetMutation(e.key, e.data, Precondition.none()); + { + const n = e.data, r = ObjectValue.empty(); + let i = new SortedSet(FieldPath$1.comparator); + for (let e of t.fields) if (!i.has(e)) { + let t = n.field(e); + // If we are deleting a nested field, we take the immediate parent as + // the mask used to construct the resulting mutation. + // Justification: Nested fields can create parent fields implicitly. If + // only a leaf entry is deleted in later mutations, the parent field + // should still remain, but we may have lost this information. + // Consider mutation (foo.bar 1), then mutation (foo.bar delete()). + // This leaves the final result (foo, {}). Despite the fact that `doc` + // has the correct result, `foo` is not in `mask`, and the resulting + // mutation would miss `foo`. + null === t && e.length > 1 && (e = e.popLast(), t = n.field(e)), null === t ? r.delete(e) : r.set(e, t), + i = i.add(e); + } + return new __PRIVATE_PatchMutation(e.key, r, new FieldMask(i.toArray()), Precondition.none()); + } +} + +/** + * Applies this mutation to the given document for the purposes of computing a + * new remote document. If the input document doesn't match the expected state + * (e.g. it is invalid or outdated), the document type may transition to + * unknown. + * + * @param mutation - The mutation to apply. + * @param document - The document to mutate. The input document can be an + * invalid document if the client has no knowledge of the pre-mutation state + * of the document. + * @param mutationResult - The result of applying the mutation from the backend. + */ function __PRIVATE_mutationApplyToRemoteDocument(e, t, n) { + e instanceof __PRIVATE_SetMutation ? function __PRIVATE_setMutationApplyToRemoteDocument(e, t, n) { + // Unlike setMutationApplyToLocalView, if we're applying a mutation to a + // remote document the server has accepted the mutation so the precondition + // must have held. + const r = e.value.clone(), i = __PRIVATE_serverTransformResults(e.fieldTransforms, t, n.transformResults); + r.setAll(i), t.convertToFoundDocument(n.version, r).setHasCommittedMutations(); + }(e, t, n) : e instanceof __PRIVATE_PatchMutation ? function __PRIVATE_patchMutationApplyToRemoteDocument(e, t, n) { + if (!__PRIVATE_preconditionIsValidForDocument(e.precondition, t)) + // Since the mutation was not rejected, we know that the precondition + // matched on the backend. We therefore must not have the expected version + // of the document in our cache and convert to an UnknownDocument with a + // known updateTime. + return void t.convertToUnknownDocument(n.version); + const r = __PRIVATE_serverTransformResults(e.fieldTransforms, t, n.transformResults), i = t.data; + i.setAll(__PRIVATE_getPatch(e)), i.setAll(r), t.convertToFoundDocument(n.version, i).setHasCommittedMutations(); + }(e, t, n) : function __PRIVATE_deleteMutationApplyToRemoteDocument(e, t, n) { + // Unlike applyToLocalView, if we're applying a mutation to a remote + // document the server has accepted the mutation so the precondition must + // have held. + t.convertToNoDocument(n.version).setHasCommittedMutations(); + }(0, t, n); +} + +/** + * Applies this mutation to the given document for the purposes of computing + * the new local view of a document. If the input document doesn't match the + * expected state, the document is not modified. + * + * @param mutation - The mutation to apply. + * @param document - The document to mutate. The input document can be an + * invalid document if the client has no knowledge of the pre-mutation state + * of the document. + * @param previousMask - The fields that have been updated before applying this mutation. + * @param localWriteTime - A timestamp indicating the local write time of the + * batch this mutation is a part of. + * @returns A `FieldMask` representing the fields that are changed by applying this mutation. + */ function __PRIVATE_mutationApplyToLocalView(e, t, n, r) { + return e instanceof __PRIVATE_SetMutation ? function __PRIVATE_setMutationApplyToLocalView(e, t, n, r) { + if (!__PRIVATE_preconditionIsValidForDocument(e.precondition, t)) + // The mutation failed to apply (e.g. a document ID created with add() + // caused a name collision). + return n; + const i = e.value.clone(), s = __PRIVATE_localTransformResults(e.fieldTransforms, r, t); + return i.setAll(s), t.convertToFoundDocument(t.version, i).setHasLocalMutations(), + null; + // SetMutation overwrites all fields. + } + /** + * A mutation that modifies fields of the document at the given key with the + * given values. The values are applied through a field mask: + * + * * When a field is in both the mask and the values, the corresponding field + * is updated. + * * When a field is in neither the mask nor the values, the corresponding + * field is unmodified. + * * When a field is in the mask but not in the values, the corresponding field + * is deleted. + * * When a field is not in the mask but is in the values, the values map is + * ignored. + */ (e, t, n, r) : e instanceof __PRIVATE_PatchMutation ? function __PRIVATE_patchMutationApplyToLocalView(e, t, n, r) { + if (!__PRIVATE_preconditionIsValidForDocument(e.precondition, t)) return n; + const i = __PRIVATE_localTransformResults(e.fieldTransforms, r, t), s = t.data; + if (s.setAll(__PRIVATE_getPatch(e)), s.setAll(i), t.convertToFoundDocument(t.version, s).setHasLocalMutations(), + null === n) return null; + return n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map((e => e.field))); + } + /** + * Returns a FieldPath/Value map with the content of the PatchMutation. + */ (e, t, n, r) : function __PRIVATE_deleteMutationApplyToLocalView(e, t, n) { + if (__PRIVATE_preconditionIsValidForDocument(e.precondition, t)) return t.convertToNoDocument(t.version).setHasLocalMutations(), + null; + return n; + } + /** + * A mutation that verifies the existence of the document at the given key with + * the provided precondition. + * + * The `verify` operation is only used in Transactions, and this class serves + * primarily to facilitate serialization into protos. + */ (e, t, n); +} + +/** + * If this mutation is not idempotent, returns the base value to persist with + * this mutation. If a base value is returned, the mutation is always applied + * to this base value, even if document has already been updated. + * + * The base value is a sparse object that consists of only the document + * fields for which this mutation contains a non-idempotent transformation + * (e.g. a numeric increment). The provided value guarantees consistent + * behavior for non-idempotent transforms and allow us to return the same + * latency-compensated value even if the backend has already applied the + * mutation. The base value is null for idempotent mutations, as they can be + * re-played even if the backend has already applied them. + * + * @returns a base value to store along with the mutation, or null for + * idempotent mutations. + */ function __PRIVATE_mutationExtractBaseValue(e, t) { + let n = null; + for (const r of e.fieldTransforms) { + const e = t.data.field(r.field), i = __PRIVATE_computeTransformOperationBaseValue(r.transform, e || null); + null != i && (null === n && (n = ObjectValue.empty()), n.set(r.field, i)); + } + return n || null; +} + +function __PRIVATE_mutationEquals(e, t) { + return e.type === t.type && (!!e.key.isEqual(t.key) && (!!e.precondition.isEqual(t.precondition) && (!!function __PRIVATE_fieldTransformsAreEqual(e, t) { + return void 0 === e && void 0 === t || !(!e || !t) && __PRIVATE_arrayEquals(e, t, ((e, t) => __PRIVATE_fieldTransformEquals(e, t))); + }(e.fieldTransforms, t.fieldTransforms) && (0 /* MutationType.Set */ === e.type ? e.value.isEqual(t.value) : 1 /* MutationType.Patch */ !== e.type || e.data.isEqual(t.data) && e.fieldMask.isEqual(t.fieldMask))))); +} + +/** + * A mutation that creates or replaces the document at the given key with the + * object value contents. + */ class __PRIVATE_SetMutation extends Mutation { + constructor(e, t, n, r = []) { + super(), this.key = e, this.value = t, this.precondition = n, this.fieldTransforms = r, + this.type = 0 /* MutationType.Set */; + } + getFieldMask() { + return null; + } +} + +class __PRIVATE_PatchMutation extends Mutation { + constructor(e, t, n, r, i = []) { + super(), this.key = e, this.data = t, this.fieldMask = n, this.precondition = r, + this.fieldTransforms = i, this.type = 1 /* MutationType.Patch */; + } + getFieldMask() { + return this.fieldMask; + } +} + +function __PRIVATE_getPatch(e) { + const t = new Map; + return e.fieldMask.fields.forEach((n => { + if (!n.isEmpty()) { + const r = e.data.field(n); + t.set(n, r); + } + })), t; +} + +/** + * Creates a list of "transform results" (a transform result is a field value + * representing the result of applying a transform) for use after a mutation + * containing transforms has been acknowledged by the server. + * + * @param fieldTransforms - The field transforms to apply the result to. + * @param mutableDocument - The current state of the document after applying all + * previous mutations. + * @param serverTransformResults - The transform results received by the server. + * @returns The transform results list. + */ function __PRIVATE_serverTransformResults(e, t, n) { + const r = new Map; + __PRIVATE_hardAssert(e.length === n.length, 32656, { + Re: n.length, + Ve: e.length + }); + for (let i = 0; i < n.length; i++) { + const s = e[i], o = s.transform, _ = t.data.field(s.field); + r.set(s.field, __PRIVATE_applyTransformOperationToRemoteDocument(o, _, n[i])); + } + return r; +} + +/** + * Creates a list of "transform results" (a transform result is a field value + * representing the result of applying a transform) for use when applying a + * transform locally. + * + * @param fieldTransforms - The field transforms to apply the result to. + * @param localWriteTime - The local time of the mutation (used to + * generate ServerTimestampValues). + * @param mutableDocument - The document to apply transforms on. + * @returns The transform results list. + */ function __PRIVATE_localTransformResults(e, t, n) { + const r = new Map; + for (const i of e) { + const e = i.transform, s = n.data.field(i.field); + r.set(i.field, __PRIVATE_applyTransformOperationToLocalView(e, s, t)); + } + return r; +} + +/** A mutation that deletes the document at the given key. */ class __PRIVATE_DeleteMutation extends Mutation { + constructor(e, t) { + super(), this.key = e, this.precondition = t, this.type = 2 /* MutationType.Delete */ , + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } +} + +class __PRIVATE_VerifyMutation extends Mutation { + constructor(e, t) { + super(), this.key = e, this.precondition = t, this.type = 3 /* MutationType.Verify */ , + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A batch of mutations that will be sent as one unit to the backend. + */ class MutationBatch { + /** + * @param batchId - The unique ID of this mutation batch. + * @param localWriteTime - The original write time of this mutation. + * @param baseMutations - Mutations that are used to populate the base + * values when this mutation is applied locally. This can be used to locally + * overwrite values that are persisted in the remote document cache. Base + * mutations are never sent to the backend. + * @param mutations - The user-provided mutations in this mutation batch. + * User-provided mutations are applied both locally and remotely on the + * backend. + */ + constructor(e, t, n, r) { + this.batchId = e, this.localWriteTime = t, this.baseMutations = n, this.mutations = r; + } + /** + * Applies all the mutations in this MutationBatch to the specified document + * to compute the state of the remote document + * + * @param document - The document to apply mutations to. + * @param batchResult - The result of applying the MutationBatch to the + * backend. + */ applyToRemoteDocument(e, t) { + const n = t.mutationResults; + for (let t = 0; t < this.mutations.length; t++) { + const r = this.mutations[t]; + if (r.key.isEqual(e.key)) { + __PRIVATE_mutationApplyToRemoteDocument(r, e, n[t]); + } + } + } + /** + * Computes the local view of a document given all the mutations in this + * batch. + * + * @param document - The document to apply mutations to. + * @param mutatedFields - Fields that have been updated before applying this mutation batch. + * @returns A `FieldMask` representing all the fields that are mutated. + */ applyToLocalView(e, t) { + // First, apply the base state. This allows us to apply non-idempotent + // transform against a consistent set of values. + for (const n of this.baseMutations) n.key.isEqual(e.key) && (t = __PRIVATE_mutationApplyToLocalView(n, e, t, this.localWriteTime)); + // Second, apply all user-provided mutations. + for (const n of this.mutations) n.key.isEqual(e.key) && (t = __PRIVATE_mutationApplyToLocalView(n, e, t, this.localWriteTime)); + return t; + } + /** + * Computes the local view for all provided documents given the mutations in + * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to + * replace all the mutation applications. + */ applyToLocalDocumentSet(e, t) { + // TODO(mrschmidt): This implementation is O(n^2). If we apply the mutations + // directly (as done in `applyToLocalView()`), we can reduce the complexity + // to O(n). + const n = __PRIVATE_newMutationMap(); + return this.mutations.forEach((r => { + const i = e.get(r.key), s = i.overlayedDocument; + // TODO(mutabledocuments): This method should take a MutableDocumentMap + // and we should remove this cast. + let o = this.applyToLocalView(s, i.mutatedFields); + // Set mutatedFields to null if the document is only from local mutations. + // This creates a Set or Delete mutation, instead of trying to create a + // patch mutation as the overlay. + o = t.has(r.key) ? null : o; + const _ = __PRIVATE_calculateOverlayMutation(s, o); + null !== _ && n.set(r.key, _), s.isValidDocument() || s.convertToNoDocument(SnapshotVersion.min()); + })), n; + } + keys() { + return this.mutations.reduce(((e, t) => e.add(t.key)), __PRIVATE_documentKeySet()); + } + isEqual(e) { + return this.batchId === e.batchId && __PRIVATE_arrayEquals(this.mutations, e.mutations, ((e, t) => __PRIVATE_mutationEquals(e, t))) && __PRIVATE_arrayEquals(this.baseMutations, e.baseMutations, ((e, t) => __PRIVATE_mutationEquals(e, t))); + } +} + +/** The result of applying a mutation batch to the backend. */ class MutationBatchResult { + constructor(e, t, n, + /** + * A pre-computed mapping from each mutated document to the resulting + * version. + */ + r) { + this.batch = e, this.commitVersion = t, this.mutationResults = n, this.docVersions = r; + } + /** + * Creates a new MutationBatchResult for the given batch and results. There + * must be one result for each mutation in the batch. This static factory + * caches a document=>version mapping (docVersions). + */ static from(e, t, n) { + __PRIVATE_hardAssert(e.mutations.length === n.length, 58842, { + me: e.mutations.length, + fe: n.length + }); + let r = function __PRIVATE_documentVersionMap() { + return mt; + }(); + const i = e.mutations; + for (let e = 0; e < i.length; e++) r = r.insert(i[e].key, n[e].version); + return new MutationBatchResult(e, t, n, r); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Representation of an overlay computed by Firestore. + * + * Holds information about a mutation and the largest batch id in Firestore when + * the mutation was created. + */ class Overlay { + constructor(e, t) { + this.largestBatchId = e, this.mutation = t; + } + getKey() { + return this.mutation.key; + } + isEqual(e) { + return null !== e && this.mutation === e.mutation; + } + toString() { + return `Overlay{\n largestBatchId: ${this.largestBatchId},\n mutation: ${this.mutation.toString()}\n }`; + } +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Concrete implementation of the Aggregate type. + */ class __PRIVATE_AggregateImpl { + constructor(e, t, n) { + this.alias = e, this.aggregateType = t, this.fieldPath = n; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class ExistenceFilter { + constructor(e, t) { + this.count = e, this.unchangedNames = t; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Error Codes describing the different ways GRPC can fail. These are copied + * directly from GRPC's sources here: + * + * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h + * + * Important! The names of these identifiers matter because the string forms + * are used for reverse lookups from the webchannel stream. Do NOT change the + * names of these identifiers or change this into a const enum. + */ var pt, yt; + +/** + * Determines whether an error code represents a permanent error when received + * in response to a non-write operation. + * + * See isPermanentWriteError for classifying write errors. + */ +function __PRIVATE_isPermanentError(e) { + switch (e) { + case N.OK: + return fail(64938); + + case N.CANCELLED: + case N.UNKNOWN: + case N.DEADLINE_EXCEEDED: + case N.RESOURCE_EXHAUSTED: + case N.INTERNAL: + case N.UNAVAILABLE: + // Unauthenticated means something went wrong with our token and we need + // to retry with new credentials which will happen automatically. + case N.UNAUTHENTICATED: + return !1; + + case N.INVALID_ARGUMENT: + case N.NOT_FOUND: + case N.ALREADY_EXISTS: + case N.PERMISSION_DENIED: + case N.FAILED_PRECONDITION: + // Aborted might be retried in some scenarios, but that is dependent on + // the context and should handled individually by the calling code. + // See https://cloud.google.com/apis/design/errors. + case N.ABORTED: + case N.OUT_OF_RANGE: + case N.UNIMPLEMENTED: + case N.DATA_LOSS: + return !0; + + default: + return fail(15467, { + code: e + }); + } +} + +/** + * Determines whether an error code represents a permanent error when received + * in response to a write operation. + * + * Write operations must be handled specially because as of b/119437764, ABORTED + * errors on the write stream should be retried too (even though ABORTED errors + * are not generally retryable). + * + * Note that during the initial handshake on the write stream an ABORTED error + * signals that we should discard our stream token (i.e. it is permanent). This + * means a handshake error should be classified with isPermanentError, above. + */ +/** + * Maps an error Code from GRPC status code number, like 0, 1, or 14. These + * are not the same as HTTP status codes. + * + * @returns The Code equivalent to the given GRPC status code. Fails if there + * is no match. + */ +function __PRIVATE_mapCodeFromRpcCode(e) { + if (void 0 === e) + // This shouldn't normally happen, but in certain error cases (like trying + // to send invalid proto messages) we may get an error with no GRPC code. + return __PRIVATE_logError("GRPC error has no .code"), N.UNKNOWN; + switch (e) { + case pt.OK: + return N.OK; + + case pt.CANCELLED: + return N.CANCELLED; + + case pt.UNKNOWN: + return N.UNKNOWN; + + case pt.DEADLINE_EXCEEDED: + return N.DEADLINE_EXCEEDED; + + case pt.RESOURCE_EXHAUSTED: + return N.RESOURCE_EXHAUSTED; + + case pt.INTERNAL: + return N.INTERNAL; + + case pt.UNAVAILABLE: + return N.UNAVAILABLE; + + case pt.UNAUTHENTICATED: + return N.UNAUTHENTICATED; + + case pt.INVALID_ARGUMENT: + return N.INVALID_ARGUMENT; + + case pt.NOT_FOUND: + return N.NOT_FOUND; + + case pt.ALREADY_EXISTS: + return N.ALREADY_EXISTS; + + case pt.PERMISSION_DENIED: + return N.PERMISSION_DENIED; + + case pt.FAILED_PRECONDITION: + return N.FAILED_PRECONDITION; + + case pt.ABORTED: + return N.ABORTED; + + case pt.OUT_OF_RANGE: + return N.OUT_OF_RANGE; + + case pt.UNIMPLEMENTED: + return N.UNIMPLEMENTED; + + case pt.DATA_LOSS: + return N.DATA_LOSS; + + default: + return fail(39323, { + code: e + }); + } +} + +/** + * Converts an HTTP response's error status to the equivalent error code. + * + * @param status - An HTTP error response status ("FAILED_PRECONDITION", + * "UNKNOWN", etc.) + * @returns The equivalent Code. Non-matching responses are mapped to + * Code.UNKNOWN. + */ (yt = pt || (pt = {}))[yt.OK = 0] = "OK", yt[yt.CANCELLED = 1] = "CANCELLED", +yt[yt.UNKNOWN = 2] = "UNKNOWN", yt[yt.INVALID_ARGUMENT = 3] = "INVALID_ARGUMENT", +yt[yt.DEADLINE_EXCEEDED = 4] = "DEADLINE_EXCEEDED", yt[yt.NOT_FOUND = 5] = "NOT_FOUND", +yt[yt.ALREADY_EXISTS = 6] = "ALREADY_EXISTS", yt[yt.PERMISSION_DENIED = 7] = "PERMISSION_DENIED", +yt[yt.UNAUTHENTICATED = 16] = "UNAUTHENTICATED", yt[yt.RESOURCE_EXHAUSTED = 8] = "RESOURCE_EXHAUSTED", +yt[yt.FAILED_PRECONDITION = 9] = "FAILED_PRECONDITION", yt[yt.ABORTED = 10] = "ABORTED", +yt[yt.OUT_OF_RANGE = 11] = "OUT_OF_RANGE", yt[yt.UNIMPLEMENTED = 12] = "UNIMPLEMENTED", +yt[yt.INTERNAL = 13] = "INTERNAL", yt[yt.UNAVAILABLE = 14] = "UNAVAILABLE", yt[yt.DATA_LOSS = 15] = "DATA_LOSS"; + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The global, singleton instance of TestingHooksSpi. + * + * This variable will be `null` in all cases _except_ when running from + * integration tests that have registered callbacks to be notified of events + * that happen during the test execution. + */ +let wt = null; + +/** + * Sets the value of the `testingHooksSpi` object. + * @param instance the instance to set. + */ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An instance of the Platform's 'TextEncoder' implementation. + */ +function __PRIVATE_newTextEncoder() { + return new TextEncoder; +} + +/** + * An instance of the Platform's 'TextDecoder' implementation. + */ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const St = new Integer([ 4294967295, 4294967295 ], 0); + +// Hash a string using md5 hashing algorithm. +function __PRIVATE_getMd5HashValue(e) { + const t = __PRIVATE_newTextEncoder().encode(e), n = new Md5; + return n.update(t), new Uint8Array(n.digest()); +} + +// Interpret the 16 bytes array as two 64-bit unsigned integers, encoded using +// 2’s complement using little endian. +function __PRIVATE_get64BitUints(e) { + const t = new DataView(e.buffer), n = t.getUint32(0, /* littleEndian= */ !0), r = t.getUint32(4, /* littleEndian= */ !0), i = t.getUint32(8, /* littleEndian= */ !0), s = t.getUint32(12, /* littleEndian= */ !0); + return [ new Integer([ n, r ], 0), new Integer([ i, s ], 0) ]; +} + +class BloomFilter { + constructor(e, t, n) { + if (this.bitmap = e, this.padding = t, this.hashCount = n, t < 0 || t >= 8) throw new __PRIVATE_BloomFilterError(`Invalid padding: ${t}`); + if (n < 0) throw new __PRIVATE_BloomFilterError(`Invalid hash count: ${n}`); + if (e.length > 0 && 0 === this.hashCount) + // Only empty bloom filter can have 0 hash count. + throw new __PRIVATE_BloomFilterError(`Invalid hash count: ${n}`); + if (0 === e.length && 0 !== t) + // Empty bloom filter should have 0 padding. + throw new __PRIVATE_BloomFilterError(`Invalid padding when bitmap length is 0: ${t}`); + this.ge = 8 * e.length - t, + // Set the bit count in Integer to avoid repetition in mightContain(). + this.pe = Integer.fromNumber(this.ge); + } + // Calculate the ith hash value based on the hashed 64bit integers, + // and calculate its corresponding bit index in the bitmap to be checked. + ye(e, t, n) { + // Calculate hashed value h(i) = h1 + (i * h2). + let r = e.add(t.multiply(Integer.fromNumber(n))); + // Wrap if hash value overflow 64bit. + return 1 === r.compare(St) && (r = new Integer([ r.getBits(0), r.getBits(1) ], 0)), + r.modulo(this.pe).toNumber(); + } + // Return whether the bit on the given index in the bitmap is set to 1. + we(e) { + return !!(this.bitmap[Math.floor(e / 8)] & 1 << e % 8); + } + mightContain(e) { + // Empty bitmap should always return false on membership check. + if (0 === this.ge) return !1; + const t = __PRIVATE_getMd5HashValue(e), [n, r] = __PRIVATE_get64BitUints(t); + for (let e = 0; e < this.hashCount; e++) { + const t = this.ye(n, r, e); + if (!this.we(t)) return !1; + } + return !0; + } + /** Create bloom filter for testing purposes only. */ static create(e, t, n) { + const r = e % 8 == 0 ? 0 : 8 - e % 8, i = new Uint8Array(Math.ceil(e / 8)), s = new BloomFilter(i, r, t); + return n.forEach((e => s.insert(e))), s; + } + insert(e) { + if (0 === this.ge) return; + const t = __PRIVATE_getMd5HashValue(e), [n, r] = __PRIVATE_get64BitUints(t); + for (let e = 0; e < this.hashCount; e++) { + const t = this.ye(n, r, e); + this.Se(t); + } + } + Se(e) { + const t = Math.floor(e / 8), n = e % 8; + this.bitmap[t] |= 1 << n; + } +} + +class __PRIVATE_BloomFilterError extends Error { + constructor() { + super(...arguments), this.name = "BloomFilterError"; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An event from the RemoteStore. It is split into targetChanges (changes to the + * state or the set of documents in our watched targets) and documentUpdates + * (changes to the actual documents). + */ class RemoteEvent { + constructor( + /** + * The snapshot version this event brings us up to, or MIN if not set. + */ + e, + /** + * A map from target to changes to the target. See TargetChange. + */ + t, + /** + * A map of targets that is known to be inconsistent, and the purpose for + * re-listening. Listens for these targets should be re-established without + * resume tokens. + */ + n, + /** + * A set of which documents have changed or been deleted, along with the + * doc's new values (if not deleted). + */ + r, + /** + * A set of which document updates are due only to limbo resolution targets. + */ + i) { + this.snapshotVersion = e, this.targetChanges = t, this.targetMismatches = n, this.documentUpdates = r, + this.resolvedLimboDocuments = i; + } + /** + * HACK: Views require RemoteEvents in order to determine whether the view is + * CURRENT, but secondary tabs don't receive remote events. So this method is + * used to create a synthesized RemoteEvent that can be used to apply a + * CURRENT status change to a View, for queries executed in a different tab. + */ + // PORTING NOTE: Multi-tab only + static createSynthesizedRemoteEventForCurrentChange(e, t, n) { + const r = new Map; + return r.set(e, TargetChange.createSynthesizedTargetChangeForCurrentChange(e, t, n)), + new RemoteEvent(SnapshotVersion.min(), r, new SortedMap(__PRIVATE_primitiveComparator), __PRIVATE_mutableDocumentMap(), __PRIVATE_documentKeySet()); + } +} + +/** + * A TargetChange specifies the set of changes for a specific target as part of + * a RemoteEvent. These changes track which documents are added, modified or + * removed, as well as the target's resume token and whether the target is + * marked CURRENT. + * The actual changes *to* documents are not part of the TargetChange since + * documents may be part of multiple targets. + */ class TargetChange { + constructor( + /** + * An opaque, server-assigned token that allows watching a query to be resumed + * after disconnecting without retransmitting all the data that matches the + * query. The resume token essentially identifies a point in time from which + * the server should resume sending results. + */ + e, + /** + * The "current" (synced) status of this target. Note that "current" + * has special meaning in the RPC protocol that implies that a target is + * both up-to-date and consistent with the rest of the watch stream. + */ + t, + /** + * The set of documents that were newly assigned to this target as part of + * this remote event. + */ + n, + /** + * The set of documents that were already assigned to this target but received + * an update during this remote event. + */ + r, + /** + * The set of documents that were removed from this target as part of this + * remote event. + */ + i) { + this.resumeToken = e, this.current = t, this.addedDocuments = n, this.modifiedDocuments = r, + this.removedDocuments = i; + } + /** + * This method is used to create a synthesized TargetChanges that can be used to + * apply a CURRENT status change to a View (for queries executed in a different + * tab) or for new queries (to raise snapshots with correct CURRENT status). + */ static createSynthesizedTargetChangeForCurrentChange(e, t, n) { + return new TargetChange(n, t, __PRIVATE_documentKeySet(), __PRIVATE_documentKeySet(), __PRIVATE_documentKeySet()); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a changed document and a list of target ids to which this change + * applies. + * + * If document has been deleted NoDocument will be provided. + */ class __PRIVATE_DocumentWatchChange { + constructor( + /** The new document applies to all of these targets. */ + e, + /** The new document is removed from all of these targets. */ + t, + /** The key of the document for this change. */ + n, + /** + * The new document or NoDocument if it was deleted. Is null if the + * document went out of view without the server sending a new document. + */ + r) { + this.be = e, this.removedTargetIds = t, this.key = n, this.De = r; + } +} + +class __PRIVATE_ExistenceFilterChange { + constructor(e, t) { + this.targetId = e, this.Ce = t; + } +} + +class __PRIVATE_WatchTargetChange { + constructor( + /** What kind of change occurred to the watch target. */ + e, + /** The target IDs that were added/removed/set. */ + t, + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + n = ByteString.EMPTY_BYTE_STRING + /** An RPC error indicating why the watch failed. */ , r = null) { + this.state = e, this.targetIds = t, this.resumeToken = n, this.cause = r; + } +} + +/** Tracks the internal state of a Watch target. */ class __PRIVATE_TargetState { + constructor() { + /** + * The number of pending responses (adds or removes) that we are waiting on. + * We only consider targets active that have no pending responses. + */ + this.ve = 0, + /** + * Keeps track of the document changes since the last raised snapshot. + * + * These changes are continuously updated as we receive document updates and + * always reflect the current set of changes against the last issued snapshot. + */ + this.Fe = __PRIVATE_snapshotChangesMap(), + /** See public getters for explanations of these fields. */ + this.Me = ByteString.EMPTY_BYTE_STRING, this.xe = !1, + /** + * Whether this target state should be included in the next snapshot. We + * initialize to true so that newly-added targets are included in the next + * RemoteEvent. + */ + this.Oe = !0; + } + /** + * Whether this target has been marked 'current'. + * + * 'Current' has special meaning in the RPC protocol: It implies that the + * Watch backend has sent us all changes up to the point at which the target + * was added and that the target is consistent with the rest of the watch + * stream. + */ get current() { + return this.xe; + } + /** The last resume token sent to us for this target. */ get resumeToken() { + return this.Me; + } + /** Whether this target has pending target adds or target removes. */ get Ne() { + return 0 !== this.ve; + } + /** Whether we have modified any state that should trigger a snapshot. */ get Be() { + return this.Oe; + } + /** + * Applies the resume token to the TargetChange, but only when it has a new + * value. Empty resumeTokens are discarded. + */ Le(e) { + e.approximateByteSize() > 0 && (this.Oe = !0, this.Me = e); + } + /** + * Creates a target change from the current set of changes. + * + * To reset the document changes after raising this snapshot, call + * `clearPendingChanges()`. + */ ke() { + let e = __PRIVATE_documentKeySet(), t = __PRIVATE_documentKeySet(), n = __PRIVATE_documentKeySet(); + return this.Fe.forEach(((r, i) => { + switch (i) { + case 0 /* ChangeType.Added */ : + e = e.add(r); + break; + + case 2 /* ChangeType.Modified */ : + t = t.add(r); + break; + + case 1 /* ChangeType.Removed */ : + n = n.add(r); + break; + + default: + fail(38017, { + changeType: i + }); + } + })), new TargetChange(this.Me, this.xe, e, t, n); + } + /** + * Resets the document changes and sets `hasPendingChanges` to false. + */ qe() { + this.Oe = !1, this.Fe = __PRIVATE_snapshotChangesMap(); + } + Qe(e, t) { + this.Oe = !0, this.Fe = this.Fe.insert(e, t); + } + $e(e) { + this.Oe = !0, this.Fe = this.Fe.remove(e); + } + Ue() { + this.ve += 1; + } + Ke() { + this.ve -= 1, __PRIVATE_hardAssert(this.ve >= 0, 3241, { + ve: this.ve + }); + } + We() { + this.Oe = !0, this.xe = !0; + } +} + +/** + * A helper class to accumulate watch changes into a RemoteEvent. + */ +class __PRIVATE_WatchChangeAggregator { + constructor(e) { + this.Ge = e, + /** The internal state of all tracked targets. */ + this.ze = new Map, + /** Keeps track of the documents to update since the last raised snapshot. */ + this.je = __PRIVATE_mutableDocumentMap(), this.Je = __PRIVATE_documentTargetMap(), + /** A mapping of document keys to their set of target IDs. */ + this.He = __PRIVATE_documentTargetMap(), + /** + * A map of targets with existence filter mismatches. These targets are + * known to be inconsistent and their listens needs to be re-established by + * RemoteStore. + */ + this.Ye = new SortedMap(__PRIVATE_primitiveComparator); + } + /** + * Processes and adds the DocumentWatchChange to the current set of changes. + */ Ze(e) { + for (const t of e.be) e.De && e.De.isFoundDocument() ? this.Xe(t, e.De) : this.et(t, e.key, e.De); + for (const t of e.removedTargetIds) this.et(t, e.key, e.De); + } + /** Processes and adds the WatchTargetChange to the current set of changes. */ tt(e) { + this.forEachTarget(e, (t => { + const n = this.nt(t); + switch (e.state) { + case 0 /* WatchTargetChangeState.NoChange */ : + this.rt(t) && n.Le(e.resumeToken); + break; + + case 1 /* WatchTargetChangeState.Added */ : + // We need to decrement the number of pending acks needed from watch + // for this targetId. + n.Ke(), n.Ne || + // We have a freshly added target, so we need to reset any state + // that we had previously. This can happen e.g. when remove and add + // back a target for existence filter mismatches. + n.qe(), n.Le(e.resumeToken); + break; + + case 2 /* WatchTargetChangeState.Removed */ : + // We need to keep track of removed targets to we can post-filter and + // remove any target changes. + // We need to decrement the number of pending acks needed from watch + // for this targetId. + n.Ke(), n.Ne || this.removeTarget(t); + break; + + case 3 /* WatchTargetChangeState.Current */ : + this.rt(t) && (n.We(), n.Le(e.resumeToken)); + break; + + case 4 /* WatchTargetChangeState.Reset */ : + this.rt(t) && ( + // Reset the target and synthesizes removes for all existing + // documents. The backend will re-add any documents that still + // match the target before it sends the next global snapshot. + this.it(t), n.Le(e.resumeToken)); + break; + + default: + fail(56790, { + state: e.state + }); + } + })); + } + /** + * Iterates over all targetIds that the watch change applies to: either the + * targetIds explicitly listed in the change or the targetIds of all currently + * active targets. + */ forEachTarget(e, t) { + e.targetIds.length > 0 ? e.targetIds.forEach(t) : this.ze.forEach(((e, n) => { + this.rt(n) && t(n); + })); + } + /** + * Handles existence filters and synthesizes deletes for filter mismatches. + * Targets that are invalidated by filter mismatches are added to + * `pendingTargetResets`. + */ st(e) { + const t = e.targetId, n = e.Ce.count, r = this.ot(t); + if (r) { + const i = r.target; + if (__PRIVATE_targetIsDocumentTarget(i)) if (0 === n) { + // The existence filter told us the document does not exist. We deduce + // that this document does not exist and apply a deleted document to + // our updates. Without applying this deleted document there might be + // another query that will raise this document as part of a snapshot + // until it is resolved, essentially exposing inconsistency between + // queries. + const e = new DocumentKey(i.path); + this.et(t, e, MutableDocument.newNoDocument(e, SnapshotVersion.min())); + } else __PRIVATE_hardAssert(1 === n, 20013, { + expectedCount: n + }); else { + const r = this._t(t); + // Existence filter mismatch. Mark the documents as being in limbo, and + // raise a snapshot with `isFromCache:true`. + if (r !== n) { + // Apply bloom filter to identify and mark removed documents. + const n = this.ut(e), i = n ? this.ct(n, e, r) : 1 /* BloomFilterApplicationStatus.Skipped */; + if (0 /* BloomFilterApplicationStatus.Success */ !== i) { + // If bloom filter application fails, we reset the mapping and + // trigger re-run of the query. + this.it(t); + const e = 2 /* BloomFilterApplicationStatus.FalsePositive */ === i ? "TargetPurposeExistenceFilterMismatchBloom" /* TargetPurpose.ExistenceFilterMismatchBloom */ : "TargetPurposeExistenceFilterMismatch" /* TargetPurpose.ExistenceFilterMismatch */; + this.Ye = this.Ye.insert(t, e); + } + wt?.lt(function __PRIVATE_createExistenceFilterMismatchInfoForTestingHooks(e, t, n, r, i) { + const s = { + localCacheCount: e, + existenceFilterCount: t.count, + databaseId: n.database, + projectId: n.projectId + }, o = t.unchangedNames; + o && (s.bloomFilter = { + applied: 0 /* BloomFilterApplicationStatus.Success */ === i, + hashCount: o?.hashCount ?? 0, + bitmapLength: o?.bits?.bitmap?.length ?? 0, + padding: o?.bits?.padding ?? 0, + mightContain: e => r?.mightContain(e) ?? !1 + }); + return s; + } + /** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ (r, e.Ce, this.Ge.ht(), n, i)); + } + } + } + } + /** + * Parse the bloom filter from the "unchanged_names" field of an existence + * filter. + */ ut(e) { + const t = e.Ce.unchangedNames; + if (!t || !t.bits) return null; + const {bits: {bitmap: n = "", padding: r = 0}, hashCount: i = 0} = t; + let s, o; + try { + s = __PRIVATE_normalizeByteString(n).toUint8Array(); + } catch (e) { + if (e instanceof __PRIVATE_Base64DecodeError) return __PRIVATE_logWarn("Decoding the base64 bloom filter in existence filter failed (" + e.message + "); ignoring the bloom filter and falling back to full re-query."), + null; + throw e; + } + try { + // BloomFilter throws error if the inputs are invalid. + o = new BloomFilter(s, r, i); + } catch (e) { + return __PRIVATE_logWarn(e instanceof __PRIVATE_BloomFilterError ? "BloomFilter error: " : "Applying bloom filter failed: ", e), + null; + } + return 0 === o.ge ? null : o; + } + /** + * Apply bloom filter to remove the deleted documents, and return the + * application status. + */ ct(e, t, n) { + return t.Ce.count === n - this.Pt(e, t.targetId) ? 0 /* BloomFilterApplicationStatus.Success */ : 2 /* BloomFilterApplicationStatus.FalsePositive */; + } + /** + * Filter out removed documents based on bloom filter membership result and + * return number of documents removed. + */ Pt(e, t) { + const n = this.Ge.getRemoteKeysForTarget(t); + let r = 0; + return n.forEach((n => { + const i = this.Ge.ht(), s = `projects/${i.projectId}/databases/${i.database}/documents/${n.path.canonicalString()}`; + e.mightContain(s) || (this.et(t, n, /*updatedDocument=*/ null), r++); + })), r; + } + /** + * Converts the currently accumulated state into a remote event at the + * provided snapshot version. Resets the accumulated changes before returning. + */ Tt(e) { + const t = new Map; + this.ze.forEach(((n, r) => { + const i = this.ot(r); + if (i) { + if (n.current && __PRIVATE_targetIsDocumentTarget(i.target)) { + // Document queries for document that don't exist can produce an empty + // result set. To update our local cache, we synthesize a document + // delete if we have not previously received the document for this + // target. This resolves the limbo state of the document, removing it + // from limboDocumentRefs. + // TODO(dimond): Ideally we would have an explicit lookup target + // instead resulting in an explicit delete message and we could + // remove this special logic. + const t = new DocumentKey(i.target.path); + this.It(t).has(r) || this.Et(r, t) || this.et(r, t, MutableDocument.newNoDocument(t, e)); + } + n.Be && (t.set(r, n.ke()), n.qe()); + } + })); + let n = __PRIVATE_documentKeySet(); + // We extract the set of limbo-only document updates as the GC logic + // special-cases documents that do not appear in the target cache. + + // TODO(gsoltis): Expand on this comment once GC is available in the JS + // client. + this.He.forEach(((e, t) => { + let r = !0; + t.forEachWhile((e => { + const t = this.ot(e); + return !t || "TargetPurposeLimboResolution" /* TargetPurpose.LimboResolution */ === t.purpose || (r = !1, + !1); + })), r && (n = n.add(e)); + })), this.je.forEach(((t, n) => n.setReadTime(e))); + const r = new RemoteEvent(e, t, this.Ye, this.je, n); + return this.je = __PRIVATE_mutableDocumentMap(), this.Je = __PRIVATE_documentTargetMap(), + this.He = __PRIVATE_documentTargetMap(), this.Ye = new SortedMap(__PRIVATE_primitiveComparator), + r; + } + /** + * Adds the provided document to the internal list of document updates and + * its document key to the given target's mapping. + */ + // Visible for testing. + Xe(e, t) { + if (!this.rt(e)) return; + const n = this.Et(e, t.key) ? 2 /* ChangeType.Modified */ : 0 /* ChangeType.Added */; + this.nt(e).Qe(t.key, n), this.je = this.je.insert(t.key, t), this.Je = this.Je.insert(t.key, this.It(t.key).add(e)), + this.He = this.He.insert(t.key, this.dt(t.key).add(e)); + } + /** + * Removes the provided document from the target mapping. If the + * document no longer matches the target, but the document's state is still + * known (e.g. we know that the document was deleted or we received the change + * that caused the filter mismatch), the new document can be provided + * to update the remote document cache. + */ + // Visible for testing. + et(e, t, n) { + if (!this.rt(e)) return; + const r = this.nt(e); + this.Et(e, t) ? r.Qe(t, 1 /* ChangeType.Removed */) : + // The document may have entered and left the target before we raised a + // snapshot, so we can just ignore the change. + r.$e(t), this.He = this.He.insert(t, this.dt(t).delete(e)), this.He = this.He.insert(t, this.dt(t).add(e)), + n && (this.je = this.je.insert(t, n)); + } + removeTarget(e) { + this.ze.delete(e); + } + /** + * Returns the current count of documents in the target. This includes both + * the number of documents that the LocalStore considers to be part of the + * target as well as any accumulated changes. + */ _t(e) { + const t = this.nt(e).ke(); + return this.Ge.getRemoteKeysForTarget(e).size + t.addedDocuments.size - t.removedDocuments.size; + } + /** + * Increment the number of acks needed from watch before we can consider the + * server to be 'in-sync' with the client's active targets. + */ Ue(e) { + this.nt(e).Ue(); + } + nt(e) { + let t = this.ze.get(e); + return t || (t = new __PRIVATE_TargetState, this.ze.set(e, t)), t; + } + dt(e) { + let t = this.He.get(e); + return t || (t = new SortedSet(__PRIVATE_primitiveComparator), this.He = this.He.insert(e, t)), + t; + } + It(e) { + let t = this.Je.get(e); + return t || (t = new SortedSet(__PRIVATE_primitiveComparator), this.Je = this.Je.insert(e, t)), + t; + } + /** + * Verifies that the user is still interested in this target (by calling + * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs + * from watch. + */ rt(e) { + const t = null !== this.ot(e); + return t || __PRIVATE_logDebug("WatchChangeAggregator", "Detected inactive target", e), + t; + } + /** + * Returns the TargetData for an active target (i.e. a target that the user + * is still interested in that has no outstanding target change requests). + */ ot(e) { + const t = this.ze.get(e); + return t && t.Ne ? null : this.Ge.At(e); + } + /** + * Resets the state of a Watch target to its initial state (e.g. sets + * 'current' to false, clears the resume token and removes its target mapping + * from all documents). + */ it(e) { + this.ze.set(e, new __PRIVATE_TargetState); + this.Ge.getRemoteKeysForTarget(e).forEach((t => { + this.et(e, t, /*updatedDocument=*/ null); + })); + } + /** + * Returns whether the LocalStore considers the document to be part of the + * specified target. + */ Et(e, t) { + return this.Ge.getRemoteKeysForTarget(e).has(t); + } +} + +function __PRIVATE_documentTargetMap() { + return new SortedMap(DocumentKey.comparator); +} + +function __PRIVATE_snapshotChangesMap() { + return new SortedMap(DocumentKey.comparator); +} + +const bt = (() => { + const e = { + asc: "ASCENDING", + desc: "DESCENDING" + }; + return e; +})(), Dt = (() => { + const e = { + "<": "LESS_THAN", + "<=": "LESS_THAN_OR_EQUAL", + ">": "GREATER_THAN", + ">=": "GREATER_THAN_OR_EQUAL", + "==": "EQUAL", + "!=": "NOT_EQUAL", + "array-contains": "ARRAY_CONTAINS", + in: "IN", + "not-in": "NOT_IN", + "array-contains-any": "ARRAY_CONTAINS_ANY" + }; + return e; +})(), Ct = (() => { + const e = { + and: "AND", + or: "OR" + }; + return e; +})(); + +/** + * This class generates JsonObject values for the Datastore API suitable for + * sending to either GRPC stub methods or via the JSON/HTTP REST API. + * + * The serializer supports both Protobuf.js and Proto3 JSON formats. By + * setting `useProto3Json` to true, the serializer will use the Proto3 JSON + * format. + * + * For a description of the Proto3 JSON format check + * https://developers.google.com/protocol-buffers/docs/proto3#json + * + * TODO(klimt): We can remove the databaseId argument if we keep the full + * resource name in documents. + */ +class JsonProtoSerializer { + constructor(e, t) { + this.databaseId = e, this.useProto3Json = t; + } +} + +/** + * Returns a value for a number (or null) that's appropriate to put into + * a google.protobuf.Int32Value proto. + * DO NOT USE THIS FOR ANYTHING ELSE. + * This method cheats. It's typed as returning "number" because that's what + * our generated proto interfaces say Int32Value must be. But GRPC actually + * expects a { value: } struct. + */ +function __PRIVATE_toInt32Proto(e, t) { + return e.useProto3Json || __PRIVATE_isNullOrUndefined(t) ? t : { + value: t + }; +} + +/** + * Returns a number (or null) from a google.protobuf.Int32Value proto. + */ +/** + * Returns a value for a Date that's appropriate to put into a proto. + */ +function toTimestamp(e, t) { + if (e.useProto3Json) { + return `${new Date(1e3 * t.seconds).toISOString().replace(/\.\d*/, "").replace("Z", "")}.${("000000000" + t.nanoseconds).slice(-9)}Z`; + } + return { + seconds: "" + t.seconds, + nanos: t.nanoseconds + }; +} + +/** + * Returns a Timestamp typed object given protobuf timestamp value. + */ +/** + * Returns a value for bytes that's appropriate to put in a proto. + * + * Visible for testing. + */ +function __PRIVATE_toBytes(e, t) { + return e.useProto3Json ? t.toBase64() : t.toUint8Array(); +} + +/** + * Returns a ByteString based on the proto string value. + */ function __PRIVATE_toVersion(e, t) { + return toTimestamp(e, t.toTimestamp()); +} + +function __PRIVATE_fromVersion(e) { + return __PRIVATE_hardAssert(!!e, 49232), SnapshotVersion.fromTimestamp(function fromTimestamp(e) { + const t = __PRIVATE_normalizeTimestamp(e); + return new Timestamp(t.seconds, t.nanos); + }(e)); +} + +function __PRIVATE_toResourceName(e, t) { + return __PRIVATE_toResourcePath(e, t).canonicalString(); +} + +function __PRIVATE_toResourcePath(e, t) { + const n = function __PRIVATE_fullyQualifiedPrefixPath(e) { + return new ResourcePath([ "projects", e.projectId, "databases", e.database ]); + }(e).child("documents"); + return void 0 === t ? n : n.child(t); +} + +function __PRIVATE_fromResourceName(e) { + const t = ResourcePath.fromString(e); + return __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(t), 10190, { + key: t.toString() + }), t; +} + +function __PRIVATE_toName(e, t) { + return __PRIVATE_toResourceName(e.databaseId, t.path); +} + +function fromName(e, t) { + const n = __PRIVATE_fromResourceName(t); + if (n.get(1) !== e.databaseId.projectId) throw new FirestoreError(N.INVALID_ARGUMENT, "Tried to deserialize key from different project: " + n.get(1) + " vs " + e.databaseId.projectId); + if (n.get(3) !== e.databaseId.database) throw new FirestoreError(N.INVALID_ARGUMENT, "Tried to deserialize key from different database: " + n.get(3) + " vs " + e.databaseId.database); + return new DocumentKey(__PRIVATE_extractLocalPathFromResourceName(n)); +} + +function __PRIVATE_toQueryPath(e, t) { + return __PRIVATE_toResourceName(e.databaseId, t); +} + +function __PRIVATE_fromQueryPath(e) { + const t = __PRIVATE_fromResourceName(e); + // In v1beta1 queries for collections at the root did not have a trailing + // "/documents". In v1 all resource paths contain "/documents". Preserve the + // ability to read the v1beta1 form for compatibility with queries persisted + // in the local target cache. + return 4 === t.length ? ResourcePath.emptyPath() : __PRIVATE_extractLocalPathFromResourceName(t); +} + +function __PRIVATE_getEncodedDatabaseId(e) { + return new ResourcePath([ "projects", e.databaseId.projectId, "databases", e.databaseId.database ]).canonicalString(); +} + +function __PRIVATE_extractLocalPathFromResourceName(e) { + return __PRIVATE_hardAssert(e.length > 4 && "documents" === e.get(4), 29091, { + key: e.toString() + }), e.popFirst(5); +} + +/** Creates a Document proto from key and fields (but no create/update time) */ function __PRIVATE_toMutationDocument(e, t, n) { + return { + name: __PRIVATE_toName(e, t), + fields: n.value.mapValue.fields + }; +} + +function __PRIVATE_fromDocument(e, t, n) { + const r = fromName(e, t.name), i = __PRIVATE_fromVersion(t.updateTime), s = t.createTime ? __PRIVATE_fromVersion(t.createTime) : SnapshotVersion.min(), o = new ObjectValue({ + mapValue: { + fields: t.fields + } + }), _ = MutableDocument.newFoundDocument(r, i, s, o); + return n && _.setHasCommittedMutations(), n ? _.setHasCommittedMutations() : _; +} + +function __PRIVATE_fromBatchGetDocumentsResponse(e, t) { + return "found" in t ? function __PRIVATE_fromFound(e, t) { + __PRIVATE_hardAssert(!!t.found, 43571), t.found.name, t.found.updateTime; + const n = fromName(e, t.found.name), r = __PRIVATE_fromVersion(t.found.updateTime), i = t.found.createTime ? __PRIVATE_fromVersion(t.found.createTime) : SnapshotVersion.min(), s = new ObjectValue({ + mapValue: { + fields: t.found.fields + } + }); + return MutableDocument.newFoundDocument(n, r, i, s); + }(e, t) : "missing" in t ? function __PRIVATE_fromMissing(e, t) { + __PRIVATE_hardAssert(!!t.missing, 3894), __PRIVATE_hardAssert(!!t.readTime, 22933); + const n = fromName(e, t.missing), r = __PRIVATE_fromVersion(t.readTime); + return MutableDocument.newNoDocument(n, r); + }(e, t) : fail(7234, { + result: t + }); +} + +function __PRIVATE_fromWatchChange(e, t) { + let n; + if ("targetChange" in t) { + t.targetChange; + // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE' + // if unset + const r = function __PRIVATE_fromWatchTargetChangeState(e) { + return "NO_CHANGE" === e ? 0 /* WatchTargetChangeState.NoChange */ : "ADD" === e ? 1 /* WatchTargetChangeState.Added */ : "REMOVE" === e ? 2 /* WatchTargetChangeState.Removed */ : "CURRENT" === e ? 3 /* WatchTargetChangeState.Current */ : "RESET" === e ? 4 /* WatchTargetChangeState.Reset */ : fail(39313, { + state: e + }); + }(t.targetChange.targetChangeType || "NO_CHANGE"), i = t.targetChange.targetIds || [], s = function __PRIVATE_fromBytes(e, t) { + return e.useProto3Json ? (__PRIVATE_hardAssert(void 0 === t || "string" == typeof t, 58123), + ByteString.fromBase64String(t || "")) : (__PRIVATE_hardAssert(void 0 === t || + // Check if the value is an instance of both Buffer and Uint8Array, + // despite the fact that Buffer extends Uint8Array. In some + // environments, such as jsdom, the prototype chain of Buffer + // does not indicate that it extends Uint8Array. + t instanceof Buffer || t instanceof Uint8Array, 16193), ByteString.fromUint8Array(t || new Uint8Array)); + }(e, t.targetChange.resumeToken), o = t.targetChange.cause, _ = o && function __PRIVATE_fromRpcStatus(e) { + const t = void 0 === e.code ? N.UNKNOWN : __PRIVATE_mapCodeFromRpcCode(e.code); + return new FirestoreError(t, e.message || ""); + }(o); + n = new __PRIVATE_WatchTargetChange(r, i, s, _ || null); + } else if ("documentChange" in t) { + t.documentChange; + const r = t.documentChange; + r.document, r.document.name, r.document.updateTime; + const i = fromName(e, r.document.name), s = __PRIVATE_fromVersion(r.document.updateTime), o = r.document.createTime ? __PRIVATE_fromVersion(r.document.createTime) : SnapshotVersion.min(), _ = new ObjectValue({ + mapValue: { + fields: r.document.fields + } + }), a = MutableDocument.newFoundDocument(i, s, o, _), u = r.targetIds || [], c = r.removedTargetIds || []; + n = new __PRIVATE_DocumentWatchChange(u, c, a.key, a); + } else if ("documentDelete" in t) { + t.documentDelete; + const r = t.documentDelete; + r.document; + const i = fromName(e, r.document), s = r.readTime ? __PRIVATE_fromVersion(r.readTime) : SnapshotVersion.min(), o = MutableDocument.newNoDocument(i, s), _ = r.removedTargetIds || []; + n = new __PRIVATE_DocumentWatchChange([], _, o.key, o); + } else if ("documentRemove" in t) { + t.documentRemove; + const r = t.documentRemove; + r.document; + const i = fromName(e, r.document), s = r.removedTargetIds || []; + n = new __PRIVATE_DocumentWatchChange([], s, i, null); + } else { + if (!("filter" in t)) return fail(11601, { + Rt: t + }); + { + t.filter; + const e = t.filter; + e.targetId; + const {count: r = 0, unchangedNames: i} = e, s = new ExistenceFilter(r, i), o = e.targetId; + n = new __PRIVATE_ExistenceFilterChange(o, s); + } + } + return n; +} + +function toMutation(e, t) { + let n; + if (t instanceof __PRIVATE_SetMutation) n = { + update: __PRIVATE_toMutationDocument(e, t.key, t.value) + }; else if (t instanceof __PRIVATE_DeleteMutation) n = { + delete: __PRIVATE_toName(e, t.key) + }; else if (t instanceof __PRIVATE_PatchMutation) n = { + update: __PRIVATE_toMutationDocument(e, t.key, t.data), + updateMask: __PRIVATE_toDocumentMask(t.fieldMask) + }; else { + if (!(t instanceof __PRIVATE_VerifyMutation)) return fail(16599, { + Vt: t.type + }); + n = { + verify: __PRIVATE_toName(e, t.key) + }; + } + return t.fieldTransforms.length > 0 && (n.updateTransforms = t.fieldTransforms.map((e => function __PRIVATE_toFieldTransform(e, t) { + const n = t.transform; + if (n instanceof __PRIVATE_ServerTimestampTransform) return { + fieldPath: t.field.canonicalString(), + setToServerValue: "REQUEST_TIME" + }; + if (n instanceof __PRIVATE_ArrayUnionTransformOperation) return { + fieldPath: t.field.canonicalString(), + appendMissingElements: { + values: n.elements + } + }; + if (n instanceof __PRIVATE_ArrayRemoveTransformOperation) return { + fieldPath: t.field.canonicalString(), + removeAllFromArray: { + values: n.elements + } + }; + if (n instanceof __PRIVATE_NumericIncrementTransformOperation) return { + fieldPath: t.field.canonicalString(), + increment: n.Ae + }; + throw fail(20930, { + transform: t.transform + }); + }(0, e)))), t.precondition.isNone || (n.currentDocument = function __PRIVATE_toPrecondition(e, t) { + return void 0 !== t.updateTime ? { + updateTime: __PRIVATE_toVersion(e, t.updateTime) + } : void 0 !== t.exists ? { + exists: t.exists + } : fail(27497); + }(e, t.precondition)), n; +} + +function __PRIVATE_fromMutation(e, t) { + const n = t.currentDocument ? function __PRIVATE_fromPrecondition(e) { + return void 0 !== e.updateTime ? Precondition.updateTime(__PRIVATE_fromVersion(e.updateTime)) : void 0 !== e.exists ? Precondition.exists(e.exists) : Precondition.none(); + }(t.currentDocument) : Precondition.none(), r = t.updateTransforms ? t.updateTransforms.map((t => function __PRIVATE_fromFieldTransform(e, t) { + let n = null; + if ("setToServerValue" in t) __PRIVATE_hardAssert("REQUEST_TIME" === t.setToServerValue, 16630, { + proto: t + }), n = new __PRIVATE_ServerTimestampTransform; else if ("appendMissingElements" in t) { + const e = t.appendMissingElements.values || []; + n = new __PRIVATE_ArrayUnionTransformOperation(e); + } else if ("removeAllFromArray" in t) { + const e = t.removeAllFromArray.values || []; + n = new __PRIVATE_ArrayRemoveTransformOperation(e); + } else "increment" in t ? n = new __PRIVATE_NumericIncrementTransformOperation(e, t.increment) : fail(16584, { + proto: t + }); + const r = FieldPath$1.fromServerFormat(t.fieldPath); + return new FieldTransform(r, n); + }(e, t))) : []; + if (t.update) { + t.update.name; + const i = fromName(e, t.update.name), s = new ObjectValue({ + mapValue: { + fields: t.update.fields + } + }); + if (t.updateMask) { + const e = function __PRIVATE_fromDocumentMask(e) { + const t = e.fieldPaths || []; + return new FieldMask(t.map((e => FieldPath$1.fromServerFormat(e)))); + }(t.updateMask); + return new __PRIVATE_PatchMutation(i, s, e, n, r); + } + return new __PRIVATE_SetMutation(i, s, n, r); + } + if (t.delete) { + const r = fromName(e, t.delete); + return new __PRIVATE_DeleteMutation(r, n); + } + if (t.verify) { + const r = fromName(e, t.verify); + return new __PRIVATE_VerifyMutation(r, n); + } + return fail(1463, { + proto: t + }); +} + +function __PRIVATE_fromWriteResults(e, t) { + return e && e.length > 0 ? (__PRIVATE_hardAssert(void 0 !== t, 14353), e.map((e => function __PRIVATE_fromWriteResult(e, t) { + // NOTE: Deletes don't have an updateTime. + let n = e.updateTime ? __PRIVATE_fromVersion(e.updateTime) : __PRIVATE_fromVersion(t); + return n.isEqual(SnapshotVersion.min()) && ( + // The Firestore Emulator currently returns an update time of 0 for + // deletes of non-existing documents (rather than null). This breaks the + // test "get deleted doc while offline with source=cache" as NoDocuments + // with version 0 are filtered by IndexedDb's RemoteDocumentCache. + // TODO(#2149): Remove this when Emulator is fixed + n = __PRIVATE_fromVersion(t)), new MutationResult(n, e.transformResults || []); + }(e, t)))) : []; +} + +function __PRIVATE_toDocumentsTarget(e, t) { + return { + documents: [ __PRIVATE_toQueryPath(e, t.path) ] + }; +} + +function __PRIVATE_toQueryTarget(e, t) { + // Dissect the path into parent, collectionId, and optional key filter. + const n = { + structuredQuery: {} + }, r = t.path; + let i; + null !== t.collectionGroup ? (i = r, n.structuredQuery.from = [ { + collectionId: t.collectionGroup, + allDescendants: !0 + } ]) : (i = r.popLast(), n.structuredQuery.from = [ { + collectionId: r.lastSegment() + } ]), n.parent = __PRIVATE_toQueryPath(e, i); + const s = function __PRIVATE_toFilters(e) { + if (0 === e.length) return; + return __PRIVATE_toFilter(CompositeFilter.create(e, "and" /* CompositeOperator.AND */)); + }(t.filters); + s && (n.structuredQuery.where = s); + const o = function __PRIVATE_toOrder(e) { + if (0 === e.length) return; + return e.map((e => + // visible for testing + function __PRIVATE_toPropertyOrder(e) { + return { + field: __PRIVATE_toFieldPathReference(e.field), + direction: __PRIVATE_toDirection(e.dir) + }; + }(e))); + }(t.orderBy); + o && (n.structuredQuery.orderBy = o); + const _ = __PRIVATE_toInt32Proto(e, t.limit); + return null !== _ && (n.structuredQuery.limit = _), t.startAt && (n.structuredQuery.startAt = function __PRIVATE_toStartAtCursor(e) { + return { + before: e.inclusive, + values: e.position + }; + }(t.startAt)), t.endAt && (n.structuredQuery.endAt = function __PRIVATE_toEndAtCursor(e) { + return { + before: !e.inclusive, + values: e.position + }; + }(t.endAt)), { + ft: n, + parent: i + }; +} + +function __PRIVATE_toRunAggregationQueryRequest(e, t, n, r) { + const {ft: i, parent: s} = __PRIVATE_toQueryTarget(e, t), o = {}, _ = []; + let a = 0; + return n.forEach((e => { + // Map all client-side aliases to a unique short-form + // alias. This avoids issues with client-side aliases that + // exceed the 1500-byte string size limit. + const t = r ? e.alias : "aggregate_" + a++; + o[t] = e.alias, "count" === e.aggregateType ? _.push({ + alias: t, + count: {} + }) : "avg" === e.aggregateType ? _.push({ + alias: t, + avg: { + field: __PRIVATE_toFieldPathReference(e.fieldPath) + } + }) : "sum" === e.aggregateType && _.push({ + alias: t, + sum: { + field: __PRIVATE_toFieldPathReference(e.fieldPath) + } + }); + })), { + request: { + structuredAggregationQuery: { + aggregations: _, + structuredQuery: i.structuredQuery + }, + parent: i.parent + }, + gt: o, + parent: s + }; +} + +function __PRIVATE_convertQueryTargetToQuery(e) { + let t = __PRIVATE_fromQueryPath(e.parent); + const n = e.structuredQuery, r = n.from ? n.from.length : 0; + let i = null; + if (r > 0) { + __PRIVATE_hardAssert(1 === r, 65062); + const e = n.from[0]; + e.allDescendants ? i = e.collectionId : t = t.child(e.collectionId); + } + let s = []; + n.where && (s = function __PRIVATE_fromFilters(e) { + const t = __PRIVATE_fromFilter(e); + if (t instanceof CompositeFilter && __PRIVATE_compositeFilterIsFlatConjunction(t)) return t.getFilters(); + return [ t ]; + }(n.where)); + let o = []; + n.orderBy && (o = function __PRIVATE_fromOrder(e) { + return e.map((e => function __PRIVATE_fromPropertyOrder(e) { + return new OrderBy(__PRIVATE_fromFieldPathReference(e.field), + // visible for testing + function __PRIVATE_fromDirection(e) { + switch (e) { + case "ASCENDING": + return "asc" /* Direction.ASCENDING */; + + case "DESCENDING": + return "desc" /* Direction.DESCENDING */; + + default: + return; + } + } + // visible for testing + (e.direction)); + } + // visible for testing + (e))); + }(n.orderBy)); + let _ = null; + n.limit && (_ = function __PRIVATE_fromInt32Proto(e) { + let t; + return t = "object" == typeof e ? e.value : e, __PRIVATE_isNullOrUndefined(t) ? null : t; + }(n.limit)); + let a = null; + n.startAt && (a = function __PRIVATE_fromStartAtCursor(e) { + const t = !!e.before, n = e.values || []; + return new Bound(n, t); + }(n.startAt)); + let u = null; + return n.endAt && (u = function __PRIVATE_fromEndAtCursor(e) { + const t = !e.before, n = e.values || []; + return new Bound(n, t); + } + // visible for testing + (n.endAt)), __PRIVATE_newQuery(t, i, o, s, _, "F" /* LimitType.First */ , a, u); +} + +function __PRIVATE_toListenRequestLabels(e, t) { + const n = function __PRIVATE_toLabel(e) { + switch (e) { + case "TargetPurposeListen" /* TargetPurpose.Listen */ : + return null; + + case "TargetPurposeExistenceFilterMismatch" /* TargetPurpose.ExistenceFilterMismatch */ : + return "existence-filter-mismatch"; + + case "TargetPurposeExistenceFilterMismatchBloom" /* TargetPurpose.ExistenceFilterMismatchBloom */ : + return "existence-filter-mismatch-bloom"; + + case "TargetPurposeLimboResolution" /* TargetPurpose.LimboResolution */ : + return "limbo-document"; + + default: + return fail(28987, { + purpose: e + }); + } + }(t.purpose); + return null == n ? null : { + "goog-listen-tags": n + }; +} + +function __PRIVATE_fromFilter(e) { + return void 0 !== e.unaryFilter ? function __PRIVATE_fromUnaryFilter(e) { + switch (e.unaryFilter.op) { + case "IS_NAN": + const t = __PRIVATE_fromFieldPathReference(e.unaryFilter.field); + return FieldFilter.create(t, "==" /* Operator.EQUAL */ , { + doubleValue: NaN + }); + + case "IS_NULL": + const n = __PRIVATE_fromFieldPathReference(e.unaryFilter.field); + return FieldFilter.create(n, "==" /* Operator.EQUAL */ , { + nullValue: "NULL_VALUE" + }); + + case "IS_NOT_NAN": + const r = __PRIVATE_fromFieldPathReference(e.unaryFilter.field); + return FieldFilter.create(r, "!=" /* Operator.NOT_EQUAL */ , { + doubleValue: NaN + }); + + case "IS_NOT_NULL": + const i = __PRIVATE_fromFieldPathReference(e.unaryFilter.field); + return FieldFilter.create(i, "!=" /* Operator.NOT_EQUAL */ , { + nullValue: "NULL_VALUE" + }); + + case "OPERATOR_UNSPECIFIED": + return fail(61313); + + default: + return fail(60726); + } + }(e) : void 0 !== e.fieldFilter ? function __PRIVATE_fromFieldFilter(e) { + return FieldFilter.create(__PRIVATE_fromFieldPathReference(e.fieldFilter.field), function __PRIVATE_fromOperatorName(e) { + switch (e) { + case "EQUAL": + return "==" /* Operator.EQUAL */; + + case "NOT_EQUAL": + return "!=" /* Operator.NOT_EQUAL */; + + case "GREATER_THAN": + return ">" /* Operator.GREATER_THAN */; + + case "GREATER_THAN_OR_EQUAL": + return ">=" /* Operator.GREATER_THAN_OR_EQUAL */; + + case "LESS_THAN": + return "<" /* Operator.LESS_THAN */; + + case "LESS_THAN_OR_EQUAL": + return "<=" /* Operator.LESS_THAN_OR_EQUAL */; + + case "ARRAY_CONTAINS": + return "array-contains" /* Operator.ARRAY_CONTAINS */; + + case "IN": + return "in" /* Operator.IN */; + + case "NOT_IN": + return "not-in" /* Operator.NOT_IN */; + + case "ARRAY_CONTAINS_ANY": + return "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */; + + case "OPERATOR_UNSPECIFIED": + return fail(58110); + + default: + return fail(50506); + } + }(e.fieldFilter.op), e.fieldFilter.value); + }(e) : void 0 !== e.compositeFilter ? function __PRIVATE_fromCompositeFilter(e) { + return CompositeFilter.create(e.compositeFilter.filters.map((e => __PRIVATE_fromFilter(e))), function __PRIVATE_fromCompositeOperatorName(e) { + switch (e) { + case "AND": + return "and" /* CompositeOperator.AND */; + + case "OR": + return "or" /* CompositeOperator.OR */; + + default: + return fail(1026); + } + }(e.compositeFilter.op)); + }(e) : fail(30097, { + filter: e + }); +} + +function __PRIVATE_toDirection(e) { + return bt[e]; +} + +function __PRIVATE_toOperatorName(e) { + return Dt[e]; +} + +function __PRIVATE_toCompositeOperatorName(e) { + return Ct[e]; +} + +function __PRIVATE_toFieldPathReference(e) { + return { + fieldPath: e.canonicalString() + }; +} + +function __PRIVATE_fromFieldPathReference(e) { + return FieldPath$1.fromServerFormat(e.fieldPath); +} + +function __PRIVATE_toFilter(e) { + return e instanceof FieldFilter ? function __PRIVATE_toUnaryOrFieldFilter(e) { + if ("==" /* Operator.EQUAL */ === e.op) { + if (__PRIVATE_isNanValue(e.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(e.field), + op: "IS_NAN" + } + }; + if (__PRIVATE_isNullValue(e.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(e.field), + op: "IS_NULL" + } + }; + } else if ("!=" /* Operator.NOT_EQUAL */ === e.op) { + if (__PRIVATE_isNanValue(e.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(e.field), + op: "IS_NOT_NAN" + } + }; + if (__PRIVATE_isNullValue(e.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(e.field), + op: "IS_NOT_NULL" + } + }; + } + return { + fieldFilter: { + field: __PRIVATE_toFieldPathReference(e.field), + op: __PRIVATE_toOperatorName(e.op), + value: e.value + } + }; + }(e) : e instanceof CompositeFilter ? function __PRIVATE_toCompositeFilter(e) { + const t = e.getFilters().map((e => __PRIVATE_toFilter(e))); + if (1 === t.length) return t[0]; + return { + compositeFilter: { + op: __PRIVATE_toCompositeOperatorName(e.op), + filters: t + } + }; + }(e) : fail(54877, { + filter: e + }); +} + +function __PRIVATE_toDocumentMask(e) { + const t = []; + return e.fields.forEach((e => t.push(e.canonicalString()))), { + fieldPaths: t + }; +} + +function __PRIVATE_isValidResourceName(e) { + // Resource names have at least 4 components (project ID, database ID) + return e.length >= 4 && "projects" === e.get(0) && "databases" === e.get(2); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable set of metadata that the local store tracks for each target. + */ class TargetData { + constructor( + /** The target being listened to. */ + e, + /** + * The target ID to which the target corresponds; Assigned by the + * LocalStore for user listens and by the SyncEngine for limbo watches. + */ + t, + /** The purpose of the target. */ + n, + /** + * The sequence number of the last transaction during which this target data + * was modified. + */ + r, + /** The latest snapshot version seen for this target. */ + i = SnapshotVersion.min() + /** + * The maximum snapshot version at which the associated view + * contained no limbo documents. + */ , s = SnapshotVersion.min() + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ , o = ByteString.EMPTY_BYTE_STRING + /** + * The number of documents that last matched the query at the resume token or + * read time. Documents are counted only when making a listen request with + * resume token or read time, otherwise, keep it null. + */ , _ = null) { + this.target = e, this.targetId = t, this.purpose = n, this.sequenceNumber = r, this.snapshotVersion = i, + this.lastLimboFreeSnapshotVersion = s, this.resumeToken = o, this.expectedCount = _; + } + /** Creates a new target data instance with an updated sequence number. */ withSequenceNumber(e) { + return new TargetData(this.target, this.targetId, this.purpose, e, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, this.expectedCount); + } + /** + * Creates a new target data instance with an updated resume token and + * snapshot version. + */ withResumeToken(e, t) { + return new TargetData(this.target, this.targetId, this.purpose, this.sequenceNumber, t, this.lastLimboFreeSnapshotVersion, e, + /* expectedCount= */ null); + } + /** + * Creates a new target data instance with an updated expected count. + */ withExpectedCount(e) { + return new TargetData(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, e); + } + /** + * Creates a new target data instance with an updated last limbo free + * snapshot version number. + */ withLastLimboFreeSnapshotVersion(e) { + return new TargetData(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, e, this.resumeToken, this.expectedCount); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Serializer for values stored in the LocalStore. */ class __PRIVATE_LocalSerializer { + constructor(e) { + this.yt = e; + } +} + +/** Decodes a remote document from storage locally to a Document. */ function __PRIVATE_fromDbRemoteDocument(e, t) { + let n; + if (t.document) n = __PRIVATE_fromDocument(e.yt, t.document, !!t.hasCommittedMutations); else if (t.noDocument) { + const e = DocumentKey.fromSegments(t.noDocument.path), r = __PRIVATE_fromDbTimestamp(t.noDocument.readTime); + n = MutableDocument.newNoDocument(e, r), t.hasCommittedMutations && n.setHasCommittedMutations(); + } else { + if (!t.unknownDocument) return fail(56709); + { + const e = DocumentKey.fromSegments(t.unknownDocument.path), r = __PRIVATE_fromDbTimestamp(t.unknownDocument.version); + n = MutableDocument.newUnknownDocument(e, r); + } + } + return t.readTime && n.setReadTime(function __PRIVATE_fromDbTimestampKey(e) { + const t = new Timestamp(e[0], e[1]); + return SnapshotVersion.fromTimestamp(t); + }(t.readTime)), n; +} + +/** Encodes a document for storage locally. */ function __PRIVATE_toDbRemoteDocument(e, t) { + const n = t.key, r = { + prefixPath: n.getCollectionPath().popLast().toArray(), + collectionGroup: n.collectionGroup, + documentId: n.path.lastSegment(), + readTime: __PRIVATE_toDbTimestampKey(t.readTime), + hasCommittedMutations: t.hasCommittedMutations + }; + if (t.isFoundDocument()) r.document = function __PRIVATE_toDocument(e, t) { + return { + name: __PRIVATE_toName(e, t.key), + fields: t.data.value.mapValue.fields, + updateTime: toTimestamp(e, t.version.toTimestamp()), + createTime: toTimestamp(e, t.createTime.toTimestamp()) + }; + }(e.yt, t); else if (t.isNoDocument()) r.noDocument = { + path: n.path.toArray(), + readTime: __PRIVATE_toDbTimestamp(t.version) + }; else { + if (!t.isUnknownDocument()) return fail(57904, { + document: t + }); + r.unknownDocument = { + path: n.path.toArray(), + version: __PRIVATE_toDbTimestamp(t.version) + }; + } + return r; +} + +function __PRIVATE_toDbTimestampKey(e) { + const t = e.toTimestamp(); + return [ t.seconds, t.nanoseconds ]; +} + +function __PRIVATE_toDbTimestamp(e) { + const t = e.toTimestamp(); + return { + seconds: t.seconds, + nanoseconds: t.nanoseconds + }; +} + +function __PRIVATE_fromDbTimestamp(e) { + const t = new Timestamp(e.seconds, e.nanoseconds); + return SnapshotVersion.fromTimestamp(t); +} + +/** Encodes a batch of mutations into a DbMutationBatch for local storage. */ +/** Decodes a DbMutationBatch into a MutationBatch */ +function __PRIVATE_fromDbMutationBatch(e, t) { + const n = (t.baseMutations || []).map((t => __PRIVATE_fromMutation(e.yt, t))); + // Squash old transform mutations into existing patch or set mutations. + // The replacement of representing `transforms` with `update_transforms` + // on the SDK means that old `transform` mutations stored in IndexedDB need + // to be updated to `update_transforms`. + // TODO(b/174608374): Remove this code once we perform a schema migration. + for (let e = 0; e < t.mutations.length - 1; ++e) { + const n = t.mutations[e]; + if (e + 1 < t.mutations.length && void 0 !== t.mutations[e + 1].transform) { + const r = t.mutations[e + 1]; + n.updateTransforms = r.transform.fieldTransforms, t.mutations.splice(e + 1, 1), + ++e; + } + } + const r = t.mutations.map((t => __PRIVATE_fromMutation(e.yt, t))), i = Timestamp.fromMillis(t.localWriteTimeMs); + return new MutationBatch(t.batchId, i, n, r); +} + +/** Decodes a DbTarget into TargetData */ function __PRIVATE_fromDbTarget(e) { + const t = __PRIVATE_fromDbTimestamp(e.readTime), n = void 0 !== e.lastLimboFreeSnapshotVersion ? __PRIVATE_fromDbTimestamp(e.lastLimboFreeSnapshotVersion) : SnapshotVersion.min(); + let r; + return r = + /** + * A helper function for figuring out what kind of query has been stored. + */ + function __PRIVATE_isDocumentQuery(e) { + return void 0 !== e.documents; + } + /** Encodes a DbBundle to a BundleMetadata object. */ (e.query) ? function __PRIVATE_fromDocumentsTarget(e) { + const t = e.documents.length; + return __PRIVATE_hardAssert(1 === t, 1966, { + count: t + }), __PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(__PRIVATE_fromQueryPath(e.documents[0]))); + }(e.query) : function __PRIVATE_fromQueryTarget(e) { + return __PRIVATE_queryToTarget(__PRIVATE_convertQueryTargetToQuery(e)); + }(e.query), new TargetData(r, e.targetId, "TargetPurposeListen" /* TargetPurpose.Listen */ , e.lastListenSequenceNumber, t, n, ByteString.fromBase64String(e.resumeToken)); +} + +/** Encodes TargetData into a DbTarget for storage locally. */ function __PRIVATE_toDbTarget(e, t) { + const n = __PRIVATE_toDbTimestamp(t.snapshotVersion), r = __PRIVATE_toDbTimestamp(t.lastLimboFreeSnapshotVersion); + let i; + i = __PRIVATE_targetIsDocumentTarget(t.target) ? __PRIVATE_toDocumentsTarget(e.yt, t.target) : __PRIVATE_toQueryTarget(e.yt, t.target).ft; + // We can't store the resumeToken as a ByteString in IndexedDb, so we + // convert it to a base64 string for storage. + const s = t.resumeToken.toBase64(); + // lastListenSequenceNumber is always 0 until we do real GC. + return { + targetId: t.targetId, + canonicalId: __PRIVATE_canonifyTarget(t.target), + readTime: n, + resumeToken: s, + lastListenSequenceNumber: t.sequenceNumber, + lastLimboFreeSnapshotVersion: r, + query: i + }; +} + +/** + * Encodes a `BundledQuery` from bundle proto to a Query object. + * + * This reconstructs the original query used to build the bundle being loaded, + * including features exists only in SDKs (for example: limit-to-last). + */ +function __PRIVATE_fromBundledQuery(e) { + const t = __PRIVATE_convertQueryTargetToQuery({ + parent: e.parent, + structuredQuery: e.structuredQuery + }); + return "LAST" === e.limitType ? __PRIVATE_queryWithLimit(t, t.limit, "L" /* LimitType.Last */) : t; +} + +/** Encodes a NamedQuery proto object to a NamedQuery model object. */ +/** Encodes a DbDocumentOverlay object to an Overlay model object. */ +function __PRIVATE_fromDbDocumentOverlay(e, t) { + return new Overlay(t.largestBatchId, __PRIVATE_fromMutation(e.yt, t.overlayMutation)); +} + +/** Decodes an Overlay model object into a DbDocumentOverlay object. */ +/** + * Returns the DbDocumentOverlayKey corresponding to the given user and + * document key. + */ +function __PRIVATE_toDbDocumentOverlayKey(e, t) { + const n = t.path.lastSegment(); + return [ e, __PRIVATE_encodeResourcePath(t.path.popLast()), n ]; +} + +function __PRIVATE_toDbIndexState(e, t, n, r) { + return { + indexId: e, + uid: t, + sequenceNumber: n, + readTime: __PRIVATE_toDbTimestamp(r.readTime), + documentKey: __PRIVATE_encodeResourcePath(r.documentKey.path), + largestBatchId: r.largestBatchId + }; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_IndexedDbBundleCache { + getBundleMetadata(e, t) { + return __PRIVATE_bundlesStore(e).get(t).next((e => { + if (e) return function __PRIVATE_fromDbBundle(e) { + return { + id: e.bundleId, + createTime: __PRIVATE_fromDbTimestamp(e.createTime), + version: e.version + }; + } + /** Encodes a BundleMetadata to a DbBundle. */ (e); + })); + } + saveBundleMetadata(e, t) { + return __PRIVATE_bundlesStore(e).put(function __PRIVATE_toDbBundle(e) { + return { + bundleId: e.id, + createTime: __PRIVATE_toDbTimestamp(__PRIVATE_fromVersion(e.createTime)), + version: e.version + }; + } + /** Encodes a DbNamedQuery to a NamedQuery. */ (t)); + } + getNamedQuery(e, t) { + return __PRIVATE_namedQueriesStore(e).get(t).next((e => { + if (e) return function __PRIVATE_fromDbNamedQuery(e) { + return { + name: e.name, + query: __PRIVATE_fromBundledQuery(e.bundledQuery), + readTime: __PRIVATE_fromDbTimestamp(e.readTime) + }; + } + /** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */ (e); + })); + } + saveNamedQuery(e, t) { + return __PRIVATE_namedQueriesStore(e).put(function __PRIVATE_toDbNamedQuery(e) { + return { + name: e.name, + readTime: __PRIVATE_toDbTimestamp(__PRIVATE_fromVersion(e.readTime)), + bundledQuery: e.bundledQuery + }; + }(t)); + } +} + +/** + * Helper to get a typed SimpleDbStore for the bundles object store. + */ function __PRIVATE_bundlesStore(e) { + return __PRIVATE_getStore(e, be); +} + +/** + * Helper to get a typed SimpleDbStore for the namedQueries object store. + */ function __PRIVATE_namedQueriesStore(e) { + return __PRIVATE_getStore(e, Ce); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Implementation of DocumentOverlayCache using IndexedDb. + */ class __PRIVATE_IndexedDbDocumentOverlayCache { + /** + * @param serializer - The document serializer. + * @param userId - The userId for which we are accessing overlays. + */ + constructor(e, t) { + this.serializer = e, this.userId = t; + } + static wt(e, t) { + const n = t.uid || ""; + return new __PRIVATE_IndexedDbDocumentOverlayCache(e, n); + } + getOverlay(e, t) { + return __PRIVATE_documentOverlayStore(e).get(__PRIVATE_toDbDocumentOverlayKey(this.userId, t)).next((e => e ? __PRIVATE_fromDbDocumentOverlay(this.serializer, e) : null)); + } + getOverlays(e, t) { + const n = __PRIVATE_newOverlayMap(); + return PersistencePromise.forEach(t, (t => this.getOverlay(e, t).next((e => { + null !== e && n.set(t, e); + })))).next((() => n)); + } + saveOverlays(e, t, n) { + const r = []; + return n.forEach(((n, i) => { + const s = new Overlay(t, i); + r.push(this.St(e, s)); + })), PersistencePromise.waitFor(r); + } + removeOverlaysForBatchId(e, t, n) { + const r = new Set; + // Get the set of unique collection paths. + t.forEach((e => r.add(__PRIVATE_encodeResourcePath(e.getCollectionPath())))); + const i = []; + return r.forEach((t => { + const r = IDBKeyRange.bound([ this.userId, t, n ], [ this.userId, t, n + 1 ], + /*lowerOpen=*/ !1, + /*upperOpen=*/ !0); + i.push(__PRIVATE_documentOverlayStore(e).Z(Ge, r)); + })), PersistencePromise.waitFor(i); + } + getOverlaysForCollection(e, t, n) { + const r = __PRIVATE_newOverlayMap(), i = __PRIVATE_encodeResourcePath(t), s = IDBKeyRange.bound([ this.userId, i, n ], [ this.userId, i, Number.POSITIVE_INFINITY ], + /*lowerOpen=*/ !0); + return __PRIVATE_documentOverlayStore(e).J(Ge, s).next((e => { + for (const t of e) { + const e = __PRIVATE_fromDbDocumentOverlay(this.serializer, t); + r.set(e.getKey(), e); + } + return r; + })); + } + getOverlaysForCollectionGroup(e, t, n, r) { + const i = __PRIVATE_newOverlayMap(); + let s; + // We want batch IDs larger than `sinceBatchId`, and so the lower bound + // is not inclusive. + const o = IDBKeyRange.bound([ this.userId, t, n ], [ this.userId, t, Number.POSITIVE_INFINITY ], + /*lowerOpen=*/ !0); + return __PRIVATE_documentOverlayStore(e).ee({ + index: je, + range: o + }, ((e, t, n) => { + // We do not want to return partial batch overlays, even if the size + // of the result set exceeds the given `count` argument. Therefore, we + // continue to aggregate results even after the result size exceeds + // `count` if there are more overlays from the `currentBatchId`. + const o = __PRIVATE_fromDbDocumentOverlay(this.serializer, t); + i.size() < r || o.largestBatchId === s ? (i.set(o.getKey(), o), s = o.largestBatchId) : n.done(); + })).next((() => i)); + } + St(e, t) { + return __PRIVATE_documentOverlayStore(e).put(function __PRIVATE_toDbDocumentOverlay(e, t, n) { + const [r, i, s] = __PRIVATE_toDbDocumentOverlayKey(t, n.mutation.key); + return { + userId: t, + collectionPath: i, + documentId: s, + collectionGroup: n.mutation.key.getCollectionGroup(), + largestBatchId: n.largestBatchId, + overlayMutation: toMutation(e.yt, n.mutation) + }; + }(this.serializer, this.userId, t)); + } +} + +/** + * Helper to get a typed SimpleDbStore for the document overlay object store. + */ function __PRIVATE_documentOverlayStore(e) { + return __PRIVATE_getStore(e, Ke); +} + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_IndexedDbGlobalsCache { + bt(e) { + return __PRIVATE_getStore(e, He); + } + getSessionToken(e) { + return this.bt(e).get("sessionToken").next((e => { + const t = e?.value; + return t ? ByteString.fromUint8Array(t) : ByteString.EMPTY_BYTE_STRING; + })); + } + setSessionToken(e, t) { + return this.bt(e).put({ + name: "sessionToken", + value: t.toUint8Array() + }); + } +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Note: This code is copied from the backend. Code that is not used by +// Firestore was removed. +/** Firestore index value writer. */ +class __PRIVATE_FirestoreIndexValueWriter { + constructor() {} + // The write methods below short-circuit writing terminators for values + // containing a (terminating) truncated value. + // As an example, consider the resulting encoding for: + // ["bar", [2, "foo"]] -> (STRING, "bar", TERM, ARRAY, NUMBER, 2, STRING, "foo", TERM, TERM, TERM) + // ["bar", [2, truncated("foo")]] -> (STRING, "bar", TERM, ARRAY, NUMBER, 2, STRING, "foo", TRUNC) + // ["bar", truncated(["foo"])] -> (STRING, "bar", TERM, ARRAY. STRING, "foo", TERM, TRUNC) + /** Writes an index value. */ + Dt(e, t) { + this.Ct(e, t), + // Write separator to split index values + // (see go/firestore-storage-format#encodings). + t.vt(); + } + Ct(e, t) { + if ("nullValue" in e) this.Ft(t, 5); else if ("booleanValue" in e) this.Ft(t, 10), + t.Mt(e.booleanValue ? 1 : 0); else if ("integerValue" in e) this.Ft(t, 15), t.Mt(__PRIVATE_normalizeNumber(e.integerValue)); else if ("doubleValue" in e) { + const n = __PRIVATE_normalizeNumber(e.doubleValue); + isNaN(n) ? this.Ft(t, 13) : (this.Ft(t, 15), __PRIVATE_isNegativeZero(n) ? + // -0.0, 0 and 0.0 are all considered the same + t.Mt(0) : t.Mt(n)); + } else if ("timestampValue" in e) { + let n = e.timestampValue; + this.Ft(t, 20), "string" == typeof n && (n = __PRIVATE_normalizeTimestamp(n)), t.xt(`${n.seconds || ""}`), + t.Mt(n.nanos || 0); + } else if ("stringValue" in e) this.Ot(e.stringValue, t), this.Nt(t); else if ("bytesValue" in e) this.Ft(t, 30), + t.Bt(__PRIVATE_normalizeByteString(e.bytesValue)), this.Nt(t); else if ("referenceValue" in e) this.Lt(e.referenceValue, t); else if ("geoPointValue" in e) { + const n = e.geoPointValue; + this.Ft(t, 45), t.Mt(n.latitude || 0), t.Mt(n.longitude || 0); + } else "mapValue" in e ? __PRIVATE_isMaxValue(e) ? this.Ft(t, Number.MAX_SAFE_INTEGER) : __PRIVATE_isVectorValue(e) ? this.kt(e.mapValue, t) : (this.qt(e.mapValue, t), + this.Nt(t)) : "arrayValue" in e ? (this.Qt(e.arrayValue, t), this.Nt(t)) : fail(19022, { + $t: e + }); + } + Ot(e, t) { + this.Ft(t, 25), this.Ut(e, t); + } + Ut(e, t) { + t.xt(e); + } + qt(e, t) { + const n = e.fields || {}; + this.Ft(t, 55); + for (const e of Object.keys(n)) this.Ot(e, t), this.Ct(n[e], t); + } + kt(e, t) { + const n = e.fields || {}; + this.Ft(t, 53); + // Vectors sort first by length + const r = Et, i = n[r].arrayValue?.values?.length || 0; + this.Ft(t, 15), t.Mt(__PRIVATE_normalizeNumber(i)), + // Vectors then sort by position value + this.Ot(r, t), this.Ct(n[r], t); + } + Qt(e, t) { + const n = e.values || []; + this.Ft(t, 50); + for (const e of n) this.Ct(e, t); + } + Lt(e, t) { + this.Ft(t, 37); + DocumentKey.fromName(e).path.forEach((e => { + this.Ft(t, 60), this.Ut(e, t); + })); + } + Ft(e, t) { + e.Mt(t); + } + Nt(e) { + // While the SDK does not implement truncation, the truncation marker is + // used to terminate all variable length values (which are strings, bytes, + // references, arrays and maps). + e.Mt(2); + } +} + +__PRIVATE_FirestoreIndexValueWriter.Kt = new __PRIVATE_FirestoreIndexValueWriter; + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law | agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES | CONDITIONS OF ANY KIND, either express | implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** These constants are taken from the backend. */ +const vt = 255; + +/** + * Counts the number of zeros in a byte. + * + * Visible for testing. + */ +function __PRIVATE_numberOfLeadingZerosInByte(e) { + if (0 === e) return 8; + let t = 0; + return e >> 4 || ( + // Test if the first four bits are zero. + t += 4, e <<= 4), e >> 6 || ( + // Test if the first two (or next two) bits are zero. + t += 2, e <<= 2), e >> 7 || ( + // Test if the remaining bit is zero. + t += 1), t; +} + +/** Counts the number of leading zeros in the given byte array. */ +/** + * Returns the number of bytes required to store "value". Leading zero bytes + * are skipped. + */ +function __PRIVATE_unsignedNumLength(e) { + // This is just the number of bytes for the unsigned representation of the number. + const t = 64 - function __PRIVATE_numberOfLeadingZeros(e) { + let t = 0; + for (let n = 0; n < 8; ++n) { + const r = __PRIVATE_numberOfLeadingZerosInByte(255 & e[n]); + if (t += r, 8 !== r) break; + } + return t; + }(e); + return Math.ceil(t / 8); +} + +/** + * OrderedCodeWriter is a minimal-allocation implementation of the writing + * behavior defined by the backend. + * + * The code is ported from its Java counterpart. + */ class __PRIVATE_OrderedCodeWriter { + constructor() { + this.buffer = new Uint8Array(1024), this.position = 0; + } + Wt(e) { + const t = e[Symbol.iterator](); + let n = t.next(); + for (;!n.done; ) this.Gt(n.value), n = t.next(); + this.zt(); + } + jt(e) { + const t = e[Symbol.iterator](); + let n = t.next(); + for (;!n.done; ) this.Jt(n.value), n = t.next(); + this.Ht(); + } + /** Writes utf8 bytes into this byte sequence, ascending. */ Yt(e) { + for (const t of e) { + const e = t.charCodeAt(0); + if (e < 128) this.Gt(e); else if (e < 2048) this.Gt(960 | e >>> 6), this.Gt(128 | 63 & e); else if (t < "\ud800" || "\udbff" < t) this.Gt(480 | e >>> 12), + this.Gt(128 | 63 & e >>> 6), this.Gt(128 | 63 & e); else { + const e = t.codePointAt(0); + this.Gt(240 | e >>> 18), this.Gt(128 | 63 & e >>> 12), this.Gt(128 | 63 & e >>> 6), + this.Gt(128 | 63 & e); + } + } + this.zt(); + } + /** Writes utf8 bytes into this byte sequence, descending */ Zt(e) { + for (const t of e) { + const e = t.charCodeAt(0); + if (e < 128) this.Jt(e); else if (e < 2048) this.Jt(960 | e >>> 6), this.Jt(128 | 63 & e); else if (t < "\ud800" || "\udbff" < t) this.Jt(480 | e >>> 12), + this.Jt(128 | 63 & e >>> 6), this.Jt(128 | 63 & e); else { + const e = t.codePointAt(0); + this.Jt(240 | e >>> 18), this.Jt(128 | 63 & e >>> 12), this.Jt(128 | 63 & e >>> 6), + this.Jt(128 | 63 & e); + } + } + this.Ht(); + } + Xt(e) { + // Values are encoded with a single byte length prefix, followed by the + // actual value in big-endian format with leading 0 bytes dropped. + const t = this.en(e), n = __PRIVATE_unsignedNumLength(t); + this.tn(1 + n), this.buffer[this.position++] = 255 & n; + // Write the length + for (let e = t.length - n; e < t.length; ++e) this.buffer[this.position++] = 255 & t[e]; + } + nn(e) { + // Values are encoded with a single byte length prefix, followed by the + // inverted value in big-endian format with leading 0 bytes dropped. + const t = this.en(e), n = __PRIVATE_unsignedNumLength(t); + this.tn(1 + n), this.buffer[this.position++] = ~(255 & n); + // Write the length + for (let e = t.length - n; e < t.length; ++e) this.buffer[this.position++] = ~(255 & t[e]); + } + /** + * Writes the "infinity" byte sequence that sorts after all other byte + * sequences written in ascending order. + */ rn() { + this.sn(vt), this.sn(255); + } + /** + * Writes the "infinity" byte sequence that sorts before all other byte + * sequences written in descending order. + */ _n() { + this.an(vt), this.an(255); + } + /** + * Resets the buffer such that it is the same as when it was newly + * constructed. + */ reset() { + this.position = 0; + } + seed(e) { + this.tn(e.length), this.buffer.set(e, this.position), this.position += e.length; + } + /** Makes a copy of the encoded bytes in this buffer. */ un() { + return this.buffer.slice(0, this.position); + } + /** + * Encodes `val` into an encoding so that the order matches the IEEE 754 + * floating-point comparison results with the following exceptions: + * -0.0 < 0.0 + * all non-NaN < NaN + * NaN = NaN + */ en(e) { + const t = + /** Converts a JavaScript number to a byte array (using big endian encoding). */ + function __PRIVATE_doubleToLongBits(e) { + const t = new DataView(new ArrayBuffer(8)); + return t.setFloat64(0, e, /* littleEndian= */ !1), new Uint8Array(t.buffer); + }(e), n = !!(128 & t[0]); + // Check if the first bit is set. We use a bit mask since value[0] is + // encoded as a number from 0 to 255. + // Revert the two complement to get natural ordering + t[0] ^= n ? 255 : 128; + for (let e = 1; e < t.length; ++e) t[e] ^= n ? 255 : 0; + return t; + } + /** Writes a single byte ascending to the buffer. */ Gt(e) { + const t = 255 & e; + 0 === t ? (this.sn(0), this.sn(255)) : t === vt ? (this.sn(vt), this.sn(0)) : this.sn(t); + } + /** Writes a single byte descending to the buffer. */ Jt(e) { + const t = 255 & e; + 0 === t ? (this.an(0), this.an(255)) : t === vt ? (this.an(vt), this.an(0)) : this.an(e); + } + zt() { + this.sn(0), this.sn(1); + } + Ht() { + this.an(0), this.an(1); + } + sn(e) { + this.tn(1), this.buffer[this.position++] = e; + } + an(e) { + this.tn(1), this.buffer[this.position++] = ~e; + } + tn(e) { + const t = e + this.position; + if (t <= this.buffer.length) return; + // Try doubling. + let n = 2 * this.buffer.length; + // Still not big enough? Just allocate the right size. + n < t && (n = t); + // Create the new buffer. + const r = new Uint8Array(n); + r.set(this.buffer), // copy old data + this.buffer = r; + } +} + +class __PRIVATE_AscendingIndexByteEncoder { + constructor(e) { + this.cn = e; + } + Bt(e) { + this.cn.Wt(e); + } + xt(e) { + this.cn.Yt(e); + } + Mt(e) { + this.cn.Xt(e); + } + vt() { + this.cn.rn(); + } +} + +class __PRIVATE_DescendingIndexByteEncoder { + constructor(e) { + this.cn = e; + } + Bt(e) { + this.cn.jt(e); + } + xt(e) { + this.cn.Zt(e); + } + Mt(e) { + this.cn.nn(e); + } + vt() { + this.cn._n(); + } +} + +/** + * Implements `DirectionalIndexByteEncoder` using `OrderedCodeWriter` for the + * actual encoding. + */ class __PRIVATE_IndexByteEncoder { + constructor() { + this.cn = new __PRIVATE_OrderedCodeWriter, this.ln = new __PRIVATE_AscendingIndexByteEncoder(this.cn), + this.hn = new __PRIVATE_DescendingIndexByteEncoder(this.cn); + } + seed(e) { + this.cn.seed(e); + } + Pn(e) { + return 0 /* IndexKind.ASCENDING */ === e ? this.ln : this.hn; + } + un() { + return this.cn.un(); + } + reset() { + this.cn.reset(); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Represents an index entry saved by the SDK in persisted storage. */ class __PRIVATE_IndexEntry { + constructor(e, t, n, r) { + this.Tn = e, this.In = t, this.En = n, this.dn = r; + } + /** + * Returns an IndexEntry entry that sorts immediately after the current + * directional value. + */ An() { + const e = this.dn.length, t = 0 === e || 255 === this.dn[e - 1] ? e + 1 : e, n = new Uint8Array(t); + return n.set(this.dn, 0), t !== e ? n.set([ 0 ], this.dn.length) : ++n[n.length - 1], + new __PRIVATE_IndexEntry(this.Tn, this.In, this.En, n); + } + // Create a representation of the Index Entry as a DbIndexEntry + Rn(e, t, n) { + return { + indexId: this.Tn, + uid: e, + arrayValue: __PRIVATE_encodeKeySafeBytes(this.En), + directionalValue: __PRIVATE_encodeKeySafeBytes(this.dn), + orderedDocumentKey: __PRIVATE_encodeKeySafeBytes(t), + documentKey: n.path.toArray() + }; + } + // Create a representation of the Index Entry as a DbIndexEntryKey + Vn(e, t, n) { + const r = this.Rn(e, t, n); + return [ r.indexId, r.uid, r.arrayValue, r.directionalValue, r.orderedDocumentKey, r.documentKey ]; + } +} + +function __PRIVATE_indexEntryComparator(e, t) { + let n = e.Tn - t.Tn; + return 0 !== n ? n : (n = __PRIVATE_compareByteArrays(e.En, t.En), 0 !== n ? n : (n = __PRIVATE_compareByteArrays(e.dn, t.dn), + 0 !== n ? n : DocumentKey.comparator(e.In, t.In))); +} + +function __PRIVATE_compareByteArrays(e, t) { + for (let n = 0; n < e.length && n < t.length; ++n) { + const r = e[n] - t[n]; + if (0 !== r) return r; + } + return e.length - t.length; +} + +/** + * Workaround for WebKit bug: https://bugs.webkit.org/show_bug.cgi?id=292721 + * Create a key safe representation of Uint8Array values. + * If the browser is detected as Safari or WebKit, then + * the input array will be converted to "sortable byte string". + * Otherwise, the input array will be returned in its original type. + */ function __PRIVATE_encodeKeySafeBytes(e) { + return isSafariOrWebkit() ? + /** + * Encodes a Uint8Array into a "sortable byte string". + * A "sortable byte string" sorts in the same order as the Uint8Array. + * This works because JS string comparison sorts strings based on code points. + */ + function __PRIVATE_encodeUint8ArrayToSortableString(e) { + let t = ""; + for (let n = 0; n < e.length; n++) t += String.fromCharCode(e[n]); + return t; + } + /** + * Decodes a "sortable byte string" back into a Uint8Array. + * A "sortable byte string" is assumed to be created where each character's + * Unicode code point directly corresponds to a single byte value (0-255). + */ (e) : e; +} + +/** + * Reverts the key safe representation of Uint8Array (created by + * encodeKeySafeBytes) to a normal Uint8Array. + */ function __PRIVATE_decodeKeySafeBytes(e) { + return "string" != typeof e ? e : function __PRIVATE_decodeSortableStringToUint8Array(e) { + const t = new Uint8Array(e.length); + for (let n = 0; n < e.length; n++) t[n] = e.charCodeAt(n); + return t; + } + /** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * A light query planner for Firestore. + * + * This class matches a `FieldIndex` against a Firestore Query `Target`. It + * determines whether a given index can be used to serve the specified target. + * + * The following table showcases some possible index configurations: + * + * Query | Index + * ----------------------------------------------------------------------------- + * where('a', '==', 'a').where('b', '==', 'b') | a ASC, b DESC + * where('a', '==', 'a').where('b', '==', 'b') | a ASC + * where('a', '==', 'a').where('b', '==', 'b') | b DESC + * where('a', '>=', 'a').orderBy('a') | a ASC + * where('a', '>=', 'a').orderBy('a', 'desc') | a DESC + * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC, b ASC + * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC + * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS, b ASCENDING + * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS + */ (e); +} + +class __PRIVATE_TargetIndexMatcher { + constructor(e) { + // The inequality filters of the target (if it exists). + // Note: The sort on FieldFilters is not required. Using SortedSet here just to utilize the custom + // comparator. + this.mn = new SortedSet(((e, t) => FieldPath$1.comparator(e.field, t.field))), this.collectionId = null != e.collectionGroup ? e.collectionGroup : e.path.lastSegment(), + this.fn = e.orderBy, this.gn = []; + for (const t of e.filters) { + const e = t; + e.isInequality() ? this.mn = this.mn.add(e) : this.gn.push(e); + } + } + get pn() { + return this.mn.size > 1; + } + /** + * Returns whether the index can be used to serve the TargetIndexMatcher's + * target. + * + * An index is considered capable of serving the target when: + * - The target uses all index segments for its filters and orderBy clauses. + * The target can have additional filter and orderBy clauses, but not + * fewer. + * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also + * have a corresponding `CONTAINS` segment. + * - All directional index segments can be mapped to the target as a series of + * equality filters, a single inequality filter and a series of orderBy + * clauses. + * - The segments that represent the equality filters may appear out of order. + * - The optional segment for the inequality filter must appear after all + * equality segments. + * - The segments that represent that orderBy clause of the target must appear + * in order after all equality and inequality segments. Single orderBy + * clauses cannot be skipped, but a continuous orderBy suffix may be + * omitted. + */ yn(e) { + if (__PRIVATE_hardAssert(e.collectionGroup === this.collectionId, 49279), this.pn) + // Only single inequality is supported for now. + // TODO(Add support for multiple inequality query): b/298441043 + return !1; + // If there is an array element, find a matching filter. + const t = __PRIVATE_fieldIndexGetArraySegment(e); + if (void 0 !== t && !this.wn(t)) return !1; + const n = __PRIVATE_fieldIndexGetDirectionalSegments(e); + let r = new Set, i = 0, s = 0; + // Process all equalities first. Equalities can appear out of order. + for (;i < n.length && this.wn(n[i]); ++i) r = r.add(n[i].fieldPath.canonicalString()); + // If we already have processed all segments, all segments are used to serve + // the equality filters and we do not need to map any segments to the + // target's inequality and orderBy clauses. + if (i === n.length) return !0; + if (this.mn.size > 0) { + // Only a single inequality is currently supported. Get the only entry in the set. + const e = this.mn.getIterator().getNext(); + // If there is an inequality filter and the field was not in one of the + // equality filters above, the next segment must match both the filter + // and the first orderBy clause. + if (!r.has(e.field.canonicalString())) { + const t = n[i]; + if (!this.Sn(e, t) || !this.bn(this.fn[s++], t)) return !1; + } + ++i; + } + // All remaining segments need to represent the prefix of the target's + // orderBy. + for (;i < n.length; ++i) { + const e = n[i]; + if (s >= this.fn.length || !this.bn(this.fn[s++], e)) return !1; + } + return !0; + } + /** + * Returns a full matched field index for this target. Currently multiple + * inequality query is not supported so function returns null. + */ Dn() { + if (this.pn) return null; + // We want to make sure only one segment created for one field. For example, + // in case like a == 3 and a > 2, Index {a ASCENDING} will only be created + // once. + let e = new SortedSet(FieldPath$1.comparator); + const t = []; + for (const n of this.gn) { + if (n.field.isKeyField()) continue; + if ("array-contains" /* Operator.ARRAY_CONTAINS */ === n.op || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === n.op) t.push(new IndexSegment(n.field, 2 /* IndexKind.CONTAINS */)); else { + if (e.has(n.field)) continue; + e = e.add(n.field), t.push(new IndexSegment(n.field, 0 /* IndexKind.ASCENDING */)); + } + } + // Note: We do not explicitly check `this.inequalityFilter` but rather rely + // on the target defining an appropriate "order by" to ensure that the + // required index segment is added. The query engine would reject a query + // with an inequality filter that lacks the required order-by clause. + for (const n of this.fn) + // Stop adding more segments if we see a order-by on key. Typically this + // is the default implicit order-by which is covered in the index_entry + // table as a separate column. If it is not the default order-by, the + // generated index will be missing some segments optimized for order-bys, + // which is probably fine. + n.field.isKeyField() || e.has(n.field) || (e = e.add(n.field), t.push(new IndexSegment(n.field, "asc" /* Direction.ASCENDING */ === n.dir ? 0 /* IndexKind.ASCENDING */ : 1 /* IndexKind.DESCENDING */))); + return new FieldIndex(FieldIndex.UNKNOWN_ID, this.collectionId, t, IndexState.empty()); + } + wn(e) { + for (const t of this.gn) if (this.Sn(t, e)) return !0; + return !1; + } + Sn(e, t) { + if (void 0 === e || !e.field.isEqual(t.fieldPath)) return !1; + const n = "array-contains" /* Operator.ARRAY_CONTAINS */ === e.op || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === e.op; + return 2 /* IndexKind.CONTAINS */ === t.kind === n; + } + bn(e, t) { + return !!e.field.isEqual(t.fieldPath) && (0 /* IndexKind.ASCENDING */ === t.kind && "asc" /* Direction.ASCENDING */ === e.dir || 1 /* IndexKind.DESCENDING */ === t.kind && "desc" /* Direction.DESCENDING */ === e.dir); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provides utility functions that help with boolean logic transformations needed for handling + * complex filters used in queries. + */ +/** + * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in + * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given + * input into a disjunction of equality filters and returns the expanded filter. + */ function __PRIVATE_computeInExpansion(e) { + if (__PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter, 20012), + e instanceof FieldFilter) { + if (e instanceof __PRIVATE_InFilter) { + const t = e.value.arrayValue?.values?.map((t => FieldFilter.create(e.field, "==" /* Operator.EQUAL */ , t))) || []; + return CompositeFilter.create(t, "or" /* CompositeOperator.OR */); + } + // We have reached other kinds of field filters. + return e; + } + // We have a composite filter. + const t = e.filters.map((e => __PRIVATE_computeInExpansion(e))); + return CompositeFilter.create(t, e.op); +} + +/** + * Given a composite filter, returns the list of terms in its disjunctive normal form. + * + *

Each element in the return value is one term of the resulting DNF. For instance: For the + * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list + * with two elements: a composite filter that performs (A && C), and a composite filter that + * performs (B && C). + * + * @param filter the composite filter to calculate DNF transform for. + * @return the terms in the DNF transform. + */ function __PRIVATE_getDnfTerms(e) { + if (0 === e.getFilters().length) return []; + const t = __PRIVATE_computeDistributedNormalForm(__PRIVATE_computeInExpansion(e)); + return __PRIVATE_hardAssert(__PRIVATE_isDisjunctiveNormalForm(t), 7391), __PRIVATE_isSingleFieldFilter(t) || __PRIVATE_isFlatConjunction(t) ? [ t ] : t.getFilters(); +} + +/** Returns true if the given filter is a single field filter. e.g. (a == 10). */ function __PRIVATE_isSingleFieldFilter(e) { + return e instanceof FieldFilter; +} + +/** + * Returns true if the given filter is the conjunction of one or more field filters. e.g. (a == 10 + * && b == 20) + */ function __PRIVATE_isFlatConjunction(e) { + return e instanceof CompositeFilter && __PRIVATE_compositeFilterIsFlatConjunction(e); +} + +/** + * Returns whether or not the given filter is in disjunctive normal form (DNF). + * + *

In boolean logic, a disjunctive normal form (DNF) is a canonical normal form of a logical + * formula consisting of a disjunction of conjunctions; it can also be described as an OR of ANDs. + * + *

For more info, visit: https://en.wikipedia.org/wiki/Disjunctive_normal_form + */ function __PRIVATE_isDisjunctiveNormalForm(e) { + return __PRIVATE_isSingleFieldFilter(e) || __PRIVATE_isFlatConjunction(e) || + /** + * Returns true if the given filter is the disjunction of one or more "flat conjunctions" and + * field filters. e.g. (a == 10) || (b==20 && c==30) + */ + function __PRIVATE_isDisjunctionOfFieldFiltersAndFlatConjunctions(e) { + if (e instanceof CompositeFilter && __PRIVATE_compositeFilterIsDisjunction(e)) { + for (const t of e.getFilters()) if (!__PRIVATE_isSingleFieldFilter(t) && !__PRIVATE_isFlatConjunction(t)) return !1; + return !0; + } + return !1; + }(e); +} + +function __PRIVATE_computeDistributedNormalForm(e) { + if (__PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter, 34018), + e instanceof FieldFilter) return e; + if (1 === e.filters.length) return __PRIVATE_computeDistributedNormalForm(e.filters[0]); + // Compute DNF for each of the subfilters first + const t = e.filters.map((e => __PRIVATE_computeDistributedNormalForm(e))); + let n = CompositeFilter.create(t, e.op); + return n = __PRIVATE_applyAssociation(n), __PRIVATE_isDisjunctiveNormalForm(n) ? n : (__PRIVATE_hardAssert(n instanceof CompositeFilter, 64498), + __PRIVATE_hardAssert(__PRIVATE_compositeFilterIsConjunction(n), 40251), __PRIVATE_hardAssert(n.filters.length > 1, 57927), + n.filters.reduce(((e, t) => __PRIVATE_applyDistribution(e, t)))); +} + +function __PRIVATE_applyDistribution(e, t) { + let n; + return __PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter, 38388), + __PRIVATE_hardAssert(t instanceof FieldFilter || t instanceof CompositeFilter, 25473), + // FieldFilter FieldFilter + n = e instanceof FieldFilter ? t instanceof FieldFilter ? function __PRIVATE_applyDistributionFieldFilters(e, t) { + // Conjunction distribution for two field filters is the conjunction of them. + return CompositeFilter.create([ e, t ], "and" /* CompositeOperator.AND */); + }(e, t) : __PRIVATE_applyDistributionFieldAndCompositeFilters(e, t) : t instanceof FieldFilter ? __PRIVATE_applyDistributionFieldAndCompositeFilters(t, e) : function __PRIVATE_applyDistributionCompositeFilters(e, t) { + // There are four cases: + // (A & B) & (C & D) --> (A & B & C & D) + // (A & B) & (C | D) --> (A & B & C) | (A & B & D) + // (A | B) & (C & D) --> (C & D & A) | (C & D & B) + // (A | B) & (C | D) --> (A & C) | (A & D) | (B & C) | (B & D) + // Case 1 is a merge. + if (__PRIVATE_hardAssert(e.filters.length > 0 && t.filters.length > 0, 48005), __PRIVATE_compositeFilterIsConjunction(e) && __PRIVATE_compositeFilterIsConjunction(t)) return __PRIVATE_compositeFilterWithAddedFilters(e, t.getFilters()); + // Case 2,3,4 all have at least one side (lhs or rhs) that is a disjunction. In all three cases + // we should take each element of the disjunction and distribute it over the other side, and + // return the disjunction of the distribution results. + const n = __PRIVATE_compositeFilterIsDisjunction(e) ? e : t, r = __PRIVATE_compositeFilterIsDisjunction(e) ? t : e, i = n.filters.map((e => __PRIVATE_applyDistribution(e, r))); + return CompositeFilter.create(i, "or" /* CompositeOperator.OR */); + }(e, t), __PRIVATE_applyAssociation(n); +} + +function __PRIVATE_applyDistributionFieldAndCompositeFilters(e, t) { + // There are two cases: + // A & (B & C) --> (A & B & C) + // A & (B | C) --> (A & B) | (A & C) + if (__PRIVATE_compositeFilterIsConjunction(t)) + // Case 1 + return __PRIVATE_compositeFilterWithAddedFilters(t, e.getFilters()); + { + // Case 2 + const n = t.filters.map((t => __PRIVATE_applyDistribution(e, t))); + return CompositeFilter.create(n, "or" /* CompositeOperator.OR */); + } +} + +/** + * Applies the associativity property to the given filter and returns the resulting filter. + * + *

    + *
  • A | (B | C) == (A | B) | C == (A | B | C) + *
  • A & (B & C) == (A & B) & C == (A & B & C) + *
+ * + *

For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic + */ function __PRIVATE_applyAssociation(e) { + if (__PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter, 11850), + e instanceof FieldFilter) return e; + const t = e.getFilters(); + // If the composite filter only contains 1 filter, apply associativity to it. + if (1 === t.length) return __PRIVATE_applyAssociation(t[0]); + // Associativity applied to a flat composite filter results is itself. + if (__PRIVATE_compositeFilterIsFlat(e)) return e; + // First apply associativity to all subfilters. This will in turn recursively apply + // associativity to all nested composite filters and field filters. + const n = t.map((e => __PRIVATE_applyAssociation(e))), r = []; + // For composite subfilters that perform the same kind of logical operation as `compositeFilter` + // take out their filters and add them to `compositeFilter`. For example: + // compositeFilter = (A | (B | C | D)) + // compositeSubfilter = (B | C | D) + // Result: (A | B | C | D) + // Note that the `compositeSubfilter` has been eliminated, and its filters (B, C, D) have been + // added to the top-level "compositeFilter". + return n.forEach((t => { + t instanceof FieldFilter ? r.push(t) : t instanceof CompositeFilter && (t.op === e.op ? + // compositeFilter: (A | (B | C)) + // compositeSubfilter: (B | C) + // Result: (A | B | C) + r.push(...t.filters) : + // compositeFilter: (A | (B & C)) + // compositeSubfilter: (B & C) + // Result: (A | (B & C)) + r.push(t)); + })), 1 === r.length ? r[0] : CompositeFilter.create(r, e.op); +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An in-memory implementation of IndexManager. + */ class __PRIVATE_MemoryIndexManager { + constructor() { + this.Cn = new __PRIVATE_MemoryCollectionParentIndex; + } + addToCollectionParentIndex(e, t) { + return this.Cn.add(t), PersistencePromise.resolve(); + } + getCollectionParents(e, t) { + return PersistencePromise.resolve(this.Cn.getEntries(t)); + } + addFieldIndex(e, t) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(); + } + deleteFieldIndex(e, t) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(); + } + deleteAllFieldIndexes(e) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(); + } + createTargetIndexes(e, t) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(); + } + getDocumentsMatchingTarget(e, t) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(null); + } + getIndexType(e, t) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(0 /* IndexType.NONE */); + } + getFieldIndexes(e, t) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve([]); + } + getNextCollectionGroupToUpdate(e) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(null); + } + getMinOffset(e, t) { + return PersistencePromise.resolve(IndexOffset.min()); + } + getMinOffsetFromCollectionGroup(e, t) { + return PersistencePromise.resolve(IndexOffset.min()); + } + updateCollectionGroup(e, t, n) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(); + } + updateIndexEntries(e, t) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(); + } +} + +/** + * Internal implementation of the collection-parent index exposed by MemoryIndexManager. + * Also used for in-memory caching by IndexedDbIndexManager and initial index population + * in indexeddb_schema.ts + */ class __PRIVATE_MemoryCollectionParentIndex { + constructor() { + this.index = {}; + } + // Returns false if the entry already existed. + add(e) { + const t = e.lastSegment(), n = e.popLast(), r = this.index[t] || new SortedSet(ResourcePath.comparator), i = !r.has(n); + return this.index[t] = r.add(n), i; + } + has(e) { + const t = e.lastSegment(), n = e.popLast(), r = this.index[t]; + return r && r.has(n); + } + getEntries(e) { + return (this.index[e] || new SortedSet(ResourcePath.comparator)).toArray(); + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const Ft = "IndexedDbIndexManager", Mt = new Uint8Array(0); + +/** + * A persisted implementation of IndexManager. + * + * PORTING NOTE: Unlike iOS and Android, the Web SDK does not memoize index + * data as it supports multi-tab access. + */ +class __PRIVATE_IndexedDbIndexManager { + constructor(e, t) { + this.databaseId = t, + /** + * An in-memory copy of the index entries we've already written since the SDK + * launched. Used to avoid re-writing the same entry repeatedly. + * + * This is *NOT* a complete cache of what's in persistence and so can never be + * used to satisfy reads. + */ + this.vn = new __PRIVATE_MemoryCollectionParentIndex, + /** + * Maps from a target to its equivalent list of sub-targets. Each sub-target + * contains only one term from the target's disjunctive normal form (DNF). + */ + this.Fn = new ObjectMap((e => __PRIVATE_canonifyTarget(e)), ((e, t) => __PRIVATE_targetEquals(e, t))), + this.uid = e.uid || ""; + } + /** + * Adds a new entry to the collection parent index. + * + * Repeated calls for the same collectionPath should be avoided within a + * transaction as IndexedDbIndexManager only caches writes once a transaction + * has been committed. + */ addToCollectionParentIndex(e, t) { + if (!this.vn.has(t)) { + const n = t.lastSegment(), r = t.popLast(); + e.addOnCommittedListener((() => { + // Add the collection to the in memory cache only if the transaction was + // successfully committed. + this.vn.add(t); + })); + const i = { + collectionId: n, + parent: __PRIVATE_encodeResourcePath(r) + }; + return __PRIVATE_collectionParentsStore(e).put(i); + } + return PersistencePromise.resolve(); + } + getCollectionParents(e, t) { + const n = [], r = IDBKeyRange.bound([ t, "" ], [ __PRIVATE_immediateSuccessor(t), "" ], + /*lowerOpen=*/ !1, + /*upperOpen=*/ !0); + return __PRIVATE_collectionParentsStore(e).J(r).next((e => { + for (const r of e) { + // This collectionId guard shouldn't be necessary (and isn't as long + // as we're running in a real browser), but there's a bug in + // indexeddbshim that breaks our range in our tests running in node: + // https://github.com/axemclion/IndexedDBShim/issues/334 + if (r.collectionId !== t) break; + n.push(__PRIVATE_decodeResourcePath(r.parent)); + } + return n; + })); + } + addFieldIndex(e, t) { + // TODO(indexing): Verify that the auto-incrementing index ID works in + // Safari & Firefox. + const n = __PRIVATE_indexConfigurationStore(e), r = function __PRIVATE_toDbIndexConfiguration(e) { + return { + indexId: e.indexId, + collectionGroup: e.collectionGroup, + fields: e.fields.map((e => [ e.fieldPath.canonicalString(), e.kind ])) + }; + }(t); + delete r.indexId; + // `indexId` is auto-populated by IndexedDb + const i = n.add(r); + if (t.indexState) { + const n = __PRIVATE_indexStateStore(e); + return i.next((e => { + n.put(__PRIVATE_toDbIndexState(e, this.uid, t.indexState.sequenceNumber, t.indexState.offset)); + })); + } + return i.next(); + } + deleteFieldIndex(e, t) { + const n = __PRIVATE_indexConfigurationStore(e), r = __PRIVATE_indexStateStore(e), i = __PRIVATE_indexEntriesStore(e); + return n.delete(t.indexId).next((() => r.delete(IDBKeyRange.bound([ t.indexId ], [ t.indexId + 1 ], + /*lowerOpen=*/ !1, + /*upperOpen=*/ !0)))).next((() => i.delete(IDBKeyRange.bound([ t.indexId ], [ t.indexId + 1 ], + /*lowerOpen=*/ !1, + /*upperOpen=*/ !0)))); + } + deleteAllFieldIndexes(e) { + const t = __PRIVATE_indexConfigurationStore(e), n = __PRIVATE_indexEntriesStore(e), r = __PRIVATE_indexStateStore(e); + return t.Z().next((() => n.Z())).next((() => r.Z())); + } + createTargetIndexes(e, t) { + return PersistencePromise.forEach(this.Mn(t), (t => this.getIndexType(e, t).next((n => { + if (0 /* IndexType.NONE */ === n || 1 /* IndexType.PARTIAL */ === n) { + const n = new __PRIVATE_TargetIndexMatcher(t).Dn(); + if (null != n) return this.addFieldIndex(e, n); + } + })))); + } + getDocumentsMatchingTarget(e, t) { + const n = __PRIVATE_indexEntriesStore(e); + let r = !0; + const i = new Map; + return PersistencePromise.forEach(this.Mn(t), (t => this.xn(e, t).next((e => { + r && (r = !!e), i.set(t, e); + })))).next((() => { + if (r) { + let e = __PRIVATE_documentKeySet(); + const r = []; + return PersistencePromise.forEach(i, ((i, s) => { + __PRIVATE_logDebug(Ft, `Using index ${function __PRIVATE_fieldIndexToString(e) { + return `id=${e.indexId}|cg=${e.collectionGroup}|f=${e.fields.map((e => `${e.fieldPath}:${e.kind}`)).join(",")}`; + }(i)} to execute ${__PRIVATE_canonifyTarget(t)}`); + const o = function __PRIVATE_targetGetArrayValues(e, t) { + const n = __PRIVATE_fieldIndexGetArraySegment(t); + if (void 0 === n) return null; + for (const t of __PRIVATE_targetGetFieldFiltersForPath(e, n.fieldPath)) switch (t.op) { + case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ : + return t.value.arrayValue.values || []; + + case "array-contains" /* Operator.ARRAY_CONTAINS */ : + return [ t.value ]; + // Remaining filters are not array filters. + } + return null; + } + /** + * Returns the list of values that are used in != or NOT_IN filters. Returns + * `null` if there are no such filters. + */ (s, i), _ = function __PRIVATE_targetGetNotInValues(e, t) { + const n = new Map; + for (const r of __PRIVATE_fieldIndexGetDirectionalSegments(t)) for (const t of __PRIVATE_targetGetFieldFiltersForPath(e, r.fieldPath)) switch (t.op) { + case "==" /* Operator.EQUAL */ : + case "in" /* Operator.IN */ : + // Encode equality prefix, which is encoded in the index value before + // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to + // `value != 'ab'`). + n.set(r.fieldPath.canonicalString(), t.value); + break; + + case "not-in" /* Operator.NOT_IN */ : + case "!=" /* Operator.NOT_EQUAL */ : + // NotIn/NotEqual is always a suffix. There cannot be any remaining + // segments and hence we can return early here. + return n.set(r.fieldPath.canonicalString(), t.value), Array.from(n.values()); + // Remaining filters cannot be used as notIn bounds. + } + return null; + } + /** + * Returns a lower bound of field values that can be used as a starting point to + * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound + * exists. + */ (s, i), a = function __PRIVATE_targetGetLowerBound(e, t) { + const n = []; + let r = !0; + // For each segment, retrieve a lower bound if there is a suitable filter or + // startAt. + for (const i of __PRIVATE_fieldIndexGetDirectionalSegments(t)) { + const t = 0 /* IndexKind.ASCENDING */ === i.kind ? __PRIVATE_targetGetAscendingBound(e, i.fieldPath, e.startAt) : __PRIVATE_targetGetDescendingBound(e, i.fieldPath, e.startAt); + n.push(t.value), r && (r = t.inclusive); + } + return new Bound(n, r); + } + /** + * Returns an upper bound of field values that can be used as an ending point + * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no + * upper bound exists. + */ (s, i), u = function __PRIVATE_targetGetUpperBound(e, t) { + const n = []; + let r = !0; + // For each segment, retrieve an upper bound if there is a suitable filter or + // endAt. + for (const i of __PRIVATE_fieldIndexGetDirectionalSegments(t)) { + const t = 0 /* IndexKind.ASCENDING */ === i.kind ? __PRIVATE_targetGetDescendingBound(e, i.fieldPath, e.endAt) : __PRIVATE_targetGetAscendingBound(e, i.fieldPath, e.endAt); + n.push(t.value), r && (r = t.inclusive); + } + return new Bound(n, r); + }(s, i), c = this.On(i, s, a), l = this.On(i, s, u), h = this.Nn(i, s, _), P = this.Bn(i.indexId, o, c, a.inclusive, l, u.inclusive, h); + return PersistencePromise.forEach(P, (i => n.Y(i, t.limit).next((t => { + t.forEach((t => { + const n = DocumentKey.fromSegments(t.documentKey); + e.has(n) || (e = e.add(n), r.push(n)); + })); + })))); + })).next((() => r)); + } + return PersistencePromise.resolve(null); + })); + } + Mn(e) { + let t = this.Fn.get(e); + if (t) return t; + if (0 === e.filters.length) t = [ e ]; else { + t = __PRIVATE_getDnfTerms(CompositeFilter.create(e.filters, "and" /* CompositeOperator.AND */)).map((t => __PRIVATE_newTarget(e.path, e.collectionGroup, e.orderBy, t.getFilters(), e.limit, e.startAt, e.endAt))); + } + return this.Fn.set(e, t), t; + } + /** + * Constructs a key range query on `DbIndexEntryStore` that unions all + * bounds. + */ Bn(e, t, n, r, i, s, o) { + // The number of total index scans we union together. This is similar to a + // distributed normal form, but adapted for array values. We create a single + // index range per value in an ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filter + // combined with the values from the query bounds. + const _ = (null != t ? t.length : 1) * Math.max(n.length, i.length), a = _ / (null != t ? t.length : 1), u = []; + for (let c = 0; c < _; ++c) { + const _ = t ? this.Ln(t[c / a]) : Mt, l = this.kn(e, _, n[c % a], r), h = this.qn(e, _, i[c % a], s), P = o.map((t => this.kn(e, _, t, + /* inclusive= */ !0))); + u.push(...this.createRange(l, h, P)); + } + return u; + } + /** Generates the lower bound for `arrayValue` and `directionalValue`. */ kn(e, t, n, r) { + const i = new __PRIVATE_IndexEntry(e, DocumentKey.empty(), t, n); + return r ? i : i.An(); + } + /** Generates the upper bound for `arrayValue` and `directionalValue`. */ qn(e, t, n, r) { + const i = new __PRIVATE_IndexEntry(e, DocumentKey.empty(), t, n); + return r ? i.An() : i; + } + xn(e, t) { + const n = new __PRIVATE_TargetIndexMatcher(t), r = null != t.collectionGroup ? t.collectionGroup : t.path.lastSegment(); + return this.getFieldIndexes(e, r).next((e => { + // Return the index with the most number of segments. + let t = null; + for (const r of e) { + n.yn(r) && (!t || r.fields.length > t.fields.length) && (t = r); + } + return t; + })); + } + getIndexType(e, t) { + let n = 2 /* IndexType.FULL */; + const r = this.Mn(t); + return PersistencePromise.forEach(r, (t => this.xn(e, t).next((e => { + e ? 0 /* IndexType.NONE */ !== n && e.fields.length < function __PRIVATE_targetGetSegmentCount(e) { + let t = new SortedSet(FieldPath$1.comparator), n = !1; + for (const r of e.filters) for (const e of r.getFlattenedFilters()) + // __name__ is not an explicit segment of any index, so we don't need to + // count it. + e.field.isKeyField() || ( + // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately. + // For instance, it is possible to have an index for "a ARRAY a ASC". Even + // though these are on the same field, they should be counted as two + // separate segments in an index. + "array-contains" /* Operator.ARRAY_CONTAINS */ === e.op || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === e.op ? n = !0 : t = t.add(e.field)); + for (const n of e.orderBy) + // __name__ is not an explicit segment of any index, so we don't need to + // count it. + n.field.isKeyField() || (t = t.add(n.field)); + return t.size + (n ? 1 : 0); + }(t) && (n = 1 /* IndexType.PARTIAL */) : n = 0 /* IndexType.NONE */; + })))).next((() => + // OR queries have more than one sub-target (one sub-target per DNF term). We currently consider + // OR queries that have a `limit` to have a partial index. For such queries we perform sorting + // and apply the limit in memory as a post-processing step. + function __PRIVATE_targetHasLimit(e) { + return null !== e.limit; + }(t) && r.length > 1 && 2 /* IndexType.FULL */ === n ? 1 /* IndexType.PARTIAL */ : n)); + } + /** + * Returns the byte encoded form of the directional values in the field index. + * Returns `null` if the document does not have all fields specified in the + * index. + */ Qn(e, t) { + const n = new __PRIVATE_IndexByteEncoder; + for (const r of __PRIVATE_fieldIndexGetDirectionalSegments(e)) { + const e = t.data.field(r.fieldPath); + if (null == e) return null; + const i = n.Pn(r.kind); + __PRIVATE_FirestoreIndexValueWriter.Kt.Dt(e, i); + } + return n.un(); + } + /** Encodes a single value to the ascending index format. */ Ln(e) { + const t = new __PRIVATE_IndexByteEncoder; + return __PRIVATE_FirestoreIndexValueWriter.Kt.Dt(e, t.Pn(0 /* IndexKind.ASCENDING */)), + t.un(); + } + /** + * Returns an encoded form of the document key that sorts based on the key + * ordering of the field index. + */ $n(e, t) { + const n = new __PRIVATE_IndexByteEncoder; + return __PRIVATE_FirestoreIndexValueWriter.Kt.Dt(__PRIVATE_refValue(this.databaseId, t), n.Pn(function __PRIVATE_fieldIndexGetKeyOrder(e) { + const t = __PRIVATE_fieldIndexGetDirectionalSegments(e); + return 0 === t.length ? 0 /* IndexKind.ASCENDING */ : t[t.length - 1].kind; + }(e))), n.un(); + } + /** + * Encodes the given field values according to the specification in `target`. + * For IN queries, a list of possible values is returned. + */ Nn(e, t, n) { + if (null === n) return []; + let r = []; + r.push(new __PRIVATE_IndexByteEncoder); + let i = 0; + for (const s of __PRIVATE_fieldIndexGetDirectionalSegments(e)) { + const e = n[i++]; + for (const n of r) if (this.Un(t, s.fieldPath) && isArray(e)) r = this.Kn(r, s, e); else { + const t = n.Pn(s.kind); + __PRIVATE_FirestoreIndexValueWriter.Kt.Dt(e, t); + } + } + return this.Wn(r); + } + /** + * Encodes the given bounds according to the specification in `target`. For IN + * queries, a list of possible values is returned. + */ On(e, t, n) { + return this.Nn(e, t, n.position); + } + /** Returns the byte representation for the provided encoders. */ Wn(e) { + const t = []; + for (let n = 0; n < e.length; ++n) t[n] = e[n].un(); + return t; + } + /** + * Creates a separate encoder for each element of an array. + * + * The method appends each value to all existing encoders (e.g. filter("a", + * "==", "a1").filter("b", "in", ["b1", "b2"]) becomes ["a1,b1", "a1,b2"]). A + * list of new encoders is returned. + */ Kn(e, t, n) { + const r = [ ...e ], i = []; + for (const e of n.arrayValue.values || []) for (const n of r) { + const r = new __PRIVATE_IndexByteEncoder; + r.seed(n.un()), __PRIVATE_FirestoreIndexValueWriter.Kt.Dt(e, r.Pn(t.kind)), i.push(r); + } + return i; + } + Un(e, t) { + return !!e.filters.find((e => e instanceof FieldFilter && e.field.isEqual(t) && ("in" /* Operator.IN */ === e.op || "not-in" /* Operator.NOT_IN */ === e.op))); + } + getFieldIndexes(e, t) { + const n = __PRIVATE_indexConfigurationStore(e), r = __PRIVATE_indexStateStore(e); + return (t ? n.J(xe, IDBKeyRange.bound(t, t)) : n.J()).next((e => { + const t = []; + return PersistencePromise.forEach(e, (e => r.get([ e.indexId, this.uid ]).next((n => { + t.push(function __PRIVATE_fromDbIndexConfiguration(e, t) { + const n = t ? new IndexState(t.sequenceNumber, new IndexOffset(__PRIVATE_fromDbTimestamp(t.readTime), new DocumentKey(__PRIVATE_decodeResourcePath(t.documentKey)), t.largestBatchId)) : IndexState.empty(), r = e.fields.map((([e, t]) => new IndexSegment(FieldPath$1.fromServerFormat(e), t))); + return new FieldIndex(e.indexId, e.collectionGroup, r, n); + }(e, n)); + })))).next((() => t)); + })); + } + getNextCollectionGroupToUpdate(e) { + return this.getFieldIndexes(e).next((e => 0 === e.length ? null : (e.sort(((e, t) => { + const n = e.indexState.sequenceNumber - t.indexState.sequenceNumber; + return 0 !== n ? n : __PRIVATE_primitiveComparator(e.collectionGroup, t.collectionGroup); + })), e[0].collectionGroup))); + } + updateCollectionGroup(e, t, n) { + const r = __PRIVATE_indexConfigurationStore(e), i = __PRIVATE_indexStateStore(e); + return this.Gn(e).next((e => r.J(xe, IDBKeyRange.bound(t, t)).next((t => PersistencePromise.forEach(t, (t => i.put(__PRIVATE_toDbIndexState(t.indexId, this.uid, e, n)))))))); + } + updateIndexEntries(e, t) { + // Porting Note: `getFieldIndexes()` on Web does not cache index lookups as + // it could be used across different IndexedDB transactions. As any cached + // data might be invalidated by other multi-tab clients, we can only trust + // data within a single IndexedDB transaction. We therefore add a cache + // here. + const n = new Map; + return PersistencePromise.forEach(t, ((t, r) => { + const i = n.get(t.collectionGroup); + return (i ? PersistencePromise.resolve(i) : this.getFieldIndexes(e, t.collectionGroup)).next((i => (n.set(t.collectionGroup, i), + PersistencePromise.forEach(i, (n => this.zn(e, t, n).next((t => { + const i = this.jn(r, n); + return t.isEqual(i) ? PersistencePromise.resolve() : this.Jn(e, r, n, t, i); + }))))))); + })); + } + Hn(e, t, n, r) { + return __PRIVATE_indexEntriesStore(e).put(r.Rn(this.uid, this.$n(n, t.key), t.key)); + } + Yn(e, t, n, r) { + return __PRIVATE_indexEntriesStore(e).delete(r.Vn(this.uid, this.$n(n, t.key), t.key)); + } + zn(e, t, n) { + const r = __PRIVATE_indexEntriesStore(e); + let i = new SortedSet(__PRIVATE_indexEntryComparator); + return r.ee({ + index: $e, + range: IDBKeyRange.only([ n.indexId, this.uid, __PRIVATE_encodeKeySafeBytes(this.$n(n, t)) ]) + }, ((e, r) => { + i = i.add(new __PRIVATE_IndexEntry(n.indexId, t, __PRIVATE_decodeKeySafeBytes(r.arrayValue), __PRIVATE_decodeKeySafeBytes(r.directionalValue))); + })).next((() => i)); + } + /** Creates the index entries for the given document. */ jn(e, t) { + let n = new SortedSet(__PRIVATE_indexEntryComparator); + const r = this.Qn(t, e); + if (null == r) return n; + const i = __PRIVATE_fieldIndexGetArraySegment(t); + if (null != i) { + const s = e.data.field(i.fieldPath); + if (isArray(s)) for (const i of s.arrayValue.values || []) n = n.add(new __PRIVATE_IndexEntry(t.indexId, e.key, this.Ln(i), r)); + } else n = n.add(new __PRIVATE_IndexEntry(t.indexId, e.key, Mt, r)); + return n; + } + /** + * Updates the index entries for the provided document by deleting entries + * that are no longer referenced in `newEntries` and adding all newly added + * entries. + */ Jn(e, t, n, r, i) { + __PRIVATE_logDebug(Ft, "Updating index entries for document '%s'", t.key); + const s = []; + return function __PRIVATE_diffSortedSets(e, t, n, r, i) { + const s = e.getIterator(), o = t.getIterator(); + let _ = __PRIVATE_advanceIterator(s), a = __PRIVATE_advanceIterator(o); + // Walk through the two sets at the same time, using the ordering defined by + // `comparator`. + for (;_ || a; ) { + let e = !1, t = !1; + if (_ && a) { + const r = n(_, a); + r < 0 ? + // The element was removed if the next element in our ordered + // walkthrough is only in `before`. + t = !0 : r > 0 && ( + // The element was added if the next element in our ordered walkthrough + // is only in `after`. + e = !0); + } else null != _ ? t = !0 : e = !0; + e ? (r(a), a = __PRIVATE_advanceIterator(o)) : t ? (i(_), _ = __PRIVATE_advanceIterator(s)) : (_ = __PRIVATE_advanceIterator(s), + a = __PRIVATE_advanceIterator(o)); + } + }(r, i, __PRIVATE_indexEntryComparator, ( + /* onAdd= */ r => { + s.push(this.Hn(e, t, n, r)); + }), ( + /* onRemove= */ r => { + s.push(this.Yn(e, t, n, r)); + })), PersistencePromise.waitFor(s); + } + Gn(e) { + let t = 1; + return __PRIVATE_indexStateStore(e).ee({ + index: Le, + reverse: !0, + range: IDBKeyRange.upperBound([ this.uid, Number.MAX_SAFE_INTEGER ]) + }, ((e, n, r) => { + r.done(), t = n.sequenceNumber + 1; + })).next((() => t)); + } + /** + * Returns a new set of IDB ranges that splits the existing range and excludes + * any values that match the `notInValue` from these ranges. As an example, + * '[foo > 2 && foo != 3]` becomes `[foo > 2 && < 3, foo > 3]`. + */ createRange(e, t, n) { + // The notIn values need to be sorted and unique so that we can return a + // sorted set of non-overlapping ranges. + n = n.sort(((e, t) => __PRIVATE_indexEntryComparator(e, t))).filter(((e, t, n) => !t || 0 !== __PRIVATE_indexEntryComparator(e, n[t - 1]))); + const r = []; + r.push(e); + for (const i of n) { + const n = __PRIVATE_indexEntryComparator(i, e), s = __PRIVATE_indexEntryComparator(i, t); + if (0 === n) + // `notInValue` is the lower bound. We therefore need to raise the bound + // to the next value. + r[0] = e.An(); else if (n > 0 && s < 0) + // `notInValue` is in the middle of the range + r.push(i), r.push(i.An()); else if (s > 0) + // `notInValue` (and all following values) are out of the range + break; + } + r.push(t); + const i = []; + for (let e = 0; e < r.length; e += 2) { + // If we encounter two bounds that will create an unmatchable key range, + // then we return an empty set of key ranges. + if (this.Zn(r[e], r[e + 1])) return []; + const t = r[e].Vn(this.uid, Mt, DocumentKey.empty()), n = r[e + 1].Vn(this.uid, Mt, DocumentKey.empty()); + i.push(IDBKeyRange.bound(t, n)); + } + return i; + } + Zn(e, t) { + // If lower bound is greater than the upper bound, then the key + // range can never be matched. + return __PRIVATE_indexEntryComparator(e, t) > 0; + } + getMinOffsetFromCollectionGroup(e, t) { + return this.getFieldIndexes(e, t).next(__PRIVATE_getMinOffsetFromFieldIndexes); + } + getMinOffset(e, t) { + return PersistencePromise.mapArray(this.Mn(t), (t => this.xn(e, t).next((e => e || fail(44426))))).next(__PRIVATE_getMinOffsetFromFieldIndexes); + } +} + +/** + * Helper to get a typed SimpleDbStore for the collectionParents + * document store. + */ function __PRIVATE_collectionParentsStore(e) { + return __PRIVATE_getStore(e, pe); +} + +/** + * Helper to get a typed SimpleDbStore for the index entry object store. + */ function __PRIVATE_indexEntriesStore(e) { + return __PRIVATE_getStore(e, qe); +} + +/** + * Helper to get a typed SimpleDbStore for the index configuration object store. + */ function __PRIVATE_indexConfigurationStore(e) { + return __PRIVATE_getStore(e, Fe); +} + +/** + * Helper to get a typed SimpleDbStore for the index state object store. + */ function __PRIVATE_indexStateStore(e) { + return __PRIVATE_getStore(e, Ne); +} + +function __PRIVATE_getMinOffsetFromFieldIndexes(e) { + __PRIVATE_hardAssert(0 !== e.length, 28825); + let t = e[0].indexState.offset, n = t.largestBatchId; + for (let r = 1; r < e.length; r++) { + const i = e[r].indexState.offset; + __PRIVATE_indexOffsetComparator(i, t) < 0 && (t = i), n < i.largestBatchId && (n = i.largestBatchId); + } + return new IndexOffset(t.readTime, t.documentKey, n); +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const xt = { + didRun: !1, + sequenceNumbersCollected: 0, + targetsRemoved: 0, + documentsRemoved: 0 +}, Ot = 41943040; + +class LruParams { + static withCacheSize(e) { + return new LruParams(e, LruParams.DEFAULT_COLLECTION_PERCENTILE, LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT); + } + constructor( + // When we attempt to collect, we will only do so if the cache size is greater than this + // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped. + e, + // The percentage of sequence numbers that we will attempt to collect + t, + // A cap on the total number of sequence numbers that will be collected. This prevents + // us from collecting a huge number of sequence numbers if the cache has grown very large. + n) { + this.cacheSizeCollectionThreshold = e, this.percentileToCollect = t, this.maximumSequenceNumbersToCollect = n; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Delete a mutation batch and the associated document mutations. + * @returns A PersistencePromise of the document mutations that were removed. + */ +function removeMutationBatch(e, t, n) { + const r = e.store(te), i = e.store(oe), s = [], o = IDBKeyRange.only(n.batchId); + let _ = 0; + const a = r.ee({ + range: o + }, ((e, t, n) => (_++, n.delete()))); + s.push(a.next((() => { + __PRIVATE_hardAssert(1 === _, 47070, { + batchId: n.batchId + }); + }))); + const u = []; + for (const e of n.mutations) { + const r = __PRIVATE_newDbDocumentMutationKey(t, e.key.path, n.batchId); + s.push(i.delete(r)), u.push(e.key); + } + return PersistencePromise.waitFor(s).next((() => u)); +} + +/** + * Returns an approximate size for the given document. + */ function __PRIVATE_dbDocumentSize(e) { + if (!e) return 0; + let t; + if (e.document) t = e.document; else if (e.unknownDocument) t = e.unknownDocument; else { + if (!e.noDocument) throw fail(14731); + t = e.noDocument; + } + return JSON.stringify(t).length; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** A mutation queue for a specific user, backed by IndexedDB. */ LruParams.DEFAULT_COLLECTION_PERCENTILE = 10, +LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1e3, LruParams.DEFAULT = new LruParams(Ot, LruParams.DEFAULT_COLLECTION_PERCENTILE, LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT), +LruParams.DISABLED = new LruParams(-1, 0, 0); + +class __PRIVATE_IndexedDbMutationQueue { + constructor( + /** + * The normalized userId (e.g. null UID => "" userId) used to store / + * retrieve mutations. + */ + e, t, n, r) { + this.userId = e, this.serializer = t, this.indexManager = n, this.referenceDelegate = r, + /** + * Caches the document keys for pending mutation batches. If the mutation + * has been removed from IndexedDb, the cached value may continue to + * be used to retrieve the batch's document keys. To remove a cached value + * locally, `removeCachedMutationKeys()` should be invoked either directly + * or through `removeMutationBatches()`. + * + * With multi-tab, when the primary client acknowledges or rejects a mutation, + * this cache is used by secondary clients to invalidate the local + * view of the documents that were previously affected by the mutation. + */ + // PORTING NOTE: Multi-tab only. + this.Xn = {}; + } + /** + * Creates a new mutation queue for the given user. + * @param user - The user for which to create a mutation queue. + * @param serializer - The serializer to use when persisting to IndexedDb. + */ static wt(e, t, n, r) { + // TODO(mcg): Figure out what constraints there are on userIDs + // In particular, are there any reserved characters? are empty ids allowed? + // For the moment store these together in the same mutations table assuming + // that empty userIDs aren't allowed. + __PRIVATE_hardAssert("" !== e.uid, 64387); + const i = e.isAuthenticated() ? e.uid : ""; + return new __PRIVATE_IndexedDbMutationQueue(i, t, n, r); + } + checkEmpty(e) { + let t = !0; + const n = IDBKeyRange.bound([ this.userId, Number.NEGATIVE_INFINITY ], [ this.userId, Number.POSITIVE_INFINITY ]); + return __PRIVATE_mutationsStore(e).ee({ + index: re, + range: n + }, ((e, n, r) => { + t = !1, r.done(); + })).next((() => t)); + } + addMutationBatch(e, t, n, r) { + const i = __PRIVATE_documentMutationsStore(e), s = __PRIVATE_mutationsStore(e); + // The IndexedDb implementation in Chrome (and Firefox) does not handle + // compound indices that include auto-generated keys correctly. To ensure + // that the index entry is added correctly in all browsers, we perform two + // writes: The first write is used to retrieve the next auto-generated Batch + // ID, and the second write populates the index and stores the actual + // mutation batch. + // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972 + // We write an empty object to obtain key + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return s.add({}).next((o => { + __PRIVATE_hardAssert("number" == typeof o, 49019); + const _ = new MutationBatch(o, t, n, r), a = function __PRIVATE_toDbMutationBatch(e, t, n) { + const r = n.baseMutations.map((t => toMutation(e.yt, t))), i = n.mutations.map((t => toMutation(e.yt, t))); + return { + userId: t, + batchId: n.batchId, + localWriteTimeMs: n.localWriteTime.toMillis(), + baseMutations: r, + mutations: i + }; + }(this.serializer, this.userId, _), u = []; + let c = new SortedSet(((e, t) => __PRIVATE_primitiveComparator(e.canonicalString(), t.canonicalString()))); + for (const e of r) { + const t = __PRIVATE_newDbDocumentMutationKey(this.userId, e.key.path, o); + c = c.add(e.key.path.popLast()), u.push(s.put(a)), u.push(i.put(t, se)); + } + return c.forEach((t => { + u.push(this.indexManager.addToCollectionParentIndex(e, t)); + })), e.addOnCommittedListener((() => { + this.Xn[o] = _.keys(); + })), PersistencePromise.waitFor(u).next((() => _)); + })); + } + lookupMutationBatch(e, t) { + return __PRIVATE_mutationsStore(e).get(t).next((e => e ? (__PRIVATE_hardAssert(e.userId === this.userId, 48, "Unexpected user for mutation batch", { + userId: e.userId, + batchId: t + }), __PRIVATE_fromDbMutationBatch(this.serializer, e)) : null)); + } + /** + * Returns the document keys for the mutation batch with the given batchId. + * For primary clients, this method returns `null` after + * `removeMutationBatches()` has been called. Secondary clients return a + * cached result until `removeCachedMutationKeys()` is invoked. + */ + // PORTING NOTE: Multi-tab only. + er(e, t) { + return this.Xn[t] ? PersistencePromise.resolve(this.Xn[t]) : this.lookupMutationBatch(e, t).next((e => { + if (e) { + const n = e.keys(); + return this.Xn[t] = n, n; + } + return null; + })); + } + getNextMutationBatchAfterBatchId(e, t) { + const n = t + 1, r = IDBKeyRange.lowerBound([ this.userId, n ]); + let i = null; + return __PRIVATE_mutationsStore(e).ee({ + index: re, + range: r + }, ((e, t, r) => { + t.userId === this.userId && (__PRIVATE_hardAssert(t.batchId >= n, 47524, { + tr: n + }), i = __PRIVATE_fromDbMutationBatch(this.serializer, t)), r.done(); + })).next((() => i)); + } + getHighestUnacknowledgedBatchId(e) { + const t = IDBKeyRange.upperBound([ this.userId, Number.POSITIVE_INFINITY ]); + let n = j; + return __PRIVATE_mutationsStore(e).ee({ + index: re, + range: t, + reverse: !0 + }, ((e, t, r) => { + n = t.batchId, r.done(); + })).next((() => n)); + } + getAllMutationBatches(e) { + const t = IDBKeyRange.bound([ this.userId, j ], [ this.userId, Number.POSITIVE_INFINITY ]); + return __PRIVATE_mutationsStore(e).J(re, t).next((e => e.map((e => __PRIVATE_fromDbMutationBatch(this.serializer, e))))); + } + getAllMutationBatchesAffectingDocumentKey(e, t) { + // Scan the document-mutation index starting with a prefix starting with + // the given documentKey. + const n = __PRIVATE_newDbDocumentMutationPrefixForPath(this.userId, t.path), r = IDBKeyRange.lowerBound(n), i = []; + return __PRIVATE_documentMutationsStore(e).ee({ + range: r + }, ((n, r, s) => { + const [o, _, a] = n, u = __PRIVATE_decodeResourcePath(_); + // Only consider rows matching exactly the specific key of + // interest. Note that because we order by path first, and we + // order terminators before path separators, we'll encounter all + // the index rows for documentKey contiguously. In particular, all + // the rows for documentKey will occur before any rows for + // documents nested in a subcollection beneath documentKey so we + // can stop as soon as we hit any such row. + if (o === this.userId && t.path.isEqual(u)) + // Look up the mutation batch in the store. + return __PRIVATE_mutationsStore(e).get(a).next((e => { + if (!e) throw fail(61480, { + nr: n, + batchId: a + }); + __PRIVATE_hardAssert(e.userId === this.userId, 10503, "Unexpected user for mutation batch", { + userId: e.userId, + batchId: a + }), i.push(__PRIVATE_fromDbMutationBatch(this.serializer, e)); + })); + s.done(); + })).next((() => i)); + } + getAllMutationBatchesAffectingDocumentKeys(e, t) { + let n = new SortedSet(__PRIVATE_primitiveComparator); + const r = []; + return t.forEach((t => { + const i = __PRIVATE_newDbDocumentMutationPrefixForPath(this.userId, t.path), s = IDBKeyRange.lowerBound(i), o = __PRIVATE_documentMutationsStore(e).ee({ + range: s + }, ((e, r, i) => { + const [s, o, _] = e, a = __PRIVATE_decodeResourcePath(o); + // Only consider rows matching exactly the specific key of + // interest. Note that because we order by path first, and we + // order terminators before path separators, we'll encounter all + // the index rows for documentKey contiguously. In particular, all + // the rows for documentKey will occur before any rows for + // documents nested in a subcollection beneath documentKey so we + // can stop as soon as we hit any such row. + s === this.userId && t.path.isEqual(a) ? n = n.add(_) : i.done(); + })); + r.push(o); + })), PersistencePromise.waitFor(r).next((() => this.rr(e, n))); + } + getAllMutationBatchesAffectingQuery(e, t) { + const n = t.path, r = n.length + 1, i = __PRIVATE_newDbDocumentMutationPrefixForPath(this.userId, n), s = IDBKeyRange.lowerBound(i); + // Collect up unique batchIDs encountered during a scan of the index. Use a + // SortedSet to accumulate batch IDs so they can be traversed in order in a + // scan of the main table. + let o = new SortedSet(__PRIVATE_primitiveComparator); + return __PRIVATE_documentMutationsStore(e).ee({ + range: s + }, ((e, t, i) => { + const [s, _, a] = e, u = __PRIVATE_decodeResourcePath(_); + s === this.userId && n.isPrefixOf(u) ? + // Rows with document keys more than one segment longer than the + // query path can't be matches. For example, a query on 'rooms' + // can't match the document /rooms/abc/messages/xyx. + // TODO(mcg): we'll need a different scanner when we implement + // ancestor queries. + u.length === r && (o = o.add(a)) : i.done(); + })).next((() => this.rr(e, o))); + } + rr(e, t) { + const n = [], r = []; + // TODO(rockwood): Implement this using iterate. + return t.forEach((t => { + r.push(__PRIVATE_mutationsStore(e).get(t).next((e => { + if (null === e) throw fail(35274, { + batchId: t + }); + __PRIVATE_hardAssert(e.userId === this.userId, 9748, "Unexpected user for mutation batch", { + userId: e.userId, + batchId: t + }), n.push(__PRIVATE_fromDbMutationBatch(this.serializer, e)); + }))); + })), PersistencePromise.waitFor(r).next((() => n)); + } + removeMutationBatch(e, t) { + return removeMutationBatch(e.le, this.userId, t).next((n => (e.addOnCommittedListener((() => { + this.ir(t.batchId); + })), PersistencePromise.forEach(n, (t => this.referenceDelegate.markPotentiallyOrphaned(e, t)))))); + } + /** + * Clears the cached keys for a mutation batch. This method should be + * called by secondary clients after they process mutation updates. + * + * Note that this method does not have to be called from primary clients as + * the corresponding cache entries are cleared when an acknowledged or + * rejected batch is removed from the mutation queue. + */ + // PORTING NOTE: Multi-tab only + ir(e) { + delete this.Xn[e]; + } + performConsistencyCheck(e) { + return this.checkEmpty(e).next((t => { + if (!t) return PersistencePromise.resolve(); + // Verify that there are no entries in the documentMutations index if + // the queue is empty. + const n = IDBKeyRange.lowerBound( + /** + * Creates a [userId] key for use in the DbDocumentMutations index to iterate + * over all of a user's document mutations. + */ + function __PRIVATE_newDbDocumentMutationPrefixForUser(e) { + return [ e ]; + }(this.userId)), r = []; + return __PRIVATE_documentMutationsStore(e).ee({ + range: n + }, ((e, t, n) => { + if (e[0] === this.userId) { + const t = __PRIVATE_decodeResourcePath(e[1]); + r.push(t); + } else n.done(); + })).next((() => { + __PRIVATE_hardAssert(0 === r.length, 56720, { + sr: r.map((e => e.canonicalString())) + }); + })); + })); + } + containsKey(e, t) { + return __PRIVATE_mutationQueueContainsKey(e, this.userId, t); + } + // PORTING NOTE: Multi-tab only (state is held in memory in other clients). + /** Returns the mutation queue's metadata from IndexedDb. */ + _r(e) { + return __PRIVATE_mutationQueuesStore(e).get(this.userId).next((e => e || { + userId: this.userId, + lastAcknowledgedBatchId: j, + lastStreamToken: "" + })); + } +} + +/** + * @returns true if the mutation queue for the given user contains a pending + * mutation for the given key. + */ function __PRIVATE_mutationQueueContainsKey(e, t, n) { + const r = __PRIVATE_newDbDocumentMutationPrefixForPath(t, n.path), i = r[1], s = IDBKeyRange.lowerBound(r); + let o = !1; + return __PRIVATE_documentMutationsStore(e).ee({ + range: s, + X: !0 + }, ((e, n, r) => { + const [s, _, /*batchID*/ a] = e; + s === t && _ === i && (o = !0), r.done(); + })).next((() => o)); +} + +/** Returns true if any mutation queue contains the given document. */ +/** + * Helper to get a typed SimpleDbStore for the mutations object store. + */ +function __PRIVATE_mutationsStore(e) { + return __PRIVATE_getStore(e, te); +} + +/** + * Helper to get a typed SimpleDbStore for the mutationQueues object store. + */ function __PRIVATE_documentMutationsStore(e) { + return __PRIVATE_getStore(e, oe); +} + +/** + * Helper to get a typed SimpleDbStore for the mutationQueues object store. + */ function __PRIVATE_mutationQueuesStore(e) { + return __PRIVATE_getStore(e, X); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Offset to ensure non-overlapping target ids. */ +/** + * Generates monotonically increasing target IDs for sending targets to the + * watch stream. + * + * The client constructs two generators, one for the target cache, and one for + * for the sync engine (to generate limbo documents targets). These + * generators produce non-overlapping IDs (by using even and odd IDs + * respectively). + * + * By separating the target ID space, the query cache can generate target IDs + * that persist across client restarts, while sync engine can independently + * generate in-memory target IDs that are transient and can be reused after a + * restart. + */ +class __PRIVATE_TargetIdGenerator { + constructor(e) { + this.ar = e; + } + next() { + return this.ar += 2, this.ar; + } + static ur() { + // The target cache generator must return '2' in its first call to `next()` + // as there is no differentiation in the protocol layer between an unset + // number and the number '0'. If we were to sent a target with target ID + // '0', the backend would consider it unset and replace it with its own ID. + return new __PRIVATE_TargetIdGenerator(0); + } + static cr() { + // Sync engine assigns target IDs for limbo document detection. + return new __PRIVATE_TargetIdGenerator(-1); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_IndexedDbTargetCache { + constructor(e, t) { + this.referenceDelegate = e, this.serializer = t; + } + // PORTING NOTE: We don't cache global metadata for the target cache, since + // some of it (in particular `highestTargetId`) can be modified by secondary + // tabs. We could perhaps be more granular (and e.g. still cache + // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go + // to IndexedDb whenever we need to read metadata. We can revisit if it turns + // out to have a meaningful performance impact. + allocateTargetId(e) { + return this.lr(e).next((t => { + const n = new __PRIVATE_TargetIdGenerator(t.highestTargetId); + return t.highestTargetId = n.next(), this.hr(e, t).next((() => t.highestTargetId)); + })); + } + getLastRemoteSnapshotVersion(e) { + return this.lr(e).next((e => SnapshotVersion.fromTimestamp(new Timestamp(e.lastRemoteSnapshotVersion.seconds, e.lastRemoteSnapshotVersion.nanoseconds)))); + } + getHighestSequenceNumber(e) { + return this.lr(e).next((e => e.highestListenSequenceNumber)); + } + setTargetsMetadata(e, t, n) { + return this.lr(e).next((r => (r.highestListenSequenceNumber = t, n && (r.lastRemoteSnapshotVersion = n.toTimestamp()), + t > r.highestListenSequenceNumber && (r.highestListenSequenceNumber = t), this.hr(e, r)))); + } + addTargetData(e, t) { + return this.Pr(e, t).next((() => this.lr(e).next((n => (n.targetCount += 1, this.Tr(t, n), + this.hr(e, n)))))); + } + updateTargetData(e, t) { + return this.Pr(e, t); + } + removeTargetData(e, t) { + return this.removeMatchingKeysForTargetId(e, t.targetId).next((() => __PRIVATE_targetsStore(e).delete(t.targetId))).next((() => this.lr(e))).next((t => (__PRIVATE_hardAssert(t.targetCount > 0, 8065), + t.targetCount -= 1, this.hr(e, t)))); + } + /** + * Drops any targets with sequence number less than or equal to the upper bound, excepting those + * present in `activeTargetIds`. Document associations for the removed targets are also removed. + * Returns the number of targets removed. + */ removeTargets(e, t, n) { + let r = 0; + const i = []; + return __PRIVATE_targetsStore(e).ee(((s, o) => { + const _ = __PRIVATE_fromDbTarget(o); + _.sequenceNumber <= t && null === n.get(_.targetId) && (r++, i.push(this.removeTargetData(e, _))); + })).next((() => PersistencePromise.waitFor(i))).next((() => r)); + } + /** + * Call provided function with each `TargetData` that we have cached. + */ forEachTarget(e, t) { + return __PRIVATE_targetsStore(e).ee(((e, n) => { + const r = __PRIVATE_fromDbTarget(n); + t(r); + })); + } + lr(e) { + return __PRIVATE_globalTargetStore(e).get(fe).next((e => (__PRIVATE_hardAssert(null !== e, 2888), + e))); + } + hr(e, t) { + return __PRIVATE_globalTargetStore(e).put(fe, t); + } + Pr(e, t) { + return __PRIVATE_targetsStore(e).put(__PRIVATE_toDbTarget(this.serializer, t)); + } + /** + * In-place updates the provided metadata to account for values in the given + * TargetData. Saving is done separately. Returns true if there were any + * changes to the metadata. + */ Tr(e, t) { + let n = !1; + return e.targetId > t.highestTargetId && (t.highestTargetId = e.targetId, n = !0), + e.sequenceNumber > t.highestListenSequenceNumber && (t.highestListenSequenceNumber = e.sequenceNumber, + n = !0), n; + } + getTargetCount(e) { + return this.lr(e).next((e => e.targetCount)); + } + getTargetData(e, t) { + // Iterating by the canonicalId may yield more than one result because + // canonicalId values are not required to be unique per target. This query + // depends on the queryTargets index to be efficient. + const n = __PRIVATE_canonifyTarget(t), r = IDBKeyRange.bound([ n, Number.NEGATIVE_INFINITY ], [ n, Number.POSITIVE_INFINITY ]); + let i = null; + return __PRIVATE_targetsStore(e).ee({ + range: r, + index: Ee + }, ((e, n, r) => { + const s = __PRIVATE_fromDbTarget(n); + // After finding a potential match, check that the target is + // actually equal to the requested target. + __PRIVATE_targetEquals(t, s.target) && (i = s, r.done()); + })).next((() => i)); + } + addMatchingKeys(e, t, n) { + // PORTING NOTE: The reverse index (documentsTargets) is maintained by + // IndexedDb. + const r = [], i = __PRIVATE_documentTargetStore(e); + return t.forEach((t => { + const s = __PRIVATE_encodeResourcePath(t.path); + r.push(i.put({ + targetId: n, + path: s + })), r.push(this.referenceDelegate.addReference(e, n, t)); + })), PersistencePromise.waitFor(r); + } + removeMatchingKeys(e, t, n) { + // PORTING NOTE: The reverse index (documentsTargets) is maintained by + // IndexedDb. + const r = __PRIVATE_documentTargetStore(e); + return PersistencePromise.forEach(t, (t => { + const i = __PRIVATE_encodeResourcePath(t.path); + return PersistencePromise.waitFor([ r.delete([ n, i ]), this.referenceDelegate.removeReference(e, n, t) ]); + })); + } + removeMatchingKeysForTargetId(e, t) { + const n = __PRIVATE_documentTargetStore(e), r = IDBKeyRange.bound([ t ], [ t + 1 ], + /*lowerOpen=*/ !1, + /*upperOpen=*/ !0); + return n.delete(r); + } + getMatchingKeysForTargetId(e, t) { + const n = IDBKeyRange.bound([ t ], [ t + 1 ], + /*lowerOpen=*/ !1, + /*upperOpen=*/ !0), r = __PRIVATE_documentTargetStore(e); + let i = __PRIVATE_documentKeySet(); + return r.ee({ + range: n, + X: !0 + }, ((e, t, n) => { + const r = __PRIVATE_decodeResourcePath(e[1]), s = new DocumentKey(r); + i = i.add(s); + })).next((() => i)); + } + containsKey(e, t) { + const n = __PRIVATE_encodeResourcePath(t.path), r = IDBKeyRange.bound([ n ], [ __PRIVATE_immediateSuccessor(n) ], + /*lowerOpen=*/ !1, + /*upperOpen=*/ !0); + let i = 0; + return __PRIVATE_documentTargetStore(e).ee({ + index: Ve, + X: !0, + range: r + }, (([e, t], n, r) => { + // Having a sentinel row for a document does not count as containing that document; + // For the target cache, containing the document means the document is part of some + // target. + 0 !== e && (i++, r.done()); + })).next((() => i > 0)); + } + /** + * Looks up a TargetData entry by target ID. + * + * @param targetId - The target ID of the TargetData entry to look up. + * @returns The cached TargetData entry, or null if the cache has no entry for + * the target. + */ + // PORTING NOTE: Multi-tab only. + At(e, t) { + return __PRIVATE_targetsStore(e).get(t).next((e => e ? __PRIVATE_fromDbTarget(e) : null)); + } +} + +/** + * Helper to get a typed SimpleDbStore for the queries object store. + */ function __PRIVATE_targetsStore(e) { + return __PRIVATE_getStore(e, Ie); +} + +/** + * Helper to get a typed SimpleDbStore for the target globals object store. + */ function __PRIVATE_globalTargetStore(e) { + return __PRIVATE_getStore(e, ge); +} + +/** + * Helper to get a typed SimpleDbStore for the document target object store. + */ function __PRIVATE_documentTargetStore(e) { + return __PRIVATE_getStore(e, Ae); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const Nt = "LruGarbageCollector", Bt = 1048576; + +function __PRIVATE_bufferEntryComparator([e, t], [n, r]) { + const i = __PRIVATE_primitiveComparator(e, n); + return 0 === i ? __PRIVATE_primitiveComparator(t, r) : i; +} + +/** + * Used to calculate the nth sequence number. Keeps a rolling buffer of the + * lowest n values passed to `addElement`, and finally reports the largest of + * them in `maxValue`. + */ class __PRIVATE_RollingSequenceNumberBuffer { + constructor(e) { + this.Ir = e, this.buffer = new SortedSet(__PRIVATE_bufferEntryComparator), this.Er = 0; + } + dr() { + return ++this.Er; + } + Ar(e) { + const t = [ e, this.dr() ]; + if (this.buffer.size < this.Ir) this.buffer = this.buffer.add(t); else { + const e = this.buffer.last(); + __PRIVATE_bufferEntryComparator(t, e) < 0 && (this.buffer = this.buffer.delete(e).add(t)); + } + } + get maxValue() { + // Guaranteed to be non-empty. If we decide we are not collecting any + // sequence numbers, nthSequenceNumber below short-circuits. If we have + // decided that we are collecting n sequence numbers, it's because n is some + // percentage of the existing sequence numbers. That means we should never + // be in a situation where we are collecting sequence numbers but don't + // actually have any. + return this.buffer.last()[0]; + } +} + +/** + * This class is responsible for the scheduling of LRU garbage collection. It handles checking + * whether or not GC is enabled, as well as which delay to use before the next run. + */ class __PRIVATE_LruScheduler { + constructor(e, t, n) { + this.garbageCollector = e, this.asyncQueue = t, this.localStore = n, this.Rr = null; + } + start() { + -1 !== this.garbageCollector.params.cacheSizeCollectionThreshold && this.Vr(6e4); + } + stop() { + this.Rr && (this.Rr.cancel(), this.Rr = null); + } + get started() { + return null !== this.Rr; + } + Vr(e) { + __PRIVATE_logDebug(Nt, `Garbage collection scheduled in ${e}ms`), this.Rr = this.asyncQueue.enqueueAfterDelay("lru_garbage_collection" /* TimerId.LruGarbageCollection */ , e, (async () => { + this.Rr = null; + try { + await this.localStore.collectGarbage(this.garbageCollector); + } catch (e) { + __PRIVATE_isIndexedDbTransactionError(e) ? __PRIVATE_logDebug(Nt, "Ignoring IndexedDB error during garbage collection: ", e) : await __PRIVATE_ignoreIfPrimaryLeaseLoss(e); + } + await this.Vr(3e5); + })); + } +} + +/** + * Implements the steps for LRU garbage collection. + */ class __PRIVATE_LruGarbageCollectorImpl { + constructor(e, t) { + this.mr = e, this.params = t; + } + calculateTargetCount(e, t) { + return this.mr.gr(e).next((e => Math.floor(t / 100 * e))); + } + nthSequenceNumber(e, t) { + if (0 === t) return PersistencePromise.resolve(__PRIVATE_ListenSequence.ce); + const n = new __PRIVATE_RollingSequenceNumberBuffer(t); + return this.mr.forEachTarget(e, (e => n.Ar(e.sequenceNumber))).next((() => this.mr.pr(e, (e => n.Ar(e))))).next((() => n.maxValue)); + } + removeTargets(e, t, n) { + return this.mr.removeTargets(e, t, n); + } + removeOrphanedDocuments(e, t) { + return this.mr.removeOrphanedDocuments(e, t); + } + collect(e, t) { + return -1 === this.params.cacheSizeCollectionThreshold ? (__PRIVATE_logDebug("LruGarbageCollector", "Garbage collection skipped; disabled"), + PersistencePromise.resolve(xt)) : this.getCacheSize(e).next((n => n < this.params.cacheSizeCollectionThreshold ? (__PRIVATE_logDebug("LruGarbageCollector", `Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`), + xt) : this.yr(e, t))); + } + getCacheSize(e) { + return this.mr.getCacheSize(e); + } + yr(e, t) { + let n, r, i, s, o, _, u; + const c = Date.now(); + return this.calculateTargetCount(e, this.params.percentileToCollect).next((t => ( + // Cap at the configured max + t > this.params.maximumSequenceNumbersToCollect ? (__PRIVATE_logDebug("LruGarbageCollector", `Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${t}`), + r = this.params.maximumSequenceNumbersToCollect) : r = t, s = Date.now(), this.nthSequenceNumber(e, r)))).next((r => (n = r, + o = Date.now(), this.removeTargets(e, n, t)))).next((t => (i = t, _ = Date.now(), + this.removeOrphanedDocuments(e, n)))).next((e => { + if (u = Date.now(), __PRIVATE_getLogLevel() <= LogLevel.DEBUG) { + __PRIVATE_logDebug("LruGarbageCollector", `LRU Garbage Collection\n\tCounted targets in ${s - c}ms\n\tDetermined least recently used ${r} in ` + (o - s) + "ms\n" + `\tRemoved ${i} targets in ` + (_ - o) + "ms\n" + `\tRemoved ${e} documents in ` + (u - _) + "ms\n" + `Total Duration: ${u - c}ms`); + } + return PersistencePromise.resolve({ + didRun: !0, + sequenceNumbersCollected: r, + targetsRemoved: i, + documentsRemoved: e + }); + })); + } +} + +function __PRIVATE_newLruGarbageCollector(e, t) { + return new __PRIVATE_LruGarbageCollectorImpl(e, t); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Provides LRU functionality for IndexedDB persistence. */ class __PRIVATE_IndexedDbLruDelegateImpl { + constructor(e, t) { + this.db = e, this.garbageCollector = __PRIVATE_newLruGarbageCollector(this, t); + } + gr(e) { + const t = this.wr(e); + return this.db.getTargetCache().getTargetCount(e).next((e => t.next((t => e + t)))); + } + wr(e) { + let t = 0; + return this.pr(e, (e => { + t++; + })).next((() => t)); + } + forEachTarget(e, t) { + return this.db.getTargetCache().forEachTarget(e, t); + } + pr(e, t) { + return this.Sr(e, ((e, n) => t(n))); + } + addReference(e, t, n) { + return __PRIVATE_writeSentinelKey(e, n); + } + removeReference(e, t, n) { + return __PRIVATE_writeSentinelKey(e, n); + } + removeTargets(e, t, n) { + return this.db.getTargetCache().removeTargets(e, t, n); + } + markPotentiallyOrphaned(e, t) { + return __PRIVATE_writeSentinelKey(e, t); + } + /** + * Returns true if anything would prevent this document from being garbage + * collected, given that the document in question is not present in any + * targets and has a sequence number less than or equal to the upper bound for + * the collection run. + */ br(e, t) { + return function __PRIVATE_mutationQueuesContainKey(e, t) { + let n = !1; + return __PRIVATE_mutationQueuesStore(e).te((r => __PRIVATE_mutationQueueContainsKey(e, r, t).next((e => (e && (n = !0), + PersistencePromise.resolve(!e)))))).next((() => n)); + }(e, t); + } + removeOrphanedDocuments(e, t) { + const n = this.db.getRemoteDocumentCache().newChangeBuffer(), r = []; + let i = 0; + return this.Sr(e, ((s, o) => { + if (o <= t) { + const t = this.br(e, s).next((t => { + if (!t) + // Our size accounting requires us to read all documents before + // removing them. + return i++, n.getEntry(e, s).next((() => (n.removeEntry(s, SnapshotVersion.min()), + __PRIVATE_documentTargetStore(e).delete(function __PRIVATE_sentinelKey$1(e) { + return [ 0, __PRIVATE_encodeResourcePath(e.path) ]; + } + /** + * @returns A value suitable for writing a sentinel row in the target-document + * store. + */ (s))))); + })); + r.push(t); + } + })).next((() => PersistencePromise.waitFor(r))).next((() => n.apply(e))).next((() => i)); + } + removeTarget(e, t) { + const n = t.withSequenceNumber(e.currentSequenceNumber); + return this.db.getTargetCache().updateTargetData(e, n); + } + updateLimboDocument(e, t) { + return __PRIVATE_writeSentinelKey(e, t); + } + /** + * Call provided function for each document in the cache that is 'orphaned'. Orphaned + * means not a part of any target, so the only entry in the target-document index for + * that document will be the sentinel row (targetId 0), which will also have the sequence + * number for the last time the document was accessed. + */ Sr(e, t) { + const n = __PRIVATE_documentTargetStore(e); + let r, i = __PRIVATE_ListenSequence.ce; + return n.ee({ + index: Ve + }, (([e, n], {path: s, sequenceNumber: o}) => { + 0 === e ? ( + // if nextToReport is valid, report it, this is a new key so the + // last one must not be a member of any targets. + i !== __PRIVATE_ListenSequence.ce && t(new DocumentKey(__PRIVATE_decodeResourcePath(r)), i), + // set nextToReport to be this sequence number. It's the next one we + // might report, if we don't find any targets for this document. + // Note that the sequence number must be defined when the targetId + // is 0. + i = o, r = s) : + // set nextToReport to be invalid, we know we don't need to report + // this one since we found a target for it. + i = __PRIVATE_ListenSequence.ce; + })).next((() => { + // Since we report sequence numbers after getting to the next key, we + // need to check if the last key we iterated over was an orphaned + // document and report it. + i !== __PRIVATE_ListenSequence.ce && t(new DocumentKey(__PRIVATE_decodeResourcePath(r)), i); + })); + } + getCacheSize(e) { + return this.db.getRemoteDocumentCache().getSize(e); + } +} + +function __PRIVATE_writeSentinelKey(e, t) { + return __PRIVATE_documentTargetStore(e).put(function __PRIVATE_sentinelRow(e, t) { + return { + targetId: 0, + path: __PRIVATE_encodeResourcePath(e.path), + sequenceNumber: t + }; + }(t, e.currentSequenceNumber)); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An in-memory buffer of entries to be written to a RemoteDocumentCache. + * It can be used to batch up a set of changes to be written to the cache, but + * additionally supports reading entries back with the `getEntry()` method, + * falling back to the underlying RemoteDocumentCache if no entry is + * buffered. + * + * Entries added to the cache *must* be read first. This is to facilitate + * calculating the size delta of the pending changes. + * + * PORTING NOTE: This class was implemented then removed from other platforms. + * If byte-counting ends up being needed on the other platforms, consider + * porting this class as part of that implementation work. + */ class RemoteDocumentChangeBuffer { + constructor() { + // A mapping of document key to the new cache entry that should be written. + this.changes = new ObjectMap((e => e.toString()), ((e, t) => e.isEqual(t))), this.changesApplied = !1; + } + /** + * Buffers a `RemoteDocumentCache.addEntry()` call. + * + * You can only modify documents that have already been retrieved via + * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). + */ addEntry(e) { + this.assertNotApplied(), this.changes.set(e.key, e); + } + /** + * Buffers a `RemoteDocumentCache.removeEntry()` call. + * + * You can only remove documents that have already been retrieved via + * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). + */ removeEntry(e, t) { + this.assertNotApplied(), this.changes.set(e, MutableDocument.newInvalidDocument(e).setReadTime(t)); + } + /** + * Looks up an entry in the cache. The buffered changes will first be checked, + * and if no buffered change applies, this will forward to + * `RemoteDocumentCache.getEntry()`. + * + * @param transaction - The transaction in which to perform any persistence + * operations. + * @param documentKey - The key of the entry to look up. + * @returns The cached document or an invalid document if we have nothing + * cached. + */ getEntry(e, t) { + this.assertNotApplied(); + const n = this.changes.get(t); + return void 0 !== n ? PersistencePromise.resolve(n) : this.getFromCache(e, t); + } + /** + * Looks up several entries in the cache, forwarding to + * `RemoteDocumentCache.getEntry()`. + * + * @param transaction - The transaction in which to perform any persistence + * operations. + * @param documentKeys - The keys of the entries to look up. + * @returns A map of cached documents, indexed by key. If an entry cannot be + * found, the corresponding key will be mapped to an invalid document. + */ getEntries(e, t) { + return this.getAllFromCache(e, t); + } + /** + * Applies buffered changes to the underlying RemoteDocumentCache, using + * the provided transaction. + */ apply(e) { + return this.assertNotApplied(), this.changesApplied = !0, this.applyChanges(e); + } + /** Helper to assert this.changes is not null */ assertNotApplied() {} +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The RemoteDocumentCache for IndexedDb. To construct, invoke + * `newIndexedDbRemoteDocumentCache()`. + */ class __PRIVATE_IndexedDbRemoteDocumentCacheImpl { + constructor(e) { + this.serializer = e; + } + setIndexManager(e) { + this.indexManager = e; + } + /** + * Adds the supplied entries to the cache. + * + * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer + * returned by `newChangeBuffer()` to ensure proper accounting of metadata. + */ addEntry(e, t, n) { + return __PRIVATE_remoteDocumentsStore(e).put(n); + } + /** + * Removes a document from the cache. + * + * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer + * returned by `newChangeBuffer()` to ensure proper accounting of metadata. + */ removeEntry(e, t, n) { + return __PRIVATE_remoteDocumentsStore(e).delete( + /** + * Returns a key that can be used for document lookups via the primary key of + * the DbRemoteDocument object store. + */ + function __PRIVATE_dbReadTimeKey(e, t) { + const n = e.path.toArray(); + return [ + /* prefix path */ n.slice(0, n.length - 2), + /* collection id */ n[n.length - 2], __PRIVATE_toDbTimestampKey(t), + /* document id */ n[n.length - 1] ]; + } + /** + * Returns a key that can be used for document lookups on the + * `DbRemoteDocumentDocumentCollectionGroupIndex` index. + */ (t, n)); + } + /** + * Updates the current cache size. + * + * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the + * cache's metadata. + */ updateMetadata(e, t) { + return this.getMetadata(e).next((n => (n.byteSize += t, this.Dr(e, n)))); + } + getEntry(e, t) { + let n = MutableDocument.newInvalidDocument(t); + return __PRIVATE_remoteDocumentsStore(e).ee({ + index: ue, + range: IDBKeyRange.only(__PRIVATE_dbKey(t)) + }, ((e, r) => { + n = this.Cr(t, r); + })).next((() => n)); + } + /** + * Looks up an entry in the cache. + * + * @param documentKey - The key of the entry to look up. + * @returns The cached document entry and its size. + */ vr(e, t) { + let n = { + size: 0, + document: MutableDocument.newInvalidDocument(t) + }; + return __PRIVATE_remoteDocumentsStore(e).ee({ + index: ue, + range: IDBKeyRange.only(__PRIVATE_dbKey(t)) + }, ((e, r) => { + n = { + document: this.Cr(t, r), + size: __PRIVATE_dbDocumentSize(r) + }; + })).next((() => n)); + } + getEntries(e, t) { + let n = __PRIVATE_mutableDocumentMap(); + return this.Fr(e, t, ((e, t) => { + const r = this.Cr(e, t); + n = n.insert(e, r); + })).next((() => n)); + } + /** + * Looks up several entries in the cache. + * + * @param documentKeys - The set of keys entries to look up. + * @returns A map of documents indexed by key and a map of sizes indexed by + * key (zero if the document does not exist). + */ Mr(e, t) { + let n = __PRIVATE_mutableDocumentMap(), r = new SortedMap(DocumentKey.comparator); + return this.Fr(e, t, ((e, t) => { + const i = this.Cr(e, t); + n = n.insert(e, i), r = r.insert(e, __PRIVATE_dbDocumentSize(t)); + })).next((() => ({ + documents: n, + Or: r + }))); + } + Fr(e, t, n) { + if (t.isEmpty()) return PersistencePromise.resolve(); + let r = new SortedSet(__PRIVATE_dbKeyComparator); + t.forEach((e => r = r.add(e))); + const i = IDBKeyRange.bound(__PRIVATE_dbKey(r.first()), __PRIVATE_dbKey(r.last())), s = r.getIterator(); + let o = s.getNext(); + return __PRIVATE_remoteDocumentsStore(e).ee({ + index: ue, + range: i + }, ((e, t, r) => { + const i = DocumentKey.fromSegments([ ...t.prefixPath, t.collectionGroup, t.documentId ]); + // Go through keys not found in cache. + for (;o && __PRIVATE_dbKeyComparator(o, i) < 0; ) n(o, null), o = s.getNext(); + o && o.isEqual(i) && ( + // Key found in cache. + n(o, t), o = s.hasNext() ? s.getNext() : null), + // Skip to the next key (if there is one). + o ? r.j(__PRIVATE_dbKey(o)) : r.done(); + })).next((() => { + // The rest of the keys are not in the cache. One case where `iterate` + // above won't go through them is when the cache is empty. + for (;o; ) n(o, null), o = s.hasNext() ? s.getNext() : null; + })); + } + getDocumentsMatchingQuery(e, t, n, r, i) { + const s = t.path, o = [ s.popLast().toArray(), s.lastSegment(), __PRIVATE_toDbTimestampKey(n.readTime), n.documentKey.path.isEmpty() ? "" : n.documentKey.path.lastSegment() ], _ = [ s.popLast().toArray(), s.lastSegment(), [ Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER ], "" ]; + return __PRIVATE_remoteDocumentsStore(e).J(IDBKeyRange.bound(o, _, !0)).next((e => { + i?.incrementDocumentReadCount(e.length); + let n = __PRIVATE_mutableDocumentMap(); + for (const i of e) { + const e = this.Cr(DocumentKey.fromSegments(i.prefixPath.concat(i.collectionGroup, i.documentId)), i); + e.isFoundDocument() && (__PRIVATE_queryMatches(t, e) || r.has(e.key)) && ( + // Either the document matches the given query, or it is mutated. + n = n.insert(e.key, e)); + } + return n; + })); + } + getAllFromCollectionGroup(e, t, n, r) { + let i = __PRIVATE_mutableDocumentMap(); + const s = __PRIVATE_dbCollectionGroupKey(t, n), o = __PRIVATE_dbCollectionGroupKey(t, IndexOffset.max()); + return __PRIVATE_remoteDocumentsStore(e).ee({ + index: le, + range: IDBKeyRange.bound(s, o, !0) + }, ((e, t, n) => { + const s = this.Cr(DocumentKey.fromSegments(t.prefixPath.concat(t.collectionGroup, t.documentId)), t); + i = i.insert(s.key, s), i.size === r && n.done(); + })).next((() => i)); + } + newChangeBuffer(e) { + return new __PRIVATE_IndexedDbRemoteDocumentChangeBuffer(this, !!e && e.trackRemovals); + } + getSize(e) { + return this.getMetadata(e).next((e => e.byteSize)); + } + getMetadata(e) { + return __PRIVATE_documentGlobalStore(e).get(Te).next((e => (__PRIVATE_hardAssert(!!e, 20021), + e))); + } + Dr(e, t) { + return __PRIVATE_documentGlobalStore(e).put(Te, t); + } + /** + * Decodes `dbRemoteDoc` and returns the document (or an invalid document if + * the document corresponds to the format used for sentinel deletes). + */ Cr(e, t) { + if (t) { + const e = __PRIVATE_fromDbRemoteDocument(this.serializer, t); + // Whether the document is a sentinel removal and should only be used in the + // `getNewDocumentChanges()` + if (!(e.isNoDocument() && e.version.isEqual(SnapshotVersion.min()))) return e; + } + return MutableDocument.newInvalidDocument(e); + } +} + +/** Creates a new IndexedDbRemoteDocumentCache. */ function __PRIVATE_newIndexedDbRemoteDocumentCache(e) { + return new __PRIVATE_IndexedDbRemoteDocumentCacheImpl(e); +} + +/** + * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache. + * + * Unlike the MemoryRemoteDocumentChangeBuffer, the IndexedDb implementation computes the size + * delta for all submitted changes. This avoids having to re-read all documents from IndexedDb + * when we apply the changes. + */ class __PRIVATE_IndexedDbRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer { + /** + * @param documentCache - The IndexedDbRemoteDocumentCache to apply the changes to. + * @param trackRemovals - Whether to create sentinel deletes that can be tracked by + * `getNewDocumentChanges()`. + */ + constructor(e, t) { + super(), this.Nr = e, this.trackRemovals = t, + // A map of document sizes and read times prior to applying the changes in + // this buffer. + this.Br = new ObjectMap((e => e.toString()), ((e, t) => e.isEqual(t))); + } + applyChanges(e) { + const t = []; + let n = 0, r = new SortedSet(((e, t) => __PRIVATE_primitiveComparator(e.canonicalString(), t.canonicalString()))); + return this.changes.forEach(((i, s) => { + const o = this.Br.get(i); + if (t.push(this.Nr.removeEntry(e, i, o.readTime)), s.isValidDocument()) { + const _ = __PRIVATE_toDbRemoteDocument(this.Nr.serializer, s); + r = r.add(i.path.popLast()); + const a = __PRIVATE_dbDocumentSize(_); + n += a - o.size, t.push(this.Nr.addEntry(e, i, _)); + } else if (n -= o.size, this.trackRemovals) { + // In order to track removals, we store a "sentinel delete" in the + // RemoteDocumentCache. This entry is represented by a NoDocument + // with a version of 0 and ignored by `maybeDecodeDocument()` but + // preserved in `getNewDocumentChanges()`. + const n = __PRIVATE_toDbRemoteDocument(this.Nr.serializer, s.convertToNoDocument(SnapshotVersion.min())); + t.push(this.Nr.addEntry(e, i, n)); + } + })), r.forEach((n => { + t.push(this.Nr.indexManager.addToCollectionParentIndex(e, n)); + })), t.push(this.Nr.updateMetadata(e, n)), PersistencePromise.waitFor(t); + } + getFromCache(e, t) { + // Record the size of everything we load from the cache so we can compute a delta later. + return this.Nr.vr(e, t).next((e => (this.Br.set(t, { + size: e.size, + readTime: e.document.readTime + }), e.document))); + } + getAllFromCache(e, t) { + // Record the size of everything we load from the cache so we can compute + // a delta later. + return this.Nr.Mr(e, t).next((({documents: e, Or: t}) => ( + // Note: `getAllFromCache` returns two maps instead of a single map from + // keys to `DocumentSizeEntry`s. This is to allow returning the + // `MutableDocumentMap` directly, without a conversion. + t.forEach(((t, n) => { + this.Br.set(t, { + size: n, + readTime: e.get(t).readTime + }); + })), e))); + } +} + +function __PRIVATE_documentGlobalStore(e) { + return __PRIVATE_getStore(e, Pe); +} + +/** + * Helper to get a typed SimpleDbStore for the remoteDocuments object store. + */ function __PRIVATE_remoteDocumentsStore(e) { + return __PRIVATE_getStore(e, _e); +} + +/** + * Returns a key that can be used for document lookups on the + * `DbRemoteDocumentDocumentKeyIndex` index. + */ function __PRIVATE_dbKey(e) { + const t = e.path.toArray(); + return [ + /* prefix path */ t.slice(0, t.length - 2), + /* collection id */ t[t.length - 2], + /* document id */ t[t.length - 1] ]; +} + +function __PRIVATE_dbCollectionGroupKey(e, t) { + const n = t.documentKey.path.toArray(); + return [ + /* collection id */ e, __PRIVATE_toDbTimestampKey(t.readTime), + /* prefix path */ n.slice(0, n.length - 2), + /* document id */ n.length > 0 ? n[n.length - 1] : "" ]; +} + +/** + * Comparator that compares document keys according to the primary key sorting + * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id + * and then document ID). + * + * Visible for testing. + */ function __PRIVATE_dbKeyComparator(e, t) { + const n = e.path.toArray(), r = t.path.toArray(); + // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74 + let i = 0; + for (let e = 0; e < n.length - 2 && e < r.length - 2; ++e) if (i = __PRIVATE_primitiveComparator(n[e], r[e]), + i) return i; + return i = __PRIVATE_primitiveComparator(n.length, r.length), i || (i = __PRIVATE_primitiveComparator(n[n.length - 2], r[r.length - 2]), + i || __PRIVATE_primitiveComparator(n[n.length - 1], r[r.length - 1])); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Schema Version for the Web client: + * 1. Initial version including Mutation Queue, Query Cache, and Remote + * Document Cache + * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No + * longer required because migration 3 unconditionally clears it. + * 3. Dropped and re-created Query Cache to deal with cache corruption related + * to limbo resolution. Addresses + * https://github.com/firebase/firebase-ios-sdk/issues/1548 + * 4. Multi-Tab Support. + * 5. Removal of held write acks. + * 6. Create document global for tracking document cache size. + * 7. Ensure every cached document has a sentinel row with a sequence number. + * 8. Add collection-parent index for Collection Group queries. + * 9. Change RemoteDocumentChanges store to be keyed by readTime rather than + * an auto-incrementing ID. This is required for Index-Free queries. + * 10. Rewrite the canonical IDs to the explicit Protobuf-based format. + * 11. Add bundles and named_queries for bundle support. + * 12. Add document overlays. + * 13. Rewrite the keys of the remote document cache to allow for efficient + * document lookup via `getAll()`. + * 14. Add overlays. + * 15. Add indexing support. + * 16. Parse timestamp strings before creating index entries. + * 17. TODO(tomandersen) + * 18. Encode key safe representations of IndexEntry in DbIndexEntryStore. + */ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a local view (overlay) of a document, and the fields that are + * locally mutated. + */ +class OverlayedDocument { + constructor(e, + /** + * The fields that are locally mutated by patch mutations. + * + * If the overlayed document is from set or delete mutations, this is `null`. + * If there is no overlay (mutation) for the document, this is an empty `FieldMask`. + */ + t) { + this.overlayedDocument = e, this.mutatedFields = t; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A readonly view of the local state of all documents we're tracking (i.e. we + * have a cached version in remoteDocumentCache or local mutations for the + * document). The view is computed by applying the mutations in the + * MutationQueue to the RemoteDocumentCache. + */ class LocalDocumentsView { + constructor(e, t, n, r) { + this.remoteDocumentCache = e, this.mutationQueue = t, this.documentOverlayCache = n, + this.indexManager = r; + } + /** + * Get the local view of the document identified by `key`. + * + * @returns Local view of the document or null if we don't have any cached + * state for it. + */ getDocument(e, t) { + let n = null; + return this.documentOverlayCache.getOverlay(e, t).next((r => (n = r, this.remoteDocumentCache.getEntry(e, t)))).next((e => (null !== n && __PRIVATE_mutationApplyToLocalView(n.mutation, e, FieldMask.empty(), Timestamp.now()), + e))); + } + /** + * Gets the local view of the documents identified by `keys`. + * + * If we don't have cached state for a document in `keys`, a NoDocument will + * be stored for that key in the resulting set. + */ getDocuments(e, t) { + return this.remoteDocumentCache.getEntries(e, t).next((t => this.getLocalViewOfDocuments(e, t, __PRIVATE_documentKeySet()).next((() => t)))); + } + /** + * Similar to `getDocuments`, but creates the local view from the given + * `baseDocs` without retrieving documents from the local store. + * + * @param transaction - The transaction this operation is scoped to. + * @param docs - The documents to apply local mutations to get the local views. + * @param existenceStateChanged - The set of document keys whose existence state + * is changed. This is useful to determine if some documents overlay needs + * to be recalculated. + */ getLocalViewOfDocuments(e, t, n = __PRIVATE_documentKeySet()) { + const r = __PRIVATE_newOverlayMap(); + return this.populateOverlays(e, r, t).next((() => this.computeViews(e, t, r, n).next((e => { + let t = documentMap(); + return e.forEach(((e, n) => { + t = t.insert(e, n.overlayedDocument); + })), t; + })))); + } + /** + * Gets the overlayed documents for the given document map, which will include + * the local view of those documents and a `FieldMask` indicating which fields + * are mutated locally, `null` if overlay is a Set or Delete mutation. + */ getOverlayedDocuments(e, t) { + const n = __PRIVATE_newOverlayMap(); + return this.populateOverlays(e, n, t).next((() => this.computeViews(e, t, n, __PRIVATE_documentKeySet()))); + } + /** + * Fetches the overlays for {@code docs} and adds them to provided overlay map + * if the map does not already contain an entry for the given document key. + */ populateOverlays(e, t, n) { + const r = []; + return n.forEach((e => { + t.has(e) || r.push(e); + })), this.documentOverlayCache.getOverlays(e, r).next((e => { + e.forEach(((e, n) => { + t.set(e, n); + })); + })); + } + /** + * Computes the local view for the given documents. + * + * @param docs - The documents to compute views for. It also has the base + * version of the documents. + * @param overlays - The overlays that need to be applied to the given base + * version of the documents. + * @param existenceStateChanged - A set of documents whose existence states + * might have changed. This is used to determine if we need to re-calculate + * overlays from mutation queues. + * @return A map represents the local documents view. + */ computeViews(e, t, n, r) { + let i = __PRIVATE_mutableDocumentMap(); + const s = __PRIVATE_newDocumentKeyMap(), o = function __PRIVATE_newOverlayedDocumentMap() { + return __PRIVATE_newDocumentKeyMap(); + }(); + return t.forEach(((e, t) => { + const o = n.get(t.key); + // Recalculate an overlay if the document's existence state changed due to + // a remote event *and* the overlay is a PatchMutation. This is because + // document existence state can change if some patch mutation's + // preconditions are met. + // NOTE: we recalculate when `overlay` is undefined as well, because there + // might be a patch mutation whose precondition does not match before the + // change (hence overlay is undefined), but would now match. + r.has(t.key) && (void 0 === o || o.mutation instanceof __PRIVATE_PatchMutation) ? i = i.insert(t.key, t) : void 0 !== o ? (s.set(t.key, o.mutation.getFieldMask()), + __PRIVATE_mutationApplyToLocalView(o.mutation, t, o.mutation.getFieldMask(), Timestamp.now())) : + // no overlay exists + // Using EMPTY to indicate there is no overlay for the document. + s.set(t.key, FieldMask.empty()); + })), this.recalculateAndSaveOverlays(e, i).next((e => (e.forEach(((e, t) => s.set(e, t))), + t.forEach(((e, t) => o.set(e, new OverlayedDocument(t, s.get(e) ?? null)))), o))); + } + recalculateAndSaveOverlays(e, t) { + const n = __PRIVATE_newDocumentKeyMap(); + // A reverse lookup map from batch id to the documents within that batch. + let r = new SortedMap(((e, t) => e - t)), i = __PRIVATE_documentKeySet(); + return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e, t).next((e => { + for (const i of e) i.keys().forEach((e => { + const s = t.get(e); + if (null === s) return; + let o = n.get(e) || FieldMask.empty(); + o = i.applyToLocalView(s, o), n.set(e, o); + const _ = (r.get(i.batchId) || __PRIVATE_documentKeySet()).add(e); + r = r.insert(i.batchId, _); + })); + })).next((() => { + const s = [], o = r.getReverseIterator(); + // Iterate in descending order of batch IDs, and skip documents that are + // already saved. + for (;o.hasNext(); ) { + const r = o.getNext(), _ = r.key, a = r.value, u = __PRIVATE_newMutationMap(); + a.forEach((e => { + if (!i.has(e)) { + const r = __PRIVATE_calculateOverlayMutation(t.get(e), n.get(e)); + null !== r && u.set(e, r), i = i.add(e); + } + })), s.push(this.documentOverlayCache.saveOverlays(e, _, u)); + } + return PersistencePromise.waitFor(s); + })).next((() => n)); + } + /** + * Recalculates overlays by reading the documents from remote document cache + * first, and saves them after they are calculated. + */ recalculateAndSaveOverlaysForDocumentKeys(e, t) { + return this.remoteDocumentCache.getEntries(e, t).next((t => this.recalculateAndSaveOverlays(e, t))); + } + /** + * Performs a query against the local view of all documents. + * + * @param transaction - The persistence transaction. + * @param query - The query to match documents against. + * @param offset - Read time and key to start scanning by (exclusive). + * @param context - A optional tracker to keep a record of important details + * during database local query execution. + */ getDocumentsMatchingQuery(e, t, n, r) { + /** + * Returns whether the query matches a single document by path (rather than a + * collection). + */ + return function __PRIVATE_isDocumentQuery$1(e) { + return DocumentKey.isDocumentKey(e.path) && null === e.collectionGroup && 0 === e.filters.length; + }(t) ? this.getDocumentsMatchingDocumentQuery(e, t.path) : __PRIVATE_isCollectionGroupQuery(t) ? this.getDocumentsMatchingCollectionGroupQuery(e, t, n, r) : this.getDocumentsMatchingCollectionQuery(e, t, n, r); + } + /** + * Given a collection group, returns the next documents that follow the provided offset, along + * with an updated batch ID. + * + *

The documents returned by this method are ordered by remote version from the provided + * offset. If there are no more remote documents after the provided offset, documents with + * mutations in order of batch id from the offset are returned. Since all documents in a batch are + * returned together, the total number of documents returned can exceed {@code count}. + * + * @param transaction + * @param collectionGroup The collection group for the documents. + * @param offset The offset to index into. + * @param count The number of documents to return + * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id. + */ getNextDocuments(e, t, n, r) { + return this.remoteDocumentCache.getAllFromCollectionGroup(e, t, n, r).next((i => { + const s = r - i.size > 0 ? this.documentOverlayCache.getOverlaysForCollectionGroup(e, t, n.largestBatchId, r - i.size) : PersistencePromise.resolve(__PRIVATE_newOverlayMap()); + // The callsite will use the largest batch ID together with the latest read time to create + // a new index offset. Since we only process batch IDs if all remote documents have been read, + // no overlay will increase the overall read time. This is why we only need to special case + // the batch id. + let o = U, _ = i; + return s.next((t => PersistencePromise.forEach(t, ((t, n) => (o < n.largestBatchId && (o = n.largestBatchId), + i.get(t) ? PersistencePromise.resolve() : this.remoteDocumentCache.getEntry(e, t).next((e => { + _ = _.insert(t, e); + }))))).next((() => this.populateOverlays(e, t, i))).next((() => this.computeViews(e, _, t, __PRIVATE_documentKeySet()))).next((e => ({ + batchId: o, + changes: __PRIVATE_convertOverlayedDocumentMapToDocumentMap(e) + }))))); + })); + } + getDocumentsMatchingDocumentQuery(e, t) { + // Just do a simple document lookup. + return this.getDocument(e, new DocumentKey(t)).next((e => { + let t = documentMap(); + return e.isFoundDocument() && (t = t.insert(e.key, e)), t; + })); + } + getDocumentsMatchingCollectionGroupQuery(e, t, n, r) { + const i = t.collectionGroup; + let s = documentMap(); + return this.indexManager.getCollectionParents(e, i).next((o => PersistencePromise.forEach(o, (o => { + const _ = function __PRIVATE_asCollectionQueryAtPath(e, t) { + return new __PRIVATE_QueryImpl(t, + /*collectionGroup=*/ null, e.explicitOrderBy.slice(), e.filters.slice(), e.limit, e.limitType, e.startAt, e.endAt); + }(t, o.child(i)); + return this.getDocumentsMatchingCollectionQuery(e, _, n, r).next((e => { + e.forEach(((e, t) => { + s = s.insert(e, t); + })); + })); + })).next((() => s)))); + } + getDocumentsMatchingCollectionQuery(e, t, n, r) { + // Query the remote documents and overlay mutations. + let i; + return this.documentOverlayCache.getOverlaysForCollection(e, t.path, n.largestBatchId).next((s => (i = s, + this.remoteDocumentCache.getDocumentsMatchingQuery(e, t, n, i, r)))).next((e => { + // As documents might match the query because of their overlay we need to + // include documents for all overlays in the initial document set. + i.forEach(((t, n) => { + const r = n.getKey(); + null === e.get(r) && (e = e.insert(r, MutableDocument.newInvalidDocument(r))); + })); + // Apply the overlays and match against the query. + let n = documentMap(); + return e.forEach(((e, r) => { + const s = i.get(e); + void 0 !== s && __PRIVATE_mutationApplyToLocalView(s.mutation, r, FieldMask.empty(), Timestamp.now()), + // Finally, insert the documents that still match the query + __PRIVATE_queryMatches(t, r) && (n = n.insert(e, r)); + })), n; + })); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_MemoryBundleCache { + constructor(e) { + this.serializer = e, this.Lr = new Map, this.kr = new Map; + } + getBundleMetadata(e, t) { + return PersistencePromise.resolve(this.Lr.get(t)); + } + saveBundleMetadata(e, t) { + return this.Lr.set(t.id, + /** Decodes a BundleMetadata proto into a BundleMetadata object. */ + function __PRIVATE_fromBundleMetadata(e) { + return { + id: e.id, + version: e.version, + createTime: __PRIVATE_fromVersion(e.createTime) + }; + }(t)), PersistencePromise.resolve(); + } + getNamedQuery(e, t) { + return PersistencePromise.resolve(this.kr.get(t)); + } + saveNamedQuery(e, t) { + return this.kr.set(t.name, function __PRIVATE_fromProtoNamedQuery(e) { + return { + name: e.name, + query: __PRIVATE_fromBundledQuery(e.bundledQuery), + readTime: __PRIVATE_fromVersion(e.readTime) + }; + }(t)), PersistencePromise.resolve(); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An in-memory implementation of DocumentOverlayCache. + */ class __PRIVATE_MemoryDocumentOverlayCache { + constructor() { + // A map sorted by DocumentKey, whose value is a pair of the largest batch id + // for the overlay and the overlay itself. + this.overlays = new SortedMap(DocumentKey.comparator), this.qr = new Map; + } + getOverlay(e, t) { + return PersistencePromise.resolve(this.overlays.get(t)); + } + getOverlays(e, t) { + const n = __PRIVATE_newOverlayMap(); + return PersistencePromise.forEach(t, (t => this.getOverlay(e, t).next((e => { + null !== e && n.set(t, e); + })))).next((() => n)); + } + saveOverlays(e, t, n) { + return n.forEach(((n, r) => { + this.St(e, t, r); + })), PersistencePromise.resolve(); + } + removeOverlaysForBatchId(e, t, n) { + const r = this.qr.get(n); + return void 0 !== r && (r.forEach((e => this.overlays = this.overlays.remove(e))), + this.qr.delete(n)), PersistencePromise.resolve(); + } + getOverlaysForCollection(e, t, n) { + const r = __PRIVATE_newOverlayMap(), i = t.length + 1, s = new DocumentKey(t.child("")), o = this.overlays.getIteratorFrom(s); + for (;o.hasNext(); ) { + const e = o.getNext().value, s = e.getKey(); + if (!t.isPrefixOf(s.path)) break; + // Documents from sub-collections + s.path.length === i && (e.largestBatchId > n && r.set(e.getKey(), e)); + } + return PersistencePromise.resolve(r); + } + getOverlaysForCollectionGroup(e, t, n, r) { + let i = new SortedMap(((e, t) => e - t)); + const s = this.overlays.getIterator(); + for (;s.hasNext(); ) { + const e = s.getNext().value; + if (e.getKey().getCollectionGroup() === t && e.largestBatchId > n) { + let t = i.get(e.largestBatchId); + null === t && (t = __PRIVATE_newOverlayMap(), i = i.insert(e.largestBatchId, t)), + t.set(e.getKey(), e); + } + } + const o = __PRIVATE_newOverlayMap(), _ = i.getIterator(); + for (;_.hasNext(); ) { + if (_.getNext().value.forEach(((e, t) => o.set(e, t))), o.size() >= r) break; + } + return PersistencePromise.resolve(o); + } + St(e, t, n) { + // Remove the association of the overlay to its batch id. + const r = this.overlays.get(n.key); + if (null !== r) { + const e = this.qr.get(r.largestBatchId).delete(n.key); + this.qr.set(r.largestBatchId, e); + } + this.overlays = this.overlays.insert(n.key, new Overlay(t, n)); + // Create the association of this overlay to the given largestBatchId. + let i = this.qr.get(t); + void 0 === i && (i = __PRIVATE_documentKeySet(), this.qr.set(t, i)), this.qr.set(t, i.add(n.key)); + } +} + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_MemoryGlobalsCache { + constructor() { + this.sessionToken = ByteString.EMPTY_BYTE_STRING; + } + getSessionToken(e) { + return PersistencePromise.resolve(this.sessionToken); + } + setSessionToken(e, t) { + return this.sessionToken = t, PersistencePromise.resolve(); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A collection of references to a document from some kind of numbered entity + * (either a target ID or batch ID). As references are added to or removed from + * the set corresponding events are emitted to a registered garbage collector. + * + * Each reference is represented by a DocumentReference object. Each of them + * contains enough information to uniquely identify the reference. They are all + * stored primarily in a set sorted by key. A document is considered garbage if + * there's no references in that set (this can be efficiently checked thanks to + * sorting by key). + * + * ReferenceSet also keeps a secondary set that contains references sorted by + * IDs. This one is used to efficiently implement removal of all references by + * some target ID. + */ class __PRIVATE_ReferenceSet { + constructor() { + // A set of outstanding references to a document sorted by key. + this.Qr = new SortedSet(__PRIVATE_DocReference.$r), + // A set of outstanding references to a document sorted by target id. + this.Ur = new SortedSet(__PRIVATE_DocReference.Kr); + } + /** Returns true if the reference set contains no references. */ isEmpty() { + return this.Qr.isEmpty(); + } + /** Adds a reference to the given document key for the given ID. */ addReference(e, t) { + const n = new __PRIVATE_DocReference(e, t); + this.Qr = this.Qr.add(n), this.Ur = this.Ur.add(n); + } + /** Add references to the given document keys for the given ID. */ Wr(e, t) { + e.forEach((e => this.addReference(e, t))); + } + /** + * Removes a reference to the given document key for the given + * ID. + */ removeReference(e, t) { + this.Gr(new __PRIVATE_DocReference(e, t)); + } + zr(e, t) { + e.forEach((e => this.removeReference(e, t))); + } + /** + * Clears all references with a given ID. Calls removeRef() for each key + * removed. + */ jr(e) { + const t = new DocumentKey(new ResourcePath([])), n = new __PRIVATE_DocReference(t, e), r = new __PRIVATE_DocReference(t, e + 1), i = []; + return this.Ur.forEachInRange([ n, r ], (e => { + this.Gr(e), i.push(e.key); + })), i; + } + Jr() { + this.Qr.forEach((e => this.Gr(e))); + } + Gr(e) { + this.Qr = this.Qr.delete(e), this.Ur = this.Ur.delete(e); + } + Hr(e) { + const t = new DocumentKey(new ResourcePath([])), n = new __PRIVATE_DocReference(t, e), r = new __PRIVATE_DocReference(t, e + 1); + let i = __PRIVATE_documentKeySet(); + return this.Ur.forEachInRange([ n, r ], (e => { + i = i.add(e.key); + })), i; + } + containsKey(e) { + const t = new __PRIVATE_DocReference(e, 0), n = this.Qr.firstAfterOrEqual(t); + return null !== n && e.isEqual(n.key); + } +} + +class __PRIVATE_DocReference { + constructor(e, t) { + this.key = e, this.Yr = t; + } + /** Compare by key then by ID */ static $r(e, t) { + return DocumentKey.comparator(e.key, t.key) || __PRIVATE_primitiveComparator(e.Yr, t.Yr); + } + /** Compare by ID then by key */ static Kr(e, t) { + return __PRIVATE_primitiveComparator(e.Yr, t.Yr) || DocumentKey.comparator(e.key, t.key); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_MemoryMutationQueue { + constructor(e, t) { + this.indexManager = e, this.referenceDelegate = t, + /** + * The set of all mutations that have been sent but not yet been applied to + * the backend. + */ + this.mutationQueue = [], + /** Next value to use when assigning sequential IDs to each mutation batch. */ + this.tr = 1, + /** An ordered mapping between documents and the mutations batch IDs. */ + this.Zr = new SortedSet(__PRIVATE_DocReference.$r); + } + checkEmpty(e) { + return PersistencePromise.resolve(0 === this.mutationQueue.length); + } + addMutationBatch(e, t, n, r) { + const i = this.tr; + this.tr++, this.mutationQueue.length > 0 && this.mutationQueue[this.mutationQueue.length - 1]; + const s = new MutationBatch(i, t, n, r); + this.mutationQueue.push(s); + // Track references by document key and index collection parents. + for (const t of r) this.Zr = this.Zr.add(new __PRIVATE_DocReference(t.key, i)), + this.indexManager.addToCollectionParentIndex(e, t.key.path.popLast()); + return PersistencePromise.resolve(s); + } + lookupMutationBatch(e, t) { + return PersistencePromise.resolve(this.Xr(t)); + } + getNextMutationBatchAfterBatchId(e, t) { + const n = t + 1, r = this.ei(n), i = r < 0 ? 0 : r; + // The requested batchId may still be out of range so normalize it to the + // start of the queue. + return PersistencePromise.resolve(this.mutationQueue.length > i ? this.mutationQueue[i] : null); + } + getHighestUnacknowledgedBatchId() { + return PersistencePromise.resolve(0 === this.mutationQueue.length ? j : this.tr - 1); + } + getAllMutationBatches(e) { + return PersistencePromise.resolve(this.mutationQueue.slice()); + } + getAllMutationBatchesAffectingDocumentKey(e, t) { + const n = new __PRIVATE_DocReference(t, 0), r = new __PRIVATE_DocReference(t, Number.POSITIVE_INFINITY), i = []; + return this.Zr.forEachInRange([ n, r ], (e => { + const t = this.Xr(e.Yr); + i.push(t); + })), PersistencePromise.resolve(i); + } + getAllMutationBatchesAffectingDocumentKeys(e, t) { + let n = new SortedSet(__PRIVATE_primitiveComparator); + return t.forEach((e => { + const t = new __PRIVATE_DocReference(e, 0), r = new __PRIVATE_DocReference(e, Number.POSITIVE_INFINITY); + this.Zr.forEachInRange([ t, r ], (e => { + n = n.add(e.Yr); + })); + })), PersistencePromise.resolve(this.ti(n)); + } + getAllMutationBatchesAffectingQuery(e, t) { + // Use the query path as a prefix for testing if a document matches the + // query. + const n = t.path, r = n.length + 1; + // Construct a document reference for actually scanning the index. Unlike + // the prefix the document key in this reference must have an even number of + // segments. The empty segment can be used a suffix of the query path + // because it precedes all other segments in an ordered traversal. + let i = n; + DocumentKey.isDocumentKey(i) || (i = i.child("")); + const s = new __PRIVATE_DocReference(new DocumentKey(i), 0); + // Find unique batchIDs referenced by all documents potentially matching the + // query. + let o = new SortedSet(__PRIVATE_primitiveComparator); + return this.Zr.forEachWhile((e => { + const t = e.key.path; + return !!n.isPrefixOf(t) && ( + // Rows with document keys more than one segment longer than the query + // path can't be matches. For example, a query on 'rooms' can't match + // the document /rooms/abc/messages/xyx. + // TODO(mcg): we'll need a different scanner when we implement + // ancestor queries. + t.length === r && (o = o.add(e.Yr)), !0); + }), s), PersistencePromise.resolve(this.ti(o)); + } + ti(e) { + // Construct an array of matching batches, sorted by batchID to ensure that + // multiple mutations affecting the same document key are applied in order. + const t = []; + return e.forEach((e => { + const n = this.Xr(e); + null !== n && t.push(n); + })), t; + } + removeMutationBatch(e, t) { + __PRIVATE_hardAssert(0 === this.ni(t.batchId, "removed"), 55003), this.mutationQueue.shift(); + let n = this.Zr; + return PersistencePromise.forEach(t.mutations, (r => { + const i = new __PRIVATE_DocReference(r.key, t.batchId); + return n = n.delete(i), this.referenceDelegate.markPotentiallyOrphaned(e, r.key); + })).next((() => { + this.Zr = n; + })); + } + ir(e) { + // No-op since the memory mutation queue does not maintain a separate cache. + } + containsKey(e, t) { + const n = new __PRIVATE_DocReference(t, 0), r = this.Zr.firstAfterOrEqual(n); + return PersistencePromise.resolve(t.isEqual(r && r.key)); + } + performConsistencyCheck(e) { + return this.mutationQueue.length, PersistencePromise.resolve(); + } + /** + * Finds the index of the given batchId in the mutation queue and asserts that + * the resulting index is within the bounds of the queue. + * + * @param batchId - The batchId to search for + * @param action - A description of what the caller is doing, phrased in passive + * form (e.g. "acknowledged" in a routine that acknowledges batches). + */ ni(e, t) { + return this.ei(e); + } + /** + * Finds the index of the given batchId in the mutation queue. This operation + * is O(1). + * + * @returns The computed index of the batch with the given batchId, based on + * the state of the queue. Note this index can be negative if the requested + * batchId has already been removed from the queue or past the end of the + * queue if the batchId is larger than the last added batch. + */ ei(e) { + if (0 === this.mutationQueue.length) + // As an index this is past the end of the queue + return 0; + // Examine the front of the queue to figure out the difference between the + // batchId and indexes in the array. Note that since the queue is ordered + // by batchId, if the first batch has a larger batchId then the requested + // batchId doesn't exist in the queue. + return e - this.mutationQueue[0].batchId; + } + /** + * A version of lookupMutationBatch that doesn't return a promise, this makes + * other functions that uses this code easier to read and more efficient. + */ Xr(e) { + const t = this.ei(e); + if (t < 0 || t >= this.mutationQueue.length) return null; + return this.mutationQueue[t]; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The smallest value representable by a 64-bit signed integer (long). + */ +/** + * The memory-only RemoteDocumentCache for IndexedDb. To construct, invoke + * `newMemoryRemoteDocumentCache()`. + */ +class __PRIVATE_MemoryRemoteDocumentCacheImpl { + /** + * @param sizer - Used to assess the size of a document. For eager GC, this is + * expected to just return 0 to avoid unnecessarily doing the work of + * calculating the size. + */ + constructor(e) { + this.ri = e, + /** Underlying cache of documents and their read times. */ + this.docs = function __PRIVATE_documentEntryMap() { + return new SortedMap(DocumentKey.comparator); + }(), + /** Size of all cached documents. */ + this.size = 0; + } + setIndexManager(e) { + this.indexManager = e; + } + /** + * Adds the supplied entry to the cache and updates the cache size as appropriate. + * + * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer + * returned by `newChangeBuffer()`. + */ addEntry(e, t) { + const n = t.key, r = this.docs.get(n), i = r ? r.size : 0, s = this.ri(t); + return this.docs = this.docs.insert(n, { + document: t.mutableCopy(), + size: s + }), this.size += s - i, this.indexManager.addToCollectionParentIndex(e, n.path.popLast()); + } + /** + * Removes the specified entry from the cache and updates the cache size as appropriate. + * + * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer + * returned by `newChangeBuffer()`. + */ removeEntry(e) { + const t = this.docs.get(e); + t && (this.docs = this.docs.remove(e), this.size -= t.size); + } + getEntry(e, t) { + const n = this.docs.get(t); + return PersistencePromise.resolve(n ? n.document.mutableCopy() : MutableDocument.newInvalidDocument(t)); + } + getEntries(e, t) { + let n = __PRIVATE_mutableDocumentMap(); + return t.forEach((e => { + const t = this.docs.get(e); + n = n.insert(e, t ? t.document.mutableCopy() : MutableDocument.newInvalidDocument(e)); + })), PersistencePromise.resolve(n); + } + getDocumentsMatchingQuery(e, t, n, r) { + let i = __PRIVATE_mutableDocumentMap(); + // Documents are ordered by key, so we can use a prefix scan to narrow down + // the documents we need to match the query against. + const s = t.path, o = new DocumentKey(s.child("__id-9223372036854775808__")), _ = this.docs.getIteratorFrom(o); + // Document keys are ordered first by numeric value ("__id__"), + // then lexicographically by string value. Start the iterator at the minimum + // possible Document key value. + for (;_.hasNext(); ) { + const {key: e, value: {document: o}} = _.getNext(); + if (!s.isPrefixOf(e.path)) break; + e.path.length > s.length + 1 || (__PRIVATE_indexOffsetComparator(__PRIVATE_newIndexOffsetFromDocument(o), n) <= 0 || (r.has(o.key) || __PRIVATE_queryMatches(t, o)) && (i = i.insert(o.key, o.mutableCopy()))); + } + return PersistencePromise.resolve(i); + } + getAllFromCollectionGroup(e, t, n, r) { + // This method should only be called from the IndexBackfiller if persistence + // is enabled. + fail(9500); + } + ii(e, t) { + return PersistencePromise.forEach(this.docs, (e => t(e))); + } + newChangeBuffer(e) { + // `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps + // a separate changelog and does not need special handling for removals. + return new __PRIVATE_MemoryRemoteDocumentChangeBuffer(this); + } + getSize(e) { + return PersistencePromise.resolve(this.size); + } +} + +/** + * Creates a new memory-only RemoteDocumentCache. + * + * @param sizer - Used to assess the size of a document. For eager GC, this is + * expected to just return 0 to avoid unnecessarily doing the work of + * calculating the size. + */ +/** + * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache. + */ +class __PRIVATE_MemoryRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer { + constructor(e) { + super(), this.Nr = e; + } + applyChanges(e) { + const t = []; + return this.changes.forEach(((n, r) => { + r.isValidDocument() ? t.push(this.Nr.addEntry(e, r)) : this.Nr.removeEntry(n); + })), PersistencePromise.waitFor(t); + } + getFromCache(e, t) { + return this.Nr.getEntry(e, t); + } + getAllFromCache(e, t) { + return this.Nr.getEntries(e, t); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_MemoryTargetCache { + constructor(e) { + this.persistence = e, + /** + * Maps a target to the data about that target + */ + this.si = new ObjectMap((e => __PRIVATE_canonifyTarget(e)), __PRIVATE_targetEquals), + /** The last received snapshot version. */ + this.lastRemoteSnapshotVersion = SnapshotVersion.min(), + /** The highest numbered target ID encountered. */ + this.highestTargetId = 0, + /** The highest sequence number encountered. */ + this.oi = 0, + /** + * A ordered bidirectional mapping between documents and the remote target + * IDs. + */ + this._i = new __PRIVATE_ReferenceSet, this.targetCount = 0, this.ai = __PRIVATE_TargetIdGenerator.ur(); + } + forEachTarget(e, t) { + return this.si.forEach(((e, n) => t(n))), PersistencePromise.resolve(); + } + getLastRemoteSnapshotVersion(e) { + return PersistencePromise.resolve(this.lastRemoteSnapshotVersion); + } + getHighestSequenceNumber(e) { + return PersistencePromise.resolve(this.oi); + } + allocateTargetId(e) { + return this.highestTargetId = this.ai.next(), PersistencePromise.resolve(this.highestTargetId); + } + setTargetsMetadata(e, t, n) { + return n && (this.lastRemoteSnapshotVersion = n), t > this.oi && (this.oi = t), + PersistencePromise.resolve(); + } + Pr(e) { + this.si.set(e.target, e); + const t = e.targetId; + t > this.highestTargetId && (this.ai = new __PRIVATE_TargetIdGenerator(t), this.highestTargetId = t), + e.sequenceNumber > this.oi && (this.oi = e.sequenceNumber); + } + addTargetData(e, t) { + return this.Pr(t), this.targetCount += 1, PersistencePromise.resolve(); + } + updateTargetData(e, t) { + return this.Pr(t), PersistencePromise.resolve(); + } + removeTargetData(e, t) { + return this.si.delete(t.target), this._i.jr(t.targetId), this.targetCount -= 1, + PersistencePromise.resolve(); + } + removeTargets(e, t, n) { + let r = 0; + const i = []; + return this.si.forEach(((s, o) => { + o.sequenceNumber <= t && null === n.get(o.targetId) && (this.si.delete(s), i.push(this.removeMatchingKeysForTargetId(e, o.targetId)), + r++); + })), PersistencePromise.waitFor(i).next((() => r)); + } + getTargetCount(e) { + return PersistencePromise.resolve(this.targetCount); + } + getTargetData(e, t) { + const n = this.si.get(t) || null; + return PersistencePromise.resolve(n); + } + addMatchingKeys(e, t, n) { + return this._i.Wr(t, n), PersistencePromise.resolve(); + } + removeMatchingKeys(e, t, n) { + this._i.zr(t, n); + const r = this.persistence.referenceDelegate, i = []; + return r && t.forEach((t => { + i.push(r.markPotentiallyOrphaned(e, t)); + })), PersistencePromise.waitFor(i); + } + removeMatchingKeysForTargetId(e, t) { + return this._i.jr(t), PersistencePromise.resolve(); + } + getMatchingKeysForTargetId(e, t) { + const n = this._i.Hr(t); + return PersistencePromise.resolve(n); + } + containsKey(e, t) { + return PersistencePromise.resolve(this._i.containsKey(t)); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A memory-backed instance of Persistence. Data is stored only in RAM and + * not persisted across sessions. + */ +class __PRIVATE_MemoryPersistence { + /** + * The constructor accepts a factory for creating a reference delegate. This + * allows both the delegate and this instance to have strong references to + * each other without having nullable fields that would then need to be + * checked or asserted on every access. + */ + constructor(e, t) { + this.ui = {}, this.overlays = {}, this.ci = new __PRIVATE_ListenSequence(0), this.li = !1, + this.li = !0, this.hi = new __PRIVATE_MemoryGlobalsCache, this.referenceDelegate = e(this), + this.Pi = new __PRIVATE_MemoryTargetCache(this); + this.indexManager = new __PRIVATE_MemoryIndexManager, this.remoteDocumentCache = function __PRIVATE_newMemoryRemoteDocumentCache(e) { + return new __PRIVATE_MemoryRemoteDocumentCacheImpl(e); + }((e => this.referenceDelegate.Ti(e))), this.serializer = new __PRIVATE_LocalSerializer(t), + this.Ii = new __PRIVATE_MemoryBundleCache(this.serializer); + } + start() { + return Promise.resolve(); + } + shutdown() { + // No durable state to ensure is closed on shutdown. + return this.li = !1, Promise.resolve(); + } + get started() { + return this.li; + } + setDatabaseDeletedListener() { + // No op. + } + setNetworkEnabled() { + // No op. + } + getIndexManager(e) { + // We do not currently support indices for memory persistence, so we can + // return the same shared instance of the memory index manager. + return this.indexManager; + } + getDocumentOverlayCache(e) { + let t = this.overlays[e.toKey()]; + return t || (t = new __PRIVATE_MemoryDocumentOverlayCache, this.overlays[e.toKey()] = t), + t; + } + getMutationQueue(e, t) { + let n = this.ui[e.toKey()]; + return n || (n = new __PRIVATE_MemoryMutationQueue(t, this.referenceDelegate), this.ui[e.toKey()] = n), + n; + } + getGlobalsCache() { + return this.hi; + } + getTargetCache() { + return this.Pi; + } + getRemoteDocumentCache() { + return this.remoteDocumentCache; + } + getBundleCache() { + return this.Ii; + } + runTransaction(e, t, n) { + __PRIVATE_logDebug("MemoryPersistence", "Starting transaction:", e); + const r = new __PRIVATE_MemoryTransaction(this.ci.next()); + return this.referenceDelegate.Ei(), n(r).next((e => this.referenceDelegate.di(r).next((() => e)))).toPromise().then((e => (r.raiseOnCommittedEvent(), + e))); + } + Ai(e, t) { + return PersistencePromise.or(Object.values(this.ui).map((n => () => n.containsKey(e, t)))); + } +} + +/** + * Memory persistence is not actually transactional, but future implementations + * may have transaction-scoped state. + */ class __PRIVATE_MemoryTransaction extends PersistenceTransaction { + constructor(e) { + super(), this.currentSequenceNumber = e; + } +} + +class __PRIVATE_MemoryEagerDelegate { + constructor(e) { + this.persistence = e, + /** Tracks all documents that are active in Query views. */ + this.Ri = new __PRIVATE_ReferenceSet, + /** The list of documents that are potentially GCed after each transaction. */ + this.Vi = null; + } + static mi(e) { + return new __PRIVATE_MemoryEagerDelegate(e); + } + get fi() { + if (this.Vi) return this.Vi; + throw fail(60996); + } + addReference(e, t, n) { + return this.Ri.addReference(n, t), this.fi.delete(n.toString()), PersistencePromise.resolve(); + } + removeReference(e, t, n) { + return this.Ri.removeReference(n, t), this.fi.add(n.toString()), PersistencePromise.resolve(); + } + markPotentiallyOrphaned(e, t) { + return this.fi.add(t.toString()), PersistencePromise.resolve(); + } + removeTarget(e, t) { + this.Ri.jr(t.targetId).forEach((e => this.fi.add(e.toString()))); + const n = this.persistence.getTargetCache(); + return n.getMatchingKeysForTargetId(e, t.targetId).next((e => { + e.forEach((e => this.fi.add(e.toString()))); + })).next((() => n.removeTargetData(e, t))); + } + Ei() { + this.Vi = new Set; + } + di(e) { + // Remove newly orphaned documents. + const t = this.persistence.getRemoteDocumentCache().newChangeBuffer(); + return PersistencePromise.forEach(this.fi, (n => { + const r = DocumentKey.fromPath(n); + return this.gi(e, r).next((e => { + e || t.removeEntry(r, SnapshotVersion.min()); + })); + })).next((() => (this.Vi = null, t.apply(e)))); + } + updateLimboDocument(e, t) { + return this.gi(e, t).next((e => { + e ? this.fi.delete(t.toString()) : this.fi.add(t.toString()); + })); + } + Ti(e) { + // For eager GC, we don't care about the document size, there are no size thresholds. + return 0; + } + gi(e, t) { + return PersistencePromise.or([ () => PersistencePromise.resolve(this.Ri.containsKey(t)), () => this.persistence.getTargetCache().containsKey(e, t), () => this.persistence.Ai(e, t) ]); + } +} + +class __PRIVATE_MemoryLruDelegate { + constructor(e, t) { + this.persistence = e, this.pi = new ObjectMap((e => __PRIVATE_encodeResourcePath(e.path)), ((e, t) => e.isEqual(t))), + this.garbageCollector = __PRIVATE_newLruGarbageCollector(this, t); + } + static mi(e, t) { + return new __PRIVATE_MemoryLruDelegate(e, t); + } + // No-ops, present so memory persistence doesn't have to care which delegate + // it has. + Ei() {} + di(e) { + return PersistencePromise.resolve(); + } + forEachTarget(e, t) { + return this.persistence.getTargetCache().forEachTarget(e, t); + } + gr(e) { + const t = this.wr(e); + return this.persistence.getTargetCache().getTargetCount(e).next((e => t.next((t => e + t)))); + } + wr(e) { + let t = 0; + return this.pr(e, (e => { + t++; + })).next((() => t)); + } + pr(e, t) { + return PersistencePromise.forEach(this.pi, ((n, r) => this.br(e, n, r).next((e => e ? PersistencePromise.resolve() : t(r))))); + } + removeTargets(e, t, n) { + return this.persistence.getTargetCache().removeTargets(e, t, n); + } + removeOrphanedDocuments(e, t) { + let n = 0; + const r = this.persistence.getRemoteDocumentCache(), i = r.newChangeBuffer(); + return r.ii(e, (r => this.br(e, r, t).next((e => { + e || (n++, i.removeEntry(r, SnapshotVersion.min())); + })))).next((() => i.apply(e))).next((() => n)); + } + markPotentiallyOrphaned(e, t) { + return this.pi.set(t, e.currentSequenceNumber), PersistencePromise.resolve(); + } + removeTarget(e, t) { + const n = t.withSequenceNumber(e.currentSequenceNumber); + return this.persistence.getTargetCache().updateTargetData(e, n); + } + addReference(e, t, n) { + return this.pi.set(n, e.currentSequenceNumber), PersistencePromise.resolve(); + } + removeReference(e, t, n) { + return this.pi.set(n, e.currentSequenceNumber), PersistencePromise.resolve(); + } + updateLimboDocument(e, t) { + return this.pi.set(t, e.currentSequenceNumber), PersistencePromise.resolve(); + } + Ti(e) { + let t = e.key.toString().length; + return e.isFoundDocument() && (t += __PRIVATE_estimateByteSize(e.data.value)), t; + } + br(e, t, n) { + return PersistencePromise.or([ () => this.persistence.Ai(e, t), () => this.persistence.getTargetCache().containsKey(e, t), () => { + const e = this.pi.get(t); + return PersistencePromise.resolve(void 0 !== e && e > n); + } ]); + } + getCacheSize(e) { + return this.persistence.getRemoteDocumentCache().getSize(e); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Performs database creation and schema upgrades. */ class __PRIVATE_SchemaConverter { + constructor(e) { + this.serializer = e; + } + /** + * Performs database creation and schema upgrades. + * + * Note that in production, this method is only ever used to upgrade the schema + * to SCHEMA_VERSION. Different values of toVersion are only used for testing + * and local feature development. + */ k(e, t, n, r) { + const i = new __PRIVATE_SimpleDbTransaction("createOrUpgrade", t); + n < 1 && r >= 1 && (!function __PRIVATE_createPrimaryClientStore(e) { + e.createObjectStore(Y); + }(e), function __PRIVATE_createMutationQueue(e) { + e.createObjectStore(X, { + keyPath: ee + }); + const t = e.createObjectStore(te, { + keyPath: ne, + autoIncrement: !0 + }); + t.createIndex(re, ie, { + unique: !0 + }), e.createObjectStore(oe); + } + /** + * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads + * and rewrites all data. + */ (e), __PRIVATE_createQueryCache(e), function __PRIVATE_createLegacyRemoteDocumentCache(e) { + e.createObjectStore(H); + }(e)); + // Migration 2 to populate the targetGlobal object no longer needed since + // migration 3 unconditionally clears it. + let s = PersistencePromise.resolve(); + return n < 3 && r >= 3 && ( + // Brand new clients don't need to drop and recreate--only clients that + // potentially have corrupt data. + 0 !== n && (!function __PRIVATE_dropQueryCache(e) { + e.deleteObjectStore(Ae), e.deleteObjectStore(Ie), e.deleteObjectStore(ge); + }(e), __PRIVATE_createQueryCache(e)), s = s.next((() => + /** + * Creates the target global singleton row. + * + * @param txn - The version upgrade transaction for indexeddb + */ + function __PRIVATE_writeEmptyTargetGlobalEntry(e) { + const t = e.store(ge), n = { + highestTargetId: 0, + highestListenSequenceNumber: 0, + lastRemoteSnapshotVersion: SnapshotVersion.min().toTimestamp(), + targetCount: 0 + }; + return t.put(fe, n); + }(i)))), n < 4 && r >= 4 && (0 !== n && ( + // Schema version 3 uses auto-generated keys to generate globally unique + // mutation batch IDs (this was previously ensured internally by the + // client). To migrate to the new schema, we have to read all mutations + // and write them back out. We preserve the existing batch IDs to guarantee + // consistency with other object stores. Any further mutation batch IDs will + // be auto-generated. + s = s.next((() => function __PRIVATE_upgradeMutationBatchSchemaAndMigrateData(e, t) { + const n = t.store(te); + return n.J().next((n => { + e.deleteObjectStore(te); + e.createObjectStore(te, { + keyPath: ne, + autoIncrement: !0 + }).createIndex(re, ie, { + unique: !0 + }); + const r = t.store(te), i = n.map((e => r.put(e))); + return PersistencePromise.waitFor(i); + })); + }(e, i)))), s = s.next((() => { + !function __PRIVATE_createClientMetadataStore(e) { + e.createObjectStore(we, { + keyPath: Se + }); + }(e); + }))), n < 5 && r >= 5 && (s = s.next((() => this.yi(i)))), n < 6 && r >= 6 && (s = s.next((() => (function __PRIVATE_createDocumentGlobalStore(e) { + e.createObjectStore(Pe); + }(e), this.wi(i))))), n < 7 && r >= 7 && (s = s.next((() => this.Si(i)))), n < 8 && r >= 8 && (s = s.next((() => this.bi(e, i)))), + n < 9 && r >= 9 && (s = s.next((() => { + // Multi-Tab used to manage its own changelog, but this has been moved + // to the DbRemoteDocument object store itself. Since the previous change + // log only contained transient data, we can drop its object store. + !function __PRIVATE_dropRemoteDocumentChangesStore(e) { + e.objectStoreNames.contains("remoteDocumentChanges") && e.deleteObjectStore("remoteDocumentChanges"); + }(e); + // Note: Schema version 9 used to create a read time index for the + // RemoteDocumentCache. This is now done with schema version 13. + }))), n < 10 && r >= 10 && (s = s.next((() => this.Di(i)))), n < 11 && r >= 11 && (s = s.next((() => { + !function __PRIVATE_createBundlesStore(e) { + e.createObjectStore(be, { + keyPath: De + }); + }(e), function __PRIVATE_createNamedQueriesStore(e) { + e.createObjectStore(Ce, { + keyPath: ve + }); + }(e); + }))), n < 12 && r >= 12 && (s = s.next((() => { + !function __PRIVATE_createDocumentOverlayStore(e) { + const t = e.createObjectStore(Ke, { + keyPath: We + }); + t.createIndex(Ge, ze, { + unique: !1 + }), t.createIndex(je, Je, { + unique: !1 + }); + }(e); + }))), n < 13 && r >= 13 && (s = s.next((() => function __PRIVATE_createRemoteDocumentCache(e) { + const t = e.createObjectStore(_e, { + keyPath: ae + }); + t.createIndex(ue, ce), t.createIndex(le, he); + }(e))).next((() => this.Ci(e, i))).next((() => e.deleteObjectStore(H)))), n < 14 && r >= 14 && (s = s.next((() => this.Fi(e, i)))), + n < 15 && r >= 15 && (s = s.next((() => function __PRIVATE_createFieldIndex(e) { + const t = e.createObjectStore(Fe, { + keyPath: Me, + autoIncrement: !0 + }); + t.createIndex(xe, Oe, { + unique: !1 + }); + const n = e.createObjectStore(Ne, { + keyPath: Be + }); + n.createIndex(Le, ke, { + unique: !1 + }); + const r = e.createObjectStore(qe, { + keyPath: Qe + }); + r.createIndex($e, Ue, { + unique: !1 + }); + }(e)))), n < 16 && r >= 16 && ( + // Clear the object stores to remove possibly corrupted index entries + s = s.next((() => { + t.objectStore(Ne).clear(); + })).next((() => { + t.objectStore(qe).clear(); + }))), n < 17 && r >= 17 && (s = s.next((() => { + !function __PRIVATE_createGlobalsStore(e) { + e.createObjectStore(He, { + keyPath: Ye + }); + }(e); + }))), n < 18 && r >= 18 && isSafariOrWebkit() && (s = s.next((() => { + t.objectStore(Ne).clear(); + })).next((() => { + t.objectStore(qe).clear(); + }))), s; + } + wi(e) { + let t = 0; + return e.store(H).ee(((e, n) => { + t += __PRIVATE_dbDocumentSize(n); + })).next((() => { + const n = { + byteSize: t + }; + return e.store(Pe).put(Te, n); + })); + } + yi(e) { + const t = e.store(X), n = e.store(te); + return t.J().next((t => PersistencePromise.forEach(t, (t => { + const r = IDBKeyRange.bound([ t.userId, j ], [ t.userId, t.lastAcknowledgedBatchId ]); + return n.J(re, r).next((n => PersistencePromise.forEach(n, (n => { + __PRIVATE_hardAssert(n.userId === t.userId, 18650, "Cannot process batch from unexpected user", { + batchId: n.batchId + }); + const r = __PRIVATE_fromDbMutationBatch(this.serializer, n); + return removeMutationBatch(e, t.userId, r).next((() => {})); + })))); + })))); + } + /** + * Ensures that every document in the remote document cache has a corresponding sentinel row + * with a sequence number. Missing rows are given the most recently used sequence number. + */ Si(e) { + const t = e.store(Ae), n = e.store(H); + return e.store(ge).get(fe).next((e => { + const r = []; + return n.ee(((n, i) => { + const s = new ResourcePath(n), o = function __PRIVATE_sentinelKey(e) { + return [ 0, __PRIVATE_encodeResourcePath(e) ]; + }(s); + r.push(t.get(o).next((n => n ? PersistencePromise.resolve() : (n => t.put({ + targetId: 0, + path: __PRIVATE_encodeResourcePath(n), + sequenceNumber: e.highestListenSequenceNumber + }))(s)))); + })).next((() => PersistencePromise.waitFor(r))); + })); + } + bi(e, t) { + // Create the index. + e.createObjectStore(pe, { + keyPath: ye + }); + const n = t.store(pe), r = new __PRIVATE_MemoryCollectionParentIndex, addEntry = e => { + if (r.add(e)) { + const t = e.lastSegment(), r = e.popLast(); + return n.put({ + collectionId: t, + parent: __PRIVATE_encodeResourcePath(r) + }); + } + }; + // Helper to add an index entry iff we haven't already written it. + // Index existing remote documents. + return t.store(H).ee({ + X: !0 + }, ((e, t) => { + const n = new ResourcePath(e); + return addEntry(n.popLast()); + })).next((() => t.store(oe).ee({ + X: !0 + }, (([e, t, n], r) => { + const i = __PRIVATE_decodeResourcePath(t); + return addEntry(i.popLast()); + })))); + } + Di(e) { + const t = e.store(Ie); + return t.ee(((e, n) => { + const r = __PRIVATE_fromDbTarget(n), i = __PRIVATE_toDbTarget(this.serializer, r); + return t.put(i); + })); + } + Ci(e, t) { + const n = t.store(H), r = []; + return n.ee(((e, n) => { + const i = t.store(_e), s = function __PRIVATE_extractKey(e) { + return e.document ? new DocumentKey(ResourcePath.fromString(e.document.name).popFirst(5)) : e.noDocument ? DocumentKey.fromSegments(e.noDocument.path) : e.unknownDocument ? DocumentKey.fromSegments(e.unknownDocument.path) : fail(36783); + } + /** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ (n).path.toArray(), o = { + prefixPath: s.slice(0, s.length - 2), + collectionGroup: s[s.length - 2], + documentId: s[s.length - 1], + readTime: n.readTime || [ 0, 0 ], + unknownDocument: n.unknownDocument, + noDocument: n.noDocument, + document: n.document, + hasCommittedMutations: !!n.hasCommittedMutations + }; + r.push(i.put(o)); + })).next((() => PersistencePromise.waitFor(r))); + } + Fi(e, t) { + const n = t.store(te), r = __PRIVATE_newIndexedDbRemoteDocumentCache(this.serializer), i = new __PRIVATE_MemoryPersistence(__PRIVATE_MemoryEagerDelegate.mi, this.serializer.yt); + return n.J().next((e => { + const n = new Map; + return e.forEach((e => { + let t = n.get(e.userId) ?? __PRIVATE_documentKeySet(); + __PRIVATE_fromDbMutationBatch(this.serializer, e).keys().forEach((e => t = t.add(e))), + n.set(e.userId, t); + })), PersistencePromise.forEach(n, ((e, n) => { + const s = new User(n), o = __PRIVATE_IndexedDbDocumentOverlayCache.wt(this.serializer, s), _ = i.getIndexManager(s), a = __PRIVATE_IndexedDbMutationQueue.wt(s, this.serializer, _, i.referenceDelegate); + return new LocalDocumentsView(r, a, o, _).recalculateAndSaveOverlaysForDocumentKeys(new __PRIVATE_IndexedDbTransaction(t, __PRIVATE_ListenSequence.ce), e).next(); + })); + })); + } +} + +function __PRIVATE_createQueryCache(e) { + e.createObjectStore(Ae, { + keyPath: Re + }).createIndex(Ve, me, { + unique: !0 + }); + // NOTE: This is unique only because the TargetId is the suffix. + e.createObjectStore(Ie, { + keyPath: "targetId" + }).createIndex(Ee, de, { + unique: !0 + }), e.createObjectStore(ge); +} + +const Lt = "IndexedDbPersistence", kt = 18e5, qt = 5e3, Qt = "Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.", $t = "main"; + +/** + * Oldest acceptable age in milliseconds for client metadata before the client + * is considered inactive and its associated data is garbage collected. + */ +/** + * An IndexedDB-backed instance of Persistence. Data is stored persistently + * across sessions. + * + * On Web only, the Firestore SDKs support shared access to its persistence + * layer. This allows multiple browser tabs to read and write to IndexedDb and + * to synchronize state even without network connectivity. Shared access is + * currently optional and not enabled unless all clients invoke + * `enablePersistence()` with `{synchronizeTabs:true}`. + * + * In multi-tab mode, if multiple clients are active at the same time, the SDK + * will designate one client as the "primary client". An effort is made to pick + * a visible, network-connected and active client, and this client is + * responsible for letting other clients know about its presence. The primary + * client writes a unique client-generated identifier (the client ID) to + * IndexedDb’s "owner" store every 4 seconds. If the primary client fails to + * update this entry, another client can acquire the lease and take over as + * primary. + * + * Some persistence operations in the SDK are designated as primary-client only + * operations. This includes the acknowledgment of mutations and all updates of + * remote documents. The effects of these operations are written to persistence + * and then broadcast to other tabs via LocalStorage (see + * `WebStorageSharedClientState`), which then refresh their state from + * persistence. + * + * Similarly, the primary client listens to notifications sent by secondary + * clients to discover persistence changes written by secondary clients, such as + * the addition of new mutations and query targets. + * + * If multi-tab is not enabled and another tab already obtained the primary + * lease, IndexedDbPersistence enters a failed state and all subsequent + * operations will automatically fail. + * + * Additionally, there is an optimization so that when a tab is closed, the + * primary lease is released immediately (this is especially important to make + * sure that a refreshed tab is able to immediately re-acquire the primary + * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload + * since it is an asynchronous API. So in addition to attempting to give up the + * lease, the leaseholder writes its client ID to a "zombiedClient" entry in + * LocalStorage which acts as an indicator that another tab should go ahead and + * take the primary lease immediately regardless of the current lease timestamp. + * + * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no + * longer optional. + */ +class __PRIVATE_IndexedDbPersistence { + constructor( + /** + * Whether to synchronize the in-memory state of multiple tabs and share + * access to local persistence. + */ + e, t, n, r, i, s, o, _, a, + /** + * If set to true, forcefully obtains database access. Existing tabs will + * no longer be able to access IndexedDB. + */ + u, c = 18) { + if (this.allowTabSynchronization = e, this.persistenceKey = t, this.clientId = n, + this.Mi = i, this.window = s, this.document = o, this.xi = a, this.Oi = u, this.Ni = c, + this.ci = null, this.li = !1, this.isPrimary = !1, this.networkEnabled = !0, + /** Our window.unload handler, if registered. */ + this.Bi = null, this.inForeground = !1, + /** Our 'visibilitychange' listener if registered. */ + this.Li = null, + /** The client metadata refresh task. */ + this.ki = null, + /** The last time we garbage collected the client metadata object store. */ + this.qi = Number.NEGATIVE_INFINITY, + /** A listener to notify on primary state changes. */ + this.Qi = e => Promise.resolve(), !__PRIVATE_IndexedDbPersistence.v()) throw new FirestoreError(N.UNIMPLEMENTED, "This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled."); + this.referenceDelegate = new __PRIVATE_IndexedDbLruDelegateImpl(this, r), this.$i = t + $t, + this.serializer = new __PRIVATE_LocalSerializer(_), this.Ui = new __PRIVATE_SimpleDb(this.$i, this.Ni, new __PRIVATE_SchemaConverter(this.serializer)), + this.hi = new __PRIVATE_IndexedDbGlobalsCache, this.Pi = new __PRIVATE_IndexedDbTargetCache(this.referenceDelegate, this.serializer), + this.remoteDocumentCache = __PRIVATE_newIndexedDbRemoteDocumentCache(this.serializer), + this.Ii = new __PRIVATE_IndexedDbBundleCache, this.window && this.window.localStorage ? this.Ki = this.window.localStorage : (this.Ki = null, + !1 === u && __PRIVATE_logError(Lt, "LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page.")); + } + /** + * Attempt to start IndexedDb persistence. + * + * @returns Whether persistence was enabled. + */ start() { + // NOTE: This is expected to fail sometimes (in the case of another tab + // already having the persistence lock), so it's the first thing we should + // do. + return this.Wi().then((() => { + if (!this.isPrimary && !this.allowTabSynchronization) + // Fail `start()` if `synchronizeTabs` is disabled and we cannot + // obtain the primary lease. + throw new FirestoreError(N.FAILED_PRECONDITION, Qt); + return this.Gi(), this.zi(), this.ji(), this.runTransaction("getHighestListenSequenceNumber", "readonly", (e => this.Pi.getHighestSequenceNumber(e))); + })).then((e => { + this.ci = new __PRIVATE_ListenSequence(e, this.xi); + })).then((() => { + this.li = !0; + })).catch((e => (this.Ui && this.Ui.close(), Promise.reject(e)))); + } + /** + * Registers a listener that gets called when the primary state of the + * instance changes. Upon registering, this listener is invoked immediately + * with the current primary state. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ Ji(e) { + return this.Qi = async t => { + if (this.started) return e(t); + }, e(this.isPrimary); + } + /** + * Registers a listener that gets called when the database receives a + * version change event indicating that it has deleted. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ setDatabaseDeletedListener(e) { + this.Ui.$((async t => { + // Check if an attempt is made to delete IndexedDB. + null === t.newVersion && await e(); + })); + } + /** + * Adjusts the current network state in the client's metadata, potentially + * affecting the primary lease. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ setNetworkEnabled(e) { + this.networkEnabled !== e && (this.networkEnabled = e, + // Schedule a primary lease refresh for immediate execution. The eventual + // lease update will be propagated via `primaryStateListener`. + this.Mi.enqueueAndForget((async () => { + this.started && await this.Wi(); + }))); + } + /** + * Updates the client metadata in IndexedDb and attempts to either obtain or + * extend the primary lease for the local client. Asynchronously notifies the + * primary state listener if the client either newly obtained or released its + * primary lease. + */ Wi() { + return this.runTransaction("updateClientMetadataAndTryBecomePrimary", "readwrite", (e => __PRIVATE_clientMetadataStore(e).put({ + clientId: this.clientId, + updateTimeMs: Date.now(), + networkEnabled: this.networkEnabled, + inForeground: this.inForeground + }).next((() => { + if (this.isPrimary) return this.Hi(e).next((e => { + e || (this.isPrimary = !1, this.Mi.enqueueRetryable((() => this.Qi(!1)))); + })); + })).next((() => this.Yi(e))).next((t => this.isPrimary && !t ? this.Zi(e).next((() => !1)) : !!t && this.Xi(e).next((() => !0)))))).catch((e => { + if (__PRIVATE_isIndexedDbTransactionError(e)) + // Proceed with the existing state. Any subsequent access to + // IndexedDB will verify the lease. + return __PRIVATE_logDebug(Lt, "Failed to extend owner lease: ", e), this.isPrimary; + if (!this.allowTabSynchronization) throw e; + return __PRIVATE_logDebug(Lt, "Releasing owner lease after error during lease refresh", e), + /* isPrimary= */ !1; + })).then((e => { + this.isPrimary !== e && this.Mi.enqueueRetryable((() => this.Qi(e))), this.isPrimary = e; + })); + } + Hi(e) { + return __PRIVATE_primaryClientStore(e).get(Z).next((e => PersistencePromise.resolve(this.es(e)))); + } + ts(e) { + return __PRIVATE_clientMetadataStore(e).delete(this.clientId); + } + /** + * If the garbage collection threshold has passed, prunes the + * RemoteDocumentChanges and the ClientMetadata store based on the last update + * time of all clients. + */ async ns() { + if (this.isPrimary && !this.rs(this.qi, kt)) { + this.qi = Date.now(); + const e = await this.runTransaction("maybeGarbageCollectMultiClientState", "readwrite-primary", (e => { + const t = __PRIVATE_getStore(e, we); + return t.J().next((e => { + const n = this.ss(e, kt), r = e.filter((e => -1 === n.indexOf(e))); + // Delete metadata for clients that are no longer considered active. + return PersistencePromise.forEach(r, (e => t.delete(e.clientId))).next((() => r)); + })); + })).catch((() => [])); + // Delete potential leftover entries that may continue to mark the + // inactive clients as zombied in LocalStorage. + // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for + // the client atomically, but we can't. So we opt to delete the IndexedDb + // entries first to avoid potentially reviving a zombied client. + if (this.Ki) for (const t of e) this.Ki.removeItem(this._s(t.clientId)); + } + } + /** + * Schedules a recurring timer to update the client metadata and to either + * extend or acquire the primary lease if the client is eligible. + */ ji() { + this.ki = this.Mi.enqueueAfterDelay("client_metadata_refresh" /* TimerId.ClientMetadataRefresh */ , 4e3, (() => this.Wi().then((() => this.ns())).then((() => this.ji())))); + } + /** Checks whether `client` is the local client. */ es(e) { + return !!e && e.ownerId === this.clientId; + } + /** + * Evaluate the state of all active clients and determine whether the local + * client is or can act as the holder of the primary lease. Returns whether + * the client is eligible for the lease, but does not actually acquire it. + * May return 'false' even if there is no active leaseholder and another + * (foreground) client should become leaseholder instead. + */ Yi(e) { + if (this.Oi) return PersistencePromise.resolve(!0); + return __PRIVATE_primaryClientStore(e).get(Z).next((t => { + // A client is eligible for the primary lease if: + // - its network is enabled and the client's tab is in the foreground. + // - its network is enabled and no other client's tab is in the + // foreground. + // - every clients network is disabled and the client's tab is in the + // foreground. + // - every clients network is disabled and no other client's tab is in + // the foreground. + // - the `forceOwningTab` setting was passed in. + if (null !== t && this.rs(t.leaseTimestampMs, qt) && !this.us(t.ownerId)) { + if (this.es(t) && this.networkEnabled) return !0; + if (!this.es(t)) { + if (!t.allowTabSynchronization) + // Fail the `canActAsPrimary` check if the current leaseholder has + // not opted into multi-tab synchronization. If this happens at + // client startup, we reject the Promise returned by + // `enablePersistence()` and the user can continue to use Firestore + // with in-memory persistence. + // If this fails during a lease refresh, we will instead block the + // AsyncQueue from executing further operations. Note that this is + // acceptable since mixing & matching different `synchronizeTabs` + // settings is not supported. + // TODO(b/114226234): Remove this check when `synchronizeTabs` can + // no longer be turned off. + throw new FirestoreError(N.FAILED_PRECONDITION, Qt); + return !1; + } + } + return !(!this.networkEnabled || !this.inForeground) || __PRIVATE_clientMetadataStore(e).J().next((e => void 0 === this.ss(e, qt).find((e => { + if (this.clientId !== e.clientId) { + const t = !this.networkEnabled && e.networkEnabled, n = !this.inForeground && e.inForeground, r = this.networkEnabled === e.networkEnabled; + if (t || n && r) return !0; + } + return !1; + })))); + })).next((e => (this.isPrimary !== e && __PRIVATE_logDebug(Lt, `Client ${e ? "is" : "is not"} eligible for a primary lease.`), + e))); + } + async shutdown() { + // The shutdown() operations are idempotent and can be called even when + // start() aborted (e.g. because it couldn't acquire the persistence lease). + this.li = !1, this.cs(), this.ki && (this.ki.cancel(), this.ki = null), this.ls(), + this.hs(), + // Use `SimpleDb.runTransaction` directly to avoid failing if another tab + // has obtained the primary lease. + await this.Ui.runTransaction("shutdown", "readwrite", [ Y, we ], (e => { + const t = new __PRIVATE_IndexedDbTransaction(e, __PRIVATE_ListenSequence.ce); + return this.Zi(t).next((() => this.ts(t))); + })), this.Ui.close(), + // Remove the entry marking the client as zombied from LocalStorage since + // we successfully deleted its metadata from IndexedDb. + this.Ps(); + } + /** + * Returns clients that are not zombied and have an updateTime within the + * provided threshold. + */ ss(e, t) { + return e.filter((e => this.rs(e.updateTimeMs, t) && !this.us(e.clientId))); + } + /** + * Returns the IDs of the clients that are currently active. If multi-tab + * is not supported, returns an array that only contains the local client's + * ID. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ Ts() { + return this.runTransaction("getActiveClients", "readonly", (e => __PRIVATE_clientMetadataStore(e).J().next((e => this.ss(e, kt).map((e => e.clientId)))))); + } + get started() { + return this.li; + } + getGlobalsCache() { + return this.hi; + } + getMutationQueue(e, t) { + return __PRIVATE_IndexedDbMutationQueue.wt(e, this.serializer, t, this.referenceDelegate); + } + getTargetCache() { + return this.Pi; + } + getRemoteDocumentCache() { + return this.remoteDocumentCache; + } + getIndexManager(e) { + return new __PRIVATE_IndexedDbIndexManager(e, this.serializer.yt.databaseId); + } + getDocumentOverlayCache(e) { + return __PRIVATE_IndexedDbDocumentOverlayCache.wt(this.serializer, e); + } + getBundleCache() { + return this.Ii; + } + runTransaction(e, t, n) { + __PRIVATE_logDebug(Lt, "Starting transaction:", e); + const r = "readonly" === t ? "readonly" : "readwrite", i = + /** Returns the object stores for the provided schema. */ + function __PRIVATE_getObjectStores(e) { + return 18 === e ? st : 17 === e ? it : 16 === e ? rt : 15 === e ? nt : 14 === e ? tt : 13 === e ? et : 12 === e ? Xe : 11 === e ? Ze : void fail(60245); + }(this.Ni); + let s; + // Do all transactions as readwrite against all object stores, since we + // are the only reader/writer. + return this.Ui.runTransaction(e, r, i, (r => (s = new __PRIVATE_IndexedDbTransaction(r, this.ci ? this.ci.next() : __PRIVATE_ListenSequence.ce), + "readwrite-primary" === t ? this.Hi(s).next((e => !!e || this.Yi(s))).next((t => { + if (!t) throw __PRIVATE_logError(`Failed to obtain primary lease for action '${e}'.`), + this.isPrimary = !1, this.Mi.enqueueRetryable((() => this.Qi(!1))), new FirestoreError(N.FAILED_PRECONDITION, K); + return n(s); + })).next((e => this.Xi(s).next((() => e)))) : this.Is(s).next((() => n(s)))))).then((e => (s.raiseOnCommittedEvent(), + e))); + } + /** + * Verifies that the current tab is the primary leaseholder or alternatively + * that the leaseholder has opted into multi-tab synchronization. + */ + // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer + // be turned off. + Is(e) { + return __PRIVATE_primaryClientStore(e).get(Z).next((e => { + if (null !== e && this.rs(e.leaseTimestampMs, qt) && !this.us(e.ownerId) && !this.es(e) && !(this.Oi || this.allowTabSynchronization && e.allowTabSynchronization)) throw new FirestoreError(N.FAILED_PRECONDITION, Qt); + })); + } + /** + * Obtains or extends the new primary lease for the local client. This + * method does not verify that the client is eligible for this lease. + */ Xi(e) { + const t = { + ownerId: this.clientId, + allowTabSynchronization: this.allowTabSynchronization, + leaseTimestampMs: Date.now() + }; + return __PRIVATE_primaryClientStore(e).put(Z, t); + } + static v() { + return __PRIVATE_SimpleDb.v(); + } + /** Checks the primary lease and removes it if we are the current primary. */ Zi(e) { + const t = __PRIVATE_primaryClientStore(e); + return t.get(Z).next((e => this.es(e) ? (__PRIVATE_logDebug(Lt, "Releasing primary lease."), + t.delete(Z)) : PersistencePromise.resolve())); + } + /** Verifies that `updateTimeMs` is within `maxAgeMs`. */ rs(e, t) { + const n = Date.now(); + return !(e < n - t) && (!(e > n) || (__PRIVATE_logError(`Detected an update time that is in the future: ${e} > ${n}`), + !1)); + } + Gi() { + null !== this.document && "function" == typeof this.document.addEventListener && (this.Li = () => { + this.Mi.enqueueAndForget((() => (this.inForeground = "visible" === this.document.visibilityState, + this.Wi()))); + }, this.document.addEventListener("visibilitychange", this.Li), this.inForeground = "visible" === this.document.visibilityState); + } + ls() { + this.Li && (this.document.removeEventListener("visibilitychange", this.Li), this.Li = null); + } + /** + * Attaches a window.unload handler that will synchronously write our + * clientId to a "zombie client id" location in LocalStorage. This can be used + * by tabs trying to acquire the primary lease to determine that the lease + * is no longer valid even if the timestamp is recent. This is particularly + * important for the refresh case (so the tab correctly re-acquires the + * primary lease). LocalStorage is used for this rather than IndexedDb because + * it is a synchronous API and so can be used reliably from an unload + * handler. + */ zi() { + "function" == typeof this.window?.addEventListener && (this.Bi = () => { + // Note: In theory, this should be scheduled on the AsyncQueue since it + // accesses internal state. We execute this code directly during shutdown + // to make sure it gets a chance to run. + this.cs(); + const e = /(?:Version|Mobile)\/1[456]/; + isSafari() && (navigator.appVersion.match(e) || navigator.userAgent.match(e)) && + // On Safari 14, 15, and 16, we do not run any cleanup actions as it might + // trigger a bug that prevents Safari from re-opening IndexedDB during + // the next page load. + // See https://bugs.webkit.org/show_bug.cgi?id=226547 + this.Mi.enterRestrictedMode(/* purgeExistingTasks= */ !0), this.Mi.enqueueAndForget((() => this.shutdown())); + }, this.window.addEventListener("pagehide", this.Bi)); + } + hs() { + this.Bi && (this.window.removeEventListener("pagehide", this.Bi), this.Bi = null); + } + /** + * Returns whether a client is "zombied" based on its LocalStorage entry. + * Clients become zombied when their tab closes without running all of the + * cleanup logic in `shutdown()`. + */ us(e) { + try { + const t = null !== this.Ki?.getItem(this._s(e)); + return __PRIVATE_logDebug(Lt, `Client '${e}' ${t ? "is" : "is not"} zombied in LocalStorage`), + t; + } catch (e) { + // Gracefully handle if LocalStorage isn't working. + return __PRIVATE_logError(Lt, "Failed to get zombied client id.", e), !1; + } + } + /** + * Record client as zombied (a client that had its tab closed). Zombied + * clients are ignored during primary tab selection. + */ cs() { + if (this.Ki) try { + this.Ki.setItem(this._s(this.clientId), String(Date.now())); + } catch (e) { + // Gracefully handle if LocalStorage isn't available / working. + __PRIVATE_logError("Failed to set zombie client id.", e); + } + } + /** Removes the zombied client entry if it exists. */ Ps() { + if (this.Ki) try { + this.Ki.removeItem(this._s(this.clientId)); + } catch (e) { + // Ignore + } + } + _s(e) { + return `firestore_zombie_${this.persistenceKey}_${e}`; + } +} + +/** + * Helper to get a typed SimpleDbStore for the primary client object store. + */ function __PRIVATE_primaryClientStore(e) { + return __PRIVATE_getStore(e, Y); +} + +/** + * Helper to get a typed SimpleDbStore for the client metadata object store. + */ function __PRIVATE_clientMetadataStore(e) { + return __PRIVATE_getStore(e, we); +} + +/** + * Generates a string used as a prefix when storing data in IndexedDB and + * LocalStorage. + */ function __PRIVATE_indexedDbStoragePrefix(e, t) { + // Use two different prefix formats: + // * firestore / persistenceKey / projectID . databaseID / ... + // * firestore / persistenceKey / projectID / ... + // projectIDs are DNS-compatible names and cannot contain dots + // so there's no danger of collisions. + let n = e.projectId; + return e.isDefaultDatabase || (n += "." + e.database), "firestore/" + t + "/" + n + "/"; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A set of changes to what documents are currently in view and out of view for + * a given query. These changes are sent to the LocalStore by the View (via + * the SyncEngine) and are used to pin / unpin documents as appropriate. + */ +class __PRIVATE_LocalViewChanges { + constructor(e, t, n, r) { + this.targetId = e, this.fromCache = t, this.Es = n, this.ds = r; + } + static As(e, t) { + let n = __PRIVATE_documentKeySet(), r = __PRIVATE_documentKeySet(); + for (const e of t.docChanges) switch (e.type) { + case 0 /* ChangeType.Added */ : + n = n.add(e.doc.key); + break; + + case 1 /* ChangeType.Removed */ : + r = r.add(e.doc.key); + // do nothing + } + return new __PRIVATE_LocalViewChanges(e, t.fromCache, n, r); + } +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A tracker to keep a record of important details during database local query + * execution. + */ class QueryContext { + constructor() { + /** + * Counts the number of documents passed through during local query execution. + */ + this._documentReadCount = 0; + } + get documentReadCount() { + return this._documentReadCount; + } + incrementDocumentReadCount(e) { + this._documentReadCount += e; + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The Firestore query engine. + * + * Firestore queries can be executed in three modes. The Query Engine determines + * what mode to use based on what data is persisted. The mode only determines + * the runtime complexity of the query - the result set is equivalent across all + * implementations. + * + * The Query engine will use indexed-based execution if a user has configured + * any index that can be used to execute query (via `setIndexConfiguration()`). + * Otherwise, the engine will try to optimize the query by re-using a previously + * persisted query result. If that is not possible, the query will be executed + * via a full collection scan. + * + * Index-based execution is the default when available. The query engine + * supports partial indexed execution and merges the result from the index + * lookup with documents that have not yet been indexed. The index evaluation + * matches the backend's format and as such, the SDK can use indexing for all + * queries that the backend supports. + * + * If no index exists, the query engine tries to take advantage of the target + * document mapping in the TargetCache. These mappings exists for all queries + * that have been synced with the backend at least once and allow the query + * engine to only read documents that previously matched a query plus any + * documents that were edited after the query was last listened to. + * + * There are some cases when this optimization is not guaranteed to produce + * the same results as full collection scans. In these cases, query + * processing falls back to full scans. These cases are: + * + * - Limit queries where a document that matched the query previously no longer + * matches the query. + * + * - Limit queries where a document edit may cause the document to sort below + * another document that is in the local cache. + * + * - Queries that have never been CURRENT or free of limbo documents. + */ +class __PRIVATE_QueryEngine { + constructor() { + this.Rs = !1, this.Vs = !1, + /** + * SDK only decides whether it should create index when collection size is + * larger than this. + */ + this.fs = 100, this.gs = + /** + * This cost represents the evaluation result of + * (([index, docKey] + [docKey, docContent]) per document in the result set) + * / ([docKey, docContent] per documents in full collection scan) coming from + * experiment [enter PR experiment URL here]. + */ + function __PRIVATE_getDefaultRelativeIndexReadCostPerDocument() { + // These values were derived from an experiment where several members of the + // Firestore SDK team ran a performance test in various environments. + // Googlers can see b/299284287 for details. + return isSafari() ? 8 : __PRIVATE_getAndroidVersion(getUA()) > 0 ? 6 : 4; + }(); + } + /** Sets the document view to query against. */ initialize(e, t) { + this.ps = e, this.indexManager = t, this.Rs = !0; + } + /** Returns all local documents matching the specified query. */ getDocumentsMatchingQuery(e, t, n, r) { + // Stores the result from executing the query; using this object is more + // convenient than passing the result between steps of the persistence + // transaction and improves readability comparatively. + const i = { + result: null + }; + return this.ys(e, t).next((e => { + i.result = e; + })).next((() => { + if (!i.result) return this.ws(e, t, r, n).next((e => { + i.result = e; + })); + })).next((() => { + if (i.result) return; + const n = new QueryContext; + return this.Ss(e, t, n).next((r => { + if (i.result = r, this.Vs) return this.bs(e, t, n, r.size); + })); + })).next((() => i.result)); + } + bs(e, t, n, r) { + return n.documentReadCount < this.fs ? (__PRIVATE_getLogLevel() <= LogLevel.DEBUG && __PRIVATE_logDebug("QueryEngine", "SDK will not create cache indexes for query:", __PRIVATE_stringifyQuery(t), "since it only creates cache indexes for collection contains", "more than or equal to", this.fs, "documents"), + PersistencePromise.resolve()) : (__PRIVATE_getLogLevel() <= LogLevel.DEBUG && __PRIVATE_logDebug("QueryEngine", "Query:", __PRIVATE_stringifyQuery(t), "scans", n.documentReadCount, "local documents and returns", r, "documents as results."), + n.documentReadCount > this.gs * r ? (__PRIVATE_getLogLevel() <= LogLevel.DEBUG && __PRIVATE_logDebug("QueryEngine", "The SDK decides to create cache indexes for query:", __PRIVATE_stringifyQuery(t), "as using cache indexes may help improve performance."), + this.indexManager.createTargetIndexes(e, __PRIVATE_queryToTarget(t))) : PersistencePromise.resolve()); + } + /** + * Performs an indexed query that evaluates the query based on a collection's + * persisted index values. Returns `null` if an index is not available. + */ ys(e, t) { + if (__PRIVATE_queryMatchesAllDocuments(t)) + // Queries that match all documents don't benefit from using + // key-based lookups. It is more efficient to scan all documents in a + // collection, rather than to perform individual lookups. + return PersistencePromise.resolve(null); + let n = __PRIVATE_queryToTarget(t); + return this.indexManager.getIndexType(e, n).next((r => 0 /* IndexType.NONE */ === r ? null : (null !== t.limit && 1 /* IndexType.PARTIAL */ === r && ( + // We cannot apply a limit for targets that are served using a partial + // index. If a partial index will be used to serve the target, the + // query may return a superset of documents that match the target + // (e.g. if the index doesn't include all the target's filters), or + // may return the correct set of documents in the wrong order (e.g. if + // the index doesn't include a segment for one of the orderBys). + // Therefore, a limit should not be applied in such cases. + t = __PRIVATE_queryWithLimit(t, null, "F" /* LimitType.First */), n = __PRIVATE_queryToTarget(t)), + this.indexManager.getDocumentsMatchingTarget(e, n).next((r => { + const i = __PRIVATE_documentKeySet(...r); + return this.ps.getDocuments(e, i).next((r => this.indexManager.getMinOffset(e, n).next((n => { + const s = this.Ds(t, r); + return this.Cs(t, s, i, n.readTime) ? this.ys(e, __PRIVATE_queryWithLimit(t, null, "F" /* LimitType.First */)) : this.vs(e, s, t, n); + })))); + }))))); + } + /** + * Performs a query based on the target's persisted query mapping. Returns + * `null` if the mapping is not available or cannot be used. + */ ws(e, t, n, r) { + return __PRIVATE_queryMatchesAllDocuments(t) || r.isEqual(SnapshotVersion.min()) ? PersistencePromise.resolve(null) : this.ps.getDocuments(e, n).next((i => { + const s = this.Ds(t, i); + return this.Cs(t, s, n, r) ? PersistencePromise.resolve(null) : (__PRIVATE_getLogLevel() <= LogLevel.DEBUG && __PRIVATE_logDebug("QueryEngine", "Re-using previous result from %s to execute query: %s", r.toString(), __PRIVATE_stringifyQuery(t)), + this.vs(e, s, t, __PRIVATE_newIndexOffsetSuccessorFromReadTime(r, U)).next((e => e))); + })); + // Queries that have never seen a snapshot without limbo free documents + // should also be run as a full collection scan. + } + /** Applies the query filter and sorting to the provided documents. */ Ds(e, t) { + // Sort the documents and re-apply the query filter since previously + // matching documents do not necessarily still match the query. + let n = new SortedSet(__PRIVATE_newQueryComparator(e)); + return t.forEach(((t, r) => { + __PRIVATE_queryMatches(e, r) && (n = n.add(r)); + })), n; + } + /** + * Determines if a limit query needs to be refilled from cache, making it + * ineligible for index-free execution. + * + * @param query - The query. + * @param sortedPreviousResults - The documents that matched the query when it + * was last synchronized, sorted by the query's comparator. + * @param remoteKeys - The document keys that matched the query at the last + * snapshot. + * @param limboFreeSnapshotVersion - The version of the snapshot when the + * query was last synchronized. + */ Cs(e, t, n, r) { + if (null === e.limit) + // Queries without limits do not need to be refilled. + return !1; + if (n.size !== t.size) + // The query needs to be refilled if a previously matching document no + // longer matches. + return !0; + // Limit queries are not eligible for index-free query execution if there is + // a potential that an older document from cache now sorts before a document + // that was previously part of the limit. This, however, can only happen if + // the document at the edge of the limit goes out of limit. + // If a document that is not the limit boundary sorts differently, + // the boundary of the limit itself did not change and documents from cache + // will continue to be "rejected" by this boundary. Therefore, we can ignore + // any modifications that don't affect the last document. + const i = "F" /* LimitType.First */ === e.limitType ? t.last() : t.first(); + return !!i && (i.hasPendingWrites || i.version.compareTo(r) > 0); + } + Ss(e, t, n) { + return __PRIVATE_getLogLevel() <= LogLevel.DEBUG && __PRIVATE_logDebug("QueryEngine", "Using full collection scan to execute query:", __PRIVATE_stringifyQuery(t)), + this.ps.getDocumentsMatchingQuery(e, t, IndexOffset.min(), n); + } + /** + * Combines the results from an indexed execution with the remaining documents + * that have not yet been indexed. + */ vs(e, t, n, r) { + // Retrieve all results for documents that were updated since the offset. + return this.ps.getDocumentsMatchingQuery(e, n, r).next((e => ( + // Merge with existing results + t.forEach((t => { + e = e.insert(t.key, t); + })), e))); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const Ut = "LocalStore", Kt = 3e8; + +/** + * The maximum time to leave a resume token buffered without writing it out. + * This value is arbitrary: it's long enough to avoid several writes + * (possibly indefinitely if updates come more frequently than this) but + * short enough that restarting after crashing will still have a pretty + * recent resume token. + */ +/** + * Implements `LocalStore` interface. + * + * Note: some field defined in this class might have public access level, but + * the class is not exported so they are only accessible from this module. + * This is useful to implement optional features (like bundles) in free + * functions, such that they are tree-shakeable. + */ +class __PRIVATE_LocalStoreImpl { + constructor( + /** Manages our in-memory or durable persistence. */ + e, t, n, r) { + this.persistence = e, this.Fs = t, this.serializer = r, + /** + * Maps a targetID to data about its target. + * + * PORTING NOTE: We are using an immutable data structure on Web to make re-runs + * of `applyRemoteEvent()` idempotent. + */ + this.Ms = new SortedMap(__PRIVATE_primitiveComparator), + /** Maps a target to its targetID. */ + // TODO(wuandy): Evaluate if TargetId can be part of Target. + this.xs = new ObjectMap((e => __PRIVATE_canonifyTarget(e)), __PRIVATE_targetEquals), + /** + * A per collection group index of the last read time processed by + * `getNewDocumentChanges()`. + * + * PORTING NOTE: This is only used for multi-tab synchronization. + */ + this.Os = new Map, this.Ns = e.getRemoteDocumentCache(), this.Pi = e.getTargetCache(), + this.Ii = e.getBundleCache(), this.Bs(n); + } + Bs(e) { + // TODO(indexing): Add spec tests that test these components change after a + // user change + this.documentOverlayCache = this.persistence.getDocumentOverlayCache(e), this.indexManager = this.persistence.getIndexManager(e), + this.mutationQueue = this.persistence.getMutationQueue(e, this.indexManager), this.localDocuments = new LocalDocumentsView(this.Ns, this.mutationQueue, this.documentOverlayCache, this.indexManager), + this.Ns.setIndexManager(this.indexManager), this.Fs.initialize(this.localDocuments, this.indexManager); + } + collectGarbage(e) { + return this.persistence.runTransaction("Collect garbage", "readwrite-primary", (t => e.collect(t, this.Ms))); + } +} + +function __PRIVATE_newLocalStore( +/** Manages our in-memory or durable persistence. */ +e, t, n, r) { + return new __PRIVATE_LocalStoreImpl(e, t, n, r); +} + +/** + * Tells the LocalStore that the currently authenticated user has changed. + * + * In response the local store switches the mutation queue to the new user and + * returns any resulting document changes. + */ +// PORTING NOTE: Android and iOS only return the documents affected by the +// change. +async function __PRIVATE_localStoreHandleUserChange(e, t) { + const n = __PRIVATE_debugCast(e); + return await n.persistence.runTransaction("Handle user change", "readonly", (e => { + // Swap out the mutation queue, grabbing the pending mutation batches + // before and after. + let r; + return n.mutationQueue.getAllMutationBatches(e).next((i => (r = i, n.Bs(t), n.mutationQueue.getAllMutationBatches(e)))).next((t => { + const i = [], s = []; + // Union the old/new changed keys. + let o = __PRIVATE_documentKeySet(); + for (const e of r) { + i.push(e.batchId); + for (const t of e.mutations) o = o.add(t.key); + } + for (const e of t) { + s.push(e.batchId); + for (const t of e.mutations) o = o.add(t.key); + } + // Return the set of all (potentially) changed documents and the list + // of mutation batch IDs that were affected by change. + return n.localDocuments.getDocuments(e, o).next((e => ({ + Ls: e, + removedBatchIds: i, + addedBatchIds: s + }))); + })); + })); +} + +/* Accepts locally generated Mutations and commit them to storage. */ +/** + * Acknowledges the given batch. + * + * On the happy path when a batch is acknowledged, the local store will + * + * + remove the batch from the mutation queue; + * + apply the changes to the remote document cache; + * + recalculate the latency compensated view implied by those changes (there + * may be mutations in the queue that affect the documents but haven't been + * acknowledged yet); and + * + give the changed documents back the sync engine + * + * @returns The resulting (modified) documents. + */ +function __PRIVATE_localStoreAcknowledgeBatch(e, t) { + const n = __PRIVATE_debugCast(e); + return n.persistence.runTransaction("Acknowledge batch", "readwrite-primary", (e => { + const r = t.batch.keys(), i = n.Ns.newChangeBuffer({ + trackRemovals: !0 + }); + return function __PRIVATE_applyWriteToRemoteDocuments(e, t, n, r) { + const i = n.batch, s = i.keys(); + let o = PersistencePromise.resolve(); + return s.forEach((e => { + o = o.next((() => r.getEntry(t, e))).next((t => { + const s = n.docVersions.get(e); + __PRIVATE_hardAssert(null !== s, 48541), t.version.compareTo(s) < 0 && (i.applyToRemoteDocument(t, n), + t.isValidDocument() && ( + // We use the commitVersion as the readTime rather than the + // document's updateTime since the updateTime is not advanced + // for updates that do not modify the underlying document. + t.setReadTime(n.commitVersion), r.addEntry(t))); + })); + })), o.next((() => e.mutationQueue.removeMutationBatch(t, i))); + } + /** Returns the local view of the documents affected by a mutation batch. */ + // PORTING NOTE: Multi-Tab only. + (n, e, t, i).next((() => i.apply(e))).next((() => n.mutationQueue.performConsistencyCheck(e))).next((() => n.documentOverlayCache.removeOverlaysForBatchId(e, r, t.batch.batchId))).next((() => n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e, function __PRIVATE_getKeysWithTransformResults(e) { + let t = __PRIVATE_documentKeySet(); + for (let n = 0; n < e.mutationResults.length; ++n) { + e.mutationResults[n].transformResults.length > 0 && (t = t.add(e.batch.mutations[n].key)); + } + return t; + } + /** + * Removes mutations from the MutationQueue for the specified batch; + * LocalDocuments will be recalculated. + * + * @returns The resulting modified documents. + */ (t)))).next((() => n.localDocuments.getDocuments(e, r))); + })); +} + +/** + * Returns the last consistent snapshot processed (used by the RemoteStore to + * determine whether to buffer incoming snapshots from the backend). + */ +function __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e) { + const t = __PRIVATE_debugCast(e); + return t.persistence.runTransaction("Get last remote snapshot version", "readonly", (e => t.Pi.getLastRemoteSnapshotVersion(e))); +} + +/** + * Updates the "ground-state" (remote) documents. We assume that the remote + * event reflects any write batches that have been acknowledged or rejected + * (i.e. we do not re-apply local mutations to updates from this event). + * + * LocalDocuments are re-calculated if there are remaining mutations in the + * queue. + */ function __PRIVATE_localStoreApplyRemoteEventToLocalCache(e, t) { + const n = __PRIVATE_debugCast(e), r = t.snapshotVersion; + let i = n.Ms; + return n.persistence.runTransaction("Apply remote event", "readwrite-primary", (e => { + const s = n.Ns.newChangeBuffer({ + trackRemovals: !0 + }); + // Reset newTargetDataByTargetMap in case this transaction gets re-run. + i = n.Ms; + const o = []; + t.targetChanges.forEach(((s, _) => { + const a = i.get(_); + if (!a) return; + // Only update the remote keys if the target is still active. This + // ensures that we can persist the updated target data along with + // the updated assignment. + o.push(n.Pi.removeMatchingKeys(e, s.removedDocuments, _).next((() => n.Pi.addMatchingKeys(e, s.addedDocuments, _)))); + let u = a.withSequenceNumber(e.currentSequenceNumber); + null !== t.targetMismatches.get(_) ? u = u.withResumeToken(ByteString.EMPTY_BYTE_STRING, SnapshotVersion.min()).withLastLimboFreeSnapshotVersion(SnapshotVersion.min()) : s.resumeToken.approximateByteSize() > 0 && (u = u.withResumeToken(s.resumeToken, r)), + i = i.insert(_, u), + // Update the target data if there are target changes (or if + // sufficient time has passed since the last update). + /** + * Returns true if the newTargetData should be persisted during an update of + * an active target. TargetData should always be persisted when a target is + * being released and should not call this function. + * + * While the target is active, TargetData updates can be omitted when nothing + * about the target has changed except metadata like the resume token or + * snapshot version. Occasionally it's worth the extra write to prevent these + * values from getting too stale after a crash, but this doesn't have to be + * too frequent. + */ + function __PRIVATE_shouldPersistTargetData(e, t, n) { + // Always persist target data if we don't already have a resume token. + if (0 === e.resumeToken.approximateByteSize()) return !0; + // Don't allow resume token changes to be buffered indefinitely. This + // allows us to be reasonably up-to-date after a crash and avoids needing + // to loop over all active queries on shutdown. Especially in the browser + // we may not get time to do anything interesting while the current tab is + // closing. + const r = t.snapshotVersion.toMicroseconds() - e.snapshotVersion.toMicroseconds(); + if (r >= Kt) return !0; + // Otherwise if the only thing that has changed about a target is its resume + // token it's not worth persisting. Note that the RemoteStore keeps an + // in-memory view of the currently active targets which includes the current + // resume token, so stream failure or user changes will still use an + // up-to-date resume token regardless of what we do here. + const i = n.addedDocuments.size + n.modifiedDocuments.size + n.removedDocuments.size; + return i > 0; + } + /** + * Notifies local store of the changed views to locally pin documents. + */ (a, u, s) && o.push(n.Pi.updateTargetData(e, u)); + })); + let _ = __PRIVATE_mutableDocumentMap(), a = __PRIVATE_documentKeySet(); + // HACK: The only reason we allow a null snapshot version is so that we + // can synthesize remote events when we get permission denied errors while + // trying to resolve the state of a locally cached document that is in + // limbo. + if (t.documentUpdates.forEach((r => { + t.resolvedLimboDocuments.has(r) && o.push(n.persistence.referenceDelegate.updateLimboDocument(e, r)); + })), + // Each loop iteration only affects its "own" doc, so it's safe to get all + // the remote documents in advance in a single call. + o.push(__PRIVATE_populateDocumentChangeBuffer(e, s, t.documentUpdates).next((e => { + _ = e.ks, a = e.qs; + }))), !r.isEqual(SnapshotVersion.min())) { + const t = n.Pi.getLastRemoteSnapshotVersion(e).next((t => n.Pi.setTargetsMetadata(e, e.currentSequenceNumber, r))); + o.push(t); + } + return PersistencePromise.waitFor(o).next((() => s.apply(e))).next((() => n.localDocuments.getLocalViewOfDocuments(e, _, a))).next((() => _)); + })).then((e => (n.Ms = i, e))); +} + +/** + * Populates document change buffer with documents from backend or a bundle. + * Returns the document changes resulting from applying those documents, and + * also a set of documents whose existence state are changed as a result. + * + * @param txn - Transaction to use to read existing documents from storage. + * @param documentBuffer - Document buffer to collect the resulted changes to be + * applied to storage. + * @param documents - Documents to be applied. + */ function __PRIVATE_populateDocumentChangeBuffer(e, t, n) { + let r = __PRIVATE_documentKeySet(), i = __PRIVATE_documentKeySet(); + return n.forEach((e => r = r.add(e))), t.getEntries(e, r).next((e => { + let r = __PRIVATE_mutableDocumentMap(); + return n.forEach(((n, s) => { + const o = e.get(n); + // Check if see if there is a existence state change for this document. + s.isFoundDocument() !== o.isFoundDocument() && (i = i.add(n)), + // Note: The order of the steps below is important, since we want + // to ensure that rejected limbo resolutions (which fabricate + // NoDocuments with SnapshotVersion.min()) never add documents to + // cache. + s.isNoDocument() && s.version.isEqual(SnapshotVersion.min()) ? ( + // NoDocuments with SnapshotVersion.min() are used in manufactured + // events. We remove these documents from cache since we lost + // access. + t.removeEntry(n, s.readTime), r = r.insert(n, s)) : !o.isValidDocument() || s.version.compareTo(o.version) > 0 || 0 === s.version.compareTo(o.version) && o.hasPendingWrites ? (t.addEntry(s), + r = r.insert(n, s)) : __PRIVATE_logDebug(Ut, "Ignoring outdated watch update for ", n, ". Current version:", o.version, " Watch version:", s.version); + })), { + ks: r, + qs: i + }; + })); +} + +/** + * Gets the mutation batch after the passed in batchId in the mutation queue + * or null if empty. + * @param afterBatchId - If provided, the batch to search after. + * @returns The next mutation or null if there wasn't one. + */ +function __PRIVATE_localStoreGetNextMutationBatch(e, t) { + const n = __PRIVATE_debugCast(e); + return n.persistence.runTransaction("Get next mutation batch", "readonly", (e => (void 0 === t && (t = j), + n.mutationQueue.getNextMutationBatchAfterBatchId(e, t)))); +} + +/** + * Reads the current value of a Document with a given key or null if not + * found - used for testing. + */ +/** + * Assigns the given target an internal ID so that its results can be pinned so + * they don't get GC'd. A target must be allocated in the local store before + * the store can be used to manage its view. + * + * Allocating an already allocated `Target` will return the existing `TargetData` + * for that `Target`. + */ +function __PRIVATE_localStoreAllocateTarget(e, t) { + const n = __PRIVATE_debugCast(e); + return n.persistence.runTransaction("Allocate target", "readwrite", (e => { + let r; + return n.Pi.getTargetData(e, t).next((i => i ? ( + // This target has been listened to previously, so reuse the + // previous targetID. + // TODO(mcg): freshen last accessed date? + r = i, PersistencePromise.resolve(r)) : n.Pi.allocateTargetId(e).next((i => (r = new TargetData(t, i, "TargetPurposeListen" /* TargetPurpose.Listen */ , e.currentSequenceNumber), + n.Pi.addTargetData(e, r).next((() => r))))))); + })).then((e => { + // If Multi-Tab is enabled, the existing target data may be newer than + // the in-memory data + const r = n.Ms.get(e.targetId); + return (null === r || e.snapshotVersion.compareTo(r.snapshotVersion) > 0) && (n.Ms = n.Ms.insert(e.targetId, e), + n.xs.set(t, e.targetId)), e; + })); +} + +/** + * Returns the TargetData as seen by the LocalStore, including updates that may + * have not yet been persisted to the TargetCache. + */ +// Visible for testing. +/** + * Unpins all the documents associated with the given target. If + * `keepPersistedTargetData` is set to false and Eager GC enabled, the method + * directly removes the associated target data from the target cache. + * + * Releasing a non-existing `Target` is a no-op. + */ +// PORTING NOTE: `keepPersistedTargetData` is multi-tab only. +async function __PRIVATE_localStoreReleaseTarget(e, t, n) { + const r = __PRIVATE_debugCast(e), i = r.Ms.get(t), s = n ? "readwrite" : "readwrite-primary"; + try { + n || await r.persistence.runTransaction("Release target", s, (e => r.persistence.referenceDelegate.removeTarget(e, i))); + } catch (e) { + if (!__PRIVATE_isIndexedDbTransactionError(e)) throw e; + // All `releaseTarget` does is record the final metadata state for the + // target, but we've been recording this periodically during target + // activity. If we lose this write this could cause a very slight + // difference in the order of target deletion during GC, but we + // don't define exact LRU semantics so this is acceptable. + __PRIVATE_logDebug(Ut, `Failed to update sequence numbers for target ${t}: ${e}`); + } + r.Ms = r.Ms.remove(t), r.xs.delete(i.target); +} + +/** + * Runs the specified query against the local store and returns the results, + * potentially taking advantage of query data from previous executions (such + * as the set of remote keys). + * + * @param usePreviousResults - Whether results from previous executions can + * be used to optimize this query execution. + */ function __PRIVATE_localStoreExecuteQuery(e, t, n) { + const r = __PRIVATE_debugCast(e); + let i = SnapshotVersion.min(), s = __PRIVATE_documentKeySet(); + return r.persistence.runTransaction("Execute query", "readwrite", (// Use readwrite instead of readonly so indexes can be created + // Use readwrite instead of readonly so indexes can be created + e => function __PRIVATE_localStoreGetTargetData(e, t, n) { + const r = __PRIVATE_debugCast(e), i = r.xs.get(n); + return void 0 !== i ? PersistencePromise.resolve(r.Ms.get(i)) : r.Pi.getTargetData(t, n); + }(r, e, __PRIVATE_queryToTarget(t)).next((t => { + if (t) return i = t.lastLimboFreeSnapshotVersion, r.Pi.getMatchingKeysForTargetId(e, t.targetId).next((e => { + s = e; + })); + })).next((() => r.Fs.getDocumentsMatchingQuery(e, t, n ? i : SnapshotVersion.min(), n ? s : __PRIVATE_documentKeySet()))).next((e => (__PRIVATE_setMaxReadTime(r, __PRIVATE_queryCollectionGroup(t), e), + { + documents: e, + Qs: s + }))))); +} + +// PORTING NOTE: Multi-Tab only. +function __PRIVATE_localStoreGetCachedTarget(e, t) { + const n = __PRIVATE_debugCast(e), r = __PRIVATE_debugCast(n.Pi), i = n.Ms.get(t); + return i ? Promise.resolve(i.target) : n.persistence.runTransaction("Get target data", "readonly", (e => r.At(e, t).next((e => e ? e.target : null)))); +} + +/** + * Returns the set of documents that have been updated since the last call. + * If this is the first call, returns the set of changes since client + * initialization. Further invocations will return document that have changed + * since the prior call. + */ +// PORTING NOTE: Multi-Tab only. +function __PRIVATE_localStoreGetNewDocumentChanges(e, t) { + const n = __PRIVATE_debugCast(e), r = n.Os.get(t) || SnapshotVersion.min(); + // Get the current maximum read time for the collection. This should always + // exist, but to reduce the chance for regressions we default to + // SnapshotVersion.Min() + // TODO(indexing): Consider removing the default value. + return n.persistence.runTransaction("Get new document changes", "readonly", (e => n.Ns.getAllFromCollectionGroup(e, t, __PRIVATE_newIndexOffsetSuccessorFromReadTime(r, U), + /* limit= */ Number.MAX_SAFE_INTEGER))).then((e => (__PRIVATE_setMaxReadTime(n, t, e), + e))); +} + +/** Sets the collection group's maximum read time from the given documents. */ +// PORTING NOTE: Multi-Tab only. +function __PRIVATE_setMaxReadTime(e, t, n) { + let r = e.Os.get(t) || SnapshotVersion.min(); + n.forEach(((e, t) => { + t.readTime.compareTo(r) > 0 && (r = t.readTime); + })), e.Os.set(t, r); +} + +/** + * Creates a new target using the given bundle name, which will be used to + * hold the keys of all documents from the bundle in query-document mappings. + * This ensures that the loaded documents do not get garbage collected + * right away. + */ +/** + * Applies the documents from a bundle to the "ground-state" (remote) + * documents. + * + * LocalDocuments are re-calculated if there are remaining mutations in the + * queue. + */ +async function __PRIVATE_localStoreApplyBundledDocuments(e, t, n, r) { + const i = __PRIVATE_debugCast(e); + let s = __PRIVATE_documentKeySet(), o = __PRIVATE_mutableDocumentMap(); + for (const e of n) { + const n = t.$s(e.metadata.name); + e.document && (s = s.add(n)); + const r = t.Us(e); + r.setReadTime(t.Ks(e.metadata.readTime)), o = o.insert(n, r); + } + const _ = i.Ns.newChangeBuffer({ + trackRemovals: !0 + }), a = await __PRIVATE_localStoreAllocateTarget(i, function __PRIVATE_umbrellaTarget(e) { + // It is OK that the path used for the query is not valid, because this will + // not be read and queried. + return __PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(ResourcePath.fromString(`__bundle__/docs/${e}`))); + }(r)); + // Allocates a target to hold all document keys from the bundle, such that + // they will not get garbage collected right away. + return i.persistence.runTransaction("Apply bundle documents", "readwrite", (e => __PRIVATE_populateDocumentChangeBuffer(e, _, o).next((t => (_.apply(e), + t))).next((t => i.Pi.removeMatchingKeysForTargetId(e, a.targetId).next((() => i.Pi.addMatchingKeys(e, s, a.targetId))).next((() => i.localDocuments.getLocalViewOfDocuments(e, t.ks, t.qs))).next((() => t.ks)))))); +} + +/** + * Returns a promise of a boolean to indicate if the given bundle has already + * been loaded and the create time is newer than the current loading bundle. + */ +/** + * Saves the given `NamedQuery` to local persistence. + */ +async function __PRIVATE_localStoreSaveNamedQuery(e, t, n = __PRIVATE_documentKeySet()) { + // Allocate a target for the named query such that it can be resumed + // from associated read time if users use it to listen. + // NOTE: this also means if no corresponding target exists, the new target + // will remain active and will not get collected, unless users happen to + // unlisten the query somehow. + const r = await __PRIVATE_localStoreAllocateTarget(e, __PRIVATE_queryToTarget(__PRIVATE_fromBundledQuery(t.bundledQuery))), i = __PRIVATE_debugCast(e); + return i.persistence.runTransaction("Save named query", "readwrite", (e => { + const s = __PRIVATE_fromVersion(t.readTime); + // Simply save the query itself if it is older than what the SDK already + // has. + if (r.snapshotVersion.compareTo(s) >= 0) return i.Ii.saveNamedQuery(e, t); + // Update existing target data because the query from the bundle is newer. + const o = r.withResumeToken(ByteString.EMPTY_BYTE_STRING, s); + return i.Ms = i.Ms.insert(o.targetId, o), i.Pi.updateTargetData(e, o).next((() => i.Pi.removeMatchingKeysForTargetId(e, r.targetId))).next((() => i.Pi.addMatchingKeys(e, n, r.targetId))).next((() => i.Ii.saveNamedQuery(e, t))); + })); +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// The format of the LocalStorage key that stores the client state is: +// firestore_clients__ +const Wt = "firestore_clients"; + +/** Assembles the key for a client state in WebStorage */ function createWebStorageClientStateKey(e, t) { + return `${Wt}_${e}_${t}`; +} + +// The format of the WebStorage key that stores the mutation state is: +// firestore_mutations__ +// (for unauthenticated users) +// or: firestore_mutations___ + +// 'user_uid' is last to avoid needing to escape '_' characters that it might +// contain. +const Gt = "firestore_mutations"; + +/** Assembles the key for a mutation batch in WebStorage */ function createWebStorageMutationBatchKey(e, t, n) { + let r = `${Gt}_${e}_${n}`; + return t.isAuthenticated() && (r += `_${t.uid}`), r; +} + +// The format of the WebStorage key that stores a query target's metadata is: +// firestore_targets__ +const zt = "firestore_targets"; + +/** Assembles the key for a query state in WebStorage */ function createWebStorageQueryTargetMetadataKey(e, t) { + return `${zt}_${e}_${t}`; +} + +// The WebStorage prefix that stores the primary tab's online state. The +// format of the key is: +// firestore_online_state_ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const jt = "SharedClientState"; + +/** + * Holds the state of a mutation batch, including its user ID, batch ID and + * whether the batch is 'pending', 'acknowledged' or 'rejected'. + */ +// Visible for testing +class __PRIVATE_MutationMetadata { + constructor(e, t, n, r) { + this.user = e, this.batchId = t, this.state = n, this.error = r; + } + /** + * Parses a MutationMetadata from its JSON representation in WebStorage. + * Logs a warning and returns null if the format of the data is not valid. + */ static Ws(e, t, n) { + const r = JSON.parse(n); + let i, s = "object" == typeof r && -1 !== [ "pending", "acknowledged", "rejected" ].indexOf(r.state) && (void 0 === r.error || "object" == typeof r.error); + return s && r.error && (s = "string" == typeof r.error.message && "string" == typeof r.error.code, + s && (i = new FirestoreError(r.error.code, r.error.message))), s ? new __PRIVATE_MutationMetadata(e, t, r.state, i) : (__PRIVATE_logError(jt, `Failed to parse mutation state for ID '${t}': ${n}`), + null); + } + Gs() { + const e = { + state: this.state, + updateTimeMs: Date.now() + }; + return this.error && (e.error = { + code: this.error.code, + message: this.error.message + }), JSON.stringify(e); + } +} + +/** + * Holds the state of a query target, including its target ID and whether the + * target is 'not-current', 'current' or 'rejected'. + */ +// Visible for testing +class __PRIVATE_QueryTargetMetadata { + constructor(e, t, n) { + this.targetId = e, this.state = t, this.error = n; + } + /** + * Parses a QueryTargetMetadata from its JSON representation in WebStorage. + * Logs a warning and returns null if the format of the data is not valid. + */ static Ws(e, t) { + const n = JSON.parse(t); + let r, i = "object" == typeof n && -1 !== [ "not-current", "current", "rejected" ].indexOf(n.state) && (void 0 === n.error || "object" == typeof n.error); + return i && n.error && (i = "string" == typeof n.error.message && "string" == typeof n.error.code, + i && (r = new FirestoreError(n.error.code, n.error.message))), i ? new __PRIVATE_QueryTargetMetadata(e, n.state, r) : (__PRIVATE_logError(jt, `Failed to parse target state for ID '${e}': ${t}`), + null); + } + Gs() { + const e = { + state: this.state, + updateTimeMs: Date.now() + }; + return this.error && (e.error = { + code: this.error.code, + message: this.error.message + }), JSON.stringify(e); + } +} + +/** + * This class represents the immutable ClientState for a client read from + * WebStorage, containing the list of active query targets. + */ class __PRIVATE_RemoteClientState { + constructor(e, t) { + this.clientId = e, this.activeTargetIds = t; + } + /** + * Parses a RemoteClientState from the JSON representation in WebStorage. + * Logs a warning and returns null if the format of the data is not valid. + */ static Ws(e, t) { + const n = JSON.parse(t); + let r = "object" == typeof n && n.activeTargetIds instanceof Array, i = __PRIVATE_targetIdSet(); + for (let e = 0; r && e < n.activeTargetIds.length; ++e) r = isSafeInteger(n.activeTargetIds[e]), + i = i.add(n.activeTargetIds[e]); + return r ? new __PRIVATE_RemoteClientState(e, i) : (__PRIVATE_logError(jt, `Failed to parse client data for instance '${e}': ${t}`), + null); + } +} + +/** + * This class represents the online state for all clients participating in + * multi-tab. The online state is only written to by the primary client, and + * used in secondary clients to update their query views. + */ class __PRIVATE_SharedOnlineState { + constructor(e, t) { + this.clientId = e, this.onlineState = t; + } + /** + * Parses a SharedOnlineState from its JSON representation in WebStorage. + * Logs a warning and returns null if the format of the data is not valid. + */ static Ws(e) { + const t = JSON.parse(e); + return "object" == typeof t && -1 !== [ "Unknown", "Online", "Offline" ].indexOf(t.onlineState) && "string" == typeof t.clientId ? new __PRIVATE_SharedOnlineState(t.clientId, t.onlineState) : (__PRIVATE_logError(jt, `Failed to parse online state: ${e}`), + null); + } +} + +/** + * Metadata state of the local client. Unlike `RemoteClientState`, this class is + * mutable and keeps track of all pending mutations, which allows us to + * update the range of pending mutation batch IDs as new mutations are added or + * removed. + * + * The data in `LocalClientState` is not read from WebStorage and instead + * updated via its instance methods. The updated state can be serialized via + * `toWebStorageJSON()`. + */ +// Visible for testing. +class __PRIVATE_LocalClientState { + constructor() { + this.activeTargetIds = __PRIVATE_targetIdSet(); + } + zs(e) { + this.activeTargetIds = this.activeTargetIds.add(e); + } + js(e) { + this.activeTargetIds = this.activeTargetIds.delete(e); + } + /** + * Converts this entry into a JSON-encoded format we can use for WebStorage. + * Does not encode `clientId` as it is part of the key in WebStorage. + */ Gs() { + const e = { + activeTargetIds: this.activeTargetIds.toArray(), + updateTimeMs: Date.now() + }; + return JSON.stringify(e); + } +} + +/** + * `WebStorageSharedClientState` uses WebStorage (window.localStorage) as the + * backing store for the SharedClientState. It keeps track of all active + * clients and supports modifications of the local client's data. + */ class __PRIVATE_WebStorageSharedClientState { + constructor(e, t, n, r, i) { + this.window = e, this.Mi = t, this.persistenceKey = n, this.Js = r, this.syncEngine = null, + this.onlineStateHandler = null, this.sequenceNumberHandler = null, this.Hs = this.Ys.bind(this), + this.Zs = new SortedMap(__PRIVATE_primitiveComparator), this.started = !1, + /** + * Captures WebStorage events that occur before `start()` is called. These + * events are replayed once `WebStorageSharedClientState` is started. + */ + this.Xs = []; + // Escape the special characters mentioned here: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions + const s = n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + this.storage = this.window.localStorage, this.currentUser = i, this.eo = createWebStorageClientStateKey(this.persistenceKey, this.Js), + this.no = + /** Assembles the key for the current sequence number. */ + function createWebStorageSequenceNumberKey(e) { + return `firestore_sequence_number_${e}`; + }(this.persistenceKey), this.Zs = this.Zs.insert(this.Js, new __PRIVATE_LocalClientState), + this.ro = new RegExp(`^${Wt}_${s}_([^_]*)$`), this.io = new RegExp(`^${Gt}_${s}_(\\d+)(?:_(.*))?$`), + this.so = new RegExp(`^${zt}_${s}_(\\d+)$`), this.oo = + /** Assembles the key for the online state of the primary tab. */ + function createWebStorageOnlineStateKey(e) { + return `firestore_online_state_${e}`; + } + // The WebStorage prefix that plays as a event to indicate the remote documents + // might have changed due to some secondary tabs loading a bundle. + // format of the key is: + // firestore_bundle_loaded_v2_ + // The version ending with "v2" stores the list of modified collection groups. + (this.persistenceKey), this._o = function createBundleLoadedKey(e) { + return `firestore_bundle_loaded_v2_${e}`; + } + // The WebStorage key prefix for the key that stores the last sequence number allocated. The key + // looks like 'firestore_sequence_number_'. + (this.persistenceKey), + // Rather than adding the storage observer during start(), we add the + // storage observer during initialization. This ensures that we collect + // events before other components populate their initial state (during their + // respective start() calls). Otherwise, we might for example miss a + // mutation that is added after LocalStore's start() processed the existing + // mutations but before we observe WebStorage events. + this.window.addEventListener("storage", this.Hs); + } + /** Returns 'true' if WebStorage is available in the current environment. */ static v(e) { + return !(!e || !e.localStorage); + } + async start() { + // Retrieve the list of existing clients to backfill the data in + // SharedClientState. + const e = await this.syncEngine.Ts(); + for (const t of e) { + if (t === this.Js) continue; + const e = this.getItem(createWebStorageClientStateKey(this.persistenceKey, t)); + if (e) { + const n = __PRIVATE_RemoteClientState.Ws(t, e); + n && (this.Zs = this.Zs.insert(n.clientId, n)); + } + } + this.ao(); + // Check if there is an existing online state and call the callback handler + // if applicable. + const t = this.storage.getItem(this.oo); + if (t) { + const e = this.uo(t); + e && this.co(e); + } + for (const e of this.Xs) this.Ys(e); + this.Xs = [], + // Register a window unload hook to remove the client metadata entry from + // WebStorage even if `shutdown()` was not called. + this.window.addEventListener("pagehide", (() => this.shutdown())), this.started = !0; + } + writeSequenceNumber(e) { + this.setItem(this.no, JSON.stringify(e)); + } + getAllActiveQueryTargets() { + return this.lo(this.Zs); + } + isActiveQueryTarget(e) { + let t = !1; + return this.Zs.forEach(((n, r) => { + r.activeTargetIds.has(e) && (t = !0); + })), t; + } + addPendingMutation(e) { + this.ho(e, "pending"); + } + updateMutationState(e, t, n) { + this.ho(e, t, n), + // Once a final mutation result is observed by other clients, they no longer + // access the mutation's metadata entry. Since WebStorage replays events + // in order, it is safe to delete the entry right after updating it. + this.Po(e); + } + addLocalQueryTarget(e, t = !0) { + let n = "not-current"; + // Lookup an existing query state if the target ID was already registered + // by another tab + if (this.isActiveQueryTarget(e)) { + const t = this.storage.getItem(createWebStorageQueryTargetMetadataKey(this.persistenceKey, e)); + if (t) { + const r = __PRIVATE_QueryTargetMetadata.Ws(e, t); + r && (n = r.state); + } + } + // If the query is listening to cache only, the target ID should not be registered with the + // local Firestore client as an active watch target. + return t && this.To.zs(e), this.ao(), n; + } + removeLocalQueryTarget(e) { + this.To.js(e), this.ao(); + } + isLocalQueryTarget(e) { + return this.To.activeTargetIds.has(e); + } + clearQueryState(e) { + this.removeItem(createWebStorageQueryTargetMetadataKey(this.persistenceKey, e)); + } + updateQueryState(e, t, n) { + this.Io(e, t, n); + } + handleUserChange(e, t, n) { + t.forEach((e => { + this.Po(e); + })), this.currentUser = e, n.forEach((e => { + this.addPendingMutation(e); + })); + } + setOnlineState(e) { + this.Eo(e); + } + notifyBundleLoaded(e) { + this.Ao(e); + } + shutdown() { + this.started && (this.window.removeEventListener("storage", this.Hs), this.removeItem(this.eo), + this.started = !1); + } + getItem(e) { + const t = this.storage.getItem(e); + return __PRIVATE_logDebug(jt, "READ", e, t), t; + } + setItem(e, t) { + __PRIVATE_logDebug(jt, "SET", e, t), this.storage.setItem(e, t); + } + removeItem(e) { + __PRIVATE_logDebug(jt, "REMOVE", e), this.storage.removeItem(e); + } + Ys(e) { + // Note: The function is typed to take Event to be interface-compatible with + // `Window.addEventListener`. + const t = e; + if (t.storageArea === this.storage) { + if (__PRIVATE_logDebug(jt, "EVENT", t.key, t.newValue), t.key === this.eo) return void __PRIVATE_logError("Received WebStorage notification for local change. Another client might have garbage-collected our state"); + this.Mi.enqueueRetryable((async () => { + if (this.started) { + if (null !== t.key) if (this.ro.test(t.key)) { + if (null == t.newValue) { + const e = this.Ro(t.key); + return this.Vo(e, null); + } + { + const e = this.mo(t.key, t.newValue); + if (e) return this.Vo(e.clientId, e); + } + } else if (this.io.test(t.key)) { + if (null !== t.newValue) { + const e = this.fo(t.key, t.newValue); + if (e) return this.po(e); + } + } else if (this.so.test(t.key)) { + if (null !== t.newValue) { + const e = this.yo(t.key, t.newValue); + if (e) return this.wo(e); + } + } else if (t.key === this.oo) { + if (null !== t.newValue) { + const e = this.uo(t.newValue); + if (e) return this.co(e); + } + } else if (t.key === this.no) { + const e = function __PRIVATE_fromWebStorageSequenceNumber(e) { + let t = __PRIVATE_ListenSequence.ce; + if (null != e) try { + const n = JSON.parse(e); + __PRIVATE_hardAssert("number" == typeof n, 30636, { + So: e + }), t = n; + } catch (e) { + __PRIVATE_logError(jt, "Failed to read sequence number from WebStorage", e); + } + return t; + } + /** + * `MemorySharedClientState` is a simple implementation of SharedClientState for + * clients using memory persistence. The state in this class remains fully + * isolated and no synchronization is performed. + */ (t.newValue); + e !== __PRIVATE_ListenSequence.ce && this.sequenceNumberHandler(e); + } else if (t.key === this._o) { + const e = this.bo(t.newValue); + await Promise.all(e.map((e => this.syncEngine.Do(e)))); + } + } else this.Xs.push(t); + })); + } + } + get To() { + return this.Zs.get(this.Js); + } + ao() { + this.setItem(this.eo, this.To.Gs()); + } + ho(e, t, n) { + const r = new __PRIVATE_MutationMetadata(this.currentUser, e, t, n), i = createWebStorageMutationBatchKey(this.persistenceKey, this.currentUser, e); + this.setItem(i, r.Gs()); + } + Po(e) { + const t = createWebStorageMutationBatchKey(this.persistenceKey, this.currentUser, e); + this.removeItem(t); + } + Eo(e) { + const t = { + clientId: this.Js, + onlineState: e + }; + this.storage.setItem(this.oo, JSON.stringify(t)); + } + Io(e, t, n) { + const r = createWebStorageQueryTargetMetadataKey(this.persistenceKey, e), i = new __PRIVATE_QueryTargetMetadata(e, t, n); + this.setItem(r, i.Gs()); + } + Ao(e) { + const t = JSON.stringify(Array.from(e)); + this.setItem(this._o, t); + } + /** + * Parses a client state key in WebStorage. Returns null if the key does not + * match the expected key format. + */ Ro(e) { + const t = this.ro.exec(e); + return t ? t[1] : null; + } + /** + * Parses a client state in WebStorage. Returns 'null' if the value could not + * be parsed. + */ mo(e, t) { + const n = this.Ro(e); + return __PRIVATE_RemoteClientState.Ws(n, t); + } + /** + * Parses a mutation batch state in WebStorage. Returns 'null' if the value + * could not be parsed. + */ fo(e, t) { + const n = this.io.exec(e), r = Number(n[1]), i = void 0 !== n[2] ? n[2] : null; + return __PRIVATE_MutationMetadata.Ws(new User(i), r, t); + } + /** + * Parses a query target state from WebStorage. Returns 'null' if the value + * could not be parsed. + */ yo(e, t) { + const n = this.so.exec(e), r = Number(n[1]); + return __PRIVATE_QueryTargetMetadata.Ws(r, t); + } + /** + * Parses an online state from WebStorage. Returns 'null' if the value + * could not be parsed. + */ uo(e) { + return __PRIVATE_SharedOnlineState.Ws(e); + } + bo(e) { + return JSON.parse(e); + } + async po(e) { + if (e.user.uid === this.currentUser.uid) return this.syncEngine.Co(e.batchId, e.state, e.error); + __PRIVATE_logDebug(jt, `Ignoring mutation for non-active user ${e.user.uid}`); + } + wo(e) { + return this.syncEngine.vo(e.targetId, e.state, e.error); + } + Vo(e, t) { + const n = t ? this.Zs.insert(e, t) : this.Zs.remove(e), r = this.lo(this.Zs), i = this.lo(n), s = [], o = []; + return i.forEach((e => { + r.has(e) || s.push(e); + })), r.forEach((e => { + i.has(e) || o.push(e); + })), this.syncEngine.Fo(s, o).then((() => { + this.Zs = n; + })); + } + co(e) { + // We check whether the client that wrote this online state is still active + // by comparing its client ID to the list of clients kept active in + // IndexedDb. If a client does not update their IndexedDb client state + // within 5 seconds, it is considered inactive and we don't emit an online + // state event. + this.Zs.get(e.clientId) && this.onlineStateHandler(e.onlineState); + } + lo(e) { + let t = __PRIVATE_targetIdSet(); + return e.forEach(((e, n) => { + t = t.unionWith(n.activeTargetIds); + })), t; + } +} + +class __PRIVATE_MemorySharedClientState { + constructor() { + this.Mo = new __PRIVATE_LocalClientState, this.xo = {}, this.onlineStateHandler = null, + this.sequenceNumberHandler = null; + } + addPendingMutation(e) { + // No op. + } + updateMutationState(e, t, n) { + // No op. + } + addLocalQueryTarget(e, t = !0) { + return t && this.Mo.zs(e), this.xo[e] || "not-current"; + } + updateQueryState(e, t, n) { + this.xo[e] = t; + } + removeLocalQueryTarget(e) { + this.Mo.js(e); + } + isLocalQueryTarget(e) { + return this.Mo.activeTargetIds.has(e); + } + clearQueryState(e) { + delete this.xo[e]; + } + getAllActiveQueryTargets() { + return this.Mo.activeTargetIds; + } + isActiveQueryTarget(e) { + return this.Mo.activeTargetIds.has(e); + } + start() { + return this.Mo = new __PRIVATE_LocalClientState, Promise.resolve(); + } + handleUserChange(e, t, n) { + // No op. + } + setOnlineState(e) { + // No op. + } + shutdown() {} + writeSequenceNumber(e) {} + notifyBundleLoaded(e) { + // No op. + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_NoopConnectivityMonitor { + Oo(e) { + // No-op. + } + shutdown() { + // No-op. + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// References to `window` are guarded by BrowserConnectivityMonitor.isAvailable() +/* eslint-disable no-restricted-globals */ const Jt = "ConnectivityMonitor"; + +/** + * Browser implementation of ConnectivityMonitor. + */ class __PRIVATE_BrowserConnectivityMonitor { + constructor() { + this.No = () => this.Bo(), this.Lo = () => this.ko(), this.qo = [], this.Qo(); + } + Oo(e) { + this.qo.push(e); + } + shutdown() { + window.removeEventListener("online", this.No), window.removeEventListener("offline", this.Lo); + } + Qo() { + window.addEventListener("online", this.No), window.addEventListener("offline", this.Lo); + } + Bo() { + __PRIVATE_logDebug(Jt, "Network connectivity changed: AVAILABLE"); + for (const e of this.qo) e(0 /* NetworkStatus.AVAILABLE */); + } + ko() { + __PRIVATE_logDebug(Jt, "Network connectivity changed: UNAVAILABLE"); + for (const e of this.qo) e(1 /* NetworkStatus.UNAVAILABLE */); + } + // TODO(chenbrian): Consider passing in window either into this component or + // here for testing via FakeWindow. + /** Checks that all used attributes of window are available. */ + static v() { + return "undefined" != typeof window && void 0 !== window.addEventListener && void 0 !== window.removeEventListener; + } +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The value returned from the most recent invocation of + * `generateUniqueDebugId()`, or null if it has never been invoked. + */ let Ht = null; + +/** + * Generates and returns an initial value for `lastUniqueDebugId`. + * + * The returned value is randomly selected from a range of integers that are + * represented as 8 hexadecimal digits. This means that (within reason) any + * numbers generated by incrementing the returned number by 1 will also be + * represented by 8 hexadecimal digits. This leads to all "IDs" having the same + * length when converted to a hexadecimal string, making reading logs containing + * these IDs easier to follow. And since the return value is randomly selected + * it will help to differentiate between logs from different executions. + */ +/** + * Generates and returns a unique ID as a hexadecimal string. + * + * The returned ID is intended to be used in debug logging messages to help + * correlate log messages that may be spatially separated in the logs, but + * logically related. For example, a network connection could include the same + * "debug ID" string in all of its log messages to help trace a specific + * connection over time. + * + * @return the 10-character generated ID (e.g. "0xa1b2c3d4"). + */ +function __PRIVATE_generateUniqueDebugId() { + return null === Ht ? Ht = function __PRIVATE_generateInitialUniqueDebugId() { + return 268435456 + Math.round(2147483648 * Math.random()); + }() : Ht++, "0x" + Ht.toString(16); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const Yt = "RestConnection", Zt = { + BatchGetDocuments: "batchGet", + Commit: "commit", + RunQuery: "runQuery", + RunAggregationQuery: "runAggregationQuery" +}; + +/** + * Maps RPC names to the corresponding REST endpoint name. + * + * We use array notation to avoid mangling. + */ +/** + * Base class for all Rest-based connections to the backend (WebChannel and + * HTTP). + */ +class __PRIVATE_RestConnection { + get $o() { + // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine + // where to run the query, and expect the `request` to NOT specify the "path". + return !1; + } + constructor(e) { + this.databaseInfo = e, this.databaseId = e.databaseId; + const t = e.ssl ? "https" : "http", n = encodeURIComponent(this.databaseId.projectId), r = encodeURIComponent(this.databaseId.database); + this.Uo = t + "://" + e.host, this.Ko = `projects/${n}/databases/${r}`, this.Wo = this.databaseId.database === lt ? `project_id=${n}` : `project_id=${n}&database_id=${r}`; + } + Go(e, t, n, r, i) { + const s = __PRIVATE_generateUniqueDebugId(), o = this.zo(e, t.toUriEncodedString()); + __PRIVATE_logDebug(Yt, `Sending RPC '${e}' ${s}:`, o, n); + const _ = { + "google-cloud-resource-prefix": this.Ko, + "x-goog-request-params": this.Wo + }; + this.jo(_, r, i); + const {host: a} = new URL(o), u = isCloudWorkstation(a); + return this.Jo(e, o, _, n, u).then((t => (__PRIVATE_logDebug(Yt, `Received RPC '${e}' ${s}: `, t), + t)), (t => { + throw __PRIVATE_logWarn(Yt, `RPC '${e}' ${s} failed with error: `, t, "url: ", o, "request:", n), + t; + })); + } + Ho(e, t, n, r, i, s) { + // The REST API automatically aggregates all of the streamed results, so we + // can just use the normal invoke() method. + return this.Go(e, t, n, r, i); + } + /** + * Modifies the headers for a request, adding any authorization token if + * present and any additional headers for the request. + */ jo(e, t, n) { + e["X-Goog-Api-Client"] = + // SDK_VERSION is updated to different value at runtime depending on the entry point, + // so we need to get its value when we need it in a function. + function __PRIVATE_getGoogApiClientValue() { + return "gl-js/ fire/" + x; + }(), + // Content-Type: text/plain will avoid preflight requests which might + // mess with CORS and redirects by proxies. If we add custom headers + // we will need to change this code to potentially use the $httpOverwrite + // parameter supported by ESF to avoid triggering preflight requests. + e["Content-Type"] = "text/plain", this.databaseInfo.appId && (e["X-Firebase-GMPID"] = this.databaseInfo.appId), + t && t.headers.forEach(((t, n) => e[n] = t)), n && n.headers.forEach(((t, n) => e[n] = t)); + } + zo(e, t) { + const n = Zt[e]; + return `${this.Uo}/v1/${t}:${n}`; + } + /** + * Closes and cleans up any resources associated with the connection. This + * implementation is a no-op because there are no resources associated + * with the RestConnection that need to be cleaned up. + */ terminate() { + // No-op + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provides a simple helper class that implements the Stream interface to + * bridge to other implementations that are streams but do not implement the + * interface. The stream callbacks are invoked with the callOn... methods. + */ class __PRIVATE_StreamBridge { + constructor(e) { + this.Yo = e.Yo, this.Zo = e.Zo; + } + Xo(e) { + this.e_ = e; + } + t_(e) { + this.n_ = e; + } + r_(e) { + this.i_ = e; + } + onMessage(e) { + this.s_ = e; + } + close() { + this.Zo(); + } + send(e) { + this.Yo(e); + } + o_() { + this.e_(); + } + __() { + this.n_(); + } + a_(e) { + this.i_(e); + } + u_(e) { + this.s_(e); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const Xt = "WebChannelConnection"; + +class __PRIVATE_WebChannelConnection extends __PRIVATE_RestConnection { + constructor(e) { + super(e), + /** A collection of open WebChannel instances */ + this.c_ = [], this.forceLongPolling = e.forceLongPolling, this.autoDetectLongPolling = e.autoDetectLongPolling, + this.useFetchStreams = e.useFetchStreams, this.longPollingOptions = e.longPollingOptions; + } + Jo(e, t, n, r, i) { + const s = __PRIVATE_generateUniqueDebugId(); + return new Promise(((i, o) => { + const _ = new XhrIo; + _.setWithCredentials(!0), _.listenOnce(EventType.COMPLETE, (() => { + try { + switch (_.getLastErrorCode()) { + case ErrorCode.NO_ERROR: + const t = _.getResponseJson(); + __PRIVATE_logDebug(Xt, `XHR for RPC '${e}' ${s} received:`, JSON.stringify(t)), + i(t); + break; + + case ErrorCode.TIMEOUT: + __PRIVATE_logDebug(Xt, `RPC '${e}' ${s} timed out`), o(new FirestoreError(N.DEADLINE_EXCEEDED, "Request time out")); + break; + + case ErrorCode.HTTP_ERROR: + const n = _.getStatus(); + if (__PRIVATE_logDebug(Xt, `RPC '${e}' ${s} failed with status:`, n, "response text:", _.getResponseText()), + n > 0) { + let e = _.getResponseJson(); + Array.isArray(e) && (e = e[0]); + const t = e?.error; + if (t && t.status && t.message) { + const e = function __PRIVATE_mapCodeFromHttpResponseErrorStatus(e) { + const t = e.toLowerCase().replace(/_/g, "-"); + return Object.values(N).indexOf(t) >= 0 ? t : N.UNKNOWN; + }(t.status); + o(new FirestoreError(e, t.message)); + } else o(new FirestoreError(N.UNKNOWN, "Server responded with status " + _.getStatus())); + } else + // If we received an HTTP_ERROR but there's no status code, + // it's most probably a connection issue + o(new FirestoreError(N.UNAVAILABLE, "Connection failed.")); + break; + + default: + fail(9055, { + l_: e, + streamId: s, + h_: _.getLastErrorCode(), + P_: _.getLastError() + }); + } + } finally { + __PRIVATE_logDebug(Xt, `RPC '${e}' ${s} completed.`); + } + })); + const a = JSON.stringify(r); + __PRIVATE_logDebug(Xt, `RPC '${e}' ${s} sending request:`, r), _.send(t, "POST", a, n, 15); + })); + } + T_(e, t, n) { + const r = __PRIVATE_generateUniqueDebugId(), i = [ this.Uo, "/", "google.firestore.v1.Firestore", "/", e, "/channel" ], s = createWebChannelTransport(), o = getStatEventTarget(), _ = { + // Required for backend stickiness, routing behavior is based on this + // parameter. + httpSessionIdParam: "gsessionid", + initMessageHeaders: {}, + messageUrlParams: { + // This param is used to improve routing and project isolation by the + // backend and must be included in every request. + database: `projects/${this.databaseId.projectId}/databases/${this.databaseId.database}` + }, + sendRawJson: !0, + supportsCrossDomainXhr: !0, + internalChannelParams: { + // Override the default timeout (randomized between 10-20 seconds) since + // a large write batch on a slow internet connection may take a long + // time to send to the backend. Rather than have WebChannel impose a + // tight timeout which could lead to infinite timeouts and retries, we + // set it very large (5-10 minutes) and rely on the browser's builtin + // timeouts to kick in if the request isn't working. + forwardChannelRequestTimeoutMs: 6e5 + }, + forceLongPolling: this.forceLongPolling, + detectBufferingProxy: this.autoDetectLongPolling + }, a = this.longPollingOptions.timeoutSeconds; + void 0 !== a && (_.longPollingTimeout = Math.round(1e3 * a)), this.useFetchStreams && (_.useFetchStreams = !0), + this.jo(_.initMessageHeaders, t, n), + // Sending the custom headers we just added to request.initMessageHeaders + // (Authorization, etc.) will trigger the browser to make a CORS preflight + // request because the XHR will no longer meet the criteria for a "simple" + // CORS request: + // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests + // Therefore to avoid the CORS preflight request (an extra network + // roundtrip), we use the encodeInitMessageHeaders option to specify that + // the headers should instead be encoded in the request's POST payload, + // which is recognized by the webchannel backend. + _.encodeInitMessageHeaders = !0; + const u = i.join(""); + __PRIVATE_logDebug(Xt, `Creating RPC '${e}' stream ${r}: ${u}`, _); + const c = s.createWebChannel(u, _); + this.I_(c); + // WebChannel supports sending the first message with the handshake - saving + // a network round trip. However, it will have to call send in the same + // JS event loop as open. In order to enforce this, we delay actually + // opening the WebChannel until send is called. Whether we have called + // open is tracked with this variable. + let l = !1, h = !1; + // A flag to determine whether the stream was closed (by us or through an + // error/close event) to avoid delivering multiple close events or sending + // on a closed stream + const P = new __PRIVATE_StreamBridge({ + Yo: t => { + h ? __PRIVATE_logDebug(Xt, `Not sending because RPC '${e}' stream ${r} is closed:`, t) : (l || (__PRIVATE_logDebug(Xt, `Opening RPC '${e}' stream ${r} transport.`), + c.open(), l = !0), __PRIVATE_logDebug(Xt, `RPC '${e}' stream ${r} sending:`, t), + c.send(t)); + }, + Zo: () => c.close() + }), __PRIVATE_unguardedEventListen = (e, t, n) => { + // TODO(dimond): closure typing seems broken because WebChannel does + // not implement goog.events.Listenable + e.listen(t, (e => { + try { + n(e); + } catch (e) { + setTimeout((() => { + throw e; + }), 0); + } + })); + }; + // Closure events are guarded and exceptions are swallowed, so catch any + // exception and rethrow using a setTimeout so they become visible again. + // Note that eventually this function could go away if we are confident + // enough the code is exception free. + return __PRIVATE_unguardedEventListen(c, WebChannel.EventType.OPEN, (() => { + h || (__PRIVATE_logDebug(Xt, `RPC '${e}' stream ${r} transport opened.`), P.o_()); + })), __PRIVATE_unguardedEventListen(c, WebChannel.EventType.CLOSE, (() => { + h || (h = !0, __PRIVATE_logDebug(Xt, `RPC '${e}' stream ${r} transport closed`), + P.a_(), this.E_(c)); + })), __PRIVATE_unguardedEventListen(c, WebChannel.EventType.ERROR, (t => { + h || (h = !0, __PRIVATE_logWarn(Xt, `RPC '${e}' stream ${r} transport errored. Name:`, t.name, "Message:", t.message), + P.a_(new FirestoreError(N.UNAVAILABLE, "The operation could not be completed"))); + })), __PRIVATE_unguardedEventListen(c, WebChannel.EventType.MESSAGE, (t => { + if (!h) { + const n = t.data[0]; + __PRIVATE_hardAssert(!!n, 16349); + // TODO(b/35143891): There is a bug in One Platform that caused errors + // (and only errors) to be wrapped in an extra array. To be forward + // compatible with the bug we need to check either condition. The latter + // can be removed once the fix has been rolled out. + // Use any because msgData.error is not typed. + const i = n, s = i?.error || i[0]?.error; + if (s) { + __PRIVATE_logDebug(Xt, `RPC '${e}' stream ${r} received error:`, s); + // error.status will be a string like 'OK' or 'NOT_FOUND'. + const t = s.status; + let n = + /** + * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'. + * + * @returns The Code equivalent to the given status string or undefined if + * there is no match. + */ + function __PRIVATE_mapCodeFromRpcStatus(e) { + // lookup by string + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const t = pt[e]; + if (void 0 !== t) return __PRIVATE_mapCodeFromRpcCode(t); + }(t), i = s.message; + void 0 === n && (n = N.INTERNAL, i = "Unknown error status: " + t + " with message " + s.message), + // Mark closed so no further events are propagated + h = !0, P.a_(new FirestoreError(n, i)), c.close(); + } else __PRIVATE_logDebug(Xt, `RPC '${e}' stream ${r} received:`, n), P.u_(n); + } + })), __PRIVATE_unguardedEventListen(o, Event.STAT_EVENT, (t => { + t.stat === Stat.PROXY ? __PRIVATE_logDebug(Xt, `RPC '${e}' stream ${r} detected buffering proxy`) : t.stat === Stat.NOPROXY && __PRIVATE_logDebug(Xt, `RPC '${e}' stream ${r} detected no buffering proxy`); + })), setTimeout((() => { + // Technically we could/should wait for the WebChannel opened event, + // but because we want to send the first message with the WebChannel + // handshake we pretend the channel opened here (asynchronously), and + // then delay the actual open until the first message is sent. + P.__(); + }), 0), P; + } + /** + * Closes and cleans up any resources associated with the connection. + */ terminate() { + // If the Firestore instance is terminated, we will explicitly + // close any remaining open WebChannel instances. + this.c_.forEach((e => e.close())), this.c_ = []; + } + /** + * Add a WebChannel instance to the collection of open instances. + * @param webChannel + */ I_(e) { + this.c_.push(e); + } + /** + * Remove a WebChannel instance from the collection of open instances. + * @param webChannel + */ E_(e) { + this.c_ = this.c_.filter((t => t === e)); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Initializes the WebChannelConnection for the browser. */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** The Platform's 'window' implementation or null if not available. */ +function __PRIVATE_getWindow() { + // `window` is not always available, e.g. in ReactNative and WebWorkers. + // eslint-disable-next-line no-restricted-globals + return "undefined" != typeof window ? window : null; +} + +/** The Platform's 'document' implementation or null if not available. */ function getDocument() { + // `document` is not always available, e.g. in ReactNative and WebWorkers. + // eslint-disable-next-line no-restricted-globals + return "undefined" != typeof document ? document : null; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_newSerializer(e) { + return new JsonProtoSerializer(e, /* useProto3Json= */ !0); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A helper for running delayed tasks following an exponential backoff curve + * between attempts. + * + * Each delay is made up of a "base" delay which follows the exponential + * backoff curve, and a +/- 50% "jitter" that is calculated and added to the + * base delay. This prevents clients from accidentally synchronizing their + * delays causing spikes of load to the backend. + */ +class __PRIVATE_ExponentialBackoff { + constructor( + /** + * The AsyncQueue to run backoff operations on. + */ + e, + /** + * The ID to use when scheduling backoff operations on the AsyncQueue. + */ + t, + /** + * The initial delay (used as the base delay on the first retry attempt). + * Note that jitter will still be applied, so the actual delay could be as + * little as 0.5*initialDelayMs. + */ + n = 1e3 + /** + * The multiplier to use to determine the extended base delay after each + * attempt. + */ , r = 1.5 + /** + * The maximum base delay after which no further backoff is performed. + * Note that jitter will still be applied, so the actual delay could be as + * much as 1.5*maxDelayMs. + */ , i = 6e4) { + this.Mi = e, this.timerId = t, this.d_ = n, this.A_ = r, this.R_ = i, this.V_ = 0, + this.m_ = null, + /** The last backoff attempt, as epoch milliseconds. */ + this.f_ = Date.now(), this.reset(); + } + /** + * Resets the backoff delay. + * + * The very next backoffAndWait() will have no delay. If it is called again + * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and + * subsequent ones will increase according to the backoffFactor. + */ reset() { + this.V_ = 0; + } + /** + * Resets the backoff delay to the maximum delay (e.g. for use after a + * RESOURCE_EXHAUSTED error). + */ g_() { + this.V_ = this.R_; + } + /** + * Returns a promise that resolves after currentDelayMs, and increases the + * delay for any subsequent attempts. If there was a pending backoff operation + * already, it will be canceled. + */ p_(e) { + // Cancel any pending backoff operation. + this.cancel(); + // First schedule using the current base (which may be 0 and should be + // honored as such). + const t = Math.floor(this.V_ + this.y_()), n = Math.max(0, Date.now() - this.f_), r = Math.max(0, t - n); + // Guard against lastAttemptTime being in the future due to a clock change. + r > 0 && __PRIVATE_logDebug("ExponentialBackoff", `Backing off for ${r} ms (base delay: ${this.V_} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`), + this.m_ = this.Mi.enqueueAfterDelay(this.timerId, r, (() => (this.f_ = Date.now(), + e()))), + // Apply backoff factor to determine next delay and ensure it is within + // bounds. + this.V_ *= this.A_, this.V_ < this.d_ && (this.V_ = this.d_), this.V_ > this.R_ && (this.V_ = this.R_); + } + w_() { + null !== this.m_ && (this.m_.skipDelay(), this.m_ = null); + } + cancel() { + null !== this.m_ && (this.m_.cancel(), this.m_ = null); + } + /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ y_() { + return (Math.random() - .5) * this.V_; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const en = "PersistentStream"; + +/** The time a stream stays open after it is marked idle. */ +/** + * A PersistentStream is an abstract base class that represents a streaming RPC + * to the Firestore backend. It's built on top of the connections own support + * for streaming RPCs, and adds several critical features for our clients: + * + * - Exponential backoff on failure + * - Authentication via CredentialsProvider + * - Dispatching all callbacks into the shared worker queue + * - Closing idle streams after 60 seconds of inactivity + * + * Subclasses of PersistentStream implement serialization of models to and + * from the JSON representation of the protocol buffers for a specific + * streaming RPC. + * + * ## Starting and Stopping + * + * Streaming RPCs are stateful and need to be start()ed before messages can + * be sent and received. The PersistentStream will call the onOpen() function + * of the listener once the stream is ready to accept requests. + * + * Should a start() fail, PersistentStream will call the registered onClose() + * listener with a FirestoreError indicating what went wrong. + * + * A PersistentStream can be started and stopped repeatedly. + * + * Generic types: + * SendType: The type of the outgoing message of the underlying + * connection stream + * ReceiveType: The type of the incoming message of the underlying + * connection stream + * ListenerType: The type of the listener that will be used for callbacks + */ +class __PRIVATE_PersistentStream { + constructor(e, t, n, r, i, s, o, _) { + this.Mi = e, this.S_ = n, this.b_ = r, this.connection = i, this.authCredentialsProvider = s, + this.appCheckCredentialsProvider = o, this.listener = _, this.state = 0 /* PersistentStreamState.Initial */ , + /** + * A close count that's incremented every time the stream is closed; used by + * getCloseGuardedDispatcher() to invalidate callbacks that happen after + * close. + */ + this.D_ = 0, this.C_ = null, this.v_ = null, this.stream = null, + /** + * Count of response messages received. + */ + this.F_ = 0, this.M_ = new __PRIVATE_ExponentialBackoff(e, t); + } + /** + * Returns true if start() has been called and no error has occurred. True + * indicates the stream is open or in the process of opening (which + * encompasses respecting backoff, getting auth tokens, and starting the + * actual RPC). Use isOpen() to determine if the stream is open and ready for + * outbound requests. + */ x_() { + return 1 /* PersistentStreamState.Starting */ === this.state || 5 /* PersistentStreamState.Backoff */ === this.state || this.O_(); + } + /** + * Returns true if the underlying RPC is open (the onOpen() listener has been + * called) and the stream is ready for outbound requests. + */ O_() { + return 2 /* PersistentStreamState.Open */ === this.state || 3 /* PersistentStreamState.Healthy */ === this.state; + } + /** + * Starts the RPC. Only allowed if isStarted() returns false. The stream is + * not immediately ready for use: onOpen() will be invoked when the RPC is + * ready for outbound requests, at which point isOpen() will return true. + * + * When start returns, isStarted() will return true. + */ start() { + this.F_ = 0, 4 /* PersistentStreamState.Error */ !== this.state ? this.auth() : this.N_(); + } + /** + * Stops the RPC. This call is idempotent and allowed regardless of the + * current isStarted() state. + * + * When stop returns, isStarted() and isOpen() will both return false. + */ async stop() { + this.x_() && await this.close(0 /* PersistentStreamState.Initial */); + } + /** + * After an error the stream will usually back off on the next attempt to + * start it. If the error warrants an immediate restart of the stream, the + * sender can use this to indicate that the receiver should not back off. + * + * Each error will call the onClose() listener. That function can decide to + * inhibit backoff if required. + */ B_() { + this.state = 0 /* PersistentStreamState.Initial */ , this.M_.reset(); + } + /** + * Marks this stream as idle. If no further actions are performed on the + * stream for one minute, the stream will automatically close itself and + * notify the stream's onClose() handler with Status.OK. The stream will then + * be in a !isStarted() state, requiring the caller to start the stream again + * before further use. + * + * Only streams that are in state 'Open' can be marked idle, as all other + * states imply pending network operations. + */ L_() { + // Starts the idle time if we are in state 'Open' and are not yet already + // running a timer (in which case the previous idle timeout still applies). + this.O_() && null === this.C_ && (this.C_ = this.Mi.enqueueAfterDelay(this.S_, 6e4, (() => this.k_()))); + } + /** Sends a message to the underlying stream. */ q_(e) { + this.Q_(), this.stream.send(e); + } + /** Called by the idle timer when the stream should close due to inactivity. */ async k_() { + if (this.O_()) + // When timing out an idle stream there's no reason to force the stream into backoff when + // it restarts so set the stream state to Initial instead of Error. + return this.close(0 /* PersistentStreamState.Initial */); + } + /** Marks the stream as active again. */ Q_() { + this.C_ && (this.C_.cancel(), this.C_ = null); + } + /** Cancels the health check delayed operation. */ U_() { + this.v_ && (this.v_.cancel(), this.v_ = null); + } + /** + * Closes the stream and cleans up as necessary: + * + * * closes the underlying GRPC stream; + * * calls the onClose handler with the given 'error'; + * * sets internal stream state to 'finalState'; + * * adjusts the backoff timer based on the error + * + * A new stream can be opened by calling start(). + * + * @param finalState - the intended state of the stream after closing. + * @param error - the error the connection was closed with. + */ async close(e, t) { + // Cancel any outstanding timers (they're guaranteed not to execute). + this.Q_(), this.U_(), this.M_.cancel(), + // Invalidates any stream-related callbacks (e.g. from auth or the + // underlying stream), guaranteeing they won't execute. + this.D_++, 4 /* PersistentStreamState.Error */ !== e ? + // If this is an intentional close ensure we don't delay our next connection attempt. + this.M_.reset() : t && t.code === N.RESOURCE_EXHAUSTED ? ( + // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.) + __PRIVATE_logError(t.toString()), __PRIVATE_logError("Using maximum backoff delay to prevent overloading the backend."), + this.M_.g_()) : t && t.code === N.UNAUTHENTICATED && 3 /* PersistentStreamState.Healthy */ !== this.state && ( + // "unauthenticated" error means the token was rejected. This should rarely + // happen since both Auth and AppCheck ensure a sufficient TTL when we + // request a token. If a user manually resets their system clock this can + // fail, however. In this case, we should get a Code.UNAUTHENTICATED error + // before we received the first message and we need to invalidate the token + // to ensure that we fetch a new token. + this.authCredentialsProvider.invalidateToken(), this.appCheckCredentialsProvider.invalidateToken()), + // Clean up the underlying stream because we are no longer interested in events. + null !== this.stream && (this.K_(), this.stream.close(), this.stream = null), + // This state must be assigned before calling onClose() to allow the callback to + // inhibit backoff or otherwise manipulate the state in its non-started state. + this.state = e, + // Notify the listener that the stream closed. + await this.listener.r_(t); + } + /** + * Can be overridden to perform additional cleanup before the stream is closed. + * Calling super.tearDown() is not required. + */ K_() {} + auth() { + this.state = 1 /* PersistentStreamState.Starting */; + const e = this.W_(this.D_), t = this.D_; + // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below. + Promise.all([ this.authCredentialsProvider.getToken(), this.appCheckCredentialsProvider.getToken() ]).then((([e, n]) => { + // Stream can be stopped while waiting for authentication. + // TODO(mikelehen): We really should just use dispatchIfNotClosed + // and let this dispatch onto the queue, but that opened a spec test can + // of worms that I don't want to deal with in this PR. + this.D_ === t && + // Normally we'd have to schedule the callback on the AsyncQueue. + // However, the following calls are safe to be called outside the + // AsyncQueue since they don't chain asynchronous calls + this.G_(e, n); + }), (t => { + e((() => { + const e = new FirestoreError(N.UNKNOWN, "Fetching auth token failed: " + t.message); + return this.z_(e); + })); + })); + } + G_(e, t) { + const n = this.W_(this.D_); + this.stream = this.j_(e, t), this.stream.Xo((() => { + n((() => this.listener.Xo())); + })), this.stream.t_((() => { + n((() => (this.state = 2 /* PersistentStreamState.Open */ , this.v_ = this.Mi.enqueueAfterDelay(this.b_, 1e4, (() => (this.O_() && (this.state = 3 /* PersistentStreamState.Healthy */), + Promise.resolve()))), this.listener.t_()))); + })), this.stream.r_((e => { + n((() => this.z_(e))); + })), this.stream.onMessage((e => { + n((() => 1 == ++this.F_ ? this.J_(e) : this.onNext(e))); + })); + } + N_() { + this.state = 5 /* PersistentStreamState.Backoff */ , this.M_.p_((async () => { + this.state = 0 /* PersistentStreamState.Initial */ , this.start(); + })); + } + // Visible for tests + z_(e) { + // In theory the stream could close cleanly, however, in our current model + // we never expect this to happen because if we stop a stream ourselves, + // this callback will never be called. To prevent cases where we retry + // without a backoff accidentally, we set the stream to error in all cases. + return __PRIVATE_logDebug(en, `close with error: ${e}`), this.stream = null, this.close(4 /* PersistentStreamState.Error */ , e); + } + /** + * Returns a "dispatcher" function that dispatches operations onto the + * AsyncQueue but only runs them if closeCount remains unchanged. This allows + * us to turn auth / stream callbacks into no-ops if the stream is closed / + * re-opened, etc. + */ W_(e) { + return t => { + this.Mi.enqueueAndForget((() => this.D_ === e ? t() : (__PRIVATE_logDebug(en, "stream callback skipped by getCloseGuardedDispatcher."), + Promise.resolve()))); + }; + } +} + +/** + * A PersistentStream that implements the Listen RPC. + * + * Once the Listen stream has called the onOpen() listener, any number of + * listen() and unlisten() calls can be made to control what changes will be + * sent from the server for ListenResponses. + */ class __PRIVATE_PersistentListenStream extends __PRIVATE_PersistentStream { + constructor(e, t, n, r, i, s) { + super(e, "listen_stream_connection_backoff" /* TimerId.ListenStreamConnectionBackoff */ , "listen_stream_idle" /* TimerId.ListenStreamIdle */ , "health_check_timeout" /* TimerId.HealthCheckTimeout */ , t, n, r, s), + this.serializer = i; + } + j_(e, t) { + return this.connection.T_("Listen", e, t); + } + J_(e) { + return this.onNext(e); + } + onNext(e) { + // A successful response means the stream is healthy + this.M_.reset(); + const t = __PRIVATE_fromWatchChange(this.serializer, e), n = function __PRIVATE_versionFromListenResponse(e) { + // We have only reached a consistent snapshot for the entire stream if there + // is a read_time set and it applies to all targets (i.e. the list of + // targets is empty). The backend is guaranteed to send such responses. + if (!("targetChange" in e)) return SnapshotVersion.min(); + const t = e.targetChange; + return t.targetIds && t.targetIds.length ? SnapshotVersion.min() : t.readTime ? __PRIVATE_fromVersion(t.readTime) : SnapshotVersion.min(); + }(e); + return this.listener.H_(t, n); + } + /** + * Registers interest in the results of the given target. If the target + * includes a resumeToken it will be included in the request. Results that + * affect the target will be streamed back as WatchChange messages that + * reference the targetId. + */ Y_(e) { + const t = {}; + t.database = __PRIVATE_getEncodedDatabaseId(this.serializer), t.addTarget = function __PRIVATE_toTarget(e, t) { + let n; + const r = t.target; + if (n = __PRIVATE_targetIsDocumentTarget(r) ? { + documents: __PRIVATE_toDocumentsTarget(e, r) + } : { + query: __PRIVATE_toQueryTarget(e, r).ft + }, n.targetId = t.targetId, t.resumeToken.approximateByteSize() > 0) { + n.resumeToken = __PRIVATE_toBytes(e, t.resumeToken); + const r = __PRIVATE_toInt32Proto(e, t.expectedCount); + null !== r && (n.expectedCount = r); + } else if (t.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) { + // TODO(wuandy): Consider removing above check because it is most likely true. + // Right now, many tests depend on this behaviour though (leaving min() out + // of serialization). + n.readTime = toTimestamp(e, t.snapshotVersion.toTimestamp()); + const r = __PRIVATE_toInt32Proto(e, t.expectedCount); + null !== r && (n.expectedCount = r); + } + return n; + }(this.serializer, e); + const n = __PRIVATE_toListenRequestLabels(this.serializer, e); + n && (t.labels = n), this.q_(t); + } + /** + * Unregisters interest in the results of the target associated with the + * given targetId. + */ Z_(e) { + const t = {}; + t.database = __PRIVATE_getEncodedDatabaseId(this.serializer), t.removeTarget = e, + this.q_(t); + } +} + +/** + * A Stream that implements the Write RPC. + * + * The Write RPC requires the caller to maintain special streamToken + * state in between calls, to help the server understand which responses the + * client has processed by the time the next request is made. Every response + * will contain a streamToken; this value must be passed to the next + * request. + * + * After calling start() on this stream, the next request must be a handshake, + * containing whatever streamToken is on hand. Once a response to this + * request is received, all pending mutations may be submitted. When + * submitting multiple batches of mutations at the same time, it's + * okay to use the same streamToken for the calls to writeMutations. + * + * TODO(b/33271235): Use proto types + */ class __PRIVATE_PersistentWriteStream extends __PRIVATE_PersistentStream { + constructor(e, t, n, r, i, s) { + super(e, "write_stream_connection_backoff" /* TimerId.WriteStreamConnectionBackoff */ , "write_stream_idle" /* TimerId.WriteStreamIdle */ , "health_check_timeout" /* TimerId.HealthCheckTimeout */ , t, n, r, s), + this.serializer = i; + } + /** + * Tracks whether or not a handshake has been successfully exchanged and + * the stream is ready to accept mutations. + */ get X_() { + return this.F_ > 0; + } + // Override of PersistentStream.start + start() { + this.lastStreamToken = void 0, super.start(); + } + K_() { + this.X_ && this.ea([]); + } + j_(e, t) { + return this.connection.T_("Write", e, t); + } + J_(e) { + // Always capture the last stream token. + return __PRIVATE_hardAssert(!!e.streamToken, 31322), this.lastStreamToken = e.streamToken, + // The first response is always the handshake response + __PRIVATE_hardAssert(!e.writeResults || 0 === e.writeResults.length, 55816), this.listener.ta(); + } + onNext(e) { + // Always capture the last stream token. + __PRIVATE_hardAssert(!!e.streamToken, 12678), this.lastStreamToken = e.streamToken, + // A successful first write response means the stream is healthy, + // Note, that we could consider a successful handshake healthy, however, + // the write itself might be causing an error we want to back off from. + this.M_.reset(); + const t = __PRIVATE_fromWriteResults(e.writeResults, e.commitTime), n = __PRIVATE_fromVersion(e.commitTime); + return this.listener.na(n, t); + } + /** + * Sends an initial streamToken to the server, performing the handshake + * required to make the StreamingWrite RPC work. Subsequent + * calls should wait until onHandshakeComplete was called. + */ ra() { + // TODO(dimond): Support stream resumption. We intentionally do not set the + // stream token on the handshake, ignoring any stream token we might have. + const e = {}; + e.database = __PRIVATE_getEncodedDatabaseId(this.serializer), this.q_(e); + } + /** Sends a group of mutations to the Firestore backend to apply. */ ea(e) { + const t = { + streamToken: this.lastStreamToken, + writes: e.map((e => toMutation(this.serializer, e))) + }; + this.q_(t); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Datastore and its related methods are a wrapper around the external Google + * Cloud Datastore grpc API, which provides an interface that is more convenient + * for the rest of the client SDK architecture to consume. + */ class Datastore {} + +/** + * An implementation of Datastore that exposes additional state for internal + * consumption. + */ class __PRIVATE_DatastoreImpl extends Datastore { + constructor(e, t, n, r) { + super(), this.authCredentials = e, this.appCheckCredentials = t, this.connection = n, + this.serializer = r, this.ia = !1; + } + sa() { + if (this.ia) throw new FirestoreError(N.FAILED_PRECONDITION, "The client has already been terminated."); + } + /** Invokes the provided RPC with auth and AppCheck tokens. */ Go(e, t, n, r) { + return this.sa(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([i, s]) => this.connection.Go(e, __PRIVATE_toResourcePath(t, n), r, i, s))).catch((e => { + throw "FirebaseError" === e.name ? (e.code === N.UNAUTHENTICATED && (this.authCredentials.invalidateToken(), + this.appCheckCredentials.invalidateToken()), e) : new FirestoreError(N.UNKNOWN, e.toString()); + })); + } + /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ Ho(e, t, n, r, i) { + return this.sa(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([s, o]) => this.connection.Ho(e, __PRIVATE_toResourcePath(t, n), r, s, o, i))).catch((e => { + throw "FirebaseError" === e.name ? (e.code === N.UNAUTHENTICATED && (this.authCredentials.invalidateToken(), + this.appCheckCredentials.invalidateToken()), e) : new FirestoreError(N.UNKNOWN, e.toString()); + })); + } + terminate() { + this.ia = !0, this.connection.terminate(); + } +} + +// TODO(firestorexp): Make sure there is only one Datastore instance per +// firestore-exp client. +/** + * A component used by the RemoteStore to track the OnlineState (that is, + * whether or not the client as a whole should be considered to be online or + * offline), implementing the appropriate heuristics. + * + * In particular, when the client is trying to connect to the backend, we + * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for + * a connection to succeed. If we have too many failures or the timeout elapses, + * then we set the OnlineState to Offline, and the client will behave as if + * it is offline (get()s will return cached data, etc.). + */ +class __PRIVATE_OnlineStateTracker { + constructor(e, t) { + this.asyncQueue = e, this.onlineStateHandler = t, + /** The current OnlineState. */ + this.state = "Unknown" /* OnlineState.Unknown */ , + /** + * A count of consecutive failures to open the stream. If it reaches the + * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to + * Offline. + */ + this.oa = 0, + /** + * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we + * transition from OnlineState.Unknown to OnlineState.Offline without waiting + * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times). + */ + this._a = null, + /** + * Whether the client should log a warning message if it fails to connect to + * the backend (initially true, cleared after a successful stream, or if we've + * logged the message already). + */ + this.aa = !0; + } + /** + * Called by RemoteStore when a watch stream is started (including on each + * backoff attempt). + * + * If this is the first attempt, it sets the OnlineState to Unknown and starts + * the onlineStateTimer. + */ ua() { + 0 === this.oa && (this.ca("Unknown" /* OnlineState.Unknown */), this._a = this.asyncQueue.enqueueAfterDelay("online_state_timeout" /* TimerId.OnlineStateTimeout */ , 1e4, (() => (this._a = null, + this.la("Backend didn't respond within 10 seconds."), this.ca("Offline" /* OnlineState.Offline */), + Promise.resolve())))); + } + /** + * Updates our OnlineState as appropriate after the watch stream reports a + * failure. The first failure moves us to the 'Unknown' state. We then may + * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we + * actually transition to the 'Offline' state. + */ ha(e) { + "Online" /* OnlineState.Online */ === this.state ? this.ca("Unknown" /* OnlineState.Unknown */) : (this.oa++, + this.oa >= 1 && (this.Pa(), this.la(`Connection failed 1 times. Most recent error: ${e.toString()}`), + this.ca("Offline" /* OnlineState.Offline */))); + } + /** + * Explicitly sets the OnlineState to the specified state. + * + * Note that this resets our timers / failure counters, etc. used by our + * Offline heuristics, so must not be used in place of + * handleWatchStreamStart() and handleWatchStreamFailure(). + */ set(e) { + this.Pa(), this.oa = 0, "Online" /* OnlineState.Online */ === e && ( + // We've connected to watch at least once. Don't warn the developer + // about being offline going forward. + this.aa = !1), this.ca(e); + } + ca(e) { + e !== this.state && (this.state = e, this.onlineStateHandler(e)); + } + la(e) { + const t = `Could not reach Cloud Firestore backend. ${e}\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`; + this.aa ? (__PRIVATE_logError(t), this.aa = !1) : __PRIVATE_logDebug("OnlineStateTracker", t); + } + Pa() { + null !== this._a && (this._a.cancel(), this._a = null); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const tn = "RemoteStore"; + +// TODO(b/35853402): Negotiate this with the stream. +class __PRIVATE_RemoteStoreImpl { + constructor( + /** + * The local store, used to fill the write pipeline with outbound mutations. + */ + e, + /** The client-side proxy for interacting with the backend. */ + t, n, r, i) { + this.localStore = e, this.datastore = t, this.asyncQueue = n, this.remoteSyncer = {}, + /** + * A list of up to MAX_PENDING_WRITES writes that we have fetched from the + * LocalStore via fillWritePipeline() and have or will send to the write + * stream. + * + * Whenever writePipeline.length > 0 the RemoteStore will attempt to start or + * restart the write stream. When the stream is established the writes in the + * pipeline will be sent in order. + * + * Writes remain in writePipeline until they are acknowledged by the backend + * and thus will automatically be re-sent if the stream is interrupted / + * restarted before they're acknowledged. + * + * Write responses from the backend are linked to their originating request + * purely based on order, and so we can just shift() writes from the front of + * the writePipeline as we receive responses. + */ + this.Ta = [], + /** + * A mapping of watched targets that the client cares about tracking and the + * user has explicitly called a 'listen' for this target. + * + * These targets may or may not have been sent to or acknowledged by the + * server. On re-establishing the listen stream, these targets should be sent + * to the server. The targets removed with unlistens are removed eagerly + * without waiting for confirmation from the listen stream. + */ + this.Ia = new Map, + /** + * A set of reasons for why the RemoteStore may be offline. If empty, the + * RemoteStore may start its network connections. + */ + this.Ea = new Set, + /** + * Event handlers that get called when the network is disabled or enabled. + * + * PORTING NOTE: These functions are used on the Web client to create the + * underlying streams (to support tree-shakeable streams). On Android and iOS, + * the streams are created during construction of RemoteStore. + */ + this.da = [], this.Aa = i, this.Aa.Oo((e => { + n.enqueueAndForget((async () => { + // Porting Note: Unlike iOS, `restartNetwork()` is called even when the + // network becomes unreachable as we don't have any other way to tear + // down our streams. + __PRIVATE_canUseNetwork(this) && (__PRIVATE_logDebug(tn, "Restarting streams for network reachability change."), + await async function __PRIVATE_restartNetwork(e) { + const t = __PRIVATE_debugCast(e); + t.Ea.add(4 /* OfflineCause.ConnectivityChange */), await __PRIVATE_disableNetworkInternal(t), + t.Ra.set("Unknown" /* OnlineState.Unknown */), t.Ea.delete(4 /* OfflineCause.ConnectivityChange */), + await __PRIVATE_enableNetworkInternal(t); + }(this)); + })); + })), this.Ra = new __PRIVATE_OnlineStateTracker(n, r); + } +} + +async function __PRIVATE_enableNetworkInternal(e) { + if (__PRIVATE_canUseNetwork(e)) for (const t of e.da) await t(/* enabled= */ !0); +} + +/** + * Temporarily disables the network. The network can be re-enabled using + * enableNetwork(). + */ async function __PRIVATE_disableNetworkInternal(e) { + for (const t of e.da) await t(/* enabled= */ !1); +} + +/** + * Starts new listen for the given target. Uses resume token if provided. It + * is a no-op if the target of given `TargetData` is already being listened to. + */ +function __PRIVATE_remoteStoreListen(e, t) { + const n = __PRIVATE_debugCast(e); + n.Ia.has(t.targetId) || ( + // Mark this as something the client is currently listening for. + n.Ia.set(t.targetId, t), __PRIVATE_shouldStartWatchStream(n) ? + // The listen will be sent in onWatchStreamOpen + __PRIVATE_startWatchStream(n) : __PRIVATE_ensureWatchStream(n).O_() && __PRIVATE_sendWatchRequest(n, t)); +} + +/** + * Removes the listen from server. It is a no-op if the given target id is + * not being listened to. + */ function __PRIVATE_remoteStoreUnlisten(e, t) { + const n = __PRIVATE_debugCast(e), r = __PRIVATE_ensureWatchStream(n); + n.Ia.delete(t), r.O_() && __PRIVATE_sendUnwatchRequest(n, t), 0 === n.Ia.size && (r.O_() ? r.L_() : __PRIVATE_canUseNetwork(n) && + // Revert to OnlineState.Unknown if the watch stream is not open and we + // have no listeners, since without any listens to send we cannot + // confirm if the stream is healthy and upgrade to OnlineState.Online. + n.Ra.set("Unknown" /* OnlineState.Unknown */)); +} + +/** + * We need to increment the expected number of pending responses we're due + * from watch so we wait for the ack to process any messages from this target. + */ function __PRIVATE_sendWatchRequest(e, t) { + if (e.Va.Ue(t.targetId), t.resumeToken.approximateByteSize() > 0 || t.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) { + const n = e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size; + t = t.withExpectedCount(n); + } + __PRIVATE_ensureWatchStream(e).Y_(t); +} + +/** + * We need to increment the expected number of pending responses we're due + * from watch so we wait for the removal on the server before we process any + * messages from this target. + */ function __PRIVATE_sendUnwatchRequest(e, t) { + e.Va.Ue(t), __PRIVATE_ensureWatchStream(e).Z_(t); +} + +function __PRIVATE_startWatchStream(e) { + e.Va = new __PRIVATE_WatchChangeAggregator({ + getRemoteKeysForTarget: t => e.remoteSyncer.getRemoteKeysForTarget(t), + At: t => e.Ia.get(t) || null, + ht: () => e.datastore.serializer.databaseId + }), __PRIVATE_ensureWatchStream(e).start(), e.Ra.ua(); +} + +/** + * Returns whether the watch stream should be started because it's necessary + * and has not yet been started. + */ function __PRIVATE_shouldStartWatchStream(e) { + return __PRIVATE_canUseNetwork(e) && !__PRIVATE_ensureWatchStream(e).x_() && e.Ia.size > 0; +} + +function __PRIVATE_canUseNetwork(e) { + return 0 === __PRIVATE_debugCast(e).Ea.size; +} + +function __PRIVATE_cleanUpWatchStreamState(e) { + e.Va = void 0; +} + +async function __PRIVATE_onWatchStreamConnected(e) { + // Mark the client as online since we got a "connected" notification. + e.Ra.set("Online" /* OnlineState.Online */); +} + +async function __PRIVATE_onWatchStreamOpen(e) { + e.Ia.forEach(((t, n) => { + __PRIVATE_sendWatchRequest(e, t); + })); +} + +async function __PRIVATE_onWatchStreamClose(e, t) { + __PRIVATE_cleanUpWatchStreamState(e), + // If we still need the watch stream, retry the connection. + __PRIVATE_shouldStartWatchStream(e) ? (e.Ra.ha(t), __PRIVATE_startWatchStream(e)) : + // No need to restart watch stream because there are no active targets. + // The online state is set to unknown because there is no active attempt + // at establishing a connection + e.Ra.set("Unknown" /* OnlineState.Unknown */); +} + +async function __PRIVATE_onWatchStreamChange(e, t, n) { + if ( + // Mark the client as online since we got a message from the server + e.Ra.set("Online" /* OnlineState.Online */), t instanceof __PRIVATE_WatchTargetChange && 2 /* WatchTargetChangeState.Removed */ === t.state && t.cause) + // There was an error on a target, don't wait for a consistent snapshot + // to raise events + try { + /** Handles an error on a target */ + await async function __PRIVATE_handleTargetError(e, t) { + const n = t.cause; + for (const r of t.targetIds) + // A watched target might have been removed already. + e.Ia.has(r) && (await e.remoteSyncer.rejectListen(r, n), e.Ia.delete(r), e.Va.removeTarget(r)); + } + /** + * Attempts to fill our write pipeline with writes from the LocalStore. + * + * Called internally to bootstrap or refill the write pipeline and by + * SyncEngine whenever there are new mutations to process. + * + * Starts the write stream if necessary. + */ (e, t); + } catch (n) { + __PRIVATE_logDebug(tn, "Failed to remove targets %s: %s ", t.targetIds.join(","), n), + await __PRIVATE_disableNetworkUntilRecovery(e, n); + } else if (t instanceof __PRIVATE_DocumentWatchChange ? e.Va.Ze(t) : t instanceof __PRIVATE_ExistenceFilterChange ? e.Va.st(t) : e.Va.tt(t), + !n.isEqual(SnapshotVersion.min())) try { + const t = await __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e.localStore); + n.compareTo(t) >= 0 && + // We have received a target change with a global snapshot if the snapshot + // version is not equal to SnapshotVersion.min(). + /** + * Takes a batch of changes from the Datastore, repackages them as a + * RemoteEvent, and passes that on to the listener, which is typically the + * SyncEngine. + */ + await function __PRIVATE_raiseWatchSnapshot(e, t) { + const n = e.Va.Tt(t); + // Update in-memory resume tokens. LocalStore will update the + // persistent view of these when applying the completed RemoteEvent. + return n.targetChanges.forEach(((n, r) => { + if (n.resumeToken.approximateByteSize() > 0) { + const i = e.Ia.get(r); + // A watched target might have been removed already. + i && e.Ia.set(r, i.withResumeToken(n.resumeToken, t)); + } + })), + // Re-establish listens for the targets that have been invalidated by + // existence filter mismatches. + n.targetMismatches.forEach(((t, n) => { + const r = e.Ia.get(t); + if (!r) + // A watched target might have been removed already. + return; + // Clear the resume token for the target, since we're in a known mismatch + // state. + e.Ia.set(t, r.withResumeToken(ByteString.EMPTY_BYTE_STRING, r.snapshotVersion)), + // Cause a hard reset by unwatching and rewatching immediately, but + // deliberately don't send a resume token so that we get a full update. + __PRIVATE_sendUnwatchRequest(e, t); + // Mark the target we send as being on behalf of an existence filter + // mismatch, but don't actually retain that in listenTargets. This ensures + // that we flag the first re-listen this way without impacting future + // listens of this target (that might happen e.g. on reconnect). + const i = new TargetData(r.target, t, n, r.sequenceNumber); + __PRIVATE_sendWatchRequest(e, i); + })), e.remoteSyncer.applyRemoteEvent(n); + }(e, n); + } catch (t) { + __PRIVATE_logDebug(tn, "Failed to raise snapshot:", t), await __PRIVATE_disableNetworkUntilRecovery(e, t); + } +} + +/** + * Recovery logic for IndexedDB errors that takes the network offline until + * `op` succeeds. Retries are scheduled with backoff using + * `enqueueRetryable()`. If `op()` is not provided, IndexedDB access is + * validated via a generic operation. + * + * The returned Promise is resolved once the network is disabled and before + * any retry attempt. + */ async function __PRIVATE_disableNetworkUntilRecovery(e, t, n) { + if (!__PRIVATE_isIndexedDbTransactionError(t)) throw t; + e.Ea.add(1 /* OfflineCause.IndexedDbFailed */), + // Disable network and raise offline snapshots + await __PRIVATE_disableNetworkInternal(e), e.Ra.set("Offline" /* OnlineState.Offline */), + n || ( + // Use a simple read operation to determine if IndexedDB recovered. + // Ideally, we would expose a health check directly on SimpleDb, but + // RemoteStore only has access to persistence through LocalStore. + n = () => __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e.localStore)), + // Probe IndexedDB periodically and re-enable network + e.asyncQueue.enqueueRetryable((async () => { + __PRIVATE_logDebug(tn, "Retrying IndexedDB access"), await n(), e.Ea.delete(1 /* OfflineCause.IndexedDbFailed */), + await __PRIVATE_enableNetworkInternal(e); + })); +} + +/** + * Executes `op`. If `op` fails, takes the network offline until `op` + * succeeds. Returns after the first attempt. + */ function __PRIVATE_executeWithRecovery(e, t) { + return t().catch((n => __PRIVATE_disableNetworkUntilRecovery(e, n, t))); +} + +async function __PRIVATE_fillWritePipeline(e) { + const t = __PRIVATE_debugCast(e), n = __PRIVATE_ensureWriteStream(t); + let r = t.Ta.length > 0 ? t.Ta[t.Ta.length - 1].batchId : j; + for (;__PRIVATE_canAddToWritePipeline(t); ) try { + const e = await __PRIVATE_localStoreGetNextMutationBatch(t.localStore, r); + if (null === e) { + 0 === t.Ta.length && n.L_(); + break; + } + r = e.batchId, __PRIVATE_addToWritePipeline(t, e); + } catch (e) { + await __PRIVATE_disableNetworkUntilRecovery(t, e); + } + __PRIVATE_shouldStartWriteStream(t) && __PRIVATE_startWriteStream(t); +} + +/** + * Returns true if we can add to the write pipeline (i.e. the network is + * enabled and the write pipeline is not full). + */ function __PRIVATE_canAddToWritePipeline(e) { + return __PRIVATE_canUseNetwork(e) && e.Ta.length < 10; +} + +/** + * Queues additional writes to be sent to the write stream, sending them + * immediately if the write stream is established. + */ function __PRIVATE_addToWritePipeline(e, t) { + e.Ta.push(t); + const n = __PRIVATE_ensureWriteStream(e); + n.O_() && n.X_ && n.ea(t.mutations); +} + +function __PRIVATE_shouldStartWriteStream(e) { + return __PRIVATE_canUseNetwork(e) && !__PRIVATE_ensureWriteStream(e).x_() && e.Ta.length > 0; +} + +function __PRIVATE_startWriteStream(e) { + __PRIVATE_ensureWriteStream(e).start(); +} + +async function __PRIVATE_onWriteStreamOpen(e) { + __PRIVATE_ensureWriteStream(e).ra(); +} + +async function __PRIVATE_onWriteHandshakeComplete(e) { + const t = __PRIVATE_ensureWriteStream(e); + // Send the write pipeline now that the stream is established. + for (const n of e.Ta) t.ea(n.mutations); +} + +async function __PRIVATE_onMutationResult(e, t, n) { + const r = e.Ta.shift(), i = MutationBatchResult.from(r, t, n); + await __PRIVATE_executeWithRecovery(e, (() => e.remoteSyncer.applySuccessfulWrite(i))), + // It's possible that with the completion of this mutation another + // slot has freed up. + await __PRIVATE_fillWritePipeline(e); +} + +async function __PRIVATE_onWriteStreamClose(e, t) { + // If the write stream closed after the write handshake completes, a write + // operation failed and we fail the pending operation. + t && __PRIVATE_ensureWriteStream(e).X_ && + // This error affects the actual write. + await async function __PRIVATE_handleWriteError(e, t) { + // Only handle permanent errors here. If it's transient, just let the retry + // logic kick in. + if (function __PRIVATE_isPermanentWriteError(e) { + return __PRIVATE_isPermanentError(e) && e !== N.ABORTED; + }(t.code)) { + // This was a permanent error, the request itself was the problem + // so it's not going to succeed if we resend it. + const n = e.Ta.shift(); + // In this case it's also unlikely that the server itself is melting + // down -- this was just a bad request so inhibit backoff on the next + // restart. + __PRIVATE_ensureWriteStream(e).B_(), await __PRIVATE_executeWithRecovery(e, (() => e.remoteSyncer.rejectFailedWrite(n.batchId, t))), + // It's possible that with the completion of this mutation + // another slot has freed up. + await __PRIVATE_fillWritePipeline(e); + } + }(e, t), + // The write stream might have been started by refilling the write + // pipeline for failed writes + __PRIVATE_shouldStartWriteStream(e) && __PRIVATE_startWriteStream(e); +} + +async function __PRIVATE_remoteStoreHandleCredentialChange(e, t) { + const n = __PRIVATE_debugCast(e); + n.asyncQueue.verifyOperationInProgress(), __PRIVATE_logDebug(tn, "RemoteStore received new credentials"); + const r = __PRIVATE_canUseNetwork(n); + // Tear down and re-create our network streams. This will ensure we get a + // fresh auth token for the new user and re-fill the write pipeline with + // new mutations from the LocalStore (since mutations are per-user). + n.Ea.add(3 /* OfflineCause.CredentialChange */), await __PRIVATE_disableNetworkInternal(n), + r && + // Don't set the network status to Unknown if we are offline. + n.Ra.set("Unknown" /* OnlineState.Unknown */), await n.remoteSyncer.handleCredentialChange(t), + n.Ea.delete(3 /* OfflineCause.CredentialChange */), await __PRIVATE_enableNetworkInternal(n); +} + +/** + * Toggles the network state when the client gains or loses its primary lease. + */ async function __PRIVATE_remoteStoreApplyPrimaryState(e, t) { + const n = __PRIVATE_debugCast(e); + t ? (n.Ea.delete(2 /* OfflineCause.IsSecondary */), await __PRIVATE_enableNetworkInternal(n)) : t || (n.Ea.add(2 /* OfflineCause.IsSecondary */), + await __PRIVATE_disableNetworkInternal(n), n.Ra.set("Unknown" /* OnlineState.Unknown */)); +} + +/** + * If not yet initialized, registers the WatchStream and its network state + * callback with `remoteStoreImpl`. Returns the existing stream if one is + * already available. + * + * PORTING NOTE: On iOS and Android, the WatchStream gets registered on startup. + * This is not done on Web to allow it to be tree-shaken. + */ function __PRIVATE_ensureWatchStream(e) { + return e.ma || ( + // Create stream (but note that it is not started yet). + e.ma = function __PRIVATE_newPersistentWatchStream(e, t, n) { + const r = __PRIVATE_debugCast(e); + return r.sa(), new __PRIVATE_PersistentListenStream(t, r.connection, r.authCredentials, r.appCheckCredentials, r.serializer, n); + } + /** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ (e.datastore, e.asyncQueue, { + Xo: __PRIVATE_onWatchStreamConnected.bind(null, e), + t_: __PRIVATE_onWatchStreamOpen.bind(null, e), + r_: __PRIVATE_onWatchStreamClose.bind(null, e), + H_: __PRIVATE_onWatchStreamChange.bind(null, e) + }), e.da.push((async t => { + t ? (e.ma.B_(), __PRIVATE_shouldStartWatchStream(e) ? __PRIVATE_startWatchStream(e) : e.Ra.set("Unknown" /* OnlineState.Unknown */)) : (await e.ma.stop(), + __PRIVATE_cleanUpWatchStreamState(e)); + }))), e.ma; +} + +/** + * If not yet initialized, registers the WriteStream and its network state + * callback with `remoteStoreImpl`. Returns the existing stream if one is + * already available. + * + * PORTING NOTE: On iOS and Android, the WriteStream gets registered on startup. + * This is not done on Web to allow it to be tree-shaken. + */ function __PRIVATE_ensureWriteStream(e) { + return e.fa || ( + // Create stream (but note that it is not started yet). + e.fa = function __PRIVATE_newPersistentWriteStream(e, t, n) { + const r = __PRIVATE_debugCast(e); + return r.sa(), new __PRIVATE_PersistentWriteStream(t, r.connection, r.authCredentials, r.appCheckCredentials, r.serializer, n); + }(e.datastore, e.asyncQueue, { + Xo: () => Promise.resolve(), + t_: __PRIVATE_onWriteStreamOpen.bind(null, e), + r_: __PRIVATE_onWriteStreamClose.bind(null, e), + ta: __PRIVATE_onWriteHandshakeComplete.bind(null, e), + na: __PRIVATE_onMutationResult.bind(null, e) + }), e.da.push((async t => { + t ? (e.fa.B_(), + // This will start the write stream if necessary. + await __PRIVATE_fillWritePipeline(e)) : (await e.fa.stop(), e.Ta.length > 0 && (__PRIVATE_logDebug(tn, `Stopping write stream with ${e.Ta.length} pending writes`), + e.Ta = [])); + }))), e.fa; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents an operation scheduled to be run in the future on an AsyncQueue. + * + * It is created via DelayedOperation.createAndSchedule(). + * + * Supports cancellation (via cancel()) and early execution (via skipDelay()). + * + * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type + * in newer versions of TypeScript defines `finally`, which is not available in + * IE. + */ +class DelayedOperation { + constructor(e, t, n, r, i) { + this.asyncQueue = e, this.timerId = t, this.targetTimeMs = n, this.op = r, this.removalCallback = i, + this.deferred = new __PRIVATE_Deferred, this.then = this.deferred.promise.then.bind(this.deferred.promise), + // It's normal for the deferred promise to be canceled (due to cancellation) + // and so we attach a dummy catch callback to avoid + // 'UnhandledPromiseRejectionWarning' log spam. + this.deferred.promise.catch((e => {})); + } + get promise() { + return this.deferred.promise; + } + /** + * Creates and returns a DelayedOperation that has been scheduled to be + * executed on the provided asyncQueue after the provided delayMs. + * + * @param asyncQueue - The queue to schedule the operation on. + * @param id - A Timer ID identifying the type of operation this is. + * @param delayMs - The delay (ms) before the operation should be scheduled. + * @param op - The operation to run. + * @param removalCallback - A callback to be called synchronously once the + * operation is executed or canceled, notifying the AsyncQueue to remove it + * from its delayedOperations list. + * PORTING NOTE: This exists to prevent making removeDelayedOperation() and + * the DelayedOperation class public. + */ static createAndSchedule(e, t, n, r, i) { + const s = Date.now() + n, o = new DelayedOperation(e, t, s, r, i); + return o.start(n), o; + } + /** + * Starts the timer. This is called immediately after construction by + * createAndSchedule(). + */ start(e) { + this.timerHandle = setTimeout((() => this.handleDelayElapsed()), e); + } + /** + * Queues the operation to run immediately (if it hasn't already been run or + * canceled). + */ skipDelay() { + return this.handleDelayElapsed(); + } + /** + * Cancels the operation if it hasn't already been executed or canceled. The + * promise will be rejected. + * + * As long as the operation has not yet been run, calling cancel() provides a + * guarantee that the operation will not be run. + */ cancel(e) { + null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new FirestoreError(N.CANCELLED, "Operation cancelled" + (e ? ": " + e : "")))); + } + handleDelayElapsed() { + this.asyncQueue.enqueueAndForget((() => null !== this.timerHandle ? (this.clearTimeout(), + this.op().then((e => this.deferred.resolve(e)))) : Promise.resolve())); + } + clearTimeout() { + null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle), + this.timerHandle = null); + } +} + +/** + * Returns a FirestoreError that can be surfaced to the user if the provided + * error is an IndexedDbTransactionError. Re-throws the error otherwise. + */ function __PRIVATE_wrapInUserErrorIfRecoverable(e, t) { + if (__PRIVATE_logError("AsyncQueue", `${t}: ${e}`), __PRIVATE_isIndexedDbTransactionError(e)) return new FirestoreError(N.UNAVAILABLE, `${t}: ${e}`); + throw e; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * DocumentSet is an immutable (copy-on-write) collection that holds documents + * in order specified by the provided comparator. We always add a document key + * comparator on top of what is provided to guarantee document equality based on + * the key. + */ class DocumentSet { + /** + * Returns an empty copy of the existing DocumentSet, using the same + * comparator. + */ + static emptySet(e) { + return new DocumentSet(e.comparator); + } + /** The default ordering is by key if the comparator is omitted */ constructor(e) { + // We are adding document key comparator to the end as it's the only + // guaranteed unique property of a document. + this.comparator = e ? (t, n) => e(t, n) || DocumentKey.comparator(t.key, n.key) : (e, t) => DocumentKey.comparator(e.key, t.key), + this.keyedMap = documentMap(), this.sortedSet = new SortedMap(this.comparator); + } + has(e) { + return null != this.keyedMap.get(e); + } + get(e) { + return this.keyedMap.get(e); + } + first() { + return this.sortedSet.minKey(); + } + last() { + return this.sortedSet.maxKey(); + } + isEmpty() { + return this.sortedSet.isEmpty(); + } + /** + * Returns the index of the provided key in the document set, or -1 if the + * document key is not present in the set; + */ indexOf(e) { + const t = this.keyedMap.get(e); + return t ? this.sortedSet.indexOf(t) : -1; + } + get size() { + return this.sortedSet.size; + } + /** Iterates documents in order defined by "comparator" */ forEach(e) { + this.sortedSet.inorderTraversal(((t, n) => (e(t), !1))); + } + /** Inserts or updates a document with the same key */ add(e) { + // First remove the element if we have it. + const t = this.delete(e.key); + return t.copy(t.keyedMap.insert(e.key, e), t.sortedSet.insert(e, null)); + } + /** Deletes a document with a given key */ delete(e) { + const t = this.get(e); + return t ? this.copy(this.keyedMap.remove(e), this.sortedSet.remove(t)) : this; + } + isEqual(e) { + if (!(e instanceof DocumentSet)) return !1; + if (this.size !== e.size) return !1; + const t = this.sortedSet.getIterator(), n = e.sortedSet.getIterator(); + for (;t.hasNext(); ) { + const e = t.getNext().key, r = n.getNext().key; + if (!e.isEqual(r)) return !1; + } + return !0; + } + toString() { + const e = []; + return this.forEach((t => { + e.push(t.toString()); + })), 0 === e.length ? "DocumentSet ()" : "DocumentSet (\n " + e.join(" \n") + "\n)"; + } + copy(e, t) { + const n = new DocumentSet; + return n.comparator = this.comparator, n.keyedMap = e, n.sortedSet = t, n; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * DocumentChangeSet keeps track of a set of changes to docs in a query, merging + * duplicate events for the same doc. + */ class __PRIVATE_DocumentChangeSet { + constructor() { + this.ga = new SortedMap(DocumentKey.comparator); + } + track(e) { + const t = e.doc.key, n = this.ga.get(t); + n ? + // Merge the new change with the existing change. + 0 /* ChangeType.Added */ !== e.type && 3 /* ChangeType.Metadata */ === n.type ? this.ga = this.ga.insert(t, e) : 3 /* ChangeType.Metadata */ === e.type && 1 /* ChangeType.Removed */ !== n.type ? this.ga = this.ga.insert(t, { + type: n.type, + doc: e.doc + }) : 2 /* ChangeType.Modified */ === e.type && 2 /* ChangeType.Modified */ === n.type ? this.ga = this.ga.insert(t, { + type: 2 /* ChangeType.Modified */ , + doc: e.doc + }) : 2 /* ChangeType.Modified */ === e.type && 0 /* ChangeType.Added */ === n.type ? this.ga = this.ga.insert(t, { + type: 0 /* ChangeType.Added */ , + doc: e.doc + }) : 1 /* ChangeType.Removed */ === e.type && 0 /* ChangeType.Added */ === n.type ? this.ga = this.ga.remove(t) : 1 /* ChangeType.Removed */ === e.type && 2 /* ChangeType.Modified */ === n.type ? this.ga = this.ga.insert(t, { + type: 1 /* ChangeType.Removed */ , + doc: n.doc + }) : 0 /* ChangeType.Added */ === e.type && 1 /* ChangeType.Removed */ === n.type ? this.ga = this.ga.insert(t, { + type: 2 /* ChangeType.Modified */ , + doc: e.doc + }) : + // This includes these cases, which don't make sense: + // Added->Added + // Removed->Removed + // Modified->Added + // Removed->Modified + // Metadata->Added + // Removed->Metadata + fail(63341, { + Rt: e, + pa: n + }) : this.ga = this.ga.insert(t, e); + } + ya() { + const e = []; + return this.ga.inorderTraversal(((t, n) => { + e.push(n); + })), e; + } +} + +class ViewSnapshot { + constructor(e, t, n, r, i, s, o, _, a) { + this.query = e, this.docs = t, this.oldDocs = n, this.docChanges = r, this.mutatedKeys = i, + this.fromCache = s, this.syncStateChanged = o, this.excludesMetadataChanges = _, + this.hasCachedResults = a; + } + /** Returns a view snapshot as if all documents in the snapshot were added. */ static fromInitialDocuments(e, t, n, r, i) { + const s = []; + return t.forEach((e => { + s.push({ + type: 0 /* ChangeType.Added */ , + doc: e + }); + })), new ViewSnapshot(e, t, DocumentSet.emptySet(t), s, n, r, + /* syncStateChanged= */ !0, + /* excludesMetadataChanges= */ !1, i); + } + get hasPendingWrites() { + return !this.mutatedKeys.isEmpty(); + } + isEqual(e) { + if (!(this.fromCache === e.fromCache && this.hasCachedResults === e.hasCachedResults && this.syncStateChanged === e.syncStateChanged && this.mutatedKeys.isEqual(e.mutatedKeys) && __PRIVATE_queryEquals(this.query, e.query) && this.docs.isEqual(e.docs) && this.oldDocs.isEqual(e.oldDocs))) return !1; + const t = this.docChanges, n = e.docChanges; + if (t.length !== n.length) return !1; + for (let e = 0; e < t.length; e++) if (t[e].type !== n[e].type || !t[e].doc.isEqual(n[e].doc)) return !1; + return !0; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Holds the listeners and the last received ViewSnapshot for a query being + * tracked by EventManager. + */ class __PRIVATE_QueryListenersInfo { + constructor() { + this.wa = void 0, this.Sa = []; + } + // Helper methods that checks if the query has listeners that listening to remote store + ba() { + return this.Sa.some((e => e.Da())); + } +} + +class __PRIVATE_EventManagerImpl { + constructor() { + this.queries = __PRIVATE_newQueriesObjectMap(), this.onlineState = "Unknown" /* OnlineState.Unknown */ , + this.Ca = new Set; + } + terminate() { + !function __PRIVATE_errorAllTargets(e, t) { + const n = __PRIVATE_debugCast(e), r = n.queries; + // Prevent further access by clearing ObjectMap. + n.queries = __PRIVATE_newQueriesObjectMap(), r.forEach(((e, n) => { + for (const e of n.Sa) e.onError(t); + })); + } + // Call all global snapshot listeners that have been set. + (this, new FirestoreError(N.ABORTED, "Firestore shutting down")); + } +} + +function __PRIVATE_newQueriesObjectMap() { + return new ObjectMap((e => __PRIVATE_canonifyQuery(e)), __PRIVATE_queryEquals); +} + +async function __PRIVATE_eventManagerListen(e, t) { + const n = __PRIVATE_debugCast(e); + let r = 3 /* ListenerSetupAction.NoActionRequired */; + const i = t.query; + let s = n.queries.get(i); + s ? !s.ba() && t.Da() && ( + // Query has been listening to local cache, and tries to add a new listener sourced from watch. + r = 2 /* ListenerSetupAction.RequireWatchConnectionOnly */) : (s = new __PRIVATE_QueryListenersInfo, + r = t.Da() ? 0 /* ListenerSetupAction.InitializeLocalListenAndRequireWatchConnection */ : 1 /* ListenerSetupAction.InitializeLocalListenOnly */); + try { + switch (r) { + case 0 /* ListenerSetupAction.InitializeLocalListenAndRequireWatchConnection */ : + s.wa = await n.onListen(i, + /** enableRemoteListen= */ !0); + break; + + case 1 /* ListenerSetupAction.InitializeLocalListenOnly */ : + s.wa = await n.onListen(i, + /** enableRemoteListen= */ !1); + break; + + case 2 /* ListenerSetupAction.RequireWatchConnectionOnly */ : + await n.onFirstRemoteStoreListen(i); + } + } catch (e) { + const n = __PRIVATE_wrapInUserErrorIfRecoverable(e, `Initialization of query '${__PRIVATE_stringifyQuery(t.query)}' failed`); + return void t.onError(n); + } + if (n.queries.set(i, s), s.Sa.push(t), + // Run global snapshot listeners if a consistent snapshot has been emitted. + t.va(n.onlineState), s.wa) { + t.Fa(s.wa) && __PRIVATE_raiseSnapshotsInSyncEvent(n); + } +} + +async function __PRIVATE_eventManagerUnlisten(e, t) { + const n = __PRIVATE_debugCast(e), r = t.query; + let i = 3 /* ListenerRemovalAction.NoActionRequired */; + const s = n.queries.get(r); + if (s) { + const e = s.Sa.indexOf(t); + e >= 0 && (s.Sa.splice(e, 1), 0 === s.Sa.length ? i = t.Da() ? 0 /* ListenerRemovalAction.TerminateLocalListenAndRequireWatchDisconnection */ : 1 /* ListenerRemovalAction.TerminateLocalListenOnly */ : !s.ba() && t.Da() && ( + // The removed listener is the last one that sourced from watch. + i = 2 /* ListenerRemovalAction.RequireWatchDisconnectionOnly */)); + } + switch (i) { + case 0 /* ListenerRemovalAction.TerminateLocalListenAndRequireWatchDisconnection */ : + return n.queries.delete(r), n.onUnlisten(r, + /** disableRemoteListen= */ !0); + + case 1 /* ListenerRemovalAction.TerminateLocalListenOnly */ : + return n.queries.delete(r), n.onUnlisten(r, + /** disableRemoteListen= */ !1); + + case 2 /* ListenerRemovalAction.RequireWatchDisconnectionOnly */ : + return n.onLastRemoteStoreUnlisten(r); + + default: + return; + } +} + +function __PRIVATE_eventManagerOnWatchChange(e, t) { + const n = __PRIVATE_debugCast(e); + let r = !1; + for (const e of t) { + const t = e.query, i = n.queries.get(t); + if (i) { + for (const t of i.Sa) t.Fa(e) && (r = !0); + i.wa = e; + } + } + r && __PRIVATE_raiseSnapshotsInSyncEvent(n); +} + +function __PRIVATE_eventManagerOnWatchError(e, t, n) { + const r = __PRIVATE_debugCast(e), i = r.queries.get(t); + if (i) for (const e of i.Sa) e.onError(n); + // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten() + // after an error. + r.queries.delete(t); +} + +function __PRIVATE_raiseSnapshotsInSyncEvent(e) { + e.Ca.forEach((e => { + e.next(); + })); +} + +var nn, rn; + +/** Listen to both cache and server changes */ +(rn = nn || (nn = {})).Ma = "default", +/** Listen to changes in cache only */ +rn.Cache = "cache"; + +/** + * QueryListener takes a series of internal view snapshots and determines + * when to raise the event. + * + * It uses an Observer to dispatch events. + */ +class __PRIVATE_QueryListener { + constructor(e, t, n) { + this.query = e, this.xa = t, + /** + * Initial snapshots (e.g. from cache) may not be propagated to the wrapped + * observer. This flag is set to true once we've actually raised an event. + */ + this.Oa = !1, this.Na = null, this.onlineState = "Unknown" /* OnlineState.Unknown */ , + this.options = n || {}; + } + /** + * Applies the new ViewSnapshot to this listener, raising a user-facing event + * if applicable (depending on what changed, whether the user has opted into + * metadata-only changes, etc.). Returns true if a user-facing event was + * indeed raised. + */ Fa(e) { + if (!this.options.includeMetadataChanges) { + // Remove the metadata only changes. + const t = []; + for (const n of e.docChanges) 3 /* ChangeType.Metadata */ !== n.type && t.push(n); + e = new ViewSnapshot(e.query, e.docs, e.oldDocs, t, e.mutatedKeys, e.fromCache, e.syncStateChanged, + /* excludesMetadataChanges= */ !0, e.hasCachedResults); + } + let t = !1; + return this.Oa ? this.Ba(e) && (this.xa.next(e), t = !0) : this.La(e, this.onlineState) && (this.ka(e), + t = !0), this.Na = e, t; + } + onError(e) { + this.xa.error(e); + } + /** Returns whether a snapshot was raised. */ va(e) { + this.onlineState = e; + let t = !1; + return this.Na && !this.Oa && this.La(this.Na, e) && (this.ka(this.Na), t = !0), + t; + } + La(e, t) { + // Always raise the first event when we're synced + if (!e.fromCache) return !0; + // Always raise event if listening to cache + if (!this.Da()) return !0; + // NOTE: We consider OnlineState.Unknown as online (it should become Offline + // or Online if we wait long enough). + const n = "Offline" /* OnlineState.Offline */ !== t; + // Don't raise the event if we're online, aren't synced yet (checked + // above) and are waiting for a sync. + return (!this.options.qa || !n) && (!e.docs.isEmpty() || e.hasCachedResults || "Offline" /* OnlineState.Offline */ === t); + // Raise data from cache if we have any documents, have cached results before, + // or we are offline. + } + Ba(e) { + // We don't need to handle includeDocumentMetadataChanges here because + // the Metadata only changes have already been stripped out if needed. + // At this point the only changes we will see are the ones we should + // propagate. + if (e.docChanges.length > 0) return !0; + const t = this.Na && this.Na.hasPendingWrites !== e.hasPendingWrites; + return !(!e.syncStateChanged && !t) && !0 === this.options.includeMetadataChanges; + // Generally we should have hit one of the cases above, but it's possible + // to get here if there were only metadata docChanges and they got + // stripped out. + } + ka(e) { + e = ViewSnapshot.fromInitialDocuments(e.query, e.docs, e.mutatedKeys, e.fromCache, e.hasCachedResults), + this.Oa = !0, this.xa.next(e); + } + Da() { + return this.options.source !== nn.Cache; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A complete element in the bundle stream, together with the byte length it + * occupies in the stream. + */ class __PRIVATE_SizedBundleElement { + constructor(e, + // How many bytes this element takes to store in the bundle. + t) { + this.Qa = e, this.byteLength = t; + } + $a() { + return "metadata" in this.Qa; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Helper to convert objects from bundles to model objects in the SDK. + */ class __PRIVATE_BundleConverterImpl { + constructor(e) { + this.serializer = e; + } + $s(e) { + return fromName(this.serializer, e); + } + /** + * Converts a BundleDocument to a MutableDocument. + */ Us(e) { + return e.metadata.exists ? __PRIVATE_fromDocument(this.serializer, e.document, !1) : MutableDocument.newNoDocument(this.$s(e.metadata.name), this.Ks(e.metadata.readTime)); + } + Ks(e) { + return __PRIVATE_fromVersion(e); + } +} + +/** + * A class to process the elements from a bundle, and optionally load them into local + * storage and provide progress update while loading. + */ class __PRIVATE_BundleLoader { + constructor(e, t) { + this.Ua = e, this.serializer = t, + /** Batched queries to be saved into storage */ + this.Ka = [], + /** Batched documents to be saved into storage */ + this.Wa = [], + /** The collection groups affected by this bundle. */ + this.collectionGroups = new Set, this.progress = __PRIVATE_bundleInitialProgress(e); + } + /** + * Returns the named queries that have been parsed from the SizeBundleElements added by + * calling {@link adSizedElement}. + */ get queries() { + return this.Ka; + } + /** + * Returns the BundledDocuments that have been parsed from the SizeBundleElements added by + * calling {@link addSizedElement}. + */ get documents() { + return this.Wa; + } + /** + * Adds an element from the bundle to the loader. + * + * Returns a new progress if adding the element leads to a new progress, + * otherwise returns null. + */ Ga(e) { + this.progress.bytesLoaded += e.byteLength; + let t = this.progress.documentsLoaded; + if (e.Qa.namedQuery) this.Ka.push(e.Qa.namedQuery); else if (e.Qa.documentMetadata) { + this.Wa.push({ + metadata: e.Qa.documentMetadata + }), e.Qa.documentMetadata.exists || ++t; + const n = ResourcePath.fromString(e.Qa.documentMetadata.name); + this.collectionGroups.add(n.get(n.length - 2)); + } else e.Qa.document && (this.Wa[this.Wa.length - 1].document = e.Qa.document, ++t); + return t !== this.progress.documentsLoaded ? (this.progress.documentsLoaded = t, + { + ...this.progress + }) : null; + } + za(e) { + const t = new Map, n = new __PRIVATE_BundleConverterImpl(this.serializer); + for (const r of e) if (r.metadata.queries) { + const e = n.$s(r.metadata.name); + for (const n of r.metadata.queries) { + const r = (t.get(n) || __PRIVATE_documentKeySet()).add(e); + t.set(n, r); + } + } + return t; + } + /** + * Update the progress to 'Success' and return the updated progress. + */ async ja(e) { + const t = await __PRIVATE_localStoreApplyBundledDocuments(e, new __PRIVATE_BundleConverterImpl(this.serializer), this.Wa, this.Ua.id), n = this.za(this.documents); + for (const t of this.Ka) await __PRIVATE_localStoreSaveNamedQuery(e, t, n.get(t.name)); + return this.progress.taskState = "Success", { + progress: this.progress, + Ja: this.collectionGroups, + Ha: t + }; + } +} + +/** + * Returns a `LoadBundleTaskProgress` representing the initial progress of + * loading a bundle. + */ function __PRIVATE_bundleInitialProgress(e) { + return { + taskState: "Running", + documentsLoaded: 0, + bytesLoaded: 0, + totalDocuments: e.totalDocuments, + totalBytes: e.totalBytes + }; +} + +/** + * Returns a `LoadBundleTaskProgress` representing the progress that the loading + * has succeeded. + */ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class __PRIVATE_AddedLimboDocument { + constructor(e) { + this.key = e; + } +} + +class __PRIVATE_RemovedLimboDocument { + constructor(e) { + this.key = e; + } +} + +/** + * View is responsible for computing the final merged truth of what docs are in + * a query. It gets notified of local and remote changes to docs, and applies + * the query filters and limits to determine the most correct possible results. + */ class __PRIVATE_View { + constructor(e, + /** Documents included in the remote target */ + t) { + this.query = e, this.Ya = t, this.Za = null, this.hasCachedResults = !1, + /** + * A flag whether the view is current with the backend. A view is considered + * current after it has seen the current flag from the backend and did not + * lose consistency within the watch stream (e.g. because of an existence + * filter mismatch). + */ + this.current = !1, + /** Documents in the view but not in the remote target */ + this.Xa = __PRIVATE_documentKeySet(), + /** Document Keys that have local changes */ + this.mutatedKeys = __PRIVATE_documentKeySet(), this.eu = __PRIVATE_newQueryComparator(e), + this.tu = new DocumentSet(this.eu); + } + /** + * The set of remote documents that the server has told us belongs to the target associated with + * this view. + */ get nu() { + return this.Ya; + } + /** + * Iterates over a set of doc changes, applies the query limit, and computes + * what the new results should be, what the changes were, and whether we may + * need to go back to the local cache for more results. Does not make any + * changes to the view. + * @param docChanges - The doc changes to apply to this view. + * @param previousChanges - If this is being called with a refill, then start + * with this set of docs and changes instead of the current view. + * @returns a new set of docs, changes, and refill flag. + */ ru(e, t) { + const n = t ? t.iu : new __PRIVATE_DocumentChangeSet, r = t ? t.tu : this.tu; + let i = t ? t.mutatedKeys : this.mutatedKeys, s = r, o = !1; + // Track the last doc in a (full) limit. This is necessary, because some + // update (a delete, or an update moving a doc past the old limit) might + // mean there is some other document in the local cache that either should + // come (1) between the old last limit doc and the new last document, in the + // case of updates, or (2) after the new last document, in the case of + // deletes. So we keep this doc at the old limit to compare the updates to. + // Note that this should never get used in a refill (when previousChanges is + // set), because there will only be adds -- no deletes or updates. + const _ = "F" /* LimitType.First */ === this.query.limitType && r.size === this.query.limit ? r.last() : null, a = "L" /* LimitType.Last */ === this.query.limitType && r.size === this.query.limit ? r.first() : null; + // Drop documents out to meet limit/limitToLast requirement. + if (e.inorderTraversal(((e, t) => { + const u = r.get(e), c = __PRIVATE_queryMatches(this.query, t) ? t : null, l = !!u && this.mutatedKeys.has(u.key), h = !!c && (c.hasLocalMutations || + // We only consider committed mutations for documents that were + // mutated during the lifetime of the view. + this.mutatedKeys.has(c.key) && c.hasCommittedMutations); + let P = !1; + // Calculate change + if (u && c) { + u.data.isEqual(c.data) ? l !== h && (n.track({ + type: 3 /* ChangeType.Metadata */ , + doc: c + }), P = !0) : this.su(u, c) || (n.track({ + type: 2 /* ChangeType.Modified */ , + doc: c + }), P = !0, (_ && this.eu(c, _) > 0 || a && this.eu(c, a) < 0) && ( + // This doc moved from inside the limit to outside the limit. + // That means there may be some other doc in the local cache + // that should be included instead. + o = !0)); + } else !u && c ? (n.track({ + type: 0 /* ChangeType.Added */ , + doc: c + }), P = !0) : u && !c && (n.track({ + type: 1 /* ChangeType.Removed */ , + doc: u + }), P = !0, (_ || a) && ( + // A doc was removed from a full limit query. We'll need to + // requery from the local cache to see if we know about some other + // doc that should be in the results. + o = !0)); + P && (c ? (s = s.add(c), i = h ? i.add(e) : i.delete(e)) : (s = s.delete(e), i = i.delete(e))); + })), null !== this.query.limit) for (;s.size > this.query.limit; ) { + const e = "F" /* LimitType.First */ === this.query.limitType ? s.last() : s.first(); + s = s.delete(e.key), i = i.delete(e.key), n.track({ + type: 1 /* ChangeType.Removed */ , + doc: e + }); + } + return { + tu: s, + iu: n, + Cs: o, + mutatedKeys: i + }; + } + su(e, t) { + // We suppress the initial change event for documents that were modified as + // part of a write acknowledgment (e.g. when the value of a server transform + // is applied) as Watch will send us the same document again. + // By suppressing the event, we only raise two user visible events (one with + // `hasPendingWrites` and the final state of the document) instead of three + // (one with `hasPendingWrites`, the modified document with + // `hasPendingWrites` and the final state of the document). + return e.hasLocalMutations && t.hasCommittedMutations && !t.hasLocalMutations; + } + /** + * Updates the view with the given ViewDocumentChanges and optionally updates + * limbo docs and sync state from the provided target change. + * @param docChanges - The set of changes to make to the view's docs. + * @param limboResolutionEnabled - Whether to update limbo documents based on + * this change. + * @param targetChange - A target change to apply for computing limbo docs and + * sync state. + * @param targetIsPendingReset - Whether the target is pending to reset due to + * existence filter mismatch. If not explicitly specified, it is treated + * equivalently to `false`. + * @returns A new ViewChange with the given docs, changes, and sync state. + */ + // PORTING NOTE: The iOS/Android clients always compute limbo document changes. + applyChanges(e, t, n, r) { + const i = this.tu; + this.tu = e.tu, this.mutatedKeys = e.mutatedKeys; + // Sort changes based on type and query comparator + const s = e.iu.ya(); + s.sort(((e, t) => function __PRIVATE_compareChangeType(e, t) { + const order = e => { + switch (e) { + case 0 /* ChangeType.Added */ : + return 1; + + case 2 /* ChangeType.Modified */ : + case 3 /* ChangeType.Metadata */ : + // A metadata change is converted to a modified change at the public + // api layer. Since we sort by document key and then change type, + // metadata and modified changes must be sorted equivalently. + return 2; + + case 1 /* ChangeType.Removed */ : + return 0; + + default: + return fail(20277, { + Rt: e + }); + } + }; + return order(e) - order(t); + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ (e.type, t.type) || this.eu(e.doc, t.doc))), this.ou(n), r = r ?? !1; + const o = t && !r ? this._u() : [], _ = 0 === this.Xa.size && this.current && !r ? 1 /* SyncState.Synced */ : 0 /* SyncState.Local */ , a = _ !== this.Za; + // We are at synced state if there is no limbo docs are waiting to be resolved, view is current + // with the backend, and the query is not pending to reset due to existence filter mismatch. + if (this.Za = _, 0 !== s.length || a) { + return { + snapshot: new ViewSnapshot(this.query, e.tu, i, s, e.mutatedKeys, 0 /* SyncState.Local */ === _, a, + /* excludesMetadataChanges= */ !1, !!n && n.resumeToken.approximateByteSize() > 0), + au: o + }; + } + // no changes + return { + au: o + }; + } + /** + * Applies an OnlineState change to the view, potentially generating a + * ViewChange if the view's syncState changes as a result. + */ va(e) { + return this.current && "Offline" /* OnlineState.Offline */ === e ? ( + // If we're offline, set `current` to false and then call applyChanges() + // to refresh our syncState and generate a ViewChange as appropriate. We + // are guaranteed to get a new TargetChange that sets `current` back to + // true once the client is back online. + this.current = !1, this.applyChanges({ + tu: this.tu, + iu: new __PRIVATE_DocumentChangeSet, + mutatedKeys: this.mutatedKeys, + Cs: !1 + }, + /* limboResolutionEnabled= */ !1)) : { + au: [] + }; + } + /** + * Returns whether the doc for the given key should be in limbo. + */ uu(e) { + // If the remote end says it's part of this query, it's not in limbo. + return !this.Ya.has(e) && ( + // The local store doesn't think it's a result, so it shouldn't be in limbo. + !!this.tu.has(e) && !this.tu.get(e).hasLocalMutations); + } + /** + * Updates syncedDocuments, current, and limbo docs based on the given change. + * Returns the list of changes to which docs are in limbo. + */ ou(e) { + e && (e.addedDocuments.forEach((e => this.Ya = this.Ya.add(e))), e.modifiedDocuments.forEach((e => {})), + e.removedDocuments.forEach((e => this.Ya = this.Ya.delete(e))), this.current = e.current); + } + _u() { + // We can only determine limbo documents when we're in-sync with the server. + if (!this.current) return []; + // TODO(klimt): Do this incrementally so that it's not quadratic when + // updating many documents. + const e = this.Xa; + this.Xa = __PRIVATE_documentKeySet(), this.tu.forEach((e => { + this.uu(e.key) && (this.Xa = this.Xa.add(e.key)); + })); + // Diff the new limbo docs with the old limbo docs. + const t = []; + return e.forEach((e => { + this.Xa.has(e) || t.push(new __PRIVATE_RemovedLimboDocument(e)); + })), this.Xa.forEach((n => { + e.has(n) || t.push(new __PRIVATE_AddedLimboDocument(n)); + })), t; + } + /** + * Update the in-memory state of the current view with the state read from + * persistence. + * + * We update the query view whenever a client's primary status changes: + * - When a client transitions from primary to secondary, it can miss + * LocalStorage updates and its query views may temporarily not be + * synchronized with the state on disk. + * - For secondary to primary transitions, the client needs to update the list + * of `syncedDocuments` since secondary clients update their query views + * based purely on synthesized RemoteEvents. + * + * @param queryResult.documents - The documents that match the query according + * to the LocalStore. + * @param queryResult.remoteKeys - The keys of the documents that match the + * query according to the backend. + * + * @returns The ViewChange that resulted from this synchronization. + */ + // PORTING NOTE: Multi-tab only. + cu(e) { + this.Ya = e.Qs, this.Xa = __PRIVATE_documentKeySet(); + const t = this.ru(e.documents); + return this.applyChanges(t, /* limboResolutionEnabled= */ !0); + } + /** + * Returns a view snapshot as if this query was just listened to. Contains + * a document add for every existing document and the `fromCache` and + * `hasPendingWrites` status of the already established view. + */ + // PORTING NOTE: Multi-tab only. + lu() { + return ViewSnapshot.fromInitialDocuments(this.query, this.tu, this.mutatedKeys, 0 /* SyncState.Local */ === this.Za, this.hasCachedResults); + } +} + +const sn = "SyncEngine"; + +/** + * QueryView contains all of the data that SyncEngine needs to keep track of for + * a particular query. + */ class __PRIVATE_QueryView { + constructor( + /** + * The query itself. + */ + e, + /** + * The target number created by the client that is used in the watch + * stream to identify this query. + */ + t, + /** + * The view is responsible for computing the final merged truth of what + * docs are in the query. It gets notified of local and remote changes, + * and applies the query filters and limits to determine the most correct + * possible results. + */ + n) { + this.query = e, this.targetId = t, this.view = n; + } +} + +/** Tracks a limbo resolution. */ class LimboResolution { + constructor(e) { + this.key = e, + /** + * Set to true once we've received a document. This is used in + * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to + * decide whether it needs to manufacture a delete event for the target once + * the target is CURRENT. + */ + this.hu = !1; + } +} + +/** + * An implementation of `SyncEngine` coordinating with other parts of SDK. + * + * The parts of SyncEngine that act as a callback to RemoteStore need to be + * registered individually. This is done in `syncEngineWrite()` and + * `syncEngineListen()` (as well as `applyPrimaryState()`) as these methods + * serve as entry points to RemoteStore's functionality. + * + * Note: some field defined in this class might have public access level, but + * the class is not exported so they are only accessible from this module. + * This is useful to implement optional features (like bundles) in free + * functions, such that they are tree-shakeable. + */ class __PRIVATE_SyncEngineImpl { + constructor(e, t, n, + // PORTING NOTE: Manages state synchronization in multi-tab environments. + r, i, s) { + this.localStore = e, this.remoteStore = t, this.eventManager = n, this.sharedClientState = r, + this.currentUser = i, this.maxConcurrentLimboResolutions = s, this.Pu = {}, this.Tu = new ObjectMap((e => __PRIVATE_canonifyQuery(e)), __PRIVATE_queryEquals), + this.Iu = new Map, + /** + * The keys of documents that are in limbo for which we haven't yet started a + * limbo resolution query. The strings in this set are the result of calling + * `key.path.canonicalString()` where `key` is a `DocumentKey` object. + * + * The `Set` type was chosen because it provides efficient lookup and removal + * of arbitrary elements and it also maintains insertion order, providing the + * desired queue-like FIFO semantics. + */ + this.Eu = new Set, + /** + * Keeps track of the target ID for each document that is in limbo with an + * active target. + */ + this.du = new SortedMap(DocumentKey.comparator), + /** + * Keeps track of the information about an active limbo resolution for each + * active target ID that was started for the purpose of limbo resolution. + */ + this.Au = new Map, this.Ru = new __PRIVATE_ReferenceSet, + /** Stores user completion handlers, indexed by User and BatchId. */ + this.Vu = {}, + /** Stores user callbacks waiting for all pending writes to be acknowledged. */ + this.mu = new Map, this.fu = __PRIVATE_TargetIdGenerator.cr(), this.onlineState = "Unknown" /* OnlineState.Unknown */ , + // The primary state is set to `true` or `false` immediately after Firestore + // startup. In the interim, a client should only be considered primary if + // `isPrimary` is true. + this.gu = void 0; + } + get isPrimaryClient() { + return !0 === this.gu; + } +} + +/** + * Initiates the new listen, resolves promise when listen enqueued to the + * server. All the subsequent view snapshots or errors are sent to the + * subscribed handlers. Returns the initial snapshot. + */ +async function __PRIVATE_syncEngineListen(e, t, n = !0) { + const r = __PRIVATE_ensureWatchCallbacks(e); + let i; + const s = r.Tu.get(t); + return s ? ( + // PORTING NOTE: With Multi-Tab Web, it is possible that a query view + // already exists when EventManager calls us for the first time. This + // happens when the primary tab is already listening to this query on + // behalf of another tab and the user of the primary also starts listening + // to the query. EventManager will not have an assigned target ID in this + // case and calls `listen` to obtain this ID. + r.sharedClientState.addLocalQueryTarget(s.targetId), i = s.view.lu()) : i = await __PRIVATE_allocateTargetAndMaybeListen(r, t, n, + /** shouldInitializeView= */ !0), i; +} + +/** Query has been listening to the cache, and tries to initiate the remote store listen */ async function __PRIVATE_triggerRemoteStoreListen(e, t) { + const n = __PRIVATE_ensureWatchCallbacks(e); + await __PRIVATE_allocateTargetAndMaybeListen(n, t, + /** shouldListenToRemote= */ !0, + /** shouldInitializeView= */ !1); +} + +async function __PRIVATE_allocateTargetAndMaybeListen(e, t, n, r) { + const i = await __PRIVATE_localStoreAllocateTarget(e.localStore, __PRIVATE_queryToTarget(t)), s = i.targetId, o = e.sharedClientState.addLocalQueryTarget(s, n); + let _; + return r && (_ = await __PRIVATE_initializeViewAndComputeSnapshot(e, t, s, "current" === o, i.resumeToken)), + e.isPrimaryClient && n && __PRIVATE_remoteStoreListen(e.remoteStore, i), _; +} + +/** + * Registers a view for a previously unknown query and computes its initial + * snapshot. + */ async function __PRIVATE_initializeViewAndComputeSnapshot(e, t, n, r, i) { + // PORTING NOTE: On Web only, we inject the code that registers new Limbo + // targets based on view changes. This allows us to only depend on Limbo + // changes when user code includes queries. + e.pu = (t, n, r) => async function __PRIVATE_applyDocChanges(e, t, n, r) { + let i = t.view.ru(n); + i.Cs && ( + // The query has a limit and some docs were removed, so we need + // to re-run the query against the local store to make sure we + // didn't lose any good docs that had been past the limit. + i = await __PRIVATE_localStoreExecuteQuery(e.localStore, t.query, + /* usePreviousResults= */ !1).then((({documents: e}) => t.view.ru(e, i)))); + const s = r && r.targetChanges.get(t.targetId), o = r && null != r.targetMismatches.get(t.targetId), _ = t.view.applyChanges(i, + /* limboResolutionEnabled= */ e.isPrimaryClient, s, o); + return __PRIVATE_updateTrackedLimbos(e, t.targetId, _.au), _.snapshot; + }(e, t, n, r); + const s = await __PRIVATE_localStoreExecuteQuery(e.localStore, t, + /* usePreviousResults= */ !0), o = new __PRIVATE_View(t, s.Qs), _ = o.ru(s.documents), a = TargetChange.createSynthesizedTargetChangeForCurrentChange(n, r && "Offline" /* OnlineState.Offline */ !== e.onlineState, i), u = o.applyChanges(_, + /* limboResolutionEnabled= */ e.isPrimaryClient, a); + __PRIVATE_updateTrackedLimbos(e, n, u.au); + const c = new __PRIVATE_QueryView(t, n, o); + return e.Tu.set(t, c), e.Iu.has(n) ? e.Iu.get(n).push(t) : e.Iu.set(n, [ t ]), u.snapshot; +} + +/** Stops listening to the query. */ async function __PRIVATE_syncEngineUnlisten(e, t, n) { + const r = __PRIVATE_debugCast(e), i = r.Tu.get(t), s = r.Iu.get(i.targetId); + if (s.length > 1) return r.Iu.set(i.targetId, s.filter((e => !__PRIVATE_queryEquals(e, t)))), + void r.Tu.delete(t); + // No other queries are mapped to the target, clean up the query and the target. + if (r.isPrimaryClient) { + // We need to remove the local query target first to allow us to verify + // whether any other client is still interested in this target. + r.sharedClientState.removeLocalQueryTarget(i.targetId); + r.sharedClientState.isActiveQueryTarget(i.targetId) || await __PRIVATE_localStoreReleaseTarget(r.localStore, i.targetId, + /*keepPersistedTargetData=*/ !1).then((() => { + r.sharedClientState.clearQueryState(i.targetId), n && __PRIVATE_remoteStoreUnlisten(r.remoteStore, i.targetId), + __PRIVATE_removeAndCleanupTarget(r, i.targetId); + })).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss); + } else __PRIVATE_removeAndCleanupTarget(r, i.targetId), await __PRIVATE_localStoreReleaseTarget(r.localStore, i.targetId, + /*keepPersistedTargetData=*/ !0); +} + +/** Unlistens to the remote store while still listening to the cache. */ async function __PRIVATE_triggerRemoteStoreUnlisten(e, t) { + const n = __PRIVATE_debugCast(e), r = n.Tu.get(t), i = n.Iu.get(r.targetId); + n.isPrimaryClient && 1 === i.length && ( + // PORTING NOTE: Unregister the target ID with local Firestore client as + // watch target. + n.sharedClientState.removeLocalQueryTarget(r.targetId), __PRIVATE_remoteStoreUnlisten(n.remoteStore, r.targetId)); +} + +/** + * Initiates the write of local mutation batch which involves adding the + * writes to the mutation queue, notifying the remote store about new + * mutations and raising events for any changes this write caused. + * + * The promise returned by this call is resolved when the above steps + * have completed, *not* when the write was acked by the backend. The + * userCallback is resolved once the write was acked/rejected by the + * backend (or failed locally for any other reason). + */ async function __PRIVATE_syncEngineWrite(e, t, n) { + const r = __PRIVATE_syncEngineEnsureWriteCallbacks(e); + try { + const e = await function __PRIVATE_localStoreWriteLocally(e, t) { + const n = __PRIVATE_debugCast(e), r = Timestamp.now(), i = t.reduce(((e, t) => e.add(t.key)), __PRIVATE_documentKeySet()); + let s, o; + return n.persistence.runTransaction("Locally write mutations", "readwrite", (e => { + // Figure out which keys do not have a remote version in the cache, this + // is needed to create the right overlay mutation: if no remote version + // presents, we do not need to create overlays as patch mutations. + // TODO(Overlay): Is there a better way to determine this? Using the + // document version does not work because local mutations set them back + // to 0. + let _ = __PRIVATE_mutableDocumentMap(), a = __PRIVATE_documentKeySet(); + return n.Ns.getEntries(e, i).next((e => { + _ = e, _.forEach(((e, t) => { + t.isValidDocument() || (a = a.add(e)); + })); + })).next((() => n.localDocuments.getOverlayedDocuments(e, _))).next((i => { + s = i; + // For non-idempotent mutations (such as `FieldValue.increment()`), + // we record the base state in a separate patch mutation. This is + // later used to guarantee consistent values and prevents flicker + // even if the backend sends us an update that already includes our + // transform. + const o = []; + for (const e of t) { + const t = __PRIVATE_mutationExtractBaseValue(e, s.get(e.key).overlayedDocument); + null != t && + // NOTE: The base state should only be applied if there's some + // existing document to override, so use a Precondition of + // exists=true + o.push(new __PRIVATE_PatchMutation(e.key, t, __PRIVATE_extractFieldMask(t.value.mapValue), Precondition.exists(!0))); + } + return n.mutationQueue.addMutationBatch(e, r, o, t); + })).next((t => { + o = t; + const r = t.applyToLocalDocumentSet(s, a); + return n.documentOverlayCache.saveOverlays(e, t.batchId, r); + })); + })).then((() => ({ + batchId: o.batchId, + changes: __PRIVATE_convertOverlayedDocumentMapToDocumentMap(s) + }))); + }(r.localStore, t); + r.sharedClientState.addPendingMutation(e.batchId), function __PRIVATE_addMutationCallback(e, t, n) { + let r = e.Vu[e.currentUser.toKey()]; + r || (r = new SortedMap(__PRIVATE_primitiveComparator)); + r = r.insert(t, n), e.Vu[e.currentUser.toKey()] = r; + } + /** + * Resolves or rejects the user callback for the given batch and then discards + * it. + */ (r, e.batchId, n), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(r, e.changes), + await __PRIVATE_fillWritePipeline(r.remoteStore); + } catch (e) { + // If we can't persist the mutation, we reject the user callback and + // don't send the mutation. The user can then retry the write. + const t = __PRIVATE_wrapInUserErrorIfRecoverable(e, "Failed to persist write"); + n.reject(t); + } +} + +/** + * Applies one remote event to the sync engine, notifying any views of the + * changes, and releasing any pending mutation batches that would become + * visible because of the snapshot version the remote event contains. + */ async function __PRIVATE_syncEngineApplyRemoteEvent(e, t) { + const n = __PRIVATE_debugCast(e); + try { + const e = await __PRIVATE_localStoreApplyRemoteEventToLocalCache(n.localStore, t); + // Update `receivedDocument` as appropriate for any limbo targets. + t.targetChanges.forEach(((e, t) => { + const r = n.Au.get(t); + r && ( + // Since this is a limbo resolution lookup, it's for a single document + // and it could be added, modified, or removed, but not a combination. + __PRIVATE_hardAssert(e.addedDocuments.size + e.modifiedDocuments.size + e.removedDocuments.size <= 1, 22616), + e.addedDocuments.size > 0 ? r.hu = !0 : e.modifiedDocuments.size > 0 ? __PRIVATE_hardAssert(r.hu, 14607) : e.removedDocuments.size > 0 && (__PRIVATE_hardAssert(r.hu, 42227), + r.hu = !1)); + })), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e, t); + } catch (e) { + await __PRIVATE_ignoreIfPrimaryLeaseLoss(e); + } +} + +/** + * Applies an OnlineState change to the sync engine and notifies any views of + * the change. + */ function __PRIVATE_syncEngineApplyOnlineStateChange(e, t, n) { + const r = __PRIVATE_debugCast(e); + // If we are the secondary client, we explicitly ignore the remote store's + // online state (the local client may go offline, even though the primary + // tab remains online) and only apply the primary tab's online state from + // SharedClientState. + if (r.isPrimaryClient && 0 /* OnlineStateSource.RemoteStore */ === n || !r.isPrimaryClient && 1 /* OnlineStateSource.SharedClientState */ === n) { + const e = []; + r.Tu.forEach(((n, r) => { + const i = r.view.va(t); + i.snapshot && e.push(i.snapshot); + })), function __PRIVATE_eventManagerOnOnlineStateChange(e, t) { + const n = __PRIVATE_debugCast(e); + n.onlineState = t; + let r = !1; + n.queries.forEach(((e, n) => { + for (const e of n.Sa) + // Run global snapshot listeners if a consistent snapshot has been emitted. + e.va(t) && (r = !0); + })), r && __PRIVATE_raiseSnapshotsInSyncEvent(n); + }(r.eventManager, t), e.length && r.Pu.H_(e), r.onlineState = t, r.isPrimaryClient && r.sharedClientState.setOnlineState(t); + } +} + +/** + * Rejects the listen for the given targetID. This can be triggered by the + * backend for any active target. + * + * @param syncEngine - The sync engine implementation. + * @param targetId - The targetID corresponds to one previously initiated by the + * user as part of TargetData passed to listen() on RemoteStore. + * @param err - A description of the condition that has forced the rejection. + * Nearly always this will be an indication that the user is no longer + * authorized to see the data matching the target. + */ async function __PRIVATE_syncEngineRejectListen(e, t, n) { + const r = __PRIVATE_debugCast(e); + // PORTING NOTE: Multi-tab only. + r.sharedClientState.updateQueryState(t, "rejected", n); + const i = r.Au.get(t), s = i && i.key; + if (s) { + // TODO(klimt): We really only should do the following on permission + // denied errors, but we don't have the cause code here. + // It's a limbo doc. Create a synthetic event saying it was deleted. + // This is kind of a hack. Ideally, we would have a method in the local + // store to purge a document. However, it would be tricky to keep all of + // the local store's invariants with another method. + let e = new SortedMap(DocumentKey.comparator); + // TODO(b/217189216): This limbo document should ideally have a read time, + // so that it is picked up by any read-time based scans. The backend, + // however, does not send a read time for target removals. + e = e.insert(s, MutableDocument.newNoDocument(s, SnapshotVersion.min())); + const n = __PRIVATE_documentKeySet().add(s), i = new RemoteEvent(SnapshotVersion.min(), + /* targetChanges= */ new Map, + /* targetMismatches= */ new SortedMap(__PRIVATE_primitiveComparator), e, n); + await __PRIVATE_syncEngineApplyRemoteEvent(r, i), + // Since this query failed, we won't want to manually unlisten to it. + // We only remove it from bookkeeping after we successfully applied the + // RemoteEvent. If `applyRemoteEvent()` throws, we want to re-listen to + // this query when the RemoteStore restarts the Watch stream, which should + // re-trigger the target failure. + r.du = r.du.remove(s), r.Au.delete(t), __PRIVATE_pumpEnqueuedLimboResolutions(r); + } else await __PRIVATE_localStoreReleaseTarget(r.localStore, t, + /* keepPersistedTargetData */ !1).then((() => __PRIVATE_removeAndCleanupTarget(r, t, n))).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss); +} + +async function __PRIVATE_syncEngineApplySuccessfulWrite(e, t) { + const n = __PRIVATE_debugCast(e), r = t.batch.batchId; + try { + const e = await __PRIVATE_localStoreAcknowledgeBatch(n.localStore, t); + // The local store may or may not be able to apply the write result and + // raise events immediately (depending on whether the watcher is caught + // up), so we raise user callbacks first so that they consistently happen + // before listen events. + __PRIVATE_processUserCallback(n, r, /*error=*/ null), __PRIVATE_triggerPendingWritesCallbacks(n, r), + n.sharedClientState.updateMutationState(r, "acknowledged"), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e); + } catch (e) { + await __PRIVATE_ignoreIfPrimaryLeaseLoss(e); + } +} + +async function __PRIVATE_syncEngineRejectFailedWrite(e, t, n) { + const r = __PRIVATE_debugCast(e); + try { + const e = await function __PRIVATE_localStoreRejectBatch(e, t) { + const n = __PRIVATE_debugCast(e); + return n.persistence.runTransaction("Reject batch", "readwrite-primary", (e => { + let r; + return n.mutationQueue.lookupMutationBatch(e, t).next((t => (__PRIVATE_hardAssert(null !== t, 37113), + r = t.keys(), n.mutationQueue.removeMutationBatch(e, t)))).next((() => n.mutationQueue.performConsistencyCheck(e))).next((() => n.documentOverlayCache.removeOverlaysForBatchId(e, r, t))).next((() => n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e, r))).next((() => n.localDocuments.getDocuments(e, r))); + })); + } + /** + * Returns the largest (latest) batch id in mutation queue that is pending + * server response. + * + * Returns `BATCHID_UNKNOWN` if the queue is empty. + */ (r.localStore, t); + // The local store may or may not be able to apply the write result and + // raise events immediately (depending on whether the watcher is caught up), + // so we raise user callbacks first so that they consistently happen before + // listen events. + __PRIVATE_processUserCallback(r, t, n), __PRIVATE_triggerPendingWritesCallbacks(r, t), + r.sharedClientState.updateMutationState(t, "rejected", n), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(r, e); + } catch (n) { + await __PRIVATE_ignoreIfPrimaryLeaseLoss(n); + } +} + +/** + * Registers a user callback that resolves when all pending mutations at the moment of calling + * are acknowledged . + */ async function __PRIVATE_syncEngineRegisterPendingWritesCallback(e, t) { + const n = __PRIVATE_debugCast(e); + __PRIVATE_canUseNetwork(n.remoteStore) || __PRIVATE_logDebug(sn, "The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled."); + try { + const e = await function __PRIVATE_localStoreGetHighestUnacknowledgedBatchId(e) { + const t = __PRIVATE_debugCast(e); + return t.persistence.runTransaction("Get highest unacknowledged batch id", "readonly", (e => t.mutationQueue.getHighestUnacknowledgedBatchId(e))); + }(n.localStore); + if (e === j) + // Trigger the callback right away if there is no pending writes at the moment. + return void t.resolve(); + const r = n.mu.get(e) || []; + r.push(t), n.mu.set(e, r); + } catch (e) { + const n = __PRIVATE_wrapInUserErrorIfRecoverable(e, "Initialization of waitForPendingWrites() operation failed"); + t.reject(n); + } +} + +/** + * Triggers the callbacks that are waiting for this batch id to get acknowledged by server, + * if there are any. + */ function __PRIVATE_triggerPendingWritesCallbacks(e, t) { + (e.mu.get(t) || []).forEach((e => { + e.resolve(); + })), e.mu.delete(t); +} + +/** Reject all outstanding callbacks waiting for pending writes to complete. */ function __PRIVATE_processUserCallback(e, t, n) { + const r = __PRIVATE_debugCast(e); + let i = r.Vu[r.currentUser.toKey()]; + // NOTE: Mutations restored from persistence won't have callbacks, so it's + // okay for there to be no callback for this ID. + if (i) { + const e = i.get(t); + e && (n ? e.reject(n) : e.resolve(), i = i.remove(t)), r.Vu[r.currentUser.toKey()] = i; + } +} + +function __PRIVATE_removeAndCleanupTarget(e, t, n = null) { + e.sharedClientState.removeLocalQueryTarget(t); + for (const r of e.Iu.get(t)) e.Tu.delete(r), n && e.Pu.yu(r, n); + if (e.Iu.delete(t), e.isPrimaryClient) { + e.Ru.jr(t).forEach((t => { + e.Ru.containsKey(t) || + // We removed the last reference for this key + __PRIVATE_removeLimboTarget(e, t); + })); + } +} + +function __PRIVATE_removeLimboTarget(e, t) { + e.Eu.delete(t.path.canonicalString()); + // It's possible that the target already got removed because the query failed. In that case, + // the key won't exist in `limboTargetsByKey`. Only do the cleanup if we still have the target. + const n = e.du.get(t); + null !== n && (__PRIVATE_remoteStoreUnlisten(e.remoteStore, n), e.du = e.du.remove(t), + e.Au.delete(n), __PRIVATE_pumpEnqueuedLimboResolutions(e)); +} + +function __PRIVATE_updateTrackedLimbos(e, t, n) { + for (const r of n) if (r instanceof __PRIVATE_AddedLimboDocument) e.Ru.addReference(r.key, t), + __PRIVATE_trackLimboChange(e, r); else if (r instanceof __PRIVATE_RemovedLimboDocument) { + __PRIVATE_logDebug(sn, "Document no longer in limbo: " + r.key), e.Ru.removeReference(r.key, t); + e.Ru.containsKey(r.key) || + // We removed the last reference for this key + __PRIVATE_removeLimboTarget(e, r.key); + } else fail(19791, { + wu: r + }); +} + +function __PRIVATE_trackLimboChange(e, t) { + const n = t.key, r = n.path.canonicalString(); + e.du.get(n) || e.Eu.has(r) || (__PRIVATE_logDebug(sn, "New document in limbo: " + n), + e.Eu.add(r), __PRIVATE_pumpEnqueuedLimboResolutions(e)); +} + +/** + * Starts listens for documents in limbo that are enqueued for resolution, + * subject to a maximum number of concurrent resolutions. + * + * Without bounding the number of concurrent resolutions, the server can fail + * with "resource exhausted" errors which can lead to pathological client + * behavior as seen in https://github.com/firebase/firebase-js-sdk/issues/2683. + */ function __PRIVATE_pumpEnqueuedLimboResolutions(e) { + for (;e.Eu.size > 0 && e.du.size < e.maxConcurrentLimboResolutions; ) { + const t = e.Eu.values().next().value; + e.Eu.delete(t); + const n = new DocumentKey(ResourcePath.fromString(t)), r = e.fu.next(); + e.Au.set(r, new LimboResolution(n)), e.du = e.du.insert(n, r), __PRIVATE_remoteStoreListen(e.remoteStore, new TargetData(__PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(n.path)), r, "TargetPurposeLimboResolution" /* TargetPurpose.LimboResolution */ , __PRIVATE_ListenSequence.ce)); + } +} + +async function __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(e, t, n) { + const r = __PRIVATE_debugCast(e), i = [], s = [], o = []; + r.Tu.isEmpty() || (r.Tu.forEach(((e, _) => { + o.push(r.pu(_, t, n).then((e => { + // If there are changes, or we are handling a global snapshot, notify + // secondary clients to update query state. + if ((e || n) && r.isPrimaryClient) { + // Query state is set to `current` if: + // - There is a view change and it is up-to-date, or, + // - There is a global snapshot, the Target is current, and no changes to be resolved + const t = e ? !e.fromCache : n?.targetChanges.get(_.targetId)?.current; + r.sharedClientState.updateQueryState(_.targetId, t ? "current" : "not-current"); + } + // Update views if there are actual changes. + if (e) { + i.push(e); + const t = __PRIVATE_LocalViewChanges.As(_.targetId, e); + s.push(t); + } + }))); + })), await Promise.all(o), r.Pu.H_(i), await async function __PRIVATE_localStoreNotifyLocalViewChanges(e, t) { + const n = __PRIVATE_debugCast(e); + try { + await n.persistence.runTransaction("notifyLocalViewChanges", "readwrite", (e => PersistencePromise.forEach(t, (t => PersistencePromise.forEach(t.Es, (r => n.persistence.referenceDelegate.addReference(e, t.targetId, r))).next((() => PersistencePromise.forEach(t.ds, (r => n.persistence.referenceDelegate.removeReference(e, t.targetId, r))))))))); + } catch (e) { + if (!__PRIVATE_isIndexedDbTransactionError(e)) throw e; + // If `notifyLocalViewChanges` fails, we did not advance the sequence + // number for the documents that were included in this transaction. + // This might trigger them to be deleted earlier than they otherwise + // would have, but it should not invalidate the integrity of the data. + __PRIVATE_logDebug(Ut, "Failed to update sequence numbers: " + e); + } + for (const e of t) { + const t = e.targetId; + if (!e.fromCache) { + const e = n.Ms.get(t), r = e.snapshotVersion, i = e.withLastLimboFreeSnapshotVersion(r); + // Advance the last limbo free snapshot version + n.Ms = n.Ms.insert(t, i); + } + } + }(r.localStore, s)); +} + +async function __PRIVATE_syncEngineHandleCredentialChange(e, t) { + const n = __PRIVATE_debugCast(e); + if (!n.currentUser.isEqual(t)) { + __PRIVATE_logDebug(sn, "User change. New user:", t.toKey()); + const e = await __PRIVATE_localStoreHandleUserChange(n.localStore, t); + n.currentUser = t, + // Fails tasks waiting for pending writes requested by previous user. + function __PRIVATE_rejectOutstandingPendingWritesCallbacks(e, t) { + e.mu.forEach((e => { + e.forEach((e => { + e.reject(new FirestoreError(N.CANCELLED, t)); + })); + })), e.mu.clear(); + }(n, "'waitForPendingWrites' promise is rejected due to a user change."), + // TODO(b/114226417): Consider calling this only in the primary tab. + n.sharedClientState.handleUserChange(t, e.removedBatchIds, e.addedBatchIds), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e.Ls); + } +} + +function __PRIVATE_syncEngineGetRemoteKeysForTarget(e, t) { + const n = __PRIVATE_debugCast(e), r = n.Au.get(t); + if (r && r.hu) return __PRIVATE_documentKeySet().add(r.key); + { + let e = __PRIVATE_documentKeySet(); + const r = n.Iu.get(t); + if (!r) return e; + for (const t of r) { + const r = n.Tu.get(t); + e = e.unionWith(r.view.nu); + } + return e; + } +} + +/** + * Reconcile the list of synced documents in an existing view with those + * from persistence. + */ async function __PRIVATE_synchronizeViewAndComputeSnapshot(e, t) { + const n = __PRIVATE_debugCast(e), r = await __PRIVATE_localStoreExecuteQuery(n.localStore, t.query, + /* usePreviousResults= */ !0), i = t.view.cu(r); + return n.isPrimaryClient && __PRIVATE_updateTrackedLimbos(n, t.targetId, i.au), + i; +} + +/** + * Retrieves newly changed documents from remote document cache and raises + * snapshots if needed. + */ +// PORTING NOTE: Multi-Tab only. +async function __PRIVATE_syncEngineSynchronizeWithChangedDocuments(e, t) { + const n = __PRIVATE_debugCast(e); + return __PRIVATE_localStoreGetNewDocumentChanges(n.localStore, t).then((e => __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e))); +} + +/** Applies a mutation state to an existing batch. */ +// PORTING NOTE: Multi-Tab only. +async function __PRIVATE_syncEngineApplyBatchState(e, t, n, r) { + const i = __PRIVATE_debugCast(e), s = await function __PRIVATE_localStoreLookupMutationDocuments(e, t) { + const n = __PRIVATE_debugCast(e), r = __PRIVATE_debugCast(n.mutationQueue); + return n.persistence.runTransaction("Lookup mutation documents", "readonly", (e => r.er(e, t).next((t => t ? n.localDocuments.getDocuments(e, t) : PersistencePromise.resolve(null))))); + } + // PORTING NOTE: Multi-Tab only. + (i.localStore, t); + null !== s ? ("pending" === n ? + // If we are the primary client, we need to send this write to the + // backend. Secondary clients will ignore these writes since their remote + // connection is disabled. + await __PRIVATE_fillWritePipeline(i.remoteStore) : "acknowledged" === n || "rejected" === n ? ( + // NOTE: Both these methods are no-ops for batches that originated from + // other clients. + __PRIVATE_processUserCallback(i, t, r || null), __PRIVATE_triggerPendingWritesCallbacks(i, t), + function __PRIVATE_localStoreRemoveCachedMutationBatchMetadata(e, t) { + __PRIVATE_debugCast(__PRIVATE_debugCast(e).mutationQueue).ir(t); + } + // PORTING NOTE: Multi-Tab only. + (i.localStore, t)) : fail(6720, "Unknown batchState", { + Su: n + }), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(i, s)) : + // A throttled tab may not have seen the mutation before it was completed + // and removed from the mutation queue, in which case we won't have cached + // the affected documents. In this case we can safely ignore the update + // since that means we didn't apply the mutation locally at all (if we + // had, we would have cached the affected documents), and so we will just + // see any resulting document changes via normal remote document updates + // as applicable. + __PRIVATE_logDebug(sn, "Cannot apply mutation batch with id: " + t); +} + +/** Applies a query target change from a different tab. */ +// PORTING NOTE: Multi-Tab only. +async function __PRIVATE_syncEngineApplyPrimaryState(e, t) { + const n = __PRIVATE_debugCast(e); + if (__PRIVATE_ensureWatchCallbacks(n), __PRIVATE_syncEngineEnsureWriteCallbacks(n), + !0 === t && !0 !== n.gu) { + // Secondary tabs only maintain Views for their local listeners and the + // Views internal state may not be 100% populated (in particular + // secondary tabs don't track syncedDocuments, the set of documents the + // server considers to be in the target). So when a secondary becomes + // primary, we need to need to make sure that all views for all targets + // match the state on disk. + const e = n.sharedClientState.getAllActiveQueryTargets(), t = await __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(n, e.toArray()); + n.gu = !0, await __PRIVATE_remoteStoreApplyPrimaryState(n.remoteStore, !0); + for (const e of t) __PRIVATE_remoteStoreListen(n.remoteStore, e); + } else if (!1 === t && !1 !== n.gu) { + const e = []; + let t = Promise.resolve(); + n.Iu.forEach(((r, i) => { + n.sharedClientState.isLocalQueryTarget(i) ? e.push(i) : t = t.then((() => (__PRIVATE_removeAndCleanupTarget(n, i), + __PRIVATE_localStoreReleaseTarget(n.localStore, i, + /*keepPersistedTargetData=*/ !0)))), __PRIVATE_remoteStoreUnlisten(n.remoteStore, i); + })), await t, await __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(n, e), + // PORTING NOTE: Multi-Tab only. + function __PRIVATE_resetLimboDocuments(e) { + const t = __PRIVATE_debugCast(e); + t.Au.forEach(((e, n) => { + __PRIVATE_remoteStoreUnlisten(t.remoteStore, n); + })), t.Ru.Jr(), t.Au = new Map, t.du = new SortedMap(DocumentKey.comparator); + } + /** + * Reconcile the query views of the provided query targets with the state from + * persistence. Raises snapshots for any changes that affect the local + * client and returns the updated state of all target's query data. + * + * @param syncEngine - The sync engine implementation + * @param targets - the list of targets with views that need to be recomputed + * @param transitionToPrimary - `true` iff the tab transitions from a secondary + * tab to a primary tab + */ + // PORTING NOTE: Multi-Tab only. + (n), n.gu = !1, await __PRIVATE_remoteStoreApplyPrimaryState(n.remoteStore, !1); + } +} + +async function __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(e, t, n) { + const r = __PRIVATE_debugCast(e), i = [], s = []; + for (const e of t) { + let t; + const n = r.Iu.get(e); + if (n && 0 !== n.length) { + // For queries that have a local View, we fetch their current state + // from LocalStore (as the resume token and the snapshot version + // might have changed) and reconcile their views with the persisted + // state (the list of syncedDocuments may have gotten out of sync). + t = await __PRIVATE_localStoreAllocateTarget(r.localStore, __PRIVATE_queryToTarget(n[0])); + for (const e of n) { + const t = r.Tu.get(e), n = await __PRIVATE_synchronizeViewAndComputeSnapshot(r, t); + n.snapshot && s.push(n.snapshot); + } + } else { + // For queries that never executed on this client, we need to + // allocate the target in LocalStore and initialize a new View. + const n = await __PRIVATE_localStoreGetCachedTarget(r.localStore, e); + t = await __PRIVATE_localStoreAllocateTarget(r.localStore, n), await __PRIVATE_initializeViewAndComputeSnapshot(r, __PRIVATE_synthesizeTargetToQuery(n), e, + /*current=*/ !1, t.resumeToken); + } + i.push(t); + } + return r.Pu.H_(s), i; +} + +/** + * Creates a `Query` object from the specified `Target`. There is no way to + * obtain the original `Query`, so we synthesize a `Query` from the `Target` + * object. + * + * The synthesized result might be different from the original `Query`, but + * since the synthesized `Query` should return the same results as the + * original one (only the presentation of results might differ), the potential + * difference will not cause issues. + */ +// PORTING NOTE: Multi-Tab only. +function __PRIVATE_synthesizeTargetToQuery(e) { + return __PRIVATE_newQuery(e.path, e.collectionGroup, e.orderBy, e.filters, e.limit, "F" /* LimitType.First */ , e.startAt, e.endAt); +} + +/** Returns the IDs of the clients that are currently active. */ +// PORTING NOTE: Multi-Tab only. +function __PRIVATE_syncEngineGetActiveClients(e) { + return function __PRIVATE_localStoreGetActiveClients(e) { + return __PRIVATE_debugCast(__PRIVATE_debugCast(e).persistence).Ts(); + }(__PRIVATE_debugCast(e).localStore); +} + +/** Applies a query target change from a different tab. */ +// PORTING NOTE: Multi-Tab only. +async function __PRIVATE_syncEngineApplyTargetState(e, t, n, r) { + const i = __PRIVATE_debugCast(e); + if (i.gu) + // If we receive a target state notification via WebStorage, we are + // either already secondary or another tab has taken the primary lease. + return void __PRIVATE_logDebug(sn, "Ignoring unexpected query state notification."); + const s = i.Iu.get(t); + if (s && s.length > 0) switch (n) { + case "current": + case "not-current": + { + const e = await __PRIVATE_localStoreGetNewDocumentChanges(i.localStore, __PRIVATE_queryCollectionGroup(s[0])), r = RemoteEvent.createSynthesizedRemoteEventForCurrentChange(t, "current" === n, ByteString.EMPTY_BYTE_STRING); + await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(i, e, r); + break; + } + + case "rejected": + await __PRIVATE_localStoreReleaseTarget(i.localStore, t, + /* keepPersistedTargetData */ !0), __PRIVATE_removeAndCleanupTarget(i, t, r); + break; + + default: + fail(64155, n); + } +} + +/** Adds or removes Watch targets for queries from different tabs. */ async function __PRIVATE_syncEngineApplyActiveTargetsChange(e, t, n) { + const r = __PRIVATE_ensureWatchCallbacks(e); + if (r.gu) { + for (const e of t) { + if (r.Iu.has(e) && r.sharedClientState.isActiveQueryTarget(e)) { + __PRIVATE_logDebug(sn, "Adding an already active target " + e); + continue; + } + const t = await __PRIVATE_localStoreGetCachedTarget(r.localStore, e), n = await __PRIVATE_localStoreAllocateTarget(r.localStore, t); + await __PRIVATE_initializeViewAndComputeSnapshot(r, __PRIVATE_synthesizeTargetToQuery(t), n.targetId, + /*current=*/ !1, n.resumeToken), __PRIVATE_remoteStoreListen(r.remoteStore, n); + } + for (const e of n) + // Check that the target is still active since the target might have been + // removed if it has been rejected by the backend. + r.Iu.has(e) && + // Release queries that are still active. + await __PRIVATE_localStoreReleaseTarget(r.localStore, e, + /* keepPersistedTargetData */ !1).then((() => { + __PRIVATE_remoteStoreUnlisten(r.remoteStore, e), __PRIVATE_removeAndCleanupTarget(r, e); + })).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss); + } +} + +function __PRIVATE_ensureWatchCallbacks(e) { + const t = __PRIVATE_debugCast(e); + return t.remoteStore.remoteSyncer.applyRemoteEvent = __PRIVATE_syncEngineApplyRemoteEvent.bind(null, t), + t.remoteStore.remoteSyncer.getRemoteKeysForTarget = __PRIVATE_syncEngineGetRemoteKeysForTarget.bind(null, t), + t.remoteStore.remoteSyncer.rejectListen = __PRIVATE_syncEngineRejectListen.bind(null, t), + t.Pu.H_ = __PRIVATE_eventManagerOnWatchChange.bind(null, t.eventManager), t.Pu.yu = __PRIVATE_eventManagerOnWatchError.bind(null, t.eventManager), + t; +} + +function __PRIVATE_syncEngineEnsureWriteCallbacks(e) { + const t = __PRIVATE_debugCast(e); + return t.remoteStore.remoteSyncer.applySuccessfulWrite = __PRIVATE_syncEngineApplySuccessfulWrite.bind(null, t), + t.remoteStore.remoteSyncer.rejectFailedWrite = __PRIVATE_syncEngineRejectFailedWrite.bind(null, t), + t; +} + +/** + * Loads a Firestore bundle into the SDK. The returned promise resolves when + * the bundle finished loading. + * + * @param syncEngine - SyncEngine to use. + * @param bundleReader - Bundle to load into the SDK. + * @param task - LoadBundleTask used to update the loading progress to public API. + */ function __PRIVATE_syncEngineLoadBundle(e, t, n) { + const r = __PRIVATE_debugCast(e); + // eslint-disable-next-line @typescript-eslint/no-floating-promises + ( + /** Loads a bundle and returns the list of affected collection groups. */ + async function __PRIVATE_loadBundleImpl(e, t, n) { + try { + const r = await t.getMetadata(); + if (await function __PRIVATE_localStoreHasNewerBundle(e, t) { + const n = __PRIVATE_debugCast(e), r = __PRIVATE_fromVersion(t.createTime); + return n.persistence.runTransaction("hasNewerBundle", "readonly", (e => n.Ii.getBundleMetadata(e, t.id))).then((e => !!e && e.createTime.compareTo(r) >= 0)); + } + /** + * Saves the given `BundleMetadata` to local persistence. + */ (e.localStore, r)) return await t.close(), n._completeWith(function __PRIVATE_bundleSuccessProgress(e) { + return { + taskState: "Success", + documentsLoaded: e.totalDocuments, + bytesLoaded: e.totalBytes, + totalDocuments: e.totalDocuments, + totalBytes: e.totalBytes + }; + }(r)), Promise.resolve(new Set); + n._updateProgress(__PRIVATE_bundleInitialProgress(r)); + const i = new __PRIVATE_BundleLoader(r, t.serializer); + let s = await t.bu(); + for (;s; ) { + const e = await i.Ga(s); + e && n._updateProgress(e), s = await t.bu(); + } + const o = await i.ja(e.localStore); + return await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(e, o.Ha, + /* remoteEvent */ void 0), + // Save metadata, so loading the same bundle will skip. + await function __PRIVATE_localStoreSaveBundle(e, t) { + const n = __PRIVATE_debugCast(e); + return n.persistence.runTransaction("Save bundle", "readwrite", (e => n.Ii.saveBundleMetadata(e, t))); + } + /** + * Returns a promise of a `NamedQuery` associated with given query name. Promise + * resolves to undefined if no persisted data can be found. + */ (e.localStore, r), n._completeWith(o.progress), Promise.resolve(o.Ja); + } catch (e) { + return __PRIVATE_logWarn(sn, `Loading bundle failed with ${e}`), n._failWith(e), + Promise.resolve(new Set); + } + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Provides all components needed for Firestore with in-memory persistence. + * Uses EagerGC garbage collection. + */)(r, t, n).then((e => { + r.sharedClientState.notifyBundleLoaded(e); + })); +} + +class __PRIVATE_MemoryOfflineComponentProvider { + constructor() { + this.kind = "memory", this.synchronizeTabs = !1; + } + async initialize(e) { + this.serializer = __PRIVATE_newSerializer(e.databaseInfo.databaseId), this.sharedClientState = this.Du(e), + this.persistence = this.Cu(e), await this.persistence.start(), this.localStore = this.vu(e), + this.gcScheduler = this.Fu(e, this.localStore), this.indexBackfillerScheduler = this.Mu(e, this.localStore); + } + Fu(e, t) { + return null; + } + Mu(e, t) { + return null; + } + vu(e) { + return __PRIVATE_newLocalStore(this.persistence, new __PRIVATE_QueryEngine, e.initialUser, this.serializer); + } + Cu(e) { + return new __PRIVATE_MemoryPersistence(__PRIVATE_MemoryEagerDelegate.mi, this.serializer); + } + Du(e) { + return new __PRIVATE_MemorySharedClientState; + } + async terminate() { + this.gcScheduler?.stop(), this.indexBackfillerScheduler?.stop(), this.sharedClientState.shutdown(), + await this.persistence.shutdown(); + } +} + +__PRIVATE_MemoryOfflineComponentProvider.provider = { + build: () => new __PRIVATE_MemoryOfflineComponentProvider +}; + +class __PRIVATE_LruGcMemoryOfflineComponentProvider extends __PRIVATE_MemoryOfflineComponentProvider { + constructor(e) { + super(), this.cacheSizeBytes = e; + } + Fu(e, t) { + __PRIVATE_hardAssert(this.persistence.referenceDelegate instanceof __PRIVATE_MemoryLruDelegate, 46915); + const n = this.persistence.referenceDelegate.garbageCollector; + return new __PRIVATE_LruScheduler(n, e.asyncQueue, t); + } + Cu(e) { + const t = void 0 !== this.cacheSizeBytes ? LruParams.withCacheSize(this.cacheSizeBytes) : LruParams.DEFAULT; + return new __PRIVATE_MemoryPersistence((e => __PRIVATE_MemoryLruDelegate.mi(e, t)), this.serializer); + } +} + +/** + * Provides all components needed for Firestore with IndexedDB persistence. + */ class __PRIVATE_IndexedDbOfflineComponentProvider extends __PRIVATE_MemoryOfflineComponentProvider { + constructor(e, t, n) { + super(), this.xu = e, this.cacheSizeBytes = t, this.forceOwnership = n, this.kind = "persistent", + this.synchronizeTabs = !1; + } + async initialize(e) { + await super.initialize(e), await this.xu.initialize(this, e), + // Enqueue writes from a previous session + await __PRIVATE_syncEngineEnsureWriteCallbacks(this.xu.syncEngine), await __PRIVATE_fillWritePipeline(this.xu.remoteStore), + // NOTE: This will immediately call the listener, so we make sure to + // set it after localStore / remoteStore are started. + await this.persistence.Ji((() => (this.gcScheduler && !this.gcScheduler.started && this.gcScheduler.start(), + this.indexBackfillerScheduler && !this.indexBackfillerScheduler.started && this.indexBackfillerScheduler.start(), + Promise.resolve()))); + } + vu(e) { + return __PRIVATE_newLocalStore(this.persistence, new __PRIVATE_QueryEngine, e.initialUser, this.serializer); + } + Fu(e, t) { + const n = this.persistence.referenceDelegate.garbageCollector; + return new __PRIVATE_LruScheduler(n, e.asyncQueue, t); + } + Mu(e, t) { + const n = new __PRIVATE_IndexBackfiller(t, this.persistence); + return new __PRIVATE_IndexBackfillerScheduler(e.asyncQueue, n); + } + Cu(e) { + const t = __PRIVATE_indexedDbStoragePrefix(e.databaseInfo.databaseId, e.databaseInfo.persistenceKey), n = void 0 !== this.cacheSizeBytes ? LruParams.withCacheSize(this.cacheSizeBytes) : LruParams.DEFAULT; + return new __PRIVATE_IndexedDbPersistence(this.synchronizeTabs, t, e.clientId, n, e.asyncQueue, __PRIVATE_getWindow(), getDocument(), this.serializer, this.sharedClientState, !!this.forceOwnership); + } + Du(e) { + return new __PRIVATE_MemorySharedClientState; + } +} + +/** + * Provides all components needed for Firestore with multi-tab IndexedDB + * persistence. + * + * In the legacy client, this provider is used to provide both multi-tab and + * non-multi-tab persistence since we cannot tell at build time whether + * `synchronizeTabs` will be enabled. + */ class __PRIVATE_MultiTabOfflineComponentProvider extends __PRIVATE_IndexedDbOfflineComponentProvider { + constructor(e, t) { + super(e, t, /* forceOwnership= */ !1), this.xu = e, this.cacheSizeBytes = t, this.synchronizeTabs = !0; + } + async initialize(e) { + await super.initialize(e); + const t = this.xu.syncEngine; + this.sharedClientState instanceof __PRIVATE_WebStorageSharedClientState && (this.sharedClientState.syncEngine = { + Co: __PRIVATE_syncEngineApplyBatchState.bind(null, t), + vo: __PRIVATE_syncEngineApplyTargetState.bind(null, t), + Fo: __PRIVATE_syncEngineApplyActiveTargetsChange.bind(null, t), + Ts: __PRIVATE_syncEngineGetActiveClients.bind(null, t), + Do: __PRIVATE_syncEngineSynchronizeWithChangedDocuments.bind(null, t) + }, await this.sharedClientState.start()), + // NOTE: This will immediately call the listener, so we make sure to + // set it after localStore / remoteStore are started. + await this.persistence.Ji((async e => { + await __PRIVATE_syncEngineApplyPrimaryState(this.xu.syncEngine, e), this.gcScheduler && (e && !this.gcScheduler.started ? this.gcScheduler.start() : e || this.gcScheduler.stop()), + this.indexBackfillerScheduler && (e && !this.indexBackfillerScheduler.started ? this.indexBackfillerScheduler.start() : e || this.indexBackfillerScheduler.stop()); + })); + } + Du(e) { + const t = __PRIVATE_getWindow(); + if (!__PRIVATE_WebStorageSharedClientState.v(t)) throw new FirestoreError(N.UNIMPLEMENTED, "IndexedDB persistence is only available on platforms that support LocalStorage."); + const n = __PRIVATE_indexedDbStoragePrefix(e.databaseInfo.databaseId, e.databaseInfo.persistenceKey); + return new __PRIVATE_WebStorageSharedClientState(t, e.asyncQueue, n, e.clientId, e.initialUser); + } +} + +/** + * Initializes and wires the components that are needed to interface with the + * network. + */ class OnlineComponentProvider { + async initialize(e, t) { + this.localStore || (this.localStore = e.localStore, this.sharedClientState = e.sharedClientState, + this.datastore = this.createDatastore(t), this.remoteStore = this.createRemoteStore(t), + this.eventManager = this.createEventManager(t), this.syncEngine = this.createSyncEngine(t, + /* startAsPrimary=*/ !e.synchronizeTabs), this.sharedClientState.onlineStateHandler = e => __PRIVATE_syncEngineApplyOnlineStateChange(this.syncEngine, e, 1 /* OnlineStateSource.SharedClientState */), + this.remoteStore.remoteSyncer.handleCredentialChange = __PRIVATE_syncEngineHandleCredentialChange.bind(null, this.syncEngine), + await __PRIVATE_remoteStoreApplyPrimaryState(this.remoteStore, this.syncEngine.isPrimaryClient)); + } + createEventManager(e) { + return function __PRIVATE_newEventManager() { + return new __PRIVATE_EventManagerImpl; + }(); + } + createDatastore(e) { + const t = __PRIVATE_newSerializer(e.databaseInfo.databaseId), n = function __PRIVATE_newConnection(e) { + return new __PRIVATE_WebChannelConnection(e); + } + /** Return the Platform-specific connectivity monitor. */ (e.databaseInfo); + return function __PRIVATE_newDatastore(e, t, n, r) { + return new __PRIVATE_DatastoreImpl(e, t, n, r); + }(e.authCredentials, e.appCheckCredentials, n, t); + } + createRemoteStore(e) { + return function __PRIVATE_newRemoteStore(e, t, n, r, i) { + return new __PRIVATE_RemoteStoreImpl(e, t, n, r, i); + } + /** Re-enables the network. Idempotent. */ (this.localStore, this.datastore, e.asyncQueue, (e => __PRIVATE_syncEngineApplyOnlineStateChange(this.syncEngine, e, 0 /* OnlineStateSource.RemoteStore */)), function __PRIVATE_newConnectivityMonitor() { + return __PRIVATE_BrowserConnectivityMonitor.v() ? new __PRIVATE_BrowserConnectivityMonitor : new __PRIVATE_NoopConnectivityMonitor; + }()); + } + createSyncEngine(e, t) { + return function __PRIVATE_newSyncEngine(e, t, n, + // PORTING NOTE: Manages state synchronization in multi-tab environments. + r, i, s, o) { + const _ = new __PRIVATE_SyncEngineImpl(e, t, n, r, i, s); + return o && (_.gu = !0), _; + }(this.localStore, this.remoteStore, this.eventManager, this.sharedClientState, e.initialUser, e.maxConcurrentLimboResolutions, t); + } + async terminate() { + await async function __PRIVATE_remoteStoreShutdown(e) { + const t = __PRIVATE_debugCast(e); + __PRIVATE_logDebug(tn, "RemoteStore shutting down."), t.Ea.add(5 /* OfflineCause.Shutdown */), + await __PRIVATE_disableNetworkInternal(t), t.Aa.shutdown(), + // Set the OnlineState to Unknown (rather than Offline) to avoid potentially + // triggering spurious listener events with cached data, etc. + t.Ra.set("Unknown" /* OnlineState.Unknown */); + }(this.remoteStore), this.datastore?.terminate(), this.eventManager?.terminate(); + } +} + +OnlineComponentProvider.provider = { + build: () => new OnlineComponentProvider +}; + +/** + * Builds a `ByteStreamReader` from a UInt8Array. + * @param source - The data source to use. + * @param bytesPerRead - How many bytes each `read()` from the returned reader + * will read. + */ +function __PRIVATE_toByteStreamReaderHelper(e, t = 10240) { + let n = 0; + // The TypeScript definition for ReadableStreamReader changed. We use + // `any` here to allow this code to compile with different versions. + // See https://github.com/microsoft/TypeScript/issues/42970 + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + async read() { + if (n < e.byteLength) { + const r = { + value: e.slice(n, n + t), + done: !1 + }; + return n += t, r; + } + return { + done: !0 + }; + }, + async cancel() {}, + releaseLock() {}, + closed: Promise.resolve() + }; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * On web, a `ReadableStream` is wrapped around by a `ByteStreamReader`. + */ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * A wrapper implementation of Observer that will dispatch events + * asynchronously. To allow immediate silencing, a mute call is added which + * causes events scheduled to no longer be raised. + */ +class __PRIVATE_AsyncObserver { + constructor(e) { + this.observer = e, + /** + * When set to true, will not raise future events. Necessary to deal with + * async detachment of listener. + */ + this.muted = !1; + } + next(e) { + this.muted || this.observer.next && this.Ou(this.observer.next, e); + } + error(e) { + this.muted || (this.observer.error ? this.Ou(this.observer.error, e) : __PRIVATE_logError("Uncaught Error in snapshot listener:", e.toString())); + } + Nu() { + this.muted = !0; + } + Ou(e, t) { + setTimeout((() => { + this.muted || e(t); + }), 0); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A class representing a bundle. + * + * Takes a bundle stream or buffer, and presents abstractions to read bundled + * elements out of the underlying content. + */ class __PRIVATE_BundleReaderImpl { + constructor( + /** The reader to read from underlying binary bundle data source. */ + e, t) { + this.Bu = e, this.serializer = t, + /** Cached bundle metadata. */ + this.metadata = new __PRIVATE_Deferred, + /** + * Internal buffer to hold bundle content, accumulating incomplete element + * content. + */ + this.buffer = new Uint8Array, this.Lu = function __PRIVATE_newTextDecoder() { + return new TextDecoder("utf-8"); + }(), + // Read the metadata (which is the first element). + this.ku().then((e => { + e && e.$a() ? this.metadata.resolve(e.Qa.metadata) : this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\n ${JSON.stringify(e?.Qa)}`)); + }), (e => this.metadata.reject(e))); + } + close() { + return this.Bu.cancel(); + } + async getMetadata() { + return this.metadata.promise; + } + async bu() { + // Makes sure metadata is read before proceeding. + return await this.getMetadata(), this.ku(); + } + /** + * Reads from the head of internal buffer, and pulling more data from + * underlying stream if a complete element cannot be found, until an + * element(including the prefixed length and the JSON string) is found. + * + * Once a complete element is read, it is dropped from internal buffer. + * + * Returns either the bundled element, or null if we have reached the end of + * the stream. + */ async ku() { + const e = await this.qu(); + if (null === e) return null; + const t = this.Lu.decode(e), n = Number(t); + isNaN(n) && this.Qu(`length string (${t}) is not valid number`); + const r = await this.$u(n); + return new __PRIVATE_SizedBundleElement(JSON.parse(r), e.length + n); + } + /** First index of '{' from the underlying buffer. */ Uu() { + return this.buffer.findIndex((e => e === "{".charCodeAt(0))); + } + /** + * Reads from the beginning of the internal buffer, until the first '{', and + * return the content. + * + * If reached end of the stream, returns a null. + */ async qu() { + for (;this.Uu() < 0; ) { + if (await this.Ku()) break; + } + // Broke out of the loop because underlying stream is closed, and there + // happens to be no more data to process. + if (0 === this.buffer.length) return null; + const e = this.Uu(); + // Broke out of the loop because underlying stream is closed, but still + // cannot find an open bracket. + e < 0 && this.Qu("Reached the end of bundle when a length string is expected."); + const t = this.buffer.slice(0, e); + // Update the internal buffer to drop the read length. + return this.buffer = this.buffer.slice(e), t; + } + /** + * Reads from a specified position from the internal buffer, for a specified + * number of bytes, pulling more data from the underlying stream if needed. + * + * Returns a string decoded from the read bytes. + */ async $u(e) { + for (;this.buffer.length < e; ) { + await this.Ku() && this.Qu("Reached the end of bundle when more is expected."); + } + const t = this.Lu.decode(this.buffer.slice(0, e)); + // Update the internal buffer to drop the read json string. + return this.buffer = this.buffer.slice(e), t; + } + Qu(e) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + throw this.Bu.cancel(), new Error(`Invalid bundle format: ${e}`); + } + /** + * Pulls more data from underlying stream to internal buffer. + * Returns a boolean indicating whether the stream is finished. + */ async Ku() { + const e = await this.Bu.read(); + if (!e.done) { + const t = new Uint8Array(this.buffer.length + e.value.length); + t.set(this.buffer), t.set(e.value, this.buffer.length), this.buffer = t; + } + return e.done; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A class that can parse a bundle form the string serialization of a bundle. + */ +class __PRIVATE_BundleReaderSyncImpl { + constructor(e, t) { + this.bundleData = e, this.serializer = t, this.cursor = 0, this.elements = []; + let n = this.bu(); + if (!n || !n.$a()) throw new Error(`The first element of the bundle is not a metadata object, it is\n ${JSON.stringify(n?.Qa)}`); + this.metadata = n; + do { + n = this.bu(), null !== n && this.elements.push(n); + } while (null !== n); + } + /* Returns the parsed metadata of the bundle. */ getMetadata() { + return this.metadata; + } + /* Returns the DocumentSnapshot or NamedQuery elements of the bundle. */ Wu() { + return this.elements; + } + /** + * Parses the next element of the bundle. + * + * @returns a SizedBundleElement representation of the next element in the bundle, or null if + * no more elements exist. + */ bu() { + if (this.cursor === this.bundleData.length) return null; + const e = this.qu(), t = this.$u(e); + return new __PRIVATE_SizedBundleElement(JSON.parse(t), e); + } + /** + * Reads from a specified position from the bundleData string, for a specified + * number of bytes. + * + * @param length how many characters to read. + * @returns a string parsed from the bundle. + */ $u(e) { + if (this.cursor + e > this.bundleData.length) throw new FirestoreError(N.INTERNAL, "Reached the end of bundle when more is expected."); + return this.bundleData.slice(this.cursor, this.cursor += e); + } + /** + * Reads from the current cursor until the first '{'. + * + * @returns A string to integer represention of the parsed value. + * @throws An {@link Error} if the cursor has reached the end of the stream, since lengths + * prefix bundle objects. + */ qu() { + const e = this.cursor; + let t = this.cursor; + for (;t < this.bundleData.length; ) { + if ("{" === this.bundleData[t]) { + if (t === e) throw new Error("First character is a bracket and not a number"); + return this.cursor = t, Number(this.bundleData.slice(e, t)); + } + t++; + } + throw new Error("Reached the end of bundle when more is expected."); + } +} + +/** + * Creates an instance of BundleReader without exposing the BundleReaderSyncImpl class type. + */ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Internal transaction object responsible for accumulating the mutations to + * perform and the base versions for any documents read. + */ +class Transaction$2 { + constructor(e) { + this.datastore = e, + // The version of each document that was read during this transaction. + this.readVersions = new Map, this.mutations = [], this.committed = !1, + /** + * A deferred usage error that occurred previously in this transaction that + * will cause the transaction to fail once it actually commits. + */ + this.lastTransactionError = null, + /** + * Set of documents that have been written in the transaction. + * + * When there's more than one write to the same key in a transaction, any + * writes after the first are handled differently. + */ + this.writtenDocs = new Set; + } + async lookup(e) { + if (this.ensureCommitNotCalled(), this.mutations.length > 0) throw this.lastTransactionError = new FirestoreError(N.INVALID_ARGUMENT, "Firestore transactions require all reads to be executed before all writes."), + this.lastTransactionError; + const t = await async function __PRIVATE_invokeBatchGetDocumentsRpc(e, t) { + const n = __PRIVATE_debugCast(e), r = { + documents: t.map((e => __PRIVATE_toName(n.serializer, e))) + }, i = await n.Ho("BatchGetDocuments", n.serializer.databaseId, ResourcePath.emptyPath(), r, t.length), s = new Map; + i.forEach((e => { + const t = __PRIVATE_fromBatchGetDocumentsResponse(n.serializer, e); + s.set(t.key.toString(), t); + })); + const o = []; + return t.forEach((e => { + const t = s.get(e.toString()); + __PRIVATE_hardAssert(!!t, 55234, { + key: e + }), o.push(t); + })), o; + }(this.datastore, e); + return t.forEach((e => this.recordVersion(e))), t; + } + set(e, t) { + this.write(t.toMutation(e, this.precondition(e))), this.writtenDocs.add(e.toString()); + } + update(e, t) { + try { + this.write(t.toMutation(e, this.preconditionForUpdate(e))); + } catch (e) { + this.lastTransactionError = e; + } + this.writtenDocs.add(e.toString()); + } + delete(e) { + this.write(new __PRIVATE_DeleteMutation(e, this.precondition(e))), this.writtenDocs.add(e.toString()); + } + async commit() { + if (this.ensureCommitNotCalled(), this.lastTransactionError) throw this.lastTransactionError; + const e = this.readVersions; + // For each mutation, note that the doc was written. + this.mutations.forEach((t => { + e.delete(t.key.toString()); + })), + // For each document that was read but not written to, we want to perform + // a `verify` operation. + e.forEach(((e, t) => { + const n = DocumentKey.fromPath(t); + this.mutations.push(new __PRIVATE_VerifyMutation(n, this.precondition(n))); + })), await async function __PRIVATE_invokeCommitRpc(e, t) { + const n = __PRIVATE_debugCast(e), r = { + writes: t.map((e => toMutation(n.serializer, e))) + }; + await n.Go("Commit", n.serializer.databaseId, ResourcePath.emptyPath(), r); + }(this.datastore, this.mutations), this.committed = !0; + } + recordVersion(e) { + let t; + if (e.isFoundDocument()) t = e.version; else { + if (!e.isNoDocument()) throw fail(50498, { + Gu: e.constructor.name + }); + // Represent a deleted doc using SnapshotVersion.min(). + t = SnapshotVersion.min(); + } + const n = this.readVersions.get(e.key.toString()); + if (n) { + if (!t.isEqual(n)) + // This transaction will fail no matter what. + throw new FirestoreError(N.ABORTED, "Document version changed between two reads."); + } else this.readVersions.set(e.key.toString(), t); + } + /** + * Returns the version of this document when it was read in this transaction, + * as a precondition, or no precondition if it was not read. + */ precondition(e) { + const t = this.readVersions.get(e.toString()); + return !this.writtenDocs.has(e.toString()) && t ? t.isEqual(SnapshotVersion.min()) ? Precondition.exists(!1) : Precondition.updateTime(t) : Precondition.none(); + } + /** + * Returns the precondition for a document if the operation is an update. + */ preconditionForUpdate(e) { + const t = this.readVersions.get(e.toString()); + // The first time a document is written, we want to take into account the + // read time and existence + if (!this.writtenDocs.has(e.toString()) && t) { + if (t.isEqual(SnapshotVersion.min())) + // The document doesn't exist, so fail the transaction. + // This has to be validated locally because you can't send a + // precondition that a document does not exist without changing the + // semantics of the backend write to be an insert. This is the reverse + // of what we want, since we want to assert that the document doesn't + // exist but then send the update and have it fail. Since we can't + // express that to the backend, we have to validate locally. + // Note: this can change once we can send separate verify writes in the + // transaction. + throw new FirestoreError(N.INVALID_ARGUMENT, "Can't update a document that doesn't exist."); + // Document exists, base precondition on document update time. + return Precondition.updateTime(t); + } + // Document was not read, so we just use the preconditions for a blind + // update. + return Precondition.exists(!0); + } + write(e) { + this.ensureCommitNotCalled(), this.mutations.push(e); + } + ensureCommitNotCalled() {} +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * TransactionRunner encapsulates the logic needed to run and retry transactions + * with backoff. + */ class __PRIVATE_TransactionRunner { + constructor(e, t, n, r, i) { + this.asyncQueue = e, this.datastore = t, this.options = n, this.updateFunction = r, + this.deferred = i, this.zu = n.maxAttempts, this.M_ = new __PRIVATE_ExponentialBackoff(this.asyncQueue, "transaction_retry" /* TimerId.TransactionRetry */); + } + /** Runs the transaction and sets the result on deferred. */ ju() { + this.zu -= 1, this.Ju(); + } + Ju() { + this.M_.p_((async () => { + const e = new Transaction$2(this.datastore), t = this.Hu(e); + t && t.then((t => { + this.asyncQueue.enqueueAndForget((() => e.commit().then((() => { + this.deferred.resolve(t); + })).catch((e => { + this.Yu(e); + })))); + })).catch((e => { + this.Yu(e); + })); + })); + } + Hu(e) { + try { + const t = this.updateFunction(e); + return !__PRIVATE_isNullOrUndefined(t) && t.catch && t.then ? t : (this.deferred.reject(Error("Transaction callback must return a Promise")), + null); + } catch (e) { + // Do not retry errors thrown by user provided updateFunction. + return this.deferred.reject(e), null; + } + } + Yu(e) { + this.zu > 0 && this.Zu(e) ? (this.zu -= 1, this.asyncQueue.enqueueAndForget((() => (this.Ju(), + Promise.resolve())))) : this.deferred.reject(e); + } + Zu(e) { + if ("FirebaseError" === e?.name) { + // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and + // non-matching document versions with ABORTED. These errors should be retried. + const t = e.code; + return "aborted" === t || "failed-precondition" === t || "already-exists" === t || !__PRIVATE_isPermanentError(t); + } + return !1; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const on = "FirestoreClient"; + +/** + * FirestoreClient is a top-level class that constructs and owns all of the // + * pieces of the client SDK architecture. It is responsible for creating the // + * async queue that is shared by all of the other components in the system. // + */ +class FirestoreClient { + constructor(e, t, + /** + * Asynchronous queue responsible for all of our internal processing. When + * we get incoming work from the user (via public API) or the network + * (incoming GRPC messages), we should always schedule onto this queue. + * This ensures all of our work is properly serialized (e.g. we don't + * start processing a new operation while the previous one is waiting for + * an async I/O to complete). + */ + n, r, i) { + this.authCredentials = e, this.appCheckCredentials = t, this.asyncQueue = n, this.databaseInfo = r, + this.user = User.UNAUTHENTICATED, this.clientId = __PRIVATE_AutoId.newId(), this.authCredentialListener = () => Promise.resolve(), + this.appCheckCredentialListener = () => Promise.resolve(), this._uninitializedComponentsProvider = i, + this.authCredentials.start(n, (async e => { + __PRIVATE_logDebug(on, "Received user=", e.uid), await this.authCredentialListener(e), + this.user = e; + })), this.appCheckCredentials.start(n, (e => (__PRIVATE_logDebug(on, "Received new app check token=", e), + this.appCheckCredentialListener(e, this.user)))); + } + get configuration() { + return { + asyncQueue: this.asyncQueue, + databaseInfo: this.databaseInfo, + clientId: this.clientId, + authCredentials: this.authCredentials, + appCheckCredentials: this.appCheckCredentials, + initialUser: this.user, + maxConcurrentLimboResolutions: 100 + }; + } + setCredentialChangeListener(e) { + this.authCredentialListener = e; + } + setAppCheckTokenChangeListener(e) { + this.appCheckCredentialListener = e; + } + terminate() { + this.asyncQueue.enterRestrictedMode(); + const e = new __PRIVATE_Deferred; + return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((async () => { + try { + this._onlineComponents && await this._onlineComponents.terminate(), this._offlineComponents && await this._offlineComponents.terminate(), + // The credentials provider must be terminated after shutting down the + // RemoteStore as it will prevent the RemoteStore from retrieving auth + // tokens. + this.authCredentials.shutdown(), this.appCheckCredentials.shutdown(), e.resolve(); + } catch (t) { + const n = __PRIVATE_wrapInUserErrorIfRecoverable(t, "Failed to shutdown persistence"); + e.reject(n); + } + })), e.promise; + } +} + +async function __PRIVATE_setOfflineComponentProvider(e, t) { + e.asyncQueue.verifyOperationInProgress(), __PRIVATE_logDebug(on, "Initializing OfflineComponentProvider"); + const n = e.configuration; + await t.initialize(n); + let r = n.initialUser; + e.setCredentialChangeListener((async e => { + r.isEqual(e) || (await __PRIVATE_localStoreHandleUserChange(t.localStore, e), r = e); + })), + // When a user calls clearPersistence() in one client, all other clients + // need to be terminated to allow the delete to succeed. + t.persistence.setDatabaseDeletedListener((() => e.terminate())), e._offlineComponents = t; +} + +async function __PRIVATE_setOnlineComponentProvider(e, t) { + e.asyncQueue.verifyOperationInProgress(); + const n = await __PRIVATE_ensureOfflineComponents(e); + __PRIVATE_logDebug(on, "Initializing OnlineComponentProvider"), await t.initialize(n, e.configuration), + // The CredentialChangeListener of the online component provider takes + // precedence over the offline component provider. + e.setCredentialChangeListener((e => __PRIVATE_remoteStoreHandleCredentialChange(t.remoteStore, e))), + e.setAppCheckTokenChangeListener(((e, n) => __PRIVATE_remoteStoreHandleCredentialChange(t.remoteStore, n))), + e._onlineComponents = t; +} + +/** + * Decides whether the provided error allows us to gracefully disable + * persistence (as opposed to crashing the client). + */ async function __PRIVATE_ensureOfflineComponents(e) { + if (!e._offlineComponents) if (e._uninitializedComponentsProvider) { + __PRIVATE_logDebug(on, "Using user provided OfflineComponentProvider"); + try { + await __PRIVATE_setOfflineComponentProvider(e, e._uninitializedComponentsProvider._offline); + } catch (t) { + const n = t; + if (!function __PRIVATE_canFallbackFromIndexedDbError(e) { + return "FirebaseError" === e.name ? e.code === N.FAILED_PRECONDITION || e.code === N.UNIMPLEMENTED : !("undefined" != typeof DOMException && e instanceof DOMException) || + // When the browser is out of quota we could get either quota exceeded + // or an aborted error depending on whether the error happened during + // schema migration. + 22 === e.code || 20 === e.code || + // Firefox Private Browsing mode disables IndexedDb and returns + // INVALID_STATE for any usage. + 11 === e.code; + }(n)) throw n; + __PRIVATE_logWarn("Error using user provided cache. Falling back to memory cache: " + n), + await __PRIVATE_setOfflineComponentProvider(e, new __PRIVATE_MemoryOfflineComponentProvider); + } + } else __PRIVATE_logDebug(on, "Using default OfflineComponentProvider"), await __PRIVATE_setOfflineComponentProvider(e, new __PRIVATE_LruGcMemoryOfflineComponentProvider(void 0)); + return e._offlineComponents; +} + +async function __PRIVATE_ensureOnlineComponents(e) { + return e._onlineComponents || (e._uninitializedComponentsProvider ? (__PRIVATE_logDebug(on, "Using user provided OnlineComponentProvider"), + await __PRIVATE_setOnlineComponentProvider(e, e._uninitializedComponentsProvider._online)) : (__PRIVATE_logDebug(on, "Using default OnlineComponentProvider"), + await __PRIVATE_setOnlineComponentProvider(e, new OnlineComponentProvider))), e._onlineComponents; +} + +function __PRIVATE_getPersistence(e) { + return __PRIVATE_ensureOfflineComponents(e).then((e => e.persistence)); +} + +function __PRIVATE_getLocalStore(e) { + return __PRIVATE_ensureOfflineComponents(e).then((e => e.localStore)); +} + +function __PRIVATE_getRemoteStore(e) { + return __PRIVATE_ensureOnlineComponents(e).then((e => e.remoteStore)); +} + +function __PRIVATE_getSyncEngine(e) { + return __PRIVATE_ensureOnlineComponents(e).then((e => e.syncEngine)); +} + +function __PRIVATE_getDatastore(e) { + return __PRIVATE_ensureOnlineComponents(e).then((e => e.datastore)); +} + +async function __PRIVATE_getEventManager(e) { + const t = await __PRIVATE_ensureOnlineComponents(e), n = t.eventManager; + return n.onListen = __PRIVATE_syncEngineListen.bind(null, t.syncEngine), n.onUnlisten = __PRIVATE_syncEngineUnlisten.bind(null, t.syncEngine), + n.onFirstRemoteStoreListen = __PRIVATE_triggerRemoteStoreListen.bind(null, t.syncEngine), + n.onLastRemoteStoreUnlisten = __PRIVATE_triggerRemoteStoreUnlisten.bind(null, t.syncEngine), + n; +} + +/** Enables the network connection and re-enqueues all pending operations. */ function __PRIVATE_firestoreClientEnableNetwork(e) { + return e.asyncQueue.enqueue((async () => { + const t = await __PRIVATE_getPersistence(e), n = await __PRIVATE_getRemoteStore(e); + return t.setNetworkEnabled(!0), function __PRIVATE_remoteStoreEnableNetwork(e) { + const t = __PRIVATE_debugCast(e); + return t.Ea.delete(0 /* OfflineCause.UserDisabled */), __PRIVATE_enableNetworkInternal(t); + }(n); + })); +} + +/** Disables the network connection. Pending operations will not complete. */ function __PRIVATE_firestoreClientDisableNetwork(e) { + return e.asyncQueue.enqueue((async () => { + const t = await __PRIVATE_getPersistence(e), n = await __PRIVATE_getRemoteStore(e); + return t.setNetworkEnabled(!1), async function __PRIVATE_remoteStoreDisableNetwork(e) { + const t = __PRIVATE_debugCast(e); + t.Ea.add(0 /* OfflineCause.UserDisabled */), await __PRIVATE_disableNetworkInternal(t), + // Set the OnlineState to Offline so get()s return from cache, etc. + t.Ra.set("Offline" /* OnlineState.Offline */); + }(n); + })); +} + +/** + * Returns a Promise that resolves when all writes that were pending at the time + * this method was called received server acknowledgement. An acknowledgement + * can be either acceptance or rejection. + */ function __PRIVATE_firestoreClientGetDocumentFromLocalCache(e, t) { + const n = new __PRIVATE_Deferred; + return e.asyncQueue.enqueueAndForget((async () => async function __PRIVATE_readDocumentFromCache(e, t, n) { + try { + const r = await function __PRIVATE_localStoreReadDocument(e, t) { + const n = __PRIVATE_debugCast(e); + return n.persistence.runTransaction("read document", "readonly", (e => n.localDocuments.getDocument(e, t))); + }(e, t); + r.isFoundDocument() ? n.resolve(r) : r.isNoDocument() ? n.resolve(null) : n.reject(new FirestoreError(N.UNAVAILABLE, "Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)")); + } catch (e) { + const r = __PRIVATE_wrapInUserErrorIfRecoverable(e, `Failed to get document '${t} from cache`); + n.reject(r); + } + } + /** + * Retrieves a latency-compensated document from the backend via a + * SnapshotListener. + */ (await __PRIVATE_getLocalStore(e), t, n))), n.promise; +} + +function __PRIVATE_firestoreClientGetDocumentViaSnapshotListener(e, t, n = {}) { + const r = new __PRIVATE_Deferred; + return e.asyncQueue.enqueueAndForget((async () => function __PRIVATE_readDocumentViaSnapshotListener(e, t, n, r, i) { + const s = new __PRIVATE_AsyncObserver({ + next: _ => { + // Mute and remove query first before passing event to user to avoid + // user actions affecting the now stale query. + s.Nu(), t.enqueueAndForget((() => __PRIVATE_eventManagerUnlisten(e, o))); + const a = _.docs.has(n); + !a && _.fromCache ? + // TODO(dimond): If we're online and the document doesn't + // exist then we resolve with a doc.exists set to false. If + // we're offline however, we reject the Promise in this + // case. Two options: 1) Cache the negative response from + // the server so we can deliver that even when you're + // offline 2) Actually reject the Promise in the online case + // if the document doesn't exist. + i.reject(new FirestoreError(N.UNAVAILABLE, "Failed to get document because the client is offline.")) : a && _.fromCache && r && "server" === r.source ? i.reject(new FirestoreError(N.UNAVAILABLE, 'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')) : i.resolve(_); + }, + error: e => i.reject(e) + }), o = new __PRIVATE_QueryListener(__PRIVATE_newQueryForPath(n.path), s, { + includeMetadataChanges: !0, + qa: !0 + }); + return __PRIVATE_eventManagerListen(e, o); + }(await __PRIVATE_getEventManager(e), e.asyncQueue, t, n, r))), r.promise; +} + +function __PRIVATE_firestoreClientGetDocumentsFromLocalCache(e, t) { + const n = new __PRIVATE_Deferred; + return e.asyncQueue.enqueueAndForget((async () => async function __PRIVATE_executeQueryFromCache(e, t, n) { + try { + const r = await __PRIVATE_localStoreExecuteQuery(e, t, + /* usePreviousResults= */ !0), i = new __PRIVATE_View(t, r.Qs), s = i.ru(r.documents), o = i.applyChanges(s, + /* limboResolutionEnabled= */ !1); + n.resolve(o.snapshot); + } catch (e) { + const r = __PRIVATE_wrapInUserErrorIfRecoverable(e, `Failed to execute query '${t} against cache`); + n.reject(r); + } + } + /** + * Retrieves a latency-compensated query snapshot from the backend via a + * SnapshotListener. + */ (await __PRIVATE_getLocalStore(e), t, n))), n.promise; +} + +function __PRIVATE_firestoreClientGetDocumentsViaSnapshotListener(e, t, n = {}) { + const r = new __PRIVATE_Deferred; + return e.asyncQueue.enqueueAndForget((async () => function __PRIVATE_executeQueryViaSnapshotListener(e, t, n, r, i) { + const s = new __PRIVATE_AsyncObserver({ + next: n => { + // Mute and remove query first before passing event to user to avoid + // user actions affecting the now stale query. + s.Nu(), t.enqueueAndForget((() => __PRIVATE_eventManagerUnlisten(e, o))), n.fromCache && "server" === r.source ? i.reject(new FirestoreError(N.UNAVAILABLE, 'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')) : i.resolve(n); + }, + error: e => i.reject(e) + }), o = new __PRIVATE_QueryListener(n, s, { + includeMetadataChanges: !0, + qa: !0 + }); + return __PRIVATE_eventManagerListen(e, o); + }(await __PRIVATE_getEventManager(e), e.asyncQueue, t, n, r))), r.promise; +} + +function __PRIVATE_firestoreClientRunAggregateQuery(e, t, n) { + const r = new __PRIVATE_Deferred; + return e.asyncQueue.enqueueAndForget((async () => { + // Implement and call executeAggregateQueryViaSnapshotListener, similar + // to the implementation in firestoreClientGetDocumentsViaSnapshotListener + // above + try { + // TODO(b/277628384): check `canUseNetwork()` and handle multi-tab. + const i = await __PRIVATE_getDatastore(e); + r.resolve(async function __PRIVATE_invokeRunAggregationQueryRpc(e, t, n) { + const r = __PRIVATE_debugCast(e), {request: i, gt: s, parent: o} = __PRIVATE_toRunAggregationQueryRequest(r.serializer, __PRIVATE_queryToAggregateTarget(t), n); + r.connection.$o || delete i.parent; + const _ = (await r.Ho("RunAggregationQuery", r.serializer.databaseId, o, i, + /*expectedResponseCount=*/ 1)).filter((e => !!e.result)); + // Omit RunAggregationQueryResponse that only contain readTimes. + __PRIVATE_hardAssert(1 === _.length, 64727); + // Remap the short-form aliases that were sent to the server + // to the client-side aliases. Users will access the results + // using the client-side alias. + const a = _[0].result?.aggregateFields; + return Object.keys(a).reduce(((e, t) => (e[s[t]] = a[t], e)), {}); + }(i, t, n)); + } catch (e) { + r.reject(e); + } + })), r.promise; +} + +function __PRIVATE_firestoreClientAddSnapshotsInSyncListener(e, t) { + const n = new __PRIVATE_AsyncObserver(t); + return e.asyncQueue.enqueueAndForget((async () => function __PRIVATE_addSnapshotsInSyncListener(e, t) { + __PRIVATE_debugCast(e).Ca.add(t), + // Immediately fire an initial event, indicating all existing listeners + // are in-sync. + t.next(); + }(await __PRIVATE_getEventManager(e), n))), () => { + n.Nu(), e.asyncQueue.enqueueAndForget((async () => function __PRIVATE_removeSnapshotsInSyncListener(e, t) { + __PRIVATE_debugCast(e).Ca.delete(t); + }(await __PRIVATE_getEventManager(e), n))); + }; +} + +/** + * Takes an updateFunction in which a set of reads and writes can be performed + * atomically. In the updateFunction, the client can read and write values + * using the supplied transaction object. After the updateFunction, all + * changes will be committed. If a retryable error occurs (ex: some other + * client has changed any of the data referenced), then the updateFunction + * will be called again after a backoff. If the updateFunction still fails + * after all retries, then the transaction will be rejected. + * + * The transaction object passed to the updateFunction contains methods for + * accessing documents and collections. Unlike other datastore access, data + * accessed with the transaction will not reflect local changes that have not + * been committed. For this reason, it is required that all reads are + * performed before any writes. Transactions must be performed while online. + */ function __PRIVATE_firestoreClientLoadBundle(e, t, n, r) { + const i = function __PRIVATE_createBundleReader(e, t) { + let n; + n = "string" == typeof e ? __PRIVATE_newTextEncoder().encode(e) : e; + return function __PRIVATE_newBundleReader(e, t) { + return new __PRIVATE_BundleReaderImpl(e, t); + }(function __PRIVATE_toByteStreamReader(e, t) { + if (e instanceof Uint8Array) return __PRIVATE_toByteStreamReaderHelper(e, t); + if (e instanceof ArrayBuffer) return __PRIVATE_toByteStreamReaderHelper(new Uint8Array(e), t); + if (e instanceof ReadableStream) return e.getReader(); + throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream"); + }(n), t); + }(n, __PRIVATE_newSerializer(t)); + e.asyncQueue.enqueueAndForget((async () => { + __PRIVATE_syncEngineLoadBundle(await __PRIVATE_getSyncEngine(e), i, r); + })); +} + +function __PRIVATE_firestoreClientGetNamedQuery(e, t) { + return e.asyncQueue.enqueue((async () => function __PRIVATE_localStoreGetNamedQuery(e, t) { + const n = __PRIVATE_debugCast(e); + return n.persistence.runTransaction("Get named query", "readonly", (e => n.Ii.getNamedQuery(e, t))); + }(await __PRIVATE_getLocalStore(e), t))); +} + +function __PRIVATE_createBundleReaderSync(e, t) { + return function __PRIVATE_newBundleReaderSync(e, t) { + return new __PRIVATE_BundleReaderSyncImpl(e, t); + }(e, t); +} + +function __PRIVATE_firestoreClientSetIndexConfiguration(e, t) { + return e.asyncQueue.enqueue((async () => async function __PRIVATE_localStoreConfigureFieldIndexes(e, t) { + const n = __PRIVATE_debugCast(e), r = n.indexManager, i = []; + return n.persistence.runTransaction("Configure indexes", "readwrite", (e => r.getFieldIndexes(e).next((n => + /** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Compares two array for equality using comparator. The method computes the + * intersection and invokes `onAdd` for every element that is in `after` but not + * `before`. `onRemove` is invoked for every element in `before` but missing + * from `after`. + * + * The method creates a copy of both `before` and `after` and runs in O(n log + * n), where n is the size of the two lists. + * + * @param before - The elements that exist in the original array. + * @param after - The elements to diff against the original array. + * @param comparator - The comparator for the elements in before and after. + * @param onAdd - A function to invoke for every element that is part of ` + * after` but not `before`. + * @param onRemove - A function to invoke for every element that is part of + * `before` but not `after`. + */ + function __PRIVATE_diffArrays(e, t, n, r, i) { + e = [ ...e ], t = [ ...t ], e.sort(n), t.sort(n); + const s = e.length, o = t.length; + let _ = 0, a = 0; + for (;_ < o && a < s; ) { + const s = n(e[a], t[_]); + s < 0 ? + // The element was removed if the next element in our ordered + // walkthrough is only in `before`. + i(e[a++]) : s > 0 ? + // The element was added if the next element in our ordered walkthrough + // is only in `after`. + r(t[_++]) : (_++, a++); + } + for (;_ < o; ) r(t[_++]); + for (;a < s; ) i(e[a++]); + } + /** + * Verifies equality for an array of primitives. + * + * @private + * @internal + * @param left Array of primitives. + * @param right Array of primitives. + * @return True if arrays are equal. + */ (n, t, __PRIVATE_fieldIndexSemanticComparator, (t => { + i.push(r.addFieldIndex(e, t)); + }), (t => { + i.push(r.deleteFieldIndex(e, t)); + })))).next((() => PersistencePromise.waitFor(i))))); + }(await __PRIVATE_getLocalStore(e), t))); +} + +function __PRIVATE_firestoreClientSetPersistentCacheIndexAutoCreationEnabled(e, t) { + return e.asyncQueue.enqueue((async () => function __PRIVATE_localStoreSetIndexAutoCreationEnabled(e, t) { + __PRIVATE_debugCast(e).Fs.Vs = t; + }(await __PRIVATE_getLocalStore(e), t))); +} + +function __PRIVATE_firestoreClientDeleteAllFieldIndexes(e) { + return e.asyncQueue.enqueue((async () => function __PRIVATE_localStoreDeleteAllFieldIndexes(e) { + const t = __PRIVATE_debugCast(e), n = t.indexManager; + return t.persistence.runTransaction("Delete All Indexes", "readwrite", (e => n.deleteAllFieldIndexes(e))); + }(await __PRIVATE_getLocalStore(e)))); +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Compares two `ExperimentalLongPollingOptions` objects for equality. + */ +/** + * Creates and returns a new `ExperimentalLongPollingOptions` with the same + * option values as the given instance. + */ +function __PRIVATE_cloneLongPollingOptions(e) { + const t = {}; + return void 0 !== e.timeoutSeconds && (t.timeoutSeconds = e.timeoutSeconds), t; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const _n = new Map; + +/** + * An instance map that ensures only one Datastore exists per Firestore + * instance. + */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// settings() defaults: +const an = "firestore.googleapis.com", un = !0; + +/** + * A concrete type describing all the values that can be applied via a + * user-supplied `FirestoreSettings` object. This is a separate type so that + * defaults can be supplied and the value can be checked for equality. + */ +class FirestoreSettingsImpl { + constructor(e) { + if (void 0 === e.host) { + if (void 0 !== e.ssl) throw new FirestoreError(N.INVALID_ARGUMENT, "Can't provide ssl option if host option is not set"); + this.host = an, this.ssl = un; + } else this.host = e.host, this.ssl = e.ssl ?? un; + if (this.isUsingEmulator = void 0 !== e.emulatorOptions, this.credentials = e.credentials, + this.ignoreUndefinedProperties = !!e.ignoreUndefinedProperties, this.localCache = e.localCache, + void 0 === e.cacheSizeBytes) this.cacheSizeBytes = Ot; else { + if (-1 !== e.cacheSizeBytes && e.cacheSizeBytes < Bt) throw new FirestoreError(N.INVALID_ARGUMENT, "cacheSizeBytes must be at least 1048576"); + this.cacheSizeBytes = e.cacheSizeBytes; + } + __PRIVATE_validateIsNotUsedTogether("experimentalForceLongPolling", e.experimentalForceLongPolling, "experimentalAutoDetectLongPolling", e.experimentalAutoDetectLongPolling), + this.experimentalForceLongPolling = !!e.experimentalForceLongPolling, this.experimentalForceLongPolling ? this.experimentalAutoDetectLongPolling = !1 : void 0 === e.experimentalAutoDetectLongPolling ? this.experimentalAutoDetectLongPolling = true : + // For backwards compatibility, coerce the value to boolean even though + // the TypeScript compiler has narrowed the type to boolean already. + // noinspection PointlessBooleanExpressionJS + this.experimentalAutoDetectLongPolling = !!e.experimentalAutoDetectLongPolling, + this.experimentalLongPollingOptions = __PRIVATE_cloneLongPollingOptions(e.experimentalLongPollingOptions ?? {}), + function __PRIVATE_validateLongPollingOptions(e) { + if (void 0 !== e.timeoutSeconds) { + if (isNaN(e.timeoutSeconds)) throw new FirestoreError(N.INVALID_ARGUMENT, `invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`); + if (e.timeoutSeconds < 5) throw new FirestoreError(N.INVALID_ARGUMENT, `invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`); + if (e.timeoutSeconds > 30) throw new FirestoreError(N.INVALID_ARGUMENT, `invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`); + } + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ (this.experimentalLongPollingOptions), this.useFetchStreams = !!e.useFetchStreams; + } + isEqual(e) { + return this.host === e.host && this.ssl === e.ssl && this.credentials === e.credentials && this.cacheSizeBytes === e.cacheSizeBytes && this.experimentalForceLongPolling === e.experimentalForceLongPolling && this.experimentalAutoDetectLongPolling === e.experimentalAutoDetectLongPolling && function __PRIVATE_longPollingOptionsEqual(e, t) { + return e.timeoutSeconds === t.timeoutSeconds; + }(this.experimentalLongPollingOptions, e.experimentalLongPollingOptions) && this.ignoreUndefinedProperties === e.ignoreUndefinedProperties && this.useFetchStreams === e.useFetchStreams; + } +} + +class Firestore$1 { + /** @hideconstructor */ + constructor(e, t, n, r) { + this._authCredentials = e, this._appCheckCredentials = t, this._databaseId = n, + this._app = r, + /** + * Whether it's a Firestore or Firestore Lite instance. + */ + this.type = "firestore-lite", this._persistenceKey = "(lite)", this._settings = new FirestoreSettingsImpl({}), + this._settingsFrozen = !1, this._emulatorOptions = {}, + // A task that is assigned when the terminate() is invoked and resolved when + // all components have shut down. Otherwise, Firestore is not terminated, + // which can mean either the FirestoreClient is in the process of starting, + // or restarting. + this._terminateTask = "notTerminated"; + } + /** + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service + * instance. + */ get app() { + if (!this._app) throw new FirestoreError(N.FAILED_PRECONDITION, "Firestore was not initialized using the Firebase SDK. 'app' is not available"); + return this._app; + } + get _initialized() { + return this._settingsFrozen; + } + get _terminated() { + return "notTerminated" !== this._terminateTask; + } + _setSettings(e) { + if (this._settingsFrozen) throw new FirestoreError(N.FAILED_PRECONDITION, "Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object."); + this._settings = new FirestoreSettingsImpl(e), this._emulatorOptions = e.emulatorOptions || {}, + void 0 !== e.credentials && (this._authCredentials = function __PRIVATE_makeAuthCredentialsProvider(e) { + if (!e) return new __PRIVATE_EmptyAuthCredentialsProvider; + switch (e.type) { + case "firstParty": + return new __PRIVATE_FirstPartyAuthCredentialsProvider(e.sessionIndex || "0", e.iamToken || null, e.authTokenFactory || null); + + case "provider": + return e.client; + + default: + throw new FirestoreError(N.INVALID_ARGUMENT, "makeAuthCredentialsProvider failed due to invalid credential type"); + } + }(e.credentials)); + } + _getSettings() { + return this._settings; + } + _getEmulatorOptions() { + return this._emulatorOptions; + } + _freezeSettings() { + return this._settingsFrozen = !0, this._settings; + } + _delete() { + // The `_terminateTask` must be assigned future that completes when + // terminate is complete. The existence of this future puts SDK in state + // that will not accept further API interaction. + return "notTerminated" === this._terminateTask && (this._terminateTask = this._terminate()), + this._terminateTask; + } + async _restart() { + // The `_terminateTask` must equal 'notTerminated' after restart to + // signal that client is in a state that accepts API calls. + "notTerminated" === this._terminateTask ? await this._terminate() : this._terminateTask = "notTerminated"; + } + /** Returns a JSON-serializable representation of this `Firestore` instance. */ toJSON() { + return { + app: this._app, + databaseId: this._databaseId, + settings: this._settings + }; + } + /** + * Terminates all components used by this client. Subclasses can override + * this method to clean up their own dependencies, but must also call this + * method. + * + * Only ever called once. + */ _terminate() { + /** + * Removes all components associated with the provided instance. Must be called + * when the `Firestore` instance is terminated. + */ + return function __PRIVATE_removeComponents(e) { + const t = _n.get(e); + t && (__PRIVATE_logDebug("ComponentProvider", "Removing Datastore"), _n.delete(e), + t.terminate()); + }(this), Promise.resolve(); + } +} + +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ function connectFirestoreEmulator(e, t, n, r = {}) { + e = __PRIVATE_cast(e, Firestore$1); + const i = isCloudWorkstation(t), s = e._getSettings(), o = { + ...s, + emulatorOptions: e._getEmulatorOptions() + }, _ = `${t}:${n}`; + i && (pingServer(`https://${_}`), updateEmulatorBanner("Firestore", !0)), s.host !== an && s.host !== _ && __PRIVATE_logWarn("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."); + const a = { + ...s, + host: _, + ssl: i, + emulatorOptions: r + }; + // No-op if the new configuration matches the current configuration. This supports SSR + // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice. + if (!deepEqual(a, o) && (e._setSettings(a), r.mockUserToken)) { + let t, n; + if ("string" == typeof r.mockUserToken) t = r.mockUserToken, n = User.MOCK_USER; else { + // Let createMockUserToken validate first (catches common mistakes like + // invalid field "uid" and missing field "sub" / "user_id".) + t = createMockUserToken(r.mockUserToken, e._app?.options.projectId); + const i = r.mockUserToken.sub || r.mockUserToken.user_id; + if (!i) throw new FirestoreError(N.INVALID_ARGUMENT, "mockUserToken must contain 'sub' or 'user_id' field!"); + n = new User(i); + } + e._authCredentials = new __PRIVATE_EmulatorAuthCredentialsProvider(new __PRIVATE_OAuthToken(t, n)); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `Query` refers to a query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ class Query { + // This is the lite version of the Query class in the main SDK. + /** @hideconstructor protected */ + constructor(e, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + t, n) { + this.converter = t, this._query = n, + /** The type of this Firestore reference. */ + this.type = "query", this.firestore = e; + } + withConverter(e) { + return new Query(this.firestore, e, this._query); + } +} + +/** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. + */ class DocumentReference { + /** @hideconstructor */ + constructor(e, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + t, n) { + this.converter = t, this._key = n, + /** The type of this Firestore reference. */ + this.type = "document", this.firestore = e; + } + get _path() { + return this._key.path; + } + /** + * The document's identifier within its collection. + */ get id() { + return this._key.path.lastSegment(); + } + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ get path() { + return this._key.path.canonicalString(); + } + /** + * The collection this `DocumentReference` belongs to. + */ get parent() { + return new CollectionReference(this.firestore, this.converter, this._key.path.popLast()); + } + withConverter(e) { + return new DocumentReference(this.firestore, e, this._key); + } + /** + * Returns a JSON-serializable representation of this `DocumentReference` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + type: DocumentReference._jsonSchemaVersion, + referencePath: this._key.toString() + }; + } + static fromJSON(e, t, n) { + if (__PRIVATE_validateJSON(t, DocumentReference._jsonSchema)) return new DocumentReference(e, n || null, new DocumentKey(ResourcePath.fromString(t.referencePath))); + } +} + +DocumentReference._jsonSchemaVersion = "firestore/documentReference/1.0", DocumentReference._jsonSchema = { + type: property("string", DocumentReference._jsonSchemaVersion), + referencePath: property("string") +}; + +/** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using {@link (query:1)}). + */ +class CollectionReference extends Query { + /** @hideconstructor */ + constructor(e, t, n) { + super(e, t, __PRIVATE_newQueryForPath(n)), this._path = n, + /** The type of this Firestore reference. */ + this.type = "collection"; + } + /** The collection's identifier. */ get id() { + return this._query.path.lastSegment(); + } + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ get path() { + return this._query.path.canonicalString(); + } + /** + * A reference to the containing `DocumentReference` if this is a + * subcollection. If this isn't a subcollection, the reference is null. + */ get parent() { + const e = this._path.popLast(); + return e.isEmpty() ? null : new DocumentReference(this.firestore, + /* converter= */ null, new DocumentKey(e)); + } + withConverter(e) { + return new CollectionReference(this.firestore, e, this._path); + } +} + +function collection(e, t, ...n) { + if (e = getModularInstance(e), __PRIVATE_validateNonEmptyArgument("collection", "path", t), e instanceof Firestore$1) { + const r = ResourcePath.fromString(t, ...n); + return __PRIVATE_validateCollectionPath(r), new CollectionReference(e, /* converter= */ null, r); + } + { + if (!(e instanceof DocumentReference || e instanceof CollectionReference)) throw new FirestoreError(N.INVALID_ARGUMENT, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore"); + const r = e._path.child(ResourcePath.fromString(t, ...n)); + return __PRIVATE_validateCollectionPath(r), new CollectionReference(e.firestore, + /* converter= */ null, r); + } +} + +// TODO(firestorelite): Consider using ErrorFactory - +// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106 +/** + * Creates and returns a new `Query` instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given `collectionId`. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param collectionId - Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `Query`. + */ function collectionGroup(e, t) { + if (e = __PRIVATE_cast(e, Firestore$1), __PRIVATE_validateNonEmptyArgument("collectionGroup", "collection id", t), + t.indexOf("/") >= 0) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`); + return new Query(e, + /* converter= */ null, function __PRIVATE_newQueryForCollectionGroup(e) { + return new __PRIVATE_QueryImpl(ResourcePath.emptyPath(), e); + }(t)); +} + +function doc(e, t, ...n) { + if (e = getModularInstance(e), + // We allow omission of 'pathString' but explicitly prohibit passing in both + // 'undefined' and 'null'. + 1 === arguments.length && (t = __PRIVATE_AutoId.newId()), __PRIVATE_validateNonEmptyArgument("doc", "path", t), + e instanceof Firestore$1) { + const r = ResourcePath.fromString(t, ...n); + return __PRIVATE_validateDocumentPath(r), new DocumentReference(e, + /* converter= */ null, new DocumentKey(r)); + } + { + if (!(e instanceof DocumentReference || e instanceof CollectionReference)) throw new FirestoreError(N.INVALID_ARGUMENT, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore"); + const r = e._path.child(ResourcePath.fromString(t, ...n)); + return __PRIVATE_validateDocumentPath(r), new DocumentReference(e.firestore, e instanceof CollectionReference ? e.converter : null, new DocumentKey(r)); + } +} + +/** + * Returns true if the provided references are equal. + * + * @param left - A reference to compare. + * @param right - A reference to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ function refEqual(e, t) { + return e = getModularInstance(e), t = getModularInstance(t), (e instanceof DocumentReference || e instanceof CollectionReference) && (t instanceof DocumentReference || t instanceof CollectionReference) && (e.firestore === t.firestore && e.path === t.path && e.converter === t.converter); +} + +/** + * Returns true if the provided queries point to the same collection and apply + * the same constraints. + * + * @param left - A `Query` to compare. + * @param right - A `Query` to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ function queryEqual(e, t) { + return e = getModularInstance(e), t = getModularInstance(t), e instanceof Query && t instanceof Query && (e.firestore === t.firestore && __PRIVATE_queryEquals(e._query, t._query) && e.converter === t.converter); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const cn = "AsyncQueue"; + +class __PRIVATE_AsyncQueueImpl { + constructor(e = Promise.resolve()) { + // A list of retryable operations. Retryable operations are run in order and + // retried with backoff. + this.Xu = [], + // Is this AsyncQueue being shut down? Once it is set to true, it will not + // be changed again. + this.ec = !1, + // Operations scheduled to be queued in the future. Operations are + // automatically removed after they are run or canceled. + this.tc = [], + // visible for testing + this.nc = null, + // Flag set while there's an outstanding AsyncQueue operation, used for + // assertion sanity-checks. + this.rc = !1, + // Enabled during shutdown on Safari to prevent future access to IndexedDB. + this.sc = !1, + // List of TimerIds to fast-forward delays for. + this.oc = [], + // Backoff timer used to schedule retries for retryable operations + this.M_ = new __PRIVATE_ExponentialBackoff(this, "async_queue_retry" /* TimerId.AsyncQueueRetry */), + // Visibility handler that triggers an immediate retry of all retryable + // operations. Meant to speed up recovery when we regain file system access + // after page comes into foreground. + this._c = () => { + const e = getDocument(); + e && __PRIVATE_logDebug(cn, "Visibility state changed to " + e.visibilityState), + this.M_.w_(); + }, this.ac = e; + const t = getDocument(); + t && "function" == typeof t.addEventListener && t.addEventListener("visibilitychange", this._c); + } + get isShuttingDown() { + return this.ec; + } + /** + * Adds a new operation to the queue without waiting for it to complete (i.e. + * we ignore the Promise result). + */ enqueueAndForget(e) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.enqueue(e); + } + enqueueAndForgetEvenWhileRestricted(e) { + this.uc(), + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.cc(e); + } + enterRestrictedMode(e) { + if (!this.ec) { + this.ec = !0, this.sc = e || !1; + const t = getDocument(); + t && "function" == typeof t.removeEventListener && t.removeEventListener("visibilitychange", this._c); + } + } + enqueue(e) { + if (this.uc(), this.ec) + // Return a Promise which never resolves. + return new Promise((() => {})); + // Create a deferred Promise that we can return to the callee. This + // allows us to return a "hanging Promise" only to the callee and still + // advance the queue even when the operation is not run. + const t = new __PRIVATE_Deferred; + return this.cc((() => this.ec && this.sc ? Promise.resolve() : (e().then(t.resolve, t.reject), + t.promise))).then((() => t.promise)); + } + enqueueRetryable(e) { + this.enqueueAndForget((() => (this.Xu.push(e), this.lc()))); + } + /** + * Runs the next operation from the retryable queue. If the operation fails, + * reschedules with backoff. + */ async lc() { + if (0 !== this.Xu.length) { + try { + await this.Xu[0](), this.Xu.shift(), this.M_.reset(); + } catch (e) { + if (!__PRIVATE_isIndexedDbTransactionError(e)) throw e; + // Failure will be handled by AsyncQueue + __PRIVATE_logDebug(cn, "Operation failed with retryable error: " + e); + } + this.Xu.length > 0 && + // If there are additional operations, we re-schedule `retryNextOp()`. + // This is necessary to run retryable operations that failed during + // their initial attempt since we don't know whether they are already + // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1` + // needs to be re-run, we will run `op1`, `op1`, `op2` using the + // already enqueued calls to `retryNextOp()`. `op3()` will then run in the + // call scheduled here. + // Since `backoffAndRun()` cancels an existing backoff and schedules a + // new backoff on every call, there is only ever a single additional + // operation in the queue. + this.M_.p_((() => this.lc())); + } + } + cc(e) { + const t = this.ac.then((() => (this.rc = !0, e().catch((e => { + this.nc = e, this.rc = !1; + // Re-throw the error so that this.tail becomes a rejected Promise and + // all further attempts to chain (via .then) will just short-circuit + // and return the rejected Promise. + throw __PRIVATE_logError("INTERNAL UNHANDLED ERROR: ", __PRIVATE_getMessageOrStack(e)), + e; + })).then((e => (this.rc = !1, e)))))); + return this.ac = t, t; + } + enqueueAfterDelay(e, t, n) { + this.uc(), + // Fast-forward delays for timerIds that have been overridden. + this.oc.indexOf(e) > -1 && (t = 0); + const r = DelayedOperation.createAndSchedule(this, e, t, n, (e => this.hc(e))); + return this.tc.push(r), r; + } + uc() { + this.nc && fail(47125, { + Pc: __PRIVATE_getMessageOrStack(this.nc) + }); + } + verifyOperationInProgress() {} + /** + * Waits until all currently queued tasks are finished executing. Delayed + * operations are not run. + */ async Tc() { + // Operations in the queue prior to draining may have enqueued additional + // operations. Keep draining the queue until the tail is no longer advanced, + // which indicates that no more new operations were enqueued and that all + // operations were executed. + let e; + do { + e = this.ac, await e; + } while (e !== this.ac); + } + /** + * For Tests: Determine if a delayed operation with a particular TimerId + * exists. + */ Ic(e) { + for (const t of this.tc) if (t.timerId === e) return !0; + return !1; + } + /** + * For Tests: Runs some or all delayed operations early. + * + * @param lastTimerId - Delayed operations up to and including this TimerId + * will be drained. Pass TimerId.All to run all delayed operations. + * @returns a Promise that resolves once all operations have been run. + */ Ec(e) { + // Note that draining may generate more delayed ops, so we do that first. + return this.Tc().then((() => { + // Run ops in the same order they'd run if they ran naturally. + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ + this.tc.sort(((e, t) => e.targetTimeMs - t.targetTimeMs)); + for (const t of this.tc) if (t.skipDelay(), "all" /* TimerId.All */ !== e && t.timerId === e) break; + return this.Tc(); + })); + } + /** + * For Tests: Skip all subsequent delays for a timer id. + */ dc(e) { + this.oc.push(e); + } + /** Called once a DelayedOperation is run or canceled. */ hc(e) { + // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small. + const t = this.tc.indexOf(e); + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ this.tc.splice(t, 1); + } +} + +/** + * Chrome includes Error.message in Error.stack. Other browsers do not. + * This returns expected output of message + stack when available. + * @param error - Error or FirestoreError + */ function __PRIVATE_getMessageOrStack(e) { + let t = e.message || ""; + return e.stack && (t = e.stack.includes(e.message) ? e.stack : e.message + "\n" + e.stack), + t; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_isPartialObserver(e) { + /** + * Returns true if obj is an object and contains at least one of the specified + * methods. + */ + return function __PRIVATE_implementsAnyMethods(e, t) { + if ("object" != typeof e || null === e) return !1; + const n = e; + for (const e of t) if (e in n && "function" == typeof n[e]) return !0; + return !1; + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Represents the task of loading a Firestore bundle. It provides progress of bundle + * loading, as well as task completion and error events. + * + * The API is compatible with `Promise`. + */ (e, [ "next", "error", "complete" ]); +} + +class LoadBundleTask { + constructor() { + this._progressObserver = {}, this._taskCompletionResolver = new __PRIVATE_Deferred, + this._lastProgress = { + taskState: "Running", + totalBytes: 0, + totalDocuments: 0, + bytesLoaded: 0, + documentsLoaded: 0 + }; + } + /** + * Registers functions to listen to bundle loading progress events. + * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur + * each time a Firestore document is loaded from the bundle. + * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the + * error, and there should be no more updates after this. + * @param complete - Called when the loading task is complete. + */ onProgress(e, t, n) { + this._progressObserver = { + next: e, + error: t, + complete: n + }; + } + /** + * Implements the `Promise.catch` interface. + * + * @param onRejected - Called when an error occurs during bundle loading. + */ catch(e) { + return this._taskCompletionResolver.promise.catch(e); + } + /** + * Implements the `Promise.then` interface. + * + * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update. + * The update will always have its `taskState` set to `"Success"`. + * @param onRejected - Called when an error occurs during bundle loading. + */ then(e, t) { + return this._taskCompletionResolver.promise.then(e, t); + } + /** + * Notifies all observers that bundle loading has completed, with a provided + * `LoadBundleTaskProgress` object. + * + * @private + */ _completeWith(e) { + this._updateProgress(e), this._progressObserver.complete && this._progressObserver.complete(), + this._taskCompletionResolver.resolve(e); + } + /** + * Notifies all observers that bundle loading has failed, with a provided + * `Error` as the reason. + * + * @private + */ _failWith(e) { + this._lastProgress.taskState = "Error", this._progressObserver.next && this._progressObserver.next(this._lastProgress), + this._progressObserver.error && this._progressObserver.error(e), this._taskCompletionResolver.reject(e); + } + /** + * Notifies a progress update of loading a bundle. + * @param progress - The new progress. + * + * @private + */ _updateProgress(e) { + this._lastProgress = e, this._progressObserver.next && this._progressObserver.next(e); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Constant used to indicate the LRU garbage collection should be disabled. + * Set this value as the `cacheSizeBytes` on the settings passed to the + * {@link Firestore} instance. + */ const ln = -1; + +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ class Firestore extends Firestore$1 { + /** @hideconstructor */ + constructor(e, t, n, r) { + super(e, t, n, r), + /** + * Whether it's a {@link Firestore} or Firestore Lite instance. + */ + this.type = "firestore", this._queue = new __PRIVATE_AsyncQueueImpl, this._persistenceKey = r?.name || "[DEFAULT]"; + } + async _terminate() { + if (this._firestoreClient) { + const e = this._firestoreClient.terminate(); + this._queue = new __PRIVATE_AsyncQueueImpl(e), this._firestoreClient = void 0, await e; + } + } +} + +/** + * Initializes a new instance of {@link Firestore} with the provided settings. + * Can only be called before any other function, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will + * be associated. + * @param settings - A settings object to configure the {@link Firestore} instance. + * @param databaseId - The name of the database. + * @returns A newly initialized {@link Firestore} instance. + */ function initializeFirestore(e, t, n) { + n || (n = lt); + const r = _getProvider(e, "firestore"); + if (r.isInitialized(n)) { + const e = r.getImmediate({ + identifier: n + }), i = r.getOptions(n); + if (deepEqual(i, t)) return e; + throw new FirestoreError(N.FAILED_PRECONDITION, "initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance."); + } + if (void 0 !== t.cacheSizeBytes && void 0 !== t.localCache) throw new FirestoreError(N.INVALID_ARGUMENT, "cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes willbe deprecated. Instead, specify the cache size in the cache object"); + if (void 0 !== t.cacheSizeBytes && -1 !== t.cacheSizeBytes && t.cacheSizeBytes < Bt) throw new FirestoreError(N.INVALID_ARGUMENT, "cacheSizeBytes must be at least 1048576"); + // Workaround to get cookies in Firebase Studio + return t.host && isCloudWorkstation(t.host) && pingServer(t.host), r.initialize({ + options: t, + instanceIdentifier: n + }); +} + +function getFirestore(e, n) { + const r = "object" == typeof e ? e : getApp(), i = "string" == typeof e ? e : n || lt, s = _getProvider(r, "firestore").getImmediate({ + identifier: i + }); + if (!s._initialized) { + const e = getDefaultEmulatorHostnameAndPort("firestore"); + e && connectFirestoreEmulator(s, ...e); + } + return s; +} + +/** + * @internal + */ function ensureFirestoreConfigured(e) { + if (e._terminated) throw new FirestoreError(N.FAILED_PRECONDITION, "The client has already been terminated."); + return e._firestoreClient || __PRIVATE_configureFirestore(e), e._firestoreClient; +} + +function __PRIVATE_configureFirestore(e) { + const t = e._freezeSettings(), n = function __PRIVATE_makeDatabaseInfo(e, t, n, r) { + return new DatabaseInfo(e, t, n, r.host, r.ssl, r.experimentalForceLongPolling, r.experimentalAutoDetectLongPolling, __PRIVATE_cloneLongPollingOptions(r.experimentalLongPollingOptions), r.useFetchStreams, r.isUsingEmulator); + }(e._databaseId, e._app?.options.appId || "", e._persistenceKey, t); + e._componentsProvider || t.localCache?._offlineComponentProvider && t.localCache?._onlineComponentProvider && (e._componentsProvider = { + _offline: t.localCache._offlineComponentProvider, + _online: t.localCache._onlineComponentProvider + }), e._firestoreClient = new FirestoreClient(e._authCredentials, e._appCheckCredentials, e._queue, n, e._componentsProvider && function __PRIVATE_buildComponentProvider(e) { + const t = e?._online.build(); + return { + _offline: e?._offline.build(t), + _online: t + }; + } + /** + * Attempts to enable persistent storage, if possible. + * + * On failure, `enableIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. + * + * * failed-precondition: The app is already open in another browser tab. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. + * + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. + * + * Note: `enableIndexedDbPersistence()` must be called before any other functions + * (other than {@link initializeFirestore}, {@link (getFirestore:1)} or + * {@link clearIndexedDbPersistence}. + * + * Persistence cannot be used in a Node.js environment. + * + * @param firestore - The {@link Firestore} instance to enable persistence for. + * @param persistenceSettings - Optional settings object to configure + * persistence. + * @returns A `Promise` that represents successfully enabling persistent storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on IndexedDb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. + */ (e._componentsProvider)); +} + +function enableIndexedDbPersistence(e, t) { + __PRIVATE_logWarn("enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead."); + const n = e._freezeSettings(); + return __PRIVATE_setPersistenceProviders(e, OnlineComponentProvider.provider, { + build: e => new __PRIVATE_IndexedDbOfflineComponentProvider(e, n.cacheSizeBytes, t?.forceOwnership) + }), Promise.resolve(); +} + +/** + * Attempts to enable multi-tab persistent storage, if possible. If enabled + * across all tabs, all operations share access to local persistence, including + * shared execution of queries and latency-compensated local document updates + * across all connected instances. + * + * On failure, `enableMultiTabIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. + * + * * failed-precondition: The app is already open in another browser tab and + * multi-tab is not enabled. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. + * + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. + * + * @param firestore - The {@link Firestore} instance to enable persistence for. + * @returns A `Promise` that represents successfully enabling persistent + * storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on indexeddb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. + */ async function enableMultiTabIndexedDbPersistence(e) { + __PRIVATE_logWarn("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead."); + const t = e._freezeSettings(); + __PRIVATE_setPersistenceProviders(e, OnlineComponentProvider.provider, { + build: e => new __PRIVATE_MultiTabOfflineComponentProvider(e, t.cacheSizeBytes) + }); +} + +/** + * Registers both the `OfflineComponentProvider` and `OnlineComponentProvider`. + * If the operation fails with a recoverable error (see + * `canRecoverFromIndexedDbError()` below), the returned Promise is rejected + * but the client remains usable. + */ function __PRIVATE_setPersistenceProviders(e, t, n) { + if ((e = __PRIVATE_cast(e, Firestore))._firestoreClient || e._terminated) throw new FirestoreError(N.FAILED_PRECONDITION, "Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object."); + if (e._componentsProvider || e._getSettings().localCache) throw new FirestoreError(N.FAILED_PRECONDITION, "SDK cache is already specified."); + e._componentsProvider = { + _online: t, + _offline: n + }, __PRIVATE_configureFirestore(e); +} + +/** + * Clears the persistent storage. This includes pending writes and cached + * documents. + * + * Must be called while the {@link Firestore} instance is not started (after the app is + * terminated or when the app is first initialized). On startup, this function + * must be called before other functions (other than {@link + * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore} + * instance is still running, the promise will be rejected with the error code + * of `failed-precondition`. + * + * Note: `clearIndexedDbPersistence()` is primarily intended to help write + * reliable tests that use Cloud Firestore. It uses an efficient mechanism for + * dropping existing data but does not attempt to securely overwrite or + * otherwise make cached data unrecoverable. For applications that are sensitive + * to the disclosure of cached data in between user sessions, we strongly + * recommend not enabling persistence at all. + * + * @param firestore - The {@link Firestore} instance to clear persistence for. + * @returns A `Promise` that is resolved when the persistent storage is + * cleared. Otherwise, the promise is rejected with an error. + */ function clearIndexedDbPersistence(e) { + if (e._initialized && !e._terminated) throw new FirestoreError(N.FAILED_PRECONDITION, "Persistence can only be cleared before a Firestore instance is initialized or after it is terminated."); + const t = new __PRIVATE_Deferred; + return e._queue.enqueueAndForgetEvenWhileRestricted((async () => { + try { + await async function __PRIVATE_indexedDbClearPersistence(e) { + if (!__PRIVATE_SimpleDb.v()) return Promise.resolve(); + const t = e + $t; + await __PRIVATE_SimpleDb.delete(t); + }(__PRIVATE_indexedDbStoragePrefix(e._databaseId, e._persistenceKey)), t.resolve(); + } catch (e) { + t.reject(e); + } + })), t.promise; +} + +/** + * Waits until all currently pending writes for the active user have been + * acknowledged by the backend. + * + * The returned promise resolves immediately if there are no outstanding writes. + * Otherwise, the promise waits for all previously issued writes (including + * those written in a previous app session), but it does not wait for writes + * that were added after the function is called. If you want to wait for + * additional writes, call `waitForPendingWrites()` again. + * + * Any outstanding `waitForPendingWrites()` promises are rejected during user + * changes. + * + * @returns A `Promise` which resolves when all currently pending writes have been + * acknowledged by the backend. + */ function waitForPendingWrites(e) { + return function __PRIVATE_firestoreClientWaitForPendingWrites(e) { + const t = new __PRIVATE_Deferred; + return e.asyncQueue.enqueueAndForget((async () => __PRIVATE_syncEngineRegisterPendingWritesCallback(await __PRIVATE_getSyncEngine(e), t))), + t.promise; + }(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore))); +} + +/** + * Re-enables use of the network for this {@link Firestore} instance after a prior + * call to {@link disableNetwork}. + * + * @returns A `Promise` that is resolved once the network has been enabled. + */ function enableNetwork(e) { + return __PRIVATE_firestoreClientEnableNetwork(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore))); +} + +/** + * Disables network usage for this instance. It can be re-enabled via {@link + * enableNetwork}. While the network is disabled, any snapshot listeners, + * `getDoc()` or `getDocs()` calls will return results from cache, and any write + * operations will be queued until the network is restored. + * + * @returns A `Promise` that is resolved once the network has been disabled. + */ function disableNetwork(e) { + return __PRIVATE_firestoreClientDisableNetwork(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore))); +} + +/** + * Terminates the provided {@link Firestore} instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` function + * may be used. Any other function will throw a `FirestoreError`. + * + * To restart after termination, create a new instance of FirebaseFirestore with + * {@link (getFirestore:1)}. + * + * Termination does not cancel any pending writes, and any promises that are + * awaiting a response from the server will not be resolved. If you have + * persistence enabled, the next time you start this instance, it will resume + * sending these writes to the server. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all + * of its resources or in combination with `clearIndexedDbPersistence()` to + * ensure that all local state is destroyed between test runs. + * + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ function terminate(e) { + return _removeServiceInstance(e.app, "firestore", e._databaseId.database), e._delete(); +} + +/** + * Loads a Firestore bundle into the local cache. + * + * @param firestore - The {@link Firestore} instance to load bundles for. + * @param bundleData - An object representing the bundle to be loaded. Valid + * objects are `ArrayBuffer`, `ReadableStream` or `string`. + * + * @returns A `LoadBundleTask` object, which notifies callers with progress + * updates, and completion or error events. It can be used as a + * `Promise`. + */ function loadBundle(e, t) { + const n = ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)), r = new LoadBundleTask; + return __PRIVATE_firestoreClientLoadBundle(n, e._databaseId, t, r), r; +} + +/** + * Reads a Firestore {@link Query} from local cache, identified by the given + * name. + * + * The named queries are packaged into bundles on the server side (along + * with resulting documents), and loaded to local cache using `loadBundle`. Once + * in local cache, use this method to extract a {@link Query} by name. + * + * @param firestore - The {@link Firestore} instance to read the query from. + * @param name - The name of the query. + * @returns A `Promise` that is resolved with the Query or `null`. + */ function namedQuery(e, t) { + return __PRIVATE_firestoreClientGetNamedQuery(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)), t).then((t => t ? new Query(e, null, t.query) : null)); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents an aggregation that can be performed by Firestore. + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +class AggregateField { + /** + * Create a new AggregateField + * @param aggregateType Specifies the type of aggregation operation to perform. + * @param _internalFieldPath Optionally specifies the field that is aggregated. + * @internal + */ + constructor(e = "count", t) { + this._internalFieldPath = t, + /** A type string to uniquely identify instances of this class. */ + this.type = "AggregateField", this.aggregateType = e; + } +} + +/** + * The results of executing an aggregation query. + */ class AggregateQuerySnapshot { + /** @hideconstructor */ + constructor(e, t, n) { + this._userDataWriter = t, this._data = n, + /** A type string to uniquely identify instances of this class. */ + this.type = "AggregateQuerySnapshot", this.query = e; + } + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ data() { + return this._userDataWriter.convertObjectMap(this._data); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing an array of bytes. + */ class Bytes { + /** @hideconstructor */ + constructor(e) { + this._byteString = e; + } + /** + * Creates a new `Bytes` object from the given Base64 string, converting it to + * bytes. + * + * @param base64 - The Base64 string used to create the `Bytes` object. + */ static fromBase64String(e) { + try { + return new Bytes(ByteString.fromBase64String(e)); + } catch (e) { + throw new FirestoreError(N.INVALID_ARGUMENT, "Failed to construct data from Base64 string: " + e); + } + } + /** + * Creates a new `Bytes` object from the given Uint8Array. + * + * @param array - The Uint8Array used to create the `Bytes` object. + */ static fromUint8Array(e) { + return new Bytes(ByteString.fromUint8Array(e)); + } + /** + * Returns the underlying bytes as a Base64-encoded string. + * + * @returns The Base64-encoded string created from the `Bytes` object. + */ toBase64() { + return this._byteString.toBase64(); + } + /** + * Returns the underlying bytes in a new `Uint8Array`. + * + * @returns The Uint8Array created from the `Bytes` object. + */ toUint8Array() { + return this._byteString.toUint8Array(); + } + /** + * Returns a string representation of the `Bytes` object. + * + * @returns A string representation of the `Bytes` object. + */ toString() { + return "Bytes(base64: " + this.toBase64() + ")"; + } + /** + * Returns true if this `Bytes` object is equal to the provided one. + * + * @param other - The `Bytes` object to compare against. + * @returns true if this `Bytes` object is equal to the provided one. + */ isEqual(e) { + return this._byteString.isEqual(e._byteString); + } + /** + * Returns a JSON-serializable representation of this `Bytes` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + type: Bytes._jsonSchemaVersion, + bytes: this.toBase64() + }; + } + /** + * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}. + * + * @param json a JSON object represention of a `Bytes` instance + * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ static fromJSON(e) { + if (__PRIVATE_validateJSON(e, Bytes._jsonSchema)) return Bytes.fromBase64String(e.bytes); + } +} + +Bytes._jsonSchemaVersion = "firestore/bytes/1.0", Bytes._jsonSchema = { + type: property("string", Bytes._jsonSchemaVersion), + bytes: property("string") +}; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `FieldPath` refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + * + * Create a `FieldPath` by providing field names. If more than one field + * name is provided, the path will point to a nested field in a document. + */ +class FieldPath { + /** + * Creates a `FieldPath` from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames - A list of field names. + */ + constructor(...e) { + for (let t = 0; t < e.length; ++t) if (0 === e[t].length) throw new FirestoreError(N.INVALID_ARGUMENT, "Invalid field name at argument $(i + 1). Field names must not be empty."); + this._internalPath = new FieldPath$1(e); + } + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other - The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ isEqual(e) { + return this._internalPath.isEqual(e._internalPath); + } +} + +/** + * Returns a special sentinel `FieldPath` to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ function documentId() { + return new FieldPath(k); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Sentinel values that can be used when writing document fields with `set()` + * or `update()`. + */ class FieldValue { + /** + * @param _methodName - The public API endpoint that returns this class. + * @hideconstructor + */ + constructor(e) { + this._methodName = e; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ class GeoPoint { + /** + * Creates a new immutable `GeoPoint` object with the provided latitude and + * longitude values. + * @param latitude - The latitude as number between -90 and 90. + * @param longitude - The longitude as number between -180 and 180. + */ + constructor(e, t) { + if (!isFinite(e) || e < -90 || e > 90) throw new FirestoreError(N.INVALID_ARGUMENT, "Latitude must be a number between -90 and 90, but was: " + e); + if (!isFinite(t) || t < -180 || t > 180) throw new FirestoreError(N.INVALID_ARGUMENT, "Longitude must be a number between -180 and 180, but was: " + t); + this._lat = e, this._long = t; + } + /** + * The latitude of this `GeoPoint` instance. + */ get latitude() { + return this._lat; + } + /** + * The longitude of this `GeoPoint` instance. + */ get longitude() { + return this._long; + } + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other - The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ isEqual(e) { + return this._lat === e._lat && this._long === e._long; + } + /** + * Actually private to JS consumers of our API, so this function is prefixed + * with an underscore. + */ _compareTo(e) { + return __PRIVATE_primitiveComparator(this._lat, e._lat) || __PRIVATE_primitiveComparator(this._long, e._long); + } + /** + * Returns a JSON-serializable representation of this `GeoPoint` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + latitude: this._lat, + longitude: this._long, + type: GeoPoint._jsonSchemaVersion + }; + } + /** + * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}. + * + * @param json a JSON object represention of a `GeoPoint` instance + * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ static fromJSON(e) { + if (__PRIVATE_validateJSON(e, GeoPoint._jsonSchema)) return new GeoPoint(e.latitude, e.longitude); + } +} + +GeoPoint._jsonSchemaVersion = "firestore/geoPoint/1.0", GeoPoint._jsonSchema = { + type: property("string", GeoPoint._jsonSchemaVersion), + latitude: property("number"), + longitude: property("number") +}; + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link vector}. + * + * @class VectorValue + */ +class VectorValue { + /** + * @private + * @internal + */ + constructor(e) { + // Making a copy of the parameter. + this._values = (e || []).map((e => e)); + } + /** + * Returns a copy of the raw number array form of the vector. + */ toArray() { + return this._values.map((e => e)); + } + /** + * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise. + */ isEqual(e) { + return function __PRIVATE_isPrimitiveArrayEqual(e, t) { + if (e.length !== t.length) return !1; + for (let n = 0; n < e.length; ++n) if (e[n] !== t[n]) return !1; + return !0; + }(this._values, e._values); + } + /** + * Returns a JSON-serializable representation of this `VectorValue` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + type: VectorValue._jsonSchemaVersion, + vectorValues: this._values + }; + } + /** + * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}. + * + * @param json a JSON object represention of a `VectorValue` instance. + * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ static fromJSON(e) { + if (__PRIVATE_validateJSON(e, VectorValue._jsonSchema)) { + if (Array.isArray(e.vectorValues) && e.vectorValues.every((e => "number" == typeof e))) return new VectorValue(e.vectorValues); + throw new FirestoreError(N.INVALID_ARGUMENT, "Expected 'vectorValues' field to be a number array"); + } + } +} + +VectorValue._jsonSchemaVersion = "firestore/vectorValue/1.0", VectorValue._jsonSchema = { + type: property("string", VectorValue._jsonSchemaVersion), + vectorValues: property("object") +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const hn = /^__.*__$/; + +/** The result of parsing document data (e.g. for a setData call). */ class ParsedSetData { + constructor(e, t, n) { + this.data = e, this.fieldMask = t, this.fieldTransforms = n; + } + toMutation(e, t) { + return null !== this.fieldMask ? new __PRIVATE_PatchMutation(e, this.data, this.fieldMask, t, this.fieldTransforms) : new __PRIVATE_SetMutation(e, this.data, t, this.fieldTransforms); + } +} + +/** The result of parsing "update" data (i.e. for an updateData call). */ class ParsedUpdateData { + constructor(e, + // The fieldMask does not include document transforms. + t, n) { + this.data = e, this.fieldMask = t, this.fieldTransforms = n; + } + toMutation(e, t) { + return new __PRIVATE_PatchMutation(e, this.data, this.fieldMask, t, this.fieldTransforms); + } +} + +function __PRIVATE_isWrite(e) { + switch (e) { + case 0 /* UserDataSource.Set */ : + // fall through + case 2 /* UserDataSource.MergeSet */ : + // fall through + case 1 /* UserDataSource.Update */ : + return !0; + + case 3 /* UserDataSource.Argument */ : + case 4 /* UserDataSource.ArrayArgument */ : + return !1; + + default: + throw fail(40011, { + Ac: e + }); + } +} + +/** A "context" object passed around while parsing user data. */ class __PRIVATE_ParseContextImpl { + /** + * Initializes a ParseContext with the given source and path. + * + * @param settings - The settings for the parser. + * @param databaseId - The database ID of the Firestore instance. + * @param serializer - The serializer to use to generate the Value proto. + * @param ignoreUndefinedProperties - Whether to ignore undefined properties + * rather than throw. + * @param fieldTransforms - A mutable list of field transforms encountered + * while parsing the data. + * @param fieldMask - A mutable list of field paths encountered while parsing + * the data. + * + * TODO(b/34871131): We don't support array paths right now, so path can be + * null to indicate the context represents any location within an array (in + * which case certain features will not work and errors will be somewhat + * compromised). + */ + constructor(e, t, n, r, i, s) { + this.settings = e, this.databaseId = t, this.serializer = n, this.ignoreUndefinedProperties = r, + // Minor hack: If fieldTransforms is undefined, we assume this is an + // external call and we need to validate the entire path. + void 0 === i && this.Rc(), this.fieldTransforms = i || [], this.fieldMask = s || []; + } + get path() { + return this.settings.path; + } + get Ac() { + return this.settings.Ac; + } + /** Returns a new context with the specified settings overwritten. */ Vc(e) { + return new __PRIVATE_ParseContextImpl({ + ...this.settings, + ...e + }, this.databaseId, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask); + } + mc(e) { + const t = this.path?.child(e), n = this.Vc({ + path: t, + fc: !1 + }); + return n.gc(e), n; + } + yc(e) { + const t = this.path?.child(e), n = this.Vc({ + path: t, + fc: !1 + }); + return n.Rc(), n; + } + wc(e) { + // TODO(b/34871131): We don't support array paths right now; so make path + // undefined. + return this.Vc({ + path: void 0, + fc: !0 + }); + } + Sc(e) { + return __PRIVATE_createError(e, this.settings.methodName, this.settings.bc || !1, this.path, this.settings.Dc); + } + /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ contains(e) { + return void 0 !== this.fieldMask.find((t => e.isPrefixOf(t))) || void 0 !== this.fieldTransforms.find((t => e.isPrefixOf(t.field))); + } + Rc() { + // TODO(b/34871131): Remove null check once we have proper paths for fields + // within arrays. + if (this.path) for (let e = 0; e < this.path.length; e++) this.gc(this.path.get(e)); + } + gc(e) { + if (0 === e.length) throw this.Sc("Document fields must not be empty"); + if (__PRIVATE_isWrite(this.Ac) && hn.test(e)) throw this.Sc('Document fields cannot begin and end with "__"'); + } +} + +/** + * Helper for parsing raw user input (provided via the API) into internal model + * classes. + */ class __PRIVATE_UserDataReader { + constructor(e, t, n) { + this.databaseId = e, this.ignoreUndefinedProperties = t, this.serializer = n || __PRIVATE_newSerializer(e); + } + /** Creates a new top-level parse context. */ Cc(e, t, n, r = !1) { + return new __PRIVATE_ParseContextImpl({ + Ac: e, + methodName: t, + Dc: n, + path: FieldPath$1.emptyPath(), + fc: !1, + bc: r + }, this.databaseId, this.serializer, this.ignoreUndefinedProperties); + } +} + +function __PRIVATE_newUserDataReader(e) { + const t = e._freezeSettings(), n = __PRIVATE_newSerializer(e._databaseId); + return new __PRIVATE_UserDataReader(e._databaseId, !!t.ignoreUndefinedProperties, n); +} + +/** Parse document data from a set() call. */ function __PRIVATE_parseSetData(e, t, n, r, i, s = {}) { + const o = e.Cc(s.merge || s.mergeFields ? 2 /* UserDataSource.MergeSet */ : 0 /* UserDataSource.Set */ , t, n, i); + __PRIVATE_validatePlainObject("Data must be an object, but it was:", o, r); + const _ = __PRIVATE_parseObject(r, o); + let a, u; + if (s.merge) a = new FieldMask(o.fieldMask), u = o.fieldTransforms; else if (s.mergeFields) { + const e = []; + for (const r of s.mergeFields) { + const i = __PRIVATE_fieldPathFromArgument$1(t, r, n); + if (!o.contains(i)) throw new FirestoreError(N.INVALID_ARGUMENT, `Field '${i}' is specified in your field mask but missing from your input data.`); + __PRIVATE_fieldMaskContains(e, i) || e.push(i); + } + a = new FieldMask(e), u = o.fieldTransforms.filter((e => a.covers(e.field))); + } else a = null, u = o.fieldTransforms; + return new ParsedSetData(new ObjectValue(_), a, u); +} + +class __PRIVATE_DeleteFieldValueImpl extends FieldValue { + _toFieldTransform(e) { + if (2 /* UserDataSource.MergeSet */ !== e.Ac) throw 1 /* UserDataSource.Update */ === e.Ac ? e.Sc(`${this._methodName}() can only appear at the top level of your update data`) : e.Sc(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`); + // No transform to add for a delete, but we need to add it to our + // fieldMask so it gets deleted. + return e.fieldMask.push(e.path), null; + } + isEqual(e) { + return e instanceof __PRIVATE_DeleteFieldValueImpl; + } +} + +/** + * Creates a child context for parsing SerializableFieldValues. + * + * This is different than calling `ParseContext.contextWith` because it keeps + * the fieldTransforms and fieldMask separate. + * + * The created context has its `dataSource` set to `UserDataSource.Argument`. + * Although these values are used with writes, any elements in these FieldValues + * are not considered writes since they cannot contain any FieldValue sentinels, + * etc. + * + * @param fieldValue - The sentinel FieldValue for which to create a child + * context. + * @param context - The parent context. + * @param arrayElement - Whether or not the FieldValue has an array. + */ function __PRIVATE_createSentinelChildContext(e, t, n) { + return new __PRIVATE_ParseContextImpl({ + Ac: 3 /* UserDataSource.Argument */ , + Dc: t.settings.Dc, + methodName: e._methodName, + fc: n + }, t.databaseId, t.serializer, t.ignoreUndefinedProperties); +} + +class __PRIVATE_ServerTimestampFieldValueImpl extends FieldValue { + _toFieldTransform(e) { + return new FieldTransform(e.path, new __PRIVATE_ServerTimestampTransform); + } + isEqual(e) { + return e instanceof __PRIVATE_ServerTimestampFieldValueImpl; + } +} + +class __PRIVATE_ArrayUnionFieldValueImpl extends FieldValue { + constructor(e, t) { + super(e), this.vc = t; + } + _toFieldTransform(e) { + const t = __PRIVATE_createSentinelChildContext(this, e, + /*array=*/ !0), n = this.vc.map((e => __PRIVATE_parseData(e, t))), r = new __PRIVATE_ArrayUnionTransformOperation(n); + return new FieldTransform(e.path, r); + } + isEqual(e) { + return e instanceof __PRIVATE_ArrayUnionFieldValueImpl && deepEqual(this.vc, e.vc); + } +} + +class __PRIVATE_ArrayRemoveFieldValueImpl extends FieldValue { + constructor(e, t) { + super(e), this.vc = t; + } + _toFieldTransform(e) { + const t = __PRIVATE_createSentinelChildContext(this, e, + /*array=*/ !0), n = this.vc.map((e => __PRIVATE_parseData(e, t))), r = new __PRIVATE_ArrayRemoveTransformOperation(n); + return new FieldTransform(e.path, r); + } + isEqual(e) { + return e instanceof __PRIVATE_ArrayRemoveFieldValueImpl && deepEqual(this.vc, e.vc); + } +} + +class __PRIVATE_NumericIncrementFieldValueImpl extends FieldValue { + constructor(e, t) { + super(e), this.Fc = t; + } + _toFieldTransform(e) { + const t = new __PRIVATE_NumericIncrementTransformOperation(e.serializer, toNumber(e.serializer, this.Fc)); + return new FieldTransform(e.path, t); + } + isEqual(e) { + return e instanceof __PRIVATE_NumericIncrementFieldValueImpl && this.Fc === e.Fc; + } +} + +/** Parse update data from an update() call. */ function __PRIVATE_parseUpdateData(e, t, n, r) { + const i = e.Cc(1 /* UserDataSource.Update */ , t, n); + __PRIVATE_validatePlainObject("Data must be an object, but it was:", i, r); + const s = [], o = ObjectValue.empty(); + forEach(r, ((e, r) => { + const _ = __PRIVATE_fieldPathFromDotSeparatedString(t, e, n); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + r = getModularInstance(r); + const a = i.yc(_); + if (r instanceof __PRIVATE_DeleteFieldValueImpl) + // Add it to the field mask, but don't add anything to updateData. + s.push(_); else { + const e = __PRIVATE_parseData(r, a); + null != e && (s.push(_), o.set(_, e)); + } + })); + const _ = new FieldMask(s); + return new ParsedUpdateData(o, _, i.fieldTransforms); +} + +/** Parse update data from a list of field/value arguments. */ function __PRIVATE_parseUpdateVarargs(e, t, n, r, i, s) { + const o = e.Cc(1 /* UserDataSource.Update */ , t, n), _ = [ __PRIVATE_fieldPathFromArgument$1(t, r, n) ], a = [ i ]; + if (s.length % 2 != 0) throw new FirestoreError(N.INVALID_ARGUMENT, `Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`); + for (let e = 0; e < s.length; e += 2) _.push(__PRIVATE_fieldPathFromArgument$1(t, s[e])), + a.push(s[e + 1]); + const u = [], c = ObjectValue.empty(); + // We iterate in reverse order to pick the last value for a field if the + // user specified the field multiple times. + for (let e = _.length - 1; e >= 0; --e) if (!__PRIVATE_fieldMaskContains(u, _[e])) { + const t = _[e]; + let n = a[e]; + // For Compat types, we have to "extract" the underlying types before + // performing validation. + n = getModularInstance(n); + const r = o.yc(t); + if (n instanceof __PRIVATE_DeleteFieldValueImpl) + // Add it to the field mask, but don't add anything to updateData. + u.push(t); else { + const e = __PRIVATE_parseData(n, r); + null != e && (u.push(t), c.set(t, e)); + } + } + const l = new FieldMask(u); + return new ParsedUpdateData(c, l, o.fieldTransforms); +} + +/** + * Parse a "query value" (e.g. value in a where filter or a value in a cursor + * bound). + * + * @param allowArrays - Whether the query value is an array that may directly + * contain additional arrays (e.g. the operand of an `in` query). + */ function __PRIVATE_parseQueryValue(e, t, n, r = !1) { + return __PRIVATE_parseData(n, e.Cc(r ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */ , t)); +} + +/** + * Parses user data to Protobuf Values. + * + * @param input - Data to be parsed. + * @param context - A context object representing the current path being parsed, + * the source of the data being parsed, etc. + * @returns The parsed value, or null if the value was a FieldValue sentinel + * that should not be included in the resulting parsed data. + */ function __PRIVATE_parseData(e, t) { + if (__PRIVATE_looksLikeJsonObject( + // Unwrap the API type from the Compat SDK. This will return the API type + // from firestore-exp. + e = getModularInstance(e))) return __PRIVATE_validatePlainObject("Unsupported field value:", t, e), + __PRIVATE_parseObject(e, t); + if (e instanceof FieldValue) + // FieldValues usually parse into transforms (except deleteField()) + // in which case we do not want to include this field in our parsed data + // (as doing so will overwrite the field directly prior to the transform + // trying to transform it). So we don't add this location to + // context.fieldMask and we return null as our parsing result. + /** + * "Parses" the provided FieldValueImpl, adding any necessary transforms to + * context.fieldTransforms. + */ + return function __PRIVATE_parseSentinelFieldValue(e, t) { + // Sentinels are only supported with writes, and not within arrays. + if (!__PRIVATE_isWrite(t.Ac)) throw t.Sc(`${e._methodName}() can only be used with update() and set()`); + if (!t.path) throw t.Sc(`${e._methodName}() is not currently supported inside arrays`); + const n = e._toFieldTransform(t); + n && t.fieldTransforms.push(n); + } + /** + * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue) + * + * @returns The parsed value + */ (e, t), null; + if (void 0 === e && t.ignoreUndefinedProperties) + // If the input is undefined it can never participate in the fieldMask, so + // don't handle this below. If `ignoreUndefinedProperties` is false, + // `parseScalarValue` will reject an undefined value. + return null; + if ( + // If context.path is null we are inside an array and we don't support + // field mask paths more granular than the top-level array. + t.path && t.fieldMask.push(t.path), e instanceof Array) { + // TODO(b/34871131): Include the path containing the array in the error + // message. + // In the case of IN queries, the parsed data is an array (representing + // the set of values to be included for the IN query) that may directly + // contain additional arrays (each representing an individual field + // value), so we disable this validation. + if (t.settings.fc && 4 /* UserDataSource.ArrayArgument */ !== t.Ac) throw t.Sc("Nested arrays are not supported"); + return function __PRIVATE_parseArray(e, t) { + const n = []; + let r = 0; + for (const i of e) { + let e = __PRIVATE_parseData(i, t.wc(r)); + null == e && ( + // Just include nulls in the array for fields being replaced with a + // sentinel. + e = { + nullValue: "NULL_VALUE" + }), n.push(e), r++; + } + return { + arrayValue: { + values: n + } + }; + }(e, t); + } + return function __PRIVATE_parseScalarValue(e, t) { + if (null === (e = getModularInstance(e))) return { + nullValue: "NULL_VALUE" + }; + if ("number" == typeof e) return toNumber(t.serializer, e); + if ("boolean" == typeof e) return { + booleanValue: e + }; + if ("string" == typeof e) return { + stringValue: e + }; + if (e instanceof Date) { + const n = Timestamp.fromDate(e); + return { + timestampValue: toTimestamp(t.serializer, n) + }; + } + if (e instanceof Timestamp) { + // Firestore backend truncates precision down to microseconds. To ensure + // offline mode works the same with regards to truncation, perform the + // truncation immediately without waiting for the backend to do that. + const n = new Timestamp(e.seconds, 1e3 * Math.floor(e.nanoseconds / 1e3)); + return { + timestampValue: toTimestamp(t.serializer, n) + }; + } + if (e instanceof GeoPoint) return { + geoPointValue: { + latitude: e.latitude, + longitude: e.longitude + } + }; + if (e instanceof Bytes) return { + bytesValue: __PRIVATE_toBytes(t.serializer, e._byteString) + }; + if (e instanceof DocumentReference) { + const n = t.databaseId, r = e.firestore._databaseId; + if (!r.isEqual(n)) throw t.Sc(`Document reference is for database ${r.projectId}/${r.database} but should be for database ${n.projectId}/${n.database}`); + return { + referenceValue: __PRIVATE_toResourceName(e.firestore._databaseId || t.databaseId, e._key.path) + }; + } + if (e instanceof VectorValue) + /** + * Creates a new VectorValue proto value (using the internal format). + */ + return function __PRIVATE_parseVectorValue(e, t) { + const n = { + fields: { + [ht]: { + stringValue: It + }, + [Et]: { + arrayValue: { + values: e.toArray().map((e => { + if ("number" != typeof e) throw t.Sc("VectorValues must only contain numeric values."); + return __PRIVATE_toDouble(t.serializer, e); + })) + } + } + } + }; + return { + mapValue: n + }; + } + /** + * Checks whether an object looks like a JSON object that should be converted + * into a struct. Normal class/prototype instances are considered to look like + * JSON objects since they should be converted to a struct value. Arrays, Dates, + * GeoPoints, etc. are not considered to look like JSON objects since they map + * to specific FieldValue types other than ObjectValue. + */ (e, t); + throw t.Sc(`Unsupported field value: ${__PRIVATE_valueDescription(e)}`); + }(e, t); +} + +function __PRIVATE_parseObject(e, t) { + const n = {}; + return isEmpty(e) ? + // If we encounter an empty object, we explicitly add it to the update + // mask to ensure that the server creates a map entry. + t.path && t.path.length > 0 && t.fieldMask.push(t.path) : forEach(e, ((e, r) => { + const i = __PRIVATE_parseData(r, t.mc(e)); + null != i && (n[e] = i); + })), { + mapValue: { + fields: n + } + }; +} + +function __PRIVATE_looksLikeJsonObject(e) { + return !("object" != typeof e || null === e || e instanceof Array || e instanceof Date || e instanceof Timestamp || e instanceof GeoPoint || e instanceof Bytes || e instanceof DocumentReference || e instanceof FieldValue || e instanceof VectorValue); +} + +function __PRIVATE_validatePlainObject(e, t, n) { + if (!__PRIVATE_looksLikeJsonObject(n) || !__PRIVATE_isPlainObject(n)) { + const r = __PRIVATE_valueDescription(n); + throw "an object" === r ? t.Sc(e + " a custom object") : t.Sc(e + " " + r); + } +} + +/** + * Helper that calls fromDotSeparatedString() but wraps any error thrown. + */ function __PRIVATE_fieldPathFromArgument$1(e, t, n) { + if (( + // If required, replace the FieldPath Compat class with the firestore-exp + // FieldPath. + t = getModularInstance(t)) instanceof FieldPath) return t._internalPath; + if ("string" == typeof t) return __PRIVATE_fieldPathFromDotSeparatedString(e, t); + throw __PRIVATE_createError("Field path arguments must be of type string or ", e, + /* hasConverter= */ !1, + /* path= */ void 0, n); +} + +/** + * Matches any characters in a field path string that are reserved. + */ const Pn = new RegExp("[~\\*/\\[\\]]"); + +/** + * Wraps fromDotSeparatedString with an error message about the method that + * was thrown. + * @param methodName - The publicly visible method name + * @param path - The dot-separated string form of a field path which will be + * split on dots. + * @param targetDoc - The document against which the field path will be + * evaluated. + */ function __PRIVATE_fieldPathFromDotSeparatedString(e, t, n) { + if (t.search(Pn) >= 0) throw __PRIVATE_createError(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`, e, + /* hasConverter= */ !1, + /* path= */ void 0, n); + try { + return new FieldPath(...t.split("."))._internalPath; + } catch (r) { + throw __PRIVATE_createError(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`, e, + /* hasConverter= */ !1, + /* path= */ void 0, n); + } +} + +function __PRIVATE_createError(e, t, n, r, i) { + const s = r && !r.isEmpty(), o = void 0 !== i; + let _ = `Function ${t}() called with invalid data`; + n && (_ += " (via `toFirestore()`)"), _ += ". "; + let a = ""; + return (s || o) && (a += " (found", s && (a += ` in field ${r}`), o && (a += ` in document ${i}`), + a += ")"), new FirestoreError(N.INVALID_ARGUMENT, _ + e + a); +} + +/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ function __PRIVATE_fieldMaskContains(e, t) { + return e.some((e => e.isEqual(t))); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ class DocumentSnapshot$1 { + // Note: This class is stripped down version of the DocumentSnapshot in + // the legacy SDK. The changes are: + // - No support for SnapshotMetadata. + // - No support for SnapshotOptions. + /** @hideconstructor protected */ + constructor(e, t, n, r, i) { + this._firestore = e, this._userDataWriter = t, this._key = n, this._document = r, + this._converter = i; + } + /** Property of the `DocumentSnapshot` that provides the document's ID. */ get id() { + return this._key.path.lastSegment(); + } + /** + * The `DocumentReference` for the document included in the `DocumentSnapshot`. + */ get ref() { + return new DocumentReference(this._firestore, this._converter, this._key); + } + /** + * Signals whether or not the document at the snapshot's location exists. + * + * @returns true if the document exists. + */ exists() { + return null !== this._document; + } + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * @returns An `Object` containing all fields in the document or `undefined` + * if the document doesn't exist. + */ data() { + if (this._document) { + if (this._converter) { + // We only want to use the converter and create a new DocumentSnapshot + // if a converter has been provided. + const e = new QueryDocumentSnapshot$1(this._firestore, this._userDataWriter, this._key, this._document, + /* converter= */ null); + return this._converter.fromFirestore(e); + } + return this._userDataWriter.convertValue(this._document.data.value); + } + } + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + // We are using `any` here to avoid an explicit cast by our users. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get(e) { + if (this._document) { + const t = this._document.data.field(__PRIVATE_fieldPathFromArgument("DocumentSnapshot.get", e)); + if (null !== t) return this._userDataWriter.convertValue(t); + } + } +} + +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ class QueryDocumentSnapshot$1 extends DocumentSnapshot$1 { + /** + * Retrieves all fields in the document as an `Object`. + * + * @override + * @returns An `Object` containing all fields in the document. + */ + data() { + return super.data(); + } +} + +/** + * Helper that calls `fromDotSeparatedString()` but wraps any error thrown. + */ function __PRIVATE_fieldPathFromArgument(e, t) { + return "string" == typeof t ? __PRIVATE_fieldPathFromDotSeparatedString(e, t) : t instanceof FieldPath ? t._internalPath : t._delegate._internalPath; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_validateHasExplicitOrderByForLimitToLast(e) { + if ("L" /* LimitType.Last */ === e.limitType && 0 === e.explicitOrderBy.length) throw new FirestoreError(N.UNIMPLEMENTED, "limitToLast() queries require specifying at least one orderBy() clause"); +} + +/** + * An `AppliableConstraint` is an abstraction of a constraint that can be applied + * to a Firestore query. + */ class AppliableConstraint {} + +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Firestore query. `QueryConstraint`s are created by invoking {@link where}, + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that + * also contains this `QueryConstraint`. + */ class QueryConstraint extends AppliableConstraint {} + +function query(e, t, ...n) { + let r = []; + t instanceof AppliableConstraint && r.push(t), r = r.concat(n), function __PRIVATE_validateQueryConstraintArray(e) { + const t = e.filter((e => e instanceof QueryCompositeFilterConstraint)).length, n = e.filter((e => e instanceof QueryFieldFilterConstraint)).length; + if (t > 1 || t > 0 && n > 0) throw new FirestoreError(N.INVALID_ARGUMENT, "InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`."); + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Converts Firestore's internal types to the JavaScript types that we expose + * to the user. + * + * @internal + */ (r); + for (const t of r) e = t._apply(e); + return e; +} + +/** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ class QueryFieldFilterConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(e, t, n) { + super(), this._field = e, this._op = t, this._value = n, + /** The type of this query constraint */ + this.type = "where"; + } + static _create(e, t, n) { + return new QueryFieldFilterConstraint(e, t, n); + } + _apply(e) { + const t = this._parse(e); + return __PRIVATE_validateNewFieldFilter(e._query, t), new Query(e.firestore, e.converter, __PRIVATE_queryWithAddedFilter(e._query, t)); + } + _parse(e) { + const t = __PRIVATE_newUserDataReader(e.firestore), n = function __PRIVATE_newQueryFilter(e, t, n, r, i, s, o) { + let _; + if (i.isKeyField()) { + if ("array-contains" /* Operator.ARRAY_CONTAINS */ === s || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === s) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid Query. You can't perform '${s}' queries on documentId().`); + if ("in" /* Operator.IN */ === s || "not-in" /* Operator.NOT_IN */ === s) { + __PRIVATE_validateDisjunctiveFilterElements(o, s); + const t = []; + for (const n of o) t.push(__PRIVATE_parseDocumentIdValue(r, e, n)); + _ = { + arrayValue: { + values: t + } + }; + } else _ = __PRIVATE_parseDocumentIdValue(r, e, o); + } else "in" /* Operator.IN */ !== s && "not-in" /* Operator.NOT_IN */ !== s && "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ !== s || __PRIVATE_validateDisjunctiveFilterElements(o, s), + _ = __PRIVATE_parseQueryValue(n, t, o, + /* allowArrays= */ "in" /* Operator.IN */ === s || "not-in" /* Operator.NOT_IN */ === s); + const a = FieldFilter.create(i, s, _); + return a; + }(e._query, "where", t, e.firestore._databaseId, this._field, this._op, this._value); + return n; + } +} + +/** + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. + * + * @param fieldPath - The path to compare + * @param opStr - The operation string (e.g "<", "<=", "==", "<", + * "<=", "!="). + * @param value - The value for comparison + * @returns The created {@link QueryFieldFilterConstraint}. + */ function where(e, t, n) { + const r = t, i = __PRIVATE_fieldPathFromArgument("where", e); + return QueryFieldFilterConstraint._create(i, r, n); +} + +/** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ class QueryCompositeFilterConstraint extends AppliableConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + e, t) { + super(), this.type = e, this._queryConstraints = t; + } + static _create(e, t) { + return new QueryCompositeFilterConstraint(e, t); + } + _parse(e) { + const t = this._queryConstraints.map((t => t._parse(e))).filter((e => e.getFilters().length > 0)); + return 1 === t.length ? t[0] : CompositeFilter.create(t, this._getOperator()); + } + _apply(e) { + const t = this._parse(e); + return 0 === t.getFilters().length ? e : (function __PRIVATE_validateNewFilter(e, t) { + let n = e; + const r = t.getFlattenedFilters(); + for (const e of r) __PRIVATE_validateNewFieldFilter(n, e), n = __PRIVATE_queryWithAddedFilter(n, e); + } + // Checks if any of the provided filter operators are included in the given list of filters and + // returns the first one that is, or null if none are. + (e._query, t), new Query(e.firestore, e.converter, __PRIVATE_queryWithAddedFilter(e._query, t))); + } + _getQueryConstraints() { + return this._queryConstraints; + } + _getOperator() { + return "and" === this.type ? "and" /* CompositeOperator.AND */ : "or" /* CompositeOperator.OR */; + } +} + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ function or(...e) { + // Only support QueryFilterConstraints + return e.forEach((e => __PRIVATE_validateQueryFilterConstraint("or", e))), QueryCompositeFilterConstraint._create("or" /* CompositeOperator.OR */ , e); +} + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ function and(...e) { + // Only support QueryFilterConstraints + return e.forEach((e => __PRIVATE_validateQueryFilterConstraint("and", e))), QueryCompositeFilterConstraint._create("and" /* CompositeOperator.AND */ , e); +} + +/** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ class QueryOrderByConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(e, t) { + super(), this._field = e, this._direction = t, + /** The type of this query constraint */ + this.type = "orderBy"; + } + static _create(e, t) { + return new QueryOrderByConstraint(e, t); + } + _apply(e) { + const t = function __PRIVATE_newQueryOrderBy(e, t, n) { + if (null !== e.startAt) throw new FirestoreError(N.INVALID_ARGUMENT, "Invalid query. You must not call startAt() or startAfter() before calling orderBy()."); + if (null !== e.endAt) throw new FirestoreError(N.INVALID_ARGUMENT, "Invalid query. You must not call endAt() or endBefore() before calling orderBy()."); + const r = new OrderBy(t, n); + return r; + } + /** + * Create a `Bound` from a query and a document. + * + * Note that the `Bound` will always include the key of the document + * and so only the provided document will compare equal to the returned + * position. + * + * Will throw if the document does not contain all fields of the order by + * of the query or if any of the fields in the order by are an uncommitted + * server timestamp. + */ (e._query, this._field, this._direction); + return new Query(e.firestore, e.converter, function __PRIVATE_queryWithAddedOrderBy(e, t) { + // TODO(dimond): validate that orderBy does not list the same key twice. + const n = e.explicitOrderBy.concat([ t ]); + return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, n, e.filters.slice(), e.limit, e.limitType, e.startAt, e.endAt); + }(e._query, t)); + } +} + +/** + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the + * specified field, optionally in descending order instead of ascending. + * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * + * @param fieldPath - The field to sort by. + * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @returns The created {@link QueryOrderByConstraint}. + */ function orderBy(e, t = "asc") { + const n = t, r = __PRIVATE_fieldPathFromArgument("orderBy", e); + return QueryOrderByConstraint._create(r, n); +} + +/** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ class QueryLimitConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + e, t, n) { + super(), this.type = e, this._limit = t, this._limitType = n; + } + static _create(e, t, n) { + return new QueryLimitConstraint(e, t, n); + } + _apply(e) { + return new Query(e.firestore, e.converter, __PRIVATE_queryWithLimit(e._query, this._limit, this._limitType)); + } +} + +/** + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ function limit(e) { + return __PRIVATE_validatePositiveNumber("limit", e), QueryLimitConstraint._create("limit", e, "F" /* LimitType.First */); +} + +/** + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. + * + * You must specify at least one `orderBy` clause for `limitToLast` queries, + * otherwise an exception will be thrown during execution. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ function limitToLast(e) { + return __PRIVATE_validatePositiveNumber("limitToLast", e), QueryLimitConstraint._create("limitToLast", e, "L" /* LimitType.Last */); +} + +/** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ class QueryStartAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + e, t, n) { + super(), this.type = e, this._docOrFields = t, this._inclusive = n; + } + static _create(e, t, n) { + return new QueryStartAtConstraint(e, t, n); + } + _apply(e) { + const t = __PRIVATE_newQueryBoundFromDocOrFields(e, this.type, this._docOrFields, this._inclusive); + return new Query(e.firestore, e.converter, function __PRIVATE_queryWithStartAt(e, t) { + return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, e.explicitOrderBy.slice(), e.filters.slice(), e.limit, e.limitType, t, e.endAt); + }(e._query, t)); + } +} + +function startAt(...e) { + return QueryStartAtConstraint._create("startAt", e, + /*inclusive=*/ !0); +} + +function startAfter(...e) { + return QueryStartAtConstraint._create("startAfter", e, + /*inclusive=*/ !1); +} + +/** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ class QueryEndAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + e, t, n) { + super(), this.type = e, this._docOrFields = t, this._inclusive = n; + } + static _create(e, t, n) { + return new QueryEndAtConstraint(e, t, n); + } + _apply(e) { + const t = __PRIVATE_newQueryBoundFromDocOrFields(e, this.type, this._docOrFields, this._inclusive); + return new Query(e.firestore, e.converter, function __PRIVATE_queryWithEndAt(e, t) { + return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, e.explicitOrderBy.slice(), e.filters.slice(), e.limit, e.limitType, e.startAt, t); + }(e._query, t)); + } +} + +function endBefore(...e) { + return QueryEndAtConstraint._create("endBefore", e, + /*inclusive=*/ !1); +} + +function endAt(...e) { + return QueryEndAtConstraint._create("endAt", e, + /*inclusive=*/ !0); +} + +/** Helper function to create a bound from a document or fields */ function __PRIVATE_newQueryBoundFromDocOrFields(e, t, n, r) { + if (n[0] = getModularInstance(n[0]), n[0] instanceof DocumentSnapshot$1) return function __PRIVATE_newQueryBoundFromDocument(e, t, n, r, i) { + if (!r) throw new FirestoreError(N.NOT_FOUND, `Can't use a DocumentSnapshot that doesn't exist for ${n}().`); + const s = []; + // Because people expect to continue/end a query at the exact document + // provided, we need to use the implicit sort order rather than the explicit + // sort order, because it's guaranteed to contain the document key. That way + // the position becomes unambiguous and the query continues/ends exactly at + // the provided document. Without the key (by using the explicit sort + // orders), multiple documents could match the position, yielding duplicate + // results. + for (const n of __PRIVATE_queryNormalizedOrderBy(e)) if (n.field.isKeyField()) s.push(__PRIVATE_refValue(t, r.key)); else { + const e = r.data.field(n.field); + if (__PRIVATE_isServerTimestamp(e)) throw new FirestoreError(N.INVALID_ARGUMENT, 'Invalid query. You are trying to start or end a query using a document for which the field "' + n.field + '" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)'); + if (null === e) { + const e = n.field.canonicalString(); + throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid query. You are trying to start or end a query using a document for which the field '${e}' (used as the orderBy) does not exist.`); + } + s.push(e); + } + return new Bound(s, i); + } + /** + * Converts a list of field values to a `Bound` for the given query. + */ (e._query, e.firestore._databaseId, t, n[0]._document, r); + { + const i = __PRIVATE_newUserDataReader(e.firestore); + return function __PRIVATE_newQueryBoundFromFields(e, t, n, r, i, s) { + // Use explicit order by's because it has to match the query the user made + const o = e.explicitOrderBy; + if (i.length > o.length) throw new FirestoreError(N.INVALID_ARGUMENT, `Too many arguments provided to ${r}(). The number of arguments must be less than or equal to the number of orderBy() clauses`); + const _ = []; + for (let s = 0; s < i.length; s++) { + const a = i[s]; + if (o[s].field.isKeyField()) { + if ("string" != typeof a) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof a}`); + if (!__PRIVATE_isCollectionGroupQuery(e) && -1 !== a.indexOf("/")) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r}() must be a plain document ID, but '${a}' contains a slash.`); + const n = e.path.child(ResourcePath.fromString(a)); + if (!DocumentKey.isDocumentKey(n)) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${r}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`); + const i = new DocumentKey(n); + _.push(__PRIVATE_refValue(t, i)); + } else { + const e = __PRIVATE_parseQueryValue(n, r, a); + _.push(e); + } + } + return new Bound(_, s); + } + /** + * Parses the given `documentIdValue` into a `ReferenceValue`, throwing + * appropriate errors if the value is anything other than a `DocumentReference` + * or `string`, or if the string is malformed. + */ (e._query, e.firestore._databaseId, i, t, n, r); + } +} + +function __PRIVATE_parseDocumentIdValue(e, t, n) { + if ("string" == typeof (n = getModularInstance(n))) { + if ("" === n) throw new FirestoreError(N.INVALID_ARGUMENT, "Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string."); + if (!__PRIVATE_isCollectionGroupQuery(t) && -1 !== n.indexOf("/")) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`); + const r = t.path.child(ResourcePath.fromString(n)); + if (!DocumentKey.isDocumentKey(r)) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${r}' is not because it has an odd number of segments (${r.length}).`); + return __PRIVATE_refValue(e, new DocumentKey(r)); + } + if (n instanceof DocumentReference) return __PRIVATE_refValue(e, n._key); + throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${__PRIVATE_valueDescription(n)}.`); +} + +/** + * Validates that the value passed into a disjunctive filter satisfies all + * array requirements. + */ function __PRIVATE_validateDisjunctiveFilterElements(e, t) { + if (!Array.isArray(e) || 0 === e.length) throw new FirestoreError(N.INVALID_ARGUMENT, `Invalid Query. A non-empty array is required for '${t.toString()}' filters.`); +} + +/** + * Given an operator, returns the set of operators that cannot be used with it. + * + * This is not a comprehensive check, and this function should be removed in the + * long term. Validations should occur in the Firestore backend. + * + * Operators in a query must adhere to the following set of rules: + * 1. Only one inequality per query. + * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators. + */ function __PRIVATE_validateNewFieldFilter(e, t) { + const n = function __PRIVATE_findOpInsideFilters(e, t) { + for (const n of e) for (const e of n.getFlattenedFilters()) if (t.indexOf(e.op) >= 0) return e.op; + return null; + }(e.filters, function __PRIVATE_conflictingOps(e) { + switch (e) { + case "!=" /* Operator.NOT_EQUAL */ : + return [ "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ]; + + case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ : + case "in" /* Operator.IN */ : + return [ "not-in" /* Operator.NOT_IN */ ]; + + case "not-in" /* Operator.NOT_IN */ : + return [ "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , "in" /* Operator.IN */ , "not-in" /* Operator.NOT_IN */ , "!=" /* Operator.NOT_EQUAL */ ]; + + default: + return []; + } + }(t.op)); + if (null !== n) + // Special case when it's a duplicate op to give a slightly clearer error message. + throw n === t.op ? new FirestoreError(N.INVALID_ARGUMENT, `Invalid query. You cannot use more than one '${t.op.toString()}' filter.`) : new FirestoreError(N.INVALID_ARGUMENT, `Invalid query. You cannot use '${t.op.toString()}' filters with '${n.toString()}' filters.`); +} + +function __PRIVATE_validateQueryFilterConstraint(e, t) { + if (!(t instanceof QueryFieldFilterConstraint || t instanceof QueryCompositeFilterConstraint)) throw new FirestoreError(N.INVALID_ARGUMENT, `Function ${e}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`); +} + +class AbstractUserDataWriter { + convertValue(e, t = "none") { + switch (__PRIVATE_typeOrder(e)) { + case 0 /* TypeOrder.NullValue */ : + return null; + + case 1 /* TypeOrder.BooleanValue */ : + return e.booleanValue; + + case 2 /* TypeOrder.NumberValue */ : + return __PRIVATE_normalizeNumber(e.integerValue || e.doubleValue); + + case 3 /* TypeOrder.TimestampValue */ : + return this.convertTimestamp(e.timestampValue); + + case 4 /* TypeOrder.ServerTimestampValue */ : + return this.convertServerTimestamp(e, t); + + case 5 /* TypeOrder.StringValue */ : + return e.stringValue; + + case 6 /* TypeOrder.BlobValue */ : + return this.convertBytes(__PRIVATE_normalizeByteString(e.bytesValue)); + + case 7 /* TypeOrder.RefValue */ : + return this.convertReference(e.referenceValue); + + case 8 /* TypeOrder.GeoPointValue */ : + return this.convertGeoPoint(e.geoPointValue); + + case 9 /* TypeOrder.ArrayValue */ : + return this.convertArray(e.arrayValue, t); + + case 11 /* TypeOrder.ObjectValue */ : + return this.convertObject(e.mapValue, t); + + case 10 /* TypeOrder.VectorValue */ : + return this.convertVectorValue(e.mapValue); + + default: + throw fail(62114, { + value: e + }); + } + } + convertObject(e, t) { + return this.convertObjectMap(e.fields, t); + } + /** + * @internal + */ convertObjectMap(e, t = "none") { + const n = {}; + return forEach(e, ((e, r) => { + n[e] = this.convertValue(r, t); + })), n; + } + /** + * @internal + */ convertVectorValue(e) { + const t = e.fields?.[Et].arrayValue?.values?.map((e => __PRIVATE_normalizeNumber(e.doubleValue))); + return new VectorValue(t); + } + convertGeoPoint(e) { + return new GeoPoint(__PRIVATE_normalizeNumber(e.latitude), __PRIVATE_normalizeNumber(e.longitude)); + } + convertArray(e, t) { + return (e.values || []).map((e => this.convertValue(e, t))); + } + convertServerTimestamp(e, t) { + switch (t) { + case "previous": + const n = __PRIVATE_getPreviousValue(e); + return null == n ? null : this.convertValue(n, t); + + case "estimate": + return this.convertTimestamp(__PRIVATE_getLocalWriteTime(e)); + + default: + return null; + } + } + convertTimestamp(e) { + const t = __PRIVATE_normalizeTimestamp(e); + return new Timestamp(t.seconds, t.nanos); + } + convertDocumentKey(e, t) { + const n = ResourcePath.fromString(e); + __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(n), 9688, { + name: e + }); + const r = new DatabaseId(n.get(1), n.get(3)), i = new DocumentKey(n.popFirst(5)); + return r.isEqual(t) || + // TODO(b/64130202): Somehow support foreign references. + __PRIVATE_logError(`Document ${i} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`), + i; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Converts custom model object of type T into `DocumentData` by applying the + * converter if it exists. + * + * This function is used when converting user objects to `DocumentData` + * because we want to provide the user with a more specific error message if + * their `set()` or fails due to invalid data originating from a `toFirestore()` + * call. + */ function __PRIVATE_applyFirestoreDataConverter(e, t, n) { + let r; + // Cast to `any` in order to satisfy the union type constraint on + // toFirestore(). + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return r = e ? n && (n.merge || n.mergeFields) ? e.toFirestore(t, n) : e.toFirestore(t) : t, + r; +} + +class __PRIVATE_LiteUserDataWriter extends AbstractUserDataWriter { + constructor(e) { + super(), this.firestore = e; + } + convertBytes(e) { + return new Bytes(e); + } + convertReference(e) { + const t = this.convertDocumentKey(e, this.firestore._databaseId); + return new DocumentReference(this.firestore, /* converter= */ null, t); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ function sum(e) { + return new AggregateField("sum", __PRIVATE_fieldPathFromArgument$1("sum", e)); +} + +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ function average(e) { + return new AggregateField("avg", __PRIVATE_fieldPathFromArgument$1("average", e)); +} + +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ function count() { + return new AggregateField("count"); +} + +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ function aggregateFieldEqual(e, t) { + return e instanceof AggregateField && t instanceof AggregateField && e.aggregateType === t.aggregateType && e._internalFieldPath?.canonicalString() === t._internalFieldPath?.canonicalString(); +} + +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ function aggregateQuerySnapshotEqual(e, t) { + return queryEqual(e.query, t.query) && deepEqual(e.data(), t.data()); +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const Tn = "NOT SUPPORTED"; + +/** + * Metadata about a snapshot, describing the state of the snapshot. + */ class SnapshotMetadata { + /** @hideconstructor */ + constructor(e, t) { + this.hasPendingWrites = e, this.fromCache = t; + } + /** + * Returns true if this `SnapshotMetadata` is equal to the provided one. + * + * @param other - The `SnapshotMetadata` to compare against. + * @returns true if this `SnapshotMetadata` is equal to the provided one. + */ isEqual(e) { + return this.hasPendingWrites === e.hasPendingWrites && this.fromCache === e.fromCache; + } +} + +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ class DocumentSnapshot extends DocumentSnapshot$1 { + /** @hideconstructor protected */ + constructor(e, t, n, r, i, s) { + super(e, t, n, r, s), this._firestore = e, this._firestoreImpl = e, this.metadata = i; + } + /** + * Returns whether or not the data exists. True if the document exists. + */ exists() { + return super.exists(); + } + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * By default, `serverTimestamp()` values that have not yet been + * set to their final value will be returned as `null`. You can override + * this by passing an options object. + * + * @param options - An options object to configure how data is retrieved from + * the snapshot (for example the desired behavior for server timestamps that + * have not yet been set to their final value). + * @returns An `Object` containing all fields in the document or `undefined` if + * the document doesn't exist. + */ data(e = {}) { + if (this._document) { + if (this._converter) { + // We only want to use the converter and create a new DocumentSnapshot + // if a converter has been provided. + const t = new QueryDocumentSnapshot(this._firestore, this._userDataWriter, this._key, this._document, this.metadata, + /* converter= */ null); + return this._converter.fromFirestore(t, e); + } + return this._userDataWriter.convertValue(this._document.data.value, e.serverTimestamps); + } + } + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * By default, a `serverTimestamp()` that has not yet been set to + * its final value will be returned as `null`. You can override this by + * passing an options object. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @param options - An options object to configure how the field is retrieved + * from the snapshot (for example the desired behavior for server timestamps + * that have not yet been set to their final value). + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + // We are using `any` here to avoid an explicit cast by our users. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get(e, t = {}) { + if (this._document) { + const n = this._document.data.field(__PRIVATE_fieldPathFromArgument("DocumentSnapshot.get", e)); + if (null !== n) return this._userDataWriter.convertValue(n, t.serverTimestamps); + } + } + /** + * Returns a JSON-serializable representation of this `DocumentSnapshot` instance. + * + * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this + * `DocumentSnapshot` has pending writes. + */ toJSON() { + if (this.metadata.hasPendingWrites) throw new FirestoreError(N.FAILED_PRECONDITION, "DocumentSnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON()."); + const e = this._document, t = {}; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (t.type = DocumentSnapshot._jsonSchemaVersion, t.bundle = "", t.bundleSource = "DocumentSnapshot", + t.bundleName = this._key.toString(), !e || !e.isValidDocument() || !e.isFoundDocument()) return t; + this._userDataWriter.convertObjectMap(e.data.value.mapValue.fields, "previous"); + return t.bundle = (this._firestore, this.ref.path, "NOT SUPPORTED"), t; + } +} + +function documentSnapshotFromJSON(e, t, n) { + if (__PRIVATE_validateJSON(t, DocumentSnapshot._jsonSchema)) { + if (t.bundle === Tn) throw new FirestoreError(N.INVALID_ARGUMENT, "The provided JSON object was created in a client environment, which is not supported."); + // Parse the bundle data. + const r = __PRIVATE_newSerializer(e._databaseId), i = __PRIVATE_createBundleReaderSync(t.bundle, r), s = i.Wu(), o = new __PRIVATE_BundleLoader(i.getMetadata(), r); + for (const e of s) o.Ga(e); + // Ensure that we have the correct number of documents in the bundle. + const _ = o.documents; + if (1 !== _.length) throw new FirestoreError(N.INVALID_ARGUMENT, `Expected bundle data to contain 1 document, but it contains ${_.length} documents.`); + // Build out the internal document data. + const a = __PRIVATE_fromDocument(r, _[0].document), u = new DocumentKey(ResourcePath.fromString(t.bundleName)); + // Return the external facing DocumentSnapshot. + return new DocumentSnapshot(e, new __PRIVATE_LiteUserDataWriter(e), u, a, new SnapshotMetadata( + /* hasPendingWrites= */ !1, + /* fromCache= */ !1), n || null); + } +} + +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ DocumentSnapshot._jsonSchemaVersion = "firestore/documentSnapshot/1.0", DocumentSnapshot._jsonSchema = { + type: property("string", DocumentSnapshot._jsonSchemaVersion), + bundleSource: property("string", "DocumentSnapshot"), + bundleName: property("string"), + bundle: property("string") +}; + +class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * By default, `serverTimestamp()` values that have not yet been + * set to their final value will be returned as `null`. You can override + * this by passing an options object. + * + * @override + * @param options - An options object to configure how data is retrieved from + * the snapshot (for example the desired behavior for server timestamps that + * have not yet been set to their final value). + * @returns An `Object` containing all fields in the document. + */ + data(e = {}) { + return super.data(e); + } +} + +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ class QuerySnapshot { + /** @hideconstructor */ + constructor(e, t, n, r) { + this._firestore = e, this._userDataWriter = t, this._snapshot = r, this.metadata = new SnapshotMetadata(r.hasPendingWrites, r.fromCache), + this.query = n; + } + /** An array of all the documents in the `QuerySnapshot`. */ get docs() { + const e = []; + return this.forEach((t => e.push(t))), e; + } + /** The number of documents in the `QuerySnapshot`. */ get size() { + return this._snapshot.docs.size; + } + /** True if there are no documents in the `QuerySnapshot`. */ get empty() { + return 0 === this.size; + } + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ forEach(e, t) { + this._snapshot.docs.forEach((n => { + e.call(t, new QueryDocumentSnapshot(this._firestore, this._userDataWriter, n.key, n, new SnapshotMetadata(this._snapshot.mutatedKeys.has(n.key), this._snapshot.fromCache), this.query.converter)); + })); + } + /** + * Returns an array of the documents changes since the last snapshot. If this + * is the first snapshot, all documents will be in the list as 'added' + * changes. + * + * @param options - `SnapshotListenOptions` that control whether metadata-only + * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger + * snapshot events. + */ docChanges(e = {}) { + const t = !!e.includeMetadataChanges; + if (t && this._snapshot.excludesMetadataChanges) throw new FirestoreError(N.INVALID_ARGUMENT, "To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot()."); + return this._cachedChanges && this._cachedChangesIncludeMetadataChanges === t || (this._cachedChanges = + /** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */ + function __PRIVATE_changesFromSnapshot(e, t) { + if (e._snapshot.oldDocs.isEmpty()) { + let t = 0; + return e._snapshot.docChanges.map((n => { + const r = new QueryDocumentSnapshot(e._firestore, e._userDataWriter, n.doc.key, n.doc, new SnapshotMetadata(e._snapshot.mutatedKeys.has(n.doc.key), e._snapshot.fromCache), e.query.converter); + return n.doc, { + type: "added", + doc: r, + oldIndex: -1, + newIndex: t++ + }; + })); + } + { + // A `DocumentSet` that is updated incrementally as changes are applied to use + // to lookup the index of a document. + let n = e._snapshot.oldDocs; + return e._snapshot.docChanges.filter((e => t || 3 /* ChangeType.Metadata */ !== e.type)).map((t => { + const r = new QueryDocumentSnapshot(e._firestore, e._userDataWriter, t.doc.key, t.doc, new SnapshotMetadata(e._snapshot.mutatedKeys.has(t.doc.key), e._snapshot.fromCache), e.query.converter); + let i = -1, s = -1; + return 0 /* ChangeType.Added */ !== t.type && (i = n.indexOf(t.doc.key), n = n.delete(t.doc.key)), + 1 /* ChangeType.Removed */ !== t.type && (n = n.add(t.doc), s = n.indexOf(t.doc.key)), + { + type: __PRIVATE_resultChangeType(t.type), + doc: r, + oldIndex: i, + newIndex: s + }; + })); + } + }(this, t), this._cachedChangesIncludeMetadataChanges = t), this._cachedChanges; + } + /** + * Returns a JSON-serializable representation of this `QuerySnapshot` instance. + * + * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this + * `QuerySnapshot` has pending writes. + */ toJSON() { + if (this.metadata.hasPendingWrites) throw new FirestoreError(N.FAILED_PRECONDITION, "QuerySnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON()."); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const e = {}; + e.type = QuerySnapshot._jsonSchemaVersion, e.bundleSource = "QuerySnapshot", e.bundleName = __PRIVATE_AutoId.newId(), + this._firestore._databaseId.database, this._firestore._databaseId.projectId; + const t = [], n = [], r = []; + return this.docs.forEach((e => { + null !== e._document && (t.push(e._document), n.push(this._userDataWriter.convertObjectMap(e._document.data.value.mapValue.fields, "previous")), + r.push(e.ref.path)); + })), e.bundle = (this._firestore, this.query._query, e.bundleName, "NOT SUPPORTED"), + e; + } +} + +function querySnapshotFromJSON(e, t, n) { + if (__PRIVATE_validateJSON(t, QuerySnapshot._jsonSchema)) { + if (t.bundle === Tn) throw new FirestoreError(N.INVALID_ARGUMENT, "The provided JSON object was created in a client environment, which is not supported."); + // Parse the bundle data. + const r = __PRIVATE_newSerializer(e._databaseId), i = __PRIVATE_createBundleReaderSync(t.bundle, r), s = i.Wu(), o = new __PRIVATE_BundleLoader(i.getMetadata(), r); + for (const e of s) o.Ga(e); + if (1 !== o.queries.length) throw new FirestoreError(N.INVALID_ARGUMENT, `Snapshot data expected 1 query but found ${o.queries.length} queries.`); + // Create an internal Query object from the named query in the bundle. + const _ = __PRIVATE_fromBundledQuery(o.queries[0].bundledQuery), a = o.documents; + // Construct the arrays of document data for the query. + let u = new DocumentSet; + a.map((e => { + const t = __PRIVATE_fromDocument(r, e.document); + u = u.add(t); + })); + // Create a view snapshot of the query and documents. + const c = ViewSnapshot.fromInitialDocuments(_, u, __PRIVATE_documentKeySet() /* Zero mutated keys signifies no pending writes. */ , + /* fromCache= */ !1, + /* hasCachedResults= */ !1), l = new Query(e, n || null, _); + // Create an external Query object, required to construct the QuerySnapshot. + // Return a new QuerySnapshot with all of the collected data. + return new QuerySnapshot(e, new __PRIVATE_LiteUserDataWriter(e), l, c); + } +} + +function __PRIVATE_resultChangeType(e) { + switch (e) { + case 0 /* ChangeType.Added */ : + return "added"; + + case 2 /* ChangeType.Modified */ : + case 3 /* ChangeType.Metadata */ : + return "modified"; + + case 1 /* ChangeType.Removed */ : + return "removed"; + + default: + return fail(61501, { + type: e + }); + } +} + +// TODO(firestoreexp): Add tests for snapshotEqual with different snapshot +// metadata +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ function snapshotEqual(e, t) { + return e instanceof DocumentSnapshot && t instanceof DocumentSnapshot ? e._firestore === t._firestore && e._key.isEqual(t._key) && (null === e._document ? null === t._document : e._document.isEqual(t._document)) && e._converter === t._converter : e instanceof QuerySnapshot && t instanceof QuerySnapshot && (e._firestore === t._firestore && queryEqual(e.query, t.query) && e.metadata.isEqual(t.metadata) && e._snapshot.isEqual(t._snapshot)); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Reads the document referred to by this `DocumentReference`. + * + * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting + * for data from the server, but it may return cached data or fail if you are + * offline and the server cannot be reached. To specify this behavior, invoke + * {@link getDocFromCache} or {@link getDocFromServer}. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the + * current document contents. + */ function getDoc(e) { + e = __PRIVATE_cast(e, DocumentReference); + const t = __PRIVATE_cast(e.firestore, Firestore); + return __PRIVATE_firestoreClientGetDocumentViaSnapshotListener(ensureFirestoreConfigured(t), e._key).then((n => __PRIVATE_convertToDocSnapshot(t, e, n))); +} + +QuerySnapshot._jsonSchemaVersion = "firestore/querySnapshot/1.0", QuerySnapshot._jsonSchema = { + type: property("string", QuerySnapshot._jsonSchemaVersion), + bundleSource: property("string", "QuerySnapshot"), + bundleName: property("string"), + bundle: property("string") +}; + +class __PRIVATE_ExpUserDataWriter extends AbstractUserDataWriter { + constructor(e) { + super(), this.firestore = e; + } + convertBytes(e) { + return new Bytes(e); + } + convertReference(e) { + const t = this.convertDocumentKey(e, this.firestore._databaseId); + return new DocumentReference(this.firestore, /* converter= */ null, t); + } +} + +/** + * Reads the document referred to by this `DocumentReference` from cache. + * Returns an error if the document is not currently cached. + * + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the + * current document contents. + */ function getDocFromCache(e) { + e = __PRIVATE_cast(e, DocumentReference); + const t = __PRIVATE_cast(e.firestore, Firestore), n = ensureFirestoreConfigured(t), r = new __PRIVATE_ExpUserDataWriter(t); + return __PRIVATE_firestoreClientGetDocumentFromLocalCache(n, e._key).then((n => new DocumentSnapshot(t, r, e._key, n, new SnapshotMetadata(null !== n && n.hasLocalMutations, + /* fromCache= */ !0), e.converter))); +} + +/** + * Reads the document referred to by this `DocumentReference` from the server. + * Returns an error if the network is not available. + * + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the + * current document contents. + */ function getDocFromServer(e) { + e = __PRIVATE_cast(e, DocumentReference); + const t = __PRIVATE_cast(e.firestore, Firestore); + return __PRIVATE_firestoreClientGetDocumentViaSnapshotListener(ensureFirestoreConfigured(t), e._key, { + source: "server" + }).then((n => __PRIVATE_convertToDocSnapshot(t, e, n))); +} + +/** + * Executes the query and returns the results as a `QuerySnapshot`. + * + * Note: `getDocs()` attempts to provide up-to-date data when possible by + * waiting for data from the server, but it may return cached data or fail if + * you are offline and the server cannot be reached. To specify this behavior, + * invoke {@link getDocsFromCache} or {@link getDocsFromServer}. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ function getDocs(e) { + e = __PRIVATE_cast(e, Query); + const t = __PRIVATE_cast(e.firestore, Firestore), n = ensureFirestoreConfigured(t), r = new __PRIVATE_ExpUserDataWriter(t); + return __PRIVATE_validateHasExplicitOrderByForLimitToLast(e._query), __PRIVATE_firestoreClientGetDocumentsViaSnapshotListener(n, e._query).then((n => new QuerySnapshot(t, r, e, n))); +} + +/** + * Executes the query and returns the results as a `QuerySnapshot` from cache. + * Returns an empty result set if no documents matching the query are currently + * cached. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ function getDocsFromCache(e) { + e = __PRIVATE_cast(e, Query); + const t = __PRIVATE_cast(e.firestore, Firestore), n = ensureFirestoreConfigured(t), r = new __PRIVATE_ExpUserDataWriter(t); + return __PRIVATE_firestoreClientGetDocumentsFromLocalCache(n, e._query).then((n => new QuerySnapshot(t, r, e, n))); +} + +/** + * Executes the query and returns the results as a `QuerySnapshot` from the + * server. Returns an error if the network is not available. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ function getDocsFromServer(e) { + e = __PRIVATE_cast(e, Query); + const t = __PRIVATE_cast(e.firestore, Firestore), n = ensureFirestoreConfigured(t), r = new __PRIVATE_ExpUserDataWriter(t); + return __PRIVATE_firestoreClientGetDocumentsViaSnapshotListener(n, e._query, { + source: "server" + }).then((n => new QuerySnapshot(t, r, e, n))); +} + +function setDoc(e, t, n) { + e = __PRIVATE_cast(e, DocumentReference); + const r = __PRIVATE_cast(e.firestore, Firestore), i = __PRIVATE_applyFirestoreDataConverter(e.converter, t, n); + return executeWrite(r, [ __PRIVATE_parseSetData(__PRIVATE_newUserDataReader(r), "setDoc", e._key, i, null !== e.converter, n).toMutation(e._key, Precondition.none()) ]); +} + +function updateDoc(e, t, n, ...r) { + e = __PRIVATE_cast(e, DocumentReference); + const i = __PRIVATE_cast(e.firestore, Firestore), s = __PRIVATE_newUserDataReader(i); + let o; + o = "string" == typeof ( + // For Compat types, we have to "extract" the underlying types before + // performing validation. + t = getModularInstance(t)) || t instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(s, "updateDoc", e._key, t, n, r) : __PRIVATE_parseUpdateData(s, "updateDoc", e._key, t); + return executeWrite(i, [ o.toMutation(e._key, Precondition.exists(!0)) ]); +} + +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * @param reference - A reference to the document to delete. + * @returns A Promise resolved once the document has been successfully + * deleted from the backend (note that it won't resolve while you're offline). + */ function deleteDoc(e) { + return executeWrite(__PRIVATE_cast(e.firestore, Firestore), [ new __PRIVATE_DeleteMutation(e._key, Precondition.none()) ]); +} + +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend (Note that it + * won't resolve while you're offline). + */ function addDoc(e, t) { + const n = __PRIVATE_cast(e.firestore, Firestore), r = doc(e), i = __PRIVATE_applyFirestoreDataConverter(e.converter, t); + return executeWrite(n, [ __PRIVATE_parseSetData(__PRIVATE_newUserDataReader(e.firestore), "addDoc", r._key, i, null !== e.converter, {}).toMutation(r._key, Precondition.exists(!1)) ]).then((() => r)); +} + +function onSnapshot(e, ...t) { + // onSnapshot for Query or Document. + e = getModularInstance(e); + let n = { + includeMetadataChanges: !1, + source: "default" + }, r = 0; + "object" != typeof t[r] || __PRIVATE_isPartialObserver(t[r]) || (n = t[r++]); + const i = { + includeMetadataChanges: n.includeMetadataChanges, + source: n.source + }; + if (__PRIVATE_isPartialObserver(t[r])) { + const e = t[r]; + t[r] = e.next?.bind(e), t[r + 1] = e.error?.bind(e), t[r + 2] = e.complete?.bind(e); + } + let s, o, _; + if (e instanceof DocumentReference) o = __PRIVATE_cast(e.firestore, Firestore), + _ = __PRIVATE_newQueryForPath(e._key.path), s = { + next: n => { + t[r] && t[r](__PRIVATE_convertToDocSnapshot(o, e, n)); + }, + error: t[r + 1], + complete: t[r + 2] + }; else { + const n = __PRIVATE_cast(e, Query); + o = __PRIVATE_cast(n.firestore, Firestore), _ = n._query; + const i = new __PRIVATE_ExpUserDataWriter(o); + s = { + next: e => { + t[r] && t[r](new QuerySnapshot(o, i, n, e)); + }, + error: t[r + 1], + complete: t[r + 2] + }, __PRIVATE_validateHasExplicitOrderByForLimitToLast(e._query); + } + return function __PRIVATE_firestoreClientListen(e, t, n, r) { + const i = new __PRIVATE_AsyncObserver(r), s = new __PRIVATE_QueryListener(t, i, n); + return e.asyncQueue.enqueueAndForget((async () => __PRIVATE_eventManagerListen(await __PRIVATE_getEventManager(e), s))), + () => { + i.Nu(), e.asyncQueue.enqueueAndForget((async () => __PRIVATE_eventManagerUnlisten(await __PRIVATE_getEventManager(e), s))); + }; + }(ensureFirestoreConfigured(o), _, i, s); +} + +function onSnapshotResume(e, t, ...n) { + const r = getModularInstance(e), i = + /** + * Ensures the data required to construct an {@link onSnapshot} listener exist in a `snapshotJson` + * object that originates from {@link DocumentSnapshot.toJSON} or {@link Querysnapshot.toJSON}. The + * data is normalized into a typed object. + * + * @param snapshotJson - The JSON object that the app provided to {@link onSnapshot}. + * @returns A normalized object that contains all of the required bundle JSON fields. If + * {@link snapshotJson} doesn't contain the required fields, or if the fields exist as empty + * strings, then the {@link snapshotJson.error} field will be a non empty string. + * + * @internal + */ + function __PRIVATE_normalizeSnapshotJsonFields(e) { + const t = { + bundle: "", + bundleName: "", + bundleSource: "" + }, n = [ "bundle", "bundleName", "bundleSource" ]; + for (const r of n) { + if (!(r in e)) { + t.error = `snapshotJson missing required field: ${r}`; + break; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const n = e[r]; + if ("string" != typeof n) { + t.error = `snapshotJson field '${r}' must be a string.`; + break; + } + if (0 === n.length) { + t.error = `snapshotJson field '${r}' cannot be an empty string.`; + break; + } + "bundle" === r ? t.bundle = n : "bundleName" === r ? t.bundleName = n : "bundleSource" === r && (t.bundleSource = n); + } + return t; + } + /** + * Loads the bundle in a separate task and then invokes {@link onSnapshot} with a + * {@link DocumentReference} for the document in the bundle. + * + * @param firestore - The {@link Firestore} instance for the {@link onSnapshot} operation request. + * @param json - The JSON bundle to load, produced by {@link DocumentSnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot + * listener. + * + * @internal + */ (t); + if (i.error) throw new FirestoreError(N.INVALID_ARGUMENT, i.error); + let s, o = 0; + if ("object" != typeof n[o] || __PRIVATE_isPartialObserver(n[o]) || (s = n[o++]), + "QuerySnapshot" === i.bundleSource) { + let e = null; + if ("object" == typeof n[o] && __PRIVATE_isPartialObserver(n[o])) { + const t = n[o++]; + e = { + next: t.next, + error: t.error, + complete: t.complete + }; + } else e = { + next: n[o++], + error: n[o++], + complete: n[o++] + }; + /** + * Loads the bundle in a separate task and then invokes {@link onSnapshot} with a + * {@link Query} that represents the Query in the bundle. + * + * @param firestore - The {@link Firestore} instance for the {@link onSnapshot} operation request. + * @param json - The JSON bundle to load, produced by {@link QuerySnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot + * listener. + * + * @internal + */ + return function __PRIVATE_onSnapshotQuerySnapshotBundle(e, t, n, r, i) { + let s, o = !1; + const _ = loadBundle(e, t.bundle); + return _.then((() => namedQuery(e, t.bundleName))).then((e => { + if (e && !o) { + i && e.withConverter(i), s = onSnapshot(e, n || {}, r); + } + })).catch((e => (r.error && r.error(e), () => {}))), () => { + o || (o = !0, s && s()); + }; + } + /** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ (r, i, s, e, n[o]); + } + if ("DocumentSnapshot" === i.bundleSource) { + let e = null; + if ("object" == typeof n[o] && __PRIVATE_isPartialObserver(n[o])) { + const t = n[o++]; + e = { + next: t.next, + error: t.error, + complete: t.complete + }; + } else e = { + next: n[o++], + error: n[o++], + complete: n[o++] + }; + return function __PRIVATE_onSnapshotDocumentSnapshotBundle(e, t, n, r, i) { + let s, o = !1; + const _ = loadBundle(e, t.bundle); + return _.then((() => { + if (!o) { + const o = new DocumentReference(e, i || null, DocumentKey.fromPath(t.bundleName)); + s = onSnapshot(o, n || {}, r); + } + })).catch((e => (r.error && r.error(e), () => {}))), () => { + o || (o = !0, s && s()); + }; + }(r, i, s, e, n[o]); + } + throw new FirestoreError(N.INVALID_ARGUMENT, `unsupported bundle source: ${i.bundleSource}`); +} + +function onSnapshotsInSync(e, t) { + return __PRIVATE_firestoreClientAddSnapshotsInSyncListener(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)), __PRIVATE_isPartialObserver(t) ? t : { + next: t + }); +} + +/** + * Locally writes `mutations` on the async queue. + * @internal + */ function executeWrite(e, t) { + return function __PRIVATE_firestoreClientWrite(e, t) { + const n = new __PRIVATE_Deferred; + return e.asyncQueue.enqueueAndForget((async () => __PRIVATE_syncEngineWrite(await __PRIVATE_getSyncEngine(e), t, n))), + n.promise; + }(ensureFirestoreConfigured(e), t); +} + +/** + * Converts a {@link ViewSnapshot} that contains the single document specified by `ref` + * to a {@link DocumentSnapshot}. + */ function __PRIVATE_convertToDocSnapshot(e, t, n) { + const r = n.docs.get(t._key), i = new __PRIVATE_ExpUserDataWriter(e); + return new DocumentSnapshot(e, i, t._key, r, new SnapshotMetadata(n.hasPendingWrites, n.fromCache), t.converter); +} + +function getCountFromServer(e) { + return getAggregateFromServer(e, { + count: count() + }); +} + +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregateFromServer(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ function getAggregateFromServer(e, t) { + const n = __PRIVATE_cast(e.firestore, Firestore), r = ensureFirestoreConfigured(n), i = __PRIVATE_mapToArray(t, ((e, t) => new __PRIVATE_AggregateImpl(t, e.aggregateType, e._internalFieldPath))); + // Run the aggregation and convert the results + return __PRIVATE_firestoreClientRunAggregateQuery(r, e._query, i).then((t => + /** + * Converts the core aggregation result to an `AggregateQuerySnapshot` + * that can be returned to the consumer. + * @param query + * @param aggregateResult Core aggregation result + * @internal + */ + function __PRIVATE_convertToAggregateQuerySnapshot(e, t, n) { + const r = new __PRIVATE_ExpUserDataWriter(e), i = new AggregateQuerySnapshot(t, r, n); + return i; + } + /** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ (n, e, t))); +} + +class __PRIVATE_MemoryLocalCacheImpl { + constructor(e) { + this.kind = "memory", this._onlineComponentProvider = OnlineComponentProvider.provider, + this._offlineComponentProvider = e?.garbageCollector ? e.garbageCollector._offlineComponentProvider : { + build: () => new __PRIVATE_LruGcMemoryOfflineComponentProvider(void 0) + }; + } + toJSON() { + return { + kind: this.kind + }; + } +} + +class __PRIVATE_PersistentLocalCacheImpl { + constructor(e) { + let t; + this.kind = "persistent", e?.tabManager ? (e.tabManager._initialize(e), t = e.tabManager) : (t = persistentSingleTabManager(void 0), + t._initialize(e)), this._onlineComponentProvider = t._onlineComponentProvider, this._offlineComponentProvider = t._offlineComponentProvider; + } + toJSON() { + return { + kind: this.kind + }; + } +} + +class __PRIVATE_MemoryEagerGarbageCollectorImpl { + constructor() { + this.kind = "memoryEager", this._offlineComponentProvider = __PRIVATE_MemoryOfflineComponentProvider.provider; + } + toJSON() { + return { + kind: this.kind + }; + } +} + +class __PRIVATE_MemoryLruGarbageCollectorImpl { + constructor(e) { + this.kind = "memoryLru", this._offlineComponentProvider = { + build: () => new __PRIVATE_LruGcMemoryOfflineComponentProvider(e) + }; + } + toJSON() { + return { + kind: this.kind + }; + } +} + +/** + * Creates an instance of `MemoryEagerGarbageCollector`. This is also the + * default garbage collector unless it is explicitly specified otherwise. + */ function memoryEagerGarbageCollector() { + return new __PRIVATE_MemoryEagerGarbageCollectorImpl; +} + +/** + * Creates an instance of `MemoryLruGarbageCollector`. + * + * A target size can be specified as part of the setting parameter. The + * collector will start deleting documents once the cache size exceeds + * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes). + */ function memoryLruGarbageCollector(e) { + return new __PRIVATE_MemoryLruGarbageCollectorImpl(e?.cacheSizeBytes); +} + +/** + * Creates an instance of `MemoryLocalCache`. The instance can be set to + * `FirestoreSettings.cache` to tell the SDK which cache layer to use. + */ function memoryLocalCache(e) { + return new __PRIVATE_MemoryLocalCacheImpl(e); +} + +/** + * Creates an instance of `PersistentLocalCache`. The instance can be set to + * `FirestoreSettings.cache` to tell the SDK which cache layer to use. + * + * Persistent cache cannot be used in a Node.js environment. + */ function persistentLocalCache(e) { + return new __PRIVATE_PersistentLocalCacheImpl(e); +} + +class __PRIVATE_SingleTabManagerImpl { + constructor(e) { + this.forceOwnership = e, this.kind = "persistentSingleTab"; + } + toJSON() { + return { + kind: this.kind + }; + } + /** + * @internal + */ _initialize(e) { + this._onlineComponentProvider = OnlineComponentProvider.provider, this._offlineComponentProvider = { + build: t => new __PRIVATE_IndexedDbOfflineComponentProvider(t, e?.cacheSizeBytes, this.forceOwnership) + }; + } +} + +class __PRIVATE_MultiTabManagerImpl { + constructor() { + this.kind = "PersistentMultipleTab"; + } + toJSON() { + return { + kind: this.kind + }; + } + /** + * @internal + */ _initialize(e) { + this._onlineComponentProvider = OnlineComponentProvider.provider, this._offlineComponentProvider = { + build: t => new __PRIVATE_MultiTabOfflineComponentProvider(t, e?.cacheSizeBytes) + }; + } +} + +/** + * Creates an instance of `PersistentSingleTabManager`. + * + * @param settings Configures the created tab manager. + */ function persistentSingleTabManager(e) { + return new __PRIVATE_SingleTabManagerImpl(e?.forceOwnership); +} + +/** + * Creates an instance of `PersistentMultipleTabManager`. + */ function persistentMultipleTabManager() { + return new __PRIVATE_MultiTabManagerImpl; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const In = { + maxAttempts: 5 +}; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It + * provides methods for adding writes to the write batch. None of the writes + * will be committed (or visible locally) until {@link WriteBatch.commit} is + * called. + */ +class WriteBatch { + /** @hideconstructor */ + constructor(e, t) { + this._firestore = e, this._commitHandler = t, this._mutations = [], this._committed = !1, + this._dataReader = __PRIVATE_newUserDataReader(e); + } + set(e, t, n) { + this._verifyNotCommitted(); + const r = __PRIVATE_validateReference(e, this._firestore), i = __PRIVATE_applyFirestoreDataConverter(r.converter, t, n), s = __PRIVATE_parseSetData(this._dataReader, "WriteBatch.set", r._key, i, null !== r.converter, n); + return this._mutations.push(s.toMutation(r._key, Precondition.none())), this; + } + update(e, t, n, ...r) { + this._verifyNotCommitted(); + const i = __PRIVATE_validateReference(e, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + let s; + return s = "string" == typeof (t = getModularInstance(t)) || t instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(this._dataReader, "WriteBatch.update", i._key, t, n, r) : __PRIVATE_parseUpdateData(this._dataReader, "WriteBatch.update", i._key, t), + this._mutations.push(s.toMutation(i._key, Precondition.exists(!0))), this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ delete(e) { + this._verifyNotCommitted(); + const t = __PRIVATE_validateReference(e, this._firestore); + return this._mutations = this._mutations.concat(new __PRIVATE_DeleteMutation(t._key, Precondition.none())), + this; + } + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `Promise` resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit (note that it won't + * resolve while you're offline). + */ commit() { + return this._verifyNotCommitted(), this._committed = !0, this._mutations.length > 0 ? this._commitHandler(this._mutations) : Promise.resolve(); + } + _verifyNotCommitted() { + if (this._committed) throw new FirestoreError(N.FAILED_PRECONDITION, "A write batch can no longer be used after commit() has been called."); + } +} + +function __PRIVATE_validateReference(e, t) { + if ((e = getModularInstance(e)).firestore !== t) throw new FirestoreError(N.INVALID_ARGUMENT, "Provided document reference is from a different Firestore instance."); + return e; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the +// legacy SDK. +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ class Transaction$1 { + /** @hideconstructor */ + constructor(e, t) { + this._firestore = e, this._transaction = t, this._dataReader = __PRIVATE_newUserDataReader(e); + } + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ get(e) { + const t = __PRIVATE_validateReference(e, this._firestore), n = new __PRIVATE_LiteUserDataWriter(this._firestore); + return this._transaction.lookup([ t._key ]).then((e => { + if (!e || 1 !== e.length) return fail(24041); + const r = e[0]; + if (r.isFoundDocument()) return new DocumentSnapshot$1(this._firestore, n, r.key, r, t.converter); + if (r.isNoDocument()) return new DocumentSnapshot$1(this._firestore, n, t._key, null, t.converter); + throw fail(18433, { + doc: r + }); + })); + } + set(e, t, n) { + const r = __PRIVATE_validateReference(e, this._firestore), i = __PRIVATE_applyFirestoreDataConverter(r.converter, t, n), s = __PRIVATE_parseSetData(this._dataReader, "Transaction.set", r._key, i, null !== r.converter, n); + return this._transaction.set(r._key, s), this; + } + update(e, t, n, ...r) { + const i = __PRIVATE_validateReference(e, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + let s; + return s = "string" == typeof (t = getModularInstance(t)) || t instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(this._dataReader, "Transaction.update", i._key, t, n, r) : __PRIVATE_parseUpdateData(this._dataReader, "Transaction.update", i._key, t), + this._transaction.update(i._key, s), this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `Transaction` instance. Used for chaining method calls. + */ delete(e) { + const t = __PRIVATE_validateReference(e, this._firestore); + return this._transaction.delete(t._key), this; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ class Transaction extends Transaction$1 { + // This class implements the same logic as the Transaction API in the Lite SDK + // but is subclassed in order to return its own DocumentSnapshot types. + /** @hideconstructor */ + constructor(e, t) { + super(e, t), this._firestore = e; + } + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ get(e) { + const t = __PRIVATE_validateReference(e, this._firestore), n = new __PRIVATE_ExpUserDataWriter(this._firestore); + return super.get(e).then((e => new DocumentSnapshot(this._firestore, n, t._key, e._document, new SnapshotMetadata( + /* hasPendingWrites= */ !1, + /* fromCache= */ !1), t.converter))); + } +} + +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ function runTransaction(e, t, n) { + e = __PRIVATE_cast(e, Firestore); + const r = { + ...In, + ...n + }; + !function __PRIVATE_validateTransactionOptions(e) { + if (e.maxAttempts < 1) throw new FirestoreError(N.INVALID_ARGUMENT, "Max attempts must be at least 1"); + }(r); + return function __PRIVATE_firestoreClientTransaction(e, t, n) { + const r = new __PRIVATE_Deferred; + return e.asyncQueue.enqueueAndForget((async () => { + const i = await __PRIVATE_getDatastore(e); + new __PRIVATE_TransactionRunner(e.asyncQueue, i, n, t, r).ju(); + })), r.promise; + }(ensureFirestoreConfigured(e), (n => t(new Transaction(e, n))), r); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. + */ function deleteField() { + return new __PRIVATE_DeleteFieldValueImpl("deleteField"); +} + +/** + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to + * include a server-generated timestamp in the written data. + */ function serverTimestamp() { + return new __PRIVATE_ServerTimestampFieldValueImpl("serverTimestamp"); +} + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array + * value that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements - The elements to union into the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()`. + */ function arrayUnion(...e) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new __PRIVATE_ArrayUnionFieldValueImpl("arrayUnion", e); +} + +/** + * Returns a special value that can be used with {@link (setDoc:1)} or {@link + * updateDoc:1} that tells the server to remove the given elements from any + * array value that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is not + * already an array it will be overwritten with an empty array. + * + * @param elements - The elements to remove from the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ function arrayRemove(...e) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new __PRIVATE_ArrayRemoveFieldValueImpl("arrayRemove", e); +} + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by + * the given value. + * + * If either the operand or the current field value uses floating point + * precision, all arithmetic follows IEEE 754 semantics. If both values are + * integers, values outside of JavaScript's safe number range + * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to + * precision loss. Furthermore, once processed by the Firestore backend, all + * integer operations are capped between -2^63 and 2^63-1. + * + * If the current field value is not of type `number`, or if the field does not + * yet exist, the transformation sets the field to the given value. + * + * @param n - The value to increment by. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ function increment(e) { + return new __PRIVATE_NumericIncrementFieldValueImpl("increment", e); +} + +/** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ function vector(e) { + return new VectorValue(e); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch} + * is 500. + * + * Unlike transactions, write batches are persisted offline and therefore are + * preferable when you don't need to condition your writes on read data. + * + * @returns A {@link WriteBatch} that can be used to atomically execute multiple + * writes. + */ function writeBatch(e) { + return ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)), new WriteBatch(e, (t => executeWrite(e, t))); +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function setIndexConfiguration(e, t) { + const n = ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)); + if (!n._uninitializedComponentsProvider || "memory" === n._uninitializedComponentsProvider._offline.kind) + // PORTING NOTE: We don't return an error if the user has not enabled + // persistence since `enableIndexeddbPersistence()` can fail on the Web. + return __PRIVATE_logWarn("Cannot enable indexes when persistence is disabled"), + Promise.resolve(); + const r = function __PRIVATE_parseIndexes(e) { + const t = "string" == typeof e ? function __PRIVATE_tryParseJson(e) { + try { + return JSON.parse(e); + } catch (e) { + throw new FirestoreError(N.INVALID_ARGUMENT, "Failed to parse JSON: " + e?.message); + } + }(e) : e, n = []; + if (Array.isArray(t.indexes)) for (const e of t.indexes) { + const t = __PRIVATE_tryGetString(e, "collectionGroup"), r = []; + if (Array.isArray(e.fields)) for (const t of e.fields) { + const e = __PRIVATE_fieldPathFromDotSeparatedString("setIndexConfiguration", __PRIVATE_tryGetString(t, "fieldPath")); + "CONTAINS" === t.arrayConfig ? r.push(new IndexSegment(e, 2 /* IndexKind.CONTAINS */)) : "ASCENDING" === t.order ? r.push(new IndexSegment(e, 0 /* IndexKind.ASCENDING */)) : "DESCENDING" === t.order && r.push(new IndexSegment(e, 1 /* IndexKind.DESCENDING */)); + } + n.push(new FieldIndex(FieldIndex.UNKNOWN_ID, t, r, IndexState.empty())); + } + return n; + }(t); + return __PRIVATE_firestoreClientSetIndexConfiguration(n, r); +} + +function __PRIVATE_tryGetString(e, t) { + if ("string" != typeof e[t]) throw new FirestoreError(N.INVALID_ARGUMENT, "Missing string value for: " + t); + return e[t]; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `PersistentCacheIndexManager` for configuring persistent cache indexes used + * for local query execution. + * + * To use, call `getPersistentCacheIndexManager()` to get an instance. + */ class PersistentCacheIndexManager { + /** @hideconstructor */ + constructor(e) { + this._firestore = e, + /** A type string to uniquely identify instances of this class. */ + this.type = "PersistentCacheIndexManager"; + } +} + +/** + * Returns the PersistentCache Index Manager used by the given `Firestore` + * object. + * + * @return The `PersistentCacheIndexManager` instance, or `null` if local + * persistent storage is not in use. + */ function getPersistentCacheIndexManager(e) { + e = __PRIVATE_cast(e, Firestore); + const t = En.get(e); + if (t) return t; + const n = ensureFirestoreConfigured(e); + if ("persistent" !== n._uninitializedComponentsProvider?._offline.kind) return null; + const r = new PersistentCacheIndexManager(e); + return En.set(e, r), r; +} + +/** + * Enables the SDK to create persistent cache indexes automatically for local + * query execution when the SDK believes cache indexes can help improve + * performance. + * + * This feature is disabled by default. + */ function enablePersistentCacheIndexAutoCreation(e) { + __PRIVATE_setPersistentCacheIndexAutoCreationEnabled(e, !0); +} + +/** + * Stops creating persistent cache indexes automatically for local query + * execution. The indexes which have been created by calling + * `enablePersistentCacheIndexAutoCreation()` still take effect. + */ function disablePersistentCacheIndexAutoCreation(e) { + __PRIVATE_setPersistentCacheIndexAutoCreationEnabled(e, !1); +} + +/** + * Removes all persistent cache indexes. + * + * Please note this function will also deletes indexes generated by + * `setIndexConfiguration()`, which is deprecated. + */ function deleteAllPersistentCacheIndexes(e) { + __PRIVATE_firestoreClientDeleteAllFieldIndexes(ensureFirestoreConfigured(e._firestore)).then((e => __PRIVATE_logDebug("deleting all persistent cache indexes succeeded"))).catch((e => __PRIVATE_logWarn("deleting all persistent cache indexes failed", e))); +} + +function __PRIVATE_setPersistentCacheIndexAutoCreationEnabled(e, t) { + __PRIVATE_firestoreClientSetPersistentCacheIndexAutoCreationEnabled(ensureFirestoreConfigured(e._firestore), t).then((e => __PRIVATE_logDebug(`setting persistent cache index auto creation isEnabled=${t} succeeded`))).catch((e => __PRIVATE_logWarn(`setting persistent cache index auto creation isEnabled=${t} failed`, e))); +} + +/** + * Maps `Firestore` instances to their corresponding + * `PersistentCacheIndexManager` instances. + * + * Use a `WeakMap` so that the mapping will be automatically dropped when the + * `Firestore` instance is garbage collected. This emulates a private member + * as described in https://goo.gle/454yvug. + */ const En = new WeakMap; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @internal + * @private + * + * This function is for internal use only. + * + * Returns the `QueryTarget` representation of the given query. Returns `null` + * if the Firestore client associated with the given query has not been + * initialized or has been terminated. + * + * @param query - The Query to convert to proto representation. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function _internalQueryToProtoQueryTarget(e) { + const t = ensureFirestoreConfigured(__PRIVATE_cast(e.firestore, Firestore)), n = t._onlineComponents?.datastore.serializer; + return void 0 === n ? null : __PRIVATE_toQueryTarget(n, __PRIVATE_queryToTarget(e._query)).ft; +} + +/** + * @internal + * @private + * + * This function is for internal use only. + * + * Returns `RunAggregationQueryRequest` which contains the proto representation + * of the given aggregation query request. Returns null if the Firestore client + * associated with the given query has not been initialized or has been + * terminated. + * + * @param query - The Query to convert to proto representation. + * @param aggregateSpec - The set of aggregations and their aliases. + */ function _internalAggregationQueryToProtoRunAggregationQueryRequest(e, t) { + const n = __PRIVATE_mapToArray(t, ((e, t) => new __PRIVATE_AggregateImpl(t, e.aggregateType, e._internalFieldPath))), r = ensureFirestoreConfigured(__PRIVATE_cast(e.firestore, Firestore)), i = r._onlineComponents?.datastore.serializer; + return void 0 === i ? null : __PRIVATE_toRunAggregationQueryRequest(i, __PRIVATE_queryToAggregateTarget(e._query), n, + /* skipAliasing= */ !0).request; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Testing hooks for use by Firestore's integration test suite to reach into the + * SDK internals to validate logic and behavior that is not visible from the + * public API surface. + * + * @internal + */ class TestingHooks { + constructor() { + throw new Error("instances of this class should not be created"); + } + /** + * Registers a callback to be notified when an existence filter mismatch + * occurs in the Watch listen stream. + * + * The relative order in which callbacks are notified is unspecified; do not + * rely on any particular ordering. If a given callback is registered multiple + * times then it will be notified multiple times, once per registration. + * + * @param callback the callback to invoke upon existence filter mismatch. + * + * @return a function that, when called, unregisters the given callback; only + * the first invocation of the returned function does anything; all subsequent + * invocations do nothing. + */ static onExistenceFilterMismatch(e) { + return __PRIVATE_TestingHooksSpiImpl.instance.onExistenceFilterMismatch(e); + } +} + +/** + * The implementation of `TestingHooksSpi`. + */ class __PRIVATE_TestingHooksSpiImpl { + constructor() { + this.Mc = new Map; + } + static get instance() { + return dn || (dn = new __PRIVATE_TestingHooksSpiImpl, function __PRIVATE_setTestingHooksSpi(e) { + if (wt) throw new Error("a TestingHooksSpi instance is already set"); + wt = e; + }(dn)), dn; + } + lt(e) { + this.Mc.forEach((t => t(e))); + } + onExistenceFilterMismatch(e) { + const t = Symbol(), n = this.Mc; + return n.set(t, e), () => n.delete(t); + } +} + +let dn = null; + +/** + * Cloud Firestore + * + * @packageDocumentation + */ !function __PRIVATE_registerFirestore(e, t = !0) { + !function __PRIVATE_setSDKVersion(e) { + x = e; + }(SDK_VERSION), _registerComponent(new Component("firestore", ((e, {instanceIdentifier: n, options: r}) => { + const i = e.getProvider("app").getImmediate(), s = new Firestore(new __PRIVATE_FirebaseAuthCredentialsProvider(e.getProvider("auth-internal")), new __PRIVATE_FirebaseAppCheckTokenProvider(i, e.getProvider("app-check-internal")), function __PRIVATE_databaseIdFromApp(e, t) { + if (!Object.prototype.hasOwnProperty.apply(e.options, [ "projectId" ])) throw new FirestoreError(N.INVALID_ARGUMENT, '"projectId" not provided in firebase.initializeApp.'); + return new DatabaseId(e.options.projectId, t); + }(i, n), i); + return r = { + useFetchStreams: t, + ...r + }, s._setSettings(r), s; + }), "PUBLIC").setMultipleInstances(!0)), registerVersion(F, M, e), + // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation + registerVersion(F, M, "esm2020"); +}(); + +export { AbstractUserDataWriter, AggregateField, AggregateQuerySnapshot, Bytes, ln as CACHE_SIZE_UNLIMITED, CollectionReference, DocumentReference, DocumentSnapshot, FieldPath, FieldValue, Firestore, FirestoreError, GeoPoint, LoadBundleTask, PersistentCacheIndexManager, Query, QueryCompositeFilterConstraint, QueryConstraint, QueryDocumentSnapshot, QueryEndAtConstraint, QueryFieldFilterConstraint, QueryLimitConstraint, QueryOrderByConstraint, QuerySnapshot, QueryStartAtConstraint, SnapshotMetadata, Timestamp, Transaction, VectorValue, WriteBatch, __PRIVATE_AutoId as _AutoId, ByteString as _ByteString, DatabaseId as _DatabaseId, DocumentKey as _DocumentKey, __PRIVATE_EmptyAppCheckTokenProvider as _EmptyAppCheckTokenProvider, __PRIVATE_EmptyAuthCredentialsProvider as _EmptyAuthCredentialsProvider, FieldPath$1 as _FieldPath, TestingHooks as _TestingHooks, __PRIVATE_cast as _cast, __PRIVATE_debugAssert as _debugAssert, _internalAggregationQueryToProtoRunAggregationQueryRequest, _internalQueryToProtoQueryTarget, __PRIVATE_isBase64Available as _isBase64Available, __PRIVATE_logWarn as _logWarn, __PRIVATE_validateIsNotUsedTogether as _validateIsNotUsedTogether, addDoc, aggregateFieldEqual, aggregateQuerySnapshotEqual, and, arrayRemove, arrayUnion, average, clearIndexedDbPersistence, collection, collectionGroup, connectFirestoreEmulator, count, deleteAllPersistentCacheIndexes, deleteDoc, deleteField, disableNetwork, disablePersistentCacheIndexAutoCreation, doc, documentId, documentSnapshotFromJSON, enableIndexedDbPersistence, enableMultiTabIndexedDbPersistence, enableNetwork, enablePersistentCacheIndexAutoCreation, endAt, endBefore, ensureFirestoreConfigured, executeWrite, getAggregateFromServer, getCountFromServer, getDoc, getDocFromCache, getDocFromServer, getDocs, getDocsFromCache, getDocsFromServer, getFirestore, getPersistentCacheIndexManager, increment, initializeFirestore, limit, limitToLast, loadBundle, memoryEagerGarbageCollector, memoryLocalCache, memoryLruGarbageCollector, namedQuery, onSnapshot, onSnapshotResume, onSnapshotsInSync, or, orderBy, persistentLocalCache, persistentMultipleTabManager, persistentSingleTabManager, query, queryEqual, querySnapshotFromJSON, refEqual, runTransaction, serverTimestamp, setDoc, setIndexConfiguration, setLogLevel, snapshotEqual, startAfter, startAt, sum, terminate, updateDoc, vector, waitForPendingWrites, where, writeBatch }; +//# sourceMappingURL=index.esm.js.map diff --git a/frontend-old/node_modules/@firebase/firestore/dist/index.esm.js.map b/frontend-old/node_modules/@firebase/firestore/dist/index.esm.js.map new file mode 100644 index 0000000..656d631 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/index.esm.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.esm.js","sources":["../src/auth/user.ts","../src/core/version.ts","../src/util/log.ts","../src/platform/browser/format_json.ts","../src/util/assert.ts","../src/util/error.ts","../src/util/promise.ts","../src/api/credentials.ts","../src/platform/browser/random_bytes.ts","../src/util/misc.ts","../src/model/path.ts","../src/model/document_key.ts","../src/util/input_validation.ts","../src/util/json_validation.ts","../src/lite-api/timestamp.ts","../src/core/snapshot_version.ts","../src/model/field_index.ts","../src/local/persistence_transaction.ts","../src/local/local_store.ts","../src/local/persistence_promise.ts","../src/local/simple_db.ts","../src/local/index_backfiller.ts","../src/core/listen_sequence.ts","../src/util/types.ts","../src/local/encoded_resource_path.ts","../src/local/indexeddb_schema_legacy.ts","../src/local/indexeddb_sentinels.ts","../src/local/indexeddb_transaction.ts","../src/util/obj.ts","../src/util/sorted_map.ts","../src/util/sorted_set.ts","../src/model/field_mask.ts","../src/util/base64_decode_error.ts","../src/platform/browser/base64.ts","../src/util/byte_string.ts","../src/model/normalize.ts","../src/model/server_timestamps.ts","../src/core/database_info.ts","../src/model/values.ts","../src/model/object_value.ts","../src/model/document.ts","../src/core/bound.ts","../src/core/order_by.ts","../src/core/filter.ts","../src/core/target.ts","../src/core/query.ts","../src/util/obj_map.ts","../src/model/collections.ts","../src/remote/number_serializer.ts","../src/model/transform_operation.ts","../src/model/mutation.ts","../src/model/mutation_batch.ts","../src/model/overlay.ts","../src/core/aggregate.ts","../src/remote/existence_filter.ts","../src/remote/rpc_error.ts","../src/util/testing_hooks_spi.ts","../src/platform/browser/text_serializer.ts","../src/remote/bloom_filter.ts","../src/remote/remote_event.ts","../src/remote/watch_change.ts","../src/remote/serializer.ts","../src/local/target_data.ts","../src/local/local_serializer.ts","../src/local/indexeddb_bundle_cache.ts","../src/local/indexeddb_document_overlay_cache.ts","../src/local/indexeddb_globals_cache.ts","../src/index/firestore_index_value_writer.ts","../src/index/ordered_code_writer.ts","../src/index/index_byte_encoder.ts","../src/index/index_entry.ts","../src/model/target_index_matcher.ts","../src/util/logic_utils.ts","../src/local/memory_index_manager.ts","../src/local/indexeddb_index_manager.ts","../src/local/lru_garbage_collector.ts","../src/local/indexeddb_mutation_batch_impl.ts","../src/local/indexeddb_mutation_queue.ts","../src/core/target_id_generator.ts","../src/local/indexeddb_target_cache.ts","../src/local/lru_garbage_collector_impl.ts","../src/local/indexeddb_lru_delegate_impl.ts","../src/local/remote_document_change_buffer.ts","../src/local/indexeddb_remote_document_cache.ts","../src/local/overlayed_document.ts","../src/local/local_documents_view.ts","../src/local/memory_bundle_cache.ts","../src/local/memory_document_overlay_cache.ts","../src/local/memory_globals_cache.ts","../src/local/reference_set.ts","../src/local/memory_mutation_queue.ts","../src/local/memory_remote_document_cache.ts","../src/local/memory_target_cache.ts","../src/local/memory_persistence.ts","../src/local/indexeddb_schema_converter.ts","../src/local/indexeddb_persistence.ts","../src/local/indexeddb_schema.ts","../src/local/local_view_changes.ts","../src/local/query_context.ts","../src/local/query_engine.ts","../src/local/local_store_impl.ts","../src/local/shared_client_state_schema.ts","../src/local/shared_client_state.ts","../src/remote/connectivity_monitor_noop.ts","../src/platform/browser/connectivity_monitor.ts","../src/util/debug_uid.ts","../src/remote/rest_connection.ts","../src/remote/stream_bridge.ts","../src/platform/browser/webchannel_connection.ts","../src/platform/browser/dom.ts","../src/platform/browser/serializer.ts","../src/remote/backoff.ts","../src/remote/persistent_stream.ts","../src/remote/datastore.ts","../src/remote/online_state_tracker.ts","../src/remote/remote_store.ts","../src/util/async_queue.ts","../src/model/document_set.ts","../src/core/view_snapshot.ts","../src/core/event_manager.ts","../src/util/bundle_reader.ts","../src/core/bundle_impl.ts","../src/core/view.ts","../src/core/sync_engine_impl.ts","../src/core/component_provider.ts","../src/platform/browser/connection.ts","../src/util/byte_stream.ts","../src/util/async_observer.ts","../src/util/bundle_reader_impl.ts","../src/util/bundle_reader_sync_impl.ts","../src/core/transaction.ts","../src/core/transaction_runner.ts","../src/core/firestore_client.ts","../src/platform/browser/byte_stream_reader.ts","../src/util/array.ts","../src/api/long_polling_options.ts","../src/lite-api/components.ts","../src/lite-api/settings.ts","../src/lite-api/database.ts","../src/lite-api/reference.ts","../src/util/async_queue_impl.ts","../src/api/observer.ts","../src/api/bundle.ts","../src/api/database.ts","../src/lite-api/aggregate_types.ts","../src/lite-api/bytes.ts","../src/lite-api/field_path.ts","../src/lite-api/field_value.ts","../src/lite-api/geo_point.ts","../src/lite-api/vector_value.ts","../src/lite-api/user_data_reader.ts","../src/lite-api/snapshot.ts","../src/lite-api/query.ts","../src/lite-api/user_data_writer.ts","../src/lite-api/reference_impl.ts","../src/lite-api/aggregate.ts","../src/api/snapshot.ts","../src/platform/browser/snapshot_to_json.ts","../src/api/reference_impl.ts","../src/api/aggregate.ts","../src/api/cache_config.ts","../src/core/transaction_options.ts","../src/lite-api/write_batch.ts","../src/lite-api/transaction.ts","../src/api/transaction.ts","../src/lite-api/field_value_impl.ts","../src/api/write_batch.ts","../src/api/index_configuration.ts","../src/api/persistent_cache_index_manager.ts","../src/remote/internal_serializer.ts","../src/util/testing_hooks.ts","../src/register.ts","../src/index.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Simple wrapper around a nullable UID. Mostly exists to make code more\n * readable.\n */\nexport class User {\n /** A user with a null UID. */\n static readonly UNAUTHENTICATED = new User(null);\n\n // TODO(mikelehen): Look into getting a proper uid-equivalent for\n // non-FirebaseAuth providers.\n static readonly GOOGLE_CREDENTIALS = new User('google-credentials-uid');\n static readonly FIRST_PARTY = new User('first-party-uid');\n static readonly MOCK_USER = new User('mock-user');\n\n constructor(readonly uid: string | null) {}\n\n isAuthenticated(): boolean {\n return this.uid != null;\n }\n\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */\n toKey(): string {\n if (this.isAuthenticated()) {\n return 'uid:' + this.uid;\n } else {\n return 'anonymous-user';\n }\n }\n\n isEqual(otherUser: User): boolean {\n return otherUser.uid === this.uid;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The semver (www.semver.org) version of the SDK. */\nimport { version } from '../../../firebase/package.json';\nexport let SDK_VERSION = version;\nexport function setSDKVersion(version: string): void {\n SDK_VERSION = version;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel, LogLevelString } from '@firebase/logger';\n\nimport { SDK_VERSION } from '../core/version';\nimport { formatJSON } from '../platform/format_json';\n\nexport { LogLevel, LogLevelString };\n\nconst logClient = new Logger('@firebase/firestore');\n\n// Helper methods are needed because variables can't be exported as read/write\nexport function getLogLevel(): LogLevel {\n return logClient.logLevel;\n}\n\n/**\n * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).\n *\n * @param logLevel - The verbosity you set for activity and error logging. Can\n * be any of the following values:\n *\n *

    \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 *\n * @param code generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(\n code: number,\n message: string,\n context?: Record\n): never;\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 *\n * @param id generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(id: number, context?: Record): never;\n\nexport function fail(\n id: number,\n messageOrContext?: string | Record,\n context?: Record\n): never {\n let message = 'Unexpected state';\n if (typeof messageOrContext === 'string') {\n message = messageOrContext;\n } else {\n context = messageOrContext;\n }\n _fail(id, message, context);\n}\n\nfunction _fail(\n id: number,\n failure: string,\n context?: Record\n): never {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n let message = `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ${failure} (ID: ${id.toString(\n 16\n )})`;\n if (context !== undefined) {\n try {\n const stringContext = JSON.stringify(context);\n message += ' CONTEXT: ' + stringContext;\n } catch (e) {\n message += ' CONTEXT: ' + context;\n }\n }\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 *\n * @param id generate a new unique value with `yarn assertion-idgenerate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n assertion: boolean,\n id: number,\n message: string,\n context?: Record\n): asserts assertion;\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 *\n * @param id generate a new unique value with `yarn assertion-id:generate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n assertion: boolean,\n id: number,\n context?: Record\n): asserts assertion;\n\nexport function hardAssert(\n assertion: boolean,\n id: number,\n messageOrContext?: string | Record,\n context?: Record\n): asserts assertion {\n let message = 'Unexpected state';\n if (typeof messageOrContext === 'string') {\n message = messageOrContext;\n } else {\n context = messageOrContext;\n }\n\n if (!assertion) {\n _fail(id, message, context);\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(0xdeb6, 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 { FirebaseApp, _isFirebaseServerApp } from '@firebase/app';\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 0xa539,\n 'Invalid tokenData returned from getToken()',\n { 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 0xa540,\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 0x7c5d,\n 'Invalid tokenData returned from getToken()',\n { 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 0x0807,\n 'Received invalid UID',\n { 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 private serverAppAppCheckToken: string | null = null;\n\n constructor(\n app: FirebaseApp,\n private appCheckProvider: Provider\n ) {\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n }\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n hardAssert(\n this.tokenListener === undefined,\n 0x0db8,\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 if (this.serverAppAppCheckToken) {\n return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n }\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 0xae0e,\n 'Invalid tokenResult returned from getToken()',\n { 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 private serverAppAppCheckToken: string | null = null;\n\n constructor(\n app: FirebaseApp,\n private appCheckProvider: Provider\n ) {\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n appCheckProvider.onInit(appCheck => {\n this.appCheck = appCheck;\n });\n }\n\n getToken(): Promise {\n if (this.serverAppAppCheckToken) {\n return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n }\n\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 0x0d8e,\n 'Invalid tokenResult returned from getToken()',\n { 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\n/** Compare strings in UTF-8 encoded byte order */\nexport function compareUtf8Strings(left: string, right: string): number {\n // Find the first differing character (a.k.a. \"UTF-16 code unit\") in the two strings and,\n // if found, use that character to determine the relative ordering of the two strings as a\n // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by\n // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8\n // and UTF-16 happen to represent Unicode code points.\n //\n // After finding the first pair of differing characters, there are two cases:\n //\n // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or\n // both are surrogates from a surrogate pair (that collectively represent code points greater\n // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the\n // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is\n // sufficient.\n //\n // Case 2: One character is a surrogate and the other is not. In this case the surrogate-\n // containing string is always ordered after the non-surrogate. This is because surrogates are\n // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations\n // and are lexicographically greater than the 1, 2, or 3-byte representations of code points\n // less than or equal to 0xFFFF.\n //\n // An example of why Case 2 is required is comparing the following two Unicode code points:\n //\n // |-----------------------|------------|---------------------|-----------------|\n // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding |\n // |-----------------------|------------|---------------------|-----------------|\n // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD |\n // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 |\n // |-----------------------|------------|---------------------|-----------------|\n //\n // A lexicographical comparison of the UTF-8 encodings of these code points would order\n // \"Replacement Character\" _before_ \"Grinning Face\" because 0xEF is less than 0xF0. However, a\n // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously\n // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out,\n // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate\n // pair with those that do not.\n const length = Math.min(left.length, right.length);\n for (let i = 0; i < length; i++) {\n const leftChar = left.charAt(i);\n const rightChar = right.charAt(i);\n if (leftChar !== rightChar) {\n return isSurrogate(leftChar) === isSurrogate(rightChar)\n ? primitiveComparator(leftChar, rightChar)\n : isSurrogate(leftChar)\n ? 1\n : -1;\n }\n }\n\n // Use the lengths of the strings to determine the overall comparison result since either the\n // strings were equal or one is a prefix of the other.\n return primitiveComparator(left.length, right.length);\n}\n\nconst MIN_SURROGATE = 0xd800;\nconst MAX_SURROGATE = 0xdfff;\n\nexport function isSurrogate(s: string): boolean {\n debugAssert(s.length === 1, `s.length == ${s.length}, but expected 1`);\n const c = s.charCodeAt(0);\n return c >= MIN_SURROGATE && c <= MAX_SURROGATE;\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 { Integer } from '@firebase/webchannel-wrapper/bloom-blob';\n\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { compareUtf8Strings, primitiveComparator } from '../util/misc';\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(0x027d, 'offset out of range', {\n offset,\n range: segments.length\n });\n }\n\n if (length === undefined) {\n length = segments.length - offset;\n } else if (length > segments.length - offset) {\n fail(0x06d2, 'length out of range', {\n length,\n range: segments.length - offset\n });\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 /**\n * Compare 2 paths segment by segment, prioritizing numeric IDs\n * (e.g., \"__id123__\") in numeric ascending order, followed by string\n * segments in lexicographical order.\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 comparison = BasePath.compareSegments(p1.get(i), p2.get(i));\n if (comparison !== 0) {\n return comparison;\n }\n }\n return primitiveComparator(p1.length, p2.length);\n }\n\n private static compareSegments(lhs: string, rhs: string): number {\n const isLhsNumeric = BasePath.isNumericId(lhs);\n const isRhsNumeric = BasePath.isNumericId(rhs);\n\n if (isLhsNumeric && !isRhsNumeric) {\n // Only lhs is numeric\n return -1;\n } else if (!isLhsNumeric && isRhsNumeric) {\n // Only rhs is numeric\n return 1;\n } else if (isLhsNumeric && isRhsNumeric) {\n // both numeric\n return BasePath.extractNumericId(lhs).compare(\n BasePath.extractNumericId(rhs)\n );\n } else {\n // both non-numeric\n return compareUtf8Strings(lhs, rhs);\n }\n }\n\n // Checks if a segment is a numeric ID (starts with \"__id\" and ends with \"__\").\n private static isNumericId(segment: string): boolean {\n return segment.startsWith('__id') && segment.endsWith('__');\n }\n\n private static extractNumericId(segment: string): Integer {\n return Integer.fromString(segment.substring(4, segment.length - 2));\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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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(0x3029, 'Unknown wrong type', { 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 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isPlainObject } from '../util/input_validation';\n\nimport { Code, FirestoreError } from './error';\n\n/**\n * A list of data types Firestore objects may serialize in their toJSON implemenetations.\n * @private\n * @internal\n */\nexport type JsonTypeDesc =\n | 'object'\n | 'string'\n | 'number'\n | 'boolean'\n | 'null'\n | 'undefined';\n\n/**\n * An association of JsonTypeDesc values to their native types.\n * @private\n * @internal\n */\nexport type TSType = T extends 'object'\n ? object\n : T extends 'string'\n ? string\n : T extends 'number'\n ? number\n : T extends 'boolean'\n ? boolean\n : T extends 'null'\n ? null\n : T extends 'undefined'\n ? undefined\n : never;\n\n/**\n * The representation of a JSON object property name and its type value.\n * @private\n * @internal\n */\nexport interface Property {\n value?: TSType;\n typeString: JsonTypeDesc;\n}\n\n/**\n * A type Firestore data types may use to define the fields used in their JSON serialization.\n * @private\n * @internal\n */\nexport interface JsonSchema {\n [key: string]: Property;\n}\n\n/**\n * Associates the JSON property type to the native type and sets them to be Required.\n * @private\n * @internal\n */\nexport type Json = {\n [K in keyof T]: Required['value'];\n};\n\n/**\n * Helper function to define a JSON schema {@link Property}.\n * @private\n * @internal\n */\nexport function property(\n typeString: T,\n optionalValue?: TSType\n): Property {\n const result: Property = {\n typeString\n };\n if (optionalValue) {\n result.value = optionalValue;\n }\n return result;\n}\n\n/**\n * Validates the JSON object based on the provided schema, and narrows the type to the provided\n * JSON schema.\n * @private\n * @internal\n *\n * @param json A JSON object to validate.\n * @param scheme a {@link JsonSchema} that defines the properties to validate.\n * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise.\n */\nexport function validateJSON(\n json: object,\n schema: S\n): json is Json {\n if (!isPlainObject(json)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'JSON must be an object');\n }\n let error: string | undefined = undefined;\n for (const key in schema) {\n if (schema[key]) {\n const typeString = schema[key].typeString;\n const value: { value: unknown } | undefined =\n 'value' in schema[key] ? { value: schema[key].value } : undefined;\n if (!(key in json)) {\n error = `JSON missing required field: '${key}'`;\n break;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const fieldValue = (json as any)[key];\n if (typeString && typeof fieldValue !== typeString) {\n error = `JSON field '${key}' must be a ${typeString}.`;\n break;\n } else if (value !== undefined && fieldValue !== value.value) {\n error = `Expected '${key}' field to equal '${value.value}'`;\n break;\n }\n }\n }\n if (error) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, error);\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 { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\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 static _jsonSchemaVersion: string = 'firestore/timestamp/1.0';\n static _jsonSchema = {\n type: property('string', Timestamp._jsonSchemaVersion),\n seconds: property('number'),\n nanoseconds: property('number')\n };\n\n /**\n * Returns a JSON-serializable representation of this `Timestamp`.\n */\n toJSON(): { seconds: number; nanoseconds: number; type: string } {\n return {\n type: Timestamp._jsonSchemaVersion,\n seconds: this.seconds,\n nanoseconds: this.nanoseconds\n };\n }\n\n /**\n * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}.\n */\n static fromJSON(json: object): Timestamp {\n if (validateJSON(json, Timestamp._jsonSchema)) {\n return new Timestamp(json.seconds, json.nanoseconds);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Timestamp from JSON.'\n );\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 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(0xe830, '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 { getGlobal, 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 `indexedDB` are guarded by SimpleDb.isAvailable() and getGlobal()\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 lastClosedDbVersion: number | null = null;\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 const globals = getGlobal();\n return wrapRequest(\n globals.indexedDB.deleteDatabase(name)\n ).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\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 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { FirestoreError } from '../api';\nimport { DocumentMap } from '../model/collections';\nimport {\n IndexOffset,\n indexOffsetComparator,\n newIndexOffsetFromDocument\n} from '../model/field_index';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { logDebug } from '../util/log';\n\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from './local_store';\nimport { LocalWriteResult } from './local_store_impl';\nimport { Persistence, Scheduler } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { isIndexedDbTransactionError } from './simple_db';\n\nconst LOG_TAG = 'IndexBackfiller';\n\n/** How long we wait to try running index backfill after SDK initialization. */\nconst INITIAL_BACKFILL_DELAY_MS = 15 * 1000;\n\n/** Minimum amount of time between backfill checks, after the first one. */\nconst REGULAR_BACKFILL_DELAY_MS = 60 * 1000;\n\n/** The maximum number of documents to process each time backfill() is called. */\nconst MAX_DOCUMENTS_TO_PROCESS = 50;\n\n/** This class is responsible for the scheduling of Index Backfiller. */\nexport class IndexBackfillerScheduler implements Scheduler {\n private task: DelayedOperation | null;\n\n constructor(\n private readonly asyncQueue: AsyncQueue,\n private readonly backfiller: IndexBackfiller\n ) {\n this.task = null;\n }\n\n start(): void {\n debugAssert(\n this.task === null,\n 'Cannot start an already started IndexBackfillerScheduler'\n );\n this.schedule(INITIAL_BACKFILL_DELAY_MS);\n }\n\n stop(): void {\n if (this.task) {\n this.task.cancel();\n this.task = null;\n }\n }\n\n get started(): boolean {\n return this.task !== null;\n }\n\n private schedule(delay: number): void {\n debugAssert(\n this.task === null,\n 'Cannot schedule IndexBackfiller while a task is pending'\n );\n logDebug(LOG_TAG, `Scheduled in ${delay}ms`);\n this.task = this.asyncQueue.enqueueAfterDelay(\n TimerId.IndexBackfill,\n delay,\n async () => {\n this.task = null;\n try {\n const documentsProcessed = await this.backfiller.backfill();\n logDebug(LOG_TAG, `Documents written: ${documentsProcessed}`);\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(\n LOG_TAG,\n 'Ignoring IndexedDB error during index backfill: ',\n e\n );\n } else {\n await ignoreIfPrimaryLeaseLoss(e as FirestoreError);\n }\n }\n await this.schedule(REGULAR_BACKFILL_DELAY_MS);\n }\n );\n }\n}\n\n/** Implements the steps for backfilling indexes. */\nexport class IndexBackfiller {\n constructor(\n /**\n * LocalStore provides access to IndexManager and LocalDocumentView.\n * These properties will update when the user changes. Consequently,\n * making a local copy of IndexManager and LocalDocumentView will require\n * updates over time. The simpler solution is to rely on LocalStore to have\n * an up-to-date references to IndexManager and LocalDocumentStore.\n */\n private readonly localStore: LocalStore,\n private readonly persistence: Persistence\n ) {}\n\n async backfill(\n maxDocumentsToProcess: number = MAX_DOCUMENTS_TO_PROCESS\n ): Promise {\n return this.persistence.runTransaction(\n 'Backfill Indexes',\n 'readwrite-primary',\n txn => this.writeIndexEntries(txn, maxDocumentsToProcess)\n );\n }\n\n /** Writes index entries until the cap is reached. Returns the number of documents processed. */\n private writeIndexEntries(\n transaction: PersistenceTransaction,\n maxDocumentsToProcess: number\n ): PersistencePromise {\n const processedCollectionGroups = new Set();\n let documentsRemaining = maxDocumentsToProcess;\n let continueLoop = true;\n return PersistencePromise.doWhile(\n () => continueLoop === true && documentsRemaining > 0,\n () => {\n return this.localStore.indexManager\n .getNextCollectionGroupToUpdate(transaction)\n .next((collectionGroup: string | null) => {\n if (\n collectionGroup === null ||\n processedCollectionGroups.has(collectionGroup)\n ) {\n continueLoop = false;\n } else {\n logDebug(LOG_TAG, `Processing collection: ${collectionGroup}`);\n return this.writeEntriesForCollectionGroup(\n transaction,\n collectionGroup,\n documentsRemaining\n ).next(documentsProcessed => {\n documentsRemaining -= documentsProcessed;\n processedCollectionGroups.add(collectionGroup);\n });\n }\n });\n }\n ).next(() => maxDocumentsToProcess - documentsRemaining);\n }\n\n /**\n * Writes entries for the provided collection group. Returns the number of documents processed.\n */\n private writeEntriesForCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n documentsRemainingUnderCap: number\n ): PersistencePromise {\n // Use the earliest offset of all field indexes to query the local cache.\n return this.localStore.indexManager\n .getMinOffsetFromCollectionGroup(transaction, collectionGroup)\n .next(existingOffset =>\n this.localStore.localDocuments\n .getNextDocuments(\n transaction,\n collectionGroup,\n existingOffset,\n documentsRemainingUnderCap\n )\n .next(nextBatch => {\n const docs: DocumentMap = nextBatch.changes;\n return this.localStore.indexManager\n .updateIndexEntries(transaction, docs)\n .next(() => this.getNewOffset(existingOffset, nextBatch))\n .next(newOffset => {\n logDebug(LOG_TAG, `Updating offset: ${newOffset}`);\n return this.localStore.indexManager.updateCollectionGroup(\n transaction,\n collectionGroup,\n newOffset\n );\n })\n .next(() => docs.size);\n })\n );\n }\n\n /** Returns the next offset based on the provided documents. */\n private getNewOffset(\n existingOffset: IndexOffset,\n lookupResult: LocalWriteResult\n ): IndexOffset {\n let maxOffset: IndexOffset = existingOffset;\n lookupResult.changes.forEach((key, document) => {\n const newOffset: IndexOffset = newIndexOffsetFromDocument(document);\n if (indexOffsetComparator(newOffset, maxOffset) > 0) {\n maxOffset = newOffset;\n }\n });\n return new IndexOffset(\n maxOffset.readTime,\n maxOffset.documentKey,\n Math.max(lookupResult.batchId, existingOffset.largestBatchId)\n );\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequenceNumber } from './types';\n\n/**\n * `SequenceNumberSyncer` defines the methods required to keep multiple instances of a\n * `ListenSequence` in sync.\n */\nexport interface SequenceNumberSyncer {\n // Notify the syncer that a new sequence number has been used.\n writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void;\n // Setting this property allows the syncer to notify when a sequence number has been used, and\n // and lets the ListenSequence adjust its internal previous value accordingly.\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null;\n}\n\n/**\n * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to\n * exceed. All subsequent calls to next will return increasing values. If provided with a\n * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as\n * well as write out sequence numbers that it produces via `next()`.\n */\nexport class ListenSequence {\n static readonly INVALID: ListenSequenceNumber = -1;\n\n private writeNewSequenceNumber?: (\n newSequenceNumber: ListenSequenceNumber\n ) => void;\n\n constructor(\n private previousValue: ListenSequenceNumber,\n sequenceNumberSyncer?: SequenceNumberSyncer\n ) {\n if (sequenceNumberSyncer) {\n sequenceNumberSyncer.sequenceNumberHandler = sequenceNumber =>\n this.setPreviousValue(sequenceNumber);\n this.writeNewSequenceNumber = sequenceNumber =>\n sequenceNumberSyncer.writeSequenceNumber(sequenceNumber);\n }\n }\n\n private setPreviousValue(\n externalPreviousValue: ListenSequenceNumber\n ): ListenSequenceNumber {\n this.previousValue = Math.max(externalPreviousValue, this.previousValue);\n return this.previousValue;\n }\n\n next(): ListenSequenceNumber {\n const nextValue = ++this.previousValue;\n if (this.writeNewSequenceNumber) {\n this.writeNewSequenceNumber(nextValue);\n }\n return nextValue;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Sentinel value that sorts before any Mutation Batch ID. */\nexport const BATCHID_UNKNOWN = -1;\n\n// An Object whose keys and values are strings.\nexport interface StringMap {\n [key: string]: string;\n}\n\n/**\n * Returns whether a variable is either undefined or null.\n */\nexport function isNullOrUndefined(value: unknown): value is null | undefined {\n return value === null || value === undefined;\n}\n\n/** Returns whether the value represents -0. */\nexport function isNegativeZero(value: number): boolean {\n // Detect if the value is -0.0. Based on polyfill from\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n return value === 0 && 1 / value === 1 / -0;\n}\n\n/**\n * Returns whether a value is an integer and in the safe integer range\n * @param value - The value to test for being an integer and in the safe range\n */\nexport function isSafeInteger(value: unknown): boolean {\n return (\n typeof value === 'number' &&\n Number.isInteger(value) &&\n !isNegativeZero(value) &&\n value <= Number.MAX_SAFE_INTEGER &&\n value >= Number.MIN_SAFE_INTEGER\n );\n}\n\n/** The subset of the browser's Window interface used by the SDK. */\nexport interface WindowLike {\n readonly localStorage: Storage;\n readonly indexedDB: IDBFactory | null;\n addEventListener(type: string, listener: EventListener): void;\n removeEventListener(type: string, listener: EventListener): void;\n}\n\n/** The subset of the browser's Document interface used by the SDK. */\nexport interface DocumentLike {\n readonly visibilityState: DocumentVisibilityState;\n addEventListener(type: string, listener: EventListener): void;\n removeEventListener(type: string, listener: EventListener): void;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ResourcePath } from '../model/path';\nimport { fail, hardAssert } from '../util/assert';\n\n/**\n * Helpers for dealing with resource paths stored in IndexedDB.\n *\n * Resource paths in their canonical string form do not sort as the server\n * sorts them. Specifically the server splits paths into segments first and then\n * sorts, putting end-of-segment before any character. In a UTF-8 string\n * encoding the slash ('/') that denotes the end-of-segment naturally comes\n * after other characters so the intent here is to encode the path delimiters in\n * such a way that the resulting strings sort naturally.\n *\n * Resource paths are also used for prefix scans so it's important to\n * distinguish whole segments from any longer segments of which they might be a\n * prefix. For example, it's important to make it possible to scan documents in\n * a collection \"foo\" without encountering documents in a collection \"foobar\".\n *\n * Separate from the concerns about resource path ordering and separation,\n * On Android, SQLite imposes additional restrictions since it does not handle\n * keys with embedded NUL bytes particularly well. Rather than change the\n * implementation we keep the encoding identical to keep the ports similar.\n *\n * Taken together this means resource paths when encoded for storage in\n * IndexedDB have the following characteristics:\n *\n * * Segment separators (\"/\") sort before everything else.\n * * All paths have a trailing separator.\n * * NUL bytes do not exist in the output, since IndexedDB doesn't treat them\n * well.\n *\n * Therefore resource paths are encoded into string form using the following\n * rules:\n *\n * * '\\x01' is used as an escape character.\n * * Path separators are encoded as \"\\x01\\x01\"\n * * NUL bytes are encoded as \"\\x01\\x10\"\n * * '\\x01' is encoded as \"\\x01\\x11\"\n *\n * This encoding leaves some room between path separators and the NUL byte\n * just in case we decide to support integer document ids after all.\n *\n * Note that characters treated specially by the backend ('.', '/', and '~')\n * are not treated specially here. This class assumes that any unescaping of\n * resource path strings into actual ResourcePath objects will handle these\n * characters there.\n */\nexport type EncodedResourcePath = string;\n\nconst escapeChar = '\\u0001';\nconst encodedSeparatorChar = '\\u0001';\nconst encodedNul = '\\u0010';\nconst encodedEscape = '\\u0011';\n\n/**\n * Encodes a resource path into a IndexedDb-compatible string form.\n */\nexport function encodeResourcePath(path: ResourcePath): EncodedResourcePath {\n let result = '';\n for (let i = 0; i < path.length; i++) {\n if (result.length > 0) {\n result = encodeSeparator(result);\n }\n result = encodeSegment(path.get(i), result);\n }\n return encodeSeparator(result);\n}\n\n/** Encodes a single segment of a resource path into the given result */\nfunction encodeSegment(segment: string, resultBuf: string): string {\n let result = resultBuf;\n const length = segment.length;\n for (let i = 0; i < length; i++) {\n const c = segment.charAt(i);\n switch (c) {\n case '\\0':\n result += escapeChar + encodedNul;\n break;\n case escapeChar:\n result += escapeChar + encodedEscape;\n break;\n default:\n result += c;\n }\n }\n return result;\n}\n\n/** Encodes a path separator into the given result */\nfunction encodeSeparator(result: string): string {\n return result + escapeChar + encodedSeparatorChar;\n}\n\n/**\n * Decodes the given IndexedDb-compatible string form of a resource path into\n * a ResourcePath instance. Note that this method is not suitable for use with\n * decoding resource names from the server; those are One Platform format\n * strings.\n */\nexport function decodeResourcePath(path: EncodedResourcePath): ResourcePath {\n // Event the empty path must encode as a path of at least length 2. A path\n // with exactly 2 must be the empty path.\n const length = path.length;\n hardAssert(length >= 2, 0xfb98, 'Invalid path', { path });\n if (length === 2) {\n hardAssert(\n path.charAt(0) === escapeChar && path.charAt(1) === encodedSeparatorChar,\n 0xdb51,\n 'Non-empty path had length 2',\n { path }\n );\n return ResourcePath.emptyPath();\n }\n\n // Escape characters cannot exist past the second-to-last position in the\n // source value.\n const lastReasonableEscapeIndex = length - 2;\n\n const segments: string[] = [];\n let segmentBuilder = '';\n\n for (let start = 0; start < length; ) {\n // The last two characters of a valid encoded path must be a separator, so\n // there must be an end to this segment.\n const end = path.indexOf(escapeChar, start);\n if (end < 0 || end > lastReasonableEscapeIndex) {\n fail(0xc553, 'Invalid encoded resource path', { path });\n }\n\n const next = path.charAt(end + 1);\n switch (next) {\n case encodedSeparatorChar:\n const currentPiece = path.substring(start, end);\n let segment;\n if (segmentBuilder.length === 0) {\n // Avoid copying for the common case of a segment that excludes \\0\n // and \\001\n segment = currentPiece;\n } else {\n segmentBuilder += currentPiece;\n segment = segmentBuilder;\n segmentBuilder = '';\n }\n segments.push(segment);\n break;\n case encodedNul:\n segmentBuilder += path.substring(start, end);\n segmentBuilder += '\\0';\n break;\n case encodedEscape:\n // The escape character can be used in the output to encode itself.\n segmentBuilder += path.substring(start, end + 1);\n break;\n default:\n fail(0xeeef, 'Invalid encoded resource path', { path });\n }\n\n start = end + 2;\n }\n\n return new ResourcePath(segments);\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 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 * Representation of a byte array that is safe for\n * use in an IndexedDb key. The value is either\n * a \"sortable byte string\", which is key safe in\n * Safari/WebKit, or the value is a Uint8Array,\n * which is key safe in other browsers.\n */\nexport type KeySafeBytes = Uint8Array | string;\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 KeySafeBytes,\n KeySafeBytes,\n KeySafeBytes,\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];\nexport const V18_STORES = V17_STORES;\n\n/**\n * The list of all default IndexedDB stores used throughout the SDK. This is\n * used when creating transactions so that access across all stores is done\n * atomically.\n */\nexport const ALL_STORES = V12_STORES;\n\n/** Returns the object stores for the provided schema. */\nexport function getObjectStores(schemaVersion: number): string[] {\n if (schemaVersion === 18) {\n return V18_STORES;\n } else 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(0xeb55, 'Only schema versions >11 are supported');\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 { ListenSequenceNumber } from '../core/types';\nimport { debugCast } from '../util/assert';\n\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDb, SimpleDbStore, SimpleDbTransaction } from './simple_db';\n\nexport class IndexedDbTransaction extends PersistenceTransaction {\n constructor(\n readonly simpleDbTransaction: SimpleDbTransaction,\n readonly currentSequenceNumber: ListenSequenceNumber\n ) {\n super();\n }\n}\n\nexport function getStore(\n txn: PersistenceTransaction,\n store: string\n): SimpleDbStore {\n const indexedDbTransaction = debugCast(txn, IndexedDbTransaction);\n return SimpleDb.getStore(\n indexedDbTransaction.simpleDbTransaction,\n store\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from './assert';\n\nexport interface Dict {\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(0xaad2, 'Red node has red child', {\n key: this.key,\n value: this.value\n });\n }\n if (this.right.isRed()) {\n throw fail(0x3721, 'Right child of (`key`, `value`) is red', {\n key: this.key,\n value: this.value\n });\n }\n const blackDepth = (this.left as LLRBNode).check();\n if (blackDepth !== (this.right as LLRBNode).check()) {\n throw fail(0x6d2d, '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(0xe1a6, 'LLRBEmptyNode has no key.');\n }\n get value(): never {\n throw fail(0x3f0d, 'LLRBEmptyNode has no value.');\n }\n get color(): never {\n throw fail(0x4157, 'LLRBEmptyNode has no color.');\n }\n get left(): never {\n throw fail(0x741e, 'LLRBEmptyNode has no left child.');\n }\n get right(): never {\n throw fail(0x901e, '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 { 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 { 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 { 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, 0x986a, '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, 0xb5de, 'invalid timestamp', {\n timestamp: date\n });\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 readonly isUsingEmulator: 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 {\n arrayEquals,\n compareUtf8Strings,\n primitiveComparator\n} 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(0x6e87, 'Invalid value type', { 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(0xcbf8, 'Unexpected value type', { 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 compareUtf8Strings(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(0x5ae0, '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 = compareUtf8Strings(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(0xee4d, 'Invalid value type', { 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(0x34ae, 'Invalid value type', { 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(0x8c66, 'Invalid value type', { 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(0xf207, 'Invalid value type', { 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(\n 0xa786,\n \"Trying to compare documents on fields that don't exist\"\n );\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 other.nullValue === undefined &&\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(0xb8a2, 'Unknown FieldFilter operator', {\n operator: this.op\n });\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(0x4bef, '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 (\n other !== null &&\n other.nullValue === undefined &&\n !arrayValueContains(this.value.arrayValue!, other)\n );\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(0x4d4e, 'Unknown direction', { 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 0x7f90,\n 'server transform result count should match field transform count',\n {\n serverTransformResultCount: serverTransformResults.length,\n fieldTransformCount: fieldTransforms.length\n }\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 0xe5da,\n 'Mutations sent must equal results received',\n {\n mutationsSent: batch.mutations.length,\n resultsReceived: results.length\n }\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 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 { FieldPath } from '../model/path';\n\n/**\n * Union type representing the aggregate type to be performed.\n */\nexport type AggregateType = 'count' | 'avg' | 'sum';\n\n/**\n * Represents an Aggregate to be performed over a query result set.\n */\nexport interface Aggregate {\n readonly fieldPath?: FieldPath;\n readonly alias: string;\n readonly aggregateType: AggregateType;\n}\n\n/**\n * Concrete implementation of the Aggregate type.\n */\nexport class AggregateImpl implements Aggregate {\n constructor(\n readonly alias: string,\n readonly aggregateType: AggregateType,\n readonly fieldPath?: 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 { 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(0xfdaa, '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(0x3c6b, '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(0x999b, '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(0x3019, '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(0x9481, '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 0x0ca9,\n '`pendingResponses` is less than 0. This indicates that the SDK received more target acks from the server than expected. The SDK should not continue to operate.',\n { pendingResponses: this.pendingResponses }\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 private pendingDocumentUpdatesByTarget = documentTargetMap();\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(0xddd6, 'Unknown target watch change state', {\n state: targetChange.state\n });\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 0x4e2d,\n 'Single document existence filter with count',\n { 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 for this\n // target. This resolves the limbo state of the document, removing it\n // from 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.ensureDocumentUpdateByTarget(key).has(targetId) &&\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.pendingDocumentUpdatesByTarget = documentTargetMap();\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.pendingDocumentUpdatesByTarget =\n this.pendingDocumentUpdatesByTarget.insert(\n document.key,\n this.ensureDocumentUpdateByTarget(document.key).add(targetId)\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 this.pendingDocumentTargetMapping =\n this.pendingDocumentTargetMapping.insert(\n key,\n this.ensureDocumentTargetMapping(key).add(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 private ensureDocumentUpdateByTarget(key: DocumentKey): SortedSet {\n let targetMapping = this.pendingDocumentUpdatesByTarget.get(key);\n\n if (!targetMapping) {\n targetMapping = new SortedSet(primitiveComparator);\n this.pendingDocumentUpdatesByTarget =\n this.pendingDocumentUpdatesByTarget.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\n/**\n * Returns a Timestamp typed object given protobuf timestamp value.\n */\nexport function 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 0xe30b,\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 0x3f41,\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, 0xc050, \"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 0x27ce,\n 'Tried to deserialize invalid key',\n { 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 0x71a3,\n 'tried to deserialize invalid key',\n { 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 0xaa33,\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 0x0f36,\n 'Tried to deserialize a missing document from a found document.'\n );\n hardAssert(\n !!result.readTime,\n 0x5995,\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(0x1c42, 'invalid batch get response', { 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(0x2d51, 'Unknown change type', { 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(0x9991, '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(0x40d7, 'Unknown mutation type', {\n mutationType: mutation.type\n });\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(0x05b7, 'unknown mutation proto', { 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(0x6b69, '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 0x3811,\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(0x51c2, 'Unknown transform', {\n transform: fieldTransform.transform\n });\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 0x40f6,\n 'Unknown server value transform proto',\n { 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(0x40c8, 'Unknown transform proto', { 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 0x07ae,\n 'DocumentsTarget contained other than 1 document',\n {\n count\n }\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 0xfe26,\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(0x713b, '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(0x7591, 'Unknown filter', { 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(0xe2fe, 'Unspecified operator');\n default:\n return fail(0xc54a, '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(0x0402, '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(0xd65d, 'Unrecognized filter type', { 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(0xef81, 'Unspecified filter');\n default:\n return fail(0xed36, '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(0xdd85, '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(0xe230, 'Unexpected Document', { document });\n }\n return remoteDoc;\n}\n\nexport function toDbTimestampKey(\n snapshotVersion: SnapshotVersion\n): DbTimestampKey {\n const timestamp = snapshotVersion.toTimestamp();\n return [timestamp.seconds, timestamp.nanoseconds];\n}\n\nexport function fromDbTimestampKey(\n dbTimestampKey: DbTimestampKey\n): SnapshotVersion {\n const timestamp = new Timestamp(dbTimestampKey[0], dbTimestampKey[1]);\n return SnapshotVersion.fromTimestamp(timestamp);\n}\n\nexport function toDbTimestamp(snapshotVersion: SnapshotVersion): DbTimestamp {\n const timestamp = snapshotVersion.toTimestamp();\n return { seconds: timestamp.seconds, nanoseconds: timestamp.nanoseconds };\n}\n\nfunction fromDbTimestamp(dbTimestamp: DbTimestamp): SnapshotVersion {\n const timestamp = new Timestamp(dbTimestamp.seconds, dbTimestamp.nanoseconds);\n return SnapshotVersion.fromTimestamp(timestamp);\n}\n\n/** Encodes a batch of mutations into a DbMutationBatch for local storage. */\nexport function toDbMutationBatch(\n localSerializer: LocalSerializer,\n userId: string,\n batch: MutationBatch\n): DbMutationBatch {\n const serializedBaseMutations = batch.baseMutations.map(m =>\n toMutation(localSerializer.remoteSerializer, m)\n );\n const serializedMutations = batch.mutations.map(m =>\n toMutation(localSerializer.remoteSerializer, m)\n );\n return {\n userId,\n batchId: batch.batchId,\n localWriteTimeMs: batch.localWriteTime.toMillis(),\n baseMutations: serializedBaseMutations,\n mutations: serializedMutations\n };\n}\n\n/** Decodes a DbMutationBatch into a MutationBatch */\nexport function fromDbMutationBatch(\n localSerializer: LocalSerializer,\n dbBatch: DbMutationBatch\n): MutationBatch {\n const baseMutations = (dbBatch.baseMutations || []).map(m =>\n fromMutation(localSerializer.remoteSerializer, m)\n );\n\n // Squash old transform mutations into existing patch or set mutations.\n // The replacement of representing `transforms` with `update_transforms`\n // on the SDK means that old `transform` mutations stored in IndexedDB need\n // to be updated to `update_transforms`.\n // TODO(b/174608374): Remove this code once we perform a schema migration.\n for (let i = 0; i < dbBatch.mutations.length - 1; ++i) {\n const currentMutation = dbBatch.mutations[i];\n const hasTransform =\n i + 1 < dbBatch.mutations.length &&\n dbBatch.mutations[i + 1].transform !== undefined;\n if (hasTransform) {\n debugAssert(\n dbBatch.mutations[i].transform === undefined &&\n dbBatch.mutations[i].update !== undefined,\n 'TransformMutation should be preceded by a patch or set mutation'\n );\n const transformMutation = dbBatch.mutations[i + 1];\n currentMutation.updateTransforms =\n transformMutation.transform!.fieldTransforms;\n dbBatch.mutations.splice(i + 1, 1);\n ++i;\n }\n }\n\n const mutations = dbBatch.mutations.map(m =>\n fromMutation(localSerializer.remoteSerializer, m)\n );\n const timestamp = Timestamp.fromMillis(dbBatch.localWriteTimeMs);\n return new MutationBatch(\n dbBatch.batchId,\n timestamp,\n baseMutations,\n mutations\n );\n}\n\n/** Decodes a DbTarget into TargetData */\nexport function fromDbTarget(dbTarget: DbTarget): TargetData {\n const version = fromDbTimestamp(dbTarget.readTime);\n const lastLimboFreeSnapshotVersion =\n dbTarget.lastLimboFreeSnapshotVersion !== undefined\n ? fromDbTimestamp(dbTarget.lastLimboFreeSnapshotVersion)\n : SnapshotVersion.min();\n\n let target: Target;\n if (isDocumentQuery(dbTarget.query)) {\n target = fromDocumentsTarget(dbTarget.query);\n } else {\n target = fromQueryTarget(dbTarget.query);\n }\n return new TargetData(\n target,\n dbTarget.targetId,\n TargetPurpose.Listen,\n dbTarget.lastListenSequenceNumber,\n version,\n lastLimboFreeSnapshotVersion,\n ByteString.fromBase64String(dbTarget.resumeToken)\n );\n}\n\n/** Encodes TargetData into a DbTarget for storage locally. */\nexport function toDbTarget(\n localSerializer: LocalSerializer,\n targetData: TargetData\n): DbTarget {\n debugAssert(\n TargetPurpose.Listen === targetData.purpose,\n 'Only queries with purpose ' +\n TargetPurpose.Listen +\n ' may be stored, got ' +\n targetData.purpose\n );\n const dbTimestamp = toDbTimestamp(targetData.snapshotVersion);\n const dbLastLimboFreeTimestamp = toDbTimestamp(\n targetData.lastLimboFreeSnapshotVersion\n );\n let queryProto: DbQuery;\n if (targetIsDocumentTarget(targetData.target)) {\n queryProto = toDocumentsTarget(\n localSerializer.remoteSerializer,\n targetData.target\n );\n } else {\n queryProto = toQueryTarget(\n localSerializer.remoteSerializer,\n targetData.target\n ).queryTarget;\n }\n\n // We can't store the resumeToken as a ByteString in IndexedDb, so we\n // convert it to a base64 string for storage.\n const resumeToken = targetData.resumeToken.toBase64();\n\n // lastListenSequenceNumber is always 0 until we do real GC.\n return {\n targetId: targetData.targetId,\n canonicalId: canonifyTarget(targetData.target),\n readTime: dbTimestamp,\n resumeToken,\n lastListenSequenceNumber: targetData.sequenceNumber,\n lastLimboFreeSnapshotVersion: dbLastLimboFreeTimestamp,\n query: queryProto\n };\n}\n\n/**\n * A helper function for figuring out what kind of query has been stored.\n */\nfunction isDocumentQuery(dbQuery: DbQuery): dbQuery is PublicDocumentsTarget {\n return (dbQuery as PublicDocumentsTarget).documents !== undefined;\n}\n\n/** Encodes a DbBundle to a BundleMetadata object. */\nexport function fromDbBundle(dbBundle: DbBundle): BundleMetadata {\n return {\n id: dbBundle.bundleId,\n createTime: fromDbTimestamp(dbBundle.createTime),\n version: dbBundle.version\n };\n}\n\n/** Encodes a BundleMetadata to a DbBundle. */\nexport function toDbBundle(metadata: ProtoBundleMetadata): DbBundle {\n return {\n bundleId: metadata.id!,\n createTime: toDbTimestamp(fromVersion(metadata.createTime!)),\n version: metadata.version!\n };\n}\n\n/** Encodes a DbNamedQuery to a NamedQuery. */\nexport function fromDbNamedQuery(dbNamedQuery: DbNamedQuery): NamedQuery {\n return {\n name: dbNamedQuery.name,\n query: fromBundledQuery(dbNamedQuery.bundledQuery),\n readTime: fromDbTimestamp(dbNamedQuery.readTime)\n };\n}\n\n/** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */\nexport function toDbNamedQuery(query: ProtoNamedQuery): DbNamedQuery {\n return {\n name: query.name!,\n readTime: toDbTimestamp(fromVersion(query.readTime!)),\n bundledQuery: query.bundledQuery!\n };\n}\n\n/**\n * Encodes a `BundledQuery` from bundle proto to a Query object.\n *\n * This reconstructs the original query used to build the bundle being loaded,\n * including features exists only in SDKs (for example: limit-to-last).\n */\nexport function fromBundledQuery(bundledQuery: ProtoBundledQuery): Query {\n const query = convertQueryTargetToQuery({\n parent: bundledQuery.parent!,\n structuredQuery: bundledQuery.structuredQuery!\n });\n if (bundledQuery.limitType === 'LAST') {\n debugAssert(\n !!query.limit,\n 'Bundled query has limitType LAST, but limit is null'\n );\n return queryWithLimit(query, query.limit, LimitType.Last);\n }\n return query;\n}\n\n/** Encodes a NamedQuery proto object to a NamedQuery model object. */\nexport function fromProtoNamedQuery(namedQuery: ProtoNamedQuery): NamedQuery {\n return {\n name: namedQuery.name!,\n query: fromBundledQuery(namedQuery.bundledQuery!),\n readTime: fromVersion(namedQuery.readTime!)\n };\n}\n\n/** Decodes a BundleMetadata proto into a BundleMetadata object. */\nexport function fromBundleMetadata(\n metadata: ProtoBundleMetadata\n): BundleMetadata {\n return {\n id: metadata.id!,\n version: metadata.version!,\n createTime: fromVersion(metadata.createTime!)\n };\n}\n\n/** Encodes a DbDocumentOverlay object to an Overlay model object. */\nexport function fromDbDocumentOverlay(\n localSerializer: LocalSerializer,\n dbDocumentOverlay: DbDocumentOverlay\n): Overlay {\n return new Overlay(\n dbDocumentOverlay.largestBatchId,\n fromMutation(\n localSerializer.remoteSerializer,\n dbDocumentOverlay.overlayMutation\n )\n );\n}\n\n/** Decodes an Overlay model object into a DbDocumentOverlay object. */\nexport function toDbDocumentOverlay(\n localSerializer: LocalSerializer,\n userId: string,\n overlay: Overlay\n): DbDocumentOverlay {\n const [_, collectionPath, documentId] = toDbDocumentOverlayKey(\n userId,\n overlay.mutation.key\n );\n return {\n userId,\n collectionPath,\n documentId,\n collectionGroup: overlay.mutation.key.getCollectionGroup(),\n largestBatchId: overlay.largestBatchId,\n overlayMutation: toMutation(\n localSerializer.remoteSerializer,\n overlay.mutation\n )\n };\n}\n\n/**\n * Returns the DbDocumentOverlayKey corresponding to the given user and\n * document key.\n */\nexport function toDbDocumentOverlayKey(\n userId: string,\n docKey: DocumentKey\n): DbDocumentOverlayKey {\n const docId = docKey.path.lastSegment();\n const collectionPath = encodeResourcePath(docKey.path.popLast());\n return [userId, collectionPath, docId];\n}\n\nexport function toDbIndexConfiguration(\n index: FieldIndex\n): DbIndexConfiguration {\n return {\n indexId: index.indexId,\n collectionGroup: index.collectionGroup,\n fields: index.fields.map(s => [s.fieldPath.canonicalString(), s.kind])\n };\n}\n\nexport function fromDbIndexConfiguration(\n index: DbIndexConfiguration,\n state: DbIndexState | null\n): FieldIndex {\n const decodedState = state\n ? new IndexState(\n state.sequenceNumber,\n new IndexOffset(\n fromDbTimestamp(state.readTime),\n new DocumentKey(decodeResourcePath(state.documentKey)),\n state.largestBatchId\n )\n )\n : IndexState.empty();\n const decodedSegments = index.fields.map(\n ([fieldPath, kind]) =>\n new IndexSegment(FieldPath.fromServerFormat(fieldPath), kind)\n );\n return new FieldIndex(\n index.indexId!,\n index.collectionGroup,\n decodedSegments,\n decodedState\n );\n}\n\nexport function toDbIndexState(\n indexId: number,\n uid: string,\n sequenceNumber: number,\n offset: IndexOffset\n): DbIndexState {\n return {\n indexId,\n uid,\n sequenceNumber,\n readTime: toDbTimestamp(offset.readTime),\n documentKey: encodeResourcePath(offset.documentKey.path),\n largestBatchId: offset.largestBatchId\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BundleMetadata, NamedQuery } from '../core/bundle';\nimport {\n BundleMetadata as ProtoBundleMetadata,\n NamedQuery as ProtoNamedQuery\n} from '../protos/firestore_bundle_proto';\n\nimport { BundleCache } from './bundle_cache';\nimport { DbBundle, DbNamedQuery } from './indexeddb_schema';\nimport {\n DbBundlesKey,\n DbBundleStore,\n DbNamedQueriesKey,\n DbNamedQueryStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n fromDbBundle,\n fromDbNamedQuery,\n toDbBundle,\n toDbNamedQuery\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\nexport class IndexedDbBundleCache implements BundleCache {\n getBundleMetadata(\n transaction: PersistenceTransaction,\n bundleId: string\n ): PersistencePromise {\n return bundlesStore(transaction)\n .get(bundleId)\n .next(bundle => {\n if (bundle) {\n return fromDbBundle(bundle);\n }\n return undefined;\n });\n }\n\n saveBundleMetadata(\n transaction: PersistenceTransaction,\n bundleMetadata: ProtoBundleMetadata\n ): PersistencePromise {\n return bundlesStore(transaction).put(toDbBundle(bundleMetadata));\n }\n\n getNamedQuery(\n transaction: PersistenceTransaction,\n queryName: string\n ): PersistencePromise {\n return namedQueriesStore(transaction)\n .get(queryName)\n .next(query => {\n if (query) {\n return fromDbNamedQuery(query);\n }\n return undefined;\n });\n }\n\n saveNamedQuery(\n transaction: PersistenceTransaction,\n query: ProtoNamedQuery\n ): PersistencePromise {\n return namedQueriesStore(transaction).put(toDbNamedQuery(query));\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the bundles object store.\n */\nfunction bundlesStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbBundleStore);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the namedQueries object store.\n */\nfunction namedQueriesStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbNamedQueryStore);\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport {\n DocumentKeySet,\n MutationMap,\n OverlayMap,\n newOverlayMap\n} from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { Overlay } from '../model/overlay';\nimport { ResourcePath } from '../model/path';\n\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { encodeResourcePath } from './encoded_resource_path';\nimport { DbDocumentOverlay } from './indexeddb_schema';\nimport {\n DbDocumentOverlayCollectionGroupOverlayIndex,\n DbDocumentOverlayCollectionPathOverlayIndex,\n DbDocumentOverlayKey,\n DbDocumentOverlayStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n fromDbDocumentOverlay,\n LocalSerializer,\n toDbDocumentOverlay,\n toDbDocumentOverlayKey\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\n/**\n * Implementation of DocumentOverlayCache using IndexedDb.\n */\nexport class IndexedDbDocumentOverlayCache implements DocumentOverlayCache {\n /**\n * @param serializer - The document serializer.\n * @param userId - The userId for which we are accessing overlays.\n */\n constructor(\n private readonly serializer: LocalSerializer,\n private readonly userId: string\n ) {}\n\n static forUser(\n serializer: LocalSerializer,\n user: User\n ): IndexedDbDocumentOverlayCache {\n const userId = user.uid || '';\n return new IndexedDbDocumentOverlayCache(serializer, userId);\n }\n\n getOverlay(\n transaction: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return documentOverlayStore(transaction)\n .get(toDbDocumentOverlayKey(this.userId, key))\n .next(dbOverlay => {\n if (dbOverlay) {\n return fromDbDocumentOverlay(this.serializer, dbOverlay);\n }\n return null;\n });\n }\n\n getOverlays(\n transaction: PersistenceTransaction,\n keys: DocumentKey[]\n ): PersistencePromise {\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 const promises: Array> = [];\n overlays.forEach((_, mutation) => {\n const overlay = new Overlay(largestBatchId, mutation);\n promises.push(this.saveOverlay(transaction, overlay));\n });\n return PersistencePromise.waitFor(promises);\n }\n\n removeOverlaysForBatchId(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet,\n batchId: number\n ): PersistencePromise {\n const collectionPaths = new Set();\n\n // Get the set of unique collection paths.\n documentKeys.forEach(key =>\n collectionPaths.add(encodeResourcePath(key.getCollectionPath()))\n );\n\n const promises: Array> = [];\n collectionPaths.forEach(collectionPath => {\n const range = IDBKeyRange.bound(\n [this.userId, collectionPath, batchId],\n [this.userId, collectionPath, batchId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n promises.push(\n documentOverlayStore(transaction).deleteAll(\n DbDocumentOverlayCollectionPathOverlayIndex,\n range\n )\n );\n });\n return PersistencePromise.waitFor(promises);\n }\n\n getOverlaysForCollection(\n transaction: PersistenceTransaction,\n collection: ResourcePath,\n sinceBatchId: number\n ): PersistencePromise {\n const result = newOverlayMap();\n const collectionPath = encodeResourcePath(collection);\n // We want batch IDs larger than `sinceBatchId`, and so the lower bound\n // is not inclusive.\n const range = IDBKeyRange.bound(\n [this.userId, collectionPath, sinceBatchId],\n [this.userId, collectionPath, Number.POSITIVE_INFINITY],\n /*lowerOpen=*/ true\n );\n return documentOverlayStore(transaction)\n .loadAll(DbDocumentOverlayCollectionPathOverlayIndex, range)\n .next(dbOverlays => {\n for (const dbOverlay of dbOverlays) {\n const overlay = fromDbDocumentOverlay(this.serializer, dbOverlay);\n result.set(overlay.getKey(), overlay);\n }\n return result;\n });\n }\n\n getOverlaysForCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n sinceBatchId: number,\n count: number\n ): PersistencePromise {\n const result = newOverlayMap();\n let currentBatchId: number | undefined = undefined;\n // We want batch IDs larger than `sinceBatchId`, and so the lower bound\n // is not inclusive.\n const range = IDBKeyRange.bound(\n [this.userId, collectionGroup, sinceBatchId],\n [this.userId, collectionGroup, Number.POSITIVE_INFINITY],\n /*lowerOpen=*/ true\n );\n return documentOverlayStore(transaction)\n .iterate(\n {\n index: DbDocumentOverlayCollectionGroupOverlayIndex,\n range\n },\n (_, dbOverlay, control) => {\n // We do not want to return partial batch overlays, even if the size\n // of the result set exceeds the given `count` argument. Therefore, we\n // continue to aggregate results even after the result size exceeds\n // `count` if there are more overlays from the `currentBatchId`.\n const overlay = fromDbDocumentOverlay(this.serializer, dbOverlay);\n if (\n result.size() < count ||\n overlay.largestBatchId === currentBatchId\n ) {\n result.set(overlay.getKey(), overlay);\n currentBatchId = overlay.largestBatchId;\n } else {\n control.done();\n }\n }\n )\n .next(() => result);\n }\n\n private saveOverlay(\n transaction: PersistenceTransaction,\n overlay: Overlay\n ): PersistencePromise {\n return documentOverlayStore(transaction).put(\n toDbDocumentOverlay(this.serializer, this.userId, overlay)\n );\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document overlay object store.\n */\nfunction documentOverlayStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbDocumentOverlayStore\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 { DbGlobals } from './indexeddb_schema';\nimport { DbGlobalsStore, DbGlobalsKey } from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\nexport class IndexedDbGlobalsCache implements GlobalsCache {\n private globalsStore(\n txn: PersistenceTransaction\n ): SimpleDbStore {\n return getStore(txn, DbGlobalsStore);\n }\n\n getSessionToken(txn: PersistenceTransaction): PersistencePromise {\n const globals = this.globalsStore(txn);\n return globals.get('sessionToken').next(global => {\n const value = global?.value;\n return value\n ? ByteString.fromUint8Array(value)\n : ByteString.EMPTY_BYTE_STRING;\n });\n }\n\n setSessionToken(\n txn: PersistenceTransaction,\n sessionToken: ByteString\n ): PersistencePromise {\n const globals = this.globalsStore(txn);\n return globals.put({\n name: 'sessionToken',\n value: sessionToken.toUint8Array()\n });\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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(0x4a4e, '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 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law | agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES | CONDITIONS OF ANY KIND, either express | implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { debugAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\n\n/** These constants are taken from the backend. */\nconst MIN_SURROGATE = '\\uD800';\nconst MAX_SURROGATE = '\\uDBFF';\n\nconst ESCAPE1 = 0x00;\nconst NULL_BYTE = 0xff; // Combined with ESCAPE1\nconst SEPARATOR = 0x01; // Combined with ESCAPE1\n\nconst ESCAPE2 = 0xff;\nconst INFINITY = 0xff; // Combined with ESCAPE2\nconst FF_BYTE = 0x00; // Combined with ESCAPE2\n\nconst LONG_SIZE = 64;\nconst BYTE_SIZE = 8;\n\n/**\n * The default size of the buffer. This is arbitrary, but likely larger than\n * most index values so that less copies of the underlying buffer will be made.\n * For large values, a single copy will made to double the buffer length.\n */\nconst DEFAULT_BUFFER_SIZE = 1024;\n\n/** Converts a JavaScript number to a byte array (using big endian encoding). */\nfunction doubleToLongBits(value: number): Uint8Array {\n const dv = new DataView(new ArrayBuffer(8));\n dv.setFloat64(0, value, /* littleEndian= */ false);\n return new Uint8Array(dv.buffer);\n}\n\n/**\n * Counts the number of zeros in a byte.\n *\n * Visible for testing.\n */\nexport function numberOfLeadingZerosInByte(x: number): number {\n debugAssert(x < 256, 'Provided value is not a byte: ' + x);\n if (x === 0) {\n return 8;\n }\n\n let zeros = 0;\n if (x >> 4 === 0) {\n // Test if the first four bits are zero.\n zeros += 4;\n x = x << 4;\n }\n if (x >> 6 === 0) {\n // Test if the first two (or next two) bits are zero.\n zeros += 2;\n x = x << 2;\n }\n if (x >> 7 === 0) {\n // Test if the remaining bit is zero.\n zeros += 1;\n }\n return zeros;\n}\n\n/** Counts the number of leading zeros in the given byte array. */\nfunction numberOfLeadingZeros(bytes: Uint8Array): number {\n debugAssert(\n bytes.length === 8,\n 'Can only count leading zeros in 64-bit numbers'\n );\n let leadingZeros = 0;\n for (let i = 0; i < 8; ++i) {\n const zeros = numberOfLeadingZerosInByte(bytes[i] & 0xff);\n leadingZeros += zeros;\n if (zeros !== 8) {\n break;\n }\n }\n return leadingZeros;\n}\n\n/**\n * Returns the number of bytes required to store \"value\". Leading zero bytes\n * are skipped.\n */\nfunction unsignedNumLength(value: Uint8Array): number {\n // This is just the number of bytes for the unsigned representation of the number.\n const numBits = LONG_SIZE - numberOfLeadingZeros(value);\n return Math.ceil(numBits / BYTE_SIZE);\n}\n\n/**\n * OrderedCodeWriter is a minimal-allocation implementation of the writing\n * behavior defined by the backend.\n *\n * The code is ported from its Java counterpart.\n */\nexport class OrderedCodeWriter {\n buffer = new Uint8Array(DEFAULT_BUFFER_SIZE);\n position = 0;\n\n writeBytesAscending(value: ByteString): void {\n const it = value[Symbol.iterator]();\n let byte = it.next();\n while (!byte.done) {\n this.writeByteAscending(byte.value);\n byte = it.next();\n }\n this.writeSeparatorAscending();\n }\n\n writeBytesDescending(value: ByteString): void {\n const it = value[Symbol.iterator]();\n let byte = it.next();\n while (!byte.done) {\n this.writeByteDescending(byte.value);\n byte = it.next();\n }\n this.writeSeparatorDescending();\n }\n\n /** Writes utf8 bytes into this byte sequence, ascending. */\n writeUtf8Ascending(sequence: string): void {\n for (const c of sequence) {\n const charCode = c.charCodeAt(0);\n if (charCode < 0x80) {\n this.writeByteAscending(charCode);\n } else if (charCode < 0x800) {\n this.writeByteAscending((0x0f << 6) | (charCode >>> 6));\n this.writeByteAscending(0x80 | (0x3f & charCode));\n } else if (c < MIN_SURROGATE || MAX_SURROGATE < c) {\n this.writeByteAscending((0x0f << 5) | (charCode >>> 12));\n this.writeByteAscending(0x80 | (0x3f & (charCode >>> 6)));\n this.writeByteAscending(0x80 | (0x3f & charCode));\n } else {\n const codePoint = c.codePointAt(0)!;\n this.writeByteAscending((0x0f << 4) | (codePoint >>> 18));\n this.writeByteAscending(0x80 | (0x3f & (codePoint >>> 12)));\n this.writeByteAscending(0x80 | (0x3f & (codePoint >>> 6)));\n this.writeByteAscending(0x80 | (0x3f & codePoint));\n }\n }\n this.writeSeparatorAscending();\n }\n\n /** Writes utf8 bytes into this byte sequence, descending */\n writeUtf8Descending(sequence: string): void {\n for (const c of sequence) {\n const charCode = c.charCodeAt(0);\n if (charCode < 0x80) {\n this.writeByteDescending(charCode);\n } else if (charCode < 0x800) {\n this.writeByteDescending((0x0f << 6) | (charCode >>> 6));\n this.writeByteDescending(0x80 | (0x3f & charCode));\n } else if (c < MIN_SURROGATE || MAX_SURROGATE < c) {\n this.writeByteDescending((0x0f << 5) | (charCode >>> 12));\n this.writeByteDescending(0x80 | (0x3f & (charCode >>> 6)));\n this.writeByteDescending(0x80 | (0x3f & charCode));\n } else {\n const codePoint = c.codePointAt(0)!;\n this.writeByteDescending((0x0f << 4) | (codePoint >>> 18));\n this.writeByteDescending(0x80 | (0x3f & (codePoint >>> 12)));\n this.writeByteDescending(0x80 | (0x3f & (codePoint >>> 6)));\n this.writeByteDescending(0x80 | (0x3f & codePoint));\n }\n }\n this.writeSeparatorDescending();\n }\n\n writeNumberAscending(val: number): void {\n // Values are encoded with a single byte length prefix, followed by the\n // actual value in big-endian format with leading 0 bytes dropped.\n const value = this.toOrderedBits(val);\n const len = unsignedNumLength(value);\n this.ensureAvailable(1 + len);\n this.buffer[this.position++] = len & 0xff; // Write the length\n for (let i = value.length - len; i < value.length; ++i) {\n this.buffer[this.position++] = value[i] & 0xff;\n }\n }\n\n writeNumberDescending(val: number): void {\n // Values are encoded with a single byte length prefix, followed by the\n // inverted value in big-endian format with leading 0 bytes dropped.\n const value = this.toOrderedBits(val);\n const len = unsignedNumLength(value);\n this.ensureAvailable(1 + len);\n this.buffer[this.position++] = ~(len & 0xff); // Write the length\n for (let i = value.length - len; i < value.length; ++i) {\n this.buffer[this.position++] = ~(value[i] & 0xff);\n }\n }\n\n /**\n * Writes the \"infinity\" byte sequence that sorts after all other byte\n * sequences written in ascending order.\n */\n writeInfinityAscending(): void {\n this.writeEscapedByteAscending(ESCAPE2);\n this.writeEscapedByteAscending(INFINITY);\n }\n\n /**\n * Writes the \"infinity\" byte sequence that sorts before all other byte\n * sequences written in descending order.\n */\n writeInfinityDescending(): void {\n this.writeEscapedByteDescending(ESCAPE2);\n this.writeEscapedByteDescending(INFINITY);\n }\n\n /**\n * Resets the buffer such that it is the same as when it was newly\n * constructed.\n */\n reset(): void {\n this.position = 0;\n }\n\n seed(encodedBytes: Uint8Array): void {\n this.ensureAvailable(encodedBytes.length);\n this.buffer.set(encodedBytes, this.position);\n this.position += encodedBytes.length;\n }\n\n /** Makes a copy of the encoded bytes in this buffer. */\n encodedBytes(): Uint8Array {\n return this.buffer.slice(0, this.position);\n }\n\n /**\n * Encodes `val` into an encoding so that the order matches the IEEE 754\n * floating-point comparison results with the following exceptions:\n * -0.0 < 0.0\n * all non-NaN < NaN\n * NaN = NaN\n */\n private toOrderedBits(val: number): Uint8Array {\n const value = doubleToLongBits(val);\n // Check if the first bit is set. We use a bit mask since value[0] is\n // encoded as a number from 0 to 255.\n const isNegative = (value[0] & 0x80) !== 0;\n\n // Revert the two complement to get natural ordering\n value[0] ^= isNegative ? 0xff : 0x80;\n for (let i = 1; i < value.length; ++i) {\n value[i] ^= isNegative ? 0xff : 0x00;\n }\n return value;\n }\n\n /** Writes a single byte ascending to the buffer. */\n private writeByteAscending(b: number): void {\n const masked = b & 0xff;\n if (masked === ESCAPE1) {\n this.writeEscapedByteAscending(ESCAPE1);\n this.writeEscapedByteAscending(NULL_BYTE);\n } else if (masked === ESCAPE2) {\n this.writeEscapedByteAscending(ESCAPE2);\n this.writeEscapedByteAscending(FF_BYTE);\n } else {\n this.writeEscapedByteAscending(masked);\n }\n }\n\n /** Writes a single byte descending to the buffer. */\n private writeByteDescending(b: number): void {\n const masked = b & 0xff;\n if (masked === ESCAPE1) {\n this.writeEscapedByteDescending(ESCAPE1);\n this.writeEscapedByteDescending(NULL_BYTE);\n } else if (masked === ESCAPE2) {\n this.writeEscapedByteDescending(ESCAPE2);\n this.writeEscapedByteDescending(FF_BYTE);\n } else {\n this.writeEscapedByteDescending(b);\n }\n }\n\n private writeSeparatorAscending(): void {\n this.writeEscapedByteAscending(ESCAPE1);\n this.writeEscapedByteAscending(SEPARATOR);\n }\n\n private writeSeparatorDescending(): void {\n this.writeEscapedByteDescending(ESCAPE1);\n this.writeEscapedByteDescending(SEPARATOR);\n }\n\n private writeEscapedByteAscending(b: number): void {\n this.ensureAvailable(1);\n this.buffer[this.position++] = b;\n }\n\n private writeEscapedByteDescending(b: number): void {\n this.ensureAvailable(1);\n this.buffer[this.position++] = ~b;\n }\n\n private ensureAvailable(bytes: number): void {\n const minCapacity = bytes + this.position;\n if (minCapacity <= this.buffer.length) {\n return;\n }\n // Try doubling.\n let newLength = this.buffer.length * 2;\n // Still not big enough? Just allocate the right size.\n if (newLength < minCapacity) {\n newLength = minCapacity;\n }\n // Create the new buffer.\n const newBuffer = new Uint8Array(newLength);\n newBuffer.set(this.buffer); // copy old data\n this.buffer = newBuffer;\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { IndexKind } from '../model/field_index';\nimport { ByteString } from '../util/byte_string';\n\nimport { DirectionalIndexByteEncoder } from './directional_index_byte_encoder';\nimport { OrderedCodeWriter } from './ordered_code_writer';\n\nclass AscendingIndexByteEncoder implements DirectionalIndexByteEncoder {\n constructor(private orderedCode: OrderedCodeWriter) {}\n writeBytes(value: ByteString): void {\n this.orderedCode.writeBytesAscending(value);\n }\n\n writeString(value: string): void {\n this.orderedCode.writeUtf8Ascending(value);\n }\n\n writeNumber(value: number): void {\n this.orderedCode.writeNumberAscending(value);\n }\n\n writeInfinity(): void {\n this.orderedCode.writeInfinityAscending();\n }\n}\n\nclass DescendingIndexByteEncoder implements DirectionalIndexByteEncoder {\n constructor(private orderedCode: OrderedCodeWriter) {}\n writeBytes(value: ByteString): void {\n this.orderedCode.writeBytesDescending(value);\n }\n\n writeString(value: string): void {\n this.orderedCode.writeUtf8Descending(value);\n }\n\n writeNumber(value: number): void {\n this.orderedCode.writeNumberDescending(value);\n }\n\n writeInfinity(): void {\n this.orderedCode.writeInfinityDescending();\n }\n}\n/**\n * Implements `DirectionalIndexByteEncoder` using `OrderedCodeWriter` for the\n * actual encoding.\n */\nexport class IndexByteEncoder {\n private orderedCode = new OrderedCodeWriter();\n private ascending = new AscendingIndexByteEncoder(this.orderedCode);\n private descending = new DescendingIndexByteEncoder(this.orderedCode);\n\n seed(encodedBytes: Uint8Array): void {\n this.orderedCode.seed(encodedBytes);\n }\n\n forKind(kind: IndexKind): DirectionalIndexByteEncoder {\n return kind === IndexKind.ASCENDING ? this.ascending : this.descending;\n }\n\n encodedBytes(): Uint8Array {\n return this.orderedCode.encodedBytes();\n }\n\n reset(): void {\n this.orderedCode.reset();\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isSafariOrWebkit } from '@firebase/util';\n\nimport { DbIndexEntry } from '../local/indexeddb_schema';\nimport { DbIndexEntryKey, KeySafeBytes } from '../local/indexeddb_sentinels';\nimport { DocumentKey } from '../model/document_key';\n\n/** Represents an index entry saved by the SDK in persisted storage. */\nexport class IndexEntry {\n constructor(\n readonly _indexId: number,\n readonly _documentKey: DocumentKey,\n readonly _arrayValue: Uint8Array,\n readonly _directionalValue: Uint8Array\n ) {}\n\n /**\n * Returns an IndexEntry entry that sorts immediately after the current\n * directional value.\n */\n successor(): IndexEntry {\n const currentLength = this._directionalValue.length;\n const newLength =\n currentLength === 0 || this._directionalValue[currentLength - 1] === 255\n ? currentLength + 1\n : currentLength;\n\n const successor = new Uint8Array(newLength);\n successor.set(this._directionalValue, 0);\n if (newLength !== currentLength) {\n successor.set([0], this._directionalValue.length);\n } else {\n ++successor[successor.length - 1];\n }\n\n return new IndexEntry(\n this._indexId,\n this._documentKey,\n this._arrayValue,\n successor\n );\n }\n\n // Create a representation of the Index Entry as a DbIndexEntry\n dbIndexEntry(\n uid: string,\n orderedDocumentKey: Uint8Array,\n documentKey: DocumentKey\n ): DbIndexEntry {\n return {\n indexId: this._indexId,\n uid,\n arrayValue: encodeKeySafeBytes(this._arrayValue),\n directionalValue: encodeKeySafeBytes(this._directionalValue),\n orderedDocumentKey: encodeKeySafeBytes(orderedDocumentKey),\n documentKey: documentKey.path.toArray()\n };\n }\n\n // Create a representation of the Index Entry as a DbIndexEntryKey\n dbIndexEntryKey(\n uid: string,\n orderedDocumentKey: Uint8Array,\n documentKey: DocumentKey\n ): DbIndexEntryKey {\n const entry = this.dbIndexEntry(uid, orderedDocumentKey, documentKey);\n return [\n entry.indexId,\n entry.uid,\n entry.arrayValue,\n entry.directionalValue,\n entry.orderedDocumentKey,\n entry.documentKey\n ];\n }\n}\n\nexport function indexEntryComparator(\n left: IndexEntry,\n right: IndexEntry\n): number {\n let cmp = left._indexId - right._indexId;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = compareByteArrays(left._arrayValue, right._arrayValue);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = compareByteArrays(left._directionalValue, right._directionalValue);\n if (cmp !== 0) {\n return cmp;\n }\n\n return DocumentKey.comparator(left._documentKey, right._documentKey);\n}\n\nexport function compareByteArrays(left: Uint8Array, right: Uint8Array): number {\n for (let i = 0; i < left.length && i < right.length; ++i) {\n const compare = left[i] - right[i];\n if (compare !== 0) {\n return compare;\n }\n }\n return left.length - right.length;\n}\n\n/**\n * Workaround for WebKit bug: https://bugs.webkit.org/show_bug.cgi?id=292721\n * Create a key safe representation of Uint8Array values.\n * If the browser is detected as Safari or WebKit, then\n * the input array will be converted to \"sortable byte string\".\n * Otherwise, the input array will be returned in its original type.\n */\nexport function encodeKeySafeBytes(array: Uint8Array): KeySafeBytes {\n if (isSafariOrWebkit()) {\n return encodeUint8ArrayToSortableString(array);\n }\n return array;\n}\n\n/**\n * Reverts the key safe representation of Uint8Array (created by\n * encodeKeySafeBytes) to a normal Uint8Array.\n */\nexport function decodeKeySafeBytes(input: KeySafeBytes): Uint8Array {\n if (typeof input !== 'string') {\n return input;\n }\n return decodeSortableStringToUint8Array(input);\n}\n\n/**\n * Encodes a Uint8Array into a \"sortable byte string\".\n * A \"sortable byte string\" sorts in the same order as the Uint8Array.\n * This works because JS string comparison sorts strings based on code points.\n */\nfunction encodeUint8ArrayToSortableString(array: Uint8Array): string {\n let byteString = '';\n for (let i = 0; i < array.length; i++) {\n byteString += String.fromCharCode(array[i]);\n }\n\n return byteString;\n}\n\n/**\n * Decodes a \"sortable byte string\" back into a Uint8Array.\n * A \"sortable byte string\" is assumed to be created where each character's\n * Unicode code point directly corresponds to a single byte value (0-255).\n */\nfunction decodeSortableStringToUint8Array(byteString: string): Uint8Array {\n const uint8array = new Uint8Array(byteString.length);\n\n for (let i = 0; i < byteString.length; i++) {\n uint8array[i] = byteString.charCodeAt(i);\n }\n\n return uint8array;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldFilter, Operator } from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport { Target } from '../core/target';\nimport { hardAssert } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport {\n FieldIndex,\n fieldIndexGetArraySegment,\n fieldIndexGetDirectionalSegments,\n IndexKind,\n IndexSegment,\n IndexState\n} from './field_index';\nimport { FieldPath } from './path';\n\n/**\n * A light query planner for Firestore.\n *\n * This class matches a `FieldIndex` against a Firestore Query `Target`. It\n * determines whether a given index can be used to serve the specified target.\n *\n * The following table showcases some possible index configurations:\n *\n * Query | Index\n * -----------------------------------------------------------------------------\n * where('a', '==', 'a').where('b', '==', 'b') | a ASC, b DESC\n * where('a', '==', 'a').where('b', '==', 'b') | a ASC\n * where('a', '==', 'a').where('b', '==', 'b') | b DESC\n * where('a', '>=', 'a').orderBy('a') | a ASC\n * where('a', '>=', 'a').orderBy('a', 'desc') | a DESC\n * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC, b ASC\n * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC\n * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS, b ASCENDING\n * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS\n */\nexport class TargetIndexMatcher {\n // The collection ID (or collection group) of the query target.\n private readonly collectionId: string;\n // The inequality filters of the target (if it exists).\n // Note: The sort on FieldFilters is not required. Using SortedSet here just to utilize the custom\n // comparator.\n private inequalityFilters = new SortedSet((lhs, rhs) =>\n FieldPath.comparator(lhs.field, rhs.field)\n );\n\n // The list of equality filters of the target.\n private readonly equalityFilters: FieldFilter[];\n // The list of orderBys of the target.\n private readonly orderBys: OrderBy[];\n\n constructor(target: Target) {\n this.collectionId =\n target.collectionGroup != null\n ? target.collectionGroup\n : target.path.lastSegment();\n this.orderBys = target.orderBy;\n this.equalityFilters = [];\n for (const filter of target.filters) {\n const fieldFilter = filter as FieldFilter;\n if (fieldFilter.isInequality()) {\n this.inequalityFilters = this.inequalityFilters.add(fieldFilter);\n } else {\n this.equalityFilters.push(fieldFilter);\n }\n }\n }\n\n get hasMultipleInequality(): boolean {\n return this.inequalityFilters.size > 1;\n }\n\n /**\n * Returns whether the index can be used to serve the TargetIndexMatcher's\n * target.\n *\n * An index is considered capable of serving the target when:\n * - The target uses all index segments for its filters and orderBy clauses.\n * The target can have additional filter and orderBy clauses, but not\n * fewer.\n * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also\n * have a corresponding `CONTAINS` segment.\n * - All directional index segments can be mapped to the target as a series of\n * equality filters, a single inequality filter and a series of orderBy\n * clauses.\n * - The segments that represent the equality filters may appear out of order.\n * - The optional segment for the inequality filter must appear after all\n * equality segments.\n * - The segments that represent that orderBy clause of the target must appear\n * in order after all equality and inequality segments. Single orderBy\n * clauses cannot be skipped, but a continuous orderBy suffix may be\n * omitted.\n */\n servedByIndex(index: FieldIndex): boolean {\n hardAssert(\n index.collectionGroup === this.collectionId,\n 0xc07f,\n 'Collection IDs do not match'\n );\n\n if (this.hasMultipleInequality) {\n // Only single inequality is supported for now.\n // TODO(Add support for multiple inequality query): b/298441043\n return false;\n }\n\n // If there is an array element, find a matching filter.\n const arraySegment = fieldIndexGetArraySegment(index);\n if (\n arraySegment !== undefined &&\n !this.hasMatchingEqualityFilter(arraySegment)\n ) {\n return false;\n }\n\n const segments = fieldIndexGetDirectionalSegments(index);\n let equalitySegments = new Set();\n let segmentIndex = 0;\n let orderBysIndex = 0;\n\n // Process all equalities first. Equalities can appear out of order.\n for (; segmentIndex < segments.length; ++segmentIndex) {\n // We attempt to greedily match all segments to equality filters. If a\n // filter matches an index segment, we can mark the segment as used.\n if (this.hasMatchingEqualityFilter(segments[segmentIndex])) {\n equalitySegments = equalitySegments.add(\n segments[segmentIndex].fieldPath.canonicalString()\n );\n } else {\n // If we cannot find a matching filter, we need to verify whether the\n // remaining segments map to the target's inequality and its orderBy\n // clauses.\n break;\n }\n }\n\n // If we already have processed all segments, all segments are used to serve\n // the equality filters and we do not need to map any segments to the\n // target's inequality and orderBy clauses.\n if (segmentIndex === segments.length) {\n return true;\n }\n\n if (this.inequalityFilters.size > 0) {\n // Only a single inequality is currently supported. Get the only entry in the set.\n const inequalityFilter = this.inequalityFilters.getIterator().getNext();\n // If there is an inequality filter and the field was not in one of the\n // equality filters above, the next segment must match both the filter\n // and the first orderBy clause.\n if (!equalitySegments.has(inequalityFilter.field.canonicalString())) {\n const segment = segments[segmentIndex];\n\n if (\n !this.matchesFilter(inequalityFilter, segment) ||\n !this.matchesOrderBy(this.orderBys[orderBysIndex++], segment)\n ) {\n return false;\n }\n }\n\n ++segmentIndex;\n }\n\n // All remaining segments need to represent the prefix of the target's\n // orderBy.\n for (; segmentIndex < segments.length; ++segmentIndex) {\n const segment = segments[segmentIndex];\n if (\n orderBysIndex >= this.orderBys.length ||\n !this.matchesOrderBy(this.orderBys[orderBysIndex++], segment)\n ) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Returns a full matched field index for this target. Currently multiple\n * inequality query is not supported so function returns null.\n */\n buildTargetIndex(): FieldIndex | null {\n if (this.hasMultipleInequality) {\n return null;\n }\n\n // We want to make sure only one segment created for one field. For example,\n // in case like a == 3 and a > 2, Index {a ASCENDING} will only be created\n // once.\n let uniqueFields = new SortedSet(FieldPath.comparator);\n const segments: IndexSegment[] = [];\n\n for (const filter of this.equalityFilters) {\n if (filter.field.isKeyField()) {\n continue;\n }\n const isArrayOperator =\n filter.op === Operator.ARRAY_CONTAINS ||\n filter.op === Operator.ARRAY_CONTAINS_ANY;\n if (isArrayOperator) {\n segments.push(new IndexSegment(filter.field, IndexKind.CONTAINS));\n } else {\n if (uniqueFields.has(filter.field)) {\n continue;\n }\n uniqueFields = uniqueFields.add(filter.field);\n segments.push(new IndexSegment(filter.field, IndexKind.ASCENDING));\n }\n }\n\n // Note: We do not explicitly check `this.inequalityFilter` but rather rely\n // on the target defining an appropriate \"order by\" to ensure that the\n // required index segment is added. The query engine would reject a query\n // with an inequality filter that lacks the required order-by clause.\n for (const orderBy of this.orderBys) {\n // Stop adding more segments if we see a order-by on key. Typically this\n // is the default implicit order-by which is covered in the index_entry\n // table as a separate column. If it is not the default order-by, the\n // generated index will be missing some segments optimized for order-bys,\n // which is probably fine.\n if (orderBy.field.isKeyField()) {\n continue;\n }\n\n if (uniqueFields.has(orderBy.field)) {\n continue;\n }\n uniqueFields = uniqueFields.add(orderBy.field);\n\n segments.push(\n new IndexSegment(\n orderBy.field,\n orderBy.dir === Direction.ASCENDING\n ? IndexKind.ASCENDING\n : IndexKind.DESCENDING\n )\n );\n }\n\n return new FieldIndex(\n FieldIndex.UNKNOWN_ID,\n this.collectionId,\n segments,\n IndexState.empty()\n );\n }\n\n private hasMatchingEqualityFilter(segment: IndexSegment): boolean {\n for (const filter of this.equalityFilters) {\n if (this.matchesFilter(filter, segment)) {\n return true;\n }\n }\n return false;\n }\n\n private matchesFilter(\n filter: FieldFilter | undefined,\n segment: IndexSegment\n ): boolean {\n if (filter === undefined || !filter.field.isEqual(segment.fieldPath)) {\n return false;\n }\n const isArrayOperator =\n filter.op === Operator.ARRAY_CONTAINS ||\n filter.op === Operator.ARRAY_CONTAINS_ANY;\n return (segment.kind === IndexKind.CONTAINS) === isArrayOperator;\n }\n\n private matchesOrderBy(orderBy: OrderBy, segment: IndexSegment): boolean {\n if (!orderBy.field.isEqual(segment.fieldPath)) {\n return false;\n }\n return (\n (segment.kind === IndexKind.ASCENDING &&\n orderBy.dir === Direction.ASCENDING) ||\n (segment.kind === IndexKind.DESCENDING &&\n orderBy.dir === Direction.DESCENDING)\n );\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n CompositeFilter,\n compositeFilterIsConjunction,\n compositeFilterIsDisjunction,\n compositeFilterIsFlat,\n compositeFilterIsFlatConjunction,\n compositeFilterWithAddedFilters,\n CompositeOperator,\n FieldFilter,\n Filter,\n InFilter,\n Operator\n} from '../core/filter';\n\nimport { hardAssert } from './assert';\n\n/**\n * Provides utility functions that help with boolean logic transformations needed for handling\n * complex filters used in queries.\n */\n\n/**\n * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in\n * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given\n * input into a disjunction of equality filters and returns the expanded filter.\n */\nexport function computeInExpansion(filter: Filter): Filter {\n hardAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 0x4e2c,\n 'Only field filters and composite filters are accepted.'\n );\n\n if (filter instanceof FieldFilter) {\n if (filter instanceof InFilter) {\n const expandedFilters =\n filter.value.arrayValue?.values?.map(value =>\n FieldFilter.create(filter.field, Operator.EQUAL, value)\n ) || [];\n\n return CompositeFilter.create(expandedFilters, CompositeOperator.OR);\n } else {\n // We have reached other kinds of field filters.\n return filter;\n }\n }\n\n // We have a composite filter.\n const expandedFilters = filter.filters.map(subfilter =>\n computeInExpansion(subfilter)\n );\n return CompositeFilter.create(expandedFilters, filter.op);\n}\n\n/**\n * Given a composite filter, returns the list of terms in its disjunctive normal form.\n *\n *

Each element in the return value is one term of the resulting DNF. For instance: For the\n * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list\n * with two elements: a composite filter that performs (A && C), and a composite filter that\n * performs (B && C).\n *\n * @param filter the composite filter to calculate DNF transform for.\n * @return the terms in the DNF transform.\n */\nexport function getDnfTerms(filter: CompositeFilter): Filter[] {\n if (filter.getFilters().length === 0) {\n return [];\n }\n\n const result: Filter = computeDistributedNormalForm(\n computeInExpansion(filter)\n );\n\n hardAssert(\n isDisjunctiveNormalForm(result),\n 0x1cdf,\n 'computeDistributedNormalForm did not result in disjunctive normal form'\n );\n\n if (isSingleFieldFilter(result) || isFlatConjunction(result)) {\n return [result];\n }\n\n return result.getFilters();\n}\n\n/** Returns true if the given filter is a single field filter. e.g. (a == 10). */\nfunction isSingleFieldFilter(filter: Filter): boolean {\n return filter instanceof FieldFilter;\n}\n\n/**\n * Returns true if the given filter is the conjunction of one or more field filters. e.g. (a == 10\n * && b == 20)\n */\nfunction isFlatConjunction(filter: Filter): boolean {\n return (\n filter instanceof CompositeFilter &&\n compositeFilterIsFlatConjunction(filter)\n );\n}\n\n/**\n * Returns whether or not the given filter is in disjunctive normal form (DNF).\n *\n *

In boolean logic, a disjunctive normal form (DNF) is a canonical normal form of a logical\n * formula consisting of a disjunction of conjunctions; it can also be described as an OR of ANDs.\n *\n *

For more info, visit: https://en.wikipedia.org/wiki/Disjunctive_normal_form\n */\nfunction isDisjunctiveNormalForm(filter: Filter): boolean {\n return (\n isSingleFieldFilter(filter) ||\n isFlatConjunction(filter) ||\n isDisjunctionOfFieldFiltersAndFlatConjunctions(filter)\n );\n}\n\n/**\n * Returns true if the given filter is the disjunction of one or more \"flat conjunctions\" and\n * field filters. e.g. (a == 10) || (b==20 && c==30)\n */\nfunction isDisjunctionOfFieldFiltersAndFlatConjunctions(\n filter: Filter\n): boolean {\n if (filter instanceof CompositeFilter) {\n if (compositeFilterIsDisjunction(filter)) {\n for (const subFilter of filter.getFilters()) {\n if (!isSingleFieldFilter(subFilter) && !isFlatConjunction(subFilter)) {\n return false;\n }\n }\n\n return true;\n }\n }\n\n return false;\n}\n\nexport function computeDistributedNormalForm(filter: Filter): Filter {\n hardAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 0x84e2,\n 'Only field filters and composite filters are accepted.'\n );\n\n if (filter instanceof FieldFilter) {\n return filter;\n }\n\n if (filter.filters.length === 1) {\n return computeDistributedNormalForm(filter.filters[0]);\n }\n\n // Compute DNF for each of the subfilters first\n const result = filter.filters.map(subfilter =>\n computeDistributedNormalForm(subfilter)\n );\n\n let newFilter: Filter = CompositeFilter.create(result, filter.op);\n newFilter = applyAssociation(newFilter);\n\n if (isDisjunctiveNormalForm(newFilter)) {\n return newFilter;\n }\n\n hardAssert(\n newFilter instanceof CompositeFilter,\n 0xfbf2,\n 'field filters are already in DNF form'\n );\n hardAssert(\n compositeFilterIsConjunction(newFilter),\n 0x9d3b,\n 'Disjunction of filters all of which are already in DNF form is itself in DNF form.'\n );\n hardAssert(\n newFilter.filters.length > 1,\n 0xe247,\n 'Single-filter composite filters are already in DNF form.'\n );\n\n return newFilter.filters.reduce((runningResult, filter) =>\n applyDistribution(runningResult, filter)\n );\n}\n\nexport function applyDistribution(lhs: Filter, rhs: Filter): Filter {\n hardAssert(\n lhs instanceof FieldFilter || lhs instanceof CompositeFilter,\n 0x95f4,\n 'Only field filters and composite filters are accepted.'\n );\n hardAssert(\n rhs instanceof FieldFilter || rhs instanceof CompositeFilter,\n 0x6381,\n 'Only field filters and composite filters are accepted.'\n );\n\n let result: Filter;\n\n if (lhs instanceof FieldFilter) {\n if (rhs instanceof FieldFilter) {\n // FieldFilter FieldFilter\n result = applyDistributionFieldFilters(lhs, rhs);\n } else {\n // FieldFilter CompositeFilter\n result = applyDistributionFieldAndCompositeFilters(lhs, rhs);\n }\n } else {\n if (rhs instanceof FieldFilter) {\n // CompositeFilter FieldFilter\n result = applyDistributionFieldAndCompositeFilters(rhs, lhs);\n } else {\n // CompositeFilter CompositeFilter\n result = applyDistributionCompositeFilters(lhs, rhs);\n }\n }\n\n return applyAssociation(result);\n}\n\nfunction applyDistributionFieldFilters(\n lhs: FieldFilter,\n rhs: FieldFilter\n): Filter {\n // Conjunction distribution for two field filters is the conjunction of them.\n return CompositeFilter.create([lhs, rhs], CompositeOperator.AND);\n}\n\nfunction applyDistributionCompositeFilters(\n lhs: CompositeFilter,\n rhs: CompositeFilter\n): Filter {\n hardAssert(\n lhs.filters.length > 0 && rhs.filters.length > 0,\n 0xbb85,\n 'Found an empty composite filter'\n );\n\n // There are four cases:\n // (A & B) & (C & D) --> (A & B & C & D)\n // (A & B) & (C | D) --> (A & B & C) | (A & B & D)\n // (A | B) & (C & D) --> (C & D & A) | (C & D & B)\n // (A | B) & (C | D) --> (A & C) | (A & D) | (B & C) | (B & D)\n\n // Case 1 is a merge.\n if (compositeFilterIsConjunction(lhs) && compositeFilterIsConjunction(rhs)) {\n return compositeFilterWithAddedFilters(lhs, rhs.getFilters());\n }\n\n // Case 2,3,4 all have at least one side (lhs or rhs) that is a disjunction. In all three cases\n // we should take each element of the disjunction and distribute it over the other side, and\n // return the disjunction of the distribution results.\n const disjunctionSide = compositeFilterIsDisjunction(lhs) ? lhs : rhs;\n const otherSide = compositeFilterIsDisjunction(lhs) ? rhs : lhs;\n const results = disjunctionSide.filters.map(subfilter =>\n applyDistribution(subfilter, otherSide)\n );\n return CompositeFilter.create(results, CompositeOperator.OR);\n}\n\nfunction applyDistributionFieldAndCompositeFilters(\n fieldFilter: FieldFilter,\n compositeFilter: CompositeFilter\n): Filter {\n // There are two cases:\n // A & (B & C) --> (A & B & C)\n // A & (B | C) --> (A & B) | (A & C)\n if (compositeFilterIsConjunction(compositeFilter)) {\n // Case 1\n return compositeFilterWithAddedFilters(\n compositeFilter,\n fieldFilter.getFilters()\n );\n } else {\n // Case 2\n const newFilters = compositeFilter.filters.map(subfilter =>\n applyDistribution(fieldFilter, subfilter)\n );\n\n return CompositeFilter.create(newFilters, CompositeOperator.OR);\n }\n}\n\n/**\n * Applies the associativity property to the given filter and returns the resulting filter.\n *\n *

    \n *
  • A | (B | C) == (A | B) | C == (A | B | C)\n *
  • A & (B & C) == (A & B) & C == (A & B & C)\n *
\n *\n *

For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic\n */\nexport function applyAssociation(filter: Filter): Filter {\n hardAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 0x2e4a,\n 'Only field filters and composite filters are accepted.'\n );\n\n if (filter instanceof FieldFilter) {\n return filter;\n }\n\n const filters = filter.getFilters();\n\n // If the composite filter only contains 1 filter, apply associativity to it.\n if (filters.length === 1) {\n return applyAssociation(filters[0]);\n }\n\n // Associativity applied to a flat composite filter results is itself.\n if (compositeFilterIsFlat(filter)) {\n return filter;\n }\n\n // First apply associativity to all subfilters. This will in turn recursively apply\n // associativity to all nested composite filters and field filters.\n const updatedFilters = filters.map(subfilter => applyAssociation(subfilter));\n\n // For composite subfilters that perform the same kind of logical operation as `compositeFilter`\n // take out their filters and add them to `compositeFilter`. For example:\n // compositeFilter = (A | (B | C | D))\n // compositeSubfilter = (B | C | D)\n // Result: (A | B | C | D)\n // Note that the `compositeSubfilter` has been eliminated, and its filters (B, C, D) have been\n // added to the top-level \"compositeFilter\".\n const newSubfilters: Filter[] = [];\n updatedFilters.forEach(subfilter => {\n if (subfilter instanceof FieldFilter) {\n newSubfilters.push(subfilter);\n } else if (subfilter instanceof CompositeFilter) {\n if (subfilter.op === filter.op) {\n // compositeFilter: (A | (B | C))\n // compositeSubfilter: (B | C)\n // Result: (A | B | C)\n newSubfilters.push(...subfilter.filters);\n } else {\n // compositeFilter: (A | (B & C))\n // compositeSubfilter: (B & C)\n // Result: (A | (B & C))\n newSubfilters.push(subfilter);\n }\n }\n });\n\n if (newSubfilters.length === 1) {\n return newSubfilters[0];\n }\n\n return CompositeFilter.create(newSubfilters, filter.op);\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Target } from '../core/target';\nimport { DocumentMap } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldIndex, IndexOffset } from '../model/field_index';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { IndexManager, IndexType } from './index_manager';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\n/**\n * An in-memory implementation of IndexManager.\n */\nexport class MemoryIndexManager implements IndexManager {\n private collectionParentIndex = new MemoryCollectionParentIndex();\n\n addToCollectionParentIndex(\n transaction: PersistenceTransaction,\n collectionPath: ResourcePath\n ): PersistencePromise {\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 {\n IndexEntry,\n indexEntryComparator,\n encodeKeySafeBytes,\n decodeKeySafeBytes\n} 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 indexEntry.dbIndexEntry(\n this.uid,\n this.encodeDirectionalKey(fieldIndex, document.key),\n document.key\n )\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.dbIndexEntryKey(\n this.uid,\n this.encodeDirectionalKey(fieldIndex, document.key),\n document.key\n )\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 encodeKeySafeBytes(\n this.encodeDirectionalKey(fieldIndex, documentKey)\n )\n ])\n },\n (_, entry) => {\n results = results.add(\n new IndexEntry(\n fieldIndex.indexId,\n documentKey,\n decodeKeySafeBytes(entry.arrayValue),\n decodeKeySafeBytes(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 = bounds[i].dbIndexEntryKey(\n this.uid,\n EMPTY_VALUE,\n DocumentKey.empty()\n );\n const upperBound = bounds[i + 1].dbIndexEntryKey(\n this.uid,\n EMPTY_VALUE,\n DocumentKey.empty()\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(0xad8a, '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 0x7099,\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from '../model/document_key';\nimport { fail, hardAssert } from '../util/assert';\n\nimport {\n DbDocumentMutation,\n DbMutationBatch,\n DbRemoteDocument\n} from './indexeddb_schema';\nimport { DbRemoteDocument as DbRemoteDocumentLegacy } from './indexeddb_schema_legacy';\nimport {\n DbDocumentMutationKey,\n DbDocumentMutationStore,\n DbMutationBatchKey,\n DbMutationBatchStore,\n newDbDocumentMutationKey\n} from './indexeddb_sentinels';\nimport { PersistencePromise } from './persistence_promise';\nimport { SimpleDbTransaction } from './simple_db';\n\n/**\n * Delete a mutation batch and the associated document mutations.\n * @returns A PersistencePromise of the document mutations that were removed.\n */\nexport function removeMutationBatch(\n txn: SimpleDbTransaction,\n userId: string,\n batch: { batchId: number; mutations: Array<{ key: DocumentKey }> }\n): PersistencePromise {\n const mutationStore = txn.store(\n DbMutationBatchStore\n );\n const indexTxn = txn.store(\n DbDocumentMutationStore\n );\n const promises: Array> = [];\n\n const range = IDBKeyRange.only(batch.batchId);\n let numDeleted = 0;\n const removePromise = mutationStore.iterate(\n { range },\n (key, value, control) => {\n numDeleted++;\n return control.delete();\n }\n );\n promises.push(\n removePromise.next(() => {\n hardAssert(\n numDeleted === 1,\n 0xb7de,\n 'Dangling document-mutation reference found: Missing batch',\n { batchId: batch.batchId }\n );\n })\n );\n const removedDocuments: DocumentKey[] = [];\n for (const mutation of batch.mutations) {\n const indexKey = newDbDocumentMutationKey(\n userId,\n mutation.key.path,\n batch.batchId\n );\n promises.push(indexTxn.delete(indexKey));\n removedDocuments.push(mutation.key);\n }\n return PersistencePromise.waitFor(promises).next(() => removedDocuments);\n}\n\n/**\n * Returns an approximate size for the given document.\n */\nexport function dbDocumentSize(\n doc: DbRemoteDocument | DbRemoteDocumentLegacy | null\n): number {\n if (!doc) {\n return 0;\n }\n\n let value: unknown;\n if (doc.document) {\n value = doc.document;\n } else if (doc.unknownDocument) {\n value = doc.unknownDocument;\n } else if (doc.noDocument) {\n value = doc.noDocument;\n } else {\n throw fail(0x398b, 'Unknown remote document type');\n }\n return JSON.stringify(value).length;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { isCollectionGroupQuery, isDocumentQuery, Query } from '../core/query';\nimport { BatchId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { DocumentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { MutationBatch } from '../model/mutation_batch';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport { decodeResourcePath } from './encoded_resource_path';\nimport { IndexManager } from './index_manager';\nimport { removeMutationBatch } from './indexeddb_mutation_batch_impl';\nimport {\n DbDocumentMutation,\n DbMutationBatch,\n DbMutationQueue\n} from './indexeddb_schema';\nimport {\n DbDocumentMutationKey,\n DbDocumentMutationPlaceholder,\n DbDocumentMutationStore,\n DbMutationBatchKey,\n DbMutationBatchStore,\n DbMutationBatchUserMutationsIndex,\n DbMutationQueueKey,\n DbMutationQueueStore,\n newDbDocumentMutationKey,\n newDbDocumentMutationPrefixForPath,\n newDbDocumentMutationPrefixForUser\n} from './indexeddb_sentinels';\nimport { IndexedDbTransaction, getStore } from './indexeddb_transaction';\nimport {\n fromDbMutationBatch,\n LocalSerializer,\n toDbMutationBatch\n} from './local_serializer';\nimport { MutationQueue } from './mutation_queue';\nimport { ReferenceDelegate } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\n/** A mutation queue for a specific user, backed by IndexedDB. */\nexport class IndexedDbMutationQueue implements MutationQueue {\n /**\n * Caches the document keys for pending mutation batches. If the mutation\n * has been removed from IndexedDb, the cached value may continue to\n * be used to retrieve the batch's document keys. To remove a cached value\n * locally, `removeCachedMutationKeys()` should be invoked either directly\n * or through `removeMutationBatches()`.\n *\n * With multi-tab, when the primary client acknowledges or rejects a mutation,\n * this cache is used by secondary clients to invalidate the local\n * view of the documents that were previously affected by the mutation.\n */\n // PORTING NOTE: Multi-tab only.\n private documentKeysByBatchId = {} as { [batchId: number]: DocumentKeySet };\n\n constructor(\n /**\n * The normalized userId (e.g. null UID => \"\" userId) used to store /\n * retrieve mutations.\n */\n private userId: string,\n private readonly serializer: LocalSerializer,\n private readonly indexManager: IndexManager,\n private readonly referenceDelegate: ReferenceDelegate\n ) {}\n\n /**\n * Creates a new mutation queue for the given user.\n * @param user - The user for which to create a mutation queue.\n * @param serializer - The serializer to use when persisting to IndexedDb.\n */\n static forUser(\n user: User,\n serializer: LocalSerializer,\n indexManager: IndexManager,\n referenceDelegate: ReferenceDelegate\n ): IndexedDbMutationQueue {\n // TODO(mcg): Figure out what constraints there are on userIDs\n // In particular, are there any reserved characters? are empty ids allowed?\n // For the moment store these together in the same mutations table assuming\n // that empty userIDs aren't allowed.\n hardAssert(user.uid !== '', 0xfb83, 'UserID must not be an empty string.');\n const userId = user.isAuthenticated() ? user.uid! : '';\n return new IndexedDbMutationQueue(\n userId,\n serializer,\n indexManager,\n referenceDelegate\n );\n }\n\n checkEmpty(transaction: PersistenceTransaction): PersistencePromise {\n let empty = true;\n const range = IDBKeyRange.bound(\n [this.userId, Number.NEGATIVE_INFINITY],\n [this.userId, Number.POSITIVE_INFINITY]\n );\n return mutationsStore(transaction)\n .iterate(\n { index: DbMutationBatchUserMutationsIndex, range },\n (key, value, control) => {\n empty = false;\n control.done();\n }\n )\n .next(() => empty);\n }\n\n addMutationBatch(\n transaction: PersistenceTransaction,\n localWriteTime: Timestamp,\n baseMutations: Mutation[],\n mutations: Mutation[]\n ): PersistencePromise {\n const documentStore = documentMutationsStore(transaction);\n const mutationStore = mutationsStore(transaction);\n\n // The IndexedDb implementation in Chrome (and Firefox) does not handle\n // compound indices that include auto-generated keys correctly. To ensure\n // that the index entry is added correctly in all browsers, we perform two\n // writes: The first write is used to retrieve the next auto-generated Batch\n // ID, and the second write populates the index and stores the actual\n // mutation batch.\n // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972\n\n // We write an empty object to obtain key\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return mutationStore.add({} as any).next(batchId => {\n hardAssert(\n typeof batchId === 'number',\n 0xbf7b,\n 'Auto-generated key is not a number'\n );\n\n const batch = new MutationBatch(\n batchId,\n localWriteTime,\n baseMutations,\n mutations\n );\n const dbBatch = toDbMutationBatch(this.serializer, this.userId, batch);\n\n const promises: Array> = [];\n let collectionParents = new SortedSet((l, r) =>\n primitiveComparator(l.canonicalString(), r.canonicalString())\n );\n for (const mutation of mutations) {\n const indexKey = newDbDocumentMutationKey(\n this.userId,\n mutation.key.path,\n batchId\n );\n collectionParents = collectionParents.add(mutation.key.path.popLast());\n promises.push(mutationStore.put(dbBatch));\n promises.push(\n documentStore.put(indexKey, DbDocumentMutationPlaceholder)\n );\n }\n\n collectionParents.forEach(parent => {\n promises.push(\n this.indexManager.addToCollectionParentIndex(transaction, parent)\n );\n });\n\n transaction.addOnCommittedListener(() => {\n this.documentKeysByBatchId[batchId] = batch.keys();\n });\n\n return PersistencePromise.waitFor(promises).next(() => batch);\n });\n }\n\n lookupMutationBatch(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise {\n return mutationsStore(transaction)\n .get(batchId)\n .next(dbBatch => {\n if (dbBatch) {\n hardAssert(\n dbBatch.userId === this.userId,\n 0x0030,\n `Unexpected user for mutation batch`,\n {\n userId: dbBatch.userId,\n batchId\n }\n );\n return fromDbMutationBatch(this.serializer, dbBatch);\n }\n return null;\n });\n }\n\n /**\n * Returns the document keys for the mutation batch with the given batchId.\n * For primary clients, this method returns `null` after\n * `removeMutationBatches()` has been called. Secondary clients return a\n * cached result until `removeCachedMutationKeys()` is invoked.\n */\n // PORTING NOTE: Multi-tab only.\n lookupMutationKeys(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise {\n if (this.documentKeysByBatchId[batchId]) {\n return PersistencePromise.resolve(\n this.documentKeysByBatchId[batchId]\n );\n } else {\n return this.lookupMutationBatch(transaction, batchId).next(batch => {\n if (batch) {\n const keys = batch.keys();\n this.documentKeysByBatchId[batchId] = keys;\n return keys;\n } else {\n return null;\n }\n });\n }\n }\n\n getNextMutationBatchAfterBatchId(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise {\n const nextBatchId = batchId + 1;\n\n const range = IDBKeyRange.lowerBound([this.userId, nextBatchId]);\n let foundBatch: MutationBatch | null = null;\n return mutationsStore(transaction)\n .iterate(\n { index: DbMutationBatchUserMutationsIndex, range },\n (key, dbBatch, control) => {\n if (dbBatch.userId === this.userId) {\n hardAssert(\n dbBatch.batchId >= nextBatchId,\n 0xb9a4,\n 'Should have found mutation after `nextBatchId`',\n { nextBatchId }\n );\n foundBatch = fromDbMutationBatch(this.serializer, dbBatch);\n }\n control.done();\n }\n )\n .next(() => foundBatch);\n }\n\n getHighestUnacknowledgedBatchId(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n const range = IDBKeyRange.upperBound([\n this.userId,\n Number.POSITIVE_INFINITY\n ]);\n\n let batchId = BATCHID_UNKNOWN;\n return mutationsStore(transaction)\n .iterate(\n { index: DbMutationBatchUserMutationsIndex, range, reverse: true },\n (key, dbBatch, control) => {\n batchId = dbBatch.batchId;\n control.done();\n }\n )\n .next(() => batchId);\n }\n\n getAllMutationBatches(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n const range = IDBKeyRange.bound(\n [this.userId, BATCHID_UNKNOWN],\n [this.userId, Number.POSITIVE_INFINITY]\n );\n return mutationsStore(transaction)\n .loadAll(DbMutationBatchUserMutationsIndex, range)\n .next(dbBatches =>\n dbBatches.map(dbBatch => fromDbMutationBatch(this.serializer, dbBatch))\n );\n }\n\n getAllMutationBatchesAffectingDocumentKey(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n // Scan the document-mutation index starting with a prefix starting with\n // the given documentKey.\n const indexPrefix = newDbDocumentMutationPrefixForPath(\n this.userId,\n documentKey.path\n );\n const indexStart = IDBKeyRange.lowerBound(indexPrefix);\n\n const results: MutationBatch[] = [];\n return documentMutationsStore(transaction)\n .iterate({ range: indexStart }, (indexKey, _, control) => {\n const [userID, encodedPath, batchId] = indexKey;\n\n // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n const path = decodeResourcePath(encodedPath);\n if (userID !== this.userId || !documentKey.path.isEqual(path)) {\n control.done();\n return;\n }\n // Look up the mutation batch in the store.\n return mutationsStore(transaction)\n .get(batchId)\n .next(mutation => {\n if (!mutation) {\n throw fail(\n 0xf028,\n 'Dangling document-mutation reference found: `indexKey` which points to `batchId`',\n {\n indexKey,\n batchId\n }\n );\n }\n hardAssert(\n mutation.userId === this.userId,\n 0x2907,\n `Unexpected user for mutation batch`,\n {\n userId: mutation.userId,\n batchId\n }\n );\n results.push(fromDbMutationBatch(this.serializer, mutation));\n });\n })\n .next(() => results);\n }\n\n getAllMutationBatchesAffectingDocumentKeys(\n transaction: PersistenceTransaction,\n documentKeys: SortedMap\n ): PersistencePromise {\n let uniqueBatchIDs = new SortedSet(primitiveComparator);\n\n const promises: Array> = [];\n documentKeys.forEach(documentKey => {\n const indexStart = newDbDocumentMutationPrefixForPath(\n this.userId,\n documentKey.path\n );\n const range = IDBKeyRange.lowerBound(indexStart);\n\n const promise = documentMutationsStore(transaction).iterate(\n { range },\n (indexKey, _, control) => {\n const [userID, encodedPath, batchID] = indexKey;\n\n // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n const path = decodeResourcePath(encodedPath);\n if (userID !== this.userId || !documentKey.path.isEqual(path)) {\n control.done();\n return;\n }\n\n uniqueBatchIDs = uniqueBatchIDs.add(batchID);\n }\n );\n\n promises.push(promise);\n });\n\n return PersistencePromise.waitFor(promises).next(() =>\n this.lookupMutationBatches(transaction, uniqueBatchIDs)\n );\n }\n\n getAllMutationBatchesAffectingQuery(\n transaction: PersistenceTransaction,\n query: Query\n ): PersistencePromise {\n debugAssert(\n !isDocumentQuery(query),\n \"Document queries shouldn't go down this path\"\n );\n debugAssert(\n !isCollectionGroupQuery(query),\n 'CollectionGroup queries should be handled in LocalDocumentsView'\n );\n\n const queryPath = query.path;\n const immediateChildrenLength = queryPath.length + 1;\n\n // TODO(mcg): Actually implement a single-collection query\n //\n // This is actually executing an ancestor query, traversing the whole\n // subtree below the collection which can be horrifically inefficient for\n // some structures. The right way to solve this is to implement the full\n // value index, but that's not in the cards in the near future so this is\n // the best we can do for the moment.\n //\n // Since we don't yet index the actual properties in the mutations, our\n // current approach is to just return all mutation batches that affect\n // documents in the collection being queried.\n const indexPrefix = newDbDocumentMutationPrefixForPath(\n this.userId,\n queryPath\n );\n const indexStart = IDBKeyRange.lowerBound(indexPrefix);\n\n // Collect up unique batchIDs encountered during a scan of the index. Use a\n // SortedSet to accumulate batch IDs so they can be traversed in order in a\n // scan of the main table.\n let uniqueBatchIDs = new SortedSet(primitiveComparator);\n return documentMutationsStore(transaction)\n .iterate({ range: indexStart }, (indexKey, _, control) => {\n const [userID, encodedPath, batchID] = indexKey;\n const path = decodeResourcePath(encodedPath);\n if (userID !== this.userId || !queryPath.isPrefixOf(path)) {\n control.done();\n return;\n }\n // Rows with document keys more than one segment longer than the\n // query path can't be matches. For example, a query on 'rooms'\n // can't match the document /rooms/abc/messages/xyx.\n // TODO(mcg): we'll need a different scanner when we implement\n // ancestor queries.\n if (path.length !== immediateChildrenLength) {\n return;\n }\n uniqueBatchIDs = uniqueBatchIDs.add(batchID);\n })\n .next(() => this.lookupMutationBatches(transaction, uniqueBatchIDs));\n }\n\n private lookupMutationBatches(\n transaction: PersistenceTransaction,\n batchIDs: SortedSet\n ): PersistencePromise {\n const results: MutationBatch[] = [];\n const promises: Array> = [];\n // TODO(rockwood): Implement this using iterate.\n batchIDs.forEach(batchId => {\n promises.push(\n mutationsStore(transaction)\n .get(batchId)\n .next(mutation => {\n if (mutation === null) {\n throw fail(\n 0x89ca,\n 'Dangling document-mutation reference found, which points to `batchId`',\n {\n batchId\n }\n );\n }\n hardAssert(\n mutation.userId === this.userId,\n 0x2614,\n `Unexpected user for mutation batch`,\n { userId: mutation.userId, batchId }\n );\n results.push(fromDbMutationBatch(this.serializer, mutation));\n })\n );\n });\n return PersistencePromise.waitFor(promises).next(() => results);\n }\n\n removeMutationBatch(\n transaction: PersistenceTransaction,\n batch: MutationBatch\n ): PersistencePromise {\n return removeMutationBatch(\n (transaction as IndexedDbTransaction).simpleDbTransaction,\n this.userId,\n batch\n ).next(removedDocuments => {\n transaction.addOnCommittedListener(() => {\n this.removeCachedMutationKeys(batch.batchId);\n });\n return PersistencePromise.forEach(\n removedDocuments,\n (key: DocumentKey) => {\n return this.referenceDelegate.markPotentiallyOrphaned(\n transaction,\n key\n );\n }\n );\n });\n }\n\n /**\n * Clears the cached keys for a mutation batch. This method should be\n * called by secondary clients after they process mutation updates.\n *\n * Note that this method does not have to be called from primary clients as\n * the corresponding cache entries are cleared when an acknowledged or\n * rejected batch is removed from the mutation queue.\n */\n // PORTING NOTE: Multi-tab only\n removeCachedMutationKeys(batchId: BatchId): void {\n delete this.documentKeysByBatchId[batchId];\n }\n\n performConsistencyCheck(\n txn: PersistenceTransaction\n ): PersistencePromise {\n return this.checkEmpty(txn).next(empty => {\n if (!empty) {\n return PersistencePromise.resolve();\n }\n\n // Verify that there are no entries in the documentMutations index if\n // the queue is empty.\n const startRange = IDBKeyRange.lowerBound(\n newDbDocumentMutationPrefixForUser(this.userId)\n );\n const danglingMutationReferences: ResourcePath[] = [];\n return documentMutationsStore(txn)\n .iterate({ range: startRange }, (key, _, control) => {\n const userID = key[0];\n if (userID !== this.userId) {\n control.done();\n return;\n } else {\n const path = decodeResourcePath(key[1]);\n danglingMutationReferences.push(path);\n }\n })\n .next(() => {\n hardAssert(\n danglingMutationReferences.length === 0,\n 0xdd90,\n 'Document leak -- detected dangling mutation references when queue is empty.',\n {\n danglingKeys: danglingMutationReferences.map(p =>\n p.canonicalString()\n )\n }\n );\n });\n });\n }\n\n containsKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return mutationQueueContainsKey(txn, this.userId, key);\n }\n\n // PORTING NOTE: Multi-tab only (state is held in memory in other clients).\n /** Returns the mutation queue's metadata from IndexedDb. */\n private getMutationQueueMetadata(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return mutationQueuesStore(transaction)\n .get(this.userId)\n .next((metadata: DbMutationQueue | null) => {\n return (\n metadata || {\n userId: this.userId,\n lastAcknowledgedBatchId: BATCHID_UNKNOWN,\n lastStreamToken: ''\n }\n );\n });\n }\n}\n\n/**\n * @returns true if the mutation queue for the given user contains a pending\n * mutation for the given key.\n */\nfunction mutationQueueContainsKey(\n txn: PersistenceTransaction,\n userId: string,\n key: DocumentKey\n): PersistencePromise {\n const indexKey = newDbDocumentMutationPrefixForPath(userId, key.path);\n const encodedPath = indexKey[1];\n const startRange = IDBKeyRange.lowerBound(indexKey);\n let containsKey = false;\n return documentMutationsStore(txn)\n .iterate({ range: startRange, keysOnly: true }, (key, value, control) => {\n const [userID, keyPath, /*batchID*/ _] = key;\n if (userID === userId && keyPath === encodedPath) {\n containsKey = true;\n }\n control.done();\n })\n .next(() => containsKey);\n}\n\n/** Returns true if any mutation queue contains the given document. */\nexport function mutationQueuesContainKey(\n txn: PersistenceTransaction,\n docKey: DocumentKey\n): PersistencePromise {\n let found = false;\n return mutationQueuesStore(txn)\n .iterateSerial(userId => {\n return mutationQueueContainsKey(txn, userId, docKey).next(containsKey => {\n if (containsKey) {\n found = true;\n }\n return PersistencePromise.resolve(!containsKey);\n });\n })\n .next(() => found);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutations object store.\n */\nfunction mutationsStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbMutationBatchStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction documentMutationsStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbDocumentMutationStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction mutationQueuesStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbMutationQueueStore\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TargetId } from './types';\n\n/** Offset to ensure non-overlapping target ids. */\nconst OFFSET = 2;\n\n/**\n * Generates monotonically increasing target IDs for sending targets to the\n * watch stream.\n *\n * The client constructs two generators, one for the target cache, and one for\n * for the sync engine (to generate limbo documents targets). These\n * generators produce non-overlapping IDs (by using even and odd IDs\n * respectively).\n *\n * By separating the target ID space, the query cache can generate target IDs\n * that persist across client restarts, while sync engine can independently\n * generate in-memory target IDs that are transient and can be reused after a\n * restart.\n */\nexport class TargetIdGenerator {\n constructor(private lastId: number) {}\n\n next(): TargetId {\n this.lastId += OFFSET;\n return this.lastId;\n }\n\n static forTargetCache(): TargetIdGenerator {\n // The target cache generator must return '2' in its first call to `next()`\n // as there is no differentiation in the protocol layer between an unset\n // number and the number '0'. If we were to sent a target with target ID\n // '0', the backend would consider it unset and replace it with its own ID.\n return new TargetIdGenerator(2 - OFFSET);\n }\n\n static forSyncEngine(): TargetIdGenerator {\n // Sync engine assigns target IDs for limbo document detection.\n return new TargetIdGenerator(1 - OFFSET);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { canonifyTarget, Target, targetEquals } from '../core/target';\nimport { TargetIdGenerator } from '../core/target_id_generator';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { DocumentKeySet, documentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { hardAssert } from '../util/assert';\nimport { immediateSuccessor } from '../util/misc';\n\nimport {\n decodeResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { IndexedDbLruDelegate } from './indexeddb_lru_delegate';\nimport { DbTarget, DbTargetDocument, DbTargetGlobal } from './indexeddb_schema';\nimport {\n DbTargetDocumentDocumentTargetsIndex,\n DbTargetDocumentKey,\n DbTargetDocumentStore,\n DbTargetGlobalKey,\n DbTargetGlobalStore,\n DbTargetKey,\n DbTargetQueryTargetsIndexName,\n DbTargetStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport { fromDbTarget, LocalSerializer, toDbTarget } from './local_serializer';\nimport { ActiveTargets } from './lru_garbage_collector';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\nimport { TargetCache } from './target_cache';\nimport { TargetData } from './target_data';\n\nexport class IndexedDbTargetCache implements TargetCache {\n constructor(\n private readonly referenceDelegate: IndexedDbLruDelegate,\n private serializer: LocalSerializer\n ) {}\n\n // PORTING NOTE: We don't cache global metadata for the target cache, since\n // some of it (in particular `highestTargetId`) can be modified by secondary\n // tabs. We could perhaps be more granular (and e.g. still cache\n // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go\n // to IndexedDb whenever we need to read metadata. We can revisit if it turns\n // out to have a meaningful performance impact.\n\n allocateTargetId(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(metadata => {\n const targetIdGenerator = new TargetIdGenerator(metadata.highestTargetId);\n metadata.highestTargetId = targetIdGenerator.next();\n return this.saveMetadata(transaction, metadata).next(\n () => metadata.highestTargetId\n );\n });\n }\n\n getLastRemoteSnapshotVersion(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(metadata => {\n return SnapshotVersion.fromTimestamp(\n new Timestamp(\n metadata.lastRemoteSnapshotVersion.seconds,\n metadata.lastRemoteSnapshotVersion.nanoseconds\n )\n );\n });\n }\n\n getHighestSequenceNumber(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(\n targetGlobal => targetGlobal.highestListenSequenceNumber\n );\n }\n\n setTargetsMetadata(\n transaction: PersistenceTransaction,\n highestListenSequenceNumber: number,\n lastRemoteSnapshotVersion?: SnapshotVersion\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(metadata => {\n metadata.highestListenSequenceNumber = highestListenSequenceNumber;\n if (lastRemoteSnapshotVersion) {\n metadata.lastRemoteSnapshotVersion =\n lastRemoteSnapshotVersion.toTimestamp();\n }\n if (highestListenSequenceNumber > metadata.highestListenSequenceNumber) {\n metadata.highestListenSequenceNumber = highestListenSequenceNumber;\n }\n return this.saveMetadata(transaction, metadata);\n });\n }\n\n addTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n return this.saveTargetData(transaction, targetData).next(() => {\n return this.retrieveMetadata(transaction).next(metadata => {\n metadata.targetCount += 1;\n this.updateMetadataFromTargetData(targetData, metadata);\n return this.saveMetadata(transaction, metadata);\n });\n });\n }\n\n updateTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n return this.saveTargetData(transaction, targetData);\n }\n\n removeTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n return this.removeMatchingKeysForTargetId(transaction, targetData.targetId)\n .next(() => targetsStore(transaction).delete(targetData.targetId))\n .next(() => this.retrieveMetadata(transaction))\n .next(metadata => {\n hardAssert(\n metadata.targetCount > 0,\n 0x1f81,\n 'Removing from an empty target cache'\n );\n metadata.targetCount -= 1;\n return this.saveMetadata(transaction, metadata);\n });\n }\n\n /**\n * Drops any targets with sequence number less than or equal to the upper bound, excepting those\n * present in `activeTargetIds`. Document associations for the removed targets are also removed.\n * Returns the number of targets removed.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n let count = 0;\n const promises: Array> = [];\n return targetsStore(txn)\n .iterate((key, value) => {\n const targetData = fromDbTarget(value);\n if (\n targetData.sequenceNumber <= upperBound &&\n activeTargetIds.get(targetData.targetId) === null\n ) {\n count++;\n promises.push(this.removeTargetData(txn, targetData));\n }\n })\n .next(() => PersistencePromise.waitFor(promises))\n .next(() => count);\n }\n\n /**\n * Call provided function with each `TargetData` that we have cached.\n */\n forEachTarget(\n txn: PersistenceTransaction,\n f: (q: TargetData) => void\n ): PersistencePromise {\n return targetsStore(txn).iterate((key, value) => {\n const targetData = fromDbTarget(value);\n f(targetData);\n });\n }\n\n private retrieveMetadata(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return globalTargetStore(transaction)\n .get(DbTargetGlobalKey)\n .next(metadata => {\n hardAssert(metadata !== null, 0x0b48, 'Missing metadata row.');\n return metadata;\n });\n }\n\n private saveMetadata(\n transaction: PersistenceTransaction,\n metadata: DbTargetGlobal\n ): PersistencePromise {\n return globalTargetStore(transaction).put(DbTargetGlobalKey, metadata);\n }\n\n private saveTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n return targetsStore(transaction).put(\n toDbTarget(this.serializer, targetData)\n );\n }\n\n /**\n * In-place updates the provided metadata to account for values in the given\n * TargetData. Saving is done separately. Returns true if there were any\n * changes to the metadata.\n */\n private updateMetadataFromTargetData(\n targetData: TargetData,\n metadata: DbTargetGlobal\n ): boolean {\n let updated = false;\n if (targetData.targetId > metadata.highestTargetId) {\n metadata.highestTargetId = targetData.targetId;\n updated = true;\n }\n\n if (targetData.sequenceNumber > metadata.highestListenSequenceNumber) {\n metadata.highestListenSequenceNumber = targetData.sequenceNumber;\n updated = true;\n }\n return updated;\n }\n\n getTargetCount(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(\n metadata => metadata.targetCount\n );\n }\n\n getTargetData(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise {\n // Iterating by the canonicalId may yield more than one result because\n // canonicalId values are not required to be unique per target. This query\n // depends on the queryTargets index to be efficient.\n const canonicalId = canonifyTarget(target);\n const range = IDBKeyRange.bound(\n [canonicalId, Number.NEGATIVE_INFINITY],\n [canonicalId, Number.POSITIVE_INFINITY]\n );\n let result: TargetData | null = null;\n return targetsStore(transaction)\n .iterate(\n { range, index: DbTargetQueryTargetsIndexName },\n (key, value, control) => {\n const found = fromDbTarget(value);\n // After finding a potential match, check that the target is\n // actually equal to the requested target.\n if (targetEquals(target, found.target)) {\n result = found;\n control.done();\n }\n }\n )\n .next(() => result);\n }\n\n addMatchingKeys(\n txn: PersistenceTransaction,\n keys: DocumentKeySet,\n targetId: TargetId\n ): PersistencePromise {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n const promises: Array> = [];\n const store = documentTargetStore(txn);\n keys.forEach(key => {\n const path = encodeResourcePath(key.path);\n promises.push(store.put({ targetId, path }));\n promises.push(this.referenceDelegate.addReference(txn, targetId, key));\n });\n return PersistencePromise.waitFor(promises);\n }\n\n removeMatchingKeys(\n txn: PersistenceTransaction,\n keys: DocumentKeySet,\n targetId: TargetId\n ): PersistencePromise {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n const store = documentTargetStore(txn);\n return PersistencePromise.forEach(keys, (key: DocumentKey) => {\n const path = encodeResourcePath(key.path);\n return PersistencePromise.waitFor([\n store.delete([targetId, path]),\n this.referenceDelegate.removeReference(txn, targetId, key)\n ]);\n });\n }\n\n removeMatchingKeysForTargetId(\n txn: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise {\n const store = documentTargetStore(txn);\n const range = IDBKeyRange.bound(\n [targetId],\n [targetId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n return store.delete(range);\n }\n\n getMatchingKeysForTargetId(\n txn: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise {\n const range = IDBKeyRange.bound(\n [targetId],\n [targetId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n const store = documentTargetStore(txn);\n let result = documentKeySet();\n\n return store\n .iterate({ range, keysOnly: true }, (key, _, control) => {\n const path = decodeResourcePath(key[1]);\n const docKey = new DocumentKey(path);\n result = result.add(docKey);\n })\n .next(() => result);\n }\n\n containsKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n const path = encodeResourcePath(key.path);\n const range = IDBKeyRange.bound(\n [path],\n [immediateSuccessor(path)],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n let count = 0;\n return documentTargetStore(txn!)\n .iterate(\n {\n index: DbTargetDocumentDocumentTargetsIndex,\n keysOnly: true,\n range\n },\n ([targetId, path], _, control) => {\n // Having a sentinel row for a document does not count as containing that document;\n // For the target cache, containing the document means the document is part of some\n // target.\n if (targetId !== 0) {\n count++;\n control.done();\n }\n }\n )\n .next(() => count > 0);\n }\n\n /**\n * Looks up a TargetData entry by target ID.\n *\n * @param targetId - The target ID of the TargetData entry to look up.\n * @returns The cached TargetData entry, or null if the cache has no entry for\n * the target.\n */\n // PORTING NOTE: Multi-tab only.\n getTargetDataForTarget(\n transaction: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise {\n return targetsStore(transaction)\n .get(targetId)\n .next(found => {\n if (found) {\n return fromDbTarget(found);\n } else {\n return null;\n }\n });\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the queries object store.\n */\nfunction targetsStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbTargetStore);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the target globals object store.\n */\nfunction globalTargetStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbTargetGlobalStore);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document target object store.\n */\nexport function documentTargetStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbTargetDocumentStore\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirestoreError } from '../api';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { ListenSequenceNumber } from '../core/types';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { getLogLevel, logDebug, LogLevel } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from './local_store';\nimport {\n ActiveTargets,\n GC_DID_NOT_RUN,\n LRU_COLLECTION_DISABLED,\n LruDelegate,\n LruGarbageCollector,\n LruParams,\n LruResults\n} from './lru_garbage_collector';\nimport { Scheduler } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { isIndexedDbTransactionError } from './simple_db';\n\nconst LOG_TAG = 'LruGarbageCollector';\n\nexport const LRU_MINIMUM_CACHE_SIZE_BYTES = 1 * 1024 * 1024;\n\n/** How long we wait to try running LRU GC after SDK initialization. */\nconst INITIAL_GC_DELAY_MS = 1 * 60 * 1000;\n/** Minimum amount of time between GC checks, after the first one. */\nconst REGULAR_GC_DELAY_MS = 5 * 60 * 1000;\n\n// The type and comparator for the items contained in the SortedSet used in\n// place of a priority queue for the RollingSequenceNumberBuffer.\ntype BufferEntry = [ListenSequenceNumber, number];\n\nfunction bufferEntryComparator(\n [aSequence, aIndex]: BufferEntry,\n [bSequence, bIndex]: BufferEntry\n): number {\n const seqCmp = primitiveComparator(aSequence, bSequence);\n if (seqCmp === 0) {\n // This order doesn't matter, but we can bias against churn by sorting\n // entries created earlier as less than newer entries.\n return primitiveComparator(aIndex, bIndex);\n } else {\n return seqCmp;\n }\n}\n\n/**\n * Used to calculate the nth sequence number. Keeps a rolling buffer of the\n * lowest n values passed to `addElement`, and finally reports the largest of\n * them in `maxValue`.\n */\nclass RollingSequenceNumberBuffer {\n private buffer: SortedSet = 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\nimport { ListenSequence } from '../core/listen_sequence';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { DocumentKey } from '../model/document_key';\n\nimport {\n decodeResourcePath,\n EncodedResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { IndexedDbLruDelegate } from './indexeddb_lru_delegate';\nimport { mutationQueuesContainKey } from './indexeddb_mutation_queue';\nimport { DbTargetDocument } from './indexeddb_schema';\nimport { DbTargetDocumentDocumentTargetsIndex } from './indexeddb_sentinels';\nimport {\n documentTargetStore,\n IndexedDbTargetCache\n} from './indexeddb_target_cache';\nimport {\n ActiveTargets,\n LruGarbageCollector,\n LruParams\n} from './lru_garbage_collector';\nimport { newLruGarbageCollector } from './lru_garbage_collector_impl';\nimport { Persistence } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { TargetData } from './target_data';\n\n/** Provides LRU functionality for IndexedDB persistence. */\nexport class IndexedDbLruDelegateImpl implements IndexedDbLruDelegate {\n readonly garbageCollector: LruGarbageCollector;\n\n constructor(private readonly db: Persistence, params: LruParams) {\n this.garbageCollector = newLruGarbageCollector(this, params);\n }\n\n getSequenceNumberCount(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const docCountPromise = this.orphanedDocumentCount(txn);\n const targetCountPromise = this.db.getTargetCache().getTargetCount(txn);\n return targetCountPromise.next(targetCount =>\n docCountPromise.next(docCount => targetCount + docCount)\n );\n }\n\n private orphanedDocumentCount(\n txn: PersistenceTransaction\n ): PersistencePromise {\n let orphanedCount = 0;\n return this.forEachOrphanedDocumentSequenceNumber(txn, _ => {\n orphanedCount++;\n }).next(() => orphanedCount);\n }\n\n forEachTarget(\n txn: PersistenceTransaction,\n f: (q: TargetData) => void\n ): PersistencePromise {\n return this.db.getTargetCache().forEachTarget(txn, f);\n }\n\n forEachOrphanedDocumentSequenceNumber(\n txn: PersistenceTransaction,\n f: (sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise {\n return this.forEachOrphanedDocument(txn, (docKey, sequenceNumber) =>\n f(sequenceNumber)\n );\n }\n\n addReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise {\n return writeSentinelKey(txn, key);\n }\n\n removeReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise {\n return writeSentinelKey(txn, key);\n }\n\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n return (this.db.getTargetCache() as IndexedDbTargetCache).removeTargets(\n txn,\n upperBound,\n activeTargetIds\n );\n }\n\n markPotentiallyOrphaned(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return writeSentinelKey(txn, key);\n }\n\n /**\n * Returns true if anything would prevent this document from being garbage\n * collected, given that the document in question is not present in any\n * targets and has a sequence number less than or equal to the upper bound for\n * the collection run.\n */\n private isPinned(\n txn: PersistenceTransaction,\n docKey: DocumentKey\n ): PersistencePromise {\n return mutationQueuesContainKey(txn, docKey);\n }\n\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise {\n const documentCache = this.db.getRemoteDocumentCache();\n const changeBuffer = documentCache.newChangeBuffer();\n\n const promises: Array> = [];\n let documentCount = 0;\n\n const iteration = this.forEachOrphanedDocument(\n txn,\n (docKey, sequenceNumber) => {\n if (sequenceNumber <= upperBound) {\n const p = this.isPinned(txn, docKey).next(isPinned => {\n if (!isPinned) {\n documentCount++;\n // Our size accounting requires us to read all documents before\n // removing them.\n return changeBuffer.getEntry(txn, docKey).next(() => {\n changeBuffer.removeEntry(docKey, SnapshotVersion.min());\n return documentTargetStore(txn).delete(sentinelKey(docKey));\n });\n }\n });\n promises.push(p);\n }\n }\n );\n\n return iteration\n .next(() => PersistencePromise.waitFor(promises))\n .next(() => changeBuffer.apply(txn))\n .next(() => documentCount);\n }\n\n removeTarget(\n txn: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n const updated = targetData.withSequenceNumber(txn.currentSequenceNumber);\n return this.db.getTargetCache().updateTargetData(txn, updated);\n }\n\n updateLimboDocument(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return writeSentinelKey(txn, key);\n }\n\n /**\n * Call provided function for each document in the cache that is 'orphaned'. Orphaned\n * means not a part of any target, so the only entry in the target-document index for\n * that document will be the sentinel row (targetId 0), which will also have the sequence\n * number for the last time the document was accessed.\n */\n private forEachOrphanedDocument(\n txn: PersistenceTransaction,\n f: (docKey: DocumentKey, sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise {\n const store = documentTargetStore(txn);\n let nextToReport: ListenSequenceNumber = ListenSequence.INVALID;\n let nextPath: EncodedResourcePath;\n return store\n .iterate(\n {\n index: DbTargetDocumentDocumentTargetsIndex\n },\n ([targetId, docKey], { path, sequenceNumber }) => {\n if (targetId === 0) {\n // if nextToReport is valid, report it, this is a new key so the\n // last one must not be a member of any targets.\n if (nextToReport !== ListenSequence.INVALID) {\n f(new DocumentKey(decodeResourcePath(nextPath)), nextToReport);\n }\n // set nextToReport to be this sequence number. It's the next one we\n // might report, if we don't find any targets for this document.\n // Note that the sequence number must be defined when the targetId\n // is 0.\n nextToReport = sequenceNumber!;\n nextPath = path;\n } else {\n // set nextToReport to be invalid, we know we don't need to report\n // this one since we found a target for it.\n nextToReport = ListenSequence.INVALID;\n }\n }\n )\n .next(() => {\n // Since we report sequence numbers after getting to the next key, we\n // need to check if the last key we iterated over was an orphaned\n // document and report it.\n if (nextToReport !== ListenSequence.INVALID) {\n f(new DocumentKey(decodeResourcePath(nextPath)), nextToReport);\n }\n });\n }\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise {\n return this.db.getRemoteDocumentCache().getSize(txn);\n }\n}\n\nfunction sentinelKey(key: DocumentKey): [TargetId, EncodedResourcePath] {\n return [0, encodeResourcePath(key.path)];\n}\n\n/**\n * @returns A value suitable for writing a sentinel row in the target-document\n * store.\n */\nfunction sentinelRow(\n key: DocumentKey,\n sequenceNumber: ListenSequenceNumber\n): DbTargetDocument {\n return { targetId: 0, path: encodeResourcePath(key.path), sequenceNumber };\n}\n\nfunction writeSentinelKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n): PersistencePromise {\n return documentTargetStore(txn).put(\n sentinelRow(key, txn.currentSequenceNumber)\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { DocumentKeySet, MutableDocumentMap } from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { debugAssert } from '../util/assert';\nimport { ObjectMap } from '../util/obj_map';\n\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\n/**\n * An in-memory buffer of entries to be written to a RemoteDocumentCache.\n * It can be used to batch up a set of changes to be written to the cache, but\n * additionally supports reading entries back with the `getEntry()` method,\n * falling back to the underlying RemoteDocumentCache if no entry is\n * buffered.\n *\n * Entries added to the cache *must* be read first. This is to facilitate\n * calculating the size delta of the pending changes.\n *\n * PORTING NOTE: This class was implemented then removed from other platforms.\n * If byte-counting ends up being needed on the other platforms, consider\n * porting this class as part of that implementation work.\n */\nexport abstract class RemoteDocumentChangeBuffer {\n // A mapping of document key to the new cache entry that should be written.\n protected changes: ObjectMap = 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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Query, queryMatches } from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport {\n DocumentKeySet,\n DocumentSizeEntries,\n MutableDocumentMap,\n mutableDocumentMap,\n OverlayMap\n} from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { IndexOffset } from '../model/field_index';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { IndexManager } from './index_manager';\nimport { dbDocumentSize } from './indexeddb_mutation_batch_impl';\nimport { DbRemoteDocument, DbRemoteDocumentGlobal } from './indexeddb_schema';\nimport {\n DbRemoteDocumentCollectionGroupIndex,\n DbRemoteDocumentDocumentKeyIndex,\n DbRemoteDocumentGlobalKey,\n DbRemoteDocumentGlobalStore,\n DbRemoteDocumentKey,\n DbRemoteDocumentStore,\n DbTimestampKey\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n fromDbRemoteDocument,\n LocalSerializer,\n toDbRemoteDocument,\n toDbTimestampKey\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { QueryContext } from './query_context';\nimport { RemoteDocumentCache } from './remote_document_cache';\nimport { RemoteDocumentChangeBuffer } from './remote_document_change_buffer';\nimport { SimpleDbStore } from './simple_db';\n\nexport interface DocumentSizeEntry {\n document: MutableDocument;\n size: number;\n}\n\nexport interface IndexedDbRemoteDocumentCache extends RemoteDocumentCache {\n // The IndexedDbRemoteDocumentCache doesn't implement any methods on top\n // of RemoteDocumentCache. This class exists for consistency.\n}\n\n/**\n * The RemoteDocumentCache for IndexedDb. To construct, invoke\n * `newIndexedDbRemoteDocumentCache()`.\n */\nclass IndexedDbRemoteDocumentCacheImpl implements IndexedDbRemoteDocumentCache {\n indexManager!: IndexManager;\n\n constructor(readonly serializer: LocalSerializer) {}\n\n setIndexManager(indexManager: IndexManager): void {\n this.indexManager = indexManager;\n }\n\n /**\n * Adds the supplied entries to the cache.\n *\n * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n */\n addEntry(\n transaction: PersistenceTransaction,\n key: DocumentKey,\n doc: DbRemoteDocument\n ): PersistencePromise {\n const documentStore = remoteDocumentsStore(transaction);\n return documentStore.put(doc);\n }\n\n /**\n * Removes a document from the cache.\n *\n * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n */\n removeEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey,\n readTime: SnapshotVersion\n ): PersistencePromise {\n const store = remoteDocumentsStore(transaction);\n return store.delete(dbReadTimeKey(documentKey, readTime));\n }\n\n /**\n * Updates the current cache size.\n *\n * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the\n * cache's metadata.\n */\n updateMetadata(\n transaction: PersistenceTransaction,\n sizeDelta: number\n ): PersistencePromise {\n return this.getMetadata(transaction).next(metadata => {\n metadata.byteSize += sizeDelta;\n return this.setMetadata(transaction, metadata);\n });\n }\n\n getEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n let doc = MutableDocument.newInvalidDocument(documentKey);\n return remoteDocumentsStore(transaction)\n .iterate(\n {\n index: DbRemoteDocumentDocumentKeyIndex,\n range: IDBKeyRange.only(dbKey(documentKey))\n },\n (_, dbRemoteDoc) => {\n doc = this.maybeDecodeDocument(documentKey, dbRemoteDoc);\n }\n )\n .next(() => doc);\n }\n\n /**\n * Looks up an entry in the cache.\n *\n * @param documentKey - The key of the entry to look up.\n * @returns The cached document entry and its size.\n */\n getSizedEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n let result = {\n size: 0,\n document: MutableDocument.newInvalidDocument(documentKey)\n };\n return remoteDocumentsStore(transaction)\n .iterate(\n {\n index: DbRemoteDocumentDocumentKeyIndex,\n range: IDBKeyRange.only(dbKey(documentKey))\n },\n (_, dbRemoteDoc) => {\n result = {\n document: this.maybeDecodeDocument(documentKey, dbRemoteDoc),\n size: dbDocumentSize(dbRemoteDoc)\n };\n }\n )\n .next(() => result);\n }\n\n getEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise {\n let results = mutableDocumentMap();\n return this.forEachDbEntry(\n transaction,\n documentKeys,\n (key, dbRemoteDoc) => {\n const doc = this.maybeDecodeDocument(key, dbRemoteDoc);\n results = results.insert(key, doc);\n }\n ).next(() => results);\n }\n\n /**\n * Looks up several entries in the cache.\n *\n * @param documentKeys - The set of keys entries to look up.\n * @returns A map of documents indexed by key and a map of sizes indexed by\n * key (zero if the document does not exist).\n */\n getSizedEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise {\n let results = mutableDocumentMap();\n let sizeMap = new SortedMap(DocumentKey.comparator);\n return this.forEachDbEntry(\n transaction,\n documentKeys,\n (key, dbRemoteDoc) => {\n const doc = this.maybeDecodeDocument(key, dbRemoteDoc);\n results = results.insert(key, doc);\n sizeMap = sizeMap.insert(key, dbDocumentSize(dbRemoteDoc));\n }\n ).next(() => {\n return { documents: results, sizeMap };\n });\n }\n\n private forEachDbEntry(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet,\n callback: (key: DocumentKey, doc: DbRemoteDocument | null) => void\n ): PersistencePromise {\n if (documentKeys.isEmpty()) {\n return PersistencePromise.resolve();\n }\n\n let sortedKeys = new SortedSet(dbKeyComparator);\n documentKeys.forEach(e => (sortedKeys = sortedKeys.add(e)));\n const range = IDBKeyRange.bound(\n dbKey(sortedKeys.first()!),\n dbKey(sortedKeys.last()!)\n );\n const keyIter = sortedKeys.getIterator();\n let nextKey: DocumentKey | null = keyIter.getNext();\n\n return remoteDocumentsStore(transaction)\n .iterate(\n { index: DbRemoteDocumentDocumentKeyIndex, range },\n (_, dbRemoteDoc, control) => {\n const potentialKey = DocumentKey.fromSegments([\n ...dbRemoteDoc.prefixPath,\n dbRemoteDoc.collectionGroup,\n dbRemoteDoc.documentId\n ]);\n\n // Go through keys not found in cache.\n while (nextKey && dbKeyComparator(nextKey!, potentialKey) < 0) {\n callback(nextKey!, null);\n nextKey = keyIter.getNext();\n }\n\n if (nextKey && nextKey!.isEqual(potentialKey)) {\n // Key found in cache.\n callback(nextKey!, dbRemoteDoc);\n nextKey = keyIter.hasNext() ? keyIter.getNext() : null;\n }\n\n // Skip to the next key (if there is one).\n if (nextKey) {\n control.skip(dbKey(nextKey));\n } else {\n control.done();\n }\n }\n )\n .next(() => {\n // The rest of the keys are not in the cache. One case where `iterate`\n // above won't go through them is when the cache is empty.\n while (nextKey) {\n callback(nextKey!, null);\n nextKey = keyIter.hasNext() ? keyIter.getNext() : null;\n }\n });\n }\n\n getDocumentsMatchingQuery(\n transaction: PersistenceTransaction,\n query: Query,\n offset: IndexOffset,\n mutatedDocs: OverlayMap,\n context?: QueryContext\n ): PersistencePromise {\n const collection = query.path;\n const startKey = [\n collection.popLast().toArray(),\n collection.lastSegment(),\n toDbTimestampKey(offset.readTime),\n offset.documentKey.path.isEmpty()\n ? ''\n : offset.documentKey.path.lastSegment()\n ];\n const endKey: DbRemoteDocumentKey = [\n collection.popLast().toArray(),\n collection.lastSegment(),\n [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n ''\n ];\n\n return remoteDocumentsStore(transaction)\n .loadAll(IDBKeyRange.bound(startKey, endKey, true))\n .next(dbRemoteDocs => {\n context?.incrementDocumentReadCount(dbRemoteDocs.length);\n let results = mutableDocumentMap();\n for (const dbRemoteDoc of dbRemoteDocs) {\n const document = this.maybeDecodeDocument(\n DocumentKey.fromSegments(\n dbRemoteDoc.prefixPath.concat(\n dbRemoteDoc.collectionGroup,\n dbRemoteDoc.documentId\n )\n ),\n dbRemoteDoc\n );\n if (\n document.isFoundDocument() &&\n (queryMatches(query, document) || mutatedDocs.has(document.key))\n ) {\n // Either the document matches the given query, or it is mutated.\n results = results.insert(document.key, document);\n }\n }\n return results;\n });\n }\n\n getAllFromCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n offset: IndexOffset,\n limit: number\n ): PersistencePromise {\n debugAssert(limit > 0, 'Limit should be at least 1');\n let results = mutableDocumentMap();\n\n const startKey = dbCollectionGroupKey(collectionGroup, offset);\n const endKey = dbCollectionGroupKey(collectionGroup, IndexOffset.max());\n return remoteDocumentsStore(transaction)\n .iterate(\n {\n index: DbRemoteDocumentCollectionGroupIndex,\n range: IDBKeyRange.bound(startKey, endKey, true)\n },\n (_, dbRemoteDoc, control) => {\n const document = this.maybeDecodeDocument(\n DocumentKey.fromSegments(\n dbRemoteDoc.prefixPath.concat(\n dbRemoteDoc.collectionGroup,\n dbRemoteDoc.documentId\n )\n ),\n dbRemoteDoc\n );\n results = results.insert(document.key, document);\n if (results.size === limit) {\n control.done();\n }\n }\n )\n .next(() => results);\n }\n\n newChangeBuffer(options?: {\n trackRemovals: boolean;\n }): RemoteDocumentChangeBuffer {\n return new IndexedDbRemoteDocumentChangeBuffer(\n this,\n !!options && options.trackRemovals\n );\n }\n\n getSize(txn: PersistenceTransaction): PersistencePromise {\n return this.getMetadata(txn).next(metadata => metadata.byteSize);\n }\n\n private getMetadata(\n txn: PersistenceTransaction\n ): PersistencePromise {\n return documentGlobalStore(txn)\n .get(DbRemoteDocumentGlobalKey)\n .next(metadata => {\n hardAssert(!!metadata, 0x4e35, 'Missing document cache metadata');\n return metadata!;\n });\n }\n\n private setMetadata(\n txn: PersistenceTransaction,\n metadata: DbRemoteDocumentGlobal\n ): PersistencePromise {\n return documentGlobalStore(txn).put(DbRemoteDocumentGlobalKey, metadata);\n }\n\n /**\n * Decodes `dbRemoteDoc` and returns the document (or an invalid document if\n * the document corresponds to the format used for sentinel deletes).\n */\n private maybeDecodeDocument(\n documentKey: DocumentKey,\n dbRemoteDoc: DbRemoteDocument | null\n ): MutableDocument {\n if (dbRemoteDoc) {\n const doc = fromDbRemoteDocument(this.serializer, dbRemoteDoc);\n // Whether the document is a sentinel removal and should only be used in the\n // `getNewDocumentChanges()`\n const isSentinelRemoval =\n doc.isNoDocument() && doc.version.isEqual(SnapshotVersion.min());\n if (!isSentinelRemoval) {\n return doc;\n }\n }\n return MutableDocument.newInvalidDocument(documentKey);\n }\n}\n\n/** Creates a new IndexedDbRemoteDocumentCache. */\nexport function newIndexedDbRemoteDocumentCache(\n serializer: LocalSerializer\n): IndexedDbRemoteDocumentCache {\n return new IndexedDbRemoteDocumentCacheImpl(serializer);\n}\n\n/**\n * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache.\n *\n * Unlike the MemoryRemoteDocumentChangeBuffer, the IndexedDb implementation computes the size\n * delta for all submitted changes. This avoids having to re-read all documents from IndexedDb\n * when we apply the changes.\n */\nclass IndexedDbRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer {\n // A map of document sizes and read times prior to applying the changes in\n // this buffer.\n protected documentStates: ObjectMap<\n DocumentKey,\n { size: number; readTime: SnapshotVersion }\n > = new ObjectMap(\n key => key.toString(),\n (l, r) => l.isEqual(r)\n );\n\n /**\n * @param documentCache - The IndexedDbRemoteDocumentCache to apply the changes to.\n * @param trackRemovals - Whether to create sentinel deletes that can be tracked by\n * `getNewDocumentChanges()`.\n */\n constructor(\n private readonly documentCache: IndexedDbRemoteDocumentCacheImpl,\n private readonly trackRemovals: boolean\n ) {\n super();\n }\n\n protected applyChanges(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n const promises: Array> = [];\n\n let sizeDelta = 0;\n\n let collectionParents = new SortedSet((l, r) =>\n primitiveComparator(l.canonicalString(), r.canonicalString())\n );\n\n this.changes.forEach((key, documentChange) => {\n const previousDoc = this.documentStates.get(key);\n debugAssert(\n previousDoc !== undefined,\n `Cannot modify a document that wasn't read (for ${key})`\n );\n promises.push(\n this.documentCache.removeEntry(transaction, key, previousDoc.readTime)\n );\n if (documentChange.isValidDocument()) {\n debugAssert(\n !documentChange.readTime.isEqual(SnapshotVersion.min()),\n 'Cannot add a document with a read time of zero'\n );\n const doc = toDbRemoteDocument(\n this.documentCache.serializer,\n documentChange\n );\n collectionParents = collectionParents.add(key.path.popLast());\n\n const size = dbDocumentSize(doc);\n sizeDelta += size - previousDoc.size;\n promises.push(this.documentCache.addEntry(transaction, key, doc));\n } else {\n sizeDelta -= previousDoc.size;\n if (this.trackRemovals) {\n // In order to track removals, we store a \"sentinel delete\" in the\n // RemoteDocumentCache. This entry is represented by a NoDocument\n // with a version of 0 and ignored by `maybeDecodeDocument()` but\n // preserved in `getNewDocumentChanges()`.\n const deletedDoc = toDbRemoteDocument(\n this.documentCache.serializer,\n documentChange.convertToNoDocument(SnapshotVersion.min())\n );\n promises.push(\n this.documentCache.addEntry(transaction, key, deletedDoc)\n );\n }\n }\n });\n\n collectionParents.forEach(parent => {\n promises.push(\n this.documentCache.indexManager.addToCollectionParentIndex(\n transaction,\n parent\n )\n );\n });\n\n promises.push(this.documentCache.updateMetadata(transaction, sizeDelta));\n\n return PersistencePromise.waitFor(promises);\n }\n\n protected getFromCache(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n // Record the size of everything we load from the cache so we can compute a delta later.\n return this.documentCache\n .getSizedEntry(transaction, documentKey)\n .next(getResult => {\n this.documentStates.set(documentKey, {\n size: getResult.size,\n readTime: getResult.document.readTime\n });\n return getResult.document;\n });\n }\n\n protected getAllFromCache(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise {\n // Record the size of everything we load from the cache so we can compute\n // a delta later.\n return this.documentCache\n .getSizedEntries(transaction, documentKeys)\n .next(({ documents, sizeMap }) => {\n // Note: `getAllFromCache` returns two maps instead of a single map from\n // keys to `DocumentSizeEntry`s. This is to allow returning the\n // `MutableDocumentMap` directly, without a conversion.\n sizeMap.forEach((documentKey, size) => {\n this.documentStates.set(documentKey, {\n size,\n readTime: documents.get(documentKey)!.readTime\n });\n });\n return documents;\n });\n }\n}\n\nfunction documentGlobalStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbRemoteDocumentGlobalStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the remoteDocuments object store.\n */\nfunction remoteDocumentsStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbRemoteDocumentStore\n );\n}\n\n/**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentKeyIndex` index.\n */\nfunction dbKey(documentKey: DocumentKey): [string[], string, string] {\n const path = documentKey.path.toArray();\n return [\n /* prefix path */ path.slice(0, path.length - 2),\n /* collection id */ path[path.length - 2],\n /* document id */ path[path.length - 1]\n ];\n}\n\n/**\n * Returns a key that can be used for document lookups via the primary key of\n * the DbRemoteDocument object store.\n */\nfunction dbReadTimeKey(\n documentKey: DocumentKey,\n readTime: SnapshotVersion\n): DbRemoteDocumentKey {\n const path = documentKey.path.toArray();\n return [\n /* prefix path */ path.slice(0, path.length - 2),\n /* collection id */ path[path.length - 2],\n toDbTimestampKey(readTime),\n /* document id */ path[path.length - 1]\n ];\n}\n\n/**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentCollectionGroupIndex` index.\n */\nfunction dbCollectionGroupKey(\n collectionGroup: string,\n offset: IndexOffset\n): [string, DbTimestampKey, string[], string] {\n const path = offset.documentKey.path.toArray();\n return [\n /* collection id */ collectionGroup,\n toDbTimestampKey(offset.readTime),\n /* prefix path */ path.slice(0, path.length - 2),\n /* document id */ path.length > 0 ? path[path.length - 1] : ''\n ];\n}\n\n/**\n * Comparator that compares document keys according to the primary key sorting\n * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id\n * and then document ID).\n *\n * Visible for testing.\n */\nexport function dbKeyComparator(l: DocumentKey, r: DocumentKey): number {\n const left = l.path.toArray();\n const right = r.path.toArray();\n\n // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74\n let cmp = 0;\n for (let i = 0; i < left.length - 2 && i < right.length - 2; ++i) {\n cmp = primitiveComparator(left[i], right[i]);\n if (cmp) {\n return cmp;\n }\n }\n\n cmp = primitiveComparator(left.length, right.length);\n if (cmp) {\n return cmp;\n }\n\n cmp = primitiveComparator(left[left.length - 2], right[right.length - 2]);\n if (cmp) {\n return cmp;\n }\n\n // TODO(b/329441702): Document IDs should be sorted by UTF-8 encoded byte\n // order, but IndexedDB sorts strings lexicographically. Document ID\n // comparison here still relies on primitive comparison to avoid mismatches\n // observed in snapshot listeners with Unicode characters in documentIds\n return primitiveComparator(left[left.length - 1], right[right.length - 1]);\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Document } from '../model/document';\nimport { FieldMask } from '../model/field_mask';\n\n/**\n * Represents a local view (overlay) of a document, and the fields that are\n * locally mutated.\n */\nexport class OverlayedDocument {\n constructor(\n readonly overlayedDocument: Document,\n\n /**\n * The fields that are locally mutated by patch mutations.\n *\n * If the overlayed\tdocument is from set or delete mutations, this is `null`.\n * If there is no overlay (mutation) for the document, this is an empty `FieldMask`.\n */\n readonly mutatedFields: FieldMask | null\n ) {}\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n asCollectionQueryAtPath,\n isCollectionGroupQuery,\n isDocumentQuery,\n Query,\n queryMatches\n} from '../core/query';\nimport { Timestamp } from '../lite-api/timestamp';\nimport {\n DocumentKeySet,\n OverlayMap,\n DocumentMap,\n MutableDocumentMap,\n newDocumentKeyMap,\n newMutationMap,\n newOverlayMap,\n documentMap,\n mutableDocumentMap,\n documentKeySet,\n DocumentKeyMap,\n convertOverlayedDocumentMapToDocumentMap,\n OverlayedDocumentMap,\n newOverlayedDocumentMap\n} from '../model/collections';\nimport { Document, MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { IndexOffset, INITIAL_LARGEST_BATCH_ID } from '../model/field_index';\nimport { FieldMask } from '../model/field_mask';\nimport {\n calculateOverlayMutation,\n mutationApplyToLocalView,\n PatchMutation\n} from '../model/mutation';\nimport { Overlay } from '../model/overlay';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert } from '../util/assert';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { IndexManager } from './index_manager';\nimport { LocalWriteResult } from './local_store_impl';\nimport { MutationQueue } from './mutation_queue';\nimport { OverlayedDocument } from './overlayed_document';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { QueryContext } from './query_context';\nimport { RemoteDocumentCache } from './remote_document_cache';\n\n/**\n * A readonly view of the local state of all documents we're tracking (i.e. we\n * have a cached version in remoteDocumentCache or local mutations for the\n * document). The view is computed by applying the mutations in the\n * MutationQueue to the RemoteDocumentCache.\n */\nexport class LocalDocumentsView {\n constructor(\n readonly remoteDocumentCache: RemoteDocumentCache,\n readonly mutationQueue: MutationQueue,\n readonly documentOverlayCache: DocumentOverlayCache,\n readonly indexManager: IndexManager\n ) {}\n\n /**\n * Get the local view of the document identified by `key`.\n *\n * @returns Local view of the document or null if we don't have any cached\n * state for it.\n */\n getDocument(\n transaction: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\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 *

+ */ +function setLogLevel(logLevel) { + logClient.setLogLevel(logLevel); +} +function logDebug(msg, ...obj) { + if (logClient.logLevel <= logger.LogLevel.DEBUG) { + const args = obj.map(argToString); + logClient.debug(`Firestore (${SDK_VERSION}): ${msg}`, ...args); + } +} +function logError(msg, ...obj) { + if (logClient.logLevel <= logger.LogLevel.ERROR) { + const args = obj.map(argToString); + logClient.error(`Firestore (${SDK_VERSION}): ${msg}`, ...args); + } +} +/** + * @internal + */ +function logWarn(msg, ...obj) { + if (logClient.logLevel <= logger.LogLevel.WARN) { + const args = obj.map(argToString); + logClient.warn(`Firestore (${SDK_VERSION}): ${msg}`, ...args); + } +} +/** + * Converts an additional log parameter to a string representation. + */ +function argToString(obj) { + if (typeof obj === 'string') { + return obj; + } + else { + try { + return formatJSON(obj); + } + catch (e) { + // Converting to JSON failed, just log the object directly + return obj; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function fail(id, messageOrContext, context) { + let message = 'Unexpected state'; + if (typeof messageOrContext === 'string') { + message = messageOrContext; + } + else { + context = messageOrContext; + } + _fail(id, message, context); +} +function _fail(id, failure, context) { + // Log the failure in addition to throw an exception, just in case the + // exception is swallowed. + let message = `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ${failure} (ID: ${id.toString(16)})`; + if (context !== undefined) { + try { + const stringContext = JSON.stringify(context); + message += ' CONTEXT: ' + stringContext; + } + catch (e) { + message += ' CONTEXT: ' + context; + } + } + logError(message); + // NOTE: We don't use FirestoreError here because these are internal failures + // that cannot be handled by the user. (Also it would create a circular + // dependency between the error and assert modules which doesn't work.) + throw new Error(message); +} +function hardAssert(assertion, id, messageOrContext, context) { + let message = 'Unexpected state'; + if (typeof messageOrContext === 'string') { + message = messageOrContext; + } + else { + context = messageOrContext; + } + if (!assertion) { + _fail(id, message, context); + } +} +/** + * Fails if the given assertion condition is false, throwing an Error with the + * given message if it did. + * + * The code of callsites invoking this function are stripped out in production + * builds. Any side-effects of code within the debugAssert() invocation will not + * happen in this case. + * + * @internal + */ +function debugAssert(assertion, message) { + if (!assertion) { + fail(0xdeb6, message); + } +} +/** + * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an + * instance of `T` before casting. + */ +function debugCast(obj, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +constructor) { + return obj; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const Code = { + // Causes are copied from: + // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h + /** Not an error; returned on success. */ + OK: 'ok', + /** The operation was cancelled (typically by the caller). */ + CANCELLED: 'cancelled', + /** Unknown error or an error from a different error domain. */ + UNKNOWN: 'unknown', + /** + * Client specified an invalid argument. Note that this differs from + * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are + * problematic regardless of the state of the system (e.g., a malformed file + * name). + */ + INVALID_ARGUMENT: 'invalid-argument', + /** + * Deadline expired before operation could complete. For operations that + * change the state of the system, this error may be returned even if the + * operation has completed successfully. For example, a successful response + * from a server could have been delayed long enough for the deadline to + * expire. + */ + DEADLINE_EXCEEDED: 'deadline-exceeded', + /** Some requested entity (e.g., file or directory) was not found. */ + NOT_FOUND: 'not-found', + /** + * Some entity that we attempted to create (e.g., file or directory) already + * exists. + */ + ALREADY_EXISTS: 'already-exists', + /** + * The caller does not have permission to execute the specified operation. + * PERMISSION_DENIED must not be used for rejections caused by exhausting + * some resource (use RESOURCE_EXHAUSTED instead for those errors). + * PERMISSION_DENIED must not be used if the caller cannot be identified + * (use UNAUTHENTICATED instead for those errors). + */ + PERMISSION_DENIED: 'permission-denied', + /** + * The request does not have valid authentication credentials for the + * operation. + */ + UNAUTHENTICATED: 'unauthenticated', + /** + * Some resource has been exhausted, perhaps a per-user quota, or perhaps the + * entire file system is out of space. + */ + RESOURCE_EXHAUSTED: 'resource-exhausted', + /** + * Operation was rejected because the system is not in a state required for + * the operation's execution. For example, directory to be deleted may be + * non-empty, an rmdir operation is applied to a non-directory, etc. + * + * A litmus test that may help a service implementor in deciding + * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: + * (a) Use UNAVAILABLE if the client can retry just the failing call. + * (b) Use ABORTED if the client should retry at a higher-level + * (e.g., restarting a read-modify-write sequence). + * (c) Use FAILED_PRECONDITION if the client should not retry until + * the system state has been explicitly fixed. E.g., if an "rmdir" + * fails because the directory is non-empty, FAILED_PRECONDITION + * should be returned since the client should not retry unless + * they have first fixed up the directory by deleting files from it. + * (d) Use FAILED_PRECONDITION if the client performs conditional + * REST Get/Update/Delete on a resource and the resource on the + * server does not match the condition. E.g., conflicting + * read-modify-write on the same resource. + */ + FAILED_PRECONDITION: 'failed-precondition', + /** + * The operation was aborted, typically due to a concurrency issue like + * sequencer check failures, transaction aborts, etc. + * + * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, + * and UNAVAILABLE. + */ + ABORTED: 'aborted', + /** + * Operation was attempted past the valid range. E.g., seeking or reading + * past end of file. + * + * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed + * if the system state changes. For example, a 32-bit file system will + * generate INVALID_ARGUMENT if asked to read at an offset that is not in the + * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from + * an offset past the current file size. + * + * There is a fair bit of overlap between FAILED_PRECONDITION and + * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) + * when it applies so that callers who are iterating through a space can + * easily look for an OUT_OF_RANGE error to detect when they are done. + */ + OUT_OF_RANGE: 'out-of-range', + /** Operation is not implemented or not supported/enabled in this service. */ + UNIMPLEMENTED: 'unimplemented', + /** + * Internal errors. Means some invariants expected by underlying System has + * been broken. If you see one of these errors, Something is very broken. + */ + INTERNAL: 'internal', + /** + * The service is currently unavailable. This is a most likely a transient + * condition and may be corrected by retrying with a backoff. + * + * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, + * and UNAVAILABLE. + */ + UNAVAILABLE: 'unavailable', + /** Unrecoverable data loss or corruption. */ + DATA_LOSS: 'data-loss' +}; +/** An error returned by a Firestore operation. */ +class FirestoreError extends util.FirebaseError { + /** @hideconstructor */ + constructor( + /** + * The backend error code associated with this error. + */ + code, + /** + * A custom error description. + */ + message) { + super(code, message); + this.code = code; + this.message = message; + // HACK: We write a toString property directly because Error is not a real + // class and so inheritance does not work correctly. We could alternatively + // do the same "back-door inheritance" trick that FirebaseError does. + this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Deferred { + constructor() { + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + }); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class OAuthToken { + constructor(value, user) { + this.user = user; + this.type = 'OAuth'; + this.headers = new Map(); + this.headers.set('Authorization', `Bearer ${value}`); + } +} +/** + * A CredentialsProvider that always yields an empty token. + * @internal + */ +class EmptyAuthCredentialsProvider { + getToken() { + return Promise.resolve(null); + } + invalidateToken() { } + start(asyncQueue, changeListener) { + // Fire with initial user. + asyncQueue.enqueueRetryable(() => changeListener(User.UNAUTHENTICATED)); + } + shutdown() { } +} +/** + * A CredentialsProvider that always returns a constant token. Used for + * emulator token mocking. + */ +class EmulatorAuthCredentialsProvider { + constructor(token) { + this.token = token; + /** + * Stores the listener registered with setChangeListener() + * This isn't actually necessary since the UID never changes, but we use this + * to verify the listen contract is adhered to in tests. + */ + this.changeListener = null; + } + getToken() { + return Promise.resolve(this.token); + } + invalidateToken() { } + start(asyncQueue, changeListener) { + this.changeListener = changeListener; + // Fire with initial user. + asyncQueue.enqueueRetryable(() => changeListener(this.token.user)); + } + shutdown() { + this.changeListener = null; + } +} +class FirebaseAuthCredentialsProvider { + constructor(authProvider) { + this.authProvider = authProvider; + /** Tracks the current User. */ + this.currentUser = User.UNAUTHENTICATED; + /** + * Counter used to detect if the token changed while a getToken request was + * outstanding. + */ + this.tokenCounter = 0; + this.forceRefresh = false; + this.auth = null; + } + start(asyncQueue, changeListener) { + hardAssert(this.tokenListener === undefined, 0xa540); + let lastTokenId = this.tokenCounter; + // A change listener that prevents double-firing for the same token change. + const guardedChangeListener = user => { + if (this.tokenCounter !== lastTokenId) { + lastTokenId = this.tokenCounter; + return changeListener(user); + } + else { + return Promise.resolve(); + } + }; + // A promise that can be waited on to block on the next token change. + // This promise is re-created after each change. + let nextToken = new Deferred(); + this.tokenListener = () => { + this.tokenCounter++; + this.currentUser = this.getUser(); + nextToken.resolve(); + nextToken = new Deferred(); + asyncQueue.enqueueRetryable(() => guardedChangeListener(this.currentUser)); + }; + const awaitNextToken = () => { + const currentTokenAttempt = nextToken; + asyncQueue.enqueueRetryable(async () => { + await currentTokenAttempt.promise; + await guardedChangeListener(this.currentUser); + }); + }; + const registerAuth = (auth) => { + logDebug('FirebaseAuthCredentialsProvider', 'Auth detected'); + this.auth = auth; + if (this.tokenListener) { + this.auth.addAuthTokenListener(this.tokenListener); + awaitNextToken(); + } + }; + this.authProvider.onInit(auth => registerAuth(auth)); + // Our users can initialize Auth right after Firestore, so we give it + // a chance to register itself with the component framework before we + // determine whether to start up in unauthenticated mode. + setTimeout(() => { + if (!this.auth) { + const auth = this.authProvider.getImmediate({ optional: true }); + if (auth) { + registerAuth(auth); + } + else { + // If auth is still not available, proceed with `null` user + logDebug('FirebaseAuthCredentialsProvider', 'Auth not yet detected'); + nextToken.resolve(); + nextToken = new Deferred(); + } + } + }, 0); + awaitNextToken(); + } + getToken() { + // Take note of the current value of the tokenCounter so that this method + // can fail (with an ABORTED error) if there is a token change while the + // request is outstanding. + const initialTokenCounter = this.tokenCounter; + const forceRefresh = this.forceRefresh; + this.forceRefresh = false; + if (!this.auth) { + return Promise.resolve(null); + } + return this.auth.getToken(forceRefresh).then(tokenData => { + // Cancel the request since the token changed while the request was + // outstanding so the response is potentially for a previous user (which + // user, we can't be sure). + if (this.tokenCounter !== initialTokenCounter) { + logDebug('FirebaseAuthCredentialsProvider', 'getToken aborted due to token change.'); + return this.getToken(); + } + else { + if (tokenData) { + hardAssert(typeof tokenData.accessToken === 'string', 0x7c5d, { tokenData }); + return new OAuthToken(tokenData.accessToken, this.currentUser); + } + else { + return null; + } + } + }); + } + invalidateToken() { + this.forceRefresh = true; + } + shutdown() { + if (this.auth && this.tokenListener) { + this.auth.removeAuthTokenListener(this.tokenListener); + } + this.tokenListener = undefined; + } + // Auth.getUid() can return null even with a user logged in. It is because + // getUid() is synchronous, but the auth code populating Uid is asynchronous. + // This method should only be called in the AuthTokenListener callback + // to guarantee to get the actual user. + getUser() { + const currentUid = this.auth && this.auth.getUid(); + hardAssert(currentUid === null || typeof currentUid === 'string', 0x0807, { currentUid }); + return new User(currentUid); + } +} +/* + * FirstPartyToken provides a fresh token each time its value + * is requested, because if the token is too old, requests will be rejected. + * Technically this may no longer be necessary since the SDK should gracefully + * recover from unauthenticated errors (see b/33147818 for context), but it's + * safer to keep the implementation as-is. + */ +class FirstPartyToken { + constructor(sessionIndex, iamToken, authTokenFactory) { + this.sessionIndex = sessionIndex; + this.iamToken = iamToken; + this.authTokenFactory = authTokenFactory; + this.type = 'FirstParty'; + this.user = User.FIRST_PARTY; + this._headers = new Map(); + } + /** + * Gets an authorization token, using a provided factory function, or return + * null. + */ + getAuthToken() { + if (this.authTokenFactory) { + return this.authTokenFactory(); + } + else { + return null; + } + } + get headers() { + this._headers.set('X-Goog-AuthUser', this.sessionIndex); + // Use array notation to prevent minification + const authHeaderTokenValue = this.getAuthToken(); + if (authHeaderTokenValue) { + this._headers.set('Authorization', authHeaderTokenValue); + } + if (this.iamToken) { + this._headers.set('X-Goog-Iam-Authorization-Token', this.iamToken); + } + return this._headers; + } +} +/* + * Provides user credentials required for the Firestore JavaScript SDK + * to authenticate the user, using technique that is only available + * to applications hosted by Google. + */ +class FirstPartyAuthCredentialsProvider { + constructor(sessionIndex, iamToken, authTokenFactory) { + this.sessionIndex = sessionIndex; + this.iamToken = iamToken; + this.authTokenFactory = authTokenFactory; + } + getToken() { + return Promise.resolve(new FirstPartyToken(this.sessionIndex, this.iamToken, this.authTokenFactory)); + } + start(asyncQueue, changeListener) { + // Fire with initial uid. + asyncQueue.enqueueRetryable(() => changeListener(User.FIRST_PARTY)); + } + shutdown() { } + invalidateToken() { } +} +class AppCheckToken { + constructor(value) { + this.value = value; + this.type = 'AppCheck'; + this.headers = new Map(); + if (value && value.length > 0) { + this.headers.set('x-firebase-appcheck', this.value); + } + } +} +class FirebaseAppCheckTokenProvider { + constructor(app$1, appCheckProvider) { + this.appCheckProvider = appCheckProvider; + this.forceRefresh = false; + this.appCheck = null; + this.latestAppCheckToken = null; + this.serverAppAppCheckToken = null; + if (app._isFirebaseServerApp(app$1) && app$1.settings.appCheckToken) { + this.serverAppAppCheckToken = app$1.settings.appCheckToken; + } + } + start(asyncQueue, changeListener) { + hardAssert(this.tokenListener === undefined, 0x0db8); + const onTokenChanged = tokenResult => { + if (tokenResult.error != null) { + logDebug('FirebaseAppCheckTokenProvider', `Error getting App Check token; using placeholder token instead. Error: ${tokenResult.error.message}`); + } + const tokenUpdated = tokenResult.token !== this.latestAppCheckToken; + this.latestAppCheckToken = tokenResult.token; + logDebug('FirebaseAppCheckTokenProvider', `Received ${tokenUpdated ? 'new' : 'existing'} token.`); + return tokenUpdated + ? changeListener(tokenResult.token) + : Promise.resolve(); + }; + this.tokenListener = (tokenResult) => { + asyncQueue.enqueueRetryable(() => onTokenChanged(tokenResult)); + }; + const registerAppCheck = (appCheck) => { + logDebug('FirebaseAppCheckTokenProvider', 'AppCheck detected'); + this.appCheck = appCheck; + if (this.tokenListener) { + this.appCheck.addTokenListener(this.tokenListener); + } + }; + this.appCheckProvider.onInit(appCheck => registerAppCheck(appCheck)); + // Our users can initialize AppCheck after Firestore, so we give it + // a chance to register itself with the component framework. + setTimeout(() => { + if (!this.appCheck) { + const appCheck = this.appCheckProvider.getImmediate({ optional: true }); + if (appCheck) { + registerAppCheck(appCheck); + } + else { + // If AppCheck is still not available, proceed without it. + logDebug('FirebaseAppCheckTokenProvider', 'AppCheck not yet detected'); + } + } + }, 0); + } + getToken() { + if (this.serverAppAppCheckToken) { + return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken)); + } + const forceRefresh = this.forceRefresh; + this.forceRefresh = false; + if (!this.appCheck) { + return Promise.resolve(null); + } + return this.appCheck.getToken(forceRefresh).then(tokenResult => { + if (tokenResult) { + hardAssert(typeof tokenResult.token === 'string', 0xae0e, { tokenResult }); + this.latestAppCheckToken = tokenResult.token; + return new AppCheckToken(tokenResult.token); + } + else { + return null; + } + }); + } + invalidateToken() { + this.forceRefresh = true; + } + shutdown() { + if (this.appCheck && this.tokenListener) { + this.appCheck.removeTokenListener(this.tokenListener); + } + this.tokenListener = undefined; + } +} +/** + * An AppCheck token provider that always yields an empty token. + * @internal + */ +class EmptyAppCheckTokenProvider { + getToken() { + return Promise.resolve(new AppCheckToken('')); + } + invalidateToken() { } + start(asyncQueue, changeListener) { } + shutdown() { } +} +/** + * Builds a CredentialsProvider depending on the type of + * the credentials passed in. + */ +function makeAuthCredentialsProvider(credentials) { + if (!credentials) { + return new EmptyAuthCredentialsProvider(); + } + switch (credentials['type']) { + case 'firstParty': + return new FirstPartyAuthCredentialsProvider(credentials['sessionIndex'] || '0', credentials['iamToken'] || null, credentials['authTokenFactory'] || null); + case 'provider': + return credentials['client']; + default: + throw new FirestoreError(Code.INVALID_ARGUMENT, 'makeAuthCredentialsProvider failed due to invalid credential type'); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Generates `nBytes` of random bytes. + * + * If `nBytes < 0` , an error will be thrown. + */ +function randomBytes(nBytes) { + return crypto.randomBytes(nBytes); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A utility class for generating unique alphanumeric IDs of a specified length. + * + * @internal + * Exported internally for testing purposes. + */ +class AutoId { + static newId() { + // Alphanumeric characters + const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + // The largest byte value that is a multiple of `char.length`. + const maxMultiple = Math.floor(256 / chars.length) * chars.length; + let autoId = ''; + const targetLength = 20; + while (autoId.length < targetLength) { + const bytes = randomBytes(40); + for (let i = 0; i < bytes.length; ++i) { + // Only accept values that are [0, maxMultiple), this ensures they can + // be evenly mapped to indices of `chars` via a modulo operation. + if (autoId.length < targetLength && bytes[i] < maxMultiple) { + autoId += chars.charAt(bytes[i] % chars.length); + } + } + } + return autoId; + } +} +function primitiveComparator(left, right) { + if (left < right) { + return -1; + } + if (left > right) { + return 1; + } + return 0; +} +/** Compare strings in UTF-8 encoded byte order */ +function compareUtf8Strings(left, right) { + // Find the first differing character (a.k.a. "UTF-16 code unit") in the two strings and, + // if found, use that character to determine the relative ordering of the two strings as a + // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by + // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8 + // and UTF-16 happen to represent Unicode code points. + // + // After finding the first pair of differing characters, there are two cases: + // + // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or + // both are surrogates from a surrogate pair (that collectively represent code points greater + // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the + // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is + // sufficient. + // + // Case 2: One character is a surrogate and the other is not. In this case the surrogate- + // containing string is always ordered after the non-surrogate. This is because surrogates are + // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations + // and are lexicographically greater than the 1, 2, or 3-byte representations of code points + // less than or equal to 0xFFFF. + // + // An example of why Case 2 is required is comparing the following two Unicode code points: + // + // |-----------------------|------------|---------------------|-----------------| + // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding | + // |-----------------------|------------|---------------------|-----------------| + // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD | + // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 | + // |-----------------------|------------|---------------------|-----------------| + // + // A lexicographical comparison of the UTF-8 encodings of these code points would order + // "Replacement Character" _before_ "Grinning Face" because 0xEF is less than 0xF0. However, a + // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously + // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out, + // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate + // pair with those that do not. + const length = Math.min(left.length, right.length); + for (let i = 0; i < length; i++) { + const leftChar = left.charAt(i); + const rightChar = right.charAt(i); + if (leftChar !== rightChar) { + return isSurrogate(leftChar) === isSurrogate(rightChar) + ? primitiveComparator(leftChar, rightChar) + : isSurrogate(leftChar) + ? 1 + : -1; + } + } + // Use the lengths of the strings to determine the overall comparison result since either the + // strings were equal or one is a prefix of the other. + return primitiveComparator(left.length, right.length); +} +const MIN_SURROGATE$1 = 0xd800; +const MAX_SURROGATE$1 = 0xdfff; +function isSurrogate(s) { + const c = s.charCodeAt(0); + return c >= MIN_SURROGATE$1 && c <= MAX_SURROGATE$1; +} +/** Helper to compare arrays using isEqual(). */ +function arrayEquals(left, right, comparator) { + if (left.length !== right.length) { + return false; + } + return left.every((value, index) => comparator(value, right[index])); +} +/** + * Returns the immediate lexicographically-following string. This is useful to + * construct an inclusive range for indexeddb iterators. + */ +function immediateSuccessor(s) { + // Return the input string, with an additional NUL byte appended. + return s + '\0'; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const DOCUMENT_KEY_NAME = '__name__'; +/** + * Path represents an ordered sequence of string segments. + */ +class BasePath { + constructor(segments, offset, length) { + if (offset === undefined) { + offset = 0; + } + else if (offset > segments.length) { + fail(0x027d, { + offset, + range: segments.length + }); + } + if (length === undefined) { + length = segments.length - offset; + } + else if (length > segments.length - offset) { + fail(0x06d2, { + length, + range: segments.length - offset + }); + } + this.segments = segments; + this.offset = offset; + this.len = length; + } + get length() { + return this.len; + } + isEqual(other) { + return BasePath.comparator(this, other) === 0; + } + child(nameOrPath) { + const segments = this.segments.slice(this.offset, this.limit()); + if (nameOrPath instanceof BasePath) { + nameOrPath.forEach(segment => { + segments.push(segment); + }); + } + else { + segments.push(nameOrPath); + } + return this.construct(segments); + } + /** The index of one past the last segment of the path. */ + limit() { + return this.offset + this.length; + } + popFirst(size) { + size = size === undefined ? 1 : size; + return this.construct(this.segments, this.offset + size, this.length - size); + } + popLast() { + return this.construct(this.segments, this.offset, this.length - 1); + } + firstSegment() { + return this.segments[this.offset]; + } + lastSegment() { + return this.get(this.length - 1); + } + get(index) { + return this.segments[this.offset + index]; + } + isEmpty() { + return this.length === 0; + } + isPrefixOf(other) { + if (other.length < this.length) { + return false; + } + for (let i = 0; i < this.length; i++) { + if (this.get(i) !== other.get(i)) { + return false; + } + } + return true; + } + isImmediateParentOf(potentialChild) { + if (this.length + 1 !== potentialChild.length) { + return false; + } + for (let i = 0; i < this.length; i++) { + if (this.get(i) !== potentialChild.get(i)) { + return false; + } + } + return true; + } + forEach(fn) { + for (let i = this.offset, end = this.limit(); i < end; i++) { + fn(this.segments[i]); + } + } + toArray() { + return this.segments.slice(this.offset, this.limit()); + } + /** + * Compare 2 paths segment by segment, prioritizing numeric IDs + * (e.g., "__id123__") in numeric ascending order, followed by string + * segments in lexicographical order. + */ + static comparator(p1, p2) { + const len = Math.min(p1.length, p2.length); + for (let i = 0; i < len; i++) { + const comparison = BasePath.compareSegments(p1.get(i), p2.get(i)); + if (comparison !== 0) { + return comparison; + } + } + return primitiveComparator(p1.length, p2.length); + } + static compareSegments(lhs, rhs) { + const isLhsNumeric = BasePath.isNumericId(lhs); + const isRhsNumeric = BasePath.isNumericId(rhs); + if (isLhsNumeric && !isRhsNumeric) { + // Only lhs is numeric + return -1; + } + else if (!isLhsNumeric && isRhsNumeric) { + // Only rhs is numeric + return 1; + } + else if (isLhsNumeric && isRhsNumeric) { + // both numeric + return BasePath.extractNumericId(lhs).compare(BasePath.extractNumericId(rhs)); + } + else { + // both non-numeric + return compareUtf8Strings(lhs, rhs); + } + } + // Checks if a segment is a numeric ID (starts with "__id" and ends with "__"). + static isNumericId(segment) { + return segment.startsWith('__id') && segment.endsWith('__'); + } + static extractNumericId(segment) { + return bloomBlob.Integer.fromString(segment.substring(4, segment.length - 2)); + } +} +/** + * A slash-separated path for navigating resources (documents and collections) + * within Firestore. + * + * @internal + */ +class ResourcePath extends BasePath { + construct(segments, offset, length) { + return new ResourcePath(segments, offset, length); + } + canonicalString() { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + return this.toArray().join('/'); + } + toString() { + return this.canonicalString(); + } + /** + * Returns a string representation of this path + * where each path segment has been encoded with + * `encodeURIComponent`. + */ + toUriEncodedString() { + return this.toArray().map(encodeURIComponent).join('/'); + } + /** + * Creates a resource path from the given slash-delimited string. If multiple + * arguments are provided, all components are combined. Leading and trailing + * slashes from all components are ignored. + */ + static fromString(...pathComponents) { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + const segments = []; + for (const path of pathComponents) { + if (path.indexOf('//') >= 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid segment (${path}). Paths must not contain // in them.`); + } + // Strip leading and trailing slashed. + segments.push(...path.split('/').filter(segment => segment.length > 0)); + } + return new ResourcePath(segments); + } + static emptyPath() { + return new ResourcePath([]); + } +} +const identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/; +/** + * A dot-separated path for navigating sub-objects within a document. + * @internal + */ +class FieldPath$1 extends BasePath { + construct(segments, offset, length) { + return new FieldPath$1(segments, offset, length); + } + /** + * Returns true if the string could be used as a segment in a field path + * without escaping. + */ + static isValidIdentifier(segment) { + return identifierRegExp.test(segment); + } + canonicalString() { + return this.toArray() + .map(str => { + str = str.replace(/\\/g, '\\\\').replace(/`/g, '\\`'); + if (!FieldPath$1.isValidIdentifier(str)) { + str = '`' + str + '`'; + } + return str; + }) + .join('.'); + } + toString() { + return this.canonicalString(); + } + /** + * Returns true if this field references the key of a document. + */ + isKeyField() { + return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME; + } + /** + * The field designating the key of a document. + */ + static keyField() { + return new FieldPath$1([DOCUMENT_KEY_NAME]); + } + /** + * Parses a field string from the given server-formatted string. + * + * - Splitting the empty string is not allowed (for now at least). + * - Empty segments within the string (e.g. if there are two consecutive + * separators) are not allowed. + * + * TODO(b/37244157): we should make this more strict. Right now, it allows + * non-identifier path components, even if they aren't escaped. + */ + static fromServerFormat(path) { + const segments = []; + let current = ''; + let i = 0; + const addCurrentSegment = () => { + if (current.length === 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid field path (${path}). Paths must not be empty, begin ` + + `with '.', end with '.', or contain '..'`); + } + segments.push(current); + current = ''; + }; + let inBackticks = false; + while (i < path.length) { + const c = path[i]; + if (c === '\\') { + if (i + 1 === path.length) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has trailing escape character: ' + path); + } + const next = path[i + 1]; + if (!(next === '\\' || next === '.' || next === '`')) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has invalid escape sequence: ' + path); + } + current += next; + i += 2; + } + else if (c === '`') { + inBackticks = !inBackticks; + i++; + } + else if (c === '.' && !inBackticks) { + addCurrentSegment(); + i++; + } + else { + current += c; + i++; + } + } + addCurrentSegment(); + if (inBackticks) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Unterminated ` in path: ' + path); + } + return new FieldPath$1(segments); + } + static emptyPath() { + return new FieldPath$1([]); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @internal + */ +class DocumentKey { + constructor(path) { + this.path = path; + } + static fromPath(path) { + return new DocumentKey(ResourcePath.fromString(path)); + } + static fromName(name) { + return new DocumentKey(ResourcePath.fromString(name).popFirst(5)); + } + static empty() { + return new DocumentKey(ResourcePath.emptyPath()); + } + get collectionGroup() { + return this.path.popLast().lastSegment(); + } + /** Returns true if the document is in the specified collectionId. */ + hasCollectionId(collectionId) { + return (this.path.length >= 2 && + this.path.get(this.path.length - 2) === collectionId); + } + /** Returns the collection group (i.e. the name of the parent collection) for this key. */ + getCollectionGroup() { + return this.path.get(this.path.length - 2); + } + /** Returns the fully qualified path to the parent collection. */ + getCollectionPath() { + return this.path.popLast(); + } + isEqual(other) { + return (other !== null && ResourcePath.comparator(this.path, other.path) === 0); + } + toString() { + return this.path.toString(); + } + static comparator(k1, k2) { + return ResourcePath.comparator(k1.path, k2.path); + } + static isDocumentKey(path) { + return path.length % 2 === 0; + } + /** + * Creates and returns a new document key with the given segments. + * + * @param segments - The segments of the path to the document + * @returns A new instance of DocumentKey + */ + static fromSegments(segments) { + return new DocumentKey(new ResourcePath(segments.slice())); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function validateNonEmptyArgument(functionName, argumentName, argument) { + if (!argument) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${functionName}() cannot be called with an empty ${argumentName}.`); + } +} +/** + * Validates that two boolean options are not set at the same time. + * @internal + */ +function validateIsNotUsedTogether(optionName1, argument1, optionName2, argument2) { + if (argument1 === true && argument2 === true) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `${optionName1} and ${optionName2} cannot be used together.`); + } +} +/** + * Validates that `path` refers to a document (indicated by the fact it contains + * an even numbers of segments). + */ +function validateDocumentPath(path) { + if (!DocumentKey.isDocumentKey(path)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid document reference. Document references must have an even number of segments, but ${path} has ${path.length}.`); + } +} +/** + * Validates that `path` refers to a collection (indicated by the fact it + * contains an odd numbers of segments). + */ +function validateCollectionPath(path) { + if (DocumentKey.isDocumentKey(path)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid collection reference. Collection references must have an odd number of segments, but ${path} has ${path.length}.`); + } +} +/** + * Returns true if it's a non-null object without a custom prototype + * (i.e. excludes Array, Date, etc.). + */ +function isPlainObject(input) { + return (typeof input === 'object' && + input !== null && + (Object.getPrototypeOf(input) === Object.prototype || + Object.getPrototypeOf(input) === null)); +} +/** Returns a string describing the type / value of the provided input. */ +function valueDescription(input) { + if (input === undefined) { + return 'undefined'; + } + else if (input === null) { + return 'null'; + } + else if (typeof input === 'string') { + if (input.length > 20) { + input = `${input.substring(0, 20)}...`; + } + return JSON.stringify(input); + } + else if (typeof input === 'number' || typeof input === 'boolean') { + return '' + input; + } + else if (typeof input === 'object') { + if (input instanceof Array) { + return 'an array'; + } + else { + const customObjectName = tryGetCustomObjectType(input); + if (customObjectName) { + return `a custom ${customObjectName} object`; + } + else { + return 'an object'; + } + } + } + else if (typeof input === 'function') { + return 'a function'; + } + else { + return fail(0x3029, { type: typeof input }); + } +} +/** try to get the constructor name for an object. */ +function tryGetCustomObjectType(input) { + if (input.constructor) { + return input.constructor.name; + } + return null; +} +/** + * Casts `obj` to `T`, optionally unwrapping Compat types to expose the + * underlying instance. Throws if `obj` is not an instance of `T`. + * + * This cast is used in the Lite and Full SDK to verify instance types for + * arguments passed to the public API. + * @internal + */ +function cast(obj, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +constructor) { + if ('_delegate' in obj) { + // Unwrap Compat types + // eslint-disable-next-line @typescript-eslint/no-explicit-any + obj = obj._delegate; + } + if (!(obj instanceof constructor)) { + if (constructor.name === obj.constructor.name) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Type does not match the expected instance. Did you pass a ' + + `reference from a different Firestore SDK?`); + } + else { + const description = valueDescription(obj); + throw new FirestoreError(Code.INVALID_ARGUMENT, `Expected type '${constructor.name}', but it was: ${description}`); + } + } + return obj; +} +function validatePositiveNumber(functionName, n) { + if (n <= 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${functionName}() requires a positive number, but it was: ${n}.`); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Helper function to define a JSON schema {@link Property}. + * @private + * @internal + */ +function property(typeString, optionalValue) { + const result = { + typeString + }; + if (optionalValue) { + result.value = optionalValue; + } + return result; +} +/** + * Validates the JSON object based on the provided schema, and narrows the type to the provided + * JSON schema. + * @private + * @internal + * + * @param json A JSON object to validate. + * @param scheme a {@link JsonSchema} that defines the properties to validate. + * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise. + */ +function validateJSON(json, schema) { + if (!isPlainObject(json)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'JSON must be an object'); + } + let error = undefined; + for (const key in schema) { + if (schema[key]) { + const typeString = schema[key].typeString; + const value = 'value' in schema[key] ? { value: schema[key].value } : undefined; + if (!(key in json)) { + error = `JSON missing required field: '${key}'`; + break; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const fieldValue = json[key]; + if (typeString && typeof fieldValue !== typeString) { + error = `JSON field '${key}' must be a ${typeString}.`; + break; + } + else if (value !== undefined && fieldValue !== value.value) { + error = `Expected '${key}' field to equal '${value.value}'`; + break; + } + } + } + if (error) { + throw new FirestoreError(Code.INVALID_ARGUMENT, error); + } + return true; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z). +const MIN_SECONDS = -62135596800; +// Number of nanoseconds in a millisecond. +const MS_TO_NANOS = 1e6; +/** + * A `Timestamp` represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. + * + * It is encoded using the Proleptic Gregorian Calendar which extends the + * Gregorian calendar backwards to year one. It is encoded assuming all minutes + * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59.999999999Z. + * + * For examples and further specifications, refer to the + * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. + */ +class Timestamp { + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns a new timestamp representing the current date. + */ + static now() { + return Timestamp.fromMillis(Date.now()); + } + /** + * Creates a new timestamp from the given date. + * + * @param date - The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the given + * date. + */ + static fromDate(date) { + return Timestamp.fromMillis(date.getTime()); + } + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds - Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the given + * number of milliseconds. + */ + static fromMillis(milliseconds) { + const seconds = Math.floor(milliseconds / 1000); + const nanos = Math.floor((milliseconds - seconds * 1000) * MS_TO_NANOS); + return new Timestamp(seconds, nanos); + } + /** + * Creates a new timestamp. + * + * @param seconds - The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds - The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ + constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + seconds, + /** + * The fractions of a second at nanosecond resolution.* + */ + nanoseconds) { + this.seconds = seconds; + this.nanoseconds = nanoseconds; + if (nanoseconds < 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp nanoseconds out of range: ' + nanoseconds); + } + if (nanoseconds >= 1e9) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp nanoseconds out of range: ' + nanoseconds); + } + if (seconds < MIN_SECONDS) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp seconds out of range: ' + seconds); + } + // This will break in the year 10,000. + if (seconds >= 253402300800) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp seconds out of range: ' + seconds); + } + } + /** + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ + toDate() { + return new Date(this.toMillis()); + } + /** + * Converts a `Timestamp` to a numeric timestamp (in milliseconds since + * epoch). This operation causes a loss of precision. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ + toMillis() { + return this.seconds * 1000 + this.nanoseconds / MS_TO_NANOS; + } + _compareTo(other) { + if (this.seconds === other.seconds) { + return primitiveComparator(this.nanoseconds, other.nanoseconds); + } + return primitiveComparator(this.seconds, other.seconds); + } + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other - The `Timestamp` to compare against. + * @returns true if this `Timestamp` is equal to the provided one. + */ + isEqual(other) { + return (other.seconds === this.seconds && other.nanoseconds === this.nanoseconds); + } + /** Returns a textual representation of this `Timestamp`. */ + toString() { + return ('Timestamp(seconds=' + + this.seconds + + ', nanoseconds=' + + this.nanoseconds + + ')'); + } + /** + * Returns a JSON-serializable representation of this `Timestamp`. + */ + toJSON() { + return { + type: Timestamp._jsonSchemaVersion, + seconds: this.seconds, + nanoseconds: this.nanoseconds + }; + } + /** + * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}. + */ + static fromJSON(json) { + if (validateJSON(json, Timestamp._jsonSchema)) { + return new Timestamp(json.seconds, json.nanoseconds); + } + } + /** + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. + */ + valueOf() { + // This method returns a string of the form . where + // is translated to have a non-negative value and both + // and are left-padded with zeroes to be a consistent length. + // Strings with this format then have a lexicographical ordering that matches + // the expected ordering. The translation is done to avoid having + // a leading negative sign (i.e. a leading '-' character) in its string + // representation, which would affect its lexicographical ordering. + const adjustedSeconds = this.seconds - MIN_SECONDS; + // Note: Up to 12 decimal digits are required to represent all valid + // 'seconds' values. + const formattedSeconds = String(adjustedSeconds).padStart(12, '0'); + const formattedNanoseconds = String(this.nanoseconds).padStart(9, '0'); + return formattedSeconds + '.' + formattedNanoseconds; + } +} +Timestamp._jsonSchemaVersion = 'firestore/timestamp/1.0'; +Timestamp._jsonSchema = { + type: property('string', Timestamp._jsonSchemaVersion), + seconds: property('number'), + nanoseconds: property('number') +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A version of a document in Firestore. This corresponds to the version + * timestamp, such as update_time or read_time. + */ +class SnapshotVersion { + static fromTimestamp(value) { + return new SnapshotVersion(value); + } + static min() { + return new SnapshotVersion(new Timestamp(0, 0)); + } + static max() { + return new SnapshotVersion(new Timestamp(253402300799, 1e9 - 1)); + } + constructor(timestamp) { + this.timestamp = timestamp; + } + compareTo(other) { + return this.timestamp._compareTo(other.timestamp); + } + isEqual(other) { + return this.timestamp.isEqual(other.timestamp); + } + /** Returns a number representation of the version for use in spec tests. */ + toMicroseconds() { + // Convert to microseconds. + return this.timestamp.seconds * 1e6 + this.timestamp.nanoseconds / 1000; + } + toString() { + return 'SnapshotVersion(' + this.timestamp.toString() + ')'; + } + toTimestamp() { + return this.timestamp; + } +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The initial mutation batch id for each index. Gets updated during index + * backfill. + */ +const INITIAL_LARGEST_BATCH_ID = -1; +/** + * The initial sequence number for each index. Gets updated during index + * backfill. + */ +const INITIAL_SEQUENCE_NUMBER = 0; +/** + * An index definition for field indexes in Firestore. + * + * Every index is associated with a collection. The definition contains a list + * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or + * `CONTAINS` for ArrayContains/ArrayContainsAny queries). + * + * Unlike the backend, the SDK does not differentiate between collection or + * collection group-scoped indices. Every index can be used for both single + * collection and collection group queries. + */ +class FieldIndex { + constructor( + /** + * The index ID. Returns -1 if the index ID is not available (e.g. the index + * has not yet been persisted). + */ + indexId, + /** The collection ID this index applies to. */ + collectionGroup, + /** The field segments for this index. */ + fields, + /** Shows how up-to-date the index is for the current user. */ + indexState) { + this.indexId = indexId; + this.collectionGroup = collectionGroup; + this.fields = fields; + this.indexState = indexState; + } +} +/** An ID for an index that has not yet been added to persistence. */ +FieldIndex.UNKNOWN_ID = -1; +/** Returns the ArrayContains/ArrayContainsAny segment for this index. */ +function fieldIndexGetArraySegment(fieldIndex) { + return fieldIndex.fields.find(s => s.kind === 2 /* IndexKind.CONTAINS */); +} +/** Returns all directional (ascending/descending) segments for this index. */ +function fieldIndexGetDirectionalSegments(fieldIndex) { + return fieldIndex.fields.filter(s => s.kind !== 2 /* IndexKind.CONTAINS */); +} +/** + * Returns the order of the document key component for the given index. + * + * PORTING NOTE: This is only used in the Web IndexedDb implementation. + */ +function fieldIndexGetKeyOrder(fieldIndex) { + const directionalSegments = fieldIndexGetDirectionalSegments(fieldIndex); + return directionalSegments.length === 0 + ? 0 /* IndexKind.ASCENDING */ + : directionalSegments[directionalSegments.length - 1].kind; +} +/** + * Compares indexes by collection group and segments. Ignores update time and + * index ID. + */ +function fieldIndexSemanticComparator(left, right) { + let cmp = primitiveComparator(left.collectionGroup, right.collectionGroup); + if (cmp !== 0) { + return cmp; + } + for (let i = 0; i < Math.min(left.fields.length, right.fields.length); ++i) { + cmp = indexSegmentComparator(left.fields[i], right.fields[i]); + if (cmp !== 0) { + return cmp; + } + } + return primitiveComparator(left.fields.length, right.fields.length); +} +/** Returns a debug representation of the field index */ +function fieldIndexToString(fieldIndex) { + return `id=${fieldIndex.indexId}|cg=${fieldIndex.collectionGroup}|f=${fieldIndex.fields.map(f => `${f.fieldPath}:${f.kind}`).join(',')}`; +} +/** An index component consisting of field path and index type. */ +class IndexSegment { + constructor( + /** The field path of the component. */ + fieldPath, + /** The fields sorting order. */ + kind) { + this.fieldPath = fieldPath; + this.kind = kind; + } +} +function indexSegmentComparator(left, right) { + const cmp = FieldPath$1.comparator(left.fieldPath, right.fieldPath); + if (cmp !== 0) { + return cmp; + } + return primitiveComparator(left.kind, right.kind); +} +/** + * Stores the "high water mark" that indicates how updated the Index is for the + * current user. + */ +class IndexState { + constructor( + /** + * Indicates when the index was last updated (relative to other indexes). + */ + sequenceNumber, + /** The the latest indexed read time, document and batch id. */ + offset) { + this.sequenceNumber = sequenceNumber; + this.offset = offset; + } + /** The state of an index that has not yet been backfilled. */ + static empty() { + return new IndexState(INITIAL_SEQUENCE_NUMBER, IndexOffset.min()); + } +} +/** + * Creates an offset that matches all documents with a read time higher than + * `readTime`. + */ +function newIndexOffsetSuccessorFromReadTime(readTime, largestBatchId) { + // We want to create an offset that matches all documents with a read time + // greater than the provided read time. To do so, we technically need to + // create an offset for `(readTime, MAX_DOCUMENT_KEY)`. While we could use + // Unicode codepoints to generate MAX_DOCUMENT_KEY, it is much easier to use + // `(readTime + 1, DocumentKey.empty())` since `> DocumentKey.empty()` matches + // all valid document IDs. + const successorSeconds = readTime.toTimestamp().seconds; + const successorNanos = readTime.toTimestamp().nanoseconds + 1; + const successor = SnapshotVersion.fromTimestamp(successorNanos === 1e9 + ? new Timestamp(successorSeconds + 1, 0) + : new Timestamp(successorSeconds, successorNanos)); + return new IndexOffset(successor, DocumentKey.empty(), largestBatchId); +} +/** Creates a new offset based on the provided document. */ +function newIndexOffsetFromDocument(document) { + return new IndexOffset(document.readTime, document.key, INITIAL_LARGEST_BATCH_ID); +} +/** + * Stores the latest read time, document and batch ID that were processed for an + * index. + */ +class IndexOffset { + constructor( + /** + * The latest read time version that has been indexed by Firestore for this + * field index. + */ + readTime, + /** + * The key of the last document that was indexed for this query. Use + * `DocumentKey.empty()` if no document has been indexed. + */ + documentKey, + /* + * The largest mutation batch id that's been processed by Firestore. + */ + largestBatchId) { + this.readTime = readTime; + this.documentKey = documentKey; + this.largestBatchId = largestBatchId; + } + /** Returns an offset that sorts before all regular offsets. */ + static min() { + return new IndexOffset(SnapshotVersion.min(), DocumentKey.empty(), INITIAL_LARGEST_BATCH_ID); + } + /** Returns an offset that sorts after all regular offsets. */ + static max() { + return new IndexOffset(SnapshotVersion.max(), DocumentKey.empty(), INITIAL_LARGEST_BATCH_ID); + } +} +function indexOffsetComparator(left, right) { + let cmp = left.readTime.compareTo(right.readTime); + if (cmp !== 0) { + return cmp; + } + cmp = DocumentKey.comparator(left.documentKey, right.documentKey); + if (cmp !== 0) { + return cmp; + } + return primitiveComparator(left.largestBatchId, right.largestBatchId); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const PRIMARY_LEASE_LOST_ERROR_MSG = 'The current tab is not in the required state to perform this operation. ' + + 'It might be necessary to refresh the browser tab.'; +/** + * A base class representing a persistence transaction, encapsulating both the + * transaction's sequence numbers as well as a list of onCommitted listeners. + * + * When you call Persistence.runTransaction(), it will create a transaction and + * pass it to your callback. You then pass it to any method that operates + * on persistence. + */ +class PersistenceTransaction { + constructor() { + this.onCommittedListeners = []; + } + addOnCommittedListener(listener) { + this.onCommittedListeners.push(listener); + } + raiseOnCommittedEvent() { + this.onCommittedListeners.forEach(listener => listener()); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Verifies the error thrown by a LocalStore operation. If a LocalStore + * operation fails because the primary lease has been taken by another client, + * we ignore the error (the persistence layer will immediately call + * `applyPrimaryLease` to propagate the primary state change). All other errors + * are re-thrown. + * + * @param err - An error returned by a LocalStore operation. + * @returns A Promise that resolves after we recovered, or the original error. + */ +async function ignoreIfPrimaryLeaseLoss(err) { + if (err.code === Code.FAILED_PRECONDITION && + err.message === PRIMARY_LEASE_LOST_ERROR_MSG) { + logDebug('LocalStore', 'Unexpectedly lost primary lease'); + } + else { + throw err; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * PersistencePromise is essentially a re-implementation of Promise except + * it has a .next() method instead of .then() and .next() and .catch() callbacks + * are executed synchronously when a PersistencePromise resolves rather than + * asynchronously (Promise implementations use setImmediate() or similar). + * + * This is necessary to interoperate with IndexedDB which will automatically + * commit transactions if control is returned to the event loop without + * synchronously initiating another operation on the transaction. + * + * NOTE: .then() and .catch() only allow a single consumer, unlike normal + * Promises. + */ +class PersistencePromise { + constructor(callback) { + // NOTE: next/catchCallback will always point to our own wrapper functions, + // not the user's raw next() or catch() callbacks. + this.nextCallback = null; + this.catchCallback = null; + // When the operation resolves, we'll set result or error and mark isDone. + this.result = undefined; + this.error = undefined; + this.isDone = false; + // Set to true when .then() or .catch() are called and prevents additional + // chaining. + this.callbackAttached = false; + callback(value => { + this.isDone = true; + this.result = value; + if (this.nextCallback) { + // value should be defined unless T is Void, but we can't express + // that in the type system. + this.nextCallback(value); + } + }, error => { + this.isDone = true; + this.error = error; + if (this.catchCallback) { + this.catchCallback(error); + } + }); + } + catch(fn) { + return this.next(undefined, fn); + } + next(nextFn, catchFn) { + if (this.callbackAttached) { + fail(0xe830); + } + this.callbackAttached = true; + if (this.isDone) { + if (!this.error) { + return this.wrapSuccess(nextFn, this.result); + } + else { + return this.wrapFailure(catchFn, this.error); + } + } + else { + return new PersistencePromise((resolve, reject) => { + this.nextCallback = (value) => { + this.wrapSuccess(nextFn, value).next(resolve, reject); + }; + this.catchCallback = (error) => { + this.wrapFailure(catchFn, error).next(resolve, reject); + }; + }); + } + } + toPromise() { + return new Promise((resolve, reject) => { + this.next(resolve, reject); + }); + } + wrapUserFunction(fn) { + try { + const result = fn(); + if (result instanceof PersistencePromise) { + return result; + } + else { + return PersistencePromise.resolve(result); + } + } + catch (e) { + return PersistencePromise.reject(e); + } + } + wrapSuccess(nextFn, value) { + if (nextFn) { + return this.wrapUserFunction(() => nextFn(value)); + } + else { + // If there's no nextFn, then R must be the same as T + return PersistencePromise.resolve(value); + } + } + wrapFailure(catchFn, error) { + if (catchFn) { + return this.wrapUserFunction(() => catchFn(error)); + } + else { + return PersistencePromise.reject(error); + } + } + static resolve(result) { + return new PersistencePromise((resolve, reject) => { + resolve(result); + }); + } + static reject(error) { + return new PersistencePromise((resolve, reject) => { + reject(error); + }); + } + static waitFor( + // Accept all Promise types in waitFor(). + // eslint-disable-next-line @typescript-eslint/no-explicit-any + all) { + return new PersistencePromise((resolve, reject) => { + let expectedCount = 0; + let resolvedCount = 0; + let done = false; + all.forEach(element => { + ++expectedCount; + element.next(() => { + ++resolvedCount; + if (done && resolvedCount === expectedCount) { + resolve(); + } + }, err => reject(err)); + }); + done = true; + if (resolvedCount === expectedCount) { + resolve(); + } + }); + } + /** + * Given an array of predicate functions that asynchronously evaluate to a + * boolean, implements a short-circuiting `or` between the results. Predicates + * will be evaluated until one of them returns `true`, then stop. The final + * result will be whether any of them returned `true`. + */ + static or(predicates) { + let p = PersistencePromise.resolve(false); + for (const predicate of predicates) { + p = p.next(isTrue => { + if (isTrue) { + return PersistencePromise.resolve(isTrue); + } + else { + return predicate(); + } + }); + } + return p; + } + static forEach(collection, f) { + const promises = []; + collection.forEach((r, s) => { + promises.push(f.call(this, r, s)); + }); + return this.waitFor(promises); + } + /** + * Concurrently map all array elements through asynchronous function. + */ + static mapArray(array, f) { + return new PersistencePromise((resolve, reject) => { + const expectedCount = array.length; + const results = new Array(expectedCount); + let resolvedCount = 0; + for (let i = 0; i < expectedCount; i++) { + const current = i; + f(array[current]).next(result => { + results[current] = result; + ++resolvedCount; + if (resolvedCount === expectedCount) { + resolve(results); + } + }, err => reject(err)); + } + }); + } + /** + * An alternative to recursive PersistencePromise calls, that avoids + * potential memory problems from unbounded chains of promises. + * + * The `action` will be called repeatedly while `condition` is true. + */ + static doWhile(condition, action) { + return new PersistencePromise((resolve, reject) => { + const process = () => { + if (condition() === true) { + action().next(() => { + process(); + }, reject); + } + else { + resolve(); + } + }; + process(); + }); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// References to `indexedDB` are guarded by SimpleDb.isAvailable() and getGlobal() +/* eslint-disable no-restricted-globals */ +const LOG_TAG$i = 'SimpleDb'; +/** + * The maximum number of retry attempts for an IndexedDb transaction that fails + * with a DOMException. + */ +const TRANSACTION_RETRY_COUNT = 3; +/** + * Wraps an IDBTransaction and exposes a store() method to get a handle to a + * specific object store. + */ +class SimpleDbTransaction { + static open(db, action, mode, objectStoreNames) { + try { + return new SimpleDbTransaction(action, db.transaction(objectStoreNames, mode)); + } + catch (e) { + throw new IndexedDbTransactionError(action, e); + } + } + constructor(action, transaction) { + this.action = action; + this.transaction = transaction; + this.aborted = false; + /** + * A `Promise` that resolves with the result of the IndexedDb transaction. + */ + this.completionDeferred = new Deferred(); + this.transaction.oncomplete = () => { + this.completionDeferred.resolve(); + }; + this.transaction.onabort = () => { + if (transaction.error) { + this.completionDeferred.reject(new IndexedDbTransactionError(action, transaction.error)); + } + else { + this.completionDeferred.resolve(); + } + }; + this.transaction.onerror = (event) => { + const error = checkForAndReportiOSError(event.target.error); + this.completionDeferred.reject(new IndexedDbTransactionError(action, error)); + }; + } + get completionPromise() { + return this.completionDeferred.promise; + } + abort(error) { + if (error) { + this.completionDeferred.reject(error); + } + if (!this.aborted) { + logDebug(LOG_TAG$i, 'Aborting transaction:', error ? error.message : 'Client-initiated abort'); + this.aborted = true; + this.transaction.abort(); + } + } + maybeCommit() { + // If the browser supports V3 IndexedDB, we invoke commit() explicitly to + // speed up index DB processing if the event loop remains blocks. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const maybeV3IndexedDb = this.transaction; + if (!this.aborted && typeof maybeV3IndexedDb.commit === 'function') { + maybeV3IndexedDb.commit(); + } + } + /** + * Returns a SimpleDbStore for the specified store. All + * operations performed on the SimpleDbStore happen within the context of this + * transaction and it cannot be used anymore once the transaction is + * completed. + * + * Note that we can't actually enforce that the KeyType and ValueType are + * correct, but they allow type safety through the rest of the consuming code. + */ + store(storeName) { + const store = this.transaction.objectStore(storeName); + return new SimpleDbStore(store); + } +} +/** + * Provides a wrapper around IndexedDb with a simplified interface that uses + * Promise-like return values to chain operations. Real promises cannot be used + * since .then() continuations are executed asynchronously (e.g. via + * .setImmediate), which would cause IndexedDB to end the transaction. + * See PersistencePromise for more details. + */ +class SimpleDb { + /** Deletes the specified database. */ + static delete(name) { + logDebug(LOG_TAG$i, 'Removing database:', name); + const globals = util.getGlobal(); + return wrapRequest(globals.indexedDB.deleteDatabase(name)).toPromise(); + } + /** Returns true if IndexedDB is available in the current environment. */ + static isAvailable() { + if (!util.isIndexedDBAvailable()) { + return false; + } + if (SimpleDb.isMockPersistence()) { + return true; + } + // We extensively use indexed array values and compound keys, + // which IE and Edge do not support. However, they still have indexedDB + // defined on the window, so we need to check for them here and make sure + // to return that persistence is not enabled for those browsers. + // For tracking support of this feature, see here: + // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/ + // Check the UA string to find out the browser. + const ua = util.getUA(); + // IE 10 + // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)'; + // IE 11 + // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko'; + // Edge + // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, + // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0'; + // iOS Safari: Disable for users running iOS version < 10. + const iOSVersion = SimpleDb.getIOSVersion(ua); + const isUnsupportedIOS = 0 < iOSVersion && iOSVersion < 10; + // Android browser: Disable for users running version < 4.5. + const androidVersion = getAndroidVersion(ua); + const isUnsupportedAndroid = 0 < androidVersion && androidVersion < 4.5; + if (ua.indexOf('MSIE ') > 0 || + ua.indexOf('Trident/') > 0 || + ua.indexOf('Edge/') > 0 || + isUnsupportedIOS || + isUnsupportedAndroid) { + return false; + } + else { + return true; + } + } + /** + * Returns true if the backing IndexedDB store is the Node IndexedDBShim + * (see https://github.com/axemclion/IndexedDBShim). + */ + static isMockPersistence() { + return (typeof process !== 'undefined' && + process.env?.USE_MOCK_PERSISTENCE === 'YES'); + } + /** Helper to get a typed SimpleDbStore from a transaction. */ + static getStore(txn, store) { + return txn.store(store); + } + // visible for testing + /** Parse User Agent to determine iOS version. Returns -1 if not found. */ + static getIOSVersion(ua) { + const iOSVersionRegex = ua.match(/i(?:phone|pad|pod) os ([\d_]+)/i); + const version = iOSVersionRegex + ? iOSVersionRegex[1].split('_').slice(0, 2).join('.') + : '-1'; + return Number(version); + } + /* + * Creates a new SimpleDb wrapper for IndexedDb database `name`. + * + * Note that `version` must not be a downgrade. IndexedDB does not support + * downgrading the schema version. We currently do not support any way to do + * versioning outside of IndexedDB's versioning mechanism, as only + * version-upgrade transactions are allowed to do things like create + * objectstores. + */ + constructor(name, version, schemaConverter) { + this.name = name; + this.version = version; + this.schemaConverter = schemaConverter; + this.lastClosedDbVersion = null; + const iOSVersion = SimpleDb.getIOSVersion(util.getUA()); + // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the + // bug we're checking for should exist in iOS >= 12.2 and < 13, but for + // whatever reason it's much harder to hit after 12.2 so we only proactively + // log on 12.2. + if (iOSVersion === 12.2) { + logError('Firestore persistence suffers from a bug in iOS 12.2 ' + + 'Safari that may cause your app to stop working. See ' + + 'https://stackoverflow.com/q/56496296/110915 for details ' + + 'and a potential workaround.'); + } + } + /** + * Opens the specified database, creating or upgrading it if necessary. + */ + async ensureDb(action) { + if (!this.db) { + logDebug(LOG_TAG$i, 'Opening database:', this.name); + this.db = await new Promise((resolve, reject) => { + // TODO(mikelehen): Investigate browser compatibility. + // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB + // suggests IE9 and older WebKit browsers handle upgrade + // differently. They expect setVersion, as described here: + // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion + const request = indexedDB.open(this.name, this.version); + request.onsuccess = (event) => { + const db = event.target.result; + resolve(db); + }; + request.onblocked = () => { + reject(new IndexedDbTransactionError(action, 'Cannot upgrade IndexedDB schema while another tab is open. ' + + 'Close all tabs that access Firestore and reload this page to proceed.')); + }; + request.onerror = (event) => { + const error = event.target.error; + if (error.name === 'VersionError') { + reject(new FirestoreError(Code.FAILED_PRECONDITION, 'A newer version of the Firestore SDK was previously used and so the persisted ' + + 'data is not compatible with the version of the SDK you are now using. The SDK ' + + 'will operate with persistence disabled. If you need persistence, please ' + + 're-upgrade to a newer version of the SDK or else clear the persisted IndexedDB ' + + 'data for your app to start fresh.')); + } + else if (error.name === 'InvalidStateError') { + reject(new FirestoreError(Code.FAILED_PRECONDITION, 'Unable to open an IndexedDB connection. This could be due to running in a ' + + 'private browsing session on a browser whose private browsing sessions do not ' + + 'support IndexedDB: ' + + error)); + } + else { + reject(new IndexedDbTransactionError(action, error)); + } + }; + request.onupgradeneeded = (event) => { + logDebug(LOG_TAG$i, 'Database "' + this.name + '" requires upgrade from version:', event.oldVersion); + const db = event.target.result; + this.schemaConverter + .createOrUpgrade(db, request.transaction, event.oldVersion, this.version) + .next(() => { + logDebug(LOG_TAG$i, 'Database upgrade to version ' + this.version + ' complete'); + }); + }; + }); + } + if (this.versionchangelistener) { + this.db.onversionchange = event => this.versionchangelistener(event); + } + return this.db; + } + setVersionChangeListener(versionChangeListener) { + this.versionchangelistener = versionChangeListener; + if (this.db) { + this.db.onversionchange = (event) => { + return versionChangeListener(event); + }; + } + } + async runTransaction(action, mode, objectStores, transactionFn) { + const readonly = mode === 'readonly'; + let attemptNumber = 0; + while (true) { + ++attemptNumber; + try { + this.db = await this.ensureDb(action); + const transaction = SimpleDbTransaction.open(this.db, action, readonly ? 'readonly' : 'readwrite', objectStores); + const transactionFnResult = transactionFn(transaction) + .next(result => { + transaction.maybeCommit(); + return result; + }) + .catch(error => { + // Abort the transaction if there was an error. + transaction.abort(error); + // We cannot actually recover, and calling `abort()` will cause the transaction's + // completion promise to be rejected. This in turn means that we won't use + // `transactionFnResult` below. We return a rejection here so that we don't add the + // possibility of returning `void` to the type of `transactionFnResult`. + return PersistencePromise.reject(error); + }) + .toPromise(); + // As noted above, errors are propagated by aborting the transaction. So + // we swallow any error here to avoid the browser logging it as unhandled. + transactionFnResult.catch(() => { }); + // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to + // fire), but still return the original transactionFnResult back to the + // caller. + await transaction.completionPromise; + return transactionFnResult; + } + catch (e) { + const error = e; + // TODO(schmidt-sebastian): We could probably be smarter about this and + // not retry exceptions that are likely unrecoverable (such as quota + // exceeded errors). + // Note: We cannot use an instanceof check for FirestoreException, since the + // exception is wrapped in a generic error by our async/await handling. + const retryable = error.name !== 'FirebaseError' && + attemptNumber < TRANSACTION_RETRY_COUNT; + logDebug(LOG_TAG$i, 'Transaction failed with error:', error.message, 'Retrying:', retryable); + this.close(); + if (!retryable) { + return Promise.reject(error); + } + } + } + } + close() { + if (this.db) { + this.db.close(); + } + this.db = undefined; + } +} +/** Parse User Agent to determine Android version. Returns -1 if not found. */ +function getAndroidVersion(ua) { + const androidVersionRegex = ua.match(/Android ([\d.]+)/i); + const version = androidVersionRegex + ? androidVersionRegex[1].split('.').slice(0, 2).join('.') + : '-1'; + return Number(version); +} +/** + * A controller for iterating over a key range or index. It allows an iterate + * callback to delete the currently-referenced object, or jump to a new key + * within the key range or index. + */ +class IterationController { + constructor(dbCursor) { + this.dbCursor = dbCursor; + this.shouldStop = false; + this.nextKey = null; + } + get isDone() { + return this.shouldStop; + } + get skipToKey() { + return this.nextKey; + } + set cursor(value) { + this.dbCursor = value; + } + /** + * This function can be called to stop iteration at any point. + */ + done() { + this.shouldStop = true; + } + /** + * This function can be called to skip to that next key, which could be + * an index or a primary key. + */ + skip(key) { + this.nextKey = key; + } + /** + * Delete the current cursor value from the object store. + * + * NOTE: You CANNOT do this with a keysOnly query. + */ + delete() { + return wrapRequest(this.dbCursor.delete()); + } +} +/** An error that wraps exceptions that thrown during IndexedDB execution. */ +class IndexedDbTransactionError extends FirestoreError { + constructor(actionName, cause) { + super(Code.UNAVAILABLE, `IndexedDB transaction '${actionName}' failed: ${cause}`); + this.name = 'IndexedDbTransactionError'; + } +} +/** Verifies whether `e` is an IndexedDbTransactionError. */ +function isIndexedDbTransactionError(e) { + // Use name equality, as instanceof checks on errors don't work with errors + // that wrap other errors. + return e.name === 'IndexedDbTransactionError'; +} +/** + * A wrapper around an IDBObjectStore providing an API that: + * + * 1) Has generic KeyType / ValueType parameters to provide strongly-typed + * methods for acting against the object store. + * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every + * method return a PersistencePromise instead. + * 3) Provides a higher-level API to avoid needing to do excessive wrapping of + * intermediate IndexedDB types (IDBCursorWithValue, etc.) + */ +class SimpleDbStore { + constructor(store) { + this.store = store; + } + put(keyOrValue, value) { + let request; + if (value !== undefined) { + logDebug(LOG_TAG$i, 'PUT', this.store.name, keyOrValue, value); + request = this.store.put(value, keyOrValue); + } + else { + logDebug(LOG_TAG$i, 'PUT', this.store.name, '', keyOrValue); + request = this.store.put(keyOrValue); + } + return wrapRequest(request); + } + /** + * Adds a new value into an Object Store and returns the new key. Similar to + * IndexedDb's `add()`, this method will fail on primary key collisions. + * + * @param value - The object to write. + * @returns The key of the value to add. + */ + add(value) { + logDebug(LOG_TAG$i, 'ADD', this.store.name, value, value); + const request = this.store.add(value); + return wrapRequest(request); + } + /** + * Gets the object with the specified key from the specified store, or null + * if no object exists with the specified key. + * + * @key The key of the object to get. + * @returns The object with the specified key or null if no object exists. + */ + get(key) { + const request = this.store.get(key); + // We're doing an unsafe cast to ValueType. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return wrapRequest(request).next(result => { + // Normalize nonexistence to null. + if (result === undefined) { + result = null; + } + logDebug(LOG_TAG$i, 'GET', this.store.name, key, result); + return result; + }); + } + delete(key) { + logDebug(LOG_TAG$i, 'DELETE', this.store.name, key); + const request = this.store.delete(key); + return wrapRequest(request); + } + /** + * If we ever need more of the count variants, we can add overloads. For now, + * all we need is to count everything in a store. + * + * Returns the number of rows in the store. + */ + count() { + logDebug(LOG_TAG$i, 'COUNT', this.store.name); + const request = this.store.count(); + return wrapRequest(request); + } + loadAll(indexOrRange, range) { + const iterateOptions = this.options(indexOrRange, range); + // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly + // 20% faster. + const store = iterateOptions.index + ? this.store.index(iterateOptions.index) + : this.store; + if (typeof store.getAll === 'function') { + const request = store.getAll(iterateOptions.range); + return new PersistencePromise((resolve, reject) => { + request.onerror = (event) => { + reject(event.target.error); + }; + request.onsuccess = (event) => { + resolve(event.target.result); + }; + }); + } + else { + const cursor = this.cursor(iterateOptions); + const results = []; + return this.iterateCursor(cursor, (key, value) => { + results.push(value); + }).next(() => { + return results; + }); + } + } + /** + * Loads the first `count` elements from the provided index range. Loads all + * elements if no limit is provided. + */ + loadFirst(range, count) { + const request = this.store.getAll(range, count === null ? undefined : count); + return new PersistencePromise((resolve, reject) => { + request.onerror = (event) => { + reject(event.target.error); + }; + request.onsuccess = (event) => { + resolve(event.target.result); + }; + }); + } + deleteAll(indexOrRange, range) { + logDebug(LOG_TAG$i, 'DELETE ALL', this.store.name); + const options = this.options(indexOrRange, range); + options.keysOnly = false; + const cursor = this.cursor(options); + return this.iterateCursor(cursor, (key, value, control) => { + // NOTE: Calling delete() on a cursor is documented as more efficient than + // calling delete() on an object store with a single key + // (https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete), + // however, this requires us *not* to use a keysOnly cursor + // (https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/delete). We + // may want to compare the performance of each method. + return control.delete(); + }); + } + iterate(optionsOrCallback, callback) { + let options; + if (!callback) { + options = {}; + callback = optionsOrCallback; + } + else { + options = optionsOrCallback; + } + const cursor = this.cursor(options); + return this.iterateCursor(cursor, callback); + } + /** + * Iterates over a store, but waits for the given callback to complete for + * each entry before iterating the next entry. This allows the callback to do + * asynchronous work to determine if this iteration should continue. + * + * The provided callback should return `true` to continue iteration, and + * `false` otherwise. + */ + iterateSerial(callback) { + const cursorRequest = this.cursor({}); + return new PersistencePromise((resolve, reject) => { + cursorRequest.onerror = (event) => { + const error = checkForAndReportiOSError(event.target.error); + reject(error); + }; + cursorRequest.onsuccess = (event) => { + const cursor = event.target.result; + if (!cursor) { + resolve(); + return; + } + callback(cursor.primaryKey, cursor.value).next(shouldContinue => { + if (shouldContinue) { + cursor.continue(); + } + else { + resolve(); + } + }); + }; + }); + } + iterateCursor(cursorRequest, fn) { + const results = []; + return new PersistencePromise((resolve, reject) => { + cursorRequest.onerror = (event) => { + reject(event.target.error); + }; + cursorRequest.onsuccess = (event) => { + const cursor = event.target.result; + if (!cursor) { + resolve(); + return; + } + const controller = new IterationController(cursor); + const userResult = fn(cursor.primaryKey, cursor.value, controller); + if (userResult instanceof PersistencePromise) { + const userPromise = userResult.catch(err => { + controller.done(); + return PersistencePromise.reject(err); + }); + results.push(userPromise); + } + if (controller.isDone) { + resolve(); + } + else if (controller.skipToKey === null) { + cursor.continue(); + } + else { + cursor.continue(controller.skipToKey); + } + }; + }).next(() => PersistencePromise.waitFor(results)); + } + options(indexOrRange, range) { + let indexName = undefined; + if (indexOrRange !== undefined) { + if (typeof indexOrRange === 'string') { + indexName = indexOrRange; + } + else { + range = indexOrRange; + } + } + return { index: indexName, range }; + } + cursor(options) { + let direction = 'next'; + if (options.reverse) { + direction = 'prev'; + } + if (options.index) { + const index = this.store.index(options.index); + if (options.keysOnly) { + return index.openKeyCursor(options.range, direction); + } + else { + return index.openCursor(options.range, direction); + } + } + else { + return this.store.openCursor(options.range, direction); + } + } +} +/** + * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror + * handlers to resolve / reject the PersistencePromise as appropriate. + */ +function wrapRequest(request) { + return new PersistencePromise((resolve, reject) => { + request.onsuccess = (event) => { + const result = event.target.result; + resolve(result); + }; + request.onerror = (event) => { + const error = checkForAndReportiOSError(event.target.error); + reject(error); + }; + }); +} +// Guard so we only report the error once. +let reportedIOSError = false; +function checkForAndReportiOSError(error) { + const iOSVersion = SimpleDb.getIOSVersion(util.getUA()); + if (iOSVersion >= 12.2 && iOSVersion < 13) { + const IOS_ERROR = 'An internal error was encountered in the Indexed Database server'; + if (error.message.indexOf(IOS_ERROR) >= 0) { + // Wrap error in a more descriptive one. + const newError = new FirestoreError('internal', `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${IOS_ERROR}'. This is likely ` + + `due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 ` + + `for details and a potential workaround.`); + if (!reportedIOSError) { + reportedIOSError = true; + // Throw a global exception outside of this promise chain, for the user to + // potentially catch. + setTimeout(() => { + throw newError; + }, 0); + } + return newError; + } + } + return error; +} + +const LOG_TAG$h = 'IndexBackfiller'; +/** How long we wait to try running index backfill after SDK initialization. */ +const INITIAL_BACKFILL_DELAY_MS = 15 * 1000; +/** Minimum amount of time between backfill checks, after the first one. */ +const REGULAR_BACKFILL_DELAY_MS = 60 * 1000; +/** The maximum number of documents to process each time backfill() is called. */ +const MAX_DOCUMENTS_TO_PROCESS = 50; +/** This class is responsible for the scheduling of Index Backfiller. */ +class IndexBackfillerScheduler { + constructor(asyncQueue, backfiller) { + this.asyncQueue = asyncQueue; + this.backfiller = backfiller; + this.task = null; + } + start() { + this.schedule(INITIAL_BACKFILL_DELAY_MS); + } + stop() { + if (this.task) { + this.task.cancel(); + this.task = null; + } + } + get started() { + return this.task !== null; + } + schedule(delay) { + logDebug(LOG_TAG$h, `Scheduled in ${delay}ms`); + this.task = this.asyncQueue.enqueueAfterDelay("index_backfill" /* TimerId.IndexBackfill */, delay, async () => { + this.task = null; + try { + const documentsProcessed = await this.backfiller.backfill(); + logDebug(LOG_TAG$h, `Documents written: ${documentsProcessed}`); + } + catch (e) { + if (isIndexedDbTransactionError(e)) { + logDebug(LOG_TAG$h, 'Ignoring IndexedDB error during index backfill: ', e); + } + else { + await ignoreIfPrimaryLeaseLoss(e); + } + } + await this.schedule(REGULAR_BACKFILL_DELAY_MS); + }); + } +} +/** Implements the steps for backfilling indexes. */ +class IndexBackfiller { + constructor( + /** + * LocalStore provides access to IndexManager and LocalDocumentView. + * These properties will update when the user changes. Consequently, + * making a local copy of IndexManager and LocalDocumentView will require + * updates over time. The simpler solution is to rely on LocalStore to have + * an up-to-date references to IndexManager and LocalDocumentStore. + */ + localStore, persistence) { + this.localStore = localStore; + this.persistence = persistence; + } + async backfill(maxDocumentsToProcess = MAX_DOCUMENTS_TO_PROCESS) { + return this.persistence.runTransaction('Backfill Indexes', 'readwrite-primary', txn => this.writeIndexEntries(txn, maxDocumentsToProcess)); + } + /** Writes index entries until the cap is reached. Returns the number of documents processed. */ + writeIndexEntries(transaction, maxDocumentsToProcess) { + const processedCollectionGroups = new Set(); + let documentsRemaining = maxDocumentsToProcess; + let continueLoop = true; + return PersistencePromise.doWhile(() => continueLoop === true && documentsRemaining > 0, () => { + return this.localStore.indexManager + .getNextCollectionGroupToUpdate(transaction) + .next((collectionGroup) => { + if (collectionGroup === null || + processedCollectionGroups.has(collectionGroup)) { + continueLoop = false; + } + else { + logDebug(LOG_TAG$h, `Processing collection: ${collectionGroup}`); + return this.writeEntriesForCollectionGroup(transaction, collectionGroup, documentsRemaining).next(documentsProcessed => { + documentsRemaining -= documentsProcessed; + processedCollectionGroups.add(collectionGroup); + }); + } + }); + }).next(() => maxDocumentsToProcess - documentsRemaining); + } + /** + * Writes entries for the provided collection group. Returns the number of documents processed. + */ + writeEntriesForCollectionGroup(transaction, collectionGroup, documentsRemainingUnderCap) { + // Use the earliest offset of all field indexes to query the local cache. + return this.localStore.indexManager + .getMinOffsetFromCollectionGroup(transaction, collectionGroup) + .next(existingOffset => this.localStore.localDocuments + .getNextDocuments(transaction, collectionGroup, existingOffset, documentsRemainingUnderCap) + .next(nextBatch => { + const docs = nextBatch.changes; + return this.localStore.indexManager + .updateIndexEntries(transaction, docs) + .next(() => this.getNewOffset(existingOffset, nextBatch)) + .next(newOffset => { + logDebug(LOG_TAG$h, `Updating offset: ${newOffset}`); + return this.localStore.indexManager.updateCollectionGroup(transaction, collectionGroup, newOffset); + }) + .next(() => docs.size); + })); + } + /** Returns the next offset based on the provided documents. */ + getNewOffset(existingOffset, lookupResult) { + let maxOffset = existingOffset; + lookupResult.changes.forEach((key, document) => { + const newOffset = newIndexOffsetFromDocument(document); + if (indexOffsetComparator(newOffset, maxOffset) > 0) { + maxOffset = newOffset; + } + }); + return new IndexOffset(maxOffset.readTime, maxOffset.documentKey, Math.max(lookupResult.batchId, existingOffset.largestBatchId)); + } +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to + * exceed. All subsequent calls to next will return increasing values. If provided with a + * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as + * well as write out sequence numbers that it produces via `next()`. + */ +class ListenSequence { + constructor(previousValue, sequenceNumberSyncer) { + this.previousValue = previousValue; + if (sequenceNumberSyncer) { + sequenceNumberSyncer.sequenceNumberHandler = sequenceNumber => this.setPreviousValue(sequenceNumber); + this.writeNewSequenceNumber = sequenceNumber => sequenceNumberSyncer.writeSequenceNumber(sequenceNumber); + } + } + setPreviousValue(externalPreviousValue) { + this.previousValue = Math.max(externalPreviousValue, this.previousValue); + return this.previousValue; + } + next() { + const nextValue = ++this.previousValue; + if (this.writeNewSequenceNumber) { + this.writeNewSequenceNumber(nextValue); + } + return nextValue; + } +} +ListenSequence.INVALID = -1; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const escapeChar = '\u0001'; +const encodedSeparatorChar = '\u0001'; +const encodedNul = '\u0010'; +const encodedEscape = '\u0011'; +/** + * Encodes a resource path into a IndexedDb-compatible string form. + */ +function encodeResourcePath(path) { + let result = ''; + for (let i = 0; i < path.length; i++) { + if (result.length > 0) { + result = encodeSeparator(result); + } + result = encodeSegment(path.get(i), result); + } + return encodeSeparator(result); +} +/** Encodes a single segment of a resource path into the given result */ +function encodeSegment(segment, resultBuf) { + let result = resultBuf; + const length = segment.length; + for (let i = 0; i < length; i++) { + const c = segment.charAt(i); + switch (c) { + case '\0': + result += escapeChar + encodedNul; + break; + case escapeChar: + result += escapeChar + encodedEscape; + break; + default: + result += c; + } + } + return result; +} +/** Encodes a path separator into the given result */ +function encodeSeparator(result) { + return result + escapeChar + encodedSeparatorChar; +} +/** + * Decodes the given IndexedDb-compatible string form of a resource path into + * a ResourcePath instance. Note that this method is not suitable for use with + * decoding resource names from the server; those are One Platform format + * strings. + */ +function decodeResourcePath(path) { + // Event the empty path must encode as a path of at least length 2. A path + // with exactly 2 must be the empty path. + const length = path.length; + hardAssert(length >= 2, 0xfb98, { path }); + if (length === 2) { + hardAssert(path.charAt(0) === escapeChar && path.charAt(1) === encodedSeparatorChar, 0xdb51, { path }); + return ResourcePath.emptyPath(); + } + // Escape characters cannot exist past the second-to-last position in the + // source value. + const lastReasonableEscapeIndex = length - 2; + const segments = []; + let segmentBuilder = ''; + for (let start = 0; start < length;) { + // The last two characters of a valid encoded path must be a separator, so + // there must be an end to this segment. + const end = path.indexOf(escapeChar, start); + if (end < 0 || end > lastReasonableEscapeIndex) { + fail(0xc553, { path }); + } + const next = path.charAt(end + 1); + switch (next) { + case encodedSeparatorChar: + const currentPiece = path.substring(start, end); + let segment; + if (segmentBuilder.length === 0) { + // Avoid copying for the common case of a segment that excludes \0 + // and \001 + segment = currentPiece; + } + else { + segmentBuilder += currentPiece; + segment = segmentBuilder; + segmentBuilder = ''; + } + segments.push(segment); + break; + case encodedNul: + segmentBuilder += path.substring(start, end); + segmentBuilder += '\0'; + break; + case encodedEscape: + // The escape character can be used in the output to encode itself. + segmentBuilder += path.substring(start, end + 1); + break; + default: + fail(0xeeef, { path }); + } + start = end + 2; + } + return new ResourcePath(segments); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const DbRemoteDocumentStore$1 = 'remoteDocuments'; + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Name of the IndexedDb object store. + * + * Note that the name 'owner' is chosen to ensure backwards compatibility with + * older clients that only supported single locked access to the persistence + * layer. + */ +const DbPrimaryClientStore = 'owner'; +/** + * The key string used for the single object that exists in the + * DbPrimaryClient store. + */ +const DbPrimaryClientKey = 'owner'; +/** Name of the IndexedDb object store. */ +const DbMutationQueueStore = 'mutationQueues'; +/** Keys are automatically assigned via the userId property. */ +const DbMutationQueueKeyPath = 'userId'; +/** Name of the IndexedDb object store. */ +const DbMutationBatchStore = 'mutations'; +/** Keys are automatically assigned via the userId, batchId properties. */ +const DbMutationBatchKeyPath = 'batchId'; +/** The index name for lookup of mutations by user. */ +const DbMutationBatchUserMutationsIndex = 'userMutationsIndex'; +/** The user mutations index is keyed by [userId, batchId] pairs. */ +const DbMutationBatchUserMutationsKeyPath = ['userId', 'batchId']; +/** + * Creates a [userId] key for use in the DbDocumentMutations index to iterate + * over all of a user's document mutations. + */ +function newDbDocumentMutationPrefixForUser(userId) { + return [userId]; +} +/** + * Creates a [userId, encodedPath] key for use in the DbDocumentMutations + * index to iterate over all at document mutations for a given path or lower. + */ +function newDbDocumentMutationPrefixForPath(userId, path) { + return [userId, encodeResourcePath(path)]; +} +/** + * Creates a full index key of [userId, encodedPath, batchId] for inserting + * and deleting into the DbDocumentMutations index. + */ +function newDbDocumentMutationKey(userId, path, batchId) { + return [userId, encodeResourcePath(path), batchId]; +} +/** + * Because we store all the useful information for this store in the key, + * there is no useful information to store as the value. The raw (unencoded) + * path cannot be stored because IndexedDb doesn't store prototype + * information. + */ +const DbDocumentMutationPlaceholder = {}; +const DbDocumentMutationStore = 'documentMutations'; +const DbRemoteDocumentStore = 'remoteDocumentsV14'; +/** + * The primary key of the remote documents store, which allows for efficient + * access by collection path and read time. + */ +const DbRemoteDocumentKeyPath = [ + 'prefixPath', + 'collectionGroup', + 'readTime', + 'documentId' +]; +/** An index that provides access to documents by key. */ +const DbRemoteDocumentDocumentKeyIndex = 'documentKeyIndex'; +const DbRemoteDocumentDocumentKeyIndexPath = [ + 'prefixPath', + 'collectionGroup', + 'documentId' +]; +/** + * An index that provides access to documents by collection group and read + * time. + * + * This index is used by the index backfiller. + */ +const DbRemoteDocumentCollectionGroupIndex = 'collectionGroupIndex'; +const DbRemoteDocumentCollectionGroupIndexPath = [ + 'collectionGroup', + 'readTime', + 'prefixPath', + 'documentId' +]; +const DbRemoteDocumentGlobalStore = 'remoteDocumentGlobal'; +const DbRemoteDocumentGlobalKey = 'remoteDocumentGlobalKey'; +const DbTargetStore = 'targets'; +/** Keys are automatically assigned via the targetId property. */ +const DbTargetKeyPath = 'targetId'; +/** The name of the queryTargets index. */ +const DbTargetQueryTargetsIndexName = 'queryTargetsIndex'; +/** + * The index of all canonicalIds to the targets that they match. This is not + * a unique mapping because canonicalId does not promise a unique name for all + * possible queries, so we append the targetId to make the mapping unique. + */ +const DbTargetQueryTargetsKeyPath = ['canonicalId', 'targetId']; +/** Name of the IndexedDb object store. */ +const DbTargetDocumentStore = 'targetDocuments'; +/** Keys are automatically assigned via the targetId, path properties. */ +const DbTargetDocumentKeyPath = ['targetId', 'path']; +/** The index name for the reverse index. */ +const DbTargetDocumentDocumentTargetsIndex = 'documentTargetsIndex'; +/** We also need to create the reverse index for these properties. */ +const DbTargetDocumentDocumentTargetsKeyPath = ['path', 'targetId']; +/** + * The key string used for the single object that exists in the + * DbTargetGlobal store. + */ +const DbTargetGlobalKey = 'targetGlobalKey'; +const DbTargetGlobalStore = 'targetGlobal'; +/** Name of the IndexedDb object store. */ +const DbCollectionParentStore = 'collectionParents'; +/** Keys are automatically assigned via the collectionId, parent properties. */ +const DbCollectionParentKeyPath = ['collectionId', 'parent']; +/** Name of the IndexedDb object store. */ +const DbClientMetadataStore = 'clientMetadata'; +/** Keys are automatically assigned via the clientId properties. */ +const DbClientMetadataKeyPath = 'clientId'; +/** Name of the IndexedDb object store. */ +const DbBundleStore = 'bundles'; +const DbBundleKeyPath = 'bundleId'; +/** Name of the IndexedDb object store. */ +const DbNamedQueryStore = 'namedQueries'; +const DbNamedQueryKeyPath = 'name'; +/** Name of the IndexedDb object store. */ +const DbIndexConfigurationStore = 'indexConfiguration'; +const DbIndexConfigurationKeyPath = 'indexId'; +/** + * An index that provides access to the index configurations by collection + * group. + * + * PORTING NOTE: iOS and Android maintain this index in-memory, but this is + * not possible here as the Web client supports concurrent access to + * persistence via multi-tab. + */ +const DbIndexConfigurationCollectionGroupIndex = 'collectionGroupIndex'; +const DbIndexConfigurationCollectionGroupIndexPath = 'collectionGroup'; +/** Name of the IndexedDb object store. */ +const DbIndexStateStore = 'indexState'; +const DbIndexStateKeyPath = ['indexId', 'uid']; +/** + * An index that provides access to documents in a collection sorted by last + * update time. Used by the backfiller. + * + * PORTING NOTE: iOS and Android maintain this index in-memory, but this is + * not possible here as the Web client supports concurrent access to + * persistence via multi-tab. + */ +const DbIndexStateSequenceNumberIndex = 'sequenceNumberIndex'; +const DbIndexStateSequenceNumberIndexPath = ['uid', 'sequenceNumber']; +/** Name of the IndexedDb object store. */ +const DbIndexEntryStore = 'indexEntries'; +const DbIndexEntryKeyPath = [ + 'indexId', + 'uid', + 'arrayValue', + 'directionalValue', + 'orderedDocumentKey', + 'documentKey' +]; +const DbIndexEntryDocumentKeyIndex = 'documentKeyIndex'; +const DbIndexEntryDocumentKeyIndexPath = [ + 'indexId', + 'uid', + 'orderedDocumentKey' +]; +/** Name of the IndexedDb object store. */ +const DbDocumentOverlayStore = 'documentOverlays'; +const DbDocumentOverlayKeyPath = [ + 'userId', + 'collectionPath', + 'documentId' +]; +const DbDocumentOverlayCollectionPathOverlayIndex = 'collectionPathOverlayIndex'; +const DbDocumentOverlayCollectionPathOverlayIndexPath = [ + 'userId', + 'collectionPath', + 'largestBatchId' +]; +const DbDocumentOverlayCollectionGroupOverlayIndex = 'collectionGroupOverlayIndex'; +const DbDocumentOverlayCollectionGroupOverlayIndexPath = [ + 'userId', + 'collectionGroup', + 'largestBatchId' +]; +/** Name of the IndexedDb object store. */ +const DbGlobalsStore = 'globals'; +const DbGlobalsKeyPath = 'name'; +// Visible for testing +const V1_STORES = [ + DbMutationQueueStore, + DbMutationBatchStore, + DbDocumentMutationStore, + DbRemoteDocumentStore$1, + DbTargetStore, + DbPrimaryClientStore, + DbTargetGlobalStore, + DbTargetDocumentStore +]; +// Visible for testing +const V3_STORES = V1_STORES; +// Note: DbRemoteDocumentChanges is no longer used and dropped with v9. +const V4_STORES = [...V3_STORES, DbClientMetadataStore]; +const V6_STORES = [...V4_STORES, DbRemoteDocumentGlobalStore]; +const V8_STORES = [...V6_STORES, DbCollectionParentStore]; +const V11_STORES = [...V8_STORES, DbBundleStore, DbNamedQueryStore]; +const V12_STORES = [...V11_STORES, DbDocumentOverlayStore]; +const V13_STORES = [ + DbMutationQueueStore, + DbMutationBatchStore, + DbDocumentMutationStore, + DbRemoteDocumentStore, + DbTargetStore, + DbPrimaryClientStore, + DbTargetGlobalStore, + DbTargetDocumentStore, + DbClientMetadataStore, + DbRemoteDocumentGlobalStore, + DbCollectionParentStore, + DbBundleStore, + DbNamedQueryStore, + DbDocumentOverlayStore +]; +const V14_STORES = V13_STORES; +const V15_STORES = [ + ...V14_STORES, + DbIndexConfigurationStore, + DbIndexStateStore, + DbIndexEntryStore +]; +const V16_STORES = V15_STORES; +const V17_STORES = [...V15_STORES, DbGlobalsStore]; +const V18_STORES = V17_STORES; +/** Returns the object stores for the provided schema. */ +function getObjectStores(schemaVersion) { + if (schemaVersion === 18) { + return V18_STORES; + } + else if (schemaVersion === 17) { + return V17_STORES; + } + else if (schemaVersion === 16) { + return V16_STORES; + } + else if (schemaVersion === 15) { + return V15_STORES; + } + else if (schemaVersion === 14) { + return V14_STORES; + } + else if (schemaVersion === 13) { + return V13_STORES; + } + else if (schemaVersion === 12) { + return V12_STORES; + } + else if (schemaVersion === 11) { + return V11_STORES; + } + else { + fail(0xeb55); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class IndexedDbTransaction extends PersistenceTransaction { + constructor(simpleDbTransaction, currentSequenceNumber) { + super(); + this.simpleDbTransaction = simpleDbTransaction; + this.currentSequenceNumber = currentSequenceNumber; + } +} +function getStore(txn, store) { + const indexedDbTransaction = debugCast(txn); + return SimpleDb.getStore(indexedDbTransaction.simpleDbTransaction, store); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function objectSize(obj) { + let count = 0; + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + count++; + } + } + return count; +} +function forEach(obj, fn) { + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + fn(key, obj[key]); + } + } +} +function mapToArray(obj, fn) { + const result = []; + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + result.push(fn(obj[key], key, obj)); + } + } + return result; +} +function isEmpty(obj) { + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + return false; + } + } + return true; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// An immutable sorted map implementation, based on a Left-leaning Red-Black +// tree. +class SortedMap { + constructor(comparator, root) { + this.comparator = comparator; + this.root = root ? root : LLRBNode.EMPTY; + } + // Returns a copy of the map, with the specified key/value added or replaced. + insert(key, value) { + return new SortedMap(this.comparator, this.root + .insert(key, value, this.comparator) + .copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns a copy of the map, with the specified key removed. + remove(key) { + return new SortedMap(this.comparator, this.root + .remove(key, this.comparator) + .copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns the value of the node with the given key, or null. + get(key) { + let node = this.root; + while (!node.isEmpty()) { + const cmp = this.comparator(key, node.key); + if (cmp === 0) { + return node.value; + } + else if (cmp < 0) { + node = node.left; + } + else if (cmp > 0) { + node = node.right; + } + } + return null; + } + // Returns the index of the element in this sorted map, or -1 if it doesn't + // exist. + indexOf(key) { + // Number of nodes that were pruned when descending right + let prunedNodes = 0; + let node = this.root; + while (!node.isEmpty()) { + const cmp = this.comparator(key, node.key); + if (cmp === 0) { + return prunedNodes + node.left.size; + } + else if (cmp < 0) { + node = node.left; + } + else { + // Count all nodes left of the node plus the node itself + prunedNodes += node.left.size + 1; + node = node.right; + } + } + // Node not found + return -1; + } + isEmpty() { + return this.root.isEmpty(); + } + // Returns the total number of nodes in the map. + get size() { + return this.root.size; + } + // Returns the minimum key in the map. + minKey() { + return this.root.minKey(); + } + // Returns the maximum key in the map. + maxKey() { + return this.root.maxKey(); + } + // Traverses the map in key order and calls the specified action function + // for each key/value pair. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(action) { + return this.root.inorderTraversal(action); + } + forEach(fn) { + this.inorderTraversal((k, v) => { + fn(k, v); + return false; + }); + } + toString() { + const descriptions = []; + this.inorderTraversal((k, v) => { + descriptions.push(`${k}:${v}`); + return false; + }); + return `{${descriptions.join(', ')}}`; + } + // Traverses the map in reverse key order and calls the specified action + // function for each key/value pair. If action returns true, traversal is + // aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(action) { + return this.root.reverseTraversal(action); + } + // Returns an iterator over the SortedMap. + getIterator() { + return new SortedMapIterator(this.root, null, this.comparator, false); + } + getIteratorFrom(key) { + return new SortedMapIterator(this.root, key, this.comparator, false); + } + getReverseIterator() { + return new SortedMapIterator(this.root, null, this.comparator, true); + } + getReverseIteratorFrom(key) { + return new SortedMapIterator(this.root, key, this.comparator, true); + } +} // end SortedMap +// An iterator over an LLRBNode. +class SortedMapIterator { + constructor(node, startKey, comparator, isReverse) { + this.isReverse = isReverse; + this.nodeStack = []; + let cmp = 1; + while (!node.isEmpty()) { + cmp = startKey ? comparator(node.key, startKey) : 1; + // flip the comparison if we're going in reverse + if (startKey && isReverse) { + cmp *= -1; + } + if (cmp < 0) { + // This node is less than our start key. ignore it + if (this.isReverse) { + node = node.left; + } + else { + node = node.right; + } + } + else if (cmp === 0) { + // This node is exactly equal to our start key. Push it on the stack, + // but stop iterating; + this.nodeStack.push(node); + break; + } + else { + // This node is greater than our start key, add it to the stack and move + // to the next one + this.nodeStack.push(node); + if (this.isReverse) { + node = node.right; + } + else { + node = node.left; + } + } + } + } + getNext() { + let node = this.nodeStack.pop(); + const result = { key: node.key, value: node.value }; + if (this.isReverse) { + node = node.left; + while (!node.isEmpty()) { + this.nodeStack.push(node); + node = node.right; + } + } + else { + node = node.right; + while (!node.isEmpty()) { + this.nodeStack.push(node); + node = node.left; + } + } + return result; + } + hasNext() { + return this.nodeStack.length > 0; + } + peek() { + if (this.nodeStack.length === 0) { + return null; + } + const node = this.nodeStack[this.nodeStack.length - 1]; + return { key: node.key, value: node.value }; + } +} // end SortedMapIterator +// Represents a node in a Left-leaning Red-Black tree. +class LLRBNode { + constructor(key, value, color, left, right) { + this.key = key; + this.value = value; + this.color = color != null ? color : LLRBNode.RED; + this.left = left != null ? left : LLRBNode.EMPTY; + this.right = right != null ? right : LLRBNode.EMPTY; + this.size = this.left.size + 1 + this.right.size; + } + // Returns a copy of the current node, optionally replacing pieces of it. + copy(key, value, color, left, right) { + return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right); + } + isEmpty() { + return false; + } + // Traverses the tree in key order and calls the specified action function + // for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(action) { + return (this.left.inorderTraversal(action) || + action(this.key, this.value) || + this.right.inorderTraversal(action)); + } + // Traverses the tree in reverse key order and calls the specified action + // function for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(action) { + return (this.right.reverseTraversal(action) || + action(this.key, this.value) || + this.left.reverseTraversal(action)); + } + // Returns the minimum node in the tree. + min() { + if (this.left.isEmpty()) { + return this; + } + else { + return this.left.min(); + } + } + // Returns the maximum key in the tree. + minKey() { + return this.min().key; + } + // Returns the maximum key in the tree. + maxKey() { + if (this.right.isEmpty()) { + return this.key; + } + else { + return this.right.maxKey(); + } + } + // Returns new tree, with the key/value added. + insert(key, value, comparator) { + let n = this; + const cmp = comparator(key, n.key); + if (cmp < 0) { + n = n.copy(null, null, null, n.left.insert(key, value, comparator), null); + } + else if (cmp === 0) { + n = n.copy(null, value, null, null, null); + } + else { + n = n.copy(null, null, null, null, n.right.insert(key, value, comparator)); + } + return n.fixUp(); + } + removeMin() { + if (this.left.isEmpty()) { + return LLRBNode.EMPTY; + } + let n = this; + if (!n.left.isRed() && !n.left.left.isRed()) { + n = n.moveRedLeft(); + } + n = n.copy(null, null, null, n.left.removeMin(), null); + return n.fixUp(); + } + // Returns new tree, with the specified item removed. + remove(key, comparator) { + let smallest; + let n = this; + if (comparator(key, n.key) < 0) { + if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) { + n = n.moveRedLeft(); + } + n = n.copy(null, null, null, n.left.remove(key, comparator), null); + } + else { + if (n.left.isRed()) { + n = n.rotateRight(); + } + if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) { + n = n.moveRedRight(); + } + if (comparator(key, n.key) === 0) { + if (n.right.isEmpty()) { + return LLRBNode.EMPTY; + } + else { + smallest = n.right.min(); + n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin()); + } + } + n = n.copy(null, null, null, null, n.right.remove(key, comparator)); + } + return n.fixUp(); + } + isRed() { + return this.color; + } + // Returns new tree after performing any needed rotations. + fixUp() { + let n = this; + if (n.right.isRed() && !n.left.isRed()) { + n = n.rotateLeft(); + } + if (n.left.isRed() && n.left.left.isRed()) { + n = n.rotateRight(); + } + if (n.left.isRed() && n.right.isRed()) { + n = n.colorFlip(); + } + return n; + } + moveRedLeft() { + let n = this.colorFlip(); + if (n.right.left.isRed()) { + n = n.copy(null, null, null, null, n.right.rotateRight()); + n = n.rotateLeft(); + n = n.colorFlip(); + } + return n; + } + moveRedRight() { + let n = this.colorFlip(); + if (n.left.left.isRed()) { + n = n.rotateRight(); + n = n.colorFlip(); + } + return n; + } + rotateLeft() { + const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left); + return this.right.copy(null, null, this.color, nl, null); + } + rotateRight() { + const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null); + return this.left.copy(null, null, this.color, null, nr); + } + colorFlip() { + const left = this.left.copy(null, null, !this.left.color, null, null); + const right = this.right.copy(null, null, !this.right.color, null, null); + return this.copy(null, null, !this.color, left, right); + } + // For testing. + checkMaxDepth() { + const blackDepth = this.check(); + if (Math.pow(2.0, blackDepth) <= this.size + 1) { + return true; + } + else { + return false; + } + } + // In a balanced RB tree, the black-depth (number of black nodes) from root to + // leaves is equal on both sides. This function verifies that or asserts. + check() { + if (this.isRed() && this.left.isRed()) { + throw fail(0xaad2, { + key: this.key, + value: this.value + }); + } + if (this.right.isRed()) { + throw fail(0x3721, { + key: this.key, + value: this.value + }); + } + const blackDepth = this.left.check(); + if (blackDepth !== this.right.check()) { + throw fail(0x6d2d); + } + else { + return blackDepth + (this.isRed() ? 0 : 1); + } + } +} // end LLRBNode +// Empty node is shared between all LLRB trees. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +LLRBNode.EMPTY = null; +LLRBNode.RED = true; +LLRBNode.BLACK = false; +// Represents an empty node (a leaf node in the Red-Black Tree). +class LLRBEmptyNode { + constructor() { + this.size = 0; + } + get key() { + throw fail(0xe1a6); + } + get value() { + throw fail(0x3f0d); + } + get color() { + throw fail(0x4157); + } + get left() { + throw fail(0x741e); + } + get right() { + throw fail(0x901e); + } + // Returns a copy of the current node. + copy(key, value, color, left, right) { + return this; + } + // Returns a copy of the tree, with the specified key/value added. + insert(key, value, comparator) { + return new LLRBNode(key, value); + } + // Returns a copy of the tree, with the specified key removed. + remove(key, comparator) { + return this; + } + isEmpty() { + return true; + } + inorderTraversal(action) { + return false; + } + reverseTraversal(action) { + return false; + } + minKey() { + return null; + } + maxKey() { + return null; + } + isRed() { + return false; + } + // For testing. + checkMaxDepth() { + return true; + } + check() { + return 0; + } +} // end LLRBEmptyNode +LLRBNode.EMPTY = new LLRBEmptyNode(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * SortedSet is an immutable (copy-on-write) collection that holds elements + * in order specified by the provided comparator. + * + * NOTE: if provided comparator returns 0 for two elements, we consider them to + * be equal! + */ +class SortedSet { + constructor(comparator) { + this.comparator = comparator; + this.data = new SortedMap(this.comparator); + } + has(elem) { + return this.data.get(elem) !== null; + } + first() { + return this.data.minKey(); + } + last() { + return this.data.maxKey(); + } + get size() { + return this.data.size; + } + indexOf(elem) { + return this.data.indexOf(elem); + } + /** Iterates elements in order defined by "comparator" */ + forEach(cb) { + this.data.inorderTraversal((k, v) => { + cb(k); + return false; + }); + } + /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ + forEachInRange(range, cb) { + const iter = this.data.getIteratorFrom(range[0]); + while (iter.hasNext()) { + const elem = iter.getNext(); + if (this.comparator(elem.key, range[1]) >= 0) { + return; + } + cb(elem.key); + } + } + /** + * Iterates over `elem`s such that: start <= elem until false is returned. + */ + forEachWhile(cb, start) { + let iter; + if (start !== undefined) { + iter = this.data.getIteratorFrom(start); + } + else { + iter = this.data.getIterator(); + } + while (iter.hasNext()) { + const elem = iter.getNext(); + const result = cb(elem.key); + if (!result) { + return; + } + } + } + /** Finds the least element greater than or equal to `elem`. */ + firstAfterOrEqual(elem) { + const iter = this.data.getIteratorFrom(elem); + return iter.hasNext() ? iter.getNext().key : null; + } + getIterator() { + return new SortedSetIterator(this.data.getIterator()); + } + getIteratorFrom(key) { + return new SortedSetIterator(this.data.getIteratorFrom(key)); + } + /** Inserts or updates an element */ + add(elem) { + return this.copy(this.data.remove(elem).insert(elem, true)); + } + /** Deletes an element */ + delete(elem) { + if (!this.has(elem)) { + return this; + } + return this.copy(this.data.remove(elem)); + } + isEmpty() { + return this.data.isEmpty(); + } + unionWith(other) { + let result = this; + // Make sure `result` always refers to the larger one of the two sets. + if (result.size < other.size) { + result = other; + other = this; + } + other.forEach(elem => { + result = result.add(elem); + }); + return result; + } + isEqual(other) { + if (!(other instanceof SortedSet)) { + return false; + } + if (this.size !== other.size) { + return false; + } + const thisIt = this.data.getIterator(); + const otherIt = other.data.getIterator(); + while (thisIt.hasNext()) { + const thisElem = thisIt.getNext().key; + const otherElem = otherIt.getNext().key; + if (this.comparator(thisElem, otherElem) !== 0) { + return false; + } + } + return true; + } + toArray() { + const res = []; + this.forEach(targetId => { + res.push(targetId); + }); + return res; + } + toString() { + const result = []; + this.forEach(elem => result.push(elem)); + return 'SortedSet(' + result.toString() + ')'; + } + copy(data) { + const result = new SortedSet(this.comparator); + result.data = data; + return result; + } +} +class SortedSetIterator { + constructor(iter) { + this.iter = iter; + } + getNext() { + return this.iter.getNext().key; + } + hasNext() { + return this.iter.hasNext(); + } +} +/** + * Compares two sorted sets for equality using their natural ordering. The + * method computes the intersection and invokes `onAdd` for every element that + * is in `after` but not `before`. `onRemove` is invoked for every element in + * `before` but missing from `after`. + * + * The method creates a copy of both `before` and `after` and runs in O(n log + * n), where n is the size of the two lists. + * + * @param before - The elements that exist in the original set. + * @param after - The elements to diff against the original set. + * @param comparator - The comparator for the elements in before and after. + * @param onAdd - A function to invoke for every element that is part of ` + * after` but not `before`. + * @param onRemove - A function to invoke for every element that is part of + * `before` but not `after`. + */ +function diffSortedSets(before, after, comparator, onAdd, onRemove) { + const beforeIt = before.getIterator(); + const afterIt = after.getIterator(); + let beforeValue = advanceIterator(beforeIt); + let afterValue = advanceIterator(afterIt); + // Walk through the two sets at the same time, using the ordering defined by + // `comparator`. + while (beforeValue || afterValue) { + let added = false; + let removed = false; + if (beforeValue && afterValue) { + const cmp = comparator(beforeValue, afterValue); + if (cmp < 0) { + // The element was removed if the next element in our ordered + // walkthrough is only in `before`. + removed = true; + } + else if (cmp > 0) { + // The element was added if the next element in our ordered walkthrough + // is only in `after`. + added = true; + } + } + else if (beforeValue != null) { + removed = true; + } + else { + added = true; + } + if (added) { + onAdd(afterValue); + afterValue = advanceIterator(afterIt); + } + else if (removed) { + onRemove(beforeValue); + beforeValue = advanceIterator(beforeIt); + } + else { + beforeValue = advanceIterator(beforeIt); + afterValue = advanceIterator(afterIt); + } + } +} +/** + * Returns the next element from the iterator or `undefined` if none available. + */ +function advanceIterator(it) { + return it.hasNext() ? it.getNext() : undefined; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provides a set of fields that can be used to partially patch a document. + * FieldMask is used in conjunction with ObjectValue. + * Examples: + * foo - Overwrites foo entirely with the provided value. If foo is not + * present in the companion ObjectValue, the field is deleted. + * foo.bar - Overwrites only the field bar of the object foo. + * If foo is not an object, foo is replaced with an object + * containing foo + */ +class FieldMask { + constructor(fields) { + this.fields = fields; + // TODO(dimond): validation of FieldMask + // Sort the field mask to support `FieldMask.isEqual()` and assert below. + fields.sort(FieldPath$1.comparator); + } + static empty() { + return new FieldMask([]); + } + /** + * Returns a new FieldMask object that is the result of adding all the given + * fields paths to this field mask. + */ + unionWith(extraFields) { + let mergedMaskSet = new SortedSet(FieldPath$1.comparator); + for (const fieldPath of this.fields) { + mergedMaskSet = mergedMaskSet.add(fieldPath); + } + for (const fieldPath of extraFields) { + mergedMaskSet = mergedMaskSet.add(fieldPath); + } + return new FieldMask(mergedMaskSet.toArray()); + } + /** + * Verifies that `fieldPath` is included by at least one field in this field + * mask. + * + * This is an O(n) operation, where `n` is the size of the field mask. + */ + covers(fieldPath) { + for (const fieldMaskPath of this.fields) { + if (fieldMaskPath.isPrefixOf(fieldPath)) { + return true; + } + } + return false; + } + isEqual(other) { + return arrayEquals(this.fields, other.fields, (l, r) => l.isEqual(r)); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Converts a Base64 encoded string to a binary string. */ +function decodeBase64(encoded) { + // Note: We used to validate the base64 string here via a regular expression. + // This was removed to improve the performance of indexing. + return Buffer.from(encoded, 'base64').toString('binary'); +} +/** Converts a binary string to a Base64 encoded string. */ +function encodeBase64(raw) { + return Buffer.from(raw, 'binary').toString('base64'); +} +/** True if and only if the Base64 conversion functions are available. */ +function isBase64Available() { + return true; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Immutable class that represents a "proto" byte string. + * + * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when + * sent on the wire. This class abstracts away this differentiation by holding + * the proto byte string in a common class that must be converted into a string + * before being sent as a proto. + * @internal + */ +class ByteString { + constructor(binaryString) { + this.binaryString = binaryString; + } + static fromBase64String(base64) { + const binaryString = decodeBase64(base64); + return new ByteString(binaryString); + } + static fromUint8Array(array) { + // TODO(indexing); Remove the copy of the byte string here as this method + // is frequently called during indexing. + const binaryString = binaryStringFromUint8Array(array); + return new ByteString(binaryString); + } + [Symbol.iterator]() { + let i = 0; + return { + next: () => { + if (i < this.binaryString.length) { + return { value: this.binaryString.charCodeAt(i++), done: false }; + } + else { + return { value: undefined, done: true }; + } + } + }; + } + toBase64() { + return encodeBase64(this.binaryString); + } + toUint8Array() { + return uint8ArrayFromBinaryString(this.binaryString); + } + approximateByteSize() { + return this.binaryString.length * 2; + } + compareTo(other) { + return primitiveComparator(this.binaryString, other.binaryString); + } + isEqual(other) { + return this.binaryString === other.binaryString; + } +} +ByteString.EMPTY_BYTE_STRING = new ByteString(''); +/** + * Helper function to convert an Uint8array to a binary string. + */ +function binaryStringFromUint8Array(array) { + let binaryString = ''; + for (let i = 0; i < array.length; ++i) { + binaryString += String.fromCharCode(array[i]); + } + return binaryString; +} +/** + * Helper function to convert a binary string to an Uint8Array. + */ +function uint8ArrayFromBinaryString(binaryString) { + const buffer = new Uint8Array(binaryString.length); + for (let i = 0; i < binaryString.length; i++) { + buffer[i] = binaryString.charCodeAt(i); + } + return buffer; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// A RegExp matching ISO 8601 UTC timestamps with optional fraction. +const ISO_TIMESTAMP_REG_EXP = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/); +/** + * Converts the possible Proto values for a timestamp value into a "seconds and + * nanos" representation. + */ +function normalizeTimestamp(date) { + hardAssert(!!date, 0x986a); + // The json interface (for the browser) will return an iso timestamp string, + // while the proto js library (for node) will return a + // google.protobuf.Timestamp instance. + if (typeof date === 'string') { + // The date string can have higher precision (nanos) than the Date class + // (millis), so we do some custom parsing here. + // Parse the nanos right out of the string. + let nanos = 0; + const fraction = ISO_TIMESTAMP_REG_EXP.exec(date); + hardAssert(!!fraction, 0xb5de, { + timestamp: date + }); + if (fraction[1]) { + // Pad the fraction out to 9 digits (nanos). + let nanoStr = fraction[1]; + nanoStr = (nanoStr + '000000000').substr(0, 9); + nanos = Number(nanoStr); + } + // Parse the date to get the seconds. + const parsedDate = new Date(date); + const seconds = Math.floor(parsedDate.getTime() / 1000); + return { seconds, nanos }; + } + else { + // TODO(b/37282237): Use strings for Proto3 timestamps + // assert(!this.options.useProto3Json, + // 'The timestamp instance format requires Proto JS.'); + const seconds = normalizeNumber(date.seconds); + const nanos = normalizeNumber(date.nanos); + return { seconds, nanos }; + } +} +/** + * Converts the possible Proto types for numbers into a JavaScript number. + * Returns 0 if the value is not numeric. + */ +function normalizeNumber(value) { + // TODO(bjornick): Handle int64 greater than 53 bits. + if (typeof value === 'number') { + return value; + } + else if (typeof value === 'string') { + return Number(value); + } + else { + return 0; + } +} +/** Converts the possible Proto types for Blobs into a ByteString. */ +function normalizeByteString(blob) { + if (typeof blob === 'string') { + return ByteString.fromBase64String(blob); + } + else { + return ByteString.fromUint8Array(blob); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a locally-applied ServerTimestamp. + * + * Server Timestamps are backed by MapValues that contain an internal field + * `__type__` with a value of `server_timestamp`. The previous value and local + * write time are stored in its `__previous_value__` and `__local_write_time__` + * fields respectively. + * + * Notes: + * - ServerTimestampValue instances are created as the result of applying a + * transform. They can only exist in the local view of a document. Therefore + * they do not need to be parsed or serialized. + * - When evaluated locally (e.g. for snapshot.data()), they by default + * evaluate to `null`. This behavior can be configured by passing custom + * FieldValueOptions to value(). + * - With respect to other ServerTimestampValues, they sort by their + * localWriteTime. + */ +const SERVER_TIMESTAMP_SENTINEL = 'server_timestamp'; +const TYPE_KEY$1 = '__type__'; +const PREVIOUS_VALUE_KEY = '__previous_value__'; +const LOCAL_WRITE_TIME_KEY = '__local_write_time__'; +function isServerTimestamp(value) { + const type = (value?.mapValue?.fields || {})[TYPE_KEY$1]?.stringValue; + return type === SERVER_TIMESTAMP_SENTINEL; +} +/** + * Creates a new ServerTimestamp proto value (using the internal format). + */ +function serverTimestamp$1(localWriteTime, previousValue) { + const mapValue = { + fields: { + [TYPE_KEY$1]: { + stringValue: SERVER_TIMESTAMP_SENTINEL + }, + [LOCAL_WRITE_TIME_KEY]: { + timestampValue: { + seconds: localWriteTime.seconds, + nanos: localWriteTime.nanoseconds + } + } + } + }; + // We should avoid storing deeply nested server timestamp map values + // because we never use the intermediate "previous values". + // For example: + // previous: 42L, add: t1, result: t1 -> 42L + // previous: t1, add: t2, result: t2 -> 42L (NOT t2 -> t1 -> 42L) + // previous: t2, add: t3, result: t3 -> 42L (NOT t3 -> t2 -> t1 -> 42L) + // `getPreviousValue` recursively traverses server timestamps to find the + // least recent Value. + if (previousValue && isServerTimestamp(previousValue)) { + previousValue = getPreviousValue(previousValue); + } + if (previousValue) { + mapValue.fields[PREVIOUS_VALUE_KEY] = previousValue; + } + return { mapValue }; +} +/** + * Returns the value of the field before this ServerTimestamp was set. + * + * Preserving the previous values allows the user to display the last resoled + * value until the backend responds with the timestamp. + */ +function getPreviousValue(value) { + const previousValue = value.mapValue.fields[PREVIOUS_VALUE_KEY]; + if (isServerTimestamp(previousValue)) { + return getPreviousValue(previousValue); + } + return previousValue; +} +/** + * Returns the local time at which this timestamp was first set. + */ +function getLocalWriteTime(value) { + const localWriteTime = normalizeTimestamp(value.mapValue.fields[LOCAL_WRITE_TIME_KEY].timestampValue); + return new Timestamp(localWriteTime.seconds, localWriteTime.nanos); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class DatabaseInfo { + /** + * Constructs a DatabaseInfo using the provided host, databaseId and + * persistenceKey. + * + * @param databaseId - The database to use. + * @param appId - The Firebase App Id. + * @param persistenceKey - A unique identifier for this Firestore's local + * storage (used in conjunction with the databaseId). + * @param host - The Firestore backend host to connect to. + * @param ssl - Whether to use SSL when connecting. + * @param forceLongPolling - Whether to use the forceLongPolling option + * when using WebChannel as the network transport. + * @param autoDetectLongPolling - Whether to use the detectBufferingProxy + * option when using WebChannel as the network transport. + * @param longPollingOptions Options that configure long-polling. + * @param useFetchStreams Whether to use the Fetch API instead of + * XMLHTTPRequest + */ + constructor(databaseId, appId, persistenceKey, host, ssl, forceLongPolling, autoDetectLongPolling, longPollingOptions, useFetchStreams, isUsingEmulator) { + this.databaseId = databaseId; + this.appId = appId; + this.persistenceKey = persistenceKey; + this.host = host; + this.ssl = ssl; + this.forceLongPolling = forceLongPolling; + this.autoDetectLongPolling = autoDetectLongPolling; + this.longPollingOptions = longPollingOptions; + this.useFetchStreams = useFetchStreams; + this.isUsingEmulator = isUsingEmulator; + } +} +/** The default database name for a project. */ +const DEFAULT_DATABASE_NAME = '(default)'; +/** + * Represents the database ID a Firestore client is associated with. + * @internal + */ +class DatabaseId { + constructor(projectId, database) { + this.projectId = projectId; + this.database = database ? database : DEFAULT_DATABASE_NAME; + } + static empty() { + return new DatabaseId('', ''); + } + get isDefaultDatabase() { + return this.database === DEFAULT_DATABASE_NAME; + } + isEqual(other) { + return (other instanceof DatabaseId && + other.projectId === this.projectId && + other.database === this.database); + } +} +function databaseIdFromApp(app, database) { + if (!Object.prototype.hasOwnProperty.apply(app.options, ['projectId'])) { + throw new FirestoreError(Code.INVALID_ARGUMENT, '"projectId" not provided in firebase.initializeApp.'); + } + return new DatabaseId(app.options.projectId, database); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Sentinel value that sorts before any Mutation Batch ID. */ +const BATCHID_UNKNOWN = -1; +/** + * Returns whether a variable is either undefined or null. + */ +function isNullOrUndefined(value) { + return value === null || value === undefined; +} +/** Returns whether the value represents -0. */ +function isNegativeZero(value) { + // Detect if the value is -0.0. Based on polyfill from + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is + return value === 0 && 1 / value === 1 / -0; +} +/** + * Returns whether a value is an integer and in the safe integer range + * @param value - The value to test for being an integer and in the safe range + */ +function isSafeInteger(value) { + return (typeof value === 'number' && + Number.isInteger(value) && + !isNegativeZero(value) && + value <= Number.MAX_SAFE_INTEGER && + value >= Number.MIN_SAFE_INTEGER); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const TYPE_KEY = '__type__'; +const MAX_VALUE_TYPE = '__max__'; +const MAX_VALUE = { + mapValue: { + fields: { + '__type__': { stringValue: MAX_VALUE_TYPE } + } + } +}; +const VECTOR_VALUE_SENTINEL = '__vector__'; +const VECTOR_MAP_VECTORS_KEY = 'value'; +const MIN_VALUE = { + nullValue: 'NULL_VALUE' +}; +/** Extracts the backend's type order for the provided value. */ +function typeOrder(value) { + if ('nullValue' in value) { + return 0 /* TypeOrder.NullValue */; + } + else if ('booleanValue' in value) { + return 1 /* TypeOrder.BooleanValue */; + } + else if ('integerValue' in value || 'doubleValue' in value) { + return 2 /* TypeOrder.NumberValue */; + } + else if ('timestampValue' in value) { + return 3 /* TypeOrder.TimestampValue */; + } + else if ('stringValue' in value) { + return 5 /* TypeOrder.StringValue */; + } + else if ('bytesValue' in value) { + return 6 /* TypeOrder.BlobValue */; + } + else if ('referenceValue' in value) { + return 7 /* TypeOrder.RefValue */; + } + else if ('geoPointValue' in value) { + return 8 /* TypeOrder.GeoPointValue */; + } + else if ('arrayValue' in value) { + return 9 /* TypeOrder.ArrayValue */; + } + else if ('mapValue' in value) { + if (isServerTimestamp(value)) { + return 4 /* TypeOrder.ServerTimestampValue */; + } + else if (isMaxValue(value)) { + return 9007199254740991 /* TypeOrder.MaxValue */; + } + else if (isVectorValue(value)) { + return 10 /* TypeOrder.VectorValue */; + } + return 11 /* TypeOrder.ObjectValue */; + } + else { + return fail(0x6e87, { value }); + } +} +/** Tests `left` and `right` for equality based on the backend semantics. */ +function valueEquals(left, right) { + if (left === right) { + return true; + } + const leftType = typeOrder(left); + const rightType = typeOrder(right); + if (leftType !== rightType) { + return false; + } + switch (leftType) { + case 0 /* TypeOrder.NullValue */: + return true; + case 1 /* TypeOrder.BooleanValue */: + return left.booleanValue === right.booleanValue; + case 4 /* TypeOrder.ServerTimestampValue */: + return getLocalWriteTime(left).isEqual(getLocalWriteTime(right)); + case 3 /* TypeOrder.TimestampValue */: + return timestampEquals(left, right); + case 5 /* TypeOrder.StringValue */: + return left.stringValue === right.stringValue; + case 6 /* TypeOrder.BlobValue */: + return blobEquals(left, right); + case 7 /* TypeOrder.RefValue */: + return left.referenceValue === right.referenceValue; + case 8 /* TypeOrder.GeoPointValue */: + return geoPointEquals(left, right); + case 2 /* TypeOrder.NumberValue */: + return numberEquals(left, right); + case 9 /* TypeOrder.ArrayValue */: + return arrayEquals(left.arrayValue.values || [], right.arrayValue.values || [], valueEquals); + case 10 /* TypeOrder.VectorValue */: + case 11 /* TypeOrder.ObjectValue */: + return objectEquals(left, right); + case 9007199254740991 /* TypeOrder.MaxValue */: + return true; + default: + return fail(0xcbf8, { left }); + } +} +function timestampEquals(left, right) { + if (typeof left.timestampValue === 'string' && + typeof right.timestampValue === 'string' && + left.timestampValue.length === right.timestampValue.length) { + // Use string equality for ISO 8601 timestamps + return left.timestampValue === right.timestampValue; + } + const leftTimestamp = normalizeTimestamp(left.timestampValue); + const rightTimestamp = normalizeTimestamp(right.timestampValue); + return (leftTimestamp.seconds === rightTimestamp.seconds && + leftTimestamp.nanos === rightTimestamp.nanos); +} +function geoPointEquals(left, right) { + return (normalizeNumber(left.geoPointValue.latitude) === + normalizeNumber(right.geoPointValue.latitude) && + normalizeNumber(left.geoPointValue.longitude) === + normalizeNumber(right.geoPointValue.longitude)); +} +function blobEquals(left, right) { + return normalizeByteString(left.bytesValue).isEqual(normalizeByteString(right.bytesValue)); +} +function numberEquals(left, right) { + if ('integerValue' in left && 'integerValue' in right) { + return (normalizeNumber(left.integerValue) === normalizeNumber(right.integerValue)); + } + else if ('doubleValue' in left && 'doubleValue' in right) { + const n1 = normalizeNumber(left.doubleValue); + const n2 = normalizeNumber(right.doubleValue); + if (n1 === n2) { + return isNegativeZero(n1) === isNegativeZero(n2); + } + else { + return isNaN(n1) && isNaN(n2); + } + } + return false; +} +function objectEquals(left, right) { + const leftMap = left.mapValue.fields || {}; + const rightMap = right.mapValue.fields || {}; + if (objectSize(leftMap) !== objectSize(rightMap)) { + return false; + } + for (const key in leftMap) { + if (leftMap.hasOwnProperty(key)) { + if (rightMap[key] === undefined || + !valueEquals(leftMap[key], rightMap[key])) { + return false; + } + } + } + return true; +} +/** Returns true if the ArrayValue contains the specified element. */ +function arrayValueContains(haystack, needle) { + return ((haystack.values || []).find(v => valueEquals(v, needle)) !== undefined); +} +function valueCompare(left, right) { + if (left === right) { + return 0; + } + const leftType = typeOrder(left); + const rightType = typeOrder(right); + if (leftType !== rightType) { + return primitiveComparator(leftType, rightType); + } + switch (leftType) { + case 0 /* TypeOrder.NullValue */: + case 9007199254740991 /* TypeOrder.MaxValue */: + return 0; + case 1 /* TypeOrder.BooleanValue */: + return primitiveComparator(left.booleanValue, right.booleanValue); + case 2 /* TypeOrder.NumberValue */: + return compareNumbers(left, right); + case 3 /* TypeOrder.TimestampValue */: + return compareTimestamps(left.timestampValue, right.timestampValue); + case 4 /* TypeOrder.ServerTimestampValue */: + return compareTimestamps(getLocalWriteTime(left), getLocalWriteTime(right)); + case 5 /* TypeOrder.StringValue */: + return compareUtf8Strings(left.stringValue, right.stringValue); + case 6 /* TypeOrder.BlobValue */: + return compareBlobs(left.bytesValue, right.bytesValue); + case 7 /* TypeOrder.RefValue */: + return compareReferences(left.referenceValue, right.referenceValue); + case 8 /* TypeOrder.GeoPointValue */: + return compareGeoPoints(left.geoPointValue, right.geoPointValue); + case 9 /* TypeOrder.ArrayValue */: + return compareArrays(left.arrayValue, right.arrayValue); + case 10 /* TypeOrder.VectorValue */: + return compareVectors(left.mapValue, right.mapValue); + case 11 /* TypeOrder.ObjectValue */: + return compareMaps(left.mapValue, right.mapValue); + default: + throw fail(0x5ae0, { leftType }); + } +} +function compareNumbers(left, right) { + const leftNumber = normalizeNumber(left.integerValue || left.doubleValue); + const rightNumber = normalizeNumber(right.integerValue || right.doubleValue); + if (leftNumber < rightNumber) { + return -1; + } + else if (leftNumber > rightNumber) { + return 1; + } + else if (leftNumber === rightNumber) { + return 0; + } + else { + // one or both are NaN. + if (isNaN(leftNumber)) { + return isNaN(rightNumber) ? 0 : -1; + } + else { + return 1; + } + } +} +function compareTimestamps(left, right) { + if (typeof left === 'string' && + typeof right === 'string' && + left.length === right.length) { + return primitiveComparator(left, right); + } + const leftTimestamp = normalizeTimestamp(left); + const rightTimestamp = normalizeTimestamp(right); + const comparison = primitiveComparator(leftTimestamp.seconds, rightTimestamp.seconds); + if (comparison !== 0) { + return comparison; + } + return primitiveComparator(leftTimestamp.nanos, rightTimestamp.nanos); +} +function compareReferences(leftPath, rightPath) { + const leftSegments = leftPath.split('/'); + const rightSegments = rightPath.split('/'); + for (let i = 0; i < leftSegments.length && i < rightSegments.length; i++) { + const comparison = primitiveComparator(leftSegments[i], rightSegments[i]); + if (comparison !== 0) { + return comparison; + } + } + return primitiveComparator(leftSegments.length, rightSegments.length); +} +function compareGeoPoints(left, right) { + const comparison = primitiveComparator(normalizeNumber(left.latitude), normalizeNumber(right.latitude)); + if (comparison !== 0) { + return comparison; + } + return primitiveComparator(normalizeNumber(left.longitude), normalizeNumber(right.longitude)); +} +function compareBlobs(left, right) { + const leftBytes = normalizeByteString(left); + const rightBytes = normalizeByteString(right); + return leftBytes.compareTo(rightBytes); +} +function compareArrays(left, right) { + const leftArray = left.values || []; + const rightArray = right.values || []; + for (let i = 0; i < leftArray.length && i < rightArray.length; ++i) { + const compare = valueCompare(leftArray[i], rightArray[i]); + if (compare) { + return compare; + } + } + return primitiveComparator(leftArray.length, rightArray.length); +} +function compareVectors(left, right) { + const leftMap = left.fields || {}; + const rightMap = right.fields || {}; + // The vector is a map, but only vector value is compared. + const leftArrayValue = leftMap[VECTOR_MAP_VECTORS_KEY]?.arrayValue; + const rightArrayValue = rightMap[VECTOR_MAP_VECTORS_KEY]?.arrayValue; + const lengthCompare = primitiveComparator(leftArrayValue?.values?.length || 0, rightArrayValue?.values?.length || 0); + if (lengthCompare !== 0) { + return lengthCompare; + } + return compareArrays(leftArrayValue, rightArrayValue); +} +function compareMaps(left, right) { + if (left === MAX_VALUE.mapValue && right === MAX_VALUE.mapValue) { + return 0; + } + else if (left === MAX_VALUE.mapValue) { + return 1; + } + else if (right === MAX_VALUE.mapValue) { + return -1; + } + const leftMap = left.fields || {}; + const leftKeys = Object.keys(leftMap); + const rightMap = right.fields || {}; + const rightKeys = Object.keys(rightMap); + // Even though MapValues are likely sorted correctly based on their insertion + // order (e.g. when received from the backend), local modifications can bring + // elements out of order. We need to re-sort the elements to ensure that + // canonical IDs are independent of insertion order. + leftKeys.sort(); + rightKeys.sort(); + for (let i = 0; i < leftKeys.length && i < rightKeys.length; ++i) { + const keyCompare = compareUtf8Strings(leftKeys[i], rightKeys[i]); + if (keyCompare !== 0) { + return keyCompare; + } + const compare = valueCompare(leftMap[leftKeys[i]], rightMap[rightKeys[i]]); + if (compare !== 0) { + return compare; + } + } + return primitiveComparator(leftKeys.length, rightKeys.length); +} +/** + * Generates the canonical ID for the provided field value (as used in Target + * serialization). + */ +function canonicalId(value) { + return canonifyValue(value); +} +function canonifyValue(value) { + if ('nullValue' in value) { + return 'null'; + } + else if ('booleanValue' in value) { + return '' + value.booleanValue; + } + else if ('integerValue' in value) { + return '' + value.integerValue; + } + else if ('doubleValue' in value) { + return '' + value.doubleValue; + } + else if ('timestampValue' in value) { + return canonifyTimestamp(value.timestampValue); + } + else if ('stringValue' in value) { + return value.stringValue; + } + else if ('bytesValue' in value) { + return canonifyByteString(value.bytesValue); + } + else if ('referenceValue' in value) { + return canonifyReference(value.referenceValue); + } + else if ('geoPointValue' in value) { + return canonifyGeoPoint(value.geoPointValue); + } + else if ('arrayValue' in value) { + return canonifyArray(value.arrayValue); + } + else if ('mapValue' in value) { + return canonifyMap(value.mapValue); + } + else { + return fail(0xee4d, { value }); + } +} +function canonifyByteString(byteString) { + return normalizeByteString(byteString).toBase64(); +} +function canonifyTimestamp(timestamp) { + const normalizedTimestamp = normalizeTimestamp(timestamp); + return `time(${normalizedTimestamp.seconds},${normalizedTimestamp.nanos})`; +} +function canonifyGeoPoint(geoPoint) { + return `geo(${geoPoint.latitude},${geoPoint.longitude})`; +} +function canonifyReference(referenceValue) { + return DocumentKey.fromName(referenceValue).toString(); +} +function canonifyMap(mapValue) { + // Iteration order in JavaScript is not guaranteed. To ensure that we generate + // matching canonical IDs for identical maps, we need to sort the keys. + const sortedKeys = Object.keys(mapValue.fields || {}).sort(); + let result = '{'; + let first = true; + for (const key of sortedKeys) { + if (!first) { + result += ','; + } + else { + first = false; + } + result += `${key}:${canonifyValue(mapValue.fields[key])}`; + } + return result + '}'; +} +function canonifyArray(arrayValue) { + let result = '['; + let first = true; + for (const value of arrayValue.values || []) { + if (!first) { + result += ','; + } + else { + first = false; + } + result += canonifyValue(value); + } + return result + ']'; +} +/** + * Returns an approximate (and wildly inaccurate) in-memory size for the field + * value. + * + * The memory size takes into account only the actual user data as it resides + * in memory and ignores object overhead. + */ +function estimateByteSize(value) { + switch (typeOrder(value)) { + case 0 /* TypeOrder.NullValue */: + return 4; + case 1 /* TypeOrder.BooleanValue */: + return 4; + case 2 /* TypeOrder.NumberValue */: + return 8; + case 3 /* TypeOrder.TimestampValue */: + // Timestamps are made up of two distinct numbers (seconds + nanoseconds) + return 16; + case 4 /* TypeOrder.ServerTimestampValue */: + const previousValue = getPreviousValue(value); + return previousValue ? 16 + estimateByteSize(previousValue) : 16; + case 5 /* TypeOrder.StringValue */: + // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures: + // "JavaScript's String type is [...] a set of elements of 16-bit unsigned + // integer values" + return value.stringValue.length * 2; + case 6 /* TypeOrder.BlobValue */: + return normalizeByteString(value.bytesValue).approximateByteSize(); + case 7 /* TypeOrder.RefValue */: + return value.referenceValue.length; + case 8 /* TypeOrder.GeoPointValue */: + // GeoPoints are made up of two distinct numbers (latitude + longitude) + return 16; + case 9 /* TypeOrder.ArrayValue */: + return estimateArrayByteSize(value.arrayValue); + case 10 /* TypeOrder.VectorValue */: + case 11 /* TypeOrder.ObjectValue */: + return estimateMapByteSize(value.mapValue); + default: + throw fail(0x34ae, { value }); + } +} +function estimateMapByteSize(mapValue) { + let size = 0; + forEach(mapValue.fields, (key, val) => { + size += key.length + estimateByteSize(val); + }); + return size; +} +function estimateArrayByteSize(arrayValue) { + return (arrayValue.values || []).reduce((previousSize, value) => previousSize + estimateByteSize(value), 0); +} +/** Returns a reference value for the provided database and key. */ +function refValue(databaseId, key) { + return { + referenceValue: `projects/${databaseId.projectId}/databases/${databaseId.database}/documents/${key.path.canonicalString()}` + }; +} +/** Returns true if `value` is an IntegerValue . */ +function isInteger(value) { + return !!value && 'integerValue' in value; +} +/** Returns true if `value` is a DoubleValue. */ +function isDouble(value) { + return !!value && 'doubleValue' in value; +} +/** Returns true if `value` is either an IntegerValue or a DoubleValue. */ +function isNumber(value) { + return isInteger(value) || isDouble(value); +} +/** Returns true if `value` is an ArrayValue. */ +function isArray(value) { + return !!value && 'arrayValue' in value; +} +/** Returns true if `value` is a NullValue. */ +function isNullValue(value) { + return !!value && 'nullValue' in value; +} +/** Returns true if `value` is NaN. */ +function isNanValue(value) { + return !!value && 'doubleValue' in value && isNaN(Number(value.doubleValue)); +} +/** Returns true if `value` is a MapValue. */ +function isMapValue(value) { + return !!value && 'mapValue' in value; +} +/** Returns true if `value` is a VetorValue. */ +function isVectorValue(value) { + const type = (value?.mapValue?.fields || {})[TYPE_KEY]?.stringValue; + return type === VECTOR_VALUE_SENTINEL; +} +/** Creates a deep copy of `source`. */ +function deepClone(source) { + if (source.geoPointValue) { + return { geoPointValue: { ...source.geoPointValue } }; + } + else if (source.timestampValue && + typeof source.timestampValue === 'object') { + return { timestampValue: { ...source.timestampValue } }; + } + else if (source.mapValue) { + const target = { mapValue: { fields: {} } }; + forEach(source.mapValue.fields, (key, val) => (target.mapValue.fields[key] = deepClone(val))); + return target; + } + else if (source.arrayValue) { + const target = { arrayValue: { values: [] } }; + for (let i = 0; i < (source.arrayValue.values || []).length; ++i) { + target.arrayValue.values[i] = deepClone(source.arrayValue.values[i]); + } + return target; + } + else { + return { ...source }; + } +} +/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ +function isMaxValue(value) { + return ((((value.mapValue || {}).fields || {})['__type__'] || {}).stringValue === + MAX_VALUE_TYPE); +} +const MIN_VECTOR_VALUE = { + mapValue: { + fields: { + [TYPE_KEY]: { stringValue: VECTOR_VALUE_SENTINEL }, + [VECTOR_MAP_VECTORS_KEY]: { + arrayValue: {} + } + } + } +}; +/** Returns the lowest value for the given value type (inclusive). */ +function valuesGetLowerBound(value) { + if ('nullValue' in value) { + return MIN_VALUE; + } + else if ('booleanValue' in value) { + return { booleanValue: false }; + } + else if ('integerValue' in value || 'doubleValue' in value) { + return { doubleValue: NaN }; + } + else if ('timestampValue' in value) { + return { timestampValue: { seconds: Number.MIN_SAFE_INTEGER } }; + } + else if ('stringValue' in value) { + return { stringValue: '' }; + } + else if ('bytesValue' in value) { + return { bytesValue: '' }; + } + else if ('referenceValue' in value) { + return refValue(DatabaseId.empty(), DocumentKey.empty()); + } + else if ('geoPointValue' in value) { + return { geoPointValue: { latitude: -90, longitude: -180 } }; + } + else if ('arrayValue' in value) { + return { arrayValue: {} }; + } + else if ('mapValue' in value) { + if (isVectorValue(value)) { + return MIN_VECTOR_VALUE; + } + return { mapValue: {} }; + } + else { + return fail(0x8c66, { value }); + } +} +/** Returns the largest value for the given value type (exclusive). */ +function valuesGetUpperBound(value) { + if ('nullValue' in value) { + return { booleanValue: false }; + } + else if ('booleanValue' in value) { + return { doubleValue: NaN }; + } + else if ('integerValue' in value || 'doubleValue' in value) { + return { timestampValue: { seconds: Number.MIN_SAFE_INTEGER } }; + } + else if ('timestampValue' in value) { + return { stringValue: '' }; + } + else if ('stringValue' in value) { + return { bytesValue: '' }; + } + else if ('bytesValue' in value) { + return refValue(DatabaseId.empty(), DocumentKey.empty()); + } + else if ('referenceValue' in value) { + return { geoPointValue: { latitude: -90, longitude: -180 } }; + } + else if ('geoPointValue' in value) { + return { arrayValue: {} }; + } + else if ('arrayValue' in value) { + return MIN_VECTOR_VALUE; + } + else if ('mapValue' in value) { + if (isVectorValue(value)) { + return { mapValue: {} }; + } + return MAX_VALUE; + } + else { + return fail(0xf207, { value }); + } +} +function lowerBoundCompare(left, right) { + const cmp = valueCompare(left.value, right.value); + if (cmp !== 0) { + return cmp; + } + if (left.inclusive && !right.inclusive) { + return -1; + } + else if (!left.inclusive && right.inclusive) { + return 1; + } + return 0; +} +function upperBoundCompare(left, right) { + const cmp = valueCompare(left.value, right.value); + if (cmp !== 0) { + return cmp; + } + if (left.inclusive && !right.inclusive) { + return 1; + } + else if (!left.inclusive && right.inclusive) { + return -1; + } + return 0; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An ObjectValue represents a MapValue in the Firestore Proto and offers the + * ability to add and remove fields (via the ObjectValueBuilder). + */ +class ObjectValue { + constructor(value) { + this.value = value; + } + static empty() { + return new ObjectValue({ mapValue: {} }); + } + /** + * Returns the value at the given path or null. + * + * @param path - the path to search + * @returns The value at the path or null if the path is not set. + */ + field(path) { + if (path.isEmpty()) { + return this.value; + } + else { + let currentLevel = this.value; + for (let i = 0; i < path.length - 1; ++i) { + currentLevel = (currentLevel.mapValue.fields || {})[path.get(i)]; + if (!isMapValue(currentLevel)) { + return null; + } + } + currentLevel = (currentLevel.mapValue.fields || {})[path.lastSegment()]; + return currentLevel || null; + } + } + /** + * Sets the field to the provided value. + * + * @param path - The field path to set. + * @param value - The value to set. + */ + set(path, value) { + const fieldsMap = this.getFieldsMap(path.popLast()); + fieldsMap[path.lastSegment()] = deepClone(value); + } + /** + * Sets the provided fields to the provided values. + * + * @param data - A map of fields to values (or null for deletes). + */ + setAll(data) { + let parent = FieldPath$1.emptyPath(); + let upserts = {}; + let deletes = []; + data.forEach((value, path) => { + if (!parent.isImmediateParentOf(path)) { + // Insert the accumulated changes at this parent location + const fieldsMap = this.getFieldsMap(parent); + this.applyChanges(fieldsMap, upserts, deletes); + upserts = {}; + deletes = []; + parent = path.popLast(); + } + if (value) { + upserts[path.lastSegment()] = deepClone(value); + } + else { + deletes.push(path.lastSegment()); + } + }); + const fieldsMap = this.getFieldsMap(parent); + this.applyChanges(fieldsMap, upserts, deletes); + } + /** + * Removes the field at the specified path. If there is no field at the + * specified path, nothing is changed. + * + * @param path - The field path to remove. + */ + delete(path) { + const nestedValue = this.field(path.popLast()); + if (isMapValue(nestedValue) && nestedValue.mapValue.fields) { + delete nestedValue.mapValue.fields[path.lastSegment()]; + } + } + isEqual(other) { + return valueEquals(this.value, other.value); + } + /** + * Returns the map that contains the leaf element of `path`. If the parent + * entry does not yet exist, or if it is not a map, a new map will be created. + */ + getFieldsMap(path) { + let current = this.value; + if (!current.mapValue.fields) { + current.mapValue = { fields: {} }; + } + for (let i = 0; i < path.length; ++i) { + let next = current.mapValue.fields[path.get(i)]; + if (!isMapValue(next) || !next.mapValue.fields) { + next = { mapValue: { fields: {} } }; + current.mapValue.fields[path.get(i)] = next; + } + current = next; + } + return current.mapValue.fields; + } + /** + * Modifies `fieldsMap` by adding, replacing or deleting the specified + * entries. + */ + applyChanges(fieldsMap, inserts, deletes) { + forEach(inserts, (key, val) => (fieldsMap[key] = val)); + for (const field of deletes) { + delete fieldsMap[field]; + } + } + clone() { + return new ObjectValue(deepClone(this.value)); + } +} +/** + * Returns a FieldMask built from all fields in a MapValue. + */ +function extractFieldMask(value) { + const fields = []; + forEach(value.fields, (key, value) => { + const currentPath = new FieldPath$1([key]); + if (isMapValue(value)) { + const nestedMask = extractFieldMask(value.mapValue); + const nestedFields = nestedMask.fields; + if (nestedFields.length === 0) { + // Preserve the empty map by adding it to the FieldMask. + fields.push(currentPath); + } + else { + // For nested and non-empty ObjectValues, add the FieldPath of the + // leaf nodes. + for (const nestedPath of nestedFields) { + fields.push(currentPath.child(nestedPath)); + } + } + } + else { + // For nested and non-empty ObjectValues, add the FieldPath of the leaf + // nodes. + fields.push(currentPath); + } + }); + return new FieldMask(fields); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a document in Firestore with a key, version, data and whether it + * has local mutations applied to it. + * + * Documents can transition between states via `convertToFoundDocument()`, + * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does + * not transition to one of these states even after all mutations have been + * applied, `isValidDocument()` returns false and the document should be removed + * from all views. + */ +class MutableDocument { + constructor(key, documentType, version, readTime, createTime, data, documentState) { + this.key = key; + this.documentType = documentType; + this.version = version; + this.readTime = readTime; + this.createTime = createTime; + this.data = data; + this.documentState = documentState; + } + /** + * Creates a document with no known version or data, but which can serve as + * base document for mutations. + */ + static newInvalidDocument(documentKey) { + return new MutableDocument(documentKey, 0 /* DocumentType.INVALID */, + /* version */ SnapshotVersion.min(), + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist with the given data at the + * given version. + */ + static newFoundDocument(documentKey, version, createTime, value) { + return new MutableDocument(documentKey, 1 /* DocumentType.FOUND_DOCUMENT */, + /* version */ version, + /* readTime */ SnapshotVersion.min(), + /* createTime */ createTime, value, 0 /* DocumentState.SYNCED */); + } + /** Creates a new document that is known to not exist at the given version. */ + static newNoDocument(documentKey, version) { + return new MutableDocument(documentKey, 2 /* DocumentType.NO_DOCUMENT */, + /* version */ version, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist at the given version but + * whose data is not known (e.g. a document that was updated without a known + * base document). + */ + static newUnknownDocument(documentKey, version) { + return new MutableDocument(documentKey, 3 /* DocumentType.UNKNOWN_DOCUMENT */, + /* version */ version, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */); + } + /** + * Changes the document type to indicate that it exists and that its version + * and data are known. + */ + convertToFoundDocument(version, value) { + // If a document is switching state from being an invalid or deleted + // document to a valid (FOUND_DOCUMENT) document, either due to receiving an + // update from Watch or due to applying a local set mutation on top + // of a deleted document, our best guess about its createTime would be the + // version at which the document transitioned to a FOUND_DOCUMENT. + if (this.createTime.isEqual(SnapshotVersion.min()) && + (this.documentType === 2 /* DocumentType.NO_DOCUMENT */ || + this.documentType === 0 /* DocumentType.INVALID */)) { + this.createTime = version; + } + this.version = version; + this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */; + this.data = value; + this.documentState = 0 /* DocumentState.SYNCED */; + return this; + } + /** + * Changes the document type to indicate that it doesn't exist at the given + * version. + */ + convertToNoDocument(version) { + this.version = version; + this.documentType = 2 /* DocumentType.NO_DOCUMENT */; + this.data = ObjectValue.empty(); + this.documentState = 0 /* DocumentState.SYNCED */; + return this; + } + /** + * Changes the document type to indicate that it exists at a given version but + * that its data is not known (e.g. a document that was updated without a known + * base document). + */ + convertToUnknownDocument(version) { + this.version = version; + this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */; + this.data = ObjectValue.empty(); + this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */; + return this; + } + setHasCommittedMutations() { + this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */; + return this; + } + setHasLocalMutations() { + this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */; + this.version = SnapshotVersion.min(); + return this; + } + setReadTime(readTime) { + this.readTime = readTime; + return this; + } + get hasLocalMutations() { + return this.documentState === 1 /* DocumentState.HAS_LOCAL_MUTATIONS */; + } + get hasCommittedMutations() { + return this.documentState === 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */; + } + get hasPendingWrites() { + return this.hasLocalMutations || this.hasCommittedMutations; + } + isValidDocument() { + return this.documentType !== 0 /* DocumentType.INVALID */; + } + isFoundDocument() { + return this.documentType === 1 /* DocumentType.FOUND_DOCUMENT */; + } + isNoDocument() { + return this.documentType === 2 /* DocumentType.NO_DOCUMENT */; + } + isUnknownDocument() { + return this.documentType === 3 /* DocumentType.UNKNOWN_DOCUMENT */; + } + isEqual(other) { + return (other instanceof MutableDocument && + this.key.isEqual(other.key) && + this.version.isEqual(other.version) && + this.documentType === other.documentType && + this.documentState === other.documentState && + this.data.isEqual(other.data)); + } + mutableCopy() { + return new MutableDocument(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState); + } + toString() { + return (`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, ` + + `{createTime: ${this.createTime}}), ` + + `{documentType: ${this.documentType}}), ` + + `{documentState: ${this.documentState}})`); + } +} +/** + * Compares the value for field `field` in the provided documents. Throws if + * the field does not exist in both documents. + */ +function compareDocumentsByField(field, d1, d2) { + const v1 = d1.data.field(field); + const v2 = d2.data.field(field); + if (v1 !== null && v2 !== null) { + return valueCompare(v1, v2); + } + else { + return fail(0xa786); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a bound of a query. + * + * The bound is specified with the given components representing a position and + * whether it's just before or just after the position (relative to whatever the + * query order is). + * + * The position represents a logical index position for a query. It's a prefix + * of values for the (potentially implicit) order by clauses of a query. + * + * Bound provides a function to determine whether a document comes before or + * after a bound. This is influenced by whether the position is just before or + * just after the provided values. + */ +class Bound { + constructor(position, inclusive) { + this.position = position; + this.inclusive = inclusive; + } +} +function boundCompareToDocument(bound, orderBy, doc) { + let comparison = 0; + for (let i = 0; i < bound.position.length; i++) { + const orderByComponent = orderBy[i]; + const component = bound.position[i]; + if (orderByComponent.field.isKeyField()) { + comparison = DocumentKey.comparator(DocumentKey.fromName(component.referenceValue), doc.key); + } + else { + const docValue = doc.data.field(orderByComponent.field); + comparison = valueCompare(component, docValue); + } + if (orderByComponent.dir === "desc" /* Direction.DESCENDING */) { + comparison = comparison * -1; + } + if (comparison !== 0) { + break; + } + } + return comparison; +} +/** + * Returns true if a document sorts after a bound using the provided sort + * order. + */ +function boundSortsAfterDocument(bound, orderBy, doc) { + const comparison = boundCompareToDocument(bound, orderBy, doc); + return bound.inclusive ? comparison >= 0 : comparison > 0; +} +/** + * Returns true if a document sorts before a bound using the provided sort + * order. + */ +function boundSortsBeforeDocument(bound, orderBy, doc) { + const comparison = boundCompareToDocument(bound, orderBy, doc); + return bound.inclusive ? comparison <= 0 : comparison < 0; +} +function boundEquals(left, right) { + if (left === null) { + return right === null; + } + else if (right === null) { + return false; + } + if (left.inclusive !== right.inclusive || + left.position.length !== right.position.length) { + return false; + } + for (let i = 0; i < left.position.length; i++) { + const leftPosition = left.position[i]; + const rightPosition = right.position[i]; + if (!valueEquals(leftPosition, rightPosition)) { + return false; + } + } + return true; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An ordering on a field, in some Direction. Direction defaults to ASCENDING. + */ +class OrderBy { + constructor(field, dir = "asc" /* Direction.ASCENDING */) { + this.field = field; + this.dir = dir; + } +} +function canonifyOrderBy(orderBy) { + // TODO(b/29183165): Make this collision robust. + return orderBy.field.canonicalString() + orderBy.dir; +} +function stringifyOrderBy(orderBy) { + return `${orderBy.field.canonicalString()} (${orderBy.dir})`; +} +function orderByEquals(left, right) { + return left.dir === right.dir && left.field.isEqual(right.field); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Filter { +} +class FieldFilter extends Filter { + constructor(field, op, value) { + super(); + this.field = field; + this.op = op; + this.value = value; + } + /** + * Creates a filter based on the provided arguments. + */ + static create(field, op, value) { + if (field.isKeyField()) { + if (op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */) { + return this.createKeyFieldInFilter(field, op, value); + } + else { + return new KeyFieldFilter(field, op, value); + } + } + else if (op === "array-contains" /* Operator.ARRAY_CONTAINS */) { + return new ArrayContainsFilter(field, value); + } + else if (op === "in" /* Operator.IN */) { + return new InFilter(field, value); + } + else if (op === "not-in" /* Operator.NOT_IN */) { + return new NotInFilter(field, value); + } + else if (op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) { + return new ArrayContainsAnyFilter(field, value); + } + else { + return new FieldFilter(field, op, value); + } + } + static createKeyFieldInFilter(field, op, value) { + return op === "in" /* Operator.IN */ + ? new KeyFieldInFilter(field, value) + : new KeyFieldNotInFilter(field, value); + } + matches(doc) { + const other = doc.data.field(this.field); + // Types do not have to match in NOT_EQUAL filters. + if (this.op === "!=" /* Operator.NOT_EQUAL */) { + return (other !== null && + other.nullValue === undefined && + this.matchesComparison(valueCompare(other, this.value))); + } + // Only compare types with matching backend order (such as double and int). + return (other !== null && + typeOrder(this.value) === typeOrder(other) && + this.matchesComparison(valueCompare(other, this.value))); + } + matchesComparison(comparison) { + switch (this.op) { + case "<" /* Operator.LESS_THAN */: + return comparison < 0; + case "<=" /* Operator.LESS_THAN_OR_EQUAL */: + return comparison <= 0; + case "==" /* Operator.EQUAL */: + return comparison === 0; + case "!=" /* Operator.NOT_EQUAL */: + return comparison !== 0; + case ">" /* Operator.GREATER_THAN */: + return comparison > 0; + case ">=" /* Operator.GREATER_THAN_OR_EQUAL */: + return comparison >= 0; + default: + return fail(0xb8a2, { + operator: this.op + }); + } + } + isInequality() { + return ([ + "<" /* Operator.LESS_THAN */, + "<=" /* Operator.LESS_THAN_OR_EQUAL */, + ">" /* Operator.GREATER_THAN */, + ">=" /* Operator.GREATER_THAN_OR_EQUAL */, + "!=" /* Operator.NOT_EQUAL */, + "not-in" /* Operator.NOT_IN */ + ].indexOf(this.op) >= 0); + } + getFlattenedFilters() { + return [this]; + } + getFilters() { + return [this]; + } +} +class CompositeFilter extends Filter { + constructor(filters, op) { + super(); + this.filters = filters; + this.op = op; + this.memoizedFlattenedFilters = null; + } + /** + * Creates a filter based on the provided arguments. + */ + static create(filters, op) { + return new CompositeFilter(filters, op); + } + matches(doc) { + if (compositeFilterIsConjunction(this)) { + // For conjunctions, all filters must match, so return false if any filter doesn't match. + return this.filters.find(filter => !filter.matches(doc)) === undefined; + } + else { + // For disjunctions, at least one filter should match. + return this.filters.find(filter => filter.matches(doc)) !== undefined; + } + } + getFlattenedFilters() { + if (this.memoizedFlattenedFilters !== null) { + return this.memoizedFlattenedFilters; + } + this.memoizedFlattenedFilters = this.filters.reduce((result, subfilter) => { + return result.concat(subfilter.getFlattenedFilters()); + }, []); + return this.memoizedFlattenedFilters; + } + // Returns a mutable copy of `this.filters` + getFilters() { + return Object.assign([], this.filters); + } +} +function compositeFilterIsConjunction(compositeFilter) { + return compositeFilter.op === "and" /* CompositeOperator.AND */; +} +function compositeFilterIsDisjunction(compositeFilter) { + return compositeFilter.op === "or" /* CompositeOperator.OR */; +} +/** + * Returns true if this filter is a conjunction of field filters only. Returns false otherwise. + */ +function compositeFilterIsFlatConjunction(compositeFilter) { + return (compositeFilterIsFlat(compositeFilter) && + compositeFilterIsConjunction(compositeFilter)); +} +/** + * Returns true if this filter does not contain any composite filters. Returns false otherwise. + */ +function compositeFilterIsFlat(compositeFilter) { + for (const filter of compositeFilter.filters) { + if (filter instanceof CompositeFilter) { + return false; + } + } + return true; +} +function canonifyFilter(filter) { + if (filter instanceof FieldFilter) { + // TODO(b/29183165): Technically, this won't be unique if two values have + // the same description, such as the int 3 and the string "3". So we should + // add the types in here somehow, too. + return (filter.field.canonicalString() + + filter.op.toString() + + canonicalId(filter.value)); + } + else if (compositeFilterIsFlatConjunction(filter)) { + // Older SDK versions use an implicit AND operation between their filters. + // In the new SDK versions, the developer may use an explicit AND filter. + // To stay consistent with the old usages, we add a special case to ensure + // the canonical ID for these two are the same. For example: + // `col.whereEquals("a", 1).whereEquals("b", 2)` should have the same + // canonical ID as `col.where(and(equals("a",1), equals("b",2)))`. + return filter.filters.map(filter => canonifyFilter(filter)).join(','); + } + else { + // filter instanceof CompositeFilter + const canonicalIdsString = filter.filters + .map(filter => canonifyFilter(filter)) + .join(','); + return `${filter.op}(${canonicalIdsString})`; + } +} +function filterEquals(f1, f2) { + if (f1 instanceof FieldFilter) { + return fieldFilterEquals(f1, f2); + } + else if (f1 instanceof CompositeFilter) { + return compositeFilterEquals(f1, f2); + } + else { + fail(0x4bef); + } +} +function fieldFilterEquals(f1, f2) { + return (f2 instanceof FieldFilter && + f1.op === f2.op && + f1.field.isEqual(f2.field) && + valueEquals(f1.value, f2.value)); +} +function compositeFilterEquals(f1, f2) { + if (f2 instanceof CompositeFilter && + f1.op === f2.op && + f1.filters.length === f2.filters.length) { + const subFiltersMatch = f1.filters.reduce((result, f1Filter, index) => result && filterEquals(f1Filter, f2.filters[index]), true); + return subFiltersMatch; + } + return false; +} +/** + * Returns a new composite filter that contains all filter from + * `compositeFilter` plus all the given filters in `otherFilters`. + */ +function compositeFilterWithAddedFilters(compositeFilter, otherFilters) { + const mergedFilters = compositeFilter.filters.concat(otherFilters); + return CompositeFilter.create(mergedFilters, compositeFilter.op); +} +/** Returns a debug description for `filter`. */ +function stringifyFilter(filter) { + if (filter instanceof FieldFilter) { + return stringifyFieldFilter(filter); + } + else if (filter instanceof CompositeFilter) { + return stringifyCompositeFilter(filter); + } + else { + return 'Filter'; + } +} +function stringifyCompositeFilter(filter) { + return (filter.op.toString() + + ` {` + + filter.getFilters().map(stringifyFilter).join(' ,') + + '}'); +} +function stringifyFieldFilter(filter) { + return `${filter.field.canonicalString()} ${filter.op} ${canonicalId(filter.value)}`; +} +/** Filter that matches on key fields (i.e. '__name__'). */ +class KeyFieldFilter extends FieldFilter { + constructor(field, op, value) { + super(field, op, value); + this.key = DocumentKey.fromName(value.referenceValue); + } + matches(doc) { + const comparison = DocumentKey.comparator(doc.key, this.key); + return this.matchesComparison(comparison); + } +} +/** Filter that matches on key fields within an array. */ +class KeyFieldInFilter extends FieldFilter { + constructor(field, value) { + super(field, "in" /* Operator.IN */, value); + this.keys = extractDocumentKeysFromArrayValue("in" /* Operator.IN */, value); + } + matches(doc) { + return this.keys.some(key => key.isEqual(doc.key)); + } +} +/** Filter that matches on key fields not present within an array. */ +class KeyFieldNotInFilter extends FieldFilter { + constructor(field, value) { + super(field, "not-in" /* Operator.NOT_IN */, value); + this.keys = extractDocumentKeysFromArrayValue("not-in" /* Operator.NOT_IN */, value); + } + matches(doc) { + return !this.keys.some(key => key.isEqual(doc.key)); + } +} +function extractDocumentKeysFromArrayValue(op, value) { + return (value.arrayValue?.values || []).map(v => { + return DocumentKey.fromName(v.referenceValue); + }); +} +/** A Filter that implements the array-contains operator. */ +class ArrayContainsFilter extends FieldFilter { + constructor(field, value) { + super(field, "array-contains" /* Operator.ARRAY_CONTAINS */, value); + } + matches(doc) { + const other = doc.data.field(this.field); + return isArray(other) && arrayValueContains(other.arrayValue, this.value); + } +} +/** A Filter that implements the IN operator. */ +class InFilter extends FieldFilter { + constructor(field, value) { + super(field, "in" /* Operator.IN */, value); + } + matches(doc) { + const other = doc.data.field(this.field); + return other !== null && arrayValueContains(this.value.arrayValue, other); + } +} +/** A Filter that implements the not-in operator. */ +class NotInFilter extends FieldFilter { + constructor(field, value) { + super(field, "not-in" /* Operator.NOT_IN */, value); + } + matches(doc) { + if (arrayValueContains(this.value.arrayValue, { nullValue: 'NULL_VALUE' })) { + return false; + } + const other = doc.data.field(this.field); + return (other !== null && + other.nullValue === undefined && + !arrayValueContains(this.value.arrayValue, other)); + } +} +/** A Filter that implements the array-contains-any operator. */ +class ArrayContainsAnyFilter extends FieldFilter { + constructor(field, value) { + super(field, "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */, value); + } + matches(doc) { + const other = doc.data.field(this.field); + if (!isArray(other) || !other.arrayValue.values) { + return false; + } + return other.arrayValue.values.some(val => arrayValueContains(this.value.arrayValue, val)); + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Visible for testing +class TargetImpl { + constructor(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) { + this.path = path; + this.collectionGroup = collectionGroup; + this.orderBy = orderBy; + this.filters = filters; + this.limit = limit; + this.startAt = startAt; + this.endAt = endAt; + this.memoizedCanonicalId = null; + } +} +/** + * Initializes a Target with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + * + * NOTE: you should always construct `Target` from `Query.toTarget` instead of + * using this factory method, because `Query` provides an implicit `orderBy` + * property. + */ +function newTarget(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) { + return new TargetImpl(path, collectionGroup, orderBy, filters, limit, startAt, endAt); +} +function canonifyTarget(target) { + const targetImpl = debugCast(target); + if (targetImpl.memoizedCanonicalId === null) { + let str = targetImpl.path.canonicalString(); + if (targetImpl.collectionGroup !== null) { + str += '|cg:' + targetImpl.collectionGroup; + } + str += '|f:'; + str += targetImpl.filters.map(f => canonifyFilter(f)).join(','); + str += '|ob:'; + str += targetImpl.orderBy.map(o => canonifyOrderBy(o)).join(','); + if (!isNullOrUndefined(targetImpl.limit)) { + str += '|l:'; + str += targetImpl.limit; + } + if (targetImpl.startAt) { + str += '|lb:'; + str += targetImpl.startAt.inclusive ? 'b:' : 'a:'; + str += targetImpl.startAt.position.map(p => canonicalId(p)).join(','); + } + if (targetImpl.endAt) { + str += '|ub:'; + str += targetImpl.endAt.inclusive ? 'a:' : 'b:'; + str += targetImpl.endAt.position.map(p => canonicalId(p)).join(','); + } + targetImpl.memoizedCanonicalId = str; + } + return targetImpl.memoizedCanonicalId; +} +function stringifyTarget(target) { + let str = target.path.canonicalString(); + if (target.collectionGroup !== null) { + str += ' collectionGroup=' + target.collectionGroup; + } + if (target.filters.length > 0) { + str += `, filters: [${target.filters + .map(f => stringifyFilter(f)) + .join(', ')}]`; + } + if (!isNullOrUndefined(target.limit)) { + str += ', limit: ' + target.limit; + } + if (target.orderBy.length > 0) { + str += `, orderBy: [${target.orderBy + .map(o => stringifyOrderBy(o)) + .join(', ')}]`; + } + if (target.startAt) { + str += ', startAt: '; + str += target.startAt.inclusive ? 'b:' : 'a:'; + str += target.startAt.position.map(p => canonicalId(p)).join(','); + } + if (target.endAt) { + str += ', endAt: '; + str += target.endAt.inclusive ? 'a:' : 'b:'; + str += target.endAt.position.map(p => canonicalId(p)).join(','); + } + return `Target(${str})`; +} +function targetEquals(left, right) { + if (left.limit !== right.limit) { + return false; + } + if (left.orderBy.length !== right.orderBy.length) { + return false; + } + for (let i = 0; i < left.orderBy.length; i++) { + if (!orderByEquals(left.orderBy[i], right.orderBy[i])) { + return false; + } + } + if (left.filters.length !== right.filters.length) { + return false; + } + for (let i = 0; i < left.filters.length; i++) { + if (!filterEquals(left.filters[i], right.filters[i])) { + return false; + } + } + if (left.collectionGroup !== right.collectionGroup) { + return false; + } + if (!left.path.isEqual(right.path)) { + return false; + } + if (!boundEquals(left.startAt, right.startAt)) { + return false; + } + return boundEquals(left.endAt, right.endAt); +} +function targetIsDocumentTarget(target) { + return (DocumentKey.isDocumentKey(target.path) && + target.collectionGroup === null && + target.filters.length === 0); +} +/** Returns the field filters that target the given field path. */ +function targetGetFieldFiltersForPath(target, path) { + return target.filters.filter(f => f instanceof FieldFilter && f.field.isEqual(path)); +} +/** + * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY + * filters. Returns `null` if there are no such filters. + */ +function targetGetArrayValues(target, fieldIndex) { + const segment = fieldIndexGetArraySegment(fieldIndex); + if (segment === undefined) { + return null; + } + for (const fieldFilter of targetGetFieldFiltersForPath(target, segment.fieldPath)) { + switch (fieldFilter.op) { + case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */: + return fieldFilter.value.arrayValue.values || []; + case "array-contains" /* Operator.ARRAY_CONTAINS */: + return [fieldFilter.value]; + // Remaining filters are not array filters. + } + } + return null; +} +/** + * Returns the list of values that are used in != or NOT_IN filters. Returns + * `null` if there are no such filters. + */ +function targetGetNotInValues(target, fieldIndex) { + const values = new Map(); + for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) { + for (const fieldFilter of targetGetFieldFiltersForPath(target, segment.fieldPath)) { + switch (fieldFilter.op) { + case "==" /* Operator.EQUAL */: + case "in" /* Operator.IN */: + // Encode equality prefix, which is encoded in the index value before + // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to + // `value != 'ab'`). + values.set(segment.fieldPath.canonicalString(), fieldFilter.value); + break; + case "not-in" /* Operator.NOT_IN */: + case "!=" /* Operator.NOT_EQUAL */: + // NotIn/NotEqual is always a suffix. There cannot be any remaining + // segments and hence we can return early here. + values.set(segment.fieldPath.canonicalString(), fieldFilter.value); + return Array.from(values.values()); + // Remaining filters cannot be used as notIn bounds. + } + } + } + return null; +} +/** + * Returns a lower bound of field values that can be used as a starting point to + * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound + * exists. + */ +function targetGetLowerBound(target, fieldIndex) { + const values = []; + let inclusive = true; + // For each segment, retrieve a lower bound if there is a suitable filter or + // startAt. + for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) { + const segmentBound = segment.kind === 0 /* IndexKind.ASCENDING */ + ? targetGetAscendingBound(target, segment.fieldPath, target.startAt) + : targetGetDescendingBound(target, segment.fieldPath, target.startAt); + values.push(segmentBound.value); + inclusive && (inclusive = segmentBound.inclusive); + } + return new Bound(values, inclusive); +} +/** + * Returns an upper bound of field values that can be used as an ending point + * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no + * upper bound exists. + */ +function targetGetUpperBound(target, fieldIndex) { + const values = []; + let inclusive = true; + // For each segment, retrieve an upper bound if there is a suitable filter or + // endAt. + for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) { + const segmentBound = segment.kind === 0 /* IndexKind.ASCENDING */ + ? targetGetDescendingBound(target, segment.fieldPath, target.endAt) + : targetGetAscendingBound(target, segment.fieldPath, target.endAt); + values.push(segmentBound.value); + inclusive && (inclusive = segmentBound.inclusive); + } + return new Bound(values, inclusive); +} +/** + * Returns the value to use as the lower bound for ascending index segment at + * the provided `fieldPath` (or the upper bound for an descending segment). + */ +function targetGetAscendingBound(target, fieldPath, bound) { + let value = MIN_VALUE; + let inclusive = true; + // Process all filters to find a value for the current field segment + for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) { + let filterValue = MIN_VALUE; + let filterInclusive = true; + switch (fieldFilter.op) { + case "<" /* Operator.LESS_THAN */: + case "<=" /* Operator.LESS_THAN_OR_EQUAL */: + filterValue = valuesGetLowerBound(fieldFilter.value); + break; + case "==" /* Operator.EQUAL */: + case "in" /* Operator.IN */: + case ">=" /* Operator.GREATER_THAN_OR_EQUAL */: + filterValue = fieldFilter.value; + break; + case ">" /* Operator.GREATER_THAN */: + filterValue = fieldFilter.value; + filterInclusive = false; + break; + case "!=" /* Operator.NOT_EQUAL */: + case "not-in" /* Operator.NOT_IN */: + filterValue = MIN_VALUE; + break; + // Remaining filters cannot be used as lower bounds. + } + if (lowerBoundCompare({ value, inclusive }, { value: filterValue, inclusive: filterInclusive }) < 0) { + value = filterValue; + inclusive = filterInclusive; + } + } + // If there is an additional bound, compare the values against the existing + // range to see if we can narrow the scope. + if (bound !== null) { + for (let i = 0; i < target.orderBy.length; ++i) { + const orderBy = target.orderBy[i]; + if (orderBy.field.isEqual(fieldPath)) { + const cursorValue = bound.position[i]; + if (lowerBoundCompare({ value, inclusive }, { value: cursorValue, inclusive: bound.inclusive }) < 0) { + value = cursorValue; + inclusive = bound.inclusive; + } + break; + } + } + } + return { value, inclusive }; +} +/** + * Returns the value to use as the upper bound for ascending index segment at + * the provided `fieldPath` (or the lower bound for a descending segment). + */ +function targetGetDescendingBound(target, fieldPath, bound) { + let value = MAX_VALUE; + let inclusive = true; + // Process all filters to find a value for the current field segment + for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) { + let filterValue = MAX_VALUE; + let filterInclusive = true; + switch (fieldFilter.op) { + case ">=" /* Operator.GREATER_THAN_OR_EQUAL */: + case ">" /* Operator.GREATER_THAN */: + filterValue = valuesGetUpperBound(fieldFilter.value); + filterInclusive = false; + break; + case "==" /* Operator.EQUAL */: + case "in" /* Operator.IN */: + case "<=" /* Operator.LESS_THAN_OR_EQUAL */: + filterValue = fieldFilter.value; + break; + case "<" /* Operator.LESS_THAN */: + filterValue = fieldFilter.value; + filterInclusive = false; + break; + case "!=" /* Operator.NOT_EQUAL */: + case "not-in" /* Operator.NOT_IN */: + filterValue = MAX_VALUE; + break; + // Remaining filters cannot be used as upper bounds. + } + if (upperBoundCompare({ value, inclusive }, { value: filterValue, inclusive: filterInclusive }) > 0) { + value = filterValue; + inclusive = filterInclusive; + } + } + // If there is an additional bound, compare the values against the existing + // range to see if we can narrow the scope. + if (bound !== null) { + for (let i = 0; i < target.orderBy.length; ++i) { + const orderBy = target.orderBy[i]; + if (orderBy.field.isEqual(fieldPath)) { + const cursorValue = bound.position[i]; + if (upperBoundCompare({ value, inclusive }, { value: cursorValue, inclusive: bound.inclusive }) > 0) { + value = cursorValue; + inclusive = bound.inclusive; + } + break; + } + } + } + return { value, inclusive }; +} +/** Returns the number of segments of a perfect index for this target. */ +function targetGetSegmentCount(target) { + let fields = new SortedSet(FieldPath$1.comparator); + let hasArraySegment = false; + for (const filter of target.filters) { + for (const subFilter of filter.getFlattenedFilters()) { + // __name__ is not an explicit segment of any index, so we don't need to + // count it. + if (subFilter.field.isKeyField()) { + continue; + } + // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately. + // For instance, it is possible to have an index for "a ARRAY a ASC". Even + // though these are on the same field, they should be counted as two + // separate segments in an index. + if (subFilter.op === "array-contains" /* Operator.ARRAY_CONTAINS */ || + subFilter.op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) { + hasArraySegment = true; + } + else { + fields = fields.add(subFilter.field); + } + } + } + for (const orderBy of target.orderBy) { + // __name__ is not an explicit segment of any index, so we don't need to + // count it. + if (!orderBy.field.isKeyField()) { + fields = fields.add(orderBy.field); + } + } + return fields.size + (hasArraySegment ? 1 : 0); +} +function targetHasLimit(target) { + return target.limit !== null; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Query encapsulates all the query attributes we support in the SDK. It can + * be run against the LocalStore, as well as be converted to a `Target` to + * query the RemoteStore results. + * + * Visible for testing. + */ +class QueryImpl { + /** + * Initializes a Query with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + */ + constructor(path, collectionGroup = null, explicitOrderBy = [], filters = [], limit = null, limitType = "F" /* LimitType.First */, startAt = null, endAt = null) { + this.path = path; + this.collectionGroup = collectionGroup; + this.explicitOrderBy = explicitOrderBy; + this.filters = filters; + this.limit = limit; + this.limitType = limitType; + this.startAt = startAt; + this.endAt = endAt; + this.memoizedNormalizedOrderBy = null; + // The corresponding `Target` of this `Query` instance, for use with + // non-aggregate queries. + this.memoizedTarget = null; + // The corresponding `Target` of this `Query` instance, for use with + // aggregate queries. Unlike targets for non-aggregate queries, + // aggregate query targets do not contain normalized order-bys, they only + // contain explicit order-bys. + this.memoizedAggregateTarget = null; + if (this.startAt) ; + if (this.endAt) ; + } +} +/** Creates a new Query instance with the options provided. */ +function newQuery(path, collectionGroup, explicitOrderBy, filters, limit, limitType, startAt, endAt) { + return new QueryImpl(path, collectionGroup, explicitOrderBy, filters, limit, limitType, startAt, endAt); +} +/** Creates a new Query for a query that matches all documents at `path` */ +function newQueryForPath(path) { + return new QueryImpl(path); +} +/** + * Helper to convert a collection group query into a collection query at a + * specific path. This is used when executing collection group queries, since + * we have to split the query into a set of collection queries at multiple + * paths. + */ +function asCollectionQueryAtPath(query, path) { + return new QueryImpl(path, + /*collectionGroup=*/ null, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, query.startAt, query.endAt); +} +/** + * Returns true if this query does not specify any query constraints that + * could remove results. + */ +function queryMatchesAllDocuments(query) { + return (query.filters.length === 0 && + query.limit === null && + query.startAt == null && + query.endAt == null && + (query.explicitOrderBy.length === 0 || + (query.explicitOrderBy.length === 1 && + query.explicitOrderBy[0].field.isKeyField()))); +} +// Returns the sorted set of inequality filter fields used in this query. +function getInequalityFilterFields(query) { + let result = new SortedSet(FieldPath$1.comparator); + query.filters.forEach((filter) => { + const subFilters = filter.getFlattenedFilters(); + subFilters.forEach((filter) => { + if (filter.isInequality()) { + result = result.add(filter.field); + } + }); + }); + return result; +} +/** + * Creates a new Query for a collection group query that matches all documents + * within the provided collection group. + */ +function newQueryForCollectionGroup(collectionId) { + return new QueryImpl(ResourcePath.emptyPath(), collectionId); +} +/** + * Returns whether the query matches a single document by path (rather than a + * collection). + */ +function isDocumentQuery$1(query) { + return (DocumentKey.isDocumentKey(query.path) && + query.collectionGroup === null && + query.filters.length === 0); +} +/** + * Returns whether the query matches a collection group rather than a specific + * collection. + */ +function isCollectionGroupQuery(query) { + return query.collectionGroup !== null; +} +/** + * Returns the normalized order-by constraint that is used to execute the Query, + * which can be different from the order-by constraints the user provided (e.g. + * the SDK and backend always orders by `__name__`). The normalized order-by + * includes implicit order-bys in addition to the explicit user provided + * order-bys. + */ +function queryNormalizedOrderBy(query) { + const queryImpl = debugCast(query); + if (queryImpl.memoizedNormalizedOrderBy === null) { + queryImpl.memoizedNormalizedOrderBy = []; + const fieldsNormalized = new Set(); + // Any explicit order by fields should be added as is. + for (const orderBy of queryImpl.explicitOrderBy) { + queryImpl.memoizedNormalizedOrderBy.push(orderBy); + fieldsNormalized.add(orderBy.field.canonicalString()); + } + // The order of the implicit ordering always matches the last explicit order by. + const lastDirection = queryImpl.explicitOrderBy.length > 0 + ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1].dir + : "asc" /* Direction.ASCENDING */; + // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical + // order. When there are multiple inequality filters on the same field, the field should be added + // only once. + // Note: `SortedSet` sorts the key field before other fields. However, we want the key + // field to be sorted last. + const inequalityFields = getInequalityFilterFields(queryImpl); + inequalityFields.forEach(field => { + if (!fieldsNormalized.has(field.canonicalString()) && + !field.isKeyField()) { + queryImpl.memoizedNormalizedOrderBy.push(new OrderBy(field, lastDirection)); + } + }); + // Add the document key field to the last if it is not explicitly ordered. + if (!fieldsNormalized.has(FieldPath$1.keyField().canonicalString())) { + queryImpl.memoizedNormalizedOrderBy.push(new OrderBy(FieldPath$1.keyField(), lastDirection)); + } + } + return queryImpl.memoizedNormalizedOrderBy; +} +/** + * Converts this `Query` instance to its corresponding `Target` representation. + */ +function queryToTarget(query) { + const queryImpl = debugCast(query); + if (!queryImpl.memoizedTarget) { + queryImpl.memoizedTarget = _queryToTarget(queryImpl, queryNormalizedOrderBy(query)); + } + return queryImpl.memoizedTarget; +} +/** + * Converts this `Query` instance to its corresponding `Target` representation, + * for use within an aggregate query. Unlike targets for non-aggregate queries, + * aggregate query targets do not contain normalized order-bys, they only + * contain explicit order-bys. + */ +function queryToAggregateTarget(query) { + const queryImpl = debugCast(query); + if (!queryImpl.memoizedAggregateTarget) { + // Do not include implicit order-bys for aggregate queries. + queryImpl.memoizedAggregateTarget = _queryToTarget(queryImpl, query.explicitOrderBy); + } + return queryImpl.memoizedAggregateTarget; +} +function _queryToTarget(queryImpl, orderBys) { + if (queryImpl.limitType === "F" /* LimitType.First */) { + return newTarget(queryImpl.path, queryImpl.collectionGroup, orderBys, queryImpl.filters, queryImpl.limit, queryImpl.startAt, queryImpl.endAt); + } + else { + // Flip the orderBy directions since we want the last results + orderBys = orderBys.map(orderBy => { + const dir = orderBy.dir === "desc" /* Direction.DESCENDING */ + ? "asc" /* Direction.ASCENDING */ + : "desc" /* Direction.DESCENDING */; + return new OrderBy(orderBy.field, dir); + }); + // We need to swap the cursors to match the now-flipped query ordering. + const startAt = queryImpl.endAt + ? new Bound(queryImpl.endAt.position, queryImpl.endAt.inclusive) + : null; + const endAt = queryImpl.startAt + ? new Bound(queryImpl.startAt.position, queryImpl.startAt.inclusive) + : null; + // Now return as a LimitType.First query. + return newTarget(queryImpl.path, queryImpl.collectionGroup, orderBys, queryImpl.filters, queryImpl.limit, startAt, endAt); + } +} +function queryWithAddedFilter(query, filter) { + const newFilters = query.filters.concat([filter]); + return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), newFilters, query.limit, query.limitType, query.startAt, query.endAt); +} +function queryWithAddedOrderBy(query, orderBy) { + // TODO(dimond): validate that orderBy does not list the same key twice. + const newOrderBy = query.explicitOrderBy.concat([orderBy]); + return new QueryImpl(query.path, query.collectionGroup, newOrderBy, query.filters.slice(), query.limit, query.limitType, query.startAt, query.endAt); +} +function queryWithLimit(query, limit, limitType) { + return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), limit, limitType, query.startAt, query.endAt); +} +function queryWithStartAt(query, bound) { + return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, bound, query.endAt); +} +function queryWithEndAt(query, bound) { + return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, query.startAt, bound); +} +function queryEquals(left, right) { + return (targetEquals(queryToTarget(left), queryToTarget(right)) && + left.limitType === right.limitType); +} +// TODO(b/29183165): This is used to get a unique string from a query to, for +// example, use as a dictionary key, but the implementation is subject to +// collisions. Make it collision-free. +function canonifyQuery(query) { + return `${canonifyTarget(queryToTarget(query))}|lt:${query.limitType}`; +} +function stringifyQuery(query) { + return `Query(target=${stringifyTarget(queryToTarget(query))}; limitType=${query.limitType})`; +} +/** Returns whether `doc` matches the constraints of `query`. */ +function queryMatches(query, doc) { + return (doc.isFoundDocument() && + queryMatchesPathAndCollectionGroup(query, doc) && + queryMatchesOrderBy(query, doc) && + queryMatchesFilters(query, doc) && + queryMatchesBounds(query, doc)); +} +function queryMatchesPathAndCollectionGroup(query, doc) { + const docPath = doc.key.path; + if (query.collectionGroup !== null) { + // NOTE: this.path is currently always empty since we don't expose Collection + // Group queries rooted at a document path yet. + return (doc.key.hasCollectionId(query.collectionGroup) && + query.path.isPrefixOf(docPath)); + } + else if (DocumentKey.isDocumentKey(query.path)) { + // exact match for document queries + return query.path.isEqual(docPath); + } + else { + // shallow ancestor queries by default + return query.path.isImmediateParentOf(docPath); + } +} +/** + * A document must have a value for every ordering clause in order to show up + * in the results. + */ +function queryMatchesOrderBy(query, doc) { + // We must use `queryNormalizedOrderBy()` to get the list of all orderBys (both implicit and explicit). + // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must + // be taken into account. For example, the query "a > 1 || b==1" has an implicit "orderBy a" due + // to the inequality, and is evaluated as "a > 1 orderBy a || b==1 orderBy a". + // A document with content of {b:1} matches the filters, but does not match the orderBy because + // it's missing the field 'a'. + for (const orderBy of queryNormalizedOrderBy(query)) { + // order-by key always matches + if (!orderBy.field.isKeyField() && doc.data.field(orderBy.field) === null) { + return false; + } + } + return true; +} +function queryMatchesFilters(query, doc) { + for (const filter of query.filters) { + if (!filter.matches(doc)) { + return false; + } + } + return true; +} +/** Makes sure a document is within the bounds, if provided. */ +function queryMatchesBounds(query, doc) { + if (query.startAt && + !boundSortsBeforeDocument(query.startAt, queryNormalizedOrderBy(query), doc)) { + return false; + } + if (query.endAt && + !boundSortsAfterDocument(query.endAt, queryNormalizedOrderBy(query), doc)) { + return false; + } + return true; +} +/** + * Returns the collection group that this query targets. + * + * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab + * synchronization for query results. + */ +function queryCollectionGroup(query) { + return (query.collectionGroup || + (query.path.length % 2 === 1 + ? query.path.lastSegment() + : query.path.get(query.path.length - 2))); +} +/** + * Returns a new comparator function that can be used to compare two documents + * based on the Query's ordering constraint. + */ +function newQueryComparator(query) { + return (d1, d2) => { + let comparedOnKeyField = false; + for (const orderBy of queryNormalizedOrderBy(query)) { + const comp = compareDocs(orderBy, d1, d2); + if (comp !== 0) { + return comp; + } + comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField(); + } + return 0; + }; +} +function compareDocs(orderBy, d1, d2) { + const comparison = orderBy.field.isKeyField() + ? DocumentKey.comparator(d1.key, d2.key) + : compareDocumentsByField(orderBy.field, d1, d2); + switch (orderBy.dir) { + case "asc" /* Direction.ASCENDING */: + return comparison; + case "desc" /* Direction.DESCENDING */: + return -1 * comparison; + default: + return fail(0x4d4e, { direction: orderBy.dir }); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A map implementation that uses objects as keys. Objects must have an + * associated equals function and must be immutable. Entries in the map are + * stored together with the key being produced from the mapKeyFn. This map + * automatically handles collisions of keys. + */ +class ObjectMap { + constructor(mapKeyFn, equalsFn) { + this.mapKeyFn = mapKeyFn; + this.equalsFn = equalsFn; + /** + * The inner map for a key/value pair. Due to the possibility of collisions we + * keep a list of entries that we do a linear search through to find an actual + * match. Note that collisions should be rare, so we still expect near + * constant time lookups in practice. + */ + this.inner = {}; + /** The number of entries stored in the map */ + this.innerSize = 0; + } + /** Get a value for this key, or undefined if it does not exist. */ + get(key) { + const id = this.mapKeyFn(key); + const matches = this.inner[id]; + if (matches === undefined) { + return undefined; + } + for (const [otherKey, value] of matches) { + if (this.equalsFn(otherKey, key)) { + return value; + } + } + return undefined; + } + has(key) { + return this.get(key) !== undefined; + } + /** Put this key and value in the map. */ + set(key, value) { + const id = this.mapKeyFn(key); + const matches = this.inner[id]; + if (matches === undefined) { + this.inner[id] = [[key, value]]; + this.innerSize++; + return; + } + for (let i = 0; i < matches.length; i++) { + if (this.equalsFn(matches[i][0], key)) { + // This is updating an existing entry and does not increase `innerSize`. + matches[i] = [key, value]; + return; + } + } + matches.push([key, value]); + this.innerSize++; + } + /** + * Remove this key from the map. Returns a boolean if anything was deleted. + */ + delete(key) { + const id = this.mapKeyFn(key); + const matches = this.inner[id]; + if (matches === undefined) { + return false; + } + for (let i = 0; i < matches.length; i++) { + if (this.equalsFn(matches[i][0], key)) { + if (matches.length === 1) { + delete this.inner[id]; + } + else { + matches.splice(i, 1); + } + this.innerSize--; + return true; + } + } + return false; + } + forEach(fn) { + forEach(this.inner, (_, entries) => { + for (const [k, v] of entries) { + fn(k, v); + } + }); + } + isEmpty() { + return isEmpty(this.inner); + } + size() { + return this.innerSize; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const EMPTY_MUTABLE_DOCUMENT_MAP = new SortedMap(DocumentKey.comparator); +function mutableDocumentMap() { + return EMPTY_MUTABLE_DOCUMENT_MAP; +} +const EMPTY_DOCUMENT_MAP = new SortedMap(DocumentKey.comparator); +function documentMap(...docs) { + let map = EMPTY_DOCUMENT_MAP; + for (const doc of docs) { + map = map.insert(doc.key, doc); + } + return map; +} +function newOverlayedDocumentMap() { + return newDocumentKeyMap(); +} +function convertOverlayedDocumentMapToDocumentMap(collection) { + let documents = EMPTY_DOCUMENT_MAP; + collection.forEach((k, v) => (documents = documents.insert(k, v.overlayedDocument))); + return documents; +} +function newOverlayMap() { + return newDocumentKeyMap(); +} +function newMutationMap() { + return newDocumentKeyMap(); +} +function newDocumentKeyMap() { + return new ObjectMap(key => key.toString(), (l, r) => l.isEqual(r)); +} +const EMPTY_DOCUMENT_VERSION_MAP = new SortedMap(DocumentKey.comparator); +function documentVersionMap() { + return EMPTY_DOCUMENT_VERSION_MAP; +} +const EMPTY_DOCUMENT_KEY_SET = new SortedSet(DocumentKey.comparator); +function documentKeySet(...keys) { + let set = EMPTY_DOCUMENT_KEY_SET; + for (const key of keys) { + set = set.add(key); + } + return set; +} +const EMPTY_TARGET_ID_SET = new SortedSet(primitiveComparator); +function targetIdSet() { + return EMPTY_TARGET_ID_SET; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns an DoubleValue for `value` that is encoded based the serializer's + * `useProto3Json` setting. + */ +function toDouble(serializer, value) { + if (serializer.useProto3Json) { + if (isNaN(value)) { + return { doubleValue: 'NaN' }; + } + else if (value === Infinity) { + return { doubleValue: 'Infinity' }; + } + else if (value === -Infinity) { + return { doubleValue: '-Infinity' }; + } + } + return { doubleValue: isNegativeZero(value) ? '-0' : value }; +} +/** + * Returns an IntegerValue for `value`. + */ +function toInteger(value) { + return { integerValue: '' + value }; +} +/** + * Returns a value for a number that's appropriate to put into a proto. + * The return value is an IntegerValue if it can safely represent the value, + * otherwise a DoubleValue is returned. + */ +function toNumber(serializer, value) { + return isSafeInteger(value) ? toInteger(value) : toDouble(serializer, value); +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Used to represent a field transform on a mutation. */ +class TransformOperation { + constructor() { + // Make sure that the structural type of `TransformOperation` is unique. + // See https://github.com/microsoft/TypeScript/issues/5451 + this._ = undefined; + } +} +/** + * Computes the local transform result against the provided `previousValue`, + * optionally using the provided localWriteTime. + */ +function applyTransformOperationToLocalView(transform, previousValue, localWriteTime) { + if (transform instanceof ServerTimestampTransform) { + return serverTimestamp$1(localWriteTime, previousValue); + } + else if (transform instanceof ArrayUnionTransformOperation) { + return applyArrayUnionTransformOperation(transform, previousValue); + } + else if (transform instanceof ArrayRemoveTransformOperation) { + return applyArrayRemoveTransformOperation(transform, previousValue); + } + else { + return applyNumericIncrementTransformOperationToLocalView(transform, previousValue); + } +} +/** + * Computes a final transform result after the transform has been acknowledged + * by the server, potentially using the server-provided transformResult. + */ +function applyTransformOperationToRemoteDocument(transform, previousValue, transformResult) { + // The server just sends null as the transform result for array operations, + // so we have to calculate a result the same as we do for local + // applications. + if (transform instanceof ArrayUnionTransformOperation) { + return applyArrayUnionTransformOperation(transform, previousValue); + } + else if (transform instanceof ArrayRemoveTransformOperation) { + return applyArrayRemoveTransformOperation(transform, previousValue); + } + return transformResult; +} +/** + * If this transform operation is not idempotent, returns the base value to + * persist for this transform. If a base value is returned, the transform + * operation is always applied to this base value, even if document has + * already been updated. + * + * Base values provide consistent behavior for non-idempotent transforms and + * allow us to return the same latency-compensated value even if the backend + * has already applied the transform operation. The base value is null for + * idempotent transforms, as they can be re-played even if the backend has + * already applied them. + * + * @returns a base value to store along with the mutation, or null for + * idempotent transforms. + */ +function computeTransformOperationBaseValue(transform, previousValue) { + if (transform instanceof NumericIncrementTransformOperation) { + return isNumber(previousValue) ? previousValue : { integerValue: 0 }; + } + return null; +} +function transformOperationEquals(left, right) { + if (left instanceof ArrayUnionTransformOperation && + right instanceof ArrayUnionTransformOperation) { + return arrayEquals(left.elements, right.elements, valueEquals); + } + else if (left instanceof ArrayRemoveTransformOperation && + right instanceof ArrayRemoveTransformOperation) { + return arrayEquals(left.elements, right.elements, valueEquals); + } + else if (left instanceof NumericIncrementTransformOperation && + right instanceof NumericIncrementTransformOperation) { + return valueEquals(left.operand, right.operand); + } + return (left instanceof ServerTimestampTransform && + right instanceof ServerTimestampTransform); +} +/** Transforms a value into a server-generated timestamp. */ +class ServerTimestampTransform extends TransformOperation { +} +/** Transforms an array value via a union operation. */ +class ArrayUnionTransformOperation extends TransformOperation { + constructor(elements) { + super(); + this.elements = elements; + } +} +function applyArrayUnionTransformOperation(transform, previousValue) { + const values = coercedFieldValuesArray(previousValue); + for (const toUnion of transform.elements) { + if (!values.some(element => valueEquals(element, toUnion))) { + values.push(toUnion); + } + } + return { arrayValue: { values } }; +} +/** Transforms an array value via a remove operation. */ +class ArrayRemoveTransformOperation extends TransformOperation { + constructor(elements) { + super(); + this.elements = elements; + } +} +function applyArrayRemoveTransformOperation(transform, previousValue) { + let values = coercedFieldValuesArray(previousValue); + for (const toRemove of transform.elements) { + values = values.filter(element => !valueEquals(element, toRemove)); + } + return { arrayValue: { values } }; +} +/** + * Implements the backend semantics for locally computed NUMERIC_ADD (increment) + * transforms. Converts all field values to integers or doubles, but unlike the + * backend does not cap integer values at 2^63. Instead, JavaScript number + * arithmetic is used and precision loss can occur for values greater than 2^53. + */ +class NumericIncrementTransformOperation extends TransformOperation { + constructor(serializer, operand) { + super(); + this.serializer = serializer; + this.operand = operand; + } +} +function applyNumericIncrementTransformOperationToLocalView(transform, previousValue) { + // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit + // precision and resolves overflows by reducing precision, we do not + // manually cap overflows at 2^63. + const baseValue = computeTransformOperationBaseValue(transform, previousValue); + const sum = asNumber(baseValue) + asNumber(transform.operand); + if (isInteger(baseValue) && isInteger(transform.operand)) { + return toInteger(sum); + } + else { + return toDouble(transform.serializer, sum); + } +} +function asNumber(value) { + return normalizeNumber(value.integerValue || value.doubleValue); +} +function coercedFieldValuesArray(value) { + return isArray(value) && value.arrayValue.values + ? value.arrayValue.values.slice() + : []; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** A field path and the TransformOperation to perform upon it. */ +class FieldTransform { + constructor(field, transform) { + this.field = field; + this.transform = transform; + } +} +function fieldTransformEquals(left, right) { + return (left.field.isEqual(right.field) && + transformOperationEquals(left.transform, right.transform)); +} +function fieldTransformsAreEqual(left, right) { + if (left === undefined && right === undefined) { + return true; + } + if (left && right) { + return arrayEquals(left, right, (l, r) => fieldTransformEquals(l, r)); + } + return false; +} +/** The result of successfully applying a mutation to the backend. */ +class MutationResult { + constructor( + /** + * The version at which the mutation was committed: + * + * - For most operations, this is the updateTime in the WriteResult. + * - For deletes, the commitTime of the WriteResponse (because deletes are + * not stored and have no updateTime). + * + * Note that these versions can be different: No-op writes will not change + * the updateTime even though the commitTime advances. + */ + version, + /** + * The resulting fields returned from the backend after a mutation + * containing field transforms has been committed. Contains one FieldValue + * for each FieldTransform that was in the mutation. + * + * Will be empty if the mutation did not contain any field transforms. + */ + transformResults) { + this.version = version; + this.transformResults = transformResults; + } +} +/** + * Encodes a precondition for a mutation. This follows the model that the + * backend accepts with the special case of an explicit "empty" precondition + * (meaning no precondition). + */ +class Precondition { + constructor(updateTime, exists) { + this.updateTime = updateTime; + this.exists = exists; + } + /** Creates a new empty Precondition. */ + static none() { + return new Precondition(); + } + /** Creates a new Precondition with an exists flag. */ + static exists(exists) { + return new Precondition(undefined, exists); + } + /** Creates a new Precondition based on a version a document exists at. */ + static updateTime(version) { + return new Precondition(version); + } + /** Returns whether this Precondition is empty. */ + get isNone() { + return this.updateTime === undefined && this.exists === undefined; + } + isEqual(other) { + return (this.exists === other.exists && + (this.updateTime + ? !!other.updateTime && this.updateTime.isEqual(other.updateTime) + : !other.updateTime)); + } +} +/** Returns true if the preconditions is valid for the given document. */ +function preconditionIsValidForDocument(precondition, document) { + if (precondition.updateTime !== undefined) { + return (document.isFoundDocument() && + document.version.isEqual(precondition.updateTime)); + } + else if (precondition.exists !== undefined) { + return precondition.exists === document.isFoundDocument(); + } + else { + return true; + } +} +/** + * A mutation describes a self-contained change to a document. Mutations can + * create, replace, delete, and update subsets of documents. + * + * Mutations not only act on the value of the document but also its version. + * + * For local mutations (mutations that haven't been committed yet), we preserve + * the existing version for Set and Patch mutations. For Delete mutations, we + * reset the version to 0. + * + * Here's the expected transition table. + * + * MUTATION APPLIED TO RESULTS IN + * + * SetMutation Document(v3) Document(v3) + * SetMutation NoDocument(v3) Document(v0) + * SetMutation InvalidDocument(v0) Document(v0) + * PatchMutation Document(v3) Document(v3) + * PatchMutation NoDocument(v3) NoDocument(v3) + * PatchMutation InvalidDocument(v0) UnknownDocument(v3) + * DeleteMutation Document(v3) NoDocument(v0) + * DeleteMutation NoDocument(v3) NoDocument(v0) + * DeleteMutation InvalidDocument(v0) NoDocument(v0) + * + * For acknowledged mutations, we use the updateTime of the WriteResponse as + * the resulting version for Set and Patch mutations. As deletes have no + * explicit update time, we use the commitTime of the WriteResponse for + * Delete mutations. + * + * If a mutation is acknowledged by the backend but fails the precondition check + * locally, we transition to an `UnknownDocument` and rely on Watch to send us + * the updated version. + * + * Field transforms are used only with Patch and Set Mutations. We use the + * `updateTransforms` message to store transforms, rather than the `transforms`s + * messages. + * + * ## Subclassing Notes + * + * Every type of mutation needs to implement its own applyToRemoteDocument() and + * applyToLocalView() to implement the actual behavior of applying the mutation + * to some source document (see `setMutationApplyToRemoteDocument()` for an + * example). + */ +class Mutation { +} +/** + * A utility method to calculate a `Mutation` representing the overlay from the + * final state of the document, and a `FieldMask` representing the fields that + * are mutated by the local mutations. + */ +function calculateOverlayMutation(doc, mask) { + if (!doc.hasLocalMutations || (mask && mask.fields.length === 0)) { + return null; + } + // mask is null when sets or deletes are applied to the current document. + if (mask === null) { + if (doc.isNoDocument()) { + return new DeleteMutation(doc.key, Precondition.none()); + } + else { + return new SetMutation(doc.key, doc.data, Precondition.none()); + } + } + else { + const docValue = doc.data; + const patchValue = ObjectValue.empty(); + let maskSet = new SortedSet(FieldPath$1.comparator); + for (let path of mask.fields) { + if (!maskSet.has(path)) { + let value = docValue.field(path); + // If we are deleting a nested field, we take the immediate parent as + // the mask used to construct the resulting mutation. + // Justification: Nested fields can create parent fields implicitly. If + // only a leaf entry is deleted in later mutations, the parent field + // should still remain, but we may have lost this information. + // Consider mutation (foo.bar 1), then mutation (foo.bar delete()). + // This leaves the final result (foo, {}). Despite the fact that `doc` + // has the correct result, `foo` is not in `mask`, and the resulting + // mutation would miss `foo`. + if (value === null && path.length > 1) { + path = path.popLast(); + value = docValue.field(path); + } + if (value === null) { + patchValue.delete(path); + } + else { + patchValue.set(path, value); + } + maskSet = maskSet.add(path); + } + } + return new PatchMutation(doc.key, patchValue, new FieldMask(maskSet.toArray()), Precondition.none()); + } +} +/** + * Applies this mutation to the given document for the purposes of computing a + * new remote document. If the input document doesn't match the expected state + * (e.g. it is invalid or outdated), the document type may transition to + * unknown. + * + * @param mutation - The mutation to apply. + * @param document - The document to mutate. The input document can be an + * invalid document if the client has no knowledge of the pre-mutation state + * of the document. + * @param mutationResult - The result of applying the mutation from the backend. + */ +function mutationApplyToRemoteDocument(mutation, document, mutationResult) { + if (mutation instanceof SetMutation) { + setMutationApplyToRemoteDocument(mutation, document, mutationResult); + } + else if (mutation instanceof PatchMutation) { + patchMutationApplyToRemoteDocument(mutation, document, mutationResult); + } + else { + deleteMutationApplyToRemoteDocument(mutation, document, mutationResult); + } +} +/** + * Applies this mutation to the given document for the purposes of computing + * the new local view of a document. If the input document doesn't match the + * expected state, the document is not modified. + * + * @param mutation - The mutation to apply. + * @param document - The document to mutate. The input document can be an + * invalid document if the client has no knowledge of the pre-mutation state + * of the document. + * @param previousMask - The fields that have been updated before applying this mutation. + * @param localWriteTime - A timestamp indicating the local write time of the + * batch this mutation is a part of. + * @returns A `FieldMask` representing the fields that are changed by applying this mutation. + */ +function mutationApplyToLocalView(mutation, document, previousMask, localWriteTime) { + if (mutation instanceof SetMutation) { + return setMutationApplyToLocalView(mutation, document, previousMask, localWriteTime); + } + else if (mutation instanceof PatchMutation) { + return patchMutationApplyToLocalView(mutation, document, previousMask, localWriteTime); + } + else { + return deleteMutationApplyToLocalView(mutation, document, previousMask); + } +} +/** + * If this mutation is not idempotent, returns the base value to persist with + * this mutation. If a base value is returned, the mutation is always applied + * to this base value, even if document has already been updated. + * + * The base value is a sparse object that consists of only the document + * fields for which this mutation contains a non-idempotent transformation + * (e.g. a numeric increment). The provided value guarantees consistent + * behavior for non-idempotent transforms and allow us to return the same + * latency-compensated value even if the backend has already applied the + * mutation. The base value is null for idempotent mutations, as they can be + * re-played even if the backend has already applied them. + * + * @returns a base value to store along with the mutation, or null for + * idempotent mutations. + */ +function mutationExtractBaseValue(mutation, document) { + let baseObject = null; + for (const fieldTransform of mutation.fieldTransforms) { + const existingValue = document.data.field(fieldTransform.field); + const coercedValue = computeTransformOperationBaseValue(fieldTransform.transform, existingValue || null); + if (coercedValue != null) { + if (baseObject === null) { + baseObject = ObjectValue.empty(); + } + baseObject.set(fieldTransform.field, coercedValue); + } + } + return baseObject ? baseObject : null; +} +function mutationEquals(left, right) { + if (left.type !== right.type) { + return false; + } + if (!left.key.isEqual(right.key)) { + return false; + } + if (!left.precondition.isEqual(right.precondition)) { + return false; + } + if (!fieldTransformsAreEqual(left.fieldTransforms, right.fieldTransforms)) { + return false; + } + if (left.type === 0 /* MutationType.Set */) { + return left.value.isEqual(right.value); + } + if (left.type === 1 /* MutationType.Patch */) { + return (left.data.isEqual(right.data) && + left.fieldMask.isEqual(right.fieldMask)); + } + return true; +} +/** + * A mutation that creates or replaces the document at the given key with the + * object value contents. + */ +class SetMutation extends Mutation { + constructor(key, value, precondition, fieldTransforms = []) { + super(); + this.key = key; + this.value = value; + this.precondition = precondition; + this.fieldTransforms = fieldTransforms; + this.type = 0 /* MutationType.Set */; + } + getFieldMask() { + return null; + } +} +function setMutationApplyToRemoteDocument(mutation, document, mutationResult) { + // Unlike setMutationApplyToLocalView, if we're applying a mutation to a + // remote document the server has accepted the mutation so the precondition + // must have held. + const newData = mutation.value.clone(); + const transformResults = serverTransformResults(mutation.fieldTransforms, document, mutationResult.transformResults); + newData.setAll(transformResults); + document + .convertToFoundDocument(mutationResult.version, newData) + .setHasCommittedMutations(); +} +function setMutationApplyToLocalView(mutation, document, previousMask, localWriteTime) { + if (!preconditionIsValidForDocument(mutation.precondition, document)) { + // The mutation failed to apply (e.g. a document ID created with add() + // caused a name collision). + return previousMask; + } + const newData = mutation.value.clone(); + const transformResults = localTransformResults(mutation.fieldTransforms, localWriteTime, document); + newData.setAll(transformResults); + document + .convertToFoundDocument(document.version, newData) + .setHasLocalMutations(); + return null; // SetMutation overwrites all fields. +} +/** + * A mutation that modifies fields of the document at the given key with the + * given values. The values are applied through a field mask: + * + * * When a field is in both the mask and the values, the corresponding field + * is updated. + * * When a field is in neither the mask nor the values, the corresponding + * field is unmodified. + * * When a field is in the mask but not in the values, the corresponding field + * is deleted. + * * When a field is not in the mask but is in the values, the values map is + * ignored. + */ +class PatchMutation extends Mutation { + constructor(key, data, fieldMask, precondition, fieldTransforms = []) { + super(); + this.key = key; + this.data = data; + this.fieldMask = fieldMask; + this.precondition = precondition; + this.fieldTransforms = fieldTransforms; + this.type = 1 /* MutationType.Patch */; + } + getFieldMask() { + return this.fieldMask; + } +} +function patchMutationApplyToRemoteDocument(mutation, document, mutationResult) { + if (!preconditionIsValidForDocument(mutation.precondition, document)) { + // Since the mutation was not rejected, we know that the precondition + // matched on the backend. We therefore must not have the expected version + // of the document in our cache and convert to an UnknownDocument with a + // known updateTime. + document.convertToUnknownDocument(mutationResult.version); + return; + } + const transformResults = serverTransformResults(mutation.fieldTransforms, document, mutationResult.transformResults); + const newData = document.data; + newData.setAll(getPatch(mutation)); + newData.setAll(transformResults); + document + .convertToFoundDocument(mutationResult.version, newData) + .setHasCommittedMutations(); +} +function patchMutationApplyToLocalView(mutation, document, previousMask, localWriteTime) { + if (!preconditionIsValidForDocument(mutation.precondition, document)) { + return previousMask; + } + const transformResults = localTransformResults(mutation.fieldTransforms, localWriteTime, document); + const newData = document.data; + newData.setAll(getPatch(mutation)); + newData.setAll(transformResults); + document + .convertToFoundDocument(document.version, newData) + .setHasLocalMutations(); + if (previousMask === null) { + return null; + } + return previousMask + .unionWith(mutation.fieldMask.fields) + .unionWith(mutation.fieldTransforms.map(transform => transform.field)); +} +/** + * Returns a FieldPath/Value map with the content of the PatchMutation. + */ +function getPatch(mutation) { + const result = new Map(); + mutation.fieldMask.fields.forEach(fieldPath => { + if (!fieldPath.isEmpty()) { + const newValue = mutation.data.field(fieldPath); + result.set(fieldPath, newValue); + } + }); + return result; +} +/** + * Creates a list of "transform results" (a transform result is a field value + * representing the result of applying a transform) for use after a mutation + * containing transforms has been acknowledged by the server. + * + * @param fieldTransforms - The field transforms to apply the result to. + * @param mutableDocument - The current state of the document after applying all + * previous mutations. + * @param serverTransformResults - The transform results received by the server. + * @returns The transform results list. + */ +function serverTransformResults(fieldTransforms, mutableDocument, serverTransformResults) { + const transformResults = new Map(); + hardAssert(fieldTransforms.length === serverTransformResults.length, 0x7f90, { + serverTransformResultCount: serverTransformResults.length, + fieldTransformCount: fieldTransforms.length + }); + for (let i = 0; i < serverTransformResults.length; i++) { + const fieldTransform = fieldTransforms[i]; + const transform = fieldTransform.transform; + const previousValue = mutableDocument.data.field(fieldTransform.field); + transformResults.set(fieldTransform.field, applyTransformOperationToRemoteDocument(transform, previousValue, serverTransformResults[i])); + } + return transformResults; +} +/** + * Creates a list of "transform results" (a transform result is a field value + * representing the result of applying a transform) for use when applying a + * transform locally. + * + * @param fieldTransforms - The field transforms to apply the result to. + * @param localWriteTime - The local time of the mutation (used to + * generate ServerTimestampValues). + * @param mutableDocument - The document to apply transforms on. + * @returns The transform results list. + */ +function localTransformResults(fieldTransforms, localWriteTime, mutableDocument) { + const transformResults = new Map(); + for (const fieldTransform of fieldTransforms) { + const transform = fieldTransform.transform; + const previousValue = mutableDocument.data.field(fieldTransform.field); + transformResults.set(fieldTransform.field, applyTransformOperationToLocalView(transform, previousValue, localWriteTime)); + } + return transformResults; +} +/** A mutation that deletes the document at the given key. */ +class DeleteMutation extends Mutation { + constructor(key, precondition) { + super(); + this.key = key; + this.precondition = precondition; + this.type = 2 /* MutationType.Delete */; + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } +} +function deleteMutationApplyToRemoteDocument(mutation, document, mutationResult) { + // Unlike applyToLocalView, if we're applying a mutation to a remote + // document the server has accepted the mutation so the precondition must + // have held. + document + .convertToNoDocument(mutationResult.version) + .setHasCommittedMutations(); +} +function deleteMutationApplyToLocalView(mutation, document, previousMask) { + if (preconditionIsValidForDocument(mutation.precondition, document)) { + document.convertToNoDocument(document.version).setHasLocalMutations(); + return null; + } + return previousMask; +} +/** + * A mutation that verifies the existence of the document at the given key with + * the provided precondition. + * + * The `verify` operation is only used in Transactions, and this class serves + * primarily to facilitate serialization into protos. + */ +class VerifyMutation extends Mutation { + constructor(key, precondition) { + super(); + this.key = key; + this.precondition = precondition; + this.type = 3 /* MutationType.Verify */; + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A batch of mutations that will be sent as one unit to the backend. + */ +class MutationBatch { + /** + * @param batchId - The unique ID of this mutation batch. + * @param localWriteTime - The original write time of this mutation. + * @param baseMutations - Mutations that are used to populate the base + * values when this mutation is applied locally. This can be used to locally + * overwrite values that are persisted in the remote document cache. Base + * mutations are never sent to the backend. + * @param mutations - The user-provided mutations in this mutation batch. + * User-provided mutations are applied both locally and remotely on the + * backend. + */ + constructor(batchId, localWriteTime, baseMutations, mutations) { + this.batchId = batchId; + this.localWriteTime = localWriteTime; + this.baseMutations = baseMutations; + this.mutations = mutations; + } + /** + * Applies all the mutations in this MutationBatch to the specified document + * to compute the state of the remote document + * + * @param document - The document to apply mutations to. + * @param batchResult - The result of applying the MutationBatch to the + * backend. + */ + applyToRemoteDocument(document, batchResult) { + const mutationResults = batchResult.mutationResults; + for (let i = 0; i < this.mutations.length; i++) { + const mutation = this.mutations[i]; + if (mutation.key.isEqual(document.key)) { + const mutationResult = mutationResults[i]; + mutationApplyToRemoteDocument(mutation, document, mutationResult); + } + } + } + /** + * Computes the local view of a document given all the mutations in this + * batch. + * + * @param document - The document to apply mutations to. + * @param mutatedFields - Fields that have been updated before applying this mutation batch. + * @returns A `FieldMask` representing all the fields that are mutated. + */ + applyToLocalView(document, mutatedFields) { + // First, apply the base state. This allows us to apply non-idempotent + // transform against a consistent set of values. + for (const mutation of this.baseMutations) { + if (mutation.key.isEqual(document.key)) { + mutatedFields = mutationApplyToLocalView(mutation, document, mutatedFields, this.localWriteTime); + } + } + // Second, apply all user-provided mutations. + for (const mutation of this.mutations) { + if (mutation.key.isEqual(document.key)) { + mutatedFields = mutationApplyToLocalView(mutation, document, mutatedFields, this.localWriteTime); + } + } + return mutatedFields; + } + /** + * Computes the local view for all provided documents given the mutations in + * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to + * replace all the mutation applications. + */ + applyToLocalDocumentSet(documentMap, documentsWithoutRemoteVersion) { + // TODO(mrschmidt): This implementation is O(n^2). If we apply the mutations + // directly (as done in `applyToLocalView()`), we can reduce the complexity + // to O(n). + const overlays = newMutationMap(); + this.mutations.forEach(m => { + const overlayedDocument = documentMap.get(m.key); + // TODO(mutabledocuments): This method should take a MutableDocumentMap + // and we should remove this cast. + const mutableDocument = overlayedDocument.overlayedDocument; + let mutatedFields = this.applyToLocalView(mutableDocument, overlayedDocument.mutatedFields); + // Set mutatedFields to null if the document is only from local mutations. + // This creates a Set or Delete mutation, instead of trying to create a + // patch mutation as the overlay. + mutatedFields = documentsWithoutRemoteVersion.has(m.key) + ? null + : mutatedFields; + const overlay = calculateOverlayMutation(mutableDocument, mutatedFields); + if (overlay !== null) { + overlays.set(m.key, overlay); + } + if (!mutableDocument.isValidDocument()) { + mutableDocument.convertToNoDocument(SnapshotVersion.min()); + } + }); + return overlays; + } + keys() { + return this.mutations.reduce((keys, m) => keys.add(m.key), documentKeySet()); + } + isEqual(other) { + return (this.batchId === other.batchId && + arrayEquals(this.mutations, other.mutations, (l, r) => mutationEquals(l, r)) && + arrayEquals(this.baseMutations, other.baseMutations, (l, r) => mutationEquals(l, r))); + } +} +/** The result of applying a mutation batch to the backend. */ +class MutationBatchResult { + constructor(batch, commitVersion, mutationResults, + /** + * A pre-computed mapping from each mutated document to the resulting + * version. + */ + docVersions) { + this.batch = batch; + this.commitVersion = commitVersion; + this.mutationResults = mutationResults; + this.docVersions = docVersions; + } + /** + * Creates a new MutationBatchResult for the given batch and results. There + * must be one result for each mutation in the batch. This static factory + * caches a document=>version mapping (docVersions). + */ + static from(batch, commitVersion, results) { + hardAssert(batch.mutations.length === results.length, 0xe5da, { + mutationsSent: batch.mutations.length, + resultsReceived: results.length + }); + let versionMap = documentVersionMap(); + const mutations = batch.mutations; + for (let i = 0; i < mutations.length; i++) { + versionMap = versionMap.insert(mutations[i].key, results[i].version); + } + return new MutationBatchResult(batch, commitVersion, results, versionMap); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Representation of an overlay computed by Firestore. + * + * Holds information about a mutation and the largest batch id in Firestore when + * the mutation was created. + */ +class Overlay { + constructor(largestBatchId, mutation) { + this.largestBatchId = largestBatchId; + this.mutation = mutation; + } + getKey() { + return this.mutation.key; + } + isEqual(other) { + return other !== null && this.mutation === other.mutation; + } + toString() { + return `Overlay{ + largestBatchId: ${this.largestBatchId}, + mutation: ${this.mutation.toString()} + }`; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class ExistenceFilter { + constructor(count, unchangedNames) { + this.count = count; + this.unchangedNames = unchangedNames; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Error Codes describing the different ways GRPC can fail. These are copied + * directly from GRPC's sources here: + * + * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h + * + * Important! The names of these identifiers matter because the string forms + * are used for reverse lookups from the webchannel stream. Do NOT change the + * names of these identifiers or change this into a const enum. + */ +var RpcCode; +(function (RpcCode) { + RpcCode[RpcCode["OK"] = 0] = "OK"; + RpcCode[RpcCode["CANCELLED"] = 1] = "CANCELLED"; + RpcCode[RpcCode["UNKNOWN"] = 2] = "UNKNOWN"; + RpcCode[RpcCode["INVALID_ARGUMENT"] = 3] = "INVALID_ARGUMENT"; + RpcCode[RpcCode["DEADLINE_EXCEEDED"] = 4] = "DEADLINE_EXCEEDED"; + RpcCode[RpcCode["NOT_FOUND"] = 5] = "NOT_FOUND"; + RpcCode[RpcCode["ALREADY_EXISTS"] = 6] = "ALREADY_EXISTS"; + RpcCode[RpcCode["PERMISSION_DENIED"] = 7] = "PERMISSION_DENIED"; + RpcCode[RpcCode["UNAUTHENTICATED"] = 16] = "UNAUTHENTICATED"; + RpcCode[RpcCode["RESOURCE_EXHAUSTED"] = 8] = "RESOURCE_EXHAUSTED"; + RpcCode[RpcCode["FAILED_PRECONDITION"] = 9] = "FAILED_PRECONDITION"; + RpcCode[RpcCode["ABORTED"] = 10] = "ABORTED"; + RpcCode[RpcCode["OUT_OF_RANGE"] = 11] = "OUT_OF_RANGE"; + RpcCode[RpcCode["UNIMPLEMENTED"] = 12] = "UNIMPLEMENTED"; + RpcCode[RpcCode["INTERNAL"] = 13] = "INTERNAL"; + RpcCode[RpcCode["UNAVAILABLE"] = 14] = "UNAVAILABLE"; + RpcCode[RpcCode["DATA_LOSS"] = 15] = "DATA_LOSS"; +})(RpcCode || (RpcCode = {})); +/** + * Determines whether an error code represents a permanent error when received + * in response to a non-write operation. + * + * See isPermanentWriteError for classifying write errors. + */ +function isPermanentError(code) { + switch (code) { + case Code.OK: + return fail(0xfdaa); + case Code.CANCELLED: + case Code.UNKNOWN: + case Code.DEADLINE_EXCEEDED: + case Code.RESOURCE_EXHAUSTED: + case Code.INTERNAL: + case Code.UNAVAILABLE: + // Unauthenticated means something went wrong with our token and we need + // to retry with new credentials which will happen automatically. + case Code.UNAUTHENTICATED: + return false; + case Code.INVALID_ARGUMENT: + case Code.NOT_FOUND: + case Code.ALREADY_EXISTS: + case Code.PERMISSION_DENIED: + case Code.FAILED_PRECONDITION: + // Aborted might be retried in some scenarios, but that is dependent on + // the context and should handled individually by the calling code. + // See https://cloud.google.com/apis/design/errors. + case Code.ABORTED: + case Code.OUT_OF_RANGE: + case Code.UNIMPLEMENTED: + case Code.DATA_LOSS: + return true; + default: + return fail(0x3c6b, { code }); + } +} +/** + * Determines whether an error code represents a permanent error when received + * in response to a write operation. + * + * Write operations must be handled specially because as of b/119437764, ABORTED + * errors on the write stream should be retried too (even though ABORTED errors + * are not generally retryable). + * + * Note that during the initial handshake on the write stream an ABORTED error + * signals that we should discard our stream token (i.e. it is permanent). This + * means a handshake error should be classified with isPermanentError, above. + */ +function isPermanentWriteError(code) { + return isPermanentError(code) && code !== Code.ABORTED; +} +/** + * Maps an error Code from GRPC status code number, like 0, 1, or 14. These + * are not the same as HTTP status codes. + * + * @returns The Code equivalent to the given GRPC status code. Fails if there + * is no match. + */ +function mapCodeFromRpcCode(code) { + if (code === undefined) { + // This shouldn't normally happen, but in certain error cases (like trying + // to send invalid proto messages) we may get an error with no GRPC code. + logError('GRPC error has no .code'); + return Code.UNKNOWN; + } + switch (code) { + case RpcCode.OK: + return Code.OK; + case RpcCode.CANCELLED: + return Code.CANCELLED; + case RpcCode.UNKNOWN: + return Code.UNKNOWN; + case RpcCode.DEADLINE_EXCEEDED: + return Code.DEADLINE_EXCEEDED; + case RpcCode.RESOURCE_EXHAUSTED: + return Code.RESOURCE_EXHAUSTED; + case RpcCode.INTERNAL: + return Code.INTERNAL; + case RpcCode.UNAVAILABLE: + return Code.UNAVAILABLE; + case RpcCode.UNAUTHENTICATED: + return Code.UNAUTHENTICATED; + case RpcCode.INVALID_ARGUMENT: + return Code.INVALID_ARGUMENT; + case RpcCode.NOT_FOUND: + return Code.NOT_FOUND; + case RpcCode.ALREADY_EXISTS: + return Code.ALREADY_EXISTS; + case RpcCode.PERMISSION_DENIED: + return Code.PERMISSION_DENIED; + case RpcCode.FAILED_PRECONDITION: + return Code.FAILED_PRECONDITION; + case RpcCode.ABORTED: + return Code.ABORTED; + case RpcCode.OUT_OF_RANGE: + return Code.OUT_OF_RANGE; + case RpcCode.UNIMPLEMENTED: + return Code.UNIMPLEMENTED; + case RpcCode.DATA_LOSS: + return Code.DATA_LOSS; + default: + return fail(0x999b, { code }); + } +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An error encountered while decoding base64 string. + */ +class Base64DecodeError extends Error { + constructor() { + super(...arguments); + this.name = 'Base64DecodeError'; + } +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The global, singleton instance of TestingHooksSpi. + * + * This variable will be `null` in all cases _except_ when running from + * integration tests that have registered callbacks to be notified of events + * that happen during the test execution. + */ +let testingHooksSpi = null; +/** + * Sets the value of the `testingHooksSpi` object. + * @param instance the instance to set. + */ +function setTestingHooksSpi(instance) { + if (testingHooksSpi) { + throw new Error('a TestingHooksSpi instance is already set'); + } + testingHooksSpi = instance; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An instance of the Platform's 'TextEncoder' implementation. + */ +function newTextEncoder() { + return new util$1.TextEncoder(); +} +/** + * An instance of the Platform's 'TextDecoder' implementation. + */ +function newTextDecoder() { + return new util$1.TextDecoder('utf-8'); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const MAX_64_BIT_UNSIGNED_INTEGER = new bloomBlob.Integer([0xffffffff, 0xffffffff], 0); +// Hash a string using md5 hashing algorithm. +function getMd5HashValue(value) { + const encodedValue = newTextEncoder().encode(value); + const md5 = new bloomBlob.Md5(); + md5.update(encodedValue); + return new Uint8Array(md5.digest()); +} +// Interpret the 16 bytes array as two 64-bit unsigned integers, encoded using +// 2’s complement using little endian. +function get64BitUints(Bytes) { + const dataView = new DataView(Bytes.buffer); + const chunk1 = dataView.getUint32(0, /* littleEndian= */ true); + const chunk2 = dataView.getUint32(4, /* littleEndian= */ true); + const chunk3 = dataView.getUint32(8, /* littleEndian= */ true); + const chunk4 = dataView.getUint32(12, /* littleEndian= */ true); + const integer1 = new bloomBlob.Integer([chunk1, chunk2], 0); + const integer2 = new bloomBlob.Integer([chunk3, chunk4], 0); + return [integer1, integer2]; +} +class BloomFilter { + constructor(bitmap, padding, hashCount) { + this.bitmap = bitmap; + this.padding = padding; + this.hashCount = hashCount; + if (padding < 0 || padding >= 8) { + throw new BloomFilterError(`Invalid padding: ${padding}`); + } + if (hashCount < 0) { + throw new BloomFilterError(`Invalid hash count: ${hashCount}`); + } + if (bitmap.length > 0 && this.hashCount === 0) { + // Only empty bloom filter can have 0 hash count. + throw new BloomFilterError(`Invalid hash count: ${hashCount}`); + } + if (bitmap.length === 0 && padding !== 0) { + // Empty bloom filter should have 0 padding. + throw new BloomFilterError(`Invalid padding when bitmap length is 0: ${padding}`); + } + this.bitCount = bitmap.length * 8 - padding; + // Set the bit count in Integer to avoid repetition in mightContain(). + this.bitCountInInteger = bloomBlob.Integer.fromNumber(this.bitCount); + } + // Calculate the ith hash value based on the hashed 64bit integers, + // and calculate its corresponding bit index in the bitmap to be checked. + getBitIndex(num1, num2, hashIndex) { + // Calculate hashed value h(i) = h1 + (i * h2). + let hashValue = num1.add(num2.multiply(bloomBlob.Integer.fromNumber(hashIndex))); + // Wrap if hash value overflow 64bit. + if (hashValue.compare(MAX_64_BIT_UNSIGNED_INTEGER) === 1) { + hashValue = new bloomBlob.Integer([hashValue.getBits(0), hashValue.getBits(1)], 0); + } + return hashValue.modulo(this.bitCountInInteger).toNumber(); + } + // Return whether the bit on the given index in the bitmap is set to 1. + isBitSet(index) { + // To retrieve bit n, calculate: (bitmap[n / 8] & (0x01 << (n % 8))). + const byte = this.bitmap[Math.floor(index / 8)]; + const offset = index % 8; + return (byte & (0x01 << offset)) !== 0; + } + mightContain(value) { + // Empty bitmap should always return false on membership check. + if (this.bitCount === 0) { + return false; + } + const md5HashedValue = getMd5HashValue(value); + const [hash1, hash2] = get64BitUints(md5HashedValue); + for (let i = 0; i < this.hashCount; i++) { + const index = this.getBitIndex(hash1, hash2, i); + if (!this.isBitSet(index)) { + return false; + } + } + return true; + } + /** Create bloom filter for testing purposes only. */ + static create(bitCount, hashCount, contains) { + const padding = bitCount % 8 === 0 ? 0 : 8 - (bitCount % 8); + const bitmap = new Uint8Array(Math.ceil(bitCount / 8)); + const bloomFilter = new BloomFilter(bitmap, padding, hashCount); + contains.forEach(item => bloomFilter.insert(item)); + return bloomFilter; + } + insert(value) { + if (this.bitCount === 0) { + return; + } + const md5HashedValue = getMd5HashValue(value); + const [hash1, hash2] = get64BitUints(md5HashedValue); + for (let i = 0; i < this.hashCount; i++) { + const index = this.getBitIndex(hash1, hash2, i); + this.setBit(index); + } + } + setBit(index) { + const indexOfByte = Math.floor(index / 8); + const offset = index % 8; + this.bitmap[indexOfByte] |= 0x01 << offset; + } +} +class BloomFilterError extends Error { + constructor() { + super(...arguments); + this.name = 'BloomFilterError'; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An event from the RemoteStore. It is split into targetChanges (changes to the + * state or the set of documents in our watched targets) and documentUpdates + * (changes to the actual documents). + */ +class RemoteEvent { + constructor( + /** + * The snapshot version this event brings us up to, or MIN if not set. + */ + snapshotVersion, + /** + * A map from target to changes to the target. See TargetChange. + */ + targetChanges, + /** + * A map of targets that is known to be inconsistent, and the purpose for + * re-listening. Listens for these targets should be re-established without + * resume tokens. + */ + targetMismatches, + /** + * A set of which documents have changed or been deleted, along with the + * doc's new values (if not deleted). + */ + documentUpdates, + /** + * A set of which document updates are due only to limbo resolution targets. + */ + resolvedLimboDocuments) { + this.snapshotVersion = snapshotVersion; + this.targetChanges = targetChanges; + this.targetMismatches = targetMismatches; + this.documentUpdates = documentUpdates; + this.resolvedLimboDocuments = resolvedLimboDocuments; + } + /** + * HACK: Views require RemoteEvents in order to determine whether the view is + * CURRENT, but secondary tabs don't receive remote events. So this method is + * used to create a synthesized RemoteEvent that can be used to apply a + * CURRENT status change to a View, for queries executed in a different tab. + */ + // PORTING NOTE: Multi-tab only + static createSynthesizedRemoteEventForCurrentChange(targetId, current, resumeToken) { + const targetChanges = new Map(); + targetChanges.set(targetId, TargetChange.createSynthesizedTargetChangeForCurrentChange(targetId, current, resumeToken)); + return new RemoteEvent(SnapshotVersion.min(), targetChanges, new SortedMap(primitiveComparator), mutableDocumentMap(), documentKeySet()); + } +} +/** + * A TargetChange specifies the set of changes for a specific target as part of + * a RemoteEvent. These changes track which documents are added, modified or + * removed, as well as the target's resume token and whether the target is + * marked CURRENT. + * The actual changes *to* documents are not part of the TargetChange since + * documents may be part of multiple targets. + */ +class TargetChange { + constructor( + /** + * An opaque, server-assigned token that allows watching a query to be resumed + * after disconnecting without retransmitting all the data that matches the + * query. The resume token essentially identifies a point in time from which + * the server should resume sending results. + */ + resumeToken, + /** + * The "current" (synced) status of this target. Note that "current" + * has special meaning in the RPC protocol that implies that a target is + * both up-to-date and consistent with the rest of the watch stream. + */ + current, + /** + * The set of documents that were newly assigned to this target as part of + * this remote event. + */ + addedDocuments, + /** + * The set of documents that were already assigned to this target but received + * an update during this remote event. + */ + modifiedDocuments, + /** + * The set of documents that were removed from this target as part of this + * remote event. + */ + removedDocuments) { + this.resumeToken = resumeToken; + this.current = current; + this.addedDocuments = addedDocuments; + this.modifiedDocuments = modifiedDocuments; + this.removedDocuments = removedDocuments; + } + /** + * This method is used to create a synthesized TargetChanges that can be used to + * apply a CURRENT status change to a View (for queries executed in a different + * tab) or for new queries (to raise snapshots with correct CURRENT status). + */ + static createSynthesizedTargetChangeForCurrentChange(targetId, current, resumeToken) { + return new TargetChange(resumeToken, current, documentKeySet(), documentKeySet(), documentKeySet()); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a changed document and a list of target ids to which this change + * applies. + * + * If document has been deleted NoDocument will be provided. + */ +class DocumentWatchChange { + constructor( + /** The new document applies to all of these targets. */ + updatedTargetIds, + /** The new document is removed from all of these targets. */ + removedTargetIds, + /** The key of the document for this change. */ + key, + /** + * The new document or NoDocument if it was deleted. Is null if the + * document went out of view without the server sending a new document. + */ + newDoc) { + this.updatedTargetIds = updatedTargetIds; + this.removedTargetIds = removedTargetIds; + this.key = key; + this.newDoc = newDoc; + } +} +class ExistenceFilterChange { + constructor(targetId, existenceFilter) { + this.targetId = targetId; + this.existenceFilter = existenceFilter; + } +} +class WatchTargetChange { + constructor( + /** What kind of change occurred to the watch target. */ + state, + /** The target IDs that were added/removed/set. */ + targetIds, + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + resumeToken = ByteString.EMPTY_BYTE_STRING, + /** An RPC error indicating why the watch failed. */ + cause = null) { + this.state = state; + this.targetIds = targetIds; + this.resumeToken = resumeToken; + this.cause = cause; + } +} +/** Tracks the internal state of a Watch target. */ +class TargetState { + constructor() { + /** + * The number of pending responses (adds or removes) that we are waiting on. + * We only consider targets active that have no pending responses. + */ + this.pendingResponses = 0; + /** + * Keeps track of the document changes since the last raised snapshot. + * + * These changes are continuously updated as we receive document updates and + * always reflect the current set of changes against the last issued snapshot. + */ + this.documentChanges = snapshotChangesMap(); + /** See public getters for explanations of these fields. */ + this._resumeToken = ByteString.EMPTY_BYTE_STRING; + this._current = false; + /** + * Whether this target state should be included in the next snapshot. We + * initialize to true so that newly-added targets are included in the next + * RemoteEvent. + */ + this._hasPendingChanges = true; + } + /** + * Whether this target has been marked 'current'. + * + * 'Current' has special meaning in the RPC protocol: It implies that the + * Watch backend has sent us all changes up to the point at which the target + * was added and that the target is consistent with the rest of the watch + * stream. + */ + get current() { + return this._current; + } + /** The last resume token sent to us for this target. */ + get resumeToken() { + return this._resumeToken; + } + /** Whether this target has pending target adds or target removes. */ + get isPending() { + return this.pendingResponses !== 0; + } + /** Whether we have modified any state that should trigger a snapshot. */ + get hasPendingChanges() { + return this._hasPendingChanges; + } + /** + * Applies the resume token to the TargetChange, but only when it has a new + * value. Empty resumeTokens are discarded. + */ + updateResumeToken(resumeToken) { + if (resumeToken.approximateByteSize() > 0) { + this._hasPendingChanges = true; + this._resumeToken = resumeToken; + } + } + /** + * Creates a target change from the current set of changes. + * + * To reset the document changes after raising this snapshot, call + * `clearPendingChanges()`. + */ + toTargetChange() { + let addedDocuments = documentKeySet(); + let modifiedDocuments = documentKeySet(); + let removedDocuments = documentKeySet(); + this.documentChanges.forEach((key, changeType) => { + switch (changeType) { + case 0 /* ChangeType.Added */: + addedDocuments = addedDocuments.add(key); + break; + case 2 /* ChangeType.Modified */: + modifiedDocuments = modifiedDocuments.add(key); + break; + case 1 /* ChangeType.Removed */: + removedDocuments = removedDocuments.add(key); + break; + default: + fail(0x9481, { changeType }); + } + }); + return new TargetChange(this._resumeToken, this._current, addedDocuments, modifiedDocuments, removedDocuments); + } + /** + * Resets the document changes and sets `hasPendingChanges` to false. + */ + clearPendingChanges() { + this._hasPendingChanges = false; + this.documentChanges = snapshotChangesMap(); + } + addDocumentChange(key, changeType) { + this._hasPendingChanges = true; + this.documentChanges = this.documentChanges.insert(key, changeType); + } + removeDocumentChange(key) { + this._hasPendingChanges = true; + this.documentChanges = this.documentChanges.remove(key); + } + recordPendingTargetRequest() { + this.pendingResponses += 1; + } + recordTargetResponse() { + this.pendingResponses -= 1; + hardAssert(this.pendingResponses >= 0, 0x0ca9, { pendingResponses: this.pendingResponses }); + } + markCurrent() { + this._hasPendingChanges = true; + this._current = true; + } +} +const LOG_TAG$g = 'WatchChangeAggregator'; +/** + * A helper class to accumulate watch changes into a RemoteEvent. + */ +class WatchChangeAggregator { + constructor(metadataProvider) { + this.metadataProvider = metadataProvider; + /** The internal state of all tracked targets. */ + this.targetStates = new Map(); + /** Keeps track of the documents to update since the last raised snapshot. */ + this.pendingDocumentUpdates = mutableDocumentMap(); + this.pendingDocumentUpdatesByTarget = documentTargetMap(); + /** A mapping of document keys to their set of target IDs. */ + this.pendingDocumentTargetMapping = documentTargetMap(); + /** + * A map of targets with existence filter mismatches. These targets are + * known to be inconsistent and their listens needs to be re-established by + * RemoteStore. + */ + this.pendingTargetResets = new SortedMap(primitiveComparator); + } + /** + * Processes and adds the DocumentWatchChange to the current set of changes. + */ + handleDocumentChange(docChange) { + for (const targetId of docChange.updatedTargetIds) { + if (docChange.newDoc && docChange.newDoc.isFoundDocument()) { + this.addDocumentToTarget(targetId, docChange.newDoc); + } + else { + this.removeDocumentFromTarget(targetId, docChange.key, docChange.newDoc); + } + } + for (const targetId of docChange.removedTargetIds) { + this.removeDocumentFromTarget(targetId, docChange.key, docChange.newDoc); + } + } + /** Processes and adds the WatchTargetChange to the current set of changes. */ + handleTargetChange(targetChange) { + this.forEachTarget(targetChange, targetId => { + const targetState = this.ensureTargetState(targetId); + switch (targetChange.state) { + case 0 /* WatchTargetChangeState.NoChange */: + if (this.isActiveTarget(targetId)) { + targetState.updateResumeToken(targetChange.resumeToken); + } + break; + case 1 /* WatchTargetChangeState.Added */: + // We need to decrement the number of pending acks needed from watch + // for this targetId. + targetState.recordTargetResponse(); + if (!targetState.isPending) { + // We have a freshly added target, so we need to reset any state + // that we had previously. This can happen e.g. when remove and add + // back a target for existence filter mismatches. + targetState.clearPendingChanges(); + } + targetState.updateResumeToken(targetChange.resumeToken); + break; + case 2 /* WatchTargetChangeState.Removed */: + // We need to keep track of removed targets to we can post-filter and + // remove any target changes. + // We need to decrement the number of pending acks needed from watch + // for this targetId. + targetState.recordTargetResponse(); + if (!targetState.isPending) { + this.removeTarget(targetId); + } + break; + case 3 /* WatchTargetChangeState.Current */: + if (this.isActiveTarget(targetId)) { + targetState.markCurrent(); + targetState.updateResumeToken(targetChange.resumeToken); + } + break; + case 4 /* WatchTargetChangeState.Reset */: + if (this.isActiveTarget(targetId)) { + // Reset the target and synthesizes removes for all existing + // documents. The backend will re-add any documents that still + // match the target before it sends the next global snapshot. + this.resetTarget(targetId); + targetState.updateResumeToken(targetChange.resumeToken); + } + break; + default: + fail(0xddd6, { + state: targetChange.state + }); + } + }); + } + /** + * Iterates over all targetIds that the watch change applies to: either the + * targetIds explicitly listed in the change or the targetIds of all currently + * active targets. + */ + forEachTarget(targetChange, fn) { + if (targetChange.targetIds.length > 0) { + targetChange.targetIds.forEach(fn); + } + else { + this.targetStates.forEach((_, targetId) => { + if (this.isActiveTarget(targetId)) { + fn(targetId); + } + }); + } + } + /** + * Handles existence filters and synthesizes deletes for filter mismatches. + * Targets that are invalidated by filter mismatches are added to + * `pendingTargetResets`. + */ + handleExistenceFilter(watchChange) { + const targetId = watchChange.targetId; + const expectedCount = watchChange.existenceFilter.count; + const targetData = this.targetDataForActiveTarget(targetId); + if (targetData) { + const target = targetData.target; + if (targetIsDocumentTarget(target)) { + if (expectedCount === 0) { + // The existence filter told us the document does not exist. We deduce + // that this document does not exist and apply a deleted document to + // our updates. Without applying this deleted document there might be + // another query that will raise this document as part of a snapshot + // until it is resolved, essentially exposing inconsistency between + // queries. + const key = new DocumentKey(target.path); + this.removeDocumentFromTarget(targetId, key, MutableDocument.newNoDocument(key, SnapshotVersion.min())); + } + else { + hardAssert(expectedCount === 1, 0x4e2d, { expectedCount }); + } + } + else { + const currentSize = this.getCurrentDocumentCountForTarget(targetId); + // Existence filter mismatch. Mark the documents as being in limbo, and + // raise a snapshot with `isFromCache:true`. + if (currentSize !== expectedCount) { + // Apply bloom filter to identify and mark removed documents. + const bloomFilter = this.parseBloomFilter(watchChange); + const status = bloomFilter + ? this.applyBloomFilter(bloomFilter, watchChange, currentSize) + : 1 /* BloomFilterApplicationStatus.Skipped */; + if (status !== 0 /* BloomFilterApplicationStatus.Success */) { + // If bloom filter application fails, we reset the mapping and + // trigger re-run of the query. + this.resetTarget(targetId); + const purpose = status === 2 /* BloomFilterApplicationStatus.FalsePositive */ + ? "TargetPurposeExistenceFilterMismatchBloom" /* TargetPurpose.ExistenceFilterMismatchBloom */ + : "TargetPurposeExistenceFilterMismatch" /* TargetPurpose.ExistenceFilterMismatch */; + this.pendingTargetResets = this.pendingTargetResets.insert(targetId, purpose); + } + testingHooksSpi?.notifyOnExistenceFilterMismatch(createExistenceFilterMismatchInfoForTestingHooks(currentSize, watchChange.existenceFilter, this.metadataProvider.getDatabaseId(), bloomFilter, status)); + } + } + } + } + /** + * Parse the bloom filter from the "unchanged_names" field of an existence + * filter. + */ + parseBloomFilter(watchChange) { + const unchangedNames = watchChange.existenceFilter.unchangedNames; + if (!unchangedNames || !unchangedNames.bits) { + return null; + } + const { bits: { bitmap = '', padding = 0 }, hashCount = 0 } = unchangedNames; + let normalizedBitmap; + try { + normalizedBitmap = normalizeByteString(bitmap).toUint8Array(); + } + catch (err) { + if (err instanceof Base64DecodeError) { + logWarn('Decoding the base64 bloom filter in existence filter failed (' + + err.message + + '); ignoring the bloom filter and falling back to full re-query.'); + return null; + } + else { + throw err; + } + } + let bloomFilter; + try { + // BloomFilter throws error if the inputs are invalid. + bloomFilter = new BloomFilter(normalizedBitmap, padding, hashCount); + } + catch (err) { + if (err instanceof BloomFilterError) { + logWarn('BloomFilter error: ', err); + } + else { + logWarn('Applying bloom filter failed: ', err); + } + return null; + } + if (bloomFilter.bitCount === 0) { + return null; + } + return bloomFilter; + } + /** + * Apply bloom filter to remove the deleted documents, and return the + * application status. + */ + applyBloomFilter(bloomFilter, watchChange, currentCount) { + const expectedCount = watchChange.existenceFilter.count; + const removedDocumentCount = this.filterRemovedDocuments(bloomFilter, watchChange.targetId); + return expectedCount === currentCount - removedDocumentCount + ? 0 /* BloomFilterApplicationStatus.Success */ + : 2 /* BloomFilterApplicationStatus.FalsePositive */; + } + /** + * Filter out removed documents based on bloom filter membership result and + * return number of documents removed. + */ + filterRemovedDocuments(bloomFilter, targetId) { + const existingKeys = this.metadataProvider.getRemoteKeysForTarget(targetId); + let removalCount = 0; + existingKeys.forEach(key => { + const databaseId = this.metadataProvider.getDatabaseId(); + const documentPath = `projects/${databaseId.projectId}` + + `/databases/${databaseId.database}` + + `/documents/${key.path.canonicalString()}`; + if (!bloomFilter.mightContain(documentPath)) { + this.removeDocumentFromTarget(targetId, key, /*updatedDocument=*/ null); + removalCount++; + } + }); + return removalCount; + } + /** + * Converts the currently accumulated state into a remote event at the + * provided snapshot version. Resets the accumulated changes before returning. + */ + createRemoteEvent(snapshotVersion) { + const targetChanges = new Map(); + this.targetStates.forEach((targetState, targetId) => { + const targetData = this.targetDataForActiveTarget(targetId); + if (targetData) { + if (targetState.current && targetIsDocumentTarget(targetData.target)) { + // Document queries for document that don't exist can produce an empty + // result set. To update our local cache, we synthesize a document + // delete if we have not previously received the document for this + // target. This resolves the limbo state of the document, removing it + // from limboDocumentRefs. + // + // TODO(dimond): Ideally we would have an explicit lookup target + // instead resulting in an explicit delete message and we could + // remove this special logic. + const key = new DocumentKey(targetData.target.path); + if (!this.ensureDocumentUpdateByTarget(key).has(targetId) && + !this.targetContainsDocument(targetId, key)) { + this.removeDocumentFromTarget(targetId, key, MutableDocument.newNoDocument(key, snapshotVersion)); + } + } + if (targetState.hasPendingChanges) { + targetChanges.set(targetId, targetState.toTargetChange()); + targetState.clearPendingChanges(); + } + } + }); + let resolvedLimboDocuments = documentKeySet(); + // We extract the set of limbo-only document updates as the GC logic + // special-cases documents that do not appear in the target cache. + // + // TODO(gsoltis): Expand on this comment once GC is available in the JS + // client. + this.pendingDocumentTargetMapping.forEach((key, targets) => { + let isOnlyLimboTarget = true; + targets.forEachWhile(targetId => { + const targetData = this.targetDataForActiveTarget(targetId); + if (targetData && + targetData.purpose !== "TargetPurposeLimboResolution" /* TargetPurpose.LimboResolution */) { + isOnlyLimboTarget = false; + return false; + } + return true; + }); + if (isOnlyLimboTarget) { + resolvedLimboDocuments = resolvedLimboDocuments.add(key); + } + }); + this.pendingDocumentUpdates.forEach((_, doc) => doc.setReadTime(snapshotVersion)); + const remoteEvent = new RemoteEvent(snapshotVersion, targetChanges, this.pendingTargetResets, this.pendingDocumentUpdates, resolvedLimboDocuments); + this.pendingDocumentUpdates = mutableDocumentMap(); + this.pendingDocumentUpdatesByTarget = documentTargetMap(); + this.pendingDocumentTargetMapping = documentTargetMap(); + this.pendingTargetResets = new SortedMap(primitiveComparator); + return remoteEvent; + } + /** + * Adds the provided document to the internal list of document updates and + * its document key to the given target's mapping. + */ + // Visible for testing. + addDocumentToTarget(targetId, document) { + if (!this.isActiveTarget(targetId)) { + return; + } + const changeType = this.targetContainsDocument(targetId, document.key) + ? 2 /* ChangeType.Modified */ + : 0 /* ChangeType.Added */; + const targetState = this.ensureTargetState(targetId); + targetState.addDocumentChange(document.key, changeType); + this.pendingDocumentUpdates = this.pendingDocumentUpdates.insert(document.key, document); + this.pendingDocumentUpdatesByTarget = + this.pendingDocumentUpdatesByTarget.insert(document.key, this.ensureDocumentUpdateByTarget(document.key).add(targetId)); + this.pendingDocumentTargetMapping = + this.pendingDocumentTargetMapping.insert(document.key, this.ensureDocumentTargetMapping(document.key).add(targetId)); + } + /** + * Removes the provided document from the target mapping. If the + * document no longer matches the target, but the document's state is still + * known (e.g. we know that the document was deleted or we received the change + * that caused the filter mismatch), the new document can be provided + * to update the remote document cache. + */ + // Visible for testing. + removeDocumentFromTarget(targetId, key, updatedDocument) { + if (!this.isActiveTarget(targetId)) { + return; + } + const targetState = this.ensureTargetState(targetId); + if (this.targetContainsDocument(targetId, key)) { + targetState.addDocumentChange(key, 1 /* ChangeType.Removed */); + } + else { + // The document may have entered and left the target before we raised a + // snapshot, so we can just ignore the change. + targetState.removeDocumentChange(key); + } + this.pendingDocumentTargetMapping = + this.pendingDocumentTargetMapping.insert(key, this.ensureDocumentTargetMapping(key).delete(targetId)); + this.pendingDocumentTargetMapping = + this.pendingDocumentTargetMapping.insert(key, this.ensureDocumentTargetMapping(key).add(targetId)); + if (updatedDocument) { + this.pendingDocumentUpdates = this.pendingDocumentUpdates.insert(key, updatedDocument); + } + } + removeTarget(targetId) { + this.targetStates.delete(targetId); + } + /** + * Returns the current count of documents in the target. This includes both + * the number of documents that the LocalStore considers to be part of the + * target as well as any accumulated changes. + */ + getCurrentDocumentCountForTarget(targetId) { + const targetState = this.ensureTargetState(targetId); + const targetChange = targetState.toTargetChange(); + return (this.metadataProvider.getRemoteKeysForTarget(targetId).size + + targetChange.addedDocuments.size - + targetChange.removedDocuments.size); + } + /** + * Increment the number of acks needed from watch before we can consider the + * server to be 'in-sync' with the client's active targets. + */ + recordPendingTargetRequest(targetId) { + // For each request we get we need to record we need a response for it. + const targetState = this.ensureTargetState(targetId); + targetState.recordPendingTargetRequest(); + } + ensureTargetState(targetId) { + let result = this.targetStates.get(targetId); + if (!result) { + result = new TargetState(); + this.targetStates.set(targetId, result); + } + return result; + } + ensureDocumentTargetMapping(key) { + let targetMapping = this.pendingDocumentTargetMapping.get(key); + if (!targetMapping) { + targetMapping = new SortedSet(primitiveComparator); + this.pendingDocumentTargetMapping = + this.pendingDocumentTargetMapping.insert(key, targetMapping); + } + return targetMapping; + } + ensureDocumentUpdateByTarget(key) { + let targetMapping = this.pendingDocumentUpdatesByTarget.get(key); + if (!targetMapping) { + targetMapping = new SortedSet(primitiveComparator); + this.pendingDocumentUpdatesByTarget = + this.pendingDocumentUpdatesByTarget.insert(key, targetMapping); + } + return targetMapping; + } + /** + * Verifies that the user is still interested in this target (by calling + * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs + * from watch. + */ + isActiveTarget(targetId) { + const targetActive = this.targetDataForActiveTarget(targetId) !== null; + if (!targetActive) { + logDebug(LOG_TAG$g, 'Detected inactive target', targetId); + } + return targetActive; + } + /** + * Returns the TargetData for an active target (i.e. a target that the user + * is still interested in that has no outstanding target change requests). + */ + targetDataForActiveTarget(targetId) { + const targetState = this.targetStates.get(targetId); + return targetState && targetState.isPending + ? null + : this.metadataProvider.getTargetDataForTarget(targetId); + } + /** + * Resets the state of a Watch target to its initial state (e.g. sets + * 'current' to false, clears the resume token and removes its target mapping + * from all documents). + */ + resetTarget(targetId) { + this.targetStates.set(targetId, new TargetState()); + // Trigger removal for any documents currently mapped to this target. + // These removals will be part of the initial snapshot if Watch does not + // resend these documents. + const existingKeys = this.metadataProvider.getRemoteKeysForTarget(targetId); + existingKeys.forEach(key => { + this.removeDocumentFromTarget(targetId, key, /*updatedDocument=*/ null); + }); + } + /** + * Returns whether the LocalStore considers the document to be part of the + * specified target. + */ + targetContainsDocument(targetId, key) { + const existingKeys = this.metadataProvider.getRemoteKeysForTarget(targetId); + return existingKeys.has(key); + } +} +function documentTargetMap() { + return new SortedMap(DocumentKey.comparator); +} +function snapshotChangesMap() { + return new SortedMap(DocumentKey.comparator); +} +function createExistenceFilterMismatchInfoForTestingHooks(localCacheCount, existenceFilter, databaseId, bloomFilter, bloomFilterStatus) { + const result = { + localCacheCount, + existenceFilterCount: existenceFilter.count, + databaseId: databaseId.database, + projectId: databaseId.projectId + }; + const unchangedNames = existenceFilter.unchangedNames; + if (unchangedNames) { + result.bloomFilter = { + applied: bloomFilterStatus === 0 /* BloomFilterApplicationStatus.Success */, + hashCount: unchangedNames?.hashCount ?? 0, + bitmapLength: unchangedNames?.bits?.bitmap?.length ?? 0, + padding: unchangedNames?.bits?.padding ?? 0, + mightContain: (value) => bloomFilter?.mightContain(value) ?? false + }; + } + return result; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const DIRECTIONS = (() => { + const dirs = {}; + dirs["asc" /* Direction.ASCENDING */] = 'ASCENDING'; + dirs["desc" /* Direction.DESCENDING */] = 'DESCENDING'; + return dirs; +})(); +const OPERATORS = (() => { + const ops = {}; + ops["<" /* Operator.LESS_THAN */] = 'LESS_THAN'; + ops["<=" /* Operator.LESS_THAN_OR_EQUAL */] = 'LESS_THAN_OR_EQUAL'; + ops[">" /* Operator.GREATER_THAN */] = 'GREATER_THAN'; + ops[">=" /* Operator.GREATER_THAN_OR_EQUAL */] = 'GREATER_THAN_OR_EQUAL'; + ops["==" /* Operator.EQUAL */] = 'EQUAL'; + ops["!=" /* Operator.NOT_EQUAL */] = 'NOT_EQUAL'; + ops["array-contains" /* Operator.ARRAY_CONTAINS */] = 'ARRAY_CONTAINS'; + ops["in" /* Operator.IN */] = 'IN'; + ops["not-in" /* Operator.NOT_IN */] = 'NOT_IN'; + ops["array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */] = 'ARRAY_CONTAINS_ANY'; + return ops; +})(); +const COMPOSITE_OPERATORS = (() => { + const ops = {}; + ops["and" /* CompositeOperator.AND */] = 'AND'; + ops["or" /* CompositeOperator.OR */] = 'OR'; + return ops; +})(); +function assertPresent(value, description) { +} +/** + * This class generates JsonObject values for the Datastore API suitable for + * sending to either GRPC stub methods or via the JSON/HTTP REST API. + * + * The serializer supports both Protobuf.js and Proto3 JSON formats. By + * setting `useProto3Json` to true, the serializer will use the Proto3 JSON + * format. + * + * For a description of the Proto3 JSON format check + * https://developers.google.com/protocol-buffers/docs/proto3#json + * + * TODO(klimt): We can remove the databaseId argument if we keep the full + * resource name in documents. + */ +class JsonProtoSerializer { + constructor(databaseId, useProto3Json) { + this.databaseId = databaseId; + this.useProto3Json = useProto3Json; + } +} +function fromRpcStatus(status) { + const code = status.code === undefined ? Code.UNKNOWN : mapCodeFromRpcCode(status.code); + return new FirestoreError(code, status.message || ''); +} +/** + * Returns a value for a number (or null) that's appropriate to put into + * a google.protobuf.Int32Value proto. + * DO NOT USE THIS FOR ANYTHING ELSE. + * This method cheats. It's typed as returning "number" because that's what + * our generated proto interfaces say Int32Value must be. But GRPC actually + * expects a { value: } struct. + */ +function toInt32Proto(serializer, val) { + if (serializer.useProto3Json || isNullOrUndefined(val)) { + return val; + } + else { + return { value: val }; + } +} +/** + * Returns a number (or null) from a google.protobuf.Int32Value proto. + */ +function fromInt32Proto(val) { + let result; + if (typeof val === 'object') { + result = val.value; + } + else { + result = val; + } + return isNullOrUndefined(result) ? null : result; +} +/** + * Returns a value for a Date that's appropriate to put into a proto. + */ +function toTimestamp(serializer, timestamp) { + if (serializer.useProto3Json) { + // Serialize to ISO-8601 date format, but with full nano resolution. + // Since JS Date has only millis, let's only use it for the seconds and + // then manually add the fractions to the end. + const jsDateStr = new Date(timestamp.seconds * 1000).toISOString(); + // Remove .xxx frac part and Z in the end. + const strUntilSeconds = jsDateStr.replace(/\.\d*/, '').replace('Z', ''); + // Pad the fraction out to 9 digits (nanos). + const nanoStr = ('000000000' + timestamp.nanoseconds).slice(-9); + return `${strUntilSeconds}.${nanoStr}Z`; + } + else { + return { + seconds: '' + timestamp.seconds, + nanos: timestamp.nanoseconds + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }; + } +} +/** + * Returns a Timestamp typed object given protobuf timestamp value. + */ +function fromTimestamp(date) { + const timestamp = normalizeTimestamp(date); + return new Timestamp(timestamp.seconds, timestamp.nanos); +} +/** + * Returns a value for bytes that's appropriate to put in a proto. + * + * Visible for testing. + */ +function toBytes(serializer, bytes) { + if (serializer.useProto3Json) { + return bytes.toBase64(); + } + else { + return bytes.toUint8Array(); + } +} +/** + * Returns a ByteString based on the proto string value. + */ +function fromBytes(serializer, value) { + if (serializer.useProto3Json) { + hardAssert(value === undefined || typeof value === 'string', 0xe30b); + return ByteString.fromBase64String(value ? value : ''); + } + else { + hardAssert(value === undefined || + // Check if the value is an instance of both Buffer and Uint8Array, + // despite the fact that Buffer extends Uint8Array. In some + // environments, such as jsdom, the prototype chain of Buffer + // does not indicate that it extends Uint8Array. + value instanceof Buffer || + value instanceof Uint8Array, 0x3f41); + return ByteString.fromUint8Array(value ? value : new Uint8Array()); + } +} +function toVersion(serializer, version) { + return toTimestamp(serializer, version.toTimestamp()); +} +function fromVersion(version) { + hardAssert(!!version, 0xc050); + return SnapshotVersion.fromTimestamp(fromTimestamp(version)); +} +function toResourceName(databaseId, path) { + return toResourcePath(databaseId, path).canonicalString(); +} +function toResourcePath(databaseId, path) { + const resourcePath = fullyQualifiedPrefixPath(databaseId).child('documents'); + return path === undefined ? resourcePath : resourcePath.child(path); +} +function fromResourceName(name) { + const resource = ResourcePath.fromString(name); + hardAssert(isValidResourceName(resource), 0x27ce, { key: resource.toString() }); + return resource; +} +function toName(serializer, key) { + return toResourceName(serializer.databaseId, key.path); +} +function fromName(serializer, name) { + const resource = fromResourceName(name); + if (resource.get(1) !== serializer.databaseId.projectId) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Tried to deserialize key from different project: ' + + resource.get(1) + + ' vs ' + + serializer.databaseId.projectId); + } + if (resource.get(3) !== serializer.databaseId.database) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Tried to deserialize key from different database: ' + + resource.get(3) + + ' vs ' + + serializer.databaseId.database); + } + return new DocumentKey(extractLocalPathFromResourceName(resource)); +} +function toQueryPath(serializer, path) { + return toResourceName(serializer.databaseId, path); +} +function fromQueryPath(name) { + const resourceName = fromResourceName(name); + // In v1beta1 queries for collections at the root did not have a trailing + // "/documents". In v1 all resource paths contain "/documents". Preserve the + // ability to read the v1beta1 form for compatibility with queries persisted + // in the local target cache. + if (resourceName.length === 4) { + return ResourcePath.emptyPath(); + } + return extractLocalPathFromResourceName(resourceName); +} +function getEncodedDatabaseId(serializer) { + const path = new ResourcePath([ + 'projects', + serializer.databaseId.projectId, + 'databases', + serializer.databaseId.database + ]); + return path.canonicalString(); +} +function fullyQualifiedPrefixPath(databaseId) { + return new ResourcePath([ + 'projects', + databaseId.projectId, + 'databases', + databaseId.database + ]); +} +function extractLocalPathFromResourceName(resourceName) { + hardAssert(resourceName.length > 4 && resourceName.get(4) === 'documents', 0x71a3, { key: resourceName.toString() }); + return resourceName.popFirst(5); +} +/** Creates a Document proto from key and fields (but no create/update time) */ +function toMutationDocument(serializer, key, fields) { + return { + name: toName(serializer, key), + fields: fields.value.mapValue.fields + }; +} +function toDocument(serializer, document) { + return { + name: toName(serializer, document.key), + fields: document.data.value.mapValue.fields, + updateTime: toTimestamp(serializer, document.version.toTimestamp()), + createTime: toTimestamp(serializer, document.createTime.toTimestamp()) + }; +} +function fromDocument(serializer, document, hasCommittedMutations) { + const key = fromName(serializer, document.name); + const version = fromVersion(document.updateTime); + // If we read a document from persistence that is missing createTime, it's due + // to older SDK versions not storing this information. In such cases, we'll + // set the createTime to zero. This can be removed in the long term. + const createTime = document.createTime + ? fromVersion(document.createTime) + : SnapshotVersion.min(); + const data = new ObjectValue({ mapValue: { fields: document.fields } }); + const result = MutableDocument.newFoundDocument(key, version, createTime, data); + if (hasCommittedMutations) { + result.setHasCommittedMutations(); + } + return hasCommittedMutations ? result.setHasCommittedMutations() : result; +} +function fromFound(serializer, doc) { + hardAssert(!!doc.found, 0xaa33); + assertPresent(doc.found.name); + assertPresent(doc.found.updateTime); + const key = fromName(serializer, doc.found.name); + const version = fromVersion(doc.found.updateTime); + const createTime = doc.found.createTime + ? fromVersion(doc.found.createTime) + : SnapshotVersion.min(); + const data = new ObjectValue({ mapValue: { fields: doc.found.fields } }); + return MutableDocument.newFoundDocument(key, version, createTime, data); +} +function fromMissing(serializer, result) { + hardAssert(!!result.missing, 0x0f36); + hardAssert(!!result.readTime, 0x5995); + const key = fromName(serializer, result.missing); + const version = fromVersion(result.readTime); + return MutableDocument.newNoDocument(key, version); +} +function fromBatchGetDocumentsResponse(serializer, result) { + if ('found' in result) { + return fromFound(serializer, result); + } + else if ('missing' in result) { + return fromMissing(serializer, result); + } + return fail(0x1c42, { result }); +} +function fromWatchChange(serializer, change) { + let watchChange; + if ('targetChange' in change) { + assertPresent(change.targetChange); + // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE' + // if unset + const state = fromWatchTargetChangeState(change.targetChange.targetChangeType || 'NO_CHANGE'); + const targetIds = change.targetChange.targetIds || []; + const resumeToken = fromBytes(serializer, change.targetChange.resumeToken); + const causeProto = change.targetChange.cause; + const cause = causeProto && fromRpcStatus(causeProto); + watchChange = new WatchTargetChange(state, targetIds, resumeToken, cause || null); + } + else if ('documentChange' in change) { + assertPresent(change.documentChange); + const entityChange = change.documentChange; + assertPresent(entityChange.document); + assertPresent(entityChange.document.name); + assertPresent(entityChange.document.updateTime); + const key = fromName(serializer, entityChange.document.name); + const version = fromVersion(entityChange.document.updateTime); + const createTime = entityChange.document.createTime + ? fromVersion(entityChange.document.createTime) + : SnapshotVersion.min(); + const data = new ObjectValue({ + mapValue: { fields: entityChange.document.fields } + }); + const doc = MutableDocument.newFoundDocument(key, version, createTime, data); + const updatedTargetIds = entityChange.targetIds || []; + const removedTargetIds = entityChange.removedTargetIds || []; + watchChange = new DocumentWatchChange(updatedTargetIds, removedTargetIds, doc.key, doc); + } + else if ('documentDelete' in change) { + assertPresent(change.documentDelete); + const docDelete = change.documentDelete; + assertPresent(docDelete.document); + const key = fromName(serializer, docDelete.document); + const version = docDelete.readTime + ? fromVersion(docDelete.readTime) + : SnapshotVersion.min(); + const doc = MutableDocument.newNoDocument(key, version); + const removedTargetIds = docDelete.removedTargetIds || []; + watchChange = new DocumentWatchChange([], removedTargetIds, doc.key, doc); + } + else if ('documentRemove' in change) { + assertPresent(change.documentRemove); + const docRemove = change.documentRemove; + assertPresent(docRemove.document); + const key = fromName(serializer, docRemove.document); + const removedTargetIds = docRemove.removedTargetIds || []; + watchChange = new DocumentWatchChange([], removedTargetIds, key, null); + } + else if ('filter' in change) { + // TODO(dimond): implement existence filter parsing with strategy. + assertPresent(change.filter); + const filter = change.filter; + assertPresent(filter.targetId); + const { count = 0, unchangedNames } = filter; + const existenceFilter = new ExistenceFilter(count, unchangedNames); + const targetId = filter.targetId; + watchChange = new ExistenceFilterChange(targetId, existenceFilter); + } + else { + return fail(0x2d51, { change }); + } + return watchChange; +} +function fromWatchTargetChangeState(state) { + if (state === 'NO_CHANGE') { + return 0 /* WatchTargetChangeState.NoChange */; + } + else if (state === 'ADD') { + return 1 /* WatchTargetChangeState.Added */; + } + else if (state === 'REMOVE') { + return 2 /* WatchTargetChangeState.Removed */; + } + else if (state === 'CURRENT') { + return 3 /* WatchTargetChangeState.Current */; + } + else if (state === 'RESET') { + return 4 /* WatchTargetChangeState.Reset */; + } + else { + return fail(0x9991, { state }); + } +} +function versionFromListenResponse(change) { + // We have only reached a consistent snapshot for the entire stream if there + // is a read_time set and it applies to all targets (i.e. the list of + // targets is empty). The backend is guaranteed to send such responses. + if (!('targetChange' in change)) { + return SnapshotVersion.min(); + } + const targetChange = change.targetChange; + if (targetChange.targetIds && targetChange.targetIds.length) { + return SnapshotVersion.min(); + } + if (!targetChange.readTime) { + return SnapshotVersion.min(); + } + return fromVersion(targetChange.readTime); +} +function toMutation(serializer, mutation) { + let result; + if (mutation instanceof SetMutation) { + result = { + update: toMutationDocument(serializer, mutation.key, mutation.value) + }; + } + else if (mutation instanceof DeleteMutation) { + result = { delete: toName(serializer, mutation.key) }; + } + else if (mutation instanceof PatchMutation) { + result = { + update: toMutationDocument(serializer, mutation.key, mutation.data), + updateMask: toDocumentMask(mutation.fieldMask) + }; + } + else if (mutation instanceof VerifyMutation) { + result = { + verify: toName(serializer, mutation.key) + }; + } + else { + return fail(0x40d7, { + mutationType: mutation.type + }); + } + if (mutation.fieldTransforms.length > 0) { + result.updateTransforms = mutation.fieldTransforms.map(transform => toFieldTransform(serializer, transform)); + } + if (!mutation.precondition.isNone) { + result.currentDocument = toPrecondition(serializer, mutation.precondition); + } + return result; +} +function fromMutation(serializer, proto) { + const precondition = proto.currentDocument + ? fromPrecondition(proto.currentDocument) + : Precondition.none(); + const fieldTransforms = proto.updateTransforms + ? proto.updateTransforms.map(transform => fromFieldTransform(serializer, transform)) + : []; + if (proto.update) { + assertPresent(proto.update.name); + const key = fromName(serializer, proto.update.name); + const value = new ObjectValue({ + mapValue: { fields: proto.update.fields } + }); + if (proto.updateMask) { + const fieldMask = fromDocumentMask(proto.updateMask); + return new PatchMutation(key, value, fieldMask, precondition, fieldTransforms); + } + else { + return new SetMutation(key, value, precondition, fieldTransforms); + } + } + else if (proto.delete) { + const key = fromName(serializer, proto.delete); + return new DeleteMutation(key, precondition); + } + else if (proto.verify) { + const key = fromName(serializer, proto.verify); + return new VerifyMutation(key, precondition); + } + else { + return fail(0x05b7, { proto }); + } +} +function toPrecondition(serializer, precondition) { + if (precondition.updateTime !== undefined) { + return { + updateTime: toVersion(serializer, precondition.updateTime) + }; + } + else if (precondition.exists !== undefined) { + return { exists: precondition.exists }; + } + else { + return fail(0x6b69); + } +} +function fromPrecondition(precondition) { + if (precondition.updateTime !== undefined) { + return Precondition.updateTime(fromVersion(precondition.updateTime)); + } + else if (precondition.exists !== undefined) { + return Precondition.exists(precondition.exists); + } + else { + return Precondition.none(); + } +} +function fromWriteResult(proto, commitTime) { + // NOTE: Deletes don't have an updateTime. + let version = proto.updateTime + ? fromVersion(proto.updateTime) + : fromVersion(commitTime); + if (version.isEqual(SnapshotVersion.min())) { + // The Firestore Emulator currently returns an update time of 0 for + // deletes of non-existing documents (rather than null). This breaks the + // test "get deleted doc while offline with source=cache" as NoDocuments + // with version 0 are filtered by IndexedDb's RemoteDocumentCache. + // TODO(#2149): Remove this when Emulator is fixed + version = fromVersion(commitTime); + } + return new MutationResult(version, proto.transformResults || []); +} +function fromWriteResults(protos, commitTime) { + if (protos && protos.length > 0) { + hardAssert(commitTime !== undefined, 0x3811); + return protos.map(proto => fromWriteResult(proto, commitTime)); + } + else { + return []; + } +} +function toFieldTransform(serializer, fieldTransform) { + const transform = fieldTransform.transform; + if (transform instanceof ServerTimestampTransform) { + return { + fieldPath: fieldTransform.field.canonicalString(), + setToServerValue: 'REQUEST_TIME' + }; + } + else if (transform instanceof ArrayUnionTransformOperation) { + return { + fieldPath: fieldTransform.field.canonicalString(), + appendMissingElements: { + values: transform.elements + } + }; + } + else if (transform instanceof ArrayRemoveTransformOperation) { + return { + fieldPath: fieldTransform.field.canonicalString(), + removeAllFromArray: { + values: transform.elements + } + }; + } + else if (transform instanceof NumericIncrementTransformOperation) { + return { + fieldPath: fieldTransform.field.canonicalString(), + increment: transform.operand + }; + } + else { + throw fail(0x51c2, { + transform: fieldTransform.transform + }); + } +} +function fromFieldTransform(serializer, proto) { + let transform = null; + if ('setToServerValue' in proto) { + hardAssert(proto.setToServerValue === 'REQUEST_TIME', 0x40f6, { proto }); + transform = new ServerTimestampTransform(); + } + else if ('appendMissingElements' in proto) { + const values = proto.appendMissingElements.values || []; + transform = new ArrayUnionTransformOperation(values); + } + else if ('removeAllFromArray' in proto) { + const values = proto.removeAllFromArray.values || []; + transform = new ArrayRemoveTransformOperation(values); + } + else if ('increment' in proto) { + transform = new NumericIncrementTransformOperation(serializer, proto.increment); + } + else { + fail(0x40c8, { proto }); + } + const fieldPath = FieldPath$1.fromServerFormat(proto.fieldPath); + return new FieldTransform(fieldPath, transform); +} +function toDocumentsTarget(serializer, target) { + return { documents: [toQueryPath(serializer, target.path)] }; +} +function fromDocumentsTarget(documentsTarget) { + const count = documentsTarget.documents.length; + hardAssert(count === 1, 0x07ae, { + count + }); + const name = documentsTarget.documents[0]; + return queryToTarget(newQueryForPath(fromQueryPath(name))); +} +function toQueryTarget(serializer, target) { + // Dissect the path into parent, collectionId, and optional key filter. + const queryTarget = { structuredQuery: {} }; + const path = target.path; + let parent; + if (target.collectionGroup !== null) { + parent = path; + queryTarget.structuredQuery.from = [ + { + collectionId: target.collectionGroup, + allDescendants: true + } + ]; + } + else { + parent = path.popLast(); + queryTarget.structuredQuery.from = [{ collectionId: path.lastSegment() }]; + } + queryTarget.parent = toQueryPath(serializer, parent); + const where = toFilters(target.filters); + if (where) { + queryTarget.structuredQuery.where = where; + } + const orderBy = toOrder(target.orderBy); + if (orderBy) { + queryTarget.structuredQuery.orderBy = orderBy; + } + const limit = toInt32Proto(serializer, target.limit); + if (limit !== null) { + queryTarget.structuredQuery.limit = limit; + } + if (target.startAt) { + queryTarget.structuredQuery.startAt = toStartAtCursor(target.startAt); + } + if (target.endAt) { + queryTarget.structuredQuery.endAt = toEndAtCursor(target.endAt); + } + return { queryTarget, parent }; +} +function toRunAggregationQueryRequest(serializer, target, aggregates, skipAliasing) { + const { queryTarget, parent } = toQueryTarget(serializer, target); + const aliasMap = {}; + const aggregations = []; + let aggregationNum = 0; + aggregates.forEach(aggregate => { + // Map all client-side aliases to a unique short-form + // alias. This avoids issues with client-side aliases that + // exceed the 1500-byte string size limit. + const serverAlias = skipAliasing + ? aggregate.alias + : `aggregate_${aggregationNum++}`; + aliasMap[serverAlias] = aggregate.alias; + if (aggregate.aggregateType === 'count') { + aggregations.push({ + alias: serverAlias, + count: {} + }); + } + else if (aggregate.aggregateType === 'avg') { + aggregations.push({ + alias: serverAlias, + avg: { + field: toFieldPathReference(aggregate.fieldPath) + } + }); + } + else if (aggregate.aggregateType === 'sum') { + aggregations.push({ + alias: serverAlias, + sum: { + field: toFieldPathReference(aggregate.fieldPath) + } + }); + } + }); + return { + request: { + structuredAggregationQuery: { + aggregations, + structuredQuery: queryTarget.structuredQuery + }, + parent: queryTarget.parent + }, + aliasMap, + parent + }; +} +function convertQueryTargetToQuery(target) { + let path = fromQueryPath(target.parent); + const query = target.structuredQuery; + const fromCount = query.from ? query.from.length : 0; + let collectionGroup = null; + if (fromCount > 0) { + hardAssert(fromCount === 1, 0xfe26); + const from = query.from[0]; + if (from.allDescendants) { + collectionGroup = from.collectionId; + } + else { + path = path.child(from.collectionId); + } + } + let filterBy = []; + if (query.where) { + filterBy = fromFilters(query.where); + } + let orderBy = []; + if (query.orderBy) { + orderBy = fromOrder(query.orderBy); + } + let limit = null; + if (query.limit) { + limit = fromInt32Proto(query.limit); + } + let startAt = null; + if (query.startAt) { + startAt = fromStartAtCursor(query.startAt); + } + let endAt = null; + if (query.endAt) { + endAt = fromEndAtCursor(query.endAt); + } + return newQuery(path, collectionGroup, orderBy, filterBy, limit, "F" /* LimitType.First */, startAt, endAt); +} +function fromQueryTarget(target) { + return queryToTarget(convertQueryTargetToQuery(target)); +} +function toListenRequestLabels(serializer, targetData) { + const value = toLabel(targetData.purpose); + if (value == null) { + return null; + } + else { + return { + 'goog-listen-tags': value + }; + } +} +function toLabel(purpose) { + switch (purpose) { + case "TargetPurposeListen" /* TargetPurpose.Listen */: + return null; + case "TargetPurposeExistenceFilterMismatch" /* TargetPurpose.ExistenceFilterMismatch */: + return 'existence-filter-mismatch'; + case "TargetPurposeExistenceFilterMismatchBloom" /* TargetPurpose.ExistenceFilterMismatchBloom */: + return 'existence-filter-mismatch-bloom'; + case "TargetPurposeLimboResolution" /* TargetPurpose.LimboResolution */: + return 'limbo-document'; + default: + return fail(0x713b, { purpose }); + } +} +function toTarget(serializer, targetData) { + let result; + const target = targetData.target; + if (targetIsDocumentTarget(target)) { + result = { documents: toDocumentsTarget(serializer, target) }; + } + else { + result = { query: toQueryTarget(serializer, target).queryTarget }; + } + result.targetId = targetData.targetId; + if (targetData.resumeToken.approximateByteSize() > 0) { + result.resumeToken = toBytes(serializer, targetData.resumeToken); + const expectedCount = toInt32Proto(serializer, targetData.expectedCount); + if (expectedCount !== null) { + result.expectedCount = expectedCount; + } + } + else if (targetData.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) { + // TODO(wuandy): Consider removing above check because it is most likely true. + // Right now, many tests depend on this behaviour though (leaving min() out + // of serialization). + result.readTime = toTimestamp(serializer, targetData.snapshotVersion.toTimestamp()); + const expectedCount = toInt32Proto(serializer, targetData.expectedCount); + if (expectedCount !== null) { + result.expectedCount = expectedCount; + } + } + return result; +} +function toFilters(filters) { + if (filters.length === 0) { + return; + } + return toFilter(CompositeFilter.create(filters, "and" /* CompositeOperator.AND */)); +} +function fromFilters(filter) { + const result = fromFilter(filter); + if (result instanceof CompositeFilter && + compositeFilterIsFlatConjunction(result)) { + return result.getFilters(); + } + return [result]; +} +function fromFilter(filter) { + if (filter.unaryFilter !== undefined) { + return fromUnaryFilter(filter); + } + else if (filter.fieldFilter !== undefined) { + return fromFieldFilter(filter); + } + else if (filter.compositeFilter !== undefined) { + return fromCompositeFilter(filter); + } + else { + return fail(0x7591, { filter }); + } +} +function toOrder(orderBys) { + if (orderBys.length === 0) { + return; + } + return orderBys.map(order => toPropertyOrder(order)); +} +function fromOrder(orderBys) { + return orderBys.map(order => fromPropertyOrder(order)); +} +function toStartAtCursor(cursor) { + return { + before: cursor.inclusive, + values: cursor.position + }; +} +function toEndAtCursor(cursor) { + return { + before: !cursor.inclusive, + values: cursor.position + }; +} +function fromStartAtCursor(cursor) { + const inclusive = !!cursor.before; + const position = cursor.values || []; + return new Bound(position, inclusive); +} +function fromEndAtCursor(cursor) { + const inclusive = !cursor.before; + const position = cursor.values || []; + return new Bound(position, inclusive); +} +// visible for testing +function toDirection(dir) { + return DIRECTIONS[dir]; +} +// visible for testing +function fromDirection(dir) { + switch (dir) { + case 'ASCENDING': + return "asc" /* Direction.ASCENDING */; + case 'DESCENDING': + return "desc" /* Direction.DESCENDING */; + default: + return undefined; + } +} +// visible for testing +function toOperatorName(op) { + return OPERATORS[op]; +} +function toCompositeOperatorName(op) { + return COMPOSITE_OPERATORS[op]; +} +function fromOperatorName(op) { + switch (op) { + case 'EQUAL': + return "==" /* Operator.EQUAL */; + case 'NOT_EQUAL': + return "!=" /* Operator.NOT_EQUAL */; + case 'GREATER_THAN': + return ">" /* Operator.GREATER_THAN */; + case 'GREATER_THAN_OR_EQUAL': + return ">=" /* Operator.GREATER_THAN_OR_EQUAL */; + case 'LESS_THAN': + return "<" /* Operator.LESS_THAN */; + case 'LESS_THAN_OR_EQUAL': + return "<=" /* Operator.LESS_THAN_OR_EQUAL */; + case 'ARRAY_CONTAINS': + return "array-contains" /* Operator.ARRAY_CONTAINS */; + case 'IN': + return "in" /* Operator.IN */; + case 'NOT_IN': + return "not-in" /* Operator.NOT_IN */; + case 'ARRAY_CONTAINS_ANY': + return "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */; + case 'OPERATOR_UNSPECIFIED': + return fail(0xe2fe); + default: + return fail(0xc54a); + } +} +function fromCompositeOperatorName(op) { + switch (op) { + case 'AND': + return "and" /* CompositeOperator.AND */; + case 'OR': + return "or" /* CompositeOperator.OR */; + default: + return fail(0x0402); + } +} +function toFieldPathReference(path) { + return { fieldPath: path.canonicalString() }; +} +function fromFieldPathReference(fieldReference) { + return FieldPath$1.fromServerFormat(fieldReference.fieldPath); +} +// visible for testing +function toPropertyOrder(orderBy) { + return { + field: toFieldPathReference(orderBy.field), + direction: toDirection(orderBy.dir) + }; +} +function fromPropertyOrder(orderBy) { + return new OrderBy(fromFieldPathReference(orderBy.field), fromDirection(orderBy.direction)); +} +// visible for testing +function toFilter(filter) { + if (filter instanceof FieldFilter) { + return toUnaryOrFieldFilter(filter); + } + else if (filter instanceof CompositeFilter) { + return toCompositeFilter(filter); + } + else { + return fail(0xd65d, { filter }); + } +} +function toCompositeFilter(filter) { + const protos = filter.getFilters().map(filter => toFilter(filter)); + if (protos.length === 1) { + return protos[0]; + } + return { + compositeFilter: { + op: toCompositeOperatorName(filter.op), + filters: protos + } + }; +} +function toUnaryOrFieldFilter(filter) { + if (filter.op === "==" /* Operator.EQUAL */) { + if (isNanValue(filter.value)) { + return { + unaryFilter: { + field: toFieldPathReference(filter.field), + op: 'IS_NAN' + } + }; + } + else if (isNullValue(filter.value)) { + return { + unaryFilter: { + field: toFieldPathReference(filter.field), + op: 'IS_NULL' + } + }; + } + } + else if (filter.op === "!=" /* Operator.NOT_EQUAL */) { + if (isNanValue(filter.value)) { + return { + unaryFilter: { + field: toFieldPathReference(filter.field), + op: 'IS_NOT_NAN' + } + }; + } + else if (isNullValue(filter.value)) { + return { + unaryFilter: { + field: toFieldPathReference(filter.field), + op: 'IS_NOT_NULL' + } + }; + } + } + return { + fieldFilter: { + field: toFieldPathReference(filter.field), + op: toOperatorName(filter.op), + value: filter.value + } + }; +} +function fromUnaryFilter(filter) { + switch (filter.unaryFilter.op) { + case 'IS_NAN': + const nanField = fromFieldPathReference(filter.unaryFilter.field); + return FieldFilter.create(nanField, "==" /* Operator.EQUAL */, { + doubleValue: NaN + }); + case 'IS_NULL': + const nullField = fromFieldPathReference(filter.unaryFilter.field); + return FieldFilter.create(nullField, "==" /* Operator.EQUAL */, { + nullValue: 'NULL_VALUE' + }); + case 'IS_NOT_NAN': + const notNanField = fromFieldPathReference(filter.unaryFilter.field); + return FieldFilter.create(notNanField, "!=" /* Operator.NOT_EQUAL */, { + doubleValue: NaN + }); + case 'IS_NOT_NULL': + const notNullField = fromFieldPathReference(filter.unaryFilter.field); + return FieldFilter.create(notNullField, "!=" /* Operator.NOT_EQUAL */, { + nullValue: 'NULL_VALUE' + }); + case 'OPERATOR_UNSPECIFIED': + return fail(0xef81); + default: + return fail(0xed36); + } +} +function fromFieldFilter(filter) { + return FieldFilter.create(fromFieldPathReference(filter.fieldFilter.field), fromOperatorName(filter.fieldFilter.op), filter.fieldFilter.value); +} +function fromCompositeFilter(filter) { + return CompositeFilter.create(filter.compositeFilter.filters.map(filter => fromFilter(filter)), fromCompositeOperatorName(filter.compositeFilter.op)); +} +function toDocumentMask(fieldMask) { + const canonicalFields = []; + fieldMask.fields.forEach(field => canonicalFields.push(field.canonicalString())); + return { + fieldPaths: canonicalFields + }; +} +function fromDocumentMask(proto) { + const paths = proto.fieldPaths || []; + return new FieldMask(paths.map(path => FieldPath$1.fromServerFormat(path))); +} +function isValidResourceName(path) { + // Resource names have at least 4 components (project ID, database ID) + return (path.length >= 4 && + path.get(0) === 'projects' && + path.get(2) === 'databases'); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable set of metadata that the local store tracks for each target. + */ +class TargetData { + constructor( + /** The target being listened to. */ + target, + /** + * The target ID to which the target corresponds; Assigned by the + * LocalStore for user listens and by the SyncEngine for limbo watches. + */ + targetId, + /** The purpose of the target. */ + purpose, + /** + * The sequence number of the last transaction during which this target data + * was modified. + */ + sequenceNumber, + /** The latest snapshot version seen for this target. */ + snapshotVersion = SnapshotVersion.min(), + /** + * The maximum snapshot version at which the associated view + * contained no limbo documents. + */ + lastLimboFreeSnapshotVersion = SnapshotVersion.min(), + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + resumeToken = ByteString.EMPTY_BYTE_STRING, + /** + * The number of documents that last matched the query at the resume token or + * read time. Documents are counted only when making a listen request with + * resume token or read time, otherwise, keep it null. + */ + expectedCount = null) { + this.target = target; + this.targetId = targetId; + this.purpose = purpose; + this.sequenceNumber = sequenceNumber; + this.snapshotVersion = snapshotVersion; + this.lastLimboFreeSnapshotVersion = lastLimboFreeSnapshotVersion; + this.resumeToken = resumeToken; + this.expectedCount = expectedCount; + } + /** Creates a new target data instance with an updated sequence number. */ + withSequenceNumber(sequenceNumber) { + return new TargetData(this.target, this.targetId, this.purpose, sequenceNumber, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, this.expectedCount); + } + /** + * Creates a new target data instance with an updated resume token and + * snapshot version. + */ + withResumeToken(resumeToken, snapshotVersion) { + return new TargetData(this.target, this.targetId, this.purpose, this.sequenceNumber, snapshotVersion, this.lastLimboFreeSnapshotVersion, resumeToken, + /* expectedCount= */ null); + } + /** + * Creates a new target data instance with an updated expected count. + */ + withExpectedCount(expectedCount) { + return new TargetData(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, expectedCount); + } + /** + * Creates a new target data instance with an updated last limbo free + * snapshot version number. + */ + withLastLimboFreeSnapshotVersion(lastLimboFreeSnapshotVersion) { + return new TargetData(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, lastLimboFreeSnapshotVersion, this.resumeToken, this.expectedCount); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Serializer for values stored in the LocalStore. */ +class LocalSerializer { + constructor(remoteSerializer) { + this.remoteSerializer = remoteSerializer; + } +} +/** Decodes a remote document from storage locally to a Document. */ +function fromDbRemoteDocument(localSerializer, remoteDoc) { + let doc; + if (remoteDoc.document) { + doc = fromDocument(localSerializer.remoteSerializer, remoteDoc.document, !!remoteDoc.hasCommittedMutations); + } + else if (remoteDoc.noDocument) { + const key = DocumentKey.fromSegments(remoteDoc.noDocument.path); + const version = fromDbTimestamp(remoteDoc.noDocument.readTime); + doc = MutableDocument.newNoDocument(key, version); + if (remoteDoc.hasCommittedMutations) { + doc.setHasCommittedMutations(); + } + } + else if (remoteDoc.unknownDocument) { + const key = DocumentKey.fromSegments(remoteDoc.unknownDocument.path); + const version = fromDbTimestamp(remoteDoc.unknownDocument.version); + doc = MutableDocument.newUnknownDocument(key, version); + } + else { + return fail(0xdd85); + } + if (remoteDoc.readTime) { + doc.setReadTime(fromDbTimestampKey(remoteDoc.readTime)); + } + return doc; +} +/** Encodes a document for storage locally. */ +function toDbRemoteDocument(localSerializer, document) { + const key = document.key; + const remoteDoc = { + prefixPath: key.getCollectionPath().popLast().toArray(), + collectionGroup: key.collectionGroup, + documentId: key.path.lastSegment(), + readTime: toDbTimestampKey(document.readTime), + hasCommittedMutations: document.hasCommittedMutations + }; + if (document.isFoundDocument()) { + remoteDoc.document = toDocument(localSerializer.remoteSerializer, document); + } + else if (document.isNoDocument()) { + remoteDoc.noDocument = { + path: key.path.toArray(), + readTime: toDbTimestamp(document.version) + }; + } + else if (document.isUnknownDocument()) { + remoteDoc.unknownDocument = { + path: key.path.toArray(), + version: toDbTimestamp(document.version) + }; + } + else { + return fail(0xe230, { document }); + } + return remoteDoc; +} +function toDbTimestampKey(snapshotVersion) { + const timestamp = snapshotVersion.toTimestamp(); + return [timestamp.seconds, timestamp.nanoseconds]; +} +function fromDbTimestampKey(dbTimestampKey) { + const timestamp = new Timestamp(dbTimestampKey[0], dbTimestampKey[1]); + return SnapshotVersion.fromTimestamp(timestamp); +} +function toDbTimestamp(snapshotVersion) { + const timestamp = snapshotVersion.toTimestamp(); + return { seconds: timestamp.seconds, nanoseconds: timestamp.nanoseconds }; +} +function fromDbTimestamp(dbTimestamp) { + const timestamp = new Timestamp(dbTimestamp.seconds, dbTimestamp.nanoseconds); + return SnapshotVersion.fromTimestamp(timestamp); +} +/** Encodes a batch of mutations into a DbMutationBatch for local storage. */ +function toDbMutationBatch(localSerializer, userId, batch) { + const serializedBaseMutations = batch.baseMutations.map(m => toMutation(localSerializer.remoteSerializer, m)); + const serializedMutations = batch.mutations.map(m => toMutation(localSerializer.remoteSerializer, m)); + return { + userId, + batchId: batch.batchId, + localWriteTimeMs: batch.localWriteTime.toMillis(), + baseMutations: serializedBaseMutations, + mutations: serializedMutations + }; +} +/** Decodes a DbMutationBatch into a MutationBatch */ +function fromDbMutationBatch(localSerializer, dbBatch) { + const baseMutations = (dbBatch.baseMutations || []).map(m => fromMutation(localSerializer.remoteSerializer, m)); + // Squash old transform mutations into existing patch or set mutations. + // The replacement of representing `transforms` with `update_transforms` + // on the SDK means that old `transform` mutations stored in IndexedDB need + // to be updated to `update_transforms`. + // TODO(b/174608374): Remove this code once we perform a schema migration. + for (let i = 0; i < dbBatch.mutations.length - 1; ++i) { + const currentMutation = dbBatch.mutations[i]; + const hasTransform = i + 1 < dbBatch.mutations.length && + dbBatch.mutations[i + 1].transform !== undefined; + if (hasTransform) { + const transformMutation = dbBatch.mutations[i + 1]; + currentMutation.updateTransforms = + transformMutation.transform.fieldTransforms; + dbBatch.mutations.splice(i + 1, 1); + ++i; + } + } + const mutations = dbBatch.mutations.map(m => fromMutation(localSerializer.remoteSerializer, m)); + const timestamp = Timestamp.fromMillis(dbBatch.localWriteTimeMs); + return new MutationBatch(dbBatch.batchId, timestamp, baseMutations, mutations); +} +/** Decodes a DbTarget into TargetData */ +function fromDbTarget(dbTarget) { + const version = fromDbTimestamp(dbTarget.readTime); + const lastLimboFreeSnapshotVersion = dbTarget.lastLimboFreeSnapshotVersion !== undefined + ? fromDbTimestamp(dbTarget.lastLimboFreeSnapshotVersion) + : SnapshotVersion.min(); + let target; + if (isDocumentQuery(dbTarget.query)) { + target = fromDocumentsTarget(dbTarget.query); + } + else { + target = fromQueryTarget(dbTarget.query); + } + return new TargetData(target, dbTarget.targetId, "TargetPurposeListen" /* TargetPurpose.Listen */, dbTarget.lastListenSequenceNumber, version, lastLimboFreeSnapshotVersion, ByteString.fromBase64String(dbTarget.resumeToken)); +} +/** Encodes TargetData into a DbTarget for storage locally. */ +function toDbTarget(localSerializer, targetData) { + const dbTimestamp = toDbTimestamp(targetData.snapshotVersion); + const dbLastLimboFreeTimestamp = toDbTimestamp(targetData.lastLimboFreeSnapshotVersion); + let queryProto; + if (targetIsDocumentTarget(targetData.target)) { + queryProto = toDocumentsTarget(localSerializer.remoteSerializer, targetData.target); + } + else { + queryProto = toQueryTarget(localSerializer.remoteSerializer, targetData.target).queryTarget; + } + // We can't store the resumeToken as a ByteString in IndexedDb, so we + // convert it to a base64 string for storage. + const resumeToken = targetData.resumeToken.toBase64(); + // lastListenSequenceNumber is always 0 until we do real GC. + return { + targetId: targetData.targetId, + canonicalId: canonifyTarget(targetData.target), + readTime: dbTimestamp, + resumeToken, + lastListenSequenceNumber: targetData.sequenceNumber, + lastLimboFreeSnapshotVersion: dbLastLimboFreeTimestamp, + query: queryProto + }; +} +/** + * A helper function for figuring out what kind of query has been stored. + */ +function isDocumentQuery(dbQuery) { + return dbQuery.documents !== undefined; +} +/** Encodes a DbBundle to a BundleMetadata object. */ +function fromDbBundle(dbBundle) { + return { + id: dbBundle.bundleId, + createTime: fromDbTimestamp(dbBundle.createTime), + version: dbBundle.version + }; +} +/** Encodes a BundleMetadata to a DbBundle. */ +function toDbBundle(metadata) { + return { + bundleId: metadata.id, + createTime: toDbTimestamp(fromVersion(metadata.createTime)), + version: metadata.version + }; +} +/** Encodes a DbNamedQuery to a NamedQuery. */ +function fromDbNamedQuery(dbNamedQuery) { + return { + name: dbNamedQuery.name, + query: fromBundledQuery(dbNamedQuery.bundledQuery), + readTime: fromDbTimestamp(dbNamedQuery.readTime) + }; +} +/** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */ +function toDbNamedQuery(query) { + return { + name: query.name, + readTime: toDbTimestamp(fromVersion(query.readTime)), + bundledQuery: query.bundledQuery + }; +} +/** + * Encodes a `BundledQuery` from bundle proto to a Query object. + * + * This reconstructs the original query used to build the bundle being loaded, + * including features exists only in SDKs (for example: limit-to-last). + */ +function fromBundledQuery(bundledQuery) { + const query = convertQueryTargetToQuery({ + parent: bundledQuery.parent, + structuredQuery: bundledQuery.structuredQuery + }); + if (bundledQuery.limitType === 'LAST') { + return queryWithLimit(query, query.limit, "L" /* LimitType.Last */); + } + return query; +} +/** Encodes a NamedQuery proto object to a NamedQuery model object. */ +function fromProtoNamedQuery(namedQuery) { + return { + name: namedQuery.name, + query: fromBundledQuery(namedQuery.bundledQuery), + readTime: fromVersion(namedQuery.readTime) + }; +} +/** Decodes a BundleMetadata proto into a BundleMetadata object. */ +function fromBundleMetadata(metadata) { + return { + id: metadata.id, + version: metadata.version, + createTime: fromVersion(metadata.createTime) + }; +} +/** Encodes a DbDocumentOverlay object to an Overlay model object. */ +function fromDbDocumentOverlay(localSerializer, dbDocumentOverlay) { + return new Overlay(dbDocumentOverlay.largestBatchId, fromMutation(localSerializer.remoteSerializer, dbDocumentOverlay.overlayMutation)); +} +/** Decodes an Overlay model object into a DbDocumentOverlay object. */ +function toDbDocumentOverlay(localSerializer, userId, overlay) { + const [_, collectionPath, documentId] = toDbDocumentOverlayKey(userId, overlay.mutation.key); + return { + userId, + collectionPath, + documentId, + collectionGroup: overlay.mutation.key.getCollectionGroup(), + largestBatchId: overlay.largestBatchId, + overlayMutation: toMutation(localSerializer.remoteSerializer, overlay.mutation) + }; +} +/** + * Returns the DbDocumentOverlayKey corresponding to the given user and + * document key. + */ +function toDbDocumentOverlayKey(userId, docKey) { + const docId = docKey.path.lastSegment(); + const collectionPath = encodeResourcePath(docKey.path.popLast()); + return [userId, collectionPath, docId]; +} +function toDbIndexConfiguration(index) { + return { + indexId: index.indexId, + collectionGroup: index.collectionGroup, + fields: index.fields.map(s => [s.fieldPath.canonicalString(), s.kind]) + }; +} +function fromDbIndexConfiguration(index, state) { + const decodedState = state + ? new IndexState(state.sequenceNumber, new IndexOffset(fromDbTimestamp(state.readTime), new DocumentKey(decodeResourcePath(state.documentKey)), state.largestBatchId)) + : IndexState.empty(); + const decodedSegments = index.fields.map(([fieldPath, kind]) => new IndexSegment(FieldPath$1.fromServerFormat(fieldPath), kind)); + return new FieldIndex(index.indexId, index.collectionGroup, decodedSegments, decodedState); +} +function toDbIndexState(indexId, uid, sequenceNumber, offset) { + return { + indexId, + uid, + sequenceNumber, + readTime: toDbTimestamp(offset.readTime), + documentKey: encodeResourcePath(offset.documentKey.path), + largestBatchId: offset.largestBatchId + }; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class IndexedDbBundleCache { + getBundleMetadata(transaction, bundleId) { + return bundlesStore(transaction) + .get(bundleId) + .next(bundle => { + if (bundle) { + return fromDbBundle(bundle); + } + return undefined; + }); + } + saveBundleMetadata(transaction, bundleMetadata) { + return bundlesStore(transaction).put(toDbBundle(bundleMetadata)); + } + getNamedQuery(transaction, queryName) { + return namedQueriesStore(transaction) + .get(queryName) + .next(query => { + if (query) { + return fromDbNamedQuery(query); + } + return undefined; + }); + } + saveNamedQuery(transaction, query) { + return namedQueriesStore(transaction).put(toDbNamedQuery(query)); + } +} +/** + * Helper to get a typed SimpleDbStore for the bundles object store. + */ +function bundlesStore(txn) { + return getStore(txn, DbBundleStore); +} +/** + * Helper to get a typed SimpleDbStore for the namedQueries object store. + */ +function namedQueriesStore(txn) { + return getStore(txn, DbNamedQueryStore); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Implementation of DocumentOverlayCache using IndexedDb. + */ +class IndexedDbDocumentOverlayCache { + /** + * @param serializer - The document serializer. + * @param userId - The userId for which we are accessing overlays. + */ + constructor(serializer, userId) { + this.serializer = serializer; + this.userId = userId; + } + static forUser(serializer, user) { + const userId = user.uid || ''; + return new IndexedDbDocumentOverlayCache(serializer, userId); + } + getOverlay(transaction, key) { + return documentOverlayStore(transaction) + .get(toDbDocumentOverlayKey(this.userId, key)) + .next(dbOverlay => { + if (dbOverlay) { + return fromDbDocumentOverlay(this.serializer, dbOverlay); + } + return null; + }); + } + getOverlays(transaction, keys) { + const result = newOverlayMap(); + return PersistencePromise.forEach(keys, (key) => { + return this.getOverlay(transaction, key).next(overlay => { + if (overlay !== null) { + result.set(key, overlay); + } + }); + }).next(() => result); + } + saveOverlays(transaction, largestBatchId, overlays) { + const promises = []; + overlays.forEach((_, mutation) => { + const overlay = new Overlay(largestBatchId, mutation); + promises.push(this.saveOverlay(transaction, overlay)); + }); + return PersistencePromise.waitFor(promises); + } + removeOverlaysForBatchId(transaction, documentKeys, batchId) { + const collectionPaths = new Set(); + // Get the set of unique collection paths. + documentKeys.forEach(key => collectionPaths.add(encodeResourcePath(key.getCollectionPath()))); + const promises = []; + collectionPaths.forEach(collectionPath => { + const range = IDBKeyRange.bound([this.userId, collectionPath, batchId], [this.userId, collectionPath, batchId + 1], + /*lowerOpen=*/ false, + /*upperOpen=*/ true); + promises.push(documentOverlayStore(transaction).deleteAll(DbDocumentOverlayCollectionPathOverlayIndex, range)); + }); + return PersistencePromise.waitFor(promises); + } + getOverlaysForCollection(transaction, collection, sinceBatchId) { + const result = newOverlayMap(); + const collectionPath = encodeResourcePath(collection); + // We want batch IDs larger than `sinceBatchId`, and so the lower bound + // is not inclusive. + const range = IDBKeyRange.bound([this.userId, collectionPath, sinceBatchId], [this.userId, collectionPath, Number.POSITIVE_INFINITY], + /*lowerOpen=*/ true); + return documentOverlayStore(transaction) + .loadAll(DbDocumentOverlayCollectionPathOverlayIndex, range) + .next(dbOverlays => { + for (const dbOverlay of dbOverlays) { + const overlay = fromDbDocumentOverlay(this.serializer, dbOverlay); + result.set(overlay.getKey(), overlay); + } + return result; + }); + } + getOverlaysForCollectionGroup(transaction, collectionGroup, sinceBatchId, count) { + const result = newOverlayMap(); + let currentBatchId = undefined; + // We want batch IDs larger than `sinceBatchId`, and so the lower bound + // is not inclusive. + const range = IDBKeyRange.bound([this.userId, collectionGroup, sinceBatchId], [this.userId, collectionGroup, Number.POSITIVE_INFINITY], + /*lowerOpen=*/ true); + return documentOverlayStore(transaction) + .iterate({ + index: DbDocumentOverlayCollectionGroupOverlayIndex, + range + }, (_, dbOverlay, control) => { + // We do not want to return partial batch overlays, even if the size + // of the result set exceeds the given `count` argument. Therefore, we + // continue to aggregate results even after the result size exceeds + // `count` if there are more overlays from the `currentBatchId`. + const overlay = fromDbDocumentOverlay(this.serializer, dbOverlay); + if (result.size() < count || + overlay.largestBatchId === currentBatchId) { + result.set(overlay.getKey(), overlay); + currentBatchId = overlay.largestBatchId; + } + else { + control.done(); + } + }) + .next(() => result); + } + saveOverlay(transaction, overlay) { + return documentOverlayStore(transaction).put(toDbDocumentOverlay(this.serializer, this.userId, overlay)); + } +} +/** + * Helper to get a typed SimpleDbStore for the document overlay object store. + */ +function documentOverlayStore(txn) { + return getStore(txn, DbDocumentOverlayStore); +} + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class IndexedDbGlobalsCache { + globalsStore(txn) { + return getStore(txn, DbGlobalsStore); + } + getSessionToken(txn) { + const globals = this.globalsStore(txn); + return globals.get('sessionToken').next(global => { + const value = global?.value; + return value + ? ByteString.fromUint8Array(value) + : ByteString.EMPTY_BYTE_STRING; + }); + } + setSessionToken(txn, sessionToken) { + const globals = this.globalsStore(txn); + return globals.put({ + name: 'sessionToken', + value: sessionToken.toUint8Array() + }); + } +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Note: This code is copied from the backend. Code that is not used by +// Firestore was removed. +const INDEX_TYPE_NULL = 5; +const INDEX_TYPE_BOOLEAN = 10; +const INDEX_TYPE_NAN = 13; +const INDEX_TYPE_NUMBER = 15; +const INDEX_TYPE_TIMESTAMP = 20; +const INDEX_TYPE_STRING = 25; +const INDEX_TYPE_BLOB = 30; +const INDEX_TYPE_REFERENCE = 37; +const INDEX_TYPE_GEOPOINT = 45; +const INDEX_TYPE_ARRAY = 50; +const INDEX_TYPE_VECTOR = 53; +const INDEX_TYPE_MAP = 55; +const INDEX_TYPE_REFERENCE_SEGMENT = 60; +// A terminator that indicates that a truncatable value was not truncated. +// This must be smaller than all other type labels. +const NOT_TRUNCATED = 2; +/** Firestore index value writer. */ +class FirestoreIndexValueWriter { + constructor() { } + // The write methods below short-circuit writing terminators for values + // containing a (terminating) truncated value. + // + // As an example, consider the resulting encoding for: + // + // ["bar", [2, "foo"]] -> (STRING, "bar", TERM, ARRAY, NUMBER, 2, STRING, "foo", TERM, TERM, TERM) + // ["bar", [2, truncated("foo")]] -> (STRING, "bar", TERM, ARRAY, NUMBER, 2, STRING, "foo", TRUNC) + // ["bar", truncated(["foo"])] -> (STRING, "bar", TERM, ARRAY. STRING, "foo", TERM, TRUNC) + /** Writes an index value. */ + writeIndexValue(value, encoder) { + this.writeIndexValueAux(value, encoder); + // Write separator to split index values + // (see go/firestore-storage-format#encodings). + encoder.writeInfinity(); + } + writeIndexValueAux(indexValue, encoder) { + if ('nullValue' in indexValue) { + this.writeValueTypeLabel(encoder, INDEX_TYPE_NULL); + } + else if ('booleanValue' in indexValue) { + this.writeValueTypeLabel(encoder, INDEX_TYPE_BOOLEAN); + encoder.writeNumber(indexValue.booleanValue ? 1 : 0); + } + else if ('integerValue' in indexValue) { + this.writeValueTypeLabel(encoder, INDEX_TYPE_NUMBER); + encoder.writeNumber(normalizeNumber(indexValue.integerValue)); + } + else if ('doubleValue' in indexValue) { + const n = normalizeNumber(indexValue.doubleValue); + if (isNaN(n)) { + this.writeValueTypeLabel(encoder, INDEX_TYPE_NAN); + } + else { + this.writeValueTypeLabel(encoder, INDEX_TYPE_NUMBER); + if (isNegativeZero(n)) { + // -0.0, 0 and 0.0 are all considered the same + encoder.writeNumber(0.0); + } + else { + encoder.writeNumber(n); + } + } + } + else if ('timestampValue' in indexValue) { + let timestamp = indexValue.timestampValue; + this.writeValueTypeLabel(encoder, INDEX_TYPE_TIMESTAMP); + if (typeof timestamp === 'string') { + timestamp = normalizeTimestamp(timestamp); + } + encoder.writeString(`${timestamp.seconds || ''}`); + encoder.writeNumber(timestamp.nanos || 0); + } + else if ('stringValue' in indexValue) { + this.writeIndexString(indexValue.stringValue, encoder); + this.writeTruncationMarker(encoder); + } + else if ('bytesValue' in indexValue) { + this.writeValueTypeLabel(encoder, INDEX_TYPE_BLOB); + encoder.writeBytes(normalizeByteString(indexValue.bytesValue)); + this.writeTruncationMarker(encoder); + } + else if ('referenceValue' in indexValue) { + this.writeIndexEntityRef(indexValue.referenceValue, encoder); + } + else if ('geoPointValue' in indexValue) { + const geoPoint = indexValue.geoPointValue; + this.writeValueTypeLabel(encoder, INDEX_TYPE_GEOPOINT); + encoder.writeNumber(geoPoint.latitude || 0); + encoder.writeNumber(geoPoint.longitude || 0); + } + else if ('mapValue' in indexValue) { + if (isMaxValue(indexValue)) { + this.writeValueTypeLabel(encoder, Number.MAX_SAFE_INTEGER); + } + else if (isVectorValue(indexValue)) { + this.writeIndexVector(indexValue.mapValue, encoder); + } + else { + this.writeIndexMap(indexValue.mapValue, encoder); + this.writeTruncationMarker(encoder); + } + } + else if ('arrayValue' in indexValue) { + this.writeIndexArray(indexValue.arrayValue, encoder); + this.writeTruncationMarker(encoder); + } + else { + fail(0x4a4e, { indexValue }); + } + } + writeIndexString(stringIndexValue, encoder) { + this.writeValueTypeLabel(encoder, INDEX_TYPE_STRING); + this.writeUnlabeledIndexString(stringIndexValue, encoder); + } + writeUnlabeledIndexString(stringIndexValue, encoder) { + encoder.writeString(stringIndexValue); + } + writeIndexMap(mapIndexValue, encoder) { + const map = mapIndexValue.fields || {}; + this.writeValueTypeLabel(encoder, INDEX_TYPE_MAP); + for (const key of Object.keys(map)) { + this.writeIndexString(key, encoder); + this.writeIndexValueAux(map[key], encoder); + } + } + writeIndexVector(mapIndexValue, encoder) { + const map = mapIndexValue.fields || {}; + this.writeValueTypeLabel(encoder, INDEX_TYPE_VECTOR); + // Vectors sort first by length + const key = VECTOR_MAP_VECTORS_KEY; + const length = map[key].arrayValue?.values?.length || 0; + this.writeValueTypeLabel(encoder, INDEX_TYPE_NUMBER); + encoder.writeNumber(normalizeNumber(length)); + // Vectors then sort by position value + this.writeIndexString(key, encoder); + this.writeIndexValueAux(map[key], encoder); + } + writeIndexArray(arrayIndexValue, encoder) { + const values = arrayIndexValue.values || []; + this.writeValueTypeLabel(encoder, INDEX_TYPE_ARRAY); + for (const element of values) { + this.writeIndexValueAux(element, encoder); + } + } + writeIndexEntityRef(referenceValue, encoder) { + this.writeValueTypeLabel(encoder, INDEX_TYPE_REFERENCE); + const path = DocumentKey.fromName(referenceValue).path; + path.forEach(segment => { + this.writeValueTypeLabel(encoder, INDEX_TYPE_REFERENCE_SEGMENT); + this.writeUnlabeledIndexString(segment, encoder); + }); + } + writeValueTypeLabel(encoder, typeOrder) { + encoder.writeNumber(typeOrder); + } + writeTruncationMarker(encoder) { + // While the SDK does not implement truncation, the truncation marker is + // used to terminate all variable length values (which are strings, bytes, + // references, arrays and maps). + encoder.writeNumber(NOT_TRUNCATED); + } +} +FirestoreIndexValueWriter.INSTANCE = new FirestoreIndexValueWriter(); + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law | agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES | CONDITIONS OF ANY KIND, either express | implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** These constants are taken from the backend. */ +const MIN_SURROGATE = '\uD800'; +const MAX_SURROGATE = '\uDBFF'; +const ESCAPE1 = 0x00; +const NULL_BYTE = 0xff; // Combined with ESCAPE1 +const SEPARATOR = 0x01; // Combined with ESCAPE1 +const ESCAPE2 = 0xff; +const INFINITY = 0xff; // Combined with ESCAPE2 +const FF_BYTE = 0x00; // Combined with ESCAPE2 +const LONG_SIZE = 64; +const BYTE_SIZE = 8; +/** + * The default size of the buffer. This is arbitrary, but likely larger than + * most index values so that less copies of the underlying buffer will be made. + * For large values, a single copy will made to double the buffer length. + */ +const DEFAULT_BUFFER_SIZE = 1024; +/** Converts a JavaScript number to a byte array (using big endian encoding). */ +function doubleToLongBits(value) { + const dv = new DataView(new ArrayBuffer(8)); + dv.setFloat64(0, value, /* littleEndian= */ false); + return new Uint8Array(dv.buffer); +} +/** + * Counts the number of zeros in a byte. + * + * Visible for testing. + */ +function numberOfLeadingZerosInByte(x) { + if (x === 0) { + return 8; + } + let zeros = 0; + if (x >> 4 === 0) { + // Test if the first four bits are zero. + zeros += 4; + x = x << 4; + } + if (x >> 6 === 0) { + // Test if the first two (or next two) bits are zero. + zeros += 2; + x = x << 2; + } + if (x >> 7 === 0) { + // Test if the remaining bit is zero. + zeros += 1; + } + return zeros; +} +/** Counts the number of leading zeros in the given byte array. */ +function numberOfLeadingZeros(bytes) { + let leadingZeros = 0; + for (let i = 0; i < 8; ++i) { + const zeros = numberOfLeadingZerosInByte(bytes[i] & 0xff); + leadingZeros += zeros; + if (zeros !== 8) { + break; + } + } + return leadingZeros; +} +/** + * Returns the number of bytes required to store "value". Leading zero bytes + * are skipped. + */ +function unsignedNumLength(value) { + // This is just the number of bytes for the unsigned representation of the number. + const numBits = LONG_SIZE - numberOfLeadingZeros(value); + return Math.ceil(numBits / BYTE_SIZE); +} +/** + * OrderedCodeWriter is a minimal-allocation implementation of the writing + * behavior defined by the backend. + * + * The code is ported from its Java counterpart. + */ +class OrderedCodeWriter { + constructor() { + this.buffer = new Uint8Array(DEFAULT_BUFFER_SIZE); + this.position = 0; + } + writeBytesAscending(value) { + const it = value[Symbol.iterator](); + let byte = it.next(); + while (!byte.done) { + this.writeByteAscending(byte.value); + byte = it.next(); + } + this.writeSeparatorAscending(); + } + writeBytesDescending(value) { + const it = value[Symbol.iterator](); + let byte = it.next(); + while (!byte.done) { + this.writeByteDescending(byte.value); + byte = it.next(); + } + this.writeSeparatorDescending(); + } + /** Writes utf8 bytes into this byte sequence, ascending. */ + writeUtf8Ascending(sequence) { + for (const c of sequence) { + const charCode = c.charCodeAt(0); + if (charCode < 0x80) { + this.writeByteAscending(charCode); + } + else if (charCode < 0x800) { + this.writeByteAscending((0x0f << 6) | (charCode >>> 6)); + this.writeByteAscending(0x80 | (0x3f & charCode)); + } + else if (c < MIN_SURROGATE || MAX_SURROGATE < c) { + this.writeByteAscending((0x0f << 5) | (charCode >>> 12)); + this.writeByteAscending(0x80 | (0x3f & (charCode >>> 6))); + this.writeByteAscending(0x80 | (0x3f & charCode)); + } + else { + const codePoint = c.codePointAt(0); + this.writeByteAscending((0x0f << 4) | (codePoint >>> 18)); + this.writeByteAscending(0x80 | (0x3f & (codePoint >>> 12))); + this.writeByteAscending(0x80 | (0x3f & (codePoint >>> 6))); + this.writeByteAscending(0x80 | (0x3f & codePoint)); + } + } + this.writeSeparatorAscending(); + } + /** Writes utf8 bytes into this byte sequence, descending */ + writeUtf8Descending(sequence) { + for (const c of sequence) { + const charCode = c.charCodeAt(0); + if (charCode < 0x80) { + this.writeByteDescending(charCode); + } + else if (charCode < 0x800) { + this.writeByteDescending((0x0f << 6) | (charCode >>> 6)); + this.writeByteDescending(0x80 | (0x3f & charCode)); + } + else if (c < MIN_SURROGATE || MAX_SURROGATE < c) { + this.writeByteDescending((0x0f << 5) | (charCode >>> 12)); + this.writeByteDescending(0x80 | (0x3f & (charCode >>> 6))); + this.writeByteDescending(0x80 | (0x3f & charCode)); + } + else { + const codePoint = c.codePointAt(0); + this.writeByteDescending((0x0f << 4) | (codePoint >>> 18)); + this.writeByteDescending(0x80 | (0x3f & (codePoint >>> 12))); + this.writeByteDescending(0x80 | (0x3f & (codePoint >>> 6))); + this.writeByteDescending(0x80 | (0x3f & codePoint)); + } + } + this.writeSeparatorDescending(); + } + writeNumberAscending(val) { + // Values are encoded with a single byte length prefix, followed by the + // actual value in big-endian format with leading 0 bytes dropped. + const value = this.toOrderedBits(val); + const len = unsignedNumLength(value); + this.ensureAvailable(1 + len); + this.buffer[this.position++] = len & 0xff; // Write the length + for (let i = value.length - len; i < value.length; ++i) { + this.buffer[this.position++] = value[i] & 0xff; + } + } + writeNumberDescending(val) { + // Values are encoded with a single byte length prefix, followed by the + // inverted value in big-endian format with leading 0 bytes dropped. + const value = this.toOrderedBits(val); + const len = unsignedNumLength(value); + this.ensureAvailable(1 + len); + this.buffer[this.position++] = ~(len & 0xff); // Write the length + for (let i = value.length - len; i < value.length; ++i) { + this.buffer[this.position++] = ~(value[i] & 0xff); + } + } + /** + * Writes the "infinity" byte sequence that sorts after all other byte + * sequences written in ascending order. + */ + writeInfinityAscending() { + this.writeEscapedByteAscending(ESCAPE2); + this.writeEscapedByteAscending(INFINITY); + } + /** + * Writes the "infinity" byte sequence that sorts before all other byte + * sequences written in descending order. + */ + writeInfinityDescending() { + this.writeEscapedByteDescending(ESCAPE2); + this.writeEscapedByteDescending(INFINITY); + } + /** + * Resets the buffer such that it is the same as when it was newly + * constructed. + */ + reset() { + this.position = 0; + } + seed(encodedBytes) { + this.ensureAvailable(encodedBytes.length); + this.buffer.set(encodedBytes, this.position); + this.position += encodedBytes.length; + } + /** Makes a copy of the encoded bytes in this buffer. */ + encodedBytes() { + return this.buffer.slice(0, this.position); + } + /** + * Encodes `val` into an encoding so that the order matches the IEEE 754 + * floating-point comparison results with the following exceptions: + * -0.0 < 0.0 + * all non-NaN < NaN + * NaN = NaN + */ + toOrderedBits(val) { + const value = doubleToLongBits(val); + // Check if the first bit is set. We use a bit mask since value[0] is + // encoded as a number from 0 to 255. + const isNegative = (value[0] & 0x80) !== 0; + // Revert the two complement to get natural ordering + value[0] ^= isNegative ? 0xff : 0x80; + for (let i = 1; i < value.length; ++i) { + value[i] ^= isNegative ? 0xff : 0x00; + } + return value; + } + /** Writes a single byte ascending to the buffer. */ + writeByteAscending(b) { + const masked = b & 0xff; + if (masked === ESCAPE1) { + this.writeEscapedByteAscending(ESCAPE1); + this.writeEscapedByteAscending(NULL_BYTE); + } + else if (masked === ESCAPE2) { + this.writeEscapedByteAscending(ESCAPE2); + this.writeEscapedByteAscending(FF_BYTE); + } + else { + this.writeEscapedByteAscending(masked); + } + } + /** Writes a single byte descending to the buffer. */ + writeByteDescending(b) { + const masked = b & 0xff; + if (masked === ESCAPE1) { + this.writeEscapedByteDescending(ESCAPE1); + this.writeEscapedByteDescending(NULL_BYTE); + } + else if (masked === ESCAPE2) { + this.writeEscapedByteDescending(ESCAPE2); + this.writeEscapedByteDescending(FF_BYTE); + } + else { + this.writeEscapedByteDescending(b); + } + } + writeSeparatorAscending() { + this.writeEscapedByteAscending(ESCAPE1); + this.writeEscapedByteAscending(SEPARATOR); + } + writeSeparatorDescending() { + this.writeEscapedByteDescending(ESCAPE1); + this.writeEscapedByteDescending(SEPARATOR); + } + writeEscapedByteAscending(b) { + this.ensureAvailable(1); + this.buffer[this.position++] = b; + } + writeEscapedByteDescending(b) { + this.ensureAvailable(1); + this.buffer[this.position++] = ~b; + } + ensureAvailable(bytes) { + const minCapacity = bytes + this.position; + if (minCapacity <= this.buffer.length) { + return; + } + // Try doubling. + let newLength = this.buffer.length * 2; + // Still not big enough? Just allocate the right size. + if (newLength < minCapacity) { + newLength = minCapacity; + } + // Create the new buffer. + const newBuffer = new Uint8Array(newLength); + newBuffer.set(this.buffer); // copy old data + this.buffer = newBuffer; + } +} + +class AscendingIndexByteEncoder { + constructor(orderedCode) { + this.orderedCode = orderedCode; + } + writeBytes(value) { + this.orderedCode.writeBytesAscending(value); + } + writeString(value) { + this.orderedCode.writeUtf8Ascending(value); + } + writeNumber(value) { + this.orderedCode.writeNumberAscending(value); + } + writeInfinity() { + this.orderedCode.writeInfinityAscending(); + } +} +class DescendingIndexByteEncoder { + constructor(orderedCode) { + this.orderedCode = orderedCode; + } + writeBytes(value) { + this.orderedCode.writeBytesDescending(value); + } + writeString(value) { + this.orderedCode.writeUtf8Descending(value); + } + writeNumber(value) { + this.orderedCode.writeNumberDescending(value); + } + writeInfinity() { + this.orderedCode.writeInfinityDescending(); + } +} +/** + * Implements `DirectionalIndexByteEncoder` using `OrderedCodeWriter` for the + * actual encoding. + */ +class IndexByteEncoder { + constructor() { + this.orderedCode = new OrderedCodeWriter(); + this.ascending = new AscendingIndexByteEncoder(this.orderedCode); + this.descending = new DescendingIndexByteEncoder(this.orderedCode); + } + seed(encodedBytes) { + this.orderedCode.seed(encodedBytes); + } + forKind(kind) { + return kind === 0 /* IndexKind.ASCENDING */ ? this.ascending : this.descending; + } + encodedBytes() { + return this.orderedCode.encodedBytes(); + } + reset() { + this.orderedCode.reset(); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Represents an index entry saved by the SDK in persisted storage. */ +class IndexEntry { + constructor(_indexId, _documentKey, _arrayValue, _directionalValue) { + this._indexId = _indexId; + this._documentKey = _documentKey; + this._arrayValue = _arrayValue; + this._directionalValue = _directionalValue; + } + /** + * Returns an IndexEntry entry that sorts immediately after the current + * directional value. + */ + successor() { + const currentLength = this._directionalValue.length; + const newLength = currentLength === 0 || this._directionalValue[currentLength - 1] === 255 + ? currentLength + 1 + : currentLength; + const successor = new Uint8Array(newLength); + successor.set(this._directionalValue, 0); + if (newLength !== currentLength) { + successor.set([0], this._directionalValue.length); + } + else { + ++successor[successor.length - 1]; + } + return new IndexEntry(this._indexId, this._documentKey, this._arrayValue, successor); + } + // Create a representation of the Index Entry as a DbIndexEntry + dbIndexEntry(uid, orderedDocumentKey, documentKey) { + return { + indexId: this._indexId, + uid, + arrayValue: encodeKeySafeBytes(this._arrayValue), + directionalValue: encodeKeySafeBytes(this._directionalValue), + orderedDocumentKey: encodeKeySafeBytes(orderedDocumentKey), + documentKey: documentKey.path.toArray() + }; + } + // Create a representation of the Index Entry as a DbIndexEntryKey + dbIndexEntryKey(uid, orderedDocumentKey, documentKey) { + const entry = this.dbIndexEntry(uid, orderedDocumentKey, documentKey); + return [ + entry.indexId, + entry.uid, + entry.arrayValue, + entry.directionalValue, + entry.orderedDocumentKey, + entry.documentKey + ]; + } +} +function indexEntryComparator(left, right) { + let cmp = left._indexId - right._indexId; + if (cmp !== 0) { + return cmp; + } + cmp = compareByteArrays(left._arrayValue, right._arrayValue); + if (cmp !== 0) { + return cmp; + } + cmp = compareByteArrays(left._directionalValue, right._directionalValue); + if (cmp !== 0) { + return cmp; + } + return DocumentKey.comparator(left._documentKey, right._documentKey); +} +function compareByteArrays(left, right) { + for (let i = 0; i < left.length && i < right.length; ++i) { + const compare = left[i] - right[i]; + if (compare !== 0) { + return compare; + } + } + return left.length - right.length; +} +/** + * Workaround for WebKit bug: https://bugs.webkit.org/show_bug.cgi?id=292721 + * Create a key safe representation of Uint8Array values. + * If the browser is detected as Safari or WebKit, then + * the input array will be converted to "sortable byte string". + * Otherwise, the input array will be returned in its original type. + */ +function encodeKeySafeBytes(array) { + if (util.isSafariOrWebkit()) { + return encodeUint8ArrayToSortableString(array); + } + return array; +} +/** + * Reverts the key safe representation of Uint8Array (created by + * encodeKeySafeBytes) to a normal Uint8Array. + */ +function decodeKeySafeBytes(input) { + if (typeof input !== 'string') { + return input; + } + return decodeSortableStringToUint8Array(input); +} +/** + * Encodes a Uint8Array into a "sortable byte string". + * A "sortable byte string" sorts in the same order as the Uint8Array. + * This works because JS string comparison sorts strings based on code points. + */ +function encodeUint8ArrayToSortableString(array) { + let byteString = ''; + for (let i = 0; i < array.length; i++) { + byteString += String.fromCharCode(array[i]); + } + return byteString; +} +/** + * Decodes a "sortable byte string" back into a Uint8Array. + * A "sortable byte string" is assumed to be created where each character's + * Unicode code point directly corresponds to a single byte value (0-255). + */ +function decodeSortableStringToUint8Array(byteString) { + const uint8array = new Uint8Array(byteString.length); + for (let i = 0; i < byteString.length; i++) { + uint8array[i] = byteString.charCodeAt(i); + } + return uint8array; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A light query planner for Firestore. + * + * This class matches a `FieldIndex` against a Firestore Query `Target`. It + * determines whether a given index can be used to serve the specified target. + * + * The following table showcases some possible index configurations: + * + * Query | Index + * ----------------------------------------------------------------------------- + * where('a', '==', 'a').where('b', '==', 'b') | a ASC, b DESC + * where('a', '==', 'a').where('b', '==', 'b') | a ASC + * where('a', '==', 'a').where('b', '==', 'b') | b DESC + * where('a', '>=', 'a').orderBy('a') | a ASC + * where('a', '>=', 'a').orderBy('a', 'desc') | a DESC + * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC, b ASC + * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC + * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS, b ASCENDING + * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS + */ +class TargetIndexMatcher { + constructor(target) { + // The inequality filters of the target (if it exists). + // Note: The sort on FieldFilters is not required. Using SortedSet here just to utilize the custom + // comparator. + this.inequalityFilters = new SortedSet((lhs, rhs) => FieldPath$1.comparator(lhs.field, rhs.field)); + this.collectionId = + target.collectionGroup != null + ? target.collectionGroup + : target.path.lastSegment(); + this.orderBys = target.orderBy; + this.equalityFilters = []; + for (const filter of target.filters) { + const fieldFilter = filter; + if (fieldFilter.isInequality()) { + this.inequalityFilters = this.inequalityFilters.add(fieldFilter); + } + else { + this.equalityFilters.push(fieldFilter); + } + } + } + get hasMultipleInequality() { + return this.inequalityFilters.size > 1; + } + /** + * Returns whether the index can be used to serve the TargetIndexMatcher's + * target. + * + * An index is considered capable of serving the target when: + * - The target uses all index segments for its filters and orderBy clauses. + * The target can have additional filter and orderBy clauses, but not + * fewer. + * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also + * have a corresponding `CONTAINS` segment. + * - All directional index segments can be mapped to the target as a series of + * equality filters, a single inequality filter and a series of orderBy + * clauses. + * - The segments that represent the equality filters may appear out of order. + * - The optional segment for the inequality filter must appear after all + * equality segments. + * - The segments that represent that orderBy clause of the target must appear + * in order after all equality and inequality segments. Single orderBy + * clauses cannot be skipped, but a continuous orderBy suffix may be + * omitted. + */ + servedByIndex(index) { + hardAssert(index.collectionGroup === this.collectionId, 0xc07f); + if (this.hasMultipleInequality) { + // Only single inequality is supported for now. + // TODO(Add support for multiple inequality query): b/298441043 + return false; + } + // If there is an array element, find a matching filter. + const arraySegment = fieldIndexGetArraySegment(index); + if (arraySegment !== undefined && + !this.hasMatchingEqualityFilter(arraySegment)) { + return false; + } + const segments = fieldIndexGetDirectionalSegments(index); + let equalitySegments = new Set(); + let segmentIndex = 0; + let orderBysIndex = 0; + // Process all equalities first. Equalities can appear out of order. + for (; segmentIndex < segments.length; ++segmentIndex) { + // We attempt to greedily match all segments to equality filters. If a + // filter matches an index segment, we can mark the segment as used. + if (this.hasMatchingEqualityFilter(segments[segmentIndex])) { + equalitySegments = equalitySegments.add(segments[segmentIndex].fieldPath.canonicalString()); + } + else { + // If we cannot find a matching filter, we need to verify whether the + // remaining segments map to the target's inequality and its orderBy + // clauses. + break; + } + } + // If we already have processed all segments, all segments are used to serve + // the equality filters and we do not need to map any segments to the + // target's inequality and orderBy clauses. + if (segmentIndex === segments.length) { + return true; + } + if (this.inequalityFilters.size > 0) { + // Only a single inequality is currently supported. Get the only entry in the set. + const inequalityFilter = this.inequalityFilters.getIterator().getNext(); + // If there is an inequality filter and the field was not in one of the + // equality filters above, the next segment must match both the filter + // and the first orderBy clause. + if (!equalitySegments.has(inequalityFilter.field.canonicalString())) { + const segment = segments[segmentIndex]; + if (!this.matchesFilter(inequalityFilter, segment) || + !this.matchesOrderBy(this.orderBys[orderBysIndex++], segment)) { + return false; + } + } + ++segmentIndex; + } + // All remaining segments need to represent the prefix of the target's + // orderBy. + for (; segmentIndex < segments.length; ++segmentIndex) { + const segment = segments[segmentIndex]; + if (orderBysIndex >= this.orderBys.length || + !this.matchesOrderBy(this.orderBys[orderBysIndex++], segment)) { + return false; + } + } + return true; + } + /** + * Returns a full matched field index for this target. Currently multiple + * inequality query is not supported so function returns null. + */ + buildTargetIndex() { + if (this.hasMultipleInequality) { + return null; + } + // We want to make sure only one segment created for one field. For example, + // in case like a == 3 and a > 2, Index {a ASCENDING} will only be created + // once. + let uniqueFields = new SortedSet(FieldPath$1.comparator); + const segments = []; + for (const filter of this.equalityFilters) { + if (filter.field.isKeyField()) { + continue; + } + const isArrayOperator = filter.op === "array-contains" /* Operator.ARRAY_CONTAINS */ || + filter.op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */; + if (isArrayOperator) { + segments.push(new IndexSegment(filter.field, 2 /* IndexKind.CONTAINS */)); + } + else { + if (uniqueFields.has(filter.field)) { + continue; + } + uniqueFields = uniqueFields.add(filter.field); + segments.push(new IndexSegment(filter.field, 0 /* IndexKind.ASCENDING */)); + } + } + // Note: We do not explicitly check `this.inequalityFilter` but rather rely + // on the target defining an appropriate "order by" to ensure that the + // required index segment is added. The query engine would reject a query + // with an inequality filter that lacks the required order-by clause. + for (const orderBy of this.orderBys) { + // Stop adding more segments if we see a order-by on key. Typically this + // is the default implicit order-by which is covered in the index_entry + // table as a separate column. If it is not the default order-by, the + // generated index will be missing some segments optimized for order-bys, + // which is probably fine. + if (orderBy.field.isKeyField()) { + continue; + } + if (uniqueFields.has(orderBy.field)) { + continue; + } + uniqueFields = uniqueFields.add(orderBy.field); + segments.push(new IndexSegment(orderBy.field, orderBy.dir === "asc" /* Direction.ASCENDING */ + ? 0 /* IndexKind.ASCENDING */ + : 1 /* IndexKind.DESCENDING */)); + } + return new FieldIndex(FieldIndex.UNKNOWN_ID, this.collectionId, segments, IndexState.empty()); + } + hasMatchingEqualityFilter(segment) { + for (const filter of this.equalityFilters) { + if (this.matchesFilter(filter, segment)) { + return true; + } + } + return false; + } + matchesFilter(filter, segment) { + if (filter === undefined || !filter.field.isEqual(segment.fieldPath)) { + return false; + } + const isArrayOperator = filter.op === "array-contains" /* Operator.ARRAY_CONTAINS */ || + filter.op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */; + return (segment.kind === 2 /* IndexKind.CONTAINS */) === isArrayOperator; + } + matchesOrderBy(orderBy, segment) { + if (!orderBy.field.isEqual(segment.fieldPath)) { + return false; + } + return ((segment.kind === 0 /* IndexKind.ASCENDING */ && + orderBy.dir === "asc" /* Direction.ASCENDING */) || + (segment.kind === 1 /* IndexKind.DESCENDING */ && + orderBy.dir === "desc" /* Direction.DESCENDING */)); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provides utility functions that help with boolean logic transformations needed for handling + * complex filters used in queries. + */ +/** + * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in + * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given + * input into a disjunction of equality filters and returns the expanded filter. + */ +function computeInExpansion(filter) { + hardAssert(filter instanceof FieldFilter || filter instanceof CompositeFilter, 0x4e2c); + if (filter instanceof FieldFilter) { + if (filter instanceof InFilter) { + const expandedFilters = filter.value.arrayValue?.values?.map(value => FieldFilter.create(filter.field, "==" /* Operator.EQUAL */, value)) || []; + return CompositeFilter.create(expandedFilters, "or" /* CompositeOperator.OR */); + } + else { + // We have reached other kinds of field filters. + return filter; + } + } + // We have a composite filter. + const expandedFilters = filter.filters.map(subfilter => computeInExpansion(subfilter)); + return CompositeFilter.create(expandedFilters, filter.op); +} +/** + * Given a composite filter, returns the list of terms in its disjunctive normal form. + * + *

Each element in the return value is one term of the resulting DNF. For instance: For the + * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list + * with two elements: a composite filter that performs (A && C), and a composite filter that + * performs (B && C). + * + * @param filter the composite filter to calculate DNF transform for. + * @return the terms in the DNF transform. + */ +function getDnfTerms(filter) { + if (filter.getFilters().length === 0) { + return []; + } + const result = computeDistributedNormalForm(computeInExpansion(filter)); + hardAssert(isDisjunctiveNormalForm(result), 0x1cdf); + if (isSingleFieldFilter(result) || isFlatConjunction(result)) { + return [result]; + } + return result.getFilters(); +} +/** Returns true if the given filter is a single field filter. e.g. (a == 10). */ +function isSingleFieldFilter(filter) { + return filter instanceof FieldFilter; +} +/** + * Returns true if the given filter is the conjunction of one or more field filters. e.g. (a == 10 + * && b == 20) + */ +function isFlatConjunction(filter) { + return (filter instanceof CompositeFilter && + compositeFilterIsFlatConjunction(filter)); +} +/** + * Returns whether or not the given filter is in disjunctive normal form (DNF). + * + *

In boolean logic, a disjunctive normal form (DNF) is a canonical normal form of a logical + * formula consisting of a disjunction of conjunctions; it can also be described as an OR of ANDs. + * + *

For more info, visit: https://en.wikipedia.org/wiki/Disjunctive_normal_form + */ +function isDisjunctiveNormalForm(filter) { + return (isSingleFieldFilter(filter) || + isFlatConjunction(filter) || + isDisjunctionOfFieldFiltersAndFlatConjunctions(filter)); +} +/** + * Returns true if the given filter is the disjunction of one or more "flat conjunctions" and + * field filters. e.g. (a == 10) || (b==20 && c==30) + */ +function isDisjunctionOfFieldFiltersAndFlatConjunctions(filter) { + if (filter instanceof CompositeFilter) { + if (compositeFilterIsDisjunction(filter)) { + for (const subFilter of filter.getFilters()) { + if (!isSingleFieldFilter(subFilter) && !isFlatConjunction(subFilter)) { + return false; + } + } + return true; + } + } + return false; +} +function computeDistributedNormalForm(filter) { + hardAssert(filter instanceof FieldFilter || filter instanceof CompositeFilter, 0x84e2); + if (filter instanceof FieldFilter) { + return filter; + } + if (filter.filters.length === 1) { + return computeDistributedNormalForm(filter.filters[0]); + } + // Compute DNF for each of the subfilters first + const result = filter.filters.map(subfilter => computeDistributedNormalForm(subfilter)); + let newFilter = CompositeFilter.create(result, filter.op); + newFilter = applyAssociation(newFilter); + if (isDisjunctiveNormalForm(newFilter)) { + return newFilter; + } + hardAssert(newFilter instanceof CompositeFilter, 0xfbf2); + hardAssert(compositeFilterIsConjunction(newFilter), 0x9d3b); + hardAssert(newFilter.filters.length > 1, 0xe247); + return newFilter.filters.reduce((runningResult, filter) => applyDistribution(runningResult, filter)); +} +function applyDistribution(lhs, rhs) { + hardAssert(lhs instanceof FieldFilter || lhs instanceof CompositeFilter, 0x95f4); + hardAssert(rhs instanceof FieldFilter || rhs instanceof CompositeFilter, 0x6381); + let result; + if (lhs instanceof FieldFilter) { + if (rhs instanceof FieldFilter) { + // FieldFilter FieldFilter + result = applyDistributionFieldFilters(lhs, rhs); + } + else { + // FieldFilter CompositeFilter + result = applyDistributionFieldAndCompositeFilters(lhs, rhs); + } + } + else { + if (rhs instanceof FieldFilter) { + // CompositeFilter FieldFilter + result = applyDistributionFieldAndCompositeFilters(rhs, lhs); + } + else { + // CompositeFilter CompositeFilter + result = applyDistributionCompositeFilters(lhs, rhs); + } + } + return applyAssociation(result); +} +function applyDistributionFieldFilters(lhs, rhs) { + // Conjunction distribution for two field filters is the conjunction of them. + return CompositeFilter.create([lhs, rhs], "and" /* CompositeOperator.AND */); +} +function applyDistributionCompositeFilters(lhs, rhs) { + hardAssert(lhs.filters.length > 0 && rhs.filters.length > 0, 0xbb85); + // There are four cases: + // (A & B) & (C & D) --> (A & B & C & D) + // (A & B) & (C | D) --> (A & B & C) | (A & B & D) + // (A | B) & (C & D) --> (C & D & A) | (C & D & B) + // (A | B) & (C | D) --> (A & C) | (A & D) | (B & C) | (B & D) + // Case 1 is a merge. + if (compositeFilterIsConjunction(lhs) && compositeFilterIsConjunction(rhs)) { + return compositeFilterWithAddedFilters(lhs, rhs.getFilters()); + } + // Case 2,3,4 all have at least one side (lhs or rhs) that is a disjunction. In all three cases + // we should take each element of the disjunction and distribute it over the other side, and + // return the disjunction of the distribution results. + const disjunctionSide = compositeFilterIsDisjunction(lhs) ? lhs : rhs; + const otherSide = compositeFilterIsDisjunction(lhs) ? rhs : lhs; + const results = disjunctionSide.filters.map(subfilter => applyDistribution(subfilter, otherSide)); + return CompositeFilter.create(results, "or" /* CompositeOperator.OR */); +} +function applyDistributionFieldAndCompositeFilters(fieldFilter, compositeFilter) { + // There are two cases: + // A & (B & C) --> (A & B & C) + // A & (B | C) --> (A & B) | (A & C) + if (compositeFilterIsConjunction(compositeFilter)) { + // Case 1 + return compositeFilterWithAddedFilters(compositeFilter, fieldFilter.getFilters()); + } + else { + // Case 2 + const newFilters = compositeFilter.filters.map(subfilter => applyDistribution(fieldFilter, subfilter)); + return CompositeFilter.create(newFilters, "or" /* CompositeOperator.OR */); + } +} +/** + * Applies the associativity property to the given filter and returns the resulting filter. + * + *

    + *
  • A | (B | C) == (A | B) | C == (A | B | C) + *
  • A & (B & C) == (A & B) & C == (A & B & C) + *
+ * + *

For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic + */ +function applyAssociation(filter) { + hardAssert(filter instanceof FieldFilter || filter instanceof CompositeFilter, 0x2e4a); + if (filter instanceof FieldFilter) { + return filter; + } + const filters = filter.getFilters(); + // If the composite filter only contains 1 filter, apply associativity to it. + if (filters.length === 1) { + return applyAssociation(filters[0]); + } + // Associativity applied to a flat composite filter results is itself. + if (compositeFilterIsFlat(filter)) { + return filter; + } + // First apply associativity to all subfilters. This will in turn recursively apply + // associativity to all nested composite filters and field filters. + const updatedFilters = filters.map(subfilter => applyAssociation(subfilter)); + // For composite subfilters that perform the same kind of logical operation as `compositeFilter` + // take out their filters and add them to `compositeFilter`. For example: + // compositeFilter = (A | (B | C | D)) + // compositeSubfilter = (B | C | D) + // Result: (A | B | C | D) + // Note that the `compositeSubfilter` has been eliminated, and its filters (B, C, D) have been + // added to the top-level "compositeFilter". + const newSubfilters = []; + updatedFilters.forEach(subfilter => { + if (subfilter instanceof FieldFilter) { + newSubfilters.push(subfilter); + } + else if (subfilter instanceof CompositeFilter) { + if (subfilter.op === filter.op) { + // compositeFilter: (A | (B | C)) + // compositeSubfilter: (B | C) + // Result: (A | B | C) + newSubfilters.push(...subfilter.filters); + } + else { + // compositeFilter: (A | (B & C)) + // compositeSubfilter: (B & C) + // Result: (A | (B & C)) + newSubfilters.push(subfilter); + } + } + }); + if (newSubfilters.length === 1) { + return newSubfilters[0]; + } + return CompositeFilter.create(newSubfilters, filter.op); +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An in-memory implementation of IndexManager. + */ +class MemoryIndexManager { + constructor() { + this.collectionParentIndex = new MemoryCollectionParentIndex(); + } + addToCollectionParentIndex(transaction, collectionPath) { + this.collectionParentIndex.add(collectionPath); + return PersistencePromise.resolve(); + } + getCollectionParents(transaction, collectionId) { + return PersistencePromise.resolve(this.collectionParentIndex.getEntries(collectionId)); + } + addFieldIndex(transaction, index) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(); + } + deleteFieldIndex(transaction, index) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(); + } + deleteAllFieldIndexes(transaction) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(); + } + createTargetIndexes(transaction, target) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(); + } + getDocumentsMatchingTarget(transaction, target) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(null); + } + getIndexType(transaction, target) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(0 /* IndexType.NONE */); + } + getFieldIndexes(transaction, collectionGroup) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve([]); + } + getNextCollectionGroupToUpdate(transaction) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(null); + } + getMinOffset(transaction, target) { + return PersistencePromise.resolve(IndexOffset.min()); + } + getMinOffsetFromCollectionGroup(transaction, collectionGroup) { + return PersistencePromise.resolve(IndexOffset.min()); + } + updateCollectionGroup(transaction, collectionGroup, offset) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(); + } + updateIndexEntries(transaction, documents) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(); + } +} +/** + * Internal implementation of the collection-parent index exposed by MemoryIndexManager. + * Also used for in-memory caching by IndexedDbIndexManager and initial index population + * in indexeddb_schema.ts + */ +class MemoryCollectionParentIndex { + constructor() { + this.index = {}; + } + // Returns false if the entry already existed. + add(collectionPath) { + const collectionId = collectionPath.lastSegment(); + const parentPath = collectionPath.popLast(); + const existingParents = this.index[collectionId] || + new SortedSet(ResourcePath.comparator); + const added = !existingParents.has(parentPath); + this.index[collectionId] = existingParents.add(parentPath); + return added; + } + has(collectionPath) { + const collectionId = collectionPath.lastSegment(); + const parentPath = collectionPath.popLast(); + const existingParents = this.index[collectionId]; + return existingParents && existingParents.has(parentPath); + } + getEntries(collectionId) { + const parentPaths = this.index[collectionId] || + new SortedSet(ResourcePath.comparator); + return parentPaths.toArray(); + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$f = 'IndexedDbIndexManager'; +const EMPTY_VALUE = new Uint8Array(0); +/** + * A persisted implementation of IndexManager. + * + * PORTING NOTE: Unlike iOS and Android, the Web SDK does not memoize index + * data as it supports multi-tab access. + */ +class IndexedDbIndexManager { + constructor(user, databaseId) { + this.databaseId = databaseId; + /** + * An in-memory copy of the index entries we've already written since the SDK + * launched. Used to avoid re-writing the same entry repeatedly. + * + * This is *NOT* a complete cache of what's in persistence and so can never be + * used to satisfy reads. + */ + this.collectionParentsCache = new MemoryCollectionParentIndex(); + /** + * Maps from a target to its equivalent list of sub-targets. Each sub-target + * contains only one term from the target's disjunctive normal form (DNF). + */ + this.targetToDnfSubTargets = new ObjectMap(t => canonifyTarget(t), (l, r) => targetEquals(l, r)); + this.uid = user.uid || ''; + } + /** + * Adds a new entry to the collection parent index. + * + * Repeated calls for the same collectionPath should be avoided within a + * transaction as IndexedDbIndexManager only caches writes once a transaction + * has been committed. + */ + addToCollectionParentIndex(transaction, collectionPath) { + if (!this.collectionParentsCache.has(collectionPath)) { + const collectionId = collectionPath.lastSegment(); + const parentPath = collectionPath.popLast(); + transaction.addOnCommittedListener(() => { + // Add the collection to the in memory cache only if the transaction was + // successfully committed. + this.collectionParentsCache.add(collectionPath); + }); + const collectionParent = { + collectionId, + parent: encodeResourcePath(parentPath) + }; + return collectionParentsStore(transaction).put(collectionParent); + } + return PersistencePromise.resolve(); + } + getCollectionParents(transaction, collectionId) { + const parentPaths = []; + const range = IDBKeyRange.bound([collectionId, ''], [immediateSuccessor(collectionId), ''], + /*lowerOpen=*/ false, + /*upperOpen=*/ true); + return collectionParentsStore(transaction) + .loadAll(range) + .next(entries => { + for (const entry of entries) { + // This collectionId guard shouldn't be necessary (and isn't as long + // as we're running in a real browser), but there's a bug in + // indexeddbshim that breaks our range in our tests running in node: + // https://github.com/axemclion/IndexedDBShim/issues/334 + if (entry.collectionId !== collectionId) { + break; + } + parentPaths.push(decodeResourcePath(entry.parent)); + } + return parentPaths; + }); + } + addFieldIndex(transaction, index) { + // TODO(indexing): Verify that the auto-incrementing index ID works in + // Safari & Firefox. + const indexes = indexConfigurationStore(transaction); + const dbIndex = toDbIndexConfiguration(index); + delete dbIndex.indexId; // `indexId` is auto-populated by IndexedDb + const result = indexes.add(dbIndex); + if (index.indexState) { + const states = indexStateStore(transaction); + return result.next(indexId => { + states.put(toDbIndexState(indexId, this.uid, index.indexState.sequenceNumber, index.indexState.offset)); + }); + } + else { + return result.next(); + } + } + deleteFieldIndex(transaction, index) { + const indexes = indexConfigurationStore(transaction); + const states = indexStateStore(transaction); + const entries = indexEntriesStore(transaction); + return indexes + .delete(index.indexId) + .next(() => states.delete(IDBKeyRange.bound([index.indexId], [index.indexId + 1], + /*lowerOpen=*/ false, + /*upperOpen=*/ true))) + .next(() => entries.delete(IDBKeyRange.bound([index.indexId], [index.indexId + 1], + /*lowerOpen=*/ false, + /*upperOpen=*/ true))); + } + deleteAllFieldIndexes(transaction) { + const indexes = indexConfigurationStore(transaction); + const entries = indexEntriesStore(transaction); + const states = indexStateStore(transaction); + return indexes + .deleteAll() + .next(() => entries.deleteAll()) + .next(() => states.deleteAll()); + } + createTargetIndexes(transaction, target) { + return PersistencePromise.forEach(this.getSubTargets(target), (subTarget) => { + return this.getIndexType(transaction, subTarget).next(type => { + if (type === 0 /* IndexType.NONE */ || type === 1 /* IndexType.PARTIAL */) { + const targetIndexMatcher = new TargetIndexMatcher(subTarget); + const fieldIndex = targetIndexMatcher.buildTargetIndex(); + if (fieldIndex != null) { + return this.addFieldIndex(transaction, fieldIndex); + } + } + }); + }); + } + getDocumentsMatchingTarget(transaction, target) { + const indexEntries = indexEntriesStore(transaction); + let canServeTarget = true; + const indexes = new Map(); + return PersistencePromise.forEach(this.getSubTargets(target), (subTarget) => { + return this.getFieldIndex(transaction, subTarget).next(index => { + canServeTarget && (canServeTarget = !!index); + indexes.set(subTarget, index); + }); + }).next(() => { + if (!canServeTarget) { + return PersistencePromise.resolve(null); + } + else { + let existingKeys = documentKeySet(); + const result = []; + return PersistencePromise.forEach(indexes, (index, subTarget) => { + logDebug(LOG_TAG$f, `Using index ${fieldIndexToString(index)} to execute ${canonifyTarget(target)}`); + const arrayValues = targetGetArrayValues(subTarget, index); + const notInValues = targetGetNotInValues(subTarget, index); + const lowerBound = targetGetLowerBound(subTarget, index); + const upperBound = targetGetUpperBound(subTarget, index); + const lowerBoundEncoded = this.encodeBound(index, subTarget, lowerBound); + const upperBoundEncoded = this.encodeBound(index, subTarget, upperBound); + const notInEncoded = this.encodeValues(index, subTarget, notInValues); + const indexRanges = this.generateIndexRanges(index.indexId, arrayValues, lowerBoundEncoded, lowerBound.inclusive, upperBoundEncoded, upperBound.inclusive, notInEncoded); + return PersistencePromise.forEach(indexRanges, (indexRange) => { + return indexEntries + .loadFirst(indexRange, target.limit) + .next(entries => { + entries.forEach(entry => { + const documentKey = DocumentKey.fromSegments(entry.documentKey); + if (!existingKeys.has(documentKey)) { + existingKeys = existingKeys.add(documentKey); + result.push(documentKey); + } + }); + }); + }); + }).next(() => result); + } + }); + } + getSubTargets(target) { + let subTargets = this.targetToDnfSubTargets.get(target); + if (subTargets) { + return subTargets; + } + if (target.filters.length === 0) { + subTargets = [target]; + } + else { + // There is an implicit AND operation between all the filters stored in the target + const dnf = getDnfTerms(CompositeFilter.create(target.filters, "and" /* CompositeOperator.AND */)); + subTargets = dnf.map(term => newTarget(target.path, target.collectionGroup, target.orderBy, term.getFilters(), target.limit, target.startAt, target.endAt)); + } + this.targetToDnfSubTargets.set(target, subTargets); + return subTargets; + } + /** + * Constructs a key range query on `DbIndexEntryStore` that unions all + * bounds. + */ + generateIndexRanges(indexId, arrayValues, lowerBounds, lowerBoundInclusive, upperBounds, upperBoundInclusive, notInValues) { + // The number of total index scans we union together. This is similar to a + // distributed normal form, but adapted for array values. We create a single + // index range per value in an ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filter + // combined with the values from the query bounds. + const totalScans = (arrayValues != null ? arrayValues.length : 1) * + Math.max(lowerBounds.length, upperBounds.length); + const scansPerArrayElement = totalScans / (arrayValues != null ? arrayValues.length : 1); + const indexRanges = []; + for (let i = 0; i < totalScans; ++i) { + const arrayValue = arrayValues + ? this.encodeSingleElement(arrayValues[i / scansPerArrayElement]) + : EMPTY_VALUE; + const lowerBound = this.generateLowerBound(indexId, arrayValue, lowerBounds[i % scansPerArrayElement], lowerBoundInclusive); + const upperBound = this.generateUpperBound(indexId, arrayValue, upperBounds[i % scansPerArrayElement], upperBoundInclusive); + const notInBound = notInValues.map(notIn => this.generateLowerBound(indexId, arrayValue, notIn, + /* inclusive= */ true)); + indexRanges.push(...this.createRange(lowerBound, upperBound, notInBound)); + } + return indexRanges; + } + /** Generates the lower bound for `arrayValue` and `directionalValue`. */ + generateLowerBound(indexId, arrayValue, directionalValue, inclusive) { + const entry = new IndexEntry(indexId, DocumentKey.empty(), arrayValue, directionalValue); + return inclusive ? entry : entry.successor(); + } + /** Generates the upper bound for `arrayValue` and `directionalValue`. */ + generateUpperBound(indexId, arrayValue, directionalValue, inclusive) { + const entry = new IndexEntry(indexId, DocumentKey.empty(), arrayValue, directionalValue); + return inclusive ? entry.successor() : entry; + } + getFieldIndex(transaction, target) { + const targetIndexMatcher = new TargetIndexMatcher(target); + const collectionGroup = target.collectionGroup != null + ? target.collectionGroup + : target.path.lastSegment(); + return this.getFieldIndexes(transaction, collectionGroup).next(indexes => { + // Return the index with the most number of segments. + let index = null; + for (const candidate of indexes) { + const matches = targetIndexMatcher.servedByIndex(candidate); + if (matches && + (!index || candidate.fields.length > index.fields.length)) { + index = candidate; + } + } + return index; + }); + } + getIndexType(transaction, target) { + let indexType = 2 /* IndexType.FULL */; + const subTargets = this.getSubTargets(target); + return PersistencePromise.forEach(subTargets, (target) => { + return this.getFieldIndex(transaction, target).next(index => { + if (!index) { + indexType = 0 /* IndexType.NONE */; + } + else if (indexType !== 0 /* IndexType.NONE */ && + index.fields.length < targetGetSegmentCount(target)) { + indexType = 1 /* IndexType.PARTIAL */; + } + }); + }).next(() => { + // OR queries have more than one sub-target (one sub-target per DNF term). We currently consider + // OR queries that have a `limit` to have a partial index. For such queries we perform sorting + // and apply the limit in memory as a post-processing step. + if (targetHasLimit(target) && + subTargets.length > 1 && + indexType === 2 /* IndexType.FULL */) { + return 1 /* IndexType.PARTIAL */; + } + return indexType; + }); + } + /** + * Returns the byte encoded form of the directional values in the field index. + * Returns `null` if the document does not have all fields specified in the + * index. + */ + encodeDirectionalElements(fieldIndex, document) { + const encoder = new IndexByteEncoder(); + for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) { + const field = document.data.field(segment.fieldPath); + if (field == null) { + return null; + } + const directionalEncoder = encoder.forKind(segment.kind); + FirestoreIndexValueWriter.INSTANCE.writeIndexValue(field, directionalEncoder); + } + return encoder.encodedBytes(); + } + /** Encodes a single value to the ascending index format. */ + encodeSingleElement(value) { + const encoder = new IndexByteEncoder(); + FirestoreIndexValueWriter.INSTANCE.writeIndexValue(value, encoder.forKind(0 /* IndexKind.ASCENDING */)); + return encoder.encodedBytes(); + } + /** + * Returns an encoded form of the document key that sorts based on the key + * ordering of the field index. + */ + encodeDirectionalKey(fieldIndex, documentKey) { + const encoder = new IndexByteEncoder(); + FirestoreIndexValueWriter.INSTANCE.writeIndexValue(refValue(this.databaseId, documentKey), encoder.forKind(fieldIndexGetKeyOrder(fieldIndex))); + return encoder.encodedBytes(); + } + /** + * Encodes the given field values according to the specification in `target`. + * For IN queries, a list of possible values is returned. + */ + encodeValues(fieldIndex, target, values) { + if (values === null) { + return []; + } + let encoders = []; + encoders.push(new IndexByteEncoder()); + let valueIdx = 0; + for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) { + const value = values[valueIdx++]; + for (const encoder of encoders) { + if (this.isInFilter(target, segment.fieldPath) && isArray(value)) { + encoders = this.expandIndexValues(encoders, segment, value); + } + else { + const directionalEncoder = encoder.forKind(segment.kind); + FirestoreIndexValueWriter.INSTANCE.writeIndexValue(value, directionalEncoder); + } + } + } + return this.getEncodedBytes(encoders); + } + /** + * Encodes the given bounds according to the specification in `target`. For IN + * queries, a list of possible values is returned. + */ + encodeBound(fieldIndex, target, bound) { + return this.encodeValues(fieldIndex, target, bound.position); + } + /** Returns the byte representation for the provided encoders. */ + getEncodedBytes(encoders) { + const result = []; + for (let i = 0; i < encoders.length; ++i) { + result[i] = encoders[i].encodedBytes(); + } + return result; + } + /** + * Creates a separate encoder for each element of an array. + * + * The method appends each value to all existing encoders (e.g. filter("a", + * "==", "a1").filter("b", "in", ["b1", "b2"]) becomes ["a1,b1", "a1,b2"]). A + * list of new encoders is returned. + */ + expandIndexValues(encoders, segment, value) { + const prefixes = [...encoders]; + const results = []; + for (const arrayElement of value.arrayValue.values || []) { + for (const prefix of prefixes) { + const clonedEncoder = new IndexByteEncoder(); + clonedEncoder.seed(prefix.encodedBytes()); + FirestoreIndexValueWriter.INSTANCE.writeIndexValue(arrayElement, clonedEncoder.forKind(segment.kind)); + results.push(clonedEncoder); + } + } + return results; + } + isInFilter(target, fieldPath) { + return !!target.filters.find(f => f instanceof FieldFilter && + f.field.isEqual(fieldPath) && + (f.op === "in" /* Operator.IN */ || f.op === "not-in" /* Operator.NOT_IN */)); + } + getFieldIndexes(transaction, collectionGroup) { + const indexes = indexConfigurationStore(transaction); + const states = indexStateStore(transaction); + return (collectionGroup + ? indexes.loadAll(DbIndexConfigurationCollectionGroupIndex, IDBKeyRange.bound(collectionGroup, collectionGroup)) + : indexes.loadAll()).next(indexConfigs => { + const result = []; + return PersistencePromise.forEach(indexConfigs, (indexConfig) => { + return states + .get([indexConfig.indexId, this.uid]) + .next(indexState => { + result.push(fromDbIndexConfiguration(indexConfig, indexState)); + }); + }).next(() => result); + }); + } + getNextCollectionGroupToUpdate(transaction) { + return this.getFieldIndexes(transaction).next(indexes => { + if (indexes.length === 0) { + return null; + } + indexes.sort((l, r) => { + const cmp = l.indexState.sequenceNumber - r.indexState.sequenceNumber; + return cmp !== 0 + ? cmp + : primitiveComparator(l.collectionGroup, r.collectionGroup); + }); + return indexes[0].collectionGroup; + }); + } + updateCollectionGroup(transaction, collectionGroup, offset) { + const indexes = indexConfigurationStore(transaction); + const states = indexStateStore(transaction); + return this.getNextSequenceNumber(transaction).next(nextSequenceNumber => indexes + .loadAll(DbIndexConfigurationCollectionGroupIndex, IDBKeyRange.bound(collectionGroup, collectionGroup)) + .next(configs => PersistencePromise.forEach(configs, (config) => states.put(toDbIndexState(config.indexId, this.uid, nextSequenceNumber, offset))))); + } + updateIndexEntries(transaction, documents) { + // Porting Note: `getFieldIndexes()` on Web does not cache index lookups as + // it could be used across different IndexedDB transactions. As any cached + // data might be invalidated by other multi-tab clients, we can only trust + // data within a single IndexedDB transaction. We therefore add a cache + // here. + const memoizedIndexes = new Map(); + return PersistencePromise.forEach(documents, (key, doc) => { + const memoizedCollectionIndexes = memoizedIndexes.get(key.collectionGroup); + const fieldIndexes = memoizedCollectionIndexes + ? PersistencePromise.resolve(memoizedCollectionIndexes) + : this.getFieldIndexes(transaction, key.collectionGroup); + return fieldIndexes.next(fieldIndexes => { + memoizedIndexes.set(key.collectionGroup, fieldIndexes); + return PersistencePromise.forEach(fieldIndexes, (fieldIndex) => { + return this.getExistingIndexEntries(transaction, key, fieldIndex).next(existingEntries => { + const newEntries = this.computeIndexEntries(doc, fieldIndex); + if (!existingEntries.isEqual(newEntries)) { + return this.updateEntries(transaction, doc, fieldIndex, existingEntries, newEntries); + } + return PersistencePromise.resolve(); + }); + }); + }); + }); + } + addIndexEntry(transaction, document, fieldIndex, indexEntry) { + const indexEntries = indexEntriesStore(transaction); + return indexEntries.put(indexEntry.dbIndexEntry(this.uid, this.encodeDirectionalKey(fieldIndex, document.key), document.key)); + } + deleteIndexEntry(transaction, document, fieldIndex, indexEntry) { + const indexEntries = indexEntriesStore(transaction); + return indexEntries.delete(indexEntry.dbIndexEntryKey(this.uid, this.encodeDirectionalKey(fieldIndex, document.key), document.key)); + } + getExistingIndexEntries(transaction, documentKey, fieldIndex) { + const indexEntries = indexEntriesStore(transaction); + let results = new SortedSet(indexEntryComparator); + return indexEntries + .iterate({ + index: DbIndexEntryDocumentKeyIndex, + range: IDBKeyRange.only([ + fieldIndex.indexId, + this.uid, + encodeKeySafeBytes(this.encodeDirectionalKey(fieldIndex, documentKey)) + ]) + }, (_, entry) => { + results = results.add(new IndexEntry(fieldIndex.indexId, documentKey, decodeKeySafeBytes(entry.arrayValue), decodeKeySafeBytes(entry.directionalValue))); + }) + .next(() => results); + } + /** Creates the index entries for the given document. */ + computeIndexEntries(document, fieldIndex) { + let results = new SortedSet(indexEntryComparator); + const directionalValue = this.encodeDirectionalElements(fieldIndex, document); + if (directionalValue == null) { + return results; + } + const arraySegment = fieldIndexGetArraySegment(fieldIndex); + if (arraySegment != null) { + const value = document.data.field(arraySegment.fieldPath); + if (isArray(value)) { + for (const arrayValue of value.arrayValue.values || []) { + results = results.add(new IndexEntry(fieldIndex.indexId, document.key, this.encodeSingleElement(arrayValue), directionalValue)); + } + } + } + else { + results = results.add(new IndexEntry(fieldIndex.indexId, document.key, EMPTY_VALUE, directionalValue)); + } + return results; + } + /** + * Updates the index entries for the provided document by deleting entries + * that are no longer referenced in `newEntries` and adding all newly added + * entries. + */ + updateEntries(transaction, document, fieldIndex, existingEntries, newEntries) { + logDebug(LOG_TAG$f, "Updating index entries for document '%s'", document.key); + const promises = []; + diffSortedSets(existingEntries, newEntries, indexEntryComparator, + /* onAdd= */ entry => { + promises.push(this.addIndexEntry(transaction, document, fieldIndex, entry)); + }, + /* onRemove= */ entry => { + promises.push(this.deleteIndexEntry(transaction, document, fieldIndex, entry)); + }); + return PersistencePromise.waitFor(promises); + } + getNextSequenceNumber(transaction) { + let nextSequenceNumber = 1; + const states = indexStateStore(transaction); + return states + .iterate({ + index: DbIndexStateSequenceNumberIndex, + reverse: true, + range: IDBKeyRange.upperBound([this.uid, Number.MAX_SAFE_INTEGER]) + }, (_, state, controller) => { + controller.done(); + nextSequenceNumber = state.sequenceNumber + 1; + }) + .next(() => nextSequenceNumber); + } + /** + * Returns a new set of IDB ranges that splits the existing range and excludes + * any values that match the `notInValue` from these ranges. As an example, + * '[foo > 2 && foo != 3]` becomes `[foo > 2 && < 3, foo > 3]`. + */ + createRange(lower, upper, notInValues) { + // The notIn values need to be sorted and unique so that we can return a + // sorted set of non-overlapping ranges. + notInValues = notInValues + .sort((l, r) => indexEntryComparator(l, r)) + .filter((el, i, values) => !i || indexEntryComparator(el, values[i - 1]) !== 0); + const bounds = []; + bounds.push(lower); + for (const notInValue of notInValues) { + const cmpToLower = indexEntryComparator(notInValue, lower); + const cmpToUpper = indexEntryComparator(notInValue, upper); + if (cmpToLower === 0) { + // `notInValue` is the lower bound. We therefore need to raise the bound + // to the next value. + bounds[0] = lower.successor(); + } + else if (cmpToLower > 0 && cmpToUpper < 0) { + // `notInValue` is in the middle of the range + bounds.push(notInValue); + bounds.push(notInValue.successor()); + } + else if (cmpToUpper > 0) { + // `notInValue` (and all following values) are out of the range + break; + } + } + bounds.push(upper); + const ranges = []; + for (let i = 0; i < bounds.length; i += 2) { + // If we encounter two bounds that will create an unmatchable key range, + // then we return an empty set of key ranges. + if (this.isRangeMatchable(bounds[i], bounds[i + 1])) { + return []; + } + const lowerBound = bounds[i].dbIndexEntryKey(this.uid, EMPTY_VALUE, DocumentKey.empty()); + const upperBound = bounds[i + 1].dbIndexEntryKey(this.uid, EMPTY_VALUE, DocumentKey.empty()); + ranges.push(IDBKeyRange.bound(lowerBound, upperBound)); + } + return ranges; + } + isRangeMatchable(lowerBound, upperBound) { + // If lower bound is greater than the upper bound, then the key + // range can never be matched. + return indexEntryComparator(lowerBound, upperBound) > 0; + } + getMinOffsetFromCollectionGroup(transaction, collectionGroup) { + return this.getFieldIndexes(transaction, collectionGroup).next(getMinOffsetFromFieldIndexes); + } + getMinOffset(transaction, target) { + return PersistencePromise.mapArray(this.getSubTargets(target), (subTarget) => this.getFieldIndex(transaction, subTarget).next(index => index ? index : fail(0xad8a))).next(getMinOffsetFromFieldIndexes); + } +} +/** + * Helper to get a typed SimpleDbStore for the collectionParents + * document store. + */ +function collectionParentsStore(txn) { + return getStore(txn, DbCollectionParentStore); +} +/** + * Helper to get a typed SimpleDbStore for the index entry object store. + */ +function indexEntriesStore(txn) { + return getStore(txn, DbIndexEntryStore); +} +/** + * Helper to get a typed SimpleDbStore for the index configuration object store. + */ +function indexConfigurationStore(txn) { + return getStore(txn, DbIndexConfigurationStore); +} +/** + * Helper to get a typed SimpleDbStore for the index state object store. + */ +function indexStateStore(txn) { + return getStore(txn, DbIndexStateStore); +} +function getMinOffsetFromFieldIndexes(fieldIndexes) { + hardAssert(fieldIndexes.length !== 0, 0x7099); + let minOffset = fieldIndexes[0].indexState.offset; + let maxBatchId = minOffset.largestBatchId; + for (let i = 1; i < fieldIndexes.length; i++) { + const newOffset = fieldIndexes[i].indexState.offset; + if (indexOffsetComparator(newOffset, minOffset) < 0) { + minOffset = newOffset; + } + if (maxBatchId < newOffset.largestBatchId) { + maxBatchId = newOffset.largestBatchId; + } + } + return new IndexOffset(minOffset.readTime, minOffset.documentKey, maxBatchId); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Delete a mutation batch and the associated document mutations. + * @returns A PersistencePromise of the document mutations that were removed. + */ +function removeMutationBatch(txn, userId, batch) { + const mutationStore = txn.store(DbMutationBatchStore); + const indexTxn = txn.store(DbDocumentMutationStore); + const promises = []; + const range = IDBKeyRange.only(batch.batchId); + let numDeleted = 0; + const removePromise = mutationStore.iterate({ range }, (key, value, control) => { + numDeleted++; + return control.delete(); + }); + promises.push(removePromise.next(() => { + hardAssert(numDeleted === 1, 0xb7de, { batchId: batch.batchId }); + })); + const removedDocuments = []; + for (const mutation of batch.mutations) { + const indexKey = newDbDocumentMutationKey(userId, mutation.key.path, batch.batchId); + promises.push(indexTxn.delete(indexKey)); + removedDocuments.push(mutation.key); + } + return PersistencePromise.waitFor(promises).next(() => removedDocuments); +} +/** + * Returns an approximate size for the given document. + */ +function dbDocumentSize(doc) { + if (!doc) { + return 0; + } + let value; + if (doc.document) { + value = doc.document; + } + else if (doc.unknownDocument) { + value = doc.unknownDocument; + } + else if (doc.noDocument) { + value = doc.noDocument; + } + else { + throw fail(0x398b); + } + return JSON.stringify(value).length; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** A mutation queue for a specific user, backed by IndexedDB. */ +class IndexedDbMutationQueue { + constructor( + /** + * The normalized userId (e.g. null UID => "" userId) used to store / + * retrieve mutations. + */ + userId, serializer, indexManager, referenceDelegate) { + this.userId = userId; + this.serializer = serializer; + this.indexManager = indexManager; + this.referenceDelegate = referenceDelegate; + /** + * Caches the document keys for pending mutation batches. If the mutation + * has been removed from IndexedDb, the cached value may continue to + * be used to retrieve the batch's document keys. To remove a cached value + * locally, `removeCachedMutationKeys()` should be invoked either directly + * or through `removeMutationBatches()`. + * + * With multi-tab, when the primary client acknowledges or rejects a mutation, + * this cache is used by secondary clients to invalidate the local + * view of the documents that were previously affected by the mutation. + */ + // PORTING NOTE: Multi-tab only. + this.documentKeysByBatchId = {}; + } + /** + * Creates a new mutation queue for the given user. + * @param user - The user for which to create a mutation queue. + * @param serializer - The serializer to use when persisting to IndexedDb. + */ + static forUser(user, serializer, indexManager, referenceDelegate) { + // TODO(mcg): Figure out what constraints there are on userIDs + // In particular, are there any reserved characters? are empty ids allowed? + // For the moment store these together in the same mutations table assuming + // that empty userIDs aren't allowed. + hardAssert(user.uid !== '', 0xfb83); + const userId = user.isAuthenticated() ? user.uid : ''; + return new IndexedDbMutationQueue(userId, serializer, indexManager, referenceDelegate); + } + checkEmpty(transaction) { + let empty = true; + const range = IDBKeyRange.bound([this.userId, Number.NEGATIVE_INFINITY], [this.userId, Number.POSITIVE_INFINITY]); + return mutationsStore(transaction) + .iterate({ index: DbMutationBatchUserMutationsIndex, range }, (key, value, control) => { + empty = false; + control.done(); + }) + .next(() => empty); + } + addMutationBatch(transaction, localWriteTime, baseMutations, mutations) { + const documentStore = documentMutationsStore(transaction); + const mutationStore = mutationsStore(transaction); + // The IndexedDb implementation in Chrome (and Firefox) does not handle + // compound indices that include auto-generated keys correctly. To ensure + // that the index entry is added correctly in all browsers, we perform two + // writes: The first write is used to retrieve the next auto-generated Batch + // ID, and the second write populates the index and stores the actual + // mutation batch. + // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972 + // We write an empty object to obtain key + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return mutationStore.add({}).next(batchId => { + hardAssert(typeof batchId === 'number', 0xbf7b); + const batch = new MutationBatch(batchId, localWriteTime, baseMutations, mutations); + const dbBatch = toDbMutationBatch(this.serializer, this.userId, batch); + const promises = []; + let collectionParents = new SortedSet((l, r) => primitiveComparator(l.canonicalString(), r.canonicalString())); + for (const mutation of mutations) { + const indexKey = newDbDocumentMutationKey(this.userId, mutation.key.path, batchId); + collectionParents = collectionParents.add(mutation.key.path.popLast()); + promises.push(mutationStore.put(dbBatch)); + promises.push(documentStore.put(indexKey, DbDocumentMutationPlaceholder)); + } + collectionParents.forEach(parent => { + promises.push(this.indexManager.addToCollectionParentIndex(transaction, parent)); + }); + transaction.addOnCommittedListener(() => { + this.documentKeysByBatchId[batchId] = batch.keys(); + }); + return PersistencePromise.waitFor(promises).next(() => batch); + }); + } + lookupMutationBatch(transaction, batchId) { + return mutationsStore(transaction) + .get(batchId) + .next(dbBatch => { + if (dbBatch) { + hardAssert(dbBatch.userId === this.userId, 0x0030, `Unexpected user for mutation batch`, { + userId: dbBatch.userId, + batchId + }); + return fromDbMutationBatch(this.serializer, dbBatch); + } + return null; + }); + } + /** + * Returns the document keys for the mutation batch with the given batchId. + * For primary clients, this method returns `null` after + * `removeMutationBatches()` has been called. Secondary clients return a + * cached result until `removeCachedMutationKeys()` is invoked. + */ + // PORTING NOTE: Multi-tab only. + lookupMutationKeys(transaction, batchId) { + if (this.documentKeysByBatchId[batchId]) { + return PersistencePromise.resolve(this.documentKeysByBatchId[batchId]); + } + else { + return this.lookupMutationBatch(transaction, batchId).next(batch => { + if (batch) { + const keys = batch.keys(); + this.documentKeysByBatchId[batchId] = keys; + return keys; + } + else { + return null; + } + }); + } + } + getNextMutationBatchAfterBatchId(transaction, batchId) { + const nextBatchId = batchId + 1; + const range = IDBKeyRange.lowerBound([this.userId, nextBatchId]); + let foundBatch = null; + return mutationsStore(transaction) + .iterate({ index: DbMutationBatchUserMutationsIndex, range }, (key, dbBatch, control) => { + if (dbBatch.userId === this.userId) { + hardAssert(dbBatch.batchId >= nextBatchId, 0xb9a4, { nextBatchId }); + foundBatch = fromDbMutationBatch(this.serializer, dbBatch); + } + control.done(); + }) + .next(() => foundBatch); + } + getHighestUnacknowledgedBatchId(transaction) { + const range = IDBKeyRange.upperBound([ + this.userId, + Number.POSITIVE_INFINITY + ]); + let batchId = BATCHID_UNKNOWN; + return mutationsStore(transaction) + .iterate({ index: DbMutationBatchUserMutationsIndex, range, reverse: true }, (key, dbBatch, control) => { + batchId = dbBatch.batchId; + control.done(); + }) + .next(() => batchId); + } + getAllMutationBatches(transaction) { + const range = IDBKeyRange.bound([this.userId, BATCHID_UNKNOWN], [this.userId, Number.POSITIVE_INFINITY]); + return mutationsStore(transaction) + .loadAll(DbMutationBatchUserMutationsIndex, range) + .next(dbBatches => dbBatches.map(dbBatch => fromDbMutationBatch(this.serializer, dbBatch))); + } + getAllMutationBatchesAffectingDocumentKey(transaction, documentKey) { + // Scan the document-mutation index starting with a prefix starting with + // the given documentKey. + const indexPrefix = newDbDocumentMutationPrefixForPath(this.userId, documentKey.path); + const indexStart = IDBKeyRange.lowerBound(indexPrefix); + const results = []; + return documentMutationsStore(transaction) + .iterate({ range: indexStart }, (indexKey, _, control) => { + const [userID, encodedPath, batchId] = indexKey; + // Only consider rows matching exactly the specific key of + // interest. Note that because we order by path first, and we + // order terminators before path separators, we'll encounter all + // the index rows for documentKey contiguously. In particular, all + // the rows for documentKey will occur before any rows for + // documents nested in a subcollection beneath documentKey so we + // can stop as soon as we hit any such row. + const path = decodeResourcePath(encodedPath); + if (userID !== this.userId || !documentKey.path.isEqual(path)) { + control.done(); + return; + } + // Look up the mutation batch in the store. + return mutationsStore(transaction) + .get(batchId) + .next(mutation => { + if (!mutation) { + throw fail(0xf028, { + indexKey, + batchId + }); + } + hardAssert(mutation.userId === this.userId, 0x2907, `Unexpected user for mutation batch`, { + userId: mutation.userId, + batchId + }); + results.push(fromDbMutationBatch(this.serializer, mutation)); + }); + }) + .next(() => results); + } + getAllMutationBatchesAffectingDocumentKeys(transaction, documentKeys) { + let uniqueBatchIDs = new SortedSet(primitiveComparator); + const promises = []; + documentKeys.forEach(documentKey => { + const indexStart = newDbDocumentMutationPrefixForPath(this.userId, documentKey.path); + const range = IDBKeyRange.lowerBound(indexStart); + const promise = documentMutationsStore(transaction).iterate({ range }, (indexKey, _, control) => { + const [userID, encodedPath, batchID] = indexKey; + // Only consider rows matching exactly the specific key of + // interest. Note that because we order by path first, and we + // order terminators before path separators, we'll encounter all + // the index rows for documentKey contiguously. In particular, all + // the rows for documentKey will occur before any rows for + // documents nested in a subcollection beneath documentKey so we + // can stop as soon as we hit any such row. + const path = decodeResourcePath(encodedPath); + if (userID !== this.userId || !documentKey.path.isEqual(path)) { + control.done(); + return; + } + uniqueBatchIDs = uniqueBatchIDs.add(batchID); + }); + promises.push(promise); + }); + return PersistencePromise.waitFor(promises).next(() => this.lookupMutationBatches(transaction, uniqueBatchIDs)); + } + getAllMutationBatchesAffectingQuery(transaction, query) { + const queryPath = query.path; + const immediateChildrenLength = queryPath.length + 1; + // TODO(mcg): Actually implement a single-collection query + // + // This is actually executing an ancestor query, traversing the whole + // subtree below the collection which can be horrifically inefficient for + // some structures. The right way to solve this is to implement the full + // value index, but that's not in the cards in the near future so this is + // the best we can do for the moment. + // + // Since we don't yet index the actual properties in the mutations, our + // current approach is to just return all mutation batches that affect + // documents in the collection being queried. + const indexPrefix = newDbDocumentMutationPrefixForPath(this.userId, queryPath); + const indexStart = IDBKeyRange.lowerBound(indexPrefix); + // Collect up unique batchIDs encountered during a scan of the index. Use a + // SortedSet to accumulate batch IDs so they can be traversed in order in a + // scan of the main table. + let uniqueBatchIDs = new SortedSet(primitiveComparator); + return documentMutationsStore(transaction) + .iterate({ range: indexStart }, (indexKey, _, control) => { + const [userID, encodedPath, batchID] = indexKey; + const path = decodeResourcePath(encodedPath); + if (userID !== this.userId || !queryPath.isPrefixOf(path)) { + control.done(); + return; + } + // Rows with document keys more than one segment longer than the + // query path can't be matches. For example, a query on 'rooms' + // can't match the document /rooms/abc/messages/xyx. + // TODO(mcg): we'll need a different scanner when we implement + // ancestor queries. + if (path.length !== immediateChildrenLength) { + return; + } + uniqueBatchIDs = uniqueBatchIDs.add(batchID); + }) + .next(() => this.lookupMutationBatches(transaction, uniqueBatchIDs)); + } + lookupMutationBatches(transaction, batchIDs) { + const results = []; + const promises = []; + // TODO(rockwood): Implement this using iterate. + batchIDs.forEach(batchId => { + promises.push(mutationsStore(transaction) + .get(batchId) + .next(mutation => { + if (mutation === null) { + throw fail(0x89ca, { + batchId + }); + } + hardAssert(mutation.userId === this.userId, 0x2614, `Unexpected user for mutation batch`, { userId: mutation.userId, batchId }); + results.push(fromDbMutationBatch(this.serializer, mutation)); + })); + }); + return PersistencePromise.waitFor(promises).next(() => results); + } + removeMutationBatch(transaction, batch) { + return removeMutationBatch(transaction.simpleDbTransaction, this.userId, batch).next(removedDocuments => { + transaction.addOnCommittedListener(() => { + this.removeCachedMutationKeys(batch.batchId); + }); + return PersistencePromise.forEach(removedDocuments, (key) => { + return this.referenceDelegate.markPotentiallyOrphaned(transaction, key); + }); + }); + } + /** + * Clears the cached keys for a mutation batch. This method should be + * called by secondary clients after they process mutation updates. + * + * Note that this method does not have to be called from primary clients as + * the corresponding cache entries are cleared when an acknowledged or + * rejected batch is removed from the mutation queue. + */ + // PORTING NOTE: Multi-tab only + removeCachedMutationKeys(batchId) { + delete this.documentKeysByBatchId[batchId]; + } + performConsistencyCheck(txn) { + return this.checkEmpty(txn).next(empty => { + if (!empty) { + return PersistencePromise.resolve(); + } + // Verify that there are no entries in the documentMutations index if + // the queue is empty. + const startRange = IDBKeyRange.lowerBound(newDbDocumentMutationPrefixForUser(this.userId)); + const danglingMutationReferences = []; + return documentMutationsStore(txn) + .iterate({ range: startRange }, (key, _, control) => { + const userID = key[0]; + if (userID !== this.userId) { + control.done(); + return; + } + else { + const path = decodeResourcePath(key[1]); + danglingMutationReferences.push(path); + } + }) + .next(() => { + hardAssert(danglingMutationReferences.length === 0, 0xdd90, { + danglingKeys: danglingMutationReferences.map(p => p.canonicalString()) + }); + }); + }); + } + containsKey(txn, key) { + return mutationQueueContainsKey(txn, this.userId, key); + } + // PORTING NOTE: Multi-tab only (state is held in memory in other clients). + /** Returns the mutation queue's metadata from IndexedDb. */ + getMutationQueueMetadata(transaction) { + return mutationQueuesStore(transaction) + .get(this.userId) + .next((metadata) => { + return (metadata || { + userId: this.userId, + lastAcknowledgedBatchId: BATCHID_UNKNOWN, + lastStreamToken: '' + }); + }); + } +} +/** + * @returns true if the mutation queue for the given user contains a pending + * mutation for the given key. + */ +function mutationQueueContainsKey(txn, userId, key) { + const indexKey = newDbDocumentMutationPrefixForPath(userId, key.path); + const encodedPath = indexKey[1]; + const startRange = IDBKeyRange.lowerBound(indexKey); + let containsKey = false; + return documentMutationsStore(txn) + .iterate({ range: startRange, keysOnly: true }, (key, value, control) => { + const [userID, keyPath, /*batchID*/ _] = key; + if (userID === userId && keyPath === encodedPath) { + containsKey = true; + } + control.done(); + }) + .next(() => containsKey); +} +/** Returns true if any mutation queue contains the given document. */ +function mutationQueuesContainKey(txn, docKey) { + let found = false; + return mutationQueuesStore(txn) + .iterateSerial(userId => { + return mutationQueueContainsKey(txn, userId, docKey).next(containsKey => { + if (containsKey) { + found = true; + } + return PersistencePromise.resolve(!containsKey); + }); + }) + .next(() => found); +} +/** + * Helper to get a typed SimpleDbStore for the mutations object store. + */ +function mutationsStore(txn) { + return getStore(txn, DbMutationBatchStore); +} +/** + * Helper to get a typed SimpleDbStore for the mutationQueues object store. + */ +function documentMutationsStore(txn) { + return getStore(txn, DbDocumentMutationStore); +} +/** + * Helper to get a typed SimpleDbStore for the mutationQueues object store. + */ +function mutationQueuesStore(txn) { + return getStore(txn, DbMutationQueueStore); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Offset to ensure non-overlapping target ids. */ +const OFFSET = 2; +/** + * Generates monotonically increasing target IDs for sending targets to the + * watch stream. + * + * The client constructs two generators, one for the target cache, and one for + * for the sync engine (to generate limbo documents targets). These + * generators produce non-overlapping IDs (by using even and odd IDs + * respectively). + * + * By separating the target ID space, the query cache can generate target IDs + * that persist across client restarts, while sync engine can independently + * generate in-memory target IDs that are transient and can be reused after a + * restart. + */ +class TargetIdGenerator { + constructor(lastId) { + this.lastId = lastId; + } + next() { + this.lastId += OFFSET; + return this.lastId; + } + static forTargetCache() { + // The target cache generator must return '2' in its first call to `next()` + // as there is no differentiation in the protocol layer between an unset + // number and the number '0'. If we were to sent a target with target ID + // '0', the backend would consider it unset and replace it with its own ID. + return new TargetIdGenerator(2 - OFFSET); + } + static forSyncEngine() { + // Sync engine assigns target IDs for limbo document detection. + return new TargetIdGenerator(1 - OFFSET); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class IndexedDbTargetCache { + constructor(referenceDelegate, serializer) { + this.referenceDelegate = referenceDelegate; + this.serializer = serializer; + } + // PORTING NOTE: We don't cache global metadata for the target cache, since + // some of it (in particular `highestTargetId`) can be modified by secondary + // tabs. We could perhaps be more granular (and e.g. still cache + // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go + // to IndexedDb whenever we need to read metadata. We can revisit if it turns + // out to have a meaningful performance impact. + allocateTargetId(transaction) { + return this.retrieveMetadata(transaction).next(metadata => { + const targetIdGenerator = new TargetIdGenerator(metadata.highestTargetId); + metadata.highestTargetId = targetIdGenerator.next(); + return this.saveMetadata(transaction, metadata).next(() => metadata.highestTargetId); + }); + } + getLastRemoteSnapshotVersion(transaction) { + return this.retrieveMetadata(transaction).next(metadata => { + return SnapshotVersion.fromTimestamp(new Timestamp(metadata.lastRemoteSnapshotVersion.seconds, metadata.lastRemoteSnapshotVersion.nanoseconds)); + }); + } + getHighestSequenceNumber(transaction) { + return this.retrieveMetadata(transaction).next(targetGlobal => targetGlobal.highestListenSequenceNumber); + } + setTargetsMetadata(transaction, highestListenSequenceNumber, lastRemoteSnapshotVersion) { + return this.retrieveMetadata(transaction).next(metadata => { + metadata.highestListenSequenceNumber = highestListenSequenceNumber; + if (lastRemoteSnapshotVersion) { + metadata.lastRemoteSnapshotVersion = + lastRemoteSnapshotVersion.toTimestamp(); + } + if (highestListenSequenceNumber > metadata.highestListenSequenceNumber) { + metadata.highestListenSequenceNumber = highestListenSequenceNumber; + } + return this.saveMetadata(transaction, metadata); + }); + } + addTargetData(transaction, targetData) { + return this.saveTargetData(transaction, targetData).next(() => { + return this.retrieveMetadata(transaction).next(metadata => { + metadata.targetCount += 1; + this.updateMetadataFromTargetData(targetData, metadata); + return this.saveMetadata(transaction, metadata); + }); + }); + } + updateTargetData(transaction, targetData) { + return this.saveTargetData(transaction, targetData); + } + removeTargetData(transaction, targetData) { + return this.removeMatchingKeysForTargetId(transaction, targetData.targetId) + .next(() => targetsStore(transaction).delete(targetData.targetId)) + .next(() => this.retrieveMetadata(transaction)) + .next(metadata => { + hardAssert(metadata.targetCount > 0, 0x1f81); + metadata.targetCount -= 1; + return this.saveMetadata(transaction, metadata); + }); + } + /** + * Drops any targets with sequence number less than or equal to the upper bound, excepting those + * present in `activeTargetIds`. Document associations for the removed targets are also removed. + * Returns the number of targets removed. + */ + removeTargets(txn, upperBound, activeTargetIds) { + let count = 0; + const promises = []; + return targetsStore(txn) + .iterate((key, value) => { + const targetData = fromDbTarget(value); + if (targetData.sequenceNumber <= upperBound && + activeTargetIds.get(targetData.targetId) === null) { + count++; + promises.push(this.removeTargetData(txn, targetData)); + } + }) + .next(() => PersistencePromise.waitFor(promises)) + .next(() => count); + } + /** + * Call provided function with each `TargetData` that we have cached. + */ + forEachTarget(txn, f) { + return targetsStore(txn).iterate((key, value) => { + const targetData = fromDbTarget(value); + f(targetData); + }); + } + retrieveMetadata(transaction) { + return globalTargetStore(transaction) + .get(DbTargetGlobalKey) + .next(metadata => { + hardAssert(metadata !== null, 0x0b48); + return metadata; + }); + } + saveMetadata(transaction, metadata) { + return globalTargetStore(transaction).put(DbTargetGlobalKey, metadata); + } + saveTargetData(transaction, targetData) { + return targetsStore(transaction).put(toDbTarget(this.serializer, targetData)); + } + /** + * In-place updates the provided metadata to account for values in the given + * TargetData. Saving is done separately. Returns true if there were any + * changes to the metadata. + */ + updateMetadataFromTargetData(targetData, metadata) { + let updated = false; + if (targetData.targetId > metadata.highestTargetId) { + metadata.highestTargetId = targetData.targetId; + updated = true; + } + if (targetData.sequenceNumber > metadata.highestListenSequenceNumber) { + metadata.highestListenSequenceNumber = targetData.sequenceNumber; + updated = true; + } + return updated; + } + getTargetCount(transaction) { + return this.retrieveMetadata(transaction).next(metadata => metadata.targetCount); + } + getTargetData(transaction, target) { + // Iterating by the canonicalId may yield more than one result because + // canonicalId values are not required to be unique per target. This query + // depends on the queryTargets index to be efficient. + const canonicalId = canonifyTarget(target); + const range = IDBKeyRange.bound([canonicalId, Number.NEGATIVE_INFINITY], [canonicalId, Number.POSITIVE_INFINITY]); + let result = null; + return targetsStore(transaction) + .iterate({ range, index: DbTargetQueryTargetsIndexName }, (key, value, control) => { + const found = fromDbTarget(value); + // After finding a potential match, check that the target is + // actually equal to the requested target. + if (targetEquals(target, found.target)) { + result = found; + control.done(); + } + }) + .next(() => result); + } + addMatchingKeys(txn, keys, targetId) { + // PORTING NOTE: The reverse index (documentsTargets) is maintained by + // IndexedDb. + const promises = []; + const store = documentTargetStore(txn); + keys.forEach(key => { + const path = encodeResourcePath(key.path); + promises.push(store.put({ targetId, path })); + promises.push(this.referenceDelegate.addReference(txn, targetId, key)); + }); + return PersistencePromise.waitFor(promises); + } + removeMatchingKeys(txn, keys, targetId) { + // PORTING NOTE: The reverse index (documentsTargets) is maintained by + // IndexedDb. + const store = documentTargetStore(txn); + return PersistencePromise.forEach(keys, (key) => { + const path = encodeResourcePath(key.path); + return PersistencePromise.waitFor([ + store.delete([targetId, path]), + this.referenceDelegate.removeReference(txn, targetId, key) + ]); + }); + } + removeMatchingKeysForTargetId(txn, targetId) { + const store = documentTargetStore(txn); + const range = IDBKeyRange.bound([targetId], [targetId + 1], + /*lowerOpen=*/ false, + /*upperOpen=*/ true); + return store.delete(range); + } + getMatchingKeysForTargetId(txn, targetId) { + const range = IDBKeyRange.bound([targetId], [targetId + 1], + /*lowerOpen=*/ false, + /*upperOpen=*/ true); + const store = documentTargetStore(txn); + let result = documentKeySet(); + return store + .iterate({ range, keysOnly: true }, (key, _, control) => { + const path = decodeResourcePath(key[1]); + const docKey = new DocumentKey(path); + result = result.add(docKey); + }) + .next(() => result); + } + containsKey(txn, key) { + const path = encodeResourcePath(key.path); + const range = IDBKeyRange.bound([path], [immediateSuccessor(path)], + /*lowerOpen=*/ false, + /*upperOpen=*/ true); + let count = 0; + return documentTargetStore(txn) + .iterate({ + index: DbTargetDocumentDocumentTargetsIndex, + keysOnly: true, + range + }, ([targetId, path], _, control) => { + // Having a sentinel row for a document does not count as containing that document; + // For the target cache, containing the document means the document is part of some + // target. + if (targetId !== 0) { + count++; + control.done(); + } + }) + .next(() => count > 0); + } + /** + * Looks up a TargetData entry by target ID. + * + * @param targetId - The target ID of the TargetData entry to look up. + * @returns The cached TargetData entry, or null if the cache has no entry for + * the target. + */ + // PORTING NOTE: Multi-tab only. + getTargetDataForTarget(transaction, targetId) { + return targetsStore(transaction) + .get(targetId) + .next(found => { + if (found) { + return fromDbTarget(found); + } + else { + return null; + } + }); + } +} +/** + * Helper to get a typed SimpleDbStore for the queries object store. + */ +function targetsStore(txn) { + return getStore(txn, DbTargetStore); +} +/** + * Helper to get a typed SimpleDbStore for the target globals object store. + */ +function globalTargetStore(txn) { + return getStore(txn, DbTargetGlobalStore); +} +/** + * Helper to get a typed SimpleDbStore for the document target object store. + */ +function documentTargetStore(txn) { + return getStore(txn, DbTargetDocumentStore); +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const GC_DID_NOT_RUN = { + didRun: false, + sequenceNumbersCollected: 0, + targetsRemoved: 0, + documentsRemoved: 0 +}; +const LRU_COLLECTION_DISABLED = -1; +const LRU_DEFAULT_CACHE_SIZE_BYTES = 40 * 1024 * 1024; +class LruParams { + static withCacheSize(cacheSize) { + return new LruParams(cacheSize, LruParams.DEFAULT_COLLECTION_PERCENTILE, LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT); + } + constructor( + // When we attempt to collect, we will only do so if the cache size is greater than this + // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped. + cacheSizeCollectionThreshold, + // The percentage of sequence numbers that we will attempt to collect + percentileToCollect, + // A cap on the total number of sequence numbers that will be collected. This prevents + // us from collecting a huge number of sequence numbers if the cache has grown very large. + maximumSequenceNumbersToCollect) { + this.cacheSizeCollectionThreshold = cacheSizeCollectionThreshold; + this.percentileToCollect = percentileToCollect; + this.maximumSequenceNumbersToCollect = maximumSequenceNumbersToCollect; + } +} +LruParams.DEFAULT_COLLECTION_PERCENTILE = 10; +LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1000; +LruParams.DEFAULT = new LruParams(LRU_DEFAULT_CACHE_SIZE_BYTES, LruParams.DEFAULT_COLLECTION_PERCENTILE, LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT); +LruParams.DISABLED = new LruParams(LRU_COLLECTION_DISABLED, 0, 0); + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$e = 'LruGarbageCollector'; +const LRU_MINIMUM_CACHE_SIZE_BYTES = 1 * 1024 * 1024; +/** How long we wait to try running LRU GC after SDK initialization. */ +const INITIAL_GC_DELAY_MS = 1 * 60 * 1000; +/** Minimum amount of time between GC checks, after the first one. */ +const REGULAR_GC_DELAY_MS = 5 * 60 * 1000; +function bufferEntryComparator([aSequence, aIndex], [bSequence, bIndex]) { + const seqCmp = primitiveComparator(aSequence, bSequence); + if (seqCmp === 0) { + // This order doesn't matter, but we can bias against churn by sorting + // entries created earlier as less than newer entries. + return primitiveComparator(aIndex, bIndex); + } + else { + return seqCmp; + } +} +/** + * Used to calculate the nth sequence number. Keeps a rolling buffer of the + * lowest n values passed to `addElement`, and finally reports the largest of + * them in `maxValue`. + */ +class RollingSequenceNumberBuffer { + constructor(maxElements) { + this.maxElements = maxElements; + this.buffer = new SortedSet(bufferEntryComparator); + this.previousIndex = 0; + } + nextIndex() { + return ++this.previousIndex; + } + addElement(sequenceNumber) { + const entry = [sequenceNumber, this.nextIndex()]; + if (this.buffer.size < this.maxElements) { + this.buffer = this.buffer.add(entry); + } + else { + const highestValue = this.buffer.last(); + if (bufferEntryComparator(entry, highestValue) < 0) { + this.buffer = this.buffer.delete(highestValue).add(entry); + } + } + } + get maxValue() { + // Guaranteed to be non-empty. If we decide we are not collecting any + // sequence numbers, nthSequenceNumber below short-circuits. If we have + // decided that we are collecting n sequence numbers, it's because n is some + // percentage of the existing sequence numbers. That means we should never + // be in a situation where we are collecting sequence numbers but don't + // actually have any. + return this.buffer.last()[0]; + } +} +/** + * This class is responsible for the scheduling of LRU garbage collection. It handles checking + * whether or not GC is enabled, as well as which delay to use before the next run. + */ +class LruScheduler { + constructor(garbageCollector, asyncQueue, localStore) { + this.garbageCollector = garbageCollector; + this.asyncQueue = asyncQueue; + this.localStore = localStore; + this.gcTask = null; + } + start() { + if (this.garbageCollector.params.cacheSizeCollectionThreshold !== + LRU_COLLECTION_DISABLED) { + this.scheduleGC(INITIAL_GC_DELAY_MS); + } + } + stop() { + if (this.gcTask) { + this.gcTask.cancel(); + this.gcTask = null; + } + } + get started() { + return this.gcTask !== null; + } + scheduleGC(delay) { + logDebug(LOG_TAG$e, `Garbage collection scheduled in ${delay}ms`); + this.gcTask = this.asyncQueue.enqueueAfterDelay("lru_garbage_collection" /* TimerId.LruGarbageCollection */, delay, async () => { + this.gcTask = null; + try { + await this.localStore.collectGarbage(this.garbageCollector); + } + catch (e) { + if (isIndexedDbTransactionError(e)) { + logDebug(LOG_TAG$e, 'Ignoring IndexedDB error during garbage collection: ', e); + } + else { + await ignoreIfPrimaryLeaseLoss(e); + } + } + await this.scheduleGC(REGULAR_GC_DELAY_MS); + }); + } +} +/** + * Implements the steps for LRU garbage collection. + */ +class LruGarbageCollectorImpl { + constructor(delegate, params) { + this.delegate = delegate; + this.params = params; + } + calculateTargetCount(txn, percentile) { + return this.delegate.getSequenceNumberCount(txn).next(targetCount => { + return Math.floor((percentile / 100.0) * targetCount); + }); + } + nthSequenceNumber(txn, n) { + if (n === 0) { + return PersistencePromise.resolve(ListenSequence.INVALID); + } + const buffer = new RollingSequenceNumberBuffer(n); + return this.delegate + .forEachTarget(txn, target => buffer.addElement(target.sequenceNumber)) + .next(() => { + return this.delegate.forEachOrphanedDocumentSequenceNumber(txn, sequenceNumber => buffer.addElement(sequenceNumber)); + }) + .next(() => buffer.maxValue); + } + removeTargets(txn, upperBound, activeTargetIds) { + return this.delegate.removeTargets(txn, upperBound, activeTargetIds); + } + removeOrphanedDocuments(txn, upperBound) { + return this.delegate.removeOrphanedDocuments(txn, upperBound); + } + collect(txn, activeTargetIds) { + if (this.params.cacheSizeCollectionThreshold === LRU_COLLECTION_DISABLED) { + logDebug('LruGarbageCollector', 'Garbage collection skipped; disabled'); + return PersistencePromise.resolve(GC_DID_NOT_RUN); + } + return this.getCacheSize(txn).next(cacheSize => { + if (cacheSize < this.params.cacheSizeCollectionThreshold) { + logDebug('LruGarbageCollector', `Garbage collection skipped; Cache size ${cacheSize} ` + + `is lower than threshold ${this.params.cacheSizeCollectionThreshold}`); + return GC_DID_NOT_RUN; + } + else { + return this.runGarbageCollection(txn, activeTargetIds); + } + }); + } + getCacheSize(txn) { + return this.delegate.getCacheSize(txn); + } + runGarbageCollection(txn, activeTargetIds) { + let upperBoundSequenceNumber; + let sequenceNumbersToCollect, targetsRemoved; + // Timestamps for various pieces of the process + let countedTargetsTs, foundUpperBoundTs, removedTargetsTs, removedDocumentsTs; + const startTs = Date.now(); + return this.calculateTargetCount(txn, this.params.percentileToCollect) + .next(sequenceNumbers => { + // Cap at the configured max + if (sequenceNumbers > this.params.maximumSequenceNumbersToCollect) { + logDebug('LruGarbageCollector', 'Capping sequence numbers to collect down ' + + `to the maximum of ${this.params.maximumSequenceNumbersToCollect} ` + + `from ${sequenceNumbers}`); + sequenceNumbersToCollect = + this.params.maximumSequenceNumbersToCollect; + } + else { + sequenceNumbersToCollect = sequenceNumbers; + } + countedTargetsTs = Date.now(); + return this.nthSequenceNumber(txn, sequenceNumbersToCollect); + }) + .next(upperBound => { + upperBoundSequenceNumber = upperBound; + foundUpperBoundTs = Date.now(); + return this.removeTargets(txn, upperBoundSequenceNumber, activeTargetIds); + }) + .next(numTargetsRemoved => { + targetsRemoved = numTargetsRemoved; + removedTargetsTs = Date.now(); + return this.removeOrphanedDocuments(txn, upperBoundSequenceNumber); + }) + .next(documentsRemoved => { + removedDocumentsTs = Date.now(); + if (getLogLevel() <= logger.LogLevel.DEBUG) { + const desc = 'LRU Garbage Collection\n' + + `\tCounted targets in ${countedTargetsTs - startTs}ms\n` + + `\tDetermined least recently used ${sequenceNumbersToCollect} in ` + + `${foundUpperBoundTs - countedTargetsTs}ms\n` + + `\tRemoved ${targetsRemoved} targets in ` + + `${removedTargetsTs - foundUpperBoundTs}ms\n` + + `\tRemoved ${documentsRemoved} documents in ` + + `${removedDocumentsTs - removedTargetsTs}ms\n` + + `Total Duration: ${removedDocumentsTs - startTs}ms`; + logDebug('LruGarbageCollector', desc); + } + return PersistencePromise.resolve({ + didRun: true, + sequenceNumbersCollected: sequenceNumbersToCollect, + targetsRemoved, + documentsRemoved + }); + }); + } +} +function newLruGarbageCollector(delegate, params) { + return new LruGarbageCollectorImpl(delegate, params); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Provides LRU functionality for IndexedDB persistence. */ +class IndexedDbLruDelegateImpl { + constructor(db, params) { + this.db = db; + this.garbageCollector = newLruGarbageCollector(this, params); + } + getSequenceNumberCount(txn) { + const docCountPromise = this.orphanedDocumentCount(txn); + const targetCountPromise = this.db.getTargetCache().getTargetCount(txn); + return targetCountPromise.next(targetCount => docCountPromise.next(docCount => targetCount + docCount)); + } + orphanedDocumentCount(txn) { + let orphanedCount = 0; + return this.forEachOrphanedDocumentSequenceNumber(txn, _ => { + orphanedCount++; + }).next(() => orphanedCount); + } + forEachTarget(txn, f) { + return this.db.getTargetCache().forEachTarget(txn, f); + } + forEachOrphanedDocumentSequenceNumber(txn, f) { + return this.forEachOrphanedDocument(txn, (docKey, sequenceNumber) => f(sequenceNumber)); + } + addReference(txn, targetId, key) { + return writeSentinelKey(txn, key); + } + removeReference(txn, targetId, key) { + return writeSentinelKey(txn, key); + } + removeTargets(txn, upperBound, activeTargetIds) { + return this.db.getTargetCache().removeTargets(txn, upperBound, activeTargetIds); + } + markPotentiallyOrphaned(txn, key) { + return writeSentinelKey(txn, key); + } + /** + * Returns true if anything would prevent this document from being garbage + * collected, given that the document in question is not present in any + * targets and has a sequence number less than or equal to the upper bound for + * the collection run. + */ + isPinned(txn, docKey) { + return mutationQueuesContainKey(txn, docKey); + } + removeOrphanedDocuments(txn, upperBound) { + const documentCache = this.db.getRemoteDocumentCache(); + const changeBuffer = documentCache.newChangeBuffer(); + const promises = []; + let documentCount = 0; + const iteration = this.forEachOrphanedDocument(txn, (docKey, sequenceNumber) => { + if (sequenceNumber <= upperBound) { + const p = this.isPinned(txn, docKey).next(isPinned => { + if (!isPinned) { + documentCount++; + // Our size accounting requires us to read all documents before + // removing them. + return changeBuffer.getEntry(txn, docKey).next(() => { + changeBuffer.removeEntry(docKey, SnapshotVersion.min()); + return documentTargetStore(txn).delete(sentinelKey$1(docKey)); + }); + } + }); + promises.push(p); + } + }); + return iteration + .next(() => PersistencePromise.waitFor(promises)) + .next(() => changeBuffer.apply(txn)) + .next(() => documentCount); + } + removeTarget(txn, targetData) { + const updated = targetData.withSequenceNumber(txn.currentSequenceNumber); + return this.db.getTargetCache().updateTargetData(txn, updated); + } + updateLimboDocument(txn, key) { + return writeSentinelKey(txn, key); + } + /** + * Call provided function for each document in the cache that is 'orphaned'. Orphaned + * means not a part of any target, so the only entry in the target-document index for + * that document will be the sentinel row (targetId 0), which will also have the sequence + * number for the last time the document was accessed. + */ + forEachOrphanedDocument(txn, f) { + const store = documentTargetStore(txn); + let nextToReport = ListenSequence.INVALID; + let nextPath; + return store + .iterate({ + index: DbTargetDocumentDocumentTargetsIndex + }, ([targetId, docKey], { path, sequenceNumber }) => { + if (targetId === 0) { + // if nextToReport is valid, report it, this is a new key so the + // last one must not be a member of any targets. + if (nextToReport !== ListenSequence.INVALID) { + f(new DocumentKey(decodeResourcePath(nextPath)), nextToReport); + } + // set nextToReport to be this sequence number. It's the next one we + // might report, if we don't find any targets for this document. + // Note that the sequence number must be defined when the targetId + // is 0. + nextToReport = sequenceNumber; + nextPath = path; + } + else { + // set nextToReport to be invalid, we know we don't need to report + // this one since we found a target for it. + nextToReport = ListenSequence.INVALID; + } + }) + .next(() => { + // Since we report sequence numbers after getting to the next key, we + // need to check if the last key we iterated over was an orphaned + // document and report it. + if (nextToReport !== ListenSequence.INVALID) { + f(new DocumentKey(decodeResourcePath(nextPath)), nextToReport); + } + }); + } + getCacheSize(txn) { + return this.db.getRemoteDocumentCache().getSize(txn); + } +} +function sentinelKey$1(key) { + return [0, encodeResourcePath(key.path)]; +} +/** + * @returns A value suitable for writing a sentinel row in the target-document + * store. + */ +function sentinelRow(key, sequenceNumber) { + return { targetId: 0, path: encodeResourcePath(key.path), sequenceNumber }; +} +function writeSentinelKey(txn, key) { + return documentTargetStore(txn).put(sentinelRow(key, txn.currentSequenceNumber)); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An in-memory buffer of entries to be written to a RemoteDocumentCache. + * It can be used to batch up a set of changes to be written to the cache, but + * additionally supports reading entries back with the `getEntry()` method, + * falling back to the underlying RemoteDocumentCache if no entry is + * buffered. + * + * Entries added to the cache *must* be read first. This is to facilitate + * calculating the size delta of the pending changes. + * + * PORTING NOTE: This class was implemented then removed from other platforms. + * If byte-counting ends up being needed on the other platforms, consider + * porting this class as part of that implementation work. + */ +class RemoteDocumentChangeBuffer { + constructor() { + // A mapping of document key to the new cache entry that should be written. + this.changes = new ObjectMap(key => key.toString(), (l, r) => l.isEqual(r)); + this.changesApplied = false; + } + /** + * Buffers a `RemoteDocumentCache.addEntry()` call. + * + * You can only modify documents that have already been retrieved via + * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). + */ + addEntry(document) { + this.assertNotApplied(); + this.changes.set(document.key, document); + } + /** + * Buffers a `RemoteDocumentCache.removeEntry()` call. + * + * You can only remove documents that have already been retrieved via + * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). + */ + removeEntry(key, readTime) { + this.assertNotApplied(); + this.changes.set(key, MutableDocument.newInvalidDocument(key).setReadTime(readTime)); + } + /** + * Looks up an entry in the cache. The buffered changes will first be checked, + * and if no buffered change applies, this will forward to + * `RemoteDocumentCache.getEntry()`. + * + * @param transaction - The transaction in which to perform any persistence + * operations. + * @param documentKey - The key of the entry to look up. + * @returns The cached document or an invalid document if we have nothing + * cached. + */ + getEntry(transaction, documentKey) { + this.assertNotApplied(); + const bufferedEntry = this.changes.get(documentKey); + if (bufferedEntry !== undefined) { + return PersistencePromise.resolve(bufferedEntry); + } + else { + return this.getFromCache(transaction, documentKey); + } + } + /** + * Looks up several entries in the cache, forwarding to + * `RemoteDocumentCache.getEntry()`. + * + * @param transaction - The transaction in which to perform any persistence + * operations. + * @param documentKeys - The keys of the entries to look up. + * @returns A map of cached documents, indexed by key. If an entry cannot be + * found, the corresponding key will be mapped to an invalid document. + */ + getEntries(transaction, documentKeys) { + return this.getAllFromCache(transaction, documentKeys); + } + /** + * Applies buffered changes to the underlying RemoteDocumentCache, using + * the provided transaction. + */ + apply(transaction) { + this.assertNotApplied(); + this.changesApplied = true; + return this.applyChanges(transaction); + } + /** Helper to assert this.changes is not null */ + assertNotApplied() { + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The RemoteDocumentCache for IndexedDb. To construct, invoke + * `newIndexedDbRemoteDocumentCache()`. + */ +class IndexedDbRemoteDocumentCacheImpl { + constructor(serializer) { + this.serializer = serializer; + } + setIndexManager(indexManager) { + this.indexManager = indexManager; + } + /** + * Adds the supplied entries to the cache. + * + * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer + * returned by `newChangeBuffer()` to ensure proper accounting of metadata. + */ + addEntry(transaction, key, doc) { + const documentStore = remoteDocumentsStore(transaction); + return documentStore.put(doc); + } + /** + * Removes a document from the cache. + * + * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer + * returned by `newChangeBuffer()` to ensure proper accounting of metadata. + */ + removeEntry(transaction, documentKey, readTime) { + const store = remoteDocumentsStore(transaction); + return store.delete(dbReadTimeKey(documentKey, readTime)); + } + /** + * Updates the current cache size. + * + * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the + * cache's metadata. + */ + updateMetadata(transaction, sizeDelta) { + return this.getMetadata(transaction).next(metadata => { + metadata.byteSize += sizeDelta; + return this.setMetadata(transaction, metadata); + }); + } + getEntry(transaction, documentKey) { + let doc = MutableDocument.newInvalidDocument(documentKey); + return remoteDocumentsStore(transaction) + .iterate({ + index: DbRemoteDocumentDocumentKeyIndex, + range: IDBKeyRange.only(dbKey(documentKey)) + }, (_, dbRemoteDoc) => { + doc = this.maybeDecodeDocument(documentKey, dbRemoteDoc); + }) + .next(() => doc); + } + /** + * Looks up an entry in the cache. + * + * @param documentKey - The key of the entry to look up. + * @returns The cached document entry and its size. + */ + getSizedEntry(transaction, documentKey) { + let result = { + size: 0, + document: MutableDocument.newInvalidDocument(documentKey) + }; + return remoteDocumentsStore(transaction) + .iterate({ + index: DbRemoteDocumentDocumentKeyIndex, + range: IDBKeyRange.only(dbKey(documentKey)) + }, (_, dbRemoteDoc) => { + result = { + document: this.maybeDecodeDocument(documentKey, dbRemoteDoc), + size: dbDocumentSize(dbRemoteDoc) + }; + }) + .next(() => result); + } + getEntries(transaction, documentKeys) { + let results = mutableDocumentMap(); + return this.forEachDbEntry(transaction, documentKeys, (key, dbRemoteDoc) => { + const doc = this.maybeDecodeDocument(key, dbRemoteDoc); + results = results.insert(key, doc); + }).next(() => results); + } + /** + * Looks up several entries in the cache. + * + * @param documentKeys - The set of keys entries to look up. + * @returns A map of documents indexed by key and a map of sizes indexed by + * key (zero if the document does not exist). + */ + getSizedEntries(transaction, documentKeys) { + let results = mutableDocumentMap(); + let sizeMap = new SortedMap(DocumentKey.comparator); + return this.forEachDbEntry(transaction, documentKeys, (key, dbRemoteDoc) => { + const doc = this.maybeDecodeDocument(key, dbRemoteDoc); + results = results.insert(key, doc); + sizeMap = sizeMap.insert(key, dbDocumentSize(dbRemoteDoc)); + }).next(() => { + return { documents: results, sizeMap }; + }); + } + forEachDbEntry(transaction, documentKeys, callback) { + if (documentKeys.isEmpty()) { + return PersistencePromise.resolve(); + } + let sortedKeys = new SortedSet(dbKeyComparator); + documentKeys.forEach(e => (sortedKeys = sortedKeys.add(e))); + const range = IDBKeyRange.bound(dbKey(sortedKeys.first()), dbKey(sortedKeys.last())); + const keyIter = sortedKeys.getIterator(); + let nextKey = keyIter.getNext(); + return remoteDocumentsStore(transaction) + .iterate({ index: DbRemoteDocumentDocumentKeyIndex, range }, (_, dbRemoteDoc, control) => { + const potentialKey = DocumentKey.fromSegments([ + ...dbRemoteDoc.prefixPath, + dbRemoteDoc.collectionGroup, + dbRemoteDoc.documentId + ]); + // Go through keys not found in cache. + while (nextKey && dbKeyComparator(nextKey, potentialKey) < 0) { + callback(nextKey, null); + nextKey = keyIter.getNext(); + } + if (nextKey && nextKey.isEqual(potentialKey)) { + // Key found in cache. + callback(nextKey, dbRemoteDoc); + nextKey = keyIter.hasNext() ? keyIter.getNext() : null; + } + // Skip to the next key (if there is one). + if (nextKey) { + control.skip(dbKey(nextKey)); + } + else { + control.done(); + } + }) + .next(() => { + // The rest of the keys are not in the cache. One case where `iterate` + // above won't go through them is when the cache is empty. + while (nextKey) { + callback(nextKey, null); + nextKey = keyIter.hasNext() ? keyIter.getNext() : null; + } + }); + } + getDocumentsMatchingQuery(transaction, query, offset, mutatedDocs, context) { + const collection = query.path; + const startKey = [ + collection.popLast().toArray(), + collection.lastSegment(), + toDbTimestampKey(offset.readTime), + offset.documentKey.path.isEmpty() + ? '' + : offset.documentKey.path.lastSegment() + ]; + const endKey = [ + collection.popLast().toArray(), + collection.lastSegment(), + [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], + '' + ]; + return remoteDocumentsStore(transaction) + .loadAll(IDBKeyRange.bound(startKey, endKey, true)) + .next(dbRemoteDocs => { + context?.incrementDocumentReadCount(dbRemoteDocs.length); + let results = mutableDocumentMap(); + for (const dbRemoteDoc of dbRemoteDocs) { + const document = this.maybeDecodeDocument(DocumentKey.fromSegments(dbRemoteDoc.prefixPath.concat(dbRemoteDoc.collectionGroup, dbRemoteDoc.documentId)), dbRemoteDoc); + if (document.isFoundDocument() && + (queryMatches(query, document) || mutatedDocs.has(document.key))) { + // Either the document matches the given query, or it is mutated. + results = results.insert(document.key, document); + } + } + return results; + }); + } + getAllFromCollectionGroup(transaction, collectionGroup, offset, limit) { + let results = mutableDocumentMap(); + const startKey = dbCollectionGroupKey(collectionGroup, offset); + const endKey = dbCollectionGroupKey(collectionGroup, IndexOffset.max()); + return remoteDocumentsStore(transaction) + .iterate({ + index: DbRemoteDocumentCollectionGroupIndex, + range: IDBKeyRange.bound(startKey, endKey, true) + }, (_, dbRemoteDoc, control) => { + const document = this.maybeDecodeDocument(DocumentKey.fromSegments(dbRemoteDoc.prefixPath.concat(dbRemoteDoc.collectionGroup, dbRemoteDoc.documentId)), dbRemoteDoc); + results = results.insert(document.key, document); + if (results.size === limit) { + control.done(); + } + }) + .next(() => results); + } + newChangeBuffer(options) { + return new IndexedDbRemoteDocumentChangeBuffer(this, !!options && options.trackRemovals); + } + getSize(txn) { + return this.getMetadata(txn).next(metadata => metadata.byteSize); + } + getMetadata(txn) { + return documentGlobalStore(txn) + .get(DbRemoteDocumentGlobalKey) + .next(metadata => { + hardAssert(!!metadata, 0x4e35); + return metadata; + }); + } + setMetadata(txn, metadata) { + return documentGlobalStore(txn).put(DbRemoteDocumentGlobalKey, metadata); + } + /** + * Decodes `dbRemoteDoc` and returns the document (or an invalid document if + * the document corresponds to the format used for sentinel deletes). + */ + maybeDecodeDocument(documentKey, dbRemoteDoc) { + if (dbRemoteDoc) { + const doc = fromDbRemoteDocument(this.serializer, dbRemoteDoc); + // Whether the document is a sentinel removal and should only be used in the + // `getNewDocumentChanges()` + const isSentinelRemoval = doc.isNoDocument() && doc.version.isEqual(SnapshotVersion.min()); + if (!isSentinelRemoval) { + return doc; + } + } + return MutableDocument.newInvalidDocument(documentKey); + } +} +/** Creates a new IndexedDbRemoteDocumentCache. */ +function newIndexedDbRemoteDocumentCache(serializer) { + return new IndexedDbRemoteDocumentCacheImpl(serializer); +} +/** + * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache. + * + * Unlike the MemoryRemoteDocumentChangeBuffer, the IndexedDb implementation computes the size + * delta for all submitted changes. This avoids having to re-read all documents from IndexedDb + * when we apply the changes. + */ +class IndexedDbRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer { + /** + * @param documentCache - The IndexedDbRemoteDocumentCache to apply the changes to. + * @param trackRemovals - Whether to create sentinel deletes that can be tracked by + * `getNewDocumentChanges()`. + */ + constructor(documentCache, trackRemovals) { + super(); + this.documentCache = documentCache; + this.trackRemovals = trackRemovals; + // A map of document sizes and read times prior to applying the changes in + // this buffer. + this.documentStates = new ObjectMap(key => key.toString(), (l, r) => l.isEqual(r)); + } + applyChanges(transaction) { + const promises = []; + let sizeDelta = 0; + let collectionParents = new SortedSet((l, r) => primitiveComparator(l.canonicalString(), r.canonicalString())); + this.changes.forEach((key, documentChange) => { + const previousDoc = this.documentStates.get(key); + promises.push(this.documentCache.removeEntry(transaction, key, previousDoc.readTime)); + if (documentChange.isValidDocument()) { + const doc = toDbRemoteDocument(this.documentCache.serializer, documentChange); + collectionParents = collectionParents.add(key.path.popLast()); + const size = dbDocumentSize(doc); + sizeDelta += size - previousDoc.size; + promises.push(this.documentCache.addEntry(transaction, key, doc)); + } + else { + sizeDelta -= previousDoc.size; + if (this.trackRemovals) { + // In order to track removals, we store a "sentinel delete" in the + // RemoteDocumentCache. This entry is represented by a NoDocument + // with a version of 0 and ignored by `maybeDecodeDocument()` but + // preserved in `getNewDocumentChanges()`. + const deletedDoc = toDbRemoteDocument(this.documentCache.serializer, documentChange.convertToNoDocument(SnapshotVersion.min())); + promises.push(this.documentCache.addEntry(transaction, key, deletedDoc)); + } + } + }); + collectionParents.forEach(parent => { + promises.push(this.documentCache.indexManager.addToCollectionParentIndex(transaction, parent)); + }); + promises.push(this.documentCache.updateMetadata(transaction, sizeDelta)); + return PersistencePromise.waitFor(promises); + } + getFromCache(transaction, documentKey) { + // Record the size of everything we load from the cache so we can compute a delta later. + return this.documentCache + .getSizedEntry(transaction, documentKey) + .next(getResult => { + this.documentStates.set(documentKey, { + size: getResult.size, + readTime: getResult.document.readTime + }); + return getResult.document; + }); + } + getAllFromCache(transaction, documentKeys) { + // Record the size of everything we load from the cache so we can compute + // a delta later. + return this.documentCache + .getSizedEntries(transaction, documentKeys) + .next(({ documents, sizeMap }) => { + // Note: `getAllFromCache` returns two maps instead of a single map from + // keys to `DocumentSizeEntry`s. This is to allow returning the + // `MutableDocumentMap` directly, without a conversion. + sizeMap.forEach((documentKey, size) => { + this.documentStates.set(documentKey, { + size, + readTime: documents.get(documentKey).readTime + }); + }); + return documents; + }); + } +} +function documentGlobalStore(txn) { + return getStore(txn, DbRemoteDocumentGlobalStore); +} +/** + * Helper to get a typed SimpleDbStore for the remoteDocuments object store. + */ +function remoteDocumentsStore(txn) { + return getStore(txn, DbRemoteDocumentStore); +} +/** + * Returns a key that can be used for document lookups on the + * `DbRemoteDocumentDocumentKeyIndex` index. + */ +function dbKey(documentKey) { + const path = documentKey.path.toArray(); + return [ + /* prefix path */ path.slice(0, path.length - 2), + /* collection id */ path[path.length - 2], + /* document id */ path[path.length - 1] + ]; +} +/** + * Returns a key that can be used for document lookups via the primary key of + * the DbRemoteDocument object store. + */ +function dbReadTimeKey(documentKey, readTime) { + const path = documentKey.path.toArray(); + return [ + /* prefix path */ path.slice(0, path.length - 2), + /* collection id */ path[path.length - 2], + toDbTimestampKey(readTime), + /* document id */ path[path.length - 1] + ]; +} +/** + * Returns a key that can be used for document lookups on the + * `DbRemoteDocumentDocumentCollectionGroupIndex` index. + */ +function dbCollectionGroupKey(collectionGroup, offset) { + const path = offset.documentKey.path.toArray(); + return [ + /* collection id */ collectionGroup, + toDbTimestampKey(offset.readTime), + /* prefix path */ path.slice(0, path.length - 2), + /* document id */ path.length > 0 ? path[path.length - 1] : '' + ]; +} +/** + * Comparator that compares document keys according to the primary key sorting + * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id + * and then document ID). + * + * Visible for testing. + */ +function dbKeyComparator(l, r) { + const left = l.path.toArray(); + const right = r.path.toArray(); + // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74 + let cmp = 0; + for (let i = 0; i < left.length - 2 && i < right.length - 2; ++i) { + cmp = primitiveComparator(left[i], right[i]); + if (cmp) { + return cmp; + } + } + cmp = primitiveComparator(left.length, right.length); + if (cmp) { + return cmp; + } + cmp = primitiveComparator(left[left.length - 2], right[right.length - 2]); + if (cmp) { + return cmp; + } + // TODO(b/329441702): Document IDs should be sorted by UTF-8 encoded byte + // order, but IndexedDB sorts strings lexicographically. Document ID + // comparison here still relies on primitive comparison to avoid mismatches + // observed in snapshot listeners with Unicode characters in documentIds + return primitiveComparator(left[left.length - 1], right[right.length - 1]); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Schema Version for the Web client: + * 1. Initial version including Mutation Queue, Query Cache, and Remote + * Document Cache + * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No + * longer required because migration 3 unconditionally clears it. + * 3. Dropped and re-created Query Cache to deal with cache corruption related + * to limbo resolution. Addresses + * https://github.com/firebase/firebase-ios-sdk/issues/1548 + * 4. Multi-Tab Support. + * 5. Removal of held write acks. + * 6. Create document global for tracking document cache size. + * 7. Ensure every cached document has a sentinel row with a sequence number. + * 8. Add collection-parent index for Collection Group queries. + * 9. Change RemoteDocumentChanges store to be keyed by readTime rather than + * an auto-incrementing ID. This is required for Index-Free queries. + * 10. Rewrite the canonical IDs to the explicit Protobuf-based format. + * 11. Add bundles and named_queries for bundle support. + * 12. Add document overlays. + * 13. Rewrite the keys of the remote document cache to allow for efficient + * document lookup via `getAll()`. + * 14. Add overlays. + * 15. Add indexing support. + * 16. Parse timestamp strings before creating index entries. + * 17. TODO(tomandersen) + * 18. Encode key safe representations of IndexEntry in DbIndexEntryStore. + */ +const SCHEMA_VERSION = 18; + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a local view (overlay) of a document, and the fields that are + * locally mutated. + */ +class OverlayedDocument { + constructor(overlayedDocument, + /** + * The fields that are locally mutated by patch mutations. + * + * If the overlayed document is from set or delete mutations, this is `null`. + * If there is no overlay (mutation) for the document, this is an empty `FieldMask`. + */ + mutatedFields) { + this.overlayedDocument = overlayedDocument; + this.mutatedFields = mutatedFields; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A readonly view of the local state of all documents we're tracking (i.e. we + * have a cached version in remoteDocumentCache or local mutations for the + * document). The view is computed by applying the mutations in the + * MutationQueue to the RemoteDocumentCache. + */ +class LocalDocumentsView { + constructor(remoteDocumentCache, mutationQueue, documentOverlayCache, indexManager) { + this.remoteDocumentCache = remoteDocumentCache; + this.mutationQueue = mutationQueue; + this.documentOverlayCache = documentOverlayCache; + this.indexManager = indexManager; + } + /** + * Get the local view of the document identified by `key`. + * + * @returns Local view of the document or null if we don't have any cached + * state for it. + */ + getDocument(transaction, key) { + let overlay = null; + return this.documentOverlayCache + .getOverlay(transaction, key) + .next(value => { + overlay = value; + return this.remoteDocumentCache.getEntry(transaction, key); + }) + .next(document => { + if (overlay !== null) { + mutationApplyToLocalView(overlay.mutation, document, FieldMask.empty(), Timestamp.now()); + } + return document; + }); + } + /** + * Gets the local view of the documents identified by `keys`. + * + * If we don't have cached state for a document in `keys`, a NoDocument will + * be stored for that key in the resulting set. + */ + getDocuments(transaction, keys) { + return this.remoteDocumentCache + .getEntries(transaction, keys) + .next(docs => this.getLocalViewOfDocuments(transaction, docs, documentKeySet()).next(() => docs)); + } + /** + * Similar to `getDocuments`, but creates the local view from the given + * `baseDocs` without retrieving documents from the local store. + * + * @param transaction - The transaction this operation is scoped to. + * @param docs - The documents to apply local mutations to get the local views. + * @param existenceStateChanged - The set of document keys whose existence state + * is changed. This is useful to determine if some documents overlay needs + * to be recalculated. + */ + getLocalViewOfDocuments(transaction, docs, existenceStateChanged = documentKeySet()) { + const overlays = newOverlayMap(); + return this.populateOverlays(transaction, overlays, docs).next(() => { + return this.computeViews(transaction, docs, overlays, existenceStateChanged).next(computeViewsResult => { + let result = documentMap(); + computeViewsResult.forEach((documentKey, overlayedDocument) => { + result = result.insert(documentKey, overlayedDocument.overlayedDocument); + }); + return result; + }); + }); + } + /** + * Gets the overlayed documents for the given document map, which will include + * the local view of those documents and a `FieldMask` indicating which fields + * are mutated locally, `null` if overlay is a Set or Delete mutation. + */ + getOverlayedDocuments(transaction, docs) { + const overlays = newOverlayMap(); + return this.populateOverlays(transaction, overlays, docs).next(() => this.computeViews(transaction, docs, overlays, documentKeySet())); + } + /** + * Fetches the overlays for {@code docs} and adds them to provided overlay map + * if the map does not already contain an entry for the given document key. + */ + populateOverlays(transaction, overlays, docs) { + const missingOverlays = []; + docs.forEach(key => { + if (!overlays.has(key)) { + missingOverlays.push(key); + } + }); + return this.documentOverlayCache + .getOverlays(transaction, missingOverlays) + .next(result => { + result.forEach((key, val) => { + overlays.set(key, val); + }); + }); + } + /** + * Computes the local view for the given documents. + * + * @param docs - The documents to compute views for. It also has the base + * version of the documents. + * @param overlays - The overlays that need to be applied to the given base + * version of the documents. + * @param existenceStateChanged - A set of documents whose existence states + * might have changed. This is used to determine if we need to re-calculate + * overlays from mutation queues. + * @return A map represents the local documents view. + */ + computeViews(transaction, docs, overlays, existenceStateChanged) { + let recalculateDocuments = mutableDocumentMap(); + const mutatedFields = newDocumentKeyMap(); + const results = newOverlayedDocumentMap(); + docs.forEach((_, doc) => { + const overlay = overlays.get(doc.key); + // Recalculate an overlay if the document's existence state changed due to + // a remote event *and* the overlay is a PatchMutation. This is because + // document existence state can change if some patch mutation's + // preconditions are met. + // NOTE: we recalculate when `overlay` is undefined as well, because there + // might be a patch mutation whose precondition does not match before the + // change (hence overlay is undefined), but would now match. + if (existenceStateChanged.has(doc.key) && + (overlay === undefined || overlay.mutation instanceof PatchMutation)) { + recalculateDocuments = recalculateDocuments.insert(doc.key, doc); + } + else if (overlay !== undefined) { + mutatedFields.set(doc.key, overlay.mutation.getFieldMask()); + mutationApplyToLocalView(overlay.mutation, doc, overlay.mutation.getFieldMask(), Timestamp.now()); + } + else { + // no overlay exists + // Using EMPTY to indicate there is no overlay for the document. + mutatedFields.set(doc.key, FieldMask.empty()); + } + }); + return this.recalculateAndSaveOverlays(transaction, recalculateDocuments).next(recalculatedFields => { + recalculatedFields.forEach((documentKey, mask) => mutatedFields.set(documentKey, mask)); + docs.forEach((documentKey, document) => results.set(documentKey, new OverlayedDocument(document, mutatedFields.get(documentKey) ?? null))); + return results; + }); + } + recalculateAndSaveOverlays(transaction, docs) { + const masks = newDocumentKeyMap(); + // A reverse lookup map from batch id to the documents within that batch. + let documentsByBatchId = new SortedMap((key1, key2) => key1 - key2); + let processed = documentKeySet(); + return this.mutationQueue + .getAllMutationBatchesAffectingDocumentKeys(transaction, docs) + .next(batches => { + for (const batch of batches) { + batch.keys().forEach(key => { + const baseDoc = docs.get(key); + if (baseDoc === null) { + return; + } + let mask = masks.get(key) || FieldMask.empty(); + mask = batch.applyToLocalView(baseDoc, mask); + masks.set(key, mask); + const newSet = (documentsByBatchId.get(batch.batchId) || documentKeySet()).add(key); + documentsByBatchId = documentsByBatchId.insert(batch.batchId, newSet); + }); + } + }) + .next(() => { + const promises = []; + // Iterate in descending order of batch IDs, and skip documents that are + // already saved. + const iter = documentsByBatchId.getReverseIterator(); + while (iter.hasNext()) { + const entry = iter.getNext(); + const batchId = entry.key; + const keys = entry.value; + const overlays = newMutationMap(); + keys.forEach(key => { + if (!processed.has(key)) { + const overlayMutation = calculateOverlayMutation(docs.get(key), masks.get(key)); + if (overlayMutation !== null) { + overlays.set(key, overlayMutation); + } + processed = processed.add(key); + } + }); + promises.push(this.documentOverlayCache.saveOverlays(transaction, batchId, overlays)); + } + return PersistencePromise.waitFor(promises); + }) + .next(() => masks); + } + /** + * Recalculates overlays by reading the documents from remote document cache + * first, and saves them after they are calculated. + */ + recalculateAndSaveOverlaysForDocumentKeys(transaction, documentKeys) { + return this.remoteDocumentCache + .getEntries(transaction, documentKeys) + .next(docs => this.recalculateAndSaveOverlays(transaction, docs)); + } + /** + * Performs a query against the local view of all documents. + * + * @param transaction - The persistence transaction. + * @param query - The query to match documents against. + * @param offset - Read time and key to start scanning by (exclusive). + * @param context - A optional tracker to keep a record of important details + * during database local query execution. + */ + getDocumentsMatchingQuery(transaction, query, offset, context) { + if (isDocumentQuery$1(query)) { + return this.getDocumentsMatchingDocumentQuery(transaction, query.path); + } + else if (isCollectionGroupQuery(query)) { + return this.getDocumentsMatchingCollectionGroupQuery(transaction, query, offset, context); + } + else { + return this.getDocumentsMatchingCollectionQuery(transaction, query, offset, context); + } + } + /** + * Given a collection group, returns the next documents that follow the provided offset, along + * with an updated batch ID. + * + *

The documents returned by this method are ordered by remote version from the provided + * offset. If there are no more remote documents after the provided offset, documents with + * mutations in order of batch id from the offset are returned. Since all documents in a batch are + * returned together, the total number of documents returned can exceed {@code count}. + * + * @param transaction + * @param collectionGroup The collection group for the documents. + * @param offset The offset to index into. + * @param count The number of documents to return + * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id. + */ + getNextDocuments(transaction, collectionGroup, offset, count) { + return this.remoteDocumentCache + .getAllFromCollectionGroup(transaction, collectionGroup, offset, count) + .next((originalDocs) => { + const overlaysPromise = count - originalDocs.size > 0 + ? this.documentOverlayCache.getOverlaysForCollectionGroup(transaction, collectionGroup, offset.largestBatchId, count - originalDocs.size) + : PersistencePromise.resolve(newOverlayMap()); + // The callsite will use the largest batch ID together with the latest read time to create + // a new index offset. Since we only process batch IDs if all remote documents have been read, + // no overlay will increase the overall read time. This is why we only need to special case + // the batch id. + let largestBatchId = INITIAL_LARGEST_BATCH_ID; + let modifiedDocs = originalDocs; + return overlaysPromise.next(overlays => { + return PersistencePromise.forEach(overlays, (key, overlay) => { + if (largestBatchId < overlay.largestBatchId) { + largestBatchId = overlay.largestBatchId; + } + if (originalDocs.get(key)) { + return PersistencePromise.resolve(); + } + return this.remoteDocumentCache + .getEntry(transaction, key) + .next(doc => { + modifiedDocs = modifiedDocs.insert(key, doc); + }); + }) + .next(() => this.populateOverlays(transaction, overlays, originalDocs)) + .next(() => this.computeViews(transaction, modifiedDocs, overlays, documentKeySet())) + .next(localDocs => ({ + batchId: largestBatchId, + changes: convertOverlayedDocumentMapToDocumentMap(localDocs) + })); + }); + }); + } + getDocumentsMatchingDocumentQuery(transaction, docPath) { + // Just do a simple document lookup. + return this.getDocument(transaction, new DocumentKey(docPath)).next(document => { + let result = documentMap(); + if (document.isFoundDocument()) { + result = result.insert(document.key, document); + } + return result; + }); + } + getDocumentsMatchingCollectionGroupQuery(transaction, query, offset, context) { + const collectionId = query.collectionGroup; + let results = documentMap(); + return this.indexManager + .getCollectionParents(transaction, collectionId) + .next(parents => { + // Perform a collection query against each parent that contains the + // collectionId and aggregate the results. + return PersistencePromise.forEach(parents, (parent) => { + const collectionQuery = asCollectionQueryAtPath(query, parent.child(collectionId)); + return this.getDocumentsMatchingCollectionQuery(transaction, collectionQuery, offset, context).next(r => { + r.forEach((key, doc) => { + results = results.insert(key, doc); + }); + }); + }).next(() => results); + }); + } + getDocumentsMatchingCollectionQuery(transaction, query, offset, context) { + // Query the remote documents and overlay mutations. + let overlays; + return this.documentOverlayCache + .getOverlaysForCollection(transaction, query.path, offset.largestBatchId) + .next(result => { + overlays = result; + return this.remoteDocumentCache.getDocumentsMatchingQuery(transaction, query, offset, overlays, context); + }) + .next(remoteDocuments => { + // As documents might match the query because of their overlay we need to + // include documents for all overlays in the initial document set. + overlays.forEach((_, overlay) => { + const key = overlay.getKey(); + if (remoteDocuments.get(key) === null) { + remoteDocuments = remoteDocuments.insert(key, MutableDocument.newInvalidDocument(key)); + } + }); + // Apply the overlays and match against the query. + let results = documentMap(); + remoteDocuments.forEach((key, document) => { + const overlay = overlays.get(key); + if (overlay !== undefined) { + mutationApplyToLocalView(overlay.mutation, document, FieldMask.empty(), Timestamp.now()); + } + // Finally, insert the documents that still match the query + if (queryMatches(query, document)) { + results = results.insert(key, document); + } + }); + return results; + }); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class MemoryBundleCache { + constructor(serializer) { + this.serializer = serializer; + this.bundles = new Map(); + this.namedQueries = new Map(); + } + getBundleMetadata(transaction, bundleId) { + return PersistencePromise.resolve(this.bundles.get(bundleId)); + } + saveBundleMetadata(transaction, bundleMetadata) { + this.bundles.set(bundleMetadata.id, fromBundleMetadata(bundleMetadata)); + return PersistencePromise.resolve(); + } + getNamedQuery(transaction, queryName) { + return PersistencePromise.resolve(this.namedQueries.get(queryName)); + } + saveNamedQuery(transaction, query) { + this.namedQueries.set(query.name, fromProtoNamedQuery(query)); + return PersistencePromise.resolve(); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An in-memory implementation of DocumentOverlayCache. + */ +class MemoryDocumentOverlayCache { + constructor() { + // A map sorted by DocumentKey, whose value is a pair of the largest batch id + // for the overlay and the overlay itself. + this.overlays = new SortedMap(DocumentKey.comparator); + this.overlayByBatchId = new Map(); + } + getOverlay(transaction, key) { + return PersistencePromise.resolve(this.overlays.get(key)); + } + getOverlays(transaction, keys) { + const result = newOverlayMap(); + return PersistencePromise.forEach(keys, (key) => { + return this.getOverlay(transaction, key).next(overlay => { + if (overlay !== null) { + result.set(key, overlay); + } + }); + }).next(() => result); + } + saveOverlays(transaction, largestBatchId, overlays) { + overlays.forEach((_, mutation) => { + this.saveOverlay(transaction, largestBatchId, mutation); + }); + return PersistencePromise.resolve(); + } + removeOverlaysForBatchId(transaction, documentKeys, batchId) { + const keys = this.overlayByBatchId.get(batchId); + if (keys !== undefined) { + keys.forEach(key => (this.overlays = this.overlays.remove(key))); + this.overlayByBatchId.delete(batchId); + } + return PersistencePromise.resolve(); + } + getOverlaysForCollection(transaction, collection, sinceBatchId) { + const result = newOverlayMap(); + const immediateChildrenPathLength = collection.length + 1; + const prefix = new DocumentKey(collection.child('')); + const iter = this.overlays.getIteratorFrom(prefix); + while (iter.hasNext()) { + const entry = iter.getNext(); + const overlay = entry.value; + const key = overlay.getKey(); + if (!collection.isPrefixOf(key.path)) { + break; + } + // Documents from sub-collections + if (key.path.length !== immediateChildrenPathLength) { + continue; + } + if (overlay.largestBatchId > sinceBatchId) { + result.set(overlay.getKey(), overlay); + } + } + return PersistencePromise.resolve(result); + } + getOverlaysForCollectionGroup(transaction, collectionGroup, sinceBatchId, count) { + let batchIdToOverlays = new SortedMap((key1, key2) => key1 - key2); + const iter = this.overlays.getIterator(); + while (iter.hasNext()) { + const entry = iter.getNext(); + const overlay = entry.value; + const key = overlay.getKey(); + if (key.getCollectionGroup() !== collectionGroup) { + continue; + } + if (overlay.largestBatchId > sinceBatchId) { + let overlaysForBatchId = batchIdToOverlays.get(overlay.largestBatchId); + if (overlaysForBatchId === null) { + overlaysForBatchId = newOverlayMap(); + batchIdToOverlays = batchIdToOverlays.insert(overlay.largestBatchId, overlaysForBatchId); + } + overlaysForBatchId.set(overlay.getKey(), overlay); + } + } + const result = newOverlayMap(); + const batchIter = batchIdToOverlays.getIterator(); + while (batchIter.hasNext()) { + const entry = batchIter.getNext(); + const overlays = entry.value; + overlays.forEach((key, overlay) => result.set(key, overlay)); + if (result.size() >= count) { + break; + } + } + return PersistencePromise.resolve(result); + } + saveOverlay(transaction, largestBatchId, mutation) { + // Remove the association of the overlay to its batch id. + const existing = this.overlays.get(mutation.key); + if (existing !== null) { + const newSet = this.overlayByBatchId + .get(existing.largestBatchId) + .delete(mutation.key); + this.overlayByBatchId.set(existing.largestBatchId, newSet); + } + this.overlays = this.overlays.insert(mutation.key, new Overlay(largestBatchId, mutation)); + // Create the association of this overlay to the given largestBatchId. + let batch = this.overlayByBatchId.get(largestBatchId); + if (batch === undefined) { + batch = documentKeySet(); + this.overlayByBatchId.set(largestBatchId, batch); + } + this.overlayByBatchId.set(largestBatchId, batch.add(mutation.key)); + } +} + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class MemoryGlobalsCache { + constructor() { + this.sessionToken = ByteString.EMPTY_BYTE_STRING; + } + getSessionToken(transaction) { + return PersistencePromise.resolve(this.sessionToken); + } + setSessionToken(transaction, sessionToken) { + this.sessionToken = sessionToken; + return PersistencePromise.resolve(); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A collection of references to a document from some kind of numbered entity + * (either a target ID or batch ID). As references are added to or removed from + * the set corresponding events are emitted to a registered garbage collector. + * + * Each reference is represented by a DocumentReference object. Each of them + * contains enough information to uniquely identify the reference. They are all + * stored primarily in a set sorted by key. A document is considered garbage if + * there's no references in that set (this can be efficiently checked thanks to + * sorting by key). + * + * ReferenceSet also keeps a secondary set that contains references sorted by + * IDs. This one is used to efficiently implement removal of all references by + * some target ID. + */ +class ReferenceSet { + constructor() { + // A set of outstanding references to a document sorted by key. + this.refsByKey = new SortedSet(DocReference.compareByKey); + // A set of outstanding references to a document sorted by target id. + this.refsByTarget = new SortedSet(DocReference.compareByTargetId); + } + /** Returns true if the reference set contains no references. */ + isEmpty() { + return this.refsByKey.isEmpty(); + } + /** Adds a reference to the given document key for the given ID. */ + addReference(key, id) { + const ref = new DocReference(key, id); + this.refsByKey = this.refsByKey.add(ref); + this.refsByTarget = this.refsByTarget.add(ref); + } + /** Add references to the given document keys for the given ID. */ + addReferences(keys, id) { + keys.forEach(key => this.addReference(key, id)); + } + /** + * Removes a reference to the given document key for the given + * ID. + */ + removeReference(key, id) { + this.removeRef(new DocReference(key, id)); + } + removeReferences(keys, id) { + keys.forEach(key => this.removeReference(key, id)); + } + /** + * Clears all references with a given ID. Calls removeRef() for each key + * removed. + */ + removeReferencesForId(id) { + const emptyKey = new DocumentKey(new ResourcePath([])); + const startRef = new DocReference(emptyKey, id); + const endRef = new DocReference(emptyKey, id + 1); + const keys = []; + this.refsByTarget.forEachInRange([startRef, endRef], ref => { + this.removeRef(ref); + keys.push(ref.key); + }); + return keys; + } + removeAllReferences() { + this.refsByKey.forEach(ref => this.removeRef(ref)); + } + removeRef(ref) { + this.refsByKey = this.refsByKey.delete(ref); + this.refsByTarget = this.refsByTarget.delete(ref); + } + referencesForId(id) { + const emptyKey = new DocumentKey(new ResourcePath([])); + const startRef = new DocReference(emptyKey, id); + const endRef = new DocReference(emptyKey, id + 1); + let keys = documentKeySet(); + this.refsByTarget.forEachInRange([startRef, endRef], ref => { + keys = keys.add(ref.key); + }); + return keys; + } + containsKey(key) { + const ref = new DocReference(key, 0); + const firstRef = this.refsByKey.firstAfterOrEqual(ref); + return firstRef !== null && key.isEqual(firstRef.key); + } +} +class DocReference { + constructor(key, targetOrBatchId) { + this.key = key; + this.targetOrBatchId = targetOrBatchId; + } + /** Compare by key then by ID */ + static compareByKey(left, right) { + return (DocumentKey.comparator(left.key, right.key) || + primitiveComparator(left.targetOrBatchId, right.targetOrBatchId)); + } + /** Compare by ID then by key */ + static compareByTargetId(left, right) { + return (primitiveComparator(left.targetOrBatchId, right.targetOrBatchId) || + DocumentKey.comparator(left.key, right.key)); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class MemoryMutationQueue { + constructor(indexManager, referenceDelegate) { + this.indexManager = indexManager; + this.referenceDelegate = referenceDelegate; + /** + * The set of all mutations that have been sent but not yet been applied to + * the backend. + */ + this.mutationQueue = []; + /** Next value to use when assigning sequential IDs to each mutation batch. */ + this.nextBatchId = 1; + /** An ordered mapping between documents and the mutations batch IDs. */ + this.batchesByDocumentKey = new SortedSet(DocReference.compareByKey); + } + checkEmpty(transaction) { + return PersistencePromise.resolve(this.mutationQueue.length === 0); + } + addMutationBatch(transaction, localWriteTime, baseMutations, mutations) { + const batchId = this.nextBatchId; + this.nextBatchId++; + if (this.mutationQueue.length > 0) { + this.mutationQueue[this.mutationQueue.length - 1]; + } + const batch = new MutationBatch(batchId, localWriteTime, baseMutations, mutations); + this.mutationQueue.push(batch); + // Track references by document key and index collection parents. + for (const mutation of mutations) { + this.batchesByDocumentKey = this.batchesByDocumentKey.add(new DocReference(mutation.key, batchId)); + this.indexManager.addToCollectionParentIndex(transaction, mutation.key.path.popLast()); + } + return PersistencePromise.resolve(batch); + } + lookupMutationBatch(transaction, batchId) { + return PersistencePromise.resolve(this.findMutationBatch(batchId)); + } + getNextMutationBatchAfterBatchId(transaction, batchId) { + const nextBatchId = batchId + 1; + // The requested batchId may still be out of range so normalize it to the + // start of the queue. + const rawIndex = this.indexOfBatchId(nextBatchId); + const index = rawIndex < 0 ? 0 : rawIndex; + return PersistencePromise.resolve(this.mutationQueue.length > index ? this.mutationQueue[index] : null); + } + getHighestUnacknowledgedBatchId() { + return PersistencePromise.resolve(this.mutationQueue.length === 0 ? BATCHID_UNKNOWN : this.nextBatchId - 1); + } + getAllMutationBatches(transaction) { + return PersistencePromise.resolve(this.mutationQueue.slice()); + } + getAllMutationBatchesAffectingDocumentKey(transaction, documentKey) { + const start = new DocReference(documentKey, 0); + const end = new DocReference(documentKey, Number.POSITIVE_INFINITY); + const result = []; + this.batchesByDocumentKey.forEachInRange([start, end], ref => { + const batch = this.findMutationBatch(ref.targetOrBatchId); + result.push(batch); + }); + return PersistencePromise.resolve(result); + } + getAllMutationBatchesAffectingDocumentKeys(transaction, documentKeys) { + let uniqueBatchIDs = new SortedSet(primitiveComparator); + documentKeys.forEach(documentKey => { + const start = new DocReference(documentKey, 0); + const end = new DocReference(documentKey, Number.POSITIVE_INFINITY); + this.batchesByDocumentKey.forEachInRange([start, end], ref => { + uniqueBatchIDs = uniqueBatchIDs.add(ref.targetOrBatchId); + }); + }); + return PersistencePromise.resolve(this.findMutationBatches(uniqueBatchIDs)); + } + getAllMutationBatchesAffectingQuery(transaction, query) { + // Use the query path as a prefix for testing if a document matches the + // query. + const prefix = query.path; + const immediateChildrenPathLength = prefix.length + 1; + // Construct a document reference for actually scanning the index. Unlike + // the prefix the document key in this reference must have an even number of + // segments. The empty segment can be used a suffix of the query path + // because it precedes all other segments in an ordered traversal. + let startPath = prefix; + if (!DocumentKey.isDocumentKey(startPath)) { + startPath = startPath.child(''); + } + const start = new DocReference(new DocumentKey(startPath), 0); + // Find unique batchIDs referenced by all documents potentially matching the + // query. + let uniqueBatchIDs = new SortedSet(primitiveComparator); + this.batchesByDocumentKey.forEachWhile(ref => { + const rowKeyPath = ref.key.path; + if (!prefix.isPrefixOf(rowKeyPath)) { + return false; + } + else { + // Rows with document keys more than one segment longer than the query + // path can't be matches. For example, a query on 'rooms' can't match + // the document /rooms/abc/messages/xyx. + // TODO(mcg): we'll need a different scanner when we implement + // ancestor queries. + if (rowKeyPath.length === immediateChildrenPathLength) { + uniqueBatchIDs = uniqueBatchIDs.add(ref.targetOrBatchId); + } + return true; + } + }, start); + return PersistencePromise.resolve(this.findMutationBatches(uniqueBatchIDs)); + } + findMutationBatches(batchIDs) { + // Construct an array of matching batches, sorted by batchID to ensure that + // multiple mutations affecting the same document key are applied in order. + const result = []; + batchIDs.forEach(batchId => { + const batch = this.findMutationBatch(batchId); + if (batch !== null) { + result.push(batch); + } + }); + return result; + } + removeMutationBatch(transaction, batch) { + // Find the position of the first batch for removal. + const batchIndex = this.indexOfExistingBatchId(batch.batchId, 'removed'); + hardAssert(batchIndex === 0, 0xd6db); + this.mutationQueue.shift(); + let references = this.batchesByDocumentKey; + return PersistencePromise.forEach(batch.mutations, (mutation) => { + const ref = new DocReference(mutation.key, batch.batchId); + references = references.delete(ref); + return this.referenceDelegate.markPotentiallyOrphaned(transaction, mutation.key); + }).next(() => { + this.batchesByDocumentKey = references; + }); + } + removeCachedMutationKeys(batchId) { + // No-op since the memory mutation queue does not maintain a separate cache. + } + containsKey(txn, key) { + const ref = new DocReference(key, 0); + const firstRef = this.batchesByDocumentKey.firstAfterOrEqual(ref); + return PersistencePromise.resolve(key.isEqual(firstRef && firstRef.key)); + } + performConsistencyCheck(txn) { + if (this.mutationQueue.length === 0) ; + return PersistencePromise.resolve(); + } + /** + * Finds the index of the given batchId in the mutation queue and asserts that + * the resulting index is within the bounds of the queue. + * + * @param batchId - The batchId to search for + * @param action - A description of what the caller is doing, phrased in passive + * form (e.g. "acknowledged" in a routine that acknowledges batches). + */ + indexOfExistingBatchId(batchId, action) { + const index = this.indexOfBatchId(batchId); + return index; + } + /** + * Finds the index of the given batchId in the mutation queue. This operation + * is O(1). + * + * @returns The computed index of the batch with the given batchId, based on + * the state of the queue. Note this index can be negative if the requested + * batchId has already been removed from the queue or past the end of the + * queue if the batchId is larger than the last added batch. + */ + indexOfBatchId(batchId) { + if (this.mutationQueue.length === 0) { + // As an index this is past the end of the queue + return 0; + } + // Examine the front of the queue to figure out the difference between the + // batchId and indexes in the array. Note that since the queue is ordered + // by batchId, if the first batch has a larger batchId then the requested + // batchId doesn't exist in the queue. + const firstBatchId = this.mutationQueue[0].batchId; + return batchId - firstBatchId; + } + /** + * A version of lookupMutationBatch that doesn't return a promise, this makes + * other functions that uses this code easier to read and more efficient. + */ + findMutationBatch(batchId) { + const index = this.indexOfBatchId(batchId); + if (index < 0 || index >= this.mutationQueue.length) { + return null; + } + const batch = this.mutationQueue[index]; + return batch; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The smallest value representable by a 64-bit signed integer (long). + */ +const MIN_LONG_VALUE = '-9223372036854775808'; +function documentEntryMap() { + return new SortedMap(DocumentKey.comparator); +} +/** + * The memory-only RemoteDocumentCache for IndexedDb. To construct, invoke + * `newMemoryRemoteDocumentCache()`. + */ +class MemoryRemoteDocumentCacheImpl { + /** + * @param sizer - Used to assess the size of a document. For eager GC, this is + * expected to just return 0 to avoid unnecessarily doing the work of + * calculating the size. + */ + constructor(sizer) { + this.sizer = sizer; + /** Underlying cache of documents and their read times. */ + this.docs = documentEntryMap(); + /** Size of all cached documents. */ + this.size = 0; + } + setIndexManager(indexManager) { + this.indexManager = indexManager; + } + /** + * Adds the supplied entry to the cache and updates the cache size as appropriate. + * + * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer + * returned by `newChangeBuffer()`. + */ + addEntry(transaction, doc) { + const key = doc.key; + const entry = this.docs.get(key); + const previousSize = entry ? entry.size : 0; + const currentSize = this.sizer(doc); + this.docs = this.docs.insert(key, { + document: doc.mutableCopy(), + size: currentSize + }); + this.size += currentSize - previousSize; + return this.indexManager.addToCollectionParentIndex(transaction, key.path.popLast()); + } + /** + * Removes the specified entry from the cache and updates the cache size as appropriate. + * + * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer + * returned by `newChangeBuffer()`. + */ + removeEntry(documentKey) { + const entry = this.docs.get(documentKey); + if (entry) { + this.docs = this.docs.remove(documentKey); + this.size -= entry.size; + } + } + getEntry(transaction, documentKey) { + const entry = this.docs.get(documentKey); + return PersistencePromise.resolve(entry + ? entry.document.mutableCopy() + : MutableDocument.newInvalidDocument(documentKey)); + } + getEntries(transaction, documentKeys) { + let results = mutableDocumentMap(); + documentKeys.forEach(documentKey => { + const entry = this.docs.get(documentKey); + results = results.insert(documentKey, entry + ? entry.document.mutableCopy() + : MutableDocument.newInvalidDocument(documentKey)); + }); + return PersistencePromise.resolve(results); + } + getDocumentsMatchingQuery(transaction, query, offset, mutatedDocs) { + let results = mutableDocumentMap(); + // Documents are ordered by key, so we can use a prefix scan to narrow down + // the documents we need to match the query against. + const collectionPath = query.path; + // Document keys are ordered first by numeric value ("__id__"), + // then lexicographically by string value. Start the iterator at the minimum + // possible Document key value. + const prefix = new DocumentKey(collectionPath.child('__id' + MIN_LONG_VALUE + '__')); + const iterator = this.docs.getIteratorFrom(prefix); + while (iterator.hasNext()) { + const { key, value: { document } } = iterator.getNext(); + if (!collectionPath.isPrefixOf(key.path)) { + break; + } + if (key.path.length > collectionPath.length + 1) { + // Exclude entries from subcollections. + continue; + } + if (indexOffsetComparator(newIndexOffsetFromDocument(document), offset) <= 0) { + // The document sorts before the offset. + continue; + } + if (!mutatedDocs.has(document.key) && !queryMatches(query, document)) { + // The document cannot possibly match the query. + continue; + } + results = results.insert(document.key, document.mutableCopy()); + } + return PersistencePromise.resolve(results); + } + getAllFromCollectionGroup(transaction, collectionGroup, offset, limit) { + // This method should only be called from the IndexBackfiller if persistence + // is enabled. + fail(0x251c); + } + forEachDocumentKey(transaction, f) { + return PersistencePromise.forEach(this.docs, (key) => f(key)); + } + newChangeBuffer(options) { + // `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps + // a separate changelog and does not need special handling for removals. + return new MemoryRemoteDocumentChangeBuffer(this); + } + getSize(txn) { + return PersistencePromise.resolve(this.size); + } +} +/** + * Creates a new memory-only RemoteDocumentCache. + * + * @param sizer - Used to assess the size of a document. For eager GC, this is + * expected to just return 0 to avoid unnecessarily doing the work of + * calculating the size. + */ +function newMemoryRemoteDocumentCache(sizer) { + return new MemoryRemoteDocumentCacheImpl(sizer); +} +/** + * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache. + */ +class MemoryRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer { + constructor(documentCache) { + super(); + this.documentCache = documentCache; + } + applyChanges(transaction) { + const promises = []; + this.changes.forEach((key, doc) => { + if (doc.isValidDocument()) { + promises.push(this.documentCache.addEntry(transaction, doc)); + } + else { + this.documentCache.removeEntry(key); + } + }); + return PersistencePromise.waitFor(promises); + } + getFromCache(transaction, documentKey) { + return this.documentCache.getEntry(transaction, documentKey); + } + getAllFromCache(transaction, documentKeys) { + return this.documentCache.getEntries(transaction, documentKeys); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class MemoryTargetCache { + constructor(persistence) { + this.persistence = persistence; + /** + * Maps a target to the data about that target + */ + this.targets = new ObjectMap(t => canonifyTarget(t), targetEquals); + /** The last received snapshot version. */ + this.lastRemoteSnapshotVersion = SnapshotVersion.min(); + /** The highest numbered target ID encountered. */ + this.highestTargetId = 0; + /** The highest sequence number encountered. */ + this.highestSequenceNumber = 0; + /** + * A ordered bidirectional mapping between documents and the remote target + * IDs. + */ + this.references = new ReferenceSet(); + this.targetCount = 0; + this.targetIdGenerator = TargetIdGenerator.forTargetCache(); + } + forEachTarget(txn, f) { + this.targets.forEach((_, targetData) => f(targetData)); + return PersistencePromise.resolve(); + } + getLastRemoteSnapshotVersion(transaction) { + return PersistencePromise.resolve(this.lastRemoteSnapshotVersion); + } + getHighestSequenceNumber(transaction) { + return PersistencePromise.resolve(this.highestSequenceNumber); + } + allocateTargetId(transaction) { + this.highestTargetId = this.targetIdGenerator.next(); + return PersistencePromise.resolve(this.highestTargetId); + } + setTargetsMetadata(transaction, highestListenSequenceNumber, lastRemoteSnapshotVersion) { + if (lastRemoteSnapshotVersion) { + this.lastRemoteSnapshotVersion = lastRemoteSnapshotVersion; + } + if (highestListenSequenceNumber > this.highestSequenceNumber) { + this.highestSequenceNumber = highestListenSequenceNumber; + } + return PersistencePromise.resolve(); + } + saveTargetData(targetData) { + this.targets.set(targetData.target, targetData); + const targetId = targetData.targetId; + if (targetId > this.highestTargetId) { + this.targetIdGenerator = new TargetIdGenerator(targetId); + this.highestTargetId = targetId; + } + if (targetData.sequenceNumber > this.highestSequenceNumber) { + this.highestSequenceNumber = targetData.sequenceNumber; + } + } + addTargetData(transaction, targetData) { + this.saveTargetData(targetData); + this.targetCount += 1; + return PersistencePromise.resolve(); + } + updateTargetData(transaction, targetData) { + this.saveTargetData(targetData); + return PersistencePromise.resolve(); + } + removeTargetData(transaction, targetData) { + this.targets.delete(targetData.target); + this.references.removeReferencesForId(targetData.targetId); + this.targetCount -= 1; + return PersistencePromise.resolve(); + } + removeTargets(transaction, upperBound, activeTargetIds) { + let count = 0; + const removals = []; + this.targets.forEach((key, targetData) => { + if (targetData.sequenceNumber <= upperBound && + activeTargetIds.get(targetData.targetId) === null) { + this.targets.delete(key); + removals.push(this.removeMatchingKeysForTargetId(transaction, targetData.targetId)); + count++; + } + }); + return PersistencePromise.waitFor(removals).next(() => count); + } + getTargetCount(transaction) { + return PersistencePromise.resolve(this.targetCount); + } + getTargetData(transaction, target) { + const targetData = this.targets.get(target) || null; + return PersistencePromise.resolve(targetData); + } + addMatchingKeys(txn, keys, targetId) { + this.references.addReferences(keys, targetId); + return PersistencePromise.resolve(); + } + removeMatchingKeys(txn, keys, targetId) { + this.references.removeReferences(keys, targetId); + const referenceDelegate = this.persistence.referenceDelegate; + const promises = []; + if (referenceDelegate) { + keys.forEach(key => { + promises.push(referenceDelegate.markPotentiallyOrphaned(txn, key)); + }); + } + return PersistencePromise.waitFor(promises); + } + removeMatchingKeysForTargetId(txn, targetId) { + this.references.removeReferencesForId(targetId); + return PersistencePromise.resolve(); + } + getMatchingKeysForTargetId(txn, targetId) { + const matchingKeys = this.references.referencesForId(targetId); + return PersistencePromise.resolve(matchingKeys); + } + containsKey(txn, key) { + return PersistencePromise.resolve(this.references.containsKey(key)); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$d = 'MemoryPersistence'; +/** + * A memory-backed instance of Persistence. Data is stored only in RAM and + * not persisted across sessions. + */ +class MemoryPersistence { + /** + * The constructor accepts a factory for creating a reference delegate. This + * allows both the delegate and this instance to have strong references to + * each other without having nullable fields that would then need to be + * checked or asserted on every access. + */ + constructor(referenceDelegateFactory, serializer) { + this.mutationQueues = {}; + this.overlays = {}; + this.listenSequence = new ListenSequence(0); + this._started = false; + this._started = true; + this.globalsCache = new MemoryGlobalsCache(); + this.referenceDelegate = referenceDelegateFactory(this); + this.targetCache = new MemoryTargetCache(this); + const sizer = (doc) => this.referenceDelegate.documentSize(doc); + this.indexManager = new MemoryIndexManager(); + this.remoteDocumentCache = newMemoryRemoteDocumentCache(sizer); + this.serializer = new LocalSerializer(serializer); + this.bundleCache = new MemoryBundleCache(this.serializer); + } + start() { + return Promise.resolve(); + } + shutdown() { + // No durable state to ensure is closed on shutdown. + this._started = false; + return Promise.resolve(); + } + get started() { + return this._started; + } + setDatabaseDeletedListener() { + // No op. + } + setNetworkEnabled() { + // No op. + } + getIndexManager(user) { + // We do not currently support indices for memory persistence, so we can + // return the same shared instance of the memory index manager. + return this.indexManager; + } + getDocumentOverlayCache(user) { + let overlay = this.overlays[user.toKey()]; + if (!overlay) { + overlay = new MemoryDocumentOverlayCache(); + this.overlays[user.toKey()] = overlay; + } + return overlay; + } + getMutationQueue(user, indexManager) { + let queue = this.mutationQueues[user.toKey()]; + if (!queue) { + queue = new MemoryMutationQueue(indexManager, this.referenceDelegate); + this.mutationQueues[user.toKey()] = queue; + } + return queue; + } + getGlobalsCache() { + return this.globalsCache; + } + getTargetCache() { + return this.targetCache; + } + getRemoteDocumentCache() { + return this.remoteDocumentCache; + } + getBundleCache() { + return this.bundleCache; + } + runTransaction(action, mode, transactionOperation) { + logDebug(LOG_TAG$d, 'Starting transaction:', action); + const txn = new MemoryTransaction(this.listenSequence.next()); + this.referenceDelegate.onTransactionStarted(); + return transactionOperation(txn) + .next(result => { + return this.referenceDelegate + .onTransactionCommitted(txn) + .next(() => result); + }) + .toPromise() + .then(result => { + txn.raiseOnCommittedEvent(); + return result; + }); + } + mutationQueuesContainKey(transaction, key) { + return PersistencePromise.or(Object.values(this.mutationQueues).map(queue => () => queue.containsKey(transaction, key))); + } +} +/** + * Memory persistence is not actually transactional, but future implementations + * may have transaction-scoped state. + */ +class MemoryTransaction extends PersistenceTransaction { + constructor(currentSequenceNumber) { + super(); + this.currentSequenceNumber = currentSequenceNumber; + } +} +class MemoryEagerDelegate { + constructor(persistence) { + this.persistence = persistence; + /** Tracks all documents that are active in Query views. */ + this.localViewReferences = new ReferenceSet(); + /** The list of documents that are potentially GCed after each transaction. */ + this._orphanedDocuments = null; + } + static factory(persistence) { + return new MemoryEagerDelegate(persistence); + } + get orphanedDocuments() { + if (!this._orphanedDocuments) { + throw fail(0xee44); + } + else { + return this._orphanedDocuments; + } + } + addReference(txn, targetId, key) { + this.localViewReferences.addReference(key, targetId); + this.orphanedDocuments.delete(key.toString()); + return PersistencePromise.resolve(); + } + removeReference(txn, targetId, key) { + this.localViewReferences.removeReference(key, targetId); + this.orphanedDocuments.add(key.toString()); + return PersistencePromise.resolve(); + } + markPotentiallyOrphaned(txn, key) { + this.orphanedDocuments.add(key.toString()); + return PersistencePromise.resolve(); + } + removeTarget(txn, targetData) { + const orphaned = this.localViewReferences.removeReferencesForId(targetData.targetId); + orphaned.forEach(key => this.orphanedDocuments.add(key.toString())); + const cache = this.persistence.getTargetCache(); + return cache + .getMatchingKeysForTargetId(txn, targetData.targetId) + .next(keys => { + keys.forEach(key => this.orphanedDocuments.add(key.toString())); + }) + .next(() => cache.removeTargetData(txn, targetData)); + } + onTransactionStarted() { + this._orphanedDocuments = new Set(); + } + onTransactionCommitted(txn) { + // Remove newly orphaned documents. + const cache = this.persistence.getRemoteDocumentCache(); + const changeBuffer = cache.newChangeBuffer(); + return PersistencePromise.forEach(this.orphanedDocuments, (path) => { + const key = DocumentKey.fromPath(path); + return this.isReferenced(txn, key).next(isReferenced => { + if (!isReferenced) { + changeBuffer.removeEntry(key, SnapshotVersion.min()); + } + }); + }).next(() => { + this._orphanedDocuments = null; + return changeBuffer.apply(txn); + }); + } + updateLimboDocument(txn, key) { + return this.isReferenced(txn, key).next(isReferenced => { + if (isReferenced) { + this.orphanedDocuments.delete(key.toString()); + } + else { + this.orphanedDocuments.add(key.toString()); + } + }); + } + documentSize(doc) { + // For eager GC, we don't care about the document size, there are no size thresholds. + return 0; + } + isReferenced(txn, key) { + return PersistencePromise.or([ + () => PersistencePromise.resolve(this.localViewReferences.containsKey(key)), + () => this.persistence.getTargetCache().containsKey(txn, key), + () => this.persistence.mutationQueuesContainKey(txn, key) + ]); + } +} +class MemoryLruDelegate { + constructor(persistence, lruParams) { + this.persistence = persistence; + this.orphanedSequenceNumbers = new ObjectMap(k => encodeResourcePath(k.path), (l, r) => l.isEqual(r)); + this.garbageCollector = newLruGarbageCollector(this, lruParams); + } + static factory(persistence, lruParams) { + return new MemoryLruDelegate(persistence, lruParams); + } + // No-ops, present so memory persistence doesn't have to care which delegate + // it has. + onTransactionStarted() { } + onTransactionCommitted(txn) { + return PersistencePromise.resolve(); + } + forEachTarget(txn, f) { + return this.persistence.getTargetCache().forEachTarget(txn, f); + } + getSequenceNumberCount(txn) { + const docCountPromise = this.orphanedDocumentCount(txn); + const targetCountPromise = this.persistence + .getTargetCache() + .getTargetCount(txn); + return targetCountPromise.next(targetCount => docCountPromise.next(docCount => targetCount + docCount)); + } + orphanedDocumentCount(txn) { + let orphanedCount = 0; + return this.forEachOrphanedDocumentSequenceNumber(txn, _ => { + orphanedCount++; + }).next(() => orphanedCount); + } + forEachOrphanedDocumentSequenceNumber(txn, f) { + return PersistencePromise.forEach(this.orphanedSequenceNumbers, (key, sequenceNumber) => { + // Pass in the exact sequence number as the upper bound so we know it won't be pinned by + // being too recent. + return this.isPinned(txn, key, sequenceNumber).next(isPinned => { + if (!isPinned) { + return f(sequenceNumber); + } + else { + return PersistencePromise.resolve(); + } + }); + }); + } + removeTargets(txn, upperBound, activeTargetIds) { + return this.persistence + .getTargetCache() + .removeTargets(txn, upperBound, activeTargetIds); + } + removeOrphanedDocuments(txn, upperBound) { + let count = 0; + const cache = this.persistence.getRemoteDocumentCache(); + const changeBuffer = cache.newChangeBuffer(); + const p = cache.forEachDocumentKey(txn, key => { + return this.isPinned(txn, key, upperBound).next(isPinned => { + if (!isPinned) { + count++; + changeBuffer.removeEntry(key, SnapshotVersion.min()); + } + }); + }); + return p.next(() => changeBuffer.apply(txn)).next(() => count); + } + markPotentiallyOrphaned(txn, key) { + this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber); + return PersistencePromise.resolve(); + } + removeTarget(txn, targetData) { + const updated = targetData.withSequenceNumber(txn.currentSequenceNumber); + return this.persistence.getTargetCache().updateTargetData(txn, updated); + } + addReference(txn, targetId, key) { + this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber); + return PersistencePromise.resolve(); + } + removeReference(txn, targetId, key) { + this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber); + return PersistencePromise.resolve(); + } + updateLimboDocument(txn, key) { + this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber); + return PersistencePromise.resolve(); + } + documentSize(document) { + let documentSize = document.key.toString().length; + if (document.isFoundDocument()) { + documentSize += estimateByteSize(document.data.value); + } + return documentSize; + } + isPinned(txn, key, upperBound) { + return PersistencePromise.or([ + () => this.persistence.mutationQueuesContainKey(txn, key), + () => this.persistence.getTargetCache().containsKey(txn, key), + () => { + const orphanedAt = this.orphanedSequenceNumbers.get(key); + return PersistencePromise.resolve(orphanedAt !== undefined && orphanedAt > upperBound); + } + ]); + } + getCacheSize(txn) { + return this.persistence.getRemoteDocumentCache().getSize(txn); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Performs database creation and schema upgrades. */ +class SchemaConverter { + constructor(serializer) { + this.serializer = serializer; + } + /** + * Performs database creation and schema upgrades. + * + * Note that in production, this method is only ever used to upgrade the schema + * to SCHEMA_VERSION. Different values of toVersion are only used for testing + * and local feature development. + */ + createOrUpgrade(db, txn, fromVersion, toVersion) { + const simpleDbTransaction = new SimpleDbTransaction('createOrUpgrade', txn); + if (fromVersion < 1 && toVersion >= 1) { + createPrimaryClientStore(db); + createMutationQueue(db); + createQueryCache(db); + createLegacyRemoteDocumentCache(db); + } + // Migration 2 to populate the targetGlobal object no longer needed since + // migration 3 unconditionally clears it. + let p = PersistencePromise.resolve(); + if (fromVersion < 3 && toVersion >= 3) { + // Brand new clients don't need to drop and recreate--only clients that + // potentially have corrupt data. + if (fromVersion !== 0) { + dropQueryCache(db); + createQueryCache(db); + } + p = p.next(() => writeEmptyTargetGlobalEntry(simpleDbTransaction)); + } + if (fromVersion < 4 && toVersion >= 4) { + if (fromVersion !== 0) { + // Schema version 3 uses auto-generated keys to generate globally unique + // mutation batch IDs (this was previously ensured internally by the + // client). To migrate to the new schema, we have to read all mutations + // and write them back out. We preserve the existing batch IDs to guarantee + // consistency with other object stores. Any further mutation batch IDs will + // be auto-generated. + p = p.next(() => upgradeMutationBatchSchemaAndMigrateData(db, simpleDbTransaction)); + } + p = p.next(() => { + createClientMetadataStore(db); + }); + } + if (fromVersion < 5 && toVersion >= 5) { + p = p.next(() => this.removeAcknowledgedMutations(simpleDbTransaction)); + } + if (fromVersion < 6 && toVersion >= 6) { + p = p.next(() => { + createDocumentGlobalStore(db); + return this.addDocumentGlobal(simpleDbTransaction); + }); + } + if (fromVersion < 7 && toVersion >= 7) { + p = p.next(() => this.ensureSequenceNumbers(simpleDbTransaction)); + } + if (fromVersion < 8 && toVersion >= 8) { + p = p.next(() => this.createCollectionParentIndex(db, simpleDbTransaction)); + } + if (fromVersion < 9 && toVersion >= 9) { + p = p.next(() => { + // Multi-Tab used to manage its own changelog, but this has been moved + // to the DbRemoteDocument object store itself. Since the previous change + // log only contained transient data, we can drop its object store. + dropRemoteDocumentChangesStore(db); + // Note: Schema version 9 used to create a read time index for the + // RemoteDocumentCache. This is now done with schema version 13. + }); + } + if (fromVersion < 10 && toVersion >= 10) { + p = p.next(() => this.rewriteCanonicalIds(simpleDbTransaction)); + } + if (fromVersion < 11 && toVersion >= 11) { + p = p.next(() => { + createBundlesStore(db); + createNamedQueriesStore(db); + }); + } + if (fromVersion < 12 && toVersion >= 12) { + p = p.next(() => { + createDocumentOverlayStore(db); + }); + } + if (fromVersion < 13 && toVersion >= 13) { + p = p + .next(() => createRemoteDocumentCache(db)) + .next(() => this.rewriteRemoteDocumentCache(db, simpleDbTransaction)) + .next(() => db.deleteObjectStore(DbRemoteDocumentStore$1)); + } + if (fromVersion < 14 && toVersion >= 14) { + p = p.next(() => this.runOverlayMigration(db, simpleDbTransaction)); + } + if (fromVersion < 15 && toVersion >= 15) { + p = p.next(() => createFieldIndex(db)); + } + if (fromVersion < 16 && toVersion >= 16) { + // Clear the object stores to remove possibly corrupted index entries + p = p + .next(() => { + const indexStateStore = txn.objectStore(DbIndexStateStore); + indexStateStore.clear(); + }) + .next(() => { + const indexEntryStore = txn.objectStore(DbIndexEntryStore); + indexEntryStore.clear(); + }); + } + if (fromVersion < 17 && toVersion >= 17) { + p = p.next(() => { + createGlobalsStore(db); + }); + } + if (fromVersion < 18 && toVersion >= 18) { + // Clear the IndexEntryStores on WebKit and Safari to remove possibly + // corrupted index entries + if (util.isSafariOrWebkit()) { + p = p + .next(() => { + const indexStateStore = txn.objectStore(DbIndexStateStore); + indexStateStore.clear(); + }) + .next(() => { + const indexEntryStore = txn.objectStore(DbIndexEntryStore); + indexEntryStore.clear(); + }); + } + } + return p; + } + addDocumentGlobal(txn) { + let byteSize = 0; + return txn + .store(DbRemoteDocumentStore$1) + .iterate((_, doc) => { + byteSize += dbDocumentSize(doc); + }) + .next(() => { + const metadata = { byteSize }; + return txn + .store(DbRemoteDocumentGlobalStore) + .put(DbRemoteDocumentGlobalKey, metadata); + }); + } + removeAcknowledgedMutations(txn) { + const queuesStore = txn.store(DbMutationQueueStore); + const mutationsStore = txn.store(DbMutationBatchStore); + return queuesStore.loadAll().next(queues => { + return PersistencePromise.forEach(queues, (queue) => { + const range = IDBKeyRange.bound([queue.userId, BATCHID_UNKNOWN], [queue.userId, queue.lastAcknowledgedBatchId]); + return mutationsStore + .loadAll(DbMutationBatchUserMutationsIndex, range) + .next(dbBatches => { + return PersistencePromise.forEach(dbBatches, (dbBatch) => { + hardAssert(dbBatch.userId === queue.userId, 0x48da, `Cannot process batch from unexpected user`, { batchId: dbBatch.batchId }); + const batch = fromDbMutationBatch(this.serializer, dbBatch); + return removeMutationBatch(txn, queue.userId, batch).next(() => { }); + }); + }); + }); + }); + } + /** + * Ensures that every document in the remote document cache has a corresponding sentinel row + * with a sequence number. Missing rows are given the most recently used sequence number. + */ + ensureSequenceNumbers(txn) { + const documentTargetStore = txn.store(DbTargetDocumentStore); + const documentsStore = txn.store(DbRemoteDocumentStore$1); + const globalTargetStore = txn.store(DbTargetGlobalStore); + return globalTargetStore.get(DbTargetGlobalKey).next(metadata => { + const writeSentinelKey = (path) => { + return documentTargetStore.put({ + targetId: 0, + path: encodeResourcePath(path), + sequenceNumber: metadata.highestListenSequenceNumber + }); + }; + const promises = []; + return documentsStore + .iterate((key, doc) => { + const path = new ResourcePath(key); + const docSentinelKey = sentinelKey(path); + promises.push(documentTargetStore.get(docSentinelKey).next(maybeSentinel => { + if (!maybeSentinel) { + return writeSentinelKey(path); + } + else { + return PersistencePromise.resolve(); + } + })); + }) + .next(() => PersistencePromise.waitFor(promises)); + }); + } + createCollectionParentIndex(db, txn) { + // Create the index. + db.createObjectStore(DbCollectionParentStore, { + keyPath: DbCollectionParentKeyPath + }); + const collectionParentsStore = txn.store(DbCollectionParentStore); + // Helper to add an index entry iff we haven't already written it. + const cache = new MemoryCollectionParentIndex(); + const addEntry = (collectionPath) => { + if (cache.add(collectionPath)) { + const collectionId = collectionPath.lastSegment(); + const parentPath = collectionPath.popLast(); + return collectionParentsStore.put({ + collectionId, + parent: encodeResourcePath(parentPath) + }); + } + }; + // Index existing remote documents. + return txn + .store(DbRemoteDocumentStore$1) + .iterate({ keysOnly: true }, (pathSegments, _) => { + const path = new ResourcePath(pathSegments); + return addEntry(path.popLast()); + }) + .next(() => { + // Index existing mutations. + return txn + .store(DbDocumentMutationStore) + .iterate({ keysOnly: true }, ([userID, encodedPath, batchId], _) => { + const path = decodeResourcePath(encodedPath); + return addEntry(path.popLast()); + }); + }); + } + rewriteCanonicalIds(txn) { + const targetStore = txn.store(DbTargetStore); + return targetStore.iterate((key, originalDbTarget) => { + const originalTargetData = fromDbTarget(originalDbTarget); + const updatedDbTarget = toDbTarget(this.serializer, originalTargetData); + return targetStore.put(updatedDbTarget); + }); + } + rewriteRemoteDocumentCache(db, transaction) { + const legacyRemoteDocumentStore = transaction.store(DbRemoteDocumentStore$1); + const writes = []; + return legacyRemoteDocumentStore + .iterate((_, legacyDocument) => { + const remoteDocumentStore = transaction.store(DbRemoteDocumentStore); + const path = extractKey(legacyDocument).path.toArray(); + const dbRemoteDocument = { + prefixPath: path.slice(0, path.length - 2), + collectionGroup: path[path.length - 2], + documentId: path[path.length - 1], + readTime: legacyDocument.readTime || [0, 0], + unknownDocument: legacyDocument.unknownDocument, + noDocument: legacyDocument.noDocument, + document: legacyDocument.document, + hasCommittedMutations: !!legacyDocument.hasCommittedMutations + }; + writes.push(remoteDocumentStore.put(dbRemoteDocument)); + }) + .next(() => PersistencePromise.waitFor(writes)); + } + runOverlayMigration(db, transaction) { + const mutationsStore = transaction.store(DbMutationBatchStore); + const remoteDocumentCache = newIndexedDbRemoteDocumentCache(this.serializer); + const memoryPersistence = new MemoryPersistence(MemoryEagerDelegate.factory, this.serializer.remoteSerializer); + return mutationsStore.loadAll().next(dbBatches => { + const userToDocumentSet = new Map(); + dbBatches.forEach(dbBatch => { + let documentSet = userToDocumentSet.get(dbBatch.userId) ?? documentKeySet(); + const batch = fromDbMutationBatch(this.serializer, dbBatch); + batch.keys().forEach(key => (documentSet = documentSet.add(key))); + userToDocumentSet.set(dbBatch.userId, documentSet); + }); + return PersistencePromise.forEach(userToDocumentSet, (allDocumentKeysForUser, userId) => { + const user = new User(userId); + const documentOverlayCache = IndexedDbDocumentOverlayCache.forUser(this.serializer, user); + // NOTE: The index manager and the reference delegate are + // irrelevant for the purpose of recalculating and saving + // overlays. We can therefore simply use the memory + // implementation. + const indexManager = memoryPersistence.getIndexManager(user); + const mutationQueue = IndexedDbMutationQueue.forUser(user, this.serializer, indexManager, memoryPersistence.referenceDelegate); + const localDocumentsView = new LocalDocumentsView(remoteDocumentCache, mutationQueue, documentOverlayCache, indexManager); + return localDocumentsView + .recalculateAndSaveOverlaysForDocumentKeys(new IndexedDbTransaction(transaction, ListenSequence.INVALID), allDocumentKeysForUser) + .next(); + }); + }); + } +} +function sentinelKey(path) { + return [0, encodeResourcePath(path)]; +} +function createPrimaryClientStore(db) { + db.createObjectStore(DbPrimaryClientStore); +} +function createMutationQueue(db) { + db.createObjectStore(DbMutationQueueStore, { + keyPath: DbMutationQueueKeyPath + }); + const mutationBatchesStore = db.createObjectStore(DbMutationBatchStore, { + keyPath: DbMutationBatchKeyPath, + autoIncrement: true + }); + mutationBatchesStore.createIndex(DbMutationBatchUserMutationsIndex, DbMutationBatchUserMutationsKeyPath, { unique: true }); + db.createObjectStore(DbDocumentMutationStore); +} +/** + * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads + * and rewrites all data. + */ +function upgradeMutationBatchSchemaAndMigrateData(db, txn) { + const v1MutationsStore = txn.store(DbMutationBatchStore); + return v1MutationsStore.loadAll().next(existingMutations => { + db.deleteObjectStore(DbMutationBatchStore); + const mutationsStore = db.createObjectStore(DbMutationBatchStore, { + keyPath: DbMutationBatchKeyPath, + autoIncrement: true + }); + mutationsStore.createIndex(DbMutationBatchUserMutationsIndex, DbMutationBatchUserMutationsKeyPath, { unique: true }); + const v3MutationsStore = txn.store(DbMutationBatchStore); + const writeAll = existingMutations.map(mutation => v3MutationsStore.put(mutation)); + return PersistencePromise.waitFor(writeAll); + }); +} +function createLegacyRemoteDocumentCache(db) { + db.createObjectStore(DbRemoteDocumentStore$1); +} +function createRemoteDocumentCache(db) { + const remoteDocumentStore = db.createObjectStore(DbRemoteDocumentStore, { + keyPath: DbRemoteDocumentKeyPath + }); + remoteDocumentStore.createIndex(DbRemoteDocumentDocumentKeyIndex, DbRemoteDocumentDocumentKeyIndexPath); + remoteDocumentStore.createIndex(DbRemoteDocumentCollectionGroupIndex, DbRemoteDocumentCollectionGroupIndexPath); +} +function createDocumentGlobalStore(db) { + db.createObjectStore(DbRemoteDocumentGlobalStore); +} +function createQueryCache(db) { + const targetDocumentsStore = db.createObjectStore(DbTargetDocumentStore, { + keyPath: DbTargetDocumentKeyPath + }); + targetDocumentsStore.createIndex(DbTargetDocumentDocumentTargetsIndex, DbTargetDocumentDocumentTargetsKeyPath, { unique: true }); + const targetStore = db.createObjectStore(DbTargetStore, { + keyPath: DbTargetKeyPath + }); + // NOTE: This is unique only because the TargetId is the suffix. + targetStore.createIndex(DbTargetQueryTargetsIndexName, DbTargetQueryTargetsKeyPath, { unique: true }); + db.createObjectStore(DbTargetGlobalStore); +} +function dropQueryCache(db) { + db.deleteObjectStore(DbTargetDocumentStore); + db.deleteObjectStore(DbTargetStore); + db.deleteObjectStore(DbTargetGlobalStore); +} +function dropRemoteDocumentChangesStore(db) { + if (db.objectStoreNames.contains('remoteDocumentChanges')) { + db.deleteObjectStore('remoteDocumentChanges'); + } +} +/** + * Creates the target global singleton row. + * + * @param txn - The version upgrade transaction for indexeddb + */ +function writeEmptyTargetGlobalEntry(txn) { + const globalStore = txn.store(DbTargetGlobalStore); + const metadata = { + highestTargetId: 0, + highestListenSequenceNumber: 0, + lastRemoteSnapshotVersion: SnapshotVersion.min().toTimestamp(), + targetCount: 0 + }; + return globalStore.put(DbTargetGlobalKey, metadata); +} +function createClientMetadataStore(db) { + db.createObjectStore(DbClientMetadataStore, { + keyPath: DbClientMetadataKeyPath + }); +} +function createBundlesStore(db) { + db.createObjectStore(DbBundleStore, { + keyPath: DbBundleKeyPath + }); +} +function createNamedQueriesStore(db) { + db.createObjectStore(DbNamedQueryStore, { + keyPath: DbNamedQueryKeyPath + }); +} +function createFieldIndex(db) { + const indexConfigurationStore = db.createObjectStore(DbIndexConfigurationStore, { + keyPath: DbIndexConfigurationKeyPath, + autoIncrement: true + }); + indexConfigurationStore.createIndex(DbIndexConfigurationCollectionGroupIndex, DbIndexConfigurationCollectionGroupIndexPath, { unique: false }); + const indexStateStore = db.createObjectStore(DbIndexStateStore, { + keyPath: DbIndexStateKeyPath + }); + indexStateStore.createIndex(DbIndexStateSequenceNumberIndex, DbIndexStateSequenceNumberIndexPath, { unique: false }); + const indexEntryStore = db.createObjectStore(DbIndexEntryStore, { + keyPath: DbIndexEntryKeyPath + }); + indexEntryStore.createIndex(DbIndexEntryDocumentKeyIndex, DbIndexEntryDocumentKeyIndexPath, { unique: false }); +} +function createDocumentOverlayStore(db) { + const documentOverlayStore = db.createObjectStore(DbDocumentOverlayStore, { + keyPath: DbDocumentOverlayKeyPath + }); + documentOverlayStore.createIndex(DbDocumentOverlayCollectionPathOverlayIndex, DbDocumentOverlayCollectionPathOverlayIndexPath, { unique: false }); + documentOverlayStore.createIndex(DbDocumentOverlayCollectionGroupOverlayIndex, DbDocumentOverlayCollectionGroupOverlayIndexPath, { unique: false }); +} +function createGlobalsStore(db) { + db.createObjectStore(DbGlobalsStore, { + keyPath: DbGlobalsKeyPath + }); +} +function extractKey(remoteDoc) { + if (remoteDoc.document) { + return new DocumentKey(ResourcePath.fromString(remoteDoc.document.name).popFirst(5)); + } + else if (remoteDoc.noDocument) { + return DocumentKey.fromSegments(remoteDoc.noDocument.path); + } + else if (remoteDoc.unknownDocument) { + return DocumentKey.fromSegments(remoteDoc.unknownDocument.path); + } + else { + return fail(0x8faf); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$c = 'IndexedDbPersistence'; +/** + * Oldest acceptable age in milliseconds for client metadata before the client + * is considered inactive and its associated data is garbage collected. + */ +const MAX_CLIENT_AGE_MS = 30 * 60 * 1000; // 30 minutes +/** + * Oldest acceptable metadata age for clients that may participate in the + * primary lease election. Clients that have not updated their client metadata + * within 5 seconds are not eligible to receive a primary lease. + */ +const MAX_PRIMARY_ELIGIBLE_AGE_MS = 5000; +/** + * The interval at which clients will update their metadata, including + * refreshing their primary lease if held or potentially trying to acquire it if + * not held. + * + * Primary clients may opportunistically refresh their metadata earlier + * if they're already performing an IndexedDB operation. + */ +const CLIENT_METADATA_REFRESH_INTERVAL_MS = 4000; +/** User-facing error when the primary lease is required but not available. */ +const PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG = 'Failed to obtain exclusive access to the persistence layer. To allow ' + + 'shared access, multi-tab synchronization has to be enabled in all tabs. ' + + 'If you are using `experimentalForceOwningTab:true`, make sure that only ' + + 'one tab has persistence enabled at any given time.'; +const UNSUPPORTED_PLATFORM_ERROR_MSG = 'This platform is either missing IndexedDB or is known to have ' + + 'an incomplete implementation. Offline persistence has been disabled.'; +// The format of the LocalStorage key that stores zombied client is: +// firestore_zombie__ +const ZOMBIED_CLIENTS_KEY_PREFIX = 'firestore_zombie'; +/** + * The name of the main (and currently only) IndexedDB database. This name is + * appended to the prefix provided to the IndexedDbPersistence constructor. + */ +const MAIN_DATABASE = 'main'; +/** + * An IndexedDB-backed instance of Persistence. Data is stored persistently + * across sessions. + * + * On Web only, the Firestore SDKs support shared access to its persistence + * layer. This allows multiple browser tabs to read and write to IndexedDb and + * to synchronize state even without network connectivity. Shared access is + * currently optional and not enabled unless all clients invoke + * `enablePersistence()` with `{synchronizeTabs:true}`. + * + * In multi-tab mode, if multiple clients are active at the same time, the SDK + * will designate one client as the "primary client". An effort is made to pick + * a visible, network-connected and active client, and this client is + * responsible for letting other clients know about its presence. The primary + * client writes a unique client-generated identifier (the client ID) to + * IndexedDb’s "owner" store every 4 seconds. If the primary client fails to + * update this entry, another client can acquire the lease and take over as + * primary. + * + * Some persistence operations in the SDK are designated as primary-client only + * operations. This includes the acknowledgment of mutations and all updates of + * remote documents. The effects of these operations are written to persistence + * and then broadcast to other tabs via LocalStorage (see + * `WebStorageSharedClientState`), which then refresh their state from + * persistence. + * + * Similarly, the primary client listens to notifications sent by secondary + * clients to discover persistence changes written by secondary clients, such as + * the addition of new mutations and query targets. + * + * If multi-tab is not enabled and another tab already obtained the primary + * lease, IndexedDbPersistence enters a failed state and all subsequent + * operations will automatically fail. + * + * Additionally, there is an optimization so that when a tab is closed, the + * primary lease is released immediately (this is especially important to make + * sure that a refreshed tab is able to immediately re-acquire the primary + * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload + * since it is an asynchronous API. So in addition to attempting to give up the + * lease, the leaseholder writes its client ID to a "zombiedClient" entry in + * LocalStorage which acts as an indicator that another tab should go ahead and + * take the primary lease immediately regardless of the current lease timestamp. + * + * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no + * longer optional. + */ +class IndexedDbPersistence { + constructor( + /** + * Whether to synchronize the in-memory state of multiple tabs and share + * access to local persistence. + */ + allowTabSynchronization, persistenceKey, clientId, lruParams, queue, window, document, serializer, sequenceNumberSyncer, + /** + * If set to true, forcefully obtains database access. Existing tabs will + * no longer be able to access IndexedDB. + */ + forceOwningTab, schemaVersion = SCHEMA_VERSION) { + this.allowTabSynchronization = allowTabSynchronization; + this.persistenceKey = persistenceKey; + this.clientId = clientId; + this.queue = queue; + this.window = window; + this.document = document; + this.sequenceNumberSyncer = sequenceNumberSyncer; + this.forceOwningTab = forceOwningTab; + this.schemaVersion = schemaVersion; + this.listenSequence = null; + this._started = false; + this.isPrimary = false; + this.networkEnabled = true; + /** Our window.unload handler, if registered. */ + this.windowUnloadHandler = null; + this.inForeground = false; + /** Our 'visibilitychange' listener if registered. */ + this.documentVisibilityHandler = null; + /** The client metadata refresh task. */ + this.clientMetadataRefresher = null; + /** The last time we garbage collected the client metadata object store. */ + this.lastGarbageCollectionTime = Number.NEGATIVE_INFINITY; + /** A listener to notify on primary state changes. */ + this.primaryStateListener = _ => Promise.resolve(); + if (!IndexedDbPersistence.isAvailable()) { + throw new FirestoreError(Code.UNIMPLEMENTED, UNSUPPORTED_PLATFORM_ERROR_MSG); + } + this.referenceDelegate = new IndexedDbLruDelegateImpl(this, lruParams); + this.dbName = persistenceKey + MAIN_DATABASE; + this.serializer = new LocalSerializer(serializer); + this.simpleDb = new SimpleDb(this.dbName, this.schemaVersion, new SchemaConverter(this.serializer)); + this.globalsCache = new IndexedDbGlobalsCache(); + this.targetCache = new IndexedDbTargetCache(this.referenceDelegate, this.serializer); + this.remoteDocumentCache = newIndexedDbRemoteDocumentCache(this.serializer); + this.bundleCache = new IndexedDbBundleCache(); + if (this.window && this.window.localStorage) { + this.webStorage = this.window.localStorage; + } + else { + this.webStorage = null; + if (forceOwningTab === false) { + logError(LOG_TAG$c, 'LocalStorage is unavailable. As a result, persistence may not work ' + + 'reliably. In particular enablePersistence() could fail immediately ' + + 'after refreshing the page.'); + } + } + } + /** + * Attempt to start IndexedDb persistence. + * + * @returns Whether persistence was enabled. + */ + start() { + // NOTE: This is expected to fail sometimes (in the case of another tab + // already having the persistence lock), so it's the first thing we should + // do. + return this.updateClientMetadataAndTryBecomePrimary() + .then(() => { + if (!this.isPrimary && !this.allowTabSynchronization) { + // Fail `start()` if `synchronizeTabs` is disabled and we cannot + // obtain the primary lease. + throw new FirestoreError(Code.FAILED_PRECONDITION, PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG); + } + this.attachVisibilityHandler(); + this.attachWindowUnloadHook(); + this.scheduleClientMetadataAndPrimaryLeaseRefreshes(); + return this.runTransaction('getHighestListenSequenceNumber', 'readonly', txn => this.targetCache.getHighestSequenceNumber(txn)); + }) + .then(highestListenSequenceNumber => { + this.listenSequence = new ListenSequence(highestListenSequenceNumber, this.sequenceNumberSyncer); + }) + .then(() => { + this._started = true; + }) + .catch(reason => { + this.simpleDb && this.simpleDb.close(); + return Promise.reject(reason); + }); + } + /** + * Registers a listener that gets called when the primary state of the + * instance changes. Upon registering, this listener is invoked immediately + * with the current primary state. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setPrimaryStateListener(primaryStateListener) { + this.primaryStateListener = async (primaryState) => { + if (this.started) { + return primaryStateListener(primaryState); + } + }; + return primaryStateListener(this.isPrimary); + } + /** + * Registers a listener that gets called when the database receives a + * version change event indicating that it has deleted. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setDatabaseDeletedListener(databaseDeletedListener) { + this.simpleDb.setVersionChangeListener(async (event) => { + // Check if an attempt is made to delete IndexedDB. + if (event.newVersion === null) { + await databaseDeletedListener(); + } + }); + } + /** + * Adjusts the current network state in the client's metadata, potentially + * affecting the primary lease. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setNetworkEnabled(networkEnabled) { + if (this.networkEnabled !== networkEnabled) { + this.networkEnabled = networkEnabled; + // Schedule a primary lease refresh for immediate execution. The eventual + // lease update will be propagated via `primaryStateListener`. + this.queue.enqueueAndForget(async () => { + if (this.started) { + await this.updateClientMetadataAndTryBecomePrimary(); + } + }); + } + } + /** + * Updates the client metadata in IndexedDb and attempts to either obtain or + * extend the primary lease for the local client. Asynchronously notifies the + * primary state listener if the client either newly obtained or released its + * primary lease. + */ + updateClientMetadataAndTryBecomePrimary() { + return this.runTransaction('updateClientMetadataAndTryBecomePrimary', 'readwrite', txn => { + const metadataStore = clientMetadataStore(txn); + return metadataStore + .put({ + clientId: this.clientId, + updateTimeMs: Date.now(), + networkEnabled: this.networkEnabled, + inForeground: this.inForeground + }) + .next(() => { + if (this.isPrimary) { + return this.verifyPrimaryLease(txn).next(success => { + if (!success) { + this.isPrimary = false; + this.queue.enqueueRetryable(() => this.primaryStateListener(false)); + } + }); + } + }) + .next(() => this.canActAsPrimary(txn)) + .next(canActAsPrimary => { + if (this.isPrimary && !canActAsPrimary) { + return this.releasePrimaryLeaseIfHeld(txn).next(() => false); + } + else if (canActAsPrimary) { + return this.acquireOrExtendPrimaryLease(txn).next(() => true); + } + else { + return /* canActAsPrimary= */ false; + } + }); + }) + .catch(e => { + if (isIndexedDbTransactionError(e)) { + logDebug(LOG_TAG$c, 'Failed to extend owner lease: ', e); + // Proceed with the existing state. Any subsequent access to + // IndexedDB will verify the lease. + return this.isPrimary; + } + if (!this.allowTabSynchronization) { + throw e; + } + logDebug(LOG_TAG$c, 'Releasing owner lease after error during lease refresh', e); + return /* isPrimary= */ false; + }) + .then(isPrimary => { + if (this.isPrimary !== isPrimary) { + this.queue.enqueueRetryable(() => this.primaryStateListener(isPrimary)); + } + this.isPrimary = isPrimary; + }); + } + verifyPrimaryLease(txn) { + const store = primaryClientStore(txn); + return store.get(DbPrimaryClientKey).next(primaryClient => { + return PersistencePromise.resolve(this.isLocalClient(primaryClient)); + }); + } + removeClientMetadata(txn) { + const metadataStore = clientMetadataStore(txn); + return metadataStore.delete(this.clientId); + } + /** + * If the garbage collection threshold has passed, prunes the + * RemoteDocumentChanges and the ClientMetadata store based on the last update + * time of all clients. + */ + async maybeGarbageCollectMultiClientState() { + if (this.isPrimary && + !this.isWithinAge(this.lastGarbageCollectionTime, MAX_CLIENT_AGE_MS)) { + this.lastGarbageCollectionTime = Date.now(); + const inactiveClients = await this.runTransaction('maybeGarbageCollectMultiClientState', 'readwrite-primary', txn => { + const metadataStore = getStore(txn, DbClientMetadataStore); + return metadataStore.loadAll().next(existingClients => { + const active = this.filterActiveClients(existingClients, MAX_CLIENT_AGE_MS); + const inactive = existingClients.filter(client => active.indexOf(client) === -1); + // Delete metadata for clients that are no longer considered active. + return PersistencePromise.forEach(inactive, (inactiveClient) => metadataStore.delete(inactiveClient.clientId)).next(() => inactive); + }); + }).catch(() => { + // Ignore primary lease violations or any other type of error. The next + // primary will run `maybeGarbageCollectMultiClientState()` again. + // We don't use `ignoreIfPrimaryLeaseLoss()` since we don't want to depend + // on LocalStore. + return []; + }); + // Delete potential leftover entries that may continue to mark the + // inactive clients as zombied in LocalStorage. + // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for + // the client atomically, but we can't. So we opt to delete the IndexedDb + // entries first to avoid potentially reviving a zombied client. + if (this.webStorage) { + for (const inactiveClient of inactiveClients) { + this.webStorage.removeItem(this.zombiedClientLocalStorageKey(inactiveClient.clientId)); + } + } + } + } + /** + * Schedules a recurring timer to update the client metadata and to either + * extend or acquire the primary lease if the client is eligible. + */ + scheduleClientMetadataAndPrimaryLeaseRefreshes() { + this.clientMetadataRefresher = this.queue.enqueueAfterDelay("client_metadata_refresh" /* TimerId.ClientMetadataRefresh */, CLIENT_METADATA_REFRESH_INTERVAL_MS, () => { + return this.updateClientMetadataAndTryBecomePrimary() + .then(() => this.maybeGarbageCollectMultiClientState()) + .then(() => this.scheduleClientMetadataAndPrimaryLeaseRefreshes()); + }); + } + /** Checks whether `client` is the local client. */ + isLocalClient(client) { + return client ? client.ownerId === this.clientId : false; + } + /** + * Evaluate the state of all active clients and determine whether the local + * client is or can act as the holder of the primary lease. Returns whether + * the client is eligible for the lease, but does not actually acquire it. + * May return 'false' even if there is no active leaseholder and another + * (foreground) client should become leaseholder instead. + */ + canActAsPrimary(txn) { + if (this.forceOwningTab) { + return PersistencePromise.resolve(true); + } + const store = primaryClientStore(txn); + return store + .get(DbPrimaryClientKey) + .next(currentPrimary => { + const currentLeaseIsValid = currentPrimary !== null && + this.isWithinAge(currentPrimary.leaseTimestampMs, MAX_PRIMARY_ELIGIBLE_AGE_MS) && + !this.isClientZombied(currentPrimary.ownerId); + // A client is eligible for the primary lease if: + // - its network is enabled and the client's tab is in the foreground. + // - its network is enabled and no other client's tab is in the + // foreground. + // - every clients network is disabled and the client's tab is in the + // foreground. + // - every clients network is disabled and no other client's tab is in + // the foreground. + // - the `forceOwningTab` setting was passed in. + if (currentLeaseIsValid) { + if (this.isLocalClient(currentPrimary) && this.networkEnabled) { + return true; + } + if (!this.isLocalClient(currentPrimary)) { + if (!currentPrimary.allowTabSynchronization) { + // Fail the `canActAsPrimary` check if the current leaseholder has + // not opted into multi-tab synchronization. If this happens at + // client startup, we reject the Promise returned by + // `enablePersistence()` and the user can continue to use Firestore + // with in-memory persistence. + // If this fails during a lease refresh, we will instead block the + // AsyncQueue from executing further operations. Note that this is + // acceptable since mixing & matching different `synchronizeTabs` + // settings is not supported. + // + // TODO(b/114226234): Remove this check when `synchronizeTabs` can + // no longer be turned off. + throw new FirestoreError(Code.FAILED_PRECONDITION, PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG); + } + return false; + } + } + if (this.networkEnabled && this.inForeground) { + return true; + } + return clientMetadataStore(txn) + .loadAll() + .next(existingClients => { + // Process all existing clients and determine whether at least one of + // them is better suited to obtain the primary lease. + const preferredCandidate = this.filterActiveClients(existingClients, MAX_PRIMARY_ELIGIBLE_AGE_MS).find(otherClient => { + if (this.clientId !== otherClient.clientId) { + const otherClientHasBetterNetworkState = !this.networkEnabled && otherClient.networkEnabled; + const otherClientHasBetterVisibility = !this.inForeground && otherClient.inForeground; + const otherClientHasSameNetworkState = this.networkEnabled === otherClient.networkEnabled; + if (otherClientHasBetterNetworkState || + (otherClientHasBetterVisibility && + otherClientHasSameNetworkState)) { + return true; + } + } + return false; + }); + return preferredCandidate === undefined; + }); + }) + .next(canActAsPrimary => { + if (this.isPrimary !== canActAsPrimary) { + logDebug(LOG_TAG$c, `Client ${canActAsPrimary ? 'is' : 'is not'} eligible for a primary lease.`); + } + return canActAsPrimary; + }); + } + async shutdown() { + // The shutdown() operations are idempotent and can be called even when + // start() aborted (e.g. because it couldn't acquire the persistence lease). + this._started = false; + this.markClientZombied(); + if (this.clientMetadataRefresher) { + this.clientMetadataRefresher.cancel(); + this.clientMetadataRefresher = null; + } + this.detachVisibilityHandler(); + this.detachWindowUnloadHook(); + // Use `SimpleDb.runTransaction` directly to avoid failing if another tab + // has obtained the primary lease. + await this.simpleDb.runTransaction('shutdown', 'readwrite', [DbPrimaryClientStore, DbClientMetadataStore], simpleDbTxn => { + const persistenceTransaction = new IndexedDbTransaction(simpleDbTxn, ListenSequence.INVALID); + return this.releasePrimaryLeaseIfHeld(persistenceTransaction).next(() => this.removeClientMetadata(persistenceTransaction)); + }); + this.simpleDb.close(); + // Remove the entry marking the client as zombied from LocalStorage since + // we successfully deleted its metadata from IndexedDb. + this.removeClientZombiedEntry(); + } + /** + * Returns clients that are not zombied and have an updateTime within the + * provided threshold. + */ + filterActiveClients(clients, activityThresholdMs) { + return clients.filter(client => this.isWithinAge(client.updateTimeMs, activityThresholdMs) && + !this.isClientZombied(client.clientId)); + } + /** + * Returns the IDs of the clients that are currently active. If multi-tab + * is not supported, returns an array that only contains the local client's + * ID. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + getActiveClients() { + return this.runTransaction('getActiveClients', 'readonly', txn => { + return clientMetadataStore(txn) + .loadAll() + .next(clients => this.filterActiveClients(clients, MAX_CLIENT_AGE_MS).map(clientMetadata => clientMetadata.clientId)); + }); + } + get started() { + return this._started; + } + getGlobalsCache() { + return this.globalsCache; + } + getMutationQueue(user, indexManager) { + return IndexedDbMutationQueue.forUser(user, this.serializer, indexManager, this.referenceDelegate); + } + getTargetCache() { + return this.targetCache; + } + getRemoteDocumentCache() { + return this.remoteDocumentCache; + } + getIndexManager(user) { + return new IndexedDbIndexManager(user, this.serializer.remoteSerializer.databaseId); + } + getDocumentOverlayCache(user) { + return IndexedDbDocumentOverlayCache.forUser(this.serializer, user); + } + getBundleCache() { + return this.bundleCache; + } + runTransaction(action, mode, transactionOperation) { + logDebug(LOG_TAG$c, 'Starting transaction:', action); + const simpleDbMode = mode === 'readonly' ? 'readonly' : 'readwrite'; + const objectStores = getObjectStores(this.schemaVersion); + let persistenceTransaction; + // Do all transactions as readwrite against all object stores, since we + // are the only reader/writer. + return this.simpleDb + .runTransaction(action, simpleDbMode, objectStores, simpleDbTxn => { + persistenceTransaction = new IndexedDbTransaction(simpleDbTxn, this.listenSequence + ? this.listenSequence.next() + : ListenSequence.INVALID); + if (mode === 'readwrite-primary') { + // While we merely verify that we have (or can acquire) the lease + // immediately, we wait to extend the primary lease until after + // executing transactionOperation(). This ensures that even if the + // transactionOperation takes a long time, we'll use a recent + // leaseTimestampMs in the extended (or newly acquired) lease. + return this.verifyPrimaryLease(persistenceTransaction) + .next(holdsPrimaryLease => { + if (holdsPrimaryLease) { + return /* holdsPrimaryLease= */ true; + } + return this.canActAsPrimary(persistenceTransaction); + }) + .next(holdsPrimaryLease => { + if (!holdsPrimaryLease) { + logError(`Failed to obtain primary lease for action '${action}'.`); + this.isPrimary = false; + this.queue.enqueueRetryable(() => this.primaryStateListener(false)); + throw new FirestoreError(Code.FAILED_PRECONDITION, PRIMARY_LEASE_LOST_ERROR_MSG); + } + return transactionOperation(persistenceTransaction); + }) + .next(result => { + return this.acquireOrExtendPrimaryLease(persistenceTransaction).next(() => result); + }); + } + else { + return this.verifyAllowTabSynchronization(persistenceTransaction).next(() => transactionOperation(persistenceTransaction)); + } + }) + .then(result => { + persistenceTransaction.raiseOnCommittedEvent(); + return result; + }); + } + /** + * Verifies that the current tab is the primary leaseholder or alternatively + * that the leaseholder has opted into multi-tab synchronization. + */ + // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer + // be turned off. + verifyAllowTabSynchronization(txn) { + const store = primaryClientStore(txn); + return store.get(DbPrimaryClientKey).next(currentPrimary => { + const currentLeaseIsValid = currentPrimary !== null && + this.isWithinAge(currentPrimary.leaseTimestampMs, MAX_PRIMARY_ELIGIBLE_AGE_MS) && + !this.isClientZombied(currentPrimary.ownerId); + if (currentLeaseIsValid && !this.isLocalClient(currentPrimary)) { + if (!this.forceOwningTab && + (!this.allowTabSynchronization || + !currentPrimary.allowTabSynchronization)) { + throw new FirestoreError(Code.FAILED_PRECONDITION, PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG); + } + } + }); + } + /** + * Obtains or extends the new primary lease for the local client. This + * method does not verify that the client is eligible for this lease. + */ + acquireOrExtendPrimaryLease(txn) { + const newPrimary = { + ownerId: this.clientId, + allowTabSynchronization: this.allowTabSynchronization, + leaseTimestampMs: Date.now() + }; + return primaryClientStore(txn).put(DbPrimaryClientKey, newPrimary); + } + static isAvailable() { + return SimpleDb.isAvailable(); + } + /** Checks the primary lease and removes it if we are the current primary. */ + releasePrimaryLeaseIfHeld(txn) { + const store = primaryClientStore(txn); + return store.get(DbPrimaryClientKey).next(primaryClient => { + if (this.isLocalClient(primaryClient)) { + logDebug(LOG_TAG$c, 'Releasing primary lease.'); + return store.delete(DbPrimaryClientKey); + } + else { + return PersistencePromise.resolve(); + } + }); + } + /** Verifies that `updateTimeMs` is within `maxAgeMs`. */ + isWithinAge(updateTimeMs, maxAgeMs) { + const now = Date.now(); + const minAcceptable = now - maxAgeMs; + const maxAcceptable = now; + if (updateTimeMs < minAcceptable) { + return false; + } + else if (updateTimeMs > maxAcceptable) { + logError(`Detected an update time that is in the future: ${updateTimeMs} > ${maxAcceptable}`); + return false; + } + return true; + } + attachVisibilityHandler() { + if (this.document !== null && + typeof this.document.addEventListener === 'function') { + this.documentVisibilityHandler = () => { + this.queue.enqueueAndForget(() => { + this.inForeground = this.document.visibilityState === 'visible'; + return this.updateClientMetadataAndTryBecomePrimary(); + }); + }; + this.document.addEventListener('visibilitychange', this.documentVisibilityHandler); + this.inForeground = this.document.visibilityState === 'visible'; + } + } + detachVisibilityHandler() { + if (this.documentVisibilityHandler) { + this.document.removeEventListener('visibilitychange', this.documentVisibilityHandler); + this.documentVisibilityHandler = null; + } + } + /** + * Attaches a window.unload handler that will synchronously write our + * clientId to a "zombie client id" location in LocalStorage. This can be used + * by tabs trying to acquire the primary lease to determine that the lease + * is no longer valid even if the timestamp is recent. This is particularly + * important for the refresh case (so the tab correctly re-acquires the + * primary lease). LocalStorage is used for this rather than IndexedDb because + * it is a synchronous API and so can be used reliably from an unload + * handler. + */ + attachWindowUnloadHook() { + if (typeof this.window?.addEventListener === 'function') { + this.windowUnloadHandler = () => { + // Note: In theory, this should be scheduled on the AsyncQueue since it + // accesses internal state. We execute this code directly during shutdown + // to make sure it gets a chance to run. + this.markClientZombied(); + const safariIndexdbBugVersionRegex = /(?:Version|Mobile)\/1[456]/; + if (util.isSafari() && + (navigator.appVersion.match(safariIndexdbBugVersionRegex) || + navigator.userAgent.match(safariIndexdbBugVersionRegex))) { + // On Safari 14, 15, and 16, we do not run any cleanup actions as it might + // trigger a bug that prevents Safari from re-opening IndexedDB during + // the next page load. + // See https://bugs.webkit.org/show_bug.cgi?id=226547 + this.queue.enterRestrictedMode(/* purgeExistingTasks= */ true); + } + this.queue.enqueueAndForget(() => { + // Attempt graceful shutdown (including releasing our primary lease), + // but there's no guarantee it will complete. + return this.shutdown(); + }); + }; + this.window.addEventListener('pagehide', this.windowUnloadHandler); + } + } + detachWindowUnloadHook() { + if (this.windowUnloadHandler) { + this.window.removeEventListener('pagehide', this.windowUnloadHandler); + this.windowUnloadHandler = null; + } + } + /** + * Returns whether a client is "zombied" based on its LocalStorage entry. + * Clients become zombied when their tab closes without running all of the + * cleanup logic in `shutdown()`. + */ + isClientZombied(clientId) { + try { + const isZombied = this.webStorage?.getItem(this.zombiedClientLocalStorageKey(clientId)) !== null; + logDebug(LOG_TAG$c, `Client '${clientId}' ${isZombied ? 'is' : 'is not'} zombied in LocalStorage`); + return isZombied; + } + catch (e) { + // Gracefully handle if LocalStorage isn't working. + logError(LOG_TAG$c, 'Failed to get zombied client id.', e); + return false; + } + } + /** + * Record client as zombied (a client that had its tab closed). Zombied + * clients are ignored during primary tab selection. + */ + markClientZombied() { + if (!this.webStorage) { + return; + } + try { + this.webStorage.setItem(this.zombiedClientLocalStorageKey(this.clientId), String(Date.now())); + } + catch (e) { + // Gracefully handle if LocalStorage isn't available / working. + logError('Failed to set zombie client id.', e); + } + } + /** Removes the zombied client entry if it exists. */ + removeClientZombiedEntry() { + if (!this.webStorage) { + return; + } + try { + this.webStorage.removeItem(this.zombiedClientLocalStorageKey(this.clientId)); + } + catch (e) { + // Ignore + } + } + zombiedClientLocalStorageKey(clientId) { + return `${ZOMBIED_CLIENTS_KEY_PREFIX}_${this.persistenceKey}_${clientId}`; + } +} +/** + * Helper to get a typed SimpleDbStore for the primary client object store. + */ +function primaryClientStore(txn) { + return getStore(txn, DbPrimaryClientStore); +} +/** + * Helper to get a typed SimpleDbStore for the client metadata object store. + */ +function clientMetadataStore(txn) { + return getStore(txn, DbClientMetadataStore); +} +/** + * Generates a string used as a prefix when storing data in IndexedDB and + * LocalStorage. + */ +function indexedDbStoragePrefix(databaseId, persistenceKey) { + // Use two different prefix formats: + // + // * firestore / persistenceKey / projectID . databaseID / ... + // * firestore / persistenceKey / projectID / ... + // + // projectIDs are DNS-compatible names and cannot contain dots + // so there's no danger of collisions. + let database = databaseId.projectId; + if (!databaseId.isDefaultDatabase) { + database += '.' + databaseId.database; + } + return 'firestore/' + persistenceKey + '/' + database + '/'; +} +async function indexedDbClearPersistence(persistenceKey) { + if (!SimpleDb.isAvailable()) { + return Promise.resolve(); + } + const dbName = persistenceKey + MAIN_DATABASE; + await SimpleDb.delete(dbName); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Compares two array for equality using comparator. The method computes the + * intersection and invokes `onAdd` for every element that is in `after` but not + * `before`. `onRemove` is invoked for every element in `before` but missing + * from `after`. + * + * The method creates a copy of both `before` and `after` and runs in O(n log + * n), where n is the size of the two lists. + * + * @param before - The elements that exist in the original array. + * @param after - The elements to diff against the original array. + * @param comparator - The comparator for the elements in before and after. + * @param onAdd - A function to invoke for every element that is part of ` + * after` but not `before`. + * @param onRemove - A function to invoke for every element that is part of + * `before` but not `after`. + */ +function diffArrays(before, after, comparator, onAdd, onRemove) { + before = [...before]; + after = [...after]; + before.sort(comparator); + after.sort(comparator); + const bLen = before.length; + const aLen = after.length; + let a = 0; + let b = 0; + while (a < aLen && b < bLen) { + const cmp = comparator(before[b], after[a]); + if (cmp < 0) { + // The element was removed if the next element in our ordered + // walkthrough is only in `before`. + onRemove(before[b++]); + } + else if (cmp > 0) { + // The element was added if the next element in our ordered walkthrough + // is only in `after`. + onAdd(after[a++]); + } + else { + a++; + b++; + } + } + while (a < aLen) { + onAdd(after[a++]); + } + while (b < bLen) { + onRemove(before[b++]); + } +} +/** + * Verifies equality for an array of primitives. + * + * @private + * @internal + * @param left Array of primitives. + * @param right Array of primitives. + * @return True if arrays are equal. + */ +function isPrimitiveArrayEqual(left, right) { + if (left.length !== right.length) { + return false; + } + for (let i = 0; i < left.length; ++i) { + if (left[i] !== right[i]) { + return false; + } + } + return true; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$b = 'LocalStore'; +/** + * The maximum time to leave a resume token buffered without writing it out. + * This value is arbitrary: it's long enough to avoid several writes + * (possibly indefinitely if updates come more frequently than this) but + * short enough that restarting after crashing will still have a pretty + * recent resume token. + */ +const RESUME_TOKEN_MAX_AGE_MICROS = 5 * 60 * 1e6; +/** + * Implements `LocalStore` interface. + * + * Note: some field defined in this class might have public access level, but + * the class is not exported so they are only accessible from this module. + * This is useful to implement optional features (like bundles) in free + * functions, such that they are tree-shakeable. + */ +class LocalStoreImpl { + constructor( + /** Manages our in-memory or durable persistence. */ + persistence, queryEngine, initialUser, serializer) { + this.persistence = persistence; + this.queryEngine = queryEngine; + this.serializer = serializer; + /** + * Maps a targetID to data about its target. + * + * PORTING NOTE: We are using an immutable data structure on Web to make re-runs + * of `applyRemoteEvent()` idempotent. + */ + this.targetDataByTarget = new SortedMap(primitiveComparator); + /** Maps a target to its targetID. */ + // TODO(wuandy): Evaluate if TargetId can be part of Target. + this.targetIdByTarget = new ObjectMap(t => canonifyTarget(t), targetEquals); + /** + * A per collection group index of the last read time processed by + * `getNewDocumentChanges()`. + * + * PORTING NOTE: This is only used for multi-tab synchronization. + */ + this.collectionGroupReadTime = new Map(); + this.remoteDocuments = persistence.getRemoteDocumentCache(); + this.targetCache = persistence.getTargetCache(); + this.bundleCache = persistence.getBundleCache(); + this.initializeUserComponents(initialUser); + } + initializeUserComponents(user) { + // TODO(indexing): Add spec tests that test these components change after a + // user change + this.documentOverlayCache = this.persistence.getDocumentOverlayCache(user); + this.indexManager = this.persistence.getIndexManager(user); + this.mutationQueue = this.persistence.getMutationQueue(user, this.indexManager); + this.localDocuments = new LocalDocumentsView(this.remoteDocuments, this.mutationQueue, this.documentOverlayCache, this.indexManager); + this.remoteDocuments.setIndexManager(this.indexManager); + this.queryEngine.initialize(this.localDocuments, this.indexManager); + } + collectGarbage(garbageCollector) { + return this.persistence.runTransaction('Collect garbage', 'readwrite-primary', txn => garbageCollector.collect(txn, this.targetDataByTarget)); + } +} +function newLocalStore( +/** Manages our in-memory or durable persistence. */ +persistence, queryEngine, initialUser, serializer) { + return new LocalStoreImpl(persistence, queryEngine, initialUser, serializer); +} +/** + * Tells the LocalStore that the currently authenticated user has changed. + * + * In response the local store switches the mutation queue to the new user and + * returns any resulting document changes. + */ +// PORTING NOTE: Android and iOS only return the documents affected by the +// change. +async function localStoreHandleUserChange(localStore, user) { + const localStoreImpl = debugCast(localStore); + const result = await localStoreImpl.persistence.runTransaction('Handle user change', 'readonly', txn => { + // Swap out the mutation queue, grabbing the pending mutation batches + // before and after. + let oldBatches; + return localStoreImpl.mutationQueue + .getAllMutationBatches(txn) + .next(promisedOldBatches => { + oldBatches = promisedOldBatches; + localStoreImpl.initializeUserComponents(user); + return localStoreImpl.mutationQueue.getAllMutationBatches(txn); + }) + .next(newBatches => { + const removedBatchIds = []; + const addedBatchIds = []; + // Union the old/new changed keys. + let changedKeys = documentKeySet(); + for (const batch of oldBatches) { + removedBatchIds.push(batch.batchId); + for (const mutation of batch.mutations) { + changedKeys = changedKeys.add(mutation.key); + } + } + for (const batch of newBatches) { + addedBatchIds.push(batch.batchId); + for (const mutation of batch.mutations) { + changedKeys = changedKeys.add(mutation.key); + } + } + // Return the set of all (potentially) changed documents and the list + // of mutation batch IDs that were affected by change. + return localStoreImpl.localDocuments + .getDocuments(txn, changedKeys) + .next(affectedDocuments => { + return { + affectedDocuments, + removedBatchIds, + addedBatchIds + }; + }); + }); + }); + return result; +} +/* Accepts locally generated Mutations and commit them to storage. */ +function localStoreWriteLocally(localStore, mutations) { + const localStoreImpl = debugCast(localStore); + const localWriteTime = Timestamp.now(); + const keys = mutations.reduce((keys, m) => keys.add(m.key), documentKeySet()); + let overlayedDocuments; + let mutationBatch; + return localStoreImpl.persistence + .runTransaction('Locally write mutations', 'readwrite', txn => { + // Figure out which keys do not have a remote version in the cache, this + // is needed to create the right overlay mutation: if no remote version + // presents, we do not need to create overlays as patch mutations. + // TODO(Overlay): Is there a better way to determine this? Using the + // document version does not work because local mutations set them back + // to 0. + let remoteDocs = mutableDocumentMap(); + let docsWithoutRemoteVersion = documentKeySet(); + return localStoreImpl.remoteDocuments + .getEntries(txn, keys) + .next(docs => { + remoteDocs = docs; + remoteDocs.forEach((key, doc) => { + if (!doc.isValidDocument()) { + docsWithoutRemoteVersion = docsWithoutRemoteVersion.add(key); + } + }); + }) + .next(() => { + // Load and apply all existing mutations. This lets us compute the + // current base state for all non-idempotent transforms before applying + // any additional user-provided writes. + return localStoreImpl.localDocuments.getOverlayedDocuments(txn, remoteDocs); + }) + .next((docs) => { + overlayedDocuments = docs; + // For non-idempotent mutations (such as `FieldValue.increment()`), + // we record the base state in a separate patch mutation. This is + // later used to guarantee consistent values and prevents flicker + // even if the backend sends us an update that already includes our + // transform. + const baseMutations = []; + for (const mutation of mutations) { + const baseValue = mutationExtractBaseValue(mutation, overlayedDocuments.get(mutation.key).overlayedDocument); + if (baseValue != null) { + // NOTE: The base state should only be applied if there's some + // existing document to override, so use a Precondition of + // exists=true + baseMutations.push(new PatchMutation(mutation.key, baseValue, extractFieldMask(baseValue.value.mapValue), Precondition.exists(true))); + } + } + return localStoreImpl.mutationQueue.addMutationBatch(txn, localWriteTime, baseMutations, mutations); + }) + .next(batch => { + mutationBatch = batch; + const overlays = batch.applyToLocalDocumentSet(overlayedDocuments, docsWithoutRemoteVersion); + return localStoreImpl.documentOverlayCache.saveOverlays(txn, batch.batchId, overlays); + }); + }) + .then(() => ({ + batchId: mutationBatch.batchId, + changes: convertOverlayedDocumentMapToDocumentMap(overlayedDocuments) + })); +} +/** + * Acknowledges the given batch. + * + * On the happy path when a batch is acknowledged, the local store will + * + * + remove the batch from the mutation queue; + * + apply the changes to the remote document cache; + * + recalculate the latency compensated view implied by those changes (there + * may be mutations in the queue that affect the documents but haven't been + * acknowledged yet); and + * + give the changed documents back the sync engine + * + * @returns The resulting (modified) documents. + */ +function localStoreAcknowledgeBatch(localStore, batchResult) { + const localStoreImpl = debugCast(localStore); + return localStoreImpl.persistence.runTransaction('Acknowledge batch', 'readwrite-primary', txn => { + const affected = batchResult.batch.keys(); + const documentBuffer = localStoreImpl.remoteDocuments.newChangeBuffer({ + trackRemovals: true // Make sure document removals show up in `getNewDocumentChanges()` + }); + return applyWriteToRemoteDocuments(localStoreImpl, txn, batchResult, documentBuffer) + .next(() => documentBuffer.apply(txn)) + .next(() => localStoreImpl.mutationQueue.performConsistencyCheck(txn)) + .next(() => localStoreImpl.documentOverlayCache.removeOverlaysForBatchId(txn, affected, batchResult.batch.batchId)) + .next(() => localStoreImpl.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(txn, getKeysWithTransformResults(batchResult))) + .next(() => localStoreImpl.localDocuments.getDocuments(txn, affected)); + }); +} +function getKeysWithTransformResults(batchResult) { + let result = documentKeySet(); + for (let i = 0; i < batchResult.mutationResults.length; ++i) { + const mutationResult = batchResult.mutationResults[i]; + if (mutationResult.transformResults.length > 0) { + result = result.add(batchResult.batch.mutations[i].key); + } + } + return result; +} +/** + * Removes mutations from the MutationQueue for the specified batch; + * LocalDocuments will be recalculated. + * + * @returns The resulting modified documents. + */ +function localStoreRejectBatch(localStore, batchId) { + const localStoreImpl = debugCast(localStore); + return localStoreImpl.persistence.runTransaction('Reject batch', 'readwrite-primary', txn => { + let affectedKeys; + return localStoreImpl.mutationQueue + .lookupMutationBatch(txn, batchId) + .next((batch) => { + hardAssert(batch !== null, 0x90f9); + affectedKeys = batch.keys(); + return localStoreImpl.mutationQueue.removeMutationBatch(txn, batch); + }) + .next(() => localStoreImpl.mutationQueue.performConsistencyCheck(txn)) + .next(() => localStoreImpl.documentOverlayCache.removeOverlaysForBatchId(txn, affectedKeys, batchId)) + .next(() => localStoreImpl.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(txn, affectedKeys)) + .next(() => localStoreImpl.localDocuments.getDocuments(txn, affectedKeys)); + }); +} +/** + * Returns the largest (latest) batch id in mutation queue that is pending + * server response. + * + * Returns `BATCHID_UNKNOWN` if the queue is empty. + */ +function localStoreGetHighestUnacknowledgedBatchId(localStore) { + const localStoreImpl = debugCast(localStore); + return localStoreImpl.persistence.runTransaction('Get highest unacknowledged batch id', 'readonly', txn => localStoreImpl.mutationQueue.getHighestUnacknowledgedBatchId(txn)); +} +/** + * Returns the last consistent snapshot processed (used by the RemoteStore to + * determine whether to buffer incoming snapshots from the backend). + */ +function localStoreGetLastRemoteSnapshotVersion(localStore) { + const localStoreImpl = debugCast(localStore); + return localStoreImpl.persistence.runTransaction('Get last remote snapshot version', 'readonly', txn => localStoreImpl.targetCache.getLastRemoteSnapshotVersion(txn)); +} +/** + * Updates the "ground-state" (remote) documents. We assume that the remote + * event reflects any write batches that have been acknowledged or rejected + * (i.e. we do not re-apply local mutations to updates from this event). + * + * LocalDocuments are re-calculated if there are remaining mutations in the + * queue. + */ +function localStoreApplyRemoteEventToLocalCache(localStore, remoteEvent) { + const localStoreImpl = debugCast(localStore); + const remoteVersion = remoteEvent.snapshotVersion; + let newTargetDataByTargetMap = localStoreImpl.targetDataByTarget; + return localStoreImpl.persistence + .runTransaction('Apply remote event', 'readwrite-primary', txn => { + const documentBuffer = localStoreImpl.remoteDocuments.newChangeBuffer({ + trackRemovals: true // Make sure document removals show up in `getNewDocumentChanges()` + }); + // Reset newTargetDataByTargetMap in case this transaction gets re-run. + newTargetDataByTargetMap = localStoreImpl.targetDataByTarget; + const promises = []; + remoteEvent.targetChanges.forEach((change, targetId) => { + const oldTargetData = newTargetDataByTargetMap.get(targetId); + if (!oldTargetData) { + return; + } + // Only update the remote keys if the target is still active. This + // ensures that we can persist the updated target data along with + // the updated assignment. + promises.push(localStoreImpl.targetCache + .removeMatchingKeys(txn, change.removedDocuments, targetId) + .next(() => { + return localStoreImpl.targetCache.addMatchingKeys(txn, change.addedDocuments, targetId); + })); + let newTargetData = oldTargetData.withSequenceNumber(txn.currentSequenceNumber); + if (remoteEvent.targetMismatches.get(targetId) !== null) { + newTargetData = newTargetData + .withResumeToken(ByteString.EMPTY_BYTE_STRING, SnapshotVersion.min()) + .withLastLimboFreeSnapshotVersion(SnapshotVersion.min()); + } + else if (change.resumeToken.approximateByteSize() > 0) { + newTargetData = newTargetData.withResumeToken(change.resumeToken, remoteVersion); + } + newTargetDataByTargetMap = newTargetDataByTargetMap.insert(targetId, newTargetData); + // Update the target data if there are target changes (or if + // sufficient time has passed since the last update). + if (shouldPersistTargetData(oldTargetData, newTargetData, change)) { + promises.push(localStoreImpl.targetCache.updateTargetData(txn, newTargetData)); + } + }); + let changedDocs = mutableDocumentMap(); + let existenceChangedKeys = documentKeySet(); + remoteEvent.documentUpdates.forEach(key => { + if (remoteEvent.resolvedLimboDocuments.has(key)) { + promises.push(localStoreImpl.persistence.referenceDelegate.updateLimboDocument(txn, key)); + } + }); + // Each loop iteration only affects its "own" doc, so it's safe to get all + // the remote documents in advance in a single call. + promises.push(populateDocumentChangeBuffer(txn, documentBuffer, remoteEvent.documentUpdates).next(result => { + changedDocs = result.changedDocuments; + existenceChangedKeys = result.existenceChangedKeys; + })); + // HACK: The only reason we allow a null snapshot version is so that we + // can synthesize remote events when we get permission denied errors while + // trying to resolve the state of a locally cached document that is in + // limbo. + if (!remoteVersion.isEqual(SnapshotVersion.min())) { + const updateRemoteVersion = localStoreImpl.targetCache + .getLastRemoteSnapshotVersion(txn) + .next(lastRemoteSnapshotVersion => { + return localStoreImpl.targetCache.setTargetsMetadata(txn, txn.currentSequenceNumber, remoteVersion); + }); + promises.push(updateRemoteVersion); + } + return PersistencePromise.waitFor(promises) + .next(() => documentBuffer.apply(txn)) + .next(() => localStoreImpl.localDocuments.getLocalViewOfDocuments(txn, changedDocs, existenceChangedKeys)) + .next(() => changedDocs); + }) + .then(changedDocs => { + localStoreImpl.targetDataByTarget = newTargetDataByTargetMap; + return changedDocs; + }); +} +/** + * Populates document change buffer with documents from backend or a bundle. + * Returns the document changes resulting from applying those documents, and + * also a set of documents whose existence state are changed as a result. + * + * @param txn - Transaction to use to read existing documents from storage. + * @param documentBuffer - Document buffer to collect the resulted changes to be + * applied to storage. + * @param documents - Documents to be applied. + */ +function populateDocumentChangeBuffer(txn, documentBuffer, documents) { + let updatedKeys = documentKeySet(); + let existenceChangedKeys = documentKeySet(); + documents.forEach(k => (updatedKeys = updatedKeys.add(k))); + return documentBuffer.getEntries(txn, updatedKeys).next(existingDocs => { + let changedDocuments = mutableDocumentMap(); + documents.forEach((key, doc) => { + const existingDoc = existingDocs.get(key); + // Check if see if there is a existence state change for this document. + if (doc.isFoundDocument() !== existingDoc.isFoundDocument()) { + existenceChangedKeys = existenceChangedKeys.add(key); + } + // Note: The order of the steps below is important, since we want + // to ensure that rejected limbo resolutions (which fabricate + // NoDocuments with SnapshotVersion.min()) never add documents to + // cache. + if (doc.isNoDocument() && doc.version.isEqual(SnapshotVersion.min())) { + // NoDocuments with SnapshotVersion.min() are used in manufactured + // events. We remove these documents from cache since we lost + // access. + documentBuffer.removeEntry(key, doc.readTime); + changedDocuments = changedDocuments.insert(key, doc); + } + else if (!existingDoc.isValidDocument() || + doc.version.compareTo(existingDoc.version) > 0 || + (doc.version.compareTo(existingDoc.version) === 0 && + existingDoc.hasPendingWrites)) { + documentBuffer.addEntry(doc); + changedDocuments = changedDocuments.insert(key, doc); + } + else { + logDebug(LOG_TAG$b, 'Ignoring outdated watch update for ', key, '. Current version:', existingDoc.version, ' Watch version:', doc.version); + } + }); + return { changedDocuments, existenceChangedKeys }; + }); +} +/** + * Returns true if the newTargetData should be persisted during an update of + * an active target. TargetData should always be persisted when a target is + * being released and should not call this function. + * + * While the target is active, TargetData updates can be omitted when nothing + * about the target has changed except metadata like the resume token or + * snapshot version. Occasionally it's worth the extra write to prevent these + * values from getting too stale after a crash, but this doesn't have to be + * too frequent. + */ +function shouldPersistTargetData(oldTargetData, newTargetData, change) { + // Always persist target data if we don't already have a resume token. + if (oldTargetData.resumeToken.approximateByteSize() === 0) { + return true; + } + // Don't allow resume token changes to be buffered indefinitely. This + // allows us to be reasonably up-to-date after a crash and avoids needing + // to loop over all active queries on shutdown. Especially in the browser + // we may not get time to do anything interesting while the current tab is + // closing. + const timeDelta = newTargetData.snapshotVersion.toMicroseconds() - + oldTargetData.snapshotVersion.toMicroseconds(); + if (timeDelta >= RESUME_TOKEN_MAX_AGE_MICROS) { + return true; + } + // Otherwise if the only thing that has changed about a target is its resume + // token it's not worth persisting. Note that the RemoteStore keeps an + // in-memory view of the currently active targets which includes the current + // resume token, so stream failure or user changes will still use an + // up-to-date resume token regardless of what we do here. + const changes = change.addedDocuments.size + + change.modifiedDocuments.size + + change.removedDocuments.size; + return changes > 0; +} +/** + * Notifies local store of the changed views to locally pin documents. + */ +async function localStoreNotifyLocalViewChanges(localStore, viewChanges) { + const localStoreImpl = debugCast(localStore); + try { + await localStoreImpl.persistence.runTransaction('notifyLocalViewChanges', 'readwrite', txn => { + return PersistencePromise.forEach(viewChanges, (viewChange) => { + return PersistencePromise.forEach(viewChange.addedKeys, (key) => localStoreImpl.persistence.referenceDelegate.addReference(txn, viewChange.targetId, key)).next(() => PersistencePromise.forEach(viewChange.removedKeys, (key) => localStoreImpl.persistence.referenceDelegate.removeReference(txn, viewChange.targetId, key))); + }); + }); + } + catch (e) { + if (isIndexedDbTransactionError(e)) { + // If `notifyLocalViewChanges` fails, we did not advance the sequence + // number for the documents that were included in this transaction. + // This might trigger them to be deleted earlier than they otherwise + // would have, but it should not invalidate the integrity of the data. + logDebug(LOG_TAG$b, 'Failed to update sequence numbers: ' + e); + } + else { + throw e; + } + } + for (const viewChange of viewChanges) { + const targetId = viewChange.targetId; + if (!viewChange.fromCache) { + const targetData = localStoreImpl.targetDataByTarget.get(targetId); + // Advance the last limbo free snapshot version + const lastLimboFreeSnapshotVersion = targetData.snapshotVersion; + const updatedTargetData = targetData.withLastLimboFreeSnapshotVersion(lastLimboFreeSnapshotVersion); + localStoreImpl.targetDataByTarget = + localStoreImpl.targetDataByTarget.insert(targetId, updatedTargetData); + // TODO(b/272564316): Apply the optimization done on other platforms. + // This is a problem for web because saving the updated targetData from + // non-primary client conflicts with what primary client saved. + } + } +} +/** + * Gets the mutation batch after the passed in batchId in the mutation queue + * or null if empty. + * @param afterBatchId - If provided, the batch to search after. + * @returns The next mutation or null if there wasn't one. + */ +function localStoreGetNextMutationBatch(localStore, afterBatchId) { + const localStoreImpl = debugCast(localStore); + return localStoreImpl.persistence.runTransaction('Get next mutation batch', 'readonly', txn => { + if (afterBatchId === undefined) { + afterBatchId = BATCHID_UNKNOWN; + } + return localStoreImpl.mutationQueue.getNextMutationBatchAfterBatchId(txn, afterBatchId); + }); +} +/** + * Reads the current value of a Document with a given key or null if not + * found - used for testing. + */ +function localStoreReadDocument(localStore, key) { + const localStoreImpl = debugCast(localStore); + return localStoreImpl.persistence.runTransaction('read document', 'readonly', txn => localStoreImpl.localDocuments.getDocument(txn, key)); +} +/** + * Assigns the given target an internal ID so that its results can be pinned so + * they don't get GC'd. A target must be allocated in the local store before + * the store can be used to manage its view. + * + * Allocating an already allocated `Target` will return the existing `TargetData` + * for that `Target`. + */ +function localStoreAllocateTarget(localStore, target) { + const localStoreImpl = debugCast(localStore); + return localStoreImpl.persistence + .runTransaction('Allocate target', 'readwrite', txn => { + let targetData; + return localStoreImpl.targetCache + .getTargetData(txn, target) + .next((cached) => { + if (cached) { + // This target has been listened to previously, so reuse the + // previous targetID. + // TODO(mcg): freshen last accessed date? + targetData = cached; + return PersistencePromise.resolve(targetData); + } + else { + return localStoreImpl.targetCache + .allocateTargetId(txn) + .next(targetId => { + targetData = new TargetData(target, targetId, "TargetPurposeListen" /* TargetPurpose.Listen */, txn.currentSequenceNumber); + return localStoreImpl.targetCache + .addTargetData(txn, targetData) + .next(() => targetData); + }); + } + }); + }) + .then(targetData => { + // If Multi-Tab is enabled, the existing target data may be newer than + // the in-memory data + const cachedTargetData = localStoreImpl.targetDataByTarget.get(targetData.targetId); + if (cachedTargetData === null || + targetData.snapshotVersion.compareTo(cachedTargetData.snapshotVersion) > + 0) { + localStoreImpl.targetDataByTarget = + localStoreImpl.targetDataByTarget.insert(targetData.targetId, targetData); + localStoreImpl.targetIdByTarget.set(target, targetData.targetId); + } + return targetData; + }); +} +/** + * Returns the TargetData as seen by the LocalStore, including updates that may + * have not yet been persisted to the TargetCache. + */ +// Visible for testing. +function localStoreGetTargetData(localStore, transaction, target) { + const localStoreImpl = debugCast(localStore); + const targetId = localStoreImpl.targetIdByTarget.get(target); + if (targetId !== undefined) { + return PersistencePromise.resolve(localStoreImpl.targetDataByTarget.get(targetId)); + } + else { + return localStoreImpl.targetCache.getTargetData(transaction, target); + } +} +/** + * Unpins all the documents associated with the given target. If + * `keepPersistedTargetData` is set to false and Eager GC enabled, the method + * directly removes the associated target data from the target cache. + * + * Releasing a non-existing `Target` is a no-op. + */ +// PORTING NOTE: `keepPersistedTargetData` is multi-tab only. +async function localStoreReleaseTarget(localStore, targetId, keepPersistedTargetData) { + const localStoreImpl = debugCast(localStore); + const targetData = localStoreImpl.targetDataByTarget.get(targetId); + const mode = keepPersistedTargetData ? 'readwrite' : 'readwrite-primary'; + try { + if (!keepPersistedTargetData) { + await localStoreImpl.persistence.runTransaction('Release target', mode, txn => { + return localStoreImpl.persistence.referenceDelegate.removeTarget(txn, targetData); + }); + } + } + catch (e) { + if (isIndexedDbTransactionError(e)) { + // All `releaseTarget` does is record the final metadata state for the + // target, but we've been recording this periodically during target + // activity. If we lose this write this could cause a very slight + // difference in the order of target deletion during GC, but we + // don't define exact LRU semantics so this is acceptable. + logDebug(LOG_TAG$b, `Failed to update sequence numbers for target ${targetId}: ${e}`); + } + else { + throw e; + } + } + localStoreImpl.targetDataByTarget = + localStoreImpl.targetDataByTarget.remove(targetId); + localStoreImpl.targetIdByTarget.delete(targetData.target); +} +/** + * Runs the specified query against the local store and returns the results, + * potentially taking advantage of query data from previous executions (such + * as the set of remote keys). + * + * @param usePreviousResults - Whether results from previous executions can + * be used to optimize this query execution. + */ +function localStoreExecuteQuery(localStore, query, usePreviousResults) { + const localStoreImpl = debugCast(localStore); + let lastLimboFreeSnapshotVersion = SnapshotVersion.min(); + let remoteKeys = documentKeySet(); + return localStoreImpl.persistence.runTransaction('Execute query', 'readwrite', // Use readwrite instead of readonly so indexes can be created + // Use readwrite instead of readonly so indexes can be created + txn => { + return localStoreGetTargetData(localStoreImpl, txn, queryToTarget(query)) + .next(targetData => { + if (targetData) { + lastLimboFreeSnapshotVersion = + targetData.lastLimboFreeSnapshotVersion; + return localStoreImpl.targetCache + .getMatchingKeysForTargetId(txn, targetData.targetId) + .next(result => { + remoteKeys = result; + }); + } + }) + .next(() => localStoreImpl.queryEngine.getDocumentsMatchingQuery(txn, query, usePreviousResults + ? lastLimboFreeSnapshotVersion + : SnapshotVersion.min(), usePreviousResults ? remoteKeys : documentKeySet())) + .next(documents => { + setMaxReadTime(localStoreImpl, queryCollectionGroup(query), documents); + return { documents, remoteKeys }; + }); + }); +} +function applyWriteToRemoteDocuments(localStoreImpl, txn, batchResult, documentBuffer) { + const batch = batchResult.batch; + const docKeys = batch.keys(); + let promiseChain = PersistencePromise.resolve(); + docKeys.forEach(docKey => { + promiseChain = promiseChain + .next(() => documentBuffer.getEntry(txn, docKey)) + .next(doc => { + const ackVersion = batchResult.docVersions.get(docKey); + hardAssert(ackVersion !== null, 0xbd9d); + if (doc.version.compareTo(ackVersion) < 0) { + batch.applyToRemoteDocument(doc, batchResult); + if (doc.isValidDocument()) { + // We use the commitVersion as the readTime rather than the + // document's updateTime since the updateTime is not advanced + // for updates that do not modify the underlying document. + doc.setReadTime(batchResult.commitVersion); + documentBuffer.addEntry(doc); + } + } + }); + }); + return promiseChain.next(() => localStoreImpl.mutationQueue.removeMutationBatch(txn, batch)); +} +/** Returns the local view of the documents affected by a mutation batch. */ +// PORTING NOTE: Multi-Tab only. +function localStoreLookupMutationDocuments(localStore, batchId) { + const localStoreImpl = debugCast(localStore); + const mutationQueueImpl = debugCast(localStoreImpl.mutationQueue); + return localStoreImpl.persistence.runTransaction('Lookup mutation documents', 'readonly', txn => { + return mutationQueueImpl.lookupMutationKeys(txn, batchId).next(keys => { + if (keys) { + return localStoreImpl.localDocuments.getDocuments(txn, keys); + } + else { + return PersistencePromise.resolve(null); + } + }); + }); +} +// PORTING NOTE: Multi-Tab only. +function localStoreRemoveCachedMutationBatchMetadata(localStore, batchId) { + const mutationQueueImpl = debugCast(debugCast(localStore, LocalStoreImpl).mutationQueue); + mutationQueueImpl.removeCachedMutationKeys(batchId); +} +// PORTING NOTE: Multi-Tab only. +function localStoreGetActiveClients(localStore) { + const persistenceImpl = debugCast(debugCast(localStore, LocalStoreImpl).persistence); + return persistenceImpl.getActiveClients(); +} +// PORTING NOTE: Multi-Tab only. +function localStoreGetCachedTarget(localStore, targetId) { + const localStoreImpl = debugCast(localStore); + const targetCacheImpl = debugCast(localStoreImpl.targetCache); + const cachedTargetData = localStoreImpl.targetDataByTarget.get(targetId); + if (cachedTargetData) { + return Promise.resolve(cachedTargetData.target); + } + else { + return localStoreImpl.persistence.runTransaction('Get target data', 'readonly', txn => { + return targetCacheImpl + .getTargetDataForTarget(txn, targetId) + .next(targetData => (targetData ? targetData.target : null)); + }); + } +} +/** + * Returns the set of documents that have been updated since the last call. + * If this is the first call, returns the set of changes since client + * initialization. Further invocations will return document that have changed + * since the prior call. + */ +// PORTING NOTE: Multi-Tab only. +function localStoreGetNewDocumentChanges(localStore, collectionGroup) { + const localStoreImpl = debugCast(localStore); + // Get the current maximum read time for the collection. This should always + // exist, but to reduce the chance for regressions we default to + // SnapshotVersion.Min() + // TODO(indexing): Consider removing the default value. + const readTime = localStoreImpl.collectionGroupReadTime.get(collectionGroup) || + SnapshotVersion.min(); + return localStoreImpl.persistence + .runTransaction('Get new document changes', 'readonly', txn => localStoreImpl.remoteDocuments.getAllFromCollectionGroup(txn, collectionGroup, newIndexOffsetSuccessorFromReadTime(readTime, INITIAL_LARGEST_BATCH_ID), + /* limit= */ Number.MAX_SAFE_INTEGER)) + .then(changedDocs => { + setMaxReadTime(localStoreImpl, collectionGroup, changedDocs); + return changedDocs; + }); +} +/** Sets the collection group's maximum read time from the given documents. */ +// PORTING NOTE: Multi-Tab only. +function setMaxReadTime(localStoreImpl, collectionGroup, changedDocs) { + let readTime = localStoreImpl.collectionGroupReadTime.get(collectionGroup) || + SnapshotVersion.min(); + changedDocs.forEach((_, doc) => { + if (doc.readTime.compareTo(readTime) > 0) { + readTime = doc.readTime; + } + }); + localStoreImpl.collectionGroupReadTime.set(collectionGroup, readTime); +} +/** + * Creates a new target using the given bundle name, which will be used to + * hold the keys of all documents from the bundle in query-document mappings. + * This ensures that the loaded documents do not get garbage collected + * right away. + */ +function umbrellaTarget(bundleName) { + // It is OK that the path used for the query is not valid, because this will + // not be read and queried. + return queryToTarget(newQueryForPath(ResourcePath.fromString(`__bundle__/docs/${bundleName}`))); +} +/** + * Applies the documents from a bundle to the "ground-state" (remote) + * documents. + * + * LocalDocuments are re-calculated if there are remaining mutations in the + * queue. + */ +async function localStoreApplyBundledDocuments(localStore, bundleConverter, documents, bundleName) { + const localStoreImpl = debugCast(localStore); + let documentKeys = documentKeySet(); + let documentMap = mutableDocumentMap(); + for (const bundleDoc of documents) { + const documentKey = bundleConverter.toDocumentKey(bundleDoc.metadata.name); + if (bundleDoc.document) { + documentKeys = documentKeys.add(documentKey); + } + const doc = bundleConverter.toMutableDocument(bundleDoc); + doc.setReadTime(bundleConverter.toSnapshotVersion(bundleDoc.metadata.readTime)); + documentMap = documentMap.insert(documentKey, doc); + } + const documentBuffer = localStoreImpl.remoteDocuments.newChangeBuffer({ + trackRemovals: true // Make sure document removals show up in `getNewDocumentChanges()` + }); + // Allocates a target to hold all document keys from the bundle, such that + // they will not get garbage collected right away. + const umbrellaTargetData = await localStoreAllocateTarget(localStoreImpl, umbrellaTarget(bundleName)); + return localStoreImpl.persistence.runTransaction('Apply bundle documents', 'readwrite', txn => { + return populateDocumentChangeBuffer(txn, documentBuffer, documentMap) + .next(documentChangeResult => { + documentBuffer.apply(txn); + return documentChangeResult; + }) + .next(documentChangeResult => { + return localStoreImpl.targetCache + .removeMatchingKeysForTargetId(txn, umbrellaTargetData.targetId) + .next(() => localStoreImpl.targetCache.addMatchingKeys(txn, documentKeys, umbrellaTargetData.targetId)) + .next(() => localStoreImpl.localDocuments.getLocalViewOfDocuments(txn, documentChangeResult.changedDocuments, documentChangeResult.existenceChangedKeys)) + .next(() => documentChangeResult.changedDocuments); + }); + }); +} +/** + * Returns a promise of a boolean to indicate if the given bundle has already + * been loaded and the create time is newer than the current loading bundle. + */ +function localStoreHasNewerBundle(localStore, bundleMetadata) { + const localStoreImpl = debugCast(localStore); + const currentReadTime = fromVersion(bundleMetadata.createTime); + return localStoreImpl.persistence + .runTransaction('hasNewerBundle', 'readonly', transaction => { + return localStoreImpl.bundleCache.getBundleMetadata(transaction, bundleMetadata.id); + }) + .then(cached => { + return !!cached && cached.createTime.compareTo(currentReadTime) >= 0; + }); +} +/** + * Saves the given `BundleMetadata` to local persistence. + */ +function localStoreSaveBundle(localStore, bundleMetadata) { + const localStoreImpl = debugCast(localStore); + return localStoreImpl.persistence.runTransaction('Save bundle', 'readwrite', transaction => { + return localStoreImpl.bundleCache.saveBundleMetadata(transaction, bundleMetadata); + }); +} +/** + * Returns a promise of a `NamedQuery` associated with given query name. Promise + * resolves to undefined if no persisted data can be found. + */ +function localStoreGetNamedQuery(localStore, queryName) { + const localStoreImpl = debugCast(localStore); + return localStoreImpl.persistence.runTransaction('Get named query', 'readonly', transaction => localStoreImpl.bundleCache.getNamedQuery(transaction, queryName)); +} +/** + * Saves the given `NamedQuery` to local persistence. + */ +async function localStoreSaveNamedQuery(localStore, query, documents = documentKeySet()) { + // Allocate a target for the named query such that it can be resumed + // from associated read time if users use it to listen. + // NOTE: this also means if no corresponding target exists, the new target + // will remain active and will not get collected, unless users happen to + // unlisten the query somehow. + const allocated = await localStoreAllocateTarget(localStore, queryToTarget(fromBundledQuery(query.bundledQuery))); + const localStoreImpl = debugCast(localStore); + return localStoreImpl.persistence.runTransaction('Save named query', 'readwrite', transaction => { + const readTime = fromVersion(query.readTime); + // Simply save the query itself if it is older than what the SDK already + // has. + if (allocated.snapshotVersion.compareTo(readTime) >= 0) { + return localStoreImpl.bundleCache.saveNamedQuery(transaction, query); + } + // Update existing target data because the query from the bundle is newer. + const newTargetData = allocated.withResumeToken(ByteString.EMPTY_BYTE_STRING, readTime); + localStoreImpl.targetDataByTarget = + localStoreImpl.targetDataByTarget.insert(newTargetData.targetId, newTargetData); + return localStoreImpl.targetCache + .updateTargetData(transaction, newTargetData) + .next(() => localStoreImpl.targetCache.removeMatchingKeysForTargetId(transaction, allocated.targetId)) + .next(() => localStoreImpl.targetCache.addMatchingKeys(transaction, documents, allocated.targetId)) + .next(() => localStoreImpl.bundleCache.saveNamedQuery(transaction, query)); + }); +} +async function localStoreConfigureFieldIndexes(localStore, newFieldIndexes) { + const localStoreImpl = debugCast(localStore); + const indexManager = localStoreImpl.indexManager; + const promises = []; + return localStoreImpl.persistence.runTransaction('Configure indexes', 'readwrite', transaction => indexManager + .getFieldIndexes(transaction) + .next(oldFieldIndexes => diffArrays(oldFieldIndexes, newFieldIndexes, fieldIndexSemanticComparator, fieldIndex => { + promises.push(indexManager.addFieldIndex(transaction, fieldIndex)); + }, fieldIndex => { + promises.push(indexManager.deleteFieldIndex(transaction, fieldIndex)); + })) + .next(() => PersistencePromise.waitFor(promises))); +} +function localStoreSetIndexAutoCreationEnabled(localStore, isEnabled) { + const localStoreImpl = debugCast(localStore); + localStoreImpl.queryEngine.indexAutoCreationEnabled = isEnabled; +} +function localStoreDeleteAllFieldIndexes(localStore) { + const localStoreImpl = debugCast(localStore); + const indexManager = localStoreImpl.indexManager; + return localStoreImpl.persistence.runTransaction('Delete All Indexes', 'readwrite', transaction => indexManager.deleteAllFieldIndexes(transaction)); +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A tracker to keep a record of important details during database local query + * execution. + */ +class QueryContext { + constructor() { + /** + * Counts the number of documents passed through during local query execution. + */ + this._documentReadCount = 0; + } + get documentReadCount() { + return this._documentReadCount; + } + incrementDocumentReadCount(amount) { + this._documentReadCount += amount; + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const DEFAULT_INDEX_AUTO_CREATION_MIN_COLLECTION_SIZE = 100; +/** + * This cost represents the evaluation result of + * (([index, docKey] + [docKey, docContent]) per document in the result set) + * / ([docKey, docContent] per documents in full collection scan) coming from + * experiment [enter PR experiment URL here]. + */ +function getDefaultRelativeIndexReadCostPerDocument() { + // These values were derived from an experiment where several members of the + // Firestore SDK team ran a performance test in various environments. + // Googlers can see b/299284287 for details. + if (util.isSafari()) { + return 8; + } + else if (getAndroidVersion(util.getUA()) > 0) { + return 6; + } + else { + return 4; + } +} +/** + * The Firestore query engine. + * + * Firestore queries can be executed in three modes. The Query Engine determines + * what mode to use based on what data is persisted. The mode only determines + * the runtime complexity of the query - the result set is equivalent across all + * implementations. + * + * The Query engine will use indexed-based execution if a user has configured + * any index that can be used to execute query (via `setIndexConfiguration()`). + * Otherwise, the engine will try to optimize the query by re-using a previously + * persisted query result. If that is not possible, the query will be executed + * via a full collection scan. + * + * Index-based execution is the default when available. The query engine + * supports partial indexed execution and merges the result from the index + * lookup with documents that have not yet been indexed. The index evaluation + * matches the backend's format and as such, the SDK can use indexing for all + * queries that the backend supports. + * + * If no index exists, the query engine tries to take advantage of the target + * document mapping in the TargetCache. These mappings exists for all queries + * that have been synced with the backend at least once and allow the query + * engine to only read documents that previously matched a query plus any + * documents that were edited after the query was last listened to. + * + * There are some cases when this optimization is not guaranteed to produce + * the same results as full collection scans. In these cases, query + * processing falls back to full scans. These cases are: + * + * - Limit queries where a document that matched the query previously no longer + * matches the query. + * + * - Limit queries where a document edit may cause the document to sort below + * another document that is in the local cache. + * + * - Queries that have never been CURRENT or free of limbo documents. + */ +class QueryEngine { + constructor() { + this.initialized = false; + this.indexAutoCreationEnabled = false; + /** + * SDK only decides whether it should create index when collection size is + * larger than this. + */ + this.indexAutoCreationMinCollectionSize = DEFAULT_INDEX_AUTO_CREATION_MIN_COLLECTION_SIZE; + this.relativeIndexReadCostPerDocument = getDefaultRelativeIndexReadCostPerDocument(); + } + /** Sets the document view to query against. */ + initialize(localDocuments, indexManager) { + this.localDocumentsView = localDocuments; + this.indexManager = indexManager; + this.initialized = true; + } + /** Returns all local documents matching the specified query. */ + getDocumentsMatchingQuery(transaction, query, lastLimboFreeSnapshotVersion, remoteKeys) { + // Stores the result from executing the query; using this object is more + // convenient than passing the result between steps of the persistence + // transaction and improves readability comparatively. + const queryResult = { result: null }; + return this.performQueryUsingIndex(transaction, query) + .next(result => { + queryResult.result = result; + }) + .next(() => { + if (queryResult.result) { + return; + } + return this.performQueryUsingRemoteKeys(transaction, query, remoteKeys, lastLimboFreeSnapshotVersion).next(result => { + queryResult.result = result; + }); + }) + .next(() => { + if (queryResult.result) { + return; + } + const context = new QueryContext(); + return this.executeFullCollectionScan(transaction, query, context).next(result => { + queryResult.result = result; + if (this.indexAutoCreationEnabled) { + return this.createCacheIndexes(transaction, query, context, result.size); + } + }); + }) + .next(() => queryResult.result); + } + createCacheIndexes(transaction, query, context, resultSize) { + if (context.documentReadCount < this.indexAutoCreationMinCollectionSize) { + if (getLogLevel() <= logger.LogLevel.DEBUG) { + logDebug('QueryEngine', 'SDK will not create cache indexes for query:', stringifyQuery(query), 'since it only creates cache indexes for collection contains', 'more than or equal to', this.indexAutoCreationMinCollectionSize, 'documents'); + } + return PersistencePromise.resolve(); + } + if (getLogLevel() <= logger.LogLevel.DEBUG) { + logDebug('QueryEngine', 'Query:', stringifyQuery(query), 'scans', context.documentReadCount, 'local documents and returns', resultSize, 'documents as results.'); + } + if (context.documentReadCount > + this.relativeIndexReadCostPerDocument * resultSize) { + if (getLogLevel() <= logger.LogLevel.DEBUG) { + logDebug('QueryEngine', 'The SDK decides to create cache indexes for query:', stringifyQuery(query), 'as using cache indexes may help improve performance.'); + } + return this.indexManager.createTargetIndexes(transaction, queryToTarget(query)); + } + return PersistencePromise.resolve(); + } + /** + * Performs an indexed query that evaluates the query based on a collection's + * persisted index values. Returns `null` if an index is not available. + */ + performQueryUsingIndex(transaction, query) { + if (queryMatchesAllDocuments(query)) { + // Queries that match all documents don't benefit from using + // key-based lookups. It is more efficient to scan all documents in a + // collection, rather than to perform individual lookups. + return PersistencePromise.resolve(null); + } + let target = queryToTarget(query); + return this.indexManager + .getIndexType(transaction, target) + .next(indexType => { + if (indexType === 0 /* IndexType.NONE */) { + // The target cannot be served from any index. + return null; + } + if (query.limit !== null && indexType === 1 /* IndexType.PARTIAL */) { + // We cannot apply a limit for targets that are served using a partial + // index. If a partial index will be used to serve the target, the + // query may return a superset of documents that match the target + // (e.g. if the index doesn't include all the target's filters), or + // may return the correct set of documents in the wrong order (e.g. if + // the index doesn't include a segment for one of the orderBys). + // Therefore, a limit should not be applied in such cases. + query = queryWithLimit(query, null, "F" /* LimitType.First */); + target = queryToTarget(query); + } + return this.indexManager + .getDocumentsMatchingTarget(transaction, target) + .next(keys => { + const sortedKeys = documentKeySet(...keys); + return this.localDocumentsView + .getDocuments(transaction, sortedKeys) + .next(indexedDocuments => { + return this.indexManager + .getMinOffset(transaction, target) + .next(offset => { + const previousResults = this.applyQuery(query, indexedDocuments); + if (this.needsRefill(query, previousResults, sortedKeys, offset.readTime)) { + // A limit query whose boundaries change due to local + // edits can be re-run against the cache by excluding the + // limit. This ensures that all documents that match the + // query's filters are included in the result set. The SDK + // can then apply the limit once all local edits are + // incorporated. + return this.performQueryUsingIndex(transaction, queryWithLimit(query, null, "F" /* LimitType.First */)); + } + return this.appendRemainingResults(transaction, previousResults, query, offset); + }); + }); + }); + }); + } + /** + * Performs a query based on the target's persisted query mapping. Returns + * `null` if the mapping is not available or cannot be used. + */ + performQueryUsingRemoteKeys(transaction, query, remoteKeys, lastLimboFreeSnapshotVersion) { + if (queryMatchesAllDocuments(query)) { + // Queries that match all documents don't benefit from using + // key-based lookups. It is more efficient to scan all documents in a + // collection, rather than to perform individual lookups. + return PersistencePromise.resolve(null); + } + // Queries that have never seen a snapshot without limbo free documents + // should also be run as a full collection scan. + if (lastLimboFreeSnapshotVersion.isEqual(SnapshotVersion.min())) { + return PersistencePromise.resolve(null); + } + return this.localDocumentsView.getDocuments(transaction, remoteKeys).next(documents => { + const previousResults = this.applyQuery(query, documents); + if (this.needsRefill(query, previousResults, remoteKeys, lastLimboFreeSnapshotVersion)) { + return PersistencePromise.resolve(null); + } + if (getLogLevel() <= logger.LogLevel.DEBUG) { + logDebug('QueryEngine', 'Re-using previous result from %s to execute query: %s', lastLimboFreeSnapshotVersion.toString(), stringifyQuery(query)); + } + // Retrieve all results for documents that were updated since the last + // limbo-document free remote snapshot. + return this.appendRemainingResults(transaction, previousResults, query, newIndexOffsetSuccessorFromReadTime(lastLimboFreeSnapshotVersion, INITIAL_LARGEST_BATCH_ID)).next(results => results); + }); + } + /** Applies the query filter and sorting to the provided documents. */ + applyQuery(query, documents) { + // Sort the documents and re-apply the query filter since previously + // matching documents do not necessarily still match the query. + let queryResults = new SortedSet(newQueryComparator(query)); + documents.forEach((_, maybeDoc) => { + if (queryMatches(query, maybeDoc)) { + queryResults = queryResults.add(maybeDoc); + } + }); + return queryResults; + } + /** + * Determines if a limit query needs to be refilled from cache, making it + * ineligible for index-free execution. + * + * @param query - The query. + * @param sortedPreviousResults - The documents that matched the query when it + * was last synchronized, sorted by the query's comparator. + * @param remoteKeys - The document keys that matched the query at the last + * snapshot. + * @param limboFreeSnapshotVersion - The version of the snapshot when the + * query was last synchronized. + */ + needsRefill(query, sortedPreviousResults, remoteKeys, limboFreeSnapshotVersion) { + if (query.limit === null) { + // Queries without limits do not need to be refilled. + return false; + } + if (remoteKeys.size !== sortedPreviousResults.size) { + // The query needs to be refilled if a previously matching document no + // longer matches. + return true; + } + // Limit queries are not eligible for index-free query execution if there is + // a potential that an older document from cache now sorts before a document + // that was previously part of the limit. This, however, can only happen if + // the document at the edge of the limit goes out of limit. + // If a document that is not the limit boundary sorts differently, + // the boundary of the limit itself did not change and documents from cache + // will continue to be "rejected" by this boundary. Therefore, we can ignore + // any modifications that don't affect the last document. + const docAtLimitEdge = query.limitType === "F" /* LimitType.First */ + ? sortedPreviousResults.last() + : sortedPreviousResults.first(); + if (!docAtLimitEdge) { + // We don't need to refill the query if there were already no documents. + return false; + } + return (docAtLimitEdge.hasPendingWrites || + docAtLimitEdge.version.compareTo(limboFreeSnapshotVersion) > 0); + } + executeFullCollectionScan(transaction, query, context) { + if (getLogLevel() <= logger.LogLevel.DEBUG) { + logDebug('QueryEngine', 'Using full collection scan to execute query:', stringifyQuery(query)); + } + return this.localDocumentsView.getDocumentsMatchingQuery(transaction, query, IndexOffset.min(), context); + } + /** + * Combines the results from an indexed execution with the remaining documents + * that have not yet been indexed. + */ + appendRemainingResults(transaction, indexedResults, query, offset) { + // Retrieve all results for documents that were updated since the offset. + return this.localDocumentsView + .getDocumentsMatchingQuery(transaction, query, offset) + .next(remainingResults => { + // Merge with existing results + indexedResults.forEach(d => { + remainingResults = remainingResults.insert(d.key, d); + }); + return remainingResults; + }); + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// The format of the LocalStorage key that stores the client state is: +// firestore_clients__ +const CLIENT_STATE_KEY_PREFIX = 'firestore_clients'; +/** Assembles the key for a client state in WebStorage */ +function createWebStorageClientStateKey(persistenceKey, clientId) { + return `${CLIENT_STATE_KEY_PREFIX}_${persistenceKey}_${clientId}`; +} +// The format of the WebStorage key that stores the mutation state is: +// firestore_mutations__ +// (for unauthenticated users) +// or: firestore_mutations___ +// +// 'user_uid' is last to avoid needing to escape '_' characters that it might +// contain. +const MUTATION_BATCH_KEY_PREFIX = 'firestore_mutations'; +/** Assembles the key for a mutation batch in WebStorage */ +function createWebStorageMutationBatchKey(persistenceKey, user, batchId) { + let mutationKey = `${MUTATION_BATCH_KEY_PREFIX}_${persistenceKey}_${batchId}`; + if (user.isAuthenticated()) { + mutationKey += `_${user.uid}`; + } + return mutationKey; +} +// The format of the WebStorage key that stores a query target's metadata is: +// firestore_targets__ +const QUERY_TARGET_KEY_PREFIX = 'firestore_targets'; +/** Assembles the key for a query state in WebStorage */ +function createWebStorageQueryTargetMetadataKey(persistenceKey, targetId) { + return `${QUERY_TARGET_KEY_PREFIX}_${persistenceKey}_${targetId}`; +} +// The WebStorage prefix that stores the primary tab's online state. The +// format of the key is: +// firestore_online_state_ +const ONLINE_STATE_KEY_PREFIX = 'firestore_online_state'; +/** Assembles the key for the online state of the primary tab. */ +function createWebStorageOnlineStateKey(persistenceKey) { + return `${ONLINE_STATE_KEY_PREFIX}_${persistenceKey}`; +} +// The WebStorage prefix that plays as a event to indicate the remote documents +// might have changed due to some secondary tabs loading a bundle. +// format of the key is: +// firestore_bundle_loaded_v2_ +// The version ending with "v2" stores the list of modified collection groups. +const BUNDLE_LOADED_KEY_PREFIX = 'firestore_bundle_loaded_v2'; +function createBundleLoadedKey(persistenceKey) { + return `${BUNDLE_LOADED_KEY_PREFIX}_${persistenceKey}`; +} +// The WebStorage key prefix for the key that stores the last sequence number allocated. The key +// looks like 'firestore_sequence_number_'. +const SEQUENCE_NUMBER_KEY_PREFIX = 'firestore_sequence_number'; +/** Assembles the key for the current sequence number. */ +function createWebStorageSequenceNumberKey(persistenceKey) { + return `${SEQUENCE_NUMBER_KEY_PREFIX}_${persistenceKey}`; +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$a = 'SharedClientState'; +/** + * Holds the state of a mutation batch, including its user ID, batch ID and + * whether the batch is 'pending', 'acknowledged' or 'rejected'. + */ +// Visible for testing +class MutationMetadata { + constructor(user, batchId, state, error) { + this.user = user; + this.batchId = batchId; + this.state = state; + this.error = error; + } + /** + * Parses a MutationMetadata from its JSON representation in WebStorage. + * Logs a warning and returns null if the format of the data is not valid. + */ + static fromWebStorageEntry(user, batchId, value) { + const mutationBatch = JSON.parse(value); + let validData = typeof mutationBatch === 'object' && + ['pending', 'acknowledged', 'rejected'].indexOf(mutationBatch.state) !== + -1 && + (mutationBatch.error === undefined || + typeof mutationBatch.error === 'object'); + let firestoreError = undefined; + if (validData && mutationBatch.error) { + validData = + typeof mutationBatch.error.message === 'string' && + typeof mutationBatch.error.code === 'string'; + if (validData) { + firestoreError = new FirestoreError(mutationBatch.error.code, mutationBatch.error.message); + } + } + if (validData) { + return new MutationMetadata(user, batchId, mutationBatch.state, firestoreError); + } + else { + logError(LOG_TAG$a, `Failed to parse mutation state for ID '${batchId}': ${value}`); + return null; + } + } + toWebStorageJSON() { + const batchMetadata = { + state: this.state, + updateTimeMs: Date.now() // Modify the existing value to trigger update. + }; + if (this.error) { + batchMetadata.error = { + code: this.error.code, + message: this.error.message + }; + } + return JSON.stringify(batchMetadata); + } +} +/** + * Holds the state of a query target, including its target ID and whether the + * target is 'not-current', 'current' or 'rejected'. + */ +// Visible for testing +class QueryTargetMetadata { + constructor(targetId, state, error) { + this.targetId = targetId; + this.state = state; + this.error = error; + } + /** + * Parses a QueryTargetMetadata from its JSON representation in WebStorage. + * Logs a warning and returns null if the format of the data is not valid. + */ + static fromWebStorageEntry(targetId, value) { + const targetState = JSON.parse(value); + let validData = typeof targetState === 'object' && + ['not-current', 'current', 'rejected'].indexOf(targetState.state) !== + -1 && + (targetState.error === undefined || + typeof targetState.error === 'object'); + let firestoreError = undefined; + if (validData && targetState.error) { + validData = + typeof targetState.error.message === 'string' && + typeof targetState.error.code === 'string'; + if (validData) { + firestoreError = new FirestoreError(targetState.error.code, targetState.error.message); + } + } + if (validData) { + return new QueryTargetMetadata(targetId, targetState.state, firestoreError); + } + else { + logError(LOG_TAG$a, `Failed to parse target state for ID '${targetId}': ${value}`); + return null; + } + } + toWebStorageJSON() { + const targetState = { + state: this.state, + updateTimeMs: Date.now() // Modify the existing value to trigger update. + }; + if (this.error) { + targetState.error = { + code: this.error.code, + message: this.error.message + }; + } + return JSON.stringify(targetState); + } +} +/** + * This class represents the immutable ClientState for a client read from + * WebStorage, containing the list of active query targets. + */ +class RemoteClientState { + constructor(clientId, activeTargetIds) { + this.clientId = clientId; + this.activeTargetIds = activeTargetIds; + } + /** + * Parses a RemoteClientState from the JSON representation in WebStorage. + * Logs a warning and returns null if the format of the data is not valid. + */ + static fromWebStorageEntry(clientId, value) { + const clientState = JSON.parse(value); + let validData = typeof clientState === 'object' && + clientState.activeTargetIds instanceof Array; + let activeTargetIdsSet = targetIdSet(); + for (let i = 0; validData && i < clientState.activeTargetIds.length; ++i) { + validData = isSafeInteger(clientState.activeTargetIds[i]); + activeTargetIdsSet = activeTargetIdsSet.add(clientState.activeTargetIds[i]); + } + if (validData) { + return new RemoteClientState(clientId, activeTargetIdsSet); + } + else { + logError(LOG_TAG$a, `Failed to parse client data for instance '${clientId}': ${value}`); + return null; + } + } +} +/** + * This class represents the online state for all clients participating in + * multi-tab. The online state is only written to by the primary client, and + * used in secondary clients to update their query views. + */ +class SharedOnlineState { + constructor(clientId, onlineState) { + this.clientId = clientId; + this.onlineState = onlineState; + } + /** + * Parses a SharedOnlineState from its JSON representation in WebStorage. + * Logs a warning and returns null if the format of the data is not valid. + */ + static fromWebStorageEntry(value) { + const onlineState = JSON.parse(value); + const validData = typeof onlineState === 'object' && + ['Unknown', 'Online', 'Offline'].indexOf(onlineState.onlineState) !== + -1 && + typeof onlineState.clientId === 'string'; + if (validData) { + return new SharedOnlineState(onlineState.clientId, onlineState.onlineState); + } + else { + logError(LOG_TAG$a, `Failed to parse online state: ${value}`); + return null; + } + } +} +/** + * Metadata state of the local client. Unlike `RemoteClientState`, this class is + * mutable and keeps track of all pending mutations, which allows us to + * update the range of pending mutation batch IDs as new mutations are added or + * removed. + * + * The data in `LocalClientState` is not read from WebStorage and instead + * updated via its instance methods. The updated state can be serialized via + * `toWebStorageJSON()`. + */ +// Visible for testing. +class LocalClientState { + constructor() { + this.activeTargetIds = targetIdSet(); + } + addQueryTarget(targetId) { + this.activeTargetIds = this.activeTargetIds.add(targetId); + } + removeQueryTarget(targetId) { + this.activeTargetIds = this.activeTargetIds.delete(targetId); + } + /** + * Converts this entry into a JSON-encoded format we can use for WebStorage. + * Does not encode `clientId` as it is part of the key in WebStorage. + */ + toWebStorageJSON() { + const data = { + activeTargetIds: this.activeTargetIds.toArray(), + updateTimeMs: Date.now() // Modify the existing value to trigger update. + }; + return JSON.stringify(data); + } +} +/** + * `WebStorageSharedClientState` uses WebStorage (window.localStorage) as the + * backing store for the SharedClientState. It keeps track of all active + * clients and supports modifications of the local client's data. + */ +class WebStorageSharedClientState { + constructor(window, queue, persistenceKey, localClientId, initialUser) { + this.window = window; + this.queue = queue; + this.persistenceKey = persistenceKey; + this.localClientId = localClientId; + this.syncEngine = null; + this.onlineStateHandler = null; + this.sequenceNumberHandler = null; + this.storageListener = this.handleWebStorageEvent.bind(this); + this.activeClients = new SortedMap(primitiveComparator); + this.started = false; + /** + * Captures WebStorage events that occur before `start()` is called. These + * events are replayed once `WebStorageSharedClientState` is started. + */ + this.earlyEvents = []; + // Escape the special characters mentioned here: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions + const escapedPersistenceKey = persistenceKey.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + this.storage = this.window.localStorage; + this.currentUser = initialUser; + this.localClientStorageKey = createWebStorageClientStateKey(this.persistenceKey, this.localClientId); + this.sequenceNumberKey = createWebStorageSequenceNumberKey(this.persistenceKey); + this.activeClients = this.activeClients.insert(this.localClientId, new LocalClientState()); + this.clientStateKeyRe = new RegExp(`^${CLIENT_STATE_KEY_PREFIX}_${escapedPersistenceKey}_([^_]*)$`); + this.mutationBatchKeyRe = new RegExp(`^${MUTATION_BATCH_KEY_PREFIX}_${escapedPersistenceKey}_(\\d+)(?:_(.*))?$`); + this.queryTargetKeyRe = new RegExp(`^${QUERY_TARGET_KEY_PREFIX}_${escapedPersistenceKey}_(\\d+)$`); + this.onlineStateKey = createWebStorageOnlineStateKey(this.persistenceKey); + this.bundleLoadedKey = createBundleLoadedKey(this.persistenceKey); + // Rather than adding the storage observer during start(), we add the + // storage observer during initialization. This ensures that we collect + // events before other components populate their initial state (during their + // respective start() calls). Otherwise, we might for example miss a + // mutation that is added after LocalStore's start() processed the existing + // mutations but before we observe WebStorage events. + this.window.addEventListener('storage', this.storageListener); + } + /** Returns 'true' if WebStorage is available in the current environment. */ + static isAvailable(window) { + return !!(window && window.localStorage); + } + async start() { + // Retrieve the list of existing clients to backfill the data in + // SharedClientState. + const existingClients = await this.syncEngine.getActiveClients(); + for (const clientId of existingClients) { + if (clientId === this.localClientId) { + continue; + } + const storageItem = this.getItem(createWebStorageClientStateKey(this.persistenceKey, clientId)); + if (storageItem) { + const clientState = RemoteClientState.fromWebStorageEntry(clientId, storageItem); + if (clientState) { + this.activeClients = this.activeClients.insert(clientState.clientId, clientState); + } + } + } + this.persistClientState(); + // Check if there is an existing online state and call the callback handler + // if applicable. + const onlineStateJSON = this.storage.getItem(this.onlineStateKey); + if (onlineStateJSON) { + const onlineState = this.fromWebStorageOnlineState(onlineStateJSON); + if (onlineState) { + this.handleOnlineStateEvent(onlineState); + } + } + for (const event of this.earlyEvents) { + this.handleWebStorageEvent(event); + } + this.earlyEvents = []; + // Register a window unload hook to remove the client metadata entry from + // WebStorage even if `shutdown()` was not called. + this.window.addEventListener('pagehide', () => this.shutdown()); + this.started = true; + } + writeSequenceNumber(sequenceNumber) { + this.setItem(this.sequenceNumberKey, JSON.stringify(sequenceNumber)); + } + getAllActiveQueryTargets() { + return this.extractActiveQueryTargets(this.activeClients); + } + isActiveQueryTarget(targetId) { + let found = false; + this.activeClients.forEach((key, value) => { + if (value.activeTargetIds.has(targetId)) { + found = true; + } + }); + return found; + } + addPendingMutation(batchId) { + this.persistMutationState(batchId, 'pending'); + } + updateMutationState(batchId, state, error) { + this.persistMutationState(batchId, state, error); + // Once a final mutation result is observed by other clients, they no longer + // access the mutation's metadata entry. Since WebStorage replays events + // in order, it is safe to delete the entry right after updating it. + this.removeMutationState(batchId); + } + addLocalQueryTarget(targetId, addToActiveTargetIds = true) { + let queryState = 'not-current'; + // Lookup an existing query state if the target ID was already registered + // by another tab + if (this.isActiveQueryTarget(targetId)) { + const storageItem = this.storage.getItem(createWebStorageQueryTargetMetadataKey(this.persistenceKey, targetId)); + if (storageItem) { + const metadata = QueryTargetMetadata.fromWebStorageEntry(targetId, storageItem); + if (metadata) { + queryState = metadata.state; + } + } + } + // If the query is listening to cache only, the target ID should not be registered with the + // local Firestore client as an active watch target. + if (addToActiveTargetIds) { + this.localClientState.addQueryTarget(targetId); + } + this.persistClientState(); + return queryState; + } + removeLocalQueryTarget(targetId) { + this.localClientState.removeQueryTarget(targetId); + this.persistClientState(); + } + isLocalQueryTarget(targetId) { + return this.localClientState.activeTargetIds.has(targetId); + } + clearQueryState(targetId) { + this.removeItem(createWebStorageQueryTargetMetadataKey(this.persistenceKey, targetId)); + } + updateQueryState(targetId, state, error) { + this.persistQueryTargetState(targetId, state, error); + } + handleUserChange(user, removedBatchIds, addedBatchIds) { + removedBatchIds.forEach(batchId => { + this.removeMutationState(batchId); + }); + this.currentUser = user; + addedBatchIds.forEach(batchId => { + this.addPendingMutation(batchId); + }); + } + setOnlineState(onlineState) { + this.persistOnlineState(onlineState); + } + notifyBundleLoaded(collectionGroups) { + this.persistBundleLoadedState(collectionGroups); + } + shutdown() { + if (this.started) { + this.window.removeEventListener('storage', this.storageListener); + this.removeItem(this.localClientStorageKey); + this.started = false; + } + } + getItem(key) { + const value = this.storage.getItem(key); + logDebug(LOG_TAG$a, 'READ', key, value); + return value; + } + setItem(key, value) { + logDebug(LOG_TAG$a, 'SET', key, value); + this.storage.setItem(key, value); + } + removeItem(key) { + logDebug(LOG_TAG$a, 'REMOVE', key); + this.storage.removeItem(key); + } + handleWebStorageEvent(event) { + // Note: The function is typed to take Event to be interface-compatible with + // `Window.addEventListener`. + const storageEvent = event; + if (storageEvent.storageArea === this.storage) { + logDebug(LOG_TAG$a, 'EVENT', storageEvent.key, storageEvent.newValue); + if (storageEvent.key === this.localClientStorageKey) { + logError('Received WebStorage notification for local change. Another client might have ' + + 'garbage-collected our state'); + return; + } + this.queue.enqueueRetryable(async () => { + if (!this.started) { + this.earlyEvents.push(storageEvent); + return; + } + if (storageEvent.key === null) { + return; + } + if (this.clientStateKeyRe.test(storageEvent.key)) { + if (storageEvent.newValue != null) { + const clientState = this.fromWebStorageClientState(storageEvent.key, storageEvent.newValue); + if (clientState) { + return this.handleClientStateEvent(clientState.clientId, clientState); + } + } + else { + const clientId = this.fromWebStorageClientStateKey(storageEvent.key); + return this.handleClientStateEvent(clientId, null); + } + } + else if (this.mutationBatchKeyRe.test(storageEvent.key)) { + if (storageEvent.newValue !== null) { + const mutationMetadata = this.fromWebStorageMutationMetadata(storageEvent.key, storageEvent.newValue); + if (mutationMetadata) { + return this.handleMutationBatchEvent(mutationMetadata); + } + } + } + else if (this.queryTargetKeyRe.test(storageEvent.key)) { + if (storageEvent.newValue !== null) { + const queryTargetMetadata = this.fromWebStorageQueryTargetMetadata(storageEvent.key, storageEvent.newValue); + if (queryTargetMetadata) { + return this.handleQueryTargetEvent(queryTargetMetadata); + } + } + } + else if (storageEvent.key === this.onlineStateKey) { + if (storageEvent.newValue !== null) { + const onlineState = this.fromWebStorageOnlineState(storageEvent.newValue); + if (onlineState) { + return this.handleOnlineStateEvent(onlineState); + } + } + } + else if (storageEvent.key === this.sequenceNumberKey) { + const sequenceNumber = fromWebStorageSequenceNumber(storageEvent.newValue); + if (sequenceNumber !== ListenSequence.INVALID) { + this.sequenceNumberHandler(sequenceNumber); + } + } + else if (storageEvent.key === this.bundleLoadedKey) { + const collectionGroups = this.fromWebStoreBundleLoadedState(storageEvent.newValue); + await Promise.all(collectionGroups.map(cg => this.syncEngine.synchronizeWithChangedDocuments(cg))); + } + }); + } + } + get localClientState() { + return this.activeClients.get(this.localClientId); + } + persistClientState() { + this.setItem(this.localClientStorageKey, this.localClientState.toWebStorageJSON()); + } + persistMutationState(batchId, state, error) { + const mutationState = new MutationMetadata(this.currentUser, batchId, state, error); + const mutationKey = createWebStorageMutationBatchKey(this.persistenceKey, this.currentUser, batchId); + this.setItem(mutationKey, mutationState.toWebStorageJSON()); + } + removeMutationState(batchId) { + const mutationKey = createWebStorageMutationBatchKey(this.persistenceKey, this.currentUser, batchId); + this.removeItem(mutationKey); + } + persistOnlineState(onlineState) { + const entry = { + clientId: this.localClientId, + onlineState + }; + this.storage.setItem(this.onlineStateKey, JSON.stringify(entry)); + } + persistQueryTargetState(targetId, state, error) { + const targetKey = createWebStorageQueryTargetMetadataKey(this.persistenceKey, targetId); + const targetMetadata = new QueryTargetMetadata(targetId, state, error); + this.setItem(targetKey, targetMetadata.toWebStorageJSON()); + } + persistBundleLoadedState(collectionGroups) { + const json = JSON.stringify(Array.from(collectionGroups)); + this.setItem(this.bundleLoadedKey, json); + } + /** + * Parses a client state key in WebStorage. Returns null if the key does not + * match the expected key format. + */ + fromWebStorageClientStateKey(key) { + const match = this.clientStateKeyRe.exec(key); + return match ? match[1] : null; + } + /** + * Parses a client state in WebStorage. Returns 'null' if the value could not + * be parsed. + */ + fromWebStorageClientState(key, value) { + const clientId = this.fromWebStorageClientStateKey(key); + return RemoteClientState.fromWebStorageEntry(clientId, value); + } + /** + * Parses a mutation batch state in WebStorage. Returns 'null' if the value + * could not be parsed. + */ + fromWebStorageMutationMetadata(key, value) { + const match = this.mutationBatchKeyRe.exec(key); + const batchId = Number(match[1]); + const userId = match[2] !== undefined ? match[2] : null; + return MutationMetadata.fromWebStorageEntry(new User(userId), batchId, value); + } + /** + * Parses a query target state from WebStorage. Returns 'null' if the value + * could not be parsed. + */ + fromWebStorageQueryTargetMetadata(key, value) { + const match = this.queryTargetKeyRe.exec(key); + const targetId = Number(match[1]); + return QueryTargetMetadata.fromWebStorageEntry(targetId, value); + } + /** + * Parses an online state from WebStorage. Returns 'null' if the value + * could not be parsed. + */ + fromWebStorageOnlineState(value) { + return SharedOnlineState.fromWebStorageEntry(value); + } + fromWebStoreBundleLoadedState(value) { + return JSON.parse(value); + } + async handleMutationBatchEvent(mutationBatch) { + if (mutationBatch.user.uid !== this.currentUser.uid) { + logDebug(LOG_TAG$a, `Ignoring mutation for non-active user ${mutationBatch.user.uid}`); + return; + } + return this.syncEngine.applyBatchState(mutationBatch.batchId, mutationBatch.state, mutationBatch.error); + } + handleQueryTargetEvent(targetMetadata) { + return this.syncEngine.applyTargetState(targetMetadata.targetId, targetMetadata.state, targetMetadata.error); + } + handleClientStateEvent(clientId, clientState) { + const updatedClients = clientState + ? this.activeClients.insert(clientId, clientState) + : this.activeClients.remove(clientId); + const existingTargets = this.extractActiveQueryTargets(this.activeClients); + const newTargets = this.extractActiveQueryTargets(updatedClients); + const addedTargets = []; + const removedTargets = []; + newTargets.forEach(targetId => { + if (!existingTargets.has(targetId)) { + addedTargets.push(targetId); + } + }); + existingTargets.forEach(targetId => { + if (!newTargets.has(targetId)) { + removedTargets.push(targetId); + } + }); + return this.syncEngine.applyActiveTargetsChange(addedTargets, removedTargets).then(() => { + this.activeClients = updatedClients; + }); + } + handleOnlineStateEvent(onlineState) { + // We check whether the client that wrote this online state is still active + // by comparing its client ID to the list of clients kept active in + // IndexedDb. If a client does not update their IndexedDb client state + // within 5 seconds, it is considered inactive and we don't emit an online + // state event. + if (this.activeClients.get(onlineState.clientId)) { + this.onlineStateHandler(onlineState.onlineState); + } + } + extractActiveQueryTargets(clients) { + let activeTargets = targetIdSet(); + clients.forEach((kev, value) => { + activeTargets = activeTargets.unionWith(value.activeTargetIds); + }); + return activeTargets; + } +} +function fromWebStorageSequenceNumber(seqString) { + let sequenceNumber = ListenSequence.INVALID; + if (seqString != null) { + try { + const parsed = JSON.parse(seqString); + hardAssert(typeof parsed === 'number', 0x77ac, { seqString }); + sequenceNumber = parsed; + } + catch (e) { + logError(LOG_TAG$a, 'Failed to read sequence number from WebStorage', e); + } + } + return sequenceNumber; +} +/** + * `MemorySharedClientState` is a simple implementation of SharedClientState for + * clients using memory persistence. The state in this class remains fully + * isolated and no synchronization is performed. + */ +class MemorySharedClientState { + constructor() { + this.localState = new LocalClientState(); + this.queryState = {}; + this.onlineStateHandler = null; + this.sequenceNumberHandler = null; + } + addPendingMutation(batchId) { + // No op. + } + updateMutationState(batchId, state, error) { + // No op. + } + addLocalQueryTarget(targetId, addToActiveTargetIds = true) { + if (addToActiveTargetIds) { + this.localState.addQueryTarget(targetId); + } + return this.queryState[targetId] || 'not-current'; + } + updateQueryState(targetId, state, error) { + this.queryState[targetId] = state; + } + removeLocalQueryTarget(targetId) { + this.localState.removeQueryTarget(targetId); + } + isLocalQueryTarget(targetId) { + return this.localState.activeTargetIds.has(targetId); + } + clearQueryState(targetId) { + delete this.queryState[targetId]; + } + getAllActiveQueryTargets() { + return this.localState.activeTargetIds; + } + isActiveQueryTarget(targetId) { + return this.localState.activeTargetIds.has(targetId); + } + start() { + this.localState = new LocalClientState(); + return Promise.resolve(); + } + handleUserChange(user, removedBatchIds, addedBatchIds) { + // No op. + } + setOnlineState(onlineState) { + // No op. + } + shutdown() { } + writeSequenceNumber(sequenceNumber) { } + notifyBundleLoaded(collectionGroups) { + // No op. + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class NoopConnectivityMonitor { + addCallback(callback) { + // No-op. + } + shutdown() { + // No-op. + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provides a simple helper class that implements the Stream interface to + * bridge to other implementations that are streams but do not implement the + * interface. The stream callbacks are invoked with the callOn... methods. + */ +class StreamBridge { + constructor(args) { + this.sendFn = args.sendFn; + this.closeFn = args.closeFn; + } + onConnected(callback) { + this.wrappedOnConnected = callback; + } + onOpen(callback) { + this.wrappedOnOpen = callback; + } + onClose(callback) { + this.wrappedOnClose = callback; + } + onMessage(callback) { + this.wrappedOnMessage = callback; + } + close() { + this.closeFn(); + } + send(msg) { + this.sendFn(msg); + } + callOnConnected() { + this.wrappedOnConnected(); + } + callOnOpen() { + this.wrappedOnOpen(); + } + callOnClose(err) { + this.wrappedOnClose(err); + } + callOnMessage(msg) { + this.wrappedOnMessage(msg); + } +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The value returned from the most recent invocation of + * `generateUniqueDebugId()`, or null if it has never been invoked. + */ +let lastUniqueDebugId = null; +/** + * Generates and returns an initial value for `lastUniqueDebugId`. + * + * The returned value is randomly selected from a range of integers that are + * represented as 8 hexadecimal digits. This means that (within reason) any + * numbers generated by incrementing the returned number by 1 will also be + * represented by 8 hexadecimal digits. This leads to all "IDs" having the same + * length when converted to a hexadecimal string, making reading logs containing + * these IDs easier to follow. And since the return value is randomly selected + * it will help to differentiate between logs from different executions. + */ +function generateInitialUniqueDebugId() { + const minResult = 0x10000000; + const maxResult = 0x90000000; + const resultRange = maxResult - minResult; + const resultOffset = Math.round(resultRange * Math.random()); + return minResult + resultOffset; +} +/** + * Generates and returns a unique ID as a hexadecimal string. + * + * The returned ID is intended to be used in debug logging messages to help + * correlate log messages that may be spatially separated in the logs, but + * logically related. For example, a network connection could include the same + * "debug ID" string in all of its log messages to help trace a specific + * connection over time. + * + * @return the 10-character generated ID (e.g. "0xa1b2c3d4"). + */ +function generateUniqueDebugId() { + if (lastUniqueDebugId === null) { + lastUniqueDebugId = generateInitialUniqueDebugId(); + } + else { + lastUniqueDebugId++; + } + return '0x' + lastUniqueDebugId.toString(16); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * Utilities for dealing with node.js-style APIs. See nodePromise for more + * details. + */ +/** + * Creates a node-style callback that resolves or rejects a new Promise. The + * callback is passed to the given action which can then use the callback as + * a parameter to a node-style function. + * + * The intent is to directly bridge a node-style function (which takes a + * callback) into a Promise without manually converting between the node-style + * callback and the promise at each call. + * + * In effect it allows you to convert: + * + * @example + * new Promise((resolve: (value?: fs.Stats) => void, + * reject: (error?: any) => void) => { + * fs.stat(path, (error?: any, stat?: fs.Stats) => { + * if (error) { + * reject(error); + * } else { + * resolve(stat); + * } + * }); + * }); + * + * Into + * @example + * nodePromise((callback: NodeCallback) => { + * fs.stat(path, callback); + * }); + * + * @param action - a function that takes a node-style callback as an argument + * and then uses that callback to invoke some node-style API. + * @returns a new Promise which will be rejected if the callback is given the + * first Error parameter or will resolve to the value given otherwise. + */ +function nodePromise(action) { + return new Promise((resolve, reject) => { + action((error, value) => { + if (error) { + reject(error); + } + else { + resolve(value); + } + }); + }); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// TODO: Fetch runtime version from grpc-js/package.json instead +// when there's a cleaner way to dynamic require JSON in both Node ESM and CJS +const grpcVersion = '1.9.15'; +const LOG_TAG$9 = 'GrpcConnection'; +const X_GOOG_API_CLIENT_VALUE = `gl-node/${process.versions.node} fire/${SDK_VERSION} grpc/${grpcVersion}`; +function createMetadata(databasePath, authToken, appCheckToken, appId) { + hardAssert(authToken === null || authToken.type === 'OAuth', 0x9048); + const metadata = new grpc__namespace.Metadata(); + if (authToken) { + authToken.headers.forEach((value, key) => metadata.set(key, value)); + } + if (appCheckToken) { + appCheckToken.headers.forEach((value, key) => metadata.set(key, value)); + } + if (appId) { + metadata.set('X-Firebase-GMPID', appId); + } + metadata.set('X-Goog-Api-Client', X_GOOG_API_CLIENT_VALUE); + // These headers are used to improve routing and project isolation by the + // backend. + // TODO(b/199767712): We are keeping 'Google-Cloud-Resource-Prefix' until Emulators can be + // released with cl/428820046. Currently blocked because Emulators are now built with Java + // 11 from Google3. + metadata.set('Google-Cloud-Resource-Prefix', databasePath); + metadata.set('x-goog-request-params', databasePath); + return metadata; +} +/** + * A Connection implemented by GRPC-Node. + */ +class GrpcConnection { + get shouldResourcePathBeIncludedInRequest() { + // Both `invokeRPC()` and `invokeStreamingRPC()` ignore their `path` arguments, and expect + // the "path" to be part of the given `request`. + return true; + } + constructor(protos, databaseInfo) { + this.databaseInfo = databaseInfo; + // We cache stubs for the most-recently-used token. + this.cachedStub = null; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.firestore = protos['google']['firestore']['v1']; + this.databasePath = `projects/${databaseInfo.databaseId.projectId}/databases/${databaseInfo.databaseId.database}`; + } + ensureActiveStub() { + if (!this.cachedStub) { + logDebug(LOG_TAG$9, 'Creating Firestore stub.'); + const credentials = this.databaseInfo.ssl + ? grpc__namespace.credentials.createSsl() + : grpc__namespace.credentials.createInsecure(); + this.cachedStub = new this.firestore.Firestore(this.databaseInfo.host, credentials); + } + return this.cachedStub; + } + invokeRPC(rpcName, path, request, authToken, appCheckToken) { + const streamId = generateUniqueDebugId(); + const stub = this.ensureActiveStub(); + const metadata = createMetadata(this.databasePath, authToken, appCheckToken, this.databaseInfo.appId); + const jsonRequest = { database: this.databasePath, ...request }; + return nodePromise((callback) => { + logDebug(LOG_TAG$9, `RPC '${rpcName}' ${streamId} invoked with request:`, request); + return stub[rpcName](jsonRequest, metadata, (grpcError, value) => { + if (grpcError) { + logDebug(LOG_TAG$9, `RPC '${rpcName}' ${streamId} failed with error:`, grpcError); + callback(new FirestoreError(mapCodeFromRpcCode(grpcError.code), grpcError.message)); + } + else { + logDebug(LOG_TAG$9, `RPC '${rpcName}' ${streamId} completed with response:`, value); + callback(undefined, value); + } + }); + }); + } + invokeStreamingRPC(rpcName, path, request, authToken, appCheckToken, expectedResponseCount) { + const streamId = generateUniqueDebugId(); + const results = []; + const responseDeferred = new Deferred(); + logDebug(LOG_TAG$9, `RPC '${rpcName}' ${streamId} invoked (streaming) with request:`, request); + const stub = this.ensureActiveStub(); + const metadata = createMetadata(this.databasePath, authToken, appCheckToken, this.databaseInfo.appId); + const jsonRequest = { ...request, database: this.databasePath }; + const stream = stub[rpcName](jsonRequest, metadata); + let callbackFired = false; + stream.on('data', (response) => { + logDebug(LOG_TAG$9, `RPC ${rpcName} ${streamId} received result:`, response); + results.push(response); + if (expectedResponseCount !== undefined && + results.length === expectedResponseCount) { + callbackFired = true; + responseDeferred.resolve(results); + } + }); + stream.on('end', () => { + logDebug(LOG_TAG$9, `RPC '${rpcName}' ${streamId} completed.`); + if (!callbackFired) { + callbackFired = true; + responseDeferred.resolve(results); + } + }); + stream.on('error', (grpcError) => { + logDebug(LOG_TAG$9, `RPC '${rpcName}' ${streamId} failed with error:`, grpcError); + const code = mapCodeFromRpcCode(grpcError.code); + responseDeferred.reject(new FirestoreError(code, grpcError.message)); + }); + return responseDeferred.promise; + } + // TODO(mikelehen): This "method" is a monster. Should be refactored. + openStream(rpcName, authToken, appCheckToken) { + const streamId = generateUniqueDebugId(); + const stub = this.ensureActiveStub(); + const metadata = createMetadata(this.databasePath, authToken, appCheckToken, this.databaseInfo.appId); + const grpcStream = stub[rpcName](metadata); + let closed = false; + const close = (err) => { + if (!closed) { + closed = true; + stream.callOnClose(err); + grpcStream.end(); + } + }; + const stream = new StreamBridge({ + sendFn: (msg) => { + if (!closed) { + logDebug(LOG_TAG$9, `RPC '${rpcName}' stream ${streamId} sending:`, msg); + try { + grpcStream.write(msg); + } + catch (e) { + // This probably means we didn't conform to the proto. Make sure to + // log the message we sent. + logError('Failure sending:', msg); + logError('Error:', e); + throw e; + } + } + else { + logDebug(LOG_TAG$9, `RPC '${rpcName}' stream ${streamId} ` + + 'not sending because gRPC stream is closed:', msg); + } + }, + closeFn: () => { + logDebug(LOG_TAG$9, `RPC '${rpcName}' stream ${streamId} closed locally via close().`); + close(); + } + }); + let onConnectedSent = false; + grpcStream.on('data', (msg) => { + if (!closed) { + logDebug(LOG_TAG$9, `RPC '${rpcName}' stream ${streamId} received:`, msg); + // Emulate the "onConnected" event that WebChannelConnection sends. + if (!onConnectedSent) { + stream.callOnConnected(); + onConnectedSent = true; + } + stream.callOnMessage(msg); + } + }); + grpcStream.on('end', () => { + logDebug(LOG_TAG$9, `RPC '${rpcName}' stream ${streamId} ended.`); + close(); + }); + grpcStream.on('error', (grpcError) => { + if (!closed) { + logWarn(LOG_TAG$9, `RPC '${rpcName}' stream ${streamId} error. Code:`, grpcError.code, 'Message:', grpcError.message); + const code = mapCodeFromRpcCode(grpcError.code); + close(new FirestoreError(code, grpcError.message)); + } + }); + logDebug(LOG_TAG$9, `Opening RPC '${rpcName}' stream ${streamId} ` + + `to ${this.databaseInfo.host}`); + // TODO(dimond): Since grpc has no explicit open status (or does it?) we + // simulate an onOpen in the next loop after the stream had it's listeners + // registered + setTimeout(() => { + stream.callOnOpen(); + }, 0); + return stream; + } + /** + * Closes and cleans up any resources associated with the GrpcConnection. + * If a gRPC client has been generated for this connection, the gRPC client + * is closed. Failure to call terminate on a GrpcConnection can result + * in leaked resources of the gRPC client. + */ + terminate() { + if (this.cachedStub) { + this.cachedStub.close(); + this.cachedStub = undefined; + } + } +} + +const nested = { + google: { + nested: { + protobuf: { + options: { + csharp_namespace: "Google.Protobuf.WellKnownTypes", + go_package: "github.com/golang/protobuf/ptypes/wrappers", + java_package: "com.google.protobuf", + java_outer_classname: "WrappersProto", + java_multiple_files: true, + objc_class_prefix: "GPB", + cc_enable_arenas: true, + optimize_for: "SPEED" + }, + nested: { + Timestamp: { + fields: { + seconds: { + type: "int64", + id: 1 + }, + nanos: { + type: "int32", + id: 2 + } + } + }, + FileDescriptorSet: { + fields: { + file: { + rule: "repeated", + type: "FileDescriptorProto", + id: 1 + } + } + }, + FileDescriptorProto: { + fields: { + name: { + type: "string", + id: 1 + }, + "package": { + type: "string", + id: 2 + }, + dependency: { + rule: "repeated", + type: "string", + id: 3 + }, + publicDependency: { + rule: "repeated", + type: "int32", + id: 10, + options: { + packed: false + } + }, + weakDependency: { + rule: "repeated", + type: "int32", + id: 11, + options: { + packed: false + } + }, + messageType: { + rule: "repeated", + type: "DescriptorProto", + id: 4 + }, + enumType: { + rule: "repeated", + type: "EnumDescriptorProto", + id: 5 + }, + service: { + rule: "repeated", + type: "ServiceDescriptorProto", + id: 6 + }, + extension: { + rule: "repeated", + type: "FieldDescriptorProto", + id: 7 + }, + options: { + type: "FileOptions", + id: 8 + }, + sourceCodeInfo: { + type: "SourceCodeInfo", + id: 9 + }, + syntax: { + type: "string", + id: 12 + } + } + }, + DescriptorProto: { + fields: { + name: { + type: "string", + id: 1 + }, + field: { + rule: "repeated", + type: "FieldDescriptorProto", + id: 2 + }, + extension: { + rule: "repeated", + type: "FieldDescriptorProto", + id: 6 + }, + nestedType: { + rule: "repeated", + type: "DescriptorProto", + id: 3 + }, + enumType: { + rule: "repeated", + type: "EnumDescriptorProto", + id: 4 + }, + extensionRange: { + rule: "repeated", + type: "ExtensionRange", + id: 5 + }, + oneofDecl: { + rule: "repeated", + type: "OneofDescriptorProto", + id: 8 + }, + options: { + type: "MessageOptions", + id: 7 + }, + reservedRange: { + rule: "repeated", + type: "ReservedRange", + id: 9 + }, + reservedName: { + rule: "repeated", + type: "string", + id: 10 + } + }, + nested: { + ExtensionRange: { + fields: { + start: { + type: "int32", + id: 1 + }, + end: { + type: "int32", + id: 2 + } + } + }, + ReservedRange: { + fields: { + start: { + type: "int32", + id: 1 + }, + end: { + type: "int32", + id: 2 + } + } + } + } + }, + FieldDescriptorProto: { + fields: { + name: { + type: "string", + id: 1 + }, + number: { + type: "int32", + id: 3 + }, + label: { + type: "Label", + id: 4 + }, + type: { + type: "Type", + id: 5 + }, + typeName: { + type: "string", + id: 6 + }, + extendee: { + type: "string", + id: 2 + }, + defaultValue: { + type: "string", + id: 7 + }, + oneofIndex: { + type: "int32", + id: 9 + }, + jsonName: { + type: "string", + id: 10 + }, + options: { + type: "FieldOptions", + id: 8 + } + }, + nested: { + Type: { + values: { + TYPE_DOUBLE: 1, + TYPE_FLOAT: 2, + TYPE_INT64: 3, + TYPE_UINT64: 4, + TYPE_INT32: 5, + TYPE_FIXED64: 6, + TYPE_FIXED32: 7, + TYPE_BOOL: 8, + TYPE_STRING: 9, + TYPE_GROUP: 10, + TYPE_MESSAGE: 11, + TYPE_BYTES: 12, + TYPE_UINT32: 13, + TYPE_ENUM: 14, + TYPE_SFIXED32: 15, + TYPE_SFIXED64: 16, + TYPE_SINT32: 17, + TYPE_SINT64: 18 + } + }, + Label: { + values: { + LABEL_OPTIONAL: 1, + LABEL_REQUIRED: 2, + LABEL_REPEATED: 3 + } + } + } + }, + OneofDescriptorProto: { + fields: { + name: { + type: "string", + id: 1 + }, + options: { + type: "OneofOptions", + id: 2 + } + } + }, + EnumDescriptorProto: { + fields: { + name: { + type: "string", + id: 1 + }, + value: { + rule: "repeated", + type: "EnumValueDescriptorProto", + id: 2 + }, + options: { + type: "EnumOptions", + id: 3 + } + } + }, + EnumValueDescriptorProto: { + fields: { + name: { + type: "string", + id: 1 + }, + number: { + type: "int32", + id: 2 + }, + options: { + type: "EnumValueOptions", + id: 3 + } + } + }, + ServiceDescriptorProto: { + fields: { + name: { + type: "string", + id: 1 + }, + method: { + rule: "repeated", + type: "MethodDescriptorProto", + id: 2 + }, + options: { + type: "ServiceOptions", + id: 3 + } + } + }, + MethodDescriptorProto: { + fields: { + name: { + type: "string", + id: 1 + }, + inputType: { + type: "string", + id: 2 + }, + outputType: { + type: "string", + id: 3 + }, + options: { + type: "MethodOptions", + id: 4 + }, + clientStreaming: { + type: "bool", + id: 5 + }, + serverStreaming: { + type: "bool", + id: 6 + } + } + }, + FileOptions: { + fields: { + javaPackage: { + type: "string", + id: 1 + }, + javaOuterClassname: { + type: "string", + id: 8 + }, + javaMultipleFiles: { + type: "bool", + id: 10 + }, + javaGenerateEqualsAndHash: { + type: "bool", + id: 20, + options: { + deprecated: true + } + }, + javaStringCheckUtf8: { + type: "bool", + id: 27 + }, + optimizeFor: { + type: "OptimizeMode", + id: 9, + options: { + "default": "SPEED" + } + }, + goPackage: { + type: "string", + id: 11 + }, + ccGenericServices: { + type: "bool", + id: 16 + }, + javaGenericServices: { + type: "bool", + id: 17 + }, + pyGenericServices: { + type: "bool", + id: 18 + }, + deprecated: { + type: "bool", + id: 23 + }, + ccEnableArenas: { + type: "bool", + id: 31 + }, + objcClassPrefix: { + type: "string", + id: 36 + }, + csharpNamespace: { + type: "string", + id: 37 + }, + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1000, + 536870911 + ] + ], + reserved: [ + [ + 38, + 38 + ] + ], + nested: { + OptimizeMode: { + values: { + SPEED: 1, + CODE_SIZE: 2, + LITE_RUNTIME: 3 + } + } + } + }, + MessageOptions: { + fields: { + messageSetWireFormat: { + type: "bool", + id: 1 + }, + noStandardDescriptorAccessor: { + type: "bool", + id: 2 + }, + deprecated: { + type: "bool", + id: 3 + }, + mapEntry: { + type: "bool", + id: 7 + }, + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1000, + 536870911 + ] + ], + reserved: [ + [ + 8, + 8 + ] + ] + }, + FieldOptions: { + fields: { + ctype: { + type: "CType", + id: 1, + options: { + "default": "STRING" + } + }, + packed: { + type: "bool", + id: 2 + }, + jstype: { + type: "JSType", + id: 6, + options: { + "default": "JS_NORMAL" + } + }, + lazy: { + type: "bool", + id: 5 + }, + deprecated: { + type: "bool", + id: 3 + }, + weak: { + type: "bool", + id: 10 + }, + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1000, + 536870911 + ] + ], + reserved: [ + [ + 4, + 4 + ] + ], + nested: { + CType: { + values: { + STRING: 0, + CORD: 1, + STRING_PIECE: 2 + } + }, + JSType: { + values: { + JS_NORMAL: 0, + JS_STRING: 1, + JS_NUMBER: 2 + } + } + } + }, + OneofOptions: { + fields: { + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1000, + 536870911 + ] + ] + }, + EnumOptions: { + fields: { + allowAlias: { + type: "bool", + id: 2 + }, + deprecated: { + type: "bool", + id: 3 + }, + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1000, + 536870911 + ] + ] + }, + EnumValueOptions: { + fields: { + deprecated: { + type: "bool", + id: 1 + }, + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1000, + 536870911 + ] + ] + }, + ServiceOptions: { + fields: { + deprecated: { + type: "bool", + id: 33 + }, + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1000, + 536870911 + ] + ] + }, + MethodOptions: { + fields: { + deprecated: { + type: "bool", + id: 33 + }, + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1000, + 536870911 + ] + ] + }, + UninterpretedOption: { + fields: { + name: { + rule: "repeated", + type: "NamePart", + id: 2 + }, + identifierValue: { + type: "string", + id: 3 + }, + positiveIntValue: { + type: "uint64", + id: 4 + }, + negativeIntValue: { + type: "int64", + id: 5 + }, + doubleValue: { + type: "double", + id: 6 + }, + stringValue: { + type: "bytes", + id: 7 + }, + aggregateValue: { + type: "string", + id: 8 + } + }, + nested: { + NamePart: { + fields: { + namePart: { + rule: "required", + type: "string", + id: 1 + }, + isExtension: { + rule: "required", + type: "bool", + id: 2 + } + } + } + } + }, + SourceCodeInfo: { + fields: { + location: { + rule: "repeated", + type: "Location", + id: 1 + } + }, + nested: { + Location: { + fields: { + path: { + rule: "repeated", + type: "int32", + id: 1 + }, + span: { + rule: "repeated", + type: "int32", + id: 2 + }, + leadingComments: { + type: "string", + id: 3 + }, + trailingComments: { + type: "string", + id: 4 + }, + leadingDetachedComments: { + rule: "repeated", + type: "string", + id: 6 + } + } + } + } + }, + GeneratedCodeInfo: { + fields: { + annotation: { + rule: "repeated", + type: "Annotation", + id: 1 + } + }, + nested: { + Annotation: { + fields: { + path: { + rule: "repeated", + type: "int32", + id: 1 + }, + sourceFile: { + type: "string", + id: 2 + }, + begin: { + type: "int32", + id: 3 + }, + end: { + type: "int32", + id: 4 + } + } + } + } + }, + Struct: { + fields: { + fields: { + keyType: "string", + type: "Value", + id: 1 + } + } + }, + Value: { + oneofs: { + kind: { + oneof: [ + "nullValue", + "numberValue", + "stringValue", + "boolValue", + "structValue", + "listValue" + ] + } + }, + fields: { + nullValue: { + type: "NullValue", + id: 1 + }, + numberValue: { + type: "double", + id: 2 + }, + stringValue: { + type: "string", + id: 3 + }, + boolValue: { + type: "bool", + id: 4 + }, + structValue: { + type: "Struct", + id: 5 + }, + listValue: { + type: "ListValue", + id: 6 + } + } + }, + NullValue: { + values: { + NULL_VALUE: 0 + } + }, + ListValue: { + fields: { + values: { + rule: "repeated", + type: "Value", + id: 1 + } + } + }, + Empty: { + fields: { + } + }, + DoubleValue: { + fields: { + value: { + type: "double", + id: 1 + } + } + }, + FloatValue: { + fields: { + value: { + type: "float", + id: 1 + } + } + }, + Int64Value: { + fields: { + value: { + type: "int64", + id: 1 + } + } + }, + UInt64Value: { + fields: { + value: { + type: "uint64", + id: 1 + } + } + }, + Int32Value: { + fields: { + value: { + type: "int32", + id: 1 + } + } + }, + UInt32Value: { + fields: { + value: { + type: "uint32", + id: 1 + } + } + }, + BoolValue: { + fields: { + value: { + type: "bool", + id: 1 + } + } + }, + StringValue: { + fields: { + value: { + type: "string", + id: 1 + } + } + }, + BytesValue: { + fields: { + value: { + type: "bytes", + id: 1 + } + } + }, + Any: { + fields: { + typeUrl: { + type: "string", + id: 1 + }, + value: { + type: "bytes", + id: 2 + } + } + } + } + }, + firestore: { + nested: { + v1: { + options: { + csharp_namespace: "Google.Cloud.Firestore.V1", + go_package: "google.golang.org/genproto/googleapis/firestore/v1;firestore", + java_multiple_files: true, + java_outer_classname: "WriteProto", + java_package: "com.google.firestore.v1", + objc_class_prefix: "GCFS", + php_namespace: "Google\\Cloud\\Firestore\\V1", + ruby_package: "Google::Cloud::Firestore::V1" + }, + nested: { + AggregationResult: { + fields: { + aggregateFields: { + keyType: "string", + type: "Value", + id: 2 + } + } + }, + BitSequence: { + fields: { + bitmap: { + type: "bytes", + id: 1 + }, + padding: { + type: "int32", + id: 2 + } + } + }, + BloomFilter: { + fields: { + bits: { + type: "BitSequence", + id: 1 + }, + hashCount: { + type: "int32", + id: 2 + } + } + }, + DocumentMask: { + fields: { + fieldPaths: { + rule: "repeated", + type: "string", + id: 1 + } + } + }, + Precondition: { + oneofs: { + conditionType: { + oneof: [ + "exists", + "updateTime" + ] + } + }, + fields: { + exists: { + type: "bool", + id: 1 + }, + updateTime: { + type: "google.protobuf.Timestamp", + id: 2 + } + } + }, + TransactionOptions: { + oneofs: { + mode: { + oneof: [ + "readOnly", + "readWrite" + ] + } + }, + fields: { + readOnly: { + type: "ReadOnly", + id: 2 + }, + readWrite: { + type: "ReadWrite", + id: 3 + } + }, + nested: { + ReadWrite: { + fields: { + retryTransaction: { + type: "bytes", + id: 1 + } + } + }, + ReadOnly: { + oneofs: { + consistencySelector: { + oneof: [ + "readTime" + ] + } + }, + fields: { + readTime: { + type: "google.protobuf.Timestamp", + id: 2 + } + } + } + } + }, + Document: { + fields: { + name: { + type: "string", + id: 1 + }, + fields: { + keyType: "string", + type: "Value", + id: 2 + }, + createTime: { + type: "google.protobuf.Timestamp", + id: 3 + }, + updateTime: { + type: "google.protobuf.Timestamp", + id: 4 + } + } + }, + Value: { + oneofs: { + valueType: { + oneof: [ + "nullValue", + "booleanValue", + "integerValue", + "doubleValue", + "timestampValue", + "stringValue", + "bytesValue", + "referenceValue", + "geoPointValue", + "arrayValue", + "mapValue" + ] + } + }, + fields: { + nullValue: { + type: "google.protobuf.NullValue", + id: 11 + }, + booleanValue: { + type: "bool", + id: 1 + }, + integerValue: { + type: "int64", + id: 2 + }, + doubleValue: { + type: "double", + id: 3 + }, + timestampValue: { + type: "google.protobuf.Timestamp", + id: 10 + }, + stringValue: { + type: "string", + id: 17 + }, + bytesValue: { + type: "bytes", + id: 18 + }, + referenceValue: { + type: "string", + id: 5 + }, + geoPointValue: { + type: "google.type.LatLng", + id: 8 + }, + arrayValue: { + type: "ArrayValue", + id: 9 + }, + mapValue: { + type: "MapValue", + id: 6 + } + } + }, + ArrayValue: { + fields: { + values: { + rule: "repeated", + type: "Value", + id: 1 + } + } + }, + MapValue: { + fields: { + fields: { + keyType: "string", + type: "Value", + id: 1 + } + } + }, + Firestore: { + options: { + "(google.api.default_host)": "firestore.googleapis.com", + "(google.api.oauth_scopes)": "https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/datastore" + }, + methods: { + GetDocument: { + requestType: "GetDocumentRequest", + responseType: "Document", + options: { + "(google.api.http).get": "/v1/{name=projects/*/databases/*/documents/*/**}" + }, + parsedOptions: [ + { + "(google.api.http)": { + get: "/v1/{name=projects/*/databases/*/documents/*/**}" + } + } + ] + }, + ListDocuments: { + requestType: "ListDocumentsRequest", + responseType: "ListDocumentsResponse", + options: { + "(google.api.http).get": "/v1/{parent=projects/*/databases/*/documents/*/**}/{collection_id}" + }, + parsedOptions: [ + { + "(google.api.http)": { + get: "/v1/{parent=projects/*/databases/*/documents/*/**}/{collection_id}" + } + } + ] + }, + UpdateDocument: { + requestType: "UpdateDocumentRequest", + responseType: "Document", + options: { + "(google.api.http).patch": "/v1/{document.name=projects/*/databases/*/documents/*/**}", + "(google.api.http).body": "document", + "(google.api.method_signature)": "document,update_mask" + }, + parsedOptions: [ + { + "(google.api.http)": { + patch: "/v1/{document.name=projects/*/databases/*/documents/*/**}", + body: "document" + } + }, + { + "(google.api.method_signature)": "document,update_mask" + } + ] + }, + DeleteDocument: { + requestType: "DeleteDocumentRequest", + responseType: "google.protobuf.Empty", + options: { + "(google.api.http).delete": "/v1/{name=projects/*/databases/*/documents/*/**}", + "(google.api.method_signature)": "name" + }, + parsedOptions: [ + { + "(google.api.http)": { + "delete": "/v1/{name=projects/*/databases/*/documents/*/**}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + BatchGetDocuments: { + requestType: "BatchGetDocumentsRequest", + responseType: "BatchGetDocumentsResponse", + responseStream: true, + options: { + "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:batchGet", + "(google.api.http).body": "*" + }, + parsedOptions: [ + { + "(google.api.http)": { + post: "/v1/{database=projects/*/databases/*}/documents:batchGet", + body: "*" + } + } + ] + }, + BeginTransaction: { + requestType: "BeginTransactionRequest", + responseType: "BeginTransactionResponse", + options: { + "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:beginTransaction", + "(google.api.http).body": "*", + "(google.api.method_signature)": "database" + }, + parsedOptions: [ + { + "(google.api.http)": { + post: "/v1/{database=projects/*/databases/*}/documents:beginTransaction", + body: "*" + } + }, + { + "(google.api.method_signature)": "database" + } + ] + }, + Commit: { + requestType: "CommitRequest", + responseType: "CommitResponse", + options: { + "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:commit", + "(google.api.http).body": "*", + "(google.api.method_signature)": "database,writes" + }, + parsedOptions: [ + { + "(google.api.http)": { + post: "/v1/{database=projects/*/databases/*}/documents:commit", + body: "*" + } + }, + { + "(google.api.method_signature)": "database,writes" + } + ] + }, + Rollback: { + requestType: "RollbackRequest", + responseType: "google.protobuf.Empty", + options: { + "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:rollback", + "(google.api.http).body": "*", + "(google.api.method_signature)": "database,transaction" + }, + parsedOptions: [ + { + "(google.api.http)": { + post: "/v1/{database=projects/*/databases/*}/documents:rollback", + body: "*" + } + }, + { + "(google.api.method_signature)": "database,transaction" + } + ] + }, + RunQuery: { + requestType: "RunQueryRequest", + responseType: "RunQueryResponse", + responseStream: true, + options: { + "(google.api.http).post": "/v1/{parent=projects/*/databases/*/documents}:runQuery", + "(google.api.http).body": "*", + "(google.api.http).additional_bindings.post": "/v1/{parent=projects/*/databases/*/documents/*/**}:runQuery", + "(google.api.http).additional_bindings.body": "*" + }, + parsedOptions: [ + { + "(google.api.http)": { + post: "/v1/{parent=projects/*/databases/*/documents}:runQuery", + body: "*", + additional_bindings: { + post: "/v1/{parent=projects/*/databases/*/documents/*/**}:runQuery", + body: "*" + } + } + } + ] + }, + RunAggregationQuery: { + requestType: "RunAggregationQueryRequest", + responseType: "RunAggregationQueryResponse", + responseStream: true, + options: { + "(google.api.http).post": "/v1/{parent=projects/*/databases/*/documents}:runAggregationQuery", + "(google.api.http).body": "*", + "(google.api.http).additional_bindings.post": "/v1/{parent=projects/*/databases/*/documents/*/**}:runAggregationQuery", + "(google.api.http).additional_bindings.body": "*" + }, + parsedOptions: [ + { + "(google.api.http)": { + post: "/v1/{parent=projects/*/databases/*/documents}:runAggregationQuery", + body: "*", + additional_bindings: { + post: "/v1/{parent=projects/*/databases/*/documents/*/**}:runAggregationQuery", + body: "*" + } + } + } + ] + }, + PartitionQuery: { + requestType: "PartitionQueryRequest", + responseType: "PartitionQueryResponse", + options: { + "(google.api.http).post": "/v1/{parent=projects/*/databases/*/documents}:partitionQuery", + "(google.api.http).body": "*", + "(google.api.http).additional_bindings.post": "/v1/{parent=projects/*/databases/*/documents/*/**}:partitionQuery", + "(google.api.http).additional_bindings.body": "*" + }, + parsedOptions: [ + { + "(google.api.http)": { + post: "/v1/{parent=projects/*/databases/*/documents}:partitionQuery", + body: "*", + additional_bindings: { + post: "/v1/{parent=projects/*/databases/*/documents/*/**}:partitionQuery", + body: "*" + } + } + } + ] + }, + Write: { + requestType: "WriteRequest", + requestStream: true, + responseType: "WriteResponse", + responseStream: true, + options: { + "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:write", + "(google.api.http).body": "*" + }, + parsedOptions: [ + { + "(google.api.http)": { + post: "/v1/{database=projects/*/databases/*}/documents:write", + body: "*" + } + } + ] + }, + Listen: { + requestType: "ListenRequest", + requestStream: true, + responseType: "ListenResponse", + responseStream: true, + options: { + "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:listen", + "(google.api.http).body": "*" + }, + parsedOptions: [ + { + "(google.api.http)": { + post: "/v1/{database=projects/*/databases/*}/documents:listen", + body: "*" + } + } + ] + }, + ListCollectionIds: { + requestType: "ListCollectionIdsRequest", + responseType: "ListCollectionIdsResponse", + options: { + "(google.api.http).post": "/v1/{parent=projects/*/databases/*/documents}:listCollectionIds", + "(google.api.http).body": "*", + "(google.api.http).additional_bindings.post": "/v1/{parent=projects/*/databases/*/documents/*/**}:listCollectionIds", + "(google.api.http).additional_bindings.body": "*", + "(google.api.method_signature)": "parent" + }, + parsedOptions: [ + { + "(google.api.http)": { + post: "/v1/{parent=projects/*/databases/*/documents}:listCollectionIds", + body: "*", + additional_bindings: { + post: "/v1/{parent=projects/*/databases/*/documents/*/**}:listCollectionIds", + body: "*" + } + } + }, + { + "(google.api.method_signature)": "parent" + } + ] + }, + BatchWrite: { + requestType: "BatchWriteRequest", + responseType: "BatchWriteResponse", + options: { + "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:batchWrite", + "(google.api.http).body": "*" + }, + parsedOptions: [ + { + "(google.api.http)": { + post: "/v1/{database=projects/*/databases/*}/documents:batchWrite", + body: "*" + } + } + ] + }, + CreateDocument: { + requestType: "CreateDocumentRequest", + responseType: "Document", + options: { + "(google.api.http).post": "/v1/{parent=projects/*/databases/*/documents/**}/{collection_id}", + "(google.api.http).body": "document" + }, + parsedOptions: [ + { + "(google.api.http)": { + post: "/v1/{parent=projects/*/databases/*/documents/**}/{collection_id}", + body: "document" + } + } + ] + } + } + }, + GetDocumentRequest: { + oneofs: { + consistencySelector: { + oneof: [ + "transaction", + "readTime" + ] + } + }, + fields: { + name: { + type: "string", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + mask: { + type: "DocumentMask", + id: 2 + }, + transaction: { + type: "bytes", + id: 3 + }, + readTime: { + type: "google.protobuf.Timestamp", + id: 5 + } + } + }, + ListDocumentsRequest: { + oneofs: { + consistencySelector: { + oneof: [ + "transaction", + "readTime" + ] + } + }, + fields: { + parent: { + type: "string", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + collectionId: { + type: "string", + id: 2, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + pageSize: { + type: "int32", + id: 3 + }, + pageToken: { + type: "string", + id: 4 + }, + orderBy: { + type: "string", + id: 6 + }, + mask: { + type: "DocumentMask", + id: 7 + }, + transaction: { + type: "bytes", + id: 8 + }, + readTime: { + type: "google.protobuf.Timestamp", + id: 10 + }, + showMissing: { + type: "bool", + id: 12 + } + } + }, + ListDocumentsResponse: { + fields: { + documents: { + rule: "repeated", + type: "Document", + id: 1 + }, + nextPageToken: { + type: "string", + id: 2 + } + } + }, + CreateDocumentRequest: { + fields: { + parent: { + type: "string", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + collectionId: { + type: "string", + id: 2, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + documentId: { + type: "string", + id: 3 + }, + document: { + type: "Document", + id: 4, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + mask: { + type: "DocumentMask", + id: 5 + } + } + }, + UpdateDocumentRequest: { + fields: { + document: { + type: "Document", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + updateMask: { + type: "DocumentMask", + id: 2 + }, + mask: { + type: "DocumentMask", + id: 3 + }, + currentDocument: { + type: "Precondition", + id: 4 + } + } + }, + DeleteDocumentRequest: { + fields: { + name: { + type: "string", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + currentDocument: { + type: "Precondition", + id: 2 + } + } + }, + BatchGetDocumentsRequest: { + oneofs: { + consistencySelector: { + oneof: [ + "transaction", + "newTransaction", + "readTime" + ] + } + }, + fields: { + database: { + type: "string", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + documents: { + rule: "repeated", + type: "string", + id: 2 + }, + mask: { + type: "DocumentMask", + id: 3 + }, + transaction: { + type: "bytes", + id: 4 + }, + newTransaction: { + type: "TransactionOptions", + id: 5 + }, + readTime: { + type: "google.protobuf.Timestamp", + id: 7 + } + } + }, + BatchGetDocumentsResponse: { + oneofs: { + result: { + oneof: [ + "found", + "missing" + ] + } + }, + fields: { + found: { + type: "Document", + id: 1 + }, + missing: { + type: "string", + id: 2 + }, + transaction: { + type: "bytes", + id: 3 + }, + readTime: { + type: "google.protobuf.Timestamp", + id: 4 + } + } + }, + BeginTransactionRequest: { + fields: { + database: { + type: "string", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + options: { + type: "TransactionOptions", + id: 2 + } + } + }, + BeginTransactionResponse: { + fields: { + transaction: { + type: "bytes", + id: 1 + } + } + }, + CommitRequest: { + fields: { + database: { + type: "string", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + writes: { + rule: "repeated", + type: "Write", + id: 2 + }, + transaction: { + type: "bytes", + id: 3 + } + } + }, + CommitResponse: { + fields: { + writeResults: { + rule: "repeated", + type: "WriteResult", + id: 1 + }, + commitTime: { + type: "google.protobuf.Timestamp", + id: 2 + } + } + }, + RollbackRequest: { + fields: { + database: { + type: "string", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + transaction: { + type: "bytes", + id: 2, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + RunQueryRequest: { + oneofs: { + queryType: { + oneof: [ + "structuredQuery" + ] + }, + consistencySelector: { + oneof: [ + "transaction", + "newTransaction", + "readTime" + ] + } + }, + fields: { + parent: { + type: "string", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + structuredQuery: { + type: "StructuredQuery", + id: 2 + }, + transaction: { + type: "bytes", + id: 5 + }, + newTransaction: { + type: "TransactionOptions", + id: 6 + }, + readTime: { + type: "google.protobuf.Timestamp", + id: 7 + } + } + }, + RunQueryResponse: { + fields: { + transaction: { + type: "bytes", + id: 2 + }, + document: { + type: "Document", + id: 1 + }, + readTime: { + type: "google.protobuf.Timestamp", + id: 3 + }, + skippedResults: { + type: "int32", + id: 4 + } + } + }, + RunAggregationQueryRequest: { + oneofs: { + queryType: { + oneof: [ + "structuredAggregationQuery" + ] + }, + consistencySelector: { + oneof: [ + "transaction", + "newTransaction", + "readTime" + ] + } + }, + fields: { + parent: { + type: "string", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + structuredAggregationQuery: { + type: "StructuredAggregationQuery", + id: 2 + }, + transaction: { + type: "bytes", + id: 4 + }, + newTransaction: { + type: "TransactionOptions", + id: 5 + }, + readTime: { + type: "google.protobuf.Timestamp", + id: 6 + } + } + }, + RunAggregationQueryResponse: { + fields: { + result: { + type: "AggregationResult", + id: 1 + }, + transaction: { + type: "bytes", + id: 2 + }, + readTime: { + type: "google.protobuf.Timestamp", + id: 3 + } + } + }, + PartitionQueryRequest: { + oneofs: { + queryType: { + oneof: [ + "structuredQuery" + ] + } + }, + fields: { + parent: { + type: "string", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + structuredQuery: { + type: "StructuredQuery", + id: 2 + }, + partitionCount: { + type: "int64", + id: 3 + }, + pageToken: { + type: "string", + id: 4 + }, + pageSize: { + type: "int32", + id: 5 + } + } + }, + PartitionQueryResponse: { + fields: { + partitions: { + rule: "repeated", + type: "Cursor", + id: 1 + }, + nextPageToken: { + type: "string", + id: 2 + } + } + }, + WriteRequest: { + fields: { + database: { + type: "string", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + streamId: { + type: "string", + id: 2 + }, + writes: { + rule: "repeated", + type: "Write", + id: 3 + }, + streamToken: { + type: "bytes", + id: 4 + }, + labels: { + keyType: "string", + type: "string", + id: 5 + } + } + }, + WriteResponse: { + fields: { + streamId: { + type: "string", + id: 1 + }, + streamToken: { + type: "bytes", + id: 2 + }, + writeResults: { + rule: "repeated", + type: "WriteResult", + id: 3 + }, + commitTime: { + type: "google.protobuf.Timestamp", + id: 4 + } + } + }, + ListenRequest: { + oneofs: { + targetChange: { + oneof: [ + "addTarget", + "removeTarget" + ] + } + }, + fields: { + database: { + type: "string", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + addTarget: { + type: "Target", + id: 2 + }, + removeTarget: { + type: "int32", + id: 3 + }, + labels: { + keyType: "string", + type: "string", + id: 4 + } + } + }, + ListenResponse: { + oneofs: { + responseType: { + oneof: [ + "targetChange", + "documentChange", + "documentDelete", + "documentRemove", + "filter" + ] + } + }, + fields: { + targetChange: { + type: "TargetChange", + id: 2 + }, + documentChange: { + type: "DocumentChange", + id: 3 + }, + documentDelete: { + type: "DocumentDelete", + id: 4 + }, + documentRemove: { + type: "DocumentRemove", + id: 6 + }, + filter: { + type: "ExistenceFilter", + id: 5 + } + } + }, + Target: { + oneofs: { + targetType: { + oneof: [ + "query", + "documents" + ] + }, + resumeType: { + oneof: [ + "resumeToken", + "readTime" + ] + } + }, + fields: { + query: { + type: "QueryTarget", + id: 2 + }, + documents: { + type: "DocumentsTarget", + id: 3 + }, + resumeToken: { + type: "bytes", + id: 4 + }, + readTime: { + type: "google.protobuf.Timestamp", + id: 11 + }, + targetId: { + type: "int32", + id: 5 + }, + once: { + type: "bool", + id: 6 + }, + expectedCount: { + type: "google.protobuf.Int32Value", + id: 12 + } + }, + nested: { + DocumentsTarget: { + fields: { + documents: { + rule: "repeated", + type: "string", + id: 2 + } + } + }, + QueryTarget: { + oneofs: { + queryType: { + oneof: [ + "structuredQuery" + ] + } + }, + fields: { + parent: { + type: "string", + id: 1 + }, + structuredQuery: { + type: "StructuredQuery", + id: 2 + } + } + } + } + }, + TargetChange: { + fields: { + targetChangeType: { + type: "TargetChangeType", + id: 1 + }, + targetIds: { + rule: "repeated", + type: "int32", + id: 2 + }, + cause: { + type: "google.rpc.Status", + id: 3 + }, + resumeToken: { + type: "bytes", + id: 4 + }, + readTime: { + type: "google.protobuf.Timestamp", + id: 6 + } + }, + nested: { + TargetChangeType: { + values: { + NO_CHANGE: 0, + ADD: 1, + REMOVE: 2, + CURRENT: 3, + RESET: 4 + } + } + } + }, + ListCollectionIdsRequest: { + fields: { + parent: { + type: "string", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + pageSize: { + type: "int32", + id: 2 + }, + pageToken: { + type: "string", + id: 3 + } + } + }, + ListCollectionIdsResponse: { + fields: { + collectionIds: { + rule: "repeated", + type: "string", + id: 1 + }, + nextPageToken: { + type: "string", + id: 2 + } + } + }, + BatchWriteRequest: { + fields: { + database: { + type: "string", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + writes: { + rule: "repeated", + type: "Write", + id: 2 + }, + labels: { + keyType: "string", + type: "string", + id: 3 + } + } + }, + BatchWriteResponse: { + fields: { + writeResults: { + rule: "repeated", + type: "WriteResult", + id: 1 + }, + status: { + rule: "repeated", + type: "google.rpc.Status", + id: 2 + } + } + }, + StructuredQuery: { + fields: { + select: { + type: "Projection", + id: 1 + }, + from: { + rule: "repeated", + type: "CollectionSelector", + id: 2 + }, + where: { + type: "Filter", + id: 3 + }, + orderBy: { + rule: "repeated", + type: "Order", + id: 4 + }, + startAt: { + type: "Cursor", + id: 7 + }, + endAt: { + type: "Cursor", + id: 8 + }, + offset: { + type: "int32", + id: 6 + }, + limit: { + type: "google.protobuf.Int32Value", + id: 5 + } + }, + nested: { + CollectionSelector: { + fields: { + collectionId: { + type: "string", + id: 2 + }, + allDescendants: { + type: "bool", + id: 3 + } + } + }, + Filter: { + oneofs: { + filterType: { + oneof: [ + "compositeFilter", + "fieldFilter", + "unaryFilter" + ] + } + }, + fields: { + compositeFilter: { + type: "CompositeFilter", + id: 1 + }, + fieldFilter: { + type: "FieldFilter", + id: 2 + }, + unaryFilter: { + type: "UnaryFilter", + id: 3 + } + } + }, + CompositeFilter: { + fields: { + op: { + type: "Operator", + id: 1 + }, + filters: { + rule: "repeated", + type: "Filter", + id: 2 + } + }, + nested: { + Operator: { + values: { + OPERATOR_UNSPECIFIED: 0, + AND: 1, + OR: 2 + } + } + } + }, + FieldFilter: { + fields: { + field: { + type: "FieldReference", + id: 1 + }, + op: { + type: "Operator", + id: 2 + }, + value: { + type: "Value", + id: 3 + } + }, + nested: { + Operator: { + values: { + OPERATOR_UNSPECIFIED: 0, + LESS_THAN: 1, + LESS_THAN_OR_EQUAL: 2, + GREATER_THAN: 3, + GREATER_THAN_OR_EQUAL: 4, + EQUAL: 5, + NOT_EQUAL: 6, + ARRAY_CONTAINS: 7, + IN: 8, + ARRAY_CONTAINS_ANY: 9, + NOT_IN: 10 + } + } + } + }, + UnaryFilter: { + oneofs: { + operandType: { + oneof: [ + "field" + ] + } + }, + fields: { + op: { + type: "Operator", + id: 1 + }, + field: { + type: "FieldReference", + id: 2 + } + }, + nested: { + Operator: { + values: { + OPERATOR_UNSPECIFIED: 0, + IS_NAN: 2, + IS_NULL: 3, + IS_NOT_NAN: 4, + IS_NOT_NULL: 5 + } + } + } + }, + Order: { + fields: { + field: { + type: "FieldReference", + id: 1 + }, + direction: { + type: "Direction", + id: 2 + } + } + }, + FieldReference: { + fields: { + fieldPath: { + type: "string", + id: 2 + } + } + }, + Projection: { + fields: { + fields: { + rule: "repeated", + type: "FieldReference", + id: 2 + } + } + }, + Direction: { + values: { + DIRECTION_UNSPECIFIED: 0, + ASCENDING: 1, + DESCENDING: 2 + } + } + } + }, + StructuredAggregationQuery: { + oneofs: { + queryType: { + oneof: [ + "structuredQuery" + ] + } + }, + fields: { + structuredQuery: { + type: "StructuredQuery", + id: 1 + }, + aggregations: { + rule: "repeated", + type: "Aggregation", + id: 3 + } + }, + nested: { + Aggregation: { + oneofs: { + operator: { + oneof: [ + "count", + "sum", + "avg" + ] + } + }, + fields: { + count: { + type: "Count", + id: 1 + }, + sum: { + type: "Sum", + id: 2 + }, + avg: { + type: "Avg", + id: 3 + }, + alias: { + type: "string", + id: 7 + } + }, + nested: { + Count: { + fields: { + upTo: { + type: "google.protobuf.Int64Value", + id: 1 + } + } + }, + Sum: { + fields: { + field: { + type: "FieldReference", + id: 1 + } + } + }, + Avg: { + fields: { + field: { + type: "FieldReference", + id: 1 + } + } + } + } + } + } + }, + Cursor: { + fields: { + values: { + rule: "repeated", + type: "Value", + id: 1 + }, + before: { + type: "bool", + id: 2 + } + } + }, + Write: { + oneofs: { + operation: { + oneof: [ + "update", + "delete", + "verify", + "transform" + ] + } + }, + fields: { + update: { + type: "Document", + id: 1 + }, + "delete": { + type: "string", + id: 2 + }, + verify: { + type: "string", + id: 5 + }, + transform: { + type: "DocumentTransform", + id: 6 + }, + updateMask: { + type: "DocumentMask", + id: 3 + }, + updateTransforms: { + rule: "repeated", + type: "DocumentTransform.FieldTransform", + id: 7 + }, + currentDocument: { + type: "Precondition", + id: 4 + } + } + }, + DocumentTransform: { + fields: { + document: { + type: "string", + id: 1 + }, + fieldTransforms: { + rule: "repeated", + type: "FieldTransform", + id: 2 + } + }, + nested: { + FieldTransform: { + oneofs: { + transformType: { + oneof: [ + "setToServerValue", + "increment", + "maximum", + "minimum", + "appendMissingElements", + "removeAllFromArray" + ] + } + }, + fields: { + fieldPath: { + type: "string", + id: 1 + }, + setToServerValue: { + type: "ServerValue", + id: 2 + }, + increment: { + type: "Value", + id: 3 + }, + maximum: { + type: "Value", + id: 4 + }, + minimum: { + type: "Value", + id: 5 + }, + appendMissingElements: { + type: "ArrayValue", + id: 6 + }, + removeAllFromArray: { + type: "ArrayValue", + id: 7 + } + }, + nested: { + ServerValue: { + values: { + SERVER_VALUE_UNSPECIFIED: 0, + REQUEST_TIME: 1 + } + } + } + } + } + }, + WriteResult: { + fields: { + updateTime: { + type: "google.protobuf.Timestamp", + id: 1 + }, + transformResults: { + rule: "repeated", + type: "Value", + id: 2 + } + } + }, + DocumentChange: { + fields: { + document: { + type: "Document", + id: 1 + }, + targetIds: { + rule: "repeated", + type: "int32", + id: 5 + }, + removedTargetIds: { + rule: "repeated", + type: "int32", + id: 6 + } + } + }, + DocumentDelete: { + fields: { + document: { + type: "string", + id: 1 + }, + removedTargetIds: { + rule: "repeated", + type: "int32", + id: 6 + }, + readTime: { + type: "google.protobuf.Timestamp", + id: 4 + } + } + }, + DocumentRemove: { + fields: { + document: { + type: "string", + id: 1 + }, + removedTargetIds: { + rule: "repeated", + type: "int32", + id: 2 + }, + readTime: { + type: "google.protobuf.Timestamp", + id: 4 + } + } + }, + ExistenceFilter: { + fields: { + targetId: { + type: "int32", + id: 1 + }, + count: { + type: "int32", + id: 2 + }, + unchangedNames: { + type: "BloomFilter", + id: 3 + } + } + } + } + } + } + }, + api: { + options: { + go_package: "google.golang.org/genproto/googleapis/api/annotations;annotations", + java_multiple_files: true, + java_outer_classname: "HttpProto", + java_package: "com.google.api", + objc_class_prefix: "GAPI", + cc_enable_arenas: true + }, + nested: { + http: { + type: "HttpRule", + id: 72295728, + extend: "google.protobuf.MethodOptions" + }, + Http: { + fields: { + rules: { + rule: "repeated", + type: "HttpRule", + id: 1 + } + } + }, + HttpRule: { + oneofs: { + pattern: { + oneof: [ + "get", + "put", + "post", + "delete", + "patch", + "custom" + ] + } + }, + fields: { + get: { + type: "string", + id: 2 + }, + put: { + type: "string", + id: 3 + }, + post: { + type: "string", + id: 4 + }, + "delete": { + type: "string", + id: 5 + }, + patch: { + type: "string", + id: 6 + }, + custom: { + type: "CustomHttpPattern", + id: 8 + }, + selector: { + type: "string", + id: 1 + }, + body: { + type: "string", + id: 7 + }, + additionalBindings: { + rule: "repeated", + type: "HttpRule", + id: 11 + } + } + }, + CustomHttpPattern: { + fields: { + kind: { + type: "string", + id: 1 + }, + path: { + type: "string", + id: 2 + } + } + }, + methodSignature: { + rule: "repeated", + type: "string", + id: 1051, + extend: "google.protobuf.MethodOptions" + }, + defaultHost: { + type: "string", + id: 1049, + extend: "google.protobuf.ServiceOptions" + }, + oauthScopes: { + type: "string", + id: 1050, + extend: "google.protobuf.ServiceOptions" + }, + fieldBehavior: { + rule: "repeated", + type: "google.api.FieldBehavior", + id: 1052, + extend: "google.protobuf.FieldOptions" + }, + FieldBehavior: { + values: { + FIELD_BEHAVIOR_UNSPECIFIED: 0, + OPTIONAL: 1, + REQUIRED: 2, + OUTPUT_ONLY: 3, + INPUT_ONLY: 4, + IMMUTABLE: 5, + UNORDERED_LIST: 6, + NON_EMPTY_DEFAULT: 7 + } + } + } + }, + type: { + options: { + cc_enable_arenas: true, + go_package: "google.golang.org/genproto/googleapis/type/latlng;latlng", + java_multiple_files: true, + java_outer_classname: "LatLngProto", + java_package: "com.google.type", + objc_class_prefix: "GTP" + }, + nested: { + LatLng: { + fields: { + latitude: { + type: "double", + id: 1 + }, + longitude: { + type: "double", + id: 2 + } + } + } + } + }, + rpc: { + options: { + cc_enable_arenas: true, + go_package: "google.golang.org/genproto/googleapis/rpc/status;status", + java_multiple_files: true, + java_outer_classname: "StatusProto", + java_package: "com.google.rpc", + objc_class_prefix: "RPC" + }, + nested: { + Status: { + fields: { + code: { + type: "int32", + id: 1 + }, + message: { + type: "string", + id: 2 + }, + details: { + rule: "repeated", + type: "google.protobuf.Any", + id: 3 + } + } + } + } + } + } + } +}; +var protos = { + nested: nested +}; + +var protos$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + nested: nested, + 'default': protos +}); + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Used by tests so we can match @grpc/proto-loader behavior. */ +const protoLoaderOptions = { + longs: String, + enums: String, + defaults: true, + oneofs: false +}; +/** + * Loads the protocol buffer definitions for Firestore. + * + * @returns The GrpcObject representing our protos. + */ +function loadProtos() { + const packageDefinition = protoLoader__namespace.fromJSON(protos$1, protoLoaderOptions); + return grpc__namespace.loadPackageDefinition(packageDefinition); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Loads the GRPC stack */ +function newConnection(databaseInfo) { + const protos = loadProtos(); + return new GrpcConnection(protos, databaseInfo); +} +/** Return the Platform-specific connectivity monitor. */ +function newConnectivityMonitor() { + return new NoopConnectivityMonitor(); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** The Platform's 'window' implementation or null if not available. */ +function getWindow() { + if (process.env.USE_MOCK_PERSISTENCE === 'YES') { + // eslint-disable-next-line no-restricted-globals + return window; + } + return null; +} +/** The Platform's 'document' implementation or null if not available. */ +function getDocument() { + return null; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function newSerializer(databaseId) { + return new JsonProtoSerializer(databaseId, /* useProto3Json= */ false); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$8 = 'ExponentialBackoff'; +/** + * Initial backoff time in milliseconds after an error. + * Set to 1s according to https://cloud.google.com/apis/design/errors. + */ +const DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000; +const DEFAULT_BACKOFF_FACTOR = 1.5; +/** Maximum backoff time in milliseconds */ +const DEFAULT_BACKOFF_MAX_DELAY_MS = 60 * 1000; +/** + * A helper for running delayed tasks following an exponential backoff curve + * between attempts. + * + * Each delay is made up of a "base" delay which follows the exponential + * backoff curve, and a +/- 50% "jitter" that is calculated and added to the + * base delay. This prevents clients from accidentally synchronizing their + * delays causing spikes of load to the backend. + */ +class ExponentialBackoff { + constructor( + /** + * The AsyncQueue to run backoff operations on. + */ + queue, + /** + * The ID to use when scheduling backoff operations on the AsyncQueue. + */ + timerId, + /** + * The initial delay (used as the base delay on the first retry attempt). + * Note that jitter will still be applied, so the actual delay could be as + * little as 0.5*initialDelayMs. + */ + initialDelayMs = DEFAULT_BACKOFF_INITIAL_DELAY_MS, + /** + * The multiplier to use to determine the extended base delay after each + * attempt. + */ + backoffFactor = DEFAULT_BACKOFF_FACTOR, + /** + * The maximum base delay after which no further backoff is performed. + * Note that jitter will still be applied, so the actual delay could be as + * much as 1.5*maxDelayMs. + */ + maxDelayMs = DEFAULT_BACKOFF_MAX_DELAY_MS) { + this.queue = queue; + this.timerId = timerId; + this.initialDelayMs = initialDelayMs; + this.backoffFactor = backoffFactor; + this.maxDelayMs = maxDelayMs; + this.currentBaseMs = 0; + this.timerPromise = null; + /** The last backoff attempt, as epoch milliseconds. */ + this.lastAttemptTime = Date.now(); + this.reset(); + } + /** + * Resets the backoff delay. + * + * The very next backoffAndWait() will have no delay. If it is called again + * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and + * subsequent ones will increase according to the backoffFactor. + */ + reset() { + this.currentBaseMs = 0; + } + /** + * Resets the backoff delay to the maximum delay (e.g. for use after a + * RESOURCE_EXHAUSTED error). + */ + resetToMax() { + this.currentBaseMs = this.maxDelayMs; + } + /** + * Returns a promise that resolves after currentDelayMs, and increases the + * delay for any subsequent attempts. If there was a pending backoff operation + * already, it will be canceled. + */ + backoffAndRun(op) { + // Cancel any pending backoff operation. + this.cancel(); + // First schedule using the current base (which may be 0 and should be + // honored as such). + const desiredDelayWithJitterMs = Math.floor(this.currentBaseMs + this.jitterDelayMs()); + // Guard against lastAttemptTime being in the future due to a clock change. + const delaySoFarMs = Math.max(0, Date.now() - this.lastAttemptTime); + // Guard against the backoff delay already being past. + const remainingDelayMs = Math.max(0, desiredDelayWithJitterMs - delaySoFarMs); + if (remainingDelayMs > 0) { + logDebug(LOG_TAG$8, `Backing off for ${remainingDelayMs} ms ` + + `(base delay: ${this.currentBaseMs} ms, ` + + `delay with jitter: ${desiredDelayWithJitterMs} ms, ` + + `last attempt: ${delaySoFarMs} ms ago)`); + } + this.timerPromise = this.queue.enqueueAfterDelay(this.timerId, remainingDelayMs, () => { + this.lastAttemptTime = Date.now(); + return op(); + }); + // Apply backoff factor to determine next delay and ensure it is within + // bounds. + this.currentBaseMs *= this.backoffFactor; + if (this.currentBaseMs < this.initialDelayMs) { + this.currentBaseMs = this.initialDelayMs; + } + if (this.currentBaseMs > this.maxDelayMs) { + this.currentBaseMs = this.maxDelayMs; + } + } + skipBackoff() { + if (this.timerPromise !== null) { + this.timerPromise.skipDelay(); + this.timerPromise = null; + } + } + cancel() { + if (this.timerPromise !== null) { + this.timerPromise.cancel(); + this.timerPromise = null; + } + } + /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ + jitterDelayMs() { + return (Math.random() - 0.5) * this.currentBaseMs; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$7 = 'PersistentStream'; +/** The time a stream stays open after it is marked idle. */ +const IDLE_TIMEOUT_MS = 60 * 1000; +/** The time a stream stays open until we consider it healthy. */ +const HEALTHY_TIMEOUT_MS = 10 * 1000; +/** + * A PersistentStream is an abstract base class that represents a streaming RPC + * to the Firestore backend. It's built on top of the connections own support + * for streaming RPCs, and adds several critical features for our clients: + * + * - Exponential backoff on failure + * - Authentication via CredentialsProvider + * - Dispatching all callbacks into the shared worker queue + * - Closing idle streams after 60 seconds of inactivity + * + * Subclasses of PersistentStream implement serialization of models to and + * from the JSON representation of the protocol buffers for a specific + * streaming RPC. + * + * ## Starting and Stopping + * + * Streaming RPCs are stateful and need to be start()ed before messages can + * be sent and received. The PersistentStream will call the onOpen() function + * of the listener once the stream is ready to accept requests. + * + * Should a start() fail, PersistentStream will call the registered onClose() + * listener with a FirestoreError indicating what went wrong. + * + * A PersistentStream can be started and stopped repeatedly. + * + * Generic types: + * SendType: The type of the outgoing message of the underlying + * connection stream + * ReceiveType: The type of the incoming message of the underlying + * connection stream + * ListenerType: The type of the listener that will be used for callbacks + */ +class PersistentStream { + constructor(queue, connectionTimerId, idleTimerId, healthTimerId, connection, authCredentialsProvider, appCheckCredentialsProvider, listener) { + this.queue = queue; + this.idleTimerId = idleTimerId; + this.healthTimerId = healthTimerId; + this.connection = connection; + this.authCredentialsProvider = authCredentialsProvider; + this.appCheckCredentialsProvider = appCheckCredentialsProvider; + this.listener = listener; + this.state = 0 /* PersistentStreamState.Initial */; + /** + * A close count that's incremented every time the stream is closed; used by + * getCloseGuardedDispatcher() to invalidate callbacks that happen after + * close. + */ + this.closeCount = 0; + this.idleTimer = null; + this.healthCheck = null; + this.stream = null; + /** + * Count of response messages received. + */ + this.responseCount = 0; + this.backoff = new ExponentialBackoff(queue, connectionTimerId); + } + /** + * Returns true if start() has been called and no error has occurred. True + * indicates the stream is open or in the process of opening (which + * encompasses respecting backoff, getting auth tokens, and starting the + * actual RPC). Use isOpen() to determine if the stream is open and ready for + * outbound requests. + */ + isStarted() { + return (this.state === 1 /* PersistentStreamState.Starting */ || + this.state === 5 /* PersistentStreamState.Backoff */ || + this.isOpen()); + } + /** + * Returns true if the underlying RPC is open (the onOpen() listener has been + * called) and the stream is ready for outbound requests. + */ + isOpen() { + return (this.state === 2 /* PersistentStreamState.Open */ || + this.state === 3 /* PersistentStreamState.Healthy */); + } + /** + * Starts the RPC. Only allowed if isStarted() returns false. The stream is + * not immediately ready for use: onOpen() will be invoked when the RPC is + * ready for outbound requests, at which point isOpen() will return true. + * + * When start returns, isStarted() will return true. + */ + start() { + this.responseCount = 0; + if (this.state === 4 /* PersistentStreamState.Error */) { + this.performBackoff(); + return; + } + this.auth(); + } + /** + * Stops the RPC. This call is idempotent and allowed regardless of the + * current isStarted() state. + * + * When stop returns, isStarted() and isOpen() will both return false. + */ + async stop() { + if (this.isStarted()) { + await this.close(0 /* PersistentStreamState.Initial */); + } + } + /** + * After an error the stream will usually back off on the next attempt to + * start it. If the error warrants an immediate restart of the stream, the + * sender can use this to indicate that the receiver should not back off. + * + * Each error will call the onClose() listener. That function can decide to + * inhibit backoff if required. + */ + inhibitBackoff() { + this.state = 0 /* PersistentStreamState.Initial */; + this.backoff.reset(); + } + /** + * Marks this stream as idle. If no further actions are performed on the + * stream for one minute, the stream will automatically close itself and + * notify the stream's onClose() handler with Status.OK. The stream will then + * be in a !isStarted() state, requiring the caller to start the stream again + * before further use. + * + * Only streams that are in state 'Open' can be marked idle, as all other + * states imply pending network operations. + */ + markIdle() { + // Starts the idle time if we are in state 'Open' and are not yet already + // running a timer (in which case the previous idle timeout still applies). + if (this.isOpen() && this.idleTimer === null) { + this.idleTimer = this.queue.enqueueAfterDelay(this.idleTimerId, IDLE_TIMEOUT_MS, () => this.handleIdleCloseTimer()); + } + } + /** Sends a message to the underlying stream. */ + sendRequest(msg) { + this.cancelIdleCheck(); + this.stream.send(msg); + } + /** Called by the idle timer when the stream should close due to inactivity. */ + async handleIdleCloseTimer() { + if (this.isOpen()) { + // When timing out an idle stream there's no reason to force the stream into backoff when + // it restarts so set the stream state to Initial instead of Error. + return this.close(0 /* PersistentStreamState.Initial */); + } + } + /** Marks the stream as active again. */ + cancelIdleCheck() { + if (this.idleTimer) { + this.idleTimer.cancel(); + this.idleTimer = null; + } + } + /** Cancels the health check delayed operation. */ + cancelHealthCheck() { + if (this.healthCheck) { + this.healthCheck.cancel(); + this.healthCheck = null; + } + } + /** + * Closes the stream and cleans up as necessary: + * + * * closes the underlying GRPC stream; + * * calls the onClose handler with the given 'error'; + * * sets internal stream state to 'finalState'; + * * adjusts the backoff timer based on the error + * + * A new stream can be opened by calling start(). + * + * @param finalState - the intended state of the stream after closing. + * @param error - the error the connection was closed with. + */ + async close(finalState, error) { + // Cancel any outstanding timers (they're guaranteed not to execute). + this.cancelIdleCheck(); + this.cancelHealthCheck(); + this.backoff.cancel(); + // Invalidates any stream-related callbacks (e.g. from auth or the + // underlying stream), guaranteeing they won't execute. + this.closeCount++; + if (finalState !== 4 /* PersistentStreamState.Error */) { + // If this is an intentional close ensure we don't delay our next connection attempt. + this.backoff.reset(); + } + else if (error && error.code === Code.RESOURCE_EXHAUSTED) { + // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.) + logError(error.toString()); + logError('Using maximum backoff delay to prevent overloading the backend.'); + this.backoff.resetToMax(); + } + else if (error && + error.code === Code.UNAUTHENTICATED && + this.state !== 3 /* PersistentStreamState.Healthy */) { + // "unauthenticated" error means the token was rejected. This should rarely + // happen since both Auth and AppCheck ensure a sufficient TTL when we + // request a token. If a user manually resets their system clock this can + // fail, however. In this case, we should get a Code.UNAUTHENTICATED error + // before we received the first message and we need to invalidate the token + // to ensure that we fetch a new token. + this.authCredentialsProvider.invalidateToken(); + this.appCheckCredentialsProvider.invalidateToken(); + } + // Clean up the underlying stream because we are no longer interested in events. + if (this.stream !== null) { + this.tearDown(); + this.stream.close(); + this.stream = null; + } + // This state must be assigned before calling onClose() to allow the callback to + // inhibit backoff or otherwise manipulate the state in its non-started state. + this.state = finalState; + // Notify the listener that the stream closed. + await this.listener.onClose(error); + } + /** + * Can be overridden to perform additional cleanup before the stream is closed. + * Calling super.tearDown() is not required. + */ + tearDown() { } + auth() { + this.state = 1 /* PersistentStreamState.Starting */; + const dispatchIfNotClosed = this.getCloseGuardedDispatcher(this.closeCount); + // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below. + const closeCount = this.closeCount; + Promise.all([ + this.authCredentialsProvider.getToken(), + this.appCheckCredentialsProvider.getToken() + ]).then(([authToken, appCheckToken]) => { + // Stream can be stopped while waiting for authentication. + // TODO(mikelehen): We really should just use dispatchIfNotClosed + // and let this dispatch onto the queue, but that opened a spec test can + // of worms that I don't want to deal with in this PR. + if (this.closeCount === closeCount) { + // Normally we'd have to schedule the callback on the AsyncQueue. + // However, the following calls are safe to be called outside the + // AsyncQueue since they don't chain asynchronous calls + this.startStream(authToken, appCheckToken); + } + }, (error) => { + dispatchIfNotClosed(() => { + const rpcError = new FirestoreError(Code.UNKNOWN, 'Fetching auth token failed: ' + error.message); + return this.handleStreamClose(rpcError); + }); + }); + } + startStream(authToken, appCheckToken) { + const dispatchIfNotClosed = this.getCloseGuardedDispatcher(this.closeCount); + this.stream = this.startRpc(authToken, appCheckToken); + this.stream.onConnected(() => { + dispatchIfNotClosed(() => this.listener.onConnected()); + }); + this.stream.onOpen(() => { + dispatchIfNotClosed(() => { + this.state = 2 /* PersistentStreamState.Open */; + this.healthCheck = this.queue.enqueueAfterDelay(this.healthTimerId, HEALTHY_TIMEOUT_MS, () => { + if (this.isOpen()) { + this.state = 3 /* PersistentStreamState.Healthy */; + } + return Promise.resolve(); + }); + return this.listener.onOpen(); + }); + }); + this.stream.onClose((error) => { + dispatchIfNotClosed(() => { + return this.handleStreamClose(error); + }); + }); + this.stream.onMessage((msg) => { + dispatchIfNotClosed(() => { + if (++this.responseCount === 1) { + return this.onFirst(msg); + } + else { + return this.onNext(msg); + } + }); + }); + } + performBackoff() { + this.state = 5 /* PersistentStreamState.Backoff */; + this.backoff.backoffAndRun(async () => { + this.state = 0 /* PersistentStreamState.Initial */; + this.start(); + }); + } + // Visible for tests + handleStreamClose(error) { + logDebug(LOG_TAG$7, `close with error: ${error}`); + this.stream = null; + // In theory the stream could close cleanly, however, in our current model + // we never expect this to happen because if we stop a stream ourselves, + // this callback will never be called. To prevent cases where we retry + // without a backoff accidentally, we set the stream to error in all cases. + return this.close(4 /* PersistentStreamState.Error */, error); + } + /** + * Returns a "dispatcher" function that dispatches operations onto the + * AsyncQueue but only runs them if closeCount remains unchanged. This allows + * us to turn auth / stream callbacks into no-ops if the stream is closed / + * re-opened, etc. + */ + getCloseGuardedDispatcher(startCloseCount) { + return (fn) => { + this.queue.enqueueAndForget(() => { + if (this.closeCount === startCloseCount) { + return fn(); + } + else { + logDebug(LOG_TAG$7, 'stream callback skipped by getCloseGuardedDispatcher.'); + return Promise.resolve(); + } + }); + }; + } +} +/** + * A PersistentStream that implements the Listen RPC. + * + * Once the Listen stream has called the onOpen() listener, any number of + * listen() and unlisten() calls can be made to control what changes will be + * sent from the server for ListenResponses. + */ +class PersistentListenStream extends PersistentStream { + constructor(queue, connection, authCredentials, appCheckCredentials, serializer, listener) { + super(queue, "listen_stream_connection_backoff" /* TimerId.ListenStreamConnectionBackoff */, "listen_stream_idle" /* TimerId.ListenStreamIdle */, "health_check_timeout" /* TimerId.HealthCheckTimeout */, connection, authCredentials, appCheckCredentials, listener); + this.serializer = serializer; + } + startRpc(authToken, appCheckToken) { + return this.connection.openStream('Listen', authToken, appCheckToken); + } + onFirst(watchChangeProto) { + return this.onNext(watchChangeProto); + } + onNext(watchChangeProto) { + // A successful response means the stream is healthy + this.backoff.reset(); + const watchChange = fromWatchChange(this.serializer, watchChangeProto); + const snapshot = versionFromListenResponse(watchChangeProto); + return this.listener.onWatchChange(watchChange, snapshot); + } + /** + * Registers interest in the results of the given target. If the target + * includes a resumeToken it will be included in the request. Results that + * affect the target will be streamed back as WatchChange messages that + * reference the targetId. + */ + watch(targetData) { + const request = {}; + request.database = getEncodedDatabaseId(this.serializer); + request.addTarget = toTarget(this.serializer, targetData); + const labels = toListenRequestLabels(this.serializer, targetData); + if (labels) { + request.labels = labels; + } + this.sendRequest(request); + } + /** + * Unregisters interest in the results of the target associated with the + * given targetId. + */ + unwatch(targetId) { + const request = {}; + request.database = getEncodedDatabaseId(this.serializer); + request.removeTarget = targetId; + this.sendRequest(request); + } +} +/** + * A Stream that implements the Write RPC. + * + * The Write RPC requires the caller to maintain special streamToken + * state in between calls, to help the server understand which responses the + * client has processed by the time the next request is made. Every response + * will contain a streamToken; this value must be passed to the next + * request. + * + * After calling start() on this stream, the next request must be a handshake, + * containing whatever streamToken is on hand. Once a response to this + * request is received, all pending mutations may be submitted. When + * submitting multiple batches of mutations at the same time, it's + * okay to use the same streamToken for the calls to writeMutations. + * + * TODO(b/33271235): Use proto types + */ +class PersistentWriteStream extends PersistentStream { + constructor(queue, connection, authCredentials, appCheckCredentials, serializer, listener) { + super(queue, "write_stream_connection_backoff" /* TimerId.WriteStreamConnectionBackoff */, "write_stream_idle" /* TimerId.WriteStreamIdle */, "health_check_timeout" /* TimerId.HealthCheckTimeout */, connection, authCredentials, appCheckCredentials, listener); + this.serializer = serializer; + } + /** + * Tracks whether or not a handshake has been successfully exchanged and + * the stream is ready to accept mutations. + */ + get handshakeComplete() { + return this.responseCount > 0; + } + // Override of PersistentStream.start + start() { + this.lastStreamToken = undefined; + super.start(); + } + tearDown() { + if (this.handshakeComplete) { + this.writeMutations([]); + } + } + startRpc(authToken, appCheckToken) { + return this.connection.openStream('Write', authToken, appCheckToken); + } + onFirst(responseProto) { + // Always capture the last stream token. + hardAssert(!!responseProto.streamToken, 0x7a5a); + this.lastStreamToken = responseProto.streamToken; + // The first response is always the handshake response + hardAssert(!responseProto.writeResults || responseProto.writeResults.length === 0, 0xda08); + return this.listener.onHandshakeComplete(); + } + onNext(responseProto) { + // Always capture the last stream token. + hardAssert(!!responseProto.streamToken, 0x3186); + this.lastStreamToken = responseProto.streamToken; + // A successful first write response means the stream is healthy, + // Note, that we could consider a successful handshake healthy, however, + // the write itself might be causing an error we want to back off from. + this.backoff.reset(); + const results = fromWriteResults(responseProto.writeResults, responseProto.commitTime); + const commitVersion = fromVersion(responseProto.commitTime); + return this.listener.onMutationResult(commitVersion, results); + } + /** + * Sends an initial streamToken to the server, performing the handshake + * required to make the StreamingWrite RPC work. Subsequent + * calls should wait until onHandshakeComplete was called. + */ + writeHandshake() { + // TODO(dimond): Support stream resumption. We intentionally do not set the + // stream token on the handshake, ignoring any stream token we might have. + const request = {}; + request.database = getEncodedDatabaseId(this.serializer); + this.sendRequest(request); + } + /** Sends a group of mutations to the Firestore backend to apply. */ + writeMutations(mutations) { + const request = { + streamToken: this.lastStreamToken, + writes: mutations.map(mutation => toMutation(this.serializer, mutation)) + }; + this.sendRequest(request); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Datastore and its related methods are a wrapper around the external Google + * Cloud Datastore grpc API, which provides an interface that is more convenient + * for the rest of the client SDK architecture to consume. + */ +class Datastore { +} +/** + * An implementation of Datastore that exposes additional state for internal + * consumption. + */ +class DatastoreImpl extends Datastore { + constructor(authCredentials, appCheckCredentials, connection, serializer) { + super(); + this.authCredentials = authCredentials; + this.appCheckCredentials = appCheckCredentials; + this.connection = connection; + this.serializer = serializer; + this.terminated = false; + } + verifyInitialized() { + if (this.terminated) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'The client has already been terminated.'); + } + } + /** Invokes the provided RPC with auth and AppCheck tokens. */ + invokeRPC(rpcName, databaseId, resourcePath, request) { + this.verifyInitialized(); + return Promise.all([ + this.authCredentials.getToken(), + this.appCheckCredentials.getToken() + ]) + .then(([authToken, appCheckToken]) => { + return this.connection.invokeRPC(rpcName, toResourcePath(databaseId, resourcePath), request, authToken, appCheckToken); + }) + .catch((error) => { + if (error.name === 'FirebaseError') { + if (error.code === Code.UNAUTHENTICATED) { + this.authCredentials.invalidateToken(); + this.appCheckCredentials.invalidateToken(); + } + throw error; + } + else { + throw new FirestoreError(Code.UNKNOWN, error.toString()); + } + }); + } + /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ + invokeStreamingRPC(rpcName, databaseId, resourcePath, request, expectedResponseCount) { + this.verifyInitialized(); + return Promise.all([ + this.authCredentials.getToken(), + this.appCheckCredentials.getToken() + ]) + .then(([authToken, appCheckToken]) => { + return this.connection.invokeStreamingRPC(rpcName, toResourcePath(databaseId, resourcePath), request, authToken, appCheckToken, expectedResponseCount); + }) + .catch((error) => { + if (error.name === 'FirebaseError') { + if (error.code === Code.UNAUTHENTICATED) { + this.authCredentials.invalidateToken(); + this.appCheckCredentials.invalidateToken(); + } + throw error; + } + else { + throw new FirestoreError(Code.UNKNOWN, error.toString()); + } + }); + } + terminate() { + this.terminated = true; + this.connection.terminate(); + } +} +// TODO(firestorexp): Make sure there is only one Datastore instance per +// firestore-exp client. +function newDatastore(authCredentials, appCheckCredentials, connection, serializer) { + return new DatastoreImpl(authCredentials, appCheckCredentials, connection, serializer); +} +async function invokeCommitRpc(datastore, mutations) { + const datastoreImpl = debugCast(datastore); + const request = { + writes: mutations.map(m => toMutation(datastoreImpl.serializer, m)) + }; + await datastoreImpl.invokeRPC('Commit', datastoreImpl.serializer.databaseId, ResourcePath.emptyPath(), request); +} +async function invokeBatchGetDocumentsRpc(datastore, keys) { + const datastoreImpl = debugCast(datastore); + const request = { + documents: keys.map(k => toName(datastoreImpl.serializer, k)) + }; + const response = await datastoreImpl.invokeStreamingRPC('BatchGetDocuments', datastoreImpl.serializer.databaseId, ResourcePath.emptyPath(), request, keys.length); + const docs = new Map(); + response.forEach(proto => { + const doc = fromBatchGetDocumentsResponse(datastoreImpl.serializer, proto); + docs.set(doc.key.toString(), doc); + }); + const result = []; + keys.forEach(key => { + const doc = docs.get(key.toString()); + hardAssert(!!doc, 0xd7c2, { + key + }); + result.push(doc); + }); + return result; +} +async function invokeRunAggregationQueryRpc(datastore, query, aggregates) { + const datastoreImpl = debugCast(datastore); + const { request, aliasMap, parent } = toRunAggregationQueryRequest(datastoreImpl.serializer, queryToAggregateTarget(query), aggregates); + if (!datastoreImpl.connection.shouldResourcePathBeIncludedInRequest) { + delete request.parent; + } + const response = await datastoreImpl.invokeStreamingRPC('RunAggregationQuery', datastoreImpl.serializer.databaseId, parent, request, + /*expectedResponseCount=*/ 1); + // Omit RunAggregationQueryResponse that only contain readTimes. + const filteredResult = response.filter(proto => !!proto.result); + hardAssert(filteredResult.length === 1, 0xfcd7); + // Remap the short-form aliases that were sent to the server + // to the client-side aliases. Users will access the results + // using the client-side alias. + const unmappedAggregateFields = filteredResult[0].result?.aggregateFields; + const remappedFields = Object.keys(unmappedAggregateFields).reduce((accumulator, key) => { + accumulator[aliasMap[key]] = unmappedAggregateFields[key]; + return accumulator; + }, {}); + return remappedFields; +} +function newPersistentWriteStream(datastore, queue, listener) { + const datastoreImpl = debugCast(datastore); + datastoreImpl.verifyInitialized(); + return new PersistentWriteStream(queue, datastoreImpl.connection, datastoreImpl.authCredentials, datastoreImpl.appCheckCredentials, datastoreImpl.serializer, listener); +} +function newPersistentWatchStream(datastore, queue, listener) { + const datastoreImpl = debugCast(datastore); + datastoreImpl.verifyInitialized(); + return new PersistentListenStream(queue, datastoreImpl.connection, datastoreImpl.authCredentials, datastoreImpl.appCheckCredentials, datastoreImpl.serializer, listener); +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$6 = 'OnlineStateTracker'; +// To deal with transient failures, we allow multiple stream attempts before +// giving up and transitioning from OnlineState.Unknown to Offline. +// TODO(mikelehen): This used to be set to 2 as a mitigation for b/66228394. +// @jdimond thinks that bug is sufficiently fixed so that we can set this back +// to 1. If that works okay, we could potentially remove this logic entirely. +const MAX_WATCH_STREAM_FAILURES = 1; +// To deal with stream attempts that don't succeed or fail in a timely manner, +// we have a timeout for OnlineState to reach Online or Offline. +// If the timeout is reached, we transition to Offline rather than waiting +// indefinitely. +const ONLINE_STATE_TIMEOUT_MS = 10 * 1000; +/** + * A component used by the RemoteStore to track the OnlineState (that is, + * whether or not the client as a whole should be considered to be online or + * offline), implementing the appropriate heuristics. + * + * In particular, when the client is trying to connect to the backend, we + * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for + * a connection to succeed. If we have too many failures or the timeout elapses, + * then we set the OnlineState to Offline, and the client will behave as if + * it is offline (get()s will return cached data, etc.). + */ +class OnlineStateTracker { + constructor(asyncQueue, onlineStateHandler) { + this.asyncQueue = asyncQueue; + this.onlineStateHandler = onlineStateHandler; + /** The current OnlineState. */ + this.state = "Unknown" /* OnlineState.Unknown */; + /** + * A count of consecutive failures to open the stream. If it reaches the + * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to + * Offline. + */ + this.watchStreamFailures = 0; + /** + * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we + * transition from OnlineState.Unknown to OnlineState.Offline without waiting + * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times). + */ + this.onlineStateTimer = null; + /** + * Whether the client should log a warning message if it fails to connect to + * the backend (initially true, cleared after a successful stream, or if we've + * logged the message already). + */ + this.shouldWarnClientIsOffline = true; + } + /** + * Called by RemoteStore when a watch stream is started (including on each + * backoff attempt). + * + * If this is the first attempt, it sets the OnlineState to Unknown and starts + * the onlineStateTimer. + */ + handleWatchStreamStart() { + if (this.watchStreamFailures === 0) { + this.setAndBroadcast("Unknown" /* OnlineState.Unknown */); + this.onlineStateTimer = this.asyncQueue.enqueueAfterDelay("online_state_timeout" /* TimerId.OnlineStateTimeout */, ONLINE_STATE_TIMEOUT_MS, () => { + this.onlineStateTimer = null; + this.logClientOfflineWarningIfNecessary(`Backend didn't respond within ${ONLINE_STATE_TIMEOUT_MS / 1000} ` + + `seconds.`); + this.setAndBroadcast("Offline" /* OnlineState.Offline */); + // NOTE: handleWatchStreamFailure() will continue to increment + // watchStreamFailures even though we are already marked Offline, + // but this is non-harmful. + return Promise.resolve(); + }); + } + } + /** + * Updates our OnlineState as appropriate after the watch stream reports a + * failure. The first failure moves us to the 'Unknown' state. We then may + * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we + * actually transition to the 'Offline' state. + */ + handleWatchStreamFailure(error) { + if (this.state === "Online" /* OnlineState.Online */) { + this.setAndBroadcast("Unknown" /* OnlineState.Unknown */); + } + else { + this.watchStreamFailures++; + if (this.watchStreamFailures >= MAX_WATCH_STREAM_FAILURES) { + this.clearOnlineStateTimer(); + this.logClientOfflineWarningIfNecessary(`Connection failed ${MAX_WATCH_STREAM_FAILURES} ` + + `times. Most recent error: ${error.toString()}`); + this.setAndBroadcast("Offline" /* OnlineState.Offline */); + } + } + } + /** + * Explicitly sets the OnlineState to the specified state. + * + * Note that this resets our timers / failure counters, etc. used by our + * Offline heuristics, so must not be used in place of + * handleWatchStreamStart() and handleWatchStreamFailure(). + */ + set(newState) { + this.clearOnlineStateTimer(); + this.watchStreamFailures = 0; + if (newState === "Online" /* OnlineState.Online */) { + // We've connected to watch at least once. Don't warn the developer + // about being offline going forward. + this.shouldWarnClientIsOffline = false; + } + this.setAndBroadcast(newState); + } + setAndBroadcast(newState) { + if (newState !== this.state) { + this.state = newState; + this.onlineStateHandler(newState); + } + } + logClientOfflineWarningIfNecessary(details) { + const message = `Could not reach Cloud Firestore backend. ${details}\n` + + `This typically indicates that your device does not have a healthy ` + + `Internet connection at the moment. The client will operate in offline ` + + `mode until it is able to successfully connect to the backend.`; + if (this.shouldWarnClientIsOffline) { + logError(message); + this.shouldWarnClientIsOffline = false; + } + else { + logDebug(LOG_TAG$6, message); + } + } + clearOnlineStateTimer() { + if (this.onlineStateTimer !== null) { + this.onlineStateTimer.cancel(); + this.onlineStateTimer = null; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$5 = 'RemoteStore'; +// TODO(b/35853402): Negotiate this with the stream. +const MAX_PENDING_WRITES = 10; +class RemoteStoreImpl { + constructor( + /** + * The local store, used to fill the write pipeline with outbound mutations. + */ + localStore, + /** The client-side proxy for interacting with the backend. */ + datastore, asyncQueue, onlineStateHandler, connectivityMonitor) { + this.localStore = localStore; + this.datastore = datastore; + this.asyncQueue = asyncQueue; + this.remoteSyncer = {}; + /** + * A list of up to MAX_PENDING_WRITES writes that we have fetched from the + * LocalStore via fillWritePipeline() and have or will send to the write + * stream. + * + * Whenever writePipeline.length > 0 the RemoteStore will attempt to start or + * restart the write stream. When the stream is established the writes in the + * pipeline will be sent in order. + * + * Writes remain in writePipeline until they are acknowledged by the backend + * and thus will automatically be re-sent if the stream is interrupted / + * restarted before they're acknowledged. + * + * Write responses from the backend are linked to their originating request + * purely based on order, and so we can just shift() writes from the front of + * the writePipeline as we receive responses. + */ + this.writePipeline = []; + /** + * A mapping of watched targets that the client cares about tracking and the + * user has explicitly called a 'listen' for this target. + * + * These targets may or may not have been sent to or acknowledged by the + * server. On re-establishing the listen stream, these targets should be sent + * to the server. The targets removed with unlistens are removed eagerly + * without waiting for confirmation from the listen stream. + */ + this.listenTargets = new Map(); + /** + * A set of reasons for why the RemoteStore may be offline. If empty, the + * RemoteStore may start its network connections. + */ + this.offlineCauses = new Set(); + /** + * Event handlers that get called when the network is disabled or enabled. + * + * PORTING NOTE: These functions are used on the Web client to create the + * underlying streams (to support tree-shakeable streams). On Android and iOS, + * the streams are created during construction of RemoteStore. + */ + this.onNetworkStatusChange = []; + this.connectivityMonitor = connectivityMonitor; + this.connectivityMonitor.addCallback((_) => { + asyncQueue.enqueueAndForget(async () => { + // Porting Note: Unlike iOS, `restartNetwork()` is called even when the + // network becomes unreachable as we don't have any other way to tear + // down our streams. + if (canUseNetwork(this)) { + logDebug(LOG_TAG$5, 'Restarting streams for network reachability change.'); + await restartNetwork(this); + } + }); + }); + this.onlineStateTracker = new OnlineStateTracker(asyncQueue, onlineStateHandler); + } +} +function newRemoteStore(localStore, datastore, asyncQueue, onlineStateHandler, connectivityMonitor) { + return new RemoteStoreImpl(localStore, datastore, asyncQueue, onlineStateHandler, connectivityMonitor); +} +/** Re-enables the network. Idempotent. */ +function remoteStoreEnableNetwork(remoteStore) { + const remoteStoreImpl = debugCast(remoteStore); + remoteStoreImpl.offlineCauses.delete(0 /* OfflineCause.UserDisabled */); + return enableNetworkInternal(remoteStoreImpl); +} +async function enableNetworkInternal(remoteStoreImpl) { + if (canUseNetwork(remoteStoreImpl)) { + for (const networkStatusHandler of remoteStoreImpl.onNetworkStatusChange) { + await networkStatusHandler(/* enabled= */ true); + } + } +} +/** + * Temporarily disables the network. The network can be re-enabled using + * enableNetwork(). + */ +async function remoteStoreDisableNetwork(remoteStore) { + const remoteStoreImpl = debugCast(remoteStore); + remoteStoreImpl.offlineCauses.add(0 /* OfflineCause.UserDisabled */); + await disableNetworkInternal(remoteStoreImpl); + // Set the OnlineState to Offline so get()s return from cache, etc. + remoteStoreImpl.onlineStateTracker.set("Offline" /* OnlineState.Offline */); +} +async function disableNetworkInternal(remoteStoreImpl) { + for (const networkStatusHandler of remoteStoreImpl.onNetworkStatusChange) { + await networkStatusHandler(/* enabled= */ false); + } +} +async function remoteStoreShutdown(remoteStore) { + const remoteStoreImpl = debugCast(remoteStore); + logDebug(LOG_TAG$5, 'RemoteStore shutting down.'); + remoteStoreImpl.offlineCauses.add(5 /* OfflineCause.Shutdown */); + await disableNetworkInternal(remoteStoreImpl); + remoteStoreImpl.connectivityMonitor.shutdown(); + // Set the OnlineState to Unknown (rather than Offline) to avoid potentially + // triggering spurious listener events with cached data, etc. + remoteStoreImpl.onlineStateTracker.set("Unknown" /* OnlineState.Unknown */); +} +/** + * Starts new listen for the given target. Uses resume token if provided. It + * is a no-op if the target of given `TargetData` is already being listened to. + */ +function remoteStoreListen(remoteStore, targetData) { + const remoteStoreImpl = debugCast(remoteStore); + if (remoteStoreImpl.listenTargets.has(targetData.targetId)) { + return; + } + // Mark this as something the client is currently listening for. + remoteStoreImpl.listenTargets.set(targetData.targetId, targetData); + if (shouldStartWatchStream(remoteStoreImpl)) { + // The listen will be sent in onWatchStreamOpen + startWatchStream(remoteStoreImpl); + } + else if (ensureWatchStream(remoteStoreImpl).isOpen()) { + sendWatchRequest(remoteStoreImpl, targetData); + } +} +/** + * Removes the listen from server. It is a no-op if the given target id is + * not being listened to. + */ +function remoteStoreUnlisten(remoteStore, targetId) { + const remoteStoreImpl = debugCast(remoteStore); + const watchStream = ensureWatchStream(remoteStoreImpl); + remoteStoreImpl.listenTargets.delete(targetId); + if (watchStream.isOpen()) { + sendUnwatchRequest(remoteStoreImpl, targetId); + } + if (remoteStoreImpl.listenTargets.size === 0) { + if (watchStream.isOpen()) { + watchStream.markIdle(); + } + else if (canUseNetwork(remoteStoreImpl)) { + // Revert to OnlineState.Unknown if the watch stream is not open and we + // have no listeners, since without any listens to send we cannot + // confirm if the stream is healthy and upgrade to OnlineState.Online. + remoteStoreImpl.onlineStateTracker.set("Unknown" /* OnlineState.Unknown */); + } + } +} +/** + * We need to increment the expected number of pending responses we're due + * from watch so we wait for the ack to process any messages from this target. + */ +function sendWatchRequest(remoteStoreImpl, targetData) { + remoteStoreImpl.watchChangeAggregator.recordPendingTargetRequest(targetData.targetId); + if (targetData.resumeToken.approximateByteSize() > 0 || + targetData.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) { + const expectedCount = remoteStoreImpl.remoteSyncer.getRemoteKeysForTarget(targetData.targetId).size; + targetData = targetData.withExpectedCount(expectedCount); + } + ensureWatchStream(remoteStoreImpl).watch(targetData); +} +/** + * We need to increment the expected number of pending responses we're due + * from watch so we wait for the removal on the server before we process any + * messages from this target. + */ +function sendUnwatchRequest(remoteStoreImpl, targetId) { + remoteStoreImpl.watchChangeAggregator.recordPendingTargetRequest(targetId); + ensureWatchStream(remoteStoreImpl).unwatch(targetId); +} +function startWatchStream(remoteStoreImpl) { + remoteStoreImpl.watchChangeAggregator = new WatchChangeAggregator({ + getRemoteKeysForTarget: targetId => remoteStoreImpl.remoteSyncer.getRemoteKeysForTarget(targetId), + getTargetDataForTarget: targetId => remoteStoreImpl.listenTargets.get(targetId) || null, + getDatabaseId: () => remoteStoreImpl.datastore.serializer.databaseId + }); + ensureWatchStream(remoteStoreImpl).start(); + remoteStoreImpl.onlineStateTracker.handleWatchStreamStart(); +} +/** + * Returns whether the watch stream should be started because it's necessary + * and has not yet been started. + */ +function shouldStartWatchStream(remoteStoreImpl) { + return (canUseNetwork(remoteStoreImpl) && + !ensureWatchStream(remoteStoreImpl).isStarted() && + remoteStoreImpl.listenTargets.size > 0); +} +function canUseNetwork(remoteStore) { + const remoteStoreImpl = debugCast(remoteStore); + return remoteStoreImpl.offlineCauses.size === 0; +} +function cleanUpWatchStreamState(remoteStoreImpl) { + remoteStoreImpl.watchChangeAggregator = undefined; +} +async function onWatchStreamConnected(remoteStoreImpl) { + // Mark the client as online since we got a "connected" notification. + remoteStoreImpl.onlineStateTracker.set("Online" /* OnlineState.Online */); +} +async function onWatchStreamOpen(remoteStoreImpl) { + remoteStoreImpl.listenTargets.forEach((targetData, targetId) => { + sendWatchRequest(remoteStoreImpl, targetData); + }); +} +async function onWatchStreamClose(remoteStoreImpl, error) { + cleanUpWatchStreamState(remoteStoreImpl); + // If we still need the watch stream, retry the connection. + if (shouldStartWatchStream(remoteStoreImpl)) { + remoteStoreImpl.onlineStateTracker.handleWatchStreamFailure(error); + startWatchStream(remoteStoreImpl); + } + else { + // No need to restart watch stream because there are no active targets. + // The online state is set to unknown because there is no active attempt + // at establishing a connection + remoteStoreImpl.onlineStateTracker.set("Unknown" /* OnlineState.Unknown */); + } +} +async function onWatchStreamChange(remoteStoreImpl, watchChange, snapshotVersion) { + // Mark the client as online since we got a message from the server + remoteStoreImpl.onlineStateTracker.set("Online" /* OnlineState.Online */); + if (watchChange instanceof WatchTargetChange && + watchChange.state === 2 /* WatchTargetChangeState.Removed */ && + watchChange.cause) { + // There was an error on a target, don't wait for a consistent snapshot + // to raise events + try { + await handleTargetError(remoteStoreImpl, watchChange); + } + catch (e) { + logDebug(LOG_TAG$5, 'Failed to remove targets %s: %s ', watchChange.targetIds.join(','), e); + await disableNetworkUntilRecovery(remoteStoreImpl, e); + } + return; + } + if (watchChange instanceof DocumentWatchChange) { + remoteStoreImpl.watchChangeAggregator.handleDocumentChange(watchChange); + } + else if (watchChange instanceof ExistenceFilterChange) { + remoteStoreImpl.watchChangeAggregator.handleExistenceFilter(watchChange); + } + else { + remoteStoreImpl.watchChangeAggregator.handleTargetChange(watchChange); + } + if (!snapshotVersion.isEqual(SnapshotVersion.min())) { + try { + const lastRemoteSnapshotVersion = await localStoreGetLastRemoteSnapshotVersion(remoteStoreImpl.localStore); + if (snapshotVersion.compareTo(lastRemoteSnapshotVersion) >= 0) { + // We have received a target change with a global snapshot if the snapshot + // version is not equal to SnapshotVersion.min(). + await raiseWatchSnapshot(remoteStoreImpl, snapshotVersion); + } + } + catch (e) { + logDebug(LOG_TAG$5, 'Failed to raise snapshot:', e); + await disableNetworkUntilRecovery(remoteStoreImpl, e); + } + } +} +/** + * Recovery logic for IndexedDB errors that takes the network offline until + * `op` succeeds. Retries are scheduled with backoff using + * `enqueueRetryable()`. If `op()` is not provided, IndexedDB access is + * validated via a generic operation. + * + * The returned Promise is resolved once the network is disabled and before + * any retry attempt. + */ +async function disableNetworkUntilRecovery(remoteStoreImpl, e, op) { + if (isIndexedDbTransactionError(e)) { + remoteStoreImpl.offlineCauses.add(1 /* OfflineCause.IndexedDbFailed */); + // Disable network and raise offline snapshots + await disableNetworkInternal(remoteStoreImpl); + remoteStoreImpl.onlineStateTracker.set("Offline" /* OnlineState.Offline */); + if (!op) { + // Use a simple read operation to determine if IndexedDB recovered. + // Ideally, we would expose a health check directly on SimpleDb, but + // RemoteStore only has access to persistence through LocalStore. + op = () => localStoreGetLastRemoteSnapshotVersion(remoteStoreImpl.localStore); + } + // Probe IndexedDB periodically and re-enable network + remoteStoreImpl.asyncQueue.enqueueRetryable(async () => { + logDebug(LOG_TAG$5, 'Retrying IndexedDB access'); + await op(); + remoteStoreImpl.offlineCauses.delete(1 /* OfflineCause.IndexedDbFailed */); + await enableNetworkInternal(remoteStoreImpl); + }); + } + else { + throw e; + } +} +/** + * Executes `op`. If `op` fails, takes the network offline until `op` + * succeeds. Returns after the first attempt. + */ +function executeWithRecovery(remoteStoreImpl, op) { + return op().catch(e => disableNetworkUntilRecovery(remoteStoreImpl, e, op)); +} +/** + * Takes a batch of changes from the Datastore, repackages them as a + * RemoteEvent, and passes that on to the listener, which is typically the + * SyncEngine. + */ +function raiseWatchSnapshot(remoteStoreImpl, snapshotVersion) { + const remoteEvent = remoteStoreImpl.watchChangeAggregator.createRemoteEvent(snapshotVersion); + // Update in-memory resume tokens. LocalStore will update the + // persistent view of these when applying the completed RemoteEvent. + remoteEvent.targetChanges.forEach((change, targetId) => { + if (change.resumeToken.approximateByteSize() > 0) { + const targetData = remoteStoreImpl.listenTargets.get(targetId); + // A watched target might have been removed already. + if (targetData) { + remoteStoreImpl.listenTargets.set(targetId, targetData.withResumeToken(change.resumeToken, snapshotVersion)); + } + } + }); + // Re-establish listens for the targets that have been invalidated by + // existence filter mismatches. + remoteEvent.targetMismatches.forEach((targetId, targetPurpose) => { + const targetData = remoteStoreImpl.listenTargets.get(targetId); + if (!targetData) { + // A watched target might have been removed already. + return; + } + // Clear the resume token for the target, since we're in a known mismatch + // state. + remoteStoreImpl.listenTargets.set(targetId, targetData.withResumeToken(ByteString.EMPTY_BYTE_STRING, targetData.snapshotVersion)); + // Cause a hard reset by unwatching and rewatching immediately, but + // deliberately don't send a resume token so that we get a full update. + sendUnwatchRequest(remoteStoreImpl, targetId); + // Mark the target we send as being on behalf of an existence filter + // mismatch, but don't actually retain that in listenTargets. This ensures + // that we flag the first re-listen this way without impacting future + // listens of this target (that might happen e.g. on reconnect). + const requestTargetData = new TargetData(targetData.target, targetId, targetPurpose, targetData.sequenceNumber); + sendWatchRequest(remoteStoreImpl, requestTargetData); + }); + return remoteStoreImpl.remoteSyncer.applyRemoteEvent(remoteEvent); +} +/** Handles an error on a target */ +async function handleTargetError(remoteStoreImpl, watchChange) { + const error = watchChange.cause; + for (const targetId of watchChange.targetIds) { + // A watched target might have been removed already. + if (remoteStoreImpl.listenTargets.has(targetId)) { + await remoteStoreImpl.remoteSyncer.rejectListen(targetId, error); + remoteStoreImpl.listenTargets.delete(targetId); + remoteStoreImpl.watchChangeAggregator.removeTarget(targetId); + } + } +} +/** + * Attempts to fill our write pipeline with writes from the LocalStore. + * + * Called internally to bootstrap or refill the write pipeline and by + * SyncEngine whenever there are new mutations to process. + * + * Starts the write stream if necessary. + */ +async function fillWritePipeline(remoteStore) { + const remoteStoreImpl = debugCast(remoteStore); + const writeStream = ensureWriteStream(remoteStoreImpl); + let lastBatchIdRetrieved = remoteStoreImpl.writePipeline.length > 0 + ? remoteStoreImpl.writePipeline[remoteStoreImpl.writePipeline.length - 1] + .batchId + : BATCHID_UNKNOWN; + while (canAddToWritePipeline(remoteStoreImpl)) { + try { + const batch = await localStoreGetNextMutationBatch(remoteStoreImpl.localStore, lastBatchIdRetrieved); + if (batch === null) { + if (remoteStoreImpl.writePipeline.length === 0) { + writeStream.markIdle(); + } + break; + } + else { + lastBatchIdRetrieved = batch.batchId; + addToWritePipeline(remoteStoreImpl, batch); + } + } + catch (e) { + await disableNetworkUntilRecovery(remoteStoreImpl, e); + } + } + if (shouldStartWriteStream(remoteStoreImpl)) { + startWriteStream(remoteStoreImpl); + } +} +/** + * Returns true if we can add to the write pipeline (i.e. the network is + * enabled and the write pipeline is not full). + */ +function canAddToWritePipeline(remoteStoreImpl) { + return (canUseNetwork(remoteStoreImpl) && + remoteStoreImpl.writePipeline.length < MAX_PENDING_WRITES); +} +/** + * Queues additional writes to be sent to the write stream, sending them + * immediately if the write stream is established. + */ +function addToWritePipeline(remoteStoreImpl, batch) { + remoteStoreImpl.writePipeline.push(batch); + const writeStream = ensureWriteStream(remoteStoreImpl); + if (writeStream.isOpen() && writeStream.handshakeComplete) { + writeStream.writeMutations(batch.mutations); + } +} +function shouldStartWriteStream(remoteStoreImpl) { + return (canUseNetwork(remoteStoreImpl) && + !ensureWriteStream(remoteStoreImpl).isStarted() && + remoteStoreImpl.writePipeline.length > 0); +} +function startWriteStream(remoteStoreImpl) { + ensureWriteStream(remoteStoreImpl).start(); +} +async function onWriteStreamOpen(remoteStoreImpl) { + ensureWriteStream(remoteStoreImpl).writeHandshake(); +} +async function onWriteHandshakeComplete(remoteStoreImpl) { + const writeStream = ensureWriteStream(remoteStoreImpl); + // Send the write pipeline now that the stream is established. + for (const batch of remoteStoreImpl.writePipeline) { + writeStream.writeMutations(batch.mutations); + } +} +async function onMutationResult(remoteStoreImpl, commitVersion, results) { + const batch = remoteStoreImpl.writePipeline.shift(); + const success = MutationBatchResult.from(batch, commitVersion, results); + await executeWithRecovery(remoteStoreImpl, () => remoteStoreImpl.remoteSyncer.applySuccessfulWrite(success)); + // It's possible that with the completion of this mutation another + // slot has freed up. + await fillWritePipeline(remoteStoreImpl); +} +async function onWriteStreamClose(remoteStoreImpl, error) { + // If the write stream closed after the write handshake completes, a write + // operation failed and we fail the pending operation. + if (error && ensureWriteStream(remoteStoreImpl).handshakeComplete) { + // This error affects the actual write. + await handleWriteError(remoteStoreImpl, error); + } + // The write stream might have been started by refilling the write + // pipeline for failed writes + if (shouldStartWriteStream(remoteStoreImpl)) { + startWriteStream(remoteStoreImpl); + } +} +async function handleWriteError(remoteStoreImpl, error) { + // Only handle permanent errors here. If it's transient, just let the retry + // logic kick in. + if (isPermanentWriteError(error.code)) { + // This was a permanent error, the request itself was the problem + // so it's not going to succeed if we resend it. + const batch = remoteStoreImpl.writePipeline.shift(); + // In this case it's also unlikely that the server itself is melting + // down -- this was just a bad request so inhibit backoff on the next + // restart. + ensureWriteStream(remoteStoreImpl).inhibitBackoff(); + await executeWithRecovery(remoteStoreImpl, () => remoteStoreImpl.remoteSyncer.rejectFailedWrite(batch.batchId, error)); + // It's possible that with the completion of this mutation + // another slot has freed up. + await fillWritePipeline(remoteStoreImpl); + } +} +async function restartNetwork(remoteStore) { + const remoteStoreImpl = debugCast(remoteStore); + remoteStoreImpl.offlineCauses.add(4 /* OfflineCause.ConnectivityChange */); + await disableNetworkInternal(remoteStoreImpl); + remoteStoreImpl.onlineStateTracker.set("Unknown" /* OnlineState.Unknown */); + remoteStoreImpl.offlineCauses.delete(4 /* OfflineCause.ConnectivityChange */); + await enableNetworkInternal(remoteStoreImpl); +} +async function remoteStoreHandleCredentialChange(remoteStore, user) { + const remoteStoreImpl = debugCast(remoteStore); + remoteStoreImpl.asyncQueue.verifyOperationInProgress(); + logDebug(LOG_TAG$5, 'RemoteStore received new credentials'); + const usesNetwork = canUseNetwork(remoteStoreImpl); + // Tear down and re-create our network streams. This will ensure we get a + // fresh auth token for the new user and re-fill the write pipeline with + // new mutations from the LocalStore (since mutations are per-user). + remoteStoreImpl.offlineCauses.add(3 /* OfflineCause.CredentialChange */); + await disableNetworkInternal(remoteStoreImpl); + if (usesNetwork) { + // Don't set the network status to Unknown if we are offline. + remoteStoreImpl.onlineStateTracker.set("Unknown" /* OnlineState.Unknown */); + } + await remoteStoreImpl.remoteSyncer.handleCredentialChange(user); + remoteStoreImpl.offlineCauses.delete(3 /* OfflineCause.CredentialChange */); + await enableNetworkInternal(remoteStoreImpl); +} +/** + * Toggles the network state when the client gains or loses its primary lease. + */ +async function remoteStoreApplyPrimaryState(remoteStore, isPrimary) { + const remoteStoreImpl = debugCast(remoteStore); + if (isPrimary) { + remoteStoreImpl.offlineCauses.delete(2 /* OfflineCause.IsSecondary */); + await enableNetworkInternal(remoteStoreImpl); + } + else if (!isPrimary) { + remoteStoreImpl.offlineCauses.add(2 /* OfflineCause.IsSecondary */); + await disableNetworkInternal(remoteStoreImpl); + remoteStoreImpl.onlineStateTracker.set("Unknown" /* OnlineState.Unknown */); + } +} +/** + * If not yet initialized, registers the WatchStream and its network state + * callback with `remoteStoreImpl`. Returns the existing stream if one is + * already available. + * + * PORTING NOTE: On iOS and Android, the WatchStream gets registered on startup. + * This is not done on Web to allow it to be tree-shaken. + */ +function ensureWatchStream(remoteStoreImpl) { + if (!remoteStoreImpl.watchStream) { + // Create stream (but note that it is not started yet). + remoteStoreImpl.watchStream = newPersistentWatchStream(remoteStoreImpl.datastore, remoteStoreImpl.asyncQueue, { + onConnected: onWatchStreamConnected.bind(null, remoteStoreImpl), + onOpen: onWatchStreamOpen.bind(null, remoteStoreImpl), + onClose: onWatchStreamClose.bind(null, remoteStoreImpl), + onWatchChange: onWatchStreamChange.bind(null, remoteStoreImpl) + }); + remoteStoreImpl.onNetworkStatusChange.push(async (enabled) => { + if (enabled) { + remoteStoreImpl.watchStream.inhibitBackoff(); + if (shouldStartWatchStream(remoteStoreImpl)) { + startWatchStream(remoteStoreImpl); + } + else { + remoteStoreImpl.onlineStateTracker.set("Unknown" /* OnlineState.Unknown */); + } + } + else { + await remoteStoreImpl.watchStream.stop(); + cleanUpWatchStreamState(remoteStoreImpl); + } + }); + } + return remoteStoreImpl.watchStream; +} +/** + * If not yet initialized, registers the WriteStream and its network state + * callback with `remoteStoreImpl`. Returns the existing stream if one is + * already available. + * + * PORTING NOTE: On iOS and Android, the WriteStream gets registered on startup. + * This is not done on Web to allow it to be tree-shaken. + */ +function ensureWriteStream(remoteStoreImpl) { + if (!remoteStoreImpl.writeStream) { + // Create stream (but note that it is not started yet). + remoteStoreImpl.writeStream = newPersistentWriteStream(remoteStoreImpl.datastore, remoteStoreImpl.asyncQueue, { + onConnected: () => Promise.resolve(), + onOpen: onWriteStreamOpen.bind(null, remoteStoreImpl), + onClose: onWriteStreamClose.bind(null, remoteStoreImpl), + onHandshakeComplete: onWriteHandshakeComplete.bind(null, remoteStoreImpl), + onMutationResult: onMutationResult.bind(null, remoteStoreImpl) + }); + remoteStoreImpl.onNetworkStatusChange.push(async (enabled) => { + if (enabled) { + remoteStoreImpl.writeStream.inhibitBackoff(); + // This will start the write stream if necessary. + await fillWritePipeline(remoteStoreImpl); + } + else { + await remoteStoreImpl.writeStream.stop(); + if (remoteStoreImpl.writePipeline.length > 0) { + logDebug(LOG_TAG$5, `Stopping write stream with ${remoteStoreImpl.writePipeline.length} pending writes`); + remoteStoreImpl.writePipeline = []; + } + } + }); + } + return remoteStoreImpl.writeStream; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$4 = 'AsyncQueue'; +/** + * Represents an operation scheduled to be run in the future on an AsyncQueue. + * + * It is created via DelayedOperation.createAndSchedule(). + * + * Supports cancellation (via cancel()) and early execution (via skipDelay()). + * + * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type + * in newer versions of TypeScript defines `finally`, which is not available in + * IE. + */ +class DelayedOperation { + constructor(asyncQueue, timerId, targetTimeMs, op, removalCallback) { + this.asyncQueue = asyncQueue; + this.timerId = timerId; + this.targetTimeMs = targetTimeMs; + this.op = op; + this.removalCallback = removalCallback; + this.deferred = new Deferred(); + this.then = this.deferred.promise.then.bind(this.deferred.promise); + // It's normal for the deferred promise to be canceled (due to cancellation) + // and so we attach a dummy catch callback to avoid + // 'UnhandledPromiseRejectionWarning' log spam. + this.deferred.promise.catch(err => { }); + } + get promise() { + return this.deferred.promise; + } + /** + * Creates and returns a DelayedOperation that has been scheduled to be + * executed on the provided asyncQueue after the provided delayMs. + * + * @param asyncQueue - The queue to schedule the operation on. + * @param id - A Timer ID identifying the type of operation this is. + * @param delayMs - The delay (ms) before the operation should be scheduled. + * @param op - The operation to run. + * @param removalCallback - A callback to be called synchronously once the + * operation is executed or canceled, notifying the AsyncQueue to remove it + * from its delayedOperations list. + * PORTING NOTE: This exists to prevent making removeDelayedOperation() and + * the DelayedOperation class public. + */ + static createAndSchedule(asyncQueue, timerId, delayMs, op, removalCallback) { + const targetTime = Date.now() + delayMs; + const delayedOp = new DelayedOperation(asyncQueue, timerId, targetTime, op, removalCallback); + delayedOp.start(delayMs); + return delayedOp; + } + /** + * Starts the timer. This is called immediately after construction by + * createAndSchedule(). + */ + start(delayMs) { + this.timerHandle = setTimeout(() => this.handleDelayElapsed(), delayMs); + } + /** + * Queues the operation to run immediately (if it hasn't already been run or + * canceled). + */ + skipDelay() { + return this.handleDelayElapsed(); + } + /** + * Cancels the operation if it hasn't already been executed or canceled. The + * promise will be rejected. + * + * As long as the operation has not yet been run, calling cancel() provides a + * guarantee that the operation will not be run. + */ + cancel(reason) { + if (this.timerHandle !== null) { + this.clearTimeout(); + this.deferred.reject(new FirestoreError(Code.CANCELLED, 'Operation cancelled' + (reason ? ': ' + reason : ''))); + } + } + handleDelayElapsed() { + this.asyncQueue.enqueueAndForget(() => { + if (this.timerHandle !== null) { + this.clearTimeout(); + return this.op().then(result => { + return this.deferred.resolve(result); + }); + } + else { + return Promise.resolve(); + } + }); + } + clearTimeout() { + if (this.timerHandle !== null) { + this.removalCallback(this); + clearTimeout(this.timerHandle); + this.timerHandle = null; + } + } +} +/** + * Returns a FirestoreError that can be surfaced to the user if the provided + * error is an IndexedDbTransactionError. Re-throws the error otherwise. + */ +function wrapInUserErrorIfRecoverable(e, msg) { + logError(LOG_TAG$4, `${msg}: ${e}`); + if (isIndexedDbTransactionError(e)) { + return new FirestoreError(Code.UNAVAILABLE, `${msg}: ${e}`); + } + else { + throw e; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * DocumentSet is an immutable (copy-on-write) collection that holds documents + * in order specified by the provided comparator. We always add a document key + * comparator on top of what is provided to guarantee document equality based on + * the key. + */ +class DocumentSet { + /** + * Returns an empty copy of the existing DocumentSet, using the same + * comparator. + */ + static emptySet(oldSet) { + return new DocumentSet(oldSet.comparator); + } + /** The default ordering is by key if the comparator is omitted */ + constructor(comp) { + // We are adding document key comparator to the end as it's the only + // guaranteed unique property of a document. + if (comp) { + this.comparator = (d1, d2) => comp(d1, d2) || DocumentKey.comparator(d1.key, d2.key); + } + else { + this.comparator = (d1, d2) => DocumentKey.comparator(d1.key, d2.key); + } + this.keyedMap = documentMap(); + this.sortedSet = new SortedMap(this.comparator); + } + has(key) { + return this.keyedMap.get(key) != null; + } + get(key) { + return this.keyedMap.get(key); + } + first() { + return this.sortedSet.minKey(); + } + last() { + return this.sortedSet.maxKey(); + } + isEmpty() { + return this.sortedSet.isEmpty(); + } + /** + * Returns the index of the provided key in the document set, or -1 if the + * document key is not present in the set; + */ + indexOf(key) { + const doc = this.keyedMap.get(key); + return doc ? this.sortedSet.indexOf(doc) : -1; + } + get size() { + return this.sortedSet.size; + } + /** Iterates documents in order defined by "comparator" */ + forEach(cb) { + this.sortedSet.inorderTraversal((k, v) => { + cb(k); + return false; + }); + } + /** Inserts or updates a document with the same key */ + add(doc) { + // First remove the element if we have it. + const set = this.delete(doc.key); + return set.copy(set.keyedMap.insert(doc.key, doc), set.sortedSet.insert(doc, null)); + } + /** Deletes a document with a given key */ + delete(key) { + const doc = this.get(key); + if (!doc) { + return this; + } + return this.copy(this.keyedMap.remove(key), this.sortedSet.remove(doc)); + } + isEqual(other) { + if (!(other instanceof DocumentSet)) { + return false; + } + if (this.size !== other.size) { + return false; + } + const thisIt = this.sortedSet.getIterator(); + const otherIt = other.sortedSet.getIterator(); + while (thisIt.hasNext()) { + const thisDoc = thisIt.getNext().key; + const otherDoc = otherIt.getNext().key; + if (!thisDoc.isEqual(otherDoc)) { + return false; + } + } + return true; + } + toString() { + const docStrings = []; + this.forEach(doc => { + docStrings.push(doc.toString()); + }); + if (docStrings.length === 0) { + return 'DocumentSet ()'; + } + else { + return 'DocumentSet (\n ' + docStrings.join(' \n') + '\n)'; + } + } + copy(keyedMap, sortedSet) { + const newSet = new DocumentSet(); + newSet.comparator = this.comparator; + newSet.keyedMap = keyedMap; + newSet.sortedSet = sortedSet; + return newSet; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * DocumentChangeSet keeps track of a set of changes to docs in a query, merging + * duplicate events for the same doc. + */ +class DocumentChangeSet { + constructor() { + this.changeMap = new SortedMap(DocumentKey.comparator); + } + track(change) { + const key = change.doc.key; + const oldChange = this.changeMap.get(key); + if (!oldChange) { + this.changeMap = this.changeMap.insert(key, change); + return; + } + // Merge the new change with the existing change. + if (change.type !== 0 /* ChangeType.Added */ && + oldChange.type === 3 /* ChangeType.Metadata */) { + this.changeMap = this.changeMap.insert(key, change); + } + else if (change.type === 3 /* ChangeType.Metadata */ && + oldChange.type !== 1 /* ChangeType.Removed */) { + this.changeMap = this.changeMap.insert(key, { + type: oldChange.type, + doc: change.doc + }); + } + else if (change.type === 2 /* ChangeType.Modified */ && + oldChange.type === 2 /* ChangeType.Modified */) { + this.changeMap = this.changeMap.insert(key, { + type: 2 /* ChangeType.Modified */, + doc: change.doc + }); + } + else if (change.type === 2 /* ChangeType.Modified */ && + oldChange.type === 0 /* ChangeType.Added */) { + this.changeMap = this.changeMap.insert(key, { + type: 0 /* ChangeType.Added */, + doc: change.doc + }); + } + else if (change.type === 1 /* ChangeType.Removed */ && + oldChange.type === 0 /* ChangeType.Added */) { + this.changeMap = this.changeMap.remove(key); + } + else if (change.type === 1 /* ChangeType.Removed */ && + oldChange.type === 2 /* ChangeType.Modified */) { + this.changeMap = this.changeMap.insert(key, { + type: 1 /* ChangeType.Removed */, + doc: oldChange.doc + }); + } + else if (change.type === 0 /* ChangeType.Added */ && + oldChange.type === 1 /* ChangeType.Removed */) { + this.changeMap = this.changeMap.insert(key, { + type: 2 /* ChangeType.Modified */, + doc: change.doc + }); + } + else { + // This includes these cases, which don't make sense: + // Added->Added + // Removed->Removed + // Modified->Added + // Removed->Modified + // Metadata->Added + // Removed->Metadata + fail(0xf76d, { + change, + oldChange + }); + } + } + getChanges() { + const changes = []; + this.changeMap.inorderTraversal((key, change) => { + changes.push(change); + }); + return changes; + } +} +class ViewSnapshot { + constructor(query, docs, oldDocs, docChanges, mutatedKeys, fromCache, syncStateChanged, excludesMetadataChanges, hasCachedResults) { + this.query = query; + this.docs = docs; + this.oldDocs = oldDocs; + this.docChanges = docChanges; + this.mutatedKeys = mutatedKeys; + this.fromCache = fromCache; + this.syncStateChanged = syncStateChanged; + this.excludesMetadataChanges = excludesMetadataChanges; + this.hasCachedResults = hasCachedResults; + } + /** Returns a view snapshot as if all documents in the snapshot were added. */ + static fromInitialDocuments(query, documents, mutatedKeys, fromCache, hasCachedResults) { + const changes = []; + documents.forEach(doc => { + changes.push({ type: 0 /* ChangeType.Added */, doc }); + }); + return new ViewSnapshot(query, documents, DocumentSet.emptySet(documents), changes, mutatedKeys, fromCache, + /* syncStateChanged= */ true, + /* excludesMetadataChanges= */ false, hasCachedResults); + } + get hasPendingWrites() { + return !this.mutatedKeys.isEmpty(); + } + isEqual(other) { + if (this.fromCache !== other.fromCache || + this.hasCachedResults !== other.hasCachedResults || + this.syncStateChanged !== other.syncStateChanged || + !this.mutatedKeys.isEqual(other.mutatedKeys) || + !queryEquals(this.query, other.query) || + !this.docs.isEqual(other.docs) || + !this.oldDocs.isEqual(other.oldDocs)) { + return false; + } + const changes = this.docChanges; + const otherChanges = other.docChanges; + if (changes.length !== otherChanges.length) { + return false; + } + for (let i = 0; i < changes.length; i++) { + if (changes[i].type !== otherChanges[i].type || + !changes[i].doc.isEqual(otherChanges[i].doc)) { + return false; + } + } + return true; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Holds the listeners and the last received ViewSnapshot for a query being + * tracked by EventManager. + */ +class QueryListenersInfo { + constructor() { + this.viewSnap = undefined; + this.listeners = []; + } + // Helper methods that checks if the query has listeners that listening to remote store + hasRemoteListeners() { + return this.listeners.some(listener => listener.listensToRemoteStore()); + } +} +function newEventManager() { + return new EventManagerImpl(); +} +class EventManagerImpl { + constructor() { + this.queries = newQueriesObjectMap(); + this.onlineState = "Unknown" /* OnlineState.Unknown */; + this.snapshotsInSyncListeners = new Set(); + } + terminate() { + errorAllTargets(this, new FirestoreError(Code.ABORTED, 'Firestore shutting down')); + } +} +function newQueriesObjectMap() { + return new ObjectMap(q => canonifyQuery(q), queryEquals); +} +async function eventManagerListen(eventManager, listener) { + const eventManagerImpl = debugCast(eventManager); + let listenerAction = 3 /* ListenerSetupAction.NoActionRequired */; + const query = listener.query; + let queryInfo = eventManagerImpl.queries.get(query); + if (!queryInfo) { + queryInfo = new QueryListenersInfo(); + listenerAction = listener.listensToRemoteStore() + ? 0 /* ListenerSetupAction.InitializeLocalListenAndRequireWatchConnection */ + : 1 /* ListenerSetupAction.InitializeLocalListenOnly */; + } + else if (!queryInfo.hasRemoteListeners() && + listener.listensToRemoteStore()) { + // Query has been listening to local cache, and tries to add a new listener sourced from watch. + listenerAction = 2 /* ListenerSetupAction.RequireWatchConnectionOnly */; + } + try { + switch (listenerAction) { + case 0 /* ListenerSetupAction.InitializeLocalListenAndRequireWatchConnection */: + queryInfo.viewSnap = await eventManagerImpl.onListen(query, + /** enableRemoteListen= */ true); + break; + case 1 /* ListenerSetupAction.InitializeLocalListenOnly */: + queryInfo.viewSnap = await eventManagerImpl.onListen(query, + /** enableRemoteListen= */ false); + break; + case 2 /* ListenerSetupAction.RequireWatchConnectionOnly */: + await eventManagerImpl.onFirstRemoteStoreListen(query); + break; + default: + break; + } + } + catch (e) { + const firestoreError = wrapInUserErrorIfRecoverable(e, `Initialization of query '${stringifyQuery(listener.query)}' failed`); + listener.onError(firestoreError); + return; + } + eventManagerImpl.queries.set(query, queryInfo); + queryInfo.listeners.push(listener); + // Run global snapshot listeners if a consistent snapshot has been emitted. + listener.applyOnlineStateChange(eventManagerImpl.onlineState); + if (queryInfo.viewSnap) { + const raisedEvent = listener.onViewSnapshot(queryInfo.viewSnap); + if (raisedEvent) { + raiseSnapshotsInSyncEvent(eventManagerImpl); + } + } +} +async function eventManagerUnlisten(eventManager, listener) { + const eventManagerImpl = debugCast(eventManager); + const query = listener.query; + let listenerAction = 3 /* ListenerRemovalAction.NoActionRequired */; + const queryInfo = eventManagerImpl.queries.get(query); + if (queryInfo) { + const i = queryInfo.listeners.indexOf(listener); + if (i >= 0) { + queryInfo.listeners.splice(i, 1); + if (queryInfo.listeners.length === 0) { + listenerAction = listener.listensToRemoteStore() + ? 0 /* ListenerRemovalAction.TerminateLocalListenAndRequireWatchDisconnection */ + : 1 /* ListenerRemovalAction.TerminateLocalListenOnly */; + } + else if (!queryInfo.hasRemoteListeners() && + listener.listensToRemoteStore()) { + // The removed listener is the last one that sourced from watch. + listenerAction = 2 /* ListenerRemovalAction.RequireWatchDisconnectionOnly */; + } + } + } + switch (listenerAction) { + case 0 /* ListenerRemovalAction.TerminateLocalListenAndRequireWatchDisconnection */: + eventManagerImpl.queries.delete(query); + return eventManagerImpl.onUnlisten(query, + /** disableRemoteListen= */ true); + case 1 /* ListenerRemovalAction.TerminateLocalListenOnly */: + eventManagerImpl.queries.delete(query); + return eventManagerImpl.onUnlisten(query, + /** disableRemoteListen= */ false); + case 2 /* ListenerRemovalAction.RequireWatchDisconnectionOnly */: + return eventManagerImpl.onLastRemoteStoreUnlisten(query); + default: + return; + } +} +function eventManagerOnWatchChange(eventManager, viewSnaps) { + const eventManagerImpl = debugCast(eventManager); + let raisedEvent = false; + for (const viewSnap of viewSnaps) { + const query = viewSnap.query; + const queryInfo = eventManagerImpl.queries.get(query); + if (queryInfo) { + for (const listener of queryInfo.listeners) { + if (listener.onViewSnapshot(viewSnap)) { + raisedEvent = true; + } + } + queryInfo.viewSnap = viewSnap; + } + } + if (raisedEvent) { + raiseSnapshotsInSyncEvent(eventManagerImpl); + } +} +function eventManagerOnWatchError(eventManager, query, error) { + const eventManagerImpl = debugCast(eventManager); + const queryInfo = eventManagerImpl.queries.get(query); + if (queryInfo) { + for (const listener of queryInfo.listeners) { + listener.onError(error); + } + } + // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten() + // after an error. + eventManagerImpl.queries.delete(query); +} +function eventManagerOnOnlineStateChange(eventManager, onlineState) { + const eventManagerImpl = debugCast(eventManager); + eventManagerImpl.onlineState = onlineState; + let raisedEvent = false; + eventManagerImpl.queries.forEach((_, queryInfo) => { + for (const listener of queryInfo.listeners) { + // Run global snapshot listeners if a consistent snapshot has been emitted. + if (listener.applyOnlineStateChange(onlineState)) { + raisedEvent = true; + } + } + }); + if (raisedEvent) { + raiseSnapshotsInSyncEvent(eventManagerImpl); + } +} +function addSnapshotsInSyncListener(eventManager, observer) { + const eventManagerImpl = debugCast(eventManager); + eventManagerImpl.snapshotsInSyncListeners.add(observer); + // Immediately fire an initial event, indicating all existing listeners + // are in-sync. + observer.next(); +} +function removeSnapshotsInSyncListener(eventManager, observer) { + const eventManagerImpl = debugCast(eventManager); + eventManagerImpl.snapshotsInSyncListeners.delete(observer); +} +function errorAllTargets(eventManager, error) { + const eventManagerImpl = debugCast(eventManager); + const queries = eventManagerImpl.queries; + // Prevent further access by clearing ObjectMap. + eventManagerImpl.queries = newQueriesObjectMap(); + queries.forEach((_, queryInfo) => { + for (const listener of queryInfo.listeners) { + listener.onError(error); + } + }); +} +// Call all global snapshot listeners that have been set. +function raiseSnapshotsInSyncEvent(eventManagerImpl) { + eventManagerImpl.snapshotsInSyncListeners.forEach(observer => { + observer.next(); + }); +} +var ListenerDataSource; +(function (ListenerDataSource) { + /** Listen to both cache and server changes */ + ListenerDataSource["Default"] = "default"; + /** Listen to changes in cache only */ + ListenerDataSource["Cache"] = "cache"; +})(ListenerDataSource || (ListenerDataSource = {})); +/** + * QueryListener takes a series of internal view snapshots and determines + * when to raise the event. + * + * It uses an Observer to dispatch events. + */ +class QueryListener { + constructor(query, queryObserver, options) { + this.query = query; + this.queryObserver = queryObserver; + /** + * Initial snapshots (e.g. from cache) may not be propagated to the wrapped + * observer. This flag is set to true once we've actually raised an event. + */ + this.raisedInitialEvent = false; + this.snap = null; + this.onlineState = "Unknown" /* OnlineState.Unknown */; + this.options = options || {}; + } + /** + * Applies the new ViewSnapshot to this listener, raising a user-facing event + * if applicable (depending on what changed, whether the user has opted into + * metadata-only changes, etc.). Returns true if a user-facing event was + * indeed raised. + */ + onViewSnapshot(snap) { + if (!this.options.includeMetadataChanges) { + // Remove the metadata only changes. + const docChanges = []; + for (const docChange of snap.docChanges) { + if (docChange.type !== 3 /* ChangeType.Metadata */) { + docChanges.push(docChange); + } + } + snap = new ViewSnapshot(snap.query, snap.docs, snap.oldDocs, docChanges, snap.mutatedKeys, snap.fromCache, snap.syncStateChanged, + /* excludesMetadataChanges= */ true, snap.hasCachedResults); + } + let raisedEvent = false; + if (!this.raisedInitialEvent) { + if (this.shouldRaiseInitialEvent(snap, this.onlineState)) { + this.raiseInitialEvent(snap); + raisedEvent = true; + } + } + else if (this.shouldRaiseEvent(snap)) { + this.queryObserver.next(snap); + raisedEvent = true; + } + this.snap = snap; + return raisedEvent; + } + onError(error) { + this.queryObserver.error(error); + } + /** Returns whether a snapshot was raised. */ + applyOnlineStateChange(onlineState) { + this.onlineState = onlineState; + let raisedEvent = false; + if (this.snap && + !this.raisedInitialEvent && + this.shouldRaiseInitialEvent(this.snap, onlineState)) { + this.raiseInitialEvent(this.snap); + raisedEvent = true; + } + return raisedEvent; + } + shouldRaiseInitialEvent(snap, onlineState) { + // Always raise the first event when we're synced + if (!snap.fromCache) { + return true; + } + // Always raise event if listening to cache + if (!this.listensToRemoteStore()) { + return true; + } + // NOTE: We consider OnlineState.Unknown as online (it should become Offline + // or Online if we wait long enough). + const maybeOnline = onlineState !== "Offline" /* OnlineState.Offline */; + // Don't raise the event if we're online, aren't synced yet (checked + // above) and are waiting for a sync. + if (this.options.waitForSyncWhenOnline && maybeOnline) { + return false; + } + // Raise data from cache if we have any documents, have cached results before, + // or we are offline. + return (!snap.docs.isEmpty() || + snap.hasCachedResults || + onlineState === "Offline" /* OnlineState.Offline */); + } + shouldRaiseEvent(snap) { + // We don't need to handle includeDocumentMetadataChanges here because + // the Metadata only changes have already been stripped out if needed. + // At this point the only changes we will see are the ones we should + // propagate. + if (snap.docChanges.length > 0) { + return true; + } + const hasPendingWritesChanged = this.snap && this.snap.hasPendingWrites !== snap.hasPendingWrites; + if (snap.syncStateChanged || hasPendingWritesChanged) { + return this.options.includeMetadataChanges === true; + } + // Generally we should have hit one of the cases above, but it's possible + // to get here if there were only metadata docChanges and they got + // stripped out. + return false; + } + raiseInitialEvent(snap) { + snap = ViewSnapshot.fromInitialDocuments(snap.query, snap.docs, snap.mutatedKeys, snap.fromCache, snap.hasCachedResults); + this.raisedInitialEvent = true; + this.queryObserver.next(snap); + } + listensToRemoteStore() { + return this.options.source !== ListenerDataSource.Cache; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A set of changes to what documents are currently in view and out of view for + * a given query. These changes are sent to the LocalStore by the View (via + * the SyncEngine) and are used to pin / unpin documents as appropriate. + */ +class LocalViewChanges { + constructor(targetId, fromCache, addedKeys, removedKeys) { + this.targetId = targetId; + this.fromCache = fromCache; + this.addedKeys = addedKeys; + this.removedKeys = removedKeys; + } + static fromSnapshot(targetId, viewSnapshot) { + let addedKeys = documentKeySet(); + let removedKeys = documentKeySet(); + for (const docChange of viewSnapshot.docChanges) { + switch (docChange.type) { + case 0 /* ChangeType.Added */: + addedKeys = addedKeys.add(docChange.doc.key); + break; + case 1 /* ChangeType.Removed */: + removedKeys = removedKeys.add(docChange.doc.key); + break; + // do nothing + } + } + return new LocalViewChanges(targetId, viewSnapshot.fromCache, addedKeys, removedKeys); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Helper to convert objects from bundles to model objects in the SDK. + */ +class BundleConverterImpl { + constructor(serializer) { + this.serializer = serializer; + } + toDocumentKey(name) { + return fromName(this.serializer, name); + } + /** + * Converts a BundleDocument to a MutableDocument. + */ + toMutableDocument(bundledDoc) { + if (bundledDoc.metadata.exists) { + return fromDocument(this.serializer, bundledDoc.document, false); + } + else { + return MutableDocument.newNoDocument(this.toDocumentKey(bundledDoc.metadata.name), this.toSnapshotVersion(bundledDoc.metadata.readTime)); + } + } + toSnapshotVersion(time) { + return fromVersion(time); + } +} +/** + * A class to process the elements from a bundle, and optionally load them into local + * storage and provide progress update while loading. + */ +class BundleLoader { + constructor(bundleMetadata, serializer) { + this.bundleMetadata = bundleMetadata; + this.serializer = serializer; + /** Batched queries to be saved into storage */ + this._queries = []; + /** Batched documents to be saved into storage */ + this._documents = []; + /** The collection groups affected by this bundle. */ + this.collectionGroups = new Set(); + this.progress = bundleInitialProgress(bundleMetadata); + } + /** + * Returns the named queries that have been parsed from the SizeBundleElements added by + * calling {@link adSizedElement}. + */ + get queries() { + return this._queries; + } + /** + * Returns the BundledDocuments that have been parsed from the SizeBundleElements added by + * calling {@link addSizedElement}. + */ + get documents() { + return this._documents; + } + /** + * Adds an element from the bundle to the loader. + * + * Returns a new progress if adding the element leads to a new progress, + * otherwise returns null. + */ + addSizedElement(element) { + this.progress.bytesLoaded += element.byteLength; + let documentsLoaded = this.progress.documentsLoaded; + if (element.payload.namedQuery) { + this._queries.push(element.payload.namedQuery); + } + else if (element.payload.documentMetadata) { + this._documents.push({ metadata: element.payload.documentMetadata }); + if (!element.payload.documentMetadata.exists) { + ++documentsLoaded; + } + const path = ResourcePath.fromString(element.payload.documentMetadata.name); + this.collectionGroups.add(path.get(path.length - 2)); + } + else if (element.payload.document) { + this._documents[this._documents.length - 1].document = + element.payload.document; + ++documentsLoaded; + } + if (documentsLoaded !== this.progress.documentsLoaded) { + this.progress.documentsLoaded = documentsLoaded; + return { ...this.progress }; + } + return null; + } + getQueryDocumentMapping(documents) { + const queryDocumentMap = new Map(); + const bundleConverter = new BundleConverterImpl(this.serializer); + for (const bundleDoc of documents) { + if (bundleDoc.metadata.queries) { + const documentKey = bundleConverter.toDocumentKey(bundleDoc.metadata.name); + for (const queryName of bundleDoc.metadata.queries) { + const documentKeys = (queryDocumentMap.get(queryName) || documentKeySet()).add(documentKey); + queryDocumentMap.set(queryName, documentKeys); + } + } + } + return queryDocumentMap; + } + /** + * Update the progress to 'Success' and return the updated progress. + */ + async completeAndStoreAsync(localStore) { + const changedDocs = await localStoreApplyBundledDocuments(localStore, new BundleConverterImpl(this.serializer), this._documents, this.bundleMetadata.id); + const queryDocumentMap = this.getQueryDocumentMapping(this.documents); + for (const q of this._queries) { + await localStoreSaveNamedQuery(localStore, q, queryDocumentMap.get(q.name)); + } + this.progress.taskState = 'Success'; + return { + progress: this.progress, + changedCollectionGroups: this.collectionGroups, + changedDocs + }; + } +} +/** + * Returns a `LoadBundleTaskProgress` representing the initial progress of + * loading a bundle. + */ +function bundleInitialProgress(metadata) { + return { + taskState: 'Running', + documentsLoaded: 0, + bytesLoaded: 0, + totalDocuments: metadata.totalDocuments, + totalBytes: metadata.totalBytes + }; +} +/** + * Returns a `LoadBundleTaskProgress` representing the progress that the loading + * has succeeded. + */ +function bundleSuccessProgress(metadata) { + return { + taskState: 'Success', + documentsLoaded: metadata.totalDocuments, + bytesLoaded: metadata.totalBytes, + totalDocuments: metadata.totalDocuments, + totalBytes: metadata.totalBytes + }; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class AddedLimboDocument { + constructor(key) { + this.key = key; + } +} +class RemovedLimboDocument { + constructor(key) { + this.key = key; + } +} +/** + * View is responsible for computing the final merged truth of what docs are in + * a query. It gets notified of local and remote changes to docs, and applies + * the query filters and limits to determine the most correct possible results. + */ +class View { + constructor(query, + /** Documents included in the remote target */ + _syncedDocuments) { + this.query = query; + this._syncedDocuments = _syncedDocuments; + this.syncState = null; + this.hasCachedResults = false; + /** + * A flag whether the view is current with the backend. A view is considered + * current after it has seen the current flag from the backend and did not + * lose consistency within the watch stream (e.g. because of an existence + * filter mismatch). + */ + this.current = false; + /** Documents in the view but not in the remote target */ + this.limboDocuments = documentKeySet(); + /** Document Keys that have local changes */ + this.mutatedKeys = documentKeySet(); + this.docComparator = newQueryComparator(query); + this.documentSet = new DocumentSet(this.docComparator); + } + /** + * The set of remote documents that the server has told us belongs to the target associated with + * this view. + */ + get syncedDocuments() { + return this._syncedDocuments; + } + /** + * Iterates over a set of doc changes, applies the query limit, and computes + * what the new results should be, what the changes were, and whether we may + * need to go back to the local cache for more results. Does not make any + * changes to the view. + * @param docChanges - The doc changes to apply to this view. + * @param previousChanges - If this is being called with a refill, then start + * with this set of docs and changes instead of the current view. + * @returns a new set of docs, changes, and refill flag. + */ + computeDocChanges(docChanges, previousChanges) { + const changeSet = previousChanges + ? previousChanges.changeSet + : new DocumentChangeSet(); + const oldDocumentSet = previousChanges + ? previousChanges.documentSet + : this.documentSet; + let newMutatedKeys = previousChanges + ? previousChanges.mutatedKeys + : this.mutatedKeys; + let newDocumentSet = oldDocumentSet; + let needsRefill = false; + // Track the last doc in a (full) limit. This is necessary, because some + // update (a delete, or an update moving a doc past the old limit) might + // mean there is some other document in the local cache that either should + // come (1) between the old last limit doc and the new last document, in the + // case of updates, or (2) after the new last document, in the case of + // deletes. So we keep this doc at the old limit to compare the updates to. + // + // Note that this should never get used in a refill (when previousChanges is + // set), because there will only be adds -- no deletes or updates. + const lastDocInLimit = this.query.limitType === "F" /* LimitType.First */ && + oldDocumentSet.size === this.query.limit + ? oldDocumentSet.last() + : null; + const firstDocInLimit = this.query.limitType === "L" /* LimitType.Last */ && + oldDocumentSet.size === this.query.limit + ? oldDocumentSet.first() + : null; + docChanges.inorderTraversal((key, entry) => { + const oldDoc = oldDocumentSet.get(key); + const newDoc = queryMatches(this.query, entry) ? entry : null; + const oldDocHadPendingMutations = oldDoc + ? this.mutatedKeys.has(oldDoc.key) + : false; + const newDocHasPendingMutations = newDoc + ? newDoc.hasLocalMutations || + // We only consider committed mutations for documents that were + // mutated during the lifetime of the view. + (this.mutatedKeys.has(newDoc.key) && newDoc.hasCommittedMutations) + : false; + let changeApplied = false; + // Calculate change + if (oldDoc && newDoc) { + const docsEqual = oldDoc.data.isEqual(newDoc.data); + if (!docsEqual) { + if (!this.shouldWaitForSyncedDocument(oldDoc, newDoc)) { + changeSet.track({ + type: 2 /* ChangeType.Modified */, + doc: newDoc + }); + changeApplied = true; + if ((lastDocInLimit && + this.docComparator(newDoc, lastDocInLimit) > 0) || + (firstDocInLimit && + this.docComparator(newDoc, firstDocInLimit) < 0)) { + // This doc moved from inside the limit to outside the limit. + // That means there may be some other doc in the local cache + // that should be included instead. + needsRefill = true; + } + } + } + else if (oldDocHadPendingMutations !== newDocHasPendingMutations) { + changeSet.track({ type: 3 /* ChangeType.Metadata */, doc: newDoc }); + changeApplied = true; + } + } + else if (!oldDoc && newDoc) { + changeSet.track({ type: 0 /* ChangeType.Added */, doc: newDoc }); + changeApplied = true; + } + else if (oldDoc && !newDoc) { + changeSet.track({ type: 1 /* ChangeType.Removed */, doc: oldDoc }); + changeApplied = true; + if (lastDocInLimit || firstDocInLimit) { + // A doc was removed from a full limit query. We'll need to + // requery from the local cache to see if we know about some other + // doc that should be in the results. + needsRefill = true; + } + } + if (changeApplied) { + if (newDoc) { + newDocumentSet = newDocumentSet.add(newDoc); + if (newDocHasPendingMutations) { + newMutatedKeys = newMutatedKeys.add(key); + } + else { + newMutatedKeys = newMutatedKeys.delete(key); + } + } + else { + newDocumentSet = newDocumentSet.delete(key); + newMutatedKeys = newMutatedKeys.delete(key); + } + } + }); + // Drop documents out to meet limit/limitToLast requirement. + if (this.query.limit !== null) { + while (newDocumentSet.size > this.query.limit) { + const oldDoc = this.query.limitType === "F" /* LimitType.First */ + ? newDocumentSet.last() + : newDocumentSet.first(); + newDocumentSet = newDocumentSet.delete(oldDoc.key); + newMutatedKeys = newMutatedKeys.delete(oldDoc.key); + changeSet.track({ type: 1 /* ChangeType.Removed */, doc: oldDoc }); + } + } + return { + documentSet: newDocumentSet, + changeSet, + needsRefill, + mutatedKeys: newMutatedKeys + }; + } + shouldWaitForSyncedDocument(oldDoc, newDoc) { + // We suppress the initial change event for documents that were modified as + // part of a write acknowledgment (e.g. when the value of a server transform + // is applied) as Watch will send us the same document again. + // By suppressing the event, we only raise two user visible events (one with + // `hasPendingWrites` and the final state of the document) instead of three + // (one with `hasPendingWrites`, the modified document with + // `hasPendingWrites` and the final state of the document). + return (oldDoc.hasLocalMutations && + newDoc.hasCommittedMutations && + !newDoc.hasLocalMutations); + } + /** + * Updates the view with the given ViewDocumentChanges and optionally updates + * limbo docs and sync state from the provided target change. + * @param docChanges - The set of changes to make to the view's docs. + * @param limboResolutionEnabled - Whether to update limbo documents based on + * this change. + * @param targetChange - A target change to apply for computing limbo docs and + * sync state. + * @param targetIsPendingReset - Whether the target is pending to reset due to + * existence filter mismatch. If not explicitly specified, it is treated + * equivalently to `false`. + * @returns A new ViewChange with the given docs, changes, and sync state. + */ + // PORTING NOTE: The iOS/Android clients always compute limbo document changes. + applyChanges(docChanges, limboResolutionEnabled, targetChange, targetIsPendingReset) { + const oldDocs = this.documentSet; + this.documentSet = docChanges.documentSet; + this.mutatedKeys = docChanges.mutatedKeys; + // Sort changes based on type and query comparator + const changes = docChanges.changeSet.getChanges(); + changes.sort((c1, c2) => { + return (compareChangeType(c1.type, c2.type) || + this.docComparator(c1.doc, c2.doc)); + }); + this.applyTargetChange(targetChange); + targetIsPendingReset = targetIsPendingReset ?? false; + const limboChanges = limboResolutionEnabled && !targetIsPendingReset + ? this.updateLimboDocuments() + : []; + // We are at synced state if there is no limbo docs are waiting to be resolved, view is current + // with the backend, and the query is not pending to reset due to existence filter mismatch. + const synced = this.limboDocuments.size === 0 && this.current && !targetIsPendingReset; + const newSyncState = synced ? 1 /* SyncState.Synced */ : 0 /* SyncState.Local */; + const syncStateChanged = newSyncState !== this.syncState; + this.syncState = newSyncState; + if (changes.length === 0 && !syncStateChanged) { + // no changes + return { limboChanges }; + } + else { + const snap = new ViewSnapshot(this.query, docChanges.documentSet, oldDocs, changes, docChanges.mutatedKeys, newSyncState === 0 /* SyncState.Local */, syncStateChanged, + /* excludesMetadataChanges= */ false, targetChange + ? targetChange.resumeToken.approximateByteSize() > 0 + : false); + return { + snapshot: snap, + limboChanges + }; + } + } + /** + * Applies an OnlineState change to the view, potentially generating a + * ViewChange if the view's syncState changes as a result. + */ + applyOnlineStateChange(onlineState) { + if (this.current && onlineState === "Offline" /* OnlineState.Offline */) { + // If we're offline, set `current` to false and then call applyChanges() + // to refresh our syncState and generate a ViewChange as appropriate. We + // are guaranteed to get a new TargetChange that sets `current` back to + // true once the client is back online. + this.current = false; + return this.applyChanges({ + documentSet: this.documentSet, + changeSet: new DocumentChangeSet(), + mutatedKeys: this.mutatedKeys, + needsRefill: false + }, + /* limboResolutionEnabled= */ false); + } + else { + // No effect, just return a no-op ViewChange. + return { limboChanges: [] }; + } + } + /** + * Returns whether the doc for the given key should be in limbo. + */ + shouldBeInLimbo(key) { + // If the remote end says it's part of this query, it's not in limbo. + if (this._syncedDocuments.has(key)) { + return false; + } + // The local store doesn't think it's a result, so it shouldn't be in limbo. + if (!this.documentSet.has(key)) { + return false; + } + // If there are local changes to the doc, they might explain why the server + // doesn't know that it's part of the query. So don't put it in limbo. + // TODO(klimt): Ideally, we would only consider changes that might actually + // affect this specific query. + if (this.documentSet.get(key).hasLocalMutations) { + return false; + } + // Everything else is in limbo. + return true; + } + /** + * Updates syncedDocuments, current, and limbo docs based on the given change. + * Returns the list of changes to which docs are in limbo. + */ + applyTargetChange(targetChange) { + if (targetChange) { + targetChange.addedDocuments.forEach(key => (this._syncedDocuments = this._syncedDocuments.add(key))); + targetChange.modifiedDocuments.forEach(key => { + }); + targetChange.removedDocuments.forEach(key => (this._syncedDocuments = this._syncedDocuments.delete(key))); + this.current = targetChange.current; + } + } + updateLimboDocuments() { + // We can only determine limbo documents when we're in-sync with the server. + if (!this.current) { + return []; + } + // TODO(klimt): Do this incrementally so that it's not quadratic when + // updating many documents. + const oldLimboDocuments = this.limboDocuments; + this.limboDocuments = documentKeySet(); + this.documentSet.forEach(doc => { + if (this.shouldBeInLimbo(doc.key)) { + this.limboDocuments = this.limboDocuments.add(doc.key); + } + }); + // Diff the new limbo docs with the old limbo docs. + const changes = []; + oldLimboDocuments.forEach(key => { + if (!this.limboDocuments.has(key)) { + changes.push(new RemovedLimboDocument(key)); + } + }); + this.limboDocuments.forEach(key => { + if (!oldLimboDocuments.has(key)) { + changes.push(new AddedLimboDocument(key)); + } + }); + return changes; + } + /** + * Update the in-memory state of the current view with the state read from + * persistence. + * + * We update the query view whenever a client's primary status changes: + * - When a client transitions from primary to secondary, it can miss + * LocalStorage updates and its query views may temporarily not be + * synchronized with the state on disk. + * - For secondary to primary transitions, the client needs to update the list + * of `syncedDocuments` since secondary clients update their query views + * based purely on synthesized RemoteEvents. + * + * @param queryResult.documents - The documents that match the query according + * to the LocalStore. + * @param queryResult.remoteKeys - The keys of the documents that match the + * query according to the backend. + * + * @returns The ViewChange that resulted from this synchronization. + */ + // PORTING NOTE: Multi-tab only. + synchronizeWithPersistedState(queryResult) { + this._syncedDocuments = queryResult.remoteKeys; + this.limboDocuments = documentKeySet(); + const docChanges = this.computeDocChanges(queryResult.documents); + return this.applyChanges(docChanges, /* limboResolutionEnabled= */ true); + } + /** + * Returns a view snapshot as if this query was just listened to. Contains + * a document add for every existing document and the `fromCache` and + * `hasPendingWrites` status of the already established view. + */ + // PORTING NOTE: Multi-tab only. + computeInitialSnapshot() { + return ViewSnapshot.fromInitialDocuments(this.query, this.documentSet, this.mutatedKeys, this.syncState === 0 /* SyncState.Local */, this.hasCachedResults); + } +} +function compareChangeType(c1, c2) { + const order = (change) => { + switch (change) { + case 0 /* ChangeType.Added */: + return 1; + case 2 /* ChangeType.Modified */: + return 2; + case 3 /* ChangeType.Metadata */: + // A metadata change is converted to a modified change at the public + // api layer. Since we sort by document key and then change type, + // metadata and modified changes must be sorted equivalently. + return 2; + case 1 /* ChangeType.Removed */: + return 0; + default: + return fail(0x4f35, { change }); + } + }; + return order(c1) - order(c2); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$3 = 'SyncEngine'; +/** + * QueryView contains all of the data that SyncEngine needs to keep track of for + * a particular query. + */ +class QueryView { + constructor( + /** + * The query itself. + */ + query, + /** + * The target number created by the client that is used in the watch + * stream to identify this query. + */ + targetId, + /** + * The view is responsible for computing the final merged truth of what + * docs are in the query. It gets notified of local and remote changes, + * and applies the query filters and limits to determine the most correct + * possible results. + */ + view) { + this.query = query; + this.targetId = targetId; + this.view = view; + } +} +/** Tracks a limbo resolution. */ +class LimboResolution { + constructor(key) { + this.key = key; + /** + * Set to true once we've received a document. This is used in + * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to + * decide whether it needs to manufacture a delete event for the target once + * the target is CURRENT. + */ + this.receivedDocument = false; + } +} +/** + * An implementation of `SyncEngine` coordinating with other parts of SDK. + * + * The parts of SyncEngine that act as a callback to RemoteStore need to be + * registered individually. This is done in `syncEngineWrite()` and + * `syncEngineListen()` (as well as `applyPrimaryState()`) as these methods + * serve as entry points to RemoteStore's functionality. + * + * Note: some field defined in this class might have public access level, but + * the class is not exported so they are only accessible from this module. + * This is useful to implement optional features (like bundles) in free + * functions, such that they are tree-shakeable. + */ +class SyncEngineImpl { + constructor(localStore, remoteStore, eventManager, + // PORTING NOTE: Manages state synchronization in multi-tab environments. + sharedClientState, currentUser, maxConcurrentLimboResolutions) { + this.localStore = localStore; + this.remoteStore = remoteStore; + this.eventManager = eventManager; + this.sharedClientState = sharedClientState; + this.currentUser = currentUser; + this.maxConcurrentLimboResolutions = maxConcurrentLimboResolutions; + this.syncEngineListener = {}; + this.queryViewsByQuery = new ObjectMap(q => canonifyQuery(q), queryEquals); + this.queriesByTarget = new Map(); + /** + * The keys of documents that are in limbo for which we haven't yet started a + * limbo resolution query. The strings in this set are the result of calling + * `key.path.canonicalString()` where `key` is a `DocumentKey` object. + * + * The `Set` type was chosen because it provides efficient lookup and removal + * of arbitrary elements and it also maintains insertion order, providing the + * desired queue-like FIFO semantics. + */ + this.enqueuedLimboResolutions = new Set(); + /** + * Keeps track of the target ID for each document that is in limbo with an + * active target. + */ + this.activeLimboTargetsByKey = new SortedMap(DocumentKey.comparator); + /** + * Keeps track of the information about an active limbo resolution for each + * active target ID that was started for the purpose of limbo resolution. + */ + this.activeLimboResolutionsByTarget = new Map(); + this.limboDocumentRefs = new ReferenceSet(); + /** Stores user completion handlers, indexed by User and BatchId. */ + this.mutationUserCallbacks = {}; + /** Stores user callbacks waiting for all pending writes to be acknowledged. */ + this.pendingWritesCallbacks = new Map(); + this.limboTargetIdGenerator = TargetIdGenerator.forSyncEngine(); + this.onlineState = "Unknown" /* OnlineState.Unknown */; + // The primary state is set to `true` or `false` immediately after Firestore + // startup. In the interim, a client should only be considered primary if + // `isPrimary` is true. + this._isPrimaryClient = undefined; + } + get isPrimaryClient() { + return this._isPrimaryClient === true; + } +} +function newSyncEngine(localStore, remoteStore, eventManager, +// PORTING NOTE: Manages state synchronization in multi-tab environments. +sharedClientState, currentUser, maxConcurrentLimboResolutions, isPrimary) { + const syncEngine = new SyncEngineImpl(localStore, remoteStore, eventManager, sharedClientState, currentUser, maxConcurrentLimboResolutions); + if (isPrimary) { + syncEngine._isPrimaryClient = true; + } + return syncEngine; +} +/** + * Initiates the new listen, resolves promise when listen enqueued to the + * server. All the subsequent view snapshots or errors are sent to the + * subscribed handlers. Returns the initial snapshot. + */ +async function syncEngineListen(syncEngine, query, shouldListenToRemote = true) { + const syncEngineImpl = ensureWatchCallbacks(syncEngine); + let viewSnapshot; + const queryView = syncEngineImpl.queryViewsByQuery.get(query); + if (queryView) { + // PORTING NOTE: With Multi-Tab Web, it is possible that a query view + // already exists when EventManager calls us for the first time. This + // happens when the primary tab is already listening to this query on + // behalf of another tab and the user of the primary also starts listening + // to the query. EventManager will not have an assigned target ID in this + // case and calls `listen` to obtain this ID. + syncEngineImpl.sharedClientState.addLocalQueryTarget(queryView.targetId); + viewSnapshot = queryView.view.computeInitialSnapshot(); + } + else { + viewSnapshot = await allocateTargetAndMaybeListen(syncEngineImpl, query, shouldListenToRemote, + /** shouldInitializeView= */ true); + } + return viewSnapshot; +} +/** Query has been listening to the cache, and tries to initiate the remote store listen */ +async function triggerRemoteStoreListen(syncEngine, query) { + const syncEngineImpl = ensureWatchCallbacks(syncEngine); + await allocateTargetAndMaybeListen(syncEngineImpl, query, + /** shouldListenToRemote= */ true, + /** shouldInitializeView= */ false); +} +async function allocateTargetAndMaybeListen(syncEngineImpl, query, shouldListenToRemote, shouldInitializeView) { + const targetData = await localStoreAllocateTarget(syncEngineImpl.localStore, queryToTarget(query)); + const targetId = targetData.targetId; + // PORTING NOTE: When the query is listening to cache only, we skip sending it over to Watch by + // not registering it in shared client state, and directly calculate initial snapshots and + // subsequent updates from cache. Otherwise, register the target ID with local Firestore client + // as active watch target. + const status = syncEngineImpl.sharedClientState.addLocalQueryTarget(targetId, + /* addToActiveTargetIds= */ shouldListenToRemote); + let viewSnapshot; + if (shouldInitializeView) { + viewSnapshot = await initializeViewAndComputeSnapshot(syncEngineImpl, query, targetId, status === 'current', targetData.resumeToken); + } + if (syncEngineImpl.isPrimaryClient && shouldListenToRemote) { + remoteStoreListen(syncEngineImpl.remoteStore, targetData); + } + return viewSnapshot; +} +/** + * Registers a view for a previously unknown query and computes its initial + * snapshot. + */ +async function initializeViewAndComputeSnapshot(syncEngineImpl, query, targetId, current, resumeToken) { + // PORTING NOTE: On Web only, we inject the code that registers new Limbo + // targets based on view changes. This allows us to only depend on Limbo + // changes when user code includes queries. + syncEngineImpl.applyDocChanges = (queryView, changes, remoteEvent) => applyDocChanges(syncEngineImpl, queryView, changes, remoteEvent); + const queryResult = await localStoreExecuteQuery(syncEngineImpl.localStore, query, + /* usePreviousResults= */ true); + const view = new View(query, queryResult.remoteKeys); + const viewDocChanges = view.computeDocChanges(queryResult.documents); + const synthesizedTargetChange = TargetChange.createSynthesizedTargetChangeForCurrentChange(targetId, current && syncEngineImpl.onlineState !== "Offline" /* OnlineState.Offline */, resumeToken); + const viewChange = view.applyChanges(viewDocChanges, + /* limboResolutionEnabled= */ syncEngineImpl.isPrimaryClient, synthesizedTargetChange); + updateTrackedLimbos(syncEngineImpl, targetId, viewChange.limboChanges); + const data = new QueryView(query, targetId, view); + syncEngineImpl.queryViewsByQuery.set(query, data); + if (syncEngineImpl.queriesByTarget.has(targetId)) { + syncEngineImpl.queriesByTarget.get(targetId).push(query); + } + else { + syncEngineImpl.queriesByTarget.set(targetId, [query]); + } + return viewChange.snapshot; +} +/** Stops listening to the query. */ +async function syncEngineUnlisten(syncEngine, query, shouldUnlistenToRemote) { + const syncEngineImpl = debugCast(syncEngine); + const queryView = syncEngineImpl.queryViewsByQuery.get(query); + // Only clean up the query view and target if this is the only query mapped + // to the target. + const queries = syncEngineImpl.queriesByTarget.get(queryView.targetId); + if (queries.length > 1) { + syncEngineImpl.queriesByTarget.set(queryView.targetId, queries.filter(q => !queryEquals(q, query))); + syncEngineImpl.queryViewsByQuery.delete(query); + return; + } + // No other queries are mapped to the target, clean up the query and the target. + if (syncEngineImpl.isPrimaryClient) { + // We need to remove the local query target first to allow us to verify + // whether any other client is still interested in this target. + syncEngineImpl.sharedClientState.removeLocalQueryTarget(queryView.targetId); + const targetRemainsActive = syncEngineImpl.sharedClientState.isActiveQueryTarget(queryView.targetId); + if (!targetRemainsActive) { + await localStoreReleaseTarget(syncEngineImpl.localStore, queryView.targetId, + /*keepPersistedTargetData=*/ false) + .then(() => { + syncEngineImpl.sharedClientState.clearQueryState(queryView.targetId); + if (shouldUnlistenToRemote) { + remoteStoreUnlisten(syncEngineImpl.remoteStore, queryView.targetId); + } + removeAndCleanupTarget(syncEngineImpl, queryView.targetId); + }) + .catch(ignoreIfPrimaryLeaseLoss); + } + } + else { + removeAndCleanupTarget(syncEngineImpl, queryView.targetId); + await localStoreReleaseTarget(syncEngineImpl.localStore, queryView.targetId, + /*keepPersistedTargetData=*/ true); + } +} +/** Unlistens to the remote store while still listening to the cache. */ +async function triggerRemoteStoreUnlisten(syncEngine, query) { + const syncEngineImpl = debugCast(syncEngine); + const queryView = syncEngineImpl.queryViewsByQuery.get(query); + const queries = syncEngineImpl.queriesByTarget.get(queryView.targetId); + if (syncEngineImpl.isPrimaryClient && queries.length === 1) { + // PORTING NOTE: Unregister the target ID with local Firestore client as + // watch target. + syncEngineImpl.sharedClientState.removeLocalQueryTarget(queryView.targetId); + remoteStoreUnlisten(syncEngineImpl.remoteStore, queryView.targetId); + } +} +/** + * Initiates the write of local mutation batch which involves adding the + * writes to the mutation queue, notifying the remote store about new + * mutations and raising events for any changes this write caused. + * + * The promise returned by this call is resolved when the above steps + * have completed, *not* when the write was acked by the backend. The + * userCallback is resolved once the write was acked/rejected by the + * backend (or failed locally for any other reason). + */ +async function syncEngineWrite(syncEngine, batch, userCallback) { + const syncEngineImpl = syncEngineEnsureWriteCallbacks(syncEngine); + try { + const result = await localStoreWriteLocally(syncEngineImpl.localStore, batch); + syncEngineImpl.sharedClientState.addPendingMutation(result.batchId); + addMutationCallback(syncEngineImpl, result.batchId, userCallback); + await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, result.changes); + await fillWritePipeline(syncEngineImpl.remoteStore); + } + catch (e) { + // If we can't persist the mutation, we reject the user callback and + // don't send the mutation. The user can then retry the write. + const error = wrapInUserErrorIfRecoverable(e, `Failed to persist write`); + userCallback.reject(error); + } +} +/** + * Applies one remote event to the sync engine, notifying any views of the + * changes, and releasing any pending mutation batches that would become + * visible because of the snapshot version the remote event contains. + */ +async function syncEngineApplyRemoteEvent(syncEngine, remoteEvent) { + const syncEngineImpl = debugCast(syncEngine); + try { + const changes = await localStoreApplyRemoteEventToLocalCache(syncEngineImpl.localStore, remoteEvent); + // Update `receivedDocument` as appropriate for any limbo targets. + remoteEvent.targetChanges.forEach((targetChange, targetId) => { + const limboResolution = syncEngineImpl.activeLimboResolutionsByTarget.get(targetId); + if (limboResolution) { + // Since this is a limbo resolution lookup, it's for a single document + // and it could be added, modified, or removed, but not a combination. + hardAssert(targetChange.addedDocuments.size + + targetChange.modifiedDocuments.size + + targetChange.removedDocuments.size <= + 1, 0x5858); + if (targetChange.addedDocuments.size > 0) { + limboResolution.receivedDocument = true; + } + else if (targetChange.modifiedDocuments.size > 0) { + hardAssert(limboResolution.receivedDocument, 0x390f); + } + else if (targetChange.removedDocuments.size > 0) { + hardAssert(limboResolution.receivedDocument, 0xa4f3); + limboResolution.receivedDocument = false; + } + else { + // This was probably just a CURRENT targetChange or similar. + } + } + }); + await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, changes, remoteEvent); + } + catch (error) { + await ignoreIfPrimaryLeaseLoss(error); + } +} +/** + * Applies an OnlineState change to the sync engine and notifies any views of + * the change. + */ +function syncEngineApplyOnlineStateChange(syncEngine, onlineState, source) { + const syncEngineImpl = debugCast(syncEngine); + // If we are the secondary client, we explicitly ignore the remote store's + // online state (the local client may go offline, even though the primary + // tab remains online) and only apply the primary tab's online state from + // SharedClientState. + if ((syncEngineImpl.isPrimaryClient && + source === 0 /* OnlineStateSource.RemoteStore */) || + (!syncEngineImpl.isPrimaryClient && + source === 1 /* OnlineStateSource.SharedClientState */)) { + const newViewSnapshots = []; + syncEngineImpl.queryViewsByQuery.forEach((query, queryView) => { + const viewChange = queryView.view.applyOnlineStateChange(onlineState); + if (viewChange.snapshot) { + newViewSnapshots.push(viewChange.snapshot); + } + }); + eventManagerOnOnlineStateChange(syncEngineImpl.eventManager, onlineState); + if (newViewSnapshots.length) { + syncEngineImpl.syncEngineListener.onWatchChange(newViewSnapshots); + } + syncEngineImpl.onlineState = onlineState; + if (syncEngineImpl.isPrimaryClient) { + syncEngineImpl.sharedClientState.setOnlineState(onlineState); + } + } +} +/** + * Rejects the listen for the given targetID. This can be triggered by the + * backend for any active target. + * + * @param syncEngine - The sync engine implementation. + * @param targetId - The targetID corresponds to one previously initiated by the + * user as part of TargetData passed to listen() on RemoteStore. + * @param err - A description of the condition that has forced the rejection. + * Nearly always this will be an indication that the user is no longer + * authorized to see the data matching the target. + */ +async function syncEngineRejectListen(syncEngine, targetId, err) { + const syncEngineImpl = debugCast(syncEngine); + // PORTING NOTE: Multi-tab only. + syncEngineImpl.sharedClientState.updateQueryState(targetId, 'rejected', err); + const limboResolution = syncEngineImpl.activeLimboResolutionsByTarget.get(targetId); + const limboKey = limboResolution && limboResolution.key; + if (limboKey) { + // TODO(klimt): We really only should do the following on permission + // denied errors, but we don't have the cause code here. + // It's a limbo doc. Create a synthetic event saying it was deleted. + // This is kind of a hack. Ideally, we would have a method in the local + // store to purge a document. However, it would be tricky to keep all of + // the local store's invariants with another method. + let documentUpdates = new SortedMap(DocumentKey.comparator); + // TODO(b/217189216): This limbo document should ideally have a read time, + // so that it is picked up by any read-time based scans. The backend, + // however, does not send a read time for target removals. + documentUpdates = documentUpdates.insert(limboKey, MutableDocument.newNoDocument(limboKey, SnapshotVersion.min())); + const resolvedLimboDocuments = documentKeySet().add(limboKey); + const event = new RemoteEvent(SnapshotVersion.min(), + /* targetChanges= */ new Map(), + /* targetMismatches= */ new SortedMap(primitiveComparator), documentUpdates, resolvedLimboDocuments); + await syncEngineApplyRemoteEvent(syncEngineImpl, event); + // Since this query failed, we won't want to manually unlisten to it. + // We only remove it from bookkeeping after we successfully applied the + // RemoteEvent. If `applyRemoteEvent()` throws, we want to re-listen to + // this query when the RemoteStore restarts the Watch stream, which should + // re-trigger the target failure. + syncEngineImpl.activeLimboTargetsByKey = + syncEngineImpl.activeLimboTargetsByKey.remove(limboKey); + syncEngineImpl.activeLimboResolutionsByTarget.delete(targetId); + pumpEnqueuedLimboResolutions(syncEngineImpl); + } + else { + await localStoreReleaseTarget(syncEngineImpl.localStore, targetId, + /* keepPersistedTargetData */ false) + .then(() => removeAndCleanupTarget(syncEngineImpl, targetId, err)) + .catch(ignoreIfPrimaryLeaseLoss); + } +} +async function syncEngineApplySuccessfulWrite(syncEngine, mutationBatchResult) { + const syncEngineImpl = debugCast(syncEngine); + const batchId = mutationBatchResult.batch.batchId; + try { + const changes = await localStoreAcknowledgeBatch(syncEngineImpl.localStore, mutationBatchResult); + // The local store may or may not be able to apply the write result and + // raise events immediately (depending on whether the watcher is caught + // up), so we raise user callbacks first so that they consistently happen + // before listen events. + processUserCallback(syncEngineImpl, batchId, /*error=*/ null); + triggerPendingWritesCallbacks(syncEngineImpl, batchId); + syncEngineImpl.sharedClientState.updateMutationState(batchId, 'acknowledged'); + await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, changes); + } + catch (error) { + await ignoreIfPrimaryLeaseLoss(error); + } +} +async function syncEngineRejectFailedWrite(syncEngine, batchId, error) { + const syncEngineImpl = debugCast(syncEngine); + try { + const changes = await localStoreRejectBatch(syncEngineImpl.localStore, batchId); + // The local store may or may not be able to apply the write result and + // raise events immediately (depending on whether the watcher is caught up), + // so we raise user callbacks first so that they consistently happen before + // listen events. + processUserCallback(syncEngineImpl, batchId, error); + triggerPendingWritesCallbacks(syncEngineImpl, batchId); + syncEngineImpl.sharedClientState.updateMutationState(batchId, 'rejected', error); + await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, changes); + } + catch (error) { + await ignoreIfPrimaryLeaseLoss(error); + } +} +/** + * Registers a user callback that resolves when all pending mutations at the moment of calling + * are acknowledged . + */ +async function syncEngineRegisterPendingWritesCallback(syncEngine, callback) { + const syncEngineImpl = debugCast(syncEngine); + if (!canUseNetwork(syncEngineImpl.remoteStore)) { + logDebug(LOG_TAG$3, 'The network is disabled. The task returned by ' + + "'awaitPendingWrites()' will not complete until the network is enabled."); + } + try { + const highestBatchId = await localStoreGetHighestUnacknowledgedBatchId(syncEngineImpl.localStore); + if (highestBatchId === BATCHID_UNKNOWN) { + // Trigger the callback right away if there is no pending writes at the moment. + callback.resolve(); + return; + } + const callbacks = syncEngineImpl.pendingWritesCallbacks.get(highestBatchId) || []; + callbacks.push(callback); + syncEngineImpl.pendingWritesCallbacks.set(highestBatchId, callbacks); + } + catch (e) { + const firestoreError = wrapInUserErrorIfRecoverable(e, 'Initialization of waitForPendingWrites() operation failed'); + callback.reject(firestoreError); + } +} +/** + * Triggers the callbacks that are waiting for this batch id to get acknowledged by server, + * if there are any. + */ +function triggerPendingWritesCallbacks(syncEngineImpl, batchId) { + (syncEngineImpl.pendingWritesCallbacks.get(batchId) || []).forEach(callback => { + callback.resolve(); + }); + syncEngineImpl.pendingWritesCallbacks.delete(batchId); +} +/** Reject all outstanding callbacks waiting for pending writes to complete. */ +function rejectOutstandingPendingWritesCallbacks(syncEngineImpl, errorMessage) { + syncEngineImpl.pendingWritesCallbacks.forEach(callbacks => { + callbacks.forEach(callback => { + callback.reject(new FirestoreError(Code.CANCELLED, errorMessage)); + }); + }); + syncEngineImpl.pendingWritesCallbacks.clear(); +} +function addMutationCallback(syncEngineImpl, batchId, callback) { + let newCallbacks = syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()]; + if (!newCallbacks) { + newCallbacks = new SortedMap(primitiveComparator); + } + newCallbacks = newCallbacks.insert(batchId, callback); + syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()] = + newCallbacks; +} +/** + * Resolves or rejects the user callback for the given batch and then discards + * it. + */ +function processUserCallback(syncEngine, batchId, error) { + const syncEngineImpl = debugCast(syncEngine); + let newCallbacks = syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()]; + // NOTE: Mutations restored from persistence won't have callbacks, so it's + // okay for there to be no callback for this ID. + if (newCallbacks) { + const callback = newCallbacks.get(batchId); + if (callback) { + if (error) { + callback.reject(error); + } + else { + callback.resolve(); + } + newCallbacks = newCallbacks.remove(batchId); + } + syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()] = + newCallbacks; + } +} +function removeAndCleanupTarget(syncEngineImpl, targetId, error = null) { + syncEngineImpl.sharedClientState.removeLocalQueryTarget(targetId); + for (const query of syncEngineImpl.queriesByTarget.get(targetId)) { + syncEngineImpl.queryViewsByQuery.delete(query); + if (error) { + syncEngineImpl.syncEngineListener.onWatchError(query, error); + } + } + syncEngineImpl.queriesByTarget.delete(targetId); + if (syncEngineImpl.isPrimaryClient) { + const limboKeys = syncEngineImpl.limboDocumentRefs.removeReferencesForId(targetId); + limboKeys.forEach(limboKey => { + const isReferenced = syncEngineImpl.limboDocumentRefs.containsKey(limboKey); + if (!isReferenced) { + // We removed the last reference for this key + removeLimboTarget(syncEngineImpl, limboKey); + } + }); + } +} +function removeLimboTarget(syncEngineImpl, key) { + syncEngineImpl.enqueuedLimboResolutions.delete(key.path.canonicalString()); + // It's possible that the target already got removed because the query failed. In that case, + // the key won't exist in `limboTargetsByKey`. Only do the cleanup if we still have the target. + const limboTargetId = syncEngineImpl.activeLimboTargetsByKey.get(key); + if (limboTargetId === null) { + // This target already got removed, because the query failed. + return; + } + remoteStoreUnlisten(syncEngineImpl.remoteStore, limboTargetId); + syncEngineImpl.activeLimboTargetsByKey = + syncEngineImpl.activeLimboTargetsByKey.remove(key); + syncEngineImpl.activeLimboResolutionsByTarget.delete(limboTargetId); + pumpEnqueuedLimboResolutions(syncEngineImpl); +} +function updateTrackedLimbos(syncEngineImpl, targetId, limboChanges) { + for (const limboChange of limboChanges) { + if (limboChange instanceof AddedLimboDocument) { + syncEngineImpl.limboDocumentRefs.addReference(limboChange.key, targetId); + trackLimboChange(syncEngineImpl, limboChange); + } + else if (limboChange instanceof RemovedLimboDocument) { + logDebug(LOG_TAG$3, 'Document no longer in limbo: ' + limboChange.key); + syncEngineImpl.limboDocumentRefs.removeReference(limboChange.key, targetId); + const isReferenced = syncEngineImpl.limboDocumentRefs.containsKey(limboChange.key); + if (!isReferenced) { + // We removed the last reference for this key + removeLimboTarget(syncEngineImpl, limboChange.key); + } + } + else { + fail(0x4d4f, { limboChange }); + } + } +} +function trackLimboChange(syncEngineImpl, limboChange) { + const key = limboChange.key; + const keyString = key.path.canonicalString(); + if (!syncEngineImpl.activeLimboTargetsByKey.get(key) && + !syncEngineImpl.enqueuedLimboResolutions.has(keyString)) { + logDebug(LOG_TAG$3, 'New document in limbo: ' + key); + syncEngineImpl.enqueuedLimboResolutions.add(keyString); + pumpEnqueuedLimboResolutions(syncEngineImpl); + } +} +/** + * Starts listens for documents in limbo that are enqueued for resolution, + * subject to a maximum number of concurrent resolutions. + * + * Without bounding the number of concurrent resolutions, the server can fail + * with "resource exhausted" errors which can lead to pathological client + * behavior as seen in https://github.com/firebase/firebase-js-sdk/issues/2683. + */ +function pumpEnqueuedLimboResolutions(syncEngineImpl) { + while (syncEngineImpl.enqueuedLimboResolutions.size > 0 && + syncEngineImpl.activeLimboTargetsByKey.size < + syncEngineImpl.maxConcurrentLimboResolutions) { + const keyString = syncEngineImpl.enqueuedLimboResolutions + .values() + .next().value; + syncEngineImpl.enqueuedLimboResolutions.delete(keyString); + const key = new DocumentKey(ResourcePath.fromString(keyString)); + const limboTargetId = syncEngineImpl.limboTargetIdGenerator.next(); + syncEngineImpl.activeLimboResolutionsByTarget.set(limboTargetId, new LimboResolution(key)); + syncEngineImpl.activeLimboTargetsByKey = + syncEngineImpl.activeLimboTargetsByKey.insert(key, limboTargetId); + remoteStoreListen(syncEngineImpl.remoteStore, new TargetData(queryToTarget(newQueryForPath(key.path)), limboTargetId, "TargetPurposeLimboResolution" /* TargetPurpose.LimboResolution */, ListenSequence.INVALID)); + } +} +async function syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngine, changes, remoteEvent) { + const syncEngineImpl = debugCast(syncEngine); + const newSnaps = []; + const docChangesInAllViews = []; + const queriesProcessed = []; + if (syncEngineImpl.queryViewsByQuery.isEmpty()) { + // Return early since `onWatchChange()` might not have been assigned yet. + return; + } + syncEngineImpl.queryViewsByQuery.forEach((_, queryView) => { + queriesProcessed.push(syncEngineImpl + .applyDocChanges(queryView, changes, remoteEvent) + .then(viewSnapshot => { + // If there are changes, or we are handling a global snapshot, notify + // secondary clients to update query state. + if (viewSnapshot || remoteEvent) { + if (syncEngineImpl.isPrimaryClient) { + // Query state is set to `current` if: + // - There is a view change and it is up-to-date, or, + // - There is a global snapshot, the Target is current, and no changes to be resolved + const isCurrent = viewSnapshot + ? !viewSnapshot.fromCache + : remoteEvent?.targetChanges.get(queryView.targetId)?.current; + syncEngineImpl.sharedClientState.updateQueryState(queryView.targetId, isCurrent ? 'current' : 'not-current'); + } + } + // Update views if there are actual changes. + if (!!viewSnapshot) { + newSnaps.push(viewSnapshot); + const docChanges = LocalViewChanges.fromSnapshot(queryView.targetId, viewSnapshot); + docChangesInAllViews.push(docChanges); + } + })); + }); + await Promise.all(queriesProcessed); + syncEngineImpl.syncEngineListener.onWatchChange(newSnaps); + await localStoreNotifyLocalViewChanges(syncEngineImpl.localStore, docChangesInAllViews); +} +async function applyDocChanges(syncEngineImpl, queryView, changes, remoteEvent) { + let viewDocChanges = queryView.view.computeDocChanges(changes); + if (viewDocChanges.needsRefill) { + // The query has a limit and some docs were removed, so we need + // to re-run the query against the local store to make sure we + // didn't lose any good docs that had been past the limit. + viewDocChanges = await localStoreExecuteQuery(syncEngineImpl.localStore, queryView.query, + /* usePreviousResults= */ false).then(({ documents }) => { + return queryView.view.computeDocChanges(documents, viewDocChanges); + }); + } + const targetChange = remoteEvent && remoteEvent.targetChanges.get(queryView.targetId); + const targetIsPendingReset = remoteEvent && remoteEvent.targetMismatches.get(queryView.targetId) != null; + const viewChange = queryView.view.applyChanges(viewDocChanges, + /* limboResolutionEnabled= */ syncEngineImpl.isPrimaryClient, targetChange, targetIsPendingReset); + updateTrackedLimbos(syncEngineImpl, queryView.targetId, viewChange.limboChanges); + return viewChange.snapshot; +} +async function syncEngineHandleCredentialChange(syncEngine, user) { + const syncEngineImpl = debugCast(syncEngine); + const userChanged = !syncEngineImpl.currentUser.isEqual(user); + if (userChanged) { + logDebug(LOG_TAG$3, 'User change. New user:', user.toKey()); + const result = await localStoreHandleUserChange(syncEngineImpl.localStore, user); + syncEngineImpl.currentUser = user; + // Fails tasks waiting for pending writes requested by previous user. + rejectOutstandingPendingWritesCallbacks(syncEngineImpl, "'waitForPendingWrites' promise is rejected due to a user change."); + // TODO(b/114226417): Consider calling this only in the primary tab. + syncEngineImpl.sharedClientState.handleUserChange(user, result.removedBatchIds, result.addedBatchIds); + await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, result.affectedDocuments); + } +} +function syncEngineGetRemoteKeysForTarget(syncEngine, targetId) { + const syncEngineImpl = debugCast(syncEngine); + const limboResolution = syncEngineImpl.activeLimboResolutionsByTarget.get(targetId); + if (limboResolution && limboResolution.receivedDocument) { + return documentKeySet().add(limboResolution.key); + } + else { + let keySet = documentKeySet(); + const queries = syncEngineImpl.queriesByTarget.get(targetId); + if (!queries) { + return keySet; + } + for (const query of queries) { + const queryView = syncEngineImpl.queryViewsByQuery.get(query); + keySet = keySet.unionWith(queryView.view.syncedDocuments); + } + return keySet; + } +} +/** + * Reconcile the list of synced documents in an existing view with those + * from persistence. + */ +async function synchronizeViewAndComputeSnapshot(syncEngine, queryView) { + const syncEngineImpl = debugCast(syncEngine); + const queryResult = await localStoreExecuteQuery(syncEngineImpl.localStore, queryView.query, + /* usePreviousResults= */ true); + const viewSnapshot = queryView.view.synchronizeWithPersistedState(queryResult); + if (syncEngineImpl.isPrimaryClient) { + updateTrackedLimbos(syncEngineImpl, queryView.targetId, viewSnapshot.limboChanges); + } + return viewSnapshot; +} +/** + * Retrieves newly changed documents from remote document cache and raises + * snapshots if needed. + */ +// PORTING NOTE: Multi-Tab only. +async function syncEngineSynchronizeWithChangedDocuments(syncEngine, collectionGroup) { + const syncEngineImpl = debugCast(syncEngine); + return localStoreGetNewDocumentChanges(syncEngineImpl.localStore, collectionGroup).then(changes => syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, changes)); +} +/** Applies a mutation state to an existing batch. */ +// PORTING NOTE: Multi-Tab only. +async function syncEngineApplyBatchState(syncEngine, batchId, batchState, error) { + const syncEngineImpl = debugCast(syncEngine); + const documents = await localStoreLookupMutationDocuments(syncEngineImpl.localStore, batchId); + if (documents === null) { + // A throttled tab may not have seen the mutation before it was completed + // and removed from the mutation queue, in which case we won't have cached + // the affected documents. In this case we can safely ignore the update + // since that means we didn't apply the mutation locally at all (if we + // had, we would have cached the affected documents), and so we will just + // see any resulting document changes via normal remote document updates + // as applicable. + logDebug(LOG_TAG$3, 'Cannot apply mutation batch with id: ' + batchId); + return; + } + if (batchState === 'pending') { + // If we are the primary client, we need to send this write to the + // backend. Secondary clients will ignore these writes since their remote + // connection is disabled. + await fillWritePipeline(syncEngineImpl.remoteStore); + } + else if (batchState === 'acknowledged' || batchState === 'rejected') { + // NOTE: Both these methods are no-ops for batches that originated from + // other clients. + processUserCallback(syncEngineImpl, batchId, error ? error : null); + triggerPendingWritesCallbacks(syncEngineImpl, batchId); + localStoreRemoveCachedMutationBatchMetadata(syncEngineImpl.localStore, batchId); + } + else { + fail(0x1a40, `Unknown batchState`, { batchState }); + } + await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, documents); +} +/** Applies a query target change from a different tab. */ +// PORTING NOTE: Multi-Tab only. +async function syncEngineApplyPrimaryState(syncEngine, isPrimary) { + const syncEngineImpl = debugCast(syncEngine); + ensureWatchCallbacks(syncEngineImpl); + syncEngineEnsureWriteCallbacks(syncEngineImpl); + if (isPrimary === true && syncEngineImpl._isPrimaryClient !== true) { + // Secondary tabs only maintain Views for their local listeners and the + // Views internal state may not be 100% populated (in particular + // secondary tabs don't track syncedDocuments, the set of documents the + // server considers to be in the target). So when a secondary becomes + // primary, we need to need to make sure that all views for all targets + // match the state on disk. + const activeTargets = syncEngineImpl.sharedClientState.getAllActiveQueryTargets(); + const activeQueries = await synchronizeQueryViewsAndRaiseSnapshots(syncEngineImpl, activeTargets.toArray()); + syncEngineImpl._isPrimaryClient = true; + await remoteStoreApplyPrimaryState(syncEngineImpl.remoteStore, true); + for (const targetData of activeQueries) { + remoteStoreListen(syncEngineImpl.remoteStore, targetData); + } + } + else if (isPrimary === false && syncEngineImpl._isPrimaryClient !== false) { + const activeTargets = []; + let p = Promise.resolve(); + syncEngineImpl.queriesByTarget.forEach((_, targetId) => { + if (syncEngineImpl.sharedClientState.isLocalQueryTarget(targetId)) { + activeTargets.push(targetId); + } + else { + p = p.then(() => { + removeAndCleanupTarget(syncEngineImpl, targetId); + return localStoreReleaseTarget(syncEngineImpl.localStore, targetId, + /*keepPersistedTargetData=*/ true); + }); + } + remoteStoreUnlisten(syncEngineImpl.remoteStore, targetId); + }); + await p; + await synchronizeQueryViewsAndRaiseSnapshots(syncEngineImpl, activeTargets); + resetLimboDocuments(syncEngineImpl); + syncEngineImpl._isPrimaryClient = false; + await remoteStoreApplyPrimaryState(syncEngineImpl.remoteStore, false); + } +} +// PORTING NOTE: Multi-Tab only. +function resetLimboDocuments(syncEngine) { + const syncEngineImpl = debugCast(syncEngine); + syncEngineImpl.activeLimboResolutionsByTarget.forEach((_, targetId) => { + remoteStoreUnlisten(syncEngineImpl.remoteStore, targetId); + }); + syncEngineImpl.limboDocumentRefs.removeAllReferences(); + syncEngineImpl.activeLimboResolutionsByTarget = new Map(); + syncEngineImpl.activeLimboTargetsByKey = new SortedMap(DocumentKey.comparator); +} +/** + * Reconcile the query views of the provided query targets with the state from + * persistence. Raises snapshots for any changes that affect the local + * client and returns the updated state of all target's query data. + * + * @param syncEngine - The sync engine implementation + * @param targets - the list of targets with views that need to be recomputed + * @param transitionToPrimary - `true` iff the tab transitions from a secondary + * tab to a primary tab + */ +// PORTING NOTE: Multi-Tab only. +async function synchronizeQueryViewsAndRaiseSnapshots(syncEngine, targets, transitionToPrimary) { + const syncEngineImpl = debugCast(syncEngine); + const activeQueries = []; + const newViewSnapshots = []; + for (const targetId of targets) { + let targetData; + const queries = syncEngineImpl.queriesByTarget.get(targetId); + if (queries && queries.length !== 0) { + // For queries that have a local View, we fetch their current state + // from LocalStore (as the resume token and the snapshot version + // might have changed) and reconcile their views with the persisted + // state (the list of syncedDocuments may have gotten out of sync). + targetData = await localStoreAllocateTarget(syncEngineImpl.localStore, queryToTarget(queries[0])); + for (const query of queries) { + const queryView = syncEngineImpl.queryViewsByQuery.get(query); + const viewChange = await synchronizeViewAndComputeSnapshot(syncEngineImpl, queryView); + if (viewChange.snapshot) { + newViewSnapshots.push(viewChange.snapshot); + } + } + } + else { + // For queries that never executed on this client, we need to + // allocate the target in LocalStore and initialize a new View. + const target = await localStoreGetCachedTarget(syncEngineImpl.localStore, targetId); + targetData = await localStoreAllocateTarget(syncEngineImpl.localStore, target); + await initializeViewAndComputeSnapshot(syncEngineImpl, synthesizeTargetToQuery(target), targetId, + /*current=*/ false, targetData.resumeToken); + } + activeQueries.push(targetData); + } + syncEngineImpl.syncEngineListener.onWatchChange(newViewSnapshots); + return activeQueries; +} +/** + * Creates a `Query` object from the specified `Target`. There is no way to + * obtain the original `Query`, so we synthesize a `Query` from the `Target` + * object. + * + * The synthesized result might be different from the original `Query`, but + * since the synthesized `Query` should return the same results as the + * original one (only the presentation of results might differ), the potential + * difference will not cause issues. + */ +// PORTING NOTE: Multi-Tab only. +function synthesizeTargetToQuery(target) { + return newQuery(target.path, target.collectionGroup, target.orderBy, target.filters, target.limit, "F" /* LimitType.First */, target.startAt, target.endAt); +} +/** Returns the IDs of the clients that are currently active. */ +// PORTING NOTE: Multi-Tab only. +function syncEngineGetActiveClients(syncEngine) { + const syncEngineImpl = debugCast(syncEngine); + return localStoreGetActiveClients(syncEngineImpl.localStore); +} +/** Applies a query target change from a different tab. */ +// PORTING NOTE: Multi-Tab only. +async function syncEngineApplyTargetState(syncEngine, targetId, state, error) { + const syncEngineImpl = debugCast(syncEngine); + if (syncEngineImpl._isPrimaryClient) { + // If we receive a target state notification via WebStorage, we are + // either already secondary or another tab has taken the primary lease. + logDebug(LOG_TAG$3, 'Ignoring unexpected query state notification.'); + return; + } + const query = syncEngineImpl.queriesByTarget.get(targetId); + if (query && query.length > 0) { + switch (state) { + case 'current': + case 'not-current': { + const changes = await localStoreGetNewDocumentChanges(syncEngineImpl.localStore, queryCollectionGroup(query[0])); + const synthesizedRemoteEvent = RemoteEvent.createSynthesizedRemoteEventForCurrentChange(targetId, state === 'current', ByteString.EMPTY_BYTE_STRING); + await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, changes, synthesizedRemoteEvent); + break; + } + case 'rejected': { + await localStoreReleaseTarget(syncEngineImpl.localStore, targetId, + /* keepPersistedTargetData */ true); + removeAndCleanupTarget(syncEngineImpl, targetId, error); + break; + } + default: + fail(0xfa9b, state); + } + } +} +/** Adds or removes Watch targets for queries from different tabs. */ +async function syncEngineApplyActiveTargetsChange(syncEngine, added, removed) { + const syncEngineImpl = ensureWatchCallbacks(syncEngine); + if (!syncEngineImpl._isPrimaryClient) { + return; + } + for (const targetId of added) { + // A target is already listening to remote store if it is already registered to + // sharedClientState. + const targetAlreadyListeningToRemoteStore = syncEngineImpl.queriesByTarget.has(targetId) && + syncEngineImpl.sharedClientState.isActiveQueryTarget(targetId); + if (targetAlreadyListeningToRemoteStore) { + logDebug(LOG_TAG$3, 'Adding an already active target ' + targetId); + continue; + } + const target = await localStoreGetCachedTarget(syncEngineImpl.localStore, targetId); + const targetData = await localStoreAllocateTarget(syncEngineImpl.localStore, target); + await initializeViewAndComputeSnapshot(syncEngineImpl, synthesizeTargetToQuery(target), targetData.targetId, + /*current=*/ false, targetData.resumeToken); + remoteStoreListen(syncEngineImpl.remoteStore, targetData); + } + for (const targetId of removed) { + // Check that the target is still active since the target might have been + // removed if it has been rejected by the backend. + if (!syncEngineImpl.queriesByTarget.has(targetId)) { + continue; + } + // Release queries that are still active. + await localStoreReleaseTarget(syncEngineImpl.localStore, targetId, + /* keepPersistedTargetData */ false) + .then(() => { + remoteStoreUnlisten(syncEngineImpl.remoteStore, targetId); + removeAndCleanupTarget(syncEngineImpl, targetId); + }) + .catch(ignoreIfPrimaryLeaseLoss); + } +} +function ensureWatchCallbacks(syncEngine) { + const syncEngineImpl = debugCast(syncEngine); + syncEngineImpl.remoteStore.remoteSyncer.applyRemoteEvent = + syncEngineApplyRemoteEvent.bind(null, syncEngineImpl); + syncEngineImpl.remoteStore.remoteSyncer.getRemoteKeysForTarget = + syncEngineGetRemoteKeysForTarget.bind(null, syncEngineImpl); + syncEngineImpl.remoteStore.remoteSyncer.rejectListen = + syncEngineRejectListen.bind(null, syncEngineImpl); + syncEngineImpl.syncEngineListener.onWatchChange = + eventManagerOnWatchChange.bind(null, syncEngineImpl.eventManager); + syncEngineImpl.syncEngineListener.onWatchError = + eventManagerOnWatchError.bind(null, syncEngineImpl.eventManager); + return syncEngineImpl; +} +function syncEngineEnsureWriteCallbacks(syncEngine) { + const syncEngineImpl = debugCast(syncEngine); + syncEngineImpl.remoteStore.remoteSyncer.applySuccessfulWrite = + syncEngineApplySuccessfulWrite.bind(null, syncEngineImpl); + syncEngineImpl.remoteStore.remoteSyncer.rejectFailedWrite = + syncEngineRejectFailedWrite.bind(null, syncEngineImpl); + return syncEngineImpl; +} +/** + * Loads a Firestore bundle into the SDK. The returned promise resolves when + * the bundle finished loading. + * + * @param syncEngine - SyncEngine to use. + * @param bundleReader - Bundle to load into the SDK. + * @param task - LoadBundleTask used to update the loading progress to public API. + */ +function syncEngineLoadBundle(syncEngine, bundleReader, task) { + const syncEngineImpl = debugCast(syncEngine); + // eslint-disable-next-line @typescript-eslint/no-floating-promises + loadBundleImpl(syncEngineImpl, bundleReader, task).then(collectionGroups => { + syncEngineImpl.sharedClientState.notifyBundleLoaded(collectionGroups); + }); +} +/** Loads a bundle and returns the list of affected collection groups. */ +async function loadBundleImpl(syncEngine, reader, task) { + try { + const metadata = await reader.getMetadata(); + const skip = await localStoreHasNewerBundle(syncEngine.localStore, metadata); + if (skip) { + await reader.close(); + task._completeWith(bundleSuccessProgress(metadata)); + return Promise.resolve(new Set()); + } + task._updateProgress(bundleInitialProgress(metadata)); + const loader = new BundleLoader(metadata, reader.serializer); + let element = await reader.nextElement(); + while (element) { + ; + const progress = await loader.addSizedElement(element); + if (progress) { + task._updateProgress(progress); + } + element = await reader.nextElement(); + } + const result = await loader.completeAndStoreAsync(syncEngine.localStore); + await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngine, result.changedDocs, + /* remoteEvent */ undefined); + // Save metadata, so loading the same bundle will skip. + await localStoreSaveBundle(syncEngine.localStore, metadata); + task._completeWith(result.progress); + return Promise.resolve(result.changedCollectionGroups); + } + catch (e) { + logWarn(LOG_TAG$3, `Loading bundle failed with ${e}`); + task._failWith(e); + return Promise.resolve(new Set()); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provides all components needed for Firestore with in-memory persistence. + * Uses EagerGC garbage collection. + */ +class MemoryOfflineComponentProvider { + constructor() { + this.kind = 'memory'; + this.synchronizeTabs = false; + } + async initialize(cfg) { + this.serializer = newSerializer(cfg.databaseInfo.databaseId); + this.sharedClientState = this.createSharedClientState(cfg); + this.persistence = this.createPersistence(cfg); + await this.persistence.start(); + this.localStore = this.createLocalStore(cfg); + this.gcScheduler = this.createGarbageCollectionScheduler(cfg, this.localStore); + this.indexBackfillerScheduler = this.createIndexBackfillerScheduler(cfg, this.localStore); + } + createGarbageCollectionScheduler(cfg, localStore) { + return null; + } + createIndexBackfillerScheduler(cfg, localStore) { + return null; + } + createLocalStore(cfg) { + return newLocalStore(this.persistence, new QueryEngine(), cfg.initialUser, this.serializer); + } + createPersistence(cfg) { + return new MemoryPersistence(MemoryEagerDelegate.factory, this.serializer); + } + createSharedClientState(cfg) { + return new MemorySharedClientState(); + } + async terminate() { + this.gcScheduler?.stop(); + this.indexBackfillerScheduler?.stop(); + this.sharedClientState.shutdown(); + await this.persistence.shutdown(); + } +} +MemoryOfflineComponentProvider.provider = { + build: () => new MemoryOfflineComponentProvider() +}; +class LruGcMemoryOfflineComponentProvider extends MemoryOfflineComponentProvider { + constructor(cacheSizeBytes) { + super(); + this.cacheSizeBytes = cacheSizeBytes; + } + createGarbageCollectionScheduler(cfg, localStore) { + hardAssert(this.persistence.referenceDelegate instanceof MemoryLruDelegate, 0xb743); + const garbageCollector = this.persistence.referenceDelegate.garbageCollector; + return new LruScheduler(garbageCollector, cfg.asyncQueue, localStore); + } + createPersistence(cfg) { + const lruParams = this.cacheSizeBytes !== undefined + ? LruParams.withCacheSize(this.cacheSizeBytes) + : LruParams.DEFAULT; + return new MemoryPersistence(p => MemoryLruDelegate.factory(p, lruParams), this.serializer); + } +} +/** + * Provides all components needed for Firestore with IndexedDB persistence. + */ +class IndexedDbOfflineComponentProvider extends MemoryOfflineComponentProvider { + constructor(onlineComponentProvider, cacheSizeBytes, forceOwnership) { + super(); + this.onlineComponentProvider = onlineComponentProvider; + this.cacheSizeBytes = cacheSizeBytes; + this.forceOwnership = forceOwnership; + this.kind = 'persistent'; + this.synchronizeTabs = false; + } + async initialize(cfg) { + await super.initialize(cfg); + await this.onlineComponentProvider.initialize(this, cfg); + // Enqueue writes from a previous session + await syncEngineEnsureWriteCallbacks(this.onlineComponentProvider.syncEngine); + await fillWritePipeline(this.onlineComponentProvider.remoteStore); + // NOTE: This will immediately call the listener, so we make sure to + // set it after localStore / remoteStore are started. + await this.persistence.setPrimaryStateListener(() => { + if (this.gcScheduler && !this.gcScheduler.started) { + this.gcScheduler.start(); + } + if (this.indexBackfillerScheduler && + !this.indexBackfillerScheduler.started) { + this.indexBackfillerScheduler.start(); + } + return Promise.resolve(); + }); + } + createLocalStore(cfg) { + return newLocalStore(this.persistence, new QueryEngine(), cfg.initialUser, this.serializer); + } + createGarbageCollectionScheduler(cfg, localStore) { + const garbageCollector = this.persistence.referenceDelegate.garbageCollector; + return new LruScheduler(garbageCollector, cfg.asyncQueue, localStore); + } + createIndexBackfillerScheduler(cfg, localStore) { + const indexBackfiller = new IndexBackfiller(localStore, this.persistence); + return new IndexBackfillerScheduler(cfg.asyncQueue, indexBackfiller); + } + createPersistence(cfg) { + const persistenceKey = indexedDbStoragePrefix(cfg.databaseInfo.databaseId, cfg.databaseInfo.persistenceKey); + const lruParams = this.cacheSizeBytes !== undefined + ? LruParams.withCacheSize(this.cacheSizeBytes) + : LruParams.DEFAULT; + return new IndexedDbPersistence(this.synchronizeTabs, persistenceKey, cfg.clientId, lruParams, cfg.asyncQueue, getWindow(), getDocument(), this.serializer, this.sharedClientState, !!this.forceOwnership); + } + createSharedClientState(cfg) { + return new MemorySharedClientState(); + } +} +/** + * Provides all components needed for Firestore with multi-tab IndexedDB + * persistence. + * + * In the legacy client, this provider is used to provide both multi-tab and + * non-multi-tab persistence since we cannot tell at build time whether + * `synchronizeTabs` will be enabled. + */ +class MultiTabOfflineComponentProvider extends IndexedDbOfflineComponentProvider { + constructor(onlineComponentProvider, cacheSizeBytes) { + super(onlineComponentProvider, cacheSizeBytes, /* forceOwnership= */ false); + this.onlineComponentProvider = onlineComponentProvider; + this.cacheSizeBytes = cacheSizeBytes; + this.synchronizeTabs = true; + } + async initialize(cfg) { + await super.initialize(cfg); + const syncEngine = this.onlineComponentProvider.syncEngine; + if (this.sharedClientState instanceof WebStorageSharedClientState) { + this.sharedClientState.syncEngine = { + applyBatchState: syncEngineApplyBatchState.bind(null, syncEngine), + applyTargetState: syncEngineApplyTargetState.bind(null, syncEngine), + applyActiveTargetsChange: syncEngineApplyActiveTargetsChange.bind(null, syncEngine), + getActiveClients: syncEngineGetActiveClients.bind(null, syncEngine), + synchronizeWithChangedDocuments: syncEngineSynchronizeWithChangedDocuments.bind(null, syncEngine) + }; + await this.sharedClientState.start(); + } + // NOTE: This will immediately call the listener, so we make sure to + // set it after localStore / remoteStore are started. + await this.persistence.setPrimaryStateListener(async (isPrimary) => { + await syncEngineApplyPrimaryState(this.onlineComponentProvider.syncEngine, isPrimary); + if (this.gcScheduler) { + if (isPrimary && !this.gcScheduler.started) { + this.gcScheduler.start(); + } + else if (!isPrimary) { + this.gcScheduler.stop(); + } + } + if (this.indexBackfillerScheduler) { + if (isPrimary && !this.indexBackfillerScheduler.started) { + this.indexBackfillerScheduler.start(); + } + else if (!isPrimary) { + this.indexBackfillerScheduler.stop(); + } + } + }); + } + createSharedClientState(cfg) { + const window = getWindow(); + if (!WebStorageSharedClientState.isAvailable(window)) { + throw new FirestoreError(Code.UNIMPLEMENTED, 'IndexedDB persistence is only available on platforms that support LocalStorage.'); + } + const persistenceKey = indexedDbStoragePrefix(cfg.databaseInfo.databaseId, cfg.databaseInfo.persistenceKey); + return new WebStorageSharedClientState(window, cfg.asyncQueue, persistenceKey, cfg.clientId, cfg.initialUser); + } +} +/** + * Initializes and wires the components that are needed to interface with the + * network. + */ +class OnlineComponentProvider { + async initialize(offlineComponentProvider, cfg) { + if (this.localStore) { + // OnlineComponentProvider may get initialized multiple times if + // multi-tab persistence is used. + return; + } + this.localStore = offlineComponentProvider.localStore; + this.sharedClientState = offlineComponentProvider.sharedClientState; + this.datastore = this.createDatastore(cfg); + this.remoteStore = this.createRemoteStore(cfg); + this.eventManager = this.createEventManager(cfg); + this.syncEngine = this.createSyncEngine(cfg, + /* startAsPrimary=*/ !offlineComponentProvider.synchronizeTabs); + this.sharedClientState.onlineStateHandler = onlineState => syncEngineApplyOnlineStateChange(this.syncEngine, onlineState, 1 /* OnlineStateSource.SharedClientState */); + this.remoteStore.remoteSyncer.handleCredentialChange = + syncEngineHandleCredentialChange.bind(null, this.syncEngine); + await remoteStoreApplyPrimaryState(this.remoteStore, this.syncEngine.isPrimaryClient); + } + createEventManager(cfg) { + return newEventManager(); + } + createDatastore(cfg) { + const serializer = newSerializer(cfg.databaseInfo.databaseId); + const connection = newConnection(cfg.databaseInfo); + return newDatastore(cfg.authCredentials, cfg.appCheckCredentials, connection, serializer); + } + createRemoteStore(cfg) { + return newRemoteStore(this.localStore, this.datastore, cfg.asyncQueue, onlineState => syncEngineApplyOnlineStateChange(this.syncEngine, onlineState, 0 /* OnlineStateSource.RemoteStore */), newConnectivityMonitor()); + } + createSyncEngine(cfg, startAsPrimary) { + return newSyncEngine(this.localStore, this.remoteStore, this.eventManager, this.sharedClientState, cfg.initialUser, cfg.maxConcurrentLimboResolutions, startAsPrimary); + } + async terminate() { + await remoteStoreShutdown(this.remoteStore); + this.datastore?.terminate(); + this.eventManager?.terminate(); + } +} +OnlineComponentProvider.provider = { + build: () => new OnlineComponentProvider() +}; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * How many bytes to read each time when `ReadableStreamReader.read()` is + * called. Only applicable for byte streams that we control (e.g. those backed + * by an UInt8Array). + */ +const DEFAULT_BYTES_PER_READ = 10240; +/** + * Builds a `ByteStreamReader` from a UInt8Array. + * @param source - The data source to use. + * @param bytesPerRead - How many bytes each `read()` from the returned reader + * will read. + */ +function toByteStreamReaderHelper(source, bytesPerRead = DEFAULT_BYTES_PER_READ) { + let readFrom = 0; + // The TypeScript definition for ReadableStreamReader changed. We use + // `any` here to allow this code to compile with different versions. + // See https://github.com/microsoft/TypeScript/issues/42970 + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const reader = { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + async read() { + if (readFrom < source.byteLength) { + const result = { + value: source.slice(readFrom, readFrom + bytesPerRead), + done: false + }; + readFrom += bytesPerRead; + return result; + } + return { done: true }; + }, + async cancel() { }, + releaseLock() { }, + closed: Promise.resolve() + }; + return reader; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * On Node, only supported data source is a `Uint8Array` for now. + */ +function toByteStreamReader(source, bytesPerRead) { + if (!(source instanceof Uint8Array)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `NodePlatform.toByteStreamReader expects source to be Uint8Array, got ${valueDescription(source)}`); + } + return toByteStreamReaderHelper(source, bytesPerRead); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * A wrapper implementation of Observer that will dispatch events + * asynchronously. To allow immediate silencing, a mute call is added which + * causes events scheduled to no longer be raised. + */ +class AsyncObserver { + constructor(observer) { + this.observer = observer; + /** + * When set to true, will not raise future events. Necessary to deal with + * async detachment of listener. + */ + this.muted = false; + } + next(value) { + if (this.muted) { + return; + } + if (this.observer.next) { + this.scheduleEvent(this.observer.next, value); + } + } + error(error) { + if (this.muted) { + return; + } + if (this.observer.error) { + this.scheduleEvent(this.observer.error, error); + } + else { + logError('Uncaught Error in snapshot listener:', error.toString()); + } + } + mute() { + this.muted = true; + } + scheduleEvent(eventHandler, event) { + setTimeout(() => { + if (!this.muted) { + eventHandler(event); + } + }, 0); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A complete element in the bundle stream, together with the byte length it + * occupies in the stream. + */ +class SizedBundleElement { + constructor(payload, + // How many bytes this element takes to store in the bundle. + byteLength) { + this.payload = payload; + this.byteLength = byteLength; + } + isBundleMetadata() { + return 'metadata' in this.payload; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A class representing a bundle. + * + * Takes a bundle stream or buffer, and presents abstractions to read bundled + * elements out of the underlying content. + */ +class BundleReaderImpl { + constructor( + /** The reader to read from underlying binary bundle data source. */ + reader, serializer) { + this.reader = reader; + this.serializer = serializer; + /** Cached bundle metadata. */ + this.metadata = new Deferred(); + /** + * Internal buffer to hold bundle content, accumulating incomplete element + * content. + */ + this.buffer = new Uint8Array(); + this.textDecoder = newTextDecoder(); + // Read the metadata (which is the first element). + this.nextElementImpl().then(element => { + if (element && element.isBundleMetadata()) { + this.metadata.resolve(element.payload.metadata); + } + else { + this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is + ${JSON.stringify(element?.payload)}`)); + } + }, error => this.metadata.reject(error)); + } + close() { + return this.reader.cancel(); + } + async getMetadata() { + return this.metadata.promise; + } + async nextElement() { + // Makes sure metadata is read before proceeding. + await this.getMetadata(); + return this.nextElementImpl(); + } + /** + * Reads from the head of internal buffer, and pulling more data from + * underlying stream if a complete element cannot be found, until an + * element(including the prefixed length and the JSON string) is found. + * + * Once a complete element is read, it is dropped from internal buffer. + * + * Returns either the bundled element, or null if we have reached the end of + * the stream. + */ + async nextElementImpl() { + const lengthBuffer = await this.readLength(); + if (lengthBuffer === null) { + return null; + } + const lengthString = this.textDecoder.decode(lengthBuffer); + const length = Number(lengthString); + if (isNaN(length)) { + this.raiseError(`length string (${lengthString}) is not valid number`); + } + const jsonString = await this.readJsonString(length); + return new SizedBundleElement(JSON.parse(jsonString), lengthBuffer.length + length); + } + /** First index of '{' from the underlying buffer. */ + indexOfOpenBracket() { + return this.buffer.findIndex(v => v === '{'.charCodeAt(0)); + } + /** + * Reads from the beginning of the internal buffer, until the first '{', and + * return the content. + * + * If reached end of the stream, returns a null. + */ + async readLength() { + while (this.indexOfOpenBracket() < 0) { + const done = await this.pullMoreDataToBuffer(); + if (done) { + break; + } + } + // Broke out of the loop because underlying stream is closed, and there + // happens to be no more data to process. + if (this.buffer.length === 0) { + return null; + } + const position = this.indexOfOpenBracket(); + // Broke out of the loop because underlying stream is closed, but still + // cannot find an open bracket. + if (position < 0) { + this.raiseError('Reached the end of bundle when a length string is expected.'); + } + const result = this.buffer.slice(0, position); + // Update the internal buffer to drop the read length. + this.buffer = this.buffer.slice(position); + return result; + } + /** + * Reads from a specified position from the internal buffer, for a specified + * number of bytes, pulling more data from the underlying stream if needed. + * + * Returns a string decoded from the read bytes. + */ + async readJsonString(length) { + while (this.buffer.length < length) { + const done = await this.pullMoreDataToBuffer(); + if (done) { + this.raiseError('Reached the end of bundle when more is expected.'); + } + } + const result = this.textDecoder.decode(this.buffer.slice(0, length)); + // Update the internal buffer to drop the read json string. + this.buffer = this.buffer.slice(length); + return result; + } + raiseError(message) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.reader.cancel(); + throw new Error(`Invalid bundle format: ${message}`); + } + /** + * Pulls more data from underlying stream to internal buffer. + * Returns a boolean indicating whether the stream is finished. + */ + async pullMoreDataToBuffer() { + const result = await this.reader.read(); + if (!result.done) { + const newBuffer = new Uint8Array(this.buffer.length + result.value.length); + newBuffer.set(this.buffer); + newBuffer.set(result.value, this.buffer.length); + this.buffer = newBuffer; + } + return result.done; + } +} +function newBundleReader(reader, serializer) { + return new BundleReaderImpl(reader, serializer); +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A class that can parse a bundle form the string serialization of a bundle. + */ +class BundleReaderSyncImpl { + constructor(bundleData, serializer) { + this.bundleData = bundleData; + this.serializer = serializer; + this.cursor = 0; + this.elements = []; + let element = this.nextElement(); + if (element && element.isBundleMetadata()) { + this.metadata = element; + } + else { + throw new Error(`The first element of the bundle is not a metadata object, it is + ${JSON.stringify(element?.payload)}`); + } + do { + element = this.nextElement(); + if (element !== null) { + this.elements.push(element); + } + } while (element !== null); + } + /* Returns the parsed metadata of the bundle. */ + getMetadata() { + return this.metadata; + } + /* Returns the DocumentSnapshot or NamedQuery elements of the bundle. */ + getElements() { + return this.elements; + } + /** + * Parses the next element of the bundle. + * + * @returns a SizedBundleElement representation of the next element in the bundle, or null if + * no more elements exist. + */ + nextElement() { + if (this.cursor === this.bundleData.length) { + return null; + } + const length = this.readLength(); + const jsonString = this.readJsonString(length); + return new SizedBundleElement(JSON.parse(jsonString), length); + } + /** + * Reads from a specified position from the bundleData string, for a specified + * number of bytes. + * + * @param length how many characters to read. + * @returns a string parsed from the bundle. + */ + readJsonString(length) { + if (this.cursor + length > this.bundleData.length) { + throw new FirestoreError(Code.INTERNAL, 'Reached the end of bundle when more is expected.'); + } + const result = this.bundleData.slice(this.cursor, (this.cursor += length)); + return result; + } + /** + * Reads from the current cursor until the first '{'. + * + * @returns A string to integer represention of the parsed value. + * @throws An {@link Error} if the cursor has reached the end of the stream, since lengths + * prefix bundle objects. + */ + readLength() { + const startIndex = this.cursor; + let curIndex = this.cursor; + while (curIndex < this.bundleData.length) { + if (this.bundleData[curIndex] === '{') { + if (curIndex === startIndex) { + throw new Error('First character is a bracket and not a number'); + } + this.cursor = curIndex; + return Number(this.bundleData.slice(startIndex, curIndex)); + } + curIndex++; + } + throw new Error('Reached the end of bundle when more is expected.'); + } +} +/** + * Creates an instance of BundleReader without exposing the BundleReaderSyncImpl class type. + */ +function newBundleReaderSync(bundleData, serializer) { + return new BundleReaderSyncImpl(bundleData, serializer); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Internal transaction object responsible for accumulating the mutations to + * perform and the base versions for any documents read. + */ +class Transaction$2 { + constructor(datastore) { + this.datastore = datastore; + // The version of each document that was read during this transaction. + this.readVersions = new Map(); + this.mutations = []; + this.committed = false; + /** + * A deferred usage error that occurred previously in this transaction that + * will cause the transaction to fail once it actually commits. + */ + this.lastTransactionError = null; + /** + * Set of documents that have been written in the transaction. + * + * When there's more than one write to the same key in a transaction, any + * writes after the first are handled differently. + */ + this.writtenDocs = new Set(); + } + async lookup(keys) { + this.ensureCommitNotCalled(); + if (this.mutations.length > 0) { + this.lastTransactionError = new FirestoreError(Code.INVALID_ARGUMENT, 'Firestore transactions require all reads to be executed before all writes.'); + throw this.lastTransactionError; + } + const docs = await invokeBatchGetDocumentsRpc(this.datastore, keys); + docs.forEach(doc => this.recordVersion(doc)); + return docs; + } + set(key, data) { + this.write(data.toMutation(key, this.precondition(key))); + this.writtenDocs.add(key.toString()); + } + update(key, data) { + try { + this.write(data.toMutation(key, this.preconditionForUpdate(key))); + } + catch (e) { + this.lastTransactionError = e; + } + this.writtenDocs.add(key.toString()); + } + delete(key) { + this.write(new DeleteMutation(key, this.precondition(key))); + this.writtenDocs.add(key.toString()); + } + async commit() { + this.ensureCommitNotCalled(); + if (this.lastTransactionError) { + throw this.lastTransactionError; + } + const unwritten = this.readVersions; + // For each mutation, note that the doc was written. + this.mutations.forEach(mutation => { + unwritten.delete(mutation.key.toString()); + }); + // For each document that was read but not written to, we want to perform + // a `verify` operation. + unwritten.forEach((_, path) => { + const key = DocumentKey.fromPath(path); + this.mutations.push(new VerifyMutation(key, this.precondition(key))); + }); + await invokeCommitRpc(this.datastore, this.mutations); + this.committed = true; + } + recordVersion(doc) { + let docVersion; + if (doc.isFoundDocument()) { + docVersion = doc.version; + } + else if (doc.isNoDocument()) { + // Represent a deleted doc using SnapshotVersion.min(). + docVersion = SnapshotVersion.min(); + } + else { + throw fail(0xc542, { + documentName: doc.constructor.name + }); + } + const existingVersion = this.readVersions.get(doc.key.toString()); + if (existingVersion) { + if (!docVersion.isEqual(existingVersion)) { + // This transaction will fail no matter what. + throw new FirestoreError(Code.ABORTED, 'Document version changed between two reads.'); + } + } + else { + this.readVersions.set(doc.key.toString(), docVersion); + } + } + /** + * Returns the version of this document when it was read in this transaction, + * as a precondition, or no precondition if it was not read. + */ + precondition(key) { + const version = this.readVersions.get(key.toString()); + if (!this.writtenDocs.has(key.toString()) && version) { + if (version.isEqual(SnapshotVersion.min())) { + return Precondition.exists(false); + } + else { + return Precondition.updateTime(version); + } + } + else { + return Precondition.none(); + } + } + /** + * Returns the precondition for a document if the operation is an update. + */ + preconditionForUpdate(key) { + const version = this.readVersions.get(key.toString()); + // The first time a document is written, we want to take into account the + // read time and existence + if (!this.writtenDocs.has(key.toString()) && version) { + if (version.isEqual(SnapshotVersion.min())) { + // The document doesn't exist, so fail the transaction. + // This has to be validated locally because you can't send a + // precondition that a document does not exist without changing the + // semantics of the backend write to be an insert. This is the reverse + // of what we want, since we want to assert that the document doesn't + // exist but then send the update and have it fail. Since we can't + // express that to the backend, we have to validate locally. + // Note: this can change once we can send separate verify writes in the + // transaction. + throw new FirestoreError(Code.INVALID_ARGUMENT, "Can't update a document that doesn't exist."); + } + // Document exists, base precondition on document update time. + return Precondition.updateTime(version); + } + else { + // Document was not read, so we just use the preconditions for a blind + // update. + return Precondition.exists(true); + } + } + write(mutation) { + this.ensureCommitNotCalled(); + this.mutations.push(mutation); + } + ensureCommitNotCalled() { + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * TransactionRunner encapsulates the logic needed to run and retry transactions + * with backoff. + */ +class TransactionRunner { + constructor(asyncQueue, datastore, options, updateFunction, deferred) { + this.asyncQueue = asyncQueue; + this.datastore = datastore; + this.options = options; + this.updateFunction = updateFunction; + this.deferred = deferred; + this.attemptsRemaining = options.maxAttempts; + this.backoff = new ExponentialBackoff(this.asyncQueue, "transaction_retry" /* TimerId.TransactionRetry */); + } + /** Runs the transaction and sets the result on deferred. */ + run() { + this.attemptsRemaining -= 1; + this.runWithBackOff(); + } + runWithBackOff() { + this.backoff.backoffAndRun(async () => { + const transaction = new Transaction$2(this.datastore); + const userPromise = this.tryRunUpdateFunction(transaction); + if (userPromise) { + userPromise + .then(result => { + this.asyncQueue.enqueueAndForget(() => { + return transaction + .commit() + .then(() => { + this.deferred.resolve(result); + }) + .catch(commitError => { + this.handleTransactionError(commitError); + }); + }); + }) + .catch(userPromiseError => { + this.handleTransactionError(userPromiseError); + }); + } + }); + } + tryRunUpdateFunction(transaction) { + try { + const userPromise = this.updateFunction(transaction); + if (isNullOrUndefined(userPromise) || + !userPromise.catch || + !userPromise.then) { + this.deferred.reject(Error('Transaction callback must return a Promise')); + return null; + } + return userPromise; + } + catch (error) { + // Do not retry errors thrown by user provided updateFunction. + this.deferred.reject(error); + return null; + } + } + handleTransactionError(error) { + if (this.attemptsRemaining > 0 && this.isRetryableTransactionError(error)) { + this.attemptsRemaining -= 1; + this.asyncQueue.enqueueAndForget(() => { + this.runWithBackOff(); + return Promise.resolve(); + }); + } + else { + this.deferred.reject(error); + } + } + isRetryableTransactionError(error) { + if (error?.name === 'FirebaseError') { + // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and + // non-matching document versions with ABORTED. These errors should be retried. + const code = error.code; + return (code === 'aborted' || + code === 'failed-precondition' || + code === 'already-exists' || + !isPermanentError(code)); + } + return false; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$2 = 'FirestoreClient'; +const MAX_CONCURRENT_LIMBO_RESOLUTIONS = 100; +/** DOMException error code constants. */ +const DOM_EXCEPTION_INVALID_STATE = 11; +const DOM_EXCEPTION_ABORTED = 20; +const DOM_EXCEPTION_QUOTA_EXCEEDED = 22; +/** + * FirestoreClient is a top-level class that constructs and owns all of the // + * pieces of the client SDK architecture. It is responsible for creating the // + * async queue that is shared by all of the other components in the system. // + */ +class FirestoreClient { + constructor(authCredentials, appCheckCredentials, + /** + * Asynchronous queue responsible for all of our internal processing. When + * we get incoming work from the user (via public API) or the network + * (incoming GRPC messages), we should always schedule onto this queue. + * This ensures all of our work is properly serialized (e.g. we don't + * start processing a new operation while the previous one is waiting for + * an async I/O to complete). + */ + asyncQueue, databaseInfo, componentProvider) { + this.authCredentials = authCredentials; + this.appCheckCredentials = appCheckCredentials; + this.asyncQueue = asyncQueue; + this.databaseInfo = databaseInfo; + this.user = User.UNAUTHENTICATED; + this.clientId = AutoId.newId(); + this.authCredentialListener = () => Promise.resolve(); + this.appCheckCredentialListener = () => Promise.resolve(); + this._uninitializedComponentsProvider = componentProvider; + this.authCredentials.start(asyncQueue, async (user) => { + logDebug(LOG_TAG$2, 'Received user=', user.uid); + await this.authCredentialListener(user); + this.user = user; + }); + this.appCheckCredentials.start(asyncQueue, newAppCheckToken => { + logDebug(LOG_TAG$2, 'Received new app check token=', newAppCheckToken); + return this.appCheckCredentialListener(newAppCheckToken, this.user); + }); + } + get configuration() { + return { + asyncQueue: this.asyncQueue, + databaseInfo: this.databaseInfo, + clientId: this.clientId, + authCredentials: this.authCredentials, + appCheckCredentials: this.appCheckCredentials, + initialUser: this.user, + maxConcurrentLimboResolutions: MAX_CONCURRENT_LIMBO_RESOLUTIONS + }; + } + setCredentialChangeListener(listener) { + this.authCredentialListener = listener; + } + setAppCheckTokenChangeListener(listener) { + this.appCheckCredentialListener = listener; + } + terminate() { + this.asyncQueue.enterRestrictedMode(); + const deferred = new Deferred(); + this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async () => { + try { + if (this._onlineComponents) { + await this._onlineComponents.terminate(); + } + if (this._offlineComponents) { + await this._offlineComponents.terminate(); + } + // The credentials provider must be terminated after shutting down the + // RemoteStore as it will prevent the RemoteStore from retrieving auth + // tokens. + this.authCredentials.shutdown(); + this.appCheckCredentials.shutdown(); + deferred.resolve(); + } + catch (e) { + const firestoreError = wrapInUserErrorIfRecoverable(e, `Failed to shutdown persistence`); + deferred.reject(firestoreError); + } + }); + return deferred.promise; + } +} +async function setOfflineComponentProvider(client, offlineComponentProvider) { + client.asyncQueue.verifyOperationInProgress(); + logDebug(LOG_TAG$2, 'Initializing OfflineComponentProvider'); + const configuration = client.configuration; + await offlineComponentProvider.initialize(configuration); + let currentUser = configuration.initialUser; + client.setCredentialChangeListener(async (user) => { + if (!currentUser.isEqual(user)) { + await localStoreHandleUserChange(offlineComponentProvider.localStore, user); + currentUser = user; + } + }); + // When a user calls clearPersistence() in one client, all other clients + // need to be terminated to allow the delete to succeed. + offlineComponentProvider.persistence.setDatabaseDeletedListener(() => client.terminate()); + client._offlineComponents = offlineComponentProvider; +} +async function setOnlineComponentProvider(client, onlineComponentProvider) { + client.asyncQueue.verifyOperationInProgress(); + const offlineComponents = await ensureOfflineComponents(client); + logDebug(LOG_TAG$2, 'Initializing OnlineComponentProvider'); + await onlineComponentProvider.initialize(offlineComponents, client.configuration); + // The CredentialChangeListener of the online component provider takes + // precedence over the offline component provider. + client.setCredentialChangeListener(user => remoteStoreHandleCredentialChange(onlineComponentProvider.remoteStore, user)); + client.setAppCheckTokenChangeListener((_, user) => remoteStoreHandleCredentialChange(onlineComponentProvider.remoteStore, user)); + client._onlineComponents = onlineComponentProvider; +} +/** + * Decides whether the provided error allows us to gracefully disable + * persistence (as opposed to crashing the client). + */ +function canFallbackFromIndexedDbError(error) { + if (error.name === 'FirebaseError') { + return (error.code === Code.FAILED_PRECONDITION || + error.code === Code.UNIMPLEMENTED); + } + else if (typeof DOMException !== 'undefined' && + error instanceof DOMException) { + // There are a few known circumstances where we can open IndexedDb but + // trying to read/write will fail (e.g. quota exceeded). For + // well-understood cases, we attempt to detect these and then gracefully + // fall back to memory persistence. + // NOTE: Rather than continue to add to this list, we could decide to + // always fall back, with the risk that we might accidentally hide errors + // representing actual SDK bugs. + return ( + // When the browser is out of quota we could get either quota exceeded + // or an aborted error depending on whether the error happened during + // schema migration. + error.code === DOM_EXCEPTION_QUOTA_EXCEEDED || + error.code === DOM_EXCEPTION_ABORTED || + // Firefox Private Browsing mode disables IndexedDb and returns + // INVALID_STATE for any usage. + error.code === DOM_EXCEPTION_INVALID_STATE); + } + return true; +} +async function ensureOfflineComponents(client) { + if (!client._offlineComponents) { + if (client._uninitializedComponentsProvider) { + logDebug(LOG_TAG$2, 'Using user provided OfflineComponentProvider'); + try { + await setOfflineComponentProvider(client, client._uninitializedComponentsProvider._offline); + } + catch (e) { + const error = e; + if (!canFallbackFromIndexedDbError(error)) { + throw error; + } + logWarn('Error using user provided cache. Falling back to ' + + 'memory cache: ' + + error); + await setOfflineComponentProvider(client, new MemoryOfflineComponentProvider()); + } + } + else { + logDebug(LOG_TAG$2, 'Using default OfflineComponentProvider'); + await setOfflineComponentProvider(client, new LruGcMemoryOfflineComponentProvider(undefined)); + } + } + return client._offlineComponents; +} +async function ensureOnlineComponents(client) { + if (!client._onlineComponents) { + if (client._uninitializedComponentsProvider) { + logDebug(LOG_TAG$2, 'Using user provided OnlineComponentProvider'); + await setOnlineComponentProvider(client, client._uninitializedComponentsProvider._online); + } + else { + logDebug(LOG_TAG$2, 'Using default OnlineComponentProvider'); + await setOnlineComponentProvider(client, new OnlineComponentProvider()); + } + } + return client._onlineComponents; +} +function getPersistence(client) { + return ensureOfflineComponents(client).then(c => c.persistence); +} +function getLocalStore(client) { + return ensureOfflineComponents(client).then(c => c.localStore); +} +function getRemoteStore(client) { + return ensureOnlineComponents(client).then(c => c.remoteStore); +} +function getSyncEngine(client) { + return ensureOnlineComponents(client).then(c => c.syncEngine); +} +function getDatastore(client) { + return ensureOnlineComponents(client).then(c => c.datastore); +} +async function getEventManager(client) { + const onlineComponentProvider = await ensureOnlineComponents(client); + const eventManager = onlineComponentProvider.eventManager; + eventManager.onListen = syncEngineListen.bind(null, onlineComponentProvider.syncEngine); + eventManager.onUnlisten = syncEngineUnlisten.bind(null, onlineComponentProvider.syncEngine); + eventManager.onFirstRemoteStoreListen = triggerRemoteStoreListen.bind(null, onlineComponentProvider.syncEngine); + eventManager.onLastRemoteStoreUnlisten = triggerRemoteStoreUnlisten.bind(null, onlineComponentProvider.syncEngine); + return eventManager; +} +/** Enables the network connection and re-enqueues all pending operations. */ +function firestoreClientEnableNetwork(client) { + return client.asyncQueue.enqueue(async () => { + const persistence = await getPersistence(client); + const remoteStore = await getRemoteStore(client); + persistence.setNetworkEnabled(true); + return remoteStoreEnableNetwork(remoteStore); + }); +} +/** Disables the network connection. Pending operations will not complete. */ +function firestoreClientDisableNetwork(client) { + return client.asyncQueue.enqueue(async () => { + const persistence = await getPersistence(client); + const remoteStore = await getRemoteStore(client); + persistence.setNetworkEnabled(false); + return remoteStoreDisableNetwork(remoteStore); + }); +} +/** + * Returns a Promise that resolves when all writes that were pending at the time + * this method was called received server acknowledgement. An acknowledgement + * can be either acceptance or rejection. + */ +function firestoreClientWaitForPendingWrites(client) { + const deferred = new Deferred(); + client.asyncQueue.enqueueAndForget(async () => { + const syncEngine = await getSyncEngine(client); + return syncEngineRegisterPendingWritesCallback(syncEngine, deferred); + }); + return deferred.promise; +} +function firestoreClientListen(client, query, options, observer) { + const wrappedObserver = new AsyncObserver(observer); + const listener = new QueryListener(query, wrappedObserver, options); + client.asyncQueue.enqueueAndForget(async () => { + const eventManager = await getEventManager(client); + return eventManagerListen(eventManager, listener); + }); + return () => { + wrappedObserver.mute(); + client.asyncQueue.enqueueAndForget(async () => { + const eventManager = await getEventManager(client); + return eventManagerUnlisten(eventManager, listener); + }); + }; +} +function firestoreClientGetDocumentFromLocalCache(client, docKey) { + const deferred = new Deferred(); + client.asyncQueue.enqueueAndForget(async () => { + const localStore = await getLocalStore(client); + return readDocumentFromCache(localStore, docKey, deferred); + }); + return deferred.promise; +} +function firestoreClientGetDocumentViaSnapshotListener(client, key, options = {}) { + const deferred = new Deferred(); + client.asyncQueue.enqueueAndForget(async () => { + const eventManager = await getEventManager(client); + return readDocumentViaSnapshotListener(eventManager, client.asyncQueue, key, options, deferred); + }); + return deferred.promise; +} +function firestoreClientGetDocumentsFromLocalCache(client, query) { + const deferred = new Deferred(); + client.asyncQueue.enqueueAndForget(async () => { + const localStore = await getLocalStore(client); + return executeQueryFromCache(localStore, query, deferred); + }); + return deferred.promise; +} +function firestoreClientGetDocumentsViaSnapshotListener(client, query, options = {}) { + const deferred = new Deferred(); + client.asyncQueue.enqueueAndForget(async () => { + const eventManager = await getEventManager(client); + return executeQueryViaSnapshotListener(eventManager, client.asyncQueue, query, options, deferred); + }); + return deferred.promise; +} +function firestoreClientRunAggregateQuery(client, query, aggregates) { + const deferred = new Deferred(); + client.asyncQueue.enqueueAndForget(async () => { + // Implement and call executeAggregateQueryViaSnapshotListener, similar + // to the implementation in firestoreClientGetDocumentsViaSnapshotListener + // above + try { + // TODO(b/277628384): check `canUseNetwork()` and handle multi-tab. + const datastore = await getDatastore(client); + deferred.resolve(invokeRunAggregationQueryRpc(datastore, query, aggregates)); + } + catch (e) { + deferred.reject(e); + } + }); + return deferred.promise; +} +function firestoreClientWrite(client, mutations) { + const deferred = new Deferred(); + client.asyncQueue.enqueueAndForget(async () => { + const syncEngine = await getSyncEngine(client); + return syncEngineWrite(syncEngine, mutations, deferred); + }); + return deferred.promise; +} +function firestoreClientAddSnapshotsInSyncListener(client, observer) { + const wrappedObserver = new AsyncObserver(observer); + client.asyncQueue.enqueueAndForget(async () => { + const eventManager = await getEventManager(client); + return addSnapshotsInSyncListener(eventManager, wrappedObserver); + }); + return () => { + wrappedObserver.mute(); + client.asyncQueue.enqueueAndForget(async () => { + const eventManager = await getEventManager(client); + return removeSnapshotsInSyncListener(eventManager, wrappedObserver); + }); + }; +} +/** + * Takes an updateFunction in which a set of reads and writes can be performed + * atomically. In the updateFunction, the client can read and write values + * using the supplied transaction object. After the updateFunction, all + * changes will be committed. If a retryable error occurs (ex: some other + * client has changed any of the data referenced), then the updateFunction + * will be called again after a backoff. If the updateFunction still fails + * after all retries, then the transaction will be rejected. + * + * The transaction object passed to the updateFunction contains methods for + * accessing documents and collections. Unlike other datastore access, data + * accessed with the transaction will not reflect local changes that have not + * been committed. For this reason, it is required that all reads are + * performed before any writes. Transactions must be performed while online. + */ +function firestoreClientTransaction(client, updateFunction, options) { + const deferred = new Deferred(); + client.asyncQueue.enqueueAndForget(async () => { + const datastore = await getDatastore(client); + new TransactionRunner(client.asyncQueue, datastore, options, updateFunction, deferred).run(); + }); + return deferred.promise; +} +async function readDocumentFromCache(localStore, docKey, result) { + try { + const document = await localStoreReadDocument(localStore, docKey); + if (document.isFoundDocument()) { + result.resolve(document); + } + else if (document.isNoDocument()) { + result.resolve(null); + } + else { + result.reject(new FirestoreError(Code.UNAVAILABLE, 'Failed to get document from cache. (However, this document may ' + + "exist on the server. Run again without setting 'source' in " + + 'the GetOptions to attempt to retrieve the document from the ' + + 'server.)')); + } + } + catch (e) { + const firestoreError = wrapInUserErrorIfRecoverable(e, `Failed to get document '${docKey} from cache`); + result.reject(firestoreError); + } +} +/** + * Retrieves a latency-compensated document from the backend via a + * SnapshotListener. + */ +function readDocumentViaSnapshotListener(eventManager, asyncQueue, key, options, result) { + const wrappedObserver = new AsyncObserver({ + next: (snap) => { + // Mute and remove query first before passing event to user to avoid + // user actions affecting the now stale query. + wrappedObserver.mute(); + asyncQueue.enqueueAndForget(() => eventManagerUnlisten(eventManager, listener)); + const exists = snap.docs.has(key); + if (!exists && snap.fromCache) { + // TODO(dimond): If we're online and the document doesn't + // exist then we resolve with a doc.exists set to false. If + // we're offline however, we reject the Promise in this + // case. Two options: 1) Cache the negative response from + // the server so we can deliver that even when you're + // offline 2) Actually reject the Promise in the online case + // if the document doesn't exist. + result.reject(new FirestoreError(Code.UNAVAILABLE, 'Failed to get document because the client is offline.')); + } + else if (exists && + snap.fromCache && + options && + options.source === 'server') { + result.reject(new FirestoreError(Code.UNAVAILABLE, 'Failed to get document from server. (However, this ' + + 'document does exist in the local cache. Run again ' + + 'without setting source to "server" to ' + + 'retrieve the cached document.)')); + } + else { + result.resolve(snap); + } + }, + error: e => result.reject(e) + }); + const listener = new QueryListener(newQueryForPath(key.path), wrappedObserver, { + includeMetadataChanges: true, + waitForSyncWhenOnline: true + }); + return eventManagerListen(eventManager, listener); +} +async function executeQueryFromCache(localStore, query, result) { + try { + const queryResult = await localStoreExecuteQuery(localStore, query, + /* usePreviousResults= */ true); + const view = new View(query, queryResult.remoteKeys); + const viewDocChanges = view.computeDocChanges(queryResult.documents); + const viewChange = view.applyChanges(viewDocChanges, + /* limboResolutionEnabled= */ false); + result.resolve(viewChange.snapshot); + } + catch (e) { + const firestoreError = wrapInUserErrorIfRecoverable(e, `Failed to execute query '${query} against cache`); + result.reject(firestoreError); + } +} +/** + * Retrieves a latency-compensated query snapshot from the backend via a + * SnapshotListener. + */ +function executeQueryViaSnapshotListener(eventManager, asyncQueue, query, options, result) { + const wrappedObserver = new AsyncObserver({ + next: snapshot => { + // Mute and remove query first before passing event to user to avoid + // user actions affecting the now stale query. + wrappedObserver.mute(); + asyncQueue.enqueueAndForget(() => eventManagerUnlisten(eventManager, listener)); + if (snapshot.fromCache && options.source === 'server') { + result.reject(new FirestoreError(Code.UNAVAILABLE, 'Failed to get documents from server. (However, these ' + + 'documents may exist in the local cache. Run again ' + + 'without setting source to "server" to ' + + 'retrieve the cached documents.)')); + } + else { + result.resolve(snapshot); + } + }, + error: e => result.reject(e) + }); + const listener = new QueryListener(query, wrappedObserver, { + includeMetadataChanges: true, + waitForSyncWhenOnline: true + }); + return eventManagerListen(eventManager, listener); +} +function firestoreClientLoadBundle(client, databaseId, data, resultTask) { + const reader = createBundleReader(data, newSerializer(databaseId)); + client.asyncQueue.enqueueAndForget(async () => { + syncEngineLoadBundle(await getSyncEngine(client), reader, resultTask); + }); +} +function firestoreClientGetNamedQuery(client, queryName) { + return client.asyncQueue.enqueue(async () => localStoreGetNamedQuery(await getLocalStore(client), queryName)); +} +function createBundleReader(data, serializer) { + let content; + if (typeof data === 'string') { + content = newTextEncoder().encode(data); + } + else { + content = data; + } + return newBundleReader(toByteStreamReader(content), serializer); +} +function createBundleReaderSync(bundleData, serializer) { + return newBundleReaderSync(bundleData, serializer); +} +function firestoreClientSetIndexConfiguration(client, indexes) { + return client.asyncQueue.enqueue(async () => { + return localStoreConfigureFieldIndexes(await getLocalStore(client), indexes); + }); +} +function firestoreClientSetPersistentCacheIndexAutoCreationEnabled(client, isEnabled) { + return client.asyncQueue.enqueue(async () => { + return localStoreSetIndexAutoCreationEnabled(await getLocalStore(client), isEnabled); + }); +} +function firestoreClientDeleteAllFieldIndexes(client) { + return client.asyncQueue.enqueue(async () => { + return localStoreDeleteAllFieldIndexes(await getLocalStore(client)); + }); +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Compares two `ExperimentalLongPollingOptions` objects for equality. + */ +function longPollingOptionsEqual(options1, options2) { + return options1.timeoutSeconds === options2.timeoutSeconds; +} +/** + * Creates and returns a new `ExperimentalLongPollingOptions` with the same + * option values as the given instance. + */ +function cloneLongPollingOptions(options) { + const clone = {}; + if (options.timeoutSeconds !== undefined) { + clone.timeoutSeconds = options.timeoutSeconds; + } + return clone; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$1 = 'ComponentProvider'; +/** + * An instance map that ensures only one Datastore exists per Firestore + * instance. + */ +const datastoreInstances = new Map(); +/** + * Removes all components associated with the provided instance. Must be called + * when the `Firestore` instance is terminated. + */ +function removeComponents(firestore) { + const datastore = datastoreInstances.get(firestore); + if (datastore) { + logDebug(LOG_TAG$1, 'Removing Datastore'); + datastoreInstances.delete(firestore); + datastore.terminate(); + } +} +function makeDatabaseInfo(databaseId, appId, persistenceKey, settings) { + return new DatabaseInfo(databaseId, appId, persistenceKey, settings.host, settings.ssl, settings.experimentalForceLongPolling, settings.experimentalAutoDetectLongPolling, cloneLongPollingOptions(settings.experimentalLongPollingOptions), settings.useFetchStreams, settings.isUsingEmulator); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// settings() defaults: +const DEFAULT_HOST = 'firestore.googleapis.com'; +const DEFAULT_SSL = true; +// The minimum long-polling timeout is hardcoded on the server. The value here +// should be kept in sync with the value used by the server, as the server will +// silently ignore a value below the minimum and fall back to the default. +// Googlers see b/266868871 for relevant discussion. +const MIN_LONG_POLLING_TIMEOUT_SECONDS = 5; +// No maximum long-polling timeout is configured in the server, and defaults to +// 30 seconds, which is what Watch appears to use. +// Googlers see b/266868871 for relevant discussion. +const MAX_LONG_POLLING_TIMEOUT_SECONDS = 30; +// Whether long-polling auto-detected is enabled by default. +const DEFAULT_AUTO_DETECT_LONG_POLLING = true; +/** + * A concrete type describing all the values that can be applied via a + * user-supplied `FirestoreSettings` object. This is a separate type so that + * defaults can be supplied and the value can be checked for equality. + */ +class FirestoreSettingsImpl { + constructor(settings) { + if (settings.host === undefined) { + if (settings.ssl !== undefined) { + throw new FirestoreError(Code.INVALID_ARGUMENT, "Can't provide ssl option if host option is not set"); + } + this.host = DEFAULT_HOST; + this.ssl = DEFAULT_SSL; + } + else { + this.host = settings.host; + this.ssl = settings.ssl ?? DEFAULT_SSL; + } + this.isUsingEmulator = settings.emulatorOptions !== undefined; + this.credentials = settings.credentials; + this.ignoreUndefinedProperties = !!settings.ignoreUndefinedProperties; + this.localCache = settings.localCache; + if (settings.cacheSizeBytes === undefined) { + this.cacheSizeBytes = LRU_DEFAULT_CACHE_SIZE_BYTES; + } + else { + if (settings.cacheSizeBytes !== LRU_COLLECTION_DISABLED && + settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`); + } + else { + this.cacheSizeBytes = settings.cacheSizeBytes; + } + } + validateIsNotUsedTogether('experimentalForceLongPolling', settings.experimentalForceLongPolling, 'experimentalAutoDetectLongPolling', settings.experimentalAutoDetectLongPolling); + this.experimentalForceLongPolling = !!settings.experimentalForceLongPolling; + if (this.experimentalForceLongPolling) { + this.experimentalAutoDetectLongPolling = false; + } + else if (settings.experimentalAutoDetectLongPolling === undefined) { + this.experimentalAutoDetectLongPolling = DEFAULT_AUTO_DETECT_LONG_POLLING; + } + else { + // For backwards compatibility, coerce the value to boolean even though + // the TypeScript compiler has narrowed the type to boolean already. + // noinspection PointlessBooleanExpressionJS + this.experimentalAutoDetectLongPolling = + !!settings.experimentalAutoDetectLongPolling; + } + this.experimentalLongPollingOptions = cloneLongPollingOptions(settings.experimentalLongPollingOptions ?? {}); + validateLongPollingOptions(this.experimentalLongPollingOptions); + this.useFetchStreams = !!settings.useFetchStreams; + } + isEqual(other) { + return (this.host === other.host && + this.ssl === other.ssl && + this.credentials === other.credentials && + this.cacheSizeBytes === other.cacheSizeBytes && + this.experimentalForceLongPolling === + other.experimentalForceLongPolling && + this.experimentalAutoDetectLongPolling === + other.experimentalAutoDetectLongPolling && + longPollingOptionsEqual(this.experimentalLongPollingOptions, other.experimentalLongPollingOptions) && + this.ignoreUndefinedProperties === other.ignoreUndefinedProperties && + this.useFetchStreams === other.useFetchStreams); + } +} +function validateLongPollingOptions(options) { + if (options.timeoutSeconds !== undefined) { + if (isNaN(options.timeoutSeconds)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `invalid long polling timeout: ` + + `${options.timeoutSeconds} (must not be NaN)`); + } + if (options.timeoutSeconds < MIN_LONG_POLLING_TIMEOUT_SECONDS) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `invalid long polling timeout: ${options.timeoutSeconds} ` + + `(minimum allowed value is ${MIN_LONG_POLLING_TIMEOUT_SECONDS})`); + } + if (options.timeoutSeconds > MAX_LONG_POLLING_TIMEOUT_SECONDS) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `invalid long polling timeout: ${options.timeoutSeconds} ` + + `(maximum allowed value is ${MAX_LONG_POLLING_TIMEOUT_SECONDS})`); + } + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ +class Firestore$1 { + /** @hideconstructor */ + constructor(_authCredentials, _appCheckCredentials, _databaseId, _app) { + this._authCredentials = _authCredentials; + this._appCheckCredentials = _appCheckCredentials; + this._databaseId = _databaseId; + this._app = _app; + /** + * Whether it's a Firestore or Firestore Lite instance. + */ + this.type = 'firestore-lite'; + this._persistenceKey = '(lite)'; + this._settings = new FirestoreSettingsImpl({}); + this._settingsFrozen = false; + this._emulatorOptions = {}; + // A task that is assigned when the terminate() is invoked and resolved when + // all components have shut down. Otherwise, Firestore is not terminated, + // which can mean either the FirestoreClient is in the process of starting, + // or restarting. + this._terminateTask = 'notTerminated'; + } + /** + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service + * instance. + */ + get app() { + if (!this._app) { + throw new FirestoreError(Code.FAILED_PRECONDITION, "Firestore was not initialized using the Firebase SDK. 'app' is " + + 'not available'); + } + return this._app; + } + get _initialized() { + return this._settingsFrozen; + } + get _terminated() { + return this._terminateTask !== 'notTerminated'; + } + _setSettings(settings) { + if (this._settingsFrozen) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore has already been started and its settings can no longer ' + + 'be changed. You can only modify settings before calling any other ' + + 'methods on a Firestore object.'); + } + this._settings = new FirestoreSettingsImpl(settings); + this._emulatorOptions = settings.emulatorOptions || {}; + if (settings.credentials !== undefined) { + this._authCredentials = makeAuthCredentialsProvider(settings.credentials); + } + } + _getSettings() { + return this._settings; + } + _getEmulatorOptions() { + return this._emulatorOptions; + } + _freezeSettings() { + this._settingsFrozen = true; + return this._settings; + } + _delete() { + // The `_terminateTask` must be assigned future that completes when + // terminate is complete. The existence of this future puts SDK in state + // that will not accept further API interaction. + if (this._terminateTask === 'notTerminated') { + this._terminateTask = this._terminate(); + } + return this._terminateTask; + } + async _restart() { + // The `_terminateTask` must equal 'notTerminated' after restart to + // signal that client is in a state that accepts API calls. + if (this._terminateTask === 'notTerminated') { + await this._terminate(); + } + else { + this._terminateTask = 'notTerminated'; + } + } + /** Returns a JSON-serializable representation of this `Firestore` instance. */ + toJSON() { + return { + app: this._app, + databaseId: this._databaseId, + settings: this._settings + }; + } + /** + * Terminates all components used by this client. Subclasses can override + * this method to clean up their own dependencies, but must also call this + * method. + * + * Only ever called once. + */ + _terminate() { + removeComponents(this); + return Promise.resolve(); + } +} +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ +function connectFirestoreEmulator(firestore, host, port, options = {}) { + firestore = cast(firestore, Firestore$1); + const useSsl = util.isCloudWorkstation(host); + const settings = firestore._getSettings(); + const existingConfig = { + ...settings, + emulatorOptions: firestore._getEmulatorOptions() + }; + const newHostSetting = `${host}:${port}`; + if (useSsl) { + void util.pingServer(`https://${newHostSetting}`); + util.updateEmulatorBanner('Firestore', true); + } + if (settings.host !== DEFAULT_HOST && settings.host !== newHostSetting) { + logWarn('Host has been set in both settings() and connectFirestoreEmulator(), emulator host ' + + 'will be used.'); + } + const newConfig = { + ...settings, + host: newHostSetting, + ssl: useSsl, + emulatorOptions: options + }; + // No-op if the new configuration matches the current configuration. This supports SSR + // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice. + if (util.deepEqual(newConfig, existingConfig)) { + return; + } + firestore._setSettings(newConfig); + if (options.mockUserToken) { + let token; + let user; + if (typeof options.mockUserToken === 'string') { + token = options.mockUserToken; + user = User.MOCK_USER; + } + else { + // Let createMockUserToken validate first (catches common mistakes like + // invalid field "uid" and missing field "sub" / "user_id".) + token = util.createMockUserToken(options.mockUserToken, firestore._app?.options.projectId); + const uid = options.mockUserToken.sub || options.mockUserToken.user_id; + if (!uid) { + throw new FirestoreError(Code.INVALID_ARGUMENT, "mockUserToken must contain 'sub' or 'user_id' field!"); + } + user = new User(uid); + } + firestore._authCredentials = new EmulatorAuthCredentialsProvider(new OAuthToken(token, user)); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `Query` refers to a query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ +class Query { + // This is the lite version of the Query class in the main SDK. + /** @hideconstructor protected */ + constructor(firestore, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter, _query) { + this.converter = converter; + this._query = _query; + /** The type of this Firestore reference. */ + this.type = 'query'; + this.firestore = firestore; + } + withConverter(converter) { + return new Query(this.firestore, converter, this._query); + } +} +/** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. + */ +class DocumentReference { + /** @hideconstructor */ + constructor(firestore, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter, _key) { + this.converter = converter; + this._key = _key; + /** The type of this Firestore reference. */ + this.type = 'document'; + this.firestore = firestore; + } + get _path() { + return this._key.path; + } + /** + * The document's identifier within its collection. + */ + get id() { + return this._key.path.lastSegment(); + } + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ + get path() { + return this._key.path.canonicalString(); + } + /** + * The collection this `DocumentReference` belongs to. + */ + get parent() { + return new CollectionReference(this.firestore, this.converter, this._key.path.popLast()); + } + withConverter(converter) { + return new DocumentReference(this.firestore, converter, this._key); + } + /** + * Returns a JSON-serializable representation of this `DocumentReference` instance. + * + * @returns a JSON representation of this object. + */ + toJSON() { + return { + type: DocumentReference._jsonSchemaVersion, + referencePath: this._key.toString() + }; + } + static fromJSON(firestore, json, converter) { + if (validateJSON(json, DocumentReference._jsonSchema)) { + return new DocumentReference(firestore, converter ? converter : null, new DocumentKey(ResourcePath.fromString(json.referencePath))); + } + } +} +DocumentReference._jsonSchemaVersion = 'firestore/documentReference/1.0'; +DocumentReference._jsonSchema = { + type: property('string', DocumentReference._jsonSchemaVersion), + referencePath: property('string') +}; +/** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using {@link (query:1)}). + */ +class CollectionReference extends Query { + /** @hideconstructor */ + constructor(firestore, converter, _path) { + super(firestore, converter, newQueryForPath(_path)); + this._path = _path; + /** The type of this Firestore reference. */ + this.type = 'collection'; + } + /** The collection's identifier. */ + get id() { + return this._query.path.lastSegment(); + } + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ + get path() { + return this._query.path.canonicalString(); + } + /** + * A reference to the containing `DocumentReference` if this is a + * subcollection. If this isn't a subcollection, the reference is null. + */ + get parent() { + const parentPath = this._path.popLast(); + if (parentPath.isEmpty()) { + return null; + } + else { + return new DocumentReference(this.firestore, + /* converter= */ null, new DocumentKey(parentPath)); + } + } + withConverter(converter) { + return new CollectionReference(this.firestore, converter, this._path); + } +} +function collection(parent, path, ...pathSegments) { + parent = util.getModularInstance(parent); + validateNonEmptyArgument('collection', 'path', path); + if (parent instanceof Firestore$1) { + const absolutePath = ResourcePath.fromString(path, ...pathSegments); + validateCollectionPath(absolutePath); + return new CollectionReference(parent, /* converter= */ null, absolutePath); + } + else { + if (!(parent instanceof DocumentReference) && + !(parent instanceof CollectionReference)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Expected first argument to collection() to be a CollectionReference, ' + + 'a DocumentReference or FirebaseFirestore'); + } + const absolutePath = parent._path.child(ResourcePath.fromString(path, ...pathSegments)); + validateCollectionPath(absolutePath); + return new CollectionReference(parent.firestore, + /* converter= */ null, absolutePath); + } +} +// TODO(firestorelite): Consider using ErrorFactory - +// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106 +/** + * Creates and returns a new `Query` instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given `collectionId`. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param collectionId - Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `Query`. + */ +function collectionGroup(firestore, collectionId) { + firestore = cast(firestore, Firestore$1); + validateNonEmptyArgument('collectionGroup', 'collection id', collectionId); + if (collectionId.indexOf('/') >= 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid collection ID '${collectionId}' passed to function ` + + `collectionGroup(). Collection IDs must not contain '/'.`); + } + return new Query(firestore, + /* converter= */ null, newQueryForCollectionGroup(collectionId)); +} +function doc(parent, path, ...pathSegments) { + parent = util.getModularInstance(parent); + // We allow omission of 'pathString' but explicitly prohibit passing in both + // 'undefined' and 'null'. + if (arguments.length === 1) { + path = AutoId.newId(); + } + validateNonEmptyArgument('doc', 'path', path); + if (parent instanceof Firestore$1) { + const absolutePath = ResourcePath.fromString(path, ...pathSegments); + validateDocumentPath(absolutePath); + return new DocumentReference(parent, + /* converter= */ null, new DocumentKey(absolutePath)); + } + else { + if (!(parent instanceof DocumentReference) && + !(parent instanceof CollectionReference)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Expected first argument to collection() to be a CollectionReference, ' + + 'a DocumentReference or FirebaseFirestore'); + } + const absolutePath = parent._path.child(ResourcePath.fromString(path, ...pathSegments)); + validateDocumentPath(absolutePath); + return new DocumentReference(parent.firestore, parent instanceof CollectionReference ? parent.converter : null, new DocumentKey(absolutePath)); + } +} +/** + * Returns true if the provided references are equal. + * + * @param left - A reference to compare. + * @param right - A reference to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +function refEqual(left, right) { + left = util.getModularInstance(left); + right = util.getModularInstance(right); + if ((left instanceof DocumentReference || + left instanceof CollectionReference) && + (right instanceof DocumentReference || right instanceof CollectionReference)) { + return (left.firestore === right.firestore && + left.path === right.path && + left.converter === right.converter); + } + return false; +} +/** + * Returns true if the provided queries point to the same collection and apply + * the same constraints. + * + * @param left - A `Query` to compare. + * @param right - A `Query` to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +function queryEqual(left, right) { + left = util.getModularInstance(left); + right = util.getModularInstance(right); + if (left instanceof Query && right instanceof Query) { + return (left.firestore === right.firestore && + queryEquals(left._query, right._query) && + left.converter === right.converter); + } + return false; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG = 'AsyncQueue'; +class AsyncQueueImpl { + constructor(tail = Promise.resolve()) { + // A list of retryable operations. Retryable operations are run in order and + // retried with backoff. + this.retryableOps = []; + // Is this AsyncQueue being shut down? Once it is set to true, it will not + // be changed again. + this._isShuttingDown = false; + // Operations scheduled to be queued in the future. Operations are + // automatically removed after they are run or canceled. + this.delayedOperations = []; + // visible for testing + this.failure = null; + // Flag set while there's an outstanding AsyncQueue operation, used for + // assertion sanity-checks. + this.operationInProgress = false; + // Enabled during shutdown on Safari to prevent future access to IndexedDB. + this.skipNonRestrictedTasks = false; + // List of TimerIds to fast-forward delays for. + this.timerIdsToSkip = []; + // Backoff timer used to schedule retries for retryable operations + this.backoff = new ExponentialBackoff(this, "async_queue_retry" /* TimerId.AsyncQueueRetry */); + // Visibility handler that triggers an immediate retry of all retryable + // operations. Meant to speed up recovery when we regain file system access + // after page comes into foreground. + this.visibilityHandler = () => { + this.backoff.skipBackoff(); + }; + this.tail = tail; + } + get isShuttingDown() { + return this._isShuttingDown; + } + /** + * Adds a new operation to the queue without waiting for it to complete (i.e. + * we ignore the Promise result). + */ + enqueueAndForget(op) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.enqueue(op); + } + enqueueAndForgetEvenWhileRestricted(op) { + this.verifyNotFailed(); + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.enqueueInternal(op); + } + enterRestrictedMode(purgeExistingTasks) { + if (!this._isShuttingDown) { + this._isShuttingDown = true; + this.skipNonRestrictedTasks = purgeExistingTasks || false; + } + } + enqueue(op) { + this.verifyNotFailed(); + if (this._isShuttingDown) { + // Return a Promise which never resolves. + return new Promise(() => { }); + } + // Create a deferred Promise that we can return to the callee. This + // allows us to return a "hanging Promise" only to the callee and still + // advance the queue even when the operation is not run. + const task = new Deferred(); + return this.enqueueInternal(() => { + if (this._isShuttingDown && this.skipNonRestrictedTasks) { + // We do not resolve 'task' + return Promise.resolve(); + } + op().then(task.resolve, task.reject); + return task.promise; + }).then(() => task.promise); + } + enqueueRetryable(op) { + this.enqueueAndForget(() => { + this.retryableOps.push(op); + return this.retryNextOp(); + }); + } + /** + * Runs the next operation from the retryable queue. If the operation fails, + * reschedules with backoff. + */ + async retryNextOp() { + if (this.retryableOps.length === 0) { + return; + } + try { + await this.retryableOps[0](); + this.retryableOps.shift(); + this.backoff.reset(); + } + catch (e) { + if (isIndexedDbTransactionError(e)) { + logDebug(LOG_TAG, 'Operation failed with retryable error: ' + e); + } + else { + throw e; // Failure will be handled by AsyncQueue + } + } + if (this.retryableOps.length > 0) { + // If there are additional operations, we re-schedule `retryNextOp()`. + // This is necessary to run retryable operations that failed during + // their initial attempt since we don't know whether they are already + // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1` + // needs to be re-run, we will run `op1`, `op1`, `op2` using the + // already enqueued calls to `retryNextOp()`. `op3()` will then run in the + // call scheduled here. + // Since `backoffAndRun()` cancels an existing backoff and schedules a + // new backoff on every call, there is only ever a single additional + // operation in the queue. + this.backoff.backoffAndRun(() => this.retryNextOp()); + } + } + enqueueInternal(op) { + const newTail = this.tail.then(() => { + this.operationInProgress = true; + return op() + .catch((error) => { + this.failure = error; + this.operationInProgress = false; + const message = getMessageOrStack(error); + logError('INTERNAL UNHANDLED ERROR: ', message); + // Re-throw the error so that this.tail becomes a rejected Promise and + // all further attempts to chain (via .then) will just short-circuit + // and return the rejected Promise. + throw error; + }) + .then(result => { + this.operationInProgress = false; + return result; + }); + }); + this.tail = newTail; + return newTail; + } + enqueueAfterDelay(timerId, delayMs, op) { + this.verifyNotFailed(); + // Fast-forward delays for timerIds that have been overridden. + if (this.timerIdsToSkip.indexOf(timerId) > -1) { + delayMs = 0; + } + const delayedOp = DelayedOperation.createAndSchedule(this, timerId, delayMs, op, removedOp => this.removeDelayedOperation(removedOp)); + this.delayedOperations.push(delayedOp); + return delayedOp; + } + verifyNotFailed() { + if (this.failure) { + fail(0xb815, { + messageOrStack: getMessageOrStack(this.failure) + }); + } + } + verifyOperationInProgress() { + } + /** + * Waits until all currently queued tasks are finished executing. Delayed + * operations are not run. + */ + async drain() { + // Operations in the queue prior to draining may have enqueued additional + // operations. Keep draining the queue until the tail is no longer advanced, + // which indicates that no more new operations were enqueued and that all + // operations were executed. + let currentTail; + do { + currentTail = this.tail; + await currentTail; + } while (currentTail !== this.tail); + } + /** + * For Tests: Determine if a delayed operation with a particular TimerId + * exists. + */ + containsDelayedOperation(timerId) { + for (const op of this.delayedOperations) { + if (op.timerId === timerId) { + return true; + } + } + return false; + } + /** + * For Tests: Runs some or all delayed operations early. + * + * @param lastTimerId - Delayed operations up to and including this TimerId + * will be drained. Pass TimerId.All to run all delayed operations. + * @returns a Promise that resolves once all operations have been run. + */ + runAllDelayedOperationsUntil(lastTimerId) { + // Note that draining may generate more delayed ops, so we do that first. + return this.drain().then(() => { + // Run ops in the same order they'd run if they ran naturally. + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ + this.delayedOperations.sort((a, b) => a.targetTimeMs - b.targetTimeMs); + for (const op of this.delayedOperations) { + op.skipDelay(); + if (lastTimerId !== "all" /* TimerId.All */ && op.timerId === lastTimerId) { + break; + } + } + return this.drain(); + }); + } + /** + * For Tests: Skip all subsequent delays for a timer id. + */ + skipDelaysForTimerId(timerId) { + this.timerIdsToSkip.push(timerId); + } + /** Called once a DelayedOperation is run or canceled. */ + removeDelayedOperation(op) { + // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small. + const index = this.delayedOperations.indexOf(op); + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ + this.delayedOperations.splice(index, 1); + } +} +/** + * Chrome includes Error.message in Error.stack. Other browsers do not. + * This returns expected output of message + stack when available. + * @param error - Error or FirestoreError + */ +function getMessageOrStack(error) { + let message = error.message || ''; + if (error.stack) { + if (error.stack.includes(error.message)) { + message = error.stack; + } + else { + message = error.message + '\n' + error.stack; + } + } + return message; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents the task of loading a Firestore bundle. It provides progress of bundle + * loading, as well as task completion and error events. + * + * The API is compatible with `Promise`. + */ +class LoadBundleTask { + constructor() { + this._progressObserver = {}; + this._taskCompletionResolver = new Deferred(); + this._lastProgress = { + taskState: 'Running', + totalBytes: 0, + totalDocuments: 0, + bytesLoaded: 0, + documentsLoaded: 0 + }; + } + /** + * Registers functions to listen to bundle loading progress events. + * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur + * each time a Firestore document is loaded from the bundle. + * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the + * error, and there should be no more updates after this. + * @param complete - Called when the loading task is complete. + */ + onProgress(next, error, complete) { + this._progressObserver = { + next, + error, + complete + }; + } + /** + * Implements the `Promise.catch` interface. + * + * @param onRejected - Called when an error occurs during bundle loading. + */ + catch(onRejected) { + return this._taskCompletionResolver.promise.catch(onRejected); + } + /** + * Implements the `Promise.then` interface. + * + * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update. + * The update will always have its `taskState` set to `"Success"`. + * @param onRejected - Called when an error occurs during bundle loading. + */ + then(onFulfilled, onRejected) { + return this._taskCompletionResolver.promise.then(onFulfilled, onRejected); + } + /** + * Notifies all observers that bundle loading has completed, with a provided + * `LoadBundleTaskProgress` object. + * + * @private + */ + _completeWith(progress) { + this._updateProgress(progress); + if (this._progressObserver.complete) { + this._progressObserver.complete(); + } + this._taskCompletionResolver.resolve(progress); + } + /** + * Notifies all observers that bundle loading has failed, with a provided + * `Error` as the reason. + * + * @private + */ + _failWith(error) { + this._lastProgress.taskState = 'Error'; + if (this._progressObserver.next) { + this._progressObserver.next(this._lastProgress); + } + if (this._progressObserver.error) { + this._progressObserver.error(error); + } + this._taskCompletionResolver.reject(error); + } + /** + * Notifies a progress update of loading a bundle. + * @param progress - The new progress. + * + * @private + */ + _updateProgress(progress) { + this._lastProgress = progress; + if (this._progressObserver.next) { + this._progressObserver.next(progress); + } + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Constant used to indicate the LRU garbage collection should be disabled. + * Set this value as the `cacheSizeBytes` on the settings passed to the + * {@link Firestore} instance. + */ +const CACHE_SIZE_UNLIMITED = LRU_COLLECTION_DISABLED; +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ +class Firestore extends Firestore$1 { + /** @hideconstructor */ + constructor(authCredentialsProvider, appCheckCredentialsProvider, databaseId, app) { + super(authCredentialsProvider, appCheckCredentialsProvider, databaseId, app); + /** + * Whether it's a {@link Firestore} or Firestore Lite instance. + */ + this.type = 'firestore'; + this._queue = new AsyncQueueImpl(); + this._persistenceKey = app?.name || '[DEFAULT]'; + } + async _terminate() { + if (this._firestoreClient) { + const terminate = this._firestoreClient.terminate(); + this._queue = new AsyncQueueImpl(terminate); + this._firestoreClient = undefined; + await terminate; + } + } +} +/** + * Initializes a new instance of {@link Firestore} with the provided settings. + * Can only be called before any other function, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will + * be associated. + * @param settings - A settings object to configure the {@link Firestore} instance. + * @param databaseId - The name of the database. + * @returns A newly initialized {@link Firestore} instance. + */ +function initializeFirestore(app$1, settings, databaseId) { + if (!databaseId) { + databaseId = DEFAULT_DATABASE_NAME; + } + const provider = app._getProvider(app$1, 'firestore'); + if (provider.isInitialized(databaseId)) { + const existingInstance = provider.getImmediate({ + identifier: databaseId + }); + const initialSettings = provider.getOptions(databaseId); + if (util.deepEqual(initialSettings, settings)) { + return existingInstance; + } + else { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'initializeFirestore() has already been called with ' + + 'different options. To avoid this error, call initializeFirestore() with the ' + + 'same options as when it was originally called, or call getFirestore() to return the' + + ' already initialized instance.'); + } + } + if (settings.cacheSizeBytes !== undefined && + settings.localCache !== undefined) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes will` + + `be deprecated. Instead, specify the cache size in the cache object`); + } + if (settings.cacheSizeBytes !== undefined && + settings.cacheSizeBytes !== CACHE_SIZE_UNLIMITED && + settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`); + } + // Workaround to get cookies in Firebase Studio + if (settings.host && util.isCloudWorkstation(settings.host)) { + void util.pingServer(settings.host); + } + return provider.initialize({ + options: settings, + instanceIdentifier: databaseId + }); +} +function getFirestore(appOrDatabaseId, optionalDatabaseId) { + const app$1 = typeof appOrDatabaseId === 'object' ? appOrDatabaseId : app.getApp(); + const databaseId = typeof appOrDatabaseId === 'string' + ? appOrDatabaseId + : optionalDatabaseId || DEFAULT_DATABASE_NAME; + const db = app._getProvider(app$1, 'firestore').getImmediate({ + identifier: databaseId + }); + if (!db._initialized) { + const emulator = util.getDefaultEmulatorHostnameAndPort('firestore'); + if (emulator) { + connectFirestoreEmulator(db, ...emulator); + } + } + return db; +} +/** + * @internal + */ +function ensureFirestoreConfigured(firestore) { + if (firestore._terminated) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'The client has already been terminated.'); + } + if (!firestore._firestoreClient) { + configureFirestore(firestore); + } + return firestore._firestoreClient; +} +function configureFirestore(firestore) { + const settings = firestore._freezeSettings(); + const databaseInfo = makeDatabaseInfo(firestore._databaseId, firestore._app?.options.appId || '', firestore._persistenceKey, settings); + if (!firestore._componentsProvider) { + if (settings.localCache?._offlineComponentProvider && + settings.localCache?._onlineComponentProvider) { + firestore._componentsProvider = { + _offline: settings.localCache._offlineComponentProvider, + _online: settings.localCache._onlineComponentProvider + }; + } + } + firestore._firestoreClient = new FirestoreClient(firestore._authCredentials, firestore._appCheckCredentials, firestore._queue, databaseInfo, firestore._componentsProvider && + buildComponentProvider(firestore._componentsProvider)); +} +function buildComponentProvider(componentsProvider) { + const online = componentsProvider?._online.build(); + return { + _offline: componentsProvider?._offline.build(online), + _online: online + }; +} +/** + * Attempts to enable persistent storage, if possible. + * + * On failure, `enableIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. + * + * * failed-precondition: The app is already open in another browser tab. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. + * + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. + * + * Note: `enableIndexedDbPersistence()` must be called before any other functions + * (other than {@link initializeFirestore}, {@link (getFirestore:1)} or + * {@link clearIndexedDbPersistence}. + * + * Persistence cannot be used in a Node.js environment. + * + * @param firestore - The {@link Firestore} instance to enable persistence for. + * @param persistenceSettings - Optional settings object to configure + * persistence. + * @returns A `Promise` that represents successfully enabling persistent storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on IndexedDb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. + */ +function enableIndexedDbPersistence(firestore, persistenceSettings) { + logWarn('enableIndexedDbPersistence() will be deprecated in the future, ' + + 'you can use `FirestoreSettings.cache` instead.'); + const settings = firestore._freezeSettings(); + setPersistenceProviders(firestore, OnlineComponentProvider.provider, { + build: (onlineComponents) => new IndexedDbOfflineComponentProvider(onlineComponents, settings.cacheSizeBytes, persistenceSettings?.forceOwnership) + }); + return Promise.resolve(); +} +/** + * Attempts to enable multi-tab persistent storage, if possible. If enabled + * across all tabs, all operations share access to local persistence, including + * shared execution of queries and latency-compensated local document updates + * across all connected instances. + * + * On failure, `enableMultiTabIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. + * + * * failed-precondition: The app is already open in another browser tab and + * multi-tab is not enabled. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. + * + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. + * + * @param firestore - The {@link Firestore} instance to enable persistence for. + * @returns A `Promise` that represents successfully enabling persistent + * storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on indexeddb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. + */ +async function enableMultiTabIndexedDbPersistence(firestore) { + logWarn('enableMultiTabIndexedDbPersistence() will be deprecated in the future, ' + + 'you can use `FirestoreSettings.cache` instead.'); + const settings = firestore._freezeSettings(); + setPersistenceProviders(firestore, OnlineComponentProvider.provider, { + build: (onlineComponents) => new MultiTabOfflineComponentProvider(onlineComponents, settings.cacheSizeBytes) + }); +} +/** + * Registers both the `OfflineComponentProvider` and `OnlineComponentProvider`. + * If the operation fails with a recoverable error (see + * `canRecoverFromIndexedDbError()` below), the returned Promise is rejected + * but the client remains usable. + */ +function setPersistenceProviders(firestore, onlineComponentProvider, offlineComponentProvider) { + firestore = cast(firestore, Firestore); + if (firestore._firestoreClient || firestore._terminated) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore has already been started and persistence can no longer be ' + + 'enabled. You can only enable persistence before calling any other ' + + 'methods on a Firestore object.'); + } + if (firestore._componentsProvider || firestore._getSettings().localCache) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'SDK cache is already specified.'); + } + firestore._componentsProvider = { + _online: onlineComponentProvider, + _offline: offlineComponentProvider + }; + configureFirestore(firestore); +} +/** + * Clears the persistent storage. This includes pending writes and cached + * documents. + * + * Must be called while the {@link Firestore} instance is not started (after the app is + * terminated or when the app is first initialized). On startup, this function + * must be called before other functions (other than {@link + * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore} + * instance is still running, the promise will be rejected with the error code + * of `failed-precondition`. + * + * Note: `clearIndexedDbPersistence()` is primarily intended to help write + * reliable tests that use Cloud Firestore. It uses an efficient mechanism for + * dropping existing data but does not attempt to securely overwrite or + * otherwise make cached data unrecoverable. For applications that are sensitive + * to the disclosure of cached data in between user sessions, we strongly + * recommend not enabling persistence at all. + * + * @param firestore - The {@link Firestore} instance to clear persistence for. + * @returns A `Promise` that is resolved when the persistent storage is + * cleared. Otherwise, the promise is rejected with an error. + */ +function clearIndexedDbPersistence(firestore) { + if (firestore._initialized && !firestore._terminated) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'Persistence can only be cleared before a Firestore instance is ' + + 'initialized or after it is terminated.'); + } + const deferred = new Deferred(); + firestore._queue.enqueueAndForgetEvenWhileRestricted(async () => { + try { + await indexedDbClearPersistence(indexedDbStoragePrefix(firestore._databaseId, firestore._persistenceKey)); + deferred.resolve(); + } + catch (e) { + deferred.reject(e); + } + }); + return deferred.promise; +} +/** + * Waits until all currently pending writes for the active user have been + * acknowledged by the backend. + * + * The returned promise resolves immediately if there are no outstanding writes. + * Otherwise, the promise waits for all previously issued writes (including + * those written in a previous app session), but it does not wait for writes + * that were added after the function is called. If you want to wait for + * additional writes, call `waitForPendingWrites()` again. + * + * Any outstanding `waitForPendingWrites()` promises are rejected during user + * changes. + * + * @returns A `Promise` which resolves when all currently pending writes have been + * acknowledged by the backend. + */ +function waitForPendingWrites(firestore) { + firestore = cast(firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + return firestoreClientWaitForPendingWrites(client); +} +/** + * Re-enables use of the network for this {@link Firestore} instance after a prior + * call to {@link disableNetwork}. + * + * @returns A `Promise` that is resolved once the network has been enabled. + */ +function enableNetwork(firestore) { + firestore = cast(firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + return firestoreClientEnableNetwork(client); +} +/** + * Disables network usage for this instance. It can be re-enabled via {@link + * enableNetwork}. While the network is disabled, any snapshot listeners, + * `getDoc()` or `getDocs()` calls will return results from cache, and any write + * operations will be queued until the network is restored. + * + * @returns A `Promise` that is resolved once the network has been disabled. + */ +function disableNetwork(firestore) { + firestore = cast(firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + return firestoreClientDisableNetwork(client); +} +/** + * Terminates the provided {@link Firestore} instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` function + * may be used. Any other function will throw a `FirestoreError`. + * + * To restart after termination, create a new instance of FirebaseFirestore with + * {@link (getFirestore:1)}. + * + * Termination does not cancel any pending writes, and any promises that are + * awaiting a response from the server will not be resolved. If you have + * persistence enabled, the next time you start this instance, it will resume + * sending these writes to the server. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all + * of its resources or in combination with `clearIndexedDbPersistence()` to + * ensure that all local state is destroyed between test runs. + * + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ +function terminate(firestore) { + app._removeServiceInstance(firestore.app, 'firestore', firestore._databaseId.database); + return firestore._delete(); +} +/** + * Loads a Firestore bundle into the local cache. + * + * @param firestore - The {@link Firestore} instance to load bundles for. + * @param bundleData - An object representing the bundle to be loaded. Valid + * objects are `ArrayBuffer`, `ReadableStream` or `string`. + * + * @returns A `LoadBundleTask` object, which notifies callers with progress + * updates, and completion or error events. It can be used as a + * `Promise`. + */ +function loadBundle(firestore, bundleData) { + firestore = cast(firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + const resultTask = new LoadBundleTask(); + firestoreClientLoadBundle(client, firestore._databaseId, bundleData, resultTask); + return resultTask; +} +/** + * Reads a Firestore {@link Query} from local cache, identified by the given + * name. + * + * The named queries are packaged into bundles on the server side (along + * with resulting documents), and loaded to local cache using `loadBundle`. Once + * in local cache, use this method to extract a {@link Query} by name. + * + * @param firestore - The {@link Firestore} instance to read the query from. + * @param name - The name of the query. + * @returns A `Promise` that is resolved with the Query or `null`. + */ +function namedQuery(firestore, name) { + firestore = cast(firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + return firestoreClientGetNamedQuery(client, name).then(namedQuery => { + if (!namedQuery) { + return null; + } + return new Query(firestore, null, namedQuery.query); + }); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function registerFirestore(variant, useFetchStreams = true) { + setSDKVersion(app.SDK_VERSION); + app._registerComponent(new component.Component('firestore', (container, { instanceIdentifier: databaseId, options: settings }) => { + const app = container.getProvider('app').getImmediate(); + const firestoreInstance = new Firestore(new FirebaseAuthCredentialsProvider(container.getProvider('auth-internal')), new FirebaseAppCheckTokenProvider(app, container.getProvider('app-check-internal')), databaseIdFromApp(app, databaseId), app); + settings = { useFetchStreams, ...settings }; + firestoreInstance._setSettings(settings); + return firestoreInstance; + }, 'PUBLIC').setMultipleInstances(true)); + app.registerVersion(name$1, version$1, variant); + // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation + app.registerVersion(name$1, version$1, 'cjs2020'); +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Concrete implementation of the Aggregate type. + */ +class AggregateImpl { + constructor(alias, aggregateType, fieldPath) { + this.alias = alias; + this.aggregateType = aggregateType; + this.fieldPath = fieldPath; + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents an aggregation that can be performed by Firestore. + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +class AggregateField { + /** + * Create a new AggregateField + * @param aggregateType Specifies the type of aggregation operation to perform. + * @param _internalFieldPath Optionally specifies the field that is aggregated. + * @internal + */ + constructor(aggregateType = 'count', _internalFieldPath) { + this._internalFieldPath = _internalFieldPath; + /** A type string to uniquely identify instances of this class. */ + this.type = 'AggregateField'; + this.aggregateType = aggregateType; + } +} +/** + * The results of executing an aggregation query. + */ +class AggregateQuerySnapshot { + /** @hideconstructor */ + constructor(query, _userDataWriter, _data) { + this._userDataWriter = _userDataWriter; + this._data = _data; + /** A type string to uniquely identify instances of this class. */ + this.type = 'AggregateQuerySnapshot'; + this.query = query; + } + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ + data() { + return this._userDataWriter.convertObjectMap(this._data); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing an array of bytes. + */ +class Bytes { + /** @hideconstructor */ + constructor(byteString) { + this._byteString = byteString; + } + /** + * Creates a new `Bytes` object from the given Base64 string, converting it to + * bytes. + * + * @param base64 - The Base64 string used to create the `Bytes` object. + */ + static fromBase64String(base64) { + try { + return new Bytes(ByteString.fromBase64String(base64)); + } + catch (e) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Failed to construct data from Base64 string: ' + e); + } + } + /** + * Creates a new `Bytes` object from the given Uint8Array. + * + * @param array - The Uint8Array used to create the `Bytes` object. + */ + static fromUint8Array(array) { + return new Bytes(ByteString.fromUint8Array(array)); + } + /** + * Returns the underlying bytes as a Base64-encoded string. + * + * @returns The Base64-encoded string created from the `Bytes` object. + */ + toBase64() { + return this._byteString.toBase64(); + } + /** + * Returns the underlying bytes in a new `Uint8Array`. + * + * @returns The Uint8Array created from the `Bytes` object. + */ + toUint8Array() { + return this._byteString.toUint8Array(); + } + /** + * Returns a string representation of the `Bytes` object. + * + * @returns A string representation of the `Bytes` object. + */ + toString() { + return 'Bytes(base64: ' + this.toBase64() + ')'; + } + /** + * Returns true if this `Bytes` object is equal to the provided one. + * + * @param other - The `Bytes` object to compare against. + * @returns true if this `Bytes` object is equal to the provided one. + */ + isEqual(other) { + return this._byteString.isEqual(other._byteString); + } + /** + * Returns a JSON-serializable representation of this `Bytes` instance. + * + * @returns a JSON representation of this object. + */ + toJSON() { + return { + type: Bytes._jsonSchemaVersion, + bytes: this.toBase64() + }; + } + /** + * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}. + * + * @param json a JSON object represention of a `Bytes` instance + * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json) { + if (validateJSON(json, Bytes._jsonSchema)) { + return Bytes.fromBase64String(json.bytes); + } + } +} +Bytes._jsonSchemaVersion = 'firestore/bytes/1.0'; +Bytes._jsonSchema = { + type: property('string', Bytes._jsonSchemaVersion), + bytes: property('string') +}; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `FieldPath` refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + * + * Create a `FieldPath` by providing field names. If more than one field + * name is provided, the path will point to a nested field in a document. + */ +class FieldPath { + /** + * Creates a `FieldPath` from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames - A list of field names. + */ + constructor(...fieldNames) { + for (let i = 0; i < fieldNames.length; ++i) { + if (fieldNames[i].length === 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid field name at argument $(i + 1). ` + + 'Field names must not be empty.'); + } + } + this._internalPath = new FieldPath$1(fieldNames); + } + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other - The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ + isEqual(other) { + return this._internalPath.isEqual(other._internalPath); + } +} +/** + * Returns a special sentinel `FieldPath` to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ +function documentId() { + return new FieldPath(DOCUMENT_KEY_NAME); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Sentinel values that can be used when writing document fields with `set()` + * or `update()`. + */ +class FieldValue { + /** + * @param _methodName - The public API endpoint that returns this class. + * @hideconstructor + */ + constructor(_methodName) { + this._methodName = _methodName; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ +class GeoPoint { + /** + * Creates a new immutable `GeoPoint` object with the provided latitude and + * longitude values. + * @param latitude - The latitude as number between -90 and 90. + * @param longitude - The longitude as number between -180 and 180. + */ + constructor(latitude, longitude) { + if (!isFinite(latitude) || latitude < -90 || latitude > 90) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Latitude must be a number between -90 and 90, but was: ' + latitude); + } + if (!isFinite(longitude) || longitude < -180 || longitude > 180) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Longitude must be a number between -180 and 180, but was: ' + longitude); + } + this._lat = latitude; + this._long = longitude; + } + /** + * The latitude of this `GeoPoint` instance. + */ + get latitude() { + return this._lat; + } + /** + * The longitude of this `GeoPoint` instance. + */ + get longitude() { + return this._long; + } + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other - The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ + isEqual(other) { + return this._lat === other._lat && this._long === other._long; + } + /** + * Actually private to JS consumers of our API, so this function is prefixed + * with an underscore. + */ + _compareTo(other) { + return (primitiveComparator(this._lat, other._lat) || + primitiveComparator(this._long, other._long)); + } + /** + * Returns a JSON-serializable representation of this `GeoPoint` instance. + * + * @returns a JSON representation of this object. + */ + toJSON() { + return { + latitude: this._lat, + longitude: this._long, + type: GeoPoint._jsonSchemaVersion + }; + } + /** + * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}. + * + * @param json a JSON object represention of a `GeoPoint` instance + * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json) { + if (validateJSON(json, GeoPoint._jsonSchema)) { + return new GeoPoint(json.latitude, json.longitude); + } + } +} +GeoPoint._jsonSchemaVersion = 'firestore/geoPoint/1.0'; +GeoPoint._jsonSchema = { + type: property('string', GeoPoint._jsonSchemaVersion), + latitude: property('number'), + longitude: property('number') +}; + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link vector}. + * + * @class VectorValue + */ +class VectorValue { + /** + * @private + * @internal + */ + constructor(values) { + // Making a copy of the parameter. + this._values = (values || []).map(n => n); + } + /** + * Returns a copy of the raw number array form of the vector. + */ + toArray() { + return this._values.map(n => n); + } + /** + * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise. + */ + isEqual(other) { + return isPrimitiveArrayEqual(this._values, other._values); + } + /** + * Returns a JSON-serializable representation of this `VectorValue` instance. + * + * @returns a JSON representation of this object. + */ + toJSON() { + return { + type: VectorValue._jsonSchemaVersion, + vectorValues: this._values + }; + } + /** + * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}. + * + * @param json a JSON object represention of a `VectorValue` instance. + * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json) { + if (validateJSON(json, VectorValue._jsonSchema)) { + if (Array.isArray(json.vectorValues) && + json.vectorValues.every(element => typeof element === 'number')) { + return new VectorValue(json.vectorValues); + } + throw new FirestoreError(Code.INVALID_ARGUMENT, "Expected 'vectorValues' field to be a number array"); + } + } +} +VectorValue._jsonSchemaVersion = 'firestore/vectorValue/1.0'; +VectorValue._jsonSchema = { + type: property('string', VectorValue._jsonSchemaVersion), + vectorValues: property('object') +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const RESERVED_FIELD_REGEX = /^__.*__$/; +/** The result of parsing document data (e.g. for a setData call). */ +class ParsedSetData { + constructor(data, fieldMask, fieldTransforms) { + this.data = data; + this.fieldMask = fieldMask; + this.fieldTransforms = fieldTransforms; + } + toMutation(key, precondition) { + if (this.fieldMask !== null) { + return new PatchMutation(key, this.data, this.fieldMask, precondition, this.fieldTransforms); + } + else { + return new SetMutation(key, this.data, precondition, this.fieldTransforms); + } + } +} +/** The result of parsing "update" data (i.e. for an updateData call). */ +class ParsedUpdateData { + constructor(data, + // The fieldMask does not include document transforms. + fieldMask, fieldTransforms) { + this.data = data; + this.fieldMask = fieldMask; + this.fieldTransforms = fieldTransforms; + } + toMutation(key, precondition) { + return new PatchMutation(key, this.data, this.fieldMask, precondition, this.fieldTransforms); + } +} +function isWrite(dataSource) { + switch (dataSource) { + case 0 /* UserDataSource.Set */: // fall through + case 2 /* UserDataSource.MergeSet */: // fall through + case 1 /* UserDataSource.Update */: + return true; + case 3 /* UserDataSource.Argument */: + case 4 /* UserDataSource.ArrayArgument */: + return false; + default: + throw fail(0x9c4b, { + dataSource + }); + } +} +/** A "context" object passed around while parsing user data. */ +class ParseContextImpl { + /** + * Initializes a ParseContext with the given source and path. + * + * @param settings - The settings for the parser. + * @param databaseId - The database ID of the Firestore instance. + * @param serializer - The serializer to use to generate the Value proto. + * @param ignoreUndefinedProperties - Whether to ignore undefined properties + * rather than throw. + * @param fieldTransforms - A mutable list of field transforms encountered + * while parsing the data. + * @param fieldMask - A mutable list of field paths encountered while parsing + * the data. + * + * TODO(b/34871131): We don't support array paths right now, so path can be + * null to indicate the context represents any location within an array (in + * which case certain features will not work and errors will be somewhat + * compromised). + */ + constructor(settings, databaseId, serializer, ignoreUndefinedProperties, fieldTransforms, fieldMask) { + this.settings = settings; + this.databaseId = databaseId; + this.serializer = serializer; + this.ignoreUndefinedProperties = ignoreUndefinedProperties; + // Minor hack: If fieldTransforms is undefined, we assume this is an + // external call and we need to validate the entire path. + if (fieldTransforms === undefined) { + this.validatePath(); + } + this.fieldTransforms = fieldTransforms || []; + this.fieldMask = fieldMask || []; + } + get path() { + return this.settings.path; + } + get dataSource() { + return this.settings.dataSource; + } + /** Returns a new context with the specified settings overwritten. */ + contextWith(configuration) { + return new ParseContextImpl({ ...this.settings, ...configuration }, this.databaseId, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask); + } + childContextForField(field) { + const childPath = this.path?.child(field); + const context = this.contextWith({ path: childPath, arrayElement: false }); + context.validatePathSegment(field); + return context; + } + childContextForFieldPath(field) { + const childPath = this.path?.child(field); + const context = this.contextWith({ path: childPath, arrayElement: false }); + context.validatePath(); + return context; + } + childContextForArray(index) { + // TODO(b/34871131): We don't support array paths right now; so make path + // undefined. + return this.contextWith({ path: undefined, arrayElement: true }); + } + createError(reason) { + return createError(reason, this.settings.methodName, this.settings.hasConverter || false, this.path, this.settings.targetDoc); + } + /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ + contains(fieldPath) { + return (this.fieldMask.find(field => fieldPath.isPrefixOf(field)) !== undefined || + this.fieldTransforms.find(transform => fieldPath.isPrefixOf(transform.field)) !== undefined); + } + validatePath() { + // TODO(b/34871131): Remove null check once we have proper paths for fields + // within arrays. + if (!this.path) { + return; + } + for (let i = 0; i < this.path.length; i++) { + this.validatePathSegment(this.path.get(i)); + } + } + validatePathSegment(segment) { + if (segment.length === 0) { + throw this.createError('Document fields must not be empty'); + } + if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) { + throw this.createError('Document fields cannot begin and end with "__"'); + } + } +} +/** + * Helper for parsing raw user input (provided via the API) into internal model + * classes. + */ +class UserDataReader { + constructor(databaseId, ignoreUndefinedProperties, serializer) { + this.databaseId = databaseId; + this.ignoreUndefinedProperties = ignoreUndefinedProperties; + this.serializer = serializer || newSerializer(databaseId); + } + /** Creates a new top-level parse context. */ + createContext(dataSource, methodName, targetDoc, hasConverter = false) { + return new ParseContextImpl({ + dataSource, + methodName, + targetDoc, + path: FieldPath$1.emptyPath(), + arrayElement: false, + hasConverter + }, this.databaseId, this.serializer, this.ignoreUndefinedProperties); + } +} +function newUserDataReader(firestore) { + const settings = firestore._freezeSettings(); + const serializer = newSerializer(firestore._databaseId); + return new UserDataReader(firestore._databaseId, !!settings.ignoreUndefinedProperties, serializer); +} +/** Parse document data from a set() call. */ +function parseSetData(userDataReader, methodName, targetDoc, input, hasConverter, options = {}) { + const context = userDataReader.createContext(options.merge || options.mergeFields + ? 2 /* UserDataSource.MergeSet */ + : 0 /* UserDataSource.Set */, methodName, targetDoc, hasConverter); + validatePlainObject('Data must be an object, but it was:', context, input); + const updateData = parseObject(input, context); + let fieldMask; + let fieldTransforms; + if (options.merge) { + fieldMask = new FieldMask(context.fieldMask); + fieldTransforms = context.fieldTransforms; + } + else if (options.mergeFields) { + const validatedFieldPaths = []; + for (const stringOrFieldPath of options.mergeFields) { + const fieldPath = fieldPathFromArgument$1(methodName, stringOrFieldPath, targetDoc); + if (!context.contains(fieldPath)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Field '${fieldPath}' is specified in your field mask but missing from your input data.`); + } + if (!fieldMaskContains(validatedFieldPaths, fieldPath)) { + validatedFieldPaths.push(fieldPath); + } + } + fieldMask = new FieldMask(validatedFieldPaths); + fieldTransforms = context.fieldTransforms.filter(transform => fieldMask.covers(transform.field)); + } + else { + fieldMask = null; + fieldTransforms = context.fieldTransforms; + } + return new ParsedSetData(new ObjectValue(updateData), fieldMask, fieldTransforms); +} +class DeleteFieldValueImpl extends FieldValue { + _toFieldTransform(context) { + if (context.dataSource === 2 /* UserDataSource.MergeSet */) { + // No transform to add for a delete, but we need to add it to our + // fieldMask so it gets deleted. + context.fieldMask.push(context.path); + } + else if (context.dataSource === 1 /* UserDataSource.Update */) { + throw context.createError(`${this._methodName}() can only appear at the top level ` + + 'of your update data'); + } + else { + // We shouldn't encounter delete sentinels for queries or non-merge set() calls. + throw context.createError(`${this._methodName}() cannot be used with set() unless you pass ` + + '{merge:true}'); + } + return null; + } + isEqual(other) { + return other instanceof DeleteFieldValueImpl; + } +} +/** + * Creates a child context for parsing SerializableFieldValues. + * + * This is different than calling `ParseContext.contextWith` because it keeps + * the fieldTransforms and fieldMask separate. + * + * The created context has its `dataSource` set to `UserDataSource.Argument`. + * Although these values are used with writes, any elements in these FieldValues + * are not considered writes since they cannot contain any FieldValue sentinels, + * etc. + * + * @param fieldValue - The sentinel FieldValue for which to create a child + * context. + * @param context - The parent context. + * @param arrayElement - Whether or not the FieldValue has an array. + */ +function createSentinelChildContext(fieldValue, context, arrayElement) { + return new ParseContextImpl({ + dataSource: 3 /* UserDataSource.Argument */, + targetDoc: context.settings.targetDoc, + methodName: fieldValue._methodName, + arrayElement + }, context.databaseId, context.serializer, context.ignoreUndefinedProperties); +} +class ServerTimestampFieldValueImpl extends FieldValue { + _toFieldTransform(context) { + return new FieldTransform(context.path, new ServerTimestampTransform()); + } + isEqual(other) { + return other instanceof ServerTimestampFieldValueImpl; + } +} +class ArrayUnionFieldValueImpl extends FieldValue { + constructor(methodName, _elements) { + super(methodName); + this._elements = _elements; + } + _toFieldTransform(context) { + const parseContext = createSentinelChildContext(this, context, + /*array=*/ true); + const parsedElements = this._elements.map(element => parseData(element, parseContext)); + const arrayUnion = new ArrayUnionTransformOperation(parsedElements); + return new FieldTransform(context.path, arrayUnion); + } + isEqual(other) { + return (other instanceof ArrayUnionFieldValueImpl && + util.deepEqual(this._elements, other._elements)); + } +} +class ArrayRemoveFieldValueImpl extends FieldValue { + constructor(methodName, _elements) { + super(methodName); + this._elements = _elements; + } + _toFieldTransform(context) { + const parseContext = createSentinelChildContext(this, context, + /*array=*/ true); + const parsedElements = this._elements.map(element => parseData(element, parseContext)); + const arrayUnion = new ArrayRemoveTransformOperation(parsedElements); + return new FieldTransform(context.path, arrayUnion); + } + isEqual(other) { + return (other instanceof ArrayRemoveFieldValueImpl && + util.deepEqual(this._elements, other._elements)); + } +} +class NumericIncrementFieldValueImpl extends FieldValue { + constructor(methodName, _operand) { + super(methodName); + this._operand = _operand; + } + _toFieldTransform(context) { + const numericIncrement = new NumericIncrementTransformOperation(context.serializer, toNumber(context.serializer, this._operand)); + return new FieldTransform(context.path, numericIncrement); + } + isEqual(other) { + return (other instanceof NumericIncrementFieldValueImpl && + this._operand === other._operand); + } +} +/** Parse update data from an update() call. */ +function parseUpdateData(userDataReader, methodName, targetDoc, input) { + const context = userDataReader.createContext(1 /* UserDataSource.Update */, methodName, targetDoc); + validatePlainObject('Data must be an object, but it was:', context, input); + const fieldMaskPaths = []; + const updateData = ObjectValue.empty(); + forEach(input, (key, value) => { + const path = fieldPathFromDotSeparatedString(methodName, key, targetDoc); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + value = util.getModularInstance(value); + const childContext = context.childContextForFieldPath(path); + if (value instanceof DeleteFieldValueImpl) { + // Add it to the field mask, but don't add anything to updateData. + fieldMaskPaths.push(path); + } + else { + const parsedValue = parseData(value, childContext); + if (parsedValue != null) { + fieldMaskPaths.push(path); + updateData.set(path, parsedValue); + } + } + }); + const mask = new FieldMask(fieldMaskPaths); + return new ParsedUpdateData(updateData, mask, context.fieldTransforms); +} +/** Parse update data from a list of field/value arguments. */ +function parseUpdateVarargs(userDataReader, methodName, targetDoc, field, value, moreFieldsAndValues) { + const context = userDataReader.createContext(1 /* UserDataSource.Update */, methodName, targetDoc); + const keys = [fieldPathFromArgument$1(methodName, field, targetDoc)]; + const values = [value]; + if (moreFieldsAndValues.length % 2 !== 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${methodName}() needs to be called with an even number ` + + 'of arguments that alternate between field names and values.'); + } + for (let i = 0; i < moreFieldsAndValues.length; i += 2) { + keys.push(fieldPathFromArgument$1(methodName, moreFieldsAndValues[i])); + values.push(moreFieldsAndValues[i + 1]); + } + const fieldMaskPaths = []; + const updateData = ObjectValue.empty(); + // We iterate in reverse order to pick the last value for a field if the + // user specified the field multiple times. + for (let i = keys.length - 1; i >= 0; --i) { + if (!fieldMaskContains(fieldMaskPaths, keys[i])) { + const path = keys[i]; + let value = values[i]; + // For Compat types, we have to "extract" the underlying types before + // performing validation. + value = util.getModularInstance(value); + const childContext = context.childContextForFieldPath(path); + if (value instanceof DeleteFieldValueImpl) { + // Add it to the field mask, but don't add anything to updateData. + fieldMaskPaths.push(path); + } + else { + const parsedValue = parseData(value, childContext); + if (parsedValue != null) { + fieldMaskPaths.push(path); + updateData.set(path, parsedValue); + } + } + } + } + const mask = new FieldMask(fieldMaskPaths); + return new ParsedUpdateData(updateData, mask, context.fieldTransforms); +} +/** + * Parse a "query value" (e.g. value in a where filter or a value in a cursor + * bound). + * + * @param allowArrays - Whether the query value is an array that may directly + * contain additional arrays (e.g. the operand of an `in` query). + */ +function parseQueryValue(userDataReader, methodName, input, allowArrays = false) { + const context = userDataReader.createContext(allowArrays ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */, methodName); + const parsed = parseData(input, context); + return parsed; +} +/** + * Parses user data to Protobuf Values. + * + * @param input - Data to be parsed. + * @param context - A context object representing the current path being parsed, + * the source of the data being parsed, etc. + * @returns The parsed value, or null if the value was a FieldValue sentinel + * that should not be included in the resulting parsed data. + */ +function parseData(input, context) { + // Unwrap the API type from the Compat SDK. This will return the API type + // from firestore-exp. + input = util.getModularInstance(input); + if (looksLikeJsonObject(input)) { + validatePlainObject('Unsupported field value:', context, input); + return parseObject(input, context); + } + else if (input instanceof FieldValue) { + // FieldValues usually parse into transforms (except deleteField()) + // in which case we do not want to include this field in our parsed data + // (as doing so will overwrite the field directly prior to the transform + // trying to transform it). So we don't add this location to + // context.fieldMask and we return null as our parsing result. + parseSentinelFieldValue(input, context); + return null; + } + else if (input === undefined && context.ignoreUndefinedProperties) { + // If the input is undefined it can never participate in the fieldMask, so + // don't handle this below. If `ignoreUndefinedProperties` is false, + // `parseScalarValue` will reject an undefined value. + return null; + } + else { + // If context.path is null we are inside an array and we don't support + // field mask paths more granular than the top-level array. + if (context.path) { + context.fieldMask.push(context.path); + } + if (input instanceof Array) { + // TODO(b/34871131): Include the path containing the array in the error + // message. + // In the case of IN queries, the parsed data is an array (representing + // the set of values to be included for the IN query) that may directly + // contain additional arrays (each representing an individual field + // value), so we disable this validation. + if (context.settings.arrayElement && + context.dataSource !== 4 /* UserDataSource.ArrayArgument */) { + throw context.createError('Nested arrays are not supported'); + } + return parseArray(input, context); + } + else { + return parseScalarValue(input, context); + } + } +} +function parseObject(obj, context) { + const fields = {}; + if (isEmpty(obj)) { + // If we encounter an empty object, we explicitly add it to the update + // mask to ensure that the server creates a map entry. + if (context.path && context.path.length > 0) { + context.fieldMask.push(context.path); + } + } + else { + forEach(obj, (key, val) => { + const parsedValue = parseData(val, context.childContextForField(key)); + if (parsedValue != null) { + fields[key] = parsedValue; + } + }); + } + return { mapValue: { fields } }; +} +function parseArray(array, context) { + const values = []; + let entryIndex = 0; + for (const entry of array) { + let parsedEntry = parseData(entry, context.childContextForArray(entryIndex)); + if (parsedEntry == null) { + // Just include nulls in the array for fields being replaced with a + // sentinel. + parsedEntry = { nullValue: 'NULL_VALUE' }; + } + values.push(parsedEntry); + entryIndex++; + } + return { arrayValue: { values } }; +} +/** + * "Parses" the provided FieldValueImpl, adding any necessary transforms to + * context.fieldTransforms. + */ +function parseSentinelFieldValue(value, context) { + // Sentinels are only supported with writes, and not within arrays. + if (!isWrite(context.dataSource)) { + throw context.createError(`${value._methodName}() can only be used with update() and set()`); + } + if (!context.path) { + throw context.createError(`${value._methodName}() is not currently supported inside arrays`); + } + const fieldTransform = value._toFieldTransform(context); + if (fieldTransform) { + context.fieldTransforms.push(fieldTransform); + } +} +/** + * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue) + * + * @returns The parsed value + */ +function parseScalarValue(value, context) { + value = util.getModularInstance(value); + if (value === null) { + return { nullValue: 'NULL_VALUE' }; + } + else if (typeof value === 'number') { + return toNumber(context.serializer, value); + } + else if (typeof value === 'boolean') { + return { booleanValue: value }; + } + else if (typeof value === 'string') { + return { stringValue: value }; + } + else if (value instanceof Date) { + const timestamp = Timestamp.fromDate(value); + return { + timestampValue: toTimestamp(context.serializer, timestamp) + }; + } + else if (value instanceof Timestamp) { + // Firestore backend truncates precision down to microseconds. To ensure + // offline mode works the same with regards to truncation, perform the + // truncation immediately without waiting for the backend to do that. + const timestamp = new Timestamp(value.seconds, Math.floor(value.nanoseconds / 1000) * 1000); + return { + timestampValue: toTimestamp(context.serializer, timestamp) + }; + } + else if (value instanceof GeoPoint) { + return { + geoPointValue: { + latitude: value.latitude, + longitude: value.longitude + } + }; + } + else if (value instanceof Bytes) { + return { bytesValue: toBytes(context.serializer, value._byteString) }; + } + else if (value instanceof DocumentReference) { + const thisDb = context.databaseId; + const otherDb = value.firestore._databaseId; + if (!otherDb.isEqual(thisDb)) { + throw context.createError('Document reference is for database ' + + `${otherDb.projectId}/${otherDb.database} but should be ` + + `for database ${thisDb.projectId}/${thisDb.database}`); + } + return { + referenceValue: toResourceName(value.firestore._databaseId || context.databaseId, value._key.path) + }; + } + else if (value instanceof VectorValue) { + return parseVectorValue(value, context); + } + else { + throw context.createError(`Unsupported field value: ${valueDescription(value)}`); + } +} +/** + * Creates a new VectorValue proto value (using the internal format). + */ +function parseVectorValue(value, context) { + const mapValue = { + fields: { + [TYPE_KEY]: { + stringValue: VECTOR_VALUE_SENTINEL + }, + [VECTOR_MAP_VECTORS_KEY]: { + arrayValue: { + values: value.toArray().map(value => { + if (typeof value !== 'number') { + throw context.createError('VectorValues must only contain numeric values.'); + } + return toDouble(context.serializer, value); + }) + } + } + } + }; + return { mapValue }; +} +/** + * Checks whether an object looks like a JSON object that should be converted + * into a struct. Normal class/prototype instances are considered to look like + * JSON objects since they should be converted to a struct value. Arrays, Dates, + * GeoPoints, etc. are not considered to look like JSON objects since they map + * to specific FieldValue types other than ObjectValue. + */ +function looksLikeJsonObject(input) { + return (typeof input === 'object' && + input !== null && + !(input instanceof Array) && + !(input instanceof Date) && + !(input instanceof Timestamp) && + !(input instanceof GeoPoint) && + !(input instanceof Bytes) && + !(input instanceof DocumentReference) && + !(input instanceof FieldValue) && + !(input instanceof VectorValue)); +} +function validatePlainObject(message, context, input) { + if (!looksLikeJsonObject(input) || !isPlainObject(input)) { + const description = valueDescription(input); + if (description === 'an object') { + // Massage the error if it was an object. + throw context.createError(message + ' a custom object'); + } + else { + throw context.createError(message + ' ' + description); + } + } +} +/** + * Helper that calls fromDotSeparatedString() but wraps any error thrown. + */ +function fieldPathFromArgument$1(methodName, path, targetDoc) { + // If required, replace the FieldPath Compat class with the firestore-exp + // FieldPath. + path = util.getModularInstance(path); + if (path instanceof FieldPath) { + return path._internalPath; + } + else if (typeof path === 'string') { + return fieldPathFromDotSeparatedString(methodName, path); + } + else { + const message = 'Field path arguments must be of type string or '; + throw createError(message, methodName, + /* hasConverter= */ false, + /* path= */ undefined, targetDoc); + } +} +/** + * Matches any characters in a field path string that are reserved. + */ +const FIELD_PATH_RESERVED = new RegExp('[~\\*/\\[\\]]'); +/** + * Wraps fromDotSeparatedString with an error message about the method that + * was thrown. + * @param methodName - The publicly visible method name + * @param path - The dot-separated string form of a field path which will be + * split on dots. + * @param targetDoc - The document against which the field path will be + * evaluated. + */ +function fieldPathFromDotSeparatedString(methodName, path, targetDoc) { + const found = path.search(FIELD_PATH_RESERVED); + if (found >= 0) { + throw createError(`Invalid field path (${path}). Paths must not contain ` + + `'~', '*', '/', '[', or ']'`, methodName, + /* hasConverter= */ false, + /* path= */ undefined, targetDoc); + } + try { + return new FieldPath(...path.split('.'))._internalPath; + } + catch (e) { + throw createError(`Invalid field path (${path}). Paths must not be empty, ` + + `begin with '.', end with '.', or contain '..'`, methodName, + /* hasConverter= */ false, + /* path= */ undefined, targetDoc); + } +} +function createError(reason, methodName, hasConverter, path, targetDoc) { + const hasPath = path && !path.isEmpty(); + const hasDocument = targetDoc !== undefined; + let message = `Function ${methodName}() called with invalid data`; + if (hasConverter) { + message += ' (via `toFirestore()`)'; + } + message += '. '; + let description = ''; + if (hasPath || hasDocument) { + description += ' (found'; + if (hasPath) { + description += ` in field ${path}`; + } + if (hasDocument) { + description += ` in document ${targetDoc}`; + } + description += ')'; + } + return new FirestoreError(Code.INVALID_ARGUMENT, message + reason + description); +} +/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ +function fieldMaskContains(haystack, needle) { + return haystack.some(v => v.isEqual(needle)); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ +class DocumentSnapshot$1 { + // Note: This class is stripped down version of the DocumentSnapshot in + // the legacy SDK. The changes are: + // - No support for SnapshotMetadata. + // - No support for SnapshotOptions. + /** @hideconstructor protected */ + constructor(_firestore, _userDataWriter, _key, _document, _converter) { + this._firestore = _firestore; + this._userDataWriter = _userDataWriter; + this._key = _key; + this._document = _document; + this._converter = _converter; + } + /** Property of the `DocumentSnapshot` that provides the document's ID. */ + get id() { + return this._key.path.lastSegment(); + } + /** + * The `DocumentReference` for the document included in the `DocumentSnapshot`. + */ + get ref() { + return new DocumentReference(this._firestore, this._converter, this._key); + } + /** + * Signals whether or not the document at the snapshot's location exists. + * + * @returns true if the document exists. + */ + exists() { + return this._document !== null; + } + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * @returns An `Object` containing all fields in the document or `undefined` + * if the document doesn't exist. + */ + data() { + if (!this._document) { + return undefined; + } + else if (this._converter) { + // We only want to use the converter and create a new DocumentSnapshot + // if a converter has been provided. + const snapshot = new QueryDocumentSnapshot$1(this._firestore, this._userDataWriter, this._key, this._document, + /* converter= */ null); + return this._converter.fromFirestore(snapshot); + } + else { + return this._userDataWriter.convertValue(this._document.data.value); + } + } + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + // We are using `any` here to avoid an explicit cast by our users. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get(fieldPath) { + if (this._document) { + const value = this._document.data.field(fieldPathFromArgument('DocumentSnapshot.get', fieldPath)); + if (value !== null) { + return this._userDataWriter.convertValue(value); + } + } + return undefined; + } +} +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ +class QueryDocumentSnapshot$1 extends DocumentSnapshot$1 { + /** + * Retrieves all fields in the document as an `Object`. + * + * @override + * @returns An `Object` containing all fields in the document. + */ + data() { + return super.data(); + } +} +/** + * Helper that calls `fromDotSeparatedString()` but wraps any error thrown. + */ +function fieldPathFromArgument(methodName, arg) { + if (typeof arg === 'string') { + return fieldPathFromDotSeparatedString(methodName, arg); + } + else if (arg instanceof FieldPath) { + return arg._internalPath; + } + else { + return arg._delegate._internalPath; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function validateHasExplicitOrderByForLimitToLast(query) { + if (query.limitType === "L" /* LimitType.Last */ && + query.explicitOrderBy.length === 0) { + throw new FirestoreError(Code.UNIMPLEMENTED, 'limitToLast() queries require specifying at least one orderBy() clause'); + } +} +/** + * An `AppliableConstraint` is an abstraction of a constraint that can be applied + * to a Firestore query. + */ +class AppliableConstraint { +} +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Firestore query. `QueryConstraint`s are created by invoking {@link where}, + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that + * also contains this `QueryConstraint`. + */ +class QueryConstraint extends AppliableConstraint { +} +function query(query, queryConstraint, ...additionalQueryConstraints) { + let queryConstraints = []; + if (queryConstraint instanceof AppliableConstraint) { + queryConstraints.push(queryConstraint); + } + queryConstraints = queryConstraints.concat(additionalQueryConstraints); + validateQueryConstraintArray(queryConstraints); + for (const constraint of queryConstraints) { + query = constraint._apply(query); + } + return query; +} +/** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ +class QueryFieldFilterConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(_field, _op, _value) { + super(); + this._field = _field; + this._op = _op; + this._value = _value; + /** The type of this query constraint */ + this.type = 'where'; + } + static _create(_field, _op, _value) { + return new QueryFieldFilterConstraint(_field, _op, _value); + } + _apply(query) { + const filter = this._parse(query); + validateNewFieldFilter(query._query, filter); + return new Query(query.firestore, query.converter, queryWithAddedFilter(query._query, filter)); + } + _parse(query) { + const reader = newUserDataReader(query.firestore); + const filter = newQueryFilter(query._query, 'where', reader, query.firestore._databaseId, this._field, this._op, this._value); + return filter; + } +} +/** + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. + * + * @param fieldPath - The path to compare + * @param opStr - The operation string (e.g "<", "<=", "==", "<", + * "<=", "!="). + * @param value - The value for comparison + * @returns The created {@link QueryFieldFilterConstraint}. + */ +function where(fieldPath, opStr, value) { + const op = opStr; + const field = fieldPathFromArgument('where', fieldPath); + return QueryFieldFilterConstraint._create(field, op, value); +} +/** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ +class QueryCompositeFilterConstraint extends AppliableConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + type, _queryConstraints) { + super(); + this.type = type; + this._queryConstraints = _queryConstraints; + } + static _create(type, _queryConstraints) { + return new QueryCompositeFilterConstraint(type, _queryConstraints); + } + _parse(query) { + const parsedFilters = this._queryConstraints + .map(queryConstraint => { + return queryConstraint._parse(query); + }) + .filter(parsedFilter => parsedFilter.getFilters().length > 0); + if (parsedFilters.length === 1) { + return parsedFilters[0]; + } + return CompositeFilter.create(parsedFilters, this._getOperator()); + } + _apply(query) { + const parsedFilter = this._parse(query); + if (parsedFilter.getFilters().length === 0) { + // Return the existing query if not adding any more filters (e.g. an empty + // composite filter). + return query; + } + validateNewFilter(query._query, parsedFilter); + return new Query(query.firestore, query.converter, queryWithAddedFilter(query._query, parsedFilter)); + } + _getQueryConstraints() { + return this._queryConstraints; + } + _getOperator() { + return this.type === 'and' ? "and" /* CompositeOperator.AND */ : "or" /* CompositeOperator.OR */; + } +} +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +function or(...queryConstraints) { + // Only support QueryFilterConstraints + queryConstraints.forEach(queryConstraint => validateQueryFilterConstraint('or', queryConstraint)); + return QueryCompositeFilterConstraint._create("or" /* CompositeOperator.OR */, queryConstraints); +} +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +function and(...queryConstraints) { + // Only support QueryFilterConstraints + queryConstraints.forEach(queryConstraint => validateQueryFilterConstraint('and', queryConstraint)); + return QueryCompositeFilterConstraint._create("and" /* CompositeOperator.AND */, queryConstraints); +} +/** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ +class QueryOrderByConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(_field, _direction) { + super(); + this._field = _field; + this._direction = _direction; + /** The type of this query constraint */ + this.type = 'orderBy'; + } + static _create(_field, _direction) { + return new QueryOrderByConstraint(_field, _direction); + } + _apply(query) { + const orderBy = newQueryOrderBy(query._query, this._field, this._direction); + return new Query(query.firestore, query.converter, queryWithAddedOrderBy(query._query, orderBy)); + } +} +/** + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the + * specified field, optionally in descending order instead of ascending. + * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * + * @param fieldPath - The field to sort by. + * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @returns The created {@link QueryOrderByConstraint}. + */ +function orderBy(fieldPath, directionStr = 'asc') { + const direction = directionStr; + const path = fieldPathFromArgument('orderBy', fieldPath); + return QueryOrderByConstraint._create(path, direction); +} +/** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ +class QueryLimitConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + type, _limit, _limitType) { + super(); + this.type = type; + this._limit = _limit; + this._limitType = _limitType; + } + static _create(type, _limit, _limitType) { + return new QueryLimitConstraint(type, _limit, _limitType); + } + _apply(query) { + return new Query(query.firestore, query.converter, queryWithLimit(query._query, this._limit, this._limitType)); + } +} +/** + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +function limit(limit) { + validatePositiveNumber('limit', limit); + return QueryLimitConstraint._create('limit', limit, "F" /* LimitType.First */); +} +/** + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. + * + * You must specify at least one `orderBy` clause for `limitToLast` queries, + * otherwise an exception will be thrown during execution. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +function limitToLast(limit) { + validatePositiveNumber('limitToLast', limit); + return QueryLimitConstraint._create('limitToLast', limit, "L" /* LimitType.Last */); +} +/** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ +class QueryStartAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + type, _docOrFields, _inclusive) { + super(); + this.type = type; + this._docOrFields = _docOrFields; + this._inclusive = _inclusive; + } + static _create(type, _docOrFields, _inclusive) { + return new QueryStartAtConstraint(type, _docOrFields, _inclusive); + } + _apply(query) { + const bound = newQueryBoundFromDocOrFields(query, this.type, this._docOrFields, this._inclusive); + return new Query(query.firestore, query.converter, queryWithStartAt(query._query, bound)); + } +} +function startAt(...docOrFields) { + return QueryStartAtConstraint._create('startAt', docOrFields, + /*inclusive=*/ true); +} +function startAfter(...docOrFields) { + return QueryStartAtConstraint._create('startAfter', docOrFields, + /*inclusive=*/ false); +} +/** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ +class QueryEndAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + type, _docOrFields, _inclusive) { + super(); + this.type = type; + this._docOrFields = _docOrFields; + this._inclusive = _inclusive; + } + static _create(type, _docOrFields, _inclusive) { + return new QueryEndAtConstraint(type, _docOrFields, _inclusive); + } + _apply(query) { + const bound = newQueryBoundFromDocOrFields(query, this.type, this._docOrFields, this._inclusive); + return new Query(query.firestore, query.converter, queryWithEndAt(query._query, bound)); + } +} +function endBefore(...docOrFields) { + return QueryEndAtConstraint._create('endBefore', docOrFields, + /*inclusive=*/ false); +} +function endAt(...docOrFields) { + return QueryEndAtConstraint._create('endAt', docOrFields, + /*inclusive=*/ true); +} +/** Helper function to create a bound from a document or fields */ +function newQueryBoundFromDocOrFields(query, methodName, docOrFields, inclusive) { + docOrFields[0] = util.getModularInstance(docOrFields[0]); + if (docOrFields[0] instanceof DocumentSnapshot$1) { + return newQueryBoundFromDocument(query._query, query.firestore._databaseId, methodName, docOrFields[0]._document, inclusive); + } + else { + const reader = newUserDataReader(query.firestore); + return newQueryBoundFromFields(query._query, query.firestore._databaseId, reader, methodName, docOrFields, inclusive); + } +} +function newQueryFilter(query, methodName, dataReader, databaseId, fieldPath, op, value) { + let fieldValue; + if (fieldPath.isKeyField()) { + if (op === "array-contains" /* Operator.ARRAY_CONTAINS */ || op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid Query. You can't perform '${op}' queries on documentId().`); + } + else if (op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */) { + validateDisjunctiveFilterElements(value, op); + const referenceList = []; + for (const arrayValue of value) { + referenceList.push(parseDocumentIdValue(databaseId, query, arrayValue)); + } + fieldValue = { arrayValue: { values: referenceList } }; + } + else { + fieldValue = parseDocumentIdValue(databaseId, query, value); + } + } + else { + if (op === "in" /* Operator.IN */ || + op === "not-in" /* Operator.NOT_IN */ || + op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) { + validateDisjunctiveFilterElements(value, op); + } + fieldValue = parseQueryValue(dataReader, methodName, value, + /* allowArrays= */ op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */); + } + const filter = FieldFilter.create(fieldPath, op, fieldValue); + return filter; +} +function newQueryOrderBy(query, fieldPath, direction) { + if (query.startAt !== null) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call startAt() or startAfter() before ' + + 'calling orderBy().'); + } + if (query.endAt !== null) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call endAt() or endBefore() before ' + + 'calling orderBy().'); + } + const orderBy = new OrderBy(fieldPath, direction); + return orderBy; +} +/** + * Create a `Bound` from a query and a document. + * + * Note that the `Bound` will always include the key of the document + * and so only the provided document will compare equal to the returned + * position. + * + * Will throw if the document does not contain all fields of the order by + * of the query or if any of the fields in the order by are an uncommitted + * server timestamp. + */ +function newQueryBoundFromDocument(query, databaseId, methodName, doc, inclusive) { + if (!doc) { + throw new FirestoreError(Code.NOT_FOUND, `Can't use a DocumentSnapshot that doesn't exist for ` + + `${methodName}().`); + } + const components = []; + // Because people expect to continue/end a query at the exact document + // provided, we need to use the implicit sort order rather than the explicit + // sort order, because it's guaranteed to contain the document key. That way + // the position becomes unambiguous and the query continues/ends exactly at + // the provided document. Without the key (by using the explicit sort + // orders), multiple documents could match the position, yielding duplicate + // results. + for (const orderBy of queryNormalizedOrderBy(query)) { + if (orderBy.field.isKeyField()) { + components.push(refValue(databaseId, doc.key)); + } + else { + const value = doc.data.field(orderBy.field); + if (isServerTimestamp(value)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You are trying to start or end a query using a ' + + 'document for which the field "' + + orderBy.field + + '" is an uncommitted server timestamp. (Since the value of ' + + 'this field is unknown, you cannot start/end a query with it.)'); + } + else if (value !== null) { + components.push(value); + } + else { + const field = orderBy.field.canonicalString(); + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. You are trying to start or end a query using a ` + + `document for which the field '${field}' (used as the ` + + `orderBy) does not exist.`); + } + } + } + return new Bound(components, inclusive); +} +/** + * Converts a list of field values to a `Bound` for the given query. + */ +function newQueryBoundFromFields(query, databaseId, dataReader, methodName, values, inclusive) { + // Use explicit order by's because it has to match the query the user made + const orderBy = query.explicitOrderBy; + if (values.length > orderBy.length) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Too many arguments provided to ${methodName}(). ` + + `The number of arguments must be less than or equal to the ` + + `number of orderBy() clauses`); + } + const components = []; + for (let i = 0; i < values.length; i++) { + const rawValue = values[i]; + const orderByComponent = orderBy[i]; + if (orderByComponent.field.isKeyField()) { + if (typeof rawValue !== 'string') { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. Expected a string for document ID in ` + + `${methodName}(), but got a ${typeof rawValue}`); + } + if (!isCollectionGroupQuery(query) && rawValue.indexOf('/') !== -1) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection and ordering by documentId(), ` + + `the value passed to ${methodName}() must be a plain document ID, but ` + + `'${rawValue}' contains a slash.`); + } + const path = query.path.child(ResourcePath.fromString(rawValue)); + if (!DocumentKey.isDocumentKey(path)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection group and ordering by ` + + `documentId(), the value passed to ${methodName}() must result in a ` + + `valid document path, but '${path}' is not because it contains an odd number ` + + `of segments.`); + } + const key = new DocumentKey(path); + components.push(refValue(databaseId, key)); + } + else { + const wrapped = parseQueryValue(dataReader, methodName, rawValue); + components.push(wrapped); + } + } + return new Bound(components, inclusive); +} +/** + * Parses the given `documentIdValue` into a `ReferenceValue`, throwing + * appropriate errors if the value is anything other than a `DocumentReference` + * or `string`, or if the string is malformed. + */ +function parseDocumentIdValue(databaseId, query, documentIdValue) { + documentIdValue = util.getModularInstance(documentIdValue); + if (typeof documentIdValue === 'string') { + if (documentIdValue === '') { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. When querying with documentId(), you ' + + 'must provide a valid document ID, but it was an empty string.'); + } + if (!isCollectionGroupQuery(query) && documentIdValue.indexOf('/') !== -1) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection by ` + + `documentId(), you must provide a plain document ID, but ` + + `'${documentIdValue}' contains a '/' character.`); + } + const path = query.path.child(ResourcePath.fromString(documentIdValue)); + if (!DocumentKey.isDocumentKey(path)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection group by ` + + `documentId(), the value provided must result in a valid document path, ` + + `but '${path}' is not because it has an odd number of segments (${path.length}).`); + } + return refValue(databaseId, new DocumentKey(path)); + } + else if (documentIdValue instanceof DocumentReference) { + return refValue(databaseId, documentIdValue._key); + } + else { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying with documentId(), you must provide a valid ` + + `string or a DocumentReference, but it was: ` + + `${valueDescription(documentIdValue)}.`); + } +} +/** + * Validates that the value passed into a disjunctive filter satisfies all + * array requirements. + */ +function validateDisjunctiveFilterElements(value, operator) { + if (!Array.isArray(value) || value.length === 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid Query. A non-empty array is required for ' + + `'${operator.toString()}' filters.`); + } +} +/** + * Given an operator, returns the set of operators that cannot be used with it. + * + * This is not a comprehensive check, and this function should be removed in the + * long term. Validations should occur in the Firestore backend. + * + * Operators in a query must adhere to the following set of rules: + * 1. Only one inequality per query. + * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators. + */ +function conflictingOps(op) { + switch (op) { + case "!=" /* Operator.NOT_EQUAL */: + return ["!=" /* Operator.NOT_EQUAL */, "not-in" /* Operator.NOT_IN */]; + case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */: + case "in" /* Operator.IN */: + return ["not-in" /* Operator.NOT_IN */]; + case "not-in" /* Operator.NOT_IN */: + return [ + "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */, + "in" /* Operator.IN */, + "not-in" /* Operator.NOT_IN */, + "!=" /* Operator.NOT_EQUAL */ + ]; + default: + return []; + } +} +function validateNewFieldFilter(query, fieldFilter) { + const conflictingOp = findOpInsideFilters(query.filters, conflictingOps(fieldFilter.op)); + if (conflictingOp !== null) { + // Special case when it's a duplicate op to give a slightly clearer error message. + if (conflictingOp === fieldFilter.op) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You cannot use more than one ' + + `'${fieldFilter.op.toString()}' filter.`); + } + else { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. You cannot use '${fieldFilter.op.toString()}' filters ` + + `with '${conflictingOp.toString()}' filters.`); + } + } +} +function validateNewFilter(query, filter) { + let testQuery = query; + const subFilters = filter.getFlattenedFilters(); + for (const subFilter of subFilters) { + validateNewFieldFilter(testQuery, subFilter); + testQuery = queryWithAddedFilter(testQuery, subFilter); + } +} +// Checks if any of the provided filter operators are included in the given list of filters and +// returns the first one that is, or null if none are. +function findOpInsideFilters(filters, operators) { + for (const filter of filters) { + for (const fieldFilter of filter.getFlattenedFilters()) { + if (operators.indexOf(fieldFilter.op) >= 0) { + return fieldFilter.op; + } + } + } + return null; +} +function validateQueryFilterConstraint(functionName, queryConstraint) { + if (!(queryConstraint instanceof QueryFieldFilterConstraint) && + !(queryConstraint instanceof QueryCompositeFilterConstraint)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${functionName}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`); + } +} +function validateQueryConstraintArray(queryConstraint) { + const compositeFilterCount = queryConstraint.filter(filter => filter instanceof QueryCompositeFilterConstraint).length; + const fieldFilterCount = queryConstraint.filter(filter => filter instanceof QueryFieldFilterConstraint).length; + if (compositeFilterCount > 1 || + (compositeFilterCount > 0 && fieldFilterCount > 0)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'InvalidQuery. When using composite filters, you cannot use ' + + 'more than one filter at the top level. Consider nesting the multiple ' + + 'filters within an `and(...)` statement. For example: ' + + 'change `query(query, where(...), or(...))` to ' + + '`query(query, and(where(...), or(...)))`.'); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Converts Firestore's internal types to the JavaScript types that we expose + * to the user. + * + * @internal + */ +class AbstractUserDataWriter { + convertValue(value, serverTimestampBehavior = 'none') { + switch (typeOrder(value)) { + case 0 /* TypeOrder.NullValue */: + return null; + case 1 /* TypeOrder.BooleanValue */: + return value.booleanValue; + case 2 /* TypeOrder.NumberValue */: + return normalizeNumber(value.integerValue || value.doubleValue); + case 3 /* TypeOrder.TimestampValue */: + return this.convertTimestamp(value.timestampValue); + case 4 /* TypeOrder.ServerTimestampValue */: + return this.convertServerTimestamp(value, serverTimestampBehavior); + case 5 /* TypeOrder.StringValue */: + return value.stringValue; + case 6 /* TypeOrder.BlobValue */: + return this.convertBytes(normalizeByteString(value.bytesValue)); + case 7 /* TypeOrder.RefValue */: + return this.convertReference(value.referenceValue); + case 8 /* TypeOrder.GeoPointValue */: + return this.convertGeoPoint(value.geoPointValue); + case 9 /* TypeOrder.ArrayValue */: + return this.convertArray(value.arrayValue, serverTimestampBehavior); + case 11 /* TypeOrder.ObjectValue */: + return this.convertObject(value.mapValue, serverTimestampBehavior); + case 10 /* TypeOrder.VectorValue */: + return this.convertVectorValue(value.mapValue); + default: + throw fail(0xf2a2, { + value + }); + } + } + convertObject(mapValue, serverTimestampBehavior) { + return this.convertObjectMap(mapValue.fields, serverTimestampBehavior); + } + /** + * @internal + */ + convertObjectMap(fields, serverTimestampBehavior = 'none') { + const result = {}; + forEach(fields, (key, value) => { + result[key] = this.convertValue(value, serverTimestampBehavior); + }); + return result; + } + /** + * @internal + */ + convertVectorValue(mapValue) { + const values = mapValue.fields?.[VECTOR_MAP_VECTORS_KEY].arrayValue?.values?.map(value => { + return normalizeNumber(value.doubleValue); + }); + return new VectorValue(values); + } + convertGeoPoint(value) { + return new GeoPoint(normalizeNumber(value.latitude), normalizeNumber(value.longitude)); + } + convertArray(arrayValue, serverTimestampBehavior) { + return (arrayValue.values || []).map(value => this.convertValue(value, serverTimestampBehavior)); + } + convertServerTimestamp(value, serverTimestampBehavior) { + switch (serverTimestampBehavior) { + case 'previous': + const previousValue = getPreviousValue(value); + if (previousValue == null) { + return null; + } + return this.convertValue(previousValue, serverTimestampBehavior); + case 'estimate': + return this.convertTimestamp(getLocalWriteTime(value)); + default: + return null; + } + } + convertTimestamp(value) { + const normalizedValue = normalizeTimestamp(value); + return new Timestamp(normalizedValue.seconds, normalizedValue.nanos); + } + convertDocumentKey(name, expectedDatabaseId) { + const resourcePath = ResourcePath.fromString(name); + hardAssert(isValidResourceName(resourcePath), 0x25d8, { name }); + const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3)); + const key = new DocumentKey(resourcePath.popFirst(5)); + if (!databaseId.isEqual(expectedDatabaseId)) { + // TODO(b/64130202): Somehow support foreign references. + logError(`Document ${key} contains a document ` + + `reference within a different database (` + + `${databaseId.projectId}/${databaseId.database}) which is not ` + + `supported. It will be treated as a reference in the current ` + + `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` + + `instead.`); + } + return key; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Converts custom model object of type T into `DocumentData` by applying the + * converter if it exists. + * + * This function is used when converting user objects to `DocumentData` + * because we want to provide the user with a more specific error message if + * their `set()` or fails due to invalid data originating from a `toFirestore()` + * call. + */ +function applyFirestoreDataConverter(converter, value, options) { + let convertedValue; + if (converter) { + if (options && (options.merge || options.mergeFields)) { + // Cast to `any` in order to satisfy the union type constraint on + // toFirestore(). + // eslint-disable-next-line @typescript-eslint/no-explicit-any + convertedValue = converter.toFirestore(value, options); + } + else { + convertedValue = converter.toFirestore(value); + } + } + else { + convertedValue = value; + } + return convertedValue; +} +class LiteUserDataWriter extends AbstractUserDataWriter { + constructor(firestore) { + super(); + this.firestore = firestore; + } + convertBytes(bytes) { + return new Bytes(bytes); + } + convertReference(name) { + const key = this.convertDocumentKey(name, this.firestore._databaseId); + return new DocumentReference(this.firestore, /* converter= */ null, key); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ +function sum(field) { + return new AggregateField('sum', fieldPathFromArgument$1('sum', field)); +} +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ +function average(field) { + return new AggregateField('avg', fieldPathFromArgument$1('average', field)); +} +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ +function count() { + return new AggregateField('count'); +} +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ +function aggregateFieldEqual(left, right) { + return (left instanceof AggregateField && + right instanceof AggregateField && + left.aggregateType === right.aggregateType && + left._internalFieldPath?.canonicalString() === + right._internalFieldPath?.canonicalString()); +} +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ +function aggregateQuerySnapshotEqual(left, right) { + return (queryEqual(left.query, right.query) && util.deepEqual(left.data(), right.data())); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function isPartialObserver(obj) { + return implementsAnyMethods(obj, ['next', 'error', 'complete']); +} +/** + * Returns true if obj is an object and contains at least one of the specified + * methods. + */ +function implementsAnyMethods(obj, methods) { + if (typeof obj !== 'object' || obj === null) { + return false; + } + const object = obj; + for (const method of methods) { + if (method in object && typeof object[method] === 'function') { + return true; + } + } + return false; +} + +const encoder = newTextEncoder(); +function lengthPrefixedString(o) { + const str = JSON.stringify(o); + const l = encoder.encode(str).byteLength; + return `${l}${str}`; +} +// TODO(wuandy): Ideally, these should use `TestBundleBuilder` above. +const meta = { + metadata: { + id: 'test-bundle', + createTime: { seconds: 1577836805, nanos: 6 }, + version: 1, + totalDocuments: 1, + totalBytes: 416 + } +}; +lengthPrefixedString(meta); +const doc1Meta = { + documentMetadata: { + name: 'projects/test-project/databases/(default)/documents/collectionId/doc1', + readTime: { seconds: 5, nanos: 6 }, + exists: true + } +}; +lengthPrefixedString(doc1Meta); +const doc1 = { + document: { + name: 'projects/test-project/databases/(default)/documents/collectionId/doc1', + createTime: { seconds: 1, nanos: 2000000 }, + updateTime: { seconds: 3, nanos: 4000 }, + fields: { foo: { stringValue: 'value' }, bar: { integerValue: -42 } } + } +}; +lengthPrefixedString(doc1); +const doc2Meta = { + documentMetadata: { + name: 'projects/test-project/databases/(default)/documents/collectionId/doc2', + readTime: { seconds: 5, nanos: 6 }, + exists: true + } +}; +lengthPrefixedString(doc2Meta); +const doc2 = { + document: { + name: 'projects/test-project/databases/(default)/documents/collectionId/doc2', + createTime: { seconds: 1, nanos: 2000000 }, + updateTime: { seconds: 3, nanos: 4000 }, + fields: { + foo: { stringValue: 'value1' }, + bar: { integerValue: 42 }, + emptyArray: { arrayValue: {} }, + emptyMap: { mapValue: {} } + } + } +}; +lengthPrefixedString(doc2); +const noDocMeta = { + documentMetadata: { + name: 'projects/test-project/databases/(default)/documents/collectionId/nodoc', + readTime: { seconds: 5, nanos: 6 }, + exists: false + } +}; +lengthPrefixedString(noDocMeta); +const limitQuery = { + namedQuery: { + name: 'limitQuery', + bundledQuery: { + parent: 'projects/fireeats-97d5e/databases/(default)/documents', + structuredQuery: { + from: [{ collectionId: 'node_3.7.5_7Li7XoCjutvNxwD0tpo9' }], + orderBy: [{ field: { fieldPath: 'sort' }, direction: 'DESCENDING' }], + limit: { 'value': 1 } + }, + limitType: 'FIRST' + }, + readTime: { 'seconds': 1590011379, 'nanos': 191164000 } + } +}; +lengthPrefixedString(limitQuery); +const limitToLastQuery = { + namedQuery: { + name: 'limitToLastQuery', + bundledQuery: { + parent: 'projects/fireeats-97d5e/databases/(default)/documents', + structuredQuery: { + from: [{ collectionId: 'node_3.7.5_7Li7XoCjutvNxwD0tpo9' }], + orderBy: [{ field: { fieldPath: 'sort' }, direction: 'ASCENDING' }], + limit: { 'value': 1 } + }, + limitType: 'LAST' + }, + readTime: { 'seconds': 1590011379, 'nanos': 543063000 } + } +}; +lengthPrefixedString(limitToLastQuery); + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const BUNDLE_VERSION = 1; +/** + * Builds a Firestore data bundle with results from the given document and query snapshots. + */ +class BundleBuilder { + constructor(firestore, bundleId) { + this.firestore = firestore; + this.bundleId = bundleId; + // Resulting documents for the bundle, keyed by full document path. + this.documents = new Map(); + // Named queries saved in the bundle, keyed by query name. + this.namedQueries = new Map(); + // The latest read time among all bundled documents and queries. + this.latestReadTime = new Timestamp(0, 0); + this.databaseId = firestore._databaseId; + // useProto3Json is true because the objects will be serialized to JSON string + // before being written to the bundle buffer. + this.serializer = new JsonProtoSerializer(this.databaseId, + /*useProto3Json=*/ true); + this.userDataReader = new UserDataReader(this.databaseId, true, this.serializer); + } + /** + * Adds data from a DocumentSnapshot to the bundle. + * @internal + * @param docBundleData A DocumentSnapshotBundleData containing information from the + * DocumentSnapshot. Note we cannot accept a DocumentSnapshot directly due to a circular + * dependency error. + * @param queryName The name of the QuerySnapshot if this document is part of a Query. + */ + addBundleDocument(docBundleData, queryName) { + const originalDocument = this.documents.get(docBundleData.documentPath); + const originalQueries = originalDocument?.metadata.queries; + const docReadTime = docBundleData.readTime; + const origDocReadTime = !!originalDocument?.metadata + .readTime + ? fromTimestamp(originalDocument.metadata.readTime) + : null; + const neitherHasReadTime = !docReadTime && origDocReadTime == null; + const docIsNewer = docReadTime !== undefined && + (origDocReadTime == null || origDocReadTime < docReadTime); + if (neitherHasReadTime || docIsNewer) { + // Store document. + this.documents.set(docBundleData.documentPath, { + document: this.toBundleDocument(docBundleData), + metadata: { + name: toName(this.serializer, docBundleData.documentKey), + readTime: !!docReadTime + ? toTimestamp(this.serializer, docReadTime) // Convert Timestamp to proto format. + : undefined, + exists: docBundleData.documentExists + } + }); + } + if (docReadTime && docReadTime > this.latestReadTime) { + this.latestReadTime = docReadTime; + } + // Update `queries` to include both original and `queryName`. + if (queryName) { + const newDocument = this.documents.get(docBundleData.documentPath); + newDocument.metadata.queries = originalQueries || []; + newDocument.metadata.queries.push(queryName); + } + } + /** + * Adds data from a QuerySnapshot to the bundle. + * @internal + * @param docBundleData A QuerySnapshotBundleData containing information from the + * QuerySnapshot. Note we cannot accept a QuerySnapshot directly due to a circular + * dependency error. + */ + addBundleQuery(queryBundleData) { + if (this.namedQueries.has(queryBundleData.name)) { + throw new Error(`Query name conflict: ${name} has already been added.`); + } + let latestReadTime = new Timestamp(0, 0); + for (const docBundleData of queryBundleData.docBundleDataArray) { + this.addBundleDocument(docBundleData, queryBundleData.name); + if (docBundleData.readTime && docBundleData.readTime > latestReadTime) { + latestReadTime = docBundleData.readTime; + } + } + const queryTarget = toQueryTarget(this.serializer, queryToTarget(queryBundleData.query)); + const bundledQuery = { + parent: queryBundleData.parent, + structuredQuery: queryTarget.queryTarget.structuredQuery + }; + this.namedQueries.set(queryBundleData.name, { + name: queryBundleData.name, + bundledQuery, + readTime: toTimestamp(this.serializer, latestReadTime) + }); + } + /** + * Convert data from a DocumentSnapshot into the serialized form within a bundle. + * @private + * @internal + * @param docBundleData a DocumentSnapshotBundleData containing the data required to + * serialize a document. + */ + toBundleDocument(docBundleData) { + // a parse context is typically used for validating and parsing user data, but in this + // case we are using it internally to convert DocumentData to Proto3 JSON + const context = this.userDataReader.createContext(4 /* UserDataSource.ArrayArgument */, 'internal toBundledDocument'); + const proto3Fields = parseObject(docBundleData.documentData, context); + return { + name: toName(this.serializer, docBundleData.documentKey), + fields: proto3Fields.mapValue.fields, + updateTime: toTimestamp(this.serializer, docBundleData.versionTime), + createTime: toTimestamp(this.serializer, docBundleData.createdTime) + }; + } + /** + * Converts a IBundleElement to a Buffer whose content is the length prefixed JSON representation + * of the element. + * @private + * @internal + * @param bundleElement A ProtoBundleElement that is expected to be Proto3 JSON compatible. + */ + lengthPrefixedString(bundleElement) { + const str = JSON.stringify(bundleElement); + // TODO: it's not ideal to have to re-encode all of these strings multiple times + // It may be more performant to return a UInt8Array that is concatenated to other + // UInt8Arrays instead of returning and concatenating strings and then + // converting the full string to UInt8Array. + const l = encoder.encode(str).byteLength; + return `${l}${str}`; + } + /** + * Construct a serialized string containing document and query information that has previously + * been added to the BundleBuilder through the addBundleDocument and addBundleQuery methods. + * @internal + */ + build() { + let bundleString = ''; + for (const namedQuery of this.namedQueries.values()) { + bundleString += this.lengthPrefixedString({ namedQuery }); + } + for (const bundledDocument of this.documents.values()) { + const documentMetadata = bundledDocument.metadata; + bundleString += this.lengthPrefixedString({ documentMetadata }); + // Write to the bundle if document exists. + const document = bundledDocument.document; + if (document) { + bundleString += this.lengthPrefixedString({ document }); + } + } + const metadata = { + id: this.bundleId, + createTime: toTimestamp(this.serializer, this.latestReadTime), + version: BUNDLE_VERSION, + totalDocuments: this.documents.size, + // TODO: it's not ideal to have to re-encode all of these strings multiple times + totalBytes: encoder.encode(bundleString).length + }; + // Prepends the metadata element to the bundleBuffer: `bundleBuffer` is the second argument to `Buffer.concat`. + bundleString = this.lengthPrefixedString({ metadata }) + bundleString; + return bundleString; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function buildDocumentSnapshotJsonBundle(db, document, docData, path) { + const builder = new BundleBuilder(db, AutoId.newId()); + builder.addBundleDocument(documentToDocumentSnapshotBundleData(path, docData, document)); + return builder.build(); +} +function buildQuerySnapshotJsonBundle(db, query, bundleName, parent, paths, docs, documentData) { + const docBundleDataArray = []; + for (let i = 0; i < docs.length; i++) { + docBundleDataArray.push(documentToDocumentSnapshotBundleData(paths[i], documentData[i], docs[i])); + } + const bundleData = { + name: bundleName, + query, + parent, + docBundleDataArray + }; + const builder = new BundleBuilder(db, bundleName); + builder.addBundleQuery(bundleData); + return builder.build(); +} +// Formats Document data for bundling a DocumentSnapshot. +function documentToDocumentSnapshotBundleData(path, documentData, document) { + return { + documentData, + documentKey: document.mutableCopy().key, + documentPath: path, + documentExists: true, + createdTime: document.createTime.toTimestamp(), + readTime: document.readTime.toTimestamp(), + versionTime: document.version.toTimestamp() + }; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const NOT_SUPPORTED = 'NOT SUPPORTED'; +/** + * Metadata about a snapshot, describing the state of the snapshot. + */ +class SnapshotMetadata { + /** @hideconstructor */ + constructor(hasPendingWrites, fromCache) { + this.hasPendingWrites = hasPendingWrites; + this.fromCache = fromCache; + } + /** + * Returns true if this `SnapshotMetadata` is equal to the provided one. + * + * @param other - The `SnapshotMetadata` to compare against. + * @returns true if this `SnapshotMetadata` is equal to the provided one. + */ + isEqual(other) { + return (this.hasPendingWrites === other.hasPendingWrites && + this.fromCache === other.fromCache); + } +} +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ +class DocumentSnapshot extends DocumentSnapshot$1 { + /** @hideconstructor protected */ + constructor(_firestore, userDataWriter, key, document, metadata, converter) { + super(_firestore, userDataWriter, key, document, converter); + this._firestore = _firestore; + this._firestoreImpl = _firestore; + this.metadata = metadata; + } + /** + * Returns whether or not the data exists. True if the document exists. + */ + exists() { + return super.exists(); + } + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * By default, `serverTimestamp()` values that have not yet been + * set to their final value will be returned as `null`. You can override + * this by passing an options object. + * + * @param options - An options object to configure how data is retrieved from + * the snapshot (for example the desired behavior for server timestamps that + * have not yet been set to their final value). + * @returns An `Object` containing all fields in the document or `undefined` if + * the document doesn't exist. + */ + data(options = {}) { + if (!this._document) { + return undefined; + } + else if (this._converter) { + // We only want to use the converter and create a new DocumentSnapshot + // if a converter has been provided. + const snapshot = new QueryDocumentSnapshot(this._firestore, this._userDataWriter, this._key, this._document, this.metadata, + /* converter= */ null); + return this._converter.fromFirestore(snapshot, options); + } + else { + return this._userDataWriter.convertValue(this._document.data.value, options.serverTimestamps); + } + } + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * By default, a `serverTimestamp()` that has not yet been set to + * its final value will be returned as `null`. You can override this by + * passing an options object. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @param options - An options object to configure how the field is retrieved + * from the snapshot (for example the desired behavior for server timestamps + * that have not yet been set to their final value). + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + // We are using `any` here to avoid an explicit cast by our users. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get(fieldPath, options = {}) { + if (this._document) { + const value = this._document.data.field(fieldPathFromArgument('DocumentSnapshot.get', fieldPath)); + if (value !== null) { + return this._userDataWriter.convertValue(value, options.serverTimestamps); + } + } + return undefined; + } + /** + * Returns a JSON-serializable representation of this `DocumentSnapshot` instance. + * + * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this + * `DocumentSnapshot` has pending writes. + */ + toJSON() { + if (this.metadata.hasPendingWrites) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'DocumentSnapshot.toJSON() attempted to serialize a document with pending writes. ' + + 'Await waitForPendingWrites() before invoking toJSON().'); + } + const document = this._document; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const result = {}; + result['type'] = DocumentSnapshot._jsonSchemaVersion; + result['bundle'] = ''; + result['bundleSource'] = 'DocumentSnapshot'; + result['bundleName'] = this._key.toString(); + if (!document || + !document.isValidDocument() || + !document.isFoundDocument()) { + return result; + } + const documentData = this._userDataWriter.convertObjectMap(document.data.value.mapValue.fields, 'previous'); + result['bundle'] = buildDocumentSnapshotJsonBundle(this._firestore, document, documentData, this.ref.path); + return result; + } +} +DocumentSnapshot._jsonSchemaVersion = 'firestore/documentSnapshot/1.0'; +DocumentSnapshot._jsonSchema = { + type: property('string', DocumentSnapshot._jsonSchemaVersion), + bundleSource: property('string', 'DocumentSnapshot'), + bundleName: property('string'), + bundle: property('string') +}; +function documentSnapshotFromJSON(db, json, converter) { + if (validateJSON(json, DocumentSnapshot._jsonSchema)) { + if (json.bundle === NOT_SUPPORTED) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'The provided JSON object was created in a client environment, which is not supported.'); + } + // Parse the bundle data. + const serializer = newSerializer(db._databaseId); + const bundleReader = createBundleReaderSync(json.bundle, serializer); + const elements = bundleReader.getElements(); + const bundleLoader = new BundleLoader(bundleReader.getMetadata(), serializer); + for (const element of elements) { + bundleLoader.addSizedElement(element); + } + // Ensure that we have the correct number of documents in the bundle. + const bundledDocuments = bundleLoader.documents; + if (bundledDocuments.length !== 1) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Expected bundle data to contain 1 document, but it contains ${bundledDocuments.length} documents.`); + } + // Build out the internal document data. + const document = fromDocument(serializer, bundledDocuments[0].document); + const documentKey = new DocumentKey(ResourcePath.fromString(json.bundleName)); + // Return the external facing DocumentSnapshot. + return new DocumentSnapshot(db, new LiteUserDataWriter(db), documentKey, document, new SnapshotMetadata( + /* hasPendingWrites= */ false, + /* fromCache= */ false), converter ? converter : null); + } +} +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ +class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * By default, `serverTimestamp()` values that have not yet been + * set to their final value will be returned as `null`. You can override + * this by passing an options object. + * + * @override + * @param options - An options object to configure how data is retrieved from + * the snapshot (for example the desired behavior for server timestamps that + * have not yet been set to their final value). + * @returns An `Object` containing all fields in the document. + */ + data(options = {}) { + return super.data(options); + } +} +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ +class QuerySnapshot { + /** @hideconstructor */ + constructor(_firestore, _userDataWriter, query, _snapshot) { + this._firestore = _firestore; + this._userDataWriter = _userDataWriter; + this._snapshot = _snapshot; + this.metadata = new SnapshotMetadata(_snapshot.hasPendingWrites, _snapshot.fromCache); + this.query = query; + } + /** An array of all the documents in the `QuerySnapshot`. */ + get docs() { + const result = []; + this.forEach(doc => result.push(doc)); + return result; + } + /** The number of documents in the `QuerySnapshot`. */ + get size() { + return this._snapshot.docs.size; + } + /** True if there are no documents in the `QuerySnapshot`. */ + get empty() { + return this.size === 0; + } + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ + forEach(callback, thisArg) { + this._snapshot.docs.forEach(doc => { + callback.call(thisArg, new QueryDocumentSnapshot(this._firestore, this._userDataWriter, doc.key, doc, new SnapshotMetadata(this._snapshot.mutatedKeys.has(doc.key), this._snapshot.fromCache), this.query.converter)); + }); + } + /** + * Returns an array of the documents changes since the last snapshot. If this + * is the first snapshot, all documents will be in the list as 'added' + * changes. + * + * @param options - `SnapshotListenOptions` that control whether metadata-only + * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger + * snapshot events. + */ + docChanges(options = {}) { + const includeMetadataChanges = !!options.includeMetadataChanges; + if (includeMetadataChanges && this._snapshot.excludesMetadataChanges) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'To include metadata changes with your document changes, you must ' + + 'also pass { includeMetadataChanges:true } to onSnapshot().'); + } + if (!this._cachedChanges || + this._cachedChangesIncludeMetadataChanges !== includeMetadataChanges) { + this._cachedChanges = changesFromSnapshot(this, includeMetadataChanges); + this._cachedChangesIncludeMetadataChanges = includeMetadataChanges; + } + return this._cachedChanges; + } + /** + * Returns a JSON-serializable representation of this `QuerySnapshot` instance. + * + * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this + * `QuerySnapshot` has pending writes. + */ + toJSON() { + if (this.metadata.hasPendingWrites) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'QuerySnapshot.toJSON() attempted to serialize a document with pending writes. ' + + 'Await waitForPendingWrites() before invoking toJSON().'); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const result = {}; + result['type'] = QuerySnapshot._jsonSchemaVersion; + result['bundleSource'] = 'QuerySnapshot'; + result['bundleName'] = AutoId.newId(); + const databaseId = this._firestore._databaseId.database; + const projectId = this._firestore._databaseId.projectId; + const parent = `projects/${projectId}/databases/${databaseId}/documents`; + const documents = []; + const documentData = []; + const paths = []; + this.docs.forEach(doc => { + if (doc._document === null) { + return; + } + documents.push(doc._document); + documentData.push(this._userDataWriter.convertObjectMap(doc._document.data.value.mapValue.fields, 'previous')); + paths.push(doc.ref.path); + }); + result['bundle'] = buildQuerySnapshotJsonBundle(this._firestore, this.query._query, result['bundleName'], parent, paths, documents, documentData); + return result; + } +} +QuerySnapshot._jsonSchemaVersion = 'firestore/querySnapshot/1.0'; +QuerySnapshot._jsonSchema = { + type: property('string', QuerySnapshot._jsonSchemaVersion), + bundleSource: property('string', 'QuerySnapshot'), + bundleName: property('string'), + bundle: property('string') +}; +function querySnapshotFromJSON(db, json, converter) { + if (validateJSON(json, QuerySnapshot._jsonSchema)) { + if (json.bundle === NOT_SUPPORTED) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'The provided JSON object was created in a client environment, which is not supported.'); + } + // Parse the bundle data. + const serializer = newSerializer(db._databaseId); + const bundleReader = createBundleReaderSync(json.bundle, serializer); + const elements = bundleReader.getElements(); + const bundleLoader = new BundleLoader(bundleReader.getMetadata(), serializer); + for (const element of elements) { + bundleLoader.addSizedElement(element); + } + if (bundleLoader.queries.length !== 1) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Snapshot data expected 1 query but found ${bundleLoader.queries.length} queries.`); + } + // Create an internal Query object from the named query in the bundle. + const query = fromBundledQuery(bundleLoader.queries[0].bundledQuery); + // Construct the arrays of document data for the query. + const bundledDocuments = bundleLoader.documents; + let documentSet = new DocumentSet(); + bundledDocuments.map(bundledDocument => { + const document = fromDocument(serializer, bundledDocument.document); + documentSet = documentSet.add(document); + }); + // Create a view snapshot of the query and documents. + const viewSnapshot = ViewSnapshot.fromInitialDocuments(query, documentSet, documentKeySet() /* Zero mutated keys signifies no pending writes. */, + /* fromCache= */ false, + /* hasCachedResults= */ false); + // Create an external Query object, required to construct the QuerySnapshot. + const externalQuery = new Query(db, converter ? converter : null, query); + // Return a new QuerySnapshot with all of the collected data. + return new QuerySnapshot(db, new LiteUserDataWriter(db), externalQuery, viewSnapshot); + } +} +/** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */ +function changesFromSnapshot(querySnapshot, includeMetadataChanges) { + if (querySnapshot._snapshot.oldDocs.isEmpty()) { + let index = 0; + return querySnapshot._snapshot.docChanges.map(change => { + const doc = new QueryDocumentSnapshot(querySnapshot._firestore, querySnapshot._userDataWriter, change.doc.key, change.doc, new SnapshotMetadata(querySnapshot._snapshot.mutatedKeys.has(change.doc.key), querySnapshot._snapshot.fromCache), querySnapshot.query.converter); + change.doc; + return { + type: 'added', + doc, + oldIndex: -1, + newIndex: index++ + }; + }); + } + else { + // A `DocumentSet` that is updated incrementally as changes are applied to use + // to lookup the index of a document. + let indexTracker = querySnapshot._snapshot.oldDocs; + return querySnapshot._snapshot.docChanges + .filter(change => includeMetadataChanges || change.type !== 3 /* ChangeType.Metadata */) + .map(change => { + const doc = new QueryDocumentSnapshot(querySnapshot._firestore, querySnapshot._userDataWriter, change.doc.key, change.doc, new SnapshotMetadata(querySnapshot._snapshot.mutatedKeys.has(change.doc.key), querySnapshot._snapshot.fromCache), querySnapshot.query.converter); + let oldIndex = -1; + let newIndex = -1; + if (change.type !== 0 /* ChangeType.Added */) { + oldIndex = indexTracker.indexOf(change.doc.key); + indexTracker = indexTracker.delete(change.doc.key); + } + if (change.type !== 1 /* ChangeType.Removed */) { + indexTracker = indexTracker.add(change.doc); + newIndex = indexTracker.indexOf(change.doc.key); + } + return { + type: resultChangeType(change.type), + doc, + oldIndex, + newIndex + }; + }); + } +} +function resultChangeType(type) { + switch (type) { + case 0 /* ChangeType.Added */: + return 'added'; + case 2 /* ChangeType.Modified */: + case 3 /* ChangeType.Metadata */: + return 'modified'; + case 1 /* ChangeType.Removed */: + return 'removed'; + default: + return fail(0xf03d, { type }); + } +} +// TODO(firestoreexp): Add tests for snapshotEqual with different snapshot +// metadata +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ +function snapshotEqual(left, right) { + if (left instanceof DocumentSnapshot && right instanceof DocumentSnapshot) { + return (left._firestore === right._firestore && + left._key.isEqual(right._key) && + (left._document === null + ? right._document === null + : left._document.isEqual(right._document)) && + left._converter === right._converter); + } + else if (left instanceof QuerySnapshot && right instanceof QuerySnapshot) { + return (left._firestore === right._firestore && + queryEqual(left.query, right.query) && + left.metadata.isEqual(right.metadata) && + left._snapshot.isEqual(right._snapshot)); + } + return false; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Reads the document referred to by this `DocumentReference`. + * + * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting + * for data from the server, but it may return cached data or fail if you are + * offline and the server cannot be reached. To specify this behavior, invoke + * {@link getDocFromCache} or {@link getDocFromServer}. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +function getDoc(reference) { + reference = cast(reference, DocumentReference); + const firestore = cast(reference.firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + return firestoreClientGetDocumentViaSnapshotListener(client, reference._key).then(snapshot => convertToDocSnapshot(firestore, reference, snapshot)); +} +class ExpUserDataWriter extends AbstractUserDataWriter { + constructor(firestore) { + super(); + this.firestore = firestore; + } + convertBytes(bytes) { + return new Bytes(bytes); + } + convertReference(name) { + const key = this.convertDocumentKey(name, this.firestore._databaseId); + return new DocumentReference(this.firestore, /* converter= */ null, key); + } +} +/** + * Reads the document referred to by this `DocumentReference` from cache. + * Returns an error if the document is not currently cached. + * + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +function getDocFromCache(reference) { + reference = cast(reference, DocumentReference); + const firestore = cast(reference.firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + const userDataWriter = new ExpUserDataWriter(firestore); + return firestoreClientGetDocumentFromLocalCache(client, reference._key).then(doc => new DocumentSnapshot(firestore, userDataWriter, reference._key, doc, new SnapshotMetadata(doc !== null && doc.hasLocalMutations, + /* fromCache= */ true), reference.converter)); +} +/** + * Reads the document referred to by this `DocumentReference` from the server. + * Returns an error if the network is not available. + * + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +function getDocFromServer(reference) { + reference = cast(reference, DocumentReference); + const firestore = cast(reference.firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + return firestoreClientGetDocumentViaSnapshotListener(client, reference._key, { + source: 'server' + }).then(snapshot => convertToDocSnapshot(firestore, reference, snapshot)); +} +/** + * Executes the query and returns the results as a `QuerySnapshot`. + * + * Note: `getDocs()` attempts to provide up-to-date data when possible by + * waiting for data from the server, but it may return cached data or fail if + * you are offline and the server cannot be reached. To specify this behavior, + * invoke {@link getDocsFromCache} or {@link getDocsFromServer}. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +function getDocs(query) { + query = cast(query, Query); + const firestore = cast(query.firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + const userDataWriter = new ExpUserDataWriter(firestore); + validateHasExplicitOrderByForLimitToLast(query._query); + return firestoreClientGetDocumentsViaSnapshotListener(client, query._query).then(snapshot => new QuerySnapshot(firestore, userDataWriter, query, snapshot)); +} +/** + * Executes the query and returns the results as a `QuerySnapshot` from cache. + * Returns an empty result set if no documents matching the query are currently + * cached. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +function getDocsFromCache(query) { + query = cast(query, Query); + const firestore = cast(query.firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + const userDataWriter = new ExpUserDataWriter(firestore); + return firestoreClientGetDocumentsFromLocalCache(client, query._query).then(snapshot => new QuerySnapshot(firestore, userDataWriter, query, snapshot)); +} +/** + * Executes the query and returns the results as a `QuerySnapshot` from the + * server. Returns an error if the network is not available. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +function getDocsFromServer(query) { + query = cast(query, Query); + const firestore = cast(query.firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + const userDataWriter = new ExpUserDataWriter(firestore); + return firestoreClientGetDocumentsViaSnapshotListener(client, query._query, { + source: 'server' + }).then(snapshot => new QuerySnapshot(firestore, userDataWriter, query, snapshot)); +} +function setDoc(reference, data, options) { + reference = cast(reference, DocumentReference); + const firestore = cast(reference.firestore, Firestore); + const convertedValue = applyFirestoreDataConverter(reference.converter, data, options); + const dataReader = newUserDataReader(firestore); + const parsed = parseSetData(dataReader, 'setDoc', reference._key, convertedValue, reference.converter !== null, options); + const mutation = parsed.toMutation(reference._key, Precondition.none()); + return executeWrite(firestore, [mutation]); +} +function updateDoc(reference, fieldOrUpdateData, value, ...moreFieldsAndValues) { + reference = cast(reference, DocumentReference); + const firestore = cast(reference.firestore, Firestore); + const dataReader = newUserDataReader(firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + fieldOrUpdateData = util.getModularInstance(fieldOrUpdateData); + let parsed; + if (typeof fieldOrUpdateData === 'string' || + fieldOrUpdateData instanceof FieldPath) { + parsed = parseUpdateVarargs(dataReader, 'updateDoc', reference._key, fieldOrUpdateData, value, moreFieldsAndValues); + } + else { + parsed = parseUpdateData(dataReader, 'updateDoc', reference._key, fieldOrUpdateData); + } + const mutation = parsed.toMutation(reference._key, Precondition.exists(true)); + return executeWrite(firestore, [mutation]); +} +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * @param reference - A reference to the document to delete. + * @returns A Promise resolved once the document has been successfully + * deleted from the backend (note that it won't resolve while you're offline). + */ +function deleteDoc(reference) { + const firestore = cast(reference.firestore, Firestore); + const mutations = [new DeleteMutation(reference._key, Precondition.none())]; + return executeWrite(firestore, mutations); +} +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend (Note that it + * won't resolve while you're offline). + */ +function addDoc(reference, data) { + const firestore = cast(reference.firestore, Firestore); + const docRef = doc(reference); + const convertedValue = applyFirestoreDataConverter(reference.converter, data); + const dataReader = newUserDataReader(reference.firestore); + const parsed = parseSetData(dataReader, 'addDoc', docRef._key, convertedValue, reference.converter !== null, {}); + const mutation = parsed.toMutation(docRef._key, Precondition.exists(false)); + return executeWrite(firestore, [mutation]).then(() => docRef); +} +function onSnapshot(reference, ...args) { + // onSnapshot for Query or Document. + reference = util.getModularInstance(reference); + let options = { + includeMetadataChanges: false, + source: 'default' + }; + let currArg = 0; + if (typeof args[currArg] === 'object' && !isPartialObserver(args[currArg])) { + options = args[currArg++]; + } + const internalOptions = { + includeMetadataChanges: options.includeMetadataChanges, + source: options.source + }; + if (isPartialObserver(args[currArg])) { + const userObserver = args[currArg]; + args[currArg] = userObserver.next?.bind(userObserver); + args[currArg + 1] = userObserver.error?.bind(userObserver); + args[currArg + 2] = userObserver.complete?.bind(userObserver); + } + let observer; + let firestore; + let internalQuery; + if (reference instanceof DocumentReference) { + firestore = cast(reference.firestore, Firestore); + internalQuery = newQueryForPath(reference._key.path); + observer = { + next: snapshot => { + if (args[currArg]) { + args[currArg](convertToDocSnapshot(firestore, reference, snapshot)); + } + }, + error: args[currArg + 1], + complete: args[currArg + 2] + }; + } + else { + const query = cast(reference, Query); + firestore = cast(query.firestore, Firestore); + internalQuery = query._query; + const userDataWriter = new ExpUserDataWriter(firestore); + observer = { + next: snapshot => { + if (args[currArg]) { + args[currArg](new QuerySnapshot(firestore, userDataWriter, query, snapshot)); + } + }, + error: args[currArg + 1], + complete: args[currArg + 2] + }; + validateHasExplicitOrderByForLimitToLast(reference._query); + } + const client = ensureFirestoreConfigured(firestore); + return firestoreClientListen(client, internalQuery, internalOptions, observer); +} +function onSnapshotResume(reference, snapshotJson, ...args) { + const db = util.getModularInstance(reference); + const json = normalizeSnapshotJsonFields(snapshotJson); + if (json.error) { + throw new FirestoreError(Code.INVALID_ARGUMENT, json.error); + } + let curArg = 0; + let options = undefined; + if (typeof args[curArg] === 'object' && !isPartialObserver(args[curArg])) { + options = args[curArg++]; + } + if (json.bundleSource === 'QuerySnapshot') { + let observer = null; + if (typeof args[curArg] === 'object' && isPartialObserver(args[curArg])) { + const userObserver = args[curArg++]; + observer = { + next: userObserver.next, + error: userObserver.error, + complete: userObserver.complete + }; + } + else { + observer = { + next: args[curArg++], + error: args[curArg++], + complete: args[curArg++] + }; + } + return onSnapshotQuerySnapshotBundle(db, json, options, observer, args[curArg]); + } + else if (json.bundleSource === 'DocumentSnapshot') { + let observer = null; + if (typeof args[curArg] === 'object' && isPartialObserver(args[curArg])) { + const userObserver = args[curArg++]; + observer = { + next: userObserver.next, + error: userObserver.error, + complete: userObserver.complete + }; + } + else { + observer = { + next: args[curArg++], + error: args[curArg++], + complete: args[curArg++] + }; + } + return onSnapshotDocumentSnapshotBundle(db, json, options, observer, args[curArg]); + } + else { + throw new FirestoreError(Code.INVALID_ARGUMENT, `unsupported bundle source: ${json.bundleSource}`); + } +} +function onSnapshotsInSync(firestore, arg) { + firestore = cast(firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + const observer = isPartialObserver(arg) + ? arg + : { + next: arg + }; + return firestoreClientAddSnapshotsInSyncListener(client, observer); +} +/** + * Locally writes `mutations` on the async queue. + * @internal + */ +function executeWrite(firestore, mutations) { + const client = ensureFirestoreConfigured(firestore); + return firestoreClientWrite(client, mutations); +} +/** + * Converts a {@link ViewSnapshot} that contains the single document specified by `ref` + * to a {@link DocumentSnapshot}. + */ +function convertToDocSnapshot(firestore, ref, snapshot) { + const doc = snapshot.docs.get(ref._key); + const userDataWriter = new ExpUserDataWriter(firestore); + return new DocumentSnapshot(firestore, userDataWriter, ref._key, doc, new SnapshotMetadata(snapshot.hasPendingWrites, snapshot.fromCache), ref.converter); +} +/** + * Ensures the data required to construct an {@link onSnapshot} listener exist in a `snapshotJson` + * object that originates from {@link DocumentSnapshot.toJSON} or {@link Querysnapshot.toJSON}. The + * data is normalized into a typed object. + * + * @param snapshotJson - The JSON object that the app provided to {@link onSnapshot}. + * @returns A normalized object that contains all of the required bundle JSON fields. If + * {@link snapshotJson} doesn't contain the required fields, or if the fields exist as empty + * strings, then the {@link snapshotJson.error} field will be a non empty string. + * + * @internal + */ +function normalizeSnapshotJsonFields(snapshotJson) { + const result = { + bundle: '', + bundleName: '', + bundleSource: '' + }; + const requiredKeys = ['bundle', 'bundleName', 'bundleSource']; + for (const key of requiredKeys) { + if (!(key in snapshotJson)) { + result.error = `snapshotJson missing required field: ${key}`; + break; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const value = snapshotJson[key]; + if (typeof value !== 'string') { + result.error = `snapshotJson field '${key}' must be a string.`; + break; + } + if (value.length === 0) { + result.error = `snapshotJson field '${key}' cannot be an empty string.`; + break; + } + if (key === 'bundle') { + result.bundle = value; + } + else if (key === 'bundleName') { + result.bundleName = value; + } + else if (key === 'bundleSource') { + result.bundleSource = value; + } + } + return result; +} +/** + * Loads the bundle in a separate task and then invokes {@link onSnapshot} with a + * {@link DocumentReference} for the document in the bundle. + * + * @param firestore - The {@link Firestore} instance for the {@link onSnapshot} operation request. + * @param json - The JSON bundle to load, produced by {@link DocumentSnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot + * listener. + * + * @internal + */ +function onSnapshotDocumentSnapshotBundle(db, json, options, observer, converter) { + let unsubscribed = false; + let internalUnsubscribe; + const loadTask = loadBundle(db, json.bundle); + loadTask + .then(() => { + if (!unsubscribed) { + const docReference = new DocumentReference(db, converter ? converter : null, DocumentKey.fromPath(json.bundleName)); + internalUnsubscribe = onSnapshot(docReference, options ? options : {}, observer); + } + }) + .catch(e => { + if (observer.error) { + observer.error(e); + } + return () => { }; + }); + return () => { + if (unsubscribed) { + return; + } + unsubscribed = true; + if (internalUnsubscribe) { + internalUnsubscribe(); + } + }; +} +/** + * Loads the bundle in a separate task and then invokes {@link onSnapshot} with a + * {@link Query} that represents the Query in the bundle. + * + * @param firestore - The {@link Firestore} instance for the {@link onSnapshot} operation request. + * @param json - The JSON bundle to load, produced by {@link QuerySnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot + * listener. + * + * @internal + */ +function onSnapshotQuerySnapshotBundle(db, json, options, observer, converter) { + let unsubscribed = false; + let internalUnsubscribe; + const loadTask = loadBundle(db, json.bundle); + loadTask + .then(() => namedQuery(db, json.bundleName)) + .then(query => { + if (query && !unsubscribed) { + const realQuery = query; + if (converter) { + realQuery.withConverter(converter); + } + internalUnsubscribe = onSnapshot(query, options ? options : {}, observer); + } + }) + .catch(e => { + if (observer.error) { + observer.error(e); + } + return () => { }; + }); + return () => { + if (unsubscribed) { + return; + } + unsubscribed = true; + if (internalUnsubscribe) { + internalUnsubscribe(); + } + }; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ +function getCountFromServer(query) { + const countQuerySpec = { + count: count() + }; + return getAggregateFromServer(query, countQuerySpec); +} +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregateFromServer(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ +function getAggregateFromServer(query, aggregateSpec) { + const firestore = cast(query.firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => { + return new AggregateImpl(alias, aggregate.aggregateType, aggregate._internalFieldPath); + }); + // Run the aggregation and convert the results + return firestoreClientRunAggregateQuery(client, query._query, internalAggregates).then(aggregateResult => convertToAggregateQuerySnapshot(firestore, query, aggregateResult)); +} +/** + * Converts the core aggregation result to an `AggregateQuerySnapshot` + * that can be returned to the consumer. + * @param query + * @param aggregateResult Core aggregation result + * @internal + */ +function convertToAggregateQuerySnapshot(firestore, query, aggregateResult) { + const userDataWriter = new ExpUserDataWriter(firestore); + const querySnapshot = new AggregateQuerySnapshot(query, userDataWriter, aggregateResult); + return querySnapshot; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class MemoryLocalCacheImpl { + constructor(settings) { + this.kind = 'memory'; + this._onlineComponentProvider = OnlineComponentProvider.provider; + if (settings?.garbageCollector) { + this._offlineComponentProvider = + settings.garbageCollector._offlineComponentProvider; + } + else { + this._offlineComponentProvider = { + build: () => new LruGcMemoryOfflineComponentProvider(undefined) + }; + } + } + toJSON() { + return { kind: this.kind }; + } +} +class PersistentLocalCacheImpl { + constructor(settings) { + this.kind = 'persistent'; + let tabManager; + if (settings?.tabManager) { + settings.tabManager._initialize(settings); + tabManager = settings.tabManager; + } + else { + tabManager = persistentSingleTabManager(undefined); + tabManager._initialize(settings); + } + this._onlineComponentProvider = tabManager._onlineComponentProvider; + this._offlineComponentProvider = tabManager._offlineComponentProvider; + } + toJSON() { + return { kind: this.kind }; + } +} +class MemoryEagerGarbageCollectorImpl { + constructor() { + this.kind = 'memoryEager'; + this._offlineComponentProvider = MemoryOfflineComponentProvider.provider; + } + toJSON() { + return { kind: this.kind }; + } +} +class MemoryLruGarbageCollectorImpl { + constructor(cacheSize) { + this.kind = 'memoryLru'; + this._offlineComponentProvider = { + build: () => new LruGcMemoryOfflineComponentProvider(cacheSize) + }; + } + toJSON() { + return { kind: this.kind }; + } +} +/** + * Creates an instance of `MemoryEagerGarbageCollector`. This is also the + * default garbage collector unless it is explicitly specified otherwise. + */ +function memoryEagerGarbageCollector() { + return new MemoryEagerGarbageCollectorImpl(); +} +/** + * Creates an instance of `MemoryLruGarbageCollector`. + * + * A target size can be specified as part of the setting parameter. The + * collector will start deleting documents once the cache size exceeds + * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes). + */ +function memoryLruGarbageCollector(settings) { + return new MemoryLruGarbageCollectorImpl(settings?.cacheSizeBytes); +} +/** + * Creates an instance of `MemoryLocalCache`. The instance can be set to + * `FirestoreSettings.cache` to tell the SDK which cache layer to use. + */ +function memoryLocalCache(settings) { + return new MemoryLocalCacheImpl(settings); +} +/** + * Creates an instance of `PersistentLocalCache`. The instance can be set to + * `FirestoreSettings.cache` to tell the SDK which cache layer to use. + * + * Persistent cache cannot be used in a Node.js environment. + */ +function persistentLocalCache(settings) { + return new PersistentLocalCacheImpl(settings); +} +class SingleTabManagerImpl { + constructor(forceOwnership) { + this.forceOwnership = forceOwnership; + this.kind = 'persistentSingleTab'; + } + toJSON() { + return { kind: this.kind }; + } + /** + * @internal + */ + _initialize(settings) { + this._onlineComponentProvider = OnlineComponentProvider.provider; + this._offlineComponentProvider = { + build: (onlineComponents) => new IndexedDbOfflineComponentProvider(onlineComponents, settings?.cacheSizeBytes, this.forceOwnership) + }; + } +} +class MultiTabManagerImpl { + constructor() { + this.kind = 'PersistentMultipleTab'; + } + toJSON() { + return { kind: this.kind }; + } + /** + * @internal + */ + _initialize(settings) { + this._onlineComponentProvider = OnlineComponentProvider.provider; + this._offlineComponentProvider = { + build: (onlineComponents) => new MultiTabOfflineComponentProvider(onlineComponents, settings?.cacheSizeBytes) + }; + } +} +/** + * Creates an instance of `PersistentSingleTabManager`. + * + * @param settings Configures the created tab manager. + */ +function persistentSingleTabManager(settings) { + return new SingleTabManagerImpl(settings?.forceOwnership); +} +/** + * Creates an instance of `PersistentMultipleTabManager`. + */ +function persistentMultipleTabManager() { + return new MultiTabManagerImpl(); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const DEFAULT_TRANSACTION_OPTIONS = { + maxAttempts: 5 +}; +function validateTransactionOptions(options) { + if (options.maxAttempts < 1) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Max attempts must be at least 1'); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It + * provides methods for adding writes to the write batch. None of the writes + * will be committed (or visible locally) until {@link WriteBatch.commit} is + * called. + */ +class WriteBatch { + /** @hideconstructor */ + constructor(_firestore, _commitHandler) { + this._firestore = _firestore; + this._commitHandler = _commitHandler; + this._mutations = []; + this._committed = false; + this._dataReader = newUserDataReader(_firestore); + } + set(documentRef, data, options) { + this._verifyNotCommitted(); + const ref = validateReference(documentRef, this._firestore); + const convertedValue = applyFirestoreDataConverter(ref.converter, data, options); + const parsed = parseSetData(this._dataReader, 'WriteBatch.set', ref._key, convertedValue, ref.converter !== null, options); + this._mutations.push(parsed.toMutation(ref._key, Precondition.none())); + return this; + } + update(documentRef, fieldOrUpdateData, value, ...moreFieldsAndValues) { + this._verifyNotCommitted(); + const ref = validateReference(documentRef, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + fieldOrUpdateData = util.getModularInstance(fieldOrUpdateData); + let parsed; + if (typeof fieldOrUpdateData === 'string' || + fieldOrUpdateData instanceof FieldPath) { + parsed = parseUpdateVarargs(this._dataReader, 'WriteBatch.update', ref._key, fieldOrUpdateData, value, moreFieldsAndValues); + } + else { + parsed = parseUpdateData(this._dataReader, 'WriteBatch.update', ref._key, fieldOrUpdateData); + } + this._mutations.push(parsed.toMutation(ref._key, Precondition.exists(true))); + return this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + delete(documentRef) { + this._verifyNotCommitted(); + const ref = validateReference(documentRef, this._firestore); + this._mutations = this._mutations.concat(new DeleteMutation(ref._key, Precondition.none())); + return this; + } + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `Promise` resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit (note that it won't + * resolve while you're offline). + */ + commit() { + this._verifyNotCommitted(); + this._committed = true; + if (this._mutations.length > 0) { + return this._commitHandler(this._mutations); + } + return Promise.resolve(); + } + _verifyNotCommitted() { + if (this._committed) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'A write batch can no longer be used after commit() ' + + 'has been called.'); + } + } +} +function validateReference(documentRef, firestore) { + documentRef = util.getModularInstance(documentRef); + if (documentRef.firestore !== firestore) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Provided document reference is from a different Firestore instance.'); + } + else { + return documentRef; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the +// legacy SDK. +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ +class Transaction$1 { + /** @hideconstructor */ + constructor(_firestore, _transaction) { + this._firestore = _firestore; + this._transaction = _transaction; + this._dataReader = newUserDataReader(_firestore); + } + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ + get(documentRef) { + const ref = validateReference(documentRef, this._firestore); + const userDataWriter = new LiteUserDataWriter(this._firestore); + return this._transaction.lookup([ref._key]).then(docs => { + if (!docs || docs.length !== 1) { + return fail(0x5de9); + } + const doc = docs[0]; + if (doc.isFoundDocument()) { + return new DocumentSnapshot$1(this._firestore, userDataWriter, doc.key, doc, ref.converter); + } + else if (doc.isNoDocument()) { + return new DocumentSnapshot$1(this._firestore, userDataWriter, ref._key, null, ref.converter); + } + else { + throw fail(0x4801, { + doc + }); + } + }); + } + set(documentRef, value, options) { + const ref = validateReference(documentRef, this._firestore); + const convertedValue = applyFirestoreDataConverter(ref.converter, value, options); + const parsed = parseSetData(this._dataReader, 'Transaction.set', ref._key, convertedValue, ref.converter !== null, options); + this._transaction.set(ref._key, parsed); + return this; + } + update(documentRef, fieldOrUpdateData, value, ...moreFieldsAndValues) { + const ref = validateReference(documentRef, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + fieldOrUpdateData = util.getModularInstance(fieldOrUpdateData); + let parsed; + if (typeof fieldOrUpdateData === 'string' || + fieldOrUpdateData instanceof FieldPath) { + parsed = parseUpdateVarargs(this._dataReader, 'Transaction.update', ref._key, fieldOrUpdateData, value, moreFieldsAndValues); + } + else { + parsed = parseUpdateData(this._dataReader, 'Transaction.update', ref._key, fieldOrUpdateData); + } + this._transaction.update(ref._key, parsed); + return this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + delete(documentRef) { + const ref = validateReference(documentRef, this._firestore); + this._transaction.delete(ref._key); + return this; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ +class Transaction extends Transaction$1 { + // This class implements the same logic as the Transaction API in the Lite SDK + // but is subclassed in order to return its own DocumentSnapshot types. + /** @hideconstructor */ + constructor(_firestore, _transaction) { + super(_firestore, _transaction); + this._firestore = _firestore; + } + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ + get(documentRef) { + const ref = validateReference(documentRef, this._firestore); + const userDataWriter = new ExpUserDataWriter(this._firestore); + return super + .get(documentRef) + .then(liteDocumentSnapshot => new DocumentSnapshot(this._firestore, userDataWriter, ref._key, liteDocumentSnapshot._document, new SnapshotMetadata( + /* hasPendingWrites= */ false, + /* fromCache= */ false), ref.converter)); + } +} +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ +function runTransaction(firestore, updateFunction, options) { + firestore = cast(firestore, Firestore); + const optionsWithDefaults = { + ...DEFAULT_TRANSACTION_OPTIONS, + ...options + }; + validateTransactionOptions(optionsWithDefaults); + const client = ensureFirestoreConfigured(firestore); + return firestoreClientTransaction(client, internalTransaction => updateFunction(new Transaction(firestore, internalTransaction)), optionsWithDefaults); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. + */ +function deleteField() { + return new DeleteFieldValueImpl('deleteField'); +} +/** + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to + * include a server-generated timestamp in the written data. + */ +function serverTimestamp() { + return new ServerTimestampFieldValueImpl('serverTimestamp'); +} +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array + * value that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements - The elements to union into the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()`. + */ +function arrayUnion(...elements) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new ArrayUnionFieldValueImpl('arrayUnion', elements); +} +/** + * Returns a special value that can be used with {@link (setDoc:1)} or {@link + * updateDoc:1} that tells the server to remove the given elements from any + * array value that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is not + * already an array it will be overwritten with an empty array. + * + * @param elements - The elements to remove from the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +function arrayRemove(...elements) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new ArrayRemoveFieldValueImpl('arrayRemove', elements); +} +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by + * the given value. + * + * If either the operand or the current field value uses floating point + * precision, all arithmetic follows IEEE 754 semantics. If both values are + * integers, values outside of JavaScript's safe number range + * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to + * precision loss. Furthermore, once processed by the Firestore backend, all + * integer operations are capped between -2^63 and 2^63-1. + * + * If the current field value is not of type `number`, or if the field does not + * yet exist, the transformation sets the field to the given value. + * + * @param n - The value to increment by. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +function increment(n) { + return new NumericIncrementFieldValueImpl('increment', n); +} +/** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ +function vector(values) { + return new VectorValue(values); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch} + * is 500. + * + * Unlike transactions, write batches are persisted offline and therefore are + * preferable when you don't need to condition your writes on read data. + * + * @returns A {@link WriteBatch} that can be used to atomically execute multiple + * writes. + */ +function writeBatch(firestore) { + firestore = cast(firestore, Firestore); + ensureFirestoreConfigured(firestore); + return new WriteBatch(firestore, mutations => executeWrite(firestore, mutations)); +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function setIndexConfiguration(firestore, jsonOrConfiguration) { + firestore = cast(firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + if (!client._uninitializedComponentsProvider || + client._uninitializedComponentsProvider._offline.kind === 'memory') { + // PORTING NOTE: We don't return an error if the user has not enabled + // persistence since `enableIndexeddbPersistence()` can fail on the Web. + logWarn('Cannot enable indexes when persistence is disabled'); + return Promise.resolve(); + } + const parsedIndexes = parseIndexes(jsonOrConfiguration); + return firestoreClientSetIndexConfiguration(client, parsedIndexes); +} +function parseIndexes(jsonOrConfiguration) { + const indexConfiguration = typeof jsonOrConfiguration === 'string' + ? tryParseJson(jsonOrConfiguration) + : jsonOrConfiguration; + const parsedIndexes = []; + if (Array.isArray(indexConfiguration.indexes)) { + for (const index of indexConfiguration.indexes) { + const collectionGroup = tryGetString(index, 'collectionGroup'); + const segments = []; + if (Array.isArray(index.fields)) { + for (const field of index.fields) { + const fieldPathString = tryGetString(field, 'fieldPath'); + const fieldPath = fieldPathFromDotSeparatedString('setIndexConfiguration', fieldPathString); + if (field.arrayConfig === 'CONTAINS') { + segments.push(new IndexSegment(fieldPath, 2 /* IndexKind.CONTAINS */)); + } + else if (field.order === 'ASCENDING') { + segments.push(new IndexSegment(fieldPath, 0 /* IndexKind.ASCENDING */)); + } + else if (field.order === 'DESCENDING') { + segments.push(new IndexSegment(fieldPath, 1 /* IndexKind.DESCENDING */)); + } + } + } + parsedIndexes.push(new FieldIndex(FieldIndex.UNKNOWN_ID, collectionGroup, segments, IndexState.empty())); + } + } + return parsedIndexes; +} +function tryParseJson(json) { + try { + return JSON.parse(json); + } + catch (e) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Failed to parse JSON: ' + e?.message); + } +} +function tryGetString(data, property) { + if (typeof data[property] !== 'string') { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Missing string value for: ' + property); + } + return data[property]; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `PersistentCacheIndexManager` for configuring persistent cache indexes used + * for local query execution. + * + * To use, call `getPersistentCacheIndexManager()` to get an instance. + */ +class PersistentCacheIndexManager { + /** @hideconstructor */ + constructor(_firestore) { + this._firestore = _firestore; + /** A type string to uniquely identify instances of this class. */ + this.type = 'PersistentCacheIndexManager'; + } +} +/** + * Returns the PersistentCache Index Manager used by the given `Firestore` + * object. + * + * @return The `PersistentCacheIndexManager` instance, or `null` if local + * persistent storage is not in use. + */ +function getPersistentCacheIndexManager(firestore) { + firestore = cast(firestore, Firestore); + const cachedInstance = persistentCacheIndexManagerByFirestore.get(firestore); + if (cachedInstance) { + return cachedInstance; + } + const client = ensureFirestoreConfigured(firestore); + if (client._uninitializedComponentsProvider?._offline.kind !== 'persistent') { + return null; + } + const instance = new PersistentCacheIndexManager(firestore); + persistentCacheIndexManagerByFirestore.set(firestore, instance); + return instance; +} +/** + * Enables the SDK to create persistent cache indexes automatically for local + * query execution when the SDK believes cache indexes can help improve + * performance. + * + * This feature is disabled by default. + */ +function enablePersistentCacheIndexAutoCreation(indexManager) { + setPersistentCacheIndexAutoCreationEnabled(indexManager, true); +} +/** + * Stops creating persistent cache indexes automatically for local query + * execution. The indexes which have been created by calling + * `enablePersistentCacheIndexAutoCreation()` still take effect. + */ +function disablePersistentCacheIndexAutoCreation(indexManager) { + setPersistentCacheIndexAutoCreationEnabled(indexManager, false); +} +/** + * Removes all persistent cache indexes. + * + * Please note this function will also deletes indexes generated by + * `setIndexConfiguration()`, which is deprecated. + */ +function deleteAllPersistentCacheIndexes(indexManager) { + const client = ensureFirestoreConfigured(indexManager._firestore); + const promise = firestoreClientDeleteAllFieldIndexes(client); + promise + .then(_ => logDebug('deleting all persistent cache indexes succeeded')) + .catch(error => logWarn('deleting all persistent cache indexes failed', error)); +} +function setPersistentCacheIndexAutoCreationEnabled(indexManager, isEnabled) { + const client = ensureFirestoreConfigured(indexManager._firestore); + const promise = firestoreClientSetPersistentCacheIndexAutoCreationEnabled(client, isEnabled); + promise + .then(_ => logDebug(`setting persistent cache index auto creation ` + + `isEnabled=${isEnabled} succeeded`)) + .catch(error => logWarn(`setting persistent cache index auto creation ` + + `isEnabled=${isEnabled} failed`, error)); +} +/** + * Maps `Firestore` instances to their corresponding + * `PersistentCacheIndexManager` instances. + * + * Use a `WeakMap` so that the mapping will be automatically dropped when the + * `Firestore` instance is garbage collected. This emulates a private member + * as described in https://goo.gle/454yvug. + */ +const persistentCacheIndexManagerByFirestore = new WeakMap(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @internal + * @private + * + * This function is for internal use only. + * + * Returns the `QueryTarget` representation of the given query. Returns `null` + * if the Firestore client associated with the given query has not been + * initialized or has been terminated. + * + * @param query - The Query to convert to proto representation. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function _internalQueryToProtoQueryTarget(query) { + const firestore = cast(query.firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + const serializer = client._onlineComponents?.datastore.serializer; + if (serializer === undefined) { + return null; + } + return toQueryTarget(serializer, queryToTarget(query._query)).queryTarget; +} +/** + * @internal + * @private + * + * This function is for internal use only. + * + * Returns `RunAggregationQueryRequest` which contains the proto representation + * of the given aggregation query request. Returns null if the Firestore client + * associated with the given query has not been initialized or has been + * terminated. + * + * @param query - The Query to convert to proto representation. + * @param aggregateSpec - The set of aggregations and their aliases. + */ +function _internalAggregationQueryToProtoRunAggregationQueryRequest(query, aggregateSpec) { + const aggregates = mapToArray(aggregateSpec, (aggregate, alias) => { + return new AggregateImpl(alias, aggregate.aggregateType, aggregate._internalFieldPath); + }); + const firestore = cast(query.firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + const serializer = client._onlineComponents?.datastore.serializer; + if (serializer === undefined) { + return null; + } + return toRunAggregationQueryRequest(serializer, queryToAggregateTarget(query._query), aggregates, + /* skipAliasing= */ true).request; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Testing hooks for use by Firestore's integration test suite to reach into the + * SDK internals to validate logic and behavior that is not visible from the + * public API surface. + * + * @internal + */ +class TestingHooks { + constructor() { + throw new Error('instances of this class should not be created'); + } + /** + * Registers a callback to be notified when an existence filter mismatch + * occurs in the Watch listen stream. + * + * The relative order in which callbacks are notified is unspecified; do not + * rely on any particular ordering. If a given callback is registered multiple + * times then it will be notified multiple times, once per registration. + * + * @param callback the callback to invoke upon existence filter mismatch. + * + * @return a function that, when called, unregisters the given callback; only + * the first invocation of the returned function does anything; all subsequent + * invocations do nothing. + */ + static onExistenceFilterMismatch(callback) { + return TestingHooksSpiImpl.instance.onExistenceFilterMismatch(callback); + } +} +/** + * The implementation of `TestingHooksSpi`. + */ +class TestingHooksSpiImpl { + constructor() { + this.existenceFilterMismatchCallbacksById = new Map(); + } + static get instance() { + if (!testingHooksSpiImplInstance) { + testingHooksSpiImplInstance = new TestingHooksSpiImpl(); + setTestingHooksSpi(testingHooksSpiImplInstance); + } + return testingHooksSpiImplInstance; + } + notifyOnExistenceFilterMismatch(info) { + this.existenceFilterMismatchCallbacksById.forEach(callback => callback(info)); + } + onExistenceFilterMismatch(callback) { + const id = Symbol(); + const callbacks = this.existenceFilterMismatchCallbacksById; + callbacks.set(id, callback); + return () => callbacks.delete(id); + } +} +let testingHooksSpiImplInstance = null; + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +registerFirestore('node'); + +exports.AbstractUserDataWriter = AbstractUserDataWriter; +exports.AggregateField = AggregateField; +exports.AggregateQuerySnapshot = AggregateQuerySnapshot; +exports.Bytes = Bytes; +exports.CACHE_SIZE_UNLIMITED = CACHE_SIZE_UNLIMITED; +exports.CollectionReference = CollectionReference; +exports.DocumentReference = DocumentReference; +exports.DocumentSnapshot = DocumentSnapshot; +exports.FieldPath = FieldPath; +exports.FieldValue = FieldValue; +exports.Firestore = Firestore; +exports.FirestoreError = FirestoreError; +exports.GeoPoint = GeoPoint; +exports.LoadBundleTask = LoadBundleTask; +exports.PersistentCacheIndexManager = PersistentCacheIndexManager; +exports.Query = Query; +exports.QueryCompositeFilterConstraint = QueryCompositeFilterConstraint; +exports.QueryConstraint = QueryConstraint; +exports.QueryDocumentSnapshot = QueryDocumentSnapshot; +exports.QueryEndAtConstraint = QueryEndAtConstraint; +exports.QueryFieldFilterConstraint = QueryFieldFilterConstraint; +exports.QueryLimitConstraint = QueryLimitConstraint; +exports.QueryOrderByConstraint = QueryOrderByConstraint; +exports.QuerySnapshot = QuerySnapshot; +exports.QueryStartAtConstraint = QueryStartAtConstraint; +exports.SnapshotMetadata = SnapshotMetadata; +exports.Timestamp = Timestamp; +exports.Transaction = Transaction; +exports.VectorValue = VectorValue; +exports.WriteBatch = WriteBatch; +exports._AutoId = AutoId; +exports._ByteString = ByteString; +exports._DatabaseId = DatabaseId; +exports._DocumentKey = DocumentKey; +exports._EmptyAppCheckTokenProvider = EmptyAppCheckTokenProvider; +exports._EmptyAuthCredentialsProvider = EmptyAuthCredentialsProvider; +exports._FieldPath = FieldPath$1; +exports._TestingHooks = TestingHooks; +exports._cast = cast; +exports._debugAssert = debugAssert; +exports._internalAggregationQueryToProtoRunAggregationQueryRequest = _internalAggregationQueryToProtoRunAggregationQueryRequest; +exports._internalQueryToProtoQueryTarget = _internalQueryToProtoQueryTarget; +exports._isBase64Available = isBase64Available; +exports._logWarn = logWarn; +exports._validateIsNotUsedTogether = validateIsNotUsedTogether; +exports.addDoc = addDoc; +exports.aggregateFieldEqual = aggregateFieldEqual; +exports.aggregateQuerySnapshotEqual = aggregateQuerySnapshotEqual; +exports.and = and; +exports.arrayRemove = arrayRemove; +exports.arrayUnion = arrayUnion; +exports.average = average; +exports.clearIndexedDbPersistence = clearIndexedDbPersistence; +exports.collection = collection; +exports.collectionGroup = collectionGroup; +exports.connectFirestoreEmulator = connectFirestoreEmulator; +exports.count = count; +exports.deleteAllPersistentCacheIndexes = deleteAllPersistentCacheIndexes; +exports.deleteDoc = deleteDoc; +exports.deleteField = deleteField; +exports.disableNetwork = disableNetwork; +exports.disablePersistentCacheIndexAutoCreation = disablePersistentCacheIndexAutoCreation; +exports.doc = doc; +exports.documentId = documentId; +exports.documentSnapshotFromJSON = documentSnapshotFromJSON; +exports.enableIndexedDbPersistence = enableIndexedDbPersistence; +exports.enableMultiTabIndexedDbPersistence = enableMultiTabIndexedDbPersistence; +exports.enableNetwork = enableNetwork; +exports.enablePersistentCacheIndexAutoCreation = enablePersistentCacheIndexAutoCreation; +exports.endAt = endAt; +exports.endBefore = endBefore; +exports.ensureFirestoreConfigured = ensureFirestoreConfigured; +exports.executeWrite = executeWrite; +exports.getAggregateFromServer = getAggregateFromServer; +exports.getCountFromServer = getCountFromServer; +exports.getDoc = getDoc; +exports.getDocFromCache = getDocFromCache; +exports.getDocFromServer = getDocFromServer; +exports.getDocs = getDocs; +exports.getDocsFromCache = getDocsFromCache; +exports.getDocsFromServer = getDocsFromServer; +exports.getFirestore = getFirestore; +exports.getPersistentCacheIndexManager = getPersistentCacheIndexManager; +exports.increment = increment; +exports.initializeFirestore = initializeFirestore; +exports.limit = limit; +exports.limitToLast = limitToLast; +exports.loadBundle = loadBundle; +exports.memoryEagerGarbageCollector = memoryEagerGarbageCollector; +exports.memoryLocalCache = memoryLocalCache; +exports.memoryLruGarbageCollector = memoryLruGarbageCollector; +exports.namedQuery = namedQuery; +exports.onSnapshot = onSnapshot; +exports.onSnapshotResume = onSnapshotResume; +exports.onSnapshotsInSync = onSnapshotsInSync; +exports.or = or; +exports.orderBy = orderBy; +exports.persistentLocalCache = persistentLocalCache; +exports.persistentMultipleTabManager = persistentMultipleTabManager; +exports.persistentSingleTabManager = persistentSingleTabManager; +exports.query = query; +exports.queryEqual = queryEqual; +exports.querySnapshotFromJSON = querySnapshotFromJSON; +exports.refEqual = refEqual; +exports.runTransaction = runTransaction; +exports.serverTimestamp = serverTimestamp; +exports.setDoc = setDoc; +exports.setIndexConfiguration = setIndexConfiguration; +exports.setLogLevel = setLogLevel; +exports.snapshotEqual = snapshotEqual; +exports.startAfter = startAfter; +exports.startAt = startAt; +exports.sum = sum; +exports.terminate = terminate; +exports.updateDoc = updateDoc; +exports.vector = vector; +exports.waitForPendingWrites = waitForPendingWrites; +exports.where = where; +exports.writeBatch = writeBatch; +//# sourceMappingURL=index.node.cjs.js.map diff --git a/frontend-old/node_modules/@firebase/firestore/dist/index.node.cjs.js.map b/frontend-old/node_modules/@firebase/firestore/dist/index.node.cjs.js.map new file mode 100644 index 0000000..e33bd8a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/index.node.cjs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.node.cjs.js","sources":["../src/auth/user.ts","../src/core/version.ts","../src/platform/node/format_json.ts","../src/util/log.ts","../src/util/assert.ts","../src/util/error.ts","../src/util/promise.ts","../src/api/credentials.ts","../src/platform/node/random_bytes.ts","../src/util/misc.ts","../src/model/path.ts","../src/model/document_key.ts","../src/util/input_validation.ts","../src/util/json_validation.ts","../src/lite-api/timestamp.ts","../src/core/snapshot_version.ts","../src/model/field_index.ts","../src/local/persistence_transaction.ts","../src/local/local_store.ts","../src/local/persistence_promise.ts","../src/local/simple_db.ts","../src/local/index_backfiller.ts","../src/core/listen_sequence.ts","../src/local/encoded_resource_path.ts","../src/local/indexeddb_schema_legacy.ts","../src/local/indexeddb_sentinels.ts","../src/local/indexeddb_transaction.ts","../src/util/obj.ts","../src/util/sorted_map.ts","../src/util/sorted_set.ts","../src/model/field_mask.ts","../src/platform/node/base64.ts","../src/util/byte_string.ts","../src/model/normalize.ts","../src/model/server_timestamps.ts","../src/core/database_info.ts","../src/util/types.ts","../src/model/values.ts","../src/model/object_value.ts","../src/model/document.ts","../src/core/bound.ts","../src/core/order_by.ts","../src/core/filter.ts","../src/core/target.ts","../src/core/query.ts","../src/util/obj_map.ts","../src/model/collections.ts","../src/remote/number_serializer.ts","../src/model/transform_operation.ts","../src/model/mutation.ts","../src/model/mutation_batch.ts","../src/model/overlay.ts","../src/remote/existence_filter.ts","../src/remote/rpc_error.ts","../src/util/base64_decode_error.ts","../src/util/testing_hooks_spi.ts","../src/platform/node/text_serializer.ts","../src/remote/bloom_filter.ts","../src/remote/remote_event.ts","../src/remote/watch_change.ts","../src/remote/serializer.ts","../src/local/target_data.ts","../src/local/local_serializer.ts","../src/local/indexeddb_bundle_cache.ts","../src/local/indexeddb_document_overlay_cache.ts","../src/local/indexeddb_globals_cache.ts","../src/index/firestore_index_value_writer.ts","../src/index/ordered_code_writer.ts","../src/index/index_byte_encoder.ts","../src/index/index_entry.ts","../src/model/target_index_matcher.ts","../src/util/logic_utils.ts","../src/local/memory_index_manager.ts","../src/local/indexeddb_index_manager.ts","../src/local/indexeddb_mutation_batch_impl.ts","../src/local/indexeddb_mutation_queue.ts","../src/core/target_id_generator.ts","../src/local/indexeddb_target_cache.ts","../src/local/lru_garbage_collector.ts","../src/local/lru_garbage_collector_impl.ts","../src/local/indexeddb_lru_delegate_impl.ts","../src/local/remote_document_change_buffer.ts","../src/local/indexeddb_remote_document_cache.ts","../src/local/indexeddb_schema.ts","../src/local/overlayed_document.ts","../src/local/local_documents_view.ts","../src/local/memory_bundle_cache.ts","../src/local/memory_document_overlay_cache.ts","../src/local/memory_globals_cache.ts","../src/local/reference_set.ts","../src/local/memory_mutation_queue.ts","../src/local/memory_remote_document_cache.ts","../src/local/memory_target_cache.ts","../src/local/memory_persistence.ts","../src/local/indexeddb_schema_converter.ts","../src/local/indexeddb_persistence.ts","../src/util/array.ts","../src/local/local_store_impl.ts","../src/local/query_context.ts","../src/local/query_engine.ts","../src/local/shared_client_state_schema.ts","../src/local/shared_client_state.ts","../src/remote/connectivity_monitor_noop.ts","../src/remote/stream_bridge.ts","../src/util/debug_uid.ts","../src/util/node_api.ts","../src/platform/node/grpc_connection.ts","../src/platform/node/load_protos.ts","../src/platform/node/connection.ts","../src/platform/node/dom.ts","../src/platform/node/serializer.ts","../src/remote/backoff.ts","../src/remote/persistent_stream.ts","../src/remote/datastore.ts","../src/remote/online_state_tracker.ts","../src/remote/remote_store.ts","../src/util/async_queue.ts","../src/model/document_set.ts","../src/core/view_snapshot.ts","../src/core/event_manager.ts","../src/local/local_view_changes.ts","../src/core/bundle_impl.ts","../src/core/view.ts","../src/core/sync_engine_impl.ts","../src/core/component_provider.ts","../src/util/byte_stream.ts","../src/platform/node/byte_stream_reader.ts","../src/util/async_observer.ts","../src/util/bundle_reader.ts","../src/util/bundle_reader_impl.ts","../src/util/bundle_reader_sync_impl.ts","../src/core/transaction.ts","../src/core/transaction_runner.ts","../src/core/firestore_client.ts","../src/api/long_polling_options.ts","../src/lite-api/components.ts","../src/lite-api/settings.ts","../src/lite-api/database.ts","../src/lite-api/reference.ts","../src/util/async_queue_impl.ts","../src/api/bundle.ts","../src/api/database.ts","../src/register.ts","../src/core/aggregate.ts","../src/lite-api/aggregate_types.ts","../src/lite-api/bytes.ts","../src/lite-api/field_path.ts","../src/lite-api/field_value.ts","../src/lite-api/geo_point.ts","../src/lite-api/vector_value.ts","../src/lite-api/user_data_reader.ts","../src/lite-api/snapshot.ts","../src/lite-api/query.ts","../src/lite-api/user_data_writer.ts","../src/lite-api/reference_impl.ts","../src/lite-api/aggregate.ts","../src/api/observer.ts","../test/unit/util/bundle_data.ts","../src/util/bundle_builder_impl.ts","../src/platform/node/snapshot_to_json.ts","../src/api/snapshot.ts","../src/api/reference_impl.ts","../src/api/aggregate.ts","../src/api/cache_config.ts","../src/core/transaction_options.ts","../src/lite-api/write_batch.ts","../src/lite-api/transaction.ts","../src/api/transaction.ts","../src/lite-api/field_value_impl.ts","../src/api/write_batch.ts","../src/api/index_configuration.ts","../src/api/persistent_cache_index_manager.ts","../src/remote/internal_serializer.ts","../src/util/testing_hooks.ts","../src/index.node.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Simple wrapper around a nullable UID. Mostly exists to make code more\n * readable.\n */\nexport class User {\n /** A user with a null UID. */\n static readonly UNAUTHENTICATED = new User(null);\n\n // TODO(mikelehen): Look into getting a proper uid-equivalent for\n // non-FirebaseAuth providers.\n static readonly GOOGLE_CREDENTIALS = new User('google-credentials-uid');\n static readonly FIRST_PARTY = new User('first-party-uid');\n static readonly MOCK_USER = new User('mock-user');\n\n constructor(readonly uid: string | null) {}\n\n isAuthenticated(): boolean {\n return this.uid != null;\n }\n\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */\n toKey(): string {\n if (this.isAuthenticated()) {\n return 'uid:' + this.uid;\n } else {\n return 'anonymous-user';\n }\n }\n\n isEqual(otherUser: User): boolean {\n return otherUser.uid === this.uid;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The semver (www.semver.org) version of the SDK. */\nimport { version } from '../../../firebase/package.json';\nexport let SDK_VERSION = version;\nexport function setSDKVersion(version: string): void {\n SDK_VERSION = version;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { inspect } from 'util';\n\n/** Formats an object as a JSON string, suitable for logging. */\nexport function formatJSON(value: unknown): string {\n // util.inspect() results in much more readable output than JSON.stringify()\n return inspect(value, { depth: 100 });\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel, LogLevelString } from '@firebase/logger';\n\nimport { SDK_VERSION } from '../core/version';\nimport { formatJSON } from '../platform/format_json';\n\nexport { LogLevel, LogLevelString };\n\nconst logClient = new Logger('@firebase/firestore');\n\n// Helper methods are needed because variables can't be exported as read/write\nexport function getLogLevel(): LogLevel {\n return logClient.logLevel;\n}\n\n/**\n * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).\n *\n * @param logLevel - The verbosity you set for activity and error logging. Can\n * be any of the following values:\n *\n *

    \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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 *\n * @param code generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(\n code: number,\n message: string,\n context?: Record\n): never;\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 *\n * @param id generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(id: number, context?: Record): never;\n\nexport function fail(\n id: number,\n messageOrContext?: string | Record,\n context?: Record\n): never {\n let message = 'Unexpected state';\n if (typeof messageOrContext === 'string') {\n message = messageOrContext;\n } else {\n context = messageOrContext;\n }\n _fail(id, message, context);\n}\n\nfunction _fail(\n id: number,\n failure: string,\n context?: Record\n): never {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n let message = `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ${failure} (ID: ${id.toString(\n 16\n )})`;\n if (context !== undefined) {\n try {\n const stringContext = JSON.stringify(context);\n message += ' CONTEXT: ' + stringContext;\n } catch (e) {\n message += ' CONTEXT: ' + context;\n }\n }\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 *\n * @param id generate a new unique value with `yarn assertion-idgenerate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n assertion: boolean,\n id: number,\n message: string,\n context?: Record\n): asserts assertion;\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 *\n * @param id generate a new unique value with `yarn assertion-id:generate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n assertion: boolean,\n id: number,\n context?: Record\n): asserts assertion;\n\nexport function hardAssert(\n assertion: boolean,\n id: number,\n messageOrContext?: string | Record,\n context?: Record\n): asserts assertion {\n let message = 'Unexpected state';\n if (typeof messageOrContext === 'string') {\n message = messageOrContext;\n } else {\n context = messageOrContext;\n }\n\n if (!assertion) {\n _fail(id, message, context);\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(0xdeb6, 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 { FirebaseApp, _isFirebaseServerApp } from '@firebase/app';\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 0xa539,\n 'Invalid tokenData returned from getToken()',\n { 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 0xa540,\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 0x7c5d,\n 'Invalid tokenData returned from getToken()',\n { 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 0x0807,\n 'Received invalid UID',\n { 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 private serverAppAppCheckToken: string | null = null;\n\n constructor(\n app: FirebaseApp,\n private appCheckProvider: Provider\n ) {\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n }\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n hardAssert(\n this.tokenListener === undefined,\n 0x0db8,\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 if (this.serverAppAppCheckToken) {\n return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n }\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 0xae0e,\n 'Invalid tokenResult returned from getToken()',\n { 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 private serverAppAppCheckToken: string | null = null;\n\n constructor(\n app: FirebaseApp,\n private appCheckProvider: Provider\n ) {\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n appCheckProvider.onInit(appCheck => {\n this.appCheck = appCheck;\n });\n }\n\n getToken(): Promise {\n if (this.serverAppAppCheckToken) {\n return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n }\n\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 0x0d8e,\n 'Invalid tokenResult returned from getToken()',\n { 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 { randomBytes as generateRandomBytes } from 'crypto';\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 return generateRandomBytes(nBytes);\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\n/** Compare strings in UTF-8 encoded byte order */\nexport function compareUtf8Strings(left: string, right: string): number {\n // Find the first differing character (a.k.a. \"UTF-16 code unit\") in the two strings and,\n // if found, use that character to determine the relative ordering of the two strings as a\n // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by\n // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8\n // and UTF-16 happen to represent Unicode code points.\n //\n // After finding the first pair of differing characters, there are two cases:\n //\n // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or\n // both are surrogates from a surrogate pair (that collectively represent code points greater\n // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the\n // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is\n // sufficient.\n //\n // Case 2: One character is a surrogate and the other is not. In this case the surrogate-\n // containing string is always ordered after the non-surrogate. This is because surrogates are\n // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations\n // and are lexicographically greater than the 1, 2, or 3-byte representations of code points\n // less than or equal to 0xFFFF.\n //\n // An example of why Case 2 is required is comparing the following two Unicode code points:\n //\n // |-----------------------|------------|---------------------|-----------------|\n // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding |\n // |-----------------------|------------|---------------------|-----------------|\n // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD |\n // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 |\n // |-----------------------|------------|---------------------|-----------------|\n //\n // A lexicographical comparison of the UTF-8 encodings of these code points would order\n // \"Replacement Character\" _before_ \"Grinning Face\" because 0xEF is less than 0xF0. However, a\n // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously\n // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out,\n // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate\n // pair with those that do not.\n const length = Math.min(left.length, right.length);\n for (let i = 0; i < length; i++) {\n const leftChar = left.charAt(i);\n const rightChar = right.charAt(i);\n if (leftChar !== rightChar) {\n return isSurrogate(leftChar) === isSurrogate(rightChar)\n ? primitiveComparator(leftChar, rightChar)\n : isSurrogate(leftChar)\n ? 1\n : -1;\n }\n }\n\n // Use the lengths of the strings to determine the overall comparison result since either the\n // strings were equal or one is a prefix of the other.\n return primitiveComparator(left.length, right.length);\n}\n\nconst MIN_SURROGATE = 0xd800;\nconst MAX_SURROGATE = 0xdfff;\n\nexport function isSurrogate(s: string): boolean {\n debugAssert(s.length === 1, `s.length == ${s.length}, but expected 1`);\n const c = s.charCodeAt(0);\n return c >= MIN_SURROGATE && c <= MAX_SURROGATE;\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 { Integer } from '@firebase/webchannel-wrapper/bloom-blob';\n\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { compareUtf8Strings, primitiveComparator } from '../util/misc';\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(0x027d, 'offset out of range', {\n offset,\n range: segments.length\n });\n }\n\n if (length === undefined) {\n length = segments.length - offset;\n } else if (length > segments.length - offset) {\n fail(0x06d2, 'length out of range', {\n length,\n range: segments.length - offset\n });\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 /**\n * Compare 2 paths segment by segment, prioritizing numeric IDs\n * (e.g., \"__id123__\") in numeric ascending order, followed by string\n * segments in lexicographical order.\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 comparison = BasePath.compareSegments(p1.get(i), p2.get(i));\n if (comparison !== 0) {\n return comparison;\n }\n }\n return primitiveComparator(p1.length, p2.length);\n }\n\n private static compareSegments(lhs: string, rhs: string): number {\n const isLhsNumeric = BasePath.isNumericId(lhs);\n const isRhsNumeric = BasePath.isNumericId(rhs);\n\n if (isLhsNumeric && !isRhsNumeric) {\n // Only lhs is numeric\n return -1;\n } else if (!isLhsNumeric && isRhsNumeric) {\n // Only rhs is numeric\n return 1;\n } else if (isLhsNumeric && isRhsNumeric) {\n // both numeric\n return BasePath.extractNumericId(lhs).compare(\n BasePath.extractNumericId(rhs)\n );\n } else {\n // both non-numeric\n return compareUtf8Strings(lhs, rhs);\n }\n }\n\n // Checks if a segment is a numeric ID (starts with \"__id\" and ends with \"__\").\n private static isNumericId(segment: string): boolean {\n return segment.startsWith('__id') && segment.endsWith('__');\n }\n\n private static extractNumericId(segment: string): Integer {\n return Integer.fromString(segment.substring(4, segment.length - 2));\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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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(0x3029, 'Unknown wrong type', { 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 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isPlainObject } from '../util/input_validation';\n\nimport { Code, FirestoreError } from './error';\n\n/**\n * A list of data types Firestore objects may serialize in their toJSON implemenetations.\n * @private\n * @internal\n */\nexport type JsonTypeDesc =\n | 'object'\n | 'string'\n | 'number'\n | 'boolean'\n | 'null'\n | 'undefined';\n\n/**\n * An association of JsonTypeDesc values to their native types.\n * @private\n * @internal\n */\nexport type TSType = T extends 'object'\n ? object\n : T extends 'string'\n ? string\n : T extends 'number'\n ? number\n : T extends 'boolean'\n ? boolean\n : T extends 'null'\n ? null\n : T extends 'undefined'\n ? undefined\n : never;\n\n/**\n * The representation of a JSON object property name and its type value.\n * @private\n * @internal\n */\nexport interface Property {\n value?: TSType;\n typeString: JsonTypeDesc;\n}\n\n/**\n * A type Firestore data types may use to define the fields used in their JSON serialization.\n * @private\n * @internal\n */\nexport interface JsonSchema {\n [key: string]: Property;\n}\n\n/**\n * Associates the JSON property type to the native type and sets them to be Required.\n * @private\n * @internal\n */\nexport type Json = {\n [K in keyof T]: Required['value'];\n};\n\n/**\n * Helper function to define a JSON schema {@link Property}.\n * @private\n * @internal\n */\nexport function property(\n typeString: T,\n optionalValue?: TSType\n): Property {\n const result: Property = {\n typeString\n };\n if (optionalValue) {\n result.value = optionalValue;\n }\n return result;\n}\n\n/**\n * Validates the JSON object based on the provided schema, and narrows the type to the provided\n * JSON schema.\n * @private\n * @internal\n *\n * @param json A JSON object to validate.\n * @param scheme a {@link JsonSchema} that defines the properties to validate.\n * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise.\n */\nexport function validateJSON(\n json: object,\n schema: S\n): json is Json {\n if (!isPlainObject(json)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'JSON must be an object');\n }\n let error: string | undefined = undefined;\n for (const key in schema) {\n if (schema[key]) {\n const typeString = schema[key].typeString;\n const value: { value: unknown } | undefined =\n 'value' in schema[key] ? { value: schema[key].value } : undefined;\n if (!(key in json)) {\n error = `JSON missing required field: '${key}'`;\n break;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const fieldValue = (json as any)[key];\n if (typeString && typeof fieldValue !== typeString) {\n error = `JSON field '${key}' must be a ${typeString}.`;\n break;\n } else if (value !== undefined && fieldValue !== value.value) {\n error = `Expected '${key}' field to equal '${value.value}'`;\n break;\n }\n }\n }\n if (error) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, error);\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 { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\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 static _jsonSchemaVersion: string = 'firestore/timestamp/1.0';\n static _jsonSchema = {\n type: property('string', Timestamp._jsonSchemaVersion),\n seconds: property('number'),\n nanoseconds: property('number')\n };\n\n /**\n * Returns a JSON-serializable representation of this `Timestamp`.\n */\n toJSON(): { seconds: number; nanoseconds: number; type: string } {\n return {\n type: Timestamp._jsonSchemaVersion,\n seconds: this.seconds,\n nanoseconds: this.nanoseconds\n };\n }\n\n /**\n * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}.\n */\n static fromJSON(json: object): Timestamp {\n if (validateJSON(json, Timestamp._jsonSchema)) {\n return new Timestamp(json.seconds, json.nanoseconds);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Timestamp from JSON.'\n );\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 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(0xe830, '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 { getGlobal, 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 `indexedDB` are guarded by SimpleDb.isAvailable() and getGlobal()\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 lastClosedDbVersion: number | null = null;\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 const globals = getGlobal();\n return wrapRequest(\n globals.indexedDB.deleteDatabase(name)\n ).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\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 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { FirestoreError } from '../api';\nimport { DocumentMap } from '../model/collections';\nimport {\n IndexOffset,\n indexOffsetComparator,\n newIndexOffsetFromDocument\n} from '../model/field_index';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { logDebug } from '../util/log';\n\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from './local_store';\nimport { LocalWriteResult } from './local_store_impl';\nimport { Persistence, Scheduler } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { isIndexedDbTransactionError } from './simple_db';\n\nconst LOG_TAG = 'IndexBackfiller';\n\n/** How long we wait to try running index backfill after SDK initialization. */\nconst INITIAL_BACKFILL_DELAY_MS = 15 * 1000;\n\n/** Minimum amount of time between backfill checks, after the first one. */\nconst REGULAR_BACKFILL_DELAY_MS = 60 * 1000;\n\n/** The maximum number of documents to process each time backfill() is called. */\nconst MAX_DOCUMENTS_TO_PROCESS = 50;\n\n/** This class is responsible for the scheduling of Index Backfiller. */\nexport class IndexBackfillerScheduler implements Scheduler {\n private task: DelayedOperation | null;\n\n constructor(\n private readonly asyncQueue: AsyncQueue,\n private readonly backfiller: IndexBackfiller\n ) {\n this.task = null;\n }\n\n start(): void {\n debugAssert(\n this.task === null,\n 'Cannot start an already started IndexBackfillerScheduler'\n );\n this.schedule(INITIAL_BACKFILL_DELAY_MS);\n }\n\n stop(): void {\n if (this.task) {\n this.task.cancel();\n this.task = null;\n }\n }\n\n get started(): boolean {\n return this.task !== null;\n }\n\n private schedule(delay: number): void {\n debugAssert(\n this.task === null,\n 'Cannot schedule IndexBackfiller while a task is pending'\n );\n logDebug(LOG_TAG, `Scheduled in ${delay}ms`);\n this.task = this.asyncQueue.enqueueAfterDelay(\n TimerId.IndexBackfill,\n delay,\n async () => {\n this.task = null;\n try {\n const documentsProcessed = await this.backfiller.backfill();\n logDebug(LOG_TAG, `Documents written: ${documentsProcessed}`);\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(\n LOG_TAG,\n 'Ignoring IndexedDB error during index backfill: ',\n e\n );\n } else {\n await ignoreIfPrimaryLeaseLoss(e as FirestoreError);\n }\n }\n await this.schedule(REGULAR_BACKFILL_DELAY_MS);\n }\n );\n }\n}\n\n/** Implements the steps for backfilling indexes. */\nexport class IndexBackfiller {\n constructor(\n /**\n * LocalStore provides access to IndexManager and LocalDocumentView.\n * These properties will update when the user changes. Consequently,\n * making a local copy of IndexManager and LocalDocumentView will require\n * updates over time. The simpler solution is to rely on LocalStore to have\n * an up-to-date references to IndexManager and LocalDocumentStore.\n */\n private readonly localStore: LocalStore,\n private readonly persistence: Persistence\n ) {}\n\n async backfill(\n maxDocumentsToProcess: number = MAX_DOCUMENTS_TO_PROCESS\n ): Promise {\n return this.persistence.runTransaction(\n 'Backfill Indexes',\n 'readwrite-primary',\n txn => this.writeIndexEntries(txn, maxDocumentsToProcess)\n );\n }\n\n /** Writes index entries until the cap is reached. Returns the number of documents processed. */\n private writeIndexEntries(\n transaction: PersistenceTransaction,\n maxDocumentsToProcess: number\n ): PersistencePromise {\n const processedCollectionGroups = new Set();\n let documentsRemaining = maxDocumentsToProcess;\n let continueLoop = true;\n return PersistencePromise.doWhile(\n () => continueLoop === true && documentsRemaining > 0,\n () => {\n return this.localStore.indexManager\n .getNextCollectionGroupToUpdate(transaction)\n .next((collectionGroup: string | null) => {\n if (\n collectionGroup === null ||\n processedCollectionGroups.has(collectionGroup)\n ) {\n continueLoop = false;\n } else {\n logDebug(LOG_TAG, `Processing collection: ${collectionGroup}`);\n return this.writeEntriesForCollectionGroup(\n transaction,\n collectionGroup,\n documentsRemaining\n ).next(documentsProcessed => {\n documentsRemaining -= documentsProcessed;\n processedCollectionGroups.add(collectionGroup);\n });\n }\n });\n }\n ).next(() => maxDocumentsToProcess - documentsRemaining);\n }\n\n /**\n * Writes entries for the provided collection group. Returns the number of documents processed.\n */\n private writeEntriesForCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n documentsRemainingUnderCap: number\n ): PersistencePromise {\n // Use the earliest offset of all field indexes to query the local cache.\n return this.localStore.indexManager\n .getMinOffsetFromCollectionGroup(transaction, collectionGroup)\n .next(existingOffset =>\n this.localStore.localDocuments\n .getNextDocuments(\n transaction,\n collectionGroup,\n existingOffset,\n documentsRemainingUnderCap\n )\n .next(nextBatch => {\n const docs: DocumentMap = nextBatch.changes;\n return this.localStore.indexManager\n .updateIndexEntries(transaction, docs)\n .next(() => this.getNewOffset(existingOffset, nextBatch))\n .next(newOffset => {\n logDebug(LOG_TAG, `Updating offset: ${newOffset}`);\n return this.localStore.indexManager.updateCollectionGroup(\n transaction,\n collectionGroup,\n newOffset\n );\n })\n .next(() => docs.size);\n })\n );\n }\n\n /** Returns the next offset based on the provided documents. */\n private getNewOffset(\n existingOffset: IndexOffset,\n lookupResult: LocalWriteResult\n ): IndexOffset {\n let maxOffset: IndexOffset = existingOffset;\n lookupResult.changes.forEach((key, document) => {\n const newOffset: IndexOffset = newIndexOffsetFromDocument(document);\n if (indexOffsetComparator(newOffset, maxOffset) > 0) {\n maxOffset = newOffset;\n }\n });\n return new IndexOffset(\n maxOffset.readTime,\n maxOffset.documentKey,\n Math.max(lookupResult.batchId, existingOffset.largestBatchId)\n );\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequenceNumber } from './types';\n\n/**\n * `SequenceNumberSyncer` defines the methods required to keep multiple instances of a\n * `ListenSequence` in sync.\n */\nexport interface SequenceNumberSyncer {\n // Notify the syncer that a new sequence number has been used.\n writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void;\n // Setting this property allows the syncer to notify when a sequence number has been used, and\n // and lets the ListenSequence adjust its internal previous value accordingly.\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null;\n}\n\n/**\n * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to\n * exceed. All subsequent calls to next will return increasing values. If provided with a\n * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as\n * well as write out sequence numbers that it produces via `next()`.\n */\nexport class ListenSequence {\n static readonly INVALID: ListenSequenceNumber = -1;\n\n private writeNewSequenceNumber?: (\n newSequenceNumber: ListenSequenceNumber\n ) => void;\n\n constructor(\n private previousValue: ListenSequenceNumber,\n sequenceNumberSyncer?: SequenceNumberSyncer\n ) {\n if (sequenceNumberSyncer) {\n sequenceNumberSyncer.sequenceNumberHandler = sequenceNumber =>\n this.setPreviousValue(sequenceNumber);\n this.writeNewSequenceNumber = sequenceNumber =>\n sequenceNumberSyncer.writeSequenceNumber(sequenceNumber);\n }\n }\n\n private setPreviousValue(\n externalPreviousValue: ListenSequenceNumber\n ): ListenSequenceNumber {\n this.previousValue = Math.max(externalPreviousValue, this.previousValue);\n return this.previousValue;\n }\n\n next(): ListenSequenceNumber {\n const nextValue = ++this.previousValue;\n if (this.writeNewSequenceNumber) {\n this.writeNewSequenceNumber(nextValue);\n }\n return nextValue;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ResourcePath } from '../model/path';\nimport { fail, hardAssert } from '../util/assert';\n\n/**\n * Helpers for dealing with resource paths stored in IndexedDB.\n *\n * Resource paths in their canonical string form do not sort as the server\n * sorts them. Specifically the server splits paths into segments first and then\n * sorts, putting end-of-segment before any character. In a UTF-8 string\n * encoding the slash ('/') that denotes the end-of-segment naturally comes\n * after other characters so the intent here is to encode the path delimiters in\n * such a way that the resulting strings sort naturally.\n *\n * Resource paths are also used for prefix scans so it's important to\n * distinguish whole segments from any longer segments of which they might be a\n * prefix. For example, it's important to make it possible to scan documents in\n * a collection \"foo\" without encountering documents in a collection \"foobar\".\n *\n * Separate from the concerns about resource path ordering and separation,\n * On Android, SQLite imposes additional restrictions since it does not handle\n * keys with embedded NUL bytes particularly well. Rather than change the\n * implementation we keep the encoding identical to keep the ports similar.\n *\n * Taken together this means resource paths when encoded for storage in\n * IndexedDB have the following characteristics:\n *\n * * Segment separators (\"/\") sort before everything else.\n * * All paths have a trailing separator.\n * * NUL bytes do not exist in the output, since IndexedDB doesn't treat them\n * well.\n *\n * Therefore resource paths are encoded into string form using the following\n * rules:\n *\n * * '\\x01' is used as an escape character.\n * * Path separators are encoded as \"\\x01\\x01\"\n * * NUL bytes are encoded as \"\\x01\\x10\"\n * * '\\x01' is encoded as \"\\x01\\x11\"\n *\n * This encoding leaves some room between path separators and the NUL byte\n * just in case we decide to support integer document ids after all.\n *\n * Note that characters treated specially by the backend ('.', '/', and '~')\n * are not treated specially here. This class assumes that any unescaping of\n * resource path strings into actual ResourcePath objects will handle these\n * characters there.\n */\nexport type EncodedResourcePath = string;\n\nconst escapeChar = '\\u0001';\nconst encodedSeparatorChar = '\\u0001';\nconst encodedNul = '\\u0010';\nconst encodedEscape = '\\u0011';\n\n/**\n * Encodes a resource path into a IndexedDb-compatible string form.\n */\nexport function encodeResourcePath(path: ResourcePath): EncodedResourcePath {\n let result = '';\n for (let i = 0; i < path.length; i++) {\n if (result.length > 0) {\n result = encodeSeparator(result);\n }\n result = encodeSegment(path.get(i), result);\n }\n return encodeSeparator(result);\n}\n\n/** Encodes a single segment of a resource path into the given result */\nfunction encodeSegment(segment: string, resultBuf: string): string {\n let result = resultBuf;\n const length = segment.length;\n for (let i = 0; i < length; i++) {\n const c = segment.charAt(i);\n switch (c) {\n case '\\0':\n result += escapeChar + encodedNul;\n break;\n case escapeChar:\n result += escapeChar + encodedEscape;\n break;\n default:\n result += c;\n }\n }\n return result;\n}\n\n/** Encodes a path separator into the given result */\nfunction encodeSeparator(result: string): string {\n return result + escapeChar + encodedSeparatorChar;\n}\n\n/**\n * Decodes the given IndexedDb-compatible string form of a resource path into\n * a ResourcePath instance. Note that this method is not suitable for use with\n * decoding resource names from the server; those are One Platform format\n * strings.\n */\nexport function decodeResourcePath(path: EncodedResourcePath): ResourcePath {\n // Event the empty path must encode as a path of at least length 2. A path\n // with exactly 2 must be the empty path.\n const length = path.length;\n hardAssert(length >= 2, 0xfb98, 'Invalid path', { path });\n if (length === 2) {\n hardAssert(\n path.charAt(0) === escapeChar && path.charAt(1) === encodedSeparatorChar,\n 0xdb51,\n 'Non-empty path had length 2',\n { path }\n );\n return ResourcePath.emptyPath();\n }\n\n // Escape characters cannot exist past the second-to-last position in the\n // source value.\n const lastReasonableEscapeIndex = length - 2;\n\n const segments: string[] = [];\n let segmentBuilder = '';\n\n for (let start = 0; start < length; ) {\n // The last two characters of a valid encoded path must be a separator, so\n // there must be an end to this segment.\n const end = path.indexOf(escapeChar, start);\n if (end < 0 || end > lastReasonableEscapeIndex) {\n fail(0xc553, 'Invalid encoded resource path', { path });\n }\n\n const next = path.charAt(end + 1);\n switch (next) {\n case encodedSeparatorChar:\n const currentPiece = path.substring(start, end);\n let segment;\n if (segmentBuilder.length === 0) {\n // Avoid copying for the common case of a segment that excludes \\0\n // and \\001\n segment = currentPiece;\n } else {\n segmentBuilder += currentPiece;\n segment = segmentBuilder;\n segmentBuilder = '';\n }\n segments.push(segment);\n break;\n case encodedNul:\n segmentBuilder += path.substring(start, end);\n segmentBuilder += '\\0';\n break;\n case encodedEscape:\n // The escape character can be used in the output to encode itself.\n segmentBuilder += path.substring(start, end + 1);\n break;\n default:\n fail(0xeeef, 'Invalid encoded resource path', { path });\n }\n\n start = end + 2;\n }\n\n return new ResourcePath(segments);\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 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 * Representation of a byte array that is safe for\n * use in an IndexedDb key. The value is either\n * a \"sortable byte string\", which is key safe in\n * Safari/WebKit, or the value is a Uint8Array,\n * which is key safe in other browsers.\n */\nexport type KeySafeBytes = Uint8Array | string;\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 KeySafeBytes,\n KeySafeBytes,\n KeySafeBytes,\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];\nexport const V18_STORES = V17_STORES;\n\n/**\n * The list of all default IndexedDB stores used throughout the SDK. This is\n * used when creating transactions so that access across all stores is done\n * atomically.\n */\nexport const ALL_STORES = V12_STORES;\n\n/** Returns the object stores for the provided schema. */\nexport function getObjectStores(schemaVersion: number): string[] {\n if (schemaVersion === 18) {\n return V18_STORES;\n } else 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(0xeb55, 'Only schema versions >11 are supported');\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 { ListenSequenceNumber } from '../core/types';\nimport { debugCast } from '../util/assert';\n\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDb, SimpleDbStore, SimpleDbTransaction } from './simple_db';\n\nexport class IndexedDbTransaction extends PersistenceTransaction {\n constructor(\n readonly simpleDbTransaction: SimpleDbTransaction,\n readonly currentSequenceNumber: ListenSequenceNumber\n ) {\n super();\n }\n}\n\nexport function getStore(\n txn: PersistenceTransaction,\n store: string\n): SimpleDbStore {\n const indexedDbTransaction = debugCast(txn, IndexedDbTransaction);\n return SimpleDb.getStore(\n indexedDbTransaction.simpleDbTransaction,\n store\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from './assert';\n\nexport interface Dict {\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(0xaad2, 'Red node has red child', {\n key: this.key,\n value: this.value\n });\n }\n if (this.right.isRed()) {\n throw fail(0x3721, 'Right child of (`key`, `value`) is red', {\n key: this.key,\n value: this.value\n });\n }\n const blackDepth = (this.left as LLRBNode).check();\n if (blackDepth !== (this.right as LLRBNode).check()) {\n throw fail(0x6d2d, '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(0xe1a6, 'LLRBEmptyNode has no key.');\n }\n get value(): never {\n throw fail(0x3f0d, 'LLRBEmptyNode has no value.');\n }\n get color(): never {\n throw fail(0x4157, 'LLRBEmptyNode has no color.');\n }\n get left(): never {\n throw fail(0x741e, 'LLRBEmptyNode has no left child.');\n }\n get right(): never {\n throw fail(0x901e, '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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Converts a Base64 encoded string to a binary string. */\n\nexport function decodeBase64(encoded: string): string {\n // Note: We used to validate the base64 string here via a regular expression.\n // This was removed to improve the performance of indexing.\n return Buffer.from(encoded, 'base64').toString('binary');\n}\n\n/** Converts a binary string to a Base64 encoded string. */\nexport function encodeBase64(raw: string): string {\n return Buffer.from(raw, 'binary').toString('base64');\n}\n\n/** True if and only if the Base64 conversion functions are available. */\nexport function isBase64Available(): boolean {\n return true;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 { 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, 0x986a, '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, 0xb5de, 'invalid timestamp', {\n timestamp: date\n });\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 readonly isUsingEmulator: 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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 {\n arrayEquals,\n compareUtf8Strings,\n primitiveComparator\n} 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(0x6e87, 'Invalid value type', { 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(0xcbf8, 'Unexpected value type', { 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 compareUtf8Strings(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(0x5ae0, '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 = compareUtf8Strings(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(0xee4d, 'Invalid value type', { 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(0x34ae, 'Invalid value type', { 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(0x8c66, 'Invalid value type', { 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(0xf207, 'Invalid value type', { 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(\n 0xa786,\n \"Trying to compare documents on fields that don't exist\"\n );\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 other.nullValue === undefined &&\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(0xb8a2, 'Unknown FieldFilter operator', {\n operator: this.op\n });\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(0x4bef, '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 (\n other !== null &&\n other.nullValue === undefined &&\n !arrayValueContains(this.value.arrayValue!, other)\n );\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(0x4d4e, 'Unknown direction', { 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 0x7f90,\n 'server transform result count should match field transform count',\n {\n serverTransformResultCount: serverTransformResults.length,\n fieldTransformCount: fieldTransforms.length\n }\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 0xe5da,\n 'Mutations sent must equal results received',\n {\n mutationsSent: batch.mutations.length,\n resultsReceived: results.length\n }\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(0xfdaa, '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(0x3c6b, '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(0x999b, '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(0x3019, '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 * An error encountered while decoding base64 string.\n */\nexport class Base64DecodeError extends Error {\n readonly name = 'Base64DecodeError';\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\nimport { TextDecoder, TextEncoder } from 'util';\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(0x9481, '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 0x0ca9,\n '`pendingResponses` is less than 0. This indicates that the SDK received more target acks from the server than expected. The SDK should not continue to operate.',\n { pendingResponses: this.pendingResponses }\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 private pendingDocumentUpdatesByTarget = documentTargetMap();\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(0xddd6, 'Unknown target watch change state', {\n state: targetChange.state\n });\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 0x4e2d,\n 'Single document existence filter with count',\n { 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 for this\n // target. This resolves the limbo state of the document, removing it\n // from 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.ensureDocumentUpdateByTarget(key).has(targetId) &&\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.pendingDocumentUpdatesByTarget = documentTargetMap();\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.pendingDocumentUpdatesByTarget =\n this.pendingDocumentUpdatesByTarget.insert(\n document.key,\n this.ensureDocumentUpdateByTarget(document.key).add(targetId)\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 this.pendingDocumentTargetMapping =\n this.pendingDocumentTargetMapping.insert(\n key,\n this.ensureDocumentTargetMapping(key).add(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 private ensureDocumentUpdateByTarget(key: DocumentKey): SortedSet {\n let targetMapping = this.pendingDocumentUpdatesByTarget.get(key);\n\n if (!targetMapping) {\n targetMapping = new SortedSet(primitiveComparator);\n this.pendingDocumentUpdatesByTarget =\n this.pendingDocumentUpdatesByTarget.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\n/**\n * Returns a Timestamp typed object given protobuf timestamp value.\n */\nexport function 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 0xe30b,\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 0x3f41,\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, 0xc050, \"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 0x27ce,\n 'Tried to deserialize invalid key',\n { 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 0x71a3,\n 'tried to deserialize invalid key',\n { 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 0xaa33,\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 0x0f36,\n 'Tried to deserialize a missing document from a found document.'\n );\n hardAssert(\n !!result.readTime,\n 0x5995,\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(0x1c42, 'invalid batch get response', { 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(0x2d51, 'Unknown change type', { 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(0x9991, '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(0x40d7, 'Unknown mutation type', {\n mutationType: mutation.type\n });\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(0x05b7, 'unknown mutation proto', { 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(0x6b69, '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 0x3811,\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(0x51c2, 'Unknown transform', {\n transform: fieldTransform.transform\n });\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 0x40f6,\n 'Unknown server value transform proto',\n { 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(0x40c8, 'Unknown transform proto', { 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 0x07ae,\n 'DocumentsTarget contained other than 1 document',\n {\n count\n }\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 0xfe26,\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(0x713b, '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(0x7591, 'Unknown filter', { 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(0xe2fe, 'Unspecified operator');\n default:\n return fail(0xc54a, '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(0x0402, '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(0xd65d, 'Unrecognized filter type', { 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(0xef81, 'Unspecified filter');\n default:\n return fail(0xed36, '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(0xdd85, '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(0xe230, 'Unexpected Document', { document });\n }\n return remoteDoc;\n}\n\nexport function toDbTimestampKey(\n snapshotVersion: SnapshotVersion\n): DbTimestampKey {\n const timestamp = snapshotVersion.toTimestamp();\n return [timestamp.seconds, timestamp.nanoseconds];\n}\n\nexport function fromDbTimestampKey(\n dbTimestampKey: DbTimestampKey\n): SnapshotVersion {\n const timestamp = new Timestamp(dbTimestampKey[0], dbTimestampKey[1]);\n return SnapshotVersion.fromTimestamp(timestamp);\n}\n\nexport function toDbTimestamp(snapshotVersion: SnapshotVersion): DbTimestamp {\n const timestamp = snapshotVersion.toTimestamp();\n return { seconds: timestamp.seconds, nanoseconds: timestamp.nanoseconds };\n}\n\nfunction fromDbTimestamp(dbTimestamp: DbTimestamp): SnapshotVersion {\n const timestamp = new Timestamp(dbTimestamp.seconds, dbTimestamp.nanoseconds);\n return SnapshotVersion.fromTimestamp(timestamp);\n}\n\n/** Encodes a batch of mutations into a DbMutationBatch for local storage. */\nexport function toDbMutationBatch(\n localSerializer: LocalSerializer,\n userId: string,\n batch: MutationBatch\n): DbMutationBatch {\n const serializedBaseMutations = batch.baseMutations.map(m =>\n toMutation(localSerializer.remoteSerializer, m)\n );\n const serializedMutations = batch.mutations.map(m =>\n toMutation(localSerializer.remoteSerializer, m)\n );\n return {\n userId,\n batchId: batch.batchId,\n localWriteTimeMs: batch.localWriteTime.toMillis(),\n baseMutations: serializedBaseMutations,\n mutations: serializedMutations\n };\n}\n\n/** Decodes a DbMutationBatch into a MutationBatch */\nexport function fromDbMutationBatch(\n localSerializer: LocalSerializer,\n dbBatch: DbMutationBatch\n): MutationBatch {\n const baseMutations = (dbBatch.baseMutations || []).map(m =>\n fromMutation(localSerializer.remoteSerializer, m)\n );\n\n // Squash old transform mutations into existing patch or set mutations.\n // The replacement of representing `transforms` with `update_transforms`\n // on the SDK means that old `transform` mutations stored in IndexedDB need\n // to be updated to `update_transforms`.\n // TODO(b/174608374): Remove this code once we perform a schema migration.\n for (let i = 0; i < dbBatch.mutations.length - 1; ++i) {\n const currentMutation = dbBatch.mutations[i];\n const hasTransform =\n i + 1 < dbBatch.mutations.length &&\n dbBatch.mutations[i + 1].transform !== undefined;\n if (hasTransform) {\n debugAssert(\n dbBatch.mutations[i].transform === undefined &&\n dbBatch.mutations[i].update !== undefined,\n 'TransformMutation should be preceded by a patch or set mutation'\n );\n const transformMutation = dbBatch.mutations[i + 1];\n currentMutation.updateTransforms =\n transformMutation.transform!.fieldTransforms;\n dbBatch.mutations.splice(i + 1, 1);\n ++i;\n }\n }\n\n const mutations = dbBatch.mutations.map(m =>\n fromMutation(localSerializer.remoteSerializer, m)\n );\n const timestamp = Timestamp.fromMillis(dbBatch.localWriteTimeMs);\n return new MutationBatch(\n dbBatch.batchId,\n timestamp,\n baseMutations,\n mutations\n );\n}\n\n/** Decodes a DbTarget into TargetData */\nexport function fromDbTarget(dbTarget: DbTarget): TargetData {\n const version = fromDbTimestamp(dbTarget.readTime);\n const lastLimboFreeSnapshotVersion =\n dbTarget.lastLimboFreeSnapshotVersion !== undefined\n ? fromDbTimestamp(dbTarget.lastLimboFreeSnapshotVersion)\n : SnapshotVersion.min();\n\n let target: Target;\n if (isDocumentQuery(dbTarget.query)) {\n target = fromDocumentsTarget(dbTarget.query);\n } else {\n target = fromQueryTarget(dbTarget.query);\n }\n return new TargetData(\n target,\n dbTarget.targetId,\n TargetPurpose.Listen,\n dbTarget.lastListenSequenceNumber,\n version,\n lastLimboFreeSnapshotVersion,\n ByteString.fromBase64String(dbTarget.resumeToken)\n );\n}\n\n/** Encodes TargetData into a DbTarget for storage locally. */\nexport function toDbTarget(\n localSerializer: LocalSerializer,\n targetData: TargetData\n): DbTarget {\n debugAssert(\n TargetPurpose.Listen === targetData.purpose,\n 'Only queries with purpose ' +\n TargetPurpose.Listen +\n ' may be stored, got ' +\n targetData.purpose\n );\n const dbTimestamp = toDbTimestamp(targetData.snapshotVersion);\n const dbLastLimboFreeTimestamp = toDbTimestamp(\n targetData.lastLimboFreeSnapshotVersion\n );\n let queryProto: DbQuery;\n if (targetIsDocumentTarget(targetData.target)) {\n queryProto = toDocumentsTarget(\n localSerializer.remoteSerializer,\n targetData.target\n );\n } else {\n queryProto = toQueryTarget(\n localSerializer.remoteSerializer,\n targetData.target\n ).queryTarget;\n }\n\n // We can't store the resumeToken as a ByteString in IndexedDb, so we\n // convert it to a base64 string for storage.\n const resumeToken = targetData.resumeToken.toBase64();\n\n // lastListenSequenceNumber is always 0 until we do real GC.\n return {\n targetId: targetData.targetId,\n canonicalId: canonifyTarget(targetData.target),\n readTime: dbTimestamp,\n resumeToken,\n lastListenSequenceNumber: targetData.sequenceNumber,\n lastLimboFreeSnapshotVersion: dbLastLimboFreeTimestamp,\n query: queryProto\n };\n}\n\n/**\n * A helper function for figuring out what kind of query has been stored.\n */\nfunction isDocumentQuery(dbQuery: DbQuery): dbQuery is PublicDocumentsTarget {\n return (dbQuery as PublicDocumentsTarget).documents !== undefined;\n}\n\n/** Encodes a DbBundle to a BundleMetadata object. */\nexport function fromDbBundle(dbBundle: DbBundle): BundleMetadata {\n return {\n id: dbBundle.bundleId,\n createTime: fromDbTimestamp(dbBundle.createTime),\n version: dbBundle.version\n };\n}\n\n/** Encodes a BundleMetadata to a DbBundle. */\nexport function toDbBundle(metadata: ProtoBundleMetadata): DbBundle {\n return {\n bundleId: metadata.id!,\n createTime: toDbTimestamp(fromVersion(metadata.createTime!)),\n version: metadata.version!\n };\n}\n\n/** Encodes a DbNamedQuery to a NamedQuery. */\nexport function fromDbNamedQuery(dbNamedQuery: DbNamedQuery): NamedQuery {\n return {\n name: dbNamedQuery.name,\n query: fromBundledQuery(dbNamedQuery.bundledQuery),\n readTime: fromDbTimestamp(dbNamedQuery.readTime)\n };\n}\n\n/** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */\nexport function toDbNamedQuery(query: ProtoNamedQuery): DbNamedQuery {\n return {\n name: query.name!,\n readTime: toDbTimestamp(fromVersion(query.readTime!)),\n bundledQuery: query.bundledQuery!\n };\n}\n\n/**\n * Encodes a `BundledQuery` from bundle proto to a Query object.\n *\n * This reconstructs the original query used to build the bundle being loaded,\n * including features exists only in SDKs (for example: limit-to-last).\n */\nexport function fromBundledQuery(bundledQuery: ProtoBundledQuery): Query {\n const query = convertQueryTargetToQuery({\n parent: bundledQuery.parent!,\n structuredQuery: bundledQuery.structuredQuery!\n });\n if (bundledQuery.limitType === 'LAST') {\n debugAssert(\n !!query.limit,\n 'Bundled query has limitType LAST, but limit is null'\n );\n return queryWithLimit(query, query.limit, LimitType.Last);\n }\n return query;\n}\n\n/** Encodes a NamedQuery proto object to a NamedQuery model object. */\nexport function fromProtoNamedQuery(namedQuery: ProtoNamedQuery): NamedQuery {\n return {\n name: namedQuery.name!,\n query: fromBundledQuery(namedQuery.bundledQuery!),\n readTime: fromVersion(namedQuery.readTime!)\n };\n}\n\n/** Decodes a BundleMetadata proto into a BundleMetadata object. */\nexport function fromBundleMetadata(\n metadata: ProtoBundleMetadata\n): BundleMetadata {\n return {\n id: metadata.id!,\n version: metadata.version!,\n createTime: fromVersion(metadata.createTime!)\n };\n}\n\n/** Encodes a DbDocumentOverlay object to an Overlay model object. */\nexport function fromDbDocumentOverlay(\n localSerializer: LocalSerializer,\n dbDocumentOverlay: DbDocumentOverlay\n): Overlay {\n return new Overlay(\n dbDocumentOverlay.largestBatchId,\n fromMutation(\n localSerializer.remoteSerializer,\n dbDocumentOverlay.overlayMutation\n )\n );\n}\n\n/** Decodes an Overlay model object into a DbDocumentOverlay object. */\nexport function toDbDocumentOverlay(\n localSerializer: LocalSerializer,\n userId: string,\n overlay: Overlay\n): DbDocumentOverlay {\n const [_, collectionPath, documentId] = toDbDocumentOverlayKey(\n userId,\n overlay.mutation.key\n );\n return {\n userId,\n collectionPath,\n documentId,\n collectionGroup: overlay.mutation.key.getCollectionGroup(),\n largestBatchId: overlay.largestBatchId,\n overlayMutation: toMutation(\n localSerializer.remoteSerializer,\n overlay.mutation\n )\n };\n}\n\n/**\n * Returns the DbDocumentOverlayKey corresponding to the given user and\n * document key.\n */\nexport function toDbDocumentOverlayKey(\n userId: string,\n docKey: DocumentKey\n): DbDocumentOverlayKey {\n const docId = docKey.path.lastSegment();\n const collectionPath = encodeResourcePath(docKey.path.popLast());\n return [userId, collectionPath, docId];\n}\n\nexport function toDbIndexConfiguration(\n index: FieldIndex\n): DbIndexConfiguration {\n return {\n indexId: index.indexId,\n collectionGroup: index.collectionGroup,\n fields: index.fields.map(s => [s.fieldPath.canonicalString(), s.kind])\n };\n}\n\nexport function fromDbIndexConfiguration(\n index: DbIndexConfiguration,\n state: DbIndexState | null\n): FieldIndex {\n const decodedState = state\n ? new IndexState(\n state.sequenceNumber,\n new IndexOffset(\n fromDbTimestamp(state.readTime),\n new DocumentKey(decodeResourcePath(state.documentKey)),\n state.largestBatchId\n )\n )\n : IndexState.empty();\n const decodedSegments = index.fields.map(\n ([fieldPath, kind]) =>\n new IndexSegment(FieldPath.fromServerFormat(fieldPath), kind)\n );\n return new FieldIndex(\n index.indexId!,\n index.collectionGroup,\n decodedSegments,\n decodedState\n );\n}\n\nexport function toDbIndexState(\n indexId: number,\n uid: string,\n sequenceNumber: number,\n offset: IndexOffset\n): DbIndexState {\n return {\n indexId,\n uid,\n sequenceNumber,\n readTime: toDbTimestamp(offset.readTime),\n documentKey: encodeResourcePath(offset.documentKey.path),\n largestBatchId: offset.largestBatchId\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BundleMetadata, NamedQuery } from '../core/bundle';\nimport {\n BundleMetadata as ProtoBundleMetadata,\n NamedQuery as ProtoNamedQuery\n} from '../protos/firestore_bundle_proto';\n\nimport { BundleCache } from './bundle_cache';\nimport { DbBundle, DbNamedQuery } from './indexeddb_schema';\nimport {\n DbBundlesKey,\n DbBundleStore,\n DbNamedQueriesKey,\n DbNamedQueryStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n fromDbBundle,\n fromDbNamedQuery,\n toDbBundle,\n toDbNamedQuery\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\nexport class IndexedDbBundleCache implements BundleCache {\n getBundleMetadata(\n transaction: PersistenceTransaction,\n bundleId: string\n ): PersistencePromise {\n return bundlesStore(transaction)\n .get(bundleId)\n .next(bundle => {\n if (bundle) {\n return fromDbBundle(bundle);\n }\n return undefined;\n });\n }\n\n saveBundleMetadata(\n transaction: PersistenceTransaction,\n bundleMetadata: ProtoBundleMetadata\n ): PersistencePromise {\n return bundlesStore(transaction).put(toDbBundle(bundleMetadata));\n }\n\n getNamedQuery(\n transaction: PersistenceTransaction,\n queryName: string\n ): PersistencePromise {\n return namedQueriesStore(transaction)\n .get(queryName)\n .next(query => {\n if (query) {\n return fromDbNamedQuery(query);\n }\n return undefined;\n });\n }\n\n saveNamedQuery(\n transaction: PersistenceTransaction,\n query: ProtoNamedQuery\n ): PersistencePromise {\n return namedQueriesStore(transaction).put(toDbNamedQuery(query));\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the bundles object store.\n */\nfunction bundlesStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbBundleStore);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the namedQueries object store.\n */\nfunction namedQueriesStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbNamedQueryStore);\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport {\n DocumentKeySet,\n MutationMap,\n OverlayMap,\n newOverlayMap\n} from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { Overlay } from '../model/overlay';\nimport { ResourcePath } from '../model/path';\n\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { encodeResourcePath } from './encoded_resource_path';\nimport { DbDocumentOverlay } from './indexeddb_schema';\nimport {\n DbDocumentOverlayCollectionGroupOverlayIndex,\n DbDocumentOverlayCollectionPathOverlayIndex,\n DbDocumentOverlayKey,\n DbDocumentOverlayStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n fromDbDocumentOverlay,\n LocalSerializer,\n toDbDocumentOverlay,\n toDbDocumentOverlayKey\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\n/**\n * Implementation of DocumentOverlayCache using IndexedDb.\n */\nexport class IndexedDbDocumentOverlayCache implements DocumentOverlayCache {\n /**\n * @param serializer - The document serializer.\n * @param userId - The userId for which we are accessing overlays.\n */\n constructor(\n private readonly serializer: LocalSerializer,\n private readonly userId: string\n ) {}\n\n static forUser(\n serializer: LocalSerializer,\n user: User\n ): IndexedDbDocumentOverlayCache {\n const userId = user.uid || '';\n return new IndexedDbDocumentOverlayCache(serializer, userId);\n }\n\n getOverlay(\n transaction: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return documentOverlayStore(transaction)\n .get(toDbDocumentOverlayKey(this.userId, key))\n .next(dbOverlay => {\n if (dbOverlay) {\n return fromDbDocumentOverlay(this.serializer, dbOverlay);\n }\n return null;\n });\n }\n\n getOverlays(\n transaction: PersistenceTransaction,\n keys: DocumentKey[]\n ): PersistencePromise {\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 const promises: Array> = [];\n overlays.forEach((_, mutation) => {\n const overlay = new Overlay(largestBatchId, mutation);\n promises.push(this.saveOverlay(transaction, overlay));\n });\n return PersistencePromise.waitFor(promises);\n }\n\n removeOverlaysForBatchId(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet,\n batchId: number\n ): PersistencePromise {\n const collectionPaths = new Set();\n\n // Get the set of unique collection paths.\n documentKeys.forEach(key =>\n collectionPaths.add(encodeResourcePath(key.getCollectionPath()))\n );\n\n const promises: Array> = [];\n collectionPaths.forEach(collectionPath => {\n const range = IDBKeyRange.bound(\n [this.userId, collectionPath, batchId],\n [this.userId, collectionPath, batchId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n promises.push(\n documentOverlayStore(transaction).deleteAll(\n DbDocumentOverlayCollectionPathOverlayIndex,\n range\n )\n );\n });\n return PersistencePromise.waitFor(promises);\n }\n\n getOverlaysForCollection(\n transaction: PersistenceTransaction,\n collection: ResourcePath,\n sinceBatchId: number\n ): PersistencePromise {\n const result = newOverlayMap();\n const collectionPath = encodeResourcePath(collection);\n // We want batch IDs larger than `sinceBatchId`, and so the lower bound\n // is not inclusive.\n const range = IDBKeyRange.bound(\n [this.userId, collectionPath, sinceBatchId],\n [this.userId, collectionPath, Number.POSITIVE_INFINITY],\n /*lowerOpen=*/ true\n );\n return documentOverlayStore(transaction)\n .loadAll(DbDocumentOverlayCollectionPathOverlayIndex, range)\n .next(dbOverlays => {\n for (const dbOverlay of dbOverlays) {\n const overlay = fromDbDocumentOverlay(this.serializer, dbOverlay);\n result.set(overlay.getKey(), overlay);\n }\n return result;\n });\n }\n\n getOverlaysForCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n sinceBatchId: number,\n count: number\n ): PersistencePromise {\n const result = newOverlayMap();\n let currentBatchId: number | undefined = undefined;\n // We want batch IDs larger than `sinceBatchId`, and so the lower bound\n // is not inclusive.\n const range = IDBKeyRange.bound(\n [this.userId, collectionGroup, sinceBatchId],\n [this.userId, collectionGroup, Number.POSITIVE_INFINITY],\n /*lowerOpen=*/ true\n );\n return documentOverlayStore(transaction)\n .iterate(\n {\n index: DbDocumentOverlayCollectionGroupOverlayIndex,\n range\n },\n (_, dbOverlay, control) => {\n // We do not want to return partial batch overlays, even if the size\n // of the result set exceeds the given `count` argument. Therefore, we\n // continue to aggregate results even after the result size exceeds\n // `count` if there are more overlays from the `currentBatchId`.\n const overlay = fromDbDocumentOverlay(this.serializer, dbOverlay);\n if (\n result.size() < count ||\n overlay.largestBatchId === currentBatchId\n ) {\n result.set(overlay.getKey(), overlay);\n currentBatchId = overlay.largestBatchId;\n } else {\n control.done();\n }\n }\n )\n .next(() => result);\n }\n\n private saveOverlay(\n transaction: PersistenceTransaction,\n overlay: Overlay\n ): PersistencePromise {\n return documentOverlayStore(transaction).put(\n toDbDocumentOverlay(this.serializer, this.userId, overlay)\n );\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document overlay object store.\n */\nfunction documentOverlayStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbDocumentOverlayStore\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 { DbGlobals } from './indexeddb_schema';\nimport { DbGlobalsStore, DbGlobalsKey } from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\nexport class IndexedDbGlobalsCache implements GlobalsCache {\n private globalsStore(\n txn: PersistenceTransaction\n ): SimpleDbStore {\n return getStore(txn, DbGlobalsStore);\n }\n\n getSessionToken(txn: PersistenceTransaction): PersistencePromise {\n const globals = this.globalsStore(txn);\n return globals.get('sessionToken').next(global => {\n const value = global?.value;\n return value\n ? ByteString.fromUint8Array(value)\n : ByteString.EMPTY_BYTE_STRING;\n });\n }\n\n setSessionToken(\n txn: PersistenceTransaction,\n sessionToken: ByteString\n ): PersistencePromise {\n const globals = this.globalsStore(txn);\n return globals.put({\n name: 'sessionToken',\n value: sessionToken.toUint8Array()\n });\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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(0x4a4e, '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 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law | agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES | CONDITIONS OF ANY KIND, either express | implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { debugAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\n\n/** These constants are taken from the backend. */\nconst MIN_SURROGATE = '\\uD800';\nconst MAX_SURROGATE = '\\uDBFF';\n\nconst ESCAPE1 = 0x00;\nconst NULL_BYTE = 0xff; // Combined with ESCAPE1\nconst SEPARATOR = 0x01; // Combined with ESCAPE1\n\nconst ESCAPE2 = 0xff;\nconst INFINITY = 0xff; // Combined with ESCAPE2\nconst FF_BYTE = 0x00; // Combined with ESCAPE2\n\nconst LONG_SIZE = 64;\nconst BYTE_SIZE = 8;\n\n/**\n * The default size of the buffer. This is arbitrary, but likely larger than\n * most index values so that less copies of the underlying buffer will be made.\n * For large values, a single copy will made to double the buffer length.\n */\nconst DEFAULT_BUFFER_SIZE = 1024;\n\n/** Converts a JavaScript number to a byte array (using big endian encoding). */\nfunction doubleToLongBits(value: number): Uint8Array {\n const dv = new DataView(new ArrayBuffer(8));\n dv.setFloat64(0, value, /* littleEndian= */ false);\n return new Uint8Array(dv.buffer);\n}\n\n/**\n * Counts the number of zeros in a byte.\n *\n * Visible for testing.\n */\nexport function numberOfLeadingZerosInByte(x: number): number {\n debugAssert(x < 256, 'Provided value is not a byte: ' + x);\n if (x === 0) {\n return 8;\n }\n\n let zeros = 0;\n if (x >> 4 === 0) {\n // Test if the first four bits are zero.\n zeros += 4;\n x = x << 4;\n }\n if (x >> 6 === 0) {\n // Test if the first two (or next two) bits are zero.\n zeros += 2;\n x = x << 2;\n }\n if (x >> 7 === 0) {\n // Test if the remaining bit is zero.\n zeros += 1;\n }\n return zeros;\n}\n\n/** Counts the number of leading zeros in the given byte array. */\nfunction numberOfLeadingZeros(bytes: Uint8Array): number {\n debugAssert(\n bytes.length === 8,\n 'Can only count leading zeros in 64-bit numbers'\n );\n let leadingZeros = 0;\n for (let i = 0; i < 8; ++i) {\n const zeros = numberOfLeadingZerosInByte(bytes[i] & 0xff);\n leadingZeros += zeros;\n if (zeros !== 8) {\n break;\n }\n }\n return leadingZeros;\n}\n\n/**\n * Returns the number of bytes required to store \"value\". Leading zero bytes\n * are skipped.\n */\nfunction unsignedNumLength(value: Uint8Array): number {\n // This is just the number of bytes for the unsigned representation of the number.\n const numBits = LONG_SIZE - numberOfLeadingZeros(value);\n return Math.ceil(numBits / BYTE_SIZE);\n}\n\n/**\n * OrderedCodeWriter is a minimal-allocation implementation of the writing\n * behavior defined by the backend.\n *\n * The code is ported from its Java counterpart.\n */\nexport class OrderedCodeWriter {\n buffer = new Uint8Array(DEFAULT_BUFFER_SIZE);\n position = 0;\n\n writeBytesAscending(value: ByteString): void {\n const it = value[Symbol.iterator]();\n let byte = it.next();\n while (!byte.done) {\n this.writeByteAscending(byte.value);\n byte = it.next();\n }\n this.writeSeparatorAscending();\n }\n\n writeBytesDescending(value: ByteString): void {\n const it = value[Symbol.iterator]();\n let byte = it.next();\n while (!byte.done) {\n this.writeByteDescending(byte.value);\n byte = it.next();\n }\n this.writeSeparatorDescending();\n }\n\n /** Writes utf8 bytes into this byte sequence, ascending. */\n writeUtf8Ascending(sequence: string): void {\n for (const c of sequence) {\n const charCode = c.charCodeAt(0);\n if (charCode < 0x80) {\n this.writeByteAscending(charCode);\n } else if (charCode < 0x800) {\n this.writeByteAscending((0x0f << 6) | (charCode >>> 6));\n this.writeByteAscending(0x80 | (0x3f & charCode));\n } else if (c < MIN_SURROGATE || MAX_SURROGATE < c) {\n this.writeByteAscending((0x0f << 5) | (charCode >>> 12));\n this.writeByteAscending(0x80 | (0x3f & (charCode >>> 6)));\n this.writeByteAscending(0x80 | (0x3f & charCode));\n } else {\n const codePoint = c.codePointAt(0)!;\n this.writeByteAscending((0x0f << 4) | (codePoint >>> 18));\n this.writeByteAscending(0x80 | (0x3f & (codePoint >>> 12)));\n this.writeByteAscending(0x80 | (0x3f & (codePoint >>> 6)));\n this.writeByteAscending(0x80 | (0x3f & codePoint));\n }\n }\n this.writeSeparatorAscending();\n }\n\n /** Writes utf8 bytes into this byte sequence, descending */\n writeUtf8Descending(sequence: string): void {\n for (const c of sequence) {\n const charCode = c.charCodeAt(0);\n if (charCode < 0x80) {\n this.writeByteDescending(charCode);\n } else if (charCode < 0x800) {\n this.writeByteDescending((0x0f << 6) | (charCode >>> 6));\n this.writeByteDescending(0x80 | (0x3f & charCode));\n } else if (c < MIN_SURROGATE || MAX_SURROGATE < c) {\n this.writeByteDescending((0x0f << 5) | (charCode >>> 12));\n this.writeByteDescending(0x80 | (0x3f & (charCode >>> 6)));\n this.writeByteDescending(0x80 | (0x3f & charCode));\n } else {\n const codePoint = c.codePointAt(0)!;\n this.writeByteDescending((0x0f << 4) | (codePoint >>> 18));\n this.writeByteDescending(0x80 | (0x3f & (codePoint >>> 12)));\n this.writeByteDescending(0x80 | (0x3f & (codePoint >>> 6)));\n this.writeByteDescending(0x80 | (0x3f & codePoint));\n }\n }\n this.writeSeparatorDescending();\n }\n\n writeNumberAscending(val: number): void {\n // Values are encoded with a single byte length prefix, followed by the\n // actual value in big-endian format with leading 0 bytes dropped.\n const value = this.toOrderedBits(val);\n const len = unsignedNumLength(value);\n this.ensureAvailable(1 + len);\n this.buffer[this.position++] = len & 0xff; // Write the length\n for (let i = value.length - len; i < value.length; ++i) {\n this.buffer[this.position++] = value[i] & 0xff;\n }\n }\n\n writeNumberDescending(val: number): void {\n // Values are encoded with a single byte length prefix, followed by the\n // inverted value in big-endian format with leading 0 bytes dropped.\n const value = this.toOrderedBits(val);\n const len = unsignedNumLength(value);\n this.ensureAvailable(1 + len);\n this.buffer[this.position++] = ~(len & 0xff); // Write the length\n for (let i = value.length - len; i < value.length; ++i) {\n this.buffer[this.position++] = ~(value[i] & 0xff);\n }\n }\n\n /**\n * Writes the \"infinity\" byte sequence that sorts after all other byte\n * sequences written in ascending order.\n */\n writeInfinityAscending(): void {\n this.writeEscapedByteAscending(ESCAPE2);\n this.writeEscapedByteAscending(INFINITY);\n }\n\n /**\n * Writes the \"infinity\" byte sequence that sorts before all other byte\n * sequences written in descending order.\n */\n writeInfinityDescending(): void {\n this.writeEscapedByteDescending(ESCAPE2);\n this.writeEscapedByteDescending(INFINITY);\n }\n\n /**\n * Resets the buffer such that it is the same as when it was newly\n * constructed.\n */\n reset(): void {\n this.position = 0;\n }\n\n seed(encodedBytes: Uint8Array): void {\n this.ensureAvailable(encodedBytes.length);\n this.buffer.set(encodedBytes, this.position);\n this.position += encodedBytes.length;\n }\n\n /** Makes a copy of the encoded bytes in this buffer. */\n encodedBytes(): Uint8Array {\n return this.buffer.slice(0, this.position);\n }\n\n /**\n * Encodes `val` into an encoding so that the order matches the IEEE 754\n * floating-point comparison results with the following exceptions:\n * -0.0 < 0.0\n * all non-NaN < NaN\n * NaN = NaN\n */\n private toOrderedBits(val: number): Uint8Array {\n const value = doubleToLongBits(val);\n // Check if the first bit is set. We use a bit mask since value[0] is\n // encoded as a number from 0 to 255.\n const isNegative = (value[0] & 0x80) !== 0;\n\n // Revert the two complement to get natural ordering\n value[0] ^= isNegative ? 0xff : 0x80;\n for (let i = 1; i < value.length; ++i) {\n value[i] ^= isNegative ? 0xff : 0x00;\n }\n return value;\n }\n\n /** Writes a single byte ascending to the buffer. */\n private writeByteAscending(b: number): void {\n const masked = b & 0xff;\n if (masked === ESCAPE1) {\n this.writeEscapedByteAscending(ESCAPE1);\n this.writeEscapedByteAscending(NULL_BYTE);\n } else if (masked === ESCAPE2) {\n this.writeEscapedByteAscending(ESCAPE2);\n this.writeEscapedByteAscending(FF_BYTE);\n } else {\n this.writeEscapedByteAscending(masked);\n }\n }\n\n /** Writes a single byte descending to the buffer. */\n private writeByteDescending(b: number): void {\n const masked = b & 0xff;\n if (masked === ESCAPE1) {\n this.writeEscapedByteDescending(ESCAPE1);\n this.writeEscapedByteDescending(NULL_BYTE);\n } else if (masked === ESCAPE2) {\n this.writeEscapedByteDescending(ESCAPE2);\n this.writeEscapedByteDescending(FF_BYTE);\n } else {\n this.writeEscapedByteDescending(b);\n }\n }\n\n private writeSeparatorAscending(): void {\n this.writeEscapedByteAscending(ESCAPE1);\n this.writeEscapedByteAscending(SEPARATOR);\n }\n\n private writeSeparatorDescending(): void {\n this.writeEscapedByteDescending(ESCAPE1);\n this.writeEscapedByteDescending(SEPARATOR);\n }\n\n private writeEscapedByteAscending(b: number): void {\n this.ensureAvailable(1);\n this.buffer[this.position++] = b;\n }\n\n private writeEscapedByteDescending(b: number): void {\n this.ensureAvailable(1);\n this.buffer[this.position++] = ~b;\n }\n\n private ensureAvailable(bytes: number): void {\n const minCapacity = bytes + this.position;\n if (minCapacity <= this.buffer.length) {\n return;\n }\n // Try doubling.\n let newLength = this.buffer.length * 2;\n // Still not big enough? Just allocate the right size.\n if (newLength < minCapacity) {\n newLength = minCapacity;\n }\n // Create the new buffer.\n const newBuffer = new Uint8Array(newLength);\n newBuffer.set(this.buffer); // copy old data\n this.buffer = newBuffer;\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { IndexKind } from '../model/field_index';\nimport { ByteString } from '../util/byte_string';\n\nimport { DirectionalIndexByteEncoder } from './directional_index_byte_encoder';\nimport { OrderedCodeWriter } from './ordered_code_writer';\n\nclass AscendingIndexByteEncoder implements DirectionalIndexByteEncoder {\n constructor(private orderedCode: OrderedCodeWriter) {}\n writeBytes(value: ByteString): void {\n this.orderedCode.writeBytesAscending(value);\n }\n\n writeString(value: string): void {\n this.orderedCode.writeUtf8Ascending(value);\n }\n\n writeNumber(value: number): void {\n this.orderedCode.writeNumberAscending(value);\n }\n\n writeInfinity(): void {\n this.orderedCode.writeInfinityAscending();\n }\n}\n\nclass DescendingIndexByteEncoder implements DirectionalIndexByteEncoder {\n constructor(private orderedCode: OrderedCodeWriter) {}\n writeBytes(value: ByteString): void {\n this.orderedCode.writeBytesDescending(value);\n }\n\n writeString(value: string): void {\n this.orderedCode.writeUtf8Descending(value);\n }\n\n writeNumber(value: number): void {\n this.orderedCode.writeNumberDescending(value);\n }\n\n writeInfinity(): void {\n this.orderedCode.writeInfinityDescending();\n }\n}\n/**\n * Implements `DirectionalIndexByteEncoder` using `OrderedCodeWriter` for the\n * actual encoding.\n */\nexport class IndexByteEncoder {\n private orderedCode = new OrderedCodeWriter();\n private ascending = new AscendingIndexByteEncoder(this.orderedCode);\n private descending = new DescendingIndexByteEncoder(this.orderedCode);\n\n seed(encodedBytes: Uint8Array): void {\n this.orderedCode.seed(encodedBytes);\n }\n\n forKind(kind: IndexKind): DirectionalIndexByteEncoder {\n return kind === IndexKind.ASCENDING ? this.ascending : this.descending;\n }\n\n encodedBytes(): Uint8Array {\n return this.orderedCode.encodedBytes();\n }\n\n reset(): void {\n this.orderedCode.reset();\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isSafariOrWebkit } from '@firebase/util';\n\nimport { DbIndexEntry } from '../local/indexeddb_schema';\nimport { DbIndexEntryKey, KeySafeBytes } from '../local/indexeddb_sentinels';\nimport { DocumentKey } from '../model/document_key';\n\n/** Represents an index entry saved by the SDK in persisted storage. */\nexport class IndexEntry {\n constructor(\n readonly _indexId: number,\n readonly _documentKey: DocumentKey,\n readonly _arrayValue: Uint8Array,\n readonly _directionalValue: Uint8Array\n ) {}\n\n /**\n * Returns an IndexEntry entry that sorts immediately after the current\n * directional value.\n */\n successor(): IndexEntry {\n const currentLength = this._directionalValue.length;\n const newLength =\n currentLength === 0 || this._directionalValue[currentLength - 1] === 255\n ? currentLength + 1\n : currentLength;\n\n const successor = new Uint8Array(newLength);\n successor.set(this._directionalValue, 0);\n if (newLength !== currentLength) {\n successor.set([0], this._directionalValue.length);\n } else {\n ++successor[successor.length - 1];\n }\n\n return new IndexEntry(\n this._indexId,\n this._documentKey,\n this._arrayValue,\n successor\n );\n }\n\n // Create a representation of the Index Entry as a DbIndexEntry\n dbIndexEntry(\n uid: string,\n orderedDocumentKey: Uint8Array,\n documentKey: DocumentKey\n ): DbIndexEntry {\n return {\n indexId: this._indexId,\n uid,\n arrayValue: encodeKeySafeBytes(this._arrayValue),\n directionalValue: encodeKeySafeBytes(this._directionalValue),\n orderedDocumentKey: encodeKeySafeBytes(orderedDocumentKey),\n documentKey: documentKey.path.toArray()\n };\n }\n\n // Create a representation of the Index Entry as a DbIndexEntryKey\n dbIndexEntryKey(\n uid: string,\n orderedDocumentKey: Uint8Array,\n documentKey: DocumentKey\n ): DbIndexEntryKey {\n const entry = this.dbIndexEntry(uid, orderedDocumentKey, documentKey);\n return [\n entry.indexId,\n entry.uid,\n entry.arrayValue,\n entry.directionalValue,\n entry.orderedDocumentKey,\n entry.documentKey\n ];\n }\n}\n\nexport function indexEntryComparator(\n left: IndexEntry,\n right: IndexEntry\n): number {\n let cmp = left._indexId - right._indexId;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = compareByteArrays(left._arrayValue, right._arrayValue);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = compareByteArrays(left._directionalValue, right._directionalValue);\n if (cmp !== 0) {\n return cmp;\n }\n\n return DocumentKey.comparator(left._documentKey, right._documentKey);\n}\n\nexport function compareByteArrays(left: Uint8Array, right: Uint8Array): number {\n for (let i = 0; i < left.length && i < right.length; ++i) {\n const compare = left[i] - right[i];\n if (compare !== 0) {\n return compare;\n }\n }\n return left.length - right.length;\n}\n\n/**\n * Workaround for WebKit bug: https://bugs.webkit.org/show_bug.cgi?id=292721\n * Create a key safe representation of Uint8Array values.\n * If the browser is detected as Safari or WebKit, then\n * the input array will be converted to \"sortable byte string\".\n * Otherwise, the input array will be returned in its original type.\n */\nexport function encodeKeySafeBytes(array: Uint8Array): KeySafeBytes {\n if (isSafariOrWebkit()) {\n return encodeUint8ArrayToSortableString(array);\n }\n return array;\n}\n\n/**\n * Reverts the key safe representation of Uint8Array (created by\n * encodeKeySafeBytes) to a normal Uint8Array.\n */\nexport function decodeKeySafeBytes(input: KeySafeBytes): Uint8Array {\n if (typeof input !== 'string') {\n return input;\n }\n return decodeSortableStringToUint8Array(input);\n}\n\n/**\n * Encodes a Uint8Array into a \"sortable byte string\".\n * A \"sortable byte string\" sorts in the same order as the Uint8Array.\n * This works because JS string comparison sorts strings based on code points.\n */\nfunction encodeUint8ArrayToSortableString(array: Uint8Array): string {\n let byteString = '';\n for (let i = 0; i < array.length; i++) {\n byteString += String.fromCharCode(array[i]);\n }\n\n return byteString;\n}\n\n/**\n * Decodes a \"sortable byte string\" back into a Uint8Array.\n * A \"sortable byte string\" is assumed to be created where each character's\n * Unicode code point directly corresponds to a single byte value (0-255).\n */\nfunction decodeSortableStringToUint8Array(byteString: string): Uint8Array {\n const uint8array = new Uint8Array(byteString.length);\n\n for (let i = 0; i < byteString.length; i++) {\n uint8array[i] = byteString.charCodeAt(i);\n }\n\n return uint8array;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldFilter, Operator } from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport { Target } from '../core/target';\nimport { hardAssert } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport {\n FieldIndex,\n fieldIndexGetArraySegment,\n fieldIndexGetDirectionalSegments,\n IndexKind,\n IndexSegment,\n IndexState\n} from './field_index';\nimport { FieldPath } from './path';\n\n/**\n * A light query planner for Firestore.\n *\n * This class matches a `FieldIndex` against a Firestore Query `Target`. It\n * determines whether a given index can be used to serve the specified target.\n *\n * The following table showcases some possible index configurations:\n *\n * Query | Index\n * -----------------------------------------------------------------------------\n * where('a', '==', 'a').where('b', '==', 'b') | a ASC, b DESC\n * where('a', '==', 'a').where('b', '==', 'b') | a ASC\n * where('a', '==', 'a').where('b', '==', 'b') | b DESC\n * where('a', '>=', 'a').orderBy('a') | a ASC\n * where('a', '>=', 'a').orderBy('a', 'desc') | a DESC\n * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC, b ASC\n * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC\n * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS, b ASCENDING\n * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS\n */\nexport class TargetIndexMatcher {\n // The collection ID (or collection group) of the query target.\n private readonly collectionId: string;\n // The inequality filters of the target (if it exists).\n // Note: The sort on FieldFilters is not required. Using SortedSet here just to utilize the custom\n // comparator.\n private inequalityFilters = new SortedSet((lhs, rhs) =>\n FieldPath.comparator(lhs.field, rhs.field)\n );\n\n // The list of equality filters of the target.\n private readonly equalityFilters: FieldFilter[];\n // The list of orderBys of the target.\n private readonly orderBys: OrderBy[];\n\n constructor(target: Target) {\n this.collectionId =\n target.collectionGroup != null\n ? target.collectionGroup\n : target.path.lastSegment();\n this.orderBys = target.orderBy;\n this.equalityFilters = [];\n for (const filter of target.filters) {\n const fieldFilter = filter as FieldFilter;\n if (fieldFilter.isInequality()) {\n this.inequalityFilters = this.inequalityFilters.add(fieldFilter);\n } else {\n this.equalityFilters.push(fieldFilter);\n }\n }\n }\n\n get hasMultipleInequality(): boolean {\n return this.inequalityFilters.size > 1;\n }\n\n /**\n * Returns whether the index can be used to serve the TargetIndexMatcher's\n * target.\n *\n * An index is considered capable of serving the target when:\n * - The target uses all index segments for its filters and orderBy clauses.\n * The target can have additional filter and orderBy clauses, but not\n * fewer.\n * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also\n * have a corresponding `CONTAINS` segment.\n * - All directional index segments can be mapped to the target as a series of\n * equality filters, a single inequality filter and a series of orderBy\n * clauses.\n * - The segments that represent the equality filters may appear out of order.\n * - The optional segment for the inequality filter must appear after all\n * equality segments.\n * - The segments that represent that orderBy clause of the target must appear\n * in order after all equality and inequality segments. Single orderBy\n * clauses cannot be skipped, but a continuous orderBy suffix may be\n * omitted.\n */\n servedByIndex(index: FieldIndex): boolean {\n hardAssert(\n index.collectionGroup === this.collectionId,\n 0xc07f,\n 'Collection IDs do not match'\n );\n\n if (this.hasMultipleInequality) {\n // Only single inequality is supported for now.\n // TODO(Add support for multiple inequality query): b/298441043\n return false;\n }\n\n // If there is an array element, find a matching filter.\n const arraySegment = fieldIndexGetArraySegment(index);\n if (\n arraySegment !== undefined &&\n !this.hasMatchingEqualityFilter(arraySegment)\n ) {\n return false;\n }\n\n const segments = fieldIndexGetDirectionalSegments(index);\n let equalitySegments = new Set();\n let segmentIndex = 0;\n let orderBysIndex = 0;\n\n // Process all equalities first. Equalities can appear out of order.\n for (; segmentIndex < segments.length; ++segmentIndex) {\n // We attempt to greedily match all segments to equality filters. If a\n // filter matches an index segment, we can mark the segment as used.\n if (this.hasMatchingEqualityFilter(segments[segmentIndex])) {\n equalitySegments = equalitySegments.add(\n segments[segmentIndex].fieldPath.canonicalString()\n );\n } else {\n // If we cannot find a matching filter, we need to verify whether the\n // remaining segments map to the target's inequality and its orderBy\n // clauses.\n break;\n }\n }\n\n // If we already have processed all segments, all segments are used to serve\n // the equality filters and we do not need to map any segments to the\n // target's inequality and orderBy clauses.\n if (segmentIndex === segments.length) {\n return true;\n }\n\n if (this.inequalityFilters.size > 0) {\n // Only a single inequality is currently supported. Get the only entry in the set.\n const inequalityFilter = this.inequalityFilters.getIterator().getNext();\n // If there is an inequality filter and the field was not in one of the\n // equality filters above, the next segment must match both the filter\n // and the first orderBy clause.\n if (!equalitySegments.has(inequalityFilter.field.canonicalString())) {\n const segment = segments[segmentIndex];\n\n if (\n !this.matchesFilter(inequalityFilter, segment) ||\n !this.matchesOrderBy(this.orderBys[orderBysIndex++], segment)\n ) {\n return false;\n }\n }\n\n ++segmentIndex;\n }\n\n // All remaining segments need to represent the prefix of the target's\n // orderBy.\n for (; segmentIndex < segments.length; ++segmentIndex) {\n const segment = segments[segmentIndex];\n if (\n orderBysIndex >= this.orderBys.length ||\n !this.matchesOrderBy(this.orderBys[orderBysIndex++], segment)\n ) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Returns a full matched field index for this target. Currently multiple\n * inequality query is not supported so function returns null.\n */\n buildTargetIndex(): FieldIndex | null {\n if (this.hasMultipleInequality) {\n return null;\n }\n\n // We want to make sure only one segment created for one field. For example,\n // in case like a == 3 and a > 2, Index {a ASCENDING} will only be created\n // once.\n let uniqueFields = new SortedSet(FieldPath.comparator);\n const segments: IndexSegment[] = [];\n\n for (const filter of this.equalityFilters) {\n if (filter.field.isKeyField()) {\n continue;\n }\n const isArrayOperator =\n filter.op === Operator.ARRAY_CONTAINS ||\n filter.op === Operator.ARRAY_CONTAINS_ANY;\n if (isArrayOperator) {\n segments.push(new IndexSegment(filter.field, IndexKind.CONTAINS));\n } else {\n if (uniqueFields.has(filter.field)) {\n continue;\n }\n uniqueFields = uniqueFields.add(filter.field);\n segments.push(new IndexSegment(filter.field, IndexKind.ASCENDING));\n }\n }\n\n // Note: We do not explicitly check `this.inequalityFilter` but rather rely\n // on the target defining an appropriate \"order by\" to ensure that the\n // required index segment is added. The query engine would reject a query\n // with an inequality filter that lacks the required order-by clause.\n for (const orderBy of this.orderBys) {\n // Stop adding more segments if we see a order-by on key. Typically this\n // is the default implicit order-by which is covered in the index_entry\n // table as a separate column. If it is not the default order-by, the\n // generated index will be missing some segments optimized for order-bys,\n // which is probably fine.\n if (orderBy.field.isKeyField()) {\n continue;\n }\n\n if (uniqueFields.has(orderBy.field)) {\n continue;\n }\n uniqueFields = uniqueFields.add(orderBy.field);\n\n segments.push(\n new IndexSegment(\n orderBy.field,\n orderBy.dir === Direction.ASCENDING\n ? IndexKind.ASCENDING\n : IndexKind.DESCENDING\n )\n );\n }\n\n return new FieldIndex(\n FieldIndex.UNKNOWN_ID,\n this.collectionId,\n segments,\n IndexState.empty()\n );\n }\n\n private hasMatchingEqualityFilter(segment: IndexSegment): boolean {\n for (const filter of this.equalityFilters) {\n if (this.matchesFilter(filter, segment)) {\n return true;\n }\n }\n return false;\n }\n\n private matchesFilter(\n filter: FieldFilter | undefined,\n segment: IndexSegment\n ): boolean {\n if (filter === undefined || !filter.field.isEqual(segment.fieldPath)) {\n return false;\n }\n const isArrayOperator =\n filter.op === Operator.ARRAY_CONTAINS ||\n filter.op === Operator.ARRAY_CONTAINS_ANY;\n return (segment.kind === IndexKind.CONTAINS) === isArrayOperator;\n }\n\n private matchesOrderBy(orderBy: OrderBy, segment: IndexSegment): boolean {\n if (!orderBy.field.isEqual(segment.fieldPath)) {\n return false;\n }\n return (\n (segment.kind === IndexKind.ASCENDING &&\n orderBy.dir === Direction.ASCENDING) ||\n (segment.kind === IndexKind.DESCENDING &&\n orderBy.dir === Direction.DESCENDING)\n );\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n CompositeFilter,\n compositeFilterIsConjunction,\n compositeFilterIsDisjunction,\n compositeFilterIsFlat,\n compositeFilterIsFlatConjunction,\n compositeFilterWithAddedFilters,\n CompositeOperator,\n FieldFilter,\n Filter,\n InFilter,\n Operator\n} from '../core/filter';\n\nimport { hardAssert } from './assert';\n\n/**\n * Provides utility functions that help with boolean logic transformations needed for handling\n * complex filters used in queries.\n */\n\n/**\n * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in\n * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given\n * input into a disjunction of equality filters and returns the expanded filter.\n */\nexport function computeInExpansion(filter: Filter): Filter {\n hardAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 0x4e2c,\n 'Only field filters and composite filters are accepted.'\n );\n\n if (filter instanceof FieldFilter) {\n if (filter instanceof InFilter) {\n const expandedFilters =\n filter.value.arrayValue?.values?.map(value =>\n FieldFilter.create(filter.field, Operator.EQUAL, value)\n ) || [];\n\n return CompositeFilter.create(expandedFilters, CompositeOperator.OR);\n } else {\n // We have reached other kinds of field filters.\n return filter;\n }\n }\n\n // We have a composite filter.\n const expandedFilters = filter.filters.map(subfilter =>\n computeInExpansion(subfilter)\n );\n return CompositeFilter.create(expandedFilters, filter.op);\n}\n\n/**\n * Given a composite filter, returns the list of terms in its disjunctive normal form.\n *\n *

Each element in the return value is one term of the resulting DNF. For instance: For the\n * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list\n * with two elements: a composite filter that performs (A && C), and a composite filter that\n * performs (B && C).\n *\n * @param filter the composite filter to calculate DNF transform for.\n * @return the terms in the DNF transform.\n */\nexport function getDnfTerms(filter: CompositeFilter): Filter[] {\n if (filter.getFilters().length === 0) {\n return [];\n }\n\n const result: Filter = computeDistributedNormalForm(\n computeInExpansion(filter)\n );\n\n hardAssert(\n isDisjunctiveNormalForm(result),\n 0x1cdf,\n 'computeDistributedNormalForm did not result in disjunctive normal form'\n );\n\n if (isSingleFieldFilter(result) || isFlatConjunction(result)) {\n return [result];\n }\n\n return result.getFilters();\n}\n\n/** Returns true if the given filter is a single field filter. e.g. (a == 10). */\nfunction isSingleFieldFilter(filter: Filter): boolean {\n return filter instanceof FieldFilter;\n}\n\n/**\n * Returns true if the given filter is the conjunction of one or more field filters. e.g. (a == 10\n * && b == 20)\n */\nfunction isFlatConjunction(filter: Filter): boolean {\n return (\n filter instanceof CompositeFilter &&\n compositeFilterIsFlatConjunction(filter)\n );\n}\n\n/**\n * Returns whether or not the given filter is in disjunctive normal form (DNF).\n *\n *

In boolean logic, a disjunctive normal form (DNF) is a canonical normal form of a logical\n * formula consisting of a disjunction of conjunctions; it can also be described as an OR of ANDs.\n *\n *

For more info, visit: https://en.wikipedia.org/wiki/Disjunctive_normal_form\n */\nfunction isDisjunctiveNormalForm(filter: Filter): boolean {\n return (\n isSingleFieldFilter(filter) ||\n isFlatConjunction(filter) ||\n isDisjunctionOfFieldFiltersAndFlatConjunctions(filter)\n );\n}\n\n/**\n * Returns true if the given filter is the disjunction of one or more \"flat conjunctions\" and\n * field filters. e.g. (a == 10) || (b==20 && c==30)\n */\nfunction isDisjunctionOfFieldFiltersAndFlatConjunctions(\n filter: Filter\n): boolean {\n if (filter instanceof CompositeFilter) {\n if (compositeFilterIsDisjunction(filter)) {\n for (const subFilter of filter.getFilters()) {\n if (!isSingleFieldFilter(subFilter) && !isFlatConjunction(subFilter)) {\n return false;\n }\n }\n\n return true;\n }\n }\n\n return false;\n}\n\nexport function computeDistributedNormalForm(filter: Filter): Filter {\n hardAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 0x84e2,\n 'Only field filters and composite filters are accepted.'\n );\n\n if (filter instanceof FieldFilter) {\n return filter;\n }\n\n if (filter.filters.length === 1) {\n return computeDistributedNormalForm(filter.filters[0]);\n }\n\n // Compute DNF for each of the subfilters first\n const result = filter.filters.map(subfilter =>\n computeDistributedNormalForm(subfilter)\n );\n\n let newFilter: Filter = CompositeFilter.create(result, filter.op);\n newFilter = applyAssociation(newFilter);\n\n if (isDisjunctiveNormalForm(newFilter)) {\n return newFilter;\n }\n\n hardAssert(\n newFilter instanceof CompositeFilter,\n 0xfbf2,\n 'field filters are already in DNF form'\n );\n hardAssert(\n compositeFilterIsConjunction(newFilter),\n 0x9d3b,\n 'Disjunction of filters all of which are already in DNF form is itself in DNF form.'\n );\n hardAssert(\n newFilter.filters.length > 1,\n 0xe247,\n 'Single-filter composite filters are already in DNF form.'\n );\n\n return newFilter.filters.reduce((runningResult, filter) =>\n applyDistribution(runningResult, filter)\n );\n}\n\nexport function applyDistribution(lhs: Filter, rhs: Filter): Filter {\n hardAssert(\n lhs instanceof FieldFilter || lhs instanceof CompositeFilter,\n 0x95f4,\n 'Only field filters and composite filters are accepted.'\n );\n hardAssert(\n rhs instanceof FieldFilter || rhs instanceof CompositeFilter,\n 0x6381,\n 'Only field filters and composite filters are accepted.'\n );\n\n let result: Filter;\n\n if (lhs instanceof FieldFilter) {\n if (rhs instanceof FieldFilter) {\n // FieldFilter FieldFilter\n result = applyDistributionFieldFilters(lhs, rhs);\n } else {\n // FieldFilter CompositeFilter\n result = applyDistributionFieldAndCompositeFilters(lhs, rhs);\n }\n } else {\n if (rhs instanceof FieldFilter) {\n // CompositeFilter FieldFilter\n result = applyDistributionFieldAndCompositeFilters(rhs, lhs);\n } else {\n // CompositeFilter CompositeFilter\n result = applyDistributionCompositeFilters(lhs, rhs);\n }\n }\n\n return applyAssociation(result);\n}\n\nfunction applyDistributionFieldFilters(\n lhs: FieldFilter,\n rhs: FieldFilter\n): Filter {\n // Conjunction distribution for two field filters is the conjunction of them.\n return CompositeFilter.create([lhs, rhs], CompositeOperator.AND);\n}\n\nfunction applyDistributionCompositeFilters(\n lhs: CompositeFilter,\n rhs: CompositeFilter\n): Filter {\n hardAssert(\n lhs.filters.length > 0 && rhs.filters.length > 0,\n 0xbb85,\n 'Found an empty composite filter'\n );\n\n // There are four cases:\n // (A & B) & (C & D) --> (A & B & C & D)\n // (A & B) & (C | D) --> (A & B & C) | (A & B & D)\n // (A | B) & (C & D) --> (C & D & A) | (C & D & B)\n // (A | B) & (C | D) --> (A & C) | (A & D) | (B & C) | (B & D)\n\n // Case 1 is a merge.\n if (compositeFilterIsConjunction(lhs) && compositeFilterIsConjunction(rhs)) {\n return compositeFilterWithAddedFilters(lhs, rhs.getFilters());\n }\n\n // Case 2,3,4 all have at least one side (lhs or rhs) that is a disjunction. In all three cases\n // we should take each element of the disjunction and distribute it over the other side, and\n // return the disjunction of the distribution results.\n const disjunctionSide = compositeFilterIsDisjunction(lhs) ? lhs : rhs;\n const otherSide = compositeFilterIsDisjunction(lhs) ? rhs : lhs;\n const results = disjunctionSide.filters.map(subfilter =>\n applyDistribution(subfilter, otherSide)\n );\n return CompositeFilter.create(results, CompositeOperator.OR);\n}\n\nfunction applyDistributionFieldAndCompositeFilters(\n fieldFilter: FieldFilter,\n compositeFilter: CompositeFilter\n): Filter {\n // There are two cases:\n // A & (B & C) --> (A & B & C)\n // A & (B | C) --> (A & B) | (A & C)\n if (compositeFilterIsConjunction(compositeFilter)) {\n // Case 1\n return compositeFilterWithAddedFilters(\n compositeFilter,\n fieldFilter.getFilters()\n );\n } else {\n // Case 2\n const newFilters = compositeFilter.filters.map(subfilter =>\n applyDistribution(fieldFilter, subfilter)\n );\n\n return CompositeFilter.create(newFilters, CompositeOperator.OR);\n }\n}\n\n/**\n * Applies the associativity property to the given filter and returns the resulting filter.\n *\n *

    \n *
  • A | (B | C) == (A | B) | C == (A | B | C)\n *
  • A & (B & C) == (A & B) & C == (A & B & C)\n *
\n *\n *

For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic\n */\nexport function applyAssociation(filter: Filter): Filter {\n hardAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 0x2e4a,\n 'Only field filters and composite filters are accepted.'\n );\n\n if (filter instanceof FieldFilter) {\n return filter;\n }\n\n const filters = filter.getFilters();\n\n // If the composite filter only contains 1 filter, apply associativity to it.\n if (filters.length === 1) {\n return applyAssociation(filters[0]);\n }\n\n // Associativity applied to a flat composite filter results is itself.\n if (compositeFilterIsFlat(filter)) {\n return filter;\n }\n\n // First apply associativity to all subfilters. This will in turn recursively apply\n // associativity to all nested composite filters and field filters.\n const updatedFilters = filters.map(subfilter => applyAssociation(subfilter));\n\n // For composite subfilters that perform the same kind of logical operation as `compositeFilter`\n // take out their filters and add them to `compositeFilter`. For example:\n // compositeFilter = (A | (B | C | D))\n // compositeSubfilter = (B | C | D)\n // Result: (A | B | C | D)\n // Note that the `compositeSubfilter` has been eliminated, and its filters (B, C, D) have been\n // added to the top-level \"compositeFilter\".\n const newSubfilters: Filter[] = [];\n updatedFilters.forEach(subfilter => {\n if (subfilter instanceof FieldFilter) {\n newSubfilters.push(subfilter);\n } else if (subfilter instanceof CompositeFilter) {\n if (subfilter.op === filter.op) {\n // compositeFilter: (A | (B | C))\n // compositeSubfilter: (B | C)\n // Result: (A | B | C)\n newSubfilters.push(...subfilter.filters);\n } else {\n // compositeFilter: (A | (B & C))\n // compositeSubfilter: (B & C)\n // Result: (A | (B & C))\n newSubfilters.push(subfilter);\n }\n }\n });\n\n if (newSubfilters.length === 1) {\n return newSubfilters[0];\n }\n\n return CompositeFilter.create(newSubfilters, filter.op);\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Target } from '../core/target';\nimport { DocumentMap } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldIndex, IndexOffset } from '../model/field_index';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { IndexManager, IndexType } from './index_manager';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\n/**\n * An in-memory implementation of IndexManager.\n */\nexport class MemoryIndexManager implements IndexManager {\n private collectionParentIndex = new MemoryCollectionParentIndex();\n\n addToCollectionParentIndex(\n transaction: PersistenceTransaction,\n collectionPath: ResourcePath\n ): PersistencePromise {\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 {\n IndexEntry,\n indexEntryComparator,\n encodeKeySafeBytes,\n decodeKeySafeBytes\n} 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 indexEntry.dbIndexEntry(\n this.uid,\n this.encodeDirectionalKey(fieldIndex, document.key),\n document.key\n )\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.dbIndexEntryKey(\n this.uid,\n this.encodeDirectionalKey(fieldIndex, document.key),\n document.key\n )\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 encodeKeySafeBytes(\n this.encodeDirectionalKey(fieldIndex, documentKey)\n )\n ])\n },\n (_, entry) => {\n results = results.add(\n new IndexEntry(\n fieldIndex.indexId,\n documentKey,\n decodeKeySafeBytes(entry.arrayValue),\n decodeKeySafeBytes(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 = bounds[i].dbIndexEntryKey(\n this.uid,\n EMPTY_VALUE,\n DocumentKey.empty()\n );\n const upperBound = bounds[i + 1].dbIndexEntryKey(\n this.uid,\n EMPTY_VALUE,\n DocumentKey.empty()\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(0xad8a, '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 0x7099,\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from '../model/document_key';\nimport { fail, hardAssert } from '../util/assert';\n\nimport {\n DbDocumentMutation,\n DbMutationBatch,\n DbRemoteDocument\n} from './indexeddb_schema';\nimport { DbRemoteDocument as DbRemoteDocumentLegacy } from './indexeddb_schema_legacy';\nimport {\n DbDocumentMutationKey,\n DbDocumentMutationStore,\n DbMutationBatchKey,\n DbMutationBatchStore,\n newDbDocumentMutationKey\n} from './indexeddb_sentinels';\nimport { PersistencePromise } from './persistence_promise';\nimport { SimpleDbTransaction } from './simple_db';\n\n/**\n * Delete a mutation batch and the associated document mutations.\n * @returns A PersistencePromise of the document mutations that were removed.\n */\nexport function removeMutationBatch(\n txn: SimpleDbTransaction,\n userId: string,\n batch: { batchId: number; mutations: Array<{ key: DocumentKey }> }\n): PersistencePromise {\n const mutationStore = txn.store(\n DbMutationBatchStore\n );\n const indexTxn = txn.store(\n DbDocumentMutationStore\n );\n const promises: Array> = [];\n\n const range = IDBKeyRange.only(batch.batchId);\n let numDeleted = 0;\n const removePromise = mutationStore.iterate(\n { range },\n (key, value, control) => {\n numDeleted++;\n return control.delete();\n }\n );\n promises.push(\n removePromise.next(() => {\n hardAssert(\n numDeleted === 1,\n 0xb7de,\n 'Dangling document-mutation reference found: Missing batch',\n { batchId: batch.batchId }\n );\n })\n );\n const removedDocuments: DocumentKey[] = [];\n for (const mutation of batch.mutations) {\n const indexKey = newDbDocumentMutationKey(\n userId,\n mutation.key.path,\n batch.batchId\n );\n promises.push(indexTxn.delete(indexKey));\n removedDocuments.push(mutation.key);\n }\n return PersistencePromise.waitFor(promises).next(() => removedDocuments);\n}\n\n/**\n * Returns an approximate size for the given document.\n */\nexport function dbDocumentSize(\n doc: DbRemoteDocument | DbRemoteDocumentLegacy | null\n): number {\n if (!doc) {\n return 0;\n }\n\n let value: unknown;\n if (doc.document) {\n value = doc.document;\n } else if (doc.unknownDocument) {\n value = doc.unknownDocument;\n } else if (doc.noDocument) {\n value = doc.noDocument;\n } else {\n throw fail(0x398b, 'Unknown remote document type');\n }\n return JSON.stringify(value).length;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { isCollectionGroupQuery, isDocumentQuery, Query } from '../core/query';\nimport { BatchId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { DocumentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { MutationBatch } from '../model/mutation_batch';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport { decodeResourcePath } from './encoded_resource_path';\nimport { IndexManager } from './index_manager';\nimport { removeMutationBatch } from './indexeddb_mutation_batch_impl';\nimport {\n DbDocumentMutation,\n DbMutationBatch,\n DbMutationQueue\n} from './indexeddb_schema';\nimport {\n DbDocumentMutationKey,\n DbDocumentMutationPlaceholder,\n DbDocumentMutationStore,\n DbMutationBatchKey,\n DbMutationBatchStore,\n DbMutationBatchUserMutationsIndex,\n DbMutationQueueKey,\n DbMutationQueueStore,\n newDbDocumentMutationKey,\n newDbDocumentMutationPrefixForPath,\n newDbDocumentMutationPrefixForUser\n} from './indexeddb_sentinels';\nimport { IndexedDbTransaction, getStore } from './indexeddb_transaction';\nimport {\n fromDbMutationBatch,\n LocalSerializer,\n toDbMutationBatch\n} from './local_serializer';\nimport { MutationQueue } from './mutation_queue';\nimport { ReferenceDelegate } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\n/** A mutation queue for a specific user, backed by IndexedDB. */\nexport class IndexedDbMutationQueue implements MutationQueue {\n /**\n * Caches the document keys for pending mutation batches. If the mutation\n * has been removed from IndexedDb, the cached value may continue to\n * be used to retrieve the batch's document keys. To remove a cached value\n * locally, `removeCachedMutationKeys()` should be invoked either directly\n * or through `removeMutationBatches()`.\n *\n * With multi-tab, when the primary client acknowledges or rejects a mutation,\n * this cache is used by secondary clients to invalidate the local\n * view of the documents that were previously affected by the mutation.\n */\n // PORTING NOTE: Multi-tab only.\n private documentKeysByBatchId = {} as { [batchId: number]: DocumentKeySet };\n\n constructor(\n /**\n * The normalized userId (e.g. null UID => \"\" userId) used to store /\n * retrieve mutations.\n */\n private userId: string,\n private readonly serializer: LocalSerializer,\n private readonly indexManager: IndexManager,\n private readonly referenceDelegate: ReferenceDelegate\n ) {}\n\n /**\n * Creates a new mutation queue for the given user.\n * @param user - The user for which to create a mutation queue.\n * @param serializer - The serializer to use when persisting to IndexedDb.\n */\n static forUser(\n user: User,\n serializer: LocalSerializer,\n indexManager: IndexManager,\n referenceDelegate: ReferenceDelegate\n ): IndexedDbMutationQueue {\n // TODO(mcg): Figure out what constraints there are on userIDs\n // In particular, are there any reserved characters? are empty ids allowed?\n // For the moment store these together in the same mutations table assuming\n // that empty userIDs aren't allowed.\n hardAssert(user.uid !== '', 0xfb83, 'UserID must not be an empty string.');\n const userId = user.isAuthenticated() ? user.uid! : '';\n return new IndexedDbMutationQueue(\n userId,\n serializer,\n indexManager,\n referenceDelegate\n );\n }\n\n checkEmpty(transaction: PersistenceTransaction): PersistencePromise {\n let empty = true;\n const range = IDBKeyRange.bound(\n [this.userId, Number.NEGATIVE_INFINITY],\n [this.userId, Number.POSITIVE_INFINITY]\n );\n return mutationsStore(transaction)\n .iterate(\n { index: DbMutationBatchUserMutationsIndex, range },\n (key, value, control) => {\n empty = false;\n control.done();\n }\n )\n .next(() => empty);\n }\n\n addMutationBatch(\n transaction: PersistenceTransaction,\n localWriteTime: Timestamp,\n baseMutations: Mutation[],\n mutations: Mutation[]\n ): PersistencePromise {\n const documentStore = documentMutationsStore(transaction);\n const mutationStore = mutationsStore(transaction);\n\n // The IndexedDb implementation in Chrome (and Firefox) does not handle\n // compound indices that include auto-generated keys correctly. To ensure\n // that the index entry is added correctly in all browsers, we perform two\n // writes: The first write is used to retrieve the next auto-generated Batch\n // ID, and the second write populates the index and stores the actual\n // mutation batch.\n // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972\n\n // We write an empty object to obtain key\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return mutationStore.add({} as any).next(batchId => {\n hardAssert(\n typeof batchId === 'number',\n 0xbf7b,\n 'Auto-generated key is not a number'\n );\n\n const batch = new MutationBatch(\n batchId,\n localWriteTime,\n baseMutations,\n mutations\n );\n const dbBatch = toDbMutationBatch(this.serializer, this.userId, batch);\n\n const promises: Array> = [];\n let collectionParents = new SortedSet((l, r) =>\n primitiveComparator(l.canonicalString(), r.canonicalString())\n );\n for (const mutation of mutations) {\n const indexKey = newDbDocumentMutationKey(\n this.userId,\n mutation.key.path,\n batchId\n );\n collectionParents = collectionParents.add(mutation.key.path.popLast());\n promises.push(mutationStore.put(dbBatch));\n promises.push(\n documentStore.put(indexKey, DbDocumentMutationPlaceholder)\n );\n }\n\n collectionParents.forEach(parent => {\n promises.push(\n this.indexManager.addToCollectionParentIndex(transaction, parent)\n );\n });\n\n transaction.addOnCommittedListener(() => {\n this.documentKeysByBatchId[batchId] = batch.keys();\n });\n\n return PersistencePromise.waitFor(promises).next(() => batch);\n });\n }\n\n lookupMutationBatch(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise {\n return mutationsStore(transaction)\n .get(batchId)\n .next(dbBatch => {\n if (dbBatch) {\n hardAssert(\n dbBatch.userId === this.userId,\n 0x0030,\n `Unexpected user for mutation batch`,\n {\n userId: dbBatch.userId,\n batchId\n }\n );\n return fromDbMutationBatch(this.serializer, dbBatch);\n }\n return null;\n });\n }\n\n /**\n * Returns the document keys for the mutation batch with the given batchId.\n * For primary clients, this method returns `null` after\n * `removeMutationBatches()` has been called. Secondary clients return a\n * cached result until `removeCachedMutationKeys()` is invoked.\n */\n // PORTING NOTE: Multi-tab only.\n lookupMutationKeys(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise {\n if (this.documentKeysByBatchId[batchId]) {\n return PersistencePromise.resolve(\n this.documentKeysByBatchId[batchId]\n );\n } else {\n return this.lookupMutationBatch(transaction, batchId).next(batch => {\n if (batch) {\n const keys = batch.keys();\n this.documentKeysByBatchId[batchId] = keys;\n return keys;\n } else {\n return null;\n }\n });\n }\n }\n\n getNextMutationBatchAfterBatchId(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise {\n const nextBatchId = batchId + 1;\n\n const range = IDBKeyRange.lowerBound([this.userId, nextBatchId]);\n let foundBatch: MutationBatch | null = null;\n return mutationsStore(transaction)\n .iterate(\n { index: DbMutationBatchUserMutationsIndex, range },\n (key, dbBatch, control) => {\n if (dbBatch.userId === this.userId) {\n hardAssert(\n dbBatch.batchId >= nextBatchId,\n 0xb9a4,\n 'Should have found mutation after `nextBatchId`',\n { nextBatchId }\n );\n foundBatch = fromDbMutationBatch(this.serializer, dbBatch);\n }\n control.done();\n }\n )\n .next(() => foundBatch);\n }\n\n getHighestUnacknowledgedBatchId(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n const range = IDBKeyRange.upperBound([\n this.userId,\n Number.POSITIVE_INFINITY\n ]);\n\n let batchId = BATCHID_UNKNOWN;\n return mutationsStore(transaction)\n .iterate(\n { index: DbMutationBatchUserMutationsIndex, range, reverse: true },\n (key, dbBatch, control) => {\n batchId = dbBatch.batchId;\n control.done();\n }\n )\n .next(() => batchId);\n }\n\n getAllMutationBatches(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n const range = IDBKeyRange.bound(\n [this.userId, BATCHID_UNKNOWN],\n [this.userId, Number.POSITIVE_INFINITY]\n );\n return mutationsStore(transaction)\n .loadAll(DbMutationBatchUserMutationsIndex, range)\n .next(dbBatches =>\n dbBatches.map(dbBatch => fromDbMutationBatch(this.serializer, dbBatch))\n );\n }\n\n getAllMutationBatchesAffectingDocumentKey(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n // Scan the document-mutation index starting with a prefix starting with\n // the given documentKey.\n const indexPrefix = newDbDocumentMutationPrefixForPath(\n this.userId,\n documentKey.path\n );\n const indexStart = IDBKeyRange.lowerBound(indexPrefix);\n\n const results: MutationBatch[] = [];\n return documentMutationsStore(transaction)\n .iterate({ range: indexStart }, (indexKey, _, control) => {\n const [userID, encodedPath, batchId] = indexKey;\n\n // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n const path = decodeResourcePath(encodedPath);\n if (userID !== this.userId || !documentKey.path.isEqual(path)) {\n control.done();\n return;\n }\n // Look up the mutation batch in the store.\n return mutationsStore(transaction)\n .get(batchId)\n .next(mutation => {\n if (!mutation) {\n throw fail(\n 0xf028,\n 'Dangling document-mutation reference found: `indexKey` which points to `batchId`',\n {\n indexKey,\n batchId\n }\n );\n }\n hardAssert(\n mutation.userId === this.userId,\n 0x2907,\n `Unexpected user for mutation batch`,\n {\n userId: mutation.userId,\n batchId\n }\n );\n results.push(fromDbMutationBatch(this.serializer, mutation));\n });\n })\n .next(() => results);\n }\n\n getAllMutationBatchesAffectingDocumentKeys(\n transaction: PersistenceTransaction,\n documentKeys: SortedMap\n ): PersistencePromise {\n let uniqueBatchIDs = new SortedSet(primitiveComparator);\n\n const promises: Array> = [];\n documentKeys.forEach(documentKey => {\n const indexStart = newDbDocumentMutationPrefixForPath(\n this.userId,\n documentKey.path\n );\n const range = IDBKeyRange.lowerBound(indexStart);\n\n const promise = documentMutationsStore(transaction).iterate(\n { range },\n (indexKey, _, control) => {\n const [userID, encodedPath, batchID] = indexKey;\n\n // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n const path = decodeResourcePath(encodedPath);\n if (userID !== this.userId || !documentKey.path.isEqual(path)) {\n control.done();\n return;\n }\n\n uniqueBatchIDs = uniqueBatchIDs.add(batchID);\n }\n );\n\n promises.push(promise);\n });\n\n return PersistencePromise.waitFor(promises).next(() =>\n this.lookupMutationBatches(transaction, uniqueBatchIDs)\n );\n }\n\n getAllMutationBatchesAffectingQuery(\n transaction: PersistenceTransaction,\n query: Query\n ): PersistencePromise {\n debugAssert(\n !isDocumentQuery(query),\n \"Document queries shouldn't go down this path\"\n );\n debugAssert(\n !isCollectionGroupQuery(query),\n 'CollectionGroup queries should be handled in LocalDocumentsView'\n );\n\n const queryPath = query.path;\n const immediateChildrenLength = queryPath.length + 1;\n\n // TODO(mcg): Actually implement a single-collection query\n //\n // This is actually executing an ancestor query, traversing the whole\n // subtree below the collection which can be horrifically inefficient for\n // some structures. The right way to solve this is to implement the full\n // value index, but that's not in the cards in the near future so this is\n // the best we can do for the moment.\n //\n // Since we don't yet index the actual properties in the mutations, our\n // current approach is to just return all mutation batches that affect\n // documents in the collection being queried.\n const indexPrefix = newDbDocumentMutationPrefixForPath(\n this.userId,\n queryPath\n );\n const indexStart = IDBKeyRange.lowerBound(indexPrefix);\n\n // Collect up unique batchIDs encountered during a scan of the index. Use a\n // SortedSet to accumulate batch IDs so they can be traversed in order in a\n // scan of the main table.\n let uniqueBatchIDs = new SortedSet(primitiveComparator);\n return documentMutationsStore(transaction)\n .iterate({ range: indexStart }, (indexKey, _, control) => {\n const [userID, encodedPath, batchID] = indexKey;\n const path = decodeResourcePath(encodedPath);\n if (userID !== this.userId || !queryPath.isPrefixOf(path)) {\n control.done();\n return;\n }\n // Rows with document keys more than one segment longer than the\n // query path can't be matches. For example, a query on 'rooms'\n // can't match the document /rooms/abc/messages/xyx.\n // TODO(mcg): we'll need a different scanner when we implement\n // ancestor queries.\n if (path.length !== immediateChildrenLength) {\n return;\n }\n uniqueBatchIDs = uniqueBatchIDs.add(batchID);\n })\n .next(() => this.lookupMutationBatches(transaction, uniqueBatchIDs));\n }\n\n private lookupMutationBatches(\n transaction: PersistenceTransaction,\n batchIDs: SortedSet\n ): PersistencePromise {\n const results: MutationBatch[] = [];\n const promises: Array> = [];\n // TODO(rockwood): Implement this using iterate.\n batchIDs.forEach(batchId => {\n promises.push(\n mutationsStore(transaction)\n .get(batchId)\n .next(mutation => {\n if (mutation === null) {\n throw fail(\n 0x89ca,\n 'Dangling document-mutation reference found, which points to `batchId`',\n {\n batchId\n }\n );\n }\n hardAssert(\n mutation.userId === this.userId,\n 0x2614,\n `Unexpected user for mutation batch`,\n { userId: mutation.userId, batchId }\n );\n results.push(fromDbMutationBatch(this.serializer, mutation));\n })\n );\n });\n return PersistencePromise.waitFor(promises).next(() => results);\n }\n\n removeMutationBatch(\n transaction: PersistenceTransaction,\n batch: MutationBatch\n ): PersistencePromise {\n return removeMutationBatch(\n (transaction as IndexedDbTransaction).simpleDbTransaction,\n this.userId,\n batch\n ).next(removedDocuments => {\n transaction.addOnCommittedListener(() => {\n this.removeCachedMutationKeys(batch.batchId);\n });\n return PersistencePromise.forEach(\n removedDocuments,\n (key: DocumentKey) => {\n return this.referenceDelegate.markPotentiallyOrphaned(\n transaction,\n key\n );\n }\n );\n });\n }\n\n /**\n * Clears the cached keys for a mutation batch. This method should be\n * called by secondary clients after they process mutation updates.\n *\n * Note that this method does not have to be called from primary clients as\n * the corresponding cache entries are cleared when an acknowledged or\n * rejected batch is removed from the mutation queue.\n */\n // PORTING NOTE: Multi-tab only\n removeCachedMutationKeys(batchId: BatchId): void {\n delete this.documentKeysByBatchId[batchId];\n }\n\n performConsistencyCheck(\n txn: PersistenceTransaction\n ): PersistencePromise {\n return this.checkEmpty(txn).next(empty => {\n if (!empty) {\n return PersistencePromise.resolve();\n }\n\n // Verify that there are no entries in the documentMutations index if\n // the queue is empty.\n const startRange = IDBKeyRange.lowerBound(\n newDbDocumentMutationPrefixForUser(this.userId)\n );\n const danglingMutationReferences: ResourcePath[] = [];\n return documentMutationsStore(txn)\n .iterate({ range: startRange }, (key, _, control) => {\n const userID = key[0];\n if (userID !== this.userId) {\n control.done();\n return;\n } else {\n const path = decodeResourcePath(key[1]);\n danglingMutationReferences.push(path);\n }\n })\n .next(() => {\n hardAssert(\n danglingMutationReferences.length === 0,\n 0xdd90,\n 'Document leak -- detected dangling mutation references when queue is empty.',\n {\n danglingKeys: danglingMutationReferences.map(p =>\n p.canonicalString()\n )\n }\n );\n });\n });\n }\n\n containsKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return mutationQueueContainsKey(txn, this.userId, key);\n }\n\n // PORTING NOTE: Multi-tab only (state is held in memory in other clients).\n /** Returns the mutation queue's metadata from IndexedDb. */\n private getMutationQueueMetadata(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return mutationQueuesStore(transaction)\n .get(this.userId)\n .next((metadata: DbMutationQueue | null) => {\n return (\n metadata || {\n userId: this.userId,\n lastAcknowledgedBatchId: BATCHID_UNKNOWN,\n lastStreamToken: ''\n }\n );\n });\n }\n}\n\n/**\n * @returns true if the mutation queue for the given user contains a pending\n * mutation for the given key.\n */\nfunction mutationQueueContainsKey(\n txn: PersistenceTransaction,\n userId: string,\n key: DocumentKey\n): PersistencePromise {\n const indexKey = newDbDocumentMutationPrefixForPath(userId, key.path);\n const encodedPath = indexKey[1];\n const startRange = IDBKeyRange.lowerBound(indexKey);\n let containsKey = false;\n return documentMutationsStore(txn)\n .iterate({ range: startRange, keysOnly: true }, (key, value, control) => {\n const [userID, keyPath, /*batchID*/ _] = key;\n if (userID === userId && keyPath === encodedPath) {\n containsKey = true;\n }\n control.done();\n })\n .next(() => containsKey);\n}\n\n/** Returns true if any mutation queue contains the given document. */\nexport function mutationQueuesContainKey(\n txn: PersistenceTransaction,\n docKey: DocumentKey\n): PersistencePromise {\n let found = false;\n return mutationQueuesStore(txn)\n .iterateSerial(userId => {\n return mutationQueueContainsKey(txn, userId, docKey).next(containsKey => {\n if (containsKey) {\n found = true;\n }\n return PersistencePromise.resolve(!containsKey);\n });\n })\n .next(() => found);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutations object store.\n */\nfunction mutationsStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbMutationBatchStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction documentMutationsStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbDocumentMutationStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction mutationQueuesStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbMutationQueueStore\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TargetId } from './types';\n\n/** Offset to ensure non-overlapping target ids. */\nconst OFFSET = 2;\n\n/**\n * Generates monotonically increasing target IDs for sending targets to the\n * watch stream.\n *\n * The client constructs two generators, one for the target cache, and one for\n * for the sync engine (to generate limbo documents targets). These\n * generators produce non-overlapping IDs (by using even and odd IDs\n * respectively).\n *\n * By separating the target ID space, the query cache can generate target IDs\n * that persist across client restarts, while sync engine can independently\n * generate in-memory target IDs that are transient and can be reused after a\n * restart.\n */\nexport class TargetIdGenerator {\n constructor(private lastId: number) {}\n\n next(): TargetId {\n this.lastId += OFFSET;\n return this.lastId;\n }\n\n static forTargetCache(): TargetIdGenerator {\n // The target cache generator must return '2' in its first call to `next()`\n // as there is no differentiation in the protocol layer between an unset\n // number and the number '0'. If we were to sent a target with target ID\n // '0', the backend would consider it unset and replace it with its own ID.\n return new TargetIdGenerator(2 - OFFSET);\n }\n\n static forSyncEngine(): TargetIdGenerator {\n // Sync engine assigns target IDs for limbo document detection.\n return new TargetIdGenerator(1 - OFFSET);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { canonifyTarget, Target, targetEquals } from '../core/target';\nimport { TargetIdGenerator } from '../core/target_id_generator';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { DocumentKeySet, documentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { hardAssert } from '../util/assert';\nimport { immediateSuccessor } from '../util/misc';\n\nimport {\n decodeResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { IndexedDbLruDelegate } from './indexeddb_lru_delegate';\nimport { DbTarget, DbTargetDocument, DbTargetGlobal } from './indexeddb_schema';\nimport {\n DbTargetDocumentDocumentTargetsIndex,\n DbTargetDocumentKey,\n DbTargetDocumentStore,\n DbTargetGlobalKey,\n DbTargetGlobalStore,\n DbTargetKey,\n DbTargetQueryTargetsIndexName,\n DbTargetStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport { fromDbTarget, LocalSerializer, toDbTarget } from './local_serializer';\nimport { ActiveTargets } from './lru_garbage_collector';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\nimport { TargetCache } from './target_cache';\nimport { TargetData } from './target_data';\n\nexport class IndexedDbTargetCache implements TargetCache {\n constructor(\n private readonly referenceDelegate: IndexedDbLruDelegate,\n private serializer: LocalSerializer\n ) {}\n\n // PORTING NOTE: We don't cache global metadata for the target cache, since\n // some of it (in particular `highestTargetId`) can be modified by secondary\n // tabs. We could perhaps be more granular (and e.g. still cache\n // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go\n // to IndexedDb whenever we need to read metadata. We can revisit if it turns\n // out to have a meaningful performance impact.\n\n allocateTargetId(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(metadata => {\n const targetIdGenerator = new TargetIdGenerator(metadata.highestTargetId);\n metadata.highestTargetId = targetIdGenerator.next();\n return this.saveMetadata(transaction, metadata).next(\n () => metadata.highestTargetId\n );\n });\n }\n\n getLastRemoteSnapshotVersion(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(metadata => {\n return SnapshotVersion.fromTimestamp(\n new Timestamp(\n metadata.lastRemoteSnapshotVersion.seconds,\n metadata.lastRemoteSnapshotVersion.nanoseconds\n )\n );\n });\n }\n\n getHighestSequenceNumber(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(\n targetGlobal => targetGlobal.highestListenSequenceNumber\n );\n }\n\n setTargetsMetadata(\n transaction: PersistenceTransaction,\n highestListenSequenceNumber: number,\n lastRemoteSnapshotVersion?: SnapshotVersion\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(metadata => {\n metadata.highestListenSequenceNumber = highestListenSequenceNumber;\n if (lastRemoteSnapshotVersion) {\n metadata.lastRemoteSnapshotVersion =\n lastRemoteSnapshotVersion.toTimestamp();\n }\n if (highestListenSequenceNumber > metadata.highestListenSequenceNumber) {\n metadata.highestListenSequenceNumber = highestListenSequenceNumber;\n }\n return this.saveMetadata(transaction, metadata);\n });\n }\n\n addTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n return this.saveTargetData(transaction, targetData).next(() => {\n return this.retrieveMetadata(transaction).next(metadata => {\n metadata.targetCount += 1;\n this.updateMetadataFromTargetData(targetData, metadata);\n return this.saveMetadata(transaction, metadata);\n });\n });\n }\n\n updateTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n return this.saveTargetData(transaction, targetData);\n }\n\n removeTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n return this.removeMatchingKeysForTargetId(transaction, targetData.targetId)\n .next(() => targetsStore(transaction).delete(targetData.targetId))\n .next(() => this.retrieveMetadata(transaction))\n .next(metadata => {\n hardAssert(\n metadata.targetCount > 0,\n 0x1f81,\n 'Removing from an empty target cache'\n );\n metadata.targetCount -= 1;\n return this.saveMetadata(transaction, metadata);\n });\n }\n\n /**\n * Drops any targets with sequence number less than or equal to the upper bound, excepting those\n * present in `activeTargetIds`. Document associations for the removed targets are also removed.\n * Returns the number of targets removed.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n let count = 0;\n const promises: Array> = [];\n return targetsStore(txn)\n .iterate((key, value) => {\n const targetData = fromDbTarget(value);\n if (\n targetData.sequenceNumber <= upperBound &&\n activeTargetIds.get(targetData.targetId) === null\n ) {\n count++;\n promises.push(this.removeTargetData(txn, targetData));\n }\n })\n .next(() => PersistencePromise.waitFor(promises))\n .next(() => count);\n }\n\n /**\n * Call provided function with each `TargetData` that we have cached.\n */\n forEachTarget(\n txn: PersistenceTransaction,\n f: (q: TargetData) => void\n ): PersistencePromise {\n return targetsStore(txn).iterate((key, value) => {\n const targetData = fromDbTarget(value);\n f(targetData);\n });\n }\n\n private retrieveMetadata(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return globalTargetStore(transaction)\n .get(DbTargetGlobalKey)\n .next(metadata => {\n hardAssert(metadata !== null, 0x0b48, 'Missing metadata row.');\n return metadata;\n });\n }\n\n private saveMetadata(\n transaction: PersistenceTransaction,\n metadata: DbTargetGlobal\n ): PersistencePromise {\n return globalTargetStore(transaction).put(DbTargetGlobalKey, metadata);\n }\n\n private saveTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n return targetsStore(transaction).put(\n toDbTarget(this.serializer, targetData)\n );\n }\n\n /**\n * In-place updates the provided metadata to account for values in the given\n * TargetData. Saving is done separately. Returns true if there were any\n * changes to the metadata.\n */\n private updateMetadataFromTargetData(\n targetData: TargetData,\n metadata: DbTargetGlobal\n ): boolean {\n let updated = false;\n if (targetData.targetId > metadata.highestTargetId) {\n metadata.highestTargetId = targetData.targetId;\n updated = true;\n }\n\n if (targetData.sequenceNumber > metadata.highestListenSequenceNumber) {\n metadata.highestListenSequenceNumber = targetData.sequenceNumber;\n updated = true;\n }\n return updated;\n }\n\n getTargetCount(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(\n metadata => metadata.targetCount\n );\n }\n\n getTargetData(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise {\n // Iterating by the canonicalId may yield more than one result because\n // canonicalId values are not required to be unique per target. This query\n // depends on the queryTargets index to be efficient.\n const canonicalId = canonifyTarget(target);\n const range = IDBKeyRange.bound(\n [canonicalId, Number.NEGATIVE_INFINITY],\n [canonicalId, Number.POSITIVE_INFINITY]\n );\n let result: TargetData | null = null;\n return targetsStore(transaction)\n .iterate(\n { range, index: DbTargetQueryTargetsIndexName },\n (key, value, control) => {\n const found = fromDbTarget(value);\n // After finding a potential match, check that the target is\n // actually equal to the requested target.\n if (targetEquals(target, found.target)) {\n result = found;\n control.done();\n }\n }\n )\n .next(() => result);\n }\n\n addMatchingKeys(\n txn: PersistenceTransaction,\n keys: DocumentKeySet,\n targetId: TargetId\n ): PersistencePromise {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n const promises: Array> = [];\n const store = documentTargetStore(txn);\n keys.forEach(key => {\n const path = encodeResourcePath(key.path);\n promises.push(store.put({ targetId, path }));\n promises.push(this.referenceDelegate.addReference(txn, targetId, key));\n });\n return PersistencePromise.waitFor(promises);\n }\n\n removeMatchingKeys(\n txn: PersistenceTransaction,\n keys: DocumentKeySet,\n targetId: TargetId\n ): PersistencePromise {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n const store = documentTargetStore(txn);\n return PersistencePromise.forEach(keys, (key: DocumentKey) => {\n const path = encodeResourcePath(key.path);\n return PersistencePromise.waitFor([\n store.delete([targetId, path]),\n this.referenceDelegate.removeReference(txn, targetId, key)\n ]);\n });\n }\n\n removeMatchingKeysForTargetId(\n txn: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise {\n const store = documentTargetStore(txn);\n const range = IDBKeyRange.bound(\n [targetId],\n [targetId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n return store.delete(range);\n }\n\n getMatchingKeysForTargetId(\n txn: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise {\n const range = IDBKeyRange.bound(\n [targetId],\n [targetId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n const store = documentTargetStore(txn);\n let result = documentKeySet();\n\n return store\n .iterate({ range, keysOnly: true }, (key, _, control) => {\n const path = decodeResourcePath(key[1]);\n const docKey = new DocumentKey(path);\n result = result.add(docKey);\n })\n .next(() => result);\n }\n\n containsKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n const path = encodeResourcePath(key.path);\n const range = IDBKeyRange.bound(\n [path],\n [immediateSuccessor(path)],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n let count = 0;\n return documentTargetStore(txn!)\n .iterate(\n {\n index: DbTargetDocumentDocumentTargetsIndex,\n keysOnly: true,\n range\n },\n ([targetId, path], _, control) => {\n // Having a sentinel row for a document does not count as containing that document;\n // For the target cache, containing the document means the document is part of some\n // target.\n if (targetId !== 0) {\n count++;\n control.done();\n }\n }\n )\n .next(() => count > 0);\n }\n\n /**\n * Looks up a TargetData entry by target ID.\n *\n * @param targetId - The target ID of the TargetData entry to look up.\n * @returns The cached TargetData entry, or null if the cache has no entry for\n * the target.\n */\n // PORTING NOTE: Multi-tab only.\n getTargetDataForTarget(\n transaction: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise {\n return targetsStore(transaction)\n .get(targetId)\n .next(found => {\n if (found) {\n return fromDbTarget(found);\n } else {\n return null;\n }\n });\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the queries object store.\n */\nfunction targetsStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbTargetStore);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the target globals object store.\n */\nfunction globalTargetStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbTargetGlobalStore);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document target object store.\n */\nexport function documentTargetStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbTargetDocumentStore\n );\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequenceNumber, 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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\nimport { ListenSequence } from '../core/listen_sequence';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { DocumentKey } from '../model/document_key';\n\nimport {\n decodeResourcePath,\n EncodedResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { IndexedDbLruDelegate } from './indexeddb_lru_delegate';\nimport { mutationQueuesContainKey } from './indexeddb_mutation_queue';\nimport { DbTargetDocument } from './indexeddb_schema';\nimport { DbTargetDocumentDocumentTargetsIndex } from './indexeddb_sentinels';\nimport {\n documentTargetStore,\n IndexedDbTargetCache\n} from './indexeddb_target_cache';\nimport {\n ActiveTargets,\n LruGarbageCollector,\n LruParams\n} from './lru_garbage_collector';\nimport { newLruGarbageCollector } from './lru_garbage_collector_impl';\nimport { Persistence } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { TargetData } from './target_data';\n\n/** Provides LRU functionality for IndexedDB persistence. */\nexport class IndexedDbLruDelegateImpl implements IndexedDbLruDelegate {\n readonly garbageCollector: LruGarbageCollector;\n\n constructor(private readonly db: Persistence, params: LruParams) {\n this.garbageCollector = newLruGarbageCollector(this, params);\n }\n\n getSequenceNumberCount(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const docCountPromise = this.orphanedDocumentCount(txn);\n const targetCountPromise = this.db.getTargetCache().getTargetCount(txn);\n return targetCountPromise.next(targetCount =>\n docCountPromise.next(docCount => targetCount + docCount)\n );\n }\n\n private orphanedDocumentCount(\n txn: PersistenceTransaction\n ): PersistencePromise {\n let orphanedCount = 0;\n return this.forEachOrphanedDocumentSequenceNumber(txn, _ => {\n orphanedCount++;\n }).next(() => orphanedCount);\n }\n\n forEachTarget(\n txn: PersistenceTransaction,\n f: (q: TargetData) => void\n ): PersistencePromise {\n return this.db.getTargetCache().forEachTarget(txn, f);\n }\n\n forEachOrphanedDocumentSequenceNumber(\n txn: PersistenceTransaction,\n f: (sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise {\n return this.forEachOrphanedDocument(txn, (docKey, sequenceNumber) =>\n f(sequenceNumber)\n );\n }\n\n addReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise {\n return writeSentinelKey(txn, key);\n }\n\n removeReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise {\n return writeSentinelKey(txn, key);\n }\n\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n return (this.db.getTargetCache() as IndexedDbTargetCache).removeTargets(\n txn,\n upperBound,\n activeTargetIds\n );\n }\n\n markPotentiallyOrphaned(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return writeSentinelKey(txn, key);\n }\n\n /**\n * Returns true if anything would prevent this document from being garbage\n * collected, given that the document in question is not present in any\n * targets and has a sequence number less than or equal to the upper bound for\n * the collection run.\n */\n private isPinned(\n txn: PersistenceTransaction,\n docKey: DocumentKey\n ): PersistencePromise {\n return mutationQueuesContainKey(txn, docKey);\n }\n\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise {\n const documentCache = this.db.getRemoteDocumentCache();\n const changeBuffer = documentCache.newChangeBuffer();\n\n const promises: Array> = [];\n let documentCount = 0;\n\n const iteration = this.forEachOrphanedDocument(\n txn,\n (docKey, sequenceNumber) => {\n if (sequenceNumber <= upperBound) {\n const p = this.isPinned(txn, docKey).next(isPinned => {\n if (!isPinned) {\n documentCount++;\n // Our size accounting requires us to read all documents before\n // removing them.\n return changeBuffer.getEntry(txn, docKey).next(() => {\n changeBuffer.removeEntry(docKey, SnapshotVersion.min());\n return documentTargetStore(txn).delete(sentinelKey(docKey));\n });\n }\n });\n promises.push(p);\n }\n }\n );\n\n return iteration\n .next(() => PersistencePromise.waitFor(promises))\n .next(() => changeBuffer.apply(txn))\n .next(() => documentCount);\n }\n\n removeTarget(\n txn: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n const updated = targetData.withSequenceNumber(txn.currentSequenceNumber);\n return this.db.getTargetCache().updateTargetData(txn, updated);\n }\n\n updateLimboDocument(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return writeSentinelKey(txn, key);\n }\n\n /**\n * Call provided function for each document in the cache that is 'orphaned'. Orphaned\n * means not a part of any target, so the only entry in the target-document index for\n * that document will be the sentinel row (targetId 0), which will also have the sequence\n * number for the last time the document was accessed.\n */\n private forEachOrphanedDocument(\n txn: PersistenceTransaction,\n f: (docKey: DocumentKey, sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise {\n const store = documentTargetStore(txn);\n let nextToReport: ListenSequenceNumber = ListenSequence.INVALID;\n let nextPath: EncodedResourcePath;\n return store\n .iterate(\n {\n index: DbTargetDocumentDocumentTargetsIndex\n },\n ([targetId, docKey], { path, sequenceNumber }) => {\n if (targetId === 0) {\n // if nextToReport is valid, report it, this is a new key so the\n // last one must not be a member of any targets.\n if (nextToReport !== ListenSequence.INVALID) {\n f(new DocumentKey(decodeResourcePath(nextPath)), nextToReport);\n }\n // set nextToReport to be this sequence number. It's the next one we\n // might report, if we don't find any targets for this document.\n // Note that the sequence number must be defined when the targetId\n // is 0.\n nextToReport = sequenceNumber!;\n nextPath = path;\n } else {\n // set nextToReport to be invalid, we know we don't need to report\n // this one since we found a target for it.\n nextToReport = ListenSequence.INVALID;\n }\n }\n )\n .next(() => {\n // Since we report sequence numbers after getting to the next key, we\n // need to check if the last key we iterated over was an orphaned\n // document and report it.\n if (nextToReport !== ListenSequence.INVALID) {\n f(new DocumentKey(decodeResourcePath(nextPath)), nextToReport);\n }\n });\n }\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise {\n return this.db.getRemoteDocumentCache().getSize(txn);\n }\n}\n\nfunction sentinelKey(key: DocumentKey): [TargetId, EncodedResourcePath] {\n return [0, encodeResourcePath(key.path)];\n}\n\n/**\n * @returns A value suitable for writing a sentinel row in the target-document\n * store.\n */\nfunction sentinelRow(\n key: DocumentKey,\n sequenceNumber: ListenSequenceNumber\n): DbTargetDocument {\n return { targetId: 0, path: encodeResourcePath(key.path), sequenceNumber };\n}\n\nfunction writeSentinelKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n): PersistencePromise {\n return documentTargetStore(txn).put(\n sentinelRow(key, txn.currentSequenceNumber)\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { DocumentKeySet, MutableDocumentMap } from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { debugAssert } from '../util/assert';\nimport { ObjectMap } from '../util/obj_map';\n\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\n/**\n * An in-memory buffer of entries to be written to a RemoteDocumentCache.\n * It can be used to batch up a set of changes to be written to the cache, but\n * additionally supports reading entries back with the `getEntry()` method,\n * falling back to the underlying RemoteDocumentCache if no entry is\n * buffered.\n *\n * Entries added to the cache *must* be read first. This is to facilitate\n * calculating the size delta of the pending changes.\n *\n * PORTING NOTE: This class was implemented then removed from other platforms.\n * If byte-counting ends up being needed on the other platforms, consider\n * porting this class as part of that implementation work.\n */\nexport abstract class RemoteDocumentChangeBuffer {\n // A mapping of document key to the new cache entry that should be written.\n protected changes: ObjectMap = 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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Query, queryMatches } from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport {\n DocumentKeySet,\n DocumentSizeEntries,\n MutableDocumentMap,\n mutableDocumentMap,\n OverlayMap\n} from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { IndexOffset } from '../model/field_index';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { IndexManager } from './index_manager';\nimport { dbDocumentSize } from './indexeddb_mutation_batch_impl';\nimport { DbRemoteDocument, DbRemoteDocumentGlobal } from './indexeddb_schema';\nimport {\n DbRemoteDocumentCollectionGroupIndex,\n DbRemoteDocumentDocumentKeyIndex,\n DbRemoteDocumentGlobalKey,\n DbRemoteDocumentGlobalStore,\n DbRemoteDocumentKey,\n DbRemoteDocumentStore,\n DbTimestampKey\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n fromDbRemoteDocument,\n LocalSerializer,\n toDbRemoteDocument,\n toDbTimestampKey\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { QueryContext } from './query_context';\nimport { RemoteDocumentCache } from './remote_document_cache';\nimport { RemoteDocumentChangeBuffer } from './remote_document_change_buffer';\nimport { SimpleDbStore } from './simple_db';\n\nexport interface DocumentSizeEntry {\n document: MutableDocument;\n size: number;\n}\n\nexport interface IndexedDbRemoteDocumentCache extends RemoteDocumentCache {\n // The IndexedDbRemoteDocumentCache doesn't implement any methods on top\n // of RemoteDocumentCache. This class exists for consistency.\n}\n\n/**\n * The RemoteDocumentCache for IndexedDb. To construct, invoke\n * `newIndexedDbRemoteDocumentCache()`.\n */\nclass IndexedDbRemoteDocumentCacheImpl implements IndexedDbRemoteDocumentCache {\n indexManager!: IndexManager;\n\n constructor(readonly serializer: LocalSerializer) {}\n\n setIndexManager(indexManager: IndexManager): void {\n this.indexManager = indexManager;\n }\n\n /**\n * Adds the supplied entries to the cache.\n *\n * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n */\n addEntry(\n transaction: PersistenceTransaction,\n key: DocumentKey,\n doc: DbRemoteDocument\n ): PersistencePromise {\n const documentStore = remoteDocumentsStore(transaction);\n return documentStore.put(doc);\n }\n\n /**\n * Removes a document from the cache.\n *\n * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n */\n removeEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey,\n readTime: SnapshotVersion\n ): PersistencePromise {\n const store = remoteDocumentsStore(transaction);\n return store.delete(dbReadTimeKey(documentKey, readTime));\n }\n\n /**\n * Updates the current cache size.\n *\n * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the\n * cache's metadata.\n */\n updateMetadata(\n transaction: PersistenceTransaction,\n sizeDelta: number\n ): PersistencePromise {\n return this.getMetadata(transaction).next(metadata => {\n metadata.byteSize += sizeDelta;\n return this.setMetadata(transaction, metadata);\n });\n }\n\n getEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n let doc = MutableDocument.newInvalidDocument(documentKey);\n return remoteDocumentsStore(transaction)\n .iterate(\n {\n index: DbRemoteDocumentDocumentKeyIndex,\n range: IDBKeyRange.only(dbKey(documentKey))\n },\n (_, dbRemoteDoc) => {\n doc = this.maybeDecodeDocument(documentKey, dbRemoteDoc);\n }\n )\n .next(() => doc);\n }\n\n /**\n * Looks up an entry in the cache.\n *\n * @param documentKey - The key of the entry to look up.\n * @returns The cached document entry and its size.\n */\n getSizedEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n let result = {\n size: 0,\n document: MutableDocument.newInvalidDocument(documentKey)\n };\n return remoteDocumentsStore(transaction)\n .iterate(\n {\n index: DbRemoteDocumentDocumentKeyIndex,\n range: IDBKeyRange.only(dbKey(documentKey))\n },\n (_, dbRemoteDoc) => {\n result = {\n document: this.maybeDecodeDocument(documentKey, dbRemoteDoc),\n size: dbDocumentSize(dbRemoteDoc)\n };\n }\n )\n .next(() => result);\n }\n\n getEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise {\n let results = mutableDocumentMap();\n return this.forEachDbEntry(\n transaction,\n documentKeys,\n (key, dbRemoteDoc) => {\n const doc = this.maybeDecodeDocument(key, dbRemoteDoc);\n results = results.insert(key, doc);\n }\n ).next(() => results);\n }\n\n /**\n * Looks up several entries in the cache.\n *\n * @param documentKeys - The set of keys entries to look up.\n * @returns A map of documents indexed by key and a map of sizes indexed by\n * key (zero if the document does not exist).\n */\n getSizedEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise {\n let results = mutableDocumentMap();\n let sizeMap = new SortedMap(DocumentKey.comparator);\n return this.forEachDbEntry(\n transaction,\n documentKeys,\n (key, dbRemoteDoc) => {\n const doc = this.maybeDecodeDocument(key, dbRemoteDoc);\n results = results.insert(key, doc);\n sizeMap = sizeMap.insert(key, dbDocumentSize(dbRemoteDoc));\n }\n ).next(() => {\n return { documents: results, sizeMap };\n });\n }\n\n private forEachDbEntry(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet,\n callback: (key: DocumentKey, doc: DbRemoteDocument | null) => void\n ): PersistencePromise {\n if (documentKeys.isEmpty()) {\n return PersistencePromise.resolve();\n }\n\n let sortedKeys = new SortedSet(dbKeyComparator);\n documentKeys.forEach(e => (sortedKeys = sortedKeys.add(e)));\n const range = IDBKeyRange.bound(\n dbKey(sortedKeys.first()!),\n dbKey(sortedKeys.last()!)\n );\n const keyIter = sortedKeys.getIterator();\n let nextKey: DocumentKey | null = keyIter.getNext();\n\n return remoteDocumentsStore(transaction)\n .iterate(\n { index: DbRemoteDocumentDocumentKeyIndex, range },\n (_, dbRemoteDoc, control) => {\n const potentialKey = DocumentKey.fromSegments([\n ...dbRemoteDoc.prefixPath,\n dbRemoteDoc.collectionGroup,\n dbRemoteDoc.documentId\n ]);\n\n // Go through keys not found in cache.\n while (nextKey && dbKeyComparator(nextKey!, potentialKey) < 0) {\n callback(nextKey!, null);\n nextKey = keyIter.getNext();\n }\n\n if (nextKey && nextKey!.isEqual(potentialKey)) {\n // Key found in cache.\n callback(nextKey!, dbRemoteDoc);\n nextKey = keyIter.hasNext() ? keyIter.getNext() : null;\n }\n\n // Skip to the next key (if there is one).\n if (nextKey) {\n control.skip(dbKey(nextKey));\n } else {\n control.done();\n }\n }\n )\n .next(() => {\n // The rest of the keys are not in the cache. One case where `iterate`\n // above won't go through them is when the cache is empty.\n while (nextKey) {\n callback(nextKey!, null);\n nextKey = keyIter.hasNext() ? keyIter.getNext() : null;\n }\n });\n }\n\n getDocumentsMatchingQuery(\n transaction: PersistenceTransaction,\n query: Query,\n offset: IndexOffset,\n mutatedDocs: OverlayMap,\n context?: QueryContext\n ): PersistencePromise {\n const collection = query.path;\n const startKey = [\n collection.popLast().toArray(),\n collection.lastSegment(),\n toDbTimestampKey(offset.readTime),\n offset.documentKey.path.isEmpty()\n ? ''\n : offset.documentKey.path.lastSegment()\n ];\n const endKey: DbRemoteDocumentKey = [\n collection.popLast().toArray(),\n collection.lastSegment(),\n [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n ''\n ];\n\n return remoteDocumentsStore(transaction)\n .loadAll(IDBKeyRange.bound(startKey, endKey, true))\n .next(dbRemoteDocs => {\n context?.incrementDocumentReadCount(dbRemoteDocs.length);\n let results = mutableDocumentMap();\n for (const dbRemoteDoc of dbRemoteDocs) {\n const document = this.maybeDecodeDocument(\n DocumentKey.fromSegments(\n dbRemoteDoc.prefixPath.concat(\n dbRemoteDoc.collectionGroup,\n dbRemoteDoc.documentId\n )\n ),\n dbRemoteDoc\n );\n if (\n document.isFoundDocument() &&\n (queryMatches(query, document) || mutatedDocs.has(document.key))\n ) {\n // Either the document matches the given query, or it is mutated.\n results = results.insert(document.key, document);\n }\n }\n return results;\n });\n }\n\n getAllFromCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n offset: IndexOffset,\n limit: number\n ): PersistencePromise {\n debugAssert(limit > 0, 'Limit should be at least 1');\n let results = mutableDocumentMap();\n\n const startKey = dbCollectionGroupKey(collectionGroup, offset);\n const endKey = dbCollectionGroupKey(collectionGroup, IndexOffset.max());\n return remoteDocumentsStore(transaction)\n .iterate(\n {\n index: DbRemoteDocumentCollectionGroupIndex,\n range: IDBKeyRange.bound(startKey, endKey, true)\n },\n (_, dbRemoteDoc, control) => {\n const document = this.maybeDecodeDocument(\n DocumentKey.fromSegments(\n dbRemoteDoc.prefixPath.concat(\n dbRemoteDoc.collectionGroup,\n dbRemoteDoc.documentId\n )\n ),\n dbRemoteDoc\n );\n results = results.insert(document.key, document);\n if (results.size === limit) {\n control.done();\n }\n }\n )\n .next(() => results);\n }\n\n newChangeBuffer(options?: {\n trackRemovals: boolean;\n }): RemoteDocumentChangeBuffer {\n return new IndexedDbRemoteDocumentChangeBuffer(\n this,\n !!options && options.trackRemovals\n );\n }\n\n getSize(txn: PersistenceTransaction): PersistencePromise {\n return this.getMetadata(txn).next(metadata => metadata.byteSize);\n }\n\n private getMetadata(\n txn: PersistenceTransaction\n ): PersistencePromise {\n return documentGlobalStore(txn)\n .get(DbRemoteDocumentGlobalKey)\n .next(metadata => {\n hardAssert(!!metadata, 0x4e35, 'Missing document cache metadata');\n return metadata!;\n });\n }\n\n private setMetadata(\n txn: PersistenceTransaction,\n metadata: DbRemoteDocumentGlobal\n ): PersistencePromise {\n return documentGlobalStore(txn).put(DbRemoteDocumentGlobalKey, metadata);\n }\n\n /**\n * Decodes `dbRemoteDoc` and returns the document (or an invalid document if\n * the document corresponds to the format used for sentinel deletes).\n */\n private maybeDecodeDocument(\n documentKey: DocumentKey,\n dbRemoteDoc: DbRemoteDocument | null\n ): MutableDocument {\n if (dbRemoteDoc) {\n const doc = fromDbRemoteDocument(this.serializer, dbRemoteDoc);\n // Whether the document is a sentinel removal and should only be used in the\n // `getNewDocumentChanges()`\n const isSentinelRemoval =\n doc.isNoDocument() && doc.version.isEqual(SnapshotVersion.min());\n if (!isSentinelRemoval) {\n return doc;\n }\n }\n return MutableDocument.newInvalidDocument(documentKey);\n }\n}\n\n/** Creates a new IndexedDbRemoteDocumentCache. */\nexport function newIndexedDbRemoteDocumentCache(\n serializer: LocalSerializer\n): IndexedDbRemoteDocumentCache {\n return new IndexedDbRemoteDocumentCacheImpl(serializer);\n}\n\n/**\n * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache.\n *\n * Unlike the MemoryRemoteDocumentChangeBuffer, the IndexedDb implementation computes the size\n * delta for all submitted changes. This avoids having to re-read all documents from IndexedDb\n * when we apply the changes.\n */\nclass IndexedDbRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer {\n // A map of document sizes and read times prior to applying the changes in\n // this buffer.\n protected documentStates: ObjectMap<\n DocumentKey,\n { size: number; readTime: SnapshotVersion }\n > = new ObjectMap(\n key => key.toString(),\n (l, r) => l.isEqual(r)\n );\n\n /**\n * @param documentCache - The IndexedDbRemoteDocumentCache to apply the changes to.\n * @param trackRemovals - Whether to create sentinel deletes that can be tracked by\n * `getNewDocumentChanges()`.\n */\n constructor(\n private readonly documentCache: IndexedDbRemoteDocumentCacheImpl,\n private readonly trackRemovals: boolean\n ) {\n super();\n }\n\n protected applyChanges(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n const promises: Array> = [];\n\n let sizeDelta = 0;\n\n let collectionParents = new SortedSet((l, r) =>\n primitiveComparator(l.canonicalString(), r.canonicalString())\n );\n\n this.changes.forEach((key, documentChange) => {\n const previousDoc = this.documentStates.get(key);\n debugAssert(\n previousDoc !== undefined,\n `Cannot modify a document that wasn't read (for ${key})`\n );\n promises.push(\n this.documentCache.removeEntry(transaction, key, previousDoc.readTime)\n );\n if (documentChange.isValidDocument()) {\n debugAssert(\n !documentChange.readTime.isEqual(SnapshotVersion.min()),\n 'Cannot add a document with a read time of zero'\n );\n const doc = toDbRemoteDocument(\n this.documentCache.serializer,\n documentChange\n );\n collectionParents = collectionParents.add(key.path.popLast());\n\n const size = dbDocumentSize(doc);\n sizeDelta += size - previousDoc.size;\n promises.push(this.documentCache.addEntry(transaction, key, doc));\n } else {\n sizeDelta -= previousDoc.size;\n if (this.trackRemovals) {\n // In order to track removals, we store a \"sentinel delete\" in the\n // RemoteDocumentCache. This entry is represented by a NoDocument\n // with a version of 0 and ignored by `maybeDecodeDocument()` but\n // preserved in `getNewDocumentChanges()`.\n const deletedDoc = toDbRemoteDocument(\n this.documentCache.serializer,\n documentChange.convertToNoDocument(SnapshotVersion.min())\n );\n promises.push(\n this.documentCache.addEntry(transaction, key, deletedDoc)\n );\n }\n }\n });\n\n collectionParents.forEach(parent => {\n promises.push(\n this.documentCache.indexManager.addToCollectionParentIndex(\n transaction,\n parent\n )\n );\n });\n\n promises.push(this.documentCache.updateMetadata(transaction, sizeDelta));\n\n return PersistencePromise.waitFor(promises);\n }\n\n protected getFromCache(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n // Record the size of everything we load from the cache so we can compute a delta later.\n return this.documentCache\n .getSizedEntry(transaction, documentKey)\n .next(getResult => {\n this.documentStates.set(documentKey, {\n size: getResult.size,\n readTime: getResult.document.readTime\n });\n return getResult.document;\n });\n }\n\n protected getAllFromCache(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise {\n // Record the size of everything we load from the cache so we can compute\n // a delta later.\n return this.documentCache\n .getSizedEntries(transaction, documentKeys)\n .next(({ documents, sizeMap }) => {\n // Note: `getAllFromCache` returns two maps instead of a single map from\n // keys to `DocumentSizeEntry`s. This is to allow returning the\n // `MutableDocumentMap` directly, without a conversion.\n sizeMap.forEach((documentKey, size) => {\n this.documentStates.set(documentKey, {\n size,\n readTime: documents.get(documentKey)!.readTime\n });\n });\n return documents;\n });\n }\n}\n\nfunction documentGlobalStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbRemoteDocumentGlobalStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the remoteDocuments object store.\n */\nfunction remoteDocumentsStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbRemoteDocumentStore\n );\n}\n\n/**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentKeyIndex` index.\n */\nfunction dbKey(documentKey: DocumentKey): [string[], string, string] {\n const path = documentKey.path.toArray();\n return [\n /* prefix path */ path.slice(0, path.length - 2),\n /* collection id */ path[path.length - 2],\n /* document id */ path[path.length - 1]\n ];\n}\n\n/**\n * Returns a key that can be used for document lookups via the primary key of\n * the DbRemoteDocument object store.\n */\nfunction dbReadTimeKey(\n documentKey: DocumentKey,\n readTime: SnapshotVersion\n): DbRemoteDocumentKey {\n const path = documentKey.path.toArray();\n return [\n /* prefix path */ path.slice(0, path.length - 2),\n /* collection id */ path[path.length - 2],\n toDbTimestampKey(readTime),\n /* document id */ path[path.length - 1]\n ];\n}\n\n/**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentCollectionGroupIndex` index.\n */\nfunction dbCollectionGroupKey(\n collectionGroup: string,\n offset: IndexOffset\n): [string, DbTimestampKey, string[], string] {\n const path = offset.documentKey.path.toArray();\n return [\n /* collection id */ collectionGroup,\n toDbTimestampKey(offset.readTime),\n /* prefix path */ path.slice(0, path.length - 2),\n /* document id */ path.length > 0 ? path[path.length - 1] : ''\n ];\n}\n\n/**\n * Comparator that compares document keys according to the primary key sorting\n * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id\n * and then document ID).\n *\n * Visible for testing.\n */\nexport function dbKeyComparator(l: DocumentKey, r: DocumentKey): number {\n const left = l.path.toArray();\n const right = r.path.toArray();\n\n // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74\n let cmp = 0;\n for (let i = 0; i < left.length - 2 && i < right.length - 2; ++i) {\n cmp = primitiveComparator(left[i], right[i]);\n if (cmp) {\n return cmp;\n }\n }\n\n cmp = primitiveComparator(left.length, right.length);\n if (cmp) {\n return cmp;\n }\n\n cmp = primitiveComparator(left[left.length - 2], right[right.length - 2]);\n if (cmp) {\n return cmp;\n }\n\n // TODO(b/329441702): Document IDs should be sorted by UTF-8 encoded byte\n // order, but IndexedDB sorts strings lexicographically. Document ID\n // comparison here still relies on primitive comparison to avoid mismatches\n // observed in snapshot listeners with Unicode characters in documentIds\n return primitiveComparator(left[left.length - 1], right[right.length - 1]);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BatchId, ListenSequenceNumber, TargetId } from '../core/types';\nimport { IndexKind } from '../model/field_index';\nimport { BundledQuery } from '../protos/firestore_bundle_proto';\nimport {\n Document as ProtoDocument,\n DocumentsTarget as ProtoDocumentsTarget,\n QueryTarget as ProtoQueryTarget,\n Write as ProtoWrite\n} from '../protos/firestore_proto_api';\n\nimport { EncodedResourcePath } from './encoded_resource_path';\nimport { DbTimestampKey, KeySafeBytes } from './indexeddb_sentinels';\n\n/**\n * Schema Version for the Web client:\n * 1. Initial version including Mutation Queue, Query Cache, and Remote\n * Document Cache\n * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No\n * longer required because migration 3 unconditionally clears it.\n * 3. Dropped and re-created Query Cache to deal with cache corruption related\n * to limbo resolution. Addresses\n * https://github.com/firebase/firebase-ios-sdk/issues/1548\n * 4. Multi-Tab Support.\n * 5. Removal of held write acks.\n * 6. Create document global for tracking document cache size.\n * 7. Ensure every cached document has a sentinel row with a sequence number.\n * 8. Add collection-parent index for Collection Group queries.\n * 9. Change RemoteDocumentChanges store to be keyed by readTime rather than\n * an auto-incrementing ID. This is required for Index-Free queries.\n * 10. Rewrite the canonical IDs to the explicit Protobuf-based format.\n * 11. Add bundles and named_queries for bundle support.\n * 12. Add document overlays.\n * 13. Rewrite the keys of the remote document cache to allow for efficient\n * document lookup via `getAll()`.\n * 14. Add overlays.\n * 15. Add indexing support.\n * 16. Parse timestamp strings before creating index entries.\n * 17. TODO(tomandersen)\n * 18. Encode key safe representations of IndexEntry in DbIndexEntryStore.\n */\n\nexport const SCHEMA_VERSION = 18;\n\n/**\n * Wrapper class to store timestamps (seconds and nanos) in IndexedDb objects.\n */\nexport interface DbTimestamp {\n seconds: number;\n nanoseconds: number;\n}\n\n/**\n * A singleton object to be stored in the 'owner' store in IndexedDb.\n *\n * A given database can have a single primary tab assigned at a given time. That\n * tab must validate that it is still holding the primary lease before every\n * operation that requires locked access. The primary tab should regularly\n * write an updated timestamp to this lease to prevent other tabs from\n * \"stealing\" the primary lease\n */\nexport interface DbPrimaryClient {\n ownerId: string;\n /** Whether to allow shared access from multiple tabs. */\n allowTabSynchronization: boolean;\n leaseTimestampMs: number;\n}\n\n/**\n * An object to be stored in the 'mutationQueues' store in IndexedDb.\n *\n * Each user gets a single queue of MutationBatches to apply to the server.\n * DbMutationQueue tracks the metadata about the queue.\n */\nexport interface DbMutationQueue {\n /**\n * The normalized user ID to which this queue belongs.\n */\n userId: string;\n /**\n * An identifier for the highest numbered batch that has been acknowledged\n * by the server. All MutationBatches in this queue with batchIds less\n * than or equal to this value are considered to have been acknowledged by\n * the server.\n *\n * NOTE: this is deprecated and no longer used by the code.\n */\n lastAcknowledgedBatchId: number;\n /**\n * A stream token that was previously sent by the server.\n *\n * See StreamingWriteRequest in datastore.proto for more details about\n * usage.\n *\n * After sending this token, earlier tokens may not be used anymore so\n * only a single stream token is retained.\n *\n * NOTE: this is deprecated and no longer used by the code.\n */\n lastStreamToken: string;\n}\n\n/**\n * An object to be stored in the 'mutations' store in IndexedDb.\n *\n * Represents a batch of user-level mutations intended to be sent to the server\n * in a single write. Each user-level batch gets a separate DbMutationBatch\n * with a new batchId.\n */\nexport interface DbMutationBatch {\n /**\n * The normalized user ID to which this batch belongs.\n */\n userId: string;\n /**\n * An identifier for this batch, allocated using an auto-generated key.\n */\n batchId: BatchId;\n /**\n * The local write time of the batch, stored as milliseconds since the\n * epoch.\n */\n localWriteTimeMs: number;\n /**\n * A list of \"mutations\" that represent a partial base state from when this\n * write batch was initially created. During local application of the write\n * batch, these baseMutations are applied prior to the real writes in order\n * to override certain document fields from the remote document cache. This\n * is necessary in the case of non-idempotent writes (e.g. `increment()`\n * transforms) to make sure that the local view of the modified documents\n * doesn't flicker if the remote document cache receives the result of the\n * non-idempotent write before the write is removed from the queue.\n *\n * These mutations are never sent to the backend.\n */\n baseMutations?: ProtoWrite[];\n /**\n * A list of mutations to apply. All mutations will be applied atomically.\n *\n * Mutations are serialized via toMutation().\n */\n mutations: ProtoWrite[];\n}\n\n/**\n * An object to be stored in the 'documentMutations' store in IndexedDb.\n *\n * A manually maintained index of all the mutation batches that affect a given\n * document key. The rows in this table are references based on the contents of\n * DbMutationBatch.mutations.\n */\nexport interface DbDocumentMutation {}\n\n/**\n * Represents the known absence of a document at a particular version.\n * Stored in IndexedDb as part of a DbRemoteDocument object.\n */\nexport interface DbNoDocument {\n path: string[];\n readTime: DbTimestamp;\n}\n\n/**\n * Represents a document that is known to exist but whose data is unknown.\n * Stored in IndexedDb as part of a DbRemoteDocument object.\n */\nexport interface DbUnknownDocument {\n path: string[];\n version: DbTimestamp;\n}\n\n/**\n * An object to be stored in the 'remoteDocuments' store in IndexedDb.\n * It represents either:\n *\n * - A complete document.\n * - A \"no document\" representing a document that is known not to exist (at\n * some version).\n * - An \"unknown document\" representing a document that is known to exist (at\n * some version) but whose contents are unknown.\n *\n * The document key is split up across `prefixPath`, `collectionGroup` and\n * `documentId`.\n *\n * Note: This is the persisted equivalent of a MaybeDocument and could perhaps\n * be made more general if necessary.\n */\nexport interface DbRemoteDocument {\n /** The path to the document's collection (excluding). */\n prefixPath: string[];\n\n /** The collection ID the document is directly nested under. */\n collectionGroup: string;\n\n /** The document ID. */\n documentId: string;\n\n /** When the document was read from the backend. */\n readTime: DbTimestampKey;\n\n /**\n * Set to an instance of DbUnknownDocument if the data for a document is\n * not known, but it is known that a document exists at the specified\n * version (e.g. it had a successful update applied to it)\n */\n unknownDocument?: DbUnknownDocument;\n /**\n * Set to an instance of a DbNoDocument if it is known that no document\n * exists.\n */\n noDocument?: DbNoDocument;\n /**\n * Set to an instance of a Document if there's a cached version of the\n * document.\n */\n document?: ProtoDocument;\n /**\n * Documents that were written to the remote document store based on\n * a write acknowledgment are marked with `hasCommittedMutations`. These\n * documents are potentially inconsistent with the backend's copy and use\n * the write's commit version as their document version.\n */\n hasCommittedMutations: boolean;\n}\n\n/**\n * Contains a single entry that has metadata about the remote document cache.\n */\nexport interface DbRemoteDocumentGlobal {\n /**\n * Approximately the total size in bytes of all the\n * documents in the document cache.\n */\n byteSize: number;\n}\n\n/**\n * The persisted type for a query nested with in the 'targets' store in\n * IndexedDb. We use the proto definitions for these two kinds of queries in\n * order to avoid writing extra serialization logic.\n */\nexport type DbQuery = ProtoQueryTarget | ProtoDocumentsTarget;\n\n/**\n * An object to be stored in the 'targets' store in IndexedDb.\n *\n * This is based on and should be kept in sync with the proto used in the iOS\n * client.\n *\n * Each query the client listens to against the server is tracked on disk so\n * that the query can be efficiently resumed on restart.\n */\nexport interface DbTarget {\n /**\n * An auto-generated sequential numeric identifier for the query.\n *\n * Queries are stored using their canonicalId as the key, but these\n * canonicalIds can be quite long so we additionally assign a unique\n * queryId which can be used by referenced data structures (e.g.\n * indexes) to minimize the on-disk cost.\n */\n targetId: TargetId;\n /**\n * The canonical string representing this query. This is not unique.\n */\n canonicalId: string;\n /**\n * The last readTime received from the Watch Service for this query.\n *\n * This is the same value as TargetChange.read_time in the protos.\n */\n readTime: DbTimestamp;\n /**\n * An opaque, server-assigned token that allows watching a query to be\n * resumed after disconnecting without retransmitting all the data\n * that matches the query. The resume token essentially identifies a\n * point in time from which the server should resume sending results.\n *\n * This is related to the snapshotVersion in that the resumeToken\n * effectively also encodes that value, but the resumeToken is opaque\n * and sometimes encodes additional information.\n *\n * A consequence of this is that the resumeToken should be used when\n * asking the server to reason about where this client is in the watch\n * stream, but the client should use the snapshotVersion for its own\n * purposes.\n *\n * This is the same value as TargetChange.resume_token in the protos.\n */\n resumeToken: string;\n /**\n * A sequence number representing the last time this query was\n * listened to, used for garbage collection purposes.\n *\n * Conventionally this would be a timestamp value, but device-local\n * clocks are unreliable and they must be able to create new listens\n * even while disconnected. Instead this should be a monotonically\n * increasing number that's incremented on each listen call.\n *\n * This is different from the queryId since the queryId is an\n * immutable identifier assigned to the Query on first use while\n * lastListenSequenceNumber is updated every time the query is\n * listened to.\n */\n lastListenSequenceNumber: number;\n /**\n * Denotes the maximum snapshot version at which the associated query view\n * contained no limbo documents. Undefined for data written prior to\n * schema version 9.\n */\n lastLimboFreeSnapshotVersion?: DbTimestamp;\n /**\n * The query for this target.\n *\n * Because canonical ids are not unique we must store the actual query. We\n * use the proto to have an object we can persist without having to\n * duplicate translation logic to and from a `Query` object.\n */\n query: DbQuery;\n}\n\n/**\n * An object representing an association between a target and a document, or a\n * sentinel row marking the last sequence number at which a document was used.\n * Each document cached must have a corresponding sentinel row before lru\n * garbage collection is enabled.\n *\n * The target associations and sentinel rows are co-located so that orphaned\n * documents and their sequence numbers can be identified efficiently via a scan\n * of this store.\n */\nexport interface DbTargetDocument {\n /**\n * The targetId identifying a target or 0 for a sentinel row.\n */\n targetId: TargetId;\n /**\n * The path to the document, as encoded in the key.\n */\n path: EncodedResourcePath;\n /**\n * If this is a sentinel row, this should be the sequence number of the last\n * time the document specified by `path` was used. Otherwise, it should be\n * `undefined`.\n */\n sequenceNumber?: ListenSequenceNumber;\n}\n\n/**\n * A record of global state tracked across all Targets, tracked separately\n * to avoid the need for extra indexes.\n *\n * This should be kept in-sync with the proto used in the iOS client.\n */\nexport interface DbTargetGlobal {\n /**\n * The highest numbered target id across all targets.\n *\n * See DbTarget.targetId.\n */\n highestTargetId: TargetId;\n /**\n * The highest numbered lastListenSequenceNumber across all targets.\n *\n * See DbTarget.lastListenSequenceNumber.\n */\n highestListenSequenceNumber: number;\n /**\n * A global snapshot version representing the last consistent snapshot we\n * received from the backend. This is monotonically increasing and any\n * snapshots received from the backend prior to this version (e.g. for\n * targets resumed with a resumeToken) should be suppressed (buffered)\n * until the backend has caught up to this snapshot version again. This\n * prevents our cache from ever going backwards in time.\n */\n lastRemoteSnapshotVersion: DbTimestamp;\n /**\n * The number of targets persisted.\n */\n targetCount: number;\n}\n\n/**\n * An object representing an association between a Collection id (e.g. 'messages')\n * to a parent path (e.g. '/chats/123') that contains it as a (sub)collection.\n * This is used to efficiently find all collections to query when performing\n * a Collection Group query.\n */\nexport interface DbCollectionParent {\n /**\n * The collectionId (e.g. 'messages')\n */\n collectionId: string;\n /**\n * The path to the parent (either a document location or an empty path for\n * a root-level collection).\n */\n parent: EncodedResourcePath;\n}\n\n/**\n * A record of the metadata state of each client.\n *\n * PORTING NOTE: This is used to synchronize multi-tab state and does not need\n * to be ported to iOS or Android.\n */\nexport interface DbClientMetadata {\n // Note: Previous schema versions included a field\n // \"lastProcessedDocumentChangeId\". Don't use anymore.\n\n /** The auto-generated client id assigned at client startup. */\n clientId: string;\n /** The last time this state was updated. */\n updateTimeMs: number;\n /** Whether the client's network connection is enabled. */\n networkEnabled: boolean;\n /** Whether this client is running in a foreground tab. */\n inForeground: boolean;\n}\n\n/** An object representing a bundle loaded by the SDK. */\nexport interface DbBundle {\n /** The ID of the loaded bundle. */\n bundleId: string;\n /** The create time of the loaded bundle. */\n createTime: DbTimestamp;\n /** The schema version of the loaded bundle. */\n version: number;\n}\n\n/** An object representing a named query loaded by the SDK via a bundle. */\nexport interface DbNamedQuery {\n /** The name of the query. */\n name: string;\n /** The read time of the results saved in the bundle from the named query. */\n readTime: DbTimestamp;\n /** The query saved in the bundle. */\n bundledQuery: BundledQuery;\n}\n\n/** An object representing the global configuration for a field index. */\nexport interface DbIndexConfiguration {\n /**\n * The index id for this entry. Undefined for indexes that are not yet\n * persisted.\n */\n indexId?: number;\n /** The collection group this index belongs to. */\n collectionGroup: string;\n /** The fields to index for this index. */\n fields: Array<[name: string, kind: IndexKind]>;\n}\n\n/**\n * An object describing how up-to-date the index backfill is for each user and\n * index.\n */\nexport interface DbIndexState {\n /** The index id for this entry. */\n indexId: number;\n /** The user id for this entry. */\n uid: string;\n /**\n * A number that indicates when the index was last updated (relative to\n * other indexes).\n */\n sequenceNumber: number;\n /**\n * The latest read time that has been indexed by Firestore for this field\n * index. Set to `{seconds: 0, nanos: 0}` if no documents have been indexed.\n */\n readTime: DbTimestamp;\n /**\n * The last document that has been indexed for this field index. Empty if\n * no documents have been indexed.\n */\n documentKey: EncodedResourcePath;\n /**\n * The largest mutation batch id that has been processed for this index. -1\n * if no mutations have been indexed.\n */\n largestBatchId: number;\n}\n\n/** An object that stores the encoded entries for all documents and fields. */\nexport interface DbIndexEntry {\n // TODO(indexing): Consider just storing `orderedDocumentKey` and decoding\n // the ordered key into a document key. This would reduce storage space on\n // disk but require us to port parts of OrderedCodeReader.\n\n /** The index id for this entry. */\n indexId: number;\n /** The user id for this entry. */\n uid: string;\n /** The encoded array index value for this entry. */\n arrayValue: KeySafeBytes;\n /** The encoded directional value for equality and inequality filters. */\n directionalValue: KeySafeBytes;\n /**\n * The document key this entry points to. This entry is encoded by an ordered\n * encoder to match the key order of the index.\n */\n orderedDocumentKey: KeySafeBytes;\n /** The segments of the document key this entry points to. */\n documentKey: string[];\n}\n\n/**\n * An object representing a document overlay.\n */\nexport interface DbDocumentOverlay {\n /** The user ID to whom this overlay belongs. */\n userId: string;\n /** The path to the collection that contains the document. */\n collectionPath: string;\n /** The ID (key) of the document within the collection. */\n documentId: string;\n /** The collection group to which the document belongs. */\n collectionGroup: string;\n /** The largest batch ID that's been applied for this overlay. */\n largestBatchId: number;\n /** The overlay mutation. */\n overlayMutation: ProtoWrite;\n}\n\n/**\n * An object containing global name/value pair.\n */\nexport interface DbGlobals {\n /** Name is a globally unique identifier for a value. */\n name: string;\n /** Value is a general purpose storage for global data. */\n value: Uint8Array;\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 *

+ */ +function setLogLevel(logLevel) { + logClient.setLogLevel(logLevel); +} +function logDebug(msg, ...obj) { + if (logClient.logLevel <= LogLevel.DEBUG) { + const args = obj.map(argToString); + logClient.debug(`Firestore (${SDK_VERSION}): ${msg}`, ...args); + } +} +function logError(msg, ...obj) { + if (logClient.logLevel <= LogLevel.ERROR) { + const args = obj.map(argToString); + logClient.error(`Firestore (${SDK_VERSION}): ${msg}`, ...args); + } +} +/** + * @internal + */ +function logWarn(msg, ...obj) { + if (logClient.logLevel <= LogLevel.WARN) { + const args = obj.map(argToString); + logClient.warn(`Firestore (${SDK_VERSION}): ${msg}`, ...args); + } +} +/** + * Converts an additional log parameter to a string representation. + */ +function argToString(obj) { + if (typeof obj === 'string') { + return obj; + } + else { + try { + return formatJSON(obj); + } + catch (e) { + // Converting to JSON failed, just log the object directly + return obj; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function fail(id, messageOrContext, context) { + let message = 'Unexpected state'; + if (typeof messageOrContext === 'string') { + message = messageOrContext; + } + else { + context = messageOrContext; + } + _fail(id, message, context); +} +function _fail(id, failure, context) { + // Log the failure in addition to throw an exception, just in case the + // exception is swallowed. + let message = `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ${failure} (ID: ${id.toString(16)})`; + if (context !== undefined) { + try { + const stringContext = JSON.stringify(context); + message += ' CONTEXT: ' + stringContext; + } + catch (e) { + message += ' CONTEXT: ' + context; + } + } + logError(message); + // NOTE: We don't use FirestoreError here because these are internal failures + // that cannot be handled by the user. (Also it would create a circular + // dependency between the error and assert modules which doesn't work.) + throw new Error(message); +} +function hardAssert(assertion, id, messageOrContext, context) { + let message = 'Unexpected state'; + if (typeof messageOrContext === 'string') { + message = messageOrContext; + } + else { + context = messageOrContext; + } + if (!assertion) { + _fail(id, message, context); + } +} +/** + * Fails if the given assertion condition is false, throwing an Error with the + * given message if it did. + * + * The code of callsites invoking this function are stripped out in production + * builds. Any side-effects of code within the debugAssert() invocation will not + * happen in this case. + * + * @internal + */ +function debugAssert(assertion, message) { + if (!assertion) { + fail(0xdeb6, message); + } +} +/** + * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an + * instance of `T` before casting. + */ +function debugCast(obj, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +constructor) { + return obj; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const Code = { + // Causes are copied from: + // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h + /** Not an error; returned on success. */ + OK: 'ok', + /** The operation was cancelled (typically by the caller). */ + CANCELLED: 'cancelled', + /** Unknown error or an error from a different error domain. */ + UNKNOWN: 'unknown', + /** + * Client specified an invalid argument. Note that this differs from + * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are + * problematic regardless of the state of the system (e.g., a malformed file + * name). + */ + INVALID_ARGUMENT: 'invalid-argument', + /** + * Deadline expired before operation could complete. For operations that + * change the state of the system, this error may be returned even if the + * operation has completed successfully. For example, a successful response + * from a server could have been delayed long enough for the deadline to + * expire. + */ + DEADLINE_EXCEEDED: 'deadline-exceeded', + /** Some requested entity (e.g., file or directory) was not found. */ + NOT_FOUND: 'not-found', + /** + * Some entity that we attempted to create (e.g., file or directory) already + * exists. + */ + ALREADY_EXISTS: 'already-exists', + /** + * The caller does not have permission to execute the specified operation. + * PERMISSION_DENIED must not be used for rejections caused by exhausting + * some resource (use RESOURCE_EXHAUSTED instead for those errors). + * PERMISSION_DENIED must not be used if the caller cannot be identified + * (use UNAUTHENTICATED instead for those errors). + */ + PERMISSION_DENIED: 'permission-denied', + /** + * The request does not have valid authentication credentials for the + * operation. + */ + UNAUTHENTICATED: 'unauthenticated', + /** + * Some resource has been exhausted, perhaps a per-user quota, or perhaps the + * entire file system is out of space. + */ + RESOURCE_EXHAUSTED: 'resource-exhausted', + /** + * Operation was rejected because the system is not in a state required for + * the operation's execution. For example, directory to be deleted may be + * non-empty, an rmdir operation is applied to a non-directory, etc. + * + * A litmus test that may help a service implementor in deciding + * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: + * (a) Use UNAVAILABLE if the client can retry just the failing call. + * (b) Use ABORTED if the client should retry at a higher-level + * (e.g., restarting a read-modify-write sequence). + * (c) Use FAILED_PRECONDITION if the client should not retry until + * the system state has been explicitly fixed. E.g., if an "rmdir" + * fails because the directory is non-empty, FAILED_PRECONDITION + * should be returned since the client should not retry unless + * they have first fixed up the directory by deleting files from it. + * (d) Use FAILED_PRECONDITION if the client performs conditional + * REST Get/Update/Delete on a resource and the resource on the + * server does not match the condition. E.g., conflicting + * read-modify-write on the same resource. + */ + FAILED_PRECONDITION: 'failed-precondition', + /** + * The operation was aborted, typically due to a concurrency issue like + * sequencer check failures, transaction aborts, etc. + * + * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, + * and UNAVAILABLE. + */ + ABORTED: 'aborted', + /** + * Operation was attempted past the valid range. E.g., seeking or reading + * past end of file. + * + * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed + * if the system state changes. For example, a 32-bit file system will + * generate INVALID_ARGUMENT if asked to read at an offset that is not in the + * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from + * an offset past the current file size. + * + * There is a fair bit of overlap between FAILED_PRECONDITION and + * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) + * when it applies so that callers who are iterating through a space can + * easily look for an OUT_OF_RANGE error to detect when they are done. + */ + OUT_OF_RANGE: 'out-of-range', + /** Operation is not implemented or not supported/enabled in this service. */ + UNIMPLEMENTED: 'unimplemented', + /** + * Internal errors. Means some invariants expected by underlying System has + * been broken. If you see one of these errors, Something is very broken. + */ + INTERNAL: 'internal', + /** + * The service is currently unavailable. This is a most likely a transient + * condition and may be corrected by retrying with a backoff. + * + * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, + * and UNAVAILABLE. + */ + UNAVAILABLE: 'unavailable', + /** Unrecoverable data loss or corruption. */ + DATA_LOSS: 'data-loss' +}; +/** An error returned by a Firestore operation. */ +class FirestoreError extends FirebaseError { + /** @hideconstructor */ + constructor( + /** + * The backend error code associated with this error. + */ + code, + /** + * A custom error description. + */ + message) { + super(code, message); + this.code = code; + this.message = message; + // HACK: We write a toString property directly because Error is not a real + // class and so inheritance does not work correctly. We could alternatively + // do the same "back-door inheritance" trick that FirebaseError does. + this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Deferred { + constructor() { + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + }); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class OAuthToken { + constructor(value, user) { + this.user = user; + this.type = 'OAuth'; + this.headers = new Map(); + this.headers.set('Authorization', `Bearer ${value}`); + } +} +/** + * A CredentialsProvider that always yields an empty token. + * @internal + */ +class EmptyAuthCredentialsProvider { + getToken() { + return Promise.resolve(null); + } + invalidateToken() { } + start(asyncQueue, changeListener) { + // Fire with initial user. + asyncQueue.enqueueRetryable(() => changeListener(User.UNAUTHENTICATED)); + } + shutdown() { } +} +/** + * A CredentialsProvider that always returns a constant token. Used for + * emulator token mocking. + */ +class EmulatorAuthCredentialsProvider { + constructor(token) { + this.token = token; + /** + * Stores the listener registered with setChangeListener() + * This isn't actually necessary since the UID never changes, but we use this + * to verify the listen contract is adhered to in tests. + */ + this.changeListener = null; + } + getToken() { + return Promise.resolve(this.token); + } + invalidateToken() { } + start(asyncQueue, changeListener) { + this.changeListener = changeListener; + // Fire with initial user. + asyncQueue.enqueueRetryable(() => changeListener(this.token.user)); + } + shutdown() { + this.changeListener = null; + } +} +class FirebaseAuthCredentialsProvider { + constructor(authProvider) { + this.authProvider = authProvider; + /** Tracks the current User. */ + this.currentUser = User.UNAUTHENTICATED; + /** + * Counter used to detect if the token changed while a getToken request was + * outstanding. + */ + this.tokenCounter = 0; + this.forceRefresh = false; + this.auth = null; + } + start(asyncQueue, changeListener) { + hardAssert(this.tokenListener === undefined, 0xa540); + let lastTokenId = this.tokenCounter; + // A change listener that prevents double-firing for the same token change. + const guardedChangeListener = user => { + if (this.tokenCounter !== lastTokenId) { + lastTokenId = this.tokenCounter; + return changeListener(user); + } + else { + return Promise.resolve(); + } + }; + // A promise that can be waited on to block on the next token change. + // This promise is re-created after each change. + let nextToken = new Deferred(); + this.tokenListener = () => { + this.tokenCounter++; + this.currentUser = this.getUser(); + nextToken.resolve(); + nextToken = new Deferred(); + asyncQueue.enqueueRetryable(() => guardedChangeListener(this.currentUser)); + }; + const awaitNextToken = () => { + const currentTokenAttempt = nextToken; + asyncQueue.enqueueRetryable(async () => { + await currentTokenAttempt.promise; + await guardedChangeListener(this.currentUser); + }); + }; + const registerAuth = (auth) => { + logDebug('FirebaseAuthCredentialsProvider', 'Auth detected'); + this.auth = auth; + if (this.tokenListener) { + this.auth.addAuthTokenListener(this.tokenListener); + awaitNextToken(); + } + }; + this.authProvider.onInit(auth => registerAuth(auth)); + // Our users can initialize Auth right after Firestore, so we give it + // a chance to register itself with the component framework before we + // determine whether to start up in unauthenticated mode. + setTimeout(() => { + if (!this.auth) { + const auth = this.authProvider.getImmediate({ optional: true }); + if (auth) { + registerAuth(auth); + } + else { + // If auth is still not available, proceed with `null` user + logDebug('FirebaseAuthCredentialsProvider', 'Auth not yet detected'); + nextToken.resolve(); + nextToken = new Deferred(); + } + } + }, 0); + awaitNextToken(); + } + getToken() { + // Take note of the current value of the tokenCounter so that this method + // can fail (with an ABORTED error) if there is a token change while the + // request is outstanding. + const initialTokenCounter = this.tokenCounter; + const forceRefresh = this.forceRefresh; + this.forceRefresh = false; + if (!this.auth) { + return Promise.resolve(null); + } + return this.auth.getToken(forceRefresh).then(tokenData => { + // Cancel the request since the token changed while the request was + // outstanding so the response is potentially for a previous user (which + // user, we can't be sure). + if (this.tokenCounter !== initialTokenCounter) { + logDebug('FirebaseAuthCredentialsProvider', 'getToken aborted due to token change.'); + return this.getToken(); + } + else { + if (tokenData) { + hardAssert(typeof tokenData.accessToken === 'string', 0x7c5d, { tokenData }); + return new OAuthToken(tokenData.accessToken, this.currentUser); + } + else { + return null; + } + } + }); + } + invalidateToken() { + this.forceRefresh = true; + } + shutdown() { + if (this.auth && this.tokenListener) { + this.auth.removeAuthTokenListener(this.tokenListener); + } + this.tokenListener = undefined; + } + // Auth.getUid() can return null even with a user logged in. It is because + // getUid() is synchronous, but the auth code populating Uid is asynchronous. + // This method should only be called in the AuthTokenListener callback + // to guarantee to get the actual user. + getUser() { + const currentUid = this.auth && this.auth.getUid(); + hardAssert(currentUid === null || typeof currentUid === 'string', 0x0807, { currentUid }); + return new User(currentUid); + } +} +/* + * FirstPartyToken provides a fresh token each time its value + * is requested, because if the token is too old, requests will be rejected. + * Technically this may no longer be necessary since the SDK should gracefully + * recover from unauthenticated errors (see b/33147818 for context), but it's + * safer to keep the implementation as-is. + */ +class FirstPartyToken { + constructor(sessionIndex, iamToken, authTokenFactory) { + this.sessionIndex = sessionIndex; + this.iamToken = iamToken; + this.authTokenFactory = authTokenFactory; + this.type = 'FirstParty'; + this.user = User.FIRST_PARTY; + this._headers = new Map(); + } + /** + * Gets an authorization token, using a provided factory function, or return + * null. + */ + getAuthToken() { + if (this.authTokenFactory) { + return this.authTokenFactory(); + } + else { + return null; + } + } + get headers() { + this._headers.set('X-Goog-AuthUser', this.sessionIndex); + // Use array notation to prevent minification + const authHeaderTokenValue = this.getAuthToken(); + if (authHeaderTokenValue) { + this._headers.set('Authorization', authHeaderTokenValue); + } + if (this.iamToken) { + this._headers.set('X-Goog-Iam-Authorization-Token', this.iamToken); + } + return this._headers; + } +} +/* + * Provides user credentials required for the Firestore JavaScript SDK + * to authenticate the user, using technique that is only available + * to applications hosted by Google. + */ +class FirstPartyAuthCredentialsProvider { + constructor(sessionIndex, iamToken, authTokenFactory) { + this.sessionIndex = sessionIndex; + this.iamToken = iamToken; + this.authTokenFactory = authTokenFactory; + } + getToken() { + return Promise.resolve(new FirstPartyToken(this.sessionIndex, this.iamToken, this.authTokenFactory)); + } + start(asyncQueue, changeListener) { + // Fire with initial uid. + asyncQueue.enqueueRetryable(() => changeListener(User.FIRST_PARTY)); + } + shutdown() { } + invalidateToken() { } +} +class AppCheckToken { + constructor(value) { + this.value = value; + this.type = 'AppCheck'; + this.headers = new Map(); + if (value && value.length > 0) { + this.headers.set('x-firebase-appcheck', this.value); + } + } +} +class FirebaseAppCheckTokenProvider { + constructor(app, appCheckProvider) { + this.appCheckProvider = appCheckProvider; + this.forceRefresh = false; + this.appCheck = null; + this.latestAppCheckToken = null; + this.serverAppAppCheckToken = null; + if (_isFirebaseServerApp(app) && app.settings.appCheckToken) { + this.serverAppAppCheckToken = app.settings.appCheckToken; + } + } + start(asyncQueue, changeListener) { + hardAssert(this.tokenListener === undefined, 0x0db8); + const onTokenChanged = tokenResult => { + if (tokenResult.error != null) { + logDebug('FirebaseAppCheckTokenProvider', `Error getting App Check token; using placeholder token instead. Error: ${tokenResult.error.message}`); + } + const tokenUpdated = tokenResult.token !== this.latestAppCheckToken; + this.latestAppCheckToken = tokenResult.token; + logDebug('FirebaseAppCheckTokenProvider', `Received ${tokenUpdated ? 'new' : 'existing'} token.`); + return tokenUpdated + ? changeListener(tokenResult.token) + : Promise.resolve(); + }; + this.tokenListener = (tokenResult) => { + asyncQueue.enqueueRetryable(() => onTokenChanged(tokenResult)); + }; + const registerAppCheck = (appCheck) => { + logDebug('FirebaseAppCheckTokenProvider', 'AppCheck detected'); + this.appCheck = appCheck; + if (this.tokenListener) { + this.appCheck.addTokenListener(this.tokenListener); + } + }; + this.appCheckProvider.onInit(appCheck => registerAppCheck(appCheck)); + // Our users can initialize AppCheck after Firestore, so we give it + // a chance to register itself with the component framework. + setTimeout(() => { + if (!this.appCheck) { + const appCheck = this.appCheckProvider.getImmediate({ optional: true }); + if (appCheck) { + registerAppCheck(appCheck); + } + else { + // If AppCheck is still not available, proceed without it. + logDebug('FirebaseAppCheckTokenProvider', 'AppCheck not yet detected'); + } + } + }, 0); + } + getToken() { + if (this.serverAppAppCheckToken) { + return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken)); + } + const forceRefresh = this.forceRefresh; + this.forceRefresh = false; + if (!this.appCheck) { + return Promise.resolve(null); + } + return this.appCheck.getToken(forceRefresh).then(tokenResult => { + if (tokenResult) { + hardAssert(typeof tokenResult.token === 'string', 0xae0e, { tokenResult }); + this.latestAppCheckToken = tokenResult.token; + return new AppCheckToken(tokenResult.token); + } + else { + return null; + } + }); + } + invalidateToken() { + this.forceRefresh = true; + } + shutdown() { + if (this.appCheck && this.tokenListener) { + this.appCheck.removeTokenListener(this.tokenListener); + } + this.tokenListener = undefined; + } +} +/** + * An AppCheck token provider that always yields an empty token. + * @internal + */ +class EmptyAppCheckTokenProvider { + getToken() { + return Promise.resolve(new AppCheckToken('')); + } + invalidateToken() { } + start(asyncQueue, changeListener) { } + shutdown() { } +} +/** + * Builds a CredentialsProvider depending on the type of + * the credentials passed in. + */ +function makeAuthCredentialsProvider(credentials) { + if (!credentials) { + return new EmptyAuthCredentialsProvider(); + } + switch (credentials['type']) { + case 'firstParty': + return new FirstPartyAuthCredentialsProvider(credentials['sessionIndex'] || '0', credentials['iamToken'] || null, credentials['authTokenFactory'] || null); + case 'provider': + return credentials['client']; + default: + throw new FirestoreError(Code.INVALID_ARGUMENT, 'makeAuthCredentialsProvider failed due to invalid credential type'); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Generates `nBytes` of random bytes. + * + * If `nBytes < 0` , an error will be thrown. + */ +function randomBytes(nBytes) { + return randomBytes$1(nBytes); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A utility class for generating unique alphanumeric IDs of a specified length. + * + * @internal + * Exported internally for testing purposes. + */ +class AutoId { + static newId() { + // Alphanumeric characters + const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + // The largest byte value that is a multiple of `char.length`. + const maxMultiple = Math.floor(256 / chars.length) * chars.length; + let autoId = ''; + const targetLength = 20; + while (autoId.length < targetLength) { + const bytes = randomBytes(40); + for (let i = 0; i < bytes.length; ++i) { + // Only accept values that are [0, maxMultiple), this ensures they can + // be evenly mapped to indices of `chars` via a modulo operation. + if (autoId.length < targetLength && bytes[i] < maxMultiple) { + autoId += chars.charAt(bytes[i] % chars.length); + } + } + } + return autoId; + } +} +function primitiveComparator(left, right) { + if (left < right) { + return -1; + } + if (left > right) { + return 1; + } + return 0; +} +/** Compare strings in UTF-8 encoded byte order */ +function compareUtf8Strings(left, right) { + // Find the first differing character (a.k.a. "UTF-16 code unit") in the two strings and, + // if found, use that character to determine the relative ordering of the two strings as a + // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by + // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8 + // and UTF-16 happen to represent Unicode code points. + // + // After finding the first pair of differing characters, there are two cases: + // + // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or + // both are surrogates from a surrogate pair (that collectively represent code points greater + // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the + // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is + // sufficient. + // + // Case 2: One character is a surrogate and the other is not. In this case the surrogate- + // containing string is always ordered after the non-surrogate. This is because surrogates are + // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations + // and are lexicographically greater than the 1, 2, or 3-byte representations of code points + // less than or equal to 0xFFFF. + // + // An example of why Case 2 is required is comparing the following two Unicode code points: + // + // |-----------------------|------------|---------------------|-----------------| + // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding | + // |-----------------------|------------|---------------------|-----------------| + // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD | + // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 | + // |-----------------------|------------|---------------------|-----------------| + // + // A lexicographical comparison of the UTF-8 encodings of these code points would order + // "Replacement Character" _before_ "Grinning Face" because 0xEF is less than 0xF0. However, a + // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously + // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out, + // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate + // pair with those that do not. + const length = Math.min(left.length, right.length); + for (let i = 0; i < length; i++) { + const leftChar = left.charAt(i); + const rightChar = right.charAt(i); + if (leftChar !== rightChar) { + return isSurrogate(leftChar) === isSurrogate(rightChar) + ? primitiveComparator(leftChar, rightChar) + : isSurrogate(leftChar) + ? 1 + : -1; + } + } + // Use the lengths of the strings to determine the overall comparison result since either the + // strings were equal or one is a prefix of the other. + return primitiveComparator(left.length, right.length); +} +const MIN_SURROGATE$1 = 0xd800; +const MAX_SURROGATE$1 = 0xdfff; +function isSurrogate(s) { + const c = s.charCodeAt(0); + return c >= MIN_SURROGATE$1 && c <= MAX_SURROGATE$1; +} +/** Helper to compare arrays using isEqual(). */ +function arrayEquals(left, right, comparator) { + if (left.length !== right.length) { + return false; + } + return left.every((value, index) => comparator(value, right[index])); +} +/** + * Returns the immediate lexicographically-following string. This is useful to + * construct an inclusive range for indexeddb iterators. + */ +function immediateSuccessor(s) { + // Return the input string, with an additional NUL byte appended. + return s + '\0'; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const DOCUMENT_KEY_NAME = '__name__'; +/** + * Path represents an ordered sequence of string segments. + */ +class BasePath { + constructor(segments, offset, length) { + if (offset === undefined) { + offset = 0; + } + else if (offset > segments.length) { + fail(0x027d, { + offset, + range: segments.length + }); + } + if (length === undefined) { + length = segments.length - offset; + } + else if (length > segments.length - offset) { + fail(0x06d2, { + length, + range: segments.length - offset + }); + } + this.segments = segments; + this.offset = offset; + this.len = length; + } + get length() { + return this.len; + } + isEqual(other) { + return BasePath.comparator(this, other) === 0; + } + child(nameOrPath) { + const segments = this.segments.slice(this.offset, this.limit()); + if (nameOrPath instanceof BasePath) { + nameOrPath.forEach(segment => { + segments.push(segment); + }); + } + else { + segments.push(nameOrPath); + } + return this.construct(segments); + } + /** The index of one past the last segment of the path. */ + limit() { + return this.offset + this.length; + } + popFirst(size) { + size = size === undefined ? 1 : size; + return this.construct(this.segments, this.offset + size, this.length - size); + } + popLast() { + return this.construct(this.segments, this.offset, this.length - 1); + } + firstSegment() { + return this.segments[this.offset]; + } + lastSegment() { + return this.get(this.length - 1); + } + get(index) { + return this.segments[this.offset + index]; + } + isEmpty() { + return this.length === 0; + } + isPrefixOf(other) { + if (other.length < this.length) { + return false; + } + for (let i = 0; i < this.length; i++) { + if (this.get(i) !== other.get(i)) { + return false; + } + } + return true; + } + isImmediateParentOf(potentialChild) { + if (this.length + 1 !== potentialChild.length) { + return false; + } + for (let i = 0; i < this.length; i++) { + if (this.get(i) !== potentialChild.get(i)) { + return false; + } + } + return true; + } + forEach(fn) { + for (let i = this.offset, end = this.limit(); i < end; i++) { + fn(this.segments[i]); + } + } + toArray() { + return this.segments.slice(this.offset, this.limit()); + } + /** + * Compare 2 paths segment by segment, prioritizing numeric IDs + * (e.g., "__id123__") in numeric ascending order, followed by string + * segments in lexicographical order. + */ + static comparator(p1, p2) { + const len = Math.min(p1.length, p2.length); + for (let i = 0; i < len; i++) { + const comparison = BasePath.compareSegments(p1.get(i), p2.get(i)); + if (comparison !== 0) { + return comparison; + } + } + return primitiveComparator(p1.length, p2.length); + } + static compareSegments(lhs, rhs) { + const isLhsNumeric = BasePath.isNumericId(lhs); + const isRhsNumeric = BasePath.isNumericId(rhs); + if (isLhsNumeric && !isRhsNumeric) { + // Only lhs is numeric + return -1; + } + else if (!isLhsNumeric && isRhsNumeric) { + // Only rhs is numeric + return 1; + } + else if (isLhsNumeric && isRhsNumeric) { + // both numeric + return BasePath.extractNumericId(lhs).compare(BasePath.extractNumericId(rhs)); + } + else { + // both non-numeric + return compareUtf8Strings(lhs, rhs); + } + } + // Checks if a segment is a numeric ID (starts with "__id" and ends with "__"). + static isNumericId(segment) { + return segment.startsWith('__id') && segment.endsWith('__'); + } + static extractNumericId(segment) { + return Integer.fromString(segment.substring(4, segment.length - 2)); + } +} +/** + * A slash-separated path for navigating resources (documents and collections) + * within Firestore. + * + * @internal + */ +class ResourcePath extends BasePath { + construct(segments, offset, length) { + return new ResourcePath(segments, offset, length); + } + canonicalString() { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + return this.toArray().join('/'); + } + toString() { + return this.canonicalString(); + } + /** + * Returns a string representation of this path + * where each path segment has been encoded with + * `encodeURIComponent`. + */ + toUriEncodedString() { + return this.toArray().map(encodeURIComponent).join('/'); + } + /** + * Creates a resource path from the given slash-delimited string. If multiple + * arguments are provided, all components are combined. Leading and trailing + * slashes from all components are ignored. + */ + static fromString(...pathComponents) { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + const segments = []; + for (const path of pathComponents) { + if (path.indexOf('//') >= 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid segment (${path}). Paths must not contain // in them.`); + } + // Strip leading and trailing slashed. + segments.push(...path.split('/').filter(segment => segment.length > 0)); + } + return new ResourcePath(segments); + } + static emptyPath() { + return new ResourcePath([]); + } +} +const identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/; +/** + * A dot-separated path for navigating sub-objects within a document. + * @internal + */ +class FieldPath$1 extends BasePath { + construct(segments, offset, length) { + return new FieldPath$1(segments, offset, length); + } + /** + * Returns true if the string could be used as a segment in a field path + * without escaping. + */ + static isValidIdentifier(segment) { + return identifierRegExp.test(segment); + } + canonicalString() { + return this.toArray() + .map(str => { + str = str.replace(/\\/g, '\\\\').replace(/`/g, '\\`'); + if (!FieldPath$1.isValidIdentifier(str)) { + str = '`' + str + '`'; + } + return str; + }) + .join('.'); + } + toString() { + return this.canonicalString(); + } + /** + * Returns true if this field references the key of a document. + */ + isKeyField() { + return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME; + } + /** + * The field designating the key of a document. + */ + static keyField() { + return new FieldPath$1([DOCUMENT_KEY_NAME]); + } + /** + * Parses a field string from the given server-formatted string. + * + * - Splitting the empty string is not allowed (for now at least). + * - Empty segments within the string (e.g. if there are two consecutive + * separators) are not allowed. + * + * TODO(b/37244157): we should make this more strict. Right now, it allows + * non-identifier path components, even if they aren't escaped. + */ + static fromServerFormat(path) { + const segments = []; + let current = ''; + let i = 0; + const addCurrentSegment = () => { + if (current.length === 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid field path (${path}). Paths must not be empty, begin ` + + `with '.', end with '.', or contain '..'`); + } + segments.push(current); + current = ''; + }; + let inBackticks = false; + while (i < path.length) { + const c = path[i]; + if (c === '\\') { + if (i + 1 === path.length) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has trailing escape character: ' + path); + } + const next = path[i + 1]; + if (!(next === '\\' || next === '.' || next === '`')) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has invalid escape sequence: ' + path); + } + current += next; + i += 2; + } + else if (c === '`') { + inBackticks = !inBackticks; + i++; + } + else if (c === '.' && !inBackticks) { + addCurrentSegment(); + i++; + } + else { + current += c; + i++; + } + } + addCurrentSegment(); + if (inBackticks) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Unterminated ` in path: ' + path); + } + return new FieldPath$1(segments); + } + static emptyPath() { + return new FieldPath$1([]); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @internal + */ +class DocumentKey { + constructor(path) { + this.path = path; + } + static fromPath(path) { + return new DocumentKey(ResourcePath.fromString(path)); + } + static fromName(name) { + return new DocumentKey(ResourcePath.fromString(name).popFirst(5)); + } + static empty() { + return new DocumentKey(ResourcePath.emptyPath()); + } + get collectionGroup() { + return this.path.popLast().lastSegment(); + } + /** Returns true if the document is in the specified collectionId. */ + hasCollectionId(collectionId) { + return (this.path.length >= 2 && + this.path.get(this.path.length - 2) === collectionId); + } + /** Returns the collection group (i.e. the name of the parent collection) for this key. */ + getCollectionGroup() { + return this.path.get(this.path.length - 2); + } + /** Returns the fully qualified path to the parent collection. */ + getCollectionPath() { + return this.path.popLast(); + } + isEqual(other) { + return (other !== null && ResourcePath.comparator(this.path, other.path) === 0); + } + toString() { + return this.path.toString(); + } + static comparator(k1, k2) { + return ResourcePath.comparator(k1.path, k2.path); + } + static isDocumentKey(path) { + return path.length % 2 === 0; + } + /** + * Creates and returns a new document key with the given segments. + * + * @param segments - The segments of the path to the document + * @returns A new instance of DocumentKey + */ + static fromSegments(segments) { + return new DocumentKey(new ResourcePath(segments.slice())); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function validateNonEmptyArgument(functionName, argumentName, argument) { + if (!argument) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${functionName}() cannot be called with an empty ${argumentName}.`); + } +} +/** + * Validates that two boolean options are not set at the same time. + * @internal + */ +function validateIsNotUsedTogether(optionName1, argument1, optionName2, argument2) { + if (argument1 === true && argument2 === true) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `${optionName1} and ${optionName2} cannot be used together.`); + } +} +/** + * Validates that `path` refers to a document (indicated by the fact it contains + * an even numbers of segments). + */ +function validateDocumentPath(path) { + if (!DocumentKey.isDocumentKey(path)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid document reference. Document references must have an even number of segments, but ${path} has ${path.length}.`); + } +} +/** + * Validates that `path` refers to a collection (indicated by the fact it + * contains an odd numbers of segments). + */ +function validateCollectionPath(path) { + if (DocumentKey.isDocumentKey(path)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid collection reference. Collection references must have an odd number of segments, but ${path} has ${path.length}.`); + } +} +/** + * Returns true if it's a non-null object without a custom prototype + * (i.e. excludes Array, Date, etc.). + */ +function isPlainObject(input) { + return (typeof input === 'object' && + input !== null && + (Object.getPrototypeOf(input) === Object.prototype || + Object.getPrototypeOf(input) === null)); +} +/** Returns a string describing the type / value of the provided input. */ +function valueDescription(input) { + if (input === undefined) { + return 'undefined'; + } + else if (input === null) { + return 'null'; + } + else if (typeof input === 'string') { + if (input.length > 20) { + input = `${input.substring(0, 20)}...`; + } + return JSON.stringify(input); + } + else if (typeof input === 'number' || typeof input === 'boolean') { + return '' + input; + } + else if (typeof input === 'object') { + if (input instanceof Array) { + return 'an array'; + } + else { + const customObjectName = tryGetCustomObjectType(input); + if (customObjectName) { + return `a custom ${customObjectName} object`; + } + else { + return 'an object'; + } + } + } + else if (typeof input === 'function') { + return 'a function'; + } + else { + return fail(0x3029, { type: typeof input }); + } +} +/** try to get the constructor name for an object. */ +function tryGetCustomObjectType(input) { + if (input.constructor) { + return input.constructor.name; + } + return null; +} +/** + * Casts `obj` to `T`, optionally unwrapping Compat types to expose the + * underlying instance. Throws if `obj` is not an instance of `T`. + * + * This cast is used in the Lite and Full SDK to verify instance types for + * arguments passed to the public API. + * @internal + */ +function cast(obj, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +constructor) { + if ('_delegate' in obj) { + // Unwrap Compat types + // eslint-disable-next-line @typescript-eslint/no-explicit-any + obj = obj._delegate; + } + if (!(obj instanceof constructor)) { + if (constructor.name === obj.constructor.name) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Type does not match the expected instance. Did you pass a ' + + `reference from a different Firestore SDK?`); + } + else { + const description = valueDescription(obj); + throw new FirestoreError(Code.INVALID_ARGUMENT, `Expected type '${constructor.name}', but it was: ${description}`); + } + } + return obj; +} +function validatePositiveNumber(functionName, n) { + if (n <= 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${functionName}() requires a positive number, but it was: ${n}.`); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Helper function to define a JSON schema {@link Property}. + * @private + * @internal + */ +function property(typeString, optionalValue) { + const result = { + typeString + }; + if (optionalValue) { + result.value = optionalValue; + } + return result; +} +/** + * Validates the JSON object based on the provided schema, and narrows the type to the provided + * JSON schema. + * @private + * @internal + * + * @param json A JSON object to validate. + * @param scheme a {@link JsonSchema} that defines the properties to validate. + * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise. + */ +function validateJSON(json, schema) { + if (!isPlainObject(json)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'JSON must be an object'); + } + let error = undefined; + for (const key in schema) { + if (schema[key]) { + const typeString = schema[key].typeString; + const value = 'value' in schema[key] ? { value: schema[key].value } : undefined; + if (!(key in json)) { + error = `JSON missing required field: '${key}'`; + break; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const fieldValue = json[key]; + if (typeString && typeof fieldValue !== typeString) { + error = `JSON field '${key}' must be a ${typeString}.`; + break; + } + else if (value !== undefined && fieldValue !== value.value) { + error = `Expected '${key}' field to equal '${value.value}'`; + break; + } + } + } + if (error) { + throw new FirestoreError(Code.INVALID_ARGUMENT, error); + } + return true; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z). +const MIN_SECONDS = -62135596800; +// Number of nanoseconds in a millisecond. +const MS_TO_NANOS = 1e6; +/** + * A `Timestamp` represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. + * + * It is encoded using the Proleptic Gregorian Calendar which extends the + * Gregorian calendar backwards to year one. It is encoded assuming all minutes + * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59.999999999Z. + * + * For examples and further specifications, refer to the + * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. + */ +class Timestamp { + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns a new timestamp representing the current date. + */ + static now() { + return Timestamp.fromMillis(Date.now()); + } + /** + * Creates a new timestamp from the given date. + * + * @param date - The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the given + * date. + */ + static fromDate(date) { + return Timestamp.fromMillis(date.getTime()); + } + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds - Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the given + * number of milliseconds. + */ + static fromMillis(milliseconds) { + const seconds = Math.floor(milliseconds / 1000); + const nanos = Math.floor((milliseconds - seconds * 1000) * MS_TO_NANOS); + return new Timestamp(seconds, nanos); + } + /** + * Creates a new timestamp. + * + * @param seconds - The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds - The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ + constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + seconds, + /** + * The fractions of a second at nanosecond resolution.* + */ + nanoseconds) { + this.seconds = seconds; + this.nanoseconds = nanoseconds; + if (nanoseconds < 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp nanoseconds out of range: ' + nanoseconds); + } + if (nanoseconds >= 1e9) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp nanoseconds out of range: ' + nanoseconds); + } + if (seconds < MIN_SECONDS) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp seconds out of range: ' + seconds); + } + // This will break in the year 10,000. + if (seconds >= 253402300800) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp seconds out of range: ' + seconds); + } + } + /** + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ + toDate() { + return new Date(this.toMillis()); + } + /** + * Converts a `Timestamp` to a numeric timestamp (in milliseconds since + * epoch). This operation causes a loss of precision. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ + toMillis() { + return this.seconds * 1000 + this.nanoseconds / MS_TO_NANOS; + } + _compareTo(other) { + if (this.seconds === other.seconds) { + return primitiveComparator(this.nanoseconds, other.nanoseconds); + } + return primitiveComparator(this.seconds, other.seconds); + } + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other - The `Timestamp` to compare against. + * @returns true if this `Timestamp` is equal to the provided one. + */ + isEqual(other) { + return (other.seconds === this.seconds && other.nanoseconds === this.nanoseconds); + } + /** Returns a textual representation of this `Timestamp`. */ + toString() { + return ('Timestamp(seconds=' + + this.seconds + + ', nanoseconds=' + + this.nanoseconds + + ')'); + } + /** + * Returns a JSON-serializable representation of this `Timestamp`. + */ + toJSON() { + return { + type: Timestamp._jsonSchemaVersion, + seconds: this.seconds, + nanoseconds: this.nanoseconds + }; + } + /** + * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}. + */ + static fromJSON(json) { + if (validateJSON(json, Timestamp._jsonSchema)) { + return new Timestamp(json.seconds, json.nanoseconds); + } + } + /** + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. + */ + valueOf() { + // This method returns a string of the form . where + // is translated to have a non-negative value and both + // and are left-padded with zeroes to be a consistent length. + // Strings with this format then have a lexicographical ordering that matches + // the expected ordering. The translation is done to avoid having + // a leading negative sign (i.e. a leading '-' character) in its string + // representation, which would affect its lexicographical ordering. + const adjustedSeconds = this.seconds - MIN_SECONDS; + // Note: Up to 12 decimal digits are required to represent all valid + // 'seconds' values. + const formattedSeconds = String(adjustedSeconds).padStart(12, '0'); + const formattedNanoseconds = String(this.nanoseconds).padStart(9, '0'); + return formattedSeconds + '.' + formattedNanoseconds; + } +} +Timestamp._jsonSchemaVersion = 'firestore/timestamp/1.0'; +Timestamp._jsonSchema = { + type: property('string', Timestamp._jsonSchemaVersion), + seconds: property('number'), + nanoseconds: property('number') +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A version of a document in Firestore. This corresponds to the version + * timestamp, such as update_time or read_time. + */ +class SnapshotVersion { + static fromTimestamp(value) { + return new SnapshotVersion(value); + } + static min() { + return new SnapshotVersion(new Timestamp(0, 0)); + } + static max() { + return new SnapshotVersion(new Timestamp(253402300799, 1e9 - 1)); + } + constructor(timestamp) { + this.timestamp = timestamp; + } + compareTo(other) { + return this.timestamp._compareTo(other.timestamp); + } + isEqual(other) { + return this.timestamp.isEqual(other.timestamp); + } + /** Returns a number representation of the version for use in spec tests. */ + toMicroseconds() { + // Convert to microseconds. + return this.timestamp.seconds * 1e6 + this.timestamp.nanoseconds / 1000; + } + toString() { + return 'SnapshotVersion(' + this.timestamp.toString() + ')'; + } + toTimestamp() { + return this.timestamp; + } +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The initial mutation batch id for each index. Gets updated during index + * backfill. + */ +const INITIAL_LARGEST_BATCH_ID = -1; +/** + * The initial sequence number for each index. Gets updated during index + * backfill. + */ +const INITIAL_SEQUENCE_NUMBER = 0; +/** + * An index definition for field indexes in Firestore. + * + * Every index is associated with a collection. The definition contains a list + * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or + * `CONTAINS` for ArrayContains/ArrayContainsAny queries). + * + * Unlike the backend, the SDK does not differentiate between collection or + * collection group-scoped indices. Every index can be used for both single + * collection and collection group queries. + */ +class FieldIndex { + constructor( + /** + * The index ID. Returns -1 if the index ID is not available (e.g. the index + * has not yet been persisted). + */ + indexId, + /** The collection ID this index applies to. */ + collectionGroup, + /** The field segments for this index. */ + fields, + /** Shows how up-to-date the index is for the current user. */ + indexState) { + this.indexId = indexId; + this.collectionGroup = collectionGroup; + this.fields = fields; + this.indexState = indexState; + } +} +/** An ID for an index that has not yet been added to persistence. */ +FieldIndex.UNKNOWN_ID = -1; +/** Returns the ArrayContains/ArrayContainsAny segment for this index. */ +function fieldIndexGetArraySegment(fieldIndex) { + return fieldIndex.fields.find(s => s.kind === 2 /* IndexKind.CONTAINS */); +} +/** Returns all directional (ascending/descending) segments for this index. */ +function fieldIndexGetDirectionalSegments(fieldIndex) { + return fieldIndex.fields.filter(s => s.kind !== 2 /* IndexKind.CONTAINS */); +} +/** + * Returns the order of the document key component for the given index. + * + * PORTING NOTE: This is only used in the Web IndexedDb implementation. + */ +function fieldIndexGetKeyOrder(fieldIndex) { + const directionalSegments = fieldIndexGetDirectionalSegments(fieldIndex); + return directionalSegments.length === 0 + ? 0 /* IndexKind.ASCENDING */ + : directionalSegments[directionalSegments.length - 1].kind; +} +/** + * Compares indexes by collection group and segments. Ignores update time and + * index ID. + */ +function fieldIndexSemanticComparator(left, right) { + let cmp = primitiveComparator(left.collectionGroup, right.collectionGroup); + if (cmp !== 0) { + return cmp; + } + for (let i = 0; i < Math.min(left.fields.length, right.fields.length); ++i) { + cmp = indexSegmentComparator(left.fields[i], right.fields[i]); + if (cmp !== 0) { + return cmp; + } + } + return primitiveComparator(left.fields.length, right.fields.length); +} +/** Returns a debug representation of the field index */ +function fieldIndexToString(fieldIndex) { + return `id=${fieldIndex.indexId}|cg=${fieldIndex.collectionGroup}|f=${fieldIndex.fields.map(f => `${f.fieldPath}:${f.kind}`).join(',')}`; +} +/** An index component consisting of field path and index type. */ +class IndexSegment { + constructor( + /** The field path of the component. */ + fieldPath, + /** The fields sorting order. */ + kind) { + this.fieldPath = fieldPath; + this.kind = kind; + } +} +function indexSegmentComparator(left, right) { + const cmp = FieldPath$1.comparator(left.fieldPath, right.fieldPath); + if (cmp !== 0) { + return cmp; + } + return primitiveComparator(left.kind, right.kind); +} +/** + * Stores the "high water mark" that indicates how updated the Index is for the + * current user. + */ +class IndexState { + constructor( + /** + * Indicates when the index was last updated (relative to other indexes). + */ + sequenceNumber, + /** The the latest indexed read time, document and batch id. */ + offset) { + this.sequenceNumber = sequenceNumber; + this.offset = offset; + } + /** The state of an index that has not yet been backfilled. */ + static empty() { + return new IndexState(INITIAL_SEQUENCE_NUMBER, IndexOffset.min()); + } +} +/** + * Creates an offset that matches all documents with a read time higher than + * `readTime`. + */ +function newIndexOffsetSuccessorFromReadTime(readTime, largestBatchId) { + // We want to create an offset that matches all documents with a read time + // greater than the provided read time. To do so, we technically need to + // create an offset for `(readTime, MAX_DOCUMENT_KEY)`. While we could use + // Unicode codepoints to generate MAX_DOCUMENT_KEY, it is much easier to use + // `(readTime + 1, DocumentKey.empty())` since `> DocumentKey.empty()` matches + // all valid document IDs. + const successorSeconds = readTime.toTimestamp().seconds; + const successorNanos = readTime.toTimestamp().nanoseconds + 1; + const successor = SnapshotVersion.fromTimestamp(successorNanos === 1e9 + ? new Timestamp(successorSeconds + 1, 0) + : new Timestamp(successorSeconds, successorNanos)); + return new IndexOffset(successor, DocumentKey.empty(), largestBatchId); +} +/** Creates a new offset based on the provided document. */ +function newIndexOffsetFromDocument(document) { + return new IndexOffset(document.readTime, document.key, INITIAL_LARGEST_BATCH_ID); +} +/** + * Stores the latest read time, document and batch ID that were processed for an + * index. + */ +class IndexOffset { + constructor( + /** + * The latest read time version that has been indexed by Firestore for this + * field index. + */ + readTime, + /** + * The key of the last document that was indexed for this query. Use + * `DocumentKey.empty()` if no document has been indexed. + */ + documentKey, + /* + * The largest mutation batch id that's been processed by Firestore. + */ + largestBatchId) { + this.readTime = readTime; + this.documentKey = documentKey; + this.largestBatchId = largestBatchId; + } + /** Returns an offset that sorts before all regular offsets. */ + static min() { + return new IndexOffset(SnapshotVersion.min(), DocumentKey.empty(), INITIAL_LARGEST_BATCH_ID); + } + /** Returns an offset that sorts after all regular offsets. */ + static max() { + return new IndexOffset(SnapshotVersion.max(), DocumentKey.empty(), INITIAL_LARGEST_BATCH_ID); + } +} +function indexOffsetComparator(left, right) { + let cmp = left.readTime.compareTo(right.readTime); + if (cmp !== 0) { + return cmp; + } + cmp = DocumentKey.comparator(left.documentKey, right.documentKey); + if (cmp !== 0) { + return cmp; + } + return primitiveComparator(left.largestBatchId, right.largestBatchId); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const PRIMARY_LEASE_LOST_ERROR_MSG = 'The current tab is not in the required state to perform this operation. ' + + 'It might be necessary to refresh the browser tab.'; +/** + * A base class representing a persistence transaction, encapsulating both the + * transaction's sequence numbers as well as a list of onCommitted listeners. + * + * When you call Persistence.runTransaction(), it will create a transaction and + * pass it to your callback. You then pass it to any method that operates + * on persistence. + */ +class PersistenceTransaction { + constructor() { + this.onCommittedListeners = []; + } + addOnCommittedListener(listener) { + this.onCommittedListeners.push(listener); + } + raiseOnCommittedEvent() { + this.onCommittedListeners.forEach(listener => listener()); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Verifies the error thrown by a LocalStore operation. If a LocalStore + * operation fails because the primary lease has been taken by another client, + * we ignore the error (the persistence layer will immediately call + * `applyPrimaryLease` to propagate the primary state change). All other errors + * are re-thrown. + * + * @param err - An error returned by a LocalStore operation. + * @returns A Promise that resolves after we recovered, or the original error. + */ +async function ignoreIfPrimaryLeaseLoss(err) { + if (err.code === Code.FAILED_PRECONDITION && + err.message === PRIMARY_LEASE_LOST_ERROR_MSG) { + logDebug('LocalStore', 'Unexpectedly lost primary lease'); + } + else { + throw err; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * PersistencePromise is essentially a re-implementation of Promise except + * it has a .next() method instead of .then() and .next() and .catch() callbacks + * are executed synchronously when a PersistencePromise resolves rather than + * asynchronously (Promise implementations use setImmediate() or similar). + * + * This is necessary to interoperate with IndexedDB which will automatically + * commit transactions if control is returned to the event loop without + * synchronously initiating another operation on the transaction. + * + * NOTE: .then() and .catch() only allow a single consumer, unlike normal + * Promises. + */ +class PersistencePromise { + constructor(callback) { + // NOTE: next/catchCallback will always point to our own wrapper functions, + // not the user's raw next() or catch() callbacks. + this.nextCallback = null; + this.catchCallback = null; + // When the operation resolves, we'll set result or error and mark isDone. + this.result = undefined; + this.error = undefined; + this.isDone = false; + // Set to true when .then() or .catch() are called and prevents additional + // chaining. + this.callbackAttached = false; + callback(value => { + this.isDone = true; + this.result = value; + if (this.nextCallback) { + // value should be defined unless T is Void, but we can't express + // that in the type system. + this.nextCallback(value); + } + }, error => { + this.isDone = true; + this.error = error; + if (this.catchCallback) { + this.catchCallback(error); + } + }); + } + catch(fn) { + return this.next(undefined, fn); + } + next(nextFn, catchFn) { + if (this.callbackAttached) { + fail(0xe830); + } + this.callbackAttached = true; + if (this.isDone) { + if (!this.error) { + return this.wrapSuccess(nextFn, this.result); + } + else { + return this.wrapFailure(catchFn, this.error); + } + } + else { + return new PersistencePromise((resolve, reject) => { + this.nextCallback = (value) => { + this.wrapSuccess(nextFn, value).next(resolve, reject); + }; + this.catchCallback = (error) => { + this.wrapFailure(catchFn, error).next(resolve, reject); + }; + }); + } + } + toPromise() { + return new Promise((resolve, reject) => { + this.next(resolve, reject); + }); + } + wrapUserFunction(fn) { + try { + const result = fn(); + if (result instanceof PersistencePromise) { + return result; + } + else { + return PersistencePromise.resolve(result); + } + } + catch (e) { + return PersistencePromise.reject(e); + } + } + wrapSuccess(nextFn, value) { + if (nextFn) { + return this.wrapUserFunction(() => nextFn(value)); + } + else { + // If there's no nextFn, then R must be the same as T + return PersistencePromise.resolve(value); + } + } + wrapFailure(catchFn, error) { + if (catchFn) { + return this.wrapUserFunction(() => catchFn(error)); + } + else { + return PersistencePromise.reject(error); + } + } + static resolve(result) { + return new PersistencePromise((resolve, reject) => { + resolve(result); + }); + } + static reject(error) { + return new PersistencePromise((resolve, reject) => { + reject(error); + }); + } + static waitFor( + // Accept all Promise types in waitFor(). + // eslint-disable-next-line @typescript-eslint/no-explicit-any + all) { + return new PersistencePromise((resolve, reject) => { + let expectedCount = 0; + let resolvedCount = 0; + let done = false; + all.forEach(element => { + ++expectedCount; + element.next(() => { + ++resolvedCount; + if (done && resolvedCount === expectedCount) { + resolve(); + } + }, err => reject(err)); + }); + done = true; + if (resolvedCount === expectedCount) { + resolve(); + } + }); + } + /** + * Given an array of predicate functions that asynchronously evaluate to a + * boolean, implements a short-circuiting `or` between the results. Predicates + * will be evaluated until one of them returns `true`, then stop. The final + * result will be whether any of them returned `true`. + */ + static or(predicates) { + let p = PersistencePromise.resolve(false); + for (const predicate of predicates) { + p = p.next(isTrue => { + if (isTrue) { + return PersistencePromise.resolve(isTrue); + } + else { + return predicate(); + } + }); + } + return p; + } + static forEach(collection, f) { + const promises = []; + collection.forEach((r, s) => { + promises.push(f.call(this, r, s)); + }); + return this.waitFor(promises); + } + /** + * Concurrently map all array elements through asynchronous function. + */ + static mapArray(array, f) { + return new PersistencePromise((resolve, reject) => { + const expectedCount = array.length; + const results = new Array(expectedCount); + let resolvedCount = 0; + for (let i = 0; i < expectedCount; i++) { + const current = i; + f(array[current]).next(result => { + results[current] = result; + ++resolvedCount; + if (resolvedCount === expectedCount) { + resolve(results); + } + }, err => reject(err)); + } + }); + } + /** + * An alternative to recursive PersistencePromise calls, that avoids + * potential memory problems from unbounded chains of promises. + * + * The `action` will be called repeatedly while `condition` is true. + */ + static doWhile(condition, action) { + return new PersistencePromise((resolve, reject) => { + const process = () => { + if (condition() === true) { + action().next(() => { + process(); + }, reject); + } + else { + resolve(); + } + }; + process(); + }); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// References to `indexedDB` are guarded by SimpleDb.isAvailable() and getGlobal() +/* eslint-disable no-restricted-globals */ +const LOG_TAG$i = 'SimpleDb'; +/** + * The maximum number of retry attempts for an IndexedDb transaction that fails + * with a DOMException. + */ +const TRANSACTION_RETRY_COUNT = 3; +/** + * Wraps an IDBTransaction and exposes a store() method to get a handle to a + * specific object store. + */ +class SimpleDbTransaction { + static open(db, action, mode, objectStoreNames) { + try { + return new SimpleDbTransaction(action, db.transaction(objectStoreNames, mode)); + } + catch (e) { + throw new IndexedDbTransactionError(action, e); + } + } + constructor(action, transaction) { + this.action = action; + this.transaction = transaction; + this.aborted = false; + /** + * A `Promise` that resolves with the result of the IndexedDb transaction. + */ + this.completionDeferred = new Deferred(); + this.transaction.oncomplete = () => { + this.completionDeferred.resolve(); + }; + this.transaction.onabort = () => { + if (transaction.error) { + this.completionDeferred.reject(new IndexedDbTransactionError(action, transaction.error)); + } + else { + this.completionDeferred.resolve(); + } + }; + this.transaction.onerror = (event) => { + const error = checkForAndReportiOSError(event.target.error); + this.completionDeferred.reject(new IndexedDbTransactionError(action, error)); + }; + } + get completionPromise() { + return this.completionDeferred.promise; + } + abort(error) { + if (error) { + this.completionDeferred.reject(error); + } + if (!this.aborted) { + logDebug(LOG_TAG$i, 'Aborting transaction:', error ? error.message : 'Client-initiated abort'); + this.aborted = true; + this.transaction.abort(); + } + } + maybeCommit() { + // If the browser supports V3 IndexedDB, we invoke commit() explicitly to + // speed up index DB processing if the event loop remains blocks. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const maybeV3IndexedDb = this.transaction; + if (!this.aborted && typeof maybeV3IndexedDb.commit === 'function') { + maybeV3IndexedDb.commit(); + } + } + /** + * Returns a SimpleDbStore for the specified store. All + * operations performed on the SimpleDbStore happen within the context of this + * transaction and it cannot be used anymore once the transaction is + * completed. + * + * Note that we can't actually enforce that the KeyType and ValueType are + * correct, but they allow type safety through the rest of the consuming code. + */ + store(storeName) { + const store = this.transaction.objectStore(storeName); + return new SimpleDbStore(store); + } +} +/** + * Provides a wrapper around IndexedDb with a simplified interface that uses + * Promise-like return values to chain operations. Real promises cannot be used + * since .then() continuations are executed asynchronously (e.g. via + * .setImmediate), which would cause IndexedDB to end the transaction. + * See PersistencePromise for more details. + */ +class SimpleDb { + /** Deletes the specified database. */ + static delete(name) { + logDebug(LOG_TAG$i, 'Removing database:', name); + const globals = getGlobal(); + return wrapRequest(globals.indexedDB.deleteDatabase(name)).toPromise(); + } + /** Returns true if IndexedDB is available in the current environment. */ + static isAvailable() { + if (!isIndexedDBAvailable()) { + return false; + } + if (SimpleDb.isMockPersistence()) { + return true; + } + // We extensively use indexed array values and compound keys, + // which IE and Edge do not support. However, they still have indexedDB + // defined on the window, so we need to check for them here and make sure + // to return that persistence is not enabled for those browsers. + // For tracking support of this feature, see here: + // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/ + // Check the UA string to find out the browser. + const ua = getUA(); + // IE 10 + // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)'; + // IE 11 + // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko'; + // Edge + // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, + // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0'; + // iOS Safari: Disable for users running iOS version < 10. + const iOSVersion = SimpleDb.getIOSVersion(ua); + const isUnsupportedIOS = 0 < iOSVersion && iOSVersion < 10; + // Android browser: Disable for users running version < 4.5. + const androidVersion = getAndroidVersion(ua); + const isUnsupportedAndroid = 0 < androidVersion && androidVersion < 4.5; + if (ua.indexOf('MSIE ') > 0 || + ua.indexOf('Trident/') > 0 || + ua.indexOf('Edge/') > 0 || + isUnsupportedIOS || + isUnsupportedAndroid) { + return false; + } + else { + return true; + } + } + /** + * Returns true if the backing IndexedDB store is the Node IndexedDBShim + * (see https://github.com/axemclion/IndexedDBShim). + */ + static isMockPersistence() { + return (typeof process !== 'undefined' && + process.env?.USE_MOCK_PERSISTENCE === 'YES'); + } + /** Helper to get a typed SimpleDbStore from a transaction. */ + static getStore(txn, store) { + return txn.store(store); + } + // visible for testing + /** Parse User Agent to determine iOS version. Returns -1 if not found. */ + static getIOSVersion(ua) { + const iOSVersionRegex = ua.match(/i(?:phone|pad|pod) os ([\d_]+)/i); + const version = iOSVersionRegex + ? iOSVersionRegex[1].split('_').slice(0, 2).join('.') + : '-1'; + return Number(version); + } + /* + * Creates a new SimpleDb wrapper for IndexedDb database `name`. + * + * Note that `version` must not be a downgrade. IndexedDB does not support + * downgrading the schema version. We currently do not support any way to do + * versioning outside of IndexedDB's versioning mechanism, as only + * version-upgrade transactions are allowed to do things like create + * objectstores. + */ + constructor(name, version, schemaConverter) { + this.name = name; + this.version = version; + this.schemaConverter = schemaConverter; + this.lastClosedDbVersion = null; + const iOSVersion = SimpleDb.getIOSVersion(getUA()); + // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the + // bug we're checking for should exist in iOS >= 12.2 and < 13, but for + // whatever reason it's much harder to hit after 12.2 so we only proactively + // log on 12.2. + if (iOSVersion === 12.2) { + logError('Firestore persistence suffers from a bug in iOS 12.2 ' + + 'Safari that may cause your app to stop working. See ' + + 'https://stackoverflow.com/q/56496296/110915 for details ' + + 'and a potential workaround.'); + } + } + /** + * Opens the specified database, creating or upgrading it if necessary. + */ + async ensureDb(action) { + if (!this.db) { + logDebug(LOG_TAG$i, 'Opening database:', this.name); + this.db = await new Promise((resolve, reject) => { + // TODO(mikelehen): Investigate browser compatibility. + // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB + // suggests IE9 and older WebKit browsers handle upgrade + // differently. They expect setVersion, as described here: + // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion + const request = indexedDB.open(this.name, this.version); + request.onsuccess = (event) => { + const db = event.target.result; + resolve(db); + }; + request.onblocked = () => { + reject(new IndexedDbTransactionError(action, 'Cannot upgrade IndexedDB schema while another tab is open. ' + + 'Close all tabs that access Firestore and reload this page to proceed.')); + }; + request.onerror = (event) => { + const error = event.target.error; + if (error.name === 'VersionError') { + reject(new FirestoreError(Code.FAILED_PRECONDITION, 'A newer version of the Firestore SDK was previously used and so the persisted ' + + 'data is not compatible with the version of the SDK you are now using. The SDK ' + + 'will operate with persistence disabled. If you need persistence, please ' + + 're-upgrade to a newer version of the SDK or else clear the persisted IndexedDB ' + + 'data for your app to start fresh.')); + } + else if (error.name === 'InvalidStateError') { + reject(new FirestoreError(Code.FAILED_PRECONDITION, 'Unable to open an IndexedDB connection. This could be due to running in a ' + + 'private browsing session on a browser whose private browsing sessions do not ' + + 'support IndexedDB: ' + + error)); + } + else { + reject(new IndexedDbTransactionError(action, error)); + } + }; + request.onupgradeneeded = (event) => { + logDebug(LOG_TAG$i, 'Database "' + this.name + '" requires upgrade from version:', event.oldVersion); + const db = event.target.result; + this.schemaConverter + .createOrUpgrade(db, request.transaction, event.oldVersion, this.version) + .next(() => { + logDebug(LOG_TAG$i, 'Database upgrade to version ' + this.version + ' complete'); + }); + }; + }); + } + if (this.versionchangelistener) { + this.db.onversionchange = event => this.versionchangelistener(event); + } + return this.db; + } + setVersionChangeListener(versionChangeListener) { + this.versionchangelistener = versionChangeListener; + if (this.db) { + this.db.onversionchange = (event) => { + return versionChangeListener(event); + }; + } + } + async runTransaction(action, mode, objectStores, transactionFn) { + const readonly = mode === 'readonly'; + let attemptNumber = 0; + while (true) { + ++attemptNumber; + try { + this.db = await this.ensureDb(action); + const transaction = SimpleDbTransaction.open(this.db, action, readonly ? 'readonly' : 'readwrite', objectStores); + const transactionFnResult = transactionFn(transaction) + .next(result => { + transaction.maybeCommit(); + return result; + }) + .catch(error => { + // Abort the transaction if there was an error. + transaction.abort(error); + // We cannot actually recover, and calling `abort()` will cause the transaction's + // completion promise to be rejected. This in turn means that we won't use + // `transactionFnResult` below. We return a rejection here so that we don't add the + // possibility of returning `void` to the type of `transactionFnResult`. + return PersistencePromise.reject(error); + }) + .toPromise(); + // As noted above, errors are propagated by aborting the transaction. So + // we swallow any error here to avoid the browser logging it as unhandled. + transactionFnResult.catch(() => { }); + // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to + // fire), but still return the original transactionFnResult back to the + // caller. + await transaction.completionPromise; + return transactionFnResult; + } + catch (e) { + const error = e; + // TODO(schmidt-sebastian): We could probably be smarter about this and + // not retry exceptions that are likely unrecoverable (such as quota + // exceeded errors). + // Note: We cannot use an instanceof check for FirestoreException, since the + // exception is wrapped in a generic error by our async/await handling. + const retryable = error.name !== 'FirebaseError' && + attemptNumber < TRANSACTION_RETRY_COUNT; + logDebug(LOG_TAG$i, 'Transaction failed with error:', error.message, 'Retrying:', retryable); + this.close(); + if (!retryable) { + return Promise.reject(error); + } + } + } + } + close() { + if (this.db) { + this.db.close(); + } + this.db = undefined; + } +} +/** Parse User Agent to determine Android version. Returns -1 if not found. */ +function getAndroidVersion(ua) { + const androidVersionRegex = ua.match(/Android ([\d.]+)/i); + const version = androidVersionRegex + ? androidVersionRegex[1].split('.').slice(0, 2).join('.') + : '-1'; + return Number(version); +} +/** + * A controller for iterating over a key range or index. It allows an iterate + * callback to delete the currently-referenced object, or jump to a new key + * within the key range or index. + */ +class IterationController { + constructor(dbCursor) { + this.dbCursor = dbCursor; + this.shouldStop = false; + this.nextKey = null; + } + get isDone() { + return this.shouldStop; + } + get skipToKey() { + return this.nextKey; + } + set cursor(value) { + this.dbCursor = value; + } + /** + * This function can be called to stop iteration at any point. + */ + done() { + this.shouldStop = true; + } + /** + * This function can be called to skip to that next key, which could be + * an index or a primary key. + */ + skip(key) { + this.nextKey = key; + } + /** + * Delete the current cursor value from the object store. + * + * NOTE: You CANNOT do this with a keysOnly query. + */ + delete() { + return wrapRequest(this.dbCursor.delete()); + } +} +/** An error that wraps exceptions that thrown during IndexedDB execution. */ +class IndexedDbTransactionError extends FirestoreError { + constructor(actionName, cause) { + super(Code.UNAVAILABLE, `IndexedDB transaction '${actionName}' failed: ${cause}`); + this.name = 'IndexedDbTransactionError'; + } +} +/** Verifies whether `e` is an IndexedDbTransactionError. */ +function isIndexedDbTransactionError(e) { + // Use name equality, as instanceof checks on errors don't work with errors + // that wrap other errors. + return e.name === 'IndexedDbTransactionError'; +} +/** + * A wrapper around an IDBObjectStore providing an API that: + * + * 1) Has generic KeyType / ValueType parameters to provide strongly-typed + * methods for acting against the object store. + * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every + * method return a PersistencePromise instead. + * 3) Provides a higher-level API to avoid needing to do excessive wrapping of + * intermediate IndexedDB types (IDBCursorWithValue, etc.) + */ +class SimpleDbStore { + constructor(store) { + this.store = store; + } + put(keyOrValue, value) { + let request; + if (value !== undefined) { + logDebug(LOG_TAG$i, 'PUT', this.store.name, keyOrValue, value); + request = this.store.put(value, keyOrValue); + } + else { + logDebug(LOG_TAG$i, 'PUT', this.store.name, '', keyOrValue); + request = this.store.put(keyOrValue); + } + return wrapRequest(request); + } + /** + * Adds a new value into an Object Store and returns the new key. Similar to + * IndexedDb's `add()`, this method will fail on primary key collisions. + * + * @param value - The object to write. + * @returns The key of the value to add. + */ + add(value) { + logDebug(LOG_TAG$i, 'ADD', this.store.name, value, value); + const request = this.store.add(value); + return wrapRequest(request); + } + /** + * Gets the object with the specified key from the specified store, or null + * if no object exists with the specified key. + * + * @key The key of the object to get. + * @returns The object with the specified key or null if no object exists. + */ + get(key) { + const request = this.store.get(key); + // We're doing an unsafe cast to ValueType. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return wrapRequest(request).next(result => { + // Normalize nonexistence to null. + if (result === undefined) { + result = null; + } + logDebug(LOG_TAG$i, 'GET', this.store.name, key, result); + return result; + }); + } + delete(key) { + logDebug(LOG_TAG$i, 'DELETE', this.store.name, key); + const request = this.store.delete(key); + return wrapRequest(request); + } + /** + * If we ever need more of the count variants, we can add overloads. For now, + * all we need is to count everything in a store. + * + * Returns the number of rows in the store. + */ + count() { + logDebug(LOG_TAG$i, 'COUNT', this.store.name); + const request = this.store.count(); + return wrapRequest(request); + } + loadAll(indexOrRange, range) { + const iterateOptions = this.options(indexOrRange, range); + // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly + // 20% faster. + const store = iterateOptions.index + ? this.store.index(iterateOptions.index) + : this.store; + if (typeof store.getAll === 'function') { + const request = store.getAll(iterateOptions.range); + return new PersistencePromise((resolve, reject) => { + request.onerror = (event) => { + reject(event.target.error); + }; + request.onsuccess = (event) => { + resolve(event.target.result); + }; + }); + } + else { + const cursor = this.cursor(iterateOptions); + const results = []; + return this.iterateCursor(cursor, (key, value) => { + results.push(value); + }).next(() => { + return results; + }); + } + } + /** + * Loads the first `count` elements from the provided index range. Loads all + * elements if no limit is provided. + */ + loadFirst(range, count) { + const request = this.store.getAll(range, count === null ? undefined : count); + return new PersistencePromise((resolve, reject) => { + request.onerror = (event) => { + reject(event.target.error); + }; + request.onsuccess = (event) => { + resolve(event.target.result); + }; + }); + } + deleteAll(indexOrRange, range) { + logDebug(LOG_TAG$i, 'DELETE ALL', this.store.name); + const options = this.options(indexOrRange, range); + options.keysOnly = false; + const cursor = this.cursor(options); + return this.iterateCursor(cursor, (key, value, control) => { + // NOTE: Calling delete() on a cursor is documented as more efficient than + // calling delete() on an object store with a single key + // (https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete), + // however, this requires us *not* to use a keysOnly cursor + // (https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/delete). We + // may want to compare the performance of each method. + return control.delete(); + }); + } + iterate(optionsOrCallback, callback) { + let options; + if (!callback) { + options = {}; + callback = optionsOrCallback; + } + else { + options = optionsOrCallback; + } + const cursor = this.cursor(options); + return this.iterateCursor(cursor, callback); + } + /** + * Iterates over a store, but waits for the given callback to complete for + * each entry before iterating the next entry. This allows the callback to do + * asynchronous work to determine if this iteration should continue. + * + * The provided callback should return `true` to continue iteration, and + * `false` otherwise. + */ + iterateSerial(callback) { + const cursorRequest = this.cursor({}); + return new PersistencePromise((resolve, reject) => { + cursorRequest.onerror = (event) => { + const error = checkForAndReportiOSError(event.target.error); + reject(error); + }; + cursorRequest.onsuccess = (event) => { + const cursor = event.target.result; + if (!cursor) { + resolve(); + return; + } + callback(cursor.primaryKey, cursor.value).next(shouldContinue => { + if (shouldContinue) { + cursor.continue(); + } + else { + resolve(); + } + }); + }; + }); + } + iterateCursor(cursorRequest, fn) { + const results = []; + return new PersistencePromise((resolve, reject) => { + cursorRequest.onerror = (event) => { + reject(event.target.error); + }; + cursorRequest.onsuccess = (event) => { + const cursor = event.target.result; + if (!cursor) { + resolve(); + return; + } + const controller = new IterationController(cursor); + const userResult = fn(cursor.primaryKey, cursor.value, controller); + if (userResult instanceof PersistencePromise) { + const userPromise = userResult.catch(err => { + controller.done(); + return PersistencePromise.reject(err); + }); + results.push(userPromise); + } + if (controller.isDone) { + resolve(); + } + else if (controller.skipToKey === null) { + cursor.continue(); + } + else { + cursor.continue(controller.skipToKey); + } + }; + }).next(() => PersistencePromise.waitFor(results)); + } + options(indexOrRange, range) { + let indexName = undefined; + if (indexOrRange !== undefined) { + if (typeof indexOrRange === 'string') { + indexName = indexOrRange; + } + else { + range = indexOrRange; + } + } + return { index: indexName, range }; + } + cursor(options) { + let direction = 'next'; + if (options.reverse) { + direction = 'prev'; + } + if (options.index) { + const index = this.store.index(options.index); + if (options.keysOnly) { + return index.openKeyCursor(options.range, direction); + } + else { + return index.openCursor(options.range, direction); + } + } + else { + return this.store.openCursor(options.range, direction); + } + } +} +/** + * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror + * handlers to resolve / reject the PersistencePromise as appropriate. + */ +function wrapRequest(request) { + return new PersistencePromise((resolve, reject) => { + request.onsuccess = (event) => { + const result = event.target.result; + resolve(result); + }; + request.onerror = (event) => { + const error = checkForAndReportiOSError(event.target.error); + reject(error); + }; + }); +} +// Guard so we only report the error once. +let reportedIOSError = false; +function checkForAndReportiOSError(error) { + const iOSVersion = SimpleDb.getIOSVersion(getUA()); + if (iOSVersion >= 12.2 && iOSVersion < 13) { + const IOS_ERROR = 'An internal error was encountered in the Indexed Database server'; + if (error.message.indexOf(IOS_ERROR) >= 0) { + // Wrap error in a more descriptive one. + const newError = new FirestoreError('internal', `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${IOS_ERROR}'. This is likely ` + + `due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 ` + + `for details and a potential workaround.`); + if (!reportedIOSError) { + reportedIOSError = true; + // Throw a global exception outside of this promise chain, for the user to + // potentially catch. + setTimeout(() => { + throw newError; + }, 0); + } + return newError; + } + } + return error; +} + +const LOG_TAG$h = 'IndexBackfiller'; +/** How long we wait to try running index backfill after SDK initialization. */ +const INITIAL_BACKFILL_DELAY_MS = 15 * 1000; +/** Minimum amount of time between backfill checks, after the first one. */ +const REGULAR_BACKFILL_DELAY_MS = 60 * 1000; +/** The maximum number of documents to process each time backfill() is called. */ +const MAX_DOCUMENTS_TO_PROCESS = 50; +/** This class is responsible for the scheduling of Index Backfiller. */ +class IndexBackfillerScheduler { + constructor(asyncQueue, backfiller) { + this.asyncQueue = asyncQueue; + this.backfiller = backfiller; + this.task = null; + } + start() { + this.schedule(INITIAL_BACKFILL_DELAY_MS); + } + stop() { + if (this.task) { + this.task.cancel(); + this.task = null; + } + } + get started() { + return this.task !== null; + } + schedule(delay) { + logDebug(LOG_TAG$h, `Scheduled in ${delay}ms`); + this.task = this.asyncQueue.enqueueAfterDelay("index_backfill" /* TimerId.IndexBackfill */, delay, async () => { + this.task = null; + try { + const documentsProcessed = await this.backfiller.backfill(); + logDebug(LOG_TAG$h, `Documents written: ${documentsProcessed}`); + } + catch (e) { + if (isIndexedDbTransactionError(e)) { + logDebug(LOG_TAG$h, 'Ignoring IndexedDB error during index backfill: ', e); + } + else { + await ignoreIfPrimaryLeaseLoss(e); + } + } + await this.schedule(REGULAR_BACKFILL_DELAY_MS); + }); + } +} +/** Implements the steps for backfilling indexes. */ +class IndexBackfiller { + constructor( + /** + * LocalStore provides access to IndexManager and LocalDocumentView. + * These properties will update when the user changes. Consequently, + * making a local copy of IndexManager and LocalDocumentView will require + * updates over time. The simpler solution is to rely on LocalStore to have + * an up-to-date references to IndexManager and LocalDocumentStore. + */ + localStore, persistence) { + this.localStore = localStore; + this.persistence = persistence; + } + async backfill(maxDocumentsToProcess = MAX_DOCUMENTS_TO_PROCESS) { + return this.persistence.runTransaction('Backfill Indexes', 'readwrite-primary', txn => this.writeIndexEntries(txn, maxDocumentsToProcess)); + } + /** Writes index entries until the cap is reached. Returns the number of documents processed. */ + writeIndexEntries(transaction, maxDocumentsToProcess) { + const processedCollectionGroups = new Set(); + let documentsRemaining = maxDocumentsToProcess; + let continueLoop = true; + return PersistencePromise.doWhile(() => continueLoop === true && documentsRemaining > 0, () => { + return this.localStore.indexManager + .getNextCollectionGroupToUpdate(transaction) + .next((collectionGroup) => { + if (collectionGroup === null || + processedCollectionGroups.has(collectionGroup)) { + continueLoop = false; + } + else { + logDebug(LOG_TAG$h, `Processing collection: ${collectionGroup}`); + return this.writeEntriesForCollectionGroup(transaction, collectionGroup, documentsRemaining).next(documentsProcessed => { + documentsRemaining -= documentsProcessed; + processedCollectionGroups.add(collectionGroup); + }); + } + }); + }).next(() => maxDocumentsToProcess - documentsRemaining); + } + /** + * Writes entries for the provided collection group. Returns the number of documents processed. + */ + writeEntriesForCollectionGroup(transaction, collectionGroup, documentsRemainingUnderCap) { + // Use the earliest offset of all field indexes to query the local cache. + return this.localStore.indexManager + .getMinOffsetFromCollectionGroup(transaction, collectionGroup) + .next(existingOffset => this.localStore.localDocuments + .getNextDocuments(transaction, collectionGroup, existingOffset, documentsRemainingUnderCap) + .next(nextBatch => { + const docs = nextBatch.changes; + return this.localStore.indexManager + .updateIndexEntries(transaction, docs) + .next(() => this.getNewOffset(existingOffset, nextBatch)) + .next(newOffset => { + logDebug(LOG_TAG$h, `Updating offset: ${newOffset}`); + return this.localStore.indexManager.updateCollectionGroup(transaction, collectionGroup, newOffset); + }) + .next(() => docs.size); + })); + } + /** Returns the next offset based on the provided documents. */ + getNewOffset(existingOffset, lookupResult) { + let maxOffset = existingOffset; + lookupResult.changes.forEach((key, document) => { + const newOffset = newIndexOffsetFromDocument(document); + if (indexOffsetComparator(newOffset, maxOffset) > 0) { + maxOffset = newOffset; + } + }); + return new IndexOffset(maxOffset.readTime, maxOffset.documentKey, Math.max(lookupResult.batchId, existingOffset.largestBatchId)); + } +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to + * exceed. All subsequent calls to next will return increasing values. If provided with a + * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as + * well as write out sequence numbers that it produces via `next()`. + */ +class ListenSequence { + constructor(previousValue, sequenceNumberSyncer) { + this.previousValue = previousValue; + if (sequenceNumberSyncer) { + sequenceNumberSyncer.sequenceNumberHandler = sequenceNumber => this.setPreviousValue(sequenceNumber); + this.writeNewSequenceNumber = sequenceNumber => sequenceNumberSyncer.writeSequenceNumber(sequenceNumber); + } + } + setPreviousValue(externalPreviousValue) { + this.previousValue = Math.max(externalPreviousValue, this.previousValue); + return this.previousValue; + } + next() { + const nextValue = ++this.previousValue; + if (this.writeNewSequenceNumber) { + this.writeNewSequenceNumber(nextValue); + } + return nextValue; + } +} +ListenSequence.INVALID = -1; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const escapeChar = '\u0001'; +const encodedSeparatorChar = '\u0001'; +const encodedNul = '\u0010'; +const encodedEscape = '\u0011'; +/** + * Encodes a resource path into a IndexedDb-compatible string form. + */ +function encodeResourcePath(path) { + let result = ''; + for (let i = 0; i < path.length; i++) { + if (result.length > 0) { + result = encodeSeparator(result); + } + result = encodeSegment(path.get(i), result); + } + return encodeSeparator(result); +} +/** Encodes a single segment of a resource path into the given result */ +function encodeSegment(segment, resultBuf) { + let result = resultBuf; + const length = segment.length; + for (let i = 0; i < length; i++) { + const c = segment.charAt(i); + switch (c) { + case '\0': + result += escapeChar + encodedNul; + break; + case escapeChar: + result += escapeChar + encodedEscape; + break; + default: + result += c; + } + } + return result; +} +/** Encodes a path separator into the given result */ +function encodeSeparator(result) { + return result + escapeChar + encodedSeparatorChar; +} +/** + * Decodes the given IndexedDb-compatible string form of a resource path into + * a ResourcePath instance. Note that this method is not suitable for use with + * decoding resource names from the server; those are One Platform format + * strings. + */ +function decodeResourcePath(path) { + // Event the empty path must encode as a path of at least length 2. A path + // with exactly 2 must be the empty path. + const length = path.length; + hardAssert(length >= 2, 0xfb98, { path }); + if (length === 2) { + hardAssert(path.charAt(0) === escapeChar && path.charAt(1) === encodedSeparatorChar, 0xdb51, { path }); + return ResourcePath.emptyPath(); + } + // Escape characters cannot exist past the second-to-last position in the + // source value. + const lastReasonableEscapeIndex = length - 2; + const segments = []; + let segmentBuilder = ''; + for (let start = 0; start < length;) { + // The last two characters of a valid encoded path must be a separator, so + // there must be an end to this segment. + const end = path.indexOf(escapeChar, start); + if (end < 0 || end > lastReasonableEscapeIndex) { + fail(0xc553, { path }); + } + const next = path.charAt(end + 1); + switch (next) { + case encodedSeparatorChar: + const currentPiece = path.substring(start, end); + let segment; + if (segmentBuilder.length === 0) { + // Avoid copying for the common case of a segment that excludes \0 + // and \001 + segment = currentPiece; + } + else { + segmentBuilder += currentPiece; + segment = segmentBuilder; + segmentBuilder = ''; + } + segments.push(segment); + break; + case encodedNul: + segmentBuilder += path.substring(start, end); + segmentBuilder += '\0'; + break; + case encodedEscape: + // The escape character can be used in the output to encode itself. + segmentBuilder += path.substring(start, end + 1); + break; + default: + fail(0xeeef, { path }); + } + start = end + 2; + } + return new ResourcePath(segments); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const DbRemoteDocumentStore$1 = 'remoteDocuments'; + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Name of the IndexedDb object store. + * + * Note that the name 'owner' is chosen to ensure backwards compatibility with + * older clients that only supported single locked access to the persistence + * layer. + */ +const DbPrimaryClientStore = 'owner'; +/** + * The key string used for the single object that exists in the + * DbPrimaryClient store. + */ +const DbPrimaryClientKey = 'owner'; +/** Name of the IndexedDb object store. */ +const DbMutationQueueStore = 'mutationQueues'; +/** Keys are automatically assigned via the userId property. */ +const DbMutationQueueKeyPath = 'userId'; +/** Name of the IndexedDb object store. */ +const DbMutationBatchStore = 'mutations'; +/** Keys are automatically assigned via the userId, batchId properties. */ +const DbMutationBatchKeyPath = 'batchId'; +/** The index name for lookup of mutations by user. */ +const DbMutationBatchUserMutationsIndex = 'userMutationsIndex'; +/** The user mutations index is keyed by [userId, batchId] pairs. */ +const DbMutationBatchUserMutationsKeyPath = ['userId', 'batchId']; +/** + * Creates a [userId] key for use in the DbDocumentMutations index to iterate + * over all of a user's document mutations. + */ +function newDbDocumentMutationPrefixForUser(userId) { + return [userId]; +} +/** + * Creates a [userId, encodedPath] key for use in the DbDocumentMutations + * index to iterate over all at document mutations for a given path or lower. + */ +function newDbDocumentMutationPrefixForPath(userId, path) { + return [userId, encodeResourcePath(path)]; +} +/** + * Creates a full index key of [userId, encodedPath, batchId] for inserting + * and deleting into the DbDocumentMutations index. + */ +function newDbDocumentMutationKey(userId, path, batchId) { + return [userId, encodeResourcePath(path), batchId]; +} +/** + * Because we store all the useful information for this store in the key, + * there is no useful information to store as the value. The raw (unencoded) + * path cannot be stored because IndexedDb doesn't store prototype + * information. + */ +const DbDocumentMutationPlaceholder = {}; +const DbDocumentMutationStore = 'documentMutations'; +const DbRemoteDocumentStore = 'remoteDocumentsV14'; +/** + * The primary key of the remote documents store, which allows for efficient + * access by collection path and read time. + */ +const DbRemoteDocumentKeyPath = [ + 'prefixPath', + 'collectionGroup', + 'readTime', + 'documentId' +]; +/** An index that provides access to documents by key. */ +const DbRemoteDocumentDocumentKeyIndex = 'documentKeyIndex'; +const DbRemoteDocumentDocumentKeyIndexPath = [ + 'prefixPath', + 'collectionGroup', + 'documentId' +]; +/** + * An index that provides access to documents by collection group and read + * time. + * + * This index is used by the index backfiller. + */ +const DbRemoteDocumentCollectionGroupIndex = 'collectionGroupIndex'; +const DbRemoteDocumentCollectionGroupIndexPath = [ + 'collectionGroup', + 'readTime', + 'prefixPath', + 'documentId' +]; +const DbRemoteDocumentGlobalStore = 'remoteDocumentGlobal'; +const DbRemoteDocumentGlobalKey = 'remoteDocumentGlobalKey'; +const DbTargetStore = 'targets'; +/** Keys are automatically assigned via the targetId property. */ +const DbTargetKeyPath = 'targetId'; +/** The name of the queryTargets index. */ +const DbTargetQueryTargetsIndexName = 'queryTargetsIndex'; +/** + * The index of all canonicalIds to the targets that they match. This is not + * a unique mapping because canonicalId does not promise a unique name for all + * possible queries, so we append the targetId to make the mapping unique. + */ +const DbTargetQueryTargetsKeyPath = ['canonicalId', 'targetId']; +/** Name of the IndexedDb object store. */ +const DbTargetDocumentStore = 'targetDocuments'; +/** Keys are automatically assigned via the targetId, path properties. */ +const DbTargetDocumentKeyPath = ['targetId', 'path']; +/** The index name for the reverse index. */ +const DbTargetDocumentDocumentTargetsIndex = 'documentTargetsIndex'; +/** We also need to create the reverse index for these properties. */ +const DbTargetDocumentDocumentTargetsKeyPath = ['path', 'targetId']; +/** + * The key string used for the single object that exists in the + * DbTargetGlobal store. + */ +const DbTargetGlobalKey = 'targetGlobalKey'; +const DbTargetGlobalStore = 'targetGlobal'; +/** Name of the IndexedDb object store. */ +const DbCollectionParentStore = 'collectionParents'; +/** Keys are automatically assigned via the collectionId, parent properties. */ +const DbCollectionParentKeyPath = ['collectionId', 'parent']; +/** Name of the IndexedDb object store. */ +const DbClientMetadataStore = 'clientMetadata'; +/** Keys are automatically assigned via the clientId properties. */ +const DbClientMetadataKeyPath = 'clientId'; +/** Name of the IndexedDb object store. */ +const DbBundleStore = 'bundles'; +const DbBundleKeyPath = 'bundleId'; +/** Name of the IndexedDb object store. */ +const DbNamedQueryStore = 'namedQueries'; +const DbNamedQueryKeyPath = 'name'; +/** Name of the IndexedDb object store. */ +const DbIndexConfigurationStore = 'indexConfiguration'; +const DbIndexConfigurationKeyPath = 'indexId'; +/** + * An index that provides access to the index configurations by collection + * group. + * + * PORTING NOTE: iOS and Android maintain this index in-memory, but this is + * not possible here as the Web client supports concurrent access to + * persistence via multi-tab. + */ +const DbIndexConfigurationCollectionGroupIndex = 'collectionGroupIndex'; +const DbIndexConfigurationCollectionGroupIndexPath = 'collectionGroup'; +/** Name of the IndexedDb object store. */ +const DbIndexStateStore = 'indexState'; +const DbIndexStateKeyPath = ['indexId', 'uid']; +/** + * An index that provides access to documents in a collection sorted by last + * update time. Used by the backfiller. + * + * PORTING NOTE: iOS and Android maintain this index in-memory, but this is + * not possible here as the Web client supports concurrent access to + * persistence via multi-tab. + */ +const DbIndexStateSequenceNumberIndex = 'sequenceNumberIndex'; +const DbIndexStateSequenceNumberIndexPath = ['uid', 'sequenceNumber']; +/** Name of the IndexedDb object store. */ +const DbIndexEntryStore = 'indexEntries'; +const DbIndexEntryKeyPath = [ + 'indexId', + 'uid', + 'arrayValue', + 'directionalValue', + 'orderedDocumentKey', + 'documentKey' +]; +const DbIndexEntryDocumentKeyIndex = 'documentKeyIndex'; +const DbIndexEntryDocumentKeyIndexPath = [ + 'indexId', + 'uid', + 'orderedDocumentKey' +]; +/** Name of the IndexedDb object store. */ +const DbDocumentOverlayStore = 'documentOverlays'; +const DbDocumentOverlayKeyPath = [ + 'userId', + 'collectionPath', + 'documentId' +]; +const DbDocumentOverlayCollectionPathOverlayIndex = 'collectionPathOverlayIndex'; +const DbDocumentOverlayCollectionPathOverlayIndexPath = [ + 'userId', + 'collectionPath', + 'largestBatchId' +]; +const DbDocumentOverlayCollectionGroupOverlayIndex = 'collectionGroupOverlayIndex'; +const DbDocumentOverlayCollectionGroupOverlayIndexPath = [ + 'userId', + 'collectionGroup', + 'largestBatchId' +]; +/** Name of the IndexedDb object store. */ +const DbGlobalsStore = 'globals'; +const DbGlobalsKeyPath = 'name'; +// Visible for testing +const V1_STORES = [ + DbMutationQueueStore, + DbMutationBatchStore, + DbDocumentMutationStore, + DbRemoteDocumentStore$1, + DbTargetStore, + DbPrimaryClientStore, + DbTargetGlobalStore, + DbTargetDocumentStore +]; +// Visible for testing +const V3_STORES = V1_STORES; +// Note: DbRemoteDocumentChanges is no longer used and dropped with v9. +const V4_STORES = [...V3_STORES, DbClientMetadataStore]; +const V6_STORES = [...V4_STORES, DbRemoteDocumentGlobalStore]; +const V8_STORES = [...V6_STORES, DbCollectionParentStore]; +const V11_STORES = [...V8_STORES, DbBundleStore, DbNamedQueryStore]; +const V12_STORES = [...V11_STORES, DbDocumentOverlayStore]; +const V13_STORES = [ + DbMutationQueueStore, + DbMutationBatchStore, + DbDocumentMutationStore, + DbRemoteDocumentStore, + DbTargetStore, + DbPrimaryClientStore, + DbTargetGlobalStore, + DbTargetDocumentStore, + DbClientMetadataStore, + DbRemoteDocumentGlobalStore, + DbCollectionParentStore, + DbBundleStore, + DbNamedQueryStore, + DbDocumentOverlayStore +]; +const V14_STORES = V13_STORES; +const V15_STORES = [ + ...V14_STORES, + DbIndexConfigurationStore, + DbIndexStateStore, + DbIndexEntryStore +]; +const V16_STORES = V15_STORES; +const V17_STORES = [...V15_STORES, DbGlobalsStore]; +const V18_STORES = V17_STORES; +/** Returns the object stores for the provided schema. */ +function getObjectStores(schemaVersion) { + if (schemaVersion === 18) { + return V18_STORES; + } + else if (schemaVersion === 17) { + return V17_STORES; + } + else if (schemaVersion === 16) { + return V16_STORES; + } + else if (schemaVersion === 15) { + return V15_STORES; + } + else if (schemaVersion === 14) { + return V14_STORES; + } + else if (schemaVersion === 13) { + return V13_STORES; + } + else if (schemaVersion === 12) { + return V12_STORES; + } + else if (schemaVersion === 11) { + return V11_STORES; + } + else { + fail(0xeb55); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class IndexedDbTransaction extends PersistenceTransaction { + constructor(simpleDbTransaction, currentSequenceNumber) { + super(); + this.simpleDbTransaction = simpleDbTransaction; + this.currentSequenceNumber = currentSequenceNumber; + } +} +function getStore(txn, store) { + const indexedDbTransaction = debugCast(txn); + return SimpleDb.getStore(indexedDbTransaction.simpleDbTransaction, store); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function objectSize(obj) { + let count = 0; + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + count++; + } + } + return count; +} +function forEach(obj, fn) { + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + fn(key, obj[key]); + } + } +} +function mapToArray(obj, fn) { + const result = []; + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + result.push(fn(obj[key], key, obj)); + } + } + return result; +} +function isEmpty(obj) { + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + return false; + } + } + return true; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// An immutable sorted map implementation, based on a Left-leaning Red-Black +// tree. +class SortedMap { + constructor(comparator, root) { + this.comparator = comparator; + this.root = root ? root : LLRBNode.EMPTY; + } + // Returns a copy of the map, with the specified key/value added or replaced. + insert(key, value) { + return new SortedMap(this.comparator, this.root + .insert(key, value, this.comparator) + .copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns a copy of the map, with the specified key removed. + remove(key) { + return new SortedMap(this.comparator, this.root + .remove(key, this.comparator) + .copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns the value of the node with the given key, or null. + get(key) { + let node = this.root; + while (!node.isEmpty()) { + const cmp = this.comparator(key, node.key); + if (cmp === 0) { + return node.value; + } + else if (cmp < 0) { + node = node.left; + } + else if (cmp > 0) { + node = node.right; + } + } + return null; + } + // Returns the index of the element in this sorted map, or -1 if it doesn't + // exist. + indexOf(key) { + // Number of nodes that were pruned when descending right + let prunedNodes = 0; + let node = this.root; + while (!node.isEmpty()) { + const cmp = this.comparator(key, node.key); + if (cmp === 0) { + return prunedNodes + node.left.size; + } + else if (cmp < 0) { + node = node.left; + } + else { + // Count all nodes left of the node plus the node itself + prunedNodes += node.left.size + 1; + node = node.right; + } + } + // Node not found + return -1; + } + isEmpty() { + return this.root.isEmpty(); + } + // Returns the total number of nodes in the map. + get size() { + return this.root.size; + } + // Returns the minimum key in the map. + minKey() { + return this.root.minKey(); + } + // Returns the maximum key in the map. + maxKey() { + return this.root.maxKey(); + } + // Traverses the map in key order and calls the specified action function + // for each key/value pair. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(action) { + return this.root.inorderTraversal(action); + } + forEach(fn) { + this.inorderTraversal((k, v) => { + fn(k, v); + return false; + }); + } + toString() { + const descriptions = []; + this.inorderTraversal((k, v) => { + descriptions.push(`${k}:${v}`); + return false; + }); + return `{${descriptions.join(', ')}}`; + } + // Traverses the map in reverse key order and calls the specified action + // function for each key/value pair. If action returns true, traversal is + // aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(action) { + return this.root.reverseTraversal(action); + } + // Returns an iterator over the SortedMap. + getIterator() { + return new SortedMapIterator(this.root, null, this.comparator, false); + } + getIteratorFrom(key) { + return new SortedMapIterator(this.root, key, this.comparator, false); + } + getReverseIterator() { + return new SortedMapIterator(this.root, null, this.comparator, true); + } + getReverseIteratorFrom(key) { + return new SortedMapIterator(this.root, key, this.comparator, true); + } +} // end SortedMap +// An iterator over an LLRBNode. +class SortedMapIterator { + constructor(node, startKey, comparator, isReverse) { + this.isReverse = isReverse; + this.nodeStack = []; + let cmp = 1; + while (!node.isEmpty()) { + cmp = startKey ? comparator(node.key, startKey) : 1; + // flip the comparison if we're going in reverse + if (startKey && isReverse) { + cmp *= -1; + } + if (cmp < 0) { + // This node is less than our start key. ignore it + if (this.isReverse) { + node = node.left; + } + else { + node = node.right; + } + } + else if (cmp === 0) { + // This node is exactly equal to our start key. Push it on the stack, + // but stop iterating; + this.nodeStack.push(node); + break; + } + else { + // This node is greater than our start key, add it to the stack and move + // to the next one + this.nodeStack.push(node); + if (this.isReverse) { + node = node.right; + } + else { + node = node.left; + } + } + } + } + getNext() { + let node = this.nodeStack.pop(); + const result = { key: node.key, value: node.value }; + if (this.isReverse) { + node = node.left; + while (!node.isEmpty()) { + this.nodeStack.push(node); + node = node.right; + } + } + else { + node = node.right; + while (!node.isEmpty()) { + this.nodeStack.push(node); + node = node.left; + } + } + return result; + } + hasNext() { + return this.nodeStack.length > 0; + } + peek() { + if (this.nodeStack.length === 0) { + return null; + } + const node = this.nodeStack[this.nodeStack.length - 1]; + return { key: node.key, value: node.value }; + } +} // end SortedMapIterator +// Represents a node in a Left-leaning Red-Black tree. +class LLRBNode { + constructor(key, value, color, left, right) { + this.key = key; + this.value = value; + this.color = color != null ? color : LLRBNode.RED; + this.left = left != null ? left : LLRBNode.EMPTY; + this.right = right != null ? right : LLRBNode.EMPTY; + this.size = this.left.size + 1 + this.right.size; + } + // Returns a copy of the current node, optionally replacing pieces of it. + copy(key, value, color, left, right) { + return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right); + } + isEmpty() { + return false; + } + // Traverses the tree in key order and calls the specified action function + // for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(action) { + return (this.left.inorderTraversal(action) || + action(this.key, this.value) || + this.right.inorderTraversal(action)); + } + // Traverses the tree in reverse key order and calls the specified action + // function for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(action) { + return (this.right.reverseTraversal(action) || + action(this.key, this.value) || + this.left.reverseTraversal(action)); + } + // Returns the minimum node in the tree. + min() { + if (this.left.isEmpty()) { + return this; + } + else { + return this.left.min(); + } + } + // Returns the maximum key in the tree. + minKey() { + return this.min().key; + } + // Returns the maximum key in the tree. + maxKey() { + if (this.right.isEmpty()) { + return this.key; + } + else { + return this.right.maxKey(); + } + } + // Returns new tree, with the key/value added. + insert(key, value, comparator) { + let n = this; + const cmp = comparator(key, n.key); + if (cmp < 0) { + n = n.copy(null, null, null, n.left.insert(key, value, comparator), null); + } + else if (cmp === 0) { + n = n.copy(null, value, null, null, null); + } + else { + n = n.copy(null, null, null, null, n.right.insert(key, value, comparator)); + } + return n.fixUp(); + } + removeMin() { + if (this.left.isEmpty()) { + return LLRBNode.EMPTY; + } + let n = this; + if (!n.left.isRed() && !n.left.left.isRed()) { + n = n.moveRedLeft(); + } + n = n.copy(null, null, null, n.left.removeMin(), null); + return n.fixUp(); + } + // Returns new tree, with the specified item removed. + remove(key, comparator) { + let smallest; + let n = this; + if (comparator(key, n.key) < 0) { + if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) { + n = n.moveRedLeft(); + } + n = n.copy(null, null, null, n.left.remove(key, comparator), null); + } + else { + if (n.left.isRed()) { + n = n.rotateRight(); + } + if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) { + n = n.moveRedRight(); + } + if (comparator(key, n.key) === 0) { + if (n.right.isEmpty()) { + return LLRBNode.EMPTY; + } + else { + smallest = n.right.min(); + n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin()); + } + } + n = n.copy(null, null, null, null, n.right.remove(key, comparator)); + } + return n.fixUp(); + } + isRed() { + return this.color; + } + // Returns new tree after performing any needed rotations. + fixUp() { + let n = this; + if (n.right.isRed() && !n.left.isRed()) { + n = n.rotateLeft(); + } + if (n.left.isRed() && n.left.left.isRed()) { + n = n.rotateRight(); + } + if (n.left.isRed() && n.right.isRed()) { + n = n.colorFlip(); + } + return n; + } + moveRedLeft() { + let n = this.colorFlip(); + if (n.right.left.isRed()) { + n = n.copy(null, null, null, null, n.right.rotateRight()); + n = n.rotateLeft(); + n = n.colorFlip(); + } + return n; + } + moveRedRight() { + let n = this.colorFlip(); + if (n.left.left.isRed()) { + n = n.rotateRight(); + n = n.colorFlip(); + } + return n; + } + rotateLeft() { + const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left); + return this.right.copy(null, null, this.color, nl, null); + } + rotateRight() { + const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null); + return this.left.copy(null, null, this.color, null, nr); + } + colorFlip() { + const left = this.left.copy(null, null, !this.left.color, null, null); + const right = this.right.copy(null, null, !this.right.color, null, null); + return this.copy(null, null, !this.color, left, right); + } + // For testing. + checkMaxDepth() { + const blackDepth = this.check(); + if (Math.pow(2.0, blackDepth) <= this.size + 1) { + return true; + } + else { + return false; + } + } + // In a balanced RB tree, the black-depth (number of black nodes) from root to + // leaves is equal on both sides. This function verifies that or asserts. + check() { + if (this.isRed() && this.left.isRed()) { + throw fail(0xaad2, { + key: this.key, + value: this.value + }); + } + if (this.right.isRed()) { + throw fail(0x3721, { + key: this.key, + value: this.value + }); + } + const blackDepth = this.left.check(); + if (blackDepth !== this.right.check()) { + throw fail(0x6d2d); + } + else { + return blackDepth + (this.isRed() ? 0 : 1); + } + } +} // end LLRBNode +// Empty node is shared between all LLRB trees. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +LLRBNode.EMPTY = null; +LLRBNode.RED = true; +LLRBNode.BLACK = false; +// Represents an empty node (a leaf node in the Red-Black Tree). +class LLRBEmptyNode { + constructor() { + this.size = 0; + } + get key() { + throw fail(0xe1a6); + } + get value() { + throw fail(0x3f0d); + } + get color() { + throw fail(0x4157); + } + get left() { + throw fail(0x741e); + } + get right() { + throw fail(0x901e); + } + // Returns a copy of the current node. + copy(key, value, color, left, right) { + return this; + } + // Returns a copy of the tree, with the specified key/value added. + insert(key, value, comparator) { + return new LLRBNode(key, value); + } + // Returns a copy of the tree, with the specified key removed. + remove(key, comparator) { + return this; + } + isEmpty() { + return true; + } + inorderTraversal(action) { + return false; + } + reverseTraversal(action) { + return false; + } + minKey() { + return null; + } + maxKey() { + return null; + } + isRed() { + return false; + } + // For testing. + checkMaxDepth() { + return true; + } + check() { + return 0; + } +} // end LLRBEmptyNode +LLRBNode.EMPTY = new LLRBEmptyNode(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * SortedSet is an immutable (copy-on-write) collection that holds elements + * in order specified by the provided comparator. + * + * NOTE: if provided comparator returns 0 for two elements, we consider them to + * be equal! + */ +class SortedSet { + constructor(comparator) { + this.comparator = comparator; + this.data = new SortedMap(this.comparator); + } + has(elem) { + return this.data.get(elem) !== null; + } + first() { + return this.data.minKey(); + } + last() { + return this.data.maxKey(); + } + get size() { + return this.data.size; + } + indexOf(elem) { + return this.data.indexOf(elem); + } + /** Iterates elements in order defined by "comparator" */ + forEach(cb) { + this.data.inorderTraversal((k, v) => { + cb(k); + return false; + }); + } + /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ + forEachInRange(range, cb) { + const iter = this.data.getIteratorFrom(range[0]); + while (iter.hasNext()) { + const elem = iter.getNext(); + if (this.comparator(elem.key, range[1]) >= 0) { + return; + } + cb(elem.key); + } + } + /** + * Iterates over `elem`s such that: start <= elem until false is returned. + */ + forEachWhile(cb, start) { + let iter; + if (start !== undefined) { + iter = this.data.getIteratorFrom(start); + } + else { + iter = this.data.getIterator(); + } + while (iter.hasNext()) { + const elem = iter.getNext(); + const result = cb(elem.key); + if (!result) { + return; + } + } + } + /** Finds the least element greater than or equal to `elem`. */ + firstAfterOrEqual(elem) { + const iter = this.data.getIteratorFrom(elem); + return iter.hasNext() ? iter.getNext().key : null; + } + getIterator() { + return new SortedSetIterator(this.data.getIterator()); + } + getIteratorFrom(key) { + return new SortedSetIterator(this.data.getIteratorFrom(key)); + } + /** Inserts or updates an element */ + add(elem) { + return this.copy(this.data.remove(elem).insert(elem, true)); + } + /** Deletes an element */ + delete(elem) { + if (!this.has(elem)) { + return this; + } + return this.copy(this.data.remove(elem)); + } + isEmpty() { + return this.data.isEmpty(); + } + unionWith(other) { + let result = this; + // Make sure `result` always refers to the larger one of the two sets. + if (result.size < other.size) { + result = other; + other = this; + } + other.forEach(elem => { + result = result.add(elem); + }); + return result; + } + isEqual(other) { + if (!(other instanceof SortedSet)) { + return false; + } + if (this.size !== other.size) { + return false; + } + const thisIt = this.data.getIterator(); + const otherIt = other.data.getIterator(); + while (thisIt.hasNext()) { + const thisElem = thisIt.getNext().key; + const otherElem = otherIt.getNext().key; + if (this.comparator(thisElem, otherElem) !== 0) { + return false; + } + } + return true; + } + toArray() { + const res = []; + this.forEach(targetId => { + res.push(targetId); + }); + return res; + } + toString() { + const result = []; + this.forEach(elem => result.push(elem)); + return 'SortedSet(' + result.toString() + ')'; + } + copy(data) { + const result = new SortedSet(this.comparator); + result.data = data; + return result; + } +} +class SortedSetIterator { + constructor(iter) { + this.iter = iter; + } + getNext() { + return this.iter.getNext().key; + } + hasNext() { + return this.iter.hasNext(); + } +} +/** + * Compares two sorted sets for equality using their natural ordering. The + * method computes the intersection and invokes `onAdd` for every element that + * is in `after` but not `before`. `onRemove` is invoked for every element in + * `before` but missing from `after`. + * + * The method creates a copy of both `before` and `after` and runs in O(n log + * n), where n is the size of the two lists. + * + * @param before - The elements that exist in the original set. + * @param after - The elements to diff against the original set. + * @param comparator - The comparator for the elements in before and after. + * @param onAdd - A function to invoke for every element that is part of ` + * after` but not `before`. + * @param onRemove - A function to invoke for every element that is part of + * `before` but not `after`. + */ +function diffSortedSets(before, after, comparator, onAdd, onRemove) { + const beforeIt = before.getIterator(); + const afterIt = after.getIterator(); + let beforeValue = advanceIterator(beforeIt); + let afterValue = advanceIterator(afterIt); + // Walk through the two sets at the same time, using the ordering defined by + // `comparator`. + while (beforeValue || afterValue) { + let added = false; + let removed = false; + if (beforeValue && afterValue) { + const cmp = comparator(beforeValue, afterValue); + if (cmp < 0) { + // The element was removed if the next element in our ordered + // walkthrough is only in `before`. + removed = true; + } + else if (cmp > 0) { + // The element was added if the next element in our ordered walkthrough + // is only in `after`. + added = true; + } + } + else if (beforeValue != null) { + removed = true; + } + else { + added = true; + } + if (added) { + onAdd(afterValue); + afterValue = advanceIterator(afterIt); + } + else if (removed) { + onRemove(beforeValue); + beforeValue = advanceIterator(beforeIt); + } + else { + beforeValue = advanceIterator(beforeIt); + afterValue = advanceIterator(afterIt); + } + } +} +/** + * Returns the next element from the iterator or `undefined` if none available. + */ +function advanceIterator(it) { + return it.hasNext() ? it.getNext() : undefined; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provides a set of fields that can be used to partially patch a document. + * FieldMask is used in conjunction with ObjectValue. + * Examples: + * foo - Overwrites foo entirely with the provided value. If foo is not + * present in the companion ObjectValue, the field is deleted. + * foo.bar - Overwrites only the field bar of the object foo. + * If foo is not an object, foo is replaced with an object + * containing foo + */ +class FieldMask { + constructor(fields) { + this.fields = fields; + // TODO(dimond): validation of FieldMask + // Sort the field mask to support `FieldMask.isEqual()` and assert below. + fields.sort(FieldPath$1.comparator); + } + static empty() { + return new FieldMask([]); + } + /** + * Returns a new FieldMask object that is the result of adding all the given + * fields paths to this field mask. + */ + unionWith(extraFields) { + let mergedMaskSet = new SortedSet(FieldPath$1.comparator); + for (const fieldPath of this.fields) { + mergedMaskSet = mergedMaskSet.add(fieldPath); + } + for (const fieldPath of extraFields) { + mergedMaskSet = mergedMaskSet.add(fieldPath); + } + return new FieldMask(mergedMaskSet.toArray()); + } + /** + * Verifies that `fieldPath` is included by at least one field in this field + * mask. + * + * This is an O(n) operation, where `n` is the size of the field mask. + */ + covers(fieldPath) { + for (const fieldMaskPath of this.fields) { + if (fieldMaskPath.isPrefixOf(fieldPath)) { + return true; + } + } + return false; + } + isEqual(other) { + return arrayEquals(this.fields, other.fields, (l, r) => l.isEqual(r)); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Converts a Base64 encoded string to a binary string. */ +function decodeBase64(encoded) { + // Note: We used to validate the base64 string here via a regular expression. + // This was removed to improve the performance of indexing. + return Buffer.from(encoded, 'base64').toString('binary'); +} +/** Converts a binary string to a Base64 encoded string. */ +function encodeBase64(raw) { + return Buffer.from(raw, 'binary').toString('base64'); +} +/** True if and only if the Base64 conversion functions are available. */ +function isBase64Available() { + return true; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Immutable class that represents a "proto" byte string. + * + * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when + * sent on the wire. This class abstracts away this differentiation by holding + * the proto byte string in a common class that must be converted into a string + * before being sent as a proto. + * @internal + */ +class ByteString { + constructor(binaryString) { + this.binaryString = binaryString; + } + static fromBase64String(base64) { + const binaryString = decodeBase64(base64); + return new ByteString(binaryString); + } + static fromUint8Array(array) { + // TODO(indexing); Remove the copy of the byte string here as this method + // is frequently called during indexing. + const binaryString = binaryStringFromUint8Array(array); + return new ByteString(binaryString); + } + [Symbol.iterator]() { + let i = 0; + return { + next: () => { + if (i < this.binaryString.length) { + return { value: this.binaryString.charCodeAt(i++), done: false }; + } + else { + return { value: undefined, done: true }; + } + } + }; + } + toBase64() { + return encodeBase64(this.binaryString); + } + toUint8Array() { + return uint8ArrayFromBinaryString(this.binaryString); + } + approximateByteSize() { + return this.binaryString.length * 2; + } + compareTo(other) { + return primitiveComparator(this.binaryString, other.binaryString); + } + isEqual(other) { + return this.binaryString === other.binaryString; + } +} +ByteString.EMPTY_BYTE_STRING = new ByteString(''); +/** + * Helper function to convert an Uint8array to a binary string. + */ +function binaryStringFromUint8Array(array) { + let binaryString = ''; + for (let i = 0; i < array.length; ++i) { + binaryString += String.fromCharCode(array[i]); + } + return binaryString; +} +/** + * Helper function to convert a binary string to an Uint8Array. + */ +function uint8ArrayFromBinaryString(binaryString) { + const buffer = new Uint8Array(binaryString.length); + for (let i = 0; i < binaryString.length; i++) { + buffer[i] = binaryString.charCodeAt(i); + } + return buffer; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// A RegExp matching ISO 8601 UTC timestamps with optional fraction. +const ISO_TIMESTAMP_REG_EXP = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/); +/** + * Converts the possible Proto values for a timestamp value into a "seconds and + * nanos" representation. + */ +function normalizeTimestamp(date) { + hardAssert(!!date, 0x986a); + // The json interface (for the browser) will return an iso timestamp string, + // while the proto js library (for node) will return a + // google.protobuf.Timestamp instance. + if (typeof date === 'string') { + // The date string can have higher precision (nanos) than the Date class + // (millis), so we do some custom parsing here. + // Parse the nanos right out of the string. + let nanos = 0; + const fraction = ISO_TIMESTAMP_REG_EXP.exec(date); + hardAssert(!!fraction, 0xb5de, { + timestamp: date + }); + if (fraction[1]) { + // Pad the fraction out to 9 digits (nanos). + let nanoStr = fraction[1]; + nanoStr = (nanoStr + '000000000').substr(0, 9); + nanos = Number(nanoStr); + } + // Parse the date to get the seconds. + const parsedDate = new Date(date); + const seconds = Math.floor(parsedDate.getTime() / 1000); + return { seconds, nanos }; + } + else { + // TODO(b/37282237): Use strings for Proto3 timestamps + // assert(!this.options.useProto3Json, + // 'The timestamp instance format requires Proto JS.'); + const seconds = normalizeNumber(date.seconds); + const nanos = normalizeNumber(date.nanos); + return { seconds, nanos }; + } +} +/** + * Converts the possible Proto types for numbers into a JavaScript number. + * Returns 0 if the value is not numeric. + */ +function normalizeNumber(value) { + // TODO(bjornick): Handle int64 greater than 53 bits. + if (typeof value === 'number') { + return value; + } + else if (typeof value === 'string') { + return Number(value); + } + else { + return 0; + } +} +/** Converts the possible Proto types for Blobs into a ByteString. */ +function normalizeByteString(blob) { + if (typeof blob === 'string') { + return ByteString.fromBase64String(blob); + } + else { + return ByteString.fromUint8Array(blob); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a locally-applied ServerTimestamp. + * + * Server Timestamps are backed by MapValues that contain an internal field + * `__type__` with a value of `server_timestamp`. The previous value and local + * write time are stored in its `__previous_value__` and `__local_write_time__` + * fields respectively. + * + * Notes: + * - ServerTimestampValue instances are created as the result of applying a + * transform. They can only exist in the local view of a document. Therefore + * they do not need to be parsed or serialized. + * - When evaluated locally (e.g. for snapshot.data()), they by default + * evaluate to `null`. This behavior can be configured by passing custom + * FieldValueOptions to value(). + * - With respect to other ServerTimestampValues, they sort by their + * localWriteTime. + */ +const SERVER_TIMESTAMP_SENTINEL = 'server_timestamp'; +const TYPE_KEY$1 = '__type__'; +const PREVIOUS_VALUE_KEY = '__previous_value__'; +const LOCAL_WRITE_TIME_KEY = '__local_write_time__'; +function isServerTimestamp(value) { + const type = (value?.mapValue?.fields || {})[TYPE_KEY$1]?.stringValue; + return type === SERVER_TIMESTAMP_SENTINEL; +} +/** + * Creates a new ServerTimestamp proto value (using the internal format). + */ +function serverTimestamp$1(localWriteTime, previousValue) { + const mapValue = { + fields: { + [TYPE_KEY$1]: { + stringValue: SERVER_TIMESTAMP_SENTINEL + }, + [LOCAL_WRITE_TIME_KEY]: { + timestampValue: { + seconds: localWriteTime.seconds, + nanos: localWriteTime.nanoseconds + } + } + } + }; + // We should avoid storing deeply nested server timestamp map values + // because we never use the intermediate "previous values". + // For example: + // previous: 42L, add: t1, result: t1 -> 42L + // previous: t1, add: t2, result: t2 -> 42L (NOT t2 -> t1 -> 42L) + // previous: t2, add: t3, result: t3 -> 42L (NOT t3 -> t2 -> t1 -> 42L) + // `getPreviousValue` recursively traverses server timestamps to find the + // least recent Value. + if (previousValue && isServerTimestamp(previousValue)) { + previousValue = getPreviousValue(previousValue); + } + if (previousValue) { + mapValue.fields[PREVIOUS_VALUE_KEY] = previousValue; + } + return { mapValue }; +} +/** + * Returns the value of the field before this ServerTimestamp was set. + * + * Preserving the previous values allows the user to display the last resoled + * value until the backend responds with the timestamp. + */ +function getPreviousValue(value) { + const previousValue = value.mapValue.fields[PREVIOUS_VALUE_KEY]; + if (isServerTimestamp(previousValue)) { + return getPreviousValue(previousValue); + } + return previousValue; +} +/** + * Returns the local time at which this timestamp was first set. + */ +function getLocalWriteTime(value) { + const localWriteTime = normalizeTimestamp(value.mapValue.fields[LOCAL_WRITE_TIME_KEY].timestampValue); + return new Timestamp(localWriteTime.seconds, localWriteTime.nanos); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class DatabaseInfo { + /** + * Constructs a DatabaseInfo using the provided host, databaseId and + * persistenceKey. + * + * @param databaseId - The database to use. + * @param appId - The Firebase App Id. + * @param persistenceKey - A unique identifier for this Firestore's local + * storage (used in conjunction with the databaseId). + * @param host - The Firestore backend host to connect to. + * @param ssl - Whether to use SSL when connecting. + * @param forceLongPolling - Whether to use the forceLongPolling option + * when using WebChannel as the network transport. + * @param autoDetectLongPolling - Whether to use the detectBufferingProxy + * option when using WebChannel as the network transport. + * @param longPollingOptions Options that configure long-polling. + * @param useFetchStreams Whether to use the Fetch API instead of + * XMLHTTPRequest + */ + constructor(databaseId, appId, persistenceKey, host, ssl, forceLongPolling, autoDetectLongPolling, longPollingOptions, useFetchStreams, isUsingEmulator) { + this.databaseId = databaseId; + this.appId = appId; + this.persistenceKey = persistenceKey; + this.host = host; + this.ssl = ssl; + this.forceLongPolling = forceLongPolling; + this.autoDetectLongPolling = autoDetectLongPolling; + this.longPollingOptions = longPollingOptions; + this.useFetchStreams = useFetchStreams; + this.isUsingEmulator = isUsingEmulator; + } +} +/** The default database name for a project. */ +const DEFAULT_DATABASE_NAME = '(default)'; +/** + * Represents the database ID a Firestore client is associated with. + * @internal + */ +class DatabaseId { + constructor(projectId, database) { + this.projectId = projectId; + this.database = database ? database : DEFAULT_DATABASE_NAME; + } + static empty() { + return new DatabaseId('', ''); + } + get isDefaultDatabase() { + return this.database === DEFAULT_DATABASE_NAME; + } + isEqual(other) { + return (other instanceof DatabaseId && + other.projectId === this.projectId && + other.database === this.database); + } +} +function databaseIdFromApp(app, database) { + if (!Object.prototype.hasOwnProperty.apply(app.options, ['projectId'])) { + throw new FirestoreError(Code.INVALID_ARGUMENT, '"projectId" not provided in firebase.initializeApp.'); + } + return new DatabaseId(app.options.projectId, database); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Sentinel value that sorts before any Mutation Batch ID. */ +const BATCHID_UNKNOWN = -1; +/** + * Returns whether a variable is either undefined or null. + */ +function isNullOrUndefined(value) { + return value === null || value === undefined; +} +/** Returns whether the value represents -0. */ +function isNegativeZero(value) { + // Detect if the value is -0.0. Based on polyfill from + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is + return value === 0 && 1 / value === 1 / -0; +} +/** + * Returns whether a value is an integer and in the safe integer range + * @param value - The value to test for being an integer and in the safe range + */ +function isSafeInteger(value) { + return (typeof value === 'number' && + Number.isInteger(value) && + !isNegativeZero(value) && + value <= Number.MAX_SAFE_INTEGER && + value >= Number.MIN_SAFE_INTEGER); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const TYPE_KEY = '__type__'; +const MAX_VALUE_TYPE = '__max__'; +const MAX_VALUE = { + mapValue: { + fields: { + '__type__': { stringValue: MAX_VALUE_TYPE } + } + } +}; +const VECTOR_VALUE_SENTINEL = '__vector__'; +const VECTOR_MAP_VECTORS_KEY = 'value'; +const MIN_VALUE = { + nullValue: 'NULL_VALUE' +}; +/** Extracts the backend's type order for the provided value. */ +function typeOrder(value) { + if ('nullValue' in value) { + return 0 /* TypeOrder.NullValue */; + } + else if ('booleanValue' in value) { + return 1 /* TypeOrder.BooleanValue */; + } + else if ('integerValue' in value || 'doubleValue' in value) { + return 2 /* TypeOrder.NumberValue */; + } + else if ('timestampValue' in value) { + return 3 /* TypeOrder.TimestampValue */; + } + else if ('stringValue' in value) { + return 5 /* TypeOrder.StringValue */; + } + else if ('bytesValue' in value) { + return 6 /* TypeOrder.BlobValue */; + } + else if ('referenceValue' in value) { + return 7 /* TypeOrder.RefValue */; + } + else if ('geoPointValue' in value) { + return 8 /* TypeOrder.GeoPointValue */; + } + else if ('arrayValue' in value) { + return 9 /* TypeOrder.ArrayValue */; + } + else if ('mapValue' in value) { + if (isServerTimestamp(value)) { + return 4 /* TypeOrder.ServerTimestampValue */; + } + else if (isMaxValue(value)) { + return 9007199254740991 /* TypeOrder.MaxValue */; + } + else if (isVectorValue(value)) { + return 10 /* TypeOrder.VectorValue */; + } + return 11 /* TypeOrder.ObjectValue */; + } + else { + return fail(0x6e87, { value }); + } +} +/** Tests `left` and `right` for equality based on the backend semantics. */ +function valueEquals(left, right) { + if (left === right) { + return true; + } + const leftType = typeOrder(left); + const rightType = typeOrder(right); + if (leftType !== rightType) { + return false; + } + switch (leftType) { + case 0 /* TypeOrder.NullValue */: + return true; + case 1 /* TypeOrder.BooleanValue */: + return left.booleanValue === right.booleanValue; + case 4 /* TypeOrder.ServerTimestampValue */: + return getLocalWriteTime(left).isEqual(getLocalWriteTime(right)); + case 3 /* TypeOrder.TimestampValue */: + return timestampEquals(left, right); + case 5 /* TypeOrder.StringValue */: + return left.stringValue === right.stringValue; + case 6 /* TypeOrder.BlobValue */: + return blobEquals(left, right); + case 7 /* TypeOrder.RefValue */: + return left.referenceValue === right.referenceValue; + case 8 /* TypeOrder.GeoPointValue */: + return geoPointEquals(left, right); + case 2 /* TypeOrder.NumberValue */: + return numberEquals(left, right); + case 9 /* TypeOrder.ArrayValue */: + return arrayEquals(left.arrayValue.values || [], right.arrayValue.values || [], valueEquals); + case 10 /* TypeOrder.VectorValue */: + case 11 /* TypeOrder.ObjectValue */: + return objectEquals(left, right); + case 9007199254740991 /* TypeOrder.MaxValue */: + return true; + default: + return fail(0xcbf8, { left }); + } +} +function timestampEquals(left, right) { + if (typeof left.timestampValue === 'string' && + typeof right.timestampValue === 'string' && + left.timestampValue.length === right.timestampValue.length) { + // Use string equality for ISO 8601 timestamps + return left.timestampValue === right.timestampValue; + } + const leftTimestamp = normalizeTimestamp(left.timestampValue); + const rightTimestamp = normalizeTimestamp(right.timestampValue); + return (leftTimestamp.seconds === rightTimestamp.seconds && + leftTimestamp.nanos === rightTimestamp.nanos); +} +function geoPointEquals(left, right) { + return (normalizeNumber(left.geoPointValue.latitude) === + normalizeNumber(right.geoPointValue.latitude) && + normalizeNumber(left.geoPointValue.longitude) === + normalizeNumber(right.geoPointValue.longitude)); +} +function blobEquals(left, right) { + return normalizeByteString(left.bytesValue).isEqual(normalizeByteString(right.bytesValue)); +} +function numberEquals(left, right) { + if ('integerValue' in left && 'integerValue' in right) { + return (normalizeNumber(left.integerValue) === normalizeNumber(right.integerValue)); + } + else if ('doubleValue' in left && 'doubleValue' in right) { + const n1 = normalizeNumber(left.doubleValue); + const n2 = normalizeNumber(right.doubleValue); + if (n1 === n2) { + return isNegativeZero(n1) === isNegativeZero(n2); + } + else { + return isNaN(n1) && isNaN(n2); + } + } + return false; +} +function objectEquals(left, right) { + const leftMap = left.mapValue.fields || {}; + const rightMap = right.mapValue.fields || {}; + if (objectSize(leftMap) !== objectSize(rightMap)) { + return false; + } + for (const key in leftMap) { + if (leftMap.hasOwnProperty(key)) { + if (rightMap[key] === undefined || + !valueEquals(leftMap[key], rightMap[key])) { + return false; + } + } + } + return true; +} +/** Returns true if the ArrayValue contains the specified element. */ +function arrayValueContains(haystack, needle) { + return ((haystack.values || []).find(v => valueEquals(v, needle)) !== undefined); +} +function valueCompare(left, right) { + if (left === right) { + return 0; + } + const leftType = typeOrder(left); + const rightType = typeOrder(right); + if (leftType !== rightType) { + return primitiveComparator(leftType, rightType); + } + switch (leftType) { + case 0 /* TypeOrder.NullValue */: + case 9007199254740991 /* TypeOrder.MaxValue */: + return 0; + case 1 /* TypeOrder.BooleanValue */: + return primitiveComparator(left.booleanValue, right.booleanValue); + case 2 /* TypeOrder.NumberValue */: + return compareNumbers(left, right); + case 3 /* TypeOrder.TimestampValue */: + return compareTimestamps(left.timestampValue, right.timestampValue); + case 4 /* TypeOrder.ServerTimestampValue */: + return compareTimestamps(getLocalWriteTime(left), getLocalWriteTime(right)); + case 5 /* TypeOrder.StringValue */: + return compareUtf8Strings(left.stringValue, right.stringValue); + case 6 /* TypeOrder.BlobValue */: + return compareBlobs(left.bytesValue, right.bytesValue); + case 7 /* TypeOrder.RefValue */: + return compareReferences(left.referenceValue, right.referenceValue); + case 8 /* TypeOrder.GeoPointValue */: + return compareGeoPoints(left.geoPointValue, right.geoPointValue); + case 9 /* TypeOrder.ArrayValue */: + return compareArrays(left.arrayValue, right.arrayValue); + case 10 /* TypeOrder.VectorValue */: + return compareVectors(left.mapValue, right.mapValue); + case 11 /* TypeOrder.ObjectValue */: + return compareMaps(left.mapValue, right.mapValue); + default: + throw fail(0x5ae0, { leftType }); + } +} +function compareNumbers(left, right) { + const leftNumber = normalizeNumber(left.integerValue || left.doubleValue); + const rightNumber = normalizeNumber(right.integerValue || right.doubleValue); + if (leftNumber < rightNumber) { + return -1; + } + else if (leftNumber > rightNumber) { + return 1; + } + else if (leftNumber === rightNumber) { + return 0; + } + else { + // one or both are NaN. + if (isNaN(leftNumber)) { + return isNaN(rightNumber) ? 0 : -1; + } + else { + return 1; + } + } +} +function compareTimestamps(left, right) { + if (typeof left === 'string' && + typeof right === 'string' && + left.length === right.length) { + return primitiveComparator(left, right); + } + const leftTimestamp = normalizeTimestamp(left); + const rightTimestamp = normalizeTimestamp(right); + const comparison = primitiveComparator(leftTimestamp.seconds, rightTimestamp.seconds); + if (comparison !== 0) { + return comparison; + } + return primitiveComparator(leftTimestamp.nanos, rightTimestamp.nanos); +} +function compareReferences(leftPath, rightPath) { + const leftSegments = leftPath.split('/'); + const rightSegments = rightPath.split('/'); + for (let i = 0; i < leftSegments.length && i < rightSegments.length; i++) { + const comparison = primitiveComparator(leftSegments[i], rightSegments[i]); + if (comparison !== 0) { + return comparison; + } + } + return primitiveComparator(leftSegments.length, rightSegments.length); +} +function compareGeoPoints(left, right) { + const comparison = primitiveComparator(normalizeNumber(left.latitude), normalizeNumber(right.latitude)); + if (comparison !== 0) { + return comparison; + } + return primitiveComparator(normalizeNumber(left.longitude), normalizeNumber(right.longitude)); +} +function compareBlobs(left, right) { + const leftBytes = normalizeByteString(left); + const rightBytes = normalizeByteString(right); + return leftBytes.compareTo(rightBytes); +} +function compareArrays(left, right) { + const leftArray = left.values || []; + const rightArray = right.values || []; + for (let i = 0; i < leftArray.length && i < rightArray.length; ++i) { + const compare = valueCompare(leftArray[i], rightArray[i]); + if (compare) { + return compare; + } + } + return primitiveComparator(leftArray.length, rightArray.length); +} +function compareVectors(left, right) { + const leftMap = left.fields || {}; + const rightMap = right.fields || {}; + // The vector is a map, but only vector value is compared. + const leftArrayValue = leftMap[VECTOR_MAP_VECTORS_KEY]?.arrayValue; + const rightArrayValue = rightMap[VECTOR_MAP_VECTORS_KEY]?.arrayValue; + const lengthCompare = primitiveComparator(leftArrayValue?.values?.length || 0, rightArrayValue?.values?.length || 0); + if (lengthCompare !== 0) { + return lengthCompare; + } + return compareArrays(leftArrayValue, rightArrayValue); +} +function compareMaps(left, right) { + if (left === MAX_VALUE.mapValue && right === MAX_VALUE.mapValue) { + return 0; + } + else if (left === MAX_VALUE.mapValue) { + return 1; + } + else if (right === MAX_VALUE.mapValue) { + return -1; + } + const leftMap = left.fields || {}; + const leftKeys = Object.keys(leftMap); + const rightMap = right.fields || {}; + const rightKeys = Object.keys(rightMap); + // Even though MapValues are likely sorted correctly based on their insertion + // order (e.g. when received from the backend), local modifications can bring + // elements out of order. We need to re-sort the elements to ensure that + // canonical IDs are independent of insertion order. + leftKeys.sort(); + rightKeys.sort(); + for (let i = 0; i < leftKeys.length && i < rightKeys.length; ++i) { + const keyCompare = compareUtf8Strings(leftKeys[i], rightKeys[i]); + if (keyCompare !== 0) { + return keyCompare; + } + const compare = valueCompare(leftMap[leftKeys[i]], rightMap[rightKeys[i]]); + if (compare !== 0) { + return compare; + } + } + return primitiveComparator(leftKeys.length, rightKeys.length); +} +/** + * Generates the canonical ID for the provided field value (as used in Target + * serialization). + */ +function canonicalId(value) { + return canonifyValue(value); +} +function canonifyValue(value) { + if ('nullValue' in value) { + return 'null'; + } + else if ('booleanValue' in value) { + return '' + value.booleanValue; + } + else if ('integerValue' in value) { + return '' + value.integerValue; + } + else if ('doubleValue' in value) { + return '' + value.doubleValue; + } + else if ('timestampValue' in value) { + return canonifyTimestamp(value.timestampValue); + } + else if ('stringValue' in value) { + return value.stringValue; + } + else if ('bytesValue' in value) { + return canonifyByteString(value.bytesValue); + } + else if ('referenceValue' in value) { + return canonifyReference(value.referenceValue); + } + else if ('geoPointValue' in value) { + return canonifyGeoPoint(value.geoPointValue); + } + else if ('arrayValue' in value) { + return canonifyArray(value.arrayValue); + } + else if ('mapValue' in value) { + return canonifyMap(value.mapValue); + } + else { + return fail(0xee4d, { value }); + } +} +function canonifyByteString(byteString) { + return normalizeByteString(byteString).toBase64(); +} +function canonifyTimestamp(timestamp) { + const normalizedTimestamp = normalizeTimestamp(timestamp); + return `time(${normalizedTimestamp.seconds},${normalizedTimestamp.nanos})`; +} +function canonifyGeoPoint(geoPoint) { + return `geo(${geoPoint.latitude},${geoPoint.longitude})`; +} +function canonifyReference(referenceValue) { + return DocumentKey.fromName(referenceValue).toString(); +} +function canonifyMap(mapValue) { + // Iteration order in JavaScript is not guaranteed. To ensure that we generate + // matching canonical IDs for identical maps, we need to sort the keys. + const sortedKeys = Object.keys(mapValue.fields || {}).sort(); + let result = '{'; + let first = true; + for (const key of sortedKeys) { + if (!first) { + result += ','; + } + else { + first = false; + } + result += `${key}:${canonifyValue(mapValue.fields[key])}`; + } + return result + '}'; +} +function canonifyArray(arrayValue) { + let result = '['; + let first = true; + for (const value of arrayValue.values || []) { + if (!first) { + result += ','; + } + else { + first = false; + } + result += canonifyValue(value); + } + return result + ']'; +} +/** + * Returns an approximate (and wildly inaccurate) in-memory size for the field + * value. + * + * The memory size takes into account only the actual user data as it resides + * in memory and ignores object overhead. + */ +function estimateByteSize(value) { + switch (typeOrder(value)) { + case 0 /* TypeOrder.NullValue */: + return 4; + case 1 /* TypeOrder.BooleanValue */: + return 4; + case 2 /* TypeOrder.NumberValue */: + return 8; + case 3 /* TypeOrder.TimestampValue */: + // Timestamps are made up of two distinct numbers (seconds + nanoseconds) + return 16; + case 4 /* TypeOrder.ServerTimestampValue */: + const previousValue = getPreviousValue(value); + return previousValue ? 16 + estimateByteSize(previousValue) : 16; + case 5 /* TypeOrder.StringValue */: + // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures: + // "JavaScript's String type is [...] a set of elements of 16-bit unsigned + // integer values" + return value.stringValue.length * 2; + case 6 /* TypeOrder.BlobValue */: + return normalizeByteString(value.bytesValue).approximateByteSize(); + case 7 /* TypeOrder.RefValue */: + return value.referenceValue.length; + case 8 /* TypeOrder.GeoPointValue */: + // GeoPoints are made up of two distinct numbers (latitude + longitude) + return 16; + case 9 /* TypeOrder.ArrayValue */: + return estimateArrayByteSize(value.arrayValue); + case 10 /* TypeOrder.VectorValue */: + case 11 /* TypeOrder.ObjectValue */: + return estimateMapByteSize(value.mapValue); + default: + throw fail(0x34ae, { value }); + } +} +function estimateMapByteSize(mapValue) { + let size = 0; + forEach(mapValue.fields, (key, val) => { + size += key.length + estimateByteSize(val); + }); + return size; +} +function estimateArrayByteSize(arrayValue) { + return (arrayValue.values || []).reduce((previousSize, value) => previousSize + estimateByteSize(value), 0); +} +/** Returns a reference value for the provided database and key. */ +function refValue(databaseId, key) { + return { + referenceValue: `projects/${databaseId.projectId}/databases/${databaseId.database}/documents/${key.path.canonicalString()}` + }; +} +/** Returns true if `value` is an IntegerValue . */ +function isInteger(value) { + return !!value && 'integerValue' in value; +} +/** Returns true if `value` is a DoubleValue. */ +function isDouble(value) { + return !!value && 'doubleValue' in value; +} +/** Returns true if `value` is either an IntegerValue or a DoubleValue. */ +function isNumber(value) { + return isInteger(value) || isDouble(value); +} +/** Returns true if `value` is an ArrayValue. */ +function isArray(value) { + return !!value && 'arrayValue' in value; +} +/** Returns true if `value` is a NullValue. */ +function isNullValue(value) { + return !!value && 'nullValue' in value; +} +/** Returns true if `value` is NaN. */ +function isNanValue(value) { + return !!value && 'doubleValue' in value && isNaN(Number(value.doubleValue)); +} +/** Returns true if `value` is a MapValue. */ +function isMapValue(value) { + return !!value && 'mapValue' in value; +} +/** Returns true if `value` is a VetorValue. */ +function isVectorValue(value) { + const type = (value?.mapValue?.fields || {})[TYPE_KEY]?.stringValue; + return type === VECTOR_VALUE_SENTINEL; +} +/** Creates a deep copy of `source`. */ +function deepClone(source) { + if (source.geoPointValue) { + return { geoPointValue: { ...source.geoPointValue } }; + } + else if (source.timestampValue && + typeof source.timestampValue === 'object') { + return { timestampValue: { ...source.timestampValue } }; + } + else if (source.mapValue) { + const target = { mapValue: { fields: {} } }; + forEach(source.mapValue.fields, (key, val) => (target.mapValue.fields[key] = deepClone(val))); + return target; + } + else if (source.arrayValue) { + const target = { arrayValue: { values: [] } }; + for (let i = 0; i < (source.arrayValue.values || []).length; ++i) { + target.arrayValue.values[i] = deepClone(source.arrayValue.values[i]); + } + return target; + } + else { + return { ...source }; + } +} +/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ +function isMaxValue(value) { + return ((((value.mapValue || {}).fields || {})['__type__'] || {}).stringValue === + MAX_VALUE_TYPE); +} +const MIN_VECTOR_VALUE = { + mapValue: { + fields: { + [TYPE_KEY]: { stringValue: VECTOR_VALUE_SENTINEL }, + [VECTOR_MAP_VECTORS_KEY]: { + arrayValue: {} + } + } + } +}; +/** Returns the lowest value for the given value type (inclusive). */ +function valuesGetLowerBound(value) { + if ('nullValue' in value) { + return MIN_VALUE; + } + else if ('booleanValue' in value) { + return { booleanValue: false }; + } + else if ('integerValue' in value || 'doubleValue' in value) { + return { doubleValue: NaN }; + } + else if ('timestampValue' in value) { + return { timestampValue: { seconds: Number.MIN_SAFE_INTEGER } }; + } + else if ('stringValue' in value) { + return { stringValue: '' }; + } + else if ('bytesValue' in value) { + return { bytesValue: '' }; + } + else if ('referenceValue' in value) { + return refValue(DatabaseId.empty(), DocumentKey.empty()); + } + else if ('geoPointValue' in value) { + return { geoPointValue: { latitude: -90, longitude: -180 } }; + } + else if ('arrayValue' in value) { + return { arrayValue: {} }; + } + else if ('mapValue' in value) { + if (isVectorValue(value)) { + return MIN_VECTOR_VALUE; + } + return { mapValue: {} }; + } + else { + return fail(0x8c66, { value }); + } +} +/** Returns the largest value for the given value type (exclusive). */ +function valuesGetUpperBound(value) { + if ('nullValue' in value) { + return { booleanValue: false }; + } + else if ('booleanValue' in value) { + return { doubleValue: NaN }; + } + else if ('integerValue' in value || 'doubleValue' in value) { + return { timestampValue: { seconds: Number.MIN_SAFE_INTEGER } }; + } + else if ('timestampValue' in value) { + return { stringValue: '' }; + } + else if ('stringValue' in value) { + return { bytesValue: '' }; + } + else if ('bytesValue' in value) { + return refValue(DatabaseId.empty(), DocumentKey.empty()); + } + else if ('referenceValue' in value) { + return { geoPointValue: { latitude: -90, longitude: -180 } }; + } + else if ('geoPointValue' in value) { + return { arrayValue: {} }; + } + else if ('arrayValue' in value) { + return MIN_VECTOR_VALUE; + } + else if ('mapValue' in value) { + if (isVectorValue(value)) { + return { mapValue: {} }; + } + return MAX_VALUE; + } + else { + return fail(0xf207, { value }); + } +} +function lowerBoundCompare(left, right) { + const cmp = valueCompare(left.value, right.value); + if (cmp !== 0) { + return cmp; + } + if (left.inclusive && !right.inclusive) { + return -1; + } + else if (!left.inclusive && right.inclusive) { + return 1; + } + return 0; +} +function upperBoundCompare(left, right) { + const cmp = valueCompare(left.value, right.value); + if (cmp !== 0) { + return cmp; + } + if (left.inclusive && !right.inclusive) { + return 1; + } + else if (!left.inclusive && right.inclusive) { + return -1; + } + return 0; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An ObjectValue represents a MapValue in the Firestore Proto and offers the + * ability to add and remove fields (via the ObjectValueBuilder). + */ +class ObjectValue { + constructor(value) { + this.value = value; + } + static empty() { + return new ObjectValue({ mapValue: {} }); + } + /** + * Returns the value at the given path or null. + * + * @param path - the path to search + * @returns The value at the path or null if the path is not set. + */ + field(path) { + if (path.isEmpty()) { + return this.value; + } + else { + let currentLevel = this.value; + for (let i = 0; i < path.length - 1; ++i) { + currentLevel = (currentLevel.mapValue.fields || {})[path.get(i)]; + if (!isMapValue(currentLevel)) { + return null; + } + } + currentLevel = (currentLevel.mapValue.fields || {})[path.lastSegment()]; + return currentLevel || null; + } + } + /** + * Sets the field to the provided value. + * + * @param path - The field path to set. + * @param value - The value to set. + */ + set(path, value) { + const fieldsMap = this.getFieldsMap(path.popLast()); + fieldsMap[path.lastSegment()] = deepClone(value); + } + /** + * Sets the provided fields to the provided values. + * + * @param data - A map of fields to values (or null for deletes). + */ + setAll(data) { + let parent = FieldPath$1.emptyPath(); + let upserts = {}; + let deletes = []; + data.forEach((value, path) => { + if (!parent.isImmediateParentOf(path)) { + // Insert the accumulated changes at this parent location + const fieldsMap = this.getFieldsMap(parent); + this.applyChanges(fieldsMap, upserts, deletes); + upserts = {}; + deletes = []; + parent = path.popLast(); + } + if (value) { + upserts[path.lastSegment()] = deepClone(value); + } + else { + deletes.push(path.lastSegment()); + } + }); + const fieldsMap = this.getFieldsMap(parent); + this.applyChanges(fieldsMap, upserts, deletes); + } + /** + * Removes the field at the specified path. If there is no field at the + * specified path, nothing is changed. + * + * @param path - The field path to remove. + */ + delete(path) { + const nestedValue = this.field(path.popLast()); + if (isMapValue(nestedValue) && nestedValue.mapValue.fields) { + delete nestedValue.mapValue.fields[path.lastSegment()]; + } + } + isEqual(other) { + return valueEquals(this.value, other.value); + } + /** + * Returns the map that contains the leaf element of `path`. If the parent + * entry does not yet exist, or if it is not a map, a new map will be created. + */ + getFieldsMap(path) { + let current = this.value; + if (!current.mapValue.fields) { + current.mapValue = { fields: {} }; + } + for (let i = 0; i < path.length; ++i) { + let next = current.mapValue.fields[path.get(i)]; + if (!isMapValue(next) || !next.mapValue.fields) { + next = { mapValue: { fields: {} } }; + current.mapValue.fields[path.get(i)] = next; + } + current = next; + } + return current.mapValue.fields; + } + /** + * Modifies `fieldsMap` by adding, replacing or deleting the specified + * entries. + */ + applyChanges(fieldsMap, inserts, deletes) { + forEach(inserts, (key, val) => (fieldsMap[key] = val)); + for (const field of deletes) { + delete fieldsMap[field]; + } + } + clone() { + return new ObjectValue(deepClone(this.value)); + } +} +/** + * Returns a FieldMask built from all fields in a MapValue. + */ +function extractFieldMask(value) { + const fields = []; + forEach(value.fields, (key, value) => { + const currentPath = new FieldPath$1([key]); + if (isMapValue(value)) { + const nestedMask = extractFieldMask(value.mapValue); + const nestedFields = nestedMask.fields; + if (nestedFields.length === 0) { + // Preserve the empty map by adding it to the FieldMask. + fields.push(currentPath); + } + else { + // For nested and non-empty ObjectValues, add the FieldPath of the + // leaf nodes. + for (const nestedPath of nestedFields) { + fields.push(currentPath.child(nestedPath)); + } + } + } + else { + // For nested and non-empty ObjectValues, add the FieldPath of the leaf + // nodes. + fields.push(currentPath); + } + }); + return new FieldMask(fields); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a document in Firestore with a key, version, data and whether it + * has local mutations applied to it. + * + * Documents can transition between states via `convertToFoundDocument()`, + * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does + * not transition to one of these states even after all mutations have been + * applied, `isValidDocument()` returns false and the document should be removed + * from all views. + */ +class MutableDocument { + constructor(key, documentType, version, readTime, createTime, data, documentState) { + this.key = key; + this.documentType = documentType; + this.version = version; + this.readTime = readTime; + this.createTime = createTime; + this.data = data; + this.documentState = documentState; + } + /** + * Creates a document with no known version or data, but which can serve as + * base document for mutations. + */ + static newInvalidDocument(documentKey) { + return new MutableDocument(documentKey, 0 /* DocumentType.INVALID */, + /* version */ SnapshotVersion.min(), + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist with the given data at the + * given version. + */ + static newFoundDocument(documentKey, version, createTime, value) { + return new MutableDocument(documentKey, 1 /* DocumentType.FOUND_DOCUMENT */, + /* version */ version, + /* readTime */ SnapshotVersion.min(), + /* createTime */ createTime, value, 0 /* DocumentState.SYNCED */); + } + /** Creates a new document that is known to not exist at the given version. */ + static newNoDocument(documentKey, version) { + return new MutableDocument(documentKey, 2 /* DocumentType.NO_DOCUMENT */, + /* version */ version, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist at the given version but + * whose data is not known (e.g. a document that was updated without a known + * base document). + */ + static newUnknownDocument(documentKey, version) { + return new MutableDocument(documentKey, 3 /* DocumentType.UNKNOWN_DOCUMENT */, + /* version */ version, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */); + } + /** + * Changes the document type to indicate that it exists and that its version + * and data are known. + */ + convertToFoundDocument(version, value) { + // If a document is switching state from being an invalid or deleted + // document to a valid (FOUND_DOCUMENT) document, either due to receiving an + // update from Watch or due to applying a local set mutation on top + // of a deleted document, our best guess about its createTime would be the + // version at which the document transitioned to a FOUND_DOCUMENT. + if (this.createTime.isEqual(SnapshotVersion.min()) && + (this.documentType === 2 /* DocumentType.NO_DOCUMENT */ || + this.documentType === 0 /* DocumentType.INVALID */)) { + this.createTime = version; + } + this.version = version; + this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */; + this.data = value; + this.documentState = 0 /* DocumentState.SYNCED */; + return this; + } + /** + * Changes the document type to indicate that it doesn't exist at the given + * version. + */ + convertToNoDocument(version) { + this.version = version; + this.documentType = 2 /* DocumentType.NO_DOCUMENT */; + this.data = ObjectValue.empty(); + this.documentState = 0 /* DocumentState.SYNCED */; + return this; + } + /** + * Changes the document type to indicate that it exists at a given version but + * that its data is not known (e.g. a document that was updated without a known + * base document). + */ + convertToUnknownDocument(version) { + this.version = version; + this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */; + this.data = ObjectValue.empty(); + this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */; + return this; + } + setHasCommittedMutations() { + this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */; + return this; + } + setHasLocalMutations() { + this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */; + this.version = SnapshotVersion.min(); + return this; + } + setReadTime(readTime) { + this.readTime = readTime; + return this; + } + get hasLocalMutations() { + return this.documentState === 1 /* DocumentState.HAS_LOCAL_MUTATIONS */; + } + get hasCommittedMutations() { + return this.documentState === 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */; + } + get hasPendingWrites() { + return this.hasLocalMutations || this.hasCommittedMutations; + } + isValidDocument() { + return this.documentType !== 0 /* DocumentType.INVALID */; + } + isFoundDocument() { + return this.documentType === 1 /* DocumentType.FOUND_DOCUMENT */; + } + isNoDocument() { + return this.documentType === 2 /* DocumentType.NO_DOCUMENT */; + } + isUnknownDocument() { + return this.documentType === 3 /* DocumentType.UNKNOWN_DOCUMENT */; + } + isEqual(other) { + return (other instanceof MutableDocument && + this.key.isEqual(other.key) && + this.version.isEqual(other.version) && + this.documentType === other.documentType && + this.documentState === other.documentState && + this.data.isEqual(other.data)); + } + mutableCopy() { + return new MutableDocument(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState); + } + toString() { + return (`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, ` + + `{createTime: ${this.createTime}}), ` + + `{documentType: ${this.documentType}}), ` + + `{documentState: ${this.documentState}})`); + } +} +/** + * Compares the value for field `field` in the provided documents. Throws if + * the field does not exist in both documents. + */ +function compareDocumentsByField(field, d1, d2) { + const v1 = d1.data.field(field); + const v2 = d2.data.field(field); + if (v1 !== null && v2 !== null) { + return valueCompare(v1, v2); + } + else { + return fail(0xa786); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a bound of a query. + * + * The bound is specified with the given components representing a position and + * whether it's just before or just after the position (relative to whatever the + * query order is). + * + * The position represents a logical index position for a query. It's a prefix + * of values for the (potentially implicit) order by clauses of a query. + * + * Bound provides a function to determine whether a document comes before or + * after a bound. This is influenced by whether the position is just before or + * just after the provided values. + */ +class Bound { + constructor(position, inclusive) { + this.position = position; + this.inclusive = inclusive; + } +} +function boundCompareToDocument(bound, orderBy, doc) { + let comparison = 0; + for (let i = 0; i < bound.position.length; i++) { + const orderByComponent = orderBy[i]; + const component = bound.position[i]; + if (orderByComponent.field.isKeyField()) { + comparison = DocumentKey.comparator(DocumentKey.fromName(component.referenceValue), doc.key); + } + else { + const docValue = doc.data.field(orderByComponent.field); + comparison = valueCompare(component, docValue); + } + if (orderByComponent.dir === "desc" /* Direction.DESCENDING */) { + comparison = comparison * -1; + } + if (comparison !== 0) { + break; + } + } + return comparison; +} +/** + * Returns true if a document sorts after a bound using the provided sort + * order. + */ +function boundSortsAfterDocument(bound, orderBy, doc) { + const comparison = boundCompareToDocument(bound, orderBy, doc); + return bound.inclusive ? comparison >= 0 : comparison > 0; +} +/** + * Returns true if a document sorts before a bound using the provided sort + * order. + */ +function boundSortsBeforeDocument(bound, orderBy, doc) { + const comparison = boundCompareToDocument(bound, orderBy, doc); + return bound.inclusive ? comparison <= 0 : comparison < 0; +} +function boundEquals(left, right) { + if (left === null) { + return right === null; + } + else if (right === null) { + return false; + } + if (left.inclusive !== right.inclusive || + left.position.length !== right.position.length) { + return false; + } + for (let i = 0; i < left.position.length; i++) { + const leftPosition = left.position[i]; + const rightPosition = right.position[i]; + if (!valueEquals(leftPosition, rightPosition)) { + return false; + } + } + return true; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An ordering on a field, in some Direction. Direction defaults to ASCENDING. + */ +class OrderBy { + constructor(field, dir = "asc" /* Direction.ASCENDING */) { + this.field = field; + this.dir = dir; + } +} +function canonifyOrderBy(orderBy) { + // TODO(b/29183165): Make this collision robust. + return orderBy.field.canonicalString() + orderBy.dir; +} +function stringifyOrderBy(orderBy) { + return `${orderBy.field.canonicalString()} (${orderBy.dir})`; +} +function orderByEquals(left, right) { + return left.dir === right.dir && left.field.isEqual(right.field); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Filter { +} +class FieldFilter extends Filter { + constructor(field, op, value) { + super(); + this.field = field; + this.op = op; + this.value = value; + } + /** + * Creates a filter based on the provided arguments. + */ + static create(field, op, value) { + if (field.isKeyField()) { + if (op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */) { + return this.createKeyFieldInFilter(field, op, value); + } + else { + return new KeyFieldFilter(field, op, value); + } + } + else if (op === "array-contains" /* Operator.ARRAY_CONTAINS */) { + return new ArrayContainsFilter(field, value); + } + else if (op === "in" /* Operator.IN */) { + return new InFilter(field, value); + } + else if (op === "not-in" /* Operator.NOT_IN */) { + return new NotInFilter(field, value); + } + else if (op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) { + return new ArrayContainsAnyFilter(field, value); + } + else { + return new FieldFilter(field, op, value); + } + } + static createKeyFieldInFilter(field, op, value) { + return op === "in" /* Operator.IN */ + ? new KeyFieldInFilter(field, value) + : new KeyFieldNotInFilter(field, value); + } + matches(doc) { + const other = doc.data.field(this.field); + // Types do not have to match in NOT_EQUAL filters. + if (this.op === "!=" /* Operator.NOT_EQUAL */) { + return (other !== null && + other.nullValue === undefined && + this.matchesComparison(valueCompare(other, this.value))); + } + // Only compare types with matching backend order (such as double and int). + return (other !== null && + typeOrder(this.value) === typeOrder(other) && + this.matchesComparison(valueCompare(other, this.value))); + } + matchesComparison(comparison) { + switch (this.op) { + case "<" /* Operator.LESS_THAN */: + return comparison < 0; + case "<=" /* Operator.LESS_THAN_OR_EQUAL */: + return comparison <= 0; + case "==" /* Operator.EQUAL */: + return comparison === 0; + case "!=" /* Operator.NOT_EQUAL */: + return comparison !== 0; + case ">" /* Operator.GREATER_THAN */: + return comparison > 0; + case ">=" /* Operator.GREATER_THAN_OR_EQUAL */: + return comparison >= 0; + default: + return fail(0xb8a2, { + operator: this.op + }); + } + } + isInequality() { + return ([ + "<" /* Operator.LESS_THAN */, + "<=" /* Operator.LESS_THAN_OR_EQUAL */, + ">" /* Operator.GREATER_THAN */, + ">=" /* Operator.GREATER_THAN_OR_EQUAL */, + "!=" /* Operator.NOT_EQUAL */, + "not-in" /* Operator.NOT_IN */ + ].indexOf(this.op) >= 0); + } + getFlattenedFilters() { + return [this]; + } + getFilters() { + return [this]; + } +} +class CompositeFilter extends Filter { + constructor(filters, op) { + super(); + this.filters = filters; + this.op = op; + this.memoizedFlattenedFilters = null; + } + /** + * Creates a filter based on the provided arguments. + */ + static create(filters, op) { + return new CompositeFilter(filters, op); + } + matches(doc) { + if (compositeFilterIsConjunction(this)) { + // For conjunctions, all filters must match, so return false if any filter doesn't match. + return this.filters.find(filter => !filter.matches(doc)) === undefined; + } + else { + // For disjunctions, at least one filter should match. + return this.filters.find(filter => filter.matches(doc)) !== undefined; + } + } + getFlattenedFilters() { + if (this.memoizedFlattenedFilters !== null) { + return this.memoizedFlattenedFilters; + } + this.memoizedFlattenedFilters = this.filters.reduce((result, subfilter) => { + return result.concat(subfilter.getFlattenedFilters()); + }, []); + return this.memoizedFlattenedFilters; + } + // Returns a mutable copy of `this.filters` + getFilters() { + return Object.assign([], this.filters); + } +} +function compositeFilterIsConjunction(compositeFilter) { + return compositeFilter.op === "and" /* CompositeOperator.AND */; +} +function compositeFilterIsDisjunction(compositeFilter) { + return compositeFilter.op === "or" /* CompositeOperator.OR */; +} +/** + * Returns true if this filter is a conjunction of field filters only. Returns false otherwise. + */ +function compositeFilterIsFlatConjunction(compositeFilter) { + return (compositeFilterIsFlat(compositeFilter) && + compositeFilterIsConjunction(compositeFilter)); +} +/** + * Returns true if this filter does not contain any composite filters. Returns false otherwise. + */ +function compositeFilterIsFlat(compositeFilter) { + for (const filter of compositeFilter.filters) { + if (filter instanceof CompositeFilter) { + return false; + } + } + return true; +} +function canonifyFilter(filter) { + if (filter instanceof FieldFilter) { + // TODO(b/29183165): Technically, this won't be unique if two values have + // the same description, such as the int 3 and the string "3". So we should + // add the types in here somehow, too. + return (filter.field.canonicalString() + + filter.op.toString() + + canonicalId(filter.value)); + } + else if (compositeFilterIsFlatConjunction(filter)) { + // Older SDK versions use an implicit AND operation between their filters. + // In the new SDK versions, the developer may use an explicit AND filter. + // To stay consistent with the old usages, we add a special case to ensure + // the canonical ID for these two are the same. For example: + // `col.whereEquals("a", 1).whereEquals("b", 2)` should have the same + // canonical ID as `col.where(and(equals("a",1), equals("b",2)))`. + return filter.filters.map(filter => canonifyFilter(filter)).join(','); + } + else { + // filter instanceof CompositeFilter + const canonicalIdsString = filter.filters + .map(filter => canonifyFilter(filter)) + .join(','); + return `${filter.op}(${canonicalIdsString})`; + } +} +function filterEquals(f1, f2) { + if (f1 instanceof FieldFilter) { + return fieldFilterEquals(f1, f2); + } + else if (f1 instanceof CompositeFilter) { + return compositeFilterEquals(f1, f2); + } + else { + fail(0x4bef); + } +} +function fieldFilterEquals(f1, f2) { + return (f2 instanceof FieldFilter && + f1.op === f2.op && + f1.field.isEqual(f2.field) && + valueEquals(f1.value, f2.value)); +} +function compositeFilterEquals(f1, f2) { + if (f2 instanceof CompositeFilter && + f1.op === f2.op && + f1.filters.length === f2.filters.length) { + const subFiltersMatch = f1.filters.reduce((result, f1Filter, index) => result && filterEquals(f1Filter, f2.filters[index]), true); + return subFiltersMatch; + } + return false; +} +/** + * Returns a new composite filter that contains all filter from + * `compositeFilter` plus all the given filters in `otherFilters`. + */ +function compositeFilterWithAddedFilters(compositeFilter, otherFilters) { + const mergedFilters = compositeFilter.filters.concat(otherFilters); + return CompositeFilter.create(mergedFilters, compositeFilter.op); +} +/** Returns a debug description for `filter`. */ +function stringifyFilter(filter) { + if (filter instanceof FieldFilter) { + return stringifyFieldFilter(filter); + } + else if (filter instanceof CompositeFilter) { + return stringifyCompositeFilter(filter); + } + else { + return 'Filter'; + } +} +function stringifyCompositeFilter(filter) { + return (filter.op.toString() + + ` {` + + filter.getFilters().map(stringifyFilter).join(' ,') + + '}'); +} +function stringifyFieldFilter(filter) { + return `${filter.field.canonicalString()} ${filter.op} ${canonicalId(filter.value)}`; +} +/** Filter that matches on key fields (i.e. '__name__'). */ +class KeyFieldFilter extends FieldFilter { + constructor(field, op, value) { + super(field, op, value); + this.key = DocumentKey.fromName(value.referenceValue); + } + matches(doc) { + const comparison = DocumentKey.comparator(doc.key, this.key); + return this.matchesComparison(comparison); + } +} +/** Filter that matches on key fields within an array. */ +class KeyFieldInFilter extends FieldFilter { + constructor(field, value) { + super(field, "in" /* Operator.IN */, value); + this.keys = extractDocumentKeysFromArrayValue("in" /* Operator.IN */, value); + } + matches(doc) { + return this.keys.some(key => key.isEqual(doc.key)); + } +} +/** Filter that matches on key fields not present within an array. */ +class KeyFieldNotInFilter extends FieldFilter { + constructor(field, value) { + super(field, "not-in" /* Operator.NOT_IN */, value); + this.keys = extractDocumentKeysFromArrayValue("not-in" /* Operator.NOT_IN */, value); + } + matches(doc) { + return !this.keys.some(key => key.isEqual(doc.key)); + } +} +function extractDocumentKeysFromArrayValue(op, value) { + return (value.arrayValue?.values || []).map(v => { + return DocumentKey.fromName(v.referenceValue); + }); +} +/** A Filter that implements the array-contains operator. */ +class ArrayContainsFilter extends FieldFilter { + constructor(field, value) { + super(field, "array-contains" /* Operator.ARRAY_CONTAINS */, value); + } + matches(doc) { + const other = doc.data.field(this.field); + return isArray(other) && arrayValueContains(other.arrayValue, this.value); + } +} +/** A Filter that implements the IN operator. */ +class InFilter extends FieldFilter { + constructor(field, value) { + super(field, "in" /* Operator.IN */, value); + } + matches(doc) { + const other = doc.data.field(this.field); + return other !== null && arrayValueContains(this.value.arrayValue, other); + } +} +/** A Filter that implements the not-in operator. */ +class NotInFilter extends FieldFilter { + constructor(field, value) { + super(field, "not-in" /* Operator.NOT_IN */, value); + } + matches(doc) { + if (arrayValueContains(this.value.arrayValue, { nullValue: 'NULL_VALUE' })) { + return false; + } + const other = doc.data.field(this.field); + return (other !== null && + other.nullValue === undefined && + !arrayValueContains(this.value.arrayValue, other)); + } +} +/** A Filter that implements the array-contains-any operator. */ +class ArrayContainsAnyFilter extends FieldFilter { + constructor(field, value) { + super(field, "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */, value); + } + matches(doc) { + const other = doc.data.field(this.field); + if (!isArray(other) || !other.arrayValue.values) { + return false; + } + return other.arrayValue.values.some(val => arrayValueContains(this.value.arrayValue, val)); + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Visible for testing +class TargetImpl { + constructor(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) { + this.path = path; + this.collectionGroup = collectionGroup; + this.orderBy = orderBy; + this.filters = filters; + this.limit = limit; + this.startAt = startAt; + this.endAt = endAt; + this.memoizedCanonicalId = null; + } +} +/** + * Initializes a Target with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + * + * NOTE: you should always construct `Target` from `Query.toTarget` instead of + * using this factory method, because `Query` provides an implicit `orderBy` + * property. + */ +function newTarget(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) { + return new TargetImpl(path, collectionGroup, orderBy, filters, limit, startAt, endAt); +} +function canonifyTarget(target) { + const targetImpl = debugCast(target); + if (targetImpl.memoizedCanonicalId === null) { + let str = targetImpl.path.canonicalString(); + if (targetImpl.collectionGroup !== null) { + str += '|cg:' + targetImpl.collectionGroup; + } + str += '|f:'; + str += targetImpl.filters.map(f => canonifyFilter(f)).join(','); + str += '|ob:'; + str += targetImpl.orderBy.map(o => canonifyOrderBy(o)).join(','); + if (!isNullOrUndefined(targetImpl.limit)) { + str += '|l:'; + str += targetImpl.limit; + } + if (targetImpl.startAt) { + str += '|lb:'; + str += targetImpl.startAt.inclusive ? 'b:' : 'a:'; + str += targetImpl.startAt.position.map(p => canonicalId(p)).join(','); + } + if (targetImpl.endAt) { + str += '|ub:'; + str += targetImpl.endAt.inclusive ? 'a:' : 'b:'; + str += targetImpl.endAt.position.map(p => canonicalId(p)).join(','); + } + targetImpl.memoizedCanonicalId = str; + } + return targetImpl.memoizedCanonicalId; +} +function stringifyTarget(target) { + let str = target.path.canonicalString(); + if (target.collectionGroup !== null) { + str += ' collectionGroup=' + target.collectionGroup; + } + if (target.filters.length > 0) { + str += `, filters: [${target.filters + .map(f => stringifyFilter(f)) + .join(', ')}]`; + } + if (!isNullOrUndefined(target.limit)) { + str += ', limit: ' + target.limit; + } + if (target.orderBy.length > 0) { + str += `, orderBy: [${target.orderBy + .map(o => stringifyOrderBy(o)) + .join(', ')}]`; + } + if (target.startAt) { + str += ', startAt: '; + str += target.startAt.inclusive ? 'b:' : 'a:'; + str += target.startAt.position.map(p => canonicalId(p)).join(','); + } + if (target.endAt) { + str += ', endAt: '; + str += target.endAt.inclusive ? 'a:' : 'b:'; + str += target.endAt.position.map(p => canonicalId(p)).join(','); + } + return `Target(${str})`; +} +function targetEquals(left, right) { + if (left.limit !== right.limit) { + return false; + } + if (left.orderBy.length !== right.orderBy.length) { + return false; + } + for (let i = 0; i < left.orderBy.length; i++) { + if (!orderByEquals(left.orderBy[i], right.orderBy[i])) { + return false; + } + } + if (left.filters.length !== right.filters.length) { + return false; + } + for (let i = 0; i < left.filters.length; i++) { + if (!filterEquals(left.filters[i], right.filters[i])) { + return false; + } + } + if (left.collectionGroup !== right.collectionGroup) { + return false; + } + if (!left.path.isEqual(right.path)) { + return false; + } + if (!boundEquals(left.startAt, right.startAt)) { + return false; + } + return boundEquals(left.endAt, right.endAt); +} +function targetIsDocumentTarget(target) { + return (DocumentKey.isDocumentKey(target.path) && + target.collectionGroup === null && + target.filters.length === 0); +} +/** Returns the field filters that target the given field path. */ +function targetGetFieldFiltersForPath(target, path) { + return target.filters.filter(f => f instanceof FieldFilter && f.field.isEqual(path)); +} +/** + * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY + * filters. Returns `null` if there are no such filters. + */ +function targetGetArrayValues(target, fieldIndex) { + const segment = fieldIndexGetArraySegment(fieldIndex); + if (segment === undefined) { + return null; + } + for (const fieldFilter of targetGetFieldFiltersForPath(target, segment.fieldPath)) { + switch (fieldFilter.op) { + case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */: + return fieldFilter.value.arrayValue.values || []; + case "array-contains" /* Operator.ARRAY_CONTAINS */: + return [fieldFilter.value]; + // Remaining filters are not array filters. + } + } + return null; +} +/** + * Returns the list of values that are used in != or NOT_IN filters. Returns + * `null` if there are no such filters. + */ +function targetGetNotInValues(target, fieldIndex) { + const values = new Map(); + for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) { + for (const fieldFilter of targetGetFieldFiltersForPath(target, segment.fieldPath)) { + switch (fieldFilter.op) { + case "==" /* Operator.EQUAL */: + case "in" /* Operator.IN */: + // Encode equality prefix, which is encoded in the index value before + // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to + // `value != 'ab'`). + values.set(segment.fieldPath.canonicalString(), fieldFilter.value); + break; + case "not-in" /* Operator.NOT_IN */: + case "!=" /* Operator.NOT_EQUAL */: + // NotIn/NotEqual is always a suffix. There cannot be any remaining + // segments and hence we can return early here. + values.set(segment.fieldPath.canonicalString(), fieldFilter.value); + return Array.from(values.values()); + // Remaining filters cannot be used as notIn bounds. + } + } + } + return null; +} +/** + * Returns a lower bound of field values that can be used as a starting point to + * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound + * exists. + */ +function targetGetLowerBound(target, fieldIndex) { + const values = []; + let inclusive = true; + // For each segment, retrieve a lower bound if there is a suitable filter or + // startAt. + for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) { + const segmentBound = segment.kind === 0 /* IndexKind.ASCENDING */ + ? targetGetAscendingBound(target, segment.fieldPath, target.startAt) + : targetGetDescendingBound(target, segment.fieldPath, target.startAt); + values.push(segmentBound.value); + inclusive && (inclusive = segmentBound.inclusive); + } + return new Bound(values, inclusive); +} +/** + * Returns an upper bound of field values that can be used as an ending point + * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no + * upper bound exists. + */ +function targetGetUpperBound(target, fieldIndex) { + const values = []; + let inclusive = true; + // For each segment, retrieve an upper bound if there is a suitable filter or + // endAt. + for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) { + const segmentBound = segment.kind === 0 /* IndexKind.ASCENDING */ + ? targetGetDescendingBound(target, segment.fieldPath, target.endAt) + : targetGetAscendingBound(target, segment.fieldPath, target.endAt); + values.push(segmentBound.value); + inclusive && (inclusive = segmentBound.inclusive); + } + return new Bound(values, inclusive); +} +/** + * Returns the value to use as the lower bound for ascending index segment at + * the provided `fieldPath` (or the upper bound for an descending segment). + */ +function targetGetAscendingBound(target, fieldPath, bound) { + let value = MIN_VALUE; + let inclusive = true; + // Process all filters to find a value for the current field segment + for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) { + let filterValue = MIN_VALUE; + let filterInclusive = true; + switch (fieldFilter.op) { + case "<" /* Operator.LESS_THAN */: + case "<=" /* Operator.LESS_THAN_OR_EQUAL */: + filterValue = valuesGetLowerBound(fieldFilter.value); + break; + case "==" /* Operator.EQUAL */: + case "in" /* Operator.IN */: + case ">=" /* Operator.GREATER_THAN_OR_EQUAL */: + filterValue = fieldFilter.value; + break; + case ">" /* Operator.GREATER_THAN */: + filterValue = fieldFilter.value; + filterInclusive = false; + break; + case "!=" /* Operator.NOT_EQUAL */: + case "not-in" /* Operator.NOT_IN */: + filterValue = MIN_VALUE; + break; + // Remaining filters cannot be used as lower bounds. + } + if (lowerBoundCompare({ value, inclusive }, { value: filterValue, inclusive: filterInclusive }) < 0) { + value = filterValue; + inclusive = filterInclusive; + } + } + // If there is an additional bound, compare the values against the existing + // range to see if we can narrow the scope. + if (bound !== null) { + for (let i = 0; i < target.orderBy.length; ++i) { + const orderBy = target.orderBy[i]; + if (orderBy.field.isEqual(fieldPath)) { + const cursorValue = bound.position[i]; + if (lowerBoundCompare({ value, inclusive }, { value: cursorValue, inclusive: bound.inclusive }) < 0) { + value = cursorValue; + inclusive = bound.inclusive; + } + break; + } + } + } + return { value, inclusive }; +} +/** + * Returns the value to use as the upper bound for ascending index segment at + * the provided `fieldPath` (or the lower bound for a descending segment). + */ +function targetGetDescendingBound(target, fieldPath, bound) { + let value = MAX_VALUE; + let inclusive = true; + // Process all filters to find a value for the current field segment + for (const fieldFilter of targetGetFieldFiltersForPath(target, fieldPath)) { + let filterValue = MAX_VALUE; + let filterInclusive = true; + switch (fieldFilter.op) { + case ">=" /* Operator.GREATER_THAN_OR_EQUAL */: + case ">" /* Operator.GREATER_THAN */: + filterValue = valuesGetUpperBound(fieldFilter.value); + filterInclusive = false; + break; + case "==" /* Operator.EQUAL */: + case "in" /* Operator.IN */: + case "<=" /* Operator.LESS_THAN_OR_EQUAL */: + filterValue = fieldFilter.value; + break; + case "<" /* Operator.LESS_THAN */: + filterValue = fieldFilter.value; + filterInclusive = false; + break; + case "!=" /* Operator.NOT_EQUAL */: + case "not-in" /* Operator.NOT_IN */: + filterValue = MAX_VALUE; + break; + // Remaining filters cannot be used as upper bounds. + } + if (upperBoundCompare({ value, inclusive }, { value: filterValue, inclusive: filterInclusive }) > 0) { + value = filterValue; + inclusive = filterInclusive; + } + } + // If there is an additional bound, compare the values against the existing + // range to see if we can narrow the scope. + if (bound !== null) { + for (let i = 0; i < target.orderBy.length; ++i) { + const orderBy = target.orderBy[i]; + if (orderBy.field.isEqual(fieldPath)) { + const cursorValue = bound.position[i]; + if (upperBoundCompare({ value, inclusive }, { value: cursorValue, inclusive: bound.inclusive }) > 0) { + value = cursorValue; + inclusive = bound.inclusive; + } + break; + } + } + } + return { value, inclusive }; +} +/** Returns the number of segments of a perfect index for this target. */ +function targetGetSegmentCount(target) { + let fields = new SortedSet(FieldPath$1.comparator); + let hasArraySegment = false; + for (const filter of target.filters) { + for (const subFilter of filter.getFlattenedFilters()) { + // __name__ is not an explicit segment of any index, so we don't need to + // count it. + if (subFilter.field.isKeyField()) { + continue; + } + // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately. + // For instance, it is possible to have an index for "a ARRAY a ASC". Even + // though these are on the same field, they should be counted as two + // separate segments in an index. + if (subFilter.op === "array-contains" /* Operator.ARRAY_CONTAINS */ || + subFilter.op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) { + hasArraySegment = true; + } + else { + fields = fields.add(subFilter.field); + } + } + } + for (const orderBy of target.orderBy) { + // __name__ is not an explicit segment of any index, so we don't need to + // count it. + if (!orderBy.field.isKeyField()) { + fields = fields.add(orderBy.field); + } + } + return fields.size + (hasArraySegment ? 1 : 0); +} +function targetHasLimit(target) { + return target.limit !== null; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Query encapsulates all the query attributes we support in the SDK. It can + * be run against the LocalStore, as well as be converted to a `Target` to + * query the RemoteStore results. + * + * Visible for testing. + */ +class QueryImpl { + /** + * Initializes a Query with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + */ + constructor(path, collectionGroup = null, explicitOrderBy = [], filters = [], limit = null, limitType = "F" /* LimitType.First */, startAt = null, endAt = null) { + this.path = path; + this.collectionGroup = collectionGroup; + this.explicitOrderBy = explicitOrderBy; + this.filters = filters; + this.limit = limit; + this.limitType = limitType; + this.startAt = startAt; + this.endAt = endAt; + this.memoizedNormalizedOrderBy = null; + // The corresponding `Target` of this `Query` instance, for use with + // non-aggregate queries. + this.memoizedTarget = null; + // The corresponding `Target` of this `Query` instance, for use with + // aggregate queries. Unlike targets for non-aggregate queries, + // aggregate query targets do not contain normalized order-bys, they only + // contain explicit order-bys. + this.memoizedAggregateTarget = null; + if (this.startAt) ; + if (this.endAt) ; + } +} +/** Creates a new Query instance with the options provided. */ +function newQuery(path, collectionGroup, explicitOrderBy, filters, limit, limitType, startAt, endAt) { + return new QueryImpl(path, collectionGroup, explicitOrderBy, filters, limit, limitType, startAt, endAt); +} +/** Creates a new Query for a query that matches all documents at `path` */ +function newQueryForPath(path) { + return new QueryImpl(path); +} +/** + * Helper to convert a collection group query into a collection query at a + * specific path. This is used when executing collection group queries, since + * we have to split the query into a set of collection queries at multiple + * paths. + */ +function asCollectionQueryAtPath(query, path) { + return new QueryImpl(path, + /*collectionGroup=*/ null, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, query.startAt, query.endAt); +} +/** + * Returns true if this query does not specify any query constraints that + * could remove results. + */ +function queryMatchesAllDocuments(query) { + return (query.filters.length === 0 && + query.limit === null && + query.startAt == null && + query.endAt == null && + (query.explicitOrderBy.length === 0 || + (query.explicitOrderBy.length === 1 && + query.explicitOrderBy[0].field.isKeyField()))); +} +// Returns the sorted set of inequality filter fields used in this query. +function getInequalityFilterFields(query) { + let result = new SortedSet(FieldPath$1.comparator); + query.filters.forEach((filter) => { + const subFilters = filter.getFlattenedFilters(); + subFilters.forEach((filter) => { + if (filter.isInequality()) { + result = result.add(filter.field); + } + }); + }); + return result; +} +/** + * Creates a new Query for a collection group query that matches all documents + * within the provided collection group. + */ +function newQueryForCollectionGroup(collectionId) { + return new QueryImpl(ResourcePath.emptyPath(), collectionId); +} +/** + * Returns whether the query matches a single document by path (rather than a + * collection). + */ +function isDocumentQuery$1(query) { + return (DocumentKey.isDocumentKey(query.path) && + query.collectionGroup === null && + query.filters.length === 0); +} +/** + * Returns whether the query matches a collection group rather than a specific + * collection. + */ +function isCollectionGroupQuery(query) { + return query.collectionGroup !== null; +} +/** + * Returns the normalized order-by constraint that is used to execute the Query, + * which can be different from the order-by constraints the user provided (e.g. + * the SDK and backend always orders by `__name__`). The normalized order-by + * includes implicit order-bys in addition to the explicit user provided + * order-bys. + */ +function queryNormalizedOrderBy(query) { + const queryImpl = debugCast(query); + if (queryImpl.memoizedNormalizedOrderBy === null) { + queryImpl.memoizedNormalizedOrderBy = []; + const fieldsNormalized = new Set(); + // Any explicit order by fields should be added as is. + for (const orderBy of queryImpl.explicitOrderBy) { + queryImpl.memoizedNormalizedOrderBy.push(orderBy); + fieldsNormalized.add(orderBy.field.canonicalString()); + } + // The order of the implicit ordering always matches the last explicit order by. + const lastDirection = queryImpl.explicitOrderBy.length > 0 + ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1].dir + : "asc" /* Direction.ASCENDING */; + // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical + // order. When there are multiple inequality filters on the same field, the field should be added + // only once. + // Note: `SortedSet` sorts the key field before other fields. However, we want the key + // field to be sorted last. + const inequalityFields = getInequalityFilterFields(queryImpl); + inequalityFields.forEach(field => { + if (!fieldsNormalized.has(field.canonicalString()) && + !field.isKeyField()) { + queryImpl.memoizedNormalizedOrderBy.push(new OrderBy(field, lastDirection)); + } + }); + // Add the document key field to the last if it is not explicitly ordered. + if (!fieldsNormalized.has(FieldPath$1.keyField().canonicalString())) { + queryImpl.memoizedNormalizedOrderBy.push(new OrderBy(FieldPath$1.keyField(), lastDirection)); + } + } + return queryImpl.memoizedNormalizedOrderBy; +} +/** + * Converts this `Query` instance to its corresponding `Target` representation. + */ +function queryToTarget(query) { + const queryImpl = debugCast(query); + if (!queryImpl.memoizedTarget) { + queryImpl.memoizedTarget = _queryToTarget(queryImpl, queryNormalizedOrderBy(query)); + } + return queryImpl.memoizedTarget; +} +/** + * Converts this `Query` instance to its corresponding `Target` representation, + * for use within an aggregate query. Unlike targets for non-aggregate queries, + * aggregate query targets do not contain normalized order-bys, they only + * contain explicit order-bys. + */ +function queryToAggregateTarget(query) { + const queryImpl = debugCast(query); + if (!queryImpl.memoizedAggregateTarget) { + // Do not include implicit order-bys for aggregate queries. + queryImpl.memoizedAggregateTarget = _queryToTarget(queryImpl, query.explicitOrderBy); + } + return queryImpl.memoizedAggregateTarget; +} +function _queryToTarget(queryImpl, orderBys) { + if (queryImpl.limitType === "F" /* LimitType.First */) { + return newTarget(queryImpl.path, queryImpl.collectionGroup, orderBys, queryImpl.filters, queryImpl.limit, queryImpl.startAt, queryImpl.endAt); + } + else { + // Flip the orderBy directions since we want the last results + orderBys = orderBys.map(orderBy => { + const dir = orderBy.dir === "desc" /* Direction.DESCENDING */ + ? "asc" /* Direction.ASCENDING */ + : "desc" /* Direction.DESCENDING */; + return new OrderBy(orderBy.field, dir); + }); + // We need to swap the cursors to match the now-flipped query ordering. + const startAt = queryImpl.endAt + ? new Bound(queryImpl.endAt.position, queryImpl.endAt.inclusive) + : null; + const endAt = queryImpl.startAt + ? new Bound(queryImpl.startAt.position, queryImpl.startAt.inclusive) + : null; + // Now return as a LimitType.First query. + return newTarget(queryImpl.path, queryImpl.collectionGroup, orderBys, queryImpl.filters, queryImpl.limit, startAt, endAt); + } +} +function queryWithAddedFilter(query, filter) { + const newFilters = query.filters.concat([filter]); + return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), newFilters, query.limit, query.limitType, query.startAt, query.endAt); +} +function queryWithAddedOrderBy(query, orderBy) { + // TODO(dimond): validate that orderBy does not list the same key twice. + const newOrderBy = query.explicitOrderBy.concat([orderBy]); + return new QueryImpl(query.path, query.collectionGroup, newOrderBy, query.filters.slice(), query.limit, query.limitType, query.startAt, query.endAt); +} +function queryWithLimit(query, limit, limitType) { + return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), limit, limitType, query.startAt, query.endAt); +} +function queryWithStartAt(query, bound) { + return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, bound, query.endAt); +} +function queryWithEndAt(query, bound) { + return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, query.startAt, bound); +} +function queryEquals(left, right) { + return (targetEquals(queryToTarget(left), queryToTarget(right)) && + left.limitType === right.limitType); +} +// TODO(b/29183165): This is used to get a unique string from a query to, for +// example, use as a dictionary key, but the implementation is subject to +// collisions. Make it collision-free. +function canonifyQuery(query) { + return `${canonifyTarget(queryToTarget(query))}|lt:${query.limitType}`; +} +function stringifyQuery(query) { + return `Query(target=${stringifyTarget(queryToTarget(query))}; limitType=${query.limitType})`; +} +/** Returns whether `doc` matches the constraints of `query`. */ +function queryMatches(query, doc) { + return (doc.isFoundDocument() && + queryMatchesPathAndCollectionGroup(query, doc) && + queryMatchesOrderBy(query, doc) && + queryMatchesFilters(query, doc) && + queryMatchesBounds(query, doc)); +} +function queryMatchesPathAndCollectionGroup(query, doc) { + const docPath = doc.key.path; + if (query.collectionGroup !== null) { + // NOTE: this.path is currently always empty since we don't expose Collection + // Group queries rooted at a document path yet. + return (doc.key.hasCollectionId(query.collectionGroup) && + query.path.isPrefixOf(docPath)); + } + else if (DocumentKey.isDocumentKey(query.path)) { + // exact match for document queries + return query.path.isEqual(docPath); + } + else { + // shallow ancestor queries by default + return query.path.isImmediateParentOf(docPath); + } +} +/** + * A document must have a value for every ordering clause in order to show up + * in the results. + */ +function queryMatchesOrderBy(query, doc) { + // We must use `queryNormalizedOrderBy()` to get the list of all orderBys (both implicit and explicit). + // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must + // be taken into account. For example, the query "a > 1 || b==1" has an implicit "orderBy a" due + // to the inequality, and is evaluated as "a > 1 orderBy a || b==1 orderBy a". + // A document with content of {b:1} matches the filters, but does not match the orderBy because + // it's missing the field 'a'. + for (const orderBy of queryNormalizedOrderBy(query)) { + // order-by key always matches + if (!orderBy.field.isKeyField() && doc.data.field(orderBy.field) === null) { + return false; + } + } + return true; +} +function queryMatchesFilters(query, doc) { + for (const filter of query.filters) { + if (!filter.matches(doc)) { + return false; + } + } + return true; +} +/** Makes sure a document is within the bounds, if provided. */ +function queryMatchesBounds(query, doc) { + if (query.startAt && + !boundSortsBeforeDocument(query.startAt, queryNormalizedOrderBy(query), doc)) { + return false; + } + if (query.endAt && + !boundSortsAfterDocument(query.endAt, queryNormalizedOrderBy(query), doc)) { + return false; + } + return true; +} +/** + * Returns the collection group that this query targets. + * + * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab + * synchronization for query results. + */ +function queryCollectionGroup(query) { + return (query.collectionGroup || + (query.path.length % 2 === 1 + ? query.path.lastSegment() + : query.path.get(query.path.length - 2))); +} +/** + * Returns a new comparator function that can be used to compare two documents + * based on the Query's ordering constraint. + */ +function newQueryComparator(query) { + return (d1, d2) => { + let comparedOnKeyField = false; + for (const orderBy of queryNormalizedOrderBy(query)) { + const comp = compareDocs(orderBy, d1, d2); + if (comp !== 0) { + return comp; + } + comparedOnKeyField = comparedOnKeyField || orderBy.field.isKeyField(); + } + return 0; + }; +} +function compareDocs(orderBy, d1, d2) { + const comparison = orderBy.field.isKeyField() + ? DocumentKey.comparator(d1.key, d2.key) + : compareDocumentsByField(orderBy.field, d1, d2); + switch (orderBy.dir) { + case "asc" /* Direction.ASCENDING */: + return comparison; + case "desc" /* Direction.DESCENDING */: + return -1 * comparison; + default: + return fail(0x4d4e, { direction: orderBy.dir }); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A map implementation that uses objects as keys. Objects must have an + * associated equals function and must be immutable. Entries in the map are + * stored together with the key being produced from the mapKeyFn. This map + * automatically handles collisions of keys. + */ +class ObjectMap { + constructor(mapKeyFn, equalsFn) { + this.mapKeyFn = mapKeyFn; + this.equalsFn = equalsFn; + /** + * The inner map for a key/value pair. Due to the possibility of collisions we + * keep a list of entries that we do a linear search through to find an actual + * match. Note that collisions should be rare, so we still expect near + * constant time lookups in practice. + */ + this.inner = {}; + /** The number of entries stored in the map */ + this.innerSize = 0; + } + /** Get a value for this key, or undefined if it does not exist. */ + get(key) { + const id = this.mapKeyFn(key); + const matches = this.inner[id]; + if (matches === undefined) { + return undefined; + } + for (const [otherKey, value] of matches) { + if (this.equalsFn(otherKey, key)) { + return value; + } + } + return undefined; + } + has(key) { + return this.get(key) !== undefined; + } + /** Put this key and value in the map. */ + set(key, value) { + const id = this.mapKeyFn(key); + const matches = this.inner[id]; + if (matches === undefined) { + this.inner[id] = [[key, value]]; + this.innerSize++; + return; + } + for (let i = 0; i < matches.length; i++) { + if (this.equalsFn(matches[i][0], key)) { + // This is updating an existing entry and does not increase `innerSize`. + matches[i] = [key, value]; + return; + } + } + matches.push([key, value]); + this.innerSize++; + } + /** + * Remove this key from the map. Returns a boolean if anything was deleted. + */ + delete(key) { + const id = this.mapKeyFn(key); + const matches = this.inner[id]; + if (matches === undefined) { + return false; + } + for (let i = 0; i < matches.length; i++) { + if (this.equalsFn(matches[i][0], key)) { + if (matches.length === 1) { + delete this.inner[id]; + } + else { + matches.splice(i, 1); + } + this.innerSize--; + return true; + } + } + return false; + } + forEach(fn) { + forEach(this.inner, (_, entries) => { + for (const [k, v] of entries) { + fn(k, v); + } + }); + } + isEmpty() { + return isEmpty(this.inner); + } + size() { + return this.innerSize; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const EMPTY_MUTABLE_DOCUMENT_MAP = new SortedMap(DocumentKey.comparator); +function mutableDocumentMap() { + return EMPTY_MUTABLE_DOCUMENT_MAP; +} +const EMPTY_DOCUMENT_MAP = new SortedMap(DocumentKey.comparator); +function documentMap(...docs) { + let map = EMPTY_DOCUMENT_MAP; + for (const doc of docs) { + map = map.insert(doc.key, doc); + } + return map; +} +function newOverlayedDocumentMap() { + return newDocumentKeyMap(); +} +function convertOverlayedDocumentMapToDocumentMap(collection) { + let documents = EMPTY_DOCUMENT_MAP; + collection.forEach((k, v) => (documents = documents.insert(k, v.overlayedDocument))); + return documents; +} +function newOverlayMap() { + return newDocumentKeyMap(); +} +function newMutationMap() { + return newDocumentKeyMap(); +} +function newDocumentKeyMap() { + return new ObjectMap(key => key.toString(), (l, r) => l.isEqual(r)); +} +const EMPTY_DOCUMENT_VERSION_MAP = new SortedMap(DocumentKey.comparator); +function documentVersionMap() { + return EMPTY_DOCUMENT_VERSION_MAP; +} +const EMPTY_DOCUMENT_KEY_SET = new SortedSet(DocumentKey.comparator); +function documentKeySet(...keys) { + let set = EMPTY_DOCUMENT_KEY_SET; + for (const key of keys) { + set = set.add(key); + } + return set; +} +const EMPTY_TARGET_ID_SET = new SortedSet(primitiveComparator); +function targetIdSet() { + return EMPTY_TARGET_ID_SET; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns an DoubleValue for `value` that is encoded based the serializer's + * `useProto3Json` setting. + */ +function toDouble(serializer, value) { + if (serializer.useProto3Json) { + if (isNaN(value)) { + return { doubleValue: 'NaN' }; + } + else if (value === Infinity) { + return { doubleValue: 'Infinity' }; + } + else if (value === -Infinity) { + return { doubleValue: '-Infinity' }; + } + } + return { doubleValue: isNegativeZero(value) ? '-0' : value }; +} +/** + * Returns an IntegerValue for `value`. + */ +function toInteger(value) { + return { integerValue: '' + value }; +} +/** + * Returns a value for a number that's appropriate to put into a proto. + * The return value is an IntegerValue if it can safely represent the value, + * otherwise a DoubleValue is returned. + */ +function toNumber(serializer, value) { + return isSafeInteger(value) ? toInteger(value) : toDouble(serializer, value); +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Used to represent a field transform on a mutation. */ +class TransformOperation { + constructor() { + // Make sure that the structural type of `TransformOperation` is unique. + // See https://github.com/microsoft/TypeScript/issues/5451 + this._ = undefined; + } +} +/** + * Computes the local transform result against the provided `previousValue`, + * optionally using the provided localWriteTime. + */ +function applyTransformOperationToLocalView(transform, previousValue, localWriteTime) { + if (transform instanceof ServerTimestampTransform) { + return serverTimestamp$1(localWriteTime, previousValue); + } + else if (transform instanceof ArrayUnionTransformOperation) { + return applyArrayUnionTransformOperation(transform, previousValue); + } + else if (transform instanceof ArrayRemoveTransformOperation) { + return applyArrayRemoveTransformOperation(transform, previousValue); + } + else { + return applyNumericIncrementTransformOperationToLocalView(transform, previousValue); + } +} +/** + * Computes a final transform result after the transform has been acknowledged + * by the server, potentially using the server-provided transformResult. + */ +function applyTransformOperationToRemoteDocument(transform, previousValue, transformResult) { + // The server just sends null as the transform result for array operations, + // so we have to calculate a result the same as we do for local + // applications. + if (transform instanceof ArrayUnionTransformOperation) { + return applyArrayUnionTransformOperation(transform, previousValue); + } + else if (transform instanceof ArrayRemoveTransformOperation) { + return applyArrayRemoveTransformOperation(transform, previousValue); + } + return transformResult; +} +/** + * If this transform operation is not idempotent, returns the base value to + * persist for this transform. If a base value is returned, the transform + * operation is always applied to this base value, even if document has + * already been updated. + * + * Base values provide consistent behavior for non-idempotent transforms and + * allow us to return the same latency-compensated value even if the backend + * has already applied the transform operation. The base value is null for + * idempotent transforms, as they can be re-played even if the backend has + * already applied them. + * + * @returns a base value to store along with the mutation, or null for + * idempotent transforms. + */ +function computeTransformOperationBaseValue(transform, previousValue) { + if (transform instanceof NumericIncrementTransformOperation) { + return isNumber(previousValue) ? previousValue : { integerValue: 0 }; + } + return null; +} +function transformOperationEquals(left, right) { + if (left instanceof ArrayUnionTransformOperation && + right instanceof ArrayUnionTransformOperation) { + return arrayEquals(left.elements, right.elements, valueEquals); + } + else if (left instanceof ArrayRemoveTransformOperation && + right instanceof ArrayRemoveTransformOperation) { + return arrayEquals(left.elements, right.elements, valueEquals); + } + else if (left instanceof NumericIncrementTransformOperation && + right instanceof NumericIncrementTransformOperation) { + return valueEquals(left.operand, right.operand); + } + return (left instanceof ServerTimestampTransform && + right instanceof ServerTimestampTransform); +} +/** Transforms a value into a server-generated timestamp. */ +class ServerTimestampTransform extends TransformOperation { +} +/** Transforms an array value via a union operation. */ +class ArrayUnionTransformOperation extends TransformOperation { + constructor(elements) { + super(); + this.elements = elements; + } +} +function applyArrayUnionTransformOperation(transform, previousValue) { + const values = coercedFieldValuesArray(previousValue); + for (const toUnion of transform.elements) { + if (!values.some(element => valueEquals(element, toUnion))) { + values.push(toUnion); + } + } + return { arrayValue: { values } }; +} +/** Transforms an array value via a remove operation. */ +class ArrayRemoveTransformOperation extends TransformOperation { + constructor(elements) { + super(); + this.elements = elements; + } +} +function applyArrayRemoveTransformOperation(transform, previousValue) { + let values = coercedFieldValuesArray(previousValue); + for (const toRemove of transform.elements) { + values = values.filter(element => !valueEquals(element, toRemove)); + } + return { arrayValue: { values } }; +} +/** + * Implements the backend semantics for locally computed NUMERIC_ADD (increment) + * transforms. Converts all field values to integers or doubles, but unlike the + * backend does not cap integer values at 2^63. Instead, JavaScript number + * arithmetic is used and precision loss can occur for values greater than 2^53. + */ +class NumericIncrementTransformOperation extends TransformOperation { + constructor(serializer, operand) { + super(); + this.serializer = serializer; + this.operand = operand; + } +} +function applyNumericIncrementTransformOperationToLocalView(transform, previousValue) { + // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit + // precision and resolves overflows by reducing precision, we do not + // manually cap overflows at 2^63. + const baseValue = computeTransformOperationBaseValue(transform, previousValue); + const sum = asNumber(baseValue) + asNumber(transform.operand); + if (isInteger(baseValue) && isInteger(transform.operand)) { + return toInteger(sum); + } + else { + return toDouble(transform.serializer, sum); + } +} +function asNumber(value) { + return normalizeNumber(value.integerValue || value.doubleValue); +} +function coercedFieldValuesArray(value) { + return isArray(value) && value.arrayValue.values + ? value.arrayValue.values.slice() + : []; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** A field path and the TransformOperation to perform upon it. */ +class FieldTransform { + constructor(field, transform) { + this.field = field; + this.transform = transform; + } +} +function fieldTransformEquals(left, right) { + return (left.field.isEqual(right.field) && + transformOperationEquals(left.transform, right.transform)); +} +function fieldTransformsAreEqual(left, right) { + if (left === undefined && right === undefined) { + return true; + } + if (left && right) { + return arrayEquals(left, right, (l, r) => fieldTransformEquals(l, r)); + } + return false; +} +/** The result of successfully applying a mutation to the backend. */ +class MutationResult { + constructor( + /** + * The version at which the mutation was committed: + * + * - For most operations, this is the updateTime in the WriteResult. + * - For deletes, the commitTime of the WriteResponse (because deletes are + * not stored and have no updateTime). + * + * Note that these versions can be different: No-op writes will not change + * the updateTime even though the commitTime advances. + */ + version, + /** + * The resulting fields returned from the backend after a mutation + * containing field transforms has been committed. Contains one FieldValue + * for each FieldTransform that was in the mutation. + * + * Will be empty if the mutation did not contain any field transforms. + */ + transformResults) { + this.version = version; + this.transformResults = transformResults; + } +} +/** + * Encodes a precondition for a mutation. This follows the model that the + * backend accepts with the special case of an explicit "empty" precondition + * (meaning no precondition). + */ +class Precondition { + constructor(updateTime, exists) { + this.updateTime = updateTime; + this.exists = exists; + } + /** Creates a new empty Precondition. */ + static none() { + return new Precondition(); + } + /** Creates a new Precondition with an exists flag. */ + static exists(exists) { + return new Precondition(undefined, exists); + } + /** Creates a new Precondition based on a version a document exists at. */ + static updateTime(version) { + return new Precondition(version); + } + /** Returns whether this Precondition is empty. */ + get isNone() { + return this.updateTime === undefined && this.exists === undefined; + } + isEqual(other) { + return (this.exists === other.exists && + (this.updateTime + ? !!other.updateTime && this.updateTime.isEqual(other.updateTime) + : !other.updateTime)); + } +} +/** Returns true if the preconditions is valid for the given document. */ +function preconditionIsValidForDocument(precondition, document) { + if (precondition.updateTime !== undefined) { + return (document.isFoundDocument() && + document.version.isEqual(precondition.updateTime)); + } + else if (precondition.exists !== undefined) { + return precondition.exists === document.isFoundDocument(); + } + else { + return true; + } +} +/** + * A mutation describes a self-contained change to a document. Mutations can + * create, replace, delete, and update subsets of documents. + * + * Mutations not only act on the value of the document but also its version. + * + * For local mutations (mutations that haven't been committed yet), we preserve + * the existing version for Set and Patch mutations. For Delete mutations, we + * reset the version to 0. + * + * Here's the expected transition table. + * + * MUTATION APPLIED TO RESULTS IN + * + * SetMutation Document(v3) Document(v3) + * SetMutation NoDocument(v3) Document(v0) + * SetMutation InvalidDocument(v0) Document(v0) + * PatchMutation Document(v3) Document(v3) + * PatchMutation NoDocument(v3) NoDocument(v3) + * PatchMutation InvalidDocument(v0) UnknownDocument(v3) + * DeleteMutation Document(v3) NoDocument(v0) + * DeleteMutation NoDocument(v3) NoDocument(v0) + * DeleteMutation InvalidDocument(v0) NoDocument(v0) + * + * For acknowledged mutations, we use the updateTime of the WriteResponse as + * the resulting version for Set and Patch mutations. As deletes have no + * explicit update time, we use the commitTime of the WriteResponse for + * Delete mutations. + * + * If a mutation is acknowledged by the backend but fails the precondition check + * locally, we transition to an `UnknownDocument` and rely on Watch to send us + * the updated version. + * + * Field transforms are used only with Patch and Set Mutations. We use the + * `updateTransforms` message to store transforms, rather than the `transforms`s + * messages. + * + * ## Subclassing Notes + * + * Every type of mutation needs to implement its own applyToRemoteDocument() and + * applyToLocalView() to implement the actual behavior of applying the mutation + * to some source document (see `setMutationApplyToRemoteDocument()` for an + * example). + */ +class Mutation { +} +/** + * A utility method to calculate a `Mutation` representing the overlay from the + * final state of the document, and a `FieldMask` representing the fields that + * are mutated by the local mutations. + */ +function calculateOverlayMutation(doc, mask) { + if (!doc.hasLocalMutations || (mask && mask.fields.length === 0)) { + return null; + } + // mask is null when sets or deletes are applied to the current document. + if (mask === null) { + if (doc.isNoDocument()) { + return new DeleteMutation(doc.key, Precondition.none()); + } + else { + return new SetMutation(doc.key, doc.data, Precondition.none()); + } + } + else { + const docValue = doc.data; + const patchValue = ObjectValue.empty(); + let maskSet = new SortedSet(FieldPath$1.comparator); + for (let path of mask.fields) { + if (!maskSet.has(path)) { + let value = docValue.field(path); + // If we are deleting a nested field, we take the immediate parent as + // the mask used to construct the resulting mutation. + // Justification: Nested fields can create parent fields implicitly. If + // only a leaf entry is deleted in later mutations, the parent field + // should still remain, but we may have lost this information. + // Consider mutation (foo.bar 1), then mutation (foo.bar delete()). + // This leaves the final result (foo, {}). Despite the fact that `doc` + // has the correct result, `foo` is not in `mask`, and the resulting + // mutation would miss `foo`. + if (value === null && path.length > 1) { + path = path.popLast(); + value = docValue.field(path); + } + if (value === null) { + patchValue.delete(path); + } + else { + patchValue.set(path, value); + } + maskSet = maskSet.add(path); + } + } + return new PatchMutation(doc.key, patchValue, new FieldMask(maskSet.toArray()), Precondition.none()); + } +} +/** + * Applies this mutation to the given document for the purposes of computing a + * new remote document. If the input document doesn't match the expected state + * (e.g. it is invalid or outdated), the document type may transition to + * unknown. + * + * @param mutation - The mutation to apply. + * @param document - The document to mutate. The input document can be an + * invalid document if the client has no knowledge of the pre-mutation state + * of the document. + * @param mutationResult - The result of applying the mutation from the backend. + */ +function mutationApplyToRemoteDocument(mutation, document, mutationResult) { + if (mutation instanceof SetMutation) { + setMutationApplyToRemoteDocument(mutation, document, mutationResult); + } + else if (mutation instanceof PatchMutation) { + patchMutationApplyToRemoteDocument(mutation, document, mutationResult); + } + else { + deleteMutationApplyToRemoteDocument(mutation, document, mutationResult); + } +} +/** + * Applies this mutation to the given document for the purposes of computing + * the new local view of a document. If the input document doesn't match the + * expected state, the document is not modified. + * + * @param mutation - The mutation to apply. + * @param document - The document to mutate. The input document can be an + * invalid document if the client has no knowledge of the pre-mutation state + * of the document. + * @param previousMask - The fields that have been updated before applying this mutation. + * @param localWriteTime - A timestamp indicating the local write time of the + * batch this mutation is a part of. + * @returns A `FieldMask` representing the fields that are changed by applying this mutation. + */ +function mutationApplyToLocalView(mutation, document, previousMask, localWriteTime) { + if (mutation instanceof SetMutation) { + return setMutationApplyToLocalView(mutation, document, previousMask, localWriteTime); + } + else if (mutation instanceof PatchMutation) { + return patchMutationApplyToLocalView(mutation, document, previousMask, localWriteTime); + } + else { + return deleteMutationApplyToLocalView(mutation, document, previousMask); + } +} +/** + * If this mutation is not idempotent, returns the base value to persist with + * this mutation. If a base value is returned, the mutation is always applied + * to this base value, even if document has already been updated. + * + * The base value is a sparse object that consists of only the document + * fields for which this mutation contains a non-idempotent transformation + * (e.g. a numeric increment). The provided value guarantees consistent + * behavior for non-idempotent transforms and allow us to return the same + * latency-compensated value even if the backend has already applied the + * mutation. The base value is null for idempotent mutations, as they can be + * re-played even if the backend has already applied them. + * + * @returns a base value to store along with the mutation, or null for + * idempotent mutations. + */ +function mutationExtractBaseValue(mutation, document) { + let baseObject = null; + for (const fieldTransform of mutation.fieldTransforms) { + const existingValue = document.data.field(fieldTransform.field); + const coercedValue = computeTransformOperationBaseValue(fieldTransform.transform, existingValue || null); + if (coercedValue != null) { + if (baseObject === null) { + baseObject = ObjectValue.empty(); + } + baseObject.set(fieldTransform.field, coercedValue); + } + } + return baseObject ? baseObject : null; +} +function mutationEquals(left, right) { + if (left.type !== right.type) { + return false; + } + if (!left.key.isEqual(right.key)) { + return false; + } + if (!left.precondition.isEqual(right.precondition)) { + return false; + } + if (!fieldTransformsAreEqual(left.fieldTransforms, right.fieldTransforms)) { + return false; + } + if (left.type === 0 /* MutationType.Set */) { + return left.value.isEqual(right.value); + } + if (left.type === 1 /* MutationType.Patch */) { + return (left.data.isEqual(right.data) && + left.fieldMask.isEqual(right.fieldMask)); + } + return true; +} +/** + * A mutation that creates or replaces the document at the given key with the + * object value contents. + */ +class SetMutation extends Mutation { + constructor(key, value, precondition, fieldTransforms = []) { + super(); + this.key = key; + this.value = value; + this.precondition = precondition; + this.fieldTransforms = fieldTransforms; + this.type = 0 /* MutationType.Set */; + } + getFieldMask() { + return null; + } +} +function setMutationApplyToRemoteDocument(mutation, document, mutationResult) { + // Unlike setMutationApplyToLocalView, if we're applying a mutation to a + // remote document the server has accepted the mutation so the precondition + // must have held. + const newData = mutation.value.clone(); + const transformResults = serverTransformResults(mutation.fieldTransforms, document, mutationResult.transformResults); + newData.setAll(transformResults); + document + .convertToFoundDocument(mutationResult.version, newData) + .setHasCommittedMutations(); +} +function setMutationApplyToLocalView(mutation, document, previousMask, localWriteTime) { + if (!preconditionIsValidForDocument(mutation.precondition, document)) { + // The mutation failed to apply (e.g. a document ID created with add() + // caused a name collision). + return previousMask; + } + const newData = mutation.value.clone(); + const transformResults = localTransformResults(mutation.fieldTransforms, localWriteTime, document); + newData.setAll(transformResults); + document + .convertToFoundDocument(document.version, newData) + .setHasLocalMutations(); + return null; // SetMutation overwrites all fields. +} +/** + * A mutation that modifies fields of the document at the given key with the + * given values. The values are applied through a field mask: + * + * * When a field is in both the mask and the values, the corresponding field + * is updated. + * * When a field is in neither the mask nor the values, the corresponding + * field is unmodified. + * * When a field is in the mask but not in the values, the corresponding field + * is deleted. + * * When a field is not in the mask but is in the values, the values map is + * ignored. + */ +class PatchMutation extends Mutation { + constructor(key, data, fieldMask, precondition, fieldTransforms = []) { + super(); + this.key = key; + this.data = data; + this.fieldMask = fieldMask; + this.precondition = precondition; + this.fieldTransforms = fieldTransforms; + this.type = 1 /* MutationType.Patch */; + } + getFieldMask() { + return this.fieldMask; + } +} +function patchMutationApplyToRemoteDocument(mutation, document, mutationResult) { + if (!preconditionIsValidForDocument(mutation.precondition, document)) { + // Since the mutation was not rejected, we know that the precondition + // matched on the backend. We therefore must not have the expected version + // of the document in our cache and convert to an UnknownDocument with a + // known updateTime. + document.convertToUnknownDocument(mutationResult.version); + return; + } + const transformResults = serverTransformResults(mutation.fieldTransforms, document, mutationResult.transformResults); + const newData = document.data; + newData.setAll(getPatch(mutation)); + newData.setAll(transformResults); + document + .convertToFoundDocument(mutationResult.version, newData) + .setHasCommittedMutations(); +} +function patchMutationApplyToLocalView(mutation, document, previousMask, localWriteTime) { + if (!preconditionIsValidForDocument(mutation.precondition, document)) { + return previousMask; + } + const transformResults = localTransformResults(mutation.fieldTransforms, localWriteTime, document); + const newData = document.data; + newData.setAll(getPatch(mutation)); + newData.setAll(transformResults); + document + .convertToFoundDocument(document.version, newData) + .setHasLocalMutations(); + if (previousMask === null) { + return null; + } + return previousMask + .unionWith(mutation.fieldMask.fields) + .unionWith(mutation.fieldTransforms.map(transform => transform.field)); +} +/** + * Returns a FieldPath/Value map with the content of the PatchMutation. + */ +function getPatch(mutation) { + const result = new Map(); + mutation.fieldMask.fields.forEach(fieldPath => { + if (!fieldPath.isEmpty()) { + const newValue = mutation.data.field(fieldPath); + result.set(fieldPath, newValue); + } + }); + return result; +} +/** + * Creates a list of "transform results" (a transform result is a field value + * representing the result of applying a transform) for use after a mutation + * containing transforms has been acknowledged by the server. + * + * @param fieldTransforms - The field transforms to apply the result to. + * @param mutableDocument - The current state of the document after applying all + * previous mutations. + * @param serverTransformResults - The transform results received by the server. + * @returns The transform results list. + */ +function serverTransformResults(fieldTransforms, mutableDocument, serverTransformResults) { + const transformResults = new Map(); + hardAssert(fieldTransforms.length === serverTransformResults.length, 0x7f90, { + serverTransformResultCount: serverTransformResults.length, + fieldTransformCount: fieldTransforms.length + }); + for (let i = 0; i < serverTransformResults.length; i++) { + const fieldTransform = fieldTransforms[i]; + const transform = fieldTransform.transform; + const previousValue = mutableDocument.data.field(fieldTransform.field); + transformResults.set(fieldTransform.field, applyTransformOperationToRemoteDocument(transform, previousValue, serverTransformResults[i])); + } + return transformResults; +} +/** + * Creates a list of "transform results" (a transform result is a field value + * representing the result of applying a transform) for use when applying a + * transform locally. + * + * @param fieldTransforms - The field transforms to apply the result to. + * @param localWriteTime - The local time of the mutation (used to + * generate ServerTimestampValues). + * @param mutableDocument - The document to apply transforms on. + * @returns The transform results list. + */ +function localTransformResults(fieldTransforms, localWriteTime, mutableDocument) { + const transformResults = new Map(); + for (const fieldTransform of fieldTransforms) { + const transform = fieldTransform.transform; + const previousValue = mutableDocument.data.field(fieldTransform.field); + transformResults.set(fieldTransform.field, applyTransformOperationToLocalView(transform, previousValue, localWriteTime)); + } + return transformResults; +} +/** A mutation that deletes the document at the given key. */ +class DeleteMutation extends Mutation { + constructor(key, precondition) { + super(); + this.key = key; + this.precondition = precondition; + this.type = 2 /* MutationType.Delete */; + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } +} +function deleteMutationApplyToRemoteDocument(mutation, document, mutationResult) { + // Unlike applyToLocalView, if we're applying a mutation to a remote + // document the server has accepted the mutation so the precondition must + // have held. + document + .convertToNoDocument(mutationResult.version) + .setHasCommittedMutations(); +} +function deleteMutationApplyToLocalView(mutation, document, previousMask) { + if (preconditionIsValidForDocument(mutation.precondition, document)) { + document.convertToNoDocument(document.version).setHasLocalMutations(); + return null; + } + return previousMask; +} +/** + * A mutation that verifies the existence of the document at the given key with + * the provided precondition. + * + * The `verify` operation is only used in Transactions, and this class serves + * primarily to facilitate serialization into protos. + */ +class VerifyMutation extends Mutation { + constructor(key, precondition) { + super(); + this.key = key; + this.precondition = precondition; + this.type = 3 /* MutationType.Verify */; + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A batch of mutations that will be sent as one unit to the backend. + */ +class MutationBatch { + /** + * @param batchId - The unique ID of this mutation batch. + * @param localWriteTime - The original write time of this mutation. + * @param baseMutations - Mutations that are used to populate the base + * values when this mutation is applied locally. This can be used to locally + * overwrite values that are persisted in the remote document cache. Base + * mutations are never sent to the backend. + * @param mutations - The user-provided mutations in this mutation batch. + * User-provided mutations are applied both locally and remotely on the + * backend. + */ + constructor(batchId, localWriteTime, baseMutations, mutations) { + this.batchId = batchId; + this.localWriteTime = localWriteTime; + this.baseMutations = baseMutations; + this.mutations = mutations; + } + /** + * Applies all the mutations in this MutationBatch to the specified document + * to compute the state of the remote document + * + * @param document - The document to apply mutations to. + * @param batchResult - The result of applying the MutationBatch to the + * backend. + */ + applyToRemoteDocument(document, batchResult) { + const mutationResults = batchResult.mutationResults; + for (let i = 0; i < this.mutations.length; i++) { + const mutation = this.mutations[i]; + if (mutation.key.isEqual(document.key)) { + const mutationResult = mutationResults[i]; + mutationApplyToRemoteDocument(mutation, document, mutationResult); + } + } + } + /** + * Computes the local view of a document given all the mutations in this + * batch. + * + * @param document - The document to apply mutations to. + * @param mutatedFields - Fields that have been updated before applying this mutation batch. + * @returns A `FieldMask` representing all the fields that are mutated. + */ + applyToLocalView(document, mutatedFields) { + // First, apply the base state. This allows us to apply non-idempotent + // transform against a consistent set of values. + for (const mutation of this.baseMutations) { + if (mutation.key.isEqual(document.key)) { + mutatedFields = mutationApplyToLocalView(mutation, document, mutatedFields, this.localWriteTime); + } + } + // Second, apply all user-provided mutations. + for (const mutation of this.mutations) { + if (mutation.key.isEqual(document.key)) { + mutatedFields = mutationApplyToLocalView(mutation, document, mutatedFields, this.localWriteTime); + } + } + return mutatedFields; + } + /** + * Computes the local view for all provided documents given the mutations in + * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to + * replace all the mutation applications. + */ + applyToLocalDocumentSet(documentMap, documentsWithoutRemoteVersion) { + // TODO(mrschmidt): This implementation is O(n^2). If we apply the mutations + // directly (as done in `applyToLocalView()`), we can reduce the complexity + // to O(n). + const overlays = newMutationMap(); + this.mutations.forEach(m => { + const overlayedDocument = documentMap.get(m.key); + // TODO(mutabledocuments): This method should take a MutableDocumentMap + // and we should remove this cast. + const mutableDocument = overlayedDocument.overlayedDocument; + let mutatedFields = this.applyToLocalView(mutableDocument, overlayedDocument.mutatedFields); + // Set mutatedFields to null if the document is only from local mutations. + // This creates a Set or Delete mutation, instead of trying to create a + // patch mutation as the overlay. + mutatedFields = documentsWithoutRemoteVersion.has(m.key) + ? null + : mutatedFields; + const overlay = calculateOverlayMutation(mutableDocument, mutatedFields); + if (overlay !== null) { + overlays.set(m.key, overlay); + } + if (!mutableDocument.isValidDocument()) { + mutableDocument.convertToNoDocument(SnapshotVersion.min()); + } + }); + return overlays; + } + keys() { + return this.mutations.reduce((keys, m) => keys.add(m.key), documentKeySet()); + } + isEqual(other) { + return (this.batchId === other.batchId && + arrayEquals(this.mutations, other.mutations, (l, r) => mutationEquals(l, r)) && + arrayEquals(this.baseMutations, other.baseMutations, (l, r) => mutationEquals(l, r))); + } +} +/** The result of applying a mutation batch to the backend. */ +class MutationBatchResult { + constructor(batch, commitVersion, mutationResults, + /** + * A pre-computed mapping from each mutated document to the resulting + * version. + */ + docVersions) { + this.batch = batch; + this.commitVersion = commitVersion; + this.mutationResults = mutationResults; + this.docVersions = docVersions; + } + /** + * Creates a new MutationBatchResult for the given batch and results. There + * must be one result for each mutation in the batch. This static factory + * caches a document=>version mapping (docVersions). + */ + static from(batch, commitVersion, results) { + hardAssert(batch.mutations.length === results.length, 0xe5da, { + mutationsSent: batch.mutations.length, + resultsReceived: results.length + }); + let versionMap = documentVersionMap(); + const mutations = batch.mutations; + for (let i = 0; i < mutations.length; i++) { + versionMap = versionMap.insert(mutations[i].key, results[i].version); + } + return new MutationBatchResult(batch, commitVersion, results, versionMap); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Representation of an overlay computed by Firestore. + * + * Holds information about a mutation and the largest batch id in Firestore when + * the mutation was created. + */ +class Overlay { + constructor(largestBatchId, mutation) { + this.largestBatchId = largestBatchId; + this.mutation = mutation; + } + getKey() { + return this.mutation.key; + } + isEqual(other) { + return other !== null && this.mutation === other.mutation; + } + toString() { + return `Overlay{ + largestBatchId: ${this.largestBatchId}, + mutation: ${this.mutation.toString()} + }`; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class ExistenceFilter { + constructor(count, unchangedNames) { + this.count = count; + this.unchangedNames = unchangedNames; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Error Codes describing the different ways GRPC can fail. These are copied + * directly from GRPC's sources here: + * + * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h + * + * Important! The names of these identifiers matter because the string forms + * are used for reverse lookups from the webchannel stream. Do NOT change the + * names of these identifiers or change this into a const enum. + */ +var RpcCode; +(function (RpcCode) { + RpcCode[RpcCode["OK"] = 0] = "OK"; + RpcCode[RpcCode["CANCELLED"] = 1] = "CANCELLED"; + RpcCode[RpcCode["UNKNOWN"] = 2] = "UNKNOWN"; + RpcCode[RpcCode["INVALID_ARGUMENT"] = 3] = "INVALID_ARGUMENT"; + RpcCode[RpcCode["DEADLINE_EXCEEDED"] = 4] = "DEADLINE_EXCEEDED"; + RpcCode[RpcCode["NOT_FOUND"] = 5] = "NOT_FOUND"; + RpcCode[RpcCode["ALREADY_EXISTS"] = 6] = "ALREADY_EXISTS"; + RpcCode[RpcCode["PERMISSION_DENIED"] = 7] = "PERMISSION_DENIED"; + RpcCode[RpcCode["UNAUTHENTICATED"] = 16] = "UNAUTHENTICATED"; + RpcCode[RpcCode["RESOURCE_EXHAUSTED"] = 8] = "RESOURCE_EXHAUSTED"; + RpcCode[RpcCode["FAILED_PRECONDITION"] = 9] = "FAILED_PRECONDITION"; + RpcCode[RpcCode["ABORTED"] = 10] = "ABORTED"; + RpcCode[RpcCode["OUT_OF_RANGE"] = 11] = "OUT_OF_RANGE"; + RpcCode[RpcCode["UNIMPLEMENTED"] = 12] = "UNIMPLEMENTED"; + RpcCode[RpcCode["INTERNAL"] = 13] = "INTERNAL"; + RpcCode[RpcCode["UNAVAILABLE"] = 14] = "UNAVAILABLE"; + RpcCode[RpcCode["DATA_LOSS"] = 15] = "DATA_LOSS"; +})(RpcCode || (RpcCode = {})); +/** + * Determines whether an error code represents a permanent error when received + * in response to a non-write operation. + * + * See isPermanentWriteError for classifying write errors. + */ +function isPermanentError(code) { + switch (code) { + case Code.OK: + return fail(0xfdaa); + case Code.CANCELLED: + case Code.UNKNOWN: + case Code.DEADLINE_EXCEEDED: + case Code.RESOURCE_EXHAUSTED: + case Code.INTERNAL: + case Code.UNAVAILABLE: + // Unauthenticated means something went wrong with our token and we need + // to retry with new credentials which will happen automatically. + case Code.UNAUTHENTICATED: + return false; + case Code.INVALID_ARGUMENT: + case Code.NOT_FOUND: + case Code.ALREADY_EXISTS: + case Code.PERMISSION_DENIED: + case Code.FAILED_PRECONDITION: + // Aborted might be retried in some scenarios, but that is dependent on + // the context and should handled individually by the calling code. + // See https://cloud.google.com/apis/design/errors. + case Code.ABORTED: + case Code.OUT_OF_RANGE: + case Code.UNIMPLEMENTED: + case Code.DATA_LOSS: + return true; + default: + return fail(0x3c6b, { code }); + } +} +/** + * Determines whether an error code represents a permanent error when received + * in response to a write operation. + * + * Write operations must be handled specially because as of b/119437764, ABORTED + * errors on the write stream should be retried too (even though ABORTED errors + * are not generally retryable). + * + * Note that during the initial handshake on the write stream an ABORTED error + * signals that we should discard our stream token (i.e. it is permanent). This + * means a handshake error should be classified with isPermanentError, above. + */ +function isPermanentWriteError(code) { + return isPermanentError(code) && code !== Code.ABORTED; +} +/** + * Maps an error Code from GRPC status code number, like 0, 1, or 14. These + * are not the same as HTTP status codes. + * + * @returns The Code equivalent to the given GRPC status code. Fails if there + * is no match. + */ +function mapCodeFromRpcCode(code) { + if (code === undefined) { + // This shouldn't normally happen, but in certain error cases (like trying + // to send invalid proto messages) we may get an error with no GRPC code. + logError('GRPC error has no .code'); + return Code.UNKNOWN; + } + switch (code) { + case RpcCode.OK: + return Code.OK; + case RpcCode.CANCELLED: + return Code.CANCELLED; + case RpcCode.UNKNOWN: + return Code.UNKNOWN; + case RpcCode.DEADLINE_EXCEEDED: + return Code.DEADLINE_EXCEEDED; + case RpcCode.RESOURCE_EXHAUSTED: + return Code.RESOURCE_EXHAUSTED; + case RpcCode.INTERNAL: + return Code.INTERNAL; + case RpcCode.UNAVAILABLE: + return Code.UNAVAILABLE; + case RpcCode.UNAUTHENTICATED: + return Code.UNAUTHENTICATED; + case RpcCode.INVALID_ARGUMENT: + return Code.INVALID_ARGUMENT; + case RpcCode.NOT_FOUND: + return Code.NOT_FOUND; + case RpcCode.ALREADY_EXISTS: + return Code.ALREADY_EXISTS; + case RpcCode.PERMISSION_DENIED: + return Code.PERMISSION_DENIED; + case RpcCode.FAILED_PRECONDITION: + return Code.FAILED_PRECONDITION; + case RpcCode.ABORTED: + return Code.ABORTED; + case RpcCode.OUT_OF_RANGE: + return Code.OUT_OF_RANGE; + case RpcCode.UNIMPLEMENTED: + return Code.UNIMPLEMENTED; + case RpcCode.DATA_LOSS: + return Code.DATA_LOSS; + default: + return fail(0x999b, { code }); + } +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An error encountered while decoding base64 string. + */ +class Base64DecodeError extends Error { + constructor() { + super(...arguments); + this.name = 'Base64DecodeError'; + } +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The global, singleton instance of TestingHooksSpi. + * + * This variable will be `null` in all cases _except_ when running from + * integration tests that have registered callbacks to be notified of events + * that happen during the test execution. + */ +let testingHooksSpi = null; +/** + * Sets the value of the `testingHooksSpi` object. + * @param instance the instance to set. + */ +function setTestingHooksSpi(instance) { + if (testingHooksSpi) { + throw new Error('a TestingHooksSpi instance is already set'); + } + testingHooksSpi = instance; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An instance of the Platform's 'TextEncoder' implementation. + */ +function newTextEncoder() { + return new TextEncoder(); +} +/** + * An instance of the Platform's 'TextDecoder' implementation. + */ +function newTextDecoder() { + return new TextDecoder('utf-8'); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const MAX_64_BIT_UNSIGNED_INTEGER = new Integer([0xffffffff, 0xffffffff], 0); +// Hash a string using md5 hashing algorithm. +function getMd5HashValue(value) { + const encodedValue = newTextEncoder().encode(value); + const md5 = new Md5(); + md5.update(encodedValue); + return new Uint8Array(md5.digest()); +} +// Interpret the 16 bytes array as two 64-bit unsigned integers, encoded using +// 2’s complement using little endian. +function get64BitUints(Bytes) { + const dataView = new DataView(Bytes.buffer); + const chunk1 = dataView.getUint32(0, /* littleEndian= */ true); + const chunk2 = dataView.getUint32(4, /* littleEndian= */ true); + const chunk3 = dataView.getUint32(8, /* littleEndian= */ true); + const chunk4 = dataView.getUint32(12, /* littleEndian= */ true); + const integer1 = new Integer([chunk1, chunk2], 0); + const integer2 = new Integer([chunk3, chunk4], 0); + return [integer1, integer2]; +} +class BloomFilter { + constructor(bitmap, padding, hashCount) { + this.bitmap = bitmap; + this.padding = padding; + this.hashCount = hashCount; + if (padding < 0 || padding >= 8) { + throw new BloomFilterError(`Invalid padding: ${padding}`); + } + if (hashCount < 0) { + throw new BloomFilterError(`Invalid hash count: ${hashCount}`); + } + if (bitmap.length > 0 && this.hashCount === 0) { + // Only empty bloom filter can have 0 hash count. + throw new BloomFilterError(`Invalid hash count: ${hashCount}`); + } + if (bitmap.length === 0 && padding !== 0) { + // Empty bloom filter should have 0 padding. + throw new BloomFilterError(`Invalid padding when bitmap length is 0: ${padding}`); + } + this.bitCount = bitmap.length * 8 - padding; + // Set the bit count in Integer to avoid repetition in mightContain(). + this.bitCountInInteger = Integer.fromNumber(this.bitCount); + } + // Calculate the ith hash value based on the hashed 64bit integers, + // and calculate its corresponding bit index in the bitmap to be checked. + getBitIndex(num1, num2, hashIndex) { + // Calculate hashed value h(i) = h1 + (i * h2). + let hashValue = num1.add(num2.multiply(Integer.fromNumber(hashIndex))); + // Wrap if hash value overflow 64bit. + if (hashValue.compare(MAX_64_BIT_UNSIGNED_INTEGER) === 1) { + hashValue = new Integer([hashValue.getBits(0), hashValue.getBits(1)], 0); + } + return hashValue.modulo(this.bitCountInInteger).toNumber(); + } + // Return whether the bit on the given index in the bitmap is set to 1. + isBitSet(index) { + // To retrieve bit n, calculate: (bitmap[n / 8] & (0x01 << (n % 8))). + const byte = this.bitmap[Math.floor(index / 8)]; + const offset = index % 8; + return (byte & (0x01 << offset)) !== 0; + } + mightContain(value) { + // Empty bitmap should always return false on membership check. + if (this.bitCount === 0) { + return false; + } + const md5HashedValue = getMd5HashValue(value); + const [hash1, hash2] = get64BitUints(md5HashedValue); + for (let i = 0; i < this.hashCount; i++) { + const index = this.getBitIndex(hash1, hash2, i); + if (!this.isBitSet(index)) { + return false; + } + } + return true; + } + /** Create bloom filter for testing purposes only. */ + static create(bitCount, hashCount, contains) { + const padding = bitCount % 8 === 0 ? 0 : 8 - (bitCount % 8); + const bitmap = new Uint8Array(Math.ceil(bitCount / 8)); + const bloomFilter = new BloomFilter(bitmap, padding, hashCount); + contains.forEach(item => bloomFilter.insert(item)); + return bloomFilter; + } + insert(value) { + if (this.bitCount === 0) { + return; + } + const md5HashedValue = getMd5HashValue(value); + const [hash1, hash2] = get64BitUints(md5HashedValue); + for (let i = 0; i < this.hashCount; i++) { + const index = this.getBitIndex(hash1, hash2, i); + this.setBit(index); + } + } + setBit(index) { + const indexOfByte = Math.floor(index / 8); + const offset = index % 8; + this.bitmap[indexOfByte] |= 0x01 << offset; + } +} +class BloomFilterError extends Error { + constructor() { + super(...arguments); + this.name = 'BloomFilterError'; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An event from the RemoteStore. It is split into targetChanges (changes to the + * state or the set of documents in our watched targets) and documentUpdates + * (changes to the actual documents). + */ +class RemoteEvent { + constructor( + /** + * The snapshot version this event brings us up to, or MIN if not set. + */ + snapshotVersion, + /** + * A map from target to changes to the target. See TargetChange. + */ + targetChanges, + /** + * A map of targets that is known to be inconsistent, and the purpose for + * re-listening. Listens for these targets should be re-established without + * resume tokens. + */ + targetMismatches, + /** + * A set of which documents have changed or been deleted, along with the + * doc's new values (if not deleted). + */ + documentUpdates, + /** + * A set of which document updates are due only to limbo resolution targets. + */ + resolvedLimboDocuments) { + this.snapshotVersion = snapshotVersion; + this.targetChanges = targetChanges; + this.targetMismatches = targetMismatches; + this.documentUpdates = documentUpdates; + this.resolvedLimboDocuments = resolvedLimboDocuments; + } + /** + * HACK: Views require RemoteEvents in order to determine whether the view is + * CURRENT, but secondary tabs don't receive remote events. So this method is + * used to create a synthesized RemoteEvent that can be used to apply a + * CURRENT status change to a View, for queries executed in a different tab. + */ + // PORTING NOTE: Multi-tab only + static createSynthesizedRemoteEventForCurrentChange(targetId, current, resumeToken) { + const targetChanges = new Map(); + targetChanges.set(targetId, TargetChange.createSynthesizedTargetChangeForCurrentChange(targetId, current, resumeToken)); + return new RemoteEvent(SnapshotVersion.min(), targetChanges, new SortedMap(primitiveComparator), mutableDocumentMap(), documentKeySet()); + } +} +/** + * A TargetChange specifies the set of changes for a specific target as part of + * a RemoteEvent. These changes track which documents are added, modified or + * removed, as well as the target's resume token and whether the target is + * marked CURRENT. + * The actual changes *to* documents are not part of the TargetChange since + * documents may be part of multiple targets. + */ +class TargetChange { + constructor( + /** + * An opaque, server-assigned token that allows watching a query to be resumed + * after disconnecting without retransmitting all the data that matches the + * query. The resume token essentially identifies a point in time from which + * the server should resume sending results. + */ + resumeToken, + /** + * The "current" (synced) status of this target. Note that "current" + * has special meaning in the RPC protocol that implies that a target is + * both up-to-date and consistent with the rest of the watch stream. + */ + current, + /** + * The set of documents that were newly assigned to this target as part of + * this remote event. + */ + addedDocuments, + /** + * The set of documents that were already assigned to this target but received + * an update during this remote event. + */ + modifiedDocuments, + /** + * The set of documents that were removed from this target as part of this + * remote event. + */ + removedDocuments) { + this.resumeToken = resumeToken; + this.current = current; + this.addedDocuments = addedDocuments; + this.modifiedDocuments = modifiedDocuments; + this.removedDocuments = removedDocuments; + } + /** + * This method is used to create a synthesized TargetChanges that can be used to + * apply a CURRENT status change to a View (for queries executed in a different + * tab) or for new queries (to raise snapshots with correct CURRENT status). + */ + static createSynthesizedTargetChangeForCurrentChange(targetId, current, resumeToken) { + return new TargetChange(resumeToken, current, documentKeySet(), documentKeySet(), documentKeySet()); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a changed document and a list of target ids to which this change + * applies. + * + * If document has been deleted NoDocument will be provided. + */ +class DocumentWatchChange { + constructor( + /** The new document applies to all of these targets. */ + updatedTargetIds, + /** The new document is removed from all of these targets. */ + removedTargetIds, + /** The key of the document for this change. */ + key, + /** + * The new document or NoDocument if it was deleted. Is null if the + * document went out of view without the server sending a new document. + */ + newDoc) { + this.updatedTargetIds = updatedTargetIds; + this.removedTargetIds = removedTargetIds; + this.key = key; + this.newDoc = newDoc; + } +} +class ExistenceFilterChange { + constructor(targetId, existenceFilter) { + this.targetId = targetId; + this.existenceFilter = existenceFilter; + } +} +class WatchTargetChange { + constructor( + /** What kind of change occurred to the watch target. */ + state, + /** The target IDs that were added/removed/set. */ + targetIds, + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + resumeToken = ByteString.EMPTY_BYTE_STRING, + /** An RPC error indicating why the watch failed. */ + cause = null) { + this.state = state; + this.targetIds = targetIds; + this.resumeToken = resumeToken; + this.cause = cause; + } +} +/** Tracks the internal state of a Watch target. */ +class TargetState { + constructor() { + /** + * The number of pending responses (adds or removes) that we are waiting on. + * We only consider targets active that have no pending responses. + */ + this.pendingResponses = 0; + /** + * Keeps track of the document changes since the last raised snapshot. + * + * These changes are continuously updated as we receive document updates and + * always reflect the current set of changes against the last issued snapshot. + */ + this.documentChanges = snapshotChangesMap(); + /** See public getters for explanations of these fields. */ + this._resumeToken = ByteString.EMPTY_BYTE_STRING; + this._current = false; + /** + * Whether this target state should be included in the next snapshot. We + * initialize to true so that newly-added targets are included in the next + * RemoteEvent. + */ + this._hasPendingChanges = true; + } + /** + * Whether this target has been marked 'current'. + * + * 'Current' has special meaning in the RPC protocol: It implies that the + * Watch backend has sent us all changes up to the point at which the target + * was added and that the target is consistent with the rest of the watch + * stream. + */ + get current() { + return this._current; + } + /** The last resume token sent to us for this target. */ + get resumeToken() { + return this._resumeToken; + } + /** Whether this target has pending target adds or target removes. */ + get isPending() { + return this.pendingResponses !== 0; + } + /** Whether we have modified any state that should trigger a snapshot. */ + get hasPendingChanges() { + return this._hasPendingChanges; + } + /** + * Applies the resume token to the TargetChange, but only when it has a new + * value. Empty resumeTokens are discarded. + */ + updateResumeToken(resumeToken) { + if (resumeToken.approximateByteSize() > 0) { + this._hasPendingChanges = true; + this._resumeToken = resumeToken; + } + } + /** + * Creates a target change from the current set of changes. + * + * To reset the document changes after raising this snapshot, call + * `clearPendingChanges()`. + */ + toTargetChange() { + let addedDocuments = documentKeySet(); + let modifiedDocuments = documentKeySet(); + let removedDocuments = documentKeySet(); + this.documentChanges.forEach((key, changeType) => { + switch (changeType) { + case 0 /* ChangeType.Added */: + addedDocuments = addedDocuments.add(key); + break; + case 2 /* ChangeType.Modified */: + modifiedDocuments = modifiedDocuments.add(key); + break; + case 1 /* ChangeType.Removed */: + removedDocuments = removedDocuments.add(key); + break; + default: + fail(0x9481, { changeType }); + } + }); + return new TargetChange(this._resumeToken, this._current, addedDocuments, modifiedDocuments, removedDocuments); + } + /** + * Resets the document changes and sets `hasPendingChanges` to false. + */ + clearPendingChanges() { + this._hasPendingChanges = false; + this.documentChanges = snapshotChangesMap(); + } + addDocumentChange(key, changeType) { + this._hasPendingChanges = true; + this.documentChanges = this.documentChanges.insert(key, changeType); + } + removeDocumentChange(key) { + this._hasPendingChanges = true; + this.documentChanges = this.documentChanges.remove(key); + } + recordPendingTargetRequest() { + this.pendingResponses += 1; + } + recordTargetResponse() { + this.pendingResponses -= 1; + hardAssert(this.pendingResponses >= 0, 0x0ca9, { pendingResponses: this.pendingResponses }); + } + markCurrent() { + this._hasPendingChanges = true; + this._current = true; + } +} +const LOG_TAG$g = 'WatchChangeAggregator'; +/** + * A helper class to accumulate watch changes into a RemoteEvent. + */ +class WatchChangeAggregator { + constructor(metadataProvider) { + this.metadataProvider = metadataProvider; + /** The internal state of all tracked targets. */ + this.targetStates = new Map(); + /** Keeps track of the documents to update since the last raised snapshot. */ + this.pendingDocumentUpdates = mutableDocumentMap(); + this.pendingDocumentUpdatesByTarget = documentTargetMap(); + /** A mapping of document keys to their set of target IDs. */ + this.pendingDocumentTargetMapping = documentTargetMap(); + /** + * A map of targets with existence filter mismatches. These targets are + * known to be inconsistent and their listens needs to be re-established by + * RemoteStore. + */ + this.pendingTargetResets = new SortedMap(primitiveComparator); + } + /** + * Processes and adds the DocumentWatchChange to the current set of changes. + */ + handleDocumentChange(docChange) { + for (const targetId of docChange.updatedTargetIds) { + if (docChange.newDoc && docChange.newDoc.isFoundDocument()) { + this.addDocumentToTarget(targetId, docChange.newDoc); + } + else { + this.removeDocumentFromTarget(targetId, docChange.key, docChange.newDoc); + } + } + for (const targetId of docChange.removedTargetIds) { + this.removeDocumentFromTarget(targetId, docChange.key, docChange.newDoc); + } + } + /** Processes and adds the WatchTargetChange to the current set of changes. */ + handleTargetChange(targetChange) { + this.forEachTarget(targetChange, targetId => { + const targetState = this.ensureTargetState(targetId); + switch (targetChange.state) { + case 0 /* WatchTargetChangeState.NoChange */: + if (this.isActiveTarget(targetId)) { + targetState.updateResumeToken(targetChange.resumeToken); + } + break; + case 1 /* WatchTargetChangeState.Added */: + // We need to decrement the number of pending acks needed from watch + // for this targetId. + targetState.recordTargetResponse(); + if (!targetState.isPending) { + // We have a freshly added target, so we need to reset any state + // that we had previously. This can happen e.g. when remove and add + // back a target for existence filter mismatches. + targetState.clearPendingChanges(); + } + targetState.updateResumeToken(targetChange.resumeToken); + break; + case 2 /* WatchTargetChangeState.Removed */: + // We need to keep track of removed targets to we can post-filter and + // remove any target changes. + // We need to decrement the number of pending acks needed from watch + // for this targetId. + targetState.recordTargetResponse(); + if (!targetState.isPending) { + this.removeTarget(targetId); + } + break; + case 3 /* WatchTargetChangeState.Current */: + if (this.isActiveTarget(targetId)) { + targetState.markCurrent(); + targetState.updateResumeToken(targetChange.resumeToken); + } + break; + case 4 /* WatchTargetChangeState.Reset */: + if (this.isActiveTarget(targetId)) { + // Reset the target and synthesizes removes for all existing + // documents. The backend will re-add any documents that still + // match the target before it sends the next global snapshot. + this.resetTarget(targetId); + targetState.updateResumeToken(targetChange.resumeToken); + } + break; + default: + fail(0xddd6, { + state: targetChange.state + }); + } + }); + } + /** + * Iterates over all targetIds that the watch change applies to: either the + * targetIds explicitly listed in the change or the targetIds of all currently + * active targets. + */ + forEachTarget(targetChange, fn) { + if (targetChange.targetIds.length > 0) { + targetChange.targetIds.forEach(fn); + } + else { + this.targetStates.forEach((_, targetId) => { + if (this.isActiveTarget(targetId)) { + fn(targetId); + } + }); + } + } + /** + * Handles existence filters and synthesizes deletes for filter mismatches. + * Targets that are invalidated by filter mismatches are added to + * `pendingTargetResets`. + */ + handleExistenceFilter(watchChange) { + const targetId = watchChange.targetId; + const expectedCount = watchChange.existenceFilter.count; + const targetData = this.targetDataForActiveTarget(targetId); + if (targetData) { + const target = targetData.target; + if (targetIsDocumentTarget(target)) { + if (expectedCount === 0) { + // The existence filter told us the document does not exist. We deduce + // that this document does not exist and apply a deleted document to + // our updates. Without applying this deleted document there might be + // another query that will raise this document as part of a snapshot + // until it is resolved, essentially exposing inconsistency between + // queries. + const key = new DocumentKey(target.path); + this.removeDocumentFromTarget(targetId, key, MutableDocument.newNoDocument(key, SnapshotVersion.min())); + } + else { + hardAssert(expectedCount === 1, 0x4e2d, { expectedCount }); + } + } + else { + const currentSize = this.getCurrentDocumentCountForTarget(targetId); + // Existence filter mismatch. Mark the documents as being in limbo, and + // raise a snapshot with `isFromCache:true`. + if (currentSize !== expectedCount) { + // Apply bloom filter to identify and mark removed documents. + const bloomFilter = this.parseBloomFilter(watchChange); + const status = bloomFilter + ? this.applyBloomFilter(bloomFilter, watchChange, currentSize) + : 1 /* BloomFilterApplicationStatus.Skipped */; + if (status !== 0 /* BloomFilterApplicationStatus.Success */) { + // If bloom filter application fails, we reset the mapping and + // trigger re-run of the query. + this.resetTarget(targetId); + const purpose = status === 2 /* BloomFilterApplicationStatus.FalsePositive */ + ? "TargetPurposeExistenceFilterMismatchBloom" /* TargetPurpose.ExistenceFilterMismatchBloom */ + : "TargetPurposeExistenceFilterMismatch" /* TargetPurpose.ExistenceFilterMismatch */; + this.pendingTargetResets = this.pendingTargetResets.insert(targetId, purpose); + } + testingHooksSpi?.notifyOnExistenceFilterMismatch(createExistenceFilterMismatchInfoForTestingHooks(currentSize, watchChange.existenceFilter, this.metadataProvider.getDatabaseId(), bloomFilter, status)); + } + } + } + } + /** + * Parse the bloom filter from the "unchanged_names" field of an existence + * filter. + */ + parseBloomFilter(watchChange) { + const unchangedNames = watchChange.existenceFilter.unchangedNames; + if (!unchangedNames || !unchangedNames.bits) { + return null; + } + const { bits: { bitmap = '', padding = 0 }, hashCount = 0 } = unchangedNames; + let normalizedBitmap; + try { + normalizedBitmap = normalizeByteString(bitmap).toUint8Array(); + } + catch (err) { + if (err instanceof Base64DecodeError) { + logWarn('Decoding the base64 bloom filter in existence filter failed (' + + err.message + + '); ignoring the bloom filter and falling back to full re-query.'); + return null; + } + else { + throw err; + } + } + let bloomFilter; + try { + // BloomFilter throws error if the inputs are invalid. + bloomFilter = new BloomFilter(normalizedBitmap, padding, hashCount); + } + catch (err) { + if (err instanceof BloomFilterError) { + logWarn('BloomFilter error: ', err); + } + else { + logWarn('Applying bloom filter failed: ', err); + } + return null; + } + if (bloomFilter.bitCount === 0) { + return null; + } + return bloomFilter; + } + /** + * Apply bloom filter to remove the deleted documents, and return the + * application status. + */ + applyBloomFilter(bloomFilter, watchChange, currentCount) { + const expectedCount = watchChange.existenceFilter.count; + const removedDocumentCount = this.filterRemovedDocuments(bloomFilter, watchChange.targetId); + return expectedCount === currentCount - removedDocumentCount + ? 0 /* BloomFilterApplicationStatus.Success */ + : 2 /* BloomFilterApplicationStatus.FalsePositive */; + } + /** + * Filter out removed documents based on bloom filter membership result and + * return number of documents removed. + */ + filterRemovedDocuments(bloomFilter, targetId) { + const existingKeys = this.metadataProvider.getRemoteKeysForTarget(targetId); + let removalCount = 0; + existingKeys.forEach(key => { + const databaseId = this.metadataProvider.getDatabaseId(); + const documentPath = `projects/${databaseId.projectId}` + + `/databases/${databaseId.database}` + + `/documents/${key.path.canonicalString()}`; + if (!bloomFilter.mightContain(documentPath)) { + this.removeDocumentFromTarget(targetId, key, /*updatedDocument=*/ null); + removalCount++; + } + }); + return removalCount; + } + /** + * Converts the currently accumulated state into a remote event at the + * provided snapshot version. Resets the accumulated changes before returning. + */ + createRemoteEvent(snapshotVersion) { + const targetChanges = new Map(); + this.targetStates.forEach((targetState, targetId) => { + const targetData = this.targetDataForActiveTarget(targetId); + if (targetData) { + if (targetState.current && targetIsDocumentTarget(targetData.target)) { + // Document queries for document that don't exist can produce an empty + // result set. To update our local cache, we synthesize a document + // delete if we have not previously received the document for this + // target. This resolves the limbo state of the document, removing it + // from limboDocumentRefs. + // + // TODO(dimond): Ideally we would have an explicit lookup target + // instead resulting in an explicit delete message and we could + // remove this special logic. + const key = new DocumentKey(targetData.target.path); + if (!this.ensureDocumentUpdateByTarget(key).has(targetId) && + !this.targetContainsDocument(targetId, key)) { + this.removeDocumentFromTarget(targetId, key, MutableDocument.newNoDocument(key, snapshotVersion)); + } + } + if (targetState.hasPendingChanges) { + targetChanges.set(targetId, targetState.toTargetChange()); + targetState.clearPendingChanges(); + } + } + }); + let resolvedLimboDocuments = documentKeySet(); + // We extract the set of limbo-only document updates as the GC logic + // special-cases documents that do not appear in the target cache. + // + // TODO(gsoltis): Expand on this comment once GC is available in the JS + // client. + this.pendingDocumentTargetMapping.forEach((key, targets) => { + let isOnlyLimboTarget = true; + targets.forEachWhile(targetId => { + const targetData = this.targetDataForActiveTarget(targetId); + if (targetData && + targetData.purpose !== "TargetPurposeLimboResolution" /* TargetPurpose.LimboResolution */) { + isOnlyLimboTarget = false; + return false; + } + return true; + }); + if (isOnlyLimboTarget) { + resolvedLimboDocuments = resolvedLimboDocuments.add(key); + } + }); + this.pendingDocumentUpdates.forEach((_, doc) => doc.setReadTime(snapshotVersion)); + const remoteEvent = new RemoteEvent(snapshotVersion, targetChanges, this.pendingTargetResets, this.pendingDocumentUpdates, resolvedLimboDocuments); + this.pendingDocumentUpdates = mutableDocumentMap(); + this.pendingDocumentUpdatesByTarget = documentTargetMap(); + this.pendingDocumentTargetMapping = documentTargetMap(); + this.pendingTargetResets = new SortedMap(primitiveComparator); + return remoteEvent; + } + /** + * Adds the provided document to the internal list of document updates and + * its document key to the given target's mapping. + */ + // Visible for testing. + addDocumentToTarget(targetId, document) { + if (!this.isActiveTarget(targetId)) { + return; + } + const changeType = this.targetContainsDocument(targetId, document.key) + ? 2 /* ChangeType.Modified */ + : 0 /* ChangeType.Added */; + const targetState = this.ensureTargetState(targetId); + targetState.addDocumentChange(document.key, changeType); + this.pendingDocumentUpdates = this.pendingDocumentUpdates.insert(document.key, document); + this.pendingDocumentUpdatesByTarget = + this.pendingDocumentUpdatesByTarget.insert(document.key, this.ensureDocumentUpdateByTarget(document.key).add(targetId)); + this.pendingDocumentTargetMapping = + this.pendingDocumentTargetMapping.insert(document.key, this.ensureDocumentTargetMapping(document.key).add(targetId)); + } + /** + * Removes the provided document from the target mapping. If the + * document no longer matches the target, but the document's state is still + * known (e.g. we know that the document was deleted or we received the change + * that caused the filter mismatch), the new document can be provided + * to update the remote document cache. + */ + // Visible for testing. + removeDocumentFromTarget(targetId, key, updatedDocument) { + if (!this.isActiveTarget(targetId)) { + return; + } + const targetState = this.ensureTargetState(targetId); + if (this.targetContainsDocument(targetId, key)) { + targetState.addDocumentChange(key, 1 /* ChangeType.Removed */); + } + else { + // The document may have entered and left the target before we raised a + // snapshot, so we can just ignore the change. + targetState.removeDocumentChange(key); + } + this.pendingDocumentTargetMapping = + this.pendingDocumentTargetMapping.insert(key, this.ensureDocumentTargetMapping(key).delete(targetId)); + this.pendingDocumentTargetMapping = + this.pendingDocumentTargetMapping.insert(key, this.ensureDocumentTargetMapping(key).add(targetId)); + if (updatedDocument) { + this.pendingDocumentUpdates = this.pendingDocumentUpdates.insert(key, updatedDocument); + } + } + removeTarget(targetId) { + this.targetStates.delete(targetId); + } + /** + * Returns the current count of documents in the target. This includes both + * the number of documents that the LocalStore considers to be part of the + * target as well as any accumulated changes. + */ + getCurrentDocumentCountForTarget(targetId) { + const targetState = this.ensureTargetState(targetId); + const targetChange = targetState.toTargetChange(); + return (this.metadataProvider.getRemoteKeysForTarget(targetId).size + + targetChange.addedDocuments.size - + targetChange.removedDocuments.size); + } + /** + * Increment the number of acks needed from watch before we can consider the + * server to be 'in-sync' with the client's active targets. + */ + recordPendingTargetRequest(targetId) { + // For each request we get we need to record we need a response for it. + const targetState = this.ensureTargetState(targetId); + targetState.recordPendingTargetRequest(); + } + ensureTargetState(targetId) { + let result = this.targetStates.get(targetId); + if (!result) { + result = new TargetState(); + this.targetStates.set(targetId, result); + } + return result; + } + ensureDocumentTargetMapping(key) { + let targetMapping = this.pendingDocumentTargetMapping.get(key); + if (!targetMapping) { + targetMapping = new SortedSet(primitiveComparator); + this.pendingDocumentTargetMapping = + this.pendingDocumentTargetMapping.insert(key, targetMapping); + } + return targetMapping; + } + ensureDocumentUpdateByTarget(key) { + let targetMapping = this.pendingDocumentUpdatesByTarget.get(key); + if (!targetMapping) { + targetMapping = new SortedSet(primitiveComparator); + this.pendingDocumentUpdatesByTarget = + this.pendingDocumentUpdatesByTarget.insert(key, targetMapping); + } + return targetMapping; + } + /** + * Verifies that the user is still interested in this target (by calling + * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs + * from watch. + */ + isActiveTarget(targetId) { + const targetActive = this.targetDataForActiveTarget(targetId) !== null; + if (!targetActive) { + logDebug(LOG_TAG$g, 'Detected inactive target', targetId); + } + return targetActive; + } + /** + * Returns the TargetData for an active target (i.e. a target that the user + * is still interested in that has no outstanding target change requests). + */ + targetDataForActiveTarget(targetId) { + const targetState = this.targetStates.get(targetId); + return targetState && targetState.isPending + ? null + : this.metadataProvider.getTargetDataForTarget(targetId); + } + /** + * Resets the state of a Watch target to its initial state (e.g. sets + * 'current' to false, clears the resume token and removes its target mapping + * from all documents). + */ + resetTarget(targetId) { + this.targetStates.set(targetId, new TargetState()); + // Trigger removal for any documents currently mapped to this target. + // These removals will be part of the initial snapshot if Watch does not + // resend these documents. + const existingKeys = this.metadataProvider.getRemoteKeysForTarget(targetId); + existingKeys.forEach(key => { + this.removeDocumentFromTarget(targetId, key, /*updatedDocument=*/ null); + }); + } + /** + * Returns whether the LocalStore considers the document to be part of the + * specified target. + */ + targetContainsDocument(targetId, key) { + const existingKeys = this.metadataProvider.getRemoteKeysForTarget(targetId); + return existingKeys.has(key); + } +} +function documentTargetMap() { + return new SortedMap(DocumentKey.comparator); +} +function snapshotChangesMap() { + return new SortedMap(DocumentKey.comparator); +} +function createExistenceFilterMismatchInfoForTestingHooks(localCacheCount, existenceFilter, databaseId, bloomFilter, bloomFilterStatus) { + const result = { + localCacheCount, + existenceFilterCount: existenceFilter.count, + databaseId: databaseId.database, + projectId: databaseId.projectId + }; + const unchangedNames = existenceFilter.unchangedNames; + if (unchangedNames) { + result.bloomFilter = { + applied: bloomFilterStatus === 0 /* BloomFilterApplicationStatus.Success */, + hashCount: unchangedNames?.hashCount ?? 0, + bitmapLength: unchangedNames?.bits?.bitmap?.length ?? 0, + padding: unchangedNames?.bits?.padding ?? 0, + mightContain: (value) => bloomFilter?.mightContain(value) ?? false + }; + } + return result; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const DIRECTIONS = (() => { + const dirs = {}; + dirs["asc" /* Direction.ASCENDING */] = 'ASCENDING'; + dirs["desc" /* Direction.DESCENDING */] = 'DESCENDING'; + return dirs; +})(); +const OPERATORS = (() => { + const ops = {}; + ops["<" /* Operator.LESS_THAN */] = 'LESS_THAN'; + ops["<=" /* Operator.LESS_THAN_OR_EQUAL */] = 'LESS_THAN_OR_EQUAL'; + ops[">" /* Operator.GREATER_THAN */] = 'GREATER_THAN'; + ops[">=" /* Operator.GREATER_THAN_OR_EQUAL */] = 'GREATER_THAN_OR_EQUAL'; + ops["==" /* Operator.EQUAL */] = 'EQUAL'; + ops["!=" /* Operator.NOT_EQUAL */] = 'NOT_EQUAL'; + ops["array-contains" /* Operator.ARRAY_CONTAINS */] = 'ARRAY_CONTAINS'; + ops["in" /* Operator.IN */] = 'IN'; + ops["not-in" /* Operator.NOT_IN */] = 'NOT_IN'; + ops["array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */] = 'ARRAY_CONTAINS_ANY'; + return ops; +})(); +const COMPOSITE_OPERATORS = (() => { + const ops = {}; + ops["and" /* CompositeOperator.AND */] = 'AND'; + ops["or" /* CompositeOperator.OR */] = 'OR'; + return ops; +})(); +function assertPresent(value, description) { +} +/** + * This class generates JsonObject values for the Datastore API suitable for + * sending to either GRPC stub methods or via the JSON/HTTP REST API. + * + * The serializer supports both Protobuf.js and Proto3 JSON formats. By + * setting `useProto3Json` to true, the serializer will use the Proto3 JSON + * format. + * + * For a description of the Proto3 JSON format check + * https://developers.google.com/protocol-buffers/docs/proto3#json + * + * TODO(klimt): We can remove the databaseId argument if we keep the full + * resource name in documents. + */ +class JsonProtoSerializer { + constructor(databaseId, useProto3Json) { + this.databaseId = databaseId; + this.useProto3Json = useProto3Json; + } +} +function fromRpcStatus(status) { + const code = status.code === undefined ? Code.UNKNOWN : mapCodeFromRpcCode(status.code); + return new FirestoreError(code, status.message || ''); +} +/** + * Returns a value for a number (or null) that's appropriate to put into + * a google.protobuf.Int32Value proto. + * DO NOT USE THIS FOR ANYTHING ELSE. + * This method cheats. It's typed as returning "number" because that's what + * our generated proto interfaces say Int32Value must be. But GRPC actually + * expects a { value: } struct. + */ +function toInt32Proto(serializer, val) { + if (serializer.useProto3Json || isNullOrUndefined(val)) { + return val; + } + else { + return { value: val }; + } +} +/** + * Returns a number (or null) from a google.protobuf.Int32Value proto. + */ +function fromInt32Proto(val) { + let result; + if (typeof val === 'object') { + result = val.value; + } + else { + result = val; + } + return isNullOrUndefined(result) ? null : result; +} +/** + * Returns a value for a Date that's appropriate to put into a proto. + */ +function toTimestamp(serializer, timestamp) { + if (serializer.useProto3Json) { + // Serialize to ISO-8601 date format, but with full nano resolution. + // Since JS Date has only millis, let's only use it for the seconds and + // then manually add the fractions to the end. + const jsDateStr = new Date(timestamp.seconds * 1000).toISOString(); + // Remove .xxx frac part and Z in the end. + const strUntilSeconds = jsDateStr.replace(/\.\d*/, '').replace('Z', ''); + // Pad the fraction out to 9 digits (nanos). + const nanoStr = ('000000000' + timestamp.nanoseconds).slice(-9); + return `${strUntilSeconds}.${nanoStr}Z`; + } + else { + return { + seconds: '' + timestamp.seconds, + nanos: timestamp.nanoseconds + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }; + } +} +/** + * Returns a Timestamp typed object given protobuf timestamp value. + */ +function fromTimestamp(date) { + const timestamp = normalizeTimestamp(date); + return new Timestamp(timestamp.seconds, timestamp.nanos); +} +/** + * Returns a value for bytes that's appropriate to put in a proto. + * + * Visible for testing. + */ +function toBytes(serializer, bytes) { + if (serializer.useProto3Json) { + return bytes.toBase64(); + } + else { + return bytes.toUint8Array(); + } +} +/** + * Returns a ByteString based on the proto string value. + */ +function fromBytes(serializer, value) { + if (serializer.useProto3Json) { + hardAssert(value === undefined || typeof value === 'string', 0xe30b); + return ByteString.fromBase64String(value ? value : ''); + } + else { + hardAssert(value === undefined || + // Check if the value is an instance of both Buffer and Uint8Array, + // despite the fact that Buffer extends Uint8Array. In some + // environments, such as jsdom, the prototype chain of Buffer + // does not indicate that it extends Uint8Array. + value instanceof Buffer || + value instanceof Uint8Array, 0x3f41); + return ByteString.fromUint8Array(value ? value : new Uint8Array()); + } +} +function toVersion(serializer, version) { + return toTimestamp(serializer, version.toTimestamp()); +} +function fromVersion(version) { + hardAssert(!!version, 0xc050); + return SnapshotVersion.fromTimestamp(fromTimestamp(version)); +} +function toResourceName(databaseId, path) { + return toResourcePath(databaseId, path).canonicalString(); +} +function toResourcePath(databaseId, path) { + const resourcePath = fullyQualifiedPrefixPath(databaseId).child('documents'); + return path === undefined ? resourcePath : resourcePath.child(path); +} +function fromResourceName(name) { + const resource = ResourcePath.fromString(name); + hardAssert(isValidResourceName(resource), 0x27ce, { key: resource.toString() }); + return resource; +} +function toName(serializer, key) { + return toResourceName(serializer.databaseId, key.path); +} +function fromName(serializer, name) { + const resource = fromResourceName(name); + if (resource.get(1) !== serializer.databaseId.projectId) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Tried to deserialize key from different project: ' + + resource.get(1) + + ' vs ' + + serializer.databaseId.projectId); + } + if (resource.get(3) !== serializer.databaseId.database) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Tried to deserialize key from different database: ' + + resource.get(3) + + ' vs ' + + serializer.databaseId.database); + } + return new DocumentKey(extractLocalPathFromResourceName(resource)); +} +function toQueryPath(serializer, path) { + return toResourceName(serializer.databaseId, path); +} +function fromQueryPath(name) { + const resourceName = fromResourceName(name); + // In v1beta1 queries for collections at the root did not have a trailing + // "/documents". In v1 all resource paths contain "/documents". Preserve the + // ability to read the v1beta1 form for compatibility with queries persisted + // in the local target cache. + if (resourceName.length === 4) { + return ResourcePath.emptyPath(); + } + return extractLocalPathFromResourceName(resourceName); +} +function getEncodedDatabaseId(serializer) { + const path = new ResourcePath([ + 'projects', + serializer.databaseId.projectId, + 'databases', + serializer.databaseId.database + ]); + return path.canonicalString(); +} +function fullyQualifiedPrefixPath(databaseId) { + return new ResourcePath([ + 'projects', + databaseId.projectId, + 'databases', + databaseId.database + ]); +} +function extractLocalPathFromResourceName(resourceName) { + hardAssert(resourceName.length > 4 && resourceName.get(4) === 'documents', 0x71a3, { key: resourceName.toString() }); + return resourceName.popFirst(5); +} +/** Creates a Document proto from key and fields (but no create/update time) */ +function toMutationDocument(serializer, key, fields) { + return { + name: toName(serializer, key), + fields: fields.value.mapValue.fields + }; +} +function toDocument(serializer, document) { + return { + name: toName(serializer, document.key), + fields: document.data.value.mapValue.fields, + updateTime: toTimestamp(serializer, document.version.toTimestamp()), + createTime: toTimestamp(serializer, document.createTime.toTimestamp()) + }; +} +function fromDocument(serializer, document, hasCommittedMutations) { + const key = fromName(serializer, document.name); + const version = fromVersion(document.updateTime); + // If we read a document from persistence that is missing createTime, it's due + // to older SDK versions not storing this information. In such cases, we'll + // set the createTime to zero. This can be removed in the long term. + const createTime = document.createTime + ? fromVersion(document.createTime) + : SnapshotVersion.min(); + const data = new ObjectValue({ mapValue: { fields: document.fields } }); + const result = MutableDocument.newFoundDocument(key, version, createTime, data); + if (hasCommittedMutations) { + result.setHasCommittedMutations(); + } + return hasCommittedMutations ? result.setHasCommittedMutations() : result; +} +function fromFound(serializer, doc) { + hardAssert(!!doc.found, 0xaa33); + assertPresent(doc.found.name); + assertPresent(doc.found.updateTime); + const key = fromName(serializer, doc.found.name); + const version = fromVersion(doc.found.updateTime); + const createTime = doc.found.createTime + ? fromVersion(doc.found.createTime) + : SnapshotVersion.min(); + const data = new ObjectValue({ mapValue: { fields: doc.found.fields } }); + return MutableDocument.newFoundDocument(key, version, createTime, data); +} +function fromMissing(serializer, result) { + hardAssert(!!result.missing, 0x0f36); + hardAssert(!!result.readTime, 0x5995); + const key = fromName(serializer, result.missing); + const version = fromVersion(result.readTime); + return MutableDocument.newNoDocument(key, version); +} +function fromBatchGetDocumentsResponse(serializer, result) { + if ('found' in result) { + return fromFound(serializer, result); + } + else if ('missing' in result) { + return fromMissing(serializer, result); + } + return fail(0x1c42, { result }); +} +function fromWatchChange(serializer, change) { + let watchChange; + if ('targetChange' in change) { + assertPresent(change.targetChange); + // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE' + // if unset + const state = fromWatchTargetChangeState(change.targetChange.targetChangeType || 'NO_CHANGE'); + const targetIds = change.targetChange.targetIds || []; + const resumeToken = fromBytes(serializer, change.targetChange.resumeToken); + const causeProto = change.targetChange.cause; + const cause = causeProto && fromRpcStatus(causeProto); + watchChange = new WatchTargetChange(state, targetIds, resumeToken, cause || null); + } + else if ('documentChange' in change) { + assertPresent(change.documentChange); + const entityChange = change.documentChange; + assertPresent(entityChange.document); + assertPresent(entityChange.document.name); + assertPresent(entityChange.document.updateTime); + const key = fromName(serializer, entityChange.document.name); + const version = fromVersion(entityChange.document.updateTime); + const createTime = entityChange.document.createTime + ? fromVersion(entityChange.document.createTime) + : SnapshotVersion.min(); + const data = new ObjectValue({ + mapValue: { fields: entityChange.document.fields } + }); + const doc = MutableDocument.newFoundDocument(key, version, createTime, data); + const updatedTargetIds = entityChange.targetIds || []; + const removedTargetIds = entityChange.removedTargetIds || []; + watchChange = new DocumentWatchChange(updatedTargetIds, removedTargetIds, doc.key, doc); + } + else if ('documentDelete' in change) { + assertPresent(change.documentDelete); + const docDelete = change.documentDelete; + assertPresent(docDelete.document); + const key = fromName(serializer, docDelete.document); + const version = docDelete.readTime + ? fromVersion(docDelete.readTime) + : SnapshotVersion.min(); + const doc = MutableDocument.newNoDocument(key, version); + const removedTargetIds = docDelete.removedTargetIds || []; + watchChange = new DocumentWatchChange([], removedTargetIds, doc.key, doc); + } + else if ('documentRemove' in change) { + assertPresent(change.documentRemove); + const docRemove = change.documentRemove; + assertPresent(docRemove.document); + const key = fromName(serializer, docRemove.document); + const removedTargetIds = docRemove.removedTargetIds || []; + watchChange = new DocumentWatchChange([], removedTargetIds, key, null); + } + else if ('filter' in change) { + // TODO(dimond): implement existence filter parsing with strategy. + assertPresent(change.filter); + const filter = change.filter; + assertPresent(filter.targetId); + const { count = 0, unchangedNames } = filter; + const existenceFilter = new ExistenceFilter(count, unchangedNames); + const targetId = filter.targetId; + watchChange = new ExistenceFilterChange(targetId, existenceFilter); + } + else { + return fail(0x2d51, { change }); + } + return watchChange; +} +function fromWatchTargetChangeState(state) { + if (state === 'NO_CHANGE') { + return 0 /* WatchTargetChangeState.NoChange */; + } + else if (state === 'ADD') { + return 1 /* WatchTargetChangeState.Added */; + } + else if (state === 'REMOVE') { + return 2 /* WatchTargetChangeState.Removed */; + } + else if (state === 'CURRENT') { + return 3 /* WatchTargetChangeState.Current */; + } + else if (state === 'RESET') { + return 4 /* WatchTargetChangeState.Reset */; + } + else { + return fail(0x9991, { state }); + } +} +function versionFromListenResponse(change) { + // We have only reached a consistent snapshot for the entire stream if there + // is a read_time set and it applies to all targets (i.e. the list of + // targets is empty). The backend is guaranteed to send such responses. + if (!('targetChange' in change)) { + return SnapshotVersion.min(); + } + const targetChange = change.targetChange; + if (targetChange.targetIds && targetChange.targetIds.length) { + return SnapshotVersion.min(); + } + if (!targetChange.readTime) { + return SnapshotVersion.min(); + } + return fromVersion(targetChange.readTime); +} +function toMutation(serializer, mutation) { + let result; + if (mutation instanceof SetMutation) { + result = { + update: toMutationDocument(serializer, mutation.key, mutation.value) + }; + } + else if (mutation instanceof DeleteMutation) { + result = { delete: toName(serializer, mutation.key) }; + } + else if (mutation instanceof PatchMutation) { + result = { + update: toMutationDocument(serializer, mutation.key, mutation.data), + updateMask: toDocumentMask(mutation.fieldMask) + }; + } + else if (mutation instanceof VerifyMutation) { + result = { + verify: toName(serializer, mutation.key) + }; + } + else { + return fail(0x40d7, { + mutationType: mutation.type + }); + } + if (mutation.fieldTransforms.length > 0) { + result.updateTransforms = mutation.fieldTransforms.map(transform => toFieldTransform(serializer, transform)); + } + if (!mutation.precondition.isNone) { + result.currentDocument = toPrecondition(serializer, mutation.precondition); + } + return result; +} +function fromMutation(serializer, proto) { + const precondition = proto.currentDocument + ? fromPrecondition(proto.currentDocument) + : Precondition.none(); + const fieldTransforms = proto.updateTransforms + ? proto.updateTransforms.map(transform => fromFieldTransform(serializer, transform)) + : []; + if (proto.update) { + assertPresent(proto.update.name); + const key = fromName(serializer, proto.update.name); + const value = new ObjectValue({ + mapValue: { fields: proto.update.fields } + }); + if (proto.updateMask) { + const fieldMask = fromDocumentMask(proto.updateMask); + return new PatchMutation(key, value, fieldMask, precondition, fieldTransforms); + } + else { + return new SetMutation(key, value, precondition, fieldTransforms); + } + } + else if (proto.delete) { + const key = fromName(serializer, proto.delete); + return new DeleteMutation(key, precondition); + } + else if (proto.verify) { + const key = fromName(serializer, proto.verify); + return new VerifyMutation(key, precondition); + } + else { + return fail(0x05b7, { proto }); + } +} +function toPrecondition(serializer, precondition) { + if (precondition.updateTime !== undefined) { + return { + updateTime: toVersion(serializer, precondition.updateTime) + }; + } + else if (precondition.exists !== undefined) { + return { exists: precondition.exists }; + } + else { + return fail(0x6b69); + } +} +function fromPrecondition(precondition) { + if (precondition.updateTime !== undefined) { + return Precondition.updateTime(fromVersion(precondition.updateTime)); + } + else if (precondition.exists !== undefined) { + return Precondition.exists(precondition.exists); + } + else { + return Precondition.none(); + } +} +function fromWriteResult(proto, commitTime) { + // NOTE: Deletes don't have an updateTime. + let version = proto.updateTime + ? fromVersion(proto.updateTime) + : fromVersion(commitTime); + if (version.isEqual(SnapshotVersion.min())) { + // The Firestore Emulator currently returns an update time of 0 for + // deletes of non-existing documents (rather than null). This breaks the + // test "get deleted doc while offline with source=cache" as NoDocuments + // with version 0 are filtered by IndexedDb's RemoteDocumentCache. + // TODO(#2149): Remove this when Emulator is fixed + version = fromVersion(commitTime); + } + return new MutationResult(version, proto.transformResults || []); +} +function fromWriteResults(protos, commitTime) { + if (protos && protos.length > 0) { + hardAssert(commitTime !== undefined, 0x3811); + return protos.map(proto => fromWriteResult(proto, commitTime)); + } + else { + return []; + } +} +function toFieldTransform(serializer, fieldTransform) { + const transform = fieldTransform.transform; + if (transform instanceof ServerTimestampTransform) { + return { + fieldPath: fieldTransform.field.canonicalString(), + setToServerValue: 'REQUEST_TIME' + }; + } + else if (transform instanceof ArrayUnionTransformOperation) { + return { + fieldPath: fieldTransform.field.canonicalString(), + appendMissingElements: { + values: transform.elements + } + }; + } + else if (transform instanceof ArrayRemoveTransformOperation) { + return { + fieldPath: fieldTransform.field.canonicalString(), + removeAllFromArray: { + values: transform.elements + } + }; + } + else if (transform instanceof NumericIncrementTransformOperation) { + return { + fieldPath: fieldTransform.field.canonicalString(), + increment: transform.operand + }; + } + else { + throw fail(0x51c2, { + transform: fieldTransform.transform + }); + } +} +function fromFieldTransform(serializer, proto) { + let transform = null; + if ('setToServerValue' in proto) { + hardAssert(proto.setToServerValue === 'REQUEST_TIME', 0x40f6, { proto }); + transform = new ServerTimestampTransform(); + } + else if ('appendMissingElements' in proto) { + const values = proto.appendMissingElements.values || []; + transform = new ArrayUnionTransformOperation(values); + } + else if ('removeAllFromArray' in proto) { + const values = proto.removeAllFromArray.values || []; + transform = new ArrayRemoveTransformOperation(values); + } + else if ('increment' in proto) { + transform = new NumericIncrementTransformOperation(serializer, proto.increment); + } + else { + fail(0x40c8, { proto }); + } + const fieldPath = FieldPath$1.fromServerFormat(proto.fieldPath); + return new FieldTransform(fieldPath, transform); +} +function toDocumentsTarget(serializer, target) { + return { documents: [toQueryPath(serializer, target.path)] }; +} +function fromDocumentsTarget(documentsTarget) { + const count = documentsTarget.documents.length; + hardAssert(count === 1, 0x07ae, { + count + }); + const name = documentsTarget.documents[0]; + return queryToTarget(newQueryForPath(fromQueryPath(name))); +} +function toQueryTarget(serializer, target) { + // Dissect the path into parent, collectionId, and optional key filter. + const queryTarget = { structuredQuery: {} }; + const path = target.path; + let parent; + if (target.collectionGroup !== null) { + parent = path; + queryTarget.structuredQuery.from = [ + { + collectionId: target.collectionGroup, + allDescendants: true + } + ]; + } + else { + parent = path.popLast(); + queryTarget.structuredQuery.from = [{ collectionId: path.lastSegment() }]; + } + queryTarget.parent = toQueryPath(serializer, parent); + const where = toFilters(target.filters); + if (where) { + queryTarget.structuredQuery.where = where; + } + const orderBy = toOrder(target.orderBy); + if (orderBy) { + queryTarget.structuredQuery.orderBy = orderBy; + } + const limit = toInt32Proto(serializer, target.limit); + if (limit !== null) { + queryTarget.structuredQuery.limit = limit; + } + if (target.startAt) { + queryTarget.structuredQuery.startAt = toStartAtCursor(target.startAt); + } + if (target.endAt) { + queryTarget.structuredQuery.endAt = toEndAtCursor(target.endAt); + } + return { queryTarget, parent }; +} +function toRunAggregationQueryRequest(serializer, target, aggregates, skipAliasing) { + const { queryTarget, parent } = toQueryTarget(serializer, target); + const aliasMap = {}; + const aggregations = []; + let aggregationNum = 0; + aggregates.forEach(aggregate => { + // Map all client-side aliases to a unique short-form + // alias. This avoids issues with client-side aliases that + // exceed the 1500-byte string size limit. + const serverAlias = skipAliasing + ? aggregate.alias + : `aggregate_${aggregationNum++}`; + aliasMap[serverAlias] = aggregate.alias; + if (aggregate.aggregateType === 'count') { + aggregations.push({ + alias: serverAlias, + count: {} + }); + } + else if (aggregate.aggregateType === 'avg') { + aggregations.push({ + alias: serverAlias, + avg: { + field: toFieldPathReference(aggregate.fieldPath) + } + }); + } + else if (aggregate.aggregateType === 'sum') { + aggregations.push({ + alias: serverAlias, + sum: { + field: toFieldPathReference(aggregate.fieldPath) + } + }); + } + }); + return { + request: { + structuredAggregationQuery: { + aggregations, + structuredQuery: queryTarget.structuredQuery + }, + parent: queryTarget.parent + }, + aliasMap, + parent + }; +} +function convertQueryTargetToQuery(target) { + let path = fromQueryPath(target.parent); + const query = target.structuredQuery; + const fromCount = query.from ? query.from.length : 0; + let collectionGroup = null; + if (fromCount > 0) { + hardAssert(fromCount === 1, 0xfe26); + const from = query.from[0]; + if (from.allDescendants) { + collectionGroup = from.collectionId; + } + else { + path = path.child(from.collectionId); + } + } + let filterBy = []; + if (query.where) { + filterBy = fromFilters(query.where); + } + let orderBy = []; + if (query.orderBy) { + orderBy = fromOrder(query.orderBy); + } + let limit = null; + if (query.limit) { + limit = fromInt32Proto(query.limit); + } + let startAt = null; + if (query.startAt) { + startAt = fromStartAtCursor(query.startAt); + } + let endAt = null; + if (query.endAt) { + endAt = fromEndAtCursor(query.endAt); + } + return newQuery(path, collectionGroup, orderBy, filterBy, limit, "F" /* LimitType.First */, startAt, endAt); +} +function fromQueryTarget(target) { + return queryToTarget(convertQueryTargetToQuery(target)); +} +function toListenRequestLabels(serializer, targetData) { + const value = toLabel(targetData.purpose); + if (value == null) { + return null; + } + else { + return { + 'goog-listen-tags': value + }; + } +} +function toLabel(purpose) { + switch (purpose) { + case "TargetPurposeListen" /* TargetPurpose.Listen */: + return null; + case "TargetPurposeExistenceFilterMismatch" /* TargetPurpose.ExistenceFilterMismatch */: + return 'existence-filter-mismatch'; + case "TargetPurposeExistenceFilterMismatchBloom" /* TargetPurpose.ExistenceFilterMismatchBloom */: + return 'existence-filter-mismatch-bloom'; + case "TargetPurposeLimboResolution" /* TargetPurpose.LimboResolution */: + return 'limbo-document'; + default: + return fail(0x713b, { purpose }); + } +} +function toTarget(serializer, targetData) { + let result; + const target = targetData.target; + if (targetIsDocumentTarget(target)) { + result = { documents: toDocumentsTarget(serializer, target) }; + } + else { + result = { query: toQueryTarget(serializer, target).queryTarget }; + } + result.targetId = targetData.targetId; + if (targetData.resumeToken.approximateByteSize() > 0) { + result.resumeToken = toBytes(serializer, targetData.resumeToken); + const expectedCount = toInt32Proto(serializer, targetData.expectedCount); + if (expectedCount !== null) { + result.expectedCount = expectedCount; + } + } + else if (targetData.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) { + // TODO(wuandy): Consider removing above check because it is most likely true. + // Right now, many tests depend on this behaviour though (leaving min() out + // of serialization). + result.readTime = toTimestamp(serializer, targetData.snapshotVersion.toTimestamp()); + const expectedCount = toInt32Proto(serializer, targetData.expectedCount); + if (expectedCount !== null) { + result.expectedCount = expectedCount; + } + } + return result; +} +function toFilters(filters) { + if (filters.length === 0) { + return; + } + return toFilter(CompositeFilter.create(filters, "and" /* CompositeOperator.AND */)); +} +function fromFilters(filter) { + const result = fromFilter(filter); + if (result instanceof CompositeFilter && + compositeFilterIsFlatConjunction(result)) { + return result.getFilters(); + } + return [result]; +} +function fromFilter(filter) { + if (filter.unaryFilter !== undefined) { + return fromUnaryFilter(filter); + } + else if (filter.fieldFilter !== undefined) { + return fromFieldFilter(filter); + } + else if (filter.compositeFilter !== undefined) { + return fromCompositeFilter(filter); + } + else { + return fail(0x7591, { filter }); + } +} +function toOrder(orderBys) { + if (orderBys.length === 0) { + return; + } + return orderBys.map(order => toPropertyOrder(order)); +} +function fromOrder(orderBys) { + return orderBys.map(order => fromPropertyOrder(order)); +} +function toStartAtCursor(cursor) { + return { + before: cursor.inclusive, + values: cursor.position + }; +} +function toEndAtCursor(cursor) { + return { + before: !cursor.inclusive, + values: cursor.position + }; +} +function fromStartAtCursor(cursor) { + const inclusive = !!cursor.before; + const position = cursor.values || []; + return new Bound(position, inclusive); +} +function fromEndAtCursor(cursor) { + const inclusive = !cursor.before; + const position = cursor.values || []; + return new Bound(position, inclusive); +} +// visible for testing +function toDirection(dir) { + return DIRECTIONS[dir]; +} +// visible for testing +function fromDirection(dir) { + switch (dir) { + case 'ASCENDING': + return "asc" /* Direction.ASCENDING */; + case 'DESCENDING': + return "desc" /* Direction.DESCENDING */; + default: + return undefined; + } +} +// visible for testing +function toOperatorName(op) { + return OPERATORS[op]; +} +function toCompositeOperatorName(op) { + return COMPOSITE_OPERATORS[op]; +} +function fromOperatorName(op) { + switch (op) { + case 'EQUAL': + return "==" /* Operator.EQUAL */; + case 'NOT_EQUAL': + return "!=" /* Operator.NOT_EQUAL */; + case 'GREATER_THAN': + return ">" /* Operator.GREATER_THAN */; + case 'GREATER_THAN_OR_EQUAL': + return ">=" /* Operator.GREATER_THAN_OR_EQUAL */; + case 'LESS_THAN': + return "<" /* Operator.LESS_THAN */; + case 'LESS_THAN_OR_EQUAL': + return "<=" /* Operator.LESS_THAN_OR_EQUAL */; + case 'ARRAY_CONTAINS': + return "array-contains" /* Operator.ARRAY_CONTAINS */; + case 'IN': + return "in" /* Operator.IN */; + case 'NOT_IN': + return "not-in" /* Operator.NOT_IN */; + case 'ARRAY_CONTAINS_ANY': + return "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */; + case 'OPERATOR_UNSPECIFIED': + return fail(0xe2fe); + default: + return fail(0xc54a); + } +} +function fromCompositeOperatorName(op) { + switch (op) { + case 'AND': + return "and" /* CompositeOperator.AND */; + case 'OR': + return "or" /* CompositeOperator.OR */; + default: + return fail(0x0402); + } +} +function toFieldPathReference(path) { + return { fieldPath: path.canonicalString() }; +} +function fromFieldPathReference(fieldReference) { + return FieldPath$1.fromServerFormat(fieldReference.fieldPath); +} +// visible for testing +function toPropertyOrder(orderBy) { + return { + field: toFieldPathReference(orderBy.field), + direction: toDirection(orderBy.dir) + }; +} +function fromPropertyOrder(orderBy) { + return new OrderBy(fromFieldPathReference(orderBy.field), fromDirection(orderBy.direction)); +} +// visible for testing +function toFilter(filter) { + if (filter instanceof FieldFilter) { + return toUnaryOrFieldFilter(filter); + } + else if (filter instanceof CompositeFilter) { + return toCompositeFilter(filter); + } + else { + return fail(0xd65d, { filter }); + } +} +function toCompositeFilter(filter) { + const protos = filter.getFilters().map(filter => toFilter(filter)); + if (protos.length === 1) { + return protos[0]; + } + return { + compositeFilter: { + op: toCompositeOperatorName(filter.op), + filters: protos + } + }; +} +function toUnaryOrFieldFilter(filter) { + if (filter.op === "==" /* Operator.EQUAL */) { + if (isNanValue(filter.value)) { + return { + unaryFilter: { + field: toFieldPathReference(filter.field), + op: 'IS_NAN' + } + }; + } + else if (isNullValue(filter.value)) { + return { + unaryFilter: { + field: toFieldPathReference(filter.field), + op: 'IS_NULL' + } + }; + } + } + else if (filter.op === "!=" /* Operator.NOT_EQUAL */) { + if (isNanValue(filter.value)) { + return { + unaryFilter: { + field: toFieldPathReference(filter.field), + op: 'IS_NOT_NAN' + } + }; + } + else if (isNullValue(filter.value)) { + return { + unaryFilter: { + field: toFieldPathReference(filter.field), + op: 'IS_NOT_NULL' + } + }; + } + } + return { + fieldFilter: { + field: toFieldPathReference(filter.field), + op: toOperatorName(filter.op), + value: filter.value + } + }; +} +function fromUnaryFilter(filter) { + switch (filter.unaryFilter.op) { + case 'IS_NAN': + const nanField = fromFieldPathReference(filter.unaryFilter.field); + return FieldFilter.create(nanField, "==" /* Operator.EQUAL */, { + doubleValue: NaN + }); + case 'IS_NULL': + const nullField = fromFieldPathReference(filter.unaryFilter.field); + return FieldFilter.create(nullField, "==" /* Operator.EQUAL */, { + nullValue: 'NULL_VALUE' + }); + case 'IS_NOT_NAN': + const notNanField = fromFieldPathReference(filter.unaryFilter.field); + return FieldFilter.create(notNanField, "!=" /* Operator.NOT_EQUAL */, { + doubleValue: NaN + }); + case 'IS_NOT_NULL': + const notNullField = fromFieldPathReference(filter.unaryFilter.field); + return FieldFilter.create(notNullField, "!=" /* Operator.NOT_EQUAL */, { + nullValue: 'NULL_VALUE' + }); + case 'OPERATOR_UNSPECIFIED': + return fail(0xef81); + default: + return fail(0xed36); + } +} +function fromFieldFilter(filter) { + return FieldFilter.create(fromFieldPathReference(filter.fieldFilter.field), fromOperatorName(filter.fieldFilter.op), filter.fieldFilter.value); +} +function fromCompositeFilter(filter) { + return CompositeFilter.create(filter.compositeFilter.filters.map(filter => fromFilter(filter)), fromCompositeOperatorName(filter.compositeFilter.op)); +} +function toDocumentMask(fieldMask) { + const canonicalFields = []; + fieldMask.fields.forEach(field => canonicalFields.push(field.canonicalString())); + return { + fieldPaths: canonicalFields + }; +} +function fromDocumentMask(proto) { + const paths = proto.fieldPaths || []; + return new FieldMask(paths.map(path => FieldPath$1.fromServerFormat(path))); +} +function isValidResourceName(path) { + // Resource names have at least 4 components (project ID, database ID) + return (path.length >= 4 && + path.get(0) === 'projects' && + path.get(2) === 'databases'); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable set of metadata that the local store tracks for each target. + */ +class TargetData { + constructor( + /** The target being listened to. */ + target, + /** + * The target ID to which the target corresponds; Assigned by the + * LocalStore for user listens and by the SyncEngine for limbo watches. + */ + targetId, + /** The purpose of the target. */ + purpose, + /** + * The sequence number of the last transaction during which this target data + * was modified. + */ + sequenceNumber, + /** The latest snapshot version seen for this target. */ + snapshotVersion = SnapshotVersion.min(), + /** + * The maximum snapshot version at which the associated view + * contained no limbo documents. + */ + lastLimboFreeSnapshotVersion = SnapshotVersion.min(), + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + resumeToken = ByteString.EMPTY_BYTE_STRING, + /** + * The number of documents that last matched the query at the resume token or + * read time. Documents are counted only when making a listen request with + * resume token or read time, otherwise, keep it null. + */ + expectedCount = null) { + this.target = target; + this.targetId = targetId; + this.purpose = purpose; + this.sequenceNumber = sequenceNumber; + this.snapshotVersion = snapshotVersion; + this.lastLimboFreeSnapshotVersion = lastLimboFreeSnapshotVersion; + this.resumeToken = resumeToken; + this.expectedCount = expectedCount; + } + /** Creates a new target data instance with an updated sequence number. */ + withSequenceNumber(sequenceNumber) { + return new TargetData(this.target, this.targetId, this.purpose, sequenceNumber, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, this.expectedCount); + } + /** + * Creates a new target data instance with an updated resume token and + * snapshot version. + */ + withResumeToken(resumeToken, snapshotVersion) { + return new TargetData(this.target, this.targetId, this.purpose, this.sequenceNumber, snapshotVersion, this.lastLimboFreeSnapshotVersion, resumeToken, + /* expectedCount= */ null); + } + /** + * Creates a new target data instance with an updated expected count. + */ + withExpectedCount(expectedCount) { + return new TargetData(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, expectedCount); + } + /** + * Creates a new target data instance with an updated last limbo free + * snapshot version number. + */ + withLastLimboFreeSnapshotVersion(lastLimboFreeSnapshotVersion) { + return new TargetData(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, lastLimboFreeSnapshotVersion, this.resumeToken, this.expectedCount); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Serializer for values stored in the LocalStore. */ +class LocalSerializer { + constructor(remoteSerializer) { + this.remoteSerializer = remoteSerializer; + } +} +/** Decodes a remote document from storage locally to a Document. */ +function fromDbRemoteDocument(localSerializer, remoteDoc) { + let doc; + if (remoteDoc.document) { + doc = fromDocument(localSerializer.remoteSerializer, remoteDoc.document, !!remoteDoc.hasCommittedMutations); + } + else if (remoteDoc.noDocument) { + const key = DocumentKey.fromSegments(remoteDoc.noDocument.path); + const version = fromDbTimestamp(remoteDoc.noDocument.readTime); + doc = MutableDocument.newNoDocument(key, version); + if (remoteDoc.hasCommittedMutations) { + doc.setHasCommittedMutations(); + } + } + else if (remoteDoc.unknownDocument) { + const key = DocumentKey.fromSegments(remoteDoc.unknownDocument.path); + const version = fromDbTimestamp(remoteDoc.unknownDocument.version); + doc = MutableDocument.newUnknownDocument(key, version); + } + else { + return fail(0xdd85); + } + if (remoteDoc.readTime) { + doc.setReadTime(fromDbTimestampKey(remoteDoc.readTime)); + } + return doc; +} +/** Encodes a document for storage locally. */ +function toDbRemoteDocument(localSerializer, document) { + const key = document.key; + const remoteDoc = { + prefixPath: key.getCollectionPath().popLast().toArray(), + collectionGroup: key.collectionGroup, + documentId: key.path.lastSegment(), + readTime: toDbTimestampKey(document.readTime), + hasCommittedMutations: document.hasCommittedMutations + }; + if (document.isFoundDocument()) { + remoteDoc.document = toDocument(localSerializer.remoteSerializer, document); + } + else if (document.isNoDocument()) { + remoteDoc.noDocument = { + path: key.path.toArray(), + readTime: toDbTimestamp(document.version) + }; + } + else if (document.isUnknownDocument()) { + remoteDoc.unknownDocument = { + path: key.path.toArray(), + version: toDbTimestamp(document.version) + }; + } + else { + return fail(0xe230, { document }); + } + return remoteDoc; +} +function toDbTimestampKey(snapshotVersion) { + const timestamp = snapshotVersion.toTimestamp(); + return [timestamp.seconds, timestamp.nanoseconds]; +} +function fromDbTimestampKey(dbTimestampKey) { + const timestamp = new Timestamp(dbTimestampKey[0], dbTimestampKey[1]); + return SnapshotVersion.fromTimestamp(timestamp); +} +function toDbTimestamp(snapshotVersion) { + const timestamp = snapshotVersion.toTimestamp(); + return { seconds: timestamp.seconds, nanoseconds: timestamp.nanoseconds }; +} +function fromDbTimestamp(dbTimestamp) { + const timestamp = new Timestamp(dbTimestamp.seconds, dbTimestamp.nanoseconds); + return SnapshotVersion.fromTimestamp(timestamp); +} +/** Encodes a batch of mutations into a DbMutationBatch for local storage. */ +function toDbMutationBatch(localSerializer, userId, batch) { + const serializedBaseMutations = batch.baseMutations.map(m => toMutation(localSerializer.remoteSerializer, m)); + const serializedMutations = batch.mutations.map(m => toMutation(localSerializer.remoteSerializer, m)); + return { + userId, + batchId: batch.batchId, + localWriteTimeMs: batch.localWriteTime.toMillis(), + baseMutations: serializedBaseMutations, + mutations: serializedMutations + }; +} +/** Decodes a DbMutationBatch into a MutationBatch */ +function fromDbMutationBatch(localSerializer, dbBatch) { + const baseMutations = (dbBatch.baseMutations || []).map(m => fromMutation(localSerializer.remoteSerializer, m)); + // Squash old transform mutations into existing patch or set mutations. + // The replacement of representing `transforms` with `update_transforms` + // on the SDK means that old `transform` mutations stored in IndexedDB need + // to be updated to `update_transforms`. + // TODO(b/174608374): Remove this code once we perform a schema migration. + for (let i = 0; i < dbBatch.mutations.length - 1; ++i) { + const currentMutation = dbBatch.mutations[i]; + const hasTransform = i + 1 < dbBatch.mutations.length && + dbBatch.mutations[i + 1].transform !== undefined; + if (hasTransform) { + const transformMutation = dbBatch.mutations[i + 1]; + currentMutation.updateTransforms = + transformMutation.transform.fieldTransforms; + dbBatch.mutations.splice(i + 1, 1); + ++i; + } + } + const mutations = dbBatch.mutations.map(m => fromMutation(localSerializer.remoteSerializer, m)); + const timestamp = Timestamp.fromMillis(dbBatch.localWriteTimeMs); + return new MutationBatch(dbBatch.batchId, timestamp, baseMutations, mutations); +} +/** Decodes a DbTarget into TargetData */ +function fromDbTarget(dbTarget) { + const version = fromDbTimestamp(dbTarget.readTime); + const lastLimboFreeSnapshotVersion = dbTarget.lastLimboFreeSnapshotVersion !== undefined + ? fromDbTimestamp(dbTarget.lastLimboFreeSnapshotVersion) + : SnapshotVersion.min(); + let target; + if (isDocumentQuery(dbTarget.query)) { + target = fromDocumentsTarget(dbTarget.query); + } + else { + target = fromQueryTarget(dbTarget.query); + } + return new TargetData(target, dbTarget.targetId, "TargetPurposeListen" /* TargetPurpose.Listen */, dbTarget.lastListenSequenceNumber, version, lastLimboFreeSnapshotVersion, ByteString.fromBase64String(dbTarget.resumeToken)); +} +/** Encodes TargetData into a DbTarget for storage locally. */ +function toDbTarget(localSerializer, targetData) { + const dbTimestamp = toDbTimestamp(targetData.snapshotVersion); + const dbLastLimboFreeTimestamp = toDbTimestamp(targetData.lastLimboFreeSnapshotVersion); + let queryProto; + if (targetIsDocumentTarget(targetData.target)) { + queryProto = toDocumentsTarget(localSerializer.remoteSerializer, targetData.target); + } + else { + queryProto = toQueryTarget(localSerializer.remoteSerializer, targetData.target).queryTarget; + } + // We can't store the resumeToken as a ByteString in IndexedDb, so we + // convert it to a base64 string for storage. + const resumeToken = targetData.resumeToken.toBase64(); + // lastListenSequenceNumber is always 0 until we do real GC. + return { + targetId: targetData.targetId, + canonicalId: canonifyTarget(targetData.target), + readTime: dbTimestamp, + resumeToken, + lastListenSequenceNumber: targetData.sequenceNumber, + lastLimboFreeSnapshotVersion: dbLastLimboFreeTimestamp, + query: queryProto + }; +} +/** + * A helper function for figuring out what kind of query has been stored. + */ +function isDocumentQuery(dbQuery) { + return dbQuery.documents !== undefined; +} +/** Encodes a DbBundle to a BundleMetadata object. */ +function fromDbBundle(dbBundle) { + return { + id: dbBundle.bundleId, + createTime: fromDbTimestamp(dbBundle.createTime), + version: dbBundle.version + }; +} +/** Encodes a BundleMetadata to a DbBundle. */ +function toDbBundle(metadata) { + return { + bundleId: metadata.id, + createTime: toDbTimestamp(fromVersion(metadata.createTime)), + version: metadata.version + }; +} +/** Encodes a DbNamedQuery to a NamedQuery. */ +function fromDbNamedQuery(dbNamedQuery) { + return { + name: dbNamedQuery.name, + query: fromBundledQuery(dbNamedQuery.bundledQuery), + readTime: fromDbTimestamp(dbNamedQuery.readTime) + }; +} +/** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */ +function toDbNamedQuery(query) { + return { + name: query.name, + readTime: toDbTimestamp(fromVersion(query.readTime)), + bundledQuery: query.bundledQuery + }; +} +/** + * Encodes a `BundledQuery` from bundle proto to a Query object. + * + * This reconstructs the original query used to build the bundle being loaded, + * including features exists only in SDKs (for example: limit-to-last). + */ +function fromBundledQuery(bundledQuery) { + const query = convertQueryTargetToQuery({ + parent: bundledQuery.parent, + structuredQuery: bundledQuery.structuredQuery + }); + if (bundledQuery.limitType === 'LAST') { + return queryWithLimit(query, query.limit, "L" /* LimitType.Last */); + } + return query; +} +/** Encodes a NamedQuery proto object to a NamedQuery model object. */ +function fromProtoNamedQuery(namedQuery) { + return { + name: namedQuery.name, + query: fromBundledQuery(namedQuery.bundledQuery), + readTime: fromVersion(namedQuery.readTime) + }; +} +/** Decodes a BundleMetadata proto into a BundleMetadata object. */ +function fromBundleMetadata(metadata) { + return { + id: metadata.id, + version: metadata.version, + createTime: fromVersion(metadata.createTime) + }; +} +/** Encodes a DbDocumentOverlay object to an Overlay model object. */ +function fromDbDocumentOverlay(localSerializer, dbDocumentOverlay) { + return new Overlay(dbDocumentOverlay.largestBatchId, fromMutation(localSerializer.remoteSerializer, dbDocumentOverlay.overlayMutation)); +} +/** Decodes an Overlay model object into a DbDocumentOverlay object. */ +function toDbDocumentOverlay(localSerializer, userId, overlay) { + const [_, collectionPath, documentId] = toDbDocumentOverlayKey(userId, overlay.mutation.key); + return { + userId, + collectionPath, + documentId, + collectionGroup: overlay.mutation.key.getCollectionGroup(), + largestBatchId: overlay.largestBatchId, + overlayMutation: toMutation(localSerializer.remoteSerializer, overlay.mutation) + }; +} +/** + * Returns the DbDocumentOverlayKey corresponding to the given user and + * document key. + */ +function toDbDocumentOverlayKey(userId, docKey) { + const docId = docKey.path.lastSegment(); + const collectionPath = encodeResourcePath(docKey.path.popLast()); + return [userId, collectionPath, docId]; +} +function toDbIndexConfiguration(index) { + return { + indexId: index.indexId, + collectionGroup: index.collectionGroup, + fields: index.fields.map(s => [s.fieldPath.canonicalString(), s.kind]) + }; +} +function fromDbIndexConfiguration(index, state) { + const decodedState = state + ? new IndexState(state.sequenceNumber, new IndexOffset(fromDbTimestamp(state.readTime), new DocumentKey(decodeResourcePath(state.documentKey)), state.largestBatchId)) + : IndexState.empty(); + const decodedSegments = index.fields.map(([fieldPath, kind]) => new IndexSegment(FieldPath$1.fromServerFormat(fieldPath), kind)); + return new FieldIndex(index.indexId, index.collectionGroup, decodedSegments, decodedState); +} +function toDbIndexState(indexId, uid, sequenceNumber, offset) { + return { + indexId, + uid, + sequenceNumber, + readTime: toDbTimestamp(offset.readTime), + documentKey: encodeResourcePath(offset.documentKey.path), + largestBatchId: offset.largestBatchId + }; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class IndexedDbBundleCache { + getBundleMetadata(transaction, bundleId) { + return bundlesStore(transaction) + .get(bundleId) + .next(bundle => { + if (bundle) { + return fromDbBundle(bundle); + } + return undefined; + }); + } + saveBundleMetadata(transaction, bundleMetadata) { + return bundlesStore(transaction).put(toDbBundle(bundleMetadata)); + } + getNamedQuery(transaction, queryName) { + return namedQueriesStore(transaction) + .get(queryName) + .next(query => { + if (query) { + return fromDbNamedQuery(query); + } + return undefined; + }); + } + saveNamedQuery(transaction, query) { + return namedQueriesStore(transaction).put(toDbNamedQuery(query)); + } +} +/** + * Helper to get a typed SimpleDbStore for the bundles object store. + */ +function bundlesStore(txn) { + return getStore(txn, DbBundleStore); +} +/** + * Helper to get a typed SimpleDbStore for the namedQueries object store. + */ +function namedQueriesStore(txn) { + return getStore(txn, DbNamedQueryStore); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Implementation of DocumentOverlayCache using IndexedDb. + */ +class IndexedDbDocumentOverlayCache { + /** + * @param serializer - The document serializer. + * @param userId - The userId for which we are accessing overlays. + */ + constructor(serializer, userId) { + this.serializer = serializer; + this.userId = userId; + } + static forUser(serializer, user) { + const userId = user.uid || ''; + return new IndexedDbDocumentOverlayCache(serializer, userId); + } + getOverlay(transaction, key) { + return documentOverlayStore(transaction) + .get(toDbDocumentOverlayKey(this.userId, key)) + .next(dbOverlay => { + if (dbOverlay) { + return fromDbDocumentOverlay(this.serializer, dbOverlay); + } + return null; + }); + } + getOverlays(transaction, keys) { + const result = newOverlayMap(); + return PersistencePromise.forEach(keys, (key) => { + return this.getOverlay(transaction, key).next(overlay => { + if (overlay !== null) { + result.set(key, overlay); + } + }); + }).next(() => result); + } + saveOverlays(transaction, largestBatchId, overlays) { + const promises = []; + overlays.forEach((_, mutation) => { + const overlay = new Overlay(largestBatchId, mutation); + promises.push(this.saveOverlay(transaction, overlay)); + }); + return PersistencePromise.waitFor(promises); + } + removeOverlaysForBatchId(transaction, documentKeys, batchId) { + const collectionPaths = new Set(); + // Get the set of unique collection paths. + documentKeys.forEach(key => collectionPaths.add(encodeResourcePath(key.getCollectionPath()))); + const promises = []; + collectionPaths.forEach(collectionPath => { + const range = IDBKeyRange.bound([this.userId, collectionPath, batchId], [this.userId, collectionPath, batchId + 1], + /*lowerOpen=*/ false, + /*upperOpen=*/ true); + promises.push(documentOverlayStore(transaction).deleteAll(DbDocumentOverlayCollectionPathOverlayIndex, range)); + }); + return PersistencePromise.waitFor(promises); + } + getOverlaysForCollection(transaction, collection, sinceBatchId) { + const result = newOverlayMap(); + const collectionPath = encodeResourcePath(collection); + // We want batch IDs larger than `sinceBatchId`, and so the lower bound + // is not inclusive. + const range = IDBKeyRange.bound([this.userId, collectionPath, sinceBatchId], [this.userId, collectionPath, Number.POSITIVE_INFINITY], + /*lowerOpen=*/ true); + return documentOverlayStore(transaction) + .loadAll(DbDocumentOverlayCollectionPathOverlayIndex, range) + .next(dbOverlays => { + for (const dbOverlay of dbOverlays) { + const overlay = fromDbDocumentOverlay(this.serializer, dbOverlay); + result.set(overlay.getKey(), overlay); + } + return result; + }); + } + getOverlaysForCollectionGroup(transaction, collectionGroup, sinceBatchId, count) { + const result = newOverlayMap(); + let currentBatchId = undefined; + // We want batch IDs larger than `sinceBatchId`, and so the lower bound + // is not inclusive. + const range = IDBKeyRange.bound([this.userId, collectionGroup, sinceBatchId], [this.userId, collectionGroup, Number.POSITIVE_INFINITY], + /*lowerOpen=*/ true); + return documentOverlayStore(transaction) + .iterate({ + index: DbDocumentOverlayCollectionGroupOverlayIndex, + range + }, (_, dbOverlay, control) => { + // We do not want to return partial batch overlays, even if the size + // of the result set exceeds the given `count` argument. Therefore, we + // continue to aggregate results even after the result size exceeds + // `count` if there are more overlays from the `currentBatchId`. + const overlay = fromDbDocumentOverlay(this.serializer, dbOverlay); + if (result.size() < count || + overlay.largestBatchId === currentBatchId) { + result.set(overlay.getKey(), overlay); + currentBatchId = overlay.largestBatchId; + } + else { + control.done(); + } + }) + .next(() => result); + } + saveOverlay(transaction, overlay) { + return documentOverlayStore(transaction).put(toDbDocumentOverlay(this.serializer, this.userId, overlay)); + } +} +/** + * Helper to get a typed SimpleDbStore for the document overlay object store. + */ +function documentOverlayStore(txn) { + return getStore(txn, DbDocumentOverlayStore); +} + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class IndexedDbGlobalsCache { + globalsStore(txn) { + return getStore(txn, DbGlobalsStore); + } + getSessionToken(txn) { + const globals = this.globalsStore(txn); + return globals.get('sessionToken').next(global => { + const value = global?.value; + return value + ? ByteString.fromUint8Array(value) + : ByteString.EMPTY_BYTE_STRING; + }); + } + setSessionToken(txn, sessionToken) { + const globals = this.globalsStore(txn); + return globals.put({ + name: 'sessionToken', + value: sessionToken.toUint8Array() + }); + } +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Note: This code is copied from the backend. Code that is not used by +// Firestore was removed. +const INDEX_TYPE_NULL = 5; +const INDEX_TYPE_BOOLEAN = 10; +const INDEX_TYPE_NAN = 13; +const INDEX_TYPE_NUMBER = 15; +const INDEX_TYPE_TIMESTAMP = 20; +const INDEX_TYPE_STRING = 25; +const INDEX_TYPE_BLOB = 30; +const INDEX_TYPE_REFERENCE = 37; +const INDEX_TYPE_GEOPOINT = 45; +const INDEX_TYPE_ARRAY = 50; +const INDEX_TYPE_VECTOR = 53; +const INDEX_TYPE_MAP = 55; +const INDEX_TYPE_REFERENCE_SEGMENT = 60; +// A terminator that indicates that a truncatable value was not truncated. +// This must be smaller than all other type labels. +const NOT_TRUNCATED = 2; +/** Firestore index value writer. */ +class FirestoreIndexValueWriter { + constructor() { } + // The write methods below short-circuit writing terminators for values + // containing a (terminating) truncated value. + // + // As an example, consider the resulting encoding for: + // + // ["bar", [2, "foo"]] -> (STRING, "bar", TERM, ARRAY, NUMBER, 2, STRING, "foo", TERM, TERM, TERM) + // ["bar", [2, truncated("foo")]] -> (STRING, "bar", TERM, ARRAY, NUMBER, 2, STRING, "foo", TRUNC) + // ["bar", truncated(["foo"])] -> (STRING, "bar", TERM, ARRAY. STRING, "foo", TERM, TRUNC) + /** Writes an index value. */ + writeIndexValue(value, encoder) { + this.writeIndexValueAux(value, encoder); + // Write separator to split index values + // (see go/firestore-storage-format#encodings). + encoder.writeInfinity(); + } + writeIndexValueAux(indexValue, encoder) { + if ('nullValue' in indexValue) { + this.writeValueTypeLabel(encoder, INDEX_TYPE_NULL); + } + else if ('booleanValue' in indexValue) { + this.writeValueTypeLabel(encoder, INDEX_TYPE_BOOLEAN); + encoder.writeNumber(indexValue.booleanValue ? 1 : 0); + } + else if ('integerValue' in indexValue) { + this.writeValueTypeLabel(encoder, INDEX_TYPE_NUMBER); + encoder.writeNumber(normalizeNumber(indexValue.integerValue)); + } + else if ('doubleValue' in indexValue) { + const n = normalizeNumber(indexValue.doubleValue); + if (isNaN(n)) { + this.writeValueTypeLabel(encoder, INDEX_TYPE_NAN); + } + else { + this.writeValueTypeLabel(encoder, INDEX_TYPE_NUMBER); + if (isNegativeZero(n)) { + // -0.0, 0 and 0.0 are all considered the same + encoder.writeNumber(0.0); + } + else { + encoder.writeNumber(n); + } + } + } + else if ('timestampValue' in indexValue) { + let timestamp = indexValue.timestampValue; + this.writeValueTypeLabel(encoder, INDEX_TYPE_TIMESTAMP); + if (typeof timestamp === 'string') { + timestamp = normalizeTimestamp(timestamp); + } + encoder.writeString(`${timestamp.seconds || ''}`); + encoder.writeNumber(timestamp.nanos || 0); + } + else if ('stringValue' in indexValue) { + this.writeIndexString(indexValue.stringValue, encoder); + this.writeTruncationMarker(encoder); + } + else if ('bytesValue' in indexValue) { + this.writeValueTypeLabel(encoder, INDEX_TYPE_BLOB); + encoder.writeBytes(normalizeByteString(indexValue.bytesValue)); + this.writeTruncationMarker(encoder); + } + else if ('referenceValue' in indexValue) { + this.writeIndexEntityRef(indexValue.referenceValue, encoder); + } + else if ('geoPointValue' in indexValue) { + const geoPoint = indexValue.geoPointValue; + this.writeValueTypeLabel(encoder, INDEX_TYPE_GEOPOINT); + encoder.writeNumber(geoPoint.latitude || 0); + encoder.writeNumber(geoPoint.longitude || 0); + } + else if ('mapValue' in indexValue) { + if (isMaxValue(indexValue)) { + this.writeValueTypeLabel(encoder, Number.MAX_SAFE_INTEGER); + } + else if (isVectorValue(indexValue)) { + this.writeIndexVector(indexValue.mapValue, encoder); + } + else { + this.writeIndexMap(indexValue.mapValue, encoder); + this.writeTruncationMarker(encoder); + } + } + else if ('arrayValue' in indexValue) { + this.writeIndexArray(indexValue.arrayValue, encoder); + this.writeTruncationMarker(encoder); + } + else { + fail(0x4a4e, { indexValue }); + } + } + writeIndexString(stringIndexValue, encoder) { + this.writeValueTypeLabel(encoder, INDEX_TYPE_STRING); + this.writeUnlabeledIndexString(stringIndexValue, encoder); + } + writeUnlabeledIndexString(stringIndexValue, encoder) { + encoder.writeString(stringIndexValue); + } + writeIndexMap(mapIndexValue, encoder) { + const map = mapIndexValue.fields || {}; + this.writeValueTypeLabel(encoder, INDEX_TYPE_MAP); + for (const key of Object.keys(map)) { + this.writeIndexString(key, encoder); + this.writeIndexValueAux(map[key], encoder); + } + } + writeIndexVector(mapIndexValue, encoder) { + const map = mapIndexValue.fields || {}; + this.writeValueTypeLabel(encoder, INDEX_TYPE_VECTOR); + // Vectors sort first by length + const key = VECTOR_MAP_VECTORS_KEY; + const length = map[key].arrayValue?.values?.length || 0; + this.writeValueTypeLabel(encoder, INDEX_TYPE_NUMBER); + encoder.writeNumber(normalizeNumber(length)); + // Vectors then sort by position value + this.writeIndexString(key, encoder); + this.writeIndexValueAux(map[key], encoder); + } + writeIndexArray(arrayIndexValue, encoder) { + const values = arrayIndexValue.values || []; + this.writeValueTypeLabel(encoder, INDEX_TYPE_ARRAY); + for (const element of values) { + this.writeIndexValueAux(element, encoder); + } + } + writeIndexEntityRef(referenceValue, encoder) { + this.writeValueTypeLabel(encoder, INDEX_TYPE_REFERENCE); + const path = DocumentKey.fromName(referenceValue).path; + path.forEach(segment => { + this.writeValueTypeLabel(encoder, INDEX_TYPE_REFERENCE_SEGMENT); + this.writeUnlabeledIndexString(segment, encoder); + }); + } + writeValueTypeLabel(encoder, typeOrder) { + encoder.writeNumber(typeOrder); + } + writeTruncationMarker(encoder) { + // While the SDK does not implement truncation, the truncation marker is + // used to terminate all variable length values (which are strings, bytes, + // references, arrays and maps). + encoder.writeNumber(NOT_TRUNCATED); + } +} +FirestoreIndexValueWriter.INSTANCE = new FirestoreIndexValueWriter(); + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law | agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES | CONDITIONS OF ANY KIND, either express | implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** These constants are taken from the backend. */ +const MIN_SURROGATE = '\uD800'; +const MAX_SURROGATE = '\uDBFF'; +const ESCAPE1 = 0x00; +const NULL_BYTE = 0xff; // Combined with ESCAPE1 +const SEPARATOR = 0x01; // Combined with ESCAPE1 +const ESCAPE2 = 0xff; +const INFINITY = 0xff; // Combined with ESCAPE2 +const FF_BYTE = 0x00; // Combined with ESCAPE2 +const LONG_SIZE = 64; +const BYTE_SIZE = 8; +/** + * The default size of the buffer. This is arbitrary, but likely larger than + * most index values so that less copies of the underlying buffer will be made. + * For large values, a single copy will made to double the buffer length. + */ +const DEFAULT_BUFFER_SIZE = 1024; +/** Converts a JavaScript number to a byte array (using big endian encoding). */ +function doubleToLongBits(value) { + const dv = new DataView(new ArrayBuffer(8)); + dv.setFloat64(0, value, /* littleEndian= */ false); + return new Uint8Array(dv.buffer); +} +/** + * Counts the number of zeros in a byte. + * + * Visible for testing. + */ +function numberOfLeadingZerosInByte(x) { + if (x === 0) { + return 8; + } + let zeros = 0; + if (x >> 4 === 0) { + // Test if the first four bits are zero. + zeros += 4; + x = x << 4; + } + if (x >> 6 === 0) { + // Test if the first two (or next two) bits are zero. + zeros += 2; + x = x << 2; + } + if (x >> 7 === 0) { + // Test if the remaining bit is zero. + zeros += 1; + } + return zeros; +} +/** Counts the number of leading zeros in the given byte array. */ +function numberOfLeadingZeros(bytes) { + let leadingZeros = 0; + for (let i = 0; i < 8; ++i) { + const zeros = numberOfLeadingZerosInByte(bytes[i] & 0xff); + leadingZeros += zeros; + if (zeros !== 8) { + break; + } + } + return leadingZeros; +} +/** + * Returns the number of bytes required to store "value". Leading zero bytes + * are skipped. + */ +function unsignedNumLength(value) { + // This is just the number of bytes for the unsigned representation of the number. + const numBits = LONG_SIZE - numberOfLeadingZeros(value); + return Math.ceil(numBits / BYTE_SIZE); +} +/** + * OrderedCodeWriter is a minimal-allocation implementation of the writing + * behavior defined by the backend. + * + * The code is ported from its Java counterpart. + */ +class OrderedCodeWriter { + constructor() { + this.buffer = new Uint8Array(DEFAULT_BUFFER_SIZE); + this.position = 0; + } + writeBytesAscending(value) { + const it = value[Symbol.iterator](); + let byte = it.next(); + while (!byte.done) { + this.writeByteAscending(byte.value); + byte = it.next(); + } + this.writeSeparatorAscending(); + } + writeBytesDescending(value) { + const it = value[Symbol.iterator](); + let byte = it.next(); + while (!byte.done) { + this.writeByteDescending(byte.value); + byte = it.next(); + } + this.writeSeparatorDescending(); + } + /** Writes utf8 bytes into this byte sequence, ascending. */ + writeUtf8Ascending(sequence) { + for (const c of sequence) { + const charCode = c.charCodeAt(0); + if (charCode < 0x80) { + this.writeByteAscending(charCode); + } + else if (charCode < 0x800) { + this.writeByteAscending((0x0f << 6) | (charCode >>> 6)); + this.writeByteAscending(0x80 | (0x3f & charCode)); + } + else if (c < MIN_SURROGATE || MAX_SURROGATE < c) { + this.writeByteAscending((0x0f << 5) | (charCode >>> 12)); + this.writeByteAscending(0x80 | (0x3f & (charCode >>> 6))); + this.writeByteAscending(0x80 | (0x3f & charCode)); + } + else { + const codePoint = c.codePointAt(0); + this.writeByteAscending((0x0f << 4) | (codePoint >>> 18)); + this.writeByteAscending(0x80 | (0x3f & (codePoint >>> 12))); + this.writeByteAscending(0x80 | (0x3f & (codePoint >>> 6))); + this.writeByteAscending(0x80 | (0x3f & codePoint)); + } + } + this.writeSeparatorAscending(); + } + /** Writes utf8 bytes into this byte sequence, descending */ + writeUtf8Descending(sequence) { + for (const c of sequence) { + const charCode = c.charCodeAt(0); + if (charCode < 0x80) { + this.writeByteDescending(charCode); + } + else if (charCode < 0x800) { + this.writeByteDescending((0x0f << 6) | (charCode >>> 6)); + this.writeByteDescending(0x80 | (0x3f & charCode)); + } + else if (c < MIN_SURROGATE || MAX_SURROGATE < c) { + this.writeByteDescending((0x0f << 5) | (charCode >>> 12)); + this.writeByteDescending(0x80 | (0x3f & (charCode >>> 6))); + this.writeByteDescending(0x80 | (0x3f & charCode)); + } + else { + const codePoint = c.codePointAt(0); + this.writeByteDescending((0x0f << 4) | (codePoint >>> 18)); + this.writeByteDescending(0x80 | (0x3f & (codePoint >>> 12))); + this.writeByteDescending(0x80 | (0x3f & (codePoint >>> 6))); + this.writeByteDescending(0x80 | (0x3f & codePoint)); + } + } + this.writeSeparatorDescending(); + } + writeNumberAscending(val) { + // Values are encoded with a single byte length prefix, followed by the + // actual value in big-endian format with leading 0 bytes dropped. + const value = this.toOrderedBits(val); + const len = unsignedNumLength(value); + this.ensureAvailable(1 + len); + this.buffer[this.position++] = len & 0xff; // Write the length + for (let i = value.length - len; i < value.length; ++i) { + this.buffer[this.position++] = value[i] & 0xff; + } + } + writeNumberDescending(val) { + // Values are encoded with a single byte length prefix, followed by the + // inverted value in big-endian format with leading 0 bytes dropped. + const value = this.toOrderedBits(val); + const len = unsignedNumLength(value); + this.ensureAvailable(1 + len); + this.buffer[this.position++] = ~(len & 0xff); // Write the length + for (let i = value.length - len; i < value.length; ++i) { + this.buffer[this.position++] = ~(value[i] & 0xff); + } + } + /** + * Writes the "infinity" byte sequence that sorts after all other byte + * sequences written in ascending order. + */ + writeInfinityAscending() { + this.writeEscapedByteAscending(ESCAPE2); + this.writeEscapedByteAscending(INFINITY); + } + /** + * Writes the "infinity" byte sequence that sorts before all other byte + * sequences written in descending order. + */ + writeInfinityDescending() { + this.writeEscapedByteDescending(ESCAPE2); + this.writeEscapedByteDescending(INFINITY); + } + /** + * Resets the buffer such that it is the same as when it was newly + * constructed. + */ + reset() { + this.position = 0; + } + seed(encodedBytes) { + this.ensureAvailable(encodedBytes.length); + this.buffer.set(encodedBytes, this.position); + this.position += encodedBytes.length; + } + /** Makes a copy of the encoded bytes in this buffer. */ + encodedBytes() { + return this.buffer.slice(0, this.position); + } + /** + * Encodes `val` into an encoding so that the order matches the IEEE 754 + * floating-point comparison results with the following exceptions: + * -0.0 < 0.0 + * all non-NaN < NaN + * NaN = NaN + */ + toOrderedBits(val) { + const value = doubleToLongBits(val); + // Check if the first bit is set. We use a bit mask since value[0] is + // encoded as a number from 0 to 255. + const isNegative = (value[0] & 0x80) !== 0; + // Revert the two complement to get natural ordering + value[0] ^= isNegative ? 0xff : 0x80; + for (let i = 1; i < value.length; ++i) { + value[i] ^= isNegative ? 0xff : 0x00; + } + return value; + } + /** Writes a single byte ascending to the buffer. */ + writeByteAscending(b) { + const masked = b & 0xff; + if (masked === ESCAPE1) { + this.writeEscapedByteAscending(ESCAPE1); + this.writeEscapedByteAscending(NULL_BYTE); + } + else if (masked === ESCAPE2) { + this.writeEscapedByteAscending(ESCAPE2); + this.writeEscapedByteAscending(FF_BYTE); + } + else { + this.writeEscapedByteAscending(masked); + } + } + /** Writes a single byte descending to the buffer. */ + writeByteDescending(b) { + const masked = b & 0xff; + if (masked === ESCAPE1) { + this.writeEscapedByteDescending(ESCAPE1); + this.writeEscapedByteDescending(NULL_BYTE); + } + else if (masked === ESCAPE2) { + this.writeEscapedByteDescending(ESCAPE2); + this.writeEscapedByteDescending(FF_BYTE); + } + else { + this.writeEscapedByteDescending(b); + } + } + writeSeparatorAscending() { + this.writeEscapedByteAscending(ESCAPE1); + this.writeEscapedByteAscending(SEPARATOR); + } + writeSeparatorDescending() { + this.writeEscapedByteDescending(ESCAPE1); + this.writeEscapedByteDescending(SEPARATOR); + } + writeEscapedByteAscending(b) { + this.ensureAvailable(1); + this.buffer[this.position++] = b; + } + writeEscapedByteDescending(b) { + this.ensureAvailable(1); + this.buffer[this.position++] = ~b; + } + ensureAvailable(bytes) { + const minCapacity = bytes + this.position; + if (minCapacity <= this.buffer.length) { + return; + } + // Try doubling. + let newLength = this.buffer.length * 2; + // Still not big enough? Just allocate the right size. + if (newLength < minCapacity) { + newLength = minCapacity; + } + // Create the new buffer. + const newBuffer = new Uint8Array(newLength); + newBuffer.set(this.buffer); // copy old data + this.buffer = newBuffer; + } +} + +class AscendingIndexByteEncoder { + constructor(orderedCode) { + this.orderedCode = orderedCode; + } + writeBytes(value) { + this.orderedCode.writeBytesAscending(value); + } + writeString(value) { + this.orderedCode.writeUtf8Ascending(value); + } + writeNumber(value) { + this.orderedCode.writeNumberAscending(value); + } + writeInfinity() { + this.orderedCode.writeInfinityAscending(); + } +} +class DescendingIndexByteEncoder { + constructor(orderedCode) { + this.orderedCode = orderedCode; + } + writeBytes(value) { + this.orderedCode.writeBytesDescending(value); + } + writeString(value) { + this.orderedCode.writeUtf8Descending(value); + } + writeNumber(value) { + this.orderedCode.writeNumberDescending(value); + } + writeInfinity() { + this.orderedCode.writeInfinityDescending(); + } +} +/** + * Implements `DirectionalIndexByteEncoder` using `OrderedCodeWriter` for the + * actual encoding. + */ +class IndexByteEncoder { + constructor() { + this.orderedCode = new OrderedCodeWriter(); + this.ascending = new AscendingIndexByteEncoder(this.orderedCode); + this.descending = new DescendingIndexByteEncoder(this.orderedCode); + } + seed(encodedBytes) { + this.orderedCode.seed(encodedBytes); + } + forKind(kind) { + return kind === 0 /* IndexKind.ASCENDING */ ? this.ascending : this.descending; + } + encodedBytes() { + return this.orderedCode.encodedBytes(); + } + reset() { + this.orderedCode.reset(); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Represents an index entry saved by the SDK in persisted storage. */ +class IndexEntry { + constructor(_indexId, _documentKey, _arrayValue, _directionalValue) { + this._indexId = _indexId; + this._documentKey = _documentKey; + this._arrayValue = _arrayValue; + this._directionalValue = _directionalValue; + } + /** + * Returns an IndexEntry entry that sorts immediately after the current + * directional value. + */ + successor() { + const currentLength = this._directionalValue.length; + const newLength = currentLength === 0 || this._directionalValue[currentLength - 1] === 255 + ? currentLength + 1 + : currentLength; + const successor = new Uint8Array(newLength); + successor.set(this._directionalValue, 0); + if (newLength !== currentLength) { + successor.set([0], this._directionalValue.length); + } + else { + ++successor[successor.length - 1]; + } + return new IndexEntry(this._indexId, this._documentKey, this._arrayValue, successor); + } + // Create a representation of the Index Entry as a DbIndexEntry + dbIndexEntry(uid, orderedDocumentKey, documentKey) { + return { + indexId: this._indexId, + uid, + arrayValue: encodeKeySafeBytes(this._arrayValue), + directionalValue: encodeKeySafeBytes(this._directionalValue), + orderedDocumentKey: encodeKeySafeBytes(orderedDocumentKey), + documentKey: documentKey.path.toArray() + }; + } + // Create a representation of the Index Entry as a DbIndexEntryKey + dbIndexEntryKey(uid, orderedDocumentKey, documentKey) { + const entry = this.dbIndexEntry(uid, orderedDocumentKey, documentKey); + return [ + entry.indexId, + entry.uid, + entry.arrayValue, + entry.directionalValue, + entry.orderedDocumentKey, + entry.documentKey + ]; + } +} +function indexEntryComparator(left, right) { + let cmp = left._indexId - right._indexId; + if (cmp !== 0) { + return cmp; + } + cmp = compareByteArrays(left._arrayValue, right._arrayValue); + if (cmp !== 0) { + return cmp; + } + cmp = compareByteArrays(left._directionalValue, right._directionalValue); + if (cmp !== 0) { + return cmp; + } + return DocumentKey.comparator(left._documentKey, right._documentKey); +} +function compareByteArrays(left, right) { + for (let i = 0; i < left.length && i < right.length; ++i) { + const compare = left[i] - right[i]; + if (compare !== 0) { + return compare; + } + } + return left.length - right.length; +} +/** + * Workaround for WebKit bug: https://bugs.webkit.org/show_bug.cgi?id=292721 + * Create a key safe representation of Uint8Array values. + * If the browser is detected as Safari or WebKit, then + * the input array will be converted to "sortable byte string". + * Otherwise, the input array will be returned in its original type. + */ +function encodeKeySafeBytes(array) { + if (isSafariOrWebkit()) { + return encodeUint8ArrayToSortableString(array); + } + return array; +} +/** + * Reverts the key safe representation of Uint8Array (created by + * encodeKeySafeBytes) to a normal Uint8Array. + */ +function decodeKeySafeBytes(input) { + if (typeof input !== 'string') { + return input; + } + return decodeSortableStringToUint8Array(input); +} +/** + * Encodes a Uint8Array into a "sortable byte string". + * A "sortable byte string" sorts in the same order as the Uint8Array. + * This works because JS string comparison sorts strings based on code points. + */ +function encodeUint8ArrayToSortableString(array) { + let byteString = ''; + for (let i = 0; i < array.length; i++) { + byteString += String.fromCharCode(array[i]); + } + return byteString; +} +/** + * Decodes a "sortable byte string" back into a Uint8Array. + * A "sortable byte string" is assumed to be created where each character's + * Unicode code point directly corresponds to a single byte value (0-255). + */ +function decodeSortableStringToUint8Array(byteString) { + const uint8array = new Uint8Array(byteString.length); + for (let i = 0; i < byteString.length; i++) { + uint8array[i] = byteString.charCodeAt(i); + } + return uint8array; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A light query planner for Firestore. + * + * This class matches a `FieldIndex` against a Firestore Query `Target`. It + * determines whether a given index can be used to serve the specified target. + * + * The following table showcases some possible index configurations: + * + * Query | Index + * ----------------------------------------------------------------------------- + * where('a', '==', 'a').where('b', '==', 'b') | a ASC, b DESC + * where('a', '==', 'a').where('b', '==', 'b') | a ASC + * where('a', '==', 'a').where('b', '==', 'b') | b DESC + * where('a', '>=', 'a').orderBy('a') | a ASC + * where('a', '>=', 'a').orderBy('a', 'desc') | a DESC + * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC, b ASC + * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC + * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS, b ASCENDING + * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS + */ +class TargetIndexMatcher { + constructor(target) { + // The inequality filters of the target (if it exists). + // Note: The sort on FieldFilters is not required. Using SortedSet here just to utilize the custom + // comparator. + this.inequalityFilters = new SortedSet((lhs, rhs) => FieldPath$1.comparator(lhs.field, rhs.field)); + this.collectionId = + target.collectionGroup != null + ? target.collectionGroup + : target.path.lastSegment(); + this.orderBys = target.orderBy; + this.equalityFilters = []; + for (const filter of target.filters) { + const fieldFilter = filter; + if (fieldFilter.isInequality()) { + this.inequalityFilters = this.inequalityFilters.add(fieldFilter); + } + else { + this.equalityFilters.push(fieldFilter); + } + } + } + get hasMultipleInequality() { + return this.inequalityFilters.size > 1; + } + /** + * Returns whether the index can be used to serve the TargetIndexMatcher's + * target. + * + * An index is considered capable of serving the target when: + * - The target uses all index segments for its filters and orderBy clauses. + * The target can have additional filter and orderBy clauses, but not + * fewer. + * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also + * have a corresponding `CONTAINS` segment. + * - All directional index segments can be mapped to the target as a series of + * equality filters, a single inequality filter and a series of orderBy + * clauses. + * - The segments that represent the equality filters may appear out of order. + * - The optional segment for the inequality filter must appear after all + * equality segments. + * - The segments that represent that orderBy clause of the target must appear + * in order after all equality and inequality segments. Single orderBy + * clauses cannot be skipped, but a continuous orderBy suffix may be + * omitted. + */ + servedByIndex(index) { + hardAssert(index.collectionGroup === this.collectionId, 0xc07f); + if (this.hasMultipleInequality) { + // Only single inequality is supported for now. + // TODO(Add support for multiple inequality query): b/298441043 + return false; + } + // If there is an array element, find a matching filter. + const arraySegment = fieldIndexGetArraySegment(index); + if (arraySegment !== undefined && + !this.hasMatchingEqualityFilter(arraySegment)) { + return false; + } + const segments = fieldIndexGetDirectionalSegments(index); + let equalitySegments = new Set(); + let segmentIndex = 0; + let orderBysIndex = 0; + // Process all equalities first. Equalities can appear out of order. + for (; segmentIndex < segments.length; ++segmentIndex) { + // We attempt to greedily match all segments to equality filters. If a + // filter matches an index segment, we can mark the segment as used. + if (this.hasMatchingEqualityFilter(segments[segmentIndex])) { + equalitySegments = equalitySegments.add(segments[segmentIndex].fieldPath.canonicalString()); + } + else { + // If we cannot find a matching filter, we need to verify whether the + // remaining segments map to the target's inequality and its orderBy + // clauses. + break; + } + } + // If we already have processed all segments, all segments are used to serve + // the equality filters and we do not need to map any segments to the + // target's inequality and orderBy clauses. + if (segmentIndex === segments.length) { + return true; + } + if (this.inequalityFilters.size > 0) { + // Only a single inequality is currently supported. Get the only entry in the set. + const inequalityFilter = this.inequalityFilters.getIterator().getNext(); + // If there is an inequality filter and the field was not in one of the + // equality filters above, the next segment must match both the filter + // and the first orderBy clause. + if (!equalitySegments.has(inequalityFilter.field.canonicalString())) { + const segment = segments[segmentIndex]; + if (!this.matchesFilter(inequalityFilter, segment) || + !this.matchesOrderBy(this.orderBys[orderBysIndex++], segment)) { + return false; + } + } + ++segmentIndex; + } + // All remaining segments need to represent the prefix of the target's + // orderBy. + for (; segmentIndex < segments.length; ++segmentIndex) { + const segment = segments[segmentIndex]; + if (orderBysIndex >= this.orderBys.length || + !this.matchesOrderBy(this.orderBys[orderBysIndex++], segment)) { + return false; + } + } + return true; + } + /** + * Returns a full matched field index for this target. Currently multiple + * inequality query is not supported so function returns null. + */ + buildTargetIndex() { + if (this.hasMultipleInequality) { + return null; + } + // We want to make sure only one segment created for one field. For example, + // in case like a == 3 and a > 2, Index {a ASCENDING} will only be created + // once. + let uniqueFields = new SortedSet(FieldPath$1.comparator); + const segments = []; + for (const filter of this.equalityFilters) { + if (filter.field.isKeyField()) { + continue; + } + const isArrayOperator = filter.op === "array-contains" /* Operator.ARRAY_CONTAINS */ || + filter.op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */; + if (isArrayOperator) { + segments.push(new IndexSegment(filter.field, 2 /* IndexKind.CONTAINS */)); + } + else { + if (uniqueFields.has(filter.field)) { + continue; + } + uniqueFields = uniqueFields.add(filter.field); + segments.push(new IndexSegment(filter.field, 0 /* IndexKind.ASCENDING */)); + } + } + // Note: We do not explicitly check `this.inequalityFilter` but rather rely + // on the target defining an appropriate "order by" to ensure that the + // required index segment is added. The query engine would reject a query + // with an inequality filter that lacks the required order-by clause. + for (const orderBy of this.orderBys) { + // Stop adding more segments if we see a order-by on key. Typically this + // is the default implicit order-by which is covered in the index_entry + // table as a separate column. If it is not the default order-by, the + // generated index will be missing some segments optimized for order-bys, + // which is probably fine. + if (orderBy.field.isKeyField()) { + continue; + } + if (uniqueFields.has(orderBy.field)) { + continue; + } + uniqueFields = uniqueFields.add(orderBy.field); + segments.push(new IndexSegment(orderBy.field, orderBy.dir === "asc" /* Direction.ASCENDING */ + ? 0 /* IndexKind.ASCENDING */ + : 1 /* IndexKind.DESCENDING */)); + } + return new FieldIndex(FieldIndex.UNKNOWN_ID, this.collectionId, segments, IndexState.empty()); + } + hasMatchingEqualityFilter(segment) { + for (const filter of this.equalityFilters) { + if (this.matchesFilter(filter, segment)) { + return true; + } + } + return false; + } + matchesFilter(filter, segment) { + if (filter === undefined || !filter.field.isEqual(segment.fieldPath)) { + return false; + } + const isArrayOperator = filter.op === "array-contains" /* Operator.ARRAY_CONTAINS */ || + filter.op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */; + return (segment.kind === 2 /* IndexKind.CONTAINS */) === isArrayOperator; + } + matchesOrderBy(orderBy, segment) { + if (!orderBy.field.isEqual(segment.fieldPath)) { + return false; + } + return ((segment.kind === 0 /* IndexKind.ASCENDING */ && + orderBy.dir === "asc" /* Direction.ASCENDING */) || + (segment.kind === 1 /* IndexKind.DESCENDING */ && + orderBy.dir === "desc" /* Direction.DESCENDING */)); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provides utility functions that help with boolean logic transformations needed for handling + * complex filters used in queries. + */ +/** + * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in + * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given + * input into a disjunction of equality filters and returns the expanded filter. + */ +function computeInExpansion(filter) { + hardAssert(filter instanceof FieldFilter || filter instanceof CompositeFilter, 0x4e2c); + if (filter instanceof FieldFilter) { + if (filter instanceof InFilter) { + const expandedFilters = filter.value.arrayValue?.values?.map(value => FieldFilter.create(filter.field, "==" /* Operator.EQUAL */, value)) || []; + return CompositeFilter.create(expandedFilters, "or" /* CompositeOperator.OR */); + } + else { + // We have reached other kinds of field filters. + return filter; + } + } + // We have a composite filter. + const expandedFilters = filter.filters.map(subfilter => computeInExpansion(subfilter)); + return CompositeFilter.create(expandedFilters, filter.op); +} +/** + * Given a composite filter, returns the list of terms in its disjunctive normal form. + * + *

Each element in the return value is one term of the resulting DNF. For instance: For the + * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list + * with two elements: a composite filter that performs (A && C), and a composite filter that + * performs (B && C). + * + * @param filter the composite filter to calculate DNF transform for. + * @return the terms in the DNF transform. + */ +function getDnfTerms(filter) { + if (filter.getFilters().length === 0) { + return []; + } + const result = computeDistributedNormalForm(computeInExpansion(filter)); + hardAssert(isDisjunctiveNormalForm(result), 0x1cdf); + if (isSingleFieldFilter(result) || isFlatConjunction(result)) { + return [result]; + } + return result.getFilters(); +} +/** Returns true if the given filter is a single field filter. e.g. (a == 10). */ +function isSingleFieldFilter(filter) { + return filter instanceof FieldFilter; +} +/** + * Returns true if the given filter is the conjunction of one or more field filters. e.g. (a == 10 + * && b == 20) + */ +function isFlatConjunction(filter) { + return (filter instanceof CompositeFilter && + compositeFilterIsFlatConjunction(filter)); +} +/** + * Returns whether or not the given filter is in disjunctive normal form (DNF). + * + *

In boolean logic, a disjunctive normal form (DNF) is a canonical normal form of a logical + * formula consisting of a disjunction of conjunctions; it can also be described as an OR of ANDs. + * + *

For more info, visit: https://en.wikipedia.org/wiki/Disjunctive_normal_form + */ +function isDisjunctiveNormalForm(filter) { + return (isSingleFieldFilter(filter) || + isFlatConjunction(filter) || + isDisjunctionOfFieldFiltersAndFlatConjunctions(filter)); +} +/** + * Returns true if the given filter is the disjunction of one or more "flat conjunctions" and + * field filters. e.g. (a == 10) || (b==20 && c==30) + */ +function isDisjunctionOfFieldFiltersAndFlatConjunctions(filter) { + if (filter instanceof CompositeFilter) { + if (compositeFilterIsDisjunction(filter)) { + for (const subFilter of filter.getFilters()) { + if (!isSingleFieldFilter(subFilter) && !isFlatConjunction(subFilter)) { + return false; + } + } + return true; + } + } + return false; +} +function computeDistributedNormalForm(filter) { + hardAssert(filter instanceof FieldFilter || filter instanceof CompositeFilter, 0x84e2); + if (filter instanceof FieldFilter) { + return filter; + } + if (filter.filters.length === 1) { + return computeDistributedNormalForm(filter.filters[0]); + } + // Compute DNF for each of the subfilters first + const result = filter.filters.map(subfilter => computeDistributedNormalForm(subfilter)); + let newFilter = CompositeFilter.create(result, filter.op); + newFilter = applyAssociation(newFilter); + if (isDisjunctiveNormalForm(newFilter)) { + return newFilter; + } + hardAssert(newFilter instanceof CompositeFilter, 0xfbf2); + hardAssert(compositeFilterIsConjunction(newFilter), 0x9d3b); + hardAssert(newFilter.filters.length > 1, 0xe247); + return newFilter.filters.reduce((runningResult, filter) => applyDistribution(runningResult, filter)); +} +function applyDistribution(lhs, rhs) { + hardAssert(lhs instanceof FieldFilter || lhs instanceof CompositeFilter, 0x95f4); + hardAssert(rhs instanceof FieldFilter || rhs instanceof CompositeFilter, 0x6381); + let result; + if (lhs instanceof FieldFilter) { + if (rhs instanceof FieldFilter) { + // FieldFilter FieldFilter + result = applyDistributionFieldFilters(lhs, rhs); + } + else { + // FieldFilter CompositeFilter + result = applyDistributionFieldAndCompositeFilters(lhs, rhs); + } + } + else { + if (rhs instanceof FieldFilter) { + // CompositeFilter FieldFilter + result = applyDistributionFieldAndCompositeFilters(rhs, lhs); + } + else { + // CompositeFilter CompositeFilter + result = applyDistributionCompositeFilters(lhs, rhs); + } + } + return applyAssociation(result); +} +function applyDistributionFieldFilters(lhs, rhs) { + // Conjunction distribution for two field filters is the conjunction of them. + return CompositeFilter.create([lhs, rhs], "and" /* CompositeOperator.AND */); +} +function applyDistributionCompositeFilters(lhs, rhs) { + hardAssert(lhs.filters.length > 0 && rhs.filters.length > 0, 0xbb85); + // There are four cases: + // (A & B) & (C & D) --> (A & B & C & D) + // (A & B) & (C | D) --> (A & B & C) | (A & B & D) + // (A | B) & (C & D) --> (C & D & A) | (C & D & B) + // (A | B) & (C | D) --> (A & C) | (A & D) | (B & C) | (B & D) + // Case 1 is a merge. + if (compositeFilterIsConjunction(lhs) && compositeFilterIsConjunction(rhs)) { + return compositeFilterWithAddedFilters(lhs, rhs.getFilters()); + } + // Case 2,3,4 all have at least one side (lhs or rhs) that is a disjunction. In all three cases + // we should take each element of the disjunction and distribute it over the other side, and + // return the disjunction of the distribution results. + const disjunctionSide = compositeFilterIsDisjunction(lhs) ? lhs : rhs; + const otherSide = compositeFilterIsDisjunction(lhs) ? rhs : lhs; + const results = disjunctionSide.filters.map(subfilter => applyDistribution(subfilter, otherSide)); + return CompositeFilter.create(results, "or" /* CompositeOperator.OR */); +} +function applyDistributionFieldAndCompositeFilters(fieldFilter, compositeFilter) { + // There are two cases: + // A & (B & C) --> (A & B & C) + // A & (B | C) --> (A & B) | (A & C) + if (compositeFilterIsConjunction(compositeFilter)) { + // Case 1 + return compositeFilterWithAddedFilters(compositeFilter, fieldFilter.getFilters()); + } + else { + // Case 2 + const newFilters = compositeFilter.filters.map(subfilter => applyDistribution(fieldFilter, subfilter)); + return CompositeFilter.create(newFilters, "or" /* CompositeOperator.OR */); + } +} +/** + * Applies the associativity property to the given filter and returns the resulting filter. + * + *

    + *
  • A | (B | C) == (A | B) | C == (A | B | C) + *
  • A & (B & C) == (A & B) & C == (A & B & C) + *
+ * + *

For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic + */ +function applyAssociation(filter) { + hardAssert(filter instanceof FieldFilter || filter instanceof CompositeFilter, 0x2e4a); + if (filter instanceof FieldFilter) { + return filter; + } + const filters = filter.getFilters(); + // If the composite filter only contains 1 filter, apply associativity to it. + if (filters.length === 1) { + return applyAssociation(filters[0]); + } + // Associativity applied to a flat composite filter results is itself. + if (compositeFilterIsFlat(filter)) { + return filter; + } + // First apply associativity to all subfilters. This will in turn recursively apply + // associativity to all nested composite filters and field filters. + const updatedFilters = filters.map(subfilter => applyAssociation(subfilter)); + // For composite subfilters that perform the same kind of logical operation as `compositeFilter` + // take out their filters and add them to `compositeFilter`. For example: + // compositeFilter = (A | (B | C | D)) + // compositeSubfilter = (B | C | D) + // Result: (A | B | C | D) + // Note that the `compositeSubfilter` has been eliminated, and its filters (B, C, D) have been + // added to the top-level "compositeFilter". + const newSubfilters = []; + updatedFilters.forEach(subfilter => { + if (subfilter instanceof FieldFilter) { + newSubfilters.push(subfilter); + } + else if (subfilter instanceof CompositeFilter) { + if (subfilter.op === filter.op) { + // compositeFilter: (A | (B | C)) + // compositeSubfilter: (B | C) + // Result: (A | B | C) + newSubfilters.push(...subfilter.filters); + } + else { + // compositeFilter: (A | (B & C)) + // compositeSubfilter: (B & C) + // Result: (A | (B & C)) + newSubfilters.push(subfilter); + } + } + }); + if (newSubfilters.length === 1) { + return newSubfilters[0]; + } + return CompositeFilter.create(newSubfilters, filter.op); +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An in-memory implementation of IndexManager. + */ +class MemoryIndexManager { + constructor() { + this.collectionParentIndex = new MemoryCollectionParentIndex(); + } + addToCollectionParentIndex(transaction, collectionPath) { + this.collectionParentIndex.add(collectionPath); + return PersistencePromise.resolve(); + } + getCollectionParents(transaction, collectionId) { + return PersistencePromise.resolve(this.collectionParentIndex.getEntries(collectionId)); + } + addFieldIndex(transaction, index) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(); + } + deleteFieldIndex(transaction, index) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(); + } + deleteAllFieldIndexes(transaction) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(); + } + createTargetIndexes(transaction, target) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(); + } + getDocumentsMatchingTarget(transaction, target) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(null); + } + getIndexType(transaction, target) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(0 /* IndexType.NONE */); + } + getFieldIndexes(transaction, collectionGroup) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve([]); + } + getNextCollectionGroupToUpdate(transaction) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(null); + } + getMinOffset(transaction, target) { + return PersistencePromise.resolve(IndexOffset.min()); + } + getMinOffsetFromCollectionGroup(transaction, collectionGroup) { + return PersistencePromise.resolve(IndexOffset.min()); + } + updateCollectionGroup(transaction, collectionGroup, offset) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(); + } + updateIndexEntries(transaction, documents) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(); + } +} +/** + * Internal implementation of the collection-parent index exposed by MemoryIndexManager. + * Also used for in-memory caching by IndexedDbIndexManager and initial index population + * in indexeddb_schema.ts + */ +class MemoryCollectionParentIndex { + constructor() { + this.index = {}; + } + // Returns false if the entry already existed. + add(collectionPath) { + const collectionId = collectionPath.lastSegment(); + const parentPath = collectionPath.popLast(); + const existingParents = this.index[collectionId] || + new SortedSet(ResourcePath.comparator); + const added = !existingParents.has(parentPath); + this.index[collectionId] = existingParents.add(parentPath); + return added; + } + has(collectionPath) { + const collectionId = collectionPath.lastSegment(); + const parentPath = collectionPath.popLast(); + const existingParents = this.index[collectionId]; + return existingParents && existingParents.has(parentPath); + } + getEntries(collectionId) { + const parentPaths = this.index[collectionId] || + new SortedSet(ResourcePath.comparator); + return parentPaths.toArray(); + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$f = 'IndexedDbIndexManager'; +const EMPTY_VALUE = new Uint8Array(0); +/** + * A persisted implementation of IndexManager. + * + * PORTING NOTE: Unlike iOS and Android, the Web SDK does not memoize index + * data as it supports multi-tab access. + */ +class IndexedDbIndexManager { + constructor(user, databaseId) { + this.databaseId = databaseId; + /** + * An in-memory copy of the index entries we've already written since the SDK + * launched. Used to avoid re-writing the same entry repeatedly. + * + * This is *NOT* a complete cache of what's in persistence and so can never be + * used to satisfy reads. + */ + this.collectionParentsCache = new MemoryCollectionParentIndex(); + /** + * Maps from a target to its equivalent list of sub-targets. Each sub-target + * contains only one term from the target's disjunctive normal form (DNF). + */ + this.targetToDnfSubTargets = new ObjectMap(t => canonifyTarget(t), (l, r) => targetEquals(l, r)); + this.uid = user.uid || ''; + } + /** + * Adds a new entry to the collection parent index. + * + * Repeated calls for the same collectionPath should be avoided within a + * transaction as IndexedDbIndexManager only caches writes once a transaction + * has been committed. + */ + addToCollectionParentIndex(transaction, collectionPath) { + if (!this.collectionParentsCache.has(collectionPath)) { + const collectionId = collectionPath.lastSegment(); + const parentPath = collectionPath.popLast(); + transaction.addOnCommittedListener(() => { + // Add the collection to the in memory cache only if the transaction was + // successfully committed. + this.collectionParentsCache.add(collectionPath); + }); + const collectionParent = { + collectionId, + parent: encodeResourcePath(parentPath) + }; + return collectionParentsStore(transaction).put(collectionParent); + } + return PersistencePromise.resolve(); + } + getCollectionParents(transaction, collectionId) { + const parentPaths = []; + const range = IDBKeyRange.bound([collectionId, ''], [immediateSuccessor(collectionId), ''], + /*lowerOpen=*/ false, + /*upperOpen=*/ true); + return collectionParentsStore(transaction) + .loadAll(range) + .next(entries => { + for (const entry of entries) { + // This collectionId guard shouldn't be necessary (and isn't as long + // as we're running in a real browser), but there's a bug in + // indexeddbshim that breaks our range in our tests running in node: + // https://github.com/axemclion/IndexedDBShim/issues/334 + if (entry.collectionId !== collectionId) { + break; + } + parentPaths.push(decodeResourcePath(entry.parent)); + } + return parentPaths; + }); + } + addFieldIndex(transaction, index) { + // TODO(indexing): Verify that the auto-incrementing index ID works in + // Safari & Firefox. + const indexes = indexConfigurationStore(transaction); + const dbIndex = toDbIndexConfiguration(index); + delete dbIndex.indexId; // `indexId` is auto-populated by IndexedDb + const result = indexes.add(dbIndex); + if (index.indexState) { + const states = indexStateStore(transaction); + return result.next(indexId => { + states.put(toDbIndexState(indexId, this.uid, index.indexState.sequenceNumber, index.indexState.offset)); + }); + } + else { + return result.next(); + } + } + deleteFieldIndex(transaction, index) { + const indexes = indexConfigurationStore(transaction); + const states = indexStateStore(transaction); + const entries = indexEntriesStore(transaction); + return indexes + .delete(index.indexId) + .next(() => states.delete(IDBKeyRange.bound([index.indexId], [index.indexId + 1], + /*lowerOpen=*/ false, + /*upperOpen=*/ true))) + .next(() => entries.delete(IDBKeyRange.bound([index.indexId], [index.indexId + 1], + /*lowerOpen=*/ false, + /*upperOpen=*/ true))); + } + deleteAllFieldIndexes(transaction) { + const indexes = indexConfigurationStore(transaction); + const entries = indexEntriesStore(transaction); + const states = indexStateStore(transaction); + return indexes + .deleteAll() + .next(() => entries.deleteAll()) + .next(() => states.deleteAll()); + } + createTargetIndexes(transaction, target) { + return PersistencePromise.forEach(this.getSubTargets(target), (subTarget) => { + return this.getIndexType(transaction, subTarget).next(type => { + if (type === 0 /* IndexType.NONE */ || type === 1 /* IndexType.PARTIAL */) { + const targetIndexMatcher = new TargetIndexMatcher(subTarget); + const fieldIndex = targetIndexMatcher.buildTargetIndex(); + if (fieldIndex != null) { + return this.addFieldIndex(transaction, fieldIndex); + } + } + }); + }); + } + getDocumentsMatchingTarget(transaction, target) { + const indexEntries = indexEntriesStore(transaction); + let canServeTarget = true; + const indexes = new Map(); + return PersistencePromise.forEach(this.getSubTargets(target), (subTarget) => { + return this.getFieldIndex(transaction, subTarget).next(index => { + canServeTarget && (canServeTarget = !!index); + indexes.set(subTarget, index); + }); + }).next(() => { + if (!canServeTarget) { + return PersistencePromise.resolve(null); + } + else { + let existingKeys = documentKeySet(); + const result = []; + return PersistencePromise.forEach(indexes, (index, subTarget) => { + logDebug(LOG_TAG$f, `Using index ${fieldIndexToString(index)} to execute ${canonifyTarget(target)}`); + const arrayValues = targetGetArrayValues(subTarget, index); + const notInValues = targetGetNotInValues(subTarget, index); + const lowerBound = targetGetLowerBound(subTarget, index); + const upperBound = targetGetUpperBound(subTarget, index); + const lowerBoundEncoded = this.encodeBound(index, subTarget, lowerBound); + const upperBoundEncoded = this.encodeBound(index, subTarget, upperBound); + const notInEncoded = this.encodeValues(index, subTarget, notInValues); + const indexRanges = this.generateIndexRanges(index.indexId, arrayValues, lowerBoundEncoded, lowerBound.inclusive, upperBoundEncoded, upperBound.inclusive, notInEncoded); + return PersistencePromise.forEach(indexRanges, (indexRange) => { + return indexEntries + .loadFirst(indexRange, target.limit) + .next(entries => { + entries.forEach(entry => { + const documentKey = DocumentKey.fromSegments(entry.documentKey); + if (!existingKeys.has(documentKey)) { + existingKeys = existingKeys.add(documentKey); + result.push(documentKey); + } + }); + }); + }); + }).next(() => result); + } + }); + } + getSubTargets(target) { + let subTargets = this.targetToDnfSubTargets.get(target); + if (subTargets) { + return subTargets; + } + if (target.filters.length === 0) { + subTargets = [target]; + } + else { + // There is an implicit AND operation between all the filters stored in the target + const dnf = getDnfTerms(CompositeFilter.create(target.filters, "and" /* CompositeOperator.AND */)); + subTargets = dnf.map(term => newTarget(target.path, target.collectionGroup, target.orderBy, term.getFilters(), target.limit, target.startAt, target.endAt)); + } + this.targetToDnfSubTargets.set(target, subTargets); + return subTargets; + } + /** + * Constructs a key range query on `DbIndexEntryStore` that unions all + * bounds. + */ + generateIndexRanges(indexId, arrayValues, lowerBounds, lowerBoundInclusive, upperBounds, upperBoundInclusive, notInValues) { + // The number of total index scans we union together. This is similar to a + // distributed normal form, but adapted for array values. We create a single + // index range per value in an ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filter + // combined with the values from the query bounds. + const totalScans = (arrayValues != null ? arrayValues.length : 1) * + Math.max(lowerBounds.length, upperBounds.length); + const scansPerArrayElement = totalScans / (arrayValues != null ? arrayValues.length : 1); + const indexRanges = []; + for (let i = 0; i < totalScans; ++i) { + const arrayValue = arrayValues + ? this.encodeSingleElement(arrayValues[i / scansPerArrayElement]) + : EMPTY_VALUE; + const lowerBound = this.generateLowerBound(indexId, arrayValue, lowerBounds[i % scansPerArrayElement], lowerBoundInclusive); + const upperBound = this.generateUpperBound(indexId, arrayValue, upperBounds[i % scansPerArrayElement], upperBoundInclusive); + const notInBound = notInValues.map(notIn => this.generateLowerBound(indexId, arrayValue, notIn, + /* inclusive= */ true)); + indexRanges.push(...this.createRange(lowerBound, upperBound, notInBound)); + } + return indexRanges; + } + /** Generates the lower bound for `arrayValue` and `directionalValue`. */ + generateLowerBound(indexId, arrayValue, directionalValue, inclusive) { + const entry = new IndexEntry(indexId, DocumentKey.empty(), arrayValue, directionalValue); + return inclusive ? entry : entry.successor(); + } + /** Generates the upper bound for `arrayValue` and `directionalValue`. */ + generateUpperBound(indexId, arrayValue, directionalValue, inclusive) { + const entry = new IndexEntry(indexId, DocumentKey.empty(), arrayValue, directionalValue); + return inclusive ? entry.successor() : entry; + } + getFieldIndex(transaction, target) { + const targetIndexMatcher = new TargetIndexMatcher(target); + const collectionGroup = target.collectionGroup != null + ? target.collectionGroup + : target.path.lastSegment(); + return this.getFieldIndexes(transaction, collectionGroup).next(indexes => { + // Return the index with the most number of segments. + let index = null; + for (const candidate of indexes) { + const matches = targetIndexMatcher.servedByIndex(candidate); + if (matches && + (!index || candidate.fields.length > index.fields.length)) { + index = candidate; + } + } + return index; + }); + } + getIndexType(transaction, target) { + let indexType = 2 /* IndexType.FULL */; + const subTargets = this.getSubTargets(target); + return PersistencePromise.forEach(subTargets, (target) => { + return this.getFieldIndex(transaction, target).next(index => { + if (!index) { + indexType = 0 /* IndexType.NONE */; + } + else if (indexType !== 0 /* IndexType.NONE */ && + index.fields.length < targetGetSegmentCount(target)) { + indexType = 1 /* IndexType.PARTIAL */; + } + }); + }).next(() => { + // OR queries have more than one sub-target (one sub-target per DNF term). We currently consider + // OR queries that have a `limit` to have a partial index. For such queries we perform sorting + // and apply the limit in memory as a post-processing step. + if (targetHasLimit(target) && + subTargets.length > 1 && + indexType === 2 /* IndexType.FULL */) { + return 1 /* IndexType.PARTIAL */; + } + return indexType; + }); + } + /** + * Returns the byte encoded form of the directional values in the field index. + * Returns `null` if the document does not have all fields specified in the + * index. + */ + encodeDirectionalElements(fieldIndex, document) { + const encoder = new IndexByteEncoder(); + for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) { + const field = document.data.field(segment.fieldPath); + if (field == null) { + return null; + } + const directionalEncoder = encoder.forKind(segment.kind); + FirestoreIndexValueWriter.INSTANCE.writeIndexValue(field, directionalEncoder); + } + return encoder.encodedBytes(); + } + /** Encodes a single value to the ascending index format. */ + encodeSingleElement(value) { + const encoder = new IndexByteEncoder(); + FirestoreIndexValueWriter.INSTANCE.writeIndexValue(value, encoder.forKind(0 /* IndexKind.ASCENDING */)); + return encoder.encodedBytes(); + } + /** + * Returns an encoded form of the document key that sorts based on the key + * ordering of the field index. + */ + encodeDirectionalKey(fieldIndex, documentKey) { + const encoder = new IndexByteEncoder(); + FirestoreIndexValueWriter.INSTANCE.writeIndexValue(refValue(this.databaseId, documentKey), encoder.forKind(fieldIndexGetKeyOrder(fieldIndex))); + return encoder.encodedBytes(); + } + /** + * Encodes the given field values according to the specification in `target`. + * For IN queries, a list of possible values is returned. + */ + encodeValues(fieldIndex, target, values) { + if (values === null) { + return []; + } + let encoders = []; + encoders.push(new IndexByteEncoder()); + let valueIdx = 0; + for (const segment of fieldIndexGetDirectionalSegments(fieldIndex)) { + const value = values[valueIdx++]; + for (const encoder of encoders) { + if (this.isInFilter(target, segment.fieldPath) && isArray(value)) { + encoders = this.expandIndexValues(encoders, segment, value); + } + else { + const directionalEncoder = encoder.forKind(segment.kind); + FirestoreIndexValueWriter.INSTANCE.writeIndexValue(value, directionalEncoder); + } + } + } + return this.getEncodedBytes(encoders); + } + /** + * Encodes the given bounds according to the specification in `target`. For IN + * queries, a list of possible values is returned. + */ + encodeBound(fieldIndex, target, bound) { + return this.encodeValues(fieldIndex, target, bound.position); + } + /** Returns the byte representation for the provided encoders. */ + getEncodedBytes(encoders) { + const result = []; + for (let i = 0; i < encoders.length; ++i) { + result[i] = encoders[i].encodedBytes(); + } + return result; + } + /** + * Creates a separate encoder for each element of an array. + * + * The method appends each value to all existing encoders (e.g. filter("a", + * "==", "a1").filter("b", "in", ["b1", "b2"]) becomes ["a1,b1", "a1,b2"]). A + * list of new encoders is returned. + */ + expandIndexValues(encoders, segment, value) { + const prefixes = [...encoders]; + const results = []; + for (const arrayElement of value.arrayValue.values || []) { + for (const prefix of prefixes) { + const clonedEncoder = new IndexByteEncoder(); + clonedEncoder.seed(prefix.encodedBytes()); + FirestoreIndexValueWriter.INSTANCE.writeIndexValue(arrayElement, clonedEncoder.forKind(segment.kind)); + results.push(clonedEncoder); + } + } + return results; + } + isInFilter(target, fieldPath) { + return !!target.filters.find(f => f instanceof FieldFilter && + f.field.isEqual(fieldPath) && + (f.op === "in" /* Operator.IN */ || f.op === "not-in" /* Operator.NOT_IN */)); + } + getFieldIndexes(transaction, collectionGroup) { + const indexes = indexConfigurationStore(transaction); + const states = indexStateStore(transaction); + return (collectionGroup + ? indexes.loadAll(DbIndexConfigurationCollectionGroupIndex, IDBKeyRange.bound(collectionGroup, collectionGroup)) + : indexes.loadAll()).next(indexConfigs => { + const result = []; + return PersistencePromise.forEach(indexConfigs, (indexConfig) => { + return states + .get([indexConfig.indexId, this.uid]) + .next(indexState => { + result.push(fromDbIndexConfiguration(indexConfig, indexState)); + }); + }).next(() => result); + }); + } + getNextCollectionGroupToUpdate(transaction) { + return this.getFieldIndexes(transaction).next(indexes => { + if (indexes.length === 0) { + return null; + } + indexes.sort((l, r) => { + const cmp = l.indexState.sequenceNumber - r.indexState.sequenceNumber; + return cmp !== 0 + ? cmp + : primitiveComparator(l.collectionGroup, r.collectionGroup); + }); + return indexes[0].collectionGroup; + }); + } + updateCollectionGroup(transaction, collectionGroup, offset) { + const indexes = indexConfigurationStore(transaction); + const states = indexStateStore(transaction); + return this.getNextSequenceNumber(transaction).next(nextSequenceNumber => indexes + .loadAll(DbIndexConfigurationCollectionGroupIndex, IDBKeyRange.bound(collectionGroup, collectionGroup)) + .next(configs => PersistencePromise.forEach(configs, (config) => states.put(toDbIndexState(config.indexId, this.uid, nextSequenceNumber, offset))))); + } + updateIndexEntries(transaction, documents) { + // Porting Note: `getFieldIndexes()` on Web does not cache index lookups as + // it could be used across different IndexedDB transactions. As any cached + // data might be invalidated by other multi-tab clients, we can only trust + // data within a single IndexedDB transaction. We therefore add a cache + // here. + const memoizedIndexes = new Map(); + return PersistencePromise.forEach(documents, (key, doc) => { + const memoizedCollectionIndexes = memoizedIndexes.get(key.collectionGroup); + const fieldIndexes = memoizedCollectionIndexes + ? PersistencePromise.resolve(memoizedCollectionIndexes) + : this.getFieldIndexes(transaction, key.collectionGroup); + return fieldIndexes.next(fieldIndexes => { + memoizedIndexes.set(key.collectionGroup, fieldIndexes); + return PersistencePromise.forEach(fieldIndexes, (fieldIndex) => { + return this.getExistingIndexEntries(transaction, key, fieldIndex).next(existingEntries => { + const newEntries = this.computeIndexEntries(doc, fieldIndex); + if (!existingEntries.isEqual(newEntries)) { + return this.updateEntries(transaction, doc, fieldIndex, existingEntries, newEntries); + } + return PersistencePromise.resolve(); + }); + }); + }); + }); + } + addIndexEntry(transaction, document, fieldIndex, indexEntry) { + const indexEntries = indexEntriesStore(transaction); + return indexEntries.put(indexEntry.dbIndexEntry(this.uid, this.encodeDirectionalKey(fieldIndex, document.key), document.key)); + } + deleteIndexEntry(transaction, document, fieldIndex, indexEntry) { + const indexEntries = indexEntriesStore(transaction); + return indexEntries.delete(indexEntry.dbIndexEntryKey(this.uid, this.encodeDirectionalKey(fieldIndex, document.key), document.key)); + } + getExistingIndexEntries(transaction, documentKey, fieldIndex) { + const indexEntries = indexEntriesStore(transaction); + let results = new SortedSet(indexEntryComparator); + return indexEntries + .iterate({ + index: DbIndexEntryDocumentKeyIndex, + range: IDBKeyRange.only([ + fieldIndex.indexId, + this.uid, + encodeKeySafeBytes(this.encodeDirectionalKey(fieldIndex, documentKey)) + ]) + }, (_, entry) => { + results = results.add(new IndexEntry(fieldIndex.indexId, documentKey, decodeKeySafeBytes(entry.arrayValue), decodeKeySafeBytes(entry.directionalValue))); + }) + .next(() => results); + } + /** Creates the index entries for the given document. */ + computeIndexEntries(document, fieldIndex) { + let results = new SortedSet(indexEntryComparator); + const directionalValue = this.encodeDirectionalElements(fieldIndex, document); + if (directionalValue == null) { + return results; + } + const arraySegment = fieldIndexGetArraySegment(fieldIndex); + if (arraySegment != null) { + const value = document.data.field(arraySegment.fieldPath); + if (isArray(value)) { + for (const arrayValue of value.arrayValue.values || []) { + results = results.add(new IndexEntry(fieldIndex.indexId, document.key, this.encodeSingleElement(arrayValue), directionalValue)); + } + } + } + else { + results = results.add(new IndexEntry(fieldIndex.indexId, document.key, EMPTY_VALUE, directionalValue)); + } + return results; + } + /** + * Updates the index entries for the provided document by deleting entries + * that are no longer referenced in `newEntries` and adding all newly added + * entries. + */ + updateEntries(transaction, document, fieldIndex, existingEntries, newEntries) { + logDebug(LOG_TAG$f, "Updating index entries for document '%s'", document.key); + const promises = []; + diffSortedSets(existingEntries, newEntries, indexEntryComparator, + /* onAdd= */ entry => { + promises.push(this.addIndexEntry(transaction, document, fieldIndex, entry)); + }, + /* onRemove= */ entry => { + promises.push(this.deleteIndexEntry(transaction, document, fieldIndex, entry)); + }); + return PersistencePromise.waitFor(promises); + } + getNextSequenceNumber(transaction) { + let nextSequenceNumber = 1; + const states = indexStateStore(transaction); + return states + .iterate({ + index: DbIndexStateSequenceNumberIndex, + reverse: true, + range: IDBKeyRange.upperBound([this.uid, Number.MAX_SAFE_INTEGER]) + }, (_, state, controller) => { + controller.done(); + nextSequenceNumber = state.sequenceNumber + 1; + }) + .next(() => nextSequenceNumber); + } + /** + * Returns a new set of IDB ranges that splits the existing range and excludes + * any values that match the `notInValue` from these ranges. As an example, + * '[foo > 2 && foo != 3]` becomes `[foo > 2 && < 3, foo > 3]`. + */ + createRange(lower, upper, notInValues) { + // The notIn values need to be sorted and unique so that we can return a + // sorted set of non-overlapping ranges. + notInValues = notInValues + .sort((l, r) => indexEntryComparator(l, r)) + .filter((el, i, values) => !i || indexEntryComparator(el, values[i - 1]) !== 0); + const bounds = []; + bounds.push(lower); + for (const notInValue of notInValues) { + const cmpToLower = indexEntryComparator(notInValue, lower); + const cmpToUpper = indexEntryComparator(notInValue, upper); + if (cmpToLower === 0) { + // `notInValue` is the lower bound. We therefore need to raise the bound + // to the next value. + bounds[0] = lower.successor(); + } + else if (cmpToLower > 0 && cmpToUpper < 0) { + // `notInValue` is in the middle of the range + bounds.push(notInValue); + bounds.push(notInValue.successor()); + } + else if (cmpToUpper > 0) { + // `notInValue` (and all following values) are out of the range + break; + } + } + bounds.push(upper); + const ranges = []; + for (let i = 0; i < bounds.length; i += 2) { + // If we encounter two bounds that will create an unmatchable key range, + // then we return an empty set of key ranges. + if (this.isRangeMatchable(bounds[i], bounds[i + 1])) { + return []; + } + const lowerBound = bounds[i].dbIndexEntryKey(this.uid, EMPTY_VALUE, DocumentKey.empty()); + const upperBound = bounds[i + 1].dbIndexEntryKey(this.uid, EMPTY_VALUE, DocumentKey.empty()); + ranges.push(IDBKeyRange.bound(lowerBound, upperBound)); + } + return ranges; + } + isRangeMatchable(lowerBound, upperBound) { + // If lower bound is greater than the upper bound, then the key + // range can never be matched. + return indexEntryComparator(lowerBound, upperBound) > 0; + } + getMinOffsetFromCollectionGroup(transaction, collectionGroup) { + return this.getFieldIndexes(transaction, collectionGroup).next(getMinOffsetFromFieldIndexes); + } + getMinOffset(transaction, target) { + return PersistencePromise.mapArray(this.getSubTargets(target), (subTarget) => this.getFieldIndex(transaction, subTarget).next(index => index ? index : fail(0xad8a))).next(getMinOffsetFromFieldIndexes); + } +} +/** + * Helper to get a typed SimpleDbStore for the collectionParents + * document store. + */ +function collectionParentsStore(txn) { + return getStore(txn, DbCollectionParentStore); +} +/** + * Helper to get a typed SimpleDbStore for the index entry object store. + */ +function indexEntriesStore(txn) { + return getStore(txn, DbIndexEntryStore); +} +/** + * Helper to get a typed SimpleDbStore for the index configuration object store. + */ +function indexConfigurationStore(txn) { + return getStore(txn, DbIndexConfigurationStore); +} +/** + * Helper to get a typed SimpleDbStore for the index state object store. + */ +function indexStateStore(txn) { + return getStore(txn, DbIndexStateStore); +} +function getMinOffsetFromFieldIndexes(fieldIndexes) { + hardAssert(fieldIndexes.length !== 0, 0x7099); + let minOffset = fieldIndexes[0].indexState.offset; + let maxBatchId = minOffset.largestBatchId; + for (let i = 1; i < fieldIndexes.length; i++) { + const newOffset = fieldIndexes[i].indexState.offset; + if (indexOffsetComparator(newOffset, minOffset) < 0) { + minOffset = newOffset; + } + if (maxBatchId < newOffset.largestBatchId) { + maxBatchId = newOffset.largestBatchId; + } + } + return new IndexOffset(minOffset.readTime, minOffset.documentKey, maxBatchId); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Delete a mutation batch and the associated document mutations. + * @returns A PersistencePromise of the document mutations that were removed. + */ +function removeMutationBatch(txn, userId, batch) { + const mutationStore = txn.store(DbMutationBatchStore); + const indexTxn = txn.store(DbDocumentMutationStore); + const promises = []; + const range = IDBKeyRange.only(batch.batchId); + let numDeleted = 0; + const removePromise = mutationStore.iterate({ range }, (key, value, control) => { + numDeleted++; + return control.delete(); + }); + promises.push(removePromise.next(() => { + hardAssert(numDeleted === 1, 0xb7de, { batchId: batch.batchId }); + })); + const removedDocuments = []; + for (const mutation of batch.mutations) { + const indexKey = newDbDocumentMutationKey(userId, mutation.key.path, batch.batchId); + promises.push(indexTxn.delete(indexKey)); + removedDocuments.push(mutation.key); + } + return PersistencePromise.waitFor(promises).next(() => removedDocuments); +} +/** + * Returns an approximate size for the given document. + */ +function dbDocumentSize(doc) { + if (!doc) { + return 0; + } + let value; + if (doc.document) { + value = doc.document; + } + else if (doc.unknownDocument) { + value = doc.unknownDocument; + } + else if (doc.noDocument) { + value = doc.noDocument; + } + else { + throw fail(0x398b); + } + return JSON.stringify(value).length; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** A mutation queue for a specific user, backed by IndexedDB. */ +class IndexedDbMutationQueue { + constructor( + /** + * The normalized userId (e.g. null UID => "" userId) used to store / + * retrieve mutations. + */ + userId, serializer, indexManager, referenceDelegate) { + this.userId = userId; + this.serializer = serializer; + this.indexManager = indexManager; + this.referenceDelegate = referenceDelegate; + /** + * Caches the document keys for pending mutation batches. If the mutation + * has been removed from IndexedDb, the cached value may continue to + * be used to retrieve the batch's document keys. To remove a cached value + * locally, `removeCachedMutationKeys()` should be invoked either directly + * or through `removeMutationBatches()`. + * + * With multi-tab, when the primary client acknowledges or rejects a mutation, + * this cache is used by secondary clients to invalidate the local + * view of the documents that were previously affected by the mutation. + */ + // PORTING NOTE: Multi-tab only. + this.documentKeysByBatchId = {}; + } + /** + * Creates a new mutation queue for the given user. + * @param user - The user for which to create a mutation queue. + * @param serializer - The serializer to use when persisting to IndexedDb. + */ + static forUser(user, serializer, indexManager, referenceDelegate) { + // TODO(mcg): Figure out what constraints there are on userIDs + // In particular, are there any reserved characters? are empty ids allowed? + // For the moment store these together in the same mutations table assuming + // that empty userIDs aren't allowed. + hardAssert(user.uid !== '', 0xfb83); + const userId = user.isAuthenticated() ? user.uid : ''; + return new IndexedDbMutationQueue(userId, serializer, indexManager, referenceDelegate); + } + checkEmpty(transaction) { + let empty = true; + const range = IDBKeyRange.bound([this.userId, Number.NEGATIVE_INFINITY], [this.userId, Number.POSITIVE_INFINITY]); + return mutationsStore(transaction) + .iterate({ index: DbMutationBatchUserMutationsIndex, range }, (key, value, control) => { + empty = false; + control.done(); + }) + .next(() => empty); + } + addMutationBatch(transaction, localWriteTime, baseMutations, mutations) { + const documentStore = documentMutationsStore(transaction); + const mutationStore = mutationsStore(transaction); + // The IndexedDb implementation in Chrome (and Firefox) does not handle + // compound indices that include auto-generated keys correctly. To ensure + // that the index entry is added correctly in all browsers, we perform two + // writes: The first write is used to retrieve the next auto-generated Batch + // ID, and the second write populates the index and stores the actual + // mutation batch. + // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972 + // We write an empty object to obtain key + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return mutationStore.add({}).next(batchId => { + hardAssert(typeof batchId === 'number', 0xbf7b); + const batch = new MutationBatch(batchId, localWriteTime, baseMutations, mutations); + const dbBatch = toDbMutationBatch(this.serializer, this.userId, batch); + const promises = []; + let collectionParents = new SortedSet((l, r) => primitiveComparator(l.canonicalString(), r.canonicalString())); + for (const mutation of mutations) { + const indexKey = newDbDocumentMutationKey(this.userId, mutation.key.path, batchId); + collectionParents = collectionParents.add(mutation.key.path.popLast()); + promises.push(mutationStore.put(dbBatch)); + promises.push(documentStore.put(indexKey, DbDocumentMutationPlaceholder)); + } + collectionParents.forEach(parent => { + promises.push(this.indexManager.addToCollectionParentIndex(transaction, parent)); + }); + transaction.addOnCommittedListener(() => { + this.documentKeysByBatchId[batchId] = batch.keys(); + }); + return PersistencePromise.waitFor(promises).next(() => batch); + }); + } + lookupMutationBatch(transaction, batchId) { + return mutationsStore(transaction) + .get(batchId) + .next(dbBatch => { + if (dbBatch) { + hardAssert(dbBatch.userId === this.userId, 0x0030, `Unexpected user for mutation batch`, { + userId: dbBatch.userId, + batchId + }); + return fromDbMutationBatch(this.serializer, dbBatch); + } + return null; + }); + } + /** + * Returns the document keys for the mutation batch with the given batchId. + * For primary clients, this method returns `null` after + * `removeMutationBatches()` has been called. Secondary clients return a + * cached result until `removeCachedMutationKeys()` is invoked. + */ + // PORTING NOTE: Multi-tab only. + lookupMutationKeys(transaction, batchId) { + if (this.documentKeysByBatchId[batchId]) { + return PersistencePromise.resolve(this.documentKeysByBatchId[batchId]); + } + else { + return this.lookupMutationBatch(transaction, batchId).next(batch => { + if (batch) { + const keys = batch.keys(); + this.documentKeysByBatchId[batchId] = keys; + return keys; + } + else { + return null; + } + }); + } + } + getNextMutationBatchAfterBatchId(transaction, batchId) { + const nextBatchId = batchId + 1; + const range = IDBKeyRange.lowerBound([this.userId, nextBatchId]); + let foundBatch = null; + return mutationsStore(transaction) + .iterate({ index: DbMutationBatchUserMutationsIndex, range }, (key, dbBatch, control) => { + if (dbBatch.userId === this.userId) { + hardAssert(dbBatch.batchId >= nextBatchId, 0xb9a4, { nextBatchId }); + foundBatch = fromDbMutationBatch(this.serializer, dbBatch); + } + control.done(); + }) + .next(() => foundBatch); + } + getHighestUnacknowledgedBatchId(transaction) { + const range = IDBKeyRange.upperBound([ + this.userId, + Number.POSITIVE_INFINITY + ]); + let batchId = BATCHID_UNKNOWN; + return mutationsStore(transaction) + .iterate({ index: DbMutationBatchUserMutationsIndex, range, reverse: true }, (key, dbBatch, control) => { + batchId = dbBatch.batchId; + control.done(); + }) + .next(() => batchId); + } + getAllMutationBatches(transaction) { + const range = IDBKeyRange.bound([this.userId, BATCHID_UNKNOWN], [this.userId, Number.POSITIVE_INFINITY]); + return mutationsStore(transaction) + .loadAll(DbMutationBatchUserMutationsIndex, range) + .next(dbBatches => dbBatches.map(dbBatch => fromDbMutationBatch(this.serializer, dbBatch))); + } + getAllMutationBatchesAffectingDocumentKey(transaction, documentKey) { + // Scan the document-mutation index starting with a prefix starting with + // the given documentKey. + const indexPrefix = newDbDocumentMutationPrefixForPath(this.userId, documentKey.path); + const indexStart = IDBKeyRange.lowerBound(indexPrefix); + const results = []; + return documentMutationsStore(transaction) + .iterate({ range: indexStart }, (indexKey, _, control) => { + const [userID, encodedPath, batchId] = indexKey; + // Only consider rows matching exactly the specific key of + // interest. Note that because we order by path first, and we + // order terminators before path separators, we'll encounter all + // the index rows for documentKey contiguously. In particular, all + // the rows for documentKey will occur before any rows for + // documents nested in a subcollection beneath documentKey so we + // can stop as soon as we hit any such row. + const path = decodeResourcePath(encodedPath); + if (userID !== this.userId || !documentKey.path.isEqual(path)) { + control.done(); + return; + } + // Look up the mutation batch in the store. + return mutationsStore(transaction) + .get(batchId) + .next(mutation => { + if (!mutation) { + throw fail(0xf028, { + indexKey, + batchId + }); + } + hardAssert(mutation.userId === this.userId, 0x2907, `Unexpected user for mutation batch`, { + userId: mutation.userId, + batchId + }); + results.push(fromDbMutationBatch(this.serializer, mutation)); + }); + }) + .next(() => results); + } + getAllMutationBatchesAffectingDocumentKeys(transaction, documentKeys) { + let uniqueBatchIDs = new SortedSet(primitiveComparator); + const promises = []; + documentKeys.forEach(documentKey => { + const indexStart = newDbDocumentMutationPrefixForPath(this.userId, documentKey.path); + const range = IDBKeyRange.lowerBound(indexStart); + const promise = documentMutationsStore(transaction).iterate({ range }, (indexKey, _, control) => { + const [userID, encodedPath, batchID] = indexKey; + // Only consider rows matching exactly the specific key of + // interest. Note that because we order by path first, and we + // order terminators before path separators, we'll encounter all + // the index rows for documentKey contiguously. In particular, all + // the rows for documentKey will occur before any rows for + // documents nested in a subcollection beneath documentKey so we + // can stop as soon as we hit any such row. + const path = decodeResourcePath(encodedPath); + if (userID !== this.userId || !documentKey.path.isEqual(path)) { + control.done(); + return; + } + uniqueBatchIDs = uniqueBatchIDs.add(batchID); + }); + promises.push(promise); + }); + return PersistencePromise.waitFor(promises).next(() => this.lookupMutationBatches(transaction, uniqueBatchIDs)); + } + getAllMutationBatchesAffectingQuery(transaction, query) { + const queryPath = query.path; + const immediateChildrenLength = queryPath.length + 1; + // TODO(mcg): Actually implement a single-collection query + // + // This is actually executing an ancestor query, traversing the whole + // subtree below the collection which can be horrifically inefficient for + // some structures. The right way to solve this is to implement the full + // value index, but that's not in the cards in the near future so this is + // the best we can do for the moment. + // + // Since we don't yet index the actual properties in the mutations, our + // current approach is to just return all mutation batches that affect + // documents in the collection being queried. + const indexPrefix = newDbDocumentMutationPrefixForPath(this.userId, queryPath); + const indexStart = IDBKeyRange.lowerBound(indexPrefix); + // Collect up unique batchIDs encountered during a scan of the index. Use a + // SortedSet to accumulate batch IDs so they can be traversed in order in a + // scan of the main table. + let uniqueBatchIDs = new SortedSet(primitiveComparator); + return documentMutationsStore(transaction) + .iterate({ range: indexStart }, (indexKey, _, control) => { + const [userID, encodedPath, batchID] = indexKey; + const path = decodeResourcePath(encodedPath); + if (userID !== this.userId || !queryPath.isPrefixOf(path)) { + control.done(); + return; + } + // Rows with document keys more than one segment longer than the + // query path can't be matches. For example, a query on 'rooms' + // can't match the document /rooms/abc/messages/xyx. + // TODO(mcg): we'll need a different scanner when we implement + // ancestor queries. + if (path.length !== immediateChildrenLength) { + return; + } + uniqueBatchIDs = uniqueBatchIDs.add(batchID); + }) + .next(() => this.lookupMutationBatches(transaction, uniqueBatchIDs)); + } + lookupMutationBatches(transaction, batchIDs) { + const results = []; + const promises = []; + // TODO(rockwood): Implement this using iterate. + batchIDs.forEach(batchId => { + promises.push(mutationsStore(transaction) + .get(batchId) + .next(mutation => { + if (mutation === null) { + throw fail(0x89ca, { + batchId + }); + } + hardAssert(mutation.userId === this.userId, 0x2614, `Unexpected user for mutation batch`, { userId: mutation.userId, batchId }); + results.push(fromDbMutationBatch(this.serializer, mutation)); + })); + }); + return PersistencePromise.waitFor(promises).next(() => results); + } + removeMutationBatch(transaction, batch) { + return removeMutationBatch(transaction.simpleDbTransaction, this.userId, batch).next(removedDocuments => { + transaction.addOnCommittedListener(() => { + this.removeCachedMutationKeys(batch.batchId); + }); + return PersistencePromise.forEach(removedDocuments, (key) => { + return this.referenceDelegate.markPotentiallyOrphaned(transaction, key); + }); + }); + } + /** + * Clears the cached keys for a mutation batch. This method should be + * called by secondary clients after they process mutation updates. + * + * Note that this method does not have to be called from primary clients as + * the corresponding cache entries are cleared when an acknowledged or + * rejected batch is removed from the mutation queue. + */ + // PORTING NOTE: Multi-tab only + removeCachedMutationKeys(batchId) { + delete this.documentKeysByBatchId[batchId]; + } + performConsistencyCheck(txn) { + return this.checkEmpty(txn).next(empty => { + if (!empty) { + return PersistencePromise.resolve(); + } + // Verify that there are no entries in the documentMutations index if + // the queue is empty. + const startRange = IDBKeyRange.lowerBound(newDbDocumentMutationPrefixForUser(this.userId)); + const danglingMutationReferences = []; + return documentMutationsStore(txn) + .iterate({ range: startRange }, (key, _, control) => { + const userID = key[0]; + if (userID !== this.userId) { + control.done(); + return; + } + else { + const path = decodeResourcePath(key[1]); + danglingMutationReferences.push(path); + } + }) + .next(() => { + hardAssert(danglingMutationReferences.length === 0, 0xdd90, { + danglingKeys: danglingMutationReferences.map(p => p.canonicalString()) + }); + }); + }); + } + containsKey(txn, key) { + return mutationQueueContainsKey(txn, this.userId, key); + } + // PORTING NOTE: Multi-tab only (state is held in memory in other clients). + /** Returns the mutation queue's metadata from IndexedDb. */ + getMutationQueueMetadata(transaction) { + return mutationQueuesStore(transaction) + .get(this.userId) + .next((metadata) => { + return (metadata || { + userId: this.userId, + lastAcknowledgedBatchId: BATCHID_UNKNOWN, + lastStreamToken: '' + }); + }); + } +} +/** + * @returns true if the mutation queue for the given user contains a pending + * mutation for the given key. + */ +function mutationQueueContainsKey(txn, userId, key) { + const indexKey = newDbDocumentMutationPrefixForPath(userId, key.path); + const encodedPath = indexKey[1]; + const startRange = IDBKeyRange.lowerBound(indexKey); + let containsKey = false; + return documentMutationsStore(txn) + .iterate({ range: startRange, keysOnly: true }, (key, value, control) => { + const [userID, keyPath, /*batchID*/ _] = key; + if (userID === userId && keyPath === encodedPath) { + containsKey = true; + } + control.done(); + }) + .next(() => containsKey); +} +/** Returns true if any mutation queue contains the given document. */ +function mutationQueuesContainKey(txn, docKey) { + let found = false; + return mutationQueuesStore(txn) + .iterateSerial(userId => { + return mutationQueueContainsKey(txn, userId, docKey).next(containsKey => { + if (containsKey) { + found = true; + } + return PersistencePromise.resolve(!containsKey); + }); + }) + .next(() => found); +} +/** + * Helper to get a typed SimpleDbStore for the mutations object store. + */ +function mutationsStore(txn) { + return getStore(txn, DbMutationBatchStore); +} +/** + * Helper to get a typed SimpleDbStore for the mutationQueues object store. + */ +function documentMutationsStore(txn) { + return getStore(txn, DbDocumentMutationStore); +} +/** + * Helper to get a typed SimpleDbStore for the mutationQueues object store. + */ +function mutationQueuesStore(txn) { + return getStore(txn, DbMutationQueueStore); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Offset to ensure non-overlapping target ids. */ +const OFFSET = 2; +/** + * Generates monotonically increasing target IDs for sending targets to the + * watch stream. + * + * The client constructs two generators, one for the target cache, and one for + * for the sync engine (to generate limbo documents targets). These + * generators produce non-overlapping IDs (by using even and odd IDs + * respectively). + * + * By separating the target ID space, the query cache can generate target IDs + * that persist across client restarts, while sync engine can independently + * generate in-memory target IDs that are transient and can be reused after a + * restart. + */ +class TargetIdGenerator { + constructor(lastId) { + this.lastId = lastId; + } + next() { + this.lastId += OFFSET; + return this.lastId; + } + static forTargetCache() { + // The target cache generator must return '2' in its first call to `next()` + // as there is no differentiation in the protocol layer between an unset + // number and the number '0'. If we were to sent a target with target ID + // '0', the backend would consider it unset and replace it with its own ID. + return new TargetIdGenerator(2 - OFFSET); + } + static forSyncEngine() { + // Sync engine assigns target IDs for limbo document detection. + return new TargetIdGenerator(1 - OFFSET); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class IndexedDbTargetCache { + constructor(referenceDelegate, serializer) { + this.referenceDelegate = referenceDelegate; + this.serializer = serializer; + } + // PORTING NOTE: We don't cache global metadata for the target cache, since + // some of it (in particular `highestTargetId`) can be modified by secondary + // tabs. We could perhaps be more granular (and e.g. still cache + // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go + // to IndexedDb whenever we need to read metadata. We can revisit if it turns + // out to have a meaningful performance impact. + allocateTargetId(transaction) { + return this.retrieveMetadata(transaction).next(metadata => { + const targetIdGenerator = new TargetIdGenerator(metadata.highestTargetId); + metadata.highestTargetId = targetIdGenerator.next(); + return this.saveMetadata(transaction, metadata).next(() => metadata.highestTargetId); + }); + } + getLastRemoteSnapshotVersion(transaction) { + return this.retrieveMetadata(transaction).next(metadata => { + return SnapshotVersion.fromTimestamp(new Timestamp(metadata.lastRemoteSnapshotVersion.seconds, metadata.lastRemoteSnapshotVersion.nanoseconds)); + }); + } + getHighestSequenceNumber(transaction) { + return this.retrieveMetadata(transaction).next(targetGlobal => targetGlobal.highestListenSequenceNumber); + } + setTargetsMetadata(transaction, highestListenSequenceNumber, lastRemoteSnapshotVersion) { + return this.retrieveMetadata(transaction).next(metadata => { + metadata.highestListenSequenceNumber = highestListenSequenceNumber; + if (lastRemoteSnapshotVersion) { + metadata.lastRemoteSnapshotVersion = + lastRemoteSnapshotVersion.toTimestamp(); + } + if (highestListenSequenceNumber > metadata.highestListenSequenceNumber) { + metadata.highestListenSequenceNumber = highestListenSequenceNumber; + } + return this.saveMetadata(transaction, metadata); + }); + } + addTargetData(transaction, targetData) { + return this.saveTargetData(transaction, targetData).next(() => { + return this.retrieveMetadata(transaction).next(metadata => { + metadata.targetCount += 1; + this.updateMetadataFromTargetData(targetData, metadata); + return this.saveMetadata(transaction, metadata); + }); + }); + } + updateTargetData(transaction, targetData) { + return this.saveTargetData(transaction, targetData); + } + removeTargetData(transaction, targetData) { + return this.removeMatchingKeysForTargetId(transaction, targetData.targetId) + .next(() => targetsStore(transaction).delete(targetData.targetId)) + .next(() => this.retrieveMetadata(transaction)) + .next(metadata => { + hardAssert(metadata.targetCount > 0, 0x1f81); + metadata.targetCount -= 1; + return this.saveMetadata(transaction, metadata); + }); + } + /** + * Drops any targets with sequence number less than or equal to the upper bound, excepting those + * present in `activeTargetIds`. Document associations for the removed targets are also removed. + * Returns the number of targets removed. + */ + removeTargets(txn, upperBound, activeTargetIds) { + let count = 0; + const promises = []; + return targetsStore(txn) + .iterate((key, value) => { + const targetData = fromDbTarget(value); + if (targetData.sequenceNumber <= upperBound && + activeTargetIds.get(targetData.targetId) === null) { + count++; + promises.push(this.removeTargetData(txn, targetData)); + } + }) + .next(() => PersistencePromise.waitFor(promises)) + .next(() => count); + } + /** + * Call provided function with each `TargetData` that we have cached. + */ + forEachTarget(txn, f) { + return targetsStore(txn).iterate((key, value) => { + const targetData = fromDbTarget(value); + f(targetData); + }); + } + retrieveMetadata(transaction) { + return globalTargetStore(transaction) + .get(DbTargetGlobalKey) + .next(metadata => { + hardAssert(metadata !== null, 0x0b48); + return metadata; + }); + } + saveMetadata(transaction, metadata) { + return globalTargetStore(transaction).put(DbTargetGlobalKey, metadata); + } + saveTargetData(transaction, targetData) { + return targetsStore(transaction).put(toDbTarget(this.serializer, targetData)); + } + /** + * In-place updates the provided metadata to account for values in the given + * TargetData. Saving is done separately. Returns true if there were any + * changes to the metadata. + */ + updateMetadataFromTargetData(targetData, metadata) { + let updated = false; + if (targetData.targetId > metadata.highestTargetId) { + metadata.highestTargetId = targetData.targetId; + updated = true; + } + if (targetData.sequenceNumber > metadata.highestListenSequenceNumber) { + metadata.highestListenSequenceNumber = targetData.sequenceNumber; + updated = true; + } + return updated; + } + getTargetCount(transaction) { + return this.retrieveMetadata(transaction).next(metadata => metadata.targetCount); + } + getTargetData(transaction, target) { + // Iterating by the canonicalId may yield more than one result because + // canonicalId values are not required to be unique per target. This query + // depends on the queryTargets index to be efficient. + const canonicalId = canonifyTarget(target); + const range = IDBKeyRange.bound([canonicalId, Number.NEGATIVE_INFINITY], [canonicalId, Number.POSITIVE_INFINITY]); + let result = null; + return targetsStore(transaction) + .iterate({ range, index: DbTargetQueryTargetsIndexName }, (key, value, control) => { + const found = fromDbTarget(value); + // After finding a potential match, check that the target is + // actually equal to the requested target. + if (targetEquals(target, found.target)) { + result = found; + control.done(); + } + }) + .next(() => result); + } + addMatchingKeys(txn, keys, targetId) { + // PORTING NOTE: The reverse index (documentsTargets) is maintained by + // IndexedDb. + const promises = []; + const store = documentTargetStore(txn); + keys.forEach(key => { + const path = encodeResourcePath(key.path); + promises.push(store.put({ targetId, path })); + promises.push(this.referenceDelegate.addReference(txn, targetId, key)); + }); + return PersistencePromise.waitFor(promises); + } + removeMatchingKeys(txn, keys, targetId) { + // PORTING NOTE: The reverse index (documentsTargets) is maintained by + // IndexedDb. + const store = documentTargetStore(txn); + return PersistencePromise.forEach(keys, (key) => { + const path = encodeResourcePath(key.path); + return PersistencePromise.waitFor([ + store.delete([targetId, path]), + this.referenceDelegate.removeReference(txn, targetId, key) + ]); + }); + } + removeMatchingKeysForTargetId(txn, targetId) { + const store = documentTargetStore(txn); + const range = IDBKeyRange.bound([targetId], [targetId + 1], + /*lowerOpen=*/ false, + /*upperOpen=*/ true); + return store.delete(range); + } + getMatchingKeysForTargetId(txn, targetId) { + const range = IDBKeyRange.bound([targetId], [targetId + 1], + /*lowerOpen=*/ false, + /*upperOpen=*/ true); + const store = documentTargetStore(txn); + let result = documentKeySet(); + return store + .iterate({ range, keysOnly: true }, (key, _, control) => { + const path = decodeResourcePath(key[1]); + const docKey = new DocumentKey(path); + result = result.add(docKey); + }) + .next(() => result); + } + containsKey(txn, key) { + const path = encodeResourcePath(key.path); + const range = IDBKeyRange.bound([path], [immediateSuccessor(path)], + /*lowerOpen=*/ false, + /*upperOpen=*/ true); + let count = 0; + return documentTargetStore(txn) + .iterate({ + index: DbTargetDocumentDocumentTargetsIndex, + keysOnly: true, + range + }, ([targetId, path], _, control) => { + // Having a sentinel row for a document does not count as containing that document; + // For the target cache, containing the document means the document is part of some + // target. + if (targetId !== 0) { + count++; + control.done(); + } + }) + .next(() => count > 0); + } + /** + * Looks up a TargetData entry by target ID. + * + * @param targetId - The target ID of the TargetData entry to look up. + * @returns The cached TargetData entry, or null if the cache has no entry for + * the target. + */ + // PORTING NOTE: Multi-tab only. + getTargetDataForTarget(transaction, targetId) { + return targetsStore(transaction) + .get(targetId) + .next(found => { + if (found) { + return fromDbTarget(found); + } + else { + return null; + } + }); + } +} +/** + * Helper to get a typed SimpleDbStore for the queries object store. + */ +function targetsStore(txn) { + return getStore(txn, DbTargetStore); +} +/** + * Helper to get a typed SimpleDbStore for the target globals object store. + */ +function globalTargetStore(txn) { + return getStore(txn, DbTargetGlobalStore); +} +/** + * Helper to get a typed SimpleDbStore for the document target object store. + */ +function documentTargetStore(txn) { + return getStore(txn, DbTargetDocumentStore); +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const GC_DID_NOT_RUN = { + didRun: false, + sequenceNumbersCollected: 0, + targetsRemoved: 0, + documentsRemoved: 0 +}; +const LRU_COLLECTION_DISABLED = -1; +const LRU_DEFAULT_CACHE_SIZE_BYTES = 40 * 1024 * 1024; +class LruParams { + static withCacheSize(cacheSize) { + return new LruParams(cacheSize, LruParams.DEFAULT_COLLECTION_PERCENTILE, LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT); + } + constructor( + // When we attempt to collect, we will only do so if the cache size is greater than this + // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped. + cacheSizeCollectionThreshold, + // The percentage of sequence numbers that we will attempt to collect + percentileToCollect, + // A cap on the total number of sequence numbers that will be collected. This prevents + // us from collecting a huge number of sequence numbers if the cache has grown very large. + maximumSequenceNumbersToCollect) { + this.cacheSizeCollectionThreshold = cacheSizeCollectionThreshold; + this.percentileToCollect = percentileToCollect; + this.maximumSequenceNumbersToCollect = maximumSequenceNumbersToCollect; + } +} +LruParams.DEFAULT_COLLECTION_PERCENTILE = 10; +LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1000; +LruParams.DEFAULT = new LruParams(LRU_DEFAULT_CACHE_SIZE_BYTES, LruParams.DEFAULT_COLLECTION_PERCENTILE, LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT); +LruParams.DISABLED = new LruParams(LRU_COLLECTION_DISABLED, 0, 0); + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$e = 'LruGarbageCollector'; +const LRU_MINIMUM_CACHE_SIZE_BYTES = 1 * 1024 * 1024; +/** How long we wait to try running LRU GC after SDK initialization. */ +const INITIAL_GC_DELAY_MS = 1 * 60 * 1000; +/** Minimum amount of time between GC checks, after the first one. */ +const REGULAR_GC_DELAY_MS = 5 * 60 * 1000; +function bufferEntryComparator([aSequence, aIndex], [bSequence, bIndex]) { + const seqCmp = primitiveComparator(aSequence, bSequence); + if (seqCmp === 0) { + // This order doesn't matter, but we can bias against churn by sorting + // entries created earlier as less than newer entries. + return primitiveComparator(aIndex, bIndex); + } + else { + return seqCmp; + } +} +/** + * Used to calculate the nth sequence number. Keeps a rolling buffer of the + * lowest n values passed to `addElement`, and finally reports the largest of + * them in `maxValue`. + */ +class RollingSequenceNumberBuffer { + constructor(maxElements) { + this.maxElements = maxElements; + this.buffer = new SortedSet(bufferEntryComparator); + this.previousIndex = 0; + } + nextIndex() { + return ++this.previousIndex; + } + addElement(sequenceNumber) { + const entry = [sequenceNumber, this.nextIndex()]; + if (this.buffer.size < this.maxElements) { + this.buffer = this.buffer.add(entry); + } + else { + const highestValue = this.buffer.last(); + if (bufferEntryComparator(entry, highestValue) < 0) { + this.buffer = this.buffer.delete(highestValue).add(entry); + } + } + } + get maxValue() { + // Guaranteed to be non-empty. If we decide we are not collecting any + // sequence numbers, nthSequenceNumber below short-circuits. If we have + // decided that we are collecting n sequence numbers, it's because n is some + // percentage of the existing sequence numbers. That means we should never + // be in a situation where we are collecting sequence numbers but don't + // actually have any. + return this.buffer.last()[0]; + } +} +/** + * This class is responsible for the scheduling of LRU garbage collection. It handles checking + * whether or not GC is enabled, as well as which delay to use before the next run. + */ +class LruScheduler { + constructor(garbageCollector, asyncQueue, localStore) { + this.garbageCollector = garbageCollector; + this.asyncQueue = asyncQueue; + this.localStore = localStore; + this.gcTask = null; + } + start() { + if (this.garbageCollector.params.cacheSizeCollectionThreshold !== + LRU_COLLECTION_DISABLED) { + this.scheduleGC(INITIAL_GC_DELAY_MS); + } + } + stop() { + if (this.gcTask) { + this.gcTask.cancel(); + this.gcTask = null; + } + } + get started() { + return this.gcTask !== null; + } + scheduleGC(delay) { + logDebug(LOG_TAG$e, `Garbage collection scheduled in ${delay}ms`); + this.gcTask = this.asyncQueue.enqueueAfterDelay("lru_garbage_collection" /* TimerId.LruGarbageCollection */, delay, async () => { + this.gcTask = null; + try { + await this.localStore.collectGarbage(this.garbageCollector); + } + catch (e) { + if (isIndexedDbTransactionError(e)) { + logDebug(LOG_TAG$e, 'Ignoring IndexedDB error during garbage collection: ', e); + } + else { + await ignoreIfPrimaryLeaseLoss(e); + } + } + await this.scheduleGC(REGULAR_GC_DELAY_MS); + }); + } +} +/** + * Implements the steps for LRU garbage collection. + */ +class LruGarbageCollectorImpl { + constructor(delegate, params) { + this.delegate = delegate; + this.params = params; + } + calculateTargetCount(txn, percentile) { + return this.delegate.getSequenceNumberCount(txn).next(targetCount => { + return Math.floor((percentile / 100.0) * targetCount); + }); + } + nthSequenceNumber(txn, n) { + if (n === 0) { + return PersistencePromise.resolve(ListenSequence.INVALID); + } + const buffer = new RollingSequenceNumberBuffer(n); + return this.delegate + .forEachTarget(txn, target => buffer.addElement(target.sequenceNumber)) + .next(() => { + return this.delegate.forEachOrphanedDocumentSequenceNumber(txn, sequenceNumber => buffer.addElement(sequenceNumber)); + }) + .next(() => buffer.maxValue); + } + removeTargets(txn, upperBound, activeTargetIds) { + return this.delegate.removeTargets(txn, upperBound, activeTargetIds); + } + removeOrphanedDocuments(txn, upperBound) { + return this.delegate.removeOrphanedDocuments(txn, upperBound); + } + collect(txn, activeTargetIds) { + if (this.params.cacheSizeCollectionThreshold === LRU_COLLECTION_DISABLED) { + logDebug('LruGarbageCollector', 'Garbage collection skipped; disabled'); + return PersistencePromise.resolve(GC_DID_NOT_RUN); + } + return this.getCacheSize(txn).next(cacheSize => { + if (cacheSize < this.params.cacheSizeCollectionThreshold) { + logDebug('LruGarbageCollector', `Garbage collection skipped; Cache size ${cacheSize} ` + + `is lower than threshold ${this.params.cacheSizeCollectionThreshold}`); + return GC_DID_NOT_RUN; + } + else { + return this.runGarbageCollection(txn, activeTargetIds); + } + }); + } + getCacheSize(txn) { + return this.delegate.getCacheSize(txn); + } + runGarbageCollection(txn, activeTargetIds) { + let upperBoundSequenceNumber; + let sequenceNumbersToCollect, targetsRemoved; + // Timestamps for various pieces of the process + let countedTargetsTs, foundUpperBoundTs, removedTargetsTs, removedDocumentsTs; + const startTs = Date.now(); + return this.calculateTargetCount(txn, this.params.percentileToCollect) + .next(sequenceNumbers => { + // Cap at the configured max + if (sequenceNumbers > this.params.maximumSequenceNumbersToCollect) { + logDebug('LruGarbageCollector', 'Capping sequence numbers to collect down ' + + `to the maximum of ${this.params.maximumSequenceNumbersToCollect} ` + + `from ${sequenceNumbers}`); + sequenceNumbersToCollect = + this.params.maximumSequenceNumbersToCollect; + } + else { + sequenceNumbersToCollect = sequenceNumbers; + } + countedTargetsTs = Date.now(); + return this.nthSequenceNumber(txn, sequenceNumbersToCollect); + }) + .next(upperBound => { + upperBoundSequenceNumber = upperBound; + foundUpperBoundTs = Date.now(); + return this.removeTargets(txn, upperBoundSequenceNumber, activeTargetIds); + }) + .next(numTargetsRemoved => { + targetsRemoved = numTargetsRemoved; + removedTargetsTs = Date.now(); + return this.removeOrphanedDocuments(txn, upperBoundSequenceNumber); + }) + .next(documentsRemoved => { + removedDocumentsTs = Date.now(); + if (getLogLevel() <= LogLevel.DEBUG) { + const desc = 'LRU Garbage Collection\n' + + `\tCounted targets in ${countedTargetsTs - startTs}ms\n` + + `\tDetermined least recently used ${sequenceNumbersToCollect} in ` + + `${foundUpperBoundTs - countedTargetsTs}ms\n` + + `\tRemoved ${targetsRemoved} targets in ` + + `${removedTargetsTs - foundUpperBoundTs}ms\n` + + `\tRemoved ${documentsRemoved} documents in ` + + `${removedDocumentsTs - removedTargetsTs}ms\n` + + `Total Duration: ${removedDocumentsTs - startTs}ms`; + logDebug('LruGarbageCollector', desc); + } + return PersistencePromise.resolve({ + didRun: true, + sequenceNumbersCollected: sequenceNumbersToCollect, + targetsRemoved, + documentsRemoved + }); + }); + } +} +function newLruGarbageCollector(delegate, params) { + return new LruGarbageCollectorImpl(delegate, params); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Provides LRU functionality for IndexedDB persistence. */ +class IndexedDbLruDelegateImpl { + constructor(db, params) { + this.db = db; + this.garbageCollector = newLruGarbageCollector(this, params); + } + getSequenceNumberCount(txn) { + const docCountPromise = this.orphanedDocumentCount(txn); + const targetCountPromise = this.db.getTargetCache().getTargetCount(txn); + return targetCountPromise.next(targetCount => docCountPromise.next(docCount => targetCount + docCount)); + } + orphanedDocumentCount(txn) { + let orphanedCount = 0; + return this.forEachOrphanedDocumentSequenceNumber(txn, _ => { + orphanedCount++; + }).next(() => orphanedCount); + } + forEachTarget(txn, f) { + return this.db.getTargetCache().forEachTarget(txn, f); + } + forEachOrphanedDocumentSequenceNumber(txn, f) { + return this.forEachOrphanedDocument(txn, (docKey, sequenceNumber) => f(sequenceNumber)); + } + addReference(txn, targetId, key) { + return writeSentinelKey(txn, key); + } + removeReference(txn, targetId, key) { + return writeSentinelKey(txn, key); + } + removeTargets(txn, upperBound, activeTargetIds) { + return this.db.getTargetCache().removeTargets(txn, upperBound, activeTargetIds); + } + markPotentiallyOrphaned(txn, key) { + return writeSentinelKey(txn, key); + } + /** + * Returns true if anything would prevent this document from being garbage + * collected, given that the document in question is not present in any + * targets and has a sequence number less than or equal to the upper bound for + * the collection run. + */ + isPinned(txn, docKey) { + return mutationQueuesContainKey(txn, docKey); + } + removeOrphanedDocuments(txn, upperBound) { + const documentCache = this.db.getRemoteDocumentCache(); + const changeBuffer = documentCache.newChangeBuffer(); + const promises = []; + let documentCount = 0; + const iteration = this.forEachOrphanedDocument(txn, (docKey, sequenceNumber) => { + if (sequenceNumber <= upperBound) { + const p = this.isPinned(txn, docKey).next(isPinned => { + if (!isPinned) { + documentCount++; + // Our size accounting requires us to read all documents before + // removing them. + return changeBuffer.getEntry(txn, docKey).next(() => { + changeBuffer.removeEntry(docKey, SnapshotVersion.min()); + return documentTargetStore(txn).delete(sentinelKey$1(docKey)); + }); + } + }); + promises.push(p); + } + }); + return iteration + .next(() => PersistencePromise.waitFor(promises)) + .next(() => changeBuffer.apply(txn)) + .next(() => documentCount); + } + removeTarget(txn, targetData) { + const updated = targetData.withSequenceNumber(txn.currentSequenceNumber); + return this.db.getTargetCache().updateTargetData(txn, updated); + } + updateLimboDocument(txn, key) { + return writeSentinelKey(txn, key); + } + /** + * Call provided function for each document in the cache that is 'orphaned'. Orphaned + * means not a part of any target, so the only entry in the target-document index for + * that document will be the sentinel row (targetId 0), which will also have the sequence + * number for the last time the document was accessed. + */ + forEachOrphanedDocument(txn, f) { + const store = documentTargetStore(txn); + let nextToReport = ListenSequence.INVALID; + let nextPath; + return store + .iterate({ + index: DbTargetDocumentDocumentTargetsIndex + }, ([targetId, docKey], { path, sequenceNumber }) => { + if (targetId === 0) { + // if nextToReport is valid, report it, this is a new key so the + // last one must not be a member of any targets. + if (nextToReport !== ListenSequence.INVALID) { + f(new DocumentKey(decodeResourcePath(nextPath)), nextToReport); + } + // set nextToReport to be this sequence number. It's the next one we + // might report, if we don't find any targets for this document. + // Note that the sequence number must be defined when the targetId + // is 0. + nextToReport = sequenceNumber; + nextPath = path; + } + else { + // set nextToReport to be invalid, we know we don't need to report + // this one since we found a target for it. + nextToReport = ListenSequence.INVALID; + } + }) + .next(() => { + // Since we report sequence numbers after getting to the next key, we + // need to check if the last key we iterated over was an orphaned + // document and report it. + if (nextToReport !== ListenSequence.INVALID) { + f(new DocumentKey(decodeResourcePath(nextPath)), nextToReport); + } + }); + } + getCacheSize(txn) { + return this.db.getRemoteDocumentCache().getSize(txn); + } +} +function sentinelKey$1(key) { + return [0, encodeResourcePath(key.path)]; +} +/** + * @returns A value suitable for writing a sentinel row in the target-document + * store. + */ +function sentinelRow(key, sequenceNumber) { + return { targetId: 0, path: encodeResourcePath(key.path), sequenceNumber }; +} +function writeSentinelKey(txn, key) { + return documentTargetStore(txn).put(sentinelRow(key, txn.currentSequenceNumber)); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An in-memory buffer of entries to be written to a RemoteDocumentCache. + * It can be used to batch up a set of changes to be written to the cache, but + * additionally supports reading entries back with the `getEntry()` method, + * falling back to the underlying RemoteDocumentCache if no entry is + * buffered. + * + * Entries added to the cache *must* be read first. This is to facilitate + * calculating the size delta of the pending changes. + * + * PORTING NOTE: This class was implemented then removed from other platforms. + * If byte-counting ends up being needed on the other platforms, consider + * porting this class as part of that implementation work. + */ +class RemoteDocumentChangeBuffer { + constructor() { + // A mapping of document key to the new cache entry that should be written. + this.changes = new ObjectMap(key => key.toString(), (l, r) => l.isEqual(r)); + this.changesApplied = false; + } + /** + * Buffers a `RemoteDocumentCache.addEntry()` call. + * + * You can only modify documents that have already been retrieved via + * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). + */ + addEntry(document) { + this.assertNotApplied(); + this.changes.set(document.key, document); + } + /** + * Buffers a `RemoteDocumentCache.removeEntry()` call. + * + * You can only remove documents that have already been retrieved via + * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). + */ + removeEntry(key, readTime) { + this.assertNotApplied(); + this.changes.set(key, MutableDocument.newInvalidDocument(key).setReadTime(readTime)); + } + /** + * Looks up an entry in the cache. The buffered changes will first be checked, + * and if no buffered change applies, this will forward to + * `RemoteDocumentCache.getEntry()`. + * + * @param transaction - The transaction in which to perform any persistence + * operations. + * @param documentKey - The key of the entry to look up. + * @returns The cached document or an invalid document if we have nothing + * cached. + */ + getEntry(transaction, documentKey) { + this.assertNotApplied(); + const bufferedEntry = this.changes.get(documentKey); + if (bufferedEntry !== undefined) { + return PersistencePromise.resolve(bufferedEntry); + } + else { + return this.getFromCache(transaction, documentKey); + } + } + /** + * Looks up several entries in the cache, forwarding to + * `RemoteDocumentCache.getEntry()`. + * + * @param transaction - The transaction in which to perform any persistence + * operations. + * @param documentKeys - The keys of the entries to look up. + * @returns A map of cached documents, indexed by key. If an entry cannot be + * found, the corresponding key will be mapped to an invalid document. + */ + getEntries(transaction, documentKeys) { + return this.getAllFromCache(transaction, documentKeys); + } + /** + * Applies buffered changes to the underlying RemoteDocumentCache, using + * the provided transaction. + */ + apply(transaction) { + this.assertNotApplied(); + this.changesApplied = true; + return this.applyChanges(transaction); + } + /** Helper to assert this.changes is not null */ + assertNotApplied() { + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The RemoteDocumentCache for IndexedDb. To construct, invoke + * `newIndexedDbRemoteDocumentCache()`. + */ +class IndexedDbRemoteDocumentCacheImpl { + constructor(serializer) { + this.serializer = serializer; + } + setIndexManager(indexManager) { + this.indexManager = indexManager; + } + /** + * Adds the supplied entries to the cache. + * + * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer + * returned by `newChangeBuffer()` to ensure proper accounting of metadata. + */ + addEntry(transaction, key, doc) { + const documentStore = remoteDocumentsStore(transaction); + return documentStore.put(doc); + } + /** + * Removes a document from the cache. + * + * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer + * returned by `newChangeBuffer()` to ensure proper accounting of metadata. + */ + removeEntry(transaction, documentKey, readTime) { + const store = remoteDocumentsStore(transaction); + return store.delete(dbReadTimeKey(documentKey, readTime)); + } + /** + * Updates the current cache size. + * + * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the + * cache's metadata. + */ + updateMetadata(transaction, sizeDelta) { + return this.getMetadata(transaction).next(metadata => { + metadata.byteSize += sizeDelta; + return this.setMetadata(transaction, metadata); + }); + } + getEntry(transaction, documentKey) { + let doc = MutableDocument.newInvalidDocument(documentKey); + return remoteDocumentsStore(transaction) + .iterate({ + index: DbRemoteDocumentDocumentKeyIndex, + range: IDBKeyRange.only(dbKey(documentKey)) + }, (_, dbRemoteDoc) => { + doc = this.maybeDecodeDocument(documentKey, dbRemoteDoc); + }) + .next(() => doc); + } + /** + * Looks up an entry in the cache. + * + * @param documentKey - The key of the entry to look up. + * @returns The cached document entry and its size. + */ + getSizedEntry(transaction, documentKey) { + let result = { + size: 0, + document: MutableDocument.newInvalidDocument(documentKey) + }; + return remoteDocumentsStore(transaction) + .iterate({ + index: DbRemoteDocumentDocumentKeyIndex, + range: IDBKeyRange.only(dbKey(documentKey)) + }, (_, dbRemoteDoc) => { + result = { + document: this.maybeDecodeDocument(documentKey, dbRemoteDoc), + size: dbDocumentSize(dbRemoteDoc) + }; + }) + .next(() => result); + } + getEntries(transaction, documentKeys) { + let results = mutableDocumentMap(); + return this.forEachDbEntry(transaction, documentKeys, (key, dbRemoteDoc) => { + const doc = this.maybeDecodeDocument(key, dbRemoteDoc); + results = results.insert(key, doc); + }).next(() => results); + } + /** + * Looks up several entries in the cache. + * + * @param documentKeys - The set of keys entries to look up. + * @returns A map of documents indexed by key and a map of sizes indexed by + * key (zero if the document does not exist). + */ + getSizedEntries(transaction, documentKeys) { + let results = mutableDocumentMap(); + let sizeMap = new SortedMap(DocumentKey.comparator); + return this.forEachDbEntry(transaction, documentKeys, (key, dbRemoteDoc) => { + const doc = this.maybeDecodeDocument(key, dbRemoteDoc); + results = results.insert(key, doc); + sizeMap = sizeMap.insert(key, dbDocumentSize(dbRemoteDoc)); + }).next(() => { + return { documents: results, sizeMap }; + }); + } + forEachDbEntry(transaction, documentKeys, callback) { + if (documentKeys.isEmpty()) { + return PersistencePromise.resolve(); + } + let sortedKeys = new SortedSet(dbKeyComparator); + documentKeys.forEach(e => (sortedKeys = sortedKeys.add(e))); + const range = IDBKeyRange.bound(dbKey(sortedKeys.first()), dbKey(sortedKeys.last())); + const keyIter = sortedKeys.getIterator(); + let nextKey = keyIter.getNext(); + return remoteDocumentsStore(transaction) + .iterate({ index: DbRemoteDocumentDocumentKeyIndex, range }, (_, dbRemoteDoc, control) => { + const potentialKey = DocumentKey.fromSegments([ + ...dbRemoteDoc.prefixPath, + dbRemoteDoc.collectionGroup, + dbRemoteDoc.documentId + ]); + // Go through keys not found in cache. + while (nextKey && dbKeyComparator(nextKey, potentialKey) < 0) { + callback(nextKey, null); + nextKey = keyIter.getNext(); + } + if (nextKey && nextKey.isEqual(potentialKey)) { + // Key found in cache. + callback(nextKey, dbRemoteDoc); + nextKey = keyIter.hasNext() ? keyIter.getNext() : null; + } + // Skip to the next key (if there is one). + if (nextKey) { + control.skip(dbKey(nextKey)); + } + else { + control.done(); + } + }) + .next(() => { + // The rest of the keys are not in the cache. One case where `iterate` + // above won't go through them is when the cache is empty. + while (nextKey) { + callback(nextKey, null); + nextKey = keyIter.hasNext() ? keyIter.getNext() : null; + } + }); + } + getDocumentsMatchingQuery(transaction, query, offset, mutatedDocs, context) { + const collection = query.path; + const startKey = [ + collection.popLast().toArray(), + collection.lastSegment(), + toDbTimestampKey(offset.readTime), + offset.documentKey.path.isEmpty() + ? '' + : offset.documentKey.path.lastSegment() + ]; + const endKey = [ + collection.popLast().toArray(), + collection.lastSegment(), + [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], + '' + ]; + return remoteDocumentsStore(transaction) + .loadAll(IDBKeyRange.bound(startKey, endKey, true)) + .next(dbRemoteDocs => { + context?.incrementDocumentReadCount(dbRemoteDocs.length); + let results = mutableDocumentMap(); + for (const dbRemoteDoc of dbRemoteDocs) { + const document = this.maybeDecodeDocument(DocumentKey.fromSegments(dbRemoteDoc.prefixPath.concat(dbRemoteDoc.collectionGroup, dbRemoteDoc.documentId)), dbRemoteDoc); + if (document.isFoundDocument() && + (queryMatches(query, document) || mutatedDocs.has(document.key))) { + // Either the document matches the given query, or it is mutated. + results = results.insert(document.key, document); + } + } + return results; + }); + } + getAllFromCollectionGroup(transaction, collectionGroup, offset, limit) { + let results = mutableDocumentMap(); + const startKey = dbCollectionGroupKey(collectionGroup, offset); + const endKey = dbCollectionGroupKey(collectionGroup, IndexOffset.max()); + return remoteDocumentsStore(transaction) + .iterate({ + index: DbRemoteDocumentCollectionGroupIndex, + range: IDBKeyRange.bound(startKey, endKey, true) + }, (_, dbRemoteDoc, control) => { + const document = this.maybeDecodeDocument(DocumentKey.fromSegments(dbRemoteDoc.prefixPath.concat(dbRemoteDoc.collectionGroup, dbRemoteDoc.documentId)), dbRemoteDoc); + results = results.insert(document.key, document); + if (results.size === limit) { + control.done(); + } + }) + .next(() => results); + } + newChangeBuffer(options) { + return new IndexedDbRemoteDocumentChangeBuffer(this, !!options && options.trackRemovals); + } + getSize(txn) { + return this.getMetadata(txn).next(metadata => metadata.byteSize); + } + getMetadata(txn) { + return documentGlobalStore(txn) + .get(DbRemoteDocumentGlobalKey) + .next(metadata => { + hardAssert(!!metadata, 0x4e35); + return metadata; + }); + } + setMetadata(txn, metadata) { + return documentGlobalStore(txn).put(DbRemoteDocumentGlobalKey, metadata); + } + /** + * Decodes `dbRemoteDoc` and returns the document (or an invalid document if + * the document corresponds to the format used for sentinel deletes). + */ + maybeDecodeDocument(documentKey, dbRemoteDoc) { + if (dbRemoteDoc) { + const doc = fromDbRemoteDocument(this.serializer, dbRemoteDoc); + // Whether the document is a sentinel removal and should only be used in the + // `getNewDocumentChanges()` + const isSentinelRemoval = doc.isNoDocument() && doc.version.isEqual(SnapshotVersion.min()); + if (!isSentinelRemoval) { + return doc; + } + } + return MutableDocument.newInvalidDocument(documentKey); + } +} +/** Creates a new IndexedDbRemoteDocumentCache. */ +function newIndexedDbRemoteDocumentCache(serializer) { + return new IndexedDbRemoteDocumentCacheImpl(serializer); +} +/** + * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache. + * + * Unlike the MemoryRemoteDocumentChangeBuffer, the IndexedDb implementation computes the size + * delta for all submitted changes. This avoids having to re-read all documents from IndexedDb + * when we apply the changes. + */ +class IndexedDbRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer { + /** + * @param documentCache - The IndexedDbRemoteDocumentCache to apply the changes to. + * @param trackRemovals - Whether to create sentinel deletes that can be tracked by + * `getNewDocumentChanges()`. + */ + constructor(documentCache, trackRemovals) { + super(); + this.documentCache = documentCache; + this.trackRemovals = trackRemovals; + // A map of document sizes and read times prior to applying the changes in + // this buffer. + this.documentStates = new ObjectMap(key => key.toString(), (l, r) => l.isEqual(r)); + } + applyChanges(transaction) { + const promises = []; + let sizeDelta = 0; + let collectionParents = new SortedSet((l, r) => primitiveComparator(l.canonicalString(), r.canonicalString())); + this.changes.forEach((key, documentChange) => { + const previousDoc = this.documentStates.get(key); + promises.push(this.documentCache.removeEntry(transaction, key, previousDoc.readTime)); + if (documentChange.isValidDocument()) { + const doc = toDbRemoteDocument(this.documentCache.serializer, documentChange); + collectionParents = collectionParents.add(key.path.popLast()); + const size = dbDocumentSize(doc); + sizeDelta += size - previousDoc.size; + promises.push(this.documentCache.addEntry(transaction, key, doc)); + } + else { + sizeDelta -= previousDoc.size; + if (this.trackRemovals) { + // In order to track removals, we store a "sentinel delete" in the + // RemoteDocumentCache. This entry is represented by a NoDocument + // with a version of 0 and ignored by `maybeDecodeDocument()` but + // preserved in `getNewDocumentChanges()`. + const deletedDoc = toDbRemoteDocument(this.documentCache.serializer, documentChange.convertToNoDocument(SnapshotVersion.min())); + promises.push(this.documentCache.addEntry(transaction, key, deletedDoc)); + } + } + }); + collectionParents.forEach(parent => { + promises.push(this.documentCache.indexManager.addToCollectionParentIndex(transaction, parent)); + }); + promises.push(this.documentCache.updateMetadata(transaction, sizeDelta)); + return PersistencePromise.waitFor(promises); + } + getFromCache(transaction, documentKey) { + // Record the size of everything we load from the cache so we can compute a delta later. + return this.documentCache + .getSizedEntry(transaction, documentKey) + .next(getResult => { + this.documentStates.set(documentKey, { + size: getResult.size, + readTime: getResult.document.readTime + }); + return getResult.document; + }); + } + getAllFromCache(transaction, documentKeys) { + // Record the size of everything we load from the cache so we can compute + // a delta later. + return this.documentCache + .getSizedEntries(transaction, documentKeys) + .next(({ documents, sizeMap }) => { + // Note: `getAllFromCache` returns two maps instead of a single map from + // keys to `DocumentSizeEntry`s. This is to allow returning the + // `MutableDocumentMap` directly, without a conversion. + sizeMap.forEach((documentKey, size) => { + this.documentStates.set(documentKey, { + size, + readTime: documents.get(documentKey).readTime + }); + }); + return documents; + }); + } +} +function documentGlobalStore(txn) { + return getStore(txn, DbRemoteDocumentGlobalStore); +} +/** + * Helper to get a typed SimpleDbStore for the remoteDocuments object store. + */ +function remoteDocumentsStore(txn) { + return getStore(txn, DbRemoteDocumentStore); +} +/** + * Returns a key that can be used for document lookups on the + * `DbRemoteDocumentDocumentKeyIndex` index. + */ +function dbKey(documentKey) { + const path = documentKey.path.toArray(); + return [ + /* prefix path */ path.slice(0, path.length - 2), + /* collection id */ path[path.length - 2], + /* document id */ path[path.length - 1] + ]; +} +/** + * Returns a key that can be used for document lookups via the primary key of + * the DbRemoteDocument object store. + */ +function dbReadTimeKey(documentKey, readTime) { + const path = documentKey.path.toArray(); + return [ + /* prefix path */ path.slice(0, path.length - 2), + /* collection id */ path[path.length - 2], + toDbTimestampKey(readTime), + /* document id */ path[path.length - 1] + ]; +} +/** + * Returns a key that can be used for document lookups on the + * `DbRemoteDocumentDocumentCollectionGroupIndex` index. + */ +function dbCollectionGroupKey(collectionGroup, offset) { + const path = offset.documentKey.path.toArray(); + return [ + /* collection id */ collectionGroup, + toDbTimestampKey(offset.readTime), + /* prefix path */ path.slice(0, path.length - 2), + /* document id */ path.length > 0 ? path[path.length - 1] : '' + ]; +} +/** + * Comparator that compares document keys according to the primary key sorting + * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id + * and then document ID). + * + * Visible for testing. + */ +function dbKeyComparator(l, r) { + const left = l.path.toArray(); + const right = r.path.toArray(); + // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74 + let cmp = 0; + for (let i = 0; i < left.length - 2 && i < right.length - 2; ++i) { + cmp = primitiveComparator(left[i], right[i]); + if (cmp) { + return cmp; + } + } + cmp = primitiveComparator(left.length, right.length); + if (cmp) { + return cmp; + } + cmp = primitiveComparator(left[left.length - 2], right[right.length - 2]); + if (cmp) { + return cmp; + } + // TODO(b/329441702): Document IDs should be sorted by UTF-8 encoded byte + // order, but IndexedDB sorts strings lexicographically. Document ID + // comparison here still relies on primitive comparison to avoid mismatches + // observed in snapshot listeners with Unicode characters in documentIds + return primitiveComparator(left[left.length - 1], right[right.length - 1]); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Schema Version for the Web client: + * 1. Initial version including Mutation Queue, Query Cache, and Remote + * Document Cache + * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No + * longer required because migration 3 unconditionally clears it. + * 3. Dropped and re-created Query Cache to deal with cache corruption related + * to limbo resolution. Addresses + * https://github.com/firebase/firebase-ios-sdk/issues/1548 + * 4. Multi-Tab Support. + * 5. Removal of held write acks. + * 6. Create document global for tracking document cache size. + * 7. Ensure every cached document has a sentinel row with a sequence number. + * 8. Add collection-parent index for Collection Group queries. + * 9. Change RemoteDocumentChanges store to be keyed by readTime rather than + * an auto-incrementing ID. This is required for Index-Free queries. + * 10. Rewrite the canonical IDs to the explicit Protobuf-based format. + * 11. Add bundles and named_queries for bundle support. + * 12. Add document overlays. + * 13. Rewrite the keys of the remote document cache to allow for efficient + * document lookup via `getAll()`. + * 14. Add overlays. + * 15. Add indexing support. + * 16. Parse timestamp strings before creating index entries. + * 17. TODO(tomandersen) + * 18. Encode key safe representations of IndexEntry in DbIndexEntryStore. + */ +const SCHEMA_VERSION = 18; + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a local view (overlay) of a document, and the fields that are + * locally mutated. + */ +class OverlayedDocument { + constructor(overlayedDocument, + /** + * The fields that are locally mutated by patch mutations. + * + * If the overlayed document is from set or delete mutations, this is `null`. + * If there is no overlay (mutation) for the document, this is an empty `FieldMask`. + */ + mutatedFields) { + this.overlayedDocument = overlayedDocument; + this.mutatedFields = mutatedFields; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A readonly view of the local state of all documents we're tracking (i.e. we + * have a cached version in remoteDocumentCache or local mutations for the + * document). The view is computed by applying the mutations in the + * MutationQueue to the RemoteDocumentCache. + */ +class LocalDocumentsView { + constructor(remoteDocumentCache, mutationQueue, documentOverlayCache, indexManager) { + this.remoteDocumentCache = remoteDocumentCache; + this.mutationQueue = mutationQueue; + this.documentOverlayCache = documentOverlayCache; + this.indexManager = indexManager; + } + /** + * Get the local view of the document identified by `key`. + * + * @returns Local view of the document or null if we don't have any cached + * state for it. + */ + getDocument(transaction, key) { + let overlay = null; + return this.documentOverlayCache + .getOverlay(transaction, key) + .next(value => { + overlay = value; + return this.remoteDocumentCache.getEntry(transaction, key); + }) + .next(document => { + if (overlay !== null) { + mutationApplyToLocalView(overlay.mutation, document, FieldMask.empty(), Timestamp.now()); + } + return document; + }); + } + /** + * Gets the local view of the documents identified by `keys`. + * + * If we don't have cached state for a document in `keys`, a NoDocument will + * be stored for that key in the resulting set. + */ + getDocuments(transaction, keys) { + return this.remoteDocumentCache + .getEntries(transaction, keys) + .next(docs => this.getLocalViewOfDocuments(transaction, docs, documentKeySet()).next(() => docs)); + } + /** + * Similar to `getDocuments`, but creates the local view from the given + * `baseDocs` without retrieving documents from the local store. + * + * @param transaction - The transaction this operation is scoped to. + * @param docs - The documents to apply local mutations to get the local views. + * @param existenceStateChanged - The set of document keys whose existence state + * is changed. This is useful to determine if some documents overlay needs + * to be recalculated. + */ + getLocalViewOfDocuments(transaction, docs, existenceStateChanged = documentKeySet()) { + const overlays = newOverlayMap(); + return this.populateOverlays(transaction, overlays, docs).next(() => { + return this.computeViews(transaction, docs, overlays, existenceStateChanged).next(computeViewsResult => { + let result = documentMap(); + computeViewsResult.forEach((documentKey, overlayedDocument) => { + result = result.insert(documentKey, overlayedDocument.overlayedDocument); + }); + return result; + }); + }); + } + /** + * Gets the overlayed documents for the given document map, which will include + * the local view of those documents and a `FieldMask` indicating which fields + * are mutated locally, `null` if overlay is a Set or Delete mutation. + */ + getOverlayedDocuments(transaction, docs) { + const overlays = newOverlayMap(); + return this.populateOverlays(transaction, overlays, docs).next(() => this.computeViews(transaction, docs, overlays, documentKeySet())); + } + /** + * Fetches the overlays for {@code docs} and adds them to provided overlay map + * if the map does not already contain an entry for the given document key. + */ + populateOverlays(transaction, overlays, docs) { + const missingOverlays = []; + docs.forEach(key => { + if (!overlays.has(key)) { + missingOverlays.push(key); + } + }); + return this.documentOverlayCache + .getOverlays(transaction, missingOverlays) + .next(result => { + result.forEach((key, val) => { + overlays.set(key, val); + }); + }); + } + /** + * Computes the local view for the given documents. + * + * @param docs - The documents to compute views for. It also has the base + * version of the documents. + * @param overlays - The overlays that need to be applied to the given base + * version of the documents. + * @param existenceStateChanged - A set of documents whose existence states + * might have changed. This is used to determine if we need to re-calculate + * overlays from mutation queues. + * @return A map represents the local documents view. + */ + computeViews(transaction, docs, overlays, existenceStateChanged) { + let recalculateDocuments = mutableDocumentMap(); + const mutatedFields = newDocumentKeyMap(); + const results = newOverlayedDocumentMap(); + docs.forEach((_, doc) => { + const overlay = overlays.get(doc.key); + // Recalculate an overlay if the document's existence state changed due to + // a remote event *and* the overlay is a PatchMutation. This is because + // document existence state can change if some patch mutation's + // preconditions are met. + // NOTE: we recalculate when `overlay` is undefined as well, because there + // might be a patch mutation whose precondition does not match before the + // change (hence overlay is undefined), but would now match. + if (existenceStateChanged.has(doc.key) && + (overlay === undefined || overlay.mutation instanceof PatchMutation)) { + recalculateDocuments = recalculateDocuments.insert(doc.key, doc); + } + else if (overlay !== undefined) { + mutatedFields.set(doc.key, overlay.mutation.getFieldMask()); + mutationApplyToLocalView(overlay.mutation, doc, overlay.mutation.getFieldMask(), Timestamp.now()); + } + else { + // no overlay exists + // Using EMPTY to indicate there is no overlay for the document. + mutatedFields.set(doc.key, FieldMask.empty()); + } + }); + return this.recalculateAndSaveOverlays(transaction, recalculateDocuments).next(recalculatedFields => { + recalculatedFields.forEach((documentKey, mask) => mutatedFields.set(documentKey, mask)); + docs.forEach((documentKey, document) => results.set(documentKey, new OverlayedDocument(document, mutatedFields.get(documentKey) ?? null))); + return results; + }); + } + recalculateAndSaveOverlays(transaction, docs) { + const masks = newDocumentKeyMap(); + // A reverse lookup map from batch id to the documents within that batch. + let documentsByBatchId = new SortedMap((key1, key2) => key1 - key2); + let processed = documentKeySet(); + return this.mutationQueue + .getAllMutationBatchesAffectingDocumentKeys(transaction, docs) + .next(batches => { + for (const batch of batches) { + batch.keys().forEach(key => { + const baseDoc = docs.get(key); + if (baseDoc === null) { + return; + } + let mask = masks.get(key) || FieldMask.empty(); + mask = batch.applyToLocalView(baseDoc, mask); + masks.set(key, mask); + const newSet = (documentsByBatchId.get(batch.batchId) || documentKeySet()).add(key); + documentsByBatchId = documentsByBatchId.insert(batch.batchId, newSet); + }); + } + }) + .next(() => { + const promises = []; + // Iterate in descending order of batch IDs, and skip documents that are + // already saved. + const iter = documentsByBatchId.getReverseIterator(); + while (iter.hasNext()) { + const entry = iter.getNext(); + const batchId = entry.key; + const keys = entry.value; + const overlays = newMutationMap(); + keys.forEach(key => { + if (!processed.has(key)) { + const overlayMutation = calculateOverlayMutation(docs.get(key), masks.get(key)); + if (overlayMutation !== null) { + overlays.set(key, overlayMutation); + } + processed = processed.add(key); + } + }); + promises.push(this.documentOverlayCache.saveOverlays(transaction, batchId, overlays)); + } + return PersistencePromise.waitFor(promises); + }) + .next(() => masks); + } + /** + * Recalculates overlays by reading the documents from remote document cache + * first, and saves them after they are calculated. + */ + recalculateAndSaveOverlaysForDocumentKeys(transaction, documentKeys) { + return this.remoteDocumentCache + .getEntries(transaction, documentKeys) + .next(docs => this.recalculateAndSaveOverlays(transaction, docs)); + } + /** + * Performs a query against the local view of all documents. + * + * @param transaction - The persistence transaction. + * @param query - The query to match documents against. + * @param offset - Read time and key to start scanning by (exclusive). + * @param context - A optional tracker to keep a record of important details + * during database local query execution. + */ + getDocumentsMatchingQuery(transaction, query, offset, context) { + if (isDocumentQuery$1(query)) { + return this.getDocumentsMatchingDocumentQuery(transaction, query.path); + } + else if (isCollectionGroupQuery(query)) { + return this.getDocumentsMatchingCollectionGroupQuery(transaction, query, offset, context); + } + else { + return this.getDocumentsMatchingCollectionQuery(transaction, query, offset, context); + } + } + /** + * Given a collection group, returns the next documents that follow the provided offset, along + * with an updated batch ID. + * + *

The documents returned by this method are ordered by remote version from the provided + * offset. If there are no more remote documents after the provided offset, documents with + * mutations in order of batch id from the offset are returned. Since all documents in a batch are + * returned together, the total number of documents returned can exceed {@code count}. + * + * @param transaction + * @param collectionGroup The collection group for the documents. + * @param offset The offset to index into. + * @param count The number of documents to return + * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id. + */ + getNextDocuments(transaction, collectionGroup, offset, count) { + return this.remoteDocumentCache + .getAllFromCollectionGroup(transaction, collectionGroup, offset, count) + .next((originalDocs) => { + const overlaysPromise = count - originalDocs.size > 0 + ? this.documentOverlayCache.getOverlaysForCollectionGroup(transaction, collectionGroup, offset.largestBatchId, count - originalDocs.size) + : PersistencePromise.resolve(newOverlayMap()); + // The callsite will use the largest batch ID together with the latest read time to create + // a new index offset. Since we only process batch IDs if all remote documents have been read, + // no overlay will increase the overall read time. This is why we only need to special case + // the batch id. + let largestBatchId = INITIAL_LARGEST_BATCH_ID; + let modifiedDocs = originalDocs; + return overlaysPromise.next(overlays => { + return PersistencePromise.forEach(overlays, (key, overlay) => { + if (largestBatchId < overlay.largestBatchId) { + largestBatchId = overlay.largestBatchId; + } + if (originalDocs.get(key)) { + return PersistencePromise.resolve(); + } + return this.remoteDocumentCache + .getEntry(transaction, key) + .next(doc => { + modifiedDocs = modifiedDocs.insert(key, doc); + }); + }) + .next(() => this.populateOverlays(transaction, overlays, originalDocs)) + .next(() => this.computeViews(transaction, modifiedDocs, overlays, documentKeySet())) + .next(localDocs => ({ + batchId: largestBatchId, + changes: convertOverlayedDocumentMapToDocumentMap(localDocs) + })); + }); + }); + } + getDocumentsMatchingDocumentQuery(transaction, docPath) { + // Just do a simple document lookup. + return this.getDocument(transaction, new DocumentKey(docPath)).next(document => { + let result = documentMap(); + if (document.isFoundDocument()) { + result = result.insert(document.key, document); + } + return result; + }); + } + getDocumentsMatchingCollectionGroupQuery(transaction, query, offset, context) { + const collectionId = query.collectionGroup; + let results = documentMap(); + return this.indexManager + .getCollectionParents(transaction, collectionId) + .next(parents => { + // Perform a collection query against each parent that contains the + // collectionId and aggregate the results. + return PersistencePromise.forEach(parents, (parent) => { + const collectionQuery = asCollectionQueryAtPath(query, parent.child(collectionId)); + return this.getDocumentsMatchingCollectionQuery(transaction, collectionQuery, offset, context).next(r => { + r.forEach((key, doc) => { + results = results.insert(key, doc); + }); + }); + }).next(() => results); + }); + } + getDocumentsMatchingCollectionQuery(transaction, query, offset, context) { + // Query the remote documents and overlay mutations. + let overlays; + return this.documentOverlayCache + .getOverlaysForCollection(transaction, query.path, offset.largestBatchId) + .next(result => { + overlays = result; + return this.remoteDocumentCache.getDocumentsMatchingQuery(transaction, query, offset, overlays, context); + }) + .next(remoteDocuments => { + // As documents might match the query because of their overlay we need to + // include documents for all overlays in the initial document set. + overlays.forEach((_, overlay) => { + const key = overlay.getKey(); + if (remoteDocuments.get(key) === null) { + remoteDocuments = remoteDocuments.insert(key, MutableDocument.newInvalidDocument(key)); + } + }); + // Apply the overlays and match against the query. + let results = documentMap(); + remoteDocuments.forEach((key, document) => { + const overlay = overlays.get(key); + if (overlay !== undefined) { + mutationApplyToLocalView(overlay.mutation, document, FieldMask.empty(), Timestamp.now()); + } + // Finally, insert the documents that still match the query + if (queryMatches(query, document)) { + results = results.insert(key, document); + } + }); + return results; + }); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class MemoryBundleCache { + constructor(serializer) { + this.serializer = serializer; + this.bundles = new Map(); + this.namedQueries = new Map(); + } + getBundleMetadata(transaction, bundleId) { + return PersistencePromise.resolve(this.bundles.get(bundleId)); + } + saveBundleMetadata(transaction, bundleMetadata) { + this.bundles.set(bundleMetadata.id, fromBundleMetadata(bundleMetadata)); + return PersistencePromise.resolve(); + } + getNamedQuery(transaction, queryName) { + return PersistencePromise.resolve(this.namedQueries.get(queryName)); + } + saveNamedQuery(transaction, query) { + this.namedQueries.set(query.name, fromProtoNamedQuery(query)); + return PersistencePromise.resolve(); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An in-memory implementation of DocumentOverlayCache. + */ +class MemoryDocumentOverlayCache { + constructor() { + // A map sorted by DocumentKey, whose value is a pair of the largest batch id + // for the overlay and the overlay itself. + this.overlays = new SortedMap(DocumentKey.comparator); + this.overlayByBatchId = new Map(); + } + getOverlay(transaction, key) { + return PersistencePromise.resolve(this.overlays.get(key)); + } + getOverlays(transaction, keys) { + const result = newOverlayMap(); + return PersistencePromise.forEach(keys, (key) => { + return this.getOverlay(transaction, key).next(overlay => { + if (overlay !== null) { + result.set(key, overlay); + } + }); + }).next(() => result); + } + saveOverlays(transaction, largestBatchId, overlays) { + overlays.forEach((_, mutation) => { + this.saveOverlay(transaction, largestBatchId, mutation); + }); + return PersistencePromise.resolve(); + } + removeOverlaysForBatchId(transaction, documentKeys, batchId) { + const keys = this.overlayByBatchId.get(batchId); + if (keys !== undefined) { + keys.forEach(key => (this.overlays = this.overlays.remove(key))); + this.overlayByBatchId.delete(batchId); + } + return PersistencePromise.resolve(); + } + getOverlaysForCollection(transaction, collection, sinceBatchId) { + const result = newOverlayMap(); + const immediateChildrenPathLength = collection.length + 1; + const prefix = new DocumentKey(collection.child('')); + const iter = this.overlays.getIteratorFrom(prefix); + while (iter.hasNext()) { + const entry = iter.getNext(); + const overlay = entry.value; + const key = overlay.getKey(); + if (!collection.isPrefixOf(key.path)) { + break; + } + // Documents from sub-collections + if (key.path.length !== immediateChildrenPathLength) { + continue; + } + if (overlay.largestBatchId > sinceBatchId) { + result.set(overlay.getKey(), overlay); + } + } + return PersistencePromise.resolve(result); + } + getOverlaysForCollectionGroup(transaction, collectionGroup, sinceBatchId, count) { + let batchIdToOverlays = new SortedMap((key1, key2) => key1 - key2); + const iter = this.overlays.getIterator(); + while (iter.hasNext()) { + const entry = iter.getNext(); + const overlay = entry.value; + const key = overlay.getKey(); + if (key.getCollectionGroup() !== collectionGroup) { + continue; + } + if (overlay.largestBatchId > sinceBatchId) { + let overlaysForBatchId = batchIdToOverlays.get(overlay.largestBatchId); + if (overlaysForBatchId === null) { + overlaysForBatchId = newOverlayMap(); + batchIdToOverlays = batchIdToOverlays.insert(overlay.largestBatchId, overlaysForBatchId); + } + overlaysForBatchId.set(overlay.getKey(), overlay); + } + } + const result = newOverlayMap(); + const batchIter = batchIdToOverlays.getIterator(); + while (batchIter.hasNext()) { + const entry = batchIter.getNext(); + const overlays = entry.value; + overlays.forEach((key, overlay) => result.set(key, overlay)); + if (result.size() >= count) { + break; + } + } + return PersistencePromise.resolve(result); + } + saveOverlay(transaction, largestBatchId, mutation) { + // Remove the association of the overlay to its batch id. + const existing = this.overlays.get(mutation.key); + if (existing !== null) { + const newSet = this.overlayByBatchId + .get(existing.largestBatchId) + .delete(mutation.key); + this.overlayByBatchId.set(existing.largestBatchId, newSet); + } + this.overlays = this.overlays.insert(mutation.key, new Overlay(largestBatchId, mutation)); + // Create the association of this overlay to the given largestBatchId. + let batch = this.overlayByBatchId.get(largestBatchId); + if (batch === undefined) { + batch = documentKeySet(); + this.overlayByBatchId.set(largestBatchId, batch); + } + this.overlayByBatchId.set(largestBatchId, batch.add(mutation.key)); + } +} + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class MemoryGlobalsCache { + constructor() { + this.sessionToken = ByteString.EMPTY_BYTE_STRING; + } + getSessionToken(transaction) { + return PersistencePromise.resolve(this.sessionToken); + } + setSessionToken(transaction, sessionToken) { + this.sessionToken = sessionToken; + return PersistencePromise.resolve(); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A collection of references to a document from some kind of numbered entity + * (either a target ID or batch ID). As references are added to or removed from + * the set corresponding events are emitted to a registered garbage collector. + * + * Each reference is represented by a DocumentReference object. Each of them + * contains enough information to uniquely identify the reference. They are all + * stored primarily in a set sorted by key. A document is considered garbage if + * there's no references in that set (this can be efficiently checked thanks to + * sorting by key). + * + * ReferenceSet also keeps a secondary set that contains references sorted by + * IDs. This one is used to efficiently implement removal of all references by + * some target ID. + */ +class ReferenceSet { + constructor() { + // A set of outstanding references to a document sorted by key. + this.refsByKey = new SortedSet(DocReference.compareByKey); + // A set of outstanding references to a document sorted by target id. + this.refsByTarget = new SortedSet(DocReference.compareByTargetId); + } + /** Returns true if the reference set contains no references. */ + isEmpty() { + return this.refsByKey.isEmpty(); + } + /** Adds a reference to the given document key for the given ID. */ + addReference(key, id) { + const ref = new DocReference(key, id); + this.refsByKey = this.refsByKey.add(ref); + this.refsByTarget = this.refsByTarget.add(ref); + } + /** Add references to the given document keys for the given ID. */ + addReferences(keys, id) { + keys.forEach(key => this.addReference(key, id)); + } + /** + * Removes a reference to the given document key for the given + * ID. + */ + removeReference(key, id) { + this.removeRef(new DocReference(key, id)); + } + removeReferences(keys, id) { + keys.forEach(key => this.removeReference(key, id)); + } + /** + * Clears all references with a given ID. Calls removeRef() for each key + * removed. + */ + removeReferencesForId(id) { + const emptyKey = new DocumentKey(new ResourcePath([])); + const startRef = new DocReference(emptyKey, id); + const endRef = new DocReference(emptyKey, id + 1); + const keys = []; + this.refsByTarget.forEachInRange([startRef, endRef], ref => { + this.removeRef(ref); + keys.push(ref.key); + }); + return keys; + } + removeAllReferences() { + this.refsByKey.forEach(ref => this.removeRef(ref)); + } + removeRef(ref) { + this.refsByKey = this.refsByKey.delete(ref); + this.refsByTarget = this.refsByTarget.delete(ref); + } + referencesForId(id) { + const emptyKey = new DocumentKey(new ResourcePath([])); + const startRef = new DocReference(emptyKey, id); + const endRef = new DocReference(emptyKey, id + 1); + let keys = documentKeySet(); + this.refsByTarget.forEachInRange([startRef, endRef], ref => { + keys = keys.add(ref.key); + }); + return keys; + } + containsKey(key) { + const ref = new DocReference(key, 0); + const firstRef = this.refsByKey.firstAfterOrEqual(ref); + return firstRef !== null && key.isEqual(firstRef.key); + } +} +class DocReference { + constructor(key, targetOrBatchId) { + this.key = key; + this.targetOrBatchId = targetOrBatchId; + } + /** Compare by key then by ID */ + static compareByKey(left, right) { + return (DocumentKey.comparator(left.key, right.key) || + primitiveComparator(left.targetOrBatchId, right.targetOrBatchId)); + } + /** Compare by ID then by key */ + static compareByTargetId(left, right) { + return (primitiveComparator(left.targetOrBatchId, right.targetOrBatchId) || + DocumentKey.comparator(left.key, right.key)); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class MemoryMutationQueue { + constructor(indexManager, referenceDelegate) { + this.indexManager = indexManager; + this.referenceDelegate = referenceDelegate; + /** + * The set of all mutations that have been sent but not yet been applied to + * the backend. + */ + this.mutationQueue = []; + /** Next value to use when assigning sequential IDs to each mutation batch. */ + this.nextBatchId = 1; + /** An ordered mapping between documents and the mutations batch IDs. */ + this.batchesByDocumentKey = new SortedSet(DocReference.compareByKey); + } + checkEmpty(transaction) { + return PersistencePromise.resolve(this.mutationQueue.length === 0); + } + addMutationBatch(transaction, localWriteTime, baseMutations, mutations) { + const batchId = this.nextBatchId; + this.nextBatchId++; + if (this.mutationQueue.length > 0) { + this.mutationQueue[this.mutationQueue.length - 1]; + } + const batch = new MutationBatch(batchId, localWriteTime, baseMutations, mutations); + this.mutationQueue.push(batch); + // Track references by document key and index collection parents. + for (const mutation of mutations) { + this.batchesByDocumentKey = this.batchesByDocumentKey.add(new DocReference(mutation.key, batchId)); + this.indexManager.addToCollectionParentIndex(transaction, mutation.key.path.popLast()); + } + return PersistencePromise.resolve(batch); + } + lookupMutationBatch(transaction, batchId) { + return PersistencePromise.resolve(this.findMutationBatch(batchId)); + } + getNextMutationBatchAfterBatchId(transaction, batchId) { + const nextBatchId = batchId + 1; + // The requested batchId may still be out of range so normalize it to the + // start of the queue. + const rawIndex = this.indexOfBatchId(nextBatchId); + const index = rawIndex < 0 ? 0 : rawIndex; + return PersistencePromise.resolve(this.mutationQueue.length > index ? this.mutationQueue[index] : null); + } + getHighestUnacknowledgedBatchId() { + return PersistencePromise.resolve(this.mutationQueue.length === 0 ? BATCHID_UNKNOWN : this.nextBatchId - 1); + } + getAllMutationBatches(transaction) { + return PersistencePromise.resolve(this.mutationQueue.slice()); + } + getAllMutationBatchesAffectingDocumentKey(transaction, documentKey) { + const start = new DocReference(documentKey, 0); + const end = new DocReference(documentKey, Number.POSITIVE_INFINITY); + const result = []; + this.batchesByDocumentKey.forEachInRange([start, end], ref => { + const batch = this.findMutationBatch(ref.targetOrBatchId); + result.push(batch); + }); + return PersistencePromise.resolve(result); + } + getAllMutationBatchesAffectingDocumentKeys(transaction, documentKeys) { + let uniqueBatchIDs = new SortedSet(primitiveComparator); + documentKeys.forEach(documentKey => { + const start = new DocReference(documentKey, 0); + const end = new DocReference(documentKey, Number.POSITIVE_INFINITY); + this.batchesByDocumentKey.forEachInRange([start, end], ref => { + uniqueBatchIDs = uniqueBatchIDs.add(ref.targetOrBatchId); + }); + }); + return PersistencePromise.resolve(this.findMutationBatches(uniqueBatchIDs)); + } + getAllMutationBatchesAffectingQuery(transaction, query) { + // Use the query path as a prefix for testing if a document matches the + // query. + const prefix = query.path; + const immediateChildrenPathLength = prefix.length + 1; + // Construct a document reference for actually scanning the index. Unlike + // the prefix the document key in this reference must have an even number of + // segments. The empty segment can be used a suffix of the query path + // because it precedes all other segments in an ordered traversal. + let startPath = prefix; + if (!DocumentKey.isDocumentKey(startPath)) { + startPath = startPath.child(''); + } + const start = new DocReference(new DocumentKey(startPath), 0); + // Find unique batchIDs referenced by all documents potentially matching the + // query. + let uniqueBatchIDs = new SortedSet(primitiveComparator); + this.batchesByDocumentKey.forEachWhile(ref => { + const rowKeyPath = ref.key.path; + if (!prefix.isPrefixOf(rowKeyPath)) { + return false; + } + else { + // Rows with document keys more than one segment longer than the query + // path can't be matches. For example, a query on 'rooms' can't match + // the document /rooms/abc/messages/xyx. + // TODO(mcg): we'll need a different scanner when we implement + // ancestor queries. + if (rowKeyPath.length === immediateChildrenPathLength) { + uniqueBatchIDs = uniqueBatchIDs.add(ref.targetOrBatchId); + } + return true; + } + }, start); + return PersistencePromise.resolve(this.findMutationBatches(uniqueBatchIDs)); + } + findMutationBatches(batchIDs) { + // Construct an array of matching batches, sorted by batchID to ensure that + // multiple mutations affecting the same document key are applied in order. + const result = []; + batchIDs.forEach(batchId => { + const batch = this.findMutationBatch(batchId); + if (batch !== null) { + result.push(batch); + } + }); + return result; + } + removeMutationBatch(transaction, batch) { + // Find the position of the first batch for removal. + const batchIndex = this.indexOfExistingBatchId(batch.batchId, 'removed'); + hardAssert(batchIndex === 0, 0xd6db); + this.mutationQueue.shift(); + let references = this.batchesByDocumentKey; + return PersistencePromise.forEach(batch.mutations, (mutation) => { + const ref = new DocReference(mutation.key, batch.batchId); + references = references.delete(ref); + return this.referenceDelegate.markPotentiallyOrphaned(transaction, mutation.key); + }).next(() => { + this.batchesByDocumentKey = references; + }); + } + removeCachedMutationKeys(batchId) { + // No-op since the memory mutation queue does not maintain a separate cache. + } + containsKey(txn, key) { + const ref = new DocReference(key, 0); + const firstRef = this.batchesByDocumentKey.firstAfterOrEqual(ref); + return PersistencePromise.resolve(key.isEqual(firstRef && firstRef.key)); + } + performConsistencyCheck(txn) { + if (this.mutationQueue.length === 0) ; + return PersistencePromise.resolve(); + } + /** + * Finds the index of the given batchId in the mutation queue and asserts that + * the resulting index is within the bounds of the queue. + * + * @param batchId - The batchId to search for + * @param action - A description of what the caller is doing, phrased in passive + * form (e.g. "acknowledged" in a routine that acknowledges batches). + */ + indexOfExistingBatchId(batchId, action) { + const index = this.indexOfBatchId(batchId); + return index; + } + /** + * Finds the index of the given batchId in the mutation queue. This operation + * is O(1). + * + * @returns The computed index of the batch with the given batchId, based on + * the state of the queue. Note this index can be negative if the requested + * batchId has already been removed from the queue or past the end of the + * queue if the batchId is larger than the last added batch. + */ + indexOfBatchId(batchId) { + if (this.mutationQueue.length === 0) { + // As an index this is past the end of the queue + return 0; + } + // Examine the front of the queue to figure out the difference between the + // batchId and indexes in the array. Note that since the queue is ordered + // by batchId, if the first batch has a larger batchId then the requested + // batchId doesn't exist in the queue. + const firstBatchId = this.mutationQueue[0].batchId; + return batchId - firstBatchId; + } + /** + * A version of lookupMutationBatch that doesn't return a promise, this makes + * other functions that uses this code easier to read and more efficient. + */ + findMutationBatch(batchId) { + const index = this.indexOfBatchId(batchId); + if (index < 0 || index >= this.mutationQueue.length) { + return null; + } + const batch = this.mutationQueue[index]; + return batch; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The smallest value representable by a 64-bit signed integer (long). + */ +const MIN_LONG_VALUE = '-9223372036854775808'; +function documentEntryMap() { + return new SortedMap(DocumentKey.comparator); +} +/** + * The memory-only RemoteDocumentCache for IndexedDb. To construct, invoke + * `newMemoryRemoteDocumentCache()`. + */ +class MemoryRemoteDocumentCacheImpl { + /** + * @param sizer - Used to assess the size of a document. For eager GC, this is + * expected to just return 0 to avoid unnecessarily doing the work of + * calculating the size. + */ + constructor(sizer) { + this.sizer = sizer; + /** Underlying cache of documents and their read times. */ + this.docs = documentEntryMap(); + /** Size of all cached documents. */ + this.size = 0; + } + setIndexManager(indexManager) { + this.indexManager = indexManager; + } + /** + * Adds the supplied entry to the cache and updates the cache size as appropriate. + * + * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer + * returned by `newChangeBuffer()`. + */ + addEntry(transaction, doc) { + const key = doc.key; + const entry = this.docs.get(key); + const previousSize = entry ? entry.size : 0; + const currentSize = this.sizer(doc); + this.docs = this.docs.insert(key, { + document: doc.mutableCopy(), + size: currentSize + }); + this.size += currentSize - previousSize; + return this.indexManager.addToCollectionParentIndex(transaction, key.path.popLast()); + } + /** + * Removes the specified entry from the cache and updates the cache size as appropriate. + * + * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer + * returned by `newChangeBuffer()`. + */ + removeEntry(documentKey) { + const entry = this.docs.get(documentKey); + if (entry) { + this.docs = this.docs.remove(documentKey); + this.size -= entry.size; + } + } + getEntry(transaction, documentKey) { + const entry = this.docs.get(documentKey); + return PersistencePromise.resolve(entry + ? entry.document.mutableCopy() + : MutableDocument.newInvalidDocument(documentKey)); + } + getEntries(transaction, documentKeys) { + let results = mutableDocumentMap(); + documentKeys.forEach(documentKey => { + const entry = this.docs.get(documentKey); + results = results.insert(documentKey, entry + ? entry.document.mutableCopy() + : MutableDocument.newInvalidDocument(documentKey)); + }); + return PersistencePromise.resolve(results); + } + getDocumentsMatchingQuery(transaction, query, offset, mutatedDocs) { + let results = mutableDocumentMap(); + // Documents are ordered by key, so we can use a prefix scan to narrow down + // the documents we need to match the query against. + const collectionPath = query.path; + // Document keys are ordered first by numeric value ("__id__"), + // then lexicographically by string value. Start the iterator at the minimum + // possible Document key value. + const prefix = new DocumentKey(collectionPath.child('__id' + MIN_LONG_VALUE + '__')); + const iterator = this.docs.getIteratorFrom(prefix); + while (iterator.hasNext()) { + const { key, value: { document } } = iterator.getNext(); + if (!collectionPath.isPrefixOf(key.path)) { + break; + } + if (key.path.length > collectionPath.length + 1) { + // Exclude entries from subcollections. + continue; + } + if (indexOffsetComparator(newIndexOffsetFromDocument(document), offset) <= 0) { + // The document sorts before the offset. + continue; + } + if (!mutatedDocs.has(document.key) && !queryMatches(query, document)) { + // The document cannot possibly match the query. + continue; + } + results = results.insert(document.key, document.mutableCopy()); + } + return PersistencePromise.resolve(results); + } + getAllFromCollectionGroup(transaction, collectionGroup, offset, limit) { + // This method should only be called from the IndexBackfiller if persistence + // is enabled. + fail(0x251c); + } + forEachDocumentKey(transaction, f) { + return PersistencePromise.forEach(this.docs, (key) => f(key)); + } + newChangeBuffer(options) { + // `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps + // a separate changelog and does not need special handling for removals. + return new MemoryRemoteDocumentChangeBuffer(this); + } + getSize(txn) { + return PersistencePromise.resolve(this.size); + } +} +/** + * Creates a new memory-only RemoteDocumentCache. + * + * @param sizer - Used to assess the size of a document. For eager GC, this is + * expected to just return 0 to avoid unnecessarily doing the work of + * calculating the size. + */ +function newMemoryRemoteDocumentCache(sizer) { + return new MemoryRemoteDocumentCacheImpl(sizer); +} +/** + * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache. + */ +class MemoryRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer { + constructor(documentCache) { + super(); + this.documentCache = documentCache; + } + applyChanges(transaction) { + const promises = []; + this.changes.forEach((key, doc) => { + if (doc.isValidDocument()) { + promises.push(this.documentCache.addEntry(transaction, doc)); + } + else { + this.documentCache.removeEntry(key); + } + }); + return PersistencePromise.waitFor(promises); + } + getFromCache(transaction, documentKey) { + return this.documentCache.getEntry(transaction, documentKey); + } + getAllFromCache(transaction, documentKeys) { + return this.documentCache.getEntries(transaction, documentKeys); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class MemoryTargetCache { + constructor(persistence) { + this.persistence = persistence; + /** + * Maps a target to the data about that target + */ + this.targets = new ObjectMap(t => canonifyTarget(t), targetEquals); + /** The last received snapshot version. */ + this.lastRemoteSnapshotVersion = SnapshotVersion.min(); + /** The highest numbered target ID encountered. */ + this.highestTargetId = 0; + /** The highest sequence number encountered. */ + this.highestSequenceNumber = 0; + /** + * A ordered bidirectional mapping between documents and the remote target + * IDs. + */ + this.references = new ReferenceSet(); + this.targetCount = 0; + this.targetIdGenerator = TargetIdGenerator.forTargetCache(); + } + forEachTarget(txn, f) { + this.targets.forEach((_, targetData) => f(targetData)); + return PersistencePromise.resolve(); + } + getLastRemoteSnapshotVersion(transaction) { + return PersistencePromise.resolve(this.lastRemoteSnapshotVersion); + } + getHighestSequenceNumber(transaction) { + return PersistencePromise.resolve(this.highestSequenceNumber); + } + allocateTargetId(transaction) { + this.highestTargetId = this.targetIdGenerator.next(); + return PersistencePromise.resolve(this.highestTargetId); + } + setTargetsMetadata(transaction, highestListenSequenceNumber, lastRemoteSnapshotVersion) { + if (lastRemoteSnapshotVersion) { + this.lastRemoteSnapshotVersion = lastRemoteSnapshotVersion; + } + if (highestListenSequenceNumber > this.highestSequenceNumber) { + this.highestSequenceNumber = highestListenSequenceNumber; + } + return PersistencePromise.resolve(); + } + saveTargetData(targetData) { + this.targets.set(targetData.target, targetData); + const targetId = targetData.targetId; + if (targetId > this.highestTargetId) { + this.targetIdGenerator = new TargetIdGenerator(targetId); + this.highestTargetId = targetId; + } + if (targetData.sequenceNumber > this.highestSequenceNumber) { + this.highestSequenceNumber = targetData.sequenceNumber; + } + } + addTargetData(transaction, targetData) { + this.saveTargetData(targetData); + this.targetCount += 1; + return PersistencePromise.resolve(); + } + updateTargetData(transaction, targetData) { + this.saveTargetData(targetData); + return PersistencePromise.resolve(); + } + removeTargetData(transaction, targetData) { + this.targets.delete(targetData.target); + this.references.removeReferencesForId(targetData.targetId); + this.targetCount -= 1; + return PersistencePromise.resolve(); + } + removeTargets(transaction, upperBound, activeTargetIds) { + let count = 0; + const removals = []; + this.targets.forEach((key, targetData) => { + if (targetData.sequenceNumber <= upperBound && + activeTargetIds.get(targetData.targetId) === null) { + this.targets.delete(key); + removals.push(this.removeMatchingKeysForTargetId(transaction, targetData.targetId)); + count++; + } + }); + return PersistencePromise.waitFor(removals).next(() => count); + } + getTargetCount(transaction) { + return PersistencePromise.resolve(this.targetCount); + } + getTargetData(transaction, target) { + const targetData = this.targets.get(target) || null; + return PersistencePromise.resolve(targetData); + } + addMatchingKeys(txn, keys, targetId) { + this.references.addReferences(keys, targetId); + return PersistencePromise.resolve(); + } + removeMatchingKeys(txn, keys, targetId) { + this.references.removeReferences(keys, targetId); + const referenceDelegate = this.persistence.referenceDelegate; + const promises = []; + if (referenceDelegate) { + keys.forEach(key => { + promises.push(referenceDelegate.markPotentiallyOrphaned(txn, key)); + }); + } + return PersistencePromise.waitFor(promises); + } + removeMatchingKeysForTargetId(txn, targetId) { + this.references.removeReferencesForId(targetId); + return PersistencePromise.resolve(); + } + getMatchingKeysForTargetId(txn, targetId) { + const matchingKeys = this.references.referencesForId(targetId); + return PersistencePromise.resolve(matchingKeys); + } + containsKey(txn, key) { + return PersistencePromise.resolve(this.references.containsKey(key)); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$d = 'MemoryPersistence'; +/** + * A memory-backed instance of Persistence. Data is stored only in RAM and + * not persisted across sessions. + */ +class MemoryPersistence { + /** + * The constructor accepts a factory for creating a reference delegate. This + * allows both the delegate and this instance to have strong references to + * each other without having nullable fields that would then need to be + * checked or asserted on every access. + */ + constructor(referenceDelegateFactory, serializer) { + this.mutationQueues = {}; + this.overlays = {}; + this.listenSequence = new ListenSequence(0); + this._started = false; + this._started = true; + this.globalsCache = new MemoryGlobalsCache(); + this.referenceDelegate = referenceDelegateFactory(this); + this.targetCache = new MemoryTargetCache(this); + const sizer = (doc) => this.referenceDelegate.documentSize(doc); + this.indexManager = new MemoryIndexManager(); + this.remoteDocumentCache = newMemoryRemoteDocumentCache(sizer); + this.serializer = new LocalSerializer(serializer); + this.bundleCache = new MemoryBundleCache(this.serializer); + } + start() { + return Promise.resolve(); + } + shutdown() { + // No durable state to ensure is closed on shutdown. + this._started = false; + return Promise.resolve(); + } + get started() { + return this._started; + } + setDatabaseDeletedListener() { + // No op. + } + setNetworkEnabled() { + // No op. + } + getIndexManager(user) { + // We do not currently support indices for memory persistence, so we can + // return the same shared instance of the memory index manager. + return this.indexManager; + } + getDocumentOverlayCache(user) { + let overlay = this.overlays[user.toKey()]; + if (!overlay) { + overlay = new MemoryDocumentOverlayCache(); + this.overlays[user.toKey()] = overlay; + } + return overlay; + } + getMutationQueue(user, indexManager) { + let queue = this.mutationQueues[user.toKey()]; + if (!queue) { + queue = new MemoryMutationQueue(indexManager, this.referenceDelegate); + this.mutationQueues[user.toKey()] = queue; + } + return queue; + } + getGlobalsCache() { + return this.globalsCache; + } + getTargetCache() { + return this.targetCache; + } + getRemoteDocumentCache() { + return this.remoteDocumentCache; + } + getBundleCache() { + return this.bundleCache; + } + runTransaction(action, mode, transactionOperation) { + logDebug(LOG_TAG$d, 'Starting transaction:', action); + const txn = new MemoryTransaction(this.listenSequence.next()); + this.referenceDelegate.onTransactionStarted(); + return transactionOperation(txn) + .next(result => { + return this.referenceDelegate + .onTransactionCommitted(txn) + .next(() => result); + }) + .toPromise() + .then(result => { + txn.raiseOnCommittedEvent(); + return result; + }); + } + mutationQueuesContainKey(transaction, key) { + return PersistencePromise.or(Object.values(this.mutationQueues).map(queue => () => queue.containsKey(transaction, key))); + } +} +/** + * Memory persistence is not actually transactional, but future implementations + * may have transaction-scoped state. + */ +class MemoryTransaction extends PersistenceTransaction { + constructor(currentSequenceNumber) { + super(); + this.currentSequenceNumber = currentSequenceNumber; + } +} +class MemoryEagerDelegate { + constructor(persistence) { + this.persistence = persistence; + /** Tracks all documents that are active in Query views. */ + this.localViewReferences = new ReferenceSet(); + /** The list of documents that are potentially GCed after each transaction. */ + this._orphanedDocuments = null; + } + static factory(persistence) { + return new MemoryEagerDelegate(persistence); + } + get orphanedDocuments() { + if (!this._orphanedDocuments) { + throw fail(0xee44); + } + else { + return this._orphanedDocuments; + } + } + addReference(txn, targetId, key) { + this.localViewReferences.addReference(key, targetId); + this.orphanedDocuments.delete(key.toString()); + return PersistencePromise.resolve(); + } + removeReference(txn, targetId, key) { + this.localViewReferences.removeReference(key, targetId); + this.orphanedDocuments.add(key.toString()); + return PersistencePromise.resolve(); + } + markPotentiallyOrphaned(txn, key) { + this.orphanedDocuments.add(key.toString()); + return PersistencePromise.resolve(); + } + removeTarget(txn, targetData) { + const orphaned = this.localViewReferences.removeReferencesForId(targetData.targetId); + orphaned.forEach(key => this.orphanedDocuments.add(key.toString())); + const cache = this.persistence.getTargetCache(); + return cache + .getMatchingKeysForTargetId(txn, targetData.targetId) + .next(keys => { + keys.forEach(key => this.orphanedDocuments.add(key.toString())); + }) + .next(() => cache.removeTargetData(txn, targetData)); + } + onTransactionStarted() { + this._orphanedDocuments = new Set(); + } + onTransactionCommitted(txn) { + // Remove newly orphaned documents. + const cache = this.persistence.getRemoteDocumentCache(); + const changeBuffer = cache.newChangeBuffer(); + return PersistencePromise.forEach(this.orphanedDocuments, (path) => { + const key = DocumentKey.fromPath(path); + return this.isReferenced(txn, key).next(isReferenced => { + if (!isReferenced) { + changeBuffer.removeEntry(key, SnapshotVersion.min()); + } + }); + }).next(() => { + this._orphanedDocuments = null; + return changeBuffer.apply(txn); + }); + } + updateLimboDocument(txn, key) { + return this.isReferenced(txn, key).next(isReferenced => { + if (isReferenced) { + this.orphanedDocuments.delete(key.toString()); + } + else { + this.orphanedDocuments.add(key.toString()); + } + }); + } + documentSize(doc) { + // For eager GC, we don't care about the document size, there are no size thresholds. + return 0; + } + isReferenced(txn, key) { + return PersistencePromise.or([ + () => PersistencePromise.resolve(this.localViewReferences.containsKey(key)), + () => this.persistence.getTargetCache().containsKey(txn, key), + () => this.persistence.mutationQueuesContainKey(txn, key) + ]); + } +} +class MemoryLruDelegate { + constructor(persistence, lruParams) { + this.persistence = persistence; + this.orphanedSequenceNumbers = new ObjectMap(k => encodeResourcePath(k.path), (l, r) => l.isEqual(r)); + this.garbageCollector = newLruGarbageCollector(this, lruParams); + } + static factory(persistence, lruParams) { + return new MemoryLruDelegate(persistence, lruParams); + } + // No-ops, present so memory persistence doesn't have to care which delegate + // it has. + onTransactionStarted() { } + onTransactionCommitted(txn) { + return PersistencePromise.resolve(); + } + forEachTarget(txn, f) { + return this.persistence.getTargetCache().forEachTarget(txn, f); + } + getSequenceNumberCount(txn) { + const docCountPromise = this.orphanedDocumentCount(txn); + const targetCountPromise = this.persistence + .getTargetCache() + .getTargetCount(txn); + return targetCountPromise.next(targetCount => docCountPromise.next(docCount => targetCount + docCount)); + } + orphanedDocumentCount(txn) { + let orphanedCount = 0; + return this.forEachOrphanedDocumentSequenceNumber(txn, _ => { + orphanedCount++; + }).next(() => orphanedCount); + } + forEachOrphanedDocumentSequenceNumber(txn, f) { + return PersistencePromise.forEach(this.orphanedSequenceNumbers, (key, sequenceNumber) => { + // Pass in the exact sequence number as the upper bound so we know it won't be pinned by + // being too recent. + return this.isPinned(txn, key, sequenceNumber).next(isPinned => { + if (!isPinned) { + return f(sequenceNumber); + } + else { + return PersistencePromise.resolve(); + } + }); + }); + } + removeTargets(txn, upperBound, activeTargetIds) { + return this.persistence + .getTargetCache() + .removeTargets(txn, upperBound, activeTargetIds); + } + removeOrphanedDocuments(txn, upperBound) { + let count = 0; + const cache = this.persistence.getRemoteDocumentCache(); + const changeBuffer = cache.newChangeBuffer(); + const p = cache.forEachDocumentKey(txn, key => { + return this.isPinned(txn, key, upperBound).next(isPinned => { + if (!isPinned) { + count++; + changeBuffer.removeEntry(key, SnapshotVersion.min()); + } + }); + }); + return p.next(() => changeBuffer.apply(txn)).next(() => count); + } + markPotentiallyOrphaned(txn, key) { + this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber); + return PersistencePromise.resolve(); + } + removeTarget(txn, targetData) { + const updated = targetData.withSequenceNumber(txn.currentSequenceNumber); + return this.persistence.getTargetCache().updateTargetData(txn, updated); + } + addReference(txn, targetId, key) { + this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber); + return PersistencePromise.resolve(); + } + removeReference(txn, targetId, key) { + this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber); + return PersistencePromise.resolve(); + } + updateLimboDocument(txn, key) { + this.orphanedSequenceNumbers.set(key, txn.currentSequenceNumber); + return PersistencePromise.resolve(); + } + documentSize(document) { + let documentSize = document.key.toString().length; + if (document.isFoundDocument()) { + documentSize += estimateByteSize(document.data.value); + } + return documentSize; + } + isPinned(txn, key, upperBound) { + return PersistencePromise.or([ + () => this.persistence.mutationQueuesContainKey(txn, key), + () => this.persistence.getTargetCache().containsKey(txn, key), + () => { + const orphanedAt = this.orphanedSequenceNumbers.get(key); + return PersistencePromise.resolve(orphanedAt !== undefined && orphanedAt > upperBound); + } + ]); + } + getCacheSize(txn) { + return this.persistence.getRemoteDocumentCache().getSize(txn); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Performs database creation and schema upgrades. */ +class SchemaConverter { + constructor(serializer) { + this.serializer = serializer; + } + /** + * Performs database creation and schema upgrades. + * + * Note that in production, this method is only ever used to upgrade the schema + * to SCHEMA_VERSION. Different values of toVersion are only used for testing + * and local feature development. + */ + createOrUpgrade(db, txn, fromVersion, toVersion) { + const simpleDbTransaction = new SimpleDbTransaction('createOrUpgrade', txn); + if (fromVersion < 1 && toVersion >= 1) { + createPrimaryClientStore(db); + createMutationQueue(db); + createQueryCache(db); + createLegacyRemoteDocumentCache(db); + } + // Migration 2 to populate the targetGlobal object no longer needed since + // migration 3 unconditionally clears it. + let p = PersistencePromise.resolve(); + if (fromVersion < 3 && toVersion >= 3) { + // Brand new clients don't need to drop and recreate--only clients that + // potentially have corrupt data. + if (fromVersion !== 0) { + dropQueryCache(db); + createQueryCache(db); + } + p = p.next(() => writeEmptyTargetGlobalEntry(simpleDbTransaction)); + } + if (fromVersion < 4 && toVersion >= 4) { + if (fromVersion !== 0) { + // Schema version 3 uses auto-generated keys to generate globally unique + // mutation batch IDs (this was previously ensured internally by the + // client). To migrate to the new schema, we have to read all mutations + // and write them back out. We preserve the existing batch IDs to guarantee + // consistency with other object stores. Any further mutation batch IDs will + // be auto-generated. + p = p.next(() => upgradeMutationBatchSchemaAndMigrateData(db, simpleDbTransaction)); + } + p = p.next(() => { + createClientMetadataStore(db); + }); + } + if (fromVersion < 5 && toVersion >= 5) { + p = p.next(() => this.removeAcknowledgedMutations(simpleDbTransaction)); + } + if (fromVersion < 6 && toVersion >= 6) { + p = p.next(() => { + createDocumentGlobalStore(db); + return this.addDocumentGlobal(simpleDbTransaction); + }); + } + if (fromVersion < 7 && toVersion >= 7) { + p = p.next(() => this.ensureSequenceNumbers(simpleDbTransaction)); + } + if (fromVersion < 8 && toVersion >= 8) { + p = p.next(() => this.createCollectionParentIndex(db, simpleDbTransaction)); + } + if (fromVersion < 9 && toVersion >= 9) { + p = p.next(() => { + // Multi-Tab used to manage its own changelog, but this has been moved + // to the DbRemoteDocument object store itself. Since the previous change + // log only contained transient data, we can drop its object store. + dropRemoteDocumentChangesStore(db); + // Note: Schema version 9 used to create a read time index for the + // RemoteDocumentCache. This is now done with schema version 13. + }); + } + if (fromVersion < 10 && toVersion >= 10) { + p = p.next(() => this.rewriteCanonicalIds(simpleDbTransaction)); + } + if (fromVersion < 11 && toVersion >= 11) { + p = p.next(() => { + createBundlesStore(db); + createNamedQueriesStore(db); + }); + } + if (fromVersion < 12 && toVersion >= 12) { + p = p.next(() => { + createDocumentOverlayStore(db); + }); + } + if (fromVersion < 13 && toVersion >= 13) { + p = p + .next(() => createRemoteDocumentCache(db)) + .next(() => this.rewriteRemoteDocumentCache(db, simpleDbTransaction)) + .next(() => db.deleteObjectStore(DbRemoteDocumentStore$1)); + } + if (fromVersion < 14 && toVersion >= 14) { + p = p.next(() => this.runOverlayMigration(db, simpleDbTransaction)); + } + if (fromVersion < 15 && toVersion >= 15) { + p = p.next(() => createFieldIndex(db)); + } + if (fromVersion < 16 && toVersion >= 16) { + // Clear the object stores to remove possibly corrupted index entries + p = p + .next(() => { + const indexStateStore = txn.objectStore(DbIndexStateStore); + indexStateStore.clear(); + }) + .next(() => { + const indexEntryStore = txn.objectStore(DbIndexEntryStore); + indexEntryStore.clear(); + }); + } + if (fromVersion < 17 && toVersion >= 17) { + p = p.next(() => { + createGlobalsStore(db); + }); + } + if (fromVersion < 18 && toVersion >= 18) { + // Clear the IndexEntryStores on WebKit and Safari to remove possibly + // corrupted index entries + if (isSafariOrWebkit()) { + p = p + .next(() => { + const indexStateStore = txn.objectStore(DbIndexStateStore); + indexStateStore.clear(); + }) + .next(() => { + const indexEntryStore = txn.objectStore(DbIndexEntryStore); + indexEntryStore.clear(); + }); + } + } + return p; + } + addDocumentGlobal(txn) { + let byteSize = 0; + return txn + .store(DbRemoteDocumentStore$1) + .iterate((_, doc) => { + byteSize += dbDocumentSize(doc); + }) + .next(() => { + const metadata = { byteSize }; + return txn + .store(DbRemoteDocumentGlobalStore) + .put(DbRemoteDocumentGlobalKey, metadata); + }); + } + removeAcknowledgedMutations(txn) { + const queuesStore = txn.store(DbMutationQueueStore); + const mutationsStore = txn.store(DbMutationBatchStore); + return queuesStore.loadAll().next(queues => { + return PersistencePromise.forEach(queues, (queue) => { + const range = IDBKeyRange.bound([queue.userId, BATCHID_UNKNOWN], [queue.userId, queue.lastAcknowledgedBatchId]); + return mutationsStore + .loadAll(DbMutationBatchUserMutationsIndex, range) + .next(dbBatches => { + return PersistencePromise.forEach(dbBatches, (dbBatch) => { + hardAssert(dbBatch.userId === queue.userId, 0x48da, `Cannot process batch from unexpected user`, { batchId: dbBatch.batchId }); + const batch = fromDbMutationBatch(this.serializer, dbBatch); + return removeMutationBatch(txn, queue.userId, batch).next(() => { }); + }); + }); + }); + }); + } + /** + * Ensures that every document in the remote document cache has a corresponding sentinel row + * with a sequence number. Missing rows are given the most recently used sequence number. + */ + ensureSequenceNumbers(txn) { + const documentTargetStore = txn.store(DbTargetDocumentStore); + const documentsStore = txn.store(DbRemoteDocumentStore$1); + const globalTargetStore = txn.store(DbTargetGlobalStore); + return globalTargetStore.get(DbTargetGlobalKey).next(metadata => { + const writeSentinelKey = (path) => { + return documentTargetStore.put({ + targetId: 0, + path: encodeResourcePath(path), + sequenceNumber: metadata.highestListenSequenceNumber + }); + }; + const promises = []; + return documentsStore + .iterate((key, doc) => { + const path = new ResourcePath(key); + const docSentinelKey = sentinelKey(path); + promises.push(documentTargetStore.get(docSentinelKey).next(maybeSentinel => { + if (!maybeSentinel) { + return writeSentinelKey(path); + } + else { + return PersistencePromise.resolve(); + } + })); + }) + .next(() => PersistencePromise.waitFor(promises)); + }); + } + createCollectionParentIndex(db, txn) { + // Create the index. + db.createObjectStore(DbCollectionParentStore, { + keyPath: DbCollectionParentKeyPath + }); + const collectionParentsStore = txn.store(DbCollectionParentStore); + // Helper to add an index entry iff we haven't already written it. + const cache = new MemoryCollectionParentIndex(); + const addEntry = (collectionPath) => { + if (cache.add(collectionPath)) { + const collectionId = collectionPath.lastSegment(); + const parentPath = collectionPath.popLast(); + return collectionParentsStore.put({ + collectionId, + parent: encodeResourcePath(parentPath) + }); + } + }; + // Index existing remote documents. + return txn + .store(DbRemoteDocumentStore$1) + .iterate({ keysOnly: true }, (pathSegments, _) => { + const path = new ResourcePath(pathSegments); + return addEntry(path.popLast()); + }) + .next(() => { + // Index existing mutations. + return txn + .store(DbDocumentMutationStore) + .iterate({ keysOnly: true }, ([userID, encodedPath, batchId], _) => { + const path = decodeResourcePath(encodedPath); + return addEntry(path.popLast()); + }); + }); + } + rewriteCanonicalIds(txn) { + const targetStore = txn.store(DbTargetStore); + return targetStore.iterate((key, originalDbTarget) => { + const originalTargetData = fromDbTarget(originalDbTarget); + const updatedDbTarget = toDbTarget(this.serializer, originalTargetData); + return targetStore.put(updatedDbTarget); + }); + } + rewriteRemoteDocumentCache(db, transaction) { + const legacyRemoteDocumentStore = transaction.store(DbRemoteDocumentStore$1); + const writes = []; + return legacyRemoteDocumentStore + .iterate((_, legacyDocument) => { + const remoteDocumentStore = transaction.store(DbRemoteDocumentStore); + const path = extractKey(legacyDocument).path.toArray(); + const dbRemoteDocument = { + prefixPath: path.slice(0, path.length - 2), + collectionGroup: path[path.length - 2], + documentId: path[path.length - 1], + readTime: legacyDocument.readTime || [0, 0], + unknownDocument: legacyDocument.unknownDocument, + noDocument: legacyDocument.noDocument, + document: legacyDocument.document, + hasCommittedMutations: !!legacyDocument.hasCommittedMutations + }; + writes.push(remoteDocumentStore.put(dbRemoteDocument)); + }) + .next(() => PersistencePromise.waitFor(writes)); + } + runOverlayMigration(db, transaction) { + const mutationsStore = transaction.store(DbMutationBatchStore); + const remoteDocumentCache = newIndexedDbRemoteDocumentCache(this.serializer); + const memoryPersistence = new MemoryPersistence(MemoryEagerDelegate.factory, this.serializer.remoteSerializer); + return mutationsStore.loadAll().next(dbBatches => { + const userToDocumentSet = new Map(); + dbBatches.forEach(dbBatch => { + let documentSet = userToDocumentSet.get(dbBatch.userId) ?? documentKeySet(); + const batch = fromDbMutationBatch(this.serializer, dbBatch); + batch.keys().forEach(key => (documentSet = documentSet.add(key))); + userToDocumentSet.set(dbBatch.userId, documentSet); + }); + return PersistencePromise.forEach(userToDocumentSet, (allDocumentKeysForUser, userId) => { + const user = new User(userId); + const documentOverlayCache = IndexedDbDocumentOverlayCache.forUser(this.serializer, user); + // NOTE: The index manager and the reference delegate are + // irrelevant for the purpose of recalculating and saving + // overlays. We can therefore simply use the memory + // implementation. + const indexManager = memoryPersistence.getIndexManager(user); + const mutationQueue = IndexedDbMutationQueue.forUser(user, this.serializer, indexManager, memoryPersistence.referenceDelegate); + const localDocumentsView = new LocalDocumentsView(remoteDocumentCache, mutationQueue, documentOverlayCache, indexManager); + return localDocumentsView + .recalculateAndSaveOverlaysForDocumentKeys(new IndexedDbTransaction(transaction, ListenSequence.INVALID), allDocumentKeysForUser) + .next(); + }); + }); + } +} +function sentinelKey(path) { + return [0, encodeResourcePath(path)]; +} +function createPrimaryClientStore(db) { + db.createObjectStore(DbPrimaryClientStore); +} +function createMutationQueue(db) { + db.createObjectStore(DbMutationQueueStore, { + keyPath: DbMutationQueueKeyPath + }); + const mutationBatchesStore = db.createObjectStore(DbMutationBatchStore, { + keyPath: DbMutationBatchKeyPath, + autoIncrement: true + }); + mutationBatchesStore.createIndex(DbMutationBatchUserMutationsIndex, DbMutationBatchUserMutationsKeyPath, { unique: true }); + db.createObjectStore(DbDocumentMutationStore); +} +/** + * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads + * and rewrites all data. + */ +function upgradeMutationBatchSchemaAndMigrateData(db, txn) { + const v1MutationsStore = txn.store(DbMutationBatchStore); + return v1MutationsStore.loadAll().next(existingMutations => { + db.deleteObjectStore(DbMutationBatchStore); + const mutationsStore = db.createObjectStore(DbMutationBatchStore, { + keyPath: DbMutationBatchKeyPath, + autoIncrement: true + }); + mutationsStore.createIndex(DbMutationBatchUserMutationsIndex, DbMutationBatchUserMutationsKeyPath, { unique: true }); + const v3MutationsStore = txn.store(DbMutationBatchStore); + const writeAll = existingMutations.map(mutation => v3MutationsStore.put(mutation)); + return PersistencePromise.waitFor(writeAll); + }); +} +function createLegacyRemoteDocumentCache(db) { + db.createObjectStore(DbRemoteDocumentStore$1); +} +function createRemoteDocumentCache(db) { + const remoteDocumentStore = db.createObjectStore(DbRemoteDocumentStore, { + keyPath: DbRemoteDocumentKeyPath + }); + remoteDocumentStore.createIndex(DbRemoteDocumentDocumentKeyIndex, DbRemoteDocumentDocumentKeyIndexPath); + remoteDocumentStore.createIndex(DbRemoteDocumentCollectionGroupIndex, DbRemoteDocumentCollectionGroupIndexPath); +} +function createDocumentGlobalStore(db) { + db.createObjectStore(DbRemoteDocumentGlobalStore); +} +function createQueryCache(db) { + const targetDocumentsStore = db.createObjectStore(DbTargetDocumentStore, { + keyPath: DbTargetDocumentKeyPath + }); + targetDocumentsStore.createIndex(DbTargetDocumentDocumentTargetsIndex, DbTargetDocumentDocumentTargetsKeyPath, { unique: true }); + const targetStore = db.createObjectStore(DbTargetStore, { + keyPath: DbTargetKeyPath + }); + // NOTE: This is unique only because the TargetId is the suffix. + targetStore.createIndex(DbTargetQueryTargetsIndexName, DbTargetQueryTargetsKeyPath, { unique: true }); + db.createObjectStore(DbTargetGlobalStore); +} +function dropQueryCache(db) { + db.deleteObjectStore(DbTargetDocumentStore); + db.deleteObjectStore(DbTargetStore); + db.deleteObjectStore(DbTargetGlobalStore); +} +function dropRemoteDocumentChangesStore(db) { + if (db.objectStoreNames.contains('remoteDocumentChanges')) { + db.deleteObjectStore('remoteDocumentChanges'); + } +} +/** + * Creates the target global singleton row. + * + * @param txn - The version upgrade transaction for indexeddb + */ +function writeEmptyTargetGlobalEntry(txn) { + const globalStore = txn.store(DbTargetGlobalStore); + const metadata = { + highestTargetId: 0, + highestListenSequenceNumber: 0, + lastRemoteSnapshotVersion: SnapshotVersion.min().toTimestamp(), + targetCount: 0 + }; + return globalStore.put(DbTargetGlobalKey, metadata); +} +function createClientMetadataStore(db) { + db.createObjectStore(DbClientMetadataStore, { + keyPath: DbClientMetadataKeyPath + }); +} +function createBundlesStore(db) { + db.createObjectStore(DbBundleStore, { + keyPath: DbBundleKeyPath + }); +} +function createNamedQueriesStore(db) { + db.createObjectStore(DbNamedQueryStore, { + keyPath: DbNamedQueryKeyPath + }); +} +function createFieldIndex(db) { + const indexConfigurationStore = db.createObjectStore(DbIndexConfigurationStore, { + keyPath: DbIndexConfigurationKeyPath, + autoIncrement: true + }); + indexConfigurationStore.createIndex(DbIndexConfigurationCollectionGroupIndex, DbIndexConfigurationCollectionGroupIndexPath, { unique: false }); + const indexStateStore = db.createObjectStore(DbIndexStateStore, { + keyPath: DbIndexStateKeyPath + }); + indexStateStore.createIndex(DbIndexStateSequenceNumberIndex, DbIndexStateSequenceNumberIndexPath, { unique: false }); + const indexEntryStore = db.createObjectStore(DbIndexEntryStore, { + keyPath: DbIndexEntryKeyPath + }); + indexEntryStore.createIndex(DbIndexEntryDocumentKeyIndex, DbIndexEntryDocumentKeyIndexPath, { unique: false }); +} +function createDocumentOverlayStore(db) { + const documentOverlayStore = db.createObjectStore(DbDocumentOverlayStore, { + keyPath: DbDocumentOverlayKeyPath + }); + documentOverlayStore.createIndex(DbDocumentOverlayCollectionPathOverlayIndex, DbDocumentOverlayCollectionPathOverlayIndexPath, { unique: false }); + documentOverlayStore.createIndex(DbDocumentOverlayCollectionGroupOverlayIndex, DbDocumentOverlayCollectionGroupOverlayIndexPath, { unique: false }); +} +function createGlobalsStore(db) { + db.createObjectStore(DbGlobalsStore, { + keyPath: DbGlobalsKeyPath + }); +} +function extractKey(remoteDoc) { + if (remoteDoc.document) { + return new DocumentKey(ResourcePath.fromString(remoteDoc.document.name).popFirst(5)); + } + else if (remoteDoc.noDocument) { + return DocumentKey.fromSegments(remoteDoc.noDocument.path); + } + else if (remoteDoc.unknownDocument) { + return DocumentKey.fromSegments(remoteDoc.unknownDocument.path); + } + else { + return fail(0x8faf); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$c = 'IndexedDbPersistence'; +/** + * Oldest acceptable age in milliseconds for client metadata before the client + * is considered inactive and its associated data is garbage collected. + */ +const MAX_CLIENT_AGE_MS = 30 * 60 * 1000; // 30 minutes +/** + * Oldest acceptable metadata age for clients that may participate in the + * primary lease election. Clients that have not updated their client metadata + * within 5 seconds are not eligible to receive a primary lease. + */ +const MAX_PRIMARY_ELIGIBLE_AGE_MS = 5000; +/** + * The interval at which clients will update their metadata, including + * refreshing their primary lease if held or potentially trying to acquire it if + * not held. + * + * Primary clients may opportunistically refresh their metadata earlier + * if they're already performing an IndexedDB operation. + */ +const CLIENT_METADATA_REFRESH_INTERVAL_MS = 4000; +/** User-facing error when the primary lease is required but not available. */ +const PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG = 'Failed to obtain exclusive access to the persistence layer. To allow ' + + 'shared access, multi-tab synchronization has to be enabled in all tabs. ' + + 'If you are using `experimentalForceOwningTab:true`, make sure that only ' + + 'one tab has persistence enabled at any given time.'; +const UNSUPPORTED_PLATFORM_ERROR_MSG = 'This platform is either missing IndexedDB or is known to have ' + + 'an incomplete implementation. Offline persistence has been disabled.'; +// The format of the LocalStorage key that stores zombied client is: +// firestore_zombie__ +const ZOMBIED_CLIENTS_KEY_PREFIX = 'firestore_zombie'; +/** + * The name of the main (and currently only) IndexedDB database. This name is + * appended to the prefix provided to the IndexedDbPersistence constructor. + */ +const MAIN_DATABASE = 'main'; +/** + * An IndexedDB-backed instance of Persistence. Data is stored persistently + * across sessions. + * + * On Web only, the Firestore SDKs support shared access to its persistence + * layer. This allows multiple browser tabs to read and write to IndexedDb and + * to synchronize state even without network connectivity. Shared access is + * currently optional and not enabled unless all clients invoke + * `enablePersistence()` with `{synchronizeTabs:true}`. + * + * In multi-tab mode, if multiple clients are active at the same time, the SDK + * will designate one client as the "primary client". An effort is made to pick + * a visible, network-connected and active client, and this client is + * responsible for letting other clients know about its presence. The primary + * client writes a unique client-generated identifier (the client ID) to + * IndexedDb’s "owner" store every 4 seconds. If the primary client fails to + * update this entry, another client can acquire the lease and take over as + * primary. + * + * Some persistence operations in the SDK are designated as primary-client only + * operations. This includes the acknowledgment of mutations and all updates of + * remote documents. The effects of these operations are written to persistence + * and then broadcast to other tabs via LocalStorage (see + * `WebStorageSharedClientState`), which then refresh their state from + * persistence. + * + * Similarly, the primary client listens to notifications sent by secondary + * clients to discover persistence changes written by secondary clients, such as + * the addition of new mutations and query targets. + * + * If multi-tab is not enabled and another tab already obtained the primary + * lease, IndexedDbPersistence enters a failed state and all subsequent + * operations will automatically fail. + * + * Additionally, there is an optimization so that when a tab is closed, the + * primary lease is released immediately (this is especially important to make + * sure that a refreshed tab is able to immediately re-acquire the primary + * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload + * since it is an asynchronous API. So in addition to attempting to give up the + * lease, the leaseholder writes its client ID to a "zombiedClient" entry in + * LocalStorage which acts as an indicator that another tab should go ahead and + * take the primary lease immediately regardless of the current lease timestamp. + * + * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no + * longer optional. + */ +class IndexedDbPersistence { + constructor( + /** + * Whether to synchronize the in-memory state of multiple tabs and share + * access to local persistence. + */ + allowTabSynchronization, persistenceKey, clientId, lruParams, queue, window, document, serializer, sequenceNumberSyncer, + /** + * If set to true, forcefully obtains database access. Existing tabs will + * no longer be able to access IndexedDB. + */ + forceOwningTab, schemaVersion = SCHEMA_VERSION) { + this.allowTabSynchronization = allowTabSynchronization; + this.persistenceKey = persistenceKey; + this.clientId = clientId; + this.queue = queue; + this.window = window; + this.document = document; + this.sequenceNumberSyncer = sequenceNumberSyncer; + this.forceOwningTab = forceOwningTab; + this.schemaVersion = schemaVersion; + this.listenSequence = null; + this._started = false; + this.isPrimary = false; + this.networkEnabled = true; + /** Our window.unload handler, if registered. */ + this.windowUnloadHandler = null; + this.inForeground = false; + /** Our 'visibilitychange' listener if registered. */ + this.documentVisibilityHandler = null; + /** The client metadata refresh task. */ + this.clientMetadataRefresher = null; + /** The last time we garbage collected the client metadata object store. */ + this.lastGarbageCollectionTime = Number.NEGATIVE_INFINITY; + /** A listener to notify on primary state changes. */ + this.primaryStateListener = _ => Promise.resolve(); + if (!IndexedDbPersistence.isAvailable()) { + throw new FirestoreError(Code.UNIMPLEMENTED, UNSUPPORTED_PLATFORM_ERROR_MSG); + } + this.referenceDelegate = new IndexedDbLruDelegateImpl(this, lruParams); + this.dbName = persistenceKey + MAIN_DATABASE; + this.serializer = new LocalSerializer(serializer); + this.simpleDb = new SimpleDb(this.dbName, this.schemaVersion, new SchemaConverter(this.serializer)); + this.globalsCache = new IndexedDbGlobalsCache(); + this.targetCache = new IndexedDbTargetCache(this.referenceDelegate, this.serializer); + this.remoteDocumentCache = newIndexedDbRemoteDocumentCache(this.serializer); + this.bundleCache = new IndexedDbBundleCache(); + if (this.window && this.window.localStorage) { + this.webStorage = this.window.localStorage; + } + else { + this.webStorage = null; + if (forceOwningTab === false) { + logError(LOG_TAG$c, 'LocalStorage is unavailable. As a result, persistence may not work ' + + 'reliably. In particular enablePersistence() could fail immediately ' + + 'after refreshing the page.'); + } + } + } + /** + * Attempt to start IndexedDb persistence. + * + * @returns Whether persistence was enabled. + */ + start() { + // NOTE: This is expected to fail sometimes (in the case of another tab + // already having the persistence lock), so it's the first thing we should + // do. + return this.updateClientMetadataAndTryBecomePrimary() + .then(() => { + if (!this.isPrimary && !this.allowTabSynchronization) { + // Fail `start()` if `synchronizeTabs` is disabled and we cannot + // obtain the primary lease. + throw new FirestoreError(Code.FAILED_PRECONDITION, PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG); + } + this.attachVisibilityHandler(); + this.attachWindowUnloadHook(); + this.scheduleClientMetadataAndPrimaryLeaseRefreshes(); + return this.runTransaction('getHighestListenSequenceNumber', 'readonly', txn => this.targetCache.getHighestSequenceNumber(txn)); + }) + .then(highestListenSequenceNumber => { + this.listenSequence = new ListenSequence(highestListenSequenceNumber, this.sequenceNumberSyncer); + }) + .then(() => { + this._started = true; + }) + .catch(reason => { + this.simpleDb && this.simpleDb.close(); + return Promise.reject(reason); + }); + } + /** + * Registers a listener that gets called when the primary state of the + * instance changes. Upon registering, this listener is invoked immediately + * with the current primary state. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setPrimaryStateListener(primaryStateListener) { + this.primaryStateListener = async (primaryState) => { + if (this.started) { + return primaryStateListener(primaryState); + } + }; + return primaryStateListener(this.isPrimary); + } + /** + * Registers a listener that gets called when the database receives a + * version change event indicating that it has deleted. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setDatabaseDeletedListener(databaseDeletedListener) { + this.simpleDb.setVersionChangeListener(async (event) => { + // Check if an attempt is made to delete IndexedDB. + if (event.newVersion === null) { + await databaseDeletedListener(); + } + }); + } + /** + * Adjusts the current network state in the client's metadata, potentially + * affecting the primary lease. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setNetworkEnabled(networkEnabled) { + if (this.networkEnabled !== networkEnabled) { + this.networkEnabled = networkEnabled; + // Schedule a primary lease refresh for immediate execution. The eventual + // lease update will be propagated via `primaryStateListener`. + this.queue.enqueueAndForget(async () => { + if (this.started) { + await this.updateClientMetadataAndTryBecomePrimary(); + } + }); + } + } + /** + * Updates the client metadata in IndexedDb and attempts to either obtain or + * extend the primary lease for the local client. Asynchronously notifies the + * primary state listener if the client either newly obtained or released its + * primary lease. + */ + updateClientMetadataAndTryBecomePrimary() { + return this.runTransaction('updateClientMetadataAndTryBecomePrimary', 'readwrite', txn => { + const metadataStore = clientMetadataStore(txn); + return metadataStore + .put({ + clientId: this.clientId, + updateTimeMs: Date.now(), + networkEnabled: this.networkEnabled, + inForeground: this.inForeground + }) + .next(() => { + if (this.isPrimary) { + return this.verifyPrimaryLease(txn).next(success => { + if (!success) { + this.isPrimary = false; + this.queue.enqueueRetryable(() => this.primaryStateListener(false)); + } + }); + } + }) + .next(() => this.canActAsPrimary(txn)) + .next(canActAsPrimary => { + if (this.isPrimary && !canActAsPrimary) { + return this.releasePrimaryLeaseIfHeld(txn).next(() => false); + } + else if (canActAsPrimary) { + return this.acquireOrExtendPrimaryLease(txn).next(() => true); + } + else { + return /* canActAsPrimary= */ false; + } + }); + }) + .catch(e => { + if (isIndexedDbTransactionError(e)) { + logDebug(LOG_TAG$c, 'Failed to extend owner lease: ', e); + // Proceed with the existing state. Any subsequent access to + // IndexedDB will verify the lease. + return this.isPrimary; + } + if (!this.allowTabSynchronization) { + throw e; + } + logDebug(LOG_TAG$c, 'Releasing owner lease after error during lease refresh', e); + return /* isPrimary= */ false; + }) + .then(isPrimary => { + if (this.isPrimary !== isPrimary) { + this.queue.enqueueRetryable(() => this.primaryStateListener(isPrimary)); + } + this.isPrimary = isPrimary; + }); + } + verifyPrimaryLease(txn) { + const store = primaryClientStore(txn); + return store.get(DbPrimaryClientKey).next(primaryClient => { + return PersistencePromise.resolve(this.isLocalClient(primaryClient)); + }); + } + removeClientMetadata(txn) { + const metadataStore = clientMetadataStore(txn); + return metadataStore.delete(this.clientId); + } + /** + * If the garbage collection threshold has passed, prunes the + * RemoteDocumentChanges and the ClientMetadata store based on the last update + * time of all clients. + */ + async maybeGarbageCollectMultiClientState() { + if (this.isPrimary && + !this.isWithinAge(this.lastGarbageCollectionTime, MAX_CLIENT_AGE_MS)) { + this.lastGarbageCollectionTime = Date.now(); + const inactiveClients = await this.runTransaction('maybeGarbageCollectMultiClientState', 'readwrite-primary', txn => { + const metadataStore = getStore(txn, DbClientMetadataStore); + return metadataStore.loadAll().next(existingClients => { + const active = this.filterActiveClients(existingClients, MAX_CLIENT_AGE_MS); + const inactive = existingClients.filter(client => active.indexOf(client) === -1); + // Delete metadata for clients that are no longer considered active. + return PersistencePromise.forEach(inactive, (inactiveClient) => metadataStore.delete(inactiveClient.clientId)).next(() => inactive); + }); + }).catch(() => { + // Ignore primary lease violations or any other type of error. The next + // primary will run `maybeGarbageCollectMultiClientState()` again. + // We don't use `ignoreIfPrimaryLeaseLoss()` since we don't want to depend + // on LocalStore. + return []; + }); + // Delete potential leftover entries that may continue to mark the + // inactive clients as zombied in LocalStorage. + // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for + // the client atomically, but we can't. So we opt to delete the IndexedDb + // entries first to avoid potentially reviving a zombied client. + if (this.webStorage) { + for (const inactiveClient of inactiveClients) { + this.webStorage.removeItem(this.zombiedClientLocalStorageKey(inactiveClient.clientId)); + } + } + } + } + /** + * Schedules a recurring timer to update the client metadata and to either + * extend or acquire the primary lease if the client is eligible. + */ + scheduleClientMetadataAndPrimaryLeaseRefreshes() { + this.clientMetadataRefresher = this.queue.enqueueAfterDelay("client_metadata_refresh" /* TimerId.ClientMetadataRefresh */, CLIENT_METADATA_REFRESH_INTERVAL_MS, () => { + return this.updateClientMetadataAndTryBecomePrimary() + .then(() => this.maybeGarbageCollectMultiClientState()) + .then(() => this.scheduleClientMetadataAndPrimaryLeaseRefreshes()); + }); + } + /** Checks whether `client` is the local client. */ + isLocalClient(client) { + return client ? client.ownerId === this.clientId : false; + } + /** + * Evaluate the state of all active clients and determine whether the local + * client is or can act as the holder of the primary lease. Returns whether + * the client is eligible for the lease, but does not actually acquire it. + * May return 'false' even if there is no active leaseholder and another + * (foreground) client should become leaseholder instead. + */ + canActAsPrimary(txn) { + if (this.forceOwningTab) { + return PersistencePromise.resolve(true); + } + const store = primaryClientStore(txn); + return store + .get(DbPrimaryClientKey) + .next(currentPrimary => { + const currentLeaseIsValid = currentPrimary !== null && + this.isWithinAge(currentPrimary.leaseTimestampMs, MAX_PRIMARY_ELIGIBLE_AGE_MS) && + !this.isClientZombied(currentPrimary.ownerId); + // A client is eligible for the primary lease if: + // - its network is enabled and the client's tab is in the foreground. + // - its network is enabled and no other client's tab is in the + // foreground. + // - every clients network is disabled and the client's tab is in the + // foreground. + // - every clients network is disabled and no other client's tab is in + // the foreground. + // - the `forceOwningTab` setting was passed in. + if (currentLeaseIsValid) { + if (this.isLocalClient(currentPrimary) && this.networkEnabled) { + return true; + } + if (!this.isLocalClient(currentPrimary)) { + if (!currentPrimary.allowTabSynchronization) { + // Fail the `canActAsPrimary` check if the current leaseholder has + // not opted into multi-tab synchronization. If this happens at + // client startup, we reject the Promise returned by + // `enablePersistence()` and the user can continue to use Firestore + // with in-memory persistence. + // If this fails during a lease refresh, we will instead block the + // AsyncQueue from executing further operations. Note that this is + // acceptable since mixing & matching different `synchronizeTabs` + // settings is not supported. + // + // TODO(b/114226234): Remove this check when `synchronizeTabs` can + // no longer be turned off. + throw new FirestoreError(Code.FAILED_PRECONDITION, PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG); + } + return false; + } + } + if (this.networkEnabled && this.inForeground) { + return true; + } + return clientMetadataStore(txn) + .loadAll() + .next(existingClients => { + // Process all existing clients and determine whether at least one of + // them is better suited to obtain the primary lease. + const preferredCandidate = this.filterActiveClients(existingClients, MAX_PRIMARY_ELIGIBLE_AGE_MS).find(otherClient => { + if (this.clientId !== otherClient.clientId) { + const otherClientHasBetterNetworkState = !this.networkEnabled && otherClient.networkEnabled; + const otherClientHasBetterVisibility = !this.inForeground && otherClient.inForeground; + const otherClientHasSameNetworkState = this.networkEnabled === otherClient.networkEnabled; + if (otherClientHasBetterNetworkState || + (otherClientHasBetterVisibility && + otherClientHasSameNetworkState)) { + return true; + } + } + return false; + }); + return preferredCandidate === undefined; + }); + }) + .next(canActAsPrimary => { + if (this.isPrimary !== canActAsPrimary) { + logDebug(LOG_TAG$c, `Client ${canActAsPrimary ? 'is' : 'is not'} eligible for a primary lease.`); + } + return canActAsPrimary; + }); + } + async shutdown() { + // The shutdown() operations are idempotent and can be called even when + // start() aborted (e.g. because it couldn't acquire the persistence lease). + this._started = false; + this.markClientZombied(); + if (this.clientMetadataRefresher) { + this.clientMetadataRefresher.cancel(); + this.clientMetadataRefresher = null; + } + this.detachVisibilityHandler(); + this.detachWindowUnloadHook(); + // Use `SimpleDb.runTransaction` directly to avoid failing if another tab + // has obtained the primary lease. + await this.simpleDb.runTransaction('shutdown', 'readwrite', [DbPrimaryClientStore, DbClientMetadataStore], simpleDbTxn => { + const persistenceTransaction = new IndexedDbTransaction(simpleDbTxn, ListenSequence.INVALID); + return this.releasePrimaryLeaseIfHeld(persistenceTransaction).next(() => this.removeClientMetadata(persistenceTransaction)); + }); + this.simpleDb.close(); + // Remove the entry marking the client as zombied from LocalStorage since + // we successfully deleted its metadata from IndexedDb. + this.removeClientZombiedEntry(); + } + /** + * Returns clients that are not zombied and have an updateTime within the + * provided threshold. + */ + filterActiveClients(clients, activityThresholdMs) { + return clients.filter(client => this.isWithinAge(client.updateTimeMs, activityThresholdMs) && + !this.isClientZombied(client.clientId)); + } + /** + * Returns the IDs of the clients that are currently active. If multi-tab + * is not supported, returns an array that only contains the local client's + * ID. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + getActiveClients() { + return this.runTransaction('getActiveClients', 'readonly', txn => { + return clientMetadataStore(txn) + .loadAll() + .next(clients => this.filterActiveClients(clients, MAX_CLIENT_AGE_MS).map(clientMetadata => clientMetadata.clientId)); + }); + } + get started() { + return this._started; + } + getGlobalsCache() { + return this.globalsCache; + } + getMutationQueue(user, indexManager) { + return IndexedDbMutationQueue.forUser(user, this.serializer, indexManager, this.referenceDelegate); + } + getTargetCache() { + return this.targetCache; + } + getRemoteDocumentCache() { + return this.remoteDocumentCache; + } + getIndexManager(user) { + return new IndexedDbIndexManager(user, this.serializer.remoteSerializer.databaseId); + } + getDocumentOverlayCache(user) { + return IndexedDbDocumentOverlayCache.forUser(this.serializer, user); + } + getBundleCache() { + return this.bundleCache; + } + runTransaction(action, mode, transactionOperation) { + logDebug(LOG_TAG$c, 'Starting transaction:', action); + const simpleDbMode = mode === 'readonly' ? 'readonly' : 'readwrite'; + const objectStores = getObjectStores(this.schemaVersion); + let persistenceTransaction; + // Do all transactions as readwrite against all object stores, since we + // are the only reader/writer. + return this.simpleDb + .runTransaction(action, simpleDbMode, objectStores, simpleDbTxn => { + persistenceTransaction = new IndexedDbTransaction(simpleDbTxn, this.listenSequence + ? this.listenSequence.next() + : ListenSequence.INVALID); + if (mode === 'readwrite-primary') { + // While we merely verify that we have (or can acquire) the lease + // immediately, we wait to extend the primary lease until after + // executing transactionOperation(). This ensures that even if the + // transactionOperation takes a long time, we'll use a recent + // leaseTimestampMs in the extended (or newly acquired) lease. + return this.verifyPrimaryLease(persistenceTransaction) + .next(holdsPrimaryLease => { + if (holdsPrimaryLease) { + return /* holdsPrimaryLease= */ true; + } + return this.canActAsPrimary(persistenceTransaction); + }) + .next(holdsPrimaryLease => { + if (!holdsPrimaryLease) { + logError(`Failed to obtain primary lease for action '${action}'.`); + this.isPrimary = false; + this.queue.enqueueRetryable(() => this.primaryStateListener(false)); + throw new FirestoreError(Code.FAILED_PRECONDITION, PRIMARY_LEASE_LOST_ERROR_MSG); + } + return transactionOperation(persistenceTransaction); + }) + .next(result => { + return this.acquireOrExtendPrimaryLease(persistenceTransaction).next(() => result); + }); + } + else { + return this.verifyAllowTabSynchronization(persistenceTransaction).next(() => transactionOperation(persistenceTransaction)); + } + }) + .then(result => { + persistenceTransaction.raiseOnCommittedEvent(); + return result; + }); + } + /** + * Verifies that the current tab is the primary leaseholder or alternatively + * that the leaseholder has opted into multi-tab synchronization. + */ + // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer + // be turned off. + verifyAllowTabSynchronization(txn) { + const store = primaryClientStore(txn); + return store.get(DbPrimaryClientKey).next(currentPrimary => { + const currentLeaseIsValid = currentPrimary !== null && + this.isWithinAge(currentPrimary.leaseTimestampMs, MAX_PRIMARY_ELIGIBLE_AGE_MS) && + !this.isClientZombied(currentPrimary.ownerId); + if (currentLeaseIsValid && !this.isLocalClient(currentPrimary)) { + if (!this.forceOwningTab && + (!this.allowTabSynchronization || + !currentPrimary.allowTabSynchronization)) { + throw new FirestoreError(Code.FAILED_PRECONDITION, PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG); + } + } + }); + } + /** + * Obtains or extends the new primary lease for the local client. This + * method does not verify that the client is eligible for this lease. + */ + acquireOrExtendPrimaryLease(txn) { + const newPrimary = { + ownerId: this.clientId, + allowTabSynchronization: this.allowTabSynchronization, + leaseTimestampMs: Date.now() + }; + return primaryClientStore(txn).put(DbPrimaryClientKey, newPrimary); + } + static isAvailable() { + return SimpleDb.isAvailable(); + } + /** Checks the primary lease and removes it if we are the current primary. */ + releasePrimaryLeaseIfHeld(txn) { + const store = primaryClientStore(txn); + return store.get(DbPrimaryClientKey).next(primaryClient => { + if (this.isLocalClient(primaryClient)) { + logDebug(LOG_TAG$c, 'Releasing primary lease.'); + return store.delete(DbPrimaryClientKey); + } + else { + return PersistencePromise.resolve(); + } + }); + } + /** Verifies that `updateTimeMs` is within `maxAgeMs`. */ + isWithinAge(updateTimeMs, maxAgeMs) { + const now = Date.now(); + const minAcceptable = now - maxAgeMs; + const maxAcceptable = now; + if (updateTimeMs < minAcceptable) { + return false; + } + else if (updateTimeMs > maxAcceptable) { + logError(`Detected an update time that is in the future: ${updateTimeMs} > ${maxAcceptable}`); + return false; + } + return true; + } + attachVisibilityHandler() { + if (this.document !== null && + typeof this.document.addEventListener === 'function') { + this.documentVisibilityHandler = () => { + this.queue.enqueueAndForget(() => { + this.inForeground = this.document.visibilityState === 'visible'; + return this.updateClientMetadataAndTryBecomePrimary(); + }); + }; + this.document.addEventListener('visibilitychange', this.documentVisibilityHandler); + this.inForeground = this.document.visibilityState === 'visible'; + } + } + detachVisibilityHandler() { + if (this.documentVisibilityHandler) { + this.document.removeEventListener('visibilitychange', this.documentVisibilityHandler); + this.documentVisibilityHandler = null; + } + } + /** + * Attaches a window.unload handler that will synchronously write our + * clientId to a "zombie client id" location in LocalStorage. This can be used + * by tabs trying to acquire the primary lease to determine that the lease + * is no longer valid even if the timestamp is recent. This is particularly + * important for the refresh case (so the tab correctly re-acquires the + * primary lease). LocalStorage is used for this rather than IndexedDb because + * it is a synchronous API and so can be used reliably from an unload + * handler. + */ + attachWindowUnloadHook() { + if (typeof this.window?.addEventListener === 'function') { + this.windowUnloadHandler = () => { + // Note: In theory, this should be scheduled on the AsyncQueue since it + // accesses internal state. We execute this code directly during shutdown + // to make sure it gets a chance to run. + this.markClientZombied(); + const safariIndexdbBugVersionRegex = /(?:Version|Mobile)\/1[456]/; + if (isSafari() && + (navigator.appVersion.match(safariIndexdbBugVersionRegex) || + navigator.userAgent.match(safariIndexdbBugVersionRegex))) { + // On Safari 14, 15, and 16, we do not run any cleanup actions as it might + // trigger a bug that prevents Safari from re-opening IndexedDB during + // the next page load. + // See https://bugs.webkit.org/show_bug.cgi?id=226547 + this.queue.enterRestrictedMode(/* purgeExistingTasks= */ true); + } + this.queue.enqueueAndForget(() => { + // Attempt graceful shutdown (including releasing our primary lease), + // but there's no guarantee it will complete. + return this.shutdown(); + }); + }; + this.window.addEventListener('pagehide', this.windowUnloadHandler); + } + } + detachWindowUnloadHook() { + if (this.windowUnloadHandler) { + this.window.removeEventListener('pagehide', this.windowUnloadHandler); + this.windowUnloadHandler = null; + } + } + /** + * Returns whether a client is "zombied" based on its LocalStorage entry. + * Clients become zombied when their tab closes without running all of the + * cleanup logic in `shutdown()`. + */ + isClientZombied(clientId) { + try { + const isZombied = this.webStorage?.getItem(this.zombiedClientLocalStorageKey(clientId)) !== null; + logDebug(LOG_TAG$c, `Client '${clientId}' ${isZombied ? 'is' : 'is not'} zombied in LocalStorage`); + return isZombied; + } + catch (e) { + // Gracefully handle if LocalStorage isn't working. + logError(LOG_TAG$c, 'Failed to get zombied client id.', e); + return false; + } + } + /** + * Record client as zombied (a client that had its tab closed). Zombied + * clients are ignored during primary tab selection. + */ + markClientZombied() { + if (!this.webStorage) { + return; + } + try { + this.webStorage.setItem(this.zombiedClientLocalStorageKey(this.clientId), String(Date.now())); + } + catch (e) { + // Gracefully handle if LocalStorage isn't available / working. + logError('Failed to set zombie client id.', e); + } + } + /** Removes the zombied client entry if it exists. */ + removeClientZombiedEntry() { + if (!this.webStorage) { + return; + } + try { + this.webStorage.removeItem(this.zombiedClientLocalStorageKey(this.clientId)); + } + catch (e) { + // Ignore + } + } + zombiedClientLocalStorageKey(clientId) { + return `${ZOMBIED_CLIENTS_KEY_PREFIX}_${this.persistenceKey}_${clientId}`; + } +} +/** + * Helper to get a typed SimpleDbStore for the primary client object store. + */ +function primaryClientStore(txn) { + return getStore(txn, DbPrimaryClientStore); +} +/** + * Helper to get a typed SimpleDbStore for the client metadata object store. + */ +function clientMetadataStore(txn) { + return getStore(txn, DbClientMetadataStore); +} +/** + * Generates a string used as a prefix when storing data in IndexedDB and + * LocalStorage. + */ +function indexedDbStoragePrefix(databaseId, persistenceKey) { + // Use two different prefix formats: + // + // * firestore / persistenceKey / projectID . databaseID / ... + // * firestore / persistenceKey / projectID / ... + // + // projectIDs are DNS-compatible names and cannot contain dots + // so there's no danger of collisions. + let database = databaseId.projectId; + if (!databaseId.isDefaultDatabase) { + database += '.' + databaseId.database; + } + return 'firestore/' + persistenceKey + '/' + database + '/'; +} +async function indexedDbClearPersistence(persistenceKey) { + if (!SimpleDb.isAvailable()) { + return Promise.resolve(); + } + const dbName = persistenceKey + MAIN_DATABASE; + await SimpleDb.delete(dbName); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Compares two array for equality using comparator. The method computes the + * intersection and invokes `onAdd` for every element that is in `after` but not + * `before`. `onRemove` is invoked for every element in `before` but missing + * from `after`. + * + * The method creates a copy of both `before` and `after` and runs in O(n log + * n), where n is the size of the two lists. + * + * @param before - The elements that exist in the original array. + * @param after - The elements to diff against the original array. + * @param comparator - The comparator for the elements in before and after. + * @param onAdd - A function to invoke for every element that is part of ` + * after` but not `before`. + * @param onRemove - A function to invoke for every element that is part of + * `before` but not `after`. + */ +function diffArrays(before, after, comparator, onAdd, onRemove) { + before = [...before]; + after = [...after]; + before.sort(comparator); + after.sort(comparator); + const bLen = before.length; + const aLen = after.length; + let a = 0; + let b = 0; + while (a < aLen && b < bLen) { + const cmp = comparator(before[b], after[a]); + if (cmp < 0) { + // The element was removed if the next element in our ordered + // walkthrough is only in `before`. + onRemove(before[b++]); + } + else if (cmp > 0) { + // The element was added if the next element in our ordered walkthrough + // is only in `after`. + onAdd(after[a++]); + } + else { + a++; + b++; + } + } + while (a < aLen) { + onAdd(after[a++]); + } + while (b < bLen) { + onRemove(before[b++]); + } +} +/** + * Verifies equality for an array of primitives. + * + * @private + * @internal + * @param left Array of primitives. + * @param right Array of primitives. + * @return True if arrays are equal. + */ +function isPrimitiveArrayEqual(left, right) { + if (left.length !== right.length) { + return false; + } + for (let i = 0; i < left.length; ++i) { + if (left[i] !== right[i]) { + return false; + } + } + return true; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$b = 'LocalStore'; +/** + * The maximum time to leave a resume token buffered without writing it out. + * This value is arbitrary: it's long enough to avoid several writes + * (possibly indefinitely if updates come more frequently than this) but + * short enough that restarting after crashing will still have a pretty + * recent resume token. + */ +const RESUME_TOKEN_MAX_AGE_MICROS = 5 * 60 * 1e6; +/** + * Implements `LocalStore` interface. + * + * Note: some field defined in this class might have public access level, but + * the class is not exported so they are only accessible from this module. + * This is useful to implement optional features (like bundles) in free + * functions, such that they are tree-shakeable. + */ +class LocalStoreImpl { + constructor( + /** Manages our in-memory or durable persistence. */ + persistence, queryEngine, initialUser, serializer) { + this.persistence = persistence; + this.queryEngine = queryEngine; + this.serializer = serializer; + /** + * Maps a targetID to data about its target. + * + * PORTING NOTE: We are using an immutable data structure on Web to make re-runs + * of `applyRemoteEvent()` idempotent. + */ + this.targetDataByTarget = new SortedMap(primitiveComparator); + /** Maps a target to its targetID. */ + // TODO(wuandy): Evaluate if TargetId can be part of Target. + this.targetIdByTarget = new ObjectMap(t => canonifyTarget(t), targetEquals); + /** + * A per collection group index of the last read time processed by + * `getNewDocumentChanges()`. + * + * PORTING NOTE: This is only used for multi-tab synchronization. + */ + this.collectionGroupReadTime = new Map(); + this.remoteDocuments = persistence.getRemoteDocumentCache(); + this.targetCache = persistence.getTargetCache(); + this.bundleCache = persistence.getBundleCache(); + this.initializeUserComponents(initialUser); + } + initializeUserComponents(user) { + // TODO(indexing): Add spec tests that test these components change after a + // user change + this.documentOverlayCache = this.persistence.getDocumentOverlayCache(user); + this.indexManager = this.persistence.getIndexManager(user); + this.mutationQueue = this.persistence.getMutationQueue(user, this.indexManager); + this.localDocuments = new LocalDocumentsView(this.remoteDocuments, this.mutationQueue, this.documentOverlayCache, this.indexManager); + this.remoteDocuments.setIndexManager(this.indexManager); + this.queryEngine.initialize(this.localDocuments, this.indexManager); + } + collectGarbage(garbageCollector) { + return this.persistence.runTransaction('Collect garbage', 'readwrite-primary', txn => garbageCollector.collect(txn, this.targetDataByTarget)); + } +} +function newLocalStore( +/** Manages our in-memory or durable persistence. */ +persistence, queryEngine, initialUser, serializer) { + return new LocalStoreImpl(persistence, queryEngine, initialUser, serializer); +} +/** + * Tells the LocalStore that the currently authenticated user has changed. + * + * In response the local store switches the mutation queue to the new user and + * returns any resulting document changes. + */ +// PORTING NOTE: Android and iOS only return the documents affected by the +// change. +async function localStoreHandleUserChange(localStore, user) { + const localStoreImpl = debugCast(localStore); + const result = await localStoreImpl.persistence.runTransaction('Handle user change', 'readonly', txn => { + // Swap out the mutation queue, grabbing the pending mutation batches + // before and after. + let oldBatches; + return localStoreImpl.mutationQueue + .getAllMutationBatches(txn) + .next(promisedOldBatches => { + oldBatches = promisedOldBatches; + localStoreImpl.initializeUserComponents(user); + return localStoreImpl.mutationQueue.getAllMutationBatches(txn); + }) + .next(newBatches => { + const removedBatchIds = []; + const addedBatchIds = []; + // Union the old/new changed keys. + let changedKeys = documentKeySet(); + for (const batch of oldBatches) { + removedBatchIds.push(batch.batchId); + for (const mutation of batch.mutations) { + changedKeys = changedKeys.add(mutation.key); + } + } + for (const batch of newBatches) { + addedBatchIds.push(batch.batchId); + for (const mutation of batch.mutations) { + changedKeys = changedKeys.add(mutation.key); + } + } + // Return the set of all (potentially) changed documents and the list + // of mutation batch IDs that were affected by change. + return localStoreImpl.localDocuments + .getDocuments(txn, changedKeys) + .next(affectedDocuments => { + return { + affectedDocuments, + removedBatchIds, + addedBatchIds + }; + }); + }); + }); + return result; +} +/* Accepts locally generated Mutations and commit them to storage. */ +function localStoreWriteLocally(localStore, mutations) { + const localStoreImpl = debugCast(localStore); + const localWriteTime = Timestamp.now(); + const keys = mutations.reduce((keys, m) => keys.add(m.key), documentKeySet()); + let overlayedDocuments; + let mutationBatch; + return localStoreImpl.persistence + .runTransaction('Locally write mutations', 'readwrite', txn => { + // Figure out which keys do not have a remote version in the cache, this + // is needed to create the right overlay mutation: if no remote version + // presents, we do not need to create overlays as patch mutations. + // TODO(Overlay): Is there a better way to determine this? Using the + // document version does not work because local mutations set them back + // to 0. + let remoteDocs = mutableDocumentMap(); + let docsWithoutRemoteVersion = documentKeySet(); + return localStoreImpl.remoteDocuments + .getEntries(txn, keys) + .next(docs => { + remoteDocs = docs; + remoteDocs.forEach((key, doc) => { + if (!doc.isValidDocument()) { + docsWithoutRemoteVersion = docsWithoutRemoteVersion.add(key); + } + }); + }) + .next(() => { + // Load and apply all existing mutations. This lets us compute the + // current base state for all non-idempotent transforms before applying + // any additional user-provided writes. + return localStoreImpl.localDocuments.getOverlayedDocuments(txn, remoteDocs); + }) + .next((docs) => { + overlayedDocuments = docs; + // For non-idempotent mutations (such as `FieldValue.increment()`), + // we record the base state in a separate patch mutation. This is + // later used to guarantee consistent values and prevents flicker + // even if the backend sends us an update that already includes our + // transform. + const baseMutations = []; + for (const mutation of mutations) { + const baseValue = mutationExtractBaseValue(mutation, overlayedDocuments.get(mutation.key).overlayedDocument); + if (baseValue != null) { + // NOTE: The base state should only be applied if there's some + // existing document to override, so use a Precondition of + // exists=true + baseMutations.push(new PatchMutation(mutation.key, baseValue, extractFieldMask(baseValue.value.mapValue), Precondition.exists(true))); + } + } + return localStoreImpl.mutationQueue.addMutationBatch(txn, localWriteTime, baseMutations, mutations); + }) + .next(batch => { + mutationBatch = batch; + const overlays = batch.applyToLocalDocumentSet(overlayedDocuments, docsWithoutRemoteVersion); + return localStoreImpl.documentOverlayCache.saveOverlays(txn, batch.batchId, overlays); + }); + }) + .then(() => ({ + batchId: mutationBatch.batchId, + changes: convertOverlayedDocumentMapToDocumentMap(overlayedDocuments) + })); +} +/** + * Acknowledges the given batch. + * + * On the happy path when a batch is acknowledged, the local store will + * + * + remove the batch from the mutation queue; + * + apply the changes to the remote document cache; + * + recalculate the latency compensated view implied by those changes (there + * may be mutations in the queue that affect the documents but haven't been + * acknowledged yet); and + * + give the changed documents back the sync engine + * + * @returns The resulting (modified) documents. + */ +function localStoreAcknowledgeBatch(localStore, batchResult) { + const localStoreImpl = debugCast(localStore); + return localStoreImpl.persistence.runTransaction('Acknowledge batch', 'readwrite-primary', txn => { + const affected = batchResult.batch.keys(); + const documentBuffer = localStoreImpl.remoteDocuments.newChangeBuffer({ + trackRemovals: true // Make sure document removals show up in `getNewDocumentChanges()` + }); + return applyWriteToRemoteDocuments(localStoreImpl, txn, batchResult, documentBuffer) + .next(() => documentBuffer.apply(txn)) + .next(() => localStoreImpl.mutationQueue.performConsistencyCheck(txn)) + .next(() => localStoreImpl.documentOverlayCache.removeOverlaysForBatchId(txn, affected, batchResult.batch.batchId)) + .next(() => localStoreImpl.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(txn, getKeysWithTransformResults(batchResult))) + .next(() => localStoreImpl.localDocuments.getDocuments(txn, affected)); + }); +} +function getKeysWithTransformResults(batchResult) { + let result = documentKeySet(); + for (let i = 0; i < batchResult.mutationResults.length; ++i) { + const mutationResult = batchResult.mutationResults[i]; + if (mutationResult.transformResults.length > 0) { + result = result.add(batchResult.batch.mutations[i].key); + } + } + return result; +} +/** + * Removes mutations from the MutationQueue for the specified batch; + * LocalDocuments will be recalculated. + * + * @returns The resulting modified documents. + */ +function localStoreRejectBatch(localStore, batchId) { + const localStoreImpl = debugCast(localStore); + return localStoreImpl.persistence.runTransaction('Reject batch', 'readwrite-primary', txn => { + let affectedKeys; + return localStoreImpl.mutationQueue + .lookupMutationBatch(txn, batchId) + .next((batch) => { + hardAssert(batch !== null, 0x90f9); + affectedKeys = batch.keys(); + return localStoreImpl.mutationQueue.removeMutationBatch(txn, batch); + }) + .next(() => localStoreImpl.mutationQueue.performConsistencyCheck(txn)) + .next(() => localStoreImpl.documentOverlayCache.removeOverlaysForBatchId(txn, affectedKeys, batchId)) + .next(() => localStoreImpl.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(txn, affectedKeys)) + .next(() => localStoreImpl.localDocuments.getDocuments(txn, affectedKeys)); + }); +} +/** + * Returns the largest (latest) batch id in mutation queue that is pending + * server response. + * + * Returns `BATCHID_UNKNOWN` if the queue is empty. + */ +function localStoreGetHighestUnacknowledgedBatchId(localStore) { + const localStoreImpl = debugCast(localStore); + return localStoreImpl.persistence.runTransaction('Get highest unacknowledged batch id', 'readonly', txn => localStoreImpl.mutationQueue.getHighestUnacknowledgedBatchId(txn)); +} +/** + * Returns the last consistent snapshot processed (used by the RemoteStore to + * determine whether to buffer incoming snapshots from the backend). + */ +function localStoreGetLastRemoteSnapshotVersion(localStore) { + const localStoreImpl = debugCast(localStore); + return localStoreImpl.persistence.runTransaction('Get last remote snapshot version', 'readonly', txn => localStoreImpl.targetCache.getLastRemoteSnapshotVersion(txn)); +} +/** + * Updates the "ground-state" (remote) documents. We assume that the remote + * event reflects any write batches that have been acknowledged or rejected + * (i.e. we do not re-apply local mutations to updates from this event). + * + * LocalDocuments are re-calculated if there are remaining mutations in the + * queue. + */ +function localStoreApplyRemoteEventToLocalCache(localStore, remoteEvent) { + const localStoreImpl = debugCast(localStore); + const remoteVersion = remoteEvent.snapshotVersion; + let newTargetDataByTargetMap = localStoreImpl.targetDataByTarget; + return localStoreImpl.persistence + .runTransaction('Apply remote event', 'readwrite-primary', txn => { + const documentBuffer = localStoreImpl.remoteDocuments.newChangeBuffer({ + trackRemovals: true // Make sure document removals show up in `getNewDocumentChanges()` + }); + // Reset newTargetDataByTargetMap in case this transaction gets re-run. + newTargetDataByTargetMap = localStoreImpl.targetDataByTarget; + const promises = []; + remoteEvent.targetChanges.forEach((change, targetId) => { + const oldTargetData = newTargetDataByTargetMap.get(targetId); + if (!oldTargetData) { + return; + } + // Only update the remote keys if the target is still active. This + // ensures that we can persist the updated target data along with + // the updated assignment. + promises.push(localStoreImpl.targetCache + .removeMatchingKeys(txn, change.removedDocuments, targetId) + .next(() => { + return localStoreImpl.targetCache.addMatchingKeys(txn, change.addedDocuments, targetId); + })); + let newTargetData = oldTargetData.withSequenceNumber(txn.currentSequenceNumber); + if (remoteEvent.targetMismatches.get(targetId) !== null) { + newTargetData = newTargetData + .withResumeToken(ByteString.EMPTY_BYTE_STRING, SnapshotVersion.min()) + .withLastLimboFreeSnapshotVersion(SnapshotVersion.min()); + } + else if (change.resumeToken.approximateByteSize() > 0) { + newTargetData = newTargetData.withResumeToken(change.resumeToken, remoteVersion); + } + newTargetDataByTargetMap = newTargetDataByTargetMap.insert(targetId, newTargetData); + // Update the target data if there are target changes (or if + // sufficient time has passed since the last update). + if (shouldPersistTargetData(oldTargetData, newTargetData, change)) { + promises.push(localStoreImpl.targetCache.updateTargetData(txn, newTargetData)); + } + }); + let changedDocs = mutableDocumentMap(); + let existenceChangedKeys = documentKeySet(); + remoteEvent.documentUpdates.forEach(key => { + if (remoteEvent.resolvedLimboDocuments.has(key)) { + promises.push(localStoreImpl.persistence.referenceDelegate.updateLimboDocument(txn, key)); + } + }); + // Each loop iteration only affects its "own" doc, so it's safe to get all + // the remote documents in advance in a single call. + promises.push(populateDocumentChangeBuffer(txn, documentBuffer, remoteEvent.documentUpdates).next(result => { + changedDocs = result.changedDocuments; + existenceChangedKeys = result.existenceChangedKeys; + })); + // HACK: The only reason we allow a null snapshot version is so that we + // can synthesize remote events when we get permission denied errors while + // trying to resolve the state of a locally cached document that is in + // limbo. + if (!remoteVersion.isEqual(SnapshotVersion.min())) { + const updateRemoteVersion = localStoreImpl.targetCache + .getLastRemoteSnapshotVersion(txn) + .next(lastRemoteSnapshotVersion => { + return localStoreImpl.targetCache.setTargetsMetadata(txn, txn.currentSequenceNumber, remoteVersion); + }); + promises.push(updateRemoteVersion); + } + return PersistencePromise.waitFor(promises) + .next(() => documentBuffer.apply(txn)) + .next(() => localStoreImpl.localDocuments.getLocalViewOfDocuments(txn, changedDocs, existenceChangedKeys)) + .next(() => changedDocs); + }) + .then(changedDocs => { + localStoreImpl.targetDataByTarget = newTargetDataByTargetMap; + return changedDocs; + }); +} +/** + * Populates document change buffer with documents from backend or a bundle. + * Returns the document changes resulting from applying those documents, and + * also a set of documents whose existence state are changed as a result. + * + * @param txn - Transaction to use to read existing documents from storage. + * @param documentBuffer - Document buffer to collect the resulted changes to be + * applied to storage. + * @param documents - Documents to be applied. + */ +function populateDocumentChangeBuffer(txn, documentBuffer, documents) { + let updatedKeys = documentKeySet(); + let existenceChangedKeys = documentKeySet(); + documents.forEach(k => (updatedKeys = updatedKeys.add(k))); + return documentBuffer.getEntries(txn, updatedKeys).next(existingDocs => { + let changedDocuments = mutableDocumentMap(); + documents.forEach((key, doc) => { + const existingDoc = existingDocs.get(key); + // Check if see if there is a existence state change for this document. + if (doc.isFoundDocument() !== existingDoc.isFoundDocument()) { + existenceChangedKeys = existenceChangedKeys.add(key); + } + // Note: The order of the steps below is important, since we want + // to ensure that rejected limbo resolutions (which fabricate + // NoDocuments with SnapshotVersion.min()) never add documents to + // cache. + if (doc.isNoDocument() && doc.version.isEqual(SnapshotVersion.min())) { + // NoDocuments with SnapshotVersion.min() are used in manufactured + // events. We remove these documents from cache since we lost + // access. + documentBuffer.removeEntry(key, doc.readTime); + changedDocuments = changedDocuments.insert(key, doc); + } + else if (!existingDoc.isValidDocument() || + doc.version.compareTo(existingDoc.version) > 0 || + (doc.version.compareTo(existingDoc.version) === 0 && + existingDoc.hasPendingWrites)) { + documentBuffer.addEntry(doc); + changedDocuments = changedDocuments.insert(key, doc); + } + else { + logDebug(LOG_TAG$b, 'Ignoring outdated watch update for ', key, '. Current version:', existingDoc.version, ' Watch version:', doc.version); + } + }); + return { changedDocuments, existenceChangedKeys }; + }); +} +/** + * Returns true if the newTargetData should be persisted during an update of + * an active target. TargetData should always be persisted when a target is + * being released and should not call this function. + * + * While the target is active, TargetData updates can be omitted when nothing + * about the target has changed except metadata like the resume token or + * snapshot version. Occasionally it's worth the extra write to prevent these + * values from getting too stale after a crash, but this doesn't have to be + * too frequent. + */ +function shouldPersistTargetData(oldTargetData, newTargetData, change) { + // Always persist target data if we don't already have a resume token. + if (oldTargetData.resumeToken.approximateByteSize() === 0) { + return true; + } + // Don't allow resume token changes to be buffered indefinitely. This + // allows us to be reasonably up-to-date after a crash and avoids needing + // to loop over all active queries on shutdown. Especially in the browser + // we may not get time to do anything interesting while the current tab is + // closing. + const timeDelta = newTargetData.snapshotVersion.toMicroseconds() - + oldTargetData.snapshotVersion.toMicroseconds(); + if (timeDelta >= RESUME_TOKEN_MAX_AGE_MICROS) { + return true; + } + // Otherwise if the only thing that has changed about a target is its resume + // token it's not worth persisting. Note that the RemoteStore keeps an + // in-memory view of the currently active targets which includes the current + // resume token, so stream failure or user changes will still use an + // up-to-date resume token regardless of what we do here. + const changes = change.addedDocuments.size + + change.modifiedDocuments.size + + change.removedDocuments.size; + return changes > 0; +} +/** + * Notifies local store of the changed views to locally pin documents. + */ +async function localStoreNotifyLocalViewChanges(localStore, viewChanges) { + const localStoreImpl = debugCast(localStore); + try { + await localStoreImpl.persistence.runTransaction('notifyLocalViewChanges', 'readwrite', txn => { + return PersistencePromise.forEach(viewChanges, (viewChange) => { + return PersistencePromise.forEach(viewChange.addedKeys, (key) => localStoreImpl.persistence.referenceDelegate.addReference(txn, viewChange.targetId, key)).next(() => PersistencePromise.forEach(viewChange.removedKeys, (key) => localStoreImpl.persistence.referenceDelegate.removeReference(txn, viewChange.targetId, key))); + }); + }); + } + catch (e) { + if (isIndexedDbTransactionError(e)) { + // If `notifyLocalViewChanges` fails, we did not advance the sequence + // number for the documents that were included in this transaction. + // This might trigger them to be deleted earlier than they otherwise + // would have, but it should not invalidate the integrity of the data. + logDebug(LOG_TAG$b, 'Failed to update sequence numbers: ' + e); + } + else { + throw e; + } + } + for (const viewChange of viewChanges) { + const targetId = viewChange.targetId; + if (!viewChange.fromCache) { + const targetData = localStoreImpl.targetDataByTarget.get(targetId); + // Advance the last limbo free snapshot version + const lastLimboFreeSnapshotVersion = targetData.snapshotVersion; + const updatedTargetData = targetData.withLastLimboFreeSnapshotVersion(lastLimboFreeSnapshotVersion); + localStoreImpl.targetDataByTarget = + localStoreImpl.targetDataByTarget.insert(targetId, updatedTargetData); + // TODO(b/272564316): Apply the optimization done on other platforms. + // This is a problem for web because saving the updated targetData from + // non-primary client conflicts with what primary client saved. + } + } +} +/** + * Gets the mutation batch after the passed in batchId in the mutation queue + * or null if empty. + * @param afterBatchId - If provided, the batch to search after. + * @returns The next mutation or null if there wasn't one. + */ +function localStoreGetNextMutationBatch(localStore, afterBatchId) { + const localStoreImpl = debugCast(localStore); + return localStoreImpl.persistence.runTransaction('Get next mutation batch', 'readonly', txn => { + if (afterBatchId === undefined) { + afterBatchId = BATCHID_UNKNOWN; + } + return localStoreImpl.mutationQueue.getNextMutationBatchAfterBatchId(txn, afterBatchId); + }); +} +/** + * Reads the current value of a Document with a given key or null if not + * found - used for testing. + */ +function localStoreReadDocument(localStore, key) { + const localStoreImpl = debugCast(localStore); + return localStoreImpl.persistence.runTransaction('read document', 'readonly', txn => localStoreImpl.localDocuments.getDocument(txn, key)); +} +/** + * Assigns the given target an internal ID so that its results can be pinned so + * they don't get GC'd. A target must be allocated in the local store before + * the store can be used to manage its view. + * + * Allocating an already allocated `Target` will return the existing `TargetData` + * for that `Target`. + */ +function localStoreAllocateTarget(localStore, target) { + const localStoreImpl = debugCast(localStore); + return localStoreImpl.persistence + .runTransaction('Allocate target', 'readwrite', txn => { + let targetData; + return localStoreImpl.targetCache + .getTargetData(txn, target) + .next((cached) => { + if (cached) { + // This target has been listened to previously, so reuse the + // previous targetID. + // TODO(mcg): freshen last accessed date? + targetData = cached; + return PersistencePromise.resolve(targetData); + } + else { + return localStoreImpl.targetCache + .allocateTargetId(txn) + .next(targetId => { + targetData = new TargetData(target, targetId, "TargetPurposeListen" /* TargetPurpose.Listen */, txn.currentSequenceNumber); + return localStoreImpl.targetCache + .addTargetData(txn, targetData) + .next(() => targetData); + }); + } + }); + }) + .then(targetData => { + // If Multi-Tab is enabled, the existing target data may be newer than + // the in-memory data + const cachedTargetData = localStoreImpl.targetDataByTarget.get(targetData.targetId); + if (cachedTargetData === null || + targetData.snapshotVersion.compareTo(cachedTargetData.snapshotVersion) > + 0) { + localStoreImpl.targetDataByTarget = + localStoreImpl.targetDataByTarget.insert(targetData.targetId, targetData); + localStoreImpl.targetIdByTarget.set(target, targetData.targetId); + } + return targetData; + }); +} +/** + * Returns the TargetData as seen by the LocalStore, including updates that may + * have not yet been persisted to the TargetCache. + */ +// Visible for testing. +function localStoreGetTargetData(localStore, transaction, target) { + const localStoreImpl = debugCast(localStore); + const targetId = localStoreImpl.targetIdByTarget.get(target); + if (targetId !== undefined) { + return PersistencePromise.resolve(localStoreImpl.targetDataByTarget.get(targetId)); + } + else { + return localStoreImpl.targetCache.getTargetData(transaction, target); + } +} +/** + * Unpins all the documents associated with the given target. If + * `keepPersistedTargetData` is set to false and Eager GC enabled, the method + * directly removes the associated target data from the target cache. + * + * Releasing a non-existing `Target` is a no-op. + */ +// PORTING NOTE: `keepPersistedTargetData` is multi-tab only. +async function localStoreReleaseTarget(localStore, targetId, keepPersistedTargetData) { + const localStoreImpl = debugCast(localStore); + const targetData = localStoreImpl.targetDataByTarget.get(targetId); + const mode = keepPersistedTargetData ? 'readwrite' : 'readwrite-primary'; + try { + if (!keepPersistedTargetData) { + await localStoreImpl.persistence.runTransaction('Release target', mode, txn => { + return localStoreImpl.persistence.referenceDelegate.removeTarget(txn, targetData); + }); + } + } + catch (e) { + if (isIndexedDbTransactionError(e)) { + // All `releaseTarget` does is record the final metadata state for the + // target, but we've been recording this periodically during target + // activity. If we lose this write this could cause a very slight + // difference in the order of target deletion during GC, but we + // don't define exact LRU semantics so this is acceptable. + logDebug(LOG_TAG$b, `Failed to update sequence numbers for target ${targetId}: ${e}`); + } + else { + throw e; + } + } + localStoreImpl.targetDataByTarget = + localStoreImpl.targetDataByTarget.remove(targetId); + localStoreImpl.targetIdByTarget.delete(targetData.target); +} +/** + * Runs the specified query against the local store and returns the results, + * potentially taking advantage of query data from previous executions (such + * as the set of remote keys). + * + * @param usePreviousResults - Whether results from previous executions can + * be used to optimize this query execution. + */ +function localStoreExecuteQuery(localStore, query, usePreviousResults) { + const localStoreImpl = debugCast(localStore); + let lastLimboFreeSnapshotVersion = SnapshotVersion.min(); + let remoteKeys = documentKeySet(); + return localStoreImpl.persistence.runTransaction('Execute query', 'readwrite', // Use readwrite instead of readonly so indexes can be created + // Use readwrite instead of readonly so indexes can be created + txn => { + return localStoreGetTargetData(localStoreImpl, txn, queryToTarget(query)) + .next(targetData => { + if (targetData) { + lastLimboFreeSnapshotVersion = + targetData.lastLimboFreeSnapshotVersion; + return localStoreImpl.targetCache + .getMatchingKeysForTargetId(txn, targetData.targetId) + .next(result => { + remoteKeys = result; + }); + } + }) + .next(() => localStoreImpl.queryEngine.getDocumentsMatchingQuery(txn, query, usePreviousResults + ? lastLimboFreeSnapshotVersion + : SnapshotVersion.min(), usePreviousResults ? remoteKeys : documentKeySet())) + .next(documents => { + setMaxReadTime(localStoreImpl, queryCollectionGroup(query), documents); + return { documents, remoteKeys }; + }); + }); +} +function applyWriteToRemoteDocuments(localStoreImpl, txn, batchResult, documentBuffer) { + const batch = batchResult.batch; + const docKeys = batch.keys(); + let promiseChain = PersistencePromise.resolve(); + docKeys.forEach(docKey => { + promiseChain = promiseChain + .next(() => documentBuffer.getEntry(txn, docKey)) + .next(doc => { + const ackVersion = batchResult.docVersions.get(docKey); + hardAssert(ackVersion !== null, 0xbd9d); + if (doc.version.compareTo(ackVersion) < 0) { + batch.applyToRemoteDocument(doc, batchResult); + if (doc.isValidDocument()) { + // We use the commitVersion as the readTime rather than the + // document's updateTime since the updateTime is not advanced + // for updates that do not modify the underlying document. + doc.setReadTime(batchResult.commitVersion); + documentBuffer.addEntry(doc); + } + } + }); + }); + return promiseChain.next(() => localStoreImpl.mutationQueue.removeMutationBatch(txn, batch)); +} +/** Returns the local view of the documents affected by a mutation batch. */ +// PORTING NOTE: Multi-Tab only. +function localStoreLookupMutationDocuments(localStore, batchId) { + const localStoreImpl = debugCast(localStore); + const mutationQueueImpl = debugCast(localStoreImpl.mutationQueue); + return localStoreImpl.persistence.runTransaction('Lookup mutation documents', 'readonly', txn => { + return mutationQueueImpl.lookupMutationKeys(txn, batchId).next(keys => { + if (keys) { + return localStoreImpl.localDocuments.getDocuments(txn, keys); + } + else { + return PersistencePromise.resolve(null); + } + }); + }); +} +// PORTING NOTE: Multi-Tab only. +function localStoreRemoveCachedMutationBatchMetadata(localStore, batchId) { + const mutationQueueImpl = debugCast(debugCast(localStore, LocalStoreImpl).mutationQueue); + mutationQueueImpl.removeCachedMutationKeys(batchId); +} +// PORTING NOTE: Multi-Tab only. +function localStoreGetActiveClients(localStore) { + const persistenceImpl = debugCast(debugCast(localStore, LocalStoreImpl).persistence); + return persistenceImpl.getActiveClients(); +} +// PORTING NOTE: Multi-Tab only. +function localStoreGetCachedTarget(localStore, targetId) { + const localStoreImpl = debugCast(localStore); + const targetCacheImpl = debugCast(localStoreImpl.targetCache); + const cachedTargetData = localStoreImpl.targetDataByTarget.get(targetId); + if (cachedTargetData) { + return Promise.resolve(cachedTargetData.target); + } + else { + return localStoreImpl.persistence.runTransaction('Get target data', 'readonly', txn => { + return targetCacheImpl + .getTargetDataForTarget(txn, targetId) + .next(targetData => (targetData ? targetData.target : null)); + }); + } +} +/** + * Returns the set of documents that have been updated since the last call. + * If this is the first call, returns the set of changes since client + * initialization. Further invocations will return document that have changed + * since the prior call. + */ +// PORTING NOTE: Multi-Tab only. +function localStoreGetNewDocumentChanges(localStore, collectionGroup) { + const localStoreImpl = debugCast(localStore); + // Get the current maximum read time for the collection. This should always + // exist, but to reduce the chance for regressions we default to + // SnapshotVersion.Min() + // TODO(indexing): Consider removing the default value. + const readTime = localStoreImpl.collectionGroupReadTime.get(collectionGroup) || + SnapshotVersion.min(); + return localStoreImpl.persistence + .runTransaction('Get new document changes', 'readonly', txn => localStoreImpl.remoteDocuments.getAllFromCollectionGroup(txn, collectionGroup, newIndexOffsetSuccessorFromReadTime(readTime, INITIAL_LARGEST_BATCH_ID), + /* limit= */ Number.MAX_SAFE_INTEGER)) + .then(changedDocs => { + setMaxReadTime(localStoreImpl, collectionGroup, changedDocs); + return changedDocs; + }); +} +/** Sets the collection group's maximum read time from the given documents. */ +// PORTING NOTE: Multi-Tab only. +function setMaxReadTime(localStoreImpl, collectionGroup, changedDocs) { + let readTime = localStoreImpl.collectionGroupReadTime.get(collectionGroup) || + SnapshotVersion.min(); + changedDocs.forEach((_, doc) => { + if (doc.readTime.compareTo(readTime) > 0) { + readTime = doc.readTime; + } + }); + localStoreImpl.collectionGroupReadTime.set(collectionGroup, readTime); +} +/** + * Creates a new target using the given bundle name, which will be used to + * hold the keys of all documents from the bundle in query-document mappings. + * This ensures that the loaded documents do not get garbage collected + * right away. + */ +function umbrellaTarget(bundleName) { + // It is OK that the path used for the query is not valid, because this will + // not be read and queried. + return queryToTarget(newQueryForPath(ResourcePath.fromString(`__bundle__/docs/${bundleName}`))); +} +/** + * Applies the documents from a bundle to the "ground-state" (remote) + * documents. + * + * LocalDocuments are re-calculated if there are remaining mutations in the + * queue. + */ +async function localStoreApplyBundledDocuments(localStore, bundleConverter, documents, bundleName) { + const localStoreImpl = debugCast(localStore); + let documentKeys = documentKeySet(); + let documentMap = mutableDocumentMap(); + for (const bundleDoc of documents) { + const documentKey = bundleConverter.toDocumentKey(bundleDoc.metadata.name); + if (bundleDoc.document) { + documentKeys = documentKeys.add(documentKey); + } + const doc = bundleConverter.toMutableDocument(bundleDoc); + doc.setReadTime(bundleConverter.toSnapshotVersion(bundleDoc.metadata.readTime)); + documentMap = documentMap.insert(documentKey, doc); + } + const documentBuffer = localStoreImpl.remoteDocuments.newChangeBuffer({ + trackRemovals: true // Make sure document removals show up in `getNewDocumentChanges()` + }); + // Allocates a target to hold all document keys from the bundle, such that + // they will not get garbage collected right away. + const umbrellaTargetData = await localStoreAllocateTarget(localStoreImpl, umbrellaTarget(bundleName)); + return localStoreImpl.persistence.runTransaction('Apply bundle documents', 'readwrite', txn => { + return populateDocumentChangeBuffer(txn, documentBuffer, documentMap) + .next(documentChangeResult => { + documentBuffer.apply(txn); + return documentChangeResult; + }) + .next(documentChangeResult => { + return localStoreImpl.targetCache + .removeMatchingKeysForTargetId(txn, umbrellaTargetData.targetId) + .next(() => localStoreImpl.targetCache.addMatchingKeys(txn, documentKeys, umbrellaTargetData.targetId)) + .next(() => localStoreImpl.localDocuments.getLocalViewOfDocuments(txn, documentChangeResult.changedDocuments, documentChangeResult.existenceChangedKeys)) + .next(() => documentChangeResult.changedDocuments); + }); + }); +} +/** + * Returns a promise of a boolean to indicate if the given bundle has already + * been loaded and the create time is newer than the current loading bundle. + */ +function localStoreHasNewerBundle(localStore, bundleMetadata) { + const localStoreImpl = debugCast(localStore); + const currentReadTime = fromVersion(bundleMetadata.createTime); + return localStoreImpl.persistence + .runTransaction('hasNewerBundle', 'readonly', transaction => { + return localStoreImpl.bundleCache.getBundleMetadata(transaction, bundleMetadata.id); + }) + .then(cached => { + return !!cached && cached.createTime.compareTo(currentReadTime) >= 0; + }); +} +/** + * Saves the given `BundleMetadata` to local persistence. + */ +function localStoreSaveBundle(localStore, bundleMetadata) { + const localStoreImpl = debugCast(localStore); + return localStoreImpl.persistence.runTransaction('Save bundle', 'readwrite', transaction => { + return localStoreImpl.bundleCache.saveBundleMetadata(transaction, bundleMetadata); + }); +} +/** + * Returns a promise of a `NamedQuery` associated with given query name. Promise + * resolves to undefined if no persisted data can be found. + */ +function localStoreGetNamedQuery(localStore, queryName) { + const localStoreImpl = debugCast(localStore); + return localStoreImpl.persistence.runTransaction('Get named query', 'readonly', transaction => localStoreImpl.bundleCache.getNamedQuery(transaction, queryName)); +} +/** + * Saves the given `NamedQuery` to local persistence. + */ +async function localStoreSaveNamedQuery(localStore, query, documents = documentKeySet()) { + // Allocate a target for the named query such that it can be resumed + // from associated read time if users use it to listen. + // NOTE: this also means if no corresponding target exists, the new target + // will remain active and will not get collected, unless users happen to + // unlisten the query somehow. + const allocated = await localStoreAllocateTarget(localStore, queryToTarget(fromBundledQuery(query.bundledQuery))); + const localStoreImpl = debugCast(localStore); + return localStoreImpl.persistence.runTransaction('Save named query', 'readwrite', transaction => { + const readTime = fromVersion(query.readTime); + // Simply save the query itself if it is older than what the SDK already + // has. + if (allocated.snapshotVersion.compareTo(readTime) >= 0) { + return localStoreImpl.bundleCache.saveNamedQuery(transaction, query); + } + // Update existing target data because the query from the bundle is newer. + const newTargetData = allocated.withResumeToken(ByteString.EMPTY_BYTE_STRING, readTime); + localStoreImpl.targetDataByTarget = + localStoreImpl.targetDataByTarget.insert(newTargetData.targetId, newTargetData); + return localStoreImpl.targetCache + .updateTargetData(transaction, newTargetData) + .next(() => localStoreImpl.targetCache.removeMatchingKeysForTargetId(transaction, allocated.targetId)) + .next(() => localStoreImpl.targetCache.addMatchingKeys(transaction, documents, allocated.targetId)) + .next(() => localStoreImpl.bundleCache.saveNamedQuery(transaction, query)); + }); +} +async function localStoreConfigureFieldIndexes(localStore, newFieldIndexes) { + const localStoreImpl = debugCast(localStore); + const indexManager = localStoreImpl.indexManager; + const promises = []; + return localStoreImpl.persistence.runTransaction('Configure indexes', 'readwrite', transaction => indexManager + .getFieldIndexes(transaction) + .next(oldFieldIndexes => diffArrays(oldFieldIndexes, newFieldIndexes, fieldIndexSemanticComparator, fieldIndex => { + promises.push(indexManager.addFieldIndex(transaction, fieldIndex)); + }, fieldIndex => { + promises.push(indexManager.deleteFieldIndex(transaction, fieldIndex)); + })) + .next(() => PersistencePromise.waitFor(promises))); +} +function localStoreSetIndexAutoCreationEnabled(localStore, isEnabled) { + const localStoreImpl = debugCast(localStore); + localStoreImpl.queryEngine.indexAutoCreationEnabled = isEnabled; +} +function localStoreDeleteAllFieldIndexes(localStore) { + const localStoreImpl = debugCast(localStore); + const indexManager = localStoreImpl.indexManager; + return localStoreImpl.persistence.runTransaction('Delete All Indexes', 'readwrite', transaction => indexManager.deleteAllFieldIndexes(transaction)); +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A tracker to keep a record of important details during database local query + * execution. + */ +class QueryContext { + constructor() { + /** + * Counts the number of documents passed through during local query execution. + */ + this._documentReadCount = 0; + } + get documentReadCount() { + return this._documentReadCount; + } + incrementDocumentReadCount(amount) { + this._documentReadCount += amount; + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const DEFAULT_INDEX_AUTO_CREATION_MIN_COLLECTION_SIZE = 100; +/** + * This cost represents the evaluation result of + * (([index, docKey] + [docKey, docContent]) per document in the result set) + * / ([docKey, docContent] per documents in full collection scan) coming from + * experiment [enter PR experiment URL here]. + */ +function getDefaultRelativeIndexReadCostPerDocument() { + // These values were derived from an experiment where several members of the + // Firestore SDK team ran a performance test in various environments. + // Googlers can see b/299284287 for details. + if (isSafari()) { + return 8; + } + else if (getAndroidVersion(getUA()) > 0) { + return 6; + } + else { + return 4; + } +} +/** + * The Firestore query engine. + * + * Firestore queries can be executed in three modes. The Query Engine determines + * what mode to use based on what data is persisted. The mode only determines + * the runtime complexity of the query - the result set is equivalent across all + * implementations. + * + * The Query engine will use indexed-based execution if a user has configured + * any index that can be used to execute query (via `setIndexConfiguration()`). + * Otherwise, the engine will try to optimize the query by re-using a previously + * persisted query result. If that is not possible, the query will be executed + * via a full collection scan. + * + * Index-based execution is the default when available. The query engine + * supports partial indexed execution and merges the result from the index + * lookup with documents that have not yet been indexed. The index evaluation + * matches the backend's format and as such, the SDK can use indexing for all + * queries that the backend supports. + * + * If no index exists, the query engine tries to take advantage of the target + * document mapping in the TargetCache. These mappings exists for all queries + * that have been synced with the backend at least once and allow the query + * engine to only read documents that previously matched a query plus any + * documents that were edited after the query was last listened to. + * + * There are some cases when this optimization is not guaranteed to produce + * the same results as full collection scans. In these cases, query + * processing falls back to full scans. These cases are: + * + * - Limit queries where a document that matched the query previously no longer + * matches the query. + * + * - Limit queries where a document edit may cause the document to sort below + * another document that is in the local cache. + * + * - Queries that have never been CURRENT or free of limbo documents. + */ +class QueryEngine { + constructor() { + this.initialized = false; + this.indexAutoCreationEnabled = false; + /** + * SDK only decides whether it should create index when collection size is + * larger than this. + */ + this.indexAutoCreationMinCollectionSize = DEFAULT_INDEX_AUTO_CREATION_MIN_COLLECTION_SIZE; + this.relativeIndexReadCostPerDocument = getDefaultRelativeIndexReadCostPerDocument(); + } + /** Sets the document view to query against. */ + initialize(localDocuments, indexManager) { + this.localDocumentsView = localDocuments; + this.indexManager = indexManager; + this.initialized = true; + } + /** Returns all local documents matching the specified query. */ + getDocumentsMatchingQuery(transaction, query, lastLimboFreeSnapshotVersion, remoteKeys) { + // Stores the result from executing the query; using this object is more + // convenient than passing the result between steps of the persistence + // transaction and improves readability comparatively. + const queryResult = { result: null }; + return this.performQueryUsingIndex(transaction, query) + .next(result => { + queryResult.result = result; + }) + .next(() => { + if (queryResult.result) { + return; + } + return this.performQueryUsingRemoteKeys(transaction, query, remoteKeys, lastLimboFreeSnapshotVersion).next(result => { + queryResult.result = result; + }); + }) + .next(() => { + if (queryResult.result) { + return; + } + const context = new QueryContext(); + return this.executeFullCollectionScan(transaction, query, context).next(result => { + queryResult.result = result; + if (this.indexAutoCreationEnabled) { + return this.createCacheIndexes(transaction, query, context, result.size); + } + }); + }) + .next(() => queryResult.result); + } + createCacheIndexes(transaction, query, context, resultSize) { + if (context.documentReadCount < this.indexAutoCreationMinCollectionSize) { + if (getLogLevel() <= LogLevel.DEBUG) { + logDebug('QueryEngine', 'SDK will not create cache indexes for query:', stringifyQuery(query), 'since it only creates cache indexes for collection contains', 'more than or equal to', this.indexAutoCreationMinCollectionSize, 'documents'); + } + return PersistencePromise.resolve(); + } + if (getLogLevel() <= LogLevel.DEBUG) { + logDebug('QueryEngine', 'Query:', stringifyQuery(query), 'scans', context.documentReadCount, 'local documents and returns', resultSize, 'documents as results.'); + } + if (context.documentReadCount > + this.relativeIndexReadCostPerDocument * resultSize) { + if (getLogLevel() <= LogLevel.DEBUG) { + logDebug('QueryEngine', 'The SDK decides to create cache indexes for query:', stringifyQuery(query), 'as using cache indexes may help improve performance.'); + } + return this.indexManager.createTargetIndexes(transaction, queryToTarget(query)); + } + return PersistencePromise.resolve(); + } + /** + * Performs an indexed query that evaluates the query based on a collection's + * persisted index values. Returns `null` if an index is not available. + */ + performQueryUsingIndex(transaction, query) { + if (queryMatchesAllDocuments(query)) { + // Queries that match all documents don't benefit from using + // key-based lookups. It is more efficient to scan all documents in a + // collection, rather than to perform individual lookups. + return PersistencePromise.resolve(null); + } + let target = queryToTarget(query); + return this.indexManager + .getIndexType(transaction, target) + .next(indexType => { + if (indexType === 0 /* IndexType.NONE */) { + // The target cannot be served from any index. + return null; + } + if (query.limit !== null && indexType === 1 /* IndexType.PARTIAL */) { + // We cannot apply a limit for targets that are served using a partial + // index. If a partial index will be used to serve the target, the + // query may return a superset of documents that match the target + // (e.g. if the index doesn't include all the target's filters), or + // may return the correct set of documents in the wrong order (e.g. if + // the index doesn't include a segment for one of the orderBys). + // Therefore, a limit should not be applied in such cases. + query = queryWithLimit(query, null, "F" /* LimitType.First */); + target = queryToTarget(query); + } + return this.indexManager + .getDocumentsMatchingTarget(transaction, target) + .next(keys => { + const sortedKeys = documentKeySet(...keys); + return this.localDocumentsView + .getDocuments(transaction, sortedKeys) + .next(indexedDocuments => { + return this.indexManager + .getMinOffset(transaction, target) + .next(offset => { + const previousResults = this.applyQuery(query, indexedDocuments); + if (this.needsRefill(query, previousResults, sortedKeys, offset.readTime)) { + // A limit query whose boundaries change due to local + // edits can be re-run against the cache by excluding the + // limit. This ensures that all documents that match the + // query's filters are included in the result set. The SDK + // can then apply the limit once all local edits are + // incorporated. + return this.performQueryUsingIndex(transaction, queryWithLimit(query, null, "F" /* LimitType.First */)); + } + return this.appendRemainingResults(transaction, previousResults, query, offset); + }); + }); + }); + }); + } + /** + * Performs a query based on the target's persisted query mapping. Returns + * `null` if the mapping is not available or cannot be used. + */ + performQueryUsingRemoteKeys(transaction, query, remoteKeys, lastLimboFreeSnapshotVersion) { + if (queryMatchesAllDocuments(query)) { + // Queries that match all documents don't benefit from using + // key-based lookups. It is more efficient to scan all documents in a + // collection, rather than to perform individual lookups. + return PersistencePromise.resolve(null); + } + // Queries that have never seen a snapshot without limbo free documents + // should also be run as a full collection scan. + if (lastLimboFreeSnapshotVersion.isEqual(SnapshotVersion.min())) { + return PersistencePromise.resolve(null); + } + return this.localDocumentsView.getDocuments(transaction, remoteKeys).next(documents => { + const previousResults = this.applyQuery(query, documents); + if (this.needsRefill(query, previousResults, remoteKeys, lastLimboFreeSnapshotVersion)) { + return PersistencePromise.resolve(null); + } + if (getLogLevel() <= LogLevel.DEBUG) { + logDebug('QueryEngine', 'Re-using previous result from %s to execute query: %s', lastLimboFreeSnapshotVersion.toString(), stringifyQuery(query)); + } + // Retrieve all results for documents that were updated since the last + // limbo-document free remote snapshot. + return this.appendRemainingResults(transaction, previousResults, query, newIndexOffsetSuccessorFromReadTime(lastLimboFreeSnapshotVersion, INITIAL_LARGEST_BATCH_ID)).next(results => results); + }); + } + /** Applies the query filter and sorting to the provided documents. */ + applyQuery(query, documents) { + // Sort the documents and re-apply the query filter since previously + // matching documents do not necessarily still match the query. + let queryResults = new SortedSet(newQueryComparator(query)); + documents.forEach((_, maybeDoc) => { + if (queryMatches(query, maybeDoc)) { + queryResults = queryResults.add(maybeDoc); + } + }); + return queryResults; + } + /** + * Determines if a limit query needs to be refilled from cache, making it + * ineligible for index-free execution. + * + * @param query - The query. + * @param sortedPreviousResults - The documents that matched the query when it + * was last synchronized, sorted by the query's comparator. + * @param remoteKeys - The document keys that matched the query at the last + * snapshot. + * @param limboFreeSnapshotVersion - The version of the snapshot when the + * query was last synchronized. + */ + needsRefill(query, sortedPreviousResults, remoteKeys, limboFreeSnapshotVersion) { + if (query.limit === null) { + // Queries without limits do not need to be refilled. + return false; + } + if (remoteKeys.size !== sortedPreviousResults.size) { + // The query needs to be refilled if a previously matching document no + // longer matches. + return true; + } + // Limit queries are not eligible for index-free query execution if there is + // a potential that an older document from cache now sorts before a document + // that was previously part of the limit. This, however, can only happen if + // the document at the edge of the limit goes out of limit. + // If a document that is not the limit boundary sorts differently, + // the boundary of the limit itself did not change and documents from cache + // will continue to be "rejected" by this boundary. Therefore, we can ignore + // any modifications that don't affect the last document. + const docAtLimitEdge = query.limitType === "F" /* LimitType.First */ + ? sortedPreviousResults.last() + : sortedPreviousResults.first(); + if (!docAtLimitEdge) { + // We don't need to refill the query if there were already no documents. + return false; + } + return (docAtLimitEdge.hasPendingWrites || + docAtLimitEdge.version.compareTo(limboFreeSnapshotVersion) > 0); + } + executeFullCollectionScan(transaction, query, context) { + if (getLogLevel() <= LogLevel.DEBUG) { + logDebug('QueryEngine', 'Using full collection scan to execute query:', stringifyQuery(query)); + } + return this.localDocumentsView.getDocumentsMatchingQuery(transaction, query, IndexOffset.min(), context); + } + /** + * Combines the results from an indexed execution with the remaining documents + * that have not yet been indexed. + */ + appendRemainingResults(transaction, indexedResults, query, offset) { + // Retrieve all results for documents that were updated since the offset. + return this.localDocumentsView + .getDocumentsMatchingQuery(transaction, query, offset) + .next(remainingResults => { + // Merge with existing results + indexedResults.forEach(d => { + remainingResults = remainingResults.insert(d.key, d); + }); + return remainingResults; + }); + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// The format of the LocalStorage key that stores the client state is: +// firestore_clients__ +const CLIENT_STATE_KEY_PREFIX = 'firestore_clients'; +/** Assembles the key for a client state in WebStorage */ +function createWebStorageClientStateKey(persistenceKey, clientId) { + return `${CLIENT_STATE_KEY_PREFIX}_${persistenceKey}_${clientId}`; +} +// The format of the WebStorage key that stores the mutation state is: +// firestore_mutations__ +// (for unauthenticated users) +// or: firestore_mutations___ +// +// 'user_uid' is last to avoid needing to escape '_' characters that it might +// contain. +const MUTATION_BATCH_KEY_PREFIX = 'firestore_mutations'; +/** Assembles the key for a mutation batch in WebStorage */ +function createWebStorageMutationBatchKey(persistenceKey, user, batchId) { + let mutationKey = `${MUTATION_BATCH_KEY_PREFIX}_${persistenceKey}_${batchId}`; + if (user.isAuthenticated()) { + mutationKey += `_${user.uid}`; + } + return mutationKey; +} +// The format of the WebStorage key that stores a query target's metadata is: +// firestore_targets__ +const QUERY_TARGET_KEY_PREFIX = 'firestore_targets'; +/** Assembles the key for a query state in WebStorage */ +function createWebStorageQueryTargetMetadataKey(persistenceKey, targetId) { + return `${QUERY_TARGET_KEY_PREFIX}_${persistenceKey}_${targetId}`; +} +// The WebStorage prefix that stores the primary tab's online state. The +// format of the key is: +// firestore_online_state_ +const ONLINE_STATE_KEY_PREFIX = 'firestore_online_state'; +/** Assembles the key for the online state of the primary tab. */ +function createWebStorageOnlineStateKey(persistenceKey) { + return `${ONLINE_STATE_KEY_PREFIX}_${persistenceKey}`; +} +// The WebStorage prefix that plays as a event to indicate the remote documents +// might have changed due to some secondary tabs loading a bundle. +// format of the key is: +// firestore_bundle_loaded_v2_ +// The version ending with "v2" stores the list of modified collection groups. +const BUNDLE_LOADED_KEY_PREFIX = 'firestore_bundle_loaded_v2'; +function createBundleLoadedKey(persistenceKey) { + return `${BUNDLE_LOADED_KEY_PREFIX}_${persistenceKey}`; +} +// The WebStorage key prefix for the key that stores the last sequence number allocated. The key +// looks like 'firestore_sequence_number_'. +const SEQUENCE_NUMBER_KEY_PREFIX = 'firestore_sequence_number'; +/** Assembles the key for the current sequence number. */ +function createWebStorageSequenceNumberKey(persistenceKey) { + return `${SEQUENCE_NUMBER_KEY_PREFIX}_${persistenceKey}`; +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$a = 'SharedClientState'; +/** + * Holds the state of a mutation batch, including its user ID, batch ID and + * whether the batch is 'pending', 'acknowledged' or 'rejected'. + */ +// Visible for testing +class MutationMetadata { + constructor(user, batchId, state, error) { + this.user = user; + this.batchId = batchId; + this.state = state; + this.error = error; + } + /** + * Parses a MutationMetadata from its JSON representation in WebStorage. + * Logs a warning and returns null if the format of the data is not valid. + */ + static fromWebStorageEntry(user, batchId, value) { + const mutationBatch = JSON.parse(value); + let validData = typeof mutationBatch === 'object' && + ['pending', 'acknowledged', 'rejected'].indexOf(mutationBatch.state) !== + -1 && + (mutationBatch.error === undefined || + typeof mutationBatch.error === 'object'); + let firestoreError = undefined; + if (validData && mutationBatch.error) { + validData = + typeof mutationBatch.error.message === 'string' && + typeof mutationBatch.error.code === 'string'; + if (validData) { + firestoreError = new FirestoreError(mutationBatch.error.code, mutationBatch.error.message); + } + } + if (validData) { + return new MutationMetadata(user, batchId, mutationBatch.state, firestoreError); + } + else { + logError(LOG_TAG$a, `Failed to parse mutation state for ID '${batchId}': ${value}`); + return null; + } + } + toWebStorageJSON() { + const batchMetadata = { + state: this.state, + updateTimeMs: Date.now() // Modify the existing value to trigger update. + }; + if (this.error) { + batchMetadata.error = { + code: this.error.code, + message: this.error.message + }; + } + return JSON.stringify(batchMetadata); + } +} +/** + * Holds the state of a query target, including its target ID and whether the + * target is 'not-current', 'current' or 'rejected'. + */ +// Visible for testing +class QueryTargetMetadata { + constructor(targetId, state, error) { + this.targetId = targetId; + this.state = state; + this.error = error; + } + /** + * Parses a QueryTargetMetadata from its JSON representation in WebStorage. + * Logs a warning and returns null if the format of the data is not valid. + */ + static fromWebStorageEntry(targetId, value) { + const targetState = JSON.parse(value); + let validData = typeof targetState === 'object' && + ['not-current', 'current', 'rejected'].indexOf(targetState.state) !== + -1 && + (targetState.error === undefined || + typeof targetState.error === 'object'); + let firestoreError = undefined; + if (validData && targetState.error) { + validData = + typeof targetState.error.message === 'string' && + typeof targetState.error.code === 'string'; + if (validData) { + firestoreError = new FirestoreError(targetState.error.code, targetState.error.message); + } + } + if (validData) { + return new QueryTargetMetadata(targetId, targetState.state, firestoreError); + } + else { + logError(LOG_TAG$a, `Failed to parse target state for ID '${targetId}': ${value}`); + return null; + } + } + toWebStorageJSON() { + const targetState = { + state: this.state, + updateTimeMs: Date.now() // Modify the existing value to trigger update. + }; + if (this.error) { + targetState.error = { + code: this.error.code, + message: this.error.message + }; + } + return JSON.stringify(targetState); + } +} +/** + * This class represents the immutable ClientState for a client read from + * WebStorage, containing the list of active query targets. + */ +class RemoteClientState { + constructor(clientId, activeTargetIds) { + this.clientId = clientId; + this.activeTargetIds = activeTargetIds; + } + /** + * Parses a RemoteClientState from the JSON representation in WebStorage. + * Logs a warning and returns null if the format of the data is not valid. + */ + static fromWebStorageEntry(clientId, value) { + const clientState = JSON.parse(value); + let validData = typeof clientState === 'object' && + clientState.activeTargetIds instanceof Array; + let activeTargetIdsSet = targetIdSet(); + for (let i = 0; validData && i < clientState.activeTargetIds.length; ++i) { + validData = isSafeInteger(clientState.activeTargetIds[i]); + activeTargetIdsSet = activeTargetIdsSet.add(clientState.activeTargetIds[i]); + } + if (validData) { + return new RemoteClientState(clientId, activeTargetIdsSet); + } + else { + logError(LOG_TAG$a, `Failed to parse client data for instance '${clientId}': ${value}`); + return null; + } + } +} +/** + * This class represents the online state for all clients participating in + * multi-tab. The online state is only written to by the primary client, and + * used in secondary clients to update their query views. + */ +class SharedOnlineState { + constructor(clientId, onlineState) { + this.clientId = clientId; + this.onlineState = onlineState; + } + /** + * Parses a SharedOnlineState from its JSON representation in WebStorage. + * Logs a warning and returns null if the format of the data is not valid. + */ + static fromWebStorageEntry(value) { + const onlineState = JSON.parse(value); + const validData = typeof onlineState === 'object' && + ['Unknown', 'Online', 'Offline'].indexOf(onlineState.onlineState) !== + -1 && + typeof onlineState.clientId === 'string'; + if (validData) { + return new SharedOnlineState(onlineState.clientId, onlineState.onlineState); + } + else { + logError(LOG_TAG$a, `Failed to parse online state: ${value}`); + return null; + } + } +} +/** + * Metadata state of the local client. Unlike `RemoteClientState`, this class is + * mutable and keeps track of all pending mutations, which allows us to + * update the range of pending mutation batch IDs as new mutations are added or + * removed. + * + * The data in `LocalClientState` is not read from WebStorage and instead + * updated via its instance methods. The updated state can be serialized via + * `toWebStorageJSON()`. + */ +// Visible for testing. +class LocalClientState { + constructor() { + this.activeTargetIds = targetIdSet(); + } + addQueryTarget(targetId) { + this.activeTargetIds = this.activeTargetIds.add(targetId); + } + removeQueryTarget(targetId) { + this.activeTargetIds = this.activeTargetIds.delete(targetId); + } + /** + * Converts this entry into a JSON-encoded format we can use for WebStorage. + * Does not encode `clientId` as it is part of the key in WebStorage. + */ + toWebStorageJSON() { + const data = { + activeTargetIds: this.activeTargetIds.toArray(), + updateTimeMs: Date.now() // Modify the existing value to trigger update. + }; + return JSON.stringify(data); + } +} +/** + * `WebStorageSharedClientState` uses WebStorage (window.localStorage) as the + * backing store for the SharedClientState. It keeps track of all active + * clients and supports modifications of the local client's data. + */ +class WebStorageSharedClientState { + constructor(window, queue, persistenceKey, localClientId, initialUser) { + this.window = window; + this.queue = queue; + this.persistenceKey = persistenceKey; + this.localClientId = localClientId; + this.syncEngine = null; + this.onlineStateHandler = null; + this.sequenceNumberHandler = null; + this.storageListener = this.handleWebStorageEvent.bind(this); + this.activeClients = new SortedMap(primitiveComparator); + this.started = false; + /** + * Captures WebStorage events that occur before `start()` is called. These + * events are replayed once `WebStorageSharedClientState` is started. + */ + this.earlyEvents = []; + // Escape the special characters mentioned here: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions + const escapedPersistenceKey = persistenceKey.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + this.storage = this.window.localStorage; + this.currentUser = initialUser; + this.localClientStorageKey = createWebStorageClientStateKey(this.persistenceKey, this.localClientId); + this.sequenceNumberKey = createWebStorageSequenceNumberKey(this.persistenceKey); + this.activeClients = this.activeClients.insert(this.localClientId, new LocalClientState()); + this.clientStateKeyRe = new RegExp(`^${CLIENT_STATE_KEY_PREFIX}_${escapedPersistenceKey}_([^_]*)$`); + this.mutationBatchKeyRe = new RegExp(`^${MUTATION_BATCH_KEY_PREFIX}_${escapedPersistenceKey}_(\\d+)(?:_(.*))?$`); + this.queryTargetKeyRe = new RegExp(`^${QUERY_TARGET_KEY_PREFIX}_${escapedPersistenceKey}_(\\d+)$`); + this.onlineStateKey = createWebStorageOnlineStateKey(this.persistenceKey); + this.bundleLoadedKey = createBundleLoadedKey(this.persistenceKey); + // Rather than adding the storage observer during start(), we add the + // storage observer during initialization. This ensures that we collect + // events before other components populate their initial state (during their + // respective start() calls). Otherwise, we might for example miss a + // mutation that is added after LocalStore's start() processed the existing + // mutations but before we observe WebStorage events. + this.window.addEventListener('storage', this.storageListener); + } + /** Returns 'true' if WebStorage is available in the current environment. */ + static isAvailable(window) { + return !!(window && window.localStorage); + } + async start() { + // Retrieve the list of existing clients to backfill the data in + // SharedClientState. + const existingClients = await this.syncEngine.getActiveClients(); + for (const clientId of existingClients) { + if (clientId === this.localClientId) { + continue; + } + const storageItem = this.getItem(createWebStorageClientStateKey(this.persistenceKey, clientId)); + if (storageItem) { + const clientState = RemoteClientState.fromWebStorageEntry(clientId, storageItem); + if (clientState) { + this.activeClients = this.activeClients.insert(clientState.clientId, clientState); + } + } + } + this.persistClientState(); + // Check if there is an existing online state and call the callback handler + // if applicable. + const onlineStateJSON = this.storage.getItem(this.onlineStateKey); + if (onlineStateJSON) { + const onlineState = this.fromWebStorageOnlineState(onlineStateJSON); + if (onlineState) { + this.handleOnlineStateEvent(onlineState); + } + } + for (const event of this.earlyEvents) { + this.handleWebStorageEvent(event); + } + this.earlyEvents = []; + // Register a window unload hook to remove the client metadata entry from + // WebStorage even if `shutdown()` was not called. + this.window.addEventListener('pagehide', () => this.shutdown()); + this.started = true; + } + writeSequenceNumber(sequenceNumber) { + this.setItem(this.sequenceNumberKey, JSON.stringify(sequenceNumber)); + } + getAllActiveQueryTargets() { + return this.extractActiveQueryTargets(this.activeClients); + } + isActiveQueryTarget(targetId) { + let found = false; + this.activeClients.forEach((key, value) => { + if (value.activeTargetIds.has(targetId)) { + found = true; + } + }); + return found; + } + addPendingMutation(batchId) { + this.persistMutationState(batchId, 'pending'); + } + updateMutationState(batchId, state, error) { + this.persistMutationState(batchId, state, error); + // Once a final mutation result is observed by other clients, they no longer + // access the mutation's metadata entry. Since WebStorage replays events + // in order, it is safe to delete the entry right after updating it. + this.removeMutationState(batchId); + } + addLocalQueryTarget(targetId, addToActiveTargetIds = true) { + let queryState = 'not-current'; + // Lookup an existing query state if the target ID was already registered + // by another tab + if (this.isActiveQueryTarget(targetId)) { + const storageItem = this.storage.getItem(createWebStorageQueryTargetMetadataKey(this.persistenceKey, targetId)); + if (storageItem) { + const metadata = QueryTargetMetadata.fromWebStorageEntry(targetId, storageItem); + if (metadata) { + queryState = metadata.state; + } + } + } + // If the query is listening to cache only, the target ID should not be registered with the + // local Firestore client as an active watch target. + if (addToActiveTargetIds) { + this.localClientState.addQueryTarget(targetId); + } + this.persistClientState(); + return queryState; + } + removeLocalQueryTarget(targetId) { + this.localClientState.removeQueryTarget(targetId); + this.persistClientState(); + } + isLocalQueryTarget(targetId) { + return this.localClientState.activeTargetIds.has(targetId); + } + clearQueryState(targetId) { + this.removeItem(createWebStorageQueryTargetMetadataKey(this.persistenceKey, targetId)); + } + updateQueryState(targetId, state, error) { + this.persistQueryTargetState(targetId, state, error); + } + handleUserChange(user, removedBatchIds, addedBatchIds) { + removedBatchIds.forEach(batchId => { + this.removeMutationState(batchId); + }); + this.currentUser = user; + addedBatchIds.forEach(batchId => { + this.addPendingMutation(batchId); + }); + } + setOnlineState(onlineState) { + this.persistOnlineState(onlineState); + } + notifyBundleLoaded(collectionGroups) { + this.persistBundleLoadedState(collectionGroups); + } + shutdown() { + if (this.started) { + this.window.removeEventListener('storage', this.storageListener); + this.removeItem(this.localClientStorageKey); + this.started = false; + } + } + getItem(key) { + const value = this.storage.getItem(key); + logDebug(LOG_TAG$a, 'READ', key, value); + return value; + } + setItem(key, value) { + logDebug(LOG_TAG$a, 'SET', key, value); + this.storage.setItem(key, value); + } + removeItem(key) { + logDebug(LOG_TAG$a, 'REMOVE', key); + this.storage.removeItem(key); + } + handleWebStorageEvent(event) { + // Note: The function is typed to take Event to be interface-compatible with + // `Window.addEventListener`. + const storageEvent = event; + if (storageEvent.storageArea === this.storage) { + logDebug(LOG_TAG$a, 'EVENT', storageEvent.key, storageEvent.newValue); + if (storageEvent.key === this.localClientStorageKey) { + logError('Received WebStorage notification for local change. Another client might have ' + + 'garbage-collected our state'); + return; + } + this.queue.enqueueRetryable(async () => { + if (!this.started) { + this.earlyEvents.push(storageEvent); + return; + } + if (storageEvent.key === null) { + return; + } + if (this.clientStateKeyRe.test(storageEvent.key)) { + if (storageEvent.newValue != null) { + const clientState = this.fromWebStorageClientState(storageEvent.key, storageEvent.newValue); + if (clientState) { + return this.handleClientStateEvent(clientState.clientId, clientState); + } + } + else { + const clientId = this.fromWebStorageClientStateKey(storageEvent.key); + return this.handleClientStateEvent(clientId, null); + } + } + else if (this.mutationBatchKeyRe.test(storageEvent.key)) { + if (storageEvent.newValue !== null) { + const mutationMetadata = this.fromWebStorageMutationMetadata(storageEvent.key, storageEvent.newValue); + if (mutationMetadata) { + return this.handleMutationBatchEvent(mutationMetadata); + } + } + } + else if (this.queryTargetKeyRe.test(storageEvent.key)) { + if (storageEvent.newValue !== null) { + const queryTargetMetadata = this.fromWebStorageQueryTargetMetadata(storageEvent.key, storageEvent.newValue); + if (queryTargetMetadata) { + return this.handleQueryTargetEvent(queryTargetMetadata); + } + } + } + else if (storageEvent.key === this.onlineStateKey) { + if (storageEvent.newValue !== null) { + const onlineState = this.fromWebStorageOnlineState(storageEvent.newValue); + if (onlineState) { + return this.handleOnlineStateEvent(onlineState); + } + } + } + else if (storageEvent.key === this.sequenceNumberKey) { + const sequenceNumber = fromWebStorageSequenceNumber(storageEvent.newValue); + if (sequenceNumber !== ListenSequence.INVALID) { + this.sequenceNumberHandler(sequenceNumber); + } + } + else if (storageEvent.key === this.bundleLoadedKey) { + const collectionGroups = this.fromWebStoreBundleLoadedState(storageEvent.newValue); + await Promise.all(collectionGroups.map(cg => this.syncEngine.synchronizeWithChangedDocuments(cg))); + } + }); + } + } + get localClientState() { + return this.activeClients.get(this.localClientId); + } + persistClientState() { + this.setItem(this.localClientStorageKey, this.localClientState.toWebStorageJSON()); + } + persistMutationState(batchId, state, error) { + const mutationState = new MutationMetadata(this.currentUser, batchId, state, error); + const mutationKey = createWebStorageMutationBatchKey(this.persistenceKey, this.currentUser, batchId); + this.setItem(mutationKey, mutationState.toWebStorageJSON()); + } + removeMutationState(batchId) { + const mutationKey = createWebStorageMutationBatchKey(this.persistenceKey, this.currentUser, batchId); + this.removeItem(mutationKey); + } + persistOnlineState(onlineState) { + const entry = { + clientId: this.localClientId, + onlineState + }; + this.storage.setItem(this.onlineStateKey, JSON.stringify(entry)); + } + persistQueryTargetState(targetId, state, error) { + const targetKey = createWebStorageQueryTargetMetadataKey(this.persistenceKey, targetId); + const targetMetadata = new QueryTargetMetadata(targetId, state, error); + this.setItem(targetKey, targetMetadata.toWebStorageJSON()); + } + persistBundleLoadedState(collectionGroups) { + const json = JSON.stringify(Array.from(collectionGroups)); + this.setItem(this.bundleLoadedKey, json); + } + /** + * Parses a client state key in WebStorage. Returns null if the key does not + * match the expected key format. + */ + fromWebStorageClientStateKey(key) { + const match = this.clientStateKeyRe.exec(key); + return match ? match[1] : null; + } + /** + * Parses a client state in WebStorage. Returns 'null' if the value could not + * be parsed. + */ + fromWebStorageClientState(key, value) { + const clientId = this.fromWebStorageClientStateKey(key); + return RemoteClientState.fromWebStorageEntry(clientId, value); + } + /** + * Parses a mutation batch state in WebStorage. Returns 'null' if the value + * could not be parsed. + */ + fromWebStorageMutationMetadata(key, value) { + const match = this.mutationBatchKeyRe.exec(key); + const batchId = Number(match[1]); + const userId = match[2] !== undefined ? match[2] : null; + return MutationMetadata.fromWebStorageEntry(new User(userId), batchId, value); + } + /** + * Parses a query target state from WebStorage. Returns 'null' if the value + * could not be parsed. + */ + fromWebStorageQueryTargetMetadata(key, value) { + const match = this.queryTargetKeyRe.exec(key); + const targetId = Number(match[1]); + return QueryTargetMetadata.fromWebStorageEntry(targetId, value); + } + /** + * Parses an online state from WebStorage. Returns 'null' if the value + * could not be parsed. + */ + fromWebStorageOnlineState(value) { + return SharedOnlineState.fromWebStorageEntry(value); + } + fromWebStoreBundleLoadedState(value) { + return JSON.parse(value); + } + async handleMutationBatchEvent(mutationBatch) { + if (mutationBatch.user.uid !== this.currentUser.uid) { + logDebug(LOG_TAG$a, `Ignoring mutation for non-active user ${mutationBatch.user.uid}`); + return; + } + return this.syncEngine.applyBatchState(mutationBatch.batchId, mutationBatch.state, mutationBatch.error); + } + handleQueryTargetEvent(targetMetadata) { + return this.syncEngine.applyTargetState(targetMetadata.targetId, targetMetadata.state, targetMetadata.error); + } + handleClientStateEvent(clientId, clientState) { + const updatedClients = clientState + ? this.activeClients.insert(clientId, clientState) + : this.activeClients.remove(clientId); + const existingTargets = this.extractActiveQueryTargets(this.activeClients); + const newTargets = this.extractActiveQueryTargets(updatedClients); + const addedTargets = []; + const removedTargets = []; + newTargets.forEach(targetId => { + if (!existingTargets.has(targetId)) { + addedTargets.push(targetId); + } + }); + existingTargets.forEach(targetId => { + if (!newTargets.has(targetId)) { + removedTargets.push(targetId); + } + }); + return this.syncEngine.applyActiveTargetsChange(addedTargets, removedTargets).then(() => { + this.activeClients = updatedClients; + }); + } + handleOnlineStateEvent(onlineState) { + // We check whether the client that wrote this online state is still active + // by comparing its client ID to the list of clients kept active in + // IndexedDb. If a client does not update their IndexedDb client state + // within 5 seconds, it is considered inactive and we don't emit an online + // state event. + if (this.activeClients.get(onlineState.clientId)) { + this.onlineStateHandler(onlineState.onlineState); + } + } + extractActiveQueryTargets(clients) { + let activeTargets = targetIdSet(); + clients.forEach((kev, value) => { + activeTargets = activeTargets.unionWith(value.activeTargetIds); + }); + return activeTargets; + } +} +function fromWebStorageSequenceNumber(seqString) { + let sequenceNumber = ListenSequence.INVALID; + if (seqString != null) { + try { + const parsed = JSON.parse(seqString); + hardAssert(typeof parsed === 'number', 0x77ac, { seqString }); + sequenceNumber = parsed; + } + catch (e) { + logError(LOG_TAG$a, 'Failed to read sequence number from WebStorage', e); + } + } + return sequenceNumber; +} +/** + * `MemorySharedClientState` is a simple implementation of SharedClientState for + * clients using memory persistence. The state in this class remains fully + * isolated and no synchronization is performed. + */ +class MemorySharedClientState { + constructor() { + this.localState = new LocalClientState(); + this.queryState = {}; + this.onlineStateHandler = null; + this.sequenceNumberHandler = null; + } + addPendingMutation(batchId) { + // No op. + } + updateMutationState(batchId, state, error) { + // No op. + } + addLocalQueryTarget(targetId, addToActiveTargetIds = true) { + if (addToActiveTargetIds) { + this.localState.addQueryTarget(targetId); + } + return this.queryState[targetId] || 'not-current'; + } + updateQueryState(targetId, state, error) { + this.queryState[targetId] = state; + } + removeLocalQueryTarget(targetId) { + this.localState.removeQueryTarget(targetId); + } + isLocalQueryTarget(targetId) { + return this.localState.activeTargetIds.has(targetId); + } + clearQueryState(targetId) { + delete this.queryState[targetId]; + } + getAllActiveQueryTargets() { + return this.localState.activeTargetIds; + } + isActiveQueryTarget(targetId) { + return this.localState.activeTargetIds.has(targetId); + } + start() { + this.localState = new LocalClientState(); + return Promise.resolve(); + } + handleUserChange(user, removedBatchIds, addedBatchIds) { + // No op. + } + setOnlineState(onlineState) { + // No op. + } + shutdown() { } + writeSequenceNumber(sequenceNumber) { } + notifyBundleLoaded(collectionGroups) { + // No op. + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class NoopConnectivityMonitor { + addCallback(callback) { + // No-op. + } + shutdown() { + // No-op. + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provides a simple helper class that implements the Stream interface to + * bridge to other implementations that are streams but do not implement the + * interface. The stream callbacks are invoked with the callOn... methods. + */ +class StreamBridge { + constructor(args) { + this.sendFn = args.sendFn; + this.closeFn = args.closeFn; + } + onConnected(callback) { + this.wrappedOnConnected = callback; + } + onOpen(callback) { + this.wrappedOnOpen = callback; + } + onClose(callback) { + this.wrappedOnClose = callback; + } + onMessage(callback) { + this.wrappedOnMessage = callback; + } + close() { + this.closeFn(); + } + send(msg) { + this.sendFn(msg); + } + callOnConnected() { + this.wrappedOnConnected(); + } + callOnOpen() { + this.wrappedOnOpen(); + } + callOnClose(err) { + this.wrappedOnClose(err); + } + callOnMessage(msg) { + this.wrappedOnMessage(msg); + } +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The value returned from the most recent invocation of + * `generateUniqueDebugId()`, or null if it has never been invoked. + */ +let lastUniqueDebugId = null; +/** + * Generates and returns an initial value for `lastUniqueDebugId`. + * + * The returned value is randomly selected from a range of integers that are + * represented as 8 hexadecimal digits. This means that (within reason) any + * numbers generated by incrementing the returned number by 1 will also be + * represented by 8 hexadecimal digits. This leads to all "IDs" having the same + * length when converted to a hexadecimal string, making reading logs containing + * these IDs easier to follow. And since the return value is randomly selected + * it will help to differentiate between logs from different executions. + */ +function generateInitialUniqueDebugId() { + const minResult = 0x10000000; + const maxResult = 0x90000000; + const resultRange = maxResult - minResult; + const resultOffset = Math.round(resultRange * Math.random()); + return minResult + resultOffset; +} +/** + * Generates and returns a unique ID as a hexadecimal string. + * + * The returned ID is intended to be used in debug logging messages to help + * correlate log messages that may be spatially separated in the logs, but + * logically related. For example, a network connection could include the same + * "debug ID" string in all of its log messages to help trace a specific + * connection over time. + * + * @return the 10-character generated ID (e.g. "0xa1b2c3d4"). + */ +function generateUniqueDebugId() { + if (lastUniqueDebugId === null) { + lastUniqueDebugId = generateInitialUniqueDebugId(); + } + else { + lastUniqueDebugId++; + } + return '0x' + lastUniqueDebugId.toString(16); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * Utilities for dealing with node.js-style APIs. See nodePromise for more + * details. + */ +/** + * Creates a node-style callback that resolves or rejects a new Promise. The + * callback is passed to the given action which can then use the callback as + * a parameter to a node-style function. + * + * The intent is to directly bridge a node-style function (which takes a + * callback) into a Promise without manually converting between the node-style + * callback and the promise at each call. + * + * In effect it allows you to convert: + * + * @example + * new Promise((resolve: (value?: fs.Stats) => void, + * reject: (error?: any) => void) => { + * fs.stat(path, (error?: any, stat?: fs.Stats) => { + * if (error) { + * reject(error); + * } else { + * resolve(stat); + * } + * }); + * }); + * + * Into + * @example + * nodePromise((callback: NodeCallback) => { + * fs.stat(path, callback); + * }); + * + * @param action - a function that takes a node-style callback as an argument + * and then uses that callback to invoke some node-style API. + * @returns a new Promise which will be rejected if the callback is given the + * first Error parameter or will resolve to the value given otherwise. + */ +function nodePromise(action) { + return new Promise((resolve, reject) => { + action((error, value) => { + if (error) { + reject(error); + } + else { + resolve(value); + } + }); + }); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// TODO: Fetch runtime version from grpc-js/package.json instead +// when there's a cleaner way to dynamic require JSON in both Node ESM and CJS +const grpcVersion = '1.9.15'; +const LOG_TAG$9 = 'GrpcConnection'; +const X_GOOG_API_CLIENT_VALUE = `gl-node/${process.versions.node} fire/${SDK_VERSION} grpc/${grpcVersion}`; +function createMetadata(databasePath, authToken, appCheckToken, appId) { + hardAssert(authToken === null || authToken.type === 'OAuth', 0x9048); + const metadata = new grpc.Metadata(); + if (authToken) { + authToken.headers.forEach((value, key) => metadata.set(key, value)); + } + if (appCheckToken) { + appCheckToken.headers.forEach((value, key) => metadata.set(key, value)); + } + if (appId) { + metadata.set('X-Firebase-GMPID', appId); + } + metadata.set('X-Goog-Api-Client', X_GOOG_API_CLIENT_VALUE); + // These headers are used to improve routing and project isolation by the + // backend. + // TODO(b/199767712): We are keeping 'Google-Cloud-Resource-Prefix' until Emulators can be + // released with cl/428820046. Currently blocked because Emulators are now built with Java + // 11 from Google3. + metadata.set('Google-Cloud-Resource-Prefix', databasePath); + metadata.set('x-goog-request-params', databasePath); + return metadata; +} +/** + * A Connection implemented by GRPC-Node. + */ +class GrpcConnection { + get shouldResourcePathBeIncludedInRequest() { + // Both `invokeRPC()` and `invokeStreamingRPC()` ignore their `path` arguments, and expect + // the "path" to be part of the given `request`. + return true; + } + constructor(protos, databaseInfo) { + this.databaseInfo = databaseInfo; + // We cache stubs for the most-recently-used token. + this.cachedStub = null; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.firestore = protos['google']['firestore']['v1']; + this.databasePath = `projects/${databaseInfo.databaseId.projectId}/databases/${databaseInfo.databaseId.database}`; + } + ensureActiveStub() { + if (!this.cachedStub) { + logDebug(LOG_TAG$9, 'Creating Firestore stub.'); + const credentials = this.databaseInfo.ssl + ? grpc.credentials.createSsl() + : grpc.credentials.createInsecure(); + this.cachedStub = new this.firestore.Firestore(this.databaseInfo.host, credentials); + } + return this.cachedStub; + } + invokeRPC(rpcName, path, request, authToken, appCheckToken) { + const streamId = generateUniqueDebugId(); + const stub = this.ensureActiveStub(); + const metadata = createMetadata(this.databasePath, authToken, appCheckToken, this.databaseInfo.appId); + const jsonRequest = { database: this.databasePath, ...request }; + return nodePromise((callback) => { + logDebug(LOG_TAG$9, `RPC '${rpcName}' ${streamId} invoked with request:`, request); + return stub[rpcName](jsonRequest, metadata, (grpcError, value) => { + if (grpcError) { + logDebug(LOG_TAG$9, `RPC '${rpcName}' ${streamId} failed with error:`, grpcError); + callback(new FirestoreError(mapCodeFromRpcCode(grpcError.code), grpcError.message)); + } + else { + logDebug(LOG_TAG$9, `RPC '${rpcName}' ${streamId} completed with response:`, value); + callback(undefined, value); + } + }); + }); + } + invokeStreamingRPC(rpcName, path, request, authToken, appCheckToken, expectedResponseCount) { + const streamId = generateUniqueDebugId(); + const results = []; + const responseDeferred = new Deferred(); + logDebug(LOG_TAG$9, `RPC '${rpcName}' ${streamId} invoked (streaming) with request:`, request); + const stub = this.ensureActiveStub(); + const metadata = createMetadata(this.databasePath, authToken, appCheckToken, this.databaseInfo.appId); + const jsonRequest = { ...request, database: this.databasePath }; + const stream = stub[rpcName](jsonRequest, metadata); + let callbackFired = false; + stream.on('data', (response) => { + logDebug(LOG_TAG$9, `RPC ${rpcName} ${streamId} received result:`, response); + results.push(response); + if (expectedResponseCount !== undefined && + results.length === expectedResponseCount) { + callbackFired = true; + responseDeferred.resolve(results); + } + }); + stream.on('end', () => { + logDebug(LOG_TAG$9, `RPC '${rpcName}' ${streamId} completed.`); + if (!callbackFired) { + callbackFired = true; + responseDeferred.resolve(results); + } + }); + stream.on('error', (grpcError) => { + logDebug(LOG_TAG$9, `RPC '${rpcName}' ${streamId} failed with error:`, grpcError); + const code = mapCodeFromRpcCode(grpcError.code); + responseDeferred.reject(new FirestoreError(code, grpcError.message)); + }); + return responseDeferred.promise; + } + // TODO(mikelehen): This "method" is a monster. Should be refactored. + openStream(rpcName, authToken, appCheckToken) { + const streamId = generateUniqueDebugId(); + const stub = this.ensureActiveStub(); + const metadata = createMetadata(this.databasePath, authToken, appCheckToken, this.databaseInfo.appId); + const grpcStream = stub[rpcName](metadata); + let closed = false; + const close = (err) => { + if (!closed) { + closed = true; + stream.callOnClose(err); + grpcStream.end(); + } + }; + const stream = new StreamBridge({ + sendFn: (msg) => { + if (!closed) { + logDebug(LOG_TAG$9, `RPC '${rpcName}' stream ${streamId} sending:`, msg); + try { + grpcStream.write(msg); + } + catch (e) { + // This probably means we didn't conform to the proto. Make sure to + // log the message we sent. + logError('Failure sending:', msg); + logError('Error:', e); + throw e; + } + } + else { + logDebug(LOG_TAG$9, `RPC '${rpcName}' stream ${streamId} ` + + 'not sending because gRPC stream is closed:', msg); + } + }, + closeFn: () => { + logDebug(LOG_TAG$9, `RPC '${rpcName}' stream ${streamId} closed locally via close().`); + close(); + } + }); + let onConnectedSent = false; + grpcStream.on('data', (msg) => { + if (!closed) { + logDebug(LOG_TAG$9, `RPC '${rpcName}' stream ${streamId} received:`, msg); + // Emulate the "onConnected" event that WebChannelConnection sends. + if (!onConnectedSent) { + stream.callOnConnected(); + onConnectedSent = true; + } + stream.callOnMessage(msg); + } + }); + grpcStream.on('end', () => { + logDebug(LOG_TAG$9, `RPC '${rpcName}' stream ${streamId} ended.`); + close(); + }); + grpcStream.on('error', (grpcError) => { + if (!closed) { + logWarn(LOG_TAG$9, `RPC '${rpcName}' stream ${streamId} error. Code:`, grpcError.code, 'Message:', grpcError.message); + const code = mapCodeFromRpcCode(grpcError.code); + close(new FirestoreError(code, grpcError.message)); + } + }); + logDebug(LOG_TAG$9, `Opening RPC '${rpcName}' stream ${streamId} ` + + `to ${this.databaseInfo.host}`); + // TODO(dimond): Since grpc has no explicit open status (or does it?) we + // simulate an onOpen in the next loop after the stream had it's listeners + // registered + setTimeout(() => { + stream.callOnOpen(); + }, 0); + return stream; + } + /** + * Closes and cleans up any resources associated with the GrpcConnection. + * If a gRPC client has been generated for this connection, the gRPC client + * is closed. Failure to call terminate on a GrpcConnection can result + * in leaked resources of the gRPC client. + */ + terminate() { + if (this.cachedStub) { + this.cachedStub.close(); + this.cachedStub = undefined; + } + } +} + +const nested = { + google: { + nested: { + protobuf: { + options: { + csharp_namespace: "Google.Protobuf.WellKnownTypes", + go_package: "github.com/golang/protobuf/ptypes/wrappers", + java_package: "com.google.protobuf", + java_outer_classname: "WrappersProto", + java_multiple_files: true, + objc_class_prefix: "GPB", + cc_enable_arenas: true, + optimize_for: "SPEED" + }, + nested: { + Timestamp: { + fields: { + seconds: { + type: "int64", + id: 1 + }, + nanos: { + type: "int32", + id: 2 + } + } + }, + FileDescriptorSet: { + fields: { + file: { + rule: "repeated", + type: "FileDescriptorProto", + id: 1 + } + } + }, + FileDescriptorProto: { + fields: { + name: { + type: "string", + id: 1 + }, + "package": { + type: "string", + id: 2 + }, + dependency: { + rule: "repeated", + type: "string", + id: 3 + }, + publicDependency: { + rule: "repeated", + type: "int32", + id: 10, + options: { + packed: false + } + }, + weakDependency: { + rule: "repeated", + type: "int32", + id: 11, + options: { + packed: false + } + }, + messageType: { + rule: "repeated", + type: "DescriptorProto", + id: 4 + }, + enumType: { + rule: "repeated", + type: "EnumDescriptorProto", + id: 5 + }, + service: { + rule: "repeated", + type: "ServiceDescriptorProto", + id: 6 + }, + extension: { + rule: "repeated", + type: "FieldDescriptorProto", + id: 7 + }, + options: { + type: "FileOptions", + id: 8 + }, + sourceCodeInfo: { + type: "SourceCodeInfo", + id: 9 + }, + syntax: { + type: "string", + id: 12 + } + } + }, + DescriptorProto: { + fields: { + name: { + type: "string", + id: 1 + }, + field: { + rule: "repeated", + type: "FieldDescriptorProto", + id: 2 + }, + extension: { + rule: "repeated", + type: "FieldDescriptorProto", + id: 6 + }, + nestedType: { + rule: "repeated", + type: "DescriptorProto", + id: 3 + }, + enumType: { + rule: "repeated", + type: "EnumDescriptorProto", + id: 4 + }, + extensionRange: { + rule: "repeated", + type: "ExtensionRange", + id: 5 + }, + oneofDecl: { + rule: "repeated", + type: "OneofDescriptorProto", + id: 8 + }, + options: { + type: "MessageOptions", + id: 7 + }, + reservedRange: { + rule: "repeated", + type: "ReservedRange", + id: 9 + }, + reservedName: { + rule: "repeated", + type: "string", + id: 10 + } + }, + nested: { + ExtensionRange: { + fields: { + start: { + type: "int32", + id: 1 + }, + end: { + type: "int32", + id: 2 + } + } + }, + ReservedRange: { + fields: { + start: { + type: "int32", + id: 1 + }, + end: { + type: "int32", + id: 2 + } + } + } + } + }, + FieldDescriptorProto: { + fields: { + name: { + type: "string", + id: 1 + }, + number: { + type: "int32", + id: 3 + }, + label: { + type: "Label", + id: 4 + }, + type: { + type: "Type", + id: 5 + }, + typeName: { + type: "string", + id: 6 + }, + extendee: { + type: "string", + id: 2 + }, + defaultValue: { + type: "string", + id: 7 + }, + oneofIndex: { + type: "int32", + id: 9 + }, + jsonName: { + type: "string", + id: 10 + }, + options: { + type: "FieldOptions", + id: 8 + } + }, + nested: { + Type: { + values: { + TYPE_DOUBLE: 1, + TYPE_FLOAT: 2, + TYPE_INT64: 3, + TYPE_UINT64: 4, + TYPE_INT32: 5, + TYPE_FIXED64: 6, + TYPE_FIXED32: 7, + TYPE_BOOL: 8, + TYPE_STRING: 9, + TYPE_GROUP: 10, + TYPE_MESSAGE: 11, + TYPE_BYTES: 12, + TYPE_UINT32: 13, + TYPE_ENUM: 14, + TYPE_SFIXED32: 15, + TYPE_SFIXED64: 16, + TYPE_SINT32: 17, + TYPE_SINT64: 18 + } + }, + Label: { + values: { + LABEL_OPTIONAL: 1, + LABEL_REQUIRED: 2, + LABEL_REPEATED: 3 + } + } + } + }, + OneofDescriptorProto: { + fields: { + name: { + type: "string", + id: 1 + }, + options: { + type: "OneofOptions", + id: 2 + } + } + }, + EnumDescriptorProto: { + fields: { + name: { + type: "string", + id: 1 + }, + value: { + rule: "repeated", + type: "EnumValueDescriptorProto", + id: 2 + }, + options: { + type: "EnumOptions", + id: 3 + } + } + }, + EnumValueDescriptorProto: { + fields: { + name: { + type: "string", + id: 1 + }, + number: { + type: "int32", + id: 2 + }, + options: { + type: "EnumValueOptions", + id: 3 + } + } + }, + ServiceDescriptorProto: { + fields: { + name: { + type: "string", + id: 1 + }, + method: { + rule: "repeated", + type: "MethodDescriptorProto", + id: 2 + }, + options: { + type: "ServiceOptions", + id: 3 + } + } + }, + MethodDescriptorProto: { + fields: { + name: { + type: "string", + id: 1 + }, + inputType: { + type: "string", + id: 2 + }, + outputType: { + type: "string", + id: 3 + }, + options: { + type: "MethodOptions", + id: 4 + }, + clientStreaming: { + type: "bool", + id: 5 + }, + serverStreaming: { + type: "bool", + id: 6 + } + } + }, + FileOptions: { + fields: { + javaPackage: { + type: "string", + id: 1 + }, + javaOuterClassname: { + type: "string", + id: 8 + }, + javaMultipleFiles: { + type: "bool", + id: 10 + }, + javaGenerateEqualsAndHash: { + type: "bool", + id: 20, + options: { + deprecated: true + } + }, + javaStringCheckUtf8: { + type: "bool", + id: 27 + }, + optimizeFor: { + type: "OptimizeMode", + id: 9, + options: { + "default": "SPEED" + } + }, + goPackage: { + type: "string", + id: 11 + }, + ccGenericServices: { + type: "bool", + id: 16 + }, + javaGenericServices: { + type: "bool", + id: 17 + }, + pyGenericServices: { + type: "bool", + id: 18 + }, + deprecated: { + type: "bool", + id: 23 + }, + ccEnableArenas: { + type: "bool", + id: 31 + }, + objcClassPrefix: { + type: "string", + id: 36 + }, + csharpNamespace: { + type: "string", + id: 37 + }, + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1000, + 536870911 + ] + ], + reserved: [ + [ + 38, + 38 + ] + ], + nested: { + OptimizeMode: { + values: { + SPEED: 1, + CODE_SIZE: 2, + LITE_RUNTIME: 3 + } + } + } + }, + MessageOptions: { + fields: { + messageSetWireFormat: { + type: "bool", + id: 1 + }, + noStandardDescriptorAccessor: { + type: "bool", + id: 2 + }, + deprecated: { + type: "bool", + id: 3 + }, + mapEntry: { + type: "bool", + id: 7 + }, + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1000, + 536870911 + ] + ], + reserved: [ + [ + 8, + 8 + ] + ] + }, + FieldOptions: { + fields: { + ctype: { + type: "CType", + id: 1, + options: { + "default": "STRING" + } + }, + packed: { + type: "bool", + id: 2 + }, + jstype: { + type: "JSType", + id: 6, + options: { + "default": "JS_NORMAL" + } + }, + lazy: { + type: "bool", + id: 5 + }, + deprecated: { + type: "bool", + id: 3 + }, + weak: { + type: "bool", + id: 10 + }, + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1000, + 536870911 + ] + ], + reserved: [ + [ + 4, + 4 + ] + ], + nested: { + CType: { + values: { + STRING: 0, + CORD: 1, + STRING_PIECE: 2 + } + }, + JSType: { + values: { + JS_NORMAL: 0, + JS_STRING: 1, + JS_NUMBER: 2 + } + } + } + }, + OneofOptions: { + fields: { + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1000, + 536870911 + ] + ] + }, + EnumOptions: { + fields: { + allowAlias: { + type: "bool", + id: 2 + }, + deprecated: { + type: "bool", + id: 3 + }, + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1000, + 536870911 + ] + ] + }, + EnumValueOptions: { + fields: { + deprecated: { + type: "bool", + id: 1 + }, + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1000, + 536870911 + ] + ] + }, + ServiceOptions: { + fields: { + deprecated: { + type: "bool", + id: 33 + }, + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1000, + 536870911 + ] + ] + }, + MethodOptions: { + fields: { + deprecated: { + type: "bool", + id: 33 + }, + uninterpretedOption: { + rule: "repeated", + type: "UninterpretedOption", + id: 999 + } + }, + extensions: [ + [ + 1000, + 536870911 + ] + ] + }, + UninterpretedOption: { + fields: { + name: { + rule: "repeated", + type: "NamePart", + id: 2 + }, + identifierValue: { + type: "string", + id: 3 + }, + positiveIntValue: { + type: "uint64", + id: 4 + }, + negativeIntValue: { + type: "int64", + id: 5 + }, + doubleValue: { + type: "double", + id: 6 + }, + stringValue: { + type: "bytes", + id: 7 + }, + aggregateValue: { + type: "string", + id: 8 + } + }, + nested: { + NamePart: { + fields: { + namePart: { + rule: "required", + type: "string", + id: 1 + }, + isExtension: { + rule: "required", + type: "bool", + id: 2 + } + } + } + } + }, + SourceCodeInfo: { + fields: { + location: { + rule: "repeated", + type: "Location", + id: 1 + } + }, + nested: { + Location: { + fields: { + path: { + rule: "repeated", + type: "int32", + id: 1 + }, + span: { + rule: "repeated", + type: "int32", + id: 2 + }, + leadingComments: { + type: "string", + id: 3 + }, + trailingComments: { + type: "string", + id: 4 + }, + leadingDetachedComments: { + rule: "repeated", + type: "string", + id: 6 + } + } + } + } + }, + GeneratedCodeInfo: { + fields: { + annotation: { + rule: "repeated", + type: "Annotation", + id: 1 + } + }, + nested: { + Annotation: { + fields: { + path: { + rule: "repeated", + type: "int32", + id: 1 + }, + sourceFile: { + type: "string", + id: 2 + }, + begin: { + type: "int32", + id: 3 + }, + end: { + type: "int32", + id: 4 + } + } + } + } + }, + Struct: { + fields: { + fields: { + keyType: "string", + type: "Value", + id: 1 + } + } + }, + Value: { + oneofs: { + kind: { + oneof: [ + "nullValue", + "numberValue", + "stringValue", + "boolValue", + "structValue", + "listValue" + ] + } + }, + fields: { + nullValue: { + type: "NullValue", + id: 1 + }, + numberValue: { + type: "double", + id: 2 + }, + stringValue: { + type: "string", + id: 3 + }, + boolValue: { + type: "bool", + id: 4 + }, + structValue: { + type: "Struct", + id: 5 + }, + listValue: { + type: "ListValue", + id: 6 + } + } + }, + NullValue: { + values: { + NULL_VALUE: 0 + } + }, + ListValue: { + fields: { + values: { + rule: "repeated", + type: "Value", + id: 1 + } + } + }, + Empty: { + fields: { + } + }, + DoubleValue: { + fields: { + value: { + type: "double", + id: 1 + } + } + }, + FloatValue: { + fields: { + value: { + type: "float", + id: 1 + } + } + }, + Int64Value: { + fields: { + value: { + type: "int64", + id: 1 + } + } + }, + UInt64Value: { + fields: { + value: { + type: "uint64", + id: 1 + } + } + }, + Int32Value: { + fields: { + value: { + type: "int32", + id: 1 + } + } + }, + UInt32Value: { + fields: { + value: { + type: "uint32", + id: 1 + } + } + }, + BoolValue: { + fields: { + value: { + type: "bool", + id: 1 + } + } + }, + StringValue: { + fields: { + value: { + type: "string", + id: 1 + } + } + }, + BytesValue: { + fields: { + value: { + type: "bytes", + id: 1 + } + } + }, + Any: { + fields: { + typeUrl: { + type: "string", + id: 1 + }, + value: { + type: "bytes", + id: 2 + } + } + } + } + }, + firestore: { + nested: { + v1: { + options: { + csharp_namespace: "Google.Cloud.Firestore.V1", + go_package: "google.golang.org/genproto/googleapis/firestore/v1;firestore", + java_multiple_files: true, + java_outer_classname: "WriteProto", + java_package: "com.google.firestore.v1", + objc_class_prefix: "GCFS", + php_namespace: "Google\\Cloud\\Firestore\\V1", + ruby_package: "Google::Cloud::Firestore::V1" + }, + nested: { + AggregationResult: { + fields: { + aggregateFields: { + keyType: "string", + type: "Value", + id: 2 + } + } + }, + BitSequence: { + fields: { + bitmap: { + type: "bytes", + id: 1 + }, + padding: { + type: "int32", + id: 2 + } + } + }, + BloomFilter: { + fields: { + bits: { + type: "BitSequence", + id: 1 + }, + hashCount: { + type: "int32", + id: 2 + } + } + }, + DocumentMask: { + fields: { + fieldPaths: { + rule: "repeated", + type: "string", + id: 1 + } + } + }, + Precondition: { + oneofs: { + conditionType: { + oneof: [ + "exists", + "updateTime" + ] + } + }, + fields: { + exists: { + type: "bool", + id: 1 + }, + updateTime: { + type: "google.protobuf.Timestamp", + id: 2 + } + } + }, + TransactionOptions: { + oneofs: { + mode: { + oneof: [ + "readOnly", + "readWrite" + ] + } + }, + fields: { + readOnly: { + type: "ReadOnly", + id: 2 + }, + readWrite: { + type: "ReadWrite", + id: 3 + } + }, + nested: { + ReadWrite: { + fields: { + retryTransaction: { + type: "bytes", + id: 1 + } + } + }, + ReadOnly: { + oneofs: { + consistencySelector: { + oneof: [ + "readTime" + ] + } + }, + fields: { + readTime: { + type: "google.protobuf.Timestamp", + id: 2 + } + } + } + } + }, + Document: { + fields: { + name: { + type: "string", + id: 1 + }, + fields: { + keyType: "string", + type: "Value", + id: 2 + }, + createTime: { + type: "google.protobuf.Timestamp", + id: 3 + }, + updateTime: { + type: "google.protobuf.Timestamp", + id: 4 + } + } + }, + Value: { + oneofs: { + valueType: { + oneof: [ + "nullValue", + "booleanValue", + "integerValue", + "doubleValue", + "timestampValue", + "stringValue", + "bytesValue", + "referenceValue", + "geoPointValue", + "arrayValue", + "mapValue" + ] + } + }, + fields: { + nullValue: { + type: "google.protobuf.NullValue", + id: 11 + }, + booleanValue: { + type: "bool", + id: 1 + }, + integerValue: { + type: "int64", + id: 2 + }, + doubleValue: { + type: "double", + id: 3 + }, + timestampValue: { + type: "google.protobuf.Timestamp", + id: 10 + }, + stringValue: { + type: "string", + id: 17 + }, + bytesValue: { + type: "bytes", + id: 18 + }, + referenceValue: { + type: "string", + id: 5 + }, + geoPointValue: { + type: "google.type.LatLng", + id: 8 + }, + arrayValue: { + type: "ArrayValue", + id: 9 + }, + mapValue: { + type: "MapValue", + id: 6 + } + } + }, + ArrayValue: { + fields: { + values: { + rule: "repeated", + type: "Value", + id: 1 + } + } + }, + MapValue: { + fields: { + fields: { + keyType: "string", + type: "Value", + id: 1 + } + } + }, + Firestore: { + options: { + "(google.api.default_host)": "firestore.googleapis.com", + "(google.api.oauth_scopes)": "https://www.googleapis.com/auth/cloud-platform,https://www.googleapis.com/auth/datastore" + }, + methods: { + GetDocument: { + requestType: "GetDocumentRequest", + responseType: "Document", + options: { + "(google.api.http).get": "/v1/{name=projects/*/databases/*/documents/*/**}" + }, + parsedOptions: [ + { + "(google.api.http)": { + get: "/v1/{name=projects/*/databases/*/documents/*/**}" + } + } + ] + }, + ListDocuments: { + requestType: "ListDocumentsRequest", + responseType: "ListDocumentsResponse", + options: { + "(google.api.http).get": "/v1/{parent=projects/*/databases/*/documents/*/**}/{collection_id}" + }, + parsedOptions: [ + { + "(google.api.http)": { + get: "/v1/{parent=projects/*/databases/*/documents/*/**}/{collection_id}" + } + } + ] + }, + UpdateDocument: { + requestType: "UpdateDocumentRequest", + responseType: "Document", + options: { + "(google.api.http).patch": "/v1/{document.name=projects/*/databases/*/documents/*/**}", + "(google.api.http).body": "document", + "(google.api.method_signature)": "document,update_mask" + }, + parsedOptions: [ + { + "(google.api.http)": { + patch: "/v1/{document.name=projects/*/databases/*/documents/*/**}", + body: "document" + } + }, + { + "(google.api.method_signature)": "document,update_mask" + } + ] + }, + DeleteDocument: { + requestType: "DeleteDocumentRequest", + responseType: "google.protobuf.Empty", + options: { + "(google.api.http).delete": "/v1/{name=projects/*/databases/*/documents/*/**}", + "(google.api.method_signature)": "name" + }, + parsedOptions: [ + { + "(google.api.http)": { + "delete": "/v1/{name=projects/*/databases/*/documents/*/**}" + } + }, + { + "(google.api.method_signature)": "name" + } + ] + }, + BatchGetDocuments: { + requestType: "BatchGetDocumentsRequest", + responseType: "BatchGetDocumentsResponse", + responseStream: true, + options: { + "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:batchGet", + "(google.api.http).body": "*" + }, + parsedOptions: [ + { + "(google.api.http)": { + post: "/v1/{database=projects/*/databases/*}/documents:batchGet", + body: "*" + } + } + ] + }, + BeginTransaction: { + requestType: "BeginTransactionRequest", + responseType: "BeginTransactionResponse", + options: { + "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:beginTransaction", + "(google.api.http).body": "*", + "(google.api.method_signature)": "database" + }, + parsedOptions: [ + { + "(google.api.http)": { + post: "/v1/{database=projects/*/databases/*}/documents:beginTransaction", + body: "*" + } + }, + { + "(google.api.method_signature)": "database" + } + ] + }, + Commit: { + requestType: "CommitRequest", + responseType: "CommitResponse", + options: { + "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:commit", + "(google.api.http).body": "*", + "(google.api.method_signature)": "database,writes" + }, + parsedOptions: [ + { + "(google.api.http)": { + post: "/v1/{database=projects/*/databases/*}/documents:commit", + body: "*" + } + }, + { + "(google.api.method_signature)": "database,writes" + } + ] + }, + Rollback: { + requestType: "RollbackRequest", + responseType: "google.protobuf.Empty", + options: { + "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:rollback", + "(google.api.http).body": "*", + "(google.api.method_signature)": "database,transaction" + }, + parsedOptions: [ + { + "(google.api.http)": { + post: "/v1/{database=projects/*/databases/*}/documents:rollback", + body: "*" + } + }, + { + "(google.api.method_signature)": "database,transaction" + } + ] + }, + RunQuery: { + requestType: "RunQueryRequest", + responseType: "RunQueryResponse", + responseStream: true, + options: { + "(google.api.http).post": "/v1/{parent=projects/*/databases/*/documents}:runQuery", + "(google.api.http).body": "*", + "(google.api.http).additional_bindings.post": "/v1/{parent=projects/*/databases/*/documents/*/**}:runQuery", + "(google.api.http).additional_bindings.body": "*" + }, + parsedOptions: [ + { + "(google.api.http)": { + post: "/v1/{parent=projects/*/databases/*/documents}:runQuery", + body: "*", + additional_bindings: { + post: "/v1/{parent=projects/*/databases/*/documents/*/**}:runQuery", + body: "*" + } + } + } + ] + }, + RunAggregationQuery: { + requestType: "RunAggregationQueryRequest", + responseType: "RunAggregationQueryResponse", + responseStream: true, + options: { + "(google.api.http).post": "/v1/{parent=projects/*/databases/*/documents}:runAggregationQuery", + "(google.api.http).body": "*", + "(google.api.http).additional_bindings.post": "/v1/{parent=projects/*/databases/*/documents/*/**}:runAggregationQuery", + "(google.api.http).additional_bindings.body": "*" + }, + parsedOptions: [ + { + "(google.api.http)": { + post: "/v1/{parent=projects/*/databases/*/documents}:runAggregationQuery", + body: "*", + additional_bindings: { + post: "/v1/{parent=projects/*/databases/*/documents/*/**}:runAggregationQuery", + body: "*" + } + } + } + ] + }, + PartitionQuery: { + requestType: "PartitionQueryRequest", + responseType: "PartitionQueryResponse", + options: { + "(google.api.http).post": "/v1/{parent=projects/*/databases/*/documents}:partitionQuery", + "(google.api.http).body": "*", + "(google.api.http).additional_bindings.post": "/v1/{parent=projects/*/databases/*/documents/*/**}:partitionQuery", + "(google.api.http).additional_bindings.body": "*" + }, + parsedOptions: [ + { + "(google.api.http)": { + post: "/v1/{parent=projects/*/databases/*/documents}:partitionQuery", + body: "*", + additional_bindings: { + post: "/v1/{parent=projects/*/databases/*/documents/*/**}:partitionQuery", + body: "*" + } + } + } + ] + }, + Write: { + requestType: "WriteRequest", + requestStream: true, + responseType: "WriteResponse", + responseStream: true, + options: { + "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:write", + "(google.api.http).body": "*" + }, + parsedOptions: [ + { + "(google.api.http)": { + post: "/v1/{database=projects/*/databases/*}/documents:write", + body: "*" + } + } + ] + }, + Listen: { + requestType: "ListenRequest", + requestStream: true, + responseType: "ListenResponse", + responseStream: true, + options: { + "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:listen", + "(google.api.http).body": "*" + }, + parsedOptions: [ + { + "(google.api.http)": { + post: "/v1/{database=projects/*/databases/*}/documents:listen", + body: "*" + } + } + ] + }, + ListCollectionIds: { + requestType: "ListCollectionIdsRequest", + responseType: "ListCollectionIdsResponse", + options: { + "(google.api.http).post": "/v1/{parent=projects/*/databases/*/documents}:listCollectionIds", + "(google.api.http).body": "*", + "(google.api.http).additional_bindings.post": "/v1/{parent=projects/*/databases/*/documents/*/**}:listCollectionIds", + "(google.api.http).additional_bindings.body": "*", + "(google.api.method_signature)": "parent" + }, + parsedOptions: [ + { + "(google.api.http)": { + post: "/v1/{parent=projects/*/databases/*/documents}:listCollectionIds", + body: "*", + additional_bindings: { + post: "/v1/{parent=projects/*/databases/*/documents/*/**}:listCollectionIds", + body: "*" + } + } + }, + { + "(google.api.method_signature)": "parent" + } + ] + }, + BatchWrite: { + requestType: "BatchWriteRequest", + responseType: "BatchWriteResponse", + options: { + "(google.api.http).post": "/v1/{database=projects/*/databases/*}/documents:batchWrite", + "(google.api.http).body": "*" + }, + parsedOptions: [ + { + "(google.api.http)": { + post: "/v1/{database=projects/*/databases/*}/documents:batchWrite", + body: "*" + } + } + ] + }, + CreateDocument: { + requestType: "CreateDocumentRequest", + responseType: "Document", + options: { + "(google.api.http).post": "/v1/{parent=projects/*/databases/*/documents/**}/{collection_id}", + "(google.api.http).body": "document" + }, + parsedOptions: [ + { + "(google.api.http)": { + post: "/v1/{parent=projects/*/databases/*/documents/**}/{collection_id}", + body: "document" + } + } + ] + } + } + }, + GetDocumentRequest: { + oneofs: { + consistencySelector: { + oneof: [ + "transaction", + "readTime" + ] + } + }, + fields: { + name: { + type: "string", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + mask: { + type: "DocumentMask", + id: 2 + }, + transaction: { + type: "bytes", + id: 3 + }, + readTime: { + type: "google.protobuf.Timestamp", + id: 5 + } + } + }, + ListDocumentsRequest: { + oneofs: { + consistencySelector: { + oneof: [ + "transaction", + "readTime" + ] + } + }, + fields: { + parent: { + type: "string", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + collectionId: { + type: "string", + id: 2, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + pageSize: { + type: "int32", + id: 3 + }, + pageToken: { + type: "string", + id: 4 + }, + orderBy: { + type: "string", + id: 6 + }, + mask: { + type: "DocumentMask", + id: 7 + }, + transaction: { + type: "bytes", + id: 8 + }, + readTime: { + type: "google.protobuf.Timestamp", + id: 10 + }, + showMissing: { + type: "bool", + id: 12 + } + } + }, + ListDocumentsResponse: { + fields: { + documents: { + rule: "repeated", + type: "Document", + id: 1 + }, + nextPageToken: { + type: "string", + id: 2 + } + } + }, + CreateDocumentRequest: { + fields: { + parent: { + type: "string", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + collectionId: { + type: "string", + id: 2, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + documentId: { + type: "string", + id: 3 + }, + document: { + type: "Document", + id: 4, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + mask: { + type: "DocumentMask", + id: 5 + } + } + }, + UpdateDocumentRequest: { + fields: { + document: { + type: "Document", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + updateMask: { + type: "DocumentMask", + id: 2 + }, + mask: { + type: "DocumentMask", + id: 3 + }, + currentDocument: { + type: "Precondition", + id: 4 + } + } + }, + DeleteDocumentRequest: { + fields: { + name: { + type: "string", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + currentDocument: { + type: "Precondition", + id: 2 + } + } + }, + BatchGetDocumentsRequest: { + oneofs: { + consistencySelector: { + oneof: [ + "transaction", + "newTransaction", + "readTime" + ] + } + }, + fields: { + database: { + type: "string", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + documents: { + rule: "repeated", + type: "string", + id: 2 + }, + mask: { + type: "DocumentMask", + id: 3 + }, + transaction: { + type: "bytes", + id: 4 + }, + newTransaction: { + type: "TransactionOptions", + id: 5 + }, + readTime: { + type: "google.protobuf.Timestamp", + id: 7 + } + } + }, + BatchGetDocumentsResponse: { + oneofs: { + result: { + oneof: [ + "found", + "missing" + ] + } + }, + fields: { + found: { + type: "Document", + id: 1 + }, + missing: { + type: "string", + id: 2 + }, + transaction: { + type: "bytes", + id: 3 + }, + readTime: { + type: "google.protobuf.Timestamp", + id: 4 + } + } + }, + BeginTransactionRequest: { + fields: { + database: { + type: "string", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + options: { + type: "TransactionOptions", + id: 2 + } + } + }, + BeginTransactionResponse: { + fields: { + transaction: { + type: "bytes", + id: 1 + } + } + }, + CommitRequest: { + fields: { + database: { + type: "string", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + writes: { + rule: "repeated", + type: "Write", + id: 2 + }, + transaction: { + type: "bytes", + id: 3 + } + } + }, + CommitResponse: { + fields: { + writeResults: { + rule: "repeated", + type: "WriteResult", + id: 1 + }, + commitTime: { + type: "google.protobuf.Timestamp", + id: 2 + } + } + }, + RollbackRequest: { + fields: { + database: { + type: "string", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + transaction: { + type: "bytes", + id: 2, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + } + } + }, + RunQueryRequest: { + oneofs: { + queryType: { + oneof: [ + "structuredQuery" + ] + }, + consistencySelector: { + oneof: [ + "transaction", + "newTransaction", + "readTime" + ] + } + }, + fields: { + parent: { + type: "string", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + structuredQuery: { + type: "StructuredQuery", + id: 2 + }, + transaction: { + type: "bytes", + id: 5 + }, + newTransaction: { + type: "TransactionOptions", + id: 6 + }, + readTime: { + type: "google.protobuf.Timestamp", + id: 7 + } + } + }, + RunQueryResponse: { + fields: { + transaction: { + type: "bytes", + id: 2 + }, + document: { + type: "Document", + id: 1 + }, + readTime: { + type: "google.protobuf.Timestamp", + id: 3 + }, + skippedResults: { + type: "int32", + id: 4 + } + } + }, + RunAggregationQueryRequest: { + oneofs: { + queryType: { + oneof: [ + "structuredAggregationQuery" + ] + }, + consistencySelector: { + oneof: [ + "transaction", + "newTransaction", + "readTime" + ] + } + }, + fields: { + parent: { + type: "string", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + structuredAggregationQuery: { + type: "StructuredAggregationQuery", + id: 2 + }, + transaction: { + type: "bytes", + id: 4 + }, + newTransaction: { + type: "TransactionOptions", + id: 5 + }, + readTime: { + type: "google.protobuf.Timestamp", + id: 6 + } + } + }, + RunAggregationQueryResponse: { + fields: { + result: { + type: "AggregationResult", + id: 1 + }, + transaction: { + type: "bytes", + id: 2 + }, + readTime: { + type: "google.protobuf.Timestamp", + id: 3 + } + } + }, + PartitionQueryRequest: { + oneofs: { + queryType: { + oneof: [ + "structuredQuery" + ] + } + }, + fields: { + parent: { + type: "string", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + structuredQuery: { + type: "StructuredQuery", + id: 2 + }, + partitionCount: { + type: "int64", + id: 3 + }, + pageToken: { + type: "string", + id: 4 + }, + pageSize: { + type: "int32", + id: 5 + } + } + }, + PartitionQueryResponse: { + fields: { + partitions: { + rule: "repeated", + type: "Cursor", + id: 1 + }, + nextPageToken: { + type: "string", + id: 2 + } + } + }, + WriteRequest: { + fields: { + database: { + type: "string", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + streamId: { + type: "string", + id: 2 + }, + writes: { + rule: "repeated", + type: "Write", + id: 3 + }, + streamToken: { + type: "bytes", + id: 4 + }, + labels: { + keyType: "string", + type: "string", + id: 5 + } + } + }, + WriteResponse: { + fields: { + streamId: { + type: "string", + id: 1 + }, + streamToken: { + type: "bytes", + id: 2 + }, + writeResults: { + rule: "repeated", + type: "WriteResult", + id: 3 + }, + commitTime: { + type: "google.protobuf.Timestamp", + id: 4 + } + } + }, + ListenRequest: { + oneofs: { + targetChange: { + oneof: [ + "addTarget", + "removeTarget" + ] + } + }, + fields: { + database: { + type: "string", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + addTarget: { + type: "Target", + id: 2 + }, + removeTarget: { + type: "int32", + id: 3 + }, + labels: { + keyType: "string", + type: "string", + id: 4 + } + } + }, + ListenResponse: { + oneofs: { + responseType: { + oneof: [ + "targetChange", + "documentChange", + "documentDelete", + "documentRemove", + "filter" + ] + } + }, + fields: { + targetChange: { + type: "TargetChange", + id: 2 + }, + documentChange: { + type: "DocumentChange", + id: 3 + }, + documentDelete: { + type: "DocumentDelete", + id: 4 + }, + documentRemove: { + type: "DocumentRemove", + id: 6 + }, + filter: { + type: "ExistenceFilter", + id: 5 + } + } + }, + Target: { + oneofs: { + targetType: { + oneof: [ + "query", + "documents" + ] + }, + resumeType: { + oneof: [ + "resumeToken", + "readTime" + ] + } + }, + fields: { + query: { + type: "QueryTarget", + id: 2 + }, + documents: { + type: "DocumentsTarget", + id: 3 + }, + resumeToken: { + type: "bytes", + id: 4 + }, + readTime: { + type: "google.protobuf.Timestamp", + id: 11 + }, + targetId: { + type: "int32", + id: 5 + }, + once: { + type: "bool", + id: 6 + }, + expectedCount: { + type: "google.protobuf.Int32Value", + id: 12 + } + }, + nested: { + DocumentsTarget: { + fields: { + documents: { + rule: "repeated", + type: "string", + id: 2 + } + } + }, + QueryTarget: { + oneofs: { + queryType: { + oneof: [ + "structuredQuery" + ] + } + }, + fields: { + parent: { + type: "string", + id: 1 + }, + structuredQuery: { + type: "StructuredQuery", + id: 2 + } + } + } + } + }, + TargetChange: { + fields: { + targetChangeType: { + type: "TargetChangeType", + id: 1 + }, + targetIds: { + rule: "repeated", + type: "int32", + id: 2 + }, + cause: { + type: "google.rpc.Status", + id: 3 + }, + resumeToken: { + type: "bytes", + id: 4 + }, + readTime: { + type: "google.protobuf.Timestamp", + id: 6 + } + }, + nested: { + TargetChangeType: { + values: { + NO_CHANGE: 0, + ADD: 1, + REMOVE: 2, + CURRENT: 3, + RESET: 4 + } + } + } + }, + ListCollectionIdsRequest: { + fields: { + parent: { + type: "string", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + pageSize: { + type: "int32", + id: 2 + }, + pageToken: { + type: "string", + id: 3 + } + } + }, + ListCollectionIdsResponse: { + fields: { + collectionIds: { + rule: "repeated", + type: "string", + id: 1 + }, + nextPageToken: { + type: "string", + id: 2 + } + } + }, + BatchWriteRequest: { + fields: { + database: { + type: "string", + id: 1, + options: { + "(google.api.field_behavior)": "REQUIRED" + } + }, + writes: { + rule: "repeated", + type: "Write", + id: 2 + }, + labels: { + keyType: "string", + type: "string", + id: 3 + } + } + }, + BatchWriteResponse: { + fields: { + writeResults: { + rule: "repeated", + type: "WriteResult", + id: 1 + }, + status: { + rule: "repeated", + type: "google.rpc.Status", + id: 2 + } + } + }, + StructuredQuery: { + fields: { + select: { + type: "Projection", + id: 1 + }, + from: { + rule: "repeated", + type: "CollectionSelector", + id: 2 + }, + where: { + type: "Filter", + id: 3 + }, + orderBy: { + rule: "repeated", + type: "Order", + id: 4 + }, + startAt: { + type: "Cursor", + id: 7 + }, + endAt: { + type: "Cursor", + id: 8 + }, + offset: { + type: "int32", + id: 6 + }, + limit: { + type: "google.protobuf.Int32Value", + id: 5 + } + }, + nested: { + CollectionSelector: { + fields: { + collectionId: { + type: "string", + id: 2 + }, + allDescendants: { + type: "bool", + id: 3 + } + } + }, + Filter: { + oneofs: { + filterType: { + oneof: [ + "compositeFilter", + "fieldFilter", + "unaryFilter" + ] + } + }, + fields: { + compositeFilter: { + type: "CompositeFilter", + id: 1 + }, + fieldFilter: { + type: "FieldFilter", + id: 2 + }, + unaryFilter: { + type: "UnaryFilter", + id: 3 + } + } + }, + CompositeFilter: { + fields: { + op: { + type: "Operator", + id: 1 + }, + filters: { + rule: "repeated", + type: "Filter", + id: 2 + } + }, + nested: { + Operator: { + values: { + OPERATOR_UNSPECIFIED: 0, + AND: 1, + OR: 2 + } + } + } + }, + FieldFilter: { + fields: { + field: { + type: "FieldReference", + id: 1 + }, + op: { + type: "Operator", + id: 2 + }, + value: { + type: "Value", + id: 3 + } + }, + nested: { + Operator: { + values: { + OPERATOR_UNSPECIFIED: 0, + LESS_THAN: 1, + LESS_THAN_OR_EQUAL: 2, + GREATER_THAN: 3, + GREATER_THAN_OR_EQUAL: 4, + EQUAL: 5, + NOT_EQUAL: 6, + ARRAY_CONTAINS: 7, + IN: 8, + ARRAY_CONTAINS_ANY: 9, + NOT_IN: 10 + } + } + } + }, + UnaryFilter: { + oneofs: { + operandType: { + oneof: [ + "field" + ] + } + }, + fields: { + op: { + type: "Operator", + id: 1 + }, + field: { + type: "FieldReference", + id: 2 + } + }, + nested: { + Operator: { + values: { + OPERATOR_UNSPECIFIED: 0, + IS_NAN: 2, + IS_NULL: 3, + IS_NOT_NAN: 4, + IS_NOT_NULL: 5 + } + } + } + }, + Order: { + fields: { + field: { + type: "FieldReference", + id: 1 + }, + direction: { + type: "Direction", + id: 2 + } + } + }, + FieldReference: { + fields: { + fieldPath: { + type: "string", + id: 2 + } + } + }, + Projection: { + fields: { + fields: { + rule: "repeated", + type: "FieldReference", + id: 2 + } + } + }, + Direction: { + values: { + DIRECTION_UNSPECIFIED: 0, + ASCENDING: 1, + DESCENDING: 2 + } + } + } + }, + StructuredAggregationQuery: { + oneofs: { + queryType: { + oneof: [ + "structuredQuery" + ] + } + }, + fields: { + structuredQuery: { + type: "StructuredQuery", + id: 1 + }, + aggregations: { + rule: "repeated", + type: "Aggregation", + id: 3 + } + }, + nested: { + Aggregation: { + oneofs: { + operator: { + oneof: [ + "count", + "sum", + "avg" + ] + } + }, + fields: { + count: { + type: "Count", + id: 1 + }, + sum: { + type: "Sum", + id: 2 + }, + avg: { + type: "Avg", + id: 3 + }, + alias: { + type: "string", + id: 7 + } + }, + nested: { + Count: { + fields: { + upTo: { + type: "google.protobuf.Int64Value", + id: 1 + } + } + }, + Sum: { + fields: { + field: { + type: "FieldReference", + id: 1 + } + } + }, + Avg: { + fields: { + field: { + type: "FieldReference", + id: 1 + } + } + } + } + } + } + }, + Cursor: { + fields: { + values: { + rule: "repeated", + type: "Value", + id: 1 + }, + before: { + type: "bool", + id: 2 + } + } + }, + Write: { + oneofs: { + operation: { + oneof: [ + "update", + "delete", + "verify", + "transform" + ] + } + }, + fields: { + update: { + type: "Document", + id: 1 + }, + "delete": { + type: "string", + id: 2 + }, + verify: { + type: "string", + id: 5 + }, + transform: { + type: "DocumentTransform", + id: 6 + }, + updateMask: { + type: "DocumentMask", + id: 3 + }, + updateTransforms: { + rule: "repeated", + type: "DocumentTransform.FieldTransform", + id: 7 + }, + currentDocument: { + type: "Precondition", + id: 4 + } + } + }, + DocumentTransform: { + fields: { + document: { + type: "string", + id: 1 + }, + fieldTransforms: { + rule: "repeated", + type: "FieldTransform", + id: 2 + } + }, + nested: { + FieldTransform: { + oneofs: { + transformType: { + oneof: [ + "setToServerValue", + "increment", + "maximum", + "minimum", + "appendMissingElements", + "removeAllFromArray" + ] + } + }, + fields: { + fieldPath: { + type: "string", + id: 1 + }, + setToServerValue: { + type: "ServerValue", + id: 2 + }, + increment: { + type: "Value", + id: 3 + }, + maximum: { + type: "Value", + id: 4 + }, + minimum: { + type: "Value", + id: 5 + }, + appendMissingElements: { + type: "ArrayValue", + id: 6 + }, + removeAllFromArray: { + type: "ArrayValue", + id: 7 + } + }, + nested: { + ServerValue: { + values: { + SERVER_VALUE_UNSPECIFIED: 0, + REQUEST_TIME: 1 + } + } + } + } + } + }, + WriteResult: { + fields: { + updateTime: { + type: "google.protobuf.Timestamp", + id: 1 + }, + transformResults: { + rule: "repeated", + type: "Value", + id: 2 + } + } + }, + DocumentChange: { + fields: { + document: { + type: "Document", + id: 1 + }, + targetIds: { + rule: "repeated", + type: "int32", + id: 5 + }, + removedTargetIds: { + rule: "repeated", + type: "int32", + id: 6 + } + } + }, + DocumentDelete: { + fields: { + document: { + type: "string", + id: 1 + }, + removedTargetIds: { + rule: "repeated", + type: "int32", + id: 6 + }, + readTime: { + type: "google.protobuf.Timestamp", + id: 4 + } + } + }, + DocumentRemove: { + fields: { + document: { + type: "string", + id: 1 + }, + removedTargetIds: { + rule: "repeated", + type: "int32", + id: 2 + }, + readTime: { + type: "google.protobuf.Timestamp", + id: 4 + } + } + }, + ExistenceFilter: { + fields: { + targetId: { + type: "int32", + id: 1 + }, + count: { + type: "int32", + id: 2 + }, + unchangedNames: { + type: "BloomFilter", + id: 3 + } + } + } + } + } + } + }, + api: { + options: { + go_package: "google.golang.org/genproto/googleapis/api/annotations;annotations", + java_multiple_files: true, + java_outer_classname: "HttpProto", + java_package: "com.google.api", + objc_class_prefix: "GAPI", + cc_enable_arenas: true + }, + nested: { + http: { + type: "HttpRule", + id: 72295728, + extend: "google.protobuf.MethodOptions" + }, + Http: { + fields: { + rules: { + rule: "repeated", + type: "HttpRule", + id: 1 + } + } + }, + HttpRule: { + oneofs: { + pattern: { + oneof: [ + "get", + "put", + "post", + "delete", + "patch", + "custom" + ] + } + }, + fields: { + get: { + type: "string", + id: 2 + }, + put: { + type: "string", + id: 3 + }, + post: { + type: "string", + id: 4 + }, + "delete": { + type: "string", + id: 5 + }, + patch: { + type: "string", + id: 6 + }, + custom: { + type: "CustomHttpPattern", + id: 8 + }, + selector: { + type: "string", + id: 1 + }, + body: { + type: "string", + id: 7 + }, + additionalBindings: { + rule: "repeated", + type: "HttpRule", + id: 11 + } + } + }, + CustomHttpPattern: { + fields: { + kind: { + type: "string", + id: 1 + }, + path: { + type: "string", + id: 2 + } + } + }, + methodSignature: { + rule: "repeated", + type: "string", + id: 1051, + extend: "google.protobuf.MethodOptions" + }, + defaultHost: { + type: "string", + id: 1049, + extend: "google.protobuf.ServiceOptions" + }, + oauthScopes: { + type: "string", + id: 1050, + extend: "google.protobuf.ServiceOptions" + }, + fieldBehavior: { + rule: "repeated", + type: "google.api.FieldBehavior", + id: 1052, + extend: "google.protobuf.FieldOptions" + }, + FieldBehavior: { + values: { + FIELD_BEHAVIOR_UNSPECIFIED: 0, + OPTIONAL: 1, + REQUIRED: 2, + OUTPUT_ONLY: 3, + INPUT_ONLY: 4, + IMMUTABLE: 5, + UNORDERED_LIST: 6, + NON_EMPTY_DEFAULT: 7 + } + } + } + }, + type: { + options: { + cc_enable_arenas: true, + go_package: "google.golang.org/genproto/googleapis/type/latlng;latlng", + java_multiple_files: true, + java_outer_classname: "LatLngProto", + java_package: "com.google.type", + objc_class_prefix: "GTP" + }, + nested: { + LatLng: { + fields: { + latitude: { + type: "double", + id: 1 + }, + longitude: { + type: "double", + id: 2 + } + } + } + } + }, + rpc: { + options: { + cc_enable_arenas: true, + go_package: "google.golang.org/genproto/googleapis/rpc/status;status", + java_multiple_files: true, + java_outer_classname: "StatusProto", + java_package: "com.google.rpc", + objc_class_prefix: "RPC" + }, + nested: { + Status: { + fields: { + code: { + type: "int32", + id: 1 + }, + message: { + type: "string", + id: 2 + }, + details: { + rule: "repeated", + type: "google.protobuf.Any", + id: 3 + } + } + } + } + } + } + } +}; +var protos = { + nested: nested +}; + +var protos$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + nested: nested, + 'default': protos +}); + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Used by tests so we can match @grpc/proto-loader behavior. */ +const protoLoaderOptions = { + longs: String, + enums: String, + defaults: true, + oneofs: false +}; +/** + * Loads the protocol buffer definitions for Firestore. + * + * @returns The GrpcObject representing our protos. + */ +function loadProtos() { + const packageDefinition = protoLoader.fromJSON(protos$1, protoLoaderOptions); + return grpc.loadPackageDefinition(packageDefinition); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Loads the GRPC stack */ +function newConnection(databaseInfo) { + const protos = loadProtos(); + return new GrpcConnection(protos, databaseInfo); +} +/** Return the Platform-specific connectivity monitor. */ +function newConnectivityMonitor() { + return new NoopConnectivityMonitor(); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** The Platform's 'window' implementation or null if not available. */ +function getWindow() { + if (process.env.USE_MOCK_PERSISTENCE === 'YES') { + // eslint-disable-next-line no-restricted-globals + return window; + } + return null; +} +/** The Platform's 'document' implementation or null if not available. */ +function getDocument() { + return null; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function newSerializer(databaseId) { + return new JsonProtoSerializer(databaseId, /* useProto3Json= */ false); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$8 = 'ExponentialBackoff'; +/** + * Initial backoff time in milliseconds after an error. + * Set to 1s according to https://cloud.google.com/apis/design/errors. + */ +const DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000; +const DEFAULT_BACKOFF_FACTOR = 1.5; +/** Maximum backoff time in milliseconds */ +const DEFAULT_BACKOFF_MAX_DELAY_MS = 60 * 1000; +/** + * A helper for running delayed tasks following an exponential backoff curve + * between attempts. + * + * Each delay is made up of a "base" delay which follows the exponential + * backoff curve, and a +/- 50% "jitter" that is calculated and added to the + * base delay. This prevents clients from accidentally synchronizing their + * delays causing spikes of load to the backend. + */ +class ExponentialBackoff { + constructor( + /** + * The AsyncQueue to run backoff operations on. + */ + queue, + /** + * The ID to use when scheduling backoff operations on the AsyncQueue. + */ + timerId, + /** + * The initial delay (used as the base delay on the first retry attempt). + * Note that jitter will still be applied, so the actual delay could be as + * little as 0.5*initialDelayMs. + */ + initialDelayMs = DEFAULT_BACKOFF_INITIAL_DELAY_MS, + /** + * The multiplier to use to determine the extended base delay after each + * attempt. + */ + backoffFactor = DEFAULT_BACKOFF_FACTOR, + /** + * The maximum base delay after which no further backoff is performed. + * Note that jitter will still be applied, so the actual delay could be as + * much as 1.5*maxDelayMs. + */ + maxDelayMs = DEFAULT_BACKOFF_MAX_DELAY_MS) { + this.queue = queue; + this.timerId = timerId; + this.initialDelayMs = initialDelayMs; + this.backoffFactor = backoffFactor; + this.maxDelayMs = maxDelayMs; + this.currentBaseMs = 0; + this.timerPromise = null; + /** The last backoff attempt, as epoch milliseconds. */ + this.lastAttemptTime = Date.now(); + this.reset(); + } + /** + * Resets the backoff delay. + * + * The very next backoffAndWait() will have no delay. If it is called again + * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and + * subsequent ones will increase according to the backoffFactor. + */ + reset() { + this.currentBaseMs = 0; + } + /** + * Resets the backoff delay to the maximum delay (e.g. for use after a + * RESOURCE_EXHAUSTED error). + */ + resetToMax() { + this.currentBaseMs = this.maxDelayMs; + } + /** + * Returns a promise that resolves after currentDelayMs, and increases the + * delay for any subsequent attempts. If there was a pending backoff operation + * already, it will be canceled. + */ + backoffAndRun(op) { + // Cancel any pending backoff operation. + this.cancel(); + // First schedule using the current base (which may be 0 and should be + // honored as such). + const desiredDelayWithJitterMs = Math.floor(this.currentBaseMs + this.jitterDelayMs()); + // Guard against lastAttemptTime being in the future due to a clock change. + const delaySoFarMs = Math.max(0, Date.now() - this.lastAttemptTime); + // Guard against the backoff delay already being past. + const remainingDelayMs = Math.max(0, desiredDelayWithJitterMs - delaySoFarMs); + if (remainingDelayMs > 0) { + logDebug(LOG_TAG$8, `Backing off for ${remainingDelayMs} ms ` + + `(base delay: ${this.currentBaseMs} ms, ` + + `delay with jitter: ${desiredDelayWithJitterMs} ms, ` + + `last attempt: ${delaySoFarMs} ms ago)`); + } + this.timerPromise = this.queue.enqueueAfterDelay(this.timerId, remainingDelayMs, () => { + this.lastAttemptTime = Date.now(); + return op(); + }); + // Apply backoff factor to determine next delay and ensure it is within + // bounds. + this.currentBaseMs *= this.backoffFactor; + if (this.currentBaseMs < this.initialDelayMs) { + this.currentBaseMs = this.initialDelayMs; + } + if (this.currentBaseMs > this.maxDelayMs) { + this.currentBaseMs = this.maxDelayMs; + } + } + skipBackoff() { + if (this.timerPromise !== null) { + this.timerPromise.skipDelay(); + this.timerPromise = null; + } + } + cancel() { + if (this.timerPromise !== null) { + this.timerPromise.cancel(); + this.timerPromise = null; + } + } + /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ + jitterDelayMs() { + return (Math.random() - 0.5) * this.currentBaseMs; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$7 = 'PersistentStream'; +/** The time a stream stays open after it is marked idle. */ +const IDLE_TIMEOUT_MS = 60 * 1000; +/** The time a stream stays open until we consider it healthy. */ +const HEALTHY_TIMEOUT_MS = 10 * 1000; +/** + * A PersistentStream is an abstract base class that represents a streaming RPC + * to the Firestore backend. It's built on top of the connections own support + * for streaming RPCs, and adds several critical features for our clients: + * + * - Exponential backoff on failure + * - Authentication via CredentialsProvider + * - Dispatching all callbacks into the shared worker queue + * - Closing idle streams after 60 seconds of inactivity + * + * Subclasses of PersistentStream implement serialization of models to and + * from the JSON representation of the protocol buffers for a specific + * streaming RPC. + * + * ## Starting and Stopping + * + * Streaming RPCs are stateful and need to be start()ed before messages can + * be sent and received. The PersistentStream will call the onOpen() function + * of the listener once the stream is ready to accept requests. + * + * Should a start() fail, PersistentStream will call the registered onClose() + * listener with a FirestoreError indicating what went wrong. + * + * A PersistentStream can be started and stopped repeatedly. + * + * Generic types: + * SendType: The type of the outgoing message of the underlying + * connection stream + * ReceiveType: The type of the incoming message of the underlying + * connection stream + * ListenerType: The type of the listener that will be used for callbacks + */ +class PersistentStream { + constructor(queue, connectionTimerId, idleTimerId, healthTimerId, connection, authCredentialsProvider, appCheckCredentialsProvider, listener) { + this.queue = queue; + this.idleTimerId = idleTimerId; + this.healthTimerId = healthTimerId; + this.connection = connection; + this.authCredentialsProvider = authCredentialsProvider; + this.appCheckCredentialsProvider = appCheckCredentialsProvider; + this.listener = listener; + this.state = 0 /* PersistentStreamState.Initial */; + /** + * A close count that's incremented every time the stream is closed; used by + * getCloseGuardedDispatcher() to invalidate callbacks that happen after + * close. + */ + this.closeCount = 0; + this.idleTimer = null; + this.healthCheck = null; + this.stream = null; + /** + * Count of response messages received. + */ + this.responseCount = 0; + this.backoff = new ExponentialBackoff(queue, connectionTimerId); + } + /** + * Returns true if start() has been called and no error has occurred. True + * indicates the stream is open or in the process of opening (which + * encompasses respecting backoff, getting auth tokens, and starting the + * actual RPC). Use isOpen() to determine if the stream is open and ready for + * outbound requests. + */ + isStarted() { + return (this.state === 1 /* PersistentStreamState.Starting */ || + this.state === 5 /* PersistentStreamState.Backoff */ || + this.isOpen()); + } + /** + * Returns true if the underlying RPC is open (the onOpen() listener has been + * called) and the stream is ready for outbound requests. + */ + isOpen() { + return (this.state === 2 /* PersistentStreamState.Open */ || + this.state === 3 /* PersistentStreamState.Healthy */); + } + /** + * Starts the RPC. Only allowed if isStarted() returns false. The stream is + * not immediately ready for use: onOpen() will be invoked when the RPC is + * ready for outbound requests, at which point isOpen() will return true. + * + * When start returns, isStarted() will return true. + */ + start() { + this.responseCount = 0; + if (this.state === 4 /* PersistentStreamState.Error */) { + this.performBackoff(); + return; + } + this.auth(); + } + /** + * Stops the RPC. This call is idempotent and allowed regardless of the + * current isStarted() state. + * + * When stop returns, isStarted() and isOpen() will both return false. + */ + async stop() { + if (this.isStarted()) { + await this.close(0 /* PersistentStreamState.Initial */); + } + } + /** + * After an error the stream will usually back off on the next attempt to + * start it. If the error warrants an immediate restart of the stream, the + * sender can use this to indicate that the receiver should not back off. + * + * Each error will call the onClose() listener. That function can decide to + * inhibit backoff if required. + */ + inhibitBackoff() { + this.state = 0 /* PersistentStreamState.Initial */; + this.backoff.reset(); + } + /** + * Marks this stream as idle. If no further actions are performed on the + * stream for one minute, the stream will automatically close itself and + * notify the stream's onClose() handler with Status.OK. The stream will then + * be in a !isStarted() state, requiring the caller to start the stream again + * before further use. + * + * Only streams that are in state 'Open' can be marked idle, as all other + * states imply pending network operations. + */ + markIdle() { + // Starts the idle time if we are in state 'Open' and are not yet already + // running a timer (in which case the previous idle timeout still applies). + if (this.isOpen() && this.idleTimer === null) { + this.idleTimer = this.queue.enqueueAfterDelay(this.idleTimerId, IDLE_TIMEOUT_MS, () => this.handleIdleCloseTimer()); + } + } + /** Sends a message to the underlying stream. */ + sendRequest(msg) { + this.cancelIdleCheck(); + this.stream.send(msg); + } + /** Called by the idle timer when the stream should close due to inactivity. */ + async handleIdleCloseTimer() { + if (this.isOpen()) { + // When timing out an idle stream there's no reason to force the stream into backoff when + // it restarts so set the stream state to Initial instead of Error. + return this.close(0 /* PersistentStreamState.Initial */); + } + } + /** Marks the stream as active again. */ + cancelIdleCheck() { + if (this.idleTimer) { + this.idleTimer.cancel(); + this.idleTimer = null; + } + } + /** Cancels the health check delayed operation. */ + cancelHealthCheck() { + if (this.healthCheck) { + this.healthCheck.cancel(); + this.healthCheck = null; + } + } + /** + * Closes the stream and cleans up as necessary: + * + * * closes the underlying GRPC stream; + * * calls the onClose handler with the given 'error'; + * * sets internal stream state to 'finalState'; + * * adjusts the backoff timer based on the error + * + * A new stream can be opened by calling start(). + * + * @param finalState - the intended state of the stream after closing. + * @param error - the error the connection was closed with. + */ + async close(finalState, error) { + // Cancel any outstanding timers (they're guaranteed not to execute). + this.cancelIdleCheck(); + this.cancelHealthCheck(); + this.backoff.cancel(); + // Invalidates any stream-related callbacks (e.g. from auth or the + // underlying stream), guaranteeing they won't execute. + this.closeCount++; + if (finalState !== 4 /* PersistentStreamState.Error */) { + // If this is an intentional close ensure we don't delay our next connection attempt. + this.backoff.reset(); + } + else if (error && error.code === Code.RESOURCE_EXHAUSTED) { + // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.) + logError(error.toString()); + logError('Using maximum backoff delay to prevent overloading the backend.'); + this.backoff.resetToMax(); + } + else if (error && + error.code === Code.UNAUTHENTICATED && + this.state !== 3 /* PersistentStreamState.Healthy */) { + // "unauthenticated" error means the token was rejected. This should rarely + // happen since both Auth and AppCheck ensure a sufficient TTL when we + // request a token. If a user manually resets their system clock this can + // fail, however. In this case, we should get a Code.UNAUTHENTICATED error + // before we received the first message and we need to invalidate the token + // to ensure that we fetch a new token. + this.authCredentialsProvider.invalidateToken(); + this.appCheckCredentialsProvider.invalidateToken(); + } + // Clean up the underlying stream because we are no longer interested in events. + if (this.stream !== null) { + this.tearDown(); + this.stream.close(); + this.stream = null; + } + // This state must be assigned before calling onClose() to allow the callback to + // inhibit backoff or otherwise manipulate the state in its non-started state. + this.state = finalState; + // Notify the listener that the stream closed. + await this.listener.onClose(error); + } + /** + * Can be overridden to perform additional cleanup before the stream is closed. + * Calling super.tearDown() is not required. + */ + tearDown() { } + auth() { + this.state = 1 /* PersistentStreamState.Starting */; + const dispatchIfNotClosed = this.getCloseGuardedDispatcher(this.closeCount); + // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below. + const closeCount = this.closeCount; + Promise.all([ + this.authCredentialsProvider.getToken(), + this.appCheckCredentialsProvider.getToken() + ]).then(([authToken, appCheckToken]) => { + // Stream can be stopped while waiting for authentication. + // TODO(mikelehen): We really should just use dispatchIfNotClosed + // and let this dispatch onto the queue, but that opened a spec test can + // of worms that I don't want to deal with in this PR. + if (this.closeCount === closeCount) { + // Normally we'd have to schedule the callback on the AsyncQueue. + // However, the following calls are safe to be called outside the + // AsyncQueue since they don't chain asynchronous calls + this.startStream(authToken, appCheckToken); + } + }, (error) => { + dispatchIfNotClosed(() => { + const rpcError = new FirestoreError(Code.UNKNOWN, 'Fetching auth token failed: ' + error.message); + return this.handleStreamClose(rpcError); + }); + }); + } + startStream(authToken, appCheckToken) { + const dispatchIfNotClosed = this.getCloseGuardedDispatcher(this.closeCount); + this.stream = this.startRpc(authToken, appCheckToken); + this.stream.onConnected(() => { + dispatchIfNotClosed(() => this.listener.onConnected()); + }); + this.stream.onOpen(() => { + dispatchIfNotClosed(() => { + this.state = 2 /* PersistentStreamState.Open */; + this.healthCheck = this.queue.enqueueAfterDelay(this.healthTimerId, HEALTHY_TIMEOUT_MS, () => { + if (this.isOpen()) { + this.state = 3 /* PersistentStreamState.Healthy */; + } + return Promise.resolve(); + }); + return this.listener.onOpen(); + }); + }); + this.stream.onClose((error) => { + dispatchIfNotClosed(() => { + return this.handleStreamClose(error); + }); + }); + this.stream.onMessage((msg) => { + dispatchIfNotClosed(() => { + if (++this.responseCount === 1) { + return this.onFirst(msg); + } + else { + return this.onNext(msg); + } + }); + }); + } + performBackoff() { + this.state = 5 /* PersistentStreamState.Backoff */; + this.backoff.backoffAndRun(async () => { + this.state = 0 /* PersistentStreamState.Initial */; + this.start(); + }); + } + // Visible for tests + handleStreamClose(error) { + logDebug(LOG_TAG$7, `close with error: ${error}`); + this.stream = null; + // In theory the stream could close cleanly, however, in our current model + // we never expect this to happen because if we stop a stream ourselves, + // this callback will never be called. To prevent cases where we retry + // without a backoff accidentally, we set the stream to error in all cases. + return this.close(4 /* PersistentStreamState.Error */, error); + } + /** + * Returns a "dispatcher" function that dispatches operations onto the + * AsyncQueue but only runs them if closeCount remains unchanged. This allows + * us to turn auth / stream callbacks into no-ops if the stream is closed / + * re-opened, etc. + */ + getCloseGuardedDispatcher(startCloseCount) { + return (fn) => { + this.queue.enqueueAndForget(() => { + if (this.closeCount === startCloseCount) { + return fn(); + } + else { + logDebug(LOG_TAG$7, 'stream callback skipped by getCloseGuardedDispatcher.'); + return Promise.resolve(); + } + }); + }; + } +} +/** + * A PersistentStream that implements the Listen RPC. + * + * Once the Listen stream has called the onOpen() listener, any number of + * listen() and unlisten() calls can be made to control what changes will be + * sent from the server for ListenResponses. + */ +class PersistentListenStream extends PersistentStream { + constructor(queue, connection, authCredentials, appCheckCredentials, serializer, listener) { + super(queue, "listen_stream_connection_backoff" /* TimerId.ListenStreamConnectionBackoff */, "listen_stream_idle" /* TimerId.ListenStreamIdle */, "health_check_timeout" /* TimerId.HealthCheckTimeout */, connection, authCredentials, appCheckCredentials, listener); + this.serializer = serializer; + } + startRpc(authToken, appCheckToken) { + return this.connection.openStream('Listen', authToken, appCheckToken); + } + onFirst(watchChangeProto) { + return this.onNext(watchChangeProto); + } + onNext(watchChangeProto) { + // A successful response means the stream is healthy + this.backoff.reset(); + const watchChange = fromWatchChange(this.serializer, watchChangeProto); + const snapshot = versionFromListenResponse(watchChangeProto); + return this.listener.onWatchChange(watchChange, snapshot); + } + /** + * Registers interest in the results of the given target. If the target + * includes a resumeToken it will be included in the request. Results that + * affect the target will be streamed back as WatchChange messages that + * reference the targetId. + */ + watch(targetData) { + const request = {}; + request.database = getEncodedDatabaseId(this.serializer); + request.addTarget = toTarget(this.serializer, targetData); + const labels = toListenRequestLabels(this.serializer, targetData); + if (labels) { + request.labels = labels; + } + this.sendRequest(request); + } + /** + * Unregisters interest in the results of the target associated with the + * given targetId. + */ + unwatch(targetId) { + const request = {}; + request.database = getEncodedDatabaseId(this.serializer); + request.removeTarget = targetId; + this.sendRequest(request); + } +} +/** + * A Stream that implements the Write RPC. + * + * The Write RPC requires the caller to maintain special streamToken + * state in between calls, to help the server understand which responses the + * client has processed by the time the next request is made. Every response + * will contain a streamToken; this value must be passed to the next + * request. + * + * After calling start() on this stream, the next request must be a handshake, + * containing whatever streamToken is on hand. Once a response to this + * request is received, all pending mutations may be submitted. When + * submitting multiple batches of mutations at the same time, it's + * okay to use the same streamToken for the calls to writeMutations. + * + * TODO(b/33271235): Use proto types + */ +class PersistentWriteStream extends PersistentStream { + constructor(queue, connection, authCredentials, appCheckCredentials, serializer, listener) { + super(queue, "write_stream_connection_backoff" /* TimerId.WriteStreamConnectionBackoff */, "write_stream_idle" /* TimerId.WriteStreamIdle */, "health_check_timeout" /* TimerId.HealthCheckTimeout */, connection, authCredentials, appCheckCredentials, listener); + this.serializer = serializer; + } + /** + * Tracks whether or not a handshake has been successfully exchanged and + * the stream is ready to accept mutations. + */ + get handshakeComplete() { + return this.responseCount > 0; + } + // Override of PersistentStream.start + start() { + this.lastStreamToken = undefined; + super.start(); + } + tearDown() { + if (this.handshakeComplete) { + this.writeMutations([]); + } + } + startRpc(authToken, appCheckToken) { + return this.connection.openStream('Write', authToken, appCheckToken); + } + onFirst(responseProto) { + // Always capture the last stream token. + hardAssert(!!responseProto.streamToken, 0x7a5a); + this.lastStreamToken = responseProto.streamToken; + // The first response is always the handshake response + hardAssert(!responseProto.writeResults || responseProto.writeResults.length === 0, 0xda08); + return this.listener.onHandshakeComplete(); + } + onNext(responseProto) { + // Always capture the last stream token. + hardAssert(!!responseProto.streamToken, 0x3186); + this.lastStreamToken = responseProto.streamToken; + // A successful first write response means the stream is healthy, + // Note, that we could consider a successful handshake healthy, however, + // the write itself might be causing an error we want to back off from. + this.backoff.reset(); + const results = fromWriteResults(responseProto.writeResults, responseProto.commitTime); + const commitVersion = fromVersion(responseProto.commitTime); + return this.listener.onMutationResult(commitVersion, results); + } + /** + * Sends an initial streamToken to the server, performing the handshake + * required to make the StreamingWrite RPC work. Subsequent + * calls should wait until onHandshakeComplete was called. + */ + writeHandshake() { + // TODO(dimond): Support stream resumption. We intentionally do not set the + // stream token on the handshake, ignoring any stream token we might have. + const request = {}; + request.database = getEncodedDatabaseId(this.serializer); + this.sendRequest(request); + } + /** Sends a group of mutations to the Firestore backend to apply. */ + writeMutations(mutations) { + const request = { + streamToken: this.lastStreamToken, + writes: mutations.map(mutation => toMutation(this.serializer, mutation)) + }; + this.sendRequest(request); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Datastore and its related methods are a wrapper around the external Google + * Cloud Datastore grpc API, which provides an interface that is more convenient + * for the rest of the client SDK architecture to consume. + */ +class Datastore { +} +/** + * An implementation of Datastore that exposes additional state for internal + * consumption. + */ +class DatastoreImpl extends Datastore { + constructor(authCredentials, appCheckCredentials, connection, serializer) { + super(); + this.authCredentials = authCredentials; + this.appCheckCredentials = appCheckCredentials; + this.connection = connection; + this.serializer = serializer; + this.terminated = false; + } + verifyInitialized() { + if (this.terminated) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'The client has already been terminated.'); + } + } + /** Invokes the provided RPC with auth and AppCheck tokens. */ + invokeRPC(rpcName, databaseId, resourcePath, request) { + this.verifyInitialized(); + return Promise.all([ + this.authCredentials.getToken(), + this.appCheckCredentials.getToken() + ]) + .then(([authToken, appCheckToken]) => { + return this.connection.invokeRPC(rpcName, toResourcePath(databaseId, resourcePath), request, authToken, appCheckToken); + }) + .catch((error) => { + if (error.name === 'FirebaseError') { + if (error.code === Code.UNAUTHENTICATED) { + this.authCredentials.invalidateToken(); + this.appCheckCredentials.invalidateToken(); + } + throw error; + } + else { + throw new FirestoreError(Code.UNKNOWN, error.toString()); + } + }); + } + /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ + invokeStreamingRPC(rpcName, databaseId, resourcePath, request, expectedResponseCount) { + this.verifyInitialized(); + return Promise.all([ + this.authCredentials.getToken(), + this.appCheckCredentials.getToken() + ]) + .then(([authToken, appCheckToken]) => { + return this.connection.invokeStreamingRPC(rpcName, toResourcePath(databaseId, resourcePath), request, authToken, appCheckToken, expectedResponseCount); + }) + .catch((error) => { + if (error.name === 'FirebaseError') { + if (error.code === Code.UNAUTHENTICATED) { + this.authCredentials.invalidateToken(); + this.appCheckCredentials.invalidateToken(); + } + throw error; + } + else { + throw new FirestoreError(Code.UNKNOWN, error.toString()); + } + }); + } + terminate() { + this.terminated = true; + this.connection.terminate(); + } +} +// TODO(firestorexp): Make sure there is only one Datastore instance per +// firestore-exp client. +function newDatastore(authCredentials, appCheckCredentials, connection, serializer) { + return new DatastoreImpl(authCredentials, appCheckCredentials, connection, serializer); +} +async function invokeCommitRpc(datastore, mutations) { + const datastoreImpl = debugCast(datastore); + const request = { + writes: mutations.map(m => toMutation(datastoreImpl.serializer, m)) + }; + await datastoreImpl.invokeRPC('Commit', datastoreImpl.serializer.databaseId, ResourcePath.emptyPath(), request); +} +async function invokeBatchGetDocumentsRpc(datastore, keys) { + const datastoreImpl = debugCast(datastore); + const request = { + documents: keys.map(k => toName(datastoreImpl.serializer, k)) + }; + const response = await datastoreImpl.invokeStreamingRPC('BatchGetDocuments', datastoreImpl.serializer.databaseId, ResourcePath.emptyPath(), request, keys.length); + const docs = new Map(); + response.forEach(proto => { + const doc = fromBatchGetDocumentsResponse(datastoreImpl.serializer, proto); + docs.set(doc.key.toString(), doc); + }); + const result = []; + keys.forEach(key => { + const doc = docs.get(key.toString()); + hardAssert(!!doc, 0xd7c2, { + key + }); + result.push(doc); + }); + return result; +} +async function invokeRunAggregationQueryRpc(datastore, query, aggregates) { + const datastoreImpl = debugCast(datastore); + const { request, aliasMap, parent } = toRunAggregationQueryRequest(datastoreImpl.serializer, queryToAggregateTarget(query), aggregates); + if (!datastoreImpl.connection.shouldResourcePathBeIncludedInRequest) { + delete request.parent; + } + const response = await datastoreImpl.invokeStreamingRPC('RunAggregationQuery', datastoreImpl.serializer.databaseId, parent, request, + /*expectedResponseCount=*/ 1); + // Omit RunAggregationQueryResponse that only contain readTimes. + const filteredResult = response.filter(proto => !!proto.result); + hardAssert(filteredResult.length === 1, 0xfcd7); + // Remap the short-form aliases that were sent to the server + // to the client-side aliases. Users will access the results + // using the client-side alias. + const unmappedAggregateFields = filteredResult[0].result?.aggregateFields; + const remappedFields = Object.keys(unmappedAggregateFields).reduce((accumulator, key) => { + accumulator[aliasMap[key]] = unmappedAggregateFields[key]; + return accumulator; + }, {}); + return remappedFields; +} +function newPersistentWriteStream(datastore, queue, listener) { + const datastoreImpl = debugCast(datastore); + datastoreImpl.verifyInitialized(); + return new PersistentWriteStream(queue, datastoreImpl.connection, datastoreImpl.authCredentials, datastoreImpl.appCheckCredentials, datastoreImpl.serializer, listener); +} +function newPersistentWatchStream(datastore, queue, listener) { + const datastoreImpl = debugCast(datastore); + datastoreImpl.verifyInitialized(); + return new PersistentListenStream(queue, datastoreImpl.connection, datastoreImpl.authCredentials, datastoreImpl.appCheckCredentials, datastoreImpl.serializer, listener); +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$6 = 'OnlineStateTracker'; +// To deal with transient failures, we allow multiple stream attempts before +// giving up and transitioning from OnlineState.Unknown to Offline. +// TODO(mikelehen): This used to be set to 2 as a mitigation for b/66228394. +// @jdimond thinks that bug is sufficiently fixed so that we can set this back +// to 1. If that works okay, we could potentially remove this logic entirely. +const MAX_WATCH_STREAM_FAILURES = 1; +// To deal with stream attempts that don't succeed or fail in a timely manner, +// we have a timeout for OnlineState to reach Online or Offline. +// If the timeout is reached, we transition to Offline rather than waiting +// indefinitely. +const ONLINE_STATE_TIMEOUT_MS = 10 * 1000; +/** + * A component used by the RemoteStore to track the OnlineState (that is, + * whether or not the client as a whole should be considered to be online or + * offline), implementing the appropriate heuristics. + * + * In particular, when the client is trying to connect to the backend, we + * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for + * a connection to succeed. If we have too many failures or the timeout elapses, + * then we set the OnlineState to Offline, and the client will behave as if + * it is offline (get()s will return cached data, etc.). + */ +class OnlineStateTracker { + constructor(asyncQueue, onlineStateHandler) { + this.asyncQueue = asyncQueue; + this.onlineStateHandler = onlineStateHandler; + /** The current OnlineState. */ + this.state = "Unknown" /* OnlineState.Unknown */; + /** + * A count of consecutive failures to open the stream. If it reaches the + * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to + * Offline. + */ + this.watchStreamFailures = 0; + /** + * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we + * transition from OnlineState.Unknown to OnlineState.Offline without waiting + * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times). + */ + this.onlineStateTimer = null; + /** + * Whether the client should log a warning message if it fails to connect to + * the backend (initially true, cleared after a successful stream, or if we've + * logged the message already). + */ + this.shouldWarnClientIsOffline = true; + } + /** + * Called by RemoteStore when a watch stream is started (including on each + * backoff attempt). + * + * If this is the first attempt, it sets the OnlineState to Unknown and starts + * the onlineStateTimer. + */ + handleWatchStreamStart() { + if (this.watchStreamFailures === 0) { + this.setAndBroadcast("Unknown" /* OnlineState.Unknown */); + this.onlineStateTimer = this.asyncQueue.enqueueAfterDelay("online_state_timeout" /* TimerId.OnlineStateTimeout */, ONLINE_STATE_TIMEOUT_MS, () => { + this.onlineStateTimer = null; + this.logClientOfflineWarningIfNecessary(`Backend didn't respond within ${ONLINE_STATE_TIMEOUT_MS / 1000} ` + + `seconds.`); + this.setAndBroadcast("Offline" /* OnlineState.Offline */); + // NOTE: handleWatchStreamFailure() will continue to increment + // watchStreamFailures even though we are already marked Offline, + // but this is non-harmful. + return Promise.resolve(); + }); + } + } + /** + * Updates our OnlineState as appropriate after the watch stream reports a + * failure. The first failure moves us to the 'Unknown' state. We then may + * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we + * actually transition to the 'Offline' state. + */ + handleWatchStreamFailure(error) { + if (this.state === "Online" /* OnlineState.Online */) { + this.setAndBroadcast("Unknown" /* OnlineState.Unknown */); + } + else { + this.watchStreamFailures++; + if (this.watchStreamFailures >= MAX_WATCH_STREAM_FAILURES) { + this.clearOnlineStateTimer(); + this.logClientOfflineWarningIfNecessary(`Connection failed ${MAX_WATCH_STREAM_FAILURES} ` + + `times. Most recent error: ${error.toString()}`); + this.setAndBroadcast("Offline" /* OnlineState.Offline */); + } + } + } + /** + * Explicitly sets the OnlineState to the specified state. + * + * Note that this resets our timers / failure counters, etc. used by our + * Offline heuristics, so must not be used in place of + * handleWatchStreamStart() and handleWatchStreamFailure(). + */ + set(newState) { + this.clearOnlineStateTimer(); + this.watchStreamFailures = 0; + if (newState === "Online" /* OnlineState.Online */) { + // We've connected to watch at least once. Don't warn the developer + // about being offline going forward. + this.shouldWarnClientIsOffline = false; + } + this.setAndBroadcast(newState); + } + setAndBroadcast(newState) { + if (newState !== this.state) { + this.state = newState; + this.onlineStateHandler(newState); + } + } + logClientOfflineWarningIfNecessary(details) { + const message = `Could not reach Cloud Firestore backend. ${details}\n` + + `This typically indicates that your device does not have a healthy ` + + `Internet connection at the moment. The client will operate in offline ` + + `mode until it is able to successfully connect to the backend.`; + if (this.shouldWarnClientIsOffline) { + logError(message); + this.shouldWarnClientIsOffline = false; + } + else { + logDebug(LOG_TAG$6, message); + } + } + clearOnlineStateTimer() { + if (this.onlineStateTimer !== null) { + this.onlineStateTimer.cancel(); + this.onlineStateTimer = null; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$5 = 'RemoteStore'; +// TODO(b/35853402): Negotiate this with the stream. +const MAX_PENDING_WRITES = 10; +class RemoteStoreImpl { + constructor( + /** + * The local store, used to fill the write pipeline with outbound mutations. + */ + localStore, + /** The client-side proxy for interacting with the backend. */ + datastore, asyncQueue, onlineStateHandler, connectivityMonitor) { + this.localStore = localStore; + this.datastore = datastore; + this.asyncQueue = asyncQueue; + this.remoteSyncer = {}; + /** + * A list of up to MAX_PENDING_WRITES writes that we have fetched from the + * LocalStore via fillWritePipeline() and have or will send to the write + * stream. + * + * Whenever writePipeline.length > 0 the RemoteStore will attempt to start or + * restart the write stream. When the stream is established the writes in the + * pipeline will be sent in order. + * + * Writes remain in writePipeline until they are acknowledged by the backend + * and thus will automatically be re-sent if the stream is interrupted / + * restarted before they're acknowledged. + * + * Write responses from the backend are linked to their originating request + * purely based on order, and so we can just shift() writes from the front of + * the writePipeline as we receive responses. + */ + this.writePipeline = []; + /** + * A mapping of watched targets that the client cares about tracking and the + * user has explicitly called a 'listen' for this target. + * + * These targets may or may not have been sent to or acknowledged by the + * server. On re-establishing the listen stream, these targets should be sent + * to the server. The targets removed with unlistens are removed eagerly + * without waiting for confirmation from the listen stream. + */ + this.listenTargets = new Map(); + /** + * A set of reasons for why the RemoteStore may be offline. If empty, the + * RemoteStore may start its network connections. + */ + this.offlineCauses = new Set(); + /** + * Event handlers that get called when the network is disabled or enabled. + * + * PORTING NOTE: These functions are used on the Web client to create the + * underlying streams (to support tree-shakeable streams). On Android and iOS, + * the streams are created during construction of RemoteStore. + */ + this.onNetworkStatusChange = []; + this.connectivityMonitor = connectivityMonitor; + this.connectivityMonitor.addCallback((_) => { + asyncQueue.enqueueAndForget(async () => { + // Porting Note: Unlike iOS, `restartNetwork()` is called even when the + // network becomes unreachable as we don't have any other way to tear + // down our streams. + if (canUseNetwork(this)) { + logDebug(LOG_TAG$5, 'Restarting streams for network reachability change.'); + await restartNetwork(this); + } + }); + }); + this.onlineStateTracker = new OnlineStateTracker(asyncQueue, onlineStateHandler); + } +} +function newRemoteStore(localStore, datastore, asyncQueue, onlineStateHandler, connectivityMonitor) { + return new RemoteStoreImpl(localStore, datastore, asyncQueue, onlineStateHandler, connectivityMonitor); +} +/** Re-enables the network. Idempotent. */ +function remoteStoreEnableNetwork(remoteStore) { + const remoteStoreImpl = debugCast(remoteStore); + remoteStoreImpl.offlineCauses.delete(0 /* OfflineCause.UserDisabled */); + return enableNetworkInternal(remoteStoreImpl); +} +async function enableNetworkInternal(remoteStoreImpl) { + if (canUseNetwork(remoteStoreImpl)) { + for (const networkStatusHandler of remoteStoreImpl.onNetworkStatusChange) { + await networkStatusHandler(/* enabled= */ true); + } + } +} +/** + * Temporarily disables the network. The network can be re-enabled using + * enableNetwork(). + */ +async function remoteStoreDisableNetwork(remoteStore) { + const remoteStoreImpl = debugCast(remoteStore); + remoteStoreImpl.offlineCauses.add(0 /* OfflineCause.UserDisabled */); + await disableNetworkInternal(remoteStoreImpl); + // Set the OnlineState to Offline so get()s return from cache, etc. + remoteStoreImpl.onlineStateTracker.set("Offline" /* OnlineState.Offline */); +} +async function disableNetworkInternal(remoteStoreImpl) { + for (const networkStatusHandler of remoteStoreImpl.onNetworkStatusChange) { + await networkStatusHandler(/* enabled= */ false); + } +} +async function remoteStoreShutdown(remoteStore) { + const remoteStoreImpl = debugCast(remoteStore); + logDebug(LOG_TAG$5, 'RemoteStore shutting down.'); + remoteStoreImpl.offlineCauses.add(5 /* OfflineCause.Shutdown */); + await disableNetworkInternal(remoteStoreImpl); + remoteStoreImpl.connectivityMonitor.shutdown(); + // Set the OnlineState to Unknown (rather than Offline) to avoid potentially + // triggering spurious listener events with cached data, etc. + remoteStoreImpl.onlineStateTracker.set("Unknown" /* OnlineState.Unknown */); +} +/** + * Starts new listen for the given target. Uses resume token if provided. It + * is a no-op if the target of given `TargetData` is already being listened to. + */ +function remoteStoreListen(remoteStore, targetData) { + const remoteStoreImpl = debugCast(remoteStore); + if (remoteStoreImpl.listenTargets.has(targetData.targetId)) { + return; + } + // Mark this as something the client is currently listening for. + remoteStoreImpl.listenTargets.set(targetData.targetId, targetData); + if (shouldStartWatchStream(remoteStoreImpl)) { + // The listen will be sent in onWatchStreamOpen + startWatchStream(remoteStoreImpl); + } + else if (ensureWatchStream(remoteStoreImpl).isOpen()) { + sendWatchRequest(remoteStoreImpl, targetData); + } +} +/** + * Removes the listen from server. It is a no-op if the given target id is + * not being listened to. + */ +function remoteStoreUnlisten(remoteStore, targetId) { + const remoteStoreImpl = debugCast(remoteStore); + const watchStream = ensureWatchStream(remoteStoreImpl); + remoteStoreImpl.listenTargets.delete(targetId); + if (watchStream.isOpen()) { + sendUnwatchRequest(remoteStoreImpl, targetId); + } + if (remoteStoreImpl.listenTargets.size === 0) { + if (watchStream.isOpen()) { + watchStream.markIdle(); + } + else if (canUseNetwork(remoteStoreImpl)) { + // Revert to OnlineState.Unknown if the watch stream is not open and we + // have no listeners, since without any listens to send we cannot + // confirm if the stream is healthy and upgrade to OnlineState.Online. + remoteStoreImpl.onlineStateTracker.set("Unknown" /* OnlineState.Unknown */); + } + } +} +/** + * We need to increment the expected number of pending responses we're due + * from watch so we wait for the ack to process any messages from this target. + */ +function sendWatchRequest(remoteStoreImpl, targetData) { + remoteStoreImpl.watchChangeAggregator.recordPendingTargetRequest(targetData.targetId); + if (targetData.resumeToken.approximateByteSize() > 0 || + targetData.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) { + const expectedCount = remoteStoreImpl.remoteSyncer.getRemoteKeysForTarget(targetData.targetId).size; + targetData = targetData.withExpectedCount(expectedCount); + } + ensureWatchStream(remoteStoreImpl).watch(targetData); +} +/** + * We need to increment the expected number of pending responses we're due + * from watch so we wait for the removal on the server before we process any + * messages from this target. + */ +function sendUnwatchRequest(remoteStoreImpl, targetId) { + remoteStoreImpl.watchChangeAggregator.recordPendingTargetRequest(targetId); + ensureWatchStream(remoteStoreImpl).unwatch(targetId); +} +function startWatchStream(remoteStoreImpl) { + remoteStoreImpl.watchChangeAggregator = new WatchChangeAggregator({ + getRemoteKeysForTarget: targetId => remoteStoreImpl.remoteSyncer.getRemoteKeysForTarget(targetId), + getTargetDataForTarget: targetId => remoteStoreImpl.listenTargets.get(targetId) || null, + getDatabaseId: () => remoteStoreImpl.datastore.serializer.databaseId + }); + ensureWatchStream(remoteStoreImpl).start(); + remoteStoreImpl.onlineStateTracker.handleWatchStreamStart(); +} +/** + * Returns whether the watch stream should be started because it's necessary + * and has not yet been started. + */ +function shouldStartWatchStream(remoteStoreImpl) { + return (canUseNetwork(remoteStoreImpl) && + !ensureWatchStream(remoteStoreImpl).isStarted() && + remoteStoreImpl.listenTargets.size > 0); +} +function canUseNetwork(remoteStore) { + const remoteStoreImpl = debugCast(remoteStore); + return remoteStoreImpl.offlineCauses.size === 0; +} +function cleanUpWatchStreamState(remoteStoreImpl) { + remoteStoreImpl.watchChangeAggregator = undefined; +} +async function onWatchStreamConnected(remoteStoreImpl) { + // Mark the client as online since we got a "connected" notification. + remoteStoreImpl.onlineStateTracker.set("Online" /* OnlineState.Online */); +} +async function onWatchStreamOpen(remoteStoreImpl) { + remoteStoreImpl.listenTargets.forEach((targetData, targetId) => { + sendWatchRequest(remoteStoreImpl, targetData); + }); +} +async function onWatchStreamClose(remoteStoreImpl, error) { + cleanUpWatchStreamState(remoteStoreImpl); + // If we still need the watch stream, retry the connection. + if (shouldStartWatchStream(remoteStoreImpl)) { + remoteStoreImpl.onlineStateTracker.handleWatchStreamFailure(error); + startWatchStream(remoteStoreImpl); + } + else { + // No need to restart watch stream because there are no active targets. + // The online state is set to unknown because there is no active attempt + // at establishing a connection + remoteStoreImpl.onlineStateTracker.set("Unknown" /* OnlineState.Unknown */); + } +} +async function onWatchStreamChange(remoteStoreImpl, watchChange, snapshotVersion) { + // Mark the client as online since we got a message from the server + remoteStoreImpl.onlineStateTracker.set("Online" /* OnlineState.Online */); + if (watchChange instanceof WatchTargetChange && + watchChange.state === 2 /* WatchTargetChangeState.Removed */ && + watchChange.cause) { + // There was an error on a target, don't wait for a consistent snapshot + // to raise events + try { + await handleTargetError(remoteStoreImpl, watchChange); + } + catch (e) { + logDebug(LOG_TAG$5, 'Failed to remove targets %s: %s ', watchChange.targetIds.join(','), e); + await disableNetworkUntilRecovery(remoteStoreImpl, e); + } + return; + } + if (watchChange instanceof DocumentWatchChange) { + remoteStoreImpl.watchChangeAggregator.handleDocumentChange(watchChange); + } + else if (watchChange instanceof ExistenceFilterChange) { + remoteStoreImpl.watchChangeAggregator.handleExistenceFilter(watchChange); + } + else { + remoteStoreImpl.watchChangeAggregator.handleTargetChange(watchChange); + } + if (!snapshotVersion.isEqual(SnapshotVersion.min())) { + try { + const lastRemoteSnapshotVersion = await localStoreGetLastRemoteSnapshotVersion(remoteStoreImpl.localStore); + if (snapshotVersion.compareTo(lastRemoteSnapshotVersion) >= 0) { + // We have received a target change with a global snapshot if the snapshot + // version is not equal to SnapshotVersion.min(). + await raiseWatchSnapshot(remoteStoreImpl, snapshotVersion); + } + } + catch (e) { + logDebug(LOG_TAG$5, 'Failed to raise snapshot:', e); + await disableNetworkUntilRecovery(remoteStoreImpl, e); + } + } +} +/** + * Recovery logic for IndexedDB errors that takes the network offline until + * `op` succeeds. Retries are scheduled with backoff using + * `enqueueRetryable()`. If `op()` is not provided, IndexedDB access is + * validated via a generic operation. + * + * The returned Promise is resolved once the network is disabled and before + * any retry attempt. + */ +async function disableNetworkUntilRecovery(remoteStoreImpl, e, op) { + if (isIndexedDbTransactionError(e)) { + remoteStoreImpl.offlineCauses.add(1 /* OfflineCause.IndexedDbFailed */); + // Disable network and raise offline snapshots + await disableNetworkInternal(remoteStoreImpl); + remoteStoreImpl.onlineStateTracker.set("Offline" /* OnlineState.Offline */); + if (!op) { + // Use a simple read operation to determine if IndexedDB recovered. + // Ideally, we would expose a health check directly on SimpleDb, but + // RemoteStore only has access to persistence through LocalStore. + op = () => localStoreGetLastRemoteSnapshotVersion(remoteStoreImpl.localStore); + } + // Probe IndexedDB periodically and re-enable network + remoteStoreImpl.asyncQueue.enqueueRetryable(async () => { + logDebug(LOG_TAG$5, 'Retrying IndexedDB access'); + await op(); + remoteStoreImpl.offlineCauses.delete(1 /* OfflineCause.IndexedDbFailed */); + await enableNetworkInternal(remoteStoreImpl); + }); + } + else { + throw e; + } +} +/** + * Executes `op`. If `op` fails, takes the network offline until `op` + * succeeds. Returns after the first attempt. + */ +function executeWithRecovery(remoteStoreImpl, op) { + return op().catch(e => disableNetworkUntilRecovery(remoteStoreImpl, e, op)); +} +/** + * Takes a batch of changes from the Datastore, repackages them as a + * RemoteEvent, and passes that on to the listener, which is typically the + * SyncEngine. + */ +function raiseWatchSnapshot(remoteStoreImpl, snapshotVersion) { + const remoteEvent = remoteStoreImpl.watchChangeAggregator.createRemoteEvent(snapshotVersion); + // Update in-memory resume tokens. LocalStore will update the + // persistent view of these when applying the completed RemoteEvent. + remoteEvent.targetChanges.forEach((change, targetId) => { + if (change.resumeToken.approximateByteSize() > 0) { + const targetData = remoteStoreImpl.listenTargets.get(targetId); + // A watched target might have been removed already. + if (targetData) { + remoteStoreImpl.listenTargets.set(targetId, targetData.withResumeToken(change.resumeToken, snapshotVersion)); + } + } + }); + // Re-establish listens for the targets that have been invalidated by + // existence filter mismatches. + remoteEvent.targetMismatches.forEach((targetId, targetPurpose) => { + const targetData = remoteStoreImpl.listenTargets.get(targetId); + if (!targetData) { + // A watched target might have been removed already. + return; + } + // Clear the resume token for the target, since we're in a known mismatch + // state. + remoteStoreImpl.listenTargets.set(targetId, targetData.withResumeToken(ByteString.EMPTY_BYTE_STRING, targetData.snapshotVersion)); + // Cause a hard reset by unwatching and rewatching immediately, but + // deliberately don't send a resume token so that we get a full update. + sendUnwatchRequest(remoteStoreImpl, targetId); + // Mark the target we send as being on behalf of an existence filter + // mismatch, but don't actually retain that in listenTargets. This ensures + // that we flag the first re-listen this way without impacting future + // listens of this target (that might happen e.g. on reconnect). + const requestTargetData = new TargetData(targetData.target, targetId, targetPurpose, targetData.sequenceNumber); + sendWatchRequest(remoteStoreImpl, requestTargetData); + }); + return remoteStoreImpl.remoteSyncer.applyRemoteEvent(remoteEvent); +} +/** Handles an error on a target */ +async function handleTargetError(remoteStoreImpl, watchChange) { + const error = watchChange.cause; + for (const targetId of watchChange.targetIds) { + // A watched target might have been removed already. + if (remoteStoreImpl.listenTargets.has(targetId)) { + await remoteStoreImpl.remoteSyncer.rejectListen(targetId, error); + remoteStoreImpl.listenTargets.delete(targetId); + remoteStoreImpl.watchChangeAggregator.removeTarget(targetId); + } + } +} +/** + * Attempts to fill our write pipeline with writes from the LocalStore. + * + * Called internally to bootstrap or refill the write pipeline and by + * SyncEngine whenever there are new mutations to process. + * + * Starts the write stream if necessary. + */ +async function fillWritePipeline(remoteStore) { + const remoteStoreImpl = debugCast(remoteStore); + const writeStream = ensureWriteStream(remoteStoreImpl); + let lastBatchIdRetrieved = remoteStoreImpl.writePipeline.length > 0 + ? remoteStoreImpl.writePipeline[remoteStoreImpl.writePipeline.length - 1] + .batchId + : BATCHID_UNKNOWN; + while (canAddToWritePipeline(remoteStoreImpl)) { + try { + const batch = await localStoreGetNextMutationBatch(remoteStoreImpl.localStore, lastBatchIdRetrieved); + if (batch === null) { + if (remoteStoreImpl.writePipeline.length === 0) { + writeStream.markIdle(); + } + break; + } + else { + lastBatchIdRetrieved = batch.batchId; + addToWritePipeline(remoteStoreImpl, batch); + } + } + catch (e) { + await disableNetworkUntilRecovery(remoteStoreImpl, e); + } + } + if (shouldStartWriteStream(remoteStoreImpl)) { + startWriteStream(remoteStoreImpl); + } +} +/** + * Returns true if we can add to the write pipeline (i.e. the network is + * enabled and the write pipeline is not full). + */ +function canAddToWritePipeline(remoteStoreImpl) { + return (canUseNetwork(remoteStoreImpl) && + remoteStoreImpl.writePipeline.length < MAX_PENDING_WRITES); +} +/** + * Queues additional writes to be sent to the write stream, sending them + * immediately if the write stream is established. + */ +function addToWritePipeline(remoteStoreImpl, batch) { + remoteStoreImpl.writePipeline.push(batch); + const writeStream = ensureWriteStream(remoteStoreImpl); + if (writeStream.isOpen() && writeStream.handshakeComplete) { + writeStream.writeMutations(batch.mutations); + } +} +function shouldStartWriteStream(remoteStoreImpl) { + return (canUseNetwork(remoteStoreImpl) && + !ensureWriteStream(remoteStoreImpl).isStarted() && + remoteStoreImpl.writePipeline.length > 0); +} +function startWriteStream(remoteStoreImpl) { + ensureWriteStream(remoteStoreImpl).start(); +} +async function onWriteStreamOpen(remoteStoreImpl) { + ensureWriteStream(remoteStoreImpl).writeHandshake(); +} +async function onWriteHandshakeComplete(remoteStoreImpl) { + const writeStream = ensureWriteStream(remoteStoreImpl); + // Send the write pipeline now that the stream is established. + for (const batch of remoteStoreImpl.writePipeline) { + writeStream.writeMutations(batch.mutations); + } +} +async function onMutationResult(remoteStoreImpl, commitVersion, results) { + const batch = remoteStoreImpl.writePipeline.shift(); + const success = MutationBatchResult.from(batch, commitVersion, results); + await executeWithRecovery(remoteStoreImpl, () => remoteStoreImpl.remoteSyncer.applySuccessfulWrite(success)); + // It's possible that with the completion of this mutation another + // slot has freed up. + await fillWritePipeline(remoteStoreImpl); +} +async function onWriteStreamClose(remoteStoreImpl, error) { + // If the write stream closed after the write handshake completes, a write + // operation failed and we fail the pending operation. + if (error && ensureWriteStream(remoteStoreImpl).handshakeComplete) { + // This error affects the actual write. + await handleWriteError(remoteStoreImpl, error); + } + // The write stream might have been started by refilling the write + // pipeline for failed writes + if (shouldStartWriteStream(remoteStoreImpl)) { + startWriteStream(remoteStoreImpl); + } +} +async function handleWriteError(remoteStoreImpl, error) { + // Only handle permanent errors here. If it's transient, just let the retry + // logic kick in. + if (isPermanentWriteError(error.code)) { + // This was a permanent error, the request itself was the problem + // so it's not going to succeed if we resend it. + const batch = remoteStoreImpl.writePipeline.shift(); + // In this case it's also unlikely that the server itself is melting + // down -- this was just a bad request so inhibit backoff on the next + // restart. + ensureWriteStream(remoteStoreImpl).inhibitBackoff(); + await executeWithRecovery(remoteStoreImpl, () => remoteStoreImpl.remoteSyncer.rejectFailedWrite(batch.batchId, error)); + // It's possible that with the completion of this mutation + // another slot has freed up. + await fillWritePipeline(remoteStoreImpl); + } +} +async function restartNetwork(remoteStore) { + const remoteStoreImpl = debugCast(remoteStore); + remoteStoreImpl.offlineCauses.add(4 /* OfflineCause.ConnectivityChange */); + await disableNetworkInternal(remoteStoreImpl); + remoteStoreImpl.onlineStateTracker.set("Unknown" /* OnlineState.Unknown */); + remoteStoreImpl.offlineCauses.delete(4 /* OfflineCause.ConnectivityChange */); + await enableNetworkInternal(remoteStoreImpl); +} +async function remoteStoreHandleCredentialChange(remoteStore, user) { + const remoteStoreImpl = debugCast(remoteStore); + remoteStoreImpl.asyncQueue.verifyOperationInProgress(); + logDebug(LOG_TAG$5, 'RemoteStore received new credentials'); + const usesNetwork = canUseNetwork(remoteStoreImpl); + // Tear down and re-create our network streams. This will ensure we get a + // fresh auth token for the new user and re-fill the write pipeline with + // new mutations from the LocalStore (since mutations are per-user). + remoteStoreImpl.offlineCauses.add(3 /* OfflineCause.CredentialChange */); + await disableNetworkInternal(remoteStoreImpl); + if (usesNetwork) { + // Don't set the network status to Unknown if we are offline. + remoteStoreImpl.onlineStateTracker.set("Unknown" /* OnlineState.Unknown */); + } + await remoteStoreImpl.remoteSyncer.handleCredentialChange(user); + remoteStoreImpl.offlineCauses.delete(3 /* OfflineCause.CredentialChange */); + await enableNetworkInternal(remoteStoreImpl); +} +/** + * Toggles the network state when the client gains or loses its primary lease. + */ +async function remoteStoreApplyPrimaryState(remoteStore, isPrimary) { + const remoteStoreImpl = debugCast(remoteStore); + if (isPrimary) { + remoteStoreImpl.offlineCauses.delete(2 /* OfflineCause.IsSecondary */); + await enableNetworkInternal(remoteStoreImpl); + } + else if (!isPrimary) { + remoteStoreImpl.offlineCauses.add(2 /* OfflineCause.IsSecondary */); + await disableNetworkInternal(remoteStoreImpl); + remoteStoreImpl.onlineStateTracker.set("Unknown" /* OnlineState.Unknown */); + } +} +/** + * If not yet initialized, registers the WatchStream and its network state + * callback with `remoteStoreImpl`. Returns the existing stream if one is + * already available. + * + * PORTING NOTE: On iOS and Android, the WatchStream gets registered on startup. + * This is not done on Web to allow it to be tree-shaken. + */ +function ensureWatchStream(remoteStoreImpl) { + if (!remoteStoreImpl.watchStream) { + // Create stream (but note that it is not started yet). + remoteStoreImpl.watchStream = newPersistentWatchStream(remoteStoreImpl.datastore, remoteStoreImpl.asyncQueue, { + onConnected: onWatchStreamConnected.bind(null, remoteStoreImpl), + onOpen: onWatchStreamOpen.bind(null, remoteStoreImpl), + onClose: onWatchStreamClose.bind(null, remoteStoreImpl), + onWatchChange: onWatchStreamChange.bind(null, remoteStoreImpl) + }); + remoteStoreImpl.onNetworkStatusChange.push(async (enabled) => { + if (enabled) { + remoteStoreImpl.watchStream.inhibitBackoff(); + if (shouldStartWatchStream(remoteStoreImpl)) { + startWatchStream(remoteStoreImpl); + } + else { + remoteStoreImpl.onlineStateTracker.set("Unknown" /* OnlineState.Unknown */); + } + } + else { + await remoteStoreImpl.watchStream.stop(); + cleanUpWatchStreamState(remoteStoreImpl); + } + }); + } + return remoteStoreImpl.watchStream; +} +/** + * If not yet initialized, registers the WriteStream and its network state + * callback with `remoteStoreImpl`. Returns the existing stream if one is + * already available. + * + * PORTING NOTE: On iOS and Android, the WriteStream gets registered on startup. + * This is not done on Web to allow it to be tree-shaken. + */ +function ensureWriteStream(remoteStoreImpl) { + if (!remoteStoreImpl.writeStream) { + // Create stream (but note that it is not started yet). + remoteStoreImpl.writeStream = newPersistentWriteStream(remoteStoreImpl.datastore, remoteStoreImpl.asyncQueue, { + onConnected: () => Promise.resolve(), + onOpen: onWriteStreamOpen.bind(null, remoteStoreImpl), + onClose: onWriteStreamClose.bind(null, remoteStoreImpl), + onHandshakeComplete: onWriteHandshakeComplete.bind(null, remoteStoreImpl), + onMutationResult: onMutationResult.bind(null, remoteStoreImpl) + }); + remoteStoreImpl.onNetworkStatusChange.push(async (enabled) => { + if (enabled) { + remoteStoreImpl.writeStream.inhibitBackoff(); + // This will start the write stream if necessary. + await fillWritePipeline(remoteStoreImpl); + } + else { + await remoteStoreImpl.writeStream.stop(); + if (remoteStoreImpl.writePipeline.length > 0) { + logDebug(LOG_TAG$5, `Stopping write stream with ${remoteStoreImpl.writePipeline.length} pending writes`); + remoteStoreImpl.writePipeline = []; + } + } + }); + } + return remoteStoreImpl.writeStream; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$4 = 'AsyncQueue'; +/** + * Represents an operation scheduled to be run in the future on an AsyncQueue. + * + * It is created via DelayedOperation.createAndSchedule(). + * + * Supports cancellation (via cancel()) and early execution (via skipDelay()). + * + * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type + * in newer versions of TypeScript defines `finally`, which is not available in + * IE. + */ +class DelayedOperation { + constructor(asyncQueue, timerId, targetTimeMs, op, removalCallback) { + this.asyncQueue = asyncQueue; + this.timerId = timerId; + this.targetTimeMs = targetTimeMs; + this.op = op; + this.removalCallback = removalCallback; + this.deferred = new Deferred(); + this.then = this.deferred.promise.then.bind(this.deferred.promise); + // It's normal for the deferred promise to be canceled (due to cancellation) + // and so we attach a dummy catch callback to avoid + // 'UnhandledPromiseRejectionWarning' log spam. + this.deferred.promise.catch(err => { }); + } + get promise() { + return this.deferred.promise; + } + /** + * Creates and returns a DelayedOperation that has been scheduled to be + * executed on the provided asyncQueue after the provided delayMs. + * + * @param asyncQueue - The queue to schedule the operation on. + * @param id - A Timer ID identifying the type of operation this is. + * @param delayMs - The delay (ms) before the operation should be scheduled. + * @param op - The operation to run. + * @param removalCallback - A callback to be called synchronously once the + * operation is executed or canceled, notifying the AsyncQueue to remove it + * from its delayedOperations list. + * PORTING NOTE: This exists to prevent making removeDelayedOperation() and + * the DelayedOperation class public. + */ + static createAndSchedule(asyncQueue, timerId, delayMs, op, removalCallback) { + const targetTime = Date.now() + delayMs; + const delayedOp = new DelayedOperation(asyncQueue, timerId, targetTime, op, removalCallback); + delayedOp.start(delayMs); + return delayedOp; + } + /** + * Starts the timer. This is called immediately after construction by + * createAndSchedule(). + */ + start(delayMs) { + this.timerHandle = setTimeout(() => this.handleDelayElapsed(), delayMs); + } + /** + * Queues the operation to run immediately (if it hasn't already been run or + * canceled). + */ + skipDelay() { + return this.handleDelayElapsed(); + } + /** + * Cancels the operation if it hasn't already been executed or canceled. The + * promise will be rejected. + * + * As long as the operation has not yet been run, calling cancel() provides a + * guarantee that the operation will not be run. + */ + cancel(reason) { + if (this.timerHandle !== null) { + this.clearTimeout(); + this.deferred.reject(new FirestoreError(Code.CANCELLED, 'Operation cancelled' + (reason ? ': ' + reason : ''))); + } + } + handleDelayElapsed() { + this.asyncQueue.enqueueAndForget(() => { + if (this.timerHandle !== null) { + this.clearTimeout(); + return this.op().then(result => { + return this.deferred.resolve(result); + }); + } + else { + return Promise.resolve(); + } + }); + } + clearTimeout() { + if (this.timerHandle !== null) { + this.removalCallback(this); + clearTimeout(this.timerHandle); + this.timerHandle = null; + } + } +} +/** + * Returns a FirestoreError that can be surfaced to the user if the provided + * error is an IndexedDbTransactionError. Re-throws the error otherwise. + */ +function wrapInUserErrorIfRecoverable(e, msg) { + logError(LOG_TAG$4, `${msg}: ${e}`); + if (isIndexedDbTransactionError(e)) { + return new FirestoreError(Code.UNAVAILABLE, `${msg}: ${e}`); + } + else { + throw e; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * DocumentSet is an immutable (copy-on-write) collection that holds documents + * in order specified by the provided comparator. We always add a document key + * comparator on top of what is provided to guarantee document equality based on + * the key. + */ +class DocumentSet { + /** + * Returns an empty copy of the existing DocumentSet, using the same + * comparator. + */ + static emptySet(oldSet) { + return new DocumentSet(oldSet.comparator); + } + /** The default ordering is by key if the comparator is omitted */ + constructor(comp) { + // We are adding document key comparator to the end as it's the only + // guaranteed unique property of a document. + if (comp) { + this.comparator = (d1, d2) => comp(d1, d2) || DocumentKey.comparator(d1.key, d2.key); + } + else { + this.comparator = (d1, d2) => DocumentKey.comparator(d1.key, d2.key); + } + this.keyedMap = documentMap(); + this.sortedSet = new SortedMap(this.comparator); + } + has(key) { + return this.keyedMap.get(key) != null; + } + get(key) { + return this.keyedMap.get(key); + } + first() { + return this.sortedSet.minKey(); + } + last() { + return this.sortedSet.maxKey(); + } + isEmpty() { + return this.sortedSet.isEmpty(); + } + /** + * Returns the index of the provided key in the document set, or -1 if the + * document key is not present in the set; + */ + indexOf(key) { + const doc = this.keyedMap.get(key); + return doc ? this.sortedSet.indexOf(doc) : -1; + } + get size() { + return this.sortedSet.size; + } + /** Iterates documents in order defined by "comparator" */ + forEach(cb) { + this.sortedSet.inorderTraversal((k, v) => { + cb(k); + return false; + }); + } + /** Inserts or updates a document with the same key */ + add(doc) { + // First remove the element if we have it. + const set = this.delete(doc.key); + return set.copy(set.keyedMap.insert(doc.key, doc), set.sortedSet.insert(doc, null)); + } + /** Deletes a document with a given key */ + delete(key) { + const doc = this.get(key); + if (!doc) { + return this; + } + return this.copy(this.keyedMap.remove(key), this.sortedSet.remove(doc)); + } + isEqual(other) { + if (!(other instanceof DocumentSet)) { + return false; + } + if (this.size !== other.size) { + return false; + } + const thisIt = this.sortedSet.getIterator(); + const otherIt = other.sortedSet.getIterator(); + while (thisIt.hasNext()) { + const thisDoc = thisIt.getNext().key; + const otherDoc = otherIt.getNext().key; + if (!thisDoc.isEqual(otherDoc)) { + return false; + } + } + return true; + } + toString() { + const docStrings = []; + this.forEach(doc => { + docStrings.push(doc.toString()); + }); + if (docStrings.length === 0) { + return 'DocumentSet ()'; + } + else { + return 'DocumentSet (\n ' + docStrings.join(' \n') + '\n)'; + } + } + copy(keyedMap, sortedSet) { + const newSet = new DocumentSet(); + newSet.comparator = this.comparator; + newSet.keyedMap = keyedMap; + newSet.sortedSet = sortedSet; + return newSet; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * DocumentChangeSet keeps track of a set of changes to docs in a query, merging + * duplicate events for the same doc. + */ +class DocumentChangeSet { + constructor() { + this.changeMap = new SortedMap(DocumentKey.comparator); + } + track(change) { + const key = change.doc.key; + const oldChange = this.changeMap.get(key); + if (!oldChange) { + this.changeMap = this.changeMap.insert(key, change); + return; + } + // Merge the new change with the existing change. + if (change.type !== 0 /* ChangeType.Added */ && + oldChange.type === 3 /* ChangeType.Metadata */) { + this.changeMap = this.changeMap.insert(key, change); + } + else if (change.type === 3 /* ChangeType.Metadata */ && + oldChange.type !== 1 /* ChangeType.Removed */) { + this.changeMap = this.changeMap.insert(key, { + type: oldChange.type, + doc: change.doc + }); + } + else if (change.type === 2 /* ChangeType.Modified */ && + oldChange.type === 2 /* ChangeType.Modified */) { + this.changeMap = this.changeMap.insert(key, { + type: 2 /* ChangeType.Modified */, + doc: change.doc + }); + } + else if (change.type === 2 /* ChangeType.Modified */ && + oldChange.type === 0 /* ChangeType.Added */) { + this.changeMap = this.changeMap.insert(key, { + type: 0 /* ChangeType.Added */, + doc: change.doc + }); + } + else if (change.type === 1 /* ChangeType.Removed */ && + oldChange.type === 0 /* ChangeType.Added */) { + this.changeMap = this.changeMap.remove(key); + } + else if (change.type === 1 /* ChangeType.Removed */ && + oldChange.type === 2 /* ChangeType.Modified */) { + this.changeMap = this.changeMap.insert(key, { + type: 1 /* ChangeType.Removed */, + doc: oldChange.doc + }); + } + else if (change.type === 0 /* ChangeType.Added */ && + oldChange.type === 1 /* ChangeType.Removed */) { + this.changeMap = this.changeMap.insert(key, { + type: 2 /* ChangeType.Modified */, + doc: change.doc + }); + } + else { + // This includes these cases, which don't make sense: + // Added->Added + // Removed->Removed + // Modified->Added + // Removed->Modified + // Metadata->Added + // Removed->Metadata + fail(0xf76d, { + change, + oldChange + }); + } + } + getChanges() { + const changes = []; + this.changeMap.inorderTraversal((key, change) => { + changes.push(change); + }); + return changes; + } +} +class ViewSnapshot { + constructor(query, docs, oldDocs, docChanges, mutatedKeys, fromCache, syncStateChanged, excludesMetadataChanges, hasCachedResults) { + this.query = query; + this.docs = docs; + this.oldDocs = oldDocs; + this.docChanges = docChanges; + this.mutatedKeys = mutatedKeys; + this.fromCache = fromCache; + this.syncStateChanged = syncStateChanged; + this.excludesMetadataChanges = excludesMetadataChanges; + this.hasCachedResults = hasCachedResults; + } + /** Returns a view snapshot as if all documents in the snapshot were added. */ + static fromInitialDocuments(query, documents, mutatedKeys, fromCache, hasCachedResults) { + const changes = []; + documents.forEach(doc => { + changes.push({ type: 0 /* ChangeType.Added */, doc }); + }); + return new ViewSnapshot(query, documents, DocumentSet.emptySet(documents), changes, mutatedKeys, fromCache, + /* syncStateChanged= */ true, + /* excludesMetadataChanges= */ false, hasCachedResults); + } + get hasPendingWrites() { + return !this.mutatedKeys.isEmpty(); + } + isEqual(other) { + if (this.fromCache !== other.fromCache || + this.hasCachedResults !== other.hasCachedResults || + this.syncStateChanged !== other.syncStateChanged || + !this.mutatedKeys.isEqual(other.mutatedKeys) || + !queryEquals(this.query, other.query) || + !this.docs.isEqual(other.docs) || + !this.oldDocs.isEqual(other.oldDocs)) { + return false; + } + const changes = this.docChanges; + const otherChanges = other.docChanges; + if (changes.length !== otherChanges.length) { + return false; + } + for (let i = 0; i < changes.length; i++) { + if (changes[i].type !== otherChanges[i].type || + !changes[i].doc.isEqual(otherChanges[i].doc)) { + return false; + } + } + return true; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Holds the listeners and the last received ViewSnapshot for a query being + * tracked by EventManager. + */ +class QueryListenersInfo { + constructor() { + this.viewSnap = undefined; + this.listeners = []; + } + // Helper methods that checks if the query has listeners that listening to remote store + hasRemoteListeners() { + return this.listeners.some(listener => listener.listensToRemoteStore()); + } +} +function newEventManager() { + return new EventManagerImpl(); +} +class EventManagerImpl { + constructor() { + this.queries = newQueriesObjectMap(); + this.onlineState = "Unknown" /* OnlineState.Unknown */; + this.snapshotsInSyncListeners = new Set(); + } + terminate() { + errorAllTargets(this, new FirestoreError(Code.ABORTED, 'Firestore shutting down')); + } +} +function newQueriesObjectMap() { + return new ObjectMap(q => canonifyQuery(q), queryEquals); +} +async function eventManagerListen(eventManager, listener) { + const eventManagerImpl = debugCast(eventManager); + let listenerAction = 3 /* ListenerSetupAction.NoActionRequired */; + const query = listener.query; + let queryInfo = eventManagerImpl.queries.get(query); + if (!queryInfo) { + queryInfo = new QueryListenersInfo(); + listenerAction = listener.listensToRemoteStore() + ? 0 /* ListenerSetupAction.InitializeLocalListenAndRequireWatchConnection */ + : 1 /* ListenerSetupAction.InitializeLocalListenOnly */; + } + else if (!queryInfo.hasRemoteListeners() && + listener.listensToRemoteStore()) { + // Query has been listening to local cache, and tries to add a new listener sourced from watch. + listenerAction = 2 /* ListenerSetupAction.RequireWatchConnectionOnly */; + } + try { + switch (listenerAction) { + case 0 /* ListenerSetupAction.InitializeLocalListenAndRequireWatchConnection */: + queryInfo.viewSnap = await eventManagerImpl.onListen(query, + /** enableRemoteListen= */ true); + break; + case 1 /* ListenerSetupAction.InitializeLocalListenOnly */: + queryInfo.viewSnap = await eventManagerImpl.onListen(query, + /** enableRemoteListen= */ false); + break; + case 2 /* ListenerSetupAction.RequireWatchConnectionOnly */: + await eventManagerImpl.onFirstRemoteStoreListen(query); + break; + default: + break; + } + } + catch (e) { + const firestoreError = wrapInUserErrorIfRecoverable(e, `Initialization of query '${stringifyQuery(listener.query)}' failed`); + listener.onError(firestoreError); + return; + } + eventManagerImpl.queries.set(query, queryInfo); + queryInfo.listeners.push(listener); + // Run global snapshot listeners if a consistent snapshot has been emitted. + listener.applyOnlineStateChange(eventManagerImpl.onlineState); + if (queryInfo.viewSnap) { + const raisedEvent = listener.onViewSnapshot(queryInfo.viewSnap); + if (raisedEvent) { + raiseSnapshotsInSyncEvent(eventManagerImpl); + } + } +} +async function eventManagerUnlisten(eventManager, listener) { + const eventManagerImpl = debugCast(eventManager); + const query = listener.query; + let listenerAction = 3 /* ListenerRemovalAction.NoActionRequired */; + const queryInfo = eventManagerImpl.queries.get(query); + if (queryInfo) { + const i = queryInfo.listeners.indexOf(listener); + if (i >= 0) { + queryInfo.listeners.splice(i, 1); + if (queryInfo.listeners.length === 0) { + listenerAction = listener.listensToRemoteStore() + ? 0 /* ListenerRemovalAction.TerminateLocalListenAndRequireWatchDisconnection */ + : 1 /* ListenerRemovalAction.TerminateLocalListenOnly */; + } + else if (!queryInfo.hasRemoteListeners() && + listener.listensToRemoteStore()) { + // The removed listener is the last one that sourced from watch. + listenerAction = 2 /* ListenerRemovalAction.RequireWatchDisconnectionOnly */; + } + } + } + switch (listenerAction) { + case 0 /* ListenerRemovalAction.TerminateLocalListenAndRequireWatchDisconnection */: + eventManagerImpl.queries.delete(query); + return eventManagerImpl.onUnlisten(query, + /** disableRemoteListen= */ true); + case 1 /* ListenerRemovalAction.TerminateLocalListenOnly */: + eventManagerImpl.queries.delete(query); + return eventManagerImpl.onUnlisten(query, + /** disableRemoteListen= */ false); + case 2 /* ListenerRemovalAction.RequireWatchDisconnectionOnly */: + return eventManagerImpl.onLastRemoteStoreUnlisten(query); + default: + return; + } +} +function eventManagerOnWatchChange(eventManager, viewSnaps) { + const eventManagerImpl = debugCast(eventManager); + let raisedEvent = false; + for (const viewSnap of viewSnaps) { + const query = viewSnap.query; + const queryInfo = eventManagerImpl.queries.get(query); + if (queryInfo) { + for (const listener of queryInfo.listeners) { + if (listener.onViewSnapshot(viewSnap)) { + raisedEvent = true; + } + } + queryInfo.viewSnap = viewSnap; + } + } + if (raisedEvent) { + raiseSnapshotsInSyncEvent(eventManagerImpl); + } +} +function eventManagerOnWatchError(eventManager, query, error) { + const eventManagerImpl = debugCast(eventManager); + const queryInfo = eventManagerImpl.queries.get(query); + if (queryInfo) { + for (const listener of queryInfo.listeners) { + listener.onError(error); + } + } + // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten() + // after an error. + eventManagerImpl.queries.delete(query); +} +function eventManagerOnOnlineStateChange(eventManager, onlineState) { + const eventManagerImpl = debugCast(eventManager); + eventManagerImpl.onlineState = onlineState; + let raisedEvent = false; + eventManagerImpl.queries.forEach((_, queryInfo) => { + for (const listener of queryInfo.listeners) { + // Run global snapshot listeners if a consistent snapshot has been emitted. + if (listener.applyOnlineStateChange(onlineState)) { + raisedEvent = true; + } + } + }); + if (raisedEvent) { + raiseSnapshotsInSyncEvent(eventManagerImpl); + } +} +function addSnapshotsInSyncListener(eventManager, observer) { + const eventManagerImpl = debugCast(eventManager); + eventManagerImpl.snapshotsInSyncListeners.add(observer); + // Immediately fire an initial event, indicating all existing listeners + // are in-sync. + observer.next(); +} +function removeSnapshotsInSyncListener(eventManager, observer) { + const eventManagerImpl = debugCast(eventManager); + eventManagerImpl.snapshotsInSyncListeners.delete(observer); +} +function errorAllTargets(eventManager, error) { + const eventManagerImpl = debugCast(eventManager); + const queries = eventManagerImpl.queries; + // Prevent further access by clearing ObjectMap. + eventManagerImpl.queries = newQueriesObjectMap(); + queries.forEach((_, queryInfo) => { + for (const listener of queryInfo.listeners) { + listener.onError(error); + } + }); +} +// Call all global snapshot listeners that have been set. +function raiseSnapshotsInSyncEvent(eventManagerImpl) { + eventManagerImpl.snapshotsInSyncListeners.forEach(observer => { + observer.next(); + }); +} +var ListenerDataSource; +(function (ListenerDataSource) { + /** Listen to both cache and server changes */ + ListenerDataSource["Default"] = "default"; + /** Listen to changes in cache only */ + ListenerDataSource["Cache"] = "cache"; +})(ListenerDataSource || (ListenerDataSource = {})); +/** + * QueryListener takes a series of internal view snapshots and determines + * when to raise the event. + * + * It uses an Observer to dispatch events. + */ +class QueryListener { + constructor(query, queryObserver, options) { + this.query = query; + this.queryObserver = queryObserver; + /** + * Initial snapshots (e.g. from cache) may not be propagated to the wrapped + * observer. This flag is set to true once we've actually raised an event. + */ + this.raisedInitialEvent = false; + this.snap = null; + this.onlineState = "Unknown" /* OnlineState.Unknown */; + this.options = options || {}; + } + /** + * Applies the new ViewSnapshot to this listener, raising a user-facing event + * if applicable (depending on what changed, whether the user has opted into + * metadata-only changes, etc.). Returns true if a user-facing event was + * indeed raised. + */ + onViewSnapshot(snap) { + if (!this.options.includeMetadataChanges) { + // Remove the metadata only changes. + const docChanges = []; + for (const docChange of snap.docChanges) { + if (docChange.type !== 3 /* ChangeType.Metadata */) { + docChanges.push(docChange); + } + } + snap = new ViewSnapshot(snap.query, snap.docs, snap.oldDocs, docChanges, snap.mutatedKeys, snap.fromCache, snap.syncStateChanged, + /* excludesMetadataChanges= */ true, snap.hasCachedResults); + } + let raisedEvent = false; + if (!this.raisedInitialEvent) { + if (this.shouldRaiseInitialEvent(snap, this.onlineState)) { + this.raiseInitialEvent(snap); + raisedEvent = true; + } + } + else if (this.shouldRaiseEvent(snap)) { + this.queryObserver.next(snap); + raisedEvent = true; + } + this.snap = snap; + return raisedEvent; + } + onError(error) { + this.queryObserver.error(error); + } + /** Returns whether a snapshot was raised. */ + applyOnlineStateChange(onlineState) { + this.onlineState = onlineState; + let raisedEvent = false; + if (this.snap && + !this.raisedInitialEvent && + this.shouldRaiseInitialEvent(this.snap, onlineState)) { + this.raiseInitialEvent(this.snap); + raisedEvent = true; + } + return raisedEvent; + } + shouldRaiseInitialEvent(snap, onlineState) { + // Always raise the first event when we're synced + if (!snap.fromCache) { + return true; + } + // Always raise event if listening to cache + if (!this.listensToRemoteStore()) { + return true; + } + // NOTE: We consider OnlineState.Unknown as online (it should become Offline + // or Online if we wait long enough). + const maybeOnline = onlineState !== "Offline" /* OnlineState.Offline */; + // Don't raise the event if we're online, aren't synced yet (checked + // above) and are waiting for a sync. + if (this.options.waitForSyncWhenOnline && maybeOnline) { + return false; + } + // Raise data from cache if we have any documents, have cached results before, + // or we are offline. + return (!snap.docs.isEmpty() || + snap.hasCachedResults || + onlineState === "Offline" /* OnlineState.Offline */); + } + shouldRaiseEvent(snap) { + // We don't need to handle includeDocumentMetadataChanges here because + // the Metadata only changes have already been stripped out if needed. + // At this point the only changes we will see are the ones we should + // propagate. + if (snap.docChanges.length > 0) { + return true; + } + const hasPendingWritesChanged = this.snap && this.snap.hasPendingWrites !== snap.hasPendingWrites; + if (snap.syncStateChanged || hasPendingWritesChanged) { + return this.options.includeMetadataChanges === true; + } + // Generally we should have hit one of the cases above, but it's possible + // to get here if there were only metadata docChanges and they got + // stripped out. + return false; + } + raiseInitialEvent(snap) { + snap = ViewSnapshot.fromInitialDocuments(snap.query, snap.docs, snap.mutatedKeys, snap.fromCache, snap.hasCachedResults); + this.raisedInitialEvent = true; + this.queryObserver.next(snap); + } + listensToRemoteStore() { + return this.options.source !== ListenerDataSource.Cache; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A set of changes to what documents are currently in view and out of view for + * a given query. These changes are sent to the LocalStore by the View (via + * the SyncEngine) and are used to pin / unpin documents as appropriate. + */ +class LocalViewChanges { + constructor(targetId, fromCache, addedKeys, removedKeys) { + this.targetId = targetId; + this.fromCache = fromCache; + this.addedKeys = addedKeys; + this.removedKeys = removedKeys; + } + static fromSnapshot(targetId, viewSnapshot) { + let addedKeys = documentKeySet(); + let removedKeys = documentKeySet(); + for (const docChange of viewSnapshot.docChanges) { + switch (docChange.type) { + case 0 /* ChangeType.Added */: + addedKeys = addedKeys.add(docChange.doc.key); + break; + case 1 /* ChangeType.Removed */: + removedKeys = removedKeys.add(docChange.doc.key); + break; + // do nothing + } + } + return new LocalViewChanges(targetId, viewSnapshot.fromCache, addedKeys, removedKeys); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Helper to convert objects from bundles to model objects in the SDK. + */ +class BundleConverterImpl { + constructor(serializer) { + this.serializer = serializer; + } + toDocumentKey(name) { + return fromName(this.serializer, name); + } + /** + * Converts a BundleDocument to a MutableDocument. + */ + toMutableDocument(bundledDoc) { + if (bundledDoc.metadata.exists) { + return fromDocument(this.serializer, bundledDoc.document, false); + } + else { + return MutableDocument.newNoDocument(this.toDocumentKey(bundledDoc.metadata.name), this.toSnapshotVersion(bundledDoc.metadata.readTime)); + } + } + toSnapshotVersion(time) { + return fromVersion(time); + } +} +/** + * A class to process the elements from a bundle, and optionally load them into local + * storage and provide progress update while loading. + */ +class BundleLoader { + constructor(bundleMetadata, serializer) { + this.bundleMetadata = bundleMetadata; + this.serializer = serializer; + /** Batched queries to be saved into storage */ + this._queries = []; + /** Batched documents to be saved into storage */ + this._documents = []; + /** The collection groups affected by this bundle. */ + this.collectionGroups = new Set(); + this.progress = bundleInitialProgress(bundleMetadata); + } + /** + * Returns the named queries that have been parsed from the SizeBundleElements added by + * calling {@link adSizedElement}. + */ + get queries() { + return this._queries; + } + /** + * Returns the BundledDocuments that have been parsed from the SizeBundleElements added by + * calling {@link addSizedElement}. + */ + get documents() { + return this._documents; + } + /** + * Adds an element from the bundle to the loader. + * + * Returns a new progress if adding the element leads to a new progress, + * otherwise returns null. + */ + addSizedElement(element) { + this.progress.bytesLoaded += element.byteLength; + let documentsLoaded = this.progress.documentsLoaded; + if (element.payload.namedQuery) { + this._queries.push(element.payload.namedQuery); + } + else if (element.payload.documentMetadata) { + this._documents.push({ metadata: element.payload.documentMetadata }); + if (!element.payload.documentMetadata.exists) { + ++documentsLoaded; + } + const path = ResourcePath.fromString(element.payload.documentMetadata.name); + this.collectionGroups.add(path.get(path.length - 2)); + } + else if (element.payload.document) { + this._documents[this._documents.length - 1].document = + element.payload.document; + ++documentsLoaded; + } + if (documentsLoaded !== this.progress.documentsLoaded) { + this.progress.documentsLoaded = documentsLoaded; + return { ...this.progress }; + } + return null; + } + getQueryDocumentMapping(documents) { + const queryDocumentMap = new Map(); + const bundleConverter = new BundleConverterImpl(this.serializer); + for (const bundleDoc of documents) { + if (bundleDoc.metadata.queries) { + const documentKey = bundleConverter.toDocumentKey(bundleDoc.metadata.name); + for (const queryName of bundleDoc.metadata.queries) { + const documentKeys = (queryDocumentMap.get(queryName) || documentKeySet()).add(documentKey); + queryDocumentMap.set(queryName, documentKeys); + } + } + } + return queryDocumentMap; + } + /** + * Update the progress to 'Success' and return the updated progress. + */ + async completeAndStoreAsync(localStore) { + const changedDocs = await localStoreApplyBundledDocuments(localStore, new BundleConverterImpl(this.serializer), this._documents, this.bundleMetadata.id); + const queryDocumentMap = this.getQueryDocumentMapping(this.documents); + for (const q of this._queries) { + await localStoreSaveNamedQuery(localStore, q, queryDocumentMap.get(q.name)); + } + this.progress.taskState = 'Success'; + return { + progress: this.progress, + changedCollectionGroups: this.collectionGroups, + changedDocs + }; + } +} +/** + * Returns a `LoadBundleTaskProgress` representing the initial progress of + * loading a bundle. + */ +function bundleInitialProgress(metadata) { + return { + taskState: 'Running', + documentsLoaded: 0, + bytesLoaded: 0, + totalDocuments: metadata.totalDocuments, + totalBytes: metadata.totalBytes + }; +} +/** + * Returns a `LoadBundleTaskProgress` representing the progress that the loading + * has succeeded. + */ +function bundleSuccessProgress(metadata) { + return { + taskState: 'Success', + documentsLoaded: metadata.totalDocuments, + bytesLoaded: metadata.totalBytes, + totalDocuments: metadata.totalDocuments, + totalBytes: metadata.totalBytes + }; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class AddedLimboDocument { + constructor(key) { + this.key = key; + } +} +class RemovedLimboDocument { + constructor(key) { + this.key = key; + } +} +/** + * View is responsible for computing the final merged truth of what docs are in + * a query. It gets notified of local and remote changes to docs, and applies + * the query filters and limits to determine the most correct possible results. + */ +class View { + constructor(query, + /** Documents included in the remote target */ + _syncedDocuments) { + this.query = query; + this._syncedDocuments = _syncedDocuments; + this.syncState = null; + this.hasCachedResults = false; + /** + * A flag whether the view is current with the backend. A view is considered + * current after it has seen the current flag from the backend and did not + * lose consistency within the watch stream (e.g. because of an existence + * filter mismatch). + */ + this.current = false; + /** Documents in the view but not in the remote target */ + this.limboDocuments = documentKeySet(); + /** Document Keys that have local changes */ + this.mutatedKeys = documentKeySet(); + this.docComparator = newQueryComparator(query); + this.documentSet = new DocumentSet(this.docComparator); + } + /** + * The set of remote documents that the server has told us belongs to the target associated with + * this view. + */ + get syncedDocuments() { + return this._syncedDocuments; + } + /** + * Iterates over a set of doc changes, applies the query limit, and computes + * what the new results should be, what the changes were, and whether we may + * need to go back to the local cache for more results. Does not make any + * changes to the view. + * @param docChanges - The doc changes to apply to this view. + * @param previousChanges - If this is being called with a refill, then start + * with this set of docs and changes instead of the current view. + * @returns a new set of docs, changes, and refill flag. + */ + computeDocChanges(docChanges, previousChanges) { + const changeSet = previousChanges + ? previousChanges.changeSet + : new DocumentChangeSet(); + const oldDocumentSet = previousChanges + ? previousChanges.documentSet + : this.documentSet; + let newMutatedKeys = previousChanges + ? previousChanges.mutatedKeys + : this.mutatedKeys; + let newDocumentSet = oldDocumentSet; + let needsRefill = false; + // Track the last doc in a (full) limit. This is necessary, because some + // update (a delete, or an update moving a doc past the old limit) might + // mean there is some other document in the local cache that either should + // come (1) between the old last limit doc and the new last document, in the + // case of updates, or (2) after the new last document, in the case of + // deletes. So we keep this doc at the old limit to compare the updates to. + // + // Note that this should never get used in a refill (when previousChanges is + // set), because there will only be adds -- no deletes or updates. + const lastDocInLimit = this.query.limitType === "F" /* LimitType.First */ && + oldDocumentSet.size === this.query.limit + ? oldDocumentSet.last() + : null; + const firstDocInLimit = this.query.limitType === "L" /* LimitType.Last */ && + oldDocumentSet.size === this.query.limit + ? oldDocumentSet.first() + : null; + docChanges.inorderTraversal((key, entry) => { + const oldDoc = oldDocumentSet.get(key); + const newDoc = queryMatches(this.query, entry) ? entry : null; + const oldDocHadPendingMutations = oldDoc + ? this.mutatedKeys.has(oldDoc.key) + : false; + const newDocHasPendingMutations = newDoc + ? newDoc.hasLocalMutations || + // We only consider committed mutations for documents that were + // mutated during the lifetime of the view. + (this.mutatedKeys.has(newDoc.key) && newDoc.hasCommittedMutations) + : false; + let changeApplied = false; + // Calculate change + if (oldDoc && newDoc) { + const docsEqual = oldDoc.data.isEqual(newDoc.data); + if (!docsEqual) { + if (!this.shouldWaitForSyncedDocument(oldDoc, newDoc)) { + changeSet.track({ + type: 2 /* ChangeType.Modified */, + doc: newDoc + }); + changeApplied = true; + if ((lastDocInLimit && + this.docComparator(newDoc, lastDocInLimit) > 0) || + (firstDocInLimit && + this.docComparator(newDoc, firstDocInLimit) < 0)) { + // This doc moved from inside the limit to outside the limit. + // That means there may be some other doc in the local cache + // that should be included instead. + needsRefill = true; + } + } + } + else if (oldDocHadPendingMutations !== newDocHasPendingMutations) { + changeSet.track({ type: 3 /* ChangeType.Metadata */, doc: newDoc }); + changeApplied = true; + } + } + else if (!oldDoc && newDoc) { + changeSet.track({ type: 0 /* ChangeType.Added */, doc: newDoc }); + changeApplied = true; + } + else if (oldDoc && !newDoc) { + changeSet.track({ type: 1 /* ChangeType.Removed */, doc: oldDoc }); + changeApplied = true; + if (lastDocInLimit || firstDocInLimit) { + // A doc was removed from a full limit query. We'll need to + // requery from the local cache to see if we know about some other + // doc that should be in the results. + needsRefill = true; + } + } + if (changeApplied) { + if (newDoc) { + newDocumentSet = newDocumentSet.add(newDoc); + if (newDocHasPendingMutations) { + newMutatedKeys = newMutatedKeys.add(key); + } + else { + newMutatedKeys = newMutatedKeys.delete(key); + } + } + else { + newDocumentSet = newDocumentSet.delete(key); + newMutatedKeys = newMutatedKeys.delete(key); + } + } + }); + // Drop documents out to meet limit/limitToLast requirement. + if (this.query.limit !== null) { + while (newDocumentSet.size > this.query.limit) { + const oldDoc = this.query.limitType === "F" /* LimitType.First */ + ? newDocumentSet.last() + : newDocumentSet.first(); + newDocumentSet = newDocumentSet.delete(oldDoc.key); + newMutatedKeys = newMutatedKeys.delete(oldDoc.key); + changeSet.track({ type: 1 /* ChangeType.Removed */, doc: oldDoc }); + } + } + return { + documentSet: newDocumentSet, + changeSet, + needsRefill, + mutatedKeys: newMutatedKeys + }; + } + shouldWaitForSyncedDocument(oldDoc, newDoc) { + // We suppress the initial change event for documents that were modified as + // part of a write acknowledgment (e.g. when the value of a server transform + // is applied) as Watch will send us the same document again. + // By suppressing the event, we only raise two user visible events (one with + // `hasPendingWrites` and the final state of the document) instead of three + // (one with `hasPendingWrites`, the modified document with + // `hasPendingWrites` and the final state of the document). + return (oldDoc.hasLocalMutations && + newDoc.hasCommittedMutations && + !newDoc.hasLocalMutations); + } + /** + * Updates the view with the given ViewDocumentChanges and optionally updates + * limbo docs and sync state from the provided target change. + * @param docChanges - The set of changes to make to the view's docs. + * @param limboResolutionEnabled - Whether to update limbo documents based on + * this change. + * @param targetChange - A target change to apply for computing limbo docs and + * sync state. + * @param targetIsPendingReset - Whether the target is pending to reset due to + * existence filter mismatch. If not explicitly specified, it is treated + * equivalently to `false`. + * @returns A new ViewChange with the given docs, changes, and sync state. + */ + // PORTING NOTE: The iOS/Android clients always compute limbo document changes. + applyChanges(docChanges, limboResolutionEnabled, targetChange, targetIsPendingReset) { + const oldDocs = this.documentSet; + this.documentSet = docChanges.documentSet; + this.mutatedKeys = docChanges.mutatedKeys; + // Sort changes based on type and query comparator + const changes = docChanges.changeSet.getChanges(); + changes.sort((c1, c2) => { + return (compareChangeType(c1.type, c2.type) || + this.docComparator(c1.doc, c2.doc)); + }); + this.applyTargetChange(targetChange); + targetIsPendingReset = targetIsPendingReset ?? false; + const limboChanges = limboResolutionEnabled && !targetIsPendingReset + ? this.updateLimboDocuments() + : []; + // We are at synced state if there is no limbo docs are waiting to be resolved, view is current + // with the backend, and the query is not pending to reset due to existence filter mismatch. + const synced = this.limboDocuments.size === 0 && this.current && !targetIsPendingReset; + const newSyncState = synced ? 1 /* SyncState.Synced */ : 0 /* SyncState.Local */; + const syncStateChanged = newSyncState !== this.syncState; + this.syncState = newSyncState; + if (changes.length === 0 && !syncStateChanged) { + // no changes + return { limboChanges }; + } + else { + const snap = new ViewSnapshot(this.query, docChanges.documentSet, oldDocs, changes, docChanges.mutatedKeys, newSyncState === 0 /* SyncState.Local */, syncStateChanged, + /* excludesMetadataChanges= */ false, targetChange + ? targetChange.resumeToken.approximateByteSize() > 0 + : false); + return { + snapshot: snap, + limboChanges + }; + } + } + /** + * Applies an OnlineState change to the view, potentially generating a + * ViewChange if the view's syncState changes as a result. + */ + applyOnlineStateChange(onlineState) { + if (this.current && onlineState === "Offline" /* OnlineState.Offline */) { + // If we're offline, set `current` to false and then call applyChanges() + // to refresh our syncState and generate a ViewChange as appropriate. We + // are guaranteed to get a new TargetChange that sets `current` back to + // true once the client is back online. + this.current = false; + return this.applyChanges({ + documentSet: this.documentSet, + changeSet: new DocumentChangeSet(), + mutatedKeys: this.mutatedKeys, + needsRefill: false + }, + /* limboResolutionEnabled= */ false); + } + else { + // No effect, just return a no-op ViewChange. + return { limboChanges: [] }; + } + } + /** + * Returns whether the doc for the given key should be in limbo. + */ + shouldBeInLimbo(key) { + // If the remote end says it's part of this query, it's not in limbo. + if (this._syncedDocuments.has(key)) { + return false; + } + // The local store doesn't think it's a result, so it shouldn't be in limbo. + if (!this.documentSet.has(key)) { + return false; + } + // If there are local changes to the doc, they might explain why the server + // doesn't know that it's part of the query. So don't put it in limbo. + // TODO(klimt): Ideally, we would only consider changes that might actually + // affect this specific query. + if (this.documentSet.get(key).hasLocalMutations) { + return false; + } + // Everything else is in limbo. + return true; + } + /** + * Updates syncedDocuments, current, and limbo docs based on the given change. + * Returns the list of changes to which docs are in limbo. + */ + applyTargetChange(targetChange) { + if (targetChange) { + targetChange.addedDocuments.forEach(key => (this._syncedDocuments = this._syncedDocuments.add(key))); + targetChange.modifiedDocuments.forEach(key => { + }); + targetChange.removedDocuments.forEach(key => (this._syncedDocuments = this._syncedDocuments.delete(key))); + this.current = targetChange.current; + } + } + updateLimboDocuments() { + // We can only determine limbo documents when we're in-sync with the server. + if (!this.current) { + return []; + } + // TODO(klimt): Do this incrementally so that it's not quadratic when + // updating many documents. + const oldLimboDocuments = this.limboDocuments; + this.limboDocuments = documentKeySet(); + this.documentSet.forEach(doc => { + if (this.shouldBeInLimbo(doc.key)) { + this.limboDocuments = this.limboDocuments.add(doc.key); + } + }); + // Diff the new limbo docs with the old limbo docs. + const changes = []; + oldLimboDocuments.forEach(key => { + if (!this.limboDocuments.has(key)) { + changes.push(new RemovedLimboDocument(key)); + } + }); + this.limboDocuments.forEach(key => { + if (!oldLimboDocuments.has(key)) { + changes.push(new AddedLimboDocument(key)); + } + }); + return changes; + } + /** + * Update the in-memory state of the current view with the state read from + * persistence. + * + * We update the query view whenever a client's primary status changes: + * - When a client transitions from primary to secondary, it can miss + * LocalStorage updates and its query views may temporarily not be + * synchronized with the state on disk. + * - For secondary to primary transitions, the client needs to update the list + * of `syncedDocuments` since secondary clients update their query views + * based purely on synthesized RemoteEvents. + * + * @param queryResult.documents - The documents that match the query according + * to the LocalStore. + * @param queryResult.remoteKeys - The keys of the documents that match the + * query according to the backend. + * + * @returns The ViewChange that resulted from this synchronization. + */ + // PORTING NOTE: Multi-tab only. + synchronizeWithPersistedState(queryResult) { + this._syncedDocuments = queryResult.remoteKeys; + this.limboDocuments = documentKeySet(); + const docChanges = this.computeDocChanges(queryResult.documents); + return this.applyChanges(docChanges, /* limboResolutionEnabled= */ true); + } + /** + * Returns a view snapshot as if this query was just listened to. Contains + * a document add for every existing document and the `fromCache` and + * `hasPendingWrites` status of the already established view. + */ + // PORTING NOTE: Multi-tab only. + computeInitialSnapshot() { + return ViewSnapshot.fromInitialDocuments(this.query, this.documentSet, this.mutatedKeys, this.syncState === 0 /* SyncState.Local */, this.hasCachedResults); + } +} +function compareChangeType(c1, c2) { + const order = (change) => { + switch (change) { + case 0 /* ChangeType.Added */: + return 1; + case 2 /* ChangeType.Modified */: + return 2; + case 3 /* ChangeType.Metadata */: + // A metadata change is converted to a modified change at the public + // api layer. Since we sort by document key and then change type, + // metadata and modified changes must be sorted equivalently. + return 2; + case 1 /* ChangeType.Removed */: + return 0; + default: + return fail(0x4f35, { change }); + } + }; + return order(c1) - order(c2); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$3 = 'SyncEngine'; +/** + * QueryView contains all of the data that SyncEngine needs to keep track of for + * a particular query. + */ +class QueryView { + constructor( + /** + * The query itself. + */ + query, + /** + * The target number created by the client that is used in the watch + * stream to identify this query. + */ + targetId, + /** + * The view is responsible for computing the final merged truth of what + * docs are in the query. It gets notified of local and remote changes, + * and applies the query filters and limits to determine the most correct + * possible results. + */ + view) { + this.query = query; + this.targetId = targetId; + this.view = view; + } +} +/** Tracks a limbo resolution. */ +class LimboResolution { + constructor(key) { + this.key = key; + /** + * Set to true once we've received a document. This is used in + * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to + * decide whether it needs to manufacture a delete event for the target once + * the target is CURRENT. + */ + this.receivedDocument = false; + } +} +/** + * An implementation of `SyncEngine` coordinating with other parts of SDK. + * + * The parts of SyncEngine that act as a callback to RemoteStore need to be + * registered individually. This is done in `syncEngineWrite()` and + * `syncEngineListen()` (as well as `applyPrimaryState()`) as these methods + * serve as entry points to RemoteStore's functionality. + * + * Note: some field defined in this class might have public access level, but + * the class is not exported so they are only accessible from this module. + * This is useful to implement optional features (like bundles) in free + * functions, such that they are tree-shakeable. + */ +class SyncEngineImpl { + constructor(localStore, remoteStore, eventManager, + // PORTING NOTE: Manages state synchronization in multi-tab environments. + sharedClientState, currentUser, maxConcurrentLimboResolutions) { + this.localStore = localStore; + this.remoteStore = remoteStore; + this.eventManager = eventManager; + this.sharedClientState = sharedClientState; + this.currentUser = currentUser; + this.maxConcurrentLimboResolutions = maxConcurrentLimboResolutions; + this.syncEngineListener = {}; + this.queryViewsByQuery = new ObjectMap(q => canonifyQuery(q), queryEquals); + this.queriesByTarget = new Map(); + /** + * The keys of documents that are in limbo for which we haven't yet started a + * limbo resolution query. The strings in this set are the result of calling + * `key.path.canonicalString()` where `key` is a `DocumentKey` object. + * + * The `Set` type was chosen because it provides efficient lookup and removal + * of arbitrary elements and it also maintains insertion order, providing the + * desired queue-like FIFO semantics. + */ + this.enqueuedLimboResolutions = new Set(); + /** + * Keeps track of the target ID for each document that is in limbo with an + * active target. + */ + this.activeLimboTargetsByKey = new SortedMap(DocumentKey.comparator); + /** + * Keeps track of the information about an active limbo resolution for each + * active target ID that was started for the purpose of limbo resolution. + */ + this.activeLimboResolutionsByTarget = new Map(); + this.limboDocumentRefs = new ReferenceSet(); + /** Stores user completion handlers, indexed by User and BatchId. */ + this.mutationUserCallbacks = {}; + /** Stores user callbacks waiting for all pending writes to be acknowledged. */ + this.pendingWritesCallbacks = new Map(); + this.limboTargetIdGenerator = TargetIdGenerator.forSyncEngine(); + this.onlineState = "Unknown" /* OnlineState.Unknown */; + // The primary state is set to `true` or `false` immediately after Firestore + // startup. In the interim, a client should only be considered primary if + // `isPrimary` is true. + this._isPrimaryClient = undefined; + } + get isPrimaryClient() { + return this._isPrimaryClient === true; + } +} +function newSyncEngine(localStore, remoteStore, eventManager, +// PORTING NOTE: Manages state synchronization in multi-tab environments. +sharedClientState, currentUser, maxConcurrentLimboResolutions, isPrimary) { + const syncEngine = new SyncEngineImpl(localStore, remoteStore, eventManager, sharedClientState, currentUser, maxConcurrentLimboResolutions); + if (isPrimary) { + syncEngine._isPrimaryClient = true; + } + return syncEngine; +} +/** + * Initiates the new listen, resolves promise when listen enqueued to the + * server. All the subsequent view snapshots or errors are sent to the + * subscribed handlers. Returns the initial snapshot. + */ +async function syncEngineListen(syncEngine, query, shouldListenToRemote = true) { + const syncEngineImpl = ensureWatchCallbacks(syncEngine); + let viewSnapshot; + const queryView = syncEngineImpl.queryViewsByQuery.get(query); + if (queryView) { + // PORTING NOTE: With Multi-Tab Web, it is possible that a query view + // already exists when EventManager calls us for the first time. This + // happens when the primary tab is already listening to this query on + // behalf of another tab and the user of the primary also starts listening + // to the query. EventManager will not have an assigned target ID in this + // case and calls `listen` to obtain this ID. + syncEngineImpl.sharedClientState.addLocalQueryTarget(queryView.targetId); + viewSnapshot = queryView.view.computeInitialSnapshot(); + } + else { + viewSnapshot = await allocateTargetAndMaybeListen(syncEngineImpl, query, shouldListenToRemote, + /** shouldInitializeView= */ true); + } + return viewSnapshot; +} +/** Query has been listening to the cache, and tries to initiate the remote store listen */ +async function triggerRemoteStoreListen(syncEngine, query) { + const syncEngineImpl = ensureWatchCallbacks(syncEngine); + await allocateTargetAndMaybeListen(syncEngineImpl, query, + /** shouldListenToRemote= */ true, + /** shouldInitializeView= */ false); +} +async function allocateTargetAndMaybeListen(syncEngineImpl, query, shouldListenToRemote, shouldInitializeView) { + const targetData = await localStoreAllocateTarget(syncEngineImpl.localStore, queryToTarget(query)); + const targetId = targetData.targetId; + // PORTING NOTE: When the query is listening to cache only, we skip sending it over to Watch by + // not registering it in shared client state, and directly calculate initial snapshots and + // subsequent updates from cache. Otherwise, register the target ID with local Firestore client + // as active watch target. + const status = syncEngineImpl.sharedClientState.addLocalQueryTarget(targetId, + /* addToActiveTargetIds= */ shouldListenToRemote); + let viewSnapshot; + if (shouldInitializeView) { + viewSnapshot = await initializeViewAndComputeSnapshot(syncEngineImpl, query, targetId, status === 'current', targetData.resumeToken); + } + if (syncEngineImpl.isPrimaryClient && shouldListenToRemote) { + remoteStoreListen(syncEngineImpl.remoteStore, targetData); + } + return viewSnapshot; +} +/** + * Registers a view for a previously unknown query and computes its initial + * snapshot. + */ +async function initializeViewAndComputeSnapshot(syncEngineImpl, query, targetId, current, resumeToken) { + // PORTING NOTE: On Web only, we inject the code that registers new Limbo + // targets based on view changes. This allows us to only depend on Limbo + // changes when user code includes queries. + syncEngineImpl.applyDocChanges = (queryView, changes, remoteEvent) => applyDocChanges(syncEngineImpl, queryView, changes, remoteEvent); + const queryResult = await localStoreExecuteQuery(syncEngineImpl.localStore, query, + /* usePreviousResults= */ true); + const view = new View(query, queryResult.remoteKeys); + const viewDocChanges = view.computeDocChanges(queryResult.documents); + const synthesizedTargetChange = TargetChange.createSynthesizedTargetChangeForCurrentChange(targetId, current && syncEngineImpl.onlineState !== "Offline" /* OnlineState.Offline */, resumeToken); + const viewChange = view.applyChanges(viewDocChanges, + /* limboResolutionEnabled= */ syncEngineImpl.isPrimaryClient, synthesizedTargetChange); + updateTrackedLimbos(syncEngineImpl, targetId, viewChange.limboChanges); + const data = new QueryView(query, targetId, view); + syncEngineImpl.queryViewsByQuery.set(query, data); + if (syncEngineImpl.queriesByTarget.has(targetId)) { + syncEngineImpl.queriesByTarget.get(targetId).push(query); + } + else { + syncEngineImpl.queriesByTarget.set(targetId, [query]); + } + return viewChange.snapshot; +} +/** Stops listening to the query. */ +async function syncEngineUnlisten(syncEngine, query, shouldUnlistenToRemote) { + const syncEngineImpl = debugCast(syncEngine); + const queryView = syncEngineImpl.queryViewsByQuery.get(query); + // Only clean up the query view and target if this is the only query mapped + // to the target. + const queries = syncEngineImpl.queriesByTarget.get(queryView.targetId); + if (queries.length > 1) { + syncEngineImpl.queriesByTarget.set(queryView.targetId, queries.filter(q => !queryEquals(q, query))); + syncEngineImpl.queryViewsByQuery.delete(query); + return; + } + // No other queries are mapped to the target, clean up the query and the target. + if (syncEngineImpl.isPrimaryClient) { + // We need to remove the local query target first to allow us to verify + // whether any other client is still interested in this target. + syncEngineImpl.sharedClientState.removeLocalQueryTarget(queryView.targetId); + const targetRemainsActive = syncEngineImpl.sharedClientState.isActiveQueryTarget(queryView.targetId); + if (!targetRemainsActive) { + await localStoreReleaseTarget(syncEngineImpl.localStore, queryView.targetId, + /*keepPersistedTargetData=*/ false) + .then(() => { + syncEngineImpl.sharedClientState.clearQueryState(queryView.targetId); + if (shouldUnlistenToRemote) { + remoteStoreUnlisten(syncEngineImpl.remoteStore, queryView.targetId); + } + removeAndCleanupTarget(syncEngineImpl, queryView.targetId); + }) + .catch(ignoreIfPrimaryLeaseLoss); + } + } + else { + removeAndCleanupTarget(syncEngineImpl, queryView.targetId); + await localStoreReleaseTarget(syncEngineImpl.localStore, queryView.targetId, + /*keepPersistedTargetData=*/ true); + } +} +/** Unlistens to the remote store while still listening to the cache. */ +async function triggerRemoteStoreUnlisten(syncEngine, query) { + const syncEngineImpl = debugCast(syncEngine); + const queryView = syncEngineImpl.queryViewsByQuery.get(query); + const queries = syncEngineImpl.queriesByTarget.get(queryView.targetId); + if (syncEngineImpl.isPrimaryClient && queries.length === 1) { + // PORTING NOTE: Unregister the target ID with local Firestore client as + // watch target. + syncEngineImpl.sharedClientState.removeLocalQueryTarget(queryView.targetId); + remoteStoreUnlisten(syncEngineImpl.remoteStore, queryView.targetId); + } +} +/** + * Initiates the write of local mutation batch which involves adding the + * writes to the mutation queue, notifying the remote store about new + * mutations and raising events for any changes this write caused. + * + * The promise returned by this call is resolved when the above steps + * have completed, *not* when the write was acked by the backend. The + * userCallback is resolved once the write was acked/rejected by the + * backend (or failed locally for any other reason). + */ +async function syncEngineWrite(syncEngine, batch, userCallback) { + const syncEngineImpl = syncEngineEnsureWriteCallbacks(syncEngine); + try { + const result = await localStoreWriteLocally(syncEngineImpl.localStore, batch); + syncEngineImpl.sharedClientState.addPendingMutation(result.batchId); + addMutationCallback(syncEngineImpl, result.batchId, userCallback); + await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, result.changes); + await fillWritePipeline(syncEngineImpl.remoteStore); + } + catch (e) { + // If we can't persist the mutation, we reject the user callback and + // don't send the mutation. The user can then retry the write. + const error = wrapInUserErrorIfRecoverable(e, `Failed to persist write`); + userCallback.reject(error); + } +} +/** + * Applies one remote event to the sync engine, notifying any views of the + * changes, and releasing any pending mutation batches that would become + * visible because of the snapshot version the remote event contains. + */ +async function syncEngineApplyRemoteEvent(syncEngine, remoteEvent) { + const syncEngineImpl = debugCast(syncEngine); + try { + const changes = await localStoreApplyRemoteEventToLocalCache(syncEngineImpl.localStore, remoteEvent); + // Update `receivedDocument` as appropriate for any limbo targets. + remoteEvent.targetChanges.forEach((targetChange, targetId) => { + const limboResolution = syncEngineImpl.activeLimboResolutionsByTarget.get(targetId); + if (limboResolution) { + // Since this is a limbo resolution lookup, it's for a single document + // and it could be added, modified, or removed, but not a combination. + hardAssert(targetChange.addedDocuments.size + + targetChange.modifiedDocuments.size + + targetChange.removedDocuments.size <= + 1, 0x5858); + if (targetChange.addedDocuments.size > 0) { + limboResolution.receivedDocument = true; + } + else if (targetChange.modifiedDocuments.size > 0) { + hardAssert(limboResolution.receivedDocument, 0x390f); + } + else if (targetChange.removedDocuments.size > 0) { + hardAssert(limboResolution.receivedDocument, 0xa4f3); + limboResolution.receivedDocument = false; + } + else { + // This was probably just a CURRENT targetChange or similar. + } + } + }); + await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, changes, remoteEvent); + } + catch (error) { + await ignoreIfPrimaryLeaseLoss(error); + } +} +/** + * Applies an OnlineState change to the sync engine and notifies any views of + * the change. + */ +function syncEngineApplyOnlineStateChange(syncEngine, onlineState, source) { + const syncEngineImpl = debugCast(syncEngine); + // If we are the secondary client, we explicitly ignore the remote store's + // online state (the local client may go offline, even though the primary + // tab remains online) and only apply the primary tab's online state from + // SharedClientState. + if ((syncEngineImpl.isPrimaryClient && + source === 0 /* OnlineStateSource.RemoteStore */) || + (!syncEngineImpl.isPrimaryClient && + source === 1 /* OnlineStateSource.SharedClientState */)) { + const newViewSnapshots = []; + syncEngineImpl.queryViewsByQuery.forEach((query, queryView) => { + const viewChange = queryView.view.applyOnlineStateChange(onlineState); + if (viewChange.snapshot) { + newViewSnapshots.push(viewChange.snapshot); + } + }); + eventManagerOnOnlineStateChange(syncEngineImpl.eventManager, onlineState); + if (newViewSnapshots.length) { + syncEngineImpl.syncEngineListener.onWatchChange(newViewSnapshots); + } + syncEngineImpl.onlineState = onlineState; + if (syncEngineImpl.isPrimaryClient) { + syncEngineImpl.sharedClientState.setOnlineState(onlineState); + } + } +} +/** + * Rejects the listen for the given targetID. This can be triggered by the + * backend for any active target. + * + * @param syncEngine - The sync engine implementation. + * @param targetId - The targetID corresponds to one previously initiated by the + * user as part of TargetData passed to listen() on RemoteStore. + * @param err - A description of the condition that has forced the rejection. + * Nearly always this will be an indication that the user is no longer + * authorized to see the data matching the target. + */ +async function syncEngineRejectListen(syncEngine, targetId, err) { + const syncEngineImpl = debugCast(syncEngine); + // PORTING NOTE: Multi-tab only. + syncEngineImpl.sharedClientState.updateQueryState(targetId, 'rejected', err); + const limboResolution = syncEngineImpl.activeLimboResolutionsByTarget.get(targetId); + const limboKey = limboResolution && limboResolution.key; + if (limboKey) { + // TODO(klimt): We really only should do the following on permission + // denied errors, but we don't have the cause code here. + // It's a limbo doc. Create a synthetic event saying it was deleted. + // This is kind of a hack. Ideally, we would have a method in the local + // store to purge a document. However, it would be tricky to keep all of + // the local store's invariants with another method. + let documentUpdates = new SortedMap(DocumentKey.comparator); + // TODO(b/217189216): This limbo document should ideally have a read time, + // so that it is picked up by any read-time based scans. The backend, + // however, does not send a read time for target removals. + documentUpdates = documentUpdates.insert(limboKey, MutableDocument.newNoDocument(limboKey, SnapshotVersion.min())); + const resolvedLimboDocuments = documentKeySet().add(limboKey); + const event = new RemoteEvent(SnapshotVersion.min(), + /* targetChanges= */ new Map(), + /* targetMismatches= */ new SortedMap(primitiveComparator), documentUpdates, resolvedLimboDocuments); + await syncEngineApplyRemoteEvent(syncEngineImpl, event); + // Since this query failed, we won't want to manually unlisten to it. + // We only remove it from bookkeeping after we successfully applied the + // RemoteEvent. If `applyRemoteEvent()` throws, we want to re-listen to + // this query when the RemoteStore restarts the Watch stream, which should + // re-trigger the target failure. + syncEngineImpl.activeLimboTargetsByKey = + syncEngineImpl.activeLimboTargetsByKey.remove(limboKey); + syncEngineImpl.activeLimboResolutionsByTarget.delete(targetId); + pumpEnqueuedLimboResolutions(syncEngineImpl); + } + else { + await localStoreReleaseTarget(syncEngineImpl.localStore, targetId, + /* keepPersistedTargetData */ false) + .then(() => removeAndCleanupTarget(syncEngineImpl, targetId, err)) + .catch(ignoreIfPrimaryLeaseLoss); + } +} +async function syncEngineApplySuccessfulWrite(syncEngine, mutationBatchResult) { + const syncEngineImpl = debugCast(syncEngine); + const batchId = mutationBatchResult.batch.batchId; + try { + const changes = await localStoreAcknowledgeBatch(syncEngineImpl.localStore, mutationBatchResult); + // The local store may or may not be able to apply the write result and + // raise events immediately (depending on whether the watcher is caught + // up), so we raise user callbacks first so that they consistently happen + // before listen events. + processUserCallback(syncEngineImpl, batchId, /*error=*/ null); + triggerPendingWritesCallbacks(syncEngineImpl, batchId); + syncEngineImpl.sharedClientState.updateMutationState(batchId, 'acknowledged'); + await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, changes); + } + catch (error) { + await ignoreIfPrimaryLeaseLoss(error); + } +} +async function syncEngineRejectFailedWrite(syncEngine, batchId, error) { + const syncEngineImpl = debugCast(syncEngine); + try { + const changes = await localStoreRejectBatch(syncEngineImpl.localStore, batchId); + // The local store may or may not be able to apply the write result and + // raise events immediately (depending on whether the watcher is caught up), + // so we raise user callbacks first so that they consistently happen before + // listen events. + processUserCallback(syncEngineImpl, batchId, error); + triggerPendingWritesCallbacks(syncEngineImpl, batchId); + syncEngineImpl.sharedClientState.updateMutationState(batchId, 'rejected', error); + await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, changes); + } + catch (error) { + await ignoreIfPrimaryLeaseLoss(error); + } +} +/** + * Registers a user callback that resolves when all pending mutations at the moment of calling + * are acknowledged . + */ +async function syncEngineRegisterPendingWritesCallback(syncEngine, callback) { + const syncEngineImpl = debugCast(syncEngine); + if (!canUseNetwork(syncEngineImpl.remoteStore)) { + logDebug(LOG_TAG$3, 'The network is disabled. The task returned by ' + + "'awaitPendingWrites()' will not complete until the network is enabled."); + } + try { + const highestBatchId = await localStoreGetHighestUnacknowledgedBatchId(syncEngineImpl.localStore); + if (highestBatchId === BATCHID_UNKNOWN) { + // Trigger the callback right away if there is no pending writes at the moment. + callback.resolve(); + return; + } + const callbacks = syncEngineImpl.pendingWritesCallbacks.get(highestBatchId) || []; + callbacks.push(callback); + syncEngineImpl.pendingWritesCallbacks.set(highestBatchId, callbacks); + } + catch (e) { + const firestoreError = wrapInUserErrorIfRecoverable(e, 'Initialization of waitForPendingWrites() operation failed'); + callback.reject(firestoreError); + } +} +/** + * Triggers the callbacks that are waiting for this batch id to get acknowledged by server, + * if there are any. + */ +function triggerPendingWritesCallbacks(syncEngineImpl, batchId) { + (syncEngineImpl.pendingWritesCallbacks.get(batchId) || []).forEach(callback => { + callback.resolve(); + }); + syncEngineImpl.pendingWritesCallbacks.delete(batchId); +} +/** Reject all outstanding callbacks waiting for pending writes to complete. */ +function rejectOutstandingPendingWritesCallbacks(syncEngineImpl, errorMessage) { + syncEngineImpl.pendingWritesCallbacks.forEach(callbacks => { + callbacks.forEach(callback => { + callback.reject(new FirestoreError(Code.CANCELLED, errorMessage)); + }); + }); + syncEngineImpl.pendingWritesCallbacks.clear(); +} +function addMutationCallback(syncEngineImpl, batchId, callback) { + let newCallbacks = syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()]; + if (!newCallbacks) { + newCallbacks = new SortedMap(primitiveComparator); + } + newCallbacks = newCallbacks.insert(batchId, callback); + syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()] = + newCallbacks; +} +/** + * Resolves or rejects the user callback for the given batch and then discards + * it. + */ +function processUserCallback(syncEngine, batchId, error) { + const syncEngineImpl = debugCast(syncEngine); + let newCallbacks = syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()]; + // NOTE: Mutations restored from persistence won't have callbacks, so it's + // okay for there to be no callback for this ID. + if (newCallbacks) { + const callback = newCallbacks.get(batchId); + if (callback) { + if (error) { + callback.reject(error); + } + else { + callback.resolve(); + } + newCallbacks = newCallbacks.remove(batchId); + } + syncEngineImpl.mutationUserCallbacks[syncEngineImpl.currentUser.toKey()] = + newCallbacks; + } +} +function removeAndCleanupTarget(syncEngineImpl, targetId, error = null) { + syncEngineImpl.sharedClientState.removeLocalQueryTarget(targetId); + for (const query of syncEngineImpl.queriesByTarget.get(targetId)) { + syncEngineImpl.queryViewsByQuery.delete(query); + if (error) { + syncEngineImpl.syncEngineListener.onWatchError(query, error); + } + } + syncEngineImpl.queriesByTarget.delete(targetId); + if (syncEngineImpl.isPrimaryClient) { + const limboKeys = syncEngineImpl.limboDocumentRefs.removeReferencesForId(targetId); + limboKeys.forEach(limboKey => { + const isReferenced = syncEngineImpl.limboDocumentRefs.containsKey(limboKey); + if (!isReferenced) { + // We removed the last reference for this key + removeLimboTarget(syncEngineImpl, limboKey); + } + }); + } +} +function removeLimboTarget(syncEngineImpl, key) { + syncEngineImpl.enqueuedLimboResolutions.delete(key.path.canonicalString()); + // It's possible that the target already got removed because the query failed. In that case, + // the key won't exist in `limboTargetsByKey`. Only do the cleanup if we still have the target. + const limboTargetId = syncEngineImpl.activeLimboTargetsByKey.get(key); + if (limboTargetId === null) { + // This target already got removed, because the query failed. + return; + } + remoteStoreUnlisten(syncEngineImpl.remoteStore, limboTargetId); + syncEngineImpl.activeLimboTargetsByKey = + syncEngineImpl.activeLimboTargetsByKey.remove(key); + syncEngineImpl.activeLimboResolutionsByTarget.delete(limboTargetId); + pumpEnqueuedLimboResolutions(syncEngineImpl); +} +function updateTrackedLimbos(syncEngineImpl, targetId, limboChanges) { + for (const limboChange of limboChanges) { + if (limboChange instanceof AddedLimboDocument) { + syncEngineImpl.limboDocumentRefs.addReference(limboChange.key, targetId); + trackLimboChange(syncEngineImpl, limboChange); + } + else if (limboChange instanceof RemovedLimboDocument) { + logDebug(LOG_TAG$3, 'Document no longer in limbo: ' + limboChange.key); + syncEngineImpl.limboDocumentRefs.removeReference(limboChange.key, targetId); + const isReferenced = syncEngineImpl.limboDocumentRefs.containsKey(limboChange.key); + if (!isReferenced) { + // We removed the last reference for this key + removeLimboTarget(syncEngineImpl, limboChange.key); + } + } + else { + fail(0x4d4f, { limboChange }); + } + } +} +function trackLimboChange(syncEngineImpl, limboChange) { + const key = limboChange.key; + const keyString = key.path.canonicalString(); + if (!syncEngineImpl.activeLimboTargetsByKey.get(key) && + !syncEngineImpl.enqueuedLimboResolutions.has(keyString)) { + logDebug(LOG_TAG$3, 'New document in limbo: ' + key); + syncEngineImpl.enqueuedLimboResolutions.add(keyString); + pumpEnqueuedLimboResolutions(syncEngineImpl); + } +} +/** + * Starts listens for documents in limbo that are enqueued for resolution, + * subject to a maximum number of concurrent resolutions. + * + * Without bounding the number of concurrent resolutions, the server can fail + * with "resource exhausted" errors which can lead to pathological client + * behavior as seen in https://github.com/firebase/firebase-js-sdk/issues/2683. + */ +function pumpEnqueuedLimboResolutions(syncEngineImpl) { + while (syncEngineImpl.enqueuedLimboResolutions.size > 0 && + syncEngineImpl.activeLimboTargetsByKey.size < + syncEngineImpl.maxConcurrentLimboResolutions) { + const keyString = syncEngineImpl.enqueuedLimboResolutions + .values() + .next().value; + syncEngineImpl.enqueuedLimboResolutions.delete(keyString); + const key = new DocumentKey(ResourcePath.fromString(keyString)); + const limboTargetId = syncEngineImpl.limboTargetIdGenerator.next(); + syncEngineImpl.activeLimboResolutionsByTarget.set(limboTargetId, new LimboResolution(key)); + syncEngineImpl.activeLimboTargetsByKey = + syncEngineImpl.activeLimboTargetsByKey.insert(key, limboTargetId); + remoteStoreListen(syncEngineImpl.remoteStore, new TargetData(queryToTarget(newQueryForPath(key.path)), limboTargetId, "TargetPurposeLimboResolution" /* TargetPurpose.LimboResolution */, ListenSequence.INVALID)); + } +} +async function syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngine, changes, remoteEvent) { + const syncEngineImpl = debugCast(syncEngine); + const newSnaps = []; + const docChangesInAllViews = []; + const queriesProcessed = []; + if (syncEngineImpl.queryViewsByQuery.isEmpty()) { + // Return early since `onWatchChange()` might not have been assigned yet. + return; + } + syncEngineImpl.queryViewsByQuery.forEach((_, queryView) => { + queriesProcessed.push(syncEngineImpl + .applyDocChanges(queryView, changes, remoteEvent) + .then(viewSnapshot => { + // If there are changes, or we are handling a global snapshot, notify + // secondary clients to update query state. + if (viewSnapshot || remoteEvent) { + if (syncEngineImpl.isPrimaryClient) { + // Query state is set to `current` if: + // - There is a view change and it is up-to-date, or, + // - There is a global snapshot, the Target is current, and no changes to be resolved + const isCurrent = viewSnapshot + ? !viewSnapshot.fromCache + : remoteEvent?.targetChanges.get(queryView.targetId)?.current; + syncEngineImpl.sharedClientState.updateQueryState(queryView.targetId, isCurrent ? 'current' : 'not-current'); + } + } + // Update views if there are actual changes. + if (!!viewSnapshot) { + newSnaps.push(viewSnapshot); + const docChanges = LocalViewChanges.fromSnapshot(queryView.targetId, viewSnapshot); + docChangesInAllViews.push(docChanges); + } + })); + }); + await Promise.all(queriesProcessed); + syncEngineImpl.syncEngineListener.onWatchChange(newSnaps); + await localStoreNotifyLocalViewChanges(syncEngineImpl.localStore, docChangesInAllViews); +} +async function applyDocChanges(syncEngineImpl, queryView, changes, remoteEvent) { + let viewDocChanges = queryView.view.computeDocChanges(changes); + if (viewDocChanges.needsRefill) { + // The query has a limit and some docs were removed, so we need + // to re-run the query against the local store to make sure we + // didn't lose any good docs that had been past the limit. + viewDocChanges = await localStoreExecuteQuery(syncEngineImpl.localStore, queryView.query, + /* usePreviousResults= */ false).then(({ documents }) => { + return queryView.view.computeDocChanges(documents, viewDocChanges); + }); + } + const targetChange = remoteEvent && remoteEvent.targetChanges.get(queryView.targetId); + const targetIsPendingReset = remoteEvent && remoteEvent.targetMismatches.get(queryView.targetId) != null; + const viewChange = queryView.view.applyChanges(viewDocChanges, + /* limboResolutionEnabled= */ syncEngineImpl.isPrimaryClient, targetChange, targetIsPendingReset); + updateTrackedLimbos(syncEngineImpl, queryView.targetId, viewChange.limboChanges); + return viewChange.snapshot; +} +async function syncEngineHandleCredentialChange(syncEngine, user) { + const syncEngineImpl = debugCast(syncEngine); + const userChanged = !syncEngineImpl.currentUser.isEqual(user); + if (userChanged) { + logDebug(LOG_TAG$3, 'User change. New user:', user.toKey()); + const result = await localStoreHandleUserChange(syncEngineImpl.localStore, user); + syncEngineImpl.currentUser = user; + // Fails tasks waiting for pending writes requested by previous user. + rejectOutstandingPendingWritesCallbacks(syncEngineImpl, "'waitForPendingWrites' promise is rejected due to a user change."); + // TODO(b/114226417): Consider calling this only in the primary tab. + syncEngineImpl.sharedClientState.handleUserChange(user, result.removedBatchIds, result.addedBatchIds); + await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, result.affectedDocuments); + } +} +function syncEngineGetRemoteKeysForTarget(syncEngine, targetId) { + const syncEngineImpl = debugCast(syncEngine); + const limboResolution = syncEngineImpl.activeLimboResolutionsByTarget.get(targetId); + if (limboResolution && limboResolution.receivedDocument) { + return documentKeySet().add(limboResolution.key); + } + else { + let keySet = documentKeySet(); + const queries = syncEngineImpl.queriesByTarget.get(targetId); + if (!queries) { + return keySet; + } + for (const query of queries) { + const queryView = syncEngineImpl.queryViewsByQuery.get(query); + keySet = keySet.unionWith(queryView.view.syncedDocuments); + } + return keySet; + } +} +/** + * Reconcile the list of synced documents in an existing view with those + * from persistence. + */ +async function synchronizeViewAndComputeSnapshot(syncEngine, queryView) { + const syncEngineImpl = debugCast(syncEngine); + const queryResult = await localStoreExecuteQuery(syncEngineImpl.localStore, queryView.query, + /* usePreviousResults= */ true); + const viewSnapshot = queryView.view.synchronizeWithPersistedState(queryResult); + if (syncEngineImpl.isPrimaryClient) { + updateTrackedLimbos(syncEngineImpl, queryView.targetId, viewSnapshot.limboChanges); + } + return viewSnapshot; +} +/** + * Retrieves newly changed documents from remote document cache and raises + * snapshots if needed. + */ +// PORTING NOTE: Multi-Tab only. +async function syncEngineSynchronizeWithChangedDocuments(syncEngine, collectionGroup) { + const syncEngineImpl = debugCast(syncEngine); + return localStoreGetNewDocumentChanges(syncEngineImpl.localStore, collectionGroup).then(changes => syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, changes)); +} +/** Applies a mutation state to an existing batch. */ +// PORTING NOTE: Multi-Tab only. +async function syncEngineApplyBatchState(syncEngine, batchId, batchState, error) { + const syncEngineImpl = debugCast(syncEngine); + const documents = await localStoreLookupMutationDocuments(syncEngineImpl.localStore, batchId); + if (documents === null) { + // A throttled tab may not have seen the mutation before it was completed + // and removed from the mutation queue, in which case we won't have cached + // the affected documents. In this case we can safely ignore the update + // since that means we didn't apply the mutation locally at all (if we + // had, we would have cached the affected documents), and so we will just + // see any resulting document changes via normal remote document updates + // as applicable. + logDebug(LOG_TAG$3, 'Cannot apply mutation batch with id: ' + batchId); + return; + } + if (batchState === 'pending') { + // If we are the primary client, we need to send this write to the + // backend. Secondary clients will ignore these writes since their remote + // connection is disabled. + await fillWritePipeline(syncEngineImpl.remoteStore); + } + else if (batchState === 'acknowledged' || batchState === 'rejected') { + // NOTE: Both these methods are no-ops for batches that originated from + // other clients. + processUserCallback(syncEngineImpl, batchId, error ? error : null); + triggerPendingWritesCallbacks(syncEngineImpl, batchId); + localStoreRemoveCachedMutationBatchMetadata(syncEngineImpl.localStore, batchId); + } + else { + fail(0x1a40, `Unknown batchState`, { batchState }); + } + await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, documents); +} +/** Applies a query target change from a different tab. */ +// PORTING NOTE: Multi-Tab only. +async function syncEngineApplyPrimaryState(syncEngine, isPrimary) { + const syncEngineImpl = debugCast(syncEngine); + ensureWatchCallbacks(syncEngineImpl); + syncEngineEnsureWriteCallbacks(syncEngineImpl); + if (isPrimary === true && syncEngineImpl._isPrimaryClient !== true) { + // Secondary tabs only maintain Views for their local listeners and the + // Views internal state may not be 100% populated (in particular + // secondary tabs don't track syncedDocuments, the set of documents the + // server considers to be in the target). So when a secondary becomes + // primary, we need to need to make sure that all views for all targets + // match the state on disk. + const activeTargets = syncEngineImpl.sharedClientState.getAllActiveQueryTargets(); + const activeQueries = await synchronizeQueryViewsAndRaiseSnapshots(syncEngineImpl, activeTargets.toArray()); + syncEngineImpl._isPrimaryClient = true; + await remoteStoreApplyPrimaryState(syncEngineImpl.remoteStore, true); + for (const targetData of activeQueries) { + remoteStoreListen(syncEngineImpl.remoteStore, targetData); + } + } + else if (isPrimary === false && syncEngineImpl._isPrimaryClient !== false) { + const activeTargets = []; + let p = Promise.resolve(); + syncEngineImpl.queriesByTarget.forEach((_, targetId) => { + if (syncEngineImpl.sharedClientState.isLocalQueryTarget(targetId)) { + activeTargets.push(targetId); + } + else { + p = p.then(() => { + removeAndCleanupTarget(syncEngineImpl, targetId); + return localStoreReleaseTarget(syncEngineImpl.localStore, targetId, + /*keepPersistedTargetData=*/ true); + }); + } + remoteStoreUnlisten(syncEngineImpl.remoteStore, targetId); + }); + await p; + await synchronizeQueryViewsAndRaiseSnapshots(syncEngineImpl, activeTargets); + resetLimboDocuments(syncEngineImpl); + syncEngineImpl._isPrimaryClient = false; + await remoteStoreApplyPrimaryState(syncEngineImpl.remoteStore, false); + } +} +// PORTING NOTE: Multi-Tab only. +function resetLimboDocuments(syncEngine) { + const syncEngineImpl = debugCast(syncEngine); + syncEngineImpl.activeLimboResolutionsByTarget.forEach((_, targetId) => { + remoteStoreUnlisten(syncEngineImpl.remoteStore, targetId); + }); + syncEngineImpl.limboDocumentRefs.removeAllReferences(); + syncEngineImpl.activeLimboResolutionsByTarget = new Map(); + syncEngineImpl.activeLimboTargetsByKey = new SortedMap(DocumentKey.comparator); +} +/** + * Reconcile the query views of the provided query targets with the state from + * persistence. Raises snapshots for any changes that affect the local + * client and returns the updated state of all target's query data. + * + * @param syncEngine - The sync engine implementation + * @param targets - the list of targets with views that need to be recomputed + * @param transitionToPrimary - `true` iff the tab transitions from a secondary + * tab to a primary tab + */ +// PORTING NOTE: Multi-Tab only. +async function synchronizeQueryViewsAndRaiseSnapshots(syncEngine, targets, transitionToPrimary) { + const syncEngineImpl = debugCast(syncEngine); + const activeQueries = []; + const newViewSnapshots = []; + for (const targetId of targets) { + let targetData; + const queries = syncEngineImpl.queriesByTarget.get(targetId); + if (queries && queries.length !== 0) { + // For queries that have a local View, we fetch their current state + // from LocalStore (as the resume token and the snapshot version + // might have changed) and reconcile their views with the persisted + // state (the list of syncedDocuments may have gotten out of sync). + targetData = await localStoreAllocateTarget(syncEngineImpl.localStore, queryToTarget(queries[0])); + for (const query of queries) { + const queryView = syncEngineImpl.queryViewsByQuery.get(query); + const viewChange = await synchronizeViewAndComputeSnapshot(syncEngineImpl, queryView); + if (viewChange.snapshot) { + newViewSnapshots.push(viewChange.snapshot); + } + } + } + else { + // For queries that never executed on this client, we need to + // allocate the target in LocalStore and initialize a new View. + const target = await localStoreGetCachedTarget(syncEngineImpl.localStore, targetId); + targetData = await localStoreAllocateTarget(syncEngineImpl.localStore, target); + await initializeViewAndComputeSnapshot(syncEngineImpl, synthesizeTargetToQuery(target), targetId, + /*current=*/ false, targetData.resumeToken); + } + activeQueries.push(targetData); + } + syncEngineImpl.syncEngineListener.onWatchChange(newViewSnapshots); + return activeQueries; +} +/** + * Creates a `Query` object from the specified `Target`. There is no way to + * obtain the original `Query`, so we synthesize a `Query` from the `Target` + * object. + * + * The synthesized result might be different from the original `Query`, but + * since the synthesized `Query` should return the same results as the + * original one (only the presentation of results might differ), the potential + * difference will not cause issues. + */ +// PORTING NOTE: Multi-Tab only. +function synthesizeTargetToQuery(target) { + return newQuery(target.path, target.collectionGroup, target.orderBy, target.filters, target.limit, "F" /* LimitType.First */, target.startAt, target.endAt); +} +/** Returns the IDs of the clients that are currently active. */ +// PORTING NOTE: Multi-Tab only. +function syncEngineGetActiveClients(syncEngine) { + const syncEngineImpl = debugCast(syncEngine); + return localStoreGetActiveClients(syncEngineImpl.localStore); +} +/** Applies a query target change from a different tab. */ +// PORTING NOTE: Multi-Tab only. +async function syncEngineApplyTargetState(syncEngine, targetId, state, error) { + const syncEngineImpl = debugCast(syncEngine); + if (syncEngineImpl._isPrimaryClient) { + // If we receive a target state notification via WebStorage, we are + // either already secondary or another tab has taken the primary lease. + logDebug(LOG_TAG$3, 'Ignoring unexpected query state notification.'); + return; + } + const query = syncEngineImpl.queriesByTarget.get(targetId); + if (query && query.length > 0) { + switch (state) { + case 'current': + case 'not-current': { + const changes = await localStoreGetNewDocumentChanges(syncEngineImpl.localStore, queryCollectionGroup(query[0])); + const synthesizedRemoteEvent = RemoteEvent.createSynthesizedRemoteEventForCurrentChange(targetId, state === 'current', ByteString.EMPTY_BYTE_STRING); + await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngineImpl, changes, synthesizedRemoteEvent); + break; + } + case 'rejected': { + await localStoreReleaseTarget(syncEngineImpl.localStore, targetId, + /* keepPersistedTargetData */ true); + removeAndCleanupTarget(syncEngineImpl, targetId, error); + break; + } + default: + fail(0xfa9b, state); + } + } +} +/** Adds or removes Watch targets for queries from different tabs. */ +async function syncEngineApplyActiveTargetsChange(syncEngine, added, removed) { + const syncEngineImpl = ensureWatchCallbacks(syncEngine); + if (!syncEngineImpl._isPrimaryClient) { + return; + } + for (const targetId of added) { + // A target is already listening to remote store if it is already registered to + // sharedClientState. + const targetAlreadyListeningToRemoteStore = syncEngineImpl.queriesByTarget.has(targetId) && + syncEngineImpl.sharedClientState.isActiveQueryTarget(targetId); + if (targetAlreadyListeningToRemoteStore) { + logDebug(LOG_TAG$3, 'Adding an already active target ' + targetId); + continue; + } + const target = await localStoreGetCachedTarget(syncEngineImpl.localStore, targetId); + const targetData = await localStoreAllocateTarget(syncEngineImpl.localStore, target); + await initializeViewAndComputeSnapshot(syncEngineImpl, synthesizeTargetToQuery(target), targetData.targetId, + /*current=*/ false, targetData.resumeToken); + remoteStoreListen(syncEngineImpl.remoteStore, targetData); + } + for (const targetId of removed) { + // Check that the target is still active since the target might have been + // removed if it has been rejected by the backend. + if (!syncEngineImpl.queriesByTarget.has(targetId)) { + continue; + } + // Release queries that are still active. + await localStoreReleaseTarget(syncEngineImpl.localStore, targetId, + /* keepPersistedTargetData */ false) + .then(() => { + remoteStoreUnlisten(syncEngineImpl.remoteStore, targetId); + removeAndCleanupTarget(syncEngineImpl, targetId); + }) + .catch(ignoreIfPrimaryLeaseLoss); + } +} +function ensureWatchCallbacks(syncEngine) { + const syncEngineImpl = debugCast(syncEngine); + syncEngineImpl.remoteStore.remoteSyncer.applyRemoteEvent = + syncEngineApplyRemoteEvent.bind(null, syncEngineImpl); + syncEngineImpl.remoteStore.remoteSyncer.getRemoteKeysForTarget = + syncEngineGetRemoteKeysForTarget.bind(null, syncEngineImpl); + syncEngineImpl.remoteStore.remoteSyncer.rejectListen = + syncEngineRejectListen.bind(null, syncEngineImpl); + syncEngineImpl.syncEngineListener.onWatchChange = + eventManagerOnWatchChange.bind(null, syncEngineImpl.eventManager); + syncEngineImpl.syncEngineListener.onWatchError = + eventManagerOnWatchError.bind(null, syncEngineImpl.eventManager); + return syncEngineImpl; +} +function syncEngineEnsureWriteCallbacks(syncEngine) { + const syncEngineImpl = debugCast(syncEngine); + syncEngineImpl.remoteStore.remoteSyncer.applySuccessfulWrite = + syncEngineApplySuccessfulWrite.bind(null, syncEngineImpl); + syncEngineImpl.remoteStore.remoteSyncer.rejectFailedWrite = + syncEngineRejectFailedWrite.bind(null, syncEngineImpl); + return syncEngineImpl; +} +/** + * Loads a Firestore bundle into the SDK. The returned promise resolves when + * the bundle finished loading. + * + * @param syncEngine - SyncEngine to use. + * @param bundleReader - Bundle to load into the SDK. + * @param task - LoadBundleTask used to update the loading progress to public API. + */ +function syncEngineLoadBundle(syncEngine, bundleReader, task) { + const syncEngineImpl = debugCast(syncEngine); + // eslint-disable-next-line @typescript-eslint/no-floating-promises + loadBundleImpl(syncEngineImpl, bundleReader, task).then(collectionGroups => { + syncEngineImpl.sharedClientState.notifyBundleLoaded(collectionGroups); + }); +} +/** Loads a bundle and returns the list of affected collection groups. */ +async function loadBundleImpl(syncEngine, reader, task) { + try { + const metadata = await reader.getMetadata(); + const skip = await localStoreHasNewerBundle(syncEngine.localStore, metadata); + if (skip) { + await reader.close(); + task._completeWith(bundleSuccessProgress(metadata)); + return Promise.resolve(new Set()); + } + task._updateProgress(bundleInitialProgress(metadata)); + const loader = new BundleLoader(metadata, reader.serializer); + let element = await reader.nextElement(); + while (element) { + ; + const progress = await loader.addSizedElement(element); + if (progress) { + task._updateProgress(progress); + } + element = await reader.nextElement(); + } + const result = await loader.completeAndStoreAsync(syncEngine.localStore); + await syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngine, result.changedDocs, + /* remoteEvent */ undefined); + // Save metadata, so loading the same bundle will skip. + await localStoreSaveBundle(syncEngine.localStore, metadata); + task._completeWith(result.progress); + return Promise.resolve(result.changedCollectionGroups); + } + catch (e) { + logWarn(LOG_TAG$3, `Loading bundle failed with ${e}`); + task._failWith(e); + return Promise.resolve(new Set()); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provides all components needed for Firestore with in-memory persistence. + * Uses EagerGC garbage collection. + */ +class MemoryOfflineComponentProvider { + constructor() { + this.kind = 'memory'; + this.synchronizeTabs = false; + } + async initialize(cfg) { + this.serializer = newSerializer(cfg.databaseInfo.databaseId); + this.sharedClientState = this.createSharedClientState(cfg); + this.persistence = this.createPersistence(cfg); + await this.persistence.start(); + this.localStore = this.createLocalStore(cfg); + this.gcScheduler = this.createGarbageCollectionScheduler(cfg, this.localStore); + this.indexBackfillerScheduler = this.createIndexBackfillerScheduler(cfg, this.localStore); + } + createGarbageCollectionScheduler(cfg, localStore) { + return null; + } + createIndexBackfillerScheduler(cfg, localStore) { + return null; + } + createLocalStore(cfg) { + return newLocalStore(this.persistence, new QueryEngine(), cfg.initialUser, this.serializer); + } + createPersistence(cfg) { + return new MemoryPersistence(MemoryEagerDelegate.factory, this.serializer); + } + createSharedClientState(cfg) { + return new MemorySharedClientState(); + } + async terminate() { + this.gcScheduler?.stop(); + this.indexBackfillerScheduler?.stop(); + this.sharedClientState.shutdown(); + await this.persistence.shutdown(); + } +} +MemoryOfflineComponentProvider.provider = { + build: () => new MemoryOfflineComponentProvider() +}; +class LruGcMemoryOfflineComponentProvider extends MemoryOfflineComponentProvider { + constructor(cacheSizeBytes) { + super(); + this.cacheSizeBytes = cacheSizeBytes; + } + createGarbageCollectionScheduler(cfg, localStore) { + hardAssert(this.persistence.referenceDelegate instanceof MemoryLruDelegate, 0xb743); + const garbageCollector = this.persistence.referenceDelegate.garbageCollector; + return new LruScheduler(garbageCollector, cfg.asyncQueue, localStore); + } + createPersistence(cfg) { + const lruParams = this.cacheSizeBytes !== undefined + ? LruParams.withCacheSize(this.cacheSizeBytes) + : LruParams.DEFAULT; + return new MemoryPersistence(p => MemoryLruDelegate.factory(p, lruParams), this.serializer); + } +} +/** + * Provides all components needed for Firestore with IndexedDB persistence. + */ +class IndexedDbOfflineComponentProvider extends MemoryOfflineComponentProvider { + constructor(onlineComponentProvider, cacheSizeBytes, forceOwnership) { + super(); + this.onlineComponentProvider = onlineComponentProvider; + this.cacheSizeBytes = cacheSizeBytes; + this.forceOwnership = forceOwnership; + this.kind = 'persistent'; + this.synchronizeTabs = false; + } + async initialize(cfg) { + await super.initialize(cfg); + await this.onlineComponentProvider.initialize(this, cfg); + // Enqueue writes from a previous session + await syncEngineEnsureWriteCallbacks(this.onlineComponentProvider.syncEngine); + await fillWritePipeline(this.onlineComponentProvider.remoteStore); + // NOTE: This will immediately call the listener, so we make sure to + // set it after localStore / remoteStore are started. + await this.persistence.setPrimaryStateListener(() => { + if (this.gcScheduler && !this.gcScheduler.started) { + this.gcScheduler.start(); + } + if (this.indexBackfillerScheduler && + !this.indexBackfillerScheduler.started) { + this.indexBackfillerScheduler.start(); + } + return Promise.resolve(); + }); + } + createLocalStore(cfg) { + return newLocalStore(this.persistence, new QueryEngine(), cfg.initialUser, this.serializer); + } + createGarbageCollectionScheduler(cfg, localStore) { + const garbageCollector = this.persistence.referenceDelegate.garbageCollector; + return new LruScheduler(garbageCollector, cfg.asyncQueue, localStore); + } + createIndexBackfillerScheduler(cfg, localStore) { + const indexBackfiller = new IndexBackfiller(localStore, this.persistence); + return new IndexBackfillerScheduler(cfg.asyncQueue, indexBackfiller); + } + createPersistence(cfg) { + const persistenceKey = indexedDbStoragePrefix(cfg.databaseInfo.databaseId, cfg.databaseInfo.persistenceKey); + const lruParams = this.cacheSizeBytes !== undefined + ? LruParams.withCacheSize(this.cacheSizeBytes) + : LruParams.DEFAULT; + return new IndexedDbPersistence(this.synchronizeTabs, persistenceKey, cfg.clientId, lruParams, cfg.asyncQueue, getWindow(), getDocument(), this.serializer, this.sharedClientState, !!this.forceOwnership); + } + createSharedClientState(cfg) { + return new MemorySharedClientState(); + } +} +/** + * Provides all components needed for Firestore with multi-tab IndexedDB + * persistence. + * + * In the legacy client, this provider is used to provide both multi-tab and + * non-multi-tab persistence since we cannot tell at build time whether + * `synchronizeTabs` will be enabled. + */ +class MultiTabOfflineComponentProvider extends IndexedDbOfflineComponentProvider { + constructor(onlineComponentProvider, cacheSizeBytes) { + super(onlineComponentProvider, cacheSizeBytes, /* forceOwnership= */ false); + this.onlineComponentProvider = onlineComponentProvider; + this.cacheSizeBytes = cacheSizeBytes; + this.synchronizeTabs = true; + } + async initialize(cfg) { + await super.initialize(cfg); + const syncEngine = this.onlineComponentProvider.syncEngine; + if (this.sharedClientState instanceof WebStorageSharedClientState) { + this.sharedClientState.syncEngine = { + applyBatchState: syncEngineApplyBatchState.bind(null, syncEngine), + applyTargetState: syncEngineApplyTargetState.bind(null, syncEngine), + applyActiveTargetsChange: syncEngineApplyActiveTargetsChange.bind(null, syncEngine), + getActiveClients: syncEngineGetActiveClients.bind(null, syncEngine), + synchronizeWithChangedDocuments: syncEngineSynchronizeWithChangedDocuments.bind(null, syncEngine) + }; + await this.sharedClientState.start(); + } + // NOTE: This will immediately call the listener, so we make sure to + // set it after localStore / remoteStore are started. + await this.persistence.setPrimaryStateListener(async (isPrimary) => { + await syncEngineApplyPrimaryState(this.onlineComponentProvider.syncEngine, isPrimary); + if (this.gcScheduler) { + if (isPrimary && !this.gcScheduler.started) { + this.gcScheduler.start(); + } + else if (!isPrimary) { + this.gcScheduler.stop(); + } + } + if (this.indexBackfillerScheduler) { + if (isPrimary && !this.indexBackfillerScheduler.started) { + this.indexBackfillerScheduler.start(); + } + else if (!isPrimary) { + this.indexBackfillerScheduler.stop(); + } + } + }); + } + createSharedClientState(cfg) { + const window = getWindow(); + if (!WebStorageSharedClientState.isAvailable(window)) { + throw new FirestoreError(Code.UNIMPLEMENTED, 'IndexedDB persistence is only available on platforms that support LocalStorage.'); + } + const persistenceKey = indexedDbStoragePrefix(cfg.databaseInfo.databaseId, cfg.databaseInfo.persistenceKey); + return new WebStorageSharedClientState(window, cfg.asyncQueue, persistenceKey, cfg.clientId, cfg.initialUser); + } +} +/** + * Initializes and wires the components that are needed to interface with the + * network. + */ +class OnlineComponentProvider { + async initialize(offlineComponentProvider, cfg) { + if (this.localStore) { + // OnlineComponentProvider may get initialized multiple times if + // multi-tab persistence is used. + return; + } + this.localStore = offlineComponentProvider.localStore; + this.sharedClientState = offlineComponentProvider.sharedClientState; + this.datastore = this.createDatastore(cfg); + this.remoteStore = this.createRemoteStore(cfg); + this.eventManager = this.createEventManager(cfg); + this.syncEngine = this.createSyncEngine(cfg, + /* startAsPrimary=*/ !offlineComponentProvider.synchronizeTabs); + this.sharedClientState.onlineStateHandler = onlineState => syncEngineApplyOnlineStateChange(this.syncEngine, onlineState, 1 /* OnlineStateSource.SharedClientState */); + this.remoteStore.remoteSyncer.handleCredentialChange = + syncEngineHandleCredentialChange.bind(null, this.syncEngine); + await remoteStoreApplyPrimaryState(this.remoteStore, this.syncEngine.isPrimaryClient); + } + createEventManager(cfg) { + return newEventManager(); + } + createDatastore(cfg) { + const serializer = newSerializer(cfg.databaseInfo.databaseId); + const connection = newConnection(cfg.databaseInfo); + return newDatastore(cfg.authCredentials, cfg.appCheckCredentials, connection, serializer); + } + createRemoteStore(cfg) { + return newRemoteStore(this.localStore, this.datastore, cfg.asyncQueue, onlineState => syncEngineApplyOnlineStateChange(this.syncEngine, onlineState, 0 /* OnlineStateSource.RemoteStore */), newConnectivityMonitor()); + } + createSyncEngine(cfg, startAsPrimary) { + return newSyncEngine(this.localStore, this.remoteStore, this.eventManager, this.sharedClientState, cfg.initialUser, cfg.maxConcurrentLimboResolutions, startAsPrimary); + } + async terminate() { + await remoteStoreShutdown(this.remoteStore); + this.datastore?.terminate(); + this.eventManager?.terminate(); + } +} +OnlineComponentProvider.provider = { + build: () => new OnlineComponentProvider() +}; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * How many bytes to read each time when `ReadableStreamReader.read()` is + * called. Only applicable for byte streams that we control (e.g. those backed + * by an UInt8Array). + */ +const DEFAULT_BYTES_PER_READ = 10240; +/** + * Builds a `ByteStreamReader` from a UInt8Array. + * @param source - The data source to use. + * @param bytesPerRead - How many bytes each `read()` from the returned reader + * will read. + */ +function toByteStreamReaderHelper(source, bytesPerRead = DEFAULT_BYTES_PER_READ) { + let readFrom = 0; + // The TypeScript definition for ReadableStreamReader changed. We use + // `any` here to allow this code to compile with different versions. + // See https://github.com/microsoft/TypeScript/issues/42970 + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const reader = { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + async read() { + if (readFrom < source.byteLength) { + const result = { + value: source.slice(readFrom, readFrom + bytesPerRead), + done: false + }; + readFrom += bytesPerRead; + return result; + } + return { done: true }; + }, + async cancel() { }, + releaseLock() { }, + closed: Promise.resolve() + }; + return reader; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * On Node, only supported data source is a `Uint8Array` for now. + */ +function toByteStreamReader(source, bytesPerRead) { + if (!(source instanceof Uint8Array)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `NodePlatform.toByteStreamReader expects source to be Uint8Array, got ${valueDescription(source)}`); + } + return toByteStreamReaderHelper(source, bytesPerRead); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * A wrapper implementation of Observer that will dispatch events + * asynchronously. To allow immediate silencing, a mute call is added which + * causes events scheduled to no longer be raised. + */ +class AsyncObserver { + constructor(observer) { + this.observer = observer; + /** + * When set to true, will not raise future events. Necessary to deal with + * async detachment of listener. + */ + this.muted = false; + } + next(value) { + if (this.muted) { + return; + } + if (this.observer.next) { + this.scheduleEvent(this.observer.next, value); + } + } + error(error) { + if (this.muted) { + return; + } + if (this.observer.error) { + this.scheduleEvent(this.observer.error, error); + } + else { + logError('Uncaught Error in snapshot listener:', error.toString()); + } + } + mute() { + this.muted = true; + } + scheduleEvent(eventHandler, event) { + setTimeout(() => { + if (!this.muted) { + eventHandler(event); + } + }, 0); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A complete element in the bundle stream, together with the byte length it + * occupies in the stream. + */ +class SizedBundleElement { + constructor(payload, + // How many bytes this element takes to store in the bundle. + byteLength) { + this.payload = payload; + this.byteLength = byteLength; + } + isBundleMetadata() { + return 'metadata' in this.payload; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A class representing a bundle. + * + * Takes a bundle stream or buffer, and presents abstractions to read bundled + * elements out of the underlying content. + */ +class BundleReaderImpl { + constructor( + /** The reader to read from underlying binary bundle data source. */ + reader, serializer) { + this.reader = reader; + this.serializer = serializer; + /** Cached bundle metadata. */ + this.metadata = new Deferred(); + /** + * Internal buffer to hold bundle content, accumulating incomplete element + * content. + */ + this.buffer = new Uint8Array(); + this.textDecoder = newTextDecoder(); + // Read the metadata (which is the first element). + this.nextElementImpl().then(element => { + if (element && element.isBundleMetadata()) { + this.metadata.resolve(element.payload.metadata); + } + else { + this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is + ${JSON.stringify(element?.payload)}`)); + } + }, error => this.metadata.reject(error)); + } + close() { + return this.reader.cancel(); + } + async getMetadata() { + return this.metadata.promise; + } + async nextElement() { + // Makes sure metadata is read before proceeding. + await this.getMetadata(); + return this.nextElementImpl(); + } + /** + * Reads from the head of internal buffer, and pulling more data from + * underlying stream if a complete element cannot be found, until an + * element(including the prefixed length and the JSON string) is found. + * + * Once a complete element is read, it is dropped from internal buffer. + * + * Returns either the bundled element, or null if we have reached the end of + * the stream. + */ + async nextElementImpl() { + const lengthBuffer = await this.readLength(); + if (lengthBuffer === null) { + return null; + } + const lengthString = this.textDecoder.decode(lengthBuffer); + const length = Number(lengthString); + if (isNaN(length)) { + this.raiseError(`length string (${lengthString}) is not valid number`); + } + const jsonString = await this.readJsonString(length); + return new SizedBundleElement(JSON.parse(jsonString), lengthBuffer.length + length); + } + /** First index of '{' from the underlying buffer. */ + indexOfOpenBracket() { + return this.buffer.findIndex(v => v === '{'.charCodeAt(0)); + } + /** + * Reads from the beginning of the internal buffer, until the first '{', and + * return the content. + * + * If reached end of the stream, returns a null. + */ + async readLength() { + while (this.indexOfOpenBracket() < 0) { + const done = await this.pullMoreDataToBuffer(); + if (done) { + break; + } + } + // Broke out of the loop because underlying stream is closed, and there + // happens to be no more data to process. + if (this.buffer.length === 0) { + return null; + } + const position = this.indexOfOpenBracket(); + // Broke out of the loop because underlying stream is closed, but still + // cannot find an open bracket. + if (position < 0) { + this.raiseError('Reached the end of bundle when a length string is expected.'); + } + const result = this.buffer.slice(0, position); + // Update the internal buffer to drop the read length. + this.buffer = this.buffer.slice(position); + return result; + } + /** + * Reads from a specified position from the internal buffer, for a specified + * number of bytes, pulling more data from the underlying stream if needed. + * + * Returns a string decoded from the read bytes. + */ + async readJsonString(length) { + while (this.buffer.length < length) { + const done = await this.pullMoreDataToBuffer(); + if (done) { + this.raiseError('Reached the end of bundle when more is expected.'); + } + } + const result = this.textDecoder.decode(this.buffer.slice(0, length)); + // Update the internal buffer to drop the read json string. + this.buffer = this.buffer.slice(length); + return result; + } + raiseError(message) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.reader.cancel(); + throw new Error(`Invalid bundle format: ${message}`); + } + /** + * Pulls more data from underlying stream to internal buffer. + * Returns a boolean indicating whether the stream is finished. + */ + async pullMoreDataToBuffer() { + const result = await this.reader.read(); + if (!result.done) { + const newBuffer = new Uint8Array(this.buffer.length + result.value.length); + newBuffer.set(this.buffer); + newBuffer.set(result.value, this.buffer.length); + this.buffer = newBuffer; + } + return result.done; + } +} +function newBundleReader(reader, serializer) { + return new BundleReaderImpl(reader, serializer); +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A class that can parse a bundle form the string serialization of a bundle. + */ +class BundleReaderSyncImpl { + constructor(bundleData, serializer) { + this.bundleData = bundleData; + this.serializer = serializer; + this.cursor = 0; + this.elements = []; + let element = this.nextElement(); + if (element && element.isBundleMetadata()) { + this.metadata = element; + } + else { + throw new Error(`The first element of the bundle is not a metadata object, it is + ${JSON.stringify(element?.payload)}`); + } + do { + element = this.nextElement(); + if (element !== null) { + this.elements.push(element); + } + } while (element !== null); + } + /* Returns the parsed metadata of the bundle. */ + getMetadata() { + return this.metadata; + } + /* Returns the DocumentSnapshot or NamedQuery elements of the bundle. */ + getElements() { + return this.elements; + } + /** + * Parses the next element of the bundle. + * + * @returns a SizedBundleElement representation of the next element in the bundle, or null if + * no more elements exist. + */ + nextElement() { + if (this.cursor === this.bundleData.length) { + return null; + } + const length = this.readLength(); + const jsonString = this.readJsonString(length); + return new SizedBundleElement(JSON.parse(jsonString), length); + } + /** + * Reads from a specified position from the bundleData string, for a specified + * number of bytes. + * + * @param length how many characters to read. + * @returns a string parsed from the bundle. + */ + readJsonString(length) { + if (this.cursor + length > this.bundleData.length) { + throw new FirestoreError(Code.INTERNAL, 'Reached the end of bundle when more is expected.'); + } + const result = this.bundleData.slice(this.cursor, (this.cursor += length)); + return result; + } + /** + * Reads from the current cursor until the first '{'. + * + * @returns A string to integer represention of the parsed value. + * @throws An {@link Error} if the cursor has reached the end of the stream, since lengths + * prefix bundle objects. + */ + readLength() { + const startIndex = this.cursor; + let curIndex = this.cursor; + while (curIndex < this.bundleData.length) { + if (this.bundleData[curIndex] === '{') { + if (curIndex === startIndex) { + throw new Error('First character is a bracket and not a number'); + } + this.cursor = curIndex; + return Number(this.bundleData.slice(startIndex, curIndex)); + } + curIndex++; + } + throw new Error('Reached the end of bundle when more is expected.'); + } +} +/** + * Creates an instance of BundleReader without exposing the BundleReaderSyncImpl class type. + */ +function newBundleReaderSync(bundleData, serializer) { + return new BundleReaderSyncImpl(bundleData, serializer); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Internal transaction object responsible for accumulating the mutations to + * perform and the base versions for any documents read. + */ +class Transaction$2 { + constructor(datastore) { + this.datastore = datastore; + // The version of each document that was read during this transaction. + this.readVersions = new Map(); + this.mutations = []; + this.committed = false; + /** + * A deferred usage error that occurred previously in this transaction that + * will cause the transaction to fail once it actually commits. + */ + this.lastTransactionError = null; + /** + * Set of documents that have been written in the transaction. + * + * When there's more than one write to the same key in a transaction, any + * writes after the first are handled differently. + */ + this.writtenDocs = new Set(); + } + async lookup(keys) { + this.ensureCommitNotCalled(); + if (this.mutations.length > 0) { + this.lastTransactionError = new FirestoreError(Code.INVALID_ARGUMENT, 'Firestore transactions require all reads to be executed before all writes.'); + throw this.lastTransactionError; + } + const docs = await invokeBatchGetDocumentsRpc(this.datastore, keys); + docs.forEach(doc => this.recordVersion(doc)); + return docs; + } + set(key, data) { + this.write(data.toMutation(key, this.precondition(key))); + this.writtenDocs.add(key.toString()); + } + update(key, data) { + try { + this.write(data.toMutation(key, this.preconditionForUpdate(key))); + } + catch (e) { + this.lastTransactionError = e; + } + this.writtenDocs.add(key.toString()); + } + delete(key) { + this.write(new DeleteMutation(key, this.precondition(key))); + this.writtenDocs.add(key.toString()); + } + async commit() { + this.ensureCommitNotCalled(); + if (this.lastTransactionError) { + throw this.lastTransactionError; + } + const unwritten = this.readVersions; + // For each mutation, note that the doc was written. + this.mutations.forEach(mutation => { + unwritten.delete(mutation.key.toString()); + }); + // For each document that was read but not written to, we want to perform + // a `verify` operation. + unwritten.forEach((_, path) => { + const key = DocumentKey.fromPath(path); + this.mutations.push(new VerifyMutation(key, this.precondition(key))); + }); + await invokeCommitRpc(this.datastore, this.mutations); + this.committed = true; + } + recordVersion(doc) { + let docVersion; + if (doc.isFoundDocument()) { + docVersion = doc.version; + } + else if (doc.isNoDocument()) { + // Represent a deleted doc using SnapshotVersion.min(). + docVersion = SnapshotVersion.min(); + } + else { + throw fail(0xc542, { + documentName: doc.constructor.name + }); + } + const existingVersion = this.readVersions.get(doc.key.toString()); + if (existingVersion) { + if (!docVersion.isEqual(existingVersion)) { + // This transaction will fail no matter what. + throw new FirestoreError(Code.ABORTED, 'Document version changed between two reads.'); + } + } + else { + this.readVersions.set(doc.key.toString(), docVersion); + } + } + /** + * Returns the version of this document when it was read in this transaction, + * as a precondition, or no precondition if it was not read. + */ + precondition(key) { + const version = this.readVersions.get(key.toString()); + if (!this.writtenDocs.has(key.toString()) && version) { + if (version.isEqual(SnapshotVersion.min())) { + return Precondition.exists(false); + } + else { + return Precondition.updateTime(version); + } + } + else { + return Precondition.none(); + } + } + /** + * Returns the precondition for a document if the operation is an update. + */ + preconditionForUpdate(key) { + const version = this.readVersions.get(key.toString()); + // The first time a document is written, we want to take into account the + // read time and existence + if (!this.writtenDocs.has(key.toString()) && version) { + if (version.isEqual(SnapshotVersion.min())) { + // The document doesn't exist, so fail the transaction. + // This has to be validated locally because you can't send a + // precondition that a document does not exist without changing the + // semantics of the backend write to be an insert. This is the reverse + // of what we want, since we want to assert that the document doesn't + // exist but then send the update and have it fail. Since we can't + // express that to the backend, we have to validate locally. + // Note: this can change once we can send separate verify writes in the + // transaction. + throw new FirestoreError(Code.INVALID_ARGUMENT, "Can't update a document that doesn't exist."); + } + // Document exists, base precondition on document update time. + return Precondition.updateTime(version); + } + else { + // Document was not read, so we just use the preconditions for a blind + // update. + return Precondition.exists(true); + } + } + write(mutation) { + this.ensureCommitNotCalled(); + this.mutations.push(mutation); + } + ensureCommitNotCalled() { + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * TransactionRunner encapsulates the logic needed to run and retry transactions + * with backoff. + */ +class TransactionRunner { + constructor(asyncQueue, datastore, options, updateFunction, deferred) { + this.asyncQueue = asyncQueue; + this.datastore = datastore; + this.options = options; + this.updateFunction = updateFunction; + this.deferred = deferred; + this.attemptsRemaining = options.maxAttempts; + this.backoff = new ExponentialBackoff(this.asyncQueue, "transaction_retry" /* TimerId.TransactionRetry */); + } + /** Runs the transaction and sets the result on deferred. */ + run() { + this.attemptsRemaining -= 1; + this.runWithBackOff(); + } + runWithBackOff() { + this.backoff.backoffAndRun(async () => { + const transaction = new Transaction$2(this.datastore); + const userPromise = this.tryRunUpdateFunction(transaction); + if (userPromise) { + userPromise + .then(result => { + this.asyncQueue.enqueueAndForget(() => { + return transaction + .commit() + .then(() => { + this.deferred.resolve(result); + }) + .catch(commitError => { + this.handleTransactionError(commitError); + }); + }); + }) + .catch(userPromiseError => { + this.handleTransactionError(userPromiseError); + }); + } + }); + } + tryRunUpdateFunction(transaction) { + try { + const userPromise = this.updateFunction(transaction); + if (isNullOrUndefined(userPromise) || + !userPromise.catch || + !userPromise.then) { + this.deferred.reject(Error('Transaction callback must return a Promise')); + return null; + } + return userPromise; + } + catch (error) { + // Do not retry errors thrown by user provided updateFunction. + this.deferred.reject(error); + return null; + } + } + handleTransactionError(error) { + if (this.attemptsRemaining > 0 && this.isRetryableTransactionError(error)) { + this.attemptsRemaining -= 1; + this.asyncQueue.enqueueAndForget(() => { + this.runWithBackOff(); + return Promise.resolve(); + }); + } + else { + this.deferred.reject(error); + } + } + isRetryableTransactionError(error) { + if (error?.name === 'FirebaseError') { + // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and + // non-matching document versions with ABORTED. These errors should be retried. + const code = error.code; + return (code === 'aborted' || + code === 'failed-precondition' || + code === 'already-exists' || + !isPermanentError(code)); + } + return false; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$2 = 'FirestoreClient'; +const MAX_CONCURRENT_LIMBO_RESOLUTIONS = 100; +/** DOMException error code constants. */ +const DOM_EXCEPTION_INVALID_STATE = 11; +const DOM_EXCEPTION_ABORTED = 20; +const DOM_EXCEPTION_QUOTA_EXCEEDED = 22; +/** + * FirestoreClient is a top-level class that constructs and owns all of the // + * pieces of the client SDK architecture. It is responsible for creating the // + * async queue that is shared by all of the other components in the system. // + */ +class FirestoreClient { + constructor(authCredentials, appCheckCredentials, + /** + * Asynchronous queue responsible for all of our internal processing. When + * we get incoming work from the user (via public API) or the network + * (incoming GRPC messages), we should always schedule onto this queue. + * This ensures all of our work is properly serialized (e.g. we don't + * start processing a new operation while the previous one is waiting for + * an async I/O to complete). + */ + asyncQueue, databaseInfo, componentProvider) { + this.authCredentials = authCredentials; + this.appCheckCredentials = appCheckCredentials; + this.asyncQueue = asyncQueue; + this.databaseInfo = databaseInfo; + this.user = User.UNAUTHENTICATED; + this.clientId = AutoId.newId(); + this.authCredentialListener = () => Promise.resolve(); + this.appCheckCredentialListener = () => Promise.resolve(); + this._uninitializedComponentsProvider = componentProvider; + this.authCredentials.start(asyncQueue, async (user) => { + logDebug(LOG_TAG$2, 'Received user=', user.uid); + await this.authCredentialListener(user); + this.user = user; + }); + this.appCheckCredentials.start(asyncQueue, newAppCheckToken => { + logDebug(LOG_TAG$2, 'Received new app check token=', newAppCheckToken); + return this.appCheckCredentialListener(newAppCheckToken, this.user); + }); + } + get configuration() { + return { + asyncQueue: this.asyncQueue, + databaseInfo: this.databaseInfo, + clientId: this.clientId, + authCredentials: this.authCredentials, + appCheckCredentials: this.appCheckCredentials, + initialUser: this.user, + maxConcurrentLimboResolutions: MAX_CONCURRENT_LIMBO_RESOLUTIONS + }; + } + setCredentialChangeListener(listener) { + this.authCredentialListener = listener; + } + setAppCheckTokenChangeListener(listener) { + this.appCheckCredentialListener = listener; + } + terminate() { + this.asyncQueue.enterRestrictedMode(); + const deferred = new Deferred(); + this.asyncQueue.enqueueAndForgetEvenWhileRestricted(async () => { + try { + if (this._onlineComponents) { + await this._onlineComponents.terminate(); + } + if (this._offlineComponents) { + await this._offlineComponents.terminate(); + } + // The credentials provider must be terminated after shutting down the + // RemoteStore as it will prevent the RemoteStore from retrieving auth + // tokens. + this.authCredentials.shutdown(); + this.appCheckCredentials.shutdown(); + deferred.resolve(); + } + catch (e) { + const firestoreError = wrapInUserErrorIfRecoverable(e, `Failed to shutdown persistence`); + deferred.reject(firestoreError); + } + }); + return deferred.promise; + } +} +async function setOfflineComponentProvider(client, offlineComponentProvider) { + client.asyncQueue.verifyOperationInProgress(); + logDebug(LOG_TAG$2, 'Initializing OfflineComponentProvider'); + const configuration = client.configuration; + await offlineComponentProvider.initialize(configuration); + let currentUser = configuration.initialUser; + client.setCredentialChangeListener(async (user) => { + if (!currentUser.isEqual(user)) { + await localStoreHandleUserChange(offlineComponentProvider.localStore, user); + currentUser = user; + } + }); + // When a user calls clearPersistence() in one client, all other clients + // need to be terminated to allow the delete to succeed. + offlineComponentProvider.persistence.setDatabaseDeletedListener(() => client.terminate()); + client._offlineComponents = offlineComponentProvider; +} +async function setOnlineComponentProvider(client, onlineComponentProvider) { + client.asyncQueue.verifyOperationInProgress(); + const offlineComponents = await ensureOfflineComponents(client); + logDebug(LOG_TAG$2, 'Initializing OnlineComponentProvider'); + await onlineComponentProvider.initialize(offlineComponents, client.configuration); + // The CredentialChangeListener of the online component provider takes + // precedence over the offline component provider. + client.setCredentialChangeListener(user => remoteStoreHandleCredentialChange(onlineComponentProvider.remoteStore, user)); + client.setAppCheckTokenChangeListener((_, user) => remoteStoreHandleCredentialChange(onlineComponentProvider.remoteStore, user)); + client._onlineComponents = onlineComponentProvider; +} +/** + * Decides whether the provided error allows us to gracefully disable + * persistence (as opposed to crashing the client). + */ +function canFallbackFromIndexedDbError(error) { + if (error.name === 'FirebaseError') { + return (error.code === Code.FAILED_PRECONDITION || + error.code === Code.UNIMPLEMENTED); + } + else if (typeof DOMException !== 'undefined' && + error instanceof DOMException) { + // There are a few known circumstances where we can open IndexedDb but + // trying to read/write will fail (e.g. quota exceeded). For + // well-understood cases, we attempt to detect these and then gracefully + // fall back to memory persistence. + // NOTE: Rather than continue to add to this list, we could decide to + // always fall back, with the risk that we might accidentally hide errors + // representing actual SDK bugs. + return ( + // When the browser is out of quota we could get either quota exceeded + // or an aborted error depending on whether the error happened during + // schema migration. + error.code === DOM_EXCEPTION_QUOTA_EXCEEDED || + error.code === DOM_EXCEPTION_ABORTED || + // Firefox Private Browsing mode disables IndexedDb and returns + // INVALID_STATE for any usage. + error.code === DOM_EXCEPTION_INVALID_STATE); + } + return true; +} +async function ensureOfflineComponents(client) { + if (!client._offlineComponents) { + if (client._uninitializedComponentsProvider) { + logDebug(LOG_TAG$2, 'Using user provided OfflineComponentProvider'); + try { + await setOfflineComponentProvider(client, client._uninitializedComponentsProvider._offline); + } + catch (e) { + const error = e; + if (!canFallbackFromIndexedDbError(error)) { + throw error; + } + logWarn('Error using user provided cache. Falling back to ' + + 'memory cache: ' + + error); + await setOfflineComponentProvider(client, new MemoryOfflineComponentProvider()); + } + } + else { + logDebug(LOG_TAG$2, 'Using default OfflineComponentProvider'); + await setOfflineComponentProvider(client, new LruGcMemoryOfflineComponentProvider(undefined)); + } + } + return client._offlineComponents; +} +async function ensureOnlineComponents(client) { + if (!client._onlineComponents) { + if (client._uninitializedComponentsProvider) { + logDebug(LOG_TAG$2, 'Using user provided OnlineComponentProvider'); + await setOnlineComponentProvider(client, client._uninitializedComponentsProvider._online); + } + else { + logDebug(LOG_TAG$2, 'Using default OnlineComponentProvider'); + await setOnlineComponentProvider(client, new OnlineComponentProvider()); + } + } + return client._onlineComponents; +} +function getPersistence(client) { + return ensureOfflineComponents(client).then(c => c.persistence); +} +function getLocalStore(client) { + return ensureOfflineComponents(client).then(c => c.localStore); +} +function getRemoteStore(client) { + return ensureOnlineComponents(client).then(c => c.remoteStore); +} +function getSyncEngine(client) { + return ensureOnlineComponents(client).then(c => c.syncEngine); +} +function getDatastore(client) { + return ensureOnlineComponents(client).then(c => c.datastore); +} +async function getEventManager(client) { + const onlineComponentProvider = await ensureOnlineComponents(client); + const eventManager = onlineComponentProvider.eventManager; + eventManager.onListen = syncEngineListen.bind(null, onlineComponentProvider.syncEngine); + eventManager.onUnlisten = syncEngineUnlisten.bind(null, onlineComponentProvider.syncEngine); + eventManager.onFirstRemoteStoreListen = triggerRemoteStoreListen.bind(null, onlineComponentProvider.syncEngine); + eventManager.onLastRemoteStoreUnlisten = triggerRemoteStoreUnlisten.bind(null, onlineComponentProvider.syncEngine); + return eventManager; +} +/** Enables the network connection and re-enqueues all pending operations. */ +function firestoreClientEnableNetwork(client) { + return client.asyncQueue.enqueue(async () => { + const persistence = await getPersistence(client); + const remoteStore = await getRemoteStore(client); + persistence.setNetworkEnabled(true); + return remoteStoreEnableNetwork(remoteStore); + }); +} +/** Disables the network connection. Pending operations will not complete. */ +function firestoreClientDisableNetwork(client) { + return client.asyncQueue.enqueue(async () => { + const persistence = await getPersistence(client); + const remoteStore = await getRemoteStore(client); + persistence.setNetworkEnabled(false); + return remoteStoreDisableNetwork(remoteStore); + }); +} +/** + * Returns a Promise that resolves when all writes that were pending at the time + * this method was called received server acknowledgement. An acknowledgement + * can be either acceptance or rejection. + */ +function firestoreClientWaitForPendingWrites(client) { + const deferred = new Deferred(); + client.asyncQueue.enqueueAndForget(async () => { + const syncEngine = await getSyncEngine(client); + return syncEngineRegisterPendingWritesCallback(syncEngine, deferred); + }); + return deferred.promise; +} +function firestoreClientListen(client, query, options, observer) { + const wrappedObserver = new AsyncObserver(observer); + const listener = new QueryListener(query, wrappedObserver, options); + client.asyncQueue.enqueueAndForget(async () => { + const eventManager = await getEventManager(client); + return eventManagerListen(eventManager, listener); + }); + return () => { + wrappedObserver.mute(); + client.asyncQueue.enqueueAndForget(async () => { + const eventManager = await getEventManager(client); + return eventManagerUnlisten(eventManager, listener); + }); + }; +} +function firestoreClientGetDocumentFromLocalCache(client, docKey) { + const deferred = new Deferred(); + client.asyncQueue.enqueueAndForget(async () => { + const localStore = await getLocalStore(client); + return readDocumentFromCache(localStore, docKey, deferred); + }); + return deferred.promise; +} +function firestoreClientGetDocumentViaSnapshotListener(client, key, options = {}) { + const deferred = new Deferred(); + client.asyncQueue.enqueueAndForget(async () => { + const eventManager = await getEventManager(client); + return readDocumentViaSnapshotListener(eventManager, client.asyncQueue, key, options, deferred); + }); + return deferred.promise; +} +function firestoreClientGetDocumentsFromLocalCache(client, query) { + const deferred = new Deferred(); + client.asyncQueue.enqueueAndForget(async () => { + const localStore = await getLocalStore(client); + return executeQueryFromCache(localStore, query, deferred); + }); + return deferred.promise; +} +function firestoreClientGetDocumentsViaSnapshotListener(client, query, options = {}) { + const deferred = new Deferred(); + client.asyncQueue.enqueueAndForget(async () => { + const eventManager = await getEventManager(client); + return executeQueryViaSnapshotListener(eventManager, client.asyncQueue, query, options, deferred); + }); + return deferred.promise; +} +function firestoreClientRunAggregateQuery(client, query, aggregates) { + const deferred = new Deferred(); + client.asyncQueue.enqueueAndForget(async () => { + // Implement and call executeAggregateQueryViaSnapshotListener, similar + // to the implementation in firestoreClientGetDocumentsViaSnapshotListener + // above + try { + // TODO(b/277628384): check `canUseNetwork()` and handle multi-tab. + const datastore = await getDatastore(client); + deferred.resolve(invokeRunAggregationQueryRpc(datastore, query, aggregates)); + } + catch (e) { + deferred.reject(e); + } + }); + return deferred.promise; +} +function firestoreClientWrite(client, mutations) { + const deferred = new Deferred(); + client.asyncQueue.enqueueAndForget(async () => { + const syncEngine = await getSyncEngine(client); + return syncEngineWrite(syncEngine, mutations, deferred); + }); + return deferred.promise; +} +function firestoreClientAddSnapshotsInSyncListener(client, observer) { + const wrappedObserver = new AsyncObserver(observer); + client.asyncQueue.enqueueAndForget(async () => { + const eventManager = await getEventManager(client); + return addSnapshotsInSyncListener(eventManager, wrappedObserver); + }); + return () => { + wrappedObserver.mute(); + client.asyncQueue.enqueueAndForget(async () => { + const eventManager = await getEventManager(client); + return removeSnapshotsInSyncListener(eventManager, wrappedObserver); + }); + }; +} +/** + * Takes an updateFunction in which a set of reads and writes can be performed + * atomically. In the updateFunction, the client can read and write values + * using the supplied transaction object. After the updateFunction, all + * changes will be committed. If a retryable error occurs (ex: some other + * client has changed any of the data referenced), then the updateFunction + * will be called again after a backoff. If the updateFunction still fails + * after all retries, then the transaction will be rejected. + * + * The transaction object passed to the updateFunction contains methods for + * accessing documents and collections. Unlike other datastore access, data + * accessed with the transaction will not reflect local changes that have not + * been committed. For this reason, it is required that all reads are + * performed before any writes. Transactions must be performed while online. + */ +function firestoreClientTransaction(client, updateFunction, options) { + const deferred = new Deferred(); + client.asyncQueue.enqueueAndForget(async () => { + const datastore = await getDatastore(client); + new TransactionRunner(client.asyncQueue, datastore, options, updateFunction, deferred).run(); + }); + return deferred.promise; +} +async function readDocumentFromCache(localStore, docKey, result) { + try { + const document = await localStoreReadDocument(localStore, docKey); + if (document.isFoundDocument()) { + result.resolve(document); + } + else if (document.isNoDocument()) { + result.resolve(null); + } + else { + result.reject(new FirestoreError(Code.UNAVAILABLE, 'Failed to get document from cache. (However, this document may ' + + "exist on the server. Run again without setting 'source' in " + + 'the GetOptions to attempt to retrieve the document from the ' + + 'server.)')); + } + } + catch (e) { + const firestoreError = wrapInUserErrorIfRecoverable(e, `Failed to get document '${docKey} from cache`); + result.reject(firestoreError); + } +} +/** + * Retrieves a latency-compensated document from the backend via a + * SnapshotListener. + */ +function readDocumentViaSnapshotListener(eventManager, asyncQueue, key, options, result) { + const wrappedObserver = new AsyncObserver({ + next: (snap) => { + // Mute and remove query first before passing event to user to avoid + // user actions affecting the now stale query. + wrappedObserver.mute(); + asyncQueue.enqueueAndForget(() => eventManagerUnlisten(eventManager, listener)); + const exists = snap.docs.has(key); + if (!exists && snap.fromCache) { + // TODO(dimond): If we're online and the document doesn't + // exist then we resolve with a doc.exists set to false. If + // we're offline however, we reject the Promise in this + // case. Two options: 1) Cache the negative response from + // the server so we can deliver that even when you're + // offline 2) Actually reject the Promise in the online case + // if the document doesn't exist. + result.reject(new FirestoreError(Code.UNAVAILABLE, 'Failed to get document because the client is offline.')); + } + else if (exists && + snap.fromCache && + options && + options.source === 'server') { + result.reject(new FirestoreError(Code.UNAVAILABLE, 'Failed to get document from server. (However, this ' + + 'document does exist in the local cache. Run again ' + + 'without setting source to "server" to ' + + 'retrieve the cached document.)')); + } + else { + result.resolve(snap); + } + }, + error: e => result.reject(e) + }); + const listener = new QueryListener(newQueryForPath(key.path), wrappedObserver, { + includeMetadataChanges: true, + waitForSyncWhenOnline: true + }); + return eventManagerListen(eventManager, listener); +} +async function executeQueryFromCache(localStore, query, result) { + try { + const queryResult = await localStoreExecuteQuery(localStore, query, + /* usePreviousResults= */ true); + const view = new View(query, queryResult.remoteKeys); + const viewDocChanges = view.computeDocChanges(queryResult.documents); + const viewChange = view.applyChanges(viewDocChanges, + /* limboResolutionEnabled= */ false); + result.resolve(viewChange.snapshot); + } + catch (e) { + const firestoreError = wrapInUserErrorIfRecoverable(e, `Failed to execute query '${query} against cache`); + result.reject(firestoreError); + } +} +/** + * Retrieves a latency-compensated query snapshot from the backend via a + * SnapshotListener. + */ +function executeQueryViaSnapshotListener(eventManager, asyncQueue, query, options, result) { + const wrappedObserver = new AsyncObserver({ + next: snapshot => { + // Mute and remove query first before passing event to user to avoid + // user actions affecting the now stale query. + wrappedObserver.mute(); + asyncQueue.enqueueAndForget(() => eventManagerUnlisten(eventManager, listener)); + if (snapshot.fromCache && options.source === 'server') { + result.reject(new FirestoreError(Code.UNAVAILABLE, 'Failed to get documents from server. (However, these ' + + 'documents may exist in the local cache. Run again ' + + 'without setting source to "server" to ' + + 'retrieve the cached documents.)')); + } + else { + result.resolve(snapshot); + } + }, + error: e => result.reject(e) + }); + const listener = new QueryListener(query, wrappedObserver, { + includeMetadataChanges: true, + waitForSyncWhenOnline: true + }); + return eventManagerListen(eventManager, listener); +} +function firestoreClientLoadBundle(client, databaseId, data, resultTask) { + const reader = createBundleReader(data, newSerializer(databaseId)); + client.asyncQueue.enqueueAndForget(async () => { + syncEngineLoadBundle(await getSyncEngine(client), reader, resultTask); + }); +} +function firestoreClientGetNamedQuery(client, queryName) { + return client.asyncQueue.enqueue(async () => localStoreGetNamedQuery(await getLocalStore(client), queryName)); +} +function createBundleReader(data, serializer) { + let content; + if (typeof data === 'string') { + content = newTextEncoder().encode(data); + } + else { + content = data; + } + return newBundleReader(toByteStreamReader(content), serializer); +} +function createBundleReaderSync(bundleData, serializer) { + return newBundleReaderSync(bundleData, serializer); +} +function firestoreClientSetIndexConfiguration(client, indexes) { + return client.asyncQueue.enqueue(async () => { + return localStoreConfigureFieldIndexes(await getLocalStore(client), indexes); + }); +} +function firestoreClientSetPersistentCacheIndexAutoCreationEnabled(client, isEnabled) { + return client.asyncQueue.enqueue(async () => { + return localStoreSetIndexAutoCreationEnabled(await getLocalStore(client), isEnabled); + }); +} +function firestoreClientDeleteAllFieldIndexes(client) { + return client.asyncQueue.enqueue(async () => { + return localStoreDeleteAllFieldIndexes(await getLocalStore(client)); + }); +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Compares two `ExperimentalLongPollingOptions` objects for equality. + */ +function longPollingOptionsEqual(options1, options2) { + return options1.timeoutSeconds === options2.timeoutSeconds; +} +/** + * Creates and returns a new `ExperimentalLongPollingOptions` with the same + * option values as the given instance. + */ +function cloneLongPollingOptions(options) { + const clone = {}; + if (options.timeoutSeconds !== undefined) { + clone.timeoutSeconds = options.timeoutSeconds; + } + return clone; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$1 = 'ComponentProvider'; +/** + * An instance map that ensures only one Datastore exists per Firestore + * instance. + */ +const datastoreInstances = new Map(); +/** + * Removes all components associated with the provided instance. Must be called + * when the `Firestore` instance is terminated. + */ +function removeComponents(firestore) { + const datastore = datastoreInstances.get(firestore); + if (datastore) { + logDebug(LOG_TAG$1, 'Removing Datastore'); + datastoreInstances.delete(firestore); + datastore.terminate(); + } +} +function makeDatabaseInfo(databaseId, appId, persistenceKey, settings) { + return new DatabaseInfo(databaseId, appId, persistenceKey, settings.host, settings.ssl, settings.experimentalForceLongPolling, settings.experimentalAutoDetectLongPolling, cloneLongPollingOptions(settings.experimentalLongPollingOptions), settings.useFetchStreams, settings.isUsingEmulator); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// settings() defaults: +const DEFAULT_HOST = 'firestore.googleapis.com'; +const DEFAULT_SSL = true; +// The minimum long-polling timeout is hardcoded on the server. The value here +// should be kept in sync with the value used by the server, as the server will +// silently ignore a value below the minimum and fall back to the default. +// Googlers see b/266868871 for relevant discussion. +const MIN_LONG_POLLING_TIMEOUT_SECONDS = 5; +// No maximum long-polling timeout is configured in the server, and defaults to +// 30 seconds, which is what Watch appears to use. +// Googlers see b/266868871 for relevant discussion. +const MAX_LONG_POLLING_TIMEOUT_SECONDS = 30; +// Whether long-polling auto-detected is enabled by default. +const DEFAULT_AUTO_DETECT_LONG_POLLING = true; +/** + * A concrete type describing all the values that can be applied via a + * user-supplied `FirestoreSettings` object. This is a separate type so that + * defaults can be supplied and the value can be checked for equality. + */ +class FirestoreSettingsImpl { + constructor(settings) { + if (settings.host === undefined) { + if (settings.ssl !== undefined) { + throw new FirestoreError(Code.INVALID_ARGUMENT, "Can't provide ssl option if host option is not set"); + } + this.host = DEFAULT_HOST; + this.ssl = DEFAULT_SSL; + } + else { + this.host = settings.host; + this.ssl = settings.ssl ?? DEFAULT_SSL; + } + this.isUsingEmulator = settings.emulatorOptions !== undefined; + this.credentials = settings.credentials; + this.ignoreUndefinedProperties = !!settings.ignoreUndefinedProperties; + this.localCache = settings.localCache; + if (settings.cacheSizeBytes === undefined) { + this.cacheSizeBytes = LRU_DEFAULT_CACHE_SIZE_BYTES; + } + else { + if (settings.cacheSizeBytes !== LRU_COLLECTION_DISABLED && + settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`); + } + else { + this.cacheSizeBytes = settings.cacheSizeBytes; + } + } + validateIsNotUsedTogether('experimentalForceLongPolling', settings.experimentalForceLongPolling, 'experimentalAutoDetectLongPolling', settings.experimentalAutoDetectLongPolling); + this.experimentalForceLongPolling = !!settings.experimentalForceLongPolling; + if (this.experimentalForceLongPolling) { + this.experimentalAutoDetectLongPolling = false; + } + else if (settings.experimentalAutoDetectLongPolling === undefined) { + this.experimentalAutoDetectLongPolling = DEFAULT_AUTO_DETECT_LONG_POLLING; + } + else { + // For backwards compatibility, coerce the value to boolean even though + // the TypeScript compiler has narrowed the type to boolean already. + // noinspection PointlessBooleanExpressionJS + this.experimentalAutoDetectLongPolling = + !!settings.experimentalAutoDetectLongPolling; + } + this.experimentalLongPollingOptions = cloneLongPollingOptions(settings.experimentalLongPollingOptions ?? {}); + validateLongPollingOptions(this.experimentalLongPollingOptions); + this.useFetchStreams = !!settings.useFetchStreams; + } + isEqual(other) { + return (this.host === other.host && + this.ssl === other.ssl && + this.credentials === other.credentials && + this.cacheSizeBytes === other.cacheSizeBytes && + this.experimentalForceLongPolling === + other.experimentalForceLongPolling && + this.experimentalAutoDetectLongPolling === + other.experimentalAutoDetectLongPolling && + longPollingOptionsEqual(this.experimentalLongPollingOptions, other.experimentalLongPollingOptions) && + this.ignoreUndefinedProperties === other.ignoreUndefinedProperties && + this.useFetchStreams === other.useFetchStreams); + } +} +function validateLongPollingOptions(options) { + if (options.timeoutSeconds !== undefined) { + if (isNaN(options.timeoutSeconds)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `invalid long polling timeout: ` + + `${options.timeoutSeconds} (must not be NaN)`); + } + if (options.timeoutSeconds < MIN_LONG_POLLING_TIMEOUT_SECONDS) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `invalid long polling timeout: ${options.timeoutSeconds} ` + + `(minimum allowed value is ${MIN_LONG_POLLING_TIMEOUT_SECONDS})`); + } + if (options.timeoutSeconds > MAX_LONG_POLLING_TIMEOUT_SECONDS) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `invalid long polling timeout: ${options.timeoutSeconds} ` + + `(maximum allowed value is ${MAX_LONG_POLLING_TIMEOUT_SECONDS})`); + } + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ +class Firestore$1 { + /** @hideconstructor */ + constructor(_authCredentials, _appCheckCredentials, _databaseId, _app) { + this._authCredentials = _authCredentials; + this._appCheckCredentials = _appCheckCredentials; + this._databaseId = _databaseId; + this._app = _app; + /** + * Whether it's a Firestore or Firestore Lite instance. + */ + this.type = 'firestore-lite'; + this._persistenceKey = '(lite)'; + this._settings = new FirestoreSettingsImpl({}); + this._settingsFrozen = false; + this._emulatorOptions = {}; + // A task that is assigned when the terminate() is invoked and resolved when + // all components have shut down. Otherwise, Firestore is not terminated, + // which can mean either the FirestoreClient is in the process of starting, + // or restarting. + this._terminateTask = 'notTerminated'; + } + /** + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service + * instance. + */ + get app() { + if (!this._app) { + throw new FirestoreError(Code.FAILED_PRECONDITION, "Firestore was not initialized using the Firebase SDK. 'app' is " + + 'not available'); + } + return this._app; + } + get _initialized() { + return this._settingsFrozen; + } + get _terminated() { + return this._terminateTask !== 'notTerminated'; + } + _setSettings(settings) { + if (this._settingsFrozen) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore has already been started and its settings can no longer ' + + 'be changed. You can only modify settings before calling any other ' + + 'methods on a Firestore object.'); + } + this._settings = new FirestoreSettingsImpl(settings); + this._emulatorOptions = settings.emulatorOptions || {}; + if (settings.credentials !== undefined) { + this._authCredentials = makeAuthCredentialsProvider(settings.credentials); + } + } + _getSettings() { + return this._settings; + } + _getEmulatorOptions() { + return this._emulatorOptions; + } + _freezeSettings() { + this._settingsFrozen = true; + return this._settings; + } + _delete() { + // The `_terminateTask` must be assigned future that completes when + // terminate is complete. The existence of this future puts SDK in state + // that will not accept further API interaction. + if (this._terminateTask === 'notTerminated') { + this._terminateTask = this._terminate(); + } + return this._terminateTask; + } + async _restart() { + // The `_terminateTask` must equal 'notTerminated' after restart to + // signal that client is in a state that accepts API calls. + if (this._terminateTask === 'notTerminated') { + await this._terminate(); + } + else { + this._terminateTask = 'notTerminated'; + } + } + /** Returns a JSON-serializable representation of this `Firestore` instance. */ + toJSON() { + return { + app: this._app, + databaseId: this._databaseId, + settings: this._settings + }; + } + /** + * Terminates all components used by this client. Subclasses can override + * this method to clean up their own dependencies, but must also call this + * method. + * + * Only ever called once. + */ + _terminate() { + removeComponents(this); + return Promise.resolve(); + } +} +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ +function connectFirestoreEmulator(firestore, host, port, options = {}) { + firestore = cast(firestore, Firestore$1); + const useSsl = isCloudWorkstation(host); + const settings = firestore._getSettings(); + const existingConfig = { + ...settings, + emulatorOptions: firestore._getEmulatorOptions() + }; + const newHostSetting = `${host}:${port}`; + if (useSsl) { + void pingServer(`https://${newHostSetting}`); + updateEmulatorBanner('Firestore', true); + } + if (settings.host !== DEFAULT_HOST && settings.host !== newHostSetting) { + logWarn('Host has been set in both settings() and connectFirestoreEmulator(), emulator host ' + + 'will be used.'); + } + const newConfig = { + ...settings, + host: newHostSetting, + ssl: useSsl, + emulatorOptions: options + }; + // No-op if the new configuration matches the current configuration. This supports SSR + // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice. + if (deepEqual(newConfig, existingConfig)) { + return; + } + firestore._setSettings(newConfig); + if (options.mockUserToken) { + let token; + let user; + if (typeof options.mockUserToken === 'string') { + token = options.mockUserToken; + user = User.MOCK_USER; + } + else { + // Let createMockUserToken validate first (catches common mistakes like + // invalid field "uid" and missing field "sub" / "user_id".) + token = createMockUserToken(options.mockUserToken, firestore._app?.options.projectId); + const uid = options.mockUserToken.sub || options.mockUserToken.user_id; + if (!uid) { + throw new FirestoreError(Code.INVALID_ARGUMENT, "mockUserToken must contain 'sub' or 'user_id' field!"); + } + user = new User(uid); + } + firestore._authCredentials = new EmulatorAuthCredentialsProvider(new OAuthToken(token, user)); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `Query` refers to a query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ +class Query { + // This is the lite version of the Query class in the main SDK. + /** @hideconstructor protected */ + constructor(firestore, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter, _query) { + this.converter = converter; + this._query = _query; + /** The type of this Firestore reference. */ + this.type = 'query'; + this.firestore = firestore; + } + withConverter(converter) { + return new Query(this.firestore, converter, this._query); + } +} +/** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. + */ +class DocumentReference { + /** @hideconstructor */ + constructor(firestore, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter, _key) { + this.converter = converter; + this._key = _key; + /** The type of this Firestore reference. */ + this.type = 'document'; + this.firestore = firestore; + } + get _path() { + return this._key.path; + } + /** + * The document's identifier within its collection. + */ + get id() { + return this._key.path.lastSegment(); + } + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ + get path() { + return this._key.path.canonicalString(); + } + /** + * The collection this `DocumentReference` belongs to. + */ + get parent() { + return new CollectionReference(this.firestore, this.converter, this._key.path.popLast()); + } + withConverter(converter) { + return new DocumentReference(this.firestore, converter, this._key); + } + /** + * Returns a JSON-serializable representation of this `DocumentReference` instance. + * + * @returns a JSON representation of this object. + */ + toJSON() { + return { + type: DocumentReference._jsonSchemaVersion, + referencePath: this._key.toString() + }; + } + static fromJSON(firestore, json, converter) { + if (validateJSON(json, DocumentReference._jsonSchema)) { + return new DocumentReference(firestore, converter ? converter : null, new DocumentKey(ResourcePath.fromString(json.referencePath))); + } + } +} +DocumentReference._jsonSchemaVersion = 'firestore/documentReference/1.0'; +DocumentReference._jsonSchema = { + type: property('string', DocumentReference._jsonSchemaVersion), + referencePath: property('string') +}; +/** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using {@link (query:1)}). + */ +class CollectionReference extends Query { + /** @hideconstructor */ + constructor(firestore, converter, _path) { + super(firestore, converter, newQueryForPath(_path)); + this._path = _path; + /** The type of this Firestore reference. */ + this.type = 'collection'; + } + /** The collection's identifier. */ + get id() { + return this._query.path.lastSegment(); + } + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ + get path() { + return this._query.path.canonicalString(); + } + /** + * A reference to the containing `DocumentReference` if this is a + * subcollection. If this isn't a subcollection, the reference is null. + */ + get parent() { + const parentPath = this._path.popLast(); + if (parentPath.isEmpty()) { + return null; + } + else { + return new DocumentReference(this.firestore, + /* converter= */ null, new DocumentKey(parentPath)); + } + } + withConverter(converter) { + return new CollectionReference(this.firestore, converter, this._path); + } +} +function collection(parent, path, ...pathSegments) { + parent = getModularInstance(parent); + validateNonEmptyArgument('collection', 'path', path); + if (parent instanceof Firestore$1) { + const absolutePath = ResourcePath.fromString(path, ...pathSegments); + validateCollectionPath(absolutePath); + return new CollectionReference(parent, /* converter= */ null, absolutePath); + } + else { + if (!(parent instanceof DocumentReference) && + !(parent instanceof CollectionReference)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Expected first argument to collection() to be a CollectionReference, ' + + 'a DocumentReference or FirebaseFirestore'); + } + const absolutePath = parent._path.child(ResourcePath.fromString(path, ...pathSegments)); + validateCollectionPath(absolutePath); + return new CollectionReference(parent.firestore, + /* converter= */ null, absolutePath); + } +} +// TODO(firestorelite): Consider using ErrorFactory - +// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106 +/** + * Creates and returns a new `Query` instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given `collectionId`. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param collectionId - Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `Query`. + */ +function collectionGroup(firestore, collectionId) { + firestore = cast(firestore, Firestore$1); + validateNonEmptyArgument('collectionGroup', 'collection id', collectionId); + if (collectionId.indexOf('/') >= 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid collection ID '${collectionId}' passed to function ` + + `collectionGroup(). Collection IDs must not contain '/'.`); + } + return new Query(firestore, + /* converter= */ null, newQueryForCollectionGroup(collectionId)); +} +function doc(parent, path, ...pathSegments) { + parent = getModularInstance(parent); + // We allow omission of 'pathString' but explicitly prohibit passing in both + // 'undefined' and 'null'. + if (arguments.length === 1) { + path = AutoId.newId(); + } + validateNonEmptyArgument('doc', 'path', path); + if (parent instanceof Firestore$1) { + const absolutePath = ResourcePath.fromString(path, ...pathSegments); + validateDocumentPath(absolutePath); + return new DocumentReference(parent, + /* converter= */ null, new DocumentKey(absolutePath)); + } + else { + if (!(parent instanceof DocumentReference) && + !(parent instanceof CollectionReference)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Expected first argument to collection() to be a CollectionReference, ' + + 'a DocumentReference or FirebaseFirestore'); + } + const absolutePath = parent._path.child(ResourcePath.fromString(path, ...pathSegments)); + validateDocumentPath(absolutePath); + return new DocumentReference(parent.firestore, parent instanceof CollectionReference ? parent.converter : null, new DocumentKey(absolutePath)); + } +} +/** + * Returns true if the provided references are equal. + * + * @param left - A reference to compare. + * @param right - A reference to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +function refEqual(left, right) { + left = getModularInstance(left); + right = getModularInstance(right); + if ((left instanceof DocumentReference || + left instanceof CollectionReference) && + (right instanceof DocumentReference || right instanceof CollectionReference)) { + return (left.firestore === right.firestore && + left.path === right.path && + left.converter === right.converter); + } + return false; +} +/** + * Returns true if the provided queries point to the same collection and apply + * the same constraints. + * + * @param left - A `Query` to compare. + * @param right - A `Query` to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +function queryEqual(left, right) { + left = getModularInstance(left); + right = getModularInstance(right); + if (left instanceof Query && right instanceof Query) { + return (left.firestore === right.firestore && + queryEquals(left._query, right._query) && + left.converter === right.converter); + } + return false; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG = 'AsyncQueue'; +class AsyncQueueImpl { + constructor(tail = Promise.resolve()) { + // A list of retryable operations. Retryable operations are run in order and + // retried with backoff. + this.retryableOps = []; + // Is this AsyncQueue being shut down? Once it is set to true, it will not + // be changed again. + this._isShuttingDown = false; + // Operations scheduled to be queued in the future. Operations are + // automatically removed after they are run or canceled. + this.delayedOperations = []; + // visible for testing + this.failure = null; + // Flag set while there's an outstanding AsyncQueue operation, used for + // assertion sanity-checks. + this.operationInProgress = false; + // Enabled during shutdown on Safari to prevent future access to IndexedDB. + this.skipNonRestrictedTasks = false; + // List of TimerIds to fast-forward delays for. + this.timerIdsToSkip = []; + // Backoff timer used to schedule retries for retryable operations + this.backoff = new ExponentialBackoff(this, "async_queue_retry" /* TimerId.AsyncQueueRetry */); + // Visibility handler that triggers an immediate retry of all retryable + // operations. Meant to speed up recovery when we regain file system access + // after page comes into foreground. + this.visibilityHandler = () => { + this.backoff.skipBackoff(); + }; + this.tail = tail; + } + get isShuttingDown() { + return this._isShuttingDown; + } + /** + * Adds a new operation to the queue without waiting for it to complete (i.e. + * we ignore the Promise result). + */ + enqueueAndForget(op) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.enqueue(op); + } + enqueueAndForgetEvenWhileRestricted(op) { + this.verifyNotFailed(); + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.enqueueInternal(op); + } + enterRestrictedMode(purgeExistingTasks) { + if (!this._isShuttingDown) { + this._isShuttingDown = true; + this.skipNonRestrictedTasks = purgeExistingTasks || false; + } + } + enqueue(op) { + this.verifyNotFailed(); + if (this._isShuttingDown) { + // Return a Promise which never resolves. + return new Promise(() => { }); + } + // Create a deferred Promise that we can return to the callee. This + // allows us to return a "hanging Promise" only to the callee and still + // advance the queue even when the operation is not run. + const task = new Deferred(); + return this.enqueueInternal(() => { + if (this._isShuttingDown && this.skipNonRestrictedTasks) { + // We do not resolve 'task' + return Promise.resolve(); + } + op().then(task.resolve, task.reject); + return task.promise; + }).then(() => task.promise); + } + enqueueRetryable(op) { + this.enqueueAndForget(() => { + this.retryableOps.push(op); + return this.retryNextOp(); + }); + } + /** + * Runs the next operation from the retryable queue. If the operation fails, + * reschedules with backoff. + */ + async retryNextOp() { + if (this.retryableOps.length === 0) { + return; + } + try { + await this.retryableOps[0](); + this.retryableOps.shift(); + this.backoff.reset(); + } + catch (e) { + if (isIndexedDbTransactionError(e)) { + logDebug(LOG_TAG, 'Operation failed with retryable error: ' + e); + } + else { + throw e; // Failure will be handled by AsyncQueue + } + } + if (this.retryableOps.length > 0) { + // If there are additional operations, we re-schedule `retryNextOp()`. + // This is necessary to run retryable operations that failed during + // their initial attempt since we don't know whether they are already + // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1` + // needs to be re-run, we will run `op1`, `op1`, `op2` using the + // already enqueued calls to `retryNextOp()`. `op3()` will then run in the + // call scheduled here. + // Since `backoffAndRun()` cancels an existing backoff and schedules a + // new backoff on every call, there is only ever a single additional + // operation in the queue. + this.backoff.backoffAndRun(() => this.retryNextOp()); + } + } + enqueueInternal(op) { + const newTail = this.tail.then(() => { + this.operationInProgress = true; + return op() + .catch((error) => { + this.failure = error; + this.operationInProgress = false; + const message = getMessageOrStack(error); + logError('INTERNAL UNHANDLED ERROR: ', message); + // Re-throw the error so that this.tail becomes a rejected Promise and + // all further attempts to chain (via .then) will just short-circuit + // and return the rejected Promise. + throw error; + }) + .then(result => { + this.operationInProgress = false; + return result; + }); + }); + this.tail = newTail; + return newTail; + } + enqueueAfterDelay(timerId, delayMs, op) { + this.verifyNotFailed(); + // Fast-forward delays for timerIds that have been overridden. + if (this.timerIdsToSkip.indexOf(timerId) > -1) { + delayMs = 0; + } + const delayedOp = DelayedOperation.createAndSchedule(this, timerId, delayMs, op, removedOp => this.removeDelayedOperation(removedOp)); + this.delayedOperations.push(delayedOp); + return delayedOp; + } + verifyNotFailed() { + if (this.failure) { + fail(0xb815, { + messageOrStack: getMessageOrStack(this.failure) + }); + } + } + verifyOperationInProgress() { + } + /** + * Waits until all currently queued tasks are finished executing. Delayed + * operations are not run. + */ + async drain() { + // Operations in the queue prior to draining may have enqueued additional + // operations. Keep draining the queue until the tail is no longer advanced, + // which indicates that no more new operations were enqueued and that all + // operations were executed. + let currentTail; + do { + currentTail = this.tail; + await currentTail; + } while (currentTail !== this.tail); + } + /** + * For Tests: Determine if a delayed operation with a particular TimerId + * exists. + */ + containsDelayedOperation(timerId) { + for (const op of this.delayedOperations) { + if (op.timerId === timerId) { + return true; + } + } + return false; + } + /** + * For Tests: Runs some or all delayed operations early. + * + * @param lastTimerId - Delayed operations up to and including this TimerId + * will be drained. Pass TimerId.All to run all delayed operations. + * @returns a Promise that resolves once all operations have been run. + */ + runAllDelayedOperationsUntil(lastTimerId) { + // Note that draining may generate more delayed ops, so we do that first. + return this.drain().then(() => { + // Run ops in the same order they'd run if they ran naturally. + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ + this.delayedOperations.sort((a, b) => a.targetTimeMs - b.targetTimeMs); + for (const op of this.delayedOperations) { + op.skipDelay(); + if (lastTimerId !== "all" /* TimerId.All */ && op.timerId === lastTimerId) { + break; + } + } + return this.drain(); + }); + } + /** + * For Tests: Skip all subsequent delays for a timer id. + */ + skipDelaysForTimerId(timerId) { + this.timerIdsToSkip.push(timerId); + } + /** Called once a DelayedOperation is run or canceled. */ + removeDelayedOperation(op) { + // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small. + const index = this.delayedOperations.indexOf(op); + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ + this.delayedOperations.splice(index, 1); + } +} +/** + * Chrome includes Error.message in Error.stack. Other browsers do not. + * This returns expected output of message + stack when available. + * @param error - Error or FirestoreError + */ +function getMessageOrStack(error) { + let message = error.message || ''; + if (error.stack) { + if (error.stack.includes(error.message)) { + message = error.stack; + } + else { + message = error.message + '\n' + error.stack; + } + } + return message; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents the task of loading a Firestore bundle. It provides progress of bundle + * loading, as well as task completion and error events. + * + * The API is compatible with `Promise`. + */ +class LoadBundleTask { + constructor() { + this._progressObserver = {}; + this._taskCompletionResolver = new Deferred(); + this._lastProgress = { + taskState: 'Running', + totalBytes: 0, + totalDocuments: 0, + bytesLoaded: 0, + documentsLoaded: 0 + }; + } + /** + * Registers functions to listen to bundle loading progress events. + * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur + * each time a Firestore document is loaded from the bundle. + * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the + * error, and there should be no more updates after this. + * @param complete - Called when the loading task is complete. + */ + onProgress(next, error, complete) { + this._progressObserver = { + next, + error, + complete + }; + } + /** + * Implements the `Promise.catch` interface. + * + * @param onRejected - Called when an error occurs during bundle loading. + */ + catch(onRejected) { + return this._taskCompletionResolver.promise.catch(onRejected); + } + /** + * Implements the `Promise.then` interface. + * + * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update. + * The update will always have its `taskState` set to `"Success"`. + * @param onRejected - Called when an error occurs during bundle loading. + */ + then(onFulfilled, onRejected) { + return this._taskCompletionResolver.promise.then(onFulfilled, onRejected); + } + /** + * Notifies all observers that bundle loading has completed, with a provided + * `LoadBundleTaskProgress` object. + * + * @private + */ + _completeWith(progress) { + this._updateProgress(progress); + if (this._progressObserver.complete) { + this._progressObserver.complete(); + } + this._taskCompletionResolver.resolve(progress); + } + /** + * Notifies all observers that bundle loading has failed, with a provided + * `Error` as the reason. + * + * @private + */ + _failWith(error) { + this._lastProgress.taskState = 'Error'; + if (this._progressObserver.next) { + this._progressObserver.next(this._lastProgress); + } + if (this._progressObserver.error) { + this._progressObserver.error(error); + } + this._taskCompletionResolver.reject(error); + } + /** + * Notifies a progress update of loading a bundle. + * @param progress - The new progress. + * + * @private + */ + _updateProgress(progress) { + this._lastProgress = progress; + if (this._progressObserver.next) { + this._progressObserver.next(progress); + } + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Constant used to indicate the LRU garbage collection should be disabled. + * Set this value as the `cacheSizeBytes` on the settings passed to the + * {@link Firestore} instance. + */ +const CACHE_SIZE_UNLIMITED = LRU_COLLECTION_DISABLED; +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ +class Firestore extends Firestore$1 { + /** @hideconstructor */ + constructor(authCredentialsProvider, appCheckCredentialsProvider, databaseId, app) { + super(authCredentialsProvider, appCheckCredentialsProvider, databaseId, app); + /** + * Whether it's a {@link Firestore} or Firestore Lite instance. + */ + this.type = 'firestore'; + this._queue = new AsyncQueueImpl(); + this._persistenceKey = app?.name || '[DEFAULT]'; + } + async _terminate() { + if (this._firestoreClient) { + const terminate = this._firestoreClient.terminate(); + this._queue = new AsyncQueueImpl(terminate); + this._firestoreClient = undefined; + await terminate; + } + } +} +/** + * Initializes a new instance of {@link Firestore} with the provided settings. + * Can only be called before any other function, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will + * be associated. + * @param settings - A settings object to configure the {@link Firestore} instance. + * @param databaseId - The name of the database. + * @returns A newly initialized {@link Firestore} instance. + */ +function initializeFirestore(app, settings, databaseId) { + if (!databaseId) { + databaseId = DEFAULT_DATABASE_NAME; + } + const provider = _getProvider(app, 'firestore'); + if (provider.isInitialized(databaseId)) { + const existingInstance = provider.getImmediate({ + identifier: databaseId + }); + const initialSettings = provider.getOptions(databaseId); + if (deepEqual(initialSettings, settings)) { + return existingInstance; + } + else { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'initializeFirestore() has already been called with ' + + 'different options. To avoid this error, call initializeFirestore() with the ' + + 'same options as when it was originally called, or call getFirestore() to return the' + + ' already initialized instance.'); + } + } + if (settings.cacheSizeBytes !== undefined && + settings.localCache !== undefined) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes will` + + `be deprecated. Instead, specify the cache size in the cache object`); + } + if (settings.cacheSizeBytes !== undefined && + settings.cacheSizeBytes !== CACHE_SIZE_UNLIMITED && + settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`); + } + // Workaround to get cookies in Firebase Studio + if (settings.host && isCloudWorkstation(settings.host)) { + void pingServer(settings.host); + } + return provider.initialize({ + options: settings, + instanceIdentifier: databaseId + }); +} +function getFirestore(appOrDatabaseId, optionalDatabaseId) { + const app = typeof appOrDatabaseId === 'object' ? appOrDatabaseId : getApp(); + const databaseId = typeof appOrDatabaseId === 'string' + ? appOrDatabaseId + : optionalDatabaseId || DEFAULT_DATABASE_NAME; + const db = _getProvider(app, 'firestore').getImmediate({ + identifier: databaseId + }); + if (!db._initialized) { + const emulator = getDefaultEmulatorHostnameAndPort('firestore'); + if (emulator) { + connectFirestoreEmulator(db, ...emulator); + } + } + return db; +} +/** + * @internal + */ +function ensureFirestoreConfigured(firestore) { + if (firestore._terminated) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'The client has already been terminated.'); + } + if (!firestore._firestoreClient) { + configureFirestore(firestore); + } + return firestore._firestoreClient; +} +function configureFirestore(firestore) { + const settings = firestore._freezeSettings(); + const databaseInfo = makeDatabaseInfo(firestore._databaseId, firestore._app?.options.appId || '', firestore._persistenceKey, settings); + if (!firestore._componentsProvider) { + if (settings.localCache?._offlineComponentProvider && + settings.localCache?._onlineComponentProvider) { + firestore._componentsProvider = { + _offline: settings.localCache._offlineComponentProvider, + _online: settings.localCache._onlineComponentProvider + }; + } + } + firestore._firestoreClient = new FirestoreClient(firestore._authCredentials, firestore._appCheckCredentials, firestore._queue, databaseInfo, firestore._componentsProvider && + buildComponentProvider(firestore._componentsProvider)); +} +function buildComponentProvider(componentsProvider) { + const online = componentsProvider?._online.build(); + return { + _offline: componentsProvider?._offline.build(online), + _online: online + }; +} +/** + * Attempts to enable persistent storage, if possible. + * + * On failure, `enableIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. + * + * * failed-precondition: The app is already open in another browser tab. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. + * + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. + * + * Note: `enableIndexedDbPersistence()` must be called before any other functions + * (other than {@link initializeFirestore}, {@link (getFirestore:1)} or + * {@link clearIndexedDbPersistence}. + * + * Persistence cannot be used in a Node.js environment. + * + * @param firestore - The {@link Firestore} instance to enable persistence for. + * @param persistenceSettings - Optional settings object to configure + * persistence. + * @returns A `Promise` that represents successfully enabling persistent storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on IndexedDb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. + */ +function enableIndexedDbPersistence(firestore, persistenceSettings) { + logWarn('enableIndexedDbPersistence() will be deprecated in the future, ' + + 'you can use `FirestoreSettings.cache` instead.'); + const settings = firestore._freezeSettings(); + setPersistenceProviders(firestore, OnlineComponentProvider.provider, { + build: (onlineComponents) => new IndexedDbOfflineComponentProvider(onlineComponents, settings.cacheSizeBytes, persistenceSettings?.forceOwnership) + }); + return Promise.resolve(); +} +/** + * Attempts to enable multi-tab persistent storage, if possible. If enabled + * across all tabs, all operations share access to local persistence, including + * shared execution of queries and latency-compensated local document updates + * across all connected instances. + * + * On failure, `enableMultiTabIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. + * + * * failed-precondition: The app is already open in another browser tab and + * multi-tab is not enabled. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. + * + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. + * + * @param firestore - The {@link Firestore} instance to enable persistence for. + * @returns A `Promise` that represents successfully enabling persistent + * storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on indexeddb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. + */ +async function enableMultiTabIndexedDbPersistence(firestore) { + logWarn('enableMultiTabIndexedDbPersistence() will be deprecated in the future, ' + + 'you can use `FirestoreSettings.cache` instead.'); + const settings = firestore._freezeSettings(); + setPersistenceProviders(firestore, OnlineComponentProvider.provider, { + build: (onlineComponents) => new MultiTabOfflineComponentProvider(onlineComponents, settings.cacheSizeBytes) + }); +} +/** + * Registers both the `OfflineComponentProvider` and `OnlineComponentProvider`. + * If the operation fails with a recoverable error (see + * `canRecoverFromIndexedDbError()` below), the returned Promise is rejected + * but the client remains usable. + */ +function setPersistenceProviders(firestore, onlineComponentProvider, offlineComponentProvider) { + firestore = cast(firestore, Firestore); + if (firestore._firestoreClient || firestore._terminated) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore has already been started and persistence can no longer be ' + + 'enabled. You can only enable persistence before calling any other ' + + 'methods on a Firestore object.'); + } + if (firestore._componentsProvider || firestore._getSettings().localCache) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'SDK cache is already specified.'); + } + firestore._componentsProvider = { + _online: onlineComponentProvider, + _offline: offlineComponentProvider + }; + configureFirestore(firestore); +} +/** + * Clears the persistent storage. This includes pending writes and cached + * documents. + * + * Must be called while the {@link Firestore} instance is not started (after the app is + * terminated or when the app is first initialized). On startup, this function + * must be called before other functions (other than {@link + * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore} + * instance is still running, the promise will be rejected with the error code + * of `failed-precondition`. + * + * Note: `clearIndexedDbPersistence()` is primarily intended to help write + * reliable tests that use Cloud Firestore. It uses an efficient mechanism for + * dropping existing data but does not attempt to securely overwrite or + * otherwise make cached data unrecoverable. For applications that are sensitive + * to the disclosure of cached data in between user sessions, we strongly + * recommend not enabling persistence at all. + * + * @param firestore - The {@link Firestore} instance to clear persistence for. + * @returns A `Promise` that is resolved when the persistent storage is + * cleared. Otherwise, the promise is rejected with an error. + */ +function clearIndexedDbPersistence(firestore) { + if (firestore._initialized && !firestore._terminated) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'Persistence can only be cleared before a Firestore instance is ' + + 'initialized or after it is terminated.'); + } + const deferred = new Deferred(); + firestore._queue.enqueueAndForgetEvenWhileRestricted(async () => { + try { + await indexedDbClearPersistence(indexedDbStoragePrefix(firestore._databaseId, firestore._persistenceKey)); + deferred.resolve(); + } + catch (e) { + deferred.reject(e); + } + }); + return deferred.promise; +} +/** + * Waits until all currently pending writes for the active user have been + * acknowledged by the backend. + * + * The returned promise resolves immediately if there are no outstanding writes. + * Otherwise, the promise waits for all previously issued writes (including + * those written in a previous app session), but it does not wait for writes + * that were added after the function is called. If you want to wait for + * additional writes, call `waitForPendingWrites()` again. + * + * Any outstanding `waitForPendingWrites()` promises are rejected during user + * changes. + * + * @returns A `Promise` which resolves when all currently pending writes have been + * acknowledged by the backend. + */ +function waitForPendingWrites(firestore) { + firestore = cast(firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + return firestoreClientWaitForPendingWrites(client); +} +/** + * Re-enables use of the network for this {@link Firestore} instance after a prior + * call to {@link disableNetwork}. + * + * @returns A `Promise` that is resolved once the network has been enabled. + */ +function enableNetwork(firestore) { + firestore = cast(firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + return firestoreClientEnableNetwork(client); +} +/** + * Disables network usage for this instance. It can be re-enabled via {@link + * enableNetwork}. While the network is disabled, any snapshot listeners, + * `getDoc()` or `getDocs()` calls will return results from cache, and any write + * operations will be queued until the network is restored. + * + * @returns A `Promise` that is resolved once the network has been disabled. + */ +function disableNetwork(firestore) { + firestore = cast(firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + return firestoreClientDisableNetwork(client); +} +/** + * Terminates the provided {@link Firestore} instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` function + * may be used. Any other function will throw a `FirestoreError`. + * + * To restart after termination, create a new instance of FirebaseFirestore with + * {@link (getFirestore:1)}. + * + * Termination does not cancel any pending writes, and any promises that are + * awaiting a response from the server will not be resolved. If you have + * persistence enabled, the next time you start this instance, it will resume + * sending these writes to the server. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all + * of its resources or in combination with `clearIndexedDbPersistence()` to + * ensure that all local state is destroyed between test runs. + * + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ +function terminate(firestore) { + _removeServiceInstance(firestore.app, 'firestore', firestore._databaseId.database); + return firestore._delete(); +} +/** + * Loads a Firestore bundle into the local cache. + * + * @param firestore - The {@link Firestore} instance to load bundles for. + * @param bundleData - An object representing the bundle to be loaded. Valid + * objects are `ArrayBuffer`, `ReadableStream` or `string`. + * + * @returns A `LoadBundleTask` object, which notifies callers with progress + * updates, and completion or error events. It can be used as a + * `Promise`. + */ +function loadBundle(firestore, bundleData) { + firestore = cast(firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + const resultTask = new LoadBundleTask(); + firestoreClientLoadBundle(client, firestore._databaseId, bundleData, resultTask); + return resultTask; +} +/** + * Reads a Firestore {@link Query} from local cache, identified by the given + * name. + * + * The named queries are packaged into bundles on the server side (along + * with resulting documents), and loaded to local cache using `loadBundle`. Once + * in local cache, use this method to extract a {@link Query} by name. + * + * @param firestore - The {@link Firestore} instance to read the query from. + * @param name - The name of the query. + * @returns A `Promise` that is resolved with the Query or `null`. + */ +function namedQuery(firestore, name) { + firestore = cast(firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + return firestoreClientGetNamedQuery(client, name).then(namedQuery => { + if (!namedQuery) { + return null; + } + return new Query(firestore, null, namedQuery.query); + }); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function registerFirestore(variant, useFetchStreams = true) { + setSDKVersion(SDK_VERSION$1); + _registerComponent(new Component('firestore', (container, { instanceIdentifier: databaseId, options: settings }) => { + const app = container.getProvider('app').getImmediate(); + const firestoreInstance = new Firestore(new FirebaseAuthCredentialsProvider(container.getProvider('auth-internal')), new FirebaseAppCheckTokenProvider(app, container.getProvider('app-check-internal')), databaseIdFromApp(app, databaseId), app); + settings = { useFetchStreams, ...settings }; + firestoreInstance._setSettings(settings); + return firestoreInstance; + }, 'PUBLIC').setMultipleInstances(true)); + registerVersion(name$1, version$1, variant); + // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation + registerVersion(name$1, version$1, 'esm2020'); +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Concrete implementation of the Aggregate type. + */ +class AggregateImpl { + constructor(alias, aggregateType, fieldPath) { + this.alias = alias; + this.aggregateType = aggregateType; + this.fieldPath = fieldPath; + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents an aggregation that can be performed by Firestore. + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +class AggregateField { + /** + * Create a new AggregateField + * @param aggregateType Specifies the type of aggregation operation to perform. + * @param _internalFieldPath Optionally specifies the field that is aggregated. + * @internal + */ + constructor(aggregateType = 'count', _internalFieldPath) { + this._internalFieldPath = _internalFieldPath; + /** A type string to uniquely identify instances of this class. */ + this.type = 'AggregateField'; + this.aggregateType = aggregateType; + } +} +/** + * The results of executing an aggregation query. + */ +class AggregateQuerySnapshot { + /** @hideconstructor */ + constructor(query, _userDataWriter, _data) { + this._userDataWriter = _userDataWriter; + this._data = _data; + /** A type string to uniquely identify instances of this class. */ + this.type = 'AggregateQuerySnapshot'; + this.query = query; + } + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ + data() { + return this._userDataWriter.convertObjectMap(this._data); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing an array of bytes. + */ +class Bytes { + /** @hideconstructor */ + constructor(byteString) { + this._byteString = byteString; + } + /** + * Creates a new `Bytes` object from the given Base64 string, converting it to + * bytes. + * + * @param base64 - The Base64 string used to create the `Bytes` object. + */ + static fromBase64String(base64) { + try { + return new Bytes(ByteString.fromBase64String(base64)); + } + catch (e) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Failed to construct data from Base64 string: ' + e); + } + } + /** + * Creates a new `Bytes` object from the given Uint8Array. + * + * @param array - The Uint8Array used to create the `Bytes` object. + */ + static fromUint8Array(array) { + return new Bytes(ByteString.fromUint8Array(array)); + } + /** + * Returns the underlying bytes as a Base64-encoded string. + * + * @returns The Base64-encoded string created from the `Bytes` object. + */ + toBase64() { + return this._byteString.toBase64(); + } + /** + * Returns the underlying bytes in a new `Uint8Array`. + * + * @returns The Uint8Array created from the `Bytes` object. + */ + toUint8Array() { + return this._byteString.toUint8Array(); + } + /** + * Returns a string representation of the `Bytes` object. + * + * @returns A string representation of the `Bytes` object. + */ + toString() { + return 'Bytes(base64: ' + this.toBase64() + ')'; + } + /** + * Returns true if this `Bytes` object is equal to the provided one. + * + * @param other - The `Bytes` object to compare against. + * @returns true if this `Bytes` object is equal to the provided one. + */ + isEqual(other) { + return this._byteString.isEqual(other._byteString); + } + /** + * Returns a JSON-serializable representation of this `Bytes` instance. + * + * @returns a JSON representation of this object. + */ + toJSON() { + return { + type: Bytes._jsonSchemaVersion, + bytes: this.toBase64() + }; + } + /** + * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}. + * + * @param json a JSON object represention of a `Bytes` instance + * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json) { + if (validateJSON(json, Bytes._jsonSchema)) { + return Bytes.fromBase64String(json.bytes); + } + } +} +Bytes._jsonSchemaVersion = 'firestore/bytes/1.0'; +Bytes._jsonSchema = { + type: property('string', Bytes._jsonSchemaVersion), + bytes: property('string') +}; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `FieldPath` refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + * + * Create a `FieldPath` by providing field names. If more than one field + * name is provided, the path will point to a nested field in a document. + */ +class FieldPath { + /** + * Creates a `FieldPath` from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames - A list of field names. + */ + constructor(...fieldNames) { + for (let i = 0; i < fieldNames.length; ++i) { + if (fieldNames[i].length === 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid field name at argument $(i + 1). ` + + 'Field names must not be empty.'); + } + } + this._internalPath = new FieldPath$1(fieldNames); + } + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other - The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ + isEqual(other) { + return this._internalPath.isEqual(other._internalPath); + } +} +/** + * Returns a special sentinel `FieldPath` to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ +function documentId() { + return new FieldPath(DOCUMENT_KEY_NAME); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Sentinel values that can be used when writing document fields with `set()` + * or `update()`. + */ +class FieldValue { + /** + * @param _methodName - The public API endpoint that returns this class. + * @hideconstructor + */ + constructor(_methodName) { + this._methodName = _methodName; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ +class GeoPoint { + /** + * Creates a new immutable `GeoPoint` object with the provided latitude and + * longitude values. + * @param latitude - The latitude as number between -90 and 90. + * @param longitude - The longitude as number between -180 and 180. + */ + constructor(latitude, longitude) { + if (!isFinite(latitude) || latitude < -90 || latitude > 90) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Latitude must be a number between -90 and 90, but was: ' + latitude); + } + if (!isFinite(longitude) || longitude < -180 || longitude > 180) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Longitude must be a number between -180 and 180, but was: ' + longitude); + } + this._lat = latitude; + this._long = longitude; + } + /** + * The latitude of this `GeoPoint` instance. + */ + get latitude() { + return this._lat; + } + /** + * The longitude of this `GeoPoint` instance. + */ + get longitude() { + return this._long; + } + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other - The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ + isEqual(other) { + return this._lat === other._lat && this._long === other._long; + } + /** + * Actually private to JS consumers of our API, so this function is prefixed + * with an underscore. + */ + _compareTo(other) { + return (primitiveComparator(this._lat, other._lat) || + primitiveComparator(this._long, other._long)); + } + /** + * Returns a JSON-serializable representation of this `GeoPoint` instance. + * + * @returns a JSON representation of this object. + */ + toJSON() { + return { + latitude: this._lat, + longitude: this._long, + type: GeoPoint._jsonSchemaVersion + }; + } + /** + * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}. + * + * @param json a JSON object represention of a `GeoPoint` instance + * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json) { + if (validateJSON(json, GeoPoint._jsonSchema)) { + return new GeoPoint(json.latitude, json.longitude); + } + } +} +GeoPoint._jsonSchemaVersion = 'firestore/geoPoint/1.0'; +GeoPoint._jsonSchema = { + type: property('string', GeoPoint._jsonSchemaVersion), + latitude: property('number'), + longitude: property('number') +}; + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link vector}. + * + * @class VectorValue + */ +class VectorValue { + /** + * @private + * @internal + */ + constructor(values) { + // Making a copy of the parameter. + this._values = (values || []).map(n => n); + } + /** + * Returns a copy of the raw number array form of the vector. + */ + toArray() { + return this._values.map(n => n); + } + /** + * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise. + */ + isEqual(other) { + return isPrimitiveArrayEqual(this._values, other._values); + } + /** + * Returns a JSON-serializable representation of this `VectorValue` instance. + * + * @returns a JSON representation of this object. + */ + toJSON() { + return { + type: VectorValue._jsonSchemaVersion, + vectorValues: this._values + }; + } + /** + * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}. + * + * @param json a JSON object represention of a `VectorValue` instance. + * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json) { + if (validateJSON(json, VectorValue._jsonSchema)) { + if (Array.isArray(json.vectorValues) && + json.vectorValues.every(element => typeof element === 'number')) { + return new VectorValue(json.vectorValues); + } + throw new FirestoreError(Code.INVALID_ARGUMENT, "Expected 'vectorValues' field to be a number array"); + } + } +} +VectorValue._jsonSchemaVersion = 'firestore/vectorValue/1.0'; +VectorValue._jsonSchema = { + type: property('string', VectorValue._jsonSchemaVersion), + vectorValues: property('object') +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const RESERVED_FIELD_REGEX = /^__.*__$/; +/** The result of parsing document data (e.g. for a setData call). */ +class ParsedSetData { + constructor(data, fieldMask, fieldTransforms) { + this.data = data; + this.fieldMask = fieldMask; + this.fieldTransforms = fieldTransforms; + } + toMutation(key, precondition) { + if (this.fieldMask !== null) { + return new PatchMutation(key, this.data, this.fieldMask, precondition, this.fieldTransforms); + } + else { + return new SetMutation(key, this.data, precondition, this.fieldTransforms); + } + } +} +/** The result of parsing "update" data (i.e. for an updateData call). */ +class ParsedUpdateData { + constructor(data, + // The fieldMask does not include document transforms. + fieldMask, fieldTransforms) { + this.data = data; + this.fieldMask = fieldMask; + this.fieldTransforms = fieldTransforms; + } + toMutation(key, precondition) { + return new PatchMutation(key, this.data, this.fieldMask, precondition, this.fieldTransforms); + } +} +function isWrite(dataSource) { + switch (dataSource) { + case 0 /* UserDataSource.Set */: // fall through + case 2 /* UserDataSource.MergeSet */: // fall through + case 1 /* UserDataSource.Update */: + return true; + case 3 /* UserDataSource.Argument */: + case 4 /* UserDataSource.ArrayArgument */: + return false; + default: + throw fail(0x9c4b, { + dataSource + }); + } +} +/** A "context" object passed around while parsing user data. */ +class ParseContextImpl { + /** + * Initializes a ParseContext with the given source and path. + * + * @param settings - The settings for the parser. + * @param databaseId - The database ID of the Firestore instance. + * @param serializer - The serializer to use to generate the Value proto. + * @param ignoreUndefinedProperties - Whether to ignore undefined properties + * rather than throw. + * @param fieldTransforms - A mutable list of field transforms encountered + * while parsing the data. + * @param fieldMask - A mutable list of field paths encountered while parsing + * the data. + * + * TODO(b/34871131): We don't support array paths right now, so path can be + * null to indicate the context represents any location within an array (in + * which case certain features will not work and errors will be somewhat + * compromised). + */ + constructor(settings, databaseId, serializer, ignoreUndefinedProperties, fieldTransforms, fieldMask) { + this.settings = settings; + this.databaseId = databaseId; + this.serializer = serializer; + this.ignoreUndefinedProperties = ignoreUndefinedProperties; + // Minor hack: If fieldTransforms is undefined, we assume this is an + // external call and we need to validate the entire path. + if (fieldTransforms === undefined) { + this.validatePath(); + } + this.fieldTransforms = fieldTransforms || []; + this.fieldMask = fieldMask || []; + } + get path() { + return this.settings.path; + } + get dataSource() { + return this.settings.dataSource; + } + /** Returns a new context with the specified settings overwritten. */ + contextWith(configuration) { + return new ParseContextImpl({ ...this.settings, ...configuration }, this.databaseId, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask); + } + childContextForField(field) { + const childPath = this.path?.child(field); + const context = this.contextWith({ path: childPath, arrayElement: false }); + context.validatePathSegment(field); + return context; + } + childContextForFieldPath(field) { + const childPath = this.path?.child(field); + const context = this.contextWith({ path: childPath, arrayElement: false }); + context.validatePath(); + return context; + } + childContextForArray(index) { + // TODO(b/34871131): We don't support array paths right now; so make path + // undefined. + return this.contextWith({ path: undefined, arrayElement: true }); + } + createError(reason) { + return createError(reason, this.settings.methodName, this.settings.hasConverter || false, this.path, this.settings.targetDoc); + } + /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ + contains(fieldPath) { + return (this.fieldMask.find(field => fieldPath.isPrefixOf(field)) !== undefined || + this.fieldTransforms.find(transform => fieldPath.isPrefixOf(transform.field)) !== undefined); + } + validatePath() { + // TODO(b/34871131): Remove null check once we have proper paths for fields + // within arrays. + if (!this.path) { + return; + } + for (let i = 0; i < this.path.length; i++) { + this.validatePathSegment(this.path.get(i)); + } + } + validatePathSegment(segment) { + if (segment.length === 0) { + throw this.createError('Document fields must not be empty'); + } + if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) { + throw this.createError('Document fields cannot begin and end with "__"'); + } + } +} +/** + * Helper for parsing raw user input (provided via the API) into internal model + * classes. + */ +class UserDataReader { + constructor(databaseId, ignoreUndefinedProperties, serializer) { + this.databaseId = databaseId; + this.ignoreUndefinedProperties = ignoreUndefinedProperties; + this.serializer = serializer || newSerializer(databaseId); + } + /** Creates a new top-level parse context. */ + createContext(dataSource, methodName, targetDoc, hasConverter = false) { + return new ParseContextImpl({ + dataSource, + methodName, + targetDoc, + path: FieldPath$1.emptyPath(), + arrayElement: false, + hasConverter + }, this.databaseId, this.serializer, this.ignoreUndefinedProperties); + } +} +function newUserDataReader(firestore) { + const settings = firestore._freezeSettings(); + const serializer = newSerializer(firestore._databaseId); + return new UserDataReader(firestore._databaseId, !!settings.ignoreUndefinedProperties, serializer); +} +/** Parse document data from a set() call. */ +function parseSetData(userDataReader, methodName, targetDoc, input, hasConverter, options = {}) { + const context = userDataReader.createContext(options.merge || options.mergeFields + ? 2 /* UserDataSource.MergeSet */ + : 0 /* UserDataSource.Set */, methodName, targetDoc, hasConverter); + validatePlainObject('Data must be an object, but it was:', context, input); + const updateData = parseObject(input, context); + let fieldMask; + let fieldTransforms; + if (options.merge) { + fieldMask = new FieldMask(context.fieldMask); + fieldTransforms = context.fieldTransforms; + } + else if (options.mergeFields) { + const validatedFieldPaths = []; + for (const stringOrFieldPath of options.mergeFields) { + const fieldPath = fieldPathFromArgument$1(methodName, stringOrFieldPath, targetDoc); + if (!context.contains(fieldPath)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Field '${fieldPath}' is specified in your field mask but missing from your input data.`); + } + if (!fieldMaskContains(validatedFieldPaths, fieldPath)) { + validatedFieldPaths.push(fieldPath); + } + } + fieldMask = new FieldMask(validatedFieldPaths); + fieldTransforms = context.fieldTransforms.filter(transform => fieldMask.covers(transform.field)); + } + else { + fieldMask = null; + fieldTransforms = context.fieldTransforms; + } + return new ParsedSetData(new ObjectValue(updateData), fieldMask, fieldTransforms); +} +class DeleteFieldValueImpl extends FieldValue { + _toFieldTransform(context) { + if (context.dataSource === 2 /* UserDataSource.MergeSet */) { + // No transform to add for a delete, but we need to add it to our + // fieldMask so it gets deleted. + context.fieldMask.push(context.path); + } + else if (context.dataSource === 1 /* UserDataSource.Update */) { + throw context.createError(`${this._methodName}() can only appear at the top level ` + + 'of your update data'); + } + else { + // We shouldn't encounter delete sentinels for queries or non-merge set() calls. + throw context.createError(`${this._methodName}() cannot be used with set() unless you pass ` + + '{merge:true}'); + } + return null; + } + isEqual(other) { + return other instanceof DeleteFieldValueImpl; + } +} +/** + * Creates a child context for parsing SerializableFieldValues. + * + * This is different than calling `ParseContext.contextWith` because it keeps + * the fieldTransforms and fieldMask separate. + * + * The created context has its `dataSource` set to `UserDataSource.Argument`. + * Although these values are used with writes, any elements in these FieldValues + * are not considered writes since they cannot contain any FieldValue sentinels, + * etc. + * + * @param fieldValue - The sentinel FieldValue for which to create a child + * context. + * @param context - The parent context. + * @param arrayElement - Whether or not the FieldValue has an array. + */ +function createSentinelChildContext(fieldValue, context, arrayElement) { + return new ParseContextImpl({ + dataSource: 3 /* UserDataSource.Argument */, + targetDoc: context.settings.targetDoc, + methodName: fieldValue._methodName, + arrayElement + }, context.databaseId, context.serializer, context.ignoreUndefinedProperties); +} +class ServerTimestampFieldValueImpl extends FieldValue { + _toFieldTransform(context) { + return new FieldTransform(context.path, new ServerTimestampTransform()); + } + isEqual(other) { + return other instanceof ServerTimestampFieldValueImpl; + } +} +class ArrayUnionFieldValueImpl extends FieldValue { + constructor(methodName, _elements) { + super(methodName); + this._elements = _elements; + } + _toFieldTransform(context) { + const parseContext = createSentinelChildContext(this, context, + /*array=*/ true); + const parsedElements = this._elements.map(element => parseData(element, parseContext)); + const arrayUnion = new ArrayUnionTransformOperation(parsedElements); + return new FieldTransform(context.path, arrayUnion); + } + isEqual(other) { + return (other instanceof ArrayUnionFieldValueImpl && + deepEqual(this._elements, other._elements)); + } +} +class ArrayRemoveFieldValueImpl extends FieldValue { + constructor(methodName, _elements) { + super(methodName); + this._elements = _elements; + } + _toFieldTransform(context) { + const parseContext = createSentinelChildContext(this, context, + /*array=*/ true); + const parsedElements = this._elements.map(element => parseData(element, parseContext)); + const arrayUnion = new ArrayRemoveTransformOperation(parsedElements); + return new FieldTransform(context.path, arrayUnion); + } + isEqual(other) { + return (other instanceof ArrayRemoveFieldValueImpl && + deepEqual(this._elements, other._elements)); + } +} +class NumericIncrementFieldValueImpl extends FieldValue { + constructor(methodName, _operand) { + super(methodName); + this._operand = _operand; + } + _toFieldTransform(context) { + const numericIncrement = new NumericIncrementTransformOperation(context.serializer, toNumber(context.serializer, this._operand)); + return new FieldTransform(context.path, numericIncrement); + } + isEqual(other) { + return (other instanceof NumericIncrementFieldValueImpl && + this._operand === other._operand); + } +} +/** Parse update data from an update() call. */ +function parseUpdateData(userDataReader, methodName, targetDoc, input) { + const context = userDataReader.createContext(1 /* UserDataSource.Update */, methodName, targetDoc); + validatePlainObject('Data must be an object, but it was:', context, input); + const fieldMaskPaths = []; + const updateData = ObjectValue.empty(); + forEach(input, (key, value) => { + const path = fieldPathFromDotSeparatedString(methodName, key, targetDoc); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + value = getModularInstance(value); + const childContext = context.childContextForFieldPath(path); + if (value instanceof DeleteFieldValueImpl) { + // Add it to the field mask, but don't add anything to updateData. + fieldMaskPaths.push(path); + } + else { + const parsedValue = parseData(value, childContext); + if (parsedValue != null) { + fieldMaskPaths.push(path); + updateData.set(path, parsedValue); + } + } + }); + const mask = new FieldMask(fieldMaskPaths); + return new ParsedUpdateData(updateData, mask, context.fieldTransforms); +} +/** Parse update data from a list of field/value arguments. */ +function parseUpdateVarargs(userDataReader, methodName, targetDoc, field, value, moreFieldsAndValues) { + const context = userDataReader.createContext(1 /* UserDataSource.Update */, methodName, targetDoc); + const keys = [fieldPathFromArgument$1(methodName, field, targetDoc)]; + const values = [value]; + if (moreFieldsAndValues.length % 2 !== 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${methodName}() needs to be called with an even number ` + + 'of arguments that alternate between field names and values.'); + } + for (let i = 0; i < moreFieldsAndValues.length; i += 2) { + keys.push(fieldPathFromArgument$1(methodName, moreFieldsAndValues[i])); + values.push(moreFieldsAndValues[i + 1]); + } + const fieldMaskPaths = []; + const updateData = ObjectValue.empty(); + // We iterate in reverse order to pick the last value for a field if the + // user specified the field multiple times. + for (let i = keys.length - 1; i >= 0; --i) { + if (!fieldMaskContains(fieldMaskPaths, keys[i])) { + const path = keys[i]; + let value = values[i]; + // For Compat types, we have to "extract" the underlying types before + // performing validation. + value = getModularInstance(value); + const childContext = context.childContextForFieldPath(path); + if (value instanceof DeleteFieldValueImpl) { + // Add it to the field mask, but don't add anything to updateData. + fieldMaskPaths.push(path); + } + else { + const parsedValue = parseData(value, childContext); + if (parsedValue != null) { + fieldMaskPaths.push(path); + updateData.set(path, parsedValue); + } + } + } + } + const mask = new FieldMask(fieldMaskPaths); + return new ParsedUpdateData(updateData, mask, context.fieldTransforms); +} +/** + * Parse a "query value" (e.g. value in a where filter or a value in a cursor + * bound). + * + * @param allowArrays - Whether the query value is an array that may directly + * contain additional arrays (e.g. the operand of an `in` query). + */ +function parseQueryValue(userDataReader, methodName, input, allowArrays = false) { + const context = userDataReader.createContext(allowArrays ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */, methodName); + const parsed = parseData(input, context); + return parsed; +} +/** + * Parses user data to Protobuf Values. + * + * @param input - Data to be parsed. + * @param context - A context object representing the current path being parsed, + * the source of the data being parsed, etc. + * @returns The parsed value, or null if the value was a FieldValue sentinel + * that should not be included in the resulting parsed data. + */ +function parseData(input, context) { + // Unwrap the API type from the Compat SDK. This will return the API type + // from firestore-exp. + input = getModularInstance(input); + if (looksLikeJsonObject(input)) { + validatePlainObject('Unsupported field value:', context, input); + return parseObject(input, context); + } + else if (input instanceof FieldValue) { + // FieldValues usually parse into transforms (except deleteField()) + // in which case we do not want to include this field in our parsed data + // (as doing so will overwrite the field directly prior to the transform + // trying to transform it). So we don't add this location to + // context.fieldMask and we return null as our parsing result. + parseSentinelFieldValue(input, context); + return null; + } + else if (input === undefined && context.ignoreUndefinedProperties) { + // If the input is undefined it can never participate in the fieldMask, so + // don't handle this below. If `ignoreUndefinedProperties` is false, + // `parseScalarValue` will reject an undefined value. + return null; + } + else { + // If context.path is null we are inside an array and we don't support + // field mask paths more granular than the top-level array. + if (context.path) { + context.fieldMask.push(context.path); + } + if (input instanceof Array) { + // TODO(b/34871131): Include the path containing the array in the error + // message. + // In the case of IN queries, the parsed data is an array (representing + // the set of values to be included for the IN query) that may directly + // contain additional arrays (each representing an individual field + // value), so we disable this validation. + if (context.settings.arrayElement && + context.dataSource !== 4 /* UserDataSource.ArrayArgument */) { + throw context.createError('Nested arrays are not supported'); + } + return parseArray(input, context); + } + else { + return parseScalarValue(input, context); + } + } +} +function parseObject(obj, context) { + const fields = {}; + if (isEmpty(obj)) { + // If we encounter an empty object, we explicitly add it to the update + // mask to ensure that the server creates a map entry. + if (context.path && context.path.length > 0) { + context.fieldMask.push(context.path); + } + } + else { + forEach(obj, (key, val) => { + const parsedValue = parseData(val, context.childContextForField(key)); + if (parsedValue != null) { + fields[key] = parsedValue; + } + }); + } + return { mapValue: { fields } }; +} +function parseArray(array, context) { + const values = []; + let entryIndex = 0; + for (const entry of array) { + let parsedEntry = parseData(entry, context.childContextForArray(entryIndex)); + if (parsedEntry == null) { + // Just include nulls in the array for fields being replaced with a + // sentinel. + parsedEntry = { nullValue: 'NULL_VALUE' }; + } + values.push(parsedEntry); + entryIndex++; + } + return { arrayValue: { values } }; +} +/** + * "Parses" the provided FieldValueImpl, adding any necessary transforms to + * context.fieldTransforms. + */ +function parseSentinelFieldValue(value, context) { + // Sentinels are only supported with writes, and not within arrays. + if (!isWrite(context.dataSource)) { + throw context.createError(`${value._methodName}() can only be used with update() and set()`); + } + if (!context.path) { + throw context.createError(`${value._methodName}() is not currently supported inside arrays`); + } + const fieldTransform = value._toFieldTransform(context); + if (fieldTransform) { + context.fieldTransforms.push(fieldTransform); + } +} +/** + * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue) + * + * @returns The parsed value + */ +function parseScalarValue(value, context) { + value = getModularInstance(value); + if (value === null) { + return { nullValue: 'NULL_VALUE' }; + } + else if (typeof value === 'number') { + return toNumber(context.serializer, value); + } + else if (typeof value === 'boolean') { + return { booleanValue: value }; + } + else if (typeof value === 'string') { + return { stringValue: value }; + } + else if (value instanceof Date) { + const timestamp = Timestamp.fromDate(value); + return { + timestampValue: toTimestamp(context.serializer, timestamp) + }; + } + else if (value instanceof Timestamp) { + // Firestore backend truncates precision down to microseconds. To ensure + // offline mode works the same with regards to truncation, perform the + // truncation immediately without waiting for the backend to do that. + const timestamp = new Timestamp(value.seconds, Math.floor(value.nanoseconds / 1000) * 1000); + return { + timestampValue: toTimestamp(context.serializer, timestamp) + }; + } + else if (value instanceof GeoPoint) { + return { + geoPointValue: { + latitude: value.latitude, + longitude: value.longitude + } + }; + } + else if (value instanceof Bytes) { + return { bytesValue: toBytes(context.serializer, value._byteString) }; + } + else if (value instanceof DocumentReference) { + const thisDb = context.databaseId; + const otherDb = value.firestore._databaseId; + if (!otherDb.isEqual(thisDb)) { + throw context.createError('Document reference is for database ' + + `${otherDb.projectId}/${otherDb.database} but should be ` + + `for database ${thisDb.projectId}/${thisDb.database}`); + } + return { + referenceValue: toResourceName(value.firestore._databaseId || context.databaseId, value._key.path) + }; + } + else if (value instanceof VectorValue) { + return parseVectorValue(value, context); + } + else { + throw context.createError(`Unsupported field value: ${valueDescription(value)}`); + } +} +/** + * Creates a new VectorValue proto value (using the internal format). + */ +function parseVectorValue(value, context) { + const mapValue = { + fields: { + [TYPE_KEY]: { + stringValue: VECTOR_VALUE_SENTINEL + }, + [VECTOR_MAP_VECTORS_KEY]: { + arrayValue: { + values: value.toArray().map(value => { + if (typeof value !== 'number') { + throw context.createError('VectorValues must only contain numeric values.'); + } + return toDouble(context.serializer, value); + }) + } + } + } + }; + return { mapValue }; +} +/** + * Checks whether an object looks like a JSON object that should be converted + * into a struct. Normal class/prototype instances are considered to look like + * JSON objects since they should be converted to a struct value. Arrays, Dates, + * GeoPoints, etc. are not considered to look like JSON objects since they map + * to specific FieldValue types other than ObjectValue. + */ +function looksLikeJsonObject(input) { + return (typeof input === 'object' && + input !== null && + !(input instanceof Array) && + !(input instanceof Date) && + !(input instanceof Timestamp) && + !(input instanceof GeoPoint) && + !(input instanceof Bytes) && + !(input instanceof DocumentReference) && + !(input instanceof FieldValue) && + !(input instanceof VectorValue)); +} +function validatePlainObject(message, context, input) { + if (!looksLikeJsonObject(input) || !isPlainObject(input)) { + const description = valueDescription(input); + if (description === 'an object') { + // Massage the error if it was an object. + throw context.createError(message + ' a custom object'); + } + else { + throw context.createError(message + ' ' + description); + } + } +} +/** + * Helper that calls fromDotSeparatedString() but wraps any error thrown. + */ +function fieldPathFromArgument$1(methodName, path, targetDoc) { + // If required, replace the FieldPath Compat class with the firestore-exp + // FieldPath. + path = getModularInstance(path); + if (path instanceof FieldPath) { + return path._internalPath; + } + else if (typeof path === 'string') { + return fieldPathFromDotSeparatedString(methodName, path); + } + else { + const message = 'Field path arguments must be of type string or '; + throw createError(message, methodName, + /* hasConverter= */ false, + /* path= */ undefined, targetDoc); + } +} +/** + * Matches any characters in a field path string that are reserved. + */ +const FIELD_PATH_RESERVED = new RegExp('[~\\*/\\[\\]]'); +/** + * Wraps fromDotSeparatedString with an error message about the method that + * was thrown. + * @param methodName - The publicly visible method name + * @param path - The dot-separated string form of a field path which will be + * split on dots. + * @param targetDoc - The document against which the field path will be + * evaluated. + */ +function fieldPathFromDotSeparatedString(methodName, path, targetDoc) { + const found = path.search(FIELD_PATH_RESERVED); + if (found >= 0) { + throw createError(`Invalid field path (${path}). Paths must not contain ` + + `'~', '*', '/', '[', or ']'`, methodName, + /* hasConverter= */ false, + /* path= */ undefined, targetDoc); + } + try { + return new FieldPath(...path.split('.'))._internalPath; + } + catch (e) { + throw createError(`Invalid field path (${path}). Paths must not be empty, ` + + `begin with '.', end with '.', or contain '..'`, methodName, + /* hasConverter= */ false, + /* path= */ undefined, targetDoc); + } +} +function createError(reason, methodName, hasConverter, path, targetDoc) { + const hasPath = path && !path.isEmpty(); + const hasDocument = targetDoc !== undefined; + let message = `Function ${methodName}() called with invalid data`; + if (hasConverter) { + message += ' (via `toFirestore()`)'; + } + message += '. '; + let description = ''; + if (hasPath || hasDocument) { + description += ' (found'; + if (hasPath) { + description += ` in field ${path}`; + } + if (hasDocument) { + description += ` in document ${targetDoc}`; + } + description += ')'; + } + return new FirestoreError(Code.INVALID_ARGUMENT, message + reason + description); +} +/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ +function fieldMaskContains(haystack, needle) { + return haystack.some(v => v.isEqual(needle)); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ +class DocumentSnapshot$1 { + // Note: This class is stripped down version of the DocumentSnapshot in + // the legacy SDK. The changes are: + // - No support for SnapshotMetadata. + // - No support for SnapshotOptions. + /** @hideconstructor protected */ + constructor(_firestore, _userDataWriter, _key, _document, _converter) { + this._firestore = _firestore; + this._userDataWriter = _userDataWriter; + this._key = _key; + this._document = _document; + this._converter = _converter; + } + /** Property of the `DocumentSnapshot` that provides the document's ID. */ + get id() { + return this._key.path.lastSegment(); + } + /** + * The `DocumentReference` for the document included in the `DocumentSnapshot`. + */ + get ref() { + return new DocumentReference(this._firestore, this._converter, this._key); + } + /** + * Signals whether or not the document at the snapshot's location exists. + * + * @returns true if the document exists. + */ + exists() { + return this._document !== null; + } + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * @returns An `Object` containing all fields in the document or `undefined` + * if the document doesn't exist. + */ + data() { + if (!this._document) { + return undefined; + } + else if (this._converter) { + // We only want to use the converter and create a new DocumentSnapshot + // if a converter has been provided. + const snapshot = new QueryDocumentSnapshot$1(this._firestore, this._userDataWriter, this._key, this._document, + /* converter= */ null); + return this._converter.fromFirestore(snapshot); + } + else { + return this._userDataWriter.convertValue(this._document.data.value); + } + } + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + // We are using `any` here to avoid an explicit cast by our users. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get(fieldPath) { + if (this._document) { + const value = this._document.data.field(fieldPathFromArgument('DocumentSnapshot.get', fieldPath)); + if (value !== null) { + return this._userDataWriter.convertValue(value); + } + } + return undefined; + } +} +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ +class QueryDocumentSnapshot$1 extends DocumentSnapshot$1 { + /** + * Retrieves all fields in the document as an `Object`. + * + * @override + * @returns An `Object` containing all fields in the document. + */ + data() { + return super.data(); + } +} +/** + * Helper that calls `fromDotSeparatedString()` but wraps any error thrown. + */ +function fieldPathFromArgument(methodName, arg) { + if (typeof arg === 'string') { + return fieldPathFromDotSeparatedString(methodName, arg); + } + else if (arg instanceof FieldPath) { + return arg._internalPath; + } + else { + return arg._delegate._internalPath; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function validateHasExplicitOrderByForLimitToLast(query) { + if (query.limitType === "L" /* LimitType.Last */ && + query.explicitOrderBy.length === 0) { + throw new FirestoreError(Code.UNIMPLEMENTED, 'limitToLast() queries require specifying at least one orderBy() clause'); + } +} +/** + * An `AppliableConstraint` is an abstraction of a constraint that can be applied + * to a Firestore query. + */ +class AppliableConstraint { +} +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Firestore query. `QueryConstraint`s are created by invoking {@link where}, + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that + * also contains this `QueryConstraint`. + */ +class QueryConstraint extends AppliableConstraint { +} +function query(query, queryConstraint, ...additionalQueryConstraints) { + let queryConstraints = []; + if (queryConstraint instanceof AppliableConstraint) { + queryConstraints.push(queryConstraint); + } + queryConstraints = queryConstraints.concat(additionalQueryConstraints); + validateQueryConstraintArray(queryConstraints); + for (const constraint of queryConstraints) { + query = constraint._apply(query); + } + return query; +} +/** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ +class QueryFieldFilterConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(_field, _op, _value) { + super(); + this._field = _field; + this._op = _op; + this._value = _value; + /** The type of this query constraint */ + this.type = 'where'; + } + static _create(_field, _op, _value) { + return new QueryFieldFilterConstraint(_field, _op, _value); + } + _apply(query) { + const filter = this._parse(query); + validateNewFieldFilter(query._query, filter); + return new Query(query.firestore, query.converter, queryWithAddedFilter(query._query, filter)); + } + _parse(query) { + const reader = newUserDataReader(query.firestore); + const filter = newQueryFilter(query._query, 'where', reader, query.firestore._databaseId, this._field, this._op, this._value); + return filter; + } +} +/** + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. + * + * @param fieldPath - The path to compare + * @param opStr - The operation string (e.g "<", "<=", "==", "<", + * "<=", "!="). + * @param value - The value for comparison + * @returns The created {@link QueryFieldFilterConstraint}. + */ +function where(fieldPath, opStr, value) { + const op = opStr; + const field = fieldPathFromArgument('where', fieldPath); + return QueryFieldFilterConstraint._create(field, op, value); +} +/** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ +class QueryCompositeFilterConstraint extends AppliableConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + type, _queryConstraints) { + super(); + this.type = type; + this._queryConstraints = _queryConstraints; + } + static _create(type, _queryConstraints) { + return new QueryCompositeFilterConstraint(type, _queryConstraints); + } + _parse(query) { + const parsedFilters = this._queryConstraints + .map(queryConstraint => { + return queryConstraint._parse(query); + }) + .filter(parsedFilter => parsedFilter.getFilters().length > 0); + if (parsedFilters.length === 1) { + return parsedFilters[0]; + } + return CompositeFilter.create(parsedFilters, this._getOperator()); + } + _apply(query) { + const parsedFilter = this._parse(query); + if (parsedFilter.getFilters().length === 0) { + // Return the existing query if not adding any more filters (e.g. an empty + // composite filter). + return query; + } + validateNewFilter(query._query, parsedFilter); + return new Query(query.firestore, query.converter, queryWithAddedFilter(query._query, parsedFilter)); + } + _getQueryConstraints() { + return this._queryConstraints; + } + _getOperator() { + return this.type === 'and' ? "and" /* CompositeOperator.AND */ : "or" /* CompositeOperator.OR */; + } +} +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +function or(...queryConstraints) { + // Only support QueryFilterConstraints + queryConstraints.forEach(queryConstraint => validateQueryFilterConstraint('or', queryConstraint)); + return QueryCompositeFilterConstraint._create("or" /* CompositeOperator.OR */, queryConstraints); +} +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +function and(...queryConstraints) { + // Only support QueryFilterConstraints + queryConstraints.forEach(queryConstraint => validateQueryFilterConstraint('and', queryConstraint)); + return QueryCompositeFilterConstraint._create("and" /* CompositeOperator.AND */, queryConstraints); +} +/** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ +class QueryOrderByConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(_field, _direction) { + super(); + this._field = _field; + this._direction = _direction; + /** The type of this query constraint */ + this.type = 'orderBy'; + } + static _create(_field, _direction) { + return new QueryOrderByConstraint(_field, _direction); + } + _apply(query) { + const orderBy = newQueryOrderBy(query._query, this._field, this._direction); + return new Query(query.firestore, query.converter, queryWithAddedOrderBy(query._query, orderBy)); + } +} +/** + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the + * specified field, optionally in descending order instead of ascending. + * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * + * @param fieldPath - The field to sort by. + * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @returns The created {@link QueryOrderByConstraint}. + */ +function orderBy(fieldPath, directionStr = 'asc') { + const direction = directionStr; + const path = fieldPathFromArgument('orderBy', fieldPath); + return QueryOrderByConstraint._create(path, direction); +} +/** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ +class QueryLimitConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + type, _limit, _limitType) { + super(); + this.type = type; + this._limit = _limit; + this._limitType = _limitType; + } + static _create(type, _limit, _limitType) { + return new QueryLimitConstraint(type, _limit, _limitType); + } + _apply(query) { + return new Query(query.firestore, query.converter, queryWithLimit(query._query, this._limit, this._limitType)); + } +} +/** + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +function limit(limit) { + validatePositiveNumber('limit', limit); + return QueryLimitConstraint._create('limit', limit, "F" /* LimitType.First */); +} +/** + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. + * + * You must specify at least one `orderBy` clause for `limitToLast` queries, + * otherwise an exception will be thrown during execution. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +function limitToLast(limit) { + validatePositiveNumber('limitToLast', limit); + return QueryLimitConstraint._create('limitToLast', limit, "L" /* LimitType.Last */); +} +/** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ +class QueryStartAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + type, _docOrFields, _inclusive) { + super(); + this.type = type; + this._docOrFields = _docOrFields; + this._inclusive = _inclusive; + } + static _create(type, _docOrFields, _inclusive) { + return new QueryStartAtConstraint(type, _docOrFields, _inclusive); + } + _apply(query) { + const bound = newQueryBoundFromDocOrFields(query, this.type, this._docOrFields, this._inclusive); + return new Query(query.firestore, query.converter, queryWithStartAt(query._query, bound)); + } +} +function startAt(...docOrFields) { + return QueryStartAtConstraint._create('startAt', docOrFields, + /*inclusive=*/ true); +} +function startAfter(...docOrFields) { + return QueryStartAtConstraint._create('startAfter', docOrFields, + /*inclusive=*/ false); +} +/** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ +class QueryEndAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + type, _docOrFields, _inclusive) { + super(); + this.type = type; + this._docOrFields = _docOrFields; + this._inclusive = _inclusive; + } + static _create(type, _docOrFields, _inclusive) { + return new QueryEndAtConstraint(type, _docOrFields, _inclusive); + } + _apply(query) { + const bound = newQueryBoundFromDocOrFields(query, this.type, this._docOrFields, this._inclusive); + return new Query(query.firestore, query.converter, queryWithEndAt(query._query, bound)); + } +} +function endBefore(...docOrFields) { + return QueryEndAtConstraint._create('endBefore', docOrFields, + /*inclusive=*/ false); +} +function endAt(...docOrFields) { + return QueryEndAtConstraint._create('endAt', docOrFields, + /*inclusive=*/ true); +} +/** Helper function to create a bound from a document or fields */ +function newQueryBoundFromDocOrFields(query, methodName, docOrFields, inclusive) { + docOrFields[0] = getModularInstance(docOrFields[0]); + if (docOrFields[0] instanceof DocumentSnapshot$1) { + return newQueryBoundFromDocument(query._query, query.firestore._databaseId, methodName, docOrFields[0]._document, inclusive); + } + else { + const reader = newUserDataReader(query.firestore); + return newQueryBoundFromFields(query._query, query.firestore._databaseId, reader, methodName, docOrFields, inclusive); + } +} +function newQueryFilter(query, methodName, dataReader, databaseId, fieldPath, op, value) { + let fieldValue; + if (fieldPath.isKeyField()) { + if (op === "array-contains" /* Operator.ARRAY_CONTAINS */ || op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid Query. You can't perform '${op}' queries on documentId().`); + } + else if (op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */) { + validateDisjunctiveFilterElements(value, op); + const referenceList = []; + for (const arrayValue of value) { + referenceList.push(parseDocumentIdValue(databaseId, query, arrayValue)); + } + fieldValue = { arrayValue: { values: referenceList } }; + } + else { + fieldValue = parseDocumentIdValue(databaseId, query, value); + } + } + else { + if (op === "in" /* Operator.IN */ || + op === "not-in" /* Operator.NOT_IN */ || + op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) { + validateDisjunctiveFilterElements(value, op); + } + fieldValue = parseQueryValue(dataReader, methodName, value, + /* allowArrays= */ op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */); + } + const filter = FieldFilter.create(fieldPath, op, fieldValue); + return filter; +} +function newQueryOrderBy(query, fieldPath, direction) { + if (query.startAt !== null) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call startAt() or startAfter() before ' + + 'calling orderBy().'); + } + if (query.endAt !== null) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call endAt() or endBefore() before ' + + 'calling orderBy().'); + } + const orderBy = new OrderBy(fieldPath, direction); + return orderBy; +} +/** + * Create a `Bound` from a query and a document. + * + * Note that the `Bound` will always include the key of the document + * and so only the provided document will compare equal to the returned + * position. + * + * Will throw if the document does not contain all fields of the order by + * of the query or if any of the fields in the order by are an uncommitted + * server timestamp. + */ +function newQueryBoundFromDocument(query, databaseId, methodName, doc, inclusive) { + if (!doc) { + throw new FirestoreError(Code.NOT_FOUND, `Can't use a DocumentSnapshot that doesn't exist for ` + + `${methodName}().`); + } + const components = []; + // Because people expect to continue/end a query at the exact document + // provided, we need to use the implicit sort order rather than the explicit + // sort order, because it's guaranteed to contain the document key. That way + // the position becomes unambiguous and the query continues/ends exactly at + // the provided document. Without the key (by using the explicit sort + // orders), multiple documents could match the position, yielding duplicate + // results. + for (const orderBy of queryNormalizedOrderBy(query)) { + if (orderBy.field.isKeyField()) { + components.push(refValue(databaseId, doc.key)); + } + else { + const value = doc.data.field(orderBy.field); + if (isServerTimestamp(value)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You are trying to start or end a query using a ' + + 'document for which the field "' + + orderBy.field + + '" is an uncommitted server timestamp. (Since the value of ' + + 'this field is unknown, you cannot start/end a query with it.)'); + } + else if (value !== null) { + components.push(value); + } + else { + const field = orderBy.field.canonicalString(); + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. You are trying to start or end a query using a ` + + `document for which the field '${field}' (used as the ` + + `orderBy) does not exist.`); + } + } + } + return new Bound(components, inclusive); +} +/** + * Converts a list of field values to a `Bound` for the given query. + */ +function newQueryBoundFromFields(query, databaseId, dataReader, methodName, values, inclusive) { + // Use explicit order by's because it has to match the query the user made + const orderBy = query.explicitOrderBy; + if (values.length > orderBy.length) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Too many arguments provided to ${methodName}(). ` + + `The number of arguments must be less than or equal to the ` + + `number of orderBy() clauses`); + } + const components = []; + for (let i = 0; i < values.length; i++) { + const rawValue = values[i]; + const orderByComponent = orderBy[i]; + if (orderByComponent.field.isKeyField()) { + if (typeof rawValue !== 'string') { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. Expected a string for document ID in ` + + `${methodName}(), but got a ${typeof rawValue}`); + } + if (!isCollectionGroupQuery(query) && rawValue.indexOf('/') !== -1) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection and ordering by documentId(), ` + + `the value passed to ${methodName}() must be a plain document ID, but ` + + `'${rawValue}' contains a slash.`); + } + const path = query.path.child(ResourcePath.fromString(rawValue)); + if (!DocumentKey.isDocumentKey(path)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection group and ordering by ` + + `documentId(), the value passed to ${methodName}() must result in a ` + + `valid document path, but '${path}' is not because it contains an odd number ` + + `of segments.`); + } + const key = new DocumentKey(path); + components.push(refValue(databaseId, key)); + } + else { + const wrapped = parseQueryValue(dataReader, methodName, rawValue); + components.push(wrapped); + } + } + return new Bound(components, inclusive); +} +/** + * Parses the given `documentIdValue` into a `ReferenceValue`, throwing + * appropriate errors if the value is anything other than a `DocumentReference` + * or `string`, or if the string is malformed. + */ +function parseDocumentIdValue(databaseId, query, documentIdValue) { + documentIdValue = getModularInstance(documentIdValue); + if (typeof documentIdValue === 'string') { + if (documentIdValue === '') { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. When querying with documentId(), you ' + + 'must provide a valid document ID, but it was an empty string.'); + } + if (!isCollectionGroupQuery(query) && documentIdValue.indexOf('/') !== -1) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection by ` + + `documentId(), you must provide a plain document ID, but ` + + `'${documentIdValue}' contains a '/' character.`); + } + const path = query.path.child(ResourcePath.fromString(documentIdValue)); + if (!DocumentKey.isDocumentKey(path)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection group by ` + + `documentId(), the value provided must result in a valid document path, ` + + `but '${path}' is not because it has an odd number of segments (${path.length}).`); + } + return refValue(databaseId, new DocumentKey(path)); + } + else if (documentIdValue instanceof DocumentReference) { + return refValue(databaseId, documentIdValue._key); + } + else { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying with documentId(), you must provide a valid ` + + `string or a DocumentReference, but it was: ` + + `${valueDescription(documentIdValue)}.`); + } +} +/** + * Validates that the value passed into a disjunctive filter satisfies all + * array requirements. + */ +function validateDisjunctiveFilterElements(value, operator) { + if (!Array.isArray(value) || value.length === 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid Query. A non-empty array is required for ' + + `'${operator.toString()}' filters.`); + } +} +/** + * Given an operator, returns the set of operators that cannot be used with it. + * + * This is not a comprehensive check, and this function should be removed in the + * long term. Validations should occur in the Firestore backend. + * + * Operators in a query must adhere to the following set of rules: + * 1. Only one inequality per query. + * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators. + */ +function conflictingOps(op) { + switch (op) { + case "!=" /* Operator.NOT_EQUAL */: + return ["!=" /* Operator.NOT_EQUAL */, "not-in" /* Operator.NOT_IN */]; + case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */: + case "in" /* Operator.IN */: + return ["not-in" /* Operator.NOT_IN */]; + case "not-in" /* Operator.NOT_IN */: + return [ + "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */, + "in" /* Operator.IN */, + "not-in" /* Operator.NOT_IN */, + "!=" /* Operator.NOT_EQUAL */ + ]; + default: + return []; + } +} +function validateNewFieldFilter(query, fieldFilter) { + const conflictingOp = findOpInsideFilters(query.filters, conflictingOps(fieldFilter.op)); + if (conflictingOp !== null) { + // Special case when it's a duplicate op to give a slightly clearer error message. + if (conflictingOp === fieldFilter.op) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You cannot use more than one ' + + `'${fieldFilter.op.toString()}' filter.`); + } + else { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. You cannot use '${fieldFilter.op.toString()}' filters ` + + `with '${conflictingOp.toString()}' filters.`); + } + } +} +function validateNewFilter(query, filter) { + let testQuery = query; + const subFilters = filter.getFlattenedFilters(); + for (const subFilter of subFilters) { + validateNewFieldFilter(testQuery, subFilter); + testQuery = queryWithAddedFilter(testQuery, subFilter); + } +} +// Checks if any of the provided filter operators are included in the given list of filters and +// returns the first one that is, or null if none are. +function findOpInsideFilters(filters, operators) { + for (const filter of filters) { + for (const fieldFilter of filter.getFlattenedFilters()) { + if (operators.indexOf(fieldFilter.op) >= 0) { + return fieldFilter.op; + } + } + } + return null; +} +function validateQueryFilterConstraint(functionName, queryConstraint) { + if (!(queryConstraint instanceof QueryFieldFilterConstraint) && + !(queryConstraint instanceof QueryCompositeFilterConstraint)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${functionName}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`); + } +} +function validateQueryConstraintArray(queryConstraint) { + const compositeFilterCount = queryConstraint.filter(filter => filter instanceof QueryCompositeFilterConstraint).length; + const fieldFilterCount = queryConstraint.filter(filter => filter instanceof QueryFieldFilterConstraint).length; + if (compositeFilterCount > 1 || + (compositeFilterCount > 0 && fieldFilterCount > 0)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'InvalidQuery. When using composite filters, you cannot use ' + + 'more than one filter at the top level. Consider nesting the multiple ' + + 'filters within an `and(...)` statement. For example: ' + + 'change `query(query, where(...), or(...))` to ' + + '`query(query, and(where(...), or(...)))`.'); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Converts Firestore's internal types to the JavaScript types that we expose + * to the user. + * + * @internal + */ +class AbstractUserDataWriter { + convertValue(value, serverTimestampBehavior = 'none') { + switch (typeOrder(value)) { + case 0 /* TypeOrder.NullValue */: + return null; + case 1 /* TypeOrder.BooleanValue */: + return value.booleanValue; + case 2 /* TypeOrder.NumberValue */: + return normalizeNumber(value.integerValue || value.doubleValue); + case 3 /* TypeOrder.TimestampValue */: + return this.convertTimestamp(value.timestampValue); + case 4 /* TypeOrder.ServerTimestampValue */: + return this.convertServerTimestamp(value, serverTimestampBehavior); + case 5 /* TypeOrder.StringValue */: + return value.stringValue; + case 6 /* TypeOrder.BlobValue */: + return this.convertBytes(normalizeByteString(value.bytesValue)); + case 7 /* TypeOrder.RefValue */: + return this.convertReference(value.referenceValue); + case 8 /* TypeOrder.GeoPointValue */: + return this.convertGeoPoint(value.geoPointValue); + case 9 /* TypeOrder.ArrayValue */: + return this.convertArray(value.arrayValue, serverTimestampBehavior); + case 11 /* TypeOrder.ObjectValue */: + return this.convertObject(value.mapValue, serverTimestampBehavior); + case 10 /* TypeOrder.VectorValue */: + return this.convertVectorValue(value.mapValue); + default: + throw fail(0xf2a2, { + value + }); + } + } + convertObject(mapValue, serverTimestampBehavior) { + return this.convertObjectMap(mapValue.fields, serverTimestampBehavior); + } + /** + * @internal + */ + convertObjectMap(fields, serverTimestampBehavior = 'none') { + const result = {}; + forEach(fields, (key, value) => { + result[key] = this.convertValue(value, serverTimestampBehavior); + }); + return result; + } + /** + * @internal + */ + convertVectorValue(mapValue) { + const values = mapValue.fields?.[VECTOR_MAP_VECTORS_KEY].arrayValue?.values?.map(value => { + return normalizeNumber(value.doubleValue); + }); + return new VectorValue(values); + } + convertGeoPoint(value) { + return new GeoPoint(normalizeNumber(value.latitude), normalizeNumber(value.longitude)); + } + convertArray(arrayValue, serverTimestampBehavior) { + return (arrayValue.values || []).map(value => this.convertValue(value, serverTimestampBehavior)); + } + convertServerTimestamp(value, serverTimestampBehavior) { + switch (serverTimestampBehavior) { + case 'previous': + const previousValue = getPreviousValue(value); + if (previousValue == null) { + return null; + } + return this.convertValue(previousValue, serverTimestampBehavior); + case 'estimate': + return this.convertTimestamp(getLocalWriteTime(value)); + default: + return null; + } + } + convertTimestamp(value) { + const normalizedValue = normalizeTimestamp(value); + return new Timestamp(normalizedValue.seconds, normalizedValue.nanos); + } + convertDocumentKey(name, expectedDatabaseId) { + const resourcePath = ResourcePath.fromString(name); + hardAssert(isValidResourceName(resourcePath), 0x25d8, { name }); + const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3)); + const key = new DocumentKey(resourcePath.popFirst(5)); + if (!databaseId.isEqual(expectedDatabaseId)) { + // TODO(b/64130202): Somehow support foreign references. + logError(`Document ${key} contains a document ` + + `reference within a different database (` + + `${databaseId.projectId}/${databaseId.database}) which is not ` + + `supported. It will be treated as a reference in the current ` + + `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` + + `instead.`); + } + return key; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Converts custom model object of type T into `DocumentData` by applying the + * converter if it exists. + * + * This function is used when converting user objects to `DocumentData` + * because we want to provide the user with a more specific error message if + * their `set()` or fails due to invalid data originating from a `toFirestore()` + * call. + */ +function applyFirestoreDataConverter(converter, value, options) { + let convertedValue; + if (converter) { + if (options && (options.merge || options.mergeFields)) { + // Cast to `any` in order to satisfy the union type constraint on + // toFirestore(). + // eslint-disable-next-line @typescript-eslint/no-explicit-any + convertedValue = converter.toFirestore(value, options); + } + else { + convertedValue = converter.toFirestore(value); + } + } + else { + convertedValue = value; + } + return convertedValue; +} +class LiteUserDataWriter extends AbstractUserDataWriter { + constructor(firestore) { + super(); + this.firestore = firestore; + } + convertBytes(bytes) { + return new Bytes(bytes); + } + convertReference(name) { + const key = this.convertDocumentKey(name, this.firestore._databaseId); + return new DocumentReference(this.firestore, /* converter= */ null, key); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ +function sum(field) { + return new AggregateField('sum', fieldPathFromArgument$1('sum', field)); +} +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ +function average(field) { + return new AggregateField('avg', fieldPathFromArgument$1('average', field)); +} +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ +function count() { + return new AggregateField('count'); +} +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ +function aggregateFieldEqual(left, right) { + return (left instanceof AggregateField && + right instanceof AggregateField && + left.aggregateType === right.aggregateType && + left._internalFieldPath?.canonicalString() === + right._internalFieldPath?.canonicalString()); +} +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ +function aggregateQuerySnapshotEqual(left, right) { + return (queryEqual(left.query, right.query) && deepEqual(left.data(), right.data())); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function isPartialObserver(obj) { + return implementsAnyMethods(obj, ['next', 'error', 'complete']); +} +/** + * Returns true if obj is an object and contains at least one of the specified + * methods. + */ +function implementsAnyMethods(obj, methods) { + if (typeof obj !== 'object' || obj === null) { + return false; + } + const object = obj; + for (const method of methods) { + if (method in object && typeof object[method] === 'function') { + return true; + } + } + return false; +} + +const encoder = newTextEncoder(); +function lengthPrefixedString(o) { + const str = JSON.stringify(o); + const l = encoder.encode(str).byteLength; + return `${l}${str}`; +} +// TODO(wuandy): Ideally, these should use `TestBundleBuilder` above. +const meta = { + metadata: { + id: 'test-bundle', + createTime: { seconds: 1577836805, nanos: 6 }, + version: 1, + totalDocuments: 1, + totalBytes: 416 + } +}; +lengthPrefixedString(meta); +const doc1Meta = { + documentMetadata: { + name: 'projects/test-project/databases/(default)/documents/collectionId/doc1', + readTime: { seconds: 5, nanos: 6 }, + exists: true + } +}; +lengthPrefixedString(doc1Meta); +const doc1 = { + document: { + name: 'projects/test-project/databases/(default)/documents/collectionId/doc1', + createTime: { seconds: 1, nanos: 2000000 }, + updateTime: { seconds: 3, nanos: 4000 }, + fields: { foo: { stringValue: 'value' }, bar: { integerValue: -42 } } + } +}; +lengthPrefixedString(doc1); +const doc2Meta = { + documentMetadata: { + name: 'projects/test-project/databases/(default)/documents/collectionId/doc2', + readTime: { seconds: 5, nanos: 6 }, + exists: true + } +}; +lengthPrefixedString(doc2Meta); +const doc2 = { + document: { + name: 'projects/test-project/databases/(default)/documents/collectionId/doc2', + createTime: { seconds: 1, nanos: 2000000 }, + updateTime: { seconds: 3, nanos: 4000 }, + fields: { + foo: { stringValue: 'value1' }, + bar: { integerValue: 42 }, + emptyArray: { arrayValue: {} }, + emptyMap: { mapValue: {} } + } + } +}; +lengthPrefixedString(doc2); +const noDocMeta = { + documentMetadata: { + name: 'projects/test-project/databases/(default)/documents/collectionId/nodoc', + readTime: { seconds: 5, nanos: 6 }, + exists: false + } +}; +lengthPrefixedString(noDocMeta); +const limitQuery = { + namedQuery: { + name: 'limitQuery', + bundledQuery: { + parent: 'projects/fireeats-97d5e/databases/(default)/documents', + structuredQuery: { + from: [{ collectionId: 'node_3.7.5_7Li7XoCjutvNxwD0tpo9' }], + orderBy: [{ field: { fieldPath: 'sort' }, direction: 'DESCENDING' }], + limit: { 'value': 1 } + }, + limitType: 'FIRST' + }, + readTime: { 'seconds': 1590011379, 'nanos': 191164000 } + } +}; +lengthPrefixedString(limitQuery); +const limitToLastQuery = { + namedQuery: { + name: 'limitToLastQuery', + bundledQuery: { + parent: 'projects/fireeats-97d5e/databases/(default)/documents', + structuredQuery: { + from: [{ collectionId: 'node_3.7.5_7Li7XoCjutvNxwD0tpo9' }], + orderBy: [{ field: { fieldPath: 'sort' }, direction: 'ASCENDING' }], + limit: { 'value': 1 } + }, + limitType: 'LAST' + }, + readTime: { 'seconds': 1590011379, 'nanos': 543063000 } + } +}; +lengthPrefixedString(limitToLastQuery); + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const BUNDLE_VERSION = 1; +/** + * Builds a Firestore data bundle with results from the given document and query snapshots. + */ +class BundleBuilder { + constructor(firestore, bundleId) { + this.firestore = firestore; + this.bundleId = bundleId; + // Resulting documents for the bundle, keyed by full document path. + this.documents = new Map(); + // Named queries saved in the bundle, keyed by query name. + this.namedQueries = new Map(); + // The latest read time among all bundled documents and queries. + this.latestReadTime = new Timestamp(0, 0); + this.databaseId = firestore._databaseId; + // useProto3Json is true because the objects will be serialized to JSON string + // before being written to the bundle buffer. + this.serializer = new JsonProtoSerializer(this.databaseId, + /*useProto3Json=*/ true); + this.userDataReader = new UserDataReader(this.databaseId, true, this.serializer); + } + /** + * Adds data from a DocumentSnapshot to the bundle. + * @internal + * @param docBundleData A DocumentSnapshotBundleData containing information from the + * DocumentSnapshot. Note we cannot accept a DocumentSnapshot directly due to a circular + * dependency error. + * @param queryName The name of the QuerySnapshot if this document is part of a Query. + */ + addBundleDocument(docBundleData, queryName) { + const originalDocument = this.documents.get(docBundleData.documentPath); + const originalQueries = originalDocument?.metadata.queries; + const docReadTime = docBundleData.readTime; + const origDocReadTime = !!originalDocument?.metadata + .readTime + ? fromTimestamp(originalDocument.metadata.readTime) + : null; + const neitherHasReadTime = !docReadTime && origDocReadTime == null; + const docIsNewer = docReadTime !== undefined && + (origDocReadTime == null || origDocReadTime < docReadTime); + if (neitherHasReadTime || docIsNewer) { + // Store document. + this.documents.set(docBundleData.documentPath, { + document: this.toBundleDocument(docBundleData), + metadata: { + name: toName(this.serializer, docBundleData.documentKey), + readTime: !!docReadTime + ? toTimestamp(this.serializer, docReadTime) // Convert Timestamp to proto format. + : undefined, + exists: docBundleData.documentExists + } + }); + } + if (docReadTime && docReadTime > this.latestReadTime) { + this.latestReadTime = docReadTime; + } + // Update `queries` to include both original and `queryName`. + if (queryName) { + const newDocument = this.documents.get(docBundleData.documentPath); + newDocument.metadata.queries = originalQueries || []; + newDocument.metadata.queries.push(queryName); + } + } + /** + * Adds data from a QuerySnapshot to the bundle. + * @internal + * @param docBundleData A QuerySnapshotBundleData containing information from the + * QuerySnapshot. Note we cannot accept a QuerySnapshot directly due to a circular + * dependency error. + */ + addBundleQuery(queryBundleData) { + if (this.namedQueries.has(queryBundleData.name)) { + throw new Error(`Query name conflict: ${name} has already been added.`); + } + let latestReadTime = new Timestamp(0, 0); + for (const docBundleData of queryBundleData.docBundleDataArray) { + this.addBundleDocument(docBundleData, queryBundleData.name); + if (docBundleData.readTime && docBundleData.readTime > latestReadTime) { + latestReadTime = docBundleData.readTime; + } + } + const queryTarget = toQueryTarget(this.serializer, queryToTarget(queryBundleData.query)); + const bundledQuery = { + parent: queryBundleData.parent, + structuredQuery: queryTarget.queryTarget.structuredQuery + }; + this.namedQueries.set(queryBundleData.name, { + name: queryBundleData.name, + bundledQuery, + readTime: toTimestamp(this.serializer, latestReadTime) + }); + } + /** + * Convert data from a DocumentSnapshot into the serialized form within a bundle. + * @private + * @internal + * @param docBundleData a DocumentSnapshotBundleData containing the data required to + * serialize a document. + */ + toBundleDocument(docBundleData) { + // a parse context is typically used for validating and parsing user data, but in this + // case we are using it internally to convert DocumentData to Proto3 JSON + const context = this.userDataReader.createContext(4 /* UserDataSource.ArrayArgument */, 'internal toBundledDocument'); + const proto3Fields = parseObject(docBundleData.documentData, context); + return { + name: toName(this.serializer, docBundleData.documentKey), + fields: proto3Fields.mapValue.fields, + updateTime: toTimestamp(this.serializer, docBundleData.versionTime), + createTime: toTimestamp(this.serializer, docBundleData.createdTime) + }; + } + /** + * Converts a IBundleElement to a Buffer whose content is the length prefixed JSON representation + * of the element. + * @private + * @internal + * @param bundleElement A ProtoBundleElement that is expected to be Proto3 JSON compatible. + */ + lengthPrefixedString(bundleElement) { + const str = JSON.stringify(bundleElement); + // TODO: it's not ideal to have to re-encode all of these strings multiple times + // It may be more performant to return a UInt8Array that is concatenated to other + // UInt8Arrays instead of returning and concatenating strings and then + // converting the full string to UInt8Array. + const l = encoder.encode(str).byteLength; + return `${l}${str}`; + } + /** + * Construct a serialized string containing document and query information that has previously + * been added to the BundleBuilder through the addBundleDocument and addBundleQuery methods. + * @internal + */ + build() { + let bundleString = ''; + for (const namedQuery of this.namedQueries.values()) { + bundleString += this.lengthPrefixedString({ namedQuery }); + } + for (const bundledDocument of this.documents.values()) { + const documentMetadata = bundledDocument.metadata; + bundleString += this.lengthPrefixedString({ documentMetadata }); + // Write to the bundle if document exists. + const document = bundledDocument.document; + if (document) { + bundleString += this.lengthPrefixedString({ document }); + } + } + const metadata = { + id: this.bundleId, + createTime: toTimestamp(this.serializer, this.latestReadTime), + version: BUNDLE_VERSION, + totalDocuments: this.documents.size, + // TODO: it's not ideal to have to re-encode all of these strings multiple times + totalBytes: encoder.encode(bundleString).length + }; + // Prepends the metadata element to the bundleBuffer: `bundleBuffer` is the second argument to `Buffer.concat`. + bundleString = this.lengthPrefixedString({ metadata }) + bundleString; + return bundleString; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function buildDocumentSnapshotJsonBundle(db, document, docData, path) { + const builder = new BundleBuilder(db, AutoId.newId()); + builder.addBundleDocument(documentToDocumentSnapshotBundleData(path, docData, document)); + return builder.build(); +} +function buildQuerySnapshotJsonBundle(db, query, bundleName, parent, paths, docs, documentData) { + const docBundleDataArray = []; + for (let i = 0; i < docs.length; i++) { + docBundleDataArray.push(documentToDocumentSnapshotBundleData(paths[i], documentData[i], docs[i])); + } + const bundleData = { + name: bundleName, + query, + parent, + docBundleDataArray + }; + const builder = new BundleBuilder(db, bundleName); + builder.addBundleQuery(bundleData); + return builder.build(); +} +// Formats Document data for bundling a DocumentSnapshot. +function documentToDocumentSnapshotBundleData(path, documentData, document) { + return { + documentData, + documentKey: document.mutableCopy().key, + documentPath: path, + documentExists: true, + createdTime: document.createTime.toTimestamp(), + readTime: document.readTime.toTimestamp(), + versionTime: document.version.toTimestamp() + }; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const NOT_SUPPORTED = 'NOT SUPPORTED'; +/** + * Metadata about a snapshot, describing the state of the snapshot. + */ +class SnapshotMetadata { + /** @hideconstructor */ + constructor(hasPendingWrites, fromCache) { + this.hasPendingWrites = hasPendingWrites; + this.fromCache = fromCache; + } + /** + * Returns true if this `SnapshotMetadata` is equal to the provided one. + * + * @param other - The `SnapshotMetadata` to compare against. + * @returns true if this `SnapshotMetadata` is equal to the provided one. + */ + isEqual(other) { + return (this.hasPendingWrites === other.hasPendingWrites && + this.fromCache === other.fromCache); + } +} +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ +class DocumentSnapshot extends DocumentSnapshot$1 { + /** @hideconstructor protected */ + constructor(_firestore, userDataWriter, key, document, metadata, converter) { + super(_firestore, userDataWriter, key, document, converter); + this._firestore = _firestore; + this._firestoreImpl = _firestore; + this.metadata = metadata; + } + /** + * Returns whether or not the data exists. True if the document exists. + */ + exists() { + return super.exists(); + } + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * By default, `serverTimestamp()` values that have not yet been + * set to their final value will be returned as `null`. You can override + * this by passing an options object. + * + * @param options - An options object to configure how data is retrieved from + * the snapshot (for example the desired behavior for server timestamps that + * have not yet been set to their final value). + * @returns An `Object` containing all fields in the document or `undefined` if + * the document doesn't exist. + */ + data(options = {}) { + if (!this._document) { + return undefined; + } + else if (this._converter) { + // We only want to use the converter and create a new DocumentSnapshot + // if a converter has been provided. + const snapshot = new QueryDocumentSnapshot(this._firestore, this._userDataWriter, this._key, this._document, this.metadata, + /* converter= */ null); + return this._converter.fromFirestore(snapshot, options); + } + else { + return this._userDataWriter.convertValue(this._document.data.value, options.serverTimestamps); + } + } + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * By default, a `serverTimestamp()` that has not yet been set to + * its final value will be returned as `null`. You can override this by + * passing an options object. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @param options - An options object to configure how the field is retrieved + * from the snapshot (for example the desired behavior for server timestamps + * that have not yet been set to their final value). + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + // We are using `any` here to avoid an explicit cast by our users. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get(fieldPath, options = {}) { + if (this._document) { + const value = this._document.data.field(fieldPathFromArgument('DocumentSnapshot.get', fieldPath)); + if (value !== null) { + return this._userDataWriter.convertValue(value, options.serverTimestamps); + } + } + return undefined; + } + /** + * Returns a JSON-serializable representation of this `DocumentSnapshot` instance. + * + * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this + * `DocumentSnapshot` has pending writes. + */ + toJSON() { + if (this.metadata.hasPendingWrites) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'DocumentSnapshot.toJSON() attempted to serialize a document with pending writes. ' + + 'Await waitForPendingWrites() before invoking toJSON().'); + } + const document = this._document; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const result = {}; + result['type'] = DocumentSnapshot._jsonSchemaVersion; + result['bundle'] = ''; + result['bundleSource'] = 'DocumentSnapshot'; + result['bundleName'] = this._key.toString(); + if (!document || + !document.isValidDocument() || + !document.isFoundDocument()) { + return result; + } + const documentData = this._userDataWriter.convertObjectMap(document.data.value.mapValue.fields, 'previous'); + result['bundle'] = buildDocumentSnapshotJsonBundle(this._firestore, document, documentData, this.ref.path); + return result; + } +} +DocumentSnapshot._jsonSchemaVersion = 'firestore/documentSnapshot/1.0'; +DocumentSnapshot._jsonSchema = { + type: property('string', DocumentSnapshot._jsonSchemaVersion), + bundleSource: property('string', 'DocumentSnapshot'), + bundleName: property('string'), + bundle: property('string') +}; +function documentSnapshotFromJSON(db, json, converter) { + if (validateJSON(json, DocumentSnapshot._jsonSchema)) { + if (json.bundle === NOT_SUPPORTED) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'The provided JSON object was created in a client environment, which is not supported.'); + } + // Parse the bundle data. + const serializer = newSerializer(db._databaseId); + const bundleReader = createBundleReaderSync(json.bundle, serializer); + const elements = bundleReader.getElements(); + const bundleLoader = new BundleLoader(bundleReader.getMetadata(), serializer); + for (const element of elements) { + bundleLoader.addSizedElement(element); + } + // Ensure that we have the correct number of documents in the bundle. + const bundledDocuments = bundleLoader.documents; + if (bundledDocuments.length !== 1) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Expected bundle data to contain 1 document, but it contains ${bundledDocuments.length} documents.`); + } + // Build out the internal document data. + const document = fromDocument(serializer, bundledDocuments[0].document); + const documentKey = new DocumentKey(ResourcePath.fromString(json.bundleName)); + // Return the external facing DocumentSnapshot. + return new DocumentSnapshot(db, new LiteUserDataWriter(db), documentKey, document, new SnapshotMetadata( + /* hasPendingWrites= */ false, + /* fromCache= */ false), converter ? converter : null); + } +} +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ +class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * By default, `serverTimestamp()` values that have not yet been + * set to their final value will be returned as `null`. You can override + * this by passing an options object. + * + * @override + * @param options - An options object to configure how data is retrieved from + * the snapshot (for example the desired behavior for server timestamps that + * have not yet been set to their final value). + * @returns An `Object` containing all fields in the document. + */ + data(options = {}) { + return super.data(options); + } +} +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ +class QuerySnapshot { + /** @hideconstructor */ + constructor(_firestore, _userDataWriter, query, _snapshot) { + this._firestore = _firestore; + this._userDataWriter = _userDataWriter; + this._snapshot = _snapshot; + this.metadata = new SnapshotMetadata(_snapshot.hasPendingWrites, _snapshot.fromCache); + this.query = query; + } + /** An array of all the documents in the `QuerySnapshot`. */ + get docs() { + const result = []; + this.forEach(doc => result.push(doc)); + return result; + } + /** The number of documents in the `QuerySnapshot`. */ + get size() { + return this._snapshot.docs.size; + } + /** True if there are no documents in the `QuerySnapshot`. */ + get empty() { + return this.size === 0; + } + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ + forEach(callback, thisArg) { + this._snapshot.docs.forEach(doc => { + callback.call(thisArg, new QueryDocumentSnapshot(this._firestore, this._userDataWriter, doc.key, doc, new SnapshotMetadata(this._snapshot.mutatedKeys.has(doc.key), this._snapshot.fromCache), this.query.converter)); + }); + } + /** + * Returns an array of the documents changes since the last snapshot. If this + * is the first snapshot, all documents will be in the list as 'added' + * changes. + * + * @param options - `SnapshotListenOptions` that control whether metadata-only + * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger + * snapshot events. + */ + docChanges(options = {}) { + const includeMetadataChanges = !!options.includeMetadataChanges; + if (includeMetadataChanges && this._snapshot.excludesMetadataChanges) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'To include metadata changes with your document changes, you must ' + + 'also pass { includeMetadataChanges:true } to onSnapshot().'); + } + if (!this._cachedChanges || + this._cachedChangesIncludeMetadataChanges !== includeMetadataChanges) { + this._cachedChanges = changesFromSnapshot(this, includeMetadataChanges); + this._cachedChangesIncludeMetadataChanges = includeMetadataChanges; + } + return this._cachedChanges; + } + /** + * Returns a JSON-serializable representation of this `QuerySnapshot` instance. + * + * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this + * `QuerySnapshot` has pending writes. + */ + toJSON() { + if (this.metadata.hasPendingWrites) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'QuerySnapshot.toJSON() attempted to serialize a document with pending writes. ' + + 'Await waitForPendingWrites() before invoking toJSON().'); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const result = {}; + result['type'] = QuerySnapshot._jsonSchemaVersion; + result['bundleSource'] = 'QuerySnapshot'; + result['bundleName'] = AutoId.newId(); + const databaseId = this._firestore._databaseId.database; + const projectId = this._firestore._databaseId.projectId; + const parent = `projects/${projectId}/databases/${databaseId}/documents`; + const documents = []; + const documentData = []; + const paths = []; + this.docs.forEach(doc => { + if (doc._document === null) { + return; + } + documents.push(doc._document); + documentData.push(this._userDataWriter.convertObjectMap(doc._document.data.value.mapValue.fields, 'previous')); + paths.push(doc.ref.path); + }); + result['bundle'] = buildQuerySnapshotJsonBundle(this._firestore, this.query._query, result['bundleName'], parent, paths, documents, documentData); + return result; + } +} +QuerySnapshot._jsonSchemaVersion = 'firestore/querySnapshot/1.0'; +QuerySnapshot._jsonSchema = { + type: property('string', QuerySnapshot._jsonSchemaVersion), + bundleSource: property('string', 'QuerySnapshot'), + bundleName: property('string'), + bundle: property('string') +}; +function querySnapshotFromJSON(db, json, converter) { + if (validateJSON(json, QuerySnapshot._jsonSchema)) { + if (json.bundle === NOT_SUPPORTED) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'The provided JSON object was created in a client environment, which is not supported.'); + } + // Parse the bundle data. + const serializer = newSerializer(db._databaseId); + const bundleReader = createBundleReaderSync(json.bundle, serializer); + const elements = bundleReader.getElements(); + const bundleLoader = new BundleLoader(bundleReader.getMetadata(), serializer); + for (const element of elements) { + bundleLoader.addSizedElement(element); + } + if (bundleLoader.queries.length !== 1) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Snapshot data expected 1 query but found ${bundleLoader.queries.length} queries.`); + } + // Create an internal Query object from the named query in the bundle. + const query = fromBundledQuery(bundleLoader.queries[0].bundledQuery); + // Construct the arrays of document data for the query. + const bundledDocuments = bundleLoader.documents; + let documentSet = new DocumentSet(); + bundledDocuments.map(bundledDocument => { + const document = fromDocument(serializer, bundledDocument.document); + documentSet = documentSet.add(document); + }); + // Create a view snapshot of the query and documents. + const viewSnapshot = ViewSnapshot.fromInitialDocuments(query, documentSet, documentKeySet() /* Zero mutated keys signifies no pending writes. */, + /* fromCache= */ false, + /* hasCachedResults= */ false); + // Create an external Query object, required to construct the QuerySnapshot. + const externalQuery = new Query(db, converter ? converter : null, query); + // Return a new QuerySnapshot with all of the collected data. + return new QuerySnapshot(db, new LiteUserDataWriter(db), externalQuery, viewSnapshot); + } +} +/** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */ +function changesFromSnapshot(querySnapshot, includeMetadataChanges) { + if (querySnapshot._snapshot.oldDocs.isEmpty()) { + let index = 0; + return querySnapshot._snapshot.docChanges.map(change => { + const doc = new QueryDocumentSnapshot(querySnapshot._firestore, querySnapshot._userDataWriter, change.doc.key, change.doc, new SnapshotMetadata(querySnapshot._snapshot.mutatedKeys.has(change.doc.key), querySnapshot._snapshot.fromCache), querySnapshot.query.converter); + change.doc; + return { + type: 'added', + doc, + oldIndex: -1, + newIndex: index++ + }; + }); + } + else { + // A `DocumentSet` that is updated incrementally as changes are applied to use + // to lookup the index of a document. + let indexTracker = querySnapshot._snapshot.oldDocs; + return querySnapshot._snapshot.docChanges + .filter(change => includeMetadataChanges || change.type !== 3 /* ChangeType.Metadata */) + .map(change => { + const doc = new QueryDocumentSnapshot(querySnapshot._firestore, querySnapshot._userDataWriter, change.doc.key, change.doc, new SnapshotMetadata(querySnapshot._snapshot.mutatedKeys.has(change.doc.key), querySnapshot._snapshot.fromCache), querySnapshot.query.converter); + let oldIndex = -1; + let newIndex = -1; + if (change.type !== 0 /* ChangeType.Added */) { + oldIndex = indexTracker.indexOf(change.doc.key); + indexTracker = indexTracker.delete(change.doc.key); + } + if (change.type !== 1 /* ChangeType.Removed */) { + indexTracker = indexTracker.add(change.doc); + newIndex = indexTracker.indexOf(change.doc.key); + } + return { + type: resultChangeType(change.type), + doc, + oldIndex, + newIndex + }; + }); + } +} +function resultChangeType(type) { + switch (type) { + case 0 /* ChangeType.Added */: + return 'added'; + case 2 /* ChangeType.Modified */: + case 3 /* ChangeType.Metadata */: + return 'modified'; + case 1 /* ChangeType.Removed */: + return 'removed'; + default: + return fail(0xf03d, { type }); + } +} +// TODO(firestoreexp): Add tests for snapshotEqual with different snapshot +// metadata +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ +function snapshotEqual(left, right) { + if (left instanceof DocumentSnapshot && right instanceof DocumentSnapshot) { + return (left._firestore === right._firestore && + left._key.isEqual(right._key) && + (left._document === null + ? right._document === null + : left._document.isEqual(right._document)) && + left._converter === right._converter); + } + else if (left instanceof QuerySnapshot && right instanceof QuerySnapshot) { + return (left._firestore === right._firestore && + queryEqual(left.query, right.query) && + left.metadata.isEqual(right.metadata) && + left._snapshot.isEqual(right._snapshot)); + } + return false; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Reads the document referred to by this `DocumentReference`. + * + * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting + * for data from the server, but it may return cached data or fail if you are + * offline and the server cannot be reached. To specify this behavior, invoke + * {@link getDocFromCache} or {@link getDocFromServer}. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +function getDoc(reference) { + reference = cast(reference, DocumentReference); + const firestore = cast(reference.firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + return firestoreClientGetDocumentViaSnapshotListener(client, reference._key).then(snapshot => convertToDocSnapshot(firestore, reference, snapshot)); +} +class ExpUserDataWriter extends AbstractUserDataWriter { + constructor(firestore) { + super(); + this.firestore = firestore; + } + convertBytes(bytes) { + return new Bytes(bytes); + } + convertReference(name) { + const key = this.convertDocumentKey(name, this.firestore._databaseId); + return new DocumentReference(this.firestore, /* converter= */ null, key); + } +} +/** + * Reads the document referred to by this `DocumentReference` from cache. + * Returns an error if the document is not currently cached. + * + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +function getDocFromCache(reference) { + reference = cast(reference, DocumentReference); + const firestore = cast(reference.firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + const userDataWriter = new ExpUserDataWriter(firestore); + return firestoreClientGetDocumentFromLocalCache(client, reference._key).then(doc => new DocumentSnapshot(firestore, userDataWriter, reference._key, doc, new SnapshotMetadata(doc !== null && doc.hasLocalMutations, + /* fromCache= */ true), reference.converter)); +} +/** + * Reads the document referred to by this `DocumentReference` from the server. + * Returns an error if the network is not available. + * + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +function getDocFromServer(reference) { + reference = cast(reference, DocumentReference); + const firestore = cast(reference.firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + return firestoreClientGetDocumentViaSnapshotListener(client, reference._key, { + source: 'server' + }).then(snapshot => convertToDocSnapshot(firestore, reference, snapshot)); +} +/** + * Executes the query and returns the results as a `QuerySnapshot`. + * + * Note: `getDocs()` attempts to provide up-to-date data when possible by + * waiting for data from the server, but it may return cached data or fail if + * you are offline and the server cannot be reached. To specify this behavior, + * invoke {@link getDocsFromCache} or {@link getDocsFromServer}. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +function getDocs(query) { + query = cast(query, Query); + const firestore = cast(query.firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + const userDataWriter = new ExpUserDataWriter(firestore); + validateHasExplicitOrderByForLimitToLast(query._query); + return firestoreClientGetDocumentsViaSnapshotListener(client, query._query).then(snapshot => new QuerySnapshot(firestore, userDataWriter, query, snapshot)); +} +/** + * Executes the query and returns the results as a `QuerySnapshot` from cache. + * Returns an empty result set if no documents matching the query are currently + * cached. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +function getDocsFromCache(query) { + query = cast(query, Query); + const firestore = cast(query.firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + const userDataWriter = new ExpUserDataWriter(firestore); + return firestoreClientGetDocumentsFromLocalCache(client, query._query).then(snapshot => new QuerySnapshot(firestore, userDataWriter, query, snapshot)); +} +/** + * Executes the query and returns the results as a `QuerySnapshot` from the + * server. Returns an error if the network is not available. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +function getDocsFromServer(query) { + query = cast(query, Query); + const firestore = cast(query.firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + const userDataWriter = new ExpUserDataWriter(firestore); + return firestoreClientGetDocumentsViaSnapshotListener(client, query._query, { + source: 'server' + }).then(snapshot => new QuerySnapshot(firestore, userDataWriter, query, snapshot)); +} +function setDoc(reference, data, options) { + reference = cast(reference, DocumentReference); + const firestore = cast(reference.firestore, Firestore); + const convertedValue = applyFirestoreDataConverter(reference.converter, data, options); + const dataReader = newUserDataReader(firestore); + const parsed = parseSetData(dataReader, 'setDoc', reference._key, convertedValue, reference.converter !== null, options); + const mutation = parsed.toMutation(reference._key, Precondition.none()); + return executeWrite(firestore, [mutation]); +} +function updateDoc(reference, fieldOrUpdateData, value, ...moreFieldsAndValues) { + reference = cast(reference, DocumentReference); + const firestore = cast(reference.firestore, Firestore); + const dataReader = newUserDataReader(firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + fieldOrUpdateData = getModularInstance(fieldOrUpdateData); + let parsed; + if (typeof fieldOrUpdateData === 'string' || + fieldOrUpdateData instanceof FieldPath) { + parsed = parseUpdateVarargs(dataReader, 'updateDoc', reference._key, fieldOrUpdateData, value, moreFieldsAndValues); + } + else { + parsed = parseUpdateData(dataReader, 'updateDoc', reference._key, fieldOrUpdateData); + } + const mutation = parsed.toMutation(reference._key, Precondition.exists(true)); + return executeWrite(firestore, [mutation]); +} +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * @param reference - A reference to the document to delete. + * @returns A Promise resolved once the document has been successfully + * deleted from the backend (note that it won't resolve while you're offline). + */ +function deleteDoc(reference) { + const firestore = cast(reference.firestore, Firestore); + const mutations = [new DeleteMutation(reference._key, Precondition.none())]; + return executeWrite(firestore, mutations); +} +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend (Note that it + * won't resolve while you're offline). + */ +function addDoc(reference, data) { + const firestore = cast(reference.firestore, Firestore); + const docRef = doc(reference); + const convertedValue = applyFirestoreDataConverter(reference.converter, data); + const dataReader = newUserDataReader(reference.firestore); + const parsed = parseSetData(dataReader, 'addDoc', docRef._key, convertedValue, reference.converter !== null, {}); + const mutation = parsed.toMutation(docRef._key, Precondition.exists(false)); + return executeWrite(firestore, [mutation]).then(() => docRef); +} +function onSnapshot(reference, ...args) { + // onSnapshot for Query or Document. + reference = getModularInstance(reference); + let options = { + includeMetadataChanges: false, + source: 'default' + }; + let currArg = 0; + if (typeof args[currArg] === 'object' && !isPartialObserver(args[currArg])) { + options = args[currArg++]; + } + const internalOptions = { + includeMetadataChanges: options.includeMetadataChanges, + source: options.source + }; + if (isPartialObserver(args[currArg])) { + const userObserver = args[currArg]; + args[currArg] = userObserver.next?.bind(userObserver); + args[currArg + 1] = userObserver.error?.bind(userObserver); + args[currArg + 2] = userObserver.complete?.bind(userObserver); + } + let observer; + let firestore; + let internalQuery; + if (reference instanceof DocumentReference) { + firestore = cast(reference.firestore, Firestore); + internalQuery = newQueryForPath(reference._key.path); + observer = { + next: snapshot => { + if (args[currArg]) { + args[currArg](convertToDocSnapshot(firestore, reference, snapshot)); + } + }, + error: args[currArg + 1], + complete: args[currArg + 2] + }; + } + else { + const query = cast(reference, Query); + firestore = cast(query.firestore, Firestore); + internalQuery = query._query; + const userDataWriter = new ExpUserDataWriter(firestore); + observer = { + next: snapshot => { + if (args[currArg]) { + args[currArg](new QuerySnapshot(firestore, userDataWriter, query, snapshot)); + } + }, + error: args[currArg + 1], + complete: args[currArg + 2] + }; + validateHasExplicitOrderByForLimitToLast(reference._query); + } + const client = ensureFirestoreConfigured(firestore); + return firestoreClientListen(client, internalQuery, internalOptions, observer); +} +function onSnapshotResume(reference, snapshotJson, ...args) { + const db = getModularInstance(reference); + const json = normalizeSnapshotJsonFields(snapshotJson); + if (json.error) { + throw new FirestoreError(Code.INVALID_ARGUMENT, json.error); + } + let curArg = 0; + let options = undefined; + if (typeof args[curArg] === 'object' && !isPartialObserver(args[curArg])) { + options = args[curArg++]; + } + if (json.bundleSource === 'QuerySnapshot') { + let observer = null; + if (typeof args[curArg] === 'object' && isPartialObserver(args[curArg])) { + const userObserver = args[curArg++]; + observer = { + next: userObserver.next, + error: userObserver.error, + complete: userObserver.complete + }; + } + else { + observer = { + next: args[curArg++], + error: args[curArg++], + complete: args[curArg++] + }; + } + return onSnapshotQuerySnapshotBundle(db, json, options, observer, args[curArg]); + } + else if (json.bundleSource === 'DocumentSnapshot') { + let observer = null; + if (typeof args[curArg] === 'object' && isPartialObserver(args[curArg])) { + const userObserver = args[curArg++]; + observer = { + next: userObserver.next, + error: userObserver.error, + complete: userObserver.complete + }; + } + else { + observer = { + next: args[curArg++], + error: args[curArg++], + complete: args[curArg++] + }; + } + return onSnapshotDocumentSnapshotBundle(db, json, options, observer, args[curArg]); + } + else { + throw new FirestoreError(Code.INVALID_ARGUMENT, `unsupported bundle source: ${json.bundleSource}`); + } +} +function onSnapshotsInSync(firestore, arg) { + firestore = cast(firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + const observer = isPartialObserver(arg) + ? arg + : { + next: arg + }; + return firestoreClientAddSnapshotsInSyncListener(client, observer); +} +/** + * Locally writes `mutations` on the async queue. + * @internal + */ +function executeWrite(firestore, mutations) { + const client = ensureFirestoreConfigured(firestore); + return firestoreClientWrite(client, mutations); +} +/** + * Converts a {@link ViewSnapshot} that contains the single document specified by `ref` + * to a {@link DocumentSnapshot}. + */ +function convertToDocSnapshot(firestore, ref, snapshot) { + const doc = snapshot.docs.get(ref._key); + const userDataWriter = new ExpUserDataWriter(firestore); + return new DocumentSnapshot(firestore, userDataWriter, ref._key, doc, new SnapshotMetadata(snapshot.hasPendingWrites, snapshot.fromCache), ref.converter); +} +/** + * Ensures the data required to construct an {@link onSnapshot} listener exist in a `snapshotJson` + * object that originates from {@link DocumentSnapshot.toJSON} or {@link Querysnapshot.toJSON}. The + * data is normalized into a typed object. + * + * @param snapshotJson - The JSON object that the app provided to {@link onSnapshot}. + * @returns A normalized object that contains all of the required bundle JSON fields. If + * {@link snapshotJson} doesn't contain the required fields, or if the fields exist as empty + * strings, then the {@link snapshotJson.error} field will be a non empty string. + * + * @internal + */ +function normalizeSnapshotJsonFields(snapshotJson) { + const result = { + bundle: '', + bundleName: '', + bundleSource: '' + }; + const requiredKeys = ['bundle', 'bundleName', 'bundleSource']; + for (const key of requiredKeys) { + if (!(key in snapshotJson)) { + result.error = `snapshotJson missing required field: ${key}`; + break; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const value = snapshotJson[key]; + if (typeof value !== 'string') { + result.error = `snapshotJson field '${key}' must be a string.`; + break; + } + if (value.length === 0) { + result.error = `snapshotJson field '${key}' cannot be an empty string.`; + break; + } + if (key === 'bundle') { + result.bundle = value; + } + else if (key === 'bundleName') { + result.bundleName = value; + } + else if (key === 'bundleSource') { + result.bundleSource = value; + } + } + return result; +} +/** + * Loads the bundle in a separate task and then invokes {@link onSnapshot} with a + * {@link DocumentReference} for the document in the bundle. + * + * @param firestore - The {@link Firestore} instance for the {@link onSnapshot} operation request. + * @param json - The JSON bundle to load, produced by {@link DocumentSnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot + * listener. + * + * @internal + */ +function onSnapshotDocumentSnapshotBundle(db, json, options, observer, converter) { + let unsubscribed = false; + let internalUnsubscribe; + const loadTask = loadBundle(db, json.bundle); + loadTask + .then(() => { + if (!unsubscribed) { + const docReference = new DocumentReference(db, converter ? converter : null, DocumentKey.fromPath(json.bundleName)); + internalUnsubscribe = onSnapshot(docReference, options ? options : {}, observer); + } + }) + .catch(e => { + if (observer.error) { + observer.error(e); + } + return () => { }; + }); + return () => { + if (unsubscribed) { + return; + } + unsubscribed = true; + if (internalUnsubscribe) { + internalUnsubscribe(); + } + }; +} +/** + * Loads the bundle in a separate task and then invokes {@link onSnapshot} with a + * {@link Query} that represents the Query in the bundle. + * + * @param firestore - The {@link Firestore} instance for the {@link onSnapshot} operation request. + * @param json - The JSON bundle to load, produced by {@link QuerySnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot + * listener. + * + * @internal + */ +function onSnapshotQuerySnapshotBundle(db, json, options, observer, converter) { + let unsubscribed = false; + let internalUnsubscribe; + const loadTask = loadBundle(db, json.bundle); + loadTask + .then(() => namedQuery(db, json.bundleName)) + .then(query => { + if (query && !unsubscribed) { + const realQuery = query; + if (converter) { + realQuery.withConverter(converter); + } + internalUnsubscribe = onSnapshot(query, options ? options : {}, observer); + } + }) + .catch(e => { + if (observer.error) { + observer.error(e); + } + return () => { }; + }); + return () => { + if (unsubscribed) { + return; + } + unsubscribed = true; + if (internalUnsubscribe) { + internalUnsubscribe(); + } + }; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ +function getCountFromServer(query) { + const countQuerySpec = { + count: count() + }; + return getAggregateFromServer(query, countQuerySpec); +} +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregateFromServer(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ +function getAggregateFromServer(query, aggregateSpec) { + const firestore = cast(query.firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => { + return new AggregateImpl(alias, aggregate.aggregateType, aggregate._internalFieldPath); + }); + // Run the aggregation and convert the results + return firestoreClientRunAggregateQuery(client, query._query, internalAggregates).then(aggregateResult => convertToAggregateQuerySnapshot(firestore, query, aggregateResult)); +} +/** + * Converts the core aggregation result to an `AggregateQuerySnapshot` + * that can be returned to the consumer. + * @param query + * @param aggregateResult Core aggregation result + * @internal + */ +function convertToAggregateQuerySnapshot(firestore, query, aggregateResult) { + const userDataWriter = new ExpUserDataWriter(firestore); + const querySnapshot = new AggregateQuerySnapshot(query, userDataWriter, aggregateResult); + return querySnapshot; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class MemoryLocalCacheImpl { + constructor(settings) { + this.kind = 'memory'; + this._onlineComponentProvider = OnlineComponentProvider.provider; + if (settings?.garbageCollector) { + this._offlineComponentProvider = + settings.garbageCollector._offlineComponentProvider; + } + else { + this._offlineComponentProvider = { + build: () => new LruGcMemoryOfflineComponentProvider(undefined) + }; + } + } + toJSON() { + return { kind: this.kind }; + } +} +class PersistentLocalCacheImpl { + constructor(settings) { + this.kind = 'persistent'; + let tabManager; + if (settings?.tabManager) { + settings.tabManager._initialize(settings); + tabManager = settings.tabManager; + } + else { + tabManager = persistentSingleTabManager(undefined); + tabManager._initialize(settings); + } + this._onlineComponentProvider = tabManager._onlineComponentProvider; + this._offlineComponentProvider = tabManager._offlineComponentProvider; + } + toJSON() { + return { kind: this.kind }; + } +} +class MemoryEagerGarbageCollectorImpl { + constructor() { + this.kind = 'memoryEager'; + this._offlineComponentProvider = MemoryOfflineComponentProvider.provider; + } + toJSON() { + return { kind: this.kind }; + } +} +class MemoryLruGarbageCollectorImpl { + constructor(cacheSize) { + this.kind = 'memoryLru'; + this._offlineComponentProvider = { + build: () => new LruGcMemoryOfflineComponentProvider(cacheSize) + }; + } + toJSON() { + return { kind: this.kind }; + } +} +/** + * Creates an instance of `MemoryEagerGarbageCollector`. This is also the + * default garbage collector unless it is explicitly specified otherwise. + */ +function memoryEagerGarbageCollector() { + return new MemoryEagerGarbageCollectorImpl(); +} +/** + * Creates an instance of `MemoryLruGarbageCollector`. + * + * A target size can be specified as part of the setting parameter. The + * collector will start deleting documents once the cache size exceeds + * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes). + */ +function memoryLruGarbageCollector(settings) { + return new MemoryLruGarbageCollectorImpl(settings?.cacheSizeBytes); +} +/** + * Creates an instance of `MemoryLocalCache`. The instance can be set to + * `FirestoreSettings.cache` to tell the SDK which cache layer to use. + */ +function memoryLocalCache(settings) { + return new MemoryLocalCacheImpl(settings); +} +/** + * Creates an instance of `PersistentLocalCache`. The instance can be set to + * `FirestoreSettings.cache` to tell the SDK which cache layer to use. + * + * Persistent cache cannot be used in a Node.js environment. + */ +function persistentLocalCache(settings) { + return new PersistentLocalCacheImpl(settings); +} +class SingleTabManagerImpl { + constructor(forceOwnership) { + this.forceOwnership = forceOwnership; + this.kind = 'persistentSingleTab'; + } + toJSON() { + return { kind: this.kind }; + } + /** + * @internal + */ + _initialize(settings) { + this._onlineComponentProvider = OnlineComponentProvider.provider; + this._offlineComponentProvider = { + build: (onlineComponents) => new IndexedDbOfflineComponentProvider(onlineComponents, settings?.cacheSizeBytes, this.forceOwnership) + }; + } +} +class MultiTabManagerImpl { + constructor() { + this.kind = 'PersistentMultipleTab'; + } + toJSON() { + return { kind: this.kind }; + } + /** + * @internal + */ + _initialize(settings) { + this._onlineComponentProvider = OnlineComponentProvider.provider; + this._offlineComponentProvider = { + build: (onlineComponents) => new MultiTabOfflineComponentProvider(onlineComponents, settings?.cacheSizeBytes) + }; + } +} +/** + * Creates an instance of `PersistentSingleTabManager`. + * + * @param settings Configures the created tab manager. + */ +function persistentSingleTabManager(settings) { + return new SingleTabManagerImpl(settings?.forceOwnership); +} +/** + * Creates an instance of `PersistentMultipleTabManager`. + */ +function persistentMultipleTabManager() { + return new MultiTabManagerImpl(); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const DEFAULT_TRANSACTION_OPTIONS = { + maxAttempts: 5 +}; +function validateTransactionOptions(options) { + if (options.maxAttempts < 1) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Max attempts must be at least 1'); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It + * provides methods for adding writes to the write batch. None of the writes + * will be committed (or visible locally) until {@link WriteBatch.commit} is + * called. + */ +class WriteBatch { + /** @hideconstructor */ + constructor(_firestore, _commitHandler) { + this._firestore = _firestore; + this._commitHandler = _commitHandler; + this._mutations = []; + this._committed = false; + this._dataReader = newUserDataReader(_firestore); + } + set(documentRef, data, options) { + this._verifyNotCommitted(); + const ref = validateReference(documentRef, this._firestore); + const convertedValue = applyFirestoreDataConverter(ref.converter, data, options); + const parsed = parseSetData(this._dataReader, 'WriteBatch.set', ref._key, convertedValue, ref.converter !== null, options); + this._mutations.push(parsed.toMutation(ref._key, Precondition.none())); + return this; + } + update(documentRef, fieldOrUpdateData, value, ...moreFieldsAndValues) { + this._verifyNotCommitted(); + const ref = validateReference(documentRef, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + fieldOrUpdateData = getModularInstance(fieldOrUpdateData); + let parsed; + if (typeof fieldOrUpdateData === 'string' || + fieldOrUpdateData instanceof FieldPath) { + parsed = parseUpdateVarargs(this._dataReader, 'WriteBatch.update', ref._key, fieldOrUpdateData, value, moreFieldsAndValues); + } + else { + parsed = parseUpdateData(this._dataReader, 'WriteBatch.update', ref._key, fieldOrUpdateData); + } + this._mutations.push(parsed.toMutation(ref._key, Precondition.exists(true))); + return this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + delete(documentRef) { + this._verifyNotCommitted(); + const ref = validateReference(documentRef, this._firestore); + this._mutations = this._mutations.concat(new DeleteMutation(ref._key, Precondition.none())); + return this; + } + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `Promise` resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit (note that it won't + * resolve while you're offline). + */ + commit() { + this._verifyNotCommitted(); + this._committed = true; + if (this._mutations.length > 0) { + return this._commitHandler(this._mutations); + } + return Promise.resolve(); + } + _verifyNotCommitted() { + if (this._committed) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'A write batch can no longer be used after commit() ' + + 'has been called.'); + } + } +} +function validateReference(documentRef, firestore) { + documentRef = getModularInstance(documentRef); + if (documentRef.firestore !== firestore) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Provided document reference is from a different Firestore instance.'); + } + else { + return documentRef; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the +// legacy SDK. +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ +class Transaction$1 { + /** @hideconstructor */ + constructor(_firestore, _transaction) { + this._firestore = _firestore; + this._transaction = _transaction; + this._dataReader = newUserDataReader(_firestore); + } + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ + get(documentRef) { + const ref = validateReference(documentRef, this._firestore); + const userDataWriter = new LiteUserDataWriter(this._firestore); + return this._transaction.lookup([ref._key]).then(docs => { + if (!docs || docs.length !== 1) { + return fail(0x5de9); + } + const doc = docs[0]; + if (doc.isFoundDocument()) { + return new DocumentSnapshot$1(this._firestore, userDataWriter, doc.key, doc, ref.converter); + } + else if (doc.isNoDocument()) { + return new DocumentSnapshot$1(this._firestore, userDataWriter, ref._key, null, ref.converter); + } + else { + throw fail(0x4801, { + doc + }); + } + }); + } + set(documentRef, value, options) { + const ref = validateReference(documentRef, this._firestore); + const convertedValue = applyFirestoreDataConverter(ref.converter, value, options); + const parsed = parseSetData(this._dataReader, 'Transaction.set', ref._key, convertedValue, ref.converter !== null, options); + this._transaction.set(ref._key, parsed); + return this; + } + update(documentRef, fieldOrUpdateData, value, ...moreFieldsAndValues) { + const ref = validateReference(documentRef, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + fieldOrUpdateData = getModularInstance(fieldOrUpdateData); + let parsed; + if (typeof fieldOrUpdateData === 'string' || + fieldOrUpdateData instanceof FieldPath) { + parsed = parseUpdateVarargs(this._dataReader, 'Transaction.update', ref._key, fieldOrUpdateData, value, moreFieldsAndValues); + } + else { + parsed = parseUpdateData(this._dataReader, 'Transaction.update', ref._key, fieldOrUpdateData); + } + this._transaction.update(ref._key, parsed); + return this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + delete(documentRef) { + const ref = validateReference(documentRef, this._firestore); + this._transaction.delete(ref._key); + return this; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ +class Transaction extends Transaction$1 { + // This class implements the same logic as the Transaction API in the Lite SDK + // but is subclassed in order to return its own DocumentSnapshot types. + /** @hideconstructor */ + constructor(_firestore, _transaction) { + super(_firestore, _transaction); + this._firestore = _firestore; + } + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ + get(documentRef) { + const ref = validateReference(documentRef, this._firestore); + const userDataWriter = new ExpUserDataWriter(this._firestore); + return super + .get(documentRef) + .then(liteDocumentSnapshot => new DocumentSnapshot(this._firestore, userDataWriter, ref._key, liteDocumentSnapshot._document, new SnapshotMetadata( + /* hasPendingWrites= */ false, + /* fromCache= */ false), ref.converter)); + } +} +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ +function runTransaction(firestore, updateFunction, options) { + firestore = cast(firestore, Firestore); + const optionsWithDefaults = { + ...DEFAULT_TRANSACTION_OPTIONS, + ...options + }; + validateTransactionOptions(optionsWithDefaults); + const client = ensureFirestoreConfigured(firestore); + return firestoreClientTransaction(client, internalTransaction => updateFunction(new Transaction(firestore, internalTransaction)), optionsWithDefaults); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. + */ +function deleteField() { + return new DeleteFieldValueImpl('deleteField'); +} +/** + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to + * include a server-generated timestamp in the written data. + */ +function serverTimestamp() { + return new ServerTimestampFieldValueImpl('serverTimestamp'); +} +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array + * value that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements - The elements to union into the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()`. + */ +function arrayUnion(...elements) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new ArrayUnionFieldValueImpl('arrayUnion', elements); +} +/** + * Returns a special value that can be used with {@link (setDoc:1)} or {@link + * updateDoc:1} that tells the server to remove the given elements from any + * array value that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is not + * already an array it will be overwritten with an empty array. + * + * @param elements - The elements to remove from the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +function arrayRemove(...elements) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new ArrayRemoveFieldValueImpl('arrayRemove', elements); +} +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by + * the given value. + * + * If either the operand or the current field value uses floating point + * precision, all arithmetic follows IEEE 754 semantics. If both values are + * integers, values outside of JavaScript's safe number range + * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to + * precision loss. Furthermore, once processed by the Firestore backend, all + * integer operations are capped between -2^63 and 2^63-1. + * + * If the current field value is not of type `number`, or if the field does not + * yet exist, the transformation sets the field to the given value. + * + * @param n - The value to increment by. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +function increment(n) { + return new NumericIncrementFieldValueImpl('increment', n); +} +/** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ +function vector(values) { + return new VectorValue(values); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch} + * is 500. + * + * Unlike transactions, write batches are persisted offline and therefore are + * preferable when you don't need to condition your writes on read data. + * + * @returns A {@link WriteBatch} that can be used to atomically execute multiple + * writes. + */ +function writeBatch(firestore) { + firestore = cast(firestore, Firestore); + ensureFirestoreConfigured(firestore); + return new WriteBatch(firestore, mutations => executeWrite(firestore, mutations)); +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function setIndexConfiguration(firestore, jsonOrConfiguration) { + firestore = cast(firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + if (!client._uninitializedComponentsProvider || + client._uninitializedComponentsProvider._offline.kind === 'memory') { + // PORTING NOTE: We don't return an error if the user has not enabled + // persistence since `enableIndexeddbPersistence()` can fail on the Web. + logWarn('Cannot enable indexes when persistence is disabled'); + return Promise.resolve(); + } + const parsedIndexes = parseIndexes(jsonOrConfiguration); + return firestoreClientSetIndexConfiguration(client, parsedIndexes); +} +function parseIndexes(jsonOrConfiguration) { + const indexConfiguration = typeof jsonOrConfiguration === 'string' + ? tryParseJson(jsonOrConfiguration) + : jsonOrConfiguration; + const parsedIndexes = []; + if (Array.isArray(indexConfiguration.indexes)) { + for (const index of indexConfiguration.indexes) { + const collectionGroup = tryGetString(index, 'collectionGroup'); + const segments = []; + if (Array.isArray(index.fields)) { + for (const field of index.fields) { + const fieldPathString = tryGetString(field, 'fieldPath'); + const fieldPath = fieldPathFromDotSeparatedString('setIndexConfiguration', fieldPathString); + if (field.arrayConfig === 'CONTAINS') { + segments.push(new IndexSegment(fieldPath, 2 /* IndexKind.CONTAINS */)); + } + else if (field.order === 'ASCENDING') { + segments.push(new IndexSegment(fieldPath, 0 /* IndexKind.ASCENDING */)); + } + else if (field.order === 'DESCENDING') { + segments.push(new IndexSegment(fieldPath, 1 /* IndexKind.DESCENDING */)); + } + } + } + parsedIndexes.push(new FieldIndex(FieldIndex.UNKNOWN_ID, collectionGroup, segments, IndexState.empty())); + } + } + return parsedIndexes; +} +function tryParseJson(json) { + try { + return JSON.parse(json); + } + catch (e) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Failed to parse JSON: ' + e?.message); + } +} +function tryGetString(data, property) { + if (typeof data[property] !== 'string') { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Missing string value for: ' + property); + } + return data[property]; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `PersistentCacheIndexManager` for configuring persistent cache indexes used + * for local query execution. + * + * To use, call `getPersistentCacheIndexManager()` to get an instance. + */ +class PersistentCacheIndexManager { + /** @hideconstructor */ + constructor(_firestore) { + this._firestore = _firestore; + /** A type string to uniquely identify instances of this class. */ + this.type = 'PersistentCacheIndexManager'; + } +} +/** + * Returns the PersistentCache Index Manager used by the given `Firestore` + * object. + * + * @return The `PersistentCacheIndexManager` instance, or `null` if local + * persistent storage is not in use. + */ +function getPersistentCacheIndexManager(firestore) { + firestore = cast(firestore, Firestore); + const cachedInstance = persistentCacheIndexManagerByFirestore.get(firestore); + if (cachedInstance) { + return cachedInstance; + } + const client = ensureFirestoreConfigured(firestore); + if (client._uninitializedComponentsProvider?._offline.kind !== 'persistent') { + return null; + } + const instance = new PersistentCacheIndexManager(firestore); + persistentCacheIndexManagerByFirestore.set(firestore, instance); + return instance; +} +/** + * Enables the SDK to create persistent cache indexes automatically for local + * query execution when the SDK believes cache indexes can help improve + * performance. + * + * This feature is disabled by default. + */ +function enablePersistentCacheIndexAutoCreation(indexManager) { + setPersistentCacheIndexAutoCreationEnabled(indexManager, true); +} +/** + * Stops creating persistent cache indexes automatically for local query + * execution. The indexes which have been created by calling + * `enablePersistentCacheIndexAutoCreation()` still take effect. + */ +function disablePersistentCacheIndexAutoCreation(indexManager) { + setPersistentCacheIndexAutoCreationEnabled(indexManager, false); +} +/** + * Removes all persistent cache indexes. + * + * Please note this function will also deletes indexes generated by + * `setIndexConfiguration()`, which is deprecated. + */ +function deleteAllPersistentCacheIndexes(indexManager) { + const client = ensureFirestoreConfigured(indexManager._firestore); + const promise = firestoreClientDeleteAllFieldIndexes(client); + promise + .then(_ => logDebug('deleting all persistent cache indexes succeeded')) + .catch(error => logWarn('deleting all persistent cache indexes failed', error)); +} +function setPersistentCacheIndexAutoCreationEnabled(indexManager, isEnabled) { + const client = ensureFirestoreConfigured(indexManager._firestore); + const promise = firestoreClientSetPersistentCacheIndexAutoCreationEnabled(client, isEnabled); + promise + .then(_ => logDebug(`setting persistent cache index auto creation ` + + `isEnabled=${isEnabled} succeeded`)) + .catch(error => logWarn(`setting persistent cache index auto creation ` + + `isEnabled=${isEnabled} failed`, error)); +} +/** + * Maps `Firestore` instances to their corresponding + * `PersistentCacheIndexManager` instances. + * + * Use a `WeakMap` so that the mapping will be automatically dropped when the + * `Firestore` instance is garbage collected. This emulates a private member + * as described in https://goo.gle/454yvug. + */ +const persistentCacheIndexManagerByFirestore = new WeakMap(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @internal + * @private + * + * This function is for internal use only. + * + * Returns the `QueryTarget` representation of the given query. Returns `null` + * if the Firestore client associated with the given query has not been + * initialized or has been terminated. + * + * @param query - The Query to convert to proto representation. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function _internalQueryToProtoQueryTarget(query) { + const firestore = cast(query.firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + const serializer = client._onlineComponents?.datastore.serializer; + if (serializer === undefined) { + return null; + } + return toQueryTarget(serializer, queryToTarget(query._query)).queryTarget; +} +/** + * @internal + * @private + * + * This function is for internal use only. + * + * Returns `RunAggregationQueryRequest` which contains the proto representation + * of the given aggregation query request. Returns null if the Firestore client + * associated with the given query has not been initialized or has been + * terminated. + * + * @param query - The Query to convert to proto representation. + * @param aggregateSpec - The set of aggregations and their aliases. + */ +function _internalAggregationQueryToProtoRunAggregationQueryRequest(query, aggregateSpec) { + const aggregates = mapToArray(aggregateSpec, (aggregate, alias) => { + return new AggregateImpl(alias, aggregate.aggregateType, aggregate._internalFieldPath); + }); + const firestore = cast(query.firestore, Firestore); + const client = ensureFirestoreConfigured(firestore); + const serializer = client._onlineComponents?.datastore.serializer; + if (serializer === undefined) { + return null; + } + return toRunAggregationQueryRequest(serializer, queryToAggregateTarget(query._query), aggregates, + /* skipAliasing= */ true).request; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Testing hooks for use by Firestore's integration test suite to reach into the + * SDK internals to validate logic and behavior that is not visible from the + * public API surface. + * + * @internal + */ +class TestingHooks { + constructor() { + throw new Error('instances of this class should not be created'); + } + /** + * Registers a callback to be notified when an existence filter mismatch + * occurs in the Watch listen stream. + * + * The relative order in which callbacks are notified is unspecified; do not + * rely on any particular ordering. If a given callback is registered multiple + * times then it will be notified multiple times, once per registration. + * + * @param callback the callback to invoke upon existence filter mismatch. + * + * @return a function that, when called, unregisters the given callback; only + * the first invocation of the returned function does anything; all subsequent + * invocations do nothing. + */ + static onExistenceFilterMismatch(callback) { + return TestingHooksSpiImpl.instance.onExistenceFilterMismatch(callback); + } +} +/** + * The implementation of `TestingHooksSpi`. + */ +class TestingHooksSpiImpl { + constructor() { + this.existenceFilterMismatchCallbacksById = new Map(); + } + static get instance() { + if (!testingHooksSpiImplInstance) { + testingHooksSpiImplInstance = new TestingHooksSpiImpl(); + setTestingHooksSpi(testingHooksSpiImplInstance); + } + return testingHooksSpiImplInstance; + } + notifyOnExistenceFilterMismatch(info) { + this.existenceFilterMismatchCallbacksById.forEach(callback => callback(info)); + } + onExistenceFilterMismatch(callback) { + const id = Symbol(); + const callbacks = this.existenceFilterMismatchCallbacksById; + callbacks.set(id, callback); + return () => callbacks.delete(id); + } +} +let testingHooksSpiImplInstance = null; + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +registerFirestore('node'); + +export { AbstractUserDataWriter, AggregateField, AggregateQuerySnapshot, Bytes, CACHE_SIZE_UNLIMITED, CollectionReference, DocumentReference, DocumentSnapshot, FieldPath, FieldValue, Firestore, FirestoreError, GeoPoint, LoadBundleTask, PersistentCacheIndexManager, Query, QueryCompositeFilterConstraint, QueryConstraint, QueryDocumentSnapshot, QueryEndAtConstraint, QueryFieldFilterConstraint, QueryLimitConstraint, QueryOrderByConstraint, QuerySnapshot, QueryStartAtConstraint, SnapshotMetadata, Timestamp, Transaction, VectorValue, WriteBatch, AutoId as _AutoId, ByteString as _ByteString, DatabaseId as _DatabaseId, DocumentKey as _DocumentKey, EmptyAppCheckTokenProvider as _EmptyAppCheckTokenProvider, EmptyAuthCredentialsProvider as _EmptyAuthCredentialsProvider, FieldPath$1 as _FieldPath, TestingHooks as _TestingHooks, cast as _cast, debugAssert as _debugAssert, _internalAggregationQueryToProtoRunAggregationQueryRequest, _internalQueryToProtoQueryTarget, isBase64Available as _isBase64Available, logWarn as _logWarn, validateIsNotUsedTogether as _validateIsNotUsedTogether, addDoc, aggregateFieldEqual, aggregateQuerySnapshotEqual, and, arrayRemove, arrayUnion, average, clearIndexedDbPersistence, collection, collectionGroup, connectFirestoreEmulator, count, deleteAllPersistentCacheIndexes, deleteDoc, deleteField, disableNetwork, disablePersistentCacheIndexAutoCreation, doc, documentId, documentSnapshotFromJSON, enableIndexedDbPersistence, enableMultiTabIndexedDbPersistence, enableNetwork, enablePersistentCacheIndexAutoCreation, endAt, endBefore, ensureFirestoreConfigured, executeWrite, getAggregateFromServer, getCountFromServer, getDoc, getDocFromCache, getDocFromServer, getDocs, getDocsFromCache, getDocsFromServer, getFirestore, getPersistentCacheIndexManager, increment, initializeFirestore, limit, limitToLast, loadBundle, memoryEagerGarbageCollector, memoryLocalCache, memoryLruGarbageCollector, namedQuery, onSnapshot, onSnapshotResume, onSnapshotsInSync, or, orderBy, persistentLocalCache, persistentMultipleTabManager, persistentSingleTabManager, query, queryEqual, querySnapshotFromJSON, refEqual, runTransaction, serverTimestamp, setDoc, setIndexConfiguration, setLogLevel, snapshotEqual, startAfter, startAt, sum, terminate, updateDoc, vector, waitForPendingWrites, where, writeBatch }; +//# sourceMappingURL=index.node.mjs.map diff --git a/frontend-old/node_modules/@firebase/firestore/dist/index.node.mjs.map b/frontend-old/node_modules/@firebase/firestore/dist/index.node.mjs.map new file mode 100644 index 0000000..f65a6f5 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/index.node.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.node.mjs","sources":["../src/auth/user.ts","../src/core/version.ts","../src/platform/node/format_json.ts","../src/util/log.ts","../src/util/assert.ts","../src/util/error.ts","../src/util/promise.ts","../src/api/credentials.ts","../src/platform/node/random_bytes.ts","../src/util/misc.ts","../src/model/path.ts","../src/model/document_key.ts","../src/util/input_validation.ts","../src/util/json_validation.ts","../src/lite-api/timestamp.ts","../src/core/snapshot_version.ts","../src/model/field_index.ts","../src/local/persistence_transaction.ts","../src/local/local_store.ts","../src/local/persistence_promise.ts","../src/local/simple_db.ts","../src/local/index_backfiller.ts","../src/core/listen_sequence.ts","../src/local/encoded_resource_path.ts","../src/local/indexeddb_schema_legacy.ts","../src/local/indexeddb_sentinels.ts","../src/local/indexeddb_transaction.ts","../src/util/obj.ts","../src/util/sorted_map.ts","../src/util/sorted_set.ts","../src/model/field_mask.ts","../src/platform/node/base64.ts","../src/util/byte_string.ts","../src/model/normalize.ts","../src/model/server_timestamps.ts","../src/core/database_info.ts","../src/util/types.ts","../src/model/values.ts","../src/model/object_value.ts","../src/model/document.ts","../src/core/bound.ts","../src/core/order_by.ts","../src/core/filter.ts","../src/core/target.ts","../src/core/query.ts","../src/util/obj_map.ts","../src/model/collections.ts","../src/remote/number_serializer.ts","../src/model/transform_operation.ts","../src/model/mutation.ts","../src/model/mutation_batch.ts","../src/model/overlay.ts","../src/remote/existence_filter.ts","../src/remote/rpc_error.ts","../src/util/base64_decode_error.ts","../src/util/testing_hooks_spi.ts","../src/platform/node/text_serializer.ts","../src/remote/bloom_filter.ts","../src/remote/remote_event.ts","../src/remote/watch_change.ts","../src/remote/serializer.ts","../src/local/target_data.ts","../src/local/local_serializer.ts","../src/local/indexeddb_bundle_cache.ts","../src/local/indexeddb_document_overlay_cache.ts","../src/local/indexeddb_globals_cache.ts","../src/index/firestore_index_value_writer.ts","../src/index/ordered_code_writer.ts","../src/index/index_byte_encoder.ts","../src/index/index_entry.ts","../src/model/target_index_matcher.ts","../src/util/logic_utils.ts","../src/local/memory_index_manager.ts","../src/local/indexeddb_index_manager.ts","../src/local/indexeddb_mutation_batch_impl.ts","../src/local/indexeddb_mutation_queue.ts","../src/core/target_id_generator.ts","../src/local/indexeddb_target_cache.ts","../src/local/lru_garbage_collector.ts","../src/local/lru_garbage_collector_impl.ts","../src/local/indexeddb_lru_delegate_impl.ts","../src/local/remote_document_change_buffer.ts","../src/local/indexeddb_remote_document_cache.ts","../src/local/indexeddb_schema.ts","../src/local/overlayed_document.ts","../src/local/local_documents_view.ts","../src/local/memory_bundle_cache.ts","../src/local/memory_document_overlay_cache.ts","../src/local/memory_globals_cache.ts","../src/local/reference_set.ts","../src/local/memory_mutation_queue.ts","../src/local/memory_remote_document_cache.ts","../src/local/memory_target_cache.ts","../src/local/memory_persistence.ts","../src/local/indexeddb_schema_converter.ts","../src/local/indexeddb_persistence.ts","../src/util/array.ts","../src/local/local_store_impl.ts","../src/local/query_context.ts","../src/local/query_engine.ts","../src/local/shared_client_state_schema.ts","../src/local/shared_client_state.ts","../src/remote/connectivity_monitor_noop.ts","../src/remote/stream_bridge.ts","../src/util/debug_uid.ts","../src/util/node_api.ts","../src/platform/node/grpc_connection.ts","../src/platform/node/load_protos.ts","../src/platform/node/connection.ts","../src/platform/node/dom.ts","../src/platform/node/serializer.ts","../src/remote/backoff.ts","../src/remote/persistent_stream.ts","../src/remote/datastore.ts","../src/remote/online_state_tracker.ts","../src/remote/remote_store.ts","../src/util/async_queue.ts","../src/model/document_set.ts","../src/core/view_snapshot.ts","../src/core/event_manager.ts","../src/local/local_view_changes.ts","../src/core/bundle_impl.ts","../src/core/view.ts","../src/core/sync_engine_impl.ts","../src/core/component_provider.ts","../src/util/byte_stream.ts","../src/platform/node/byte_stream_reader.ts","../src/util/async_observer.ts","../src/util/bundle_reader.ts","../src/util/bundle_reader_impl.ts","../src/util/bundle_reader_sync_impl.ts","../src/core/transaction.ts","../src/core/transaction_runner.ts","../src/core/firestore_client.ts","../src/api/long_polling_options.ts","../src/lite-api/components.ts","../src/lite-api/settings.ts","../src/lite-api/database.ts","../src/lite-api/reference.ts","../src/util/async_queue_impl.ts","../src/api/bundle.ts","../src/api/database.ts","../src/register.ts","../src/core/aggregate.ts","../src/lite-api/aggregate_types.ts","../src/lite-api/bytes.ts","../src/lite-api/field_path.ts","../src/lite-api/field_value.ts","../src/lite-api/geo_point.ts","../src/lite-api/vector_value.ts","../src/lite-api/user_data_reader.ts","../src/lite-api/snapshot.ts","../src/lite-api/query.ts","../src/lite-api/user_data_writer.ts","../src/lite-api/reference_impl.ts","../src/lite-api/aggregate.ts","../src/api/observer.ts","../test/unit/util/bundle_data.ts","../src/util/bundle_builder_impl.ts","../src/platform/node/snapshot_to_json.ts","../src/api/snapshot.ts","../src/api/reference_impl.ts","../src/api/aggregate.ts","../src/api/cache_config.ts","../src/core/transaction_options.ts","../src/lite-api/write_batch.ts","../src/lite-api/transaction.ts","../src/api/transaction.ts","../src/lite-api/field_value_impl.ts","../src/api/write_batch.ts","../src/api/index_configuration.ts","../src/api/persistent_cache_index_manager.ts","../src/remote/internal_serializer.ts","../src/util/testing_hooks.ts","../src/index.node.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Simple wrapper around a nullable UID. Mostly exists to make code more\n * readable.\n */\nexport class User {\n /** A user with a null UID. */\n static readonly UNAUTHENTICATED = new User(null);\n\n // TODO(mikelehen): Look into getting a proper uid-equivalent for\n // non-FirebaseAuth providers.\n static readonly GOOGLE_CREDENTIALS = new User('google-credentials-uid');\n static readonly FIRST_PARTY = new User('first-party-uid');\n static readonly MOCK_USER = new User('mock-user');\n\n constructor(readonly uid: string | null) {}\n\n isAuthenticated(): boolean {\n return this.uid != null;\n }\n\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */\n toKey(): string {\n if (this.isAuthenticated()) {\n return 'uid:' + this.uid;\n } else {\n return 'anonymous-user';\n }\n }\n\n isEqual(otherUser: User): boolean {\n return otherUser.uid === this.uid;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The semver (www.semver.org) version of the SDK. */\nimport { version } from '../../../firebase/package.json';\nexport let SDK_VERSION = version;\nexport function setSDKVersion(version: string): void {\n SDK_VERSION = version;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { inspect } from 'util';\n\n/** Formats an object as a JSON string, suitable for logging. */\nexport function formatJSON(value: unknown): string {\n // util.inspect() results in much more readable output than JSON.stringify()\n return inspect(value, { depth: 100 });\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel, LogLevelString } from '@firebase/logger';\n\nimport { SDK_VERSION } from '../core/version';\nimport { formatJSON } from '../platform/format_json';\n\nexport { LogLevel, LogLevelString };\n\nconst logClient = new Logger('@firebase/firestore');\n\n// Helper methods are needed because variables can't be exported as read/write\nexport function getLogLevel(): LogLevel {\n return logClient.logLevel;\n}\n\n/**\n * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).\n *\n * @param logLevel - The verbosity you set for activity and error logging. Can\n * be any of the following values:\n *\n *

    \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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 *\n * @param code generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(\n code: number,\n message: string,\n context?: Record\n): never;\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 *\n * @param id generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(id: number, context?: Record): never;\n\nexport function fail(\n id: number,\n messageOrContext?: string | Record,\n context?: Record\n): never {\n let message = 'Unexpected state';\n if (typeof messageOrContext === 'string') {\n message = messageOrContext;\n } else {\n context = messageOrContext;\n }\n _fail(id, message, context);\n}\n\nfunction _fail(\n id: number,\n failure: string,\n context?: Record\n): never {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n let message = `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ${failure} (ID: ${id.toString(\n 16\n )})`;\n if (context !== undefined) {\n try {\n const stringContext = JSON.stringify(context);\n message += ' CONTEXT: ' + stringContext;\n } catch (e) {\n message += ' CONTEXT: ' + context;\n }\n }\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 *\n * @param id generate a new unique value with `yarn assertion-idgenerate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n assertion: boolean,\n id: number,\n message: string,\n context?: Record\n): asserts assertion;\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 *\n * @param id generate a new unique value with `yarn assertion-id:generate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n assertion: boolean,\n id: number,\n context?: Record\n): asserts assertion;\n\nexport function hardAssert(\n assertion: boolean,\n id: number,\n messageOrContext?: string | Record,\n context?: Record\n): asserts assertion {\n let message = 'Unexpected state';\n if (typeof messageOrContext === 'string') {\n message = messageOrContext;\n } else {\n context = messageOrContext;\n }\n\n if (!assertion) {\n _fail(id, message, context);\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(0xdeb6, 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 { FirebaseApp, _isFirebaseServerApp } from '@firebase/app';\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 0xa539,\n 'Invalid tokenData returned from getToken()',\n { 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 0xa540,\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 0x7c5d,\n 'Invalid tokenData returned from getToken()',\n { 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 0x0807,\n 'Received invalid UID',\n { 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 private serverAppAppCheckToken: string | null = null;\n\n constructor(\n app: FirebaseApp,\n private appCheckProvider: Provider\n ) {\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n }\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n hardAssert(\n this.tokenListener === undefined,\n 0x0db8,\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 if (this.serverAppAppCheckToken) {\n return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n }\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 0xae0e,\n 'Invalid tokenResult returned from getToken()',\n { 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 private serverAppAppCheckToken: string | null = null;\n\n constructor(\n app: FirebaseApp,\n private appCheckProvider: Provider\n ) {\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n appCheckProvider.onInit(appCheck => {\n this.appCheck = appCheck;\n });\n }\n\n getToken(): Promise {\n if (this.serverAppAppCheckToken) {\n return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n }\n\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 0x0d8e,\n 'Invalid tokenResult returned from getToken()',\n { 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 { randomBytes as generateRandomBytes } from 'crypto';\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 return generateRandomBytes(nBytes);\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\n/** Compare strings in UTF-8 encoded byte order */\nexport function compareUtf8Strings(left: string, right: string): number {\n // Find the first differing character (a.k.a. \"UTF-16 code unit\") in the two strings and,\n // if found, use that character to determine the relative ordering of the two strings as a\n // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by\n // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8\n // and UTF-16 happen to represent Unicode code points.\n //\n // After finding the first pair of differing characters, there are two cases:\n //\n // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or\n // both are surrogates from a surrogate pair (that collectively represent code points greater\n // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the\n // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is\n // sufficient.\n //\n // Case 2: One character is a surrogate and the other is not. In this case the surrogate-\n // containing string is always ordered after the non-surrogate. This is because surrogates are\n // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations\n // and are lexicographically greater than the 1, 2, or 3-byte representations of code points\n // less than or equal to 0xFFFF.\n //\n // An example of why Case 2 is required is comparing the following two Unicode code points:\n //\n // |-----------------------|------------|---------------------|-----------------|\n // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding |\n // |-----------------------|------------|---------------------|-----------------|\n // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD |\n // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 |\n // |-----------------------|------------|---------------------|-----------------|\n //\n // A lexicographical comparison of the UTF-8 encodings of these code points would order\n // \"Replacement Character\" _before_ \"Grinning Face\" because 0xEF is less than 0xF0. However, a\n // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously\n // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out,\n // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate\n // pair with those that do not.\n const length = Math.min(left.length, right.length);\n for (let i = 0; i < length; i++) {\n const leftChar = left.charAt(i);\n const rightChar = right.charAt(i);\n if (leftChar !== rightChar) {\n return isSurrogate(leftChar) === isSurrogate(rightChar)\n ? primitiveComparator(leftChar, rightChar)\n : isSurrogate(leftChar)\n ? 1\n : -1;\n }\n }\n\n // Use the lengths of the strings to determine the overall comparison result since either the\n // strings were equal or one is a prefix of the other.\n return primitiveComparator(left.length, right.length);\n}\n\nconst MIN_SURROGATE = 0xd800;\nconst MAX_SURROGATE = 0xdfff;\n\nexport function isSurrogate(s: string): boolean {\n debugAssert(s.length === 1, `s.length == ${s.length}, but expected 1`);\n const c = s.charCodeAt(0);\n return c >= MIN_SURROGATE && c <= MAX_SURROGATE;\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 { Integer } from '@firebase/webchannel-wrapper/bloom-blob';\n\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { compareUtf8Strings, primitiveComparator } from '../util/misc';\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(0x027d, 'offset out of range', {\n offset,\n range: segments.length\n });\n }\n\n if (length === undefined) {\n length = segments.length - offset;\n } else if (length > segments.length - offset) {\n fail(0x06d2, 'length out of range', {\n length,\n range: segments.length - offset\n });\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 /**\n * Compare 2 paths segment by segment, prioritizing numeric IDs\n * (e.g., \"__id123__\") in numeric ascending order, followed by string\n * segments in lexicographical order.\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 comparison = BasePath.compareSegments(p1.get(i), p2.get(i));\n if (comparison !== 0) {\n return comparison;\n }\n }\n return primitiveComparator(p1.length, p2.length);\n }\n\n private static compareSegments(lhs: string, rhs: string): number {\n const isLhsNumeric = BasePath.isNumericId(lhs);\n const isRhsNumeric = BasePath.isNumericId(rhs);\n\n if (isLhsNumeric && !isRhsNumeric) {\n // Only lhs is numeric\n return -1;\n } else if (!isLhsNumeric && isRhsNumeric) {\n // Only rhs is numeric\n return 1;\n } else if (isLhsNumeric && isRhsNumeric) {\n // both numeric\n return BasePath.extractNumericId(lhs).compare(\n BasePath.extractNumericId(rhs)\n );\n } else {\n // both non-numeric\n return compareUtf8Strings(lhs, rhs);\n }\n }\n\n // Checks if a segment is a numeric ID (starts with \"__id\" and ends with \"__\").\n private static isNumericId(segment: string): boolean {\n return segment.startsWith('__id') && segment.endsWith('__');\n }\n\n private static extractNumericId(segment: string): Integer {\n return Integer.fromString(segment.substring(4, segment.length - 2));\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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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(0x3029, 'Unknown wrong type', { 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 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isPlainObject } from '../util/input_validation';\n\nimport { Code, FirestoreError } from './error';\n\n/**\n * A list of data types Firestore objects may serialize in their toJSON implemenetations.\n * @private\n * @internal\n */\nexport type JsonTypeDesc =\n | 'object'\n | 'string'\n | 'number'\n | 'boolean'\n | 'null'\n | 'undefined';\n\n/**\n * An association of JsonTypeDesc values to their native types.\n * @private\n * @internal\n */\nexport type TSType = T extends 'object'\n ? object\n : T extends 'string'\n ? string\n : T extends 'number'\n ? number\n : T extends 'boolean'\n ? boolean\n : T extends 'null'\n ? null\n : T extends 'undefined'\n ? undefined\n : never;\n\n/**\n * The representation of a JSON object property name and its type value.\n * @private\n * @internal\n */\nexport interface Property {\n value?: TSType;\n typeString: JsonTypeDesc;\n}\n\n/**\n * A type Firestore data types may use to define the fields used in their JSON serialization.\n * @private\n * @internal\n */\nexport interface JsonSchema {\n [key: string]: Property;\n}\n\n/**\n * Associates the JSON property type to the native type and sets them to be Required.\n * @private\n * @internal\n */\nexport type Json = {\n [K in keyof T]: Required['value'];\n};\n\n/**\n * Helper function to define a JSON schema {@link Property}.\n * @private\n * @internal\n */\nexport function property(\n typeString: T,\n optionalValue?: TSType\n): Property {\n const result: Property = {\n typeString\n };\n if (optionalValue) {\n result.value = optionalValue;\n }\n return result;\n}\n\n/**\n * Validates the JSON object based on the provided schema, and narrows the type to the provided\n * JSON schema.\n * @private\n * @internal\n *\n * @param json A JSON object to validate.\n * @param scheme a {@link JsonSchema} that defines the properties to validate.\n * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise.\n */\nexport function validateJSON(\n json: object,\n schema: S\n): json is Json {\n if (!isPlainObject(json)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'JSON must be an object');\n }\n let error: string | undefined = undefined;\n for (const key in schema) {\n if (schema[key]) {\n const typeString = schema[key].typeString;\n const value: { value: unknown } | undefined =\n 'value' in schema[key] ? { value: schema[key].value } : undefined;\n if (!(key in json)) {\n error = `JSON missing required field: '${key}'`;\n break;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const fieldValue = (json as any)[key];\n if (typeString && typeof fieldValue !== typeString) {\n error = `JSON field '${key}' must be a ${typeString}.`;\n break;\n } else if (value !== undefined && fieldValue !== value.value) {\n error = `Expected '${key}' field to equal '${value.value}'`;\n break;\n }\n }\n }\n if (error) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, error);\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 { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\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 static _jsonSchemaVersion: string = 'firestore/timestamp/1.0';\n static _jsonSchema = {\n type: property('string', Timestamp._jsonSchemaVersion),\n seconds: property('number'),\n nanoseconds: property('number')\n };\n\n /**\n * Returns a JSON-serializable representation of this `Timestamp`.\n */\n toJSON(): { seconds: number; nanoseconds: number; type: string } {\n return {\n type: Timestamp._jsonSchemaVersion,\n seconds: this.seconds,\n nanoseconds: this.nanoseconds\n };\n }\n\n /**\n * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}.\n */\n static fromJSON(json: object): Timestamp {\n if (validateJSON(json, Timestamp._jsonSchema)) {\n return new Timestamp(json.seconds, json.nanoseconds);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Timestamp from JSON.'\n );\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 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(0xe830, '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 { getGlobal, 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 `indexedDB` are guarded by SimpleDb.isAvailable() and getGlobal()\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 lastClosedDbVersion: number | null = null;\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 const globals = getGlobal();\n return wrapRequest(\n globals.indexedDB.deleteDatabase(name)\n ).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\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 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { FirestoreError } from '../api';\nimport { DocumentMap } from '../model/collections';\nimport {\n IndexOffset,\n indexOffsetComparator,\n newIndexOffsetFromDocument\n} from '../model/field_index';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { logDebug } from '../util/log';\n\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from './local_store';\nimport { LocalWriteResult } from './local_store_impl';\nimport { Persistence, Scheduler } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { isIndexedDbTransactionError } from './simple_db';\n\nconst LOG_TAG = 'IndexBackfiller';\n\n/** How long we wait to try running index backfill after SDK initialization. */\nconst INITIAL_BACKFILL_DELAY_MS = 15 * 1000;\n\n/** Minimum amount of time between backfill checks, after the first one. */\nconst REGULAR_BACKFILL_DELAY_MS = 60 * 1000;\n\n/** The maximum number of documents to process each time backfill() is called. */\nconst MAX_DOCUMENTS_TO_PROCESS = 50;\n\n/** This class is responsible for the scheduling of Index Backfiller. */\nexport class IndexBackfillerScheduler implements Scheduler {\n private task: DelayedOperation | null;\n\n constructor(\n private readonly asyncQueue: AsyncQueue,\n private readonly backfiller: IndexBackfiller\n ) {\n this.task = null;\n }\n\n start(): void {\n debugAssert(\n this.task === null,\n 'Cannot start an already started IndexBackfillerScheduler'\n );\n this.schedule(INITIAL_BACKFILL_DELAY_MS);\n }\n\n stop(): void {\n if (this.task) {\n this.task.cancel();\n this.task = null;\n }\n }\n\n get started(): boolean {\n return this.task !== null;\n }\n\n private schedule(delay: number): void {\n debugAssert(\n this.task === null,\n 'Cannot schedule IndexBackfiller while a task is pending'\n );\n logDebug(LOG_TAG, `Scheduled in ${delay}ms`);\n this.task = this.asyncQueue.enqueueAfterDelay(\n TimerId.IndexBackfill,\n delay,\n async () => {\n this.task = null;\n try {\n const documentsProcessed = await this.backfiller.backfill();\n logDebug(LOG_TAG, `Documents written: ${documentsProcessed}`);\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(\n LOG_TAG,\n 'Ignoring IndexedDB error during index backfill: ',\n e\n );\n } else {\n await ignoreIfPrimaryLeaseLoss(e as FirestoreError);\n }\n }\n await this.schedule(REGULAR_BACKFILL_DELAY_MS);\n }\n );\n }\n}\n\n/** Implements the steps for backfilling indexes. */\nexport class IndexBackfiller {\n constructor(\n /**\n * LocalStore provides access to IndexManager and LocalDocumentView.\n * These properties will update when the user changes. Consequently,\n * making a local copy of IndexManager and LocalDocumentView will require\n * updates over time. The simpler solution is to rely on LocalStore to have\n * an up-to-date references to IndexManager and LocalDocumentStore.\n */\n private readonly localStore: LocalStore,\n private readonly persistence: Persistence\n ) {}\n\n async backfill(\n maxDocumentsToProcess: number = MAX_DOCUMENTS_TO_PROCESS\n ): Promise {\n return this.persistence.runTransaction(\n 'Backfill Indexes',\n 'readwrite-primary',\n txn => this.writeIndexEntries(txn, maxDocumentsToProcess)\n );\n }\n\n /** Writes index entries until the cap is reached. Returns the number of documents processed. */\n private writeIndexEntries(\n transaction: PersistenceTransaction,\n maxDocumentsToProcess: number\n ): PersistencePromise {\n const processedCollectionGroups = new Set();\n let documentsRemaining = maxDocumentsToProcess;\n let continueLoop = true;\n return PersistencePromise.doWhile(\n () => continueLoop === true && documentsRemaining > 0,\n () => {\n return this.localStore.indexManager\n .getNextCollectionGroupToUpdate(transaction)\n .next((collectionGroup: string | null) => {\n if (\n collectionGroup === null ||\n processedCollectionGroups.has(collectionGroup)\n ) {\n continueLoop = false;\n } else {\n logDebug(LOG_TAG, `Processing collection: ${collectionGroup}`);\n return this.writeEntriesForCollectionGroup(\n transaction,\n collectionGroup,\n documentsRemaining\n ).next(documentsProcessed => {\n documentsRemaining -= documentsProcessed;\n processedCollectionGroups.add(collectionGroup);\n });\n }\n });\n }\n ).next(() => maxDocumentsToProcess - documentsRemaining);\n }\n\n /**\n * Writes entries for the provided collection group. Returns the number of documents processed.\n */\n private writeEntriesForCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n documentsRemainingUnderCap: number\n ): PersistencePromise {\n // Use the earliest offset of all field indexes to query the local cache.\n return this.localStore.indexManager\n .getMinOffsetFromCollectionGroup(transaction, collectionGroup)\n .next(existingOffset =>\n this.localStore.localDocuments\n .getNextDocuments(\n transaction,\n collectionGroup,\n existingOffset,\n documentsRemainingUnderCap\n )\n .next(nextBatch => {\n const docs: DocumentMap = nextBatch.changes;\n return this.localStore.indexManager\n .updateIndexEntries(transaction, docs)\n .next(() => this.getNewOffset(existingOffset, nextBatch))\n .next(newOffset => {\n logDebug(LOG_TAG, `Updating offset: ${newOffset}`);\n return this.localStore.indexManager.updateCollectionGroup(\n transaction,\n collectionGroup,\n newOffset\n );\n })\n .next(() => docs.size);\n })\n );\n }\n\n /** Returns the next offset based on the provided documents. */\n private getNewOffset(\n existingOffset: IndexOffset,\n lookupResult: LocalWriteResult\n ): IndexOffset {\n let maxOffset: IndexOffset = existingOffset;\n lookupResult.changes.forEach((key, document) => {\n const newOffset: IndexOffset = newIndexOffsetFromDocument(document);\n if (indexOffsetComparator(newOffset, maxOffset) > 0) {\n maxOffset = newOffset;\n }\n });\n return new IndexOffset(\n maxOffset.readTime,\n maxOffset.documentKey,\n Math.max(lookupResult.batchId, existingOffset.largestBatchId)\n );\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequenceNumber } from './types';\n\n/**\n * `SequenceNumberSyncer` defines the methods required to keep multiple instances of a\n * `ListenSequence` in sync.\n */\nexport interface SequenceNumberSyncer {\n // Notify the syncer that a new sequence number has been used.\n writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void;\n // Setting this property allows the syncer to notify when a sequence number has been used, and\n // and lets the ListenSequence adjust its internal previous value accordingly.\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null;\n}\n\n/**\n * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to\n * exceed. All subsequent calls to next will return increasing values. If provided with a\n * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as\n * well as write out sequence numbers that it produces via `next()`.\n */\nexport class ListenSequence {\n static readonly INVALID: ListenSequenceNumber = -1;\n\n private writeNewSequenceNumber?: (\n newSequenceNumber: ListenSequenceNumber\n ) => void;\n\n constructor(\n private previousValue: ListenSequenceNumber,\n sequenceNumberSyncer?: SequenceNumberSyncer\n ) {\n if (sequenceNumberSyncer) {\n sequenceNumberSyncer.sequenceNumberHandler = sequenceNumber =>\n this.setPreviousValue(sequenceNumber);\n this.writeNewSequenceNumber = sequenceNumber =>\n sequenceNumberSyncer.writeSequenceNumber(sequenceNumber);\n }\n }\n\n private setPreviousValue(\n externalPreviousValue: ListenSequenceNumber\n ): ListenSequenceNumber {\n this.previousValue = Math.max(externalPreviousValue, this.previousValue);\n return this.previousValue;\n }\n\n next(): ListenSequenceNumber {\n const nextValue = ++this.previousValue;\n if (this.writeNewSequenceNumber) {\n this.writeNewSequenceNumber(nextValue);\n }\n return nextValue;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ResourcePath } from '../model/path';\nimport { fail, hardAssert } from '../util/assert';\n\n/**\n * Helpers for dealing with resource paths stored in IndexedDB.\n *\n * Resource paths in their canonical string form do not sort as the server\n * sorts them. Specifically the server splits paths into segments first and then\n * sorts, putting end-of-segment before any character. In a UTF-8 string\n * encoding the slash ('/') that denotes the end-of-segment naturally comes\n * after other characters so the intent here is to encode the path delimiters in\n * such a way that the resulting strings sort naturally.\n *\n * Resource paths are also used for prefix scans so it's important to\n * distinguish whole segments from any longer segments of which they might be a\n * prefix. For example, it's important to make it possible to scan documents in\n * a collection \"foo\" without encountering documents in a collection \"foobar\".\n *\n * Separate from the concerns about resource path ordering and separation,\n * On Android, SQLite imposes additional restrictions since it does not handle\n * keys with embedded NUL bytes particularly well. Rather than change the\n * implementation we keep the encoding identical to keep the ports similar.\n *\n * Taken together this means resource paths when encoded for storage in\n * IndexedDB have the following characteristics:\n *\n * * Segment separators (\"/\") sort before everything else.\n * * All paths have a trailing separator.\n * * NUL bytes do not exist in the output, since IndexedDB doesn't treat them\n * well.\n *\n * Therefore resource paths are encoded into string form using the following\n * rules:\n *\n * * '\\x01' is used as an escape character.\n * * Path separators are encoded as \"\\x01\\x01\"\n * * NUL bytes are encoded as \"\\x01\\x10\"\n * * '\\x01' is encoded as \"\\x01\\x11\"\n *\n * This encoding leaves some room between path separators and the NUL byte\n * just in case we decide to support integer document ids after all.\n *\n * Note that characters treated specially by the backend ('.', '/', and '~')\n * are not treated specially here. This class assumes that any unescaping of\n * resource path strings into actual ResourcePath objects will handle these\n * characters there.\n */\nexport type EncodedResourcePath = string;\n\nconst escapeChar = '\\u0001';\nconst encodedSeparatorChar = '\\u0001';\nconst encodedNul = '\\u0010';\nconst encodedEscape = '\\u0011';\n\n/**\n * Encodes a resource path into a IndexedDb-compatible string form.\n */\nexport function encodeResourcePath(path: ResourcePath): EncodedResourcePath {\n let result = '';\n for (let i = 0; i < path.length; i++) {\n if (result.length > 0) {\n result = encodeSeparator(result);\n }\n result = encodeSegment(path.get(i), result);\n }\n return encodeSeparator(result);\n}\n\n/** Encodes a single segment of a resource path into the given result */\nfunction encodeSegment(segment: string, resultBuf: string): string {\n let result = resultBuf;\n const length = segment.length;\n for (let i = 0; i < length; i++) {\n const c = segment.charAt(i);\n switch (c) {\n case '\\0':\n result += escapeChar + encodedNul;\n break;\n case escapeChar:\n result += escapeChar + encodedEscape;\n break;\n default:\n result += c;\n }\n }\n return result;\n}\n\n/** Encodes a path separator into the given result */\nfunction encodeSeparator(result: string): string {\n return result + escapeChar + encodedSeparatorChar;\n}\n\n/**\n * Decodes the given IndexedDb-compatible string form of a resource path into\n * a ResourcePath instance. Note that this method is not suitable for use with\n * decoding resource names from the server; those are One Platform format\n * strings.\n */\nexport function decodeResourcePath(path: EncodedResourcePath): ResourcePath {\n // Event the empty path must encode as a path of at least length 2. A path\n // with exactly 2 must be the empty path.\n const length = path.length;\n hardAssert(length >= 2, 0xfb98, 'Invalid path', { path });\n if (length === 2) {\n hardAssert(\n path.charAt(0) === escapeChar && path.charAt(1) === encodedSeparatorChar,\n 0xdb51,\n 'Non-empty path had length 2',\n { path }\n );\n return ResourcePath.emptyPath();\n }\n\n // Escape characters cannot exist past the second-to-last position in the\n // source value.\n const lastReasonableEscapeIndex = length - 2;\n\n const segments: string[] = [];\n let segmentBuilder = '';\n\n for (let start = 0; start < length; ) {\n // The last two characters of a valid encoded path must be a separator, so\n // there must be an end to this segment.\n const end = path.indexOf(escapeChar, start);\n if (end < 0 || end > lastReasonableEscapeIndex) {\n fail(0xc553, 'Invalid encoded resource path', { path });\n }\n\n const next = path.charAt(end + 1);\n switch (next) {\n case encodedSeparatorChar:\n const currentPiece = path.substring(start, end);\n let segment;\n if (segmentBuilder.length === 0) {\n // Avoid copying for the common case of a segment that excludes \\0\n // and \\001\n segment = currentPiece;\n } else {\n segmentBuilder += currentPiece;\n segment = segmentBuilder;\n segmentBuilder = '';\n }\n segments.push(segment);\n break;\n case encodedNul:\n segmentBuilder += path.substring(start, end);\n segmentBuilder += '\\0';\n break;\n case encodedEscape:\n // The escape character can be used in the output to encode itself.\n segmentBuilder += path.substring(start, end + 1);\n break;\n default:\n fail(0xeeef, 'Invalid encoded resource path', { path });\n }\n\n start = end + 2;\n }\n\n return new ResourcePath(segments);\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 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 * Representation of a byte array that is safe for\n * use in an IndexedDb key. The value is either\n * a \"sortable byte string\", which is key safe in\n * Safari/WebKit, or the value is a Uint8Array,\n * which is key safe in other browsers.\n */\nexport type KeySafeBytes = Uint8Array | string;\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 KeySafeBytes,\n KeySafeBytes,\n KeySafeBytes,\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];\nexport const V18_STORES = V17_STORES;\n\n/**\n * The list of all default IndexedDB stores used throughout the SDK. This is\n * used when creating transactions so that access across all stores is done\n * atomically.\n */\nexport const ALL_STORES = V12_STORES;\n\n/** Returns the object stores for the provided schema. */\nexport function getObjectStores(schemaVersion: number): string[] {\n if (schemaVersion === 18) {\n return V18_STORES;\n } else 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(0xeb55, 'Only schema versions >11 are supported');\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 { ListenSequenceNumber } from '../core/types';\nimport { debugCast } from '../util/assert';\n\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDb, SimpleDbStore, SimpleDbTransaction } from './simple_db';\n\nexport class IndexedDbTransaction extends PersistenceTransaction {\n constructor(\n readonly simpleDbTransaction: SimpleDbTransaction,\n readonly currentSequenceNumber: ListenSequenceNumber\n ) {\n super();\n }\n}\n\nexport function getStore(\n txn: PersistenceTransaction,\n store: string\n): SimpleDbStore {\n const indexedDbTransaction = debugCast(txn, IndexedDbTransaction);\n return SimpleDb.getStore(\n indexedDbTransaction.simpleDbTransaction,\n store\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from './assert';\n\nexport interface Dict {\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(0xaad2, 'Red node has red child', {\n key: this.key,\n value: this.value\n });\n }\n if (this.right.isRed()) {\n throw fail(0x3721, 'Right child of (`key`, `value`) is red', {\n key: this.key,\n value: this.value\n });\n }\n const blackDepth = (this.left as LLRBNode).check();\n if (blackDepth !== (this.right as LLRBNode).check()) {\n throw fail(0x6d2d, '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(0xe1a6, 'LLRBEmptyNode has no key.');\n }\n get value(): never {\n throw fail(0x3f0d, 'LLRBEmptyNode has no value.');\n }\n get color(): never {\n throw fail(0x4157, 'LLRBEmptyNode has no color.');\n }\n get left(): never {\n throw fail(0x741e, 'LLRBEmptyNode has no left child.');\n }\n get right(): never {\n throw fail(0x901e, '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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Converts a Base64 encoded string to a binary string. */\n\nexport function decodeBase64(encoded: string): string {\n // Note: We used to validate the base64 string here via a regular expression.\n // This was removed to improve the performance of indexing.\n return Buffer.from(encoded, 'base64').toString('binary');\n}\n\n/** Converts a binary string to a Base64 encoded string. */\nexport function encodeBase64(raw: string): string {\n return Buffer.from(raw, 'binary').toString('base64');\n}\n\n/** True if and only if the Base64 conversion functions are available. */\nexport function isBase64Available(): boolean {\n return true;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 { 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, 0x986a, '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, 0xb5de, 'invalid timestamp', {\n timestamp: date\n });\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 readonly isUsingEmulator: 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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 {\n arrayEquals,\n compareUtf8Strings,\n primitiveComparator\n} 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(0x6e87, 'Invalid value type', { 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(0xcbf8, 'Unexpected value type', { 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 compareUtf8Strings(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(0x5ae0, '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 = compareUtf8Strings(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(0xee4d, 'Invalid value type', { 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(0x34ae, 'Invalid value type', { 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(0x8c66, 'Invalid value type', { 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(0xf207, 'Invalid value type', { 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(\n 0xa786,\n \"Trying to compare documents on fields that don't exist\"\n );\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 other.nullValue === undefined &&\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(0xb8a2, 'Unknown FieldFilter operator', {\n operator: this.op\n });\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(0x4bef, '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 (\n other !== null &&\n other.nullValue === undefined &&\n !arrayValueContains(this.value.arrayValue!, other)\n );\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(0x4d4e, 'Unknown direction', { 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 0x7f90,\n 'server transform result count should match field transform count',\n {\n serverTransformResultCount: serverTransformResults.length,\n fieldTransformCount: fieldTransforms.length\n }\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 0xe5da,\n 'Mutations sent must equal results received',\n {\n mutationsSent: batch.mutations.length,\n resultsReceived: results.length\n }\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(0xfdaa, '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(0x3c6b, '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(0x999b, '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(0x3019, '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 * An error encountered while decoding base64 string.\n */\nexport class Base64DecodeError extends Error {\n readonly name = 'Base64DecodeError';\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\nimport { TextDecoder, TextEncoder } from 'util';\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(0x9481, '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 0x0ca9,\n '`pendingResponses` is less than 0. This indicates that the SDK received more target acks from the server than expected. The SDK should not continue to operate.',\n { pendingResponses: this.pendingResponses }\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 private pendingDocumentUpdatesByTarget = documentTargetMap();\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(0xddd6, 'Unknown target watch change state', {\n state: targetChange.state\n });\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 0x4e2d,\n 'Single document existence filter with count',\n { 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 for this\n // target. This resolves the limbo state of the document, removing it\n // from 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.ensureDocumentUpdateByTarget(key).has(targetId) &&\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.pendingDocumentUpdatesByTarget = documentTargetMap();\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.pendingDocumentUpdatesByTarget =\n this.pendingDocumentUpdatesByTarget.insert(\n document.key,\n this.ensureDocumentUpdateByTarget(document.key).add(targetId)\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 this.pendingDocumentTargetMapping =\n this.pendingDocumentTargetMapping.insert(\n key,\n this.ensureDocumentTargetMapping(key).add(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 private ensureDocumentUpdateByTarget(key: DocumentKey): SortedSet {\n let targetMapping = this.pendingDocumentUpdatesByTarget.get(key);\n\n if (!targetMapping) {\n targetMapping = new SortedSet(primitiveComparator);\n this.pendingDocumentUpdatesByTarget =\n this.pendingDocumentUpdatesByTarget.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\n/**\n * Returns a Timestamp typed object given protobuf timestamp value.\n */\nexport function 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 0xe30b,\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 0x3f41,\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, 0xc050, \"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 0x27ce,\n 'Tried to deserialize invalid key',\n { 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 0x71a3,\n 'tried to deserialize invalid key',\n { 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 0xaa33,\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 0x0f36,\n 'Tried to deserialize a missing document from a found document.'\n );\n hardAssert(\n !!result.readTime,\n 0x5995,\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(0x1c42, 'invalid batch get response', { 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(0x2d51, 'Unknown change type', { 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(0x9991, '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(0x40d7, 'Unknown mutation type', {\n mutationType: mutation.type\n });\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(0x05b7, 'unknown mutation proto', { 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(0x6b69, '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 0x3811,\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(0x51c2, 'Unknown transform', {\n transform: fieldTransform.transform\n });\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 0x40f6,\n 'Unknown server value transform proto',\n { 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(0x40c8, 'Unknown transform proto', { 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 0x07ae,\n 'DocumentsTarget contained other than 1 document',\n {\n count\n }\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 0xfe26,\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(0x713b, '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(0x7591, 'Unknown filter', { 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(0xe2fe, 'Unspecified operator');\n default:\n return fail(0xc54a, '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(0x0402, '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(0xd65d, 'Unrecognized filter type', { 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(0xef81, 'Unspecified filter');\n default:\n return fail(0xed36, '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(0xdd85, '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(0xe230, 'Unexpected Document', { document });\n }\n return remoteDoc;\n}\n\nexport function toDbTimestampKey(\n snapshotVersion: SnapshotVersion\n): DbTimestampKey {\n const timestamp = snapshotVersion.toTimestamp();\n return [timestamp.seconds, timestamp.nanoseconds];\n}\n\nexport function fromDbTimestampKey(\n dbTimestampKey: DbTimestampKey\n): SnapshotVersion {\n const timestamp = new Timestamp(dbTimestampKey[0], dbTimestampKey[1]);\n return SnapshotVersion.fromTimestamp(timestamp);\n}\n\nexport function toDbTimestamp(snapshotVersion: SnapshotVersion): DbTimestamp {\n const timestamp = snapshotVersion.toTimestamp();\n return { seconds: timestamp.seconds, nanoseconds: timestamp.nanoseconds };\n}\n\nfunction fromDbTimestamp(dbTimestamp: DbTimestamp): SnapshotVersion {\n const timestamp = new Timestamp(dbTimestamp.seconds, dbTimestamp.nanoseconds);\n return SnapshotVersion.fromTimestamp(timestamp);\n}\n\n/** Encodes a batch of mutations into a DbMutationBatch for local storage. */\nexport function toDbMutationBatch(\n localSerializer: LocalSerializer,\n userId: string,\n batch: MutationBatch\n): DbMutationBatch {\n const serializedBaseMutations = batch.baseMutations.map(m =>\n toMutation(localSerializer.remoteSerializer, m)\n );\n const serializedMutations = batch.mutations.map(m =>\n toMutation(localSerializer.remoteSerializer, m)\n );\n return {\n userId,\n batchId: batch.batchId,\n localWriteTimeMs: batch.localWriteTime.toMillis(),\n baseMutations: serializedBaseMutations,\n mutations: serializedMutations\n };\n}\n\n/** Decodes a DbMutationBatch into a MutationBatch */\nexport function fromDbMutationBatch(\n localSerializer: LocalSerializer,\n dbBatch: DbMutationBatch\n): MutationBatch {\n const baseMutations = (dbBatch.baseMutations || []).map(m =>\n fromMutation(localSerializer.remoteSerializer, m)\n );\n\n // Squash old transform mutations into existing patch or set mutations.\n // The replacement of representing `transforms` with `update_transforms`\n // on the SDK means that old `transform` mutations stored in IndexedDB need\n // to be updated to `update_transforms`.\n // TODO(b/174608374): Remove this code once we perform a schema migration.\n for (let i = 0; i < dbBatch.mutations.length - 1; ++i) {\n const currentMutation = dbBatch.mutations[i];\n const hasTransform =\n i + 1 < dbBatch.mutations.length &&\n dbBatch.mutations[i + 1].transform !== undefined;\n if (hasTransform) {\n debugAssert(\n dbBatch.mutations[i].transform === undefined &&\n dbBatch.mutations[i].update !== undefined,\n 'TransformMutation should be preceded by a patch or set mutation'\n );\n const transformMutation = dbBatch.mutations[i + 1];\n currentMutation.updateTransforms =\n transformMutation.transform!.fieldTransforms;\n dbBatch.mutations.splice(i + 1, 1);\n ++i;\n }\n }\n\n const mutations = dbBatch.mutations.map(m =>\n fromMutation(localSerializer.remoteSerializer, m)\n );\n const timestamp = Timestamp.fromMillis(dbBatch.localWriteTimeMs);\n return new MutationBatch(\n dbBatch.batchId,\n timestamp,\n baseMutations,\n mutations\n );\n}\n\n/** Decodes a DbTarget into TargetData */\nexport function fromDbTarget(dbTarget: DbTarget): TargetData {\n const version = fromDbTimestamp(dbTarget.readTime);\n const lastLimboFreeSnapshotVersion =\n dbTarget.lastLimboFreeSnapshotVersion !== undefined\n ? fromDbTimestamp(dbTarget.lastLimboFreeSnapshotVersion)\n : SnapshotVersion.min();\n\n let target: Target;\n if (isDocumentQuery(dbTarget.query)) {\n target = fromDocumentsTarget(dbTarget.query);\n } else {\n target = fromQueryTarget(dbTarget.query);\n }\n return new TargetData(\n target,\n dbTarget.targetId,\n TargetPurpose.Listen,\n dbTarget.lastListenSequenceNumber,\n version,\n lastLimboFreeSnapshotVersion,\n ByteString.fromBase64String(dbTarget.resumeToken)\n );\n}\n\n/** Encodes TargetData into a DbTarget for storage locally. */\nexport function toDbTarget(\n localSerializer: LocalSerializer,\n targetData: TargetData\n): DbTarget {\n debugAssert(\n TargetPurpose.Listen === targetData.purpose,\n 'Only queries with purpose ' +\n TargetPurpose.Listen +\n ' may be stored, got ' +\n targetData.purpose\n );\n const dbTimestamp = toDbTimestamp(targetData.snapshotVersion);\n const dbLastLimboFreeTimestamp = toDbTimestamp(\n targetData.lastLimboFreeSnapshotVersion\n );\n let queryProto: DbQuery;\n if (targetIsDocumentTarget(targetData.target)) {\n queryProto = toDocumentsTarget(\n localSerializer.remoteSerializer,\n targetData.target\n );\n } else {\n queryProto = toQueryTarget(\n localSerializer.remoteSerializer,\n targetData.target\n ).queryTarget;\n }\n\n // We can't store the resumeToken as a ByteString in IndexedDb, so we\n // convert it to a base64 string for storage.\n const resumeToken = targetData.resumeToken.toBase64();\n\n // lastListenSequenceNumber is always 0 until we do real GC.\n return {\n targetId: targetData.targetId,\n canonicalId: canonifyTarget(targetData.target),\n readTime: dbTimestamp,\n resumeToken,\n lastListenSequenceNumber: targetData.sequenceNumber,\n lastLimboFreeSnapshotVersion: dbLastLimboFreeTimestamp,\n query: queryProto\n };\n}\n\n/**\n * A helper function for figuring out what kind of query has been stored.\n */\nfunction isDocumentQuery(dbQuery: DbQuery): dbQuery is PublicDocumentsTarget {\n return (dbQuery as PublicDocumentsTarget).documents !== undefined;\n}\n\n/** Encodes a DbBundle to a BundleMetadata object. */\nexport function fromDbBundle(dbBundle: DbBundle): BundleMetadata {\n return {\n id: dbBundle.bundleId,\n createTime: fromDbTimestamp(dbBundle.createTime),\n version: dbBundle.version\n };\n}\n\n/** Encodes a BundleMetadata to a DbBundle. */\nexport function toDbBundle(metadata: ProtoBundleMetadata): DbBundle {\n return {\n bundleId: metadata.id!,\n createTime: toDbTimestamp(fromVersion(metadata.createTime!)),\n version: metadata.version!\n };\n}\n\n/** Encodes a DbNamedQuery to a NamedQuery. */\nexport function fromDbNamedQuery(dbNamedQuery: DbNamedQuery): NamedQuery {\n return {\n name: dbNamedQuery.name,\n query: fromBundledQuery(dbNamedQuery.bundledQuery),\n readTime: fromDbTimestamp(dbNamedQuery.readTime)\n };\n}\n\n/** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */\nexport function toDbNamedQuery(query: ProtoNamedQuery): DbNamedQuery {\n return {\n name: query.name!,\n readTime: toDbTimestamp(fromVersion(query.readTime!)),\n bundledQuery: query.bundledQuery!\n };\n}\n\n/**\n * Encodes a `BundledQuery` from bundle proto to a Query object.\n *\n * This reconstructs the original query used to build the bundle being loaded,\n * including features exists only in SDKs (for example: limit-to-last).\n */\nexport function fromBundledQuery(bundledQuery: ProtoBundledQuery): Query {\n const query = convertQueryTargetToQuery({\n parent: bundledQuery.parent!,\n structuredQuery: bundledQuery.structuredQuery!\n });\n if (bundledQuery.limitType === 'LAST') {\n debugAssert(\n !!query.limit,\n 'Bundled query has limitType LAST, but limit is null'\n );\n return queryWithLimit(query, query.limit, LimitType.Last);\n }\n return query;\n}\n\n/** Encodes a NamedQuery proto object to a NamedQuery model object. */\nexport function fromProtoNamedQuery(namedQuery: ProtoNamedQuery): NamedQuery {\n return {\n name: namedQuery.name!,\n query: fromBundledQuery(namedQuery.bundledQuery!),\n readTime: fromVersion(namedQuery.readTime!)\n };\n}\n\n/** Decodes a BundleMetadata proto into a BundleMetadata object. */\nexport function fromBundleMetadata(\n metadata: ProtoBundleMetadata\n): BundleMetadata {\n return {\n id: metadata.id!,\n version: metadata.version!,\n createTime: fromVersion(metadata.createTime!)\n };\n}\n\n/** Encodes a DbDocumentOverlay object to an Overlay model object. */\nexport function fromDbDocumentOverlay(\n localSerializer: LocalSerializer,\n dbDocumentOverlay: DbDocumentOverlay\n): Overlay {\n return new Overlay(\n dbDocumentOverlay.largestBatchId,\n fromMutation(\n localSerializer.remoteSerializer,\n dbDocumentOverlay.overlayMutation\n )\n );\n}\n\n/** Decodes an Overlay model object into a DbDocumentOverlay object. */\nexport function toDbDocumentOverlay(\n localSerializer: LocalSerializer,\n userId: string,\n overlay: Overlay\n): DbDocumentOverlay {\n const [_, collectionPath, documentId] = toDbDocumentOverlayKey(\n userId,\n overlay.mutation.key\n );\n return {\n userId,\n collectionPath,\n documentId,\n collectionGroup: overlay.mutation.key.getCollectionGroup(),\n largestBatchId: overlay.largestBatchId,\n overlayMutation: toMutation(\n localSerializer.remoteSerializer,\n overlay.mutation\n )\n };\n}\n\n/**\n * Returns the DbDocumentOverlayKey corresponding to the given user and\n * document key.\n */\nexport function toDbDocumentOverlayKey(\n userId: string,\n docKey: DocumentKey\n): DbDocumentOverlayKey {\n const docId = docKey.path.lastSegment();\n const collectionPath = encodeResourcePath(docKey.path.popLast());\n return [userId, collectionPath, docId];\n}\n\nexport function toDbIndexConfiguration(\n index: FieldIndex\n): DbIndexConfiguration {\n return {\n indexId: index.indexId,\n collectionGroup: index.collectionGroup,\n fields: index.fields.map(s => [s.fieldPath.canonicalString(), s.kind])\n };\n}\n\nexport function fromDbIndexConfiguration(\n index: DbIndexConfiguration,\n state: DbIndexState | null\n): FieldIndex {\n const decodedState = state\n ? new IndexState(\n state.sequenceNumber,\n new IndexOffset(\n fromDbTimestamp(state.readTime),\n new DocumentKey(decodeResourcePath(state.documentKey)),\n state.largestBatchId\n )\n )\n : IndexState.empty();\n const decodedSegments = index.fields.map(\n ([fieldPath, kind]) =>\n new IndexSegment(FieldPath.fromServerFormat(fieldPath), kind)\n );\n return new FieldIndex(\n index.indexId!,\n index.collectionGroup,\n decodedSegments,\n decodedState\n );\n}\n\nexport function toDbIndexState(\n indexId: number,\n uid: string,\n sequenceNumber: number,\n offset: IndexOffset\n): DbIndexState {\n return {\n indexId,\n uid,\n sequenceNumber,\n readTime: toDbTimestamp(offset.readTime),\n documentKey: encodeResourcePath(offset.documentKey.path),\n largestBatchId: offset.largestBatchId\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BundleMetadata, NamedQuery } from '../core/bundle';\nimport {\n BundleMetadata as ProtoBundleMetadata,\n NamedQuery as ProtoNamedQuery\n} from '../protos/firestore_bundle_proto';\n\nimport { BundleCache } from './bundle_cache';\nimport { DbBundle, DbNamedQuery } from './indexeddb_schema';\nimport {\n DbBundlesKey,\n DbBundleStore,\n DbNamedQueriesKey,\n DbNamedQueryStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n fromDbBundle,\n fromDbNamedQuery,\n toDbBundle,\n toDbNamedQuery\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\nexport class IndexedDbBundleCache implements BundleCache {\n getBundleMetadata(\n transaction: PersistenceTransaction,\n bundleId: string\n ): PersistencePromise {\n return bundlesStore(transaction)\n .get(bundleId)\n .next(bundle => {\n if (bundle) {\n return fromDbBundle(bundle);\n }\n return undefined;\n });\n }\n\n saveBundleMetadata(\n transaction: PersistenceTransaction,\n bundleMetadata: ProtoBundleMetadata\n ): PersistencePromise {\n return bundlesStore(transaction).put(toDbBundle(bundleMetadata));\n }\n\n getNamedQuery(\n transaction: PersistenceTransaction,\n queryName: string\n ): PersistencePromise {\n return namedQueriesStore(transaction)\n .get(queryName)\n .next(query => {\n if (query) {\n return fromDbNamedQuery(query);\n }\n return undefined;\n });\n }\n\n saveNamedQuery(\n transaction: PersistenceTransaction,\n query: ProtoNamedQuery\n ): PersistencePromise {\n return namedQueriesStore(transaction).put(toDbNamedQuery(query));\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the bundles object store.\n */\nfunction bundlesStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbBundleStore);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the namedQueries object store.\n */\nfunction namedQueriesStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbNamedQueryStore);\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport {\n DocumentKeySet,\n MutationMap,\n OverlayMap,\n newOverlayMap\n} from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { Overlay } from '../model/overlay';\nimport { ResourcePath } from '../model/path';\n\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { encodeResourcePath } from './encoded_resource_path';\nimport { DbDocumentOverlay } from './indexeddb_schema';\nimport {\n DbDocumentOverlayCollectionGroupOverlayIndex,\n DbDocumentOverlayCollectionPathOverlayIndex,\n DbDocumentOverlayKey,\n DbDocumentOverlayStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n fromDbDocumentOverlay,\n LocalSerializer,\n toDbDocumentOverlay,\n toDbDocumentOverlayKey\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\n/**\n * Implementation of DocumentOverlayCache using IndexedDb.\n */\nexport class IndexedDbDocumentOverlayCache implements DocumentOverlayCache {\n /**\n * @param serializer - The document serializer.\n * @param userId - The userId for which we are accessing overlays.\n */\n constructor(\n private readonly serializer: LocalSerializer,\n private readonly userId: string\n ) {}\n\n static forUser(\n serializer: LocalSerializer,\n user: User\n ): IndexedDbDocumentOverlayCache {\n const userId = user.uid || '';\n return new IndexedDbDocumentOverlayCache(serializer, userId);\n }\n\n getOverlay(\n transaction: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return documentOverlayStore(transaction)\n .get(toDbDocumentOverlayKey(this.userId, key))\n .next(dbOverlay => {\n if (dbOverlay) {\n return fromDbDocumentOverlay(this.serializer, dbOverlay);\n }\n return null;\n });\n }\n\n getOverlays(\n transaction: PersistenceTransaction,\n keys: DocumentKey[]\n ): PersistencePromise {\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 const promises: Array> = [];\n overlays.forEach((_, mutation) => {\n const overlay = new Overlay(largestBatchId, mutation);\n promises.push(this.saveOverlay(transaction, overlay));\n });\n return PersistencePromise.waitFor(promises);\n }\n\n removeOverlaysForBatchId(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet,\n batchId: number\n ): PersistencePromise {\n const collectionPaths = new Set();\n\n // Get the set of unique collection paths.\n documentKeys.forEach(key =>\n collectionPaths.add(encodeResourcePath(key.getCollectionPath()))\n );\n\n const promises: Array> = [];\n collectionPaths.forEach(collectionPath => {\n const range = IDBKeyRange.bound(\n [this.userId, collectionPath, batchId],\n [this.userId, collectionPath, batchId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n promises.push(\n documentOverlayStore(transaction).deleteAll(\n DbDocumentOverlayCollectionPathOverlayIndex,\n range\n )\n );\n });\n return PersistencePromise.waitFor(promises);\n }\n\n getOverlaysForCollection(\n transaction: PersistenceTransaction,\n collection: ResourcePath,\n sinceBatchId: number\n ): PersistencePromise {\n const result = newOverlayMap();\n const collectionPath = encodeResourcePath(collection);\n // We want batch IDs larger than `sinceBatchId`, and so the lower bound\n // is not inclusive.\n const range = IDBKeyRange.bound(\n [this.userId, collectionPath, sinceBatchId],\n [this.userId, collectionPath, Number.POSITIVE_INFINITY],\n /*lowerOpen=*/ true\n );\n return documentOverlayStore(transaction)\n .loadAll(DbDocumentOverlayCollectionPathOverlayIndex, range)\n .next(dbOverlays => {\n for (const dbOverlay of dbOverlays) {\n const overlay = fromDbDocumentOverlay(this.serializer, dbOverlay);\n result.set(overlay.getKey(), overlay);\n }\n return result;\n });\n }\n\n getOverlaysForCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n sinceBatchId: number,\n count: number\n ): PersistencePromise {\n const result = newOverlayMap();\n let currentBatchId: number | undefined = undefined;\n // We want batch IDs larger than `sinceBatchId`, and so the lower bound\n // is not inclusive.\n const range = IDBKeyRange.bound(\n [this.userId, collectionGroup, sinceBatchId],\n [this.userId, collectionGroup, Number.POSITIVE_INFINITY],\n /*lowerOpen=*/ true\n );\n return documentOverlayStore(transaction)\n .iterate(\n {\n index: DbDocumentOverlayCollectionGroupOverlayIndex,\n range\n },\n (_, dbOverlay, control) => {\n // We do not want to return partial batch overlays, even if the size\n // of the result set exceeds the given `count` argument. Therefore, we\n // continue to aggregate results even after the result size exceeds\n // `count` if there are more overlays from the `currentBatchId`.\n const overlay = fromDbDocumentOverlay(this.serializer, dbOverlay);\n if (\n result.size() < count ||\n overlay.largestBatchId === currentBatchId\n ) {\n result.set(overlay.getKey(), overlay);\n currentBatchId = overlay.largestBatchId;\n } else {\n control.done();\n }\n }\n )\n .next(() => result);\n }\n\n private saveOverlay(\n transaction: PersistenceTransaction,\n overlay: Overlay\n ): PersistencePromise {\n return documentOverlayStore(transaction).put(\n toDbDocumentOverlay(this.serializer, this.userId, overlay)\n );\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document overlay object store.\n */\nfunction documentOverlayStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbDocumentOverlayStore\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 { DbGlobals } from './indexeddb_schema';\nimport { DbGlobalsStore, DbGlobalsKey } from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\nexport class IndexedDbGlobalsCache implements GlobalsCache {\n private globalsStore(\n txn: PersistenceTransaction\n ): SimpleDbStore {\n return getStore(txn, DbGlobalsStore);\n }\n\n getSessionToken(txn: PersistenceTransaction): PersistencePromise {\n const globals = this.globalsStore(txn);\n return globals.get('sessionToken').next(global => {\n const value = global?.value;\n return value\n ? ByteString.fromUint8Array(value)\n : ByteString.EMPTY_BYTE_STRING;\n });\n }\n\n setSessionToken(\n txn: PersistenceTransaction,\n sessionToken: ByteString\n ): PersistencePromise {\n const globals = this.globalsStore(txn);\n return globals.put({\n name: 'sessionToken',\n value: sessionToken.toUint8Array()\n });\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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(0x4a4e, '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 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law | agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES | CONDITIONS OF ANY KIND, either express | implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { debugAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\n\n/** These constants are taken from the backend. */\nconst MIN_SURROGATE = '\\uD800';\nconst MAX_SURROGATE = '\\uDBFF';\n\nconst ESCAPE1 = 0x00;\nconst NULL_BYTE = 0xff; // Combined with ESCAPE1\nconst SEPARATOR = 0x01; // Combined with ESCAPE1\n\nconst ESCAPE2 = 0xff;\nconst INFINITY = 0xff; // Combined with ESCAPE2\nconst FF_BYTE = 0x00; // Combined with ESCAPE2\n\nconst LONG_SIZE = 64;\nconst BYTE_SIZE = 8;\n\n/**\n * The default size of the buffer. This is arbitrary, but likely larger than\n * most index values so that less copies of the underlying buffer will be made.\n * For large values, a single copy will made to double the buffer length.\n */\nconst DEFAULT_BUFFER_SIZE = 1024;\n\n/** Converts a JavaScript number to a byte array (using big endian encoding). */\nfunction doubleToLongBits(value: number): Uint8Array {\n const dv = new DataView(new ArrayBuffer(8));\n dv.setFloat64(0, value, /* littleEndian= */ false);\n return new Uint8Array(dv.buffer);\n}\n\n/**\n * Counts the number of zeros in a byte.\n *\n * Visible for testing.\n */\nexport function numberOfLeadingZerosInByte(x: number): number {\n debugAssert(x < 256, 'Provided value is not a byte: ' + x);\n if (x === 0) {\n return 8;\n }\n\n let zeros = 0;\n if (x >> 4 === 0) {\n // Test if the first four bits are zero.\n zeros += 4;\n x = x << 4;\n }\n if (x >> 6 === 0) {\n // Test if the first two (or next two) bits are zero.\n zeros += 2;\n x = x << 2;\n }\n if (x >> 7 === 0) {\n // Test if the remaining bit is zero.\n zeros += 1;\n }\n return zeros;\n}\n\n/** Counts the number of leading zeros in the given byte array. */\nfunction numberOfLeadingZeros(bytes: Uint8Array): number {\n debugAssert(\n bytes.length === 8,\n 'Can only count leading zeros in 64-bit numbers'\n );\n let leadingZeros = 0;\n for (let i = 0; i < 8; ++i) {\n const zeros = numberOfLeadingZerosInByte(bytes[i] & 0xff);\n leadingZeros += zeros;\n if (zeros !== 8) {\n break;\n }\n }\n return leadingZeros;\n}\n\n/**\n * Returns the number of bytes required to store \"value\". Leading zero bytes\n * are skipped.\n */\nfunction unsignedNumLength(value: Uint8Array): number {\n // This is just the number of bytes for the unsigned representation of the number.\n const numBits = LONG_SIZE - numberOfLeadingZeros(value);\n return Math.ceil(numBits / BYTE_SIZE);\n}\n\n/**\n * OrderedCodeWriter is a minimal-allocation implementation of the writing\n * behavior defined by the backend.\n *\n * The code is ported from its Java counterpart.\n */\nexport class OrderedCodeWriter {\n buffer = new Uint8Array(DEFAULT_BUFFER_SIZE);\n position = 0;\n\n writeBytesAscending(value: ByteString): void {\n const it = value[Symbol.iterator]();\n let byte = it.next();\n while (!byte.done) {\n this.writeByteAscending(byte.value);\n byte = it.next();\n }\n this.writeSeparatorAscending();\n }\n\n writeBytesDescending(value: ByteString): void {\n const it = value[Symbol.iterator]();\n let byte = it.next();\n while (!byte.done) {\n this.writeByteDescending(byte.value);\n byte = it.next();\n }\n this.writeSeparatorDescending();\n }\n\n /** Writes utf8 bytes into this byte sequence, ascending. */\n writeUtf8Ascending(sequence: string): void {\n for (const c of sequence) {\n const charCode = c.charCodeAt(0);\n if (charCode < 0x80) {\n this.writeByteAscending(charCode);\n } else if (charCode < 0x800) {\n this.writeByteAscending((0x0f << 6) | (charCode >>> 6));\n this.writeByteAscending(0x80 | (0x3f & charCode));\n } else if (c < MIN_SURROGATE || MAX_SURROGATE < c) {\n this.writeByteAscending((0x0f << 5) | (charCode >>> 12));\n this.writeByteAscending(0x80 | (0x3f & (charCode >>> 6)));\n this.writeByteAscending(0x80 | (0x3f & charCode));\n } else {\n const codePoint = c.codePointAt(0)!;\n this.writeByteAscending((0x0f << 4) | (codePoint >>> 18));\n this.writeByteAscending(0x80 | (0x3f & (codePoint >>> 12)));\n this.writeByteAscending(0x80 | (0x3f & (codePoint >>> 6)));\n this.writeByteAscending(0x80 | (0x3f & codePoint));\n }\n }\n this.writeSeparatorAscending();\n }\n\n /** Writes utf8 bytes into this byte sequence, descending */\n writeUtf8Descending(sequence: string): void {\n for (const c of sequence) {\n const charCode = c.charCodeAt(0);\n if (charCode < 0x80) {\n this.writeByteDescending(charCode);\n } else if (charCode < 0x800) {\n this.writeByteDescending((0x0f << 6) | (charCode >>> 6));\n this.writeByteDescending(0x80 | (0x3f & charCode));\n } else if (c < MIN_SURROGATE || MAX_SURROGATE < c) {\n this.writeByteDescending((0x0f << 5) | (charCode >>> 12));\n this.writeByteDescending(0x80 | (0x3f & (charCode >>> 6)));\n this.writeByteDescending(0x80 | (0x3f & charCode));\n } else {\n const codePoint = c.codePointAt(0)!;\n this.writeByteDescending((0x0f << 4) | (codePoint >>> 18));\n this.writeByteDescending(0x80 | (0x3f & (codePoint >>> 12)));\n this.writeByteDescending(0x80 | (0x3f & (codePoint >>> 6)));\n this.writeByteDescending(0x80 | (0x3f & codePoint));\n }\n }\n this.writeSeparatorDescending();\n }\n\n writeNumberAscending(val: number): void {\n // Values are encoded with a single byte length prefix, followed by the\n // actual value in big-endian format with leading 0 bytes dropped.\n const value = this.toOrderedBits(val);\n const len = unsignedNumLength(value);\n this.ensureAvailable(1 + len);\n this.buffer[this.position++] = len & 0xff; // Write the length\n for (let i = value.length - len; i < value.length; ++i) {\n this.buffer[this.position++] = value[i] & 0xff;\n }\n }\n\n writeNumberDescending(val: number): void {\n // Values are encoded with a single byte length prefix, followed by the\n // inverted value in big-endian format with leading 0 bytes dropped.\n const value = this.toOrderedBits(val);\n const len = unsignedNumLength(value);\n this.ensureAvailable(1 + len);\n this.buffer[this.position++] = ~(len & 0xff); // Write the length\n for (let i = value.length - len; i < value.length; ++i) {\n this.buffer[this.position++] = ~(value[i] & 0xff);\n }\n }\n\n /**\n * Writes the \"infinity\" byte sequence that sorts after all other byte\n * sequences written in ascending order.\n */\n writeInfinityAscending(): void {\n this.writeEscapedByteAscending(ESCAPE2);\n this.writeEscapedByteAscending(INFINITY);\n }\n\n /**\n * Writes the \"infinity\" byte sequence that sorts before all other byte\n * sequences written in descending order.\n */\n writeInfinityDescending(): void {\n this.writeEscapedByteDescending(ESCAPE2);\n this.writeEscapedByteDescending(INFINITY);\n }\n\n /**\n * Resets the buffer such that it is the same as when it was newly\n * constructed.\n */\n reset(): void {\n this.position = 0;\n }\n\n seed(encodedBytes: Uint8Array): void {\n this.ensureAvailable(encodedBytes.length);\n this.buffer.set(encodedBytes, this.position);\n this.position += encodedBytes.length;\n }\n\n /** Makes a copy of the encoded bytes in this buffer. */\n encodedBytes(): Uint8Array {\n return this.buffer.slice(0, this.position);\n }\n\n /**\n * Encodes `val` into an encoding so that the order matches the IEEE 754\n * floating-point comparison results with the following exceptions:\n * -0.0 < 0.0\n * all non-NaN < NaN\n * NaN = NaN\n */\n private toOrderedBits(val: number): Uint8Array {\n const value = doubleToLongBits(val);\n // Check if the first bit is set. We use a bit mask since value[0] is\n // encoded as a number from 0 to 255.\n const isNegative = (value[0] & 0x80) !== 0;\n\n // Revert the two complement to get natural ordering\n value[0] ^= isNegative ? 0xff : 0x80;\n for (let i = 1; i < value.length; ++i) {\n value[i] ^= isNegative ? 0xff : 0x00;\n }\n return value;\n }\n\n /** Writes a single byte ascending to the buffer. */\n private writeByteAscending(b: number): void {\n const masked = b & 0xff;\n if (masked === ESCAPE1) {\n this.writeEscapedByteAscending(ESCAPE1);\n this.writeEscapedByteAscending(NULL_BYTE);\n } else if (masked === ESCAPE2) {\n this.writeEscapedByteAscending(ESCAPE2);\n this.writeEscapedByteAscending(FF_BYTE);\n } else {\n this.writeEscapedByteAscending(masked);\n }\n }\n\n /** Writes a single byte descending to the buffer. */\n private writeByteDescending(b: number): void {\n const masked = b & 0xff;\n if (masked === ESCAPE1) {\n this.writeEscapedByteDescending(ESCAPE1);\n this.writeEscapedByteDescending(NULL_BYTE);\n } else if (masked === ESCAPE2) {\n this.writeEscapedByteDescending(ESCAPE2);\n this.writeEscapedByteDescending(FF_BYTE);\n } else {\n this.writeEscapedByteDescending(b);\n }\n }\n\n private writeSeparatorAscending(): void {\n this.writeEscapedByteAscending(ESCAPE1);\n this.writeEscapedByteAscending(SEPARATOR);\n }\n\n private writeSeparatorDescending(): void {\n this.writeEscapedByteDescending(ESCAPE1);\n this.writeEscapedByteDescending(SEPARATOR);\n }\n\n private writeEscapedByteAscending(b: number): void {\n this.ensureAvailable(1);\n this.buffer[this.position++] = b;\n }\n\n private writeEscapedByteDescending(b: number): void {\n this.ensureAvailable(1);\n this.buffer[this.position++] = ~b;\n }\n\n private ensureAvailable(bytes: number): void {\n const minCapacity = bytes + this.position;\n if (minCapacity <= this.buffer.length) {\n return;\n }\n // Try doubling.\n let newLength = this.buffer.length * 2;\n // Still not big enough? Just allocate the right size.\n if (newLength < minCapacity) {\n newLength = minCapacity;\n }\n // Create the new buffer.\n const newBuffer = new Uint8Array(newLength);\n newBuffer.set(this.buffer); // copy old data\n this.buffer = newBuffer;\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { IndexKind } from '../model/field_index';\nimport { ByteString } from '../util/byte_string';\n\nimport { DirectionalIndexByteEncoder } from './directional_index_byte_encoder';\nimport { OrderedCodeWriter } from './ordered_code_writer';\n\nclass AscendingIndexByteEncoder implements DirectionalIndexByteEncoder {\n constructor(private orderedCode: OrderedCodeWriter) {}\n writeBytes(value: ByteString): void {\n this.orderedCode.writeBytesAscending(value);\n }\n\n writeString(value: string): void {\n this.orderedCode.writeUtf8Ascending(value);\n }\n\n writeNumber(value: number): void {\n this.orderedCode.writeNumberAscending(value);\n }\n\n writeInfinity(): void {\n this.orderedCode.writeInfinityAscending();\n }\n}\n\nclass DescendingIndexByteEncoder implements DirectionalIndexByteEncoder {\n constructor(private orderedCode: OrderedCodeWriter) {}\n writeBytes(value: ByteString): void {\n this.orderedCode.writeBytesDescending(value);\n }\n\n writeString(value: string): void {\n this.orderedCode.writeUtf8Descending(value);\n }\n\n writeNumber(value: number): void {\n this.orderedCode.writeNumberDescending(value);\n }\n\n writeInfinity(): void {\n this.orderedCode.writeInfinityDescending();\n }\n}\n/**\n * Implements `DirectionalIndexByteEncoder` using `OrderedCodeWriter` for the\n * actual encoding.\n */\nexport class IndexByteEncoder {\n private orderedCode = new OrderedCodeWriter();\n private ascending = new AscendingIndexByteEncoder(this.orderedCode);\n private descending = new DescendingIndexByteEncoder(this.orderedCode);\n\n seed(encodedBytes: Uint8Array): void {\n this.orderedCode.seed(encodedBytes);\n }\n\n forKind(kind: IndexKind): DirectionalIndexByteEncoder {\n return kind === IndexKind.ASCENDING ? this.ascending : this.descending;\n }\n\n encodedBytes(): Uint8Array {\n return this.orderedCode.encodedBytes();\n }\n\n reset(): void {\n this.orderedCode.reset();\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isSafariOrWebkit } from '@firebase/util';\n\nimport { DbIndexEntry } from '../local/indexeddb_schema';\nimport { DbIndexEntryKey, KeySafeBytes } from '../local/indexeddb_sentinels';\nimport { DocumentKey } from '../model/document_key';\n\n/** Represents an index entry saved by the SDK in persisted storage. */\nexport class IndexEntry {\n constructor(\n readonly _indexId: number,\n readonly _documentKey: DocumentKey,\n readonly _arrayValue: Uint8Array,\n readonly _directionalValue: Uint8Array\n ) {}\n\n /**\n * Returns an IndexEntry entry that sorts immediately after the current\n * directional value.\n */\n successor(): IndexEntry {\n const currentLength = this._directionalValue.length;\n const newLength =\n currentLength === 0 || this._directionalValue[currentLength - 1] === 255\n ? currentLength + 1\n : currentLength;\n\n const successor = new Uint8Array(newLength);\n successor.set(this._directionalValue, 0);\n if (newLength !== currentLength) {\n successor.set([0], this._directionalValue.length);\n } else {\n ++successor[successor.length - 1];\n }\n\n return new IndexEntry(\n this._indexId,\n this._documentKey,\n this._arrayValue,\n successor\n );\n }\n\n // Create a representation of the Index Entry as a DbIndexEntry\n dbIndexEntry(\n uid: string,\n orderedDocumentKey: Uint8Array,\n documentKey: DocumentKey\n ): DbIndexEntry {\n return {\n indexId: this._indexId,\n uid,\n arrayValue: encodeKeySafeBytes(this._arrayValue),\n directionalValue: encodeKeySafeBytes(this._directionalValue),\n orderedDocumentKey: encodeKeySafeBytes(orderedDocumentKey),\n documentKey: documentKey.path.toArray()\n };\n }\n\n // Create a representation of the Index Entry as a DbIndexEntryKey\n dbIndexEntryKey(\n uid: string,\n orderedDocumentKey: Uint8Array,\n documentKey: DocumentKey\n ): DbIndexEntryKey {\n const entry = this.dbIndexEntry(uid, orderedDocumentKey, documentKey);\n return [\n entry.indexId,\n entry.uid,\n entry.arrayValue,\n entry.directionalValue,\n entry.orderedDocumentKey,\n entry.documentKey\n ];\n }\n}\n\nexport function indexEntryComparator(\n left: IndexEntry,\n right: IndexEntry\n): number {\n let cmp = left._indexId - right._indexId;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = compareByteArrays(left._arrayValue, right._arrayValue);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = compareByteArrays(left._directionalValue, right._directionalValue);\n if (cmp !== 0) {\n return cmp;\n }\n\n return DocumentKey.comparator(left._documentKey, right._documentKey);\n}\n\nexport function compareByteArrays(left: Uint8Array, right: Uint8Array): number {\n for (let i = 0; i < left.length && i < right.length; ++i) {\n const compare = left[i] - right[i];\n if (compare !== 0) {\n return compare;\n }\n }\n return left.length - right.length;\n}\n\n/**\n * Workaround for WebKit bug: https://bugs.webkit.org/show_bug.cgi?id=292721\n * Create a key safe representation of Uint8Array values.\n * If the browser is detected as Safari or WebKit, then\n * the input array will be converted to \"sortable byte string\".\n * Otherwise, the input array will be returned in its original type.\n */\nexport function encodeKeySafeBytes(array: Uint8Array): KeySafeBytes {\n if (isSafariOrWebkit()) {\n return encodeUint8ArrayToSortableString(array);\n }\n return array;\n}\n\n/**\n * Reverts the key safe representation of Uint8Array (created by\n * encodeKeySafeBytes) to a normal Uint8Array.\n */\nexport function decodeKeySafeBytes(input: KeySafeBytes): Uint8Array {\n if (typeof input !== 'string') {\n return input;\n }\n return decodeSortableStringToUint8Array(input);\n}\n\n/**\n * Encodes a Uint8Array into a \"sortable byte string\".\n * A \"sortable byte string\" sorts in the same order as the Uint8Array.\n * This works because JS string comparison sorts strings based on code points.\n */\nfunction encodeUint8ArrayToSortableString(array: Uint8Array): string {\n let byteString = '';\n for (let i = 0; i < array.length; i++) {\n byteString += String.fromCharCode(array[i]);\n }\n\n return byteString;\n}\n\n/**\n * Decodes a \"sortable byte string\" back into a Uint8Array.\n * A \"sortable byte string\" is assumed to be created where each character's\n * Unicode code point directly corresponds to a single byte value (0-255).\n */\nfunction decodeSortableStringToUint8Array(byteString: string): Uint8Array {\n const uint8array = new Uint8Array(byteString.length);\n\n for (let i = 0; i < byteString.length; i++) {\n uint8array[i] = byteString.charCodeAt(i);\n }\n\n return uint8array;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldFilter, Operator } from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport { Target } from '../core/target';\nimport { hardAssert } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport {\n FieldIndex,\n fieldIndexGetArraySegment,\n fieldIndexGetDirectionalSegments,\n IndexKind,\n IndexSegment,\n IndexState\n} from './field_index';\nimport { FieldPath } from './path';\n\n/**\n * A light query planner for Firestore.\n *\n * This class matches a `FieldIndex` against a Firestore Query `Target`. It\n * determines whether a given index can be used to serve the specified target.\n *\n * The following table showcases some possible index configurations:\n *\n * Query | Index\n * -----------------------------------------------------------------------------\n * where('a', '==', 'a').where('b', '==', 'b') | a ASC, b DESC\n * where('a', '==', 'a').where('b', '==', 'b') | a ASC\n * where('a', '==', 'a').where('b', '==', 'b') | b DESC\n * where('a', '>=', 'a').orderBy('a') | a ASC\n * where('a', '>=', 'a').orderBy('a', 'desc') | a DESC\n * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC, b ASC\n * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC\n * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS, b ASCENDING\n * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS\n */\nexport class TargetIndexMatcher {\n // The collection ID (or collection group) of the query target.\n private readonly collectionId: string;\n // The inequality filters of the target (if it exists).\n // Note: The sort on FieldFilters is not required. Using SortedSet here just to utilize the custom\n // comparator.\n private inequalityFilters = new SortedSet((lhs, rhs) =>\n FieldPath.comparator(lhs.field, rhs.field)\n );\n\n // The list of equality filters of the target.\n private readonly equalityFilters: FieldFilter[];\n // The list of orderBys of the target.\n private readonly orderBys: OrderBy[];\n\n constructor(target: Target) {\n this.collectionId =\n target.collectionGroup != null\n ? target.collectionGroup\n : target.path.lastSegment();\n this.orderBys = target.orderBy;\n this.equalityFilters = [];\n for (const filter of target.filters) {\n const fieldFilter = filter as FieldFilter;\n if (fieldFilter.isInequality()) {\n this.inequalityFilters = this.inequalityFilters.add(fieldFilter);\n } else {\n this.equalityFilters.push(fieldFilter);\n }\n }\n }\n\n get hasMultipleInequality(): boolean {\n return this.inequalityFilters.size > 1;\n }\n\n /**\n * Returns whether the index can be used to serve the TargetIndexMatcher's\n * target.\n *\n * An index is considered capable of serving the target when:\n * - The target uses all index segments for its filters and orderBy clauses.\n * The target can have additional filter and orderBy clauses, but not\n * fewer.\n * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also\n * have a corresponding `CONTAINS` segment.\n * - All directional index segments can be mapped to the target as a series of\n * equality filters, a single inequality filter and a series of orderBy\n * clauses.\n * - The segments that represent the equality filters may appear out of order.\n * - The optional segment for the inequality filter must appear after all\n * equality segments.\n * - The segments that represent that orderBy clause of the target must appear\n * in order after all equality and inequality segments. Single orderBy\n * clauses cannot be skipped, but a continuous orderBy suffix may be\n * omitted.\n */\n servedByIndex(index: FieldIndex): boolean {\n hardAssert(\n index.collectionGroup === this.collectionId,\n 0xc07f,\n 'Collection IDs do not match'\n );\n\n if (this.hasMultipleInequality) {\n // Only single inequality is supported for now.\n // TODO(Add support for multiple inequality query): b/298441043\n return false;\n }\n\n // If there is an array element, find a matching filter.\n const arraySegment = fieldIndexGetArraySegment(index);\n if (\n arraySegment !== undefined &&\n !this.hasMatchingEqualityFilter(arraySegment)\n ) {\n return false;\n }\n\n const segments = fieldIndexGetDirectionalSegments(index);\n let equalitySegments = new Set();\n let segmentIndex = 0;\n let orderBysIndex = 0;\n\n // Process all equalities first. Equalities can appear out of order.\n for (; segmentIndex < segments.length; ++segmentIndex) {\n // We attempt to greedily match all segments to equality filters. If a\n // filter matches an index segment, we can mark the segment as used.\n if (this.hasMatchingEqualityFilter(segments[segmentIndex])) {\n equalitySegments = equalitySegments.add(\n segments[segmentIndex].fieldPath.canonicalString()\n );\n } else {\n // If we cannot find a matching filter, we need to verify whether the\n // remaining segments map to the target's inequality and its orderBy\n // clauses.\n break;\n }\n }\n\n // If we already have processed all segments, all segments are used to serve\n // the equality filters and we do not need to map any segments to the\n // target's inequality and orderBy clauses.\n if (segmentIndex === segments.length) {\n return true;\n }\n\n if (this.inequalityFilters.size > 0) {\n // Only a single inequality is currently supported. Get the only entry in the set.\n const inequalityFilter = this.inequalityFilters.getIterator().getNext();\n // If there is an inequality filter and the field was not in one of the\n // equality filters above, the next segment must match both the filter\n // and the first orderBy clause.\n if (!equalitySegments.has(inequalityFilter.field.canonicalString())) {\n const segment = segments[segmentIndex];\n\n if (\n !this.matchesFilter(inequalityFilter, segment) ||\n !this.matchesOrderBy(this.orderBys[orderBysIndex++], segment)\n ) {\n return false;\n }\n }\n\n ++segmentIndex;\n }\n\n // All remaining segments need to represent the prefix of the target's\n // orderBy.\n for (; segmentIndex < segments.length; ++segmentIndex) {\n const segment = segments[segmentIndex];\n if (\n orderBysIndex >= this.orderBys.length ||\n !this.matchesOrderBy(this.orderBys[orderBysIndex++], segment)\n ) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Returns a full matched field index for this target. Currently multiple\n * inequality query is not supported so function returns null.\n */\n buildTargetIndex(): FieldIndex | null {\n if (this.hasMultipleInequality) {\n return null;\n }\n\n // We want to make sure only one segment created for one field. For example,\n // in case like a == 3 and a > 2, Index {a ASCENDING} will only be created\n // once.\n let uniqueFields = new SortedSet(FieldPath.comparator);\n const segments: IndexSegment[] = [];\n\n for (const filter of this.equalityFilters) {\n if (filter.field.isKeyField()) {\n continue;\n }\n const isArrayOperator =\n filter.op === Operator.ARRAY_CONTAINS ||\n filter.op === Operator.ARRAY_CONTAINS_ANY;\n if (isArrayOperator) {\n segments.push(new IndexSegment(filter.field, IndexKind.CONTAINS));\n } else {\n if (uniqueFields.has(filter.field)) {\n continue;\n }\n uniqueFields = uniqueFields.add(filter.field);\n segments.push(new IndexSegment(filter.field, IndexKind.ASCENDING));\n }\n }\n\n // Note: We do not explicitly check `this.inequalityFilter` but rather rely\n // on the target defining an appropriate \"order by\" to ensure that the\n // required index segment is added. The query engine would reject a query\n // with an inequality filter that lacks the required order-by clause.\n for (const orderBy of this.orderBys) {\n // Stop adding more segments if we see a order-by on key. Typically this\n // is the default implicit order-by which is covered in the index_entry\n // table as a separate column. If it is not the default order-by, the\n // generated index will be missing some segments optimized for order-bys,\n // which is probably fine.\n if (orderBy.field.isKeyField()) {\n continue;\n }\n\n if (uniqueFields.has(orderBy.field)) {\n continue;\n }\n uniqueFields = uniqueFields.add(orderBy.field);\n\n segments.push(\n new IndexSegment(\n orderBy.field,\n orderBy.dir === Direction.ASCENDING\n ? IndexKind.ASCENDING\n : IndexKind.DESCENDING\n )\n );\n }\n\n return new FieldIndex(\n FieldIndex.UNKNOWN_ID,\n this.collectionId,\n segments,\n IndexState.empty()\n );\n }\n\n private hasMatchingEqualityFilter(segment: IndexSegment): boolean {\n for (const filter of this.equalityFilters) {\n if (this.matchesFilter(filter, segment)) {\n return true;\n }\n }\n return false;\n }\n\n private matchesFilter(\n filter: FieldFilter | undefined,\n segment: IndexSegment\n ): boolean {\n if (filter === undefined || !filter.field.isEqual(segment.fieldPath)) {\n return false;\n }\n const isArrayOperator =\n filter.op === Operator.ARRAY_CONTAINS ||\n filter.op === Operator.ARRAY_CONTAINS_ANY;\n return (segment.kind === IndexKind.CONTAINS) === isArrayOperator;\n }\n\n private matchesOrderBy(orderBy: OrderBy, segment: IndexSegment): boolean {\n if (!orderBy.field.isEqual(segment.fieldPath)) {\n return false;\n }\n return (\n (segment.kind === IndexKind.ASCENDING &&\n orderBy.dir === Direction.ASCENDING) ||\n (segment.kind === IndexKind.DESCENDING &&\n orderBy.dir === Direction.DESCENDING)\n );\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n CompositeFilter,\n compositeFilterIsConjunction,\n compositeFilterIsDisjunction,\n compositeFilterIsFlat,\n compositeFilterIsFlatConjunction,\n compositeFilterWithAddedFilters,\n CompositeOperator,\n FieldFilter,\n Filter,\n InFilter,\n Operator\n} from '../core/filter';\n\nimport { hardAssert } from './assert';\n\n/**\n * Provides utility functions that help with boolean logic transformations needed for handling\n * complex filters used in queries.\n */\n\n/**\n * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in\n * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given\n * input into a disjunction of equality filters and returns the expanded filter.\n */\nexport function computeInExpansion(filter: Filter): Filter {\n hardAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 0x4e2c,\n 'Only field filters and composite filters are accepted.'\n );\n\n if (filter instanceof FieldFilter) {\n if (filter instanceof InFilter) {\n const expandedFilters =\n filter.value.arrayValue?.values?.map(value =>\n FieldFilter.create(filter.field, Operator.EQUAL, value)\n ) || [];\n\n return CompositeFilter.create(expandedFilters, CompositeOperator.OR);\n } else {\n // We have reached other kinds of field filters.\n return filter;\n }\n }\n\n // We have a composite filter.\n const expandedFilters = filter.filters.map(subfilter =>\n computeInExpansion(subfilter)\n );\n return CompositeFilter.create(expandedFilters, filter.op);\n}\n\n/**\n * Given a composite filter, returns the list of terms in its disjunctive normal form.\n *\n *

Each element in the return value is one term of the resulting DNF. For instance: For the\n * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list\n * with two elements: a composite filter that performs (A && C), and a composite filter that\n * performs (B && C).\n *\n * @param filter the composite filter to calculate DNF transform for.\n * @return the terms in the DNF transform.\n */\nexport function getDnfTerms(filter: CompositeFilter): Filter[] {\n if (filter.getFilters().length === 0) {\n return [];\n }\n\n const result: Filter = computeDistributedNormalForm(\n computeInExpansion(filter)\n );\n\n hardAssert(\n isDisjunctiveNormalForm(result),\n 0x1cdf,\n 'computeDistributedNormalForm did not result in disjunctive normal form'\n );\n\n if (isSingleFieldFilter(result) || isFlatConjunction(result)) {\n return [result];\n }\n\n return result.getFilters();\n}\n\n/** Returns true if the given filter is a single field filter. e.g. (a == 10). */\nfunction isSingleFieldFilter(filter: Filter): boolean {\n return filter instanceof FieldFilter;\n}\n\n/**\n * Returns true if the given filter is the conjunction of one or more field filters. e.g. (a == 10\n * && b == 20)\n */\nfunction isFlatConjunction(filter: Filter): boolean {\n return (\n filter instanceof CompositeFilter &&\n compositeFilterIsFlatConjunction(filter)\n );\n}\n\n/**\n * Returns whether or not the given filter is in disjunctive normal form (DNF).\n *\n *

In boolean logic, a disjunctive normal form (DNF) is a canonical normal form of a logical\n * formula consisting of a disjunction of conjunctions; it can also be described as an OR of ANDs.\n *\n *

For more info, visit: https://en.wikipedia.org/wiki/Disjunctive_normal_form\n */\nfunction isDisjunctiveNormalForm(filter: Filter): boolean {\n return (\n isSingleFieldFilter(filter) ||\n isFlatConjunction(filter) ||\n isDisjunctionOfFieldFiltersAndFlatConjunctions(filter)\n );\n}\n\n/**\n * Returns true if the given filter is the disjunction of one or more \"flat conjunctions\" and\n * field filters. e.g. (a == 10) || (b==20 && c==30)\n */\nfunction isDisjunctionOfFieldFiltersAndFlatConjunctions(\n filter: Filter\n): boolean {\n if (filter instanceof CompositeFilter) {\n if (compositeFilterIsDisjunction(filter)) {\n for (const subFilter of filter.getFilters()) {\n if (!isSingleFieldFilter(subFilter) && !isFlatConjunction(subFilter)) {\n return false;\n }\n }\n\n return true;\n }\n }\n\n return false;\n}\n\nexport function computeDistributedNormalForm(filter: Filter): Filter {\n hardAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 0x84e2,\n 'Only field filters and composite filters are accepted.'\n );\n\n if (filter instanceof FieldFilter) {\n return filter;\n }\n\n if (filter.filters.length === 1) {\n return computeDistributedNormalForm(filter.filters[0]);\n }\n\n // Compute DNF for each of the subfilters first\n const result = filter.filters.map(subfilter =>\n computeDistributedNormalForm(subfilter)\n );\n\n let newFilter: Filter = CompositeFilter.create(result, filter.op);\n newFilter = applyAssociation(newFilter);\n\n if (isDisjunctiveNormalForm(newFilter)) {\n return newFilter;\n }\n\n hardAssert(\n newFilter instanceof CompositeFilter,\n 0xfbf2,\n 'field filters are already in DNF form'\n );\n hardAssert(\n compositeFilterIsConjunction(newFilter),\n 0x9d3b,\n 'Disjunction of filters all of which are already in DNF form is itself in DNF form.'\n );\n hardAssert(\n newFilter.filters.length > 1,\n 0xe247,\n 'Single-filter composite filters are already in DNF form.'\n );\n\n return newFilter.filters.reduce((runningResult, filter) =>\n applyDistribution(runningResult, filter)\n );\n}\n\nexport function applyDistribution(lhs: Filter, rhs: Filter): Filter {\n hardAssert(\n lhs instanceof FieldFilter || lhs instanceof CompositeFilter,\n 0x95f4,\n 'Only field filters and composite filters are accepted.'\n );\n hardAssert(\n rhs instanceof FieldFilter || rhs instanceof CompositeFilter,\n 0x6381,\n 'Only field filters and composite filters are accepted.'\n );\n\n let result: Filter;\n\n if (lhs instanceof FieldFilter) {\n if (rhs instanceof FieldFilter) {\n // FieldFilter FieldFilter\n result = applyDistributionFieldFilters(lhs, rhs);\n } else {\n // FieldFilter CompositeFilter\n result = applyDistributionFieldAndCompositeFilters(lhs, rhs);\n }\n } else {\n if (rhs instanceof FieldFilter) {\n // CompositeFilter FieldFilter\n result = applyDistributionFieldAndCompositeFilters(rhs, lhs);\n } else {\n // CompositeFilter CompositeFilter\n result = applyDistributionCompositeFilters(lhs, rhs);\n }\n }\n\n return applyAssociation(result);\n}\n\nfunction applyDistributionFieldFilters(\n lhs: FieldFilter,\n rhs: FieldFilter\n): Filter {\n // Conjunction distribution for two field filters is the conjunction of them.\n return CompositeFilter.create([lhs, rhs], CompositeOperator.AND);\n}\n\nfunction applyDistributionCompositeFilters(\n lhs: CompositeFilter,\n rhs: CompositeFilter\n): Filter {\n hardAssert(\n lhs.filters.length > 0 && rhs.filters.length > 0,\n 0xbb85,\n 'Found an empty composite filter'\n );\n\n // There are four cases:\n // (A & B) & (C & D) --> (A & B & C & D)\n // (A & B) & (C | D) --> (A & B & C) | (A & B & D)\n // (A | B) & (C & D) --> (C & D & A) | (C & D & B)\n // (A | B) & (C | D) --> (A & C) | (A & D) | (B & C) | (B & D)\n\n // Case 1 is a merge.\n if (compositeFilterIsConjunction(lhs) && compositeFilterIsConjunction(rhs)) {\n return compositeFilterWithAddedFilters(lhs, rhs.getFilters());\n }\n\n // Case 2,3,4 all have at least one side (lhs or rhs) that is a disjunction. In all three cases\n // we should take each element of the disjunction and distribute it over the other side, and\n // return the disjunction of the distribution results.\n const disjunctionSide = compositeFilterIsDisjunction(lhs) ? lhs : rhs;\n const otherSide = compositeFilterIsDisjunction(lhs) ? rhs : lhs;\n const results = disjunctionSide.filters.map(subfilter =>\n applyDistribution(subfilter, otherSide)\n );\n return CompositeFilter.create(results, CompositeOperator.OR);\n}\n\nfunction applyDistributionFieldAndCompositeFilters(\n fieldFilter: FieldFilter,\n compositeFilter: CompositeFilter\n): Filter {\n // There are two cases:\n // A & (B & C) --> (A & B & C)\n // A & (B | C) --> (A & B) | (A & C)\n if (compositeFilterIsConjunction(compositeFilter)) {\n // Case 1\n return compositeFilterWithAddedFilters(\n compositeFilter,\n fieldFilter.getFilters()\n );\n } else {\n // Case 2\n const newFilters = compositeFilter.filters.map(subfilter =>\n applyDistribution(fieldFilter, subfilter)\n );\n\n return CompositeFilter.create(newFilters, CompositeOperator.OR);\n }\n}\n\n/**\n * Applies the associativity property to the given filter and returns the resulting filter.\n *\n *

    \n *
  • A | (B | C) == (A | B) | C == (A | B | C)\n *
  • A & (B & C) == (A & B) & C == (A & B & C)\n *
\n *\n *

For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic\n */\nexport function applyAssociation(filter: Filter): Filter {\n hardAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 0x2e4a,\n 'Only field filters and composite filters are accepted.'\n );\n\n if (filter instanceof FieldFilter) {\n return filter;\n }\n\n const filters = filter.getFilters();\n\n // If the composite filter only contains 1 filter, apply associativity to it.\n if (filters.length === 1) {\n return applyAssociation(filters[0]);\n }\n\n // Associativity applied to a flat composite filter results is itself.\n if (compositeFilterIsFlat(filter)) {\n return filter;\n }\n\n // First apply associativity to all subfilters. This will in turn recursively apply\n // associativity to all nested composite filters and field filters.\n const updatedFilters = filters.map(subfilter => applyAssociation(subfilter));\n\n // For composite subfilters that perform the same kind of logical operation as `compositeFilter`\n // take out their filters and add them to `compositeFilter`. For example:\n // compositeFilter = (A | (B | C | D))\n // compositeSubfilter = (B | C | D)\n // Result: (A | B | C | D)\n // Note that the `compositeSubfilter` has been eliminated, and its filters (B, C, D) have been\n // added to the top-level \"compositeFilter\".\n const newSubfilters: Filter[] = [];\n updatedFilters.forEach(subfilter => {\n if (subfilter instanceof FieldFilter) {\n newSubfilters.push(subfilter);\n } else if (subfilter instanceof CompositeFilter) {\n if (subfilter.op === filter.op) {\n // compositeFilter: (A | (B | C))\n // compositeSubfilter: (B | C)\n // Result: (A | B | C)\n newSubfilters.push(...subfilter.filters);\n } else {\n // compositeFilter: (A | (B & C))\n // compositeSubfilter: (B & C)\n // Result: (A | (B & C))\n newSubfilters.push(subfilter);\n }\n }\n });\n\n if (newSubfilters.length === 1) {\n return newSubfilters[0];\n }\n\n return CompositeFilter.create(newSubfilters, filter.op);\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Target } from '../core/target';\nimport { DocumentMap } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldIndex, IndexOffset } from '../model/field_index';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { IndexManager, IndexType } from './index_manager';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\n/**\n * An in-memory implementation of IndexManager.\n */\nexport class MemoryIndexManager implements IndexManager {\n private collectionParentIndex = new MemoryCollectionParentIndex();\n\n addToCollectionParentIndex(\n transaction: PersistenceTransaction,\n collectionPath: ResourcePath\n ): PersistencePromise {\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 {\n IndexEntry,\n indexEntryComparator,\n encodeKeySafeBytes,\n decodeKeySafeBytes\n} 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 indexEntry.dbIndexEntry(\n this.uid,\n this.encodeDirectionalKey(fieldIndex, document.key),\n document.key\n )\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.dbIndexEntryKey(\n this.uid,\n this.encodeDirectionalKey(fieldIndex, document.key),\n document.key\n )\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 encodeKeySafeBytes(\n this.encodeDirectionalKey(fieldIndex, documentKey)\n )\n ])\n },\n (_, entry) => {\n results = results.add(\n new IndexEntry(\n fieldIndex.indexId,\n documentKey,\n decodeKeySafeBytes(entry.arrayValue),\n decodeKeySafeBytes(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 = bounds[i].dbIndexEntryKey(\n this.uid,\n EMPTY_VALUE,\n DocumentKey.empty()\n );\n const upperBound = bounds[i + 1].dbIndexEntryKey(\n this.uid,\n EMPTY_VALUE,\n DocumentKey.empty()\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(0xad8a, '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 0x7099,\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from '../model/document_key';\nimport { fail, hardAssert } from '../util/assert';\n\nimport {\n DbDocumentMutation,\n DbMutationBatch,\n DbRemoteDocument\n} from './indexeddb_schema';\nimport { DbRemoteDocument as DbRemoteDocumentLegacy } from './indexeddb_schema_legacy';\nimport {\n DbDocumentMutationKey,\n DbDocumentMutationStore,\n DbMutationBatchKey,\n DbMutationBatchStore,\n newDbDocumentMutationKey\n} from './indexeddb_sentinels';\nimport { PersistencePromise } from './persistence_promise';\nimport { SimpleDbTransaction } from './simple_db';\n\n/**\n * Delete a mutation batch and the associated document mutations.\n * @returns A PersistencePromise of the document mutations that were removed.\n */\nexport function removeMutationBatch(\n txn: SimpleDbTransaction,\n userId: string,\n batch: { batchId: number; mutations: Array<{ key: DocumentKey }> }\n): PersistencePromise {\n const mutationStore = txn.store(\n DbMutationBatchStore\n );\n const indexTxn = txn.store(\n DbDocumentMutationStore\n );\n const promises: Array> = [];\n\n const range = IDBKeyRange.only(batch.batchId);\n let numDeleted = 0;\n const removePromise = mutationStore.iterate(\n { range },\n (key, value, control) => {\n numDeleted++;\n return control.delete();\n }\n );\n promises.push(\n removePromise.next(() => {\n hardAssert(\n numDeleted === 1,\n 0xb7de,\n 'Dangling document-mutation reference found: Missing batch',\n { batchId: batch.batchId }\n );\n })\n );\n const removedDocuments: DocumentKey[] = [];\n for (const mutation of batch.mutations) {\n const indexKey = newDbDocumentMutationKey(\n userId,\n mutation.key.path,\n batch.batchId\n );\n promises.push(indexTxn.delete(indexKey));\n removedDocuments.push(mutation.key);\n }\n return PersistencePromise.waitFor(promises).next(() => removedDocuments);\n}\n\n/**\n * Returns an approximate size for the given document.\n */\nexport function dbDocumentSize(\n doc: DbRemoteDocument | DbRemoteDocumentLegacy | null\n): number {\n if (!doc) {\n return 0;\n }\n\n let value: unknown;\n if (doc.document) {\n value = doc.document;\n } else if (doc.unknownDocument) {\n value = doc.unknownDocument;\n } else if (doc.noDocument) {\n value = doc.noDocument;\n } else {\n throw fail(0x398b, 'Unknown remote document type');\n }\n return JSON.stringify(value).length;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { isCollectionGroupQuery, isDocumentQuery, Query } from '../core/query';\nimport { BatchId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { DocumentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { MutationBatch } from '../model/mutation_batch';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport { decodeResourcePath } from './encoded_resource_path';\nimport { IndexManager } from './index_manager';\nimport { removeMutationBatch } from './indexeddb_mutation_batch_impl';\nimport {\n DbDocumentMutation,\n DbMutationBatch,\n DbMutationQueue\n} from './indexeddb_schema';\nimport {\n DbDocumentMutationKey,\n DbDocumentMutationPlaceholder,\n DbDocumentMutationStore,\n DbMutationBatchKey,\n DbMutationBatchStore,\n DbMutationBatchUserMutationsIndex,\n DbMutationQueueKey,\n DbMutationQueueStore,\n newDbDocumentMutationKey,\n newDbDocumentMutationPrefixForPath,\n newDbDocumentMutationPrefixForUser\n} from './indexeddb_sentinels';\nimport { IndexedDbTransaction, getStore } from './indexeddb_transaction';\nimport {\n fromDbMutationBatch,\n LocalSerializer,\n toDbMutationBatch\n} from './local_serializer';\nimport { MutationQueue } from './mutation_queue';\nimport { ReferenceDelegate } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\n/** A mutation queue for a specific user, backed by IndexedDB. */\nexport class IndexedDbMutationQueue implements MutationQueue {\n /**\n * Caches the document keys for pending mutation batches. If the mutation\n * has been removed from IndexedDb, the cached value may continue to\n * be used to retrieve the batch's document keys. To remove a cached value\n * locally, `removeCachedMutationKeys()` should be invoked either directly\n * or through `removeMutationBatches()`.\n *\n * With multi-tab, when the primary client acknowledges or rejects a mutation,\n * this cache is used by secondary clients to invalidate the local\n * view of the documents that were previously affected by the mutation.\n */\n // PORTING NOTE: Multi-tab only.\n private documentKeysByBatchId = {} as { [batchId: number]: DocumentKeySet };\n\n constructor(\n /**\n * The normalized userId (e.g. null UID => \"\" userId) used to store /\n * retrieve mutations.\n */\n private userId: string,\n private readonly serializer: LocalSerializer,\n private readonly indexManager: IndexManager,\n private readonly referenceDelegate: ReferenceDelegate\n ) {}\n\n /**\n * Creates a new mutation queue for the given user.\n * @param user - The user for which to create a mutation queue.\n * @param serializer - The serializer to use when persisting to IndexedDb.\n */\n static forUser(\n user: User,\n serializer: LocalSerializer,\n indexManager: IndexManager,\n referenceDelegate: ReferenceDelegate\n ): IndexedDbMutationQueue {\n // TODO(mcg): Figure out what constraints there are on userIDs\n // In particular, are there any reserved characters? are empty ids allowed?\n // For the moment store these together in the same mutations table assuming\n // that empty userIDs aren't allowed.\n hardAssert(user.uid !== '', 0xfb83, 'UserID must not be an empty string.');\n const userId = user.isAuthenticated() ? user.uid! : '';\n return new IndexedDbMutationQueue(\n userId,\n serializer,\n indexManager,\n referenceDelegate\n );\n }\n\n checkEmpty(transaction: PersistenceTransaction): PersistencePromise {\n let empty = true;\n const range = IDBKeyRange.bound(\n [this.userId, Number.NEGATIVE_INFINITY],\n [this.userId, Number.POSITIVE_INFINITY]\n );\n return mutationsStore(transaction)\n .iterate(\n { index: DbMutationBatchUserMutationsIndex, range },\n (key, value, control) => {\n empty = false;\n control.done();\n }\n )\n .next(() => empty);\n }\n\n addMutationBatch(\n transaction: PersistenceTransaction,\n localWriteTime: Timestamp,\n baseMutations: Mutation[],\n mutations: Mutation[]\n ): PersistencePromise {\n const documentStore = documentMutationsStore(transaction);\n const mutationStore = mutationsStore(transaction);\n\n // The IndexedDb implementation in Chrome (and Firefox) does not handle\n // compound indices that include auto-generated keys correctly. To ensure\n // that the index entry is added correctly in all browsers, we perform two\n // writes: The first write is used to retrieve the next auto-generated Batch\n // ID, and the second write populates the index and stores the actual\n // mutation batch.\n // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972\n\n // We write an empty object to obtain key\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return mutationStore.add({} as any).next(batchId => {\n hardAssert(\n typeof batchId === 'number',\n 0xbf7b,\n 'Auto-generated key is not a number'\n );\n\n const batch = new MutationBatch(\n batchId,\n localWriteTime,\n baseMutations,\n mutations\n );\n const dbBatch = toDbMutationBatch(this.serializer, this.userId, batch);\n\n const promises: Array> = [];\n let collectionParents = new SortedSet((l, r) =>\n primitiveComparator(l.canonicalString(), r.canonicalString())\n );\n for (const mutation of mutations) {\n const indexKey = newDbDocumentMutationKey(\n this.userId,\n mutation.key.path,\n batchId\n );\n collectionParents = collectionParents.add(mutation.key.path.popLast());\n promises.push(mutationStore.put(dbBatch));\n promises.push(\n documentStore.put(indexKey, DbDocumentMutationPlaceholder)\n );\n }\n\n collectionParents.forEach(parent => {\n promises.push(\n this.indexManager.addToCollectionParentIndex(transaction, parent)\n );\n });\n\n transaction.addOnCommittedListener(() => {\n this.documentKeysByBatchId[batchId] = batch.keys();\n });\n\n return PersistencePromise.waitFor(promises).next(() => batch);\n });\n }\n\n lookupMutationBatch(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise {\n return mutationsStore(transaction)\n .get(batchId)\n .next(dbBatch => {\n if (dbBatch) {\n hardAssert(\n dbBatch.userId === this.userId,\n 0x0030,\n `Unexpected user for mutation batch`,\n {\n userId: dbBatch.userId,\n batchId\n }\n );\n return fromDbMutationBatch(this.serializer, dbBatch);\n }\n return null;\n });\n }\n\n /**\n * Returns the document keys for the mutation batch with the given batchId.\n * For primary clients, this method returns `null` after\n * `removeMutationBatches()` has been called. Secondary clients return a\n * cached result until `removeCachedMutationKeys()` is invoked.\n */\n // PORTING NOTE: Multi-tab only.\n lookupMutationKeys(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise {\n if (this.documentKeysByBatchId[batchId]) {\n return PersistencePromise.resolve(\n this.documentKeysByBatchId[batchId]\n );\n } else {\n return this.lookupMutationBatch(transaction, batchId).next(batch => {\n if (batch) {\n const keys = batch.keys();\n this.documentKeysByBatchId[batchId] = keys;\n return keys;\n } else {\n return null;\n }\n });\n }\n }\n\n getNextMutationBatchAfterBatchId(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise {\n const nextBatchId = batchId + 1;\n\n const range = IDBKeyRange.lowerBound([this.userId, nextBatchId]);\n let foundBatch: MutationBatch | null = null;\n return mutationsStore(transaction)\n .iterate(\n { index: DbMutationBatchUserMutationsIndex, range },\n (key, dbBatch, control) => {\n if (dbBatch.userId === this.userId) {\n hardAssert(\n dbBatch.batchId >= nextBatchId,\n 0xb9a4,\n 'Should have found mutation after `nextBatchId`',\n { nextBatchId }\n );\n foundBatch = fromDbMutationBatch(this.serializer, dbBatch);\n }\n control.done();\n }\n )\n .next(() => foundBatch);\n }\n\n getHighestUnacknowledgedBatchId(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n const range = IDBKeyRange.upperBound([\n this.userId,\n Number.POSITIVE_INFINITY\n ]);\n\n let batchId = BATCHID_UNKNOWN;\n return mutationsStore(transaction)\n .iterate(\n { index: DbMutationBatchUserMutationsIndex, range, reverse: true },\n (key, dbBatch, control) => {\n batchId = dbBatch.batchId;\n control.done();\n }\n )\n .next(() => batchId);\n }\n\n getAllMutationBatches(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n const range = IDBKeyRange.bound(\n [this.userId, BATCHID_UNKNOWN],\n [this.userId, Number.POSITIVE_INFINITY]\n );\n return mutationsStore(transaction)\n .loadAll(DbMutationBatchUserMutationsIndex, range)\n .next(dbBatches =>\n dbBatches.map(dbBatch => fromDbMutationBatch(this.serializer, dbBatch))\n );\n }\n\n getAllMutationBatchesAffectingDocumentKey(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n // Scan the document-mutation index starting with a prefix starting with\n // the given documentKey.\n const indexPrefix = newDbDocumentMutationPrefixForPath(\n this.userId,\n documentKey.path\n );\n const indexStart = IDBKeyRange.lowerBound(indexPrefix);\n\n const results: MutationBatch[] = [];\n return documentMutationsStore(transaction)\n .iterate({ range: indexStart }, (indexKey, _, control) => {\n const [userID, encodedPath, batchId] = indexKey;\n\n // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n const path = decodeResourcePath(encodedPath);\n if (userID !== this.userId || !documentKey.path.isEqual(path)) {\n control.done();\n return;\n }\n // Look up the mutation batch in the store.\n return mutationsStore(transaction)\n .get(batchId)\n .next(mutation => {\n if (!mutation) {\n throw fail(\n 0xf028,\n 'Dangling document-mutation reference found: `indexKey` which points to `batchId`',\n {\n indexKey,\n batchId\n }\n );\n }\n hardAssert(\n mutation.userId === this.userId,\n 0x2907,\n `Unexpected user for mutation batch`,\n {\n userId: mutation.userId,\n batchId\n }\n );\n results.push(fromDbMutationBatch(this.serializer, mutation));\n });\n })\n .next(() => results);\n }\n\n getAllMutationBatchesAffectingDocumentKeys(\n transaction: PersistenceTransaction,\n documentKeys: SortedMap\n ): PersistencePromise {\n let uniqueBatchIDs = new SortedSet(primitiveComparator);\n\n const promises: Array> = [];\n documentKeys.forEach(documentKey => {\n const indexStart = newDbDocumentMutationPrefixForPath(\n this.userId,\n documentKey.path\n );\n const range = IDBKeyRange.lowerBound(indexStart);\n\n const promise = documentMutationsStore(transaction).iterate(\n { range },\n (indexKey, _, control) => {\n const [userID, encodedPath, batchID] = indexKey;\n\n // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n const path = decodeResourcePath(encodedPath);\n if (userID !== this.userId || !documentKey.path.isEqual(path)) {\n control.done();\n return;\n }\n\n uniqueBatchIDs = uniqueBatchIDs.add(batchID);\n }\n );\n\n promises.push(promise);\n });\n\n return PersistencePromise.waitFor(promises).next(() =>\n this.lookupMutationBatches(transaction, uniqueBatchIDs)\n );\n }\n\n getAllMutationBatchesAffectingQuery(\n transaction: PersistenceTransaction,\n query: Query\n ): PersistencePromise {\n debugAssert(\n !isDocumentQuery(query),\n \"Document queries shouldn't go down this path\"\n );\n debugAssert(\n !isCollectionGroupQuery(query),\n 'CollectionGroup queries should be handled in LocalDocumentsView'\n );\n\n const queryPath = query.path;\n const immediateChildrenLength = queryPath.length + 1;\n\n // TODO(mcg): Actually implement a single-collection query\n //\n // This is actually executing an ancestor query, traversing the whole\n // subtree below the collection which can be horrifically inefficient for\n // some structures. The right way to solve this is to implement the full\n // value index, but that's not in the cards in the near future so this is\n // the best we can do for the moment.\n //\n // Since we don't yet index the actual properties in the mutations, our\n // current approach is to just return all mutation batches that affect\n // documents in the collection being queried.\n const indexPrefix = newDbDocumentMutationPrefixForPath(\n this.userId,\n queryPath\n );\n const indexStart = IDBKeyRange.lowerBound(indexPrefix);\n\n // Collect up unique batchIDs encountered during a scan of the index. Use a\n // SortedSet to accumulate batch IDs so they can be traversed in order in a\n // scan of the main table.\n let uniqueBatchIDs = new SortedSet(primitiveComparator);\n return documentMutationsStore(transaction)\n .iterate({ range: indexStart }, (indexKey, _, control) => {\n const [userID, encodedPath, batchID] = indexKey;\n const path = decodeResourcePath(encodedPath);\n if (userID !== this.userId || !queryPath.isPrefixOf(path)) {\n control.done();\n return;\n }\n // Rows with document keys more than one segment longer than the\n // query path can't be matches. For example, a query on 'rooms'\n // can't match the document /rooms/abc/messages/xyx.\n // TODO(mcg): we'll need a different scanner when we implement\n // ancestor queries.\n if (path.length !== immediateChildrenLength) {\n return;\n }\n uniqueBatchIDs = uniqueBatchIDs.add(batchID);\n })\n .next(() => this.lookupMutationBatches(transaction, uniqueBatchIDs));\n }\n\n private lookupMutationBatches(\n transaction: PersistenceTransaction,\n batchIDs: SortedSet\n ): PersistencePromise {\n const results: MutationBatch[] = [];\n const promises: Array> = [];\n // TODO(rockwood): Implement this using iterate.\n batchIDs.forEach(batchId => {\n promises.push(\n mutationsStore(transaction)\n .get(batchId)\n .next(mutation => {\n if (mutation === null) {\n throw fail(\n 0x89ca,\n 'Dangling document-mutation reference found, which points to `batchId`',\n {\n batchId\n }\n );\n }\n hardAssert(\n mutation.userId === this.userId,\n 0x2614,\n `Unexpected user for mutation batch`,\n { userId: mutation.userId, batchId }\n );\n results.push(fromDbMutationBatch(this.serializer, mutation));\n })\n );\n });\n return PersistencePromise.waitFor(promises).next(() => results);\n }\n\n removeMutationBatch(\n transaction: PersistenceTransaction,\n batch: MutationBatch\n ): PersistencePromise {\n return removeMutationBatch(\n (transaction as IndexedDbTransaction).simpleDbTransaction,\n this.userId,\n batch\n ).next(removedDocuments => {\n transaction.addOnCommittedListener(() => {\n this.removeCachedMutationKeys(batch.batchId);\n });\n return PersistencePromise.forEach(\n removedDocuments,\n (key: DocumentKey) => {\n return this.referenceDelegate.markPotentiallyOrphaned(\n transaction,\n key\n );\n }\n );\n });\n }\n\n /**\n * Clears the cached keys for a mutation batch. This method should be\n * called by secondary clients after they process mutation updates.\n *\n * Note that this method does not have to be called from primary clients as\n * the corresponding cache entries are cleared when an acknowledged or\n * rejected batch is removed from the mutation queue.\n */\n // PORTING NOTE: Multi-tab only\n removeCachedMutationKeys(batchId: BatchId): void {\n delete this.documentKeysByBatchId[batchId];\n }\n\n performConsistencyCheck(\n txn: PersistenceTransaction\n ): PersistencePromise {\n return this.checkEmpty(txn).next(empty => {\n if (!empty) {\n return PersistencePromise.resolve();\n }\n\n // Verify that there are no entries in the documentMutations index if\n // the queue is empty.\n const startRange = IDBKeyRange.lowerBound(\n newDbDocumentMutationPrefixForUser(this.userId)\n );\n const danglingMutationReferences: ResourcePath[] = [];\n return documentMutationsStore(txn)\n .iterate({ range: startRange }, (key, _, control) => {\n const userID = key[0];\n if (userID !== this.userId) {\n control.done();\n return;\n } else {\n const path = decodeResourcePath(key[1]);\n danglingMutationReferences.push(path);\n }\n })\n .next(() => {\n hardAssert(\n danglingMutationReferences.length === 0,\n 0xdd90,\n 'Document leak -- detected dangling mutation references when queue is empty.',\n {\n danglingKeys: danglingMutationReferences.map(p =>\n p.canonicalString()\n )\n }\n );\n });\n });\n }\n\n containsKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return mutationQueueContainsKey(txn, this.userId, key);\n }\n\n // PORTING NOTE: Multi-tab only (state is held in memory in other clients).\n /** Returns the mutation queue's metadata from IndexedDb. */\n private getMutationQueueMetadata(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return mutationQueuesStore(transaction)\n .get(this.userId)\n .next((metadata: DbMutationQueue | null) => {\n return (\n metadata || {\n userId: this.userId,\n lastAcknowledgedBatchId: BATCHID_UNKNOWN,\n lastStreamToken: ''\n }\n );\n });\n }\n}\n\n/**\n * @returns true if the mutation queue for the given user contains a pending\n * mutation for the given key.\n */\nfunction mutationQueueContainsKey(\n txn: PersistenceTransaction,\n userId: string,\n key: DocumentKey\n): PersistencePromise {\n const indexKey = newDbDocumentMutationPrefixForPath(userId, key.path);\n const encodedPath = indexKey[1];\n const startRange = IDBKeyRange.lowerBound(indexKey);\n let containsKey = false;\n return documentMutationsStore(txn)\n .iterate({ range: startRange, keysOnly: true }, (key, value, control) => {\n const [userID, keyPath, /*batchID*/ _] = key;\n if (userID === userId && keyPath === encodedPath) {\n containsKey = true;\n }\n control.done();\n })\n .next(() => containsKey);\n}\n\n/** Returns true if any mutation queue contains the given document. */\nexport function mutationQueuesContainKey(\n txn: PersistenceTransaction,\n docKey: DocumentKey\n): PersistencePromise {\n let found = false;\n return mutationQueuesStore(txn)\n .iterateSerial(userId => {\n return mutationQueueContainsKey(txn, userId, docKey).next(containsKey => {\n if (containsKey) {\n found = true;\n }\n return PersistencePromise.resolve(!containsKey);\n });\n })\n .next(() => found);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutations object store.\n */\nfunction mutationsStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbMutationBatchStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction documentMutationsStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbDocumentMutationStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction mutationQueuesStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbMutationQueueStore\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TargetId } from './types';\n\n/** Offset to ensure non-overlapping target ids. */\nconst OFFSET = 2;\n\n/**\n * Generates monotonically increasing target IDs for sending targets to the\n * watch stream.\n *\n * The client constructs two generators, one for the target cache, and one for\n * for the sync engine (to generate limbo documents targets). These\n * generators produce non-overlapping IDs (by using even and odd IDs\n * respectively).\n *\n * By separating the target ID space, the query cache can generate target IDs\n * that persist across client restarts, while sync engine can independently\n * generate in-memory target IDs that are transient and can be reused after a\n * restart.\n */\nexport class TargetIdGenerator {\n constructor(private lastId: number) {}\n\n next(): TargetId {\n this.lastId += OFFSET;\n return this.lastId;\n }\n\n static forTargetCache(): TargetIdGenerator {\n // The target cache generator must return '2' in its first call to `next()`\n // as there is no differentiation in the protocol layer between an unset\n // number and the number '0'. If we were to sent a target with target ID\n // '0', the backend would consider it unset and replace it with its own ID.\n return new TargetIdGenerator(2 - OFFSET);\n }\n\n static forSyncEngine(): TargetIdGenerator {\n // Sync engine assigns target IDs for limbo document detection.\n return new TargetIdGenerator(1 - OFFSET);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { canonifyTarget, Target, targetEquals } from '../core/target';\nimport { TargetIdGenerator } from '../core/target_id_generator';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { DocumentKeySet, documentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { hardAssert } from '../util/assert';\nimport { immediateSuccessor } from '../util/misc';\n\nimport {\n decodeResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { IndexedDbLruDelegate } from './indexeddb_lru_delegate';\nimport { DbTarget, DbTargetDocument, DbTargetGlobal } from './indexeddb_schema';\nimport {\n DbTargetDocumentDocumentTargetsIndex,\n DbTargetDocumentKey,\n DbTargetDocumentStore,\n DbTargetGlobalKey,\n DbTargetGlobalStore,\n DbTargetKey,\n DbTargetQueryTargetsIndexName,\n DbTargetStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport { fromDbTarget, LocalSerializer, toDbTarget } from './local_serializer';\nimport { ActiveTargets } from './lru_garbage_collector';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\nimport { TargetCache } from './target_cache';\nimport { TargetData } from './target_data';\n\nexport class IndexedDbTargetCache implements TargetCache {\n constructor(\n private readonly referenceDelegate: IndexedDbLruDelegate,\n private serializer: LocalSerializer\n ) {}\n\n // PORTING NOTE: We don't cache global metadata for the target cache, since\n // some of it (in particular `highestTargetId`) can be modified by secondary\n // tabs. We could perhaps be more granular (and e.g. still cache\n // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go\n // to IndexedDb whenever we need to read metadata. We can revisit if it turns\n // out to have a meaningful performance impact.\n\n allocateTargetId(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(metadata => {\n const targetIdGenerator = new TargetIdGenerator(metadata.highestTargetId);\n metadata.highestTargetId = targetIdGenerator.next();\n return this.saveMetadata(transaction, metadata).next(\n () => metadata.highestTargetId\n );\n });\n }\n\n getLastRemoteSnapshotVersion(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(metadata => {\n return SnapshotVersion.fromTimestamp(\n new Timestamp(\n metadata.lastRemoteSnapshotVersion.seconds,\n metadata.lastRemoteSnapshotVersion.nanoseconds\n )\n );\n });\n }\n\n getHighestSequenceNumber(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(\n targetGlobal => targetGlobal.highestListenSequenceNumber\n );\n }\n\n setTargetsMetadata(\n transaction: PersistenceTransaction,\n highestListenSequenceNumber: number,\n lastRemoteSnapshotVersion?: SnapshotVersion\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(metadata => {\n metadata.highestListenSequenceNumber = highestListenSequenceNumber;\n if (lastRemoteSnapshotVersion) {\n metadata.lastRemoteSnapshotVersion =\n lastRemoteSnapshotVersion.toTimestamp();\n }\n if (highestListenSequenceNumber > metadata.highestListenSequenceNumber) {\n metadata.highestListenSequenceNumber = highestListenSequenceNumber;\n }\n return this.saveMetadata(transaction, metadata);\n });\n }\n\n addTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n return this.saveTargetData(transaction, targetData).next(() => {\n return this.retrieveMetadata(transaction).next(metadata => {\n metadata.targetCount += 1;\n this.updateMetadataFromTargetData(targetData, metadata);\n return this.saveMetadata(transaction, metadata);\n });\n });\n }\n\n updateTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n return this.saveTargetData(transaction, targetData);\n }\n\n removeTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n return this.removeMatchingKeysForTargetId(transaction, targetData.targetId)\n .next(() => targetsStore(transaction).delete(targetData.targetId))\n .next(() => this.retrieveMetadata(transaction))\n .next(metadata => {\n hardAssert(\n metadata.targetCount > 0,\n 0x1f81,\n 'Removing from an empty target cache'\n );\n metadata.targetCount -= 1;\n return this.saveMetadata(transaction, metadata);\n });\n }\n\n /**\n * Drops any targets with sequence number less than or equal to the upper bound, excepting those\n * present in `activeTargetIds`. Document associations for the removed targets are also removed.\n * Returns the number of targets removed.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n let count = 0;\n const promises: Array> = [];\n return targetsStore(txn)\n .iterate((key, value) => {\n const targetData = fromDbTarget(value);\n if (\n targetData.sequenceNumber <= upperBound &&\n activeTargetIds.get(targetData.targetId) === null\n ) {\n count++;\n promises.push(this.removeTargetData(txn, targetData));\n }\n })\n .next(() => PersistencePromise.waitFor(promises))\n .next(() => count);\n }\n\n /**\n * Call provided function with each `TargetData` that we have cached.\n */\n forEachTarget(\n txn: PersistenceTransaction,\n f: (q: TargetData) => void\n ): PersistencePromise {\n return targetsStore(txn).iterate((key, value) => {\n const targetData = fromDbTarget(value);\n f(targetData);\n });\n }\n\n private retrieveMetadata(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return globalTargetStore(transaction)\n .get(DbTargetGlobalKey)\n .next(metadata => {\n hardAssert(metadata !== null, 0x0b48, 'Missing metadata row.');\n return metadata;\n });\n }\n\n private saveMetadata(\n transaction: PersistenceTransaction,\n metadata: DbTargetGlobal\n ): PersistencePromise {\n return globalTargetStore(transaction).put(DbTargetGlobalKey, metadata);\n }\n\n private saveTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n return targetsStore(transaction).put(\n toDbTarget(this.serializer, targetData)\n );\n }\n\n /**\n * In-place updates the provided metadata to account for values in the given\n * TargetData. Saving is done separately. Returns true if there were any\n * changes to the metadata.\n */\n private updateMetadataFromTargetData(\n targetData: TargetData,\n metadata: DbTargetGlobal\n ): boolean {\n let updated = false;\n if (targetData.targetId > metadata.highestTargetId) {\n metadata.highestTargetId = targetData.targetId;\n updated = true;\n }\n\n if (targetData.sequenceNumber > metadata.highestListenSequenceNumber) {\n metadata.highestListenSequenceNumber = targetData.sequenceNumber;\n updated = true;\n }\n return updated;\n }\n\n getTargetCount(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(\n metadata => metadata.targetCount\n );\n }\n\n getTargetData(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise {\n // Iterating by the canonicalId may yield more than one result because\n // canonicalId values are not required to be unique per target. This query\n // depends on the queryTargets index to be efficient.\n const canonicalId = canonifyTarget(target);\n const range = IDBKeyRange.bound(\n [canonicalId, Number.NEGATIVE_INFINITY],\n [canonicalId, Number.POSITIVE_INFINITY]\n );\n let result: TargetData | null = null;\n return targetsStore(transaction)\n .iterate(\n { range, index: DbTargetQueryTargetsIndexName },\n (key, value, control) => {\n const found = fromDbTarget(value);\n // After finding a potential match, check that the target is\n // actually equal to the requested target.\n if (targetEquals(target, found.target)) {\n result = found;\n control.done();\n }\n }\n )\n .next(() => result);\n }\n\n addMatchingKeys(\n txn: PersistenceTransaction,\n keys: DocumentKeySet,\n targetId: TargetId\n ): PersistencePromise {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n const promises: Array> = [];\n const store = documentTargetStore(txn);\n keys.forEach(key => {\n const path = encodeResourcePath(key.path);\n promises.push(store.put({ targetId, path }));\n promises.push(this.referenceDelegate.addReference(txn, targetId, key));\n });\n return PersistencePromise.waitFor(promises);\n }\n\n removeMatchingKeys(\n txn: PersistenceTransaction,\n keys: DocumentKeySet,\n targetId: TargetId\n ): PersistencePromise {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n const store = documentTargetStore(txn);\n return PersistencePromise.forEach(keys, (key: DocumentKey) => {\n const path = encodeResourcePath(key.path);\n return PersistencePromise.waitFor([\n store.delete([targetId, path]),\n this.referenceDelegate.removeReference(txn, targetId, key)\n ]);\n });\n }\n\n removeMatchingKeysForTargetId(\n txn: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise {\n const store = documentTargetStore(txn);\n const range = IDBKeyRange.bound(\n [targetId],\n [targetId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n return store.delete(range);\n }\n\n getMatchingKeysForTargetId(\n txn: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise {\n const range = IDBKeyRange.bound(\n [targetId],\n [targetId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n const store = documentTargetStore(txn);\n let result = documentKeySet();\n\n return store\n .iterate({ range, keysOnly: true }, (key, _, control) => {\n const path = decodeResourcePath(key[1]);\n const docKey = new DocumentKey(path);\n result = result.add(docKey);\n })\n .next(() => result);\n }\n\n containsKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n const path = encodeResourcePath(key.path);\n const range = IDBKeyRange.bound(\n [path],\n [immediateSuccessor(path)],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n let count = 0;\n return documentTargetStore(txn!)\n .iterate(\n {\n index: DbTargetDocumentDocumentTargetsIndex,\n keysOnly: true,\n range\n },\n ([targetId, path], _, control) => {\n // Having a sentinel row for a document does not count as containing that document;\n // For the target cache, containing the document means the document is part of some\n // target.\n if (targetId !== 0) {\n count++;\n control.done();\n }\n }\n )\n .next(() => count > 0);\n }\n\n /**\n * Looks up a TargetData entry by target ID.\n *\n * @param targetId - The target ID of the TargetData entry to look up.\n * @returns The cached TargetData entry, or null if the cache has no entry for\n * the target.\n */\n // PORTING NOTE: Multi-tab only.\n getTargetDataForTarget(\n transaction: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise {\n return targetsStore(transaction)\n .get(targetId)\n .next(found => {\n if (found) {\n return fromDbTarget(found);\n } else {\n return null;\n }\n });\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the queries object store.\n */\nfunction targetsStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbTargetStore);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the target globals object store.\n */\nfunction globalTargetStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbTargetGlobalStore);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document target object store.\n */\nexport function documentTargetStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbTargetDocumentStore\n );\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequenceNumber, 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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\nimport { ListenSequence } from '../core/listen_sequence';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { DocumentKey } from '../model/document_key';\n\nimport {\n decodeResourcePath,\n EncodedResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { IndexedDbLruDelegate } from './indexeddb_lru_delegate';\nimport { mutationQueuesContainKey } from './indexeddb_mutation_queue';\nimport { DbTargetDocument } from './indexeddb_schema';\nimport { DbTargetDocumentDocumentTargetsIndex } from './indexeddb_sentinels';\nimport {\n documentTargetStore,\n IndexedDbTargetCache\n} from './indexeddb_target_cache';\nimport {\n ActiveTargets,\n LruGarbageCollector,\n LruParams\n} from './lru_garbage_collector';\nimport { newLruGarbageCollector } from './lru_garbage_collector_impl';\nimport { Persistence } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { TargetData } from './target_data';\n\n/** Provides LRU functionality for IndexedDB persistence. */\nexport class IndexedDbLruDelegateImpl implements IndexedDbLruDelegate {\n readonly garbageCollector: LruGarbageCollector;\n\n constructor(private readonly db: Persistence, params: LruParams) {\n this.garbageCollector = newLruGarbageCollector(this, params);\n }\n\n getSequenceNumberCount(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const docCountPromise = this.orphanedDocumentCount(txn);\n const targetCountPromise = this.db.getTargetCache().getTargetCount(txn);\n return targetCountPromise.next(targetCount =>\n docCountPromise.next(docCount => targetCount + docCount)\n );\n }\n\n private orphanedDocumentCount(\n txn: PersistenceTransaction\n ): PersistencePromise {\n let orphanedCount = 0;\n return this.forEachOrphanedDocumentSequenceNumber(txn, _ => {\n orphanedCount++;\n }).next(() => orphanedCount);\n }\n\n forEachTarget(\n txn: PersistenceTransaction,\n f: (q: TargetData) => void\n ): PersistencePromise {\n return this.db.getTargetCache().forEachTarget(txn, f);\n }\n\n forEachOrphanedDocumentSequenceNumber(\n txn: PersistenceTransaction,\n f: (sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise {\n return this.forEachOrphanedDocument(txn, (docKey, sequenceNumber) =>\n f(sequenceNumber)\n );\n }\n\n addReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise {\n return writeSentinelKey(txn, key);\n }\n\n removeReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise {\n return writeSentinelKey(txn, key);\n }\n\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n return (this.db.getTargetCache() as IndexedDbTargetCache).removeTargets(\n txn,\n upperBound,\n activeTargetIds\n );\n }\n\n markPotentiallyOrphaned(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return writeSentinelKey(txn, key);\n }\n\n /**\n * Returns true if anything would prevent this document from being garbage\n * collected, given that the document in question is not present in any\n * targets and has a sequence number less than or equal to the upper bound for\n * the collection run.\n */\n private isPinned(\n txn: PersistenceTransaction,\n docKey: DocumentKey\n ): PersistencePromise {\n return mutationQueuesContainKey(txn, docKey);\n }\n\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise {\n const documentCache = this.db.getRemoteDocumentCache();\n const changeBuffer = documentCache.newChangeBuffer();\n\n const promises: Array> = [];\n let documentCount = 0;\n\n const iteration = this.forEachOrphanedDocument(\n txn,\n (docKey, sequenceNumber) => {\n if (sequenceNumber <= upperBound) {\n const p = this.isPinned(txn, docKey).next(isPinned => {\n if (!isPinned) {\n documentCount++;\n // Our size accounting requires us to read all documents before\n // removing them.\n return changeBuffer.getEntry(txn, docKey).next(() => {\n changeBuffer.removeEntry(docKey, SnapshotVersion.min());\n return documentTargetStore(txn).delete(sentinelKey(docKey));\n });\n }\n });\n promises.push(p);\n }\n }\n );\n\n return iteration\n .next(() => PersistencePromise.waitFor(promises))\n .next(() => changeBuffer.apply(txn))\n .next(() => documentCount);\n }\n\n removeTarget(\n txn: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n const updated = targetData.withSequenceNumber(txn.currentSequenceNumber);\n return this.db.getTargetCache().updateTargetData(txn, updated);\n }\n\n updateLimboDocument(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return writeSentinelKey(txn, key);\n }\n\n /**\n * Call provided function for each document in the cache that is 'orphaned'. Orphaned\n * means not a part of any target, so the only entry in the target-document index for\n * that document will be the sentinel row (targetId 0), which will also have the sequence\n * number for the last time the document was accessed.\n */\n private forEachOrphanedDocument(\n txn: PersistenceTransaction,\n f: (docKey: DocumentKey, sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise {\n const store = documentTargetStore(txn);\n let nextToReport: ListenSequenceNumber = ListenSequence.INVALID;\n let nextPath: EncodedResourcePath;\n return store\n .iterate(\n {\n index: DbTargetDocumentDocumentTargetsIndex\n },\n ([targetId, docKey], { path, sequenceNumber }) => {\n if (targetId === 0) {\n // if nextToReport is valid, report it, this is a new key so the\n // last one must not be a member of any targets.\n if (nextToReport !== ListenSequence.INVALID) {\n f(new DocumentKey(decodeResourcePath(nextPath)), nextToReport);\n }\n // set nextToReport to be this sequence number. It's the next one we\n // might report, if we don't find any targets for this document.\n // Note that the sequence number must be defined when the targetId\n // is 0.\n nextToReport = sequenceNumber!;\n nextPath = path;\n } else {\n // set nextToReport to be invalid, we know we don't need to report\n // this one since we found a target for it.\n nextToReport = ListenSequence.INVALID;\n }\n }\n )\n .next(() => {\n // Since we report sequence numbers after getting to the next key, we\n // need to check if the last key we iterated over was an orphaned\n // document and report it.\n if (nextToReport !== ListenSequence.INVALID) {\n f(new DocumentKey(decodeResourcePath(nextPath)), nextToReport);\n }\n });\n }\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise {\n return this.db.getRemoteDocumentCache().getSize(txn);\n }\n}\n\nfunction sentinelKey(key: DocumentKey): [TargetId, EncodedResourcePath] {\n return [0, encodeResourcePath(key.path)];\n}\n\n/**\n * @returns A value suitable for writing a sentinel row in the target-document\n * store.\n */\nfunction sentinelRow(\n key: DocumentKey,\n sequenceNumber: ListenSequenceNumber\n): DbTargetDocument {\n return { targetId: 0, path: encodeResourcePath(key.path), sequenceNumber };\n}\n\nfunction writeSentinelKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n): PersistencePromise {\n return documentTargetStore(txn).put(\n sentinelRow(key, txn.currentSequenceNumber)\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { DocumentKeySet, MutableDocumentMap } from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { debugAssert } from '../util/assert';\nimport { ObjectMap } from '../util/obj_map';\n\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\n/**\n * An in-memory buffer of entries to be written to a RemoteDocumentCache.\n * It can be used to batch up a set of changes to be written to the cache, but\n * additionally supports reading entries back with the `getEntry()` method,\n * falling back to the underlying RemoteDocumentCache if no entry is\n * buffered.\n *\n * Entries added to the cache *must* be read first. This is to facilitate\n * calculating the size delta of the pending changes.\n *\n * PORTING NOTE: This class was implemented then removed from other platforms.\n * If byte-counting ends up being needed on the other platforms, consider\n * porting this class as part of that implementation work.\n */\nexport abstract class RemoteDocumentChangeBuffer {\n // A mapping of document key to the new cache entry that should be written.\n protected changes: ObjectMap = 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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Query, queryMatches } from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport {\n DocumentKeySet,\n DocumentSizeEntries,\n MutableDocumentMap,\n mutableDocumentMap,\n OverlayMap\n} from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { IndexOffset } from '../model/field_index';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { IndexManager } from './index_manager';\nimport { dbDocumentSize } from './indexeddb_mutation_batch_impl';\nimport { DbRemoteDocument, DbRemoteDocumentGlobal } from './indexeddb_schema';\nimport {\n DbRemoteDocumentCollectionGroupIndex,\n DbRemoteDocumentDocumentKeyIndex,\n DbRemoteDocumentGlobalKey,\n DbRemoteDocumentGlobalStore,\n DbRemoteDocumentKey,\n DbRemoteDocumentStore,\n DbTimestampKey\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n fromDbRemoteDocument,\n LocalSerializer,\n toDbRemoteDocument,\n toDbTimestampKey\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { QueryContext } from './query_context';\nimport { RemoteDocumentCache } from './remote_document_cache';\nimport { RemoteDocumentChangeBuffer } from './remote_document_change_buffer';\nimport { SimpleDbStore } from './simple_db';\n\nexport interface DocumentSizeEntry {\n document: MutableDocument;\n size: number;\n}\n\nexport interface IndexedDbRemoteDocumentCache extends RemoteDocumentCache {\n // The IndexedDbRemoteDocumentCache doesn't implement any methods on top\n // of RemoteDocumentCache. This class exists for consistency.\n}\n\n/**\n * The RemoteDocumentCache for IndexedDb. To construct, invoke\n * `newIndexedDbRemoteDocumentCache()`.\n */\nclass IndexedDbRemoteDocumentCacheImpl implements IndexedDbRemoteDocumentCache {\n indexManager!: IndexManager;\n\n constructor(readonly serializer: LocalSerializer) {}\n\n setIndexManager(indexManager: IndexManager): void {\n this.indexManager = indexManager;\n }\n\n /**\n * Adds the supplied entries to the cache.\n *\n * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n */\n addEntry(\n transaction: PersistenceTransaction,\n key: DocumentKey,\n doc: DbRemoteDocument\n ): PersistencePromise {\n const documentStore = remoteDocumentsStore(transaction);\n return documentStore.put(doc);\n }\n\n /**\n * Removes a document from the cache.\n *\n * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n */\n removeEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey,\n readTime: SnapshotVersion\n ): PersistencePromise {\n const store = remoteDocumentsStore(transaction);\n return store.delete(dbReadTimeKey(documentKey, readTime));\n }\n\n /**\n * Updates the current cache size.\n *\n * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the\n * cache's metadata.\n */\n updateMetadata(\n transaction: PersistenceTransaction,\n sizeDelta: number\n ): PersistencePromise {\n return this.getMetadata(transaction).next(metadata => {\n metadata.byteSize += sizeDelta;\n return this.setMetadata(transaction, metadata);\n });\n }\n\n getEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n let doc = MutableDocument.newInvalidDocument(documentKey);\n return remoteDocumentsStore(transaction)\n .iterate(\n {\n index: DbRemoteDocumentDocumentKeyIndex,\n range: IDBKeyRange.only(dbKey(documentKey))\n },\n (_, dbRemoteDoc) => {\n doc = this.maybeDecodeDocument(documentKey, dbRemoteDoc);\n }\n )\n .next(() => doc);\n }\n\n /**\n * Looks up an entry in the cache.\n *\n * @param documentKey - The key of the entry to look up.\n * @returns The cached document entry and its size.\n */\n getSizedEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n let result = {\n size: 0,\n document: MutableDocument.newInvalidDocument(documentKey)\n };\n return remoteDocumentsStore(transaction)\n .iterate(\n {\n index: DbRemoteDocumentDocumentKeyIndex,\n range: IDBKeyRange.only(dbKey(documentKey))\n },\n (_, dbRemoteDoc) => {\n result = {\n document: this.maybeDecodeDocument(documentKey, dbRemoteDoc),\n size: dbDocumentSize(dbRemoteDoc)\n };\n }\n )\n .next(() => result);\n }\n\n getEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise {\n let results = mutableDocumentMap();\n return this.forEachDbEntry(\n transaction,\n documentKeys,\n (key, dbRemoteDoc) => {\n const doc = this.maybeDecodeDocument(key, dbRemoteDoc);\n results = results.insert(key, doc);\n }\n ).next(() => results);\n }\n\n /**\n * Looks up several entries in the cache.\n *\n * @param documentKeys - The set of keys entries to look up.\n * @returns A map of documents indexed by key and a map of sizes indexed by\n * key (zero if the document does not exist).\n */\n getSizedEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise {\n let results = mutableDocumentMap();\n let sizeMap = new SortedMap(DocumentKey.comparator);\n return this.forEachDbEntry(\n transaction,\n documentKeys,\n (key, dbRemoteDoc) => {\n const doc = this.maybeDecodeDocument(key, dbRemoteDoc);\n results = results.insert(key, doc);\n sizeMap = sizeMap.insert(key, dbDocumentSize(dbRemoteDoc));\n }\n ).next(() => {\n return { documents: results, sizeMap };\n });\n }\n\n private forEachDbEntry(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet,\n callback: (key: DocumentKey, doc: DbRemoteDocument | null) => void\n ): PersistencePromise {\n if (documentKeys.isEmpty()) {\n return PersistencePromise.resolve();\n }\n\n let sortedKeys = new SortedSet(dbKeyComparator);\n documentKeys.forEach(e => (sortedKeys = sortedKeys.add(e)));\n const range = IDBKeyRange.bound(\n dbKey(sortedKeys.first()!),\n dbKey(sortedKeys.last()!)\n );\n const keyIter = sortedKeys.getIterator();\n let nextKey: DocumentKey | null = keyIter.getNext();\n\n return remoteDocumentsStore(transaction)\n .iterate(\n { index: DbRemoteDocumentDocumentKeyIndex, range },\n (_, dbRemoteDoc, control) => {\n const potentialKey = DocumentKey.fromSegments([\n ...dbRemoteDoc.prefixPath,\n dbRemoteDoc.collectionGroup,\n dbRemoteDoc.documentId\n ]);\n\n // Go through keys not found in cache.\n while (nextKey && dbKeyComparator(nextKey!, potentialKey) < 0) {\n callback(nextKey!, null);\n nextKey = keyIter.getNext();\n }\n\n if (nextKey && nextKey!.isEqual(potentialKey)) {\n // Key found in cache.\n callback(nextKey!, dbRemoteDoc);\n nextKey = keyIter.hasNext() ? keyIter.getNext() : null;\n }\n\n // Skip to the next key (if there is one).\n if (nextKey) {\n control.skip(dbKey(nextKey));\n } else {\n control.done();\n }\n }\n )\n .next(() => {\n // The rest of the keys are not in the cache. One case where `iterate`\n // above won't go through them is when the cache is empty.\n while (nextKey) {\n callback(nextKey!, null);\n nextKey = keyIter.hasNext() ? keyIter.getNext() : null;\n }\n });\n }\n\n getDocumentsMatchingQuery(\n transaction: PersistenceTransaction,\n query: Query,\n offset: IndexOffset,\n mutatedDocs: OverlayMap,\n context?: QueryContext\n ): PersistencePromise {\n const collection = query.path;\n const startKey = [\n collection.popLast().toArray(),\n collection.lastSegment(),\n toDbTimestampKey(offset.readTime),\n offset.documentKey.path.isEmpty()\n ? ''\n : offset.documentKey.path.lastSegment()\n ];\n const endKey: DbRemoteDocumentKey = [\n collection.popLast().toArray(),\n collection.lastSegment(),\n [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n ''\n ];\n\n return remoteDocumentsStore(transaction)\n .loadAll(IDBKeyRange.bound(startKey, endKey, true))\n .next(dbRemoteDocs => {\n context?.incrementDocumentReadCount(dbRemoteDocs.length);\n let results = mutableDocumentMap();\n for (const dbRemoteDoc of dbRemoteDocs) {\n const document = this.maybeDecodeDocument(\n DocumentKey.fromSegments(\n dbRemoteDoc.prefixPath.concat(\n dbRemoteDoc.collectionGroup,\n dbRemoteDoc.documentId\n )\n ),\n dbRemoteDoc\n );\n if (\n document.isFoundDocument() &&\n (queryMatches(query, document) || mutatedDocs.has(document.key))\n ) {\n // Either the document matches the given query, or it is mutated.\n results = results.insert(document.key, document);\n }\n }\n return results;\n });\n }\n\n getAllFromCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n offset: IndexOffset,\n limit: number\n ): PersistencePromise {\n debugAssert(limit > 0, 'Limit should be at least 1');\n let results = mutableDocumentMap();\n\n const startKey = dbCollectionGroupKey(collectionGroup, offset);\n const endKey = dbCollectionGroupKey(collectionGroup, IndexOffset.max());\n return remoteDocumentsStore(transaction)\n .iterate(\n {\n index: DbRemoteDocumentCollectionGroupIndex,\n range: IDBKeyRange.bound(startKey, endKey, true)\n },\n (_, dbRemoteDoc, control) => {\n const document = this.maybeDecodeDocument(\n DocumentKey.fromSegments(\n dbRemoteDoc.prefixPath.concat(\n dbRemoteDoc.collectionGroup,\n dbRemoteDoc.documentId\n )\n ),\n dbRemoteDoc\n );\n results = results.insert(document.key, document);\n if (results.size === limit) {\n control.done();\n }\n }\n )\n .next(() => results);\n }\n\n newChangeBuffer(options?: {\n trackRemovals: boolean;\n }): RemoteDocumentChangeBuffer {\n return new IndexedDbRemoteDocumentChangeBuffer(\n this,\n !!options && options.trackRemovals\n );\n }\n\n getSize(txn: PersistenceTransaction): PersistencePromise {\n return this.getMetadata(txn).next(metadata => metadata.byteSize);\n }\n\n private getMetadata(\n txn: PersistenceTransaction\n ): PersistencePromise {\n return documentGlobalStore(txn)\n .get(DbRemoteDocumentGlobalKey)\n .next(metadata => {\n hardAssert(!!metadata, 0x4e35, 'Missing document cache metadata');\n return metadata!;\n });\n }\n\n private setMetadata(\n txn: PersistenceTransaction,\n metadata: DbRemoteDocumentGlobal\n ): PersistencePromise {\n return documentGlobalStore(txn).put(DbRemoteDocumentGlobalKey, metadata);\n }\n\n /**\n * Decodes `dbRemoteDoc` and returns the document (or an invalid document if\n * the document corresponds to the format used for sentinel deletes).\n */\n private maybeDecodeDocument(\n documentKey: DocumentKey,\n dbRemoteDoc: DbRemoteDocument | null\n ): MutableDocument {\n if (dbRemoteDoc) {\n const doc = fromDbRemoteDocument(this.serializer, dbRemoteDoc);\n // Whether the document is a sentinel removal and should only be used in the\n // `getNewDocumentChanges()`\n const isSentinelRemoval =\n doc.isNoDocument() && doc.version.isEqual(SnapshotVersion.min());\n if (!isSentinelRemoval) {\n return doc;\n }\n }\n return MutableDocument.newInvalidDocument(documentKey);\n }\n}\n\n/** Creates a new IndexedDbRemoteDocumentCache. */\nexport function newIndexedDbRemoteDocumentCache(\n serializer: LocalSerializer\n): IndexedDbRemoteDocumentCache {\n return new IndexedDbRemoteDocumentCacheImpl(serializer);\n}\n\n/**\n * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache.\n *\n * Unlike the MemoryRemoteDocumentChangeBuffer, the IndexedDb implementation computes the size\n * delta for all submitted changes. This avoids having to re-read all documents from IndexedDb\n * when we apply the changes.\n */\nclass IndexedDbRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer {\n // A map of document sizes and read times prior to applying the changes in\n // this buffer.\n protected documentStates: ObjectMap<\n DocumentKey,\n { size: number; readTime: SnapshotVersion }\n > = new ObjectMap(\n key => key.toString(),\n (l, r) => l.isEqual(r)\n );\n\n /**\n * @param documentCache - The IndexedDbRemoteDocumentCache to apply the changes to.\n * @param trackRemovals - Whether to create sentinel deletes that can be tracked by\n * `getNewDocumentChanges()`.\n */\n constructor(\n private readonly documentCache: IndexedDbRemoteDocumentCacheImpl,\n private readonly trackRemovals: boolean\n ) {\n super();\n }\n\n protected applyChanges(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n const promises: Array> = [];\n\n let sizeDelta = 0;\n\n let collectionParents = new SortedSet((l, r) =>\n primitiveComparator(l.canonicalString(), r.canonicalString())\n );\n\n this.changes.forEach((key, documentChange) => {\n const previousDoc = this.documentStates.get(key);\n debugAssert(\n previousDoc !== undefined,\n `Cannot modify a document that wasn't read (for ${key})`\n );\n promises.push(\n this.documentCache.removeEntry(transaction, key, previousDoc.readTime)\n );\n if (documentChange.isValidDocument()) {\n debugAssert(\n !documentChange.readTime.isEqual(SnapshotVersion.min()),\n 'Cannot add a document with a read time of zero'\n );\n const doc = toDbRemoteDocument(\n this.documentCache.serializer,\n documentChange\n );\n collectionParents = collectionParents.add(key.path.popLast());\n\n const size = dbDocumentSize(doc);\n sizeDelta += size - previousDoc.size;\n promises.push(this.documentCache.addEntry(transaction, key, doc));\n } else {\n sizeDelta -= previousDoc.size;\n if (this.trackRemovals) {\n // In order to track removals, we store a \"sentinel delete\" in the\n // RemoteDocumentCache. This entry is represented by a NoDocument\n // with a version of 0 and ignored by `maybeDecodeDocument()` but\n // preserved in `getNewDocumentChanges()`.\n const deletedDoc = toDbRemoteDocument(\n this.documentCache.serializer,\n documentChange.convertToNoDocument(SnapshotVersion.min())\n );\n promises.push(\n this.documentCache.addEntry(transaction, key, deletedDoc)\n );\n }\n }\n });\n\n collectionParents.forEach(parent => {\n promises.push(\n this.documentCache.indexManager.addToCollectionParentIndex(\n transaction,\n parent\n )\n );\n });\n\n promises.push(this.documentCache.updateMetadata(transaction, sizeDelta));\n\n return PersistencePromise.waitFor(promises);\n }\n\n protected getFromCache(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n // Record the size of everything we load from the cache so we can compute a delta later.\n return this.documentCache\n .getSizedEntry(transaction, documentKey)\n .next(getResult => {\n this.documentStates.set(documentKey, {\n size: getResult.size,\n readTime: getResult.document.readTime\n });\n return getResult.document;\n });\n }\n\n protected getAllFromCache(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise {\n // Record the size of everything we load from the cache so we can compute\n // a delta later.\n return this.documentCache\n .getSizedEntries(transaction, documentKeys)\n .next(({ documents, sizeMap }) => {\n // Note: `getAllFromCache` returns two maps instead of a single map from\n // keys to `DocumentSizeEntry`s. This is to allow returning the\n // `MutableDocumentMap` directly, without a conversion.\n sizeMap.forEach((documentKey, size) => {\n this.documentStates.set(documentKey, {\n size,\n readTime: documents.get(documentKey)!.readTime\n });\n });\n return documents;\n });\n }\n}\n\nfunction documentGlobalStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbRemoteDocumentGlobalStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the remoteDocuments object store.\n */\nfunction remoteDocumentsStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbRemoteDocumentStore\n );\n}\n\n/**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentKeyIndex` index.\n */\nfunction dbKey(documentKey: DocumentKey): [string[], string, string] {\n const path = documentKey.path.toArray();\n return [\n /* prefix path */ path.slice(0, path.length - 2),\n /* collection id */ path[path.length - 2],\n /* document id */ path[path.length - 1]\n ];\n}\n\n/**\n * Returns a key that can be used for document lookups via the primary key of\n * the DbRemoteDocument object store.\n */\nfunction dbReadTimeKey(\n documentKey: DocumentKey,\n readTime: SnapshotVersion\n): DbRemoteDocumentKey {\n const path = documentKey.path.toArray();\n return [\n /* prefix path */ path.slice(0, path.length - 2),\n /* collection id */ path[path.length - 2],\n toDbTimestampKey(readTime),\n /* document id */ path[path.length - 1]\n ];\n}\n\n/**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentCollectionGroupIndex` index.\n */\nfunction dbCollectionGroupKey(\n collectionGroup: string,\n offset: IndexOffset\n): [string, DbTimestampKey, string[], string] {\n const path = offset.documentKey.path.toArray();\n return [\n /* collection id */ collectionGroup,\n toDbTimestampKey(offset.readTime),\n /* prefix path */ path.slice(0, path.length - 2),\n /* document id */ path.length > 0 ? path[path.length - 1] : ''\n ];\n}\n\n/**\n * Comparator that compares document keys according to the primary key sorting\n * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id\n * and then document ID).\n *\n * Visible for testing.\n */\nexport function dbKeyComparator(l: DocumentKey, r: DocumentKey): number {\n const left = l.path.toArray();\n const right = r.path.toArray();\n\n // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74\n let cmp = 0;\n for (let i = 0; i < left.length - 2 && i < right.length - 2; ++i) {\n cmp = primitiveComparator(left[i], right[i]);\n if (cmp) {\n return cmp;\n }\n }\n\n cmp = primitiveComparator(left.length, right.length);\n if (cmp) {\n return cmp;\n }\n\n cmp = primitiveComparator(left[left.length - 2], right[right.length - 2]);\n if (cmp) {\n return cmp;\n }\n\n // TODO(b/329441702): Document IDs should be sorted by UTF-8 encoded byte\n // order, but IndexedDB sorts strings lexicographically. Document ID\n // comparison here still relies on primitive comparison to avoid mismatches\n // observed in snapshot listeners with Unicode characters in documentIds\n return primitiveComparator(left[left.length - 1], right[right.length - 1]);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BatchId, ListenSequenceNumber, TargetId } from '../core/types';\nimport { IndexKind } from '../model/field_index';\nimport { BundledQuery } from '../protos/firestore_bundle_proto';\nimport {\n Document as ProtoDocument,\n DocumentsTarget as ProtoDocumentsTarget,\n QueryTarget as ProtoQueryTarget,\n Write as ProtoWrite\n} from '../protos/firestore_proto_api';\n\nimport { EncodedResourcePath } from './encoded_resource_path';\nimport { DbTimestampKey, KeySafeBytes } from './indexeddb_sentinels';\n\n/**\n * Schema Version for the Web client:\n * 1. Initial version including Mutation Queue, Query Cache, and Remote\n * Document Cache\n * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No\n * longer required because migration 3 unconditionally clears it.\n * 3. Dropped and re-created Query Cache to deal with cache corruption related\n * to limbo resolution. Addresses\n * https://github.com/firebase/firebase-ios-sdk/issues/1548\n * 4. Multi-Tab Support.\n * 5. Removal of held write acks.\n * 6. Create document global for tracking document cache size.\n * 7. Ensure every cached document has a sentinel row with a sequence number.\n * 8. Add collection-parent index for Collection Group queries.\n * 9. Change RemoteDocumentChanges store to be keyed by readTime rather than\n * an auto-incrementing ID. This is required for Index-Free queries.\n * 10. Rewrite the canonical IDs to the explicit Protobuf-based format.\n * 11. Add bundles and named_queries for bundle support.\n * 12. Add document overlays.\n * 13. Rewrite the keys of the remote document cache to allow for efficient\n * document lookup via `getAll()`.\n * 14. Add overlays.\n * 15. Add indexing support.\n * 16. Parse timestamp strings before creating index entries.\n * 17. TODO(tomandersen)\n * 18. Encode key safe representations of IndexEntry in DbIndexEntryStore.\n */\n\nexport const SCHEMA_VERSION = 18;\n\n/**\n * Wrapper class to store timestamps (seconds and nanos) in IndexedDb objects.\n */\nexport interface DbTimestamp {\n seconds: number;\n nanoseconds: number;\n}\n\n/**\n * A singleton object to be stored in the 'owner' store in IndexedDb.\n *\n * A given database can have a single primary tab assigned at a given time. That\n * tab must validate that it is still holding the primary lease before every\n * operation that requires locked access. The primary tab should regularly\n * write an updated timestamp to this lease to prevent other tabs from\n * \"stealing\" the primary lease\n */\nexport interface DbPrimaryClient {\n ownerId: string;\n /** Whether to allow shared access from multiple tabs. */\n allowTabSynchronization: boolean;\n leaseTimestampMs: number;\n}\n\n/**\n * An object to be stored in the 'mutationQueues' store in IndexedDb.\n *\n * Each user gets a single queue of MutationBatches to apply to the server.\n * DbMutationQueue tracks the metadata about the queue.\n */\nexport interface DbMutationQueue {\n /**\n * The normalized user ID to which this queue belongs.\n */\n userId: string;\n /**\n * An identifier for the highest numbered batch that has been acknowledged\n * by the server. All MutationBatches in this queue with batchIds less\n * than or equal to this value are considered to have been acknowledged by\n * the server.\n *\n * NOTE: this is deprecated and no longer used by the code.\n */\n lastAcknowledgedBatchId: number;\n /**\n * A stream token that was previously sent by the server.\n *\n * See StreamingWriteRequest in datastore.proto for more details about\n * usage.\n *\n * After sending this token, earlier tokens may not be used anymore so\n * only a single stream token is retained.\n *\n * NOTE: this is deprecated and no longer used by the code.\n */\n lastStreamToken: string;\n}\n\n/**\n * An object to be stored in the 'mutations' store in IndexedDb.\n *\n * Represents a batch of user-level mutations intended to be sent to the server\n * in a single write. Each user-level batch gets a separate DbMutationBatch\n * with a new batchId.\n */\nexport interface DbMutationBatch {\n /**\n * The normalized user ID to which this batch belongs.\n */\n userId: string;\n /**\n * An identifier for this batch, allocated using an auto-generated key.\n */\n batchId: BatchId;\n /**\n * The local write time of the batch, stored as milliseconds since the\n * epoch.\n */\n localWriteTimeMs: number;\n /**\n * A list of \"mutations\" that represent a partial base state from when this\n * write batch was initially created. During local application of the write\n * batch, these baseMutations are applied prior to the real writes in order\n * to override certain document fields from the remote document cache. This\n * is necessary in the case of non-idempotent writes (e.g. `increment()`\n * transforms) to make sure that the local view of the modified documents\n * doesn't flicker if the remote document cache receives the result of the\n * non-idempotent write before the write is removed from the queue.\n *\n * These mutations are never sent to the backend.\n */\n baseMutations?: ProtoWrite[];\n /**\n * A list of mutations to apply. All mutations will be applied atomically.\n *\n * Mutations are serialized via toMutation().\n */\n mutations: ProtoWrite[];\n}\n\n/**\n * An object to be stored in the 'documentMutations' store in IndexedDb.\n *\n * A manually maintained index of all the mutation batches that affect a given\n * document key. The rows in this table are references based on the contents of\n * DbMutationBatch.mutations.\n */\nexport interface DbDocumentMutation {}\n\n/**\n * Represents the known absence of a document at a particular version.\n * Stored in IndexedDb as part of a DbRemoteDocument object.\n */\nexport interface DbNoDocument {\n path: string[];\n readTime: DbTimestamp;\n}\n\n/**\n * Represents a document that is known to exist but whose data is unknown.\n * Stored in IndexedDb as part of a DbRemoteDocument object.\n */\nexport interface DbUnknownDocument {\n path: string[];\n version: DbTimestamp;\n}\n\n/**\n * An object to be stored in the 'remoteDocuments' store in IndexedDb.\n * It represents either:\n *\n * - A complete document.\n * - A \"no document\" representing a document that is known not to exist (at\n * some version).\n * - An \"unknown document\" representing a document that is known to exist (at\n * some version) but whose contents are unknown.\n *\n * The document key is split up across `prefixPath`, `collectionGroup` and\n * `documentId`.\n *\n * Note: This is the persisted equivalent of a MaybeDocument and could perhaps\n * be made more general if necessary.\n */\nexport interface DbRemoteDocument {\n /** The path to the document's collection (excluding). */\n prefixPath: string[];\n\n /** The collection ID the document is directly nested under. */\n collectionGroup: string;\n\n /** The document ID. */\n documentId: string;\n\n /** When the document was read from the backend. */\n readTime: DbTimestampKey;\n\n /**\n * Set to an instance of DbUnknownDocument if the data for a document is\n * not known, but it is known that a document exists at the specified\n * version (e.g. it had a successful update applied to it)\n */\n unknownDocument?: DbUnknownDocument;\n /**\n * Set to an instance of a DbNoDocument if it is known that no document\n * exists.\n */\n noDocument?: DbNoDocument;\n /**\n * Set to an instance of a Document if there's a cached version of the\n * document.\n */\n document?: ProtoDocument;\n /**\n * Documents that were written to the remote document store based on\n * a write acknowledgment are marked with `hasCommittedMutations`. These\n * documents are potentially inconsistent with the backend's copy and use\n * the write's commit version as their document version.\n */\n hasCommittedMutations: boolean;\n}\n\n/**\n * Contains a single entry that has metadata about the remote document cache.\n */\nexport interface DbRemoteDocumentGlobal {\n /**\n * Approximately the total size in bytes of all the\n * documents in the document cache.\n */\n byteSize: number;\n}\n\n/**\n * The persisted type for a query nested with in the 'targets' store in\n * IndexedDb. We use the proto definitions for these two kinds of queries in\n * order to avoid writing extra serialization logic.\n */\nexport type DbQuery = ProtoQueryTarget | ProtoDocumentsTarget;\n\n/**\n * An object to be stored in the 'targets' store in IndexedDb.\n *\n * This is based on and should be kept in sync with the proto used in the iOS\n * client.\n *\n * Each query the client listens to against the server is tracked on disk so\n * that the query can be efficiently resumed on restart.\n */\nexport interface DbTarget {\n /**\n * An auto-generated sequential numeric identifier for the query.\n *\n * Queries are stored using their canonicalId as the key, but these\n * canonicalIds can be quite long so we additionally assign a unique\n * queryId which can be used by referenced data structures (e.g.\n * indexes) to minimize the on-disk cost.\n */\n targetId: TargetId;\n /**\n * The canonical string representing this query. This is not unique.\n */\n canonicalId: string;\n /**\n * The last readTime received from the Watch Service for this query.\n *\n * This is the same value as TargetChange.read_time in the protos.\n */\n readTime: DbTimestamp;\n /**\n * An opaque, server-assigned token that allows watching a query to be\n * resumed after disconnecting without retransmitting all the data\n * that matches the query. The resume token essentially identifies a\n * point in time from which the server should resume sending results.\n *\n * This is related to the snapshotVersion in that the resumeToken\n * effectively also encodes that value, but the resumeToken is opaque\n * and sometimes encodes additional information.\n *\n * A consequence of this is that the resumeToken should be used when\n * asking the server to reason about where this client is in the watch\n * stream, but the client should use the snapshotVersion for its own\n * purposes.\n *\n * This is the same value as TargetChange.resume_token in the protos.\n */\n resumeToken: string;\n /**\n * A sequence number representing the last time this query was\n * listened to, used for garbage collection purposes.\n *\n * Conventionally this would be a timestamp value, but device-local\n * clocks are unreliable and they must be able to create new listens\n * even while disconnected. Instead this should be a monotonically\n * increasing number that's incremented on each listen call.\n *\n * This is different from the queryId since the queryId is an\n * immutable identifier assigned to the Query on first use while\n * lastListenSequenceNumber is updated every time the query is\n * listened to.\n */\n lastListenSequenceNumber: number;\n /**\n * Denotes the maximum snapshot version at which the associated query view\n * contained no limbo documents. Undefined for data written prior to\n * schema version 9.\n */\n lastLimboFreeSnapshotVersion?: DbTimestamp;\n /**\n * The query for this target.\n *\n * Because canonical ids are not unique we must store the actual query. We\n * use the proto to have an object we can persist without having to\n * duplicate translation logic to and from a `Query` object.\n */\n query: DbQuery;\n}\n\n/**\n * An object representing an association between a target and a document, or a\n * sentinel row marking the last sequence number at which a document was used.\n * Each document cached must have a corresponding sentinel row before lru\n * garbage collection is enabled.\n *\n * The target associations and sentinel rows are co-located so that orphaned\n * documents and their sequence numbers can be identified efficiently via a scan\n * of this store.\n */\nexport interface DbTargetDocument {\n /**\n * The targetId identifying a target or 0 for a sentinel row.\n */\n targetId: TargetId;\n /**\n * The path to the document, as encoded in the key.\n */\n path: EncodedResourcePath;\n /**\n * If this is a sentinel row, this should be the sequence number of the last\n * time the document specified by `path` was used. Otherwise, it should be\n * `undefined`.\n */\n sequenceNumber?: ListenSequenceNumber;\n}\n\n/**\n * A record of global state tracked across all Targets, tracked separately\n * to avoid the need for extra indexes.\n *\n * This should be kept in-sync with the proto used in the iOS client.\n */\nexport interface DbTargetGlobal {\n /**\n * The highest numbered target id across all targets.\n *\n * See DbTarget.targetId.\n */\n highestTargetId: TargetId;\n /**\n * The highest numbered lastListenSequenceNumber across all targets.\n *\n * See DbTarget.lastListenSequenceNumber.\n */\n highestListenSequenceNumber: number;\n /**\n * A global snapshot version representing the last consistent snapshot we\n * received from the backend. This is monotonically increasing and any\n * snapshots received from the backend prior to this version (e.g. for\n * targets resumed with a resumeToken) should be suppressed (buffered)\n * until the backend has caught up to this snapshot version again. This\n * prevents our cache from ever going backwards in time.\n */\n lastRemoteSnapshotVersion: DbTimestamp;\n /**\n * The number of targets persisted.\n */\n targetCount: number;\n}\n\n/**\n * An object representing an association between a Collection id (e.g. 'messages')\n * to a parent path (e.g. '/chats/123') that contains it as a (sub)collection.\n * This is used to efficiently find all collections to query when performing\n * a Collection Group query.\n */\nexport interface DbCollectionParent {\n /**\n * The collectionId (e.g. 'messages')\n */\n collectionId: string;\n /**\n * The path to the parent (either a document location or an empty path for\n * a root-level collection).\n */\n parent: EncodedResourcePath;\n}\n\n/**\n * A record of the metadata state of each client.\n *\n * PORTING NOTE: This is used to synchronize multi-tab state and does not need\n * to be ported to iOS or Android.\n */\nexport interface DbClientMetadata {\n // Note: Previous schema versions included a field\n // \"lastProcessedDocumentChangeId\". Don't use anymore.\n\n /** The auto-generated client id assigned at client startup. */\n clientId: string;\n /** The last time this state was updated. */\n updateTimeMs: number;\n /** Whether the client's network connection is enabled. */\n networkEnabled: boolean;\n /** Whether this client is running in a foreground tab. */\n inForeground: boolean;\n}\n\n/** An object representing a bundle loaded by the SDK. */\nexport interface DbBundle {\n /** The ID of the loaded bundle. */\n bundleId: string;\n /** The create time of the loaded bundle. */\n createTime: DbTimestamp;\n /** The schema version of the loaded bundle. */\n version: number;\n}\n\n/** An object representing a named query loaded by the SDK via a bundle. */\nexport interface DbNamedQuery {\n /** The name of the query. */\n name: string;\n /** The read time of the results saved in the bundle from the named query. */\n readTime: DbTimestamp;\n /** The query saved in the bundle. */\n bundledQuery: BundledQuery;\n}\n\n/** An object representing the global configuration for a field index. */\nexport interface DbIndexConfiguration {\n /**\n * The index id for this entry. Undefined for indexes that are not yet\n * persisted.\n */\n indexId?: number;\n /** The collection group this index belongs to. */\n collectionGroup: string;\n /** The fields to index for this index. */\n fields: Array<[name: string, kind: IndexKind]>;\n}\n\n/**\n * An object describing how up-to-date the index backfill is for each user and\n * index.\n */\nexport interface DbIndexState {\n /** The index id for this entry. */\n indexId: number;\n /** The user id for this entry. */\n uid: string;\n /**\n * A number that indicates when the index was last updated (relative to\n * other indexes).\n */\n sequenceNumber: number;\n /**\n * The latest read time that has been indexed by Firestore for this field\n * index. Set to `{seconds: 0, nanos: 0}` if no documents have been indexed.\n */\n readTime: DbTimestamp;\n /**\n * The last document that has been indexed for this field index. Empty if\n * no documents have been indexed.\n */\n documentKey: EncodedResourcePath;\n /**\n * The largest mutation batch id that has been processed for this index. -1\n * if no mutations have been indexed.\n */\n largestBatchId: number;\n}\n\n/** An object that stores the encoded entries for all documents and fields. */\nexport interface DbIndexEntry {\n // TODO(indexing): Consider just storing `orderedDocumentKey` and decoding\n // the ordered key into a document key. This would reduce storage space on\n // disk but require us to port parts of OrderedCodeReader.\n\n /** The index id for this entry. */\n indexId: number;\n /** The user id for this entry. */\n uid: string;\n /** The encoded array index value for this entry. */\n arrayValue: KeySafeBytes;\n /** The encoded directional value for equality and inequality filters. */\n directionalValue: KeySafeBytes;\n /**\n * The document key this entry points to. This entry is encoded by an ordered\n * encoder to match the key order of the index.\n */\n orderedDocumentKey: KeySafeBytes;\n /** The segments of the document key this entry points to. */\n documentKey: string[];\n}\n\n/**\n * An object representing a document overlay.\n */\nexport interface DbDocumentOverlay {\n /** The user ID to whom this overlay belongs. */\n userId: string;\n /** The path to the collection that contains the document. */\n collectionPath: string;\n /** The ID (key) of the document within the collection. */\n documentId: string;\n /** The collection group to which the document belongs. */\n collectionGroup: string;\n /** The largest batch ID that's been applied for this overlay. */\n largestBatchId: number;\n /** The overlay mutation. */\n overlayMutation: ProtoWrite;\n}\n\n/**\n * An object containing global name/value pair.\n */\nexport interface DbGlobals {\n /** Name is a globally unique identifier for a value. */\n name: string;\n /** Value is a general purpose storage for global data. */\n value: Uint8Array;\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 *

+ */ function setLogLevel(e) { + B.setLogLevel(e); +} + +function __PRIVATE_logDebug(e, ...t) { + if (B.logLevel <= a.DEBUG) { + const n = t.map(__PRIVATE_argToString); + B.debug(`Firestore (${N}): ${e}`, ...n); + } +} + +function __PRIVATE_logError(e, ...t) { + if (B.logLevel <= a.ERROR) { + const n = t.map(__PRIVATE_argToString); + B.error(`Firestore (${N}): ${e}`, ...n); + } +} + +/** + * @internal + */ function __PRIVATE_logWarn(e, ...t) { + if (B.logLevel <= a.WARN) { + const n = t.map(__PRIVATE_argToString); + B.warn(`Firestore (${N}): ${e}`, ...n); + } +} + +/** + * Converts an additional log parameter to a string representation. + */ function __PRIVATE_argToString(e) { + if ("string" == typeof e) return e; + try { + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** Formats an object as a JSON string, suitable for logging. */ + return function __PRIVATE_formatJSON(e) { + return JSON.stringify(e); + }(e); + } catch (t) { + // Converting to JSON failed, just log the object directly + return e; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function fail(e, t, n) { + let r = "Unexpected state"; + "string" == typeof t ? r = t : n = t, __PRIVATE__fail(e, r, n); +} + +function __PRIVATE__fail(e, t, n) { + // Log the failure in addition to throw an exception, just in case the + // exception is swallowed. + let r = `FIRESTORE (${N}) INTERNAL ASSERTION FAILED: ${t} (ID: ${e.toString(16)})`; + if (void 0 !== n) try { + r += " CONTEXT: " + JSON.stringify(n); + } catch (e) { + r += " CONTEXT: " + n; + } + // NOTE: We don't use FirestoreError here because these are internal failures + // that cannot be handled by the user. (Also it would create a circular + // dependency between the error and assert modules which doesn't work.) + throw __PRIVATE_logError(r), new Error(r); +} + +function __PRIVATE_hardAssert(e, t, n, r) { + let i = "Unexpected state"; + "string" == typeof n ? i = n : r = n, e || __PRIVATE__fail(t, i, r); +} + +/** + * Fails if the given assertion condition is false, throwing an Error with the + * given message if it did. + * + * The code of callsites invoking this function are stripped out in production + * builds. Any side-effects of code within the debugAssert() invocation will not + * happen in this case. + * + * @internal + */ function __PRIVATE_debugAssert(e, t) { + e || fail(57014, t); +} + +/** + * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an + * instance of `T` before casting. + */ function __PRIVATE_debugCast(e, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +t) { + return e; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const L = { + // Causes are copied from: + // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h + /** Not an error; returned on success. */ + OK: "ok", + /** The operation was cancelled (typically by the caller). */ + CANCELLED: "cancelled", + /** Unknown error or an error from a different error domain. */ + UNKNOWN: "unknown", + /** + * Client specified an invalid argument. Note that this differs from + * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are + * problematic regardless of the state of the system (e.g., a malformed file + * name). + */ + INVALID_ARGUMENT: "invalid-argument", + /** + * Deadline expired before operation could complete. For operations that + * change the state of the system, this error may be returned even if the + * operation has completed successfully. For example, a successful response + * from a server could have been delayed long enough for the deadline to + * expire. + */ + DEADLINE_EXCEEDED: "deadline-exceeded", + /** Some requested entity (e.g., file or directory) was not found. */ + NOT_FOUND: "not-found", + /** + * Some entity that we attempted to create (e.g., file or directory) already + * exists. + */ + ALREADY_EXISTS: "already-exists", + /** + * The caller does not have permission to execute the specified operation. + * PERMISSION_DENIED must not be used for rejections caused by exhausting + * some resource (use RESOURCE_EXHAUSTED instead for those errors). + * PERMISSION_DENIED must not be used if the caller cannot be identified + * (use UNAUTHENTICATED instead for those errors). + */ + PERMISSION_DENIED: "permission-denied", + /** + * The request does not have valid authentication credentials for the + * operation. + */ + UNAUTHENTICATED: "unauthenticated", + /** + * Some resource has been exhausted, perhaps a per-user quota, or perhaps the + * entire file system is out of space. + */ + RESOURCE_EXHAUSTED: "resource-exhausted", + /** + * Operation was rejected because the system is not in a state required for + * the operation's execution. For example, directory to be deleted may be + * non-empty, an rmdir operation is applied to a non-directory, etc. + * + * A litmus test that may help a service implementor in deciding + * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: + * (a) Use UNAVAILABLE if the client can retry just the failing call. + * (b) Use ABORTED if the client should retry at a higher-level + * (e.g., restarting a read-modify-write sequence). + * (c) Use FAILED_PRECONDITION if the client should not retry until + * the system state has been explicitly fixed. E.g., if an "rmdir" + * fails because the directory is non-empty, FAILED_PRECONDITION + * should be returned since the client should not retry unless + * they have first fixed up the directory by deleting files from it. + * (d) Use FAILED_PRECONDITION if the client performs conditional + * REST Get/Update/Delete on a resource and the resource on the + * server does not match the condition. E.g., conflicting + * read-modify-write on the same resource. + */ + FAILED_PRECONDITION: "failed-precondition", + /** + * The operation was aborted, typically due to a concurrency issue like + * sequencer check failures, transaction aborts, etc. + * + * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, + * and UNAVAILABLE. + */ + ABORTED: "aborted", + /** + * Operation was attempted past the valid range. E.g., seeking or reading + * past end of file. + * + * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed + * if the system state changes. For example, a 32-bit file system will + * generate INVALID_ARGUMENT if asked to read at an offset that is not in the + * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from + * an offset past the current file size. + * + * There is a fair bit of overlap between FAILED_PRECONDITION and + * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) + * when it applies so that callers who are iterating through a space can + * easily look for an OUT_OF_RANGE error to detect when they are done. + */ + OUT_OF_RANGE: "out-of-range", + /** Operation is not implemented or not supported/enabled in this service. */ + UNIMPLEMENTED: "unimplemented", + /** + * Internal errors. Means some invariants expected by underlying System has + * been broken. If you see one of these errors, Something is very broken. + */ + INTERNAL: "internal", + /** + * The service is currently unavailable. This is a most likely a transient + * condition and may be corrected by retrying with a backoff. + * + * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, + * and UNAVAILABLE. + */ + UNAVAILABLE: "unavailable", + /** Unrecoverable data loss or corruption. */ + DATA_LOSS: "data-loss" +}; + +/** An error returned by a Firestore operation. */ class FirestoreError extends u { + /** @hideconstructor */ + constructor( + /** + * The backend error code associated with this error. + */ + e, + /** + * A custom error description. + */ + t) { + super(e, t), this.code = e, this.message = t, + // HACK: We write a toString property directly because Error is not a real + // class and so inheritance does not work correctly. We could alternatively + // do the same "back-door inheritance" trick that FirebaseError does. + this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_Deferred { + constructor() { + this.promise = new Promise(((e, t) => { + this.resolve = e, this.reject = t; + })); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_OAuthToken { + constructor(e, t) { + this.user = t, this.type = "OAuth", this.headers = new Map, this.headers.set("Authorization", `Bearer ${e}`); + } +} + +/** + * A CredentialsProvider that always yields an empty token. + * @internal + */ class __PRIVATE_EmptyAuthCredentialsProvider { + getToken() { + return Promise.resolve(null); + } + invalidateToken() {} + start(e, t) { + // Fire with initial user. + e.enqueueRetryable((() => t(User.UNAUTHENTICATED))); + } + shutdown() {} +} + +/** + * A CredentialsProvider that always returns a constant token. Used for + * emulator token mocking. + */ class __PRIVATE_EmulatorAuthCredentialsProvider { + constructor(e) { + this.token = e, + /** + * Stores the listener registered with setChangeListener() + * This isn't actually necessary since the UID never changes, but we use this + * to verify the listen contract is adhered to in tests. + */ + this.changeListener = null; + } + getToken() { + return Promise.resolve(this.token); + } + invalidateToken() {} + start(e, t) { + this.changeListener = t, + // Fire with initial user. + e.enqueueRetryable((() => t(this.token.user))); + } + shutdown() { + this.changeListener = null; + } +} + +class __PRIVATE_FirebaseAuthCredentialsProvider { + constructor(e) { + this.t = e, + /** Tracks the current User. */ + this.currentUser = User.UNAUTHENTICATED, + /** + * Counter used to detect if the token changed while a getToken request was + * outstanding. + */ + this.i = 0, this.forceRefresh = !1, this.auth = null; + } + start(e, t) { + __PRIVATE_hardAssert(void 0 === this.o, 42304); + let n = this.i; + // A change listener that prevents double-firing for the same token change. + const __PRIVATE_guardedChangeListener = e => this.i !== n ? (n = this.i, + t(e)) : Promise.resolve(); + // A promise that can be waited on to block on the next token change. + // This promise is re-created after each change. + let r = new __PRIVATE_Deferred; + this.o = () => { + this.i++, this.currentUser = this.u(), r.resolve(), r = new __PRIVATE_Deferred, + e.enqueueRetryable((() => __PRIVATE_guardedChangeListener(this.currentUser))); + }; + const __PRIVATE_awaitNextToken = () => { + const t = r; + e.enqueueRetryable((async () => { + await t.promise, await __PRIVATE_guardedChangeListener(this.currentUser); + })); + }, __PRIVATE_registerAuth = e => { + __PRIVATE_logDebug("FirebaseAuthCredentialsProvider", "Auth detected"), this.auth = e, + this.o && (this.auth.addAuthTokenListener(this.o), __PRIVATE_awaitNextToken()); + }; + this.t.onInit((e => __PRIVATE_registerAuth(e))), + // Our users can initialize Auth right after Firestore, so we give it + // a chance to register itself with the component framework before we + // determine whether to start up in unauthenticated mode. + setTimeout((() => { + if (!this.auth) { + const e = this.t.getImmediate({ + optional: !0 + }); + e ? __PRIVATE_registerAuth(e) : ( + // If auth is still not available, proceed with `null` user + __PRIVATE_logDebug("FirebaseAuthCredentialsProvider", "Auth not yet detected"), + r.resolve(), r = new __PRIVATE_Deferred); + } + }), 0), __PRIVATE_awaitNextToken(); + } + getToken() { + // Take note of the current value of the tokenCounter so that this method + // can fail (with an ABORTED error) if there is a token change while the + // request is outstanding. + const e = this.i, t = this.forceRefresh; + return this.forceRefresh = !1, this.auth ? this.auth.getToken(t).then((t => + // Cancel the request since the token changed while the request was + // outstanding so the response is potentially for a previous user (which + // user, we can't be sure). + this.i !== e ? (__PRIVATE_logDebug("FirebaseAuthCredentialsProvider", "getToken aborted due to token change."), + this.getToken()) : t ? (__PRIVATE_hardAssert("string" == typeof t.accessToken, 31837, { + l: t + }), new __PRIVATE_OAuthToken(t.accessToken, this.currentUser)) : null)) : Promise.resolve(null); + } + invalidateToken() { + this.forceRefresh = !0; + } + shutdown() { + this.auth && this.o && this.auth.removeAuthTokenListener(this.o), this.o = void 0; + } + // Auth.getUid() can return null even with a user logged in. It is because + // getUid() is synchronous, but the auth code populating Uid is asynchronous. + // This method should only be called in the AuthTokenListener callback + // to guarantee to get the actual user. + u() { + const e = this.auth && this.auth.getUid(); + return __PRIVATE_hardAssert(null === e || "string" == typeof e, 2055, { + h: e + }), new User(e); + } +} + +/* + * FirstPartyToken provides a fresh token each time its value + * is requested, because if the token is too old, requests will be rejected. + * Technically this may no longer be necessary since the SDK should gracefully + * recover from unauthenticated errors (see b/33147818 for context), but it's + * safer to keep the implementation as-is. + */ class __PRIVATE_FirstPartyToken { + constructor(e, t, n) { + this.P = e, this.T = t, this.I = n, this.type = "FirstParty", this.user = User.FIRST_PARTY, + this.A = new Map; + } + /** + * Gets an authorization token, using a provided factory function, or return + * null. + */ R() { + return this.I ? this.I() : null; + } + get headers() { + this.A.set("X-Goog-AuthUser", this.P); + // Use array notation to prevent minification + const e = this.R(); + return e && this.A.set("Authorization", e), this.T && this.A.set("X-Goog-Iam-Authorization-Token", this.T), + this.A; + } +} + +/* + * Provides user credentials required for the Firestore JavaScript SDK + * to authenticate the user, using technique that is only available + * to applications hosted by Google. + */ class __PRIVATE_FirstPartyAuthCredentialsProvider { + constructor(e, t, n) { + this.P = e, this.T = t, this.I = n; + } + getToken() { + return Promise.resolve(new __PRIVATE_FirstPartyToken(this.P, this.T, this.I)); + } + start(e, t) { + // Fire with initial uid. + e.enqueueRetryable((() => t(User.FIRST_PARTY))); + } + shutdown() {} + invalidateToken() {} +} + +class AppCheckToken { + constructor(e) { + this.value = e, this.type = "AppCheck", this.headers = new Map, e && e.length > 0 && this.headers.set("x-firebase-appcheck", this.value); + } +} + +class __PRIVATE_FirebaseAppCheckTokenProvider { + constructor(t, n) { + this.V = n, this.forceRefresh = !1, this.appCheck = null, this.m = null, this.p = null, + e(t) && t.settings.appCheckToken && (this.p = t.settings.appCheckToken); + } + start(e, t) { + __PRIVATE_hardAssert(void 0 === this.o, 3512); + const onTokenChanged = e => { + null != e.error && __PRIVATE_logDebug("FirebaseAppCheckTokenProvider", `Error getting App Check token; using placeholder token instead. Error: ${e.error.message}`); + const n = e.token !== this.m; + return this.m = e.token, __PRIVATE_logDebug("FirebaseAppCheckTokenProvider", `Received ${n ? "new" : "existing"} token.`), + n ? t(e.token) : Promise.resolve(); + }; + this.o = t => { + e.enqueueRetryable((() => onTokenChanged(t))); + }; + const __PRIVATE_registerAppCheck = e => { + __PRIVATE_logDebug("FirebaseAppCheckTokenProvider", "AppCheck detected"), this.appCheck = e, + this.o && this.appCheck.addTokenListener(this.o); + }; + this.V.onInit((e => __PRIVATE_registerAppCheck(e))), + // Our users can initialize AppCheck after Firestore, so we give it + // a chance to register itself with the component framework. + setTimeout((() => { + if (!this.appCheck) { + const e = this.V.getImmediate({ + optional: !0 + }); + e ? __PRIVATE_registerAppCheck(e) : + // If AppCheck is still not available, proceed without it. + __PRIVATE_logDebug("FirebaseAppCheckTokenProvider", "AppCheck not yet detected"); + } + }), 0); + } + getToken() { + if (this.p) return Promise.resolve(new AppCheckToken(this.p)); + const e = this.forceRefresh; + return this.forceRefresh = !1, this.appCheck ? this.appCheck.getToken(e).then((e => e ? (__PRIVATE_hardAssert("string" == typeof e.token, 44558, { + tokenResult: e + }), this.m = e.token, new AppCheckToken(e.token)) : null)) : Promise.resolve(null); + } + invalidateToken() { + this.forceRefresh = !0; + } + shutdown() { + this.appCheck && this.o && this.appCheck.removeTokenListener(this.o), this.o = void 0; + } +} + +/** + * An AppCheck token provider that always yields an empty token. + * @internal + */ class __PRIVATE_EmptyAppCheckTokenProvider { + getToken() { + return Promise.resolve(new AppCheckToken("")); + } + invalidateToken() {} + start(e, t) {} + shutdown() {} +} + +/** + * Builds a CredentialsProvider depending on the type of + * the credentials passed in. + */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Generates `nBytes` of random bytes. + * + * If `nBytes < 0` , an error will be thrown. + */ +function __PRIVATE_randomBytes(e) { + // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available. + const t = + // eslint-disable-next-line @typescript-eslint/no-explicit-any + "undefined" != typeof self && (self.crypto || self.msCrypto), n = new Uint8Array(e); + if (t && "function" == typeof t.getRandomValues) t.getRandomValues(n); else + // Falls back to Math.random + for (let t = 0; t < e; t++) n[t] = Math.floor(256 * Math.random()); + return n; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A utility class for generating unique alphanumeric IDs of a specified length. + * + * @internal + * Exported internally for testing purposes. + */ class __PRIVATE_AutoId { + static newId() { + // Alphanumeric characters + const e = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", t = 62 * Math.floor(256 / 62); + // The largest byte value that is a multiple of `char.length`. + let n = ""; + for (;n.length < 20; ) { + const r = __PRIVATE_randomBytes(40); + for (let i = 0; i < r.length; ++i) + // Only accept values that are [0, maxMultiple), this ensures they can + // be evenly mapped to indices of `chars` via a modulo operation. + n.length < 20 && r[i] < t && (n += e.charAt(r[i] % 62)); + } + return n; + } +} + +function __PRIVATE_primitiveComparator(e, t) { + return e < t ? -1 : e > t ? 1 : 0; +} + +/** Compare strings in UTF-8 encoded byte order */ function __PRIVATE_compareUtf8Strings(e, t) { + // Find the first differing character (a.k.a. "UTF-16 code unit") in the two strings and, + // if found, use that character to determine the relative ordering of the two strings as a + // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by + // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8 + // and UTF-16 happen to represent Unicode code points. + // After finding the first pair of differing characters, there are two cases: + // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or + // both are surrogates from a surrogate pair (that collectively represent code points greater + // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the + // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is + // sufficient. + // Case 2: One character is a surrogate and the other is not. In this case the surrogate- + // containing string is always ordered after the non-surrogate. This is because surrogates are + // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations + // and are lexicographically greater than the 1, 2, or 3-byte representations of code points + // less than or equal to 0xFFFF. + // An example of why Case 2 is required is comparing the following two Unicode code points: + // |-----------------------|------------|---------------------|-----------------| + // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding | + // |-----------------------|------------|---------------------|-----------------| + // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD | + // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 | + // |-----------------------|------------|---------------------|-----------------| + // A lexicographical comparison of the UTF-8 encodings of these code points would order + // "Replacement Character" _before_ "Grinning Face" because 0xEF is less than 0xF0. However, a + // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously + // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out, + // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate + // pair with those that do not. + const n = Math.min(e.length, t.length); + for (let r = 0; r < n; r++) { + const n = e.charAt(r), i = t.charAt(r); + if (n !== i) return __PRIVATE_isSurrogate(n) === __PRIVATE_isSurrogate(i) ? __PRIVATE_primitiveComparator(n, i) : __PRIVATE_isSurrogate(n) ? 1 : -1; + } + // Use the lengths of the strings to determine the overall comparison result since either the + // strings were equal or one is a prefix of the other. + return __PRIVATE_primitiveComparator(e.length, t.length); +} + +const k = 55296, q = 57343; + +function __PRIVATE_isSurrogate(e) { + const t = e.charCodeAt(0); + return t >= k && t <= q; +} + +/** Helper to compare arrays using isEqual(). */ function __PRIVATE_arrayEquals(e, t, n) { + return e.length === t.length && e.every(((e, r) => n(e, t[r]))); +} + +/** + * Returns the immediate lexicographically-following string. This is useful to + * construct an inclusive range for indexeddb iterators. + */ function __PRIVATE_immediateSuccessor(e) { + // Return the input string, with an additional NUL byte appended. + return e + "\0"; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const Q = "__name__"; + +/** + * Path represents an ordered sequence of string segments. + */ class BasePath { + constructor(e, t, n) { + void 0 === t ? t = 0 : t > e.length && fail(637, { + offset: t, + range: e.length + }), void 0 === n ? n = e.length - t : n > e.length - t && fail(1746, { + length: n, + range: e.length - t + }), this.segments = e, this.offset = t, this.len = n; + } + get length() { + return this.len; + } + isEqual(e) { + return 0 === BasePath.comparator(this, e); + } + child(e) { + const t = this.segments.slice(this.offset, this.limit()); + return e instanceof BasePath ? e.forEach((e => { + t.push(e); + })) : t.push(e), this.construct(t); + } + /** The index of one past the last segment of the path. */ limit() { + return this.offset + this.length; + } + popFirst(e) { + return e = void 0 === e ? 1 : e, this.construct(this.segments, this.offset + e, this.length - e); + } + popLast() { + return this.construct(this.segments, this.offset, this.length - 1); + } + firstSegment() { + return this.segments[this.offset]; + } + lastSegment() { + return this.get(this.length - 1); + } + get(e) { + return this.segments[this.offset + e]; + } + isEmpty() { + return 0 === this.length; + } + isPrefixOf(e) { + if (e.length < this.length) return !1; + for (let t = 0; t < this.length; t++) if (this.get(t) !== e.get(t)) return !1; + return !0; + } + isImmediateParentOf(e) { + if (this.length + 1 !== e.length) return !1; + for (let t = 0; t < this.length; t++) if (this.get(t) !== e.get(t)) return !1; + return !0; + } + forEach(e) { + for (let t = this.offset, n = this.limit(); t < n; t++) e(this.segments[t]); + } + toArray() { + return this.segments.slice(this.offset, this.limit()); + } + /** + * Compare 2 paths segment by segment, prioritizing numeric IDs + * (e.g., "__id123__") in numeric ascending order, followed by string + * segments in lexicographical order. + */ static comparator(e, t) { + const n = Math.min(e.length, t.length); + for (let r = 0; r < n; r++) { + const n = BasePath.compareSegments(e.get(r), t.get(r)); + if (0 !== n) return n; + } + return __PRIVATE_primitiveComparator(e.length, t.length); + } + static compareSegments(e, t) { + const n = BasePath.isNumericId(e), r = BasePath.isNumericId(t); + return n && !r ? -1 : !n && r ? 1 : n && r ? BasePath.extractNumericId(e).compare(BasePath.extractNumericId(t)) : __PRIVATE_compareUtf8Strings(e, t); + } + // Checks if a segment is a numeric ID (starts with "__id" and ends with "__"). + static isNumericId(e) { + return e.startsWith("__id") && e.endsWith("__"); + } + static extractNumericId(e) { + return p.fromString(e.substring(4, e.length - 2)); + } +} + +/** + * A slash-separated path for navigating resources (documents and collections) + * within Firestore. + * + * @internal + */ class ResourcePath extends BasePath { + construct(e, t, n) { + return new ResourcePath(e, t, n); + } + canonicalString() { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + return this.toArray().join("/"); + } + toString() { + return this.canonicalString(); + } + /** + * Returns a string representation of this path + * where each path segment has been encoded with + * `encodeURIComponent`. + */ toUriEncodedString() { + return this.toArray().map(encodeURIComponent).join("/"); + } + /** + * Creates a resource path from the given slash-delimited string. If multiple + * arguments are provided, all components are combined. Leading and trailing + * slashes from all components are ignored. + */ static fromString(...e) { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + const t = []; + for (const n of e) { + if (n.indexOf("//") >= 0) throw new FirestoreError(L.INVALID_ARGUMENT, `Invalid segment (${n}). Paths must not contain // in them.`); + // Strip leading and trailing slashed. + t.push(...n.split("/").filter((e => e.length > 0))); + } + return new ResourcePath(t); + } + static emptyPath() { + return new ResourcePath([]); + } +} + +const $ = /^[_a-zA-Z][_a-zA-Z0-9]*$/; + +/** + * A dot-separated path for navigating sub-objects within a document. + * @internal + */ class FieldPath$1 extends BasePath { + construct(e, t, n) { + return new FieldPath$1(e, t, n); + } + /** + * Returns true if the string could be used as a segment in a field path + * without escaping. + */ static isValidIdentifier(e) { + return $.test(e); + } + canonicalString() { + return this.toArray().map((e => (e = e.replace(/\\/g, "\\\\").replace(/`/g, "\\`"), + FieldPath$1.isValidIdentifier(e) || (e = "`" + e + "`"), e))).join("."); + } + toString() { + return this.canonicalString(); + } + /** + * Returns true if this field references the key of a document. + */ isKeyField() { + return 1 === this.length && this.get(0) === Q; + } + /** + * The field designating the key of a document. + */ static keyField() { + return new FieldPath$1([ Q ]); + } + /** + * Parses a field string from the given server-formatted string. + * + * - Splitting the empty string is not allowed (for now at least). + * - Empty segments within the string (e.g. if there are two consecutive + * separators) are not allowed. + * + * TODO(b/37244157): we should make this more strict. Right now, it allows + * non-identifier path components, even if they aren't escaped. + */ static fromServerFormat(e) { + const t = []; + let n = "", r = 0; + const __PRIVATE_addCurrentSegment = () => { + if (0 === n.length) throw new FirestoreError(L.INVALID_ARGUMENT, `Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`); + t.push(n), n = ""; + }; + let i = !1; + for (;r < e.length; ) { + const t = e[r]; + if ("\\" === t) { + if (r + 1 === e.length) throw new FirestoreError(L.INVALID_ARGUMENT, "Path has trailing escape character: " + e); + const t = e[r + 1]; + if ("\\" !== t && "." !== t && "`" !== t) throw new FirestoreError(L.INVALID_ARGUMENT, "Path has invalid escape sequence: " + e); + n += t, r += 2; + } else "`" === t ? (i = !i, r++) : "." !== t || i ? (n += t, r++) : (__PRIVATE_addCurrentSegment(), + r++); + } + if (__PRIVATE_addCurrentSegment(), i) throw new FirestoreError(L.INVALID_ARGUMENT, "Unterminated ` in path: " + e); + return new FieldPath$1(t); + } + static emptyPath() { + return new FieldPath$1([]); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @internal + */ class DocumentKey { + constructor(e) { + this.path = e; + } + static fromPath(e) { + return new DocumentKey(ResourcePath.fromString(e)); + } + static fromName(e) { + return new DocumentKey(ResourcePath.fromString(e).popFirst(5)); + } + static empty() { + return new DocumentKey(ResourcePath.emptyPath()); + } + get collectionGroup() { + return this.path.popLast().lastSegment(); + } + /** Returns true if the document is in the specified collectionId. */ hasCollectionId(e) { + return this.path.length >= 2 && this.path.get(this.path.length - 2) === e; + } + /** Returns the collection group (i.e. the name of the parent collection) for this key. */ getCollectionGroup() { + return this.path.get(this.path.length - 2); + } + /** Returns the fully qualified path to the parent collection. */ getCollectionPath() { + return this.path.popLast(); + } + isEqual(e) { + return null !== e && 0 === ResourcePath.comparator(this.path, e.path); + } + toString() { + return this.path.toString(); + } + static comparator(e, t) { + return ResourcePath.comparator(e.path, t.path); + } + static isDocumentKey(e) { + return e.length % 2 == 0; + } + /** + * Creates and returns a new document key with the given segments. + * + * @param segments - The segments of the path to the document + * @returns A new instance of DocumentKey + */ static fromSegments(e) { + return new DocumentKey(new ResourcePath(e.slice())); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_validateNonEmptyArgument(e, t, n) { + if (!n) throw new FirestoreError(L.INVALID_ARGUMENT, `Function ${e}() cannot be called with an empty ${t}.`); +} + +/** + * Validates that two boolean options are not set at the same time. + * @internal + */ function __PRIVATE_validateIsNotUsedTogether(e, t, n, r) { + if (!0 === t && !0 === r) throw new FirestoreError(L.INVALID_ARGUMENT, `${e} and ${n} cannot be used together.`); +} + +/** + * Validates that `path` refers to a document (indicated by the fact it contains + * an even numbers of segments). + */ function __PRIVATE_validateDocumentPath(e) { + if (!DocumentKey.isDocumentKey(e)) throw new FirestoreError(L.INVALID_ARGUMENT, `Invalid document reference. Document references must have an even number of segments, but ${e} has ${e.length}.`); +} + +/** + * Validates that `path` refers to a collection (indicated by the fact it + * contains an odd numbers of segments). + */ function __PRIVATE_validateCollectionPath(e) { + if (DocumentKey.isDocumentKey(e)) throw new FirestoreError(L.INVALID_ARGUMENT, `Invalid collection reference. Collection references must have an odd number of segments, but ${e} has ${e.length}.`); +} + +/** + * Returns true if it's a non-null object without a custom prototype + * (i.e. excludes Array, Date, etc.). + */ function __PRIVATE_isPlainObject(e) { + return "object" == typeof e && null !== e && (Object.getPrototypeOf(e) === Object.prototype || null === Object.getPrototypeOf(e)); +} + +/** Returns a string describing the type / value of the provided input. */ function __PRIVATE_valueDescription(e) { + if (void 0 === e) return "undefined"; + if (null === e) return "null"; + if ("string" == typeof e) return e.length > 20 && (e = `${e.substring(0, 20)}...`), + JSON.stringify(e); + if ("number" == typeof e || "boolean" == typeof e) return "" + e; + if ("object" == typeof e) { + if (e instanceof Array) return "an array"; + { + const t = + /** try to get the constructor name for an object. */ + function __PRIVATE_tryGetCustomObjectType(e) { + if (e.constructor) return e.constructor.name; + return null; + } + /** + * Casts `obj` to `T`, optionally unwrapping Compat types to expose the + * underlying instance. Throws if `obj` is not an instance of `T`. + * + * This cast is used in the Lite and Full SDK to verify instance types for + * arguments passed to the public API. + * @internal + */ (e); + return t ? `a custom ${t} object` : "an object"; + } + } + return "function" == typeof e ? "a function" : fail(12329, { + type: typeof e + }); +} + +function __PRIVATE_cast(e, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +t) { + if ("_delegate" in e && ( + // Unwrap Compat types + // eslint-disable-next-line @typescript-eslint/no-explicit-any + e = e._delegate), !(e instanceof t)) { + if (t.name === e.constructor.name) throw new FirestoreError(L.INVALID_ARGUMENT, "Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?"); + { + const n = __PRIVATE_valueDescription(e); + throw new FirestoreError(L.INVALID_ARGUMENT, `Expected type '${t.name}', but it was: ${n}`); + } + } + return e; +} + +function __PRIVATE_validatePositiveNumber(e, t) { + if (t <= 0) throw new FirestoreError(L.INVALID_ARGUMENT, `Function ${e}() requires a positive number, but it was: ${t}.`); +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Helper function to define a JSON schema {@link Property}. + * @private + * @internal + */ function property(e, t) { + const n = { + typeString: e + }; + return t && (n.value = t), n; +} + +/** + * Validates the JSON object based on the provided schema, and narrows the type to the provided + * JSON schema. + * @private + * @internal + * + * @param json A JSON object to validate. + * @param scheme a {@link JsonSchema} that defines the properties to validate. + * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise. + */ function __PRIVATE_validateJSON(e, t) { + if (!__PRIVATE_isPlainObject(e)) throw new FirestoreError(L.INVALID_ARGUMENT, "JSON must be an object"); + let n; + for (const r in t) if (t[r]) { + const i = t[r].typeString, s = "value" in t[r] ? { + value: t[r].value + } : void 0; + if (!(r in e)) { + n = `JSON missing required field: '${r}'`; + break; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const o = e[r]; + if (i && typeof o !== i) { + n = `JSON field '${r}' must be a ${i}.`; + break; + } + if (void 0 !== s && o !== s.value) { + n = `Expected '${r}' field to equal '${s.value}'`; + break; + } + } + if (n) throw new FirestoreError(L.INVALID_ARGUMENT, n); + return !0; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z). +const U = -62135596800, K = 1e6; + +// Number of nanoseconds in a millisecond. +/** + * A `Timestamp` represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. + * + * It is encoded using the Proleptic Gregorian Calendar which extends the + * Gregorian calendar backwards to year one. It is encoded assuming all minutes + * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59.999999999Z. + * + * For examples and further specifications, refer to the + * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. + */ +class Timestamp { + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns a new timestamp representing the current date. + */ + static now() { + return Timestamp.fromMillis(Date.now()); + } + /** + * Creates a new timestamp from the given date. + * + * @param date - The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the given + * date. + */ static fromDate(e) { + return Timestamp.fromMillis(e.getTime()); + } + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds - Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the given + * number of milliseconds. + */ static fromMillis(e) { + const t = Math.floor(e / 1e3), n = Math.floor((e - 1e3 * t) * K); + return new Timestamp(t, n); + } + /** + * Creates a new timestamp. + * + * @param seconds - The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds - The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + e, + /** + * The fractions of a second at nanosecond resolution.* + */ + t) { + if (this.seconds = e, this.nanoseconds = t, t < 0) throw new FirestoreError(L.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + t); + if (t >= 1e9) throw new FirestoreError(L.INVALID_ARGUMENT, "Timestamp nanoseconds out of range: " + t); + if (e < U) throw new FirestoreError(L.INVALID_ARGUMENT, "Timestamp seconds out of range: " + e); + // This will break in the year 10,000. + if (e >= 253402300800) throw new FirestoreError(L.INVALID_ARGUMENT, "Timestamp seconds out of range: " + e); + } + /** + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ toDate() { + return new Date(this.toMillis()); + } + /** + * Converts a `Timestamp` to a numeric timestamp (in milliseconds since + * epoch). This operation causes a loss of precision. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ toMillis() { + return 1e3 * this.seconds + this.nanoseconds / K; + } + _compareTo(e) { + return this.seconds === e.seconds ? __PRIVATE_primitiveComparator(this.nanoseconds, e.nanoseconds) : __PRIVATE_primitiveComparator(this.seconds, e.seconds); + } + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other - The `Timestamp` to compare against. + * @returns true if this `Timestamp` is equal to the provided one. + */ isEqual(e) { + return e.seconds === this.seconds && e.nanoseconds === this.nanoseconds; + } + /** Returns a textual representation of this `Timestamp`. */ toString() { + return "Timestamp(seconds=" + this.seconds + ", nanoseconds=" + this.nanoseconds + ")"; + } + /** + * Returns a JSON-serializable representation of this `Timestamp`. + */ toJSON() { + return { + type: Timestamp._jsonSchemaVersion, + seconds: this.seconds, + nanoseconds: this.nanoseconds + }; + } + /** + * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}. + */ static fromJSON(e) { + if (__PRIVATE_validateJSON(e, Timestamp._jsonSchema)) return new Timestamp(e.seconds, e.nanoseconds); + } + /** + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. + */ valueOf() { + // This method returns a string of the form . where + // is translated to have a non-negative value and both + // and are left-padded with zeroes to be a consistent length. + // Strings with this format then have a lexicographical ordering that matches + // the expected ordering. The translation is done to avoid having + // a leading negative sign (i.e. a leading '-' character) in its string + // representation, which would affect its lexicographical ordering. + const e = this.seconds - U; + // Note: Up to 12 decimal digits are required to represent all valid + // 'seconds' values. + return String(e).padStart(12, "0") + "." + String(this.nanoseconds).padStart(9, "0"); + } +} + +Timestamp._jsonSchemaVersion = "firestore/timestamp/1.0", Timestamp._jsonSchema = { + type: property("string", Timestamp._jsonSchemaVersion), + seconds: property("number"), + nanoseconds: property("number") +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A version of a document in Firestore. This corresponds to the version + * timestamp, such as update_time or read_time. + */ +class SnapshotVersion { + static fromTimestamp(e) { + return new SnapshotVersion(e); + } + static min() { + return new SnapshotVersion(new Timestamp(0, 0)); + } + static max() { + return new SnapshotVersion(new Timestamp(253402300799, 999999999)); + } + constructor(e) { + this.timestamp = e; + } + compareTo(e) { + return this.timestamp._compareTo(e.timestamp); + } + isEqual(e) { + return this.timestamp.isEqual(e.timestamp); + } + /** Returns a number representation of the version for use in spec tests. */ toMicroseconds() { + // Convert to microseconds. + return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3; + } + toString() { + return "SnapshotVersion(" + this.timestamp.toString() + ")"; + } + toTimestamp() { + return this.timestamp; + } +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The initial mutation batch id for each index. Gets updated during index + * backfill. + */ const W = -1; + +/** + * The initial sequence number for each index. Gets updated during index + * backfill. + */ +/** + * An index definition for field indexes in Firestore. + * + * Every index is associated with a collection. The definition contains a list + * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or + * `CONTAINS` for ArrayContains/ArrayContainsAny queries). + * + * Unlike the backend, the SDK does not differentiate between collection or + * collection group-scoped indices. Every index can be used for both single + * collection and collection group queries. + */ +class FieldIndex { + constructor( + /** + * The index ID. Returns -1 if the index ID is not available (e.g. the index + * has not yet been persisted). + */ + e, + /** The collection ID this index applies to. */ + t, + /** The field segments for this index. */ + n, + /** Shows how up-to-date the index is for the current user. */ + r) { + this.indexId = e, this.collectionGroup = t, this.fields = n, this.indexState = r; + } +} + +/** An ID for an index that has not yet been added to persistence. */ +/** Returns the ArrayContains/ArrayContainsAny segment for this index. */ +function __PRIVATE_fieldIndexGetArraySegment(e) { + return e.fields.find((e => 2 /* IndexKind.CONTAINS */ === e.kind)); +} + +/** Returns all directional (ascending/descending) segments for this index. */ function __PRIVATE_fieldIndexGetDirectionalSegments(e) { + return e.fields.filter((e => 2 /* IndexKind.CONTAINS */ !== e.kind)); +} + +/** + * Returns the order of the document key component for the given index. + * + * PORTING NOTE: This is only used in the Web IndexedDb implementation. + */ +/** + * Compares indexes by collection group and segments. Ignores update time and + * index ID. + */ +function __PRIVATE_fieldIndexSemanticComparator(e, t) { + let n = __PRIVATE_primitiveComparator(e.collectionGroup, t.collectionGroup); + if (0 !== n) return n; + for (let r = 0; r < Math.min(e.fields.length, t.fields.length); ++r) if (n = __PRIVATE_indexSegmentComparator(e.fields[r], t.fields[r]), + 0 !== n) return n; + return __PRIVATE_primitiveComparator(e.fields.length, t.fields.length); +} + +/** Returns a debug representation of the field index */ FieldIndex.UNKNOWN_ID = -1; + +/** An index component consisting of field path and index type. */ +class IndexSegment { + constructor( + /** The field path of the component. */ + e, + /** The fields sorting order. */ + t) { + this.fieldPath = e, this.kind = t; + } +} + +function __PRIVATE_indexSegmentComparator(e, t) { + const n = FieldPath$1.comparator(e.fieldPath, t.fieldPath); + return 0 !== n ? n : __PRIVATE_primitiveComparator(e.kind, t.kind); +} + +/** + * Stores the "high water mark" that indicates how updated the Index is for the + * current user. + */ class IndexState { + constructor( + /** + * Indicates when the index was last updated (relative to other indexes). + */ + e, + /** The the latest indexed read time, document and batch id. */ + t) { + this.sequenceNumber = e, this.offset = t; + } + /** The state of an index that has not yet been backfilled. */ static empty() { + return new IndexState(0, IndexOffset.min()); + } +} + +/** + * Creates an offset that matches all documents with a read time higher than + * `readTime`. + */ function __PRIVATE_newIndexOffsetSuccessorFromReadTime(e, t) { + // We want to create an offset that matches all documents with a read time + // greater than the provided read time. To do so, we technically need to + // create an offset for `(readTime, MAX_DOCUMENT_KEY)`. While we could use + // Unicode codepoints to generate MAX_DOCUMENT_KEY, it is much easier to use + // `(readTime + 1, DocumentKey.empty())` since `> DocumentKey.empty()` matches + // all valid document IDs. + const n = e.toTimestamp().seconds, r = e.toTimestamp().nanoseconds + 1, i = SnapshotVersion.fromTimestamp(1e9 === r ? new Timestamp(n + 1, 0) : new Timestamp(n, r)); + return new IndexOffset(i, DocumentKey.empty(), t); +} + +/** Creates a new offset based on the provided document. */ function __PRIVATE_newIndexOffsetFromDocument(e) { + return new IndexOffset(e.readTime, e.key, W); +} + +/** + * Stores the latest read time, document and batch ID that were processed for an + * index. + */ class IndexOffset { + constructor( + /** + * The latest read time version that has been indexed by Firestore for this + * field index. + */ + e, + /** + * The key of the last document that was indexed for this query. Use + * `DocumentKey.empty()` if no document has been indexed. + */ + t, + /* + * The largest mutation batch id that's been processed by Firestore. + */ + n) { + this.readTime = e, this.documentKey = t, this.largestBatchId = n; + } + /** Returns an offset that sorts before all regular offsets. */ static min() { + return new IndexOffset(SnapshotVersion.min(), DocumentKey.empty(), W); + } + /** Returns an offset that sorts after all regular offsets. */ static max() { + return new IndexOffset(SnapshotVersion.max(), DocumentKey.empty(), W); + } +} + +function __PRIVATE_indexOffsetComparator(e, t) { + let n = e.readTime.compareTo(t.readTime); + return 0 !== n ? n : (n = DocumentKey.comparator(e.documentKey, t.documentKey), + 0 !== n ? n : __PRIVATE_primitiveComparator(e.largestBatchId, t.largestBatchId)); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const G = "The current tab is not in the required state to perform this operation. It might be necessary to refresh the browser tab."; + +/** + * A base class representing a persistence transaction, encapsulating both the + * transaction's sequence numbers as well as a list of onCommitted listeners. + * + * When you call Persistence.runTransaction(), it will create a transaction and + * pass it to your callback. You then pass it to any method that operates + * on persistence. + */ class PersistenceTransaction { + constructor() { + this.onCommittedListeners = []; + } + addOnCommittedListener(e) { + this.onCommittedListeners.push(e); + } + raiseOnCommittedEvent() { + this.onCommittedListeners.forEach((e => e())); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Verifies the error thrown by a LocalStore operation. If a LocalStore + * operation fails because the primary lease has been taken by another client, + * we ignore the error (the persistence layer will immediately call + * `applyPrimaryLease` to propagate the primary state change). All other errors + * are re-thrown. + * + * @param err - An error returned by a LocalStore operation. + * @returns A Promise that resolves after we recovered, or the original error. + */ async function __PRIVATE_ignoreIfPrimaryLeaseLoss(e) { + if (e.code !== L.FAILED_PRECONDITION || e.message !== G) throw e; + __PRIVATE_logDebug("LocalStore", "Unexpectedly lost primary lease"); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * PersistencePromise is essentially a re-implementation of Promise except + * it has a .next() method instead of .then() and .next() and .catch() callbacks + * are executed synchronously when a PersistencePromise resolves rather than + * asynchronously (Promise implementations use setImmediate() or similar). + * + * This is necessary to interoperate with IndexedDB which will automatically + * commit transactions if control is returned to the event loop without + * synchronously initiating another operation on the transaction. + * + * NOTE: .then() and .catch() only allow a single consumer, unlike normal + * Promises. + */ class PersistencePromise { + constructor(e) { + // NOTE: next/catchCallback will always point to our own wrapper functions, + // not the user's raw next() or catch() callbacks. + this.nextCallback = null, this.catchCallback = null, + // When the operation resolves, we'll set result or error and mark isDone. + this.result = void 0, this.error = void 0, this.isDone = !1, + // Set to true when .then() or .catch() are called and prevents additional + // chaining. + this.callbackAttached = !1, e((e => { + this.isDone = !0, this.result = e, this.nextCallback && + // value should be defined unless T is Void, but we can't express + // that in the type system. + this.nextCallback(e); + }), (e => { + this.isDone = !0, this.error = e, this.catchCallback && this.catchCallback(e); + })); + } + catch(e) { + return this.next(void 0, e); + } + next(e, t) { + return this.callbackAttached && fail(59440), this.callbackAttached = !0, this.isDone ? this.error ? this.wrapFailure(t, this.error) : this.wrapSuccess(e, this.result) : new PersistencePromise(((n, r) => { + this.nextCallback = t => { + this.wrapSuccess(e, t).next(n, r); + }, this.catchCallback = e => { + this.wrapFailure(t, e).next(n, r); + }; + })); + } + toPromise() { + return new Promise(((e, t) => { + this.next(e, t); + })); + } + wrapUserFunction(e) { + try { + const t = e(); + return t instanceof PersistencePromise ? t : PersistencePromise.resolve(t); + } catch (e) { + return PersistencePromise.reject(e); + } + } + wrapSuccess(e, t) { + return e ? this.wrapUserFunction((() => e(t))) : PersistencePromise.resolve(t); + } + wrapFailure(e, t) { + return e ? this.wrapUserFunction((() => e(t))) : PersistencePromise.reject(t); + } + static resolve(e) { + return new PersistencePromise(((t, n) => { + t(e); + })); + } + static reject(e) { + return new PersistencePromise(((t, n) => { + n(e); + })); + } + static waitFor( + // Accept all Promise types in waitFor(). + // eslint-disable-next-line @typescript-eslint/no-explicit-any + e) { + return new PersistencePromise(((t, n) => { + let r = 0, i = 0, s = !1; + e.forEach((e => { + ++r, e.next((() => { + ++i, s && i === r && t(); + }), (e => n(e))); + })), s = !0, i === r && t(); + })); + } + /** + * Given an array of predicate functions that asynchronously evaluate to a + * boolean, implements a short-circuiting `or` between the results. Predicates + * will be evaluated until one of them returns `true`, then stop. The final + * result will be whether any of them returned `true`. + */ static or(e) { + let t = PersistencePromise.resolve(!1); + for (const n of e) t = t.next((e => e ? PersistencePromise.resolve(e) : n())); + return t; + } + static forEach(e, t) { + const n = []; + return e.forEach(((e, r) => { + n.push(t.call(this, e, r)); + })), this.waitFor(n); + } + /** + * Concurrently map all array elements through asynchronous function. + */ static mapArray(e, t) { + return new PersistencePromise(((n, r) => { + const i = e.length, s = new Array(i); + let o = 0; + for (let _ = 0; _ < i; _++) { + const a = _; + t(e[a]).next((e => { + s[a] = e, ++o, o === i && n(s); + }), (e => r(e))); + } + })); + } + /** + * An alternative to recursive PersistencePromise calls, that avoids + * potential memory problems from unbounded chains of promises. + * + * The `action` will be called repeatedly while `condition` is true. + */ static doWhile(e, t) { + return new PersistencePromise(((n, r) => { + const process = () => { + !0 === e() ? t().next((() => { + process(); + }), r) : n(); + }; + process(); + })); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// References to `indexedDB` are guarded by SimpleDb.isAvailable() and getGlobal() +/* eslint-disable no-restricted-globals */ const z = "SimpleDb"; + +/** + * The maximum number of retry attempts for an IndexedDb transaction that fails + * with a DOMException. + */ +/** + * Wraps an IDBTransaction and exposes a store() method to get a handle to a + * specific object store. + */ +class __PRIVATE_SimpleDbTransaction { + static open(e, t, n, r) { + try { + return new __PRIVATE_SimpleDbTransaction(t, e.transaction(r, n)); + } catch (e) { + throw new __PRIVATE_IndexedDbTransactionError(t, e); + } + } + constructor(e, t) { + this.action = e, this.transaction = t, this.aborted = !1, + /** + * A `Promise` that resolves with the result of the IndexedDb transaction. + */ + this.S = new __PRIVATE_Deferred, this.transaction.oncomplete = () => { + this.S.resolve(); + }, this.transaction.onabort = () => { + t.error ? this.S.reject(new __PRIVATE_IndexedDbTransactionError(e, t.error)) : this.S.resolve(); + }, this.transaction.onerror = t => { + const n = __PRIVATE_checkForAndReportiOSError(t.target.error); + this.S.reject(new __PRIVATE_IndexedDbTransactionError(e, n)); + }; + } + get D() { + return this.S.promise; + } + abort(e) { + e && this.S.reject(e), this.aborted || (__PRIVATE_logDebug(z, "Aborting transaction:", e ? e.message : "Client-initiated abort"), + this.aborted = !0, this.transaction.abort()); + } + C() { + // If the browser supports V3 IndexedDB, we invoke commit() explicitly to + // speed up index DB processing if the event loop remains blocks. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const e = this.transaction; + this.aborted || "function" != typeof e.commit || e.commit(); + } + /** + * Returns a SimpleDbStore for the specified store. All + * operations performed on the SimpleDbStore happen within the context of this + * transaction and it cannot be used anymore once the transaction is + * completed. + * + * Note that we can't actually enforce that the KeyType and ValueType are + * correct, but they allow type safety through the rest of the consuming code. + */ store(e) { + const t = this.transaction.objectStore(e); + return new __PRIVATE_SimpleDbStore(t); + } +} + +/** + * Provides a wrapper around IndexedDb with a simplified interface that uses + * Promise-like return values to chain operations. Real promises cannot be used + * since .then() continuations are executed asynchronously (e.g. via + * .setImmediate), which would cause IndexedDB to end the transaction. + * See PersistencePromise for more details. + */ class __PRIVATE_SimpleDb { + /** Deletes the specified database. */ + static delete(e) { + __PRIVATE_logDebug(z, "Removing database:", e); + return __PRIVATE_wrapRequest(c().indexedDB.deleteDatabase(e)).toPromise(); + } + /** Returns true if IndexedDB is available in the current environment. */ static v() { + if (!l()) return !1; + if (__PRIVATE_SimpleDb.F()) return !0; + // We extensively use indexed array values and compound keys, + // which IE and Edge do not support. However, they still have indexedDB + // defined on the window, so we need to check for them here and make sure + // to return that persistence is not enabled for those browsers. + // For tracking support of this feature, see here: + // https://developer.microsoft.com/en-us/microsoft-edge/platform/status/indexeddbarraysandmultientrysupport/ + // Check the UA string to find out the browser. + const e = h(), t = __PRIVATE_SimpleDb.M(e), n = 0 < t && t < 10, r = __PRIVATE_getAndroidVersion(e), i = 0 < r && r < 4.5; + // IE 10 + // ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)'; + // IE 11 + // ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko'; + // Edge + // ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, + // like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0'; + // iOS Safari: Disable for users running iOS version < 10. + return !(e.indexOf("MSIE ") > 0 || e.indexOf("Trident/") > 0 || e.indexOf("Edge/") > 0 || n || i); + } + /** + * Returns true if the backing IndexedDB store is the Node IndexedDBShim + * (see https://github.com/axemclion/IndexedDBShim). + */ static F() { + return "undefined" != typeof process && "YES" === process.__PRIVATE_env?.__PRIVATE_USE_MOCK_PERSISTENCE; + } + /** Helper to get a typed SimpleDbStore from a transaction. */ static O(e, t) { + return e.store(t); + } + // visible for testing + /** Parse User Agent to determine iOS version. Returns -1 if not found. */ + static M(e) { + const t = e.match(/i(?:phone|pad|pod) os ([\d_]+)/i), n = t ? t[1].split("_").slice(0, 2).join(".") : "-1"; + return Number(n); + } + /* + * Creates a new SimpleDb wrapper for IndexedDb database `name`. + * + * Note that `version` must not be a downgrade. IndexedDB does not support + * downgrading the schema version. We currently do not support any way to do + * versioning outside of IndexedDB's versioning mechanism, as only + * version-upgrade transactions are allowed to do things like create + * objectstores. + */ constructor(e, t, n) { + this.name = e, this.version = t, this.N = n, this.B = null; + // NOTE: According to https://bugs.webkit.org/show_bug.cgi?id=197050, the + // bug we're checking for should exist in iOS >= 12.2 and < 13, but for + // whatever reason it's much harder to hit after 12.2 so we only proactively + // log on 12.2. + 12.2 === __PRIVATE_SimpleDb.M(h()) && __PRIVATE_logError("Firestore persistence suffers from a bug in iOS 12.2 Safari that may cause your app to stop working. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround."); + } + /** + * Opens the specified database, creating or upgrading it if necessary. + */ async L(e) { + return this.db || (__PRIVATE_logDebug(z, "Opening database:", this.name), this.db = await new Promise(((t, n) => { + // TODO(mikelehen): Investigate browser compatibility. + // https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB + // suggests IE9 and older WebKit browsers handle upgrade + // differently. They expect setVersion, as described here: + // https://developer.mozilla.org/en-US/docs/Web/API/IDBVersionChangeRequest/setVersion + const r = indexedDB.open(this.name, this.version); + r.onsuccess = e => { + const n = e.target.result; + t(n); + }, r.onblocked = () => { + n(new __PRIVATE_IndexedDbTransactionError(e, "Cannot upgrade IndexedDB schema while another tab is open. Close all tabs that access Firestore and reload this page to proceed.")); + }, r.onerror = t => { + const r = t.target.error; + "VersionError" === r.name ? n(new FirestoreError(L.FAILED_PRECONDITION, "A newer version of the Firestore SDK was previously used and so the persisted data is not compatible with the version of the SDK you are now using. The SDK will operate with persistence disabled. If you need persistence, please re-upgrade to a newer version of the SDK or else clear the persisted IndexedDB data for your app to start fresh.")) : "InvalidStateError" === r.name ? n(new FirestoreError(L.FAILED_PRECONDITION, "Unable to open an IndexedDB connection. This could be due to running in a private browsing session on a browser whose private browsing sessions do not support IndexedDB: " + r)) : n(new __PRIVATE_IndexedDbTransactionError(e, r)); + }, r.onupgradeneeded = e => { + __PRIVATE_logDebug(z, 'Database "' + this.name + '" requires upgrade from version:', e.oldVersion); + const t = e.target.result; + this.N.k(t, r.transaction, e.oldVersion, this.version).next((() => { + __PRIVATE_logDebug(z, "Database upgrade to version " + this.version + " complete"); + })); + }; + }))), this.q && (this.db.onversionchange = e => this.q(e)), this.db; + } + $(e) { + this.q = e, this.db && (this.db.onversionchange = t => e(t)); + } + async runTransaction(e, t, n, r) { + const i = "readonly" === t; + let s = 0; + for (;;) { + ++s; + try { + this.db = await this.L(e); + const t = __PRIVATE_SimpleDbTransaction.open(this.db, e, i ? "readonly" : "readwrite", n), s = r(t).next((e => (t.C(), + e))).catch((e => ( + // Abort the transaction if there was an error. + t.abort(e), PersistencePromise.reject(e)))).toPromise(); + // As noted above, errors are propagated by aborting the transaction. So + // we swallow any error here to avoid the browser logging it as unhandled. + return s.catch((() => {})), + // Wait for the transaction to complete (i.e. IndexedDb's onsuccess event to + // fire), but still return the original transactionFnResult back to the + // caller. + await t.D, s; + } catch (e) { + const t = e, n = "FirebaseError" !== t.name && s < 3; + // TODO(schmidt-sebastian): We could probably be smarter about this and + // not retry exceptions that are likely unrecoverable (such as quota + // exceeded errors). + // Note: We cannot use an instanceof check for FirestoreException, since the + // exception is wrapped in a generic error by our async/await handling. + if (__PRIVATE_logDebug(z, "Transaction failed with error:", t.message, "Retrying:", n), + this.close(), !n) return Promise.reject(t); + } + } + } + close() { + this.db && this.db.close(), this.db = void 0; + } +} + +/** Parse User Agent to determine Android version. Returns -1 if not found. */ function __PRIVATE_getAndroidVersion(e) { + const t = e.match(/Android ([\d.]+)/i), n = t ? t[1].split(".").slice(0, 2).join(".") : "-1"; + return Number(n); +} + +/** + * A controller for iterating over a key range or index. It allows an iterate + * callback to delete the currently-referenced object, or jump to a new key + * within the key range or index. + */ class __PRIVATE_IterationController { + constructor(e) { + this.U = e, this.K = !1, this.W = null; + } + get isDone() { + return this.K; + } + get G() { + return this.W; + } + set cursor(e) { + this.U = e; + } + /** + * This function can be called to stop iteration at any point. + */ done() { + this.K = !0; + } + /** + * This function can be called to skip to that next key, which could be + * an index or a primary key. + */ j(e) { + this.W = e; + } + /** + * Delete the current cursor value from the object store. + * + * NOTE: You CANNOT do this with a keysOnly query. + */ delete() { + return __PRIVATE_wrapRequest(this.U.delete()); + } +} + +/** An error that wraps exceptions that thrown during IndexedDB execution. */ class __PRIVATE_IndexedDbTransactionError extends FirestoreError { + constructor(e, t) { + super(L.UNAVAILABLE, `IndexedDB transaction '${e}' failed: ${t}`), this.name = "IndexedDbTransactionError"; + } +} + +/** Verifies whether `e` is an IndexedDbTransactionError. */ function __PRIVATE_isIndexedDbTransactionError(e) { + // Use name equality, as instanceof checks on errors don't work with errors + // that wrap other errors. + return "IndexedDbTransactionError" === e.name; +} + +/** + * A wrapper around an IDBObjectStore providing an API that: + * + * 1) Has generic KeyType / ValueType parameters to provide strongly-typed + * methods for acting against the object store. + * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every + * method return a PersistencePromise instead. + * 3) Provides a higher-level API to avoid needing to do excessive wrapping of + * intermediate IndexedDB types (IDBCursorWithValue, etc.) + */ class __PRIVATE_SimpleDbStore { + constructor(e) { + this.store = e; + } + put(e, t) { + let n; + return void 0 !== t ? (__PRIVATE_logDebug(z, "PUT", this.store.name, e, t), n = this.store.put(t, e)) : (__PRIVATE_logDebug(z, "PUT", this.store.name, "", e), + n = this.store.put(e)), __PRIVATE_wrapRequest(n); + } + /** + * Adds a new value into an Object Store and returns the new key. Similar to + * IndexedDb's `add()`, this method will fail on primary key collisions. + * + * @param value - The object to write. + * @returns The key of the value to add. + */ add(e) { + __PRIVATE_logDebug(z, "ADD", this.store.name, e, e); + return __PRIVATE_wrapRequest(this.store.add(e)); + } + /** + * Gets the object with the specified key from the specified store, or null + * if no object exists with the specified key. + * + * @key The key of the object to get. + * @returns The object with the specified key or null if no object exists. + */ get(e) { + // We're doing an unsafe cast to ValueType. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return __PRIVATE_wrapRequest(this.store.get(e)).next((t => ( + // Normalize nonexistence to null. + void 0 === t && (t = null), __PRIVATE_logDebug(z, "GET", this.store.name, e, t), + t))); + } + delete(e) { + __PRIVATE_logDebug(z, "DELETE", this.store.name, e); + return __PRIVATE_wrapRequest(this.store.delete(e)); + } + /** + * If we ever need more of the count variants, we can add overloads. For now, + * all we need is to count everything in a store. + * + * Returns the number of rows in the store. + */ count() { + __PRIVATE_logDebug(z, "COUNT", this.store.name); + return __PRIVATE_wrapRequest(this.store.count()); + } + J(e, t) { + const n = this.options(e, t), r = n.index ? this.store.index(n.index) : this.store; + // Use `getAll()` if the browser supports IndexedDB v3, as it is roughly + // 20% faster. + if ("function" == typeof r.getAll) { + const e = r.getAll(n.range); + return new PersistencePromise(((t, n) => { + e.onerror = e => { + n(e.target.error); + }, e.onsuccess = e => { + t(e.target.result); + }; + })); + } + { + const e = this.cursor(n), t = []; + return this.H(e, ((e, n) => { + t.push(n); + })).next((() => t)); + } + } + /** + * Loads the first `count` elements from the provided index range. Loads all + * elements if no limit is provided. + */ Y(e, t) { + const n = this.store.getAll(e, null === t ? void 0 : t); + return new PersistencePromise(((e, t) => { + n.onerror = e => { + t(e.target.error); + }, n.onsuccess = t => { + e(t.target.result); + }; + })); + } + Z(e, t) { + __PRIVATE_logDebug(z, "DELETE ALL", this.store.name); + const n = this.options(e, t); + n.X = !1; + const r = this.cursor(n); + return this.H(r, ((e, t, n) => n.delete())); + } + ee(e, t) { + let n; + t ? n = e : (n = {}, t = e); + const r = this.cursor(n); + return this.H(r, t); + } + /** + * Iterates over a store, but waits for the given callback to complete for + * each entry before iterating the next entry. This allows the callback to do + * asynchronous work to determine if this iteration should continue. + * + * The provided callback should return `true` to continue iteration, and + * `false` otherwise. + */ te(e) { + const t = this.cursor({}); + return new PersistencePromise(((n, r) => { + t.onerror = e => { + const t = __PRIVATE_checkForAndReportiOSError(e.target.error); + r(t); + }, t.onsuccess = t => { + const r = t.target.result; + r ? e(r.primaryKey, r.value).next((e => { + e ? r.continue() : n(); + })) : n(); + }; + })); + } + H(e, t) { + const n = []; + return new PersistencePromise(((r, i) => { + e.onerror = e => { + i(e.target.error); + }, e.onsuccess = e => { + const i = e.target.result; + if (!i) return void r(); + const s = new __PRIVATE_IterationController(i), o = t(i.primaryKey, i.value, s); + if (o instanceof PersistencePromise) { + const e = o.catch((e => (s.done(), PersistencePromise.reject(e)))); + n.push(e); + } + s.isDone ? r() : null === s.G ? i.continue() : i.continue(s.G); + }; + })).next((() => PersistencePromise.waitFor(n))); + } + options(e, t) { + let n; + return void 0 !== e && ("string" == typeof e ? n = e : t = e), { + index: n, + range: t + }; + } + cursor(e) { + let t = "next"; + if (e.reverse && (t = "prev"), e.index) { + const n = this.store.index(e.index); + return e.X ? n.openKeyCursor(e.range, t) : n.openCursor(e.range, t); + } + return this.store.openCursor(e.range, t); + } +} + +/** + * Wraps an IDBRequest in a PersistencePromise, using the onsuccess / onerror + * handlers to resolve / reject the PersistencePromise as appropriate. + */ function __PRIVATE_wrapRequest(e) { + return new PersistencePromise(((t, n) => { + e.onsuccess = e => { + const n = e.target.result; + t(n); + }, e.onerror = e => { + const t = __PRIVATE_checkForAndReportiOSError(e.target.error); + n(t); + }; + })); +} + +// Guard so we only report the error once. +let j = !1; + +function __PRIVATE_checkForAndReportiOSError(e) { + const t = __PRIVATE_SimpleDb.M(h()); + if (t >= 12.2 && t < 13) { + const t = "An internal error was encountered in the Indexed Database server"; + if (e.message.indexOf(t) >= 0) { + // Wrap error in a more descriptive one. + const e = new FirestoreError("internal", `IOS_INDEXEDDB_BUG1: IndexedDb has thrown '${t}'. This is likely due to an unavoidable bug in iOS. See https://stackoverflow.com/q/56496296/110915 for details and a potential workaround.`); + return j || (j = !0, + // Throw a global exception outside of this promise chain, for the user to + // potentially catch. + setTimeout((() => { + throw e; + }), 0)), e; + } + } + return e; +} + +const J = "IndexBackfiller"; + +/** How long we wait to try running index backfill after SDK initialization. */ +/** This class is responsible for the scheduling of Index Backfiller. */ +class __PRIVATE_IndexBackfillerScheduler { + constructor(e, t) { + this.asyncQueue = e, this.ne = t, this.task = null; + } + start() { + this.re(15e3); + } + stop() { + this.task && (this.task.cancel(), this.task = null); + } + get started() { + return null !== this.task; + } + re(e) { + __PRIVATE_logDebug(J, `Scheduled in ${e}ms`), this.task = this.asyncQueue.enqueueAfterDelay("index_backfill" /* TimerId.IndexBackfill */ , e, (async () => { + this.task = null; + try { + const e = await this.ne.ie(); + __PRIVATE_logDebug(J, `Documents written: ${e}`); + } catch (e) { + __PRIVATE_isIndexedDbTransactionError(e) ? __PRIVATE_logDebug(J, "Ignoring IndexedDB error during index backfill: ", e) : await __PRIVATE_ignoreIfPrimaryLeaseLoss(e); + } + await this.re(6e4); + })); + } +} + +/** Implements the steps for backfilling indexes. */ class __PRIVATE_IndexBackfiller { + constructor( + /** + * LocalStore provides access to IndexManager and LocalDocumentView. + * These properties will update when the user changes. Consequently, + * making a local copy of IndexManager and LocalDocumentView will require + * updates over time. The simpler solution is to rely on LocalStore to have + * an up-to-date references to IndexManager and LocalDocumentStore. + */ + e, t) { + this.localStore = e, this.persistence = t; + } + async ie(e = 50) { + return this.persistence.runTransaction("Backfill Indexes", "readwrite-primary", (t => this.se(t, e))); + } + /** Writes index entries until the cap is reached. Returns the number of documents processed. */ se(e, t) { + const n = new Set; + let r = t, i = !0; + return PersistencePromise.doWhile((() => !0 === i && r > 0), (() => this.localStore.indexManager.getNextCollectionGroupToUpdate(e).next((t => { + if (null !== t && !n.has(t)) return __PRIVATE_logDebug(J, `Processing collection: ${t}`), + this.oe(e, t, r).next((e => { + r -= e, n.add(t); + })); + i = !1; + })))).next((() => t - r)); + } + /** + * Writes entries for the provided collection group. Returns the number of documents processed. + */ oe(e, t, n) { + // Use the earliest offset of all field indexes to query the local cache. + return this.localStore.indexManager.getMinOffsetFromCollectionGroup(e, t).next((r => this.localStore.localDocuments.getNextDocuments(e, t, r, n).next((n => { + const i = n.changes; + return this.localStore.indexManager.updateIndexEntries(e, i).next((() => this._e(r, n))).next((n => (__PRIVATE_logDebug(J, `Updating offset: ${n}`), + this.localStore.indexManager.updateCollectionGroup(e, t, n)))).next((() => i.size)); + })))); + } + /** Returns the next offset based on the provided documents. */ _e(e, t) { + let n = e; + return t.changes.forEach(((e, t) => { + const r = __PRIVATE_newIndexOffsetFromDocument(t); + __PRIVATE_indexOffsetComparator(r, n) > 0 && (n = r); + })), new IndexOffset(n.readTime, n.documentKey, Math.max(t.batchId, e.largestBatchId)); + } +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to + * exceed. All subsequent calls to next will return increasing values. If provided with a + * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as + * well as write out sequence numbers that it produces via `next()`. + */ class __PRIVATE_ListenSequence { + constructor(e, t) { + this.previousValue = e, t && (t.sequenceNumberHandler = e => this.ae(e), this.ue = e => t.writeSequenceNumber(e)); + } + ae(e) { + return this.previousValue = Math.max(e, this.previousValue), this.previousValue; + } + next() { + const e = ++this.previousValue; + return this.ue && this.ue(e), e; + } +} + +__PRIVATE_ListenSequence.ce = -1; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Sentinel value that sorts before any Mutation Batch ID. */ +const H = -1; + +/** + * Returns whether a variable is either undefined or null. + */ function __PRIVATE_isNullOrUndefined(e) { + return null == e; +} + +/** Returns whether the value represents -0. */ function __PRIVATE_isNegativeZero(e) { + // Detect if the value is -0.0. Based on polyfill from + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is + return 0 === e && 1 / e == -1 / 0; +} + +/** + * Returns whether a value is an integer and in the safe integer range + * @param value - The value to test for being an integer and in the safe range + */ function isSafeInteger(e) { + return "number" == typeof e && Number.isInteger(e) && !__PRIVATE_isNegativeZero(e) && e <= Number.MAX_SAFE_INTEGER && e >= Number.MIN_SAFE_INTEGER; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const Y = ""; + +/** + * Encodes a resource path into a IndexedDb-compatible string form. + */ +function __PRIVATE_encodeResourcePath(e) { + let t = ""; + for (let n = 0; n < e.length; n++) t.length > 0 && (t = __PRIVATE_encodeSeparator(t)), + t = __PRIVATE_encodeSegment(e.get(n), t); + return __PRIVATE_encodeSeparator(t); +} + +/** Encodes a single segment of a resource path into the given result */ function __PRIVATE_encodeSegment(e, t) { + let n = t; + const r = e.length; + for (let t = 0; t < r; t++) { + const r = e.charAt(t); + switch (r) { + case "\0": + n += ""; + break; + + case Y: + n += ""; + break; + + default: + n += r; + } + } + return n; +} + +/** Encodes a path separator into the given result */ function __PRIVATE_encodeSeparator(e) { + return e + Y + ""; +} + +/** + * Decodes the given IndexedDb-compatible string form of a resource path into + * a ResourcePath instance. Note that this method is not suitable for use with + * decoding resource names from the server; those are One Platform format + * strings. + */ function __PRIVATE_decodeResourcePath(e) { + // Event the empty path must encode as a path of at least length 2. A path + // with exactly 2 must be the empty path. + const t = e.length; + if (__PRIVATE_hardAssert(t >= 2, 64408, { + path: e + }), 2 === t) return __PRIVATE_hardAssert(e.charAt(0) === Y && "" === e.charAt(1), 56145, { + path: e + }), ResourcePath.emptyPath(); + // Escape characters cannot exist past the second-to-last position in the + // source value. + const __PRIVATE_lastReasonableEscapeIndex = t - 2, n = []; + let r = ""; + for (let i = 0; i < t; ) { + // The last two characters of a valid encoded path must be a separator, so + // there must be an end to this segment. + const t = e.indexOf(Y, i); + (t < 0 || t > __PRIVATE_lastReasonableEscapeIndex) && fail(50515, { + path: e + }); + switch (e.charAt(t + 1)) { + case "": + const s = e.substring(i, t); + let o; + 0 === r.length ? + // Avoid copying for the common case of a segment that excludes \0 + // and \001 + o = s : (r += s, o = r, r = ""), n.push(o); + break; + + case "": + r += e.substring(i, t), r += "\0"; + break; + + case "": + // The escape character can be used in the output to encode itself. + r += e.substring(i, t + 1); + break; + + default: + fail(61167, { + path: e + }); + } + i = t + 2; + } + return new ResourcePath(n); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const Z = "remoteDocuments", X = "owner", ee = "owner", te = "mutationQueues", ne = "userId", re = "mutations", ie = "batchId", se = "userMutationsIndex", oe = [ "userId", "batchId" ]; + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Name of the IndexedDb object store. + * + * Note that the name 'owner' is chosen to ensure backwards compatibility with + * older clients that only supported single locked access to the persistence + * layer. + */ +/** + * Creates a [userId, encodedPath] key for use in the DbDocumentMutations + * index to iterate over all at document mutations for a given path or lower. + */ +function __PRIVATE_newDbDocumentMutationPrefixForPath(e, t) { + return [ e, __PRIVATE_encodeResourcePath(t) ]; +} + +/** + * Creates a full index key of [userId, encodedPath, batchId] for inserting + * and deleting into the DbDocumentMutations index. + */ function __PRIVATE_newDbDocumentMutationKey(e, t, n) { + return [ e, __PRIVATE_encodeResourcePath(t), n ]; +} + +/** + * Because we store all the useful information for this store in the key, + * there is no useful information to store as the value. The raw (unencoded) + * path cannot be stored because IndexedDb doesn't store prototype + * information. + */ const _e = {}, ae = "documentMutations", ue = "remoteDocumentsV14", ce = [ "prefixPath", "collectionGroup", "readTime", "documentId" ], le = "documentKeyIndex", he = [ "prefixPath", "collectionGroup", "documentId" ], Pe = "collectionGroupIndex", Te = [ "collectionGroup", "readTime", "prefixPath", "documentId" ], Ie = "remoteDocumentGlobal", Ee = "remoteDocumentGlobalKey", de = "targets", Ae = "queryTargetsIndex", Re = [ "canonicalId", "targetId" ], Ve = "targetDocuments", me = [ "targetId", "path" ], fe = "documentTargetsIndex", ge = [ "path", "targetId" ], pe = "targetGlobalKey", ye = "targetGlobal", we = "collectionParents", Se = [ "collectionId", "parent" ], be = "clientMetadata", De = "clientId", Ce = "bundles", ve = "bundleId", Fe = "namedQueries", Me = "name", xe = "indexConfiguration", Oe = "indexId", Ne = "collectionGroupIndex", Be = "collectionGroup", Le = "indexState", ke = [ "indexId", "uid" ], qe = "sequenceNumberIndex", Qe = [ "uid", "sequenceNumber" ], $e = "indexEntries", Ue = [ "indexId", "uid", "arrayValue", "directionalValue", "orderedDocumentKey", "documentKey" ], Ke = "documentKeyIndex", We = [ "indexId", "uid", "orderedDocumentKey" ], Ge = "documentOverlays", ze = [ "userId", "collectionPath", "documentId" ], je = "collectionPathOverlayIndex", Je = [ "userId", "collectionPath", "largestBatchId" ], He = "collectionGroupOverlayIndex", Ye = [ "userId", "collectionGroup", "largestBatchId" ], Ze = "globals", Xe = "name", et = [ ...[ ...[ ...[ ...[ te, re, ae, Z, de, X, ye, Ve ], be ], Ie ], we ], Ce, Fe ], tt = [ ...et, Ge ], nt = [ te, re, ae, ue, de, X, ye, Ve, be, Ie, we, Ce, Fe, Ge ], rt = nt, it = [ ...rt, xe, Le, $e ], st = it, ot = [ ...it, Ze ], _t = ot; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class __PRIVATE_IndexedDbTransaction extends PersistenceTransaction { + constructor(e, t) { + super(), this.le = e, this.currentSequenceNumber = t; + } +} + +function __PRIVATE_getStore(e, t) { + const n = __PRIVATE_debugCast(e); + return __PRIVATE_SimpleDb.O(n.le, t); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_objectSize(e) { + let t = 0; + for (const n in e) Object.prototype.hasOwnProperty.call(e, n) && t++; + return t; +} + +function forEach(e, t) { + for (const n in e) Object.prototype.hasOwnProperty.call(e, n) && t(n, e[n]); +} + +function __PRIVATE_mapToArray(e, t) { + const n = []; + for (const r in e) Object.prototype.hasOwnProperty.call(e, r) && n.push(t(e[r], r, e)); + return n; +} + +function isEmpty(e) { + for (const t in e) if (Object.prototype.hasOwnProperty.call(e, t)) return !1; + return !0; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// An immutable sorted map implementation, based on a Left-leaning Red-Black +// tree. +class SortedMap { + constructor(e, t) { + this.comparator = e, this.root = t || LLRBNode.EMPTY; + } + // Returns a copy of the map, with the specified key/value added or replaced. + insert(e, t) { + return new SortedMap(this.comparator, this.root.insert(e, t, this.comparator).copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns a copy of the map, with the specified key removed. + remove(e) { + return new SortedMap(this.comparator, this.root.remove(e, this.comparator).copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns the value of the node with the given key, or null. + get(e) { + let t = this.root; + for (;!t.isEmpty(); ) { + const n = this.comparator(e, t.key); + if (0 === n) return t.value; + n < 0 ? t = t.left : n > 0 && (t = t.right); + } + return null; + } + // Returns the index of the element in this sorted map, or -1 if it doesn't + // exist. + indexOf(e) { + // Number of nodes that were pruned when descending right + let t = 0, n = this.root; + for (;!n.isEmpty(); ) { + const r = this.comparator(e, n.key); + if (0 === r) return t + n.left.size; + r < 0 ? n = n.left : ( + // Count all nodes left of the node plus the node itself + t += n.left.size + 1, n = n.right); + } + // Node not found + return -1; + } + isEmpty() { + return this.root.isEmpty(); + } + // Returns the total number of nodes in the map. + get size() { + return this.root.size; + } + // Returns the minimum key in the map. + minKey() { + return this.root.minKey(); + } + // Returns the maximum key in the map. + maxKey() { + return this.root.maxKey(); + } + // Traverses the map in key order and calls the specified action function + // for each key/value pair. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(e) { + return this.root.inorderTraversal(e); + } + forEach(e) { + this.inorderTraversal(((t, n) => (e(t, n), !1))); + } + toString() { + const e = []; + return this.inorderTraversal(((t, n) => (e.push(`${t}:${n}`), !1))), `{${e.join(", ")}}`; + } + // Traverses the map in reverse key order and calls the specified action + // function for each key/value pair. If action returns true, traversal is + // aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(e) { + return this.root.reverseTraversal(e); + } + // Returns an iterator over the SortedMap. + getIterator() { + return new SortedMapIterator(this.root, null, this.comparator, !1); + } + getIteratorFrom(e) { + return new SortedMapIterator(this.root, e, this.comparator, !1); + } + getReverseIterator() { + return new SortedMapIterator(this.root, null, this.comparator, !0); + } + getReverseIteratorFrom(e) { + return new SortedMapIterator(this.root, e, this.comparator, !0); + } +} + + // end SortedMap +// An iterator over an LLRBNode. +class SortedMapIterator { + constructor(e, t, n, r) { + this.isReverse = r, this.nodeStack = []; + let i = 1; + for (;!e.isEmpty(); ) if (i = t ? n(e.key, t) : 1, + // flip the comparison if we're going in reverse + t && r && (i *= -1), i < 0) + // This node is less than our start key. ignore it + e = this.isReverse ? e.left : e.right; else { + if (0 === i) { + // This node is exactly equal to our start key. Push it on the stack, + // but stop iterating; + this.nodeStack.push(e); + break; + } + // This node is greater than our start key, add it to the stack and move + // to the next one + this.nodeStack.push(e), e = this.isReverse ? e.right : e.left; + } + } + getNext() { + let e = this.nodeStack.pop(); + const t = { + key: e.key, + value: e.value + }; + if (this.isReverse) for (e = e.left; !e.isEmpty(); ) this.nodeStack.push(e), e = e.right; else for (e = e.right; !e.isEmpty(); ) this.nodeStack.push(e), + e = e.left; + return t; + } + hasNext() { + return this.nodeStack.length > 0; + } + peek() { + if (0 === this.nodeStack.length) return null; + const e = this.nodeStack[this.nodeStack.length - 1]; + return { + key: e.key, + value: e.value + }; + } +} + + // end SortedMapIterator +// Represents a node in a Left-leaning Red-Black tree. +class LLRBNode { + constructor(e, t, n, r, i) { + this.key = e, this.value = t, this.color = null != n ? n : LLRBNode.RED, this.left = null != r ? r : LLRBNode.EMPTY, + this.right = null != i ? i : LLRBNode.EMPTY, this.size = this.left.size + 1 + this.right.size; + } + // Returns a copy of the current node, optionally replacing pieces of it. + copy(e, t, n, r, i) { + return new LLRBNode(null != e ? e : this.key, null != t ? t : this.value, null != n ? n : this.color, null != r ? r : this.left, null != i ? i : this.right); + } + isEmpty() { + return !1; + } + // Traverses the tree in key order and calls the specified action function + // for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(e) { + return this.left.inorderTraversal(e) || e(this.key, this.value) || this.right.inorderTraversal(e); + } + // Traverses the tree in reverse key order and calls the specified action + // function for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(e) { + return this.right.reverseTraversal(e) || e(this.key, this.value) || this.left.reverseTraversal(e); + } + // Returns the minimum node in the tree. + min() { + return this.left.isEmpty() ? this : this.left.min(); + } + // Returns the maximum key in the tree. + minKey() { + return this.min().key; + } + // Returns the maximum key in the tree. + maxKey() { + return this.right.isEmpty() ? this.key : this.right.maxKey(); + } + // Returns new tree, with the key/value added. + insert(e, t, n) { + let r = this; + const i = n(e, r.key); + return r = i < 0 ? r.copy(null, null, null, r.left.insert(e, t, n), null) : 0 === i ? r.copy(null, t, null, null, null) : r.copy(null, null, null, null, r.right.insert(e, t, n)), + r.fixUp(); + } + removeMin() { + if (this.left.isEmpty()) return LLRBNode.EMPTY; + let e = this; + return e.left.isRed() || e.left.left.isRed() || (e = e.moveRedLeft()), e = e.copy(null, null, null, e.left.removeMin(), null), + e.fixUp(); + } + // Returns new tree, with the specified item removed. + remove(e, t) { + let n, r = this; + if (t(e, r.key) < 0) r.left.isEmpty() || r.left.isRed() || r.left.left.isRed() || (r = r.moveRedLeft()), + r = r.copy(null, null, null, r.left.remove(e, t), null); else { + if (r.left.isRed() && (r = r.rotateRight()), r.right.isEmpty() || r.right.isRed() || r.right.left.isRed() || (r = r.moveRedRight()), + 0 === t(e, r.key)) { + if (r.right.isEmpty()) return LLRBNode.EMPTY; + n = r.right.min(), r = r.copy(n.key, n.value, null, null, r.right.removeMin()); + } + r = r.copy(null, null, null, null, r.right.remove(e, t)); + } + return r.fixUp(); + } + isRed() { + return this.color; + } + // Returns new tree after performing any needed rotations. + fixUp() { + let e = this; + return e.right.isRed() && !e.left.isRed() && (e = e.rotateLeft()), e.left.isRed() && e.left.left.isRed() && (e = e.rotateRight()), + e.left.isRed() && e.right.isRed() && (e = e.colorFlip()), e; + } + moveRedLeft() { + let e = this.colorFlip(); + return e.right.left.isRed() && (e = e.copy(null, null, null, null, e.right.rotateRight()), + e = e.rotateLeft(), e = e.colorFlip()), e; + } + moveRedRight() { + let e = this.colorFlip(); + return e.left.left.isRed() && (e = e.rotateRight(), e = e.colorFlip()), e; + } + rotateLeft() { + const e = this.copy(null, null, LLRBNode.RED, null, this.right.left); + return this.right.copy(null, null, this.color, e, null); + } + rotateRight() { + const e = this.copy(null, null, LLRBNode.RED, this.left.right, null); + return this.left.copy(null, null, this.color, null, e); + } + colorFlip() { + const e = this.left.copy(null, null, !this.left.color, null, null), t = this.right.copy(null, null, !this.right.color, null, null); + return this.copy(null, null, !this.color, e, t); + } + // For testing. + checkMaxDepth() { + const e = this.check(); + return Math.pow(2, e) <= this.size + 1; + } + // In a balanced RB tree, the black-depth (number of black nodes) from root to + // leaves is equal on both sides. This function verifies that or asserts. + check() { + if (this.isRed() && this.left.isRed()) throw fail(43730, { + key: this.key, + value: this.value + }); + if (this.right.isRed()) throw fail(14113, { + key: this.key, + value: this.value + }); + const e = this.left.check(); + if (e !== this.right.check()) throw fail(27949); + return e + (this.isRed() ? 0 : 1); + } +} + + // end LLRBNode +// Empty node is shared between all LLRB trees. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +LLRBNode.EMPTY = null, LLRBNode.RED = !0, LLRBNode.BLACK = !1; + +// end LLRBEmptyNode +LLRBNode.EMPTY = new +// Represents an empty node (a leaf node in the Red-Black Tree). +class LLRBEmptyNode { + constructor() { + this.size = 0; + } + get key() { + throw fail(57766); + } + get value() { + throw fail(16141); + } + get color() { + throw fail(16727); + } + get left() { + throw fail(29726); + } + get right() { + throw fail(36894); + } + // Returns a copy of the current node. + copy(e, t, n, r, i) { + return this; + } + // Returns a copy of the tree, with the specified key/value added. + insert(e, t, n) { + return new LLRBNode(e, t); + } + // Returns a copy of the tree, with the specified key removed. + remove(e, t) { + return this; + } + isEmpty() { + return !0; + } + inorderTraversal(e) { + return !1; + } + reverseTraversal(e) { + return !1; + } + minKey() { + return null; + } + maxKey() { + return null; + } + isRed() { + return !1; + } + // For testing. + checkMaxDepth() { + return !0; + } + check() { + return 0; + } +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * SortedSet is an immutable (copy-on-write) collection that holds elements + * in order specified by the provided comparator. + * + * NOTE: if provided comparator returns 0 for two elements, we consider them to + * be equal! + */ +class SortedSet { + constructor(e) { + this.comparator = e, this.data = new SortedMap(this.comparator); + } + has(e) { + return null !== this.data.get(e); + } + first() { + return this.data.minKey(); + } + last() { + return this.data.maxKey(); + } + get size() { + return this.data.size; + } + indexOf(e) { + return this.data.indexOf(e); + } + /** Iterates elements in order defined by "comparator" */ forEach(e) { + this.data.inorderTraversal(((t, n) => (e(t), !1))); + } + /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ forEachInRange(e, t) { + const n = this.data.getIteratorFrom(e[0]); + for (;n.hasNext(); ) { + const r = n.getNext(); + if (this.comparator(r.key, e[1]) >= 0) return; + t(r.key); + } + } + /** + * Iterates over `elem`s such that: start <= elem until false is returned. + */ forEachWhile(e, t) { + let n; + for (n = void 0 !== t ? this.data.getIteratorFrom(t) : this.data.getIterator(); n.hasNext(); ) { + if (!e(n.getNext().key)) return; + } + } + /** Finds the least element greater than or equal to `elem`. */ firstAfterOrEqual(e) { + const t = this.data.getIteratorFrom(e); + return t.hasNext() ? t.getNext().key : null; + } + getIterator() { + return new SortedSetIterator(this.data.getIterator()); + } + getIteratorFrom(e) { + return new SortedSetIterator(this.data.getIteratorFrom(e)); + } + /** Inserts or updates an element */ add(e) { + return this.copy(this.data.remove(e).insert(e, !0)); + } + /** Deletes an element */ delete(e) { + return this.has(e) ? this.copy(this.data.remove(e)) : this; + } + isEmpty() { + return this.data.isEmpty(); + } + unionWith(e) { + let t = this; + // Make sure `result` always refers to the larger one of the two sets. + return t.size < e.size && (t = e, e = this), e.forEach((e => { + t = t.add(e); + })), t; + } + isEqual(e) { + if (!(e instanceof SortedSet)) return !1; + if (this.size !== e.size) return !1; + const t = this.data.getIterator(), n = e.data.getIterator(); + for (;t.hasNext(); ) { + const e = t.getNext().key, r = n.getNext().key; + if (0 !== this.comparator(e, r)) return !1; + } + return !0; + } + toArray() { + const e = []; + return this.forEach((t => { + e.push(t); + })), e; + } + toString() { + const e = []; + return this.forEach((t => e.push(t))), "SortedSet(" + e.toString() + ")"; + } + copy(e) { + const t = new SortedSet(this.comparator); + return t.data = e, t; + } +} + +class SortedSetIterator { + constructor(e) { + this.iter = e; + } + getNext() { + return this.iter.getNext().key; + } + hasNext() { + return this.iter.hasNext(); + } +} + +/** + * Compares two sorted sets for equality using their natural ordering. The + * method computes the intersection and invokes `onAdd` for every element that + * is in `after` but not `before`. `onRemove` is invoked for every element in + * `before` but missing from `after`. + * + * The method creates a copy of both `before` and `after` and runs in O(n log + * n), where n is the size of the two lists. + * + * @param before - The elements that exist in the original set. + * @param after - The elements to diff against the original set. + * @param comparator - The comparator for the elements in before and after. + * @param onAdd - A function to invoke for every element that is part of ` + * after` but not `before`. + * @param onRemove - A function to invoke for every element that is part of + * `before` but not `after`. + */ +/** + * Returns the next element from the iterator or `undefined` if none available. + */ +function __PRIVATE_advanceIterator(e) { + return e.hasNext() ? e.getNext() : void 0; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provides a set of fields that can be used to partially patch a document. + * FieldMask is used in conjunction with ObjectValue. + * Examples: + * foo - Overwrites foo entirely with the provided value. If foo is not + * present in the companion ObjectValue, the field is deleted. + * foo.bar - Overwrites only the field bar of the object foo. + * If foo is not an object, foo is replaced with an object + * containing foo + */ class FieldMask { + constructor(e) { + this.fields = e, + // TODO(dimond): validation of FieldMask + // Sort the field mask to support `FieldMask.isEqual()` and assert below. + e.sort(FieldPath$1.comparator); + } + static empty() { + return new FieldMask([]); + } + /** + * Returns a new FieldMask object that is the result of adding all the given + * fields paths to this field mask. + */ unionWith(e) { + let t = new SortedSet(FieldPath$1.comparator); + for (const e of this.fields) t = t.add(e); + for (const n of e) t = t.add(n); + return new FieldMask(t.toArray()); + } + /** + * Verifies that `fieldPath` is included by at least one field in this field + * mask. + * + * This is an O(n) operation, where `n` is the size of the field mask. + */ covers(e) { + for (const t of this.fields) if (t.isPrefixOf(e)) return !0; + return !1; + } + isEqual(e) { + return __PRIVATE_arrayEquals(this.fields, e.fields, ((e, t) => e.isEqual(t))); + } +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An error encountered while decoding base64 string. + */ class __PRIVATE_Base64DecodeError extends Error { + constructor() { + super(...arguments), this.name = "Base64DecodeError"; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// WebSafe uses a different URL-encoding safe alphabet that doesn't match +// the encoding used on the backend. +const at = !1; + +/** Converts a Base64 encoded string to a binary string. */ function __PRIVATE_decodeBase64(e) { + try { + return String.fromCharCode.apply(null, + // We use `decodeStringToByteArray()` instead of `decodeString()` since + // `decodeString()` returns Unicode strings, which doesn't match the values + // returned by `atob()`'s Latin1 representation. + P.decodeStringToByteArray(e, at)); + } catch (e) { + throw e instanceof T ? new __PRIVATE_Base64DecodeError("Invalid base64 string: " + e) : e; + } +} + +/** Converts a binary string to a Base64 encoded string. */ +/** True if and only if the Base64 conversion functions are available. */ +function __PRIVATE_isBase64Available() { + return !0; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Immutable class that represents a "proto" byte string. + * + * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when + * sent on the wire. This class abstracts away this differentiation by holding + * the proto byte string in a common class that must be converted into a string + * before being sent as a proto. + * @internal + */ class ByteString { + constructor(e) { + this.binaryString = e; + } + static fromBase64String(e) { + const t = __PRIVATE_decodeBase64(e); + return new ByteString(t); + } + static fromUint8Array(e) { + // TODO(indexing); Remove the copy of the byte string here as this method + // is frequently called during indexing. + const t = + /** + * Helper function to convert an Uint8array to a binary string. + */ + function __PRIVATE_binaryStringFromUint8Array(e) { + let t = ""; + for (let n = 0; n < e.length; ++n) t += String.fromCharCode(e[n]); + return t; + } + /** + * Helper function to convert a binary string to an Uint8Array. + */ (e); + return new ByteString(t); + } + [Symbol.iterator]() { + let e = 0; + return { + next: () => e < this.binaryString.length ? { + value: this.binaryString.charCodeAt(e++), + done: !1 + } : { + value: void 0, + done: !0 + } + }; + } + toBase64() { + return function __PRIVATE_encodeBase64(e) { + const t = []; + for (let n = 0; n < e.length; n++) t[n] = e.charCodeAt(n); + return P.encodeByteArray(t, at); + }(this.binaryString); + } + toUint8Array() { + return function __PRIVATE_uint8ArrayFromBinaryString(e) { + const t = new Uint8Array(e.length); + for (let n = 0; n < e.length; n++) t[n] = e.charCodeAt(n); + return t; + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + // A RegExp matching ISO 8601 UTC timestamps with optional fraction. + (this.binaryString); + } + approximateByteSize() { + return 2 * this.binaryString.length; + } + compareTo(e) { + return __PRIVATE_primitiveComparator(this.binaryString, e.binaryString); + } + isEqual(e) { + return this.binaryString === e.binaryString; + } +} + +ByteString.EMPTY_BYTE_STRING = new ByteString(""); + +const ut = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/); + +/** + * Converts the possible Proto values for a timestamp value into a "seconds and + * nanos" representation. + */ function __PRIVATE_normalizeTimestamp(e) { + // The json interface (for the browser) will return an iso timestamp string, + // while the proto js library (for node) will return a + // google.protobuf.Timestamp instance. + if (__PRIVATE_hardAssert(!!e, 39018), "string" == typeof e) { + // The date string can have higher precision (nanos) than the Date class + // (millis), so we do some custom parsing here. + // Parse the nanos right out of the string. + let t = 0; + const n = ut.exec(e); + if (__PRIVATE_hardAssert(!!n, 46558, { + timestamp: e + }), n[1]) { + // Pad the fraction out to 9 digits (nanos). + let e = n[1]; + e = (e + "000000000").substr(0, 9), t = Number(e); + } + // Parse the date to get the seconds. + const r = new Date(e); + return { + seconds: Math.floor(r.getTime() / 1e3), + nanos: t + }; + } + return { + seconds: __PRIVATE_normalizeNumber(e.seconds), + nanos: __PRIVATE_normalizeNumber(e.nanos) + }; +} + +/** + * Converts the possible Proto types for numbers into a JavaScript number. + * Returns 0 if the value is not numeric. + */ function __PRIVATE_normalizeNumber(e) { + // TODO(bjornick): Handle int64 greater than 53 bits. + return "number" == typeof e ? e : "string" == typeof e ? Number(e) : 0; +} + +/** Converts the possible Proto types for Blobs into a ByteString. */ function __PRIVATE_normalizeByteString(e) { + return "string" == typeof e ? ByteString.fromBase64String(e) : ByteString.fromUint8Array(e); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a locally-applied ServerTimestamp. + * + * Server Timestamps are backed by MapValues that contain an internal field + * `__type__` with a value of `server_timestamp`. The previous value and local + * write time are stored in its `__previous_value__` and `__local_write_time__` + * fields respectively. + * + * Notes: + * - ServerTimestampValue instances are created as the result of applying a + * transform. They can only exist in the local view of a document. Therefore + * they do not need to be parsed or serialized. + * - When evaluated locally (e.g. for snapshot.data()), they by default + * evaluate to `null`. This behavior can be configured by passing custom + * FieldValueOptions to value(). + * - With respect to other ServerTimestampValues, they sort by their + * localWriteTime. + */ const ct = "server_timestamp", lt = "__type__", ht = "__previous_value__", Pt = "__local_write_time__"; + +function __PRIVATE_isServerTimestamp(e) { + const t = (e?.mapValue?.fields || {})[lt]?.stringValue; + return t === ct; +} + +/** + * Creates a new ServerTimestamp proto value (using the internal format). + */ +/** + * Returns the value of the field before this ServerTimestamp was set. + * + * Preserving the previous values allows the user to display the last resoled + * value until the backend responds with the timestamp. + */ +function __PRIVATE_getPreviousValue(e) { + const t = e.mapValue.fields[ht]; + return __PRIVATE_isServerTimestamp(t) ? __PRIVATE_getPreviousValue(t) : t; +} + +/** + * Returns the local time at which this timestamp was first set. + */ function __PRIVATE_getLocalWriteTime(e) { + const t = __PRIVATE_normalizeTimestamp(e.mapValue.fields[Pt].timestampValue); + return new Timestamp(t.seconds, t.nanos); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class DatabaseInfo { + /** + * Constructs a DatabaseInfo using the provided host, databaseId and + * persistenceKey. + * + * @param databaseId - The database to use. + * @param appId - The Firebase App Id. + * @param persistenceKey - A unique identifier for this Firestore's local + * storage (used in conjunction with the databaseId). + * @param host - The Firestore backend host to connect to. + * @param ssl - Whether to use SSL when connecting. + * @param forceLongPolling - Whether to use the forceLongPolling option + * when using WebChannel as the network transport. + * @param autoDetectLongPolling - Whether to use the detectBufferingProxy + * option when using WebChannel as the network transport. + * @param longPollingOptions Options that configure long-polling. + * @param useFetchStreams Whether to use the Fetch API instead of + * XMLHTTPRequest + */ + constructor(e, t, n, r, i, s, o, _, a, u) { + this.databaseId = e, this.appId = t, this.persistenceKey = n, this.host = r, this.ssl = i, + this.forceLongPolling = s, this.autoDetectLongPolling = o, this.longPollingOptions = _, + this.useFetchStreams = a, this.isUsingEmulator = u; + } +} + +/** The default database name for a project. */ const Tt = "(default)"; + +/** + * Represents the database ID a Firestore client is associated with. + * @internal + */ class DatabaseId { + constructor(e, t) { + this.projectId = e, this.database = t || Tt; + } + static empty() { + return new DatabaseId("", ""); + } + get isDefaultDatabase() { + return this.database === Tt; + } + isEqual(e) { + return e instanceof DatabaseId && e.projectId === this.projectId && e.database === this.database; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const It = "__type__", Et = "__max__", dt = { + mapValue: { + fields: { + __type__: { + stringValue: Et + } + } + } +}, At = "__vector__", Rt = "value", Vt = { + nullValue: "NULL_VALUE" +}; + +/** Extracts the backend's type order for the provided value. */ +function __PRIVATE_typeOrder(e) { + return "nullValue" in e ? 0 /* TypeOrder.NullValue */ : "booleanValue" in e ? 1 /* TypeOrder.BooleanValue */ : "integerValue" in e || "doubleValue" in e ? 2 /* TypeOrder.NumberValue */ : "timestampValue" in e ? 3 /* TypeOrder.TimestampValue */ : "stringValue" in e ? 5 /* TypeOrder.StringValue */ : "bytesValue" in e ? 6 /* TypeOrder.BlobValue */ : "referenceValue" in e ? 7 /* TypeOrder.RefValue */ : "geoPointValue" in e ? 8 /* TypeOrder.GeoPointValue */ : "arrayValue" in e ? 9 /* TypeOrder.ArrayValue */ : "mapValue" in e ? __PRIVATE_isServerTimestamp(e) ? 4 /* TypeOrder.ServerTimestampValue */ : __PRIVATE_isMaxValue(e) ? 9007199254740991 /* TypeOrder.MaxValue */ : __PRIVATE_isVectorValue(e) ? 10 /* TypeOrder.VectorValue */ : 11 /* TypeOrder.ObjectValue */ : fail(28295, { + value: e + }); +} + +/** Tests `left` and `right` for equality based on the backend semantics. */ function __PRIVATE_valueEquals(e, t) { + if (e === t) return !0; + const n = __PRIVATE_typeOrder(e); + if (n !== __PRIVATE_typeOrder(t)) return !1; + switch (n) { + case 0 /* TypeOrder.NullValue */ : + case 9007199254740991 /* TypeOrder.MaxValue */ : + return !0; + + case 1 /* TypeOrder.BooleanValue */ : + return e.booleanValue === t.booleanValue; + + case 4 /* TypeOrder.ServerTimestampValue */ : + return __PRIVATE_getLocalWriteTime(e).isEqual(__PRIVATE_getLocalWriteTime(t)); + + case 3 /* TypeOrder.TimestampValue */ : + return function __PRIVATE_timestampEquals(e, t) { + if ("string" == typeof e.timestampValue && "string" == typeof t.timestampValue && e.timestampValue.length === t.timestampValue.length) + // Use string equality for ISO 8601 timestamps + return e.timestampValue === t.timestampValue; + const n = __PRIVATE_normalizeTimestamp(e.timestampValue), r = __PRIVATE_normalizeTimestamp(t.timestampValue); + return n.seconds === r.seconds && n.nanos === r.nanos; + }(e, t); + + case 5 /* TypeOrder.StringValue */ : + return e.stringValue === t.stringValue; + + case 6 /* TypeOrder.BlobValue */ : + return function __PRIVATE_blobEquals(e, t) { + return __PRIVATE_normalizeByteString(e.bytesValue).isEqual(__PRIVATE_normalizeByteString(t.bytesValue)); + }(e, t); + + case 7 /* TypeOrder.RefValue */ : + return e.referenceValue === t.referenceValue; + + case 8 /* TypeOrder.GeoPointValue */ : + return function __PRIVATE_geoPointEquals(e, t) { + return __PRIVATE_normalizeNumber(e.geoPointValue.latitude) === __PRIVATE_normalizeNumber(t.geoPointValue.latitude) && __PRIVATE_normalizeNumber(e.geoPointValue.longitude) === __PRIVATE_normalizeNumber(t.geoPointValue.longitude); + }(e, t); + + case 2 /* TypeOrder.NumberValue */ : + return function __PRIVATE_numberEquals(e, t) { + if ("integerValue" in e && "integerValue" in t) return __PRIVATE_normalizeNumber(e.integerValue) === __PRIVATE_normalizeNumber(t.integerValue); + if ("doubleValue" in e && "doubleValue" in t) { + const n = __PRIVATE_normalizeNumber(e.doubleValue), r = __PRIVATE_normalizeNumber(t.doubleValue); + return n === r ? __PRIVATE_isNegativeZero(n) === __PRIVATE_isNegativeZero(r) : isNaN(n) && isNaN(r); + } + return !1; + }(e, t); + + case 9 /* TypeOrder.ArrayValue */ : + return __PRIVATE_arrayEquals(e.arrayValue.values || [], t.arrayValue.values || [], __PRIVATE_valueEquals); + + case 10 /* TypeOrder.VectorValue */ : + case 11 /* TypeOrder.ObjectValue */ : + return function __PRIVATE_objectEquals(e, t) { + const n = e.mapValue.fields || {}, r = t.mapValue.fields || {}; + if (__PRIVATE_objectSize(n) !== __PRIVATE_objectSize(r)) return !1; + for (const e in n) if (n.hasOwnProperty(e) && (void 0 === r[e] || !__PRIVATE_valueEquals(n[e], r[e]))) return !1; + return !0; + } + /** Returns true if the ArrayValue contains the specified element. */ (e, t); + + default: + return fail(52216, { + left: e + }); + } +} + +function __PRIVATE_arrayValueContains(e, t) { + return void 0 !== (e.values || []).find((e => __PRIVATE_valueEquals(e, t))); +} + +function __PRIVATE_valueCompare(e, t) { + if (e === t) return 0; + const n = __PRIVATE_typeOrder(e), r = __PRIVATE_typeOrder(t); + if (n !== r) return __PRIVATE_primitiveComparator(n, r); + switch (n) { + case 0 /* TypeOrder.NullValue */ : + case 9007199254740991 /* TypeOrder.MaxValue */ : + return 0; + + case 1 /* TypeOrder.BooleanValue */ : + return __PRIVATE_primitiveComparator(e.booleanValue, t.booleanValue); + + case 2 /* TypeOrder.NumberValue */ : + return function __PRIVATE_compareNumbers(e, t) { + const n = __PRIVATE_normalizeNumber(e.integerValue || e.doubleValue), r = __PRIVATE_normalizeNumber(t.integerValue || t.doubleValue); + return n < r ? -1 : n > r ? 1 : n === r ? 0 : + // one or both are NaN. + isNaN(n) ? isNaN(r) ? 0 : -1 : 1; + }(e, t); + + case 3 /* TypeOrder.TimestampValue */ : + return __PRIVATE_compareTimestamps(e.timestampValue, t.timestampValue); + + case 4 /* TypeOrder.ServerTimestampValue */ : + return __PRIVATE_compareTimestamps(__PRIVATE_getLocalWriteTime(e), __PRIVATE_getLocalWriteTime(t)); + + case 5 /* TypeOrder.StringValue */ : + return __PRIVATE_compareUtf8Strings(e.stringValue, t.stringValue); + + case 6 /* TypeOrder.BlobValue */ : + return function __PRIVATE_compareBlobs(e, t) { + const n = __PRIVATE_normalizeByteString(e), r = __PRIVATE_normalizeByteString(t); + return n.compareTo(r); + }(e.bytesValue, t.bytesValue); + + case 7 /* TypeOrder.RefValue */ : + return function __PRIVATE_compareReferences(e, t) { + const n = e.split("/"), r = t.split("/"); + for (let e = 0; e < n.length && e < r.length; e++) { + const t = __PRIVATE_primitiveComparator(n[e], r[e]); + if (0 !== t) return t; + } + return __PRIVATE_primitiveComparator(n.length, r.length); + }(e.referenceValue, t.referenceValue); + + case 8 /* TypeOrder.GeoPointValue */ : + return function __PRIVATE_compareGeoPoints(e, t) { + const n = __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(e.latitude), __PRIVATE_normalizeNumber(t.latitude)); + if (0 !== n) return n; + return __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(e.longitude), __PRIVATE_normalizeNumber(t.longitude)); + }(e.geoPointValue, t.geoPointValue); + + case 9 /* TypeOrder.ArrayValue */ : + return __PRIVATE_compareArrays(e.arrayValue, t.arrayValue); + + case 10 /* TypeOrder.VectorValue */ : + return function __PRIVATE_compareVectors(e, t) { + const n = e.fields || {}, r = t.fields || {}, i = n[Rt]?.arrayValue, s = r[Rt]?.arrayValue, o = __PRIVATE_primitiveComparator(i?.values?.length || 0, s?.values?.length || 0); + if (0 !== o) return o; + return __PRIVATE_compareArrays(i, s); + }(e.mapValue, t.mapValue); + + case 11 /* TypeOrder.ObjectValue */ : + return function __PRIVATE_compareMaps(e, t) { + if (e === dt.mapValue && t === dt.mapValue) return 0; + if (e === dt.mapValue) return 1; + if (t === dt.mapValue) return -1; + const n = e.fields || {}, r = Object.keys(n), i = t.fields || {}, s = Object.keys(i); + // Even though MapValues are likely sorted correctly based on their insertion + // order (e.g. when received from the backend), local modifications can bring + // elements out of order. We need to re-sort the elements to ensure that + // canonical IDs are independent of insertion order. + r.sort(), s.sort(); + for (let e = 0; e < r.length && e < s.length; ++e) { + const t = __PRIVATE_compareUtf8Strings(r[e], s[e]); + if (0 !== t) return t; + const o = __PRIVATE_valueCompare(n[r[e]], i[s[e]]); + if (0 !== o) return o; + } + return __PRIVATE_primitiveComparator(r.length, s.length); + } + /** + * Generates the canonical ID for the provided field value (as used in Target + * serialization). + */ (e.mapValue, t.mapValue); + + default: + throw fail(23264, { + he: n + }); + } +} + +function __PRIVATE_compareTimestamps(e, t) { + if ("string" == typeof e && "string" == typeof t && e.length === t.length) return __PRIVATE_primitiveComparator(e, t); + const n = __PRIVATE_normalizeTimestamp(e), r = __PRIVATE_normalizeTimestamp(t), i = __PRIVATE_primitiveComparator(n.seconds, r.seconds); + return 0 !== i ? i : __PRIVATE_primitiveComparator(n.nanos, r.nanos); +} + +function __PRIVATE_compareArrays(e, t) { + const n = e.values || [], r = t.values || []; + for (let e = 0; e < n.length && e < r.length; ++e) { + const t = __PRIVATE_valueCompare(n[e], r[e]); + if (t) return t; + } + return __PRIVATE_primitiveComparator(n.length, r.length); +} + +function canonicalId(e) { + return __PRIVATE_canonifyValue(e); +} + +function __PRIVATE_canonifyValue(e) { + return "nullValue" in e ? "null" : "booleanValue" in e ? "" + e.booleanValue : "integerValue" in e ? "" + e.integerValue : "doubleValue" in e ? "" + e.doubleValue : "timestampValue" in e ? function __PRIVATE_canonifyTimestamp(e) { + const t = __PRIVATE_normalizeTimestamp(e); + return `time(${t.seconds},${t.nanos})`; + }(e.timestampValue) : "stringValue" in e ? e.stringValue : "bytesValue" in e ? function __PRIVATE_canonifyByteString(e) { + return __PRIVATE_normalizeByteString(e).toBase64(); + }(e.bytesValue) : "referenceValue" in e ? function __PRIVATE_canonifyReference(e) { + return DocumentKey.fromName(e).toString(); + }(e.referenceValue) : "geoPointValue" in e ? function __PRIVATE_canonifyGeoPoint(e) { + return `geo(${e.latitude},${e.longitude})`; + }(e.geoPointValue) : "arrayValue" in e ? function __PRIVATE_canonifyArray(e) { + let t = "[", n = !0; + for (const r of e.values || []) n ? n = !1 : t += ",", t += __PRIVATE_canonifyValue(r); + return t + "]"; + } + /** + * Returns an approximate (and wildly inaccurate) in-memory size for the field + * value. + * + * The memory size takes into account only the actual user data as it resides + * in memory and ignores object overhead. + */ (e.arrayValue) : "mapValue" in e ? function __PRIVATE_canonifyMap(e) { + // Iteration order in JavaScript is not guaranteed. To ensure that we generate + // matching canonical IDs for identical maps, we need to sort the keys. + const t = Object.keys(e.fields || {}).sort(); + let n = "{", r = !0; + for (const i of t) r ? r = !1 : n += ",", n += `${i}:${__PRIVATE_canonifyValue(e.fields[i])}`; + return n + "}"; + }(e.mapValue) : fail(61005, { + value: e + }); +} + +function __PRIVATE_estimateByteSize(e) { + switch (__PRIVATE_typeOrder(e)) { + case 0 /* TypeOrder.NullValue */ : + case 1 /* TypeOrder.BooleanValue */ : + return 4; + + case 2 /* TypeOrder.NumberValue */ : + return 8; + + case 3 /* TypeOrder.TimestampValue */ : + case 8 /* TypeOrder.GeoPointValue */ : + // GeoPoints are made up of two distinct numbers (latitude + longitude) + return 16; + + case 4 /* TypeOrder.ServerTimestampValue */ : + const t = __PRIVATE_getPreviousValue(e); + return t ? 16 + __PRIVATE_estimateByteSize(t) : 16; + + case 5 /* TypeOrder.StringValue */ : + // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures: + // "JavaScript's String type is [...] a set of elements of 16-bit unsigned + // integer values" + return 2 * e.stringValue.length; + + case 6 /* TypeOrder.BlobValue */ : + return __PRIVATE_normalizeByteString(e.bytesValue).approximateByteSize(); + + case 7 /* TypeOrder.RefValue */ : + return e.referenceValue.length; + + case 9 /* TypeOrder.ArrayValue */ : + return function __PRIVATE_estimateArrayByteSize(e) { + return (e.values || []).reduce(((e, t) => e + __PRIVATE_estimateByteSize(t)), 0); + } + /** Returns a reference value for the provided database and key. */ (e.arrayValue); + + case 10 /* TypeOrder.VectorValue */ : + case 11 /* TypeOrder.ObjectValue */ : + return function __PRIVATE_estimateMapByteSize(e) { + let t = 0; + return forEach(e.fields, ((e, n) => { + t += e.length + __PRIVATE_estimateByteSize(n); + })), t; + }(e.mapValue); + + default: + throw fail(13486, { + value: e + }); + } +} + +function __PRIVATE_refValue(e, t) { + return { + referenceValue: `projects/${e.projectId}/databases/${e.database}/documents/${t.path.canonicalString()}` + }; +} + +/** Returns true if `value` is an IntegerValue . */ function isInteger(e) { + return !!e && "integerValue" in e; +} + +/** Returns true if `value` is a DoubleValue. */ +/** Returns true if `value` is an ArrayValue. */ +function isArray(e) { + return !!e && "arrayValue" in e; +} + +/** Returns true if `value` is a NullValue. */ function __PRIVATE_isNullValue(e) { + return !!e && "nullValue" in e; +} + +/** Returns true if `value` is NaN. */ function __PRIVATE_isNanValue(e) { + return !!e && "doubleValue" in e && isNaN(Number(e.doubleValue)); +} + +/** Returns true if `value` is a MapValue. */ function __PRIVATE_isMapValue(e) { + return !!e && "mapValue" in e; +} + +/** Returns true if `value` is a VetorValue. */ function __PRIVATE_isVectorValue(e) { + const t = (e?.mapValue?.fields || {})[It]?.stringValue; + return t === At; +} + +/** Creates a deep copy of `source`. */ function __PRIVATE_deepClone(e) { + if (e.geoPointValue) return { + geoPointValue: { + ...e.geoPointValue + } + }; + if (e.timestampValue && "object" == typeof e.timestampValue) return { + timestampValue: { + ...e.timestampValue + } + }; + if (e.mapValue) { + const t = { + mapValue: { + fields: {} + } + }; + return forEach(e.mapValue.fields, ((e, n) => t.mapValue.fields[e] = __PRIVATE_deepClone(n))), + t; + } + if (e.arrayValue) { + const t = { + arrayValue: { + values: [] + } + }; + for (let n = 0; n < (e.arrayValue.values || []).length; ++n) t.arrayValue.values[n] = __PRIVATE_deepClone(e.arrayValue.values[n]); + return t; + } + return { + ...e + }; +} + +/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ function __PRIVATE_isMaxValue(e) { + return (((e.mapValue || {}).fields || {}).__type__ || {}).stringValue === Et; +} + +const mt = { + mapValue: { + fields: { + [It]: { + stringValue: At + }, + [Rt]: { + arrayValue: {} + } + } + } +}; + +/** Returns the lowest value for the given value type (inclusive). */ function __PRIVATE_valuesGetLowerBound(e) { + return "nullValue" in e ? Vt : "booleanValue" in e ? { + booleanValue: !1 + } : "integerValue" in e || "doubleValue" in e ? { + doubleValue: NaN + } : "timestampValue" in e ? { + timestampValue: { + seconds: Number.MIN_SAFE_INTEGER + } + } : "stringValue" in e ? { + stringValue: "" + } : "bytesValue" in e ? { + bytesValue: "" + } : "referenceValue" in e ? __PRIVATE_refValue(DatabaseId.empty(), DocumentKey.empty()) : "geoPointValue" in e ? { + geoPointValue: { + latitude: -90, + longitude: -180 + } + } : "arrayValue" in e ? { + arrayValue: {} + } : "mapValue" in e ? __PRIVATE_isVectorValue(e) ? mt : { + mapValue: {} + } : fail(35942, { + value: e + }); +} + +/** Returns the largest value for the given value type (exclusive). */ function __PRIVATE_valuesGetUpperBound(e) { + return "nullValue" in e ? { + booleanValue: !1 + } : "booleanValue" in e ? { + doubleValue: NaN + } : "integerValue" in e || "doubleValue" in e ? { + timestampValue: { + seconds: Number.MIN_SAFE_INTEGER + } + } : "timestampValue" in e ? { + stringValue: "" + } : "stringValue" in e ? { + bytesValue: "" + } : "bytesValue" in e ? __PRIVATE_refValue(DatabaseId.empty(), DocumentKey.empty()) : "referenceValue" in e ? { + geoPointValue: { + latitude: -90, + longitude: -180 + } + } : "geoPointValue" in e ? { + arrayValue: {} + } : "arrayValue" in e ? mt : "mapValue" in e ? __PRIVATE_isVectorValue(e) ? { + mapValue: {} + } : dt : fail(61959, { + value: e + }); +} + +function __PRIVATE_lowerBoundCompare(e, t) { + const n = __PRIVATE_valueCompare(e.value, t.value); + return 0 !== n ? n : e.inclusive && !t.inclusive ? -1 : !e.inclusive && t.inclusive ? 1 : 0; +} + +function __PRIVATE_upperBoundCompare(e, t) { + const n = __PRIVATE_valueCompare(e.value, t.value); + return 0 !== n ? n : e.inclusive && !t.inclusive ? 1 : !e.inclusive && t.inclusive ? -1 : 0; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An ObjectValue represents a MapValue in the Firestore Proto and offers the + * ability to add and remove fields (via the ObjectValueBuilder). + */ class ObjectValue { + constructor(e) { + this.value = e; + } + static empty() { + return new ObjectValue({ + mapValue: {} + }); + } + /** + * Returns the value at the given path or null. + * + * @param path - the path to search + * @returns The value at the path or null if the path is not set. + */ field(e) { + if (e.isEmpty()) return this.value; + { + let t = this.value; + for (let n = 0; n < e.length - 1; ++n) if (t = (t.mapValue.fields || {})[e.get(n)], + !__PRIVATE_isMapValue(t)) return null; + return t = (t.mapValue.fields || {})[e.lastSegment()], t || null; + } + } + /** + * Sets the field to the provided value. + * + * @param path - The field path to set. + * @param value - The value to set. + */ set(e, t) { + this.getFieldsMap(e.popLast())[e.lastSegment()] = __PRIVATE_deepClone(t); + } + /** + * Sets the provided fields to the provided values. + * + * @param data - A map of fields to values (or null for deletes). + */ setAll(e) { + let t = FieldPath$1.emptyPath(), n = {}, r = []; + e.forEach(((e, i) => { + if (!t.isImmediateParentOf(i)) { + // Insert the accumulated changes at this parent location + const e = this.getFieldsMap(t); + this.applyChanges(e, n, r), n = {}, r = [], t = i.popLast(); + } + e ? n[i.lastSegment()] = __PRIVATE_deepClone(e) : r.push(i.lastSegment()); + })); + const i = this.getFieldsMap(t); + this.applyChanges(i, n, r); + } + /** + * Removes the field at the specified path. If there is no field at the + * specified path, nothing is changed. + * + * @param path - The field path to remove. + */ delete(e) { + const t = this.field(e.popLast()); + __PRIVATE_isMapValue(t) && t.mapValue.fields && delete t.mapValue.fields[e.lastSegment()]; + } + isEqual(e) { + return __PRIVATE_valueEquals(this.value, e.value); + } + /** + * Returns the map that contains the leaf element of `path`. If the parent + * entry does not yet exist, or if it is not a map, a new map will be created. + */ getFieldsMap(e) { + let t = this.value; + t.mapValue.fields || (t.mapValue = { + fields: {} + }); + for (let n = 0; n < e.length; ++n) { + let r = t.mapValue.fields[e.get(n)]; + __PRIVATE_isMapValue(r) && r.mapValue.fields || (r = { + mapValue: { + fields: {} + } + }, t.mapValue.fields[e.get(n)] = r), t = r; + } + return t.mapValue.fields; + } + /** + * Modifies `fieldsMap` by adding, replacing or deleting the specified + * entries. + */ applyChanges(e, t, n) { + forEach(t, ((t, n) => e[t] = n)); + for (const t of n) delete e[t]; + } + clone() { + return new ObjectValue(__PRIVATE_deepClone(this.value)); + } +} + +/** + * Returns a FieldMask built from all fields in a MapValue. + */ function __PRIVATE_extractFieldMask(e) { + const t = []; + return forEach(e.fields, ((e, n) => { + const r = new FieldPath$1([ e ]); + if (__PRIVATE_isMapValue(n)) { + const e = __PRIVATE_extractFieldMask(n.mapValue).fields; + if (0 === e.length) + // Preserve the empty map by adding it to the FieldMask. + t.push(r); else + // For nested and non-empty ObjectValues, add the FieldPath of the + // leaf nodes. + for (const n of e) t.push(r.child(n)); + } else + // For nested and non-empty ObjectValues, add the FieldPath of the leaf + // nodes. + t.push(r); + })), new FieldMask(t); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a document in Firestore with a key, version, data and whether it + * has local mutations applied to it. + * + * Documents can transition between states via `convertToFoundDocument()`, + * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does + * not transition to one of these states even after all mutations have been + * applied, `isValidDocument()` returns false and the document should be removed + * from all views. + */ class MutableDocument { + constructor(e, t, n, r, i, s, o) { + this.key = e, this.documentType = t, this.version = n, this.readTime = r, this.createTime = i, + this.data = s, this.documentState = o; + } + /** + * Creates a document with no known version or data, but which can serve as + * base document for mutations. + */ static newInvalidDocument(e) { + return new MutableDocument(e, 0 /* DocumentType.INVALID */ , + /* version */ SnapshotVersion.min(), + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist with the given data at the + * given version. + */ static newFoundDocument(e, t, n, r) { + return new MutableDocument(e, 1 /* DocumentType.FOUND_DOCUMENT */ , + /* version */ t, + /* readTime */ SnapshotVersion.min(), + /* createTime */ n, r, 0 /* DocumentState.SYNCED */); + } + /** Creates a new document that is known to not exist at the given version. */ static newNoDocument(e, t) { + return new MutableDocument(e, 2 /* DocumentType.NO_DOCUMENT */ , + /* version */ t, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist at the given version but + * whose data is not known (e.g. a document that was updated without a known + * base document). + */ static newUnknownDocument(e, t) { + return new MutableDocument(e, 3 /* DocumentType.UNKNOWN_DOCUMENT */ , + /* version */ t, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */); + } + /** + * Changes the document type to indicate that it exists and that its version + * and data are known. + */ convertToFoundDocument(e, t) { + // If a document is switching state from being an invalid or deleted + // document to a valid (FOUND_DOCUMENT) document, either due to receiving an + // update from Watch or due to applying a local set mutation on top + // of a deleted document, our best guess about its createTime would be the + // version at which the document transitioned to a FOUND_DOCUMENT. + return !this.createTime.isEqual(SnapshotVersion.min()) || 2 /* DocumentType.NO_DOCUMENT */ !== this.documentType && 0 /* DocumentType.INVALID */ !== this.documentType || (this.createTime = e), + this.version = e, this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */ , this.data = t, + this.documentState = 0 /* DocumentState.SYNCED */ , this; + } + /** + * Changes the document type to indicate that it doesn't exist at the given + * version. + */ convertToNoDocument(e) { + return this.version = e, this.documentType = 2 /* DocumentType.NO_DOCUMENT */ , + this.data = ObjectValue.empty(), this.documentState = 0 /* DocumentState.SYNCED */ , + this; + } + /** + * Changes the document type to indicate that it exists at a given version but + * that its data is not known (e.g. a document that was updated without a known + * base document). + */ convertToUnknownDocument(e) { + return this.version = e, this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */ , + this.data = ObjectValue.empty(), this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , + this; + } + setHasCommittedMutations() { + return this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , this; + } + setHasLocalMutations() { + return this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ , this.version = SnapshotVersion.min(), + this; + } + setReadTime(e) { + return this.readTime = e, this; + } + get hasLocalMutations() { + return 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ === this.documentState; + } + get hasCommittedMutations() { + return 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ === this.documentState; + } + get hasPendingWrites() { + return this.hasLocalMutations || this.hasCommittedMutations; + } + isValidDocument() { + return 0 /* DocumentType.INVALID */ !== this.documentType; + } + isFoundDocument() { + return 1 /* DocumentType.FOUND_DOCUMENT */ === this.documentType; + } + isNoDocument() { + return 2 /* DocumentType.NO_DOCUMENT */ === this.documentType; + } + isUnknownDocument() { + return 3 /* DocumentType.UNKNOWN_DOCUMENT */ === this.documentType; + } + isEqual(e) { + return e instanceof MutableDocument && this.key.isEqual(e.key) && this.version.isEqual(e.version) && this.documentType === e.documentType && this.documentState === e.documentState && this.data.isEqual(e.data); + } + mutableCopy() { + return new MutableDocument(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState); + } + toString() { + return `Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`; + } +} + +/** + * Compares the value for field `field` in the provided documents. Throws if + * the field does not exist in both documents. + */ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a bound of a query. + * + * The bound is specified with the given components representing a position and + * whether it's just before or just after the position (relative to whatever the + * query order is). + * + * The position represents a logical index position for a query. It's a prefix + * of values for the (potentially implicit) order by clauses of a query. + * + * Bound provides a function to determine whether a document comes before or + * after a bound. This is influenced by whether the position is just before or + * just after the provided values. + */ +class Bound { + constructor(e, t) { + this.position = e, this.inclusive = t; + } +} + +function __PRIVATE_boundCompareToDocument(e, t, n) { + let r = 0; + for (let i = 0; i < e.position.length; i++) { + const s = t[i], o = e.position[i]; + if (s.field.isKeyField()) r = DocumentKey.comparator(DocumentKey.fromName(o.referenceValue), n.key); else { + r = __PRIVATE_valueCompare(o, n.data.field(s.field)); + } + if ("desc" /* Direction.DESCENDING */ === s.dir && (r *= -1), 0 !== r) break; + } + return r; +} + +/** + * Returns true if a document sorts after a bound using the provided sort + * order. + */ function __PRIVATE_boundEquals(e, t) { + if (null === e) return null === t; + if (null === t) return !1; + if (e.inclusive !== t.inclusive || e.position.length !== t.position.length) return !1; + for (let n = 0; n < e.position.length; n++) { + if (!__PRIVATE_valueEquals(e.position[n], t.position[n])) return !1; + } + return !0; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An ordering on a field, in some Direction. Direction defaults to ASCENDING. + */ class OrderBy { + constructor(e, t = "asc" /* Direction.ASCENDING */) { + this.field = e, this.dir = t; + } +} + +function __PRIVATE_orderByEquals(e, t) { + return e.dir === t.dir && e.field.isEqual(t.field); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class Filter {} + +class FieldFilter extends Filter { + constructor(e, t, n) { + super(), this.field = e, this.op = t, this.value = n; + } + /** + * Creates a filter based on the provided arguments. + */ static create(e, t, n) { + return e.isKeyField() ? "in" /* Operator.IN */ === t || "not-in" /* Operator.NOT_IN */ === t ? this.createKeyFieldInFilter(e, t, n) : new __PRIVATE_KeyFieldFilter(e, t, n) : "array-contains" /* Operator.ARRAY_CONTAINS */ === t ? new __PRIVATE_ArrayContainsFilter(e, n) : "in" /* Operator.IN */ === t ? new __PRIVATE_InFilter(e, n) : "not-in" /* Operator.NOT_IN */ === t ? new __PRIVATE_NotInFilter(e, n) : "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === t ? new __PRIVATE_ArrayContainsAnyFilter(e, n) : new FieldFilter(e, t, n); + } + static createKeyFieldInFilter(e, t, n) { + return "in" /* Operator.IN */ === t ? new __PRIVATE_KeyFieldInFilter(e, n) : new __PRIVATE_KeyFieldNotInFilter(e, n); + } + matches(e) { + const t = e.data.field(this.field); + // Types do not have to match in NOT_EQUAL filters. + return "!=" /* Operator.NOT_EQUAL */ === this.op ? null !== t && void 0 === t.nullValue && this.matchesComparison(__PRIVATE_valueCompare(t, this.value)) : null !== t && __PRIVATE_typeOrder(this.value) === __PRIVATE_typeOrder(t) && this.matchesComparison(__PRIVATE_valueCompare(t, this.value)); + // Only compare types with matching backend order (such as double and int). + } + matchesComparison(e) { + switch (this.op) { + case "<" /* Operator.LESS_THAN */ : + return e < 0; + + case "<=" /* Operator.LESS_THAN_OR_EQUAL */ : + return e <= 0; + + case "==" /* Operator.EQUAL */ : + return 0 === e; + + case "!=" /* Operator.NOT_EQUAL */ : + return 0 !== e; + + case ">" /* Operator.GREATER_THAN */ : + return e > 0; + + case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ : + return e >= 0; + + default: + return fail(47266, { + operator: this.op + }); + } + } + isInequality() { + return [ "<" /* Operator.LESS_THAN */ , "<=" /* Operator.LESS_THAN_OR_EQUAL */ , ">" /* Operator.GREATER_THAN */ , ">=" /* Operator.GREATER_THAN_OR_EQUAL */ , "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ].indexOf(this.op) >= 0; + } + getFlattenedFilters() { + return [ this ]; + } + getFilters() { + return [ this ]; + } +} + +class CompositeFilter extends Filter { + constructor(e, t) { + super(), this.filters = e, this.op = t, this.Pe = null; + } + /** + * Creates a filter based on the provided arguments. + */ static create(e, t) { + return new CompositeFilter(e, t); + } + matches(e) { + return __PRIVATE_compositeFilterIsConjunction(this) ? void 0 === this.filters.find((t => !t.matches(e))) : void 0 !== this.filters.find((t => t.matches(e))); + } + getFlattenedFilters() { + return null !== this.Pe || (this.Pe = this.filters.reduce(((e, t) => e.concat(t.getFlattenedFilters())), [])), + this.Pe; + } + // Returns a mutable copy of `this.filters` + getFilters() { + return Object.assign([], this.filters); + } +} + +function __PRIVATE_compositeFilterIsConjunction(e) { + return "and" /* CompositeOperator.AND */ === e.op; +} + +function __PRIVATE_compositeFilterIsDisjunction(e) { + return "or" /* CompositeOperator.OR */ === e.op; +} + +/** + * Returns true if this filter is a conjunction of field filters only. Returns false otherwise. + */ function __PRIVATE_compositeFilterIsFlatConjunction(e) { + return __PRIVATE_compositeFilterIsFlat(e) && __PRIVATE_compositeFilterIsConjunction(e); +} + +/** + * Returns true if this filter does not contain any composite filters. Returns false otherwise. + */ function __PRIVATE_compositeFilterIsFlat(e) { + for (const t of e.filters) if (t instanceof CompositeFilter) return !1; + return !0; +} + +function __PRIVATE_canonifyFilter(e) { + if (e instanceof FieldFilter) + // TODO(b/29183165): Technically, this won't be unique if two values have + // the same description, such as the int 3 and the string "3". So we should + // add the types in here somehow, too. + return e.field.canonicalString() + e.op.toString() + canonicalId(e.value); + if (__PRIVATE_compositeFilterIsFlatConjunction(e)) + // Older SDK versions use an implicit AND operation between their filters. + // In the new SDK versions, the developer may use an explicit AND filter. + // To stay consistent with the old usages, we add a special case to ensure + // the canonical ID for these two are the same. For example: + // `col.whereEquals("a", 1).whereEquals("b", 2)` should have the same + // canonical ID as `col.where(and(equals("a",1), equals("b",2)))`. + return e.filters.map((e => __PRIVATE_canonifyFilter(e))).join(","); + { + // filter instanceof CompositeFilter + const t = e.filters.map((e => __PRIVATE_canonifyFilter(e))).join(","); + return `${e.op}(${t})`; + } +} + +function __PRIVATE_filterEquals(e, t) { + return e instanceof FieldFilter ? function __PRIVATE_fieldFilterEquals(e, t) { + return t instanceof FieldFilter && e.op === t.op && e.field.isEqual(t.field) && __PRIVATE_valueEquals(e.value, t.value); + }(e, t) : e instanceof CompositeFilter ? function __PRIVATE_compositeFilterEquals(e, t) { + if (t instanceof CompositeFilter && e.op === t.op && e.filters.length === t.filters.length) { + return e.filters.reduce(((e, n, r) => e && __PRIVATE_filterEquals(n, t.filters[r])), !0); + } + return !1; + } + /** + * Returns a new composite filter that contains all filter from + * `compositeFilter` plus all the given filters in `otherFilters`. + */ (e, t) : void fail(19439); +} + +function __PRIVATE_compositeFilterWithAddedFilters(e, t) { + const n = e.filters.concat(t); + return CompositeFilter.create(n, e.op); +} + +/** Returns a debug description for `filter`. */ function __PRIVATE_stringifyFilter(e) { + return e instanceof FieldFilter ? function __PRIVATE_stringifyFieldFilter(e) { + return `${e.field.canonicalString()} ${e.op} ${canonicalId(e.value)}`; + } + /** Filter that matches on key fields (i.e. '__name__'). */ (e) : e instanceof CompositeFilter ? function __PRIVATE_stringifyCompositeFilter(e) { + return e.op.toString() + " {" + e.getFilters().map(__PRIVATE_stringifyFilter).join(" ,") + "}"; + }(e) : "Filter"; +} + +class __PRIVATE_KeyFieldFilter extends FieldFilter { + constructor(e, t, n) { + super(e, t, n), this.key = DocumentKey.fromName(n.referenceValue); + } + matches(e) { + const t = DocumentKey.comparator(e.key, this.key); + return this.matchesComparison(t); + } +} + +/** Filter that matches on key fields within an array. */ class __PRIVATE_KeyFieldInFilter extends FieldFilter { + constructor(e, t) { + super(e, "in" /* Operator.IN */ , t), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue("in" /* Operator.IN */ , t); + } + matches(e) { + return this.keys.some((t => t.isEqual(e.key))); + } +} + +/** Filter that matches on key fields not present within an array. */ class __PRIVATE_KeyFieldNotInFilter extends FieldFilter { + constructor(e, t) { + super(e, "not-in" /* Operator.NOT_IN */ , t), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue("not-in" /* Operator.NOT_IN */ , t); + } + matches(e) { + return !this.keys.some((t => t.isEqual(e.key))); + } +} + +function __PRIVATE_extractDocumentKeysFromArrayValue(e, t) { + return (t.arrayValue?.values || []).map((e => DocumentKey.fromName(e.referenceValue))); +} + +/** A Filter that implements the array-contains operator. */ class __PRIVATE_ArrayContainsFilter extends FieldFilter { + constructor(e, t) { + super(e, "array-contains" /* Operator.ARRAY_CONTAINS */ , t); + } + matches(e) { + const t = e.data.field(this.field); + return isArray(t) && __PRIVATE_arrayValueContains(t.arrayValue, this.value); + } +} + +/** A Filter that implements the IN operator. */ class __PRIVATE_InFilter extends FieldFilter { + constructor(e, t) { + super(e, "in" /* Operator.IN */ , t); + } + matches(e) { + const t = e.data.field(this.field); + return null !== t && __PRIVATE_arrayValueContains(this.value.arrayValue, t); + } +} + +/** A Filter that implements the not-in operator. */ class __PRIVATE_NotInFilter extends FieldFilter { + constructor(e, t) { + super(e, "not-in" /* Operator.NOT_IN */ , t); + } + matches(e) { + if (__PRIVATE_arrayValueContains(this.value.arrayValue, { + nullValue: "NULL_VALUE" + })) return !1; + const t = e.data.field(this.field); + return null !== t && void 0 === t.nullValue && !__PRIVATE_arrayValueContains(this.value.arrayValue, t); + } +} + +/** A Filter that implements the array-contains-any operator. */ class __PRIVATE_ArrayContainsAnyFilter extends FieldFilter { + constructor(e, t) { + super(e, "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , t); + } + matches(e) { + const t = e.data.field(this.field); + return !(!isArray(t) || !t.arrayValue.values) && t.arrayValue.values.some((e => __PRIVATE_arrayValueContains(this.value.arrayValue, e))); + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Visible for testing +class __PRIVATE_TargetImpl { + constructor(e, t = null, n = [], r = [], i = null, s = null, o = null) { + this.path = e, this.collectionGroup = t, this.orderBy = n, this.filters = r, this.limit = i, + this.startAt = s, this.endAt = o, this.Te = null; + } +} + +/** + * Initializes a Target with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + * + * NOTE: you should always construct `Target` from `Query.toTarget` instead of + * using this factory method, because `Query` provides an implicit `orderBy` + * property. + */ function __PRIVATE_newTarget(e, t = null, n = [], r = [], i = null, s = null, o = null) { + return new __PRIVATE_TargetImpl(e, t, n, r, i, s, o); +} + +function __PRIVATE_canonifyTarget(e) { + const t = __PRIVATE_debugCast(e); + if (null === t.Te) { + let e = t.path.canonicalString(); + null !== t.collectionGroup && (e += "|cg:" + t.collectionGroup), e += "|f:", e += t.filters.map((e => __PRIVATE_canonifyFilter(e))).join(","), + e += "|ob:", e += t.orderBy.map((e => function __PRIVATE_canonifyOrderBy(e) { + // TODO(b/29183165): Make this collision robust. + return e.field.canonicalString() + e.dir; + }(e))).join(","), __PRIVATE_isNullOrUndefined(t.limit) || (e += "|l:", e += t.limit), + t.startAt && (e += "|lb:", e += t.startAt.inclusive ? "b:" : "a:", e += t.startAt.position.map((e => canonicalId(e))).join(",")), + t.endAt && (e += "|ub:", e += t.endAt.inclusive ? "a:" : "b:", e += t.endAt.position.map((e => canonicalId(e))).join(",")), + t.Te = e; + } + return t.Te; +} + +function __PRIVATE_targetEquals(e, t) { + if (e.limit !== t.limit) return !1; + if (e.orderBy.length !== t.orderBy.length) return !1; + for (let n = 0; n < e.orderBy.length; n++) if (!__PRIVATE_orderByEquals(e.orderBy[n], t.orderBy[n])) return !1; + if (e.filters.length !== t.filters.length) return !1; + for (let n = 0; n < e.filters.length; n++) if (!__PRIVATE_filterEquals(e.filters[n], t.filters[n])) return !1; + return e.collectionGroup === t.collectionGroup && (!!e.path.isEqual(t.path) && (!!__PRIVATE_boundEquals(e.startAt, t.startAt) && __PRIVATE_boundEquals(e.endAt, t.endAt))); +} + +function __PRIVATE_targetIsDocumentTarget(e) { + return DocumentKey.isDocumentKey(e.path) && null === e.collectionGroup && 0 === e.filters.length; +} + +/** Returns the field filters that target the given field path. */ function __PRIVATE_targetGetFieldFiltersForPath(e, t) { + return e.filters.filter((e => e instanceof FieldFilter && e.field.isEqual(t))); +} + +/** + * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY + * filters. Returns `null` if there are no such filters. + */ +/** + * Returns the value to use as the lower bound for ascending index segment at + * the provided `fieldPath` (or the upper bound for an descending segment). + */ +function __PRIVATE_targetGetAscendingBound(e, t, n) { + let r = Vt, i = !0; + // Process all filters to find a value for the current field segment + for (const n of __PRIVATE_targetGetFieldFiltersForPath(e, t)) { + let e = Vt, t = !0; + switch (n.op) { + case "<" /* Operator.LESS_THAN */ : + case "<=" /* Operator.LESS_THAN_OR_EQUAL */ : + e = __PRIVATE_valuesGetLowerBound(n.value); + break; + + case "==" /* Operator.EQUAL */ : + case "in" /* Operator.IN */ : + case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ : + e = n.value; + break; + + case ">" /* Operator.GREATER_THAN */ : + e = n.value, t = !1; + break; + + case "!=" /* Operator.NOT_EQUAL */ : + case "not-in" /* Operator.NOT_IN */ : + e = Vt; + // Remaining filters cannot be used as lower bounds. + } + __PRIVATE_lowerBoundCompare({ + value: r, + inclusive: i + }, { + value: e, + inclusive: t + }) < 0 && (r = e, i = t); + } + // If there is an additional bound, compare the values against the existing + // range to see if we can narrow the scope. + if (null !== n) for (let s = 0; s < e.orderBy.length; ++s) { + if (e.orderBy[s].field.isEqual(t)) { + const e = n.position[s]; + __PRIVATE_lowerBoundCompare({ + value: r, + inclusive: i + }, { + value: e, + inclusive: n.inclusive + }) < 0 && (r = e, i = n.inclusive); + break; + } + } + return { + value: r, + inclusive: i + }; +} + +/** + * Returns the value to use as the upper bound for ascending index segment at + * the provided `fieldPath` (or the lower bound for a descending segment). + */ function __PRIVATE_targetGetDescendingBound(e, t, n) { + let r = dt, i = !0; + // Process all filters to find a value for the current field segment + for (const n of __PRIVATE_targetGetFieldFiltersForPath(e, t)) { + let e = dt, t = !0; + switch (n.op) { + case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ : + case ">" /* Operator.GREATER_THAN */ : + e = __PRIVATE_valuesGetUpperBound(n.value), t = !1; + break; + + case "==" /* Operator.EQUAL */ : + case "in" /* Operator.IN */ : + case "<=" /* Operator.LESS_THAN_OR_EQUAL */ : + e = n.value; + break; + + case "<" /* Operator.LESS_THAN */ : + e = n.value, t = !1; + break; + + case "!=" /* Operator.NOT_EQUAL */ : + case "not-in" /* Operator.NOT_IN */ : + e = dt; + // Remaining filters cannot be used as upper bounds. + } + __PRIVATE_upperBoundCompare({ + value: r, + inclusive: i + }, { + value: e, + inclusive: t + }) > 0 && (r = e, i = t); + } + // If there is an additional bound, compare the values against the existing + // range to see if we can narrow the scope. + if (null !== n) for (let s = 0; s < e.orderBy.length; ++s) { + if (e.orderBy[s].field.isEqual(t)) { + const e = n.position[s]; + __PRIVATE_upperBoundCompare({ + value: r, + inclusive: i + }, { + value: e, + inclusive: n.inclusive + }) > 0 && (r = e, i = n.inclusive); + break; + } + } + return { + value: r, + inclusive: i + }; +} + +/** Returns the number of segments of a perfect index for this target. */ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Query encapsulates all the query attributes we support in the SDK. It can + * be run against the LocalStore, as well as be converted to a `Target` to + * query the RemoteStore results. + * + * Visible for testing. + */ +class __PRIVATE_QueryImpl { + /** + * Initializes a Query with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + */ + constructor(e, t = null, n = [], r = [], i = null, s = "F" /* LimitType.First */ , o = null, _ = null) { + this.path = e, this.collectionGroup = t, this.explicitOrderBy = n, this.filters = r, + this.limit = i, this.limitType = s, this.startAt = o, this.endAt = _, this.Ie = null, + // The corresponding `Target` of this `Query` instance, for use with + // non-aggregate queries. + this.Ee = null, + // The corresponding `Target` of this `Query` instance, for use with + // aggregate queries. Unlike targets for non-aggregate queries, + // aggregate query targets do not contain normalized order-bys, they only + // contain explicit order-bys. + this.de = null, this.startAt, this.endAt; + } +} + +/** Creates a new Query instance with the options provided. */ function __PRIVATE_newQuery(e, t, n, r, i, s, o, _) { + return new __PRIVATE_QueryImpl(e, t, n, r, i, s, o, _); +} + +/** Creates a new Query for a query that matches all documents at `path` */ function __PRIVATE_newQueryForPath(e) { + return new __PRIVATE_QueryImpl(e); +} + +/** + * Helper to convert a collection group query into a collection query at a + * specific path. This is used when executing collection group queries, since + * we have to split the query into a set of collection queries at multiple + * paths. + */ +/** + * Returns true if this query does not specify any query constraints that + * could remove results. + */ +function __PRIVATE_queryMatchesAllDocuments(e) { + return 0 === e.filters.length && null === e.limit && null == e.startAt && null == e.endAt && (0 === e.explicitOrderBy.length || 1 === e.explicitOrderBy.length && e.explicitOrderBy[0].field.isKeyField()); +} + +// Returns the sorted set of inequality filter fields used in this query. +/** + * Returns whether the query matches a collection group rather than a specific + * collection. + */ +function __PRIVATE_isCollectionGroupQuery(e) { + return null !== e.collectionGroup; +} + +/** + * Returns the normalized order-by constraint that is used to execute the Query, + * which can be different from the order-by constraints the user provided (e.g. + * the SDK and backend always orders by `__name__`). The normalized order-by + * includes implicit order-bys in addition to the explicit user provided + * order-bys. + */ function __PRIVATE_queryNormalizedOrderBy(e) { + const t = __PRIVATE_debugCast(e); + if (null === t.Ie) { + t.Ie = []; + const e = new Set; + // Any explicit order by fields should be added as is. + for (const n of t.explicitOrderBy) t.Ie.push(n), e.add(n.field.canonicalString()); + // The order of the implicit ordering always matches the last explicit order by. + const n = t.explicitOrderBy.length > 0 ? t.explicitOrderBy[t.explicitOrderBy.length - 1].dir : "asc" /* Direction.ASCENDING */ , r = function __PRIVATE_getInequalityFilterFields(e) { + let t = new SortedSet(FieldPath$1.comparator); + return e.filters.forEach((e => { + e.getFlattenedFilters().forEach((e => { + e.isInequality() && (t = t.add(e.field)); + })); + })), t; + } + /** + * Creates a new Query for a collection group query that matches all documents + * within the provided collection group. + */ (t); + // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical + // order. When there are multiple inequality filters on the same field, the field should be added + // only once. + // Note: `SortedSet` sorts the key field before other fields. However, we want the key + // field to be sorted last. + r.forEach((r => { + e.has(r.canonicalString()) || r.isKeyField() || t.Ie.push(new OrderBy(r, n)); + })), + // Add the document key field to the last if it is not explicitly ordered. + e.has(FieldPath$1.keyField().canonicalString()) || t.Ie.push(new OrderBy(FieldPath$1.keyField(), n)); + } + return t.Ie; +} + +/** + * Converts this `Query` instance to its corresponding `Target` representation. + */ function __PRIVATE_queryToTarget(e) { + const t = __PRIVATE_debugCast(e); + return t.Ee || (t.Ee = __PRIVATE__queryToTarget(t, __PRIVATE_queryNormalizedOrderBy(e))), + t.Ee; +} + +/** + * Converts this `Query` instance to its corresponding `Target` representation, + * for use within an aggregate query. Unlike targets for non-aggregate queries, + * aggregate query targets do not contain normalized order-bys, they only + * contain explicit order-bys. + */ function __PRIVATE_queryToAggregateTarget(e) { + const t = __PRIVATE_debugCast(e); + return t.de || ( + // Do not include implicit order-bys for aggregate queries. + t.de = __PRIVATE__queryToTarget(t, e.explicitOrderBy)), t.de; +} + +function __PRIVATE__queryToTarget(e, t) { + if ("F" /* LimitType.First */ === e.limitType) return __PRIVATE_newTarget(e.path, e.collectionGroup, t, e.filters, e.limit, e.startAt, e.endAt); + { + // Flip the orderBy directions since we want the last results + t = t.map((e => { + const t = "desc" /* Direction.DESCENDING */ === e.dir ? "asc" /* Direction.ASCENDING */ : "desc" /* Direction.DESCENDING */; + return new OrderBy(e.field, t); + })); + // We need to swap the cursors to match the now-flipped query ordering. + const n = e.endAt ? new Bound(e.endAt.position, e.endAt.inclusive) : null, r = e.startAt ? new Bound(e.startAt.position, e.startAt.inclusive) : null; + // Now return as a LimitType.First query. + return __PRIVATE_newTarget(e.path, e.collectionGroup, t, e.filters, e.limit, n, r); + } +} + +function __PRIVATE_queryWithAddedFilter(e, t) { + const n = e.filters.concat([ t ]); + return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, e.explicitOrderBy.slice(), n, e.limit, e.limitType, e.startAt, e.endAt); +} + +function __PRIVATE_queryWithLimit(e, t, n) { + return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, e.explicitOrderBy.slice(), e.filters.slice(), t, n, e.startAt, e.endAt); +} + +function __PRIVATE_queryEquals(e, t) { + return __PRIVATE_targetEquals(__PRIVATE_queryToTarget(e), __PRIVATE_queryToTarget(t)) && e.limitType === t.limitType; +} + +// TODO(b/29183165): This is used to get a unique string from a query to, for +// example, use as a dictionary key, but the implementation is subject to +// collisions. Make it collision-free. +function __PRIVATE_canonifyQuery(e) { + return `${__PRIVATE_canonifyTarget(__PRIVATE_queryToTarget(e))}|lt:${e.limitType}`; +} + +function __PRIVATE_stringifyQuery(e) { + return `Query(target=${function __PRIVATE_stringifyTarget(e) { + let t = e.path.canonicalString(); + return null !== e.collectionGroup && (t += " collectionGroup=" + e.collectionGroup), + e.filters.length > 0 && (t += `, filters: [${e.filters.map((e => __PRIVATE_stringifyFilter(e))).join(", ")}]`), + __PRIVATE_isNullOrUndefined(e.limit) || (t += ", limit: " + e.limit), e.orderBy.length > 0 && (t += `, orderBy: [${e.orderBy.map((e => function __PRIVATE_stringifyOrderBy(e) { + return `${e.field.canonicalString()} (${e.dir})`; + }(e))).join(", ")}]`), e.startAt && (t += ", startAt: ", t += e.startAt.inclusive ? "b:" : "a:", + t += e.startAt.position.map((e => canonicalId(e))).join(",")), e.endAt && (t += ", endAt: ", + t += e.endAt.inclusive ? "a:" : "b:", t += e.endAt.position.map((e => canonicalId(e))).join(",")), + `Target(${t})`; + }(__PRIVATE_queryToTarget(e))}; limitType=${e.limitType})`; +} + +/** Returns whether `doc` matches the constraints of `query`. */ function __PRIVATE_queryMatches(e, t) { + return t.isFoundDocument() && function __PRIVATE_queryMatchesPathAndCollectionGroup(e, t) { + const n = t.key.path; + return null !== e.collectionGroup ? t.key.hasCollectionId(e.collectionGroup) && e.path.isPrefixOf(n) : DocumentKey.isDocumentKey(e.path) ? e.path.isEqual(n) : e.path.isImmediateParentOf(n); + } + /** + * A document must have a value for every ordering clause in order to show up + * in the results. + */ (e, t) && function __PRIVATE_queryMatchesOrderBy(e, t) { + // We must use `queryNormalizedOrderBy()` to get the list of all orderBys (both implicit and explicit). + // Note that for OR queries, orderBy applies to all disjunction terms and implicit orderBys must + // be taken into account. For example, the query "a > 1 || b==1" has an implicit "orderBy a" due + // to the inequality, and is evaluated as "a > 1 orderBy a || b==1 orderBy a". + // A document with content of {b:1} matches the filters, but does not match the orderBy because + // it's missing the field 'a'. + for (const n of __PRIVATE_queryNormalizedOrderBy(e)) + // order-by key always matches + if (!n.field.isKeyField() && null === t.data.field(n.field)) return !1; + return !0; + }(e, t) && function __PRIVATE_queryMatchesFilters(e, t) { + for (const n of e.filters) if (!n.matches(t)) return !1; + return !0; + } + /** Makes sure a document is within the bounds, if provided. */ (e, t) && function __PRIVATE_queryMatchesBounds(e, t) { + if (e.startAt && ! + /** + * Returns true if a document sorts before a bound using the provided sort + * order. + */ + function __PRIVATE_boundSortsBeforeDocument(e, t, n) { + const r = __PRIVATE_boundCompareToDocument(e, t, n); + return e.inclusive ? r <= 0 : r < 0; + }(e.startAt, __PRIVATE_queryNormalizedOrderBy(e), t)) return !1; + if (e.endAt && !function __PRIVATE_boundSortsAfterDocument(e, t, n) { + const r = __PRIVATE_boundCompareToDocument(e, t, n); + return e.inclusive ? r >= 0 : r > 0; + }(e.endAt, __PRIVATE_queryNormalizedOrderBy(e), t)) return !1; + return !0; + } + /** + * Returns the collection group that this query targets. + * + * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab + * synchronization for query results. + */ (e, t); +} + +function __PRIVATE_queryCollectionGroup(e) { + return e.collectionGroup || (e.path.length % 2 == 1 ? e.path.lastSegment() : e.path.get(e.path.length - 2)); +} + +/** + * Returns a new comparator function that can be used to compare two documents + * based on the Query's ordering constraint. + */ function __PRIVATE_newQueryComparator(e) { + return (t, n) => { + let r = !1; + for (const i of __PRIVATE_queryNormalizedOrderBy(e)) { + const e = __PRIVATE_compareDocs(i, t, n); + if (0 !== e) return e; + r = r || i.field.isKeyField(); + } + return 0; + }; +} + +function __PRIVATE_compareDocs(e, t, n) { + const r = e.field.isKeyField() ? DocumentKey.comparator(t.key, n.key) : function __PRIVATE_compareDocumentsByField(e, t, n) { + const r = t.data.field(e), i = n.data.field(e); + return null !== r && null !== i ? __PRIVATE_valueCompare(r, i) : fail(42886); + }(e.field, t, n); + switch (e.dir) { + case "asc" /* Direction.ASCENDING */ : + return r; + + case "desc" /* Direction.DESCENDING */ : + return -1 * r; + + default: + return fail(19790, { + direction: e.dir + }); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A map implementation that uses objects as keys. Objects must have an + * associated equals function and must be immutable. Entries in the map are + * stored together with the key being produced from the mapKeyFn. This map + * automatically handles collisions of keys. + */ class ObjectMap { + constructor(e, t) { + this.mapKeyFn = e, this.equalsFn = t, + /** + * The inner map for a key/value pair. Due to the possibility of collisions we + * keep a list of entries that we do a linear search through to find an actual + * match. Note that collisions should be rare, so we still expect near + * constant time lookups in practice. + */ + this.inner = {}, + /** The number of entries stored in the map */ + this.innerSize = 0; + } + /** Get a value for this key, or undefined if it does not exist. */ get(e) { + const t = this.mapKeyFn(e), n = this.inner[t]; + if (void 0 !== n) for (const [t, r] of n) if (this.equalsFn(t, e)) return r; + } + has(e) { + return void 0 !== this.get(e); + } + /** Put this key and value in the map. */ set(e, t) { + const n = this.mapKeyFn(e), r = this.inner[n]; + if (void 0 === r) return this.inner[n] = [ [ e, t ] ], void this.innerSize++; + for (let n = 0; n < r.length; n++) if (this.equalsFn(r[n][0], e)) + // This is updating an existing entry and does not increase `innerSize`. + return void (r[n] = [ e, t ]); + r.push([ e, t ]), this.innerSize++; + } + /** + * Remove this key from the map. Returns a boolean if anything was deleted. + */ delete(e) { + const t = this.mapKeyFn(e), n = this.inner[t]; + if (void 0 === n) return !1; + for (let r = 0; r < n.length; r++) if (this.equalsFn(n[r][0], e)) return 1 === n.length ? delete this.inner[t] : n.splice(r, 1), + this.innerSize--, !0; + return !1; + } + forEach(e) { + forEach(this.inner, ((t, n) => { + for (const [t, r] of n) e(t, r); + })); + } + isEmpty() { + return isEmpty(this.inner); + } + size() { + return this.innerSize; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const ft = new SortedMap(DocumentKey.comparator); + +function __PRIVATE_mutableDocumentMap() { + return ft; +} + +const gt = new SortedMap(DocumentKey.comparator); + +function documentMap(...e) { + let t = gt; + for (const n of e) t = t.insert(n.key, n); + return t; +} + +function __PRIVATE_convertOverlayedDocumentMapToDocumentMap(e) { + let t = gt; + return e.forEach(((e, n) => t = t.insert(e, n.overlayedDocument))), t; +} + +function __PRIVATE_newOverlayMap() { + return __PRIVATE_newDocumentKeyMap(); +} + +function __PRIVATE_newMutationMap() { + return __PRIVATE_newDocumentKeyMap(); +} + +function __PRIVATE_newDocumentKeyMap() { + return new ObjectMap((e => e.toString()), ((e, t) => e.isEqual(t))); +} + +const pt = new SortedMap(DocumentKey.comparator); + +const yt = new SortedSet(DocumentKey.comparator); + +function __PRIVATE_documentKeySet(...e) { + let t = yt; + for (const n of e) t = t.add(n); + return t; +} + +const wt = new SortedSet(__PRIVATE_primitiveComparator); + +function __PRIVATE_targetIdSet() { + return wt; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns an DoubleValue for `value` that is encoded based the serializer's + * `useProto3Json` setting. + */ function __PRIVATE_toDouble(e, t) { + if (e.useProto3Json) { + if (isNaN(t)) return { + doubleValue: "NaN" + }; + if (t === 1 / 0) return { + doubleValue: "Infinity" + }; + if (t === -1 / 0) return { + doubleValue: "-Infinity" + }; + } + return { + doubleValue: __PRIVATE_isNegativeZero(t) ? "-0" : t + }; +} + +/** + * Returns an IntegerValue for `value`. + */ function __PRIVATE_toInteger(e) { + return { + integerValue: "" + e + }; +} + +/** + * Returns a value for a number that's appropriate to put into a proto. + * The return value is an IntegerValue if it can safely represent the value, + * otherwise a DoubleValue is returned. + */ function toNumber(e, t) { + return isSafeInteger(t) ? __PRIVATE_toInteger(t) : __PRIVATE_toDouble(e, t); +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Used to represent a field transform on a mutation. */ class TransformOperation { + constructor() { + // Make sure that the structural type of `TransformOperation` is unique. + // See https://github.com/microsoft/TypeScript/issues/5451 + this._ = void 0; + } +} + +/** + * Computes the local transform result against the provided `previousValue`, + * optionally using the provided localWriteTime. + */ function __PRIVATE_applyTransformOperationToLocalView(e, t, n) { + return e instanceof __PRIVATE_ServerTimestampTransform ? function serverTimestamp$1(e, t) { + const n = { + fields: { + [lt]: { + stringValue: ct + }, + [Pt]: { + timestampValue: { + seconds: e.seconds, + nanos: e.nanoseconds + } + } + } + }; + // We should avoid storing deeply nested server timestamp map values + // because we never use the intermediate "previous values". + // For example: + // previous: 42L, add: t1, result: t1 -> 42L + // previous: t1, add: t2, result: t2 -> 42L (NOT t2 -> t1 -> 42L) + // previous: t2, add: t3, result: t3 -> 42L (NOT t3 -> t2 -> t1 -> 42L) + // `getPreviousValue` recursively traverses server timestamps to find the + // least recent Value. + return t && __PRIVATE_isServerTimestamp(t) && (t = __PRIVATE_getPreviousValue(t)), + t && (n.fields[ht] = t), { + mapValue: n + }; + }(n, t) : e instanceof __PRIVATE_ArrayUnionTransformOperation ? __PRIVATE_applyArrayUnionTransformOperation(e, t) : e instanceof __PRIVATE_ArrayRemoveTransformOperation ? __PRIVATE_applyArrayRemoveTransformOperation(e, t) : function __PRIVATE_applyNumericIncrementTransformOperationToLocalView(e, t) { + // PORTING NOTE: Since JavaScript's integer arithmetic is limited to 53 bit + // precision and resolves overflows by reducing precision, we do not + // manually cap overflows at 2^63. + const n = __PRIVATE_computeTransformOperationBaseValue(e, t), r = asNumber(n) + asNumber(e.Ae); + return isInteger(n) && isInteger(e.Ae) ? __PRIVATE_toInteger(r) : __PRIVATE_toDouble(e.serializer, r); + }(e, t); +} + +/** + * Computes a final transform result after the transform has been acknowledged + * by the server, potentially using the server-provided transformResult. + */ function __PRIVATE_applyTransformOperationToRemoteDocument(e, t, n) { + // The server just sends null as the transform result for array operations, + // so we have to calculate a result the same as we do for local + // applications. + return e instanceof __PRIVATE_ArrayUnionTransformOperation ? __PRIVATE_applyArrayUnionTransformOperation(e, t) : e instanceof __PRIVATE_ArrayRemoveTransformOperation ? __PRIVATE_applyArrayRemoveTransformOperation(e, t) : n; +} + +/** + * If this transform operation is not idempotent, returns the base value to + * persist for this transform. If a base value is returned, the transform + * operation is always applied to this base value, even if document has + * already been updated. + * + * Base values provide consistent behavior for non-idempotent transforms and + * allow us to return the same latency-compensated value even if the backend + * has already applied the transform operation. The base value is null for + * idempotent transforms, as they can be re-played even if the backend has + * already applied them. + * + * @returns a base value to store along with the mutation, or null for + * idempotent transforms. + */ function __PRIVATE_computeTransformOperationBaseValue(e, t) { + return e instanceof __PRIVATE_NumericIncrementTransformOperation ? + /** Returns true if `value` is either an IntegerValue or a DoubleValue. */ + function __PRIVATE_isNumber(e) { + return isInteger(e) || function __PRIVATE_isDouble(e) { + return !!e && "doubleValue" in e; + }(e); + }(t) ? t : { + integerValue: 0 + } : null; +} + +/** Transforms a value into a server-generated timestamp. */ +class __PRIVATE_ServerTimestampTransform extends TransformOperation {} + +/** Transforms an array value via a union operation. */ class __PRIVATE_ArrayUnionTransformOperation extends TransformOperation { + constructor(e) { + super(), this.elements = e; + } +} + +function __PRIVATE_applyArrayUnionTransformOperation(e, t) { + const n = __PRIVATE_coercedFieldValuesArray(t); + for (const t of e.elements) n.some((e => __PRIVATE_valueEquals(e, t))) || n.push(t); + return { + arrayValue: { + values: n + } + }; +} + +/** Transforms an array value via a remove operation. */ class __PRIVATE_ArrayRemoveTransformOperation extends TransformOperation { + constructor(e) { + super(), this.elements = e; + } +} + +function __PRIVATE_applyArrayRemoveTransformOperation(e, t) { + let n = __PRIVATE_coercedFieldValuesArray(t); + for (const t of e.elements) n = n.filter((e => !__PRIVATE_valueEquals(e, t))); + return { + arrayValue: { + values: n + } + }; +} + +/** + * Implements the backend semantics for locally computed NUMERIC_ADD (increment) + * transforms. Converts all field values to integers or doubles, but unlike the + * backend does not cap integer values at 2^63. Instead, JavaScript number + * arithmetic is used and precision loss can occur for values greater than 2^53. + */ class __PRIVATE_NumericIncrementTransformOperation extends TransformOperation { + constructor(e, t) { + super(), this.serializer = e, this.Ae = t; + } +} + +function asNumber(e) { + return __PRIVATE_normalizeNumber(e.integerValue || e.doubleValue); +} + +function __PRIVATE_coercedFieldValuesArray(e) { + return isArray(e) && e.arrayValue.values ? e.arrayValue.values.slice() : []; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** A field path and the TransformOperation to perform upon it. */ class FieldTransform { + constructor(e, t) { + this.field = e, this.transform = t; + } +} + +function __PRIVATE_fieldTransformEquals(e, t) { + return e.field.isEqual(t.field) && function __PRIVATE_transformOperationEquals(e, t) { + return e instanceof __PRIVATE_ArrayUnionTransformOperation && t instanceof __PRIVATE_ArrayUnionTransformOperation || e instanceof __PRIVATE_ArrayRemoveTransformOperation && t instanceof __PRIVATE_ArrayRemoveTransformOperation ? __PRIVATE_arrayEquals(e.elements, t.elements, __PRIVATE_valueEquals) : e instanceof __PRIVATE_NumericIncrementTransformOperation && t instanceof __PRIVATE_NumericIncrementTransformOperation ? __PRIVATE_valueEquals(e.Ae, t.Ae) : e instanceof __PRIVATE_ServerTimestampTransform && t instanceof __PRIVATE_ServerTimestampTransform; + }(e.transform, t.transform); +} + +/** The result of successfully applying a mutation to the backend. */ +class MutationResult { + constructor( + /** + * The version at which the mutation was committed: + * + * - For most operations, this is the updateTime in the WriteResult. + * - For deletes, the commitTime of the WriteResponse (because deletes are + * not stored and have no updateTime). + * + * Note that these versions can be different: No-op writes will not change + * the updateTime even though the commitTime advances. + */ + e, + /** + * The resulting fields returned from the backend after a mutation + * containing field transforms has been committed. Contains one FieldValue + * for each FieldTransform that was in the mutation. + * + * Will be empty if the mutation did not contain any field transforms. + */ + t) { + this.version = e, this.transformResults = t; + } +} + +/** + * Encodes a precondition for a mutation. This follows the model that the + * backend accepts with the special case of an explicit "empty" precondition + * (meaning no precondition). + */ class Precondition { + constructor(e, t) { + this.updateTime = e, this.exists = t; + } + /** Creates a new empty Precondition. */ static none() { + return new Precondition; + } + /** Creates a new Precondition with an exists flag. */ static exists(e) { + return new Precondition(void 0, e); + } + /** Creates a new Precondition based on a version a document exists at. */ static updateTime(e) { + return new Precondition(e); + } + /** Returns whether this Precondition is empty. */ get isNone() { + return void 0 === this.updateTime && void 0 === this.exists; + } + isEqual(e) { + return this.exists === e.exists && (this.updateTime ? !!e.updateTime && this.updateTime.isEqual(e.updateTime) : !e.updateTime); + } +} + +/** Returns true if the preconditions is valid for the given document. */ function __PRIVATE_preconditionIsValidForDocument(e, t) { + return void 0 !== e.updateTime ? t.isFoundDocument() && t.version.isEqual(e.updateTime) : void 0 === e.exists || e.exists === t.isFoundDocument(); +} + +/** + * A mutation describes a self-contained change to a document. Mutations can + * create, replace, delete, and update subsets of documents. + * + * Mutations not only act on the value of the document but also its version. + * + * For local mutations (mutations that haven't been committed yet), we preserve + * the existing version for Set and Patch mutations. For Delete mutations, we + * reset the version to 0. + * + * Here's the expected transition table. + * + * MUTATION APPLIED TO RESULTS IN + * + * SetMutation Document(v3) Document(v3) + * SetMutation NoDocument(v3) Document(v0) + * SetMutation InvalidDocument(v0) Document(v0) + * PatchMutation Document(v3) Document(v3) + * PatchMutation NoDocument(v3) NoDocument(v3) + * PatchMutation InvalidDocument(v0) UnknownDocument(v3) + * DeleteMutation Document(v3) NoDocument(v0) + * DeleteMutation NoDocument(v3) NoDocument(v0) + * DeleteMutation InvalidDocument(v0) NoDocument(v0) + * + * For acknowledged mutations, we use the updateTime of the WriteResponse as + * the resulting version for Set and Patch mutations. As deletes have no + * explicit update time, we use the commitTime of the WriteResponse for + * Delete mutations. + * + * If a mutation is acknowledged by the backend but fails the precondition check + * locally, we transition to an `UnknownDocument` and rely on Watch to send us + * the updated version. + * + * Field transforms are used only with Patch and Set Mutations. We use the + * `updateTransforms` message to store transforms, rather than the `transforms`s + * messages. + * + * ## Subclassing Notes + * + * Every type of mutation needs to implement its own applyToRemoteDocument() and + * applyToLocalView() to implement the actual behavior of applying the mutation + * to some source document (see `setMutationApplyToRemoteDocument()` for an + * example). + */ class Mutation {} + +/** + * A utility method to calculate a `Mutation` representing the overlay from the + * final state of the document, and a `FieldMask` representing the fields that + * are mutated by the local mutations. + */ function __PRIVATE_calculateOverlayMutation(e, t) { + if (!e.hasLocalMutations || t && 0 === t.fields.length) return null; + // mask is null when sets or deletes are applied to the current document. + if (null === t) return e.isNoDocument() ? new __PRIVATE_DeleteMutation(e.key, Precondition.none()) : new __PRIVATE_SetMutation(e.key, e.data, Precondition.none()); + { + const n = e.data, r = ObjectValue.empty(); + let i = new SortedSet(FieldPath$1.comparator); + for (let e of t.fields) if (!i.has(e)) { + let t = n.field(e); + // If we are deleting a nested field, we take the immediate parent as + // the mask used to construct the resulting mutation. + // Justification: Nested fields can create parent fields implicitly. If + // only a leaf entry is deleted in later mutations, the parent field + // should still remain, but we may have lost this information. + // Consider mutation (foo.bar 1), then mutation (foo.bar delete()). + // This leaves the final result (foo, {}). Despite the fact that `doc` + // has the correct result, `foo` is not in `mask`, and the resulting + // mutation would miss `foo`. + null === t && e.length > 1 && (e = e.popLast(), t = n.field(e)), null === t ? r.delete(e) : r.set(e, t), + i = i.add(e); + } + return new __PRIVATE_PatchMutation(e.key, r, new FieldMask(i.toArray()), Precondition.none()); + } +} + +/** + * Applies this mutation to the given document for the purposes of computing a + * new remote document. If the input document doesn't match the expected state + * (e.g. it is invalid or outdated), the document type may transition to + * unknown. + * + * @param mutation - The mutation to apply. + * @param document - The document to mutate. The input document can be an + * invalid document if the client has no knowledge of the pre-mutation state + * of the document. + * @param mutationResult - The result of applying the mutation from the backend. + */ function __PRIVATE_mutationApplyToRemoteDocument(e, t, n) { + e instanceof __PRIVATE_SetMutation ? function __PRIVATE_setMutationApplyToRemoteDocument(e, t, n) { + // Unlike setMutationApplyToLocalView, if we're applying a mutation to a + // remote document the server has accepted the mutation so the precondition + // must have held. + const r = e.value.clone(), i = __PRIVATE_serverTransformResults(e.fieldTransforms, t, n.transformResults); + r.setAll(i), t.convertToFoundDocument(n.version, r).setHasCommittedMutations(); + }(e, t, n) : e instanceof __PRIVATE_PatchMutation ? function __PRIVATE_patchMutationApplyToRemoteDocument(e, t, n) { + if (!__PRIVATE_preconditionIsValidForDocument(e.precondition, t)) + // Since the mutation was not rejected, we know that the precondition + // matched on the backend. We therefore must not have the expected version + // of the document in our cache and convert to an UnknownDocument with a + // known updateTime. + return void t.convertToUnknownDocument(n.version); + const r = __PRIVATE_serverTransformResults(e.fieldTransforms, t, n.transformResults), i = t.data; + i.setAll(__PRIVATE_getPatch(e)), i.setAll(r), t.convertToFoundDocument(n.version, i).setHasCommittedMutations(); + }(e, t, n) : function __PRIVATE_deleteMutationApplyToRemoteDocument(e, t, n) { + // Unlike applyToLocalView, if we're applying a mutation to a remote + // document the server has accepted the mutation so the precondition must + // have held. + t.convertToNoDocument(n.version).setHasCommittedMutations(); + }(0, t, n); +} + +/** + * Applies this mutation to the given document for the purposes of computing + * the new local view of a document. If the input document doesn't match the + * expected state, the document is not modified. + * + * @param mutation - The mutation to apply. + * @param document - The document to mutate. The input document can be an + * invalid document if the client has no knowledge of the pre-mutation state + * of the document. + * @param previousMask - The fields that have been updated before applying this mutation. + * @param localWriteTime - A timestamp indicating the local write time of the + * batch this mutation is a part of. + * @returns A `FieldMask` representing the fields that are changed by applying this mutation. + */ function __PRIVATE_mutationApplyToLocalView(e, t, n, r) { + return e instanceof __PRIVATE_SetMutation ? function __PRIVATE_setMutationApplyToLocalView(e, t, n, r) { + if (!__PRIVATE_preconditionIsValidForDocument(e.precondition, t)) + // The mutation failed to apply (e.g. a document ID created with add() + // caused a name collision). + return n; + const i = e.value.clone(), s = __PRIVATE_localTransformResults(e.fieldTransforms, r, t); + return i.setAll(s), t.convertToFoundDocument(t.version, i).setHasLocalMutations(), + null; + // SetMutation overwrites all fields. + } + /** + * A mutation that modifies fields of the document at the given key with the + * given values. The values are applied through a field mask: + * + * * When a field is in both the mask and the values, the corresponding field + * is updated. + * * When a field is in neither the mask nor the values, the corresponding + * field is unmodified. + * * When a field is in the mask but not in the values, the corresponding field + * is deleted. + * * When a field is not in the mask but is in the values, the values map is + * ignored. + */ (e, t, n, r) : e instanceof __PRIVATE_PatchMutation ? function __PRIVATE_patchMutationApplyToLocalView(e, t, n, r) { + if (!__PRIVATE_preconditionIsValidForDocument(e.precondition, t)) return n; + const i = __PRIVATE_localTransformResults(e.fieldTransforms, r, t), s = t.data; + if (s.setAll(__PRIVATE_getPatch(e)), s.setAll(i), t.convertToFoundDocument(t.version, s).setHasLocalMutations(), + null === n) return null; + return n.unionWith(e.fieldMask.fields).unionWith(e.fieldTransforms.map((e => e.field))); + } + /** + * Returns a FieldPath/Value map with the content of the PatchMutation. + */ (e, t, n, r) : function __PRIVATE_deleteMutationApplyToLocalView(e, t, n) { + if (__PRIVATE_preconditionIsValidForDocument(e.precondition, t)) return t.convertToNoDocument(t.version).setHasLocalMutations(), + null; + return n; + } + /** + * A mutation that verifies the existence of the document at the given key with + * the provided precondition. + * + * The `verify` operation is only used in Transactions, and this class serves + * primarily to facilitate serialization into protos. + */ (e, t, n); +} + +/** + * If this mutation is not idempotent, returns the base value to persist with + * this mutation. If a base value is returned, the mutation is always applied + * to this base value, even if document has already been updated. + * + * The base value is a sparse object that consists of only the document + * fields for which this mutation contains a non-idempotent transformation + * (e.g. a numeric increment). The provided value guarantees consistent + * behavior for non-idempotent transforms and allow us to return the same + * latency-compensated value even if the backend has already applied the + * mutation. The base value is null for idempotent mutations, as they can be + * re-played even if the backend has already applied them. + * + * @returns a base value to store along with the mutation, or null for + * idempotent mutations. + */ function __PRIVATE_mutationExtractBaseValue(e, t) { + let n = null; + for (const r of e.fieldTransforms) { + const e = t.data.field(r.field), i = __PRIVATE_computeTransformOperationBaseValue(r.transform, e || null); + null != i && (null === n && (n = ObjectValue.empty()), n.set(r.field, i)); + } + return n || null; +} + +function __PRIVATE_mutationEquals(e, t) { + return e.type === t.type && (!!e.key.isEqual(t.key) && (!!e.precondition.isEqual(t.precondition) && (!!function __PRIVATE_fieldTransformsAreEqual(e, t) { + return void 0 === e && void 0 === t || !(!e || !t) && __PRIVATE_arrayEquals(e, t, ((e, t) => __PRIVATE_fieldTransformEquals(e, t))); + }(e.fieldTransforms, t.fieldTransforms) && (0 /* MutationType.Set */ === e.type ? e.value.isEqual(t.value) : 1 /* MutationType.Patch */ !== e.type || e.data.isEqual(t.data) && e.fieldMask.isEqual(t.fieldMask))))); +} + +/** + * A mutation that creates or replaces the document at the given key with the + * object value contents. + */ class __PRIVATE_SetMutation extends Mutation { + constructor(e, t, n, r = []) { + super(), this.key = e, this.value = t, this.precondition = n, this.fieldTransforms = r, + this.type = 0 /* MutationType.Set */; + } + getFieldMask() { + return null; + } +} + +class __PRIVATE_PatchMutation extends Mutation { + constructor(e, t, n, r, i = []) { + super(), this.key = e, this.data = t, this.fieldMask = n, this.precondition = r, + this.fieldTransforms = i, this.type = 1 /* MutationType.Patch */; + } + getFieldMask() { + return this.fieldMask; + } +} + +function __PRIVATE_getPatch(e) { + const t = new Map; + return e.fieldMask.fields.forEach((n => { + if (!n.isEmpty()) { + const r = e.data.field(n); + t.set(n, r); + } + })), t; +} + +/** + * Creates a list of "transform results" (a transform result is a field value + * representing the result of applying a transform) for use after a mutation + * containing transforms has been acknowledged by the server. + * + * @param fieldTransforms - The field transforms to apply the result to. + * @param mutableDocument - The current state of the document after applying all + * previous mutations. + * @param serverTransformResults - The transform results received by the server. + * @returns The transform results list. + */ function __PRIVATE_serverTransformResults(e, t, n) { + const r = new Map; + __PRIVATE_hardAssert(e.length === n.length, 32656, { + Re: n.length, + Ve: e.length + }); + for (let i = 0; i < n.length; i++) { + const s = e[i], o = s.transform, _ = t.data.field(s.field); + r.set(s.field, __PRIVATE_applyTransformOperationToRemoteDocument(o, _, n[i])); + } + return r; +} + +/** + * Creates a list of "transform results" (a transform result is a field value + * representing the result of applying a transform) for use when applying a + * transform locally. + * + * @param fieldTransforms - The field transforms to apply the result to. + * @param localWriteTime - The local time of the mutation (used to + * generate ServerTimestampValues). + * @param mutableDocument - The document to apply transforms on. + * @returns The transform results list. + */ function __PRIVATE_localTransformResults(e, t, n) { + const r = new Map; + for (const i of e) { + const e = i.transform, s = n.data.field(i.field); + r.set(i.field, __PRIVATE_applyTransformOperationToLocalView(e, s, t)); + } + return r; +} + +/** A mutation that deletes the document at the given key. */ class __PRIVATE_DeleteMutation extends Mutation { + constructor(e, t) { + super(), this.key = e, this.precondition = t, this.type = 2 /* MutationType.Delete */ , + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } +} + +class __PRIVATE_VerifyMutation extends Mutation { + constructor(e, t) { + super(), this.key = e, this.precondition = t, this.type = 3 /* MutationType.Verify */ , + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A batch of mutations that will be sent as one unit to the backend. + */ class MutationBatch { + /** + * @param batchId - The unique ID of this mutation batch. + * @param localWriteTime - The original write time of this mutation. + * @param baseMutations - Mutations that are used to populate the base + * values when this mutation is applied locally. This can be used to locally + * overwrite values that are persisted in the remote document cache. Base + * mutations are never sent to the backend. + * @param mutations - The user-provided mutations in this mutation batch. + * User-provided mutations are applied both locally and remotely on the + * backend. + */ + constructor(e, t, n, r) { + this.batchId = e, this.localWriteTime = t, this.baseMutations = n, this.mutations = r; + } + /** + * Applies all the mutations in this MutationBatch to the specified document + * to compute the state of the remote document + * + * @param document - The document to apply mutations to. + * @param batchResult - The result of applying the MutationBatch to the + * backend. + */ applyToRemoteDocument(e, t) { + const n = t.mutationResults; + for (let t = 0; t < this.mutations.length; t++) { + const r = this.mutations[t]; + if (r.key.isEqual(e.key)) { + __PRIVATE_mutationApplyToRemoteDocument(r, e, n[t]); + } + } + } + /** + * Computes the local view of a document given all the mutations in this + * batch. + * + * @param document - The document to apply mutations to. + * @param mutatedFields - Fields that have been updated before applying this mutation batch. + * @returns A `FieldMask` representing all the fields that are mutated. + */ applyToLocalView(e, t) { + // First, apply the base state. This allows us to apply non-idempotent + // transform against a consistent set of values. + for (const n of this.baseMutations) n.key.isEqual(e.key) && (t = __PRIVATE_mutationApplyToLocalView(n, e, t, this.localWriteTime)); + // Second, apply all user-provided mutations. + for (const n of this.mutations) n.key.isEqual(e.key) && (t = __PRIVATE_mutationApplyToLocalView(n, e, t, this.localWriteTime)); + return t; + } + /** + * Computes the local view for all provided documents given the mutations in + * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to + * replace all the mutation applications. + */ applyToLocalDocumentSet(e, t) { + // TODO(mrschmidt): This implementation is O(n^2). If we apply the mutations + // directly (as done in `applyToLocalView()`), we can reduce the complexity + // to O(n). + const n = __PRIVATE_newMutationMap(); + return this.mutations.forEach((r => { + const i = e.get(r.key), s = i.overlayedDocument; + // TODO(mutabledocuments): This method should take a MutableDocumentMap + // and we should remove this cast. + let o = this.applyToLocalView(s, i.mutatedFields); + // Set mutatedFields to null if the document is only from local mutations. + // This creates a Set or Delete mutation, instead of trying to create a + // patch mutation as the overlay. + o = t.has(r.key) ? null : o; + const _ = __PRIVATE_calculateOverlayMutation(s, o); + null !== _ && n.set(r.key, _), s.isValidDocument() || s.convertToNoDocument(SnapshotVersion.min()); + })), n; + } + keys() { + return this.mutations.reduce(((e, t) => e.add(t.key)), __PRIVATE_documentKeySet()); + } + isEqual(e) { + return this.batchId === e.batchId && __PRIVATE_arrayEquals(this.mutations, e.mutations, ((e, t) => __PRIVATE_mutationEquals(e, t))) && __PRIVATE_arrayEquals(this.baseMutations, e.baseMutations, ((e, t) => __PRIVATE_mutationEquals(e, t))); + } +} + +/** The result of applying a mutation batch to the backend. */ class MutationBatchResult { + constructor(e, t, n, + /** + * A pre-computed mapping from each mutated document to the resulting + * version. + */ + r) { + this.batch = e, this.commitVersion = t, this.mutationResults = n, this.docVersions = r; + } + /** + * Creates a new MutationBatchResult for the given batch and results. There + * must be one result for each mutation in the batch. This static factory + * caches a document=>version mapping (docVersions). + */ static from(e, t, n) { + __PRIVATE_hardAssert(e.mutations.length === n.length, 58842, { + me: e.mutations.length, + fe: n.length + }); + let r = function __PRIVATE_documentVersionMap() { + return pt; + }(); + const i = e.mutations; + for (let e = 0; e < i.length; e++) r = r.insert(i[e].key, n[e].version); + return new MutationBatchResult(e, t, n, r); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Representation of an overlay computed by Firestore. + * + * Holds information about a mutation and the largest batch id in Firestore when + * the mutation was created. + */ class Overlay { + constructor(e, t) { + this.largestBatchId = e, this.mutation = t; + } + getKey() { + return this.mutation.key; + } + isEqual(e) { + return null !== e && this.mutation === e.mutation; + } + toString() { + return `Overlay{\n largestBatchId: ${this.largestBatchId},\n mutation: ${this.mutation.toString()}\n }`; + } +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Concrete implementation of the Aggregate type. + */ class __PRIVATE_AggregateImpl { + constructor(e, t, n) { + this.alias = e, this.aggregateType = t, this.fieldPath = n; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class ExistenceFilter { + constructor(e, t) { + this.count = e, this.unchangedNames = t; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Error Codes describing the different ways GRPC can fail. These are copied + * directly from GRPC's sources here: + * + * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h + * + * Important! The names of these identifiers matter because the string forms + * are used for reverse lookups from the webchannel stream. Do NOT change the + * names of these identifiers or change this into a const enum. + */ var St, bt; + +/** + * Determines whether an error code represents a permanent error when received + * in response to a non-write operation. + * + * See isPermanentWriteError for classifying write errors. + */ +function __PRIVATE_isPermanentError(e) { + switch (e) { + case L.OK: + return fail(64938); + + case L.CANCELLED: + case L.UNKNOWN: + case L.DEADLINE_EXCEEDED: + case L.RESOURCE_EXHAUSTED: + case L.INTERNAL: + case L.UNAVAILABLE: + // Unauthenticated means something went wrong with our token and we need + // to retry with new credentials which will happen automatically. + case L.UNAUTHENTICATED: + return !1; + + case L.INVALID_ARGUMENT: + case L.NOT_FOUND: + case L.ALREADY_EXISTS: + case L.PERMISSION_DENIED: + case L.FAILED_PRECONDITION: + // Aborted might be retried in some scenarios, but that is dependent on + // the context and should handled individually by the calling code. + // See https://cloud.google.com/apis/design/errors. + case L.ABORTED: + case L.OUT_OF_RANGE: + case L.UNIMPLEMENTED: + case L.DATA_LOSS: + return !0; + + default: + return fail(15467, { + code: e + }); + } +} + +/** + * Determines whether an error code represents a permanent error when received + * in response to a write operation. + * + * Write operations must be handled specially because as of b/119437764, ABORTED + * errors on the write stream should be retried too (even though ABORTED errors + * are not generally retryable). + * + * Note that during the initial handshake on the write stream an ABORTED error + * signals that we should discard our stream token (i.e. it is permanent). This + * means a handshake error should be classified with isPermanentError, above. + */ +/** + * Maps an error Code from GRPC status code number, like 0, 1, or 14. These + * are not the same as HTTP status codes. + * + * @returns The Code equivalent to the given GRPC status code. Fails if there + * is no match. + */ +function __PRIVATE_mapCodeFromRpcCode(e) { + if (void 0 === e) + // This shouldn't normally happen, but in certain error cases (like trying + // to send invalid proto messages) we may get an error with no GRPC code. + return __PRIVATE_logError("GRPC error has no .code"), L.UNKNOWN; + switch (e) { + case St.OK: + return L.OK; + + case St.CANCELLED: + return L.CANCELLED; + + case St.UNKNOWN: + return L.UNKNOWN; + + case St.DEADLINE_EXCEEDED: + return L.DEADLINE_EXCEEDED; + + case St.RESOURCE_EXHAUSTED: + return L.RESOURCE_EXHAUSTED; + + case St.INTERNAL: + return L.INTERNAL; + + case St.UNAVAILABLE: + return L.UNAVAILABLE; + + case St.UNAUTHENTICATED: + return L.UNAUTHENTICATED; + + case St.INVALID_ARGUMENT: + return L.INVALID_ARGUMENT; + + case St.NOT_FOUND: + return L.NOT_FOUND; + + case St.ALREADY_EXISTS: + return L.ALREADY_EXISTS; + + case St.PERMISSION_DENIED: + return L.PERMISSION_DENIED; + + case St.FAILED_PRECONDITION: + return L.FAILED_PRECONDITION; + + case St.ABORTED: + return L.ABORTED; + + case St.OUT_OF_RANGE: + return L.OUT_OF_RANGE; + + case St.UNIMPLEMENTED: + return L.UNIMPLEMENTED; + + case St.DATA_LOSS: + return L.DATA_LOSS; + + default: + return fail(39323, { + code: e + }); + } +} + +/** + * Converts an HTTP response's error status to the equivalent error code. + * + * @param status - An HTTP error response status ("FAILED_PRECONDITION", + * "UNKNOWN", etc.) + * @returns The equivalent Code. Non-matching responses are mapped to + * Code.UNKNOWN. + */ (bt = St || (St = {}))[bt.OK = 0] = "OK", bt[bt.CANCELLED = 1] = "CANCELLED", +bt[bt.UNKNOWN = 2] = "UNKNOWN", bt[bt.INVALID_ARGUMENT = 3] = "INVALID_ARGUMENT", +bt[bt.DEADLINE_EXCEEDED = 4] = "DEADLINE_EXCEEDED", bt[bt.NOT_FOUND = 5] = "NOT_FOUND", +bt[bt.ALREADY_EXISTS = 6] = "ALREADY_EXISTS", bt[bt.PERMISSION_DENIED = 7] = "PERMISSION_DENIED", +bt[bt.UNAUTHENTICATED = 16] = "UNAUTHENTICATED", bt[bt.RESOURCE_EXHAUSTED = 8] = "RESOURCE_EXHAUSTED", +bt[bt.FAILED_PRECONDITION = 9] = "FAILED_PRECONDITION", bt[bt.ABORTED = 10] = "ABORTED", +bt[bt.OUT_OF_RANGE = 11] = "OUT_OF_RANGE", bt[bt.UNIMPLEMENTED = 12] = "UNIMPLEMENTED", +bt[bt.INTERNAL = 13] = "INTERNAL", bt[bt.UNAVAILABLE = 14] = "UNAVAILABLE", bt[bt.DATA_LOSS = 15] = "DATA_LOSS"; + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The global, singleton instance of TestingHooksSpi. + * + * This variable will be `null` in all cases _except_ when running from + * integration tests that have registered callbacks to be notified of events + * that happen during the test execution. + */ +let Dt = null; + +/** + * Sets the value of the `testingHooksSpi` object. + * @param instance the instance to set. + */ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An instance of the Platform's 'TextEncoder' implementation. + */ +function __PRIVATE_newTextEncoder() { + return new TextEncoder; +} + +/** + * An instance of the Platform's 'TextDecoder' implementation. + */ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const Ct = new p([ 4294967295, 4294967295 ], 0); + +// Hash a string using md5 hashing algorithm. +function __PRIVATE_getMd5HashValue(e) { + const t = __PRIVATE_newTextEncoder().encode(e), n = new y; + return n.update(t), new Uint8Array(n.digest()); +} + +// Interpret the 16 bytes array as two 64-bit unsigned integers, encoded using +// 2’s complement using little endian. +function __PRIVATE_get64BitUints(e) { + const t = new DataView(e.buffer), n = t.getUint32(0, /* littleEndian= */ !0), r = t.getUint32(4, /* littleEndian= */ !0), i = t.getUint32(8, /* littleEndian= */ !0), s = t.getUint32(12, /* littleEndian= */ !0); + return [ new p([ n, r ], 0), new p([ i, s ], 0) ]; +} + +class BloomFilter { + constructor(e, t, n) { + if (this.bitmap = e, this.padding = t, this.hashCount = n, t < 0 || t >= 8) throw new __PRIVATE_BloomFilterError(`Invalid padding: ${t}`); + if (n < 0) throw new __PRIVATE_BloomFilterError(`Invalid hash count: ${n}`); + if (e.length > 0 && 0 === this.hashCount) + // Only empty bloom filter can have 0 hash count. + throw new __PRIVATE_BloomFilterError(`Invalid hash count: ${n}`); + if (0 === e.length && 0 !== t) + // Empty bloom filter should have 0 padding. + throw new __PRIVATE_BloomFilterError(`Invalid padding when bitmap length is 0: ${t}`); + this.ge = 8 * e.length - t, + // Set the bit count in Integer to avoid repetition in mightContain(). + this.pe = p.fromNumber(this.ge); + } + // Calculate the ith hash value based on the hashed 64bit integers, + // and calculate its corresponding bit index in the bitmap to be checked. + ye(e, t, n) { + // Calculate hashed value h(i) = h1 + (i * h2). + let r = e.add(t.multiply(p.fromNumber(n))); + // Wrap if hash value overflow 64bit. + return 1 === r.compare(Ct) && (r = new p([ r.getBits(0), r.getBits(1) ], 0)), + r.modulo(this.pe).toNumber(); + } + // Return whether the bit on the given index in the bitmap is set to 1. + we(e) { + return !!(this.bitmap[Math.floor(e / 8)] & 1 << e % 8); + } + mightContain(e) { + // Empty bitmap should always return false on membership check. + if (0 === this.ge) return !1; + const t = __PRIVATE_getMd5HashValue(e), [n, r] = __PRIVATE_get64BitUints(t); + for (let e = 0; e < this.hashCount; e++) { + const t = this.ye(n, r, e); + if (!this.we(t)) return !1; + } + return !0; + } + /** Create bloom filter for testing purposes only. */ static create(e, t, n) { + const r = e % 8 == 0 ? 0 : 8 - e % 8, i = new Uint8Array(Math.ceil(e / 8)), s = new BloomFilter(i, r, t); + return n.forEach((e => s.insert(e))), s; + } + insert(e) { + if (0 === this.ge) return; + const t = __PRIVATE_getMd5HashValue(e), [n, r] = __PRIVATE_get64BitUints(t); + for (let e = 0; e < this.hashCount; e++) { + const t = this.ye(n, r, e); + this.Se(t); + } + } + Se(e) { + const t = Math.floor(e / 8), n = e % 8; + this.bitmap[t] |= 1 << n; + } +} + +class __PRIVATE_BloomFilterError extends Error { + constructor() { + super(...arguments), this.name = "BloomFilterError"; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An event from the RemoteStore. It is split into targetChanges (changes to the + * state or the set of documents in our watched targets) and documentUpdates + * (changes to the actual documents). + */ class RemoteEvent { + constructor( + /** + * The snapshot version this event brings us up to, or MIN if not set. + */ + e, + /** + * A map from target to changes to the target. See TargetChange. + */ + t, + /** + * A map of targets that is known to be inconsistent, and the purpose for + * re-listening. Listens for these targets should be re-established without + * resume tokens. + */ + n, + /** + * A set of which documents have changed or been deleted, along with the + * doc's new values (if not deleted). + */ + r, + /** + * A set of which document updates are due only to limbo resolution targets. + */ + i) { + this.snapshotVersion = e, this.targetChanges = t, this.targetMismatches = n, this.documentUpdates = r, + this.resolvedLimboDocuments = i; + } + /** + * HACK: Views require RemoteEvents in order to determine whether the view is + * CURRENT, but secondary tabs don't receive remote events. So this method is + * used to create a synthesized RemoteEvent that can be used to apply a + * CURRENT status change to a View, for queries executed in a different tab. + */ + // PORTING NOTE: Multi-tab only + static createSynthesizedRemoteEventForCurrentChange(e, t, n) { + const r = new Map; + return r.set(e, TargetChange.createSynthesizedTargetChangeForCurrentChange(e, t, n)), + new RemoteEvent(SnapshotVersion.min(), r, new SortedMap(__PRIVATE_primitiveComparator), __PRIVATE_mutableDocumentMap(), __PRIVATE_documentKeySet()); + } +} + +/** + * A TargetChange specifies the set of changes for a specific target as part of + * a RemoteEvent. These changes track which documents are added, modified or + * removed, as well as the target's resume token and whether the target is + * marked CURRENT. + * The actual changes *to* documents are not part of the TargetChange since + * documents may be part of multiple targets. + */ class TargetChange { + constructor( + /** + * An opaque, server-assigned token that allows watching a query to be resumed + * after disconnecting without retransmitting all the data that matches the + * query. The resume token essentially identifies a point in time from which + * the server should resume sending results. + */ + e, + /** + * The "current" (synced) status of this target. Note that "current" + * has special meaning in the RPC protocol that implies that a target is + * both up-to-date and consistent with the rest of the watch stream. + */ + t, + /** + * The set of documents that were newly assigned to this target as part of + * this remote event. + */ + n, + /** + * The set of documents that were already assigned to this target but received + * an update during this remote event. + */ + r, + /** + * The set of documents that were removed from this target as part of this + * remote event. + */ + i) { + this.resumeToken = e, this.current = t, this.addedDocuments = n, this.modifiedDocuments = r, + this.removedDocuments = i; + } + /** + * This method is used to create a synthesized TargetChanges that can be used to + * apply a CURRENT status change to a View (for queries executed in a different + * tab) or for new queries (to raise snapshots with correct CURRENT status). + */ static createSynthesizedTargetChangeForCurrentChange(e, t, n) { + return new TargetChange(n, t, __PRIVATE_documentKeySet(), __PRIVATE_documentKeySet(), __PRIVATE_documentKeySet()); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a changed document and a list of target ids to which this change + * applies. + * + * If document has been deleted NoDocument will be provided. + */ class __PRIVATE_DocumentWatchChange { + constructor( + /** The new document applies to all of these targets. */ + e, + /** The new document is removed from all of these targets. */ + t, + /** The key of the document for this change. */ + n, + /** + * The new document or NoDocument if it was deleted. Is null if the + * document went out of view without the server sending a new document. + */ + r) { + this.be = e, this.removedTargetIds = t, this.key = n, this.De = r; + } +} + +class __PRIVATE_ExistenceFilterChange { + constructor(e, t) { + this.targetId = e, this.Ce = t; + } +} + +class __PRIVATE_WatchTargetChange { + constructor( + /** What kind of change occurred to the watch target. */ + e, + /** The target IDs that were added/removed/set. */ + t, + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + n = ByteString.EMPTY_BYTE_STRING + /** An RPC error indicating why the watch failed. */ , r = null) { + this.state = e, this.targetIds = t, this.resumeToken = n, this.cause = r; + } +} + +/** Tracks the internal state of a Watch target. */ class __PRIVATE_TargetState { + constructor() { + /** + * The number of pending responses (adds or removes) that we are waiting on. + * We only consider targets active that have no pending responses. + */ + this.ve = 0, + /** + * Keeps track of the document changes since the last raised snapshot. + * + * These changes are continuously updated as we receive document updates and + * always reflect the current set of changes against the last issued snapshot. + */ + this.Fe = __PRIVATE_snapshotChangesMap(), + /** See public getters for explanations of these fields. */ + this.Me = ByteString.EMPTY_BYTE_STRING, this.xe = !1, + /** + * Whether this target state should be included in the next snapshot. We + * initialize to true so that newly-added targets are included in the next + * RemoteEvent. + */ + this.Oe = !0; + } + /** + * Whether this target has been marked 'current'. + * + * 'Current' has special meaning in the RPC protocol: It implies that the + * Watch backend has sent us all changes up to the point at which the target + * was added and that the target is consistent with the rest of the watch + * stream. + */ get current() { + return this.xe; + } + /** The last resume token sent to us for this target. */ get resumeToken() { + return this.Me; + } + /** Whether this target has pending target adds or target removes. */ get Ne() { + return 0 !== this.ve; + } + /** Whether we have modified any state that should trigger a snapshot. */ get Be() { + return this.Oe; + } + /** + * Applies the resume token to the TargetChange, but only when it has a new + * value. Empty resumeTokens are discarded. + */ Le(e) { + e.approximateByteSize() > 0 && (this.Oe = !0, this.Me = e); + } + /** + * Creates a target change from the current set of changes. + * + * To reset the document changes after raising this snapshot, call + * `clearPendingChanges()`. + */ ke() { + let e = __PRIVATE_documentKeySet(), t = __PRIVATE_documentKeySet(), n = __PRIVATE_documentKeySet(); + return this.Fe.forEach(((r, i) => { + switch (i) { + case 0 /* ChangeType.Added */ : + e = e.add(r); + break; + + case 2 /* ChangeType.Modified */ : + t = t.add(r); + break; + + case 1 /* ChangeType.Removed */ : + n = n.add(r); + break; + + default: + fail(38017, { + changeType: i + }); + } + })), new TargetChange(this.Me, this.xe, e, t, n); + } + /** + * Resets the document changes and sets `hasPendingChanges` to false. + */ qe() { + this.Oe = !1, this.Fe = __PRIVATE_snapshotChangesMap(); + } + Qe(e, t) { + this.Oe = !0, this.Fe = this.Fe.insert(e, t); + } + $e(e) { + this.Oe = !0, this.Fe = this.Fe.remove(e); + } + Ue() { + this.ve += 1; + } + Ke() { + this.ve -= 1, __PRIVATE_hardAssert(this.ve >= 0, 3241, { + ve: this.ve + }); + } + We() { + this.Oe = !0, this.xe = !0; + } +} + +/** + * A helper class to accumulate watch changes into a RemoteEvent. + */ +class __PRIVATE_WatchChangeAggregator { + constructor(e) { + this.Ge = e, + /** The internal state of all tracked targets. */ + this.ze = new Map, + /** Keeps track of the documents to update since the last raised snapshot. */ + this.je = __PRIVATE_mutableDocumentMap(), this.Je = __PRIVATE_documentTargetMap(), + /** A mapping of document keys to their set of target IDs. */ + this.He = __PRIVATE_documentTargetMap(), + /** + * A map of targets with existence filter mismatches. These targets are + * known to be inconsistent and their listens needs to be re-established by + * RemoteStore. + */ + this.Ye = new SortedMap(__PRIVATE_primitiveComparator); + } + /** + * Processes and adds the DocumentWatchChange to the current set of changes. + */ Ze(e) { + for (const t of e.be) e.De && e.De.isFoundDocument() ? this.Xe(t, e.De) : this.et(t, e.key, e.De); + for (const t of e.removedTargetIds) this.et(t, e.key, e.De); + } + /** Processes and adds the WatchTargetChange to the current set of changes. */ tt(e) { + this.forEachTarget(e, (t => { + const n = this.nt(t); + switch (e.state) { + case 0 /* WatchTargetChangeState.NoChange */ : + this.rt(t) && n.Le(e.resumeToken); + break; + + case 1 /* WatchTargetChangeState.Added */ : + // We need to decrement the number of pending acks needed from watch + // for this targetId. + n.Ke(), n.Ne || + // We have a freshly added target, so we need to reset any state + // that we had previously. This can happen e.g. when remove and add + // back a target for existence filter mismatches. + n.qe(), n.Le(e.resumeToken); + break; + + case 2 /* WatchTargetChangeState.Removed */ : + // We need to keep track of removed targets to we can post-filter and + // remove any target changes. + // We need to decrement the number of pending acks needed from watch + // for this targetId. + n.Ke(), n.Ne || this.removeTarget(t); + break; + + case 3 /* WatchTargetChangeState.Current */ : + this.rt(t) && (n.We(), n.Le(e.resumeToken)); + break; + + case 4 /* WatchTargetChangeState.Reset */ : + this.rt(t) && ( + // Reset the target and synthesizes removes for all existing + // documents. The backend will re-add any documents that still + // match the target before it sends the next global snapshot. + this.it(t), n.Le(e.resumeToken)); + break; + + default: + fail(56790, { + state: e.state + }); + } + })); + } + /** + * Iterates over all targetIds that the watch change applies to: either the + * targetIds explicitly listed in the change or the targetIds of all currently + * active targets. + */ forEachTarget(e, t) { + e.targetIds.length > 0 ? e.targetIds.forEach(t) : this.ze.forEach(((e, n) => { + this.rt(n) && t(n); + })); + } + /** + * Handles existence filters and synthesizes deletes for filter mismatches. + * Targets that are invalidated by filter mismatches are added to + * `pendingTargetResets`. + */ st(e) { + const t = e.targetId, n = e.Ce.count, r = this.ot(t); + if (r) { + const i = r.target; + if (__PRIVATE_targetIsDocumentTarget(i)) if (0 === n) { + // The existence filter told us the document does not exist. We deduce + // that this document does not exist and apply a deleted document to + // our updates. Without applying this deleted document there might be + // another query that will raise this document as part of a snapshot + // until it is resolved, essentially exposing inconsistency between + // queries. + const e = new DocumentKey(i.path); + this.et(t, e, MutableDocument.newNoDocument(e, SnapshotVersion.min())); + } else __PRIVATE_hardAssert(1 === n, 20013, { + expectedCount: n + }); else { + const r = this._t(t); + // Existence filter mismatch. Mark the documents as being in limbo, and + // raise a snapshot with `isFromCache:true`. + if (r !== n) { + // Apply bloom filter to identify and mark removed documents. + const n = this.ut(e), i = n ? this.ct(n, e, r) : 1 /* BloomFilterApplicationStatus.Skipped */; + if (0 /* BloomFilterApplicationStatus.Success */ !== i) { + // If bloom filter application fails, we reset the mapping and + // trigger re-run of the query. + this.it(t); + const e = 2 /* BloomFilterApplicationStatus.FalsePositive */ === i ? "TargetPurposeExistenceFilterMismatchBloom" /* TargetPurpose.ExistenceFilterMismatchBloom */ : "TargetPurposeExistenceFilterMismatch" /* TargetPurpose.ExistenceFilterMismatch */; + this.Ye = this.Ye.insert(t, e); + } + Dt?.lt(function __PRIVATE_createExistenceFilterMismatchInfoForTestingHooks(e, t, n, r, i) { + const s = { + localCacheCount: e, + existenceFilterCount: t.count, + databaseId: n.database, + projectId: n.projectId + }, o = t.unchangedNames; + o && (s.bloomFilter = { + applied: 0 /* BloomFilterApplicationStatus.Success */ === i, + hashCount: o?.hashCount ?? 0, + bitmapLength: o?.bits?.bitmap?.length ?? 0, + padding: o?.bits?.padding ?? 0, + mightContain: e => r?.mightContain(e) ?? !1 + }); + return s; + } + /** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ (r, e.Ce, this.Ge.ht(), n, i)); + } + } + } + } + /** + * Parse the bloom filter from the "unchanged_names" field of an existence + * filter. + */ ut(e) { + const t = e.Ce.unchangedNames; + if (!t || !t.bits) return null; + const {bits: {bitmap: n = "", padding: r = 0}, hashCount: i = 0} = t; + let s, o; + try { + s = __PRIVATE_normalizeByteString(n).toUint8Array(); + } catch (e) { + if (e instanceof __PRIVATE_Base64DecodeError) return __PRIVATE_logWarn("Decoding the base64 bloom filter in existence filter failed (" + e.message + "); ignoring the bloom filter and falling back to full re-query."), + null; + throw e; + } + try { + // BloomFilter throws error if the inputs are invalid. + o = new BloomFilter(s, r, i); + } catch (e) { + return __PRIVATE_logWarn(e instanceof __PRIVATE_BloomFilterError ? "BloomFilter error: " : "Applying bloom filter failed: ", e), + null; + } + return 0 === o.ge ? null : o; + } + /** + * Apply bloom filter to remove the deleted documents, and return the + * application status. + */ ct(e, t, n) { + return t.Ce.count === n - this.Pt(e, t.targetId) ? 0 /* BloomFilterApplicationStatus.Success */ : 2 /* BloomFilterApplicationStatus.FalsePositive */; + } + /** + * Filter out removed documents based on bloom filter membership result and + * return number of documents removed. + */ Pt(e, t) { + const n = this.Ge.getRemoteKeysForTarget(t); + let r = 0; + return n.forEach((n => { + const i = this.Ge.ht(), s = `projects/${i.projectId}/databases/${i.database}/documents/${n.path.canonicalString()}`; + e.mightContain(s) || (this.et(t, n, /*updatedDocument=*/ null), r++); + })), r; + } + /** + * Converts the currently accumulated state into a remote event at the + * provided snapshot version. Resets the accumulated changes before returning. + */ Tt(e) { + const t = new Map; + this.ze.forEach(((n, r) => { + const i = this.ot(r); + if (i) { + if (n.current && __PRIVATE_targetIsDocumentTarget(i.target)) { + // Document queries for document that don't exist can produce an empty + // result set. To update our local cache, we synthesize a document + // delete if we have not previously received the document for this + // target. This resolves the limbo state of the document, removing it + // from limboDocumentRefs. + // TODO(dimond): Ideally we would have an explicit lookup target + // instead resulting in an explicit delete message and we could + // remove this special logic. + const t = new DocumentKey(i.target.path); + this.It(t).has(r) || this.Et(r, t) || this.et(r, t, MutableDocument.newNoDocument(t, e)); + } + n.Be && (t.set(r, n.ke()), n.qe()); + } + })); + let n = __PRIVATE_documentKeySet(); + // We extract the set of limbo-only document updates as the GC logic + // special-cases documents that do not appear in the target cache. + + // TODO(gsoltis): Expand on this comment once GC is available in the JS + // client. + this.He.forEach(((e, t) => { + let r = !0; + t.forEachWhile((e => { + const t = this.ot(e); + return !t || "TargetPurposeLimboResolution" /* TargetPurpose.LimboResolution */ === t.purpose || (r = !1, + !1); + })), r && (n = n.add(e)); + })), this.je.forEach(((t, n) => n.setReadTime(e))); + const r = new RemoteEvent(e, t, this.Ye, this.je, n); + return this.je = __PRIVATE_mutableDocumentMap(), this.Je = __PRIVATE_documentTargetMap(), + this.He = __PRIVATE_documentTargetMap(), this.Ye = new SortedMap(__PRIVATE_primitiveComparator), + r; + } + /** + * Adds the provided document to the internal list of document updates and + * its document key to the given target's mapping. + */ + // Visible for testing. + Xe(e, t) { + if (!this.rt(e)) return; + const n = this.Et(e, t.key) ? 2 /* ChangeType.Modified */ : 0 /* ChangeType.Added */; + this.nt(e).Qe(t.key, n), this.je = this.je.insert(t.key, t), this.Je = this.Je.insert(t.key, this.It(t.key).add(e)), + this.He = this.He.insert(t.key, this.dt(t.key).add(e)); + } + /** + * Removes the provided document from the target mapping. If the + * document no longer matches the target, but the document's state is still + * known (e.g. we know that the document was deleted or we received the change + * that caused the filter mismatch), the new document can be provided + * to update the remote document cache. + */ + // Visible for testing. + et(e, t, n) { + if (!this.rt(e)) return; + const r = this.nt(e); + this.Et(e, t) ? r.Qe(t, 1 /* ChangeType.Removed */) : + // The document may have entered and left the target before we raised a + // snapshot, so we can just ignore the change. + r.$e(t), this.He = this.He.insert(t, this.dt(t).delete(e)), this.He = this.He.insert(t, this.dt(t).add(e)), + n && (this.je = this.je.insert(t, n)); + } + removeTarget(e) { + this.ze.delete(e); + } + /** + * Returns the current count of documents in the target. This includes both + * the number of documents that the LocalStore considers to be part of the + * target as well as any accumulated changes. + */ _t(e) { + const t = this.nt(e).ke(); + return this.Ge.getRemoteKeysForTarget(e).size + t.addedDocuments.size - t.removedDocuments.size; + } + /** + * Increment the number of acks needed from watch before we can consider the + * server to be 'in-sync' with the client's active targets. + */ Ue(e) { + this.nt(e).Ue(); + } + nt(e) { + let t = this.ze.get(e); + return t || (t = new __PRIVATE_TargetState, this.ze.set(e, t)), t; + } + dt(e) { + let t = this.He.get(e); + return t || (t = new SortedSet(__PRIVATE_primitiveComparator), this.He = this.He.insert(e, t)), + t; + } + It(e) { + let t = this.Je.get(e); + return t || (t = new SortedSet(__PRIVATE_primitiveComparator), this.Je = this.Je.insert(e, t)), + t; + } + /** + * Verifies that the user is still interested in this target (by calling + * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs + * from watch. + */ rt(e) { + const t = null !== this.ot(e); + return t || __PRIVATE_logDebug("WatchChangeAggregator", "Detected inactive target", e), + t; + } + /** + * Returns the TargetData for an active target (i.e. a target that the user + * is still interested in that has no outstanding target change requests). + */ ot(e) { + const t = this.ze.get(e); + return t && t.Ne ? null : this.Ge.At(e); + } + /** + * Resets the state of a Watch target to its initial state (e.g. sets + * 'current' to false, clears the resume token and removes its target mapping + * from all documents). + */ it(e) { + this.ze.set(e, new __PRIVATE_TargetState); + this.Ge.getRemoteKeysForTarget(e).forEach((t => { + this.et(e, t, /*updatedDocument=*/ null); + })); + } + /** + * Returns whether the LocalStore considers the document to be part of the + * specified target. + */ Et(e, t) { + return this.Ge.getRemoteKeysForTarget(e).has(t); + } +} + +function __PRIVATE_documentTargetMap() { + return new SortedMap(DocumentKey.comparator); +} + +function __PRIVATE_snapshotChangesMap() { + return new SortedMap(DocumentKey.comparator); +} + +const vt = (() => { + const e = { + asc: "ASCENDING", + desc: "DESCENDING" + }; + return e; +})(), Ft = (() => { + const e = { + "<": "LESS_THAN", + "<=": "LESS_THAN_OR_EQUAL", + ">": "GREATER_THAN", + ">=": "GREATER_THAN_OR_EQUAL", + "==": "EQUAL", + "!=": "NOT_EQUAL", + "array-contains": "ARRAY_CONTAINS", + in: "IN", + "not-in": "NOT_IN", + "array-contains-any": "ARRAY_CONTAINS_ANY" + }; + return e; +})(), Mt = (() => { + const e = { + and: "AND", + or: "OR" + }; + return e; +})(); + +/** + * This class generates JsonObject values for the Datastore API suitable for + * sending to either GRPC stub methods or via the JSON/HTTP REST API. + * + * The serializer supports both Protobuf.js and Proto3 JSON formats. By + * setting `useProto3Json` to true, the serializer will use the Proto3 JSON + * format. + * + * For a description of the Proto3 JSON format check + * https://developers.google.com/protocol-buffers/docs/proto3#json + * + * TODO(klimt): We can remove the databaseId argument if we keep the full + * resource name in documents. + */ +class JsonProtoSerializer { + constructor(e, t) { + this.databaseId = e, this.useProto3Json = t; + } +} + +/** + * Returns a value for a number (or null) that's appropriate to put into + * a google.protobuf.Int32Value proto. + * DO NOT USE THIS FOR ANYTHING ELSE. + * This method cheats. It's typed as returning "number" because that's what + * our generated proto interfaces say Int32Value must be. But GRPC actually + * expects a { value: } struct. + */ +function __PRIVATE_toInt32Proto(e, t) { + return e.useProto3Json || __PRIVATE_isNullOrUndefined(t) ? t : { + value: t + }; +} + +/** + * Returns a number (or null) from a google.protobuf.Int32Value proto. + */ +/** + * Returns a value for a Date that's appropriate to put into a proto. + */ +function toTimestamp(e, t) { + if (e.useProto3Json) { + return `${new Date(1e3 * t.seconds).toISOString().replace(/\.\d*/, "").replace("Z", "")}.${("000000000" + t.nanoseconds).slice(-9)}Z`; + } + return { + seconds: "" + t.seconds, + nanos: t.nanoseconds + }; +} + +/** + * Returns a Timestamp typed object given protobuf timestamp value. + */ +/** + * Returns a value for bytes that's appropriate to put in a proto. + * + * Visible for testing. + */ +function __PRIVATE_toBytes(e, t) { + return e.useProto3Json ? t.toBase64() : t.toUint8Array(); +} + +/** + * Returns a ByteString based on the proto string value. + */ function __PRIVATE_toVersion(e, t) { + return toTimestamp(e, t.toTimestamp()); +} + +function __PRIVATE_fromVersion(e) { + return __PRIVATE_hardAssert(!!e, 49232), SnapshotVersion.fromTimestamp(function fromTimestamp(e) { + const t = __PRIVATE_normalizeTimestamp(e); + return new Timestamp(t.seconds, t.nanos); + }(e)); +} + +function __PRIVATE_toResourceName(e, t) { + return __PRIVATE_toResourcePath(e, t).canonicalString(); +} + +function __PRIVATE_toResourcePath(e, t) { + const n = function __PRIVATE_fullyQualifiedPrefixPath(e) { + return new ResourcePath([ "projects", e.projectId, "databases", e.database ]); + }(e).child("documents"); + return void 0 === t ? n : n.child(t); +} + +function __PRIVATE_fromResourceName(e) { + const t = ResourcePath.fromString(e); + return __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(t), 10190, { + key: t.toString() + }), t; +} + +function __PRIVATE_toName(e, t) { + return __PRIVATE_toResourceName(e.databaseId, t.path); +} + +function fromName(e, t) { + const n = __PRIVATE_fromResourceName(t); + if (n.get(1) !== e.databaseId.projectId) throw new FirestoreError(L.INVALID_ARGUMENT, "Tried to deserialize key from different project: " + n.get(1) + " vs " + e.databaseId.projectId); + if (n.get(3) !== e.databaseId.database) throw new FirestoreError(L.INVALID_ARGUMENT, "Tried to deserialize key from different database: " + n.get(3) + " vs " + e.databaseId.database); + return new DocumentKey(__PRIVATE_extractLocalPathFromResourceName(n)); +} + +function __PRIVATE_toQueryPath(e, t) { + return __PRIVATE_toResourceName(e.databaseId, t); +} + +function __PRIVATE_fromQueryPath(e) { + const t = __PRIVATE_fromResourceName(e); + // In v1beta1 queries for collections at the root did not have a trailing + // "/documents". In v1 all resource paths contain "/documents". Preserve the + // ability to read the v1beta1 form for compatibility with queries persisted + // in the local target cache. + return 4 === t.length ? ResourcePath.emptyPath() : __PRIVATE_extractLocalPathFromResourceName(t); +} + +function __PRIVATE_getEncodedDatabaseId(e) { + return new ResourcePath([ "projects", e.databaseId.projectId, "databases", e.databaseId.database ]).canonicalString(); +} + +function __PRIVATE_extractLocalPathFromResourceName(e) { + return __PRIVATE_hardAssert(e.length > 4 && "documents" === e.get(4), 29091, { + key: e.toString() + }), e.popFirst(5); +} + +/** Creates a Document proto from key and fields (but no create/update time) */ function __PRIVATE_toMutationDocument(e, t, n) { + return { + name: __PRIVATE_toName(e, t), + fields: n.value.mapValue.fields + }; +} + +function __PRIVATE_fromDocument(e, t, n) { + const r = fromName(e, t.name), i = __PRIVATE_fromVersion(t.updateTime), s = t.createTime ? __PRIVATE_fromVersion(t.createTime) : SnapshotVersion.min(), o = new ObjectValue({ + mapValue: { + fields: t.fields + } + }), _ = MutableDocument.newFoundDocument(r, i, s, o); + return n && _.setHasCommittedMutations(), n ? _.setHasCommittedMutations() : _; +} + +function __PRIVATE_fromBatchGetDocumentsResponse(e, t) { + return "found" in t ? function __PRIVATE_fromFound(e, t) { + __PRIVATE_hardAssert(!!t.found, 43571), t.found.name, t.found.updateTime; + const n = fromName(e, t.found.name), r = __PRIVATE_fromVersion(t.found.updateTime), i = t.found.createTime ? __PRIVATE_fromVersion(t.found.createTime) : SnapshotVersion.min(), s = new ObjectValue({ + mapValue: { + fields: t.found.fields + } + }); + return MutableDocument.newFoundDocument(n, r, i, s); + }(e, t) : "missing" in t ? function __PRIVATE_fromMissing(e, t) { + __PRIVATE_hardAssert(!!t.missing, 3894), __PRIVATE_hardAssert(!!t.readTime, 22933); + const n = fromName(e, t.missing), r = __PRIVATE_fromVersion(t.readTime); + return MutableDocument.newNoDocument(n, r); + }(e, t) : fail(7234, { + result: t + }); +} + +function __PRIVATE_fromWatchChange(e, t) { + let n; + if ("targetChange" in t) { + t.targetChange; + // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE' + // if unset + const r = function __PRIVATE_fromWatchTargetChangeState(e) { + return "NO_CHANGE" === e ? 0 /* WatchTargetChangeState.NoChange */ : "ADD" === e ? 1 /* WatchTargetChangeState.Added */ : "REMOVE" === e ? 2 /* WatchTargetChangeState.Removed */ : "CURRENT" === e ? 3 /* WatchTargetChangeState.Current */ : "RESET" === e ? 4 /* WatchTargetChangeState.Reset */ : fail(39313, { + state: e + }); + }(t.targetChange.targetChangeType || "NO_CHANGE"), i = t.targetChange.targetIds || [], s = function __PRIVATE_fromBytes(e, t) { + return e.useProto3Json ? (__PRIVATE_hardAssert(void 0 === t || "string" == typeof t, 58123), + ByteString.fromBase64String(t || "")) : (__PRIVATE_hardAssert(void 0 === t || + // Check if the value is an instance of both Buffer and Uint8Array, + // despite the fact that Buffer extends Uint8Array. In some + // environments, such as jsdom, the prototype chain of Buffer + // does not indicate that it extends Uint8Array. + t instanceof Buffer || t instanceof Uint8Array, 16193), ByteString.fromUint8Array(t || new Uint8Array)); + }(e, t.targetChange.resumeToken), o = t.targetChange.cause, _ = o && function __PRIVATE_fromRpcStatus(e) { + const t = void 0 === e.code ? L.UNKNOWN : __PRIVATE_mapCodeFromRpcCode(e.code); + return new FirestoreError(t, e.message || ""); + }(o); + n = new __PRIVATE_WatchTargetChange(r, i, s, _ || null); + } else if ("documentChange" in t) { + t.documentChange; + const r = t.documentChange; + r.document, r.document.name, r.document.updateTime; + const i = fromName(e, r.document.name), s = __PRIVATE_fromVersion(r.document.updateTime), o = r.document.createTime ? __PRIVATE_fromVersion(r.document.createTime) : SnapshotVersion.min(), _ = new ObjectValue({ + mapValue: { + fields: r.document.fields + } + }), a = MutableDocument.newFoundDocument(i, s, o, _), u = r.targetIds || [], c = r.removedTargetIds || []; + n = new __PRIVATE_DocumentWatchChange(u, c, a.key, a); + } else if ("documentDelete" in t) { + t.documentDelete; + const r = t.documentDelete; + r.document; + const i = fromName(e, r.document), s = r.readTime ? __PRIVATE_fromVersion(r.readTime) : SnapshotVersion.min(), o = MutableDocument.newNoDocument(i, s), _ = r.removedTargetIds || []; + n = new __PRIVATE_DocumentWatchChange([], _, o.key, o); + } else if ("documentRemove" in t) { + t.documentRemove; + const r = t.documentRemove; + r.document; + const i = fromName(e, r.document), s = r.removedTargetIds || []; + n = new __PRIVATE_DocumentWatchChange([], s, i, null); + } else { + if (!("filter" in t)) return fail(11601, { + Rt: t + }); + { + t.filter; + const e = t.filter; + e.targetId; + const {count: r = 0, unchangedNames: i} = e, s = new ExistenceFilter(r, i), o = e.targetId; + n = new __PRIVATE_ExistenceFilterChange(o, s); + } + } + return n; +} + +function toMutation(e, t) { + let n; + if (t instanceof __PRIVATE_SetMutation) n = { + update: __PRIVATE_toMutationDocument(e, t.key, t.value) + }; else if (t instanceof __PRIVATE_DeleteMutation) n = { + delete: __PRIVATE_toName(e, t.key) + }; else if (t instanceof __PRIVATE_PatchMutation) n = { + update: __PRIVATE_toMutationDocument(e, t.key, t.data), + updateMask: __PRIVATE_toDocumentMask(t.fieldMask) + }; else { + if (!(t instanceof __PRIVATE_VerifyMutation)) return fail(16599, { + Vt: t.type + }); + n = { + verify: __PRIVATE_toName(e, t.key) + }; + } + return t.fieldTransforms.length > 0 && (n.updateTransforms = t.fieldTransforms.map((e => function __PRIVATE_toFieldTransform(e, t) { + const n = t.transform; + if (n instanceof __PRIVATE_ServerTimestampTransform) return { + fieldPath: t.field.canonicalString(), + setToServerValue: "REQUEST_TIME" + }; + if (n instanceof __PRIVATE_ArrayUnionTransformOperation) return { + fieldPath: t.field.canonicalString(), + appendMissingElements: { + values: n.elements + } + }; + if (n instanceof __PRIVATE_ArrayRemoveTransformOperation) return { + fieldPath: t.field.canonicalString(), + removeAllFromArray: { + values: n.elements + } + }; + if (n instanceof __PRIVATE_NumericIncrementTransformOperation) return { + fieldPath: t.field.canonicalString(), + increment: n.Ae + }; + throw fail(20930, { + transform: t.transform + }); + }(0, e)))), t.precondition.isNone || (n.currentDocument = function __PRIVATE_toPrecondition(e, t) { + return void 0 !== t.updateTime ? { + updateTime: __PRIVATE_toVersion(e, t.updateTime) + } : void 0 !== t.exists ? { + exists: t.exists + } : fail(27497); + }(e, t.precondition)), n; +} + +function __PRIVATE_fromMutation(e, t) { + const n = t.currentDocument ? function __PRIVATE_fromPrecondition(e) { + return void 0 !== e.updateTime ? Precondition.updateTime(__PRIVATE_fromVersion(e.updateTime)) : void 0 !== e.exists ? Precondition.exists(e.exists) : Precondition.none(); + }(t.currentDocument) : Precondition.none(), r = t.updateTransforms ? t.updateTransforms.map((t => function __PRIVATE_fromFieldTransform(e, t) { + let n = null; + if ("setToServerValue" in t) __PRIVATE_hardAssert("REQUEST_TIME" === t.setToServerValue, 16630, { + proto: t + }), n = new __PRIVATE_ServerTimestampTransform; else if ("appendMissingElements" in t) { + const e = t.appendMissingElements.values || []; + n = new __PRIVATE_ArrayUnionTransformOperation(e); + } else if ("removeAllFromArray" in t) { + const e = t.removeAllFromArray.values || []; + n = new __PRIVATE_ArrayRemoveTransformOperation(e); + } else "increment" in t ? n = new __PRIVATE_NumericIncrementTransformOperation(e, t.increment) : fail(16584, { + proto: t + }); + const r = FieldPath$1.fromServerFormat(t.fieldPath); + return new FieldTransform(r, n); + }(e, t))) : []; + if (t.update) { + t.update.name; + const i = fromName(e, t.update.name), s = new ObjectValue({ + mapValue: { + fields: t.update.fields + } + }); + if (t.updateMask) { + const e = function __PRIVATE_fromDocumentMask(e) { + const t = e.fieldPaths || []; + return new FieldMask(t.map((e => FieldPath$1.fromServerFormat(e)))); + }(t.updateMask); + return new __PRIVATE_PatchMutation(i, s, e, n, r); + } + return new __PRIVATE_SetMutation(i, s, n, r); + } + if (t.delete) { + const r = fromName(e, t.delete); + return new __PRIVATE_DeleteMutation(r, n); + } + if (t.verify) { + const r = fromName(e, t.verify); + return new __PRIVATE_VerifyMutation(r, n); + } + return fail(1463, { + proto: t + }); +} + +function __PRIVATE_fromWriteResults(e, t) { + return e && e.length > 0 ? (__PRIVATE_hardAssert(void 0 !== t, 14353), e.map((e => function __PRIVATE_fromWriteResult(e, t) { + // NOTE: Deletes don't have an updateTime. + let n = e.updateTime ? __PRIVATE_fromVersion(e.updateTime) : __PRIVATE_fromVersion(t); + return n.isEqual(SnapshotVersion.min()) && ( + // The Firestore Emulator currently returns an update time of 0 for + // deletes of non-existing documents (rather than null). This breaks the + // test "get deleted doc while offline with source=cache" as NoDocuments + // with version 0 are filtered by IndexedDb's RemoteDocumentCache. + // TODO(#2149): Remove this when Emulator is fixed + n = __PRIVATE_fromVersion(t)), new MutationResult(n, e.transformResults || []); + }(e, t)))) : []; +} + +function __PRIVATE_toDocumentsTarget(e, t) { + return { + documents: [ __PRIVATE_toQueryPath(e, t.path) ] + }; +} + +function __PRIVATE_toQueryTarget(e, t) { + // Dissect the path into parent, collectionId, and optional key filter. + const n = { + structuredQuery: {} + }, r = t.path; + let i; + null !== t.collectionGroup ? (i = r, n.structuredQuery.from = [ { + collectionId: t.collectionGroup, + allDescendants: !0 + } ]) : (i = r.popLast(), n.structuredQuery.from = [ { + collectionId: r.lastSegment() + } ]), n.parent = __PRIVATE_toQueryPath(e, i); + const s = function __PRIVATE_toFilters(e) { + if (0 === e.length) return; + return __PRIVATE_toFilter(CompositeFilter.create(e, "and" /* CompositeOperator.AND */)); + }(t.filters); + s && (n.structuredQuery.where = s); + const o = function __PRIVATE_toOrder(e) { + if (0 === e.length) return; + return e.map((e => + // visible for testing + function __PRIVATE_toPropertyOrder(e) { + return { + field: __PRIVATE_toFieldPathReference(e.field), + direction: __PRIVATE_toDirection(e.dir) + }; + }(e))); + }(t.orderBy); + o && (n.structuredQuery.orderBy = o); + const _ = __PRIVATE_toInt32Proto(e, t.limit); + return null !== _ && (n.structuredQuery.limit = _), t.startAt && (n.structuredQuery.startAt = function __PRIVATE_toStartAtCursor(e) { + return { + before: e.inclusive, + values: e.position + }; + }(t.startAt)), t.endAt && (n.structuredQuery.endAt = function __PRIVATE_toEndAtCursor(e) { + return { + before: !e.inclusive, + values: e.position + }; + }(t.endAt)), { + ft: n, + parent: i + }; +} + +function __PRIVATE_toRunAggregationQueryRequest(e, t, n, r) { + const {ft: i, parent: s} = __PRIVATE_toQueryTarget(e, t), o = {}, _ = []; + let a = 0; + return n.forEach((e => { + // Map all client-side aliases to a unique short-form + // alias. This avoids issues with client-side aliases that + // exceed the 1500-byte string size limit. + const t = r ? e.alias : "aggregate_" + a++; + o[t] = e.alias, "count" === e.aggregateType ? _.push({ + alias: t, + count: {} + }) : "avg" === e.aggregateType ? _.push({ + alias: t, + avg: { + field: __PRIVATE_toFieldPathReference(e.fieldPath) + } + }) : "sum" === e.aggregateType && _.push({ + alias: t, + sum: { + field: __PRIVATE_toFieldPathReference(e.fieldPath) + } + }); + })), { + request: { + structuredAggregationQuery: { + aggregations: _, + structuredQuery: i.structuredQuery + }, + parent: i.parent + }, + gt: o, + parent: s + }; +} + +function __PRIVATE_convertQueryTargetToQuery(e) { + let t = __PRIVATE_fromQueryPath(e.parent); + const n = e.structuredQuery, r = n.from ? n.from.length : 0; + let i = null; + if (r > 0) { + __PRIVATE_hardAssert(1 === r, 65062); + const e = n.from[0]; + e.allDescendants ? i = e.collectionId : t = t.child(e.collectionId); + } + let s = []; + n.where && (s = function __PRIVATE_fromFilters(e) { + const t = __PRIVATE_fromFilter(e); + if (t instanceof CompositeFilter && __PRIVATE_compositeFilterIsFlatConjunction(t)) return t.getFilters(); + return [ t ]; + }(n.where)); + let o = []; + n.orderBy && (o = function __PRIVATE_fromOrder(e) { + return e.map((e => function __PRIVATE_fromPropertyOrder(e) { + return new OrderBy(__PRIVATE_fromFieldPathReference(e.field), + // visible for testing + function __PRIVATE_fromDirection(e) { + switch (e) { + case "ASCENDING": + return "asc" /* Direction.ASCENDING */; + + case "DESCENDING": + return "desc" /* Direction.DESCENDING */; + + default: + return; + } + } + // visible for testing + (e.direction)); + } + // visible for testing + (e))); + }(n.orderBy)); + let _ = null; + n.limit && (_ = function __PRIVATE_fromInt32Proto(e) { + let t; + return t = "object" == typeof e ? e.value : e, __PRIVATE_isNullOrUndefined(t) ? null : t; + }(n.limit)); + let a = null; + n.startAt && (a = function __PRIVATE_fromStartAtCursor(e) { + const t = !!e.before, n = e.values || []; + return new Bound(n, t); + }(n.startAt)); + let u = null; + return n.endAt && (u = function __PRIVATE_fromEndAtCursor(e) { + const t = !e.before, n = e.values || []; + return new Bound(n, t); + } + // visible for testing + (n.endAt)), __PRIVATE_newQuery(t, i, o, s, _, "F" /* LimitType.First */ , a, u); +} + +function __PRIVATE_toListenRequestLabels(e, t) { + const n = function __PRIVATE_toLabel(e) { + switch (e) { + case "TargetPurposeListen" /* TargetPurpose.Listen */ : + return null; + + case "TargetPurposeExistenceFilterMismatch" /* TargetPurpose.ExistenceFilterMismatch */ : + return "existence-filter-mismatch"; + + case "TargetPurposeExistenceFilterMismatchBloom" /* TargetPurpose.ExistenceFilterMismatchBloom */ : + return "existence-filter-mismatch-bloom"; + + case "TargetPurposeLimboResolution" /* TargetPurpose.LimboResolution */ : + return "limbo-document"; + + default: + return fail(28987, { + purpose: e + }); + } + }(t.purpose); + return null == n ? null : { + "goog-listen-tags": n + }; +} + +function __PRIVATE_fromFilter(e) { + return void 0 !== e.unaryFilter ? function __PRIVATE_fromUnaryFilter(e) { + switch (e.unaryFilter.op) { + case "IS_NAN": + const t = __PRIVATE_fromFieldPathReference(e.unaryFilter.field); + return FieldFilter.create(t, "==" /* Operator.EQUAL */ , { + doubleValue: NaN + }); + + case "IS_NULL": + const n = __PRIVATE_fromFieldPathReference(e.unaryFilter.field); + return FieldFilter.create(n, "==" /* Operator.EQUAL */ , { + nullValue: "NULL_VALUE" + }); + + case "IS_NOT_NAN": + const r = __PRIVATE_fromFieldPathReference(e.unaryFilter.field); + return FieldFilter.create(r, "!=" /* Operator.NOT_EQUAL */ , { + doubleValue: NaN + }); + + case "IS_NOT_NULL": + const i = __PRIVATE_fromFieldPathReference(e.unaryFilter.field); + return FieldFilter.create(i, "!=" /* Operator.NOT_EQUAL */ , { + nullValue: "NULL_VALUE" + }); + + case "OPERATOR_UNSPECIFIED": + return fail(61313); + + default: + return fail(60726); + } + }(e) : void 0 !== e.fieldFilter ? function __PRIVATE_fromFieldFilter(e) { + return FieldFilter.create(__PRIVATE_fromFieldPathReference(e.fieldFilter.field), function __PRIVATE_fromOperatorName(e) { + switch (e) { + case "EQUAL": + return "==" /* Operator.EQUAL */; + + case "NOT_EQUAL": + return "!=" /* Operator.NOT_EQUAL */; + + case "GREATER_THAN": + return ">" /* Operator.GREATER_THAN */; + + case "GREATER_THAN_OR_EQUAL": + return ">=" /* Operator.GREATER_THAN_OR_EQUAL */; + + case "LESS_THAN": + return "<" /* Operator.LESS_THAN */; + + case "LESS_THAN_OR_EQUAL": + return "<=" /* Operator.LESS_THAN_OR_EQUAL */; + + case "ARRAY_CONTAINS": + return "array-contains" /* Operator.ARRAY_CONTAINS */; + + case "IN": + return "in" /* Operator.IN */; + + case "NOT_IN": + return "not-in" /* Operator.NOT_IN */; + + case "ARRAY_CONTAINS_ANY": + return "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */; + + case "OPERATOR_UNSPECIFIED": + return fail(58110); + + default: + return fail(50506); + } + }(e.fieldFilter.op), e.fieldFilter.value); + }(e) : void 0 !== e.compositeFilter ? function __PRIVATE_fromCompositeFilter(e) { + return CompositeFilter.create(e.compositeFilter.filters.map((e => __PRIVATE_fromFilter(e))), function __PRIVATE_fromCompositeOperatorName(e) { + switch (e) { + case "AND": + return "and" /* CompositeOperator.AND */; + + case "OR": + return "or" /* CompositeOperator.OR */; + + default: + return fail(1026); + } + }(e.compositeFilter.op)); + }(e) : fail(30097, { + filter: e + }); +} + +function __PRIVATE_toDirection(e) { + return vt[e]; +} + +function __PRIVATE_toOperatorName(e) { + return Ft[e]; +} + +function __PRIVATE_toCompositeOperatorName(e) { + return Mt[e]; +} + +function __PRIVATE_toFieldPathReference(e) { + return { + fieldPath: e.canonicalString() + }; +} + +function __PRIVATE_fromFieldPathReference(e) { + return FieldPath$1.fromServerFormat(e.fieldPath); +} + +function __PRIVATE_toFilter(e) { + return e instanceof FieldFilter ? function __PRIVATE_toUnaryOrFieldFilter(e) { + if ("==" /* Operator.EQUAL */ === e.op) { + if (__PRIVATE_isNanValue(e.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(e.field), + op: "IS_NAN" + } + }; + if (__PRIVATE_isNullValue(e.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(e.field), + op: "IS_NULL" + } + }; + } else if ("!=" /* Operator.NOT_EQUAL */ === e.op) { + if (__PRIVATE_isNanValue(e.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(e.field), + op: "IS_NOT_NAN" + } + }; + if (__PRIVATE_isNullValue(e.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(e.field), + op: "IS_NOT_NULL" + } + }; + } + return { + fieldFilter: { + field: __PRIVATE_toFieldPathReference(e.field), + op: __PRIVATE_toOperatorName(e.op), + value: e.value + } + }; + }(e) : e instanceof CompositeFilter ? function __PRIVATE_toCompositeFilter(e) { + const t = e.getFilters().map((e => __PRIVATE_toFilter(e))); + if (1 === t.length) return t[0]; + return { + compositeFilter: { + op: __PRIVATE_toCompositeOperatorName(e.op), + filters: t + } + }; + }(e) : fail(54877, { + filter: e + }); +} + +function __PRIVATE_toDocumentMask(e) { + const t = []; + return e.fields.forEach((e => t.push(e.canonicalString()))), { + fieldPaths: t + }; +} + +function __PRIVATE_isValidResourceName(e) { + // Resource names have at least 4 components (project ID, database ID) + return e.length >= 4 && "projects" === e.get(0) && "databases" === e.get(2); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable set of metadata that the local store tracks for each target. + */ class TargetData { + constructor( + /** The target being listened to. */ + e, + /** + * The target ID to which the target corresponds; Assigned by the + * LocalStore for user listens and by the SyncEngine for limbo watches. + */ + t, + /** The purpose of the target. */ + n, + /** + * The sequence number of the last transaction during which this target data + * was modified. + */ + r, + /** The latest snapshot version seen for this target. */ + i = SnapshotVersion.min() + /** + * The maximum snapshot version at which the associated view + * contained no limbo documents. + */ , s = SnapshotVersion.min() + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ , o = ByteString.EMPTY_BYTE_STRING + /** + * The number of documents that last matched the query at the resume token or + * read time. Documents are counted only when making a listen request with + * resume token or read time, otherwise, keep it null. + */ , _ = null) { + this.target = e, this.targetId = t, this.purpose = n, this.sequenceNumber = r, this.snapshotVersion = i, + this.lastLimboFreeSnapshotVersion = s, this.resumeToken = o, this.expectedCount = _; + } + /** Creates a new target data instance with an updated sequence number. */ withSequenceNumber(e) { + return new TargetData(this.target, this.targetId, this.purpose, e, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, this.expectedCount); + } + /** + * Creates a new target data instance with an updated resume token and + * snapshot version. + */ withResumeToken(e, t) { + return new TargetData(this.target, this.targetId, this.purpose, this.sequenceNumber, t, this.lastLimboFreeSnapshotVersion, e, + /* expectedCount= */ null); + } + /** + * Creates a new target data instance with an updated expected count. + */ withExpectedCount(e) { + return new TargetData(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, this.lastLimboFreeSnapshotVersion, this.resumeToken, e); + } + /** + * Creates a new target data instance with an updated last limbo free + * snapshot version number. + */ withLastLimboFreeSnapshotVersion(e) { + return new TargetData(this.target, this.targetId, this.purpose, this.sequenceNumber, this.snapshotVersion, e, this.resumeToken, this.expectedCount); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Serializer for values stored in the LocalStore. */ class __PRIVATE_LocalSerializer { + constructor(e) { + this.yt = e; + } +} + +/** Decodes a remote document from storage locally to a Document. */ function __PRIVATE_fromDbRemoteDocument(e, t) { + let n; + if (t.document) n = __PRIVATE_fromDocument(e.yt, t.document, !!t.hasCommittedMutations); else if (t.noDocument) { + const e = DocumentKey.fromSegments(t.noDocument.path), r = __PRIVATE_fromDbTimestamp(t.noDocument.readTime); + n = MutableDocument.newNoDocument(e, r), t.hasCommittedMutations && n.setHasCommittedMutations(); + } else { + if (!t.unknownDocument) return fail(56709); + { + const e = DocumentKey.fromSegments(t.unknownDocument.path), r = __PRIVATE_fromDbTimestamp(t.unknownDocument.version); + n = MutableDocument.newUnknownDocument(e, r); + } + } + return t.readTime && n.setReadTime(function __PRIVATE_fromDbTimestampKey(e) { + const t = new Timestamp(e[0], e[1]); + return SnapshotVersion.fromTimestamp(t); + }(t.readTime)), n; +} + +/** Encodes a document for storage locally. */ function __PRIVATE_toDbRemoteDocument(e, t) { + const n = t.key, r = { + prefixPath: n.getCollectionPath().popLast().toArray(), + collectionGroup: n.collectionGroup, + documentId: n.path.lastSegment(), + readTime: __PRIVATE_toDbTimestampKey(t.readTime), + hasCommittedMutations: t.hasCommittedMutations + }; + if (t.isFoundDocument()) r.document = function __PRIVATE_toDocument(e, t) { + return { + name: __PRIVATE_toName(e, t.key), + fields: t.data.value.mapValue.fields, + updateTime: toTimestamp(e, t.version.toTimestamp()), + createTime: toTimestamp(e, t.createTime.toTimestamp()) + }; + }(e.yt, t); else if (t.isNoDocument()) r.noDocument = { + path: n.path.toArray(), + readTime: __PRIVATE_toDbTimestamp(t.version) + }; else { + if (!t.isUnknownDocument()) return fail(57904, { + document: t + }); + r.unknownDocument = { + path: n.path.toArray(), + version: __PRIVATE_toDbTimestamp(t.version) + }; + } + return r; +} + +function __PRIVATE_toDbTimestampKey(e) { + const t = e.toTimestamp(); + return [ t.seconds, t.nanoseconds ]; +} + +function __PRIVATE_toDbTimestamp(e) { + const t = e.toTimestamp(); + return { + seconds: t.seconds, + nanoseconds: t.nanoseconds + }; +} + +function __PRIVATE_fromDbTimestamp(e) { + const t = new Timestamp(e.seconds, e.nanoseconds); + return SnapshotVersion.fromTimestamp(t); +} + +/** Encodes a batch of mutations into a DbMutationBatch for local storage. */ +/** Decodes a DbMutationBatch into a MutationBatch */ +function __PRIVATE_fromDbMutationBatch(e, t) { + const n = (t.baseMutations || []).map((t => __PRIVATE_fromMutation(e.yt, t))); + // Squash old transform mutations into existing patch or set mutations. + // The replacement of representing `transforms` with `update_transforms` + // on the SDK means that old `transform` mutations stored in IndexedDB need + // to be updated to `update_transforms`. + // TODO(b/174608374): Remove this code once we perform a schema migration. + for (let e = 0; e < t.mutations.length - 1; ++e) { + const n = t.mutations[e]; + if (e + 1 < t.mutations.length && void 0 !== t.mutations[e + 1].transform) { + const r = t.mutations[e + 1]; + n.updateTransforms = r.transform.fieldTransforms, t.mutations.splice(e + 1, 1), + ++e; + } + } + const r = t.mutations.map((t => __PRIVATE_fromMutation(e.yt, t))), i = Timestamp.fromMillis(t.localWriteTimeMs); + return new MutationBatch(t.batchId, i, n, r); +} + +/** Decodes a DbTarget into TargetData */ function __PRIVATE_fromDbTarget(e) { + const t = __PRIVATE_fromDbTimestamp(e.readTime), n = void 0 !== e.lastLimboFreeSnapshotVersion ? __PRIVATE_fromDbTimestamp(e.lastLimboFreeSnapshotVersion) : SnapshotVersion.min(); + let r; + return r = + /** + * A helper function for figuring out what kind of query has been stored. + */ + function __PRIVATE_isDocumentQuery(e) { + return void 0 !== e.documents; + } + /** Encodes a DbBundle to a BundleMetadata object. */ (e.query) ? function __PRIVATE_fromDocumentsTarget(e) { + const t = e.documents.length; + return __PRIVATE_hardAssert(1 === t, 1966, { + count: t + }), __PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(__PRIVATE_fromQueryPath(e.documents[0]))); + }(e.query) : function __PRIVATE_fromQueryTarget(e) { + return __PRIVATE_queryToTarget(__PRIVATE_convertQueryTargetToQuery(e)); + }(e.query), new TargetData(r, e.targetId, "TargetPurposeListen" /* TargetPurpose.Listen */ , e.lastListenSequenceNumber, t, n, ByteString.fromBase64String(e.resumeToken)); +} + +/** Encodes TargetData into a DbTarget for storage locally. */ function __PRIVATE_toDbTarget(e, t) { + const n = __PRIVATE_toDbTimestamp(t.snapshotVersion), r = __PRIVATE_toDbTimestamp(t.lastLimboFreeSnapshotVersion); + let i; + i = __PRIVATE_targetIsDocumentTarget(t.target) ? __PRIVATE_toDocumentsTarget(e.yt, t.target) : __PRIVATE_toQueryTarget(e.yt, t.target).ft; + // We can't store the resumeToken as a ByteString in IndexedDb, so we + // convert it to a base64 string for storage. + const s = t.resumeToken.toBase64(); + // lastListenSequenceNumber is always 0 until we do real GC. + return { + targetId: t.targetId, + canonicalId: __PRIVATE_canonifyTarget(t.target), + readTime: n, + resumeToken: s, + lastListenSequenceNumber: t.sequenceNumber, + lastLimboFreeSnapshotVersion: r, + query: i + }; +} + +/** + * Encodes a `BundledQuery` from bundle proto to a Query object. + * + * This reconstructs the original query used to build the bundle being loaded, + * including features exists only in SDKs (for example: limit-to-last). + */ +function __PRIVATE_fromBundledQuery(e) { + const t = __PRIVATE_convertQueryTargetToQuery({ + parent: e.parent, + structuredQuery: e.structuredQuery + }); + return "LAST" === e.limitType ? __PRIVATE_queryWithLimit(t, t.limit, "L" /* LimitType.Last */) : t; +} + +/** Encodes a NamedQuery proto object to a NamedQuery model object. */ +/** Encodes a DbDocumentOverlay object to an Overlay model object. */ +function __PRIVATE_fromDbDocumentOverlay(e, t) { + return new Overlay(t.largestBatchId, __PRIVATE_fromMutation(e.yt, t.overlayMutation)); +} + +/** Decodes an Overlay model object into a DbDocumentOverlay object. */ +/** + * Returns the DbDocumentOverlayKey corresponding to the given user and + * document key. + */ +function __PRIVATE_toDbDocumentOverlayKey(e, t) { + const n = t.path.lastSegment(); + return [ e, __PRIVATE_encodeResourcePath(t.path.popLast()), n ]; +} + +function __PRIVATE_toDbIndexState(e, t, n, r) { + return { + indexId: e, + uid: t, + sequenceNumber: n, + readTime: __PRIVATE_toDbTimestamp(r.readTime), + documentKey: __PRIVATE_encodeResourcePath(r.documentKey.path), + largestBatchId: r.largestBatchId + }; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_IndexedDbBundleCache { + getBundleMetadata(e, t) { + return __PRIVATE_bundlesStore(e).get(t).next((e => { + if (e) return function __PRIVATE_fromDbBundle(e) { + return { + id: e.bundleId, + createTime: __PRIVATE_fromDbTimestamp(e.createTime), + version: e.version + }; + } + /** Encodes a BundleMetadata to a DbBundle. */ (e); + })); + } + saveBundleMetadata(e, t) { + return __PRIVATE_bundlesStore(e).put(function __PRIVATE_toDbBundle(e) { + return { + bundleId: e.id, + createTime: __PRIVATE_toDbTimestamp(__PRIVATE_fromVersion(e.createTime)), + version: e.version + }; + } + /** Encodes a DbNamedQuery to a NamedQuery. */ (t)); + } + getNamedQuery(e, t) { + return __PRIVATE_namedQueriesStore(e).get(t).next((e => { + if (e) return function __PRIVATE_fromDbNamedQuery(e) { + return { + name: e.name, + query: __PRIVATE_fromBundledQuery(e.bundledQuery), + readTime: __PRIVATE_fromDbTimestamp(e.readTime) + }; + } + /** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */ (e); + })); + } + saveNamedQuery(e, t) { + return __PRIVATE_namedQueriesStore(e).put(function __PRIVATE_toDbNamedQuery(e) { + return { + name: e.name, + readTime: __PRIVATE_toDbTimestamp(__PRIVATE_fromVersion(e.readTime)), + bundledQuery: e.bundledQuery + }; + }(t)); + } +} + +/** + * Helper to get a typed SimpleDbStore for the bundles object store. + */ function __PRIVATE_bundlesStore(e) { + return __PRIVATE_getStore(e, Ce); +} + +/** + * Helper to get a typed SimpleDbStore for the namedQueries object store. + */ function __PRIVATE_namedQueriesStore(e) { + return __PRIVATE_getStore(e, Fe); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Implementation of DocumentOverlayCache using IndexedDb. + */ class __PRIVATE_IndexedDbDocumentOverlayCache { + /** + * @param serializer - The document serializer. + * @param userId - The userId for which we are accessing overlays. + */ + constructor(e, t) { + this.serializer = e, this.userId = t; + } + static wt(e, t) { + const n = t.uid || ""; + return new __PRIVATE_IndexedDbDocumentOverlayCache(e, n); + } + getOverlay(e, t) { + return __PRIVATE_documentOverlayStore(e).get(__PRIVATE_toDbDocumentOverlayKey(this.userId, t)).next((e => e ? __PRIVATE_fromDbDocumentOverlay(this.serializer, e) : null)); + } + getOverlays(e, t) { + const n = __PRIVATE_newOverlayMap(); + return PersistencePromise.forEach(t, (t => this.getOverlay(e, t).next((e => { + null !== e && n.set(t, e); + })))).next((() => n)); + } + saveOverlays(e, t, n) { + const r = []; + return n.forEach(((n, i) => { + const s = new Overlay(t, i); + r.push(this.St(e, s)); + })), PersistencePromise.waitFor(r); + } + removeOverlaysForBatchId(e, t, n) { + const r = new Set; + // Get the set of unique collection paths. + t.forEach((e => r.add(__PRIVATE_encodeResourcePath(e.getCollectionPath())))); + const i = []; + return r.forEach((t => { + const r = IDBKeyRange.bound([ this.userId, t, n ], [ this.userId, t, n + 1 ], + /*lowerOpen=*/ !1, + /*upperOpen=*/ !0); + i.push(__PRIVATE_documentOverlayStore(e).Z(je, r)); + })), PersistencePromise.waitFor(i); + } + getOverlaysForCollection(e, t, n) { + const r = __PRIVATE_newOverlayMap(), i = __PRIVATE_encodeResourcePath(t), s = IDBKeyRange.bound([ this.userId, i, n ], [ this.userId, i, Number.POSITIVE_INFINITY ], + /*lowerOpen=*/ !0); + return __PRIVATE_documentOverlayStore(e).J(je, s).next((e => { + for (const t of e) { + const e = __PRIVATE_fromDbDocumentOverlay(this.serializer, t); + r.set(e.getKey(), e); + } + return r; + })); + } + getOverlaysForCollectionGroup(e, t, n, r) { + const i = __PRIVATE_newOverlayMap(); + let s; + // We want batch IDs larger than `sinceBatchId`, and so the lower bound + // is not inclusive. + const o = IDBKeyRange.bound([ this.userId, t, n ], [ this.userId, t, Number.POSITIVE_INFINITY ], + /*lowerOpen=*/ !0); + return __PRIVATE_documentOverlayStore(e).ee({ + index: He, + range: o + }, ((e, t, n) => { + // We do not want to return partial batch overlays, even if the size + // of the result set exceeds the given `count` argument. Therefore, we + // continue to aggregate results even after the result size exceeds + // `count` if there are more overlays from the `currentBatchId`. + const o = __PRIVATE_fromDbDocumentOverlay(this.serializer, t); + i.size() < r || o.largestBatchId === s ? (i.set(o.getKey(), o), s = o.largestBatchId) : n.done(); + })).next((() => i)); + } + St(e, t) { + return __PRIVATE_documentOverlayStore(e).put(function __PRIVATE_toDbDocumentOverlay(e, t, n) { + const [r, i, s] = __PRIVATE_toDbDocumentOverlayKey(t, n.mutation.key); + return { + userId: t, + collectionPath: i, + documentId: s, + collectionGroup: n.mutation.key.getCollectionGroup(), + largestBatchId: n.largestBatchId, + overlayMutation: toMutation(e.yt, n.mutation) + }; + }(this.serializer, this.userId, t)); + } +} + +/** + * Helper to get a typed SimpleDbStore for the document overlay object store. + */ function __PRIVATE_documentOverlayStore(e) { + return __PRIVATE_getStore(e, Ge); +} + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_IndexedDbGlobalsCache { + bt(e) { + return __PRIVATE_getStore(e, Ze); + } + getSessionToken(e) { + return this.bt(e).get("sessionToken").next((e => { + const t = e?.value; + return t ? ByteString.fromUint8Array(t) : ByteString.EMPTY_BYTE_STRING; + })); + } + setSessionToken(e, t) { + return this.bt(e).put({ + name: "sessionToken", + value: t.toUint8Array() + }); + } +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Note: This code is copied from the backend. Code that is not used by +// Firestore was removed. +/** Firestore index value writer. */ +class __PRIVATE_FirestoreIndexValueWriter { + constructor() {} + // The write methods below short-circuit writing terminators for values + // containing a (terminating) truncated value. + // As an example, consider the resulting encoding for: + // ["bar", [2, "foo"]] -> (STRING, "bar", TERM, ARRAY, NUMBER, 2, STRING, "foo", TERM, TERM, TERM) + // ["bar", [2, truncated("foo")]] -> (STRING, "bar", TERM, ARRAY, NUMBER, 2, STRING, "foo", TRUNC) + // ["bar", truncated(["foo"])] -> (STRING, "bar", TERM, ARRAY. STRING, "foo", TERM, TRUNC) + /** Writes an index value. */ + Dt(e, t) { + this.Ct(e, t), + // Write separator to split index values + // (see go/firestore-storage-format#encodings). + t.vt(); + } + Ct(e, t) { + if ("nullValue" in e) this.Ft(t, 5); else if ("booleanValue" in e) this.Ft(t, 10), + t.Mt(e.booleanValue ? 1 : 0); else if ("integerValue" in e) this.Ft(t, 15), t.Mt(__PRIVATE_normalizeNumber(e.integerValue)); else if ("doubleValue" in e) { + const n = __PRIVATE_normalizeNumber(e.doubleValue); + isNaN(n) ? this.Ft(t, 13) : (this.Ft(t, 15), __PRIVATE_isNegativeZero(n) ? + // -0.0, 0 and 0.0 are all considered the same + t.Mt(0) : t.Mt(n)); + } else if ("timestampValue" in e) { + let n = e.timestampValue; + this.Ft(t, 20), "string" == typeof n && (n = __PRIVATE_normalizeTimestamp(n)), t.xt(`${n.seconds || ""}`), + t.Mt(n.nanos || 0); + } else if ("stringValue" in e) this.Ot(e.stringValue, t), this.Nt(t); else if ("bytesValue" in e) this.Ft(t, 30), + t.Bt(__PRIVATE_normalizeByteString(e.bytesValue)), this.Nt(t); else if ("referenceValue" in e) this.Lt(e.referenceValue, t); else if ("geoPointValue" in e) { + const n = e.geoPointValue; + this.Ft(t, 45), t.Mt(n.latitude || 0), t.Mt(n.longitude || 0); + } else "mapValue" in e ? __PRIVATE_isMaxValue(e) ? this.Ft(t, Number.MAX_SAFE_INTEGER) : __PRIVATE_isVectorValue(e) ? this.kt(e.mapValue, t) : (this.qt(e.mapValue, t), + this.Nt(t)) : "arrayValue" in e ? (this.Qt(e.arrayValue, t), this.Nt(t)) : fail(19022, { + $t: e + }); + } + Ot(e, t) { + this.Ft(t, 25), this.Ut(e, t); + } + Ut(e, t) { + t.xt(e); + } + qt(e, t) { + const n = e.fields || {}; + this.Ft(t, 55); + for (const e of Object.keys(n)) this.Ot(e, t), this.Ct(n[e], t); + } + kt(e, t) { + const n = e.fields || {}; + this.Ft(t, 53); + // Vectors sort first by length + const r = Rt, i = n[r].arrayValue?.values?.length || 0; + this.Ft(t, 15), t.Mt(__PRIVATE_normalizeNumber(i)), + // Vectors then sort by position value + this.Ot(r, t), this.Ct(n[r], t); + } + Qt(e, t) { + const n = e.values || []; + this.Ft(t, 50); + for (const e of n) this.Ct(e, t); + } + Lt(e, t) { + this.Ft(t, 37); + DocumentKey.fromName(e).path.forEach((e => { + this.Ft(t, 60), this.Ut(e, t); + })); + } + Ft(e, t) { + e.Mt(t); + } + Nt(e) { + // While the SDK does not implement truncation, the truncation marker is + // used to terminate all variable length values (which are strings, bytes, + // references, arrays and maps). + e.Mt(2); + } +} + +__PRIVATE_FirestoreIndexValueWriter.Kt = new __PRIVATE_FirestoreIndexValueWriter; + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law | agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES | CONDITIONS OF ANY KIND, either express | implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** These constants are taken from the backend. */ +const xt = 255; + +/** + * Counts the number of zeros in a byte. + * + * Visible for testing. + */ +function __PRIVATE_numberOfLeadingZerosInByte(e) { + if (0 === e) return 8; + let t = 0; + return e >> 4 || ( + // Test if the first four bits are zero. + t += 4, e <<= 4), e >> 6 || ( + // Test if the first two (or next two) bits are zero. + t += 2, e <<= 2), e >> 7 || ( + // Test if the remaining bit is zero. + t += 1), t; +} + +/** Counts the number of leading zeros in the given byte array. */ +/** + * Returns the number of bytes required to store "value". Leading zero bytes + * are skipped. + */ +function __PRIVATE_unsignedNumLength(e) { + // This is just the number of bytes for the unsigned representation of the number. + const t = 64 - function __PRIVATE_numberOfLeadingZeros(e) { + let t = 0; + for (let n = 0; n < 8; ++n) { + const r = __PRIVATE_numberOfLeadingZerosInByte(255 & e[n]); + if (t += r, 8 !== r) break; + } + return t; + }(e); + return Math.ceil(t / 8); +} + +/** + * OrderedCodeWriter is a minimal-allocation implementation of the writing + * behavior defined by the backend. + * + * The code is ported from its Java counterpart. + */ class __PRIVATE_OrderedCodeWriter { + constructor() { + this.buffer = new Uint8Array(1024), this.position = 0; + } + Wt(e) { + const t = e[Symbol.iterator](); + let n = t.next(); + for (;!n.done; ) this.Gt(n.value), n = t.next(); + this.zt(); + } + jt(e) { + const t = e[Symbol.iterator](); + let n = t.next(); + for (;!n.done; ) this.Jt(n.value), n = t.next(); + this.Ht(); + } + /** Writes utf8 bytes into this byte sequence, ascending. */ Yt(e) { + for (const t of e) { + const e = t.charCodeAt(0); + if (e < 128) this.Gt(e); else if (e < 2048) this.Gt(960 | e >>> 6), this.Gt(128 | 63 & e); else if (t < "\ud800" || "\udbff" < t) this.Gt(480 | e >>> 12), + this.Gt(128 | 63 & e >>> 6), this.Gt(128 | 63 & e); else { + const e = t.codePointAt(0); + this.Gt(240 | e >>> 18), this.Gt(128 | 63 & e >>> 12), this.Gt(128 | 63 & e >>> 6), + this.Gt(128 | 63 & e); + } + } + this.zt(); + } + /** Writes utf8 bytes into this byte sequence, descending */ Zt(e) { + for (const t of e) { + const e = t.charCodeAt(0); + if (e < 128) this.Jt(e); else if (e < 2048) this.Jt(960 | e >>> 6), this.Jt(128 | 63 & e); else if (t < "\ud800" || "\udbff" < t) this.Jt(480 | e >>> 12), + this.Jt(128 | 63 & e >>> 6), this.Jt(128 | 63 & e); else { + const e = t.codePointAt(0); + this.Jt(240 | e >>> 18), this.Jt(128 | 63 & e >>> 12), this.Jt(128 | 63 & e >>> 6), + this.Jt(128 | 63 & e); + } + } + this.Ht(); + } + Xt(e) { + // Values are encoded with a single byte length prefix, followed by the + // actual value in big-endian format with leading 0 bytes dropped. + const t = this.en(e), n = __PRIVATE_unsignedNumLength(t); + this.tn(1 + n), this.buffer[this.position++] = 255 & n; + // Write the length + for (let e = t.length - n; e < t.length; ++e) this.buffer[this.position++] = 255 & t[e]; + } + nn(e) { + // Values are encoded with a single byte length prefix, followed by the + // inverted value in big-endian format with leading 0 bytes dropped. + const t = this.en(e), n = __PRIVATE_unsignedNumLength(t); + this.tn(1 + n), this.buffer[this.position++] = ~(255 & n); + // Write the length + for (let e = t.length - n; e < t.length; ++e) this.buffer[this.position++] = ~(255 & t[e]); + } + /** + * Writes the "infinity" byte sequence that sorts after all other byte + * sequences written in ascending order. + */ rn() { + this.sn(xt), this.sn(255); + } + /** + * Writes the "infinity" byte sequence that sorts before all other byte + * sequences written in descending order. + */ _n() { + this.an(xt), this.an(255); + } + /** + * Resets the buffer such that it is the same as when it was newly + * constructed. + */ reset() { + this.position = 0; + } + seed(e) { + this.tn(e.length), this.buffer.set(e, this.position), this.position += e.length; + } + /** Makes a copy of the encoded bytes in this buffer. */ un() { + return this.buffer.slice(0, this.position); + } + /** + * Encodes `val` into an encoding so that the order matches the IEEE 754 + * floating-point comparison results with the following exceptions: + * -0.0 < 0.0 + * all non-NaN < NaN + * NaN = NaN + */ en(e) { + const t = + /** Converts a JavaScript number to a byte array (using big endian encoding). */ + function __PRIVATE_doubleToLongBits(e) { + const t = new DataView(new ArrayBuffer(8)); + return t.setFloat64(0, e, /* littleEndian= */ !1), new Uint8Array(t.buffer); + }(e), n = !!(128 & t[0]); + // Check if the first bit is set. We use a bit mask since value[0] is + // encoded as a number from 0 to 255. + // Revert the two complement to get natural ordering + t[0] ^= n ? 255 : 128; + for (let e = 1; e < t.length; ++e) t[e] ^= n ? 255 : 0; + return t; + } + /** Writes a single byte ascending to the buffer. */ Gt(e) { + const t = 255 & e; + 0 === t ? (this.sn(0), this.sn(255)) : t === xt ? (this.sn(xt), this.sn(0)) : this.sn(t); + } + /** Writes a single byte descending to the buffer. */ Jt(e) { + const t = 255 & e; + 0 === t ? (this.an(0), this.an(255)) : t === xt ? (this.an(xt), this.an(0)) : this.an(e); + } + zt() { + this.sn(0), this.sn(1); + } + Ht() { + this.an(0), this.an(1); + } + sn(e) { + this.tn(1), this.buffer[this.position++] = e; + } + an(e) { + this.tn(1), this.buffer[this.position++] = ~e; + } + tn(e) { + const t = e + this.position; + if (t <= this.buffer.length) return; + // Try doubling. + let n = 2 * this.buffer.length; + // Still not big enough? Just allocate the right size. + n < t && (n = t); + // Create the new buffer. + const r = new Uint8Array(n); + r.set(this.buffer), // copy old data + this.buffer = r; + } +} + +class __PRIVATE_AscendingIndexByteEncoder { + constructor(e) { + this.cn = e; + } + Bt(e) { + this.cn.Wt(e); + } + xt(e) { + this.cn.Yt(e); + } + Mt(e) { + this.cn.Xt(e); + } + vt() { + this.cn.rn(); + } +} + +class __PRIVATE_DescendingIndexByteEncoder { + constructor(e) { + this.cn = e; + } + Bt(e) { + this.cn.jt(e); + } + xt(e) { + this.cn.Zt(e); + } + Mt(e) { + this.cn.nn(e); + } + vt() { + this.cn._n(); + } +} + +/** + * Implements `DirectionalIndexByteEncoder` using `OrderedCodeWriter` for the + * actual encoding. + */ class __PRIVATE_IndexByteEncoder { + constructor() { + this.cn = new __PRIVATE_OrderedCodeWriter, this.ln = new __PRIVATE_AscendingIndexByteEncoder(this.cn), + this.hn = new __PRIVATE_DescendingIndexByteEncoder(this.cn); + } + seed(e) { + this.cn.seed(e); + } + Pn(e) { + return 0 /* IndexKind.ASCENDING */ === e ? this.ln : this.hn; + } + un() { + return this.cn.un(); + } + reset() { + this.cn.reset(); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Represents an index entry saved by the SDK in persisted storage. */ class __PRIVATE_IndexEntry { + constructor(e, t, n, r) { + this.Tn = e, this.In = t, this.En = n, this.dn = r; + } + /** + * Returns an IndexEntry entry that sorts immediately after the current + * directional value. + */ An() { + const e = this.dn.length, t = 0 === e || 255 === this.dn[e - 1] ? e + 1 : e, n = new Uint8Array(t); + return n.set(this.dn, 0), t !== e ? n.set([ 0 ], this.dn.length) : ++n[n.length - 1], + new __PRIVATE_IndexEntry(this.Tn, this.In, this.En, n); + } + // Create a representation of the Index Entry as a DbIndexEntry + Rn(e, t, n) { + return { + indexId: this.Tn, + uid: e, + arrayValue: __PRIVATE_encodeKeySafeBytes(this.En), + directionalValue: __PRIVATE_encodeKeySafeBytes(this.dn), + orderedDocumentKey: __PRIVATE_encodeKeySafeBytes(t), + documentKey: n.path.toArray() + }; + } + // Create a representation of the Index Entry as a DbIndexEntryKey + Vn(e, t, n) { + const r = this.Rn(e, t, n); + return [ r.indexId, r.uid, r.arrayValue, r.directionalValue, r.orderedDocumentKey, r.documentKey ]; + } +} + +function __PRIVATE_indexEntryComparator(e, t) { + let n = e.Tn - t.Tn; + return 0 !== n ? n : (n = __PRIVATE_compareByteArrays(e.En, t.En), 0 !== n ? n : (n = __PRIVATE_compareByteArrays(e.dn, t.dn), + 0 !== n ? n : DocumentKey.comparator(e.In, t.In))); +} + +function __PRIVATE_compareByteArrays(e, t) { + for (let n = 0; n < e.length && n < t.length; ++n) { + const r = e[n] - t[n]; + if (0 !== r) return r; + } + return e.length - t.length; +} + +/** + * Workaround for WebKit bug: https://bugs.webkit.org/show_bug.cgi?id=292721 + * Create a key safe representation of Uint8Array values. + * If the browser is detected as Safari or WebKit, then + * the input array will be converted to "sortable byte string". + * Otherwise, the input array will be returned in its original type. + */ function __PRIVATE_encodeKeySafeBytes(e) { + return I() ? + /** + * Encodes a Uint8Array into a "sortable byte string". + * A "sortable byte string" sorts in the same order as the Uint8Array. + * This works because JS string comparison sorts strings based on code points. + */ + function __PRIVATE_encodeUint8ArrayToSortableString(e) { + let t = ""; + for (let n = 0; n < e.length; n++) t += String.fromCharCode(e[n]); + return t; + } + /** + * Decodes a "sortable byte string" back into a Uint8Array. + * A "sortable byte string" is assumed to be created where each character's + * Unicode code point directly corresponds to a single byte value (0-255). + */ (e) : e; +} + +/** + * Reverts the key safe representation of Uint8Array (created by + * encodeKeySafeBytes) to a normal Uint8Array. + */ function __PRIVATE_decodeKeySafeBytes(e) { + return "string" != typeof e ? e : function __PRIVATE_decodeSortableStringToUint8Array(e) { + const t = new Uint8Array(e.length); + for (let n = 0; n < e.length; n++) t[n] = e.charCodeAt(n); + return t; + } + /** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * A light query planner for Firestore. + * + * This class matches a `FieldIndex` against a Firestore Query `Target`. It + * determines whether a given index can be used to serve the specified target. + * + * The following table showcases some possible index configurations: + * + * Query | Index + * ----------------------------------------------------------------------------- + * where('a', '==', 'a').where('b', '==', 'b') | a ASC, b DESC + * where('a', '==', 'a').where('b', '==', 'b') | a ASC + * where('a', '==', 'a').where('b', '==', 'b') | b DESC + * where('a', '>=', 'a').orderBy('a') | a ASC + * where('a', '>=', 'a').orderBy('a', 'desc') | a DESC + * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC, b ASC + * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC + * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS, b ASCENDING + * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS + */ (e); +} + +class __PRIVATE_TargetIndexMatcher { + constructor(e) { + // The inequality filters of the target (if it exists). + // Note: The sort on FieldFilters is not required. Using SortedSet here just to utilize the custom + // comparator. + this.mn = new SortedSet(((e, t) => FieldPath$1.comparator(e.field, t.field))), this.collectionId = null != e.collectionGroup ? e.collectionGroup : e.path.lastSegment(), + this.fn = e.orderBy, this.gn = []; + for (const t of e.filters) { + const e = t; + e.isInequality() ? this.mn = this.mn.add(e) : this.gn.push(e); + } + } + get pn() { + return this.mn.size > 1; + } + /** + * Returns whether the index can be used to serve the TargetIndexMatcher's + * target. + * + * An index is considered capable of serving the target when: + * - The target uses all index segments for its filters and orderBy clauses. + * The target can have additional filter and orderBy clauses, but not + * fewer. + * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also + * have a corresponding `CONTAINS` segment. + * - All directional index segments can be mapped to the target as a series of + * equality filters, a single inequality filter and a series of orderBy + * clauses. + * - The segments that represent the equality filters may appear out of order. + * - The optional segment for the inequality filter must appear after all + * equality segments. + * - The segments that represent that orderBy clause of the target must appear + * in order after all equality and inequality segments. Single orderBy + * clauses cannot be skipped, but a continuous orderBy suffix may be + * omitted. + */ yn(e) { + if (__PRIVATE_hardAssert(e.collectionGroup === this.collectionId, 49279), this.pn) + // Only single inequality is supported for now. + // TODO(Add support for multiple inequality query): b/298441043 + return !1; + // If there is an array element, find a matching filter. + const t = __PRIVATE_fieldIndexGetArraySegment(e); + if (void 0 !== t && !this.wn(t)) return !1; + const n = __PRIVATE_fieldIndexGetDirectionalSegments(e); + let r = new Set, i = 0, s = 0; + // Process all equalities first. Equalities can appear out of order. + for (;i < n.length && this.wn(n[i]); ++i) r = r.add(n[i].fieldPath.canonicalString()); + // If we already have processed all segments, all segments are used to serve + // the equality filters and we do not need to map any segments to the + // target's inequality and orderBy clauses. + if (i === n.length) return !0; + if (this.mn.size > 0) { + // Only a single inequality is currently supported. Get the only entry in the set. + const e = this.mn.getIterator().getNext(); + // If there is an inequality filter and the field was not in one of the + // equality filters above, the next segment must match both the filter + // and the first orderBy clause. + if (!r.has(e.field.canonicalString())) { + const t = n[i]; + if (!this.Sn(e, t) || !this.bn(this.fn[s++], t)) return !1; + } + ++i; + } + // All remaining segments need to represent the prefix of the target's + // orderBy. + for (;i < n.length; ++i) { + const e = n[i]; + if (s >= this.fn.length || !this.bn(this.fn[s++], e)) return !1; + } + return !0; + } + /** + * Returns a full matched field index for this target. Currently multiple + * inequality query is not supported so function returns null. + */ Dn() { + if (this.pn) return null; + // We want to make sure only one segment created for one field. For example, + // in case like a == 3 and a > 2, Index {a ASCENDING} will only be created + // once. + let e = new SortedSet(FieldPath$1.comparator); + const t = []; + for (const n of this.gn) { + if (n.field.isKeyField()) continue; + if ("array-contains" /* Operator.ARRAY_CONTAINS */ === n.op || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === n.op) t.push(new IndexSegment(n.field, 2 /* IndexKind.CONTAINS */)); else { + if (e.has(n.field)) continue; + e = e.add(n.field), t.push(new IndexSegment(n.field, 0 /* IndexKind.ASCENDING */)); + } + } + // Note: We do not explicitly check `this.inequalityFilter` but rather rely + // on the target defining an appropriate "order by" to ensure that the + // required index segment is added. The query engine would reject a query + // with an inequality filter that lacks the required order-by clause. + for (const n of this.fn) + // Stop adding more segments if we see a order-by on key. Typically this + // is the default implicit order-by which is covered in the index_entry + // table as a separate column. If it is not the default order-by, the + // generated index will be missing some segments optimized for order-bys, + // which is probably fine. + n.field.isKeyField() || e.has(n.field) || (e = e.add(n.field), t.push(new IndexSegment(n.field, "asc" /* Direction.ASCENDING */ === n.dir ? 0 /* IndexKind.ASCENDING */ : 1 /* IndexKind.DESCENDING */))); + return new FieldIndex(FieldIndex.UNKNOWN_ID, this.collectionId, t, IndexState.empty()); + } + wn(e) { + for (const t of this.gn) if (this.Sn(t, e)) return !0; + return !1; + } + Sn(e, t) { + if (void 0 === e || !e.field.isEqual(t.fieldPath)) return !1; + const n = "array-contains" /* Operator.ARRAY_CONTAINS */ === e.op || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === e.op; + return 2 /* IndexKind.CONTAINS */ === t.kind === n; + } + bn(e, t) { + return !!e.field.isEqual(t.fieldPath) && (0 /* IndexKind.ASCENDING */ === t.kind && "asc" /* Direction.ASCENDING */ === e.dir || 1 /* IndexKind.DESCENDING */ === t.kind && "desc" /* Direction.DESCENDING */ === e.dir); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provides utility functions that help with boolean logic transformations needed for handling + * complex filters used in queries. + */ +/** + * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in + * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given + * input into a disjunction of equality filters and returns the expanded filter. + */ function __PRIVATE_computeInExpansion(e) { + if (__PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter, 20012), + e instanceof FieldFilter) { + if (e instanceof __PRIVATE_InFilter) { + const t = e.value.arrayValue?.values?.map((t => FieldFilter.create(e.field, "==" /* Operator.EQUAL */ , t))) || []; + return CompositeFilter.create(t, "or" /* CompositeOperator.OR */); + } + // We have reached other kinds of field filters. + return e; + } + // We have a composite filter. + const t = e.filters.map((e => __PRIVATE_computeInExpansion(e))); + return CompositeFilter.create(t, e.op); +} + +/** + * Given a composite filter, returns the list of terms in its disjunctive normal form. + * + *

Each element in the return value is one term of the resulting DNF. For instance: For the + * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list + * with two elements: a composite filter that performs (A && C), and a composite filter that + * performs (B && C). + * + * @param filter the composite filter to calculate DNF transform for. + * @return the terms in the DNF transform. + */ function __PRIVATE_getDnfTerms(e) { + if (0 === e.getFilters().length) return []; + const t = __PRIVATE_computeDistributedNormalForm(__PRIVATE_computeInExpansion(e)); + return __PRIVATE_hardAssert(__PRIVATE_isDisjunctiveNormalForm(t), 7391), __PRIVATE_isSingleFieldFilter(t) || __PRIVATE_isFlatConjunction(t) ? [ t ] : t.getFilters(); +} + +/** Returns true if the given filter is a single field filter. e.g. (a == 10). */ function __PRIVATE_isSingleFieldFilter(e) { + return e instanceof FieldFilter; +} + +/** + * Returns true if the given filter is the conjunction of one or more field filters. e.g. (a == 10 + * && b == 20) + */ function __PRIVATE_isFlatConjunction(e) { + return e instanceof CompositeFilter && __PRIVATE_compositeFilterIsFlatConjunction(e); +} + +/** + * Returns whether or not the given filter is in disjunctive normal form (DNF). + * + *

In boolean logic, a disjunctive normal form (DNF) is a canonical normal form of a logical + * formula consisting of a disjunction of conjunctions; it can also be described as an OR of ANDs. + * + *

For more info, visit: https://en.wikipedia.org/wiki/Disjunctive_normal_form + */ function __PRIVATE_isDisjunctiveNormalForm(e) { + return __PRIVATE_isSingleFieldFilter(e) || __PRIVATE_isFlatConjunction(e) || + /** + * Returns true if the given filter is the disjunction of one or more "flat conjunctions" and + * field filters. e.g. (a == 10) || (b==20 && c==30) + */ + function __PRIVATE_isDisjunctionOfFieldFiltersAndFlatConjunctions(e) { + if (e instanceof CompositeFilter && __PRIVATE_compositeFilterIsDisjunction(e)) { + for (const t of e.getFilters()) if (!__PRIVATE_isSingleFieldFilter(t) && !__PRIVATE_isFlatConjunction(t)) return !1; + return !0; + } + return !1; + }(e); +} + +function __PRIVATE_computeDistributedNormalForm(e) { + if (__PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter, 34018), + e instanceof FieldFilter) return e; + if (1 === e.filters.length) return __PRIVATE_computeDistributedNormalForm(e.filters[0]); + // Compute DNF for each of the subfilters first + const t = e.filters.map((e => __PRIVATE_computeDistributedNormalForm(e))); + let n = CompositeFilter.create(t, e.op); + return n = __PRIVATE_applyAssociation(n), __PRIVATE_isDisjunctiveNormalForm(n) ? n : (__PRIVATE_hardAssert(n instanceof CompositeFilter, 64498), + __PRIVATE_hardAssert(__PRIVATE_compositeFilterIsConjunction(n), 40251), __PRIVATE_hardAssert(n.filters.length > 1, 57927), + n.filters.reduce(((e, t) => __PRIVATE_applyDistribution(e, t)))); +} + +function __PRIVATE_applyDistribution(e, t) { + let n; + return __PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter, 38388), + __PRIVATE_hardAssert(t instanceof FieldFilter || t instanceof CompositeFilter, 25473), + // FieldFilter FieldFilter + n = e instanceof FieldFilter ? t instanceof FieldFilter ? function __PRIVATE_applyDistributionFieldFilters(e, t) { + // Conjunction distribution for two field filters is the conjunction of them. + return CompositeFilter.create([ e, t ], "and" /* CompositeOperator.AND */); + }(e, t) : __PRIVATE_applyDistributionFieldAndCompositeFilters(e, t) : t instanceof FieldFilter ? __PRIVATE_applyDistributionFieldAndCompositeFilters(t, e) : function __PRIVATE_applyDistributionCompositeFilters(e, t) { + // There are four cases: + // (A & B) & (C & D) --> (A & B & C & D) + // (A & B) & (C | D) --> (A & B & C) | (A & B & D) + // (A | B) & (C & D) --> (C & D & A) | (C & D & B) + // (A | B) & (C | D) --> (A & C) | (A & D) | (B & C) | (B & D) + // Case 1 is a merge. + if (__PRIVATE_hardAssert(e.filters.length > 0 && t.filters.length > 0, 48005), __PRIVATE_compositeFilterIsConjunction(e) && __PRIVATE_compositeFilterIsConjunction(t)) return __PRIVATE_compositeFilterWithAddedFilters(e, t.getFilters()); + // Case 2,3,4 all have at least one side (lhs or rhs) that is a disjunction. In all three cases + // we should take each element of the disjunction and distribute it over the other side, and + // return the disjunction of the distribution results. + const n = __PRIVATE_compositeFilterIsDisjunction(e) ? e : t, r = __PRIVATE_compositeFilterIsDisjunction(e) ? t : e, i = n.filters.map((e => __PRIVATE_applyDistribution(e, r))); + return CompositeFilter.create(i, "or" /* CompositeOperator.OR */); + }(e, t), __PRIVATE_applyAssociation(n); +} + +function __PRIVATE_applyDistributionFieldAndCompositeFilters(e, t) { + // There are two cases: + // A & (B & C) --> (A & B & C) + // A & (B | C) --> (A & B) | (A & C) + if (__PRIVATE_compositeFilterIsConjunction(t)) + // Case 1 + return __PRIVATE_compositeFilterWithAddedFilters(t, e.getFilters()); + { + // Case 2 + const n = t.filters.map((t => __PRIVATE_applyDistribution(e, t))); + return CompositeFilter.create(n, "or" /* CompositeOperator.OR */); + } +} + +/** + * Applies the associativity property to the given filter and returns the resulting filter. + * + *

    + *
  • A | (B | C) == (A | B) | C == (A | B | C) + *
  • A & (B & C) == (A & B) & C == (A & B & C) + *
+ * + *

For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic + */ function __PRIVATE_applyAssociation(e) { + if (__PRIVATE_hardAssert(e instanceof FieldFilter || e instanceof CompositeFilter, 11850), + e instanceof FieldFilter) return e; + const t = e.getFilters(); + // If the composite filter only contains 1 filter, apply associativity to it. + if (1 === t.length) return __PRIVATE_applyAssociation(t[0]); + // Associativity applied to a flat composite filter results is itself. + if (__PRIVATE_compositeFilterIsFlat(e)) return e; + // First apply associativity to all subfilters. This will in turn recursively apply + // associativity to all nested composite filters and field filters. + const n = t.map((e => __PRIVATE_applyAssociation(e))), r = []; + // For composite subfilters that perform the same kind of logical operation as `compositeFilter` + // take out their filters and add them to `compositeFilter`. For example: + // compositeFilter = (A | (B | C | D)) + // compositeSubfilter = (B | C | D) + // Result: (A | B | C | D) + // Note that the `compositeSubfilter` has been eliminated, and its filters (B, C, D) have been + // added to the top-level "compositeFilter". + return n.forEach((t => { + t instanceof FieldFilter ? r.push(t) : t instanceof CompositeFilter && (t.op === e.op ? + // compositeFilter: (A | (B | C)) + // compositeSubfilter: (B | C) + // Result: (A | B | C) + r.push(...t.filters) : + // compositeFilter: (A | (B & C)) + // compositeSubfilter: (B & C) + // Result: (A | (B & C)) + r.push(t)); + })), 1 === r.length ? r[0] : CompositeFilter.create(r, e.op); +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An in-memory implementation of IndexManager. + */ class __PRIVATE_MemoryIndexManager { + constructor() { + this.Cn = new __PRIVATE_MemoryCollectionParentIndex; + } + addToCollectionParentIndex(e, t) { + return this.Cn.add(t), PersistencePromise.resolve(); + } + getCollectionParents(e, t) { + return PersistencePromise.resolve(this.Cn.getEntries(t)); + } + addFieldIndex(e, t) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(); + } + deleteFieldIndex(e, t) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(); + } + deleteAllFieldIndexes(e) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(); + } + createTargetIndexes(e, t) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(); + } + getDocumentsMatchingTarget(e, t) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(null); + } + getIndexType(e, t) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(0 /* IndexType.NONE */); + } + getFieldIndexes(e, t) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve([]); + } + getNextCollectionGroupToUpdate(e) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(null); + } + getMinOffset(e, t) { + return PersistencePromise.resolve(IndexOffset.min()); + } + getMinOffsetFromCollectionGroup(e, t) { + return PersistencePromise.resolve(IndexOffset.min()); + } + updateCollectionGroup(e, t, n) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(); + } + updateIndexEntries(e, t) { + // Field indices are not supported with memory persistence. + return PersistencePromise.resolve(); + } +} + +/** + * Internal implementation of the collection-parent index exposed by MemoryIndexManager. + * Also used for in-memory caching by IndexedDbIndexManager and initial index population + * in indexeddb_schema.ts + */ class __PRIVATE_MemoryCollectionParentIndex { + constructor() { + this.index = {}; + } + // Returns false if the entry already existed. + add(e) { + const t = e.lastSegment(), n = e.popLast(), r = this.index[t] || new SortedSet(ResourcePath.comparator), i = !r.has(n); + return this.index[t] = r.add(n), i; + } + has(e) { + const t = e.lastSegment(), n = e.popLast(), r = this.index[t]; + return r && r.has(n); + } + getEntries(e) { + return (this.index[e] || new SortedSet(ResourcePath.comparator)).toArray(); + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const Ot = "IndexedDbIndexManager", Nt = new Uint8Array(0); + +/** + * A persisted implementation of IndexManager. + * + * PORTING NOTE: Unlike iOS and Android, the Web SDK does not memoize index + * data as it supports multi-tab access. + */ +class __PRIVATE_IndexedDbIndexManager { + constructor(e, t) { + this.databaseId = t, + /** + * An in-memory copy of the index entries we've already written since the SDK + * launched. Used to avoid re-writing the same entry repeatedly. + * + * This is *NOT* a complete cache of what's in persistence and so can never be + * used to satisfy reads. + */ + this.vn = new __PRIVATE_MemoryCollectionParentIndex, + /** + * Maps from a target to its equivalent list of sub-targets. Each sub-target + * contains only one term from the target's disjunctive normal form (DNF). + */ + this.Fn = new ObjectMap((e => __PRIVATE_canonifyTarget(e)), ((e, t) => __PRIVATE_targetEquals(e, t))), + this.uid = e.uid || ""; + } + /** + * Adds a new entry to the collection parent index. + * + * Repeated calls for the same collectionPath should be avoided within a + * transaction as IndexedDbIndexManager only caches writes once a transaction + * has been committed. + */ addToCollectionParentIndex(e, t) { + if (!this.vn.has(t)) { + const n = t.lastSegment(), r = t.popLast(); + e.addOnCommittedListener((() => { + // Add the collection to the in memory cache only if the transaction was + // successfully committed. + this.vn.add(t); + })); + const i = { + collectionId: n, + parent: __PRIVATE_encodeResourcePath(r) + }; + return __PRIVATE_collectionParentsStore(e).put(i); + } + return PersistencePromise.resolve(); + } + getCollectionParents(e, t) { + const n = [], r = IDBKeyRange.bound([ t, "" ], [ __PRIVATE_immediateSuccessor(t), "" ], + /*lowerOpen=*/ !1, + /*upperOpen=*/ !0); + return __PRIVATE_collectionParentsStore(e).J(r).next((e => { + for (const r of e) { + // This collectionId guard shouldn't be necessary (and isn't as long + // as we're running in a real browser), but there's a bug in + // indexeddbshim that breaks our range in our tests running in node: + // https://github.com/axemclion/IndexedDBShim/issues/334 + if (r.collectionId !== t) break; + n.push(__PRIVATE_decodeResourcePath(r.parent)); + } + return n; + })); + } + addFieldIndex(e, t) { + // TODO(indexing): Verify that the auto-incrementing index ID works in + // Safari & Firefox. + const n = __PRIVATE_indexConfigurationStore(e), r = function __PRIVATE_toDbIndexConfiguration(e) { + return { + indexId: e.indexId, + collectionGroup: e.collectionGroup, + fields: e.fields.map((e => [ e.fieldPath.canonicalString(), e.kind ])) + }; + }(t); + delete r.indexId; + // `indexId` is auto-populated by IndexedDb + const i = n.add(r); + if (t.indexState) { + const n = __PRIVATE_indexStateStore(e); + return i.next((e => { + n.put(__PRIVATE_toDbIndexState(e, this.uid, t.indexState.sequenceNumber, t.indexState.offset)); + })); + } + return i.next(); + } + deleteFieldIndex(e, t) { + const n = __PRIVATE_indexConfigurationStore(e), r = __PRIVATE_indexStateStore(e), i = __PRIVATE_indexEntriesStore(e); + return n.delete(t.indexId).next((() => r.delete(IDBKeyRange.bound([ t.indexId ], [ t.indexId + 1 ], + /*lowerOpen=*/ !1, + /*upperOpen=*/ !0)))).next((() => i.delete(IDBKeyRange.bound([ t.indexId ], [ t.indexId + 1 ], + /*lowerOpen=*/ !1, + /*upperOpen=*/ !0)))); + } + deleteAllFieldIndexes(e) { + const t = __PRIVATE_indexConfigurationStore(e), n = __PRIVATE_indexEntriesStore(e), r = __PRIVATE_indexStateStore(e); + return t.Z().next((() => n.Z())).next((() => r.Z())); + } + createTargetIndexes(e, t) { + return PersistencePromise.forEach(this.Mn(t), (t => this.getIndexType(e, t).next((n => { + if (0 /* IndexType.NONE */ === n || 1 /* IndexType.PARTIAL */ === n) { + const n = new __PRIVATE_TargetIndexMatcher(t).Dn(); + if (null != n) return this.addFieldIndex(e, n); + } + })))); + } + getDocumentsMatchingTarget(e, t) { + const n = __PRIVATE_indexEntriesStore(e); + let r = !0; + const i = new Map; + return PersistencePromise.forEach(this.Mn(t), (t => this.xn(e, t).next((e => { + r && (r = !!e), i.set(t, e); + })))).next((() => { + if (r) { + let e = __PRIVATE_documentKeySet(); + const r = []; + return PersistencePromise.forEach(i, ((i, s) => { + __PRIVATE_logDebug(Ot, `Using index ${function __PRIVATE_fieldIndexToString(e) { + return `id=${e.indexId}|cg=${e.collectionGroup}|f=${e.fields.map((e => `${e.fieldPath}:${e.kind}`)).join(",")}`; + }(i)} to execute ${__PRIVATE_canonifyTarget(t)}`); + const o = function __PRIVATE_targetGetArrayValues(e, t) { + const n = __PRIVATE_fieldIndexGetArraySegment(t); + if (void 0 === n) return null; + for (const t of __PRIVATE_targetGetFieldFiltersForPath(e, n.fieldPath)) switch (t.op) { + case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ : + return t.value.arrayValue.values || []; + + case "array-contains" /* Operator.ARRAY_CONTAINS */ : + return [ t.value ]; + // Remaining filters are not array filters. + } + return null; + } + /** + * Returns the list of values that are used in != or NOT_IN filters. Returns + * `null` if there are no such filters. + */ (s, i), _ = function __PRIVATE_targetGetNotInValues(e, t) { + const n = new Map; + for (const r of __PRIVATE_fieldIndexGetDirectionalSegments(t)) for (const t of __PRIVATE_targetGetFieldFiltersForPath(e, r.fieldPath)) switch (t.op) { + case "==" /* Operator.EQUAL */ : + case "in" /* Operator.IN */ : + // Encode equality prefix, which is encoded in the index value before + // the inequality (e.g. `a == 'a' && b != 'b'` is encoded to + // `value != 'ab'`). + n.set(r.fieldPath.canonicalString(), t.value); + break; + + case "not-in" /* Operator.NOT_IN */ : + case "!=" /* Operator.NOT_EQUAL */ : + // NotIn/NotEqual is always a suffix. There cannot be any remaining + // segments and hence we can return early here. + return n.set(r.fieldPath.canonicalString(), t.value), Array.from(n.values()); + // Remaining filters cannot be used as notIn bounds. + } + return null; + } + /** + * Returns a lower bound of field values that can be used as a starting point to + * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound + * exists. + */ (s, i), a = function __PRIVATE_targetGetLowerBound(e, t) { + const n = []; + let r = !0; + // For each segment, retrieve a lower bound if there is a suitable filter or + // startAt. + for (const i of __PRIVATE_fieldIndexGetDirectionalSegments(t)) { + const t = 0 /* IndexKind.ASCENDING */ === i.kind ? __PRIVATE_targetGetAscendingBound(e, i.fieldPath, e.startAt) : __PRIVATE_targetGetDescendingBound(e, i.fieldPath, e.startAt); + n.push(t.value), r && (r = t.inclusive); + } + return new Bound(n, r); + } + /** + * Returns an upper bound of field values that can be used as an ending point + * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no + * upper bound exists. + */ (s, i), u = function __PRIVATE_targetGetUpperBound(e, t) { + const n = []; + let r = !0; + // For each segment, retrieve an upper bound if there is a suitable filter or + // endAt. + for (const i of __PRIVATE_fieldIndexGetDirectionalSegments(t)) { + const t = 0 /* IndexKind.ASCENDING */ === i.kind ? __PRIVATE_targetGetDescendingBound(e, i.fieldPath, e.endAt) : __PRIVATE_targetGetAscendingBound(e, i.fieldPath, e.endAt); + n.push(t.value), r && (r = t.inclusive); + } + return new Bound(n, r); + }(s, i), c = this.On(i, s, a), l = this.On(i, s, u), h = this.Nn(i, s, _), P = this.Bn(i.indexId, o, c, a.inclusive, l, u.inclusive, h); + return PersistencePromise.forEach(P, (i => n.Y(i, t.limit).next((t => { + t.forEach((t => { + const n = DocumentKey.fromSegments(t.documentKey); + e.has(n) || (e = e.add(n), r.push(n)); + })); + })))); + })).next((() => r)); + } + return PersistencePromise.resolve(null); + })); + } + Mn(e) { + let t = this.Fn.get(e); + if (t) return t; + if (0 === e.filters.length) t = [ e ]; else { + t = __PRIVATE_getDnfTerms(CompositeFilter.create(e.filters, "and" /* CompositeOperator.AND */)).map((t => __PRIVATE_newTarget(e.path, e.collectionGroup, e.orderBy, t.getFilters(), e.limit, e.startAt, e.endAt))); + } + return this.Fn.set(e, t), t; + } + /** + * Constructs a key range query on `DbIndexEntryStore` that unions all + * bounds. + */ Bn(e, t, n, r, i, s, o) { + // The number of total index scans we union together. This is similar to a + // distributed normal form, but adapted for array values. We create a single + // index range per value in an ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filter + // combined with the values from the query bounds. + const _ = (null != t ? t.length : 1) * Math.max(n.length, i.length), a = _ / (null != t ? t.length : 1), u = []; + for (let c = 0; c < _; ++c) { + const _ = t ? this.Ln(t[c / a]) : Nt, l = this.kn(e, _, n[c % a], r), h = this.qn(e, _, i[c % a], s), P = o.map((t => this.kn(e, _, t, + /* inclusive= */ !0))); + u.push(...this.createRange(l, h, P)); + } + return u; + } + /** Generates the lower bound for `arrayValue` and `directionalValue`. */ kn(e, t, n, r) { + const i = new __PRIVATE_IndexEntry(e, DocumentKey.empty(), t, n); + return r ? i : i.An(); + } + /** Generates the upper bound for `arrayValue` and `directionalValue`. */ qn(e, t, n, r) { + const i = new __PRIVATE_IndexEntry(e, DocumentKey.empty(), t, n); + return r ? i.An() : i; + } + xn(e, t) { + const n = new __PRIVATE_TargetIndexMatcher(t), r = null != t.collectionGroup ? t.collectionGroup : t.path.lastSegment(); + return this.getFieldIndexes(e, r).next((e => { + // Return the index with the most number of segments. + let t = null; + for (const r of e) { + n.yn(r) && (!t || r.fields.length > t.fields.length) && (t = r); + } + return t; + })); + } + getIndexType(e, t) { + let n = 2 /* IndexType.FULL */; + const r = this.Mn(t); + return PersistencePromise.forEach(r, (t => this.xn(e, t).next((e => { + e ? 0 /* IndexType.NONE */ !== n && e.fields.length < function __PRIVATE_targetGetSegmentCount(e) { + let t = new SortedSet(FieldPath$1.comparator), n = !1; + for (const r of e.filters) for (const e of r.getFlattenedFilters()) + // __name__ is not an explicit segment of any index, so we don't need to + // count it. + e.field.isKeyField() || ( + // ARRAY_CONTAINS or ARRAY_CONTAINS_ANY filters must be counted separately. + // For instance, it is possible to have an index for "a ARRAY a ASC". Even + // though these are on the same field, they should be counted as two + // separate segments in an index. + "array-contains" /* Operator.ARRAY_CONTAINS */ === e.op || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === e.op ? n = !0 : t = t.add(e.field)); + for (const n of e.orderBy) + // __name__ is not an explicit segment of any index, so we don't need to + // count it. + n.field.isKeyField() || (t = t.add(n.field)); + return t.size + (n ? 1 : 0); + }(t) && (n = 1 /* IndexType.PARTIAL */) : n = 0 /* IndexType.NONE */; + })))).next((() => + // OR queries have more than one sub-target (one sub-target per DNF term). We currently consider + // OR queries that have a `limit` to have a partial index. For such queries we perform sorting + // and apply the limit in memory as a post-processing step. + function __PRIVATE_targetHasLimit(e) { + return null !== e.limit; + }(t) && r.length > 1 && 2 /* IndexType.FULL */ === n ? 1 /* IndexType.PARTIAL */ : n)); + } + /** + * Returns the byte encoded form of the directional values in the field index. + * Returns `null` if the document does not have all fields specified in the + * index. + */ Qn(e, t) { + const n = new __PRIVATE_IndexByteEncoder; + for (const r of __PRIVATE_fieldIndexGetDirectionalSegments(e)) { + const e = t.data.field(r.fieldPath); + if (null == e) return null; + const i = n.Pn(r.kind); + __PRIVATE_FirestoreIndexValueWriter.Kt.Dt(e, i); + } + return n.un(); + } + /** Encodes a single value to the ascending index format. */ Ln(e) { + const t = new __PRIVATE_IndexByteEncoder; + return __PRIVATE_FirestoreIndexValueWriter.Kt.Dt(e, t.Pn(0 /* IndexKind.ASCENDING */)), + t.un(); + } + /** + * Returns an encoded form of the document key that sorts based on the key + * ordering of the field index. + */ $n(e, t) { + const n = new __PRIVATE_IndexByteEncoder; + return __PRIVATE_FirestoreIndexValueWriter.Kt.Dt(__PRIVATE_refValue(this.databaseId, t), n.Pn(function __PRIVATE_fieldIndexGetKeyOrder(e) { + const t = __PRIVATE_fieldIndexGetDirectionalSegments(e); + return 0 === t.length ? 0 /* IndexKind.ASCENDING */ : t[t.length - 1].kind; + }(e))), n.un(); + } + /** + * Encodes the given field values according to the specification in `target`. + * For IN queries, a list of possible values is returned. + */ Nn(e, t, n) { + if (null === n) return []; + let r = []; + r.push(new __PRIVATE_IndexByteEncoder); + let i = 0; + for (const s of __PRIVATE_fieldIndexGetDirectionalSegments(e)) { + const e = n[i++]; + for (const n of r) if (this.Un(t, s.fieldPath) && isArray(e)) r = this.Kn(r, s, e); else { + const t = n.Pn(s.kind); + __PRIVATE_FirestoreIndexValueWriter.Kt.Dt(e, t); + } + } + return this.Wn(r); + } + /** + * Encodes the given bounds according to the specification in `target`. For IN + * queries, a list of possible values is returned. + */ On(e, t, n) { + return this.Nn(e, t, n.position); + } + /** Returns the byte representation for the provided encoders. */ Wn(e) { + const t = []; + for (let n = 0; n < e.length; ++n) t[n] = e[n].un(); + return t; + } + /** + * Creates a separate encoder for each element of an array. + * + * The method appends each value to all existing encoders (e.g. filter("a", + * "==", "a1").filter("b", "in", ["b1", "b2"]) becomes ["a1,b1", "a1,b2"]). A + * list of new encoders is returned. + */ Kn(e, t, n) { + const r = [ ...e ], i = []; + for (const e of n.arrayValue.values || []) for (const n of r) { + const r = new __PRIVATE_IndexByteEncoder; + r.seed(n.un()), __PRIVATE_FirestoreIndexValueWriter.Kt.Dt(e, r.Pn(t.kind)), i.push(r); + } + return i; + } + Un(e, t) { + return !!e.filters.find((e => e instanceof FieldFilter && e.field.isEqual(t) && ("in" /* Operator.IN */ === e.op || "not-in" /* Operator.NOT_IN */ === e.op))); + } + getFieldIndexes(e, t) { + const n = __PRIVATE_indexConfigurationStore(e), r = __PRIVATE_indexStateStore(e); + return (t ? n.J(Ne, IDBKeyRange.bound(t, t)) : n.J()).next((e => { + const t = []; + return PersistencePromise.forEach(e, (e => r.get([ e.indexId, this.uid ]).next((n => { + t.push(function __PRIVATE_fromDbIndexConfiguration(e, t) { + const n = t ? new IndexState(t.sequenceNumber, new IndexOffset(__PRIVATE_fromDbTimestamp(t.readTime), new DocumentKey(__PRIVATE_decodeResourcePath(t.documentKey)), t.largestBatchId)) : IndexState.empty(), r = e.fields.map((([e, t]) => new IndexSegment(FieldPath$1.fromServerFormat(e), t))); + return new FieldIndex(e.indexId, e.collectionGroup, r, n); + }(e, n)); + })))).next((() => t)); + })); + } + getNextCollectionGroupToUpdate(e) { + return this.getFieldIndexes(e).next((e => 0 === e.length ? null : (e.sort(((e, t) => { + const n = e.indexState.sequenceNumber - t.indexState.sequenceNumber; + return 0 !== n ? n : __PRIVATE_primitiveComparator(e.collectionGroup, t.collectionGroup); + })), e[0].collectionGroup))); + } + updateCollectionGroup(e, t, n) { + const r = __PRIVATE_indexConfigurationStore(e), i = __PRIVATE_indexStateStore(e); + return this.Gn(e).next((e => r.J(Ne, IDBKeyRange.bound(t, t)).next((t => PersistencePromise.forEach(t, (t => i.put(__PRIVATE_toDbIndexState(t.indexId, this.uid, e, n)))))))); + } + updateIndexEntries(e, t) { + // Porting Note: `getFieldIndexes()` on Web does not cache index lookups as + // it could be used across different IndexedDB transactions. As any cached + // data might be invalidated by other multi-tab clients, we can only trust + // data within a single IndexedDB transaction. We therefore add a cache + // here. + const n = new Map; + return PersistencePromise.forEach(t, ((t, r) => { + const i = n.get(t.collectionGroup); + return (i ? PersistencePromise.resolve(i) : this.getFieldIndexes(e, t.collectionGroup)).next((i => (n.set(t.collectionGroup, i), + PersistencePromise.forEach(i, (n => this.zn(e, t, n).next((t => { + const i = this.jn(r, n); + return t.isEqual(i) ? PersistencePromise.resolve() : this.Jn(e, r, n, t, i); + }))))))); + })); + } + Hn(e, t, n, r) { + return __PRIVATE_indexEntriesStore(e).put(r.Rn(this.uid, this.$n(n, t.key), t.key)); + } + Yn(e, t, n, r) { + return __PRIVATE_indexEntriesStore(e).delete(r.Vn(this.uid, this.$n(n, t.key), t.key)); + } + zn(e, t, n) { + const r = __PRIVATE_indexEntriesStore(e); + let i = new SortedSet(__PRIVATE_indexEntryComparator); + return r.ee({ + index: Ke, + range: IDBKeyRange.only([ n.indexId, this.uid, __PRIVATE_encodeKeySafeBytes(this.$n(n, t)) ]) + }, ((e, r) => { + i = i.add(new __PRIVATE_IndexEntry(n.indexId, t, __PRIVATE_decodeKeySafeBytes(r.arrayValue), __PRIVATE_decodeKeySafeBytes(r.directionalValue))); + })).next((() => i)); + } + /** Creates the index entries for the given document. */ jn(e, t) { + let n = new SortedSet(__PRIVATE_indexEntryComparator); + const r = this.Qn(t, e); + if (null == r) return n; + const i = __PRIVATE_fieldIndexGetArraySegment(t); + if (null != i) { + const s = e.data.field(i.fieldPath); + if (isArray(s)) for (const i of s.arrayValue.values || []) n = n.add(new __PRIVATE_IndexEntry(t.indexId, e.key, this.Ln(i), r)); + } else n = n.add(new __PRIVATE_IndexEntry(t.indexId, e.key, Nt, r)); + return n; + } + /** + * Updates the index entries for the provided document by deleting entries + * that are no longer referenced in `newEntries` and adding all newly added + * entries. + */ Jn(e, t, n, r, i) { + __PRIVATE_logDebug(Ot, "Updating index entries for document '%s'", t.key); + const s = []; + return function __PRIVATE_diffSortedSets(e, t, n, r, i) { + const s = e.getIterator(), o = t.getIterator(); + let _ = __PRIVATE_advanceIterator(s), a = __PRIVATE_advanceIterator(o); + // Walk through the two sets at the same time, using the ordering defined by + // `comparator`. + for (;_ || a; ) { + let e = !1, t = !1; + if (_ && a) { + const r = n(_, a); + r < 0 ? + // The element was removed if the next element in our ordered + // walkthrough is only in `before`. + t = !0 : r > 0 && ( + // The element was added if the next element in our ordered walkthrough + // is only in `after`. + e = !0); + } else null != _ ? t = !0 : e = !0; + e ? (r(a), a = __PRIVATE_advanceIterator(o)) : t ? (i(_), _ = __PRIVATE_advanceIterator(s)) : (_ = __PRIVATE_advanceIterator(s), + a = __PRIVATE_advanceIterator(o)); + } + }(r, i, __PRIVATE_indexEntryComparator, ( + /* onAdd= */ r => { + s.push(this.Hn(e, t, n, r)); + }), ( + /* onRemove= */ r => { + s.push(this.Yn(e, t, n, r)); + })), PersistencePromise.waitFor(s); + } + Gn(e) { + let t = 1; + return __PRIVATE_indexStateStore(e).ee({ + index: qe, + reverse: !0, + range: IDBKeyRange.upperBound([ this.uid, Number.MAX_SAFE_INTEGER ]) + }, ((e, n, r) => { + r.done(), t = n.sequenceNumber + 1; + })).next((() => t)); + } + /** + * Returns a new set of IDB ranges that splits the existing range and excludes + * any values that match the `notInValue` from these ranges. As an example, + * '[foo > 2 && foo != 3]` becomes `[foo > 2 && < 3, foo > 3]`. + */ createRange(e, t, n) { + // The notIn values need to be sorted and unique so that we can return a + // sorted set of non-overlapping ranges. + n = n.sort(((e, t) => __PRIVATE_indexEntryComparator(e, t))).filter(((e, t, n) => !t || 0 !== __PRIVATE_indexEntryComparator(e, n[t - 1]))); + const r = []; + r.push(e); + for (const i of n) { + const n = __PRIVATE_indexEntryComparator(i, e), s = __PRIVATE_indexEntryComparator(i, t); + if (0 === n) + // `notInValue` is the lower bound. We therefore need to raise the bound + // to the next value. + r[0] = e.An(); else if (n > 0 && s < 0) + // `notInValue` is in the middle of the range + r.push(i), r.push(i.An()); else if (s > 0) + // `notInValue` (and all following values) are out of the range + break; + } + r.push(t); + const i = []; + for (let e = 0; e < r.length; e += 2) { + // If we encounter two bounds that will create an unmatchable key range, + // then we return an empty set of key ranges. + if (this.Zn(r[e], r[e + 1])) return []; + const t = r[e].Vn(this.uid, Nt, DocumentKey.empty()), n = r[e + 1].Vn(this.uid, Nt, DocumentKey.empty()); + i.push(IDBKeyRange.bound(t, n)); + } + return i; + } + Zn(e, t) { + // If lower bound is greater than the upper bound, then the key + // range can never be matched. + return __PRIVATE_indexEntryComparator(e, t) > 0; + } + getMinOffsetFromCollectionGroup(e, t) { + return this.getFieldIndexes(e, t).next(__PRIVATE_getMinOffsetFromFieldIndexes); + } + getMinOffset(e, t) { + return PersistencePromise.mapArray(this.Mn(t), (t => this.xn(e, t).next((e => e || fail(44426))))).next(__PRIVATE_getMinOffsetFromFieldIndexes); + } +} + +/** + * Helper to get a typed SimpleDbStore for the collectionParents + * document store. + */ function __PRIVATE_collectionParentsStore(e) { + return __PRIVATE_getStore(e, we); +} + +/** + * Helper to get a typed SimpleDbStore for the index entry object store. + */ function __PRIVATE_indexEntriesStore(e) { + return __PRIVATE_getStore(e, $e); +} + +/** + * Helper to get a typed SimpleDbStore for the index configuration object store. + */ function __PRIVATE_indexConfigurationStore(e) { + return __PRIVATE_getStore(e, xe); +} + +/** + * Helper to get a typed SimpleDbStore for the index state object store. + */ function __PRIVATE_indexStateStore(e) { + return __PRIVATE_getStore(e, Le); +} + +function __PRIVATE_getMinOffsetFromFieldIndexes(e) { + __PRIVATE_hardAssert(0 !== e.length, 28825); + let t = e[0].indexState.offset, n = t.largestBatchId; + for (let r = 1; r < e.length; r++) { + const i = e[r].indexState.offset; + __PRIVATE_indexOffsetComparator(i, t) < 0 && (t = i), n < i.largestBatchId && (n = i.largestBatchId); + } + return new IndexOffset(t.readTime, t.documentKey, n); +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const Bt = { + didRun: !1, + sequenceNumbersCollected: 0, + targetsRemoved: 0, + documentsRemoved: 0 +}, Lt = 41943040; + +class LruParams { + static withCacheSize(e) { + return new LruParams(e, LruParams.DEFAULT_COLLECTION_PERCENTILE, LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT); + } + constructor( + // When we attempt to collect, we will only do so if the cache size is greater than this + // threshold. Passing `COLLECTION_DISABLED` here will cause collection to always be skipped. + e, + // The percentage of sequence numbers that we will attempt to collect + t, + // A cap on the total number of sequence numbers that will be collected. This prevents + // us from collecting a huge number of sequence numbers if the cache has grown very large. + n) { + this.cacheSizeCollectionThreshold = e, this.percentileToCollect = t, this.maximumSequenceNumbersToCollect = n; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Delete a mutation batch and the associated document mutations. + * @returns A PersistencePromise of the document mutations that were removed. + */ +function removeMutationBatch(e, t, n) { + const r = e.store(re), i = e.store(ae), s = [], o = IDBKeyRange.only(n.batchId); + let _ = 0; + const a = r.ee({ + range: o + }, ((e, t, n) => (_++, n.delete()))); + s.push(a.next((() => { + __PRIVATE_hardAssert(1 === _, 47070, { + batchId: n.batchId + }); + }))); + const u = []; + for (const e of n.mutations) { + const r = __PRIVATE_newDbDocumentMutationKey(t, e.key.path, n.batchId); + s.push(i.delete(r)), u.push(e.key); + } + return PersistencePromise.waitFor(s).next((() => u)); +} + +/** + * Returns an approximate size for the given document. + */ function __PRIVATE_dbDocumentSize(e) { + if (!e) return 0; + let t; + if (e.document) t = e.document; else if (e.unknownDocument) t = e.unknownDocument; else { + if (!e.noDocument) throw fail(14731); + t = e.noDocument; + } + return JSON.stringify(t).length; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** A mutation queue for a specific user, backed by IndexedDB. */ LruParams.DEFAULT_COLLECTION_PERCENTILE = 10, +LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT = 1e3, LruParams.DEFAULT = new LruParams(Lt, LruParams.DEFAULT_COLLECTION_PERCENTILE, LruParams.DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT), +LruParams.DISABLED = new LruParams(-1, 0, 0); + +class __PRIVATE_IndexedDbMutationQueue { + constructor( + /** + * The normalized userId (e.g. null UID => "" userId) used to store / + * retrieve mutations. + */ + e, t, n, r) { + this.userId = e, this.serializer = t, this.indexManager = n, this.referenceDelegate = r, + /** + * Caches the document keys for pending mutation batches. If the mutation + * has been removed from IndexedDb, the cached value may continue to + * be used to retrieve the batch's document keys. To remove a cached value + * locally, `removeCachedMutationKeys()` should be invoked either directly + * or through `removeMutationBatches()`. + * + * With multi-tab, when the primary client acknowledges or rejects a mutation, + * this cache is used by secondary clients to invalidate the local + * view of the documents that were previously affected by the mutation. + */ + // PORTING NOTE: Multi-tab only. + this.Xn = {}; + } + /** + * Creates a new mutation queue for the given user. + * @param user - The user for which to create a mutation queue. + * @param serializer - The serializer to use when persisting to IndexedDb. + */ static wt(e, t, n, r) { + // TODO(mcg): Figure out what constraints there are on userIDs + // In particular, are there any reserved characters? are empty ids allowed? + // For the moment store these together in the same mutations table assuming + // that empty userIDs aren't allowed. + __PRIVATE_hardAssert("" !== e.uid, 64387); + const i = e.isAuthenticated() ? e.uid : ""; + return new __PRIVATE_IndexedDbMutationQueue(i, t, n, r); + } + checkEmpty(e) { + let t = !0; + const n = IDBKeyRange.bound([ this.userId, Number.NEGATIVE_INFINITY ], [ this.userId, Number.POSITIVE_INFINITY ]); + return __PRIVATE_mutationsStore(e).ee({ + index: se, + range: n + }, ((e, n, r) => { + t = !1, r.done(); + })).next((() => t)); + } + addMutationBatch(e, t, n, r) { + const i = __PRIVATE_documentMutationsStore(e), s = __PRIVATE_mutationsStore(e); + // The IndexedDb implementation in Chrome (and Firefox) does not handle + // compound indices that include auto-generated keys correctly. To ensure + // that the index entry is added correctly in all browsers, we perform two + // writes: The first write is used to retrieve the next auto-generated Batch + // ID, and the second write populates the index and stores the actual + // mutation batch. + // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972 + // We write an empty object to obtain key + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return s.add({}).next((o => { + __PRIVATE_hardAssert("number" == typeof o, 49019); + const _ = new MutationBatch(o, t, n, r), a = function __PRIVATE_toDbMutationBatch(e, t, n) { + const r = n.baseMutations.map((t => toMutation(e.yt, t))), i = n.mutations.map((t => toMutation(e.yt, t))); + return { + userId: t, + batchId: n.batchId, + localWriteTimeMs: n.localWriteTime.toMillis(), + baseMutations: r, + mutations: i + }; + }(this.serializer, this.userId, _), u = []; + let c = new SortedSet(((e, t) => __PRIVATE_primitiveComparator(e.canonicalString(), t.canonicalString()))); + for (const e of r) { + const t = __PRIVATE_newDbDocumentMutationKey(this.userId, e.key.path, o); + c = c.add(e.key.path.popLast()), u.push(s.put(a)), u.push(i.put(t, _e)); + } + return c.forEach((t => { + u.push(this.indexManager.addToCollectionParentIndex(e, t)); + })), e.addOnCommittedListener((() => { + this.Xn[o] = _.keys(); + })), PersistencePromise.waitFor(u).next((() => _)); + })); + } + lookupMutationBatch(e, t) { + return __PRIVATE_mutationsStore(e).get(t).next((e => e ? (__PRIVATE_hardAssert(e.userId === this.userId, 48, "Unexpected user for mutation batch", { + userId: e.userId, + batchId: t + }), __PRIVATE_fromDbMutationBatch(this.serializer, e)) : null)); + } + /** + * Returns the document keys for the mutation batch with the given batchId. + * For primary clients, this method returns `null` after + * `removeMutationBatches()` has been called. Secondary clients return a + * cached result until `removeCachedMutationKeys()` is invoked. + */ + // PORTING NOTE: Multi-tab only. + er(e, t) { + return this.Xn[t] ? PersistencePromise.resolve(this.Xn[t]) : this.lookupMutationBatch(e, t).next((e => { + if (e) { + const n = e.keys(); + return this.Xn[t] = n, n; + } + return null; + })); + } + getNextMutationBatchAfterBatchId(e, t) { + const n = t + 1, r = IDBKeyRange.lowerBound([ this.userId, n ]); + let i = null; + return __PRIVATE_mutationsStore(e).ee({ + index: se, + range: r + }, ((e, t, r) => { + t.userId === this.userId && (__PRIVATE_hardAssert(t.batchId >= n, 47524, { + tr: n + }), i = __PRIVATE_fromDbMutationBatch(this.serializer, t)), r.done(); + })).next((() => i)); + } + getHighestUnacknowledgedBatchId(e) { + const t = IDBKeyRange.upperBound([ this.userId, Number.POSITIVE_INFINITY ]); + let n = H; + return __PRIVATE_mutationsStore(e).ee({ + index: se, + range: t, + reverse: !0 + }, ((e, t, r) => { + n = t.batchId, r.done(); + })).next((() => n)); + } + getAllMutationBatches(e) { + const t = IDBKeyRange.bound([ this.userId, H ], [ this.userId, Number.POSITIVE_INFINITY ]); + return __PRIVATE_mutationsStore(e).J(se, t).next((e => e.map((e => __PRIVATE_fromDbMutationBatch(this.serializer, e))))); + } + getAllMutationBatchesAffectingDocumentKey(e, t) { + // Scan the document-mutation index starting with a prefix starting with + // the given documentKey. + const n = __PRIVATE_newDbDocumentMutationPrefixForPath(this.userId, t.path), r = IDBKeyRange.lowerBound(n), i = []; + return __PRIVATE_documentMutationsStore(e).ee({ + range: r + }, ((n, r, s) => { + const [o, _, a] = n, u = __PRIVATE_decodeResourcePath(_); + // Only consider rows matching exactly the specific key of + // interest. Note that because we order by path first, and we + // order terminators before path separators, we'll encounter all + // the index rows for documentKey contiguously. In particular, all + // the rows for documentKey will occur before any rows for + // documents nested in a subcollection beneath documentKey so we + // can stop as soon as we hit any such row. + if (o === this.userId && t.path.isEqual(u)) + // Look up the mutation batch in the store. + return __PRIVATE_mutationsStore(e).get(a).next((e => { + if (!e) throw fail(61480, { + nr: n, + batchId: a + }); + __PRIVATE_hardAssert(e.userId === this.userId, 10503, "Unexpected user for mutation batch", { + userId: e.userId, + batchId: a + }), i.push(__PRIVATE_fromDbMutationBatch(this.serializer, e)); + })); + s.done(); + })).next((() => i)); + } + getAllMutationBatchesAffectingDocumentKeys(e, t) { + let n = new SortedSet(__PRIVATE_primitiveComparator); + const r = []; + return t.forEach((t => { + const i = __PRIVATE_newDbDocumentMutationPrefixForPath(this.userId, t.path), s = IDBKeyRange.lowerBound(i), o = __PRIVATE_documentMutationsStore(e).ee({ + range: s + }, ((e, r, i) => { + const [s, o, _] = e, a = __PRIVATE_decodeResourcePath(o); + // Only consider rows matching exactly the specific key of + // interest. Note that because we order by path first, and we + // order terminators before path separators, we'll encounter all + // the index rows for documentKey contiguously. In particular, all + // the rows for documentKey will occur before any rows for + // documents nested in a subcollection beneath documentKey so we + // can stop as soon as we hit any such row. + s === this.userId && t.path.isEqual(a) ? n = n.add(_) : i.done(); + })); + r.push(o); + })), PersistencePromise.waitFor(r).next((() => this.rr(e, n))); + } + getAllMutationBatchesAffectingQuery(e, t) { + const n = t.path, r = n.length + 1, i = __PRIVATE_newDbDocumentMutationPrefixForPath(this.userId, n), s = IDBKeyRange.lowerBound(i); + // Collect up unique batchIDs encountered during a scan of the index. Use a + // SortedSet to accumulate batch IDs so they can be traversed in order in a + // scan of the main table. + let o = new SortedSet(__PRIVATE_primitiveComparator); + return __PRIVATE_documentMutationsStore(e).ee({ + range: s + }, ((e, t, i) => { + const [s, _, a] = e, u = __PRIVATE_decodeResourcePath(_); + s === this.userId && n.isPrefixOf(u) ? + // Rows with document keys more than one segment longer than the + // query path can't be matches. For example, a query on 'rooms' + // can't match the document /rooms/abc/messages/xyx. + // TODO(mcg): we'll need a different scanner when we implement + // ancestor queries. + u.length === r && (o = o.add(a)) : i.done(); + })).next((() => this.rr(e, o))); + } + rr(e, t) { + const n = [], r = []; + // TODO(rockwood): Implement this using iterate. + return t.forEach((t => { + r.push(__PRIVATE_mutationsStore(e).get(t).next((e => { + if (null === e) throw fail(35274, { + batchId: t + }); + __PRIVATE_hardAssert(e.userId === this.userId, 9748, "Unexpected user for mutation batch", { + userId: e.userId, + batchId: t + }), n.push(__PRIVATE_fromDbMutationBatch(this.serializer, e)); + }))); + })), PersistencePromise.waitFor(r).next((() => n)); + } + removeMutationBatch(e, t) { + return removeMutationBatch(e.le, this.userId, t).next((n => (e.addOnCommittedListener((() => { + this.ir(t.batchId); + })), PersistencePromise.forEach(n, (t => this.referenceDelegate.markPotentiallyOrphaned(e, t)))))); + } + /** + * Clears the cached keys for a mutation batch. This method should be + * called by secondary clients after they process mutation updates. + * + * Note that this method does not have to be called from primary clients as + * the corresponding cache entries are cleared when an acknowledged or + * rejected batch is removed from the mutation queue. + */ + // PORTING NOTE: Multi-tab only + ir(e) { + delete this.Xn[e]; + } + performConsistencyCheck(e) { + return this.checkEmpty(e).next((t => { + if (!t) return PersistencePromise.resolve(); + // Verify that there are no entries in the documentMutations index if + // the queue is empty. + const n = IDBKeyRange.lowerBound( + /** + * Creates a [userId] key for use in the DbDocumentMutations index to iterate + * over all of a user's document mutations. + */ + function __PRIVATE_newDbDocumentMutationPrefixForUser(e) { + return [ e ]; + }(this.userId)), r = []; + return __PRIVATE_documentMutationsStore(e).ee({ + range: n + }, ((e, t, n) => { + if (e[0] === this.userId) { + const t = __PRIVATE_decodeResourcePath(e[1]); + r.push(t); + } else n.done(); + })).next((() => { + __PRIVATE_hardAssert(0 === r.length, 56720, { + sr: r.map((e => e.canonicalString())) + }); + })); + })); + } + containsKey(e, t) { + return __PRIVATE_mutationQueueContainsKey(e, this.userId, t); + } + // PORTING NOTE: Multi-tab only (state is held in memory in other clients). + /** Returns the mutation queue's metadata from IndexedDb. */ + _r(e) { + return __PRIVATE_mutationQueuesStore(e).get(this.userId).next((e => e || { + userId: this.userId, + lastAcknowledgedBatchId: H, + lastStreamToken: "" + })); + } +} + +/** + * @returns true if the mutation queue for the given user contains a pending + * mutation for the given key. + */ function __PRIVATE_mutationQueueContainsKey(e, t, n) { + const r = __PRIVATE_newDbDocumentMutationPrefixForPath(t, n.path), i = r[1], s = IDBKeyRange.lowerBound(r); + let o = !1; + return __PRIVATE_documentMutationsStore(e).ee({ + range: s, + X: !0 + }, ((e, n, r) => { + const [s, _, /*batchID*/ a] = e; + s === t && _ === i && (o = !0), r.done(); + })).next((() => o)); +} + +/** Returns true if any mutation queue contains the given document. */ +/** + * Helper to get a typed SimpleDbStore for the mutations object store. + */ +function __PRIVATE_mutationsStore(e) { + return __PRIVATE_getStore(e, re); +} + +/** + * Helper to get a typed SimpleDbStore for the mutationQueues object store. + */ function __PRIVATE_documentMutationsStore(e) { + return __PRIVATE_getStore(e, ae); +} + +/** + * Helper to get a typed SimpleDbStore for the mutationQueues object store. + */ function __PRIVATE_mutationQueuesStore(e) { + return __PRIVATE_getStore(e, te); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Offset to ensure non-overlapping target ids. */ +/** + * Generates monotonically increasing target IDs for sending targets to the + * watch stream. + * + * The client constructs two generators, one for the target cache, and one for + * for the sync engine (to generate limbo documents targets). These + * generators produce non-overlapping IDs (by using even and odd IDs + * respectively). + * + * By separating the target ID space, the query cache can generate target IDs + * that persist across client restarts, while sync engine can independently + * generate in-memory target IDs that are transient and can be reused after a + * restart. + */ +class __PRIVATE_TargetIdGenerator { + constructor(e) { + this.ar = e; + } + next() { + return this.ar += 2, this.ar; + } + static ur() { + // The target cache generator must return '2' in its first call to `next()` + // as there is no differentiation in the protocol layer between an unset + // number and the number '0'. If we were to sent a target with target ID + // '0', the backend would consider it unset and replace it with its own ID. + return new __PRIVATE_TargetIdGenerator(0); + } + static cr() { + // Sync engine assigns target IDs for limbo document detection. + return new __PRIVATE_TargetIdGenerator(-1); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_IndexedDbTargetCache { + constructor(e, t) { + this.referenceDelegate = e, this.serializer = t; + } + // PORTING NOTE: We don't cache global metadata for the target cache, since + // some of it (in particular `highestTargetId`) can be modified by secondary + // tabs. We could perhaps be more granular (and e.g. still cache + // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go + // to IndexedDb whenever we need to read metadata. We can revisit if it turns + // out to have a meaningful performance impact. + allocateTargetId(e) { + return this.lr(e).next((t => { + const n = new __PRIVATE_TargetIdGenerator(t.highestTargetId); + return t.highestTargetId = n.next(), this.hr(e, t).next((() => t.highestTargetId)); + })); + } + getLastRemoteSnapshotVersion(e) { + return this.lr(e).next((e => SnapshotVersion.fromTimestamp(new Timestamp(e.lastRemoteSnapshotVersion.seconds, e.lastRemoteSnapshotVersion.nanoseconds)))); + } + getHighestSequenceNumber(e) { + return this.lr(e).next((e => e.highestListenSequenceNumber)); + } + setTargetsMetadata(e, t, n) { + return this.lr(e).next((r => (r.highestListenSequenceNumber = t, n && (r.lastRemoteSnapshotVersion = n.toTimestamp()), + t > r.highestListenSequenceNumber && (r.highestListenSequenceNumber = t), this.hr(e, r)))); + } + addTargetData(e, t) { + return this.Pr(e, t).next((() => this.lr(e).next((n => (n.targetCount += 1, this.Tr(t, n), + this.hr(e, n)))))); + } + updateTargetData(e, t) { + return this.Pr(e, t); + } + removeTargetData(e, t) { + return this.removeMatchingKeysForTargetId(e, t.targetId).next((() => __PRIVATE_targetsStore(e).delete(t.targetId))).next((() => this.lr(e))).next((t => (__PRIVATE_hardAssert(t.targetCount > 0, 8065), + t.targetCount -= 1, this.hr(e, t)))); + } + /** + * Drops any targets with sequence number less than or equal to the upper bound, excepting those + * present in `activeTargetIds`. Document associations for the removed targets are also removed. + * Returns the number of targets removed. + */ removeTargets(e, t, n) { + let r = 0; + const i = []; + return __PRIVATE_targetsStore(e).ee(((s, o) => { + const _ = __PRIVATE_fromDbTarget(o); + _.sequenceNumber <= t && null === n.get(_.targetId) && (r++, i.push(this.removeTargetData(e, _))); + })).next((() => PersistencePromise.waitFor(i))).next((() => r)); + } + /** + * Call provided function with each `TargetData` that we have cached. + */ forEachTarget(e, t) { + return __PRIVATE_targetsStore(e).ee(((e, n) => { + const r = __PRIVATE_fromDbTarget(n); + t(r); + })); + } + lr(e) { + return __PRIVATE_globalTargetStore(e).get(pe).next((e => (__PRIVATE_hardAssert(null !== e, 2888), + e))); + } + hr(e, t) { + return __PRIVATE_globalTargetStore(e).put(pe, t); + } + Pr(e, t) { + return __PRIVATE_targetsStore(e).put(__PRIVATE_toDbTarget(this.serializer, t)); + } + /** + * In-place updates the provided metadata to account for values in the given + * TargetData. Saving is done separately. Returns true if there were any + * changes to the metadata. + */ Tr(e, t) { + let n = !1; + return e.targetId > t.highestTargetId && (t.highestTargetId = e.targetId, n = !0), + e.sequenceNumber > t.highestListenSequenceNumber && (t.highestListenSequenceNumber = e.sequenceNumber, + n = !0), n; + } + getTargetCount(e) { + return this.lr(e).next((e => e.targetCount)); + } + getTargetData(e, t) { + // Iterating by the canonicalId may yield more than one result because + // canonicalId values are not required to be unique per target. This query + // depends on the queryTargets index to be efficient. + const n = __PRIVATE_canonifyTarget(t), r = IDBKeyRange.bound([ n, Number.NEGATIVE_INFINITY ], [ n, Number.POSITIVE_INFINITY ]); + let i = null; + return __PRIVATE_targetsStore(e).ee({ + range: r, + index: Ae + }, ((e, n, r) => { + const s = __PRIVATE_fromDbTarget(n); + // After finding a potential match, check that the target is + // actually equal to the requested target. + __PRIVATE_targetEquals(t, s.target) && (i = s, r.done()); + })).next((() => i)); + } + addMatchingKeys(e, t, n) { + // PORTING NOTE: The reverse index (documentsTargets) is maintained by + // IndexedDb. + const r = [], i = __PRIVATE_documentTargetStore(e); + return t.forEach((t => { + const s = __PRIVATE_encodeResourcePath(t.path); + r.push(i.put({ + targetId: n, + path: s + })), r.push(this.referenceDelegate.addReference(e, n, t)); + })), PersistencePromise.waitFor(r); + } + removeMatchingKeys(e, t, n) { + // PORTING NOTE: The reverse index (documentsTargets) is maintained by + // IndexedDb. + const r = __PRIVATE_documentTargetStore(e); + return PersistencePromise.forEach(t, (t => { + const i = __PRIVATE_encodeResourcePath(t.path); + return PersistencePromise.waitFor([ r.delete([ n, i ]), this.referenceDelegate.removeReference(e, n, t) ]); + })); + } + removeMatchingKeysForTargetId(e, t) { + const n = __PRIVATE_documentTargetStore(e), r = IDBKeyRange.bound([ t ], [ t + 1 ], + /*lowerOpen=*/ !1, + /*upperOpen=*/ !0); + return n.delete(r); + } + getMatchingKeysForTargetId(e, t) { + const n = IDBKeyRange.bound([ t ], [ t + 1 ], + /*lowerOpen=*/ !1, + /*upperOpen=*/ !0), r = __PRIVATE_documentTargetStore(e); + let i = __PRIVATE_documentKeySet(); + return r.ee({ + range: n, + X: !0 + }, ((e, t, n) => { + const r = __PRIVATE_decodeResourcePath(e[1]), s = new DocumentKey(r); + i = i.add(s); + })).next((() => i)); + } + containsKey(e, t) { + const n = __PRIVATE_encodeResourcePath(t.path), r = IDBKeyRange.bound([ n ], [ __PRIVATE_immediateSuccessor(n) ], + /*lowerOpen=*/ !1, + /*upperOpen=*/ !0); + let i = 0; + return __PRIVATE_documentTargetStore(e).ee({ + index: fe, + X: !0, + range: r + }, (([e, t], n, r) => { + // Having a sentinel row for a document does not count as containing that document; + // For the target cache, containing the document means the document is part of some + // target. + 0 !== e && (i++, r.done()); + })).next((() => i > 0)); + } + /** + * Looks up a TargetData entry by target ID. + * + * @param targetId - The target ID of the TargetData entry to look up. + * @returns The cached TargetData entry, or null if the cache has no entry for + * the target. + */ + // PORTING NOTE: Multi-tab only. + At(e, t) { + return __PRIVATE_targetsStore(e).get(t).next((e => e ? __PRIVATE_fromDbTarget(e) : null)); + } +} + +/** + * Helper to get a typed SimpleDbStore for the queries object store. + */ function __PRIVATE_targetsStore(e) { + return __PRIVATE_getStore(e, de); +} + +/** + * Helper to get a typed SimpleDbStore for the target globals object store. + */ function __PRIVATE_globalTargetStore(e) { + return __PRIVATE_getStore(e, ye); +} + +/** + * Helper to get a typed SimpleDbStore for the document target object store. + */ function __PRIVATE_documentTargetStore(e) { + return __PRIVATE_getStore(e, Ve); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const kt = "LruGarbageCollector", qt = 1048576; + +function __PRIVATE_bufferEntryComparator([e, t], [n, r]) { + const i = __PRIVATE_primitiveComparator(e, n); + return 0 === i ? __PRIVATE_primitiveComparator(t, r) : i; +} + +/** + * Used to calculate the nth sequence number. Keeps a rolling buffer of the + * lowest n values passed to `addElement`, and finally reports the largest of + * them in `maxValue`. + */ class __PRIVATE_RollingSequenceNumberBuffer { + constructor(e) { + this.Ir = e, this.buffer = new SortedSet(__PRIVATE_bufferEntryComparator), this.Er = 0; + } + dr() { + return ++this.Er; + } + Ar(e) { + const t = [ e, this.dr() ]; + if (this.buffer.size < this.Ir) this.buffer = this.buffer.add(t); else { + const e = this.buffer.last(); + __PRIVATE_bufferEntryComparator(t, e) < 0 && (this.buffer = this.buffer.delete(e).add(t)); + } + } + get maxValue() { + // Guaranteed to be non-empty. If we decide we are not collecting any + // sequence numbers, nthSequenceNumber below short-circuits. If we have + // decided that we are collecting n sequence numbers, it's because n is some + // percentage of the existing sequence numbers. That means we should never + // be in a situation where we are collecting sequence numbers but don't + // actually have any. + return this.buffer.last()[0]; + } +} + +/** + * This class is responsible for the scheduling of LRU garbage collection. It handles checking + * whether or not GC is enabled, as well as which delay to use before the next run. + */ class __PRIVATE_LruScheduler { + constructor(e, t, n) { + this.garbageCollector = e, this.asyncQueue = t, this.localStore = n, this.Rr = null; + } + start() { + -1 !== this.garbageCollector.params.cacheSizeCollectionThreshold && this.Vr(6e4); + } + stop() { + this.Rr && (this.Rr.cancel(), this.Rr = null); + } + get started() { + return null !== this.Rr; + } + Vr(e) { + __PRIVATE_logDebug(kt, `Garbage collection scheduled in ${e}ms`), this.Rr = this.asyncQueue.enqueueAfterDelay("lru_garbage_collection" /* TimerId.LruGarbageCollection */ , e, (async () => { + this.Rr = null; + try { + await this.localStore.collectGarbage(this.garbageCollector); + } catch (e) { + __PRIVATE_isIndexedDbTransactionError(e) ? __PRIVATE_logDebug(kt, "Ignoring IndexedDB error during garbage collection: ", e) : await __PRIVATE_ignoreIfPrimaryLeaseLoss(e); + } + await this.Vr(3e5); + })); + } +} + +/** + * Implements the steps for LRU garbage collection. + */ class __PRIVATE_LruGarbageCollectorImpl { + constructor(e, t) { + this.mr = e, this.params = t; + } + calculateTargetCount(e, t) { + return this.mr.gr(e).next((e => Math.floor(t / 100 * e))); + } + nthSequenceNumber(e, t) { + if (0 === t) return PersistencePromise.resolve(__PRIVATE_ListenSequence.ce); + const n = new __PRIVATE_RollingSequenceNumberBuffer(t); + return this.mr.forEachTarget(e, (e => n.Ar(e.sequenceNumber))).next((() => this.mr.pr(e, (e => n.Ar(e))))).next((() => n.maxValue)); + } + removeTargets(e, t, n) { + return this.mr.removeTargets(e, t, n); + } + removeOrphanedDocuments(e, t) { + return this.mr.removeOrphanedDocuments(e, t); + } + collect(e, t) { + return -1 === this.params.cacheSizeCollectionThreshold ? (__PRIVATE_logDebug("LruGarbageCollector", "Garbage collection skipped; disabled"), + PersistencePromise.resolve(Bt)) : this.getCacheSize(e).next((n => n < this.params.cacheSizeCollectionThreshold ? (__PRIVATE_logDebug("LruGarbageCollector", `Garbage collection skipped; Cache size ${n} is lower than threshold ${this.params.cacheSizeCollectionThreshold}`), + Bt) : this.yr(e, t))); + } + getCacheSize(e) { + return this.mr.getCacheSize(e); + } + yr(e, t) { + let n, r, i, s, o, _, u; + const c = Date.now(); + return this.calculateTargetCount(e, this.params.percentileToCollect).next((t => ( + // Cap at the configured max + t > this.params.maximumSequenceNumbersToCollect ? (__PRIVATE_logDebug("LruGarbageCollector", `Capping sequence numbers to collect down to the maximum of ${this.params.maximumSequenceNumbersToCollect} from ${t}`), + r = this.params.maximumSequenceNumbersToCollect) : r = t, s = Date.now(), this.nthSequenceNumber(e, r)))).next((r => (n = r, + o = Date.now(), this.removeTargets(e, n, t)))).next((t => (i = t, _ = Date.now(), + this.removeOrphanedDocuments(e, n)))).next((e => { + if (u = Date.now(), __PRIVATE_getLogLevel() <= a.DEBUG) { + __PRIVATE_logDebug("LruGarbageCollector", `LRU Garbage Collection\n\tCounted targets in ${s - c}ms\n\tDetermined least recently used ${r} in ` + (o - s) + "ms\n" + `\tRemoved ${i} targets in ` + (_ - o) + "ms\n" + `\tRemoved ${e} documents in ` + (u - _) + "ms\n" + `Total Duration: ${u - c}ms`); + } + return PersistencePromise.resolve({ + didRun: !0, + sequenceNumbersCollected: r, + targetsRemoved: i, + documentsRemoved: e + }); + })); + } +} + +function __PRIVATE_newLruGarbageCollector(e, t) { + return new __PRIVATE_LruGarbageCollectorImpl(e, t); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Provides LRU functionality for IndexedDB persistence. */ class __PRIVATE_IndexedDbLruDelegateImpl { + constructor(e, t) { + this.db = e, this.garbageCollector = __PRIVATE_newLruGarbageCollector(this, t); + } + gr(e) { + const t = this.wr(e); + return this.db.getTargetCache().getTargetCount(e).next((e => t.next((t => e + t)))); + } + wr(e) { + let t = 0; + return this.pr(e, (e => { + t++; + })).next((() => t)); + } + forEachTarget(e, t) { + return this.db.getTargetCache().forEachTarget(e, t); + } + pr(e, t) { + return this.Sr(e, ((e, n) => t(n))); + } + addReference(e, t, n) { + return __PRIVATE_writeSentinelKey(e, n); + } + removeReference(e, t, n) { + return __PRIVATE_writeSentinelKey(e, n); + } + removeTargets(e, t, n) { + return this.db.getTargetCache().removeTargets(e, t, n); + } + markPotentiallyOrphaned(e, t) { + return __PRIVATE_writeSentinelKey(e, t); + } + /** + * Returns true if anything would prevent this document from being garbage + * collected, given that the document in question is not present in any + * targets and has a sequence number less than or equal to the upper bound for + * the collection run. + */ br(e, t) { + return function __PRIVATE_mutationQueuesContainKey(e, t) { + let n = !1; + return __PRIVATE_mutationQueuesStore(e).te((r => __PRIVATE_mutationQueueContainsKey(e, r, t).next((e => (e && (n = !0), + PersistencePromise.resolve(!e)))))).next((() => n)); + }(e, t); + } + removeOrphanedDocuments(e, t) { + const n = this.db.getRemoteDocumentCache().newChangeBuffer(), r = []; + let i = 0; + return this.Sr(e, ((s, o) => { + if (o <= t) { + const t = this.br(e, s).next((t => { + if (!t) + // Our size accounting requires us to read all documents before + // removing them. + return i++, n.getEntry(e, s).next((() => (n.removeEntry(s, SnapshotVersion.min()), + __PRIVATE_documentTargetStore(e).delete(function __PRIVATE_sentinelKey$1(e) { + return [ 0, __PRIVATE_encodeResourcePath(e.path) ]; + } + /** + * @returns A value suitable for writing a sentinel row in the target-document + * store. + */ (s))))); + })); + r.push(t); + } + })).next((() => PersistencePromise.waitFor(r))).next((() => n.apply(e))).next((() => i)); + } + removeTarget(e, t) { + const n = t.withSequenceNumber(e.currentSequenceNumber); + return this.db.getTargetCache().updateTargetData(e, n); + } + updateLimboDocument(e, t) { + return __PRIVATE_writeSentinelKey(e, t); + } + /** + * Call provided function for each document in the cache that is 'orphaned'. Orphaned + * means not a part of any target, so the only entry in the target-document index for + * that document will be the sentinel row (targetId 0), which will also have the sequence + * number for the last time the document was accessed. + */ Sr(e, t) { + const n = __PRIVATE_documentTargetStore(e); + let r, i = __PRIVATE_ListenSequence.ce; + return n.ee({ + index: fe + }, (([e, n], {path: s, sequenceNumber: o}) => { + 0 === e ? ( + // if nextToReport is valid, report it, this is a new key so the + // last one must not be a member of any targets. + i !== __PRIVATE_ListenSequence.ce && t(new DocumentKey(__PRIVATE_decodeResourcePath(r)), i), + // set nextToReport to be this sequence number. It's the next one we + // might report, if we don't find any targets for this document. + // Note that the sequence number must be defined when the targetId + // is 0. + i = o, r = s) : + // set nextToReport to be invalid, we know we don't need to report + // this one since we found a target for it. + i = __PRIVATE_ListenSequence.ce; + })).next((() => { + // Since we report sequence numbers after getting to the next key, we + // need to check if the last key we iterated over was an orphaned + // document and report it. + i !== __PRIVATE_ListenSequence.ce && t(new DocumentKey(__PRIVATE_decodeResourcePath(r)), i); + })); + } + getCacheSize(e) { + return this.db.getRemoteDocumentCache().getSize(e); + } +} + +function __PRIVATE_writeSentinelKey(e, t) { + return __PRIVATE_documentTargetStore(e).put(function __PRIVATE_sentinelRow(e, t) { + return { + targetId: 0, + path: __PRIVATE_encodeResourcePath(e.path), + sequenceNumber: t + }; + }(t, e.currentSequenceNumber)); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An in-memory buffer of entries to be written to a RemoteDocumentCache. + * It can be used to batch up a set of changes to be written to the cache, but + * additionally supports reading entries back with the `getEntry()` method, + * falling back to the underlying RemoteDocumentCache if no entry is + * buffered. + * + * Entries added to the cache *must* be read first. This is to facilitate + * calculating the size delta of the pending changes. + * + * PORTING NOTE: This class was implemented then removed from other platforms. + * If byte-counting ends up being needed on the other platforms, consider + * porting this class as part of that implementation work. + */ class RemoteDocumentChangeBuffer { + constructor() { + // A mapping of document key to the new cache entry that should be written. + this.changes = new ObjectMap((e => e.toString()), ((e, t) => e.isEqual(t))), this.changesApplied = !1; + } + /** + * Buffers a `RemoteDocumentCache.addEntry()` call. + * + * You can only modify documents that have already been retrieved via + * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). + */ addEntry(e) { + this.assertNotApplied(), this.changes.set(e.key, e); + } + /** + * Buffers a `RemoteDocumentCache.removeEntry()` call. + * + * You can only remove documents that have already been retrieved via + * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). + */ removeEntry(e, t) { + this.assertNotApplied(), this.changes.set(e, MutableDocument.newInvalidDocument(e).setReadTime(t)); + } + /** + * Looks up an entry in the cache. The buffered changes will first be checked, + * and if no buffered change applies, this will forward to + * `RemoteDocumentCache.getEntry()`. + * + * @param transaction - The transaction in which to perform any persistence + * operations. + * @param documentKey - The key of the entry to look up. + * @returns The cached document or an invalid document if we have nothing + * cached. + */ getEntry(e, t) { + this.assertNotApplied(); + const n = this.changes.get(t); + return void 0 !== n ? PersistencePromise.resolve(n) : this.getFromCache(e, t); + } + /** + * Looks up several entries in the cache, forwarding to + * `RemoteDocumentCache.getEntry()`. + * + * @param transaction - The transaction in which to perform any persistence + * operations. + * @param documentKeys - The keys of the entries to look up. + * @returns A map of cached documents, indexed by key. If an entry cannot be + * found, the corresponding key will be mapped to an invalid document. + */ getEntries(e, t) { + return this.getAllFromCache(e, t); + } + /** + * Applies buffered changes to the underlying RemoteDocumentCache, using + * the provided transaction. + */ apply(e) { + return this.assertNotApplied(), this.changesApplied = !0, this.applyChanges(e); + } + /** Helper to assert this.changes is not null */ assertNotApplied() {} +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The RemoteDocumentCache for IndexedDb. To construct, invoke + * `newIndexedDbRemoteDocumentCache()`. + */ class __PRIVATE_IndexedDbRemoteDocumentCacheImpl { + constructor(e) { + this.serializer = e; + } + setIndexManager(e) { + this.indexManager = e; + } + /** + * Adds the supplied entries to the cache. + * + * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer + * returned by `newChangeBuffer()` to ensure proper accounting of metadata. + */ addEntry(e, t, n) { + return __PRIVATE_remoteDocumentsStore(e).put(n); + } + /** + * Removes a document from the cache. + * + * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer + * returned by `newChangeBuffer()` to ensure proper accounting of metadata. + */ removeEntry(e, t, n) { + return __PRIVATE_remoteDocumentsStore(e).delete( + /** + * Returns a key that can be used for document lookups via the primary key of + * the DbRemoteDocument object store. + */ + function __PRIVATE_dbReadTimeKey(e, t) { + const n = e.path.toArray(); + return [ + /* prefix path */ n.slice(0, n.length - 2), + /* collection id */ n[n.length - 2], __PRIVATE_toDbTimestampKey(t), + /* document id */ n[n.length - 1] ]; + } + /** + * Returns a key that can be used for document lookups on the + * `DbRemoteDocumentDocumentCollectionGroupIndex` index. + */ (t, n)); + } + /** + * Updates the current cache size. + * + * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the + * cache's metadata. + */ updateMetadata(e, t) { + return this.getMetadata(e).next((n => (n.byteSize += t, this.Dr(e, n)))); + } + getEntry(e, t) { + let n = MutableDocument.newInvalidDocument(t); + return __PRIVATE_remoteDocumentsStore(e).ee({ + index: le, + range: IDBKeyRange.only(__PRIVATE_dbKey(t)) + }, ((e, r) => { + n = this.Cr(t, r); + })).next((() => n)); + } + /** + * Looks up an entry in the cache. + * + * @param documentKey - The key of the entry to look up. + * @returns The cached document entry and its size. + */ vr(e, t) { + let n = { + size: 0, + document: MutableDocument.newInvalidDocument(t) + }; + return __PRIVATE_remoteDocumentsStore(e).ee({ + index: le, + range: IDBKeyRange.only(__PRIVATE_dbKey(t)) + }, ((e, r) => { + n = { + document: this.Cr(t, r), + size: __PRIVATE_dbDocumentSize(r) + }; + })).next((() => n)); + } + getEntries(e, t) { + let n = __PRIVATE_mutableDocumentMap(); + return this.Fr(e, t, ((e, t) => { + const r = this.Cr(e, t); + n = n.insert(e, r); + })).next((() => n)); + } + /** + * Looks up several entries in the cache. + * + * @param documentKeys - The set of keys entries to look up. + * @returns A map of documents indexed by key and a map of sizes indexed by + * key (zero if the document does not exist). + */ Mr(e, t) { + let n = __PRIVATE_mutableDocumentMap(), r = new SortedMap(DocumentKey.comparator); + return this.Fr(e, t, ((e, t) => { + const i = this.Cr(e, t); + n = n.insert(e, i), r = r.insert(e, __PRIVATE_dbDocumentSize(t)); + })).next((() => ({ + documents: n, + Or: r + }))); + } + Fr(e, t, n) { + if (t.isEmpty()) return PersistencePromise.resolve(); + let r = new SortedSet(__PRIVATE_dbKeyComparator); + t.forEach((e => r = r.add(e))); + const i = IDBKeyRange.bound(__PRIVATE_dbKey(r.first()), __PRIVATE_dbKey(r.last())), s = r.getIterator(); + let o = s.getNext(); + return __PRIVATE_remoteDocumentsStore(e).ee({ + index: le, + range: i + }, ((e, t, r) => { + const i = DocumentKey.fromSegments([ ...t.prefixPath, t.collectionGroup, t.documentId ]); + // Go through keys not found in cache. + for (;o && __PRIVATE_dbKeyComparator(o, i) < 0; ) n(o, null), o = s.getNext(); + o && o.isEqual(i) && ( + // Key found in cache. + n(o, t), o = s.hasNext() ? s.getNext() : null), + // Skip to the next key (if there is one). + o ? r.j(__PRIVATE_dbKey(o)) : r.done(); + })).next((() => { + // The rest of the keys are not in the cache. One case where `iterate` + // above won't go through them is when the cache is empty. + for (;o; ) n(o, null), o = s.hasNext() ? s.getNext() : null; + })); + } + getDocumentsMatchingQuery(e, t, n, r, i) { + const s = t.path, o = [ s.popLast().toArray(), s.lastSegment(), __PRIVATE_toDbTimestampKey(n.readTime), n.documentKey.path.isEmpty() ? "" : n.documentKey.path.lastSegment() ], _ = [ s.popLast().toArray(), s.lastSegment(), [ Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER ], "" ]; + return __PRIVATE_remoteDocumentsStore(e).J(IDBKeyRange.bound(o, _, !0)).next((e => { + i?.incrementDocumentReadCount(e.length); + let n = __PRIVATE_mutableDocumentMap(); + for (const i of e) { + const e = this.Cr(DocumentKey.fromSegments(i.prefixPath.concat(i.collectionGroup, i.documentId)), i); + e.isFoundDocument() && (__PRIVATE_queryMatches(t, e) || r.has(e.key)) && ( + // Either the document matches the given query, or it is mutated. + n = n.insert(e.key, e)); + } + return n; + })); + } + getAllFromCollectionGroup(e, t, n, r) { + let i = __PRIVATE_mutableDocumentMap(); + const s = __PRIVATE_dbCollectionGroupKey(t, n), o = __PRIVATE_dbCollectionGroupKey(t, IndexOffset.max()); + return __PRIVATE_remoteDocumentsStore(e).ee({ + index: Pe, + range: IDBKeyRange.bound(s, o, !0) + }, ((e, t, n) => { + const s = this.Cr(DocumentKey.fromSegments(t.prefixPath.concat(t.collectionGroup, t.documentId)), t); + i = i.insert(s.key, s), i.size === r && n.done(); + })).next((() => i)); + } + newChangeBuffer(e) { + return new __PRIVATE_IndexedDbRemoteDocumentChangeBuffer(this, !!e && e.trackRemovals); + } + getSize(e) { + return this.getMetadata(e).next((e => e.byteSize)); + } + getMetadata(e) { + return __PRIVATE_documentGlobalStore(e).get(Ee).next((e => (__PRIVATE_hardAssert(!!e, 20021), + e))); + } + Dr(e, t) { + return __PRIVATE_documentGlobalStore(e).put(Ee, t); + } + /** + * Decodes `dbRemoteDoc` and returns the document (or an invalid document if + * the document corresponds to the format used for sentinel deletes). + */ Cr(e, t) { + if (t) { + const e = __PRIVATE_fromDbRemoteDocument(this.serializer, t); + // Whether the document is a sentinel removal and should only be used in the + // `getNewDocumentChanges()` + if (!(e.isNoDocument() && e.version.isEqual(SnapshotVersion.min()))) return e; + } + return MutableDocument.newInvalidDocument(e); + } +} + +/** Creates a new IndexedDbRemoteDocumentCache. */ function __PRIVATE_newIndexedDbRemoteDocumentCache(e) { + return new __PRIVATE_IndexedDbRemoteDocumentCacheImpl(e); +} + +/** + * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache. + * + * Unlike the MemoryRemoteDocumentChangeBuffer, the IndexedDb implementation computes the size + * delta for all submitted changes. This avoids having to re-read all documents from IndexedDb + * when we apply the changes. + */ class __PRIVATE_IndexedDbRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer { + /** + * @param documentCache - The IndexedDbRemoteDocumentCache to apply the changes to. + * @param trackRemovals - Whether to create sentinel deletes that can be tracked by + * `getNewDocumentChanges()`. + */ + constructor(e, t) { + super(), this.Nr = e, this.trackRemovals = t, + // A map of document sizes and read times prior to applying the changes in + // this buffer. + this.Br = new ObjectMap((e => e.toString()), ((e, t) => e.isEqual(t))); + } + applyChanges(e) { + const t = []; + let n = 0, r = new SortedSet(((e, t) => __PRIVATE_primitiveComparator(e.canonicalString(), t.canonicalString()))); + return this.changes.forEach(((i, s) => { + const o = this.Br.get(i); + if (t.push(this.Nr.removeEntry(e, i, o.readTime)), s.isValidDocument()) { + const _ = __PRIVATE_toDbRemoteDocument(this.Nr.serializer, s); + r = r.add(i.path.popLast()); + const a = __PRIVATE_dbDocumentSize(_); + n += a - o.size, t.push(this.Nr.addEntry(e, i, _)); + } else if (n -= o.size, this.trackRemovals) { + // In order to track removals, we store a "sentinel delete" in the + // RemoteDocumentCache. This entry is represented by a NoDocument + // with a version of 0 and ignored by `maybeDecodeDocument()` but + // preserved in `getNewDocumentChanges()`. + const n = __PRIVATE_toDbRemoteDocument(this.Nr.serializer, s.convertToNoDocument(SnapshotVersion.min())); + t.push(this.Nr.addEntry(e, i, n)); + } + })), r.forEach((n => { + t.push(this.Nr.indexManager.addToCollectionParentIndex(e, n)); + })), t.push(this.Nr.updateMetadata(e, n)), PersistencePromise.waitFor(t); + } + getFromCache(e, t) { + // Record the size of everything we load from the cache so we can compute a delta later. + return this.Nr.vr(e, t).next((e => (this.Br.set(t, { + size: e.size, + readTime: e.document.readTime + }), e.document))); + } + getAllFromCache(e, t) { + // Record the size of everything we load from the cache so we can compute + // a delta later. + return this.Nr.Mr(e, t).next((({documents: e, Or: t}) => ( + // Note: `getAllFromCache` returns two maps instead of a single map from + // keys to `DocumentSizeEntry`s. This is to allow returning the + // `MutableDocumentMap` directly, without a conversion. + t.forEach(((t, n) => { + this.Br.set(t, { + size: n, + readTime: e.get(t).readTime + }); + })), e))); + } +} + +function __PRIVATE_documentGlobalStore(e) { + return __PRIVATE_getStore(e, Ie); +} + +/** + * Helper to get a typed SimpleDbStore for the remoteDocuments object store. + */ function __PRIVATE_remoteDocumentsStore(e) { + return __PRIVATE_getStore(e, ue); +} + +/** + * Returns a key that can be used for document lookups on the + * `DbRemoteDocumentDocumentKeyIndex` index. + */ function __PRIVATE_dbKey(e) { + const t = e.path.toArray(); + return [ + /* prefix path */ t.slice(0, t.length - 2), + /* collection id */ t[t.length - 2], + /* document id */ t[t.length - 1] ]; +} + +function __PRIVATE_dbCollectionGroupKey(e, t) { + const n = t.documentKey.path.toArray(); + return [ + /* collection id */ e, __PRIVATE_toDbTimestampKey(t.readTime), + /* prefix path */ n.slice(0, n.length - 2), + /* document id */ n.length > 0 ? n[n.length - 1] : "" ]; +} + +/** + * Comparator that compares document keys according to the primary key sorting + * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id + * and then document ID). + * + * Visible for testing. + */ function __PRIVATE_dbKeyComparator(e, t) { + const n = e.path.toArray(), r = t.path.toArray(); + // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74 + let i = 0; + for (let e = 0; e < n.length - 2 && e < r.length - 2; ++e) if (i = __PRIVATE_primitiveComparator(n[e], r[e]), + i) return i; + return i = __PRIVATE_primitiveComparator(n.length, r.length), i || (i = __PRIVATE_primitiveComparator(n[n.length - 2], r[r.length - 2]), + i || __PRIVATE_primitiveComparator(n[n.length - 1], r[r.length - 1])); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Schema Version for the Web client: + * 1. Initial version including Mutation Queue, Query Cache, and Remote + * Document Cache + * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No + * longer required because migration 3 unconditionally clears it. + * 3. Dropped and re-created Query Cache to deal with cache corruption related + * to limbo resolution. Addresses + * https://github.com/firebase/firebase-ios-sdk/issues/1548 + * 4. Multi-Tab Support. + * 5. Removal of held write acks. + * 6. Create document global for tracking document cache size. + * 7. Ensure every cached document has a sentinel row with a sequence number. + * 8. Add collection-parent index for Collection Group queries. + * 9. Change RemoteDocumentChanges store to be keyed by readTime rather than + * an auto-incrementing ID. This is required for Index-Free queries. + * 10. Rewrite the canonical IDs to the explicit Protobuf-based format. + * 11. Add bundles and named_queries for bundle support. + * 12. Add document overlays. + * 13. Rewrite the keys of the remote document cache to allow for efficient + * document lookup via `getAll()`. + * 14. Add overlays. + * 15. Add indexing support. + * 16. Parse timestamp strings before creating index entries. + * 17. TODO(tomandersen) + * 18. Encode key safe representations of IndexEntry in DbIndexEntryStore. + */ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a local view (overlay) of a document, and the fields that are + * locally mutated. + */ +class OverlayedDocument { + constructor(e, + /** + * The fields that are locally mutated by patch mutations. + * + * If the overlayed document is from set or delete mutations, this is `null`. + * If there is no overlay (mutation) for the document, this is an empty `FieldMask`. + */ + t) { + this.overlayedDocument = e, this.mutatedFields = t; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A readonly view of the local state of all documents we're tracking (i.e. we + * have a cached version in remoteDocumentCache or local mutations for the + * document). The view is computed by applying the mutations in the + * MutationQueue to the RemoteDocumentCache. + */ class LocalDocumentsView { + constructor(e, t, n, r) { + this.remoteDocumentCache = e, this.mutationQueue = t, this.documentOverlayCache = n, + this.indexManager = r; + } + /** + * Get the local view of the document identified by `key`. + * + * @returns Local view of the document or null if we don't have any cached + * state for it. + */ getDocument(e, t) { + let n = null; + return this.documentOverlayCache.getOverlay(e, t).next((r => (n = r, this.remoteDocumentCache.getEntry(e, t)))).next((e => (null !== n && __PRIVATE_mutationApplyToLocalView(n.mutation, e, FieldMask.empty(), Timestamp.now()), + e))); + } + /** + * Gets the local view of the documents identified by `keys`. + * + * If we don't have cached state for a document in `keys`, a NoDocument will + * be stored for that key in the resulting set. + */ getDocuments(e, t) { + return this.remoteDocumentCache.getEntries(e, t).next((t => this.getLocalViewOfDocuments(e, t, __PRIVATE_documentKeySet()).next((() => t)))); + } + /** + * Similar to `getDocuments`, but creates the local view from the given + * `baseDocs` without retrieving documents from the local store. + * + * @param transaction - The transaction this operation is scoped to. + * @param docs - The documents to apply local mutations to get the local views. + * @param existenceStateChanged - The set of document keys whose existence state + * is changed. This is useful to determine if some documents overlay needs + * to be recalculated. + */ getLocalViewOfDocuments(e, t, n = __PRIVATE_documentKeySet()) { + const r = __PRIVATE_newOverlayMap(); + return this.populateOverlays(e, r, t).next((() => this.computeViews(e, t, r, n).next((e => { + let t = documentMap(); + return e.forEach(((e, n) => { + t = t.insert(e, n.overlayedDocument); + })), t; + })))); + } + /** + * Gets the overlayed documents for the given document map, which will include + * the local view of those documents and a `FieldMask` indicating which fields + * are mutated locally, `null` if overlay is a Set or Delete mutation. + */ getOverlayedDocuments(e, t) { + const n = __PRIVATE_newOverlayMap(); + return this.populateOverlays(e, n, t).next((() => this.computeViews(e, t, n, __PRIVATE_documentKeySet()))); + } + /** + * Fetches the overlays for {@code docs} and adds them to provided overlay map + * if the map does not already contain an entry for the given document key. + */ populateOverlays(e, t, n) { + const r = []; + return n.forEach((e => { + t.has(e) || r.push(e); + })), this.documentOverlayCache.getOverlays(e, r).next((e => { + e.forEach(((e, n) => { + t.set(e, n); + })); + })); + } + /** + * Computes the local view for the given documents. + * + * @param docs - The documents to compute views for. It also has the base + * version of the documents. + * @param overlays - The overlays that need to be applied to the given base + * version of the documents. + * @param existenceStateChanged - A set of documents whose existence states + * might have changed. This is used to determine if we need to re-calculate + * overlays from mutation queues. + * @return A map represents the local documents view. + */ computeViews(e, t, n, r) { + let i = __PRIVATE_mutableDocumentMap(); + const s = __PRIVATE_newDocumentKeyMap(), o = function __PRIVATE_newOverlayedDocumentMap() { + return __PRIVATE_newDocumentKeyMap(); + }(); + return t.forEach(((e, t) => { + const o = n.get(t.key); + // Recalculate an overlay if the document's existence state changed due to + // a remote event *and* the overlay is a PatchMutation. This is because + // document existence state can change if some patch mutation's + // preconditions are met. + // NOTE: we recalculate when `overlay` is undefined as well, because there + // might be a patch mutation whose precondition does not match before the + // change (hence overlay is undefined), but would now match. + r.has(t.key) && (void 0 === o || o.mutation instanceof __PRIVATE_PatchMutation) ? i = i.insert(t.key, t) : void 0 !== o ? (s.set(t.key, o.mutation.getFieldMask()), + __PRIVATE_mutationApplyToLocalView(o.mutation, t, o.mutation.getFieldMask(), Timestamp.now())) : + // no overlay exists + // Using EMPTY to indicate there is no overlay for the document. + s.set(t.key, FieldMask.empty()); + })), this.recalculateAndSaveOverlays(e, i).next((e => (e.forEach(((e, t) => s.set(e, t))), + t.forEach(((e, t) => o.set(e, new OverlayedDocument(t, s.get(e) ?? null)))), o))); + } + recalculateAndSaveOverlays(e, t) { + const n = __PRIVATE_newDocumentKeyMap(); + // A reverse lookup map from batch id to the documents within that batch. + let r = new SortedMap(((e, t) => e - t)), i = __PRIVATE_documentKeySet(); + return this.mutationQueue.getAllMutationBatchesAffectingDocumentKeys(e, t).next((e => { + for (const i of e) i.keys().forEach((e => { + const s = t.get(e); + if (null === s) return; + let o = n.get(e) || FieldMask.empty(); + o = i.applyToLocalView(s, o), n.set(e, o); + const _ = (r.get(i.batchId) || __PRIVATE_documentKeySet()).add(e); + r = r.insert(i.batchId, _); + })); + })).next((() => { + const s = [], o = r.getReverseIterator(); + // Iterate in descending order of batch IDs, and skip documents that are + // already saved. + for (;o.hasNext(); ) { + const r = o.getNext(), _ = r.key, a = r.value, u = __PRIVATE_newMutationMap(); + a.forEach((e => { + if (!i.has(e)) { + const r = __PRIVATE_calculateOverlayMutation(t.get(e), n.get(e)); + null !== r && u.set(e, r), i = i.add(e); + } + })), s.push(this.documentOverlayCache.saveOverlays(e, _, u)); + } + return PersistencePromise.waitFor(s); + })).next((() => n)); + } + /** + * Recalculates overlays by reading the documents from remote document cache + * first, and saves them after they are calculated. + */ recalculateAndSaveOverlaysForDocumentKeys(e, t) { + return this.remoteDocumentCache.getEntries(e, t).next((t => this.recalculateAndSaveOverlays(e, t))); + } + /** + * Performs a query against the local view of all documents. + * + * @param transaction - The persistence transaction. + * @param query - The query to match documents against. + * @param offset - Read time and key to start scanning by (exclusive). + * @param context - A optional tracker to keep a record of important details + * during database local query execution. + */ getDocumentsMatchingQuery(e, t, n, r) { + /** + * Returns whether the query matches a single document by path (rather than a + * collection). + */ + return function __PRIVATE_isDocumentQuery$1(e) { + return DocumentKey.isDocumentKey(e.path) && null === e.collectionGroup && 0 === e.filters.length; + }(t) ? this.getDocumentsMatchingDocumentQuery(e, t.path) : __PRIVATE_isCollectionGroupQuery(t) ? this.getDocumentsMatchingCollectionGroupQuery(e, t, n, r) : this.getDocumentsMatchingCollectionQuery(e, t, n, r); + } + /** + * Given a collection group, returns the next documents that follow the provided offset, along + * with an updated batch ID. + * + *

The documents returned by this method are ordered by remote version from the provided + * offset. If there are no more remote documents after the provided offset, documents with + * mutations in order of batch id from the offset are returned. Since all documents in a batch are + * returned together, the total number of documents returned can exceed {@code count}. + * + * @param transaction + * @param collectionGroup The collection group for the documents. + * @param offset The offset to index into. + * @param count The number of documents to return + * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id. + */ getNextDocuments(e, t, n, r) { + return this.remoteDocumentCache.getAllFromCollectionGroup(e, t, n, r).next((i => { + const s = r - i.size > 0 ? this.documentOverlayCache.getOverlaysForCollectionGroup(e, t, n.largestBatchId, r - i.size) : PersistencePromise.resolve(__PRIVATE_newOverlayMap()); + // The callsite will use the largest batch ID together with the latest read time to create + // a new index offset. Since we only process batch IDs if all remote documents have been read, + // no overlay will increase the overall read time. This is why we only need to special case + // the batch id. + let o = W, _ = i; + return s.next((t => PersistencePromise.forEach(t, ((t, n) => (o < n.largestBatchId && (o = n.largestBatchId), + i.get(t) ? PersistencePromise.resolve() : this.remoteDocumentCache.getEntry(e, t).next((e => { + _ = _.insert(t, e); + }))))).next((() => this.populateOverlays(e, t, i))).next((() => this.computeViews(e, _, t, __PRIVATE_documentKeySet()))).next((e => ({ + batchId: o, + changes: __PRIVATE_convertOverlayedDocumentMapToDocumentMap(e) + }))))); + })); + } + getDocumentsMatchingDocumentQuery(e, t) { + // Just do a simple document lookup. + return this.getDocument(e, new DocumentKey(t)).next((e => { + let t = documentMap(); + return e.isFoundDocument() && (t = t.insert(e.key, e)), t; + })); + } + getDocumentsMatchingCollectionGroupQuery(e, t, n, r) { + const i = t.collectionGroup; + let s = documentMap(); + return this.indexManager.getCollectionParents(e, i).next((o => PersistencePromise.forEach(o, (o => { + const _ = function __PRIVATE_asCollectionQueryAtPath(e, t) { + return new __PRIVATE_QueryImpl(t, + /*collectionGroup=*/ null, e.explicitOrderBy.slice(), e.filters.slice(), e.limit, e.limitType, e.startAt, e.endAt); + }(t, o.child(i)); + return this.getDocumentsMatchingCollectionQuery(e, _, n, r).next((e => { + e.forEach(((e, t) => { + s = s.insert(e, t); + })); + })); + })).next((() => s)))); + } + getDocumentsMatchingCollectionQuery(e, t, n, r) { + // Query the remote documents and overlay mutations. + let i; + return this.documentOverlayCache.getOverlaysForCollection(e, t.path, n.largestBatchId).next((s => (i = s, + this.remoteDocumentCache.getDocumentsMatchingQuery(e, t, n, i, r)))).next((e => { + // As documents might match the query because of their overlay we need to + // include documents for all overlays in the initial document set. + i.forEach(((t, n) => { + const r = n.getKey(); + null === e.get(r) && (e = e.insert(r, MutableDocument.newInvalidDocument(r))); + })); + // Apply the overlays and match against the query. + let n = documentMap(); + return e.forEach(((e, r) => { + const s = i.get(e); + void 0 !== s && __PRIVATE_mutationApplyToLocalView(s.mutation, r, FieldMask.empty(), Timestamp.now()), + // Finally, insert the documents that still match the query + __PRIVATE_queryMatches(t, r) && (n = n.insert(e, r)); + })), n; + })); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_MemoryBundleCache { + constructor(e) { + this.serializer = e, this.Lr = new Map, this.kr = new Map; + } + getBundleMetadata(e, t) { + return PersistencePromise.resolve(this.Lr.get(t)); + } + saveBundleMetadata(e, t) { + return this.Lr.set(t.id, + /** Decodes a BundleMetadata proto into a BundleMetadata object. */ + function __PRIVATE_fromBundleMetadata(e) { + return { + id: e.id, + version: e.version, + createTime: __PRIVATE_fromVersion(e.createTime) + }; + }(t)), PersistencePromise.resolve(); + } + getNamedQuery(e, t) { + return PersistencePromise.resolve(this.kr.get(t)); + } + saveNamedQuery(e, t) { + return this.kr.set(t.name, function __PRIVATE_fromProtoNamedQuery(e) { + return { + name: e.name, + query: __PRIVATE_fromBundledQuery(e.bundledQuery), + readTime: __PRIVATE_fromVersion(e.readTime) + }; + }(t)), PersistencePromise.resolve(); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An in-memory implementation of DocumentOverlayCache. + */ class __PRIVATE_MemoryDocumentOverlayCache { + constructor() { + // A map sorted by DocumentKey, whose value is a pair of the largest batch id + // for the overlay and the overlay itself. + this.overlays = new SortedMap(DocumentKey.comparator), this.qr = new Map; + } + getOverlay(e, t) { + return PersistencePromise.resolve(this.overlays.get(t)); + } + getOverlays(e, t) { + const n = __PRIVATE_newOverlayMap(); + return PersistencePromise.forEach(t, (t => this.getOverlay(e, t).next((e => { + null !== e && n.set(t, e); + })))).next((() => n)); + } + saveOverlays(e, t, n) { + return n.forEach(((n, r) => { + this.St(e, t, r); + })), PersistencePromise.resolve(); + } + removeOverlaysForBatchId(e, t, n) { + const r = this.qr.get(n); + return void 0 !== r && (r.forEach((e => this.overlays = this.overlays.remove(e))), + this.qr.delete(n)), PersistencePromise.resolve(); + } + getOverlaysForCollection(e, t, n) { + const r = __PRIVATE_newOverlayMap(), i = t.length + 1, s = new DocumentKey(t.child("")), o = this.overlays.getIteratorFrom(s); + for (;o.hasNext(); ) { + const e = o.getNext().value, s = e.getKey(); + if (!t.isPrefixOf(s.path)) break; + // Documents from sub-collections + s.path.length === i && (e.largestBatchId > n && r.set(e.getKey(), e)); + } + return PersistencePromise.resolve(r); + } + getOverlaysForCollectionGroup(e, t, n, r) { + let i = new SortedMap(((e, t) => e - t)); + const s = this.overlays.getIterator(); + for (;s.hasNext(); ) { + const e = s.getNext().value; + if (e.getKey().getCollectionGroup() === t && e.largestBatchId > n) { + let t = i.get(e.largestBatchId); + null === t && (t = __PRIVATE_newOverlayMap(), i = i.insert(e.largestBatchId, t)), + t.set(e.getKey(), e); + } + } + const o = __PRIVATE_newOverlayMap(), _ = i.getIterator(); + for (;_.hasNext(); ) { + if (_.getNext().value.forEach(((e, t) => o.set(e, t))), o.size() >= r) break; + } + return PersistencePromise.resolve(o); + } + St(e, t, n) { + // Remove the association of the overlay to its batch id. + const r = this.overlays.get(n.key); + if (null !== r) { + const e = this.qr.get(r.largestBatchId).delete(n.key); + this.qr.set(r.largestBatchId, e); + } + this.overlays = this.overlays.insert(n.key, new Overlay(t, n)); + // Create the association of this overlay to the given largestBatchId. + let i = this.qr.get(t); + void 0 === i && (i = __PRIVATE_documentKeySet(), this.qr.set(t, i)), this.qr.set(t, i.add(n.key)); + } +} + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_MemoryGlobalsCache { + constructor() { + this.sessionToken = ByteString.EMPTY_BYTE_STRING; + } + getSessionToken(e) { + return PersistencePromise.resolve(this.sessionToken); + } + setSessionToken(e, t) { + return this.sessionToken = t, PersistencePromise.resolve(); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A collection of references to a document from some kind of numbered entity + * (either a target ID or batch ID). As references are added to or removed from + * the set corresponding events are emitted to a registered garbage collector. + * + * Each reference is represented by a DocumentReference object. Each of them + * contains enough information to uniquely identify the reference. They are all + * stored primarily in a set sorted by key. A document is considered garbage if + * there's no references in that set (this can be efficiently checked thanks to + * sorting by key). + * + * ReferenceSet also keeps a secondary set that contains references sorted by + * IDs. This one is used to efficiently implement removal of all references by + * some target ID. + */ class __PRIVATE_ReferenceSet { + constructor() { + // A set of outstanding references to a document sorted by key. + this.Qr = new SortedSet(__PRIVATE_DocReference.$r), + // A set of outstanding references to a document sorted by target id. + this.Ur = new SortedSet(__PRIVATE_DocReference.Kr); + } + /** Returns true if the reference set contains no references. */ isEmpty() { + return this.Qr.isEmpty(); + } + /** Adds a reference to the given document key for the given ID. */ addReference(e, t) { + const n = new __PRIVATE_DocReference(e, t); + this.Qr = this.Qr.add(n), this.Ur = this.Ur.add(n); + } + /** Add references to the given document keys for the given ID. */ Wr(e, t) { + e.forEach((e => this.addReference(e, t))); + } + /** + * Removes a reference to the given document key for the given + * ID. + */ removeReference(e, t) { + this.Gr(new __PRIVATE_DocReference(e, t)); + } + zr(e, t) { + e.forEach((e => this.removeReference(e, t))); + } + /** + * Clears all references with a given ID. Calls removeRef() for each key + * removed. + */ jr(e) { + const t = new DocumentKey(new ResourcePath([])), n = new __PRIVATE_DocReference(t, e), r = new __PRIVATE_DocReference(t, e + 1), i = []; + return this.Ur.forEachInRange([ n, r ], (e => { + this.Gr(e), i.push(e.key); + })), i; + } + Jr() { + this.Qr.forEach((e => this.Gr(e))); + } + Gr(e) { + this.Qr = this.Qr.delete(e), this.Ur = this.Ur.delete(e); + } + Hr(e) { + const t = new DocumentKey(new ResourcePath([])), n = new __PRIVATE_DocReference(t, e), r = new __PRIVATE_DocReference(t, e + 1); + let i = __PRIVATE_documentKeySet(); + return this.Ur.forEachInRange([ n, r ], (e => { + i = i.add(e.key); + })), i; + } + containsKey(e) { + const t = new __PRIVATE_DocReference(e, 0), n = this.Qr.firstAfterOrEqual(t); + return null !== n && e.isEqual(n.key); + } +} + +class __PRIVATE_DocReference { + constructor(e, t) { + this.key = e, this.Yr = t; + } + /** Compare by key then by ID */ static $r(e, t) { + return DocumentKey.comparator(e.key, t.key) || __PRIVATE_primitiveComparator(e.Yr, t.Yr); + } + /** Compare by ID then by key */ static Kr(e, t) { + return __PRIVATE_primitiveComparator(e.Yr, t.Yr) || DocumentKey.comparator(e.key, t.key); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_MemoryMutationQueue { + constructor(e, t) { + this.indexManager = e, this.referenceDelegate = t, + /** + * The set of all mutations that have been sent but not yet been applied to + * the backend. + */ + this.mutationQueue = [], + /** Next value to use when assigning sequential IDs to each mutation batch. */ + this.tr = 1, + /** An ordered mapping between documents and the mutations batch IDs. */ + this.Zr = new SortedSet(__PRIVATE_DocReference.$r); + } + checkEmpty(e) { + return PersistencePromise.resolve(0 === this.mutationQueue.length); + } + addMutationBatch(e, t, n, r) { + const i = this.tr; + this.tr++, this.mutationQueue.length > 0 && this.mutationQueue[this.mutationQueue.length - 1]; + const s = new MutationBatch(i, t, n, r); + this.mutationQueue.push(s); + // Track references by document key and index collection parents. + for (const t of r) this.Zr = this.Zr.add(new __PRIVATE_DocReference(t.key, i)), + this.indexManager.addToCollectionParentIndex(e, t.key.path.popLast()); + return PersistencePromise.resolve(s); + } + lookupMutationBatch(e, t) { + return PersistencePromise.resolve(this.Xr(t)); + } + getNextMutationBatchAfterBatchId(e, t) { + const n = t + 1, r = this.ei(n), i = r < 0 ? 0 : r; + // The requested batchId may still be out of range so normalize it to the + // start of the queue. + return PersistencePromise.resolve(this.mutationQueue.length > i ? this.mutationQueue[i] : null); + } + getHighestUnacknowledgedBatchId() { + return PersistencePromise.resolve(0 === this.mutationQueue.length ? H : this.tr - 1); + } + getAllMutationBatches(e) { + return PersistencePromise.resolve(this.mutationQueue.slice()); + } + getAllMutationBatchesAffectingDocumentKey(e, t) { + const n = new __PRIVATE_DocReference(t, 0), r = new __PRIVATE_DocReference(t, Number.POSITIVE_INFINITY), i = []; + return this.Zr.forEachInRange([ n, r ], (e => { + const t = this.Xr(e.Yr); + i.push(t); + })), PersistencePromise.resolve(i); + } + getAllMutationBatchesAffectingDocumentKeys(e, t) { + let n = new SortedSet(__PRIVATE_primitiveComparator); + return t.forEach((e => { + const t = new __PRIVATE_DocReference(e, 0), r = new __PRIVATE_DocReference(e, Number.POSITIVE_INFINITY); + this.Zr.forEachInRange([ t, r ], (e => { + n = n.add(e.Yr); + })); + })), PersistencePromise.resolve(this.ti(n)); + } + getAllMutationBatchesAffectingQuery(e, t) { + // Use the query path as a prefix for testing if a document matches the + // query. + const n = t.path, r = n.length + 1; + // Construct a document reference for actually scanning the index. Unlike + // the prefix the document key in this reference must have an even number of + // segments. The empty segment can be used a suffix of the query path + // because it precedes all other segments in an ordered traversal. + let i = n; + DocumentKey.isDocumentKey(i) || (i = i.child("")); + const s = new __PRIVATE_DocReference(new DocumentKey(i), 0); + // Find unique batchIDs referenced by all documents potentially matching the + // query. + let o = new SortedSet(__PRIVATE_primitiveComparator); + return this.Zr.forEachWhile((e => { + const t = e.key.path; + return !!n.isPrefixOf(t) && ( + // Rows with document keys more than one segment longer than the query + // path can't be matches. For example, a query on 'rooms' can't match + // the document /rooms/abc/messages/xyx. + // TODO(mcg): we'll need a different scanner when we implement + // ancestor queries. + t.length === r && (o = o.add(e.Yr)), !0); + }), s), PersistencePromise.resolve(this.ti(o)); + } + ti(e) { + // Construct an array of matching batches, sorted by batchID to ensure that + // multiple mutations affecting the same document key are applied in order. + const t = []; + return e.forEach((e => { + const n = this.Xr(e); + null !== n && t.push(n); + })), t; + } + removeMutationBatch(e, t) { + __PRIVATE_hardAssert(0 === this.ni(t.batchId, "removed"), 55003), this.mutationQueue.shift(); + let n = this.Zr; + return PersistencePromise.forEach(t.mutations, (r => { + const i = new __PRIVATE_DocReference(r.key, t.batchId); + return n = n.delete(i), this.referenceDelegate.markPotentiallyOrphaned(e, r.key); + })).next((() => { + this.Zr = n; + })); + } + ir(e) { + // No-op since the memory mutation queue does not maintain a separate cache. + } + containsKey(e, t) { + const n = new __PRIVATE_DocReference(t, 0), r = this.Zr.firstAfterOrEqual(n); + return PersistencePromise.resolve(t.isEqual(r && r.key)); + } + performConsistencyCheck(e) { + return this.mutationQueue.length, PersistencePromise.resolve(); + } + /** + * Finds the index of the given batchId in the mutation queue and asserts that + * the resulting index is within the bounds of the queue. + * + * @param batchId - The batchId to search for + * @param action - A description of what the caller is doing, phrased in passive + * form (e.g. "acknowledged" in a routine that acknowledges batches). + */ ni(e, t) { + return this.ei(e); + } + /** + * Finds the index of the given batchId in the mutation queue. This operation + * is O(1). + * + * @returns The computed index of the batch with the given batchId, based on + * the state of the queue. Note this index can be negative if the requested + * batchId has already been removed from the queue or past the end of the + * queue if the batchId is larger than the last added batch. + */ ei(e) { + if (0 === this.mutationQueue.length) + // As an index this is past the end of the queue + return 0; + // Examine the front of the queue to figure out the difference between the + // batchId and indexes in the array. Note that since the queue is ordered + // by batchId, if the first batch has a larger batchId then the requested + // batchId doesn't exist in the queue. + return e - this.mutationQueue[0].batchId; + } + /** + * A version of lookupMutationBatch that doesn't return a promise, this makes + * other functions that uses this code easier to read and more efficient. + */ Xr(e) { + const t = this.ei(e); + if (t < 0 || t >= this.mutationQueue.length) return null; + return this.mutationQueue[t]; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The smallest value representable by a 64-bit signed integer (long). + */ +/** + * The memory-only RemoteDocumentCache for IndexedDb. To construct, invoke + * `newMemoryRemoteDocumentCache()`. + */ +class __PRIVATE_MemoryRemoteDocumentCacheImpl { + /** + * @param sizer - Used to assess the size of a document. For eager GC, this is + * expected to just return 0 to avoid unnecessarily doing the work of + * calculating the size. + */ + constructor(e) { + this.ri = e, + /** Underlying cache of documents and their read times. */ + this.docs = function __PRIVATE_documentEntryMap() { + return new SortedMap(DocumentKey.comparator); + }(), + /** Size of all cached documents. */ + this.size = 0; + } + setIndexManager(e) { + this.indexManager = e; + } + /** + * Adds the supplied entry to the cache and updates the cache size as appropriate. + * + * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer + * returned by `newChangeBuffer()`. + */ addEntry(e, t) { + const n = t.key, r = this.docs.get(n), i = r ? r.size : 0, s = this.ri(t); + return this.docs = this.docs.insert(n, { + document: t.mutableCopy(), + size: s + }), this.size += s - i, this.indexManager.addToCollectionParentIndex(e, n.path.popLast()); + } + /** + * Removes the specified entry from the cache and updates the cache size as appropriate. + * + * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer + * returned by `newChangeBuffer()`. + */ removeEntry(e) { + const t = this.docs.get(e); + t && (this.docs = this.docs.remove(e), this.size -= t.size); + } + getEntry(e, t) { + const n = this.docs.get(t); + return PersistencePromise.resolve(n ? n.document.mutableCopy() : MutableDocument.newInvalidDocument(t)); + } + getEntries(e, t) { + let n = __PRIVATE_mutableDocumentMap(); + return t.forEach((e => { + const t = this.docs.get(e); + n = n.insert(e, t ? t.document.mutableCopy() : MutableDocument.newInvalidDocument(e)); + })), PersistencePromise.resolve(n); + } + getDocumentsMatchingQuery(e, t, n, r) { + let i = __PRIVATE_mutableDocumentMap(); + // Documents are ordered by key, so we can use a prefix scan to narrow down + // the documents we need to match the query against. + const s = t.path, o = new DocumentKey(s.child("__id-9223372036854775808__")), _ = this.docs.getIteratorFrom(o); + // Document keys are ordered first by numeric value ("__id__"), + // then lexicographically by string value. Start the iterator at the minimum + // possible Document key value. + for (;_.hasNext(); ) { + const {key: e, value: {document: o}} = _.getNext(); + if (!s.isPrefixOf(e.path)) break; + e.path.length > s.length + 1 || (__PRIVATE_indexOffsetComparator(__PRIVATE_newIndexOffsetFromDocument(o), n) <= 0 || (r.has(o.key) || __PRIVATE_queryMatches(t, o)) && (i = i.insert(o.key, o.mutableCopy()))); + } + return PersistencePromise.resolve(i); + } + getAllFromCollectionGroup(e, t, n, r) { + // This method should only be called from the IndexBackfiller if persistence + // is enabled. + fail(9500); + } + ii(e, t) { + return PersistencePromise.forEach(this.docs, (e => t(e))); + } + newChangeBuffer(e) { + // `trackRemovals` is ignores since the MemoryRemoteDocumentCache keeps + // a separate changelog and does not need special handling for removals. + return new __PRIVATE_MemoryRemoteDocumentChangeBuffer(this); + } + getSize(e) { + return PersistencePromise.resolve(this.size); + } +} + +/** + * Creates a new memory-only RemoteDocumentCache. + * + * @param sizer - Used to assess the size of a document. For eager GC, this is + * expected to just return 0 to avoid unnecessarily doing the work of + * calculating the size. + */ +/** + * Handles the details of adding and updating documents in the MemoryRemoteDocumentCache. + */ +class __PRIVATE_MemoryRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer { + constructor(e) { + super(), this.Nr = e; + } + applyChanges(e) { + const t = []; + return this.changes.forEach(((n, r) => { + r.isValidDocument() ? t.push(this.Nr.addEntry(e, r)) : this.Nr.removeEntry(n); + })), PersistencePromise.waitFor(t); + } + getFromCache(e, t) { + return this.Nr.getEntry(e, t); + } + getAllFromCache(e, t) { + return this.Nr.getEntries(e, t); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_MemoryTargetCache { + constructor(e) { + this.persistence = e, + /** + * Maps a target to the data about that target + */ + this.si = new ObjectMap((e => __PRIVATE_canonifyTarget(e)), __PRIVATE_targetEquals), + /** The last received snapshot version. */ + this.lastRemoteSnapshotVersion = SnapshotVersion.min(), + /** The highest numbered target ID encountered. */ + this.highestTargetId = 0, + /** The highest sequence number encountered. */ + this.oi = 0, + /** + * A ordered bidirectional mapping between documents and the remote target + * IDs. + */ + this._i = new __PRIVATE_ReferenceSet, this.targetCount = 0, this.ai = __PRIVATE_TargetIdGenerator.ur(); + } + forEachTarget(e, t) { + return this.si.forEach(((e, n) => t(n))), PersistencePromise.resolve(); + } + getLastRemoteSnapshotVersion(e) { + return PersistencePromise.resolve(this.lastRemoteSnapshotVersion); + } + getHighestSequenceNumber(e) { + return PersistencePromise.resolve(this.oi); + } + allocateTargetId(e) { + return this.highestTargetId = this.ai.next(), PersistencePromise.resolve(this.highestTargetId); + } + setTargetsMetadata(e, t, n) { + return n && (this.lastRemoteSnapshotVersion = n), t > this.oi && (this.oi = t), + PersistencePromise.resolve(); + } + Pr(e) { + this.si.set(e.target, e); + const t = e.targetId; + t > this.highestTargetId && (this.ai = new __PRIVATE_TargetIdGenerator(t), this.highestTargetId = t), + e.sequenceNumber > this.oi && (this.oi = e.sequenceNumber); + } + addTargetData(e, t) { + return this.Pr(t), this.targetCount += 1, PersistencePromise.resolve(); + } + updateTargetData(e, t) { + return this.Pr(t), PersistencePromise.resolve(); + } + removeTargetData(e, t) { + return this.si.delete(t.target), this._i.jr(t.targetId), this.targetCount -= 1, + PersistencePromise.resolve(); + } + removeTargets(e, t, n) { + let r = 0; + const i = []; + return this.si.forEach(((s, o) => { + o.sequenceNumber <= t && null === n.get(o.targetId) && (this.si.delete(s), i.push(this.removeMatchingKeysForTargetId(e, o.targetId)), + r++); + })), PersistencePromise.waitFor(i).next((() => r)); + } + getTargetCount(e) { + return PersistencePromise.resolve(this.targetCount); + } + getTargetData(e, t) { + const n = this.si.get(t) || null; + return PersistencePromise.resolve(n); + } + addMatchingKeys(e, t, n) { + return this._i.Wr(t, n), PersistencePromise.resolve(); + } + removeMatchingKeys(e, t, n) { + this._i.zr(t, n); + const r = this.persistence.referenceDelegate, i = []; + return r && t.forEach((t => { + i.push(r.markPotentiallyOrphaned(e, t)); + })), PersistencePromise.waitFor(i); + } + removeMatchingKeysForTargetId(e, t) { + return this._i.jr(t), PersistencePromise.resolve(); + } + getMatchingKeysForTargetId(e, t) { + const n = this._i.Hr(t); + return PersistencePromise.resolve(n); + } + containsKey(e, t) { + return PersistencePromise.resolve(this._i.containsKey(t)); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A memory-backed instance of Persistence. Data is stored only in RAM and + * not persisted across sessions. + */ +class __PRIVATE_MemoryPersistence { + /** + * The constructor accepts a factory for creating a reference delegate. This + * allows both the delegate and this instance to have strong references to + * each other without having nullable fields that would then need to be + * checked or asserted on every access. + */ + constructor(e, t) { + this.ui = {}, this.overlays = {}, this.ci = new __PRIVATE_ListenSequence(0), this.li = !1, + this.li = !0, this.hi = new __PRIVATE_MemoryGlobalsCache, this.referenceDelegate = e(this), + this.Pi = new __PRIVATE_MemoryTargetCache(this); + this.indexManager = new __PRIVATE_MemoryIndexManager, this.remoteDocumentCache = function __PRIVATE_newMemoryRemoteDocumentCache(e) { + return new __PRIVATE_MemoryRemoteDocumentCacheImpl(e); + }((e => this.referenceDelegate.Ti(e))), this.serializer = new __PRIVATE_LocalSerializer(t), + this.Ii = new __PRIVATE_MemoryBundleCache(this.serializer); + } + start() { + return Promise.resolve(); + } + shutdown() { + // No durable state to ensure is closed on shutdown. + return this.li = !1, Promise.resolve(); + } + get started() { + return this.li; + } + setDatabaseDeletedListener() { + // No op. + } + setNetworkEnabled() { + // No op. + } + getIndexManager(e) { + // We do not currently support indices for memory persistence, so we can + // return the same shared instance of the memory index manager. + return this.indexManager; + } + getDocumentOverlayCache(e) { + let t = this.overlays[e.toKey()]; + return t || (t = new __PRIVATE_MemoryDocumentOverlayCache, this.overlays[e.toKey()] = t), + t; + } + getMutationQueue(e, t) { + let n = this.ui[e.toKey()]; + return n || (n = new __PRIVATE_MemoryMutationQueue(t, this.referenceDelegate), this.ui[e.toKey()] = n), + n; + } + getGlobalsCache() { + return this.hi; + } + getTargetCache() { + return this.Pi; + } + getRemoteDocumentCache() { + return this.remoteDocumentCache; + } + getBundleCache() { + return this.Ii; + } + runTransaction(e, t, n) { + __PRIVATE_logDebug("MemoryPersistence", "Starting transaction:", e); + const r = new __PRIVATE_MemoryTransaction(this.ci.next()); + return this.referenceDelegate.Ei(), n(r).next((e => this.referenceDelegate.di(r).next((() => e)))).toPromise().then((e => (r.raiseOnCommittedEvent(), + e))); + } + Ai(e, t) { + return PersistencePromise.or(Object.values(this.ui).map((n => () => n.containsKey(e, t)))); + } +} + +/** + * Memory persistence is not actually transactional, but future implementations + * may have transaction-scoped state. + */ class __PRIVATE_MemoryTransaction extends PersistenceTransaction { + constructor(e) { + super(), this.currentSequenceNumber = e; + } +} + +class __PRIVATE_MemoryEagerDelegate { + constructor(e) { + this.persistence = e, + /** Tracks all documents that are active in Query views. */ + this.Ri = new __PRIVATE_ReferenceSet, + /** The list of documents that are potentially GCed after each transaction. */ + this.Vi = null; + } + static mi(e) { + return new __PRIVATE_MemoryEagerDelegate(e); + } + get fi() { + if (this.Vi) return this.Vi; + throw fail(60996); + } + addReference(e, t, n) { + return this.Ri.addReference(n, t), this.fi.delete(n.toString()), PersistencePromise.resolve(); + } + removeReference(e, t, n) { + return this.Ri.removeReference(n, t), this.fi.add(n.toString()), PersistencePromise.resolve(); + } + markPotentiallyOrphaned(e, t) { + return this.fi.add(t.toString()), PersistencePromise.resolve(); + } + removeTarget(e, t) { + this.Ri.jr(t.targetId).forEach((e => this.fi.add(e.toString()))); + const n = this.persistence.getTargetCache(); + return n.getMatchingKeysForTargetId(e, t.targetId).next((e => { + e.forEach((e => this.fi.add(e.toString()))); + })).next((() => n.removeTargetData(e, t))); + } + Ei() { + this.Vi = new Set; + } + di(e) { + // Remove newly orphaned documents. + const t = this.persistence.getRemoteDocumentCache().newChangeBuffer(); + return PersistencePromise.forEach(this.fi, (n => { + const r = DocumentKey.fromPath(n); + return this.gi(e, r).next((e => { + e || t.removeEntry(r, SnapshotVersion.min()); + })); + })).next((() => (this.Vi = null, t.apply(e)))); + } + updateLimboDocument(e, t) { + return this.gi(e, t).next((e => { + e ? this.fi.delete(t.toString()) : this.fi.add(t.toString()); + })); + } + Ti(e) { + // For eager GC, we don't care about the document size, there are no size thresholds. + return 0; + } + gi(e, t) { + return PersistencePromise.or([ () => PersistencePromise.resolve(this.Ri.containsKey(t)), () => this.persistence.getTargetCache().containsKey(e, t), () => this.persistence.Ai(e, t) ]); + } +} + +class __PRIVATE_MemoryLruDelegate { + constructor(e, t) { + this.persistence = e, this.pi = new ObjectMap((e => __PRIVATE_encodeResourcePath(e.path)), ((e, t) => e.isEqual(t))), + this.garbageCollector = __PRIVATE_newLruGarbageCollector(this, t); + } + static mi(e, t) { + return new __PRIVATE_MemoryLruDelegate(e, t); + } + // No-ops, present so memory persistence doesn't have to care which delegate + // it has. + Ei() {} + di(e) { + return PersistencePromise.resolve(); + } + forEachTarget(e, t) { + return this.persistence.getTargetCache().forEachTarget(e, t); + } + gr(e) { + const t = this.wr(e); + return this.persistence.getTargetCache().getTargetCount(e).next((e => t.next((t => e + t)))); + } + wr(e) { + let t = 0; + return this.pr(e, (e => { + t++; + })).next((() => t)); + } + pr(e, t) { + return PersistencePromise.forEach(this.pi, ((n, r) => this.br(e, n, r).next((e => e ? PersistencePromise.resolve() : t(r))))); + } + removeTargets(e, t, n) { + return this.persistence.getTargetCache().removeTargets(e, t, n); + } + removeOrphanedDocuments(e, t) { + let n = 0; + const r = this.persistence.getRemoteDocumentCache(), i = r.newChangeBuffer(); + return r.ii(e, (r => this.br(e, r, t).next((e => { + e || (n++, i.removeEntry(r, SnapshotVersion.min())); + })))).next((() => i.apply(e))).next((() => n)); + } + markPotentiallyOrphaned(e, t) { + return this.pi.set(t, e.currentSequenceNumber), PersistencePromise.resolve(); + } + removeTarget(e, t) { + const n = t.withSequenceNumber(e.currentSequenceNumber); + return this.persistence.getTargetCache().updateTargetData(e, n); + } + addReference(e, t, n) { + return this.pi.set(n, e.currentSequenceNumber), PersistencePromise.resolve(); + } + removeReference(e, t, n) { + return this.pi.set(n, e.currentSequenceNumber), PersistencePromise.resolve(); + } + updateLimboDocument(e, t) { + return this.pi.set(t, e.currentSequenceNumber), PersistencePromise.resolve(); + } + Ti(e) { + let t = e.key.toString().length; + return e.isFoundDocument() && (t += __PRIVATE_estimateByteSize(e.data.value)), t; + } + br(e, t, n) { + return PersistencePromise.or([ () => this.persistence.Ai(e, t), () => this.persistence.getTargetCache().containsKey(e, t), () => { + const e = this.pi.get(t); + return PersistencePromise.resolve(void 0 !== e && e > n); + } ]); + } + getCacheSize(e) { + return this.persistence.getRemoteDocumentCache().getSize(e); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Performs database creation and schema upgrades. */ class __PRIVATE_SchemaConverter { + constructor(e) { + this.serializer = e; + } + /** + * Performs database creation and schema upgrades. + * + * Note that in production, this method is only ever used to upgrade the schema + * to SCHEMA_VERSION. Different values of toVersion are only used for testing + * and local feature development. + */ k(e, t, n, r) { + const i = new __PRIVATE_SimpleDbTransaction("createOrUpgrade", t); + n < 1 && r >= 1 && (!function __PRIVATE_createPrimaryClientStore(e) { + e.createObjectStore(X); + }(e), function __PRIVATE_createMutationQueue(e) { + e.createObjectStore(te, { + keyPath: ne + }); + const t = e.createObjectStore(re, { + keyPath: ie, + autoIncrement: !0 + }); + t.createIndex(se, oe, { + unique: !0 + }), e.createObjectStore(ae); + } + /** + * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads + * and rewrites all data. + */ (e), __PRIVATE_createQueryCache(e), function __PRIVATE_createLegacyRemoteDocumentCache(e) { + e.createObjectStore(Z); + }(e)); + // Migration 2 to populate the targetGlobal object no longer needed since + // migration 3 unconditionally clears it. + let s = PersistencePromise.resolve(); + return n < 3 && r >= 3 && ( + // Brand new clients don't need to drop and recreate--only clients that + // potentially have corrupt data. + 0 !== n && (!function __PRIVATE_dropQueryCache(e) { + e.deleteObjectStore(Ve), e.deleteObjectStore(de), e.deleteObjectStore(ye); + }(e), __PRIVATE_createQueryCache(e)), s = s.next((() => + /** + * Creates the target global singleton row. + * + * @param txn - The version upgrade transaction for indexeddb + */ + function __PRIVATE_writeEmptyTargetGlobalEntry(e) { + const t = e.store(ye), n = { + highestTargetId: 0, + highestListenSequenceNumber: 0, + lastRemoteSnapshotVersion: SnapshotVersion.min().toTimestamp(), + targetCount: 0 + }; + return t.put(pe, n); + }(i)))), n < 4 && r >= 4 && (0 !== n && ( + // Schema version 3 uses auto-generated keys to generate globally unique + // mutation batch IDs (this was previously ensured internally by the + // client). To migrate to the new schema, we have to read all mutations + // and write them back out. We preserve the existing batch IDs to guarantee + // consistency with other object stores. Any further mutation batch IDs will + // be auto-generated. + s = s.next((() => function __PRIVATE_upgradeMutationBatchSchemaAndMigrateData(e, t) { + const n = t.store(re); + return n.J().next((n => { + e.deleteObjectStore(re); + e.createObjectStore(re, { + keyPath: ie, + autoIncrement: !0 + }).createIndex(se, oe, { + unique: !0 + }); + const r = t.store(re), i = n.map((e => r.put(e))); + return PersistencePromise.waitFor(i); + })); + }(e, i)))), s = s.next((() => { + !function __PRIVATE_createClientMetadataStore(e) { + e.createObjectStore(be, { + keyPath: De + }); + }(e); + }))), n < 5 && r >= 5 && (s = s.next((() => this.yi(i)))), n < 6 && r >= 6 && (s = s.next((() => (function __PRIVATE_createDocumentGlobalStore(e) { + e.createObjectStore(Ie); + }(e), this.wi(i))))), n < 7 && r >= 7 && (s = s.next((() => this.Si(i)))), n < 8 && r >= 8 && (s = s.next((() => this.bi(e, i)))), + n < 9 && r >= 9 && (s = s.next((() => { + // Multi-Tab used to manage its own changelog, but this has been moved + // to the DbRemoteDocument object store itself. Since the previous change + // log only contained transient data, we can drop its object store. + !function __PRIVATE_dropRemoteDocumentChangesStore(e) { + e.objectStoreNames.contains("remoteDocumentChanges") && e.deleteObjectStore("remoteDocumentChanges"); + }(e); + // Note: Schema version 9 used to create a read time index for the + // RemoteDocumentCache. This is now done with schema version 13. + }))), n < 10 && r >= 10 && (s = s.next((() => this.Di(i)))), n < 11 && r >= 11 && (s = s.next((() => { + !function __PRIVATE_createBundlesStore(e) { + e.createObjectStore(Ce, { + keyPath: ve + }); + }(e), function __PRIVATE_createNamedQueriesStore(e) { + e.createObjectStore(Fe, { + keyPath: Me + }); + }(e); + }))), n < 12 && r >= 12 && (s = s.next((() => { + !function __PRIVATE_createDocumentOverlayStore(e) { + const t = e.createObjectStore(Ge, { + keyPath: ze + }); + t.createIndex(je, Je, { + unique: !1 + }), t.createIndex(He, Ye, { + unique: !1 + }); + }(e); + }))), n < 13 && r >= 13 && (s = s.next((() => function __PRIVATE_createRemoteDocumentCache(e) { + const t = e.createObjectStore(ue, { + keyPath: ce + }); + t.createIndex(le, he), t.createIndex(Pe, Te); + }(e))).next((() => this.Ci(e, i))).next((() => e.deleteObjectStore(Z)))), n < 14 && r >= 14 && (s = s.next((() => this.Fi(e, i)))), + n < 15 && r >= 15 && (s = s.next((() => function __PRIVATE_createFieldIndex(e) { + const t = e.createObjectStore(xe, { + keyPath: Oe, + autoIncrement: !0 + }); + t.createIndex(Ne, Be, { + unique: !1 + }); + const n = e.createObjectStore(Le, { + keyPath: ke + }); + n.createIndex(qe, Qe, { + unique: !1 + }); + const r = e.createObjectStore($e, { + keyPath: Ue + }); + r.createIndex(Ke, We, { + unique: !1 + }); + }(e)))), n < 16 && r >= 16 && ( + // Clear the object stores to remove possibly corrupted index entries + s = s.next((() => { + t.objectStore(Le).clear(); + })).next((() => { + t.objectStore($e).clear(); + }))), n < 17 && r >= 17 && (s = s.next((() => { + !function __PRIVATE_createGlobalsStore(e) { + e.createObjectStore(Ze, { + keyPath: Xe + }); + }(e); + }))), n < 18 && r >= 18 && I() && (s = s.next((() => { + t.objectStore(Le).clear(); + })).next((() => { + t.objectStore($e).clear(); + }))), s; + } + wi(e) { + let t = 0; + return e.store(Z).ee(((e, n) => { + t += __PRIVATE_dbDocumentSize(n); + })).next((() => { + const n = { + byteSize: t + }; + return e.store(Ie).put(Ee, n); + })); + } + yi(e) { + const t = e.store(te), n = e.store(re); + return t.J().next((t => PersistencePromise.forEach(t, (t => { + const r = IDBKeyRange.bound([ t.userId, H ], [ t.userId, t.lastAcknowledgedBatchId ]); + return n.J(se, r).next((n => PersistencePromise.forEach(n, (n => { + __PRIVATE_hardAssert(n.userId === t.userId, 18650, "Cannot process batch from unexpected user", { + batchId: n.batchId + }); + const r = __PRIVATE_fromDbMutationBatch(this.serializer, n); + return removeMutationBatch(e, t.userId, r).next((() => {})); + })))); + })))); + } + /** + * Ensures that every document in the remote document cache has a corresponding sentinel row + * with a sequence number. Missing rows are given the most recently used sequence number. + */ Si(e) { + const t = e.store(Ve), n = e.store(Z); + return e.store(ye).get(pe).next((e => { + const r = []; + return n.ee(((n, i) => { + const s = new ResourcePath(n), o = function __PRIVATE_sentinelKey(e) { + return [ 0, __PRIVATE_encodeResourcePath(e) ]; + }(s); + r.push(t.get(o).next((n => n ? PersistencePromise.resolve() : (n => t.put({ + targetId: 0, + path: __PRIVATE_encodeResourcePath(n), + sequenceNumber: e.highestListenSequenceNumber + }))(s)))); + })).next((() => PersistencePromise.waitFor(r))); + })); + } + bi(e, t) { + // Create the index. + e.createObjectStore(we, { + keyPath: Se + }); + const n = t.store(we), r = new __PRIVATE_MemoryCollectionParentIndex, addEntry = e => { + if (r.add(e)) { + const t = e.lastSegment(), r = e.popLast(); + return n.put({ + collectionId: t, + parent: __PRIVATE_encodeResourcePath(r) + }); + } + }; + // Helper to add an index entry iff we haven't already written it. + // Index existing remote documents. + return t.store(Z).ee({ + X: !0 + }, ((e, t) => { + const n = new ResourcePath(e); + return addEntry(n.popLast()); + })).next((() => t.store(ae).ee({ + X: !0 + }, (([e, t, n], r) => { + const i = __PRIVATE_decodeResourcePath(t); + return addEntry(i.popLast()); + })))); + } + Di(e) { + const t = e.store(de); + return t.ee(((e, n) => { + const r = __PRIVATE_fromDbTarget(n), i = __PRIVATE_toDbTarget(this.serializer, r); + return t.put(i); + })); + } + Ci(e, t) { + const n = t.store(Z), r = []; + return n.ee(((e, n) => { + const i = t.store(ue), s = function __PRIVATE_extractKey(e) { + return e.document ? new DocumentKey(ResourcePath.fromString(e.document.name).popFirst(5)) : e.noDocument ? DocumentKey.fromSegments(e.noDocument.path) : e.unknownDocument ? DocumentKey.fromSegments(e.unknownDocument.path) : fail(36783); + } + /** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ (n).path.toArray(), o = { + prefixPath: s.slice(0, s.length - 2), + collectionGroup: s[s.length - 2], + documentId: s[s.length - 1], + readTime: n.readTime || [ 0, 0 ], + unknownDocument: n.unknownDocument, + noDocument: n.noDocument, + document: n.document, + hasCommittedMutations: !!n.hasCommittedMutations + }; + r.push(i.put(o)); + })).next((() => PersistencePromise.waitFor(r))); + } + Fi(e, t) { + const n = t.store(re), r = __PRIVATE_newIndexedDbRemoteDocumentCache(this.serializer), i = new __PRIVATE_MemoryPersistence(__PRIVATE_MemoryEagerDelegate.mi, this.serializer.yt); + return n.J().next((e => { + const n = new Map; + return e.forEach((e => { + let t = n.get(e.userId) ?? __PRIVATE_documentKeySet(); + __PRIVATE_fromDbMutationBatch(this.serializer, e).keys().forEach((e => t = t.add(e))), + n.set(e.userId, t); + })), PersistencePromise.forEach(n, ((e, n) => { + const s = new User(n), o = __PRIVATE_IndexedDbDocumentOverlayCache.wt(this.serializer, s), _ = i.getIndexManager(s), a = __PRIVATE_IndexedDbMutationQueue.wt(s, this.serializer, _, i.referenceDelegate); + return new LocalDocumentsView(r, a, o, _).recalculateAndSaveOverlaysForDocumentKeys(new __PRIVATE_IndexedDbTransaction(t, __PRIVATE_ListenSequence.ce), e).next(); + })); + })); + } +} + +function __PRIVATE_createQueryCache(e) { + e.createObjectStore(Ve, { + keyPath: me + }).createIndex(fe, ge, { + unique: !0 + }); + // NOTE: This is unique only because the TargetId is the suffix. + e.createObjectStore(de, { + keyPath: "targetId" + }).createIndex(Ae, Re, { + unique: !0 + }), e.createObjectStore(ye); +} + +const Qt = "IndexedDbPersistence", $t = 18e5, Ut = 5e3, Kt = "Failed to obtain exclusive access to the persistence layer. To allow shared access, multi-tab synchronization has to be enabled in all tabs. If you are using `experimentalForceOwningTab:true`, make sure that only one tab has persistence enabled at any given time.", Wt = "main"; + +/** + * Oldest acceptable age in milliseconds for client metadata before the client + * is considered inactive and its associated data is garbage collected. + */ +/** + * An IndexedDB-backed instance of Persistence. Data is stored persistently + * across sessions. + * + * On Web only, the Firestore SDKs support shared access to its persistence + * layer. This allows multiple browser tabs to read and write to IndexedDb and + * to synchronize state even without network connectivity. Shared access is + * currently optional and not enabled unless all clients invoke + * `enablePersistence()` with `{synchronizeTabs:true}`. + * + * In multi-tab mode, if multiple clients are active at the same time, the SDK + * will designate one client as the "primary client". An effort is made to pick + * a visible, network-connected and active client, and this client is + * responsible for letting other clients know about its presence. The primary + * client writes a unique client-generated identifier (the client ID) to + * IndexedDb’s "owner" store every 4 seconds. If the primary client fails to + * update this entry, another client can acquire the lease and take over as + * primary. + * + * Some persistence operations in the SDK are designated as primary-client only + * operations. This includes the acknowledgment of mutations and all updates of + * remote documents. The effects of these operations are written to persistence + * and then broadcast to other tabs via LocalStorage (see + * `WebStorageSharedClientState`), which then refresh their state from + * persistence. + * + * Similarly, the primary client listens to notifications sent by secondary + * clients to discover persistence changes written by secondary clients, such as + * the addition of new mutations and query targets. + * + * If multi-tab is not enabled and another tab already obtained the primary + * lease, IndexedDbPersistence enters a failed state and all subsequent + * operations will automatically fail. + * + * Additionally, there is an optimization so that when a tab is closed, the + * primary lease is released immediately (this is especially important to make + * sure that a refreshed tab is able to immediately re-acquire the primary + * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload + * since it is an asynchronous API. So in addition to attempting to give up the + * lease, the leaseholder writes its client ID to a "zombiedClient" entry in + * LocalStorage which acts as an indicator that another tab should go ahead and + * take the primary lease immediately regardless of the current lease timestamp. + * + * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no + * longer optional. + */ +class __PRIVATE_IndexedDbPersistence { + constructor( + /** + * Whether to synchronize the in-memory state of multiple tabs and share + * access to local persistence. + */ + e, t, n, r, i, s, o, _, a, + /** + * If set to true, forcefully obtains database access. Existing tabs will + * no longer be able to access IndexedDB. + */ + u, c = 18) { + if (this.allowTabSynchronization = e, this.persistenceKey = t, this.clientId = n, + this.Mi = i, this.window = s, this.document = o, this.xi = a, this.Oi = u, this.Ni = c, + this.ci = null, this.li = !1, this.isPrimary = !1, this.networkEnabled = !0, + /** Our window.unload handler, if registered. */ + this.Bi = null, this.inForeground = !1, + /** Our 'visibilitychange' listener if registered. */ + this.Li = null, + /** The client metadata refresh task. */ + this.ki = null, + /** The last time we garbage collected the client metadata object store. */ + this.qi = Number.NEGATIVE_INFINITY, + /** A listener to notify on primary state changes. */ + this.Qi = e => Promise.resolve(), !__PRIVATE_IndexedDbPersistence.v()) throw new FirestoreError(L.UNIMPLEMENTED, "This platform is either missing IndexedDB or is known to have an incomplete implementation. Offline persistence has been disabled."); + this.referenceDelegate = new __PRIVATE_IndexedDbLruDelegateImpl(this, r), this.$i = t + Wt, + this.serializer = new __PRIVATE_LocalSerializer(_), this.Ui = new __PRIVATE_SimpleDb(this.$i, this.Ni, new __PRIVATE_SchemaConverter(this.serializer)), + this.hi = new __PRIVATE_IndexedDbGlobalsCache, this.Pi = new __PRIVATE_IndexedDbTargetCache(this.referenceDelegate, this.serializer), + this.remoteDocumentCache = __PRIVATE_newIndexedDbRemoteDocumentCache(this.serializer), + this.Ii = new __PRIVATE_IndexedDbBundleCache, this.window && this.window.localStorage ? this.Ki = this.window.localStorage : (this.Ki = null, + !1 === u && __PRIVATE_logError(Qt, "LocalStorage is unavailable. As a result, persistence may not work reliably. In particular enablePersistence() could fail immediately after refreshing the page.")); + } + /** + * Attempt to start IndexedDb persistence. + * + * @returns Whether persistence was enabled. + */ start() { + // NOTE: This is expected to fail sometimes (in the case of another tab + // already having the persistence lock), so it's the first thing we should + // do. + return this.Wi().then((() => { + if (!this.isPrimary && !this.allowTabSynchronization) + // Fail `start()` if `synchronizeTabs` is disabled and we cannot + // obtain the primary lease. + throw new FirestoreError(L.FAILED_PRECONDITION, Kt); + return this.Gi(), this.zi(), this.ji(), this.runTransaction("getHighestListenSequenceNumber", "readonly", (e => this.Pi.getHighestSequenceNumber(e))); + })).then((e => { + this.ci = new __PRIVATE_ListenSequence(e, this.xi); + })).then((() => { + this.li = !0; + })).catch((e => (this.Ui && this.Ui.close(), Promise.reject(e)))); + } + /** + * Registers a listener that gets called when the primary state of the + * instance changes. Upon registering, this listener is invoked immediately + * with the current primary state. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ Ji(e) { + return this.Qi = async t => { + if (this.started) return e(t); + }, e(this.isPrimary); + } + /** + * Registers a listener that gets called when the database receives a + * version change event indicating that it has deleted. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ setDatabaseDeletedListener(e) { + this.Ui.$((async t => { + // Check if an attempt is made to delete IndexedDB. + null === t.newVersion && await e(); + })); + } + /** + * Adjusts the current network state in the client's metadata, potentially + * affecting the primary lease. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ setNetworkEnabled(e) { + this.networkEnabled !== e && (this.networkEnabled = e, + // Schedule a primary lease refresh for immediate execution. The eventual + // lease update will be propagated via `primaryStateListener`. + this.Mi.enqueueAndForget((async () => { + this.started && await this.Wi(); + }))); + } + /** + * Updates the client metadata in IndexedDb and attempts to either obtain or + * extend the primary lease for the local client. Asynchronously notifies the + * primary state listener if the client either newly obtained or released its + * primary lease. + */ Wi() { + return this.runTransaction("updateClientMetadataAndTryBecomePrimary", "readwrite", (e => __PRIVATE_clientMetadataStore(e).put({ + clientId: this.clientId, + updateTimeMs: Date.now(), + networkEnabled: this.networkEnabled, + inForeground: this.inForeground + }).next((() => { + if (this.isPrimary) return this.Hi(e).next((e => { + e || (this.isPrimary = !1, this.Mi.enqueueRetryable((() => this.Qi(!1)))); + })); + })).next((() => this.Yi(e))).next((t => this.isPrimary && !t ? this.Zi(e).next((() => !1)) : !!t && this.Xi(e).next((() => !0)))))).catch((e => { + if (__PRIVATE_isIndexedDbTransactionError(e)) + // Proceed with the existing state. Any subsequent access to + // IndexedDB will verify the lease. + return __PRIVATE_logDebug(Qt, "Failed to extend owner lease: ", e), this.isPrimary; + if (!this.allowTabSynchronization) throw e; + return __PRIVATE_logDebug(Qt, "Releasing owner lease after error during lease refresh", e), + /* isPrimary= */ !1; + })).then((e => { + this.isPrimary !== e && this.Mi.enqueueRetryable((() => this.Qi(e))), this.isPrimary = e; + })); + } + Hi(e) { + return __PRIVATE_primaryClientStore(e).get(ee).next((e => PersistencePromise.resolve(this.es(e)))); + } + ts(e) { + return __PRIVATE_clientMetadataStore(e).delete(this.clientId); + } + /** + * If the garbage collection threshold has passed, prunes the + * RemoteDocumentChanges and the ClientMetadata store based on the last update + * time of all clients. + */ async ns() { + if (this.isPrimary && !this.rs(this.qi, $t)) { + this.qi = Date.now(); + const e = await this.runTransaction("maybeGarbageCollectMultiClientState", "readwrite-primary", (e => { + const t = __PRIVATE_getStore(e, be); + return t.J().next((e => { + const n = this.ss(e, $t), r = e.filter((e => -1 === n.indexOf(e))); + // Delete metadata for clients that are no longer considered active. + return PersistencePromise.forEach(r, (e => t.delete(e.clientId))).next((() => r)); + })); + })).catch((() => [])); + // Delete potential leftover entries that may continue to mark the + // inactive clients as zombied in LocalStorage. + // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for + // the client atomically, but we can't. So we opt to delete the IndexedDb + // entries first to avoid potentially reviving a zombied client. + if (this.Ki) for (const t of e) this.Ki.removeItem(this._s(t.clientId)); + } + } + /** + * Schedules a recurring timer to update the client metadata and to either + * extend or acquire the primary lease if the client is eligible. + */ ji() { + this.ki = this.Mi.enqueueAfterDelay("client_metadata_refresh" /* TimerId.ClientMetadataRefresh */ , 4e3, (() => this.Wi().then((() => this.ns())).then((() => this.ji())))); + } + /** Checks whether `client` is the local client. */ es(e) { + return !!e && e.ownerId === this.clientId; + } + /** + * Evaluate the state of all active clients and determine whether the local + * client is or can act as the holder of the primary lease. Returns whether + * the client is eligible for the lease, but does not actually acquire it. + * May return 'false' even if there is no active leaseholder and another + * (foreground) client should become leaseholder instead. + */ Yi(e) { + if (this.Oi) return PersistencePromise.resolve(!0); + return __PRIVATE_primaryClientStore(e).get(ee).next((t => { + // A client is eligible for the primary lease if: + // - its network is enabled and the client's tab is in the foreground. + // - its network is enabled and no other client's tab is in the + // foreground. + // - every clients network is disabled and the client's tab is in the + // foreground. + // - every clients network is disabled and no other client's tab is in + // the foreground. + // - the `forceOwningTab` setting was passed in. + if (null !== t && this.rs(t.leaseTimestampMs, Ut) && !this.us(t.ownerId)) { + if (this.es(t) && this.networkEnabled) return !0; + if (!this.es(t)) { + if (!t.allowTabSynchronization) + // Fail the `canActAsPrimary` check if the current leaseholder has + // not opted into multi-tab synchronization. If this happens at + // client startup, we reject the Promise returned by + // `enablePersistence()` and the user can continue to use Firestore + // with in-memory persistence. + // If this fails during a lease refresh, we will instead block the + // AsyncQueue from executing further operations. Note that this is + // acceptable since mixing & matching different `synchronizeTabs` + // settings is not supported. + // TODO(b/114226234): Remove this check when `synchronizeTabs` can + // no longer be turned off. + throw new FirestoreError(L.FAILED_PRECONDITION, Kt); + return !1; + } + } + return !(!this.networkEnabled || !this.inForeground) || __PRIVATE_clientMetadataStore(e).J().next((e => void 0 === this.ss(e, Ut).find((e => { + if (this.clientId !== e.clientId) { + const t = !this.networkEnabled && e.networkEnabled, n = !this.inForeground && e.inForeground, r = this.networkEnabled === e.networkEnabled; + if (t || n && r) return !0; + } + return !1; + })))); + })).next((e => (this.isPrimary !== e && __PRIVATE_logDebug(Qt, `Client ${e ? "is" : "is not"} eligible for a primary lease.`), + e))); + } + async shutdown() { + // The shutdown() operations are idempotent and can be called even when + // start() aborted (e.g. because it couldn't acquire the persistence lease). + this.li = !1, this.cs(), this.ki && (this.ki.cancel(), this.ki = null), this.ls(), + this.hs(), + // Use `SimpleDb.runTransaction` directly to avoid failing if another tab + // has obtained the primary lease. + await this.Ui.runTransaction("shutdown", "readwrite", [ X, be ], (e => { + const t = new __PRIVATE_IndexedDbTransaction(e, __PRIVATE_ListenSequence.ce); + return this.Zi(t).next((() => this.ts(t))); + })), this.Ui.close(), + // Remove the entry marking the client as zombied from LocalStorage since + // we successfully deleted its metadata from IndexedDb. + this.Ps(); + } + /** + * Returns clients that are not zombied and have an updateTime within the + * provided threshold. + */ ss(e, t) { + return e.filter((e => this.rs(e.updateTimeMs, t) && !this.us(e.clientId))); + } + /** + * Returns the IDs of the clients that are currently active. If multi-tab + * is not supported, returns an array that only contains the local client's + * ID. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ Ts() { + return this.runTransaction("getActiveClients", "readonly", (e => __PRIVATE_clientMetadataStore(e).J().next((e => this.ss(e, $t).map((e => e.clientId)))))); + } + get started() { + return this.li; + } + getGlobalsCache() { + return this.hi; + } + getMutationQueue(e, t) { + return __PRIVATE_IndexedDbMutationQueue.wt(e, this.serializer, t, this.referenceDelegate); + } + getTargetCache() { + return this.Pi; + } + getRemoteDocumentCache() { + return this.remoteDocumentCache; + } + getIndexManager(e) { + return new __PRIVATE_IndexedDbIndexManager(e, this.serializer.yt.databaseId); + } + getDocumentOverlayCache(e) { + return __PRIVATE_IndexedDbDocumentOverlayCache.wt(this.serializer, e); + } + getBundleCache() { + return this.Ii; + } + runTransaction(e, t, n) { + __PRIVATE_logDebug(Qt, "Starting transaction:", e); + const r = "readonly" === t ? "readonly" : "readwrite", i = + /** Returns the object stores for the provided schema. */ + function __PRIVATE_getObjectStores(e) { + return 18 === e ? _t : 17 === e ? ot : 16 === e ? st : 15 === e ? it : 14 === e ? rt : 13 === e ? nt : 12 === e ? tt : 11 === e ? et : void fail(60245); + }(this.Ni); + let s; + // Do all transactions as readwrite against all object stores, since we + // are the only reader/writer. + return this.Ui.runTransaction(e, r, i, (r => (s = new __PRIVATE_IndexedDbTransaction(r, this.ci ? this.ci.next() : __PRIVATE_ListenSequence.ce), + "readwrite-primary" === t ? this.Hi(s).next((e => !!e || this.Yi(s))).next((t => { + if (!t) throw __PRIVATE_logError(`Failed to obtain primary lease for action '${e}'.`), + this.isPrimary = !1, this.Mi.enqueueRetryable((() => this.Qi(!1))), new FirestoreError(L.FAILED_PRECONDITION, G); + return n(s); + })).next((e => this.Xi(s).next((() => e)))) : this.Is(s).next((() => n(s)))))).then((e => (s.raiseOnCommittedEvent(), + e))); + } + /** + * Verifies that the current tab is the primary leaseholder or alternatively + * that the leaseholder has opted into multi-tab synchronization. + */ + // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer + // be turned off. + Is(e) { + return __PRIVATE_primaryClientStore(e).get(ee).next((e => { + if (null !== e && this.rs(e.leaseTimestampMs, Ut) && !this.us(e.ownerId) && !this.es(e) && !(this.Oi || this.allowTabSynchronization && e.allowTabSynchronization)) throw new FirestoreError(L.FAILED_PRECONDITION, Kt); + })); + } + /** + * Obtains or extends the new primary lease for the local client. This + * method does not verify that the client is eligible for this lease. + */ Xi(e) { + const t = { + ownerId: this.clientId, + allowTabSynchronization: this.allowTabSynchronization, + leaseTimestampMs: Date.now() + }; + return __PRIVATE_primaryClientStore(e).put(ee, t); + } + static v() { + return __PRIVATE_SimpleDb.v(); + } + /** Checks the primary lease and removes it if we are the current primary. */ Zi(e) { + const t = __PRIVATE_primaryClientStore(e); + return t.get(ee).next((e => this.es(e) ? (__PRIVATE_logDebug(Qt, "Releasing primary lease."), + t.delete(ee)) : PersistencePromise.resolve())); + } + /** Verifies that `updateTimeMs` is within `maxAgeMs`. */ rs(e, t) { + const n = Date.now(); + return !(e < n - t) && (!(e > n) || (__PRIVATE_logError(`Detected an update time that is in the future: ${e} > ${n}`), + !1)); + } + Gi() { + null !== this.document && "function" == typeof this.document.addEventListener && (this.Li = () => { + this.Mi.enqueueAndForget((() => (this.inForeground = "visible" === this.document.visibilityState, + this.Wi()))); + }, this.document.addEventListener("visibilitychange", this.Li), this.inForeground = "visible" === this.document.visibilityState); + } + ls() { + this.Li && (this.document.removeEventListener("visibilitychange", this.Li), this.Li = null); + } + /** + * Attaches a window.unload handler that will synchronously write our + * clientId to a "zombie client id" location in LocalStorage. This can be used + * by tabs trying to acquire the primary lease to determine that the lease + * is no longer valid even if the timestamp is recent. This is particularly + * important for the refresh case (so the tab correctly re-acquires the + * primary lease). LocalStorage is used for this rather than IndexedDb because + * it is a synchronous API and so can be used reliably from an unload + * handler. + */ zi() { + "function" == typeof this.window?.addEventListener && (this.Bi = () => { + // Note: In theory, this should be scheduled on the AsyncQueue since it + // accesses internal state. We execute this code directly during shutdown + // to make sure it gets a chance to run. + this.cs(); + const e = /(?:Version|Mobile)\/1[456]/; + E() && (navigator.appVersion.match(e) || navigator.userAgent.match(e)) && + // On Safari 14, 15, and 16, we do not run any cleanup actions as it might + // trigger a bug that prevents Safari from re-opening IndexedDB during + // the next page load. + // See https://bugs.webkit.org/show_bug.cgi?id=226547 + this.Mi.enterRestrictedMode(/* purgeExistingTasks= */ !0), this.Mi.enqueueAndForget((() => this.shutdown())); + }, this.window.addEventListener("pagehide", this.Bi)); + } + hs() { + this.Bi && (this.window.removeEventListener("pagehide", this.Bi), this.Bi = null); + } + /** + * Returns whether a client is "zombied" based on its LocalStorage entry. + * Clients become zombied when their tab closes without running all of the + * cleanup logic in `shutdown()`. + */ us(e) { + try { + const t = null !== this.Ki?.getItem(this._s(e)); + return __PRIVATE_logDebug(Qt, `Client '${e}' ${t ? "is" : "is not"} zombied in LocalStorage`), + t; + } catch (e) { + // Gracefully handle if LocalStorage isn't working. + return __PRIVATE_logError(Qt, "Failed to get zombied client id.", e), !1; + } + } + /** + * Record client as zombied (a client that had its tab closed). Zombied + * clients are ignored during primary tab selection. + */ cs() { + if (this.Ki) try { + this.Ki.setItem(this._s(this.clientId), String(Date.now())); + } catch (e) { + // Gracefully handle if LocalStorage isn't available / working. + __PRIVATE_logError("Failed to set zombie client id.", e); + } + } + /** Removes the zombied client entry if it exists. */ Ps() { + if (this.Ki) try { + this.Ki.removeItem(this._s(this.clientId)); + } catch (e) { + // Ignore + } + } + _s(e) { + return `firestore_zombie_${this.persistenceKey}_${e}`; + } +} + +/** + * Helper to get a typed SimpleDbStore for the primary client object store. + */ function __PRIVATE_primaryClientStore(e) { + return __PRIVATE_getStore(e, X); +} + +/** + * Helper to get a typed SimpleDbStore for the client metadata object store. + */ function __PRIVATE_clientMetadataStore(e) { + return __PRIVATE_getStore(e, be); +} + +/** + * Generates a string used as a prefix when storing data in IndexedDB and + * LocalStorage. + */ function __PRIVATE_indexedDbStoragePrefix(e, t) { + // Use two different prefix formats: + // * firestore / persistenceKey / projectID . databaseID / ... + // * firestore / persistenceKey / projectID / ... + // projectIDs are DNS-compatible names and cannot contain dots + // so there's no danger of collisions. + let n = e.projectId; + return e.isDefaultDatabase || (n += "." + e.database), "firestore/" + t + "/" + n + "/"; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A set of changes to what documents are currently in view and out of view for + * a given query. These changes are sent to the LocalStore by the View (via + * the SyncEngine) and are used to pin / unpin documents as appropriate. + */ +class __PRIVATE_LocalViewChanges { + constructor(e, t, n, r) { + this.targetId = e, this.fromCache = t, this.Es = n, this.ds = r; + } + static As(e, t) { + let n = __PRIVATE_documentKeySet(), r = __PRIVATE_documentKeySet(); + for (const e of t.docChanges) switch (e.type) { + case 0 /* ChangeType.Added */ : + n = n.add(e.doc.key); + break; + + case 1 /* ChangeType.Removed */ : + r = r.add(e.doc.key); + // do nothing + } + return new __PRIVATE_LocalViewChanges(e, t.fromCache, n, r); + } +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A tracker to keep a record of important details during database local query + * execution. + */ class QueryContext { + constructor() { + /** + * Counts the number of documents passed through during local query execution. + */ + this._documentReadCount = 0; + } + get documentReadCount() { + return this._documentReadCount; + } + incrementDocumentReadCount(e) { + this._documentReadCount += e; + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The Firestore query engine. + * + * Firestore queries can be executed in three modes. The Query Engine determines + * what mode to use based on what data is persisted. The mode only determines + * the runtime complexity of the query - the result set is equivalent across all + * implementations. + * + * The Query engine will use indexed-based execution if a user has configured + * any index that can be used to execute query (via `setIndexConfiguration()`). + * Otherwise, the engine will try to optimize the query by re-using a previously + * persisted query result. If that is not possible, the query will be executed + * via a full collection scan. + * + * Index-based execution is the default when available. The query engine + * supports partial indexed execution and merges the result from the index + * lookup with documents that have not yet been indexed. The index evaluation + * matches the backend's format and as such, the SDK can use indexing for all + * queries that the backend supports. + * + * If no index exists, the query engine tries to take advantage of the target + * document mapping in the TargetCache. These mappings exists for all queries + * that have been synced with the backend at least once and allow the query + * engine to only read documents that previously matched a query plus any + * documents that were edited after the query was last listened to. + * + * There are some cases when this optimization is not guaranteed to produce + * the same results as full collection scans. In these cases, query + * processing falls back to full scans. These cases are: + * + * - Limit queries where a document that matched the query previously no longer + * matches the query. + * + * - Limit queries where a document edit may cause the document to sort below + * another document that is in the local cache. + * + * - Queries that have never been CURRENT or free of limbo documents. + */ +class __PRIVATE_QueryEngine { + constructor() { + this.Rs = !1, this.Vs = !1, + /** + * SDK only decides whether it should create index when collection size is + * larger than this. + */ + this.fs = 100, this.gs = + /** + * This cost represents the evaluation result of + * (([index, docKey] + [docKey, docContent]) per document in the result set) + * / ([docKey, docContent] per documents in full collection scan) coming from + * experiment [enter PR experiment URL here]. + */ + function __PRIVATE_getDefaultRelativeIndexReadCostPerDocument() { + // These values were derived from an experiment where several members of the + // Firestore SDK team ran a performance test in various environments. + // Googlers can see b/299284287 for details. + return E() ? 8 : __PRIVATE_getAndroidVersion(h()) > 0 ? 6 : 4; + }(); + } + /** Sets the document view to query against. */ initialize(e, t) { + this.ps = e, this.indexManager = t, this.Rs = !0; + } + /** Returns all local documents matching the specified query. */ getDocumentsMatchingQuery(e, t, n, r) { + // Stores the result from executing the query; using this object is more + // convenient than passing the result between steps of the persistence + // transaction and improves readability comparatively. + const i = { + result: null + }; + return this.ys(e, t).next((e => { + i.result = e; + })).next((() => { + if (!i.result) return this.ws(e, t, r, n).next((e => { + i.result = e; + })); + })).next((() => { + if (i.result) return; + const n = new QueryContext; + return this.Ss(e, t, n).next((r => { + if (i.result = r, this.Vs) return this.bs(e, t, n, r.size); + })); + })).next((() => i.result)); + } + bs(e, t, n, r) { + return n.documentReadCount < this.fs ? (__PRIVATE_getLogLevel() <= a.DEBUG && __PRIVATE_logDebug("QueryEngine", "SDK will not create cache indexes for query:", __PRIVATE_stringifyQuery(t), "since it only creates cache indexes for collection contains", "more than or equal to", this.fs, "documents"), + PersistencePromise.resolve()) : (__PRIVATE_getLogLevel() <= a.DEBUG && __PRIVATE_logDebug("QueryEngine", "Query:", __PRIVATE_stringifyQuery(t), "scans", n.documentReadCount, "local documents and returns", r, "documents as results."), + n.documentReadCount > this.gs * r ? (__PRIVATE_getLogLevel() <= a.DEBUG && __PRIVATE_logDebug("QueryEngine", "The SDK decides to create cache indexes for query:", __PRIVATE_stringifyQuery(t), "as using cache indexes may help improve performance."), + this.indexManager.createTargetIndexes(e, __PRIVATE_queryToTarget(t))) : PersistencePromise.resolve()); + } + /** + * Performs an indexed query that evaluates the query based on a collection's + * persisted index values. Returns `null` if an index is not available. + */ ys(e, t) { + if (__PRIVATE_queryMatchesAllDocuments(t)) + // Queries that match all documents don't benefit from using + // key-based lookups. It is more efficient to scan all documents in a + // collection, rather than to perform individual lookups. + return PersistencePromise.resolve(null); + let n = __PRIVATE_queryToTarget(t); + return this.indexManager.getIndexType(e, n).next((r => 0 /* IndexType.NONE */ === r ? null : (null !== t.limit && 1 /* IndexType.PARTIAL */ === r && ( + // We cannot apply a limit for targets that are served using a partial + // index. If a partial index will be used to serve the target, the + // query may return a superset of documents that match the target + // (e.g. if the index doesn't include all the target's filters), or + // may return the correct set of documents in the wrong order (e.g. if + // the index doesn't include a segment for one of the orderBys). + // Therefore, a limit should not be applied in such cases. + t = __PRIVATE_queryWithLimit(t, null, "F" /* LimitType.First */), n = __PRIVATE_queryToTarget(t)), + this.indexManager.getDocumentsMatchingTarget(e, n).next((r => { + const i = __PRIVATE_documentKeySet(...r); + return this.ps.getDocuments(e, i).next((r => this.indexManager.getMinOffset(e, n).next((n => { + const s = this.Ds(t, r); + return this.Cs(t, s, i, n.readTime) ? this.ys(e, __PRIVATE_queryWithLimit(t, null, "F" /* LimitType.First */)) : this.vs(e, s, t, n); + })))); + }))))); + } + /** + * Performs a query based on the target's persisted query mapping. Returns + * `null` if the mapping is not available or cannot be used. + */ ws(e, t, n, r) { + return __PRIVATE_queryMatchesAllDocuments(t) || r.isEqual(SnapshotVersion.min()) ? PersistencePromise.resolve(null) : this.ps.getDocuments(e, n).next((i => { + const s = this.Ds(t, i); + return this.Cs(t, s, n, r) ? PersistencePromise.resolve(null) : (__PRIVATE_getLogLevel() <= a.DEBUG && __PRIVATE_logDebug("QueryEngine", "Re-using previous result from %s to execute query: %s", r.toString(), __PRIVATE_stringifyQuery(t)), + this.vs(e, s, t, __PRIVATE_newIndexOffsetSuccessorFromReadTime(r, W)).next((e => e))); + })); + // Queries that have never seen a snapshot without limbo free documents + // should also be run as a full collection scan. + } + /** Applies the query filter and sorting to the provided documents. */ Ds(e, t) { + // Sort the documents and re-apply the query filter since previously + // matching documents do not necessarily still match the query. + let n = new SortedSet(__PRIVATE_newQueryComparator(e)); + return t.forEach(((t, r) => { + __PRIVATE_queryMatches(e, r) && (n = n.add(r)); + })), n; + } + /** + * Determines if a limit query needs to be refilled from cache, making it + * ineligible for index-free execution. + * + * @param query - The query. + * @param sortedPreviousResults - The documents that matched the query when it + * was last synchronized, sorted by the query's comparator. + * @param remoteKeys - The document keys that matched the query at the last + * snapshot. + * @param limboFreeSnapshotVersion - The version of the snapshot when the + * query was last synchronized. + */ Cs(e, t, n, r) { + if (null === e.limit) + // Queries without limits do not need to be refilled. + return !1; + if (n.size !== t.size) + // The query needs to be refilled if a previously matching document no + // longer matches. + return !0; + // Limit queries are not eligible for index-free query execution if there is + // a potential that an older document from cache now sorts before a document + // that was previously part of the limit. This, however, can only happen if + // the document at the edge of the limit goes out of limit. + // If a document that is not the limit boundary sorts differently, + // the boundary of the limit itself did not change and documents from cache + // will continue to be "rejected" by this boundary. Therefore, we can ignore + // any modifications that don't affect the last document. + const i = "F" /* LimitType.First */ === e.limitType ? t.last() : t.first(); + return !!i && (i.hasPendingWrites || i.version.compareTo(r) > 0); + } + Ss(e, t, n) { + return __PRIVATE_getLogLevel() <= a.DEBUG && __PRIVATE_logDebug("QueryEngine", "Using full collection scan to execute query:", __PRIVATE_stringifyQuery(t)), + this.ps.getDocumentsMatchingQuery(e, t, IndexOffset.min(), n); + } + /** + * Combines the results from an indexed execution with the remaining documents + * that have not yet been indexed. + */ vs(e, t, n, r) { + // Retrieve all results for documents that were updated since the offset. + return this.ps.getDocumentsMatchingQuery(e, n, r).next((e => ( + // Merge with existing results + t.forEach((t => { + e = e.insert(t.key, t); + })), e))); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const Gt = "LocalStore", zt = 3e8; + +/** + * The maximum time to leave a resume token buffered without writing it out. + * This value is arbitrary: it's long enough to avoid several writes + * (possibly indefinitely if updates come more frequently than this) but + * short enough that restarting after crashing will still have a pretty + * recent resume token. + */ +/** + * Implements `LocalStore` interface. + * + * Note: some field defined in this class might have public access level, but + * the class is not exported so they are only accessible from this module. + * This is useful to implement optional features (like bundles) in free + * functions, such that they are tree-shakeable. + */ +class __PRIVATE_LocalStoreImpl { + constructor( + /** Manages our in-memory or durable persistence. */ + e, t, n, r) { + this.persistence = e, this.Fs = t, this.serializer = r, + /** + * Maps a targetID to data about its target. + * + * PORTING NOTE: We are using an immutable data structure on Web to make re-runs + * of `applyRemoteEvent()` idempotent. + */ + this.Ms = new SortedMap(__PRIVATE_primitiveComparator), + /** Maps a target to its targetID. */ + // TODO(wuandy): Evaluate if TargetId can be part of Target. + this.xs = new ObjectMap((e => __PRIVATE_canonifyTarget(e)), __PRIVATE_targetEquals), + /** + * A per collection group index of the last read time processed by + * `getNewDocumentChanges()`. + * + * PORTING NOTE: This is only used for multi-tab synchronization. + */ + this.Os = new Map, this.Ns = e.getRemoteDocumentCache(), this.Pi = e.getTargetCache(), + this.Ii = e.getBundleCache(), this.Bs(n); + } + Bs(e) { + // TODO(indexing): Add spec tests that test these components change after a + // user change + this.documentOverlayCache = this.persistence.getDocumentOverlayCache(e), this.indexManager = this.persistence.getIndexManager(e), + this.mutationQueue = this.persistence.getMutationQueue(e, this.indexManager), this.localDocuments = new LocalDocumentsView(this.Ns, this.mutationQueue, this.documentOverlayCache, this.indexManager), + this.Ns.setIndexManager(this.indexManager), this.Fs.initialize(this.localDocuments, this.indexManager); + } + collectGarbage(e) { + return this.persistence.runTransaction("Collect garbage", "readwrite-primary", (t => e.collect(t, this.Ms))); + } +} + +function __PRIVATE_newLocalStore( +/** Manages our in-memory or durable persistence. */ +e, t, n, r) { + return new __PRIVATE_LocalStoreImpl(e, t, n, r); +} + +/** + * Tells the LocalStore that the currently authenticated user has changed. + * + * In response the local store switches the mutation queue to the new user and + * returns any resulting document changes. + */ +// PORTING NOTE: Android and iOS only return the documents affected by the +// change. +async function __PRIVATE_localStoreHandleUserChange(e, t) { + const n = __PRIVATE_debugCast(e); + return await n.persistence.runTransaction("Handle user change", "readonly", (e => { + // Swap out the mutation queue, grabbing the pending mutation batches + // before and after. + let r; + return n.mutationQueue.getAllMutationBatches(e).next((i => (r = i, n.Bs(t), n.mutationQueue.getAllMutationBatches(e)))).next((t => { + const i = [], s = []; + // Union the old/new changed keys. + let o = __PRIVATE_documentKeySet(); + for (const e of r) { + i.push(e.batchId); + for (const t of e.mutations) o = o.add(t.key); + } + for (const e of t) { + s.push(e.batchId); + for (const t of e.mutations) o = o.add(t.key); + } + // Return the set of all (potentially) changed documents and the list + // of mutation batch IDs that were affected by change. + return n.localDocuments.getDocuments(e, o).next((e => ({ + Ls: e, + removedBatchIds: i, + addedBatchIds: s + }))); + })); + })); +} + +/* Accepts locally generated Mutations and commit them to storage. */ +/** + * Acknowledges the given batch. + * + * On the happy path when a batch is acknowledged, the local store will + * + * + remove the batch from the mutation queue; + * + apply the changes to the remote document cache; + * + recalculate the latency compensated view implied by those changes (there + * may be mutations in the queue that affect the documents but haven't been + * acknowledged yet); and + * + give the changed documents back the sync engine + * + * @returns The resulting (modified) documents. + */ +function __PRIVATE_localStoreAcknowledgeBatch(e, t) { + const n = __PRIVATE_debugCast(e); + return n.persistence.runTransaction("Acknowledge batch", "readwrite-primary", (e => { + const r = t.batch.keys(), i = n.Ns.newChangeBuffer({ + trackRemovals: !0 + }); + return function __PRIVATE_applyWriteToRemoteDocuments(e, t, n, r) { + const i = n.batch, s = i.keys(); + let o = PersistencePromise.resolve(); + return s.forEach((e => { + o = o.next((() => r.getEntry(t, e))).next((t => { + const s = n.docVersions.get(e); + __PRIVATE_hardAssert(null !== s, 48541), t.version.compareTo(s) < 0 && (i.applyToRemoteDocument(t, n), + t.isValidDocument() && ( + // We use the commitVersion as the readTime rather than the + // document's updateTime since the updateTime is not advanced + // for updates that do not modify the underlying document. + t.setReadTime(n.commitVersion), r.addEntry(t))); + })); + })), o.next((() => e.mutationQueue.removeMutationBatch(t, i))); + } + /** Returns the local view of the documents affected by a mutation batch. */ + // PORTING NOTE: Multi-Tab only. + (n, e, t, i).next((() => i.apply(e))).next((() => n.mutationQueue.performConsistencyCheck(e))).next((() => n.documentOverlayCache.removeOverlaysForBatchId(e, r, t.batch.batchId))).next((() => n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e, function __PRIVATE_getKeysWithTransformResults(e) { + let t = __PRIVATE_documentKeySet(); + for (let n = 0; n < e.mutationResults.length; ++n) { + e.mutationResults[n].transformResults.length > 0 && (t = t.add(e.batch.mutations[n].key)); + } + return t; + } + /** + * Removes mutations from the MutationQueue for the specified batch; + * LocalDocuments will be recalculated. + * + * @returns The resulting modified documents. + */ (t)))).next((() => n.localDocuments.getDocuments(e, r))); + })); +} + +/** + * Returns the last consistent snapshot processed (used by the RemoteStore to + * determine whether to buffer incoming snapshots from the backend). + */ +function __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e) { + const t = __PRIVATE_debugCast(e); + return t.persistence.runTransaction("Get last remote snapshot version", "readonly", (e => t.Pi.getLastRemoteSnapshotVersion(e))); +} + +/** + * Updates the "ground-state" (remote) documents. We assume that the remote + * event reflects any write batches that have been acknowledged or rejected + * (i.e. we do not re-apply local mutations to updates from this event). + * + * LocalDocuments are re-calculated if there are remaining mutations in the + * queue. + */ function __PRIVATE_localStoreApplyRemoteEventToLocalCache(e, t) { + const n = __PRIVATE_debugCast(e), r = t.snapshotVersion; + let i = n.Ms; + return n.persistence.runTransaction("Apply remote event", "readwrite-primary", (e => { + const s = n.Ns.newChangeBuffer({ + trackRemovals: !0 + }); + // Reset newTargetDataByTargetMap in case this transaction gets re-run. + i = n.Ms; + const o = []; + t.targetChanges.forEach(((s, _) => { + const a = i.get(_); + if (!a) return; + // Only update the remote keys if the target is still active. This + // ensures that we can persist the updated target data along with + // the updated assignment. + o.push(n.Pi.removeMatchingKeys(e, s.removedDocuments, _).next((() => n.Pi.addMatchingKeys(e, s.addedDocuments, _)))); + let u = a.withSequenceNumber(e.currentSequenceNumber); + null !== t.targetMismatches.get(_) ? u = u.withResumeToken(ByteString.EMPTY_BYTE_STRING, SnapshotVersion.min()).withLastLimboFreeSnapshotVersion(SnapshotVersion.min()) : s.resumeToken.approximateByteSize() > 0 && (u = u.withResumeToken(s.resumeToken, r)), + i = i.insert(_, u), + // Update the target data if there are target changes (or if + // sufficient time has passed since the last update). + /** + * Returns true if the newTargetData should be persisted during an update of + * an active target. TargetData should always be persisted when a target is + * being released and should not call this function. + * + * While the target is active, TargetData updates can be omitted when nothing + * about the target has changed except metadata like the resume token or + * snapshot version. Occasionally it's worth the extra write to prevent these + * values from getting too stale after a crash, but this doesn't have to be + * too frequent. + */ + function __PRIVATE_shouldPersistTargetData(e, t, n) { + // Always persist target data if we don't already have a resume token. + if (0 === e.resumeToken.approximateByteSize()) return !0; + // Don't allow resume token changes to be buffered indefinitely. This + // allows us to be reasonably up-to-date after a crash and avoids needing + // to loop over all active queries on shutdown. Especially in the browser + // we may not get time to do anything interesting while the current tab is + // closing. + const r = t.snapshotVersion.toMicroseconds() - e.snapshotVersion.toMicroseconds(); + if (r >= zt) return !0; + // Otherwise if the only thing that has changed about a target is its resume + // token it's not worth persisting. Note that the RemoteStore keeps an + // in-memory view of the currently active targets which includes the current + // resume token, so stream failure or user changes will still use an + // up-to-date resume token regardless of what we do here. + const i = n.addedDocuments.size + n.modifiedDocuments.size + n.removedDocuments.size; + return i > 0; + } + /** + * Notifies local store of the changed views to locally pin documents. + */ (a, u, s) && o.push(n.Pi.updateTargetData(e, u)); + })); + let _ = __PRIVATE_mutableDocumentMap(), a = __PRIVATE_documentKeySet(); + // HACK: The only reason we allow a null snapshot version is so that we + // can synthesize remote events when we get permission denied errors while + // trying to resolve the state of a locally cached document that is in + // limbo. + if (t.documentUpdates.forEach((r => { + t.resolvedLimboDocuments.has(r) && o.push(n.persistence.referenceDelegate.updateLimboDocument(e, r)); + })), + // Each loop iteration only affects its "own" doc, so it's safe to get all + // the remote documents in advance in a single call. + o.push(__PRIVATE_populateDocumentChangeBuffer(e, s, t.documentUpdates).next((e => { + _ = e.ks, a = e.qs; + }))), !r.isEqual(SnapshotVersion.min())) { + const t = n.Pi.getLastRemoteSnapshotVersion(e).next((t => n.Pi.setTargetsMetadata(e, e.currentSequenceNumber, r))); + o.push(t); + } + return PersistencePromise.waitFor(o).next((() => s.apply(e))).next((() => n.localDocuments.getLocalViewOfDocuments(e, _, a))).next((() => _)); + })).then((e => (n.Ms = i, e))); +} + +/** + * Populates document change buffer with documents from backend or a bundle. + * Returns the document changes resulting from applying those documents, and + * also a set of documents whose existence state are changed as a result. + * + * @param txn - Transaction to use to read existing documents from storage. + * @param documentBuffer - Document buffer to collect the resulted changes to be + * applied to storage. + * @param documents - Documents to be applied. + */ function __PRIVATE_populateDocumentChangeBuffer(e, t, n) { + let r = __PRIVATE_documentKeySet(), i = __PRIVATE_documentKeySet(); + return n.forEach((e => r = r.add(e))), t.getEntries(e, r).next((e => { + let r = __PRIVATE_mutableDocumentMap(); + return n.forEach(((n, s) => { + const o = e.get(n); + // Check if see if there is a existence state change for this document. + s.isFoundDocument() !== o.isFoundDocument() && (i = i.add(n)), + // Note: The order of the steps below is important, since we want + // to ensure that rejected limbo resolutions (which fabricate + // NoDocuments with SnapshotVersion.min()) never add documents to + // cache. + s.isNoDocument() && s.version.isEqual(SnapshotVersion.min()) ? ( + // NoDocuments with SnapshotVersion.min() are used in manufactured + // events. We remove these documents from cache since we lost + // access. + t.removeEntry(n, s.readTime), r = r.insert(n, s)) : !o.isValidDocument() || s.version.compareTo(o.version) > 0 || 0 === s.version.compareTo(o.version) && o.hasPendingWrites ? (t.addEntry(s), + r = r.insert(n, s)) : __PRIVATE_logDebug(Gt, "Ignoring outdated watch update for ", n, ". Current version:", o.version, " Watch version:", s.version); + })), { + ks: r, + qs: i + }; + })); +} + +/** + * Gets the mutation batch after the passed in batchId in the mutation queue + * or null if empty. + * @param afterBatchId - If provided, the batch to search after. + * @returns The next mutation or null if there wasn't one. + */ +function __PRIVATE_localStoreGetNextMutationBatch(e, t) { + const n = __PRIVATE_debugCast(e); + return n.persistence.runTransaction("Get next mutation batch", "readonly", (e => (void 0 === t && (t = H), + n.mutationQueue.getNextMutationBatchAfterBatchId(e, t)))); +} + +/** + * Reads the current value of a Document with a given key or null if not + * found - used for testing. + */ +/** + * Assigns the given target an internal ID so that its results can be pinned so + * they don't get GC'd. A target must be allocated in the local store before + * the store can be used to manage its view. + * + * Allocating an already allocated `Target` will return the existing `TargetData` + * for that `Target`. + */ +function __PRIVATE_localStoreAllocateTarget(e, t) { + const n = __PRIVATE_debugCast(e); + return n.persistence.runTransaction("Allocate target", "readwrite", (e => { + let r; + return n.Pi.getTargetData(e, t).next((i => i ? ( + // This target has been listened to previously, so reuse the + // previous targetID. + // TODO(mcg): freshen last accessed date? + r = i, PersistencePromise.resolve(r)) : n.Pi.allocateTargetId(e).next((i => (r = new TargetData(t, i, "TargetPurposeListen" /* TargetPurpose.Listen */ , e.currentSequenceNumber), + n.Pi.addTargetData(e, r).next((() => r))))))); + })).then((e => { + // If Multi-Tab is enabled, the existing target data may be newer than + // the in-memory data + const r = n.Ms.get(e.targetId); + return (null === r || e.snapshotVersion.compareTo(r.snapshotVersion) > 0) && (n.Ms = n.Ms.insert(e.targetId, e), + n.xs.set(t, e.targetId)), e; + })); +} + +/** + * Returns the TargetData as seen by the LocalStore, including updates that may + * have not yet been persisted to the TargetCache. + */ +// Visible for testing. +/** + * Unpins all the documents associated with the given target. If + * `keepPersistedTargetData` is set to false and Eager GC enabled, the method + * directly removes the associated target data from the target cache. + * + * Releasing a non-existing `Target` is a no-op. + */ +// PORTING NOTE: `keepPersistedTargetData` is multi-tab only. +async function __PRIVATE_localStoreReleaseTarget(e, t, n) { + const r = __PRIVATE_debugCast(e), i = r.Ms.get(t), s = n ? "readwrite" : "readwrite-primary"; + try { + n || await r.persistence.runTransaction("Release target", s, (e => r.persistence.referenceDelegate.removeTarget(e, i))); + } catch (e) { + if (!__PRIVATE_isIndexedDbTransactionError(e)) throw e; + // All `releaseTarget` does is record the final metadata state for the + // target, but we've been recording this periodically during target + // activity. If we lose this write this could cause a very slight + // difference in the order of target deletion during GC, but we + // don't define exact LRU semantics so this is acceptable. + __PRIVATE_logDebug(Gt, `Failed to update sequence numbers for target ${t}: ${e}`); + } + r.Ms = r.Ms.remove(t), r.xs.delete(i.target); +} + +/** + * Runs the specified query against the local store and returns the results, + * potentially taking advantage of query data from previous executions (such + * as the set of remote keys). + * + * @param usePreviousResults - Whether results from previous executions can + * be used to optimize this query execution. + */ function __PRIVATE_localStoreExecuteQuery(e, t, n) { + const r = __PRIVATE_debugCast(e); + let i = SnapshotVersion.min(), s = __PRIVATE_documentKeySet(); + return r.persistence.runTransaction("Execute query", "readwrite", (// Use readwrite instead of readonly so indexes can be created + // Use readwrite instead of readonly so indexes can be created + e => function __PRIVATE_localStoreGetTargetData(e, t, n) { + const r = __PRIVATE_debugCast(e), i = r.xs.get(n); + return void 0 !== i ? PersistencePromise.resolve(r.Ms.get(i)) : r.Pi.getTargetData(t, n); + }(r, e, __PRIVATE_queryToTarget(t)).next((t => { + if (t) return i = t.lastLimboFreeSnapshotVersion, r.Pi.getMatchingKeysForTargetId(e, t.targetId).next((e => { + s = e; + })); + })).next((() => r.Fs.getDocumentsMatchingQuery(e, t, n ? i : SnapshotVersion.min(), n ? s : __PRIVATE_documentKeySet()))).next((e => (__PRIVATE_setMaxReadTime(r, __PRIVATE_queryCollectionGroup(t), e), + { + documents: e, + Qs: s + }))))); +} + +// PORTING NOTE: Multi-Tab only. +function __PRIVATE_localStoreGetCachedTarget(e, t) { + const n = __PRIVATE_debugCast(e), r = __PRIVATE_debugCast(n.Pi), i = n.Ms.get(t); + return i ? Promise.resolve(i.target) : n.persistence.runTransaction("Get target data", "readonly", (e => r.At(e, t).next((e => e ? e.target : null)))); +} + +/** + * Returns the set of documents that have been updated since the last call. + * If this is the first call, returns the set of changes since client + * initialization. Further invocations will return document that have changed + * since the prior call. + */ +// PORTING NOTE: Multi-Tab only. +function __PRIVATE_localStoreGetNewDocumentChanges(e, t) { + const n = __PRIVATE_debugCast(e), r = n.Os.get(t) || SnapshotVersion.min(); + // Get the current maximum read time for the collection. This should always + // exist, but to reduce the chance for regressions we default to + // SnapshotVersion.Min() + // TODO(indexing): Consider removing the default value. + return n.persistence.runTransaction("Get new document changes", "readonly", (e => n.Ns.getAllFromCollectionGroup(e, t, __PRIVATE_newIndexOffsetSuccessorFromReadTime(r, W), + /* limit= */ Number.MAX_SAFE_INTEGER))).then((e => (__PRIVATE_setMaxReadTime(n, t, e), + e))); +} + +/** Sets the collection group's maximum read time from the given documents. */ +// PORTING NOTE: Multi-Tab only. +function __PRIVATE_setMaxReadTime(e, t, n) { + let r = e.Os.get(t) || SnapshotVersion.min(); + n.forEach(((e, t) => { + t.readTime.compareTo(r) > 0 && (r = t.readTime); + })), e.Os.set(t, r); +} + +/** + * Creates a new target using the given bundle name, which will be used to + * hold the keys of all documents from the bundle in query-document mappings. + * This ensures that the loaded documents do not get garbage collected + * right away. + */ +/** + * Applies the documents from a bundle to the "ground-state" (remote) + * documents. + * + * LocalDocuments are re-calculated if there are remaining mutations in the + * queue. + */ +async function __PRIVATE_localStoreApplyBundledDocuments(e, t, n, r) { + const i = __PRIVATE_debugCast(e); + let s = __PRIVATE_documentKeySet(), o = __PRIVATE_mutableDocumentMap(); + for (const e of n) { + const n = t.$s(e.metadata.name); + e.document && (s = s.add(n)); + const r = t.Us(e); + r.setReadTime(t.Ks(e.metadata.readTime)), o = o.insert(n, r); + } + const _ = i.Ns.newChangeBuffer({ + trackRemovals: !0 + }), a = await __PRIVATE_localStoreAllocateTarget(i, function __PRIVATE_umbrellaTarget(e) { + // It is OK that the path used for the query is not valid, because this will + // not be read and queried. + return __PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(ResourcePath.fromString(`__bundle__/docs/${e}`))); + }(r)); + // Allocates a target to hold all document keys from the bundle, such that + // they will not get garbage collected right away. + return i.persistence.runTransaction("Apply bundle documents", "readwrite", (e => __PRIVATE_populateDocumentChangeBuffer(e, _, o).next((t => (_.apply(e), + t))).next((t => i.Pi.removeMatchingKeysForTargetId(e, a.targetId).next((() => i.Pi.addMatchingKeys(e, s, a.targetId))).next((() => i.localDocuments.getLocalViewOfDocuments(e, t.ks, t.qs))).next((() => t.ks)))))); +} + +/** + * Returns a promise of a boolean to indicate if the given bundle has already + * been loaded and the create time is newer than the current loading bundle. + */ +/** + * Saves the given `NamedQuery` to local persistence. + */ +async function __PRIVATE_localStoreSaveNamedQuery(e, t, n = __PRIVATE_documentKeySet()) { + // Allocate a target for the named query such that it can be resumed + // from associated read time if users use it to listen. + // NOTE: this also means if no corresponding target exists, the new target + // will remain active and will not get collected, unless users happen to + // unlisten the query somehow. + const r = await __PRIVATE_localStoreAllocateTarget(e, __PRIVATE_queryToTarget(__PRIVATE_fromBundledQuery(t.bundledQuery))), i = __PRIVATE_debugCast(e); + return i.persistence.runTransaction("Save named query", "readwrite", (e => { + const s = __PRIVATE_fromVersion(t.readTime); + // Simply save the query itself if it is older than what the SDK already + // has. + if (r.snapshotVersion.compareTo(s) >= 0) return i.Ii.saveNamedQuery(e, t); + // Update existing target data because the query from the bundle is newer. + const o = r.withResumeToken(ByteString.EMPTY_BYTE_STRING, s); + return i.Ms = i.Ms.insert(o.targetId, o), i.Pi.updateTargetData(e, o).next((() => i.Pi.removeMatchingKeysForTargetId(e, r.targetId))).next((() => i.Pi.addMatchingKeys(e, n, r.targetId))).next((() => i.Ii.saveNamedQuery(e, t))); + })); +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// The format of the LocalStorage key that stores the client state is: +// firestore_clients__ +const jt = "firestore_clients"; + +/** Assembles the key for a client state in WebStorage */ function createWebStorageClientStateKey(e, t) { + return `${jt}_${e}_${t}`; +} + +// The format of the WebStorage key that stores the mutation state is: +// firestore_mutations__ +// (for unauthenticated users) +// or: firestore_mutations___ + +// 'user_uid' is last to avoid needing to escape '_' characters that it might +// contain. +const Jt = "firestore_mutations"; + +/** Assembles the key for a mutation batch in WebStorage */ function createWebStorageMutationBatchKey(e, t, n) { + let r = `${Jt}_${e}_${n}`; + return t.isAuthenticated() && (r += `_${t.uid}`), r; +} + +// The format of the WebStorage key that stores a query target's metadata is: +// firestore_targets__ +const Ht = "firestore_targets"; + +/** Assembles the key for a query state in WebStorage */ function createWebStorageQueryTargetMetadataKey(e, t) { + return `${Ht}_${e}_${t}`; +} + +// The WebStorage prefix that stores the primary tab's online state. The +// format of the key is: +// firestore_online_state_ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const Yt = "SharedClientState"; + +/** + * Holds the state of a mutation batch, including its user ID, batch ID and + * whether the batch is 'pending', 'acknowledged' or 'rejected'. + */ +// Visible for testing +class __PRIVATE_MutationMetadata { + constructor(e, t, n, r) { + this.user = e, this.batchId = t, this.state = n, this.error = r; + } + /** + * Parses a MutationMetadata from its JSON representation in WebStorage. + * Logs a warning and returns null if the format of the data is not valid. + */ static Ws(e, t, n) { + const r = JSON.parse(n); + let i, s = "object" == typeof r && -1 !== [ "pending", "acknowledged", "rejected" ].indexOf(r.state) && (void 0 === r.error || "object" == typeof r.error); + return s && r.error && (s = "string" == typeof r.error.message && "string" == typeof r.error.code, + s && (i = new FirestoreError(r.error.code, r.error.message))), s ? new __PRIVATE_MutationMetadata(e, t, r.state, i) : (__PRIVATE_logError(Yt, `Failed to parse mutation state for ID '${t}': ${n}`), + null); + } + Gs() { + const e = { + state: this.state, + updateTimeMs: Date.now() + }; + return this.error && (e.error = { + code: this.error.code, + message: this.error.message + }), JSON.stringify(e); + } +} + +/** + * Holds the state of a query target, including its target ID and whether the + * target is 'not-current', 'current' or 'rejected'. + */ +// Visible for testing +class __PRIVATE_QueryTargetMetadata { + constructor(e, t, n) { + this.targetId = e, this.state = t, this.error = n; + } + /** + * Parses a QueryTargetMetadata from its JSON representation in WebStorage. + * Logs a warning and returns null if the format of the data is not valid. + */ static Ws(e, t) { + const n = JSON.parse(t); + let r, i = "object" == typeof n && -1 !== [ "not-current", "current", "rejected" ].indexOf(n.state) && (void 0 === n.error || "object" == typeof n.error); + return i && n.error && (i = "string" == typeof n.error.message && "string" == typeof n.error.code, + i && (r = new FirestoreError(n.error.code, n.error.message))), i ? new __PRIVATE_QueryTargetMetadata(e, n.state, r) : (__PRIVATE_logError(Yt, `Failed to parse target state for ID '${e}': ${t}`), + null); + } + Gs() { + const e = { + state: this.state, + updateTimeMs: Date.now() + }; + return this.error && (e.error = { + code: this.error.code, + message: this.error.message + }), JSON.stringify(e); + } +} + +/** + * This class represents the immutable ClientState for a client read from + * WebStorage, containing the list of active query targets. + */ class __PRIVATE_RemoteClientState { + constructor(e, t) { + this.clientId = e, this.activeTargetIds = t; + } + /** + * Parses a RemoteClientState from the JSON representation in WebStorage. + * Logs a warning and returns null if the format of the data is not valid. + */ static Ws(e, t) { + const n = JSON.parse(t); + let r = "object" == typeof n && n.activeTargetIds instanceof Array, i = __PRIVATE_targetIdSet(); + for (let e = 0; r && e < n.activeTargetIds.length; ++e) r = isSafeInteger(n.activeTargetIds[e]), + i = i.add(n.activeTargetIds[e]); + return r ? new __PRIVATE_RemoteClientState(e, i) : (__PRIVATE_logError(Yt, `Failed to parse client data for instance '${e}': ${t}`), + null); + } +} + +/** + * This class represents the online state for all clients participating in + * multi-tab. The online state is only written to by the primary client, and + * used in secondary clients to update their query views. + */ class __PRIVATE_SharedOnlineState { + constructor(e, t) { + this.clientId = e, this.onlineState = t; + } + /** + * Parses a SharedOnlineState from its JSON representation in WebStorage. + * Logs a warning and returns null if the format of the data is not valid. + */ static Ws(e) { + const t = JSON.parse(e); + return "object" == typeof t && -1 !== [ "Unknown", "Online", "Offline" ].indexOf(t.onlineState) && "string" == typeof t.clientId ? new __PRIVATE_SharedOnlineState(t.clientId, t.onlineState) : (__PRIVATE_logError(Yt, `Failed to parse online state: ${e}`), + null); + } +} + +/** + * Metadata state of the local client. Unlike `RemoteClientState`, this class is + * mutable and keeps track of all pending mutations, which allows us to + * update the range of pending mutation batch IDs as new mutations are added or + * removed. + * + * The data in `LocalClientState` is not read from WebStorage and instead + * updated via its instance methods. The updated state can be serialized via + * `toWebStorageJSON()`. + */ +// Visible for testing. +class __PRIVATE_LocalClientState { + constructor() { + this.activeTargetIds = __PRIVATE_targetIdSet(); + } + zs(e) { + this.activeTargetIds = this.activeTargetIds.add(e); + } + js(e) { + this.activeTargetIds = this.activeTargetIds.delete(e); + } + /** + * Converts this entry into a JSON-encoded format we can use for WebStorage. + * Does not encode `clientId` as it is part of the key in WebStorage. + */ Gs() { + const e = { + activeTargetIds: this.activeTargetIds.toArray(), + updateTimeMs: Date.now() + }; + return JSON.stringify(e); + } +} + +/** + * `WebStorageSharedClientState` uses WebStorage (window.localStorage) as the + * backing store for the SharedClientState. It keeps track of all active + * clients and supports modifications of the local client's data. + */ class __PRIVATE_WebStorageSharedClientState { + constructor(e, t, n, r, i) { + this.window = e, this.Mi = t, this.persistenceKey = n, this.Js = r, this.syncEngine = null, + this.onlineStateHandler = null, this.sequenceNumberHandler = null, this.Hs = this.Ys.bind(this), + this.Zs = new SortedMap(__PRIVATE_primitiveComparator), this.started = !1, + /** + * Captures WebStorage events that occur before `start()` is called. These + * events are replayed once `WebStorageSharedClientState` is started. + */ + this.Xs = []; + // Escape the special characters mentioned here: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions + const s = n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + this.storage = this.window.localStorage, this.currentUser = i, this.eo = createWebStorageClientStateKey(this.persistenceKey, this.Js), + this.no = + /** Assembles the key for the current sequence number. */ + function createWebStorageSequenceNumberKey(e) { + return `firestore_sequence_number_${e}`; + }(this.persistenceKey), this.Zs = this.Zs.insert(this.Js, new __PRIVATE_LocalClientState), + this.ro = new RegExp(`^${jt}_${s}_([^_]*)$`), this.io = new RegExp(`^${Jt}_${s}_(\\d+)(?:_(.*))?$`), + this.so = new RegExp(`^${Ht}_${s}_(\\d+)$`), this.oo = + /** Assembles the key for the online state of the primary tab. */ + function createWebStorageOnlineStateKey(e) { + return `firestore_online_state_${e}`; + } + // The WebStorage prefix that plays as a event to indicate the remote documents + // might have changed due to some secondary tabs loading a bundle. + // format of the key is: + // firestore_bundle_loaded_v2_ + // The version ending with "v2" stores the list of modified collection groups. + (this.persistenceKey), this._o = function createBundleLoadedKey(e) { + return `firestore_bundle_loaded_v2_${e}`; + } + // The WebStorage key prefix for the key that stores the last sequence number allocated. The key + // looks like 'firestore_sequence_number_'. + (this.persistenceKey), + // Rather than adding the storage observer during start(), we add the + // storage observer during initialization. This ensures that we collect + // events before other components populate their initial state (during their + // respective start() calls). Otherwise, we might for example miss a + // mutation that is added after LocalStore's start() processed the existing + // mutations but before we observe WebStorage events. + this.window.addEventListener("storage", this.Hs); + } + /** Returns 'true' if WebStorage is available in the current environment. */ static v(e) { + return !(!e || !e.localStorage); + } + async start() { + // Retrieve the list of existing clients to backfill the data in + // SharedClientState. + const e = await this.syncEngine.Ts(); + for (const t of e) { + if (t === this.Js) continue; + const e = this.getItem(createWebStorageClientStateKey(this.persistenceKey, t)); + if (e) { + const n = __PRIVATE_RemoteClientState.Ws(t, e); + n && (this.Zs = this.Zs.insert(n.clientId, n)); + } + } + this.ao(); + // Check if there is an existing online state and call the callback handler + // if applicable. + const t = this.storage.getItem(this.oo); + if (t) { + const e = this.uo(t); + e && this.co(e); + } + for (const e of this.Xs) this.Ys(e); + this.Xs = [], + // Register a window unload hook to remove the client metadata entry from + // WebStorage even if `shutdown()` was not called. + this.window.addEventListener("pagehide", (() => this.shutdown())), this.started = !0; + } + writeSequenceNumber(e) { + this.setItem(this.no, JSON.stringify(e)); + } + getAllActiveQueryTargets() { + return this.lo(this.Zs); + } + isActiveQueryTarget(e) { + let t = !1; + return this.Zs.forEach(((n, r) => { + r.activeTargetIds.has(e) && (t = !0); + })), t; + } + addPendingMutation(e) { + this.ho(e, "pending"); + } + updateMutationState(e, t, n) { + this.ho(e, t, n), + // Once a final mutation result is observed by other clients, they no longer + // access the mutation's metadata entry. Since WebStorage replays events + // in order, it is safe to delete the entry right after updating it. + this.Po(e); + } + addLocalQueryTarget(e, t = !0) { + let n = "not-current"; + // Lookup an existing query state if the target ID was already registered + // by another tab + if (this.isActiveQueryTarget(e)) { + const t = this.storage.getItem(createWebStorageQueryTargetMetadataKey(this.persistenceKey, e)); + if (t) { + const r = __PRIVATE_QueryTargetMetadata.Ws(e, t); + r && (n = r.state); + } + } + // If the query is listening to cache only, the target ID should not be registered with the + // local Firestore client as an active watch target. + return t && this.To.zs(e), this.ao(), n; + } + removeLocalQueryTarget(e) { + this.To.js(e), this.ao(); + } + isLocalQueryTarget(e) { + return this.To.activeTargetIds.has(e); + } + clearQueryState(e) { + this.removeItem(createWebStorageQueryTargetMetadataKey(this.persistenceKey, e)); + } + updateQueryState(e, t, n) { + this.Io(e, t, n); + } + handleUserChange(e, t, n) { + t.forEach((e => { + this.Po(e); + })), this.currentUser = e, n.forEach((e => { + this.addPendingMutation(e); + })); + } + setOnlineState(e) { + this.Eo(e); + } + notifyBundleLoaded(e) { + this.Ao(e); + } + shutdown() { + this.started && (this.window.removeEventListener("storage", this.Hs), this.removeItem(this.eo), + this.started = !1); + } + getItem(e) { + const t = this.storage.getItem(e); + return __PRIVATE_logDebug(Yt, "READ", e, t), t; + } + setItem(e, t) { + __PRIVATE_logDebug(Yt, "SET", e, t), this.storage.setItem(e, t); + } + removeItem(e) { + __PRIVATE_logDebug(Yt, "REMOVE", e), this.storage.removeItem(e); + } + Ys(e) { + // Note: The function is typed to take Event to be interface-compatible with + // `Window.addEventListener`. + const t = e; + if (t.storageArea === this.storage) { + if (__PRIVATE_logDebug(Yt, "EVENT", t.key, t.newValue), t.key === this.eo) return void __PRIVATE_logError("Received WebStorage notification for local change. Another client might have garbage-collected our state"); + this.Mi.enqueueRetryable((async () => { + if (this.started) { + if (null !== t.key) if (this.ro.test(t.key)) { + if (null == t.newValue) { + const e = this.Ro(t.key); + return this.Vo(e, null); + } + { + const e = this.mo(t.key, t.newValue); + if (e) return this.Vo(e.clientId, e); + } + } else if (this.io.test(t.key)) { + if (null !== t.newValue) { + const e = this.fo(t.key, t.newValue); + if (e) return this.po(e); + } + } else if (this.so.test(t.key)) { + if (null !== t.newValue) { + const e = this.yo(t.key, t.newValue); + if (e) return this.wo(e); + } + } else if (t.key === this.oo) { + if (null !== t.newValue) { + const e = this.uo(t.newValue); + if (e) return this.co(e); + } + } else if (t.key === this.no) { + const e = function __PRIVATE_fromWebStorageSequenceNumber(e) { + let t = __PRIVATE_ListenSequence.ce; + if (null != e) try { + const n = JSON.parse(e); + __PRIVATE_hardAssert("number" == typeof n, 30636, { + So: e + }), t = n; + } catch (e) { + __PRIVATE_logError(Yt, "Failed to read sequence number from WebStorage", e); + } + return t; + } + /** + * `MemorySharedClientState` is a simple implementation of SharedClientState for + * clients using memory persistence. The state in this class remains fully + * isolated and no synchronization is performed. + */ (t.newValue); + e !== __PRIVATE_ListenSequence.ce && this.sequenceNumberHandler(e); + } else if (t.key === this._o) { + const e = this.bo(t.newValue); + await Promise.all(e.map((e => this.syncEngine.Do(e)))); + } + } else this.Xs.push(t); + })); + } + } + get To() { + return this.Zs.get(this.Js); + } + ao() { + this.setItem(this.eo, this.To.Gs()); + } + ho(e, t, n) { + const r = new __PRIVATE_MutationMetadata(this.currentUser, e, t, n), i = createWebStorageMutationBatchKey(this.persistenceKey, this.currentUser, e); + this.setItem(i, r.Gs()); + } + Po(e) { + const t = createWebStorageMutationBatchKey(this.persistenceKey, this.currentUser, e); + this.removeItem(t); + } + Eo(e) { + const t = { + clientId: this.Js, + onlineState: e + }; + this.storage.setItem(this.oo, JSON.stringify(t)); + } + Io(e, t, n) { + const r = createWebStorageQueryTargetMetadataKey(this.persistenceKey, e), i = new __PRIVATE_QueryTargetMetadata(e, t, n); + this.setItem(r, i.Gs()); + } + Ao(e) { + const t = JSON.stringify(Array.from(e)); + this.setItem(this._o, t); + } + /** + * Parses a client state key in WebStorage. Returns null if the key does not + * match the expected key format. + */ Ro(e) { + const t = this.ro.exec(e); + return t ? t[1] : null; + } + /** + * Parses a client state in WebStorage. Returns 'null' if the value could not + * be parsed. + */ mo(e, t) { + const n = this.Ro(e); + return __PRIVATE_RemoteClientState.Ws(n, t); + } + /** + * Parses a mutation batch state in WebStorage. Returns 'null' if the value + * could not be parsed. + */ fo(e, t) { + const n = this.io.exec(e), r = Number(n[1]), i = void 0 !== n[2] ? n[2] : null; + return __PRIVATE_MutationMetadata.Ws(new User(i), r, t); + } + /** + * Parses a query target state from WebStorage. Returns 'null' if the value + * could not be parsed. + */ yo(e, t) { + const n = this.so.exec(e), r = Number(n[1]); + return __PRIVATE_QueryTargetMetadata.Ws(r, t); + } + /** + * Parses an online state from WebStorage. Returns 'null' if the value + * could not be parsed. + */ uo(e) { + return __PRIVATE_SharedOnlineState.Ws(e); + } + bo(e) { + return JSON.parse(e); + } + async po(e) { + if (e.user.uid === this.currentUser.uid) return this.syncEngine.Co(e.batchId, e.state, e.error); + __PRIVATE_logDebug(Yt, `Ignoring mutation for non-active user ${e.user.uid}`); + } + wo(e) { + return this.syncEngine.vo(e.targetId, e.state, e.error); + } + Vo(e, t) { + const n = t ? this.Zs.insert(e, t) : this.Zs.remove(e), r = this.lo(this.Zs), i = this.lo(n), s = [], o = []; + return i.forEach((e => { + r.has(e) || s.push(e); + })), r.forEach((e => { + i.has(e) || o.push(e); + })), this.syncEngine.Fo(s, o).then((() => { + this.Zs = n; + })); + } + co(e) { + // We check whether the client that wrote this online state is still active + // by comparing its client ID to the list of clients kept active in + // IndexedDb. If a client does not update their IndexedDb client state + // within 5 seconds, it is considered inactive and we don't emit an online + // state event. + this.Zs.get(e.clientId) && this.onlineStateHandler(e.onlineState); + } + lo(e) { + let t = __PRIVATE_targetIdSet(); + return e.forEach(((e, n) => { + t = t.unionWith(n.activeTargetIds); + })), t; + } +} + +class __PRIVATE_MemorySharedClientState { + constructor() { + this.Mo = new __PRIVATE_LocalClientState, this.xo = {}, this.onlineStateHandler = null, + this.sequenceNumberHandler = null; + } + addPendingMutation(e) { + // No op. + } + updateMutationState(e, t, n) { + // No op. + } + addLocalQueryTarget(e, t = !0) { + return t && this.Mo.zs(e), this.xo[e] || "not-current"; + } + updateQueryState(e, t, n) { + this.xo[e] = t; + } + removeLocalQueryTarget(e) { + this.Mo.js(e); + } + isLocalQueryTarget(e) { + return this.Mo.activeTargetIds.has(e); + } + clearQueryState(e) { + delete this.xo[e]; + } + getAllActiveQueryTargets() { + return this.Mo.activeTargetIds; + } + isActiveQueryTarget(e) { + return this.Mo.activeTargetIds.has(e); + } + start() { + return this.Mo = new __PRIVATE_LocalClientState, Promise.resolve(); + } + handleUserChange(e, t, n) { + // No op. + } + setOnlineState(e) { + // No op. + } + shutdown() {} + writeSequenceNumber(e) {} + notifyBundleLoaded(e) { + // No op. + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_NoopConnectivityMonitor { + Oo(e) { + // No-op. + } + shutdown() { + // No-op. + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// References to `window` are guarded by BrowserConnectivityMonitor.isAvailable() +/* eslint-disable no-restricted-globals */ const Zt = "ConnectivityMonitor"; + +/** + * Browser implementation of ConnectivityMonitor. + */ class __PRIVATE_BrowserConnectivityMonitor { + constructor() { + this.No = () => this.Bo(), this.Lo = () => this.ko(), this.qo = [], this.Qo(); + } + Oo(e) { + this.qo.push(e); + } + shutdown() { + window.removeEventListener("online", this.No), window.removeEventListener("offline", this.Lo); + } + Qo() { + window.addEventListener("online", this.No), window.addEventListener("offline", this.Lo); + } + Bo() { + __PRIVATE_logDebug(Zt, "Network connectivity changed: AVAILABLE"); + for (const e of this.qo) e(0 /* NetworkStatus.AVAILABLE */); + } + ko() { + __PRIVATE_logDebug(Zt, "Network connectivity changed: UNAVAILABLE"); + for (const e of this.qo) e(1 /* NetworkStatus.UNAVAILABLE */); + } + // TODO(chenbrian): Consider passing in window either into this component or + // here for testing via FakeWindow. + /** Checks that all used attributes of window are available. */ + static v() { + return "undefined" != typeof window && void 0 !== window.addEventListener && void 0 !== window.removeEventListener; + } +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The value returned from the most recent invocation of + * `generateUniqueDebugId()`, or null if it has never been invoked. + */ let Xt = null; + +/** + * Generates and returns an initial value for `lastUniqueDebugId`. + * + * The returned value is randomly selected from a range of integers that are + * represented as 8 hexadecimal digits. This means that (within reason) any + * numbers generated by incrementing the returned number by 1 will also be + * represented by 8 hexadecimal digits. This leads to all "IDs" having the same + * length when converted to a hexadecimal string, making reading logs containing + * these IDs easier to follow. And since the return value is randomly selected + * it will help to differentiate between logs from different executions. + */ +/** + * Generates and returns a unique ID as a hexadecimal string. + * + * The returned ID is intended to be used in debug logging messages to help + * correlate log messages that may be spatially separated in the logs, but + * logically related. For example, a network connection could include the same + * "debug ID" string in all of its log messages to help trace a specific + * connection over time. + * + * @return the 10-character generated ID (e.g. "0xa1b2c3d4"). + */ +function __PRIVATE_generateUniqueDebugId() { + return null === Xt ? Xt = function __PRIVATE_generateInitialUniqueDebugId() { + return 268435456 + Math.round(2147483648 * Math.random()); + }() : Xt++, "0x" + Xt.toString(16); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const en = "RestConnection", tn = { + BatchGetDocuments: "batchGet", + Commit: "commit", + RunQuery: "runQuery", + RunAggregationQuery: "runAggregationQuery" +}; + +/** + * Maps RPC names to the corresponding REST endpoint name. + * + * We use array notation to avoid mangling. + */ +/** + * Base class for all Rest-based connections to the backend (WebChannel and + * HTTP). + */ +class __PRIVATE_RestConnection { + get $o() { + // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine + // where to run the query, and expect the `request` to NOT specify the "path". + return !1; + } + constructor(e) { + this.databaseInfo = e, this.databaseId = e.databaseId; + const t = e.ssl ? "https" : "http", n = encodeURIComponent(this.databaseId.projectId), r = encodeURIComponent(this.databaseId.database); + this.Uo = t + "://" + e.host, this.Ko = `projects/${n}/databases/${r}`, this.Wo = this.databaseId.database === Tt ? `project_id=${n}` : `project_id=${n}&database_id=${r}`; + } + Go(e, t, n, r, i) { + const s = __PRIVATE_generateUniqueDebugId(), o = this.zo(e, t.toUriEncodedString()); + __PRIVATE_logDebug(en, `Sending RPC '${e}' ${s}:`, o, n); + const _ = { + "google-cloud-resource-prefix": this.Ko, + "x-goog-request-params": this.Wo + }; + this.jo(_, r, i); + const {host: a} = new URL(o), u = d(a); + return this.Jo(e, o, _, n, u).then((t => (__PRIVATE_logDebug(en, `Received RPC '${e}' ${s}: `, t), + t)), (t => { + throw __PRIVATE_logWarn(en, `RPC '${e}' ${s} failed with error: `, t, "url: ", o, "request:", n), + t; + })); + } + Ho(e, t, n, r, i, s) { + // The REST API automatically aggregates all of the streamed results, so we + // can just use the normal invoke() method. + return this.Go(e, t, n, r, i); + } + /** + * Modifies the headers for a request, adding any authorization token if + * present and any additional headers for the request. + */ jo(e, t, n) { + e["X-Goog-Api-Client"] = + // SDK_VERSION is updated to different value at runtime depending on the entry point, + // so we need to get its value when we need it in a function. + function __PRIVATE_getGoogApiClientValue() { + return "gl-js/ fire/" + N; + }(), + // Content-Type: text/plain will avoid preflight requests which might + // mess with CORS and redirects by proxies. If we add custom headers + // we will need to change this code to potentially use the $httpOverwrite + // parameter supported by ESF to avoid triggering preflight requests. + e["Content-Type"] = "text/plain", this.databaseInfo.appId && (e["X-Firebase-GMPID"] = this.databaseInfo.appId), + t && t.headers.forEach(((t, n) => e[n] = t)), n && n.headers.forEach(((t, n) => e[n] = t)); + } + zo(e, t) { + const n = tn[e]; + return `${this.Uo}/v1/${t}:${n}`; + } + /** + * Closes and cleans up any resources associated with the connection. This + * implementation is a no-op because there are no resources associated + * with the RestConnection that need to be cleaned up. + */ terminate() { + // No-op + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provides a simple helper class that implements the Stream interface to + * bridge to other implementations that are streams but do not implement the + * interface. The stream callbacks are invoked with the callOn... methods. + */ class __PRIVATE_StreamBridge { + constructor(e) { + this.Yo = e.Yo, this.Zo = e.Zo; + } + Xo(e) { + this.e_ = e; + } + t_(e) { + this.n_ = e; + } + r_(e) { + this.i_ = e; + } + onMessage(e) { + this.s_ = e; + } + close() { + this.Zo(); + } + send(e) { + this.Yo(e); + } + o_() { + this.e_(); + } + __() { + this.n_(); + } + a_(e) { + this.i_(e); + } + u_(e) { + this.s_(e); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const nn = "WebChannelConnection"; + +class __PRIVATE_WebChannelConnection extends __PRIVATE_RestConnection { + constructor(e) { + super(e), + /** A collection of open WebChannel instances */ + this.c_ = [], this.forceLongPolling = e.forceLongPolling, this.autoDetectLongPolling = e.autoDetectLongPolling, + this.useFetchStreams = e.useFetchStreams, this.longPollingOptions = e.longPollingOptions; + } + Jo(e, t, n, r, i) { + const s = __PRIVATE_generateUniqueDebugId(); + return new Promise(((i, o) => { + const _ = new w; + _.setWithCredentials(!0), _.listenOnce(S.COMPLETE, (() => { + try { + switch (_.getLastErrorCode()) { + case b.NO_ERROR: + const t = _.getResponseJson(); + __PRIVATE_logDebug(nn, `XHR for RPC '${e}' ${s} received:`, JSON.stringify(t)), + i(t); + break; + + case b.TIMEOUT: + __PRIVATE_logDebug(nn, `RPC '${e}' ${s} timed out`), o(new FirestoreError(L.DEADLINE_EXCEEDED, "Request time out")); + break; + + case b.HTTP_ERROR: + const n = _.getStatus(); + if (__PRIVATE_logDebug(nn, `RPC '${e}' ${s} failed with status:`, n, "response text:", _.getResponseText()), + n > 0) { + let e = _.getResponseJson(); + Array.isArray(e) && (e = e[0]); + const t = e?.error; + if (t && t.status && t.message) { + const e = function __PRIVATE_mapCodeFromHttpResponseErrorStatus(e) { + const t = e.toLowerCase().replace(/_/g, "-"); + return Object.values(L).indexOf(t) >= 0 ? t : L.UNKNOWN; + }(t.status); + o(new FirestoreError(e, t.message)); + } else o(new FirestoreError(L.UNKNOWN, "Server responded with status " + _.getStatus())); + } else + // If we received an HTTP_ERROR but there's no status code, + // it's most probably a connection issue + o(new FirestoreError(L.UNAVAILABLE, "Connection failed.")); + break; + + default: + fail(9055, { + l_: e, + streamId: s, + h_: _.getLastErrorCode(), + P_: _.getLastError() + }); + } + } finally { + __PRIVATE_logDebug(nn, `RPC '${e}' ${s} completed.`); + } + })); + const a = JSON.stringify(r); + __PRIVATE_logDebug(nn, `RPC '${e}' ${s} sending request:`, r), _.send(t, "POST", a, n, 15); + })); + } + T_(e, t, n) { + const r = __PRIVATE_generateUniqueDebugId(), i = [ this.Uo, "/", "google.firestore.v1.Firestore", "/", e, "/channel" ], s = D(), o = C(), _ = { + // Required for backend stickiness, routing behavior is based on this + // parameter. + httpSessionIdParam: "gsessionid", + initMessageHeaders: {}, + messageUrlParams: { + // This param is used to improve routing and project isolation by the + // backend and must be included in every request. + database: `projects/${this.databaseId.projectId}/databases/${this.databaseId.database}` + }, + sendRawJson: !0, + supportsCrossDomainXhr: !0, + internalChannelParams: { + // Override the default timeout (randomized between 10-20 seconds) since + // a large write batch on a slow internet connection may take a long + // time to send to the backend. Rather than have WebChannel impose a + // tight timeout which could lead to infinite timeouts and retries, we + // set it very large (5-10 minutes) and rely on the browser's builtin + // timeouts to kick in if the request isn't working. + forwardChannelRequestTimeoutMs: 6e5 + }, + forceLongPolling: this.forceLongPolling, + detectBufferingProxy: this.autoDetectLongPolling + }, a = this.longPollingOptions.timeoutSeconds; + void 0 !== a && (_.longPollingTimeout = Math.round(1e3 * a)), this.useFetchStreams && (_.useFetchStreams = !0), + this.jo(_.initMessageHeaders, t, n), + // Sending the custom headers we just added to request.initMessageHeaders + // (Authorization, etc.) will trigger the browser to make a CORS preflight + // request because the XHR will no longer meet the criteria for a "simple" + // CORS request: + // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#Simple_requests + // Therefore to avoid the CORS preflight request (an extra network + // roundtrip), we use the encodeInitMessageHeaders option to specify that + // the headers should instead be encoded in the request's POST payload, + // which is recognized by the webchannel backend. + _.encodeInitMessageHeaders = !0; + const u = i.join(""); + __PRIVATE_logDebug(nn, `Creating RPC '${e}' stream ${r}: ${u}`, _); + const c = s.createWebChannel(u, _); + this.I_(c); + // WebChannel supports sending the first message with the handshake - saving + // a network round trip. However, it will have to call send in the same + // JS event loop as open. In order to enforce this, we delay actually + // opening the WebChannel until send is called. Whether we have called + // open is tracked with this variable. + let l = !1, h = !1; + // A flag to determine whether the stream was closed (by us or through an + // error/close event) to avoid delivering multiple close events or sending + // on a closed stream + const P = new __PRIVATE_StreamBridge({ + Yo: t => { + h ? __PRIVATE_logDebug(nn, `Not sending because RPC '${e}' stream ${r} is closed:`, t) : (l || (__PRIVATE_logDebug(nn, `Opening RPC '${e}' stream ${r} transport.`), + c.open(), l = !0), __PRIVATE_logDebug(nn, `RPC '${e}' stream ${r} sending:`, t), + c.send(t)); + }, + Zo: () => c.close() + }), __PRIVATE_unguardedEventListen = (e, t, n) => { + // TODO(dimond): closure typing seems broken because WebChannel does + // not implement goog.events.Listenable + e.listen(t, (e => { + try { + n(e); + } catch (e) { + setTimeout((() => { + throw e; + }), 0); + } + })); + }; + // Closure events are guarded and exceptions are swallowed, so catch any + // exception and rethrow using a setTimeout so they become visible again. + // Note that eventually this function could go away if we are confident + // enough the code is exception free. + return __PRIVATE_unguardedEventListen(c, v.EventType.OPEN, (() => { + h || (__PRIVATE_logDebug(nn, `RPC '${e}' stream ${r} transport opened.`), P.o_()); + })), __PRIVATE_unguardedEventListen(c, v.EventType.CLOSE, (() => { + h || (h = !0, __PRIVATE_logDebug(nn, `RPC '${e}' stream ${r} transport closed`), + P.a_(), this.E_(c)); + })), __PRIVATE_unguardedEventListen(c, v.EventType.ERROR, (t => { + h || (h = !0, __PRIVATE_logWarn(nn, `RPC '${e}' stream ${r} transport errored. Name:`, t.name, "Message:", t.message), + P.a_(new FirestoreError(L.UNAVAILABLE, "The operation could not be completed"))); + })), __PRIVATE_unguardedEventListen(c, v.EventType.MESSAGE, (t => { + if (!h) { + const n = t.data[0]; + __PRIVATE_hardAssert(!!n, 16349); + // TODO(b/35143891): There is a bug in One Platform that caused errors + // (and only errors) to be wrapped in an extra array. To be forward + // compatible with the bug we need to check either condition. The latter + // can be removed once the fix has been rolled out. + // Use any because msgData.error is not typed. + const i = n, s = i?.error || i[0]?.error; + if (s) { + __PRIVATE_logDebug(nn, `RPC '${e}' stream ${r} received error:`, s); + // error.status will be a string like 'OK' or 'NOT_FOUND'. + const t = s.status; + let n = + /** + * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'. + * + * @returns The Code equivalent to the given status string or undefined if + * there is no match. + */ + function __PRIVATE_mapCodeFromRpcStatus(e) { + // lookup by string + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const t = St[e]; + if (void 0 !== t) return __PRIVATE_mapCodeFromRpcCode(t); + }(t), i = s.message; + void 0 === n && (n = L.INTERNAL, i = "Unknown error status: " + t + " with message " + s.message), + // Mark closed so no further events are propagated + h = !0, P.a_(new FirestoreError(n, i)), c.close(); + } else __PRIVATE_logDebug(nn, `RPC '${e}' stream ${r} received:`, n), P.u_(n); + } + })), __PRIVATE_unguardedEventListen(o, F.STAT_EVENT, (t => { + t.stat === M.PROXY ? __PRIVATE_logDebug(nn, `RPC '${e}' stream ${r} detected buffering proxy`) : t.stat === M.NOPROXY && __PRIVATE_logDebug(nn, `RPC '${e}' stream ${r} detected no buffering proxy`); + })), setTimeout((() => { + // Technically we could/should wait for the WebChannel opened event, + // but because we want to send the first message with the WebChannel + // handshake we pretend the channel opened here (asynchronously), and + // then delay the actual open until the first message is sent. + P.__(); + }), 0), P; + } + /** + * Closes and cleans up any resources associated with the connection. + */ terminate() { + // If the Firestore instance is terminated, we will explicitly + // close any remaining open WebChannel instances. + this.c_.forEach((e => e.close())), this.c_ = []; + } + /** + * Add a WebChannel instance to the collection of open instances. + * @param webChannel + */ I_(e) { + this.c_.push(e); + } + /** + * Remove a WebChannel instance from the collection of open instances. + * @param webChannel + */ E_(e) { + this.c_ = this.c_.filter((t => t === e)); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Initializes the WebChannelConnection for the browser. */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** The Platform's 'window' implementation or null if not available. */ +function __PRIVATE_getWindow() { + // `window` is not always available, e.g. in ReactNative and WebWorkers. + // eslint-disable-next-line no-restricted-globals + return "undefined" != typeof window ? window : null; +} + +/** The Platform's 'document' implementation or null if not available. */ function getDocument() { + // `document` is not always available, e.g. in ReactNative and WebWorkers. + // eslint-disable-next-line no-restricted-globals + return "undefined" != typeof document ? document : null; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_newSerializer(e) { + return new JsonProtoSerializer(e, /* useProto3Json= */ !0); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A helper for running delayed tasks following an exponential backoff curve + * between attempts. + * + * Each delay is made up of a "base" delay which follows the exponential + * backoff curve, and a +/- 50% "jitter" that is calculated and added to the + * base delay. This prevents clients from accidentally synchronizing their + * delays causing spikes of load to the backend. + */ +class __PRIVATE_ExponentialBackoff { + constructor( + /** + * The AsyncQueue to run backoff operations on. + */ + e, + /** + * The ID to use when scheduling backoff operations on the AsyncQueue. + */ + t, + /** + * The initial delay (used as the base delay on the first retry attempt). + * Note that jitter will still be applied, so the actual delay could be as + * little as 0.5*initialDelayMs. + */ + n = 1e3 + /** + * The multiplier to use to determine the extended base delay after each + * attempt. + */ , r = 1.5 + /** + * The maximum base delay after which no further backoff is performed. + * Note that jitter will still be applied, so the actual delay could be as + * much as 1.5*maxDelayMs. + */ , i = 6e4) { + this.Mi = e, this.timerId = t, this.d_ = n, this.A_ = r, this.R_ = i, this.V_ = 0, + this.m_ = null, + /** The last backoff attempt, as epoch milliseconds. */ + this.f_ = Date.now(), this.reset(); + } + /** + * Resets the backoff delay. + * + * The very next backoffAndWait() will have no delay. If it is called again + * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and + * subsequent ones will increase according to the backoffFactor. + */ reset() { + this.V_ = 0; + } + /** + * Resets the backoff delay to the maximum delay (e.g. for use after a + * RESOURCE_EXHAUSTED error). + */ g_() { + this.V_ = this.R_; + } + /** + * Returns a promise that resolves after currentDelayMs, and increases the + * delay for any subsequent attempts. If there was a pending backoff operation + * already, it will be canceled. + */ p_(e) { + // Cancel any pending backoff operation. + this.cancel(); + // First schedule using the current base (which may be 0 and should be + // honored as such). + const t = Math.floor(this.V_ + this.y_()), n = Math.max(0, Date.now() - this.f_), r = Math.max(0, t - n); + // Guard against lastAttemptTime being in the future due to a clock change. + r > 0 && __PRIVATE_logDebug("ExponentialBackoff", `Backing off for ${r} ms (base delay: ${this.V_} ms, delay with jitter: ${t} ms, last attempt: ${n} ms ago)`), + this.m_ = this.Mi.enqueueAfterDelay(this.timerId, r, (() => (this.f_ = Date.now(), + e()))), + // Apply backoff factor to determine next delay and ensure it is within + // bounds. + this.V_ *= this.A_, this.V_ < this.d_ && (this.V_ = this.d_), this.V_ > this.R_ && (this.V_ = this.R_); + } + w_() { + null !== this.m_ && (this.m_.skipDelay(), this.m_ = null); + } + cancel() { + null !== this.m_ && (this.m_.cancel(), this.m_ = null); + } + /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ y_() { + return (Math.random() - .5) * this.V_; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const rn = "PersistentStream"; + +/** The time a stream stays open after it is marked idle. */ +/** + * A PersistentStream is an abstract base class that represents a streaming RPC + * to the Firestore backend. It's built on top of the connections own support + * for streaming RPCs, and adds several critical features for our clients: + * + * - Exponential backoff on failure + * - Authentication via CredentialsProvider + * - Dispatching all callbacks into the shared worker queue + * - Closing idle streams after 60 seconds of inactivity + * + * Subclasses of PersistentStream implement serialization of models to and + * from the JSON representation of the protocol buffers for a specific + * streaming RPC. + * + * ## Starting and Stopping + * + * Streaming RPCs are stateful and need to be start()ed before messages can + * be sent and received. The PersistentStream will call the onOpen() function + * of the listener once the stream is ready to accept requests. + * + * Should a start() fail, PersistentStream will call the registered onClose() + * listener with a FirestoreError indicating what went wrong. + * + * A PersistentStream can be started and stopped repeatedly. + * + * Generic types: + * SendType: The type of the outgoing message of the underlying + * connection stream + * ReceiveType: The type of the incoming message of the underlying + * connection stream + * ListenerType: The type of the listener that will be used for callbacks + */ +class __PRIVATE_PersistentStream { + constructor(e, t, n, r, i, s, o, _) { + this.Mi = e, this.S_ = n, this.b_ = r, this.connection = i, this.authCredentialsProvider = s, + this.appCheckCredentialsProvider = o, this.listener = _, this.state = 0 /* PersistentStreamState.Initial */ , + /** + * A close count that's incremented every time the stream is closed; used by + * getCloseGuardedDispatcher() to invalidate callbacks that happen after + * close. + */ + this.D_ = 0, this.C_ = null, this.v_ = null, this.stream = null, + /** + * Count of response messages received. + */ + this.F_ = 0, this.M_ = new __PRIVATE_ExponentialBackoff(e, t); + } + /** + * Returns true if start() has been called and no error has occurred. True + * indicates the stream is open or in the process of opening (which + * encompasses respecting backoff, getting auth tokens, and starting the + * actual RPC). Use isOpen() to determine if the stream is open and ready for + * outbound requests. + */ x_() { + return 1 /* PersistentStreamState.Starting */ === this.state || 5 /* PersistentStreamState.Backoff */ === this.state || this.O_(); + } + /** + * Returns true if the underlying RPC is open (the onOpen() listener has been + * called) and the stream is ready for outbound requests. + */ O_() { + return 2 /* PersistentStreamState.Open */ === this.state || 3 /* PersistentStreamState.Healthy */ === this.state; + } + /** + * Starts the RPC. Only allowed if isStarted() returns false. The stream is + * not immediately ready for use: onOpen() will be invoked when the RPC is + * ready for outbound requests, at which point isOpen() will return true. + * + * When start returns, isStarted() will return true. + */ start() { + this.F_ = 0, 4 /* PersistentStreamState.Error */ !== this.state ? this.auth() : this.N_(); + } + /** + * Stops the RPC. This call is idempotent and allowed regardless of the + * current isStarted() state. + * + * When stop returns, isStarted() and isOpen() will both return false. + */ async stop() { + this.x_() && await this.close(0 /* PersistentStreamState.Initial */); + } + /** + * After an error the stream will usually back off on the next attempt to + * start it. If the error warrants an immediate restart of the stream, the + * sender can use this to indicate that the receiver should not back off. + * + * Each error will call the onClose() listener. That function can decide to + * inhibit backoff if required. + */ B_() { + this.state = 0 /* PersistentStreamState.Initial */ , this.M_.reset(); + } + /** + * Marks this stream as idle. If no further actions are performed on the + * stream for one minute, the stream will automatically close itself and + * notify the stream's onClose() handler with Status.OK. The stream will then + * be in a !isStarted() state, requiring the caller to start the stream again + * before further use. + * + * Only streams that are in state 'Open' can be marked idle, as all other + * states imply pending network operations. + */ L_() { + // Starts the idle time if we are in state 'Open' and are not yet already + // running a timer (in which case the previous idle timeout still applies). + this.O_() && null === this.C_ && (this.C_ = this.Mi.enqueueAfterDelay(this.S_, 6e4, (() => this.k_()))); + } + /** Sends a message to the underlying stream. */ q_(e) { + this.Q_(), this.stream.send(e); + } + /** Called by the idle timer when the stream should close due to inactivity. */ async k_() { + if (this.O_()) + // When timing out an idle stream there's no reason to force the stream into backoff when + // it restarts so set the stream state to Initial instead of Error. + return this.close(0 /* PersistentStreamState.Initial */); + } + /** Marks the stream as active again. */ Q_() { + this.C_ && (this.C_.cancel(), this.C_ = null); + } + /** Cancels the health check delayed operation. */ U_() { + this.v_ && (this.v_.cancel(), this.v_ = null); + } + /** + * Closes the stream and cleans up as necessary: + * + * * closes the underlying GRPC stream; + * * calls the onClose handler with the given 'error'; + * * sets internal stream state to 'finalState'; + * * adjusts the backoff timer based on the error + * + * A new stream can be opened by calling start(). + * + * @param finalState - the intended state of the stream after closing. + * @param error - the error the connection was closed with. + */ async close(e, t) { + // Cancel any outstanding timers (they're guaranteed not to execute). + this.Q_(), this.U_(), this.M_.cancel(), + // Invalidates any stream-related callbacks (e.g. from auth or the + // underlying stream), guaranteeing they won't execute. + this.D_++, 4 /* PersistentStreamState.Error */ !== e ? + // If this is an intentional close ensure we don't delay our next connection attempt. + this.M_.reset() : t && t.code === L.RESOURCE_EXHAUSTED ? ( + // Log the error. (Probably either 'quota exceeded' or 'max queue length reached'.) + __PRIVATE_logError(t.toString()), __PRIVATE_logError("Using maximum backoff delay to prevent overloading the backend."), + this.M_.g_()) : t && t.code === L.UNAUTHENTICATED && 3 /* PersistentStreamState.Healthy */ !== this.state && ( + // "unauthenticated" error means the token was rejected. This should rarely + // happen since both Auth and AppCheck ensure a sufficient TTL when we + // request a token. If a user manually resets their system clock this can + // fail, however. In this case, we should get a Code.UNAUTHENTICATED error + // before we received the first message and we need to invalidate the token + // to ensure that we fetch a new token. + this.authCredentialsProvider.invalidateToken(), this.appCheckCredentialsProvider.invalidateToken()), + // Clean up the underlying stream because we are no longer interested in events. + null !== this.stream && (this.K_(), this.stream.close(), this.stream = null), + // This state must be assigned before calling onClose() to allow the callback to + // inhibit backoff or otherwise manipulate the state in its non-started state. + this.state = e, + // Notify the listener that the stream closed. + await this.listener.r_(t); + } + /** + * Can be overridden to perform additional cleanup before the stream is closed. + * Calling super.tearDown() is not required. + */ K_() {} + auth() { + this.state = 1 /* PersistentStreamState.Starting */; + const e = this.W_(this.D_), t = this.D_; + // TODO(mikelehen): Just use dispatchIfNotClosed, but see TODO below. + Promise.all([ this.authCredentialsProvider.getToken(), this.appCheckCredentialsProvider.getToken() ]).then((([e, n]) => { + // Stream can be stopped while waiting for authentication. + // TODO(mikelehen): We really should just use dispatchIfNotClosed + // and let this dispatch onto the queue, but that opened a spec test can + // of worms that I don't want to deal with in this PR. + this.D_ === t && + // Normally we'd have to schedule the callback on the AsyncQueue. + // However, the following calls are safe to be called outside the + // AsyncQueue since they don't chain asynchronous calls + this.G_(e, n); + }), (t => { + e((() => { + const e = new FirestoreError(L.UNKNOWN, "Fetching auth token failed: " + t.message); + return this.z_(e); + })); + })); + } + G_(e, t) { + const n = this.W_(this.D_); + this.stream = this.j_(e, t), this.stream.Xo((() => { + n((() => this.listener.Xo())); + })), this.stream.t_((() => { + n((() => (this.state = 2 /* PersistentStreamState.Open */ , this.v_ = this.Mi.enqueueAfterDelay(this.b_, 1e4, (() => (this.O_() && (this.state = 3 /* PersistentStreamState.Healthy */), + Promise.resolve()))), this.listener.t_()))); + })), this.stream.r_((e => { + n((() => this.z_(e))); + })), this.stream.onMessage((e => { + n((() => 1 == ++this.F_ ? this.J_(e) : this.onNext(e))); + })); + } + N_() { + this.state = 5 /* PersistentStreamState.Backoff */ , this.M_.p_((async () => { + this.state = 0 /* PersistentStreamState.Initial */ , this.start(); + })); + } + // Visible for tests + z_(e) { + // In theory the stream could close cleanly, however, in our current model + // we never expect this to happen because if we stop a stream ourselves, + // this callback will never be called. To prevent cases where we retry + // without a backoff accidentally, we set the stream to error in all cases. + return __PRIVATE_logDebug(rn, `close with error: ${e}`), this.stream = null, this.close(4 /* PersistentStreamState.Error */ , e); + } + /** + * Returns a "dispatcher" function that dispatches operations onto the + * AsyncQueue but only runs them if closeCount remains unchanged. This allows + * us to turn auth / stream callbacks into no-ops if the stream is closed / + * re-opened, etc. + */ W_(e) { + return t => { + this.Mi.enqueueAndForget((() => this.D_ === e ? t() : (__PRIVATE_logDebug(rn, "stream callback skipped by getCloseGuardedDispatcher."), + Promise.resolve()))); + }; + } +} + +/** + * A PersistentStream that implements the Listen RPC. + * + * Once the Listen stream has called the onOpen() listener, any number of + * listen() and unlisten() calls can be made to control what changes will be + * sent from the server for ListenResponses. + */ class __PRIVATE_PersistentListenStream extends __PRIVATE_PersistentStream { + constructor(e, t, n, r, i, s) { + super(e, "listen_stream_connection_backoff" /* TimerId.ListenStreamConnectionBackoff */ , "listen_stream_idle" /* TimerId.ListenStreamIdle */ , "health_check_timeout" /* TimerId.HealthCheckTimeout */ , t, n, r, s), + this.serializer = i; + } + j_(e, t) { + return this.connection.T_("Listen", e, t); + } + J_(e) { + return this.onNext(e); + } + onNext(e) { + // A successful response means the stream is healthy + this.M_.reset(); + const t = __PRIVATE_fromWatchChange(this.serializer, e), n = function __PRIVATE_versionFromListenResponse(e) { + // We have only reached a consistent snapshot for the entire stream if there + // is a read_time set and it applies to all targets (i.e. the list of + // targets is empty). The backend is guaranteed to send such responses. + if (!("targetChange" in e)) return SnapshotVersion.min(); + const t = e.targetChange; + return t.targetIds && t.targetIds.length ? SnapshotVersion.min() : t.readTime ? __PRIVATE_fromVersion(t.readTime) : SnapshotVersion.min(); + }(e); + return this.listener.H_(t, n); + } + /** + * Registers interest in the results of the given target. If the target + * includes a resumeToken it will be included in the request. Results that + * affect the target will be streamed back as WatchChange messages that + * reference the targetId. + */ Y_(e) { + const t = {}; + t.database = __PRIVATE_getEncodedDatabaseId(this.serializer), t.addTarget = function __PRIVATE_toTarget(e, t) { + let n; + const r = t.target; + if (n = __PRIVATE_targetIsDocumentTarget(r) ? { + documents: __PRIVATE_toDocumentsTarget(e, r) + } : { + query: __PRIVATE_toQueryTarget(e, r).ft + }, n.targetId = t.targetId, t.resumeToken.approximateByteSize() > 0) { + n.resumeToken = __PRIVATE_toBytes(e, t.resumeToken); + const r = __PRIVATE_toInt32Proto(e, t.expectedCount); + null !== r && (n.expectedCount = r); + } else if (t.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) { + // TODO(wuandy): Consider removing above check because it is most likely true. + // Right now, many tests depend on this behaviour though (leaving min() out + // of serialization). + n.readTime = toTimestamp(e, t.snapshotVersion.toTimestamp()); + const r = __PRIVATE_toInt32Proto(e, t.expectedCount); + null !== r && (n.expectedCount = r); + } + return n; + }(this.serializer, e); + const n = __PRIVATE_toListenRequestLabels(this.serializer, e); + n && (t.labels = n), this.q_(t); + } + /** + * Unregisters interest in the results of the target associated with the + * given targetId. + */ Z_(e) { + const t = {}; + t.database = __PRIVATE_getEncodedDatabaseId(this.serializer), t.removeTarget = e, + this.q_(t); + } +} + +/** + * A Stream that implements the Write RPC. + * + * The Write RPC requires the caller to maintain special streamToken + * state in between calls, to help the server understand which responses the + * client has processed by the time the next request is made. Every response + * will contain a streamToken; this value must be passed to the next + * request. + * + * After calling start() on this stream, the next request must be a handshake, + * containing whatever streamToken is on hand. Once a response to this + * request is received, all pending mutations may be submitted. When + * submitting multiple batches of mutations at the same time, it's + * okay to use the same streamToken for the calls to writeMutations. + * + * TODO(b/33271235): Use proto types + */ class __PRIVATE_PersistentWriteStream extends __PRIVATE_PersistentStream { + constructor(e, t, n, r, i, s) { + super(e, "write_stream_connection_backoff" /* TimerId.WriteStreamConnectionBackoff */ , "write_stream_idle" /* TimerId.WriteStreamIdle */ , "health_check_timeout" /* TimerId.HealthCheckTimeout */ , t, n, r, s), + this.serializer = i; + } + /** + * Tracks whether or not a handshake has been successfully exchanged and + * the stream is ready to accept mutations. + */ get X_() { + return this.F_ > 0; + } + // Override of PersistentStream.start + start() { + this.lastStreamToken = void 0, super.start(); + } + K_() { + this.X_ && this.ea([]); + } + j_(e, t) { + return this.connection.T_("Write", e, t); + } + J_(e) { + // Always capture the last stream token. + return __PRIVATE_hardAssert(!!e.streamToken, 31322), this.lastStreamToken = e.streamToken, + // The first response is always the handshake response + __PRIVATE_hardAssert(!e.writeResults || 0 === e.writeResults.length, 55816), this.listener.ta(); + } + onNext(e) { + // Always capture the last stream token. + __PRIVATE_hardAssert(!!e.streamToken, 12678), this.lastStreamToken = e.streamToken, + // A successful first write response means the stream is healthy, + // Note, that we could consider a successful handshake healthy, however, + // the write itself might be causing an error we want to back off from. + this.M_.reset(); + const t = __PRIVATE_fromWriteResults(e.writeResults, e.commitTime), n = __PRIVATE_fromVersion(e.commitTime); + return this.listener.na(n, t); + } + /** + * Sends an initial streamToken to the server, performing the handshake + * required to make the StreamingWrite RPC work. Subsequent + * calls should wait until onHandshakeComplete was called. + */ ra() { + // TODO(dimond): Support stream resumption. We intentionally do not set the + // stream token on the handshake, ignoring any stream token we might have. + const e = {}; + e.database = __PRIVATE_getEncodedDatabaseId(this.serializer), this.q_(e); + } + /** Sends a group of mutations to the Firestore backend to apply. */ ea(e) { + const t = { + streamToken: this.lastStreamToken, + writes: e.map((e => toMutation(this.serializer, e))) + }; + this.q_(t); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Datastore and its related methods are a wrapper around the external Google + * Cloud Datastore grpc API, which provides an interface that is more convenient + * for the rest of the client SDK architecture to consume. + */ class Datastore {} + +/** + * An implementation of Datastore that exposes additional state for internal + * consumption. + */ class __PRIVATE_DatastoreImpl extends Datastore { + constructor(e, t, n, r) { + super(), this.authCredentials = e, this.appCheckCredentials = t, this.connection = n, + this.serializer = r, this.ia = !1; + } + sa() { + if (this.ia) throw new FirestoreError(L.FAILED_PRECONDITION, "The client has already been terminated."); + } + /** Invokes the provided RPC with auth and AppCheck tokens. */ Go(e, t, n, r) { + return this.sa(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([i, s]) => this.connection.Go(e, __PRIVATE_toResourcePath(t, n), r, i, s))).catch((e => { + throw "FirebaseError" === e.name ? (e.code === L.UNAUTHENTICATED && (this.authCredentials.invalidateToken(), + this.appCheckCredentials.invalidateToken()), e) : new FirestoreError(L.UNKNOWN, e.toString()); + })); + } + /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ Ho(e, t, n, r, i) { + return this.sa(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([s, o]) => this.connection.Ho(e, __PRIVATE_toResourcePath(t, n), r, s, o, i))).catch((e => { + throw "FirebaseError" === e.name ? (e.code === L.UNAUTHENTICATED && (this.authCredentials.invalidateToken(), + this.appCheckCredentials.invalidateToken()), e) : new FirestoreError(L.UNKNOWN, e.toString()); + })); + } + terminate() { + this.ia = !0, this.connection.terminate(); + } +} + +// TODO(firestorexp): Make sure there is only one Datastore instance per +// firestore-exp client. +/** + * A component used by the RemoteStore to track the OnlineState (that is, + * whether or not the client as a whole should be considered to be online or + * offline), implementing the appropriate heuristics. + * + * In particular, when the client is trying to connect to the backend, we + * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for + * a connection to succeed. If we have too many failures or the timeout elapses, + * then we set the OnlineState to Offline, and the client will behave as if + * it is offline (get()s will return cached data, etc.). + */ +class __PRIVATE_OnlineStateTracker { + constructor(e, t) { + this.asyncQueue = e, this.onlineStateHandler = t, + /** The current OnlineState. */ + this.state = "Unknown" /* OnlineState.Unknown */ , + /** + * A count of consecutive failures to open the stream. If it reaches the + * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to + * Offline. + */ + this.oa = 0, + /** + * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we + * transition from OnlineState.Unknown to OnlineState.Offline without waiting + * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times). + */ + this._a = null, + /** + * Whether the client should log a warning message if it fails to connect to + * the backend (initially true, cleared after a successful stream, or if we've + * logged the message already). + */ + this.aa = !0; + } + /** + * Called by RemoteStore when a watch stream is started (including on each + * backoff attempt). + * + * If this is the first attempt, it sets the OnlineState to Unknown and starts + * the onlineStateTimer. + */ ua() { + 0 === this.oa && (this.ca("Unknown" /* OnlineState.Unknown */), this._a = this.asyncQueue.enqueueAfterDelay("online_state_timeout" /* TimerId.OnlineStateTimeout */ , 1e4, (() => (this._a = null, + this.la("Backend didn't respond within 10 seconds."), this.ca("Offline" /* OnlineState.Offline */), + Promise.resolve())))); + } + /** + * Updates our OnlineState as appropriate after the watch stream reports a + * failure. The first failure moves us to the 'Unknown' state. We then may + * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we + * actually transition to the 'Offline' state. + */ ha(e) { + "Online" /* OnlineState.Online */ === this.state ? this.ca("Unknown" /* OnlineState.Unknown */) : (this.oa++, + this.oa >= 1 && (this.Pa(), this.la(`Connection failed 1 times. Most recent error: ${e.toString()}`), + this.ca("Offline" /* OnlineState.Offline */))); + } + /** + * Explicitly sets the OnlineState to the specified state. + * + * Note that this resets our timers / failure counters, etc. used by our + * Offline heuristics, so must not be used in place of + * handleWatchStreamStart() and handleWatchStreamFailure(). + */ set(e) { + this.Pa(), this.oa = 0, "Online" /* OnlineState.Online */ === e && ( + // We've connected to watch at least once. Don't warn the developer + // about being offline going forward. + this.aa = !1), this.ca(e); + } + ca(e) { + e !== this.state && (this.state = e, this.onlineStateHandler(e)); + } + la(e) { + const t = `Could not reach Cloud Firestore backend. ${e}\nThis typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.`; + this.aa ? (__PRIVATE_logError(t), this.aa = !1) : __PRIVATE_logDebug("OnlineStateTracker", t); + } + Pa() { + null !== this._a && (this._a.cancel(), this._a = null); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const sn = "RemoteStore"; + +// TODO(b/35853402): Negotiate this with the stream. +class __PRIVATE_RemoteStoreImpl { + constructor( + /** + * The local store, used to fill the write pipeline with outbound mutations. + */ + e, + /** The client-side proxy for interacting with the backend. */ + t, n, r, i) { + this.localStore = e, this.datastore = t, this.asyncQueue = n, this.remoteSyncer = {}, + /** + * A list of up to MAX_PENDING_WRITES writes that we have fetched from the + * LocalStore via fillWritePipeline() and have or will send to the write + * stream. + * + * Whenever writePipeline.length > 0 the RemoteStore will attempt to start or + * restart the write stream. When the stream is established the writes in the + * pipeline will be sent in order. + * + * Writes remain in writePipeline until they are acknowledged by the backend + * and thus will automatically be re-sent if the stream is interrupted / + * restarted before they're acknowledged. + * + * Write responses from the backend are linked to their originating request + * purely based on order, and so we can just shift() writes from the front of + * the writePipeline as we receive responses. + */ + this.Ta = [], + /** + * A mapping of watched targets that the client cares about tracking and the + * user has explicitly called a 'listen' for this target. + * + * These targets may or may not have been sent to or acknowledged by the + * server. On re-establishing the listen stream, these targets should be sent + * to the server. The targets removed with unlistens are removed eagerly + * without waiting for confirmation from the listen stream. + */ + this.Ia = new Map, + /** + * A set of reasons for why the RemoteStore may be offline. If empty, the + * RemoteStore may start its network connections. + */ + this.Ea = new Set, + /** + * Event handlers that get called when the network is disabled or enabled. + * + * PORTING NOTE: These functions are used on the Web client to create the + * underlying streams (to support tree-shakeable streams). On Android and iOS, + * the streams are created during construction of RemoteStore. + */ + this.da = [], this.Aa = i, this.Aa.Oo((e => { + n.enqueueAndForget((async () => { + // Porting Note: Unlike iOS, `restartNetwork()` is called even when the + // network becomes unreachable as we don't have any other way to tear + // down our streams. + __PRIVATE_canUseNetwork(this) && (__PRIVATE_logDebug(sn, "Restarting streams for network reachability change."), + await async function __PRIVATE_restartNetwork(e) { + const t = __PRIVATE_debugCast(e); + t.Ea.add(4 /* OfflineCause.ConnectivityChange */), await __PRIVATE_disableNetworkInternal(t), + t.Ra.set("Unknown" /* OnlineState.Unknown */), t.Ea.delete(4 /* OfflineCause.ConnectivityChange */), + await __PRIVATE_enableNetworkInternal(t); + }(this)); + })); + })), this.Ra = new __PRIVATE_OnlineStateTracker(n, r); + } +} + +async function __PRIVATE_enableNetworkInternal(e) { + if (__PRIVATE_canUseNetwork(e)) for (const t of e.da) await t(/* enabled= */ !0); +} + +/** + * Temporarily disables the network. The network can be re-enabled using + * enableNetwork(). + */ async function __PRIVATE_disableNetworkInternal(e) { + for (const t of e.da) await t(/* enabled= */ !1); +} + +/** + * Starts new listen for the given target. Uses resume token if provided. It + * is a no-op if the target of given `TargetData` is already being listened to. + */ +function __PRIVATE_remoteStoreListen(e, t) { + const n = __PRIVATE_debugCast(e); + n.Ia.has(t.targetId) || ( + // Mark this as something the client is currently listening for. + n.Ia.set(t.targetId, t), __PRIVATE_shouldStartWatchStream(n) ? + // The listen will be sent in onWatchStreamOpen + __PRIVATE_startWatchStream(n) : __PRIVATE_ensureWatchStream(n).O_() && __PRIVATE_sendWatchRequest(n, t)); +} + +/** + * Removes the listen from server. It is a no-op if the given target id is + * not being listened to. + */ function __PRIVATE_remoteStoreUnlisten(e, t) { + const n = __PRIVATE_debugCast(e), r = __PRIVATE_ensureWatchStream(n); + n.Ia.delete(t), r.O_() && __PRIVATE_sendUnwatchRequest(n, t), 0 === n.Ia.size && (r.O_() ? r.L_() : __PRIVATE_canUseNetwork(n) && + // Revert to OnlineState.Unknown if the watch stream is not open and we + // have no listeners, since without any listens to send we cannot + // confirm if the stream is healthy and upgrade to OnlineState.Online. + n.Ra.set("Unknown" /* OnlineState.Unknown */)); +} + +/** + * We need to increment the expected number of pending responses we're due + * from watch so we wait for the ack to process any messages from this target. + */ function __PRIVATE_sendWatchRequest(e, t) { + if (e.Va.Ue(t.targetId), t.resumeToken.approximateByteSize() > 0 || t.snapshotVersion.compareTo(SnapshotVersion.min()) > 0) { + const n = e.remoteSyncer.getRemoteKeysForTarget(t.targetId).size; + t = t.withExpectedCount(n); + } + __PRIVATE_ensureWatchStream(e).Y_(t); +} + +/** + * We need to increment the expected number of pending responses we're due + * from watch so we wait for the removal on the server before we process any + * messages from this target. + */ function __PRIVATE_sendUnwatchRequest(e, t) { + e.Va.Ue(t), __PRIVATE_ensureWatchStream(e).Z_(t); +} + +function __PRIVATE_startWatchStream(e) { + e.Va = new __PRIVATE_WatchChangeAggregator({ + getRemoteKeysForTarget: t => e.remoteSyncer.getRemoteKeysForTarget(t), + At: t => e.Ia.get(t) || null, + ht: () => e.datastore.serializer.databaseId + }), __PRIVATE_ensureWatchStream(e).start(), e.Ra.ua(); +} + +/** + * Returns whether the watch stream should be started because it's necessary + * and has not yet been started. + */ function __PRIVATE_shouldStartWatchStream(e) { + return __PRIVATE_canUseNetwork(e) && !__PRIVATE_ensureWatchStream(e).x_() && e.Ia.size > 0; +} + +function __PRIVATE_canUseNetwork(e) { + return 0 === __PRIVATE_debugCast(e).Ea.size; +} + +function __PRIVATE_cleanUpWatchStreamState(e) { + e.Va = void 0; +} + +async function __PRIVATE_onWatchStreamConnected(e) { + // Mark the client as online since we got a "connected" notification. + e.Ra.set("Online" /* OnlineState.Online */); +} + +async function __PRIVATE_onWatchStreamOpen(e) { + e.Ia.forEach(((t, n) => { + __PRIVATE_sendWatchRequest(e, t); + })); +} + +async function __PRIVATE_onWatchStreamClose(e, t) { + __PRIVATE_cleanUpWatchStreamState(e), + // If we still need the watch stream, retry the connection. + __PRIVATE_shouldStartWatchStream(e) ? (e.Ra.ha(t), __PRIVATE_startWatchStream(e)) : + // No need to restart watch stream because there are no active targets. + // The online state is set to unknown because there is no active attempt + // at establishing a connection + e.Ra.set("Unknown" /* OnlineState.Unknown */); +} + +async function __PRIVATE_onWatchStreamChange(e, t, n) { + if ( + // Mark the client as online since we got a message from the server + e.Ra.set("Online" /* OnlineState.Online */), t instanceof __PRIVATE_WatchTargetChange && 2 /* WatchTargetChangeState.Removed */ === t.state && t.cause) + // There was an error on a target, don't wait for a consistent snapshot + // to raise events + try { + /** Handles an error on a target */ + await async function __PRIVATE_handleTargetError(e, t) { + const n = t.cause; + for (const r of t.targetIds) + // A watched target might have been removed already. + e.Ia.has(r) && (await e.remoteSyncer.rejectListen(r, n), e.Ia.delete(r), e.Va.removeTarget(r)); + } + /** + * Attempts to fill our write pipeline with writes from the LocalStore. + * + * Called internally to bootstrap or refill the write pipeline and by + * SyncEngine whenever there are new mutations to process. + * + * Starts the write stream if necessary. + */ (e, t); + } catch (n) { + __PRIVATE_logDebug(sn, "Failed to remove targets %s: %s ", t.targetIds.join(","), n), + await __PRIVATE_disableNetworkUntilRecovery(e, n); + } else if (t instanceof __PRIVATE_DocumentWatchChange ? e.Va.Ze(t) : t instanceof __PRIVATE_ExistenceFilterChange ? e.Va.st(t) : e.Va.tt(t), + !n.isEqual(SnapshotVersion.min())) try { + const t = await __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e.localStore); + n.compareTo(t) >= 0 && + // We have received a target change with a global snapshot if the snapshot + // version is not equal to SnapshotVersion.min(). + /** + * Takes a batch of changes from the Datastore, repackages them as a + * RemoteEvent, and passes that on to the listener, which is typically the + * SyncEngine. + */ + await function __PRIVATE_raiseWatchSnapshot(e, t) { + const n = e.Va.Tt(t); + // Update in-memory resume tokens. LocalStore will update the + // persistent view of these when applying the completed RemoteEvent. + return n.targetChanges.forEach(((n, r) => { + if (n.resumeToken.approximateByteSize() > 0) { + const i = e.Ia.get(r); + // A watched target might have been removed already. + i && e.Ia.set(r, i.withResumeToken(n.resumeToken, t)); + } + })), + // Re-establish listens for the targets that have been invalidated by + // existence filter mismatches. + n.targetMismatches.forEach(((t, n) => { + const r = e.Ia.get(t); + if (!r) + // A watched target might have been removed already. + return; + // Clear the resume token for the target, since we're in a known mismatch + // state. + e.Ia.set(t, r.withResumeToken(ByteString.EMPTY_BYTE_STRING, r.snapshotVersion)), + // Cause a hard reset by unwatching and rewatching immediately, but + // deliberately don't send a resume token so that we get a full update. + __PRIVATE_sendUnwatchRequest(e, t); + // Mark the target we send as being on behalf of an existence filter + // mismatch, but don't actually retain that in listenTargets. This ensures + // that we flag the first re-listen this way without impacting future + // listens of this target (that might happen e.g. on reconnect). + const i = new TargetData(r.target, t, n, r.sequenceNumber); + __PRIVATE_sendWatchRequest(e, i); + })), e.remoteSyncer.applyRemoteEvent(n); + }(e, n); + } catch (t) { + __PRIVATE_logDebug(sn, "Failed to raise snapshot:", t), await __PRIVATE_disableNetworkUntilRecovery(e, t); + } +} + +/** + * Recovery logic for IndexedDB errors that takes the network offline until + * `op` succeeds. Retries are scheduled with backoff using + * `enqueueRetryable()`. If `op()` is not provided, IndexedDB access is + * validated via a generic operation. + * + * The returned Promise is resolved once the network is disabled and before + * any retry attempt. + */ async function __PRIVATE_disableNetworkUntilRecovery(e, t, n) { + if (!__PRIVATE_isIndexedDbTransactionError(t)) throw t; + e.Ea.add(1 /* OfflineCause.IndexedDbFailed */), + // Disable network and raise offline snapshots + await __PRIVATE_disableNetworkInternal(e), e.Ra.set("Offline" /* OnlineState.Offline */), + n || ( + // Use a simple read operation to determine if IndexedDB recovered. + // Ideally, we would expose a health check directly on SimpleDb, but + // RemoteStore only has access to persistence through LocalStore. + n = () => __PRIVATE_localStoreGetLastRemoteSnapshotVersion(e.localStore)), + // Probe IndexedDB periodically and re-enable network + e.asyncQueue.enqueueRetryable((async () => { + __PRIVATE_logDebug(sn, "Retrying IndexedDB access"), await n(), e.Ea.delete(1 /* OfflineCause.IndexedDbFailed */), + await __PRIVATE_enableNetworkInternal(e); + })); +} + +/** + * Executes `op`. If `op` fails, takes the network offline until `op` + * succeeds. Returns after the first attempt. + */ function __PRIVATE_executeWithRecovery(e, t) { + return t().catch((n => __PRIVATE_disableNetworkUntilRecovery(e, n, t))); +} + +async function __PRIVATE_fillWritePipeline(e) { + const t = __PRIVATE_debugCast(e), n = __PRIVATE_ensureWriteStream(t); + let r = t.Ta.length > 0 ? t.Ta[t.Ta.length - 1].batchId : H; + for (;__PRIVATE_canAddToWritePipeline(t); ) try { + const e = await __PRIVATE_localStoreGetNextMutationBatch(t.localStore, r); + if (null === e) { + 0 === t.Ta.length && n.L_(); + break; + } + r = e.batchId, __PRIVATE_addToWritePipeline(t, e); + } catch (e) { + await __PRIVATE_disableNetworkUntilRecovery(t, e); + } + __PRIVATE_shouldStartWriteStream(t) && __PRIVATE_startWriteStream(t); +} + +/** + * Returns true if we can add to the write pipeline (i.e. the network is + * enabled and the write pipeline is not full). + */ function __PRIVATE_canAddToWritePipeline(e) { + return __PRIVATE_canUseNetwork(e) && e.Ta.length < 10; +} + +/** + * Queues additional writes to be sent to the write stream, sending them + * immediately if the write stream is established. + */ function __PRIVATE_addToWritePipeline(e, t) { + e.Ta.push(t); + const n = __PRIVATE_ensureWriteStream(e); + n.O_() && n.X_ && n.ea(t.mutations); +} + +function __PRIVATE_shouldStartWriteStream(e) { + return __PRIVATE_canUseNetwork(e) && !__PRIVATE_ensureWriteStream(e).x_() && e.Ta.length > 0; +} + +function __PRIVATE_startWriteStream(e) { + __PRIVATE_ensureWriteStream(e).start(); +} + +async function __PRIVATE_onWriteStreamOpen(e) { + __PRIVATE_ensureWriteStream(e).ra(); +} + +async function __PRIVATE_onWriteHandshakeComplete(e) { + const t = __PRIVATE_ensureWriteStream(e); + // Send the write pipeline now that the stream is established. + for (const n of e.Ta) t.ea(n.mutations); +} + +async function __PRIVATE_onMutationResult(e, t, n) { + const r = e.Ta.shift(), i = MutationBatchResult.from(r, t, n); + await __PRIVATE_executeWithRecovery(e, (() => e.remoteSyncer.applySuccessfulWrite(i))), + // It's possible that with the completion of this mutation another + // slot has freed up. + await __PRIVATE_fillWritePipeline(e); +} + +async function __PRIVATE_onWriteStreamClose(e, t) { + // If the write stream closed after the write handshake completes, a write + // operation failed and we fail the pending operation. + t && __PRIVATE_ensureWriteStream(e).X_ && + // This error affects the actual write. + await async function __PRIVATE_handleWriteError(e, t) { + // Only handle permanent errors here. If it's transient, just let the retry + // logic kick in. + if (function __PRIVATE_isPermanentWriteError(e) { + return __PRIVATE_isPermanentError(e) && e !== L.ABORTED; + }(t.code)) { + // This was a permanent error, the request itself was the problem + // so it's not going to succeed if we resend it. + const n = e.Ta.shift(); + // In this case it's also unlikely that the server itself is melting + // down -- this was just a bad request so inhibit backoff on the next + // restart. + __PRIVATE_ensureWriteStream(e).B_(), await __PRIVATE_executeWithRecovery(e, (() => e.remoteSyncer.rejectFailedWrite(n.batchId, t))), + // It's possible that with the completion of this mutation + // another slot has freed up. + await __PRIVATE_fillWritePipeline(e); + } + }(e, t), + // The write stream might have been started by refilling the write + // pipeline for failed writes + __PRIVATE_shouldStartWriteStream(e) && __PRIVATE_startWriteStream(e); +} + +async function __PRIVATE_remoteStoreHandleCredentialChange(e, t) { + const n = __PRIVATE_debugCast(e); + n.asyncQueue.verifyOperationInProgress(), __PRIVATE_logDebug(sn, "RemoteStore received new credentials"); + const r = __PRIVATE_canUseNetwork(n); + // Tear down and re-create our network streams. This will ensure we get a + // fresh auth token for the new user and re-fill the write pipeline with + // new mutations from the LocalStore (since mutations are per-user). + n.Ea.add(3 /* OfflineCause.CredentialChange */), await __PRIVATE_disableNetworkInternal(n), + r && + // Don't set the network status to Unknown if we are offline. + n.Ra.set("Unknown" /* OnlineState.Unknown */), await n.remoteSyncer.handleCredentialChange(t), + n.Ea.delete(3 /* OfflineCause.CredentialChange */), await __PRIVATE_enableNetworkInternal(n); +} + +/** + * Toggles the network state when the client gains or loses its primary lease. + */ async function __PRIVATE_remoteStoreApplyPrimaryState(e, t) { + const n = __PRIVATE_debugCast(e); + t ? (n.Ea.delete(2 /* OfflineCause.IsSecondary */), await __PRIVATE_enableNetworkInternal(n)) : t || (n.Ea.add(2 /* OfflineCause.IsSecondary */), + await __PRIVATE_disableNetworkInternal(n), n.Ra.set("Unknown" /* OnlineState.Unknown */)); +} + +/** + * If not yet initialized, registers the WatchStream and its network state + * callback with `remoteStoreImpl`. Returns the existing stream if one is + * already available. + * + * PORTING NOTE: On iOS and Android, the WatchStream gets registered on startup. + * This is not done on Web to allow it to be tree-shaken. + */ function __PRIVATE_ensureWatchStream(e) { + return e.ma || ( + // Create stream (but note that it is not started yet). + e.ma = function __PRIVATE_newPersistentWatchStream(e, t, n) { + const r = __PRIVATE_debugCast(e); + return r.sa(), new __PRIVATE_PersistentListenStream(t, r.connection, r.authCredentials, r.appCheckCredentials, r.serializer, n); + } + /** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ (e.datastore, e.asyncQueue, { + Xo: __PRIVATE_onWatchStreamConnected.bind(null, e), + t_: __PRIVATE_onWatchStreamOpen.bind(null, e), + r_: __PRIVATE_onWatchStreamClose.bind(null, e), + H_: __PRIVATE_onWatchStreamChange.bind(null, e) + }), e.da.push((async t => { + t ? (e.ma.B_(), __PRIVATE_shouldStartWatchStream(e) ? __PRIVATE_startWatchStream(e) : e.Ra.set("Unknown" /* OnlineState.Unknown */)) : (await e.ma.stop(), + __PRIVATE_cleanUpWatchStreamState(e)); + }))), e.ma; +} + +/** + * If not yet initialized, registers the WriteStream and its network state + * callback with `remoteStoreImpl`. Returns the existing stream if one is + * already available. + * + * PORTING NOTE: On iOS and Android, the WriteStream gets registered on startup. + * This is not done on Web to allow it to be tree-shaken. + */ function __PRIVATE_ensureWriteStream(e) { + return e.fa || ( + // Create stream (but note that it is not started yet). + e.fa = function __PRIVATE_newPersistentWriteStream(e, t, n) { + const r = __PRIVATE_debugCast(e); + return r.sa(), new __PRIVATE_PersistentWriteStream(t, r.connection, r.authCredentials, r.appCheckCredentials, r.serializer, n); + }(e.datastore, e.asyncQueue, { + Xo: () => Promise.resolve(), + t_: __PRIVATE_onWriteStreamOpen.bind(null, e), + r_: __PRIVATE_onWriteStreamClose.bind(null, e), + ta: __PRIVATE_onWriteHandshakeComplete.bind(null, e), + na: __PRIVATE_onMutationResult.bind(null, e) + }), e.da.push((async t => { + t ? (e.fa.B_(), + // This will start the write stream if necessary. + await __PRIVATE_fillWritePipeline(e)) : (await e.fa.stop(), e.Ta.length > 0 && (__PRIVATE_logDebug(sn, `Stopping write stream with ${e.Ta.length} pending writes`), + e.Ta = [])); + }))), e.fa; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents an operation scheduled to be run in the future on an AsyncQueue. + * + * It is created via DelayedOperation.createAndSchedule(). + * + * Supports cancellation (via cancel()) and early execution (via skipDelay()). + * + * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type + * in newer versions of TypeScript defines `finally`, which is not available in + * IE. + */ +class DelayedOperation { + constructor(e, t, n, r, i) { + this.asyncQueue = e, this.timerId = t, this.targetTimeMs = n, this.op = r, this.removalCallback = i, + this.deferred = new __PRIVATE_Deferred, this.then = this.deferred.promise.then.bind(this.deferred.promise), + // It's normal for the deferred promise to be canceled (due to cancellation) + // and so we attach a dummy catch callback to avoid + // 'UnhandledPromiseRejectionWarning' log spam. + this.deferred.promise.catch((e => {})); + } + get promise() { + return this.deferred.promise; + } + /** + * Creates and returns a DelayedOperation that has been scheduled to be + * executed on the provided asyncQueue after the provided delayMs. + * + * @param asyncQueue - The queue to schedule the operation on. + * @param id - A Timer ID identifying the type of operation this is. + * @param delayMs - The delay (ms) before the operation should be scheduled. + * @param op - The operation to run. + * @param removalCallback - A callback to be called synchronously once the + * operation is executed or canceled, notifying the AsyncQueue to remove it + * from its delayedOperations list. + * PORTING NOTE: This exists to prevent making removeDelayedOperation() and + * the DelayedOperation class public. + */ static createAndSchedule(e, t, n, r, i) { + const s = Date.now() + n, o = new DelayedOperation(e, t, s, r, i); + return o.start(n), o; + } + /** + * Starts the timer. This is called immediately after construction by + * createAndSchedule(). + */ start(e) { + this.timerHandle = setTimeout((() => this.handleDelayElapsed()), e); + } + /** + * Queues the operation to run immediately (if it hasn't already been run or + * canceled). + */ skipDelay() { + return this.handleDelayElapsed(); + } + /** + * Cancels the operation if it hasn't already been executed or canceled. The + * promise will be rejected. + * + * As long as the operation has not yet been run, calling cancel() provides a + * guarantee that the operation will not be run. + */ cancel(e) { + null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new FirestoreError(L.CANCELLED, "Operation cancelled" + (e ? ": " + e : "")))); + } + handleDelayElapsed() { + this.asyncQueue.enqueueAndForget((() => null !== this.timerHandle ? (this.clearTimeout(), + this.op().then((e => this.deferred.resolve(e)))) : Promise.resolve())); + } + clearTimeout() { + null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle), + this.timerHandle = null); + } +} + +/** + * Returns a FirestoreError that can be surfaced to the user if the provided + * error is an IndexedDbTransactionError. Re-throws the error otherwise. + */ function __PRIVATE_wrapInUserErrorIfRecoverable(e, t) { + if (__PRIVATE_logError("AsyncQueue", `${t}: ${e}`), __PRIVATE_isIndexedDbTransactionError(e)) return new FirestoreError(L.UNAVAILABLE, `${t}: ${e}`); + throw e; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * DocumentSet is an immutable (copy-on-write) collection that holds documents + * in order specified by the provided comparator. We always add a document key + * comparator on top of what is provided to guarantee document equality based on + * the key. + */ class DocumentSet { + /** + * Returns an empty copy of the existing DocumentSet, using the same + * comparator. + */ + static emptySet(e) { + return new DocumentSet(e.comparator); + } + /** The default ordering is by key if the comparator is omitted */ constructor(e) { + // We are adding document key comparator to the end as it's the only + // guaranteed unique property of a document. + this.comparator = e ? (t, n) => e(t, n) || DocumentKey.comparator(t.key, n.key) : (e, t) => DocumentKey.comparator(e.key, t.key), + this.keyedMap = documentMap(), this.sortedSet = new SortedMap(this.comparator); + } + has(e) { + return null != this.keyedMap.get(e); + } + get(e) { + return this.keyedMap.get(e); + } + first() { + return this.sortedSet.minKey(); + } + last() { + return this.sortedSet.maxKey(); + } + isEmpty() { + return this.sortedSet.isEmpty(); + } + /** + * Returns the index of the provided key in the document set, or -1 if the + * document key is not present in the set; + */ indexOf(e) { + const t = this.keyedMap.get(e); + return t ? this.sortedSet.indexOf(t) : -1; + } + get size() { + return this.sortedSet.size; + } + /** Iterates documents in order defined by "comparator" */ forEach(e) { + this.sortedSet.inorderTraversal(((t, n) => (e(t), !1))); + } + /** Inserts or updates a document with the same key */ add(e) { + // First remove the element if we have it. + const t = this.delete(e.key); + return t.copy(t.keyedMap.insert(e.key, e), t.sortedSet.insert(e, null)); + } + /** Deletes a document with a given key */ delete(e) { + const t = this.get(e); + return t ? this.copy(this.keyedMap.remove(e), this.sortedSet.remove(t)) : this; + } + isEqual(e) { + if (!(e instanceof DocumentSet)) return !1; + if (this.size !== e.size) return !1; + const t = this.sortedSet.getIterator(), n = e.sortedSet.getIterator(); + for (;t.hasNext(); ) { + const e = t.getNext().key, r = n.getNext().key; + if (!e.isEqual(r)) return !1; + } + return !0; + } + toString() { + const e = []; + return this.forEach((t => { + e.push(t.toString()); + })), 0 === e.length ? "DocumentSet ()" : "DocumentSet (\n " + e.join(" \n") + "\n)"; + } + copy(e, t) { + const n = new DocumentSet; + return n.comparator = this.comparator, n.keyedMap = e, n.sortedSet = t, n; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * DocumentChangeSet keeps track of a set of changes to docs in a query, merging + * duplicate events for the same doc. + */ class __PRIVATE_DocumentChangeSet { + constructor() { + this.ga = new SortedMap(DocumentKey.comparator); + } + track(e) { + const t = e.doc.key, n = this.ga.get(t); + n ? + // Merge the new change with the existing change. + 0 /* ChangeType.Added */ !== e.type && 3 /* ChangeType.Metadata */ === n.type ? this.ga = this.ga.insert(t, e) : 3 /* ChangeType.Metadata */ === e.type && 1 /* ChangeType.Removed */ !== n.type ? this.ga = this.ga.insert(t, { + type: n.type, + doc: e.doc + }) : 2 /* ChangeType.Modified */ === e.type && 2 /* ChangeType.Modified */ === n.type ? this.ga = this.ga.insert(t, { + type: 2 /* ChangeType.Modified */ , + doc: e.doc + }) : 2 /* ChangeType.Modified */ === e.type && 0 /* ChangeType.Added */ === n.type ? this.ga = this.ga.insert(t, { + type: 0 /* ChangeType.Added */ , + doc: e.doc + }) : 1 /* ChangeType.Removed */ === e.type && 0 /* ChangeType.Added */ === n.type ? this.ga = this.ga.remove(t) : 1 /* ChangeType.Removed */ === e.type && 2 /* ChangeType.Modified */ === n.type ? this.ga = this.ga.insert(t, { + type: 1 /* ChangeType.Removed */ , + doc: n.doc + }) : 0 /* ChangeType.Added */ === e.type && 1 /* ChangeType.Removed */ === n.type ? this.ga = this.ga.insert(t, { + type: 2 /* ChangeType.Modified */ , + doc: e.doc + }) : + // This includes these cases, which don't make sense: + // Added->Added + // Removed->Removed + // Modified->Added + // Removed->Modified + // Metadata->Added + // Removed->Metadata + fail(63341, { + Rt: e, + pa: n + }) : this.ga = this.ga.insert(t, e); + } + ya() { + const e = []; + return this.ga.inorderTraversal(((t, n) => { + e.push(n); + })), e; + } +} + +class ViewSnapshot { + constructor(e, t, n, r, i, s, o, _, a) { + this.query = e, this.docs = t, this.oldDocs = n, this.docChanges = r, this.mutatedKeys = i, + this.fromCache = s, this.syncStateChanged = o, this.excludesMetadataChanges = _, + this.hasCachedResults = a; + } + /** Returns a view snapshot as if all documents in the snapshot were added. */ static fromInitialDocuments(e, t, n, r, i) { + const s = []; + return t.forEach((e => { + s.push({ + type: 0 /* ChangeType.Added */ , + doc: e + }); + })), new ViewSnapshot(e, t, DocumentSet.emptySet(t), s, n, r, + /* syncStateChanged= */ !0, + /* excludesMetadataChanges= */ !1, i); + } + get hasPendingWrites() { + return !this.mutatedKeys.isEmpty(); + } + isEqual(e) { + if (!(this.fromCache === e.fromCache && this.hasCachedResults === e.hasCachedResults && this.syncStateChanged === e.syncStateChanged && this.mutatedKeys.isEqual(e.mutatedKeys) && __PRIVATE_queryEquals(this.query, e.query) && this.docs.isEqual(e.docs) && this.oldDocs.isEqual(e.oldDocs))) return !1; + const t = this.docChanges, n = e.docChanges; + if (t.length !== n.length) return !1; + for (let e = 0; e < t.length; e++) if (t[e].type !== n[e].type || !t[e].doc.isEqual(n[e].doc)) return !1; + return !0; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Holds the listeners and the last received ViewSnapshot for a query being + * tracked by EventManager. + */ class __PRIVATE_QueryListenersInfo { + constructor() { + this.wa = void 0, this.Sa = []; + } + // Helper methods that checks if the query has listeners that listening to remote store + ba() { + return this.Sa.some((e => e.Da())); + } +} + +class __PRIVATE_EventManagerImpl { + constructor() { + this.queries = __PRIVATE_newQueriesObjectMap(), this.onlineState = "Unknown" /* OnlineState.Unknown */ , + this.Ca = new Set; + } + terminate() { + !function __PRIVATE_errorAllTargets(e, t) { + const n = __PRIVATE_debugCast(e), r = n.queries; + // Prevent further access by clearing ObjectMap. + n.queries = __PRIVATE_newQueriesObjectMap(), r.forEach(((e, n) => { + for (const e of n.Sa) e.onError(t); + })); + } + // Call all global snapshot listeners that have been set. + (this, new FirestoreError(L.ABORTED, "Firestore shutting down")); + } +} + +function __PRIVATE_newQueriesObjectMap() { + return new ObjectMap((e => __PRIVATE_canonifyQuery(e)), __PRIVATE_queryEquals); +} + +async function __PRIVATE_eventManagerListen(e, t) { + const n = __PRIVATE_debugCast(e); + let r = 3 /* ListenerSetupAction.NoActionRequired */; + const i = t.query; + let s = n.queries.get(i); + s ? !s.ba() && t.Da() && ( + // Query has been listening to local cache, and tries to add a new listener sourced from watch. + r = 2 /* ListenerSetupAction.RequireWatchConnectionOnly */) : (s = new __PRIVATE_QueryListenersInfo, + r = t.Da() ? 0 /* ListenerSetupAction.InitializeLocalListenAndRequireWatchConnection */ : 1 /* ListenerSetupAction.InitializeLocalListenOnly */); + try { + switch (r) { + case 0 /* ListenerSetupAction.InitializeLocalListenAndRequireWatchConnection */ : + s.wa = await n.onListen(i, + /** enableRemoteListen= */ !0); + break; + + case 1 /* ListenerSetupAction.InitializeLocalListenOnly */ : + s.wa = await n.onListen(i, + /** enableRemoteListen= */ !1); + break; + + case 2 /* ListenerSetupAction.RequireWatchConnectionOnly */ : + await n.onFirstRemoteStoreListen(i); + } + } catch (e) { + const n = __PRIVATE_wrapInUserErrorIfRecoverable(e, `Initialization of query '${__PRIVATE_stringifyQuery(t.query)}' failed`); + return void t.onError(n); + } + if (n.queries.set(i, s), s.Sa.push(t), + // Run global snapshot listeners if a consistent snapshot has been emitted. + t.va(n.onlineState), s.wa) { + t.Fa(s.wa) && __PRIVATE_raiseSnapshotsInSyncEvent(n); + } +} + +async function __PRIVATE_eventManagerUnlisten(e, t) { + const n = __PRIVATE_debugCast(e), r = t.query; + let i = 3 /* ListenerRemovalAction.NoActionRequired */; + const s = n.queries.get(r); + if (s) { + const e = s.Sa.indexOf(t); + e >= 0 && (s.Sa.splice(e, 1), 0 === s.Sa.length ? i = t.Da() ? 0 /* ListenerRemovalAction.TerminateLocalListenAndRequireWatchDisconnection */ : 1 /* ListenerRemovalAction.TerminateLocalListenOnly */ : !s.ba() && t.Da() && ( + // The removed listener is the last one that sourced from watch. + i = 2 /* ListenerRemovalAction.RequireWatchDisconnectionOnly */)); + } + switch (i) { + case 0 /* ListenerRemovalAction.TerminateLocalListenAndRequireWatchDisconnection */ : + return n.queries.delete(r), n.onUnlisten(r, + /** disableRemoteListen= */ !0); + + case 1 /* ListenerRemovalAction.TerminateLocalListenOnly */ : + return n.queries.delete(r), n.onUnlisten(r, + /** disableRemoteListen= */ !1); + + case 2 /* ListenerRemovalAction.RequireWatchDisconnectionOnly */ : + return n.onLastRemoteStoreUnlisten(r); + + default: + return; + } +} + +function __PRIVATE_eventManagerOnWatchChange(e, t) { + const n = __PRIVATE_debugCast(e); + let r = !1; + for (const e of t) { + const t = e.query, i = n.queries.get(t); + if (i) { + for (const t of i.Sa) t.Fa(e) && (r = !0); + i.wa = e; + } + } + r && __PRIVATE_raiseSnapshotsInSyncEvent(n); +} + +function __PRIVATE_eventManagerOnWatchError(e, t, n) { + const r = __PRIVATE_debugCast(e), i = r.queries.get(t); + if (i) for (const e of i.Sa) e.onError(n); + // Remove all listeners. NOTE: We don't need to call syncEngine.unlisten() + // after an error. + r.queries.delete(t); +} + +function __PRIVATE_raiseSnapshotsInSyncEvent(e) { + e.Ca.forEach((e => { + e.next(); + })); +} + +var on, _n; + +/** Listen to both cache and server changes */ +(_n = on || (on = {})).Ma = "default", +/** Listen to changes in cache only */ +_n.Cache = "cache"; + +/** + * QueryListener takes a series of internal view snapshots and determines + * when to raise the event. + * + * It uses an Observer to dispatch events. + */ +class __PRIVATE_QueryListener { + constructor(e, t, n) { + this.query = e, this.xa = t, + /** + * Initial snapshots (e.g. from cache) may not be propagated to the wrapped + * observer. This flag is set to true once we've actually raised an event. + */ + this.Oa = !1, this.Na = null, this.onlineState = "Unknown" /* OnlineState.Unknown */ , + this.options = n || {}; + } + /** + * Applies the new ViewSnapshot to this listener, raising a user-facing event + * if applicable (depending on what changed, whether the user has opted into + * metadata-only changes, etc.). Returns true if a user-facing event was + * indeed raised. + */ Fa(e) { + if (!this.options.includeMetadataChanges) { + // Remove the metadata only changes. + const t = []; + for (const n of e.docChanges) 3 /* ChangeType.Metadata */ !== n.type && t.push(n); + e = new ViewSnapshot(e.query, e.docs, e.oldDocs, t, e.mutatedKeys, e.fromCache, e.syncStateChanged, + /* excludesMetadataChanges= */ !0, e.hasCachedResults); + } + let t = !1; + return this.Oa ? this.Ba(e) && (this.xa.next(e), t = !0) : this.La(e, this.onlineState) && (this.ka(e), + t = !0), this.Na = e, t; + } + onError(e) { + this.xa.error(e); + } + /** Returns whether a snapshot was raised. */ va(e) { + this.onlineState = e; + let t = !1; + return this.Na && !this.Oa && this.La(this.Na, e) && (this.ka(this.Na), t = !0), + t; + } + La(e, t) { + // Always raise the first event when we're synced + if (!e.fromCache) return !0; + // Always raise event if listening to cache + if (!this.Da()) return !0; + // NOTE: We consider OnlineState.Unknown as online (it should become Offline + // or Online if we wait long enough). + const n = "Offline" /* OnlineState.Offline */ !== t; + // Don't raise the event if we're online, aren't synced yet (checked + // above) and are waiting for a sync. + return (!this.options.qa || !n) && (!e.docs.isEmpty() || e.hasCachedResults || "Offline" /* OnlineState.Offline */ === t); + // Raise data from cache if we have any documents, have cached results before, + // or we are offline. + } + Ba(e) { + // We don't need to handle includeDocumentMetadataChanges here because + // the Metadata only changes have already been stripped out if needed. + // At this point the only changes we will see are the ones we should + // propagate. + if (e.docChanges.length > 0) return !0; + const t = this.Na && this.Na.hasPendingWrites !== e.hasPendingWrites; + return !(!e.syncStateChanged && !t) && !0 === this.options.includeMetadataChanges; + // Generally we should have hit one of the cases above, but it's possible + // to get here if there were only metadata docChanges and they got + // stripped out. + } + ka(e) { + e = ViewSnapshot.fromInitialDocuments(e.query, e.docs, e.mutatedKeys, e.fromCache, e.hasCachedResults), + this.Oa = !0, this.xa.next(e); + } + Da() { + return this.options.source !== on.Cache; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A complete element in the bundle stream, together with the byte length it + * occupies in the stream. + */ class __PRIVATE_SizedBundleElement { + constructor(e, + // How many bytes this element takes to store in the bundle. + t) { + this.Qa = e, this.byteLength = t; + } + $a() { + return "metadata" in this.Qa; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Helper to convert objects from bundles to model objects in the SDK. + */ class __PRIVATE_BundleConverterImpl { + constructor(e) { + this.serializer = e; + } + $s(e) { + return fromName(this.serializer, e); + } + /** + * Converts a BundleDocument to a MutableDocument. + */ Us(e) { + return e.metadata.exists ? __PRIVATE_fromDocument(this.serializer, e.document, !1) : MutableDocument.newNoDocument(this.$s(e.metadata.name), this.Ks(e.metadata.readTime)); + } + Ks(e) { + return __PRIVATE_fromVersion(e); + } +} + +/** + * A class to process the elements from a bundle, and optionally load them into local + * storage and provide progress update while loading. + */ class __PRIVATE_BundleLoader { + constructor(e, t) { + this.Ua = e, this.serializer = t, + /** Batched queries to be saved into storage */ + this.Ka = [], + /** Batched documents to be saved into storage */ + this.Wa = [], + /** The collection groups affected by this bundle. */ + this.collectionGroups = new Set, this.progress = __PRIVATE_bundleInitialProgress(e); + } + /** + * Returns the named queries that have been parsed from the SizeBundleElements added by + * calling {@link adSizedElement}. + */ get queries() { + return this.Ka; + } + /** + * Returns the BundledDocuments that have been parsed from the SizeBundleElements added by + * calling {@link addSizedElement}. + */ get documents() { + return this.Wa; + } + /** + * Adds an element from the bundle to the loader. + * + * Returns a new progress if adding the element leads to a new progress, + * otherwise returns null. + */ Ga(e) { + this.progress.bytesLoaded += e.byteLength; + let t = this.progress.documentsLoaded; + if (e.Qa.namedQuery) this.Ka.push(e.Qa.namedQuery); else if (e.Qa.documentMetadata) { + this.Wa.push({ + metadata: e.Qa.documentMetadata + }), e.Qa.documentMetadata.exists || ++t; + const n = ResourcePath.fromString(e.Qa.documentMetadata.name); + this.collectionGroups.add(n.get(n.length - 2)); + } else e.Qa.document && (this.Wa[this.Wa.length - 1].document = e.Qa.document, ++t); + return t !== this.progress.documentsLoaded ? (this.progress.documentsLoaded = t, + { + ...this.progress + }) : null; + } + za(e) { + const t = new Map, n = new __PRIVATE_BundleConverterImpl(this.serializer); + for (const r of e) if (r.metadata.queries) { + const e = n.$s(r.metadata.name); + for (const n of r.metadata.queries) { + const r = (t.get(n) || __PRIVATE_documentKeySet()).add(e); + t.set(n, r); + } + } + return t; + } + /** + * Update the progress to 'Success' and return the updated progress. + */ async ja(e) { + const t = await __PRIVATE_localStoreApplyBundledDocuments(e, new __PRIVATE_BundleConverterImpl(this.serializer), this.Wa, this.Ua.id), n = this.za(this.documents); + for (const t of this.Ka) await __PRIVATE_localStoreSaveNamedQuery(e, t, n.get(t.name)); + return this.progress.taskState = "Success", { + progress: this.progress, + Ja: this.collectionGroups, + Ha: t + }; + } +} + +/** + * Returns a `LoadBundleTaskProgress` representing the initial progress of + * loading a bundle. + */ function __PRIVATE_bundleInitialProgress(e) { + return { + taskState: "Running", + documentsLoaded: 0, + bytesLoaded: 0, + totalDocuments: e.totalDocuments, + totalBytes: e.totalBytes + }; +} + +/** + * Returns a `LoadBundleTaskProgress` representing the progress that the loading + * has succeeded. + */ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class __PRIVATE_AddedLimboDocument { + constructor(e) { + this.key = e; + } +} + +class __PRIVATE_RemovedLimboDocument { + constructor(e) { + this.key = e; + } +} + +/** + * View is responsible for computing the final merged truth of what docs are in + * a query. It gets notified of local and remote changes to docs, and applies + * the query filters and limits to determine the most correct possible results. + */ class __PRIVATE_View { + constructor(e, + /** Documents included in the remote target */ + t) { + this.query = e, this.Ya = t, this.Za = null, this.hasCachedResults = !1, + /** + * A flag whether the view is current with the backend. A view is considered + * current after it has seen the current flag from the backend and did not + * lose consistency within the watch stream (e.g. because of an existence + * filter mismatch). + */ + this.current = !1, + /** Documents in the view but not in the remote target */ + this.Xa = __PRIVATE_documentKeySet(), + /** Document Keys that have local changes */ + this.mutatedKeys = __PRIVATE_documentKeySet(), this.eu = __PRIVATE_newQueryComparator(e), + this.tu = new DocumentSet(this.eu); + } + /** + * The set of remote documents that the server has told us belongs to the target associated with + * this view. + */ get nu() { + return this.Ya; + } + /** + * Iterates over a set of doc changes, applies the query limit, and computes + * what the new results should be, what the changes were, and whether we may + * need to go back to the local cache for more results. Does not make any + * changes to the view. + * @param docChanges - The doc changes to apply to this view. + * @param previousChanges - If this is being called with a refill, then start + * with this set of docs and changes instead of the current view. + * @returns a new set of docs, changes, and refill flag. + */ ru(e, t) { + const n = t ? t.iu : new __PRIVATE_DocumentChangeSet, r = t ? t.tu : this.tu; + let i = t ? t.mutatedKeys : this.mutatedKeys, s = r, o = !1; + // Track the last doc in a (full) limit. This is necessary, because some + // update (a delete, or an update moving a doc past the old limit) might + // mean there is some other document in the local cache that either should + // come (1) between the old last limit doc and the new last document, in the + // case of updates, or (2) after the new last document, in the case of + // deletes. So we keep this doc at the old limit to compare the updates to. + // Note that this should never get used in a refill (when previousChanges is + // set), because there will only be adds -- no deletes or updates. + const _ = "F" /* LimitType.First */ === this.query.limitType && r.size === this.query.limit ? r.last() : null, a = "L" /* LimitType.Last */ === this.query.limitType && r.size === this.query.limit ? r.first() : null; + // Drop documents out to meet limit/limitToLast requirement. + if (e.inorderTraversal(((e, t) => { + const u = r.get(e), c = __PRIVATE_queryMatches(this.query, t) ? t : null, l = !!u && this.mutatedKeys.has(u.key), h = !!c && (c.hasLocalMutations || + // We only consider committed mutations for documents that were + // mutated during the lifetime of the view. + this.mutatedKeys.has(c.key) && c.hasCommittedMutations); + let P = !1; + // Calculate change + if (u && c) { + u.data.isEqual(c.data) ? l !== h && (n.track({ + type: 3 /* ChangeType.Metadata */ , + doc: c + }), P = !0) : this.su(u, c) || (n.track({ + type: 2 /* ChangeType.Modified */ , + doc: c + }), P = !0, (_ && this.eu(c, _) > 0 || a && this.eu(c, a) < 0) && ( + // This doc moved from inside the limit to outside the limit. + // That means there may be some other doc in the local cache + // that should be included instead. + o = !0)); + } else !u && c ? (n.track({ + type: 0 /* ChangeType.Added */ , + doc: c + }), P = !0) : u && !c && (n.track({ + type: 1 /* ChangeType.Removed */ , + doc: u + }), P = !0, (_ || a) && ( + // A doc was removed from a full limit query. We'll need to + // requery from the local cache to see if we know about some other + // doc that should be in the results. + o = !0)); + P && (c ? (s = s.add(c), i = h ? i.add(e) : i.delete(e)) : (s = s.delete(e), i = i.delete(e))); + })), null !== this.query.limit) for (;s.size > this.query.limit; ) { + const e = "F" /* LimitType.First */ === this.query.limitType ? s.last() : s.first(); + s = s.delete(e.key), i = i.delete(e.key), n.track({ + type: 1 /* ChangeType.Removed */ , + doc: e + }); + } + return { + tu: s, + iu: n, + Cs: o, + mutatedKeys: i + }; + } + su(e, t) { + // We suppress the initial change event for documents that were modified as + // part of a write acknowledgment (e.g. when the value of a server transform + // is applied) as Watch will send us the same document again. + // By suppressing the event, we only raise two user visible events (one with + // `hasPendingWrites` and the final state of the document) instead of three + // (one with `hasPendingWrites`, the modified document with + // `hasPendingWrites` and the final state of the document). + return e.hasLocalMutations && t.hasCommittedMutations && !t.hasLocalMutations; + } + /** + * Updates the view with the given ViewDocumentChanges and optionally updates + * limbo docs and sync state from the provided target change. + * @param docChanges - The set of changes to make to the view's docs. + * @param limboResolutionEnabled - Whether to update limbo documents based on + * this change. + * @param targetChange - A target change to apply for computing limbo docs and + * sync state. + * @param targetIsPendingReset - Whether the target is pending to reset due to + * existence filter mismatch. If not explicitly specified, it is treated + * equivalently to `false`. + * @returns A new ViewChange with the given docs, changes, and sync state. + */ + // PORTING NOTE: The iOS/Android clients always compute limbo document changes. + applyChanges(e, t, n, r) { + const i = this.tu; + this.tu = e.tu, this.mutatedKeys = e.mutatedKeys; + // Sort changes based on type and query comparator + const s = e.iu.ya(); + s.sort(((e, t) => function __PRIVATE_compareChangeType(e, t) { + const order = e => { + switch (e) { + case 0 /* ChangeType.Added */ : + return 1; + + case 2 /* ChangeType.Modified */ : + case 3 /* ChangeType.Metadata */ : + // A metadata change is converted to a modified change at the public + // api layer. Since we sort by document key and then change type, + // metadata and modified changes must be sorted equivalently. + return 2; + + case 1 /* ChangeType.Removed */ : + return 0; + + default: + return fail(20277, { + Rt: e + }); + } + }; + return order(e) - order(t); + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ (e.type, t.type) || this.eu(e.doc, t.doc))), this.ou(n), r = r ?? !1; + const o = t && !r ? this._u() : [], _ = 0 === this.Xa.size && this.current && !r ? 1 /* SyncState.Synced */ : 0 /* SyncState.Local */ , a = _ !== this.Za; + // We are at synced state if there is no limbo docs are waiting to be resolved, view is current + // with the backend, and the query is not pending to reset due to existence filter mismatch. + if (this.Za = _, 0 !== s.length || a) { + return { + snapshot: new ViewSnapshot(this.query, e.tu, i, s, e.mutatedKeys, 0 /* SyncState.Local */ === _, a, + /* excludesMetadataChanges= */ !1, !!n && n.resumeToken.approximateByteSize() > 0), + au: o + }; + } + // no changes + return { + au: o + }; + } + /** + * Applies an OnlineState change to the view, potentially generating a + * ViewChange if the view's syncState changes as a result. + */ va(e) { + return this.current && "Offline" /* OnlineState.Offline */ === e ? ( + // If we're offline, set `current` to false and then call applyChanges() + // to refresh our syncState and generate a ViewChange as appropriate. We + // are guaranteed to get a new TargetChange that sets `current` back to + // true once the client is back online. + this.current = !1, this.applyChanges({ + tu: this.tu, + iu: new __PRIVATE_DocumentChangeSet, + mutatedKeys: this.mutatedKeys, + Cs: !1 + }, + /* limboResolutionEnabled= */ !1)) : { + au: [] + }; + } + /** + * Returns whether the doc for the given key should be in limbo. + */ uu(e) { + // If the remote end says it's part of this query, it's not in limbo. + return !this.Ya.has(e) && ( + // The local store doesn't think it's a result, so it shouldn't be in limbo. + !!this.tu.has(e) && !this.tu.get(e).hasLocalMutations); + } + /** + * Updates syncedDocuments, current, and limbo docs based on the given change. + * Returns the list of changes to which docs are in limbo. + */ ou(e) { + e && (e.addedDocuments.forEach((e => this.Ya = this.Ya.add(e))), e.modifiedDocuments.forEach((e => {})), + e.removedDocuments.forEach((e => this.Ya = this.Ya.delete(e))), this.current = e.current); + } + _u() { + // We can only determine limbo documents when we're in-sync with the server. + if (!this.current) return []; + // TODO(klimt): Do this incrementally so that it's not quadratic when + // updating many documents. + const e = this.Xa; + this.Xa = __PRIVATE_documentKeySet(), this.tu.forEach((e => { + this.uu(e.key) && (this.Xa = this.Xa.add(e.key)); + })); + // Diff the new limbo docs with the old limbo docs. + const t = []; + return e.forEach((e => { + this.Xa.has(e) || t.push(new __PRIVATE_RemovedLimboDocument(e)); + })), this.Xa.forEach((n => { + e.has(n) || t.push(new __PRIVATE_AddedLimboDocument(n)); + })), t; + } + /** + * Update the in-memory state of the current view with the state read from + * persistence. + * + * We update the query view whenever a client's primary status changes: + * - When a client transitions from primary to secondary, it can miss + * LocalStorage updates and its query views may temporarily not be + * synchronized with the state on disk. + * - For secondary to primary transitions, the client needs to update the list + * of `syncedDocuments` since secondary clients update their query views + * based purely on synthesized RemoteEvents. + * + * @param queryResult.documents - The documents that match the query according + * to the LocalStore. + * @param queryResult.remoteKeys - The keys of the documents that match the + * query according to the backend. + * + * @returns The ViewChange that resulted from this synchronization. + */ + // PORTING NOTE: Multi-tab only. + cu(e) { + this.Ya = e.Qs, this.Xa = __PRIVATE_documentKeySet(); + const t = this.ru(e.documents); + return this.applyChanges(t, /* limboResolutionEnabled= */ !0); + } + /** + * Returns a view snapshot as if this query was just listened to. Contains + * a document add for every existing document and the `fromCache` and + * `hasPendingWrites` status of the already established view. + */ + // PORTING NOTE: Multi-tab only. + lu() { + return ViewSnapshot.fromInitialDocuments(this.query, this.tu, this.mutatedKeys, 0 /* SyncState.Local */ === this.Za, this.hasCachedResults); + } +} + +const an = "SyncEngine"; + +/** + * QueryView contains all of the data that SyncEngine needs to keep track of for + * a particular query. + */ class __PRIVATE_QueryView { + constructor( + /** + * The query itself. + */ + e, + /** + * The target number created by the client that is used in the watch + * stream to identify this query. + */ + t, + /** + * The view is responsible for computing the final merged truth of what + * docs are in the query. It gets notified of local and remote changes, + * and applies the query filters and limits to determine the most correct + * possible results. + */ + n) { + this.query = e, this.targetId = t, this.view = n; + } +} + +/** Tracks a limbo resolution. */ class LimboResolution { + constructor(e) { + this.key = e, + /** + * Set to true once we've received a document. This is used in + * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to + * decide whether it needs to manufacture a delete event for the target once + * the target is CURRENT. + */ + this.hu = !1; + } +} + +/** + * An implementation of `SyncEngine` coordinating with other parts of SDK. + * + * The parts of SyncEngine that act as a callback to RemoteStore need to be + * registered individually. This is done in `syncEngineWrite()` and + * `syncEngineListen()` (as well as `applyPrimaryState()`) as these methods + * serve as entry points to RemoteStore's functionality. + * + * Note: some field defined in this class might have public access level, but + * the class is not exported so they are only accessible from this module. + * This is useful to implement optional features (like bundles) in free + * functions, such that they are tree-shakeable. + */ class __PRIVATE_SyncEngineImpl { + constructor(e, t, n, + // PORTING NOTE: Manages state synchronization in multi-tab environments. + r, i, s) { + this.localStore = e, this.remoteStore = t, this.eventManager = n, this.sharedClientState = r, + this.currentUser = i, this.maxConcurrentLimboResolutions = s, this.Pu = {}, this.Tu = new ObjectMap((e => __PRIVATE_canonifyQuery(e)), __PRIVATE_queryEquals), + this.Iu = new Map, + /** + * The keys of documents that are in limbo for which we haven't yet started a + * limbo resolution query. The strings in this set are the result of calling + * `key.path.canonicalString()` where `key` is a `DocumentKey` object. + * + * The `Set` type was chosen because it provides efficient lookup and removal + * of arbitrary elements and it also maintains insertion order, providing the + * desired queue-like FIFO semantics. + */ + this.Eu = new Set, + /** + * Keeps track of the target ID for each document that is in limbo with an + * active target. + */ + this.du = new SortedMap(DocumentKey.comparator), + /** + * Keeps track of the information about an active limbo resolution for each + * active target ID that was started for the purpose of limbo resolution. + */ + this.Au = new Map, this.Ru = new __PRIVATE_ReferenceSet, + /** Stores user completion handlers, indexed by User and BatchId. */ + this.Vu = {}, + /** Stores user callbacks waiting for all pending writes to be acknowledged. */ + this.mu = new Map, this.fu = __PRIVATE_TargetIdGenerator.cr(), this.onlineState = "Unknown" /* OnlineState.Unknown */ , + // The primary state is set to `true` or `false` immediately after Firestore + // startup. In the interim, a client should only be considered primary if + // `isPrimary` is true. + this.gu = void 0; + } + get isPrimaryClient() { + return !0 === this.gu; + } +} + +/** + * Initiates the new listen, resolves promise when listen enqueued to the + * server. All the subsequent view snapshots or errors are sent to the + * subscribed handlers. Returns the initial snapshot. + */ +async function __PRIVATE_syncEngineListen(e, t, n = !0) { + const r = __PRIVATE_ensureWatchCallbacks(e); + let i; + const s = r.Tu.get(t); + return s ? ( + // PORTING NOTE: With Multi-Tab Web, it is possible that a query view + // already exists when EventManager calls us for the first time. This + // happens when the primary tab is already listening to this query on + // behalf of another tab and the user of the primary also starts listening + // to the query. EventManager will not have an assigned target ID in this + // case and calls `listen` to obtain this ID. + r.sharedClientState.addLocalQueryTarget(s.targetId), i = s.view.lu()) : i = await __PRIVATE_allocateTargetAndMaybeListen(r, t, n, + /** shouldInitializeView= */ !0), i; +} + +/** Query has been listening to the cache, and tries to initiate the remote store listen */ async function __PRIVATE_triggerRemoteStoreListen(e, t) { + const n = __PRIVATE_ensureWatchCallbacks(e); + await __PRIVATE_allocateTargetAndMaybeListen(n, t, + /** shouldListenToRemote= */ !0, + /** shouldInitializeView= */ !1); +} + +async function __PRIVATE_allocateTargetAndMaybeListen(e, t, n, r) { + const i = await __PRIVATE_localStoreAllocateTarget(e.localStore, __PRIVATE_queryToTarget(t)), s = i.targetId, o = e.sharedClientState.addLocalQueryTarget(s, n); + let _; + return r && (_ = await __PRIVATE_initializeViewAndComputeSnapshot(e, t, s, "current" === o, i.resumeToken)), + e.isPrimaryClient && n && __PRIVATE_remoteStoreListen(e.remoteStore, i), _; +} + +/** + * Registers a view for a previously unknown query and computes its initial + * snapshot. + */ async function __PRIVATE_initializeViewAndComputeSnapshot(e, t, n, r, i) { + // PORTING NOTE: On Web only, we inject the code that registers new Limbo + // targets based on view changes. This allows us to only depend on Limbo + // changes when user code includes queries. + e.pu = (t, n, r) => async function __PRIVATE_applyDocChanges(e, t, n, r) { + let i = t.view.ru(n); + i.Cs && ( + // The query has a limit and some docs were removed, so we need + // to re-run the query against the local store to make sure we + // didn't lose any good docs that had been past the limit. + i = await __PRIVATE_localStoreExecuteQuery(e.localStore, t.query, + /* usePreviousResults= */ !1).then((({documents: e}) => t.view.ru(e, i)))); + const s = r && r.targetChanges.get(t.targetId), o = r && null != r.targetMismatches.get(t.targetId), _ = t.view.applyChanges(i, + /* limboResolutionEnabled= */ e.isPrimaryClient, s, o); + return __PRIVATE_updateTrackedLimbos(e, t.targetId, _.au), _.snapshot; + }(e, t, n, r); + const s = await __PRIVATE_localStoreExecuteQuery(e.localStore, t, + /* usePreviousResults= */ !0), o = new __PRIVATE_View(t, s.Qs), _ = o.ru(s.documents), a = TargetChange.createSynthesizedTargetChangeForCurrentChange(n, r && "Offline" /* OnlineState.Offline */ !== e.onlineState, i), u = o.applyChanges(_, + /* limboResolutionEnabled= */ e.isPrimaryClient, a); + __PRIVATE_updateTrackedLimbos(e, n, u.au); + const c = new __PRIVATE_QueryView(t, n, o); + return e.Tu.set(t, c), e.Iu.has(n) ? e.Iu.get(n).push(t) : e.Iu.set(n, [ t ]), u.snapshot; +} + +/** Stops listening to the query. */ async function __PRIVATE_syncEngineUnlisten(e, t, n) { + const r = __PRIVATE_debugCast(e), i = r.Tu.get(t), s = r.Iu.get(i.targetId); + if (s.length > 1) return r.Iu.set(i.targetId, s.filter((e => !__PRIVATE_queryEquals(e, t)))), + void r.Tu.delete(t); + // No other queries are mapped to the target, clean up the query and the target. + if (r.isPrimaryClient) { + // We need to remove the local query target first to allow us to verify + // whether any other client is still interested in this target. + r.sharedClientState.removeLocalQueryTarget(i.targetId); + r.sharedClientState.isActiveQueryTarget(i.targetId) || await __PRIVATE_localStoreReleaseTarget(r.localStore, i.targetId, + /*keepPersistedTargetData=*/ !1).then((() => { + r.sharedClientState.clearQueryState(i.targetId), n && __PRIVATE_remoteStoreUnlisten(r.remoteStore, i.targetId), + __PRIVATE_removeAndCleanupTarget(r, i.targetId); + })).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss); + } else __PRIVATE_removeAndCleanupTarget(r, i.targetId), await __PRIVATE_localStoreReleaseTarget(r.localStore, i.targetId, + /*keepPersistedTargetData=*/ !0); +} + +/** Unlistens to the remote store while still listening to the cache. */ async function __PRIVATE_triggerRemoteStoreUnlisten(e, t) { + const n = __PRIVATE_debugCast(e), r = n.Tu.get(t), i = n.Iu.get(r.targetId); + n.isPrimaryClient && 1 === i.length && ( + // PORTING NOTE: Unregister the target ID with local Firestore client as + // watch target. + n.sharedClientState.removeLocalQueryTarget(r.targetId), __PRIVATE_remoteStoreUnlisten(n.remoteStore, r.targetId)); +} + +/** + * Initiates the write of local mutation batch which involves adding the + * writes to the mutation queue, notifying the remote store about new + * mutations and raising events for any changes this write caused. + * + * The promise returned by this call is resolved when the above steps + * have completed, *not* when the write was acked by the backend. The + * userCallback is resolved once the write was acked/rejected by the + * backend (or failed locally for any other reason). + */ async function __PRIVATE_syncEngineWrite(e, t, n) { + const r = __PRIVATE_syncEngineEnsureWriteCallbacks(e); + try { + const e = await function __PRIVATE_localStoreWriteLocally(e, t) { + const n = __PRIVATE_debugCast(e), r = Timestamp.now(), i = t.reduce(((e, t) => e.add(t.key)), __PRIVATE_documentKeySet()); + let s, o; + return n.persistence.runTransaction("Locally write mutations", "readwrite", (e => { + // Figure out which keys do not have a remote version in the cache, this + // is needed to create the right overlay mutation: if no remote version + // presents, we do not need to create overlays as patch mutations. + // TODO(Overlay): Is there a better way to determine this? Using the + // document version does not work because local mutations set them back + // to 0. + let _ = __PRIVATE_mutableDocumentMap(), a = __PRIVATE_documentKeySet(); + return n.Ns.getEntries(e, i).next((e => { + _ = e, _.forEach(((e, t) => { + t.isValidDocument() || (a = a.add(e)); + })); + })).next((() => n.localDocuments.getOverlayedDocuments(e, _))).next((i => { + s = i; + // For non-idempotent mutations (such as `FieldValue.increment()`), + // we record the base state in a separate patch mutation. This is + // later used to guarantee consistent values and prevents flicker + // even if the backend sends us an update that already includes our + // transform. + const o = []; + for (const e of t) { + const t = __PRIVATE_mutationExtractBaseValue(e, s.get(e.key).overlayedDocument); + null != t && + // NOTE: The base state should only be applied if there's some + // existing document to override, so use a Precondition of + // exists=true + o.push(new __PRIVATE_PatchMutation(e.key, t, __PRIVATE_extractFieldMask(t.value.mapValue), Precondition.exists(!0))); + } + return n.mutationQueue.addMutationBatch(e, r, o, t); + })).next((t => { + o = t; + const r = t.applyToLocalDocumentSet(s, a); + return n.documentOverlayCache.saveOverlays(e, t.batchId, r); + })); + })).then((() => ({ + batchId: o.batchId, + changes: __PRIVATE_convertOverlayedDocumentMapToDocumentMap(s) + }))); + }(r.localStore, t); + r.sharedClientState.addPendingMutation(e.batchId), function __PRIVATE_addMutationCallback(e, t, n) { + let r = e.Vu[e.currentUser.toKey()]; + r || (r = new SortedMap(__PRIVATE_primitiveComparator)); + r = r.insert(t, n), e.Vu[e.currentUser.toKey()] = r; + } + /** + * Resolves or rejects the user callback for the given batch and then discards + * it. + */ (r, e.batchId, n), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(r, e.changes), + await __PRIVATE_fillWritePipeline(r.remoteStore); + } catch (e) { + // If we can't persist the mutation, we reject the user callback and + // don't send the mutation. The user can then retry the write. + const t = __PRIVATE_wrapInUserErrorIfRecoverable(e, "Failed to persist write"); + n.reject(t); + } +} + +/** + * Applies one remote event to the sync engine, notifying any views of the + * changes, and releasing any pending mutation batches that would become + * visible because of the snapshot version the remote event contains. + */ async function __PRIVATE_syncEngineApplyRemoteEvent(e, t) { + const n = __PRIVATE_debugCast(e); + try { + const e = await __PRIVATE_localStoreApplyRemoteEventToLocalCache(n.localStore, t); + // Update `receivedDocument` as appropriate for any limbo targets. + t.targetChanges.forEach(((e, t) => { + const r = n.Au.get(t); + r && ( + // Since this is a limbo resolution lookup, it's for a single document + // and it could be added, modified, or removed, but not a combination. + __PRIVATE_hardAssert(e.addedDocuments.size + e.modifiedDocuments.size + e.removedDocuments.size <= 1, 22616), + e.addedDocuments.size > 0 ? r.hu = !0 : e.modifiedDocuments.size > 0 ? __PRIVATE_hardAssert(r.hu, 14607) : e.removedDocuments.size > 0 && (__PRIVATE_hardAssert(r.hu, 42227), + r.hu = !1)); + })), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e, t); + } catch (e) { + await __PRIVATE_ignoreIfPrimaryLeaseLoss(e); + } +} + +/** + * Applies an OnlineState change to the sync engine and notifies any views of + * the change. + */ function __PRIVATE_syncEngineApplyOnlineStateChange(e, t, n) { + const r = __PRIVATE_debugCast(e); + // If we are the secondary client, we explicitly ignore the remote store's + // online state (the local client may go offline, even though the primary + // tab remains online) and only apply the primary tab's online state from + // SharedClientState. + if (r.isPrimaryClient && 0 /* OnlineStateSource.RemoteStore */ === n || !r.isPrimaryClient && 1 /* OnlineStateSource.SharedClientState */ === n) { + const e = []; + r.Tu.forEach(((n, r) => { + const i = r.view.va(t); + i.snapshot && e.push(i.snapshot); + })), function __PRIVATE_eventManagerOnOnlineStateChange(e, t) { + const n = __PRIVATE_debugCast(e); + n.onlineState = t; + let r = !1; + n.queries.forEach(((e, n) => { + for (const e of n.Sa) + // Run global snapshot listeners if a consistent snapshot has been emitted. + e.va(t) && (r = !0); + })), r && __PRIVATE_raiseSnapshotsInSyncEvent(n); + }(r.eventManager, t), e.length && r.Pu.H_(e), r.onlineState = t, r.isPrimaryClient && r.sharedClientState.setOnlineState(t); + } +} + +/** + * Rejects the listen for the given targetID. This can be triggered by the + * backend for any active target. + * + * @param syncEngine - The sync engine implementation. + * @param targetId - The targetID corresponds to one previously initiated by the + * user as part of TargetData passed to listen() on RemoteStore. + * @param err - A description of the condition that has forced the rejection. + * Nearly always this will be an indication that the user is no longer + * authorized to see the data matching the target. + */ async function __PRIVATE_syncEngineRejectListen(e, t, n) { + const r = __PRIVATE_debugCast(e); + // PORTING NOTE: Multi-tab only. + r.sharedClientState.updateQueryState(t, "rejected", n); + const i = r.Au.get(t), s = i && i.key; + if (s) { + // TODO(klimt): We really only should do the following on permission + // denied errors, but we don't have the cause code here. + // It's a limbo doc. Create a synthetic event saying it was deleted. + // This is kind of a hack. Ideally, we would have a method in the local + // store to purge a document. However, it would be tricky to keep all of + // the local store's invariants with another method. + let e = new SortedMap(DocumentKey.comparator); + // TODO(b/217189216): This limbo document should ideally have a read time, + // so that it is picked up by any read-time based scans. The backend, + // however, does not send a read time for target removals. + e = e.insert(s, MutableDocument.newNoDocument(s, SnapshotVersion.min())); + const n = __PRIVATE_documentKeySet().add(s), i = new RemoteEvent(SnapshotVersion.min(), + /* targetChanges= */ new Map, + /* targetMismatches= */ new SortedMap(__PRIVATE_primitiveComparator), e, n); + await __PRIVATE_syncEngineApplyRemoteEvent(r, i), + // Since this query failed, we won't want to manually unlisten to it. + // We only remove it from bookkeeping after we successfully applied the + // RemoteEvent. If `applyRemoteEvent()` throws, we want to re-listen to + // this query when the RemoteStore restarts the Watch stream, which should + // re-trigger the target failure. + r.du = r.du.remove(s), r.Au.delete(t), __PRIVATE_pumpEnqueuedLimboResolutions(r); + } else await __PRIVATE_localStoreReleaseTarget(r.localStore, t, + /* keepPersistedTargetData */ !1).then((() => __PRIVATE_removeAndCleanupTarget(r, t, n))).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss); +} + +async function __PRIVATE_syncEngineApplySuccessfulWrite(e, t) { + const n = __PRIVATE_debugCast(e), r = t.batch.batchId; + try { + const e = await __PRIVATE_localStoreAcknowledgeBatch(n.localStore, t); + // The local store may or may not be able to apply the write result and + // raise events immediately (depending on whether the watcher is caught + // up), so we raise user callbacks first so that they consistently happen + // before listen events. + __PRIVATE_processUserCallback(n, r, /*error=*/ null), __PRIVATE_triggerPendingWritesCallbacks(n, r), + n.sharedClientState.updateMutationState(r, "acknowledged"), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e); + } catch (e) { + await __PRIVATE_ignoreIfPrimaryLeaseLoss(e); + } +} + +async function __PRIVATE_syncEngineRejectFailedWrite(e, t, n) { + const r = __PRIVATE_debugCast(e); + try { + const e = await function __PRIVATE_localStoreRejectBatch(e, t) { + const n = __PRIVATE_debugCast(e); + return n.persistence.runTransaction("Reject batch", "readwrite-primary", (e => { + let r; + return n.mutationQueue.lookupMutationBatch(e, t).next((t => (__PRIVATE_hardAssert(null !== t, 37113), + r = t.keys(), n.mutationQueue.removeMutationBatch(e, t)))).next((() => n.mutationQueue.performConsistencyCheck(e))).next((() => n.documentOverlayCache.removeOverlaysForBatchId(e, r, t))).next((() => n.localDocuments.recalculateAndSaveOverlaysForDocumentKeys(e, r))).next((() => n.localDocuments.getDocuments(e, r))); + })); + } + /** + * Returns the largest (latest) batch id in mutation queue that is pending + * server response. + * + * Returns `BATCHID_UNKNOWN` if the queue is empty. + */ (r.localStore, t); + // The local store may or may not be able to apply the write result and + // raise events immediately (depending on whether the watcher is caught up), + // so we raise user callbacks first so that they consistently happen before + // listen events. + __PRIVATE_processUserCallback(r, t, n), __PRIVATE_triggerPendingWritesCallbacks(r, t), + r.sharedClientState.updateMutationState(t, "rejected", n), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(r, e); + } catch (n) { + await __PRIVATE_ignoreIfPrimaryLeaseLoss(n); + } +} + +/** + * Registers a user callback that resolves when all pending mutations at the moment of calling + * are acknowledged . + */ async function __PRIVATE_syncEngineRegisterPendingWritesCallback(e, t) { + const n = __PRIVATE_debugCast(e); + __PRIVATE_canUseNetwork(n.remoteStore) || __PRIVATE_logDebug(an, "The network is disabled. The task returned by 'awaitPendingWrites()' will not complete until the network is enabled."); + try { + const e = await function __PRIVATE_localStoreGetHighestUnacknowledgedBatchId(e) { + const t = __PRIVATE_debugCast(e); + return t.persistence.runTransaction("Get highest unacknowledged batch id", "readonly", (e => t.mutationQueue.getHighestUnacknowledgedBatchId(e))); + }(n.localStore); + if (e === H) + // Trigger the callback right away if there is no pending writes at the moment. + return void t.resolve(); + const r = n.mu.get(e) || []; + r.push(t), n.mu.set(e, r); + } catch (e) { + const n = __PRIVATE_wrapInUserErrorIfRecoverable(e, "Initialization of waitForPendingWrites() operation failed"); + t.reject(n); + } +} + +/** + * Triggers the callbacks that are waiting for this batch id to get acknowledged by server, + * if there are any. + */ function __PRIVATE_triggerPendingWritesCallbacks(e, t) { + (e.mu.get(t) || []).forEach((e => { + e.resolve(); + })), e.mu.delete(t); +} + +/** Reject all outstanding callbacks waiting for pending writes to complete. */ function __PRIVATE_processUserCallback(e, t, n) { + const r = __PRIVATE_debugCast(e); + let i = r.Vu[r.currentUser.toKey()]; + // NOTE: Mutations restored from persistence won't have callbacks, so it's + // okay for there to be no callback for this ID. + if (i) { + const e = i.get(t); + e && (n ? e.reject(n) : e.resolve(), i = i.remove(t)), r.Vu[r.currentUser.toKey()] = i; + } +} + +function __PRIVATE_removeAndCleanupTarget(e, t, n = null) { + e.sharedClientState.removeLocalQueryTarget(t); + for (const r of e.Iu.get(t)) e.Tu.delete(r), n && e.Pu.yu(r, n); + if (e.Iu.delete(t), e.isPrimaryClient) { + e.Ru.jr(t).forEach((t => { + e.Ru.containsKey(t) || + // We removed the last reference for this key + __PRIVATE_removeLimboTarget(e, t); + })); + } +} + +function __PRIVATE_removeLimboTarget(e, t) { + e.Eu.delete(t.path.canonicalString()); + // It's possible that the target already got removed because the query failed. In that case, + // the key won't exist in `limboTargetsByKey`. Only do the cleanup if we still have the target. + const n = e.du.get(t); + null !== n && (__PRIVATE_remoteStoreUnlisten(e.remoteStore, n), e.du = e.du.remove(t), + e.Au.delete(n), __PRIVATE_pumpEnqueuedLimboResolutions(e)); +} + +function __PRIVATE_updateTrackedLimbos(e, t, n) { + for (const r of n) if (r instanceof __PRIVATE_AddedLimboDocument) e.Ru.addReference(r.key, t), + __PRIVATE_trackLimboChange(e, r); else if (r instanceof __PRIVATE_RemovedLimboDocument) { + __PRIVATE_logDebug(an, "Document no longer in limbo: " + r.key), e.Ru.removeReference(r.key, t); + e.Ru.containsKey(r.key) || + // We removed the last reference for this key + __PRIVATE_removeLimboTarget(e, r.key); + } else fail(19791, { + wu: r + }); +} + +function __PRIVATE_trackLimboChange(e, t) { + const n = t.key, r = n.path.canonicalString(); + e.du.get(n) || e.Eu.has(r) || (__PRIVATE_logDebug(an, "New document in limbo: " + n), + e.Eu.add(r), __PRIVATE_pumpEnqueuedLimboResolutions(e)); +} + +/** + * Starts listens for documents in limbo that are enqueued for resolution, + * subject to a maximum number of concurrent resolutions. + * + * Without bounding the number of concurrent resolutions, the server can fail + * with "resource exhausted" errors which can lead to pathological client + * behavior as seen in https://github.com/firebase/firebase-js-sdk/issues/2683. + */ function __PRIVATE_pumpEnqueuedLimboResolutions(e) { + for (;e.Eu.size > 0 && e.du.size < e.maxConcurrentLimboResolutions; ) { + const t = e.Eu.values().next().value; + e.Eu.delete(t); + const n = new DocumentKey(ResourcePath.fromString(t)), r = e.fu.next(); + e.Au.set(r, new LimboResolution(n)), e.du = e.du.insert(n, r), __PRIVATE_remoteStoreListen(e.remoteStore, new TargetData(__PRIVATE_queryToTarget(__PRIVATE_newQueryForPath(n.path)), r, "TargetPurposeLimboResolution" /* TargetPurpose.LimboResolution */ , __PRIVATE_ListenSequence.ce)); + } +} + +async function __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(e, t, n) { + const r = __PRIVATE_debugCast(e), i = [], s = [], o = []; + r.Tu.isEmpty() || (r.Tu.forEach(((e, _) => { + o.push(r.pu(_, t, n).then((e => { + // If there are changes, or we are handling a global snapshot, notify + // secondary clients to update query state. + if ((e || n) && r.isPrimaryClient) { + // Query state is set to `current` if: + // - There is a view change and it is up-to-date, or, + // - There is a global snapshot, the Target is current, and no changes to be resolved + const t = e ? !e.fromCache : n?.targetChanges.get(_.targetId)?.current; + r.sharedClientState.updateQueryState(_.targetId, t ? "current" : "not-current"); + } + // Update views if there are actual changes. + if (e) { + i.push(e); + const t = __PRIVATE_LocalViewChanges.As(_.targetId, e); + s.push(t); + } + }))); + })), await Promise.all(o), r.Pu.H_(i), await async function __PRIVATE_localStoreNotifyLocalViewChanges(e, t) { + const n = __PRIVATE_debugCast(e); + try { + await n.persistence.runTransaction("notifyLocalViewChanges", "readwrite", (e => PersistencePromise.forEach(t, (t => PersistencePromise.forEach(t.Es, (r => n.persistence.referenceDelegate.addReference(e, t.targetId, r))).next((() => PersistencePromise.forEach(t.ds, (r => n.persistence.referenceDelegate.removeReference(e, t.targetId, r))))))))); + } catch (e) { + if (!__PRIVATE_isIndexedDbTransactionError(e)) throw e; + // If `notifyLocalViewChanges` fails, we did not advance the sequence + // number for the documents that were included in this transaction. + // This might trigger them to be deleted earlier than they otherwise + // would have, but it should not invalidate the integrity of the data. + __PRIVATE_logDebug(Gt, "Failed to update sequence numbers: " + e); + } + for (const e of t) { + const t = e.targetId; + if (!e.fromCache) { + const e = n.Ms.get(t), r = e.snapshotVersion, i = e.withLastLimboFreeSnapshotVersion(r); + // Advance the last limbo free snapshot version + n.Ms = n.Ms.insert(t, i); + } + } + }(r.localStore, s)); +} + +async function __PRIVATE_syncEngineHandleCredentialChange(e, t) { + const n = __PRIVATE_debugCast(e); + if (!n.currentUser.isEqual(t)) { + __PRIVATE_logDebug(an, "User change. New user:", t.toKey()); + const e = await __PRIVATE_localStoreHandleUserChange(n.localStore, t); + n.currentUser = t, + // Fails tasks waiting for pending writes requested by previous user. + function __PRIVATE_rejectOutstandingPendingWritesCallbacks(e, t) { + e.mu.forEach((e => { + e.forEach((e => { + e.reject(new FirestoreError(L.CANCELLED, t)); + })); + })), e.mu.clear(); + }(n, "'waitForPendingWrites' promise is rejected due to a user change."), + // TODO(b/114226417): Consider calling this only in the primary tab. + n.sharedClientState.handleUserChange(t, e.removedBatchIds, e.addedBatchIds), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e.Ls); + } +} + +function __PRIVATE_syncEngineGetRemoteKeysForTarget(e, t) { + const n = __PRIVATE_debugCast(e), r = n.Au.get(t); + if (r && r.hu) return __PRIVATE_documentKeySet().add(r.key); + { + let e = __PRIVATE_documentKeySet(); + const r = n.Iu.get(t); + if (!r) return e; + for (const t of r) { + const r = n.Tu.get(t); + e = e.unionWith(r.view.nu); + } + return e; + } +} + +/** + * Reconcile the list of synced documents in an existing view with those + * from persistence. + */ async function __PRIVATE_synchronizeViewAndComputeSnapshot(e, t) { + const n = __PRIVATE_debugCast(e), r = await __PRIVATE_localStoreExecuteQuery(n.localStore, t.query, + /* usePreviousResults= */ !0), i = t.view.cu(r); + return n.isPrimaryClient && __PRIVATE_updateTrackedLimbos(n, t.targetId, i.au), + i; +} + +/** + * Retrieves newly changed documents from remote document cache and raises + * snapshots if needed. + */ +// PORTING NOTE: Multi-Tab only. +async function __PRIVATE_syncEngineSynchronizeWithChangedDocuments(e, t) { + const n = __PRIVATE_debugCast(e); + return __PRIVATE_localStoreGetNewDocumentChanges(n.localStore, t).then((e => __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(n, e))); +} + +/** Applies a mutation state to an existing batch. */ +// PORTING NOTE: Multi-Tab only. +async function __PRIVATE_syncEngineApplyBatchState(e, t, n, r) { + const i = __PRIVATE_debugCast(e), s = await function __PRIVATE_localStoreLookupMutationDocuments(e, t) { + const n = __PRIVATE_debugCast(e), r = __PRIVATE_debugCast(n.mutationQueue); + return n.persistence.runTransaction("Lookup mutation documents", "readonly", (e => r.er(e, t).next((t => t ? n.localDocuments.getDocuments(e, t) : PersistencePromise.resolve(null))))); + } + // PORTING NOTE: Multi-Tab only. + (i.localStore, t); + null !== s ? ("pending" === n ? + // If we are the primary client, we need to send this write to the + // backend. Secondary clients will ignore these writes since their remote + // connection is disabled. + await __PRIVATE_fillWritePipeline(i.remoteStore) : "acknowledged" === n || "rejected" === n ? ( + // NOTE: Both these methods are no-ops for batches that originated from + // other clients. + __PRIVATE_processUserCallback(i, t, r || null), __PRIVATE_triggerPendingWritesCallbacks(i, t), + function __PRIVATE_localStoreRemoveCachedMutationBatchMetadata(e, t) { + __PRIVATE_debugCast(__PRIVATE_debugCast(e).mutationQueue).ir(t); + } + // PORTING NOTE: Multi-Tab only. + (i.localStore, t)) : fail(6720, "Unknown batchState", { + Su: n + }), await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(i, s)) : + // A throttled tab may not have seen the mutation before it was completed + // and removed from the mutation queue, in which case we won't have cached + // the affected documents. In this case we can safely ignore the update + // since that means we didn't apply the mutation locally at all (if we + // had, we would have cached the affected documents), and so we will just + // see any resulting document changes via normal remote document updates + // as applicable. + __PRIVATE_logDebug(an, "Cannot apply mutation batch with id: " + t); +} + +/** Applies a query target change from a different tab. */ +// PORTING NOTE: Multi-Tab only. +async function __PRIVATE_syncEngineApplyPrimaryState(e, t) { + const n = __PRIVATE_debugCast(e); + if (__PRIVATE_ensureWatchCallbacks(n), __PRIVATE_syncEngineEnsureWriteCallbacks(n), + !0 === t && !0 !== n.gu) { + // Secondary tabs only maintain Views for their local listeners and the + // Views internal state may not be 100% populated (in particular + // secondary tabs don't track syncedDocuments, the set of documents the + // server considers to be in the target). So when a secondary becomes + // primary, we need to need to make sure that all views for all targets + // match the state on disk. + const e = n.sharedClientState.getAllActiveQueryTargets(), t = await __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(n, e.toArray()); + n.gu = !0, await __PRIVATE_remoteStoreApplyPrimaryState(n.remoteStore, !0); + for (const e of t) __PRIVATE_remoteStoreListen(n.remoteStore, e); + } else if (!1 === t && !1 !== n.gu) { + const e = []; + let t = Promise.resolve(); + n.Iu.forEach(((r, i) => { + n.sharedClientState.isLocalQueryTarget(i) ? e.push(i) : t = t.then((() => (__PRIVATE_removeAndCleanupTarget(n, i), + __PRIVATE_localStoreReleaseTarget(n.localStore, i, + /*keepPersistedTargetData=*/ !0)))), __PRIVATE_remoteStoreUnlisten(n.remoteStore, i); + })), await t, await __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(n, e), + // PORTING NOTE: Multi-Tab only. + function __PRIVATE_resetLimboDocuments(e) { + const t = __PRIVATE_debugCast(e); + t.Au.forEach(((e, n) => { + __PRIVATE_remoteStoreUnlisten(t.remoteStore, n); + })), t.Ru.Jr(), t.Au = new Map, t.du = new SortedMap(DocumentKey.comparator); + } + /** + * Reconcile the query views of the provided query targets with the state from + * persistence. Raises snapshots for any changes that affect the local + * client and returns the updated state of all target's query data. + * + * @param syncEngine - The sync engine implementation + * @param targets - the list of targets with views that need to be recomputed + * @param transitionToPrimary - `true` iff the tab transitions from a secondary + * tab to a primary tab + */ + // PORTING NOTE: Multi-Tab only. + (n), n.gu = !1, await __PRIVATE_remoteStoreApplyPrimaryState(n.remoteStore, !1); + } +} + +async function __PRIVATE_synchronizeQueryViewsAndRaiseSnapshots(e, t, n) { + const r = __PRIVATE_debugCast(e), i = [], s = []; + for (const e of t) { + let t; + const n = r.Iu.get(e); + if (n && 0 !== n.length) { + // For queries that have a local View, we fetch their current state + // from LocalStore (as the resume token and the snapshot version + // might have changed) and reconcile their views with the persisted + // state (the list of syncedDocuments may have gotten out of sync). + t = await __PRIVATE_localStoreAllocateTarget(r.localStore, __PRIVATE_queryToTarget(n[0])); + for (const e of n) { + const t = r.Tu.get(e), n = await __PRIVATE_synchronizeViewAndComputeSnapshot(r, t); + n.snapshot && s.push(n.snapshot); + } + } else { + // For queries that never executed on this client, we need to + // allocate the target in LocalStore and initialize a new View. + const n = await __PRIVATE_localStoreGetCachedTarget(r.localStore, e); + t = await __PRIVATE_localStoreAllocateTarget(r.localStore, n), await __PRIVATE_initializeViewAndComputeSnapshot(r, __PRIVATE_synthesizeTargetToQuery(n), e, + /*current=*/ !1, t.resumeToken); + } + i.push(t); + } + return r.Pu.H_(s), i; +} + +/** + * Creates a `Query` object from the specified `Target`. There is no way to + * obtain the original `Query`, so we synthesize a `Query` from the `Target` + * object. + * + * The synthesized result might be different from the original `Query`, but + * since the synthesized `Query` should return the same results as the + * original one (only the presentation of results might differ), the potential + * difference will not cause issues. + */ +// PORTING NOTE: Multi-Tab only. +function __PRIVATE_synthesizeTargetToQuery(e) { + return __PRIVATE_newQuery(e.path, e.collectionGroup, e.orderBy, e.filters, e.limit, "F" /* LimitType.First */ , e.startAt, e.endAt); +} + +/** Returns the IDs of the clients that are currently active. */ +// PORTING NOTE: Multi-Tab only. +function __PRIVATE_syncEngineGetActiveClients(e) { + return function __PRIVATE_localStoreGetActiveClients(e) { + return __PRIVATE_debugCast(__PRIVATE_debugCast(e).persistence).Ts(); + }(__PRIVATE_debugCast(e).localStore); +} + +/** Applies a query target change from a different tab. */ +// PORTING NOTE: Multi-Tab only. +async function __PRIVATE_syncEngineApplyTargetState(e, t, n, r) { + const i = __PRIVATE_debugCast(e); + if (i.gu) + // If we receive a target state notification via WebStorage, we are + // either already secondary or another tab has taken the primary lease. + return void __PRIVATE_logDebug(an, "Ignoring unexpected query state notification."); + const s = i.Iu.get(t); + if (s && s.length > 0) switch (n) { + case "current": + case "not-current": + { + const e = await __PRIVATE_localStoreGetNewDocumentChanges(i.localStore, __PRIVATE_queryCollectionGroup(s[0])), r = RemoteEvent.createSynthesizedRemoteEventForCurrentChange(t, "current" === n, ByteString.EMPTY_BYTE_STRING); + await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(i, e, r); + break; + } + + case "rejected": + await __PRIVATE_localStoreReleaseTarget(i.localStore, t, + /* keepPersistedTargetData */ !0), __PRIVATE_removeAndCleanupTarget(i, t, r); + break; + + default: + fail(64155, n); + } +} + +/** Adds or removes Watch targets for queries from different tabs. */ async function __PRIVATE_syncEngineApplyActiveTargetsChange(e, t, n) { + const r = __PRIVATE_ensureWatchCallbacks(e); + if (r.gu) { + for (const e of t) { + if (r.Iu.has(e) && r.sharedClientState.isActiveQueryTarget(e)) { + __PRIVATE_logDebug(an, "Adding an already active target " + e); + continue; + } + const t = await __PRIVATE_localStoreGetCachedTarget(r.localStore, e), n = await __PRIVATE_localStoreAllocateTarget(r.localStore, t); + await __PRIVATE_initializeViewAndComputeSnapshot(r, __PRIVATE_synthesizeTargetToQuery(t), n.targetId, + /*current=*/ !1, n.resumeToken), __PRIVATE_remoteStoreListen(r.remoteStore, n); + } + for (const e of n) + // Check that the target is still active since the target might have been + // removed if it has been rejected by the backend. + r.Iu.has(e) && + // Release queries that are still active. + await __PRIVATE_localStoreReleaseTarget(r.localStore, e, + /* keepPersistedTargetData */ !1).then((() => { + __PRIVATE_remoteStoreUnlisten(r.remoteStore, e), __PRIVATE_removeAndCleanupTarget(r, e); + })).catch(__PRIVATE_ignoreIfPrimaryLeaseLoss); + } +} + +function __PRIVATE_ensureWatchCallbacks(e) { + const t = __PRIVATE_debugCast(e); + return t.remoteStore.remoteSyncer.applyRemoteEvent = __PRIVATE_syncEngineApplyRemoteEvent.bind(null, t), + t.remoteStore.remoteSyncer.getRemoteKeysForTarget = __PRIVATE_syncEngineGetRemoteKeysForTarget.bind(null, t), + t.remoteStore.remoteSyncer.rejectListen = __PRIVATE_syncEngineRejectListen.bind(null, t), + t.Pu.H_ = __PRIVATE_eventManagerOnWatchChange.bind(null, t.eventManager), t.Pu.yu = __PRIVATE_eventManagerOnWatchError.bind(null, t.eventManager), + t; +} + +function __PRIVATE_syncEngineEnsureWriteCallbacks(e) { + const t = __PRIVATE_debugCast(e); + return t.remoteStore.remoteSyncer.applySuccessfulWrite = __PRIVATE_syncEngineApplySuccessfulWrite.bind(null, t), + t.remoteStore.remoteSyncer.rejectFailedWrite = __PRIVATE_syncEngineRejectFailedWrite.bind(null, t), + t; +} + +/** + * Loads a Firestore bundle into the SDK. The returned promise resolves when + * the bundle finished loading. + * + * @param syncEngine - SyncEngine to use. + * @param bundleReader - Bundle to load into the SDK. + * @param task - LoadBundleTask used to update the loading progress to public API. + */ function __PRIVATE_syncEngineLoadBundle(e, t, n) { + const r = __PRIVATE_debugCast(e); + // eslint-disable-next-line @typescript-eslint/no-floating-promises + ( + /** Loads a bundle and returns the list of affected collection groups. */ + async function __PRIVATE_loadBundleImpl(e, t, n) { + try { + const r = await t.getMetadata(); + if (await function __PRIVATE_localStoreHasNewerBundle(e, t) { + const n = __PRIVATE_debugCast(e), r = __PRIVATE_fromVersion(t.createTime); + return n.persistence.runTransaction("hasNewerBundle", "readonly", (e => n.Ii.getBundleMetadata(e, t.id))).then((e => !!e && e.createTime.compareTo(r) >= 0)); + } + /** + * Saves the given `BundleMetadata` to local persistence. + */ (e.localStore, r)) return await t.close(), n._completeWith(function __PRIVATE_bundleSuccessProgress(e) { + return { + taskState: "Success", + documentsLoaded: e.totalDocuments, + bytesLoaded: e.totalBytes, + totalDocuments: e.totalDocuments, + totalBytes: e.totalBytes + }; + }(r)), Promise.resolve(new Set); + n._updateProgress(__PRIVATE_bundleInitialProgress(r)); + const i = new __PRIVATE_BundleLoader(r, t.serializer); + let s = await t.bu(); + for (;s; ) { + const e = await i.Ga(s); + e && n._updateProgress(e), s = await t.bu(); + } + const o = await i.ja(e.localStore); + return await __PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore(e, o.Ha, + /* remoteEvent */ void 0), + // Save metadata, so loading the same bundle will skip. + await function __PRIVATE_localStoreSaveBundle(e, t) { + const n = __PRIVATE_debugCast(e); + return n.persistence.runTransaction("Save bundle", "readwrite", (e => n.Ii.saveBundleMetadata(e, t))); + } + /** + * Returns a promise of a `NamedQuery` associated with given query name. Promise + * resolves to undefined if no persisted data can be found. + */ (e.localStore, r), n._completeWith(o.progress), Promise.resolve(o.Ja); + } catch (e) { + return __PRIVATE_logWarn(an, `Loading bundle failed with ${e}`), n._failWith(e), + Promise.resolve(new Set); + } + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Provides all components needed for Firestore with in-memory persistence. + * Uses EagerGC garbage collection. + */)(r, t, n).then((e => { + r.sharedClientState.notifyBundleLoaded(e); + })); +} + +class __PRIVATE_MemoryOfflineComponentProvider { + constructor() { + this.kind = "memory", this.synchronizeTabs = !1; + } + async initialize(e) { + this.serializer = __PRIVATE_newSerializer(e.databaseInfo.databaseId), this.sharedClientState = this.Du(e), + this.persistence = this.Cu(e), await this.persistence.start(), this.localStore = this.vu(e), + this.gcScheduler = this.Fu(e, this.localStore), this.indexBackfillerScheduler = this.Mu(e, this.localStore); + } + Fu(e, t) { + return null; + } + Mu(e, t) { + return null; + } + vu(e) { + return __PRIVATE_newLocalStore(this.persistence, new __PRIVATE_QueryEngine, e.initialUser, this.serializer); + } + Cu(e) { + return new __PRIVATE_MemoryPersistence(__PRIVATE_MemoryEagerDelegate.mi, this.serializer); + } + Du(e) { + return new __PRIVATE_MemorySharedClientState; + } + async terminate() { + this.gcScheduler?.stop(), this.indexBackfillerScheduler?.stop(), this.sharedClientState.shutdown(), + await this.persistence.shutdown(); + } +} + +__PRIVATE_MemoryOfflineComponentProvider.provider = { + build: () => new __PRIVATE_MemoryOfflineComponentProvider +}; + +class __PRIVATE_LruGcMemoryOfflineComponentProvider extends __PRIVATE_MemoryOfflineComponentProvider { + constructor(e) { + super(), this.cacheSizeBytes = e; + } + Fu(e, t) { + __PRIVATE_hardAssert(this.persistence.referenceDelegate instanceof __PRIVATE_MemoryLruDelegate, 46915); + const n = this.persistence.referenceDelegate.garbageCollector; + return new __PRIVATE_LruScheduler(n, e.asyncQueue, t); + } + Cu(e) { + const t = void 0 !== this.cacheSizeBytes ? LruParams.withCacheSize(this.cacheSizeBytes) : LruParams.DEFAULT; + return new __PRIVATE_MemoryPersistence((e => __PRIVATE_MemoryLruDelegate.mi(e, t)), this.serializer); + } +} + +/** + * Provides all components needed for Firestore with IndexedDB persistence. + */ class __PRIVATE_IndexedDbOfflineComponentProvider extends __PRIVATE_MemoryOfflineComponentProvider { + constructor(e, t, n) { + super(), this.xu = e, this.cacheSizeBytes = t, this.forceOwnership = n, this.kind = "persistent", + this.synchronizeTabs = !1; + } + async initialize(e) { + await super.initialize(e), await this.xu.initialize(this, e), + // Enqueue writes from a previous session + await __PRIVATE_syncEngineEnsureWriteCallbacks(this.xu.syncEngine), await __PRIVATE_fillWritePipeline(this.xu.remoteStore), + // NOTE: This will immediately call the listener, so we make sure to + // set it after localStore / remoteStore are started. + await this.persistence.Ji((() => (this.gcScheduler && !this.gcScheduler.started && this.gcScheduler.start(), + this.indexBackfillerScheduler && !this.indexBackfillerScheduler.started && this.indexBackfillerScheduler.start(), + Promise.resolve()))); + } + vu(e) { + return __PRIVATE_newLocalStore(this.persistence, new __PRIVATE_QueryEngine, e.initialUser, this.serializer); + } + Fu(e, t) { + const n = this.persistence.referenceDelegate.garbageCollector; + return new __PRIVATE_LruScheduler(n, e.asyncQueue, t); + } + Mu(e, t) { + const n = new __PRIVATE_IndexBackfiller(t, this.persistence); + return new __PRIVATE_IndexBackfillerScheduler(e.asyncQueue, n); + } + Cu(e) { + const t = __PRIVATE_indexedDbStoragePrefix(e.databaseInfo.databaseId, e.databaseInfo.persistenceKey), n = void 0 !== this.cacheSizeBytes ? LruParams.withCacheSize(this.cacheSizeBytes) : LruParams.DEFAULT; + return new __PRIVATE_IndexedDbPersistence(this.synchronizeTabs, t, e.clientId, n, e.asyncQueue, __PRIVATE_getWindow(), getDocument(), this.serializer, this.sharedClientState, !!this.forceOwnership); + } + Du(e) { + return new __PRIVATE_MemorySharedClientState; + } +} + +/** + * Provides all components needed for Firestore with multi-tab IndexedDB + * persistence. + * + * In the legacy client, this provider is used to provide both multi-tab and + * non-multi-tab persistence since we cannot tell at build time whether + * `synchronizeTabs` will be enabled. + */ class __PRIVATE_MultiTabOfflineComponentProvider extends __PRIVATE_IndexedDbOfflineComponentProvider { + constructor(e, t) { + super(e, t, /* forceOwnership= */ !1), this.xu = e, this.cacheSizeBytes = t, this.synchronizeTabs = !0; + } + async initialize(e) { + await super.initialize(e); + const t = this.xu.syncEngine; + this.sharedClientState instanceof __PRIVATE_WebStorageSharedClientState && (this.sharedClientState.syncEngine = { + Co: __PRIVATE_syncEngineApplyBatchState.bind(null, t), + vo: __PRIVATE_syncEngineApplyTargetState.bind(null, t), + Fo: __PRIVATE_syncEngineApplyActiveTargetsChange.bind(null, t), + Ts: __PRIVATE_syncEngineGetActiveClients.bind(null, t), + Do: __PRIVATE_syncEngineSynchronizeWithChangedDocuments.bind(null, t) + }, await this.sharedClientState.start()), + // NOTE: This will immediately call the listener, so we make sure to + // set it after localStore / remoteStore are started. + await this.persistence.Ji((async e => { + await __PRIVATE_syncEngineApplyPrimaryState(this.xu.syncEngine, e), this.gcScheduler && (e && !this.gcScheduler.started ? this.gcScheduler.start() : e || this.gcScheduler.stop()), + this.indexBackfillerScheduler && (e && !this.indexBackfillerScheduler.started ? this.indexBackfillerScheduler.start() : e || this.indexBackfillerScheduler.stop()); + })); + } + Du(e) { + const t = __PRIVATE_getWindow(); + if (!__PRIVATE_WebStorageSharedClientState.v(t)) throw new FirestoreError(L.UNIMPLEMENTED, "IndexedDB persistence is only available on platforms that support LocalStorage."); + const n = __PRIVATE_indexedDbStoragePrefix(e.databaseInfo.databaseId, e.databaseInfo.persistenceKey); + return new __PRIVATE_WebStorageSharedClientState(t, e.asyncQueue, n, e.clientId, e.initialUser); + } +} + +/** + * Initializes and wires the components that are needed to interface with the + * network. + */ class OnlineComponentProvider { + async initialize(e, t) { + this.localStore || (this.localStore = e.localStore, this.sharedClientState = e.sharedClientState, + this.datastore = this.createDatastore(t), this.remoteStore = this.createRemoteStore(t), + this.eventManager = this.createEventManager(t), this.syncEngine = this.createSyncEngine(t, + /* startAsPrimary=*/ !e.synchronizeTabs), this.sharedClientState.onlineStateHandler = e => __PRIVATE_syncEngineApplyOnlineStateChange(this.syncEngine, e, 1 /* OnlineStateSource.SharedClientState */), + this.remoteStore.remoteSyncer.handleCredentialChange = __PRIVATE_syncEngineHandleCredentialChange.bind(null, this.syncEngine), + await __PRIVATE_remoteStoreApplyPrimaryState(this.remoteStore, this.syncEngine.isPrimaryClient)); + } + createEventManager(e) { + return function __PRIVATE_newEventManager() { + return new __PRIVATE_EventManagerImpl; + }(); + } + createDatastore(e) { + const t = __PRIVATE_newSerializer(e.databaseInfo.databaseId), n = function __PRIVATE_newConnection(e) { + return new __PRIVATE_WebChannelConnection(e); + } + /** Return the Platform-specific connectivity monitor. */ (e.databaseInfo); + return function __PRIVATE_newDatastore(e, t, n, r) { + return new __PRIVATE_DatastoreImpl(e, t, n, r); + }(e.authCredentials, e.appCheckCredentials, n, t); + } + createRemoteStore(e) { + return function __PRIVATE_newRemoteStore(e, t, n, r, i) { + return new __PRIVATE_RemoteStoreImpl(e, t, n, r, i); + } + /** Re-enables the network. Idempotent. */ (this.localStore, this.datastore, e.asyncQueue, (e => __PRIVATE_syncEngineApplyOnlineStateChange(this.syncEngine, e, 0 /* OnlineStateSource.RemoteStore */)), function __PRIVATE_newConnectivityMonitor() { + return __PRIVATE_BrowserConnectivityMonitor.v() ? new __PRIVATE_BrowserConnectivityMonitor : new __PRIVATE_NoopConnectivityMonitor; + }()); + } + createSyncEngine(e, t) { + return function __PRIVATE_newSyncEngine(e, t, n, + // PORTING NOTE: Manages state synchronization in multi-tab environments. + r, i, s, o) { + const _ = new __PRIVATE_SyncEngineImpl(e, t, n, r, i, s); + return o && (_.gu = !0), _; + }(this.localStore, this.remoteStore, this.eventManager, this.sharedClientState, e.initialUser, e.maxConcurrentLimboResolutions, t); + } + async terminate() { + await async function __PRIVATE_remoteStoreShutdown(e) { + const t = __PRIVATE_debugCast(e); + __PRIVATE_logDebug(sn, "RemoteStore shutting down."), t.Ea.add(5 /* OfflineCause.Shutdown */), + await __PRIVATE_disableNetworkInternal(t), t.Aa.shutdown(), + // Set the OnlineState to Unknown (rather than Offline) to avoid potentially + // triggering spurious listener events with cached data, etc. + t.Ra.set("Unknown" /* OnlineState.Unknown */); + }(this.remoteStore), this.datastore?.terminate(), this.eventManager?.terminate(); + } +} + +OnlineComponentProvider.provider = { + build: () => new OnlineComponentProvider +}; + +/** + * Builds a `ByteStreamReader` from a UInt8Array. + * @param source - The data source to use. + * @param bytesPerRead - How many bytes each `read()` from the returned reader + * will read. + */ +function __PRIVATE_toByteStreamReaderHelper(e, t = 10240) { + let n = 0; + // The TypeScript definition for ReadableStreamReader changed. We use + // `any` here to allow this code to compile with different versions. + // See https://github.com/microsoft/TypeScript/issues/42970 + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + async read() { + if (n < e.byteLength) { + const r = { + value: e.slice(n, n + t), + done: !1 + }; + return n += t, r; + } + return { + done: !0 + }; + }, + async cancel() {}, + releaseLock() {}, + closed: Promise.resolve() + }; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * On web, a `ReadableStream` is wrapped around by a `ByteStreamReader`. + */ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/* + * A wrapper implementation of Observer that will dispatch events + * asynchronously. To allow immediate silencing, a mute call is added which + * causes events scheduled to no longer be raised. + */ +class __PRIVATE_AsyncObserver { + constructor(e) { + this.observer = e, + /** + * When set to true, will not raise future events. Necessary to deal with + * async detachment of listener. + */ + this.muted = !1; + } + next(e) { + this.muted || this.observer.next && this.Ou(this.observer.next, e); + } + error(e) { + this.muted || (this.observer.error ? this.Ou(this.observer.error, e) : __PRIVATE_logError("Uncaught Error in snapshot listener:", e.toString())); + } + Nu() { + this.muted = !0; + } + Ou(e, t) { + setTimeout((() => { + this.muted || e(t); + }), 0); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A class representing a bundle. + * + * Takes a bundle stream or buffer, and presents abstractions to read bundled + * elements out of the underlying content. + */ class __PRIVATE_BundleReaderImpl { + constructor( + /** The reader to read from underlying binary bundle data source. */ + e, t) { + this.Bu = e, this.serializer = t, + /** Cached bundle metadata. */ + this.metadata = new __PRIVATE_Deferred, + /** + * Internal buffer to hold bundle content, accumulating incomplete element + * content. + */ + this.buffer = new Uint8Array, this.Lu = function __PRIVATE_newTextDecoder() { + return new TextDecoder("utf-8"); + }(), + // Read the metadata (which is the first element). + this.ku().then((e => { + e && e.$a() ? this.metadata.resolve(e.Qa.metadata) : this.metadata.reject(new Error(`The first element of the bundle is not a metadata, it is\n ${JSON.stringify(e?.Qa)}`)); + }), (e => this.metadata.reject(e))); + } + close() { + return this.Bu.cancel(); + } + async getMetadata() { + return this.metadata.promise; + } + async bu() { + // Makes sure metadata is read before proceeding. + return await this.getMetadata(), this.ku(); + } + /** + * Reads from the head of internal buffer, and pulling more data from + * underlying stream if a complete element cannot be found, until an + * element(including the prefixed length and the JSON string) is found. + * + * Once a complete element is read, it is dropped from internal buffer. + * + * Returns either the bundled element, or null if we have reached the end of + * the stream. + */ async ku() { + const e = await this.qu(); + if (null === e) return null; + const t = this.Lu.decode(e), n = Number(t); + isNaN(n) && this.Qu(`length string (${t}) is not valid number`); + const r = await this.$u(n); + return new __PRIVATE_SizedBundleElement(JSON.parse(r), e.length + n); + } + /** First index of '{' from the underlying buffer. */ Uu() { + return this.buffer.findIndex((e => e === "{".charCodeAt(0))); + } + /** + * Reads from the beginning of the internal buffer, until the first '{', and + * return the content. + * + * If reached end of the stream, returns a null. + */ async qu() { + for (;this.Uu() < 0; ) { + if (await this.Ku()) break; + } + // Broke out of the loop because underlying stream is closed, and there + // happens to be no more data to process. + if (0 === this.buffer.length) return null; + const e = this.Uu(); + // Broke out of the loop because underlying stream is closed, but still + // cannot find an open bracket. + e < 0 && this.Qu("Reached the end of bundle when a length string is expected."); + const t = this.buffer.slice(0, e); + // Update the internal buffer to drop the read length. + return this.buffer = this.buffer.slice(e), t; + } + /** + * Reads from a specified position from the internal buffer, for a specified + * number of bytes, pulling more data from the underlying stream if needed. + * + * Returns a string decoded from the read bytes. + */ async $u(e) { + for (;this.buffer.length < e; ) { + await this.Ku() && this.Qu("Reached the end of bundle when more is expected."); + } + const t = this.Lu.decode(this.buffer.slice(0, e)); + // Update the internal buffer to drop the read json string. + return this.buffer = this.buffer.slice(e), t; + } + Qu(e) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + throw this.Bu.cancel(), new Error(`Invalid bundle format: ${e}`); + } + /** + * Pulls more data from underlying stream to internal buffer. + * Returns a boolean indicating whether the stream is finished. + */ async Ku() { + const e = await this.Bu.read(); + if (!e.done) { + const t = new Uint8Array(this.buffer.length + e.value.length); + t.set(this.buffer), t.set(e.value, this.buffer.length), this.buffer = t; + } + return e.done; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A class that can parse a bundle form the string serialization of a bundle. + */ +class __PRIVATE_BundleReaderSyncImpl { + constructor(e, t) { + this.bundleData = e, this.serializer = t, this.cursor = 0, this.elements = []; + let n = this.bu(); + if (!n || !n.$a()) throw new Error(`The first element of the bundle is not a metadata object, it is\n ${JSON.stringify(n?.Qa)}`); + this.metadata = n; + do { + n = this.bu(), null !== n && this.elements.push(n); + } while (null !== n); + } + /* Returns the parsed metadata of the bundle. */ getMetadata() { + return this.metadata; + } + /* Returns the DocumentSnapshot or NamedQuery elements of the bundle. */ Wu() { + return this.elements; + } + /** + * Parses the next element of the bundle. + * + * @returns a SizedBundleElement representation of the next element in the bundle, or null if + * no more elements exist. + */ bu() { + if (this.cursor === this.bundleData.length) return null; + const e = this.qu(), t = this.$u(e); + return new __PRIVATE_SizedBundleElement(JSON.parse(t), e); + } + /** + * Reads from a specified position from the bundleData string, for a specified + * number of bytes. + * + * @param length how many characters to read. + * @returns a string parsed from the bundle. + */ $u(e) { + if (this.cursor + e > this.bundleData.length) throw new FirestoreError(L.INTERNAL, "Reached the end of bundle when more is expected."); + return this.bundleData.slice(this.cursor, this.cursor += e); + } + /** + * Reads from the current cursor until the first '{'. + * + * @returns A string to integer represention of the parsed value. + * @throws An {@link Error} if the cursor has reached the end of the stream, since lengths + * prefix bundle objects. + */ qu() { + const e = this.cursor; + let t = this.cursor; + for (;t < this.bundleData.length; ) { + if ("{" === this.bundleData[t]) { + if (t === e) throw new Error("First character is a bracket and not a number"); + return this.cursor = t, Number(this.bundleData.slice(e, t)); + } + t++; + } + throw new Error("Reached the end of bundle when more is expected."); + } +} + +/** + * Creates an instance of BundleReader without exposing the BundleReaderSyncImpl class type. + */ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Internal transaction object responsible for accumulating the mutations to + * perform and the base versions for any documents read. + */ +class Transaction$2 { + constructor(e) { + this.datastore = e, + // The version of each document that was read during this transaction. + this.readVersions = new Map, this.mutations = [], this.committed = !1, + /** + * A deferred usage error that occurred previously in this transaction that + * will cause the transaction to fail once it actually commits. + */ + this.lastTransactionError = null, + /** + * Set of documents that have been written in the transaction. + * + * When there's more than one write to the same key in a transaction, any + * writes after the first are handled differently. + */ + this.writtenDocs = new Set; + } + async lookup(e) { + if (this.ensureCommitNotCalled(), this.mutations.length > 0) throw this.lastTransactionError = new FirestoreError(L.INVALID_ARGUMENT, "Firestore transactions require all reads to be executed before all writes."), + this.lastTransactionError; + const t = await async function __PRIVATE_invokeBatchGetDocumentsRpc(e, t) { + const n = __PRIVATE_debugCast(e), r = { + documents: t.map((e => __PRIVATE_toName(n.serializer, e))) + }, i = await n.Ho("BatchGetDocuments", n.serializer.databaseId, ResourcePath.emptyPath(), r, t.length), s = new Map; + i.forEach((e => { + const t = __PRIVATE_fromBatchGetDocumentsResponse(n.serializer, e); + s.set(t.key.toString(), t); + })); + const o = []; + return t.forEach((e => { + const t = s.get(e.toString()); + __PRIVATE_hardAssert(!!t, 55234, { + key: e + }), o.push(t); + })), o; + }(this.datastore, e); + return t.forEach((e => this.recordVersion(e))), t; + } + set(e, t) { + this.write(t.toMutation(e, this.precondition(e))), this.writtenDocs.add(e.toString()); + } + update(e, t) { + try { + this.write(t.toMutation(e, this.preconditionForUpdate(e))); + } catch (e) { + this.lastTransactionError = e; + } + this.writtenDocs.add(e.toString()); + } + delete(e) { + this.write(new __PRIVATE_DeleteMutation(e, this.precondition(e))), this.writtenDocs.add(e.toString()); + } + async commit() { + if (this.ensureCommitNotCalled(), this.lastTransactionError) throw this.lastTransactionError; + const e = this.readVersions; + // For each mutation, note that the doc was written. + this.mutations.forEach((t => { + e.delete(t.key.toString()); + })), + // For each document that was read but not written to, we want to perform + // a `verify` operation. + e.forEach(((e, t) => { + const n = DocumentKey.fromPath(t); + this.mutations.push(new __PRIVATE_VerifyMutation(n, this.precondition(n))); + })), await async function __PRIVATE_invokeCommitRpc(e, t) { + const n = __PRIVATE_debugCast(e), r = { + writes: t.map((e => toMutation(n.serializer, e))) + }; + await n.Go("Commit", n.serializer.databaseId, ResourcePath.emptyPath(), r); + }(this.datastore, this.mutations), this.committed = !0; + } + recordVersion(e) { + let t; + if (e.isFoundDocument()) t = e.version; else { + if (!e.isNoDocument()) throw fail(50498, { + Gu: e.constructor.name + }); + // Represent a deleted doc using SnapshotVersion.min(). + t = SnapshotVersion.min(); + } + const n = this.readVersions.get(e.key.toString()); + if (n) { + if (!t.isEqual(n)) + // This transaction will fail no matter what. + throw new FirestoreError(L.ABORTED, "Document version changed between two reads."); + } else this.readVersions.set(e.key.toString(), t); + } + /** + * Returns the version of this document when it was read in this transaction, + * as a precondition, or no precondition if it was not read. + */ precondition(e) { + const t = this.readVersions.get(e.toString()); + return !this.writtenDocs.has(e.toString()) && t ? t.isEqual(SnapshotVersion.min()) ? Precondition.exists(!1) : Precondition.updateTime(t) : Precondition.none(); + } + /** + * Returns the precondition for a document if the operation is an update. + */ preconditionForUpdate(e) { + const t = this.readVersions.get(e.toString()); + // The first time a document is written, we want to take into account the + // read time and existence + if (!this.writtenDocs.has(e.toString()) && t) { + if (t.isEqual(SnapshotVersion.min())) + // The document doesn't exist, so fail the transaction. + // This has to be validated locally because you can't send a + // precondition that a document does not exist without changing the + // semantics of the backend write to be an insert. This is the reverse + // of what we want, since we want to assert that the document doesn't + // exist but then send the update and have it fail. Since we can't + // express that to the backend, we have to validate locally. + // Note: this can change once we can send separate verify writes in the + // transaction. + throw new FirestoreError(L.INVALID_ARGUMENT, "Can't update a document that doesn't exist."); + // Document exists, base precondition on document update time. + return Precondition.updateTime(t); + } + // Document was not read, so we just use the preconditions for a blind + // update. + return Precondition.exists(!0); + } + write(e) { + this.ensureCommitNotCalled(), this.mutations.push(e); + } + ensureCommitNotCalled() {} +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * TransactionRunner encapsulates the logic needed to run and retry transactions + * with backoff. + */ class __PRIVATE_TransactionRunner { + constructor(e, t, n, r, i) { + this.asyncQueue = e, this.datastore = t, this.options = n, this.updateFunction = r, + this.deferred = i, this.zu = n.maxAttempts, this.M_ = new __PRIVATE_ExponentialBackoff(this.asyncQueue, "transaction_retry" /* TimerId.TransactionRetry */); + } + /** Runs the transaction and sets the result on deferred. */ ju() { + this.zu -= 1, this.Ju(); + } + Ju() { + this.M_.p_((async () => { + const e = new Transaction$2(this.datastore), t = this.Hu(e); + t && t.then((t => { + this.asyncQueue.enqueueAndForget((() => e.commit().then((() => { + this.deferred.resolve(t); + })).catch((e => { + this.Yu(e); + })))); + })).catch((e => { + this.Yu(e); + })); + })); + } + Hu(e) { + try { + const t = this.updateFunction(e); + return !__PRIVATE_isNullOrUndefined(t) && t.catch && t.then ? t : (this.deferred.reject(Error("Transaction callback must return a Promise")), + null); + } catch (e) { + // Do not retry errors thrown by user provided updateFunction. + return this.deferred.reject(e), null; + } + } + Yu(e) { + this.zu > 0 && this.Zu(e) ? (this.zu -= 1, this.asyncQueue.enqueueAndForget((() => (this.Ju(), + Promise.resolve())))) : this.deferred.reject(e); + } + Zu(e) { + if ("FirebaseError" === e?.name) { + // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and + // non-matching document versions with ABORTED. These errors should be retried. + const t = e.code; + return "aborted" === t || "failed-precondition" === t || "already-exists" === t || !__PRIVATE_isPermanentError(t); + } + return !1; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const un = "FirestoreClient"; + +/** + * FirestoreClient is a top-level class that constructs and owns all of the // + * pieces of the client SDK architecture. It is responsible for creating the // + * async queue that is shared by all of the other components in the system. // + */ +class FirestoreClient { + constructor(e, t, + /** + * Asynchronous queue responsible for all of our internal processing. When + * we get incoming work from the user (via public API) or the network + * (incoming GRPC messages), we should always schedule onto this queue. + * This ensures all of our work is properly serialized (e.g. we don't + * start processing a new operation while the previous one is waiting for + * an async I/O to complete). + */ + n, r, i) { + this.authCredentials = e, this.appCheckCredentials = t, this.asyncQueue = n, this.databaseInfo = r, + this.user = User.UNAUTHENTICATED, this.clientId = __PRIVATE_AutoId.newId(), this.authCredentialListener = () => Promise.resolve(), + this.appCheckCredentialListener = () => Promise.resolve(), this._uninitializedComponentsProvider = i, + this.authCredentials.start(n, (async e => { + __PRIVATE_logDebug(un, "Received user=", e.uid), await this.authCredentialListener(e), + this.user = e; + })), this.appCheckCredentials.start(n, (e => (__PRIVATE_logDebug(un, "Received new app check token=", e), + this.appCheckCredentialListener(e, this.user)))); + } + get configuration() { + return { + asyncQueue: this.asyncQueue, + databaseInfo: this.databaseInfo, + clientId: this.clientId, + authCredentials: this.authCredentials, + appCheckCredentials: this.appCheckCredentials, + initialUser: this.user, + maxConcurrentLimboResolutions: 100 + }; + } + setCredentialChangeListener(e) { + this.authCredentialListener = e; + } + setAppCheckTokenChangeListener(e) { + this.appCheckCredentialListener = e; + } + terminate() { + this.asyncQueue.enterRestrictedMode(); + const e = new __PRIVATE_Deferred; + return this.asyncQueue.enqueueAndForgetEvenWhileRestricted((async () => { + try { + this._onlineComponents && await this._onlineComponents.terminate(), this._offlineComponents && await this._offlineComponents.terminate(), + // The credentials provider must be terminated after shutting down the + // RemoteStore as it will prevent the RemoteStore from retrieving auth + // tokens. + this.authCredentials.shutdown(), this.appCheckCredentials.shutdown(), e.resolve(); + } catch (t) { + const n = __PRIVATE_wrapInUserErrorIfRecoverable(t, "Failed to shutdown persistence"); + e.reject(n); + } + })), e.promise; + } +} + +async function __PRIVATE_setOfflineComponentProvider(e, t) { + e.asyncQueue.verifyOperationInProgress(), __PRIVATE_logDebug(un, "Initializing OfflineComponentProvider"); + const n = e.configuration; + await t.initialize(n); + let r = n.initialUser; + e.setCredentialChangeListener((async e => { + r.isEqual(e) || (await __PRIVATE_localStoreHandleUserChange(t.localStore, e), r = e); + })), + // When a user calls clearPersistence() in one client, all other clients + // need to be terminated to allow the delete to succeed. + t.persistence.setDatabaseDeletedListener((() => e.terminate())), e._offlineComponents = t; +} + +async function __PRIVATE_setOnlineComponentProvider(e, t) { + e.asyncQueue.verifyOperationInProgress(); + const n = await __PRIVATE_ensureOfflineComponents(e); + __PRIVATE_logDebug(un, "Initializing OnlineComponentProvider"), await t.initialize(n, e.configuration), + // The CredentialChangeListener of the online component provider takes + // precedence over the offline component provider. + e.setCredentialChangeListener((e => __PRIVATE_remoteStoreHandleCredentialChange(t.remoteStore, e))), + e.setAppCheckTokenChangeListener(((e, n) => __PRIVATE_remoteStoreHandleCredentialChange(t.remoteStore, n))), + e._onlineComponents = t; +} + +/** + * Decides whether the provided error allows us to gracefully disable + * persistence (as opposed to crashing the client). + */ async function __PRIVATE_ensureOfflineComponents(e) { + if (!e._offlineComponents) if (e._uninitializedComponentsProvider) { + __PRIVATE_logDebug(un, "Using user provided OfflineComponentProvider"); + try { + await __PRIVATE_setOfflineComponentProvider(e, e._uninitializedComponentsProvider._offline); + } catch (t) { + const n = t; + if (!function __PRIVATE_canFallbackFromIndexedDbError(e) { + return "FirebaseError" === e.name ? e.code === L.FAILED_PRECONDITION || e.code === L.UNIMPLEMENTED : !("undefined" != typeof DOMException && e instanceof DOMException) || + // When the browser is out of quota we could get either quota exceeded + // or an aborted error depending on whether the error happened during + // schema migration. + 22 === e.code || 20 === e.code || + // Firefox Private Browsing mode disables IndexedDb and returns + // INVALID_STATE for any usage. + 11 === e.code; + }(n)) throw n; + __PRIVATE_logWarn("Error using user provided cache. Falling back to memory cache: " + n), + await __PRIVATE_setOfflineComponentProvider(e, new __PRIVATE_MemoryOfflineComponentProvider); + } + } else __PRIVATE_logDebug(un, "Using default OfflineComponentProvider"), await __PRIVATE_setOfflineComponentProvider(e, new __PRIVATE_LruGcMemoryOfflineComponentProvider(void 0)); + return e._offlineComponents; +} + +async function __PRIVATE_ensureOnlineComponents(e) { + return e._onlineComponents || (e._uninitializedComponentsProvider ? (__PRIVATE_logDebug(un, "Using user provided OnlineComponentProvider"), + await __PRIVATE_setOnlineComponentProvider(e, e._uninitializedComponentsProvider._online)) : (__PRIVATE_logDebug(un, "Using default OnlineComponentProvider"), + await __PRIVATE_setOnlineComponentProvider(e, new OnlineComponentProvider))), e._onlineComponents; +} + +function __PRIVATE_getPersistence(e) { + return __PRIVATE_ensureOfflineComponents(e).then((e => e.persistence)); +} + +function __PRIVATE_getLocalStore(e) { + return __PRIVATE_ensureOfflineComponents(e).then((e => e.localStore)); +} + +function __PRIVATE_getRemoteStore(e) { + return __PRIVATE_ensureOnlineComponents(e).then((e => e.remoteStore)); +} + +function __PRIVATE_getSyncEngine(e) { + return __PRIVATE_ensureOnlineComponents(e).then((e => e.syncEngine)); +} + +function __PRIVATE_getDatastore(e) { + return __PRIVATE_ensureOnlineComponents(e).then((e => e.datastore)); +} + +async function __PRIVATE_getEventManager(e) { + const t = await __PRIVATE_ensureOnlineComponents(e), n = t.eventManager; + return n.onListen = __PRIVATE_syncEngineListen.bind(null, t.syncEngine), n.onUnlisten = __PRIVATE_syncEngineUnlisten.bind(null, t.syncEngine), + n.onFirstRemoteStoreListen = __PRIVATE_triggerRemoteStoreListen.bind(null, t.syncEngine), + n.onLastRemoteStoreUnlisten = __PRIVATE_triggerRemoteStoreUnlisten.bind(null, t.syncEngine), + n; +} + +/** Enables the network connection and re-enqueues all pending operations. */ function __PRIVATE_firestoreClientEnableNetwork(e) { + return e.asyncQueue.enqueue((async () => { + const t = await __PRIVATE_getPersistence(e), n = await __PRIVATE_getRemoteStore(e); + return t.setNetworkEnabled(!0), function __PRIVATE_remoteStoreEnableNetwork(e) { + const t = __PRIVATE_debugCast(e); + return t.Ea.delete(0 /* OfflineCause.UserDisabled */), __PRIVATE_enableNetworkInternal(t); + }(n); + })); +} + +/** Disables the network connection. Pending operations will not complete. */ function __PRIVATE_firestoreClientDisableNetwork(e) { + return e.asyncQueue.enqueue((async () => { + const t = await __PRIVATE_getPersistence(e), n = await __PRIVATE_getRemoteStore(e); + return t.setNetworkEnabled(!1), async function __PRIVATE_remoteStoreDisableNetwork(e) { + const t = __PRIVATE_debugCast(e); + t.Ea.add(0 /* OfflineCause.UserDisabled */), await __PRIVATE_disableNetworkInternal(t), + // Set the OnlineState to Offline so get()s return from cache, etc. + t.Ra.set("Offline" /* OnlineState.Offline */); + }(n); + })); +} + +/** + * Returns a Promise that resolves when all writes that were pending at the time + * this method was called received server acknowledgement. An acknowledgement + * can be either acceptance or rejection. + */ function __PRIVATE_firestoreClientGetDocumentFromLocalCache(e, t) { + const n = new __PRIVATE_Deferred; + return e.asyncQueue.enqueueAndForget((async () => async function __PRIVATE_readDocumentFromCache(e, t, n) { + try { + const r = await function __PRIVATE_localStoreReadDocument(e, t) { + const n = __PRIVATE_debugCast(e); + return n.persistence.runTransaction("read document", "readonly", (e => n.localDocuments.getDocument(e, t))); + }(e, t); + r.isFoundDocument() ? n.resolve(r) : r.isNoDocument() ? n.resolve(null) : n.reject(new FirestoreError(L.UNAVAILABLE, "Failed to get document from cache. (However, this document may exist on the server. Run again without setting 'source' in the GetOptions to attempt to retrieve the document from the server.)")); + } catch (e) { + const r = __PRIVATE_wrapInUserErrorIfRecoverable(e, `Failed to get document '${t} from cache`); + n.reject(r); + } + } + /** + * Retrieves a latency-compensated document from the backend via a + * SnapshotListener. + */ (await __PRIVATE_getLocalStore(e), t, n))), n.promise; +} + +function __PRIVATE_firestoreClientGetDocumentViaSnapshotListener(e, t, n = {}) { + const r = new __PRIVATE_Deferred; + return e.asyncQueue.enqueueAndForget((async () => function __PRIVATE_readDocumentViaSnapshotListener(e, t, n, r, i) { + const s = new __PRIVATE_AsyncObserver({ + next: _ => { + // Mute and remove query first before passing event to user to avoid + // user actions affecting the now stale query. + s.Nu(), t.enqueueAndForget((() => __PRIVATE_eventManagerUnlisten(e, o))); + const a = _.docs.has(n); + !a && _.fromCache ? + // TODO(dimond): If we're online and the document doesn't + // exist then we resolve with a doc.exists set to false. If + // we're offline however, we reject the Promise in this + // case. Two options: 1) Cache the negative response from + // the server so we can deliver that even when you're + // offline 2) Actually reject the Promise in the online case + // if the document doesn't exist. + i.reject(new FirestoreError(L.UNAVAILABLE, "Failed to get document because the client is offline.")) : a && _.fromCache && r && "server" === r.source ? i.reject(new FirestoreError(L.UNAVAILABLE, 'Failed to get document from server. (However, this document does exist in the local cache. Run again without setting source to "server" to retrieve the cached document.)')) : i.resolve(_); + }, + error: e => i.reject(e) + }), o = new __PRIVATE_QueryListener(__PRIVATE_newQueryForPath(n.path), s, { + includeMetadataChanges: !0, + qa: !0 + }); + return __PRIVATE_eventManagerListen(e, o); + }(await __PRIVATE_getEventManager(e), e.asyncQueue, t, n, r))), r.promise; +} + +function __PRIVATE_firestoreClientGetDocumentsFromLocalCache(e, t) { + const n = new __PRIVATE_Deferred; + return e.asyncQueue.enqueueAndForget((async () => async function __PRIVATE_executeQueryFromCache(e, t, n) { + try { + const r = await __PRIVATE_localStoreExecuteQuery(e, t, + /* usePreviousResults= */ !0), i = new __PRIVATE_View(t, r.Qs), s = i.ru(r.documents), o = i.applyChanges(s, + /* limboResolutionEnabled= */ !1); + n.resolve(o.snapshot); + } catch (e) { + const r = __PRIVATE_wrapInUserErrorIfRecoverable(e, `Failed to execute query '${t} against cache`); + n.reject(r); + } + } + /** + * Retrieves a latency-compensated query snapshot from the backend via a + * SnapshotListener. + */ (await __PRIVATE_getLocalStore(e), t, n))), n.promise; +} + +function __PRIVATE_firestoreClientGetDocumentsViaSnapshotListener(e, t, n = {}) { + const r = new __PRIVATE_Deferred; + return e.asyncQueue.enqueueAndForget((async () => function __PRIVATE_executeQueryViaSnapshotListener(e, t, n, r, i) { + const s = new __PRIVATE_AsyncObserver({ + next: n => { + // Mute and remove query first before passing event to user to avoid + // user actions affecting the now stale query. + s.Nu(), t.enqueueAndForget((() => __PRIVATE_eventManagerUnlisten(e, o))), n.fromCache && "server" === r.source ? i.reject(new FirestoreError(L.UNAVAILABLE, 'Failed to get documents from server. (However, these documents may exist in the local cache. Run again without setting source to "server" to retrieve the cached documents.)')) : i.resolve(n); + }, + error: e => i.reject(e) + }), o = new __PRIVATE_QueryListener(n, s, { + includeMetadataChanges: !0, + qa: !0 + }); + return __PRIVATE_eventManagerListen(e, o); + }(await __PRIVATE_getEventManager(e), e.asyncQueue, t, n, r))), r.promise; +} + +function __PRIVATE_firestoreClientRunAggregateQuery(e, t, n) { + const r = new __PRIVATE_Deferred; + return e.asyncQueue.enqueueAndForget((async () => { + // Implement and call executeAggregateQueryViaSnapshotListener, similar + // to the implementation in firestoreClientGetDocumentsViaSnapshotListener + // above + try { + // TODO(b/277628384): check `canUseNetwork()` and handle multi-tab. + const i = await __PRIVATE_getDatastore(e); + r.resolve(async function __PRIVATE_invokeRunAggregationQueryRpc(e, t, n) { + const r = __PRIVATE_debugCast(e), {request: i, gt: s, parent: o} = __PRIVATE_toRunAggregationQueryRequest(r.serializer, __PRIVATE_queryToAggregateTarget(t), n); + r.connection.$o || delete i.parent; + const _ = (await r.Ho("RunAggregationQuery", r.serializer.databaseId, o, i, + /*expectedResponseCount=*/ 1)).filter((e => !!e.result)); + // Omit RunAggregationQueryResponse that only contain readTimes. + __PRIVATE_hardAssert(1 === _.length, 64727); + // Remap the short-form aliases that were sent to the server + // to the client-side aliases. Users will access the results + // using the client-side alias. + const a = _[0].result?.aggregateFields; + return Object.keys(a).reduce(((e, t) => (e[s[t]] = a[t], e)), {}); + }(i, t, n)); + } catch (e) { + r.reject(e); + } + })), r.promise; +} + +function __PRIVATE_firestoreClientAddSnapshotsInSyncListener(e, t) { + const n = new __PRIVATE_AsyncObserver(t); + return e.asyncQueue.enqueueAndForget((async () => function __PRIVATE_addSnapshotsInSyncListener(e, t) { + __PRIVATE_debugCast(e).Ca.add(t), + // Immediately fire an initial event, indicating all existing listeners + // are in-sync. + t.next(); + }(await __PRIVATE_getEventManager(e), n))), () => { + n.Nu(), e.asyncQueue.enqueueAndForget((async () => function __PRIVATE_removeSnapshotsInSyncListener(e, t) { + __PRIVATE_debugCast(e).Ca.delete(t); + }(await __PRIVATE_getEventManager(e), n))); + }; +} + +/** + * Takes an updateFunction in which a set of reads and writes can be performed + * atomically. In the updateFunction, the client can read and write values + * using the supplied transaction object. After the updateFunction, all + * changes will be committed. If a retryable error occurs (ex: some other + * client has changed any of the data referenced), then the updateFunction + * will be called again after a backoff. If the updateFunction still fails + * after all retries, then the transaction will be rejected. + * + * The transaction object passed to the updateFunction contains methods for + * accessing documents and collections. Unlike other datastore access, data + * accessed with the transaction will not reflect local changes that have not + * been committed. For this reason, it is required that all reads are + * performed before any writes. Transactions must be performed while online. + */ function __PRIVATE_firestoreClientLoadBundle(e, t, n, r) { + const i = function __PRIVATE_createBundleReader(e, t) { + let n; + n = "string" == typeof e ? __PRIVATE_newTextEncoder().encode(e) : e; + return function __PRIVATE_newBundleReader(e, t) { + return new __PRIVATE_BundleReaderImpl(e, t); + }(function __PRIVATE_toByteStreamReader(e, t) { + if (e instanceof Uint8Array) return __PRIVATE_toByteStreamReaderHelper(e, t); + if (e instanceof ArrayBuffer) return __PRIVATE_toByteStreamReaderHelper(new Uint8Array(e), t); + if (e instanceof ReadableStream) return e.getReader(); + throw new Error("Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream"); + }(n), t); + }(n, __PRIVATE_newSerializer(t)); + e.asyncQueue.enqueueAndForget((async () => { + __PRIVATE_syncEngineLoadBundle(await __PRIVATE_getSyncEngine(e), i, r); + })); +} + +function __PRIVATE_firestoreClientGetNamedQuery(e, t) { + return e.asyncQueue.enqueue((async () => function __PRIVATE_localStoreGetNamedQuery(e, t) { + const n = __PRIVATE_debugCast(e); + return n.persistence.runTransaction("Get named query", "readonly", (e => n.Ii.getNamedQuery(e, t))); + }(await __PRIVATE_getLocalStore(e), t))); +} + +function __PRIVATE_createBundleReaderSync(e, t) { + return function __PRIVATE_newBundleReaderSync(e, t) { + return new __PRIVATE_BundleReaderSyncImpl(e, t); + }(e, t); +} + +function __PRIVATE_firestoreClientSetIndexConfiguration(e, t) { + return e.asyncQueue.enqueue((async () => async function __PRIVATE_localStoreConfigureFieldIndexes(e, t) { + const n = __PRIVATE_debugCast(e), r = n.indexManager, i = []; + return n.persistence.runTransaction("Configure indexes", "readwrite", (e => r.getFieldIndexes(e).next((n => + /** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Compares two array for equality using comparator. The method computes the + * intersection and invokes `onAdd` for every element that is in `after` but not + * `before`. `onRemove` is invoked for every element in `before` but missing + * from `after`. + * + * The method creates a copy of both `before` and `after` and runs in O(n log + * n), where n is the size of the two lists. + * + * @param before - The elements that exist in the original array. + * @param after - The elements to diff against the original array. + * @param comparator - The comparator for the elements in before and after. + * @param onAdd - A function to invoke for every element that is part of ` + * after` but not `before`. + * @param onRemove - A function to invoke for every element that is part of + * `before` but not `after`. + */ + function __PRIVATE_diffArrays(e, t, n, r, i) { + e = [ ...e ], t = [ ...t ], e.sort(n), t.sort(n); + const s = e.length, o = t.length; + let _ = 0, a = 0; + for (;_ < o && a < s; ) { + const s = n(e[a], t[_]); + s < 0 ? + // The element was removed if the next element in our ordered + // walkthrough is only in `before`. + i(e[a++]) : s > 0 ? + // The element was added if the next element in our ordered walkthrough + // is only in `after`. + r(t[_++]) : (_++, a++); + } + for (;_ < o; ) r(t[_++]); + for (;a < s; ) i(e[a++]); + } + /** + * Verifies equality for an array of primitives. + * + * @private + * @internal + * @param left Array of primitives. + * @param right Array of primitives. + * @return True if arrays are equal. + */ (n, t, __PRIVATE_fieldIndexSemanticComparator, (t => { + i.push(r.addFieldIndex(e, t)); + }), (t => { + i.push(r.deleteFieldIndex(e, t)); + })))).next((() => PersistencePromise.waitFor(i))))); + }(await __PRIVATE_getLocalStore(e), t))); +} + +function __PRIVATE_firestoreClientSetPersistentCacheIndexAutoCreationEnabled(e, t) { + return e.asyncQueue.enqueue((async () => function __PRIVATE_localStoreSetIndexAutoCreationEnabled(e, t) { + __PRIVATE_debugCast(e).Fs.Vs = t; + }(await __PRIVATE_getLocalStore(e), t))); +} + +function __PRIVATE_firestoreClientDeleteAllFieldIndexes(e) { + return e.asyncQueue.enqueue((async () => function __PRIVATE_localStoreDeleteAllFieldIndexes(e) { + const t = __PRIVATE_debugCast(e), n = t.indexManager; + return t.persistence.runTransaction("Delete All Indexes", "readwrite", (e => n.deleteAllFieldIndexes(e))); + }(await __PRIVATE_getLocalStore(e)))); +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Compares two `ExperimentalLongPollingOptions` objects for equality. + */ +/** + * Creates and returns a new `ExperimentalLongPollingOptions` with the same + * option values as the given instance. + */ +function __PRIVATE_cloneLongPollingOptions(e) { + const t = {}; + return void 0 !== e.timeoutSeconds && (t.timeoutSeconds = e.timeoutSeconds), t; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const cn = new Map; + +/** + * An instance map that ensures only one Datastore exists per Firestore + * instance. + */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// settings() defaults: +const ln = "firestore.googleapis.com", hn = !0; + +/** + * A concrete type describing all the values that can be applied via a + * user-supplied `FirestoreSettings` object. This is a separate type so that + * defaults can be supplied and the value can be checked for equality. + */ +class FirestoreSettingsImpl { + constructor(e) { + if (void 0 === e.host) { + if (void 0 !== e.ssl) throw new FirestoreError(L.INVALID_ARGUMENT, "Can't provide ssl option if host option is not set"); + this.host = ln, this.ssl = hn; + } else this.host = e.host, this.ssl = e.ssl ?? hn; + if (this.isUsingEmulator = void 0 !== e.emulatorOptions, this.credentials = e.credentials, + this.ignoreUndefinedProperties = !!e.ignoreUndefinedProperties, this.localCache = e.localCache, + void 0 === e.cacheSizeBytes) this.cacheSizeBytes = Lt; else { + if (-1 !== e.cacheSizeBytes && e.cacheSizeBytes < qt) throw new FirestoreError(L.INVALID_ARGUMENT, "cacheSizeBytes must be at least 1048576"); + this.cacheSizeBytes = e.cacheSizeBytes; + } + __PRIVATE_validateIsNotUsedTogether("experimentalForceLongPolling", e.experimentalForceLongPolling, "experimentalAutoDetectLongPolling", e.experimentalAutoDetectLongPolling), + this.experimentalForceLongPolling = !!e.experimentalForceLongPolling, this.experimentalForceLongPolling ? this.experimentalAutoDetectLongPolling = !1 : void 0 === e.experimentalAutoDetectLongPolling ? this.experimentalAutoDetectLongPolling = true : + // For backwards compatibility, coerce the value to boolean even though + // the TypeScript compiler has narrowed the type to boolean already. + // noinspection PointlessBooleanExpressionJS + this.experimentalAutoDetectLongPolling = !!e.experimentalAutoDetectLongPolling, + this.experimentalLongPollingOptions = __PRIVATE_cloneLongPollingOptions(e.experimentalLongPollingOptions ?? {}), + function __PRIVATE_validateLongPollingOptions(e) { + if (void 0 !== e.timeoutSeconds) { + if (isNaN(e.timeoutSeconds)) throw new FirestoreError(L.INVALID_ARGUMENT, `invalid long polling timeout: ${e.timeoutSeconds} (must not be NaN)`); + if (e.timeoutSeconds < 5) throw new FirestoreError(L.INVALID_ARGUMENT, `invalid long polling timeout: ${e.timeoutSeconds} (minimum allowed value is 5)`); + if (e.timeoutSeconds > 30) throw new FirestoreError(L.INVALID_ARGUMENT, `invalid long polling timeout: ${e.timeoutSeconds} (maximum allowed value is 30)`); + } + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ (this.experimentalLongPollingOptions), this.useFetchStreams = !!e.useFetchStreams; + } + isEqual(e) { + return this.host === e.host && this.ssl === e.ssl && this.credentials === e.credentials && this.cacheSizeBytes === e.cacheSizeBytes && this.experimentalForceLongPolling === e.experimentalForceLongPolling && this.experimentalAutoDetectLongPolling === e.experimentalAutoDetectLongPolling && function __PRIVATE_longPollingOptionsEqual(e, t) { + return e.timeoutSeconds === t.timeoutSeconds; + }(this.experimentalLongPollingOptions, e.experimentalLongPollingOptions) && this.ignoreUndefinedProperties === e.ignoreUndefinedProperties && this.useFetchStreams === e.useFetchStreams; + } +} + +class Firestore$1 { + /** @hideconstructor */ + constructor(e, t, n, r) { + this._authCredentials = e, this._appCheckCredentials = t, this._databaseId = n, + this._app = r, + /** + * Whether it's a Firestore or Firestore Lite instance. + */ + this.type = "firestore-lite", this._persistenceKey = "(lite)", this._settings = new FirestoreSettingsImpl({}), + this._settingsFrozen = !1, this._emulatorOptions = {}, + // A task that is assigned when the terminate() is invoked and resolved when + // all components have shut down. Otherwise, Firestore is not terminated, + // which can mean either the FirestoreClient is in the process of starting, + // or restarting. + this._terminateTask = "notTerminated"; + } + /** + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service + * instance. + */ get app() { + if (!this._app) throw new FirestoreError(L.FAILED_PRECONDITION, "Firestore was not initialized using the Firebase SDK. 'app' is not available"); + return this._app; + } + get _initialized() { + return this._settingsFrozen; + } + get _terminated() { + return "notTerminated" !== this._terminateTask; + } + _setSettings(e) { + if (this._settingsFrozen) throw new FirestoreError(L.FAILED_PRECONDITION, "Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object."); + this._settings = new FirestoreSettingsImpl(e), this._emulatorOptions = e.emulatorOptions || {}, + void 0 !== e.credentials && (this._authCredentials = function __PRIVATE_makeAuthCredentialsProvider(e) { + if (!e) return new __PRIVATE_EmptyAuthCredentialsProvider; + switch (e.type) { + case "firstParty": + return new __PRIVATE_FirstPartyAuthCredentialsProvider(e.sessionIndex || "0", e.iamToken || null, e.authTokenFactory || null); + + case "provider": + return e.client; + + default: + throw new FirestoreError(L.INVALID_ARGUMENT, "makeAuthCredentialsProvider failed due to invalid credential type"); + } + }(e.credentials)); + } + _getSettings() { + return this._settings; + } + _getEmulatorOptions() { + return this._emulatorOptions; + } + _freezeSettings() { + return this._settingsFrozen = !0, this._settings; + } + _delete() { + // The `_terminateTask` must be assigned future that completes when + // terminate is complete. The existence of this future puts SDK in state + // that will not accept further API interaction. + return "notTerminated" === this._terminateTask && (this._terminateTask = this._terminate()), + this._terminateTask; + } + async _restart() { + // The `_terminateTask` must equal 'notTerminated' after restart to + // signal that client is in a state that accepts API calls. + "notTerminated" === this._terminateTask ? await this._terminate() : this._terminateTask = "notTerminated"; + } + /** Returns a JSON-serializable representation of this `Firestore` instance. */ toJSON() { + return { + app: this._app, + databaseId: this._databaseId, + settings: this._settings + }; + } + /** + * Terminates all components used by this client. Subclasses can override + * this method to clean up their own dependencies, but must also call this + * method. + * + * Only ever called once. + */ _terminate() { + /** + * Removes all components associated with the provided instance. Must be called + * when the `Firestore` instance is terminated. + */ + return function __PRIVATE_removeComponents(e) { + const t = cn.get(e); + t && (__PRIVATE_logDebug("ComponentProvider", "Removing Datastore"), cn.delete(e), + t.terminate()); + }(this), Promise.resolve(); + } +} + +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ function connectFirestoreEmulator(e, t, n, r = {}) { + e = __PRIVATE_cast(e, Firestore$1); + const i = d(t), s = e._getSettings(), o = { + ...s, + emulatorOptions: e._getEmulatorOptions() + }, _ = `${t}:${n}`; + i && (A(`https://${_}`), R("Firestore", !0)), s.host !== ln && s.host !== _ && __PRIVATE_logWarn("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."); + const a = { + ...s, + host: _, + ssl: i, + emulatorOptions: r + }; + // No-op if the new configuration matches the current configuration. This supports SSR + // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice. + if (!V(a, o) && (e._setSettings(a), r.mockUserToken)) { + let t, n; + if ("string" == typeof r.mockUserToken) t = r.mockUserToken, n = User.MOCK_USER; else { + // Let createMockUserToken validate first (catches common mistakes like + // invalid field "uid" and missing field "sub" / "user_id".) + t = m(r.mockUserToken, e._app?.options.projectId); + const i = r.mockUserToken.sub || r.mockUserToken.user_id; + if (!i) throw new FirestoreError(L.INVALID_ARGUMENT, "mockUserToken must contain 'sub' or 'user_id' field!"); + n = new User(i); + } + e._authCredentials = new __PRIVATE_EmulatorAuthCredentialsProvider(new __PRIVATE_OAuthToken(t, n)); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `Query` refers to a query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ class Query { + // This is the lite version of the Query class in the main SDK. + /** @hideconstructor protected */ + constructor(e, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + t, n) { + this.converter = t, this._query = n, + /** The type of this Firestore reference. */ + this.type = "query", this.firestore = e; + } + withConverter(e) { + return new Query(this.firestore, e, this._query); + } +} + +/** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. + */ class DocumentReference { + /** @hideconstructor */ + constructor(e, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + t, n) { + this.converter = t, this._key = n, + /** The type of this Firestore reference. */ + this.type = "document", this.firestore = e; + } + get _path() { + return this._key.path; + } + /** + * The document's identifier within its collection. + */ get id() { + return this._key.path.lastSegment(); + } + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ get path() { + return this._key.path.canonicalString(); + } + /** + * The collection this `DocumentReference` belongs to. + */ get parent() { + return new CollectionReference(this.firestore, this.converter, this._key.path.popLast()); + } + withConverter(e) { + return new DocumentReference(this.firestore, e, this._key); + } + /** + * Returns a JSON-serializable representation of this `DocumentReference` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + type: DocumentReference._jsonSchemaVersion, + referencePath: this._key.toString() + }; + } + static fromJSON(e, t, n) { + if (__PRIVATE_validateJSON(t, DocumentReference._jsonSchema)) return new DocumentReference(e, n || null, new DocumentKey(ResourcePath.fromString(t.referencePath))); + } +} + +DocumentReference._jsonSchemaVersion = "firestore/documentReference/1.0", DocumentReference._jsonSchema = { + type: property("string", DocumentReference._jsonSchemaVersion), + referencePath: property("string") +}; + +/** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using {@link (query:1)}). + */ +class CollectionReference extends Query { + /** @hideconstructor */ + constructor(e, t, n) { + super(e, t, __PRIVATE_newQueryForPath(n)), this._path = n, + /** The type of this Firestore reference. */ + this.type = "collection"; + } + /** The collection's identifier. */ get id() { + return this._query.path.lastSegment(); + } + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ get path() { + return this._query.path.canonicalString(); + } + /** + * A reference to the containing `DocumentReference` if this is a + * subcollection. If this isn't a subcollection, the reference is null. + */ get parent() { + const e = this._path.popLast(); + return e.isEmpty() ? null : new DocumentReference(this.firestore, + /* converter= */ null, new DocumentKey(e)); + } + withConverter(e) { + return new CollectionReference(this.firestore, e, this._path); + } +} + +function collection(e, t, ...n) { + if (e = f(e), __PRIVATE_validateNonEmptyArgument("collection", "path", t), e instanceof Firestore$1) { + const r = ResourcePath.fromString(t, ...n); + return __PRIVATE_validateCollectionPath(r), new CollectionReference(e, /* converter= */ null, r); + } + { + if (!(e instanceof DocumentReference || e instanceof CollectionReference)) throw new FirestoreError(L.INVALID_ARGUMENT, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore"); + const r = e._path.child(ResourcePath.fromString(t, ...n)); + return __PRIVATE_validateCollectionPath(r), new CollectionReference(e.firestore, + /* converter= */ null, r); + } +} + +// TODO(firestorelite): Consider using ErrorFactory - +// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106 +/** + * Creates and returns a new `Query` instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given `collectionId`. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param collectionId - Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `Query`. + */ function collectionGroup(e, t) { + if (e = __PRIVATE_cast(e, Firestore$1), __PRIVATE_validateNonEmptyArgument("collectionGroup", "collection id", t), + t.indexOf("/") >= 0) throw new FirestoreError(L.INVALID_ARGUMENT, `Invalid collection ID '${t}' passed to function collectionGroup(). Collection IDs must not contain '/'.`); + return new Query(e, + /* converter= */ null, function __PRIVATE_newQueryForCollectionGroup(e) { + return new __PRIVATE_QueryImpl(ResourcePath.emptyPath(), e); + }(t)); +} + +function doc(e, t, ...n) { + if (e = f(e), + // We allow omission of 'pathString' but explicitly prohibit passing in both + // 'undefined' and 'null'. + 1 === arguments.length && (t = __PRIVATE_AutoId.newId()), __PRIVATE_validateNonEmptyArgument("doc", "path", t), + e instanceof Firestore$1) { + const r = ResourcePath.fromString(t, ...n); + return __PRIVATE_validateDocumentPath(r), new DocumentReference(e, + /* converter= */ null, new DocumentKey(r)); + } + { + if (!(e instanceof DocumentReference || e instanceof CollectionReference)) throw new FirestoreError(L.INVALID_ARGUMENT, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore"); + const r = e._path.child(ResourcePath.fromString(t, ...n)); + return __PRIVATE_validateDocumentPath(r), new DocumentReference(e.firestore, e instanceof CollectionReference ? e.converter : null, new DocumentKey(r)); + } +} + +/** + * Returns true if the provided references are equal. + * + * @param left - A reference to compare. + * @param right - A reference to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ function refEqual(e, t) { + return e = f(e), t = f(t), (e instanceof DocumentReference || e instanceof CollectionReference) && (t instanceof DocumentReference || t instanceof CollectionReference) && (e.firestore === t.firestore && e.path === t.path && e.converter === t.converter); +} + +/** + * Returns true if the provided queries point to the same collection and apply + * the same constraints. + * + * @param left - A `Query` to compare. + * @param right - A `Query` to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ function queryEqual(e, t) { + return e = f(e), t = f(t), e instanceof Query && t instanceof Query && (e.firestore === t.firestore && __PRIVATE_queryEquals(e._query, t._query) && e.converter === t.converter); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const Pn = "AsyncQueue"; + +class __PRIVATE_AsyncQueueImpl { + constructor(e = Promise.resolve()) { + // A list of retryable operations. Retryable operations are run in order and + // retried with backoff. + this.Xu = [], + // Is this AsyncQueue being shut down? Once it is set to true, it will not + // be changed again. + this.ec = !1, + // Operations scheduled to be queued in the future. Operations are + // automatically removed after they are run or canceled. + this.tc = [], + // visible for testing + this.nc = null, + // Flag set while there's an outstanding AsyncQueue operation, used for + // assertion sanity-checks. + this.rc = !1, + // Enabled during shutdown on Safari to prevent future access to IndexedDB. + this.sc = !1, + // List of TimerIds to fast-forward delays for. + this.oc = [], + // Backoff timer used to schedule retries for retryable operations + this.M_ = new __PRIVATE_ExponentialBackoff(this, "async_queue_retry" /* TimerId.AsyncQueueRetry */), + // Visibility handler that triggers an immediate retry of all retryable + // operations. Meant to speed up recovery when we regain file system access + // after page comes into foreground. + this._c = () => { + const e = getDocument(); + e && __PRIVATE_logDebug(Pn, "Visibility state changed to " + e.visibilityState), + this.M_.w_(); + }, this.ac = e; + const t = getDocument(); + t && "function" == typeof t.addEventListener && t.addEventListener("visibilitychange", this._c); + } + get isShuttingDown() { + return this.ec; + } + /** + * Adds a new operation to the queue without waiting for it to complete (i.e. + * we ignore the Promise result). + */ enqueueAndForget(e) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.enqueue(e); + } + enqueueAndForgetEvenWhileRestricted(e) { + this.uc(), + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.cc(e); + } + enterRestrictedMode(e) { + if (!this.ec) { + this.ec = !0, this.sc = e || !1; + const t = getDocument(); + t && "function" == typeof t.removeEventListener && t.removeEventListener("visibilitychange", this._c); + } + } + enqueue(e) { + if (this.uc(), this.ec) + // Return a Promise which never resolves. + return new Promise((() => {})); + // Create a deferred Promise that we can return to the callee. This + // allows us to return a "hanging Promise" only to the callee and still + // advance the queue even when the operation is not run. + const t = new __PRIVATE_Deferred; + return this.cc((() => this.ec && this.sc ? Promise.resolve() : (e().then(t.resolve, t.reject), + t.promise))).then((() => t.promise)); + } + enqueueRetryable(e) { + this.enqueueAndForget((() => (this.Xu.push(e), this.lc()))); + } + /** + * Runs the next operation from the retryable queue. If the operation fails, + * reschedules with backoff. + */ async lc() { + if (0 !== this.Xu.length) { + try { + await this.Xu[0](), this.Xu.shift(), this.M_.reset(); + } catch (e) { + if (!__PRIVATE_isIndexedDbTransactionError(e)) throw e; + // Failure will be handled by AsyncQueue + __PRIVATE_logDebug(Pn, "Operation failed with retryable error: " + e); + } + this.Xu.length > 0 && + // If there are additional operations, we re-schedule `retryNextOp()`. + // This is necessary to run retryable operations that failed during + // their initial attempt since we don't know whether they are already + // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1` + // needs to be re-run, we will run `op1`, `op1`, `op2` using the + // already enqueued calls to `retryNextOp()`. `op3()` will then run in the + // call scheduled here. + // Since `backoffAndRun()` cancels an existing backoff and schedules a + // new backoff on every call, there is only ever a single additional + // operation in the queue. + this.M_.p_((() => this.lc())); + } + } + cc(e) { + const t = this.ac.then((() => (this.rc = !0, e().catch((e => { + this.nc = e, this.rc = !1; + // Re-throw the error so that this.tail becomes a rejected Promise and + // all further attempts to chain (via .then) will just short-circuit + // and return the rejected Promise. + throw __PRIVATE_logError("INTERNAL UNHANDLED ERROR: ", __PRIVATE_getMessageOrStack(e)), + e; + })).then((e => (this.rc = !1, e)))))); + return this.ac = t, t; + } + enqueueAfterDelay(e, t, n) { + this.uc(), + // Fast-forward delays for timerIds that have been overridden. + this.oc.indexOf(e) > -1 && (t = 0); + const r = DelayedOperation.createAndSchedule(this, e, t, n, (e => this.hc(e))); + return this.tc.push(r), r; + } + uc() { + this.nc && fail(47125, { + Pc: __PRIVATE_getMessageOrStack(this.nc) + }); + } + verifyOperationInProgress() {} + /** + * Waits until all currently queued tasks are finished executing. Delayed + * operations are not run. + */ async Tc() { + // Operations in the queue prior to draining may have enqueued additional + // operations. Keep draining the queue until the tail is no longer advanced, + // which indicates that no more new operations were enqueued and that all + // operations were executed. + let e; + do { + e = this.ac, await e; + } while (e !== this.ac); + } + /** + * For Tests: Determine if a delayed operation with a particular TimerId + * exists. + */ Ic(e) { + for (const t of this.tc) if (t.timerId === e) return !0; + return !1; + } + /** + * For Tests: Runs some or all delayed operations early. + * + * @param lastTimerId - Delayed operations up to and including this TimerId + * will be drained. Pass TimerId.All to run all delayed operations. + * @returns a Promise that resolves once all operations have been run. + */ Ec(e) { + // Note that draining may generate more delayed ops, so we do that first. + return this.Tc().then((() => { + // Run ops in the same order they'd run if they ran naturally. + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ + this.tc.sort(((e, t) => e.targetTimeMs - t.targetTimeMs)); + for (const t of this.tc) if (t.skipDelay(), "all" /* TimerId.All */ !== e && t.timerId === e) break; + return this.Tc(); + })); + } + /** + * For Tests: Skip all subsequent delays for a timer id. + */ dc(e) { + this.oc.push(e); + } + /** Called once a DelayedOperation is run or canceled. */ hc(e) { + // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small. + const t = this.tc.indexOf(e); + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ this.tc.splice(t, 1); + } +} + +/** + * Chrome includes Error.message in Error.stack. Other browsers do not. + * This returns expected output of message + stack when available. + * @param error - Error or FirestoreError + */ function __PRIVATE_getMessageOrStack(e) { + let t = e.message || ""; + return e.stack && (t = e.stack.includes(e.message) ? e.stack : e.message + "\n" + e.stack), + t; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_isPartialObserver(e) { + /** + * Returns true if obj is an object and contains at least one of the specified + * methods. + */ + return function __PRIVATE_implementsAnyMethods(e, t) { + if ("object" != typeof e || null === e) return !1; + const n = e; + for (const e of t) if (e in n && "function" == typeof n[e]) return !0; + return !1; + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Represents the task of loading a Firestore bundle. It provides progress of bundle + * loading, as well as task completion and error events. + * + * The API is compatible with `Promise`. + */ (e, [ "next", "error", "complete" ]); +} + +class LoadBundleTask { + constructor() { + this._progressObserver = {}, this._taskCompletionResolver = new __PRIVATE_Deferred, + this._lastProgress = { + taskState: "Running", + totalBytes: 0, + totalDocuments: 0, + bytesLoaded: 0, + documentsLoaded: 0 + }; + } + /** + * Registers functions to listen to bundle loading progress events. + * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur + * each time a Firestore document is loaded from the bundle. + * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the + * error, and there should be no more updates after this. + * @param complete - Called when the loading task is complete. + */ onProgress(e, t, n) { + this._progressObserver = { + next: e, + error: t, + complete: n + }; + } + /** + * Implements the `Promise.catch` interface. + * + * @param onRejected - Called when an error occurs during bundle loading. + */ catch(e) { + return this._taskCompletionResolver.promise.catch(e); + } + /** + * Implements the `Promise.then` interface. + * + * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update. + * The update will always have its `taskState` set to `"Success"`. + * @param onRejected - Called when an error occurs during bundle loading. + */ then(e, t) { + return this._taskCompletionResolver.promise.then(e, t); + } + /** + * Notifies all observers that bundle loading has completed, with a provided + * `LoadBundleTaskProgress` object. + * + * @private + */ _completeWith(e) { + this._updateProgress(e), this._progressObserver.complete && this._progressObserver.complete(), + this._taskCompletionResolver.resolve(e); + } + /** + * Notifies all observers that bundle loading has failed, with a provided + * `Error` as the reason. + * + * @private + */ _failWith(e) { + this._lastProgress.taskState = "Error", this._progressObserver.next && this._progressObserver.next(this._lastProgress), + this._progressObserver.error && this._progressObserver.error(e), this._taskCompletionResolver.reject(e); + } + /** + * Notifies a progress update of loading a bundle. + * @param progress - The new progress. + * + * @private + */ _updateProgress(e) { + this._lastProgress = e, this._progressObserver.next && this._progressObserver.next(e); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Constant used to indicate the LRU garbage collection should be disabled. + * Set this value as the `cacheSizeBytes` on the settings passed to the + * {@link Firestore} instance. + */ const Tn = -1; + +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ class Firestore extends Firestore$1 { + /** @hideconstructor */ + constructor(e, t, n, r) { + super(e, t, n, r), + /** + * Whether it's a {@link Firestore} or Firestore Lite instance. + */ + this.type = "firestore", this._queue = new __PRIVATE_AsyncQueueImpl, this._persistenceKey = r?.name || "[DEFAULT]"; + } + async _terminate() { + if (this._firestoreClient) { + const e = this._firestoreClient.terminate(); + this._queue = new __PRIVATE_AsyncQueueImpl(e), this._firestoreClient = void 0, await e; + } + } +} + +/** + * Initializes a new instance of {@link Firestore} with the provided settings. + * Can only be called before any other function, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will + * be associated. + * @param settings - A settings object to configure the {@link Firestore} instance. + * @param databaseId - The name of the database. + * @returns A newly initialized {@link Firestore} instance. + */ function initializeFirestore(e, t, n) { + n || (n = Tt); + const r = _getProvider(e, "firestore"); + if (r.isInitialized(n)) { + const e = r.getImmediate({ + identifier: n + }), i = r.getOptions(n); + if (V(i, t)) return e; + throw new FirestoreError(L.FAILED_PRECONDITION, "initializeFirestore() has already been called with different options. To avoid this error, call initializeFirestore() with the same options as when it was originally called, or call getFirestore() to return the already initialized instance."); + } + if (void 0 !== t.cacheSizeBytes && void 0 !== t.localCache) throw new FirestoreError(L.INVALID_ARGUMENT, "cache and cacheSizeBytes cannot be specified at the same time as cacheSizeBytes willbe deprecated. Instead, specify the cache size in the cache object"); + if (void 0 !== t.cacheSizeBytes && -1 !== t.cacheSizeBytes && t.cacheSizeBytes < qt) throw new FirestoreError(L.INVALID_ARGUMENT, "cacheSizeBytes must be at least 1048576"); + // Workaround to get cookies in Firebase Studio + return t.host && d(t.host) && A(t.host), r.initialize({ + options: t, + instanceIdentifier: n + }); +} + +function getFirestore(e, n) { + const r = "object" == typeof e ? e : t(), i = "string" == typeof e ? e : n || Tt, s = _getProvider(r, "firestore").getImmediate({ + identifier: i + }); + if (!s._initialized) { + const e = g("firestore"); + e && connectFirestoreEmulator(s, ...e); + } + return s; +} + +/** + * @internal + */ function ensureFirestoreConfigured(e) { + if (e._terminated) throw new FirestoreError(L.FAILED_PRECONDITION, "The client has already been terminated."); + return e._firestoreClient || __PRIVATE_configureFirestore(e), e._firestoreClient; +} + +function __PRIVATE_configureFirestore(e) { + const t = e._freezeSettings(), n = function __PRIVATE_makeDatabaseInfo(e, t, n, r) { + return new DatabaseInfo(e, t, n, r.host, r.ssl, r.experimentalForceLongPolling, r.experimentalAutoDetectLongPolling, __PRIVATE_cloneLongPollingOptions(r.experimentalLongPollingOptions), r.useFetchStreams, r.isUsingEmulator); + }(e._databaseId, e._app?.options.appId || "", e._persistenceKey, t); + e._componentsProvider || t.localCache?._offlineComponentProvider && t.localCache?._onlineComponentProvider && (e._componentsProvider = { + _offline: t.localCache._offlineComponentProvider, + _online: t.localCache._onlineComponentProvider + }), e._firestoreClient = new FirestoreClient(e._authCredentials, e._appCheckCredentials, e._queue, n, e._componentsProvider && function __PRIVATE_buildComponentProvider(e) { + const t = e?._online.build(); + return { + _offline: e?._offline.build(t), + _online: t + }; + } + /** + * Attempts to enable persistent storage, if possible. + * + * On failure, `enableIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. + * + * * failed-precondition: The app is already open in another browser tab. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. + * + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. + * + * Note: `enableIndexedDbPersistence()` must be called before any other functions + * (other than {@link initializeFirestore}, {@link (getFirestore:1)} or + * {@link clearIndexedDbPersistence}. + * + * Persistence cannot be used in a Node.js environment. + * + * @param firestore - The {@link Firestore} instance to enable persistence for. + * @param persistenceSettings - Optional settings object to configure + * persistence. + * @returns A `Promise` that represents successfully enabling persistent storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on IndexedDb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. + */ (e._componentsProvider)); +} + +function enableIndexedDbPersistence(e, t) { + __PRIVATE_logWarn("enableIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead."); + const n = e._freezeSettings(); + return __PRIVATE_setPersistenceProviders(e, OnlineComponentProvider.provider, { + build: e => new __PRIVATE_IndexedDbOfflineComponentProvider(e, n.cacheSizeBytes, t?.forceOwnership) + }), Promise.resolve(); +} + +/** + * Attempts to enable multi-tab persistent storage, if possible. If enabled + * across all tabs, all operations share access to local persistence, including + * shared execution of queries and latency-compensated local document updates + * across all connected instances. + * + * On failure, `enableMultiTabIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. + * + * * failed-precondition: The app is already open in another browser tab and + * multi-tab is not enabled. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. + * + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. + * + * @param firestore - The {@link Firestore} instance to enable persistence for. + * @returns A `Promise` that represents successfully enabling persistent + * storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on indexeddb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. + */ async function enableMultiTabIndexedDbPersistence(e) { + __PRIVATE_logWarn("enableMultiTabIndexedDbPersistence() will be deprecated in the future, you can use `FirestoreSettings.cache` instead."); + const t = e._freezeSettings(); + __PRIVATE_setPersistenceProviders(e, OnlineComponentProvider.provider, { + build: e => new __PRIVATE_MultiTabOfflineComponentProvider(e, t.cacheSizeBytes) + }); +} + +/** + * Registers both the `OfflineComponentProvider` and `OnlineComponentProvider`. + * If the operation fails with a recoverable error (see + * `canRecoverFromIndexedDbError()` below), the returned Promise is rejected + * but the client remains usable. + */ function __PRIVATE_setPersistenceProviders(e, t, n) { + if ((e = __PRIVATE_cast(e, Firestore))._firestoreClient || e._terminated) throw new FirestoreError(L.FAILED_PRECONDITION, "Firestore has already been started and persistence can no longer be enabled. You can only enable persistence before calling any other methods on a Firestore object."); + if (e._componentsProvider || e._getSettings().localCache) throw new FirestoreError(L.FAILED_PRECONDITION, "SDK cache is already specified."); + e._componentsProvider = { + _online: t, + _offline: n + }, __PRIVATE_configureFirestore(e); +} + +/** + * Clears the persistent storage. This includes pending writes and cached + * documents. + * + * Must be called while the {@link Firestore} instance is not started (after the app is + * terminated or when the app is first initialized). On startup, this function + * must be called before other functions (other than {@link + * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore} + * instance is still running, the promise will be rejected with the error code + * of `failed-precondition`. + * + * Note: `clearIndexedDbPersistence()` is primarily intended to help write + * reliable tests that use Cloud Firestore. It uses an efficient mechanism for + * dropping existing data but does not attempt to securely overwrite or + * otherwise make cached data unrecoverable. For applications that are sensitive + * to the disclosure of cached data in between user sessions, we strongly + * recommend not enabling persistence at all. + * + * @param firestore - The {@link Firestore} instance to clear persistence for. + * @returns A `Promise` that is resolved when the persistent storage is + * cleared. Otherwise, the promise is rejected with an error. + */ function clearIndexedDbPersistence(e) { + if (e._initialized && !e._terminated) throw new FirestoreError(L.FAILED_PRECONDITION, "Persistence can only be cleared before a Firestore instance is initialized or after it is terminated."); + const t = new __PRIVATE_Deferred; + return e._queue.enqueueAndForgetEvenWhileRestricted((async () => { + try { + await async function __PRIVATE_indexedDbClearPersistence(e) { + if (!__PRIVATE_SimpleDb.v()) return Promise.resolve(); + const t = e + Wt; + await __PRIVATE_SimpleDb.delete(t); + }(__PRIVATE_indexedDbStoragePrefix(e._databaseId, e._persistenceKey)), t.resolve(); + } catch (e) { + t.reject(e); + } + })), t.promise; +} + +/** + * Waits until all currently pending writes for the active user have been + * acknowledged by the backend. + * + * The returned promise resolves immediately if there are no outstanding writes. + * Otherwise, the promise waits for all previously issued writes (including + * those written in a previous app session), but it does not wait for writes + * that were added after the function is called. If you want to wait for + * additional writes, call `waitForPendingWrites()` again. + * + * Any outstanding `waitForPendingWrites()` promises are rejected during user + * changes. + * + * @returns A `Promise` which resolves when all currently pending writes have been + * acknowledged by the backend. + */ function waitForPendingWrites(e) { + return function __PRIVATE_firestoreClientWaitForPendingWrites(e) { + const t = new __PRIVATE_Deferred; + return e.asyncQueue.enqueueAndForget((async () => __PRIVATE_syncEngineRegisterPendingWritesCallback(await __PRIVATE_getSyncEngine(e), t))), + t.promise; + }(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore))); +} + +/** + * Re-enables use of the network for this {@link Firestore} instance after a prior + * call to {@link disableNetwork}. + * + * @returns A `Promise` that is resolved once the network has been enabled. + */ function enableNetwork(e) { + return __PRIVATE_firestoreClientEnableNetwork(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore))); +} + +/** + * Disables network usage for this instance. It can be re-enabled via {@link + * enableNetwork}. While the network is disabled, any snapshot listeners, + * `getDoc()` or `getDocs()` calls will return results from cache, and any write + * operations will be queued until the network is restored. + * + * @returns A `Promise` that is resolved once the network has been disabled. + */ function disableNetwork(e) { + return __PRIVATE_firestoreClientDisableNetwork(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore))); +} + +/** + * Terminates the provided {@link Firestore} instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` function + * may be used. Any other function will throw a `FirestoreError`. + * + * To restart after termination, create a new instance of FirebaseFirestore with + * {@link (getFirestore:1)}. + * + * Termination does not cancel any pending writes, and any promises that are + * awaiting a response from the server will not be resolved. If you have + * persistence enabled, the next time you start this instance, it will resume + * sending these writes to the server. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all + * of its resources or in combination with `clearIndexedDbPersistence()` to + * ensure that all local state is destroyed between test runs. + * + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ function terminate(e) { + return n(e.app, "firestore", e._databaseId.database), e._delete(); +} + +/** + * Loads a Firestore bundle into the local cache. + * + * @param firestore - The {@link Firestore} instance to load bundles for. + * @param bundleData - An object representing the bundle to be loaded. Valid + * objects are `ArrayBuffer`, `ReadableStream` or `string`. + * + * @returns A `LoadBundleTask` object, which notifies callers with progress + * updates, and completion or error events. It can be used as a + * `Promise`. + */ function loadBundle(e, t) { + const n = ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)), r = new LoadBundleTask; + return __PRIVATE_firestoreClientLoadBundle(n, e._databaseId, t, r), r; +} + +/** + * Reads a Firestore {@link Query} from local cache, identified by the given + * name. + * + * The named queries are packaged into bundles on the server side (along + * with resulting documents), and loaded to local cache using `loadBundle`. Once + * in local cache, use this method to extract a {@link Query} by name. + * + * @param firestore - The {@link Firestore} instance to read the query from. + * @param name - The name of the query. + * @returns A `Promise` that is resolved with the Query or `null`. + */ function namedQuery(e, t) { + return __PRIVATE_firestoreClientGetNamedQuery(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)), t).then((t => t ? new Query(e, null, t.query) : null)); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents an aggregation that can be performed by Firestore. + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +class AggregateField { + /** + * Create a new AggregateField + * @param aggregateType Specifies the type of aggregation operation to perform. + * @param _internalFieldPath Optionally specifies the field that is aggregated. + * @internal + */ + constructor(e = "count", t) { + this._internalFieldPath = t, + /** A type string to uniquely identify instances of this class. */ + this.type = "AggregateField", this.aggregateType = e; + } +} + +/** + * The results of executing an aggregation query. + */ class AggregateQuerySnapshot { + /** @hideconstructor */ + constructor(e, t, n) { + this._userDataWriter = t, this._data = n, + /** A type string to uniquely identify instances of this class. */ + this.type = "AggregateQuerySnapshot", this.query = e; + } + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ data() { + return this._userDataWriter.convertObjectMap(this._data); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing an array of bytes. + */ class Bytes { + /** @hideconstructor */ + constructor(e) { + this._byteString = e; + } + /** + * Creates a new `Bytes` object from the given Base64 string, converting it to + * bytes. + * + * @param base64 - The Base64 string used to create the `Bytes` object. + */ static fromBase64String(e) { + try { + return new Bytes(ByteString.fromBase64String(e)); + } catch (e) { + throw new FirestoreError(L.INVALID_ARGUMENT, "Failed to construct data from Base64 string: " + e); + } + } + /** + * Creates a new `Bytes` object from the given Uint8Array. + * + * @param array - The Uint8Array used to create the `Bytes` object. + */ static fromUint8Array(e) { + return new Bytes(ByteString.fromUint8Array(e)); + } + /** + * Returns the underlying bytes as a Base64-encoded string. + * + * @returns The Base64-encoded string created from the `Bytes` object. + */ toBase64() { + return this._byteString.toBase64(); + } + /** + * Returns the underlying bytes in a new `Uint8Array`. + * + * @returns The Uint8Array created from the `Bytes` object. + */ toUint8Array() { + return this._byteString.toUint8Array(); + } + /** + * Returns a string representation of the `Bytes` object. + * + * @returns A string representation of the `Bytes` object. + */ toString() { + return "Bytes(base64: " + this.toBase64() + ")"; + } + /** + * Returns true if this `Bytes` object is equal to the provided one. + * + * @param other - The `Bytes` object to compare against. + * @returns true if this `Bytes` object is equal to the provided one. + */ isEqual(e) { + return this._byteString.isEqual(e._byteString); + } + /** + * Returns a JSON-serializable representation of this `Bytes` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + type: Bytes._jsonSchemaVersion, + bytes: this.toBase64() + }; + } + /** + * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}. + * + * @param json a JSON object represention of a `Bytes` instance + * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ static fromJSON(e) { + if (__PRIVATE_validateJSON(e, Bytes._jsonSchema)) return Bytes.fromBase64String(e.bytes); + } +} + +Bytes._jsonSchemaVersion = "firestore/bytes/1.0", Bytes._jsonSchema = { + type: property("string", Bytes._jsonSchemaVersion), + bytes: property("string") +}; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `FieldPath` refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + * + * Create a `FieldPath` by providing field names. If more than one field + * name is provided, the path will point to a nested field in a document. + */ +class FieldPath { + /** + * Creates a `FieldPath` from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames - A list of field names. + */ + constructor(...e) { + for (let t = 0; t < e.length; ++t) if (0 === e[t].length) throw new FirestoreError(L.INVALID_ARGUMENT, "Invalid field name at argument $(i + 1). Field names must not be empty."); + this._internalPath = new FieldPath$1(e); + } + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other - The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ isEqual(e) { + return this._internalPath.isEqual(e._internalPath); + } +} + +/** + * Returns a special sentinel `FieldPath` to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ function documentId() { + return new FieldPath(Q); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Sentinel values that can be used when writing document fields with `set()` + * or `update()`. + */ class FieldValue { + /** + * @param _methodName - The public API endpoint that returns this class. + * @hideconstructor + */ + constructor(e) { + this._methodName = e; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ class GeoPoint { + /** + * Creates a new immutable `GeoPoint` object with the provided latitude and + * longitude values. + * @param latitude - The latitude as number between -90 and 90. + * @param longitude - The longitude as number between -180 and 180. + */ + constructor(e, t) { + if (!isFinite(e) || e < -90 || e > 90) throw new FirestoreError(L.INVALID_ARGUMENT, "Latitude must be a number between -90 and 90, but was: " + e); + if (!isFinite(t) || t < -180 || t > 180) throw new FirestoreError(L.INVALID_ARGUMENT, "Longitude must be a number between -180 and 180, but was: " + t); + this._lat = e, this._long = t; + } + /** + * The latitude of this `GeoPoint` instance. + */ get latitude() { + return this._lat; + } + /** + * The longitude of this `GeoPoint` instance. + */ get longitude() { + return this._long; + } + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other - The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ isEqual(e) { + return this._lat === e._lat && this._long === e._long; + } + /** + * Actually private to JS consumers of our API, so this function is prefixed + * with an underscore. + */ _compareTo(e) { + return __PRIVATE_primitiveComparator(this._lat, e._lat) || __PRIVATE_primitiveComparator(this._long, e._long); + } + /** + * Returns a JSON-serializable representation of this `GeoPoint` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + latitude: this._lat, + longitude: this._long, + type: GeoPoint._jsonSchemaVersion + }; + } + /** + * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}. + * + * @param json a JSON object represention of a `GeoPoint` instance + * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ static fromJSON(e) { + if (__PRIVATE_validateJSON(e, GeoPoint._jsonSchema)) return new GeoPoint(e.latitude, e.longitude); + } +} + +GeoPoint._jsonSchemaVersion = "firestore/geoPoint/1.0", GeoPoint._jsonSchema = { + type: property("string", GeoPoint._jsonSchemaVersion), + latitude: property("number"), + longitude: property("number") +}; + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link vector}. + * + * @class VectorValue + */ +class VectorValue { + /** + * @private + * @internal + */ + constructor(e) { + // Making a copy of the parameter. + this._values = (e || []).map((e => e)); + } + /** + * Returns a copy of the raw number array form of the vector. + */ toArray() { + return this._values.map((e => e)); + } + /** + * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise. + */ isEqual(e) { + return function __PRIVATE_isPrimitiveArrayEqual(e, t) { + if (e.length !== t.length) return !1; + for (let n = 0; n < e.length; ++n) if (e[n] !== t[n]) return !1; + return !0; + }(this._values, e._values); + } + /** + * Returns a JSON-serializable representation of this `VectorValue` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + type: VectorValue._jsonSchemaVersion, + vectorValues: this._values + }; + } + /** + * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}. + * + * @param json a JSON object represention of a `VectorValue` instance. + * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ static fromJSON(e) { + if (__PRIVATE_validateJSON(e, VectorValue._jsonSchema)) { + if (Array.isArray(e.vectorValues) && e.vectorValues.every((e => "number" == typeof e))) return new VectorValue(e.vectorValues); + throw new FirestoreError(L.INVALID_ARGUMENT, "Expected 'vectorValues' field to be a number array"); + } + } +} + +VectorValue._jsonSchemaVersion = "firestore/vectorValue/1.0", VectorValue._jsonSchema = { + type: property("string", VectorValue._jsonSchemaVersion), + vectorValues: property("object") +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const In = /^__.*__$/; + +/** The result of parsing document data (e.g. for a setData call). */ class ParsedSetData { + constructor(e, t, n) { + this.data = e, this.fieldMask = t, this.fieldTransforms = n; + } + toMutation(e, t) { + return null !== this.fieldMask ? new __PRIVATE_PatchMutation(e, this.data, this.fieldMask, t, this.fieldTransforms) : new __PRIVATE_SetMutation(e, this.data, t, this.fieldTransforms); + } +} + +/** The result of parsing "update" data (i.e. for an updateData call). */ class ParsedUpdateData { + constructor(e, + // The fieldMask does not include document transforms. + t, n) { + this.data = e, this.fieldMask = t, this.fieldTransforms = n; + } + toMutation(e, t) { + return new __PRIVATE_PatchMutation(e, this.data, this.fieldMask, t, this.fieldTransforms); + } +} + +function __PRIVATE_isWrite(e) { + switch (e) { + case 0 /* UserDataSource.Set */ : + // fall through + case 2 /* UserDataSource.MergeSet */ : + // fall through + case 1 /* UserDataSource.Update */ : + return !0; + + case 3 /* UserDataSource.Argument */ : + case 4 /* UserDataSource.ArrayArgument */ : + return !1; + + default: + throw fail(40011, { + Ac: e + }); + } +} + +/** A "context" object passed around while parsing user data. */ class __PRIVATE_ParseContextImpl { + /** + * Initializes a ParseContext with the given source and path. + * + * @param settings - The settings for the parser. + * @param databaseId - The database ID of the Firestore instance. + * @param serializer - The serializer to use to generate the Value proto. + * @param ignoreUndefinedProperties - Whether to ignore undefined properties + * rather than throw. + * @param fieldTransforms - A mutable list of field transforms encountered + * while parsing the data. + * @param fieldMask - A mutable list of field paths encountered while parsing + * the data. + * + * TODO(b/34871131): We don't support array paths right now, so path can be + * null to indicate the context represents any location within an array (in + * which case certain features will not work and errors will be somewhat + * compromised). + */ + constructor(e, t, n, r, i, s) { + this.settings = e, this.databaseId = t, this.serializer = n, this.ignoreUndefinedProperties = r, + // Minor hack: If fieldTransforms is undefined, we assume this is an + // external call and we need to validate the entire path. + void 0 === i && this.Rc(), this.fieldTransforms = i || [], this.fieldMask = s || []; + } + get path() { + return this.settings.path; + } + get Ac() { + return this.settings.Ac; + } + /** Returns a new context with the specified settings overwritten. */ Vc(e) { + return new __PRIVATE_ParseContextImpl({ + ...this.settings, + ...e + }, this.databaseId, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask); + } + mc(e) { + const t = this.path?.child(e), n = this.Vc({ + path: t, + fc: !1 + }); + return n.gc(e), n; + } + yc(e) { + const t = this.path?.child(e), n = this.Vc({ + path: t, + fc: !1 + }); + return n.Rc(), n; + } + wc(e) { + // TODO(b/34871131): We don't support array paths right now; so make path + // undefined. + return this.Vc({ + path: void 0, + fc: !0 + }); + } + Sc(e) { + return __PRIVATE_createError(e, this.settings.methodName, this.settings.bc || !1, this.path, this.settings.Dc); + } + /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ contains(e) { + return void 0 !== this.fieldMask.find((t => e.isPrefixOf(t))) || void 0 !== this.fieldTransforms.find((t => e.isPrefixOf(t.field))); + } + Rc() { + // TODO(b/34871131): Remove null check once we have proper paths for fields + // within arrays. + if (this.path) for (let e = 0; e < this.path.length; e++) this.gc(this.path.get(e)); + } + gc(e) { + if (0 === e.length) throw this.Sc("Document fields must not be empty"); + if (__PRIVATE_isWrite(this.Ac) && In.test(e)) throw this.Sc('Document fields cannot begin and end with "__"'); + } +} + +/** + * Helper for parsing raw user input (provided via the API) into internal model + * classes. + */ class __PRIVATE_UserDataReader { + constructor(e, t, n) { + this.databaseId = e, this.ignoreUndefinedProperties = t, this.serializer = n || __PRIVATE_newSerializer(e); + } + /** Creates a new top-level parse context. */ Cc(e, t, n, r = !1) { + return new __PRIVATE_ParseContextImpl({ + Ac: e, + methodName: t, + Dc: n, + path: FieldPath$1.emptyPath(), + fc: !1, + bc: r + }, this.databaseId, this.serializer, this.ignoreUndefinedProperties); + } +} + +function __PRIVATE_newUserDataReader(e) { + const t = e._freezeSettings(), n = __PRIVATE_newSerializer(e._databaseId); + return new __PRIVATE_UserDataReader(e._databaseId, !!t.ignoreUndefinedProperties, n); +} + +/** Parse document data from a set() call. */ function __PRIVATE_parseSetData(e, t, n, r, i, s = {}) { + const o = e.Cc(s.merge || s.mergeFields ? 2 /* UserDataSource.MergeSet */ : 0 /* UserDataSource.Set */ , t, n, i); + __PRIVATE_validatePlainObject("Data must be an object, but it was:", o, r); + const _ = __PRIVATE_parseObject(r, o); + let a, u; + if (s.merge) a = new FieldMask(o.fieldMask), u = o.fieldTransforms; else if (s.mergeFields) { + const e = []; + for (const r of s.mergeFields) { + const i = __PRIVATE_fieldPathFromArgument$1(t, r, n); + if (!o.contains(i)) throw new FirestoreError(L.INVALID_ARGUMENT, `Field '${i}' is specified in your field mask but missing from your input data.`); + __PRIVATE_fieldMaskContains(e, i) || e.push(i); + } + a = new FieldMask(e), u = o.fieldTransforms.filter((e => a.covers(e.field))); + } else a = null, u = o.fieldTransforms; + return new ParsedSetData(new ObjectValue(_), a, u); +} + +class __PRIVATE_DeleteFieldValueImpl extends FieldValue { + _toFieldTransform(e) { + if (2 /* UserDataSource.MergeSet */ !== e.Ac) throw 1 /* UserDataSource.Update */ === e.Ac ? e.Sc(`${this._methodName}() can only appear at the top level of your update data`) : e.Sc(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`); + // No transform to add for a delete, but we need to add it to our + // fieldMask so it gets deleted. + return e.fieldMask.push(e.path), null; + } + isEqual(e) { + return e instanceof __PRIVATE_DeleteFieldValueImpl; + } +} + +/** + * Creates a child context for parsing SerializableFieldValues. + * + * This is different than calling `ParseContext.contextWith` because it keeps + * the fieldTransforms and fieldMask separate. + * + * The created context has its `dataSource` set to `UserDataSource.Argument`. + * Although these values are used with writes, any elements in these FieldValues + * are not considered writes since they cannot contain any FieldValue sentinels, + * etc. + * + * @param fieldValue - The sentinel FieldValue for which to create a child + * context. + * @param context - The parent context. + * @param arrayElement - Whether or not the FieldValue has an array. + */ function __PRIVATE_createSentinelChildContext(e, t, n) { + return new __PRIVATE_ParseContextImpl({ + Ac: 3 /* UserDataSource.Argument */ , + Dc: t.settings.Dc, + methodName: e._methodName, + fc: n + }, t.databaseId, t.serializer, t.ignoreUndefinedProperties); +} + +class __PRIVATE_ServerTimestampFieldValueImpl extends FieldValue { + _toFieldTransform(e) { + return new FieldTransform(e.path, new __PRIVATE_ServerTimestampTransform); + } + isEqual(e) { + return e instanceof __PRIVATE_ServerTimestampFieldValueImpl; + } +} + +class __PRIVATE_ArrayUnionFieldValueImpl extends FieldValue { + constructor(e, t) { + super(e), this.vc = t; + } + _toFieldTransform(e) { + const t = __PRIVATE_createSentinelChildContext(this, e, + /*array=*/ !0), n = this.vc.map((e => __PRIVATE_parseData(e, t))), r = new __PRIVATE_ArrayUnionTransformOperation(n); + return new FieldTransform(e.path, r); + } + isEqual(e) { + return e instanceof __PRIVATE_ArrayUnionFieldValueImpl && V(this.vc, e.vc); + } +} + +class __PRIVATE_ArrayRemoveFieldValueImpl extends FieldValue { + constructor(e, t) { + super(e), this.vc = t; + } + _toFieldTransform(e) { + const t = __PRIVATE_createSentinelChildContext(this, e, + /*array=*/ !0), n = this.vc.map((e => __PRIVATE_parseData(e, t))), r = new __PRIVATE_ArrayRemoveTransformOperation(n); + return new FieldTransform(e.path, r); + } + isEqual(e) { + return e instanceof __PRIVATE_ArrayRemoveFieldValueImpl && V(this.vc, e.vc); + } +} + +class __PRIVATE_NumericIncrementFieldValueImpl extends FieldValue { + constructor(e, t) { + super(e), this.Fc = t; + } + _toFieldTransform(e) { + const t = new __PRIVATE_NumericIncrementTransformOperation(e.serializer, toNumber(e.serializer, this.Fc)); + return new FieldTransform(e.path, t); + } + isEqual(e) { + return e instanceof __PRIVATE_NumericIncrementFieldValueImpl && this.Fc === e.Fc; + } +} + +/** Parse update data from an update() call. */ function __PRIVATE_parseUpdateData(e, t, n, r) { + const i = e.Cc(1 /* UserDataSource.Update */ , t, n); + __PRIVATE_validatePlainObject("Data must be an object, but it was:", i, r); + const s = [], o = ObjectValue.empty(); + forEach(r, ((e, r) => { + const _ = __PRIVATE_fieldPathFromDotSeparatedString(t, e, n); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + r = f(r); + const a = i.yc(_); + if (r instanceof __PRIVATE_DeleteFieldValueImpl) + // Add it to the field mask, but don't add anything to updateData. + s.push(_); else { + const e = __PRIVATE_parseData(r, a); + null != e && (s.push(_), o.set(_, e)); + } + })); + const _ = new FieldMask(s); + return new ParsedUpdateData(o, _, i.fieldTransforms); +} + +/** Parse update data from a list of field/value arguments. */ function __PRIVATE_parseUpdateVarargs(e, t, n, r, i, s) { + const o = e.Cc(1 /* UserDataSource.Update */ , t, n), _ = [ __PRIVATE_fieldPathFromArgument$1(t, r, n) ], a = [ i ]; + if (s.length % 2 != 0) throw new FirestoreError(L.INVALID_ARGUMENT, `Function ${t}() needs to be called with an even number of arguments that alternate between field names and values.`); + for (let e = 0; e < s.length; e += 2) _.push(__PRIVATE_fieldPathFromArgument$1(t, s[e])), + a.push(s[e + 1]); + const u = [], c = ObjectValue.empty(); + // We iterate in reverse order to pick the last value for a field if the + // user specified the field multiple times. + for (let e = _.length - 1; e >= 0; --e) if (!__PRIVATE_fieldMaskContains(u, _[e])) { + const t = _[e]; + let n = a[e]; + // For Compat types, we have to "extract" the underlying types before + // performing validation. + n = f(n); + const r = o.yc(t); + if (n instanceof __PRIVATE_DeleteFieldValueImpl) + // Add it to the field mask, but don't add anything to updateData. + u.push(t); else { + const e = __PRIVATE_parseData(n, r); + null != e && (u.push(t), c.set(t, e)); + } + } + const l = new FieldMask(u); + return new ParsedUpdateData(c, l, o.fieldTransforms); +} + +/** + * Parse a "query value" (e.g. value in a where filter or a value in a cursor + * bound). + * + * @param allowArrays - Whether the query value is an array that may directly + * contain additional arrays (e.g. the operand of an `in` query). + */ function __PRIVATE_parseQueryValue(e, t, n, r = !1) { + return __PRIVATE_parseData(n, e.Cc(r ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */ , t)); +} + +/** + * Parses user data to Protobuf Values. + * + * @param input - Data to be parsed. + * @param context - A context object representing the current path being parsed, + * the source of the data being parsed, etc. + * @returns The parsed value, or null if the value was a FieldValue sentinel + * that should not be included in the resulting parsed data. + */ function __PRIVATE_parseData(e, t) { + if (__PRIVATE_looksLikeJsonObject( + // Unwrap the API type from the Compat SDK. This will return the API type + // from firestore-exp. + e = f(e))) return __PRIVATE_validatePlainObject("Unsupported field value:", t, e), + __PRIVATE_parseObject(e, t); + if (e instanceof FieldValue) + // FieldValues usually parse into transforms (except deleteField()) + // in which case we do not want to include this field in our parsed data + // (as doing so will overwrite the field directly prior to the transform + // trying to transform it). So we don't add this location to + // context.fieldMask and we return null as our parsing result. + /** + * "Parses" the provided FieldValueImpl, adding any necessary transforms to + * context.fieldTransforms. + */ + return function __PRIVATE_parseSentinelFieldValue(e, t) { + // Sentinels are only supported with writes, and not within arrays. + if (!__PRIVATE_isWrite(t.Ac)) throw t.Sc(`${e._methodName}() can only be used with update() and set()`); + if (!t.path) throw t.Sc(`${e._methodName}() is not currently supported inside arrays`); + const n = e._toFieldTransform(t); + n && t.fieldTransforms.push(n); + } + /** + * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue) + * + * @returns The parsed value + */ (e, t), null; + if (void 0 === e && t.ignoreUndefinedProperties) + // If the input is undefined it can never participate in the fieldMask, so + // don't handle this below. If `ignoreUndefinedProperties` is false, + // `parseScalarValue` will reject an undefined value. + return null; + if ( + // If context.path is null we are inside an array and we don't support + // field mask paths more granular than the top-level array. + t.path && t.fieldMask.push(t.path), e instanceof Array) { + // TODO(b/34871131): Include the path containing the array in the error + // message. + // In the case of IN queries, the parsed data is an array (representing + // the set of values to be included for the IN query) that may directly + // contain additional arrays (each representing an individual field + // value), so we disable this validation. + if (t.settings.fc && 4 /* UserDataSource.ArrayArgument */ !== t.Ac) throw t.Sc("Nested arrays are not supported"); + return function __PRIVATE_parseArray(e, t) { + const n = []; + let r = 0; + for (const i of e) { + let e = __PRIVATE_parseData(i, t.wc(r)); + null == e && ( + // Just include nulls in the array for fields being replaced with a + // sentinel. + e = { + nullValue: "NULL_VALUE" + }), n.push(e), r++; + } + return { + arrayValue: { + values: n + } + }; + }(e, t); + } + return function __PRIVATE_parseScalarValue(e, t) { + if (null === (e = f(e))) return { + nullValue: "NULL_VALUE" + }; + if ("number" == typeof e) return toNumber(t.serializer, e); + if ("boolean" == typeof e) return { + booleanValue: e + }; + if ("string" == typeof e) return { + stringValue: e + }; + if (e instanceof Date) { + const n = Timestamp.fromDate(e); + return { + timestampValue: toTimestamp(t.serializer, n) + }; + } + if (e instanceof Timestamp) { + // Firestore backend truncates precision down to microseconds. To ensure + // offline mode works the same with regards to truncation, perform the + // truncation immediately without waiting for the backend to do that. + const n = new Timestamp(e.seconds, 1e3 * Math.floor(e.nanoseconds / 1e3)); + return { + timestampValue: toTimestamp(t.serializer, n) + }; + } + if (e instanceof GeoPoint) return { + geoPointValue: { + latitude: e.latitude, + longitude: e.longitude + } + }; + if (e instanceof Bytes) return { + bytesValue: __PRIVATE_toBytes(t.serializer, e._byteString) + }; + if (e instanceof DocumentReference) { + const n = t.databaseId, r = e.firestore._databaseId; + if (!r.isEqual(n)) throw t.Sc(`Document reference is for database ${r.projectId}/${r.database} but should be for database ${n.projectId}/${n.database}`); + return { + referenceValue: __PRIVATE_toResourceName(e.firestore._databaseId || t.databaseId, e._key.path) + }; + } + if (e instanceof VectorValue) + /** + * Creates a new VectorValue proto value (using the internal format). + */ + return function __PRIVATE_parseVectorValue(e, t) { + const n = { + fields: { + [It]: { + stringValue: At + }, + [Rt]: { + arrayValue: { + values: e.toArray().map((e => { + if ("number" != typeof e) throw t.Sc("VectorValues must only contain numeric values."); + return __PRIVATE_toDouble(t.serializer, e); + })) + } + } + } + }; + return { + mapValue: n + }; + } + /** + * Checks whether an object looks like a JSON object that should be converted + * into a struct. Normal class/prototype instances are considered to look like + * JSON objects since they should be converted to a struct value. Arrays, Dates, + * GeoPoints, etc. are not considered to look like JSON objects since they map + * to specific FieldValue types other than ObjectValue. + */ (e, t); + throw t.Sc(`Unsupported field value: ${__PRIVATE_valueDescription(e)}`); + }(e, t); +} + +function __PRIVATE_parseObject(e, t) { + const n = {}; + return isEmpty(e) ? + // If we encounter an empty object, we explicitly add it to the update + // mask to ensure that the server creates a map entry. + t.path && t.path.length > 0 && t.fieldMask.push(t.path) : forEach(e, ((e, r) => { + const i = __PRIVATE_parseData(r, t.mc(e)); + null != i && (n[e] = i); + })), { + mapValue: { + fields: n + } + }; +} + +function __PRIVATE_looksLikeJsonObject(e) { + return !("object" != typeof e || null === e || e instanceof Array || e instanceof Date || e instanceof Timestamp || e instanceof GeoPoint || e instanceof Bytes || e instanceof DocumentReference || e instanceof FieldValue || e instanceof VectorValue); +} + +function __PRIVATE_validatePlainObject(e, t, n) { + if (!__PRIVATE_looksLikeJsonObject(n) || !__PRIVATE_isPlainObject(n)) { + const r = __PRIVATE_valueDescription(n); + throw "an object" === r ? t.Sc(e + " a custom object") : t.Sc(e + " " + r); + } +} + +/** + * Helper that calls fromDotSeparatedString() but wraps any error thrown. + */ function __PRIVATE_fieldPathFromArgument$1(e, t, n) { + if (( + // If required, replace the FieldPath Compat class with the firestore-exp + // FieldPath. + t = f(t)) instanceof FieldPath) return t._internalPath; + if ("string" == typeof t) return __PRIVATE_fieldPathFromDotSeparatedString(e, t); + throw __PRIVATE_createError("Field path arguments must be of type string or ", e, + /* hasConverter= */ !1, + /* path= */ void 0, n); +} + +/** + * Matches any characters in a field path string that are reserved. + */ const En = new RegExp("[~\\*/\\[\\]]"); + +/** + * Wraps fromDotSeparatedString with an error message about the method that + * was thrown. + * @param methodName - The publicly visible method name + * @param path - The dot-separated string form of a field path which will be + * split on dots. + * @param targetDoc - The document against which the field path will be + * evaluated. + */ function __PRIVATE_fieldPathFromDotSeparatedString(e, t, n) { + if (t.search(En) >= 0) throw __PRIVATE_createError(`Invalid field path (${t}). Paths must not contain '~', '*', '/', '[', or ']'`, e, + /* hasConverter= */ !1, + /* path= */ void 0, n); + try { + return new FieldPath(...t.split("."))._internalPath; + } catch (r) { + throw __PRIVATE_createError(`Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`, e, + /* hasConverter= */ !1, + /* path= */ void 0, n); + } +} + +function __PRIVATE_createError(e, t, n, r, i) { + const s = r && !r.isEmpty(), o = void 0 !== i; + let _ = `Function ${t}() called with invalid data`; + n && (_ += " (via `toFirestore()`)"), _ += ". "; + let a = ""; + return (s || o) && (a += " (found", s && (a += ` in field ${r}`), o && (a += ` in document ${i}`), + a += ")"), new FirestoreError(L.INVALID_ARGUMENT, _ + e + a); +} + +/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ function __PRIVATE_fieldMaskContains(e, t) { + return e.some((e => e.isEqual(t))); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ class DocumentSnapshot$1 { + // Note: This class is stripped down version of the DocumentSnapshot in + // the legacy SDK. The changes are: + // - No support for SnapshotMetadata. + // - No support for SnapshotOptions. + /** @hideconstructor protected */ + constructor(e, t, n, r, i) { + this._firestore = e, this._userDataWriter = t, this._key = n, this._document = r, + this._converter = i; + } + /** Property of the `DocumentSnapshot` that provides the document's ID. */ get id() { + return this._key.path.lastSegment(); + } + /** + * The `DocumentReference` for the document included in the `DocumentSnapshot`. + */ get ref() { + return new DocumentReference(this._firestore, this._converter, this._key); + } + /** + * Signals whether or not the document at the snapshot's location exists. + * + * @returns true if the document exists. + */ exists() { + return null !== this._document; + } + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * @returns An `Object` containing all fields in the document or `undefined` + * if the document doesn't exist. + */ data() { + if (this._document) { + if (this._converter) { + // We only want to use the converter and create a new DocumentSnapshot + // if a converter has been provided. + const e = new QueryDocumentSnapshot$1(this._firestore, this._userDataWriter, this._key, this._document, + /* converter= */ null); + return this._converter.fromFirestore(e); + } + return this._userDataWriter.convertValue(this._document.data.value); + } + } + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + // We are using `any` here to avoid an explicit cast by our users. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get(e) { + if (this._document) { + const t = this._document.data.field(__PRIVATE_fieldPathFromArgument("DocumentSnapshot.get", e)); + if (null !== t) return this._userDataWriter.convertValue(t); + } + } +} + +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ class QueryDocumentSnapshot$1 extends DocumentSnapshot$1 { + /** + * Retrieves all fields in the document as an `Object`. + * + * @override + * @returns An `Object` containing all fields in the document. + */ + data() { + return super.data(); + } +} + +/** + * Helper that calls `fromDotSeparatedString()` but wraps any error thrown. + */ function __PRIVATE_fieldPathFromArgument(e, t) { + return "string" == typeof t ? __PRIVATE_fieldPathFromDotSeparatedString(e, t) : t instanceof FieldPath ? t._internalPath : t._delegate._internalPath; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_validateHasExplicitOrderByForLimitToLast(e) { + if ("L" /* LimitType.Last */ === e.limitType && 0 === e.explicitOrderBy.length) throw new FirestoreError(L.UNIMPLEMENTED, "limitToLast() queries require specifying at least one orderBy() clause"); +} + +/** + * An `AppliableConstraint` is an abstraction of a constraint that can be applied + * to a Firestore query. + */ class AppliableConstraint {} + +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Firestore query. `QueryConstraint`s are created by invoking {@link where}, + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that + * also contains this `QueryConstraint`. + */ class QueryConstraint extends AppliableConstraint {} + +function query(e, t, ...n) { + let r = []; + t instanceof AppliableConstraint && r.push(t), r = r.concat(n), function __PRIVATE_validateQueryConstraintArray(e) { + const t = e.filter((e => e instanceof QueryCompositeFilterConstraint)).length, n = e.filter((e => e instanceof QueryFieldFilterConstraint)).length; + if (t > 1 || t > 0 && n > 0) throw new FirestoreError(L.INVALID_ARGUMENT, "InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`."); + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Converts Firestore's internal types to the JavaScript types that we expose + * to the user. + * + * @internal + */ (r); + for (const t of r) e = t._apply(e); + return e; +} + +/** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ class QueryFieldFilterConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(e, t, n) { + super(), this._field = e, this._op = t, this._value = n, + /** The type of this query constraint */ + this.type = "where"; + } + static _create(e, t, n) { + return new QueryFieldFilterConstraint(e, t, n); + } + _apply(e) { + const t = this._parse(e); + return __PRIVATE_validateNewFieldFilter(e._query, t), new Query(e.firestore, e.converter, __PRIVATE_queryWithAddedFilter(e._query, t)); + } + _parse(e) { + const t = __PRIVATE_newUserDataReader(e.firestore), n = function __PRIVATE_newQueryFilter(e, t, n, r, i, s, o) { + let _; + if (i.isKeyField()) { + if ("array-contains" /* Operator.ARRAY_CONTAINS */ === s || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === s) throw new FirestoreError(L.INVALID_ARGUMENT, `Invalid Query. You can't perform '${s}' queries on documentId().`); + if ("in" /* Operator.IN */ === s || "not-in" /* Operator.NOT_IN */ === s) { + __PRIVATE_validateDisjunctiveFilterElements(o, s); + const t = []; + for (const n of o) t.push(__PRIVATE_parseDocumentIdValue(r, e, n)); + _ = { + arrayValue: { + values: t + } + }; + } else _ = __PRIVATE_parseDocumentIdValue(r, e, o); + } else "in" /* Operator.IN */ !== s && "not-in" /* Operator.NOT_IN */ !== s && "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ !== s || __PRIVATE_validateDisjunctiveFilterElements(o, s), + _ = __PRIVATE_parseQueryValue(n, t, o, + /* allowArrays= */ "in" /* Operator.IN */ === s || "not-in" /* Operator.NOT_IN */ === s); + const a = FieldFilter.create(i, s, _); + return a; + }(e._query, "where", t, e.firestore._databaseId, this._field, this._op, this._value); + return n; + } +} + +/** + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. + * + * @param fieldPath - The path to compare + * @param opStr - The operation string (e.g "<", "<=", "==", "<", + * "<=", "!="). + * @param value - The value for comparison + * @returns The created {@link QueryFieldFilterConstraint}. + */ function where(e, t, n) { + const r = t, i = __PRIVATE_fieldPathFromArgument("where", e); + return QueryFieldFilterConstraint._create(i, r, n); +} + +/** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ class QueryCompositeFilterConstraint extends AppliableConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + e, t) { + super(), this.type = e, this._queryConstraints = t; + } + static _create(e, t) { + return new QueryCompositeFilterConstraint(e, t); + } + _parse(e) { + const t = this._queryConstraints.map((t => t._parse(e))).filter((e => e.getFilters().length > 0)); + return 1 === t.length ? t[0] : CompositeFilter.create(t, this._getOperator()); + } + _apply(e) { + const t = this._parse(e); + return 0 === t.getFilters().length ? e : (function __PRIVATE_validateNewFilter(e, t) { + let n = e; + const r = t.getFlattenedFilters(); + for (const e of r) __PRIVATE_validateNewFieldFilter(n, e), n = __PRIVATE_queryWithAddedFilter(n, e); + } + // Checks if any of the provided filter operators are included in the given list of filters and + // returns the first one that is, or null if none are. + (e._query, t), new Query(e.firestore, e.converter, __PRIVATE_queryWithAddedFilter(e._query, t))); + } + _getQueryConstraints() { + return this._queryConstraints; + } + _getOperator() { + return "and" === this.type ? "and" /* CompositeOperator.AND */ : "or" /* CompositeOperator.OR */; + } +} + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ function or(...e) { + // Only support QueryFilterConstraints + return e.forEach((e => __PRIVATE_validateQueryFilterConstraint("or", e))), QueryCompositeFilterConstraint._create("or" /* CompositeOperator.OR */ , e); +} + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ function and(...e) { + // Only support QueryFilterConstraints + return e.forEach((e => __PRIVATE_validateQueryFilterConstraint("and", e))), QueryCompositeFilterConstraint._create("and" /* CompositeOperator.AND */ , e); +} + +/** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ class QueryOrderByConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(e, t) { + super(), this._field = e, this._direction = t, + /** The type of this query constraint */ + this.type = "orderBy"; + } + static _create(e, t) { + return new QueryOrderByConstraint(e, t); + } + _apply(e) { + const t = function __PRIVATE_newQueryOrderBy(e, t, n) { + if (null !== e.startAt) throw new FirestoreError(L.INVALID_ARGUMENT, "Invalid query. You must not call startAt() or startAfter() before calling orderBy()."); + if (null !== e.endAt) throw new FirestoreError(L.INVALID_ARGUMENT, "Invalid query. You must not call endAt() or endBefore() before calling orderBy()."); + const r = new OrderBy(t, n); + return r; + } + /** + * Create a `Bound` from a query and a document. + * + * Note that the `Bound` will always include the key of the document + * and so only the provided document will compare equal to the returned + * position. + * + * Will throw if the document does not contain all fields of the order by + * of the query or if any of the fields in the order by are an uncommitted + * server timestamp. + */ (e._query, this._field, this._direction); + return new Query(e.firestore, e.converter, function __PRIVATE_queryWithAddedOrderBy(e, t) { + // TODO(dimond): validate that orderBy does not list the same key twice. + const n = e.explicitOrderBy.concat([ t ]); + return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, n, e.filters.slice(), e.limit, e.limitType, e.startAt, e.endAt); + }(e._query, t)); + } +} + +/** + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the + * specified field, optionally in descending order instead of ascending. + * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * + * @param fieldPath - The field to sort by. + * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @returns The created {@link QueryOrderByConstraint}. + */ function orderBy(e, t = "asc") { + const n = t, r = __PRIVATE_fieldPathFromArgument("orderBy", e); + return QueryOrderByConstraint._create(r, n); +} + +/** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ class QueryLimitConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + e, t, n) { + super(), this.type = e, this._limit = t, this._limitType = n; + } + static _create(e, t, n) { + return new QueryLimitConstraint(e, t, n); + } + _apply(e) { + return new Query(e.firestore, e.converter, __PRIVATE_queryWithLimit(e._query, this._limit, this._limitType)); + } +} + +/** + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ function limit(e) { + return __PRIVATE_validatePositiveNumber("limit", e), QueryLimitConstraint._create("limit", e, "F" /* LimitType.First */); +} + +/** + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. + * + * You must specify at least one `orderBy` clause for `limitToLast` queries, + * otherwise an exception will be thrown during execution. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ function limitToLast(e) { + return __PRIVATE_validatePositiveNumber("limitToLast", e), QueryLimitConstraint._create("limitToLast", e, "L" /* LimitType.Last */); +} + +/** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ class QueryStartAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + e, t, n) { + super(), this.type = e, this._docOrFields = t, this._inclusive = n; + } + static _create(e, t, n) { + return new QueryStartAtConstraint(e, t, n); + } + _apply(e) { + const t = __PRIVATE_newQueryBoundFromDocOrFields(e, this.type, this._docOrFields, this._inclusive); + return new Query(e.firestore, e.converter, function __PRIVATE_queryWithStartAt(e, t) { + return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, e.explicitOrderBy.slice(), e.filters.slice(), e.limit, e.limitType, t, e.endAt); + }(e._query, t)); + } +} + +function startAt(...e) { + return QueryStartAtConstraint._create("startAt", e, + /*inclusive=*/ !0); +} + +function startAfter(...e) { + return QueryStartAtConstraint._create("startAfter", e, + /*inclusive=*/ !1); +} + +/** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ class QueryEndAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + e, t, n) { + super(), this.type = e, this._docOrFields = t, this._inclusive = n; + } + static _create(e, t, n) { + return new QueryEndAtConstraint(e, t, n); + } + _apply(e) { + const t = __PRIVATE_newQueryBoundFromDocOrFields(e, this.type, this._docOrFields, this._inclusive); + return new Query(e.firestore, e.converter, function __PRIVATE_queryWithEndAt(e, t) { + return new __PRIVATE_QueryImpl(e.path, e.collectionGroup, e.explicitOrderBy.slice(), e.filters.slice(), e.limit, e.limitType, e.startAt, t); + }(e._query, t)); + } +} + +function endBefore(...e) { + return QueryEndAtConstraint._create("endBefore", e, + /*inclusive=*/ !1); +} + +function endAt(...e) { + return QueryEndAtConstraint._create("endAt", e, + /*inclusive=*/ !0); +} + +/** Helper function to create a bound from a document or fields */ function __PRIVATE_newQueryBoundFromDocOrFields(e, t, n, r) { + if (n[0] = f(n[0]), n[0] instanceof DocumentSnapshot$1) return function __PRIVATE_newQueryBoundFromDocument(e, t, n, r, i) { + if (!r) throw new FirestoreError(L.NOT_FOUND, `Can't use a DocumentSnapshot that doesn't exist for ${n}().`); + const s = []; + // Because people expect to continue/end a query at the exact document + // provided, we need to use the implicit sort order rather than the explicit + // sort order, because it's guaranteed to contain the document key. That way + // the position becomes unambiguous and the query continues/ends exactly at + // the provided document. Without the key (by using the explicit sort + // orders), multiple documents could match the position, yielding duplicate + // results. + for (const n of __PRIVATE_queryNormalizedOrderBy(e)) if (n.field.isKeyField()) s.push(__PRIVATE_refValue(t, r.key)); else { + const e = r.data.field(n.field); + if (__PRIVATE_isServerTimestamp(e)) throw new FirestoreError(L.INVALID_ARGUMENT, 'Invalid query. You are trying to start or end a query using a document for which the field "' + n.field + '" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)'); + if (null === e) { + const e = n.field.canonicalString(); + throw new FirestoreError(L.INVALID_ARGUMENT, `Invalid query. You are trying to start or end a query using a document for which the field '${e}' (used as the orderBy) does not exist.`); + } + s.push(e); + } + return new Bound(s, i); + } + /** + * Converts a list of field values to a `Bound` for the given query. + */ (e._query, e.firestore._databaseId, t, n[0]._document, r); + { + const i = __PRIVATE_newUserDataReader(e.firestore); + return function __PRIVATE_newQueryBoundFromFields(e, t, n, r, i, s) { + // Use explicit order by's because it has to match the query the user made + const o = e.explicitOrderBy; + if (i.length > o.length) throw new FirestoreError(L.INVALID_ARGUMENT, `Too many arguments provided to ${r}(). The number of arguments must be less than or equal to the number of orderBy() clauses`); + const _ = []; + for (let s = 0; s < i.length; s++) { + const a = i[s]; + if (o[s].field.isKeyField()) { + if ("string" != typeof a) throw new FirestoreError(L.INVALID_ARGUMENT, `Invalid query. Expected a string for document ID in ${r}(), but got a ${typeof a}`); + if (!__PRIVATE_isCollectionGroupQuery(e) && -1 !== a.indexOf("/")) throw new FirestoreError(L.INVALID_ARGUMENT, `Invalid query. When querying a collection and ordering by documentId(), the value passed to ${r}() must be a plain document ID, but '${a}' contains a slash.`); + const n = e.path.child(ResourcePath.fromString(a)); + if (!DocumentKey.isDocumentKey(n)) throw new FirestoreError(L.INVALID_ARGUMENT, `Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${r}() must result in a valid document path, but '${n}' is not because it contains an odd number of segments.`); + const i = new DocumentKey(n); + _.push(__PRIVATE_refValue(t, i)); + } else { + const e = __PRIVATE_parseQueryValue(n, r, a); + _.push(e); + } + } + return new Bound(_, s); + } + /** + * Parses the given `documentIdValue` into a `ReferenceValue`, throwing + * appropriate errors if the value is anything other than a `DocumentReference` + * or `string`, or if the string is malformed. + */ (e._query, e.firestore._databaseId, i, t, n, r); + } +} + +function __PRIVATE_parseDocumentIdValue(e, t, n) { + if ("string" == typeof (n = f(n))) { + if ("" === n) throw new FirestoreError(L.INVALID_ARGUMENT, "Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string."); + if (!__PRIVATE_isCollectionGroupQuery(t) && -1 !== n.indexOf("/")) throw new FirestoreError(L.INVALID_ARGUMENT, `Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${n}' contains a '/' character.`); + const r = t.path.child(ResourcePath.fromString(n)); + if (!DocumentKey.isDocumentKey(r)) throw new FirestoreError(L.INVALID_ARGUMENT, `Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${r}' is not because it has an odd number of segments (${r.length}).`); + return __PRIVATE_refValue(e, new DocumentKey(r)); + } + if (n instanceof DocumentReference) return __PRIVATE_refValue(e, n._key); + throw new FirestoreError(L.INVALID_ARGUMENT, `Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${__PRIVATE_valueDescription(n)}.`); +} + +/** + * Validates that the value passed into a disjunctive filter satisfies all + * array requirements. + */ function __PRIVATE_validateDisjunctiveFilterElements(e, t) { + if (!Array.isArray(e) || 0 === e.length) throw new FirestoreError(L.INVALID_ARGUMENT, `Invalid Query. A non-empty array is required for '${t.toString()}' filters.`); +} + +/** + * Given an operator, returns the set of operators that cannot be used with it. + * + * This is not a comprehensive check, and this function should be removed in the + * long term. Validations should occur in the Firestore backend. + * + * Operators in a query must adhere to the following set of rules: + * 1. Only one inequality per query. + * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators. + */ function __PRIVATE_validateNewFieldFilter(e, t) { + const n = function __PRIVATE_findOpInsideFilters(e, t) { + for (const n of e) for (const e of n.getFlattenedFilters()) if (t.indexOf(e.op) >= 0) return e.op; + return null; + }(e.filters, function __PRIVATE_conflictingOps(e) { + switch (e) { + case "!=" /* Operator.NOT_EQUAL */ : + return [ "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ]; + + case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ : + case "in" /* Operator.IN */ : + return [ "not-in" /* Operator.NOT_IN */ ]; + + case "not-in" /* Operator.NOT_IN */ : + return [ "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , "in" /* Operator.IN */ , "not-in" /* Operator.NOT_IN */ , "!=" /* Operator.NOT_EQUAL */ ]; + + default: + return []; + } + }(t.op)); + if (null !== n) + // Special case when it's a duplicate op to give a slightly clearer error message. + throw n === t.op ? new FirestoreError(L.INVALID_ARGUMENT, `Invalid query. You cannot use more than one '${t.op.toString()}' filter.`) : new FirestoreError(L.INVALID_ARGUMENT, `Invalid query. You cannot use '${t.op.toString()}' filters with '${n.toString()}' filters.`); +} + +function __PRIVATE_validateQueryFilterConstraint(e, t) { + if (!(t instanceof QueryFieldFilterConstraint || t instanceof QueryCompositeFilterConstraint)) throw new FirestoreError(L.INVALID_ARGUMENT, `Function ${e}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`); +} + +class AbstractUserDataWriter { + convertValue(e, t = "none") { + switch (__PRIVATE_typeOrder(e)) { + case 0 /* TypeOrder.NullValue */ : + return null; + + case 1 /* TypeOrder.BooleanValue */ : + return e.booleanValue; + + case 2 /* TypeOrder.NumberValue */ : + return __PRIVATE_normalizeNumber(e.integerValue || e.doubleValue); + + case 3 /* TypeOrder.TimestampValue */ : + return this.convertTimestamp(e.timestampValue); + + case 4 /* TypeOrder.ServerTimestampValue */ : + return this.convertServerTimestamp(e, t); + + case 5 /* TypeOrder.StringValue */ : + return e.stringValue; + + case 6 /* TypeOrder.BlobValue */ : + return this.convertBytes(__PRIVATE_normalizeByteString(e.bytesValue)); + + case 7 /* TypeOrder.RefValue */ : + return this.convertReference(e.referenceValue); + + case 8 /* TypeOrder.GeoPointValue */ : + return this.convertGeoPoint(e.geoPointValue); + + case 9 /* TypeOrder.ArrayValue */ : + return this.convertArray(e.arrayValue, t); + + case 11 /* TypeOrder.ObjectValue */ : + return this.convertObject(e.mapValue, t); + + case 10 /* TypeOrder.VectorValue */ : + return this.convertVectorValue(e.mapValue); + + default: + throw fail(62114, { + value: e + }); + } + } + convertObject(e, t) { + return this.convertObjectMap(e.fields, t); + } + /** + * @internal + */ convertObjectMap(e, t = "none") { + const n = {}; + return forEach(e, ((e, r) => { + n[e] = this.convertValue(r, t); + })), n; + } + /** + * @internal + */ convertVectorValue(e) { + const t = e.fields?.[Rt].arrayValue?.values?.map((e => __PRIVATE_normalizeNumber(e.doubleValue))); + return new VectorValue(t); + } + convertGeoPoint(e) { + return new GeoPoint(__PRIVATE_normalizeNumber(e.latitude), __PRIVATE_normalizeNumber(e.longitude)); + } + convertArray(e, t) { + return (e.values || []).map((e => this.convertValue(e, t))); + } + convertServerTimestamp(e, t) { + switch (t) { + case "previous": + const n = __PRIVATE_getPreviousValue(e); + return null == n ? null : this.convertValue(n, t); + + case "estimate": + return this.convertTimestamp(__PRIVATE_getLocalWriteTime(e)); + + default: + return null; + } + } + convertTimestamp(e) { + const t = __PRIVATE_normalizeTimestamp(e); + return new Timestamp(t.seconds, t.nanos); + } + convertDocumentKey(e, t) { + const n = ResourcePath.fromString(e); + __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(n), 9688, { + name: e + }); + const r = new DatabaseId(n.get(1), n.get(3)), i = new DocumentKey(n.popFirst(5)); + return r.isEqual(t) || + // TODO(b/64130202): Somehow support foreign references. + __PRIVATE_logError(`Document ${i} contains a document reference within a different database (${r.projectId}/${r.database}) which is not supported. It will be treated as a reference in the current database (${t.projectId}/${t.database}) instead.`), + i; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Converts custom model object of type T into `DocumentData` by applying the + * converter if it exists. + * + * This function is used when converting user objects to `DocumentData` + * because we want to provide the user with a more specific error message if + * their `set()` or fails due to invalid data originating from a `toFirestore()` + * call. + */ function __PRIVATE_applyFirestoreDataConverter(e, t, n) { + let r; + // Cast to `any` in order to satisfy the union type constraint on + // toFirestore(). + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return r = e ? n && (n.merge || n.mergeFields) ? e.toFirestore(t, n) : e.toFirestore(t) : t, + r; +} + +class __PRIVATE_LiteUserDataWriter extends AbstractUserDataWriter { + constructor(e) { + super(), this.firestore = e; + } + convertBytes(e) { + return new Bytes(e); + } + convertReference(e) { + const t = this.convertDocumentKey(e, this.firestore._databaseId); + return new DocumentReference(this.firestore, /* converter= */ null, t); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ function sum(e) { + return new AggregateField("sum", __PRIVATE_fieldPathFromArgument$1("sum", e)); +} + +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ function average(e) { + return new AggregateField("avg", __PRIVATE_fieldPathFromArgument$1("average", e)); +} + +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ function count() { + return new AggregateField("count"); +} + +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ function aggregateFieldEqual(e, t) { + return e instanceof AggregateField && t instanceof AggregateField && e.aggregateType === t.aggregateType && e._internalFieldPath?.canonicalString() === t._internalFieldPath?.canonicalString(); +} + +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ function aggregateQuerySnapshotEqual(e, t) { + return queryEqual(e.query, t.query) && V(e.data(), t.data()); +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const dn = "NOT SUPPORTED"; + +/** + * Metadata about a snapshot, describing the state of the snapshot. + */ class SnapshotMetadata { + /** @hideconstructor */ + constructor(e, t) { + this.hasPendingWrites = e, this.fromCache = t; + } + /** + * Returns true if this `SnapshotMetadata` is equal to the provided one. + * + * @param other - The `SnapshotMetadata` to compare against. + * @returns true if this `SnapshotMetadata` is equal to the provided one. + */ isEqual(e) { + return this.hasPendingWrites === e.hasPendingWrites && this.fromCache === e.fromCache; + } +} + +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ class DocumentSnapshot extends DocumentSnapshot$1 { + /** @hideconstructor protected */ + constructor(e, t, n, r, i, s) { + super(e, t, n, r, s), this._firestore = e, this._firestoreImpl = e, this.metadata = i; + } + /** + * Returns whether or not the data exists. True if the document exists. + */ exists() { + return super.exists(); + } + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * By default, `serverTimestamp()` values that have not yet been + * set to their final value will be returned as `null`. You can override + * this by passing an options object. + * + * @param options - An options object to configure how data is retrieved from + * the snapshot (for example the desired behavior for server timestamps that + * have not yet been set to their final value). + * @returns An `Object` containing all fields in the document or `undefined` if + * the document doesn't exist. + */ data(e = {}) { + if (this._document) { + if (this._converter) { + // We only want to use the converter and create a new DocumentSnapshot + // if a converter has been provided. + const t = new QueryDocumentSnapshot(this._firestore, this._userDataWriter, this._key, this._document, this.metadata, + /* converter= */ null); + return this._converter.fromFirestore(t, e); + } + return this._userDataWriter.convertValue(this._document.data.value, e.serverTimestamps); + } + } + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * By default, a `serverTimestamp()` that has not yet been set to + * its final value will be returned as `null`. You can override this by + * passing an options object. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @param options - An options object to configure how the field is retrieved + * from the snapshot (for example the desired behavior for server timestamps + * that have not yet been set to their final value). + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + // We are using `any` here to avoid an explicit cast by our users. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get(e, t = {}) { + if (this._document) { + const n = this._document.data.field(__PRIVATE_fieldPathFromArgument("DocumentSnapshot.get", e)); + if (null !== n) return this._userDataWriter.convertValue(n, t.serverTimestamps); + } + } + /** + * Returns a JSON-serializable representation of this `DocumentSnapshot` instance. + * + * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this + * `DocumentSnapshot` has pending writes. + */ toJSON() { + if (this.metadata.hasPendingWrites) throw new FirestoreError(L.FAILED_PRECONDITION, "DocumentSnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON()."); + const e = this._document, t = {}; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (t.type = DocumentSnapshot._jsonSchemaVersion, t.bundle = "", t.bundleSource = "DocumentSnapshot", + t.bundleName = this._key.toString(), !e || !e.isValidDocument() || !e.isFoundDocument()) return t; + this._userDataWriter.convertObjectMap(e.data.value.mapValue.fields, "previous"); + return t.bundle = (this._firestore, this.ref.path, "NOT SUPPORTED"), t; + } +} + +function documentSnapshotFromJSON(e, t, n) { + if (__PRIVATE_validateJSON(t, DocumentSnapshot._jsonSchema)) { + if (t.bundle === dn) throw new FirestoreError(L.INVALID_ARGUMENT, "The provided JSON object was created in a client environment, which is not supported."); + // Parse the bundle data. + const r = __PRIVATE_newSerializer(e._databaseId), i = __PRIVATE_createBundleReaderSync(t.bundle, r), s = i.Wu(), o = new __PRIVATE_BundleLoader(i.getMetadata(), r); + for (const e of s) o.Ga(e); + // Ensure that we have the correct number of documents in the bundle. + const _ = o.documents; + if (1 !== _.length) throw new FirestoreError(L.INVALID_ARGUMENT, `Expected bundle data to contain 1 document, but it contains ${_.length} documents.`); + // Build out the internal document data. + const a = __PRIVATE_fromDocument(r, _[0].document), u = new DocumentKey(ResourcePath.fromString(t.bundleName)); + // Return the external facing DocumentSnapshot. + return new DocumentSnapshot(e, new __PRIVATE_LiteUserDataWriter(e), u, a, new SnapshotMetadata( + /* hasPendingWrites= */ !1, + /* fromCache= */ !1), n || null); + } +} + +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ DocumentSnapshot._jsonSchemaVersion = "firestore/documentSnapshot/1.0", DocumentSnapshot._jsonSchema = { + type: property("string", DocumentSnapshot._jsonSchemaVersion), + bundleSource: property("string", "DocumentSnapshot"), + bundleName: property("string"), + bundle: property("string") +}; + +class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * By default, `serverTimestamp()` values that have not yet been + * set to their final value will be returned as `null`. You can override + * this by passing an options object. + * + * @override + * @param options - An options object to configure how data is retrieved from + * the snapshot (for example the desired behavior for server timestamps that + * have not yet been set to their final value). + * @returns An `Object` containing all fields in the document. + */ + data(e = {}) { + return super.data(e); + } +} + +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ class QuerySnapshot { + /** @hideconstructor */ + constructor(e, t, n, r) { + this._firestore = e, this._userDataWriter = t, this._snapshot = r, this.metadata = new SnapshotMetadata(r.hasPendingWrites, r.fromCache), + this.query = n; + } + /** An array of all the documents in the `QuerySnapshot`. */ get docs() { + const e = []; + return this.forEach((t => e.push(t))), e; + } + /** The number of documents in the `QuerySnapshot`. */ get size() { + return this._snapshot.docs.size; + } + /** True if there are no documents in the `QuerySnapshot`. */ get empty() { + return 0 === this.size; + } + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ forEach(e, t) { + this._snapshot.docs.forEach((n => { + e.call(t, new QueryDocumentSnapshot(this._firestore, this._userDataWriter, n.key, n, new SnapshotMetadata(this._snapshot.mutatedKeys.has(n.key), this._snapshot.fromCache), this.query.converter)); + })); + } + /** + * Returns an array of the documents changes since the last snapshot. If this + * is the first snapshot, all documents will be in the list as 'added' + * changes. + * + * @param options - `SnapshotListenOptions` that control whether metadata-only + * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger + * snapshot events. + */ docChanges(e = {}) { + const t = !!e.includeMetadataChanges; + if (t && this._snapshot.excludesMetadataChanges) throw new FirestoreError(L.INVALID_ARGUMENT, "To include metadata changes with your document changes, you must also pass { includeMetadataChanges:true } to onSnapshot()."); + return this._cachedChanges && this._cachedChangesIncludeMetadataChanges === t || (this._cachedChanges = + /** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */ + function __PRIVATE_changesFromSnapshot(e, t) { + if (e._snapshot.oldDocs.isEmpty()) { + let t = 0; + return e._snapshot.docChanges.map((n => { + const r = new QueryDocumentSnapshot(e._firestore, e._userDataWriter, n.doc.key, n.doc, new SnapshotMetadata(e._snapshot.mutatedKeys.has(n.doc.key), e._snapshot.fromCache), e.query.converter); + return n.doc, { + type: "added", + doc: r, + oldIndex: -1, + newIndex: t++ + }; + })); + } + { + // A `DocumentSet` that is updated incrementally as changes are applied to use + // to lookup the index of a document. + let n = e._snapshot.oldDocs; + return e._snapshot.docChanges.filter((e => t || 3 /* ChangeType.Metadata */ !== e.type)).map((t => { + const r = new QueryDocumentSnapshot(e._firestore, e._userDataWriter, t.doc.key, t.doc, new SnapshotMetadata(e._snapshot.mutatedKeys.has(t.doc.key), e._snapshot.fromCache), e.query.converter); + let i = -1, s = -1; + return 0 /* ChangeType.Added */ !== t.type && (i = n.indexOf(t.doc.key), n = n.delete(t.doc.key)), + 1 /* ChangeType.Removed */ !== t.type && (n = n.add(t.doc), s = n.indexOf(t.doc.key)), + { + type: __PRIVATE_resultChangeType(t.type), + doc: r, + oldIndex: i, + newIndex: s + }; + })); + } + }(this, t), this._cachedChangesIncludeMetadataChanges = t), this._cachedChanges; + } + /** + * Returns a JSON-serializable representation of this `QuerySnapshot` instance. + * + * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this + * `QuerySnapshot` has pending writes. + */ toJSON() { + if (this.metadata.hasPendingWrites) throw new FirestoreError(L.FAILED_PRECONDITION, "QuerySnapshot.toJSON() attempted to serialize a document with pending writes. Await waitForPendingWrites() before invoking toJSON()."); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const e = {}; + e.type = QuerySnapshot._jsonSchemaVersion, e.bundleSource = "QuerySnapshot", e.bundleName = __PRIVATE_AutoId.newId(), + this._firestore._databaseId.database, this._firestore._databaseId.projectId; + const t = [], n = [], r = []; + return this.docs.forEach((e => { + null !== e._document && (t.push(e._document), n.push(this._userDataWriter.convertObjectMap(e._document.data.value.mapValue.fields, "previous")), + r.push(e.ref.path)); + })), e.bundle = (this._firestore, this.query._query, e.bundleName, "NOT SUPPORTED"), + e; + } +} + +function querySnapshotFromJSON(e, t, n) { + if (__PRIVATE_validateJSON(t, QuerySnapshot._jsonSchema)) { + if (t.bundle === dn) throw new FirestoreError(L.INVALID_ARGUMENT, "The provided JSON object was created in a client environment, which is not supported."); + // Parse the bundle data. + const r = __PRIVATE_newSerializer(e._databaseId), i = __PRIVATE_createBundleReaderSync(t.bundle, r), s = i.Wu(), o = new __PRIVATE_BundleLoader(i.getMetadata(), r); + for (const e of s) o.Ga(e); + if (1 !== o.queries.length) throw new FirestoreError(L.INVALID_ARGUMENT, `Snapshot data expected 1 query but found ${o.queries.length} queries.`); + // Create an internal Query object from the named query in the bundle. + const _ = __PRIVATE_fromBundledQuery(o.queries[0].bundledQuery), a = o.documents; + // Construct the arrays of document data for the query. + let u = new DocumentSet; + a.map((e => { + const t = __PRIVATE_fromDocument(r, e.document); + u = u.add(t); + })); + // Create a view snapshot of the query and documents. + const c = ViewSnapshot.fromInitialDocuments(_, u, __PRIVATE_documentKeySet() /* Zero mutated keys signifies no pending writes. */ , + /* fromCache= */ !1, + /* hasCachedResults= */ !1), l = new Query(e, n || null, _); + // Create an external Query object, required to construct the QuerySnapshot. + // Return a new QuerySnapshot with all of the collected data. + return new QuerySnapshot(e, new __PRIVATE_LiteUserDataWriter(e), l, c); + } +} + +function __PRIVATE_resultChangeType(e) { + switch (e) { + case 0 /* ChangeType.Added */ : + return "added"; + + case 2 /* ChangeType.Modified */ : + case 3 /* ChangeType.Metadata */ : + return "modified"; + + case 1 /* ChangeType.Removed */ : + return "removed"; + + default: + return fail(61501, { + type: e + }); + } +} + +// TODO(firestoreexp): Add tests for snapshotEqual with different snapshot +// metadata +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ function snapshotEqual(e, t) { + return e instanceof DocumentSnapshot && t instanceof DocumentSnapshot ? e._firestore === t._firestore && e._key.isEqual(t._key) && (null === e._document ? null === t._document : e._document.isEqual(t._document)) && e._converter === t._converter : e instanceof QuerySnapshot && t instanceof QuerySnapshot && (e._firestore === t._firestore && queryEqual(e.query, t.query) && e.metadata.isEqual(t.metadata) && e._snapshot.isEqual(t._snapshot)); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Reads the document referred to by this `DocumentReference`. + * + * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting + * for data from the server, but it may return cached data or fail if you are + * offline and the server cannot be reached. To specify this behavior, invoke + * {@link getDocFromCache} or {@link getDocFromServer}. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the + * current document contents. + */ function getDoc(e) { + e = __PRIVATE_cast(e, DocumentReference); + const t = __PRIVATE_cast(e.firestore, Firestore); + return __PRIVATE_firestoreClientGetDocumentViaSnapshotListener(ensureFirestoreConfigured(t), e._key).then((n => __PRIVATE_convertToDocSnapshot(t, e, n))); +} + +QuerySnapshot._jsonSchemaVersion = "firestore/querySnapshot/1.0", QuerySnapshot._jsonSchema = { + type: property("string", QuerySnapshot._jsonSchemaVersion), + bundleSource: property("string", "QuerySnapshot"), + bundleName: property("string"), + bundle: property("string") +}; + +class __PRIVATE_ExpUserDataWriter extends AbstractUserDataWriter { + constructor(e) { + super(), this.firestore = e; + } + convertBytes(e) { + return new Bytes(e); + } + convertReference(e) { + const t = this.convertDocumentKey(e, this.firestore._databaseId); + return new DocumentReference(this.firestore, /* converter= */ null, t); + } +} + +/** + * Reads the document referred to by this `DocumentReference` from cache. + * Returns an error if the document is not currently cached. + * + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the + * current document contents. + */ function getDocFromCache(e) { + e = __PRIVATE_cast(e, DocumentReference); + const t = __PRIVATE_cast(e.firestore, Firestore), n = ensureFirestoreConfigured(t), r = new __PRIVATE_ExpUserDataWriter(t); + return __PRIVATE_firestoreClientGetDocumentFromLocalCache(n, e._key).then((n => new DocumentSnapshot(t, r, e._key, n, new SnapshotMetadata(null !== n && n.hasLocalMutations, + /* fromCache= */ !0), e.converter))); +} + +/** + * Reads the document referred to by this `DocumentReference` from the server. + * Returns an error if the network is not available. + * + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the + * current document contents. + */ function getDocFromServer(e) { + e = __PRIVATE_cast(e, DocumentReference); + const t = __PRIVATE_cast(e.firestore, Firestore); + return __PRIVATE_firestoreClientGetDocumentViaSnapshotListener(ensureFirestoreConfigured(t), e._key, { + source: "server" + }).then((n => __PRIVATE_convertToDocSnapshot(t, e, n))); +} + +/** + * Executes the query and returns the results as a `QuerySnapshot`. + * + * Note: `getDocs()` attempts to provide up-to-date data when possible by + * waiting for data from the server, but it may return cached data or fail if + * you are offline and the server cannot be reached. To specify this behavior, + * invoke {@link getDocsFromCache} or {@link getDocsFromServer}. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ function getDocs(e) { + e = __PRIVATE_cast(e, Query); + const t = __PRIVATE_cast(e.firestore, Firestore), n = ensureFirestoreConfigured(t), r = new __PRIVATE_ExpUserDataWriter(t); + return __PRIVATE_validateHasExplicitOrderByForLimitToLast(e._query), __PRIVATE_firestoreClientGetDocumentsViaSnapshotListener(n, e._query).then((n => new QuerySnapshot(t, r, e, n))); +} + +/** + * Executes the query and returns the results as a `QuerySnapshot` from cache. + * Returns an empty result set if no documents matching the query are currently + * cached. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ function getDocsFromCache(e) { + e = __PRIVATE_cast(e, Query); + const t = __PRIVATE_cast(e.firestore, Firestore), n = ensureFirestoreConfigured(t), r = new __PRIVATE_ExpUserDataWriter(t); + return __PRIVATE_firestoreClientGetDocumentsFromLocalCache(n, e._query).then((n => new QuerySnapshot(t, r, e, n))); +} + +/** + * Executes the query and returns the results as a `QuerySnapshot` from the + * server. Returns an error if the network is not available. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ function getDocsFromServer(e) { + e = __PRIVATE_cast(e, Query); + const t = __PRIVATE_cast(e.firestore, Firestore), n = ensureFirestoreConfigured(t), r = new __PRIVATE_ExpUserDataWriter(t); + return __PRIVATE_firestoreClientGetDocumentsViaSnapshotListener(n, e._query, { + source: "server" + }).then((n => new QuerySnapshot(t, r, e, n))); +} + +function setDoc(e, t, n) { + e = __PRIVATE_cast(e, DocumentReference); + const r = __PRIVATE_cast(e.firestore, Firestore), i = __PRIVATE_applyFirestoreDataConverter(e.converter, t, n); + return executeWrite(r, [ __PRIVATE_parseSetData(__PRIVATE_newUserDataReader(r), "setDoc", e._key, i, null !== e.converter, n).toMutation(e._key, Precondition.none()) ]); +} + +function updateDoc(e, t, n, ...r) { + e = __PRIVATE_cast(e, DocumentReference); + const i = __PRIVATE_cast(e.firestore, Firestore), s = __PRIVATE_newUserDataReader(i); + let o; + o = "string" == typeof ( + // For Compat types, we have to "extract" the underlying types before + // performing validation. + t = f(t)) || t instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(s, "updateDoc", e._key, t, n, r) : __PRIVATE_parseUpdateData(s, "updateDoc", e._key, t); + return executeWrite(i, [ o.toMutation(e._key, Precondition.exists(!0)) ]); +} + +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * @param reference - A reference to the document to delete. + * @returns A Promise resolved once the document has been successfully + * deleted from the backend (note that it won't resolve while you're offline). + */ function deleteDoc(e) { + return executeWrite(__PRIVATE_cast(e.firestore, Firestore), [ new __PRIVATE_DeleteMutation(e._key, Precondition.none()) ]); +} + +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend (Note that it + * won't resolve while you're offline). + */ function addDoc(e, t) { + const n = __PRIVATE_cast(e.firestore, Firestore), r = doc(e), i = __PRIVATE_applyFirestoreDataConverter(e.converter, t); + return executeWrite(n, [ __PRIVATE_parseSetData(__PRIVATE_newUserDataReader(e.firestore), "addDoc", r._key, i, null !== e.converter, {}).toMutation(r._key, Precondition.exists(!1)) ]).then((() => r)); +} + +function onSnapshot(e, ...t) { + // onSnapshot for Query or Document. + e = f(e); + let n = { + includeMetadataChanges: !1, + source: "default" + }, r = 0; + "object" != typeof t[r] || __PRIVATE_isPartialObserver(t[r]) || (n = t[r++]); + const i = { + includeMetadataChanges: n.includeMetadataChanges, + source: n.source + }; + if (__PRIVATE_isPartialObserver(t[r])) { + const e = t[r]; + t[r] = e.next?.bind(e), t[r + 1] = e.error?.bind(e), t[r + 2] = e.complete?.bind(e); + } + let s, o, _; + if (e instanceof DocumentReference) o = __PRIVATE_cast(e.firestore, Firestore), + _ = __PRIVATE_newQueryForPath(e._key.path), s = { + next: n => { + t[r] && t[r](__PRIVATE_convertToDocSnapshot(o, e, n)); + }, + error: t[r + 1], + complete: t[r + 2] + }; else { + const n = __PRIVATE_cast(e, Query); + o = __PRIVATE_cast(n.firestore, Firestore), _ = n._query; + const i = new __PRIVATE_ExpUserDataWriter(o); + s = { + next: e => { + t[r] && t[r](new QuerySnapshot(o, i, n, e)); + }, + error: t[r + 1], + complete: t[r + 2] + }, __PRIVATE_validateHasExplicitOrderByForLimitToLast(e._query); + } + return function __PRIVATE_firestoreClientListen(e, t, n, r) { + const i = new __PRIVATE_AsyncObserver(r), s = new __PRIVATE_QueryListener(t, i, n); + return e.asyncQueue.enqueueAndForget((async () => __PRIVATE_eventManagerListen(await __PRIVATE_getEventManager(e), s))), + () => { + i.Nu(), e.asyncQueue.enqueueAndForget((async () => __PRIVATE_eventManagerUnlisten(await __PRIVATE_getEventManager(e), s))); + }; + }(ensureFirestoreConfigured(o), _, i, s); +} + +function onSnapshotResume(e, t, ...n) { + const r = f(e), i = + /** + * Ensures the data required to construct an {@link onSnapshot} listener exist in a `snapshotJson` + * object that originates from {@link DocumentSnapshot.toJSON} or {@link Querysnapshot.toJSON}. The + * data is normalized into a typed object. + * + * @param snapshotJson - The JSON object that the app provided to {@link onSnapshot}. + * @returns A normalized object that contains all of the required bundle JSON fields. If + * {@link snapshotJson} doesn't contain the required fields, or if the fields exist as empty + * strings, then the {@link snapshotJson.error} field will be a non empty string. + * + * @internal + */ + function __PRIVATE_normalizeSnapshotJsonFields(e) { + const t = { + bundle: "", + bundleName: "", + bundleSource: "" + }, n = [ "bundle", "bundleName", "bundleSource" ]; + for (const r of n) { + if (!(r in e)) { + t.error = `snapshotJson missing required field: ${r}`; + break; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const n = e[r]; + if ("string" != typeof n) { + t.error = `snapshotJson field '${r}' must be a string.`; + break; + } + if (0 === n.length) { + t.error = `snapshotJson field '${r}' cannot be an empty string.`; + break; + } + "bundle" === r ? t.bundle = n : "bundleName" === r ? t.bundleName = n : "bundleSource" === r && (t.bundleSource = n); + } + return t; + } + /** + * Loads the bundle in a separate task and then invokes {@link onSnapshot} with a + * {@link DocumentReference} for the document in the bundle. + * + * @param firestore - The {@link Firestore} instance for the {@link onSnapshot} operation request. + * @param json - The JSON bundle to load, produced by {@link DocumentSnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot + * listener. + * + * @internal + */ (t); + if (i.error) throw new FirestoreError(L.INVALID_ARGUMENT, i.error); + let s, o = 0; + if ("object" != typeof n[o] || __PRIVATE_isPartialObserver(n[o]) || (s = n[o++]), + "QuerySnapshot" === i.bundleSource) { + let e = null; + if ("object" == typeof n[o] && __PRIVATE_isPartialObserver(n[o])) { + const t = n[o++]; + e = { + next: t.next, + error: t.error, + complete: t.complete + }; + } else e = { + next: n[o++], + error: n[o++], + complete: n[o++] + }; + /** + * Loads the bundle in a separate task and then invokes {@link onSnapshot} with a + * {@link Query} that represents the Query in the bundle. + * + * @param firestore - The {@link Firestore} instance for the {@link onSnapshot} operation request. + * @param json - The JSON bundle to load, produced by {@link QuerySnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot + * listener. + * + * @internal + */ + return function __PRIVATE_onSnapshotQuerySnapshotBundle(e, t, n, r, i) { + let s, o = !1; + const _ = loadBundle(e, t.bundle); + return _.then((() => namedQuery(e, t.bundleName))).then((e => { + if (e && !o) { + i && e.withConverter(i), s = onSnapshot(e, n || {}, r); + } + })).catch((e => (r.error && r.error(e), () => {}))), () => { + o || (o = !0, s && s()); + }; + } + /** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ (r, i, s, e, n[o]); + } + if ("DocumentSnapshot" === i.bundleSource) { + let e = null; + if ("object" == typeof n[o] && __PRIVATE_isPartialObserver(n[o])) { + const t = n[o++]; + e = { + next: t.next, + error: t.error, + complete: t.complete + }; + } else e = { + next: n[o++], + error: n[o++], + complete: n[o++] + }; + return function __PRIVATE_onSnapshotDocumentSnapshotBundle(e, t, n, r, i) { + let s, o = !1; + const _ = loadBundle(e, t.bundle); + return _.then((() => { + if (!o) { + const o = new DocumentReference(e, i || null, DocumentKey.fromPath(t.bundleName)); + s = onSnapshot(o, n || {}, r); + } + })).catch((e => (r.error && r.error(e), () => {}))), () => { + o || (o = !0, s && s()); + }; + }(r, i, s, e, n[o]); + } + throw new FirestoreError(L.INVALID_ARGUMENT, `unsupported bundle source: ${i.bundleSource}`); +} + +function onSnapshotsInSync(e, t) { + return __PRIVATE_firestoreClientAddSnapshotsInSyncListener(ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)), __PRIVATE_isPartialObserver(t) ? t : { + next: t + }); +} + +/** + * Locally writes `mutations` on the async queue. + * @internal + */ function executeWrite(e, t) { + return function __PRIVATE_firestoreClientWrite(e, t) { + const n = new __PRIVATE_Deferred; + return e.asyncQueue.enqueueAndForget((async () => __PRIVATE_syncEngineWrite(await __PRIVATE_getSyncEngine(e), t, n))), + n.promise; + }(ensureFirestoreConfigured(e), t); +} + +/** + * Converts a {@link ViewSnapshot} that contains the single document specified by `ref` + * to a {@link DocumentSnapshot}. + */ function __PRIVATE_convertToDocSnapshot(e, t, n) { + const r = n.docs.get(t._key), i = new __PRIVATE_ExpUserDataWriter(e); + return new DocumentSnapshot(e, i, t._key, r, new SnapshotMetadata(n.hasPendingWrites, n.fromCache), t.converter); +} + +function getCountFromServer(e) { + return getAggregateFromServer(e, { + count: count() + }); +} + +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregateFromServer(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ function getAggregateFromServer(e, t) { + const n = __PRIVATE_cast(e.firestore, Firestore), r = ensureFirestoreConfigured(n), i = __PRIVATE_mapToArray(t, ((e, t) => new __PRIVATE_AggregateImpl(t, e.aggregateType, e._internalFieldPath))); + // Run the aggregation and convert the results + return __PRIVATE_firestoreClientRunAggregateQuery(r, e._query, i).then((t => + /** + * Converts the core aggregation result to an `AggregateQuerySnapshot` + * that can be returned to the consumer. + * @param query + * @param aggregateResult Core aggregation result + * @internal + */ + function __PRIVATE_convertToAggregateQuerySnapshot(e, t, n) { + const r = new __PRIVATE_ExpUserDataWriter(e), i = new AggregateQuerySnapshot(t, r, n); + return i; + } + /** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ (n, e, t))); +} + +class __PRIVATE_MemoryLocalCacheImpl { + constructor(e) { + this.kind = "memory", this._onlineComponentProvider = OnlineComponentProvider.provider, + this._offlineComponentProvider = e?.garbageCollector ? e.garbageCollector._offlineComponentProvider : { + build: () => new __PRIVATE_LruGcMemoryOfflineComponentProvider(void 0) + }; + } + toJSON() { + return { + kind: this.kind + }; + } +} + +class __PRIVATE_PersistentLocalCacheImpl { + constructor(e) { + let t; + this.kind = "persistent", e?.tabManager ? (e.tabManager._initialize(e), t = e.tabManager) : (t = persistentSingleTabManager(void 0), + t._initialize(e)), this._onlineComponentProvider = t._onlineComponentProvider, this._offlineComponentProvider = t._offlineComponentProvider; + } + toJSON() { + return { + kind: this.kind + }; + } +} + +class __PRIVATE_MemoryEagerGarbageCollectorImpl { + constructor() { + this.kind = "memoryEager", this._offlineComponentProvider = __PRIVATE_MemoryOfflineComponentProvider.provider; + } + toJSON() { + return { + kind: this.kind + }; + } +} + +class __PRIVATE_MemoryLruGarbageCollectorImpl { + constructor(e) { + this.kind = "memoryLru", this._offlineComponentProvider = { + build: () => new __PRIVATE_LruGcMemoryOfflineComponentProvider(e) + }; + } + toJSON() { + return { + kind: this.kind + }; + } +} + +/** + * Creates an instance of `MemoryEagerGarbageCollector`. This is also the + * default garbage collector unless it is explicitly specified otherwise. + */ function memoryEagerGarbageCollector() { + return new __PRIVATE_MemoryEagerGarbageCollectorImpl; +} + +/** + * Creates an instance of `MemoryLruGarbageCollector`. + * + * A target size can be specified as part of the setting parameter. The + * collector will start deleting documents once the cache size exceeds + * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes). + */ function memoryLruGarbageCollector(e) { + return new __PRIVATE_MemoryLruGarbageCollectorImpl(e?.cacheSizeBytes); +} + +/** + * Creates an instance of `MemoryLocalCache`. The instance can be set to + * `FirestoreSettings.cache` to tell the SDK which cache layer to use. + */ function memoryLocalCache(e) { + return new __PRIVATE_MemoryLocalCacheImpl(e); +} + +/** + * Creates an instance of `PersistentLocalCache`. The instance can be set to + * `FirestoreSettings.cache` to tell the SDK which cache layer to use. + * + * Persistent cache cannot be used in a Node.js environment. + */ function persistentLocalCache(e) { + return new __PRIVATE_PersistentLocalCacheImpl(e); +} + +class __PRIVATE_SingleTabManagerImpl { + constructor(e) { + this.forceOwnership = e, this.kind = "persistentSingleTab"; + } + toJSON() { + return { + kind: this.kind + }; + } + /** + * @internal + */ _initialize(e) { + this._onlineComponentProvider = OnlineComponentProvider.provider, this._offlineComponentProvider = { + build: t => new __PRIVATE_IndexedDbOfflineComponentProvider(t, e?.cacheSizeBytes, this.forceOwnership) + }; + } +} + +class __PRIVATE_MultiTabManagerImpl { + constructor() { + this.kind = "PersistentMultipleTab"; + } + toJSON() { + return { + kind: this.kind + }; + } + /** + * @internal + */ _initialize(e) { + this._onlineComponentProvider = OnlineComponentProvider.provider, this._offlineComponentProvider = { + build: t => new __PRIVATE_MultiTabOfflineComponentProvider(t, e?.cacheSizeBytes) + }; + } +} + +/** + * Creates an instance of `PersistentSingleTabManager`. + * + * @param settings Configures the created tab manager. + */ function persistentSingleTabManager(e) { + return new __PRIVATE_SingleTabManagerImpl(e?.forceOwnership); +} + +/** + * Creates an instance of `PersistentMultipleTabManager`. + */ function persistentMultipleTabManager() { + return new __PRIVATE_MultiTabManagerImpl; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const An = { + maxAttempts: 5 +}; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It + * provides methods for adding writes to the write batch. None of the writes + * will be committed (or visible locally) until {@link WriteBatch.commit} is + * called. + */ +class WriteBatch { + /** @hideconstructor */ + constructor(e, t) { + this._firestore = e, this._commitHandler = t, this._mutations = [], this._committed = !1, + this._dataReader = __PRIVATE_newUserDataReader(e); + } + set(e, t, n) { + this._verifyNotCommitted(); + const r = __PRIVATE_validateReference(e, this._firestore), i = __PRIVATE_applyFirestoreDataConverter(r.converter, t, n), s = __PRIVATE_parseSetData(this._dataReader, "WriteBatch.set", r._key, i, null !== r.converter, n); + return this._mutations.push(s.toMutation(r._key, Precondition.none())), this; + } + update(e, t, n, ...r) { + this._verifyNotCommitted(); + const i = __PRIVATE_validateReference(e, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + let s; + return s = "string" == typeof (t = f(t)) || t instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(this._dataReader, "WriteBatch.update", i._key, t, n, r) : __PRIVATE_parseUpdateData(this._dataReader, "WriteBatch.update", i._key, t), + this._mutations.push(s.toMutation(i._key, Precondition.exists(!0))), this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ delete(e) { + this._verifyNotCommitted(); + const t = __PRIVATE_validateReference(e, this._firestore); + return this._mutations = this._mutations.concat(new __PRIVATE_DeleteMutation(t._key, Precondition.none())), + this; + } + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `Promise` resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit (note that it won't + * resolve while you're offline). + */ commit() { + return this._verifyNotCommitted(), this._committed = !0, this._mutations.length > 0 ? this._commitHandler(this._mutations) : Promise.resolve(); + } + _verifyNotCommitted() { + if (this._committed) throw new FirestoreError(L.FAILED_PRECONDITION, "A write batch can no longer be used after commit() has been called."); + } +} + +function __PRIVATE_validateReference(e, t) { + if ((e = f(e)).firestore !== t) throw new FirestoreError(L.INVALID_ARGUMENT, "Provided document reference is from a different Firestore instance."); + return e; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the +// legacy SDK. +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ class Transaction$1 { + /** @hideconstructor */ + constructor(e, t) { + this._firestore = e, this._transaction = t, this._dataReader = __PRIVATE_newUserDataReader(e); + } + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ get(e) { + const t = __PRIVATE_validateReference(e, this._firestore), n = new __PRIVATE_LiteUserDataWriter(this._firestore); + return this._transaction.lookup([ t._key ]).then((e => { + if (!e || 1 !== e.length) return fail(24041); + const r = e[0]; + if (r.isFoundDocument()) return new DocumentSnapshot$1(this._firestore, n, r.key, r, t.converter); + if (r.isNoDocument()) return new DocumentSnapshot$1(this._firestore, n, t._key, null, t.converter); + throw fail(18433, { + doc: r + }); + })); + } + set(e, t, n) { + const r = __PRIVATE_validateReference(e, this._firestore), i = __PRIVATE_applyFirestoreDataConverter(r.converter, t, n), s = __PRIVATE_parseSetData(this._dataReader, "Transaction.set", r._key, i, null !== r.converter, n); + return this._transaction.set(r._key, s), this; + } + update(e, t, n, ...r) { + const i = __PRIVATE_validateReference(e, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + let s; + return s = "string" == typeof (t = f(t)) || t instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(this._dataReader, "Transaction.update", i._key, t, n, r) : __PRIVATE_parseUpdateData(this._dataReader, "Transaction.update", i._key, t), + this._transaction.update(i._key, s), this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `Transaction` instance. Used for chaining method calls. + */ delete(e) { + const t = __PRIVATE_validateReference(e, this._firestore); + return this._transaction.delete(t._key), this; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ class Transaction extends Transaction$1 { + // This class implements the same logic as the Transaction API in the Lite SDK + // but is subclassed in order to return its own DocumentSnapshot types. + /** @hideconstructor */ + constructor(e, t) { + super(e, t), this._firestore = e; + } + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ get(e) { + const t = __PRIVATE_validateReference(e, this._firestore), n = new __PRIVATE_ExpUserDataWriter(this._firestore); + return super.get(e).then((e => new DocumentSnapshot(this._firestore, n, t._key, e._document, new SnapshotMetadata( + /* hasPendingWrites= */ !1, + /* fromCache= */ !1), t.converter))); + } +} + +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ function runTransaction(e, t, n) { + e = __PRIVATE_cast(e, Firestore); + const r = { + ...An, + ...n + }; + !function __PRIVATE_validateTransactionOptions(e) { + if (e.maxAttempts < 1) throw new FirestoreError(L.INVALID_ARGUMENT, "Max attempts must be at least 1"); + }(r); + return function __PRIVATE_firestoreClientTransaction(e, t, n) { + const r = new __PRIVATE_Deferred; + return e.asyncQueue.enqueueAndForget((async () => { + const i = await __PRIVATE_getDatastore(e); + new __PRIVATE_TransactionRunner(e.asyncQueue, i, n, t, r).ju(); + })), r.promise; + }(ensureFirestoreConfigured(e), (n => t(new Transaction(e, n))), r); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. + */ function deleteField() { + return new __PRIVATE_DeleteFieldValueImpl("deleteField"); +} + +/** + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to + * include a server-generated timestamp in the written data. + */ function serverTimestamp() { + return new __PRIVATE_ServerTimestampFieldValueImpl("serverTimestamp"); +} + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array + * value that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements - The elements to union into the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()`. + */ function arrayUnion(...e) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new __PRIVATE_ArrayUnionFieldValueImpl("arrayUnion", e); +} + +/** + * Returns a special value that can be used with {@link (setDoc:1)} or {@link + * updateDoc:1} that tells the server to remove the given elements from any + * array value that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is not + * already an array it will be overwritten with an empty array. + * + * @param elements - The elements to remove from the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ function arrayRemove(...e) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new __PRIVATE_ArrayRemoveFieldValueImpl("arrayRemove", e); +} + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by + * the given value. + * + * If either the operand or the current field value uses floating point + * precision, all arithmetic follows IEEE 754 semantics. If both values are + * integers, values outside of JavaScript's safe number range + * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to + * precision loss. Furthermore, once processed by the Firestore backend, all + * integer operations are capped between -2^63 and 2^63-1. + * + * If the current field value is not of type `number`, or if the field does not + * yet exist, the transformation sets the field to the given value. + * + * @param n - The value to increment by. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ function increment(e) { + return new __PRIVATE_NumericIncrementFieldValueImpl("increment", e); +} + +/** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ function vector(e) { + return new VectorValue(e); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch} + * is 500. + * + * Unlike transactions, write batches are persisted offline and therefore are + * preferable when you don't need to condition your writes on read data. + * + * @returns A {@link WriteBatch} that can be used to atomically execute multiple + * writes. + */ function writeBatch(e) { + return ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)), new WriteBatch(e, (t => executeWrite(e, t))); +} + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function setIndexConfiguration(e, t) { + const n = ensureFirestoreConfigured(e = __PRIVATE_cast(e, Firestore)); + if (!n._uninitializedComponentsProvider || "memory" === n._uninitializedComponentsProvider._offline.kind) + // PORTING NOTE: We don't return an error if the user has not enabled + // persistence since `enableIndexeddbPersistence()` can fail on the Web. + return __PRIVATE_logWarn("Cannot enable indexes when persistence is disabled"), + Promise.resolve(); + const r = function __PRIVATE_parseIndexes(e) { + const t = "string" == typeof e ? function __PRIVATE_tryParseJson(e) { + try { + return JSON.parse(e); + } catch (e) { + throw new FirestoreError(L.INVALID_ARGUMENT, "Failed to parse JSON: " + e?.message); + } + }(e) : e, n = []; + if (Array.isArray(t.indexes)) for (const e of t.indexes) { + const t = __PRIVATE_tryGetString(e, "collectionGroup"), r = []; + if (Array.isArray(e.fields)) for (const t of e.fields) { + const e = __PRIVATE_fieldPathFromDotSeparatedString("setIndexConfiguration", __PRIVATE_tryGetString(t, "fieldPath")); + "CONTAINS" === t.arrayConfig ? r.push(new IndexSegment(e, 2 /* IndexKind.CONTAINS */)) : "ASCENDING" === t.order ? r.push(new IndexSegment(e, 0 /* IndexKind.ASCENDING */)) : "DESCENDING" === t.order && r.push(new IndexSegment(e, 1 /* IndexKind.DESCENDING */)); + } + n.push(new FieldIndex(FieldIndex.UNKNOWN_ID, t, r, IndexState.empty())); + } + return n; + }(t); + return __PRIVATE_firestoreClientSetIndexConfiguration(n, r); +} + +function __PRIVATE_tryGetString(e, t) { + if ("string" != typeof e[t]) throw new FirestoreError(L.INVALID_ARGUMENT, "Missing string value for: " + t); + return e[t]; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `PersistentCacheIndexManager` for configuring persistent cache indexes used + * for local query execution. + * + * To use, call `getPersistentCacheIndexManager()` to get an instance. + */ class PersistentCacheIndexManager { + /** @hideconstructor */ + constructor(e) { + this._firestore = e, + /** A type string to uniquely identify instances of this class. */ + this.type = "PersistentCacheIndexManager"; + } +} + +/** + * Returns the PersistentCache Index Manager used by the given `Firestore` + * object. + * + * @return The `PersistentCacheIndexManager` instance, or `null` if local + * persistent storage is not in use. + */ function getPersistentCacheIndexManager(e) { + e = __PRIVATE_cast(e, Firestore); + const t = Rn.get(e); + if (t) return t; + const n = ensureFirestoreConfigured(e); + if ("persistent" !== n._uninitializedComponentsProvider?._offline.kind) return null; + const r = new PersistentCacheIndexManager(e); + return Rn.set(e, r), r; +} + +/** + * Enables the SDK to create persistent cache indexes automatically for local + * query execution when the SDK believes cache indexes can help improve + * performance. + * + * This feature is disabled by default. + */ function enablePersistentCacheIndexAutoCreation(e) { + __PRIVATE_setPersistentCacheIndexAutoCreationEnabled(e, !0); +} + +/** + * Stops creating persistent cache indexes automatically for local query + * execution. The indexes which have been created by calling + * `enablePersistentCacheIndexAutoCreation()` still take effect. + */ function disablePersistentCacheIndexAutoCreation(e) { + __PRIVATE_setPersistentCacheIndexAutoCreationEnabled(e, !1); +} + +/** + * Removes all persistent cache indexes. + * + * Please note this function will also deletes indexes generated by + * `setIndexConfiguration()`, which is deprecated. + */ function deleteAllPersistentCacheIndexes(e) { + __PRIVATE_firestoreClientDeleteAllFieldIndexes(ensureFirestoreConfigured(e._firestore)).then((e => __PRIVATE_logDebug("deleting all persistent cache indexes succeeded"))).catch((e => __PRIVATE_logWarn("deleting all persistent cache indexes failed", e))); +} + +function __PRIVATE_setPersistentCacheIndexAutoCreationEnabled(e, t) { + __PRIVATE_firestoreClientSetPersistentCacheIndexAutoCreationEnabled(ensureFirestoreConfigured(e._firestore), t).then((e => __PRIVATE_logDebug(`setting persistent cache index auto creation isEnabled=${t} succeeded`))).catch((e => __PRIVATE_logWarn(`setting persistent cache index auto creation isEnabled=${t} failed`, e))); +} + +/** + * Maps `Firestore` instances to their corresponding + * `PersistentCacheIndexManager` instances. + * + * Use a `WeakMap` so that the mapping will be automatically dropped when the + * `Firestore` instance is garbage collected. This emulates a private member + * as described in https://goo.gle/454yvug. + */ const Rn = new WeakMap; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @internal + * @private + * + * This function is for internal use only. + * + * Returns the `QueryTarget` representation of the given query. Returns `null` + * if the Firestore client associated with the given query has not been + * initialized or has been terminated. + * + * @param query - The Query to convert to proto representation. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function _internalQueryToProtoQueryTarget(e) { + const t = ensureFirestoreConfigured(__PRIVATE_cast(e.firestore, Firestore)), n = t._onlineComponents?.datastore.serializer; + return void 0 === n ? null : __PRIVATE_toQueryTarget(n, __PRIVATE_queryToTarget(e._query)).ft; +} + +/** + * @internal + * @private + * + * This function is for internal use only. + * + * Returns `RunAggregationQueryRequest` which contains the proto representation + * of the given aggregation query request. Returns null if the Firestore client + * associated with the given query has not been initialized or has been + * terminated. + * + * @param query - The Query to convert to proto representation. + * @param aggregateSpec - The set of aggregations and their aliases. + */ function _internalAggregationQueryToProtoRunAggregationQueryRequest(e, t) { + const n = __PRIVATE_mapToArray(t, ((e, t) => new __PRIVATE_AggregateImpl(t, e.aggregateType, e._internalFieldPath))), r = ensureFirestoreConfigured(__PRIVATE_cast(e.firestore, Firestore)), i = r._onlineComponents?.datastore.serializer; + return void 0 === i ? null : __PRIVATE_toRunAggregationQueryRequest(i, __PRIVATE_queryToAggregateTarget(e._query), n, + /* skipAliasing= */ !0).request; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Testing hooks for use by Firestore's integration test suite to reach into the + * SDK internals to validate logic and behavior that is not visible from the + * public API surface. + * + * @internal + */ class TestingHooks { + constructor() { + throw new Error("instances of this class should not be created"); + } + /** + * Registers a callback to be notified when an existence filter mismatch + * occurs in the Watch listen stream. + * + * The relative order in which callbacks are notified is unspecified; do not + * rely on any particular ordering. If a given callback is registered multiple + * times then it will be notified multiple times, once per registration. + * + * @param callback the callback to invoke upon existence filter mismatch. + * + * @return a function that, when called, unregisters the given callback; only + * the first invocation of the returned function does anything; all subsequent + * invocations do nothing. + */ static onExistenceFilterMismatch(e) { + return __PRIVATE_TestingHooksSpiImpl.instance.onExistenceFilterMismatch(e); + } +} + +/** + * The implementation of `TestingHooksSpi`. + */ class __PRIVATE_TestingHooksSpiImpl { + constructor() { + this.Mc = new Map; + } + static get instance() { + return Vn || (Vn = new __PRIVATE_TestingHooksSpiImpl, function __PRIVATE_setTestingHooksSpi(e) { + if (Dt) throw new Error("a TestingHooksSpi instance is already set"); + Dt = e; + }(Vn)), Vn; + } + lt(e) { + this.Mc.forEach((t => t(e))); + } + onExistenceFilterMismatch(e) { + const t = Symbol(), n = this.Mc; + return n.set(t, e), () => n.delete(t); + } +} + +let Vn = null; + +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ !function __PRIVATE_registerFirestore(e, t = !0) { + !function __PRIVATE_setSDKVersion(e) { + N = e; + }(s), r(new o("firestore", ((e, {instanceIdentifier: n, options: r}) => { + const i = e.getProvider("app").getImmediate(), s = new Firestore(new __PRIVATE_FirebaseAuthCredentialsProvider(e.getProvider("auth-internal")), new __PRIVATE_FirebaseAppCheckTokenProvider(i, e.getProvider("app-check-internal")), function __PRIVATE_databaseIdFromApp(e, t) { + if (!Object.prototype.hasOwnProperty.apply(e.options, [ "projectId" ])) throw new FirestoreError(L.INVALID_ARGUMENT, '"projectId" not provided in firebase.initializeApp.'); + return new DatabaseId(e.options.projectId, t); + }(i, n), i); + return r = { + useFetchStreams: t, + ...r + }, s._setSettings(r), s; + }), "PUBLIC").setMultipleInstances(!0)), i(x, O, e), + // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation + i(x, O, "esm2020"); +}("rn", /* useFetchStreams= */ !1); + +export { AbstractUserDataWriter, AggregateField, AggregateQuerySnapshot, Bytes, Tn as CACHE_SIZE_UNLIMITED, CollectionReference, DocumentReference, DocumentSnapshot, FieldPath, FieldValue, Firestore, FirestoreError, GeoPoint, LoadBundleTask, PersistentCacheIndexManager, Query, QueryCompositeFilterConstraint, QueryConstraint, QueryDocumentSnapshot, QueryEndAtConstraint, QueryFieldFilterConstraint, QueryLimitConstraint, QueryOrderByConstraint, QuerySnapshot, QueryStartAtConstraint, SnapshotMetadata, Timestamp, Transaction, VectorValue, WriteBatch, __PRIVATE_AutoId as _AutoId, ByteString as _ByteString, DatabaseId as _DatabaseId, DocumentKey as _DocumentKey, __PRIVATE_EmptyAppCheckTokenProvider as _EmptyAppCheckTokenProvider, __PRIVATE_EmptyAuthCredentialsProvider as _EmptyAuthCredentialsProvider, FieldPath$1 as _FieldPath, TestingHooks as _TestingHooks, __PRIVATE_cast as _cast, __PRIVATE_debugAssert as _debugAssert, _internalAggregationQueryToProtoRunAggregationQueryRequest, _internalQueryToProtoQueryTarget, __PRIVATE_isBase64Available as _isBase64Available, __PRIVATE_logWarn as _logWarn, __PRIVATE_validateIsNotUsedTogether as _validateIsNotUsedTogether, addDoc, aggregateFieldEqual, aggregateQuerySnapshotEqual, and, arrayRemove, arrayUnion, average, clearIndexedDbPersistence, collection, collectionGroup, connectFirestoreEmulator, count, deleteAllPersistentCacheIndexes, deleteDoc, deleteField, disableNetwork, disablePersistentCacheIndexAutoCreation, doc, documentId, documentSnapshotFromJSON, enableIndexedDbPersistence, enableMultiTabIndexedDbPersistence, enableNetwork, enablePersistentCacheIndexAutoCreation, endAt, endBefore, ensureFirestoreConfigured, executeWrite, getAggregateFromServer, getCountFromServer, getDoc, getDocFromCache, getDocFromServer, getDocs, getDocsFromCache, getDocsFromServer, getFirestore, getPersistentCacheIndexManager, increment, initializeFirestore, limit, limitToLast, loadBundle, memoryEagerGarbageCollector, memoryLocalCache, memoryLruGarbageCollector, namedQuery, onSnapshot, onSnapshotResume, onSnapshotsInSync, or, orderBy, persistentLocalCache, persistentMultipleTabManager, persistentSingleTabManager, query, queryEqual, querySnapshotFromJSON, refEqual, runTransaction, serverTimestamp, setDoc, setIndexConfiguration, setLogLevel, snapshotEqual, startAfter, startAt, sum, terminate, updateDoc, vector, waitForPendingWrites, where, writeBatch }; +//# sourceMappingURL=index.rn.js.map diff --git a/frontend-old/node_modules/@firebase/firestore/dist/index.rn.js.map b/frontend-old/node_modules/@firebase/firestore/dist/index.rn.js.map new file mode 100644 index 0000000..4f688dd --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/index.rn.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.rn.js","sources":["../src/auth/user.ts","../src/core/version.ts","../src/util/log.ts","../src/platform/browser/format_json.ts","../src/util/assert.ts","../src/util/error.ts","../src/util/promise.ts","../src/api/credentials.ts","../src/platform/browser/random_bytes.ts","../src/util/misc.ts","../src/model/path.ts","../src/model/document_key.ts","../src/util/input_validation.ts","../src/util/json_validation.ts","../src/lite-api/timestamp.ts","../src/core/snapshot_version.ts","../src/model/field_index.ts","../src/local/persistence_transaction.ts","../src/local/local_store.ts","../src/local/persistence_promise.ts","../src/local/simple_db.ts","../src/local/index_backfiller.ts","../src/core/listen_sequence.ts","../src/util/types.ts","../src/local/encoded_resource_path.ts","../src/local/indexeddb_schema_legacy.ts","../src/local/indexeddb_sentinels.ts","../src/local/indexeddb_transaction.ts","../src/util/obj.ts","../src/util/sorted_map.ts","../src/util/sorted_set.ts","../src/model/field_mask.ts","../src/util/base64_decode_error.ts","../src/platform/rn/base64.ts","../src/util/byte_string.ts","../src/model/normalize.ts","../src/model/server_timestamps.ts","../src/core/database_info.ts","../src/model/values.ts","../src/model/object_value.ts","../src/model/document.ts","../src/core/bound.ts","../src/core/order_by.ts","../src/core/filter.ts","../src/core/target.ts","../src/core/query.ts","../src/util/obj_map.ts","../src/model/collections.ts","../src/remote/number_serializer.ts","../src/model/transform_operation.ts","../src/model/mutation.ts","../src/model/mutation_batch.ts","../src/model/overlay.ts","../src/core/aggregate.ts","../src/remote/existence_filter.ts","../src/remote/rpc_error.ts","../src/util/testing_hooks_spi.ts","../src/platform/browser/text_serializer.ts","../src/remote/bloom_filter.ts","../src/remote/remote_event.ts","../src/remote/watch_change.ts","../src/remote/serializer.ts","../src/local/target_data.ts","../src/local/local_serializer.ts","../src/local/indexeddb_bundle_cache.ts","../src/local/indexeddb_document_overlay_cache.ts","../src/local/indexeddb_globals_cache.ts","../src/index/firestore_index_value_writer.ts","../src/index/ordered_code_writer.ts","../src/index/index_byte_encoder.ts","../src/index/index_entry.ts","../src/model/target_index_matcher.ts","../src/util/logic_utils.ts","../src/local/memory_index_manager.ts","../src/local/indexeddb_index_manager.ts","../src/local/lru_garbage_collector.ts","../src/local/indexeddb_mutation_batch_impl.ts","../src/local/indexeddb_mutation_queue.ts","../src/core/target_id_generator.ts","../src/local/indexeddb_target_cache.ts","../src/local/lru_garbage_collector_impl.ts","../src/local/indexeddb_lru_delegate_impl.ts","../src/local/remote_document_change_buffer.ts","../src/local/indexeddb_remote_document_cache.ts","../src/local/overlayed_document.ts","../src/local/local_documents_view.ts","../src/local/memory_bundle_cache.ts","../src/local/memory_document_overlay_cache.ts","../src/local/memory_globals_cache.ts","../src/local/reference_set.ts","../src/local/memory_mutation_queue.ts","../src/local/memory_remote_document_cache.ts","../src/local/memory_target_cache.ts","../src/local/memory_persistence.ts","../src/local/indexeddb_schema_converter.ts","../src/local/indexeddb_persistence.ts","../src/local/indexeddb_schema.ts","../src/local/local_view_changes.ts","../src/local/query_context.ts","../src/local/query_engine.ts","../src/local/local_store_impl.ts","../src/local/shared_client_state_schema.ts","../src/local/shared_client_state.ts","../src/remote/connectivity_monitor_noop.ts","../src/platform/browser/connectivity_monitor.ts","../src/util/debug_uid.ts","../src/remote/rest_connection.ts","../src/remote/stream_bridge.ts","../src/platform/browser/webchannel_connection.ts","../src/platform/browser/dom.ts","../src/platform/browser/serializer.ts","../src/remote/backoff.ts","../src/remote/persistent_stream.ts","../src/remote/datastore.ts","../src/remote/online_state_tracker.ts","../src/remote/remote_store.ts","../src/util/async_queue.ts","../src/model/document_set.ts","../src/core/view_snapshot.ts","../src/core/event_manager.ts","../src/util/bundle_reader.ts","../src/core/bundle_impl.ts","../src/core/view.ts","../src/core/sync_engine_impl.ts","../src/core/component_provider.ts","../src/platform/browser/connection.ts","../src/util/byte_stream.ts","../src/util/async_observer.ts","../src/util/bundle_reader_impl.ts","../src/util/bundle_reader_sync_impl.ts","../src/core/transaction.ts","../src/core/transaction_runner.ts","../src/core/firestore_client.ts","../src/platform/browser/byte_stream_reader.ts","../src/util/array.ts","../src/api/long_polling_options.ts","../src/lite-api/components.ts","../src/lite-api/settings.ts","../src/lite-api/database.ts","../src/lite-api/reference.ts","../src/util/async_queue_impl.ts","../src/api/observer.ts","../src/api/bundle.ts","../src/api/database.ts","../src/lite-api/aggregate_types.ts","../src/lite-api/bytes.ts","../src/lite-api/field_path.ts","../src/lite-api/field_value.ts","../src/lite-api/geo_point.ts","../src/lite-api/vector_value.ts","../src/lite-api/user_data_reader.ts","../src/lite-api/snapshot.ts","../src/lite-api/query.ts","../src/lite-api/user_data_writer.ts","../src/lite-api/reference_impl.ts","../src/lite-api/aggregate.ts","../src/api/snapshot.ts","../src/platform/browser/snapshot_to_json.ts","../src/api/reference_impl.ts","../src/api/aggregate.ts","../src/api/cache_config.ts","../src/core/transaction_options.ts","../src/lite-api/write_batch.ts","../src/lite-api/transaction.ts","../src/api/transaction.ts","../src/lite-api/field_value_impl.ts","../src/api/write_batch.ts","../src/api/index_configuration.ts","../src/api/persistent_cache_index_manager.ts","../src/remote/internal_serializer.ts","../src/util/testing_hooks.ts","../src/register.ts","../src/index.rn.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Simple wrapper around a nullable UID. Mostly exists to make code more\n * readable.\n */\nexport class User {\n /** A user with a null UID. */\n static readonly UNAUTHENTICATED = new User(null);\n\n // TODO(mikelehen): Look into getting a proper uid-equivalent for\n // non-FirebaseAuth providers.\n static readonly GOOGLE_CREDENTIALS = new User('google-credentials-uid');\n static readonly FIRST_PARTY = new User('first-party-uid');\n static readonly MOCK_USER = new User('mock-user');\n\n constructor(readonly uid: string | null) {}\n\n isAuthenticated(): boolean {\n return this.uid != null;\n }\n\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */\n toKey(): string {\n if (this.isAuthenticated()) {\n return 'uid:' + this.uid;\n } else {\n return 'anonymous-user';\n }\n }\n\n isEqual(otherUser: User): boolean {\n return otherUser.uid === this.uid;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The semver (www.semver.org) version of the SDK. */\nimport { version } from '../../../firebase/package.json';\nexport let SDK_VERSION = version;\nexport function setSDKVersion(version: string): void {\n SDK_VERSION = version;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel, LogLevelString } from '@firebase/logger';\n\nimport { SDK_VERSION } from '../core/version';\nimport { formatJSON } from '../platform/format_json';\n\nexport { LogLevel, LogLevelString };\n\nconst logClient = new Logger('@firebase/firestore');\n\n// Helper methods are needed because variables can't be exported as read/write\nexport function getLogLevel(): LogLevel {\n return logClient.logLevel;\n}\n\n/**\n * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).\n *\n * @param logLevel - The verbosity you set for activity and error logging. Can\n * be any of the following values:\n *\n *

    \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 *\n * @param code generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(\n code: number,\n message: string,\n context?: Record\n): never;\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 *\n * @param id generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(id: number, context?: Record): never;\n\nexport function fail(\n id: number,\n messageOrContext?: string | Record,\n context?: Record\n): never {\n let message = 'Unexpected state';\n if (typeof messageOrContext === 'string') {\n message = messageOrContext;\n } else {\n context = messageOrContext;\n }\n _fail(id, message, context);\n}\n\nfunction _fail(\n id: number,\n failure: string,\n context?: Record\n): never {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n let message = `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ${failure} (ID: ${id.toString(\n 16\n )})`;\n if (context !== undefined) {\n try {\n const stringContext = JSON.stringify(context);\n message += ' CONTEXT: ' + stringContext;\n } catch (e) {\n message += ' CONTEXT: ' + context;\n }\n }\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 *\n * @param id generate a new unique value with `yarn assertion-idgenerate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n assertion: boolean,\n id: number,\n message: string,\n context?: Record\n): asserts assertion;\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 *\n * @param id generate a new unique value with `yarn assertion-id:generate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n assertion: boolean,\n id: number,\n context?: Record\n): asserts assertion;\n\nexport function hardAssert(\n assertion: boolean,\n id: number,\n messageOrContext?: string | Record,\n context?: Record\n): asserts assertion {\n let message = 'Unexpected state';\n if (typeof messageOrContext === 'string') {\n message = messageOrContext;\n } else {\n context = messageOrContext;\n }\n\n if (!assertion) {\n _fail(id, message, context);\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(0xdeb6, 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 { FirebaseApp, _isFirebaseServerApp } from '@firebase/app';\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 0xa539,\n 'Invalid tokenData returned from getToken()',\n { 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 0xa540,\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 0x7c5d,\n 'Invalid tokenData returned from getToken()',\n { 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 0x0807,\n 'Received invalid UID',\n { 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 private serverAppAppCheckToken: string | null = null;\n\n constructor(\n app: FirebaseApp,\n private appCheckProvider: Provider\n ) {\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n }\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n hardAssert(\n this.tokenListener === undefined,\n 0x0db8,\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 if (this.serverAppAppCheckToken) {\n return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n }\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 0xae0e,\n 'Invalid tokenResult returned from getToken()',\n { 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 private serverAppAppCheckToken: string | null = null;\n\n constructor(\n app: FirebaseApp,\n private appCheckProvider: Provider\n ) {\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n appCheckProvider.onInit(appCheck => {\n this.appCheck = appCheck;\n });\n }\n\n getToken(): Promise {\n if (this.serverAppAppCheckToken) {\n return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n }\n\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 0x0d8e,\n 'Invalid tokenResult returned from getToken()',\n { 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\n/** Compare strings in UTF-8 encoded byte order */\nexport function compareUtf8Strings(left: string, right: string): number {\n // Find the first differing character (a.k.a. \"UTF-16 code unit\") in the two strings and,\n // if found, use that character to determine the relative ordering of the two strings as a\n // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by\n // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8\n // and UTF-16 happen to represent Unicode code points.\n //\n // After finding the first pair of differing characters, there are two cases:\n //\n // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or\n // both are surrogates from a surrogate pair (that collectively represent code points greater\n // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the\n // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is\n // sufficient.\n //\n // Case 2: One character is a surrogate and the other is not. In this case the surrogate-\n // containing string is always ordered after the non-surrogate. This is because surrogates are\n // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations\n // and are lexicographically greater than the 1, 2, or 3-byte representations of code points\n // less than or equal to 0xFFFF.\n //\n // An example of why Case 2 is required is comparing the following two Unicode code points:\n //\n // |-----------------------|------------|---------------------|-----------------|\n // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding |\n // |-----------------------|------------|---------------------|-----------------|\n // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD |\n // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 |\n // |-----------------------|------------|---------------------|-----------------|\n //\n // A lexicographical comparison of the UTF-8 encodings of these code points would order\n // \"Replacement Character\" _before_ \"Grinning Face\" because 0xEF is less than 0xF0. However, a\n // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously\n // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out,\n // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate\n // pair with those that do not.\n const length = Math.min(left.length, right.length);\n for (let i = 0; i < length; i++) {\n const leftChar = left.charAt(i);\n const rightChar = right.charAt(i);\n if (leftChar !== rightChar) {\n return isSurrogate(leftChar) === isSurrogate(rightChar)\n ? primitiveComparator(leftChar, rightChar)\n : isSurrogate(leftChar)\n ? 1\n : -1;\n }\n }\n\n // Use the lengths of the strings to determine the overall comparison result since either the\n // strings were equal or one is a prefix of the other.\n return primitiveComparator(left.length, right.length);\n}\n\nconst MIN_SURROGATE = 0xd800;\nconst MAX_SURROGATE = 0xdfff;\n\nexport function isSurrogate(s: string): boolean {\n debugAssert(s.length === 1, `s.length == ${s.length}, but expected 1`);\n const c = s.charCodeAt(0);\n return c >= MIN_SURROGATE && c <= MAX_SURROGATE;\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 { Integer } from '@firebase/webchannel-wrapper/bloom-blob';\n\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { compareUtf8Strings, primitiveComparator } from '../util/misc';\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(0x027d, 'offset out of range', {\n offset,\n range: segments.length\n });\n }\n\n if (length === undefined) {\n length = segments.length - offset;\n } else if (length > segments.length - offset) {\n fail(0x06d2, 'length out of range', {\n length,\n range: segments.length - offset\n });\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 /**\n * Compare 2 paths segment by segment, prioritizing numeric IDs\n * (e.g., \"__id123__\") in numeric ascending order, followed by string\n * segments in lexicographical order.\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 comparison = BasePath.compareSegments(p1.get(i), p2.get(i));\n if (comparison !== 0) {\n return comparison;\n }\n }\n return primitiveComparator(p1.length, p2.length);\n }\n\n private static compareSegments(lhs: string, rhs: string): number {\n const isLhsNumeric = BasePath.isNumericId(lhs);\n const isRhsNumeric = BasePath.isNumericId(rhs);\n\n if (isLhsNumeric && !isRhsNumeric) {\n // Only lhs is numeric\n return -1;\n } else if (!isLhsNumeric && isRhsNumeric) {\n // Only rhs is numeric\n return 1;\n } else if (isLhsNumeric && isRhsNumeric) {\n // both numeric\n return BasePath.extractNumericId(lhs).compare(\n BasePath.extractNumericId(rhs)\n );\n } else {\n // both non-numeric\n return compareUtf8Strings(lhs, rhs);\n }\n }\n\n // Checks if a segment is a numeric ID (starts with \"__id\" and ends with \"__\").\n private static isNumericId(segment: string): boolean {\n return segment.startsWith('__id') && segment.endsWith('__');\n }\n\n private static extractNumericId(segment: string): Integer {\n return Integer.fromString(segment.substring(4, segment.length - 2));\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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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(0x3029, 'Unknown wrong type', { 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 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isPlainObject } from '../util/input_validation';\n\nimport { Code, FirestoreError } from './error';\n\n/**\n * A list of data types Firestore objects may serialize in their toJSON implemenetations.\n * @private\n * @internal\n */\nexport type JsonTypeDesc =\n | 'object'\n | 'string'\n | 'number'\n | 'boolean'\n | 'null'\n | 'undefined';\n\n/**\n * An association of JsonTypeDesc values to their native types.\n * @private\n * @internal\n */\nexport type TSType = T extends 'object'\n ? object\n : T extends 'string'\n ? string\n : T extends 'number'\n ? number\n : T extends 'boolean'\n ? boolean\n : T extends 'null'\n ? null\n : T extends 'undefined'\n ? undefined\n : never;\n\n/**\n * The representation of a JSON object property name and its type value.\n * @private\n * @internal\n */\nexport interface Property {\n value?: TSType;\n typeString: JsonTypeDesc;\n}\n\n/**\n * A type Firestore data types may use to define the fields used in their JSON serialization.\n * @private\n * @internal\n */\nexport interface JsonSchema {\n [key: string]: Property;\n}\n\n/**\n * Associates the JSON property type to the native type and sets them to be Required.\n * @private\n * @internal\n */\nexport type Json = {\n [K in keyof T]: Required['value'];\n};\n\n/**\n * Helper function to define a JSON schema {@link Property}.\n * @private\n * @internal\n */\nexport function property(\n typeString: T,\n optionalValue?: TSType\n): Property {\n const result: Property = {\n typeString\n };\n if (optionalValue) {\n result.value = optionalValue;\n }\n return result;\n}\n\n/**\n * Validates the JSON object based on the provided schema, and narrows the type to the provided\n * JSON schema.\n * @private\n * @internal\n *\n * @param json A JSON object to validate.\n * @param scheme a {@link JsonSchema} that defines the properties to validate.\n * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise.\n */\nexport function validateJSON(\n json: object,\n schema: S\n): json is Json {\n if (!isPlainObject(json)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'JSON must be an object');\n }\n let error: string | undefined = undefined;\n for (const key in schema) {\n if (schema[key]) {\n const typeString = schema[key].typeString;\n const value: { value: unknown } | undefined =\n 'value' in schema[key] ? { value: schema[key].value } : undefined;\n if (!(key in json)) {\n error = `JSON missing required field: '${key}'`;\n break;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const fieldValue = (json as any)[key];\n if (typeString && typeof fieldValue !== typeString) {\n error = `JSON field '${key}' must be a ${typeString}.`;\n break;\n } else if (value !== undefined && fieldValue !== value.value) {\n error = `Expected '${key}' field to equal '${value.value}'`;\n break;\n }\n }\n }\n if (error) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, error);\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 { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\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 static _jsonSchemaVersion: string = 'firestore/timestamp/1.0';\n static _jsonSchema = {\n type: property('string', Timestamp._jsonSchemaVersion),\n seconds: property('number'),\n nanoseconds: property('number')\n };\n\n /**\n * Returns a JSON-serializable representation of this `Timestamp`.\n */\n toJSON(): { seconds: number; nanoseconds: number; type: string } {\n return {\n type: Timestamp._jsonSchemaVersion,\n seconds: this.seconds,\n nanoseconds: this.nanoseconds\n };\n }\n\n /**\n * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}.\n */\n static fromJSON(json: object): Timestamp {\n if (validateJSON(json, Timestamp._jsonSchema)) {\n return new Timestamp(json.seconds, json.nanoseconds);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Timestamp from JSON.'\n );\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 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(0xe830, '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 { getGlobal, 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 `indexedDB` are guarded by SimpleDb.isAvailable() and getGlobal()\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 lastClosedDbVersion: number | null = null;\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 const globals = getGlobal();\n return wrapRequest(\n globals.indexedDB.deleteDatabase(name)\n ).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\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 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { FirestoreError } from '../api';\nimport { DocumentMap } from '../model/collections';\nimport {\n IndexOffset,\n indexOffsetComparator,\n newIndexOffsetFromDocument\n} from '../model/field_index';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { logDebug } from '../util/log';\n\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from './local_store';\nimport { LocalWriteResult } from './local_store_impl';\nimport { Persistence, Scheduler } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { isIndexedDbTransactionError } from './simple_db';\n\nconst LOG_TAG = 'IndexBackfiller';\n\n/** How long we wait to try running index backfill after SDK initialization. */\nconst INITIAL_BACKFILL_DELAY_MS = 15 * 1000;\n\n/** Minimum amount of time between backfill checks, after the first one. */\nconst REGULAR_BACKFILL_DELAY_MS = 60 * 1000;\n\n/** The maximum number of documents to process each time backfill() is called. */\nconst MAX_DOCUMENTS_TO_PROCESS = 50;\n\n/** This class is responsible for the scheduling of Index Backfiller. */\nexport class IndexBackfillerScheduler implements Scheduler {\n private task: DelayedOperation | null;\n\n constructor(\n private readonly asyncQueue: AsyncQueue,\n private readonly backfiller: IndexBackfiller\n ) {\n this.task = null;\n }\n\n start(): void {\n debugAssert(\n this.task === null,\n 'Cannot start an already started IndexBackfillerScheduler'\n );\n this.schedule(INITIAL_BACKFILL_DELAY_MS);\n }\n\n stop(): void {\n if (this.task) {\n this.task.cancel();\n this.task = null;\n }\n }\n\n get started(): boolean {\n return this.task !== null;\n }\n\n private schedule(delay: number): void {\n debugAssert(\n this.task === null,\n 'Cannot schedule IndexBackfiller while a task is pending'\n );\n logDebug(LOG_TAG, `Scheduled in ${delay}ms`);\n this.task = this.asyncQueue.enqueueAfterDelay(\n TimerId.IndexBackfill,\n delay,\n async () => {\n this.task = null;\n try {\n const documentsProcessed = await this.backfiller.backfill();\n logDebug(LOG_TAG, `Documents written: ${documentsProcessed}`);\n } catch (e) {\n if (isIndexedDbTransactionError(e as Error)) {\n logDebug(\n LOG_TAG,\n 'Ignoring IndexedDB error during index backfill: ',\n e\n );\n } else {\n await ignoreIfPrimaryLeaseLoss(e as FirestoreError);\n }\n }\n await this.schedule(REGULAR_BACKFILL_DELAY_MS);\n }\n );\n }\n}\n\n/** Implements the steps for backfilling indexes. */\nexport class IndexBackfiller {\n constructor(\n /**\n * LocalStore provides access to IndexManager and LocalDocumentView.\n * These properties will update when the user changes. Consequently,\n * making a local copy of IndexManager and LocalDocumentView will require\n * updates over time. The simpler solution is to rely on LocalStore to have\n * an up-to-date references to IndexManager and LocalDocumentStore.\n */\n private readonly localStore: LocalStore,\n private readonly persistence: Persistence\n ) {}\n\n async backfill(\n maxDocumentsToProcess: number = MAX_DOCUMENTS_TO_PROCESS\n ): Promise {\n return this.persistence.runTransaction(\n 'Backfill Indexes',\n 'readwrite-primary',\n txn => this.writeIndexEntries(txn, maxDocumentsToProcess)\n );\n }\n\n /** Writes index entries until the cap is reached. Returns the number of documents processed. */\n private writeIndexEntries(\n transaction: PersistenceTransaction,\n maxDocumentsToProcess: number\n ): PersistencePromise {\n const processedCollectionGroups = new Set();\n let documentsRemaining = maxDocumentsToProcess;\n let continueLoop = true;\n return PersistencePromise.doWhile(\n () => continueLoop === true && documentsRemaining > 0,\n () => {\n return this.localStore.indexManager\n .getNextCollectionGroupToUpdate(transaction)\n .next((collectionGroup: string | null) => {\n if (\n collectionGroup === null ||\n processedCollectionGroups.has(collectionGroup)\n ) {\n continueLoop = false;\n } else {\n logDebug(LOG_TAG, `Processing collection: ${collectionGroup}`);\n return this.writeEntriesForCollectionGroup(\n transaction,\n collectionGroup,\n documentsRemaining\n ).next(documentsProcessed => {\n documentsRemaining -= documentsProcessed;\n processedCollectionGroups.add(collectionGroup);\n });\n }\n });\n }\n ).next(() => maxDocumentsToProcess - documentsRemaining);\n }\n\n /**\n * Writes entries for the provided collection group. Returns the number of documents processed.\n */\n private writeEntriesForCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n documentsRemainingUnderCap: number\n ): PersistencePromise {\n // Use the earliest offset of all field indexes to query the local cache.\n return this.localStore.indexManager\n .getMinOffsetFromCollectionGroup(transaction, collectionGroup)\n .next(existingOffset =>\n this.localStore.localDocuments\n .getNextDocuments(\n transaction,\n collectionGroup,\n existingOffset,\n documentsRemainingUnderCap\n )\n .next(nextBatch => {\n const docs: DocumentMap = nextBatch.changes;\n return this.localStore.indexManager\n .updateIndexEntries(transaction, docs)\n .next(() => this.getNewOffset(existingOffset, nextBatch))\n .next(newOffset => {\n logDebug(LOG_TAG, `Updating offset: ${newOffset}`);\n return this.localStore.indexManager.updateCollectionGroup(\n transaction,\n collectionGroup,\n newOffset\n );\n })\n .next(() => docs.size);\n })\n );\n }\n\n /** Returns the next offset based on the provided documents. */\n private getNewOffset(\n existingOffset: IndexOffset,\n lookupResult: LocalWriteResult\n ): IndexOffset {\n let maxOffset: IndexOffset = existingOffset;\n lookupResult.changes.forEach((key, document) => {\n const newOffset: IndexOffset = newIndexOffsetFromDocument(document);\n if (indexOffsetComparator(newOffset, maxOffset) > 0) {\n maxOffset = newOffset;\n }\n });\n return new IndexOffset(\n maxOffset.readTime,\n maxOffset.documentKey,\n Math.max(lookupResult.batchId, existingOffset.largestBatchId)\n );\n }\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequenceNumber } from './types';\n\n/**\n * `SequenceNumberSyncer` defines the methods required to keep multiple instances of a\n * `ListenSequence` in sync.\n */\nexport interface SequenceNumberSyncer {\n // Notify the syncer that a new sequence number has been used.\n writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void;\n // Setting this property allows the syncer to notify when a sequence number has been used, and\n // and lets the ListenSequence adjust its internal previous value accordingly.\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null;\n}\n\n/**\n * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to\n * exceed. All subsequent calls to next will return increasing values. If provided with a\n * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as\n * well as write out sequence numbers that it produces via `next()`.\n */\nexport class ListenSequence {\n static readonly INVALID: ListenSequenceNumber = -1;\n\n private writeNewSequenceNumber?: (\n newSequenceNumber: ListenSequenceNumber\n ) => void;\n\n constructor(\n private previousValue: ListenSequenceNumber,\n sequenceNumberSyncer?: SequenceNumberSyncer\n ) {\n if (sequenceNumberSyncer) {\n sequenceNumberSyncer.sequenceNumberHandler = sequenceNumber =>\n this.setPreviousValue(sequenceNumber);\n this.writeNewSequenceNumber = sequenceNumber =>\n sequenceNumberSyncer.writeSequenceNumber(sequenceNumber);\n }\n }\n\n private setPreviousValue(\n externalPreviousValue: ListenSequenceNumber\n ): ListenSequenceNumber {\n this.previousValue = Math.max(externalPreviousValue, this.previousValue);\n return this.previousValue;\n }\n\n next(): ListenSequenceNumber {\n const nextValue = ++this.previousValue;\n if (this.writeNewSequenceNumber) {\n this.writeNewSequenceNumber(nextValue);\n }\n return nextValue;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Sentinel value that sorts before any Mutation Batch ID. */\nexport const BATCHID_UNKNOWN = -1;\n\n// An Object whose keys and values are strings.\nexport interface StringMap {\n [key: string]: string;\n}\n\n/**\n * Returns whether a variable is either undefined or null.\n */\nexport function isNullOrUndefined(value: unknown): value is null | undefined {\n return value === null || value === undefined;\n}\n\n/** Returns whether the value represents -0. */\nexport function isNegativeZero(value: number): boolean {\n // Detect if the value is -0.0. Based on polyfill from\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is\n return value === 0 && 1 / value === 1 / -0;\n}\n\n/**\n * Returns whether a value is an integer and in the safe integer range\n * @param value - The value to test for being an integer and in the safe range\n */\nexport function isSafeInteger(value: unknown): boolean {\n return (\n typeof value === 'number' &&\n Number.isInteger(value) &&\n !isNegativeZero(value) &&\n value <= Number.MAX_SAFE_INTEGER &&\n value >= Number.MIN_SAFE_INTEGER\n );\n}\n\n/** The subset of the browser's Window interface used by the SDK. */\nexport interface WindowLike {\n readonly localStorage: Storage;\n readonly indexedDB: IDBFactory | null;\n addEventListener(type: string, listener: EventListener): void;\n removeEventListener(type: string, listener: EventListener): void;\n}\n\n/** The subset of the browser's Document interface used by the SDK. */\nexport interface DocumentLike {\n readonly visibilityState: DocumentVisibilityState;\n addEventListener(type: string, listener: EventListener): void;\n removeEventListener(type: string, listener: EventListener): void;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ResourcePath } from '../model/path';\nimport { fail, hardAssert } from '../util/assert';\n\n/**\n * Helpers for dealing with resource paths stored in IndexedDB.\n *\n * Resource paths in their canonical string form do not sort as the server\n * sorts them. Specifically the server splits paths into segments first and then\n * sorts, putting end-of-segment before any character. In a UTF-8 string\n * encoding the slash ('/') that denotes the end-of-segment naturally comes\n * after other characters so the intent here is to encode the path delimiters in\n * such a way that the resulting strings sort naturally.\n *\n * Resource paths are also used for prefix scans so it's important to\n * distinguish whole segments from any longer segments of which they might be a\n * prefix. For example, it's important to make it possible to scan documents in\n * a collection \"foo\" without encountering documents in a collection \"foobar\".\n *\n * Separate from the concerns about resource path ordering and separation,\n * On Android, SQLite imposes additional restrictions since it does not handle\n * keys with embedded NUL bytes particularly well. Rather than change the\n * implementation we keep the encoding identical to keep the ports similar.\n *\n * Taken together this means resource paths when encoded for storage in\n * IndexedDB have the following characteristics:\n *\n * * Segment separators (\"/\") sort before everything else.\n * * All paths have a trailing separator.\n * * NUL bytes do not exist in the output, since IndexedDB doesn't treat them\n * well.\n *\n * Therefore resource paths are encoded into string form using the following\n * rules:\n *\n * * '\\x01' is used as an escape character.\n * * Path separators are encoded as \"\\x01\\x01\"\n * * NUL bytes are encoded as \"\\x01\\x10\"\n * * '\\x01' is encoded as \"\\x01\\x11\"\n *\n * This encoding leaves some room between path separators and the NUL byte\n * just in case we decide to support integer document ids after all.\n *\n * Note that characters treated specially by the backend ('.', '/', and '~')\n * are not treated specially here. This class assumes that any unescaping of\n * resource path strings into actual ResourcePath objects will handle these\n * characters there.\n */\nexport type EncodedResourcePath = string;\n\nconst escapeChar = '\\u0001';\nconst encodedSeparatorChar = '\\u0001';\nconst encodedNul = '\\u0010';\nconst encodedEscape = '\\u0011';\n\n/**\n * Encodes a resource path into a IndexedDb-compatible string form.\n */\nexport function encodeResourcePath(path: ResourcePath): EncodedResourcePath {\n let result = '';\n for (let i = 0; i < path.length; i++) {\n if (result.length > 0) {\n result = encodeSeparator(result);\n }\n result = encodeSegment(path.get(i), result);\n }\n return encodeSeparator(result);\n}\n\n/** Encodes a single segment of a resource path into the given result */\nfunction encodeSegment(segment: string, resultBuf: string): string {\n let result = resultBuf;\n const length = segment.length;\n for (let i = 0; i < length; i++) {\n const c = segment.charAt(i);\n switch (c) {\n case '\\0':\n result += escapeChar + encodedNul;\n break;\n case escapeChar:\n result += escapeChar + encodedEscape;\n break;\n default:\n result += c;\n }\n }\n return result;\n}\n\n/** Encodes a path separator into the given result */\nfunction encodeSeparator(result: string): string {\n return result + escapeChar + encodedSeparatorChar;\n}\n\n/**\n * Decodes the given IndexedDb-compatible string form of a resource path into\n * a ResourcePath instance. Note that this method is not suitable for use with\n * decoding resource names from the server; those are One Platform format\n * strings.\n */\nexport function decodeResourcePath(path: EncodedResourcePath): ResourcePath {\n // Event the empty path must encode as a path of at least length 2. A path\n // with exactly 2 must be the empty path.\n const length = path.length;\n hardAssert(length >= 2, 0xfb98, 'Invalid path', { path });\n if (length === 2) {\n hardAssert(\n path.charAt(0) === escapeChar && path.charAt(1) === encodedSeparatorChar,\n 0xdb51,\n 'Non-empty path had length 2',\n { path }\n );\n return ResourcePath.emptyPath();\n }\n\n // Escape characters cannot exist past the second-to-last position in the\n // source value.\n const lastReasonableEscapeIndex = length - 2;\n\n const segments: string[] = [];\n let segmentBuilder = '';\n\n for (let start = 0; start < length; ) {\n // The last two characters of a valid encoded path must be a separator, so\n // there must be an end to this segment.\n const end = path.indexOf(escapeChar, start);\n if (end < 0 || end > lastReasonableEscapeIndex) {\n fail(0xc553, 'Invalid encoded resource path', { path });\n }\n\n const next = path.charAt(end + 1);\n switch (next) {\n case encodedSeparatorChar:\n const currentPiece = path.substring(start, end);\n let segment;\n if (segmentBuilder.length === 0) {\n // Avoid copying for the common case of a segment that excludes \\0\n // and \\001\n segment = currentPiece;\n } else {\n segmentBuilder += currentPiece;\n segment = segmentBuilder;\n segmentBuilder = '';\n }\n segments.push(segment);\n break;\n case encodedNul:\n segmentBuilder += path.substring(start, end);\n segmentBuilder += '\\0';\n break;\n case encodedEscape:\n // The escape character can be used in the output to encode itself.\n segmentBuilder += path.substring(start, end + 1);\n break;\n default:\n fail(0xeeef, 'Invalid encoded resource path', { path });\n }\n\n start = end + 2;\n }\n\n return new ResourcePath(segments);\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 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 * Representation of a byte array that is safe for\n * use in an IndexedDb key. The value is either\n * a \"sortable byte string\", which is key safe in\n * Safari/WebKit, or the value is a Uint8Array,\n * which is key safe in other browsers.\n */\nexport type KeySafeBytes = Uint8Array | string;\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 KeySafeBytes,\n KeySafeBytes,\n KeySafeBytes,\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];\nexport const V18_STORES = V17_STORES;\n\n/**\n * The list of all default IndexedDB stores used throughout the SDK. This is\n * used when creating transactions so that access across all stores is done\n * atomically.\n */\nexport const ALL_STORES = V12_STORES;\n\n/** Returns the object stores for the provided schema. */\nexport function getObjectStores(schemaVersion: number): string[] {\n if (schemaVersion === 18) {\n return V18_STORES;\n } else 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(0xeb55, 'Only schema versions >11 are supported');\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 { ListenSequenceNumber } from '../core/types';\nimport { debugCast } from '../util/assert';\n\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDb, SimpleDbStore, SimpleDbTransaction } from './simple_db';\n\nexport class IndexedDbTransaction extends PersistenceTransaction {\n constructor(\n readonly simpleDbTransaction: SimpleDbTransaction,\n readonly currentSequenceNumber: ListenSequenceNumber\n ) {\n super();\n }\n}\n\nexport function getStore(\n txn: PersistenceTransaction,\n store: string\n): SimpleDbStore {\n const indexedDbTransaction = debugCast(txn, IndexedDbTransaction);\n return SimpleDb.getStore(\n indexedDbTransaction.simpleDbTransaction,\n store\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from './assert';\n\nexport interface Dict {\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(0xaad2, 'Red node has red child', {\n key: this.key,\n value: this.value\n });\n }\n if (this.right.isRed()) {\n throw fail(0x3721, 'Right child of (`key`, `value`) is red', {\n key: this.key,\n value: this.value\n });\n }\n const blackDepth = (this.left as LLRBNode).check();\n if (blackDepth !== (this.right as LLRBNode).check()) {\n throw fail(0x6d2d, '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(0xe1a6, 'LLRBEmptyNode has no key.');\n }\n get value(): never {\n throw fail(0x3f0d, 'LLRBEmptyNode has no value.');\n }\n get color(): never {\n throw fail(0x4157, 'LLRBEmptyNode has no color.');\n }\n get left(): never {\n throw fail(0x741e, 'LLRBEmptyNode has no left child.');\n }\n get right(): never {\n throw fail(0x901e, '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 { base64, DecodeBase64StringError } from '@firebase/util';\n\nimport { Base64DecodeError } from '../../util/base64_decode_error';\n\n// WebSafe uses a different URL-encoding safe alphabet that doesn't match\n// the encoding used on the backend.\nconst WEB_SAFE = false;\n\n/** Converts a Base64 encoded string to a binary string. */\nexport function decodeBase64(encoded: string): string {\n try {\n return String.fromCharCode.apply(\n null,\n // We use `decodeStringToByteArray()` instead of `decodeString()` since\n // `decodeString()` returns Unicode strings, which doesn't match the values\n // returned by `atob()`'s Latin1 representation.\n base64.decodeStringToByteArray(encoded, WEB_SAFE)\n );\n } catch (e) {\n if (e instanceof DecodeBase64StringError) {\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 const bytes: number[] = [];\n for (let i = 0; i < raw.length; i++) {\n bytes[i] = raw.charCodeAt(i);\n }\n return base64.encodeByteArray(bytes, WEB_SAFE);\n}\n\n/** True if and only if the Base64 conversion functions are available. */\nexport function isBase64Available(): boolean {\n return true;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 { 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, 0x986a, '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, 0xb5de, 'invalid timestamp', {\n timestamp: date\n });\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 readonly isUsingEmulator: 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 {\n arrayEquals,\n compareUtf8Strings,\n primitiveComparator\n} 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(0x6e87, 'Invalid value type', { 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(0xcbf8, 'Unexpected value type', { 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 compareUtf8Strings(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(0x5ae0, '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 = compareUtf8Strings(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(0xee4d, 'Invalid value type', { 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(0x34ae, 'Invalid value type', { 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(0x8c66, 'Invalid value type', { 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(0xf207, 'Invalid value type', { 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(\n 0xa786,\n \"Trying to compare documents on fields that don't exist\"\n );\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 other.nullValue === undefined &&\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(0xb8a2, 'Unknown FieldFilter operator', {\n operator: this.op\n });\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(0x4bef, '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 (\n other !== null &&\n other.nullValue === undefined &&\n !arrayValueContains(this.value.arrayValue!, other)\n );\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(0x4d4e, 'Unknown direction', { 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 0x7f90,\n 'server transform result count should match field transform count',\n {\n serverTransformResultCount: serverTransformResults.length,\n fieldTransformCount: fieldTransforms.length\n }\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 0xe5da,\n 'Mutations sent must equal results received',\n {\n mutationsSent: batch.mutations.length,\n resultsReceived: results.length\n }\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 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 { FieldPath } from '../model/path';\n\n/**\n * Union type representing the aggregate type to be performed.\n */\nexport type AggregateType = 'count' | 'avg' | 'sum';\n\n/**\n * Represents an Aggregate to be performed over a query result set.\n */\nexport interface Aggregate {\n readonly fieldPath?: FieldPath;\n readonly alias: string;\n readonly aggregateType: AggregateType;\n}\n\n/**\n * Concrete implementation of the Aggregate type.\n */\nexport class AggregateImpl implements Aggregate {\n constructor(\n readonly alias: string,\n readonly aggregateType: AggregateType,\n readonly fieldPath?: 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 { 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(0xfdaa, '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(0x3c6b, '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(0x999b, '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(0x3019, '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(0x9481, '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 0x0ca9,\n '`pendingResponses` is less than 0. This indicates that the SDK received more target acks from the server than expected. The SDK should not continue to operate.',\n { pendingResponses: this.pendingResponses }\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 private pendingDocumentUpdatesByTarget = documentTargetMap();\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(0xddd6, 'Unknown target watch change state', {\n state: targetChange.state\n });\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 0x4e2d,\n 'Single document existence filter with count',\n { 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 for this\n // target. This resolves the limbo state of the document, removing it\n // from 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.ensureDocumentUpdateByTarget(key).has(targetId) &&\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.pendingDocumentUpdatesByTarget = documentTargetMap();\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.pendingDocumentUpdatesByTarget =\n this.pendingDocumentUpdatesByTarget.insert(\n document.key,\n this.ensureDocumentUpdateByTarget(document.key).add(targetId)\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 this.pendingDocumentTargetMapping =\n this.pendingDocumentTargetMapping.insert(\n key,\n this.ensureDocumentTargetMapping(key).add(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 private ensureDocumentUpdateByTarget(key: DocumentKey): SortedSet {\n let targetMapping = this.pendingDocumentUpdatesByTarget.get(key);\n\n if (!targetMapping) {\n targetMapping = new SortedSet(primitiveComparator);\n this.pendingDocumentUpdatesByTarget =\n this.pendingDocumentUpdatesByTarget.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\n/**\n * Returns a Timestamp typed object given protobuf timestamp value.\n */\nexport function 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 0xe30b,\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 0x3f41,\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, 0xc050, \"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 0x27ce,\n 'Tried to deserialize invalid key',\n { 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 0x71a3,\n 'tried to deserialize invalid key',\n { 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 0xaa33,\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 0x0f36,\n 'Tried to deserialize a missing document from a found document.'\n );\n hardAssert(\n !!result.readTime,\n 0x5995,\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(0x1c42, 'invalid batch get response', { 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(0x2d51, 'Unknown change type', { 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(0x9991, '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(0x40d7, 'Unknown mutation type', {\n mutationType: mutation.type\n });\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(0x05b7, 'unknown mutation proto', { 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(0x6b69, '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 0x3811,\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(0x51c2, 'Unknown transform', {\n transform: fieldTransform.transform\n });\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 0x40f6,\n 'Unknown server value transform proto',\n { 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(0x40c8, 'Unknown transform proto', { 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 0x07ae,\n 'DocumentsTarget contained other than 1 document',\n {\n count\n }\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 0xfe26,\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(0x713b, '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(0x7591, 'Unknown filter', { 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(0xe2fe, 'Unspecified operator');\n default:\n return fail(0xc54a, '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(0x0402, '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(0xd65d, 'Unrecognized filter type', { 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(0xef81, 'Unspecified filter');\n default:\n return fail(0xed36, '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(0xdd85, '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(0xe230, 'Unexpected Document', { document });\n }\n return remoteDoc;\n}\n\nexport function toDbTimestampKey(\n snapshotVersion: SnapshotVersion\n): DbTimestampKey {\n const timestamp = snapshotVersion.toTimestamp();\n return [timestamp.seconds, timestamp.nanoseconds];\n}\n\nexport function fromDbTimestampKey(\n dbTimestampKey: DbTimestampKey\n): SnapshotVersion {\n const timestamp = new Timestamp(dbTimestampKey[0], dbTimestampKey[1]);\n return SnapshotVersion.fromTimestamp(timestamp);\n}\n\nexport function toDbTimestamp(snapshotVersion: SnapshotVersion): DbTimestamp {\n const timestamp = snapshotVersion.toTimestamp();\n return { seconds: timestamp.seconds, nanoseconds: timestamp.nanoseconds };\n}\n\nfunction fromDbTimestamp(dbTimestamp: DbTimestamp): SnapshotVersion {\n const timestamp = new Timestamp(dbTimestamp.seconds, dbTimestamp.nanoseconds);\n return SnapshotVersion.fromTimestamp(timestamp);\n}\n\n/** Encodes a batch of mutations into a DbMutationBatch for local storage. */\nexport function toDbMutationBatch(\n localSerializer: LocalSerializer,\n userId: string,\n batch: MutationBatch\n): DbMutationBatch {\n const serializedBaseMutations = batch.baseMutations.map(m =>\n toMutation(localSerializer.remoteSerializer, m)\n );\n const serializedMutations = batch.mutations.map(m =>\n toMutation(localSerializer.remoteSerializer, m)\n );\n return {\n userId,\n batchId: batch.batchId,\n localWriteTimeMs: batch.localWriteTime.toMillis(),\n baseMutations: serializedBaseMutations,\n mutations: serializedMutations\n };\n}\n\n/** Decodes a DbMutationBatch into a MutationBatch */\nexport function fromDbMutationBatch(\n localSerializer: LocalSerializer,\n dbBatch: DbMutationBatch\n): MutationBatch {\n const baseMutations = (dbBatch.baseMutations || []).map(m =>\n fromMutation(localSerializer.remoteSerializer, m)\n );\n\n // Squash old transform mutations into existing patch or set mutations.\n // The replacement of representing `transforms` with `update_transforms`\n // on the SDK means that old `transform` mutations stored in IndexedDB need\n // to be updated to `update_transforms`.\n // TODO(b/174608374): Remove this code once we perform a schema migration.\n for (let i = 0; i < dbBatch.mutations.length - 1; ++i) {\n const currentMutation = dbBatch.mutations[i];\n const hasTransform =\n i + 1 < dbBatch.mutations.length &&\n dbBatch.mutations[i + 1].transform !== undefined;\n if (hasTransform) {\n debugAssert(\n dbBatch.mutations[i].transform === undefined &&\n dbBatch.mutations[i].update !== undefined,\n 'TransformMutation should be preceded by a patch or set mutation'\n );\n const transformMutation = dbBatch.mutations[i + 1];\n currentMutation.updateTransforms =\n transformMutation.transform!.fieldTransforms;\n dbBatch.mutations.splice(i + 1, 1);\n ++i;\n }\n }\n\n const mutations = dbBatch.mutations.map(m =>\n fromMutation(localSerializer.remoteSerializer, m)\n );\n const timestamp = Timestamp.fromMillis(dbBatch.localWriteTimeMs);\n return new MutationBatch(\n dbBatch.batchId,\n timestamp,\n baseMutations,\n mutations\n );\n}\n\n/** Decodes a DbTarget into TargetData */\nexport function fromDbTarget(dbTarget: DbTarget): TargetData {\n const version = fromDbTimestamp(dbTarget.readTime);\n const lastLimboFreeSnapshotVersion =\n dbTarget.lastLimboFreeSnapshotVersion !== undefined\n ? fromDbTimestamp(dbTarget.lastLimboFreeSnapshotVersion)\n : SnapshotVersion.min();\n\n let target: Target;\n if (isDocumentQuery(dbTarget.query)) {\n target = fromDocumentsTarget(dbTarget.query);\n } else {\n target = fromQueryTarget(dbTarget.query);\n }\n return new TargetData(\n target,\n dbTarget.targetId,\n TargetPurpose.Listen,\n dbTarget.lastListenSequenceNumber,\n version,\n lastLimboFreeSnapshotVersion,\n ByteString.fromBase64String(dbTarget.resumeToken)\n );\n}\n\n/** Encodes TargetData into a DbTarget for storage locally. */\nexport function toDbTarget(\n localSerializer: LocalSerializer,\n targetData: TargetData\n): DbTarget {\n debugAssert(\n TargetPurpose.Listen === targetData.purpose,\n 'Only queries with purpose ' +\n TargetPurpose.Listen +\n ' may be stored, got ' +\n targetData.purpose\n );\n const dbTimestamp = toDbTimestamp(targetData.snapshotVersion);\n const dbLastLimboFreeTimestamp = toDbTimestamp(\n targetData.lastLimboFreeSnapshotVersion\n );\n let queryProto: DbQuery;\n if (targetIsDocumentTarget(targetData.target)) {\n queryProto = toDocumentsTarget(\n localSerializer.remoteSerializer,\n targetData.target\n );\n } else {\n queryProto = toQueryTarget(\n localSerializer.remoteSerializer,\n targetData.target\n ).queryTarget;\n }\n\n // We can't store the resumeToken as a ByteString in IndexedDb, so we\n // convert it to a base64 string for storage.\n const resumeToken = targetData.resumeToken.toBase64();\n\n // lastListenSequenceNumber is always 0 until we do real GC.\n return {\n targetId: targetData.targetId,\n canonicalId: canonifyTarget(targetData.target),\n readTime: dbTimestamp,\n resumeToken,\n lastListenSequenceNumber: targetData.sequenceNumber,\n lastLimboFreeSnapshotVersion: dbLastLimboFreeTimestamp,\n query: queryProto\n };\n}\n\n/**\n * A helper function for figuring out what kind of query has been stored.\n */\nfunction isDocumentQuery(dbQuery: DbQuery): dbQuery is PublicDocumentsTarget {\n return (dbQuery as PublicDocumentsTarget).documents !== undefined;\n}\n\n/** Encodes a DbBundle to a BundleMetadata object. */\nexport function fromDbBundle(dbBundle: DbBundle): BundleMetadata {\n return {\n id: dbBundle.bundleId,\n createTime: fromDbTimestamp(dbBundle.createTime),\n version: dbBundle.version\n };\n}\n\n/** Encodes a BundleMetadata to a DbBundle. */\nexport function toDbBundle(metadata: ProtoBundleMetadata): DbBundle {\n return {\n bundleId: metadata.id!,\n createTime: toDbTimestamp(fromVersion(metadata.createTime!)),\n version: metadata.version!\n };\n}\n\n/** Encodes a DbNamedQuery to a NamedQuery. */\nexport function fromDbNamedQuery(dbNamedQuery: DbNamedQuery): NamedQuery {\n return {\n name: dbNamedQuery.name,\n query: fromBundledQuery(dbNamedQuery.bundledQuery),\n readTime: fromDbTimestamp(dbNamedQuery.readTime)\n };\n}\n\n/** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */\nexport function toDbNamedQuery(query: ProtoNamedQuery): DbNamedQuery {\n return {\n name: query.name!,\n readTime: toDbTimestamp(fromVersion(query.readTime!)),\n bundledQuery: query.bundledQuery!\n };\n}\n\n/**\n * Encodes a `BundledQuery` from bundle proto to a Query object.\n *\n * This reconstructs the original query used to build the bundle being loaded,\n * including features exists only in SDKs (for example: limit-to-last).\n */\nexport function fromBundledQuery(bundledQuery: ProtoBundledQuery): Query {\n const query = convertQueryTargetToQuery({\n parent: bundledQuery.parent!,\n structuredQuery: bundledQuery.structuredQuery!\n });\n if (bundledQuery.limitType === 'LAST') {\n debugAssert(\n !!query.limit,\n 'Bundled query has limitType LAST, but limit is null'\n );\n return queryWithLimit(query, query.limit, LimitType.Last);\n }\n return query;\n}\n\n/** Encodes a NamedQuery proto object to a NamedQuery model object. */\nexport function fromProtoNamedQuery(namedQuery: ProtoNamedQuery): NamedQuery {\n return {\n name: namedQuery.name!,\n query: fromBundledQuery(namedQuery.bundledQuery!),\n readTime: fromVersion(namedQuery.readTime!)\n };\n}\n\n/** Decodes a BundleMetadata proto into a BundleMetadata object. */\nexport function fromBundleMetadata(\n metadata: ProtoBundleMetadata\n): BundleMetadata {\n return {\n id: metadata.id!,\n version: metadata.version!,\n createTime: fromVersion(metadata.createTime!)\n };\n}\n\n/** Encodes a DbDocumentOverlay object to an Overlay model object. */\nexport function fromDbDocumentOverlay(\n localSerializer: LocalSerializer,\n dbDocumentOverlay: DbDocumentOverlay\n): Overlay {\n return new Overlay(\n dbDocumentOverlay.largestBatchId,\n fromMutation(\n localSerializer.remoteSerializer,\n dbDocumentOverlay.overlayMutation\n )\n );\n}\n\n/** Decodes an Overlay model object into a DbDocumentOverlay object. */\nexport function toDbDocumentOverlay(\n localSerializer: LocalSerializer,\n userId: string,\n overlay: Overlay\n): DbDocumentOverlay {\n const [_, collectionPath, documentId] = toDbDocumentOverlayKey(\n userId,\n overlay.mutation.key\n );\n return {\n userId,\n collectionPath,\n documentId,\n collectionGroup: overlay.mutation.key.getCollectionGroup(),\n largestBatchId: overlay.largestBatchId,\n overlayMutation: toMutation(\n localSerializer.remoteSerializer,\n overlay.mutation\n )\n };\n}\n\n/**\n * Returns the DbDocumentOverlayKey corresponding to the given user and\n * document key.\n */\nexport function toDbDocumentOverlayKey(\n userId: string,\n docKey: DocumentKey\n): DbDocumentOverlayKey {\n const docId = docKey.path.lastSegment();\n const collectionPath = encodeResourcePath(docKey.path.popLast());\n return [userId, collectionPath, docId];\n}\n\nexport function toDbIndexConfiguration(\n index: FieldIndex\n): DbIndexConfiguration {\n return {\n indexId: index.indexId,\n collectionGroup: index.collectionGroup,\n fields: index.fields.map(s => [s.fieldPath.canonicalString(), s.kind])\n };\n}\n\nexport function fromDbIndexConfiguration(\n index: DbIndexConfiguration,\n state: DbIndexState | null\n): FieldIndex {\n const decodedState = state\n ? new IndexState(\n state.sequenceNumber,\n new IndexOffset(\n fromDbTimestamp(state.readTime),\n new DocumentKey(decodeResourcePath(state.documentKey)),\n state.largestBatchId\n )\n )\n : IndexState.empty();\n const decodedSegments = index.fields.map(\n ([fieldPath, kind]) =>\n new IndexSegment(FieldPath.fromServerFormat(fieldPath), kind)\n );\n return new FieldIndex(\n index.indexId!,\n index.collectionGroup,\n decodedSegments,\n decodedState\n );\n}\n\nexport function toDbIndexState(\n indexId: number,\n uid: string,\n sequenceNumber: number,\n offset: IndexOffset\n): DbIndexState {\n return {\n indexId,\n uid,\n sequenceNumber,\n readTime: toDbTimestamp(offset.readTime),\n documentKey: encodeResourcePath(offset.documentKey.path),\n largestBatchId: offset.largestBatchId\n };\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BundleMetadata, NamedQuery } from '../core/bundle';\nimport {\n BundleMetadata as ProtoBundleMetadata,\n NamedQuery as ProtoNamedQuery\n} from '../protos/firestore_bundle_proto';\n\nimport { BundleCache } from './bundle_cache';\nimport { DbBundle, DbNamedQuery } from './indexeddb_schema';\nimport {\n DbBundlesKey,\n DbBundleStore,\n DbNamedQueriesKey,\n DbNamedQueryStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n fromDbBundle,\n fromDbNamedQuery,\n toDbBundle,\n toDbNamedQuery\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\nexport class IndexedDbBundleCache implements BundleCache {\n getBundleMetadata(\n transaction: PersistenceTransaction,\n bundleId: string\n ): PersistencePromise {\n return bundlesStore(transaction)\n .get(bundleId)\n .next(bundle => {\n if (bundle) {\n return fromDbBundle(bundle);\n }\n return undefined;\n });\n }\n\n saveBundleMetadata(\n transaction: PersistenceTransaction,\n bundleMetadata: ProtoBundleMetadata\n ): PersistencePromise {\n return bundlesStore(transaction).put(toDbBundle(bundleMetadata));\n }\n\n getNamedQuery(\n transaction: PersistenceTransaction,\n queryName: string\n ): PersistencePromise {\n return namedQueriesStore(transaction)\n .get(queryName)\n .next(query => {\n if (query) {\n return fromDbNamedQuery(query);\n }\n return undefined;\n });\n }\n\n saveNamedQuery(\n transaction: PersistenceTransaction,\n query: ProtoNamedQuery\n ): PersistencePromise {\n return namedQueriesStore(transaction).put(toDbNamedQuery(query));\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the bundles object store.\n */\nfunction bundlesStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbBundleStore);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the namedQueries object store.\n */\nfunction namedQueriesStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbNamedQueryStore);\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport {\n DocumentKeySet,\n MutationMap,\n OverlayMap,\n newOverlayMap\n} from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { Overlay } from '../model/overlay';\nimport { ResourcePath } from '../model/path';\n\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { encodeResourcePath } from './encoded_resource_path';\nimport { DbDocumentOverlay } from './indexeddb_schema';\nimport {\n DbDocumentOverlayCollectionGroupOverlayIndex,\n DbDocumentOverlayCollectionPathOverlayIndex,\n DbDocumentOverlayKey,\n DbDocumentOverlayStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n fromDbDocumentOverlay,\n LocalSerializer,\n toDbDocumentOverlay,\n toDbDocumentOverlayKey\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\n/**\n * Implementation of DocumentOverlayCache using IndexedDb.\n */\nexport class IndexedDbDocumentOverlayCache implements DocumentOverlayCache {\n /**\n * @param serializer - The document serializer.\n * @param userId - The userId for which we are accessing overlays.\n */\n constructor(\n private readonly serializer: LocalSerializer,\n private readonly userId: string\n ) {}\n\n static forUser(\n serializer: LocalSerializer,\n user: User\n ): IndexedDbDocumentOverlayCache {\n const userId = user.uid || '';\n return new IndexedDbDocumentOverlayCache(serializer, userId);\n }\n\n getOverlay(\n transaction: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return documentOverlayStore(transaction)\n .get(toDbDocumentOverlayKey(this.userId, key))\n .next(dbOverlay => {\n if (dbOverlay) {\n return fromDbDocumentOverlay(this.serializer, dbOverlay);\n }\n return null;\n });\n }\n\n getOverlays(\n transaction: PersistenceTransaction,\n keys: DocumentKey[]\n ): PersistencePromise {\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 const promises: Array> = [];\n overlays.forEach((_, mutation) => {\n const overlay = new Overlay(largestBatchId, mutation);\n promises.push(this.saveOverlay(transaction, overlay));\n });\n return PersistencePromise.waitFor(promises);\n }\n\n removeOverlaysForBatchId(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet,\n batchId: number\n ): PersistencePromise {\n const collectionPaths = new Set();\n\n // Get the set of unique collection paths.\n documentKeys.forEach(key =>\n collectionPaths.add(encodeResourcePath(key.getCollectionPath()))\n );\n\n const promises: Array> = [];\n collectionPaths.forEach(collectionPath => {\n const range = IDBKeyRange.bound(\n [this.userId, collectionPath, batchId],\n [this.userId, collectionPath, batchId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n promises.push(\n documentOverlayStore(transaction).deleteAll(\n DbDocumentOverlayCollectionPathOverlayIndex,\n range\n )\n );\n });\n return PersistencePromise.waitFor(promises);\n }\n\n getOverlaysForCollection(\n transaction: PersistenceTransaction,\n collection: ResourcePath,\n sinceBatchId: number\n ): PersistencePromise {\n const result = newOverlayMap();\n const collectionPath = encodeResourcePath(collection);\n // We want batch IDs larger than `sinceBatchId`, and so the lower bound\n // is not inclusive.\n const range = IDBKeyRange.bound(\n [this.userId, collectionPath, sinceBatchId],\n [this.userId, collectionPath, Number.POSITIVE_INFINITY],\n /*lowerOpen=*/ true\n );\n return documentOverlayStore(transaction)\n .loadAll(DbDocumentOverlayCollectionPathOverlayIndex, range)\n .next(dbOverlays => {\n for (const dbOverlay of dbOverlays) {\n const overlay = fromDbDocumentOverlay(this.serializer, dbOverlay);\n result.set(overlay.getKey(), overlay);\n }\n return result;\n });\n }\n\n getOverlaysForCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n sinceBatchId: number,\n count: number\n ): PersistencePromise {\n const result = newOverlayMap();\n let currentBatchId: number | undefined = undefined;\n // We want batch IDs larger than `sinceBatchId`, and so the lower bound\n // is not inclusive.\n const range = IDBKeyRange.bound(\n [this.userId, collectionGroup, sinceBatchId],\n [this.userId, collectionGroup, Number.POSITIVE_INFINITY],\n /*lowerOpen=*/ true\n );\n return documentOverlayStore(transaction)\n .iterate(\n {\n index: DbDocumentOverlayCollectionGroupOverlayIndex,\n range\n },\n (_, dbOverlay, control) => {\n // We do not want to return partial batch overlays, even if the size\n // of the result set exceeds the given `count` argument. Therefore, we\n // continue to aggregate results even after the result size exceeds\n // `count` if there are more overlays from the `currentBatchId`.\n const overlay = fromDbDocumentOverlay(this.serializer, dbOverlay);\n if (\n result.size() < count ||\n overlay.largestBatchId === currentBatchId\n ) {\n result.set(overlay.getKey(), overlay);\n currentBatchId = overlay.largestBatchId;\n } else {\n control.done();\n }\n }\n )\n .next(() => result);\n }\n\n private saveOverlay(\n transaction: PersistenceTransaction,\n overlay: Overlay\n ): PersistencePromise {\n return documentOverlayStore(transaction).put(\n toDbDocumentOverlay(this.serializer, this.userId, overlay)\n );\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document overlay object store.\n */\nfunction documentOverlayStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbDocumentOverlayStore\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 { DbGlobals } from './indexeddb_schema';\nimport { DbGlobalsStore, DbGlobalsKey } from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\nexport class IndexedDbGlobalsCache implements GlobalsCache {\n private globalsStore(\n txn: PersistenceTransaction\n ): SimpleDbStore {\n return getStore(txn, DbGlobalsStore);\n }\n\n getSessionToken(txn: PersistenceTransaction): PersistencePromise {\n const globals = this.globalsStore(txn);\n return globals.get('sessionToken').next(global => {\n const value = global?.value;\n return value\n ? ByteString.fromUint8Array(value)\n : ByteString.EMPTY_BYTE_STRING;\n });\n }\n\n setSessionToken(\n txn: PersistenceTransaction,\n sessionToken: ByteString\n ): PersistencePromise {\n const globals = this.globalsStore(txn);\n return globals.put({\n name: 'sessionToken',\n value: sessionToken.toUint8Array()\n });\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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(0x4a4e, '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 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law | agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES | CONDITIONS OF ANY KIND, either express | implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { debugAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\n\n/** These constants are taken from the backend. */\nconst MIN_SURROGATE = '\\uD800';\nconst MAX_SURROGATE = '\\uDBFF';\n\nconst ESCAPE1 = 0x00;\nconst NULL_BYTE = 0xff; // Combined with ESCAPE1\nconst SEPARATOR = 0x01; // Combined with ESCAPE1\n\nconst ESCAPE2 = 0xff;\nconst INFINITY = 0xff; // Combined with ESCAPE2\nconst FF_BYTE = 0x00; // Combined with ESCAPE2\n\nconst LONG_SIZE = 64;\nconst BYTE_SIZE = 8;\n\n/**\n * The default size of the buffer. This is arbitrary, but likely larger than\n * most index values so that less copies of the underlying buffer will be made.\n * For large values, a single copy will made to double the buffer length.\n */\nconst DEFAULT_BUFFER_SIZE = 1024;\n\n/** Converts a JavaScript number to a byte array (using big endian encoding). */\nfunction doubleToLongBits(value: number): Uint8Array {\n const dv = new DataView(new ArrayBuffer(8));\n dv.setFloat64(0, value, /* littleEndian= */ false);\n return new Uint8Array(dv.buffer);\n}\n\n/**\n * Counts the number of zeros in a byte.\n *\n * Visible for testing.\n */\nexport function numberOfLeadingZerosInByte(x: number): number {\n debugAssert(x < 256, 'Provided value is not a byte: ' + x);\n if (x === 0) {\n return 8;\n }\n\n let zeros = 0;\n if (x >> 4 === 0) {\n // Test if the first four bits are zero.\n zeros += 4;\n x = x << 4;\n }\n if (x >> 6 === 0) {\n // Test if the first two (or next two) bits are zero.\n zeros += 2;\n x = x << 2;\n }\n if (x >> 7 === 0) {\n // Test if the remaining bit is zero.\n zeros += 1;\n }\n return zeros;\n}\n\n/** Counts the number of leading zeros in the given byte array. */\nfunction numberOfLeadingZeros(bytes: Uint8Array): number {\n debugAssert(\n bytes.length === 8,\n 'Can only count leading zeros in 64-bit numbers'\n );\n let leadingZeros = 0;\n for (let i = 0; i < 8; ++i) {\n const zeros = numberOfLeadingZerosInByte(bytes[i] & 0xff);\n leadingZeros += zeros;\n if (zeros !== 8) {\n break;\n }\n }\n return leadingZeros;\n}\n\n/**\n * Returns the number of bytes required to store \"value\". Leading zero bytes\n * are skipped.\n */\nfunction unsignedNumLength(value: Uint8Array): number {\n // This is just the number of bytes for the unsigned representation of the number.\n const numBits = LONG_SIZE - numberOfLeadingZeros(value);\n return Math.ceil(numBits / BYTE_SIZE);\n}\n\n/**\n * OrderedCodeWriter is a minimal-allocation implementation of the writing\n * behavior defined by the backend.\n *\n * The code is ported from its Java counterpart.\n */\nexport class OrderedCodeWriter {\n buffer = new Uint8Array(DEFAULT_BUFFER_SIZE);\n position = 0;\n\n writeBytesAscending(value: ByteString): void {\n const it = value[Symbol.iterator]();\n let byte = it.next();\n while (!byte.done) {\n this.writeByteAscending(byte.value);\n byte = it.next();\n }\n this.writeSeparatorAscending();\n }\n\n writeBytesDescending(value: ByteString): void {\n const it = value[Symbol.iterator]();\n let byte = it.next();\n while (!byte.done) {\n this.writeByteDescending(byte.value);\n byte = it.next();\n }\n this.writeSeparatorDescending();\n }\n\n /** Writes utf8 bytes into this byte sequence, ascending. */\n writeUtf8Ascending(sequence: string): void {\n for (const c of sequence) {\n const charCode = c.charCodeAt(0);\n if (charCode < 0x80) {\n this.writeByteAscending(charCode);\n } else if (charCode < 0x800) {\n this.writeByteAscending((0x0f << 6) | (charCode >>> 6));\n this.writeByteAscending(0x80 | (0x3f & charCode));\n } else if (c < MIN_SURROGATE || MAX_SURROGATE < c) {\n this.writeByteAscending((0x0f << 5) | (charCode >>> 12));\n this.writeByteAscending(0x80 | (0x3f & (charCode >>> 6)));\n this.writeByteAscending(0x80 | (0x3f & charCode));\n } else {\n const codePoint = c.codePointAt(0)!;\n this.writeByteAscending((0x0f << 4) | (codePoint >>> 18));\n this.writeByteAscending(0x80 | (0x3f & (codePoint >>> 12)));\n this.writeByteAscending(0x80 | (0x3f & (codePoint >>> 6)));\n this.writeByteAscending(0x80 | (0x3f & codePoint));\n }\n }\n this.writeSeparatorAscending();\n }\n\n /** Writes utf8 bytes into this byte sequence, descending */\n writeUtf8Descending(sequence: string): void {\n for (const c of sequence) {\n const charCode = c.charCodeAt(0);\n if (charCode < 0x80) {\n this.writeByteDescending(charCode);\n } else if (charCode < 0x800) {\n this.writeByteDescending((0x0f << 6) | (charCode >>> 6));\n this.writeByteDescending(0x80 | (0x3f & charCode));\n } else if (c < MIN_SURROGATE || MAX_SURROGATE < c) {\n this.writeByteDescending((0x0f << 5) | (charCode >>> 12));\n this.writeByteDescending(0x80 | (0x3f & (charCode >>> 6)));\n this.writeByteDescending(0x80 | (0x3f & charCode));\n } else {\n const codePoint = c.codePointAt(0)!;\n this.writeByteDescending((0x0f << 4) | (codePoint >>> 18));\n this.writeByteDescending(0x80 | (0x3f & (codePoint >>> 12)));\n this.writeByteDescending(0x80 | (0x3f & (codePoint >>> 6)));\n this.writeByteDescending(0x80 | (0x3f & codePoint));\n }\n }\n this.writeSeparatorDescending();\n }\n\n writeNumberAscending(val: number): void {\n // Values are encoded with a single byte length prefix, followed by the\n // actual value in big-endian format with leading 0 bytes dropped.\n const value = this.toOrderedBits(val);\n const len = unsignedNumLength(value);\n this.ensureAvailable(1 + len);\n this.buffer[this.position++] = len & 0xff; // Write the length\n for (let i = value.length - len; i < value.length; ++i) {\n this.buffer[this.position++] = value[i] & 0xff;\n }\n }\n\n writeNumberDescending(val: number): void {\n // Values are encoded with a single byte length prefix, followed by the\n // inverted value in big-endian format with leading 0 bytes dropped.\n const value = this.toOrderedBits(val);\n const len = unsignedNumLength(value);\n this.ensureAvailable(1 + len);\n this.buffer[this.position++] = ~(len & 0xff); // Write the length\n for (let i = value.length - len; i < value.length; ++i) {\n this.buffer[this.position++] = ~(value[i] & 0xff);\n }\n }\n\n /**\n * Writes the \"infinity\" byte sequence that sorts after all other byte\n * sequences written in ascending order.\n */\n writeInfinityAscending(): void {\n this.writeEscapedByteAscending(ESCAPE2);\n this.writeEscapedByteAscending(INFINITY);\n }\n\n /**\n * Writes the \"infinity\" byte sequence that sorts before all other byte\n * sequences written in descending order.\n */\n writeInfinityDescending(): void {\n this.writeEscapedByteDescending(ESCAPE2);\n this.writeEscapedByteDescending(INFINITY);\n }\n\n /**\n * Resets the buffer such that it is the same as when it was newly\n * constructed.\n */\n reset(): void {\n this.position = 0;\n }\n\n seed(encodedBytes: Uint8Array): void {\n this.ensureAvailable(encodedBytes.length);\n this.buffer.set(encodedBytes, this.position);\n this.position += encodedBytes.length;\n }\n\n /** Makes a copy of the encoded bytes in this buffer. */\n encodedBytes(): Uint8Array {\n return this.buffer.slice(0, this.position);\n }\n\n /**\n * Encodes `val` into an encoding so that the order matches the IEEE 754\n * floating-point comparison results with the following exceptions:\n * -0.0 < 0.0\n * all non-NaN < NaN\n * NaN = NaN\n */\n private toOrderedBits(val: number): Uint8Array {\n const value = doubleToLongBits(val);\n // Check if the first bit is set. We use a bit mask since value[0] is\n // encoded as a number from 0 to 255.\n const isNegative = (value[0] & 0x80) !== 0;\n\n // Revert the two complement to get natural ordering\n value[0] ^= isNegative ? 0xff : 0x80;\n for (let i = 1; i < value.length; ++i) {\n value[i] ^= isNegative ? 0xff : 0x00;\n }\n return value;\n }\n\n /** Writes a single byte ascending to the buffer. */\n private writeByteAscending(b: number): void {\n const masked = b & 0xff;\n if (masked === ESCAPE1) {\n this.writeEscapedByteAscending(ESCAPE1);\n this.writeEscapedByteAscending(NULL_BYTE);\n } else if (masked === ESCAPE2) {\n this.writeEscapedByteAscending(ESCAPE2);\n this.writeEscapedByteAscending(FF_BYTE);\n } else {\n this.writeEscapedByteAscending(masked);\n }\n }\n\n /** Writes a single byte descending to the buffer. */\n private writeByteDescending(b: number): void {\n const masked = b & 0xff;\n if (masked === ESCAPE1) {\n this.writeEscapedByteDescending(ESCAPE1);\n this.writeEscapedByteDescending(NULL_BYTE);\n } else if (masked === ESCAPE2) {\n this.writeEscapedByteDescending(ESCAPE2);\n this.writeEscapedByteDescending(FF_BYTE);\n } else {\n this.writeEscapedByteDescending(b);\n }\n }\n\n private writeSeparatorAscending(): void {\n this.writeEscapedByteAscending(ESCAPE1);\n this.writeEscapedByteAscending(SEPARATOR);\n }\n\n private writeSeparatorDescending(): void {\n this.writeEscapedByteDescending(ESCAPE1);\n this.writeEscapedByteDescending(SEPARATOR);\n }\n\n private writeEscapedByteAscending(b: number): void {\n this.ensureAvailable(1);\n this.buffer[this.position++] = b;\n }\n\n private writeEscapedByteDescending(b: number): void {\n this.ensureAvailable(1);\n this.buffer[this.position++] = ~b;\n }\n\n private ensureAvailable(bytes: number): void {\n const minCapacity = bytes + this.position;\n if (minCapacity <= this.buffer.length) {\n return;\n }\n // Try doubling.\n let newLength = this.buffer.length * 2;\n // Still not big enough? Just allocate the right size.\n if (newLength < minCapacity) {\n newLength = minCapacity;\n }\n // Create the new buffer.\n const newBuffer = new Uint8Array(newLength);\n newBuffer.set(this.buffer); // copy old data\n this.buffer = newBuffer;\n }\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { IndexKind } from '../model/field_index';\nimport { ByteString } from '../util/byte_string';\n\nimport { DirectionalIndexByteEncoder } from './directional_index_byte_encoder';\nimport { OrderedCodeWriter } from './ordered_code_writer';\n\nclass AscendingIndexByteEncoder implements DirectionalIndexByteEncoder {\n constructor(private orderedCode: OrderedCodeWriter) {}\n writeBytes(value: ByteString): void {\n this.orderedCode.writeBytesAscending(value);\n }\n\n writeString(value: string): void {\n this.orderedCode.writeUtf8Ascending(value);\n }\n\n writeNumber(value: number): void {\n this.orderedCode.writeNumberAscending(value);\n }\n\n writeInfinity(): void {\n this.orderedCode.writeInfinityAscending();\n }\n}\n\nclass DescendingIndexByteEncoder implements DirectionalIndexByteEncoder {\n constructor(private orderedCode: OrderedCodeWriter) {}\n writeBytes(value: ByteString): void {\n this.orderedCode.writeBytesDescending(value);\n }\n\n writeString(value: string): void {\n this.orderedCode.writeUtf8Descending(value);\n }\n\n writeNumber(value: number): void {\n this.orderedCode.writeNumberDescending(value);\n }\n\n writeInfinity(): void {\n this.orderedCode.writeInfinityDescending();\n }\n}\n/**\n * Implements `DirectionalIndexByteEncoder` using `OrderedCodeWriter` for the\n * actual encoding.\n */\nexport class IndexByteEncoder {\n private orderedCode = new OrderedCodeWriter();\n private ascending = new AscendingIndexByteEncoder(this.orderedCode);\n private descending = new DescendingIndexByteEncoder(this.orderedCode);\n\n seed(encodedBytes: Uint8Array): void {\n this.orderedCode.seed(encodedBytes);\n }\n\n forKind(kind: IndexKind): DirectionalIndexByteEncoder {\n return kind === IndexKind.ASCENDING ? this.ascending : this.descending;\n }\n\n encodedBytes(): Uint8Array {\n return this.orderedCode.encodedBytes();\n }\n\n reset(): void {\n this.orderedCode.reset();\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isSafariOrWebkit } from '@firebase/util';\n\nimport { DbIndexEntry } from '../local/indexeddb_schema';\nimport { DbIndexEntryKey, KeySafeBytes } from '../local/indexeddb_sentinels';\nimport { DocumentKey } from '../model/document_key';\n\n/** Represents an index entry saved by the SDK in persisted storage. */\nexport class IndexEntry {\n constructor(\n readonly _indexId: number,\n readonly _documentKey: DocumentKey,\n readonly _arrayValue: Uint8Array,\n readonly _directionalValue: Uint8Array\n ) {}\n\n /**\n * Returns an IndexEntry entry that sorts immediately after the current\n * directional value.\n */\n successor(): IndexEntry {\n const currentLength = this._directionalValue.length;\n const newLength =\n currentLength === 0 || this._directionalValue[currentLength - 1] === 255\n ? currentLength + 1\n : currentLength;\n\n const successor = new Uint8Array(newLength);\n successor.set(this._directionalValue, 0);\n if (newLength !== currentLength) {\n successor.set([0], this._directionalValue.length);\n } else {\n ++successor[successor.length - 1];\n }\n\n return new IndexEntry(\n this._indexId,\n this._documentKey,\n this._arrayValue,\n successor\n );\n }\n\n // Create a representation of the Index Entry as a DbIndexEntry\n dbIndexEntry(\n uid: string,\n orderedDocumentKey: Uint8Array,\n documentKey: DocumentKey\n ): DbIndexEntry {\n return {\n indexId: this._indexId,\n uid,\n arrayValue: encodeKeySafeBytes(this._arrayValue),\n directionalValue: encodeKeySafeBytes(this._directionalValue),\n orderedDocumentKey: encodeKeySafeBytes(orderedDocumentKey),\n documentKey: documentKey.path.toArray()\n };\n }\n\n // Create a representation of the Index Entry as a DbIndexEntryKey\n dbIndexEntryKey(\n uid: string,\n orderedDocumentKey: Uint8Array,\n documentKey: DocumentKey\n ): DbIndexEntryKey {\n const entry = this.dbIndexEntry(uid, orderedDocumentKey, documentKey);\n return [\n entry.indexId,\n entry.uid,\n entry.arrayValue,\n entry.directionalValue,\n entry.orderedDocumentKey,\n entry.documentKey\n ];\n }\n}\n\nexport function indexEntryComparator(\n left: IndexEntry,\n right: IndexEntry\n): number {\n let cmp = left._indexId - right._indexId;\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = compareByteArrays(left._arrayValue, right._arrayValue);\n if (cmp !== 0) {\n return cmp;\n }\n\n cmp = compareByteArrays(left._directionalValue, right._directionalValue);\n if (cmp !== 0) {\n return cmp;\n }\n\n return DocumentKey.comparator(left._documentKey, right._documentKey);\n}\n\nexport function compareByteArrays(left: Uint8Array, right: Uint8Array): number {\n for (let i = 0; i < left.length && i < right.length; ++i) {\n const compare = left[i] - right[i];\n if (compare !== 0) {\n return compare;\n }\n }\n return left.length - right.length;\n}\n\n/**\n * Workaround for WebKit bug: https://bugs.webkit.org/show_bug.cgi?id=292721\n * Create a key safe representation of Uint8Array values.\n * If the browser is detected as Safari or WebKit, then\n * the input array will be converted to \"sortable byte string\".\n * Otherwise, the input array will be returned in its original type.\n */\nexport function encodeKeySafeBytes(array: Uint8Array): KeySafeBytes {\n if (isSafariOrWebkit()) {\n return encodeUint8ArrayToSortableString(array);\n }\n return array;\n}\n\n/**\n * Reverts the key safe representation of Uint8Array (created by\n * encodeKeySafeBytes) to a normal Uint8Array.\n */\nexport function decodeKeySafeBytes(input: KeySafeBytes): Uint8Array {\n if (typeof input !== 'string') {\n return input;\n }\n return decodeSortableStringToUint8Array(input);\n}\n\n/**\n * Encodes a Uint8Array into a \"sortable byte string\".\n * A \"sortable byte string\" sorts in the same order as the Uint8Array.\n * This works because JS string comparison sorts strings based on code points.\n */\nfunction encodeUint8ArrayToSortableString(array: Uint8Array): string {\n let byteString = '';\n for (let i = 0; i < array.length; i++) {\n byteString += String.fromCharCode(array[i]);\n }\n\n return byteString;\n}\n\n/**\n * Decodes a \"sortable byte string\" back into a Uint8Array.\n * A \"sortable byte string\" is assumed to be created where each character's\n * Unicode code point directly corresponds to a single byte value (0-255).\n */\nfunction decodeSortableStringToUint8Array(byteString: string): Uint8Array {\n const uint8array = new Uint8Array(byteString.length);\n\n for (let i = 0; i < byteString.length; i++) {\n uint8array[i] = byteString.charCodeAt(i);\n }\n\n return uint8array;\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldFilter, Operator } from '../core/filter';\nimport { Direction, OrderBy } from '../core/order_by';\nimport { Target } from '../core/target';\nimport { hardAssert } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport {\n FieldIndex,\n fieldIndexGetArraySegment,\n fieldIndexGetDirectionalSegments,\n IndexKind,\n IndexSegment,\n IndexState\n} from './field_index';\nimport { FieldPath } from './path';\n\n/**\n * A light query planner for Firestore.\n *\n * This class matches a `FieldIndex` against a Firestore Query `Target`. It\n * determines whether a given index can be used to serve the specified target.\n *\n * The following table showcases some possible index configurations:\n *\n * Query | Index\n * -----------------------------------------------------------------------------\n * where('a', '==', 'a').where('b', '==', 'b') | a ASC, b DESC\n * where('a', '==', 'a').where('b', '==', 'b') | a ASC\n * where('a', '==', 'a').where('b', '==', 'b') | b DESC\n * where('a', '>=', 'a').orderBy('a') | a ASC\n * where('a', '>=', 'a').orderBy('a', 'desc') | a DESC\n * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC, b ASC\n * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC\n * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS, b ASCENDING\n * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS\n */\nexport class TargetIndexMatcher {\n // The collection ID (or collection group) of the query target.\n private readonly collectionId: string;\n // The inequality filters of the target (if it exists).\n // Note: The sort on FieldFilters is not required. Using SortedSet here just to utilize the custom\n // comparator.\n private inequalityFilters = new SortedSet((lhs, rhs) =>\n FieldPath.comparator(lhs.field, rhs.field)\n );\n\n // The list of equality filters of the target.\n private readonly equalityFilters: FieldFilter[];\n // The list of orderBys of the target.\n private readonly orderBys: OrderBy[];\n\n constructor(target: Target) {\n this.collectionId =\n target.collectionGroup != null\n ? target.collectionGroup\n : target.path.lastSegment();\n this.orderBys = target.orderBy;\n this.equalityFilters = [];\n for (const filter of target.filters) {\n const fieldFilter = filter as FieldFilter;\n if (fieldFilter.isInequality()) {\n this.inequalityFilters = this.inequalityFilters.add(fieldFilter);\n } else {\n this.equalityFilters.push(fieldFilter);\n }\n }\n }\n\n get hasMultipleInequality(): boolean {\n return this.inequalityFilters.size > 1;\n }\n\n /**\n * Returns whether the index can be used to serve the TargetIndexMatcher's\n * target.\n *\n * An index is considered capable of serving the target when:\n * - The target uses all index segments for its filters and orderBy clauses.\n * The target can have additional filter and orderBy clauses, but not\n * fewer.\n * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also\n * have a corresponding `CONTAINS` segment.\n * - All directional index segments can be mapped to the target as a series of\n * equality filters, a single inequality filter and a series of orderBy\n * clauses.\n * - The segments that represent the equality filters may appear out of order.\n * - The optional segment for the inequality filter must appear after all\n * equality segments.\n * - The segments that represent that orderBy clause of the target must appear\n * in order after all equality and inequality segments. Single orderBy\n * clauses cannot be skipped, but a continuous orderBy suffix may be\n * omitted.\n */\n servedByIndex(index: FieldIndex): boolean {\n hardAssert(\n index.collectionGroup === this.collectionId,\n 0xc07f,\n 'Collection IDs do not match'\n );\n\n if (this.hasMultipleInequality) {\n // Only single inequality is supported for now.\n // TODO(Add support for multiple inequality query): b/298441043\n return false;\n }\n\n // If there is an array element, find a matching filter.\n const arraySegment = fieldIndexGetArraySegment(index);\n if (\n arraySegment !== undefined &&\n !this.hasMatchingEqualityFilter(arraySegment)\n ) {\n return false;\n }\n\n const segments = fieldIndexGetDirectionalSegments(index);\n let equalitySegments = new Set();\n let segmentIndex = 0;\n let orderBysIndex = 0;\n\n // Process all equalities first. Equalities can appear out of order.\n for (; segmentIndex < segments.length; ++segmentIndex) {\n // We attempt to greedily match all segments to equality filters. If a\n // filter matches an index segment, we can mark the segment as used.\n if (this.hasMatchingEqualityFilter(segments[segmentIndex])) {\n equalitySegments = equalitySegments.add(\n segments[segmentIndex].fieldPath.canonicalString()\n );\n } else {\n // If we cannot find a matching filter, we need to verify whether the\n // remaining segments map to the target's inequality and its orderBy\n // clauses.\n break;\n }\n }\n\n // If we already have processed all segments, all segments are used to serve\n // the equality filters and we do not need to map any segments to the\n // target's inequality and orderBy clauses.\n if (segmentIndex === segments.length) {\n return true;\n }\n\n if (this.inequalityFilters.size > 0) {\n // Only a single inequality is currently supported. Get the only entry in the set.\n const inequalityFilter = this.inequalityFilters.getIterator().getNext();\n // If there is an inequality filter and the field was not in one of the\n // equality filters above, the next segment must match both the filter\n // and the first orderBy clause.\n if (!equalitySegments.has(inequalityFilter.field.canonicalString())) {\n const segment = segments[segmentIndex];\n\n if (\n !this.matchesFilter(inequalityFilter, segment) ||\n !this.matchesOrderBy(this.orderBys[orderBysIndex++], segment)\n ) {\n return false;\n }\n }\n\n ++segmentIndex;\n }\n\n // All remaining segments need to represent the prefix of the target's\n // orderBy.\n for (; segmentIndex < segments.length; ++segmentIndex) {\n const segment = segments[segmentIndex];\n if (\n orderBysIndex >= this.orderBys.length ||\n !this.matchesOrderBy(this.orderBys[orderBysIndex++], segment)\n ) {\n return false;\n }\n }\n\n return true;\n }\n\n /**\n * Returns a full matched field index for this target. Currently multiple\n * inequality query is not supported so function returns null.\n */\n buildTargetIndex(): FieldIndex | null {\n if (this.hasMultipleInequality) {\n return null;\n }\n\n // We want to make sure only one segment created for one field. For example,\n // in case like a == 3 and a > 2, Index {a ASCENDING} will only be created\n // once.\n let uniqueFields = new SortedSet(FieldPath.comparator);\n const segments: IndexSegment[] = [];\n\n for (const filter of this.equalityFilters) {\n if (filter.field.isKeyField()) {\n continue;\n }\n const isArrayOperator =\n filter.op === Operator.ARRAY_CONTAINS ||\n filter.op === Operator.ARRAY_CONTAINS_ANY;\n if (isArrayOperator) {\n segments.push(new IndexSegment(filter.field, IndexKind.CONTAINS));\n } else {\n if (uniqueFields.has(filter.field)) {\n continue;\n }\n uniqueFields = uniqueFields.add(filter.field);\n segments.push(new IndexSegment(filter.field, IndexKind.ASCENDING));\n }\n }\n\n // Note: We do not explicitly check `this.inequalityFilter` but rather rely\n // on the target defining an appropriate \"order by\" to ensure that the\n // required index segment is added. The query engine would reject a query\n // with an inequality filter that lacks the required order-by clause.\n for (const orderBy of this.orderBys) {\n // Stop adding more segments if we see a order-by on key. Typically this\n // is the default implicit order-by which is covered in the index_entry\n // table as a separate column. If it is not the default order-by, the\n // generated index will be missing some segments optimized for order-bys,\n // which is probably fine.\n if (orderBy.field.isKeyField()) {\n continue;\n }\n\n if (uniqueFields.has(orderBy.field)) {\n continue;\n }\n uniqueFields = uniqueFields.add(orderBy.field);\n\n segments.push(\n new IndexSegment(\n orderBy.field,\n orderBy.dir === Direction.ASCENDING\n ? IndexKind.ASCENDING\n : IndexKind.DESCENDING\n )\n );\n }\n\n return new FieldIndex(\n FieldIndex.UNKNOWN_ID,\n this.collectionId,\n segments,\n IndexState.empty()\n );\n }\n\n private hasMatchingEqualityFilter(segment: IndexSegment): boolean {\n for (const filter of this.equalityFilters) {\n if (this.matchesFilter(filter, segment)) {\n return true;\n }\n }\n return false;\n }\n\n private matchesFilter(\n filter: FieldFilter | undefined,\n segment: IndexSegment\n ): boolean {\n if (filter === undefined || !filter.field.isEqual(segment.fieldPath)) {\n return false;\n }\n const isArrayOperator =\n filter.op === Operator.ARRAY_CONTAINS ||\n filter.op === Operator.ARRAY_CONTAINS_ANY;\n return (segment.kind === IndexKind.CONTAINS) === isArrayOperator;\n }\n\n private matchesOrderBy(orderBy: OrderBy, segment: IndexSegment): boolean {\n if (!orderBy.field.isEqual(segment.fieldPath)) {\n return false;\n }\n return (\n (segment.kind === IndexKind.ASCENDING &&\n orderBy.dir === Direction.ASCENDING) ||\n (segment.kind === IndexKind.DESCENDING &&\n orderBy.dir === Direction.DESCENDING)\n );\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n CompositeFilter,\n compositeFilterIsConjunction,\n compositeFilterIsDisjunction,\n compositeFilterIsFlat,\n compositeFilterIsFlatConjunction,\n compositeFilterWithAddedFilters,\n CompositeOperator,\n FieldFilter,\n Filter,\n InFilter,\n Operator\n} from '../core/filter';\n\nimport { hardAssert } from './assert';\n\n/**\n * Provides utility functions that help with boolean logic transformations needed for handling\n * complex filters used in queries.\n */\n\n/**\n * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in\n * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given\n * input into a disjunction of equality filters and returns the expanded filter.\n */\nexport function computeInExpansion(filter: Filter): Filter {\n hardAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 0x4e2c,\n 'Only field filters and composite filters are accepted.'\n );\n\n if (filter instanceof FieldFilter) {\n if (filter instanceof InFilter) {\n const expandedFilters =\n filter.value.arrayValue?.values?.map(value =>\n FieldFilter.create(filter.field, Operator.EQUAL, value)\n ) || [];\n\n return CompositeFilter.create(expandedFilters, CompositeOperator.OR);\n } else {\n // We have reached other kinds of field filters.\n return filter;\n }\n }\n\n // We have a composite filter.\n const expandedFilters = filter.filters.map(subfilter =>\n computeInExpansion(subfilter)\n );\n return CompositeFilter.create(expandedFilters, filter.op);\n}\n\n/**\n * Given a composite filter, returns the list of terms in its disjunctive normal form.\n *\n *

Each element in the return value is one term of the resulting DNF. For instance: For the\n * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list\n * with two elements: a composite filter that performs (A && C), and a composite filter that\n * performs (B && C).\n *\n * @param filter the composite filter to calculate DNF transform for.\n * @return the terms in the DNF transform.\n */\nexport function getDnfTerms(filter: CompositeFilter): Filter[] {\n if (filter.getFilters().length === 0) {\n return [];\n }\n\n const result: Filter = computeDistributedNormalForm(\n computeInExpansion(filter)\n );\n\n hardAssert(\n isDisjunctiveNormalForm(result),\n 0x1cdf,\n 'computeDistributedNormalForm did not result in disjunctive normal form'\n );\n\n if (isSingleFieldFilter(result) || isFlatConjunction(result)) {\n return [result];\n }\n\n return result.getFilters();\n}\n\n/** Returns true if the given filter is a single field filter. e.g. (a == 10). */\nfunction isSingleFieldFilter(filter: Filter): boolean {\n return filter instanceof FieldFilter;\n}\n\n/**\n * Returns true if the given filter is the conjunction of one or more field filters. e.g. (a == 10\n * && b == 20)\n */\nfunction isFlatConjunction(filter: Filter): boolean {\n return (\n filter instanceof CompositeFilter &&\n compositeFilterIsFlatConjunction(filter)\n );\n}\n\n/**\n * Returns whether or not the given filter is in disjunctive normal form (DNF).\n *\n *

In boolean logic, a disjunctive normal form (DNF) is a canonical normal form of a logical\n * formula consisting of a disjunction of conjunctions; it can also be described as an OR of ANDs.\n *\n *

For more info, visit: https://en.wikipedia.org/wiki/Disjunctive_normal_form\n */\nfunction isDisjunctiveNormalForm(filter: Filter): boolean {\n return (\n isSingleFieldFilter(filter) ||\n isFlatConjunction(filter) ||\n isDisjunctionOfFieldFiltersAndFlatConjunctions(filter)\n );\n}\n\n/**\n * Returns true if the given filter is the disjunction of one or more \"flat conjunctions\" and\n * field filters. e.g. (a == 10) || (b==20 && c==30)\n */\nfunction isDisjunctionOfFieldFiltersAndFlatConjunctions(\n filter: Filter\n): boolean {\n if (filter instanceof CompositeFilter) {\n if (compositeFilterIsDisjunction(filter)) {\n for (const subFilter of filter.getFilters()) {\n if (!isSingleFieldFilter(subFilter) && !isFlatConjunction(subFilter)) {\n return false;\n }\n }\n\n return true;\n }\n }\n\n return false;\n}\n\nexport function computeDistributedNormalForm(filter: Filter): Filter {\n hardAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 0x84e2,\n 'Only field filters and composite filters are accepted.'\n );\n\n if (filter instanceof FieldFilter) {\n return filter;\n }\n\n if (filter.filters.length === 1) {\n return computeDistributedNormalForm(filter.filters[0]);\n }\n\n // Compute DNF for each of the subfilters first\n const result = filter.filters.map(subfilter =>\n computeDistributedNormalForm(subfilter)\n );\n\n let newFilter: Filter = CompositeFilter.create(result, filter.op);\n newFilter = applyAssociation(newFilter);\n\n if (isDisjunctiveNormalForm(newFilter)) {\n return newFilter;\n }\n\n hardAssert(\n newFilter instanceof CompositeFilter,\n 0xfbf2,\n 'field filters are already in DNF form'\n );\n hardAssert(\n compositeFilterIsConjunction(newFilter),\n 0x9d3b,\n 'Disjunction of filters all of which are already in DNF form is itself in DNF form.'\n );\n hardAssert(\n newFilter.filters.length > 1,\n 0xe247,\n 'Single-filter composite filters are already in DNF form.'\n );\n\n return newFilter.filters.reduce((runningResult, filter) =>\n applyDistribution(runningResult, filter)\n );\n}\n\nexport function applyDistribution(lhs: Filter, rhs: Filter): Filter {\n hardAssert(\n lhs instanceof FieldFilter || lhs instanceof CompositeFilter,\n 0x95f4,\n 'Only field filters and composite filters are accepted.'\n );\n hardAssert(\n rhs instanceof FieldFilter || rhs instanceof CompositeFilter,\n 0x6381,\n 'Only field filters and composite filters are accepted.'\n );\n\n let result: Filter;\n\n if (lhs instanceof FieldFilter) {\n if (rhs instanceof FieldFilter) {\n // FieldFilter FieldFilter\n result = applyDistributionFieldFilters(lhs, rhs);\n } else {\n // FieldFilter CompositeFilter\n result = applyDistributionFieldAndCompositeFilters(lhs, rhs);\n }\n } else {\n if (rhs instanceof FieldFilter) {\n // CompositeFilter FieldFilter\n result = applyDistributionFieldAndCompositeFilters(rhs, lhs);\n } else {\n // CompositeFilter CompositeFilter\n result = applyDistributionCompositeFilters(lhs, rhs);\n }\n }\n\n return applyAssociation(result);\n}\n\nfunction applyDistributionFieldFilters(\n lhs: FieldFilter,\n rhs: FieldFilter\n): Filter {\n // Conjunction distribution for two field filters is the conjunction of them.\n return CompositeFilter.create([lhs, rhs], CompositeOperator.AND);\n}\n\nfunction applyDistributionCompositeFilters(\n lhs: CompositeFilter,\n rhs: CompositeFilter\n): Filter {\n hardAssert(\n lhs.filters.length > 0 && rhs.filters.length > 0,\n 0xbb85,\n 'Found an empty composite filter'\n );\n\n // There are four cases:\n // (A & B) & (C & D) --> (A & B & C & D)\n // (A & B) & (C | D) --> (A & B & C) | (A & B & D)\n // (A | B) & (C & D) --> (C & D & A) | (C & D & B)\n // (A | B) & (C | D) --> (A & C) | (A & D) | (B & C) | (B & D)\n\n // Case 1 is a merge.\n if (compositeFilterIsConjunction(lhs) && compositeFilterIsConjunction(rhs)) {\n return compositeFilterWithAddedFilters(lhs, rhs.getFilters());\n }\n\n // Case 2,3,4 all have at least one side (lhs or rhs) that is a disjunction. In all three cases\n // we should take each element of the disjunction and distribute it over the other side, and\n // return the disjunction of the distribution results.\n const disjunctionSide = compositeFilterIsDisjunction(lhs) ? lhs : rhs;\n const otherSide = compositeFilterIsDisjunction(lhs) ? rhs : lhs;\n const results = disjunctionSide.filters.map(subfilter =>\n applyDistribution(subfilter, otherSide)\n );\n return CompositeFilter.create(results, CompositeOperator.OR);\n}\n\nfunction applyDistributionFieldAndCompositeFilters(\n fieldFilter: FieldFilter,\n compositeFilter: CompositeFilter\n): Filter {\n // There are two cases:\n // A & (B & C) --> (A & B & C)\n // A & (B | C) --> (A & B) | (A & C)\n if (compositeFilterIsConjunction(compositeFilter)) {\n // Case 1\n return compositeFilterWithAddedFilters(\n compositeFilter,\n fieldFilter.getFilters()\n );\n } else {\n // Case 2\n const newFilters = compositeFilter.filters.map(subfilter =>\n applyDistribution(fieldFilter, subfilter)\n );\n\n return CompositeFilter.create(newFilters, CompositeOperator.OR);\n }\n}\n\n/**\n * Applies the associativity property to the given filter and returns the resulting filter.\n *\n *

    \n *
  • A | (B | C) == (A | B) | C == (A | B | C)\n *
  • A & (B & C) == (A & B) & C == (A & B & C)\n *
\n *\n *

For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic\n */\nexport function applyAssociation(filter: Filter): Filter {\n hardAssert(\n filter instanceof FieldFilter || filter instanceof CompositeFilter,\n 0x2e4a,\n 'Only field filters and composite filters are accepted.'\n );\n\n if (filter instanceof FieldFilter) {\n return filter;\n }\n\n const filters = filter.getFilters();\n\n // If the composite filter only contains 1 filter, apply associativity to it.\n if (filters.length === 1) {\n return applyAssociation(filters[0]);\n }\n\n // Associativity applied to a flat composite filter results is itself.\n if (compositeFilterIsFlat(filter)) {\n return filter;\n }\n\n // First apply associativity to all subfilters. This will in turn recursively apply\n // associativity to all nested composite filters and field filters.\n const updatedFilters = filters.map(subfilter => applyAssociation(subfilter));\n\n // For composite subfilters that perform the same kind of logical operation as `compositeFilter`\n // take out their filters and add them to `compositeFilter`. For example:\n // compositeFilter = (A | (B | C | D))\n // compositeSubfilter = (B | C | D)\n // Result: (A | B | C | D)\n // Note that the `compositeSubfilter` has been eliminated, and its filters (B, C, D) have been\n // added to the top-level \"compositeFilter\".\n const newSubfilters: Filter[] = [];\n updatedFilters.forEach(subfilter => {\n if (subfilter instanceof FieldFilter) {\n newSubfilters.push(subfilter);\n } else if (subfilter instanceof CompositeFilter) {\n if (subfilter.op === filter.op) {\n // compositeFilter: (A | (B | C))\n // compositeSubfilter: (B | C)\n // Result: (A | B | C)\n newSubfilters.push(...subfilter.filters);\n } else {\n // compositeFilter: (A | (B & C))\n // compositeSubfilter: (B & C)\n // Result: (A | (B & C))\n newSubfilters.push(subfilter);\n }\n }\n });\n\n if (newSubfilters.length === 1) {\n return newSubfilters[0];\n }\n\n return CompositeFilter.create(newSubfilters, filter.op);\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Target } from '../core/target';\nimport { DocumentMap } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldIndex, IndexOffset } from '../model/field_index';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert } from '../util/assert';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { IndexManager, IndexType } from './index_manager';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\n/**\n * An in-memory implementation of IndexManager.\n */\nexport class MemoryIndexManager implements IndexManager {\n private collectionParentIndex = new MemoryCollectionParentIndex();\n\n addToCollectionParentIndex(\n transaction: PersistenceTransaction,\n collectionPath: ResourcePath\n ): PersistencePromise {\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 {\n IndexEntry,\n indexEntryComparator,\n encodeKeySafeBytes,\n decodeKeySafeBytes\n} 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 indexEntry.dbIndexEntry(\n this.uid,\n this.encodeDirectionalKey(fieldIndex, document.key),\n document.key\n )\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.dbIndexEntryKey(\n this.uid,\n this.encodeDirectionalKey(fieldIndex, document.key),\n document.key\n )\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 encodeKeySafeBytes(\n this.encodeDirectionalKey(fieldIndex, documentKey)\n )\n ])\n },\n (_, entry) => {\n results = results.add(\n new IndexEntry(\n fieldIndex.indexId,\n documentKey,\n decodeKeySafeBytes(entry.arrayValue),\n decodeKeySafeBytes(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 = bounds[i].dbIndexEntryKey(\n this.uid,\n EMPTY_VALUE,\n DocumentKey.empty()\n );\n const upperBound = bounds[i + 1].dbIndexEntryKey(\n this.uid,\n EMPTY_VALUE,\n DocumentKey.empty()\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(0xad8a, '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 0x7099,\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { DocumentKey } from '../model/document_key';\nimport { fail, hardAssert } from '../util/assert';\n\nimport {\n DbDocumentMutation,\n DbMutationBatch,\n DbRemoteDocument\n} from './indexeddb_schema';\nimport { DbRemoteDocument as DbRemoteDocumentLegacy } from './indexeddb_schema_legacy';\nimport {\n DbDocumentMutationKey,\n DbDocumentMutationStore,\n DbMutationBatchKey,\n DbMutationBatchStore,\n newDbDocumentMutationKey\n} from './indexeddb_sentinels';\nimport { PersistencePromise } from './persistence_promise';\nimport { SimpleDbTransaction } from './simple_db';\n\n/**\n * Delete a mutation batch and the associated document mutations.\n * @returns A PersistencePromise of the document mutations that were removed.\n */\nexport function removeMutationBatch(\n txn: SimpleDbTransaction,\n userId: string,\n batch: { batchId: number; mutations: Array<{ key: DocumentKey }> }\n): PersistencePromise {\n const mutationStore = txn.store(\n DbMutationBatchStore\n );\n const indexTxn = txn.store(\n DbDocumentMutationStore\n );\n const promises: Array> = [];\n\n const range = IDBKeyRange.only(batch.batchId);\n let numDeleted = 0;\n const removePromise = mutationStore.iterate(\n { range },\n (key, value, control) => {\n numDeleted++;\n return control.delete();\n }\n );\n promises.push(\n removePromise.next(() => {\n hardAssert(\n numDeleted === 1,\n 0xb7de,\n 'Dangling document-mutation reference found: Missing batch',\n { batchId: batch.batchId }\n );\n })\n );\n const removedDocuments: DocumentKey[] = [];\n for (const mutation of batch.mutations) {\n const indexKey = newDbDocumentMutationKey(\n userId,\n mutation.key.path,\n batch.batchId\n );\n promises.push(indexTxn.delete(indexKey));\n removedDocuments.push(mutation.key);\n }\n return PersistencePromise.waitFor(promises).next(() => removedDocuments);\n}\n\n/**\n * Returns an approximate size for the given document.\n */\nexport function dbDocumentSize(\n doc: DbRemoteDocument | DbRemoteDocumentLegacy | null\n): number {\n if (!doc) {\n return 0;\n }\n\n let value: unknown;\n if (doc.document) {\n value = doc.document;\n } else if (doc.unknownDocument) {\n value = doc.unknownDocument;\n } else if (doc.noDocument) {\n value = doc.noDocument;\n } else {\n throw fail(0x398b, 'Unknown remote document type');\n }\n return JSON.stringify(value).length;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { isCollectionGroupQuery, isDocumentQuery, Query } from '../core/query';\nimport { BatchId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { DocumentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { Mutation } from '../model/mutation';\nimport { MutationBatch } from '../model/mutation_batch';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport { decodeResourcePath } from './encoded_resource_path';\nimport { IndexManager } from './index_manager';\nimport { removeMutationBatch } from './indexeddb_mutation_batch_impl';\nimport {\n DbDocumentMutation,\n DbMutationBatch,\n DbMutationQueue\n} from './indexeddb_schema';\nimport {\n DbDocumentMutationKey,\n DbDocumentMutationPlaceholder,\n DbDocumentMutationStore,\n DbMutationBatchKey,\n DbMutationBatchStore,\n DbMutationBatchUserMutationsIndex,\n DbMutationQueueKey,\n DbMutationQueueStore,\n newDbDocumentMutationKey,\n newDbDocumentMutationPrefixForPath,\n newDbDocumentMutationPrefixForUser\n} from './indexeddb_sentinels';\nimport { IndexedDbTransaction, getStore } from './indexeddb_transaction';\nimport {\n fromDbMutationBatch,\n LocalSerializer,\n toDbMutationBatch\n} from './local_serializer';\nimport { MutationQueue } from './mutation_queue';\nimport { ReferenceDelegate } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\n\n/** A mutation queue for a specific user, backed by IndexedDB. */\nexport class IndexedDbMutationQueue implements MutationQueue {\n /**\n * Caches the document keys for pending mutation batches. If the mutation\n * has been removed from IndexedDb, the cached value may continue to\n * be used to retrieve the batch's document keys. To remove a cached value\n * locally, `removeCachedMutationKeys()` should be invoked either directly\n * or through `removeMutationBatches()`.\n *\n * With multi-tab, when the primary client acknowledges or rejects a mutation,\n * this cache is used by secondary clients to invalidate the local\n * view of the documents that were previously affected by the mutation.\n */\n // PORTING NOTE: Multi-tab only.\n private documentKeysByBatchId = {} as { [batchId: number]: DocumentKeySet };\n\n constructor(\n /**\n * The normalized userId (e.g. null UID => \"\" userId) used to store /\n * retrieve mutations.\n */\n private userId: string,\n private readonly serializer: LocalSerializer,\n private readonly indexManager: IndexManager,\n private readonly referenceDelegate: ReferenceDelegate\n ) {}\n\n /**\n * Creates a new mutation queue for the given user.\n * @param user - The user for which to create a mutation queue.\n * @param serializer - The serializer to use when persisting to IndexedDb.\n */\n static forUser(\n user: User,\n serializer: LocalSerializer,\n indexManager: IndexManager,\n referenceDelegate: ReferenceDelegate\n ): IndexedDbMutationQueue {\n // TODO(mcg): Figure out what constraints there are on userIDs\n // In particular, are there any reserved characters? are empty ids allowed?\n // For the moment store these together in the same mutations table assuming\n // that empty userIDs aren't allowed.\n hardAssert(user.uid !== '', 0xfb83, 'UserID must not be an empty string.');\n const userId = user.isAuthenticated() ? user.uid! : '';\n return new IndexedDbMutationQueue(\n userId,\n serializer,\n indexManager,\n referenceDelegate\n );\n }\n\n checkEmpty(transaction: PersistenceTransaction): PersistencePromise {\n let empty = true;\n const range = IDBKeyRange.bound(\n [this.userId, Number.NEGATIVE_INFINITY],\n [this.userId, Number.POSITIVE_INFINITY]\n );\n return mutationsStore(transaction)\n .iterate(\n { index: DbMutationBatchUserMutationsIndex, range },\n (key, value, control) => {\n empty = false;\n control.done();\n }\n )\n .next(() => empty);\n }\n\n addMutationBatch(\n transaction: PersistenceTransaction,\n localWriteTime: Timestamp,\n baseMutations: Mutation[],\n mutations: Mutation[]\n ): PersistencePromise {\n const documentStore = documentMutationsStore(transaction);\n const mutationStore = mutationsStore(transaction);\n\n // The IndexedDb implementation in Chrome (and Firefox) does not handle\n // compound indices that include auto-generated keys correctly. To ensure\n // that the index entry is added correctly in all browsers, we perform two\n // writes: The first write is used to retrieve the next auto-generated Batch\n // ID, and the second write populates the index and stores the actual\n // mutation batch.\n // See: https://bugs.chromium.org/p/chromium/issues/detail?id=701972\n\n // We write an empty object to obtain key\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n return mutationStore.add({} as any).next(batchId => {\n hardAssert(\n typeof batchId === 'number',\n 0xbf7b,\n 'Auto-generated key is not a number'\n );\n\n const batch = new MutationBatch(\n batchId,\n localWriteTime,\n baseMutations,\n mutations\n );\n const dbBatch = toDbMutationBatch(this.serializer, this.userId, batch);\n\n const promises: Array> = [];\n let collectionParents = new SortedSet((l, r) =>\n primitiveComparator(l.canonicalString(), r.canonicalString())\n );\n for (const mutation of mutations) {\n const indexKey = newDbDocumentMutationKey(\n this.userId,\n mutation.key.path,\n batchId\n );\n collectionParents = collectionParents.add(mutation.key.path.popLast());\n promises.push(mutationStore.put(dbBatch));\n promises.push(\n documentStore.put(indexKey, DbDocumentMutationPlaceholder)\n );\n }\n\n collectionParents.forEach(parent => {\n promises.push(\n this.indexManager.addToCollectionParentIndex(transaction, parent)\n );\n });\n\n transaction.addOnCommittedListener(() => {\n this.documentKeysByBatchId[batchId] = batch.keys();\n });\n\n return PersistencePromise.waitFor(promises).next(() => batch);\n });\n }\n\n lookupMutationBatch(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise {\n return mutationsStore(transaction)\n .get(batchId)\n .next(dbBatch => {\n if (dbBatch) {\n hardAssert(\n dbBatch.userId === this.userId,\n 0x0030,\n `Unexpected user for mutation batch`,\n {\n userId: dbBatch.userId,\n batchId\n }\n );\n return fromDbMutationBatch(this.serializer, dbBatch);\n }\n return null;\n });\n }\n\n /**\n * Returns the document keys for the mutation batch with the given batchId.\n * For primary clients, this method returns `null` after\n * `removeMutationBatches()` has been called. Secondary clients return a\n * cached result until `removeCachedMutationKeys()` is invoked.\n */\n // PORTING NOTE: Multi-tab only.\n lookupMutationKeys(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise {\n if (this.documentKeysByBatchId[batchId]) {\n return PersistencePromise.resolve(\n this.documentKeysByBatchId[batchId]\n );\n } else {\n return this.lookupMutationBatch(transaction, batchId).next(batch => {\n if (batch) {\n const keys = batch.keys();\n this.documentKeysByBatchId[batchId] = keys;\n return keys;\n } else {\n return null;\n }\n });\n }\n }\n\n getNextMutationBatchAfterBatchId(\n transaction: PersistenceTransaction,\n batchId: BatchId\n ): PersistencePromise {\n const nextBatchId = batchId + 1;\n\n const range = IDBKeyRange.lowerBound([this.userId, nextBatchId]);\n let foundBatch: MutationBatch | null = null;\n return mutationsStore(transaction)\n .iterate(\n { index: DbMutationBatchUserMutationsIndex, range },\n (key, dbBatch, control) => {\n if (dbBatch.userId === this.userId) {\n hardAssert(\n dbBatch.batchId >= nextBatchId,\n 0xb9a4,\n 'Should have found mutation after `nextBatchId`',\n { nextBatchId }\n );\n foundBatch = fromDbMutationBatch(this.serializer, dbBatch);\n }\n control.done();\n }\n )\n .next(() => foundBatch);\n }\n\n getHighestUnacknowledgedBatchId(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n const range = IDBKeyRange.upperBound([\n this.userId,\n Number.POSITIVE_INFINITY\n ]);\n\n let batchId = BATCHID_UNKNOWN;\n return mutationsStore(transaction)\n .iterate(\n { index: DbMutationBatchUserMutationsIndex, range, reverse: true },\n (key, dbBatch, control) => {\n batchId = dbBatch.batchId;\n control.done();\n }\n )\n .next(() => batchId);\n }\n\n getAllMutationBatches(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n const range = IDBKeyRange.bound(\n [this.userId, BATCHID_UNKNOWN],\n [this.userId, Number.POSITIVE_INFINITY]\n );\n return mutationsStore(transaction)\n .loadAll(DbMutationBatchUserMutationsIndex, range)\n .next(dbBatches =>\n dbBatches.map(dbBatch => fromDbMutationBatch(this.serializer, dbBatch))\n );\n }\n\n getAllMutationBatchesAffectingDocumentKey(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n // Scan the document-mutation index starting with a prefix starting with\n // the given documentKey.\n const indexPrefix = newDbDocumentMutationPrefixForPath(\n this.userId,\n documentKey.path\n );\n const indexStart = IDBKeyRange.lowerBound(indexPrefix);\n\n const results: MutationBatch[] = [];\n return documentMutationsStore(transaction)\n .iterate({ range: indexStart }, (indexKey, _, control) => {\n const [userID, encodedPath, batchId] = indexKey;\n\n // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n const path = decodeResourcePath(encodedPath);\n if (userID !== this.userId || !documentKey.path.isEqual(path)) {\n control.done();\n return;\n }\n // Look up the mutation batch in the store.\n return mutationsStore(transaction)\n .get(batchId)\n .next(mutation => {\n if (!mutation) {\n throw fail(\n 0xf028,\n 'Dangling document-mutation reference found: `indexKey` which points to `batchId`',\n {\n indexKey,\n batchId\n }\n );\n }\n hardAssert(\n mutation.userId === this.userId,\n 0x2907,\n `Unexpected user for mutation batch`,\n {\n userId: mutation.userId,\n batchId\n }\n );\n results.push(fromDbMutationBatch(this.serializer, mutation));\n });\n })\n .next(() => results);\n }\n\n getAllMutationBatchesAffectingDocumentKeys(\n transaction: PersistenceTransaction,\n documentKeys: SortedMap\n ): PersistencePromise {\n let uniqueBatchIDs = new SortedSet(primitiveComparator);\n\n const promises: Array> = [];\n documentKeys.forEach(documentKey => {\n const indexStart = newDbDocumentMutationPrefixForPath(\n this.userId,\n documentKey.path\n );\n const range = IDBKeyRange.lowerBound(indexStart);\n\n const promise = documentMutationsStore(transaction).iterate(\n { range },\n (indexKey, _, control) => {\n const [userID, encodedPath, batchID] = indexKey;\n\n // Only consider rows matching exactly the specific key of\n // interest. Note that because we order by path first, and we\n // order terminators before path separators, we'll encounter all\n // the index rows for documentKey contiguously. In particular, all\n // the rows for documentKey will occur before any rows for\n // documents nested in a subcollection beneath documentKey so we\n // can stop as soon as we hit any such row.\n const path = decodeResourcePath(encodedPath);\n if (userID !== this.userId || !documentKey.path.isEqual(path)) {\n control.done();\n return;\n }\n\n uniqueBatchIDs = uniqueBatchIDs.add(batchID);\n }\n );\n\n promises.push(promise);\n });\n\n return PersistencePromise.waitFor(promises).next(() =>\n this.lookupMutationBatches(transaction, uniqueBatchIDs)\n );\n }\n\n getAllMutationBatchesAffectingQuery(\n transaction: PersistenceTransaction,\n query: Query\n ): PersistencePromise {\n debugAssert(\n !isDocumentQuery(query),\n \"Document queries shouldn't go down this path\"\n );\n debugAssert(\n !isCollectionGroupQuery(query),\n 'CollectionGroup queries should be handled in LocalDocumentsView'\n );\n\n const queryPath = query.path;\n const immediateChildrenLength = queryPath.length + 1;\n\n // TODO(mcg): Actually implement a single-collection query\n //\n // This is actually executing an ancestor query, traversing the whole\n // subtree below the collection which can be horrifically inefficient for\n // some structures. The right way to solve this is to implement the full\n // value index, but that's not in the cards in the near future so this is\n // the best we can do for the moment.\n //\n // Since we don't yet index the actual properties in the mutations, our\n // current approach is to just return all mutation batches that affect\n // documents in the collection being queried.\n const indexPrefix = newDbDocumentMutationPrefixForPath(\n this.userId,\n queryPath\n );\n const indexStart = IDBKeyRange.lowerBound(indexPrefix);\n\n // Collect up unique batchIDs encountered during a scan of the index. Use a\n // SortedSet to accumulate batch IDs so they can be traversed in order in a\n // scan of the main table.\n let uniqueBatchIDs = new SortedSet(primitiveComparator);\n return documentMutationsStore(transaction)\n .iterate({ range: indexStart }, (indexKey, _, control) => {\n const [userID, encodedPath, batchID] = indexKey;\n const path = decodeResourcePath(encodedPath);\n if (userID !== this.userId || !queryPath.isPrefixOf(path)) {\n control.done();\n return;\n }\n // Rows with document keys more than one segment longer than the\n // query path can't be matches. For example, a query on 'rooms'\n // can't match the document /rooms/abc/messages/xyx.\n // TODO(mcg): we'll need a different scanner when we implement\n // ancestor queries.\n if (path.length !== immediateChildrenLength) {\n return;\n }\n uniqueBatchIDs = uniqueBatchIDs.add(batchID);\n })\n .next(() => this.lookupMutationBatches(transaction, uniqueBatchIDs));\n }\n\n private lookupMutationBatches(\n transaction: PersistenceTransaction,\n batchIDs: SortedSet\n ): PersistencePromise {\n const results: MutationBatch[] = [];\n const promises: Array> = [];\n // TODO(rockwood): Implement this using iterate.\n batchIDs.forEach(batchId => {\n promises.push(\n mutationsStore(transaction)\n .get(batchId)\n .next(mutation => {\n if (mutation === null) {\n throw fail(\n 0x89ca,\n 'Dangling document-mutation reference found, which points to `batchId`',\n {\n batchId\n }\n );\n }\n hardAssert(\n mutation.userId === this.userId,\n 0x2614,\n `Unexpected user for mutation batch`,\n { userId: mutation.userId, batchId }\n );\n results.push(fromDbMutationBatch(this.serializer, mutation));\n })\n );\n });\n return PersistencePromise.waitFor(promises).next(() => results);\n }\n\n removeMutationBatch(\n transaction: PersistenceTransaction,\n batch: MutationBatch\n ): PersistencePromise {\n return removeMutationBatch(\n (transaction as IndexedDbTransaction).simpleDbTransaction,\n this.userId,\n batch\n ).next(removedDocuments => {\n transaction.addOnCommittedListener(() => {\n this.removeCachedMutationKeys(batch.batchId);\n });\n return PersistencePromise.forEach(\n removedDocuments,\n (key: DocumentKey) => {\n return this.referenceDelegate.markPotentiallyOrphaned(\n transaction,\n key\n );\n }\n );\n });\n }\n\n /**\n * Clears the cached keys for a mutation batch. This method should be\n * called by secondary clients after they process mutation updates.\n *\n * Note that this method does not have to be called from primary clients as\n * the corresponding cache entries are cleared when an acknowledged or\n * rejected batch is removed from the mutation queue.\n */\n // PORTING NOTE: Multi-tab only\n removeCachedMutationKeys(batchId: BatchId): void {\n delete this.documentKeysByBatchId[batchId];\n }\n\n performConsistencyCheck(\n txn: PersistenceTransaction\n ): PersistencePromise {\n return this.checkEmpty(txn).next(empty => {\n if (!empty) {\n return PersistencePromise.resolve();\n }\n\n // Verify that there are no entries in the documentMutations index if\n // the queue is empty.\n const startRange = IDBKeyRange.lowerBound(\n newDbDocumentMutationPrefixForUser(this.userId)\n );\n const danglingMutationReferences: ResourcePath[] = [];\n return documentMutationsStore(txn)\n .iterate({ range: startRange }, (key, _, control) => {\n const userID = key[0];\n if (userID !== this.userId) {\n control.done();\n return;\n } else {\n const path = decodeResourcePath(key[1]);\n danglingMutationReferences.push(path);\n }\n })\n .next(() => {\n hardAssert(\n danglingMutationReferences.length === 0,\n 0xdd90,\n 'Document leak -- detected dangling mutation references when queue is empty.',\n {\n danglingKeys: danglingMutationReferences.map(p =>\n p.canonicalString()\n )\n }\n );\n });\n });\n }\n\n containsKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return mutationQueueContainsKey(txn, this.userId, key);\n }\n\n // PORTING NOTE: Multi-tab only (state is held in memory in other clients).\n /** Returns the mutation queue's metadata from IndexedDb. */\n private getMutationQueueMetadata(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return mutationQueuesStore(transaction)\n .get(this.userId)\n .next((metadata: DbMutationQueue | null) => {\n return (\n metadata || {\n userId: this.userId,\n lastAcknowledgedBatchId: BATCHID_UNKNOWN,\n lastStreamToken: ''\n }\n );\n });\n }\n}\n\n/**\n * @returns true if the mutation queue for the given user contains a pending\n * mutation for the given key.\n */\nfunction mutationQueueContainsKey(\n txn: PersistenceTransaction,\n userId: string,\n key: DocumentKey\n): PersistencePromise {\n const indexKey = newDbDocumentMutationPrefixForPath(userId, key.path);\n const encodedPath = indexKey[1];\n const startRange = IDBKeyRange.lowerBound(indexKey);\n let containsKey = false;\n return documentMutationsStore(txn)\n .iterate({ range: startRange, keysOnly: true }, (key, value, control) => {\n const [userID, keyPath, /*batchID*/ _] = key;\n if (userID === userId && keyPath === encodedPath) {\n containsKey = true;\n }\n control.done();\n })\n .next(() => containsKey);\n}\n\n/** Returns true if any mutation queue contains the given document. */\nexport function mutationQueuesContainKey(\n txn: PersistenceTransaction,\n docKey: DocumentKey\n): PersistencePromise {\n let found = false;\n return mutationQueuesStore(txn)\n .iterateSerial(userId => {\n return mutationQueueContainsKey(txn, userId, docKey).next(containsKey => {\n if (containsKey) {\n found = true;\n }\n return PersistencePromise.resolve(!containsKey);\n });\n })\n .next(() => found);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutations object store.\n */\nfunction mutationsStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbMutationBatchStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction documentMutationsStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbDocumentMutationStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the mutationQueues object store.\n */\nfunction mutationQueuesStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbMutationQueueStore\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { TargetId } from './types';\n\n/** Offset to ensure non-overlapping target ids. */\nconst OFFSET = 2;\n\n/**\n * Generates monotonically increasing target IDs for sending targets to the\n * watch stream.\n *\n * The client constructs two generators, one for the target cache, and one for\n * for the sync engine (to generate limbo documents targets). These\n * generators produce non-overlapping IDs (by using even and odd IDs\n * respectively).\n *\n * By separating the target ID space, the query cache can generate target IDs\n * that persist across client restarts, while sync engine can independently\n * generate in-memory target IDs that are transient and can be reused after a\n * restart.\n */\nexport class TargetIdGenerator {\n constructor(private lastId: number) {}\n\n next(): TargetId {\n this.lastId += OFFSET;\n return this.lastId;\n }\n\n static forTargetCache(): TargetIdGenerator {\n // The target cache generator must return '2' in its first call to `next()`\n // as there is no differentiation in the protocol layer between an unset\n // number and the number '0'. If we were to sent a target with target ID\n // '0', the backend would consider it unset and replace it with its own ID.\n return new TargetIdGenerator(2 - OFFSET);\n }\n\n static forSyncEngine(): TargetIdGenerator {\n // Sync engine assigns target IDs for limbo document detection.\n return new TargetIdGenerator(1 - OFFSET);\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { canonifyTarget, Target, targetEquals } from '../core/target';\nimport { TargetIdGenerator } from '../core/target_id_generator';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { Timestamp } from '../lite-api/timestamp';\nimport { DocumentKeySet, documentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { hardAssert } from '../util/assert';\nimport { immediateSuccessor } from '../util/misc';\n\nimport {\n decodeResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { IndexedDbLruDelegate } from './indexeddb_lru_delegate';\nimport { DbTarget, DbTargetDocument, DbTargetGlobal } from './indexeddb_schema';\nimport {\n DbTargetDocumentDocumentTargetsIndex,\n DbTargetDocumentKey,\n DbTargetDocumentStore,\n DbTargetGlobalKey,\n DbTargetGlobalStore,\n DbTargetKey,\n DbTargetQueryTargetsIndexName,\n DbTargetStore\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport { fromDbTarget, LocalSerializer, toDbTarget } from './local_serializer';\nimport { ActiveTargets } from './lru_garbage_collector';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { SimpleDbStore } from './simple_db';\nimport { TargetCache } from './target_cache';\nimport { TargetData } from './target_data';\n\nexport class IndexedDbTargetCache implements TargetCache {\n constructor(\n private readonly referenceDelegate: IndexedDbLruDelegate,\n private serializer: LocalSerializer\n ) {}\n\n // PORTING NOTE: We don't cache global metadata for the target cache, since\n // some of it (in particular `highestTargetId`) can be modified by secondary\n // tabs. We could perhaps be more granular (and e.g. still cache\n // `lastRemoteSnapshotVersion` in memory) but for simplicity we currently go\n // to IndexedDb whenever we need to read metadata. We can revisit if it turns\n // out to have a meaningful performance impact.\n\n allocateTargetId(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(metadata => {\n const targetIdGenerator = new TargetIdGenerator(metadata.highestTargetId);\n metadata.highestTargetId = targetIdGenerator.next();\n return this.saveMetadata(transaction, metadata).next(\n () => metadata.highestTargetId\n );\n });\n }\n\n getLastRemoteSnapshotVersion(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(metadata => {\n return SnapshotVersion.fromTimestamp(\n new Timestamp(\n metadata.lastRemoteSnapshotVersion.seconds,\n metadata.lastRemoteSnapshotVersion.nanoseconds\n )\n );\n });\n }\n\n getHighestSequenceNumber(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(\n targetGlobal => targetGlobal.highestListenSequenceNumber\n );\n }\n\n setTargetsMetadata(\n transaction: PersistenceTransaction,\n highestListenSequenceNumber: number,\n lastRemoteSnapshotVersion?: SnapshotVersion\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(metadata => {\n metadata.highestListenSequenceNumber = highestListenSequenceNumber;\n if (lastRemoteSnapshotVersion) {\n metadata.lastRemoteSnapshotVersion =\n lastRemoteSnapshotVersion.toTimestamp();\n }\n if (highestListenSequenceNumber > metadata.highestListenSequenceNumber) {\n metadata.highestListenSequenceNumber = highestListenSequenceNumber;\n }\n return this.saveMetadata(transaction, metadata);\n });\n }\n\n addTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n return this.saveTargetData(transaction, targetData).next(() => {\n return this.retrieveMetadata(transaction).next(metadata => {\n metadata.targetCount += 1;\n this.updateMetadataFromTargetData(targetData, metadata);\n return this.saveMetadata(transaction, metadata);\n });\n });\n }\n\n updateTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n return this.saveTargetData(transaction, targetData);\n }\n\n removeTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n return this.removeMatchingKeysForTargetId(transaction, targetData.targetId)\n .next(() => targetsStore(transaction).delete(targetData.targetId))\n .next(() => this.retrieveMetadata(transaction))\n .next(metadata => {\n hardAssert(\n metadata.targetCount > 0,\n 0x1f81,\n 'Removing from an empty target cache'\n );\n metadata.targetCount -= 1;\n return this.saveMetadata(transaction, metadata);\n });\n }\n\n /**\n * Drops any targets with sequence number less than or equal to the upper bound, excepting those\n * present in `activeTargetIds`. Document associations for the removed targets are also removed.\n * Returns the number of targets removed.\n */\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n let count = 0;\n const promises: Array> = [];\n return targetsStore(txn)\n .iterate((key, value) => {\n const targetData = fromDbTarget(value);\n if (\n targetData.sequenceNumber <= upperBound &&\n activeTargetIds.get(targetData.targetId) === null\n ) {\n count++;\n promises.push(this.removeTargetData(txn, targetData));\n }\n })\n .next(() => PersistencePromise.waitFor(promises))\n .next(() => count);\n }\n\n /**\n * Call provided function with each `TargetData` that we have cached.\n */\n forEachTarget(\n txn: PersistenceTransaction,\n f: (q: TargetData) => void\n ): PersistencePromise {\n return targetsStore(txn).iterate((key, value) => {\n const targetData = fromDbTarget(value);\n f(targetData);\n });\n }\n\n private retrieveMetadata(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return globalTargetStore(transaction)\n .get(DbTargetGlobalKey)\n .next(metadata => {\n hardAssert(metadata !== null, 0x0b48, 'Missing metadata row.');\n return metadata;\n });\n }\n\n private saveMetadata(\n transaction: PersistenceTransaction,\n metadata: DbTargetGlobal\n ): PersistencePromise {\n return globalTargetStore(transaction).put(DbTargetGlobalKey, metadata);\n }\n\n private saveTargetData(\n transaction: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n return targetsStore(transaction).put(\n toDbTarget(this.serializer, targetData)\n );\n }\n\n /**\n * In-place updates the provided metadata to account for values in the given\n * TargetData. Saving is done separately. Returns true if there were any\n * changes to the metadata.\n */\n private updateMetadataFromTargetData(\n targetData: TargetData,\n metadata: DbTargetGlobal\n ): boolean {\n let updated = false;\n if (targetData.targetId > metadata.highestTargetId) {\n metadata.highestTargetId = targetData.targetId;\n updated = true;\n }\n\n if (targetData.sequenceNumber > metadata.highestListenSequenceNumber) {\n metadata.highestListenSequenceNumber = targetData.sequenceNumber;\n updated = true;\n }\n return updated;\n }\n\n getTargetCount(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n return this.retrieveMetadata(transaction).next(\n metadata => metadata.targetCount\n );\n }\n\n getTargetData(\n transaction: PersistenceTransaction,\n target: Target\n ): PersistencePromise {\n // Iterating by the canonicalId may yield more than one result because\n // canonicalId values are not required to be unique per target. This query\n // depends on the queryTargets index to be efficient.\n const canonicalId = canonifyTarget(target);\n const range = IDBKeyRange.bound(\n [canonicalId, Number.NEGATIVE_INFINITY],\n [canonicalId, Number.POSITIVE_INFINITY]\n );\n let result: TargetData | null = null;\n return targetsStore(transaction)\n .iterate(\n { range, index: DbTargetQueryTargetsIndexName },\n (key, value, control) => {\n const found = fromDbTarget(value);\n // After finding a potential match, check that the target is\n // actually equal to the requested target.\n if (targetEquals(target, found.target)) {\n result = found;\n control.done();\n }\n }\n )\n .next(() => result);\n }\n\n addMatchingKeys(\n txn: PersistenceTransaction,\n keys: DocumentKeySet,\n targetId: TargetId\n ): PersistencePromise {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n const promises: Array> = [];\n const store = documentTargetStore(txn);\n keys.forEach(key => {\n const path = encodeResourcePath(key.path);\n promises.push(store.put({ targetId, path }));\n promises.push(this.referenceDelegate.addReference(txn, targetId, key));\n });\n return PersistencePromise.waitFor(promises);\n }\n\n removeMatchingKeys(\n txn: PersistenceTransaction,\n keys: DocumentKeySet,\n targetId: TargetId\n ): PersistencePromise {\n // PORTING NOTE: The reverse index (documentsTargets) is maintained by\n // IndexedDb.\n const store = documentTargetStore(txn);\n return PersistencePromise.forEach(keys, (key: DocumentKey) => {\n const path = encodeResourcePath(key.path);\n return PersistencePromise.waitFor([\n store.delete([targetId, path]),\n this.referenceDelegate.removeReference(txn, targetId, key)\n ]);\n });\n }\n\n removeMatchingKeysForTargetId(\n txn: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise {\n const store = documentTargetStore(txn);\n const range = IDBKeyRange.bound(\n [targetId],\n [targetId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n return store.delete(range);\n }\n\n getMatchingKeysForTargetId(\n txn: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise {\n const range = IDBKeyRange.bound(\n [targetId],\n [targetId + 1],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n const store = documentTargetStore(txn);\n let result = documentKeySet();\n\n return store\n .iterate({ range, keysOnly: true }, (key, _, control) => {\n const path = decodeResourcePath(key[1]);\n const docKey = new DocumentKey(path);\n result = result.add(docKey);\n })\n .next(() => result);\n }\n\n containsKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n const path = encodeResourcePath(key.path);\n const range = IDBKeyRange.bound(\n [path],\n [immediateSuccessor(path)],\n /*lowerOpen=*/ false,\n /*upperOpen=*/ true\n );\n let count = 0;\n return documentTargetStore(txn!)\n .iterate(\n {\n index: DbTargetDocumentDocumentTargetsIndex,\n keysOnly: true,\n range\n },\n ([targetId, path], _, control) => {\n // Having a sentinel row for a document does not count as containing that document;\n // For the target cache, containing the document means the document is part of some\n // target.\n if (targetId !== 0) {\n count++;\n control.done();\n }\n }\n )\n .next(() => count > 0);\n }\n\n /**\n * Looks up a TargetData entry by target ID.\n *\n * @param targetId - The target ID of the TargetData entry to look up.\n * @returns The cached TargetData entry, or null if the cache has no entry for\n * the target.\n */\n // PORTING NOTE: Multi-tab only.\n getTargetDataForTarget(\n transaction: PersistenceTransaction,\n targetId: TargetId\n ): PersistencePromise {\n return targetsStore(transaction)\n .get(targetId)\n .next(found => {\n if (found) {\n return fromDbTarget(found);\n } else {\n return null;\n }\n });\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the queries object store.\n */\nfunction targetsStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbTargetStore);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the target globals object store.\n */\nfunction globalTargetStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(txn, DbTargetGlobalStore);\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the document target object store.\n */\nexport function documentTargetStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbTargetDocumentStore\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FirestoreError } from '../api';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { ListenSequenceNumber } from '../core/types';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { getLogLevel, logDebug, LogLevel } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { ignoreIfPrimaryLeaseLoss, LocalStore } from './local_store';\nimport {\n ActiveTargets,\n GC_DID_NOT_RUN,\n LRU_COLLECTION_DISABLED,\n LruDelegate,\n LruGarbageCollector,\n LruParams,\n LruResults\n} from './lru_garbage_collector';\nimport { Scheduler } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { isIndexedDbTransactionError } from './simple_db';\n\nconst LOG_TAG = 'LruGarbageCollector';\n\nexport const LRU_MINIMUM_CACHE_SIZE_BYTES = 1 * 1024 * 1024;\n\n/** How long we wait to try running LRU GC after SDK initialization. */\nconst INITIAL_GC_DELAY_MS = 1 * 60 * 1000;\n/** Minimum amount of time between GC checks, after the first one. */\nconst REGULAR_GC_DELAY_MS = 5 * 60 * 1000;\n\n// The type and comparator for the items contained in the SortedSet used in\n// place of a priority queue for the RollingSequenceNumberBuffer.\ntype BufferEntry = [ListenSequenceNumber, number];\n\nfunction bufferEntryComparator(\n [aSequence, aIndex]: BufferEntry,\n [bSequence, bIndex]: BufferEntry\n): number {\n const seqCmp = primitiveComparator(aSequence, bSequence);\n if (seqCmp === 0) {\n // This order doesn't matter, but we can bias against churn by sorting\n // entries created earlier as less than newer entries.\n return primitiveComparator(aIndex, bIndex);\n } else {\n return seqCmp;\n }\n}\n\n/**\n * Used to calculate the nth sequence number. Keeps a rolling buffer of the\n * lowest n values passed to `addElement`, and finally reports the largest of\n * them in `maxValue`.\n */\nclass RollingSequenceNumberBuffer {\n private buffer: SortedSet = 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\nimport { ListenSequence } from '../core/listen_sequence';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { ListenSequenceNumber, TargetId } from '../core/types';\nimport { DocumentKey } from '../model/document_key';\n\nimport {\n decodeResourcePath,\n EncodedResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { IndexedDbLruDelegate } from './indexeddb_lru_delegate';\nimport { mutationQueuesContainKey } from './indexeddb_mutation_queue';\nimport { DbTargetDocument } from './indexeddb_schema';\nimport { DbTargetDocumentDocumentTargetsIndex } from './indexeddb_sentinels';\nimport {\n documentTargetStore,\n IndexedDbTargetCache\n} from './indexeddb_target_cache';\nimport {\n ActiveTargets,\n LruGarbageCollector,\n LruParams\n} from './lru_garbage_collector';\nimport { newLruGarbageCollector } from './lru_garbage_collector_impl';\nimport { Persistence } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { TargetData } from './target_data';\n\n/** Provides LRU functionality for IndexedDB persistence. */\nexport class IndexedDbLruDelegateImpl implements IndexedDbLruDelegate {\n readonly garbageCollector: LruGarbageCollector;\n\n constructor(private readonly db: Persistence, params: LruParams) {\n this.garbageCollector = newLruGarbageCollector(this, params);\n }\n\n getSequenceNumberCount(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const docCountPromise = this.orphanedDocumentCount(txn);\n const targetCountPromise = this.db.getTargetCache().getTargetCount(txn);\n return targetCountPromise.next(targetCount =>\n docCountPromise.next(docCount => targetCount + docCount)\n );\n }\n\n private orphanedDocumentCount(\n txn: PersistenceTransaction\n ): PersistencePromise {\n let orphanedCount = 0;\n return this.forEachOrphanedDocumentSequenceNumber(txn, _ => {\n orphanedCount++;\n }).next(() => orphanedCount);\n }\n\n forEachTarget(\n txn: PersistenceTransaction,\n f: (q: TargetData) => void\n ): PersistencePromise {\n return this.db.getTargetCache().forEachTarget(txn, f);\n }\n\n forEachOrphanedDocumentSequenceNumber(\n txn: PersistenceTransaction,\n f: (sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise {\n return this.forEachOrphanedDocument(txn, (docKey, sequenceNumber) =>\n f(sequenceNumber)\n );\n }\n\n addReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise {\n return writeSentinelKey(txn, key);\n }\n\n removeReference(\n txn: PersistenceTransaction,\n targetId: TargetId,\n key: DocumentKey\n ): PersistencePromise {\n return writeSentinelKey(txn, key);\n }\n\n removeTargets(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber,\n activeTargetIds: ActiveTargets\n ): PersistencePromise {\n return (this.db.getTargetCache() as IndexedDbTargetCache).removeTargets(\n txn,\n upperBound,\n activeTargetIds\n );\n }\n\n markPotentiallyOrphaned(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return writeSentinelKey(txn, key);\n }\n\n /**\n * Returns true if anything would prevent this document from being garbage\n * collected, given that the document in question is not present in any\n * targets and has a sequence number less than or equal to the upper bound for\n * the collection run.\n */\n private isPinned(\n txn: PersistenceTransaction,\n docKey: DocumentKey\n ): PersistencePromise {\n return mutationQueuesContainKey(txn, docKey);\n }\n\n removeOrphanedDocuments(\n txn: PersistenceTransaction,\n upperBound: ListenSequenceNumber\n ): PersistencePromise {\n const documentCache = this.db.getRemoteDocumentCache();\n const changeBuffer = documentCache.newChangeBuffer();\n\n const promises: Array> = [];\n let documentCount = 0;\n\n const iteration = this.forEachOrphanedDocument(\n txn,\n (docKey, sequenceNumber) => {\n if (sequenceNumber <= upperBound) {\n const p = this.isPinned(txn, docKey).next(isPinned => {\n if (!isPinned) {\n documentCount++;\n // Our size accounting requires us to read all documents before\n // removing them.\n return changeBuffer.getEntry(txn, docKey).next(() => {\n changeBuffer.removeEntry(docKey, SnapshotVersion.min());\n return documentTargetStore(txn).delete(sentinelKey(docKey));\n });\n }\n });\n promises.push(p);\n }\n }\n );\n\n return iteration\n .next(() => PersistencePromise.waitFor(promises))\n .next(() => changeBuffer.apply(txn))\n .next(() => documentCount);\n }\n\n removeTarget(\n txn: PersistenceTransaction,\n targetData: TargetData\n ): PersistencePromise {\n const updated = targetData.withSequenceNumber(txn.currentSequenceNumber);\n return this.db.getTargetCache().updateTargetData(txn, updated);\n }\n\n updateLimboDocument(\n txn: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\n return writeSentinelKey(txn, key);\n }\n\n /**\n * Call provided function for each document in the cache that is 'orphaned'. Orphaned\n * means not a part of any target, so the only entry in the target-document index for\n * that document will be the sentinel row (targetId 0), which will also have the sequence\n * number for the last time the document was accessed.\n */\n private forEachOrphanedDocument(\n txn: PersistenceTransaction,\n f: (docKey: DocumentKey, sequenceNumber: ListenSequenceNumber) => void\n ): PersistencePromise {\n const store = documentTargetStore(txn);\n let nextToReport: ListenSequenceNumber = ListenSequence.INVALID;\n let nextPath: EncodedResourcePath;\n return store\n .iterate(\n {\n index: DbTargetDocumentDocumentTargetsIndex\n },\n ([targetId, docKey], { path, sequenceNumber }) => {\n if (targetId === 0) {\n // if nextToReport is valid, report it, this is a new key so the\n // last one must not be a member of any targets.\n if (nextToReport !== ListenSequence.INVALID) {\n f(new DocumentKey(decodeResourcePath(nextPath)), nextToReport);\n }\n // set nextToReport to be this sequence number. It's the next one we\n // might report, if we don't find any targets for this document.\n // Note that the sequence number must be defined when the targetId\n // is 0.\n nextToReport = sequenceNumber!;\n nextPath = path;\n } else {\n // set nextToReport to be invalid, we know we don't need to report\n // this one since we found a target for it.\n nextToReport = ListenSequence.INVALID;\n }\n }\n )\n .next(() => {\n // Since we report sequence numbers after getting to the next key, we\n // need to check if the last key we iterated over was an orphaned\n // document and report it.\n if (nextToReport !== ListenSequence.INVALID) {\n f(new DocumentKey(decodeResourcePath(nextPath)), nextToReport);\n }\n });\n }\n\n getCacheSize(txn: PersistenceTransaction): PersistencePromise {\n return this.db.getRemoteDocumentCache().getSize(txn);\n }\n}\n\nfunction sentinelKey(key: DocumentKey): [TargetId, EncodedResourcePath] {\n return [0, encodeResourcePath(key.path)];\n}\n\n/**\n * @returns A value suitable for writing a sentinel row in the target-document\n * store.\n */\nfunction sentinelRow(\n key: DocumentKey,\n sequenceNumber: ListenSequenceNumber\n): DbTargetDocument {\n return { targetId: 0, path: encodeResourcePath(key.path), sequenceNumber };\n}\n\nfunction writeSentinelKey(\n txn: PersistenceTransaction,\n key: DocumentKey\n): PersistencePromise {\n return documentTargetStore(txn).put(\n sentinelRow(key, txn.currentSequenceNumber)\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { DocumentKeySet, MutableDocumentMap } from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { debugAssert } from '../util/assert';\nimport { ObjectMap } from '../util/obj_map';\n\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\n\n/**\n * An in-memory buffer of entries to be written to a RemoteDocumentCache.\n * It can be used to batch up a set of changes to be written to the cache, but\n * additionally supports reading entries back with the `getEntry()` method,\n * falling back to the underlying RemoteDocumentCache if no entry is\n * buffered.\n *\n * Entries added to the cache *must* be read first. This is to facilitate\n * calculating the size delta of the pending changes.\n *\n * PORTING NOTE: This class was implemented then removed from other platforms.\n * If byte-counting ends up being needed on the other platforms, consider\n * porting this class as part of that implementation work.\n */\nexport abstract class RemoteDocumentChangeBuffer {\n // A mapping of document key to the new cache entry that should be written.\n protected changes: ObjectMap = 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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Query, queryMatches } from '../core/query';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport {\n DocumentKeySet,\n DocumentSizeEntries,\n MutableDocumentMap,\n mutableDocumentMap,\n OverlayMap\n} from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { IndexOffset } from '../model/field_index';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert, hardAssert } from '../util/assert';\nimport { primitiveComparator } from '../util/misc';\nimport { ObjectMap } from '../util/obj_map';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\n\nimport { IndexManager } from './index_manager';\nimport { dbDocumentSize } from './indexeddb_mutation_batch_impl';\nimport { DbRemoteDocument, DbRemoteDocumentGlobal } from './indexeddb_schema';\nimport {\n DbRemoteDocumentCollectionGroupIndex,\n DbRemoteDocumentDocumentKeyIndex,\n DbRemoteDocumentGlobalKey,\n DbRemoteDocumentGlobalStore,\n DbRemoteDocumentKey,\n DbRemoteDocumentStore,\n DbTimestampKey\n} from './indexeddb_sentinels';\nimport { getStore } from './indexeddb_transaction';\nimport {\n fromDbRemoteDocument,\n LocalSerializer,\n toDbRemoteDocument,\n toDbTimestampKey\n} from './local_serializer';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { QueryContext } from './query_context';\nimport { RemoteDocumentCache } from './remote_document_cache';\nimport { RemoteDocumentChangeBuffer } from './remote_document_change_buffer';\nimport { SimpleDbStore } from './simple_db';\n\nexport interface DocumentSizeEntry {\n document: MutableDocument;\n size: number;\n}\n\nexport interface IndexedDbRemoteDocumentCache extends RemoteDocumentCache {\n // The IndexedDbRemoteDocumentCache doesn't implement any methods on top\n // of RemoteDocumentCache. This class exists for consistency.\n}\n\n/**\n * The RemoteDocumentCache for IndexedDb. To construct, invoke\n * `newIndexedDbRemoteDocumentCache()`.\n */\nclass IndexedDbRemoteDocumentCacheImpl implements IndexedDbRemoteDocumentCache {\n indexManager!: IndexManager;\n\n constructor(readonly serializer: LocalSerializer) {}\n\n setIndexManager(indexManager: IndexManager): void {\n this.indexManager = indexManager;\n }\n\n /**\n * Adds the supplied entries to the cache.\n *\n * All calls of `addEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n */\n addEntry(\n transaction: PersistenceTransaction,\n key: DocumentKey,\n doc: DbRemoteDocument\n ): PersistencePromise {\n const documentStore = remoteDocumentsStore(transaction);\n return documentStore.put(doc);\n }\n\n /**\n * Removes a document from the cache.\n *\n * All calls of `removeEntry` are required to go through the RemoteDocumentChangeBuffer\n * returned by `newChangeBuffer()` to ensure proper accounting of metadata.\n */\n removeEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey,\n readTime: SnapshotVersion\n ): PersistencePromise {\n const store = remoteDocumentsStore(transaction);\n return store.delete(dbReadTimeKey(documentKey, readTime));\n }\n\n /**\n * Updates the current cache size.\n *\n * Callers to `addEntry()` and `removeEntry()` *must* call this afterwards to update the\n * cache's metadata.\n */\n updateMetadata(\n transaction: PersistenceTransaction,\n sizeDelta: number\n ): PersistencePromise {\n return this.getMetadata(transaction).next(metadata => {\n metadata.byteSize += sizeDelta;\n return this.setMetadata(transaction, metadata);\n });\n }\n\n getEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n let doc = MutableDocument.newInvalidDocument(documentKey);\n return remoteDocumentsStore(transaction)\n .iterate(\n {\n index: DbRemoteDocumentDocumentKeyIndex,\n range: IDBKeyRange.only(dbKey(documentKey))\n },\n (_, dbRemoteDoc) => {\n doc = this.maybeDecodeDocument(documentKey, dbRemoteDoc);\n }\n )\n .next(() => doc);\n }\n\n /**\n * Looks up an entry in the cache.\n *\n * @param documentKey - The key of the entry to look up.\n * @returns The cached document entry and its size.\n */\n getSizedEntry(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n let result = {\n size: 0,\n document: MutableDocument.newInvalidDocument(documentKey)\n };\n return remoteDocumentsStore(transaction)\n .iterate(\n {\n index: DbRemoteDocumentDocumentKeyIndex,\n range: IDBKeyRange.only(dbKey(documentKey))\n },\n (_, dbRemoteDoc) => {\n result = {\n document: this.maybeDecodeDocument(documentKey, dbRemoteDoc),\n size: dbDocumentSize(dbRemoteDoc)\n };\n }\n )\n .next(() => result);\n }\n\n getEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise {\n let results = mutableDocumentMap();\n return this.forEachDbEntry(\n transaction,\n documentKeys,\n (key, dbRemoteDoc) => {\n const doc = this.maybeDecodeDocument(key, dbRemoteDoc);\n results = results.insert(key, doc);\n }\n ).next(() => results);\n }\n\n /**\n * Looks up several entries in the cache.\n *\n * @param documentKeys - The set of keys entries to look up.\n * @returns A map of documents indexed by key and a map of sizes indexed by\n * key (zero if the document does not exist).\n */\n getSizedEntries(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise {\n let results = mutableDocumentMap();\n let sizeMap = new SortedMap(DocumentKey.comparator);\n return this.forEachDbEntry(\n transaction,\n documentKeys,\n (key, dbRemoteDoc) => {\n const doc = this.maybeDecodeDocument(key, dbRemoteDoc);\n results = results.insert(key, doc);\n sizeMap = sizeMap.insert(key, dbDocumentSize(dbRemoteDoc));\n }\n ).next(() => {\n return { documents: results, sizeMap };\n });\n }\n\n private forEachDbEntry(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet,\n callback: (key: DocumentKey, doc: DbRemoteDocument | null) => void\n ): PersistencePromise {\n if (documentKeys.isEmpty()) {\n return PersistencePromise.resolve();\n }\n\n let sortedKeys = new SortedSet(dbKeyComparator);\n documentKeys.forEach(e => (sortedKeys = sortedKeys.add(e)));\n const range = IDBKeyRange.bound(\n dbKey(sortedKeys.first()!),\n dbKey(sortedKeys.last()!)\n );\n const keyIter = sortedKeys.getIterator();\n let nextKey: DocumentKey | null = keyIter.getNext();\n\n return remoteDocumentsStore(transaction)\n .iterate(\n { index: DbRemoteDocumentDocumentKeyIndex, range },\n (_, dbRemoteDoc, control) => {\n const potentialKey = DocumentKey.fromSegments([\n ...dbRemoteDoc.prefixPath,\n dbRemoteDoc.collectionGroup,\n dbRemoteDoc.documentId\n ]);\n\n // Go through keys not found in cache.\n while (nextKey && dbKeyComparator(nextKey!, potentialKey) < 0) {\n callback(nextKey!, null);\n nextKey = keyIter.getNext();\n }\n\n if (nextKey && nextKey!.isEqual(potentialKey)) {\n // Key found in cache.\n callback(nextKey!, dbRemoteDoc);\n nextKey = keyIter.hasNext() ? keyIter.getNext() : null;\n }\n\n // Skip to the next key (if there is one).\n if (nextKey) {\n control.skip(dbKey(nextKey));\n } else {\n control.done();\n }\n }\n )\n .next(() => {\n // The rest of the keys are not in the cache. One case where `iterate`\n // above won't go through them is when the cache is empty.\n while (nextKey) {\n callback(nextKey!, null);\n nextKey = keyIter.hasNext() ? keyIter.getNext() : null;\n }\n });\n }\n\n getDocumentsMatchingQuery(\n transaction: PersistenceTransaction,\n query: Query,\n offset: IndexOffset,\n mutatedDocs: OverlayMap,\n context?: QueryContext\n ): PersistencePromise {\n const collection = query.path;\n const startKey = [\n collection.popLast().toArray(),\n collection.lastSegment(),\n toDbTimestampKey(offset.readTime),\n offset.documentKey.path.isEmpty()\n ? ''\n : offset.documentKey.path.lastSegment()\n ];\n const endKey: DbRemoteDocumentKey = [\n collection.popLast().toArray(),\n collection.lastSegment(),\n [Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER],\n ''\n ];\n\n return remoteDocumentsStore(transaction)\n .loadAll(IDBKeyRange.bound(startKey, endKey, true))\n .next(dbRemoteDocs => {\n context?.incrementDocumentReadCount(dbRemoteDocs.length);\n let results = mutableDocumentMap();\n for (const dbRemoteDoc of dbRemoteDocs) {\n const document = this.maybeDecodeDocument(\n DocumentKey.fromSegments(\n dbRemoteDoc.prefixPath.concat(\n dbRemoteDoc.collectionGroup,\n dbRemoteDoc.documentId\n )\n ),\n dbRemoteDoc\n );\n if (\n document.isFoundDocument() &&\n (queryMatches(query, document) || mutatedDocs.has(document.key))\n ) {\n // Either the document matches the given query, or it is mutated.\n results = results.insert(document.key, document);\n }\n }\n return results;\n });\n }\n\n getAllFromCollectionGroup(\n transaction: PersistenceTransaction,\n collectionGroup: string,\n offset: IndexOffset,\n limit: number\n ): PersistencePromise {\n debugAssert(limit > 0, 'Limit should be at least 1');\n let results = mutableDocumentMap();\n\n const startKey = dbCollectionGroupKey(collectionGroup, offset);\n const endKey = dbCollectionGroupKey(collectionGroup, IndexOffset.max());\n return remoteDocumentsStore(transaction)\n .iterate(\n {\n index: DbRemoteDocumentCollectionGroupIndex,\n range: IDBKeyRange.bound(startKey, endKey, true)\n },\n (_, dbRemoteDoc, control) => {\n const document = this.maybeDecodeDocument(\n DocumentKey.fromSegments(\n dbRemoteDoc.prefixPath.concat(\n dbRemoteDoc.collectionGroup,\n dbRemoteDoc.documentId\n )\n ),\n dbRemoteDoc\n );\n results = results.insert(document.key, document);\n if (results.size === limit) {\n control.done();\n }\n }\n )\n .next(() => results);\n }\n\n newChangeBuffer(options?: {\n trackRemovals: boolean;\n }): RemoteDocumentChangeBuffer {\n return new IndexedDbRemoteDocumentChangeBuffer(\n this,\n !!options && options.trackRemovals\n );\n }\n\n getSize(txn: PersistenceTransaction): PersistencePromise {\n return this.getMetadata(txn).next(metadata => metadata.byteSize);\n }\n\n private getMetadata(\n txn: PersistenceTransaction\n ): PersistencePromise {\n return documentGlobalStore(txn)\n .get(DbRemoteDocumentGlobalKey)\n .next(metadata => {\n hardAssert(!!metadata, 0x4e35, 'Missing document cache metadata');\n return metadata!;\n });\n }\n\n private setMetadata(\n txn: PersistenceTransaction,\n metadata: DbRemoteDocumentGlobal\n ): PersistencePromise {\n return documentGlobalStore(txn).put(DbRemoteDocumentGlobalKey, metadata);\n }\n\n /**\n * Decodes `dbRemoteDoc` and returns the document (or an invalid document if\n * the document corresponds to the format used for sentinel deletes).\n */\n private maybeDecodeDocument(\n documentKey: DocumentKey,\n dbRemoteDoc: DbRemoteDocument | null\n ): MutableDocument {\n if (dbRemoteDoc) {\n const doc = fromDbRemoteDocument(this.serializer, dbRemoteDoc);\n // Whether the document is a sentinel removal and should only be used in the\n // `getNewDocumentChanges()`\n const isSentinelRemoval =\n doc.isNoDocument() && doc.version.isEqual(SnapshotVersion.min());\n if (!isSentinelRemoval) {\n return doc;\n }\n }\n return MutableDocument.newInvalidDocument(documentKey);\n }\n}\n\n/** Creates a new IndexedDbRemoteDocumentCache. */\nexport function newIndexedDbRemoteDocumentCache(\n serializer: LocalSerializer\n): IndexedDbRemoteDocumentCache {\n return new IndexedDbRemoteDocumentCacheImpl(serializer);\n}\n\n/**\n * Handles the details of adding and updating documents in the IndexedDbRemoteDocumentCache.\n *\n * Unlike the MemoryRemoteDocumentChangeBuffer, the IndexedDb implementation computes the size\n * delta for all submitted changes. This avoids having to re-read all documents from IndexedDb\n * when we apply the changes.\n */\nclass IndexedDbRemoteDocumentChangeBuffer extends RemoteDocumentChangeBuffer {\n // A map of document sizes and read times prior to applying the changes in\n // this buffer.\n protected documentStates: ObjectMap<\n DocumentKey,\n { size: number; readTime: SnapshotVersion }\n > = new ObjectMap(\n key => key.toString(),\n (l, r) => l.isEqual(r)\n );\n\n /**\n * @param documentCache - The IndexedDbRemoteDocumentCache to apply the changes to.\n * @param trackRemovals - Whether to create sentinel deletes that can be tracked by\n * `getNewDocumentChanges()`.\n */\n constructor(\n private readonly documentCache: IndexedDbRemoteDocumentCacheImpl,\n private readonly trackRemovals: boolean\n ) {\n super();\n }\n\n protected applyChanges(\n transaction: PersistenceTransaction\n ): PersistencePromise {\n const promises: Array> = [];\n\n let sizeDelta = 0;\n\n let collectionParents = new SortedSet((l, r) =>\n primitiveComparator(l.canonicalString(), r.canonicalString())\n );\n\n this.changes.forEach((key, documentChange) => {\n const previousDoc = this.documentStates.get(key);\n debugAssert(\n previousDoc !== undefined,\n `Cannot modify a document that wasn't read (for ${key})`\n );\n promises.push(\n this.documentCache.removeEntry(transaction, key, previousDoc.readTime)\n );\n if (documentChange.isValidDocument()) {\n debugAssert(\n !documentChange.readTime.isEqual(SnapshotVersion.min()),\n 'Cannot add a document with a read time of zero'\n );\n const doc = toDbRemoteDocument(\n this.documentCache.serializer,\n documentChange\n );\n collectionParents = collectionParents.add(key.path.popLast());\n\n const size = dbDocumentSize(doc);\n sizeDelta += size - previousDoc.size;\n promises.push(this.documentCache.addEntry(transaction, key, doc));\n } else {\n sizeDelta -= previousDoc.size;\n if (this.trackRemovals) {\n // In order to track removals, we store a \"sentinel delete\" in the\n // RemoteDocumentCache. This entry is represented by a NoDocument\n // with a version of 0 and ignored by `maybeDecodeDocument()` but\n // preserved in `getNewDocumentChanges()`.\n const deletedDoc = toDbRemoteDocument(\n this.documentCache.serializer,\n documentChange.convertToNoDocument(SnapshotVersion.min())\n );\n promises.push(\n this.documentCache.addEntry(transaction, key, deletedDoc)\n );\n }\n }\n });\n\n collectionParents.forEach(parent => {\n promises.push(\n this.documentCache.indexManager.addToCollectionParentIndex(\n transaction,\n parent\n )\n );\n });\n\n promises.push(this.documentCache.updateMetadata(transaction, sizeDelta));\n\n return PersistencePromise.waitFor(promises);\n }\n\n protected getFromCache(\n transaction: PersistenceTransaction,\n documentKey: DocumentKey\n ): PersistencePromise {\n // Record the size of everything we load from the cache so we can compute a delta later.\n return this.documentCache\n .getSizedEntry(transaction, documentKey)\n .next(getResult => {\n this.documentStates.set(documentKey, {\n size: getResult.size,\n readTime: getResult.document.readTime\n });\n return getResult.document;\n });\n }\n\n protected getAllFromCache(\n transaction: PersistenceTransaction,\n documentKeys: DocumentKeySet\n ): PersistencePromise {\n // Record the size of everything we load from the cache so we can compute\n // a delta later.\n return this.documentCache\n .getSizedEntries(transaction, documentKeys)\n .next(({ documents, sizeMap }) => {\n // Note: `getAllFromCache` returns two maps instead of a single map from\n // keys to `DocumentSizeEntry`s. This is to allow returning the\n // `MutableDocumentMap` directly, without a conversion.\n sizeMap.forEach((documentKey, size) => {\n this.documentStates.set(documentKey, {\n size,\n readTime: documents.get(documentKey)!.readTime\n });\n });\n return documents;\n });\n }\n}\n\nfunction documentGlobalStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbRemoteDocumentGlobalStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the remoteDocuments object store.\n */\nfunction remoteDocumentsStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbRemoteDocumentStore\n );\n}\n\n/**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentKeyIndex` index.\n */\nfunction dbKey(documentKey: DocumentKey): [string[], string, string] {\n const path = documentKey.path.toArray();\n return [\n /* prefix path */ path.slice(0, path.length - 2),\n /* collection id */ path[path.length - 2],\n /* document id */ path[path.length - 1]\n ];\n}\n\n/**\n * Returns a key that can be used for document lookups via the primary key of\n * the DbRemoteDocument object store.\n */\nfunction dbReadTimeKey(\n documentKey: DocumentKey,\n readTime: SnapshotVersion\n): DbRemoteDocumentKey {\n const path = documentKey.path.toArray();\n return [\n /* prefix path */ path.slice(0, path.length - 2),\n /* collection id */ path[path.length - 2],\n toDbTimestampKey(readTime),\n /* document id */ path[path.length - 1]\n ];\n}\n\n/**\n * Returns a key that can be used for document lookups on the\n * `DbRemoteDocumentDocumentCollectionGroupIndex` index.\n */\nfunction dbCollectionGroupKey(\n collectionGroup: string,\n offset: IndexOffset\n): [string, DbTimestampKey, string[], string] {\n const path = offset.documentKey.path.toArray();\n return [\n /* collection id */ collectionGroup,\n toDbTimestampKey(offset.readTime),\n /* prefix path */ path.slice(0, path.length - 2),\n /* document id */ path.length > 0 ? path[path.length - 1] : ''\n ];\n}\n\n/**\n * Comparator that compares document keys according to the primary key sorting\n * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id\n * and then document ID).\n *\n * Visible for testing.\n */\nexport function dbKeyComparator(l: DocumentKey, r: DocumentKey): number {\n const left = l.path.toArray();\n const right = r.path.toArray();\n\n // The ordering is based on https://chromium.googlesource.com/chromium/blink/+/fe5c21fef94dae71c1c3344775b8d8a7f7e6d9ec/Source/modules/indexeddb/IDBKey.cpp#74\n let cmp = 0;\n for (let i = 0; i < left.length - 2 && i < right.length - 2; ++i) {\n cmp = primitiveComparator(left[i], right[i]);\n if (cmp) {\n return cmp;\n }\n }\n\n cmp = primitiveComparator(left.length, right.length);\n if (cmp) {\n return cmp;\n }\n\n cmp = primitiveComparator(left[left.length - 2], right[right.length - 2]);\n if (cmp) {\n return cmp;\n }\n\n // TODO(b/329441702): Document IDs should be sorted by UTF-8 encoded byte\n // order, but IndexedDB sorts strings lexicographically. Document ID\n // comparison here still relies on primitive comparison to avoid mismatches\n // observed in snapshot listeners with Unicode characters in documentIds\n return primitiveComparator(left[left.length - 1], right[right.length - 1]);\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Document } from '../model/document';\nimport { FieldMask } from '../model/field_mask';\n\n/**\n * Represents a local view (overlay) of a document, and the fields that are\n * locally mutated.\n */\nexport class OverlayedDocument {\n constructor(\n readonly overlayedDocument: Document,\n\n /**\n * The fields that are locally mutated by patch mutations.\n *\n * If the overlayed\tdocument is from set or delete mutations, this is `null`.\n * If there is no overlay (mutation) for the document, this is an empty `FieldMask`.\n */\n readonly mutatedFields: FieldMask | null\n ) {}\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n asCollectionQueryAtPath,\n isCollectionGroupQuery,\n isDocumentQuery,\n Query,\n queryMatches\n} from '../core/query';\nimport { Timestamp } from '../lite-api/timestamp';\nimport {\n DocumentKeySet,\n OverlayMap,\n DocumentMap,\n MutableDocumentMap,\n newDocumentKeyMap,\n newMutationMap,\n newOverlayMap,\n documentMap,\n mutableDocumentMap,\n documentKeySet,\n DocumentKeyMap,\n convertOverlayedDocumentMapToDocumentMap,\n OverlayedDocumentMap,\n newOverlayedDocumentMap\n} from '../model/collections';\nimport { Document, MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { IndexOffset, INITIAL_LARGEST_BATCH_ID } from '../model/field_index';\nimport { FieldMask } from '../model/field_mask';\nimport {\n calculateOverlayMutation,\n mutationApplyToLocalView,\n PatchMutation\n} from '../model/mutation';\nimport { Overlay } from '../model/overlay';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert } from '../util/assert';\nimport { SortedMap } from '../util/sorted_map';\n\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { IndexManager } from './index_manager';\nimport { LocalWriteResult } from './local_store_impl';\nimport { MutationQueue } from './mutation_queue';\nimport { OverlayedDocument } from './overlayed_document';\nimport { PersistencePromise } from './persistence_promise';\nimport { PersistenceTransaction } from './persistence_transaction';\nimport { QueryContext } from './query_context';\nimport { RemoteDocumentCache } from './remote_document_cache';\n\n/**\n * A readonly view of the local state of all documents we're tracking (i.e. we\n * have a cached version in remoteDocumentCache or local mutations for the\n * document). The view is computed by applying the mutations in the\n * MutationQueue to the RemoteDocumentCache.\n */\nexport class LocalDocumentsView {\n constructor(\n readonly remoteDocumentCache: RemoteDocumentCache,\n readonly mutationQueue: MutationQueue,\n readonly documentOverlayCache: DocumentOverlayCache,\n readonly indexManager: IndexManager\n ) {}\n\n /**\n * Get the local view of the document identified by `key`.\n *\n * @returns Local view of the document or null if we don't have any cached\n * state for it.\n */\n getDocument(\n transaction: PersistenceTransaction,\n key: DocumentKey\n ): PersistencePromise {\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 + * offset. If there are no more remote documents after the provided offset, documents with + * mutations in order of batch id from the offset are returned. Since all documents in a batch are + * returned together, the total number of documents returned can exceed {@code count}. + * + * @param transaction + * @param collectionGroup The collection group for the documents. + * @param offset The offset to index into. + * @param count The number of documents to return + * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id. + */ + getNextDocuments(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset, count: number): PersistencePromise; + private getDocumentsMatchingDocumentQuery; + private getDocumentsMatchingCollectionGroupQuery; + private getDocumentsMatchingCollectionQuery; +} + +declare interface LocalStore { + collectGarbage(garbageCollector: LruGarbageCollector): Promise; + /** Manages the list of active field and collection indices. */ + indexManager: IndexManager; + /** + * The "local" view of all documents (layering mutationQueue on top of + * remoteDocumentCache). + */ + localDocuments: LocalDocumentsView; +} + +/** The result of a write to the local store. */ +declare interface LocalWriteResult { + batchId: BatchId; + changes: DocumentMap; +} +export { LogLevel } + +/** + * @internal + */ +export declare function _logWarn(msg: string, ...obj: unknown[]): void; + +declare interface LruGarbageCollector { + readonly params: LruParams; + collect(txn: PersistenceTransaction, activeTargetIds: ActiveTargets): PersistencePromise; + /** Given a percentile of target to collect, returns the number of targets to collect. */ + calculateTargetCount(txn: PersistenceTransaction, percentile: number): PersistencePromise; + /** Returns the nth sequence number, counting in order from the smallest. */ + nthSequenceNumber(txn: PersistenceTransaction, n: number): PersistencePromise; + /** + * Removes documents that have a sequence number equal to or less than the + * upper bound and are not otherwise pinned. + */ + removeOrphanedDocuments(txn: PersistenceTransaction, upperBound: ListenSequenceNumber): PersistencePromise; + getCacheSize(txn: PersistenceTransaction): PersistencePromise; + /** + * Removes targets with a sequence number equal to or less than the given + * upper bound, and removes document associations with those targets. + */ + removeTargets(txn: PersistenceTransaction, upperBound: ListenSequenceNumber, activeTargetIds: ActiveTargets): PersistencePromise; +} + +declare class LruParams { + readonly cacheSizeCollectionThreshold: number; + readonly percentileToCollect: number; + readonly maximumSequenceNumbersToCollect: number; + private static readonly DEFAULT_COLLECTION_PERCENTILE; + private static readonly DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT; + static withCacheSize(cacheSize: number): LruParams; + static readonly DEFAULT: LruParams; + static readonly DISABLED: LruParams; + constructor(cacheSizeCollectionThreshold: number, percentileToCollect: number, maximumSequenceNumbersToCollect: number); +} + +/** + * Describes the results of a garbage collection run. `didRun` will be set to + * `false` if collection was skipped (either it is disabled or the cache size + * has not hit the threshold). If collection ran, the other fields will be + * filled in with the details of the results. + */ +declare interface LruResults { + readonly didRun: boolean; + readonly sequenceNumbersCollected: number; + readonly targetsRemoved: number; + readonly documentsRemoved: number; +} + +declare type MapValue = firestoreV1ApiClientInterfaces.MapValue; + +/** + * An settings object to configure an `MemoryLocalCache` instance. + */ +export declare type MemoryCacheSettings = { + /** + * The garbage collector to use, for the memory cache layer. + * A `MemoryEagerGarbageCollector` is used when this is undefined. + */ + garbageCollector?: MemoryGarbageCollector; +}; + +/** + * A garbage collector deletes documents whenever they are not part of any + * active queries, and have no local mutations attached to them. + * + * This collector tries to ensure lowest memory footprints from the SDK, + * at the risk of documents not being cached for offline queries or for + * direct queries to the cache. + * + * Use factory function {@link memoryEagerGarbageCollector()} to create an + * instance of this collector. + */ +export declare type MemoryEagerGarbageCollector = { + kind: 'memoryEager'; + /** + * @internal + */ + _offlineComponentProvider: OfflineComponentProviderFactory; +}; + +/** + * Creates an instance of `MemoryEagerGarbageCollector`. This is also the + * default garbage collector unless it is explicitly specified otherwise. + */ +export declare function memoryEagerGarbageCollector(): MemoryEagerGarbageCollector; + +/** + * Union type from all support garbage collectors for memory local cache. + */ +export declare type MemoryGarbageCollector = MemoryEagerGarbageCollector | MemoryLruGarbageCollector; + +/** + * Provides an in-memory cache to the SDK. This is the default cache unless explicitly + * configured otherwise. + * + * To use, create an instance using the factory function {@link memoryLocalCache()}, then + * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using + * the settings object. + */ +export declare type MemoryLocalCache = { + kind: 'memory'; + /** + * @internal + */ + _onlineComponentProvider: OnlineComponentProviderFactory; + /** + * @internal + */ + _offlineComponentProvider: OfflineComponentProviderFactory; +}; + +/** + * Creates an instance of `MemoryLocalCache`. The instance can be set to + * `FirestoreSettings.cache` to tell the SDK which cache layer to use. + */ +export declare function memoryLocalCache(settings?: MemoryCacheSettings): MemoryLocalCache; + +/** + * A garbage collector deletes Least-Recently-Used documents in multiple + * batches. + * + * This collector is configured with a target size, and will only perform + * collection when the cached documents exceed the target size. It avoids + * querying backend repeated for the same query or document, at the risk + * of having a larger memory footprint. + * + * Use factory function {@link memoryLruGarbageCollector()} to create a + * instance of this collector. + */ +export declare type MemoryLruGarbageCollector = { + kind: 'memoryLru'; + /** + * @internal + */ + _offlineComponentProvider: OfflineComponentProviderFactory; +}; + +/** + * Creates an instance of `MemoryLruGarbageCollector`. + * + * A target size can be specified as part of the setting parameter. The + * collector will start deleting documents once the cache size exceeds + * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes). + */ +export declare function memoryLruGarbageCollector(settings?: { + cacheSizeBytes?: number; +}): MemoryLruGarbageCollector; + +/** + * Represents a document in Firestore with a key, version, data and whether it + * has local mutations applied to it. + * + * Documents can transition between states via `convertToFoundDocument()`, + * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does + * not transition to one of these states even after all mutations have been + * applied, `isValidDocument()` returns false and the document should be removed + * from all views. + */ +declare class MutableDocument implements Document_2 { + readonly key: _DocumentKey; + private documentType; + version: SnapshotVersion; + readTime: SnapshotVersion; + createTime: SnapshotVersion; + data: ObjectValue; + private documentState; + private constructor(); + /** + * Creates a document with no known version or data, but which can serve as + * base document for mutations. + */ + static newInvalidDocument(documentKey: _DocumentKey): MutableDocument; + /** + * Creates a new document that is known to exist with the given data at the + * given version. + */ + static newFoundDocument(documentKey: _DocumentKey, version: SnapshotVersion, createTime: SnapshotVersion, value: ObjectValue): MutableDocument; + /** Creates a new document that is known to not exist at the given version. */ + static newNoDocument(documentKey: _DocumentKey, version: SnapshotVersion): MutableDocument; + /** + * Creates a new document that is known to exist at the given version but + * whose data is not known (e.g. a document that was updated without a known + * base document). + */ + static newUnknownDocument(documentKey: _DocumentKey, version: SnapshotVersion): MutableDocument; + /** + * Changes the document type to indicate that it exists and that its version + * and data are known. + */ + convertToFoundDocument(version: SnapshotVersion, value: ObjectValue): MutableDocument; + /** + * Changes the document type to indicate that it doesn't exist at the given + * version. + */ + convertToNoDocument(version: SnapshotVersion): MutableDocument; + /** + * Changes the document type to indicate that it exists at a given version but + * that its data is not known (e.g. a document that was updated without a known + * base document). + */ + convertToUnknownDocument(version: SnapshotVersion): MutableDocument; + setHasCommittedMutations(): MutableDocument; + setHasLocalMutations(): MutableDocument; + setReadTime(readTime: SnapshotVersion): MutableDocument; + get hasLocalMutations(): boolean; + get hasCommittedMutations(): boolean; + get hasPendingWrites(): boolean; + isValidDocument(): boolean; + isFoundDocument(): boolean; + isNoDocument(): boolean; + isUnknownDocument(): boolean; + isEqual(other: Document_2 | null | undefined): boolean; + mutableCopy(): MutableDocument; + toString(): string; +} + +/** Miscellaneous collection types / constants. */ +declare type MutableDocumentMap = SortedMap<_DocumentKey, MutableDocument>; + +/** + * A mutation describes a self-contained change to a document. Mutations can + * create, replace, delete, and update subsets of documents. + * + * Mutations not only act on the value of the document but also its version. + * + * For local mutations (mutations that haven't been committed yet), we preserve + * the existing version for Set and Patch mutations. For Delete mutations, we + * reset the version to 0. + * + * Here's the expected transition table. + * + * MUTATION APPLIED TO RESULTS IN + * + * SetMutation Document(v3) Document(v3) + * SetMutation NoDocument(v3) Document(v0) + * SetMutation InvalidDocument(v0) Document(v0) + * PatchMutation Document(v3) Document(v3) + * PatchMutation NoDocument(v3) NoDocument(v3) + * PatchMutation InvalidDocument(v0) UnknownDocument(v3) + * DeleteMutation Document(v3) NoDocument(v0) + * DeleteMutation NoDocument(v3) NoDocument(v0) + * DeleteMutation InvalidDocument(v0) NoDocument(v0) + * + * For acknowledged mutations, we use the updateTime of the WriteResponse as + * the resulting version for Set and Patch mutations. As deletes have no + * explicit update time, we use the commitTime of the WriteResponse for + * Delete mutations. + * + * If a mutation is acknowledged by the backend but fails the precondition check + * locally, we transition to an `UnknownDocument` and rely on Watch to send us + * the updated version. + * + * Field transforms are used only with Patch and Set Mutations. We use the + * `updateTransforms` message to store transforms, rather than the `transforms`s + * messages. + * + * ## Subclassing Notes + * + * Every type of mutation needs to implement its own applyToRemoteDocument() and + * applyToLocalView() to implement the actual behavior of applying the mutation + * to some source document (see `setMutationApplyToRemoteDocument()` for an + * example). + */ +declare abstract class Mutation { + abstract readonly type: MutationType; + abstract readonly key: _DocumentKey; + abstract readonly precondition: Precondition; + abstract readonly fieldTransforms: FieldTransform[]; + /** + * Returns a `FieldMask` representing the fields that will be changed by + * applying this mutation. Returns `null` if the mutation will overwrite the + * entire document. + */ + abstract getFieldMask(): FieldMask | null; +} + +/** + * A batch of mutations that will be sent as one unit to the backend. + */ +declare class MutationBatch { + batchId: BatchId; + localWriteTime: Timestamp; + baseMutations: Mutation[]; + mutations: Mutation[]; + /** + * @param batchId - The unique ID of this mutation batch. + * @param localWriteTime - The original write time of this mutation. + * @param baseMutations - Mutations that are used to populate the base + * values when this mutation is applied locally. This can be used to locally + * overwrite values that are persisted in the remote document cache. Base + * mutations are never sent to the backend. + * @param mutations - The user-provided mutations in this mutation batch. + * User-provided mutations are applied both locally and remotely on the + * backend. + */ + constructor(batchId: BatchId, localWriteTime: Timestamp, baseMutations: Mutation[], mutations: Mutation[]); + /** + * Applies all the mutations in this MutationBatch to the specified document + * to compute the state of the remote document + * + * @param document - The document to apply mutations to. + * @param batchResult - The result of applying the MutationBatch to the + * backend. + */ + applyToRemoteDocument(document: MutableDocument, batchResult: MutationBatchResult): void; + /** + * Computes the local view of a document given all the mutations in this + * batch. + * + * @param document - The document to apply mutations to. + * @param mutatedFields - Fields that have been updated before applying this mutation batch. + * @returns A `FieldMask` representing all the fields that are mutated. + */ + applyToLocalView(document: MutableDocument, mutatedFields: FieldMask | null): FieldMask | null; + /** + * Computes the local view for all provided documents given the mutations in + * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to + * replace all the mutation applications. + */ + applyToLocalDocumentSet(documentMap: OverlayedDocumentMap, documentsWithoutRemoteVersion: DocumentKeySet): MutationMap; + keys(): DocumentKeySet; + isEqual(other: MutationBatch): boolean; +} + +/** The result of applying a mutation batch to the backend. */ +declare class MutationBatchResult { + readonly batch: MutationBatch; + readonly commitVersion: SnapshotVersion; + readonly mutationResults: MutationResult[]; + /** + * A pre-computed mapping from each mutated document to the resulting + * version. + */ + readonly docVersions: DocumentVersionMap; + private constructor(); + /** + * Creates a new MutationBatchResult for the given batch and results. There + * must be one result for each mutation in the batch. This static factory + * caches a document=>version mapping (docVersions). + */ + static from(batch: MutationBatch, commitVersion: SnapshotVersion, results: MutationResult[]): MutationBatchResult; +} + +declare type MutationMap = DocumentKeyMap; + +/** A queue of mutations to apply to the remote store. */ +declare interface MutationQueue { + /** Returns true if this queue contains no mutation batches. */ + checkEmpty(transaction: PersistenceTransaction): PersistencePromise; + /** + * Creates a new mutation batch and adds it to this mutation queue. + * + * @param transaction - The transaction this operation is scoped to. + * @param localWriteTime - The original write time of this mutation. + * @param baseMutations - Mutations that are used to populate the base values + * when this mutation is applied locally. These mutations are used to locally + * overwrite values that are persisted in the remote document cache. + * @param mutations - The user-provided mutations in this mutation batch. + */ + addMutationBatch(transaction: PersistenceTransaction, localWriteTime: Timestamp, baseMutations: Mutation[], mutations: Mutation[]): PersistencePromise; + /** + * Loads the mutation batch with the given batchId. + */ + lookupMutationBatch(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + /** + * Gets the first unacknowledged mutation batch after the passed in batchId + * in the mutation queue or null if empty. + * + * @param batchId - The batch to search after, or BATCHID_UNKNOWN for the + * first mutation in the queue. + * + * @returns the next mutation or null if there wasn't one. + */ + getNextMutationBatchAfterBatchId(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + /** + * Gets the largest (latest) batch id in mutation queue for the current user + * that is pending server response, returns `BATCHID_UNKNOWN` if the queue is + * empty. + * + * @returns the largest batch id in the mutation queue that is not + * acknowledged. + */ + getHighestUnacknowledgedBatchId(transaction: PersistenceTransaction): PersistencePromise; + /** Gets all mutation batches in the mutation queue. */ + getAllMutationBatches(transaction: PersistenceTransaction): PersistencePromise; + /** + * Finds all mutation batches that could possibly affect the given + * document key. Not all mutations in a batch will necessarily affect the + * document key, so when looping through the batch you'll need to check that + * the mutation itself matches the key. + * + * Batches are guaranteed to be in sorted order. + * + * Note that because of this requirement implementations are free to return + * mutation batches that don't contain the document key at all if it's + * convenient. + */ + getAllMutationBatchesAffectingDocumentKey(transaction: PersistenceTransaction, documentKey: _DocumentKey): PersistencePromise; + /** + * Finds all mutation batches that could possibly affect the given set of + * document keys. Not all mutations in a batch will necessarily affect each + * key, so when looping through the batch you'll need to check that the + * mutation itself matches the key. + * + * Batches are guaranteed to be in sorted order. + * + * Note that because of this requirement implementations are free to return + * mutation batches that don't contain any of the document keys at all if it's + * convenient. + */ + getAllMutationBatchesAffectingDocumentKeys(transaction: PersistenceTransaction, documentKeys: SortedMap<_DocumentKey, unknown>): PersistencePromise; + /** + * Finds all mutation batches that could affect the results for the given + * query. Not all mutations in a batch will necessarily affect the query, so + * when looping through the batch you'll need to check that the mutation + * itself matches the query. + * + * Batches are guaranteed to be in sorted order. + * + * Note that because of this requirement implementations are free to return + * mutation batches that don't match the query at all if it's convenient. + * + * NOTE: A PatchMutation does not need to include all fields in the query + * filter criteria in order to be a match (but any fields it does contain do + * need to match). + */ + getAllMutationBatchesAffectingQuery(transaction: PersistenceTransaction, query: Query_2): PersistencePromise; + /** + * Removes the given mutation batch from the queue. This is useful in two + * circumstances: + * + * + Removing an applied mutation from the head of the queue + * + Removing a rejected mutation from anywhere in the queue + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMutationBatch(transaction: PersistenceTransaction, batch: MutationBatch): PersistencePromise; + /** + * Performs a consistency check, examining the mutation queue for any + * leaks, if possible. + */ + performConsistencyCheck(transaction: PersistenceTransaction): PersistencePromise; +} + +/** The result of successfully applying a mutation to the backend. */ +declare class MutationResult { + /** + * The version at which the mutation was committed: + * + * - For most operations, this is the updateTime in the WriteResult. + * - For deletes, the commitTime of the WriteResponse (because deletes are + * not stored and have no updateTime). + * + * Note that these versions can be different: No-op writes will not change + * the updateTime even though the commitTime advances. + */ + readonly version: SnapshotVersion; + /** + * The resulting fields returned from the backend after a mutation + * containing field transforms has been committed. Contains one FieldValue + * for each FieldTransform that was in the mutation. + * + * Will be empty if the mutation did not contain any field transforms. + */ + readonly transformResults: Array; + constructor( + /** + * The version at which the mutation was committed: + * + * - For most operations, this is the updateTime in the WriteResult. + * - For deletes, the commitTime of the WriteResponse (because deletes are + * not stored and have no updateTime). + * + * Note that these versions can be different: No-op writes will not change + * the updateTime even though the commitTime advances. + */ + version: SnapshotVersion, + /** + * The resulting fields returned from the backend after a mutation + * containing field transforms has been committed. Contains one FieldValue + * for each FieldTransform that was in the mutation. + * + * Will be empty if the mutation did not contain any field transforms. + */ + transformResults: Array); +} + +declare const enum MutationType { + Set = 0, + Patch = 1, + Delete = 2, + Verify = 3 +} + +/** + * Represents a Query saved by the SDK in its local storage. + */ +declare interface NamedQuery { + /** The name of the query. */ + readonly name: string; + /** The underlying query associated with `name`. */ + readonly query: Query_2; + /** The time at which the results for this query were read. */ + readonly readTime: SnapshotVersion; +} + +/** + * Reads a Firestore {@link Query} from local cache, identified by the given + * name. + * + * The named queries are packaged into bundles on the server side (along + * with resulting documents), and loaded to local cache using `loadBundle`. Once + * in local cache, use this method to extract a {@link Query} by name. + * + * @param firestore - The {@link Firestore} instance to read the query from. + * @param name - The name of the query. + * @returns A `Promise` that is resolved with the Query or `null`. + */ +export declare function namedQuery(firestore: Firestore, name: string): Promise; + +/** Properties of a NamedQuery. */ +declare interface NamedQuery_2 { + /** NamedQuery name */ + name?: string | null; + /** NamedQuery bundledQuery */ + bundledQuery?: BundledQuery | null; + /** NamedQuery readTime */ + readTime?: Timestamp_2 | null; +} + +/** + * For each field (e.g. 'bar'), find all nested keys (e.g. {'bar.baz': T1, + * 'bar.qux': T2}). Intersect them together to make a single map containing + * all possible keys that are all marked as optional + */ +export declare type NestedUpdateFields> = UnionToIntersection<{ + [K in keyof T & string]: ChildUpdateFields; +}[keyof T & string]>; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A map implementation that uses objects as keys. Objects must have an + * associated equals function and must be immutable. Entries in the map are + * stored together with the key being produced from the mapKeyFn. This map + * automatically handles collisions of keys. + */ +declare class ObjectMap { + private mapKeyFn; + private equalsFn; + /** + * The inner map for a key/value pair. Due to the possibility of collisions we + * keep a list of entries that we do a linear search through to find an actual + * match. Note that collisions should be rare, so we still expect near + * constant time lookups in practice. + */ + private inner; + /** The number of entries stored in the map */ + private innerSize; + constructor(mapKeyFn: (key: KeyType) => string, equalsFn: (l: KeyType, r: KeyType) => boolean); + /** Get a value for this key, or undefined if it does not exist. */ + get(key: KeyType): ValueType | undefined; + has(key: KeyType): boolean; + /** Put this key and value in the map. */ + set(key: KeyType, value: ValueType): void; + /** + * Remove this key from the map. Returns a boolean if anything was deleted. + */ + delete(key: KeyType): boolean; + forEach(fn: (key: KeyType, val: ValueType) => void): void; + isEmpty(): boolean; + size(): number; +} + +/** + * An ObjectValue represents a MapValue in the Firestore Proto and offers the + * ability to add and remove fields (via the ObjectValueBuilder). + */ +declare class ObjectValue { + readonly value: { + mapValue: MapValue; + }; + constructor(value: { + mapValue: MapValue; + }); + static empty(): ObjectValue; + /** + * Returns the value at the given path or null. + * + * @param path - the path to search + * @returns The value at the path or null if the path is not set. + */ + field(path: _FieldPath): Value | null; + /** + * Sets the field to the provided value. + * + * @param path - The field path to set. + * @param value - The value to set. + */ + set(path: _FieldPath, value: Value): void; + /** + * Sets the provided fields to the provided values. + * + * @param data - A map of fields to values (or null for deletes). + */ + setAll(data: Map<_FieldPath, Value | null>): void; + /** + * Removes the field at the specified path. If there is no field at the + * specified path, nothing is changed. + * + * @param path - The field path to remove. + */ + delete(path: _FieldPath): void; + isEqual(other: ObjectValue): boolean; + /** + * Returns the map that contains the leaf element of `path`. If the parent + * entry does not yet exist, or if it is not a map, a new map will be created. + */ + private getFieldsMap; + /** + * Modifies `fieldsMap` by adding, replacing or deleting the specified + * entries. + */ + private applyChanges; + clone(): ObjectValue; +} + +/** + * Initializes and wires components that are needed to interface with the local + * cache. Implementations override `initialize()` to provide all components. + */ +declare interface OfflineComponentProvider { + readonly kind: Kind; + persistence: Persistence; + sharedClientState: SharedClientState; + localStore: LocalStore; + gcScheduler: Scheduler | null; + indexBackfillerScheduler: Scheduler | null; + synchronizeTabs: boolean; + initialize(cfg: ComponentConfiguration): Promise; + terminate(): Promise; +} + +declare interface OfflineComponentProviderFactory { + build(onlineComponents: OnlineComponentProvider): OfflineComponentProvider; +} + +/** + * Initializes and wires the components that are needed to interface with the + * network. + */ +declare class OnlineComponentProvider { + static readonly provider: OnlineComponentProviderFactory; + protected localStore: LocalStore; + protected sharedClientState: SharedClientState; + datastore: Datastore; + eventManager: EventManager; + remoteStore: RemoteStore; + syncEngine: SyncEngine; + initialize(offlineComponentProvider: OfflineComponentProvider, cfg: ComponentConfiguration): Promise; + createEventManager(cfg: ComponentConfiguration): EventManager; + createDatastore(cfg: ComponentConfiguration): Datastore; + createRemoteStore(cfg: ComponentConfiguration): RemoteStore; + createSyncEngine(cfg: ComponentConfiguration, startAsPrimary: boolean): SyncEngine; + terminate(): Promise; +} + +declare interface OnlineComponentProviderFactory { + build(): OnlineComponentProvider; +} + +/** + * Describes the online state of the Firestore client. Note that this does not + * indicate whether or not the remote store is trying to connect or not. This is + * primarily used by the View / EventManager code to change their behavior while + * offline (e.g. get() calls shouldn't wait for data from the server and + * snapshot events should set metadata.isFromCache=true). + * + * The string values should not be changed since they are persisted in + * WebStorage. + */ +declare const enum OnlineState { + /** + * The Firestore client is in an unknown online state. This means the client + * is either not actively trying to establish a connection or it is currently + * trying to establish a connection, but it has not succeeded or failed yet. + * Higher-level components should not operate in offline mode. + */ + Unknown = "Unknown", + /** + * The client is connected and the connections are healthy. This state is + * reached after a successful connection and there has been at least one + * successful message received from the backends. + */ + Online = "Online", + /** + * The client is either trying to establish a connection but failing, or it + * has been explicitly marked offline via a call to disableNetwork(). + * Higher-level components should operate in offline mode. + */ + Offline = "Offline" +} + +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshot(reference: DocumentReference, observer: { + next?: (snapshot: DocumentSnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}): Unsubscribe; + +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshot(reference: DocumentReference, options: SnapshotListenOptions, observer: { + next?: (snapshot: DocumentSnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}): Unsubscribe; + +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(reference: DocumentReference, onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe; + +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param options - Options controlling the listen behavior. + * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(reference: DocumentReference, options: SnapshotListenOptions, onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe; + +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The + * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(query: Query, observer: { + next?: (snapshot: QuerySnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}): Unsubscribe; + +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The + * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(query: Query, options: SnapshotListenOptions, observer: { + next?: (snapshot: QuerySnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}): Unsubscribe; + +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The + * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(query: Query, onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe; + +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The + * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param options - Options controlling the listen behavior. + * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(query: Query, options: SnapshotListenOptions, onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe; + +/** + * Attaches a listener for `QuerySnapshot` events based on data generated by invoking + * {@link QuerySnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. + * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void, converter?: FirestoreDataConverter): Unsubscribe; + +/** + * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking + * {@link DocumentSnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. + * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are + * never ending. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void, converter?: FirestoreDataConverter): Unsubscribe; + +/** + * Attaches a listener for `QuerySnapshot` events based on data generated by invoking + * {@link QuerySnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, options: SnapshotListenOptions, onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void, converter?: FirestoreDataConverter): Unsubscribe; + +/** + * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking + * {@link DocumentSnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks + * or pass a single observer object with `next` and `error` callbacks. The listener can be cancelled + * by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, options: SnapshotListenOptions, onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void, converter?: FirestoreDataConverter): Unsubscribe; + +/** + * Attaches a listener for `QuerySnapshot` events based on QuerySnapshot data generated by invoking + * {@link QuerySnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, observer: { + next: (snapshot: QuerySnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}, converter?: FirestoreDataConverter): Unsubscribe; + +/** + * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking + * {@link DocumentSnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks + * or pass a single observer object with `next` and `error` callbacks. The listener can be cancelled + * by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, observer: { + next: (snapshot: DocumentSnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}, converter?: FirestoreDataConverter): Unsubscribe; + +/** + * Attaches a listener for `QuerySnapshot` events based on QuerySnapshot data generated by invoking + * {@link QuerySnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, options: SnapshotListenOptions, observer: { + next: (snapshot: QuerySnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}, converter?: FirestoreDataConverter): Unsubscribe; + +/** + * Attaches a listener for `DocumentSnapshot` events based on QuerySnapshot data generated by + * invoking {@link DocumentSnapshot.toJSON} You may either pass individual `onNext` and `onError` + * callbacks or pass a single observer object with `next` and `error` callbacks. The listener can be + * cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, options: SnapshotListenOptions, observer: { + next: (snapshot: DocumentSnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}, converter?: FirestoreDataConverter): Unsubscribe; + +/** + * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync + * event indicates that all listeners affected by a given change have fired, + * even if a single server-generated change affects multiple listeners. + * + * NOTE: The snapshots-in-sync event only indicates that listeners are in sync + * with each other, but does not relate to whether those snapshots are in sync + * with the server. Use SnapshotMetadata in the individual listeners to + * determine if a snapshot is from the cache or the server. + * + * @param firestore - The instance of Firestore for synchronizing snapshots. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel the snapshot + * listener. + */ +export declare function onSnapshotsInSync(firestore: Firestore, observer: { + next?: (value: void) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}): Unsubscribe; + +/** + * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync + * event indicates that all listeners affected by a given change have fired, + * even if a single server-generated change affects multiple listeners. + * + * NOTE: The snapshots-in-sync event only indicates that listeners are in sync + * with each other, but does not relate to whether those snapshots are in sync + * with the server. Use `SnapshotMetadata` in the individual listeners to + * determine if a snapshot is from the cache or the server. + * + * @param firestore - The `Firestore` instance for synchronizing snapshots. + * @param onSync - A callback to be called every time all snapshot listeners are + * in sync with each other. + * @returns An unsubscribe function that can be called to cancel the snapshot + * listener. + */ +export declare function onSnapshotsInSync(firestore: Firestore, onSync: () => void): Unsubscribe; + +declare const enum Operator { + LESS_THAN = "<", + LESS_THAN_OR_EQUAL = "<=", + EQUAL = "==", + NOT_EQUAL = "!=", + GREATER_THAN = ">", + GREATER_THAN_OR_EQUAL = ">=", + ARRAY_CONTAINS = "array-contains", + IN = "in", + NOT_IN = "not-in", + ARRAY_CONTAINS_ANY = "array-contains-any" +} + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +export declare function or(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; + +/** + * An ordering on a field, in some Direction. Direction defaults to ASCENDING. + */ +declare class OrderBy { + readonly field: _FieldPath; + readonly dir: Direction; + constructor(field: _FieldPath, dir?: Direction); +} + +/** + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the + * specified field, optionally in descending order instead of ascending. + * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * + * @param fieldPath - The field to sort by. + * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @returns The created {@link QueryOrderByConstraint}. + */ +export declare function orderBy(fieldPath: string | FieldPath, directionStr?: OrderByDirection): QueryOrderByConstraint; + +/** + * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc' + * (descending or ascending). + */ +export declare type OrderByDirection = 'desc' | 'asc'; + +declare type OrderDirection = 'DIRECTION_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING'; + +/** + * Representation of an overlay computed by Firestore. + * + * Holds information about a mutation and the largest batch id in Firestore when + * the mutation was created. + */ +declare class Overlay { + readonly largestBatchId: number; + readonly mutation: Mutation; + constructor(largestBatchId: number, mutation: Mutation); + getKey(): _DocumentKey; + isEqual(other: Overlay | null): boolean; + toString(): string; +} + +/** + * Represents a local view (overlay) of a document, and the fields that are + * locally mutated. + */ +declare class OverlayedDocument { + readonly overlayedDocument: Document_2; + /** + * The fields that are locally mutated by patch mutations. + * + * If the overlayed document is from set or delete mutations, this is `null`. + * If there is no overlay (mutation) for the document, this is an empty `FieldMask`. + */ + readonly mutatedFields: FieldMask | null; + constructor(overlayedDocument: Document_2, + /** + * The fields that are locally mutated by patch mutations. + * + * If the overlayed document is from set or delete mutations, this is `null`. + * If there is no overlay (mutation) for the document, this is an empty `FieldMask`. + */ + mutatedFields: FieldMask | null); +} + +declare type OverlayedDocumentMap = DocumentKeyMap; + +declare type OverlayMap = DocumentKeyMap; + +declare interface ParseContext { + readonly databaseId: _DatabaseId; + readonly ignoreUndefinedProperties: boolean; +} + +/** The result of parsing document data (e.g. for a setData call). */ +declare class ParsedSetData { + readonly data: ObjectValue; + readonly fieldMask: FieldMask | null; + readonly fieldTransforms: FieldTransform[]; + constructor(data: ObjectValue, fieldMask: FieldMask | null, fieldTransforms: FieldTransform[]); + toMutation(key: _DocumentKey, precondition: Precondition): Mutation; +} + +/** The result of parsing "update" data (i.e. for an updateData call). */ +declare class ParsedUpdateData { + readonly data: ObjectValue; + readonly fieldMask: FieldMask; + readonly fieldTransforms: FieldTransform[]; + constructor(data: ObjectValue, fieldMask: FieldMask, fieldTransforms: FieldTransform[]); + toMutation(key: _DocumentKey, precondition: Precondition): Mutation; +} + +/** + * Similar to TypeScript's `Partial`, but allows nested fields to be + * omitted and FieldValues to be passed in as property values. + */ +export declare type PartialWithFieldValue = Partial | (T extends Primitive ? T : T extends {} ? { + [K in keyof T]?: PartialWithFieldValue | FieldValue; +} : never); + +/** + * Persistence is the lowest-level shared interface to persistent storage in + * Firestore. + * + * Persistence is used to create MutationQueue and RemoteDocumentCache + * instances backed by persistence (which might be in-memory or LevelDB). + * + * Persistence also exposes an API to create and run PersistenceTransactions + * against persistence. All read / write operations must be wrapped in a + * transaction. Implementations of PersistenceTransaction / Persistence only + * need to guarantee that writes made against the transaction are not made to + * durable storage until the transaction resolves its PersistencePromise. + * Since memory-only storage components do not alter durable storage, they are + * free to ignore the transaction. + * + * This contract is enough to allow the LocalStore be be written + * independently of whether or not the stored state actually is durably + * persisted. If persistent storage is enabled, writes are grouped together to + * avoid inconsistent state that could cause crashes. + * + * Concretely, when persistent storage is enabled, the persistent versions of + * MutationQueue, RemoteDocumentCache, and others (the mutators) will + * defer their writes into a transaction. Once the local store has completed + * one logical operation, it commits the transaction. + * + * When persistent storage is disabled, the non-persistent versions of the + * mutators ignore the transaction. This short-cut is allowed because + * memory-only storage leaves no state so it cannot be inconsistent. + * + * This simplifies the implementations of the mutators and allows memory-only + * implementations to supplement the persistent ones without requiring any + * special dual-store implementation of Persistence. The cost is that the + * LocalStore needs to be slightly careful about the order of its reads and + * writes in order to avoid relying on being able to read back uncommitted + * writes. + */ +declare interface Persistence { + /** + * Whether or not this persistence instance has been started. + */ + readonly started: boolean; + readonly referenceDelegate: ReferenceDelegate; + /** Starts persistence. */ + start(): Promise; + /** + * Releases any resources held during eager shutdown. + */ + shutdown(): Promise; + /** + * Registers a listener that gets called when the database receives a + * version change event indicating that it has deleted. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setDatabaseDeletedListener(databaseDeletedListener: () => Promise): void; + /** + * Adjusts the current network state in the client's metadata, potentially + * affecting the primary lease. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setNetworkEnabled(networkEnabled: boolean): void; + /** + * Returns GlobalCache representing a general purpose cache for global values. + */ + getGlobalsCache(): GlobalsCache; + /** + * Returns a MutationQueue representing the persisted mutations for the + * given user. + * + * Note: The implementation is free to return the same instance every time + * this is called for a given user. In particular, the memory-backed + * implementation does this to emulate the persisted implementation to the + * extent possible (e.g. in the case of uid switching from + * sally=>jack=>sally, sally's mutation queue will be preserved). + */ + getMutationQueue(user: User, indexManager: IndexManager): MutationQueue; + /** + * Returns a TargetCache representing the persisted cache of targets. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getTargetCache(): TargetCache; + /** + * Returns a RemoteDocumentCache representing the persisted cache of remote + * documents. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getRemoteDocumentCache(): RemoteDocumentCache; + /** + * Returns a BundleCache representing the persisted cache of loaded bundles. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getBundleCache(): BundleCache; + /** + * Returns an IndexManager instance that manages our persisted query indexes. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getIndexManager(user: User): IndexManager; + /** + * Returns a DocumentOverlayCache representing the documents that are mutated + * locally. + */ + getDocumentOverlayCache(user: User): DocumentOverlayCache; + /** + * Performs an operation inside a persistence transaction. Any reads or writes + * against persistence must be performed within a transaction. Writes will be + * committed atomically once the transaction completes. + * + * Persistence operations are asynchronous and therefore the provided + * transactionOperation must return a PersistencePromise. When it is resolved, + * the transaction will be committed and the Promise returned by this method + * will resolve. + * + * @param action - A description of the action performed by this transaction, + * used for logging. + * @param mode - The underlying mode of the IndexedDb transaction. Can be + * 'readonly', 'readwrite' or 'readwrite-primary'. Transactions marked + * 'readwrite-primary' can only be executed by the primary client. In this + * mode, the transactionOperation will not be run if the primary lease cannot + * be acquired and the returned promise will be rejected with a + * FAILED_PRECONDITION error. + * @param transactionOperation - The operation to run inside a transaction. + * @returns A `Promise` that is resolved once the transaction completes. + */ + runTransaction(action: string, mode: PersistenceTransactionMode, transactionOperation: (transaction: PersistenceTransaction) => PersistencePromise): Promise; +} + +/** + * PersistencePromise is essentially a re-implementation of Promise except + * it has a .next() method instead of .then() and .next() and .catch() callbacks + * are executed synchronously when a PersistencePromise resolves rather than + * asynchronously (Promise implementations use setImmediate() or similar). + * + * This is necessary to interoperate with IndexedDB which will automatically + * commit transactions if control is returned to the event loop without + * synchronously initiating another operation on the transaction. + * + * NOTE: .then() and .catch() only allow a single consumer, unlike normal + * Promises. + */ +declare class PersistencePromise { + private nextCallback; + private catchCallback; + private result; + private error; + private isDone; + private callbackAttached; + constructor(callback: (resolve: Resolver, reject: Rejector) => void); + catch(fn: (error: Error) => R | PersistencePromise): PersistencePromise; + next(nextFn?: FulfilledHandler, catchFn?: RejectedHandler): PersistencePromise; + toPromise(): Promise; + private wrapUserFunction; + private wrapSuccess; + private wrapFailure; + static resolve(): PersistencePromise; + static resolve(result: R): PersistencePromise; + static reject(error: Error): PersistencePromise; + static waitFor(all: { + forEach: (cb: (el: PersistencePromise) => void) => void; + }): PersistencePromise; + /** + * Given an array of predicate functions that asynchronously evaluate to a + * boolean, implements a short-circuiting `or` between the results. Predicates + * will be evaluated until one of them returns `true`, then stop. The final + * result will be whether any of them returned `true`. + */ + static or(predicates: Array<() => PersistencePromise>): PersistencePromise; + /** + * Given an iterable, call the given function on each element in the + * collection and wait for all of the resulting concurrent PersistencePromises + * to resolve. + */ + static forEach(collection: { + forEach: (cb: (r: R, s: S) => void) => void; + }, f: ((r: R, s: S) => PersistencePromise) | ((r: R) => PersistencePromise)): PersistencePromise; + static forEach(collection: { + forEach: (cb: (r: R) => void) => void; + }, f: (r: R) => PersistencePromise): PersistencePromise; + /** + * Concurrently map all array elements through asynchronous function. + */ + static mapArray(array: T[], f: (t: T) => PersistencePromise): PersistencePromise; + /** + * An alternative to recursive PersistencePromise calls, that avoids + * potential memory problems from unbounded chains of promises. + * + * The `action` will be called repeatedly while `condition` is true. + */ + static doWhile(condition: () => boolean, action: () => PersistencePromise): PersistencePromise; +} + +/** + * Settings that can be passed to `enableIndexedDbPersistence()` to configure + * Firestore persistence. + * + * Persistence cannot be used in a Node.js environment. + */ +export declare interface PersistenceSettings { + /** + * Whether to force enable persistence for the client. This cannot be used + * with multi-tab synchronization and is primarily intended for use with Web + * Workers. Setting this to `true` will enable persistence, but cause other + * tabs using persistence to fail. + */ + forceOwnership?: boolean; +} + +/** + * A base class representing a persistence transaction, encapsulating both the + * transaction's sequence numbers as well as a list of onCommitted listeners. + * + * When you call Persistence.runTransaction(), it will create a transaction and + * pass it to your callback. You then pass it to any method that operates + * on persistence. + */ +declare abstract class PersistenceTransaction { + private readonly onCommittedListeners; + abstract readonly currentSequenceNumber: ListenSequenceNumber; + addOnCommittedListener(listener: () => void): void; + raiseOnCommittedEvent(): void; +} + +/** The different modes supported by `Persistence.runTransaction()`. */ +declare type PersistenceTransactionMode = 'readonly' | 'readwrite' | 'readwrite-primary'; + +/** + * A `PersistentCacheIndexManager` for configuring persistent cache indexes used + * for local query execution. + * + * To use, call `getPersistentCacheIndexManager()` to get an instance. + */ +export declare class PersistentCacheIndexManager { + readonly _firestore: Firestore; + /** A type string to uniquely identify instances of this class. */ + readonly type: 'PersistentCacheIndexManager'; + /** @hideconstructor */ + constructor(_firestore: Firestore); +} + +/** + * An settings object to configure an `PersistentLocalCache` instance. + * + * Persistent cache cannot be used in a Node.js environment. + */ +export declare type PersistentCacheSettings = { + /** + * An approximate cache size threshold for the on-disk data. If the cache + * grows beyond this size, Firestore will start removing data that hasn't been + * recently used. The SDK does not guarantee that the cache will stay below + * that size, only that if the cache exceeds the given size, cleanup will be + * attempted. + * + * The default value is 40 MB. The threshold must be set to at least 1 MB, and + * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection. + */ + cacheSizeBytes?: number; + /** + * Specifies how multiple tabs/windows will be managed by the SDK. + */ + tabManager?: PersistentTabManager; +}; + +/** + * Provides a persistent cache backed by IndexedDb to the SDK. + * + * To use, create an instance using the factory function {@link persistentLocalCache()}, then + * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using + * the settings object. + */ +export declare type PersistentLocalCache = { + kind: 'persistent'; + /** + * @internal + */ + _onlineComponentProvider: OnlineComponentProviderFactory; + /** + * @internal + */ + _offlineComponentProvider: OfflineComponentProviderFactory; +}; + +/** + * Creates an instance of `PersistentLocalCache`. The instance can be set to + * `FirestoreSettings.cache` to tell the SDK which cache layer to use. + * + * Persistent cache cannot be used in a Node.js environment. + */ +export declare function persistentLocalCache(settings?: PersistentCacheSettings): PersistentLocalCache; + +/** + * A tab manager supporting multiple tabs. SDK will synchronize queries and + * mutations done across all tabs using the SDK. + */ +export declare type PersistentMultipleTabManager = { + kind: 'PersistentMultipleTab'; + /** + * @internal + */ + _initialize: (settings: Omit) => void; + /** + * @internal + */ + _onlineComponentProvider?: OnlineComponentProviderFactory; + /** + * @internal + */ + _offlineComponentProvider?: OfflineComponentProviderFactory; +}; + +/** + * Creates an instance of `PersistentMultipleTabManager`. + */ +export declare function persistentMultipleTabManager(): PersistentMultipleTabManager; + +/** + * A tab manager supporting only one tab, no synchronization will be + * performed across tabs. + */ +export declare type PersistentSingleTabManager = { + kind: 'persistentSingleTab'; + /** + * @internal + */ + _initialize: (settings: Omit | undefined) => void; + /** + * @internal + */ + _onlineComponentProvider?: OnlineComponentProviderFactory; + /** + * @internal + */ + _offlineComponentProvider?: OfflineComponentProviderFactory; +}; + +/** + * Creates an instance of `PersistentSingleTabManager`. + * + * @param settings Configures the created tab manager. + */ +export declare function persistentSingleTabManager(settings: PersistentSingleTabManagerSettings | undefined): PersistentSingleTabManager; + +/** + * Type to configure an `PersistentSingleTabManager` instance. + */ +export declare type PersistentSingleTabManagerSettings = { + /** + * Whether to force-enable persistent (IndexedDB) cache for the client. This + * cannot be used with multi-tab synchronization and is primarily intended for + * use with Web Workers. Setting this to `true` will enable IndexedDB, but cause + * other tabs using IndexedDB cache to fail. + */ + forceOwnership?: boolean; +}; + +/** + * A union of all available tab managers. + */ +export declare type PersistentTabManager = PersistentSingleTabManager | PersistentMultipleTabManager; + +/** + * Encodes a precondition for a mutation. This follows the model that the + * backend accepts with the special case of an explicit "empty" precondition + * (meaning no precondition). + */ +declare class Precondition { + readonly updateTime?: SnapshotVersion | undefined; + readonly exists?: boolean | undefined; + private constructor(); + /** Creates a new empty Precondition. */ + static none(): Precondition; + /** Creates a new Precondition with an exists flag. */ + static exists(exists: boolean): Precondition; + /** Creates a new Precondition based on a version a document exists at. */ + static updateTime(version: SnapshotVersion): Precondition; + /** Returns whether this Precondition is empty. */ + get isNone(): boolean; + isEqual(other: Precondition): boolean; +} + +/** + * These types primarily exist to support the `UpdateData`, + * `WithFieldValue`, and `PartialWithFieldValue` types and are not consumed + * directly by the end developer. + */ +/** Primitive types. */ +export declare type Primitive = string | number | boolean | undefined | null; + +/** + * @internal + * Undocumented, private additional settings not exposed in our public API. + */ +export declare interface PrivateSettings extends FirestoreSettings_2 { + credentials?: CredentialsSettings; + cacheSizeBytes?: number; + experimentalForceLongPolling?: boolean; + experimentalAutoDetectLongPolling?: boolean; + experimentalLongPollingOptions?: ExperimentalLongPollingOptions; + useFetchStreams?: boolean; + emulatorOptions?: { + mockUserToken?: EmulatorMockTokenOptions | string; + }; + localCache?: FirestoreLocalCache; +} + +/** + * The representation of a JSON object property name and its type value. + * @private + * @internal + */ +declare interface Property { + value?: TSType; + typeString: JsonTypeDesc; +} + +declare interface ProviderCredentialsSettings { + ['type']: 'provider'; + ['client']: CredentialsProvider; +} + +/** + * A `Query` refers to a query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ +export declare class Query { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter_2 | null; + readonly _query: Query_2; + /** The type of this Firestore reference. */ + readonly type: 'query' | 'collection'; + /** + * The `Firestore` instance for the Firestore database (useful for performing + * transactions, etc.). + */ + readonly firestore: Firestore_2; + /** @hideconstructor protected */ + constructor(firestore: Firestore_2, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter: FirestoreDataConverter_2 | null, _query: Query_2); + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `Query` that does not use a + * converter. + */ + withConverter(converter: null): Query; + /** + * Applies a custom data converter to this query, allowing you to use your own + * custom model objects with Firestore. When you call {@link getDocs} with + * the returned query, the provided converter will convert between Firestore + * data of type `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `Query` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter_2): Query; +} + +/** + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. + * + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to + * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or + * {@link or}. + * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to + * apply (e.g. {@link orderBy}, {@link limit}). + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query(query: Query, compositeFilter: QueryCompositeFilterConstraint, ...queryConstraints: QueryNonFilterConstraint[]): Query; + +/** + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. + * + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param queryConstraints - The list of {@link QueryConstraint}s to apply. + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query(query: Query, ...queryConstraints: QueryConstraint[]): Query; + +/** + * The Query interface defines all external properties of a query. + * + * QueryImpl implements this interface to provide memoization for `queryNormalizedOrderBy` + * and `queryToTarget`. + */ +declare interface Query_2 { + readonly path: _ResourcePath; + readonly collectionGroup: string | null; + readonly explicitOrderBy: OrderBy[]; + readonly filters: Filter[]; + readonly limit: number | null; + readonly limitType: LimitType; + readonly startAt: Bound | null; + readonly endAt: Bound | null; +} + +/** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ +export declare class QueryCompositeFilterConstraint extends AppliableConstraint { + /** The type of this query constraint */ + readonly type: 'or' | 'and'; + private readonly _queryConstraints; + /** + * @internal + */ + protected constructor( + /** The type of this query constraint */ + type: 'or' | 'and', _queryConstraints: QueryFilterConstraint[]); + static _create(type: 'or' | 'and', _queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; + _parse(query: Query): Filter; + _apply(query: Query): Query; + _getQueryConstraints(): readonly AppliableConstraint[]; + _getOperator(): CompositeOperator; +} + +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Firestore query. `QueryConstraint`s are created by invoking {@link where}, + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that + * also contains this `QueryConstraint`. + */ +export declare abstract class QueryConstraint extends AppliableConstraint { + /** The type of this query constraint */ + abstract readonly type: QueryConstraintType; + /** + * Takes the provided {@link Query} and returns a copy of the {@link Query} with this + * {@link AppliableConstraint} applied. + */ + abstract _apply(query: Query): Query; +} + +/** Describes the different query constraints available in this SDK. */ +export declare type QueryConstraintType = 'where' | 'orderBy' | 'limit' | 'limitToLast' | 'startAt' | 'startAfter' | 'endAt' | 'endBefore'; + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A tracker to keep a record of important details during database local query + * execution. + */ +declare class QueryContext { + /** + * Counts the number of documents passed through during local query execution. + */ + private _documentReadCount; + get documentReadCount(): number; + incrementDocumentReadCount(amount: number): void; +} + +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ +export declare class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * By default, `serverTimestamp()` values that have not yet been + * set to their final value will be returned as `null`. You can override + * this by passing an options object. + * + * @override + * @param options - An options object to configure how data is retrieved from + * the snapshot (for example the desired behavior for server timestamps that + * have not yet been set to their final value). + * @returns An `Object` containing all fields in the document. + */ + data(options?: SnapshotOptions): AppModelType; +} + +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ +declare class QueryDocumentSnapshot_2 extends DocumentSnapshot_2 { + /** + * Retrieves all fields in the document as an `Object`. + * + * @override + * @returns An `Object` containing all fields in the document. + */ + data(): AppModelType; +} + +/** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ +export declare class QueryEndAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'endBefore' | 'endAt'; + private readonly _docOrFields; + private readonly _inclusive; + /** + * @internal + */ + protected constructor( + /** The type of this query constraint */ + type: 'endBefore' | 'endAt', _docOrFields: Array>, _inclusive: boolean); + static _create(type: 'endBefore' | 'endAt', _docOrFields: Array>, _inclusive: boolean): QueryEndAtConstraint; + _apply(query: Query): Query; +} + +/** + * Returns true if the provided queries point to the same collection and apply + * the same constraints. + * + * @param left - A `Query` to compare. + * @param right - A `Query` to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +export declare function queryEqual(left: Query, right: Query): boolean; + +/** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ +export declare class QueryFieldFilterConstraint extends QueryConstraint { + private readonly _field; + private _op; + private _value; + /** The type of this query constraint */ + readonly type = "where"; + /** + * @internal + */ + protected constructor(_field: _FieldPath, _op: Operator, _value: unknown); + static _create(_field: _FieldPath, _op: Operator, _value: unknown): QueryFieldFilterConstraint; + _apply(query: Query): Query; + _parse(query: Query): FieldFilter; +} + +/** + * `QueryFilterConstraint` is a helper union type that represents + * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}. + */ +export declare type QueryFilterConstraint = QueryFieldFilterConstraint | QueryCompositeFilterConstraint; + +/** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ +export declare class QueryLimitConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'limit' | 'limitToLast'; + private readonly _limit; + private readonly _limitType; + /** + * @internal + */ + protected constructor( + /** The type of this query constraint */ + type: 'limit' | 'limitToLast', _limit: number, _limitType: LimitType); + static _create(type: 'limit' | 'limitToLast', _limit: number, _limitType: LimitType): QueryLimitConstraint; + _apply(query: Query): Query; +} + +/** + * `QueryNonFilterConstraint` is a helper union type that represents + * QueryConstraints which are used to narrow or order the set of documents, + * but that do not explicitly filter on a document field. + * `QueryNonFilterConstraint`s are created by invoking {@link orderBy}, + * {@link (startAt:1)}, {@link (startAfter:1)}, {@link (endBefore:1)}, {@link (endAt:1)}, + * {@link limit} or {@link limitToLast} and can then be passed to {@link (query:1)} + * to create a new query instance that also contains the `QueryConstraint`. + */ +export declare type QueryNonFilterConstraint = QueryOrderByConstraint | QueryLimitConstraint | QueryStartAtConstraint | QueryEndAtConstraint; + +/** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ +export declare class QueryOrderByConstraint extends QueryConstraint { + private readonly _field; + private _direction; + /** The type of this query constraint */ + readonly type = "orderBy"; + /** + * @internal + */ + protected constructor(_field: _FieldPath, _direction: Direction); + static _create(_field: _FieldPath, _direction: Direction): QueryOrderByConstraint; + _apply(query: Query): Query; +} + +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ +export declare class QuerySnapshot { + readonly _firestore: Firestore; + readonly _userDataWriter: AbstractUserDataWriter; + readonly _snapshot: ViewSnapshot; + /** + * Metadata about this snapshot, concerning its source and if it has local + * modifications. + */ + readonly metadata: SnapshotMetadata; + /** + * The query on which you called `get` or `onSnapshot` in order to get this + * `QuerySnapshot`. + */ + readonly query: Query; + private _cachedChanges?; + private _cachedChangesIncludeMetadataChanges?; + /** @hideconstructor */ + constructor(_firestore: Firestore, _userDataWriter: AbstractUserDataWriter, query: Query, _snapshot: ViewSnapshot); + /** An array of all the documents in the `QuerySnapshot`. */ + get docs(): Array>; + /** The number of documents in the `QuerySnapshot`. */ + get size(): number; + /** True if there are no documents in the `QuerySnapshot`. */ + get empty(): boolean; + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ + forEach(callback: (result: QueryDocumentSnapshot) => void, thisArg?: unknown): void; + /** + * Returns an array of the documents changes since the last snapshot. If this + * is the first snapshot, all documents will be in the list as 'added' + * changes. + * + * @param options - `SnapshotListenOptions` that control whether metadata-only + * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger + * snapshot events. + */ + docChanges(options?: SnapshotListenOptions): Array>; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + bundleSource: Property<"string">; + bundleName: Property<"string">; + bundle: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `QuerySnapshot` instance. + * + * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this + * `QuerySnapshot` has pending writes. + */ + toJSON(): object; +} + +/** + * Builds a `QuerySnapshot` instance from a JSON object created by + * {@link QuerySnapshot.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json - a JSON object represention of a `QuerySnapshot` instance. + * @returns an instance of {@link QuerySnapshot} if the JSON object could be + * parsed. Throws a {@link FirestoreError} if an error occurs. + */ +export declare function querySnapshotFromJSON(db: Firestore, json: object): QuerySnapshot; + +/** + * Builds a `QuerySnapshot` instance from a JSON object created by + * {@link QuerySnapshot.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json - a JSON object represention of a `QuerySnapshot` instance. + * @param converter - Converts objects to and from Firestore. + * @returns an instance of {@link QuerySnapshot} if the JSON object could be + * parsed. Throws a {@link FirestoreError} if an error occurs. + */ +export declare function querySnapshotFromJSON(db: Firestore, json: object, converter: FirestoreDataConverter): QuerySnapshot; + +/** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ +export declare class QueryStartAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'startAt' | 'startAfter'; + private readonly _docOrFields; + private readonly _inclusive; + /** + * @internal + */ + protected constructor( + /** The type of this query constraint */ + type: 'startAt' | 'startAfter', _docOrFields: Array>, _inclusive: boolean); + static _create(type: 'startAt' | 'startAfter', _docOrFields: Array>, _inclusive: boolean): QueryStartAtConstraint; + _apply(query: Query): Query; +} + +/** The different states of a watch target. */ +declare type QueryTargetState = 'not-current' | 'current' | 'rejected'; + +/** + * Returns true if the provided references are equal. + * + * @param left - A reference to compare. + * @param right - A reference to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +export declare function refEqual(left: DocumentReference | CollectionReference, right: DocumentReference | CollectionReference): boolean; + +/** + * A ReferenceDelegate instance handles all of the hooks into the document-reference lifecycle. This + * includes being added to a target, being removed from a target, being subject to mutation, and + * being mutated by the user. + * + * Different implementations may do different things with each of these events. Not every + * implementation needs to do something with every lifecycle hook. + * + * PORTING NOTE: since sequence numbers are attached to transactions in this + * client, the ReferenceDelegate does not need to deal in transactional + * semantics (onTransactionStarted/Committed()), nor does it need to track and + * generate sequence numbers (getCurrentSequenceNumber()). + */ +declare interface ReferenceDelegate { + /** Notify the delegate that the given document was added to a target. */ + addReference(txn: PersistenceTransaction, targetId: TargetId, doc: _DocumentKey): PersistencePromise; + /** Notify the delegate that the given document was removed from a target. */ + removeReference(txn: PersistenceTransaction, targetId: TargetId, doc: _DocumentKey): PersistencePromise; + /** + * Notify the delegate that a target was removed. The delegate may, but is not obligated to, + * actually delete the target and associated data. + */ + removeTarget(txn: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Notify the delegate that a document may no longer be part of any views or + * have any mutations associated. + */ + markPotentiallyOrphaned(txn: PersistenceTransaction, doc: _DocumentKey): PersistencePromise; + /** Notify the delegate that a limbo document was updated. */ + updateLimboDocument(txn: PersistenceTransaction, doc: _DocumentKey): PersistencePromise; +} + +declare type RejectedHandler = ((reason: Error) => R | PersistencePromise) | null; + +declare type Rejector = (error: Error) => void; + +/** + * Represents cached documents received from the remote backend. + * + * The cache is keyed by DocumentKey and entries in the cache are + * MutableDocuments, meaning we can cache both actual documents as well as + * documents that are known to not exist. + */ +declare interface RemoteDocumentCache { + /** Sets the index manager to use for managing the collectionGroup index. */ + setIndexManager(indexManager: IndexManager): void; + /** + * Looks up an entry in the cache. + * + * @param documentKey - The key of the entry to look up.* + * @returns The cached document entry. Returns an invalid document if the + * document is not cached. + */ + getEntry(transaction: PersistenceTransaction, documentKey: _DocumentKey): PersistencePromise; + /** + * Looks up a set of entries in the cache. + * + * @param documentKeys - The keys of the entries to look up. + * @returns The cached document entries indexed by key. If an entry is not + * cached, the corresponding key will be mapped to an invalid document. + */ + getEntries(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise; + /** + * Returns the documents matching the given query + * + * @param query - The query to match documents against. + * @param offset - The offset to start the scan at (exclusive). + * @param context - A optional tracker to keep a record of important details + * during database local query execution. + * @returns The set of matching documents. + */ + getDocumentsMatchingQuery(transaction: PersistenceTransaction, query: Query_2, offset: IndexOffset, mutatedDocs: OverlayMap, context?: QueryContext): PersistencePromise; + /** + * Looks up the next `limit` documents for a collection group based on the + * provided offset. The ordering is based on the document's read time and key. + * + * @param collectionGroup - The collection group to scan. + * @param offset - The offset to start the scan at (exclusive). + * @param limit - The maximum number of results to return. + * @returns The set of matching documents. + */ + getAllFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset, limit: number): PersistencePromise; + /** + * Provides access to add or update the contents of the cache. The buffer + * handles proper size accounting for the change. + * + * Multi-Tab Note: This should only be called by the primary client. + * + * @param options - Specify `trackRemovals` to create sentinel entries for + * removed documents, which allows removals to be tracked by + * `getNewDocumentChanges()`. + */ + newChangeBuffer(options?: { + trackRemovals: boolean; + }): RemoteDocumentChangeBuffer; + /** + * Get an estimate of the size of the document cache. Note that for eager + * garbage collection, we don't track sizes so this will return 0. + */ + getSize(transaction: PersistenceTransaction): PersistencePromise; +} + +/** + * An in-memory buffer of entries to be written to a RemoteDocumentCache. + * It can be used to batch up a set of changes to be written to the cache, but + * additionally supports reading entries back with the `getEntry()` method, + * falling back to the underlying RemoteDocumentCache if no entry is + * buffered. + * + * Entries added to the cache *must* be read first. This is to facilitate + * calculating the size delta of the pending changes. + * + * PORTING NOTE: This class was implemented then removed from other platforms. + * If byte-counting ends up being needed on the other platforms, consider + * porting this class as part of that implementation work. + */ +declare abstract class RemoteDocumentChangeBuffer { + protected changes: ObjectMap<_DocumentKey, MutableDocument>; + private changesApplied; + protected abstract getFromCache(transaction: PersistenceTransaction, documentKey: _DocumentKey): PersistencePromise; + protected abstract getAllFromCache(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise; + protected abstract applyChanges(transaction: PersistenceTransaction): PersistencePromise; + /** + * Buffers a `RemoteDocumentCache.addEntry()` call. + * + * You can only modify documents that have already been retrieved via + * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). + */ + addEntry(document: MutableDocument): void; + /** + * Buffers a `RemoteDocumentCache.removeEntry()` call. + * + * You can only remove documents that have already been retrieved via + * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). + */ + removeEntry(key: _DocumentKey, readTime: SnapshotVersion): void; + /** + * Looks up an entry in the cache. The buffered changes will first be checked, + * and if no buffered change applies, this will forward to + * `RemoteDocumentCache.getEntry()`. + * + * @param transaction - The transaction in which to perform any persistence + * operations. + * @param documentKey - The key of the entry to look up. + * @returns The cached document or an invalid document if we have nothing + * cached. + */ + getEntry(transaction: PersistenceTransaction, documentKey: _DocumentKey): PersistencePromise; + /** + * Looks up several entries in the cache, forwarding to + * `RemoteDocumentCache.getEntry()`. + * + * @param transaction - The transaction in which to perform any persistence + * operations. + * @param documentKeys - The keys of the entries to look up. + * @returns A map of cached documents, indexed by key. If an entry cannot be + * found, the corresponding key will be mapped to an invalid document. + */ + getEntries(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise; + /** + * Applies buffered changes to the underlying RemoteDocumentCache, using + * the provided transaction. + */ + apply(transaction: PersistenceTransaction): PersistencePromise; + /** Helper to assert this.changes is not null */ + protected assertNotApplied(): void; +} + +/** + * An event from the RemoteStore. It is split into targetChanges (changes to the + * state or the set of documents in our watched targets) and documentUpdates + * (changes to the actual documents). + */ +declare class RemoteEvent { + /** + * The snapshot version this event brings us up to, or MIN if not set. + */ + readonly snapshotVersion: SnapshotVersion; + /** + * A map from target to changes to the target. See TargetChange. + */ + readonly targetChanges: Map; + /** + * A map of targets that is known to be inconsistent, and the purpose for + * re-listening. Listens for these targets should be re-established without + * resume tokens. + */ + readonly targetMismatches: SortedMap; + /** + * A set of which documents have changed or been deleted, along with the + * doc's new values (if not deleted). + */ + readonly documentUpdates: MutableDocumentMap; + /** + * A set of which document updates are due only to limbo resolution targets. + */ + readonly resolvedLimboDocuments: DocumentKeySet; + constructor( + /** + * The snapshot version this event brings us up to, or MIN if not set. + */ + snapshotVersion: SnapshotVersion, + /** + * A map from target to changes to the target. See TargetChange. + */ + targetChanges: Map, + /** + * A map of targets that is known to be inconsistent, and the purpose for + * re-listening. Listens for these targets should be re-established without + * resume tokens. + */ + targetMismatches: SortedMap, + /** + * A set of which documents have changed or been deleted, along with the + * doc's new values (if not deleted). + */ + documentUpdates: MutableDocumentMap, + /** + * A set of which document updates are due only to limbo resolution targets. + */ + resolvedLimboDocuments: DocumentKeySet); + /** + * HACK: Views require RemoteEvents in order to determine whether the view is + * CURRENT, but secondary tabs don't receive remote events. So this method is + * used to create a synthesized RemoteEvent that can be used to apply a + * CURRENT status change to a View, for queries executed in a different tab. + */ + static createSynthesizedRemoteEventForCurrentChange(targetId: TargetId, current: boolean, resumeToken: _ByteString): RemoteEvent; +} + +/** + * RemoteStore - An interface to remotely stored data, basically providing a + * wrapper around the Datastore that is more reliable for the rest of the + * system. + * + * RemoteStore is responsible for maintaining the connection to the server. + * - maintaining a list of active listens. + * - reconnecting when the connection is dropped. + * - resuming all the active listens on reconnect. + * + * RemoteStore handles all incoming events from the Datastore. + * - listening to the watch stream and repackaging the events as RemoteEvents + * - notifying SyncEngine of any changes to the active listens. + * + * RemoteStore takes writes from other components and handles them reliably. + * - pulling pending mutations from LocalStore and sending them to Datastore. + * - retrying mutations that failed because of network problems. + * - acking mutations to the SyncEngine once they are accepted or rejected. + */ +declare interface RemoteStore { + /** + * SyncEngine to notify of watch and write events. This must be set + * immediately after construction. + */ + remoteSyncer: RemoteSyncer; +} + +/** + * An interface that describes the actions the RemoteStore needs to perform on + * a cooperating synchronization engine. + */ +declare interface RemoteSyncer { + /** + * Applies one remote event to the sync engine, notifying any views of the + * changes, and releasing any pending mutation batches that would become + * visible because of the snapshot version the remote event contains. + */ + applyRemoteEvent?(remoteEvent: RemoteEvent): Promise; + /** + * Rejects the listen for the given targetID. This can be triggered by the + * backend for any active target. + * + * @param targetId - The targetID corresponds to one previously initiated by + * the user as part of TargetData passed to listen() on RemoteStore. + * @param error - A description of the condition that has forced the rejection. + * Nearly always this will be an indication that the user is no longer + * authorized to see the data matching the target. + */ + rejectListen?(targetId: TargetId, error: FirestoreError): Promise; + /** + * Applies the result of a successful write of a mutation batch to the sync + * engine, emitting snapshots in any views that the mutation applies to, and + * removing the batch from the mutation queue. + */ + applySuccessfulWrite?(result: MutationBatchResult): Promise; + /** + * Rejects the batch, removing the batch from the mutation queue, recomputing + * the local view of any documents affected by the batch and then, emitting + * snapshots with the reverted value. + */ + rejectFailedWrite?(batchId: BatchId, error: FirestoreError): Promise; + /** + * Returns the set of remote document keys for the given target ID. This list + * includes the documents that were assigned to the target when we received + * the last snapshot. + */ + getRemoteKeysForTarget?(targetId: TargetId): DocumentKeySet; + /** + * Updates all local state to match the pending mutations for the given user. + * May be called repeatedly for the same user. + */ + handleCredentialChange?(user: User): Promise; +} + +declare type Resolver = (value?: T) => void; + +/** + * A slash-separated path for navigating resources (documents and collections) + * within Firestore. + * + * @internal + */ +export declare class _ResourcePath extends BasePath<_ResourcePath> { + protected construct(segments: string[], offset?: number, length?: number): _ResourcePath; + canonicalString(): string; + toString(): string; + /** + * Returns a string representation of this path + * where each path segment has been encoded with + * `encodeURIComponent`. + */ + toUriEncodedString(): string; + /** + * Creates a resource path from the given slash-delimited string. If multiple + * arguments are provided, all components are combined. Leading and trailing + * slashes from all components are ignored. + */ + static fromString(...pathComponents: string[]): _ResourcePath; + static emptyPath(): _ResourcePath; +} + +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ +export declare function runTransaction(firestore: Firestore, updateFunction: (transaction: Transaction) => Promise, options?: TransactionOptions): Promise; + +/** + * Interface to schedule periodic tasks within SDK. + */ +declare interface Scheduler { + readonly started: boolean; + start(): void; + stop(): void; +} + +/** Base interface for the Serializer implementation. */ +declare interface Serializer { + readonly useProto3Json: boolean; +} + +/** + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to + * include a server-generated timestamp in the written data. + */ +export declare function serverTimestamp(): FieldValue; + +declare type ServerTimestampBehavior = 'estimate' | 'previous' | 'none'; + +/** + * Writes to the document referred to by this `DocumentReference`. If the + * document does not yet exist, it will be created. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +export declare function setDoc(reference: DocumentReference, data: WithFieldValue): Promise; + +/** + * Writes to the document referred to by the specified `DocumentReference`. If + * the document does not yet exist, it will be created. If you provide `merge` + * or `mergeFields`, the provided data can be merged into an existing document. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @returns A Promise resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +export declare function setDoc(reference: DocumentReference, data: PartialWithFieldValue, options: SetOptions): Promise; + +/** + * Configures indexing for local query execution. Any previous index + * configuration is overridden. The `Promise` resolves once the index + * configuration has been persisted. + * + * The index entries themselves are created asynchronously. You can continue to + * use queries that require indexing even if the indices are not yet available. + * Query execution will automatically start using the index once the index + * entries have been written. + * + * Indexes are only supported with IndexedDb persistence. If IndexedDb is not + * enabled, any index configuration is ignored. + * + * @param firestore - The {@link Firestore} instance to configure indexes for. + * @param configuration -The index definition. + * @throws FirestoreError if the JSON format is invalid. + * @returns A `Promise` that resolves once all indices are successfully + * configured. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare function setIndexConfiguration(firestore: Firestore, configuration: IndexConfiguration): Promise; + +/** + * Configures indexing for local query execution. Any previous index + * configuration is overridden. The `Promise` resolves once the index + * configuration has been persisted. + * + * The index entries themselves are created asynchronously. You can continue to + * use queries that require indexing even if the indices are not yet available. + * Query execution will automatically start using the index once the index + * entries have been written. + * + * Indexes are only supported with IndexedDb persistence. Invoke either + * `enableIndexedDbPersistence()` or `enableMultiTabIndexedDbPersistence()` + * before setting an index configuration. If IndexedDb is not enabled, any + * index configuration is ignored. + * + * The method accepts the JSON format exported by the Firebase CLI (`firebase + * firestore:indexes`). If the JSON format is invalid, this method throws an + * error. + * + * @param firestore - The {@link Firestore} instance to configure indexes for. + * @param json -The JSON format exported by the Firebase CLI. + * @throws FirestoreError if the JSON format is invalid. + * @returns A `Promise` that resolves once all indices are successfully + * configured. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare function setIndexConfiguration(firestore: Firestore, json: string): Promise; + +/** + * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). + * + * @param logLevel - The verbosity you set for activity and error logging. Can + * be any of the following values: + * + *

+ */ +export declare function setLogLevel(logLevel: LogLevel): void; + +/** + * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link + * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be + * configured to perform granular merges instead of overwriting the target + * documents in their entirety by providing a `SetOptions` with `merge: true`. + * + * @param merge - Changes the behavior of a `setDoc()` call to only replace the + * values specified in its data argument. Fields omitted from the `setDoc()` + * call remain untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace + * the specified field paths. Any field path that is not specified is ignored + * and remains untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + */ +export declare type SetOptions = { + readonly merge?: boolean; +} | { + readonly mergeFields?: Array; +}; + +/** + * A `SharedClientState` keeps track of the global state of the mutations + * and query targets for all active clients with the same persistence key (i.e. + * project ID and FirebaseApp name). It relays local changes to other clients + * and updates its local state as new state is observed. + * + * `SharedClientState` is primarily used for synchronization in Multi-Tab + * environments. Each tab is responsible for registering its active query + * targets and mutations. `SharedClientState` will then notify the listener + * assigned to `.syncEngine` for updates to mutations and queries that + * originated in other clients. + * + * To receive notifications, `.syncEngine` and `.onlineStateHandler` has to be + * assigned before calling `start()`. + */ +declare interface SharedClientState { + onlineStateHandler: ((onlineState: OnlineState) => void) | null; + sequenceNumberHandler: ((sequenceNumber: ListenSequenceNumber) => void) | null; + /** Registers the Mutation Batch ID of a newly pending mutation. */ + addPendingMutation(batchId: BatchId): void; + /** + * Records that a pending mutation has been acknowledged or rejected. + * Called by the primary client to notify secondary clients of mutation + * results as they come back from the backend. + */ + updateMutationState(batchId: BatchId, state: 'acknowledged' | 'rejected', error?: FirestoreError): void; + /** + * Associates a new Query Target ID with the local Firestore client. Returns + * the new query state for the query (which can be 'current' if the query is + * already associated with another tab). + * + * If the target id is already associated with local client, the method simply + * returns its `QueryTargetState`. + */ + addLocalQueryTarget(targetId: TargetId, addToActiveTargetIds?: boolean): QueryTargetState; + /** Removes the Query Target ID association from the local client. */ + removeLocalQueryTarget(targetId: TargetId): void; + /** Checks whether the target is associated with the local client. */ + isLocalQueryTarget(targetId: TargetId): boolean; + /** + * Processes an update to a query target. + * + * Called by the primary client to notify secondary clients of document + * changes or state transitions that affect the provided query target. + */ + updateQueryState(targetId: TargetId, state: QueryTargetState, error?: FirestoreError): void; + /** + * Removes the target's metadata entry. + * + * Called by the primary client when all clients stopped listening to a query + * target. + */ + clearQueryState(targetId: TargetId): void; + /** + * Gets the active Query Targets IDs for all active clients. + * + * The implementation for this may require O(n) runtime, where 'n' is the size + * of the result set. + */ + getAllActiveQueryTargets(): SortedSet; + /** + * Checks whether the provided target ID is currently being listened to by + * any of the active clients. + * + * The implementation may require O(n*log m) runtime, where 'n' is the number + * of clients and 'm' the number of targets. + */ + isActiveQueryTarget(targetId: TargetId): boolean; + /** + * Starts the SharedClientState, reads existing client data and registers + * listeners for updates to new and existing clients. + */ + start(): Promise; + /** Shuts down the `SharedClientState` and its listeners. */ + shutdown(): void; + /** + * Changes the active user and removes all existing user-specific data. The + * user change does not call back into SyncEngine (for example, no mutations + * will be marked as removed). + */ + handleUserChange(user: User, removedBatchIds: BatchId[], addedBatchIds: BatchId[]): void; + /** Changes the shared online state of all clients. */ + setOnlineState(onlineState: OnlineState): void; + writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void; + /** + * Notifies other clients when remote documents have changed due to loading + * a bundle. + * + * @param collectionGroups The collection groups affected by this bundle. + */ + notifyBundleLoaded(collectionGroups: Set): void; +} + +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ +export declare function snapshotEqual(left: DocumentSnapshot | QuerySnapshot, right: DocumentSnapshot | QuerySnapshot): boolean; + +/** + * An options object that can be passed to {@link (onSnapshot:1)} and {@link + * QuerySnapshot.docChanges} to control which types of changes to include in the + * result set. + */ +export declare interface SnapshotListenOptions { + /** + * Include a change even if only the metadata of the query or of a document + * changed. Default is false. + */ + readonly includeMetadataChanges?: boolean; + /** + * Set the source the query listens to. Default to "default", which + * listens to both cache and server. + */ + readonly source?: ListenSource; +} + +/** + * Metadata about a snapshot, describing the state of the snapshot. + */ +export declare class SnapshotMetadata { + /** + * True if the snapshot contains the result of local writes (for example + * `set()` or `update()` calls) that have not yet been committed to the + * backend. If your listener has opted into metadata updates (via + * `SnapshotListenOptions`) you will receive another snapshot with + * `hasPendingWrites` equal to false once the writes have been committed to + * the backend. + */ + readonly hasPendingWrites: boolean; + /** + * True if the snapshot was created from cached data rather than guaranteed + * up-to-date server data. If your listener has opted into metadata updates + * (via `SnapshotListenOptions`) you will receive another snapshot with + * `fromCache` set to false once the client has received up-to-date data from + * the backend. + */ + readonly fromCache: boolean; + /** @hideconstructor */ + constructor(hasPendingWrites: boolean, fromCache: boolean); + /** + * Returns true if this `SnapshotMetadata` is equal to the provided one. + * + * @param other - The `SnapshotMetadata` to compare against. + * @returns true if this `SnapshotMetadata` is equal to the provided one. + */ + isEqual(other: SnapshotMetadata): boolean; +} + +/** + * Options that configure how data is retrieved from a `DocumentSnapshot` (for + * example the desired behavior for server timestamps that have not yet been set + * to their final value). + */ +export declare interface SnapshotOptions { + /** + * If set, controls the return value for server timestamps that have not yet + * been set to their final value. + * + * By specifying 'estimate', pending server timestamps return an estimate + * based on the local clock. This estimate will differ from the final value + * and cause these values to change once the server result becomes available. + * + * By specifying 'previous', pending timestamps will be ignored and return + * their previous value instead. + * + * If omitted or set to 'none', `null` will be returned by default until the + * server value becomes available. + */ + readonly serverTimestamps?: 'estimate' | 'previous' | 'none'; +} + +/** + * A version of a document in Firestore. This corresponds to the version + * timestamp, such as update_time or read_time. + */ +declare class SnapshotVersion { + private timestamp; + static fromTimestamp(value: Timestamp): SnapshotVersion; + static min(): SnapshotVersion; + static max(): SnapshotVersion; + private constructor(); + compareTo(other: SnapshotVersion): number; + isEqual(other: SnapshotVersion): boolean; + /** Returns a number representation of the version for use in spec tests. */ + toMicroseconds(): number; + toString(): string; + toTimestamp(): Timestamp; +} + +declare class SortedMap { + comparator: Comparator; + root: LLRBNode | LLRBEmptyNode; + constructor(comparator: Comparator, root?: LLRBNode | LLRBEmptyNode); + insert(key: K, value: V): SortedMap; + remove(key: K): SortedMap; + get(key: K): V | null; + indexOf(key: K): number; + isEmpty(): boolean; + get size(): number; + minKey(): K | null; + maxKey(): K | null; + inorderTraversal(action: (k: K, v: V) => T): T; + forEach(fn: (k: K, v: V) => void): void; + toString(): string; + reverseTraversal(action: (k: K, v: V) => T): T; + getIterator(): SortedMapIterator; + getIteratorFrom(key: K): SortedMapIterator; + getReverseIterator(): SortedMapIterator; + getReverseIteratorFrom(key: K): SortedMapIterator; +} + +declare class SortedMapIterator { + private isReverse; + private nodeStack; + constructor(node: LLRBNode | LLRBEmptyNode, startKey: K | null, comparator: Comparator, isReverse: boolean); + getNext(): Entry; + hasNext(): boolean; + peek(): Entry | null; +} + +/** + * SortedSet is an immutable (copy-on-write) collection that holds elements + * in order specified by the provided comparator. + * + * NOTE: if provided comparator returns 0 for two elements, we consider them to + * be equal! + */ +declare class SortedSet { + private comparator; + private data; + constructor(comparator: (left: T, right: T) => number); + has(elem: T): boolean; + first(): T | null; + last(): T | null; + get size(): number; + indexOf(elem: T): number; + /** Iterates elements in order defined by "comparator" */ + forEach(cb: (elem: T) => void): void; + /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ + forEachInRange(range: [T, T], cb: (elem: T) => void): void; + /** + * Iterates over `elem`s such that: start <= elem until false is returned. + */ + forEachWhile(cb: (elem: T) => boolean, start?: T): void; + /** Finds the least element greater than or equal to `elem`. */ + firstAfterOrEqual(elem: T): T | null; + getIterator(): SortedSetIterator; + getIteratorFrom(key: T): SortedSetIterator; + /** Inserts or updates an element */ + add(elem: T): SortedSet; + /** Deletes an element */ + delete(elem: T): SortedSet; + isEmpty(): boolean; + unionWith(other: SortedSet): SortedSet; + isEqual(other: SortedSet): boolean; + toArray(): T[]; + toString(): string; + private copy; +} + +declare class SortedSetIterator { + private iter; + constructor(iter: SortedMapIterator); + getNext(): T; + hasNext(): boolean; +} + +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided document (exclusive). The starting position is + * relative to the order of the query. The document must contain all of the + * fields provided in the orderBy of the query. + * + * @param snapshot - The snapshot of the document to start after. + * @returns A {@link QueryStartAtConstraint} to pass to `query()` + */ +export declare function startAfter(snapshot: DocumentSnapshot_2): QueryStartAtConstraint; + +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided fields relative to the order of the query. The order + * of the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to start this query after, in order + * of the query's order by. + * @returns A {@link QueryStartAtConstraint} to pass to `query()` + */ +export declare function startAfter(...fieldValues: unknown[]): QueryStartAtConstraint; + +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided document (inclusive). The starting position is relative + * to the order of the query. The document must contain all of the fields + * provided in the `orderBy` of this query. + * + * @param snapshot - The snapshot of the document to start at. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. + */ +export declare function startAt(snapshot: DocumentSnapshot_2): QueryStartAtConstraint; + +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to start this query at, in order + * of the query's order by. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. + */ +export declare function startAt(...fieldValues: unknown[]): QueryStartAtConstraint; + +declare type StructuredQuery = firestoreV1ApiClientInterfaces.StructuredQuery; + +/** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ +export declare function sum(field: string | FieldPath): AggregateField; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * SyncEngine is the central controller in the client SDK architecture. It is + * the glue code between the EventManager, LocalStore, and RemoteStore. Some of + * SyncEngine's responsibilities include: + * 1. Coordinating client requests and remote events between the EventManager + * and the local and remote data stores. + * 2. Managing a View object for each query, providing the unified view between + * the local and remote data stores. + * 3. Notifying the RemoteStore when the LocalStore has new mutations in its + * queue that need sending to the backend. + * + * The SyncEngine’s methods should only ever be called by methods running in the + * global async queue. + * + * PORTING NOTE: On Web, SyncEngine does not have an explicit subscribe() + * function. Instead, it directly depends on EventManager's tree-shakeable API + * (via `ensureWatchStream()`). + */ +declare interface SyncEngine { + isPrimaryClient: boolean; +} + +/** + * A Target represents the WatchTarget representation of a Query, which is used + * by the LocalStore and the RemoteStore to keep track of and to execute + * backend queries. While a Query can represent multiple Targets, each Targets + * maps to a single WatchTarget in RemoteStore and a single TargetData entry + * in persistence. + */ +declare interface Target { + readonly path: _ResourcePath; + readonly collectionGroup: string | null; + readonly orderBy: OrderBy[]; + readonly filters: Filter[]; + readonly limit: number | null; + readonly startAt: Bound | null; + readonly endAt: Bound | null; +} + +/** + * Represents cached targets received from the remote backend. + * + * The cache is keyed by `Target` and entries in the cache are `TargetData` + * instances. + */ +declare interface TargetCache { + /** + * A global snapshot version representing the last consistent snapshot we + * received from the backend. This is monotonically increasing and any + * snapshots received from the backend prior to this version (e.g. for targets + * resumed with a resume_token) should be suppressed (buffered) until the + * backend has caught up to this snapshot version again. This prevents our + * cache from ever going backwards in time. + * + * This is updated whenever our we get a TargetChange with a read_time and + * empty target_ids. + */ + getLastRemoteSnapshotVersion(transaction: PersistenceTransaction): PersistencePromise; + /** + * @returns The highest sequence number observed, including any that might be + * persisted on-disk. + */ + getHighestSequenceNumber(transaction: PersistenceTransaction): PersistencePromise; + /** + * Call provided function with each `TargetData` that we have cached. + */ + forEachTarget(txn: PersistenceTransaction, f: (q: TargetData) => void): PersistencePromise; + /** + * Set the highest listen sequence number and optionally updates the + * snapshot version of the last consistent snapshot received from the backend + * (see getLastRemoteSnapshotVersion() for more details). + * + * @param highestListenSequenceNumber - The new maximum listen sequence number. + * @param lastRemoteSnapshotVersion - The new snapshot version. Optional. + */ + setTargetsMetadata(transaction: PersistenceTransaction, highestListenSequenceNumber: number, lastRemoteSnapshotVersion?: SnapshotVersion): PersistencePromise; + /** + * Adds an entry in the cache. + * + * The cache key is extracted from `targetData.target`. The key must not already + * exist in the cache. + * + * @param targetData - A TargetData instance to put in the cache. + */ + addTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Updates an entry in the cache. + * + * The cache key is extracted from `targetData.target`. The entry must already + * exist in the cache, and it will be replaced. + * @param targetData - The TargetData to be replaced into the cache. + */ + updateTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Removes the cached entry for the given target data. It is an error to remove + * a target data that does not exist. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * The number of targets currently in the cache. + */ + getTargetCount(transaction: PersistenceTransaction): PersistencePromise; + /** + * Looks up a TargetData entry by target. + * + * @param target - The query target corresponding to the entry to look up. + * @returns The cached TargetData entry, or null if the cache has no entry for + * the target. + */ + getTargetData(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Adds the given document keys to cached query results of the given target + * ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + addMatchingKeys(transaction: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + /** + * Removes the given document keys from the cached query results of the + * given target ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMatchingKeys(transaction: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + /** + * Removes all the keys in the query results of the given target ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMatchingKeysForTargetId(transaction: PersistenceTransaction, targetId: TargetId): PersistencePromise; + /** + * Returns the document keys that match the provided target ID. + */ + getMatchingKeysForTargetId(transaction: PersistenceTransaction, targetId: TargetId): PersistencePromise; + /** + * Returns a new target ID that is higher than any query in the cache. If + * there are no queries in the cache, returns the first valid target ID. + * Allocated target IDs are persisted and `allocateTargetId()` will never + * return the same ID twice. + */ + allocateTargetId(transaction: PersistenceTransaction): PersistencePromise; + containsKey(transaction: PersistenceTransaction, key: _DocumentKey): PersistencePromise; +} + +/** + * A TargetChange specifies the set of changes for a specific target as part of + * a RemoteEvent. These changes track which documents are added, modified or + * removed, as well as the target's resume token and whether the target is + * marked CURRENT. + * The actual changes *to* documents are not part of the TargetChange since + * documents may be part of multiple targets. + */ +declare class TargetChange { + /** + * An opaque, server-assigned token that allows watching a query to be resumed + * after disconnecting without retransmitting all the data that matches the + * query. The resume token essentially identifies a point in time from which + * the server should resume sending results. + */ + readonly resumeToken: _ByteString; + /** + * The "current" (synced) status of this target. Note that "current" + * has special meaning in the RPC protocol that implies that a target is + * both up-to-date and consistent with the rest of the watch stream. + */ + readonly current: boolean; + /** + * The set of documents that were newly assigned to this target as part of + * this remote event. + */ + readonly addedDocuments: DocumentKeySet; + /** + * The set of documents that were already assigned to this target but received + * an update during this remote event. + */ + readonly modifiedDocuments: DocumentKeySet; + /** + * The set of documents that were removed from this target as part of this + * remote event. + */ + readonly removedDocuments: DocumentKeySet; + constructor( + /** + * An opaque, server-assigned token that allows watching a query to be resumed + * after disconnecting without retransmitting all the data that matches the + * query. The resume token essentially identifies a point in time from which + * the server should resume sending results. + */ + resumeToken: _ByteString, + /** + * The "current" (synced) status of this target. Note that "current" + * has special meaning in the RPC protocol that implies that a target is + * both up-to-date and consistent with the rest of the watch stream. + */ + current: boolean, + /** + * The set of documents that were newly assigned to this target as part of + * this remote event. + */ + addedDocuments: DocumentKeySet, + /** + * The set of documents that were already assigned to this target but received + * an update during this remote event. + */ + modifiedDocuments: DocumentKeySet, + /** + * The set of documents that were removed from this target as part of this + * remote event. + */ + removedDocuments: DocumentKeySet); + /** + * This method is used to create a synthesized TargetChanges that can be used to + * apply a CURRENT status change to a View (for queries executed in a different + * tab) or for new queries (to raise snapshots with correct CURRENT status). + */ + static createSynthesizedTargetChangeForCurrentChange(targetId: TargetId, current: boolean, resumeToken: _ByteString): TargetChange; +} + +declare type TargetChangeTargetChangeType = 'NO_CHANGE' | 'ADD' | 'REMOVE' | 'CURRENT' | 'RESET'; + +/** + * An immutable set of metadata that the local store tracks for each target. + */ +declare class TargetData { + /** The target being listened to. */ + readonly target: Target; + /** + * The target ID to which the target corresponds; Assigned by the + * LocalStore for user listens and by the SyncEngine for limbo watches. + */ + readonly targetId: TargetId; + /** The purpose of the target. */ + readonly purpose: TargetPurpose; + /** + * The sequence number of the last transaction during which this target data + * was modified. + */ + readonly sequenceNumber: ListenSequenceNumber; + /** The latest snapshot version seen for this target. */ + readonly snapshotVersion: SnapshotVersion; + /** + * The maximum snapshot version at which the associated view + * contained no limbo documents. + */ + readonly lastLimboFreeSnapshotVersion: SnapshotVersion; + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + readonly resumeToken: _ByteString; + /** + * The number of documents that last matched the query at the resume token or + * read time. Documents are counted only when making a listen request with + * resume token or read time, otherwise, keep it null. + */ + readonly expectedCount: number | null; + constructor( + /** The target being listened to. */ + target: Target, + /** + * The target ID to which the target corresponds; Assigned by the + * LocalStore for user listens and by the SyncEngine for limbo watches. + */ + targetId: TargetId, + /** The purpose of the target. */ + purpose: TargetPurpose, + /** + * The sequence number of the last transaction during which this target data + * was modified. + */ + sequenceNumber: ListenSequenceNumber, + /** The latest snapshot version seen for this target. */ + snapshotVersion?: SnapshotVersion, + /** + * The maximum snapshot version at which the associated view + * contained no limbo documents. + */ + lastLimboFreeSnapshotVersion?: SnapshotVersion, + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + resumeToken?: _ByteString, + /** + * The number of documents that last matched the query at the resume token or + * read time. Documents are counted only when making a listen request with + * resume token or read time, otherwise, keep it null. + */ + expectedCount?: number | null); + /** Creates a new target data instance with an updated sequence number. */ + withSequenceNumber(sequenceNumber: number): TargetData; + /** + * Creates a new target data instance with an updated resume token and + * snapshot version. + */ + withResumeToken(resumeToken: _ByteString, snapshotVersion: SnapshotVersion): TargetData; + /** + * Creates a new target data instance with an updated expected count. + */ + withExpectedCount(expectedCount: number): TargetData; + /** + * Creates a new target data instance with an updated last limbo free + * snapshot version number. + */ + withLastLimboFreeSnapshotVersion(lastLimboFreeSnapshotVersion: SnapshotVersion): TargetData; +} + +/** + * A locally-assigned ID used to refer to a target being watched via the + * Watch service. + */ +declare type TargetId = number; + +/** An enumeration of the different purposes we have for targets. */ +declare const enum TargetPurpose { + /** A regular, normal query target. */ + Listen = "TargetPurposeListen", + /** + * The query target was used to refill a query after an existence filter + * mismatch. + */ + ExistenceFilterMismatch = "TargetPurposeExistenceFilterMismatch", + /** + * The query target was used if the query is the result of a false positive in + * the bloom filter. + */ + ExistenceFilterMismatchBloom = "TargetPurposeExistenceFilterMismatchBloom", + /** The query target was used to resolve a limbo document. */ + LimboResolution = "TargetPurposeLimboResolution" +} + +/** + * Represents the state of bundle loading tasks. + * + * Both 'Error' and 'Success' are sinking state: task will abort or complete and there will + * be no more updates after they are reported. + */ +export declare type TaskState = 'Error' | 'Running' | 'Success'; + +/** + * Terminates the provided {@link Firestore} instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` function + * may be used. Any other function will throw a `FirestoreError`. + * + * To restart after termination, create a new instance of FirebaseFirestore with + * {@link (getFirestore:1)}. + * + * Termination does not cancel any pending writes, and any promises that are + * awaiting a response from the server will not be resolved. If you have + * persistence enabled, the next time you start this instance, it will resume + * sending these writes to the server. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all + * of its resources or in combination with `clearIndexedDbPersistence()` to + * ensure that all local state is destroyed between test runs. + * + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ +export declare function terminate(firestore: Firestore): Promise; + +/** + * Testing hooks for use by Firestore's integration test suite to reach into the + * SDK internals to validate logic and behavior that is not visible from the + * public API surface. + * + * @internal + */ +export declare class _TestingHooks { + private constructor(); + /** + * Registers a callback to be notified when an existence filter mismatch + * occurs in the Watch listen stream. + * + * The relative order in which callbacks are notified is unspecified; do not + * rely on any particular ordering. If a given callback is registered multiple + * times then it will be notified multiple times, once per registration. + * + * @param callback the callback to invoke upon existence filter mismatch. + * + * @return a function that, when called, unregisters the given callback; only + * the first invocation of the returned function does anything; all subsequent + * invocations do nothing. + */ + static onExistenceFilterMismatch(callback: _TestingHooksExistenceFilterMismatchCallback): Unsubscribe; +} + +/** + * The signature of callbacks registered with + * `TestingUtils.onExistenceFilterMismatch()`. + * + * The return value, if any, is ignored. + * + * @internal + */ +export declare type _TestingHooksExistenceFilterMismatchCallback = (info: _TestingHooksExistenceFilterMismatchInfo) => unknown; + +/** + * Information about an existence filter mismatch. + * @internal + */ +export declare interface _TestingHooksExistenceFilterMismatchInfo { + /** The number of documents that matched the query in the local cache. */ + localCacheCount: number; + /** + * The number of documents that matched the query on the server, as specified + * in the ExistenceFilter message's `count` field. + */ + existenceFilterCount: number; + /** + * The projectId used when checking documents for membership in the bloom + * filter. + */ + projectId: string; + /** + * The databaseId used when checking documents for membership in the bloom + * filter. + */ + databaseId: string; + /** + * Information about the bloom filter provided by Watch in the ExistenceFilter + * message's `unchangedNames` field. If this property is omitted or undefined + * then that means that Watch did _not_ provide a bloom filter. + */ + bloomFilter?: { + /** + * Whether a full requery was averted by using the bloom filter. If false, + * then something happened, such as a false positive, to prevent using the + * bloom filter to avoid a full requery. + */ + applied: boolean; + /** The number of hash functions used in the bloom filter. */ + hashCount: number; + /** The number of bytes in the bloom filter's bitmask. */ + bitmapLength: number; + /** The number of bits of padding in the last byte of the bloom filter. */ + padding: number; + /** + * Tests the given string for membership in the bloom filter created from + * the existence filter; will be undefined if creating the bloom filter + * failed. + */ + mightContain?: (value: string) => boolean; + }; +} + +/** + * Wellknown "timer" IDs used when scheduling delayed operations on the + * AsyncQueue. These IDs can then be used from tests to check for the presence + * of operations or to run them early. + * + * The string values are used when encoding these timer IDs in JSON spec tests. + */ +declare const enum TimerId { + /** All can be used with runDelayedOperationsEarly() to run all timers. */ + All = "all", + /** + * The following 5 timers are used in persistent_stream.ts for the listen and + * write streams. The "Idle" timer is used to close the stream due to + * inactivity. The "ConnectionBackoff" timer is used to restart a stream once + * the appropriate backoff delay has elapsed. The health check is used to mark + * a stream healthy if it has not received an error during its initial setup. + */ + ListenStreamIdle = "listen_stream_idle", + ListenStreamConnectionBackoff = "listen_stream_connection_backoff", + WriteStreamIdle = "write_stream_idle", + WriteStreamConnectionBackoff = "write_stream_connection_backoff", + HealthCheckTimeout = "health_check_timeout", + /** + * A timer used in online_state_tracker.ts to transition from + * OnlineState.Unknown to Offline after a set timeout, rather than waiting + * indefinitely for success or failure. + */ + OnlineStateTimeout = "online_state_timeout", + /** + * A timer used to update the client metadata in IndexedDb, which is used + * to determine the primary leaseholder. + */ + ClientMetadataRefresh = "client_metadata_refresh", + /** A timer used to periodically attempt LRU Garbage collection */ + LruGarbageCollection = "lru_garbage_collection", + /** + * A timer used to retry transactions. Since there can be multiple concurrent + * transactions, multiple of these may be in the queue at a given time. + */ + TransactionRetry = "transaction_retry", + /** + * A timer used to retry operations scheduled via retryable AsyncQueue + * operations. + */ + AsyncQueueRetry = "async_queue_retry", + /** + * A timer used to periodically attempt index backfill. + */ + IndexBackfill = "index_backfill" +} + +/** + * A `Timestamp` represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. + * + * It is encoded using the Proleptic Gregorian Calendar which extends the + * Gregorian calendar backwards to year one. It is encoded assuming all minutes + * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59.999999999Z. + * + * For examples and further specifications, refer to the + * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. + */ +export declare class Timestamp { + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + readonly seconds: number; + /** + * The fractions of a second at nanosecond resolution.* + */ + readonly nanoseconds: number; + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns a new timestamp representing the current date. + */ + static now(): Timestamp; + /** + * Creates a new timestamp from the given date. + * + * @param date - The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the given + * date. + */ + static fromDate(date: Date): Timestamp; + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds - Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the given + * number of milliseconds. + */ + static fromMillis(milliseconds: number): Timestamp; + /** + * Creates a new timestamp. + * + * @param seconds - The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds - The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ + constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + seconds: number, + /** + * The fractions of a second at nanosecond resolution.* + */ + nanoseconds: number); + /** + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ + toDate(): Date; + /** + * Converts a `Timestamp` to a numeric timestamp (in milliseconds since + * epoch). This operation causes a loss of precision. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ + toMillis(): number; + _compareTo(other: Timestamp): number; + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other - The `Timestamp` to compare against. + * @returns true if this `Timestamp` is equal to the provided one. + */ + isEqual(other: Timestamp): boolean; + /** Returns a textual representation of this `Timestamp`. */ + toString(): string; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + seconds: Property<"number">; + nanoseconds: Property<"number">; + }; + /** + * Returns a JSON-serializable representation of this `Timestamp`. + */ + toJSON(): { + seconds: number; + nanoseconds: number; + type: string; + }; + /** + * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}. + */ + static fromJSON(json: object): Timestamp; + /** + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. + */ + valueOf(): string; +} + +declare type Timestamp_2 = string | { + seconds?: string | number; + nanos?: number; +}; + +declare interface Token { + /** Type of token. */ + type: TokenType; + /** + * The user with which the token is associated (used for persisting user + * state on disk, etc.). + * This will be null for Tokens of the type 'AppCheck'. + */ + user?: User; + /** Header values to set for this token */ + headers: Map; +} + +declare type TokenType = 'OAuth' | 'FirstParty' | 'AppCheck'; + +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ +export declare class Transaction extends Transaction_2 { + protected readonly _firestore: Firestore; + /** @hideconstructor */ + constructor(_firestore: Firestore, _transaction: Transaction_3); + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ + get(documentRef: DocumentReference): Promise>; +} + +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ +declare class Transaction_2 { + protected readonly _firestore: Firestore_2; + private readonly _transaction; + private readonly _dataReader; + /** @hideconstructor */ + constructor(_firestore: Firestore_2, _transaction: Transaction_3); + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ + get(documentRef: DocumentReference): Promise>; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: WithFieldValue): this; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * If you provide `merge` or `mergeFields`, the provided data can be merged + * into an existing document. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: PartialWithFieldValue, options: SetOptions): this; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * @param documentRef - A reference to the document to be updated. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, data: UpdateData): this; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * @param documentRef - A reference to the document to be updated. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key/value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): this; + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + delete(documentRef: DocumentReference): this; +} + +/** + * Internal transaction object responsible for accumulating the mutations to + * perform and the base versions for any documents read. + */ +declare class Transaction_3 { + private datastore; + private readVersions; + private mutations; + private committed; + /** + * A deferred usage error that occurred previously in this transaction that + * will cause the transaction to fail once it actually commits. + */ + private lastTransactionError; + /** + * Set of documents that have been written in the transaction. + * + * When there's more than one write to the same key in a transaction, any + * writes after the first are handled differently. + */ + private writtenDocs; + constructor(datastore: Datastore); + lookup(keys: _DocumentKey[]): Promise; + set(key: _DocumentKey, data: ParsedSetData): void; + update(key: _DocumentKey, data: ParsedUpdateData): void; + delete(key: _DocumentKey): void; + commit(): Promise; + private recordVersion; + /** + * Returns the version of this document when it was read in this transaction, + * as a precondition, or no precondition if it was not read. + */ + private precondition; + /** + * Returns the precondition for a document if the operation is an update. + */ + private preconditionForUpdate; + private write; + private ensureCommitNotCalled; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options to customize transaction behavior. + */ +export declare interface TransactionOptions { + /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */ + readonly maxAttempts?: number; +} + +/** Used to represent a field transform on a mutation. */ +declare class TransformOperation { + private _; +} + +/** + * An association of JsonTypeDesc values to their native types. + * @private + * @internal + */ +declare type TSType = T extends 'object' ? object : T extends 'string' ? string : T extends 'number' ? number : T extends 'boolean' ? boolean : T extends 'null' ? null : T extends 'undefined' ? undefined : never; + +declare type UnaryFilterOp = 'OPERATOR_UNSPECIFIED' | 'IS_NAN' | 'IS_NULL' | 'IS_NOT_NAN' | 'IS_NOT_NULL'; + +/** + * Given a union type `U = T1 | T2 | ...`, returns an intersected type + * `(T1 & T2 & ...)`. + * + * Uses distributive conditional types and inference from conditional types. + * This works because multiple candidates for the same type variable in + * contra-variant positions causes an intersection type to be inferred. + * https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-inference-in-conditional-types + * https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type + */ +export declare type UnionToIntersection = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never; + +/** + * A function returned by `onSnapshot()` that removes the listener when invoked. + */ +export declare interface Unsubscribe { + /** Removes the listener when invoked. */ + (): void; +} + +/** + * An untyped Firestore Data Converter interface that is shared between the + * lite, firestore-exp and classic SDK. + */ +declare interface UntypedFirestoreDataConverter { + toFirestore(modelObject: WithFieldValue): WithFieldValue; + toFirestore(modelObject: PartialWithFieldValue, options: SetOptions_2): PartialWithFieldValue; + fromFirestore(snapshot: unknown, options?: unknown): AppModelType; +} + +/** + * Update data (for use with {@link (updateDoc:1)}) that consists of field paths + * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots + * reference nested fields within the document. FieldValues can be passed in + * as property values. + */ +export declare type UpdateData = T extends Primitive ? T : T extends {} ? { + [K in keyof T]?: UpdateData | FieldValue; +} & NestedUpdateFields : Partial; + +/** + * Updates fields in the document referred to by the specified + * `DocumentReference`. The update will fail if applied to a document that does + * not exist. + * + * @param reference - A reference to the document to update. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +export declare function updateDoc(reference: DocumentReference, data: UpdateData): Promise; + +/** + * Updates fields in the document referred to by the specified + * `DocumentReference` The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * @param reference - A reference to the document to update. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +export declare function updateDoc(reference: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): Promise; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Simple wrapper around a nullable UID. Mostly exists to make code more + * readable. + */ +declare class User { + readonly uid: string | null; + /** A user with a null UID. */ + static readonly UNAUTHENTICATED: User; + static readonly GOOGLE_CREDENTIALS: User; + static readonly FIRST_PARTY: User; + static readonly MOCK_USER: User; + constructor(uid: string | null); + isAuthenticated(): boolean; + /** + * Returns a key representing this user, suitable for inclusion in a + * dictionary. + */ + toKey(): string; + isEqual(otherUser: User): boolean; +} + +/** + * Validates that two boolean options are not set at the same time. + * @internal + */ +export declare function _validateIsNotUsedTogether(optionName1: string, argument1: boolean | undefined, optionName2: string, argument2: boolean | undefined): void; + +declare type Value = firestoreV1ApiClientInterfaces.Value; + +declare type ValueNullValue = 'NULL_VALUE'; + +/** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ +export declare function vector(values?: number[]): VectorValue; + +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link vector}. + * + * @class VectorValue + */ +export declare class VectorValue { + private readonly _values; + /** + * @private + * @internal + */ + constructor(values: number[] | undefined); + /** + * Returns a copy of the raw number array form of the vector. + */ + toArray(): number[]; + /** + * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise. + */ + isEqual(other: VectorValue): boolean; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + vectorValues: Property<"object">; + }; + /** + * Returns a JSON-serializable representation of this `VectorValue` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}. + * + * @param json a JSON object represention of a `VectorValue` instance. + * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): VectorValue; +} + +declare class ViewSnapshot { + readonly query: Query_2; + readonly docs: DocumentSet; + readonly oldDocs: DocumentSet; + readonly docChanges: DocumentViewChange[]; + readonly mutatedKeys: DocumentKeySet; + readonly fromCache: boolean; + readonly syncStateChanged: boolean; + readonly excludesMetadataChanges: boolean; + readonly hasCachedResults: boolean; + constructor(query: Query_2, docs: DocumentSet, oldDocs: DocumentSet, docChanges: DocumentViewChange[], mutatedKeys: DocumentKeySet, fromCache: boolean, syncStateChanged: boolean, excludesMetadataChanges: boolean, hasCachedResults: boolean); + /** Returns a view snapshot as if all documents in the snapshot were added. */ + static fromInitialDocuments(query: Query_2, documents: DocumentSet, mutatedKeys: DocumentKeySet, fromCache: boolean, hasCachedResults: boolean): ViewSnapshot; + get hasPendingWrites(): boolean; + isEqual(other: ViewSnapshot): boolean; +} + +/** + * Waits until all currently pending writes for the active user have been + * acknowledged by the backend. + * + * The returned promise resolves immediately if there are no outstanding writes. + * Otherwise, the promise waits for all previously issued writes (including + * those written in a previous app session), but it does not wait for writes + * that were added after the function is called. If you want to wait for + * additional writes, call `waitForPendingWrites()` again. + * + * Any outstanding `waitForPendingWrites()` promises are rejected during user + * changes. + * + * @returns A `Promise` which resolves when all currently pending writes have been + * acknowledged by the backend. + */ +export declare function waitForPendingWrites(firestore: Firestore): Promise; + +/** + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. + * + * @param fieldPath - The path to compare + * @param opStr - The operation string (e.g "<", "<=", "==", "<", + * "<=", "!="). + * @param value - The value for comparison + * @returns The created {@link QueryFieldFilterConstraint}. + */ +export declare function where(fieldPath: string | FieldPath, opStr: WhereFilterOp, value: unknown): QueryFieldFilterConstraint; + +/** + * Filter conditions in a {@link where} clause are specified using the + * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in', + * 'array-contains-any', and 'not-in'. + */ +export declare type WhereFilterOp = '<' | '<=' | '==' | '!=' | '>=' | '>' | 'array-contains' | 'in' | 'array-contains-any' | 'not-in'; + +/** + * Allows FieldValues to be passed in as a property value while maintaining + * type safety. + */ +export declare type WithFieldValue = T | (T extends Primitive ? T : T extends {} ? { + [K in keyof T]: WithFieldValue | FieldValue; +} : never); + +/** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It + * provides methods for adding writes to the write batch. None of the writes + * will be committed (or visible locally) until {@link WriteBatch.commit} is + * called. + */ +export declare class WriteBatch { + private readonly _firestore; + private readonly _commitHandler; + private readonly _dataReader; + private _mutations; + private _committed; + /** @hideconstructor */ + constructor(_firestore: Firestore_2, _commitHandler: (m: Mutation[]) => Promise); + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: WithFieldValue): WriteBatch; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * If you provide `merge` or `mergeFields`, the provided data can be merged + * into an existing document. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: PartialWithFieldValue, options: SetOptions): WriteBatch; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * @param documentRef - A reference to the document to be updated. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, data: UpdateData): WriteBatch; + /** + * Updates fields in the document referred to by this {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be update by providing dot-separated field path strings + * or by providing `FieldPath` objects. + * + * @param documentRef - A reference to the document to be updated. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): WriteBatch; + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + delete(documentRef: DocumentReference): WriteBatch; + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `Promise` resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit (note that it won't + * resolve while you're offline). + */ + commit(): Promise; + private _verifyNotCommitted; +} + +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch} + * is 500. + * + * Unlike transactions, write batches are persisted offline and therefore are + * preferable when you don't need to condition your writes on read data. + * + * @returns A {@link WriteBatch} that can be used to atomically execute multiple + * writes. + */ +export declare function writeBatch(firestore: Firestore): WriteBatch; + +export { } diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/lite/index.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/lite/index.d.ts new file mode 100644 index 0000000..86dd215 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/lite/index.d.ts @@ -0,0 +1,29 @@ +/** + * Firestore Lite + * + * @remarks Firestore Lite is a small online-only SDK that allows read + * and write access to your Firestore database. All operations connect + * directly to the backend, and `onSnapshot()` APIs are not supported. + * @packageDocumentation + */ +export { aggregateQuerySnapshotEqual, getCount, getAggregate, count, sum, average, aggregateFieldEqual } from '../src/lite-api/aggregate'; +export { AggregateField, AggregateFieldType, AggregateSpec, AggregateSpecData, AggregateQuerySnapshot, AggregateType } from '../src/lite-api/aggregate_types'; +export { FirestoreSettings as Settings } from '../src/lite-api/settings'; +export { Firestore as Firestore, EmulatorMockTokenOptions, initializeFirestore, getFirestore, terminate, connectFirestoreEmulator } from '../src/lite-api/database'; +export { DocumentData, UpdateData, WithFieldValue, PartialWithFieldValue, SetOptions, DocumentReference, Query, CollectionReference, collection, collectionGroup, doc, refEqual, queryEqual } from '../src/lite-api/reference'; +export { and, endAt, endBefore, startAt, startAfter, limit, limitToLast, where, or, orderBy, query, QueryConstraint, QueryConstraintType, QueryCompositeFilterConstraint, QueryFilterConstraint, QueryFieldFilterConstraint, QueryOrderByConstraint, QueryLimitConstraint, QueryNonFilterConstraint, QueryStartAtConstraint, QueryEndAtConstraint, OrderByDirection, WhereFilterOp } from '../src/lite-api/query'; +export { addDoc, deleteDoc, updateDoc, setDoc, getDoc, getDocs } from '../src/lite-api/reference_impl'; +export { Primitive, NestedUpdateFields, ChildUpdateFields, AddPrefixToKeys, UnionToIntersection } from '../src/lite-api/types'; +export { FieldPath, documentId } from '../src/lite-api/field_path'; +export { FieldValue } from '../src/lite-api/field_value'; +export { increment, arrayRemove, arrayUnion, serverTimestamp, deleteField, vector } from '../src/lite-api/field_value_impl'; +export { FirestoreDataConverter, DocumentSnapshot, QueryDocumentSnapshot, QuerySnapshot, snapshotEqual } from '../src/lite-api/snapshot'; +export { VectorValue } from '../src/lite-api/vector_value'; +export { WriteBatch, writeBatch } from '../src/lite-api/write_batch'; +export { TransactionOptions } from '../src/lite-api/transaction_options'; +export { Transaction, runTransaction } from '../src/lite-api/transaction'; +export { setLogLevel, LogLevelString as LogLevel } from '../src/util/log'; +export { Bytes } from '../src/lite-api/bytes'; +export { GeoPoint } from '../src/lite-api/geo_point'; +export { Timestamp } from '../src/lite-api/timestamp'; +export { FirestoreErrorCode, FirestoreError } from '../src/util/error'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/lite/register.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/lite/register.d.ts new file mode 100644 index 0000000..21b4ab3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/lite/register.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Firestore } from '../src/lite-api/database'; +declare module '@firebase/component' { + interface NameServiceMapping { + 'firestore/lite': Firestore; + } +} +export declare function registerFirestore(): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api.d.ts new file mode 100644 index 0000000..f5d6e02 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api.d.ts @@ -0,0 +1,65 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { aggregateFieldEqual, aggregateQuerySnapshotEqual, average, count, getAggregateFromServer, getCountFromServer, sum } from './api/aggregate'; +export { AggregateField, AggregateFieldType, AggregateQuerySnapshot, AggregateSpec, AggregateSpecData, AggregateType } from './lite-api/aggregate_types'; +export { FirestoreLocalCache, MemoryCacheSettings, MemoryEagerGarbageCollector, memoryEagerGarbageCollector, MemoryGarbageCollector, MemoryLocalCache, memoryLocalCache, MemoryLruGarbageCollector, memoryLruGarbageCollector, PersistentCacheSettings, PersistentLocalCache, persistentLocalCache, PersistentMultipleTabManager, persistentMultipleTabManager, PersistentSingleTabManager, persistentSingleTabManager, PersistentSingleTabManagerSettings, PersistentTabManager } from './api/cache_config'; +export { documentId, FieldPath } from './api/field_path'; +export { clearIndexedDbPersistence, connectFirestoreEmulator, disableNetwork, EmulatorMockTokenOptions, enableIndexedDbPersistence, enableMultiTabIndexedDbPersistence, enableNetwork, ensureFirestoreConfigured, Firestore, getFirestore, initializeFirestore, loadBundle, namedQuery, terminate, waitForPendingWrites } from './api/database'; +export { LoadBundleTask, LoadBundleTaskProgress, TaskState } from './api/bundle'; +export { FirestoreSettings, PersistenceSettings } from './api/settings'; +export type { PrivateSettings } from './lite-api/settings'; +export { ExperimentalLongPollingOptions } from './api/long_polling_options'; +export { DocumentChange, DocumentChangeType, DocumentSnapshot, documentSnapshotFromJSON, FirestoreDataConverter, QueryDocumentSnapshot, QuerySnapshot, querySnapshotFromJSON, snapshotEqual, SnapshotMetadata, SnapshotOptions } from './api/snapshot'; +export { collection, collectionGroup, CollectionReference, doc, DocumentData, DocumentReference, PartialWithFieldValue, Query, queryEqual, refEqual, SetOptions, UpdateData, WithFieldValue } from './api/reference'; +export { and, endAt, endBefore, limit, limitToLast, or, orderBy, OrderByDirection, query, QueryCompositeFilterConstraint, QueryConstraint, QueryConstraintType, QueryEndAtConstraint, QueryFieldFilterConstraint, QueryFilterConstraint, QueryLimitConstraint, QueryNonFilterConstraint, QueryOrderByConstraint, QueryStartAtConstraint, startAfter, startAt, where, WhereFilterOp } from './api/filter'; +export { ListenSource, SnapshotListenOptions, Unsubscribe } from './api/reference_impl'; +export { TransactionOptions } from './api/transaction_options'; +export { runTransaction, Transaction } from './api/transaction'; +export { addDoc, deleteDoc, executeWrite, getDoc, getDocFromCache, getDocFromServer, getDocs, getDocsFromCache, getDocsFromServer, onSnapshot, onSnapshotsInSync, onSnapshotResume, setDoc, updateDoc } from './api/reference_impl'; +export { FieldValue } from './api/field_value'; +export { arrayRemove, arrayUnion, deleteField, increment, serverTimestamp, vector } from './api/field_value_impl'; +export { VectorValue } from './lite-api/vector_value'; +export { LogLevelString as LogLevel, setLogLevel } from './util/log'; +export { Bytes } from './api/bytes'; +export { WriteBatch, writeBatch } from './api/write_batch'; +export { GeoPoint } from './api/geo_point'; +export { Timestamp } from './api/timestamp'; +export { CACHE_SIZE_UNLIMITED } from './api/database'; +export { FirestoreError, FirestoreErrorCode } from './util/error'; +export { AbstractUserDataWriter } from './lite-api/user_data_writer'; +export { AddPrefixToKeys, ChildUpdateFields, NestedUpdateFields, Primitive, UnionToIntersection } from '../src/lite-api/types'; +export { Index, IndexConfiguration, IndexField, setIndexConfiguration } from './api/index_configuration'; +export { PersistentCacheIndexManager, getPersistentCacheIndexManager, deleteAllPersistentCacheIndexes, enablePersistentCacheIndexAutoCreation, disablePersistentCacheIndexAutoCreation } from './api/persistent_cache_index_manager'; +/** + * Internal exports + */ +export { isBase64Available as _isBase64Available } from './platform/base64'; +export { DatabaseId as _DatabaseId } from './core/database_info'; +export { _internalQueryToProtoQueryTarget, _internalAggregationQueryToProtoRunAggregationQueryRequest } from './remote/internal_serializer'; +export { cast as _cast, validateIsNotUsedTogether as _validateIsNotUsedTogether } from './util/input_validation'; +export { DocumentKey as _DocumentKey } from './model/document_key'; +export { debugAssert as _debugAssert } from './util/assert'; +export { FieldPath as _FieldPath } from './model/path'; +export type { ResourcePath as _ResourcePath } from './model/path'; +export { ByteString as _ByteString } from './util/byte_string'; +export { logWarn as _logWarn } from './util/log'; +export { AutoId as _AutoId } from './util/misc'; +export type { AuthTokenFactory, FirstPartyCredentialsSettings } from './api/credentials'; +export { EmptyAuthCredentialsProvider as _EmptyAuthCredentialsProvider } from './api/credentials'; +export { EmptyAppCheckTokenProvider as _EmptyAppCheckTokenProvider } from './api/credentials'; +export { ExistenceFilterMismatchCallback as _TestingHooksExistenceFilterMismatchCallback, TestingHooks as _TestingHooks } from './util/testing_hooks'; +export { ExistenceFilterMismatchInfo as _TestingHooksExistenceFilterMismatchInfo } from './util/testing_hooks_spi'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/aggregate.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/aggregate.d.ts new file mode 100644 index 0000000..39bd4b4 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/aggregate.d.ts @@ -0,0 +1,77 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AggregateField, AggregateSpec, DocumentData, Query } from '../api'; +import { AggregateQuerySnapshot } from '../lite-api/aggregate_types'; +export { aggregateQuerySnapshotEqual, count, sum, average, aggregateFieldEqual } from '../lite-api/aggregate'; +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ +export declare function getCountFromServer(query: Query): Promise; +}, AppModelType, DbModelType>>; +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregateFromServer(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ +export declare function getAggregateFromServer(query: Query, aggregateSpec: AggregateSpecType): Promise>; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/bundle.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/bundle.d.ts new file mode 100644 index 0000000..15c33af --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/bundle.d.ts @@ -0,0 +1,94 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirestoreError } from '../util/error'; +/** + * Represents the state of bundle loading tasks. + * + * Both 'Error' and 'Success' are sinking state: task will abort or complete and there will + * be no more updates after they are reported. + */ +export type TaskState = 'Error' | 'Running' | 'Success'; +/** + * Represents a progress update or a final state from loading bundles. + */ +export interface LoadBundleTaskProgress { + /** How many documents have been loaded. */ + documentsLoaded: number; + /** How many documents are in the bundle being loaded. */ + totalDocuments: number; + /** How many bytes have been loaded. */ + bytesLoaded: number; + /** How many bytes are in the bundle being loaded. */ + totalBytes: number; + /** Current task state. */ + taskState: TaskState; +} +/** + * Represents the task of loading a Firestore bundle. It provides progress of bundle + * loading, as well as task completion and error events. + * + * The API is compatible with `Promise`. + */ +export declare class LoadBundleTask implements PromiseLike { + private _progressObserver; + private _taskCompletionResolver; + private _lastProgress; + /** + * Registers functions to listen to bundle loading progress events. + * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur + * each time a Firestore document is loaded from the bundle. + * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the + * error, and there should be no more updates after this. + * @param complete - Called when the loading task is complete. + */ + onProgress(next?: (progress: LoadBundleTaskProgress) => unknown, error?: (err: Error) => unknown, complete?: () => void): void; + /** + * Implements the `Promise.catch` interface. + * + * @param onRejected - Called when an error occurs during bundle loading. + */ + catch(onRejected: (a: Error) => R | PromiseLike): Promise; + /** + * Implements the `Promise.then` interface. + * + * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update. + * The update will always have its `taskState` set to `"Success"`. + * @param onRejected - Called when an error occurs during bundle loading. + */ + then(onFulfilled?: (a: LoadBundleTaskProgress) => T | PromiseLike, onRejected?: (a: Error) => R | PromiseLike): Promise; + /** + * Notifies all observers that bundle loading has completed, with a provided + * `LoadBundleTaskProgress` object. + * + * @private + */ + _completeWith(progress: LoadBundleTaskProgress): void; + /** + * Notifies all observers that bundle loading has failed, with a provided + * `Error` as the reason. + * + * @private + */ + _failWith(error: FirestoreError): void; + /** + * Notifies a progress update of loading a bundle. + * @param progress - The new progress. + * + * @private + */ + _updateProgress(progress: LoadBundleTaskProgress): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/bytes.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/bytes.d.ts new file mode 100644 index 0000000..0c9f5fd --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/bytes.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { Bytes } from '../lite-api/bytes'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/cache_config.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/cache_config.d.ts new file mode 100644 index 0000000..936f21e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/cache_config.d.ts @@ -0,0 +1,222 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { OfflineComponentProviderFactory, OnlineComponentProviderFactory } from '../core/component_provider'; +/** + * Provides an in-memory cache to the SDK. This is the default cache unless explicitly + * configured otherwise. + * + * To use, create an instance using the factory function {@link memoryLocalCache()}, then + * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using + * the settings object. + */ +export type MemoryLocalCache = { + kind: 'memory'; + /** + * @internal + */ + _onlineComponentProvider: OnlineComponentProviderFactory; + /** + * @internal + */ + _offlineComponentProvider: OfflineComponentProviderFactory; +}; +/** + * Provides a persistent cache backed by IndexedDb to the SDK. + * + * To use, create an instance using the factory function {@link persistentLocalCache()}, then + * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using + * the settings object. + */ +export type PersistentLocalCache = { + kind: 'persistent'; + /** + * @internal + */ + _onlineComponentProvider: OnlineComponentProviderFactory; + /** + * @internal + */ + _offlineComponentProvider: OfflineComponentProviderFactory; +}; +/** + * Union type from all supported SDK cache layer. + */ +export type FirestoreLocalCache = MemoryLocalCache | PersistentLocalCache; +/** + * Union type from all support garbage collectors for memory local cache. + */ +export type MemoryGarbageCollector = MemoryEagerGarbageCollector | MemoryLruGarbageCollector; +/** + * A garbage collector deletes documents whenever they are not part of any + * active queries, and have no local mutations attached to them. + * + * This collector tries to ensure lowest memory footprints from the SDK, + * at the risk of documents not being cached for offline queries or for + * direct queries to the cache. + * + * Use factory function {@link memoryEagerGarbageCollector()} to create an + * instance of this collector. + */ +export type MemoryEagerGarbageCollector = { + kind: 'memoryEager'; + /** + * @internal + */ + _offlineComponentProvider: OfflineComponentProviderFactory; +}; +/** + * A garbage collector deletes Least-Recently-Used documents in multiple + * batches. + * + * This collector is configured with a target size, and will only perform + * collection when the cached documents exceed the target size. It avoids + * querying backend repeated for the same query or document, at the risk + * of having a larger memory footprint. + * + * Use factory function {@link memoryLruGarbageCollector()} to create a + * instance of this collector. + */ +export type MemoryLruGarbageCollector = { + kind: 'memoryLru'; + /** + * @internal + */ + _offlineComponentProvider: OfflineComponentProviderFactory; +}; +/** + * Creates an instance of `MemoryEagerGarbageCollector`. This is also the + * default garbage collector unless it is explicitly specified otherwise. + */ +export declare function memoryEagerGarbageCollector(): MemoryEagerGarbageCollector; +/** + * Creates an instance of `MemoryLruGarbageCollector`. + * + * A target size can be specified as part of the setting parameter. The + * collector will start deleting documents once the cache size exceeds + * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes). + */ +export declare function memoryLruGarbageCollector(settings?: { + cacheSizeBytes?: number; +}): MemoryLruGarbageCollector; +/** + * An settings object to configure an `MemoryLocalCache` instance. + */ +export type MemoryCacheSettings = { + /** + * The garbage collector to use, for the memory cache layer. + * A `MemoryEagerGarbageCollector` is used when this is undefined. + */ + garbageCollector?: MemoryGarbageCollector; +}; +/** + * Creates an instance of `MemoryLocalCache`. The instance can be set to + * `FirestoreSettings.cache` to tell the SDK which cache layer to use. + */ +export declare function memoryLocalCache(settings?: MemoryCacheSettings): MemoryLocalCache; +/** + * An settings object to configure an `PersistentLocalCache` instance. + * + * Persistent cache cannot be used in a Node.js environment. + */ +export type PersistentCacheSettings = { + /** + * An approximate cache size threshold for the on-disk data. If the cache + * grows beyond this size, Firestore will start removing data that hasn't been + * recently used. The SDK does not guarantee that the cache will stay below + * that size, only that if the cache exceeds the given size, cleanup will be + * attempted. + * + * The default value is 40 MB. The threshold must be set to at least 1 MB, and + * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection. + */ + cacheSizeBytes?: number; + /** + * Specifies how multiple tabs/windows will be managed by the SDK. + */ + tabManager?: PersistentTabManager; +}; +/** + * Creates an instance of `PersistentLocalCache`. The instance can be set to + * `FirestoreSettings.cache` to tell the SDK which cache layer to use. + * + * Persistent cache cannot be used in a Node.js environment. + */ +export declare function persistentLocalCache(settings?: PersistentCacheSettings): PersistentLocalCache; +/** + * A tab manager supporting only one tab, no synchronization will be + * performed across tabs. + */ +export type PersistentSingleTabManager = { + kind: 'persistentSingleTab'; + /** + * @internal + */ + _initialize: (settings: Omit | undefined) => void; + /** + * @internal + */ + _onlineComponentProvider?: OnlineComponentProviderFactory; + /** + * @internal + */ + _offlineComponentProvider?: OfflineComponentProviderFactory; +}; +/** + * A tab manager supporting multiple tabs. SDK will synchronize queries and + * mutations done across all tabs using the SDK. + */ +export type PersistentMultipleTabManager = { + kind: 'PersistentMultipleTab'; + /** + * @internal + */ + _initialize: (settings: Omit) => void; + /** + * @internal + */ + _onlineComponentProvider?: OnlineComponentProviderFactory; + /** + * @internal + */ + _offlineComponentProvider?: OfflineComponentProviderFactory; +}; +/** + * A union of all available tab managers. + */ +export type PersistentTabManager = PersistentSingleTabManager | PersistentMultipleTabManager; +/** + * Type to configure an `PersistentSingleTabManager` instance. + */ +export type PersistentSingleTabManagerSettings = { + /** + * Whether to force-enable persistent (IndexedDB) cache for the client. This + * cannot be used with multi-tab synchronization and is primarily intended for + * use with Web Workers. Setting this to `true` will enable IndexedDB, but cause + * other tabs using IndexedDB cache to fail. + */ + forceOwnership?: boolean; +}; +/** + * Creates an instance of `PersistentSingleTabManager`. + * + * @param settings Configures the created tab manager. + */ +export declare function persistentSingleTabManager(settings: PersistentSingleTabManagerSettings | undefined): PersistentSingleTabManager; +/** + * Creates an instance of `PersistentMultipleTabManager`. + */ +export declare function persistentMultipleTabManager(): PersistentMultipleTabManager; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/credentials.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/credentials.d.ts new file mode 100644 index 0000000..98ed3c2 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/credentials.d.ts @@ -0,0 +1,222 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseApp } from '@firebase/app'; +import { AppCheckInternalComponentName } from '@firebase/app-check-interop-types'; +import { FirebaseAuthInternalName } from '@firebase/auth-interop-types'; +import { Provider } from '@firebase/component'; +import { User } from '../auth/user'; +import { AsyncQueue } from '../util/async_queue'; +/** + * @internal + */ +export type AuthTokenFactory = () => string; +/** + * @internal + */ +export interface FirstPartyCredentialsSettings { + ['type']: 'firstParty'; + ['sessionIndex']: string; + ['iamToken']: string | null; + ['authTokenFactory']: AuthTokenFactory | null; +} +export interface ProviderCredentialsSettings { + ['type']: 'provider'; + ['client']: CredentialsProvider; +} +/** Settings for private credentials */ +export type CredentialsSettings = FirstPartyCredentialsSettings | ProviderCredentialsSettings; +export type TokenType = 'OAuth' | 'FirstParty' | 'AppCheck'; +export interface Token { + /** Type of token. */ + type: TokenType; + /** + * The user with which the token is associated (used for persisting user + * state on disk, etc.). + * This will be null for Tokens of the type 'AppCheck'. + */ + user?: User; + /** Header values to set for this token */ + headers: Map; +} +export declare class OAuthToken implements Token { + user: User; + type: TokenType; + headers: Map; + constructor(value: string, user: User); +} +/** + * A Listener for credential change events. The listener should fetch a new + * token and may need to invalidate other state if the current user has also + * changed. + */ +export type CredentialChangeListener = (credential: T) => Promise; +/** + * Provides methods for getting the uid and token for the current user and + * listening for changes. + */ +export interface CredentialsProvider { + /** + * Starts the credentials provider and specifies a listener to be notified of + * credential changes (sign-in / sign-out, token changes). It is immediately + * called once with the initial user. + * + * The change listener is invoked on the provided AsyncQueue. + */ + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + /** Requests a token for the current user. */ + getToken(): Promise; + /** + * Marks the last retrieved token as invalid, making the next GetToken request + * force-refresh the token. + */ + invalidateToken(): void; + shutdown(): void; +} +/** + * A CredentialsProvider that always yields an empty token. + * @internal + */ +export declare class EmptyAuthCredentialsProvider implements CredentialsProvider { + getToken(): Promise; + invalidateToken(): void; + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + shutdown(): void; +} +/** + * A CredentialsProvider that always returns a constant token. Used for + * emulator token mocking. + */ +export declare class EmulatorAuthCredentialsProvider implements CredentialsProvider { + private token; + constructor(token: Token); + /** + * Stores the listener registered with setChangeListener() + * This isn't actually necessary since the UID never changes, but we use this + * to verify the listen contract is adhered to in tests. + */ + private changeListener; + getToken(): Promise; + invalidateToken(): void; + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + shutdown(): void; +} +/** Credential provider for the Lite SDK. */ +export declare class LiteAuthCredentialsProvider implements CredentialsProvider { + private auth; + constructor(authProvider: Provider); + getToken(): Promise; + invalidateToken(): void; + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + shutdown(): void; +} +export declare class FirebaseAuthCredentialsProvider implements CredentialsProvider { + private authProvider; + /** + * The auth token listener registered with FirebaseApp, retained here so we + * can unregister it. + */ + private tokenListener; + /** Tracks the current User. */ + private currentUser; + /** + * Counter used to detect if the token changed while a getToken request was + * outstanding. + */ + private tokenCounter; + private forceRefresh; + private auth; + constructor(authProvider: Provider); + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + getToken(): Promise; + invalidateToken(): void; + shutdown(): void; + private getUser; +} +export declare class FirstPartyToken implements Token { + private readonly sessionIndex; + private readonly iamToken; + private readonly authTokenFactory; + type: TokenType; + user: User; + private _headers; + constructor(sessionIndex: string, iamToken: string | null, authTokenFactory: AuthTokenFactory | null); + /** + * Gets an authorization token, using a provided factory function, or return + * null. + */ + private getAuthToken; + get headers(): Map; +} +export declare class FirstPartyAuthCredentialsProvider implements CredentialsProvider { + private sessionIndex; + private iamToken; + private authTokenFactory; + constructor(sessionIndex: string, iamToken: string | null, authTokenFactory: AuthTokenFactory | null); + getToken(): Promise; + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + shutdown(): void; + invalidateToken(): void; +} +export declare class AppCheckToken implements Token { + private value; + type: TokenType; + headers: Map; + constructor(value: string); +} +export declare class FirebaseAppCheckTokenProvider implements CredentialsProvider { + private appCheckProvider; + /** + * The AppCheck token listener registered with FirebaseApp, retained here so + * we can unregister it. + */ + private tokenListener; + private forceRefresh; + private appCheck; + private latestAppCheckToken; + private serverAppAppCheckToken; + constructor(app: FirebaseApp, appCheckProvider: Provider); + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + getToken(): Promise; + invalidateToken(): void; + shutdown(): void; +} +/** + * An AppCheck token provider that always yields an empty token. + * @internal + */ +export declare class EmptyAppCheckTokenProvider implements CredentialsProvider { + getToken(): Promise; + invalidateToken(): void; + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + shutdown(): void; +} +/** AppCheck token provider for the Lite SDK. */ +export declare class LiteAppCheckTokenProvider implements CredentialsProvider { + private appCheckProvider; + private appCheck; + private serverAppAppCheckToken; + constructor(app: FirebaseApp, appCheckProvider: Provider); + getToken(): Promise; + invalidateToken(): void; + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + shutdown(): void; +} +/** + * Builds a CredentialsProvider depending on the type of + * the credentials passed in. + */ +export declare function makeAuthCredentialsProvider(credentials?: CredentialsSettings): CredentialsProvider; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/database.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/database.d.ts new file mode 100644 index 0000000..8004dae --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/database.d.ts @@ -0,0 +1,279 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseApp } from '@firebase/app'; +import { User } from '../auth/user'; +import { OfflineComponentProviderFactory, OnlineComponentProviderFactory } from '../core/component_provider'; +import { DatabaseId } from '../core/database_info'; +import { FirestoreClient } from '../core/firestore_client'; +import { Firestore as LiteFirestore } from '../lite-api/database'; +import { Query } from '../lite-api/reference'; +import { AsyncQueue } from '../util/async_queue'; +import { LoadBundleTask } from './bundle'; +import { CredentialsProvider } from './credentials'; +import { FirestoreSettings, PersistenceSettings } from './settings'; +export { connectFirestoreEmulator, EmulatorMockTokenOptions } from '../lite-api/database'; +declare module '@firebase/component' { + interface NameServiceMapping { + 'firestore': Firestore; + } +} +/** + * Constant used to indicate the LRU garbage collection should be disabled. + * Set this value as the `cacheSizeBytes` on the settings passed to the + * {@link Firestore} instance. + */ +export declare const CACHE_SIZE_UNLIMITED = -1; +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ +export declare class Firestore extends LiteFirestore { + /** + * Whether it's a {@link Firestore} or Firestore Lite instance. + */ + type: 'firestore-lite' | 'firestore'; + _queue: AsyncQueue; + readonly _persistenceKey: string; + _firestoreClient: FirestoreClient | undefined; + _componentsProvider?: { + _offline: OfflineComponentProviderFactory; + _online: OnlineComponentProviderFactory; + }; + /** @hideconstructor */ + constructor(authCredentialsProvider: CredentialsProvider, appCheckCredentialsProvider: CredentialsProvider, databaseId: DatabaseId, app?: FirebaseApp); + protected _terminate(): Promise; +} +/** + * Initializes a new instance of {@link Firestore} with the provided settings. + * Can only be called before any other function, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will + * be associated. + * @param settings - A settings object to configure the {@link Firestore} instance. + * @param databaseId - The name of the database. + * @returns A newly initialized {@link Firestore} instance. + */ +export declare function initializeFirestore(app: FirebaseApp, settings: FirestoreSettings, databaseId?: string): Firestore; +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @returns The default {@link Firestore} instance of the default app. + */ +export declare function getFirestore(): Firestore; +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @returns The default {@link Firestore} instance of the provided app. + */ +export declare function getFirestore(app: FirebaseApp): Firestore; +/** + * Returns the existing named {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param databaseId - The name of the database. + * @returns The named {@link Firestore} instance of the default app. + * @beta + */ +export declare function getFirestore(databaseId: string): Firestore; +/** + * Returns the existing named {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @param databaseId - The name of the database. + * @returns The named {@link Firestore} instance of the provided app. + * @beta + */ +export declare function getFirestore(app: FirebaseApp, databaseId: string): Firestore; +/** + * @internal + */ +export declare function ensureFirestoreConfigured(firestore: Firestore): FirestoreClient; +export declare function configureFirestore(firestore: Firestore): void; +/** + * Attempts to enable persistent storage, if possible. + * + * On failure, `enableIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. + * + * * failed-precondition: The app is already open in another browser tab. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. + * + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. + * + * Note: `enableIndexedDbPersistence()` must be called before any other functions + * (other than {@link initializeFirestore}, {@link (getFirestore:1)} or + * {@link clearIndexedDbPersistence}. + * + * Persistence cannot be used in a Node.js environment. + * + * @param firestore - The {@link Firestore} instance to enable persistence for. + * @param persistenceSettings - Optional settings object to configure + * persistence. + * @returns A `Promise` that represents successfully enabling persistent storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on IndexedDb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. + */ +export declare function enableIndexedDbPersistence(firestore: Firestore, persistenceSettings?: PersistenceSettings): Promise; +/** + * Attempts to enable multi-tab persistent storage, if possible. If enabled + * across all tabs, all operations share access to local persistence, including + * shared execution of queries and latency-compensated local document updates + * across all connected instances. + * + * On failure, `enableMultiTabIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. + * + * * failed-precondition: The app is already open in another browser tab and + * multi-tab is not enabled. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. + * + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. + * + * @param firestore - The {@link Firestore} instance to enable persistence for. + * @returns A `Promise` that represents successfully enabling persistent + * storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on indexeddb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. + */ +export declare function enableMultiTabIndexedDbPersistence(firestore: Firestore): Promise; +/** + * Clears the persistent storage. This includes pending writes and cached + * documents. + * + * Must be called while the {@link Firestore} instance is not started (after the app is + * terminated or when the app is first initialized). On startup, this function + * must be called before other functions (other than {@link + * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore} + * instance is still running, the promise will be rejected with the error code + * of `failed-precondition`. + * + * Note: `clearIndexedDbPersistence()` is primarily intended to help write + * reliable tests that use Cloud Firestore. It uses an efficient mechanism for + * dropping existing data but does not attempt to securely overwrite or + * otherwise make cached data unrecoverable. For applications that are sensitive + * to the disclosure of cached data in between user sessions, we strongly + * recommend not enabling persistence at all. + * + * @param firestore - The {@link Firestore} instance to clear persistence for. + * @returns A `Promise` that is resolved when the persistent storage is + * cleared. Otherwise, the promise is rejected with an error. + */ +export declare function clearIndexedDbPersistence(firestore: Firestore): Promise; +/** + * Waits until all currently pending writes for the active user have been + * acknowledged by the backend. + * + * The returned promise resolves immediately if there are no outstanding writes. + * Otherwise, the promise waits for all previously issued writes (including + * those written in a previous app session), but it does not wait for writes + * that were added after the function is called. If you want to wait for + * additional writes, call `waitForPendingWrites()` again. + * + * Any outstanding `waitForPendingWrites()` promises are rejected during user + * changes. + * + * @returns A `Promise` which resolves when all currently pending writes have been + * acknowledged by the backend. + */ +export declare function waitForPendingWrites(firestore: Firestore): Promise; +/** + * Re-enables use of the network for this {@link Firestore} instance after a prior + * call to {@link disableNetwork}. + * + * @returns A `Promise` that is resolved once the network has been enabled. + */ +export declare function enableNetwork(firestore: Firestore): Promise; +/** + * Disables network usage for this instance. It can be re-enabled via {@link + * enableNetwork}. While the network is disabled, any snapshot listeners, + * `getDoc()` or `getDocs()` calls will return results from cache, and any write + * operations will be queued until the network is restored. + * + * @returns A `Promise` that is resolved once the network has been disabled. + */ +export declare function disableNetwork(firestore: Firestore): Promise; +/** + * Terminates the provided {@link Firestore} instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` function + * may be used. Any other function will throw a `FirestoreError`. + * + * To restart after termination, create a new instance of FirebaseFirestore with + * {@link (getFirestore:1)}. + * + * Termination does not cancel any pending writes, and any promises that are + * awaiting a response from the server will not be resolved. If you have + * persistence enabled, the next time you start this instance, it will resume + * sending these writes to the server. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all + * of its resources or in combination with `clearIndexedDbPersistence()` to + * ensure that all local state is destroyed between test runs. + * + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ +export declare function terminate(firestore: Firestore): Promise; +/** + * Loads a Firestore bundle into the local cache. + * + * @param firestore - The {@link Firestore} instance to load bundles for. + * @param bundleData - An object representing the bundle to be loaded. Valid + * objects are `ArrayBuffer`, `ReadableStream` or `string`. + * + * @returns A `LoadBundleTask` object, which notifies callers with progress + * updates, and completion or error events. It can be used as a + * `Promise`. + */ +export declare function loadBundle(firestore: Firestore, bundleData: ReadableStream | ArrayBuffer | string): LoadBundleTask; +/** + * Reads a Firestore {@link Query} from local cache, identified by the given + * name. + * + * The named queries are packaged into bundles on the server side (along + * with resulting documents), and loaded to local cache using `loadBundle`. Once + * in local cache, use this method to extract a {@link Query} by name. + * + * @param firestore - The {@link Firestore} instance to read the query from. + * @param name - The name of the query. + * @returns A `Promise` that is resolved with the Query or `null`. + */ +export declare function namedQuery(firestore: Firestore, name: string): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/field_path.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/field_path.d.ts new file mode 100644 index 0000000..7e463e5 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/field_path.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { FieldPath, documentId } from '../lite-api/field_path'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/field_value.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/field_value.d.ts new file mode 100644 index 0000000..eded0bc --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/field_value.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { FieldValue } from '../lite-api/field_value'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/field_value_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/field_value_impl.d.ts new file mode 100644 index 0000000..aac67c3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/field_value_impl.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { increment, arrayRemove, arrayUnion, serverTimestamp, deleteField, vector } from '../lite-api/field_value_impl'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/filter.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/filter.d.ts new file mode 100644 index 0000000..1dee60b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/filter.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { and, endAt, endBefore, startAfter, startAt, limitToLast, limit, or, orderBy, OrderByDirection, where, WhereFilterOp, query, QueryCompositeFilterConstraint, QueryConstraint, QueryConstraintType, QueryFilterConstraint, QueryFieldFilterConstraint, QueryOrderByConstraint, QueryLimitConstraint, QueryStartAtConstraint, QueryEndAtConstraint, QueryNonFilterConstraint } from '../lite-api/query'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/geo_point.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/geo_point.d.ts new file mode 100644 index 0000000..b14def6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/geo_point.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { GeoPoint } from '../lite-api/geo_point'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/index_configuration.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/index_configuration.d.ts new file mode 100644 index 0000000..8b10775 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/index_configuration.d.ts @@ -0,0 +1,139 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FieldIndex } from '../model/field_index'; +import { Firestore } from './database'; +export { connectFirestoreEmulator, EmulatorMockTokenOptions } from '../lite-api/database'; +/** + * A single field element in an index configuration. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export interface IndexField { + /** The field path to index. */ + readonly fieldPath: string; + /** + * What type of array index to create. Set to `CONTAINS` for `array-contains` + * and `array-contains-any` indexes. + * + * Only one of `arrayConfig` or `order` should be set; + */ + readonly arrayConfig?: 'CONTAINS'; + /** + * What type of array index to create. Set to `ASCENDING` or 'DESCENDING` for + * `==`, `!=`, `<=`, `<=`, `in` and `not-in` filters. + * + * Only one of `arrayConfig` or `order` should be set. + */ + readonly order?: 'ASCENDING' | 'DESCENDING'; + [key: string]: unknown; +} +/** + * The SDK definition of a Firestore index. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export interface Index { + /** The ID of the collection to index. */ + readonly collectionGroup: string; + /** A list of fields to index. */ + readonly fields?: IndexField[]; + [key: string]: unknown; +} +/** + * A list of Firestore indexes to speed up local query execution. + * + * See {@link https://firebase.google.com/docs/reference/firestore/indexes/#json_format | JSON Format} + * for a description of the format of the index definition. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export interface IndexConfiguration { + /** A list of all Firestore indexes. */ + readonly indexes?: Index[]; + [key: string]: unknown; +} +/** + * Configures indexing for local query execution. Any previous index + * configuration is overridden. The `Promise` resolves once the index + * configuration has been persisted. + * + * The index entries themselves are created asynchronously. You can continue to + * use queries that require indexing even if the indices are not yet available. + * Query execution will automatically start using the index once the index + * entries have been written. + * + * Indexes are only supported with IndexedDb persistence. If IndexedDb is not + * enabled, any index configuration is ignored. + * + * @param firestore - The {@link Firestore} instance to configure indexes for. + * @param configuration -The index definition. + * @throws FirestoreError if the JSON format is invalid. + * @returns A `Promise` that resolves once all indices are successfully + * configured. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare function setIndexConfiguration(firestore: Firestore, configuration: IndexConfiguration): Promise; +/** + * Configures indexing for local query execution. Any previous index + * configuration is overridden. The `Promise` resolves once the index + * configuration has been persisted. + * + * The index entries themselves are created asynchronously. You can continue to + * use queries that require indexing even if the indices are not yet available. + * Query execution will automatically start using the index once the index + * entries have been written. + * + * Indexes are only supported with IndexedDb persistence. Invoke either + * `enableIndexedDbPersistence()` or `enableMultiTabIndexedDbPersistence()` + * before setting an index configuration. If IndexedDb is not enabled, any + * index configuration is ignored. + * + * The method accepts the JSON format exported by the Firebase CLI (`firebase + * firestore:indexes`). If the JSON format is invalid, this method throws an + * error. + * + * @param firestore - The {@link Firestore} instance to configure indexes for. + * @param json -The JSON format exported by the Firebase CLI. + * @throws FirestoreError if the JSON format is invalid. + * @returns A `Promise` that resolves once all indices are successfully + * configured. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare function setIndexConfiguration(firestore: Firestore, json: string): Promise; +export declare function parseIndexes(jsonOrConfiguration: string | IndexConfiguration): FieldIndex[]; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/long_polling_options.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/long_polling_options.d.ts new file mode 100644 index 0000000..0088194 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/long_polling_options.d.ts @@ -0,0 +1,55 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options that configure the SDK’s underlying network transport (WebChannel) + * when long-polling is used. + * + * Note: This interface is "experimental" and is subject to change. + * + * See `FirestoreSettings.experimentalAutoDetectLongPolling`, + * `FirestoreSettings.experimentalForceLongPolling`, and + * `FirestoreSettings.experimentalLongPollingOptions`. + */ +export interface ExperimentalLongPollingOptions { + /** + * The desired maximum timeout interval, in seconds, to complete a + * long-polling GET response. Valid values are between 5 and 30, inclusive. + * Floating point values are allowed and will be rounded to the nearest + * millisecond. + * + * By default, when long-polling is used the "hanging GET" request sent by + * the client times out after 30 seconds. To request a different timeout + * from the server, set this setting with the desired timeout. + * + * Changing the default timeout may be useful, for example, if the buffering + * proxy that necessitated enabling long-polling in the first place has a + * shorter timeout for hanging GET requests, in which case setting the + * long-polling timeout to a shorter value, such as 25 seconds, may fix + * prematurely-closed hanging GET requests. + * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987. + */ + timeoutSeconds?: number; +} +/** + * Compares two `ExperimentalLongPollingOptions` objects for equality. + */ +export declare function longPollingOptionsEqual(options1: ExperimentalLongPollingOptions, options2: ExperimentalLongPollingOptions): boolean; +/** + * Creates and returns a new `ExperimentalLongPollingOptions` with the same + * option values as the given instance. + */ +export declare function cloneLongPollingOptions(options: ExperimentalLongPollingOptions): ExperimentalLongPollingOptions; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/observer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/observer.d.ts new file mode 100644 index 0000000..1aa4b85 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/observer.d.ts @@ -0,0 +1,29 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirestoreError } from '../util/error'; +/** + * Observer/Subscribe interfaces. + */ +export type NextFn = (value: T) => void; +export type ErrorFn = (error: FirestoreError) => void; +export type CompleteFn = () => void; +export interface PartialObserver { + next?: NextFn; + error?: ErrorFn; + complete?: CompleteFn; +} +export declare function isPartialObserver(obj: unknown): obj is PartialObserver; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/parse_context.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/parse_context.d.ts new file mode 100644 index 0000000..d2b0beb --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/parse_context.d.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseId } from '../core/database_info'; +export interface ParseContext { + readonly databaseId: DatabaseId; + readonly ignoreUndefinedProperties: boolean; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/persistent_cache_index_manager.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/persistent_cache_index_manager.d.ts new file mode 100644 index 0000000..c6e4b46 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/persistent_cache_index_manager.d.ts @@ -0,0 +1,59 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Firestore } from './database'; +/** + * A `PersistentCacheIndexManager` for configuring persistent cache indexes used + * for local query execution. + * + * To use, call `getPersistentCacheIndexManager()` to get an instance. + */ +export declare class PersistentCacheIndexManager { + readonly _firestore: Firestore; + /** A type string to uniquely identify instances of this class. */ + readonly type: 'PersistentCacheIndexManager'; + /** @hideconstructor */ + constructor(_firestore: Firestore); +} +/** + * Returns the PersistentCache Index Manager used by the given `Firestore` + * object. + * + * @return The `PersistentCacheIndexManager` instance, or `null` if local + * persistent storage is not in use. + */ +export declare function getPersistentCacheIndexManager(firestore: Firestore): PersistentCacheIndexManager | null; +/** + * Enables the SDK to create persistent cache indexes automatically for local + * query execution when the SDK believes cache indexes can help improve + * performance. + * + * This feature is disabled by default. + */ +export declare function enablePersistentCacheIndexAutoCreation(indexManager: PersistentCacheIndexManager): void; +/** + * Stops creating persistent cache indexes automatically for local query + * execution. The indexes which have been created by calling + * `enablePersistentCacheIndexAutoCreation()` still take effect. + */ +export declare function disablePersistentCacheIndexAutoCreation(indexManager: PersistentCacheIndexManager): void; +/** + * Removes all persistent cache indexes. + * + * Please note this function will also deletes indexes generated by + * `setIndexConfiguration()`, which is deprecated. + */ +export declare function deleteAllPersistentCacheIndexes(indexManager: PersistentCacheIndexManager): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/reference.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/reference.d.ts new file mode 100644 index 0000000..0e38648 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/reference.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { DocumentReference, CollectionReference, Query, collection, collectionGroup, doc, queryEqual, SetOptions, DocumentData, UpdateData, WithFieldValue, PartialWithFieldValue, refEqual } from '../lite-api/reference'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/reference_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/reference_impl.d.ts new file mode 100644 index 0000000..5dd95e6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/reference_impl.d.ts @@ -0,0 +1,536 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Bytes } from '../lite-api/bytes'; +import { FieldPath } from '../lite-api/field_path'; +import { CollectionReference, DocumentData, DocumentReference, PartialWithFieldValue, Query, SetOptions, UpdateData, WithFieldValue } from '../lite-api/reference'; +import { AbstractUserDataWriter } from '../lite-api/user_data_writer'; +import { Mutation } from '../model/mutation'; +import { ByteString } from '../util/byte_string'; +import { FirestoreError } from '../util/error'; +import { Firestore } from './database'; +import { DocumentSnapshot, FirestoreDataConverter, QuerySnapshot } from './snapshot'; +/** + * An options object that can be passed to {@link (onSnapshot:1)} and {@link + * QuerySnapshot.docChanges} to control which types of changes to include in the + * result set. + */ +export interface SnapshotListenOptions { + /** + * Include a change even if only the metadata of the query or of a document + * changed. Default is false. + */ + readonly includeMetadataChanges?: boolean; + /** + * Set the source the query listens to. Default to "default", which + * listens to both cache and server. + */ + readonly source?: ListenSource; +} +/** + * Describe the source a query listens to. + * + * Set to `default` to listen to both cache and server changes. Set to `cache` + * to listen to changes in cache only. + */ +export type ListenSource = 'default' | 'cache'; +/** + * Reads the document referred to by this `DocumentReference`. + * + * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting + * for data from the server, but it may return cached data or fail if you are + * offline and the server cannot be reached. To specify this behavior, invoke + * {@link getDocFromCache} or {@link getDocFromServer}. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +export declare function getDoc(reference: DocumentReference): Promise>; +export declare class ExpUserDataWriter extends AbstractUserDataWriter { + protected firestore: Firestore; + constructor(firestore: Firestore); + protected convertBytes(bytes: ByteString): Bytes; + protected convertReference(name: string): DocumentReference; +} +/** + * Reads the document referred to by this `DocumentReference` from cache. + * Returns an error if the document is not currently cached. + * + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +export declare function getDocFromCache(reference: DocumentReference): Promise>; +/** + * Reads the document referred to by this `DocumentReference` from the server. + * Returns an error if the network is not available. + * + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +export declare function getDocFromServer(reference: DocumentReference): Promise>; +/** + * Executes the query and returns the results as a `QuerySnapshot`. + * + * Note: `getDocs()` attempts to provide up-to-date data when possible by + * waiting for data from the server, but it may return cached data or fail if + * you are offline and the server cannot be reached. To specify this behavior, + * invoke {@link getDocsFromCache} or {@link getDocsFromServer}. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +export declare function getDocs(query: Query): Promise>; +/** + * Executes the query and returns the results as a `QuerySnapshot` from cache. + * Returns an empty result set if no documents matching the query are currently + * cached. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +export declare function getDocsFromCache(query: Query): Promise>; +/** + * Executes the query and returns the results as a `QuerySnapshot` from the + * server. Returns an error if the network is not available. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +export declare function getDocsFromServer(query: Query): Promise>; +/** + * Writes to the document referred to by this `DocumentReference`. If the + * document does not yet exist, it will be created. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +export declare function setDoc(reference: DocumentReference, data: WithFieldValue): Promise; +/** + * Writes to the document referred to by the specified `DocumentReference`. If + * the document does not yet exist, it will be created. If you provide `merge` + * or `mergeFields`, the provided data can be merged into an existing document. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @returns A Promise resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +export declare function setDoc(reference: DocumentReference, data: PartialWithFieldValue, options: SetOptions): Promise; +/** + * Updates fields in the document referred to by the specified + * `DocumentReference`. The update will fail if applied to a document that does + * not exist. + * + * @param reference - A reference to the document to update. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +export declare function updateDoc(reference: DocumentReference, data: UpdateData): Promise; +/** + * Updates fields in the document referred to by the specified + * `DocumentReference` The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * @param reference - A reference to the document to update. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +export declare function updateDoc(reference: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): Promise; +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * @param reference - A reference to the document to delete. + * @returns A Promise resolved once the document has been successfully + * deleted from the backend (note that it won't resolve while you're offline). + */ +export declare function deleteDoc(reference: DocumentReference): Promise; +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend (Note that it + * won't resolve while you're offline). + */ +export declare function addDoc(reference: CollectionReference, data: WithFieldValue): Promise>; +/** + * A function returned by `onSnapshot()` that removes the listener when invoked. + */ +export interface Unsubscribe { + /** Removes the listener when invoked. */ + (): void; +} +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshot(reference: DocumentReference, observer: { + next?: (snapshot: DocumentSnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshot(reference: DocumentReference, options: SnapshotListenOptions, observer: { + next?: (snapshot: DocumentSnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(reference: DocumentReference, onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param options - Options controlling the listen behavior. + * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(reference: DocumentReference, options: SnapshotListenOptions, onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The + * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(query: Query, observer: { + next?: (snapshot: QuerySnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The + * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(query: Query, options: SnapshotListenOptions, observer: { + next?: (snapshot: QuerySnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The + * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(query: Query, onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The + * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param options - Options controlling the listen behavior. + * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(query: Query, options: SnapshotListenOptions, onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events based on data generated by invoking + * {@link QuerySnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. + * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking + * {@link DocumentSnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. + * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are + * never ending. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events based on data generated by invoking + * {@link QuerySnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, options: SnapshotListenOptions, onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking + * {@link DocumentSnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks + * or pass a single observer object with `next` and `error` callbacks. The listener can be cancelled + * by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, options: SnapshotListenOptions, onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events based on QuerySnapshot data generated by invoking + * {@link QuerySnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, observer: { + next: (snapshot: QuerySnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking + * {@link DocumentSnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks + * or pass a single observer object with `next` and `error` callbacks. The listener can be cancelled + * by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, observer: { + next: (snapshot: DocumentSnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events based on QuerySnapshot data generated by invoking + * {@link QuerySnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, options: SnapshotListenOptions, observer: { + next: (snapshot: QuerySnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events based on QuerySnapshot data generated by + * invoking {@link DocumentSnapshot.toJSON} You may either pass individual `onNext` and `onError` + * callbacks or pass a single observer object with `next` and `error` callbacks. The listener can be + * cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, options: SnapshotListenOptions, observer: { + next: (snapshot: DocumentSnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync + * event indicates that all listeners affected by a given change have fired, + * even if a single server-generated change affects multiple listeners. + * + * NOTE: The snapshots-in-sync event only indicates that listeners are in sync + * with each other, but does not relate to whether those snapshots are in sync + * with the server. Use SnapshotMetadata in the individual listeners to + * determine if a snapshot is from the cache or the server. + * + * @param firestore - The instance of Firestore for synchronizing snapshots. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel the snapshot + * listener. + */ +export declare function onSnapshotsInSync(firestore: Firestore, observer: { + next?: (value: void) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}): Unsubscribe; +/** + * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync + * event indicates that all listeners affected by a given change have fired, + * even if a single server-generated change affects multiple listeners. + * + * NOTE: The snapshots-in-sync event only indicates that listeners are in sync + * with each other, but does not relate to whether those snapshots are in sync + * with the server. Use `SnapshotMetadata` in the individual listeners to + * determine if a snapshot is from the cache or the server. + * + * @param firestore - The `Firestore` instance for synchronizing snapshots. + * @param onSync - A callback to be called every time all snapshot listeners are + * in sync with each other. + * @returns An unsubscribe function that can be called to cancel the snapshot + * listener. + */ +export declare function onSnapshotsInSync(firestore: Firestore, onSync: () => void): Unsubscribe; +/** + * Locally writes `mutations` on the async queue. + * @internal + */ +export declare function executeWrite(firestore: Firestore, mutations: Mutation[]): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/settings.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/settings.d.ts new file mode 100644 index 0000000..8565811 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/settings.d.ts @@ -0,0 +1,108 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirestoreSettings as LiteSettings } from '../lite-api/settings'; +import { FirestoreLocalCache } from './cache_config'; +import { ExperimentalLongPollingOptions } from './long_polling_options'; +export { DEFAULT_HOST } from '../lite-api/settings'; +/** + * Settings that can be passed to `enableIndexedDbPersistence()` to configure + * Firestore persistence. + * + * Persistence cannot be used in a Node.js environment. + */ +export interface PersistenceSettings { + /** + * Whether to force enable persistence for the client. This cannot be used + * with multi-tab synchronization and is primarily intended for use with Web + * Workers. Setting this to `true` will enable persistence, but cause other + * tabs using persistence to fail. + */ + forceOwnership?: boolean; +} +/** + * Specifies custom configurations for your Cloud Firestore instance. + * You must set these before invoking any other methods. + */ +export interface FirestoreSettings extends LiteSettings { + /** + * NOTE: This field will be deprecated in a future major release. Use `cache` field + * instead to specify cache size, and other cache configurations. + * + * An approximate cache size threshold for the on-disk data. If the cache + * grows beyond this size, Firestore will start removing data that hasn't been + * recently used. The size is not a guarantee that the cache will stay below + * that size, only that if the cache exceeds the given size, cleanup will be + * attempted. + * + * The default value is 40 MB. The threshold must be set to at least 1 MB, and + * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection. + */ + cacheSizeBytes?: number; + /** + * Specifies the cache used by the SDK. Available options are `MemoryLocalCache` + * and `PersistentLocalCache`, each with different configuration options. + * + * When unspecified, `MemoryLocalCache` will be used by default. + * + * NOTE: setting this field and `cacheSizeBytes` at the same time will throw + * exception during SDK initialization. Instead, using the configuration in + * the `FirestoreLocalCache` object to specify the cache size. + */ + localCache?: FirestoreLocalCache; + /** + * Forces the SDK’s underlying network transport (WebChannel) to use + * long-polling. Each response from the backend will be closed immediately + * after the backend sends data (by default responses are kept open in + * case the backend has more data to send). This avoids incompatibility + * issues with certain proxies, antivirus software, etc. that incorrectly + * buffer traffic indefinitely. Use of this option will cause some + * performance degradation though. + * + * This setting cannot be used with `experimentalAutoDetectLongPolling` and + * may be removed in a future release. If you find yourself using it to + * work around a specific network reliability issue, please tell us about + * it in https://github.com/firebase/firebase-js-sdk/issues/1674. + * + * This setting cannot be used in a Node.js environment. + */ + experimentalForceLongPolling?: boolean; + /** + * Configures the SDK's underlying transport (WebChannel) to automatically + * detect if long-polling should be used. This is very similar to + * `experimentalForceLongPolling`, but only uses long-polling if required. + * + * After having had a default value of `false` since its inception in 2019, + * the default value of this setting was changed in May 2023 to `true` in + * v9.22.0 of the Firebase JavaScript SDK. That is, auto-detection of long + * polling is now enabled by default. To disable it, set this setting to + * `false`, and please open a GitHub issue to share the problems that + * motivated you disabling long-polling auto-detection. + * + * This setting cannot be used in a Node.js environment. + */ + experimentalAutoDetectLongPolling?: boolean; + /** + * Options that configure the SDK’s underlying network transport (WebChannel) + * when long-polling is used. + * + * These options are only used if `experimentalForceLongPolling` is true or if + * `experimentalAutoDetectLongPolling` is true and the auto-detection + * determined that long-polling was needed. Otherwise, these options have no + * effect. + */ + experimentalLongPollingOptions?: ExperimentalLongPollingOptions; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/snapshot.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/snapshot.d.ts new file mode 100644 index 0000000..24d863e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/snapshot.d.ts @@ -0,0 +1,550 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ChangeType, ViewSnapshot } from '../core/view_snapshot'; +import { FieldPath } from '../lite-api/field_path'; +import { DocumentData, PartialWithFieldValue, Query, SetOptions, WithFieldValue } from '../lite-api/reference'; +import { DocumentSnapshot as LiteDocumentSnapshot, FirestoreDataConverter as LiteFirestoreDataConverter } from '../lite-api/snapshot'; +import { UntypedFirestoreDataConverter } from '../lite-api/user_data_reader'; +import { AbstractUserDataWriter } from '../lite-api/user_data_writer'; +import { Document } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { Property } from '../util/json_validation'; +import { Firestore } from './database'; +import { SnapshotListenOptions } from './reference_impl'; +/** + * Converter used by `withConverter()` to transform user objects of type + * `AppModelType` into Firestore data of type `DbModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * In this context, an "AppModel" is a class that is used in an application to + * package together related information and functionality. Such a class could, + * for example, have properties with complex, nested data types, properties used + * for memoization, properties of types not supported by Firestore (such as + * `symbol` and `bigint`), and helper functions that perform compound + * operations. Such classes are not suitable and/or possible to store into a + * Firestore database. Instead, instances of such classes need to be converted + * to "plain old JavaScript objects" (POJOs) with exclusively primitive + * properties, potentially nested inside other POJOs or arrays of POJOs. In this + * context, this type is referred to as the "DbModel" and would be an object + * suitable for persisting into Firestore. For convenience, applications can + * implement `FirestoreDataConverter` and register the converter with Firestore + * objects, such as `DocumentReference` or `Query`, to automatically convert + * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel` + * to `AppModel` when retrieving from Firestore. + * + * @example + * + * Simple Example + * + * ```typescript + * const numberConverter = { + * toFirestore(value: WithFieldValue) { + * return { value }; + * }, + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) { + * return snapshot.data(options).value as number; + * } + * }; + * + * async function simpleDemo(db: Firestore): Promise { + * const documentRef = doc(db, 'values/value123').withConverter(numberConverter); + * + * // converters are used with `setDoc`, `addDoc`, and `getDoc` + * await setDoc(documentRef, 42); + * const snapshot1 = await getDoc(documentRef); + * assertEqual(snapshot1.data(), 42); + * + * // converters are not used when writing data with `updateDoc` + * await updateDoc(documentRef, { value: 999 }); + * const snapshot2 = await getDoc(documentRef); + * assertEqual(snapshot2.data(), 999); + * } + * ``` + * + * Advanced Example + * + * ```typescript + * // The Post class is a model that is used by our application. + * // This class may have properties and methods that are specific + * // to our application execution, which do not need to be persisted + * // to Firestore. + * class Post { + * constructor( + * readonly title: string, + * readonly author: string, + * readonly lastUpdatedMillis: number + * ) {} + * toString(): string { + * return `${this.title} by ${this.author}`; + * } + * } + * + * // The PostDbModel represents how we want our posts to be stored + * // in Firestore. This DbModel has different properties (`ttl`, + * // `aut`, and `lut`) from the Post class we use in our application. + * interface PostDbModel { + * ttl: string; + * aut: { firstName: string; lastName: string }; + * lut: Timestamp; + * } + * + * // The `PostConverter` implements `FirestoreDataConverter` and specifies + * // how the Firestore SDK can convert `Post` objects to `PostDbModel` + * // objects and vice versa. + * class PostConverter implements FirestoreDataConverter { + * toFirestore(post: WithFieldValue): WithFieldValue { + * return { + * ttl: post.title, + * aut: this._autFromAuthor(post.author), + * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis) + * }; + * } + * + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post { + * const data = snapshot.data(options) as PostDbModel; + * const author = `${data.aut.firstName} ${data.aut.lastName}`; + * return new Post(data.ttl, author, data.lut.toMillis()); + * } + * + * _autFromAuthor( + * author: string | FieldValue + * ): { firstName: string; lastName: string } | FieldValue { + * if (typeof author !== 'string') { + * // `author` is a FieldValue, so just return it. + * return author; + * } + * const [firstName, lastName] = author.split(' '); + * return {firstName, lastName}; + * } + * + * _lutFromLastUpdatedMillis( + * lastUpdatedMillis: number | FieldValue + * ): Timestamp | FieldValue { + * if (typeof lastUpdatedMillis !== 'number') { + * // `lastUpdatedMillis` must be a FieldValue, so just return it. + * return lastUpdatedMillis; + * } + * return Timestamp.fromMillis(lastUpdatedMillis); + * } + * } + * + * async function advancedDemo(db: Firestore): Promise { + * // Create a `DocumentReference` with a `FirestoreDataConverter`. + * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter()); + * + * // The `data` argument specified to `setDoc()` is type checked by the + * // TypeScript compiler to be compatible with `Post`. Since the `data` + * // argument is typed as `WithFieldValue` rather than just `Post`, + * // this allows properties of the `data` argument to also be special + * // Firestore values that perform server-side mutations, such as + * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`. + * await setDoc(documentRef, { + * title: 'My Life', + * author: 'Foo Bar', + * lastUpdatedMillis: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `setDoc()` is _not_ compatible with `WithFieldValue`. This + * // type checking prevents the caller from specifying objects with incorrect + * // properties or property values. + * // @ts-expect-error "Argument of type { ttl: string; } is not assignable + * // to parameter of type WithFieldValue" + * await setDoc(documentRef, { ttl: 'The Title' }); + * + * // When retrieving a document with `getDoc()` the `DocumentSnapshot` + * // object's `data()` method returns a `Post`, rather than a generic object, + * // which would have been returned if the `DocumentReference` did _not_ have a + * // `FirestoreDataConverter` attached to it. + * const snapshot1: DocumentSnapshot = await getDoc(documentRef); + * const post1: Post = snapshot1.data()!; + * if (post1) { + * assertEqual(post1.title, 'My Life'); + * assertEqual(post1.author, 'Foo Bar'); + * } + * + * // The `data` argument specified to `updateDoc()` is type checked by the + * // TypeScript compiler to be compatible with `PostDbModel`. Note that + * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`, + * // the `data` argument to `updateDoc()` must be compatible with + * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed + * // as `WithFieldValue` rather than just `PostDbModel`, this + * // allows properties of the `data` argument to also be those special + * // Firestore values, like `arrayRemove()`, `deleteField()`, and + * // `serverTimestamp()`. + * await updateDoc(documentRef, { + * 'aut.firstName': 'NewFirstName', + * lut: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `updateDoc()` is _not_ compatible with `WithFieldValue`. + * // This type checking prevents the caller from specifying objects with + * // incorrect properties or property values. + * // @ts-expect-error "Argument of type { title: string; } is not assignable + * // to parameter of type WithFieldValue" + * await updateDoc(documentRef, { title: 'New Title' }); + * const snapshot2: DocumentSnapshot = await getDoc(documentRef); + * const post2: Post = snapshot2.data()!; + * if (post2) { + * assertEqual(post2.title, 'My Life'); + * assertEqual(post2.author, 'NewFirstName Bar'); + * } + * } + * ``` + */ +export interface FirestoreDataConverter extends LiteFirestoreDataConverter { + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. To use `set()` + * with `merge` and `mergeFields`, `toFirestore()` must be defined with + * `PartialWithFieldValue`. + * + * The `WithFieldValue` type extends `T` to also allow FieldValues such as + * {@link (deleteField:1)} to be used as property values. + */ + toFirestore(modelObject: WithFieldValue): WithFieldValue; + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link (setDoc:1)}, {@link (WriteBatch.set:1)} and + * {@link (Transaction.set:1)} with `merge:true` or `mergeFields`. + * + * The `PartialWithFieldValue` type extends `Partial` to allow + * FieldValues such as {@link (arrayUnion:1)} to be used as property values. + * It also supports nested `Partial` by allowing nested fields to be + * omitted. + */ + toFirestore(modelObject: PartialWithFieldValue, options: SetOptions): PartialWithFieldValue; + /** + * Called by the Firestore SDK to convert Firestore data into an object of + * type `AppModelType`. You can access your data by calling: + * `snapshot.data(options)`. + * + * Generally, the data returned from `snapshot.data()` can be cast to + * `DbModelType`; however, this is not guaranteed because Firestore does not + * enforce a schema on the database. For example, writes from a previous + * version of the application or writes from another client that did not use a + * type converter could have written data with different properties and/or + * property types. The implementation will need to choose whether to + * gracefully recover from non-conforming data or throw an error. + * + * To override this method, see {@link (FirestoreDataConverter.fromFirestore:1)}. + * + * @param snapshot - A `QueryDocumentSnapshot` containing your data and metadata. + * @param options - The `SnapshotOptions` from the initial call to `data()`. + */ + fromFirestore(snapshot: QueryDocumentSnapshot, options?: SnapshotOptions): AppModelType; +} +/** + * Options that configure how data is retrieved from a `DocumentSnapshot` (for + * example the desired behavior for server timestamps that have not yet been set + * to their final value). + */ +export interface SnapshotOptions { + /** + * If set, controls the return value for server timestamps that have not yet + * been set to their final value. + * + * By specifying 'estimate', pending server timestamps return an estimate + * based on the local clock. This estimate will differ from the final value + * and cause these values to change once the server result becomes available. + * + * By specifying 'previous', pending timestamps will be ignored and return + * their previous value instead. + * + * If omitted or set to 'none', `null` will be returned by default until the + * server value becomes available. + */ + readonly serverTimestamps?: 'estimate' | 'previous' | 'none'; +} +/** + * Metadata about a snapshot, describing the state of the snapshot. + */ +export declare class SnapshotMetadata { + /** + * True if the snapshot contains the result of local writes (for example + * `set()` or `update()` calls) that have not yet been committed to the + * backend. If your listener has opted into metadata updates (via + * `SnapshotListenOptions`) you will receive another snapshot with + * `hasPendingWrites` equal to false once the writes have been committed to + * the backend. + */ + readonly hasPendingWrites: boolean; + /** + * True if the snapshot was created from cached data rather than guaranteed + * up-to-date server data. If your listener has opted into metadata updates + * (via `SnapshotListenOptions`) you will receive another snapshot with + * `fromCache` set to false once the client has received up-to-date data from + * the backend. + */ + readonly fromCache: boolean; + /** @hideconstructor */ + constructor(hasPendingWrites: boolean, fromCache: boolean); + /** + * Returns true if this `SnapshotMetadata` is equal to the provided one. + * + * @param other - The `SnapshotMetadata` to compare against. + * @returns true if this `SnapshotMetadata` is equal to the provided one. + */ + isEqual(other: SnapshotMetadata): boolean; +} +/** + * The type of a `DocumentChange` may be 'added', 'removed', or 'modified'. + */ +export type DocumentChangeType = 'added' | 'removed' | 'modified'; +/** + * A `DocumentChange` represents a change to the documents matching a query. + * It contains the document affected and the type of change that occurred. + */ +export interface DocumentChange { + /** The type of change ('added', 'modified', or 'removed'). */ + readonly type: DocumentChangeType; + /** The document affected by this change. */ + readonly doc: QueryDocumentSnapshot; + /** + * The index of the changed document in the result set immediately prior to + * this `DocumentChange` (i.e. supposing that all prior `DocumentChange` objects + * have been applied). Is `-1` for 'added' events. + */ + readonly oldIndex: number; + /** + * The index of the changed document in the result set immediately after + * this `DocumentChange` (i.e. supposing that all prior `DocumentChange` + * objects and the current `DocumentChange` object have been applied). + * Is -1 for 'removed' events. + */ + readonly newIndex: number; +} +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ +export declare class DocumentSnapshot extends LiteDocumentSnapshot { + readonly _firestore: Firestore; + private readonly _firestoreImpl; + /** + * Metadata about the `DocumentSnapshot`, including information about its + * source and local modifications. + */ + readonly metadata: SnapshotMetadata; + /** @hideconstructor protected */ + constructor(_firestore: Firestore, userDataWriter: AbstractUserDataWriter, key: DocumentKey, document: Document | null, metadata: SnapshotMetadata, converter: UntypedFirestoreDataConverter | null); + /** + * Returns whether or not the data exists. True if the document exists. + */ + exists(): this is QueryDocumentSnapshot; + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * By default, `serverTimestamp()` values that have not yet been + * set to their final value will be returned as `null`. You can override + * this by passing an options object. + * + * @param options - An options object to configure how data is retrieved from + * the snapshot (for example the desired behavior for server timestamps that + * have not yet been set to their final value). + * @returns An `Object` containing all fields in the document or `undefined` if + * the document doesn't exist. + */ + data(options?: SnapshotOptions): AppModelType | undefined; + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * By default, a `serverTimestamp()` that has not yet been set to + * its final value will be returned as `null`. You can override this by + * passing an options object. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @param options - An options object to configure how the field is retrieved + * from the snapshot (for example the desired behavior for server timestamps + * that have not yet been set to their final value). + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + get(fieldPath: string | FieldPath, options?: SnapshotOptions): any; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + bundleSource: Property<"string">; + bundleName: Property<"string">; + bundle: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `DocumentSnapshot` instance. + * + * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this + * `DocumentSnapshot` has pending writes. + */ + toJSON(): object; +} +/** + * Builds a `DocumentSnapshot` instance from a JSON object created by + * {@link DocumentSnapshot.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json - a JSON object represention of a `DocumentSnapshot` instance. + * @returns an instance of {@link DocumentSnapshot} if the JSON object could be + * parsed. Throws a {@link FirestoreError} if an error occurs. + */ +export declare function documentSnapshotFromJSON(db: Firestore, json: object): DocumentSnapshot; +/** + * Builds a `DocumentSnapshot` instance from a JSON object created by + * {@link DocumentSnapshot.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json - a JSON object represention of a `DocumentSnapshot` instance. + * @param converter - Converts objects to and from Firestore. + * @returns an instance of {@link DocumentSnapshot} if the JSON object could be + * parsed. Throws a {@link FirestoreError} if an error occurs. + */ +export declare function documentSnapshotFromJSON(db: Firestore, json: object, converter: FirestoreDataConverter): DocumentSnapshot; +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ +export declare class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * By default, `serverTimestamp()` values that have not yet been + * set to their final value will be returned as `null`. You can override + * this by passing an options object. + * + * @override + * @param options - An options object to configure how data is retrieved from + * the snapshot (for example the desired behavior for server timestamps that + * have not yet been set to their final value). + * @returns An `Object` containing all fields in the document. + */ + data(options?: SnapshotOptions): AppModelType; +} +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ +export declare class QuerySnapshot { + readonly _firestore: Firestore; + readonly _userDataWriter: AbstractUserDataWriter; + readonly _snapshot: ViewSnapshot; + /** + * Metadata about this snapshot, concerning its source and if it has local + * modifications. + */ + readonly metadata: SnapshotMetadata; + /** + * The query on which you called `get` or `onSnapshot` in order to get this + * `QuerySnapshot`. + */ + readonly query: Query; + private _cachedChanges?; + private _cachedChangesIncludeMetadataChanges?; + /** @hideconstructor */ + constructor(_firestore: Firestore, _userDataWriter: AbstractUserDataWriter, query: Query, _snapshot: ViewSnapshot); + /** An array of all the documents in the `QuerySnapshot`. */ + get docs(): Array>; + /** The number of documents in the `QuerySnapshot`. */ + get size(): number; + /** True if there are no documents in the `QuerySnapshot`. */ + get empty(): boolean; + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ + forEach(callback: (result: QueryDocumentSnapshot) => void, thisArg?: unknown): void; + /** + * Returns an array of the documents changes since the last snapshot. If this + * is the first snapshot, all documents will be in the list as 'added' + * changes. + * + * @param options - `SnapshotListenOptions` that control whether metadata-only + * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger + * snapshot events. + */ + docChanges(options?: SnapshotListenOptions): Array>; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + bundleSource: Property<"string">; + bundleName: Property<"string">; + bundle: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `QuerySnapshot` instance. + * + * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this + * `QuerySnapshot` has pending writes. + */ + toJSON(): object; +} +/** + * Builds a `QuerySnapshot` instance from a JSON object created by + * {@link QuerySnapshot.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json - a JSON object represention of a `QuerySnapshot` instance. + * @returns an instance of {@link QuerySnapshot} if the JSON object could be + * parsed. Throws a {@link FirestoreError} if an error occurs. + */ +export declare function querySnapshotFromJSON(db: Firestore, json: object): QuerySnapshot; +/** + * Builds a `QuerySnapshot` instance from a JSON object created by + * {@link QuerySnapshot.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json - a JSON object represention of a `QuerySnapshot` instance. + * @param converter - Converts objects to and from Firestore. + * @returns an instance of {@link QuerySnapshot} if the JSON object could be + * parsed. Throws a {@link FirestoreError} if an error occurs. + */ +export declare function querySnapshotFromJSON(db: Firestore, json: object, converter: FirestoreDataConverter): QuerySnapshot; +/** Calculates the array of `DocumentChange`s for a given `ViewSnapshot`. */ +export declare function changesFromSnapshot(querySnapshot: QuerySnapshot, includeMetadataChanges: boolean): Array>; +export declare function resultChangeType(type: ChangeType): DocumentChangeType; +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ +export declare function snapshotEqual(left: DocumentSnapshot | QuerySnapshot, right: DocumentSnapshot | QuerySnapshot): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/timestamp.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/timestamp.d.ts new file mode 100644 index 0000000..35969cd --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/timestamp.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { Timestamp } from '../lite-api/timestamp'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/transaction.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/transaction.d.ts new file mode 100644 index 0000000..eccd1fb --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/transaction.d.ts @@ -0,0 +1,61 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Transaction as InternalTransaction } from '../core/transaction'; +import { DocumentData, DocumentReference } from '../lite-api/reference'; +import { Transaction as LiteTransaction } from '../lite-api/transaction'; +import { Firestore } from './database'; +import { DocumentSnapshot } from './snapshot'; +import { TransactionOptions } from './transaction_options'; +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ +export declare class Transaction extends LiteTransaction { + protected readonly _firestore: Firestore; + /** @hideconstructor */ + constructor(_firestore: Firestore, _transaction: InternalTransaction); + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ + get(documentRef: DocumentReference): Promise>; +} +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ +export declare function runTransaction(firestore: Firestore, updateFunction: (transaction: Transaction) => Promise, options?: TransactionOptions): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/transaction_options.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/transaction_options.d.ts new file mode 100644 index 0000000..578e4f4 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/transaction_options.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { TransactionOptions } from '../lite-api/transaction_options'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/write_batch.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/write_batch.d.ts new file mode 100644 index 0000000..13b31d8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/api/write_batch.d.ts @@ -0,0 +1,31 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { WriteBatch } from '../lite-api/write_batch'; +import { Firestore } from './database'; +export { WriteBatch }; +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch} + * is 500. + * + * Unlike transactions, write batches are persisted offline and therefore are + * preferable when you don't need to condition your writes on read data. + * + * @returns A {@link WriteBatch} that can be used to atomically execute multiple + * writes. + */ +export declare function writeBatch(firestore: Firestore): WriteBatch; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/auth/user.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/auth/user.d.ts new file mode 100644 index 0000000..920a290 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/auth/user.d.ts @@ -0,0 +1,36 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Simple wrapper around a nullable UID. Mostly exists to make code more + * readable. + */ +export declare class User { + readonly uid: string | null; + /** A user with a null UID. */ + static readonly UNAUTHENTICATED: User; + static readonly GOOGLE_CREDENTIALS: User; + static readonly FIRST_PARTY: User; + static readonly MOCK_USER: User; + constructor(uid: string | null); + isAuthenticated(): boolean; + /** + * Returns a key representing this user, suitable for inclusion in a + * dictionary. + */ + toKey(): string; + isEqual(otherUser: User): boolean; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/aggregate.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/aggregate.d.ts new file mode 100644 index 0000000..16da2bb --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/aggregate.d.ts @@ -0,0 +1,38 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FieldPath } from '../model/path'; +/** + * Union type representing the aggregate type to be performed. + */ +export type AggregateType = 'count' | 'avg' | 'sum'; +/** + * Represents an Aggregate to be performed over a query result set. + */ +export interface Aggregate { + readonly fieldPath?: FieldPath; + readonly alias: string; + readonly aggregateType: AggregateType; +} +/** + * Concrete implementation of the Aggregate type. + */ +export declare class AggregateImpl implements Aggregate { + readonly alias: string; + readonly aggregateType: AggregateType; + readonly fieldPath?: FieldPath | undefined; + constructor(alias: string, aggregateType: AggregateType, fieldPath?: FieldPath | undefined); +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/bound.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/bound.d.ts new file mode 100644 index 0000000..8289126 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/bound.d.ts @@ -0,0 +1,49 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Document } from '../model/document'; +import { Value as ProtoValue } from '../protos/firestore_proto_api'; +import { OrderBy } from './order_by'; +/** + * Represents a bound of a query. + * + * The bound is specified with the given components representing a position and + * whether it's just before or just after the position (relative to whatever the + * query order is). + * + * The position represents a logical index position for a query. It's a prefix + * of values for the (potentially implicit) order by clauses of a query. + * + * Bound provides a function to determine whether a document comes before or + * after a bound. This is influenced by whether the position is just before or + * just after the provided values. + */ +export declare class Bound { + readonly position: ProtoValue[]; + readonly inclusive: boolean; + constructor(position: ProtoValue[], inclusive: boolean); +} +/** + * Returns true if a document sorts after a bound using the provided sort + * order. + */ +export declare function boundSortsAfterDocument(bound: Bound, orderBy: OrderBy[], doc: Document): boolean; +/** + * Returns true if a document sorts before a bound using the provided sort + * order. + */ +export declare function boundSortsBeforeDocument(bound: Bound, orderBy: OrderBy[], doc: Document): boolean; +export declare function boundEquals(left: Bound | null, right: Bound | null): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/bundle.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/bundle.d.ts new file mode 100644 index 0000000..6a81fcf --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/bundle.d.ts @@ -0,0 +1,80 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { LoadBundleTaskProgress } from '@firebase/firestore-types'; +import { DocumentMap } from '../model/collections'; +import { MutableDocument } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { BundledDocumentMetadata as ProtoBundledDocumentMetadata } from '../protos/firestore_bundle_proto'; +import { Document as ApiDocument, Timestamp as ApiTimestamp } from '../protos/firestore_proto_api'; +import { Query } from './query'; +import { SnapshotVersion } from './snapshot_version'; +/** + * Represents a bundled document, including the metadata and the document + * itself, if it exists. + */ +export interface BundledDocument { + metadata: ProtoBundledDocumentMetadata; + document?: ApiDocument; +} +/** + * An array of `BundledDocument`. + */ +export type BundledDocuments = BundledDocument[]; +export interface BundleLoadResult { + readonly progress: LoadBundleTaskProgress; + readonly changedCollectionGroups: Set; + readonly changedDocs: DocumentMap; +} +/** + * Represents a Firestore bundle saved by the SDK in its local storage. + */ +export interface BundleMetadata { + /** + * Id of the bundle. It is used together with `createTime` to determine if a + * bundle has been loaded by the SDK. + */ + readonly id: string; + /** Schema version of the bundle. */ + readonly version: number; + /** + * Set to the snapshot version of the bundle if created by the Server SDKs. + * Otherwise set to SnapshotVersion.MIN. + */ + readonly createTime: SnapshotVersion; +} +/** + * Represents a Query saved by the SDK in its local storage. + */ +export interface NamedQuery { + /** The name of the query. */ + readonly name: string; + /** The underlying query associated with `name`. */ + readonly query: Query; + /** The time at which the results for this query were read. */ + readonly readTime: SnapshotVersion; +} +/** + * Helper to convert objects from bundles to model objects in the SDK. + */ +export interface BundleConverter { + toDocumentKey(name: string): DocumentKey; + /** + * Converts a BundleDocument to a MutableDocument. + */ + toMutableDocument(bundledDoc: BundledDocument): MutableDocument; + toSnapshotVersion(time: ApiTimestamp): SnapshotVersion; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/bundle_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/bundle_impl.d.ts new file mode 100644 index 0000000..55395f2 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/bundle_impl.d.ts @@ -0,0 +1,88 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { LoadBundleTaskProgress } from '@firebase/firestore-types'; +import { LocalStore } from '../local/local_store'; +import { MutableDocument } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { BundleMetadata as ProtoBundleMetadata, NamedQuery as ProtoNamedQuery } from '../protos/firestore_bundle_proto'; +import { Timestamp as ApiTimestamp } from '../protos/firestore_proto_api'; +import { JsonProtoSerializer } from '../remote/serializer'; +import { SizedBundleElement } from '../util/bundle_reader'; +import { BundleConverter, BundledDocument, BundledDocuments, BundleLoadResult } from './bundle'; +import { SnapshotVersion } from './snapshot_version'; +/** + * Helper to convert objects from bundles to model objects in the SDK. + */ +export declare class BundleConverterImpl implements BundleConverter { + private readonly serializer; + constructor(serializer: JsonProtoSerializer); + toDocumentKey(name: string): DocumentKey; + /** + * Converts a BundleDocument to a MutableDocument. + */ + toMutableDocument(bundledDoc: BundledDocument): MutableDocument; + toSnapshotVersion(time: ApiTimestamp): SnapshotVersion; +} +/** + * A class to process the elements from a bundle, and optionally load them into local + * storage and provide progress update while loading. + */ +export declare class BundleLoader { + private bundleMetadata; + private serializer; + /** The current progress of loading */ + private progress; + /** Batched queries to be saved into storage */ + private _queries; + /** Batched documents to be saved into storage */ + private _documents; + /** The collection groups affected by this bundle. */ + private collectionGroups; + constructor(bundleMetadata: ProtoBundleMetadata, serializer: JsonProtoSerializer); + /** + * Returns the named queries that have been parsed from the SizeBundleElements added by + * calling {@link adSizedElement}. + */ + get queries(): ProtoNamedQuery[]; + /** + * Returns the BundledDocuments that have been parsed from the SizeBundleElements added by + * calling {@link addSizedElement}. + */ + get documents(): BundledDocuments; + /** + * Adds an element from the bundle to the loader. + * + * Returns a new progress if adding the element leads to a new progress, + * otherwise returns null. + */ + addSizedElement(element: SizedBundleElement): LoadBundleTaskProgress | null; + private getQueryDocumentMapping; + /** + * Update the progress to 'Success' and return the updated progress. + */ + completeAndStoreAsync(localStore: LocalStore): Promise; +} +/** + * Returns a `LoadBundleTaskProgress` representing the initial progress of + * loading a bundle. + */ +export declare function bundleInitialProgress(metadata: ProtoBundleMetadata): LoadBundleTaskProgress; +/** + * Returns a `LoadBundleTaskProgress` representing the progress that the loading + * has succeeded. + */ +export declare function bundleSuccessProgress(metadata: ProtoBundleMetadata): LoadBundleTaskProgress; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/component_provider.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/component_provider.d.ts new file mode 100644 index 0000000..97b6814 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/component_provider.d.ts @@ -0,0 +1,146 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { CredentialsProvider } from '../api/credentials'; +import { User } from '../auth/user'; +import { IndexedDbPersistence } from '../local/indexeddb_persistence'; +import { LocalStore } from '../local/local_store'; +import { Scheduler, Persistence } from '../local/persistence'; +import { ClientId, SharedClientState } from '../local/shared_client_state'; +import { Datastore } from '../remote/datastore'; +import { RemoteStore } from '../remote/remote_store'; +import { JsonProtoSerializer } from '../remote/serializer'; +import { AsyncQueue } from '../util/async_queue'; +import { DatabaseInfo } from './database_info'; +import { EventManager } from './event_manager'; +import { SyncEngine } from './sync_engine'; +type Kind = 'memory' | 'persistent'; +export interface ComponentConfiguration { + asyncQueue: AsyncQueue; + databaseInfo: DatabaseInfo; + authCredentials: CredentialsProvider; + appCheckCredentials: CredentialsProvider; + clientId: ClientId; + initialUser: User; + maxConcurrentLimboResolutions: number; +} +export interface OfflineComponentProviderFactory { + build(onlineComponents: OnlineComponentProvider): OfflineComponentProvider; +} +/** + * Initializes and wires components that are needed to interface with the local + * cache. Implementations override `initialize()` to provide all components. + */ +export interface OfflineComponentProvider { + readonly kind: Kind; + persistence: Persistence; + sharedClientState: SharedClientState; + localStore: LocalStore; + gcScheduler: Scheduler | null; + indexBackfillerScheduler: Scheduler | null; + synchronizeTabs: boolean; + initialize(cfg: ComponentConfiguration): Promise; + terminate(): Promise; +} +/** + * Provides all components needed for Firestore with in-memory persistence. + * Uses EagerGC garbage collection. + */ +export declare class MemoryOfflineComponentProvider implements OfflineComponentProvider { + kind: Kind; + static readonly provider: OfflineComponentProviderFactory; + persistence: Persistence; + sharedClientState: SharedClientState; + localStore: LocalStore; + gcScheduler: Scheduler | null; + indexBackfillerScheduler: Scheduler | null; + synchronizeTabs: boolean; + serializer: JsonProtoSerializer; + initialize(cfg: ComponentConfiguration): Promise; + createGarbageCollectionScheduler(cfg: ComponentConfiguration, localStore: LocalStore): Scheduler | null; + createIndexBackfillerScheduler(cfg: ComponentConfiguration, localStore: LocalStore): Scheduler | null; + createLocalStore(cfg: ComponentConfiguration): LocalStore; + createPersistence(cfg: ComponentConfiguration): Persistence; + createSharedClientState(cfg: ComponentConfiguration): SharedClientState; + terminate(): Promise; +} +export declare class LruGcMemoryOfflineComponentProvider extends MemoryOfflineComponentProvider { + protected readonly cacheSizeBytes: number | undefined; + constructor(cacheSizeBytes: number | undefined); + createGarbageCollectionScheduler(cfg: ComponentConfiguration, localStore: LocalStore): Scheduler | null; + createPersistence(cfg: ComponentConfiguration): Persistence; +} +/** + * Provides all components needed for Firestore with IndexedDB persistence. + */ +export declare class IndexedDbOfflineComponentProvider extends MemoryOfflineComponentProvider { + protected readonly onlineComponentProvider: OnlineComponentProvider; + protected readonly cacheSizeBytes: number | undefined; + protected readonly forceOwnership: boolean | undefined; + kind: Kind; + persistence: IndexedDbPersistence; + sharedClientState: SharedClientState; + localStore: LocalStore; + gcScheduler: Scheduler | null; + indexBackfillerScheduler: Scheduler | null; + synchronizeTabs: boolean; + constructor(onlineComponentProvider: OnlineComponentProvider, cacheSizeBytes: number | undefined, forceOwnership: boolean | undefined); + initialize(cfg: ComponentConfiguration): Promise; + createLocalStore(cfg: ComponentConfiguration): LocalStore; + createGarbageCollectionScheduler(cfg: ComponentConfiguration, localStore: LocalStore): Scheduler | null; + createIndexBackfillerScheduler(cfg: ComponentConfiguration, localStore: LocalStore): Scheduler | null; + createPersistence(cfg: ComponentConfiguration): IndexedDbPersistence; + createSharedClientState(cfg: ComponentConfiguration): SharedClientState; +} +/** + * Provides all components needed for Firestore with multi-tab IndexedDB + * persistence. + * + * In the legacy client, this provider is used to provide both multi-tab and + * non-multi-tab persistence since we cannot tell at build time whether + * `synchronizeTabs` will be enabled. + */ +export declare class MultiTabOfflineComponentProvider extends IndexedDbOfflineComponentProvider { + protected readonly onlineComponentProvider: OnlineComponentProvider; + protected readonly cacheSizeBytes: number | undefined; + synchronizeTabs: boolean; + constructor(onlineComponentProvider: OnlineComponentProvider, cacheSizeBytes: number | undefined); + initialize(cfg: ComponentConfiguration): Promise; + createSharedClientState(cfg: ComponentConfiguration): SharedClientState; +} +export interface OnlineComponentProviderFactory { + build(): OnlineComponentProvider; +} +/** + * Initializes and wires the components that are needed to interface with the + * network. + */ +export declare class OnlineComponentProvider { + static readonly provider: OnlineComponentProviderFactory; + protected localStore: LocalStore; + protected sharedClientState: SharedClientState; + datastore: Datastore; + eventManager: EventManager; + remoteStore: RemoteStore; + syncEngine: SyncEngine; + initialize(offlineComponentProvider: OfflineComponentProvider, cfg: ComponentConfiguration): Promise; + createEventManager(cfg: ComponentConfiguration): EventManager; + createDatastore(cfg: ComponentConfiguration): Datastore; + createRemoteStore(cfg: ComponentConfiguration): RemoteStore; + createSyncEngine(cfg: ComponentConfiguration, startAsPrimary: boolean): SyncEngine; + terminate(): Promise; +} +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/database_info.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/database_info.d.ts new file mode 100644 index 0000000..5429403 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/database_info.d.ts @@ -0,0 +1,64 @@ +import { FirebaseApp } from '@firebase/app'; +import { ExperimentalLongPollingOptions } from '../api/long_polling_options'; +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare class DatabaseInfo { + readonly databaseId: DatabaseId; + readonly appId: string; + readonly persistenceKey: string; + readonly host: string; + readonly ssl: boolean; + readonly forceLongPolling: boolean; + readonly autoDetectLongPolling: boolean; + readonly longPollingOptions: ExperimentalLongPollingOptions; + readonly useFetchStreams: boolean; + readonly isUsingEmulator: boolean; + /** + * Constructs a DatabaseInfo using the provided host, databaseId and + * persistenceKey. + * + * @param databaseId - The database to use. + * @param appId - The Firebase App Id. + * @param persistenceKey - A unique identifier for this Firestore's local + * storage (used in conjunction with the databaseId). + * @param host - The Firestore backend host to connect to. + * @param ssl - Whether to use SSL when connecting. + * @param forceLongPolling - Whether to use the forceLongPolling option + * when using WebChannel as the network transport. + * @param autoDetectLongPolling - Whether to use the detectBufferingProxy + * option when using WebChannel as the network transport. + * @param longPollingOptions Options that configure long-polling. + * @param useFetchStreams Whether to use the Fetch API instead of + * XMLHTTPRequest + */ + constructor(databaseId: DatabaseId, appId: string, persistenceKey: string, host: string, ssl: boolean, forceLongPolling: boolean, autoDetectLongPolling: boolean, longPollingOptions: ExperimentalLongPollingOptions, useFetchStreams: boolean, isUsingEmulator: boolean); +} +/** The default database name for a project. */ +export declare const DEFAULT_DATABASE_NAME = "(default)"; +/** + * Represents the database ID a Firestore client is associated with. + * @internal + */ +export declare class DatabaseId { + readonly projectId: string; + readonly database: string; + constructor(projectId: string, database?: string); + static empty(): DatabaseId; + get isDefaultDatabase(): boolean; + isEqual(other: {}): boolean; +} +export declare function databaseIdFromApp(app: FirebaseApp, database?: string): DatabaseId; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/event_manager.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/event_manager.d.ts new file mode 100644 index 0000000..38b980f --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/event_manager.d.ts @@ -0,0 +1,133 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirestoreError } from '../util/error'; +import { EventHandler } from '../util/misc'; +import { ObjectMap } from '../util/obj_map'; +import { Query } from './query'; +import { OnlineState } from './types'; +import { ViewSnapshot } from './view_snapshot'; +/** + * Holds the listeners and the last received ViewSnapshot for a query being + * tracked by EventManager. + */ +declare class QueryListenersInfo { + viewSnap: ViewSnapshot | undefined; + listeners: QueryListener[]; + hasRemoteListeners(): boolean; +} +/** + * Interface for handling events from the EventManager. + */ +export interface Observer { + next: EventHandler; + error: EventHandler; +} +/** + * EventManager is responsible for mapping queries to query event emitters. + * It handles "fan-out". -- Identical queries will re-use the same watch on the + * backend. + * + * PORTING NOTE: On Web, EventManager `onListen` and `onUnlisten` need to be + * assigned to SyncEngine's `listen()` and `unlisten()` API before usage. This + * allows users to tree-shake the Watch logic. + */ +export interface EventManager { + onListen?: (query: Query, enableRemoteListen: boolean) => Promise; + onUnlisten?: (query: Query, disableRemoteListen: boolean) => Promise; + onFirstRemoteStoreListen?: (query: Query) => Promise; + onLastRemoteStoreUnlisten?: (query: Query) => Promise; + terminate(): void; +} +export declare function newEventManager(): EventManager; +export declare class EventManagerImpl implements EventManager { + queries: ObjectMap; + onlineState: OnlineState; + snapshotsInSyncListeners: Set>; + /** Callback invoked when a Query is first listen to. */ + onListen?: (query: Query, enableRemoteListen: boolean) => Promise; + /** Callback invoked once all listeners to a Query are removed. */ + onUnlisten?: (query: Query, disableRemoteListen: boolean) => Promise; + /** + * Callback invoked when a Query starts listening to the remote store, while + * already listening to the cache. + */ + onFirstRemoteStoreListen?: (query: Query) => Promise; + /** + * Callback invoked when a Query stops listening to the remote store, while + * still listening to the cache. + */ + onLastRemoteStoreUnlisten?: (query: Query) => Promise; + terminate(): void; +} +export declare function eventManagerListen(eventManager: EventManager, listener: QueryListener): Promise; +export declare function eventManagerUnlisten(eventManager: EventManager, listener: QueryListener): Promise; +export declare function eventManagerOnWatchChange(eventManager: EventManager, viewSnaps: ViewSnapshot[]): void; +export declare function eventManagerOnWatchError(eventManager: EventManager, query: Query, error: FirestoreError): void; +export declare function eventManagerOnOnlineStateChange(eventManager: EventManager, onlineState: OnlineState): void; +export declare function addSnapshotsInSyncListener(eventManager: EventManager, observer: Observer): void; +export declare function removeSnapshotsInSyncListener(eventManager: EventManager, observer: Observer): void; +export declare enum ListenerDataSource { + /** Listen to both cache and server changes */ + Default = "default", + /** Listen to changes in cache only */ + Cache = "cache" +} +export interface ListenOptions { + /** Raise events even when only the metadata changes */ + readonly includeMetadataChanges?: boolean; + /** + * Wait for a sync with the server when online, but still raise events while + * offline. + */ + readonly waitForSyncWhenOnline?: boolean; + /** Set the source events raised from. */ + readonly source?: ListenerDataSource; +} +/** + * QueryListener takes a series of internal view snapshots and determines + * when to raise the event. + * + * It uses an Observer to dispatch events. + */ +export declare class QueryListener { + readonly query: Query; + private queryObserver; + /** + * Initial snapshots (e.g. from cache) may not be propagated to the wrapped + * observer. This flag is set to true once we've actually raised an event. + */ + private raisedInitialEvent; + private options; + private snap; + private onlineState; + constructor(query: Query, queryObserver: Observer, options?: ListenOptions); + /** + * Applies the new ViewSnapshot to this listener, raising a user-facing event + * if applicable (depending on what changed, whether the user has opted into + * metadata-only changes, etc.). Returns true if a user-facing event was + * indeed raised. + */ + onViewSnapshot(snap: ViewSnapshot): boolean; + onError(error: FirestoreError): void; + /** Returns whether a snapshot was raised. */ + applyOnlineStateChange(onlineState: OnlineState): boolean; + private shouldRaiseInitialEvent; + private shouldRaiseEvent; + private raiseInitialEvent; + listensToRemoteStore(): boolean; +} +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/filter.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/filter.d.ts new file mode 100644 index 0000000..ccb871f --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/filter.d.ts @@ -0,0 +1,130 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Document } from '../model/document'; +import { FieldPath } from '../model/path'; +import { Value as ProtoValue } from '../protos/firestore_proto_api'; +export declare const enum Operator { + LESS_THAN = "<", + LESS_THAN_OR_EQUAL = "<=", + EQUAL = "==", + NOT_EQUAL = "!=", + GREATER_THAN = ">", + GREATER_THAN_OR_EQUAL = ">=", + ARRAY_CONTAINS = "array-contains", + IN = "in", + NOT_IN = "not-in", + ARRAY_CONTAINS_ANY = "array-contains-any" +} +export declare const enum CompositeOperator { + OR = "or", + AND = "and" +} +export declare abstract class Filter { + abstract matches(doc: Document): boolean; + abstract getFlattenedFilters(): readonly FieldFilter[]; + abstract getFilters(): Filter[]; +} +export declare class FieldFilter extends Filter { + readonly field: FieldPath; + readonly op: Operator; + readonly value: ProtoValue; + protected constructor(field: FieldPath, op: Operator, value: ProtoValue); + /** + * Creates a filter based on the provided arguments. + */ + static create(field: FieldPath, op: Operator, value: ProtoValue): FieldFilter; + private static createKeyFieldInFilter; + matches(doc: Document): boolean; + protected matchesComparison(comparison: number): boolean; + isInequality(): boolean; + getFlattenedFilters(): readonly FieldFilter[]; + getFilters(): Filter[]; +} +export declare class CompositeFilter extends Filter { + readonly filters: readonly Filter[]; + readonly op: CompositeOperator; + private memoizedFlattenedFilters; + protected constructor(filters: readonly Filter[], op: CompositeOperator); + /** + * Creates a filter based on the provided arguments. + */ + static create(filters: Filter[], op: CompositeOperator): CompositeFilter; + matches(doc: Document): boolean; + getFlattenedFilters(): readonly FieldFilter[]; + getFilters(): Filter[]; +} +export declare function compositeFilterIsConjunction(compositeFilter: CompositeFilter): boolean; +export declare function compositeFilterIsDisjunction(compositeFilter: CompositeFilter): boolean; +/** + * Returns true if this filter is a conjunction of field filters only. Returns false otherwise. + */ +export declare function compositeFilterIsFlatConjunction(compositeFilter: CompositeFilter): boolean; +/** + * Returns true if this filter does not contain any composite filters. Returns false otherwise. + */ +export declare function compositeFilterIsFlat(compositeFilter: CompositeFilter): boolean; +export declare function canonifyFilter(filter: Filter): string; +export declare function filterEquals(f1: Filter, f2: Filter): boolean; +export declare function fieldFilterEquals(f1: FieldFilter, f2: Filter): boolean; +export declare function compositeFilterEquals(f1: CompositeFilter, f2: Filter): boolean; +/** + * Returns a new composite filter that contains all filter from + * `compositeFilter` plus all the given filters in `otherFilters`. + */ +export declare function compositeFilterWithAddedFilters(compositeFilter: CompositeFilter, otherFilters: Filter[]): CompositeFilter; +/** Returns a debug description for `filter`. */ +export declare function stringifyFilter(filter: Filter): string; +export declare function stringifyCompositeFilter(filter: CompositeFilter): string; +export declare function stringifyFieldFilter(filter: FieldFilter): string; +/** Filter that matches on key fields (i.e. '__name__'). */ +export declare class KeyFieldFilter extends FieldFilter { + private readonly key; + constructor(field: FieldPath, op: Operator, value: ProtoValue); + matches(doc: Document): boolean; +} +/** Filter that matches on key fields within an array. */ +export declare class KeyFieldInFilter extends FieldFilter { + private readonly keys; + constructor(field: FieldPath, value: ProtoValue); + matches(doc: Document): boolean; +} +/** Filter that matches on key fields not present within an array. */ +export declare class KeyFieldNotInFilter extends FieldFilter { + private readonly keys; + constructor(field: FieldPath, value: ProtoValue); + matches(doc: Document): boolean; +} +/** A Filter that implements the array-contains operator. */ +export declare class ArrayContainsFilter extends FieldFilter { + constructor(field: FieldPath, value: ProtoValue); + matches(doc: Document): boolean; +} +/** A Filter that implements the IN operator. */ +export declare class InFilter extends FieldFilter { + constructor(field: FieldPath, value: ProtoValue); + matches(doc: Document): boolean; +} +/** A Filter that implements the not-in operator. */ +export declare class NotInFilter extends FieldFilter { + constructor(field: FieldPath, value: ProtoValue); + matches(doc: Document): boolean; +} +/** A Filter that implements the array-contains-any operator. */ +export declare class ArrayContainsAnyFilter extends FieldFilter { + constructor(field: FieldPath, value: ProtoValue); + matches(doc: Document): boolean; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/firestore_client.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/firestore_client.d.ts new file mode 100644 index 0000000..a3a2b24 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/firestore_client.d.ts @@ -0,0 +1,138 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { GetOptions } from '@firebase/firestore-types'; +import { LoadBundleTask } from '../api/bundle'; +import { CredentialsProvider } from '../api/credentials'; +import { User } from '../auth/user'; +import { LocalStore } from '../local/local_store'; +import { Document } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { FieldIndex } from '../model/field_index'; +import { Mutation } from '../model/mutation'; +import { ApiClientObjectMap, Value } from '../protos/firestore_proto_api'; +import { JsonProtoSerializer } from '../remote/serializer'; +import { AsyncQueue } from '../util/async_queue'; +import { BundleReaderSync } from '../util/bundle_reader'; +import { FirestoreError } from '../util/error'; +import { Aggregate } from './aggregate'; +import { NamedQuery } from './bundle'; +import { ComponentConfiguration, OfflineComponentProvider, OnlineComponentProvider } from './component_provider'; +import { DatabaseId, DatabaseInfo } from './database_info'; +import { EventManager, ListenOptions, Observer } from './event_manager'; +import { Query } from './query'; +import { SyncEngine } from './sync_engine'; +import { Transaction } from './transaction'; +import { TransactionOptions } from './transaction_options'; +import { ViewSnapshot } from './view_snapshot'; +export declare const MAX_CONCURRENT_LIMBO_RESOLUTIONS = 100; +/** + * FirestoreClient is a top-level class that constructs and owns all of the // + * pieces of the client SDK architecture. It is responsible for creating the // + * async queue that is shared by all of the other components in the system. // + */ +export declare class FirestoreClient { + private authCredentials; + private appCheckCredentials; + /** + * Asynchronous queue responsible for all of our internal processing. When + * we get incoming work from the user (via public API) or the network + * (incoming GRPC messages), we should always schedule onto this queue. + * This ensures all of our work is properly serialized (e.g. we don't + * start processing a new operation while the previous one is waiting for + * an async I/O to complete). + */ + asyncQueue: AsyncQueue; + private databaseInfo; + private user; + private readonly clientId; + private authCredentialListener; + private appCheckCredentialListener; + _uninitializedComponentsProvider?: { + _offline: OfflineComponentProvider; + _online: OnlineComponentProvider; + }; + _offlineComponents?: OfflineComponentProvider; + _onlineComponents?: OnlineComponentProvider; + constructor(authCredentials: CredentialsProvider, appCheckCredentials: CredentialsProvider, + /** + * Asynchronous queue responsible for all of our internal processing. When + * we get incoming work from the user (via public API) or the network + * (incoming GRPC messages), we should always schedule onto this queue. + * This ensures all of our work is properly serialized (e.g. we don't + * start processing a new operation while the previous one is waiting for + * an async I/O to complete). + */ + asyncQueue: AsyncQueue, databaseInfo: DatabaseInfo, componentProvider?: { + _offline: OfflineComponentProvider; + _online: OnlineComponentProvider; + }); + get configuration(): ComponentConfiguration; + setCredentialChangeListener(listener: (user: User) => Promise): void; + setAppCheckTokenChangeListener(listener: (appCheckToken: string, user: User) => Promise): void; + terminate(): Promise; +} +export declare function setOfflineComponentProvider(client: FirestoreClient, offlineComponentProvider: OfflineComponentProvider): Promise; +export declare function setOnlineComponentProvider(client: FirestoreClient, onlineComponentProvider: OnlineComponentProvider): Promise; +/** + * Decides whether the provided error allows us to gracefully disable + * persistence (as opposed to crashing the client). + */ +export declare function canFallbackFromIndexedDbError(error: FirestoreError | DOMException): boolean; +export declare function ensureOnlineComponents(client: FirestoreClient): Promise; +export declare function getLocalStore(client: FirestoreClient): Promise; +export declare function getSyncEngine(client: FirestoreClient): Promise; +export declare function getEventManager(client: FirestoreClient): Promise; +/** Enables the network connection and re-enqueues all pending operations. */ +export declare function firestoreClientEnableNetwork(client: FirestoreClient): Promise; +/** Disables the network connection. Pending operations will not complete. */ +export declare function firestoreClientDisableNetwork(client: FirestoreClient): Promise; +/** + * Returns a Promise that resolves when all writes that were pending at the time + * this method was called received server acknowledgement. An acknowledgement + * can be either acceptance or rejection. + */ +export declare function firestoreClientWaitForPendingWrites(client: FirestoreClient): Promise; +export declare function firestoreClientListen(client: FirestoreClient, query: Query, options: ListenOptions, observer: Partial>): () => void; +export declare function firestoreClientGetDocumentFromLocalCache(client: FirestoreClient, docKey: DocumentKey): Promise; +export declare function firestoreClientGetDocumentViaSnapshotListener(client: FirestoreClient, key: DocumentKey, options?: GetOptions): Promise; +export declare function firestoreClientGetDocumentsFromLocalCache(client: FirestoreClient, query: Query): Promise; +export declare function firestoreClientGetDocumentsViaSnapshotListener(client: FirestoreClient, query: Query, options?: GetOptions): Promise; +export declare function firestoreClientRunAggregateQuery(client: FirestoreClient, query: Query, aggregates: Aggregate[]): Promise>; +export declare function firestoreClientWrite(client: FirestoreClient, mutations: Mutation[]): Promise; +export declare function firestoreClientAddSnapshotsInSyncListener(client: FirestoreClient, observer: Partial>): () => void; +/** + * Takes an updateFunction in which a set of reads and writes can be performed + * atomically. In the updateFunction, the client can read and write values + * using the supplied transaction object. After the updateFunction, all + * changes will be committed. If a retryable error occurs (ex: some other + * client has changed any of the data referenced), then the updateFunction + * will be called again after a backoff. If the updateFunction still fails + * after all retries, then the transaction will be rejected. + * + * The transaction object passed to the updateFunction contains methods for + * accessing documents and collections. Unlike other datastore access, data + * accessed with the transaction will not reflect local changes that have not + * been committed. For this reason, it is required that all reads are + * performed before any writes. Transactions must be performed while online. + */ +export declare function firestoreClientTransaction(client: FirestoreClient, updateFunction: (transaction: Transaction) => Promise, options: TransactionOptions): Promise; +export declare function firestoreClientLoadBundle(client: FirestoreClient, databaseId: DatabaseId, data: ReadableStream | ArrayBuffer | string, resultTask: LoadBundleTask): void; +export declare function firestoreClientGetNamedQuery(client: FirestoreClient, queryName: string): Promise; +export declare function createBundleReaderSync(bundleData: string, serializer: JsonProtoSerializer): BundleReaderSync; +export declare function firestoreClientSetIndexConfiguration(client: FirestoreClient, indexes: FieldIndex[]): Promise; +export declare function firestoreClientSetPersistentCacheIndexAutoCreationEnabled(client: FirestoreClient, isEnabled: boolean): Promise; +export declare function firestoreClientDeleteAllFieldIndexes(client: FirestoreClient): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/listen_sequence.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/listen_sequence.d.ts new file mode 100644 index 0000000..c824db1 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/listen_sequence.d.ts @@ -0,0 +1,39 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ListenSequenceNumber } from './types'; +/** + * `SequenceNumberSyncer` defines the methods required to keep multiple instances of a + * `ListenSequence` in sync. + */ +export interface SequenceNumberSyncer { + writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void; + sequenceNumberHandler: ((sequenceNumber: ListenSequenceNumber) => void) | null; +} +/** + * `ListenSequence` is a monotonic sequence. It is initialized with a minimum value to + * exceed. All subsequent calls to next will return increasing values. If provided with a + * `SequenceNumberSyncer`, it will additionally bump its next value when told of a new value, as + * well as write out sequence numbers that it produces via `next()`. + */ +export declare class ListenSequence { + private previousValue; + static readonly INVALID: ListenSequenceNumber; + private writeNewSequenceNumber?; + constructor(previousValue: ListenSequenceNumber, sequenceNumberSyncer?: SequenceNumberSyncer); + private setPreviousValue; + next(): ListenSequenceNumber; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/order_by.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/order_by.d.ts new file mode 100644 index 0000000..1d7aa86 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/order_by.d.ts @@ -0,0 +1,35 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FieldPath } from '../model/path'; +/** + * The direction of sorting in an order by. + */ +export declare const enum Direction { + ASCENDING = "asc", + DESCENDING = "desc" +} +/** + * An ordering on a field, in some Direction. Direction defaults to ASCENDING. + */ +export declare class OrderBy { + readonly field: FieldPath; + readonly dir: Direction; + constructor(field: FieldPath, dir?: Direction); +} +export declare function canonifyOrderBy(orderBy: OrderBy): string; +export declare function stringifyOrderBy(orderBy: OrderBy): string; +export declare function orderByEquals(left: OrderBy, right: OrderBy): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/query.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/query.d.ts new file mode 100644 index 0000000..d23e0f1 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/query.d.ts @@ -0,0 +1,142 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Document } from '../model/document'; +import { FieldPath, ResourcePath } from '../model/path'; +import { SortedSet } from '../util/sorted_set'; +import { Bound } from './bound'; +import { Filter } from './filter'; +import { OrderBy } from './order_by'; +import { Target } from './target'; +export declare const enum LimitType { + First = "F", + Last = "L" +} +/** + * The Query interface defines all external properties of a query. + * + * QueryImpl implements this interface to provide memoization for `queryNormalizedOrderBy` + * and `queryToTarget`. + */ +export interface Query { + readonly path: ResourcePath; + readonly collectionGroup: string | null; + readonly explicitOrderBy: OrderBy[]; + readonly filters: Filter[]; + readonly limit: number | null; + readonly limitType: LimitType; + readonly startAt: Bound | null; + readonly endAt: Bound | null; +} +/** + * Query encapsulates all the query attributes we support in the SDK. It can + * be run against the LocalStore, as well as be converted to a `Target` to + * query the RemoteStore results. + * + * Visible for testing. + */ +export declare class QueryImpl implements Query { + readonly path: ResourcePath; + readonly collectionGroup: string | null; + readonly explicitOrderBy: OrderBy[]; + readonly filters: Filter[]; + readonly limit: number | null; + readonly limitType: LimitType; + readonly startAt: Bound | null; + readonly endAt: Bound | null; + memoizedNormalizedOrderBy: OrderBy[] | null; + memoizedTarget: Target | null; + memoizedAggregateTarget: Target | null; + /** + * Initializes a Query with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + */ + constructor(path: ResourcePath, collectionGroup?: string | null, explicitOrderBy?: OrderBy[], filters?: Filter[], limit?: number | null, limitType?: LimitType, startAt?: Bound | null, endAt?: Bound | null); +} +/** Creates a new Query instance with the options provided. */ +export declare function newQuery(path: ResourcePath, collectionGroup: string | null, explicitOrderBy: OrderBy[], filters: Filter[], limit: number | null, limitType: LimitType, startAt: Bound | null, endAt: Bound | null): Query; +/** Creates a new Query for a query that matches all documents at `path` */ +export declare function newQueryForPath(path: ResourcePath): Query; +/** + * Helper to convert a collection group query into a collection query at a + * specific path. This is used when executing collection group queries, since + * we have to split the query into a set of collection queries at multiple + * paths. + */ +export declare function asCollectionQueryAtPath(query: Query, path: ResourcePath): Query; +/** + * Returns true if this query does not specify any query constraints that + * could remove results. + */ +export declare function queryMatchesAllDocuments(query: Query): boolean; +export declare function getInequalityFilterFields(query: Query): SortedSet; +/** + * Creates a new Query for a collection group query that matches all documents + * within the provided collection group. + */ +export declare function newQueryForCollectionGroup(collectionId: string): Query; +/** + * Returns whether the query matches a single document by path (rather than a + * collection). + */ +export declare function isDocumentQuery(query: Query): boolean; +/** + * Returns whether the query matches a collection group rather than a specific + * collection. + */ +export declare function isCollectionGroupQuery(query: Query): boolean; +/** + * Returns the normalized order-by constraint that is used to execute the Query, + * which can be different from the order-by constraints the user provided (e.g. + * the SDK and backend always orders by `__name__`). The normalized order-by + * includes implicit order-bys in addition to the explicit user provided + * order-bys. + */ +export declare function queryNormalizedOrderBy(query: Query): OrderBy[]; +/** + * Converts this `Query` instance to its corresponding `Target` representation. + */ +export declare function queryToTarget(query: Query): Target; +/** + * Converts this `Query` instance to its corresponding `Target` representation, + * for use within an aggregate query. Unlike targets for non-aggregate queries, + * aggregate query targets do not contain normalized order-bys, they only + * contain explicit order-bys. + */ +export declare function queryToAggregateTarget(query: Query): Target; +export declare function queryWithAddedFilter(query: Query, filter: Filter): Query; +export declare function queryWithAddedOrderBy(query: Query, orderBy: OrderBy): Query; +export declare function queryWithLimit(query: Query, limit: number | null, limitType: LimitType): Query; +export declare function queryWithStartAt(query: Query, bound: Bound): Query; +export declare function queryWithEndAt(query: Query, bound: Bound): Query; +export declare function queryEquals(left: Query, right: Query): boolean; +export declare function canonifyQuery(query: Query): string; +export declare function stringifyQuery(query: Query): string; +/** Returns whether `doc` matches the constraints of `query`. */ +export declare function queryMatches(query: Query, doc: Document): boolean; +/** + * Returns the collection group that this query targets. + * + * PORTING NOTE: This is only used in the Web SDK to facilitate multi-tab + * synchronization for query results. + */ +export declare function queryCollectionGroup(query: Query): string; +/** + * Returns a new comparator function that can be used to compare two documents + * based on the Query's ordering constraint. + */ +export declare function newQueryComparator(query: Query): (d1: Document, d2: Document) => number; +export declare function compareDocs(orderBy: OrderBy, d1: Document, d2: Document): number; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/snapshot_version.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/snapshot_version.d.ts new file mode 100644 index 0000000..10c508b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/snapshot_version.d.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Timestamp } from '../lite-api/timestamp'; +/** + * A version of a document in Firestore. This corresponds to the version + * timestamp, such as update_time or read_time. + */ +export declare class SnapshotVersion { + private timestamp; + static fromTimestamp(value: Timestamp): SnapshotVersion; + static min(): SnapshotVersion; + static max(): SnapshotVersion; + private constructor(); + compareTo(other: SnapshotVersion): number; + isEqual(other: SnapshotVersion): boolean; + /** Returns a number representation of the version for use in spec tests. */ + toMicroseconds(): number; + toString(): string; + toTimestamp(): Timestamp; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/sync_engine.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/sync_engine.d.ts new file mode 100644 index 0000000..2c28d31 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/sync_engine.d.ts @@ -0,0 +1,37 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * SyncEngine is the central controller in the client SDK architecture. It is + * the glue code between the EventManager, LocalStore, and RemoteStore. Some of + * SyncEngine's responsibilities include: + * 1. Coordinating client requests and remote events between the EventManager + * and the local and remote data stores. + * 2. Managing a View object for each query, providing the unified view between + * the local and remote data stores. + * 3. Notifying the RemoteStore when the LocalStore has new mutations in its + * queue that need sending to the backend. + * + * The SyncEngine’s methods should only ever be called by methods running in the + * global async queue. + * + * PORTING NOTE: On Web, SyncEngine does not have an explicit subscribe() + * function. Instead, it directly depends on EventManager's tree-shakeable API + * (via `ensureWatchStream()`). + */ +export interface SyncEngine { + isPrimaryClient: boolean; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/sync_engine_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/sync_engine_impl.d.ts new file mode 100644 index 0000000..0d2aef9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/sync_engine_impl.d.ts @@ -0,0 +1,255 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { LoadBundleTask } from '../api/bundle'; +import { User } from '../auth/user'; +import { LocalStore } from '../local/local_store'; +import { ReferenceSet } from '../local/reference_set'; +import { ClientId, SharedClientState } from '../local/shared_client_state'; +import { QueryTargetState } from '../local/shared_client_state_syncer'; +import { DocumentKeySet, DocumentMap } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { Mutation } from '../model/mutation'; +import { MutationBatchResult } from '../model/mutation_batch'; +import { RemoteEvent } from '../remote/remote_event'; +import { RemoteStore } from '../remote/remote_store'; +import { BundleReader } from '../util/bundle_reader'; +import { FirestoreError } from '../util/error'; +import { ObjectMap } from '../util/obj_map'; +import { Deferred } from '../util/promise'; +import { SortedMap } from '../util/sorted_map'; +import { EventManager } from './event_manager'; +import { Query } from './query'; +import { SyncEngine } from './sync_engine'; +import { TargetIdGenerator } from './target_id_generator'; +import { BatchId, MutationBatchState, OnlineState, OnlineStateSource, TargetId } from './types'; +import { View } from './view'; +import { ViewSnapshot } from './view_snapshot'; +/** + * QueryView contains all of the data that SyncEngine needs to keep track of for + * a particular query. + */ +declare class QueryView { + /** + * The query itself. + */ + query: Query; + /** + * The target number created by the client that is used in the watch + * stream to identify this query. + */ + targetId: TargetId; + /** + * The view is responsible for computing the final merged truth of what + * docs are in the query. It gets notified of local and remote changes, + * and applies the query filters and limits to determine the most correct + * possible results. + */ + view: View; + constructor( + /** + * The query itself. + */ + query: Query, + /** + * The target number created by the client that is used in the watch + * stream to identify this query. + */ + targetId: TargetId, + /** + * The view is responsible for computing the final merged truth of what + * docs are in the query. It gets notified of local and remote changes, + * and applies the query filters and limits to determine the most correct + * possible results. + */ + view: View); +} +/** Tracks a limbo resolution. */ +declare class LimboResolution { + key: DocumentKey; + constructor(key: DocumentKey); + /** + * Set to true once we've received a document. This is used in + * getRemoteKeysForTarget() and ultimately used by WatchChangeAggregator to + * decide whether it needs to manufacture a delete event for the target once + * the target is CURRENT. + */ + receivedDocument: boolean; +} +/** + * A function that updates a QueryView with a set of document changes (and a + * remote event if applicable). + */ +type ApplyDocChangesHandler = (queryView: QueryView, changes: DocumentMap, remoteEvent?: RemoteEvent) => Promise; +/** + * Callbacks implemented by EventManager to handle notifications from + * SyncEngine. + */ +interface SyncEngineListener { + /** Handles new view snapshots. */ + onWatchChange?(snapshots: ViewSnapshot[]): void; + /** Handles the failure of a query. */ + onWatchError?(query: Query, error: FirestoreError): void; +} +/** + * An implementation of `SyncEngine` coordinating with other parts of SDK. + * + * The parts of SyncEngine that act as a callback to RemoteStore need to be + * registered individually. This is done in `syncEngineWrite()` and + * `syncEngineListen()` (as well as `applyPrimaryState()`) as these methods + * serve as entry points to RemoteStore's functionality. + * + * Note: some field defined in this class might have public access level, but + * the class is not exported so they are only accessible from this module. + * This is useful to implement optional features (like bundles) in free + * functions, such that they are tree-shakeable. + */ +declare class SyncEngineImpl implements SyncEngine { + readonly localStore: LocalStore; + readonly remoteStore: RemoteStore; + readonly eventManager: EventManager; + readonly sharedClientState: SharedClientState; + currentUser: User; + readonly maxConcurrentLimboResolutions: number; + syncEngineListener: SyncEngineListener; + /** + * A callback that updates the QueryView based on the provided change. + * + * PORTING NOTE: On other platforms, this logic lives in + * `emitNewSnapshotsAndNotifyLocalStore()`, but on Web it is extracted to + * ensure that all view logic only exists in bundles that include views. + */ + applyDocChanges?: ApplyDocChangesHandler; + queryViewsByQuery: ObjectMap; + queriesByTarget: Map; + /** + * The keys of documents that are in limbo for which we haven't yet started a + * limbo resolution query. The strings in this set are the result of calling + * `key.path.canonicalString()` where `key` is a `DocumentKey` object. + * + * The `Set` type was chosen because it provides efficient lookup and removal + * of arbitrary elements and it also maintains insertion order, providing the + * desired queue-like FIFO semantics. + */ + enqueuedLimboResolutions: Set; + /** + * Keeps track of the target ID for each document that is in limbo with an + * active target. + */ + activeLimboTargetsByKey: SortedMap; + /** + * Keeps track of the information about an active limbo resolution for each + * active target ID that was started for the purpose of limbo resolution. + */ + activeLimboResolutionsByTarget: Map; + limboDocumentRefs: ReferenceSet; + /** Stores user completion handlers, indexed by User and BatchId. */ + mutationUserCallbacks: { + [uidKey: string]: SortedMap>; + }; + /** Stores user callbacks waiting for all pending writes to be acknowledged. */ + pendingWritesCallbacks: Map[]>; + limboTargetIdGenerator: TargetIdGenerator; + onlineState: OnlineState; + _isPrimaryClient: undefined | boolean; + constructor(localStore: LocalStore, remoteStore: RemoteStore, eventManager: EventManager, sharedClientState: SharedClientState, currentUser: User, maxConcurrentLimboResolutions: number); + get isPrimaryClient(): boolean; +} +export declare function newSyncEngine(localStore: LocalStore, remoteStore: RemoteStore, eventManager: EventManager, sharedClientState: SharedClientState, currentUser: User, maxConcurrentLimboResolutions: number, isPrimary: boolean): SyncEngine; +/** + * Initiates the new listen, resolves promise when listen enqueued to the + * server. All the subsequent view snapshots or errors are sent to the + * subscribed handlers. Returns the initial snapshot. + */ +export declare function syncEngineListen(syncEngine: SyncEngine, query: Query, shouldListenToRemote?: boolean): Promise; +/** Query has been listening to the cache, and tries to initiate the remote store listen */ +export declare function triggerRemoteStoreListen(syncEngine: SyncEngine, query: Query): Promise; +/** Stops listening to the query. */ +export declare function syncEngineUnlisten(syncEngine: SyncEngine, query: Query, shouldUnlistenToRemote: boolean): Promise; +/** Unlistens to the remote store while still listening to the cache. */ +export declare function triggerRemoteStoreUnlisten(syncEngine: SyncEngine, query: Query): Promise; +/** + * Initiates the write of local mutation batch which involves adding the + * writes to the mutation queue, notifying the remote store about new + * mutations and raising events for any changes this write caused. + * + * The promise returned by this call is resolved when the above steps + * have completed, *not* when the write was acked by the backend. The + * userCallback is resolved once the write was acked/rejected by the + * backend (or failed locally for any other reason). + */ +export declare function syncEngineWrite(syncEngine: SyncEngine, batch: Mutation[], userCallback: Deferred): Promise; +/** + * Applies one remote event to the sync engine, notifying any views of the + * changes, and releasing any pending mutation batches that would become + * visible because of the snapshot version the remote event contains. + */ +export declare function syncEngineApplyRemoteEvent(syncEngine: SyncEngine, remoteEvent: RemoteEvent): Promise; +/** + * Applies an OnlineState change to the sync engine and notifies any views of + * the change. + */ +export declare function syncEngineApplyOnlineStateChange(syncEngine: SyncEngine, onlineState: OnlineState, source: OnlineStateSource): void; +/** + * Rejects the listen for the given targetID. This can be triggered by the + * backend for any active target. + * + * @param syncEngine - The sync engine implementation. + * @param targetId - The targetID corresponds to one previously initiated by the + * user as part of TargetData passed to listen() on RemoteStore. + * @param err - A description of the condition that has forced the rejection. + * Nearly always this will be an indication that the user is no longer + * authorized to see the data matching the target. + */ +export declare function syncEngineRejectListen(syncEngine: SyncEngine, targetId: TargetId, err: FirestoreError): Promise; +export declare function syncEngineApplySuccessfulWrite(syncEngine: SyncEngine, mutationBatchResult: MutationBatchResult): Promise; +export declare function syncEngineRejectFailedWrite(syncEngine: SyncEngine, batchId: BatchId, error: FirestoreError): Promise; +/** + * Registers a user callback that resolves when all pending mutations at the moment of calling + * are acknowledged . + */ +export declare function syncEngineRegisterPendingWritesCallback(syncEngine: SyncEngine, callback: Deferred): Promise; +export declare function syncEngineGetActiveLimboDocumentResolutions(syncEngine: SyncEngine): SortedMap; +export declare function syncEngineGetEnqueuedLimboDocumentResolutions(syncEngine: SyncEngine): Set; +export declare function syncEngineEmitNewSnapsAndNotifyLocalStore(syncEngine: SyncEngine, changes: DocumentMap, remoteEvent?: RemoteEvent): Promise; +export declare function syncEngineHandleCredentialChange(syncEngine: SyncEngine, user: User): Promise; +export declare function syncEngineGetRemoteKeysForTarget(syncEngine: SyncEngine, targetId: TargetId): DocumentKeySet; +/** + * Retrieves newly changed documents from remote document cache and raises + * snapshots if needed. + */ +export declare function syncEngineSynchronizeWithChangedDocuments(syncEngine: SyncEngine, collectionGroup: string): Promise; +/** Applies a mutation state to an existing batch. */ +export declare function syncEngineApplyBatchState(syncEngine: SyncEngine, batchId: BatchId, batchState: MutationBatchState, error?: FirestoreError): Promise; +/** Applies a query target change from a different tab. */ +export declare function syncEngineApplyPrimaryState(syncEngine: SyncEngine, isPrimary: boolean): Promise; +/** Returns the IDs of the clients that are currently active. */ +export declare function syncEngineGetActiveClients(syncEngine: SyncEngine): Promise; +/** Applies a query target change from a different tab. */ +export declare function syncEngineApplyTargetState(syncEngine: SyncEngine, targetId: TargetId, state: QueryTargetState, error?: FirestoreError): Promise; +/** Adds or removes Watch targets for queries from different tabs. */ +export declare function syncEngineApplyActiveTargetsChange(syncEngine: SyncEngine, added: TargetId[], removed: TargetId[]): Promise; +export declare function syncEngineEnsureWriteCallbacks(syncEngine: SyncEngine): SyncEngineImpl; +/** + * Loads a Firestore bundle into the SDK. The returned promise resolves when + * the bundle finished loading. + * + * @param syncEngine - SyncEngine to use. + * @param bundleReader - Bundle to load into the SDK. + * @param task - LoadBundleTask used to update the loading progress to public API. + */ +export declare function syncEngineLoadBundle(syncEngine: SyncEngine, bundleReader: BundleReader, task: LoadBundleTask): void; +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/target.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/target.d.ts new file mode 100644 index 0000000..fcfed20 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/target.d.ts @@ -0,0 +1,89 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FieldIndex } from '../model/field_index'; +import { FieldPath, ResourcePath } from '../model/path'; +import { Value as ProtoValue } from '../protos/firestore_proto_api'; +import { Bound } from './bound'; +import { Filter, FieldFilter } from './filter'; +import { OrderBy } from './order_by'; +/** + * A Target represents the WatchTarget representation of a Query, which is used + * by the LocalStore and the RemoteStore to keep track of and to execute + * backend queries. While a Query can represent multiple Targets, each Targets + * maps to a single WatchTarget in RemoteStore and a single TargetData entry + * in persistence. + */ +export interface Target { + readonly path: ResourcePath; + readonly collectionGroup: string | null; + readonly orderBy: OrderBy[]; + readonly filters: Filter[]; + readonly limit: number | null; + readonly startAt: Bound | null; + readonly endAt: Bound | null; +} +export declare class TargetImpl implements Target { + readonly path: ResourcePath; + readonly collectionGroup: string | null; + readonly orderBy: OrderBy[]; + readonly filters: Filter[]; + readonly limit: number | null; + readonly startAt: Bound | null; + readonly endAt: Bound | null; + memoizedCanonicalId: string | null; + constructor(path: ResourcePath, collectionGroup?: string | null, orderBy?: OrderBy[], filters?: Filter[], limit?: number | null, startAt?: Bound | null, endAt?: Bound | null); +} +/** + * Initializes a Target with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + * + * NOTE: you should always construct `Target` from `Query.toTarget` instead of + * using this factory method, because `Query` provides an implicit `orderBy` + * property. + */ +export declare function newTarget(path: ResourcePath, collectionGroup?: string | null, orderBy?: OrderBy[], filters?: Filter[], limit?: number | null, startAt?: Bound | null, endAt?: Bound | null): Target; +export declare function canonifyTarget(target: Target): string; +export declare function stringifyTarget(target: Target): string; +export declare function targetEquals(left: Target, right: Target): boolean; +export declare function targetIsDocumentTarget(target: Target): boolean; +/** Returns the field filters that target the given field path. */ +export declare function targetGetFieldFiltersForPath(target: Target, path: FieldPath): FieldFilter[]; +/** + * Returns the values that are used in ARRAY_CONTAINS or ARRAY_CONTAINS_ANY + * filters. Returns `null` if there are no such filters. + */ +export declare function targetGetArrayValues(target: Target, fieldIndex: FieldIndex): ProtoValue[] | null; +/** + * Returns the list of values that are used in != or NOT_IN filters. Returns + * `null` if there are no such filters. + */ +export declare function targetGetNotInValues(target: Target, fieldIndex: FieldIndex): ProtoValue[] | null; +/** + * Returns a lower bound of field values that can be used as a starting point to + * scan the index defined by `fieldIndex`. Returns `MIN_VALUE` if no lower bound + * exists. + */ +export declare function targetGetLowerBound(target: Target, fieldIndex: FieldIndex): Bound; +/** + * Returns an upper bound of field values that can be used as an ending point + * when scanning the index defined by `fieldIndex`. Returns `MAX_VALUE` if no + * upper bound exists. + */ +export declare function targetGetUpperBound(target: Target, fieldIndex: FieldIndex): Bound; +/** Returns the number of segments of a perfect index for this target. */ +export declare function targetGetSegmentCount(target: Target): number; +export declare function targetHasLimit(target: Target): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/target_id_generator.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/target_id_generator.d.ts new file mode 100644 index 0000000..7a00fcd --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/target_id_generator.d.ts @@ -0,0 +1,38 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { TargetId } from './types'; +/** + * Generates monotonically increasing target IDs for sending targets to the + * watch stream. + * + * The client constructs two generators, one for the target cache, and one for + * for the sync engine (to generate limbo documents targets). These + * generators produce non-overlapping IDs (by using even and odd IDs + * respectively). + * + * By separating the target ID space, the query cache can generate target IDs + * that persist across client restarts, while sync engine can independently + * generate in-memory target IDs that are transient and can be reused after a + * restart. + */ +export declare class TargetIdGenerator { + private lastId; + constructor(lastId: number); + next(): TargetId; + static forTargetCache(): TargetIdGenerator; + static forSyncEngine(): TargetIdGenerator; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/transaction.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/transaction.d.ts new file mode 100644 index 0000000..4a982e9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/transaction.d.ts @@ -0,0 +1,60 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ParsedSetData, ParsedUpdateData } from '../lite-api/user_data_reader'; +import { Document } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { Datastore } from '../remote/datastore'; +/** + * Internal transaction object responsible for accumulating the mutations to + * perform and the base versions for any documents read. + */ +export declare class Transaction { + private datastore; + private readVersions; + private mutations; + private committed; + /** + * A deferred usage error that occurred previously in this transaction that + * will cause the transaction to fail once it actually commits. + */ + private lastTransactionError; + /** + * Set of documents that have been written in the transaction. + * + * When there's more than one write to the same key in a transaction, any + * writes after the first are handled differently. + */ + private writtenDocs; + constructor(datastore: Datastore); + lookup(keys: DocumentKey[]): Promise; + set(key: DocumentKey, data: ParsedSetData): void; + update(key: DocumentKey, data: ParsedUpdateData): void; + delete(key: DocumentKey): void; + commit(): Promise; + private recordVersion; + /** + * Returns the version of this document when it was read in this transaction, + * as a precondition, or no precondition if it was not read. + */ + private precondition; + /** + * Returns the precondition for a document if the operation is an update. + */ + private preconditionForUpdate; + private write; + private ensureCommitNotCalled; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/transaction_options.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/transaction_options.d.ts new file mode 100644 index 0000000..bf52930 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/transaction_options.d.ts @@ -0,0 +1,25 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare const DEFAULT_TRANSACTION_OPTIONS: TransactionOptions; +/** + * Options to customize transaction behavior. + */ +export declare interface TransactionOptions { + /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */ + readonly maxAttempts: number; +} +export declare function validateTransactionOptions(options: TransactionOptions): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/transaction_runner.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/transaction_runner.d.ts new file mode 100644 index 0000000..794c7d3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/transaction_runner.d.ts @@ -0,0 +1,41 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Datastore } from '../remote/datastore'; +import { AsyncQueue } from '../util/async_queue'; +import { Deferred } from '../util/promise'; +import { Transaction } from './transaction'; +import { TransactionOptions } from './transaction_options'; +/** + * TransactionRunner encapsulates the logic needed to run and retry transactions + * with backoff. + */ +export declare class TransactionRunner { + private readonly asyncQueue; + private readonly datastore; + private readonly options; + private readonly updateFunction; + private readonly deferred; + private attemptsRemaining; + private backoff; + constructor(asyncQueue: AsyncQueue, datastore: Datastore, options: TransactionOptions, updateFunction: (transaction: Transaction) => Promise, deferred: Deferred); + /** Runs the transaction and sets the result on deferred. */ + run(): void; + private runWithBackOff; + private tryRunUpdateFunction; + private handleTransactionError; + private isRetryableTransactionError; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/types.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/types.d.ts new file mode 100644 index 0000000..6c3b8ca --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/types.d.ts @@ -0,0 +1,65 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * BatchID is a locally assigned ID for a batch of mutations that have been + * applied. + */ +export type BatchId = number; +/** + * A locally-assigned ID used to refer to a target being watched via the + * Watch service. + */ +export type TargetId = number; +export type ListenSequenceNumber = number; +/** The different states of a mutation batch. */ +export type MutationBatchState = 'pending' | 'acknowledged' | 'rejected'; +/** + * Describes the online state of the Firestore client. Note that this does not + * indicate whether or not the remote store is trying to connect or not. This is + * primarily used by the View / EventManager code to change their behavior while + * offline (e.g. get() calls shouldn't wait for data from the server and + * snapshot events should set metadata.isFromCache=true). + * + * The string values should not be changed since they are persisted in + * WebStorage. + */ +export declare const enum OnlineState { + /** + * The Firestore client is in an unknown online state. This means the client + * is either not actively trying to establish a connection or it is currently + * trying to establish a connection, but it has not succeeded or failed yet. + * Higher-level components should not operate in offline mode. + */ + Unknown = "Unknown", + /** + * The client is connected and the connections are healthy. This state is + * reached after a successful connection and there has been at least one + * successful message received from the backends. + */ + Online = "Online", + /** + * The client is either trying to establish a connection but failing, or it + * has been explicitly marked offline via a call to disableNetwork(). + * Higher-level components should operate in offline mode. + */ + Offline = "Offline" +} +/** The source of an online state event. */ +export declare const enum OnlineStateSource { + RemoteStore = 0, + SharedClientState = 1 +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/version.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/version.d.ts new file mode 100644 index 0000000..9edc565 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/version.d.ts @@ -0,0 +1,18 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare let SDK_VERSION: string; +export declare function setSDKVersion(version: string): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/view.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/view.d.ts new file mode 100644 index 0000000..57680a5 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/view.d.ts @@ -0,0 +1,152 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { QueryResult } from '../local/local_store_impl'; +import { DocumentKeySet, DocumentMap } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { DocumentSet } from '../model/document_set'; +import { TargetChange } from '../remote/remote_event'; +import { Query } from './query'; +import { OnlineState } from './types'; +import { DocumentChangeSet, ViewSnapshot } from './view_snapshot'; +export type LimboDocumentChange = AddedLimboDocument | RemovedLimboDocument; +export declare class AddedLimboDocument { + key: DocumentKey; + constructor(key: DocumentKey); +} +export declare class RemovedLimboDocument { + key: DocumentKey; + constructor(key: DocumentKey); +} +/** The result of applying a set of doc changes to a view. */ +export interface ViewDocumentChanges { + /** The new set of docs that should be in the view. */ + documentSet: DocumentSet; + /** The diff of these docs with the previous set of docs. */ + changeSet: DocumentChangeSet; + /** + * Whether the set of documents passed in was not sufficient to calculate the + * new state of the view and there needs to be another pass based on the + * local cache. + */ + needsRefill: boolean; + mutatedKeys: DocumentKeySet; +} +export interface ViewChange { + snapshot?: ViewSnapshot; + limboChanges: LimboDocumentChange[]; +} +/** + * View is responsible for computing the final merged truth of what docs are in + * a query. It gets notified of local and remote changes to docs, and applies + * the query filters and limits to determine the most correct possible results. + */ +export declare class View { + private query; + /** Documents included in the remote target */ + private _syncedDocuments; + private syncState; + private hasCachedResults; + /** + * A flag whether the view is current with the backend. A view is considered + * current after it has seen the current flag from the backend and did not + * lose consistency within the watch stream (e.g. because of an existence + * filter mismatch). + */ + private current; + private documentSet; + /** Documents in the view but not in the remote target */ + private limboDocuments; + /** Document Keys that have local changes */ + private mutatedKeys; + /** Query comparator that defines the document order in this view. */ + private docComparator; + constructor(query: Query, + /** Documents included in the remote target */ + _syncedDocuments: DocumentKeySet); + /** + * The set of remote documents that the server has told us belongs to the target associated with + * this view. + */ + get syncedDocuments(): DocumentKeySet; + /** + * Iterates over a set of doc changes, applies the query limit, and computes + * what the new results should be, what the changes were, and whether we may + * need to go back to the local cache for more results. Does not make any + * changes to the view. + * @param docChanges - The doc changes to apply to this view. + * @param previousChanges - If this is being called with a refill, then start + * with this set of docs and changes instead of the current view. + * @returns a new set of docs, changes, and refill flag. + */ + computeDocChanges(docChanges: DocumentMap, previousChanges?: ViewDocumentChanges): ViewDocumentChanges; + private shouldWaitForSyncedDocument; + /** + * Updates the view with the given ViewDocumentChanges and optionally updates + * limbo docs and sync state from the provided target change. + * @param docChanges - The set of changes to make to the view's docs. + * @param limboResolutionEnabled - Whether to update limbo documents based on + * this change. + * @param targetChange - A target change to apply for computing limbo docs and + * sync state. + * @param targetIsPendingReset - Whether the target is pending to reset due to + * existence filter mismatch. If not explicitly specified, it is treated + * equivalently to `false`. + * @returns A new ViewChange with the given docs, changes, and sync state. + */ + applyChanges(docChanges: ViewDocumentChanges, limboResolutionEnabled: boolean, targetChange?: TargetChange, targetIsPendingReset?: boolean): ViewChange; + /** + * Applies an OnlineState change to the view, potentially generating a + * ViewChange if the view's syncState changes as a result. + */ + applyOnlineStateChange(onlineState: OnlineState): ViewChange; + /** + * Returns whether the doc for the given key should be in limbo. + */ + private shouldBeInLimbo; + /** + * Updates syncedDocuments, current, and limbo docs based on the given change. + * Returns the list of changes to which docs are in limbo. + */ + private applyTargetChange; + private updateLimboDocuments; + /** + * Update the in-memory state of the current view with the state read from + * persistence. + * + * We update the query view whenever a client's primary status changes: + * - When a client transitions from primary to secondary, it can miss + * LocalStorage updates and its query views may temporarily not be + * synchronized with the state on disk. + * - For secondary to primary transitions, the client needs to update the list + * of `syncedDocuments` since secondary clients update their query views + * based purely on synthesized RemoteEvents. + * + * @param queryResult.documents - The documents that match the query according + * to the LocalStore. + * @param queryResult.remoteKeys - The keys of the documents that match the + * query according to the backend. + * + * @returns The ViewChange that resulted from this synchronization. + */ + synchronizeWithPersistedState(queryResult: QueryResult): ViewChange; + /** + * Returns a view snapshot as if this query was just listened to. Contains + * a document add for every existing document and the `fromCache` and + * `hasPendingWrites` status of the already established view. + */ + computeInitialSnapshot(): ViewSnapshot; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/view_snapshot.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/view_snapshot.d.ts new file mode 100644 index 0000000..8b284df --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/core/view_snapshot.d.ts @@ -0,0 +1,59 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentKeySet } from '../model/collections'; +import { Document } from '../model/document'; +import { DocumentSet } from '../model/document_set'; +import { Query } from './query'; +export declare const enum ChangeType { + Added = 0, + Removed = 1, + Modified = 2, + Metadata = 3 +} +export interface DocumentViewChange { + type: ChangeType; + doc: Document; +} +export declare const enum SyncState { + Local = 0, + Synced = 1 +} +/** + * DocumentChangeSet keeps track of a set of changes to docs in a query, merging + * duplicate events for the same doc. + */ +export declare class DocumentChangeSet { + private changeMap; + track(change: DocumentViewChange): void; + getChanges(): DocumentViewChange[]; +} +export declare class ViewSnapshot { + readonly query: Query; + readonly docs: DocumentSet; + readonly oldDocs: DocumentSet; + readonly docChanges: DocumentViewChange[]; + readonly mutatedKeys: DocumentKeySet; + readonly fromCache: boolean; + readonly syncStateChanged: boolean; + readonly excludesMetadataChanges: boolean; + readonly hasCachedResults: boolean; + constructor(query: Query, docs: DocumentSet, oldDocs: DocumentSet, docChanges: DocumentViewChange[], mutatedKeys: DocumentKeySet, fromCache: boolean, syncStateChanged: boolean, excludesMetadataChanges: boolean, hasCachedResults: boolean); + /** Returns a view snapshot as if all documents in the snapshot were added. */ + static fromInitialDocuments(query: Query, documents: DocumentSet, mutatedKeys: DocumentKeySet, fromCache: boolean, hasCachedResults: boolean): ViewSnapshot; + get hasPendingWrites(): boolean; + isEqual(other: ViewSnapshot): boolean; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index.d.ts new file mode 100644 index 0000000..0541f3f --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index.d.ts @@ -0,0 +1,28 @@ +/** + * Cloud Firestore + * + * @packageDocumentation + */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Firestore } from './api/database'; +export * from './api'; +declare module '@firebase/component' { + interface NameServiceMapping { + 'firestore': Firestore; + } +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index.node.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index.node.d.ts new file mode 100644 index 0000000..952da59 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index.node.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from './api'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index.rn.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index.rn.d.ts new file mode 100644 index 0000000..952da59 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index.rn.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from './api'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/directional_index_byte_encoder.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/directional_index_byte_encoder.d.ts new file mode 100644 index 0000000..0038f37 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/directional_index_byte_encoder.d.ts @@ -0,0 +1,24 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ByteString } from '../util/byte_string'; +/** An index value encoder. */ +export interface DirectionalIndexByteEncoder { + writeBytes(value: ByteString): void; + writeString(value: string): void; + writeNumber(value: number): void; + writeInfinity(): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/firestore_index_value_writer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/firestore_index_value_writer.d.ts new file mode 100644 index 0000000..01298c6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/firestore_index_value_writer.d.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Value } from '../protos/firestore_proto_api'; +import { DirectionalIndexByteEncoder } from './directional_index_byte_encoder'; +/** Firestore index value writer. */ +export declare class FirestoreIndexValueWriter { + static INSTANCE: FirestoreIndexValueWriter; + private constructor(); + /** Writes an index value. */ + writeIndexValue(value: Value, encoder: DirectionalIndexByteEncoder): void; + private writeIndexValueAux; + private writeIndexString; + private writeUnlabeledIndexString; + private writeIndexMap; + private writeIndexVector; + private writeIndexArray; + private writeIndexEntityRef; + private writeValueTypeLabel; + private writeTruncationMarker; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/index_byte_encoder.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/index_byte_encoder.d.ts new file mode 100644 index 0000000..dce4631 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/index_byte_encoder.d.ts @@ -0,0 +1,31 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { IndexKind } from '../model/field_index'; +import { DirectionalIndexByteEncoder } from './directional_index_byte_encoder'; +/** + * Implements `DirectionalIndexByteEncoder` using `OrderedCodeWriter` for the + * actual encoding. + */ +export declare class IndexByteEncoder { + private orderedCode; + private ascending; + private descending; + seed(encodedBytes: Uint8Array): void; + forKind(kind: IndexKind): DirectionalIndexByteEncoder; + encodedBytes(): Uint8Array; + reset(): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/index_entry.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/index_entry.d.ts new file mode 100644 index 0000000..fe89202 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/index_entry.d.ts @@ -0,0 +1,49 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DbIndexEntry } from '../local/indexeddb_schema'; +import { DbIndexEntryKey, KeySafeBytes } from '../local/indexeddb_sentinels'; +import { DocumentKey } from '../model/document_key'; +/** Represents an index entry saved by the SDK in persisted storage. */ +export declare class IndexEntry { + readonly _indexId: number; + readonly _documentKey: DocumentKey; + readonly _arrayValue: Uint8Array; + readonly _directionalValue: Uint8Array; + constructor(_indexId: number, _documentKey: DocumentKey, _arrayValue: Uint8Array, _directionalValue: Uint8Array); + /** + * Returns an IndexEntry entry that sorts immediately after the current + * directional value. + */ + successor(): IndexEntry; + dbIndexEntry(uid: string, orderedDocumentKey: Uint8Array, documentKey: DocumentKey): DbIndexEntry; + dbIndexEntryKey(uid: string, orderedDocumentKey: Uint8Array, documentKey: DocumentKey): DbIndexEntryKey; +} +export declare function indexEntryComparator(left: IndexEntry, right: IndexEntry): number; +export declare function compareByteArrays(left: Uint8Array, right: Uint8Array): number; +/** + * Workaround for WebKit bug: https://bugs.webkit.org/show_bug.cgi?id=292721 + * Create a key safe representation of Uint8Array values. + * If the browser is detected as Safari or WebKit, then + * the input array will be converted to "sortable byte string". + * Otherwise, the input array will be returned in its original type. + */ +export declare function encodeKeySafeBytes(array: Uint8Array): KeySafeBytes; +/** + * Reverts the key safe representation of Uint8Array (created by + * encodeKeySafeBytes) to a normal Uint8Array. + */ +export declare function decodeKeySafeBytes(input: KeySafeBytes): Uint8Array; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/ordered_code_writer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/ordered_code_writer.d.ts new file mode 100644 index 0000000..be345f7 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/index/ordered_code_writer.d.ts @@ -0,0 +1,60 @@ +import { ByteString } from '../util/byte_string'; +/** + * Counts the number of zeros in a byte. + * + * Visible for testing. + */ +export declare function numberOfLeadingZerosInByte(x: number): number; +/** + * OrderedCodeWriter is a minimal-allocation implementation of the writing + * behavior defined by the backend. + * + * The code is ported from its Java counterpart. + */ +export declare class OrderedCodeWriter { + buffer: Uint8Array; + position: number; + writeBytesAscending(value: ByteString): void; + writeBytesDescending(value: ByteString): void; + /** Writes utf8 bytes into this byte sequence, ascending. */ + writeUtf8Ascending(sequence: string): void; + /** Writes utf8 bytes into this byte sequence, descending */ + writeUtf8Descending(sequence: string): void; + writeNumberAscending(val: number): void; + writeNumberDescending(val: number): void; + /** + * Writes the "infinity" byte sequence that sorts after all other byte + * sequences written in ascending order. + */ + writeInfinityAscending(): void; + /** + * Writes the "infinity" byte sequence that sorts before all other byte + * sequences written in descending order. + */ + writeInfinityDescending(): void; + /** + * Resets the buffer such that it is the same as when it was newly + * constructed. + */ + reset(): void; + seed(encodedBytes: Uint8Array): void; + /** Makes a copy of the encoded bytes in this buffer. */ + encodedBytes(): Uint8Array; + /** + * Encodes `val` into an encoding so that the order matches the IEEE 754 + * floating-point comparison results with the following exceptions: + * -0.0 < 0.0 + * all non-NaN < NaN + * NaN = NaN + */ + private toOrderedBits; + /** Writes a single byte ascending to the buffer. */ + private writeByteAscending; + /** Writes a single byte descending to the buffer. */ + private writeByteDescending; + private writeSeparatorAscending; + private writeSeparatorDescending; + private writeEscapedByteAscending; + private writeEscapedByteDescending; + private ensureAvailable; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/aggregate.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/aggregate.d.ts new file mode 100644 index 0000000..3927021 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/aggregate.d.ts @@ -0,0 +1,100 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AggregateField, AggregateQuerySnapshot, AggregateSpec } from './aggregate_types'; +import { FieldPath } from './field_path'; +import { DocumentData, Query } from './reference'; +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ +export declare function getCount(query: Query): Promise; +}, AppModelType, DbModelType>>; +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregate(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ +export declare function getAggregate(query: Query, aggregateSpec: AggregateSpecType): Promise>; +/** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ +export declare function sum(field: string | FieldPath): AggregateField; +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ +export declare function average(field: string | FieldPath): AggregateField; +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ +export declare function count(): AggregateField; +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ +export declare function aggregateFieldEqual(left: AggregateField, right: AggregateField): boolean; +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ +export declare function aggregateQuerySnapshotEqual(left: AggregateQuerySnapshot, right: AggregateQuerySnapshot): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/aggregate_types.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/aggregate_types.d.ts new file mode 100644 index 0000000..453dff1 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/aggregate_types.d.ts @@ -0,0 +1,86 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AggregateType } from '../core/aggregate'; +import { FieldPath as InternalFieldPath } from '../model/path'; +import { ApiClientObjectMap, Value } from '../protos/firestore_proto_api'; +import { average, count, sum } from './aggregate'; +import { DocumentData, Query } from './reference'; +import { AbstractUserDataWriter } from './user_data_writer'; +export { AggregateType }; +/** + * Represents an aggregation that can be performed by Firestore. + */ +export declare class AggregateField { + readonly _internalFieldPath?: InternalFieldPath | undefined; + /** A type string to uniquely identify instances of this class. */ + readonly type = "AggregateField"; + /** Indicates the aggregation operation of this AggregateField. */ + readonly aggregateType: AggregateType; + /** + * Create a new AggregateField + * @param aggregateType Specifies the type of aggregation operation to perform. + * @param _internalFieldPath Optionally specifies the field that is aggregated. + * @internal + */ + constructor(aggregateType?: AggregateType, _internalFieldPath?: InternalFieldPath | undefined); +} +/** + * The union of all `AggregateField` types that are supported by Firestore. + */ +export type AggregateFieldType = ReturnType | ReturnType | ReturnType; +/** + * Specifies a set of aggregations and their aliases. + */ +export interface AggregateSpec { + [field: string]: AggregateFieldType; +} +/** + * A type whose keys are taken from an `AggregateSpec`, and whose values are the + * result of the aggregation performed by the corresponding `AggregateField` + * from the input `AggregateSpec`. + */ +export type AggregateSpecData = { + [P in keyof T]: T[P] extends AggregateField ? U : never; +}; +/** + * The results of executing an aggregation query. + */ +export declare class AggregateQuerySnapshot { + private readonly _userDataWriter; + private readonly _data; + /** A type string to uniquely identify instances of this class. */ + readonly type = "AggregateQuerySnapshot"; + /** + * The underlying query over which the aggregations recorded in this + * `AggregateQuerySnapshot` were performed. + */ + readonly query: Query; + /** @hideconstructor */ + constructor(query: Query, _userDataWriter: AbstractUserDataWriter, _data: ApiClientObjectMap); + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ + data(): AggregateSpecData; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/bytes.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/bytes.d.ts new file mode 100644 index 0000000..e4b8e09 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/bytes.d.ts @@ -0,0 +1,83 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ByteString } from '../util/byte_string'; +import { Property } from '../util/json_validation'; +/** + * An immutable object representing an array of bytes. + */ +export declare class Bytes { + _byteString: ByteString; + /** @hideconstructor */ + constructor(byteString: ByteString); + /** + * Creates a new `Bytes` object from the given Base64 string, converting it to + * bytes. + * + * @param base64 - The Base64 string used to create the `Bytes` object. + */ + static fromBase64String(base64: string): Bytes; + /** + * Creates a new `Bytes` object from the given Uint8Array. + * + * @param array - The Uint8Array used to create the `Bytes` object. + */ + static fromUint8Array(array: Uint8Array): Bytes; + /** + * Returns the underlying bytes as a Base64-encoded string. + * + * @returns The Base64-encoded string created from the `Bytes` object. + */ + toBase64(): string; + /** + * Returns the underlying bytes in a new `Uint8Array`. + * + * @returns The Uint8Array created from the `Bytes` object. + */ + toUint8Array(): Uint8Array; + /** + * Returns a string representation of the `Bytes` object. + * + * @returns A string representation of the `Bytes` object. + */ + toString(): string; + /** + * Returns true if this `Bytes` object is equal to the provided one. + * + * @param other - The `Bytes` object to compare against. + * @returns true if this `Bytes` object is equal to the provided one. + */ + isEqual(other: Bytes): boolean; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + bytes: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `Bytes` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}. + * + * @param json a JSON object represention of a `Bytes` instance + * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): Bytes; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/components.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/components.d.ts new file mode 100644 index 0000000..a710e68 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/components.d.ts @@ -0,0 +1,49 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { _FirebaseService } from '@firebase/app'; +import { CredentialsProvider } from '../api/credentials'; +import { User } from '../auth/user'; +import { DatabaseId, DatabaseInfo } from '../core/database_info'; +import { Datastore } from '../remote/datastore'; +import { FirestoreSettingsImpl } from './settings'; +export declare const LOG_TAG = "ComponentProvider"; +/** + * An interface implemented by FirebaseFirestore that provides compatibility + * with the usage in this file. + * + * This interface mainly exists to remove a cyclic dependency. + */ +export interface FirestoreService extends _FirebaseService { + _authCredentials: CredentialsProvider; + _appCheckCredentials: CredentialsProvider; + _persistenceKey: string; + _databaseId: DatabaseId; + _terminated: boolean; + _freezeSettings(): FirestoreSettingsImpl; +} +/** + * Returns an initialized and started Datastore for the given Firestore + * instance. Callers must invoke removeComponents() when the Firestore + * instance is terminated. + */ +export declare function getDatastore(firestore: FirestoreService): Datastore; +/** + * Removes all components associated with the provided instance. Must be called + * when the `Firestore` instance is terminated. + */ +export declare function removeComponents(firestore: FirestoreService): void; +export declare function makeDatabaseInfo(databaseId: DatabaseId, appId: string, persistenceKey: string, settings: FirestoreSettingsImpl): DatabaseInfo; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/database.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/database.d.ts new file mode 100644 index 0000000..988a791 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/database.d.ts @@ -0,0 +1,179 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseApp } from '@firebase/app'; +import { EmulatorMockTokenOptions } from '@firebase/util'; +import { CredentialsProvider } from '../api/credentials'; +import { User } from '../auth/user'; +import { DatabaseId } from '../core/database_info'; +import { FirestoreService } from './components'; +import { FirestoreSettingsImpl, PrivateSettings, FirestoreSettings } from './settings'; +export { EmulatorMockTokenOptions } from '@firebase/util'; +declare module '@firebase/component' { + interface NameServiceMapping { + 'firestore/lite': Firestore; + } +} +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ +export declare class Firestore implements FirestoreService { + _authCredentials: CredentialsProvider; + _appCheckCredentials: CredentialsProvider; + readonly _databaseId: DatabaseId; + readonly _app?: FirebaseApp | undefined; + /** + * Whether it's a Firestore or Firestore Lite instance. + */ + type: 'firestore-lite' | 'firestore'; + readonly _persistenceKey: string; + private _settings; + private _settingsFrozen; + private _emulatorOptions; + private _terminateTask; + /** @hideconstructor */ + constructor(_authCredentials: CredentialsProvider, _appCheckCredentials: CredentialsProvider, _databaseId: DatabaseId, _app?: FirebaseApp | undefined); + /** + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service + * instance. + */ + get app(): FirebaseApp; + get _initialized(): boolean; + get _terminated(): boolean; + _setSettings(settings: PrivateSettings): void; + _getSettings(): FirestoreSettingsImpl; + _getEmulatorOptions(): { + mockUserToken?: EmulatorMockTokenOptions | string; + }; + _freezeSettings(): FirestoreSettingsImpl; + _delete(): Promise; + _restart(): Promise; + /** Returns a JSON-serializable representation of this `Firestore` instance. */ + toJSON(): object; + /** + * Terminates all components used by this client. Subclasses can override + * this method to clean up their own dependencies, but must also call this + * method. + * + * Only ever called once. + */ + protected _terminate(): Promise; +} +/** + * Initializes a new instance of Cloud Firestore with the provided settings. + * Can only be called before any other functions, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will + * be associated. + * @param settings - A settings object to configure the `Firestore` instance. + * @returns A newly initialized `Firestore` instance. + */ +export declare function initializeFirestore(app: FirebaseApp, settings: FirestoreSettings): Firestore; +/** + * Initializes a new instance of Cloud Firestore with the provided settings. + * Can only be called before any other functions, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will + * be associated. + * @param settings - A settings object to configure the `Firestore` instance. + * @param databaseId - The name of the database. + * @returns A newly initialized `Firestore` instance. + * @beta + */ +export declare function initializeFirestore(app: FirebaseApp, settings: FirestoreSettings, databaseId?: string): Firestore; +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @returns The {@link Firestore} instance of the provided app. + */ +export declare function getFirestore(): Firestore; +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @returns The {@link Firestore} instance of the provided app. + */ +export declare function getFirestore(app: FirebaseApp): Firestore; +/** + * Returns the existing {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param databaseId - The name of the database. + * @returns The {@link Firestore} instance of the provided app. + * @beta + */ +export declare function getFirestore(databaseId: string): Firestore; +/** + * Returns the existing {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @param databaseId - The name of the database. + * @returns The {@link Firestore} instance of the provided app. + * @beta + */ +export declare function getFirestore(app: FirebaseApp, databaseId: string): Firestore; +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ +export declare function connectFirestoreEmulator(firestore: Firestore, host: string, port: number, options?: { + mockUserToken?: EmulatorMockTokenOptions | string; +}): void; +/** + * Terminates the provided `Firestore` instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` functions + * may be used. Any other function will throw a `FirestoreError`. Termination + * does not cancel any pending writes, and any promises that are awaiting a + * response from the server will not be resolved. + * + * To restart after termination, create a new instance of `Firestore` with + * {@link (getFirestore:1)}. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all of + * its resources or in combination with {@link clearIndexedDbPersistence} to + * ensure that all local state is destroyed between test runs. + * + * @param firestore - The `Firestore` instance to terminate. + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ +export declare function terminate(firestore: Firestore): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/field_path.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/field_path.d.ts new file mode 100644 index 0000000..38faa8f --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/field_path.d.ts @@ -0,0 +1,48 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FieldPath as InternalFieldPath } from '../model/path'; +/** + * A `FieldPath` refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + * + * Create a `FieldPath` by providing field names. If more than one field + * name is provided, the path will point to a nested field in a document. + */ +export declare class FieldPath { + /** Internal representation of a Firestore field path. */ + readonly _internalPath: InternalFieldPath; + /** + * Creates a `FieldPath` from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames - A list of field names. + */ + constructor(...fieldNames: string[]); + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other - The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ + isEqual(other: FieldPath): boolean; +} +/** + * Returns a special sentinel `FieldPath` to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ +export declare function documentId(): FieldPath; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/field_value.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/field_value.d.ts new file mode 100644 index 0000000..5e44c8e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/field_value.d.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ParseContext } from '../api/parse_context'; +import { FieldTransform } from '../model/mutation'; +/** + * Sentinel values that can be used when writing document fields with `set()` + * or `update()`. + */ +export declare abstract class FieldValue { + _methodName: string; + /** + * @param _methodName - The public API endpoint that returns this class. + * @hideconstructor + */ + constructor(_methodName: string); + /** Compares `FieldValue`s for equality. */ + abstract isEqual(other: FieldValue): boolean; + abstract _toFieldTransform(context: ParseContext): FieldTransform | null; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/field_value_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/field_value_impl.d.ts new file mode 100644 index 0000000..019e460 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/field_value_impl.d.ts @@ -0,0 +1,81 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FieldValue } from './field_value'; +import { VectorValue } from './vector_value'; +/** + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. + */ +export declare function deleteField(): FieldValue; +/** + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to + * include a server-generated timestamp in the written data. + */ +export declare function serverTimestamp(): FieldValue; +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array + * value that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements - The elements to union into the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()`. + */ +export declare function arrayUnion(...elements: unknown[]): FieldValue; +/** + * Returns a special value that can be used with {@link (setDoc:1)} or {@link + * updateDoc:1} that tells the server to remove the given elements from any + * array value that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is not + * already an array it will be overwritten with an empty array. + * + * @param elements - The elements to remove from the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +export declare function arrayRemove(...elements: unknown[]): FieldValue; +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by + * the given value. + * + * If either the operand or the current field value uses floating point + * precision, all arithmetic follows IEEE 754 semantics. If both values are + * integers, values outside of JavaScript's safe number range + * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to + * precision loss. Furthermore, once processed by the Firestore backend, all + * integer operations are capped between -2^63 and 2^63-1. + * + * If the current field value is not of type `number`, or if the field does not + * yet exist, the transformation sets the field to the given value. + * + * @param n - The value to increment by. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +export declare function increment(n: number): FieldValue; +/** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ +export declare function vector(values?: number[]): VectorValue; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/geo_point.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/geo_point.d.ts new file mode 100644 index 0000000..bfe8cd5 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/geo_point.d.ts @@ -0,0 +1,79 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Property } from '../util/json_validation'; +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ +export declare class GeoPoint { + private _lat; + private _long; + /** + * Creates a new immutable `GeoPoint` object with the provided latitude and + * longitude values. + * @param latitude - The latitude as number between -90 and 90. + * @param longitude - The longitude as number between -180 and 180. + */ + constructor(latitude: number, longitude: number); + /** + * The latitude of this `GeoPoint` instance. + */ + get latitude(): number; + /** + * The longitude of this `GeoPoint` instance. + */ + get longitude(): number; + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other - The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ + isEqual(other: GeoPoint): boolean; + /** + * Actually private to JS consumers of our API, so this function is prefixed + * with an underscore. + */ + _compareTo(other: GeoPoint): number; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + latitude: Property<"number">; + longitude: Property<"number">; + }; + /** + * Returns a JSON-serializable representation of this `GeoPoint` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): { + latitude: number; + longitude: number; + type: string; + }; + /** + * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}. + * + * @param json a JSON object represention of a `GeoPoint` instance + * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): GeoPoint; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/query.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/query.d.ts new file mode 100644 index 0000000..9053d9d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/query.d.ts @@ -0,0 +1,404 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Bound } from '../core/bound'; +import { DatabaseId } from '../core/database_info'; +import { CompositeOperator, FieldFilter, Filter, Operator } from '../core/filter'; +import { Direction, OrderBy } from '../core/order_by'; +import { LimitType, Query as InternalQuery } from '../core/query'; +import { Document } from '../model/document'; +import { FieldPath as InternalFieldPath } from '../model/path'; +import { FieldPath } from './field_path'; +import { DocumentData, Query } from './reference'; +import { DocumentSnapshot } from './snapshot'; +import { UserDataReader } from './user_data_reader'; +export declare function validateHasExplicitOrderByForLimitToLast(query: InternalQuery): void; +/** Describes the different query constraints available in this SDK. */ +export type QueryConstraintType = 'where' | 'orderBy' | 'limit' | 'limitToLast' | 'startAt' | 'startAfter' | 'endAt' | 'endBefore'; +/** + * An `AppliableConstraint` is an abstraction of a constraint that can be applied + * to a Firestore query. + */ +export declare abstract class AppliableConstraint { + /** + * Takes the provided {@link Query} and returns a copy of the {@link Query} with this + * {@link AppliableConstraint} applied. + */ + abstract _apply(query: Query): Query; +} +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Firestore query. `QueryConstraint`s are created by invoking {@link where}, + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that + * also contains this `QueryConstraint`. + */ +export declare abstract class QueryConstraint extends AppliableConstraint { + /** The type of this query constraint */ + abstract readonly type: QueryConstraintType; + /** + * Takes the provided {@link Query} and returns a copy of the {@link Query} with this + * {@link AppliableConstraint} applied. + */ + abstract _apply(query: Query): Query; +} +/** + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. + * + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to + * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or + * {@link or}. + * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to + * apply (e.g. {@link orderBy}, {@link limit}). + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query(query: Query, compositeFilter: QueryCompositeFilterConstraint, ...queryConstraints: QueryNonFilterConstraint[]): Query; +/** + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. + * + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param queryConstraints - The list of {@link QueryConstraint}s to apply. + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query(query: Query, ...queryConstraints: QueryConstraint[]): Query; +/** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ +export declare class QueryFieldFilterConstraint extends QueryConstraint { + private readonly _field; + private _op; + private _value; + /** The type of this query constraint */ + readonly type = "where"; + /** + * @internal + */ + protected constructor(_field: InternalFieldPath, _op: Operator, _value: unknown); + static _create(_field: InternalFieldPath, _op: Operator, _value: unknown): QueryFieldFilterConstraint; + _apply(query: Query): Query; + _parse(query: Query): FieldFilter; +} +/** + * Filter conditions in a {@link where} clause are specified using the + * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in', + * 'array-contains-any', and 'not-in'. + */ +export type WhereFilterOp = '<' | '<=' | '==' | '!=' | '>=' | '>' | 'array-contains' | 'in' | 'array-contains-any' | 'not-in'; +/** + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. + * + * @param fieldPath - The path to compare + * @param opStr - The operation string (e.g "<", "<=", "==", "<", + * "<=", "!="). + * @param value - The value for comparison + * @returns The created {@link QueryFieldFilterConstraint}. + */ +export declare function where(fieldPath: string | FieldPath, opStr: WhereFilterOp, value: unknown): QueryFieldFilterConstraint; +/** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ +export declare class QueryCompositeFilterConstraint extends AppliableConstraint { + /** The type of this query constraint */ + readonly type: 'or' | 'and'; + private readonly _queryConstraints; + /** + * @internal + */ + protected constructor( + /** The type of this query constraint */ + type: 'or' | 'and', _queryConstraints: QueryFilterConstraint[]); + static _create(type: 'or' | 'and', _queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; + _parse(query: Query): Filter; + _apply(query: Query): Query; + _getQueryConstraints(): readonly AppliableConstraint[]; + _getOperator(): CompositeOperator; +} +/** + * `QueryNonFilterConstraint` is a helper union type that represents + * QueryConstraints which are used to narrow or order the set of documents, + * but that do not explicitly filter on a document field. + * `QueryNonFilterConstraint`s are created by invoking {@link orderBy}, + * {@link (startAt:1)}, {@link (startAfter:1)}, {@link (endBefore:1)}, {@link (endAt:1)}, + * {@link limit} or {@link limitToLast} and can then be passed to {@link (query:1)} + * to create a new query instance that also contains the `QueryConstraint`. + */ +export type QueryNonFilterConstraint = QueryOrderByConstraint | QueryLimitConstraint | QueryStartAtConstraint | QueryEndAtConstraint; +/** + * `QueryFilterConstraint` is a helper union type that represents + * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}. + */ +export type QueryFilterConstraint = QueryFieldFilterConstraint | QueryCompositeFilterConstraint; +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +export declare function or(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +export declare function and(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; +/** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ +export declare class QueryOrderByConstraint extends QueryConstraint { + private readonly _field; + private _direction; + /** The type of this query constraint */ + readonly type = "orderBy"; + /** + * @internal + */ + protected constructor(_field: InternalFieldPath, _direction: Direction); + static _create(_field: InternalFieldPath, _direction: Direction): QueryOrderByConstraint; + _apply(query: Query): Query; +} +/** + * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc' + * (descending or ascending). + */ +export type OrderByDirection = 'desc' | 'asc'; +/** + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the + * specified field, optionally in descending order instead of ascending. + * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * + * @param fieldPath - The field to sort by. + * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @returns The created {@link QueryOrderByConstraint}. + */ +export declare function orderBy(fieldPath: string | FieldPath, directionStr?: OrderByDirection): QueryOrderByConstraint; +/** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ +export declare class QueryLimitConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'limit' | 'limitToLast'; + private readonly _limit; + private readonly _limitType; + /** + * @internal + */ + protected constructor( + /** The type of this query constraint */ + type: 'limit' | 'limitToLast', _limit: number, _limitType: LimitType); + static _create(type: 'limit' | 'limitToLast', _limit: number, _limitType: LimitType): QueryLimitConstraint; + _apply(query: Query): Query; +} +/** + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +export declare function limit(limit: number): QueryLimitConstraint; +/** + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. + * + * You must specify at least one `orderBy` clause for `limitToLast` queries, + * otherwise an exception will be thrown during execution. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +export declare function limitToLast(limit: number): QueryLimitConstraint; +/** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ +export declare class QueryStartAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'startAt' | 'startAfter'; + private readonly _docOrFields; + private readonly _inclusive; + /** + * @internal + */ + protected constructor( + /** The type of this query constraint */ + type: 'startAt' | 'startAfter', _docOrFields: Array>, _inclusive: boolean); + static _create(type: 'startAt' | 'startAfter', _docOrFields: Array>, _inclusive: boolean): QueryStartAtConstraint; + _apply(query: Query): Query; +} +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided document (inclusive). The starting position is relative + * to the order of the query. The document must contain all of the fields + * provided in the `orderBy` of this query. + * + * @param snapshot - The snapshot of the document to start at. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. + */ +export declare function startAt(snapshot: DocumentSnapshot): QueryStartAtConstraint; +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to start this query at, in order + * of the query's order by. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. + */ +export declare function startAt(...fieldValues: unknown[]): QueryStartAtConstraint; +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided document (exclusive). The starting position is + * relative to the order of the query. The document must contain all of the + * fields provided in the orderBy of the query. + * + * @param snapshot - The snapshot of the document to start after. + * @returns A {@link QueryStartAtConstraint} to pass to `query()` + */ +export declare function startAfter(snapshot: DocumentSnapshot): QueryStartAtConstraint; +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided fields relative to the order of the query. The order + * of the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to start this query after, in order + * of the query's order by. + * @returns A {@link QueryStartAtConstraint} to pass to `query()` + */ +export declare function startAfter(...fieldValues: unknown[]): QueryStartAtConstraint; +/** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ +export declare class QueryEndAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'endBefore' | 'endAt'; + private readonly _docOrFields; + private readonly _inclusive; + /** + * @internal + */ + protected constructor( + /** The type of this query constraint */ + type: 'endBefore' | 'endAt', _docOrFields: Array>, _inclusive: boolean); + static _create(type: 'endBefore' | 'endAt', _docOrFields: Array>, _inclusive: boolean): QueryEndAtConstraint; + _apply(query: Query): Query; +} +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided document (exclusive). The end position is relative to the + * order of the query. The document must contain all of the fields provided in + * the orderBy of the query. + * + * @param snapshot - The snapshot of the document to end before. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endBefore(snapshot: DocumentSnapshot): QueryEndAtConstraint; +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to end this query before, in order + * of the query's order by. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endBefore(...fieldValues: unknown[]): QueryEndAtConstraint; +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided document (inclusive). The end position is relative to the order + * of the query. The document must contain all of the fields provided in the + * orderBy of the query. + * + * @param snapshot - The snapshot of the document to end at. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endAt(snapshot: DocumentSnapshot): QueryEndAtConstraint; +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided fields relative to the order of the query. The order of the field + * values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to end this query at, in order + * of the query's order by. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endAt(...fieldValues: unknown[]): QueryEndAtConstraint; +export declare function newQueryFilter(query: InternalQuery, methodName: string, dataReader: UserDataReader, databaseId: DatabaseId, fieldPath: InternalFieldPath, op: Operator, value: unknown): FieldFilter; +export declare function newQueryOrderBy(query: InternalQuery, fieldPath: InternalFieldPath, direction: Direction): OrderBy; +/** + * Create a `Bound` from a query and a document. + * + * Note that the `Bound` will always include the key of the document + * and so only the provided document will compare equal to the returned + * position. + * + * Will throw if the document does not contain all fields of the order by + * of the query or if any of the fields in the order by are an uncommitted + * server timestamp. + */ +export declare function newQueryBoundFromDocument(query: InternalQuery, databaseId: DatabaseId, methodName: string, doc: Document | null, inclusive: boolean): Bound; +/** + * Converts a list of field values to a `Bound` for the given query. + */ +export declare function newQueryBoundFromFields(query: InternalQuery, databaseId: DatabaseId, dataReader: UserDataReader, methodName: string, values: unknown[], inclusive: boolean): Bound; +export declare function validateQueryFilterConstraint(functionName: string, queryConstraint: AppliableConstraint): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/reference.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/reference.d.ts new file mode 100644 index 0000000..fd89e5a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/reference.d.ts @@ -0,0 +1,362 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Query as InternalQuery } from '../core/query'; +import { DocumentKey } from '../model/document_key'; +import { ResourcePath } from '../model/path'; +import { Property } from '../util/json_validation'; +import { Firestore } from './database'; +import { FieldPath } from './field_path'; +import { FieldValue } from './field_value'; +import { FirestoreDataConverter } from './snapshot'; +import { NestedUpdateFields, Primitive } from './types'; +/** + * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to + * values. + */ +export interface DocumentData { + /** A mapping between a field and its value. */ + [field: string]: any; +} +/** + * Similar to TypeScript's `Partial`, but allows nested fields to be + * omitted and FieldValues to be passed in as property values. + */ +export type PartialWithFieldValue = Partial | (T extends Primitive ? T : T extends {} ? { + [K in keyof T]?: PartialWithFieldValue | FieldValue; +} : never); +/** + * Allows FieldValues to be passed in as a property value while maintaining + * type safety. + */ +export type WithFieldValue = T | (T extends Primitive ? T : T extends {} ? { + [K in keyof T]: WithFieldValue | FieldValue; +} : never); +/** + * Update data (for use with {@link (updateDoc:1)}) that consists of field paths + * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots + * reference nested fields within the document. FieldValues can be passed in + * as property values. + */ +export type UpdateData = T extends Primitive ? T : T extends {} ? { + [K in keyof T]?: UpdateData | FieldValue; +} & NestedUpdateFields : Partial; +/** + * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link + * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be + * configured to perform granular merges instead of overwriting the target + * documents in their entirety by providing a `SetOptions` with `merge: true`. + * + * @param merge - Changes the behavior of a `setDoc()` call to only replace the + * values specified in its data argument. Fields omitted from the `setDoc()` + * call remain untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace + * the specified field paths. Any field path that is not specified is ignored + * and remains untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + */ +export type SetOptions = { + readonly merge?: boolean; +} | { + readonly mergeFields?: Array; +}; +/** + * A `Query` refers to a query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ +export declare class Query { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter | null; + readonly _query: InternalQuery; + /** The type of this Firestore reference. */ + readonly type: 'query' | 'collection'; + /** + * The `Firestore` instance for the Firestore database (useful for performing + * transactions, etc.). + */ + readonly firestore: Firestore; + /** @hideconstructor protected */ + constructor(firestore: Firestore, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter: FirestoreDataConverter | null, _query: InternalQuery); + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `Query` that does not use a + * converter. + */ + withConverter(converter: null): Query; + /** + * Applies a custom data converter to this query, allowing you to use your own + * custom model objects with Firestore. When you call {@link getDocs} with + * the returned query, the provided converter will convert between Firestore + * data of type `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `Query` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter): Query; +} +/** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. + */ +export declare class DocumentReference { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter | null; + readonly _key: DocumentKey; + /** The type of this Firestore reference. */ + readonly type = "document"; + /** + * The {@link Firestore} instance the document is in. + * This is useful for performing transactions, for example. + */ + readonly firestore: Firestore; + /** @hideconstructor */ + constructor(firestore: Firestore, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter: FirestoreDataConverter | null, _key: DocumentKey); + get _path(): ResourcePath; + /** + * The document's identifier within its collection. + */ + get id(): string; + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ + get path(): string; + /** + * The collection this `DocumentReference` belongs to. + */ + get parent(): CollectionReference; + /** + * Applies a custom data converter to this `DocumentReference`, allowing you + * to use your own custom model objects with Firestore. When you call {@link + * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference` + * instance, the provided converter will convert between Firestore data of + * type `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `DocumentReference` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter): DocumentReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `DocumentReference` that does not + * use a converter. + */ + withConverter(converter: null): DocumentReference; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + referencePath: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `DocumentReference` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `DocumentReference` instance from a JSON object created by + * {@link DocumentReference.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json a JSON object represention of a `DocumentReference` instance + * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(firestore: Firestore, json: object): DocumentReference; + /** + * Builds a `DocumentReference` instance from a JSON object created by + * {@link DocumentReference.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json a JSON object represention of a `DocumentReference` instance + * @param converter - Converts objects to and from Firestore. + * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(firestore: Firestore, json: object, converter: FirestoreDataConverter): DocumentReference; +} +/** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using {@link (query:1)}). + */ +export declare class CollectionReference extends Query { + readonly _path: ResourcePath; + /** The type of this Firestore reference. */ + readonly type = "collection"; + /** @hideconstructor */ + constructor(firestore: Firestore, converter: FirestoreDataConverter | null, _path: ResourcePath); + /** The collection's identifier. */ + get id(): string; + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ + get path(): string; + /** + * A reference to the containing `DocumentReference` if this is a + * subcollection. If this isn't a subcollection, the reference is null. + */ + get parent(): DocumentReference | null; + /** + * Applies a custom data converter to this `CollectionReference`, allowing you + * to use your own custom model objects with Firestore. When you call {@link + * addDoc} with the returned `CollectionReference` instance, the provided + * converter will convert between Firestore data of type `NewDbModelType` and + * your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `CollectionReference` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter): CollectionReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `CollectionReference` that does not + * use a converter. + */ + withConverter(converter: null): CollectionReference; +} +/** + * Gets a `CollectionReference` instance that refers to the collection at + * the specified absolute path. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments to apply relative to the first + * argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(firestore: Firestore, path: string, ...pathSegments: string[]): CollectionReference; +/** + * Gets a `CollectionReference` instance that refers to a subcollection of + * `reference` at the specified relative path. + * + * @param reference - A reference to a collection. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments to apply relative to the first + * argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(reference: CollectionReference, path: string, ...pathSegments: string[]): CollectionReference; +/** + * Gets a `CollectionReference` instance that refers to a subcollection of + * `reference` at the specified relative path. + * + * @param reference - A reference to a Firestore document. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(reference: DocumentReference, path: string, ...pathSegments: string[]): CollectionReference; +/** + * Creates and returns a new `Query` instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given `collectionId`. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param collectionId - Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `Query`. + */ +export declare function collectionGroup(firestore: Firestore, collectionId: string): Query; +/** + * Gets a `DocumentReference` instance that refers to the document at the + * specified absolute path. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param path - A slash-separated path to a document. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(firestore: Firestore, path: string, ...pathSegments: string[]): DocumentReference; +/** + * Gets a `DocumentReference` instance that refers to a document within + * `reference` at the specified relative path. If no path is specified, an + * automatically-generated unique ID will be used for the returned + * `DocumentReference`. + * + * @param reference - A reference to a collection. + * @param path - A slash-separated path to a document. Has to be omitted to use + * auto-generated IDs. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(reference: CollectionReference, path?: string, ...pathSegments: string[]): DocumentReference; +/** + * Gets a `DocumentReference` instance that refers to a document within + * `reference` at the specified relative path. + * + * @param reference - A reference to a Firestore document. + * @param path - A slash-separated path to a document. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(reference: DocumentReference, path: string, ...pathSegments: string[]): DocumentReference; +/** + * Returns true if the provided references are equal. + * + * @param left - A reference to compare. + * @param right - A reference to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +export declare function refEqual(left: DocumentReference | CollectionReference, right: DocumentReference | CollectionReference): boolean; +/** + * Returns true if the provided queries point to the same collection and apply + * the same constraints. + * + * @param left - A `Query` to compare. + * @param right - A `Query` to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +export declare function queryEqual(left: Query, right: Query): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/reference_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/reference_impl.d.ts new file mode 100644 index 0000000..724ae99 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/reference_impl.d.ts @@ -0,0 +1,172 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentData as PublicDocumentData, SetOptions as PublicSetOptions } from '@firebase/firestore-types'; +import { ByteString } from '../util/byte_string'; +import { Bytes } from './bytes'; +import { Firestore } from './database'; +import { FieldPath } from './field_path'; +import { CollectionReference, DocumentData, DocumentReference, PartialWithFieldValue, Query, SetOptions, UpdateData, WithFieldValue } from './reference'; +import { DocumentSnapshot, QuerySnapshot } from './snapshot'; +import { UntypedFirestoreDataConverter } from './user_data_reader'; +import { AbstractUserDataWriter } from './user_data_writer'; +/** + * Converts custom model object of type T into `DocumentData` by applying the + * converter if it exists. + * + * This function is used when converting user objects to `DocumentData` + * because we want to provide the user with a more specific error message if + * their `set()` or fails due to invalid data originating from a `toFirestore()` + * call. + */ +export declare function applyFirestoreDataConverter(converter: UntypedFirestoreDataConverter | null, value: WithFieldValue | PartialWithFieldValue, options?: PublicSetOptions): PublicDocumentData; +export declare class LiteUserDataWriter extends AbstractUserDataWriter { + protected firestore: Firestore; + constructor(firestore: Firestore); + protected convertBytes(bytes: ByteString): Bytes; + protected convertReference(name: string): DocumentReference; +} +/** + * Reads the document referred to by the specified document reference. + * + * All documents are directly fetched from the server, even if the document was + * previously read or modified. Recent modifications are only reflected in the + * retrieved `DocumentSnapshot` if they have already been applied by the + * backend. If the client is offline, the read fails. If you like to use + * caching or see local modifications, please use the full Firestore SDK. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the current + * document contents. + */ +export declare function getDoc(reference: DocumentReference): Promise>; +/** + * Executes the query and returns the results as a {@link QuerySnapshot}. + * + * All queries are executed directly by the server, even if the query was + * previously executed. Recent modifications are only reflected in the retrieved + * results if they have already been applied by the backend. If the client is + * offline, the operation fails. To see previously cached result and local + * modifications, use the full Firestore SDK. + * + * @param query - The `Query` to execute. + * @returns A Promise that will be resolved with the results of the query. + */ +export declare function getDocs(query: Query): Promise>; +/** + * Writes to the document referred to by the specified `DocumentReference`. If + * the document does not yet exist, it will be created. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function setDoc(reference: DocumentReference, data: WithFieldValue): Promise; +/** + * Writes to the document referred to by the specified `DocumentReference`. If + * the document does not yet exist, it will be created. If you provide `merge` + * or `mergeFields`, the provided data can be merged into an existing document. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function setDoc(reference: DocumentReference, data: PartialWithFieldValue, options: SetOptions): Promise; +/** + * Updates fields in the document referred to by the specified + * `DocumentReference`. The update will fail if applied to a document that does + * not exist. + * + * The result of this update will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * update fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to update. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function updateDoc(reference: DocumentReference, data: UpdateData): Promise; +/** + * Updates fields in the document referred to by the specified + * `DocumentReference` The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * The result of this update will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * update fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to update. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function updateDoc(reference: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): Promise; +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * The deletion will only be reflected in document reads that occur after the + * returned promise resolves. If the client is offline, the + * delete fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to delete. + * @returns A `Promise` resolved once the document has been successfully + * deleted from the backend. + */ +export declare function deleteDoc(reference: DocumentReference): Promise; +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend. + */ +export declare function addDoc(reference: CollectionReference, data: WithFieldValue): Promise>; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/settings.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/settings.d.ts new file mode 100644 index 0000000..e86bdbe --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/settings.d.ts @@ -0,0 +1,77 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { EmulatorMockTokenOptions } from '@firebase/util'; +import { FirestoreLocalCache } from '../api/cache_config'; +import { CredentialsSettings } from '../api/credentials'; +import { ExperimentalLongPollingOptions } from '../api/long_polling_options'; +export declare const DEFAULT_HOST = "firestore.googleapis.com"; +export declare const DEFAULT_SSL = true; +/** + * Specifies custom configurations for your Cloud Firestore instance. + * You must set these before invoking any other methods. + */ +export interface FirestoreSettings { + /** The hostname to connect to. */ + host?: string; + /** Whether to use SSL when connecting. */ + ssl?: boolean; + /** + * Whether to skip nested properties that are set to `undefined` during + * object serialization. If set to `true`, these properties are skipped + * and not written to Firestore. If set to `false` or omitted, the SDK + * throws an exception when it encounters properties of type `undefined`. + */ + ignoreUndefinedProperties?: boolean; +} +/** + * @internal + * Undocumented, private additional settings not exposed in our public API. + */ +export interface PrivateSettings extends FirestoreSettings { + credentials?: CredentialsSettings; + cacheSizeBytes?: number; + experimentalForceLongPolling?: boolean; + experimentalAutoDetectLongPolling?: boolean; + experimentalLongPollingOptions?: ExperimentalLongPollingOptions; + useFetchStreams?: boolean; + emulatorOptions?: { + mockUserToken?: EmulatorMockTokenOptions | string; + }; + localCache?: FirestoreLocalCache; +} +/** + * A concrete type describing all the values that can be applied via a + * user-supplied `FirestoreSettings` object. This is a separate type so that + * defaults can be supplied and the value can be checked for equality. + */ +export declare class FirestoreSettingsImpl { + /** The hostname to connect to. */ + readonly host: string; + /** Whether to use SSL when connecting. */ + readonly ssl: boolean; + readonly cacheSizeBytes: number; + readonly experimentalForceLongPolling: boolean; + readonly experimentalAutoDetectLongPolling: boolean; + readonly experimentalLongPollingOptions: ExperimentalLongPollingOptions; + readonly ignoreUndefinedProperties: boolean; + readonly useFetchStreams: boolean; + readonly localCache?: FirestoreLocalCache; + readonly isUsingEmulator: boolean; + credentials?: any; + constructor(settings: PrivateSettings); + isEqual(other: FirestoreSettingsImpl): boolean; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/snapshot.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/snapshot.d.ts new file mode 100644 index 0000000..312e3f3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/snapshot.d.ts @@ -0,0 +1,367 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Compat } from '@firebase/util'; +import { Document } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { FieldPath as InternalFieldPath } from '../model/path'; +import { Firestore } from './database'; +import { FieldPath } from './field_path'; +import { DocumentData, DocumentReference, PartialWithFieldValue, Query, SetOptions, WithFieldValue } from './reference'; +import { UntypedFirestoreDataConverter } from './user_data_reader'; +import { AbstractUserDataWriter } from './user_data_writer'; +/** + * Converter used by `withConverter()` to transform user objects of type + * `AppModelType` into Firestore data of type `DbModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * In this context, an "AppModel" is a class that is used in an application to + * package together related information and functionality. Such a class could, + * for example, have properties with complex, nested data types, properties used + * for memoization, properties of types not supported by Firestore (such as + * `symbol` and `bigint`), and helper functions that perform compound + * operations. Such classes are not suitable and/or possible to store into a + * Firestore database. Instead, instances of such classes need to be converted + * to "plain old JavaScript objects" (POJOs) with exclusively primitive + * properties, potentially nested inside other POJOs or arrays of POJOs. In this + * context, this type is referred to as the "DbModel" and would be an object + * suitable for persisting into Firestore. For convenience, applications can + * implement `FirestoreDataConverter` and register the converter with Firestore + * objects, such as `DocumentReference` or `Query`, to automatically convert + * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel` + * to `AppModel` when retrieving from Firestore. + * + * @example + * + * Simple Example + * + * ```typescript + * const numberConverter = { + * toFirestore(value: WithFieldValue) { + * return { value }; + * }, + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) { + * return snapshot.data(options).value as number; + * } + * }; + * + * async function simpleDemo(db: Firestore): Promise { + * const documentRef = doc(db, 'values/value123').withConverter(numberConverter); + * + * // converters are used with `setDoc`, `addDoc`, and `getDoc` + * await setDoc(documentRef, 42); + * const snapshot1 = await getDoc(documentRef); + * assertEqual(snapshot1.data(), 42); + * + * // converters are not used when writing data with `updateDoc` + * await updateDoc(documentRef, { value: 999 }); + * const snapshot2 = await getDoc(documentRef); + * assertEqual(snapshot2.data(), 999); + * } + * ``` + * + * Advanced Example + * + * ```typescript + * // The Post class is a model that is used by our application. + * // This class may have properties and methods that are specific + * // to our application execution, which do not need to be persisted + * // to Firestore. + * class Post { + * constructor( + * readonly title: string, + * readonly author: string, + * readonly lastUpdatedMillis: number + * ) {} + * toString(): string { + * return `${this.title} by ${this.author}`; + * } + * } + * + * // The PostDbModel represents how we want our posts to be stored + * // in Firestore. This DbModel has different properties (`ttl`, + * // `aut`, and `lut`) from the Post class we use in our application. + * interface PostDbModel { + * ttl: string; + * aut: { firstName: string; lastName: string }; + * lut: Timestamp; + * } + * + * // The `PostConverter` implements `FirestoreDataConverter` and specifies + * // how the Firestore SDK can convert `Post` objects to `PostDbModel` + * // objects and vice versa. + * class PostConverter implements FirestoreDataConverter { + * toFirestore(post: WithFieldValue): WithFieldValue { + * return { + * ttl: post.title, + * aut: this._autFromAuthor(post.author), + * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis) + * }; + * } + * + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post { + * const data = snapshot.data(options) as PostDbModel; + * const author = `${data.aut.firstName} ${data.aut.lastName}`; + * return new Post(data.ttl, author, data.lut.toMillis()); + * } + * + * _autFromAuthor( + * author: string | FieldValue + * ): { firstName: string; lastName: string } | FieldValue { + * if (typeof author !== 'string') { + * // `author` is a FieldValue, so just return it. + * return author; + * } + * const [firstName, lastName] = author.split(' '); + * return {firstName, lastName}; + * } + * + * _lutFromLastUpdatedMillis( + * lastUpdatedMillis: number | FieldValue + * ): Timestamp | FieldValue { + * if (typeof lastUpdatedMillis !== 'number') { + * // `lastUpdatedMillis` must be a FieldValue, so just return it. + * return lastUpdatedMillis; + * } + * return Timestamp.fromMillis(lastUpdatedMillis); + * } + * } + * + * async function advancedDemo(db: Firestore): Promise { + * // Create a `DocumentReference` with a `FirestoreDataConverter`. + * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter()); + * + * // The `data` argument specified to `setDoc()` is type checked by the + * // TypeScript compiler to be compatible with `Post`. Since the `data` + * // argument is typed as `WithFieldValue` rather than just `Post`, + * // this allows properties of the `data` argument to also be special + * // Firestore values that perform server-side mutations, such as + * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`. + * await setDoc(documentRef, { + * title: 'My Life', + * author: 'Foo Bar', + * lastUpdatedMillis: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `setDoc()` is _not_ compatible with `WithFieldValue`. This + * // type checking prevents the caller from specifying objects with incorrect + * // properties or property values. + * // @ts-expect-error "Argument of type { ttl: string; } is not assignable + * // to parameter of type WithFieldValue" + * await setDoc(documentRef, { ttl: 'The Title' }); + * + * // When retrieving a document with `getDoc()` the `DocumentSnapshot` + * // object's `data()` method returns a `Post`, rather than a generic object, + * // which would have been returned if the `DocumentReference` did _not_ have a + * // `FirestoreDataConverter` attached to it. + * const snapshot1: DocumentSnapshot = await getDoc(documentRef); + * const post1: Post = snapshot1.data()!; + * if (post1) { + * assertEqual(post1.title, 'My Life'); + * assertEqual(post1.author, 'Foo Bar'); + * } + * + * // The `data` argument specified to `updateDoc()` is type checked by the + * // TypeScript compiler to be compatible with `PostDbModel`. Note that + * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`, + * // the `data` argument to `updateDoc()` must be compatible with + * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed + * // as `WithFieldValue` rather than just `PostDbModel`, this + * // allows properties of the `data` argument to also be those special + * // Firestore values, like `arrayRemove()`, `deleteField()`, and + * // `serverTimestamp()`. + * await updateDoc(documentRef, { + * 'aut.firstName': 'NewFirstName', + * lut: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `updateDoc()` is _not_ compatible with `WithFieldValue`. + * // This type checking prevents the caller from specifying objects with + * // incorrect properties or property values. + * // @ts-expect-error "Argument of type { title: string; } is not assignable + * // to parameter of type WithFieldValue" + * await updateDoc(documentRef, { title: 'New Title' }); + * const snapshot2: DocumentSnapshot = await getDoc(documentRef); + * const post2: Post = snapshot2.data()!; + * if (post2) { + * assertEqual(post2.title, 'My Life'); + * assertEqual(post2.author, 'NewFirstName Bar'); + * } + * } + * ``` + */ +export interface FirestoreDataConverter { + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link @firebase/firestore/lite#(setDoc:1)}, + * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and + * {@link @firebase/firestore/lite#(Transaction.set:1)}. + * + * The `WithFieldValue` type extends `T` to also allow FieldValues such as + * {@link (deleteField:1)} to be used as property values. + */ + toFirestore(modelObject: WithFieldValue): WithFieldValue; + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link @firebase/firestore/lite#(setDoc:1)}, + * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and + * {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true` + * or `mergeFields`. + * + * The `PartialWithFieldValue` type extends `Partial` to allow + * FieldValues such as {@link (arrayUnion:1)} to be used as property values. + * It also supports nested `Partial` by allowing nested fields to be + * omitted. + */ + toFirestore(modelObject: PartialWithFieldValue, options: SetOptions): PartialWithFieldValue; + /** + * Called by the Firestore SDK to convert Firestore data into an object of + * type `AppModelType`. You can access your data by calling: + * `snapshot.data()`. + * + * + * Generally, the data returned from `snapshot.data()` can be cast to + * `DbModelType`; however, this is not guaranteed because Firestore does not + * enforce a schema on the database. For example, writes from a previous + * version of the application or writes from another client that did not use a + * type converter could have written data with different properties and/or + * property types. The implementation will need to choose whether to + * gracefully recover from non-conforming data or throw an error. + * + * @param snapshot - A `QueryDocumentSnapshot` containing your data and + * metadata. + */ + fromFirestore(snapshot: QueryDocumentSnapshot): AppModelType; +} +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ +export declare class DocumentSnapshot { + _firestore: Firestore; + _userDataWriter: AbstractUserDataWriter; + _key: DocumentKey; + _document: Document | null; + _converter: UntypedFirestoreDataConverter | null; + /** @hideconstructor protected */ + constructor(_firestore: Firestore, _userDataWriter: AbstractUserDataWriter, _key: DocumentKey, _document: Document | null, _converter: UntypedFirestoreDataConverter | null); + /** Property of the `DocumentSnapshot` that provides the document's ID. */ + get id(): string; + /** + * The `DocumentReference` for the document included in the `DocumentSnapshot`. + */ + get ref(): DocumentReference; + /** + * Signals whether or not the document at the snapshot's location exists. + * + * @returns true if the document exists. + */ + exists(): this is QueryDocumentSnapshot; + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * @returns An `Object` containing all fields in the document or `undefined` + * if the document doesn't exist. + */ + data(): AppModelType | undefined; + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + get(fieldPath: string | FieldPath): any; +} +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ +export declare class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * @override + * @returns An `Object` containing all fields in the document. + */ + data(): AppModelType; +} +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ +export declare class QuerySnapshot { + readonly _docs: Array>; + /** + * The query on which you called {@link getDocs} in order to get this + * `QuerySnapshot`. + */ + readonly query: Query; + /** @hideconstructor */ + constructor(_query: Query, _docs: Array>); + /** An array of all the documents in the `QuerySnapshot`. */ + get docs(): Array>; + /** The number of documents in the `QuerySnapshot`. */ + get size(): number; + /** True if there are no documents in the `QuerySnapshot`. */ + get empty(): boolean; + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ + forEach(callback: (result: QueryDocumentSnapshot) => void, thisArg?: unknown): void; +} +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ +export declare function snapshotEqual(left: DocumentSnapshot | QuerySnapshot, right: DocumentSnapshot | QuerySnapshot): boolean; +/** + * Helper that calls `fromDotSeparatedString()` but wraps any error thrown. + */ +export declare function fieldPathFromArgument(methodName: string, arg: string | FieldPath | Compat): InternalFieldPath; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/timestamp.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/timestamp.d.ts new file mode 100644 index 0000000..6d14f82 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/timestamp.d.ts @@ -0,0 +1,134 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Property } from '../util/json_validation'; +/** + * A `Timestamp` represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. + * + * It is encoded using the Proleptic Gregorian Calendar which extends the + * Gregorian calendar backwards to year one. It is encoded assuming all minutes + * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59.999999999Z. + * + * For examples and further specifications, refer to the + * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. + */ +export declare class Timestamp { + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + readonly seconds: number; + /** + * The fractions of a second at nanosecond resolution.* + */ + readonly nanoseconds: number; + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns a new timestamp representing the current date. + */ + static now(): Timestamp; + /** + * Creates a new timestamp from the given date. + * + * @param date - The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the given + * date. + */ + static fromDate(date: Date): Timestamp; + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds - Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the given + * number of milliseconds. + */ + static fromMillis(milliseconds: number): Timestamp; + /** + * Creates a new timestamp. + * + * @param seconds - The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds - The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ + constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + seconds: number, + /** + * The fractions of a second at nanosecond resolution.* + */ + nanoseconds: number); + /** + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ + toDate(): Date; + /** + * Converts a `Timestamp` to a numeric timestamp (in milliseconds since + * epoch). This operation causes a loss of precision. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ + toMillis(): number; + _compareTo(other: Timestamp): number; + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other - The `Timestamp` to compare against. + * @returns true if this `Timestamp` is equal to the provided one. + */ + isEqual(other: Timestamp): boolean; + /** Returns a textual representation of this `Timestamp`. */ + toString(): string; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + seconds: Property<"number">; + nanoseconds: Property<"number">; + }; + /** + * Returns a JSON-serializable representation of this `Timestamp`. + */ + toJSON(): { + seconds: number; + nanoseconds: number; + type: string; + }; + /** + * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}. + */ + static fromJSON(json: object): Timestamp; + /** + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. + */ + valueOf(): string; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/transaction.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/transaction.d.ts new file mode 100644 index 0000000..eee3374 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/transaction.d.ts @@ -0,0 +1,122 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Transaction as InternalTransaction } from '../core/transaction'; +import { Firestore } from './database'; +import { FieldPath } from './field_path'; +import { DocumentData, DocumentReference, PartialWithFieldValue, SetOptions, UpdateData, WithFieldValue } from './reference'; +import { DocumentSnapshot } from './snapshot'; +import { TransactionOptions } from './transaction_options'; +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ +export declare class Transaction { + protected readonly _firestore: Firestore; + private readonly _transaction; + private readonly _dataReader; + /** @hideconstructor */ + constructor(_firestore: Firestore, _transaction: InternalTransaction); + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ + get(documentRef: DocumentReference): Promise>; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: WithFieldValue): this; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * If you provide `merge` or `mergeFields`, the provided data can be merged + * into an existing document. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: PartialWithFieldValue, options: SetOptions): this; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * @param documentRef - A reference to the document to be updated. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, data: UpdateData): this; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * @param documentRef - A reference to the document to be updated. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key/value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): this; + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + delete(documentRef: DocumentReference): this; +} +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ +export declare function runTransaction(firestore: Firestore, updateFunction: (transaction: Transaction) => Promise, options?: TransactionOptions): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/transaction_options.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/transaction_options.d.ts new file mode 100644 index 0000000..113fb49 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/transaction_options.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options to customize transaction behavior. + */ +export declare interface TransactionOptions { + /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */ + readonly maxAttempts?: number; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/types.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/types.d.ts new file mode 100644 index 0000000..5c56c2d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/types.d.ts @@ -0,0 +1,61 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { UpdateData } from './reference'; +/** + * These types primarily exist to support the `UpdateData`, + * `WithFieldValue`, and `PartialWithFieldValue` types and are not consumed + * directly by the end developer. + */ +/** Primitive types. */ +export type Primitive = string | number | boolean | undefined | null; +/** + * For each field (e.g. 'bar'), find all nested keys (e.g. {'bar.baz': T1, + * 'bar.qux': T2}). Intersect them together to make a single map containing + * all possible keys that are all marked as optional + */ +export type NestedUpdateFields> = UnionToIntersection<{ + [K in keyof T & string]: ChildUpdateFields; +}[keyof T & string]>; +/** + * Helper for calculating the nested fields for a given type T1. This is needed + * to distribute union types such as `undefined | {...}` (happens for optional + * props) or `{a: A} | {b: B}`. + * + * In this use case, `V` is used to distribute the union types of `T[K]` on + * `Record`, since `T[K]` is evaluated as an expression and not distributed. + * + * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types + */ +export type ChildUpdateFields = V extends Record ? AddPrefixToKeys> : never; +/** + * Returns a new map where every key is prefixed with the outer key appended + * to a dot. + */ +export type AddPrefixToKeys> = { + [K in keyof T & string as `${Prefix}.${K}`]+?: string extends K ? any : T[K]; +}; +/** + * Given a union type `U = T1 | T2 | ...`, returns an intersected type + * `(T1 & T2 & ...)`. + * + * Uses distributive conditional types and inference from conditional types. + * This works because multiple candidates for the same type variable in + * contra-variant positions causes an intersection type to be inferred. + * https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-inference-in-conditional-types + * https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type + */ +export type UnionToIntersection = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/user_data_reader.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/user_data_reader.d.ts new file mode 100644 index 0000000..821bb46 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/user_data_reader.d.ts @@ -0,0 +1,224 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentData, FieldPath as PublicFieldPath, SetOptions } from '@firebase/firestore-types'; +import { Compat } from '@firebase/util'; +import { ParseContext } from '../api/parse_context'; +import { DatabaseId } from '../core/database_info'; +import { DocumentKey } from '../model/document_key'; +import { FieldMask } from '../model/field_mask'; +import { FieldTransform, Mutation, Precondition } from '../model/mutation'; +import { ObjectValue } from '../model/object_value'; +import { FieldPath as InternalFieldPath } from '../model/path'; +import { MapValue as ProtoMapValue, Value as ProtoValue } from '../protos/firestore_proto_api'; +import { JsonProtoSerializer } from '../remote/serializer'; +import { FirestoreError } from '../util/error'; +import { Dict } from '../util/obj'; +import { Firestore } from './database'; +import { FieldValue } from './field_value'; +import { PartialWithFieldValue, WithFieldValue } from './reference'; +import { VectorValue } from './vector_value'; +/** + * An untyped Firestore Data Converter interface that is shared between the + * lite, firestore-exp and classic SDK. + */ +export interface UntypedFirestoreDataConverter { + toFirestore(modelObject: WithFieldValue): WithFieldValue; + toFirestore(modelObject: PartialWithFieldValue, options: SetOptions): PartialWithFieldValue; + fromFirestore(snapshot: unknown, options?: unknown): AppModelType; +} +/** The result of parsing document data (e.g. for a setData call). */ +export declare class ParsedSetData { + readonly data: ObjectValue; + readonly fieldMask: FieldMask | null; + readonly fieldTransforms: FieldTransform[]; + constructor(data: ObjectValue, fieldMask: FieldMask | null, fieldTransforms: FieldTransform[]); + toMutation(key: DocumentKey, precondition: Precondition): Mutation; +} +/** The result of parsing "update" data (i.e. for an updateData call). */ +export declare class ParsedUpdateData { + readonly data: ObjectValue; + readonly fieldMask: FieldMask; + readonly fieldTransforms: FieldTransform[]; + constructor(data: ObjectValue, fieldMask: FieldMask, fieldTransforms: FieldTransform[]); + toMutation(key: DocumentKey, precondition: Precondition): Mutation; +} +export declare const enum UserDataSource { + Set = 0, + Update = 1, + MergeSet = 2, + /** + * Indicates the source is a where clause, cursor bound, arrayUnion() + * element, etc. Of note, isWrite(source) will return false. + */ + Argument = 3, + /** + * Indicates that the source is an Argument that may directly contain nested + * arrays (e.g. the operand of an `in` query). + */ + ArrayArgument = 4 +} +/** Contains the settings that are mutated as we parse user data. */ +interface ContextSettings { + /** Indicates what kind of API method this data came from. */ + readonly dataSource: UserDataSource; + /** The name of the method the user called to create the ParseContext. */ + readonly methodName: string; + /** The document the user is attempting to modify, if that applies. */ + readonly targetDoc?: DocumentKey; + /** + * A path within the object being parsed. This could be an empty path (in + * which case the context represents the root of the data being parsed), or a + * nonempty path (indicating the context represents a nested location within + * the data). + */ + readonly path?: InternalFieldPath; + /** + * Whether or not this context corresponds to an element of an array. + * If not set, elements are treated as if they were outside of arrays. + */ + readonly arrayElement?: boolean; + /** + * Whether or not a converter was specified in this context. If true, error + * messages will reference the converter when invalid data is provided. + */ + readonly hasConverter?: boolean; +} +/** A "context" object passed around while parsing user data. */ +declare class ParseContextImpl implements ParseContext { + readonly settings: ContextSettings; + readonly databaseId: DatabaseId; + readonly serializer: JsonProtoSerializer; + readonly ignoreUndefinedProperties: boolean; + readonly fieldTransforms: FieldTransform[]; + readonly fieldMask: InternalFieldPath[]; + /** + * Initializes a ParseContext with the given source and path. + * + * @param settings - The settings for the parser. + * @param databaseId - The database ID of the Firestore instance. + * @param serializer - The serializer to use to generate the Value proto. + * @param ignoreUndefinedProperties - Whether to ignore undefined properties + * rather than throw. + * @param fieldTransforms - A mutable list of field transforms encountered + * while parsing the data. + * @param fieldMask - A mutable list of field paths encountered while parsing + * the data. + * + * TODO(b/34871131): We don't support array paths right now, so path can be + * null to indicate the context represents any location within an array (in + * which case certain features will not work and errors will be somewhat + * compromised). + */ + constructor(settings: ContextSettings, databaseId: DatabaseId, serializer: JsonProtoSerializer, ignoreUndefinedProperties: boolean, fieldTransforms?: FieldTransform[], fieldMask?: InternalFieldPath[]); + get path(): InternalFieldPath | undefined; + get dataSource(): UserDataSource; + /** Returns a new context with the specified settings overwritten. */ + contextWith(configuration: Partial): ParseContextImpl; + childContextForField(field: string): ParseContextImpl; + childContextForFieldPath(field: InternalFieldPath): ParseContextImpl; + childContextForArray(index: number): ParseContextImpl; + createError(reason: string): FirestoreError; + /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ + contains(fieldPath: InternalFieldPath): boolean; + private validatePath; + private validatePathSegment; +} +/** + * Helper for parsing raw user input (provided via the API) into internal model + * classes. + */ +export declare class UserDataReader { + private readonly databaseId; + private readonly ignoreUndefinedProperties; + private readonly serializer; + constructor(databaseId: DatabaseId, ignoreUndefinedProperties: boolean, serializer?: JsonProtoSerializer); + /** Creates a new top-level parse context. */ + createContext(dataSource: UserDataSource, methodName: string, targetDoc?: DocumentKey, hasConverter?: boolean): ParseContextImpl; +} +export declare function newUserDataReader(firestore: Firestore): UserDataReader; +/** Parse document data from a set() call. */ +export declare function parseSetData(userDataReader: UserDataReader, methodName: string, targetDoc: DocumentKey, input: unknown, hasConverter: boolean, options?: SetOptions): ParsedSetData; +export declare class DeleteFieldValueImpl extends FieldValue { + _toFieldTransform(context: ParseContextImpl): null; + isEqual(other: FieldValue): boolean; +} +export declare class ServerTimestampFieldValueImpl extends FieldValue { + _toFieldTransform(context: ParseContextImpl): FieldTransform; + isEqual(other: FieldValue): boolean; +} +export declare class ArrayUnionFieldValueImpl extends FieldValue { + private readonly _elements; + constructor(methodName: string, _elements: unknown[]); + _toFieldTransform(context: ParseContextImpl): FieldTransform; + isEqual(other: FieldValue): boolean; +} +export declare class ArrayRemoveFieldValueImpl extends FieldValue { + private readonly _elements; + constructor(methodName: string, _elements: unknown[]); + _toFieldTransform(context: ParseContextImpl): FieldTransform; + isEqual(other: FieldValue): boolean; +} +export declare class NumericIncrementFieldValueImpl extends FieldValue { + private readonly _operand; + constructor(methodName: string, _operand: number); + _toFieldTransform(context: ParseContextImpl): FieldTransform; + isEqual(other: FieldValue): boolean; +} +/** Parse update data from an update() call. */ +export declare function parseUpdateData(userDataReader: UserDataReader, methodName: string, targetDoc: DocumentKey, input: unknown): ParsedUpdateData; +/** Parse update data from a list of field/value arguments. */ +export declare function parseUpdateVarargs(userDataReader: UserDataReader, methodName: string, targetDoc: DocumentKey, field: string | PublicFieldPath | Compat, value: unknown, moreFieldsAndValues: unknown[]): ParsedUpdateData; +/** + * Parse a "query value" (e.g. value in a where filter or a value in a cursor + * bound). + * + * @param allowArrays - Whether the query value is an array that may directly + * contain additional arrays (e.g. the operand of an `in` query). + */ +export declare function parseQueryValue(userDataReader: UserDataReader, methodName: string, input: unknown, allowArrays?: boolean): ProtoValue; +/** + * Parses user data to Protobuf Values. + * + * @param input - Data to be parsed. + * @param context - A context object representing the current path being parsed, + * the source of the data being parsed, etc. + * @returns The parsed value, or null if the value was a FieldValue sentinel + * that should not be included in the resulting parsed data. + */ +export declare function parseData(input: unknown, context: ParseContextImpl): ProtoValue | null; +export declare function parseObject(obj: Dict, context: ParseContextImpl): { + mapValue: ProtoMapValue; +}; +/** + * Creates a new VectorValue proto value (using the internal format). + */ +export declare function parseVectorValue(value: VectorValue, context: ParseContextImpl): ProtoValue; +/** + * Helper that calls fromDotSeparatedString() but wraps any error thrown. + */ +export declare function fieldPathFromArgument(methodName: string, path: string | PublicFieldPath | Compat, targetDoc?: DocumentKey): InternalFieldPath; +/** + * Wraps fromDotSeparatedString with an error message about the method that + * was thrown. + * @param methodName - The publicly visible method name + * @param path - The dot-separated string form of a field path which will be + * split on dots. + * @param targetDoc - The document against which the field path will be + * evaluated. + */ +export declare function fieldPathFromDotSeparatedString(methodName: string, path: string, targetDoc?: DocumentKey): InternalFieldPath; +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/user_data_writer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/user_data_writer.d.ts new file mode 100644 index 0000000..391593a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/user_data_writer.d.ts @@ -0,0 +1,48 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentData } from '@firebase/firestore-types'; +import { DatabaseId } from '../core/database_info'; +import { DocumentKey } from '../model/document_key'; +import { ApiClientObjectMap, MapValue as ProtoMapValue, Value, Value as ProtoValue } from '../protos/firestore_proto_api'; +import { ByteString } from '../util/byte_string'; +import { VectorValue } from './vector_value'; +export type ServerTimestampBehavior = 'estimate' | 'previous' | 'none'; +/** + * Converts Firestore's internal types to the JavaScript types that we expose + * to the user. + * + * @internal + */ +export declare abstract class AbstractUserDataWriter { + convertValue(value: ProtoValue, serverTimestampBehavior?: ServerTimestampBehavior): unknown; + private convertObject; + /** + * @internal + */ + convertObjectMap(fields: ApiClientObjectMap | undefined, serverTimestampBehavior?: ServerTimestampBehavior): DocumentData; + /** + * @internal + */ + convertVectorValue(mapValue: ProtoMapValue): VectorValue; + private convertGeoPoint; + private convertArray; + private convertServerTimestamp; + private convertTimestamp; + protected convertDocumentKey(name: string, expectedDatabaseId: DatabaseId): DocumentKey; + protected abstract convertReference(name: string): unknown; + protected abstract convertBytes(bytes: ByteString): unknown; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/vector_value.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/vector_value.d.ts new file mode 100644 index 0000000..b4808e0 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/vector_value.d.ts @@ -0,0 +1,58 @@ +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Property } from '../util/json_validation'; +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link vector}. + * + * @class VectorValue + */ +export declare class VectorValue { + private readonly _values; + /** + * @private + * @internal + */ + constructor(values: number[] | undefined); + /** + * Returns a copy of the raw number array form of the vector. + */ + toArray(): number[]; + /** + * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise. + */ + isEqual(other: VectorValue): boolean; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + vectorValues: Property<"object">; + }; + /** + * Returns a JSON-serializable representation of this `VectorValue` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}. + * + * @param json a JSON object represention of a `VectorValue` instance. + * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): VectorValue; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/write_batch.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/write_batch.d.ts new file mode 100644 index 0000000..4835feb --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/lite-api/write_batch.d.ts @@ -0,0 +1,125 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Compat } from '@firebase/util'; +import { Mutation } from '../model/mutation'; +import { Firestore } from './database'; +import { FieldPath } from './field_path'; +import { DocumentData, DocumentReference, PartialWithFieldValue, SetOptions, UpdateData, WithFieldValue } from './reference'; +/** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It + * provides methods for adding writes to the write batch. None of the writes + * will be committed (or visible locally) until {@link WriteBatch.commit} is + * called. + */ +export declare class WriteBatch { + private readonly _firestore; + private readonly _commitHandler; + private readonly _dataReader; + private _mutations; + private _committed; + /** @hideconstructor */ + constructor(_firestore: Firestore, _commitHandler: (m: Mutation[]) => Promise); + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: WithFieldValue): WriteBatch; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * If you provide `merge` or `mergeFields`, the provided data can be merged + * into an existing document. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: PartialWithFieldValue, options: SetOptions): WriteBatch; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * @param documentRef - A reference to the document to be updated. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, data: UpdateData): WriteBatch; + /** + * Updates fields in the document referred to by this {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be update by providing dot-separated field path strings + * or by providing `FieldPath` objects. + * + * @param documentRef - A reference to the document to be updated. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): WriteBatch; + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + delete(documentRef: DocumentReference): WriteBatch; + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `Promise` resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit (note that it won't + * resolve while you're offline). + */ + commit(): Promise; + private _verifyNotCommitted; +} +export declare function validateReference(documentRef: DocumentReference | Compat>, firestore: Firestore): DocumentReference; +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single WriteBatch + * is 500. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `WriteBatch` that can be used to atomically execute multiple + * writes. + */ +export declare function writeBatch(firestore: Firestore): WriteBatch; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/bundle_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/bundle_cache.d.ts new file mode 100644 index 0000000..2949e55 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/bundle_cache.d.ts @@ -0,0 +1,44 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BundleMetadata, NamedQuery } from '../core/bundle'; +import { NamedQuery as ProtoNamedQuery, BundleMetadata as ProtoBundleMetadata } from '../protos/firestore_bundle_proto'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** + * Provides interfaces to save and read Firestore bundles. + */ +export interface BundleCache { + /** + * Gets the saved `BundleMetadata` for a given `bundleId`, returns undefined + * if no bundle metadata is found under the given id. + */ + getBundleMetadata(transaction: PersistenceTransaction, bundleId: string): PersistencePromise; + /** + * Saves a `BundleMetadata` from a bundle into local storage, using its id as + * the persistent key. + */ + saveBundleMetadata(transaction: PersistenceTransaction, metadata: ProtoBundleMetadata): PersistencePromise; + /** + * Gets a saved `NamedQuery` for the given query name. Returns undefined if + * no queries are found under the given name. + */ + getNamedQuery(transaction: PersistenceTransaction, queryName: string): PersistencePromise; + /** + * Saves a `NamedQuery` from a bundle, using its name as the persistent key. + */ + saveNamedQuery(transaction: PersistenceTransaction, query: ProtoNamedQuery): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/document_overlay_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/document_overlay_cache.d.ts new file mode 100644 index 0000000..e1f1f2a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/document_overlay_cache.d.ts @@ -0,0 +1,76 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentKeySet, MutationMap, OverlayMap } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { Overlay } from '../model/overlay'; +import { ResourcePath } from '../model/path'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** + * Provides methods to read and write document overlays. + * + * An overlay is a saved mutation, that gives a local view of a document when + * applied to the remote version of the document. + * + * Each overlay stores the largest batch ID that is included in the overlay, + * which allows us to remove the overlay once all batches leading up to it have + * been acknowledged. + */ +export interface DocumentOverlayCache { + /** + * Gets the saved overlay mutation for the given document key. + * Returns null if there is no overlay for that key. + */ + getOverlay(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; + /** + * Gets the saved overlay mutation for the given document keys. Skips keys for + * which there are no overlays. + */ + getOverlays(transaction: PersistenceTransaction, keys: DocumentKey[]): PersistencePromise; + /** + * Saves the given document mutation map to persistence as overlays. + * All overlays will have their largest batch id set to `largestBatchId`. + */ + saveOverlays(transaction: PersistenceTransaction, largestBatchId: number, overlays: MutationMap): PersistencePromise; + /** Removes overlays for the given document keys and batch ID. */ + removeOverlaysForBatchId(transaction: PersistenceTransaction, documentKeys: DocumentKeySet, batchId: number): PersistencePromise; + /** + * Returns all saved overlays for the given collection. + * + * @param transaction - The persistence transaction to use for this operation. + * @param collection - The collection path to get the overlays for. + * @param sinceBatchId - The minimum batch ID to filter by (exclusive). + * Only overlays that contain a change past `sinceBatchId` are returned. + * @returns Mapping of each document key in the collection to its overlay. + */ + getOverlaysForCollection(transaction: PersistenceTransaction, collection: ResourcePath, sinceBatchId: number): PersistencePromise; + /** + * Returns `count` overlays with a batch ID higher than `sinceBatchId` for the + * provided collection group, processed by ascending batch ID. The method + * always returns all overlays for a batch even if the last batch contains + * more documents than the remaining limit. + * + * @param transaction - The persistence transaction used for this operation. + * @param collectionGroup - The collection group to get the overlays for. + * @param sinceBatchId - The minimum batch ID to filter by (exclusive). + * Only overlays that contain a change past `sinceBatchId` are returned. + * @param count - The number of overlays to return. Can be exceeded if the last + * batch contains more entries. + * @return Mapping of each document key in the collection group to its overlay. + */ + getOverlaysForCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, sinceBatchId: number, count: number): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/encoded_resource_path.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/encoded_resource_path.d.ts new file mode 100644 index 0000000..73353db --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/encoded_resource_path.d.ts @@ -0,0 +1,73 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ResourcePath } from '../model/path'; +/** + * Helpers for dealing with resource paths stored in IndexedDB. + * + * Resource paths in their canonical string form do not sort as the server + * sorts them. Specifically the server splits paths into segments first and then + * sorts, putting end-of-segment before any character. In a UTF-8 string + * encoding the slash ('/') that denotes the end-of-segment naturally comes + * after other characters so the intent here is to encode the path delimiters in + * such a way that the resulting strings sort naturally. + * + * Resource paths are also used for prefix scans so it's important to + * distinguish whole segments from any longer segments of which they might be a + * prefix. For example, it's important to make it possible to scan documents in + * a collection "foo" without encountering documents in a collection "foobar". + * + * Separate from the concerns about resource path ordering and separation, + * On Android, SQLite imposes additional restrictions since it does not handle + * keys with embedded NUL bytes particularly well. Rather than change the + * implementation we keep the encoding identical to keep the ports similar. + * + * Taken together this means resource paths when encoded for storage in + * IndexedDB have the following characteristics: + * + * * Segment separators ("/") sort before everything else. + * * All paths have a trailing separator. + * * NUL bytes do not exist in the output, since IndexedDB doesn't treat them + * well. + * + * Therefore resource paths are encoded into string form using the following + * rules: + * + * * '\x01' is used as an escape character. + * * Path separators are encoded as "\x01\x01" + * * NUL bytes are encoded as "\x01\x10" + * * '\x01' is encoded as "\x01\x11" + * + * This encoding leaves some room between path separators and the NUL byte + * just in case we decide to support integer document ids after all. + * + * Note that characters treated specially by the backend ('.', '/', and '~') + * are not treated specially here. This class assumes that any unescaping of + * resource path strings into actual ResourcePath objects will handle these + * characters there. + */ +export type EncodedResourcePath = string; +/** + * Encodes a resource path into a IndexedDb-compatible string form. + */ +export declare function encodeResourcePath(path: ResourcePath): EncodedResourcePath; +/** + * Decodes the given IndexedDb-compatible string form of a resource path into + * a ResourcePath instance. Note that this method is not suitable for use with + * decoding resource names from the server; those are One Platform format + * strings. + */ +export declare function decodeResourcePath(path: EncodedResourcePath): ResourcePath; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/globals_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/globals_cache.d.ts new file mode 100644 index 0000000..a2a7ff6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/globals_cache.d.ts @@ -0,0 +1,39 @@ +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ByteString } from '../util/byte_string'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** + * General purpose cache for global values. + * + * Global state that cuts across components should be saved here. Following are contained herein: + * + * `sessionToken` tracks server interaction across Listen and Write streams. This facilitates cache + * synchronization and invalidation. + */ +export interface GlobalsCache { + /** + * Gets session token. + */ + getSessionToken(transaction: PersistenceTransaction): PersistencePromise; + /** + * Sets session token. + * + * @param sessionToken - The new session token. + */ + setSessionToken(transaction: PersistenceTransaction, sessionToken: ByteString): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/index_backfiller.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/index_backfiller.d.ts new file mode 100644 index 0000000..2abeb5f --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/index_backfiller.d.ts @@ -0,0 +1,44 @@ +import { AsyncQueue } from '../util/async_queue'; +import { LocalStore } from './local_store'; +import { Persistence, Scheduler } from './persistence'; +/** This class is responsible for the scheduling of Index Backfiller. */ +export declare class IndexBackfillerScheduler implements Scheduler { + private readonly asyncQueue; + private readonly backfiller; + private task; + constructor(asyncQueue: AsyncQueue, backfiller: IndexBackfiller); + start(): void; + stop(): void; + get started(): boolean; + private schedule; +} +/** Implements the steps for backfilling indexes. */ +export declare class IndexBackfiller { + /** + * LocalStore provides access to IndexManager and LocalDocumentView. + * These properties will update when the user changes. Consequently, + * making a local copy of IndexManager and LocalDocumentView will require + * updates over time. The simpler solution is to rely on LocalStore to have + * an up-to-date references to IndexManager and LocalDocumentStore. + */ + private readonly localStore; + private readonly persistence; + constructor( + /** + * LocalStore provides access to IndexManager and LocalDocumentView. + * These properties will update when the user changes. Consequently, + * making a local copy of IndexManager and LocalDocumentView will require + * updates over time. The simpler solution is to rely on LocalStore to have + * an up-to-date references to IndexManager and LocalDocumentStore. + */ + localStore: LocalStore, persistence: Persistence); + backfill(maxDocumentsToProcess?: number): Promise; + /** Writes index entries until the cap is reached. Returns the number of documents processed. */ + private writeIndexEntries; + /** + * Writes entries for the provided collection group. Returns the number of documents processed. + */ + private writeEntriesForCollectionGroup; + /** Returns the next offset based on the provided documents. */ + private getNewOffset; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/index_manager.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/index_manager.d.ts new file mode 100644 index 0000000..6a02ffc --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/index_manager.d.ts @@ -0,0 +1,124 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Target } from '../core/target'; +import { DocumentMap } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { FieldIndex, IndexOffset } from '../model/field_index'; +import { ResourcePath } from '../model/path'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** Represents the index state as it relates to a particular target. */ +export declare const enum IndexType { + /** Indicates that no index could be found for serving the target. */ + NONE = 0, + /** + * Indicates that only a "partial index" could be found for serving the + * target. A partial index is one which does not have a segment for every + * filter/orderBy in the target. + */ + PARTIAL = 1, + /** + * Indicates that a "full index" could be found for serving the target. A full + * index is one which has a segment for every filter/orderBy in the target. + */ + FULL = 2 +} +export declare function displayNameForIndexType(indexType: IndexType): string; +/** + * Represents a set of indexes that are used to execute queries efficiently. + * + * Currently the only index is a [collection id] => [parent path] index, used + * to execute Collection Group queries. + */ +export interface IndexManager { + /** + * Creates an index entry mapping the collectionId (last segment of the path) + * to the parent path (either the containing document location or the empty + * path for root-level collections). Index entries can be retrieved via + * getCollectionParents(). + * + * NOTE: Currently we don't remove index entries. If this ends up being an + * issue we can devise some sort of GC strategy. + */ + addToCollectionParentIndex(transaction: PersistenceTransaction, collectionPath: ResourcePath): PersistencePromise; + /** + * Retrieves all parent locations containing the given collectionId, as a + * list of paths (each path being either a document location or the empty + * path for a root-level collection). + */ + getCollectionParents(transaction: PersistenceTransaction, collectionId: string): PersistencePromise; + /** + * Adds a field path index. + * + * Values for this index are persisted via the index backfill, which runs + * asynchronously in the background. Once the first values are written, + * an index can be used to serve partial results for any matching queries. + * Any unindexed portion of the database will continue to be served via + * collection scons. + */ + addFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + /** Removes the given field index and deletes all index values. */ + deleteFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + /** Removes all field indexes and deletes all index values. */ + deleteAllFieldIndexes(transaction: PersistenceTransaction): PersistencePromise; + /** Creates a full matched field index which serves the given target. */ + createTargetIndexes(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Returns a list of field indexes that correspond to the specified collection + * group. + * + * @param collectionGroup The collection group to get matching field indexes + * for. + * @return A collection of field indexes for the specified collection group. + */ + getFieldIndexes(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise; + /** Returns all configured field indexes. */ + getFieldIndexes(transaction: PersistenceTransaction): PersistencePromise; + /** + * Returns the type of index (if any) that can be used to serve the given + * target. + */ + getIndexType(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Returns the documents that match the given target based on the provided + * index or `null` if the target does not have a matching index. + */ + getDocumentsMatchingTarget(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Returns the next collection group to update. Returns `null` if no group + * exists. + */ + getNextCollectionGroupToUpdate(transaction: PersistenceTransaction): PersistencePromise; + /** + * Sets the collection group's latest read time. + * + * This method updates the index offset for all field indices for the + * collection group and increments their sequence number. Subsequent calls to + * `getNextCollectionGroupToUpdate()` will return a different collection group + * (unless only one collection group is configured). + */ + updateCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset): PersistencePromise; + /** Updates the index entries for the provided documents. */ + updateIndexEntries(transaction: PersistenceTransaction, documents: DocumentMap): PersistencePromise; + /** + * Iterates over all field indexes that are used to serve the given target, + * and returns the minimum offset of them all. + */ + getMinOffset(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** Returns the minimum offset for the given collection group. */ + getMinOffsetFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_bundle_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_bundle_cache.d.ts new file mode 100644 index 0000000..60f49fc --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_bundle_cache.d.ts @@ -0,0 +1,27 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BundleMetadata, NamedQuery } from '../core/bundle'; +import { BundleMetadata as ProtoBundleMetadata, NamedQuery as ProtoNamedQuery } from '../protos/firestore_bundle_proto'; +import { BundleCache } from './bundle_cache'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +export declare class IndexedDbBundleCache implements BundleCache { + getBundleMetadata(transaction: PersistenceTransaction, bundleId: string): PersistencePromise; + saveBundleMetadata(transaction: PersistenceTransaction, bundleMetadata: ProtoBundleMetadata): PersistencePromise; + getNamedQuery(transaction: PersistenceTransaction, queryName: string): PersistencePromise; + saveNamedQuery(transaction: PersistenceTransaction, query: ProtoNamedQuery): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_document_overlay_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_document_overlay_cache.d.ts new file mode 100644 index 0000000..eda11b2 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_document_overlay_cache.d.ts @@ -0,0 +1,45 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { DocumentKeySet, MutationMap, OverlayMap } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { Overlay } from '../model/overlay'; +import { ResourcePath } from '../model/path'; +import { DocumentOverlayCache } from './document_overlay_cache'; +import { LocalSerializer } from './local_serializer'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** + * Implementation of DocumentOverlayCache using IndexedDb. + */ +export declare class IndexedDbDocumentOverlayCache implements DocumentOverlayCache { + private readonly serializer; + private readonly userId; + /** + * @param serializer - The document serializer. + * @param userId - The userId for which we are accessing overlays. + */ + constructor(serializer: LocalSerializer, userId: string); + static forUser(serializer: LocalSerializer, user: User): IndexedDbDocumentOverlayCache; + getOverlay(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; + getOverlays(transaction: PersistenceTransaction, keys: DocumentKey[]): PersistencePromise; + saveOverlays(transaction: PersistenceTransaction, largestBatchId: number, overlays: MutationMap): PersistencePromise; + removeOverlaysForBatchId(transaction: PersistenceTransaction, documentKeys: DocumentKeySet, batchId: number): PersistencePromise; + getOverlaysForCollection(transaction: PersistenceTransaction, collection: ResourcePath, sinceBatchId: number): PersistencePromise; + getOverlaysForCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, sinceBatchId: number, count: number): PersistencePromise; + private saveOverlay; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_globals_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_globals_cache.d.ts new file mode 100644 index 0000000..2f550f5 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_globals_cache.d.ts @@ -0,0 +1,25 @@ +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ByteString } from '../util/byte_string'; +import { GlobalsCache } from './globals_cache'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +export declare class IndexedDbGlobalsCache implements GlobalsCache { + private globalsStore; + getSessionToken(txn: PersistenceTransaction): PersistencePromise; + setSessionToken(txn: PersistenceTransaction, sessionToken: ByteString): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_index_manager.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_index_manager.d.ts new file mode 100644 index 0000000..8078d1c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_index_manager.d.ts @@ -0,0 +1,136 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { DatabaseId } from '../core/database_info'; +import { Target } from '../core/target'; +import { IndexEntry } from '../index/index_entry'; +import { DocumentMap } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { FieldIndex, IndexOffset } from '../model/field_index'; +import { ResourcePath } from '../model/path'; +import { IndexManager, IndexType } from './index_manager'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** + * A persisted implementation of IndexManager. + * + * PORTING NOTE: Unlike iOS and Android, the Web SDK does not memoize index + * data as it supports multi-tab access. + */ +export declare class IndexedDbIndexManager implements IndexManager { + private readonly databaseId; + /** + * An in-memory copy of the index entries we've already written since the SDK + * launched. Used to avoid re-writing the same entry repeatedly. + * + * This is *NOT* a complete cache of what's in persistence and so can never be + * used to satisfy reads. + */ + private collectionParentsCache; + private readonly uid; + /** + * Maps from a target to its equivalent list of sub-targets. Each sub-target + * contains only one term from the target's disjunctive normal form (DNF). + */ + private targetToDnfSubTargets; + constructor(user: User, databaseId: DatabaseId); + /** + * Adds a new entry to the collection parent index. + * + * Repeated calls for the same collectionPath should be avoided within a + * transaction as IndexedDbIndexManager only caches writes once a transaction + * has been committed. + */ + addToCollectionParentIndex(transaction: PersistenceTransaction, collectionPath: ResourcePath): PersistencePromise; + getCollectionParents(transaction: PersistenceTransaction, collectionId: string): PersistencePromise; + addFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + deleteFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + deleteAllFieldIndexes(transaction: PersistenceTransaction): PersistencePromise; + createTargetIndexes(transaction: PersistenceTransaction, target: Target): PersistencePromise; + getDocumentsMatchingTarget(transaction: PersistenceTransaction, target: Target): PersistencePromise; + private getSubTargets; + /** + * Constructs a key range query on `DbIndexEntryStore` that unions all + * bounds. + */ + private generateIndexRanges; + /** Generates the lower bound for `arrayValue` and `directionalValue`. */ + private generateLowerBound; + /** Generates the upper bound for `arrayValue` and `directionalValue`. */ + private generateUpperBound; + private getFieldIndex; + getIndexType(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Returns the byte encoded form of the directional values in the field index. + * Returns `null` if the document does not have all fields specified in the + * index. + */ + private encodeDirectionalElements; + /** Encodes a single value to the ascending index format. */ + private encodeSingleElement; + /** + * Returns an encoded form of the document key that sorts based on the key + * ordering of the field index. + */ + private encodeDirectionalKey; + /** + * Encodes the given field values according to the specification in `target`. + * For IN queries, a list of possible values is returned. + */ + private encodeValues; + /** + * Encodes the given bounds according to the specification in `target`. For IN + * queries, a list of possible values is returned. + */ + private encodeBound; + /** Returns the byte representation for the provided encoders. */ + private getEncodedBytes; + /** + * Creates a separate encoder for each element of an array. + * + * The method appends each value to all existing encoders (e.g. filter("a", + * "==", "a1").filter("b", "in", ["b1", "b2"]) becomes ["a1,b1", "a1,b2"]). A + * list of new encoders is returned. + */ + private expandIndexValues; + private isInFilter; + getFieldIndexes(transaction: PersistenceTransaction, collectionGroup?: string): PersistencePromise; + getNextCollectionGroupToUpdate(transaction: PersistenceTransaction): PersistencePromise; + updateCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset): PersistencePromise; + updateIndexEntries(transaction: PersistenceTransaction, documents: DocumentMap): PersistencePromise; + private addIndexEntry; + private deleteIndexEntry; + private getExistingIndexEntries; + /** Creates the index entries for the given document. */ + private computeIndexEntries; + /** + * Updates the index entries for the provided document by deleting entries + * that are no longer referenced in `newEntries` and adding all newly added + * entries. + */ + private updateEntries; + private getNextSequenceNumber; + /** + * Returns a new set of IDB ranges that splits the existing range and excludes + * any values that match the `notInValue` from these ranges. As an example, + * '[foo > 2 && foo != 3]` becomes `[foo > 2 && < 3, foo > 3]`. + */ + private createRange; + isRangeMatchable(lowerBound: IndexEntry, upperBound: IndexEntry): boolean; + getMinOffsetFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise; + getMinOffset(transaction: PersistenceTransaction, target: Target): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_lru_delegate.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_lru_delegate.d.ts new file mode 100644 index 0000000..fea8087 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_lru_delegate.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { LruDelegate, LruGarbageCollector } from './lru_garbage_collector'; +import { ReferenceDelegate } from './persistence'; +/** Provides LRU functionality for IndexedDB persistence. */ +export interface IndexedDbLruDelegate extends ReferenceDelegate, LruDelegate { + readonly garbageCollector: LruGarbageCollector; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_lru_delegate_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_lru_delegate_impl.d.ts new file mode 100644 index 0000000..56e5e6b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_lru_delegate_impl.d.ts @@ -0,0 +1,56 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ListenSequenceNumber, TargetId } from '../core/types'; +import { DocumentKey } from '../model/document_key'; +import { IndexedDbLruDelegate } from './indexeddb_lru_delegate'; +import { ActiveTargets, LruGarbageCollector, LruParams } from './lru_garbage_collector'; +import { Persistence } from './persistence'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +import { TargetData } from './target_data'; +/** Provides LRU functionality for IndexedDB persistence. */ +export declare class IndexedDbLruDelegateImpl implements IndexedDbLruDelegate { + private readonly db; + readonly garbageCollector: LruGarbageCollector; + constructor(db: Persistence, params: LruParams); + getSequenceNumberCount(txn: PersistenceTransaction): PersistencePromise; + private orphanedDocumentCount; + forEachTarget(txn: PersistenceTransaction, f: (q: TargetData) => void): PersistencePromise; + forEachOrphanedDocumentSequenceNumber(txn: PersistenceTransaction, f: (sequenceNumber: ListenSequenceNumber) => void): PersistencePromise; + addReference(txn: PersistenceTransaction, targetId: TargetId, key: DocumentKey): PersistencePromise; + removeReference(txn: PersistenceTransaction, targetId: TargetId, key: DocumentKey): PersistencePromise; + removeTargets(txn: PersistenceTransaction, upperBound: ListenSequenceNumber, activeTargetIds: ActiveTargets): PersistencePromise; + markPotentiallyOrphaned(txn: PersistenceTransaction, key: DocumentKey): PersistencePromise; + /** + * Returns true if anything would prevent this document from being garbage + * collected, given that the document in question is not present in any + * targets and has a sequence number less than or equal to the upper bound for + * the collection run. + */ + private isPinned; + removeOrphanedDocuments(txn: PersistenceTransaction, upperBound: ListenSequenceNumber): PersistencePromise; + removeTarget(txn: PersistenceTransaction, targetData: TargetData): PersistencePromise; + updateLimboDocument(txn: PersistenceTransaction, key: DocumentKey): PersistencePromise; + /** + * Call provided function for each document in the cache that is 'orphaned'. Orphaned + * means not a part of any target, so the only entry in the target-document index for + * that document will be the sentinel row (targetId 0), which will also have the sequence + * number for the last time the document was accessed. + */ + private forEachOrphanedDocument; + getCacheSize(txn: PersistenceTransaction): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_mutation_batch_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_mutation_batch_impl.d.ts new file mode 100644 index 0000000..b4f0ac4 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_mutation_batch_impl.d.ts @@ -0,0 +1,35 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentKey } from '../model/document_key'; +import { DbRemoteDocument } from './indexeddb_schema'; +import { DbRemoteDocument as DbRemoteDocumentLegacy } from './indexeddb_schema_legacy'; +import { PersistencePromise } from './persistence_promise'; +import { SimpleDbTransaction } from './simple_db'; +/** + * Delete a mutation batch and the associated document mutations. + * @returns A PersistencePromise of the document mutations that were removed. + */ +export declare function removeMutationBatch(txn: SimpleDbTransaction, userId: string, batch: { + batchId: number; + mutations: Array<{ + key: DocumentKey; + }>; +}): PersistencePromise; +/** + * Returns an approximate size for the given document. + */ +export declare function dbDocumentSize(doc: DbRemoteDocument | DbRemoteDocumentLegacy | null): number; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_mutation_queue.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_mutation_queue.d.ts new file mode 100644 index 0000000..ad62a1d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_mutation_queue.d.ts @@ -0,0 +1,99 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { Query } from '../core/query'; +import { BatchId } from '../core/types'; +import { Timestamp } from '../lite-api/timestamp'; +import { DocumentKeySet } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { Mutation } from '../model/mutation'; +import { MutationBatch } from '../model/mutation_batch'; +import { SortedMap } from '../util/sorted_map'; +import { IndexManager } from './index_manager'; +import { LocalSerializer } from './local_serializer'; +import { MutationQueue } from './mutation_queue'; +import { ReferenceDelegate } from './persistence'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** A mutation queue for a specific user, backed by IndexedDB. */ +export declare class IndexedDbMutationQueue implements MutationQueue { + /** + * The normalized userId (e.g. null UID => "" userId) used to store / + * retrieve mutations. + */ + private userId; + private readonly serializer; + private readonly indexManager; + private readonly referenceDelegate; + /** + * Caches the document keys for pending mutation batches. If the mutation + * has been removed from IndexedDb, the cached value may continue to + * be used to retrieve the batch's document keys. To remove a cached value + * locally, `removeCachedMutationKeys()` should be invoked either directly + * or through `removeMutationBatches()`. + * + * With multi-tab, when the primary client acknowledges or rejects a mutation, + * this cache is used by secondary clients to invalidate the local + * view of the documents that were previously affected by the mutation. + */ + private documentKeysByBatchId; + constructor( + /** + * The normalized userId (e.g. null UID => "" userId) used to store / + * retrieve mutations. + */ + userId: string, serializer: LocalSerializer, indexManager: IndexManager, referenceDelegate: ReferenceDelegate); + /** + * Creates a new mutation queue for the given user. + * @param user - The user for which to create a mutation queue. + * @param serializer - The serializer to use when persisting to IndexedDb. + */ + static forUser(user: User, serializer: LocalSerializer, indexManager: IndexManager, referenceDelegate: ReferenceDelegate): IndexedDbMutationQueue; + checkEmpty(transaction: PersistenceTransaction): PersistencePromise; + addMutationBatch(transaction: PersistenceTransaction, localWriteTime: Timestamp, baseMutations: Mutation[], mutations: Mutation[]): PersistencePromise; + lookupMutationBatch(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + /** + * Returns the document keys for the mutation batch with the given batchId. + * For primary clients, this method returns `null` after + * `removeMutationBatches()` has been called. Secondary clients return a + * cached result until `removeCachedMutationKeys()` is invoked. + */ + lookupMutationKeys(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + getNextMutationBatchAfterBatchId(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + getHighestUnacknowledgedBatchId(transaction: PersistenceTransaction): PersistencePromise; + getAllMutationBatches(transaction: PersistenceTransaction): PersistencePromise; + getAllMutationBatchesAffectingDocumentKey(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + getAllMutationBatchesAffectingDocumentKeys(transaction: PersistenceTransaction, documentKeys: SortedMap): PersistencePromise; + getAllMutationBatchesAffectingQuery(transaction: PersistenceTransaction, query: Query): PersistencePromise; + private lookupMutationBatches; + removeMutationBatch(transaction: PersistenceTransaction, batch: MutationBatch): PersistencePromise; + /** + * Clears the cached keys for a mutation batch. This method should be + * called by secondary clients after they process mutation updates. + * + * Note that this method does not have to be called from primary clients as + * the corresponding cache entries are cleared when an acknowledged or + * rejected batch is removed from the mutation queue. + */ + removeCachedMutationKeys(batchId: BatchId): void; + performConsistencyCheck(txn: PersistenceTransaction): PersistencePromise; + containsKey(txn: PersistenceTransaction, key: DocumentKey): PersistencePromise; + /** Returns the mutation queue's metadata from IndexedDb. */ + private getMutationQueueMetadata; +} +/** Returns true if any mutation queue contains the given document. */ +export declare function mutationQueuesContainKey(txn: PersistenceTransaction, docKey: DocumentKey): PersistencePromise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_persistence.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_persistence.d.ts new file mode 100644 index 0000000..f4cf7d8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_persistence.d.ts @@ -0,0 +1,270 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { DatabaseId } from '../core/database_info'; +import { SequenceNumberSyncer } from '../core/listen_sequence'; +import { JsonProtoSerializer } from '../remote/serializer'; +import { AsyncQueue } from '../util/async_queue'; +import { DocumentLike, WindowLike } from '../util/types'; +import { BundleCache } from './bundle_cache'; +import { DocumentOverlayCache } from './document_overlay_cache'; +import { GlobalsCache } from './globals_cache'; +import { IndexManager } from './index_manager'; +import { IndexedDbLruDelegateImpl } from './indexeddb_lru_delegate_impl'; +import { IndexedDbMutationQueue } from './indexeddb_mutation_queue'; +import { IndexedDbRemoteDocumentCache } from './indexeddb_remote_document_cache'; +import { IndexedDbTargetCache } from './indexeddb_target_cache'; +import { LruParams } from './lru_garbage_collector'; +import { Persistence, PrimaryStateListener } from './persistence'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction, PersistenceTransactionMode } from './persistence_transaction'; +import { ClientId } from './shared_client_state'; +/** + * The name of the main (and currently only) IndexedDB database. This name is + * appended to the prefix provided to the IndexedDbPersistence constructor. + */ +export declare const MAIN_DATABASE = "main"; +/** + * An IndexedDB-backed instance of Persistence. Data is stored persistently + * across sessions. + * + * On Web only, the Firestore SDKs support shared access to its persistence + * layer. This allows multiple browser tabs to read and write to IndexedDb and + * to synchronize state even without network connectivity. Shared access is + * currently optional and not enabled unless all clients invoke + * `enablePersistence()` with `{synchronizeTabs:true}`. + * + * In multi-tab mode, if multiple clients are active at the same time, the SDK + * will designate one client as the "primary client". An effort is made to pick + * a visible, network-connected and active client, and this client is + * responsible for letting other clients know about its presence. The primary + * client writes a unique client-generated identifier (the client ID) to + * IndexedDb’s "owner" store every 4 seconds. If the primary client fails to + * update this entry, another client can acquire the lease and take over as + * primary. + * + * Some persistence operations in the SDK are designated as primary-client only + * operations. This includes the acknowledgment of mutations and all updates of + * remote documents. The effects of these operations are written to persistence + * and then broadcast to other tabs via LocalStorage (see + * `WebStorageSharedClientState`), which then refresh their state from + * persistence. + * + * Similarly, the primary client listens to notifications sent by secondary + * clients to discover persistence changes written by secondary clients, such as + * the addition of new mutations and query targets. + * + * If multi-tab is not enabled and another tab already obtained the primary + * lease, IndexedDbPersistence enters a failed state and all subsequent + * operations will automatically fail. + * + * Additionally, there is an optimization so that when a tab is closed, the + * primary lease is released immediately (this is especially important to make + * sure that a refreshed tab is able to immediately re-acquire the primary + * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload + * since it is an asynchronous API. So in addition to attempting to give up the + * lease, the leaseholder writes its client ID to a "zombiedClient" entry in + * LocalStorage which acts as an indicator that another tab should go ahead and + * take the primary lease immediately regardless of the current lease timestamp. + * + * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no + * longer optional. + */ +export declare class IndexedDbPersistence implements Persistence { + /** + * Whether to synchronize the in-memory state of multiple tabs and share + * access to local persistence. + */ + private readonly allowTabSynchronization; + private readonly persistenceKey; + private readonly clientId; + private readonly queue; + private readonly window; + private readonly document; + private readonly sequenceNumberSyncer; + /** + * If set to true, forcefully obtains database access. Existing tabs will + * no longer be able to access IndexedDB. + */ + private readonly forceOwningTab; + private readonly schemaVersion; + private simpleDb; + private listenSequence; + private _started; + private isPrimary; + private networkEnabled; + private dbName; + /** Our window.unload handler, if registered. */ + private windowUnloadHandler; + private inForeground; + private serializer; + /** Our 'visibilitychange' listener if registered. */ + private documentVisibilityHandler; + /** The client metadata refresh task. */ + private clientMetadataRefresher; + /** The last time we garbage collected the client metadata object store. */ + private lastGarbageCollectionTime; + /** A listener to notify on primary state changes. */ + private primaryStateListener; + private readonly globalsCache; + private readonly targetCache; + private readonly remoteDocumentCache; + private readonly bundleCache; + private readonly webStorage; + readonly referenceDelegate: IndexedDbLruDelegateImpl; + constructor( + /** + * Whether to synchronize the in-memory state of multiple tabs and share + * access to local persistence. + */ + allowTabSynchronization: boolean, persistenceKey: string, clientId: ClientId, lruParams: LruParams, queue: AsyncQueue, window: WindowLike | null, document: DocumentLike | null, serializer: JsonProtoSerializer, sequenceNumberSyncer: SequenceNumberSyncer, + /** + * If set to true, forcefully obtains database access. Existing tabs will + * no longer be able to access IndexedDB. + */ + forceOwningTab: boolean, schemaVersion?: number); + /** + * Attempt to start IndexedDb persistence. + * + * @returns Whether persistence was enabled. + */ + start(): Promise; + /** + * Registers a listener that gets called when the primary state of the + * instance changes. Upon registering, this listener is invoked immediately + * with the current primary state. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setPrimaryStateListener(primaryStateListener: PrimaryStateListener): Promise; + /** + * Registers a listener that gets called when the database receives a + * version change event indicating that it has deleted. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setDatabaseDeletedListener(databaseDeletedListener: () => Promise): void; + /** + * Adjusts the current network state in the client's metadata, potentially + * affecting the primary lease. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setNetworkEnabled(networkEnabled: boolean): void; + /** + * Updates the client metadata in IndexedDb and attempts to either obtain or + * extend the primary lease for the local client. Asynchronously notifies the + * primary state listener if the client either newly obtained or released its + * primary lease. + */ + private updateClientMetadataAndTryBecomePrimary; + private verifyPrimaryLease; + private removeClientMetadata; + /** + * If the garbage collection threshold has passed, prunes the + * RemoteDocumentChanges and the ClientMetadata store based on the last update + * time of all clients. + */ + private maybeGarbageCollectMultiClientState; + /** + * Schedules a recurring timer to update the client metadata and to either + * extend or acquire the primary lease if the client is eligible. + */ + private scheduleClientMetadataAndPrimaryLeaseRefreshes; + /** Checks whether `client` is the local client. */ + private isLocalClient; + /** + * Evaluate the state of all active clients and determine whether the local + * client is or can act as the holder of the primary lease. Returns whether + * the client is eligible for the lease, but does not actually acquire it. + * May return 'false' even if there is no active leaseholder and another + * (foreground) client should become leaseholder instead. + */ + private canActAsPrimary; + shutdown(): Promise; + /** + * Returns clients that are not zombied and have an updateTime within the + * provided threshold. + */ + private filterActiveClients; + /** + * Returns the IDs of the clients that are currently active. If multi-tab + * is not supported, returns an array that only contains the local client's + * ID. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + getActiveClients(): Promise; + get started(): boolean; + getGlobalsCache(): GlobalsCache; + getMutationQueue(user: User, indexManager: IndexManager): IndexedDbMutationQueue; + getTargetCache(): IndexedDbTargetCache; + getRemoteDocumentCache(): IndexedDbRemoteDocumentCache; + getIndexManager(user: User): IndexManager; + getDocumentOverlayCache(user: User): DocumentOverlayCache; + getBundleCache(): BundleCache; + runTransaction(action: string, mode: PersistenceTransactionMode, transactionOperation: (transaction: PersistenceTransaction) => PersistencePromise): Promise; + /** + * Verifies that the current tab is the primary leaseholder or alternatively + * that the leaseholder has opted into multi-tab synchronization. + */ + private verifyAllowTabSynchronization; + /** + * Obtains or extends the new primary lease for the local client. This + * method does not verify that the client is eligible for this lease. + */ + private acquireOrExtendPrimaryLease; + static isAvailable(): boolean; + /** Checks the primary lease and removes it if we are the current primary. */ + private releasePrimaryLeaseIfHeld; + /** Verifies that `updateTimeMs` is within `maxAgeMs`. */ + private isWithinAge; + private attachVisibilityHandler; + private detachVisibilityHandler; + /** + * Attaches a window.unload handler that will synchronously write our + * clientId to a "zombie client id" location in LocalStorage. This can be used + * by tabs trying to acquire the primary lease to determine that the lease + * is no longer valid even if the timestamp is recent. This is particularly + * important for the refresh case (so the tab correctly re-acquires the + * primary lease). LocalStorage is used for this rather than IndexedDb because + * it is a synchronous API and so can be used reliably from an unload + * handler. + */ + private attachWindowUnloadHook; + private detachWindowUnloadHook; + /** + * Returns whether a client is "zombied" based on its LocalStorage entry. + * Clients become zombied when their tab closes without running all of the + * cleanup logic in `shutdown()`. + */ + private isClientZombied; + /** + * Record client as zombied (a client that had its tab closed). Zombied + * clients are ignored during primary tab selection. + */ + private markClientZombied; + /** Removes the zombied client entry if it exists. */ + private removeClientZombiedEntry; + private zombiedClientLocalStorageKey; +} +/** + * Generates a string used as a prefix when storing data in IndexedDB and + * LocalStorage. + */ +export declare function indexedDbStoragePrefix(databaseId: DatabaseId, persistenceKey: string): string; +export declare function indexedDbClearPersistence(persistenceKey: string): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_remote_document_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_remote_document_cache.d.ts new file mode 100644 index 0000000..14532c1 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_remote_document_cache.d.ts @@ -0,0 +1,36 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { MutableDocument } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { LocalSerializer } from './local_serializer'; +import { RemoteDocumentCache } from './remote_document_cache'; +export interface DocumentSizeEntry { + document: MutableDocument; + size: number; +} +export interface IndexedDbRemoteDocumentCache extends RemoteDocumentCache { +} +/** Creates a new IndexedDbRemoteDocumentCache. */ +export declare function newIndexedDbRemoteDocumentCache(serializer: LocalSerializer): IndexedDbRemoteDocumentCache; +/** + * Comparator that compares document keys according to the primary key sorting + * used by the `DbRemoteDocumentDocument` store (by prefix path, collection id + * and then document ID). + * + * Visible for testing. + */ +export declare function dbKeyComparator(l: DocumentKey, r: DocumentKey): number; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_schema.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_schema.d.ts new file mode 100644 index 0000000..a88f237 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_schema.d.ts @@ -0,0 +1,509 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BatchId, ListenSequenceNumber, TargetId } from '../core/types'; +import { IndexKind } from '../model/field_index'; +import { BundledQuery } from '../protos/firestore_bundle_proto'; +import { Document as ProtoDocument, DocumentsTarget as ProtoDocumentsTarget, QueryTarget as ProtoQueryTarget, Write as ProtoWrite } from '../protos/firestore_proto_api'; +import { EncodedResourcePath } from './encoded_resource_path'; +import { DbTimestampKey, KeySafeBytes } from './indexeddb_sentinels'; +/** + * Schema Version for the Web client: + * 1. Initial version including Mutation Queue, Query Cache, and Remote + * Document Cache + * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No + * longer required because migration 3 unconditionally clears it. + * 3. Dropped and re-created Query Cache to deal with cache corruption related + * to limbo resolution. Addresses + * https://github.com/firebase/firebase-ios-sdk/issues/1548 + * 4. Multi-Tab Support. + * 5. Removal of held write acks. + * 6. Create document global for tracking document cache size. + * 7. Ensure every cached document has a sentinel row with a sequence number. + * 8. Add collection-parent index for Collection Group queries. + * 9. Change RemoteDocumentChanges store to be keyed by readTime rather than + * an auto-incrementing ID. This is required for Index-Free queries. + * 10. Rewrite the canonical IDs to the explicit Protobuf-based format. + * 11. Add bundles and named_queries for bundle support. + * 12. Add document overlays. + * 13. Rewrite the keys of the remote document cache to allow for efficient + * document lookup via `getAll()`. + * 14. Add overlays. + * 15. Add indexing support. + * 16. Parse timestamp strings before creating index entries. + * 17. TODO(tomandersen) + * 18. Encode key safe representations of IndexEntry in DbIndexEntryStore. + */ +export declare const SCHEMA_VERSION = 18; +/** + * Wrapper class to store timestamps (seconds and nanos) in IndexedDb objects. + */ +export interface DbTimestamp { + seconds: number; + nanoseconds: number; +} +/** + * A singleton object to be stored in the 'owner' store in IndexedDb. + * + * A given database can have a single primary tab assigned at a given time. That + * tab must validate that it is still holding the primary lease before every + * operation that requires locked access. The primary tab should regularly + * write an updated timestamp to this lease to prevent other tabs from + * "stealing" the primary lease + */ +export interface DbPrimaryClient { + ownerId: string; + /** Whether to allow shared access from multiple tabs. */ + allowTabSynchronization: boolean; + leaseTimestampMs: number; +} +/** + * An object to be stored in the 'mutationQueues' store in IndexedDb. + * + * Each user gets a single queue of MutationBatches to apply to the server. + * DbMutationQueue tracks the metadata about the queue. + */ +export interface DbMutationQueue { + /** + * The normalized user ID to which this queue belongs. + */ + userId: string; + /** + * An identifier for the highest numbered batch that has been acknowledged + * by the server. All MutationBatches in this queue with batchIds less + * than or equal to this value are considered to have been acknowledged by + * the server. + * + * NOTE: this is deprecated and no longer used by the code. + */ + lastAcknowledgedBatchId: number; + /** + * A stream token that was previously sent by the server. + * + * See StreamingWriteRequest in datastore.proto for more details about + * usage. + * + * After sending this token, earlier tokens may not be used anymore so + * only a single stream token is retained. + * + * NOTE: this is deprecated and no longer used by the code. + */ + lastStreamToken: string; +} +/** + * An object to be stored in the 'mutations' store in IndexedDb. + * + * Represents a batch of user-level mutations intended to be sent to the server + * in a single write. Each user-level batch gets a separate DbMutationBatch + * with a new batchId. + */ +export interface DbMutationBatch { + /** + * The normalized user ID to which this batch belongs. + */ + userId: string; + /** + * An identifier for this batch, allocated using an auto-generated key. + */ + batchId: BatchId; + /** + * The local write time of the batch, stored as milliseconds since the + * epoch. + */ + localWriteTimeMs: number; + /** + * A list of "mutations" that represent a partial base state from when this + * write batch was initially created. During local application of the write + * batch, these baseMutations are applied prior to the real writes in order + * to override certain document fields from the remote document cache. This + * is necessary in the case of non-idempotent writes (e.g. `increment()` + * transforms) to make sure that the local view of the modified documents + * doesn't flicker if the remote document cache receives the result of the + * non-idempotent write before the write is removed from the queue. + * + * These mutations are never sent to the backend. + */ + baseMutations?: ProtoWrite[]; + /** + * A list of mutations to apply. All mutations will be applied atomically. + * + * Mutations are serialized via toMutation(). + */ + mutations: ProtoWrite[]; +} +/** + * An object to be stored in the 'documentMutations' store in IndexedDb. + * + * A manually maintained index of all the mutation batches that affect a given + * document key. The rows in this table are references based on the contents of + * DbMutationBatch.mutations. + */ +export interface DbDocumentMutation { +} +/** + * Represents the known absence of a document at a particular version. + * Stored in IndexedDb as part of a DbRemoteDocument object. + */ +export interface DbNoDocument { + path: string[]; + readTime: DbTimestamp; +} +/** + * Represents a document that is known to exist but whose data is unknown. + * Stored in IndexedDb as part of a DbRemoteDocument object. + */ +export interface DbUnknownDocument { + path: string[]; + version: DbTimestamp; +} +/** + * An object to be stored in the 'remoteDocuments' store in IndexedDb. + * It represents either: + * + * - A complete document. + * - A "no document" representing a document that is known not to exist (at + * some version). + * - An "unknown document" representing a document that is known to exist (at + * some version) but whose contents are unknown. + * + * The document key is split up across `prefixPath`, `collectionGroup` and + * `documentId`. + * + * Note: This is the persisted equivalent of a MaybeDocument and could perhaps + * be made more general if necessary. + */ +export interface DbRemoteDocument { + /** The path to the document's collection (excluding). */ + prefixPath: string[]; + /** The collection ID the document is directly nested under. */ + collectionGroup: string; + /** The document ID. */ + documentId: string; + /** When the document was read from the backend. */ + readTime: DbTimestampKey; + /** + * Set to an instance of DbUnknownDocument if the data for a document is + * not known, but it is known that a document exists at the specified + * version (e.g. it had a successful update applied to it) + */ + unknownDocument?: DbUnknownDocument; + /** + * Set to an instance of a DbNoDocument if it is known that no document + * exists. + */ + noDocument?: DbNoDocument; + /** + * Set to an instance of a Document if there's a cached version of the + * document. + */ + document?: ProtoDocument; + /** + * Documents that were written to the remote document store based on + * a write acknowledgment are marked with `hasCommittedMutations`. These + * documents are potentially inconsistent with the backend's copy and use + * the write's commit version as their document version. + */ + hasCommittedMutations: boolean; +} +/** + * Contains a single entry that has metadata about the remote document cache. + */ +export interface DbRemoteDocumentGlobal { + /** + * Approximately the total size in bytes of all the + * documents in the document cache. + */ + byteSize: number; +} +/** + * The persisted type for a query nested with in the 'targets' store in + * IndexedDb. We use the proto definitions for these two kinds of queries in + * order to avoid writing extra serialization logic. + */ +export type DbQuery = ProtoQueryTarget | ProtoDocumentsTarget; +/** + * An object to be stored in the 'targets' store in IndexedDb. + * + * This is based on and should be kept in sync with the proto used in the iOS + * client. + * + * Each query the client listens to against the server is tracked on disk so + * that the query can be efficiently resumed on restart. + */ +export interface DbTarget { + /** + * An auto-generated sequential numeric identifier for the query. + * + * Queries are stored using their canonicalId as the key, but these + * canonicalIds can be quite long so we additionally assign a unique + * queryId which can be used by referenced data structures (e.g. + * indexes) to minimize the on-disk cost. + */ + targetId: TargetId; + /** + * The canonical string representing this query. This is not unique. + */ + canonicalId: string; + /** + * The last readTime received from the Watch Service for this query. + * + * This is the same value as TargetChange.read_time in the protos. + */ + readTime: DbTimestamp; + /** + * An opaque, server-assigned token that allows watching a query to be + * resumed after disconnecting without retransmitting all the data + * that matches the query. The resume token essentially identifies a + * point in time from which the server should resume sending results. + * + * This is related to the snapshotVersion in that the resumeToken + * effectively also encodes that value, but the resumeToken is opaque + * and sometimes encodes additional information. + * + * A consequence of this is that the resumeToken should be used when + * asking the server to reason about where this client is in the watch + * stream, but the client should use the snapshotVersion for its own + * purposes. + * + * This is the same value as TargetChange.resume_token in the protos. + */ + resumeToken: string; + /** + * A sequence number representing the last time this query was + * listened to, used for garbage collection purposes. + * + * Conventionally this would be a timestamp value, but device-local + * clocks are unreliable and they must be able to create new listens + * even while disconnected. Instead this should be a monotonically + * increasing number that's incremented on each listen call. + * + * This is different from the queryId since the queryId is an + * immutable identifier assigned to the Query on first use while + * lastListenSequenceNumber is updated every time the query is + * listened to. + */ + lastListenSequenceNumber: number; + /** + * Denotes the maximum snapshot version at which the associated query view + * contained no limbo documents. Undefined for data written prior to + * schema version 9. + */ + lastLimboFreeSnapshotVersion?: DbTimestamp; + /** + * The query for this target. + * + * Because canonical ids are not unique we must store the actual query. We + * use the proto to have an object we can persist without having to + * duplicate translation logic to and from a `Query` object. + */ + query: DbQuery; +} +/** + * An object representing an association between a target and a document, or a + * sentinel row marking the last sequence number at which a document was used. + * Each document cached must have a corresponding sentinel row before lru + * garbage collection is enabled. + * + * The target associations and sentinel rows are co-located so that orphaned + * documents and their sequence numbers can be identified efficiently via a scan + * of this store. + */ +export interface DbTargetDocument { + /** + * The targetId identifying a target or 0 for a sentinel row. + */ + targetId: TargetId; + /** + * The path to the document, as encoded in the key. + */ + path: EncodedResourcePath; + /** + * If this is a sentinel row, this should be the sequence number of the last + * time the document specified by `path` was used. Otherwise, it should be + * `undefined`. + */ + sequenceNumber?: ListenSequenceNumber; +} +/** + * A record of global state tracked across all Targets, tracked separately + * to avoid the need for extra indexes. + * + * This should be kept in-sync with the proto used in the iOS client. + */ +export interface DbTargetGlobal { + /** + * The highest numbered target id across all targets. + * + * See DbTarget.targetId. + */ + highestTargetId: TargetId; + /** + * The highest numbered lastListenSequenceNumber across all targets. + * + * See DbTarget.lastListenSequenceNumber. + */ + highestListenSequenceNumber: number; + /** + * A global snapshot version representing the last consistent snapshot we + * received from the backend. This is monotonically increasing and any + * snapshots received from the backend prior to this version (e.g. for + * targets resumed with a resumeToken) should be suppressed (buffered) + * until the backend has caught up to this snapshot version again. This + * prevents our cache from ever going backwards in time. + */ + lastRemoteSnapshotVersion: DbTimestamp; + /** + * The number of targets persisted. + */ + targetCount: number; +} +/** + * An object representing an association between a Collection id (e.g. 'messages') + * to a parent path (e.g. '/chats/123') that contains it as a (sub)collection. + * This is used to efficiently find all collections to query when performing + * a Collection Group query. + */ +export interface DbCollectionParent { + /** + * The collectionId (e.g. 'messages') + */ + collectionId: string; + /** + * The path to the parent (either a document location or an empty path for + * a root-level collection). + */ + parent: EncodedResourcePath; +} +/** + * A record of the metadata state of each client. + * + * PORTING NOTE: This is used to synchronize multi-tab state and does not need + * to be ported to iOS or Android. + */ +export interface DbClientMetadata { + /** The auto-generated client id assigned at client startup. */ + clientId: string; + /** The last time this state was updated. */ + updateTimeMs: number; + /** Whether the client's network connection is enabled. */ + networkEnabled: boolean; + /** Whether this client is running in a foreground tab. */ + inForeground: boolean; +} +/** An object representing a bundle loaded by the SDK. */ +export interface DbBundle { + /** The ID of the loaded bundle. */ + bundleId: string; + /** The create time of the loaded bundle. */ + createTime: DbTimestamp; + /** The schema version of the loaded bundle. */ + version: number; +} +/** An object representing a named query loaded by the SDK via a bundle. */ +export interface DbNamedQuery { + /** The name of the query. */ + name: string; + /** The read time of the results saved in the bundle from the named query. */ + readTime: DbTimestamp; + /** The query saved in the bundle. */ + bundledQuery: BundledQuery; +} +/** An object representing the global configuration for a field index. */ +export interface DbIndexConfiguration { + /** + * The index id for this entry. Undefined for indexes that are not yet + * persisted. + */ + indexId?: number; + /** The collection group this index belongs to. */ + collectionGroup: string; + /** The fields to index for this index. */ + fields: Array<[name: string, kind: IndexKind]>; +} +/** + * An object describing how up-to-date the index backfill is for each user and + * index. + */ +export interface DbIndexState { + /** The index id for this entry. */ + indexId: number; + /** The user id for this entry. */ + uid: string; + /** + * A number that indicates when the index was last updated (relative to + * other indexes). + */ + sequenceNumber: number; + /** + * The latest read time that has been indexed by Firestore for this field + * index. Set to `{seconds: 0, nanos: 0}` if no documents have been indexed. + */ + readTime: DbTimestamp; + /** + * The last document that has been indexed for this field index. Empty if + * no documents have been indexed. + */ + documentKey: EncodedResourcePath; + /** + * The largest mutation batch id that has been processed for this index. -1 + * if no mutations have been indexed. + */ + largestBatchId: number; +} +/** An object that stores the encoded entries for all documents and fields. */ +export interface DbIndexEntry { + /** The index id for this entry. */ + indexId: number; + /** The user id for this entry. */ + uid: string; + /** The encoded array index value for this entry. */ + arrayValue: KeySafeBytes; + /** The encoded directional value for equality and inequality filters. */ + directionalValue: KeySafeBytes; + /** + * The document key this entry points to. This entry is encoded by an ordered + * encoder to match the key order of the index. + */ + orderedDocumentKey: KeySafeBytes; + /** The segments of the document key this entry points to. */ + documentKey: string[]; +} +/** + * An object representing a document overlay. + */ +export interface DbDocumentOverlay { + /** The user ID to whom this overlay belongs. */ + userId: string; + /** The path to the collection that contains the document. */ + collectionPath: string; + /** The ID (key) of the document within the collection. */ + documentId: string; + /** The collection group to which the document belongs. */ + collectionGroup: string; + /** The largest batch ID that's been applied for this overlay. */ + largestBatchId: number; + /** The overlay mutation. */ + overlayMutation: ProtoWrite; +} +/** + * An object containing global name/value pair. + */ +export interface DbGlobals { + /** Name is a globally unique identifier for a value. */ + name: string; + /** Value is a general purpose storage for global data. */ + value: Uint8Array; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_schema_converter.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_schema_converter.d.ts new file mode 100644 index 0000000..0daedc5 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_schema_converter.d.ts @@ -0,0 +1,43 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { LocalSerializer } from './local_serializer'; +import { PersistencePromise } from './persistence_promise'; +import { SimpleDbSchemaConverter } from './simple_db'; +/** Performs database creation and schema upgrades. */ +export declare class SchemaConverter implements SimpleDbSchemaConverter { + private readonly serializer; + constructor(serializer: LocalSerializer); + /** + * Performs database creation and schema upgrades. + * + * Note that in production, this method is only ever used to upgrade the schema + * to SCHEMA_VERSION. Different values of toVersion are only used for testing + * and local feature development. + */ + createOrUpgrade(db: IDBDatabase, txn: IDBTransaction, fromVersion: number, toVersion: number): PersistencePromise; + private addDocumentGlobal; + private removeAcknowledgedMutations; + /** + * Ensures that every document in the remote document cache has a corresponding sentinel row + * with a sequence number. Missing rows are given the most recently used sequence number. + */ + private ensureSequenceNumbers; + private createCollectionParentIndex; + private rewriteCanonicalIds; + private rewriteRemoteDocumentCache; + private runOverlayMigration; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_schema_legacy.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_schema_legacy.d.ts new file mode 100644 index 0000000..51716a6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_schema_legacy.d.ts @@ -0,0 +1,29 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Document as ProtoDocument } from '../protos/firestore_proto_api'; +import { DbNoDocument, DbUnknownDocument } from './indexeddb_schema'; +import { DbTimestampKey } from './indexeddb_sentinels'; +export interface DbRemoteDocument { + unknownDocument?: DbUnknownDocument; + noDocument?: DbNoDocument; + document?: ProtoDocument; + hasCommittedMutations?: boolean; + readTime?: DbTimestampKey; + parentPath?: string[]; +} +export type DbRemoteDocumentKey = string[]; +export declare const DbRemoteDocumentStore = "remoteDocuments"; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_sentinels.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_sentinels.d.ts new file mode 100644 index 0000000..acd9785 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_sentinels.d.ts @@ -0,0 +1,267 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BatchId, TargetId } from '../core/types'; +import { ResourcePath } from '../model/path'; +import { EncodedResourcePath } from './encoded_resource_path'; +import { DbDocumentMutation } from './indexeddb_schema'; +/** A timestamp type that can be used in IndexedDb keys. */ +export type DbTimestampKey = [/* seconds */ number, /* nanos */ number]; +export type DbPrimaryClientKey = typeof DbPrimaryClientKey; +/** + * Name of the IndexedDb object store. + * + * Note that the name 'owner' is chosen to ensure backwards compatibility with + * older clients that only supported single locked access to the persistence + * layer. + */ +export declare const DbPrimaryClientStore = "owner"; +/** + * The key string used for the single object that exists in the + * DbPrimaryClient store. + */ +export declare const DbPrimaryClientKey = "owner"; +/** Object keys in the 'mutationQueues' store are userId strings. */ +export type DbMutationQueueKey = string; +/** Name of the IndexedDb object store. */ +export declare const DbMutationQueueStore = "mutationQueues"; +/** Keys are automatically assigned via the userId property. */ +export declare const DbMutationQueueKeyPath = "userId"; +/** The 'mutations' store is keyed by batch ID. */ +export type DbMutationBatchKey = BatchId; +/** Name of the IndexedDb object store. */ +export declare const DbMutationBatchStore = "mutations"; +/** Keys are automatically assigned via the userId, batchId properties. */ +export declare const DbMutationBatchKeyPath = "batchId"; +/** The index name for lookup of mutations by user. */ +export declare const DbMutationBatchUserMutationsIndex = "userMutationsIndex"; +/** The user mutations index is keyed by [userId, batchId] pairs. */ +export declare const DbMutationBatchUserMutationsKeyPath: string[]; +/** + * The key for a db document mutation, which is made up of a userID, path, and + * batchId. Note that the path must be serialized into a form that indexedDB can + * sort. + */ +export type DbDocumentMutationKey = [string, EncodedResourcePath, BatchId]; +/** + * Creates a [userId] key for use in the DbDocumentMutations index to iterate + * over all of a user's document mutations. + */ +export declare function newDbDocumentMutationPrefixForUser(userId: string): [string]; +/** + * Creates a [userId, encodedPath] key for use in the DbDocumentMutations + * index to iterate over all at document mutations for a given path or lower. + */ +export declare function newDbDocumentMutationPrefixForPath(userId: string, path: ResourcePath): [string, EncodedResourcePath]; +/** + * Creates a full index key of [userId, encodedPath, batchId] for inserting + * and deleting into the DbDocumentMutations index. + */ +export declare function newDbDocumentMutationKey(userId: string, path: ResourcePath, batchId: BatchId): DbDocumentMutationKey; +/** + * Because we store all the useful information for this store in the key, + * there is no useful information to store as the value. The raw (unencoded) + * path cannot be stored because IndexedDb doesn't store prototype + * information. + */ +export declare const DbDocumentMutationPlaceholder: DbDocumentMutation; +export declare const DbDocumentMutationStore = "documentMutations"; +export declare const DbRemoteDocumentStore = "remoteDocumentsV14"; +/** + * A key in the 'remoteDocumentsV14' object store is an array containing the + * collection path, the collection group, the read time and the document id. + */ +export type DbRemoteDocumentKey = [ + /** path to collection */ string[], + /** collection group */ string, + /** read time */ DbTimestampKey, + /** document ID */ string +]; +/** + * The primary key of the remote documents store, which allows for efficient + * access by collection path and read time. + */ +export declare const DbRemoteDocumentKeyPath: string[]; +/** An index that provides access to documents by key. */ +export declare const DbRemoteDocumentDocumentKeyIndex = "documentKeyIndex"; +export declare const DbRemoteDocumentDocumentKeyIndexPath: string[]; +/** + * An index that provides access to documents by collection group and read + * time. + * + * This index is used by the index backfiller. + */ +export declare const DbRemoteDocumentCollectionGroupIndex = "collectionGroupIndex"; +export declare const DbRemoteDocumentCollectionGroupIndexPath: string[]; +export declare const DbRemoteDocumentGlobalStore = "remoteDocumentGlobal"; +export declare const DbRemoteDocumentGlobalKey = "remoteDocumentGlobalKey"; +export type DbRemoteDocumentGlobalKey = typeof DbRemoteDocumentGlobalKey; +/** + * A key in the 'targets' object store is a targetId of the query. + */ +export type DbTargetKey = TargetId; +export declare const DbTargetStore = "targets"; +/** Keys are automatically assigned via the targetId property. */ +export declare const DbTargetKeyPath = "targetId"; +/** The name of the queryTargets index. */ +export declare const DbTargetQueryTargetsIndexName = "queryTargetsIndex"; +/** + * The index of all canonicalIds to the targets that they match. This is not + * a unique mapping because canonicalId does not promise a unique name for all + * possible queries, so we append the targetId to make the mapping unique. + */ +export declare const DbTargetQueryTargetsKeyPath: string[]; +/** + * The key for a DbTargetDocument, containing a targetId and an encoded resource + * path. + */ +export type DbTargetDocumentKey = [TargetId, EncodedResourcePath]; +/** Name of the IndexedDb object store. */ +export declare const DbTargetDocumentStore = "targetDocuments"; +/** Keys are automatically assigned via the targetId, path properties. */ +export declare const DbTargetDocumentKeyPath: string[]; +/** The index name for the reverse index. */ +export declare const DbTargetDocumentDocumentTargetsIndex = "documentTargetsIndex"; +/** We also need to create the reverse index for these properties. */ +export declare const DbTargetDocumentDocumentTargetsKeyPath: string[]; +/** + * The type to represent the single allowed key for the DbTargetGlobal store. + */ +export type DbTargetGlobalKey = typeof DbTargetGlobalKey; +/** + * The key string used for the single object that exists in the + * DbTargetGlobal store. + */ +export declare const DbTargetGlobalKey = "targetGlobalKey"; +export declare const DbTargetGlobalStore = "targetGlobal"; +/** + * The key for a DbCollectionParent entry, containing the collection ID + * and the parent path that contains it. Note that the parent path will be an + * empty path in the case of root-level collections. + */ +export type DbCollectionParentKey = [string, EncodedResourcePath]; +/** Name of the IndexedDb object store. */ +export declare const DbCollectionParentStore = "collectionParents"; +/** Keys are automatically assigned via the collectionId, parent properties. */ +export declare const DbCollectionParentKeyPath: string[]; +/** Name of the IndexedDb object store. */ +export declare const DbClientMetadataStore = "clientMetadata"; +/** Keys are automatically assigned via the clientId properties. */ +export declare const DbClientMetadataKeyPath = "clientId"; +/** Object keys in the 'clientMetadata' store are clientId strings. */ +export type DbClientMetadataKey = string; +export type DbBundlesKey = string; +/** Name of the IndexedDb object store. */ +export declare const DbBundleStore = "bundles"; +export declare const DbBundleKeyPath = "bundleId"; +export type DbNamedQueriesKey = string; +/** Name of the IndexedDb object store. */ +export declare const DbNamedQueryStore = "namedQueries"; +export declare const DbNamedQueryKeyPath = "name"; +/** The key for each index consisting of just the index id. */ +export type DbIndexConfigurationKey = number; +/** Name of the IndexedDb object store. */ +export declare const DbIndexConfigurationStore = "indexConfiguration"; +export declare const DbIndexConfigurationKeyPath = "indexId"; +/** + * An index that provides access to the index configurations by collection + * group. + * + * PORTING NOTE: iOS and Android maintain this index in-memory, but this is + * not possible here as the Web client supports concurrent access to + * persistence via multi-tab. + */ +export declare const DbIndexConfigurationCollectionGroupIndex = "collectionGroupIndex"; +export declare const DbIndexConfigurationCollectionGroupIndexPath = "collectionGroup"; +/** The key for each index state consisting of the index id and its user id. */ +export type DbIndexStateKey = [number, string]; +/** Name of the IndexedDb object store. */ +export declare const DbIndexStateStore = "indexState"; +export declare const DbIndexStateKeyPath: string[]; +/** + * An index that provides access to documents in a collection sorted by last + * update time. Used by the backfiller. + * + * PORTING NOTE: iOS and Android maintain this index in-memory, but this is + * not possible here as the Web client supports concurrent access to + * persistence via multi-tab. + */ +export declare const DbIndexStateSequenceNumberIndex = "sequenceNumberIndex"; +export declare const DbIndexStateSequenceNumberIndexPath: string[]; +/** + * Representation of a byte array that is safe for + * use in an IndexedDb key. The value is either + * a "sortable byte string", which is key safe in + * Safari/WebKit, or the value is a Uint8Array, + * which is key safe in other browsers. + */ +export type KeySafeBytes = Uint8Array | string; +/** + * The key for each index entry consists of the index id and its user id, + * the encoded array and directional value for the indexed fields as well as + * an ordered and an encoded document path for the indexed document. + */ +export type DbIndexEntryKey = [ + number, + string, + KeySafeBytes, + KeySafeBytes, + KeySafeBytes, + string[] +]; +/** Name of the IndexedDb object store. */ +export declare const DbIndexEntryStore = "indexEntries"; +export declare const DbIndexEntryKeyPath: string[]; +export declare const DbIndexEntryDocumentKeyIndex = "documentKeyIndex"; +export declare const DbIndexEntryDocumentKeyIndexPath: string[]; +export type DbDocumentOverlayKey = [ + string, + string, + string +]; +/** Name of the IndexedDb object store. */ +export declare const DbDocumentOverlayStore = "documentOverlays"; +export declare const DbDocumentOverlayKeyPath: string[]; +export declare const DbDocumentOverlayCollectionPathOverlayIndex = "collectionPathOverlayIndex"; +export declare const DbDocumentOverlayCollectionPathOverlayIndexPath: string[]; +export declare const DbDocumentOverlayCollectionGroupOverlayIndex = "collectionGroupOverlayIndex"; +export declare const DbDocumentOverlayCollectionGroupOverlayIndexPath: string[]; +/** Name of the IndexedDb object store. */ +export declare const DbGlobalsStore = "globals"; +export declare const DbGlobalsKeyPath = "name"; +/** Names of global values */ +export type DbGlobalsKey = 'sessionToken'; +export declare const V1_STORES: string[]; +export declare const V3_STORES: string[]; +export declare const V4_STORES: string[]; +export declare const V6_STORES: string[]; +export declare const V8_STORES: string[]; +export declare const V11_STORES: string[]; +export declare const V12_STORES: string[]; +export declare const V13_STORES: string[]; +export declare const V14_STORES: string[]; +export declare const V15_STORES: string[]; +export declare const V16_STORES: string[]; +export declare const V17_STORES: string[]; +export declare const V18_STORES: string[]; +/** + * The list of all default IndexedDB stores used throughout the SDK. This is + * used when creating transactions so that access across all stores is done + * atomically. + */ +export declare const ALL_STORES: string[]; +/** Returns the object stores for the provided schema. */ +export declare function getObjectStores(schemaVersion: number): string[]; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_target_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_target_cache.d.ts new file mode 100644 index 0000000..74654fe --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_target_cache.d.ts @@ -0,0 +1,81 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { Target } from '../core/target'; +import { ListenSequenceNumber, TargetId } from '../core/types'; +import { DocumentKeySet } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { IndexedDbLruDelegate } from './indexeddb_lru_delegate'; +import { DbTargetDocument } from './indexeddb_schema'; +import { DbTargetDocumentKey } from './indexeddb_sentinels'; +import { LocalSerializer } from './local_serializer'; +import { ActiveTargets } from './lru_garbage_collector'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +import { SimpleDbStore } from './simple_db'; +import { TargetCache } from './target_cache'; +import { TargetData } from './target_data'; +export declare class IndexedDbTargetCache implements TargetCache { + private readonly referenceDelegate; + private serializer; + constructor(referenceDelegate: IndexedDbLruDelegate, serializer: LocalSerializer); + allocateTargetId(transaction: PersistenceTransaction): PersistencePromise; + getLastRemoteSnapshotVersion(transaction: PersistenceTransaction): PersistencePromise; + getHighestSequenceNumber(transaction: PersistenceTransaction): PersistencePromise; + setTargetsMetadata(transaction: PersistenceTransaction, highestListenSequenceNumber: number, lastRemoteSnapshotVersion?: SnapshotVersion): PersistencePromise; + addTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + updateTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + removeTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Drops any targets with sequence number less than or equal to the upper bound, excepting those + * present in `activeTargetIds`. Document associations for the removed targets are also removed. + * Returns the number of targets removed. + */ + removeTargets(txn: PersistenceTransaction, upperBound: ListenSequenceNumber, activeTargetIds: ActiveTargets): PersistencePromise; + /** + * Call provided function with each `TargetData` that we have cached. + */ + forEachTarget(txn: PersistenceTransaction, f: (q: TargetData) => void): PersistencePromise; + private retrieveMetadata; + private saveMetadata; + private saveTargetData; + /** + * In-place updates the provided metadata to account for values in the given + * TargetData. Saving is done separately. Returns true if there were any + * changes to the metadata. + */ + private updateMetadataFromTargetData; + getTargetCount(transaction: PersistenceTransaction): PersistencePromise; + getTargetData(transaction: PersistenceTransaction, target: Target): PersistencePromise; + addMatchingKeys(txn: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + removeMatchingKeys(txn: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + removeMatchingKeysForTargetId(txn: PersistenceTransaction, targetId: TargetId): PersistencePromise; + getMatchingKeysForTargetId(txn: PersistenceTransaction, targetId: TargetId): PersistencePromise; + containsKey(txn: PersistenceTransaction, key: DocumentKey): PersistencePromise; + /** + * Looks up a TargetData entry by target ID. + * + * @param targetId - The target ID of the TargetData entry to look up. + * @returns The cached TargetData entry, or null if the cache has no entry for + * the target. + */ + getTargetDataForTarget(transaction: PersistenceTransaction, targetId: TargetId): PersistencePromise; +} +/** + * Helper to get a typed SimpleDbStore for the document target object store. + */ +export declare function documentTargetStore(txn: PersistenceTransaction): SimpleDbStore; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_transaction.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_transaction.d.ts new file mode 100644 index 0000000..4d1fc92 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/indexeddb_transaction.d.ts @@ -0,0 +1,25 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ListenSequenceNumber } from '../core/types'; +import { PersistenceTransaction } from './persistence_transaction'; +import { SimpleDbStore, SimpleDbTransaction } from './simple_db'; +export declare class IndexedDbTransaction extends PersistenceTransaction { + readonly simpleDbTransaction: SimpleDbTransaction; + readonly currentSequenceNumber: ListenSequenceNumber; + constructor(simpleDbTransaction: SimpleDbTransaction, currentSequenceNumber: ListenSequenceNumber); +} +export declare function getStore(txn: PersistenceTransaction, store: string): SimpleDbStore; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_documents_view.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_documents_view.d.ts new file mode 100644 index 0000000..8d276c3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_documents_view.d.ts @@ -0,0 +1,127 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Query } from '../core/query'; +import { DocumentKeySet, OverlayMap, DocumentMap, MutableDocumentMap, DocumentKeyMap, OverlayedDocumentMap } from '../model/collections'; +import { Document } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { IndexOffset } from '../model/field_index'; +import { FieldMask } from '../model/field_mask'; +import { DocumentOverlayCache } from './document_overlay_cache'; +import { IndexManager } from './index_manager'; +import { LocalWriteResult } from './local_store_impl'; +import { MutationQueue } from './mutation_queue'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +import { QueryContext } from './query_context'; +import { RemoteDocumentCache } from './remote_document_cache'; +/** + * A readonly view of the local state of all documents we're tracking (i.e. we + * have a cached version in remoteDocumentCache or local mutations for the + * document). The view is computed by applying the mutations in the + * MutationQueue to the RemoteDocumentCache. + */ +export declare class LocalDocumentsView { + readonly remoteDocumentCache: RemoteDocumentCache; + readonly mutationQueue: MutationQueue; + readonly documentOverlayCache: DocumentOverlayCache; + readonly indexManager: IndexManager; + constructor(remoteDocumentCache: RemoteDocumentCache, mutationQueue: MutationQueue, documentOverlayCache: DocumentOverlayCache, indexManager: IndexManager); + /** + * Get the local view of the document identified by `key`. + * + * @returns Local view of the document or null if we don't have any cached + * state for it. + */ + getDocument(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; + /** + * Gets the local view of the documents identified by `keys`. + * + * If we don't have cached state for a document in `keys`, a NoDocument will + * be stored for that key in the resulting set. + */ + getDocuments(transaction: PersistenceTransaction, keys: DocumentKeySet): PersistencePromise; + /** + * Similar to `getDocuments`, but creates the local view from the given + * `baseDocs` without retrieving documents from the local store. + * + * @param transaction - The transaction this operation is scoped to. + * @param docs - The documents to apply local mutations to get the local views. + * @param existenceStateChanged - The set of document keys whose existence state + * is changed. This is useful to determine if some documents overlay needs + * to be recalculated. + */ + getLocalViewOfDocuments(transaction: PersistenceTransaction, docs: MutableDocumentMap, existenceStateChanged?: DocumentKeySet): PersistencePromise; + /** + * Gets the overlayed documents for the given document map, which will include + * the local view of those documents and a `FieldMask` indicating which fields + * are mutated locally, `null` if overlay is a Set or Delete mutation. + */ + getOverlayedDocuments(transaction: PersistenceTransaction, docs: MutableDocumentMap): PersistencePromise; + /** + * Fetches the overlays for {@code docs} and adds them to provided overlay map + * if the map does not already contain an entry for the given document key. + */ + private populateOverlays; + /** + * Computes the local view for the given documents. + * + * @param docs - The documents to compute views for. It also has the base + * version of the documents. + * @param overlays - The overlays that need to be applied to the given base + * version of the documents. + * @param existenceStateChanged - A set of documents whose existence states + * might have changed. This is used to determine if we need to re-calculate + * overlays from mutation queues. + * @return A map represents the local documents view. + */ + computeViews(transaction: PersistenceTransaction, docs: MutableDocumentMap, overlays: OverlayMap, existenceStateChanged: DocumentKeySet): PersistencePromise; + private recalculateAndSaveOverlays; + /** + * Recalculates overlays by reading the documents from remote document cache + * first, and saves them after they are calculated. + */ + recalculateAndSaveOverlaysForDocumentKeys(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise>; + /** + * Performs a query against the local view of all documents. + * + * @param transaction - The persistence transaction. + * @param query - The query to match documents against. + * @param offset - Read time and key to start scanning by (exclusive). + * @param context - A optional tracker to keep a record of important details + * during database local query execution. + */ + getDocumentsMatchingQuery(transaction: PersistenceTransaction, query: Query, offset: IndexOffset, context?: QueryContext): PersistencePromise; + /** + * Given a collection group, returns the next documents that follow the provided offset, along + * with an updated batch ID. + * + * + */ +export declare function setLogLevel(logLevel: LogLevelString): void; +export declare function logDebug(msg: string, ...obj: unknown[]): void; +export declare function logError(msg: string, ...obj: unknown[]): void; +/** + * @internal + */ +export declare function logWarn(msg: string, ...obj: unknown[]): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/logic_utils.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/logic_utils.d.ts new file mode 100644 index 0000000..2333586 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/logic_utils.d.ts @@ -0,0 +1,52 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { CompositeFilter, Filter } from '../core/filter'; +/** + * Provides utility functions that help with boolean logic transformations needed for handling + * complex filters used in queries. + */ +/** + * The `in` filter is only a syntactic sugar over a disjunction of equalities. For instance: `a in + * [1,2,3]` is in fact `a==1 || a==2 || a==3`. This method expands any `in` filter in the given + * input into a disjunction of equality filters and returns the expanded filter. + */ +export declare function computeInExpansion(filter: Filter): Filter; +/** + * Given a composite filter, returns the list of terms in its disjunctive normal form. + * + *

Each element in the return value is one term of the resulting DNF. For instance: For the + * input: (A || B) && C, the DNF form is: (A && C) || (B && C), and the return value is a list + * with two elements: a composite filter that performs (A && C), and a composite filter that + * performs (B && C). + * + * @param filter the composite filter to calculate DNF transform for. + * @return the terms in the DNF transform. + */ +export declare function getDnfTerms(filter: CompositeFilter): Filter[]; +export declare function computeDistributedNormalForm(filter: Filter): Filter; +export declare function applyDistribution(lhs: Filter, rhs: Filter): Filter; +/** + * Applies the associativity property to the given filter and returns the resulting filter. + * + *

    + *
  • A | (B | C) == (A | B) | C == (A | B | C) + *
  • A & (B & C) == (A & B) & C == (A & B & C) + *
+ * + *

For more info, visit: https://en.wikipedia.org/wiki/Associative_property#Propositional_logic + */ +export declare function applyAssociation(filter: Filter): Filter; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/misc.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/misc.d.ts new file mode 100644 index 0000000..95d4d43 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/misc.d.ts @@ -0,0 +1,46 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export type EventHandler = (value: E) => void; +export interface Indexable { + [k: string]: unknown; +} +/** + * A utility class for generating unique alphanumeric IDs of a specified length. + * + * @internal + * Exported internally for testing purposes. + */ +export declare class AutoId { + static newId(): string; +} +export declare function primitiveComparator(left: T, right: T): number; +export interface Equatable { + isEqual(other: T): boolean; +} +/** Compare strings in UTF-8 encoded byte order */ +export declare function compareUtf8Strings(left: string, right: string): number; +export declare function isSurrogate(s: string): boolean; +export interface Iterable { + forEach: (cb: (v: V) => void) => void; +} +/** Helper to compare arrays using isEqual(). */ +export declare function arrayEquals(left: T[], right: T[], comparator: (l: T, r: T) => boolean): boolean; +/** + * Returns the immediate lexicographically-following string. This is useful to + * construct an inclusive range for indexeddb iterators. + */ +export declare function immediateSuccessor(s: string): string; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/node_api.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/node_api.d.ts new file mode 100644 index 0000000..2285e8e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/node_api.d.ts @@ -0,0 +1,58 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Creates a node-style callback that resolves or rejects a new Promise. The + * callback is passed to the given action which can then use the callback as + * a parameter to a node-style function. + * + * The intent is to directly bridge a node-style function (which takes a + * callback) into a Promise without manually converting between the node-style + * callback and the promise at each call. + * + * In effect it allows you to convert: + * + * @example + * new Promise((resolve: (value?: fs.Stats) => void, + * reject: (error?: any) => void) => { + * fs.stat(path, (error?: any, stat?: fs.Stats) => { + * if (error) { + * reject(error); + * } else { + * resolve(stat); + * } + * }); + * }); + * + * Into + * @example + * nodePromise((callback: NodeCallback) => { + * fs.stat(path, callback); + * }); + * + * @param action - a function that takes a node-style callback as an argument + * and then uses that callback to invoke some node-style API. + * @returns a new Promise which will be rejected if the callback is given the + * first Error parameter or will resolve to the value given otherwise. + */ +export declare function nodePromise(action: (callback: NodeCallback) => void): Promise; +/** + * A node-style callback which passes an Error as the first argument if there + * was an error, or passes null and a proper value + */ +export interface NodeCallback { + (error?: unknown, value?: R): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/obj.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/obj.d.ts new file mode 100644 index 0000000..90bf468 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/obj.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export interface Dict { + [stringKey: string]: V; +} +export declare function objectSize(obj: object): number; +export declare function forEach(obj: Dict | undefined, fn: (key: string, val: V) => void): void; +export declare function mapToArray(obj: Dict, fn: (element: V, key: string, obj: Dict) => R): R[]; +export declare function isEmpty(obj: Dict): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/obj_map.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/obj_map.d.ts new file mode 100644 index 0000000..f858bcf --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/obj_map.d.ts @@ -0,0 +1,48 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A map implementation that uses objects as keys. Objects must have an + * associated equals function and must be immutable. Entries in the map are + * stored together with the key being produced from the mapKeyFn. This map + * automatically handles collisions of keys. + */ +export declare class ObjectMap { + private mapKeyFn; + private equalsFn; + /** + * The inner map for a key/value pair. Due to the possibility of collisions we + * keep a list of entries that we do a linear search through to find an actual + * match. Note that collisions should be rare, so we still expect near + * constant time lookups in practice. + */ + private inner; + /** The number of entries stored in the map */ + private innerSize; + constructor(mapKeyFn: (key: KeyType) => string, equalsFn: (l: KeyType, r: KeyType) => boolean); + /** Get a value for this key, or undefined if it does not exist. */ + get(key: KeyType): ValueType | undefined; + has(key: KeyType): boolean; + /** Put this key and value in the map. */ + set(key: KeyType, value: ValueType): void; + /** + * Remove this key from the map. Returns a boolean if anything was deleted. + */ + delete(key: KeyType): boolean; + forEach(fn: (key: KeyType, val: ValueType) => void): void; + isEmpty(): boolean; + size(): number; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/promise.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/promise.d.ts new file mode 100644 index 0000000..f966068 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/promise.d.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export interface Resolver { + (value: R | Promise): void; +} +export interface Rejecter { + (reason?: Error): void; +} +export declare class Deferred { + promise: Promise; + resolve: Resolver; + reject: Rejecter; + constructor(); +} +/** + * Takes an array of values and a function from a value to a Promise. The function is run on each + * value sequentially, waiting for the previous promise to resolve before starting the next one. + * The returned promise resolves once the function has been run on all values. + */ +export declare function sequence(values: T[], fn: (value: T) => Promise): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/sorted_map.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/sorted_map.d.ts new file mode 100644 index 0000000..5060fa5 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/sorted_map.d.ts @@ -0,0 +1,100 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export type Comparator = (key1: K, key2: K) => number; +export interface Entry { + key: K; + value: V; +} +export declare class SortedMap { + comparator: Comparator; + root: LLRBNode | LLRBEmptyNode; + constructor(comparator: Comparator, root?: LLRBNode | LLRBEmptyNode); + insert(key: K, value: V): SortedMap; + remove(key: K): SortedMap; + get(key: K): V | null; + indexOf(key: K): number; + isEmpty(): boolean; + get size(): number; + minKey(): K | null; + maxKey(): K | null; + inorderTraversal(action: (k: K, v: V) => T): T; + forEach(fn: (k: K, v: V) => void): void; + toString(): string; + reverseTraversal(action: (k: K, v: V) => T): T; + getIterator(): SortedMapIterator; + getIteratorFrom(key: K): SortedMapIterator; + getReverseIterator(): SortedMapIterator; + getReverseIteratorFrom(key: K): SortedMapIterator; +} +export declare class SortedMapIterator { + private isReverse; + private nodeStack; + constructor(node: LLRBNode | LLRBEmptyNode, startKey: K | null, comparator: Comparator, isReverse: boolean); + getNext(): Entry; + hasNext(): boolean; + peek(): Entry | null; +} +export declare class LLRBNode { + key: K; + value: V; + readonly color: boolean; + readonly left: LLRBNode | LLRBEmptyNode; + readonly right: LLRBNode | LLRBEmptyNode; + readonly size: number; + static EMPTY: LLRBEmptyNode; + static RED: boolean; + static BLACK: boolean; + constructor(key: K, value: V, color?: boolean, left?: LLRBNode | LLRBEmptyNode, right?: LLRBNode | LLRBEmptyNode); + copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode | LLRBEmptyNode | null, right: LLRBNode | LLRBEmptyNode | null): LLRBNode; + isEmpty(): boolean; + inorderTraversal(action: (k: K, v: V) => T): T; + reverseTraversal(action: (k: K, v: V) => T): T; + private min; + minKey(): K | null; + maxKey(): K | null; + insert(key: K, value: V, comparator: Comparator): LLRBNode; + private removeMin; + remove(key: K, comparator: Comparator): LLRBNode | LLRBEmptyNode; + isRed(): boolean; + private fixUp; + private moveRedLeft; + private moveRedRight; + private rotateLeft; + private rotateRight; + private colorFlip; + checkMaxDepth(): boolean; + protected check(): number; +} +export declare class LLRBEmptyNode { + get key(): never; + get value(): never; + get color(): never; + get left(): never; + get right(): never; + size: number; + copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode | LLRBEmptyNode | null, right: LLRBNode | LLRBEmptyNode | null): LLRBEmptyNode; + insert(key: K, value: V, comparator: Comparator): LLRBNode; + remove(key: K, comparator: Comparator): LLRBEmptyNode; + isEmpty(): boolean; + inorderTraversal(action: (k: K, v: V) => boolean): boolean; + reverseTraversal(action: (k: K, v: V) => boolean): boolean; + minKey(): K | null; + maxKey(): K | null; + isRed(): boolean; + checkMaxDepth(): boolean; + protected check(): 0; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/sorted_set.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/sorted_set.d.ts new file mode 100644 index 0000000..ff6aedc --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/sorted_set.d.ts @@ -0,0 +1,80 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SortedMapIterator } from './sorted_map'; +/** + * SortedSet is an immutable (copy-on-write) collection that holds elements + * in order specified by the provided comparator. + * + * NOTE: if provided comparator returns 0 for two elements, we consider them to + * be equal! + */ +export declare class SortedSet { + private comparator; + private data; + constructor(comparator: (left: T, right: T) => number); + has(elem: T): boolean; + first(): T | null; + last(): T | null; + get size(): number; + indexOf(elem: T): number; + /** Iterates elements in order defined by "comparator" */ + forEach(cb: (elem: T) => void): void; + /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ + forEachInRange(range: [T, T], cb: (elem: T) => void): void; + /** + * Iterates over `elem`s such that: start <= elem until false is returned. + */ + forEachWhile(cb: (elem: T) => boolean, start?: T): void; + /** Finds the least element greater than or equal to `elem`. */ + firstAfterOrEqual(elem: T): T | null; + getIterator(): SortedSetIterator; + getIteratorFrom(key: T): SortedSetIterator; + /** Inserts or updates an element */ + add(elem: T): SortedSet; + /** Deletes an element */ + delete(elem: T): SortedSet; + isEmpty(): boolean; + unionWith(other: SortedSet): SortedSet; + isEqual(other: SortedSet): boolean; + toArray(): T[]; + toString(): string; + private copy; +} +export declare class SortedSetIterator { + private iter; + constructor(iter: SortedMapIterator); + getNext(): T; + hasNext(): boolean; +} +/** + * Compares two sorted sets for equality using their natural ordering. The + * method computes the intersection and invokes `onAdd` for every element that + * is in `after` but not `before`. `onRemove` is invoked for every element in + * `before` but missing from `after`. + * + * The method creates a copy of both `before` and `after` and runs in O(n log + * n), where n is the size of the two lists. + * + * @param before - The elements that exist in the original set. + * @param after - The elements to diff against the original set. + * @param comparator - The comparator for the elements in before and after. + * @param onAdd - A function to invoke for every element that is part of ` + * after` but not `before`. + * @param onRemove - A function to invoke for every element that is part of + * `before` but not `after`. + */ +export declare function diffSortedSets(before: SortedSet, after: SortedSet, comparator: (l: T, r: T) => number, onAdd: (entry: T) => void, onRemove: (entry: T) => void): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/testing_hooks.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/testing_hooks.d.ts new file mode 100644 index 0000000..90c6a65 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/testing_hooks.d.ts @@ -0,0 +1,52 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Unsubscribe } from '../api/reference_impl'; +import { ExistenceFilterMismatchInfo } from './testing_hooks_spi'; +/** + * Testing hooks for use by Firestore's integration test suite to reach into the + * SDK internals to validate logic and behavior that is not visible from the + * public API surface. + * + * @internal + */ +export declare class TestingHooks { + private constructor(); + /** + * Registers a callback to be notified when an existence filter mismatch + * occurs in the Watch listen stream. + * + * The relative order in which callbacks are notified is unspecified; do not + * rely on any particular ordering. If a given callback is registered multiple + * times then it will be notified multiple times, once per registration. + * + * @param callback the callback to invoke upon existence filter mismatch. + * + * @return a function that, when called, unregisters the given callback; only + * the first invocation of the returned function does anything; all subsequent + * invocations do nothing. + */ + static onExistenceFilterMismatch(callback: ExistenceFilterMismatchCallback): Unsubscribe; +} +/** + * The signature of callbacks registered with + * `TestingUtils.onExistenceFilterMismatch()`. + * + * The return value, if any, is ignored. + * + * @internal + */ +export type ExistenceFilterMismatchCallback = (info: ExistenceFilterMismatchInfo) => unknown; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/testing_hooks_spi.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/testing_hooks_spi.d.ts new file mode 100644 index 0000000..3d456e9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/testing_hooks_spi.d.ts @@ -0,0 +1,93 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The global, singleton instance of TestingHooksSpi. + * + * This variable will be `null` in all cases _except_ when running from + * integration tests that have registered callbacks to be notified of events + * that happen during the test execution. + */ +export declare let testingHooksSpi: TestingHooksSpi | null; +/** + * Sets the value of the `testingHooksSpi` object. + * @param instance the instance to set. + */ +export declare function setTestingHooksSpi(instance: TestingHooksSpi): void; +/** + * The "service provider interface" for the testing hooks. + * + * The implementation of this object will handle the callbacks made by the SDK + * to be handled by the integration tests. + * + * This "SPI" is separated from the implementation to avoid import cycles and + * to enable production builds to fully tree-shake away the testing hooks logic. + */ +export interface TestingHooksSpi { + /** + * Invokes all callbacks registered with + * `TestingHooks.onExistenceFilterMismatch()` with the given info. + */ + notifyOnExistenceFilterMismatch(info: ExistenceFilterMismatchInfo): void; +} +/** + * Information about an existence filter mismatch. + * @internal + */ +export interface ExistenceFilterMismatchInfo { + /** The number of documents that matched the query in the local cache. */ + localCacheCount: number; + /** + * The number of documents that matched the query on the server, as specified + * in the ExistenceFilter message's `count` field. + */ + existenceFilterCount: number; + /** + * The projectId used when checking documents for membership in the bloom + * filter. + */ + projectId: string; + /** + * The databaseId used when checking documents for membership in the bloom + * filter. + */ + databaseId: string; + /** + * Information about the bloom filter provided by Watch in the ExistenceFilter + * message's `unchangedNames` field. If this property is omitted or undefined + * then that means that Watch did _not_ provide a bloom filter. + */ + bloomFilter?: { + /** + * Whether a full requery was averted by using the bloom filter. If false, + * then something happened, such as a false positive, to prevent using the + * bloom filter to avoid a full requery. + */ + applied: boolean; + /** The number of hash functions used in the bloom filter. */ + hashCount: number; + /** The number of bytes in the bloom filter's bitmask. */ + bitmapLength: number; + /** The number of bits of padding in the last byte of the bloom filter. */ + padding: number; + /** + * Tests the given string for membership in the bloom filter created from + * the existence filter; will be undefined if creating the bloom filter + * failed. + */ + mightContain?: (value: string) => boolean; + }; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/types.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/types.d.ts new file mode 100644 index 0000000..a6842fe --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/types.d.ts @@ -0,0 +1,45 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Sentinel value that sorts before any Mutation Batch ID. */ +export declare const BATCHID_UNKNOWN = -1; +export interface StringMap { + [key: string]: string; +} +/** + * Returns whether a variable is either undefined or null. + */ +export declare function isNullOrUndefined(value: unknown): value is null | undefined; +/** Returns whether the value represents -0. */ +export declare function isNegativeZero(value: number): boolean; +/** + * Returns whether a value is an integer and in the safe integer range + * @param value - The value to test for being an integer and in the safe range + */ +export declare function isSafeInteger(value: unknown): boolean; +/** The subset of the browser's Window interface used by the SDK. */ +export interface WindowLike { + readonly localStorage: Storage; + readonly indexedDB: IDBFactory | null; + addEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: EventListener): void; +} +/** The subset of the browser's Document interface used by the SDK. */ +export interface DocumentLike { + readonly visibilityState: DocumentVisibilityState; + addEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: EventListener): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/aggregation.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/aggregation.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/aggregation.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/array_transforms.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/array_transforms.test.d.ts new file mode 100644 index 0000000..c53048a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/array_transforms.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/batch_writes.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/batch_writes.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/batch_writes.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/bundle.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/bundle.test.d.ts new file mode 100644 index 0000000..e2ec7a1 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/bundle.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare const encoder: TextEncoder; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/composite_index_query.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/composite_index_query.test.d.ts new file mode 100644 index 0000000..615869e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/composite_index_query.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/cursor.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/cursor.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/cursor.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/database.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/database.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/database.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/fields.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/fields.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/fields.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/get_options.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/get_options.test.d.ts new file mode 100644 index 0000000..c53048a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/get_options.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/index_configuration.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/index_configuration.test.d.ts new file mode 100644 index 0000000..daa6d5d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/index_configuration.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/numeric_transforms.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/numeric_transforms.test.d.ts new file mode 100644 index 0000000..c53048a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/numeric_transforms.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/persistent_cache_index_manager.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/persistent_cache_index_manager.test.d.ts new file mode 100644 index 0000000..615869e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/persistent_cache_index_manager.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/provider.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/provider.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/provider.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/query.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/query.test.d.ts new file mode 100644 index 0000000..777341d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/query.test.d.ts @@ -0,0 +1,18 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentChange, DocumentChangeType } from '../util/firebase_export'; +export declare function verifyDocumentChange(change: DocumentChange, id: string, oldIndex: number, newIndex: number, type: DocumentChangeType): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/server_timestamp.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/server_timestamp.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/server_timestamp.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/smoke.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/smoke.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/smoke.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/snapshot_listener_source.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/snapshot_listener_source.test.d.ts new file mode 100644 index 0000000..88c3c0e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/snapshot_listener_source.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/transactions.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/transactions.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/transactions.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/type.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/type.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/type.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/validation.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/validation.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api/validation.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/auth.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/auth.test.d.ts new file mode 100644 index 0000000..daa6d5d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/auth.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/database.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/database.test.d.ts new file mode 100644 index 0000000..1c93d90 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/database.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/idle_timeout.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/idle_timeout.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/idle_timeout.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/transaction.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/transaction.test.d.ts new file mode 100644 index 0000000..1c93d90 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/api_internal/transaction.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/bootstrap.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/bootstrap.d.ts new file mode 100644 index 0000000..1391c20 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/bootstrap.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import '../../src/index'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/browser/indexeddb.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/browser/indexeddb.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/browser/indexeddb.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/browser/webchannel.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/browser/webchannel.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/browser/webchannel.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/prime_backend.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/prime_backend.test.d.ts new file mode 100644 index 0000000..c53048a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/prime_backend.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/remote/remote.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/remote/remote.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/remote/remote.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/remote/stream.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/remote/stream.test.d.ts new file mode 100644 index 0000000..4f1864c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/remote/stream.test.d.ts @@ -0,0 +1,54 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { EmptyAuthCredentialsProvider } from '../../../src/api/credentials'; +import { SnapshotVersion } from '../../../src/core/snapshot_version'; +import { MutationResult } from '../../../src/model/mutation'; +import { PersistentListenStream, PersistentWriteStream, WatchStreamListener, WriteStreamListener } from '../../../src/remote/persistent_stream'; +import { DocumentWatchChange, ExistenceFilterChange, WatchTargetChange } from '../../../src/remote/watch_change'; +import { AsyncQueueImpl } from '../../../src/util/async_queue_impl'; +import { FirestoreError } from '../../../src/util/error'; +/** + * StreamEventType combines the events that can be observed by the + * WatchStreamListener and WriteStreamListener. + */ +type StreamEventType = 'handshakeComplete' | 'mutationResult' | 'watchChange' | 'open' | 'close' | 'connected'; +declare class StreamStatusListener implements WatchStreamListener, WriteStreamListener { + private pendingCallbacks; + private pendingPromises; + /** + * Returns a Promise that resolves when the next callback fires. Resolves the + * returned Promise immediately if there is already an unprocessed callback. + * + * This method asserts that the observed callback type matches + * `expectedCallback`. + */ + awaitCallback(expectedCallback: StreamEventType): Promise; + /** + * Verifies that we did not encounter any unexpected callbacks. + */ + verifyNoPendingCallbacks(): void; + onHandshakeComplete(): Promise; + onMutationResult(commitVersion: SnapshotVersion, results: MutationResult[]): Promise; + onWatchChange(watchChange: DocumentWatchChange | WatchTargetChange | ExistenceFilterChange, snapshot: SnapshotVersion): Promise; + onConnected(): Promise; + onOpen(): Promise; + onClose(err?: FirestoreError): Promise; + private resolvePending; +} +export declare function withTestWriteStream(fn: (writeStream: PersistentWriteStream, streamListener: StreamStatusListener, queue: AsyncQueueImpl) => Promise, credentialsProvider?: EmptyAuthCredentialsProvider): Promise; +export declare function withTestWatchStream(fn: (watchStream: PersistentListenStream, streamListener: StreamStatusListener) => Promise): Promise; +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/composite_index_test_helper.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/composite_index_test_helper.d.ts new file mode 100644 index 0000000..39316df --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/composite_index_test_helper.d.ts @@ -0,0 +1,41 @@ +import { CollectionReference, DocumentData, Firestore, Query, QueryConstraint, DocumentReference, QueryCompositeFilterConstraint, QueryNonFilterConstraint, DocumentSnapshot, UpdateData, QuerySnapshot } from './firebase_export'; +import { PERSISTENCE_MODE_UNSPECIFIED, PersistenceMode } from './helpers'; +/** + * This helper class is designed to facilitate integration testing of Firestore queries that + * require composite indexes within a controlled testing environment. + * + *

Key Features: + * + *

    + *
  • Runs tests against the dedicated test collection with predefined composite indexes. + *
  • Automatically associates a test ID with documents for data isolation. + *
  • Utilizes TTL policy for automatic test data cleanup. + *
  • Constructs Firestore queries with test ID filters. + *
+ */ +export declare class CompositeIndexTestHelper { + private readonly testId; + private readonly TEST_ID_FIELD; + private readonly TTL_FIELD; + constructor(); + withTestDocs(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, docs: { + [key: string]: DocumentData; + }, fn: (collection: CollectionReference, db: Firestore) => Promise): Promise; + withTestCollection(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, fn: (collection: CollectionReference, db: Firestore) => Promise): Promise; + private toHashedId; + private toHashedIds; + addTestSpecificFieldsToDoc(doc: DocumentData): DocumentData; + private removeTestSpecificFieldsFromDoc; + private prepareTestDocuments; + assertOnlineAndOfflineResultsMatch(collection: CollectionReference, query: Query, ...expectedDocs: string[]): Promise; + assertSnapshotResultIdsMatch(snapshot: QuerySnapshot, expectedIds: string[]): void; + query(query_: Query, ...queryConstraints: QueryConstraint[]): Query; + compositeQuery(query_: Query, compositeFilter: QueryCompositeFilterConstraint, ...queryConstraints: QueryNonFilterConstraint[]): Query; + getDocRef(coll: CollectionReference, docId: string): DocumentReference; + addDoc(reference: CollectionReference, data: object): Promise>; + setDoc(reference: DocumentReference, data: object): Promise; + updateDoc(reference: DocumentReference, data: UpdateData): Promise; + deleteDoc(reference: DocumentReference): Promise; + getDoc(docRef: DocumentReference): Promise>; + getDocs(query_: Query): Promise>; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/events_accumulator.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/events_accumulator.d.ts new file mode 100644 index 0000000..629d5a9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/events_accumulator.d.ts @@ -0,0 +1,39 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentSnapshot, QuerySnapshot } from './firebase_export'; +/** + * A helper object that can accumulate an arbitrary amount of events and resolve + * a promise when expected number has been emitted. + */ +export declare class EventsAccumulator { + private events; + private waitingFor; + private deferred; + private rejectAdditionalEvents; + storeEvent: (evt: T) => void; + awaitEvents(length: number): Promise; + awaitEvent(): Promise; + /** Waits for a latency compensated local snapshot. */ + awaitLocalEvent(): Promise; + /** Waits for multiple latency compensated local snapshot. */ + awaitLocalEvents(count: number): Promise; + /** Waits for a snapshot that has no pending writes */ + awaitRemoteEvent(): Promise; + assertNoAdditionalEvents(): Promise; + allowAdditionalEvents(): void; + private checkFulfilled; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/firebase_export.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/firebase_export.d.ts new file mode 100644 index 0000000..7d96efd --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/firebase_export.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseApp } from '@firebase/app'; +import { Firestore } from '../../../src'; +import { PrivateSettings } from '../../../src/lite-api/settings'; +export declare function newTestApp(projectId: string, appName?: string): FirebaseApp; +export declare function newTestFirestore(app: FirebaseApp, settings?: PrivateSettings, dbName?: string): Firestore; +export * from '../../../src'; +export { PrivateSettings }; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/helpers.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/helpers.d.ts new file mode 100644 index 0000000..731369e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/helpers.d.ts @@ -0,0 +1,138 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { CollectionReference, DocumentData, DocumentReference, Firestore, MemoryLocalCache, PersistentLocalCache, PrivateSettings, QuerySnapshot, SnapshotListenOptions, Query } from './firebase_export'; +export interface PersistenceMode { + readonly name: string; + readonly storage: 'memory' | 'indexeddb'; + readonly gc: 'eager' | 'lru'; + /** + * Creates and returns a new `PersistenceMode` object that is the nearest + * equivalent to this persistence mode but uses eager garbage collection. + */ + toEagerGc(): PersistenceMode; + /** + * Creates and returns a new `PersistenceMode` object that is the nearest + * equivalent to this persistence mode but uses LRU garbage collection. + */ + toLruGc(): PersistenceMode; + /** + * Creates and returns a new "local cache" object corresponding to this + * persistence type. + */ + asLocalCacheFirestoreSettings(): MemoryLocalCache | PersistentLocalCache; +} +export declare class MemoryEagerPersistenceMode implements PersistenceMode { + readonly name = "memory"; + readonly storage = "memory"; + readonly gc = "eager"; + toEagerGc(): MemoryEagerPersistenceMode; + toLruGc(): MemoryLruPersistenceMode; + asLocalCacheFirestoreSettings(): MemoryLocalCache; +} +export declare class MemoryLruPersistenceMode implements PersistenceMode { + readonly name = "memory_lru_gc"; + readonly storage = "memory"; + readonly gc = "lru"; + toEagerGc(): MemoryEagerPersistenceMode; + toLruGc(): MemoryLruPersistenceMode; + asLocalCacheFirestoreSettings(): MemoryLocalCache; +} +export declare class IndexedDbPersistenceMode implements PersistenceMode { + readonly name = "indexeddb"; + readonly storage = "indexeddb"; + readonly gc = "lru"; + toEagerGc(): MemoryEagerPersistenceMode; + toLruGc(): IndexedDbPersistenceMode; + asLocalCacheFirestoreSettings(): PersistentLocalCache; +} +export declare const PERSISTENCE_MODE_UNSPECIFIED: unique symbol; +export declare function isPersistenceAvailable(): boolean; +type ApiSuiteFunction = (message: string, testSuite: (persistence: PersistenceMode) => void) => void; +interface ApiDescribe { + (message: string, testSuite: (persistence: PersistenceMode) => void): void; + skip: ApiSuiteFunction; + only: ApiSuiteFunction; +} +export declare const apiDescribe: ApiDescribe; +/** Converts the documents in a QuerySnapshot to an array with the data of each document. */ +export declare function toDataArray(docSet: QuerySnapshot): DocumentData[]; +/** Converts the changes in a QuerySnapshot to an array with the data of each document. */ +export declare function toChangesArray(docSet: QuerySnapshot, options?: SnapshotListenOptions): DocumentData[]; +export declare function toDataMap(docSet: QuerySnapshot): { + [field: string]: DocumentData; +}; +/** Converts a DocumentSet to an array with the id of each document */ +export declare function toIds(docSet: QuerySnapshot): string[]; +export declare function withTestDb(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, fn: (db: Firestore) => Promise): Promise; +/** Runs provided fn with a db for an alternate project id. */ +export declare function withAlternateTestDb(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, fn: (db: Firestore) => Promise): Promise; +export declare function withTestDbs(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, numDbs: number, fn: (db: Firestore[]) => Promise): Promise; +export declare function withTestDbsSettings(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, projectId: string, settings: PrivateSettings, numDbs: number, fn: (db: Firestore[]) => Promise): Promise; +export declare function withNamedTestDbsOrSkipUnlessUsingEmulator(persistence: PersistenceMode, dbNames: string[], fn: (db: Firestore[]) => Promise): Promise; +export declare function withTestDoc(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, fn: (doc: DocumentReference, db: Firestore) => Promise): Promise; +export declare function withTestDocAndSettings(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, settings: PrivateSettings, fn: (doc: DocumentReference) => Promise): Promise; +export declare function withTestDocAndInitialData(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, initialData: DocumentData | null, fn: (doc: DocumentReference, db: Firestore) => Promise): Promise; +export declare class RetryError extends Error { + readonly name = "FirestoreIntegrationTestRetryError"; +} +export declare function withRetry(fn: (attemptNumber: number) => Promise): Promise; +export declare function withTestCollection(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, docs: { + [key: string]: DocumentData; +}, fn: (collection: CollectionReference, db: Firestore) => Promise): Promise; +export declare function withEmptyTestCollection(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, fn: (collection: CollectionReference, db: Firestore) => Promise): Promise; +export declare function withTestCollectionSettings(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, settings: PrivateSettings, docs: { + [key: string]: DocumentData; +}, fn: (collection: CollectionReference, db: Firestore) => Promise): Promise; +export declare function batchCommitDocsToCollection(persistence: PersistenceMode | typeof PERSISTENCE_MODE_UNSPECIFIED, settings: PrivateSettings, docs: { + [key: string]: DocumentData; +}, collectionId: string, fn: (collection: CollectionReference, db: Firestore) => Promise): Promise; +/** + * Creates a `docs` argument suitable for specifying to `withTestCollection()` + * that defines subsets of documents with different document data. + * + * This can be useful for pre-populating a collection with some documents that + * match a query and others that do _not_ match that query. + * + * Each key of the given `partitions` object will be considered a partition + * "name". The returned object will specify `documentCount` documents with the + * `documentData` whose document IDs are prefixed with the partition "name". + */ +export declare function partitionedTestDocs(partitions: { + [partitionName: string]: { + documentData: DocumentData; + documentCount: number; + }; +}): { + [key: string]: DocumentData; +}; +/** + * Checks that running the query while online (against the backend/emulator) results in the same + * documents as running the query while offline. If `expectedDocs` is provided, it also checks + * that both online and offline query result is equal to the expected documents. + * + * This function first performs a "get" for the entire COLLECTION from the server. + * It then performs the QUERY from CACHE which, results in `executeFullCollectionScan()` + * It then performs the QUERY from SERVER. + * It then performs the QUERY from CACHE again, which results in `performQueryUsingRemoteKeys()`. + * It then ensure that all the above QUERY results are the same. + * + * @param collection The collection on which the query is performed. + * @param query The query to check + * @param expectedDocs Ordered list of document keys that are expected to match the query + */ +export declare function checkOnlineAndOfflineResultsMatch(collection: Query, query: Query, ...expectedDocs: string[]): Promise; +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/internal_helpers.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/internal_helpers.d.ts new file mode 100644 index 0000000..cd23cb2 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/internal_helpers.d.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { CredentialChangeListener, CredentialsProvider, EmptyAuthCredentialsProvider } from '../../../src/api/credentials'; +import { User } from '../../../src/auth/user'; +import { DatabaseInfo } from '../../../src/core/database_info'; +import { Datastore } from '../../../src/remote/datastore'; +import { AsyncQueue } from '../../../src/util/async_queue'; +import { AsyncQueueImpl } from '../../../src/util/async_queue_impl'; +import { Firestore } from './firebase_export'; +import { PersistenceMode } from './helpers'; +export declare function asyncQueue(db: Firestore): AsyncQueueImpl; +export declare function getDefaultDatabaseInfo(): DatabaseInfo; +export declare function withTestDatastore(fn: (datastore: Datastore) => Promise, authCredentialsProvider?: CredentialsProvider, appCheckTokenProvider?: CredentialsProvider): Promise; +export declare class MockAuthCredentialsProvider extends EmptyAuthCredentialsProvider { + private listener; + private asyncQueue; + triggerUserChange(newUser: User): void; + start(asyncQueue: AsyncQueue, listener: CredentialChangeListener): void; +} +export declare function withMockCredentialProviderTestDb(persistence: PersistenceMode, fn: (db: Firestore, mockCredential: MockAuthCredentialsProvider) => Promise): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/settings.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/settings.d.ts new file mode 100644 index 0000000..850a5f2 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/settings.d.ts @@ -0,0 +1,24 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { PrivateSettings } from './firebase_export'; +export declare const TARGET_DB_ID: string | '(default)'; +export declare const USE_EMULATOR: boolean; +export declare const DEFAULT_SETTINGS: PrivateSettings; +export declare function getEmulatorPort(): number; +export declare const DEFAULT_PROJECT_ID: any; +export declare const ALT_PROJECT_ID = "test-db2"; +export declare const COMPOSITE_INDEX_TEST_COLLECTION = "composite-index-test-collection"; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/testing_hooks_util.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/testing_hooks_util.d.ts new file mode 100644 index 0000000..600f0fd --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/integration/util/testing_hooks_util.d.ts @@ -0,0 +1,44 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentReference } from './firebase_export'; +/** + * Captures all existence filter mismatches in the Watch 'Listen' stream that + * occur during the execution of the given code block. + * @param callback The callback to invoke; during the invocation of this + * callback all existence filter mismatches will be captured. + * @return the captured existence filter mismatches and the result of awaiting + * the given callback. + */ +export declare function captureExistenceFilterMismatches(callback: () => Promise): Promise<[ExistenceFilterMismatchInfo[], T]>; +/** + * Information about an existence filter mismatch, captured during an invocation + * of `captureExistenceFilterMismatches()`. + * + * See the documentation of `ExistenceFilterMismatchInfo` in + * `testing_hooks_spi.ts` for the meaning of these values. + */ +export interface ExistenceFilterMismatchInfo { + localCacheCount: number; + existenceFilterCount: number; + bloomFilter?: { + applied: boolean; + hashCount: number; + bitmapLength: number; + padding: number; + mightContain(documentRef: DocumentReference): boolean; + }; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/lite/bootstrap.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/lite/bootstrap.d.ts new file mode 100644 index 0000000..731d2d9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/lite/bootstrap.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/lite/helpers.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/lite/helpers.d.ts new file mode 100644 index 0000000..1033563 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/lite/helpers.d.ts @@ -0,0 +1,41 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Firestore } from '../../src/lite-api/database'; +import { DocumentData, CollectionReference, DocumentReference, SetOptions, PartialWithFieldValue } from '../../src/lite-api/reference'; +import { FirestoreSettings } from '../../src/lite-api/settings'; +import { QueryDocumentSnapshot } from '../../src/lite-api/snapshot'; +export declare function withTestDbSettings(projectId: string, settings: FirestoreSettings, fn: (db: Firestore) => void | Promise): Promise; +export declare function withTestDb(fn: (db: Firestore) => void | Promise): Promise; +export declare function withTestDoc(fn: (doc: DocumentReference) => void | Promise): Promise; +export declare function withTestDocAndInitialData(data: DocumentData, fn: (doc: DocumentReference) => void | Promise): Promise; +export declare function withTestCollectionAndInitialData(data: DocumentData[], fn: (collRef: CollectionReference) => void | Promise): Promise; +export declare function withTestCollection(fn: (collRef: CollectionReference) => void | Promise): Promise; +export declare class Post { + readonly title: string; + readonly author: string; + readonly id: number; + constructor(title: string, author: string, id?: number); + byline(): string; +} +export declare const postConverter: { + toFirestore(post: Post): DocumentData; + fromFirestore(snapshot: QueryDocumentSnapshot): Post; +}; +export declare const postConverterMerge: { + toFirestore(post: PartialWithFieldValue, options?: SetOptions): DocumentData; + fromFirestore(snapshot: QueryDocumentSnapshot): Post; +}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/lite/integration.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/lite/integration.test.d.ts new file mode 100644 index 0000000..731d2d9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/lite/integration.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/register.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/register.d.ts new file mode 100644 index 0000000..daa6d5d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/register.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/aggregate.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/aggregate.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/aggregate.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/bytes.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/bytes.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/bytes.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/database.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/database.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/database.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/document_change.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/document_change.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/document_change.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/field_path.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/field_path.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/field_path.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/field_value.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/field_value.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/field_value.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/geo_point.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/geo_point.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/geo_point.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/long_polling_options.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/long_polling_options.test.d.ts new file mode 100644 index 0000000..615869e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/long_polling_options.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/timestamp.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/timestamp.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/timestamp.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/vector_value.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/vector_value.test.d.ts new file mode 100644 index 0000000..1a6762b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/api/vector_value.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/bootstrap.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/bootstrap.d.ts new file mode 100644 index 0000000..6a6eae7 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/bootstrap.d.ts @@ -0,0 +1,24 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * This will include all of the test files and compile them as needed + * + * Taken from karma-webpack source: + * https://github.com/webpack-contrib/karma-webpack#alternative-usage + */ +declare const testsContext: any; +declare const browserTests: any; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/event_manager.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/event_manager.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/event_manager.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/filter.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/filter.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/filter.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/listen_sequence.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/listen_sequence.test.d.ts new file mode 100644 index 0000000..c53048a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/listen_sequence.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/query.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/query.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/query.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/view.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/view.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/view.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/webchannel_wrapper.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/webchannel_wrapper.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/core/webchannel_wrapper.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/index/firestore_index_value_writer.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/index/firestore_index_value_writer.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/index/firestore_index_value_writer.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/index/ordered_code_writer.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/index/ordered_code_writer.test.d.ts new file mode 100644 index 0000000..23f261f --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/index/ordered_code_writer.test.d.ts @@ -0,0 +1 @@ +export declare function compare(left: Uint8Array, right: Uint8Array): number; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/lite-api/types.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/lite-api/types.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/lite-api/types.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/bundle_cache.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/bundle_cache.test.d.ts new file mode 100644 index 0000000..731d2d9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/bundle_cache.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/counting_query_engine.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/counting_query_engine.d.ts new file mode 100644 index 0000000..f2f4574 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/counting_query_engine.d.ts @@ -0,0 +1,60 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Query } from '../../../src/core/query'; +import { SnapshotVersion } from '../../../src/core/snapshot_version'; +import { IndexManager } from '../../../src/local/index_manager'; +import { LocalDocumentsView } from '../../../src/local/local_documents_view'; +import { PersistencePromise } from '../../../src/local/persistence_promise'; +import { PersistenceTransaction } from '../../../src/local/persistence_transaction'; +import { QueryEngine } from '../../../src/local/query_engine'; +import { DocumentKeySet, DocumentMap } from '../../../src/model/collections'; +import { MutationType } from '../../../src/model/mutation'; +/** + * A test-only query engine that forwards all API calls and exposes the number + * of documents and mutations read. + */ +export declare class CountingQueryEngine extends QueryEngine { + /** + * The number of overlays returned by the DocumentOverlayCache's + * `getOverlaysByCollection(Group)` API (since the last call to + * `resetCounts()`) + */ + overlaysReadByCollection: number; + /** + * The number of overlays returned by the DocumentOverlayCache's + * `getOverlay(s)` APIs (since the last call to `resetCounts()`) + */ + overlaysReadByKey: number; + overlayTypes: { + [k: string]: MutationType; + }; + /** + * The number of documents returned by the RemoteDocumentCache's + * `getAll()` API (since the last call to `resetCounts()`). + */ + documentsReadByCollection: number; + /** + * The number of documents returned by the RemoteDocumentCache's `getEntry()` + * and `getEntries()` APIs (since the last call to `resetCounts()`) + */ + documentsReadByKey: number; + resetCounts(): void; + getDocumentsMatchingQuery(transaction: PersistenceTransaction, query: Query, lastLimboFreeSnapshotVersion: SnapshotVersion, remoteKeys: DocumentKeySet): PersistencePromise; + initialize(localDocuments: LocalDocumentsView, indexManager: IndexManager): void; + private wrapRemoteDocumentCache; + private wrapOverlayCache; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/document_overlay_cache.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/document_overlay_cache.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/document_overlay_cache.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/encoded_resource_path.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/encoded_resource_path.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/encoded_resource_path.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/globals_cache.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/globals_cache.test.d.ts new file mode 100644 index 0000000..88c3c0e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/globals_cache.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/index_backfiller.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/index_backfiller.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/index_backfiller.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/index_manager.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/index_manager.test.d.ts new file mode 100644 index 0000000..1c93d90 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/index_manager.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/indexeddb_persistence.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/indexeddb_persistence.test.d.ts new file mode 100644 index 0000000..c53048a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/indexeddb_persistence.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/local_serializer.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/local_serializer.test.d.ts new file mode 100644 index 0000000..731d2d9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/local_serializer.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/local_store.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/local_store.test.d.ts new file mode 100644 index 0000000..2ec9c10 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/local_store.test.d.ts @@ -0,0 +1,24 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { LocalStore } from '../../../src/local/local_store'; +import { Persistence } from '../../../src/local/persistence'; +import { CountingQueryEngine } from './counting_query_engine'; +export interface LocalStoreComponents { + queryEngine: CountingQueryEngine; + persistence: Persistence; + localStore: LocalStore; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/local_store_indexeddb.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/local_store_indexeddb.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/local_store_indexeddb.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/lru_garbage_collector.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/lru_garbage_collector.test.d.ts new file mode 100644 index 0000000..c53048a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/lru_garbage_collector.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/mutation_queue.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/mutation_queue.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/mutation_queue.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/persistence_promise.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/persistence_promise.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/persistence_promise.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/persistence_test_helpers.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/persistence_test_helpers.d.ts new file mode 100644 index 0000000..bb4c627 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/persistence_test_helpers.d.ts @@ -0,0 +1,67 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../../../src/auth/user'; +import { DatabaseId } from '../../../src/core/database_info'; +import { SequenceNumberSyncer } from '../../../src/core/listen_sequence'; +import { BatchId, TargetId } from '../../../src/core/types'; +import { IndexedDbPersistence } from '../../../src/local/indexeddb_persistence'; +import { LocalSerializer } from '../../../src/local/local_serializer'; +import { LruParams } from '../../../src/local/lru_garbage_collector'; +import { MemoryPersistence } from '../../../src/local/memory_persistence'; +import { ClientId } from '../../../src/local/shared_client_state'; +import { JsonProtoSerializer } from '../../../src/remote/serializer'; +import { AsyncQueue } from '../../../src/util/async_queue'; +import { WindowLike } from '../../../src/util/types'; +export declare const MOCK_SEQUENCE_NUMBER_SYNCER: SequenceNumberSyncer; +/** The Database ID used by most tests that use a serializer. */ +export declare const TEST_PROJECT = "test-project"; +export declare const TEST_DATABASE_ID: DatabaseId; +export declare const TEST_PERSISTENCE_KEY = "[PersistenceTestHelpers]"; +export declare const TEST_APP_ID = "test-app-id"; +/** The persistence prefix used for testing in IndexedBD and LocalStorage. */ +export declare const TEST_PERSISTENCE_PREFIX: string; +/** + * The database name used by tests that access IndexedDb. To be used in + * conjunction with `TEST_DATABASE_INFO` and + * `TEST_DATABASE_ID`. + */ +export declare const INDEXEDDB_TEST_DATABASE_NAME: string; +export declare const JSON_SERIALIZER: JsonProtoSerializer; +/** + * IndexedDb serializer that uses `TEST_DATABASE_ID` as its database + * id. + */ +export declare const TEST_SERIALIZER: LocalSerializer; +/** + * Creates and starts an IndexedDbPersistence instance for testing, destroying + * any previous contents if they existed. + */ +export declare function testIndexedDbPersistence(options?: { + dontPurgeData?: boolean; + synchronizeTabs?: boolean; + queue?: AsyncQueue; + schemaVersion?: number; +}, lruParams?: LruParams): Promise; +/** Creates and starts a MemoryPersistence instance for testing. */ +export declare function testMemoryEagerPersistence(): Promise; +export declare function testMemoryLruPersistence(params?: LruParams): Promise; +/** Clears the persistence in tests */ +export declare function clearTestPersistence(): Promise; +/** + * Populates Web Storage with instance data from a preexisting client. + */ +export declare function populateWebStorage(user: User, window: WindowLike, existingClientId: ClientId, existingMutationBatchIds: BatchId[], existingQueryTargetIds: TargetId[]): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/persistence_transaction.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/persistence_transaction.test.d.ts new file mode 100644 index 0000000..1c93d90 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/persistence_transaction.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/query_engine.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/query_engine.test.d.ts new file mode 100644 index 0000000..1c93d90 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/query_engine.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/reference_set.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/reference_set.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/reference_set.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/remote_document_cache.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/remote_document_cache.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/remote_document_cache.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/remote_document_change_buffer.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/remote_document_change_buffer.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/remote_document_change_buffer.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/simple_db.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/simple_db.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/simple_db.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/target_cache.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/target_cache.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/target_cache.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_bundle_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_bundle_cache.d.ts new file mode 100644 index 0000000..faff4b4 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_bundle_cache.d.ts @@ -0,0 +1,32 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BundleMetadata, NamedQuery } from '../../../src/core/bundle'; +import { Persistence } from '../../../src/local/persistence'; +import { NamedQuery as ProtoNamedQuery, BundleMetadata as ProtoBundleMetadata } from '../../../src/protos/firestore_bundle_proto'; +/** + * A wrapper around a BundleCache that automatically creates a + * transaction around every operation to reduce test boilerplate. + */ +export declare class TestBundleCache { + private readonly persistence; + private readonly cache; + constructor(persistence: Persistence); + getBundleMetadata(bundleId: string): Promise; + saveBundleMetadata(metadata: ProtoBundleMetadata): Promise; + getNamedQuery(name: string): Promise; + setNamedQuery(query: ProtoNamedQuery): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_document_overlay_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_document_overlay_cache.d.ts new file mode 100644 index 0000000..c0d0c66 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_document_overlay_cache.d.ts @@ -0,0 +1,39 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentOverlayCache } from '../../../src/local/document_overlay_cache'; +import { Persistence } from '../../../src/local/persistence'; +import { DocumentKeySet, MutationMap, OverlayMap } from '../../../src/model/collections'; +import { DocumentKey } from '../../../src/model/document_key'; +import { Mutation } from '../../../src/model/mutation'; +import { Overlay } from '../../../src/model/overlay'; +import { ResourcePath } from '../../../src/model/path'; +/** + * A wrapper around a DocumentOverlayCache that automatically creates a + * transaction around every operation to reduce test boilerplate. + */ +export declare class TestDocumentOverlayCache { + private persistence; + private cache; + constructor(persistence: Persistence, cache: DocumentOverlayCache); + saveOverlays(largestBatch: number, data: MutationMap): Promise; + getOverlay(key: DocumentKey): Promise; + getOverlays(keys: DocumentKey[]): Promise; + getOverlayMutation(docKey: string): Promise; + getOverlaysForCollection(path: ResourcePath, sinceBatchId: number): Promise; + getOverlaysForCollectionGroup(collectionGroup: string, sinceBatchId: number, count: number): Promise; + removeOverlaysForBatchId(documentKeys: DocumentKeySet, batchId: number): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_globals_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_globals_cache.d.ts new file mode 100644 index 0000000..7388b22 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_globals_cache.d.ts @@ -0,0 +1,29 @@ +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Persistence } from '../../../src/local/persistence'; +import { ByteString } from '../../../src/util/byte_string'; +/** + * A wrapper around a GlobalsCache that automatically creates a + * transaction around every operation to reduce test boilerplate. + */ +export declare class TestGlobalsCache { + private readonly persistence; + private readonly cache; + constructor(persistence: Persistence); + getSessionToken(): Promise; + setSessionToken(sessionToken: ByteString): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_index_manager.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_index_manager.d.ts new file mode 100644 index 0000000..9cd64e1 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_index_manager.d.ts @@ -0,0 +1,44 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Target } from '../../../src/core/target'; +import { IndexManager, IndexType } from '../../../src/local/index_manager'; +import { Persistence } from '../../../src/local/persistence'; +import { DocumentMap } from '../../../src/model/collections'; +import { DocumentKey } from '../../../src/model/document_key'; +import { FieldIndex, IndexOffset } from '../../../src/model/field_index'; +import { ResourcePath } from '../../../src/model/path'; +/** + * A wrapper around IndexManager that automatically creates a + * transaction around every operation to reduce test boilerplate. + */ +export declare class TestIndexManager { + persistence: Persistence; + indexManager: IndexManager; + constructor(persistence: Persistence, indexManager: IndexManager); + addToCollectionParentIndex(collectionPath: ResourcePath): Promise; + getCollectionParents(collectionId: string): Promise; + addFieldIndex(index: FieldIndex): Promise; + deleteFieldIndex(index: FieldIndex): Promise; + createTargetIndexes(target: Target): Promise; + deleteAllFieldIndexes(): Promise; + getFieldIndexes(collectionGroup?: string): Promise; + getIndexType(target: Target): Promise; + getDocumentsMatchingTarget(target: Target): Promise; + getNextCollectionGroupToUpdate(): Promise; + updateCollectionGroup(collectionGroup: string, offset: IndexOffset): Promise; + updateIndexEntries(documents: DocumentMap): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_mutation_queue.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_mutation_queue.d.ts new file mode 100644 index 0000000..56dae50 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_mutation_queue.d.ts @@ -0,0 +1,43 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Query } from '../../../src/core/query'; +import { BatchId } from '../../../src/core/types'; +import { MutationQueue } from '../../../src/local/mutation_queue'; +import { Persistence } from '../../../src/local/persistence'; +import { DocumentKeySet } from '../../../src/model/collections'; +import { DocumentKey } from '../../../src/model/document_key'; +import { Mutation } from '../../../src/model/mutation'; +import { MutationBatch } from '../../../src/model/mutation_batch'; +/** + * A wrapper around a MutationQueue that automatically creates a + * transaction around every operation to reduce test boilerplate. + */ +export declare class TestMutationQueue { + persistence: Persistence; + queue: MutationQueue; + constructor(persistence: Persistence, queue: MutationQueue); + checkEmpty(): Promise; + countBatches(): Promise; + addMutationBatch(mutations: Mutation[]): Promise; + lookupMutationBatch(batchId: BatchId): Promise; + getNextMutationBatchAfterBatchId(batchId: BatchId): Promise; + getAllMutationBatches(): Promise; + getAllMutationBatchesAffectingDocumentKey(documentKey: DocumentKey): Promise; + getAllMutationBatchesAffectingDocumentKeys(documentKeys: DocumentKeySet): Promise; + getAllMutationBatchesAffectingQuery(query: Query): Promise; + removeMutationBatch(batch: MutationBatch): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_remote_document_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_remote_document_cache.d.ts new file mode 100644 index 0000000..67fda41 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_remote_document_cache.d.ts @@ -0,0 +1,54 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Query } from '../../../src/core/query'; +import { SnapshotVersion } from '../../../src/core/snapshot_version'; +import { IndexManager } from '../../../src/local/index_manager'; +import { Persistence } from '../../../src/local/persistence'; +import { RemoteDocumentChangeBuffer } from '../../../src/local/remote_document_change_buffer'; +import { DocumentKeySet, MutableDocumentMap, OverlayMap } from '../../../src/model/collections'; +import { MutableDocument } from '../../../src/model/document'; +import { DocumentKey } from '../../../src/model/document_key'; +import { IndexOffset } from '../../../src/model/field_index'; +/** + * A wrapper around a RemoteDocumentCache that automatically creates a + * transaction around every operation to reduce test boilerplate. + */ +export declare class TestRemoteDocumentCache { + private readonly persistence; + private readonly cache; + constructor(persistence: Persistence); + setIndexManager(indexManager: IndexManager): void; + /** + * Reads all of the documents first so we can safely add them and keep the size calculation in + * sync. + */ + addEntries(documents: MutableDocument[]): Promise; + /** + * Adds a single document using the document's version as its read time. + * Reads the document first to track the document size internally. + */ + addEntry(document: MutableDocument): Promise; + removeEntry(documentKey: DocumentKey, version?: SnapshotVersion): Promise; + getEntry(documentKey: DocumentKey): Promise; + getEntries(documentKeys: DocumentKeySet): Promise; + getDocumentsMatchingQuery(query: Query, offset: IndexOffset, mutatedDocs: OverlayMap): Promise; + getAllFromCollectionGroup(collectionGroup: string, offset: IndexOffset, limit: number): Promise; + getSize(): Promise; + newChangeBuffer(options?: { + trackRemovals: boolean; + }): RemoteDocumentChangeBuffer; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_remote_document_change_buffer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_remote_document_change_buffer.d.ts new file mode 100644 index 0000000..9abb942 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_remote_document_change_buffer.d.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../../../src/core/snapshot_version'; +import { Persistence } from '../../../src/local/persistence'; +import { RemoteDocumentChangeBuffer } from '../../../src/local/remote_document_change_buffer'; +import { MutableDocument } from '../../../src/model/document'; +import { DocumentKey } from '../../../src/model/document_key'; +/** + * A wrapper around a RemoteDocumentChangeBuffer that automatically creates a + * transaction around operations to reduce test boilerplate. + */ +export declare class TestRemoteDocumentChangeBuffer { + persistence: Persistence; + buffer: RemoteDocumentChangeBuffer; + constructor(persistence: Persistence, buffer: RemoteDocumentChangeBuffer); + addEntry(document: MutableDocument, readTime: SnapshotVersion): void; + removeEntry(key: DocumentKey, readTime: SnapshotVersion): void; + getEntry(documentKey: DocumentKey): Promise; + apply(): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_target_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_target_cache.d.ts new file mode 100644 index 0000000..590e9ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/test_target_cache.d.ts @@ -0,0 +1,46 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../../../src/core/snapshot_version'; +import { Target } from '../../../src/core/target'; +import { ListenSequenceNumber, TargetId } from '../../../src/core/types'; +import { Persistence } from '../../../src/local/persistence'; +import { TargetCache } from '../../../src/local/target_cache'; +import { TargetData } from '../../../src/local/target_data'; +import { DocumentKey } from '../../../src/model/document_key'; +/** + * A wrapper around a TargetCache that automatically creates a + * transaction around every operation to reduce test boilerplate. + */ +export declare class TestTargetCache { + persistence: Persistence; + cache: TargetCache; + constructor(persistence: Persistence, cache: TargetCache); + addTargetData(targetData: TargetData): Promise; + updateTargetData(targetData: TargetData): Promise; + getTargetCount(): Promise; + removeTargetData(targetData: TargetData): Promise; + getTargetData(target: Target): Promise; + getLastRemoteSnapshotVersion(): Promise; + getHighestSequenceNumber(): Promise; + allocateTargetId(): Promise; + addMatchingKeys(keys: DocumentKey[], targetId: TargetId): Promise; + removeMatchingKeys(keys: DocumentKey[], targetId: TargetId): Promise; + getMatchingKeysForTargetId(targetId: TargetId): Promise; + removeMatchingKeysForTargetId(targetId: TargetId): Promise; + containsKey(key: DocumentKey): Promise; + setTargetsMetadata(highestListenSequenceNumber: ListenSequenceNumber, lastRemoteSnapshotVersion?: SnapshotVersion): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/web_storage_shared_client_state.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/web_storage_shared_client_state.test.d.ts new file mode 100644 index 0000000..342959e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/local/web_storage_shared_client_state.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * withOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/document.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/document.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/document.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/document_set.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/document_set.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/document_set.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/field_index.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/field_index.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/field_index.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/mutation.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/mutation.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/mutation.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/object_value.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/object_value.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/object_value.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/object_value_builder.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/object_value_builder.test.d.ts new file mode 100644 index 0000000..731d2d9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/object_value_builder.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/path.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/path.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/path.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/target.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/target.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/target.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/target_index_matcher.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/target_index_matcher.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/target_index_matcher.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/values.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/values.test.d.ts new file mode 100644 index 0000000..731d2d9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/model/values.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/bloom_filter.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/bloom_filter.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/bloom_filter.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/bloom_filter_golden_test_data/index.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/bloom_filter_golden_test_data/index.d.ts new file mode 100644 index 0000000..fda7b1b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/bloom_filter_golden_test_data/index.d.ts @@ -0,0 +1,40 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { default as count1Rate1TestData } from './Validation_BloomFilterTest_MD5_1_1_bloom_filter_proto.json'; +export { default as count1Rate1TestResult } from './Validation_BloomFilterTest_MD5_1_1_membership_test_result.json'; +export { default as count1Rate01TestData } from './Validation_BloomFilterTest_MD5_1_01_bloom_filter_proto.json'; +export { default as count1Rate01TestResult } from './Validation_BloomFilterTest_MD5_1_01_membership_test_result.json'; +export { default as count1Rate0001TestData } from './Validation_BloomFilterTest_MD5_1_0001_bloom_filter_proto.json'; +export { default as count1Rate0001TestResult } from './Validation_BloomFilterTest_MD5_1_0001_membership_test_result.json'; +export { default as count500Rate1TestData } from './Validation_BloomFilterTest_MD5_500_1_bloom_filter_proto.json'; +export { default as count500Rate1TestResult } from './Validation_BloomFilterTest_MD5_500_1_membership_test_result.json'; +export { default as count500Rate01TestData } from './Validation_BloomFilterTest_MD5_500_01_bloom_filter_proto.json'; +export { default as count500Rate01TestResult } from './Validation_BloomFilterTest_MD5_500_01_membership_test_result.json'; +export { default as count500Rate0001TestData } from './Validation_BloomFilterTest_MD5_500_0001_bloom_filter_proto.json'; +export { default as count500Rate0001TestResult } from './Validation_BloomFilterTest_MD5_500_0001_membership_test_result.json'; +export { default as count5000Rate1TestData } from './Validation_BloomFilterTest_MD5_5000_1_bloom_filter_proto.json'; +export { default as count5000Rate1TestResult } from './Validation_BloomFilterTest_MD5_5000_1_membership_test_result.json'; +export { default as count5000Rate01TestData } from './Validation_BloomFilterTest_MD5_5000_01_bloom_filter_proto.json'; +export { default as count5000Rate01TestResult } from './Validation_BloomFilterTest_MD5_5000_01_membership_test_result.json'; +export { default as count5000Rate0001TestData } from './Validation_BloomFilterTest_MD5_5000_0001_bloom_filter_proto.json'; +export { default as count5000Rate0001TestResult } from './Validation_BloomFilterTest_MD5_5000_0001_membership_test_result.json'; +export { default as count50000Rate1TestData } from './Validation_BloomFilterTest_MD5_50000_1_bloom_filter_proto.json'; +export { default as count50000Rate1TestResult } from './Validation_BloomFilterTest_MD5_50000_1_membership_test_result.json'; +export { default as count50000Rate01TestData } from './Validation_BloomFilterTest_MD5_50000_01_bloom_filter_proto.json'; +export { default as count50000Rate01TestResult } from './Validation_BloomFilterTest_MD5_50000_01_membership_test_result.json'; +export { default as count50000Rate0001TestData } from './Validation_BloomFilterTest_MD5_50000_0001_bloom_filter_proto.json'; +export { default as count50000Rate0001TestResult } from './Validation_BloomFilterTest_MD5_50000_0001_membership_test_result.json'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/datastore.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/datastore.test.d.ts new file mode 100644 index 0000000..daa6d5d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/datastore.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/fetch_connection.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/fetch_connection.test.d.ts new file mode 100644 index 0000000..1a6762b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/fetch_connection.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/remote_event.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/remote_event.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/remote_event.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/rest_connection.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/rest_connection.test.d.ts new file mode 100644 index 0000000..a6fa156 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/rest_connection.test.d.ts @@ -0,0 +1,28 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Token } from '../../../src/api/credentials'; +import { Stream } from '../../../src/remote/connection'; +import { RestConnection } from '../../../src/remote/rest_connection'; +import { StringMap } from '../../../src/util/types'; +export declare class TestRestConnection extends RestConnection { + lastUrl: string; + lastHeaders: StringMap; + lastRequestBody: unknown; + nextResponse: Promise; + openStream(rpcName: string, authToken: Token | null, appCheckToken: Token | null): Stream; + protected performRPCRequest(rpcName: string, url: string, headers: StringMap, body: Req): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/serializer.browser.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/serializer.browser.test.d.ts new file mode 100644 index 0000000..731d2d9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/serializer.browser.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/serializer.helper.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/serializer.helper.d.ts new file mode 100644 index 0000000..238e66b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/serializer.helper.d.ts @@ -0,0 +1,25 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as api from '../../../src/protos/firestore_proto_api'; +/** + * Runs the serializer test with an optional ProtobufJS verification step + * (only provided in Node). + * + * These tests are initialized in 'serializer.browser.test.ts' and + * 'serializer.node.test.ts'. + */ +export declare function serializerTest(protobufJsVerifier?: (jsonValue: api.Value) => void): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/serializer.node.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/serializer.node.test.d.ts new file mode 100644 index 0000000..94e3acc --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/remote/serializer.node.test.d.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as api from '../../../src/protos/firestore_proto_api'; +/** + * Verifies full round-trip of JSON protos through ProtobufJs. + */ +export declare function verifyProtobufJsRoundTrip(jsonValue: api.Value): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/bundle_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/bundle_spec.test.d.ts new file mode 100644 index 0000000..18aa444 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/bundle_spec.test.d.ts @@ -0,0 +1,36 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Query } from '../../../src/core/query'; +import { DocumentKey } from '../../../src/model/document_key'; +import { JsonObject } from '../../../src/model/object_value'; +import { LimitType } from '../../../src/protos/firestore_bundle_proto'; +import { TestSnapshotVersion } from '../../util/helpers'; +interface TestBundleDocument { + key: DocumentKey; + readTime: TestSnapshotVersion; + createTime?: TestSnapshotVersion; + updateTime?: TestSnapshotVersion; + content?: JsonObject; +} +interface TestBundledQuery { + name: string; + readTime: TestSnapshotVersion; + query: Query; + limitType?: LimitType; +} +export declare function bundleWithDocumentAndQuery(testDoc: TestBundleDocument, testQuery?: TestBundledQuery): string; +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/collection_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/collection_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/collection_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/describe_spec.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/describe_spec.d.ts new file mode 100644 index 0000000..8804b64 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/describe_spec.d.ts @@ -0,0 +1,44 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SpecBuilder } from './spec_builder'; +export declare const MULTI_CLIENT_TAG = "multi-client"; +/** + * If you call this function before your describeSpec, then the spec test will + * be written using the given function instead of running as a normal test. + */ +export declare function setSpecJSONHandler(writer: (json: string) => void): void; +/** + * Like it(), but for spec tests. + * @param name - A name to give the test. + * @param tags - Tags to apply to the test (e.g. 'exclusive' to only run + * individual tests) + * @param builder - A function that returns a spec. + * If writeToJSONFile has been called, the spec will be stored in + * `specsInThisTest`. Otherwise, it will be run, just as it() would run it. + */ +export declare function specTest(name: string, tags: string[], builder: () => SpecBuilder): void; +export declare function specTest(name: string, tags: string[], comment: string, builder: () => SpecBuilder): void; +/** + * Like describe, but for spec tests. + * @param name - A name to give the test. + * @param tags - Tags to apply to all tests in the spec (e.g. 'exclusive' to + * only run individual tests) + * @param builder - A function that calls specTest for each test case. + * If writeToJSONFile has been called, the specs will be stored in + * that file. Otherwise, they will be run, just as describe would run. + */ +export declare function describeSpec(name: string, tags: string[], builder: () => void): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/existence_filter_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/existence_filter_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/existence_filter_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/garbage_collection_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/garbage_collection_spec.test.d.ts new file mode 100644 index 0000000..615869e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/garbage_collection_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/index_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/index_spec.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/index_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/limbo_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/limbo_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/limbo_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/limit_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/limit_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/limit_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/listen_source_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/listen_source_spec.test.d.ts new file mode 100644 index 0000000..88c3c0e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/listen_source_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/listen_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/listen_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/listen_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/offline_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/offline_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/offline_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/orderby_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/orderby_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/orderby_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/perf_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/perf_spec.test.d.ts new file mode 100644 index 0000000..c53048a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/perf_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/persistence_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/persistence_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/persistence_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/query_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/query_spec.test.d.ts new file mode 100644 index 0000000..1c93d90 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/query_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/recovery_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/recovery_spec.test.d.ts new file mode 100644 index 0000000..731d2d9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/recovery_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/remote_store_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/remote_store_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/remote_store_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/resume_token_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/resume_token_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/resume_token_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_builder.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_builder.d.ts new file mode 100644 index 0000000..00705ca --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_builder.d.ts @@ -0,0 +1,287 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { IndexConfiguration } from '../../../src/api/index_configuration'; +import { Query } from '../../../src/core/query'; +import { Target } from '../../../src/core/target'; +import { TargetIdGenerator } from '../../../src/core/target_id_generator'; +import { TargetId } from '../../../src/core/types'; +import { TargetPurpose } from '../../../src/local/target_data'; +import { Document } from '../../../src/model/document'; +import { DocumentKey } from '../../../src/model/document_key'; +import { FieldIndex } from '../../../src/model/field_index'; +import { JsonObject } from '../../../src/model/object_value'; +import { BloomFilter as ProtoBloomFilter } from '../../../src/protos/firestore_proto_api'; +import { TimerId } from '../../../src/util/async_queue'; +import { Code } from '../../../src/util/error'; +import { ObjectMap } from '../../../src/util/obj_map'; +import { TestSnapshotVersion } from '../../util/helpers'; +import { RpcError } from './spec_rpc_error'; +import { PersistenceAction, SpecConfig, SpecQuery, SpecStep } from './spec_test_runner'; +export interface LimboMap { + [key: string]: TargetId; +} +export interface ActiveTargetSpec { + queries: SpecQuery[]; + targetPurpose?: TargetPurpose; + resumeToken?: string; + readTime?: TestSnapshotVersion; + expectedCount?: number; +} +export interface ActiveTargetMap { + [targetId: string]: ActiveTargetSpec; +} +export interface ResumeSpec { + resumeToken?: string; + readTime?: TestSnapshotVersion; + expectedCount?: number; +} +/** + * Tracks the expected memory state of a client (e.g. the expected active watch + * targets based on userListens(), userUnlistens(), and watchRemoves() + * as well as the expectActiveTargets() and expectLimboDocs() expectations). + * + * Automatically keeping track of the active targets makes writing tests + * much simpler and the tests much easier to follow. + * + * Whenever the map changes, the expected state is automatically encoded in + * the tests. + */ +export declare class ClientMemoryState { + activeTargets: ActiveTargetMap; + queryMapping: ObjectMap; + limboMapping: LimboMap; + limboIdGenerator: TargetIdGenerator; + injectFailures: boolean; + constructor(); + /** Reset all internal memory state (as done during a client restart). */ + reset(): void; + /** + * Reset the internal limbo mapping (as done during a primary lease failover). + */ + resetLimboMapping(): void; +} +/** + * Provides a high-level language to construct spec tests that can be exported + * to the spec JSON format or be run as a spec test directly. + * + * Exported JSON tests can be used in other clients without the need to + * duplicate tests in every client. + */ +export declare class SpecBuilder { + protected config: SpecConfig; + protected currentStep: SpecStep | null; + private steps; + private queryIdGenerator; + private readonly currentClientState; + protected get clientState(): ClientMemoryState; + private get limboIdGenerator(); + private get queryMapping(); + private get limboMapping(); + private get activeTargets(); + private get injectFailures(); + private set injectFailures(value); + /** + * Exports the spec steps as a JSON object that be used in the spec runner. + */ + toJSON(): { + config: SpecConfig; + steps: SpecStep[]; + }; + /** + * Run the spec as a test. If persistence is available it will run it with and + * without persistence enabled. + */ + runAsTest(name: string, tags: string[], usePersistence: boolean): Promise; + ensureManualLruGC(): this; + withMaxConcurrentLimboResolutions(value?: number): this; + private addUserListenStep; + userListens(query: Query, resume?: ResumeSpec): this; + /** Listen to query using the same options as executing a getDoc or getDocs */ + userListensForGet(query: Query, resume?: ResumeSpec): this; + userListensToCache(query: Query, resume?: ResumeSpec): this; + /** + * Registers a previously active target with the test expectations after a + * stream disconnect. + */ + restoreListen(query: Query, resumeToken: string, expectedCount?: number): this; + userUnlistens(query: Query, shouldRemoveWatchTarget?: boolean): this; + userUnlistensToCache(query: Query): this; + userSets(key: string, value: JsonObject): this; + userPatches(key: string, value: JsonObject): this; + userDeletes(key: string): this; + userAddsSnapshotsInSyncListener(): this; + userRemovesSnapshotsInSyncListener(): this; + loadBundle(bundleContent: string): this; + setIndexConfiguration(jsonOrConfiguration: string | IndexConfiguration): this; + becomeHidden(): this; + becomeVisible(): this; + runTimer(timerId: TimerId): this; + changeUser(uid: string | null): this; + disableNetwork(): this; + enableNetwork(): this; + clearPersistence(): this; + restart(): this; + shutdown(): this; + /** + * Fails the specified database transaction until `recoverDatabase()` is + * called. + */ + failDatabaseTransactions(...actions: PersistenceAction[]): this; + /** Stops failing database operations. */ + recoverDatabase(): this; + expectIsShutdown(): this; + /** Expects indexes to exist (in any order) */ + expectIndexes(indexes: FieldIndex[]): this; + /** Overrides the currently expected set of active targets. */ + expectActiveTargets(...targets: Array<{ + query: Query; + targetPurpose?: TargetPurpose; + resumeToken?: string; + readTime?: TestSnapshotVersion; + expectedCount?: number; + }>): this; + /** + * Expects a document to be in limbo. A targetId is assigned if it's not in + * limbo yet. + */ + expectLimboDocs(...keys: DocumentKey[]): this; + /** + * Expects a document to be in limbo, enqueued for limbo resolution, and + * therefore *without* an active targetId. + */ + expectEnqueuedLimboDocs(...keys: DocumentKey[]): this; + /** + * Special helper for limbo documents that acks with either a document or + * with no document for NoDocument. This is translated into normal watch + * messages. + */ + ackLimbo(version: TestSnapshotVersion, doc: Document): this; + /** + * Special helper for limbo documents that acks an unlisten for a limbo doc + * with either a document or with no document for NoDocument. This is + * translated into normal watch messages. + */ + watchRemovesLimboTarget(doc: Document): this; + /** + * Acks a write with a version and optional additional options. + * + * expectUserCallback defaults to true if omitted. + */ + writeAcks(doc: string, version: TestSnapshotVersion, options?: { + expectUserCallback?: boolean; + keepInQueue?: boolean; + }): this; + /** + * Fails a write with an error and optional additional options. + * + * expectUserCallback defaults to true if omitted. + */ + failWrite(doc: string, error: RpcError, options?: { + expectUserCallback?: boolean; + keepInQueue?: boolean; + }): this; + watchAcks(query: Query): this; + watchCurrents(query: Query, resumeToken: string): this; + watchRemoves(query: Query, cause?: RpcError): this; + watchSends(targets: { + affects?: Query[]; + removed?: Query[]; + }, ...docs: Document[]): this; + watchRemovesDoc(key: DocumentKey, ...targets: Query[]): this; + watchDeletesDoc(key: DocumentKey, version: TestSnapshotVersion, ...targets: Query[]): this; + watchFilters(queries: Query[], docs?: DocumentKey[], bloomFilter?: ProtoBloomFilter): this; + watchResets(...queries: Query[]): this; + watchSnapshots(version: TestSnapshotVersion, targets?: Query[], resumeToken?: string): this; + watchAcksFull(query: Query, version: TestSnapshotVersion, ...docs: Document[]): this; + watchStreamCloses(error: Code, opts?: { + runBackoffTimer: boolean; + }): this; + waitForPendingWrites(): this; + expectUserCallbacks(docs: { + acknowledged?: string[]; + rejected?: string[]; + }): this; + expectEvents(query: Query, events: { + fromCache?: boolean; + hasPendingWrites?: boolean; + added?: Document[]; + modified?: Document[]; + removed?: Document[]; + metadata?: Document[]; + errorCode?: Code; + }): this; + private registerQuery; + /** Registers a query that is active in another tab. */ + expectListen(query: Query, resume?: ResumeSpec): this; + /** Registers a query that is listening to cache and active in another tab. */ + expectListenToCache(query: Query, resume?: ResumeSpec): this; + removeQuery(query: Query, shouldRemoveWatchTarget?: boolean): this; + /** Removes a query that is no longer active in any tab. */ + expectUnlisten(query: Query): this; + /** Removes a query that is listening to cache and no longer active in any tab. */ + expectUnlistenToCache(query: Query): this; + /** + * Verifies the total number of requests sent to the write backend since test + * initialization. + */ + expectWriteStreamRequestCount(num: number): this; + /** + * Verifies the total number of requests sent to the watch backend since test + * initialization. + */ + expectWatchStreamRequestCount(num: number): this; + expectNumOutstandingWrites(num: number): this; + expectNumActiveClients(num: number): this; + expectPrimaryState(isPrimary: boolean): this; + expectSnapshotsInSyncEvent(count?: number): this; + expectWaitForPendingWritesEvent(count?: number): this; + triggerLruGC(cacheThreshold: number): this; + removeExpectedTargetMapping(query: Query): this; + private static queryToSpec; + private static docToSpec; + private static keyToSpec; + protected nextStep(): void; + /** + * Add the specified `Query` under give active targe id. If it is already + * added, this is a no-op. + */ + private addQueryToActiveTargets; + private removeQueryFromActiveTargets; + private assertStep; + private getTargetId; +} +/** + * SpecBuilder that supports serialized interactions between different clients. + * + * Use `client(clientIndex)` to switch between clients. + */ +export declare class MultiClientSpecBuilder extends SpecBuilder { + private activeClientIndex; + private clientStates; + protected get clientState(): ClientMemoryState; + client(clientIndex: number): MultiClientSpecBuilder; + /** + * Take the primary lease, even if another client has already obtained the + * lease. + */ + stealPrimaryLease(): this; + protected nextStep(): void; +} +/** Starts a new single-client SpecTest. */ +export declare function spec(): SpecBuilder; +/** Starts a new multi-client SpecTest. */ +export declare function client(num: number): MultiClientSpecBuilder; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_rpc_error.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_rpc_error.d.ts new file mode 100644 index 0000000..a104309 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_rpc_error.d.ts @@ -0,0 +1,24 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Code } from '../../../src/util/error'; +/** + * An error encountered making RPCs. + */ +export declare class RpcError extends Error { + code: number; + constructor(code: Code | number, message: string); +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_test_components.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_test_components.d.ts new file mode 100644 index 0000000..0152128 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_test_components.d.ts @@ -0,0 +1,156 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Token } from '../../../src/api/credentials'; +import { ComponentConfiguration, MemoryOfflineComponentProvider, OnlineComponentProvider, MultiTabOfflineComponentProvider } from '../../../src/core/component_provider'; +import { Observer } from '../../../src/core/event_manager'; +import { Query } from '../../../src/core/query'; +import { ViewSnapshot } from '../../../src/core/view_snapshot'; +import { IndexedDbPersistence } from '../../../src/local/indexeddb_persistence'; +import { LocalStore } from '../../../src/local/local_store'; +import { MemoryPersistence } from '../../../src/local/memory_persistence'; +import { Scheduler, Persistence } from '../../../src/local/persistence'; +import { PersistencePromise } from '../../../src/local/persistence_promise'; +import { PersistenceTransaction, PersistenceTransactionMode } from '../../../src/local/persistence_transaction'; +import { SharedClientState } from '../../../src/local/shared_client_state'; +import { Mutation } from '../../../src/model/mutation'; +import * as api from '../../../src/protos/firestore_proto_api'; +import { ApiClientObjectMap } from '../../../src/protos/firestore_proto_api'; +import { Connection, Stream } from '../../../src/remote/connection'; +import { Datastore } from '../../../src/remote/datastore'; +import { StreamBridge } from '../../../src/remote/stream_bridge'; +import { AsyncQueue } from '../../../src/util/async_queue'; +import { FirestoreError } from '../../../src/util/error'; +import { Deferred } from '../../../src/util/promise'; +import { WindowLike } from '../../../src/util/types'; +import { FakeDocument } from '../../util/test_platform'; +import { PersistenceAction } from './spec_test_runner'; +/** + * A test-only MemoryPersistence implementation that is able to inject + * transaction failures. + */ +export declare class MockMemoryPersistence extends MemoryPersistence { + injectFailures: PersistenceAction[]; + runTransaction(action: string, mode: PersistenceTransactionMode, transactionOperation: (transaction: PersistenceTransaction) => PersistencePromise): Promise; +} +/** + * A test-only IndexedDbPersistence implementation that is able to inject + * transaction failures. + */ +export declare class MockIndexedDbPersistence extends IndexedDbPersistence { + injectFailures: PersistenceAction[]; + runTransaction(action: string, mode: PersistenceTransactionMode, transactionOperation: (transaction: PersistenceTransaction) => PersistencePromise): Promise; +} +export declare class MockOnlineComponentProvider extends OnlineComponentProvider { + private readonly connection; + constructor(connection: MockConnection); + createDatastore(cfg: ComponentConfiguration): Datastore; +} +export declare class MockMultiTabOfflineComponentProvider extends MultiTabOfflineComponentProvider { + private readonly window; + private readonly document; + persistence: MockIndexedDbPersistence; + constructor(window: WindowLike, document: FakeDocument, onlineComponentProvider: OnlineComponentProvider); + createGarbageCollectionScheduler(cfg: ComponentConfiguration, localStore: LocalStore): Scheduler | null; + createIndexBackfillerScheduler(cfg: ComponentConfiguration, localStore: LocalStore): Scheduler | null; + createSharedClientState(cfg: ComponentConfiguration): SharedClientState; + createPersistence(cfg: ComponentConfiguration): MockIndexedDbPersistence; +} +export declare class MockMemoryOfflineComponentProvider extends MemoryOfflineComponentProvider { + private readonly eagerGCEnabled; + persistence: MockMemoryPersistence; + connection: MockConnection; + constructor(eagerGCEnabled: boolean); + createGarbageCollectionScheduler(cfg: ComponentConfiguration): Scheduler | null; + createPersistence(cfg: ComponentConfiguration): Persistence; +} +export declare class MockConnection implements Connection { + private queue; + watchStream: StreamBridge | null; + writeStream: StreamBridge | null; + /** + * Used to make sure a write was actually sent out on the network before the + * test runner continues. + */ + writeSendBarriers: Array>; + /** + * The set of mutations sent out before there was a corresponding + * writeSendBarrier. + */ + earlyWrites: api.WriteRequest[]; + /** The total number of requests sent to the watch stream. */ + watchStreamRequestCount: number; + /** The total number of requests sent to the write stream. */ + writeStreamRequestCount: number; + nextWriteStreamToken: number; + constructor(queue: AsyncQueue); + terminate(): void; + shouldResourcePathBeIncludedInRequest: boolean; + /** + * Tracks the currently active watch targets as detected by the mock watch // + * stream, as a mapping from target ID to query Target. // + */ + activeTargets: { + [targetId: number]: { + target: api.Target; + labels?: ApiClientObjectMap; + }; + }; + /** A Deferred that is resolved once watch opens. */ + watchOpen: Deferred; + /** Whether the Watch stream is open. */ + isWatchOpen: boolean; + invokeRPC(rpcName: string, request: Req): never; + invokeStreamingRPC(rpcName: string, request: Req): never; + waitForWriteRequest(): Promise; + waitForWatchOpen(): Promise; + ackWrite(commitTime?: api.Timestamp, mutationResults?: api.WriteResult[]): void; + failWrite(err: FirestoreError): void; + private resetAndCloseWriteStream; + failWatchStream(err?: FirestoreError): void; + private resetAndCloseWatchStream; + openStream(rpcName: string, token: Token | null): Stream; +} +/** + * An Observer that forwards events to the provided callback. + */ +export declare class EventAggregator implements Observer { + private query; + private pushEvent; + constructor(query: Query, pushEvent: (e: QueryEvent) => void); + next(view: ViewSnapshot): void; + error(error: Error): void; +} +/** + * FIFO queue that tracks all outstanding mutations for a single test run. + * As these mutations are shared among the set of active clients, any client can + * add or retrieve mutations. + */ +export declare class SharedWriteTracker { + private writes; + push(write: Mutation[]): void; + peek(): Mutation[]; + shift(): Mutation[]; +} +/** + * Interface used for object that contain exactly one of either a view snapshot + * or an error for the given query. + */ +export interface QueryEvent { + query: Query; + view?: ViewSnapshot; + error?: FirestoreError; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_test_runner.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_test_runner.d.ts new file mode 100644 index 0000000..50d1714 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/spec_test_runner.d.ts @@ -0,0 +1,323 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { IndexConfiguration } from '../../../src/api/index_configuration'; +import { ListenOptions } from '../../../src/core/event_manager'; +import { Query } from '../../../src/core/query'; +import { TargetId } from '../../../src/core/types'; +import { FieldIndex } from '../../../src/model/field_index'; +import { JsonObject } from '../../../src/model/object_value'; +import * as api from '../../../src/protos/firestore_proto_api'; +import { TestSnapshotVersion } from '../../util/helpers'; +import { ActiveTargetMap } from './spec_builder'; +interface DocumentOptions { + hasLocalMutations?: boolean; + hasCommittedMutations?: boolean; +} +export declare function parseQuery(querySpec: string | SpecQuery): Query; +/** + * Runs a spec test case. + * + * The spec consists of an array of individual steps to run in sequence. + */ +export declare function runSpec(name: string, tags: string[], usePersistence: boolean, config: SpecConfig, steps: SpecStep[]): Promise; +/** Specifies initial configuration information for the test. */ +export interface SpecConfig { + /** A boolean to enable / disable eager GC for memory persistence. */ + useEagerGCForMemory: boolean; + /** The number of active clients for this test run. */ + numClients: number; + /** + * The maximum number of concurrently-active listens for limbo resolutions. + * This value must be strictly greater than zero, or undefined to use the + * default value. + */ + maxConcurrentLimboResolutions?: number; +} +/** + * The cumulative list of actions run against Persistence. This is used by the + * Spec tests to fail specific types of actions. + */ +export type PersistenceAction = 'Get next mutation batch' | 'read document' | 'Allocate target' | 'Release target' | 'Execute query' | 'Handle user change' | 'Locally write mutations' | 'Acknowledge batch' | 'Reject batch' | 'Get highest unacknowledged batch id' | 'Get last stream token' | 'Set last stream token' | 'Get last remote snapshot version' | 'Set last remote snapshot version' | 'Apply remote event' | 'notifyLocalViewChanges' | 'Remote document keys' | 'Collect garbage' | 'maybeGarbageCollectMultiClientState' | 'Lookup mutation documents' | 'Get target data' | 'Get new document changes' | 'Synchronize last document change read time' | 'updateClientMetadataAndTryBecomePrimary' | 'getHighestListenSequenceNumber'; +/** + * Union type for each step. The step consists of exactly one `field` + * set and optionally expected events in the `expect` field. + */ +export interface SpecStep { + /** The index of the local client for multi-client spec tests. */ + clientIndex?: number; + /** Listen to a new query (must be unique) */ + userListen?: SpecUserListen; + /** Unlisten from a query (must be listened to) */ + userUnlisten?: SpecUserUnlisten; + /** Perform a user initiated set */ + userSet?: SpecUserSet; + /** Perform a user initiated patch */ + userPatch?: SpecUserPatch; + /** Perform a user initiated delete */ + userDelete?: SpecUserDelete; + /** Listens to a SnapshotsInSync event. */ + addSnapshotsInSyncListener?: true; + /** Unlistens from a SnapshotsInSync event. */ + removeSnapshotsInSyncListener?: true; + /** Loads a bundle from a string. */ + loadBundle?: string; + /** Ack for a query in the watch stream */ + watchAck?: SpecWatchAck; + /** Marks the query results as current */ + watchCurrent?: SpecWatchCurrent; + /** Reset the results of a query */ + watchReset?: SpecWatchReset; + /** Ack for remove or rejection of a query in the watch stream */ + watchRemove?: SpecWatchRemove; + /** Document update in the watch stream */ + watchEntity?: SpecWatchEntity; + /** Existence filter in the watch stream */ + watchFilter?: SpecWatchFilter; + /** Snapshot ("NO_CHANGE") event in the watch stream. */ + watchSnapshot?: SpecWatchSnapshot; + /** A step that the watch stream restarts. */ + watchStreamClose?: SpecWatchStreamClose; + /** Ack the last write */ + writeAck?: SpecWriteAck; + /** Fail a write */ + failWrite?: SpecWriteFailure; + /** Add a new `waitForPendingWrites` listener. */ + waitForPendingWrites?: true; + /** Fails the listed database actions. */ + failDatabase?: false | PersistenceAction[]; + /** + * Set Index Configuration + */ + setIndexConfiguration?: string | IndexConfiguration; + /** + * Run a queued timer task (without waiting for the delay to expire). See + * TimerId enum definition for possible values). + */ + runTimer?: string; + /** + * Process all events currently enqueued in the AsyncQueue. + */ + drainQueue?: true; + /** Enable or disable RemoteStore's network connection. */ + enableNetwork?: boolean; + /** Clears the persistent storage in IndexedDB. */ + clearPersistence?: true; + /** Changes the metadata state of a client instance. */ + applyClientState?: SpecClientState; + /** Change to a new active user (specified by uid or null for anonymous). */ + changeUser?: string | null; + /** Trigger a GC event with given cache threshold in bytes. */ + triggerLruGC?: number; + /** + * Restarts the SyncEngine from scratch, except re-uses persistence and auth + * components. This allows you to queue writes, get documents into cache, + * etc. and then simulate an app restart. + */ + restart?: true; + /** Shut down the client and close it network connection. */ + shutdown?: true; + /** + * Optional list of expected events. + * If not provided, the test will fail if the step causes events to be raised. + */ + expectedSnapshotEvents?: SnapshotEvent[]; + /** + * Optional dictionary of expected states. + */ + expectedState?: StateExpectation; + /** + * Optional expected number of onSnapshotsInSync callbacks to be called. + * If not provided, the test will fail if the step causes events to be raised. + */ + expectedSnapshotsInSyncEvents?: number; + /** + * Optional expected number of waitForPendingWrite callbacks to be called. + * If not provided, the test will fail if the step causes events to be raised. + */ + expectedWaitForPendingWritesEvents?: number; +} +export interface SpecUserListen { + targetId: TargetId; + query: string | SpecQuery; + options?: ListenOptions; +} +/** [, ] */ +export type SpecUserUnlisten = [TargetId, string | SpecQuery]; +/** [, ] */ +export type SpecUserSet = [string, JsonObject]; +/** [, ] */ +export type SpecUserPatch = [string, JsonObject]; +/** key */ +export type SpecUserDelete = string; +/** [, ...] */ +export type SpecWatchAck = TargetId[]; +/** [[, ...], ] */ +export type SpecWatchCurrent = [TargetId[], string]; +/** [, ...] */ +export type SpecWatchReset = TargetId[]; +export interface SpecError { + code: number; + message: string; +} +export interface SpecWatchRemove { + targetIds: TargetId[]; + cause?: SpecError; +} +export interface SpecWatchSnapshot { + version: TestSnapshotVersion; + targetIds: TargetId[]; + resumeToken?: string; +} +export interface SpecWatchStreamClose { + error: SpecError; + runBackoffTimer: boolean; +} +export interface SpecWriteAck { + /** The version the backend uses to ack the write. */ + version: TestSnapshotVersion; + /** + * Whether we should keep the write in our internal queue. This should only + * be set to 'true' if the client ignores the write (e.g. a secondary client + * which ignores write acknowledgments). + * + * Defaults to false. + */ + keepInQueue?: boolean; +} +export interface SpecWriteFailure { + /** The error the backend uses to fail the write. */ + error: SpecError; + /** + * Whether we should keep the write in our internal queue. This should be set + * to 'true' for transient errors or if the client ignores the failure + * (e.g. a secondary client which ignores write rejections). + * + * Defaults to false. + */ + keepInQueue?: boolean; +} +export interface SpecWatchEntity { + key?: string; + /** [, , ] */ + doc?: SpecDocument; + /** [, , ][] */ + docs?: SpecDocument[]; + /** [, ...] */ + targets?: TargetId[]; + /** [, ...] */ + removedTargets?: TargetId[]; +} +export interface SpecClientState { + /** The visibility state of the browser tab running the client. */ + visibility?: DocumentVisibilityState; + /** Whether this tab should try to forcefully become primary. */ + primary?: true; +} +/** + * The filter is based of a list of keys to match in the existence filter + */ +export interface SpecWatchFilter { + targetIds: TargetId[]; + keys: string[]; + bloomFilter?: api.BloomFilter; +} +export type SpecLimitType = 'LimitToFirst' | 'LimitToLast'; +/** + * [field, op, value] + * Op must be the `name` of an `Operator`. + */ +export type SpecQueryFilter = [string, string, unknown]; +/** + * [field, direction] + * Direction can be 'asc' or 'desc'. + */ +export type SpecQueryOrderBy = [string, string]; +/** + * A representation of a query. + */ +export interface SpecQuery { + path: string; + collectionGroup?: string; + limit?: number; + limitType?: SpecLimitType; + filters?: SpecQueryFilter[]; + orderBys?: SpecQueryOrderBy[]; +} +/** + * [, , , (optional), ...] + * Represents a document. is null for deleted documents. + * Doc options are: + * 'local': document has local modifications + */ +export interface SpecDocument { + key: string; + version: TestSnapshotVersion; + createTime: TestSnapshotVersion; + value: JsonObject | null; + options?: DocumentOptions; +} +export interface SnapshotEvent { + query: SpecQuery; + errorCode?: number; + fromCache?: boolean; + hasPendingWrites?: boolean; + added?: SpecDocument[]; + removed?: SpecDocument[]; + modified?: SpecDocument[]; + metadata?: SpecDocument[]; +} +export interface StateExpectation { + /** Number of outstanding writes in the datastore queue. */ + numOutstandingWrites?: number; + /** Number of clients currently marked active. Used in multi-client tests. */ + numActiveClients?: number; + /** Number of requests sent to the write stream. */ + writeStreamRequestCount?: number; + /** Number of requests sent to the watch stream. */ + watchStreamRequestCount?: number; + /** + * Current documents in limbo that have an active target. + * Verified in each step until overwritten. + */ + activeLimboDocs?: string[]; + /** + * Current documents in limbo that are enqueued and therefore do not have an + * active target. + * Verified in each step until overwritten. + */ + enqueuedLimboDocs?: string[]; + /** + * Whether the instance holds the primary lease. Used in multi-client tests. + */ + isPrimary?: boolean; + /** Whether the client is shutdown. */ + isShutdown?: boolean; + /** + * Current expected active targets. Verified in each step until overwritten. + */ + activeTargets?: ActiveTargetMap; + /** + * Expected set of callbacks for previously written docs. + */ + userCallbacks?: { + acknowledgedDocs: string[]; + rejectedDocs: string[]; + }; + /** Indexes */ + indexes?: FieldIndex[]; +} +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/write_spec.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/write_spec.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/specs/write_spec.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/array.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/array.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/array.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/assert.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/assert.test.d.ts new file mode 100644 index 0000000..1a6762b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/assert.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/async_queue.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/async_queue.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/async_queue.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/base64.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/base64.test.d.ts new file mode 100644 index 0000000..731d2d9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/base64.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/bundle.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/bundle.test.d.ts new file mode 100644 index 0000000..56e142c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/bundle.test.d.ts @@ -0,0 +1,8 @@ +/** + * Create a `ReadableStream` from a string. + * + * @param content - Bundle in string. + * @param bytesPerRead - How many bytes to read from the underlying buffer from + * each read through the stream. + */ +export declare function byteStreamReaderFromString(content: string, bytesPerRead: number): ReadableStreamDefaultReader; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/bundle_data.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/bundle_data.d.ts new file mode 100644 index 0000000..de7a107 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/bundle_data.d.ts @@ -0,0 +1,50 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseId } from '../../../src/core/database_info'; +import { Query } from '../../../src/core/query'; +import { DocumentKey } from '../../../src/model/document_key'; +import { BundleElement } from '../../../src/protos/firestore_bundle_proto'; +import * as api from '../../../src/protos/firestore_proto_api'; +import { Value } from '../../../src/protos/firestore_proto_api'; +export declare const encoder: TextEncoder; +export declare class TestBundleBuilder { + private databaseId; + readonly elements: BundleElement[]; + private serializer; + constructor(databaseId: DatabaseId); + addDocumentMetadata(docKey: DocumentKey, readTime: api.Timestamp, exists: boolean): TestBundleBuilder; + addDocument(docKey: DocumentKey, createTime: api.Timestamp, updateTime: api.Timestamp, fields: api.ApiClientObjectMap): TestBundleBuilder; + addNamedQuery(name: string, readTime: api.Timestamp, query: Query): TestBundleBuilder; + getMetadataElement(id: string, createTime: api.Timestamp, version?: number): BundleElement; + build(id: string, createTime: api.Timestamp, version?: number): string; +} +export declare const meta: BundleElement; +export declare const metaString: string; +export declare const doc1Meta: BundleElement; +export declare const doc1MetaString: string; +export declare const doc1: BundleElement; +export declare const doc1String: string; +export declare const doc2Meta: BundleElement; +export declare const doc2MetaString: string; +export declare const doc2: BundleElement; +export declare const doc2String: string; +export declare const noDocMeta: BundleElement; +export declare const noDocMetaString: string; +export declare const limitQuery: BundleElement; +export declare const limitQueryString: string; +export declare const limitToLastQuery: BundleElement; +export declare const limitToLastQueryString: string; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/logic_utils.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/logic_utils.test.d.ts new file mode 100644 index 0000000..9b0c1ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/logic_utils.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/misc.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/misc.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/misc.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/node_api.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/node_api.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/node_api.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/obj_map.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/obj_map.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/obj_map.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/sorted_map.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/sorted_map.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/sorted_map.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/sorted_set.test.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/sorted_set.test.d.ts new file mode 100644 index 0000000..9444bf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/unit/util/sorted_set.test.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/api_helpers.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/api_helpers.d.ts new file mode 100644 index 0000000..a4a9b0c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/api_helpers.d.ts @@ -0,0 +1,49 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentReference, Firestore, Query, CollectionReference, QuerySnapshot, DocumentSnapshot } from '../../src'; +import { DocumentKeySet } from '../../src/model/collections'; +import { JsonObject } from '../../src/model/object_value'; +/** + * A mock Firestore. Will not work for integration test. + */ +export declare const FIRESTORE: Firestore; +export declare function firestore(): Firestore; +export declare function newTestFirestore(projectId?: string): Firestore; +export declare function collectionReference(path: string): CollectionReference; +export declare function documentReference(path: string): DocumentReference; +export declare function documentSnapshot(path: string, data: JsonObject | null, fromCache: boolean, hasPendingWrites?: boolean): DocumentSnapshot; +export declare function query(path: string): Query; +/** + * A convenience method for creating a particular query snapshot for tests. + * + * @param path - To be used in constructing the query. + * @param oldDocs - Provides the prior set of documents in the QuerySnapshot. + * Each entry maps to a document, with the key being the document id, and the + * value being the document contents. + * @param docsToAdd - Specifies data to be added into the query snapshot as of + * now. Each entry maps to a document, with the key being the document id, and + * the value being the document contents. + * @param mutatedKeys - The list of document with pending writes. + * @param fromCache - Whether the query snapshot is cache result. + * @param syncStateChanged - Whether the sync state has changed. + * @returns A query snapshot that consists of both sets of documents. + */ +export declare function querySnapshot(path: string, oldDocs: { + [key: string]: JsonObject; +}, docsToAdd: { + [key: string]: JsonObject; +}, mutatedKeys: DocumentKeySet, fromCache: boolean, syncStateChanged: boolean, hasCachedResults?: boolean): QuerySnapshot; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/equality_matcher.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/equality_matcher.d.ts new file mode 100644 index 0000000..d019ad2 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/equality_matcher.d.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Duck-typed interface for objects that have an isEqual() method. + * + * Note: This is copied from src/util/misc.ts to avoid importing private types. + */ +export interface Equatable { + isEqual(other: T): boolean; +} +/** + * Custom equals override for types that have a free-standing equals functions + * (such as `queryEquals()`). + */ +export interface CustomMatcher { + equalsFn: (left: T, right: T) => boolean; + forType: Function; +} +export declare function addEqualityMatcher(...customMatchers: Array>): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/helpers.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/helpers.d.ts new file mode 100644 index 0000000..c8acefd --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/helpers.d.ts @@ -0,0 +1,206 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Bytes, DocumentReference } from '../../src'; +import { Bound } from '../../src/core/bound'; +import { BundledDocuments } from '../../src/core/bundle'; +import { DatabaseId } from '../../src/core/database_info'; +import { FieldFilter, CompositeFilter, Filter } from '../../src/core/filter'; +import { OrderBy } from '../../src/core/order_by'; +import { Query } from '../../src/core/query'; +import { SnapshotVersion } from '../../src/core/snapshot_version'; +import { TargetId } from '../../src/core/types'; +import { LimboDocumentChange, View, ViewChange } from '../../src/core/view'; +import { UserDataReader } from '../../src/lite-api/user_data_reader'; +import { LocalViewChanges } from '../../src/local/local_view_changes'; +import { TargetData, TargetPurpose } from '../../src/local/target_data'; +import { DocumentKeySet, DocumentMap } from '../../src/model/collections'; +import { Document, MutableDocument } from '../../src/model/document'; +import { DocumentComparator } from '../../src/model/document_comparator'; +import { DocumentKey } from '../../src/model/document_key'; +import { DocumentSet } from '../../src/model/document_set'; +import { FieldIndex, IndexKind, IndexOffset } from '../../src/model/field_index'; +import { FieldMask } from '../../src/model/field_mask'; +import { DeleteMutation, MutationResult, PatchMutation, Precondition, SetMutation } from '../../src/model/mutation'; +import { JsonObject, ObjectValue } from '../../src/model/object_value'; +import { FieldPath, ResourcePath } from '../../src/model/path'; +import { NamedQuery as ProtoNamedQuery, BundleMetadata as ProtoBundleMetadata, LimitType as ProtoLimitType } from '../../src/protos/firestore_bundle_proto'; +import * as api from '../../src/protos/firestore_proto_api'; +import { RemoteEvent, TargetChange } from '../../src/remote/remote_event'; +import { ByteString } from '../../src/util/byte_string'; +import { Code } from '../../src/util/error'; +import { Dict } from '../../src/util/obj'; +import { SortedMap } from '../../src/util/sorted_map'; +import { SortedSet } from '../../src/util/sorted_set'; +export type TestSnapshotVersion = number; +export declare function testUserDataReader(useProto3Json?: boolean): UserDataReader; +export declare function version(v: TestSnapshotVersion): SnapshotVersion; +export declare function ref(key: string, offset?: number): DocumentReference; +export declare function doc(keyStr: string, ver: TestSnapshotVersion, jsonOrObjectValue: JsonObject | ObjectValue, createTime?: TestSnapshotVersion): MutableDocument; +export declare function deletedDoc(keyStrOrDocumentKey: string | DocumentKey, ver: TestSnapshotVersion): MutableDocument; +export declare function unknownDoc(keyStr: string, ver: TestSnapshotVersion): MutableDocument; +export declare function removedDoc(keyStr: string): MutableDocument; +export declare function invalidDoc(keyStr: string): MutableDocument; +export declare function wrap(value: unknown): api.Value; +export declare function wrapObject(obj: JsonObject): ObjectValue; +export declare function dbId(project: string, database?: string): DatabaseId; +export declare function key(path: string): DocumentKey; +export declare function keys(...documents: Array): DocumentKeySet; +export declare function path(path: string, offset?: number): ResourcePath; +export declare function field(path: string): FieldPath; +export declare function fieldIndex(collectionGroup: string, options?: { + id?: number; + fields?: Array<[field: string, kind: IndexKind]>; + offset?: IndexOffset; + sequenceNumber?: number; +}): FieldIndex; +export declare function mask(...paths: string[]): FieldMask; +export declare function blob(...bytes: number[]): Bytes; +export declare function filter(path: string, op: string, value: unknown): FieldFilter; +export declare function andFilter(...filters: Filter[]): CompositeFilter; +export declare function orFilter(...filters: Filter[]): CompositeFilter; +export declare function setMutation(keyStr: string, json: JsonObject): SetMutation; +export declare function patchMutation(keyStr: string, json: JsonObject, precondition?: Precondition): PatchMutation; +export declare function mergeMutation(keyStr: string, json: JsonObject, updateMask: FieldPath[]): PatchMutation; +export declare function deleteMutation(keyStr: string): DeleteMutation; +export declare function mutationResult(testVersion: TestSnapshotVersion): MutationResult; +export declare function bound(values: unknown[], inclusive: boolean): Bound; +export declare function query(resourcePath: string, ...constraints: Array): Query; +export declare function targetData(targetId: TargetId, queryPurpose: TargetPurpose, path: string): TargetData; +export declare function noChangeEvent(targetId: number, snapshotVersion: number, resumeToken?: ByteString): RemoteEvent; +export declare function existenceFilterEvent(targetId: number, syncedKeys: DocumentKeySet, remoteCount: number, snapshotVersion: number, bloomFilter?: api.BloomFilter): RemoteEvent; +export declare function docAddedRemoteEvent(docOrDocs: MutableDocument | MutableDocument[], updatedInTargets?: TargetId[], removedFromTargets?: TargetId[], activeTargets?: TargetId[]): RemoteEvent; +export declare function docUpdateRemoteEvent(doc: MutableDocument, updatedInTargets?: TargetId[], removedFromTargets?: TargetId[], limboTargets?: TargetId[]): RemoteEvent; +export declare class TestBundledDocuments { + documents: BundledDocuments; + bundleName: string; + constructor(documents: BundledDocuments, bundleName: string); +} +export declare function bundledDocuments(documents: MutableDocument[], queryNames?: string[][], bundleName?: string): TestBundledDocuments; +export declare class TestNamedQuery { + namedQuery: ProtoNamedQuery; + matchingDocuments: DocumentKeySet; + constructor(namedQuery: ProtoNamedQuery, matchingDocuments: DocumentKeySet); +} +export declare function namedQuery(name: string, query: Query, limitType: ProtoLimitType, readTime: SnapshotVersion, matchingDocuments?: DocumentKeySet): TestNamedQuery; +export declare function bundleMetadata(id: string, createTime: TestSnapshotVersion, version?: number, totalDocuments?: number, totalBytes?: number): ProtoBundleMetadata; +export declare function updateMapping(snapshotVersion: SnapshotVersion, added: Array, modified: Array, removed: Array, current?: boolean): TargetChange; +export declare function addTargetMapping(...docsOrKeys: Array): TargetChange; +export declare function ackTarget(...docsOrKeys: Array): TargetChange; +export declare function limboChanges(changes: { + added?: Document[]; + removed?: Document[]; +}): LimboDocumentChange[]; +export declare function localViewChanges(targetId: TargetId, fromCache: boolean, changes: { + added?: string[]; + removed?: string[]; +}): LocalViewChanges; +/** + * Returns a ByteString representation for the platform from the given string. + */ +export declare function byteStringFromString(value: string): ByteString; +/** + * Decodes a base 64 decoded string. + * + * Note that this is typed to accept Uint8Arrays to match the types used + * by the spec tests. Since the spec tests only use JSON strings, this method + * throws if an Uint8Array is passed. + */ +export declare function stringFromBase64String(value?: string | Uint8Array): string; +/** Creates a resume token to match the given snapshot version. */ +export declare function resumeTokenForSnapshot(snapshotVersion: SnapshotVersion): ByteString; +export declare function orderBy(path: string, op?: string): OrderBy; +/** + * Converts a sorted map to an array with inorder traversal + */ +export declare function mapAsArray(sortedMap: SortedMap): Array<{ + key: K; + value: V; +}>; +/** + * Converts a list of documents or document keys to a sorted map. A document + * key is used to represent a deletion and maps to null. + */ +export declare function documentUpdates(...docsOrKeys: Array): DocumentMap; +/** + * Short for view.applyChanges(view.computeDocChanges(documentUpdates(docs))). + */ +export declare function applyDocChanges(view: View, ...docsOrKeys: Array): ViewChange; +/** + * Constructs a document set. + */ +export declare function documentSet(comp: DocumentComparator, ...docs: Document[]): DocumentSet; +export declare function documentSet(...docs: Document[]): DocumentSet; +/** + * Constructs a document key set. + */ +export declare function keySet(...keys: DocumentKey[]): DocumentKeySet; +/** Converts a DocumentSet to an array. */ +export declare function documentSetAsArray(docs: DocumentSet): Document[]; +export declare class DocComparator { + static byField(...fields: string[]): DocumentComparator; +} +/** + * Two helper functions to simplify testing isEqual() method. + */ +export declare function expectEqual(left: any, right: any, message?: string): void; +export declare function expectNotEqual(left: any, right: any, message?: string): void; +export declare function expectEqualArrays(left: unknown[], right: unknown[], message?: string): void; +/** + * Checks that an ordered array of elements yields the correct pair-wise + * comparison result for the supplied comparator + */ +export declare function expectCorrectComparisons(array: T[], comp: (left: T, right: T) => number): void; +/** + * Takes an array of "equality group" arrays and asserts that the comparator + * returns the same as comparing the indexes of the "equality groups" + * (0 for items in the same group). + */ +export declare function expectCorrectComparisonGroups(groups: T[][], comp: (left: T, right: T) => number): void; +/** Compares SortedSet to an array */ +export declare function expectSetToEqual(set: SortedSet, arr: T[]): void; +/** + * Takes an array of array of elements and compares each of the elements + * to every other element. + * + * Elements in the same inner array are expect to be equal with regard to + * the provided equality function to all other elements from the same array + * (including itself) and unequal to all other elements from the other array + */ +export declare function expectEqualitySets(elems: T[][], equalityFn: (v1: T, v2: T) => boolean, stringifyFn?: (v: T) => string): void; +export declare function validateFirestoreError(expectedCode: Code, actualError: Error): void; +export declare function forEachNumber(obj: Dict, fn: (key: number, val: V) => void): void; +/** + * Returns all possible permutations of the given array. + * For `[a, b]`, this method returns `[[a, b], [b, a]]`. + */ +export declare function computePermutations(input: T[]): T[][]; +/** + * Returns all possible combinations of the given array, including an empty + * array. For `[a, b, c]` this method returns + * `[[], [a], [a, b], [a, c], [b, c], [a, b, c]`. + */ +export declare function computeCombinations(input: T[]): T[][]; +/** + * Helper method to generate bloom filter proto value for mocking watch + * existence filter response. + */ +export declare function generateBloomFilterProto(config: { + contains: MutableDocument[]; + notContains: MutableDocument[]; + hashCount?: number; + bitCount?: number; +}): api.BloomFilter; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/node_persistence.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/node_persistence.d.ts new file mode 100644 index 0000000..c53048a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/node_persistence.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/promise.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/promise.d.ts new file mode 100644 index 0000000..d3f8374 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/promise.d.ts @@ -0,0 +1,28 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export interface Resolver { + (value: R | Promise): void; +} +export interface Rejecter { + (reason?: Error): void; +} +export declare class Deferred { + promise: Promise; + resolve: Resolver; + reject: Rejecter; + constructor(); +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/spec_test_helpers.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/spec_test_helpers.d.ts new file mode 100644 index 0000000..1ae9b67 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/spec_test_helpers.d.ts @@ -0,0 +1,19 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as api from '../../src/protos/firestore_proto_api'; +import { WatchChange } from '../../src/remote/watch_change'; +export declare function encodeWatchChange(watchChange: WatchChange): api.ListenResponse; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/test_platform.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/test_platform.d.ts new file mode 100644 index 0000000..8417eb4 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/test/util/test_platform.d.ts @@ -0,0 +1,61 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentLike, WindowLike } from '../../src/util/types'; +/** + * `Window` fake that implements the event and storage API that is used by + * Firestore. + */ +export declare class FakeWindow implements WindowLike { + private readonly fakeStorageArea; + private readonly fakeIndexedDb; + private storageListeners; + constructor(sharedFakeStorage: SharedFakeWebStorage, fakeIndexedDb?: IDBFactory); + get localStorage(): Storage; + get indexedDB(): IDBFactory | null; + addEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: EventListener): void; +} +export declare function testWindow(sharedWebStorage?: SharedFakeWebStorage): FakeWindow; +/** + * `Document` fake that implements the `visibilitychange` API used by Firestore. + */ +export declare class FakeDocument implements DocumentLike { + private _visibilityState; + private visibilityListener; + get visibilityState(): DocumentVisibilityState; + addEventListener(type: string, listener: EventListener): void; + removeEventListener(type: string, listener: EventListener): void; + raiseVisibilityEvent(visibility: DocumentVisibilityState): void; +} +export declare function testDocument(): FakeDocument; +/** + * `WebStorage` mock that implements the WebStorage behavior for multiple + * clients. To get a client-specific storage area that implements the WebStorage + * API, invoke `getStorageArea(storageListener)`. + */ +export declare class SharedFakeWebStorage { + private readonly data; + private readonly activeClients; + getStorageArea(storageListener: EventListener): Storage; + private clear; + private getItem; + private key; + private removeItem; + private setItem; + private get length(); + private raiseStorageEvent; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/index.browser.esm.js b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.browser.esm.js new file mode 100644 index 0000000..e44dcac --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.browser.esm.js @@ -0,0 +1,7660 @@ +import { _registerComponent, registerVersion, _isFirebaseServerApp, _getProvider, getApp, _removeServiceInstance, SDK_VERSION } from '@firebase/app'; +import { Component } from '@firebase/component'; +import { Logger, LogLevel } from '@firebase/logger'; +import { FirebaseError, getDefaultEmulatorHostnameAndPort, isCloudWorkstation, pingServer, updateEmulatorBanner, deepEqual, createMockUserToken, getModularInstance } from '@firebase/util'; +import { Integer } from '@firebase/webchannel-wrapper/bloom-blob'; + +const P = "4.9.2"; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Simple wrapper around a nullable UID. Mostly exists to make code more + * readable. + */ class User { + constructor(t) { + this.uid = t; + } + isAuthenticated() { + return null != this.uid; + } + /** + * Returns a key representing this user, suitable for inclusion in a + * dictionary. + */ toKey() { + return this.isAuthenticated() ? "uid:" + this.uid : "anonymous-user"; + } + isEqual(t) { + return t.uid === this.uid; + } +} + +/** A user with a null UID. */ User.UNAUTHENTICATED = new User(null), +// TODO(mikelehen): Look into getting a proper uid-equivalent for +// non-FirebaseAuth providers. +User.GOOGLE_CREDENTIALS = new User("google-credentials-uid"), User.FIRST_PARTY = new User("first-party-uid"), +User.MOCK_USER = new User("mock-user"); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let A = "12.3.0"; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const R = new Logger("@firebase/firestore"); + +/** + * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). + * + * @param logLevel - The verbosity you set for activity and error logging. Can + * be any of the following values: + * + *
    + *
  • `debug` for the most verbose logging level, primarily for + * debugging.
  • + *
  • `error` to log errors only.
  • + *
  • `silent` to turn off logging.
  • + *
+ */ function setLogLevel(t) { + R.setLogLevel(t); +} + +function __PRIVATE_logDebug(t, ...e) { + if (R.logLevel <= LogLevel.DEBUG) { + const r = e.map(__PRIVATE_argToString); + R.debug(`Firestore (${A}): ${t}`, ...r); + } +} + +function __PRIVATE_logError(t, ...e) { + if (R.logLevel <= LogLevel.ERROR) { + const r = e.map(__PRIVATE_argToString); + R.error(`Firestore (${A}): ${t}`, ...r); + } +} + +/** + * @internal + */ function __PRIVATE_logWarn(t, ...e) { + if (R.logLevel <= LogLevel.WARN) { + const r = e.map(__PRIVATE_argToString); + R.warn(`Firestore (${A}): ${t}`, ...r); + } +} + +/** + * Converts an additional log parameter to a string representation. + */ function __PRIVATE_argToString(t) { + if ("string" == typeof t) return t; + try { + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** Formats an object as a JSON string, suitable for logging. */ + return function __PRIVATE_formatJSON(t) { + return JSON.stringify(t); + }(t); + } catch (e) { + // Converting to JSON failed, just log the object directly + return t; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function fail(t, e, r) { + let n = "Unexpected state"; + "string" == typeof e ? n = e : r = e, __PRIVATE__fail(t, n, r); +} + +function __PRIVATE__fail(t, e, r) { + // Log the failure in addition to throw an exception, just in case the + // exception is swallowed. + let n = `FIRESTORE (${A}) INTERNAL ASSERTION FAILED: ${e} (ID: ${t.toString(16)})`; + if (void 0 !== r) try { + n += " CONTEXT: " + JSON.stringify(r); + } catch (t) { + n += " CONTEXT: " + r; + } + // NOTE: We don't use FirestoreError here because these are internal failures + // that cannot be handled by the user. (Also it would create a circular + // dependency between the error and assert modules which doesn't work.) + throw __PRIVATE_logError(n), new Error(n); +} + +function __PRIVATE_hardAssert(t, e, r, n) { + let i = "Unexpected state"; + "string" == typeof r ? i = r : n = r, t || __PRIVATE__fail(e, i, n); +} + +/** + * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an + * instance of `T` before casting. + */ function __PRIVATE_debugCast(t, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +e) { + return t; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const V = "ok", I = "cancelled", p = "unknown", y = "invalid-argument", g = "deadline-exceeded", w = "not-found", F = "already-exists", v = "permission-denied", D = "unauthenticated", b = "resource-exhausted", S = "failed-precondition", C = "aborted", N = "out-of-range", O = "unimplemented", q = "internal", B = "unavailable", $ = "data-loss"; + +/** An error returned by a Firestore operation. */ class FirestoreError extends FirebaseError { + /** @hideconstructor */ + constructor( + /** + * The backend error code associated with this error. + */ + t, + /** + * A custom error description. + */ + e) { + super(t, e), this.code = t, this.message = e, + // HACK: We write a toString property directly because Error is not a real + // class and so inheritance does not work correctly. We could alternatively + // do the same "back-door inheritance" trick that FirebaseError does. + this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_Deferred { + constructor() { + this.promise = new Promise(((t, e) => { + this.resolve = t, this.reject = e; + })); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_OAuthToken { + constructor(t, e) { + this.user = e, this.type = "OAuth", this.headers = new Map, this.headers.set("Authorization", `Bearer ${t}`); + } +} + +/** + * A CredentialsProvider that always yields an empty token. + * @internal + */ class __PRIVATE_EmptyAuthCredentialsProvider { + getToken() { + return Promise.resolve(null); + } + invalidateToken() {} + start(t, e) { + // Fire with initial user. + t.enqueueRetryable((() => e(User.UNAUTHENTICATED))); + } + shutdown() {} +} + +/** + * A CredentialsProvider that always returns a constant token. Used for + * emulator token mocking. + */ class __PRIVATE_EmulatorAuthCredentialsProvider { + constructor(t) { + this.token = t, + /** + * Stores the listener registered with setChangeListener() + * This isn't actually necessary since the UID never changes, but we use this + * to verify the listen contract is adhered to in tests. + */ + this.changeListener = null; + } + getToken() { + return Promise.resolve(this.token); + } + invalidateToken() {} + start(t, e) { + this.changeListener = e, + // Fire with initial user. + t.enqueueRetryable((() => e(this.token.user))); + } + shutdown() { + this.changeListener = null; + } +} + +/** Credential provider for the Lite SDK. */ class __PRIVATE_LiteAuthCredentialsProvider { + constructor(t) { + this.auth = null, t.onInit((t => { + this.auth = t; + })); + } + getToken() { + return this.auth ? this.auth.getToken().then((t => t ? (__PRIVATE_hardAssert("string" == typeof t.accessToken, 42297, { + t: t + }), new __PRIVATE_OAuthToken(t.accessToken, new User(this.auth.getUid()))) : null)) : Promise.resolve(null); + } + invalidateToken() {} + start(t, e) {} + shutdown() {} +} + +/* + * FirstPartyToken provides a fresh token each time its value + * is requested, because if the token is too old, requests will be rejected. + * Technically this may no longer be necessary since the SDK should gracefully + * recover from unauthenticated errors (see b/33147818 for context), but it's + * safer to keep the implementation as-is. + */ class __PRIVATE_FirstPartyToken { + constructor(t, e, r) { + this.i = t, this.o = e, this.u = r, this.type = "FirstParty", this.user = User.FIRST_PARTY, + this.l = new Map; + } + /** + * Gets an authorization token, using a provided factory function, or return + * null. + */ h() { + return this.u ? this.u() : null; + } + get headers() { + this.l.set("X-Goog-AuthUser", this.i); + // Use array notation to prevent minification + const t = this.h(); + return t && this.l.set("Authorization", t), this.o && this.l.set("X-Goog-Iam-Authorization-Token", this.o), + this.l; + } +} + +/* + * Provides user credentials required for the Firestore JavaScript SDK + * to authenticate the user, using technique that is only available + * to applications hosted by Google. + */ class __PRIVATE_FirstPartyAuthCredentialsProvider { + constructor(t, e, r) { + this.i = t, this.o = e, this.u = r; + } + getToken() { + return Promise.resolve(new __PRIVATE_FirstPartyToken(this.i, this.o, this.u)); + } + start(t, e) { + // Fire with initial uid. + t.enqueueRetryable((() => e(User.FIRST_PARTY))); + } + shutdown() {} + invalidateToken() {} +} + +class AppCheckToken { + constructor(t) { + this.value = t, this.type = "AppCheck", this.headers = new Map, t && t.length > 0 && this.headers.set("x-firebase-appcheck", this.value); + } +} + +/** AppCheck token provider for the Lite SDK. */ class __PRIVATE_LiteAppCheckTokenProvider { + constructor(e, r) { + this.m = r, this.appCheck = null, this.T = null, _isFirebaseServerApp(e) && e.settings.appCheckToken && (this.T = e.settings.appCheckToken), + r.onInit((t => { + this.appCheck = t; + })); + } + getToken() { + return this.T ? Promise.resolve(new AppCheckToken(this.T)) : this.appCheck ? this.appCheck.getToken().then((t => t ? (__PRIVATE_hardAssert("string" == typeof t.token, 3470, { + tokenResult: t + }), new AppCheckToken(t.token)) : null)) : Promise.resolve(null); + } + invalidateToken() {} + start(t, e) {} + shutdown() {} +} + +/** + * Builds a CredentialsProvider depending on the type of + * the credentials passed in. + */ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class DatabaseInfo { + /** + * Constructs a DatabaseInfo using the provided host, databaseId and + * persistenceKey. + * + * @param databaseId - The database to use. + * @param appId - The Firebase App Id. + * @param persistenceKey - A unique identifier for this Firestore's local + * storage (used in conjunction with the databaseId). + * @param host - The Firestore backend host to connect to. + * @param ssl - Whether to use SSL when connecting. + * @param forceLongPolling - Whether to use the forceLongPolling option + * when using WebChannel as the network transport. + * @param autoDetectLongPolling - Whether to use the detectBufferingProxy + * option when using WebChannel as the network transport. + * @param longPollingOptions Options that configure long-polling. + * @param useFetchStreams Whether to use the Fetch API instead of + * XMLHTTPRequest + */ + constructor(t, e, r, n, i, s, o, a, u, _) { + this.databaseId = t, this.appId = e, this.persistenceKey = r, this.host = n, this.ssl = i, + this.forceLongPolling = s, this.autoDetectLongPolling = o, this.longPollingOptions = a, + this.useFetchStreams = u, this.isUsingEmulator = _; + } +} + +/** The default database name for a project. */ const Q = "(default)"; + +/** + * Represents the database ID a Firestore client is associated with. + * @internal + */ class DatabaseId { + constructor(t, e) { + this.projectId = t, this.database = e || Q; + } + static empty() { + return new DatabaseId("", ""); + } + get isDefaultDatabase() { + return this.database === Q; + } + isEqual(t) { + return t instanceof DatabaseId && t.projectId === this.projectId && t.database === this.database; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Generates `nBytes` of random bytes. + * + * If `nBytes < 0` , an error will be thrown. + */ +function __PRIVATE_randomBytes(t) { + // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available. + const e = + // eslint-disable-next-line @typescript-eslint/no-explicit-any + "undefined" != typeof self && (self.crypto || self.msCrypto), r = new Uint8Array(t); + if (e && "function" == typeof e.getRandomValues) e.getRandomValues(r); else + // Falls back to Math.random + for (let e = 0; e < t; e++) r[e] = Math.floor(256 * Math.random()); + return r; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A utility class for generating unique alphanumeric IDs of a specified length. + * + * @internal + * Exported internally for testing purposes. + */ class __PRIVATE_AutoId { + static newId() { + // Alphanumeric characters + const t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", e = 62 * Math.floor(256 / 62); + // The largest byte value that is a multiple of `char.length`. + let r = ""; + for (;r.length < 20; ) { + const n = __PRIVATE_randomBytes(40); + for (let i = 0; i < n.length; ++i) + // Only accept values that are [0, maxMultiple), this ensures they can + // be evenly mapped to indices of `chars` via a modulo operation. + r.length < 20 && n[i] < e && (r += t.charAt(n[i] % 62)); + } + return r; + } +} + +function __PRIVATE_primitiveComparator(t, e) { + return t < e ? -1 : t > e ? 1 : 0; +} + +/** Compare strings in UTF-8 encoded byte order */ function __PRIVATE_compareUtf8Strings(t, e) { + // Find the first differing character (a.k.a. "UTF-16 code unit") in the two strings and, + // if found, use that character to determine the relative ordering of the two strings as a + // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by + // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8 + // and UTF-16 happen to represent Unicode code points. + // After finding the first pair of differing characters, there are two cases: + // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or + // both are surrogates from a surrogate pair (that collectively represent code points greater + // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the + // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is + // sufficient. + // Case 2: One character is a surrogate and the other is not. In this case the surrogate- + // containing string is always ordered after the non-surrogate. This is because surrogates are + // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations + // and are lexicographically greater than the 1, 2, or 3-byte representations of code points + // less than or equal to 0xFFFF. + // An example of why Case 2 is required is comparing the following two Unicode code points: + // |-----------------------|------------|---------------------|-----------------| + // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding | + // |-----------------------|------------|---------------------|-----------------| + // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD | + // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 | + // |-----------------------|------------|---------------------|-----------------| + // A lexicographical comparison of the UTF-8 encodings of these code points would order + // "Replacement Character" _before_ "Grinning Face" because 0xEF is less than 0xF0. However, a + // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously + // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out, + // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate + // pair with those that do not. + const r = Math.min(t.length, e.length); + for (let n = 0; n < r; n++) { + const r = t.charAt(n), i = e.charAt(n); + if (r !== i) return __PRIVATE_isSurrogate(r) === __PRIVATE_isSurrogate(i) ? __PRIVATE_primitiveComparator(r, i) : __PRIVATE_isSurrogate(r) ? 1 : -1; + } + // Use the lengths of the strings to determine the overall comparison result since either the + // strings were equal or one is a prefix of the other. + return __PRIVATE_primitiveComparator(t.length, e.length); +} + +const k = 55296, L = 57343; + +function __PRIVATE_isSurrogate(t) { + const e = t.charCodeAt(0); + return e >= k && e <= L; +} + +/** Helper to compare arrays using isEqual(). */ function __PRIVATE_arrayEquals(t, e, r) { + return t.length === e.length && t.every(((t, n) => r(t, e[n]))); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const M = "__name__"; + +/** + * Path represents an ordered sequence of string segments. + */ class BasePath { + constructor(t, e, r) { + void 0 === e ? e = 0 : e > t.length && fail(637, { + offset: e, + range: t.length + }), void 0 === r ? r = t.length - e : r > t.length - e && fail(1746, { + length: r, + range: t.length - e + }), this.segments = t, this.offset = e, this.len = r; + } + get length() { + return this.len; + } + isEqual(t) { + return 0 === BasePath.comparator(this, t); + } + child(t) { + const e = this.segments.slice(this.offset, this.limit()); + return t instanceof BasePath ? t.forEach((t => { + e.push(t); + })) : e.push(t), this.construct(e); + } + /** The index of one past the last segment of the path. */ limit() { + return this.offset + this.length; + } + popFirst(t) { + return t = void 0 === t ? 1 : t, this.construct(this.segments, this.offset + t, this.length - t); + } + popLast() { + return this.construct(this.segments, this.offset, this.length - 1); + } + firstSegment() { + return this.segments[this.offset]; + } + lastSegment() { + return this.get(this.length - 1); + } + get(t) { + return this.segments[this.offset + t]; + } + isEmpty() { + return 0 === this.length; + } + isPrefixOf(t) { + if (t.length < this.length) return !1; + for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1; + return !0; + } + isImmediateParentOf(t) { + if (this.length + 1 !== t.length) return !1; + for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1; + return !0; + } + forEach(t) { + for (let e = this.offset, r = this.limit(); e < r; e++) t(this.segments[e]); + } + toArray() { + return this.segments.slice(this.offset, this.limit()); + } + /** + * Compare 2 paths segment by segment, prioritizing numeric IDs + * (e.g., "__id123__") in numeric ascending order, followed by string + * segments in lexicographical order. + */ static comparator(t, e) { + const r = Math.min(t.length, e.length); + for (let n = 0; n < r; n++) { + const r = BasePath.compareSegments(t.get(n), e.get(n)); + if (0 !== r) return r; + } + return __PRIVATE_primitiveComparator(t.length, e.length); + } + static compareSegments(t, e) { + const r = BasePath.isNumericId(t), n = BasePath.isNumericId(e); + return r && !n ? -1 : !r && n ? 1 : r && n ? BasePath.extractNumericId(t).compare(BasePath.extractNumericId(e)) : __PRIVATE_compareUtf8Strings(t, e); + } + // Checks if a segment is a numeric ID (starts with "__id" and ends with "__"). + static isNumericId(t) { + return t.startsWith("__id") && t.endsWith("__"); + } + static extractNumericId(t) { + return Integer.fromString(t.substring(4, t.length - 2)); + } +} + +/** + * A slash-separated path for navigating resources (documents and collections) + * within Firestore. + * + * @internal + */ class ResourcePath extends BasePath { + construct(t, e, r) { + return new ResourcePath(t, e, r); + } + canonicalString() { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + return this.toArray().join("/"); + } + toString() { + return this.canonicalString(); + } + /** + * Returns a string representation of this path + * where each path segment has been encoded with + * `encodeURIComponent`. + */ toUriEncodedString() { + return this.toArray().map(encodeURIComponent).join("/"); + } + /** + * Creates a resource path from the given slash-delimited string. If multiple + * arguments are provided, all components are combined. Leading and trailing + * slashes from all components are ignored. + */ static fromString(...t) { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + const e = []; + for (const r of t) { + if (r.indexOf("//") >= 0) throw new FirestoreError(y, `Invalid segment (${r}). Paths must not contain // in them.`); + // Strip leading and trailing slashed. + e.push(...r.split("/").filter((t => t.length > 0))); + } + return new ResourcePath(e); + } + static emptyPath() { + return new ResourcePath([]); + } +} + +const x = /^[_a-zA-Z][_a-zA-Z0-9]*$/; + +/** + * A dot-separated path for navigating sub-objects within a document. + * @internal + */ class FieldPath$1 extends BasePath { + construct(t, e, r) { + return new FieldPath$1(t, e, r); + } + /** + * Returns true if the string could be used as a segment in a field path + * without escaping. + */ static isValidIdentifier(t) { + return x.test(t); + } + canonicalString() { + return this.toArray().map((t => (t = t.replace(/\\/g, "\\\\").replace(/`/g, "\\`"), + FieldPath$1.isValidIdentifier(t) || (t = "`" + t + "`"), t))).join("."); + } + toString() { + return this.canonicalString(); + } + /** + * Returns true if this field references the key of a document. + */ isKeyField() { + return 1 === this.length && this.get(0) === M; + } + /** + * The field designating the key of a document. + */ static keyField() { + return new FieldPath$1([ M ]); + } + /** + * Parses a field string from the given server-formatted string. + * + * - Splitting the empty string is not allowed (for now at least). + * - Empty segments within the string (e.g. if there are two consecutive + * separators) are not allowed. + * + * TODO(b/37244157): we should make this more strict. Right now, it allows + * non-identifier path components, even if they aren't escaped. + */ static fromServerFormat(t) { + const e = []; + let r = "", n = 0; + const __PRIVATE_addCurrentSegment = () => { + if (0 === r.length) throw new FirestoreError(y, `Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`); + e.push(r), r = ""; + }; + let i = !1; + for (;n < t.length; ) { + const e = t[n]; + if ("\\" === e) { + if (n + 1 === t.length) throw new FirestoreError(y, "Path has trailing escape character: " + t); + const e = t[n + 1]; + if ("\\" !== e && "." !== e && "`" !== e) throw new FirestoreError(y, "Path has invalid escape sequence: " + t); + r += e, n += 2; + } else "`" === e ? (i = !i, n++) : "." !== e || i ? (r += e, n++) : (__PRIVATE_addCurrentSegment(), + n++); + } + if (__PRIVATE_addCurrentSegment(), i) throw new FirestoreError(y, "Unterminated ` in path: " + t); + return new FieldPath$1(e); + } + static emptyPath() { + return new FieldPath$1([]); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @internal + */ class DocumentKey { + constructor(t) { + this.path = t; + } + static fromPath(t) { + return new DocumentKey(ResourcePath.fromString(t)); + } + static fromName(t) { + return new DocumentKey(ResourcePath.fromString(t).popFirst(5)); + } + static empty() { + return new DocumentKey(ResourcePath.emptyPath()); + } + get collectionGroup() { + return this.path.popLast().lastSegment(); + } + /** Returns true if the document is in the specified collectionId. */ hasCollectionId(t) { + return this.path.length >= 2 && this.path.get(this.path.length - 2) === t; + } + /** Returns the collection group (i.e. the name of the parent collection) for this key. */ getCollectionGroup() { + return this.path.get(this.path.length - 2); + } + /** Returns the fully qualified path to the parent collection. */ getCollectionPath() { + return this.path.popLast(); + } + isEqual(t) { + return null !== t && 0 === ResourcePath.comparator(this.path, t.path); + } + toString() { + return this.path.toString(); + } + static comparator(t, e) { + return ResourcePath.comparator(t.path, e.path); + } + static isDocumentKey(t) { + return t.length % 2 == 0; + } + /** + * Creates and returns a new document key with the given segments. + * + * @param segments - The segments of the path to the document + * @returns A new instance of DocumentKey + */ static fromSegments(t) { + return new DocumentKey(new ResourcePath(t.slice())); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_validateNonEmptyArgument(t, e, r) { + if (!r) throw new FirestoreError(y, `Function ${t}() cannot be called with an empty ${e}.`); +} + +/** + * Validates that two boolean options are not set at the same time. + * @internal + */ +/** + * Validates that `path` refers to a document (indicated by the fact it contains + * an even numbers of segments). + */ +function __PRIVATE_validateDocumentPath(t) { + if (!DocumentKey.isDocumentKey(t)) throw new FirestoreError(y, `Invalid document reference. Document references must have an even number of segments, but ${t} has ${t.length}.`); +} + +/** + * Validates that `path` refers to a collection (indicated by the fact it + * contains an odd numbers of segments). + */ function __PRIVATE_validateCollectionPath(t) { + if (DocumentKey.isDocumentKey(t)) throw new FirestoreError(y, `Invalid collection reference. Collection references must have an odd number of segments, but ${t} has ${t.length}.`); +} + +/** + * Returns true if it's a non-null object without a custom prototype + * (i.e. excludes Array, Date, etc.). + */ function __PRIVATE_isPlainObject(t) { + return "object" == typeof t && null !== t && (Object.getPrototypeOf(t) === Object.prototype || null === Object.getPrototypeOf(t)); +} + +/** Returns a string describing the type / value of the provided input. */ function __PRIVATE_valueDescription(t) { + if (void 0 === t) return "undefined"; + if (null === t) return "null"; + if ("string" == typeof t) return t.length > 20 && (t = `${t.substring(0, 20)}...`), + JSON.stringify(t); + if ("number" == typeof t || "boolean" == typeof t) return "" + t; + if ("object" == typeof t) { + if (t instanceof Array) return "an array"; + { + const e = + /** try to get the constructor name for an object. */ + function __PRIVATE_tryGetCustomObjectType(t) { + if (t.constructor) return t.constructor.name; + return null; + } + /** + * Casts `obj` to `T`, optionally unwrapping Compat types to expose the + * underlying instance. Throws if `obj` is not an instance of `T`. + * + * This cast is used in the Lite and Full SDK to verify instance types for + * arguments passed to the public API. + * @internal + */ (t); + return e ? `a custom ${e} object` : "an object"; + } + } + return "function" == typeof t ? "a function" : fail(12329, { + type: typeof t + }); +} + +function __PRIVATE_cast(t, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +e) { + if ("_delegate" in t && ( + // Unwrap Compat types + // eslint-disable-next-line @typescript-eslint/no-explicit-any + t = t._delegate), !(t instanceof e)) { + if (e.name === t.constructor.name) throw new FirestoreError(y, "Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?"); + { + const r = __PRIVATE_valueDescription(t); + throw new FirestoreError(y, `Expected type '${e.name}', but it was: ${r}`); + } + } + return t; +} + +function __PRIVATE_validatePositiveNumber(t, e) { + if (e <= 0) throw new FirestoreError(y, `Function ${t}() requires a positive number, but it was: ${e}.`); +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Compares two `ExperimentalLongPollingOptions` objects for equality. + */ +/** + * Creates and returns a new `ExperimentalLongPollingOptions` with the same + * option values as the given instance. + */ +function __PRIVATE_cloneLongPollingOptions(t) { + const e = {}; + return void 0 !== t.timeoutSeconds && (e.timeoutSeconds = t.timeoutSeconds), e; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The value returned from the most recent invocation of + * `generateUniqueDebugId()`, or null if it has never been invoked. + */ let U = null; + +/** + * Generates and returns an initial value for `lastUniqueDebugId`. + * + * The returned value is randomly selected from a range of integers that are + * represented as 8 hexadecimal digits. This means that (within reason) any + * numbers generated by incrementing the returned number by 1 will also be + * represented by 8 hexadecimal digits. This leads to all "IDs" having the same + * length when converted to a hexadecimal string, making reading logs containing + * these IDs easier to follow. And since the return value is randomly selected + * it will help to differentiate between logs from different executions. + */ +/** + * Generates and returns a unique ID as a hexadecimal string. + * + * The returned ID is intended to be used in debug logging messages to help + * correlate log messages that may be spatially separated in the logs, but + * logically related. For example, a network connection could include the same + * "debug ID" string in all of its log messages to help trace a specific + * connection over time. + * + * @return the 10-character generated ID (e.g. "0xa1b2c3d4"). + */ +function __PRIVATE_generateUniqueDebugId() { + return null === U ? U = function __PRIVATE_generateInitialUniqueDebugId() { + return 268435456 + Math.round(2147483648 * Math.random()); + }() : U++, "0x" + U.toString(16); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns whether a variable is either undefined or null. + */ function __PRIVATE_isNullOrUndefined(t) { + return null == t; +} + +/** Returns whether the value represents -0. */ function __PRIVATE_isNegativeZero(t) { + // Detect if the value is -0.0. Based on polyfill from + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is + return 0 === t && 1 / t == -1 / 0; +} + +/** + * Returns whether a value is an integer and in the safe integer range + * @param value - The value to test for being an integer and in the safe range + */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const j = "RestConnection", z = { + BatchGetDocuments: "batchGet", + Commit: "commit", + RunQuery: "runQuery", + RunAggregationQuery: "runAggregationQuery" +}; + +/** + * Maps RPC names to the corresponding REST endpoint name. + * + * We use array notation to avoid mangling. + */ +/** + * Base class for all Rest-based connections to the backend (WebChannel and + * HTTP). + */ +class __PRIVATE_RestConnection { + get P() { + // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine + // where to run the query, and expect the `request` to NOT specify the "path". + return !1; + } + constructor(t) { + this.databaseInfo = t, this.databaseId = t.databaseId; + const e = t.ssl ? "https" : "http", r = encodeURIComponent(this.databaseId.projectId), n = encodeURIComponent(this.databaseId.database); + this.A = e + "://" + t.host, this.R = `projects/${r}/databases/${n}`, this.V = this.databaseId.database === Q ? `project_id=${r}` : `project_id=${r}&database_id=${n}`; + } + I(t, e, r, n, i) { + const s = __PRIVATE_generateUniqueDebugId(), o = this.p(t, e.toUriEncodedString()); + __PRIVATE_logDebug(j, `Sending RPC '${t}' ${s}:`, o, r); + const a = { + "google-cloud-resource-prefix": this.R, + "x-goog-request-params": this.V + }; + this.F(a, n, i); + const {host: u} = new URL(o), _ = isCloudWorkstation(u); + return this.v(t, o, a, r, _).then((e => (__PRIVATE_logDebug(j, `Received RPC '${t}' ${s}: `, e), + e)), (e => { + throw __PRIVATE_logWarn(j, `RPC '${t}' ${s} failed with error: `, e, "url: ", o, "request:", r), + e; + })); + } + D(t, e, r, n, i, s) { + // The REST API automatically aggregates all of the streamed results, so we + // can just use the normal invoke() method. + return this.I(t, e, r, n, i); + } + /** + * Modifies the headers for a request, adding any authorization token if + * present and any additional headers for the request. + */ F(t, e, r) { + t["X-Goog-Api-Client"] = + // SDK_VERSION is updated to different value at runtime depending on the entry point, + // so we need to get its value when we need it in a function. + function __PRIVATE_getGoogApiClientValue() { + return "gl-js/ fire/" + A; + }(), + // Content-Type: text/plain will avoid preflight requests which might + // mess with CORS and redirects by proxies. If we add custom headers + // we will need to change this code to potentially use the $httpOverwrite + // parameter supported by ESF to avoid triggering preflight requests. + t["Content-Type"] = "text/plain", this.databaseInfo.appId && (t["X-Firebase-GMPID"] = this.databaseInfo.appId), + e && e.headers.forEach(((e, r) => t[r] = e)), r && r.headers.forEach(((e, r) => t[r] = e)); + } + p(t, e) { + const r = z[t]; + return `${this.A}/v1/${e}:${r}`; + } + /** + * Closes and cleans up any resources associated with the connection. This + * implementation is a no-op because there are no resources associated + * with the RestConnection that need to be cleaned up. + */ terminate() { + // No-op + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Error Codes describing the different ways GRPC can fail. These are copied + * directly from GRPC's sources here: + * + * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h + * + * Important! The names of these identifiers matter because the string forms + * are used for reverse lookups from the webchannel stream. Do NOT change the + * names of these identifiers or change this into a const enum. + */ var W, K; + +/** + * Converts an HTTP Status Code to the equivalent error code. + * + * @param status - An HTTP Status Code, like 200, 404, 503, etc. + * @returns The equivalent Code. Unknown status codes are mapped to + * Code.UNKNOWN. + */ +function __PRIVATE_mapCodeFromHttpStatus(t) { + if (void 0 === t) return __PRIVATE_logError("RPC_ERROR", "HTTP error has no status"), + p; + // The canonical error codes for Google APIs [1] specify mapping onto HTTP + // status codes but the mapping is not bijective. In each case of ambiguity + // this function chooses a primary error. + + // [1] + // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto + switch (t) { + case 200: + // OK + return V; + + case 400: + // Bad Request + return S; + + // Other possibilities based on the forward mapping + // return Code.INVALID_ARGUMENT; + // return Code.OUT_OF_RANGE; + case 401: + // Unauthorized + return D; + + case 403: + // Forbidden + return v; + + case 404: + // Not Found + return w; + + case 409: + // Conflict + return C; + + // Other possibilities: + // return Code.ALREADY_EXISTS; + case 416: + // Range Not Satisfiable + return N; + + case 429: + // Too Many Requests + return b; + + case 499: + // Client Closed Request + return I; + + case 500: + // Internal Server Error + return p; + + // Other possibilities: + // return Code.INTERNAL; + // return Code.DATA_LOSS; + case 501: + // Unimplemented + return O; + + case 503: + // Service Unavailable + return B; + + case 504: + // Gateway Timeout + return g; + + default: + return t >= 200 && t < 300 ? V : t >= 400 && t < 500 ? S : t >= 500 && t < 600 ? q : p; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A Rest-based connection that relies on the native HTTP stack + * (e.g. `fetch` or a polyfill). + */ (K = W || (W = {}))[K.OK = 0] = "OK", K[K.CANCELLED = 1] = "CANCELLED", K[K.UNKNOWN = 2] = "UNKNOWN", +K[K.INVALID_ARGUMENT = 3] = "INVALID_ARGUMENT", K[K.DEADLINE_EXCEEDED = 4] = "DEADLINE_EXCEEDED", +K[K.NOT_FOUND = 5] = "NOT_FOUND", K[K.ALREADY_EXISTS = 6] = "ALREADY_EXISTS", K[K.PERMISSION_DENIED = 7] = "PERMISSION_DENIED", +K[K.UNAUTHENTICATED = 16] = "UNAUTHENTICATED", K[K.RESOURCE_EXHAUSTED = 8] = "RESOURCE_EXHAUSTED", +K[K.FAILED_PRECONDITION = 9] = "FAILED_PRECONDITION", K[K.ABORTED = 10] = "ABORTED", +K[K.OUT_OF_RANGE = 11] = "OUT_OF_RANGE", K[K.UNIMPLEMENTED = 12] = "UNIMPLEMENTED", +K[K.INTERNAL = 13] = "INTERNAL", K[K.UNAVAILABLE = 14] = "UNAVAILABLE", K[K.DATA_LOSS = 15] = "DATA_LOSS"; + +class __PRIVATE_FetchConnection extends __PRIVATE_RestConnection { + S(t, e) { + throw new Error("Not supported by FetchConnection"); + } + async v(t, e, r, n, i) { + const s = JSON.stringify(n); + let o; + try { + const t = { + method: "POST", + headers: r, + body: s + }; + i && (t.credentials = "include"), o = await fetch(e, t); + } catch (t) { + const e = t; + throw new FirestoreError(__PRIVATE_mapCodeFromHttpStatus(e.status), "Request failed with error: " + e.statusText); + } + if (!o.ok) { + let t = await o.json(); + Array.isArray(t) && (t = t[0]); + const e = t?.error?.message; + throw new FirestoreError(__PRIVATE_mapCodeFromHttpStatus(o.status), `Request failed with error: ${e ?? o.statusText}`); + } + return o.json(); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Initializes the HTTP connection for the REST API. */ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Concrete implementation of the Aggregate type. + */ +class __PRIVATE_AggregateImpl { + constructor(t, e, r) { + this.alias = t, this.aggregateType = e, this.fieldPath = r; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_objectSize(t) { + let e = 0; + for (const r in t) Object.prototype.hasOwnProperty.call(t, r) && e++; + return e; +} + +function forEach(t, e) { + for (const r in t) Object.prototype.hasOwnProperty.call(t, r) && e(r, t[r]); +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An error encountered while decoding base64 string. + */ +class __PRIVATE_Base64DecodeError extends Error { + constructor() { + super(...arguments), this.name = "Base64DecodeError"; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Converts a Base64 encoded string to a binary string. */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Immutable class that represents a "proto" byte string. + * + * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when + * sent on the wire. This class abstracts away this differentiation by holding + * the proto byte string in a common class that must be converted into a string + * before being sent as a proto. + * @internal + */ +class ByteString { + constructor(t) { + this.binaryString = t; + } + static fromBase64String(t) { + const e = function __PRIVATE_decodeBase64(t) { + try { + return atob(t); + } catch (t) { + // Check that `DOMException` is defined before using it to avoid + // "ReferenceError: Property 'DOMException' doesn't exist" in react-native. + // (https://github.com/firebase/firebase-js-sdk/issues/7115) + throw "undefined" != typeof DOMException && t instanceof DOMException ? new __PRIVATE_Base64DecodeError("Invalid base64 string: " + t) : t; + } + } + /** Converts a binary string to a Base64 encoded string. */ (t); + return new ByteString(e); + } + static fromUint8Array(t) { + // TODO(indexing); Remove the copy of the byte string here as this method + // is frequently called during indexing. + const e = + /** + * Helper function to convert an Uint8array to a binary string. + */ + function __PRIVATE_binaryStringFromUint8Array(t) { + let e = ""; + for (let r = 0; r < t.length; ++r) e += String.fromCharCode(t[r]); + return e; + } + /** + * Helper function to convert a binary string to an Uint8Array. + */ (t); + return new ByteString(e); + } + [Symbol.iterator]() { + let t = 0; + return { + next: () => t < this.binaryString.length ? { + value: this.binaryString.charCodeAt(t++), + done: !1 + } : { + value: void 0, + done: !0 + } + }; + } + toBase64() { + return function __PRIVATE_encodeBase64(t) { + return btoa(t); + }(this.binaryString); + } + toUint8Array() { + return function __PRIVATE_uint8ArrayFromBinaryString(t) { + const e = new Uint8Array(t.length); + for (let r = 0; r < t.length; r++) e[r] = t.charCodeAt(r); + return e; + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + // A RegExp matching ISO 8601 UTC timestamps with optional fraction. + (this.binaryString); + } + approximateByteSize() { + return 2 * this.binaryString.length; + } + compareTo(t) { + return __PRIVATE_primitiveComparator(this.binaryString, t.binaryString); + } + isEqual(t) { + return this.binaryString === t.binaryString; + } +} + +ByteString.EMPTY_BYTE_STRING = new ByteString(""); + +const G = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/); + +/** + * Converts the possible Proto values for a timestamp value into a "seconds and + * nanos" representation. + */ function __PRIVATE_normalizeTimestamp(t) { + // The json interface (for the browser) will return an iso timestamp string, + // while the proto js library (for node) will return a + // google.protobuf.Timestamp instance. + if (__PRIVATE_hardAssert(!!t, 39018), "string" == typeof t) { + // The date string can have higher precision (nanos) than the Date class + // (millis), so we do some custom parsing here. + // Parse the nanos right out of the string. + let e = 0; + const r = G.exec(t); + if (__PRIVATE_hardAssert(!!r, 46558, { + timestamp: t + }), r[1]) { + // Pad the fraction out to 9 digits (nanos). + let t = r[1]; + t = (t + "000000000").substr(0, 9), e = Number(t); + } + // Parse the date to get the seconds. + const n = new Date(t); + return { + seconds: Math.floor(n.getTime() / 1e3), + nanos: e + }; + } + return { + seconds: __PRIVATE_normalizeNumber(t.seconds), + nanos: __PRIVATE_normalizeNumber(t.nanos) + }; +} + +/** + * Converts the possible Proto types for numbers into a JavaScript number. + * Returns 0 if the value is not numeric. + */ function __PRIVATE_normalizeNumber(t) { + // TODO(bjornick): Handle int64 greater than 53 bits. + return "number" == typeof t ? t : "string" == typeof t ? Number(t) : 0; +} + +/** Converts the possible Proto types for Blobs into a ByteString. */ function __PRIVATE_normalizeByteString(t) { + return "string" == typeof t ? ByteString.fromBase64String(t) : ByteString.fromUint8Array(t); +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Helper function to define a JSON schema {@link Property}. + * @private + * @internal + */ function property(t, e) { + const r = { + typeString: t + }; + return e && (r.value = e), r; +} + +/** + * Validates the JSON object based on the provided schema, and narrows the type to the provided + * JSON schema. + * @private + * @internal + * + * @param json A JSON object to validate. + * @param scheme a {@link JsonSchema} that defines the properties to validate. + * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise. + */ function __PRIVATE_validateJSON(t, e) { + if (!__PRIVATE_isPlainObject(t)) throw new FirestoreError(y, "JSON must be an object"); + let r; + for (const n in e) if (e[n]) { + const i = e[n].typeString, s = "value" in e[n] ? { + value: e[n].value + } : void 0; + if (!(n in t)) { + r = `JSON missing required field: '${n}'`; + break; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const o = t[n]; + if (i && typeof o !== i) { + r = `JSON field '${n}' must be a ${i}.`; + break; + } + if (void 0 !== s && o !== s.value) { + r = `Expected '${n}' field to equal '${s.value}'`; + break; + } + } + if (r) throw new FirestoreError(y, r); + return !0; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z). +const J = -62135596800, H = 1e6; + +// Number of nanoseconds in a millisecond. +/** + * A `Timestamp` represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. + * + * It is encoded using the Proleptic Gregorian Calendar which extends the + * Gregorian calendar backwards to year one. It is encoded assuming all minutes + * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59.999999999Z. + * + * For examples and further specifications, refer to the + * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. + */ +class Timestamp { + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns a new timestamp representing the current date. + */ + static now() { + return Timestamp.fromMillis(Date.now()); + } + /** + * Creates a new timestamp from the given date. + * + * @param date - The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the given + * date. + */ static fromDate(t) { + return Timestamp.fromMillis(t.getTime()); + } + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds - Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the given + * number of milliseconds. + */ static fromMillis(t) { + const e = Math.floor(t / 1e3), r = Math.floor((t - 1e3 * e) * H); + return new Timestamp(e, r); + } + /** + * Creates a new timestamp. + * + * @param seconds - The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds - The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + t, + /** + * The fractions of a second at nanosecond resolution.* + */ + e) { + if (this.seconds = t, this.nanoseconds = e, e < 0) throw new FirestoreError(y, "Timestamp nanoseconds out of range: " + e); + if (e >= 1e9) throw new FirestoreError(y, "Timestamp nanoseconds out of range: " + e); + if (t < J) throw new FirestoreError(y, "Timestamp seconds out of range: " + t); + // This will break in the year 10,000. + if (t >= 253402300800) throw new FirestoreError(y, "Timestamp seconds out of range: " + t); + } + /** + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ toDate() { + return new Date(this.toMillis()); + } + /** + * Converts a `Timestamp` to a numeric timestamp (in milliseconds since + * epoch). This operation causes a loss of precision. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ toMillis() { + return 1e3 * this.seconds + this.nanoseconds / H; + } + _compareTo(t) { + return this.seconds === t.seconds ? __PRIVATE_primitiveComparator(this.nanoseconds, t.nanoseconds) : __PRIVATE_primitiveComparator(this.seconds, t.seconds); + } + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other - The `Timestamp` to compare against. + * @returns true if this `Timestamp` is equal to the provided one. + */ isEqual(t) { + return t.seconds === this.seconds && t.nanoseconds === this.nanoseconds; + } + /** Returns a textual representation of this `Timestamp`. */ toString() { + return "Timestamp(seconds=" + this.seconds + ", nanoseconds=" + this.nanoseconds + ")"; + } + /** + * Returns a JSON-serializable representation of this `Timestamp`. + */ toJSON() { + return { + type: Timestamp._jsonSchemaVersion, + seconds: this.seconds, + nanoseconds: this.nanoseconds + }; + } + /** + * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}. + */ static fromJSON(t) { + if (__PRIVATE_validateJSON(t, Timestamp._jsonSchema)) return new Timestamp(t.seconds, t.nanoseconds); + } + /** + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. + */ valueOf() { + // This method returns a string of the form . where + // is translated to have a non-negative value and both + // and are left-padded with zeroes to be a consistent length. + // Strings with this format then have a lexicographical ordering that matches + // the expected ordering. The translation is done to avoid having + // a leading negative sign (i.e. a leading '-' character) in its string + // representation, which would affect its lexicographical ordering. + const t = this.seconds - J; + // Note: Up to 12 decimal digits are required to represent all valid + // 'seconds' values. + return String(t).padStart(12, "0") + "." + String(this.nanoseconds).padStart(9, "0"); + } +} + +Timestamp._jsonSchemaVersion = "firestore/timestamp/1.0", Timestamp._jsonSchema = { + type: property("string", Timestamp._jsonSchemaVersion), + seconds: property("number"), + nanoseconds: property("number") +}; + +function __PRIVATE_isServerTimestamp(t) { + const e = (t?.mapValue?.fields || {}).__type__?.stringValue; + return "server_timestamp" === e; +} + +/** + * Returns the value of the field before this ServerTimestamp was set. + * + * Preserving the previous values allows the user to display the last resoled + * value until the backend responds with the timestamp. + */ function __PRIVATE_getPreviousValue(t) { + const e = t.mapValue.fields.__previous_value__; + return __PRIVATE_isServerTimestamp(e) ? __PRIVATE_getPreviousValue(e) : e; +} + +/** + * Returns the local time at which this timestamp was first set. + */ function __PRIVATE_getLocalWriteTime(t) { + const e = __PRIVATE_normalizeTimestamp(t.mapValue.fields.__local_write_time__.timestampValue); + return new Timestamp(e.seconds, e.nanos); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const Y = "__type__", Z = "__max__", X = { + fields: { + __type__: { + stringValue: Z + } + } +}, tt = "__vector__", et = "value"; + +/** Extracts the backend's type order for the provided value. */ +function __PRIVATE_typeOrder(t) { + return "nullValue" in t ? 0 /* TypeOrder.NullValue */ : "booleanValue" in t ? 1 /* TypeOrder.BooleanValue */ : "integerValue" in t || "doubleValue" in t ? 2 /* TypeOrder.NumberValue */ : "timestampValue" in t ? 3 /* TypeOrder.TimestampValue */ : "stringValue" in t ? 5 /* TypeOrder.StringValue */ : "bytesValue" in t ? 6 /* TypeOrder.BlobValue */ : "referenceValue" in t ? 7 /* TypeOrder.RefValue */ : "geoPointValue" in t ? 8 /* TypeOrder.GeoPointValue */ : "arrayValue" in t ? 9 /* TypeOrder.ArrayValue */ : "mapValue" in t ? __PRIVATE_isServerTimestamp(t) ? 4 /* TypeOrder.ServerTimestampValue */ : + /** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ + function __PRIVATE_isMaxValue(t) { + return (((t.mapValue || {}).fields || {}).__type__ || {}).stringValue === Z; + } + /** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Represents a bound of a query. + * + * The bound is specified with the given components representing a position and + * whether it's just before or just after the position (relative to whatever the + * query order is). + * + * The position represents a logical index position for a query. It's a prefix + * of values for the (potentially implicit) order by clauses of a query. + * + * Bound provides a function to determine whether a document comes before or + * after a bound. This is influenced by whether the position is just before or + * just after the provided values. + */ (t) ? 9007199254740991 /* TypeOrder.MaxValue */ : + /** Returns true if `value` is a VetorValue. */ + function __PRIVATE_isVectorValue(t) { + const e = (t?.mapValue?.fields || {})[Y]?.stringValue; + return e === tt; + } + /** Creates a deep copy of `source`. */ (t) ? 10 /* TypeOrder.VectorValue */ : 11 /* TypeOrder.ObjectValue */ : fail(28295, { + value: t + }); +} + +/** Tests `left` and `right` for equality based on the backend semantics. */ function __PRIVATE_valueEquals(t, e) { + if (t === e) return !0; + const r = __PRIVATE_typeOrder(t); + if (r !== __PRIVATE_typeOrder(e)) return !1; + switch (r) { + case 0 /* TypeOrder.NullValue */ : + case 9007199254740991 /* TypeOrder.MaxValue */ : + return !0; + + case 1 /* TypeOrder.BooleanValue */ : + return t.booleanValue === e.booleanValue; + + case 4 /* TypeOrder.ServerTimestampValue */ : + return __PRIVATE_getLocalWriteTime(t).isEqual(__PRIVATE_getLocalWriteTime(e)); + + case 3 /* TypeOrder.TimestampValue */ : + return function __PRIVATE_timestampEquals(t, e) { + if ("string" == typeof t.timestampValue && "string" == typeof e.timestampValue && t.timestampValue.length === e.timestampValue.length) + // Use string equality for ISO 8601 timestamps + return t.timestampValue === e.timestampValue; + const r = __PRIVATE_normalizeTimestamp(t.timestampValue), n = __PRIVATE_normalizeTimestamp(e.timestampValue); + return r.seconds === n.seconds && r.nanos === n.nanos; + }(t, e); + + case 5 /* TypeOrder.StringValue */ : + return t.stringValue === e.stringValue; + + case 6 /* TypeOrder.BlobValue */ : + return function __PRIVATE_blobEquals(t, e) { + return __PRIVATE_normalizeByteString(t.bytesValue).isEqual(__PRIVATE_normalizeByteString(e.bytesValue)); + }(t, e); + + case 7 /* TypeOrder.RefValue */ : + return t.referenceValue === e.referenceValue; + + case 8 /* TypeOrder.GeoPointValue */ : + return function __PRIVATE_geoPointEquals(t, e) { + return __PRIVATE_normalizeNumber(t.geoPointValue.latitude) === __PRIVATE_normalizeNumber(e.geoPointValue.latitude) && __PRIVATE_normalizeNumber(t.geoPointValue.longitude) === __PRIVATE_normalizeNumber(e.geoPointValue.longitude); + }(t, e); + + case 2 /* TypeOrder.NumberValue */ : + return function __PRIVATE_numberEquals(t, e) { + if ("integerValue" in t && "integerValue" in e) return __PRIVATE_normalizeNumber(t.integerValue) === __PRIVATE_normalizeNumber(e.integerValue); + if ("doubleValue" in t && "doubleValue" in e) { + const r = __PRIVATE_normalizeNumber(t.doubleValue), n = __PRIVATE_normalizeNumber(e.doubleValue); + return r === n ? __PRIVATE_isNegativeZero(r) === __PRIVATE_isNegativeZero(n) : isNaN(r) && isNaN(n); + } + return !1; + }(t, e); + + case 9 /* TypeOrder.ArrayValue */ : + return __PRIVATE_arrayEquals(t.arrayValue.values || [], e.arrayValue.values || [], __PRIVATE_valueEquals); + + case 10 /* TypeOrder.VectorValue */ : + case 11 /* TypeOrder.ObjectValue */ : + return function __PRIVATE_objectEquals(t, e) { + const r = t.mapValue.fields || {}, n = e.mapValue.fields || {}; + if (__PRIVATE_objectSize(r) !== __PRIVATE_objectSize(n)) return !1; + for (const t in r) if (r.hasOwnProperty(t) && (void 0 === n[t] || !__PRIVATE_valueEquals(r[t], n[t]))) return !1; + return !0; + } + /** Returns true if the ArrayValue contains the specified element. */ (t, e); + + default: + return fail(52216, { + left: t + }); + } +} + +function __PRIVATE_arrayValueContains(t, e) { + return void 0 !== (t.values || []).find((t => __PRIVATE_valueEquals(t, e))); +} + +function __PRIVATE_valueCompare(t, e) { + if (t === e) return 0; + const r = __PRIVATE_typeOrder(t), n = __PRIVATE_typeOrder(e); + if (r !== n) return __PRIVATE_primitiveComparator(r, n); + switch (r) { + case 0 /* TypeOrder.NullValue */ : + case 9007199254740991 /* TypeOrder.MaxValue */ : + return 0; + + case 1 /* TypeOrder.BooleanValue */ : + return __PRIVATE_primitiveComparator(t.booleanValue, e.booleanValue); + + case 2 /* TypeOrder.NumberValue */ : + return function __PRIVATE_compareNumbers(t, e) { + const r = __PRIVATE_normalizeNumber(t.integerValue || t.doubleValue), n = __PRIVATE_normalizeNumber(e.integerValue || e.doubleValue); + return r < n ? -1 : r > n ? 1 : r === n ? 0 : + // one or both are NaN. + isNaN(r) ? isNaN(n) ? 0 : -1 : 1; + }(t, e); + + case 3 /* TypeOrder.TimestampValue */ : + return __PRIVATE_compareTimestamps(t.timestampValue, e.timestampValue); + + case 4 /* TypeOrder.ServerTimestampValue */ : + return __PRIVATE_compareTimestamps(__PRIVATE_getLocalWriteTime(t), __PRIVATE_getLocalWriteTime(e)); + + case 5 /* TypeOrder.StringValue */ : + return __PRIVATE_compareUtf8Strings(t.stringValue, e.stringValue); + + case 6 /* TypeOrder.BlobValue */ : + return function __PRIVATE_compareBlobs(t, e) { + const r = __PRIVATE_normalizeByteString(t), n = __PRIVATE_normalizeByteString(e); + return r.compareTo(n); + }(t.bytesValue, e.bytesValue); + + case 7 /* TypeOrder.RefValue */ : + return function __PRIVATE_compareReferences(t, e) { + const r = t.split("/"), n = e.split("/"); + for (let t = 0; t < r.length && t < n.length; t++) { + const e = __PRIVATE_primitiveComparator(r[t], n[t]); + if (0 !== e) return e; + } + return __PRIVATE_primitiveComparator(r.length, n.length); + }(t.referenceValue, e.referenceValue); + + case 8 /* TypeOrder.GeoPointValue */ : + return function __PRIVATE_compareGeoPoints(t, e) { + const r = __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(t.latitude), __PRIVATE_normalizeNumber(e.latitude)); + if (0 !== r) return r; + return __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(t.longitude), __PRIVATE_normalizeNumber(e.longitude)); + }(t.geoPointValue, e.geoPointValue); + + case 9 /* TypeOrder.ArrayValue */ : + return __PRIVATE_compareArrays(t.arrayValue, e.arrayValue); + + case 10 /* TypeOrder.VectorValue */ : + return function __PRIVATE_compareVectors(t, e) { + const r = t.fields || {}, n = e.fields || {}, i = r[et]?.arrayValue, s = n[et]?.arrayValue, o = __PRIVATE_primitiveComparator(i?.values?.length || 0, s?.values?.length || 0); + if (0 !== o) return o; + return __PRIVATE_compareArrays(i, s); + }(t.mapValue, e.mapValue); + + case 11 /* TypeOrder.ObjectValue */ : + return function __PRIVATE_compareMaps(t, e) { + if (t === X && e === X) return 0; + if (t === X) return 1; + if (e === X) return -1; + const r = t.fields || {}, n = Object.keys(r), i = e.fields || {}, s = Object.keys(i); + // Even though MapValues are likely sorted correctly based on their insertion + // order (e.g. when received from the backend), local modifications can bring + // elements out of order. We need to re-sort the elements to ensure that + // canonical IDs are independent of insertion order. + n.sort(), s.sort(); + for (let t = 0; t < n.length && t < s.length; ++t) { + const e = __PRIVATE_compareUtf8Strings(n[t], s[t]); + if (0 !== e) return e; + const o = __PRIVATE_valueCompare(r[n[t]], i[s[t]]); + if (0 !== o) return o; + } + return __PRIVATE_primitiveComparator(n.length, s.length); + } + /** Returns a reference value for the provided database and key. */ (t.mapValue, e.mapValue); + + default: + throw fail(23264, { + C: r + }); + } +} + +function __PRIVATE_compareTimestamps(t, e) { + if ("string" == typeof t && "string" == typeof e && t.length === e.length) return __PRIVATE_primitiveComparator(t, e); + const r = __PRIVATE_normalizeTimestamp(t), n = __PRIVATE_normalizeTimestamp(e), i = __PRIVATE_primitiveComparator(r.seconds, n.seconds); + return 0 !== i ? i : __PRIVATE_primitiveComparator(r.nanos, n.nanos); +} + +function __PRIVATE_compareArrays(t, e) { + const r = t.values || [], n = e.values || []; + for (let t = 0; t < r.length && t < n.length; ++t) { + const e = __PRIVATE_valueCompare(r[t], n[t]); + if (e) return e; + } + return __PRIVATE_primitiveComparator(r.length, n.length); +} + +function __PRIVATE_refValue(t, e) { + return { + referenceValue: `projects/${t.projectId}/databases/${t.database}/documents/${e.path.canonicalString()}` + }; +} + +/** Returns true if `value` is an ArrayValue. */ function isArray(t) { + return !!t && "arrayValue" in t; +} + +/** Returns true if `value` is a NullValue. */ function __PRIVATE_isNullValue(t) { + return !!t && "nullValue" in t; +} + +/** Returns true if `value` is NaN. */ function __PRIVATE_isNanValue(t) { + return !!t && "doubleValue" in t && isNaN(Number(t.doubleValue)); +} + +/** Returns true if `value` is a MapValue. */ function __PRIVATE_isMapValue(t) { + return !!t && "mapValue" in t; +} + +function __PRIVATE_deepClone(t) { + if (t.geoPointValue) return { + geoPointValue: { + ...t.geoPointValue + } + }; + if (t.timestampValue && "object" == typeof t.timestampValue) return { + timestampValue: { + ...t.timestampValue + } + }; + if (t.mapValue) { + const e = { + mapValue: { + fields: {} + } + }; + return forEach(t.mapValue.fields, ((t, r) => e.mapValue.fields[t] = __PRIVATE_deepClone(r))), + e; + } + if (t.arrayValue) { + const e = { + arrayValue: { + values: [] + } + }; + for (let r = 0; r < (t.arrayValue.values || []).length; ++r) e.arrayValue.values[r] = __PRIVATE_deepClone(t.arrayValue.values[r]); + return e; + } + return { + ...t + }; +} + +class Bound { + constructor(t, e) { + this.position = t, this.inclusive = e; + } +} + +function __PRIVATE_boundEquals(t, e) { + if (null === t) return null === e; + if (null === e) return !1; + if (t.inclusive !== e.inclusive || t.position.length !== e.position.length) return !1; + for (let r = 0; r < t.position.length; r++) { + if (!__PRIVATE_valueEquals(t.position[r], e.position[r])) return !1; + } + return !0; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class Filter {} + +class FieldFilter extends Filter { + constructor(t, e, r) { + super(), this.field = t, this.op = e, this.value = r; + } + /** + * Creates a filter based on the provided arguments. + */ static create(t, e, r) { + return t.isKeyField() ? "in" /* Operator.IN */ === e || "not-in" /* Operator.NOT_IN */ === e ? this.createKeyFieldInFilter(t, e, r) : new __PRIVATE_KeyFieldFilter(t, e, r) : "array-contains" /* Operator.ARRAY_CONTAINS */ === e ? new __PRIVATE_ArrayContainsFilter(t, r) : "in" /* Operator.IN */ === e ? new __PRIVATE_InFilter(t, r) : "not-in" /* Operator.NOT_IN */ === e ? new __PRIVATE_NotInFilter(t, r) : "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === e ? new __PRIVATE_ArrayContainsAnyFilter(t, r) : new FieldFilter(t, e, r); + } + static createKeyFieldInFilter(t, e, r) { + return "in" /* Operator.IN */ === e ? new __PRIVATE_KeyFieldInFilter(t, r) : new __PRIVATE_KeyFieldNotInFilter(t, r); + } + matches(t) { + const e = t.data.field(this.field); + // Types do not have to match in NOT_EQUAL filters. + return "!=" /* Operator.NOT_EQUAL */ === this.op ? null !== e && void 0 === e.nullValue && this.matchesComparison(__PRIVATE_valueCompare(e, this.value)) : null !== e && __PRIVATE_typeOrder(this.value) === __PRIVATE_typeOrder(e) && this.matchesComparison(__PRIVATE_valueCompare(e, this.value)); + // Only compare types with matching backend order (such as double and int). + } + matchesComparison(t) { + switch (this.op) { + case "<" /* Operator.LESS_THAN */ : + return t < 0; + + case "<=" /* Operator.LESS_THAN_OR_EQUAL */ : + return t <= 0; + + case "==" /* Operator.EQUAL */ : + return 0 === t; + + case "!=" /* Operator.NOT_EQUAL */ : + return 0 !== t; + + case ">" /* Operator.GREATER_THAN */ : + return t > 0; + + case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ : + return t >= 0; + + default: + return fail(47266, { + operator: this.op + }); + } + } + isInequality() { + return [ "<" /* Operator.LESS_THAN */ , "<=" /* Operator.LESS_THAN_OR_EQUAL */ , ">" /* Operator.GREATER_THAN */ , ">=" /* Operator.GREATER_THAN_OR_EQUAL */ , "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ].indexOf(this.op) >= 0; + } + getFlattenedFilters() { + return [ this ]; + } + getFilters() { + return [ this ]; + } +} + +class CompositeFilter extends Filter { + constructor(t, e) { + super(), this.filters = t, this.op = e, this.N = null; + } + /** + * Creates a filter based on the provided arguments. + */ static create(t, e) { + return new CompositeFilter(t, e); + } + matches(t) { + return function __PRIVATE_compositeFilterIsConjunction(t) { + return "and" /* CompositeOperator.AND */ === t.op; + }(this) ? void 0 === this.filters.find((e => !e.matches(t))) : void 0 !== this.filters.find((e => e.matches(t))); + } + getFlattenedFilters() { + return null !== this.N || (this.N = this.filters.reduce(((t, e) => t.concat(e.getFlattenedFilters())), [])), + this.N; + } + // Returns a mutable copy of `this.filters` + getFilters() { + return Object.assign([], this.filters); + } +} + +function __PRIVATE_filterEquals(t, e) { + return t instanceof FieldFilter ? function __PRIVATE_fieldFilterEquals(t, e) { + return e instanceof FieldFilter && t.op === e.op && t.field.isEqual(e.field) && __PRIVATE_valueEquals(t.value, e.value); + }(t, e) : t instanceof CompositeFilter ? function __PRIVATE_compositeFilterEquals(t, e) { + if (e instanceof CompositeFilter && t.op === e.op && t.filters.length === e.filters.length) { + return t.filters.reduce(((t, r, n) => t && __PRIVATE_filterEquals(r, e.filters[n])), !0); + } + return !1; + } + /** Filter that matches on key fields (i.e. '__name__'). */ (t, e) : void fail(19439); +} + +class __PRIVATE_KeyFieldFilter extends FieldFilter { + constructor(t, e, r) { + super(t, e, r), this.key = DocumentKey.fromName(r.referenceValue); + } + matches(t) { + const e = DocumentKey.comparator(t.key, this.key); + return this.matchesComparison(e); + } +} + +/** Filter that matches on key fields within an array. */ class __PRIVATE_KeyFieldInFilter extends FieldFilter { + constructor(t, e) { + super(t, "in" /* Operator.IN */ , e), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue("in" /* Operator.IN */ , e); + } + matches(t) { + return this.keys.some((e => e.isEqual(t.key))); + } +} + +/** Filter that matches on key fields not present within an array. */ class __PRIVATE_KeyFieldNotInFilter extends FieldFilter { + constructor(t, e) { + super(t, "not-in" /* Operator.NOT_IN */ , e), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue("not-in" /* Operator.NOT_IN */ , e); + } + matches(t) { + return !this.keys.some((e => e.isEqual(t.key))); + } +} + +function __PRIVATE_extractDocumentKeysFromArrayValue(t, e) { + return (e.arrayValue?.values || []).map((t => DocumentKey.fromName(t.referenceValue))); +} + +/** A Filter that implements the array-contains operator. */ class __PRIVATE_ArrayContainsFilter extends FieldFilter { + constructor(t, e) { + super(t, "array-contains" /* Operator.ARRAY_CONTAINS */ , e); + } + matches(t) { + const e = t.data.field(this.field); + return isArray(e) && __PRIVATE_arrayValueContains(e.arrayValue, this.value); + } +} + +/** A Filter that implements the IN operator. */ class __PRIVATE_InFilter extends FieldFilter { + constructor(t, e) { + super(t, "in" /* Operator.IN */ , e); + } + matches(t) { + const e = t.data.field(this.field); + return null !== e && __PRIVATE_arrayValueContains(this.value.arrayValue, e); + } +} + +/** A Filter that implements the not-in operator. */ class __PRIVATE_NotInFilter extends FieldFilter { + constructor(t, e) { + super(t, "not-in" /* Operator.NOT_IN */ , e); + } + matches(t) { + if (__PRIVATE_arrayValueContains(this.value.arrayValue, { + nullValue: "NULL_VALUE" + })) return !1; + const e = t.data.field(this.field); + return null !== e && void 0 === e.nullValue && !__PRIVATE_arrayValueContains(this.value.arrayValue, e); + } +} + +/** A Filter that implements the array-contains-any operator. */ class __PRIVATE_ArrayContainsAnyFilter extends FieldFilter { + constructor(t, e) { + super(t, "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , e); + } + matches(t) { + const e = t.data.field(this.field); + return !(!isArray(e) || !e.arrayValue.values) && e.arrayValue.values.some((t => __PRIVATE_arrayValueContains(this.value.arrayValue, t))); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An ordering on a field, in some Direction. Direction defaults to ASCENDING. + */ class OrderBy { + constructor(t, e = "asc" /* Direction.ASCENDING */) { + this.field = t, this.dir = e; + } +} + +function __PRIVATE_orderByEquals(t, e) { + return t.dir === e.dir && t.field.isEqual(e.field); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A version of a document in Firestore. This corresponds to the version + * timestamp, such as update_time or read_time. + */ class SnapshotVersion { + static fromTimestamp(t) { + return new SnapshotVersion(t); + } + static min() { + return new SnapshotVersion(new Timestamp(0, 0)); + } + static max() { + return new SnapshotVersion(new Timestamp(253402300799, 999999999)); + } + constructor(t) { + this.timestamp = t; + } + compareTo(t) { + return this.timestamp._compareTo(t.timestamp); + } + isEqual(t) { + return this.timestamp.isEqual(t.timestamp); + } + /** Returns a number representation of the version for use in spec tests. */ toMicroseconds() { + // Convert to microseconds. + return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3; + } + toString() { + return "SnapshotVersion(" + this.timestamp.toString() + ")"; + } + toTimestamp() { + return this.timestamp; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// An immutable sorted map implementation, based on a Left-leaning Red-Black +// tree. +class SortedMap { + constructor(t, e) { + this.comparator = t, this.root = e || LLRBNode.EMPTY; + } + // Returns a copy of the map, with the specified key/value added or replaced. + insert(t, e) { + return new SortedMap(this.comparator, this.root.insert(t, e, this.comparator).copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns a copy of the map, with the specified key removed. + remove(t) { + return new SortedMap(this.comparator, this.root.remove(t, this.comparator).copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns the value of the node with the given key, or null. + get(t) { + let e = this.root; + for (;!e.isEmpty(); ) { + const r = this.comparator(t, e.key); + if (0 === r) return e.value; + r < 0 ? e = e.left : r > 0 && (e = e.right); + } + return null; + } + // Returns the index of the element in this sorted map, or -1 if it doesn't + // exist. + indexOf(t) { + // Number of nodes that were pruned when descending right + let e = 0, r = this.root; + for (;!r.isEmpty(); ) { + const n = this.comparator(t, r.key); + if (0 === n) return e + r.left.size; + n < 0 ? r = r.left : ( + // Count all nodes left of the node plus the node itself + e += r.left.size + 1, r = r.right); + } + // Node not found + return -1; + } + isEmpty() { + return this.root.isEmpty(); + } + // Returns the total number of nodes in the map. + get size() { + return this.root.size; + } + // Returns the minimum key in the map. + minKey() { + return this.root.minKey(); + } + // Returns the maximum key in the map. + maxKey() { + return this.root.maxKey(); + } + // Traverses the map in key order and calls the specified action function + // for each key/value pair. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(t) { + return this.root.inorderTraversal(t); + } + forEach(t) { + this.inorderTraversal(((e, r) => (t(e, r), !1))); + } + toString() { + const t = []; + return this.inorderTraversal(((e, r) => (t.push(`${e}:${r}`), !1))), `{${t.join(", ")}}`; + } + // Traverses the map in reverse key order and calls the specified action + // function for each key/value pair. If action returns true, traversal is + // aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(t) { + return this.root.reverseTraversal(t); + } + // Returns an iterator over the SortedMap. + getIterator() { + return new SortedMapIterator(this.root, null, this.comparator, !1); + } + getIteratorFrom(t) { + return new SortedMapIterator(this.root, t, this.comparator, !1); + } + getReverseIterator() { + return new SortedMapIterator(this.root, null, this.comparator, !0); + } + getReverseIteratorFrom(t) { + return new SortedMapIterator(this.root, t, this.comparator, !0); + } +} + + // end SortedMap +// An iterator over an LLRBNode. +class SortedMapIterator { + constructor(t, e, r, n) { + this.isReverse = n, this.nodeStack = []; + let i = 1; + for (;!t.isEmpty(); ) if (i = e ? r(t.key, e) : 1, + // flip the comparison if we're going in reverse + e && n && (i *= -1), i < 0) + // This node is less than our start key. ignore it + t = this.isReverse ? t.left : t.right; else { + if (0 === i) { + // This node is exactly equal to our start key. Push it on the stack, + // but stop iterating; + this.nodeStack.push(t); + break; + } + // This node is greater than our start key, add it to the stack and move + // to the next one + this.nodeStack.push(t), t = this.isReverse ? t.right : t.left; + } + } + getNext() { + let t = this.nodeStack.pop(); + const e = { + key: t.key, + value: t.value + }; + if (this.isReverse) for (t = t.left; !t.isEmpty(); ) this.nodeStack.push(t), t = t.right; else for (t = t.right; !t.isEmpty(); ) this.nodeStack.push(t), + t = t.left; + return e; + } + hasNext() { + return this.nodeStack.length > 0; + } + peek() { + if (0 === this.nodeStack.length) return null; + const t = this.nodeStack[this.nodeStack.length - 1]; + return { + key: t.key, + value: t.value + }; + } +} + + // end SortedMapIterator +// Represents a node in a Left-leaning Red-Black tree. +class LLRBNode { + constructor(t, e, r, n, i) { + this.key = t, this.value = e, this.color = null != r ? r : LLRBNode.RED, this.left = null != n ? n : LLRBNode.EMPTY, + this.right = null != i ? i : LLRBNode.EMPTY, this.size = this.left.size + 1 + this.right.size; + } + // Returns a copy of the current node, optionally replacing pieces of it. + copy(t, e, r, n, i) { + return new LLRBNode(null != t ? t : this.key, null != e ? e : this.value, null != r ? r : this.color, null != n ? n : this.left, null != i ? i : this.right); + } + isEmpty() { + return !1; + } + // Traverses the tree in key order and calls the specified action function + // for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(t) { + return this.left.inorderTraversal(t) || t(this.key, this.value) || this.right.inorderTraversal(t); + } + // Traverses the tree in reverse key order and calls the specified action + // function for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(t) { + return this.right.reverseTraversal(t) || t(this.key, this.value) || this.left.reverseTraversal(t); + } + // Returns the minimum node in the tree. + min() { + return this.left.isEmpty() ? this : this.left.min(); + } + // Returns the maximum key in the tree. + minKey() { + return this.min().key; + } + // Returns the maximum key in the tree. + maxKey() { + return this.right.isEmpty() ? this.key : this.right.maxKey(); + } + // Returns new tree, with the key/value added. + insert(t, e, r) { + let n = this; + const i = r(t, n.key); + return n = i < 0 ? n.copy(null, null, null, n.left.insert(t, e, r), null) : 0 === i ? n.copy(null, e, null, null, null) : n.copy(null, null, null, null, n.right.insert(t, e, r)), + n.fixUp(); + } + removeMin() { + if (this.left.isEmpty()) return LLRBNode.EMPTY; + let t = this; + return t.left.isRed() || t.left.left.isRed() || (t = t.moveRedLeft()), t = t.copy(null, null, null, t.left.removeMin(), null), + t.fixUp(); + } + // Returns new tree, with the specified item removed. + remove(t, e) { + let r, n = this; + if (e(t, n.key) < 0) n.left.isEmpty() || n.left.isRed() || n.left.left.isRed() || (n = n.moveRedLeft()), + n = n.copy(null, null, null, n.left.remove(t, e), null); else { + if (n.left.isRed() && (n = n.rotateRight()), n.right.isEmpty() || n.right.isRed() || n.right.left.isRed() || (n = n.moveRedRight()), + 0 === e(t, n.key)) { + if (n.right.isEmpty()) return LLRBNode.EMPTY; + r = n.right.min(), n = n.copy(r.key, r.value, null, null, n.right.removeMin()); + } + n = n.copy(null, null, null, null, n.right.remove(t, e)); + } + return n.fixUp(); + } + isRed() { + return this.color; + } + // Returns new tree after performing any needed rotations. + fixUp() { + let t = this; + return t.right.isRed() && !t.left.isRed() && (t = t.rotateLeft()), t.left.isRed() && t.left.left.isRed() && (t = t.rotateRight()), + t.left.isRed() && t.right.isRed() && (t = t.colorFlip()), t; + } + moveRedLeft() { + let t = this.colorFlip(); + return t.right.left.isRed() && (t = t.copy(null, null, null, null, t.right.rotateRight()), + t = t.rotateLeft(), t = t.colorFlip()), t; + } + moveRedRight() { + let t = this.colorFlip(); + return t.left.left.isRed() && (t = t.rotateRight(), t = t.colorFlip()), t; + } + rotateLeft() { + const t = this.copy(null, null, LLRBNode.RED, null, this.right.left); + return this.right.copy(null, null, this.color, t, null); + } + rotateRight() { + const t = this.copy(null, null, LLRBNode.RED, this.left.right, null); + return this.left.copy(null, null, this.color, null, t); + } + colorFlip() { + const t = this.left.copy(null, null, !this.left.color, null, null), e = this.right.copy(null, null, !this.right.color, null, null); + return this.copy(null, null, !this.color, t, e); + } + // For testing. + checkMaxDepth() { + const t = this.check(); + return Math.pow(2, t) <= this.size + 1; + } + // In a balanced RB tree, the black-depth (number of black nodes) from root to + // leaves is equal on both sides. This function verifies that or asserts. + check() { + if (this.isRed() && this.left.isRed()) throw fail(43730, { + key: this.key, + value: this.value + }); + if (this.right.isRed()) throw fail(14113, { + key: this.key, + value: this.value + }); + const t = this.left.check(); + if (t !== this.right.check()) throw fail(27949); + return t + (this.isRed() ? 0 : 1); + } +} + + // end LLRBNode +// Empty node is shared between all LLRB trees. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +LLRBNode.EMPTY = null, LLRBNode.RED = !0, LLRBNode.BLACK = !1; + +// end LLRBEmptyNode +LLRBNode.EMPTY = new +// Represents an empty node (a leaf node in the Red-Black Tree). +class LLRBEmptyNode { + constructor() { + this.size = 0; + } + get key() { + throw fail(57766); + } + get value() { + throw fail(16141); + } + get color() { + throw fail(16727); + } + get left() { + throw fail(29726); + } + get right() { + throw fail(36894); + } + // Returns a copy of the current node. + copy(t, e, r, n, i) { + return this; + } + // Returns a copy of the tree, with the specified key/value added. + insert(t, e, r) { + return new LLRBNode(t, e); + } + // Returns a copy of the tree, with the specified key removed. + remove(t, e) { + return this; + } + isEmpty() { + return !0; + } + inorderTraversal(t) { + return !1; + } + reverseTraversal(t) { + return !1; + } + minKey() { + return null; + } + maxKey() { + return null; + } + isRed() { + return !1; + } + // For testing. + checkMaxDepth() { + return !0; + } + check() { + return 0; + } +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * SortedSet is an immutable (copy-on-write) collection that holds elements + * in order specified by the provided comparator. + * + * NOTE: if provided comparator returns 0 for two elements, we consider them to + * be equal! + */ +class SortedSet { + constructor(t) { + this.comparator = t, this.data = new SortedMap(this.comparator); + } + has(t) { + return null !== this.data.get(t); + } + first() { + return this.data.minKey(); + } + last() { + return this.data.maxKey(); + } + get size() { + return this.data.size; + } + indexOf(t) { + return this.data.indexOf(t); + } + /** Iterates elements in order defined by "comparator" */ forEach(t) { + this.data.inorderTraversal(((e, r) => (t(e), !1))); + } + /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ forEachInRange(t, e) { + const r = this.data.getIteratorFrom(t[0]); + for (;r.hasNext(); ) { + const n = r.getNext(); + if (this.comparator(n.key, t[1]) >= 0) return; + e(n.key); + } + } + /** + * Iterates over `elem`s such that: start <= elem until false is returned. + */ forEachWhile(t, e) { + let r; + for (r = void 0 !== e ? this.data.getIteratorFrom(e) : this.data.getIterator(); r.hasNext(); ) { + if (!t(r.getNext().key)) return; + } + } + /** Finds the least element greater than or equal to `elem`. */ firstAfterOrEqual(t) { + const e = this.data.getIteratorFrom(t); + return e.hasNext() ? e.getNext().key : null; + } + getIterator() { + return new SortedSetIterator(this.data.getIterator()); + } + getIteratorFrom(t) { + return new SortedSetIterator(this.data.getIteratorFrom(t)); + } + /** Inserts or updates an element */ add(t) { + return this.copy(this.data.remove(t).insert(t, !0)); + } + /** Deletes an element */ delete(t) { + return this.has(t) ? this.copy(this.data.remove(t)) : this; + } + isEmpty() { + return this.data.isEmpty(); + } + unionWith(t) { + let e = this; + // Make sure `result` always refers to the larger one of the two sets. + return e.size < t.size && (e = t, t = this), t.forEach((t => { + e = e.add(t); + })), e; + } + isEqual(t) { + if (!(t instanceof SortedSet)) return !1; + if (this.size !== t.size) return !1; + const e = this.data.getIterator(), r = t.data.getIterator(); + for (;e.hasNext(); ) { + const t = e.getNext().key, n = r.getNext().key; + if (0 !== this.comparator(t, n)) return !1; + } + return !0; + } + toArray() { + const t = []; + return this.forEach((e => { + t.push(e); + })), t; + } + toString() { + const t = []; + return this.forEach((e => t.push(e))), "SortedSet(" + t.toString() + ")"; + } + copy(t) { + const e = new SortedSet(this.comparator); + return e.data = t, e; + } +} + +class SortedSetIterator { + constructor(t) { + this.iter = t; + } + getNext() { + return this.iter.getNext().key; + } + hasNext() { + return this.iter.hasNext(); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provides a set of fields that can be used to partially patch a document. + * FieldMask is used in conjunction with ObjectValue. + * Examples: + * foo - Overwrites foo entirely with the provided value. If foo is not + * present in the companion ObjectValue, the field is deleted. + * foo.bar - Overwrites only the field bar of the object foo. + * If foo is not an object, foo is replaced with an object + * containing foo + */ class FieldMask { + constructor(t) { + this.fields = t, + // TODO(dimond): validation of FieldMask + // Sort the field mask to support `FieldMask.isEqual()` and assert below. + t.sort(FieldPath$1.comparator); + } + static empty() { + return new FieldMask([]); + } + /** + * Returns a new FieldMask object that is the result of adding all the given + * fields paths to this field mask. + */ unionWith(t) { + let e = new SortedSet(FieldPath$1.comparator); + for (const t of this.fields) e = e.add(t); + for (const r of t) e = e.add(r); + return new FieldMask(e.toArray()); + } + /** + * Verifies that `fieldPath` is included by at least one field in this field + * mask. + * + * This is an O(n) operation, where `n` is the size of the field mask. + */ covers(t) { + for (const e of this.fields) if (e.isPrefixOf(t)) return !0; + return !1; + } + isEqual(t) { + return __PRIVATE_arrayEquals(this.fields, t.fields, ((t, e) => t.isEqual(e))); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An ObjectValue represents a MapValue in the Firestore Proto and offers the + * ability to add and remove fields (via the ObjectValueBuilder). + */ class ObjectValue { + constructor(t) { + this.value = t; + } + static empty() { + return new ObjectValue({ + mapValue: {} + }); + } + /** + * Returns the value at the given path or null. + * + * @param path - the path to search + * @returns The value at the path or null if the path is not set. + */ field(t) { + if (t.isEmpty()) return this.value; + { + let e = this.value; + for (let r = 0; r < t.length - 1; ++r) if (e = (e.mapValue.fields || {})[t.get(r)], + !__PRIVATE_isMapValue(e)) return null; + return e = (e.mapValue.fields || {})[t.lastSegment()], e || null; + } + } + /** + * Sets the field to the provided value. + * + * @param path - The field path to set. + * @param value - The value to set. + */ set(t, e) { + this.getFieldsMap(t.popLast())[t.lastSegment()] = __PRIVATE_deepClone(e); + } + /** + * Sets the provided fields to the provided values. + * + * @param data - A map of fields to values (or null for deletes). + */ setAll(t) { + let e = FieldPath$1.emptyPath(), r = {}, n = []; + t.forEach(((t, i) => { + if (!e.isImmediateParentOf(i)) { + // Insert the accumulated changes at this parent location + const t = this.getFieldsMap(e); + this.applyChanges(t, r, n), r = {}, n = [], e = i.popLast(); + } + t ? r[i.lastSegment()] = __PRIVATE_deepClone(t) : n.push(i.lastSegment()); + })); + const i = this.getFieldsMap(e); + this.applyChanges(i, r, n); + } + /** + * Removes the field at the specified path. If there is no field at the + * specified path, nothing is changed. + * + * @param path - The field path to remove. + */ delete(t) { + const e = this.field(t.popLast()); + __PRIVATE_isMapValue(e) && e.mapValue.fields && delete e.mapValue.fields[t.lastSegment()]; + } + isEqual(t) { + return __PRIVATE_valueEquals(this.value, t.value); + } + /** + * Returns the map that contains the leaf element of `path`. If the parent + * entry does not yet exist, or if it is not a map, a new map will be created. + */ getFieldsMap(t) { + let e = this.value; + e.mapValue.fields || (e.mapValue = { + fields: {} + }); + for (let r = 0; r < t.length; ++r) { + let n = e.mapValue.fields[t.get(r)]; + __PRIVATE_isMapValue(n) && n.mapValue.fields || (n = { + mapValue: { + fields: {} + } + }, e.mapValue.fields[t.get(r)] = n), e = n; + } + return e.mapValue.fields; + } + /** + * Modifies `fieldsMap` by adding, replacing or deleting the specified + * entries. + */ applyChanges(t, e, r) { + forEach(e, ((e, r) => t[e] = r)); + for (const e of r) delete t[e]; + } + clone() { + return new ObjectValue(__PRIVATE_deepClone(this.value)); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a document in Firestore with a key, version, data and whether it + * has local mutations applied to it. + * + * Documents can transition between states via `convertToFoundDocument()`, + * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does + * not transition to one of these states even after all mutations have been + * applied, `isValidDocument()` returns false and the document should be removed + * from all views. + */ class MutableDocument { + constructor(t, e, r, n, i, s, o) { + this.key = t, this.documentType = e, this.version = r, this.readTime = n, this.createTime = i, + this.data = s, this.documentState = o; + } + /** + * Creates a document with no known version or data, but which can serve as + * base document for mutations. + */ static newInvalidDocument(t) { + return new MutableDocument(t, 0 /* DocumentType.INVALID */ , + /* version */ SnapshotVersion.min(), + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist with the given data at the + * given version. + */ static newFoundDocument(t, e, r, n) { + return new MutableDocument(t, 1 /* DocumentType.FOUND_DOCUMENT */ , + /* version */ e, + /* readTime */ SnapshotVersion.min(), + /* createTime */ r, n, 0 /* DocumentState.SYNCED */); + } + /** Creates a new document that is known to not exist at the given version. */ static newNoDocument(t, e) { + return new MutableDocument(t, 2 /* DocumentType.NO_DOCUMENT */ , + /* version */ e, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist at the given version but + * whose data is not known (e.g. a document that was updated without a known + * base document). + */ static newUnknownDocument(t, e) { + return new MutableDocument(t, 3 /* DocumentType.UNKNOWN_DOCUMENT */ , + /* version */ e, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */); + } + /** + * Changes the document type to indicate that it exists and that its version + * and data are known. + */ convertToFoundDocument(t, e) { + // If a document is switching state from being an invalid or deleted + // document to a valid (FOUND_DOCUMENT) document, either due to receiving an + // update from Watch or due to applying a local set mutation on top + // of a deleted document, our best guess about its createTime would be the + // version at which the document transitioned to a FOUND_DOCUMENT. + return !this.createTime.isEqual(SnapshotVersion.min()) || 2 /* DocumentType.NO_DOCUMENT */ !== this.documentType && 0 /* DocumentType.INVALID */ !== this.documentType || (this.createTime = t), + this.version = t, this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */ , this.data = e, + this.documentState = 0 /* DocumentState.SYNCED */ , this; + } + /** + * Changes the document type to indicate that it doesn't exist at the given + * version. + */ convertToNoDocument(t) { + return this.version = t, this.documentType = 2 /* DocumentType.NO_DOCUMENT */ , + this.data = ObjectValue.empty(), this.documentState = 0 /* DocumentState.SYNCED */ , + this; + } + /** + * Changes the document type to indicate that it exists at a given version but + * that its data is not known (e.g. a document that was updated without a known + * base document). + */ convertToUnknownDocument(t) { + return this.version = t, this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */ , + this.data = ObjectValue.empty(), this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , + this; + } + setHasCommittedMutations() { + return this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , this; + } + setHasLocalMutations() { + return this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ , this.version = SnapshotVersion.min(), + this; + } + setReadTime(t) { + return this.readTime = t, this; + } + get hasLocalMutations() { + return 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ === this.documentState; + } + get hasCommittedMutations() { + return 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ === this.documentState; + } + get hasPendingWrites() { + return this.hasLocalMutations || this.hasCommittedMutations; + } + isValidDocument() { + return 0 /* DocumentType.INVALID */ !== this.documentType; + } + isFoundDocument() { + return 1 /* DocumentType.FOUND_DOCUMENT */ === this.documentType; + } + isNoDocument() { + return 2 /* DocumentType.NO_DOCUMENT */ === this.documentType; + } + isUnknownDocument() { + return 3 /* DocumentType.UNKNOWN_DOCUMENT */ === this.documentType; + } + isEqual(t) { + return t instanceof MutableDocument && this.key.isEqual(t.key) && this.version.isEqual(t.version) && this.documentType === t.documentType && this.documentState === t.documentState && this.data.isEqual(t.data); + } + mutableCopy() { + return new MutableDocument(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState); + } + toString() { + return `Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`; + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Visible for testing +class __PRIVATE_TargetImpl { + constructor(t, e = null, r = [], n = [], i = null, s = null, o = null) { + this.path = t, this.collectionGroup = e, this.orderBy = r, this.filters = n, this.limit = i, + this.startAt = s, this.endAt = o, this.O = null; + } +} + +/** + * Initializes a Target with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + * + * NOTE: you should always construct `Target` from `Query.toTarget` instead of + * using this factory method, because `Query` provides an implicit `orderBy` + * property. + */ function __PRIVATE_newTarget(t, e = null, r = [], n = [], i = null, s = null, o = null) { + return new __PRIVATE_TargetImpl(t, e, r, n, i, s, o); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Query encapsulates all the query attributes we support in the SDK. It can + * be run against the LocalStore, as well as be converted to a `Target` to + * query the RemoteStore results. + * + * Visible for testing. + */ +class __PRIVATE_QueryImpl { + /** + * Initializes a Query with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + */ + constructor(t, e = null, r = [], n = [], i = null, s = "F" /* LimitType.First */ , o = null, a = null) { + this.path = t, this.collectionGroup = e, this.explicitOrderBy = r, this.filters = n, + this.limit = i, this.limitType = s, this.startAt = o, this.endAt = a, this.q = null, + // The corresponding `Target` of this `Query` instance, for use with + // non-aggregate queries. + this.B = null, + // The corresponding `Target` of this `Query` instance, for use with + // aggregate queries. Unlike targets for non-aggregate queries, + // aggregate query targets do not contain normalized order-bys, they only + // contain explicit order-bys. + this.$ = null, this.startAt, this.endAt; + } +} + +/** Creates a new Query for a query that matches all documents at `path` */ +/** + * Returns whether the query matches a collection group rather than a specific + * collection. + */ +function __PRIVATE_isCollectionGroupQuery(t) { + return null !== t.collectionGroup; +} + +/** + * Returns the normalized order-by constraint that is used to execute the Query, + * which can be different from the order-by constraints the user provided (e.g. + * the SDK and backend always orders by `__name__`). The normalized order-by + * includes implicit order-bys in addition to the explicit user provided + * order-bys. + */ function __PRIVATE_queryNormalizedOrderBy(t) { + const e = __PRIVATE_debugCast(t); + if (null === e.q) { + e.q = []; + const t = new Set; + // Any explicit order by fields should be added as is. + for (const r of e.explicitOrderBy) e.q.push(r), t.add(r.field.canonicalString()); + // The order of the implicit ordering always matches the last explicit order by. + const r = e.explicitOrderBy.length > 0 ? e.explicitOrderBy[e.explicitOrderBy.length - 1].dir : "asc" /* Direction.ASCENDING */ , n = + // Returns the sorted set of inequality filter fields used in this query. + function __PRIVATE_getInequalityFilterFields(t) { + let e = new SortedSet(FieldPath$1.comparator); + return t.filters.forEach((t => { + t.getFlattenedFilters().forEach((t => { + t.isInequality() && (e = e.add(t.field)); + })); + })), e; + } + /** + * Creates a new Query for a collection group query that matches all documents + * within the provided collection group. + */ (e); + // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical + // order. When there are multiple inequality filters on the same field, the field should be added + // only once. + // Note: `SortedSet` sorts the key field before other fields. However, we want the key + // field to be sorted last. + n.forEach((n => { + t.has(n.canonicalString()) || n.isKeyField() || e.q.push(new OrderBy(n, r)); + })), + // Add the document key field to the last if it is not explicitly ordered. + t.has(FieldPath$1.keyField().canonicalString()) || e.q.push(new OrderBy(FieldPath$1.keyField(), r)); + } + return e.q; +} + +/** + * Converts this `Query` instance to its corresponding `Target` representation. + */ function __PRIVATE_queryToTarget(t) { + const e = __PRIVATE_debugCast(t); + return e.B || (e.B = __PRIVATE__queryToTarget(e, __PRIVATE_queryNormalizedOrderBy(t))), + e.B; +} + +/** + * Converts this `Query` instance to its corresponding `Target` representation, + * for use within an aggregate query. Unlike targets for non-aggregate queries, + * aggregate query targets do not contain normalized order-bys, they only + * contain explicit order-bys. + */ function __PRIVATE__queryToTarget(t, e) { + if ("F" /* LimitType.First */ === t.limitType) return __PRIVATE_newTarget(t.path, t.collectionGroup, e, t.filters, t.limit, t.startAt, t.endAt); + { + // Flip the orderBy directions since we want the last results + e = e.map((t => { + const e = "desc" /* Direction.DESCENDING */ === t.dir ? "asc" /* Direction.ASCENDING */ : "desc" /* Direction.DESCENDING */; + return new OrderBy(t.field, e); + })); + // We need to swap the cursors to match the now-flipped query ordering. + const r = t.endAt ? new Bound(t.endAt.position, t.endAt.inclusive) : null, n = t.startAt ? new Bound(t.startAt.position, t.startAt.inclusive) : null; + // Now return as a LimitType.First query. + return __PRIVATE_newTarget(t.path, t.collectionGroup, e, t.filters, t.limit, r, n); + } +} + +function __PRIVATE_queryWithAddedFilter(t, e) { + const r = t.filters.concat([ e ]); + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, t.explicitOrderBy.slice(), r, t.limit, t.limitType, t.startAt, t.endAt); +} + +function __PRIVATE_queryEquals(t, e) { + return function __PRIVATE_targetEquals(t, e) { + if (t.limit !== e.limit) return !1; + if (t.orderBy.length !== e.orderBy.length) return !1; + for (let r = 0; r < t.orderBy.length; r++) if (!__PRIVATE_orderByEquals(t.orderBy[r], e.orderBy[r])) return !1; + if (t.filters.length !== e.filters.length) return !1; + for (let r = 0; r < t.filters.length; r++) if (!__PRIVATE_filterEquals(t.filters[r], e.filters[r])) return !1; + return t.collectionGroup === e.collectionGroup && !!t.path.isEqual(e.path) && !!__PRIVATE_boundEquals(t.startAt, e.startAt) && __PRIVATE_boundEquals(t.endAt, e.endAt); + }(__PRIVATE_queryToTarget(t), __PRIVATE_queryToTarget(e)) && t.limitType === e.limitType; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns an DoubleValue for `value` that is encoded based the serializer's + * `useProto3Json` setting. + */ function __PRIVATE_toDouble(t, e) { + if (t.useProto3Json) { + if (isNaN(e)) return { + doubleValue: "NaN" + }; + if (e === 1 / 0) return { + doubleValue: "Infinity" + }; + if (e === -1 / 0) return { + doubleValue: "-Infinity" + }; + } + return { + doubleValue: __PRIVATE_isNegativeZero(e) ? "-0" : e + }; +} + +/** + * Returns an IntegerValue for `value`. + */ +/** + * Returns a value for a number that's appropriate to put into a proto. + * The return value is an IntegerValue if it can safely represent the value, + * otherwise a DoubleValue is returned. + */ +function toNumber(t, e) { + return function isSafeInteger(t) { + return "number" == typeof t && Number.isInteger(t) && !__PRIVATE_isNegativeZero(t) && t <= Number.MAX_SAFE_INTEGER && t >= Number.MIN_SAFE_INTEGER; + }(e) ? function __PRIVATE_toInteger(t) { + return { + integerValue: "" + t + }; + }(e) : __PRIVATE_toDouble(t, e); +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Used to represent a field transform on a mutation. */ class TransformOperation { + constructor() { + // Make sure that the structural type of `TransformOperation` is unique. + // See https://github.com/microsoft/TypeScript/issues/5451 + this._ = void 0; + } +} + +/** Transforms a value into a server-generated timestamp. */ class __PRIVATE_ServerTimestampTransform extends TransformOperation {} + +/** Transforms an array value via a union operation. */ class __PRIVATE_ArrayUnionTransformOperation extends TransformOperation { + constructor(t) { + super(), this.elements = t; + } +} + +/** Transforms an array value via a remove operation. */ class __PRIVATE_ArrayRemoveTransformOperation extends TransformOperation { + constructor(t) { + super(), this.elements = t; + } +} + +/** + * Implements the backend semantics for locally computed NUMERIC_ADD (increment) + * transforms. Converts all field values to integers or doubles, but unlike the + * backend does not cap integer values at 2^63. Instead, JavaScript number + * arithmetic is used and precision loss can occur for values greater than 2^53. + */ class __PRIVATE_NumericIncrementTransformOperation extends TransformOperation { + constructor(t, e) { + super(), this.serializer = t, this.k = e; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** A field path and the TransformOperation to perform upon it. */ class FieldTransform { + constructor(t, e) { + this.field = t, this.transform = e; + } +} + +/** + * Encodes a precondition for a mutation. This follows the model that the + * backend accepts with the special case of an explicit "empty" precondition + * (meaning no precondition). + */ class Precondition { + constructor(t, e) { + this.updateTime = t, this.exists = e; + } + /** Creates a new empty Precondition. */ static none() { + return new Precondition; + } + /** Creates a new Precondition with an exists flag. */ static exists(t) { + return new Precondition(void 0, t); + } + /** Creates a new Precondition based on a version a document exists at. */ static updateTime(t) { + return new Precondition(t); + } + /** Returns whether this Precondition is empty. */ get isNone() { + return void 0 === this.updateTime && void 0 === this.exists; + } + isEqual(t) { + return this.exists === t.exists && (this.updateTime ? !!t.updateTime && this.updateTime.isEqual(t.updateTime) : !t.updateTime); + } +} + +/** + * A mutation describes a self-contained change to a document. Mutations can + * create, replace, delete, and update subsets of documents. + * + * Mutations not only act on the value of the document but also its version. + * + * For local mutations (mutations that haven't been committed yet), we preserve + * the existing version for Set and Patch mutations. For Delete mutations, we + * reset the version to 0. + * + * Here's the expected transition table. + * + * MUTATION APPLIED TO RESULTS IN + * + * SetMutation Document(v3) Document(v3) + * SetMutation NoDocument(v3) Document(v0) + * SetMutation InvalidDocument(v0) Document(v0) + * PatchMutation Document(v3) Document(v3) + * PatchMutation NoDocument(v3) NoDocument(v3) + * PatchMutation InvalidDocument(v0) UnknownDocument(v3) + * DeleteMutation Document(v3) NoDocument(v0) + * DeleteMutation NoDocument(v3) NoDocument(v0) + * DeleteMutation InvalidDocument(v0) NoDocument(v0) + * + * For acknowledged mutations, we use the updateTime of the WriteResponse as + * the resulting version for Set and Patch mutations. As deletes have no + * explicit update time, we use the commitTime of the WriteResponse for + * Delete mutations. + * + * If a mutation is acknowledged by the backend but fails the precondition check + * locally, we transition to an `UnknownDocument` and rely on Watch to send us + * the updated version. + * + * Field transforms are used only with Patch and Set Mutations. We use the + * `updateTransforms` message to store transforms, rather than the `transforms`s + * messages. + * + * ## Subclassing Notes + * + * Every type of mutation needs to implement its own applyToRemoteDocument() and + * applyToLocalView() to implement the actual behavior of applying the mutation + * to some source document (see `setMutationApplyToRemoteDocument()` for an + * example). + */ class Mutation {} + +/** + * A mutation that creates or replaces the document at the given key with the + * object value contents. + */ class __PRIVATE_SetMutation extends Mutation { + constructor(t, e, r, n = []) { + super(), this.key = t, this.value = e, this.precondition = r, this.fieldTransforms = n, + this.type = 0 /* MutationType.Set */; + } + getFieldMask() { + return null; + } +} + +/** + * A mutation that modifies fields of the document at the given key with the + * given values. The values are applied through a field mask: + * + * * When a field is in both the mask and the values, the corresponding field + * is updated. + * * When a field is in neither the mask nor the values, the corresponding + * field is unmodified. + * * When a field is in the mask but not in the values, the corresponding field + * is deleted. + * * When a field is not in the mask but is in the values, the values map is + * ignored. + */ class __PRIVATE_PatchMutation extends Mutation { + constructor(t, e, r, n, i = []) { + super(), this.key = t, this.data = e, this.fieldMask = r, this.precondition = n, + this.fieldTransforms = i, this.type = 1 /* MutationType.Patch */; + } + getFieldMask() { + return this.fieldMask; + } +} + +/** A mutation that deletes the document at the given key. */ class __PRIVATE_DeleteMutation extends Mutation { + constructor(t, e) { + super(), this.key = t, this.precondition = e, this.type = 2 /* MutationType.Delete */ , + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } +} + +/** + * A mutation that verifies the existence of the document at the given key with + * the provided precondition. + * + * The `verify` operation is only used in Transactions, and this class serves + * primarily to facilitate serialization into protos. + */ class __PRIVATE_VerifyMutation extends Mutation { + constructor(t, e) { + super(), this.key = t, this.precondition = e, this.type = 3 /* MutationType.Verify */ , + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const rt = (() => { + const t = { + asc: "ASCENDING", + desc: "DESCENDING" + }; + return t; +})(), nt = (() => { + const t = { + "<": "LESS_THAN", + "<=": "LESS_THAN_OR_EQUAL", + ">": "GREATER_THAN", + ">=": "GREATER_THAN_OR_EQUAL", + "==": "EQUAL", + "!=": "NOT_EQUAL", + "array-contains": "ARRAY_CONTAINS", + in: "IN", + "not-in": "NOT_IN", + "array-contains-any": "ARRAY_CONTAINS_ANY" + }; + return t; +})(), it = (() => { + const t = { + and: "AND", + or: "OR" + }; + return t; +})(); + +/** + * This class generates JsonObject values for the Datastore API suitable for + * sending to either GRPC stub methods or via the JSON/HTTP REST API. + * + * The serializer supports both Protobuf.js and Proto3 JSON formats. By + * setting `useProto3Json` to true, the serializer will use the Proto3 JSON + * format. + * + * For a description of the Proto3 JSON format check + * https://developers.google.com/protocol-buffers/docs/proto3#json + * + * TODO(klimt): We can remove the databaseId argument if we keep the full + * resource name in documents. + */ +class JsonProtoSerializer { + constructor(t, e) { + this.databaseId = t, this.useProto3Json = e; + } +} + +/** + * Returns a value for a number (or null) that's appropriate to put into + * a google.protobuf.Int32Value proto. + * DO NOT USE THIS FOR ANYTHING ELSE. + * This method cheats. It's typed as returning "number" because that's what + * our generated proto interfaces say Int32Value must be. But GRPC actually + * expects a { value: } struct. + */ +/** + * Returns a value for a Date that's appropriate to put into a proto. + */ +function toTimestamp(t, e) { + if (t.useProto3Json) { + return `${new Date(1e3 * e.seconds).toISOString().replace(/\.\d*/, "").replace("Z", "")}.${("000000000" + e.nanoseconds).slice(-9)}Z`; + } + return { + seconds: "" + e.seconds, + nanos: e.nanoseconds + }; +} + +/** + * Returns a Timestamp typed object given protobuf timestamp value. + */ +/** + * Returns a value for bytes that's appropriate to put in a proto. + * + * Visible for testing. + */ +function __PRIVATE_toBytes(t, e) { + return t.useProto3Json ? e.toBase64() : e.toUint8Array(); +} + +function __PRIVATE_toVersion(t, e) { + return toTimestamp(t, e.toTimestamp()); +} + +function __PRIVATE_fromVersion(t) { + return __PRIVATE_hardAssert(!!t, 49232), SnapshotVersion.fromTimestamp(function fromTimestamp(t) { + const e = __PRIVATE_normalizeTimestamp(t); + return new Timestamp(e.seconds, e.nanos); + }(t)); +} + +function __PRIVATE_toResourceName(t, e) { + return __PRIVATE_toResourcePath(t, e).canonicalString(); +} + +function __PRIVATE_toResourcePath(t, e) { + const r = function __PRIVATE_fullyQualifiedPrefixPath(t) { + return new ResourcePath([ "projects", t.projectId, "databases", t.database ]); + }(t).child("documents"); + return void 0 === e ? r : r.child(e); +} + +function __PRIVATE_toName(t, e) { + return __PRIVATE_toResourceName(t.databaseId, e.path); +} + +function fromName(t, e) { + const r = function __PRIVATE_fromResourceName(t) { + const e = ResourcePath.fromString(t); + return __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(e), 10190, { + key: e.toString() + }), e; + }(e); + if (r.get(1) !== t.databaseId.projectId) throw new FirestoreError(y, "Tried to deserialize key from different project: " + r.get(1) + " vs " + t.databaseId.projectId); + if (r.get(3) !== t.databaseId.database) throw new FirestoreError(y, "Tried to deserialize key from different database: " + r.get(3) + " vs " + t.databaseId.database); + return new DocumentKey(function __PRIVATE_extractLocalPathFromResourceName(t) { + return __PRIVATE_hardAssert(t.length > 4 && "documents" === t.get(4), 29091, { + key: t.toString() + }), t.popFirst(5); + } + /** Creates a Document proto from key and fields (but no create/update time) */ (r)); +} + +function __PRIVATE_toMutationDocument(t, e, r) { + return { + name: __PRIVATE_toName(t, e), + fields: r.value.mapValue.fields + }; +} + +function __PRIVATE_fromBatchGetDocumentsResponse(t, e) { + return "found" in e ? function __PRIVATE_fromFound(t, e) { + __PRIVATE_hardAssert(!!e.found, 43571), e.found.name, e.found.updateTime; + const r = fromName(t, e.found.name), n = __PRIVATE_fromVersion(e.found.updateTime), i = e.found.createTime ? __PRIVATE_fromVersion(e.found.createTime) : SnapshotVersion.min(), s = new ObjectValue({ + mapValue: { + fields: e.found.fields + } + }); + return MutableDocument.newFoundDocument(r, n, i, s); + }(t, e) : "missing" in e ? function __PRIVATE_fromMissing(t, e) { + __PRIVATE_hardAssert(!!e.missing, 3894), __PRIVATE_hardAssert(!!e.readTime, 22933); + const r = fromName(t, e.missing), n = __PRIVATE_fromVersion(e.readTime); + return MutableDocument.newNoDocument(r, n); + }(t, e) : fail(7234, { + result: e + }); +} + +function toMutation(t, e) { + let r; + if (e instanceof __PRIVATE_SetMutation) r = { + update: __PRIVATE_toMutationDocument(t, e.key, e.value) + }; else if (e instanceof __PRIVATE_DeleteMutation) r = { + delete: __PRIVATE_toName(t, e.key) + }; else if (e instanceof __PRIVATE_PatchMutation) r = { + update: __PRIVATE_toMutationDocument(t, e.key, e.data), + updateMask: __PRIVATE_toDocumentMask(e.fieldMask) + }; else { + if (!(e instanceof __PRIVATE_VerifyMutation)) return fail(16599, { + L: e.type + }); + r = { + verify: __PRIVATE_toName(t, e.key) + }; + } + return e.fieldTransforms.length > 0 && (r.updateTransforms = e.fieldTransforms.map((t => function __PRIVATE_toFieldTransform(t, e) { + const r = e.transform; + if (r instanceof __PRIVATE_ServerTimestampTransform) return { + fieldPath: e.field.canonicalString(), + setToServerValue: "REQUEST_TIME" + }; + if (r instanceof __PRIVATE_ArrayUnionTransformOperation) return { + fieldPath: e.field.canonicalString(), + appendMissingElements: { + values: r.elements + } + }; + if (r instanceof __PRIVATE_ArrayRemoveTransformOperation) return { + fieldPath: e.field.canonicalString(), + removeAllFromArray: { + values: r.elements + } + }; + if (r instanceof __PRIVATE_NumericIncrementTransformOperation) return { + fieldPath: e.field.canonicalString(), + increment: r.k + }; + throw fail(20930, { + transform: e.transform + }); + }(0, t)))), e.precondition.isNone || (r.currentDocument = function __PRIVATE_toPrecondition(t, e) { + return void 0 !== e.updateTime ? { + updateTime: __PRIVATE_toVersion(t, e.updateTime) + } : void 0 !== e.exists ? { + exists: e.exists + } : fail(27497); + }(t, e.precondition)), r; +} + +function __PRIVATE_toQueryTarget(t, e) { + // Dissect the path into parent, collectionId, and optional key filter. + const r = { + structuredQuery: {} + }, n = e.path; + let i; + null !== e.collectionGroup ? (i = n, r.structuredQuery.from = [ { + collectionId: e.collectionGroup, + allDescendants: !0 + } ]) : (i = n.popLast(), r.structuredQuery.from = [ { + collectionId: n.lastSegment() + } ]), r.parent = function __PRIVATE_toQueryPath(t, e) { + return __PRIVATE_toResourceName(t.databaseId, e); + }(t, i); + const s = function __PRIVATE_toFilters(t) { + if (0 === t.length) return; + return __PRIVATE_toFilter(CompositeFilter.create(t, "and" /* CompositeOperator.AND */)); + }(e.filters); + s && (r.structuredQuery.where = s); + const o = function __PRIVATE_toOrder(t) { + if (0 === t.length) return; + return t.map((t => + // visible for testing + function __PRIVATE_toPropertyOrder(t) { + return { + field: __PRIVATE_toFieldPathReference(t.field), + direction: __PRIVATE_toDirection(t.dir) + }; + } + // visible for testing + (t))); + }(e.orderBy); + o && (r.structuredQuery.orderBy = o); + const a = function __PRIVATE_toInt32Proto(t, e) { + return t.useProto3Json || __PRIVATE_isNullOrUndefined(e) ? e : { + value: e + }; + }(t, e.limit); + return null !== a && (r.structuredQuery.limit = a), e.startAt && (r.structuredQuery.startAt = function __PRIVATE_toStartAtCursor(t) { + return { + before: t.inclusive, + values: t.position + }; + }(e.startAt)), e.endAt && (r.structuredQuery.endAt = function __PRIVATE_toEndAtCursor(t) { + return { + before: !t.inclusive, + values: t.position + }; + } + // visible for testing + (e.endAt)), { + M: r, + parent: i + }; +} + +function __PRIVATE_toDirection(t) { + return rt[t]; +} + +// visible for testing +function __PRIVATE_toOperatorName(t) { + return nt[t]; +} + +function __PRIVATE_toCompositeOperatorName(t) { + return it[t]; +} + +function __PRIVATE_toFieldPathReference(t) { + return { + fieldPath: t.canonicalString() + }; +} + +function __PRIVATE_toFilter(t) { + return t instanceof FieldFilter ? function __PRIVATE_toUnaryOrFieldFilter(t) { + if ("==" /* Operator.EQUAL */ === t.op) { + if (__PRIVATE_isNanValue(t.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: "IS_NAN" + } + }; + if (__PRIVATE_isNullValue(t.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: "IS_NULL" + } + }; + } else if ("!=" /* Operator.NOT_EQUAL */ === t.op) { + if (__PRIVATE_isNanValue(t.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: "IS_NOT_NAN" + } + }; + if (__PRIVATE_isNullValue(t.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: "IS_NOT_NULL" + } + }; + } + return { + fieldFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: __PRIVATE_toOperatorName(t.op), + value: t.value + } + }; + }(t) : t instanceof CompositeFilter ? function __PRIVATE_toCompositeFilter(t) { + const e = t.getFilters().map((t => __PRIVATE_toFilter(t))); + if (1 === e.length) return e[0]; + return { + compositeFilter: { + op: __PRIVATE_toCompositeOperatorName(t.op), + filters: e + } + }; + }(t) : fail(54877, { + filter: t + }); +} + +function __PRIVATE_toDocumentMask(t) { + const e = []; + return t.fields.forEach((t => e.push(t.canonicalString()))), { + fieldPaths: e + }; +} + +function __PRIVATE_isValidResourceName(t) { + // Resource names have at least 4 components (project ID, database ID) + return t.length >= 4 && "projects" === t.get(0) && "databases" === t.get(2); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_newSerializer(t) { + return new JsonProtoSerializer(t, /* useProto3Json= */ !0); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A helper for running delayed tasks following an exponential backoff curve + * between attempts. + * + * Each delay is made up of a "base" delay which follows the exponential + * backoff curve, and a +/- 50% "jitter" that is calculated and added to the + * base delay. This prevents clients from accidentally synchronizing their + * delays causing spikes of load to the backend. + */ +class __PRIVATE_ExponentialBackoff { + constructor( + /** + * The AsyncQueue to run backoff operations on. + */ + t, + /** + * The ID to use when scheduling backoff operations on the AsyncQueue. + */ + e, + /** + * The initial delay (used as the base delay on the first retry attempt). + * Note that jitter will still be applied, so the actual delay could be as + * little as 0.5*initialDelayMs. + */ + r = 1e3 + /** + * The multiplier to use to determine the extended base delay after each + * attempt. + */ , n = 1.5 + /** + * The maximum base delay after which no further backoff is performed. + * Note that jitter will still be applied, so the actual delay could be as + * much as 1.5*maxDelayMs. + */ , i = 6e4) { + this.U = t, this.timerId = e, this.j = r, this.W = n, this.K = i, this.G = 0, this.J = null, + /** The last backoff attempt, as epoch milliseconds. */ + this.H = Date.now(), this.reset(); + } + /** + * Resets the backoff delay. + * + * The very next backoffAndWait() will have no delay. If it is called again + * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and + * subsequent ones will increase according to the backoffFactor. + */ reset() { + this.G = 0; + } + /** + * Resets the backoff delay to the maximum delay (e.g. for use after a + * RESOURCE_EXHAUSTED error). + */ Y() { + this.G = this.K; + } + /** + * Returns a promise that resolves after currentDelayMs, and increases the + * delay for any subsequent attempts. If there was a pending backoff operation + * already, it will be canceled. + */ Z(t) { + // Cancel any pending backoff operation. + this.cancel(); + // First schedule using the current base (which may be 0 and should be + // honored as such). + const e = Math.floor(this.G + this.X()), r = Math.max(0, Date.now() - this.H), n = Math.max(0, e - r); + // Guard against lastAttemptTime being in the future due to a clock change. + n > 0 && __PRIVATE_logDebug("ExponentialBackoff", `Backing off for ${n} ms (base delay: ${this.G} ms, delay with jitter: ${e} ms, last attempt: ${r} ms ago)`), + this.J = this.U.enqueueAfterDelay(this.timerId, n, (() => (this.H = Date.now(), + t()))), + // Apply backoff factor to determine next delay and ensure it is within + // bounds. + this.G *= this.W, this.G < this.j && (this.G = this.j), this.G > this.K && (this.G = this.K); + } + tt() { + null !== this.J && (this.J.skipDelay(), this.J = null); + } + cancel() { + null !== this.J && (this.J.cancel(), this.J = null); + } + /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ X() { + return (Math.random() - .5) * this.G; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Datastore and its related methods are a wrapper around the external Google + * Cloud Datastore grpc API, which provides an interface that is more convenient + * for the rest of the client SDK architecture to consume. + */ class Datastore {} + +/** + * An implementation of Datastore that exposes additional state for internal + * consumption. + */ class __PRIVATE_DatastoreImpl extends Datastore { + constructor(t, e, r, n) { + super(), this.authCredentials = t, this.appCheckCredentials = e, this.connection = r, + this.serializer = n, this.et = !1; + } + rt() { + if (this.et) throw new FirestoreError(S, "The client has already been terminated."); + } + /** Invokes the provided RPC with auth and AppCheck tokens. */ I(t, e, r, n) { + return this.rt(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([i, s]) => this.connection.I(t, __PRIVATE_toResourcePath(e, r), n, i, s))).catch((t => { + throw "FirebaseError" === t.name ? (t.code === D && (this.authCredentials.invalidateToken(), + this.appCheckCredentials.invalidateToken()), t) : new FirestoreError(p, t.toString()); + })); + } + /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ D(t, e, r, n, i) { + return this.rt(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([s, o]) => this.connection.D(t, __PRIVATE_toResourcePath(e, r), n, s, o, i))).catch((t => { + throw "FirebaseError" === t.name ? (t.code === D && (this.authCredentials.invalidateToken(), + this.appCheckCredentials.invalidateToken()), t) : new FirestoreError(p, t.toString()); + })); + } + terminate() { + this.et = !0, this.connection.terminate(); + } +} + +// TODO(firestorexp): Make sure there is only one Datastore instance per +// firestore-exp client. +async function __PRIVATE_invokeCommitRpc(t, e) { + const r = __PRIVATE_debugCast(t), n = { + writes: e.map((t => toMutation(r.serializer, t))) + }; + await r.I("Commit", r.serializer.databaseId, ResourcePath.emptyPath(), n); +} + +async function __PRIVATE_invokeBatchGetDocumentsRpc(t, e) { + const r = __PRIVATE_debugCast(t), n = { + documents: e.map((t => __PRIVATE_toName(r.serializer, t))) + }, i = await r.D("BatchGetDocuments", r.serializer.databaseId, ResourcePath.emptyPath(), n, e.length), s = new Map; + i.forEach((t => { + const e = __PRIVATE_fromBatchGetDocumentsResponse(r.serializer, t); + s.set(e.key.toString(), e); + })); + const o = []; + return e.forEach((t => { + const e = s.get(t.toString()); + __PRIVATE_hardAssert(!!e, 55234, { + key: t + }), o.push(e); + })), o; +} + +async function __PRIVATE_invokeRunQueryRpc(t, e) { + const r = __PRIVATE_debugCast(t), {M: n, parent: i} = __PRIVATE_toQueryTarget(r.serializer, __PRIVATE_queryToTarget(e)); + return (await r.D("RunQuery", r.serializer.databaseId, i, { + structuredQuery: n.structuredQuery + })).filter((t => !!t.document)).map((t => function __PRIVATE_fromDocument(t, e, r) { + const n = fromName(t, e.name), i = __PRIVATE_fromVersion(e.updateTime), s = e.createTime ? __PRIVATE_fromVersion(e.createTime) : SnapshotVersion.min(), o = new ObjectValue({ + mapValue: { + fields: e.fields + } + }), a = MutableDocument.newFoundDocument(n, i, s, o); + return r && a.setHasCommittedMutations(), r ? a.setHasCommittedMutations() : a; + }(r.serializer, t.document, void 0))); +} + +async function __PRIVATE_invokeRunAggregationQueryRpc(t, e, r) { + const n = __PRIVATE_debugCast(t), {request: i, nt: s, parent: o} = function __PRIVATE_toRunAggregationQueryRequest(t, e, r, n) { + const {M: i, parent: s} = __PRIVATE_toQueryTarget(t, e), o = {}, a = []; + let u = 0; + return r.forEach((t => { + // Map all client-side aliases to a unique short-form + // alias. This avoids issues with client-side aliases that + // exceed the 1500-byte string size limit. + const e = n ? t.alias : "aggregate_" + u++; + o[e] = t.alias, "count" === t.aggregateType ? a.push({ + alias: e, + count: {} + }) : "avg" === t.aggregateType ? a.push({ + alias: e, + avg: { + field: __PRIVATE_toFieldPathReference(t.fieldPath) + } + }) : "sum" === t.aggregateType && a.push({ + alias: e, + sum: { + field: __PRIVATE_toFieldPathReference(t.fieldPath) + } + }); + })), { + request: { + structuredAggregationQuery: { + aggregations: a, + structuredQuery: i.structuredQuery + }, + parent: i.parent + }, + nt: o, + parent: s + }; + }(n.serializer, function __PRIVATE_queryToAggregateTarget(t) { + const e = __PRIVATE_debugCast(t); + return e.$ || ( + // Do not include implicit order-bys for aggregate queries. + e.$ = __PRIVATE__queryToTarget(e, t.explicitOrderBy)), e.$; + }(e), r); + n.connection.P || delete i.parent; + const a = (await n.D("RunAggregationQuery", n.serializer.databaseId, o, i, + /*expectedResponseCount=*/ 1)).filter((t => !!t.result)); + // Omit RunAggregationQueryResponse that only contain readTimes. + __PRIVATE_hardAssert(1 === a.length, 64727); + // Remap the short-form aliases that were sent to the server + // to the client-side aliases. Users will access the results + // using the client-side alias. + const u = a[0].result?.aggregateFields; + return Object.keys(u).reduce(((t, e) => (t[s[e]] = u[e], t)), {}); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const st = "ComponentProvider", ot = new Map; + +/** + * An instance map that ensures only one Datastore exists per Firestore + * instance. + */ +/** + * Returns an initialized and started Datastore for the given Firestore + * instance. Callers must invoke removeComponents() when the Firestore + * instance is terminated. + */ +function __PRIVATE_getDatastore(t) { + if (t._terminated) throw new FirestoreError(S, "The client has already been terminated."); + if (!ot.has(t)) { + __PRIVATE_logDebug(st, "Initializing Datastore"); + const e = function __PRIVATE_newConnection(t) { + return new __PRIVATE_FetchConnection(t); + }(function __PRIVATE_makeDatabaseInfo(t, e, r, n) { + return new DatabaseInfo(t, e, r, n.host, n.ssl, n.experimentalForceLongPolling, n.experimentalAutoDetectLongPolling, __PRIVATE_cloneLongPollingOptions(n.experimentalLongPollingOptions), n.useFetchStreams, n.isUsingEmulator); + } + /** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ (t._databaseId, t.app.options.appId || "", t._persistenceKey, t._freezeSettings())), r = __PRIVATE_newSerializer(t._databaseId), n = function __PRIVATE_newDatastore(t, e, r, n) { + return new __PRIVATE_DatastoreImpl(t, e, r, n); + }(t._authCredentials, t._appCheckCredentials, e, r); + ot.set(t, n); + } + return ot.get(t); +} + +/** + * Removes all components associated with the provided instance. Must be called + * when the `Firestore` instance is terminated. + */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const at = 1048576, ut = "firestore.googleapis.com", _t = !0; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// settings() defaults: +/** + * A concrete type describing all the values that can be applied via a + * user-supplied `FirestoreSettings` object. This is a separate type so that + * defaults can be supplied and the value can be checked for equality. + */ +class FirestoreSettingsImpl { + constructor(t) { + if (void 0 === t.host) { + if (void 0 !== t.ssl) throw new FirestoreError(y, "Can't provide ssl option if host option is not set"); + this.host = ut, this.ssl = _t; + } else this.host = t.host, this.ssl = t.ssl ?? _t; + if (this.isUsingEmulator = void 0 !== t.emulatorOptions, this.credentials = t.credentials, + this.ignoreUndefinedProperties = !!t.ignoreUndefinedProperties, this.localCache = t.localCache, + void 0 === t.cacheSizeBytes) this.cacheSizeBytes = 41943040; else { + if (-1 !== t.cacheSizeBytes && t.cacheSizeBytes < at) throw new FirestoreError(y, "cacheSizeBytes must be at least 1048576"); + this.cacheSizeBytes = t.cacheSizeBytes; + } + !function __PRIVATE_validateIsNotUsedTogether(t, e, r, n) { + if (!0 === e && !0 === n) throw new FirestoreError(y, `${t} and ${r} cannot be used together.`); + }("experimentalForceLongPolling", t.experimentalForceLongPolling, "experimentalAutoDetectLongPolling", t.experimentalAutoDetectLongPolling), + this.experimentalForceLongPolling = !!t.experimentalForceLongPolling, this.experimentalForceLongPolling ? this.experimentalAutoDetectLongPolling = !1 : void 0 === t.experimentalAutoDetectLongPolling ? this.experimentalAutoDetectLongPolling = true : + // For backwards compatibility, coerce the value to boolean even though + // the TypeScript compiler has narrowed the type to boolean already. + // noinspection PointlessBooleanExpressionJS + this.experimentalAutoDetectLongPolling = !!t.experimentalAutoDetectLongPolling, + this.experimentalLongPollingOptions = __PRIVATE_cloneLongPollingOptions(t.experimentalLongPollingOptions ?? {}), + function __PRIVATE_validateLongPollingOptions(t) { + if (void 0 !== t.timeoutSeconds) { + if (isNaN(t.timeoutSeconds)) throw new FirestoreError(y, `invalid long polling timeout: ${t.timeoutSeconds} (must not be NaN)`); + if (t.timeoutSeconds < 5) throw new FirestoreError(y, `invalid long polling timeout: ${t.timeoutSeconds} (minimum allowed value is 5)`); + if (t.timeoutSeconds > 30) throw new FirestoreError(y, `invalid long polling timeout: ${t.timeoutSeconds} (maximum allowed value is 30)`); + } + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ (this.experimentalLongPollingOptions), this.useFetchStreams = !!t.useFetchStreams; + } + isEqual(t) { + return this.host === t.host && this.ssl === t.ssl && this.credentials === t.credentials && this.cacheSizeBytes === t.cacheSizeBytes && this.experimentalForceLongPolling === t.experimentalForceLongPolling && this.experimentalAutoDetectLongPolling === t.experimentalAutoDetectLongPolling && function __PRIVATE_longPollingOptionsEqual(t, e) { + return t.timeoutSeconds === e.timeoutSeconds; + }(this.experimentalLongPollingOptions, t.experimentalLongPollingOptions) && this.ignoreUndefinedProperties === t.ignoreUndefinedProperties && this.useFetchStreams === t.useFetchStreams; + } +} + +class Firestore { + /** @hideconstructor */ + constructor(t, e, r, n) { + this._authCredentials = t, this._appCheckCredentials = e, this._databaseId = r, + this._app = n, + /** + * Whether it's a Firestore or Firestore Lite instance. + */ + this.type = "firestore-lite", this._persistenceKey = "(lite)", this._settings = new FirestoreSettingsImpl({}), + this._settingsFrozen = !1, this._emulatorOptions = {}, + // A task that is assigned when the terminate() is invoked and resolved when + // all components have shut down. Otherwise, Firestore is not terminated, + // which can mean either the FirestoreClient is in the process of starting, + // or restarting. + this._terminateTask = "notTerminated"; + } + /** + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service + * instance. + */ get app() { + if (!this._app) throw new FirestoreError(S, "Firestore was not initialized using the Firebase SDK. 'app' is not available"); + return this._app; + } + get _initialized() { + return this._settingsFrozen; + } + get _terminated() { + return "notTerminated" !== this._terminateTask; + } + _setSettings(t) { + if (this._settingsFrozen) throw new FirestoreError(S, "Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object."); + this._settings = new FirestoreSettingsImpl(t), this._emulatorOptions = t.emulatorOptions || {}, + void 0 !== t.credentials && (this._authCredentials = function __PRIVATE_makeAuthCredentialsProvider(t) { + if (!t) return new __PRIVATE_EmptyAuthCredentialsProvider; + switch (t.type) { + case "firstParty": + return new __PRIVATE_FirstPartyAuthCredentialsProvider(t.sessionIndex || "0", t.iamToken || null, t.authTokenFactory || null); + + case "provider": + return t.client; + + default: + throw new FirestoreError(y, "makeAuthCredentialsProvider failed due to invalid credential type"); + } + }(t.credentials)); + } + _getSettings() { + return this._settings; + } + _getEmulatorOptions() { + return this._emulatorOptions; + } + _freezeSettings() { + return this._settingsFrozen = !0, this._settings; + } + _delete() { + // The `_terminateTask` must be assigned future that completes when + // terminate is complete. The existence of this future puts SDK in state + // that will not accept further API interaction. + return "notTerminated" === this._terminateTask && (this._terminateTask = this._terminate()), + this._terminateTask; + } + async _restart() { + // The `_terminateTask` must equal 'notTerminated' after restart to + // signal that client is in a state that accepts API calls. + "notTerminated" === this._terminateTask ? await this._terminate() : this._terminateTask = "notTerminated"; + } + /** Returns a JSON-serializable representation of this `Firestore` instance. */ toJSON() { + return { + app: this._app, + databaseId: this._databaseId, + settings: this._settings + }; + } + /** + * Terminates all components used by this client. Subclasses can override + * this method to clean up their own dependencies, but must also call this + * method. + * + * Only ever called once. + */ _terminate() { + return function __PRIVATE_removeComponents(t) { + const e = ot.get(t); + e && (__PRIVATE_logDebug(st, "Removing Datastore"), ot.delete(t), e.terminate()); + }(this), Promise.resolve(); + } +} + +function initializeFirestore(t, e, r) { + r || (r = Q); + const n = _getProvider(t, "firestore/lite"); + if (n.isInitialized(r)) throw new FirestoreError(S, "Firestore can only be initialized once per app."); + return n.initialize({ + options: e, + instanceIdentifier: r + }); +} + +function getFirestore(t, r) { + const n = "object" == typeof t ? t : getApp(), i = "string" == typeof t ? t : r || "(default)", s = _getProvider(n, "firestore/lite").getImmediate({ + identifier: i + }); + if (!s._initialized) { + const t = getDefaultEmulatorHostnameAndPort("firestore"); + t && connectFirestoreEmulator(s, ...t); + } + return s; +} + +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ function connectFirestoreEmulator(t, e, r, n = {}) { + t = __PRIVATE_cast(t, Firestore); + const i = isCloudWorkstation(e), s = t._getSettings(), o = { + ...s, + emulatorOptions: t._getEmulatorOptions() + }, a = `${e}:${r}`; + i && (pingServer(`https://${a}`), updateEmulatorBanner("Firestore", !0)), s.host !== ut && s.host !== a && __PRIVATE_logWarn("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."); + const u = { + ...s, + host: a, + ssl: i, + emulatorOptions: n + }; + // No-op if the new configuration matches the current configuration. This supports SSR + // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice. + if (!deepEqual(u, o) && (t._setSettings(u), n.mockUserToken)) { + let e, r; + if ("string" == typeof n.mockUserToken) e = n.mockUserToken, r = User.MOCK_USER; else { + // Let createMockUserToken validate first (catches common mistakes like + // invalid field "uid" and missing field "sub" / "user_id".) + e = createMockUserToken(n.mockUserToken, t._app?.options.projectId); + const i = n.mockUserToken.sub || n.mockUserToken.user_id; + if (!i) throw new FirestoreError(y, "mockUserToken must contain 'sub' or 'user_id' field!"); + r = new User(i); + } + t._authCredentials = new __PRIVATE_EmulatorAuthCredentialsProvider(new __PRIVATE_OAuthToken(e, r)); + } +} + +/** + * Terminates the provided `Firestore` instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` functions + * may be used. Any other function will throw a `FirestoreError`. Termination + * does not cancel any pending writes, and any promises that are awaiting a + * response from the server will not be resolved. + * + * To restart after termination, create a new instance of `Firestore` with + * {@link (getFirestore:1)}. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all of + * its resources or in combination with {@link clearIndexedDbPersistence} to + * ensure that all local state is destroyed between test runs. + * + * @param firestore - The `Firestore` instance to terminate. + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ function terminate(t) { + return t = __PRIVATE_cast(t, Firestore), _removeServiceInstance(t.app, "firestore/lite"), t._delete(); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents an aggregation that can be performed by Firestore. + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +class AggregateField { + /** + * Create a new AggregateField + * @param aggregateType Specifies the type of aggregation operation to perform. + * @param _internalFieldPath Optionally specifies the field that is aggregated. + * @internal + */ + constructor(t = "count", e) { + this._internalFieldPath = e, + /** A type string to uniquely identify instances of this class. */ + this.type = "AggregateField", this.aggregateType = t; + } +} + +/** + * The results of executing an aggregation query. + */ class AggregateQuerySnapshot { + /** @hideconstructor */ + constructor(t, e, r) { + this._userDataWriter = e, this._data = r, + /** A type string to uniquely identify instances of this class. */ + this.type = "AggregateQuerySnapshot", this.query = t; + } + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ data() { + return this._userDataWriter.convertObjectMap(this._data); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `Query` refers to a query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ class Query { + // This is the lite version of the Query class in the main SDK. + /** @hideconstructor protected */ + constructor(t, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + e, r) { + this.converter = e, this._query = r, + /** The type of this Firestore reference. */ + this.type = "query", this.firestore = t; + } + withConverter(t) { + return new Query(this.firestore, t, this._query); + } +} + +/** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. + */ class DocumentReference { + /** @hideconstructor */ + constructor(t, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + e, r) { + this.converter = e, this._key = r, + /** The type of this Firestore reference. */ + this.type = "document", this.firestore = t; + } + get _path() { + return this._key.path; + } + /** + * The document's identifier within its collection. + */ get id() { + return this._key.path.lastSegment(); + } + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ get path() { + return this._key.path.canonicalString(); + } + /** + * The collection this `DocumentReference` belongs to. + */ get parent() { + return new CollectionReference(this.firestore, this.converter, this._key.path.popLast()); + } + withConverter(t) { + return new DocumentReference(this.firestore, t, this._key); + } + /** + * Returns a JSON-serializable representation of this `DocumentReference` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + type: DocumentReference._jsonSchemaVersion, + referencePath: this._key.toString() + }; + } + static fromJSON(t, e, r) { + if (__PRIVATE_validateJSON(e, DocumentReference._jsonSchema)) return new DocumentReference(t, r || null, new DocumentKey(ResourcePath.fromString(e.referencePath))); + } +} + +DocumentReference._jsonSchemaVersion = "firestore/documentReference/1.0", DocumentReference._jsonSchema = { + type: property("string", DocumentReference._jsonSchemaVersion), + referencePath: property("string") +}; + +/** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using {@link (query:1)}). + */ +class CollectionReference extends Query { + /** @hideconstructor */ + constructor(t, e, r) { + super(t, e, function __PRIVATE_newQueryForPath(t) { + return new __PRIVATE_QueryImpl(t); + }(r)), this._path = r, + /** The type of this Firestore reference. */ + this.type = "collection"; + } + /** The collection's identifier. */ get id() { + return this._query.path.lastSegment(); + } + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ get path() { + return this._query.path.canonicalString(); + } + /** + * A reference to the containing `DocumentReference` if this is a + * subcollection. If this isn't a subcollection, the reference is null. + */ get parent() { + const t = this._path.popLast(); + return t.isEmpty() ? null : new DocumentReference(this.firestore, + /* converter= */ null, new DocumentKey(t)); + } + withConverter(t) { + return new CollectionReference(this.firestore, t, this._path); + } +} + +function collection(t, e, ...r) { + if (t = getModularInstance(t), __PRIVATE_validateNonEmptyArgument("collection", "path", e), t instanceof Firestore) { + const n = ResourcePath.fromString(e, ...r); + return __PRIVATE_validateCollectionPath(n), new CollectionReference(t, /* converter= */ null, n); + } + { + if (!(t instanceof DocumentReference || t instanceof CollectionReference)) throw new FirestoreError(y, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore"); + const n = t._path.child(ResourcePath.fromString(e, ...r)); + return __PRIVATE_validateCollectionPath(n), new CollectionReference(t.firestore, + /* converter= */ null, n); + } +} + +// TODO(firestorelite): Consider using ErrorFactory - +// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106 +/** + * Creates and returns a new `Query` instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given `collectionId`. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param collectionId - Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `Query`. + */ function collectionGroup(t, e) { + if (t = __PRIVATE_cast(t, Firestore), __PRIVATE_validateNonEmptyArgument("collectionGroup", "collection id", e), + e.indexOf("/") >= 0) throw new FirestoreError(y, `Invalid collection ID '${e}' passed to function collectionGroup(). Collection IDs must not contain '/'.`); + return new Query(t, + /* converter= */ null, function __PRIVATE_newQueryForCollectionGroup(t) { + return new __PRIVATE_QueryImpl(ResourcePath.emptyPath(), t); + }(e)); +} + +function doc(t, e, ...r) { + if (t = getModularInstance(t), + // We allow omission of 'pathString' but explicitly prohibit passing in both + // 'undefined' and 'null'. + 1 === arguments.length && (e = __PRIVATE_AutoId.newId()), __PRIVATE_validateNonEmptyArgument("doc", "path", e), + t instanceof Firestore) { + const n = ResourcePath.fromString(e, ...r); + return __PRIVATE_validateDocumentPath(n), new DocumentReference(t, + /* converter= */ null, new DocumentKey(n)); + } + { + if (!(t instanceof DocumentReference || t instanceof CollectionReference)) throw new FirestoreError(y, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore"); + const n = t._path.child(ResourcePath.fromString(e, ...r)); + return __PRIVATE_validateDocumentPath(n), new DocumentReference(t.firestore, t instanceof CollectionReference ? t.converter : null, new DocumentKey(n)); + } +} + +/** + * Returns true if the provided references are equal. + * + * @param left - A reference to compare. + * @param right - A reference to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ function refEqual(t, e) { + return t = getModularInstance(t), e = getModularInstance(e), (t instanceof DocumentReference || t instanceof CollectionReference) && (e instanceof DocumentReference || e instanceof CollectionReference) && (t.firestore === e.firestore && t.path === e.path && t.converter === e.converter); +} + +/** + * Returns true if the provided queries point to the same collection and apply + * the same constraints. + * + * @param left - A `Query` to compare. + * @param right - A `Query` to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ function queryEqual(t, e) { + return t = getModularInstance(t), e = getModularInstance(e), t instanceof Query && e instanceof Query && (t.firestore === e.firestore && __PRIVATE_queryEquals(t._query, e._query) && t.converter === e.converter); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing an array of bytes. + */ class Bytes { + /** @hideconstructor */ + constructor(t) { + this._byteString = t; + } + /** + * Creates a new `Bytes` object from the given Base64 string, converting it to + * bytes. + * + * @param base64 - The Base64 string used to create the `Bytes` object. + */ static fromBase64String(t) { + try { + return new Bytes(ByteString.fromBase64String(t)); + } catch (t) { + throw new FirestoreError(y, "Failed to construct data from Base64 string: " + t); + } + } + /** + * Creates a new `Bytes` object from the given Uint8Array. + * + * @param array - The Uint8Array used to create the `Bytes` object. + */ static fromUint8Array(t) { + return new Bytes(ByteString.fromUint8Array(t)); + } + /** + * Returns the underlying bytes as a Base64-encoded string. + * + * @returns The Base64-encoded string created from the `Bytes` object. + */ toBase64() { + return this._byteString.toBase64(); + } + /** + * Returns the underlying bytes in a new `Uint8Array`. + * + * @returns The Uint8Array created from the `Bytes` object. + */ toUint8Array() { + return this._byteString.toUint8Array(); + } + /** + * Returns a string representation of the `Bytes` object. + * + * @returns A string representation of the `Bytes` object. + */ toString() { + return "Bytes(base64: " + this.toBase64() + ")"; + } + /** + * Returns true if this `Bytes` object is equal to the provided one. + * + * @param other - The `Bytes` object to compare against. + * @returns true if this `Bytes` object is equal to the provided one. + */ isEqual(t) { + return this._byteString.isEqual(t._byteString); + } + /** + * Returns a JSON-serializable representation of this `Bytes` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + type: Bytes._jsonSchemaVersion, + bytes: this.toBase64() + }; + } + /** + * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}. + * + * @param json a JSON object represention of a `Bytes` instance + * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ static fromJSON(t) { + if (__PRIVATE_validateJSON(t, Bytes._jsonSchema)) return Bytes.fromBase64String(t.bytes); + } +} + +Bytes._jsonSchemaVersion = "firestore/bytes/1.0", Bytes._jsonSchema = { + type: property("string", Bytes._jsonSchemaVersion), + bytes: property("string") +}; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `FieldPath` refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + * + * Create a `FieldPath` by providing field names. If more than one field + * name is provided, the path will point to a nested field in a document. + */ +class FieldPath { + /** + * Creates a `FieldPath` from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames - A list of field names. + */ + constructor(...t) { + for (let e = 0; e < t.length; ++e) if (0 === t[e].length) throw new FirestoreError(y, "Invalid field name at argument $(i + 1). Field names must not be empty."); + this._internalPath = new FieldPath$1(t); + } + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other - The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ isEqual(t) { + return this._internalPath.isEqual(t._internalPath); + } +} + +/** + * Returns a special sentinel `FieldPath` to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ function documentId() { + return new FieldPath(M); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Sentinel values that can be used when writing document fields with `set()` + * or `update()`. + */ class FieldValue { + /** + * @param _methodName - The public API endpoint that returns this class. + * @hideconstructor + */ + constructor(t) { + this._methodName = t; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ class GeoPoint { + /** + * Creates a new immutable `GeoPoint` object with the provided latitude and + * longitude values. + * @param latitude - The latitude as number between -90 and 90. + * @param longitude - The longitude as number between -180 and 180. + */ + constructor(t, e) { + if (!isFinite(t) || t < -90 || t > 90) throw new FirestoreError(y, "Latitude must be a number between -90 and 90, but was: " + t); + if (!isFinite(e) || e < -180 || e > 180) throw new FirestoreError(y, "Longitude must be a number between -180 and 180, but was: " + e); + this._lat = t, this._long = e; + } + /** + * The latitude of this `GeoPoint` instance. + */ get latitude() { + return this._lat; + } + /** + * The longitude of this `GeoPoint` instance. + */ get longitude() { + return this._long; + } + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other - The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ isEqual(t) { + return this._lat === t._lat && this._long === t._long; + } + /** + * Actually private to JS consumers of our API, so this function is prefixed + * with an underscore. + */ _compareTo(t) { + return __PRIVATE_primitiveComparator(this._lat, t._lat) || __PRIVATE_primitiveComparator(this._long, t._long); + } + /** + * Returns a JSON-serializable representation of this `GeoPoint` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + latitude: this._lat, + longitude: this._long, + type: GeoPoint._jsonSchemaVersion + }; + } + /** + * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}. + * + * @param json a JSON object represention of a `GeoPoint` instance + * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ static fromJSON(t) { + if (__PRIVATE_validateJSON(t, GeoPoint._jsonSchema)) return new GeoPoint(t.latitude, t.longitude); + } +} + +GeoPoint._jsonSchemaVersion = "firestore/geoPoint/1.0", GeoPoint._jsonSchema = { + type: property("string", GeoPoint._jsonSchemaVersion), + latitude: property("number"), + longitude: property("number") +}; + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link vector}. + * + * @class VectorValue + */ +class VectorValue { + /** + * @private + * @internal + */ + constructor(t) { + // Making a copy of the parameter. + this._values = (t || []).map((t => t)); + } + /** + * Returns a copy of the raw number array form of the vector. + */ toArray() { + return this._values.map((t => t)); + } + /** + * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise. + */ isEqual(t) { + /** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Verifies equality for an array of primitives. + * + * @private + * @internal + * @param left Array of primitives. + * @param right Array of primitives. + * @return True if arrays are equal. + */ + return function __PRIVATE_isPrimitiveArrayEqual(t, e) { + if (t.length !== e.length) return !1; + for (let r = 0; r < t.length; ++r) if (t[r] !== e[r]) return !1; + return !0; + }(this._values, t._values); + } + /** + * Returns a JSON-serializable representation of this `VectorValue` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + type: VectorValue._jsonSchemaVersion, + vectorValues: this._values + }; + } + /** + * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}. + * + * @param json a JSON object represention of a `VectorValue` instance. + * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ static fromJSON(t) { + if (__PRIVATE_validateJSON(t, VectorValue._jsonSchema)) { + if (Array.isArray(t.vectorValues) && t.vectorValues.every((t => "number" == typeof t))) return new VectorValue(t.vectorValues); + throw new FirestoreError(y, "Expected 'vectorValues' field to be a number array"); + } + } +} + +VectorValue._jsonSchemaVersion = "firestore/vectorValue/1.0", VectorValue._jsonSchema = { + type: property("string", VectorValue._jsonSchemaVersion), + vectorValues: property("object") +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const ct = /^__.*__$/; + +/** The result of parsing document data (e.g. for a setData call). */ class ParsedSetData { + constructor(t, e, r) { + this.data = t, this.fieldMask = e, this.fieldTransforms = r; + } + toMutation(t, e) { + return null !== this.fieldMask ? new __PRIVATE_PatchMutation(t, this.data, this.fieldMask, e, this.fieldTransforms) : new __PRIVATE_SetMutation(t, this.data, e, this.fieldTransforms); + } +} + +/** The result of parsing "update" data (i.e. for an updateData call). */ class ParsedUpdateData { + constructor(t, + // The fieldMask does not include document transforms. + e, r) { + this.data = t, this.fieldMask = e, this.fieldTransforms = r; + } + toMutation(t, e) { + return new __PRIVATE_PatchMutation(t, this.data, this.fieldMask, e, this.fieldTransforms); + } +} + +function __PRIVATE_isWrite(t) { + switch (t) { + case 0 /* UserDataSource.Set */ : + // fall through + case 2 /* UserDataSource.MergeSet */ : + // fall through + case 1 /* UserDataSource.Update */ : + return !0; + + case 3 /* UserDataSource.Argument */ : + case 4 /* UserDataSource.ArrayArgument */ : + return !1; + + default: + throw fail(40011, { + it: t + }); + } +} + +/** A "context" object passed around while parsing user data. */ class __PRIVATE_ParseContextImpl { + /** + * Initializes a ParseContext with the given source and path. + * + * @param settings - The settings for the parser. + * @param databaseId - The database ID of the Firestore instance. + * @param serializer - The serializer to use to generate the Value proto. + * @param ignoreUndefinedProperties - Whether to ignore undefined properties + * rather than throw. + * @param fieldTransforms - A mutable list of field transforms encountered + * while parsing the data. + * @param fieldMask - A mutable list of field paths encountered while parsing + * the data. + * + * TODO(b/34871131): We don't support array paths right now, so path can be + * null to indicate the context represents any location within an array (in + * which case certain features will not work and errors will be somewhat + * compromised). + */ + constructor(t, e, r, n, i, s) { + this.settings = t, this.databaseId = e, this.serializer = r, this.ignoreUndefinedProperties = n, + // Minor hack: If fieldTransforms is undefined, we assume this is an + // external call and we need to validate the entire path. + void 0 === i && this.st(), this.fieldTransforms = i || [], this.fieldMask = s || []; + } + get path() { + return this.settings.path; + } + get it() { + return this.settings.it; + } + /** Returns a new context with the specified settings overwritten. */ ot(t) { + return new __PRIVATE_ParseContextImpl({ + ...this.settings, + ...t + }, this.databaseId, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask); + } + ut(t) { + const e = this.path?.child(t), r = this.ot({ + path: e, + _t: !1 + }); + return r.ct(t), r; + } + lt(t) { + const e = this.path?.child(t), r = this.ot({ + path: e, + _t: !1 + }); + return r.st(), r; + } + ht(t) { + // TODO(b/34871131): We don't support array paths right now; so make path + // undefined. + return this.ot({ + path: void 0, + _t: !0 + }); + } + ft(t) { + return __PRIVATE_createError(t, this.settings.methodName, this.settings.dt || !1, this.path, this.settings.Et); + } + /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ contains(t) { + return void 0 !== this.fieldMask.find((e => t.isPrefixOf(e))) || void 0 !== this.fieldTransforms.find((e => t.isPrefixOf(e.field))); + } + st() { + // TODO(b/34871131): Remove null check once we have proper paths for fields + // within arrays. + if (this.path) for (let t = 0; t < this.path.length; t++) this.ct(this.path.get(t)); + } + ct(t) { + if (0 === t.length) throw this.ft("Document fields must not be empty"); + if (__PRIVATE_isWrite(this.it) && ct.test(t)) throw this.ft('Document fields cannot begin and end with "__"'); + } +} + +/** + * Helper for parsing raw user input (provided via the API) into internal model + * classes. + */ class __PRIVATE_UserDataReader { + constructor(t, e, r) { + this.databaseId = t, this.ignoreUndefinedProperties = e, this.serializer = r || __PRIVATE_newSerializer(t); + } + /** Creates a new top-level parse context. */ Tt(t, e, r, n = !1) { + return new __PRIVATE_ParseContextImpl({ + it: t, + methodName: e, + Et: r, + path: FieldPath$1.emptyPath(), + _t: !1, + dt: n + }, this.databaseId, this.serializer, this.ignoreUndefinedProperties); + } +} + +function __PRIVATE_newUserDataReader(t) { + const e = t._freezeSettings(), r = __PRIVATE_newSerializer(t._databaseId); + return new __PRIVATE_UserDataReader(t._databaseId, !!e.ignoreUndefinedProperties, r); +} + +/** Parse document data from a set() call. */ function __PRIVATE_parseSetData(t, e, r, n, i, s = {}) { + const o = t.Tt(s.merge || s.mergeFields ? 2 /* UserDataSource.MergeSet */ : 0 /* UserDataSource.Set */ , e, r, i); + __PRIVATE_validatePlainObject("Data must be an object, but it was:", o, n); + const a = __PRIVATE_parseObject(n, o); + let u, _; + if (s.merge) u = new FieldMask(o.fieldMask), _ = o.fieldTransforms; else if (s.mergeFields) { + const t = []; + for (const n of s.mergeFields) { + const i = __PRIVATE_fieldPathFromArgument$1(e, n, r); + if (!o.contains(i)) throw new FirestoreError(y, `Field '${i}' is specified in your field mask but missing from your input data.`); + __PRIVATE_fieldMaskContains(t, i) || t.push(i); + } + u = new FieldMask(t), _ = o.fieldTransforms.filter((t => u.covers(t.field))); + } else u = null, _ = o.fieldTransforms; + return new ParsedSetData(new ObjectValue(a), u, _); +} + +class __PRIVATE_DeleteFieldValueImpl extends FieldValue { + _toFieldTransform(t) { + if (2 /* UserDataSource.MergeSet */ !== t.it) throw 1 /* UserDataSource.Update */ === t.it ? t.ft(`${this._methodName}() can only appear at the top level of your update data`) : t.ft(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`); + // No transform to add for a delete, but we need to add it to our + // fieldMask so it gets deleted. + return t.fieldMask.push(t.path), null; + } + isEqual(t) { + return t instanceof __PRIVATE_DeleteFieldValueImpl; + } +} + +/** + * Creates a child context for parsing SerializableFieldValues. + * + * This is different than calling `ParseContext.contextWith` because it keeps + * the fieldTransforms and fieldMask separate. + * + * The created context has its `dataSource` set to `UserDataSource.Argument`. + * Although these values are used with writes, any elements in these FieldValues + * are not considered writes since they cannot contain any FieldValue sentinels, + * etc. + * + * @param fieldValue - The sentinel FieldValue for which to create a child + * context. + * @param context - The parent context. + * @param arrayElement - Whether or not the FieldValue has an array. + */ function __PRIVATE_createSentinelChildContext(t, e, r) { + return new __PRIVATE_ParseContextImpl({ + it: 3 /* UserDataSource.Argument */ , + Et: e.settings.Et, + methodName: t._methodName, + _t: r + }, e.databaseId, e.serializer, e.ignoreUndefinedProperties); +} + +class __PRIVATE_ServerTimestampFieldValueImpl extends FieldValue { + _toFieldTransform(t) { + return new FieldTransform(t.path, new __PRIVATE_ServerTimestampTransform); + } + isEqual(t) { + return t instanceof __PRIVATE_ServerTimestampFieldValueImpl; + } +} + +class __PRIVATE_ArrayUnionFieldValueImpl extends FieldValue { + constructor(t, e) { + super(t), this.Pt = e; + } + _toFieldTransform(t) { + const e = __PRIVATE_createSentinelChildContext(this, t, + /*array=*/ !0), r = this.Pt.map((t => __PRIVATE_parseData(t, e))), n = new __PRIVATE_ArrayUnionTransformOperation(r); + return new FieldTransform(t.path, n); + } + isEqual(t) { + return t instanceof __PRIVATE_ArrayUnionFieldValueImpl && deepEqual(this.Pt, t.Pt); + } +} + +class __PRIVATE_ArrayRemoveFieldValueImpl extends FieldValue { + constructor(t, e) { + super(t), this.Pt = e; + } + _toFieldTransform(t) { + const e = __PRIVATE_createSentinelChildContext(this, t, + /*array=*/ !0), r = this.Pt.map((t => __PRIVATE_parseData(t, e))), n = new __PRIVATE_ArrayRemoveTransformOperation(r); + return new FieldTransform(t.path, n); + } + isEqual(t) { + return t instanceof __PRIVATE_ArrayRemoveFieldValueImpl && deepEqual(this.Pt, t.Pt); + } +} + +class __PRIVATE_NumericIncrementFieldValueImpl extends FieldValue { + constructor(t, e) { + super(t), this.At = e; + } + _toFieldTransform(t) { + const e = new __PRIVATE_NumericIncrementTransformOperation(t.serializer, toNumber(t.serializer, this.At)); + return new FieldTransform(t.path, e); + } + isEqual(t) { + return t instanceof __PRIVATE_NumericIncrementFieldValueImpl && this.At === t.At; + } +} + +/** Parse update data from an update() call. */ function __PRIVATE_parseUpdateData(t, e, r, n) { + const i = t.Tt(1 /* UserDataSource.Update */ , e, r); + __PRIVATE_validatePlainObject("Data must be an object, but it was:", i, n); + const s = [], o = ObjectValue.empty(); + forEach(n, ((t, n) => { + const a = __PRIVATE_fieldPathFromDotSeparatedString(e, t, r); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + n = getModularInstance(n); + const u = i.lt(a); + if (n instanceof __PRIVATE_DeleteFieldValueImpl) + // Add it to the field mask, but don't add anything to updateData. + s.push(a); else { + const t = __PRIVATE_parseData(n, u); + null != t && (s.push(a), o.set(a, t)); + } + })); + const a = new FieldMask(s); + return new ParsedUpdateData(o, a, i.fieldTransforms); +} + +/** Parse update data from a list of field/value arguments. */ function __PRIVATE_parseUpdateVarargs(t, e, r, n, i, s) { + const o = t.Tt(1 /* UserDataSource.Update */ , e, r), a = [ __PRIVATE_fieldPathFromArgument$1(e, n, r) ], u = [ i ]; + if (s.length % 2 != 0) throw new FirestoreError(y, `Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`); + for (let t = 0; t < s.length; t += 2) a.push(__PRIVATE_fieldPathFromArgument$1(e, s[t])), + u.push(s[t + 1]); + const _ = [], c = ObjectValue.empty(); + // We iterate in reverse order to pick the last value for a field if the + // user specified the field multiple times. + for (let t = a.length - 1; t >= 0; --t) if (!__PRIVATE_fieldMaskContains(_, a[t])) { + const e = a[t]; + let r = u[t]; + // For Compat types, we have to "extract" the underlying types before + // performing validation. + r = getModularInstance(r); + const n = o.lt(e); + if (r instanceof __PRIVATE_DeleteFieldValueImpl) + // Add it to the field mask, but don't add anything to updateData. + _.push(e); else { + const t = __PRIVATE_parseData(r, n); + null != t && (_.push(e), c.set(e, t)); + } + } + const l = new FieldMask(_); + return new ParsedUpdateData(c, l, o.fieldTransforms); +} + +/** + * Parse a "query value" (e.g. value in a where filter or a value in a cursor + * bound). + * + * @param allowArrays - Whether the query value is an array that may directly + * contain additional arrays (e.g. the operand of an `in` query). + */ function __PRIVATE_parseQueryValue(t, e, r, n = !1) { + return __PRIVATE_parseData(r, t.Tt(n ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */ , e)); +} + +/** + * Parses user data to Protobuf Values. + * + * @param input - Data to be parsed. + * @param context - A context object representing the current path being parsed, + * the source of the data being parsed, etc. + * @returns The parsed value, or null if the value was a FieldValue sentinel + * that should not be included in the resulting parsed data. + */ function __PRIVATE_parseData(t, e) { + if (__PRIVATE_looksLikeJsonObject( + // Unwrap the API type from the Compat SDK. This will return the API type + // from firestore-exp. + t = getModularInstance(t))) return __PRIVATE_validatePlainObject("Unsupported field value:", e, t), + __PRIVATE_parseObject(t, e); + if (t instanceof FieldValue) + // FieldValues usually parse into transforms (except deleteField()) + // in which case we do not want to include this field in our parsed data + // (as doing so will overwrite the field directly prior to the transform + // trying to transform it). So we don't add this location to + // context.fieldMask and we return null as our parsing result. + /** + * "Parses" the provided FieldValueImpl, adding any necessary transforms to + * context.fieldTransforms. + */ + return function __PRIVATE_parseSentinelFieldValue(t, e) { + // Sentinels are only supported with writes, and not within arrays. + if (!__PRIVATE_isWrite(e.it)) throw e.ft(`${t._methodName}() can only be used with update() and set()`); + if (!e.path) throw e.ft(`${t._methodName}() is not currently supported inside arrays`); + const r = t._toFieldTransform(e); + r && e.fieldTransforms.push(r); + } + /** + * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue) + * + * @returns The parsed value + */ (t, e), null; + if (void 0 === t && e.ignoreUndefinedProperties) + // If the input is undefined it can never participate in the fieldMask, so + // don't handle this below. If `ignoreUndefinedProperties` is false, + // `parseScalarValue` will reject an undefined value. + return null; + if ( + // If context.path is null we are inside an array and we don't support + // field mask paths more granular than the top-level array. + e.path && e.fieldMask.push(e.path), t instanceof Array) { + // TODO(b/34871131): Include the path containing the array in the error + // message. + // In the case of IN queries, the parsed data is an array (representing + // the set of values to be included for the IN query) that may directly + // contain additional arrays (each representing an individual field + // value), so we disable this validation. + if (e.settings._t && 4 /* UserDataSource.ArrayArgument */ !== e.it) throw e.ft("Nested arrays are not supported"); + return function __PRIVATE_parseArray(t, e) { + const r = []; + let n = 0; + for (const i of t) { + let t = __PRIVATE_parseData(i, e.ht(n)); + null == t && ( + // Just include nulls in the array for fields being replaced with a + // sentinel. + t = { + nullValue: "NULL_VALUE" + }), r.push(t), n++; + } + return { + arrayValue: { + values: r + } + }; + }(t, e); + } + return function __PRIVATE_parseScalarValue(t, e) { + if (null === (t = getModularInstance(t))) return { + nullValue: "NULL_VALUE" + }; + if ("number" == typeof t) return toNumber(e.serializer, t); + if ("boolean" == typeof t) return { + booleanValue: t + }; + if ("string" == typeof t) return { + stringValue: t + }; + if (t instanceof Date) { + const r = Timestamp.fromDate(t); + return { + timestampValue: toTimestamp(e.serializer, r) + }; + } + if (t instanceof Timestamp) { + // Firestore backend truncates precision down to microseconds. To ensure + // offline mode works the same with regards to truncation, perform the + // truncation immediately without waiting for the backend to do that. + const r = new Timestamp(t.seconds, 1e3 * Math.floor(t.nanoseconds / 1e3)); + return { + timestampValue: toTimestamp(e.serializer, r) + }; + } + if (t instanceof GeoPoint) return { + geoPointValue: { + latitude: t.latitude, + longitude: t.longitude + } + }; + if (t instanceof Bytes) return { + bytesValue: __PRIVATE_toBytes(e.serializer, t._byteString) + }; + if (t instanceof DocumentReference) { + const r = e.databaseId, n = t.firestore._databaseId; + if (!n.isEqual(r)) throw e.ft(`Document reference is for database ${n.projectId}/${n.database} but should be for database ${r.projectId}/${r.database}`); + return { + referenceValue: __PRIVATE_toResourceName(t.firestore._databaseId || e.databaseId, t._key.path) + }; + } + if (t instanceof VectorValue) + /** + * Creates a new VectorValue proto value (using the internal format). + */ + return function __PRIVATE_parseVectorValue(t, e) { + const r = { + fields: { + [Y]: { + stringValue: tt + }, + [et]: { + arrayValue: { + values: t.toArray().map((t => { + if ("number" != typeof t) throw e.ft("VectorValues must only contain numeric values."); + return __PRIVATE_toDouble(e.serializer, t); + })) + } + } + } + }; + return { + mapValue: r + }; + } + /** + * Checks whether an object looks like a JSON object that should be converted + * into a struct. Normal class/prototype instances are considered to look like + * JSON objects since they should be converted to a struct value. Arrays, Dates, + * GeoPoints, etc. are not considered to look like JSON objects since they map + * to specific FieldValue types other than ObjectValue. + */ (t, e); + throw e.ft(`Unsupported field value: ${__PRIVATE_valueDescription(t)}`); + }(t, e); +} + +function __PRIVATE_parseObject(t, e) { + const r = {}; + return !function isEmpty(t) { + for (const e in t) if (Object.prototype.hasOwnProperty.call(t, e)) return !1; + return !0; + }(t) ? forEach(t, ((t, n) => { + const i = __PRIVATE_parseData(n, e.ut(t)); + null != i && (r[t] = i); + })) : + // If we encounter an empty object, we explicitly add it to the update + // mask to ensure that the server creates a map entry. + e.path && e.path.length > 0 && e.fieldMask.push(e.path), { + mapValue: { + fields: r + } + }; +} + +function __PRIVATE_looksLikeJsonObject(t) { + return !("object" != typeof t || null === t || t instanceof Array || t instanceof Date || t instanceof Timestamp || t instanceof GeoPoint || t instanceof Bytes || t instanceof DocumentReference || t instanceof FieldValue || t instanceof VectorValue); +} + +function __PRIVATE_validatePlainObject(t, e, r) { + if (!__PRIVATE_looksLikeJsonObject(r) || !__PRIVATE_isPlainObject(r)) { + const n = __PRIVATE_valueDescription(r); + throw "an object" === n ? e.ft(t + " a custom object") : e.ft(t + " " + n); + } +} + +/** + * Helper that calls fromDotSeparatedString() but wraps any error thrown. + */ function __PRIVATE_fieldPathFromArgument$1(t, e, r) { + if (( + // If required, replace the FieldPath Compat class with the firestore-exp + // FieldPath. + e = getModularInstance(e)) instanceof FieldPath) return e._internalPath; + if ("string" == typeof e) return __PRIVATE_fieldPathFromDotSeparatedString(t, e); + throw __PRIVATE_createError("Field path arguments must be of type string or ", t, + /* hasConverter= */ !1, + /* path= */ void 0, r); +} + +/** + * Matches any characters in a field path string that are reserved. + */ const lt = new RegExp("[~\\*/\\[\\]]"); + +/** + * Wraps fromDotSeparatedString with an error message about the method that + * was thrown. + * @param methodName - The publicly visible method name + * @param path - The dot-separated string form of a field path which will be + * split on dots. + * @param targetDoc - The document against which the field path will be + * evaluated. + */ function __PRIVATE_fieldPathFromDotSeparatedString(t, e, r) { + if (e.search(lt) >= 0) throw __PRIVATE_createError(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`, t, + /* hasConverter= */ !1, + /* path= */ void 0, r); + try { + return new FieldPath(...e.split("."))._internalPath; + } catch (n) { + throw __PRIVATE_createError(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`, t, + /* hasConverter= */ !1, + /* path= */ void 0, r); + } +} + +function __PRIVATE_createError(t, e, r, n, i) { + const s = n && !n.isEmpty(), o = void 0 !== i; + let a = `Function ${e}() called with invalid data`; + r && (a += " (via `toFirestore()`)"), a += ". "; + let u = ""; + return (s || o) && (u += " (found", s && (u += ` in field ${n}`), o && (u += ` in document ${i}`), + u += ")"), new FirestoreError(y, a + t + u); +} + +/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ function __PRIVATE_fieldMaskContains(t, e) { + return t.some((t => t.isEqual(e))); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ class DocumentSnapshot { + // Note: This class is stripped down version of the DocumentSnapshot in + // the legacy SDK. The changes are: + // - No support for SnapshotMetadata. + // - No support for SnapshotOptions. + /** @hideconstructor protected */ + constructor(t, e, r, n, i) { + this._firestore = t, this._userDataWriter = e, this._key = r, this._document = n, + this._converter = i; + } + /** Property of the `DocumentSnapshot` that provides the document's ID. */ get id() { + return this._key.path.lastSegment(); + } + /** + * The `DocumentReference` for the document included in the `DocumentSnapshot`. + */ get ref() { + return new DocumentReference(this._firestore, this._converter, this._key); + } + /** + * Signals whether or not the document at the snapshot's location exists. + * + * @returns true if the document exists. + */ exists() { + return null !== this._document; + } + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * @returns An `Object` containing all fields in the document or `undefined` + * if the document doesn't exist. + */ data() { + if (this._document) { + if (this._converter) { + // We only want to use the converter and create a new DocumentSnapshot + // if a converter has been provided. + const t = new QueryDocumentSnapshot(this._firestore, this._userDataWriter, this._key, this._document, + /* converter= */ null); + return this._converter.fromFirestore(t); + } + return this._userDataWriter.convertValue(this._document.data.value); + } + } + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + // We are using `any` here to avoid an explicit cast by our users. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get(t) { + if (this._document) { + const e = this._document.data.field(__PRIVATE_fieldPathFromArgument("DocumentSnapshot.get", t)); + if (null !== e) return this._userDataWriter.convertValue(e); + } + } +} + +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * @override + * @returns An `Object` containing all fields in the document. + */ + data() { + return super.data(); + } +} + +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ class QuerySnapshot { + /** @hideconstructor */ + constructor(t, e) { + this._docs = e, this.query = t; + } + /** An array of all the documents in the `QuerySnapshot`. */ get docs() { + return [ ...this._docs ]; + } + /** The number of documents in the `QuerySnapshot`. */ get size() { + return this.docs.length; + } + /** True if there are no documents in the `QuerySnapshot`. */ get empty() { + return 0 === this.docs.length; + } + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ forEach(t, e) { + this._docs.forEach(t, e); + } +} + +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ function snapshotEqual(t, e) { + return t = getModularInstance(t), e = getModularInstance(e), t instanceof DocumentSnapshot && e instanceof DocumentSnapshot ? t._firestore === e._firestore && t._key.isEqual(e._key) && (null === t._document ? null === e._document : t._document.isEqual(e._document)) && t._converter === e._converter : t instanceof QuerySnapshot && e instanceof QuerySnapshot && (queryEqual(t.query, e.query) && __PRIVATE_arrayEquals(t.docs, e.docs, snapshotEqual)); +} + +/** + * Helper that calls `fromDotSeparatedString()` but wraps any error thrown. + */ function __PRIVATE_fieldPathFromArgument(t, e) { + return "string" == typeof e ? __PRIVATE_fieldPathFromDotSeparatedString(t, e) : e instanceof FieldPath ? e._internalPath : e._delegate._internalPath; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An `AppliableConstraint` is an abstraction of a constraint that can be applied + * to a Firestore query. + */ +class AppliableConstraint {} + +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Firestore query. `QueryConstraint`s are created by invoking {@link where}, + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that + * also contains this `QueryConstraint`. + */ class QueryConstraint extends AppliableConstraint {} + +function query(t, e, ...r) { + let n = []; + e instanceof AppliableConstraint && n.push(e), n = n.concat(r), function __PRIVATE_validateQueryConstraintArray(t) { + const e = t.filter((t => t instanceof QueryCompositeFilterConstraint)).length, r = t.filter((t => t instanceof QueryFieldFilterConstraint)).length; + if (e > 1 || e > 0 && r > 0) throw new FirestoreError(y, "InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`."); + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Converts Firestore's internal types to the JavaScript types that we expose + * to the user. + * + * @internal + */ (n); + for (const e of n) t = e._apply(t); + return t; +} + +/** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ class QueryFieldFilterConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(t, e, r) { + super(), this._field = t, this._op = e, this._value = r, + /** The type of this query constraint */ + this.type = "where"; + } + static _create(t, e, r) { + return new QueryFieldFilterConstraint(t, e, r); + } + _apply(t) { + const e = this._parse(t); + return __PRIVATE_validateNewFieldFilter(t._query, e), new Query(t.firestore, t.converter, __PRIVATE_queryWithAddedFilter(t._query, e)); + } + _parse(t) { + const e = __PRIVATE_newUserDataReader(t.firestore), r = function __PRIVATE_newQueryFilter(t, e, r, n, i, s, o) { + let a; + if (i.isKeyField()) { + if ("array-contains" /* Operator.ARRAY_CONTAINS */ === s || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === s) throw new FirestoreError(y, `Invalid Query. You can't perform '${s}' queries on documentId().`); + if ("in" /* Operator.IN */ === s || "not-in" /* Operator.NOT_IN */ === s) { + __PRIVATE_validateDisjunctiveFilterElements(o, s); + const e = []; + for (const r of o) e.push(__PRIVATE_parseDocumentIdValue(n, t, r)); + a = { + arrayValue: { + values: e + } + }; + } else a = __PRIVATE_parseDocumentIdValue(n, t, o); + } else "in" /* Operator.IN */ !== s && "not-in" /* Operator.NOT_IN */ !== s && "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ !== s || __PRIVATE_validateDisjunctiveFilterElements(o, s), + a = __PRIVATE_parseQueryValue(r, e, o, + /* allowArrays= */ "in" /* Operator.IN */ === s || "not-in" /* Operator.NOT_IN */ === s); + const u = FieldFilter.create(i, s, a); + return u; + }(t._query, "where", e, t.firestore._databaseId, this._field, this._op, this._value); + return r; + } +} + +/** + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. + * + * @param fieldPath - The path to compare + * @param opStr - The operation string (e.g "<", "<=", "==", "<", + * "<=", "!="). + * @param value - The value for comparison + * @returns The created {@link QueryFieldFilterConstraint}. + */ function where(t, e, r) { + const n = e, i = __PRIVATE_fieldPathFromArgument("where", t); + return QueryFieldFilterConstraint._create(i, n, r); +} + +/** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ class QueryCompositeFilterConstraint extends AppliableConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + t, e) { + super(), this.type = t, this._queryConstraints = e; + } + static _create(t, e) { + return new QueryCompositeFilterConstraint(t, e); + } + _parse(t) { + const e = this._queryConstraints.map((e => e._parse(t))).filter((t => t.getFilters().length > 0)); + return 1 === e.length ? e[0] : CompositeFilter.create(e, this._getOperator()); + } + _apply(t) { + const e = this._parse(t); + return 0 === e.getFilters().length ? t : (function __PRIVATE_validateNewFilter(t, e) { + let r = t; + const n = e.getFlattenedFilters(); + for (const t of n) __PRIVATE_validateNewFieldFilter(r, t), r = __PRIVATE_queryWithAddedFilter(r, t); + } + // Checks if any of the provided filter operators are included in the given list of filters and + // returns the first one that is, or null if none are. + (t._query, e), new Query(t.firestore, t.converter, __PRIVATE_queryWithAddedFilter(t._query, e))); + } + _getQueryConstraints() { + return this._queryConstraints; + } + _getOperator() { + return "and" === this.type ? "and" /* CompositeOperator.AND */ : "or" /* CompositeOperator.OR */; + } +} + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ function or(...t) { + // Only support QueryFilterConstraints + return t.forEach((t => __PRIVATE_validateQueryFilterConstraint("or", t))), QueryCompositeFilterConstraint._create("or" /* CompositeOperator.OR */ , t); +} + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ function and(...t) { + // Only support QueryFilterConstraints + return t.forEach((t => __PRIVATE_validateQueryFilterConstraint("and", t))), QueryCompositeFilterConstraint._create("and" /* CompositeOperator.AND */ , t); +} + +/** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ class QueryOrderByConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(t, e) { + super(), this._field = t, this._direction = e, + /** The type of this query constraint */ + this.type = "orderBy"; + } + static _create(t, e) { + return new QueryOrderByConstraint(t, e); + } + _apply(t) { + const e = function __PRIVATE_newQueryOrderBy(t, e, r) { + if (null !== t.startAt) throw new FirestoreError(y, "Invalid query. You must not call startAt() or startAfter() before calling orderBy()."); + if (null !== t.endAt) throw new FirestoreError(y, "Invalid query. You must not call endAt() or endBefore() before calling orderBy()."); + const n = new OrderBy(e, r); + return n; + } + /** + * Create a `Bound` from a query and a document. + * + * Note that the `Bound` will always include the key of the document + * and so only the provided document will compare equal to the returned + * position. + * + * Will throw if the document does not contain all fields of the order by + * of the query or if any of the fields in the order by are an uncommitted + * server timestamp. + */ (t._query, this._field, this._direction); + return new Query(t.firestore, t.converter, function __PRIVATE_queryWithAddedOrderBy(t, e) { + // TODO(dimond): validate that orderBy does not list the same key twice. + const r = t.explicitOrderBy.concat([ e ]); + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, r, t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt); + }(t._query, e)); + } +} + +/** + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the + * specified field, optionally in descending order instead of ascending. + * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * + * @param fieldPath - The field to sort by. + * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @returns The created {@link QueryOrderByConstraint}. + */ function orderBy(t, e = "asc") { + const r = e, n = __PRIVATE_fieldPathFromArgument("orderBy", t); + return QueryOrderByConstraint._create(n, r); +} + +/** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ class QueryLimitConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + t, e, r) { + super(), this.type = t, this._limit = e, this._limitType = r; + } + static _create(t, e, r) { + return new QueryLimitConstraint(t, e, r); + } + _apply(t) { + return new Query(t.firestore, t.converter, function __PRIVATE_queryWithLimit(t, e, r) { + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), e, r, t.startAt, t.endAt); + }(t._query, this._limit, this._limitType)); + } +} + +/** + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ function limit(t) { + return __PRIVATE_validatePositiveNumber("limit", t), QueryLimitConstraint._create("limit", t, "F" /* LimitType.First */); +} + +/** + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. + * + * You must specify at least one `orderBy` clause for `limitToLast` queries, + * otherwise an exception will be thrown during execution. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ function limitToLast(t) { + return __PRIVATE_validatePositiveNumber("limitToLast", t), QueryLimitConstraint._create("limitToLast", t, "L" /* LimitType.Last */); +} + +/** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ class QueryStartAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + t, e, r) { + super(), this.type = t, this._docOrFields = e, this._inclusive = r; + } + static _create(t, e, r) { + return new QueryStartAtConstraint(t, e, r); + } + _apply(t) { + const e = __PRIVATE_newQueryBoundFromDocOrFields(t, this.type, this._docOrFields, this._inclusive); + return new Query(t.firestore, t.converter, function __PRIVATE_queryWithStartAt(t, e) { + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, e, t.endAt); + }(t._query, e)); + } +} + +function startAt(...t) { + return QueryStartAtConstraint._create("startAt", t, + /*inclusive=*/ !0); +} + +function startAfter(...t) { + return QueryStartAtConstraint._create("startAfter", t, + /*inclusive=*/ !1); +} + +/** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ class QueryEndAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + t, e, r) { + super(), this.type = t, this._docOrFields = e, this._inclusive = r; + } + static _create(t, e, r) { + return new QueryEndAtConstraint(t, e, r); + } + _apply(t) { + const e = __PRIVATE_newQueryBoundFromDocOrFields(t, this.type, this._docOrFields, this._inclusive); + return new Query(t.firestore, t.converter, function __PRIVATE_queryWithEndAt(t, e) { + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, e); + }(t._query, e)); + } +} + +function endBefore(...t) { + return QueryEndAtConstraint._create("endBefore", t, + /*inclusive=*/ !1); +} + +function endAt(...t) { + return QueryEndAtConstraint._create("endAt", t, + /*inclusive=*/ !0); +} + +/** Helper function to create a bound from a document or fields */ function __PRIVATE_newQueryBoundFromDocOrFields(t, e, r, n) { + if (r[0] = getModularInstance(r[0]), r[0] instanceof DocumentSnapshot) return function __PRIVATE_newQueryBoundFromDocument(t, e, r, n, i) { + if (!n) throw new FirestoreError(w, `Can't use a DocumentSnapshot that doesn't exist for ${r}().`); + const s = []; + // Because people expect to continue/end a query at the exact document + // provided, we need to use the implicit sort order rather than the explicit + // sort order, because it's guaranteed to contain the document key. That way + // the position becomes unambiguous and the query continues/ends exactly at + // the provided document. Without the key (by using the explicit sort + // orders), multiple documents could match the position, yielding duplicate + // results. + for (const r of __PRIVATE_queryNormalizedOrderBy(t)) if (r.field.isKeyField()) s.push(__PRIVATE_refValue(e, n.key)); else { + const t = n.data.field(r.field); + if (__PRIVATE_isServerTimestamp(t)) throw new FirestoreError(y, 'Invalid query. You are trying to start or end a query using a document for which the field "' + r.field + '" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)'); + if (null === t) { + const t = r.field.canonicalString(); + throw new FirestoreError(y, `Invalid query. You are trying to start or end a query using a document for which the field '${t}' (used as the orderBy) does not exist.`); + } + s.push(t); + } + return new Bound(s, i); + } + /** + * Converts a list of field values to a `Bound` for the given query. + */ (t._query, t.firestore._databaseId, e, r[0]._document, n); + { + const i = __PRIVATE_newUserDataReader(t.firestore); + return function __PRIVATE_newQueryBoundFromFields(t, e, r, n, i, s) { + // Use explicit order by's because it has to match the query the user made + const o = t.explicitOrderBy; + if (i.length > o.length) throw new FirestoreError(y, `Too many arguments provided to ${n}(). The number of arguments must be less than or equal to the number of orderBy() clauses`); + const a = []; + for (let s = 0; s < i.length; s++) { + const u = i[s]; + if (o[s].field.isKeyField()) { + if ("string" != typeof u) throw new FirestoreError(y, `Invalid query. Expected a string for document ID in ${n}(), but got a ${typeof u}`); + if (!__PRIVATE_isCollectionGroupQuery(t) && -1 !== u.indexOf("/")) throw new FirestoreError(y, `Invalid query. When querying a collection and ordering by documentId(), the value passed to ${n}() must be a plain document ID, but '${u}' contains a slash.`); + const r = t.path.child(ResourcePath.fromString(u)); + if (!DocumentKey.isDocumentKey(r)) throw new FirestoreError(y, `Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${n}() must result in a valid document path, but '${r}' is not because it contains an odd number of segments.`); + const i = new DocumentKey(r); + a.push(__PRIVATE_refValue(e, i)); + } else { + const t = __PRIVATE_parseQueryValue(r, n, u); + a.push(t); + } + } + return new Bound(a, s); + } + /** + * Parses the given `documentIdValue` into a `ReferenceValue`, throwing + * appropriate errors if the value is anything other than a `DocumentReference` + * or `string`, or if the string is malformed. + */ (t._query, t.firestore._databaseId, i, e, r, n); + } +} + +function __PRIVATE_parseDocumentIdValue(t, e, r) { + if ("string" == typeof (r = getModularInstance(r))) { + if ("" === r) throw new FirestoreError(y, "Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string."); + if (!__PRIVATE_isCollectionGroupQuery(e) && -1 !== r.indexOf("/")) throw new FirestoreError(y, `Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${r}' contains a '/' character.`); + const n = e.path.child(ResourcePath.fromString(r)); + if (!DocumentKey.isDocumentKey(n)) throw new FirestoreError(y, `Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${n}' is not because it has an odd number of segments (${n.length}).`); + return __PRIVATE_refValue(t, new DocumentKey(n)); + } + if (r instanceof DocumentReference) return __PRIVATE_refValue(t, r._key); + throw new FirestoreError(y, `Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${__PRIVATE_valueDescription(r)}.`); +} + +/** + * Validates that the value passed into a disjunctive filter satisfies all + * array requirements. + */ function __PRIVATE_validateDisjunctiveFilterElements(t, e) { + if (!Array.isArray(t) || 0 === t.length) throw new FirestoreError(y, `Invalid Query. A non-empty array is required for '${e.toString()}' filters.`); +} + +/** + * Given an operator, returns the set of operators that cannot be used with it. + * + * This is not a comprehensive check, and this function should be removed in the + * long term. Validations should occur in the Firestore backend. + * + * Operators in a query must adhere to the following set of rules: + * 1. Only one inequality per query. + * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators. + */ function __PRIVATE_validateNewFieldFilter(t, e) { + const r = function __PRIVATE_findOpInsideFilters(t, e) { + for (const r of t) for (const t of r.getFlattenedFilters()) if (e.indexOf(t.op) >= 0) return t.op; + return null; + }(t.filters, function __PRIVATE_conflictingOps(t) { + switch (t) { + case "!=" /* Operator.NOT_EQUAL */ : + return [ "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ]; + + case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ : + case "in" /* Operator.IN */ : + return [ "not-in" /* Operator.NOT_IN */ ]; + + case "not-in" /* Operator.NOT_IN */ : + return [ "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , "in" /* Operator.IN */ , "not-in" /* Operator.NOT_IN */ , "!=" /* Operator.NOT_EQUAL */ ]; + + default: + return []; + } + }(e.op)); + if (null !== r) + // Special case when it's a duplicate op to give a slightly clearer error message. + throw r === e.op ? new FirestoreError(y, `Invalid query. You cannot use more than one '${e.op.toString()}' filter.`) : new FirestoreError(y, `Invalid query. You cannot use '${e.op.toString()}' filters with '${r.toString()}' filters.`); +} + +function __PRIVATE_validateQueryFilterConstraint(t, e) { + if (!(e instanceof QueryFieldFilterConstraint || e instanceof QueryCompositeFilterConstraint)) throw new FirestoreError(y, `Function ${t}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`); +} + +class AbstractUserDataWriter { + convertValue(t, e = "none") { + switch (__PRIVATE_typeOrder(t)) { + case 0 /* TypeOrder.NullValue */ : + return null; + + case 1 /* TypeOrder.BooleanValue */ : + return t.booleanValue; + + case 2 /* TypeOrder.NumberValue */ : + return __PRIVATE_normalizeNumber(t.integerValue || t.doubleValue); + + case 3 /* TypeOrder.TimestampValue */ : + return this.convertTimestamp(t.timestampValue); + + case 4 /* TypeOrder.ServerTimestampValue */ : + return this.convertServerTimestamp(t, e); + + case 5 /* TypeOrder.StringValue */ : + return t.stringValue; + + case 6 /* TypeOrder.BlobValue */ : + return this.convertBytes(__PRIVATE_normalizeByteString(t.bytesValue)); + + case 7 /* TypeOrder.RefValue */ : + return this.convertReference(t.referenceValue); + + case 8 /* TypeOrder.GeoPointValue */ : + return this.convertGeoPoint(t.geoPointValue); + + case 9 /* TypeOrder.ArrayValue */ : + return this.convertArray(t.arrayValue, e); + + case 11 /* TypeOrder.ObjectValue */ : + return this.convertObject(t.mapValue, e); + + case 10 /* TypeOrder.VectorValue */ : + return this.convertVectorValue(t.mapValue); + + default: + throw fail(62114, { + value: t + }); + } + } + convertObject(t, e) { + return this.convertObjectMap(t.fields, e); + } + /** + * @internal + */ convertObjectMap(t, e = "none") { + const r = {}; + return forEach(t, ((t, n) => { + r[t] = this.convertValue(n, e); + })), r; + } + /** + * @internal + */ convertVectorValue(t) { + const e = t.fields?.[et].arrayValue?.values?.map((t => __PRIVATE_normalizeNumber(t.doubleValue))); + return new VectorValue(e); + } + convertGeoPoint(t) { + return new GeoPoint(__PRIVATE_normalizeNumber(t.latitude), __PRIVATE_normalizeNumber(t.longitude)); + } + convertArray(t, e) { + return (t.values || []).map((t => this.convertValue(t, e))); + } + convertServerTimestamp(t, e) { + switch (e) { + case "previous": + const r = __PRIVATE_getPreviousValue(t); + return null == r ? null : this.convertValue(r, e); + + case "estimate": + return this.convertTimestamp(__PRIVATE_getLocalWriteTime(t)); + + default: + return null; + } + } + convertTimestamp(t) { + const e = __PRIVATE_normalizeTimestamp(t); + return new Timestamp(e.seconds, e.nanos); + } + convertDocumentKey(t, e) { + const r = ResourcePath.fromString(t); + __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(r), 9688, { + name: t + }); + const n = new DatabaseId(r.get(1), r.get(3)), i = new DocumentKey(r.popFirst(5)); + return n.isEqual(e) || + // TODO(b/64130202): Somehow support foreign references. + __PRIVATE_logError(`Document ${i} contains a document reference within a different database (${n.projectId}/${n.database}) which is not supported. It will be treated as a reference in the current database (${e.projectId}/${e.database}) instead.`), + i; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Converts custom model object of type T into `DocumentData` by applying the + * converter if it exists. + * + * This function is used when converting user objects to `DocumentData` + * because we want to provide the user with a more specific error message if + * their `set()` or fails due to invalid data originating from a `toFirestore()` + * call. + */ function __PRIVATE_applyFirestoreDataConverter(t, e, r) { + let n; + // Cast to `any` in order to satisfy the union type constraint on + // toFirestore(). + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return n = t ? r && (r.merge || r.mergeFields) ? t.toFirestore(e, r) : t.toFirestore(e) : e, + n; +} + +class __PRIVATE_LiteUserDataWriter extends AbstractUserDataWriter { + constructor(t) { + super(), this.firestore = t; + } + convertBytes(t) { + return new Bytes(t); + } + convertReference(t) { + const e = this.convertDocumentKey(t, this.firestore._databaseId); + return new DocumentReference(this.firestore, /* converter= */ null, e); + } +} + +/** + * Reads the document referred to by the specified document reference. + * + * All documents are directly fetched from the server, even if the document was + * previously read or modified. Recent modifications are only reflected in the + * retrieved `DocumentSnapshot` if they have already been applied by the + * backend. If the client is offline, the read fails. If you like to use + * caching or see local modifications, please use the full Firestore SDK. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the current + * document contents. + */ function getDoc(t) { + const e = __PRIVATE_getDatastore((t = __PRIVATE_cast(t, DocumentReference)).firestore), r = new __PRIVATE_LiteUserDataWriter(t.firestore); + return __PRIVATE_invokeBatchGetDocumentsRpc(e, [ t._key ]).then((e => { + __PRIVATE_hardAssert(1 === e.length, 15618); + const n = e[0]; + return new DocumentSnapshot(t.firestore, r, t._key, n.isFoundDocument() ? n : null, t.converter); + })); +} + +/** + * Executes the query and returns the results as a {@link QuerySnapshot}. + * + * All queries are executed directly by the server, even if the query was + * previously executed. Recent modifications are only reflected in the retrieved + * results if they have already been applied by the backend. If the client is + * offline, the operation fails. To see previously cached result and local + * modifications, use the full Firestore SDK. + * + * @param query - The `Query` to execute. + * @returns A Promise that will be resolved with the results of the query. + */ function getDocs(t) { + (function __PRIVATE_validateHasExplicitOrderByForLimitToLast(t) { + if ("L" /* LimitType.Last */ === t.limitType && 0 === t.explicitOrderBy.length) throw new FirestoreError(O, "limitToLast() queries require specifying at least one orderBy() clause"); + })((t = __PRIVATE_cast(t, Query))._query); + const e = __PRIVATE_getDatastore(t.firestore), r = new __PRIVATE_LiteUserDataWriter(t.firestore); + return __PRIVATE_invokeRunQueryRpc(e, t._query).then((e => { + const n = e.map((e => new QueryDocumentSnapshot(t.firestore, r, e.key, e, t.converter))); + return "L" /* LimitType.Last */ === t._query.limitType && + // Limit to last queries reverse the orderBy constraint that was + // specified by the user. As such, we need to reverse the order of the + // results to return the documents in the expected order. + n.reverse(), new QuerySnapshot(t, n); + })); +} + +function setDoc(t, e, r) { + const n = __PRIVATE_applyFirestoreDataConverter((t = __PRIVATE_cast(t, DocumentReference)).converter, e, r), i = __PRIVATE_parseSetData(__PRIVATE_newUserDataReader(t.firestore), "setDoc", t._key, n, null !== t.converter, r); + return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore(t.firestore), [ i.toMutation(t._key, Precondition.none()) ]); +} + +function updateDoc(t, e, r, ...n) { + const i = __PRIVATE_newUserDataReader((t = __PRIVATE_cast(t, DocumentReference)).firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + let s; + s = "string" == typeof (e = getModularInstance(e)) || e instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(i, "updateDoc", t._key, e, r, n) : __PRIVATE_parseUpdateData(i, "updateDoc", t._key, e); + return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore(t.firestore), [ s.toMutation(t._key, Precondition.exists(!0)) ]); +} + +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * The deletion will only be reflected in document reads that occur after the + * returned promise resolves. If the client is offline, the + * delete fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to delete. + * @returns A `Promise` resolved once the document has been successfully + * deleted from the backend. + */ function deleteDoc(t) { + return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore((t = __PRIVATE_cast(t, DocumentReference)).firestore), [ new __PRIVATE_DeleteMutation(t._key, Precondition.none()) ]); +} + +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend. + */ function addDoc(t, e) { + const r = doc(t = __PRIVATE_cast(t, CollectionReference)), n = __PRIVATE_applyFirestoreDataConverter(t.converter, e), i = __PRIVATE_parseSetData(__PRIVATE_newUserDataReader(t.firestore), "addDoc", r._key, n, null !== r.converter, {}); + return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore(t.firestore), [ i.toMutation(r._key, Precondition.exists(!1)) ]).then((() => r)); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ function getCount(t) { + return getAggregate(t, { + count: count() + }); +} + +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregate(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ function getAggregate(t, e) { + const r = __PRIVATE_cast(t.firestore, Firestore), n = __PRIVATE_getDatastore(r), i = function __PRIVATE_mapToArray(t, e) { + const r = []; + for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && r.push(e(t[n], n, t)); + return r; + }(e, ((t, e) => new __PRIVATE_AggregateImpl(e, t.aggregateType, t._internalFieldPath))); + // Run the aggregation and convert the results + return __PRIVATE_invokeRunAggregationQueryRpc(n, t._query, i).then((e => function __PRIVATE_convertToAggregateQuerySnapshot(t, e, r) { + const n = new __PRIVATE_LiteUserDataWriter(t), i = new AggregateQuerySnapshot(e, n, r); + return i; + } + /** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ (r, t, e))); +} + +function sum(t) { + return new AggregateField("sum", __PRIVATE_fieldPathFromArgument$1("sum", t)); +} + +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ function average(t) { + return new AggregateField("avg", __PRIVATE_fieldPathFromArgument$1("average", t)); +} + +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ function count() { + return new AggregateField("count"); +} + +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ function aggregateFieldEqual(t, e) { + return t instanceof AggregateField && e instanceof AggregateField && t.aggregateType === e.aggregateType && t._internalFieldPath?.canonicalString() === e._internalFieldPath?.canonicalString(); +} + +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ function aggregateQuerySnapshotEqual(t, e) { + return queryEqual(t.query, e.query) && deepEqual(t.data(), e.data()); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. + */ function deleteField() { + return new __PRIVATE_DeleteFieldValueImpl("deleteField"); +} + +/** + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to + * include a server-generated timestamp in the written data. + */ function serverTimestamp() { + return new __PRIVATE_ServerTimestampFieldValueImpl("serverTimestamp"); +} + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array + * value that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements - The elements to union into the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()`. + */ function arrayUnion(...t) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new __PRIVATE_ArrayUnionFieldValueImpl("arrayUnion", t); +} + +/** + * Returns a special value that can be used with {@link (setDoc:1)} or {@link + * updateDoc:1} that tells the server to remove the given elements from any + * array value that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is not + * already an array it will be overwritten with an empty array. + * + * @param elements - The elements to remove from the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ function arrayRemove(...t) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new __PRIVATE_ArrayRemoveFieldValueImpl("arrayRemove", t); +} + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by + * the given value. + * + * If either the operand or the current field value uses floating point + * precision, all arithmetic follows IEEE 754 semantics. If both values are + * integers, values outside of JavaScript's safe number range + * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to + * precision loss. Furthermore, once processed by the Firestore backend, all + * integer operations are capped between -2^63 and 2^63-1. + * + * If the current field value is not of type `number`, or if the field does not + * yet exist, the transformation sets the field to the given value. + * + * @param n - The value to increment by. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ function increment(t) { + return new __PRIVATE_NumericIncrementFieldValueImpl("increment", t); +} + +/** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ function vector(t) { + return new VectorValue(t); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It + * provides methods for adding writes to the write batch. None of the writes + * will be committed (or visible locally) until {@link WriteBatch.commit} is + * called. + */ class WriteBatch { + /** @hideconstructor */ + constructor(t, e) { + this._firestore = t, this._commitHandler = e, this._mutations = [], this._committed = !1, + this._dataReader = __PRIVATE_newUserDataReader(t); + } + set(t, e, r) { + this._verifyNotCommitted(); + const n = __PRIVATE_validateReference(t, this._firestore), i = __PRIVATE_applyFirestoreDataConverter(n.converter, e, r), s = __PRIVATE_parseSetData(this._dataReader, "WriteBatch.set", n._key, i, null !== n.converter, r); + return this._mutations.push(s.toMutation(n._key, Precondition.none())), this; + } + update(t, e, r, ...n) { + this._verifyNotCommitted(); + const i = __PRIVATE_validateReference(t, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + let s; + return s = "string" == typeof (e = getModularInstance(e)) || e instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(this._dataReader, "WriteBatch.update", i._key, e, r, n) : __PRIVATE_parseUpdateData(this._dataReader, "WriteBatch.update", i._key, e), + this._mutations.push(s.toMutation(i._key, Precondition.exists(!0))), this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ delete(t) { + this._verifyNotCommitted(); + const e = __PRIVATE_validateReference(t, this._firestore); + return this._mutations = this._mutations.concat(new __PRIVATE_DeleteMutation(e._key, Precondition.none())), + this; + } + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `Promise` resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit (note that it won't + * resolve while you're offline). + */ commit() { + return this._verifyNotCommitted(), this._committed = !0, this._mutations.length > 0 ? this._commitHandler(this._mutations) : Promise.resolve(); + } + _verifyNotCommitted() { + if (this._committed) throw new FirestoreError(S, "A write batch can no longer be used after commit() has been called."); + } +} + +function __PRIVATE_validateReference(t, e) { + if ((t = getModularInstance(t)).firestore !== e) throw new FirestoreError(y, "Provided document reference is from a different Firestore instance."); + return t; +} + +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single WriteBatch + * is 500. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `WriteBatch` that can be used to atomically execute multiple + * writes. + */ function writeBatch(t) { + const e = __PRIVATE_getDatastore(t = __PRIVATE_cast(t, Firestore)); + return new WriteBatch(t, (t => __PRIVATE_invokeCommitRpc(e, t))); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Internal transaction object responsible for accumulating the mutations to + * perform and the base versions for any documents read. + */ class Transaction$1 { + constructor(t) { + this.datastore = t, + // The version of each document that was read during this transaction. + this.readVersions = new Map, this.mutations = [], this.committed = !1, + /** + * A deferred usage error that occurred previously in this transaction that + * will cause the transaction to fail once it actually commits. + */ + this.lastTransactionError = null, + /** + * Set of documents that have been written in the transaction. + * + * When there's more than one write to the same key in a transaction, any + * writes after the first are handled differently. + */ + this.writtenDocs = new Set; + } + async lookup(t) { + if (this.ensureCommitNotCalled(), this.mutations.length > 0) throw this.lastTransactionError = new FirestoreError(y, "Firestore transactions require all reads to be executed before all writes."), + this.lastTransactionError; + const e = await __PRIVATE_invokeBatchGetDocumentsRpc(this.datastore, t); + return e.forEach((t => this.recordVersion(t))), e; + } + set(t, e) { + this.write(e.toMutation(t, this.precondition(t))), this.writtenDocs.add(t.toString()); + } + update(t, e) { + try { + this.write(e.toMutation(t, this.preconditionForUpdate(t))); + } catch (t) { + this.lastTransactionError = t; + } + this.writtenDocs.add(t.toString()); + } + delete(t) { + this.write(new __PRIVATE_DeleteMutation(t, this.precondition(t))), this.writtenDocs.add(t.toString()); + } + async commit() { + if (this.ensureCommitNotCalled(), this.lastTransactionError) throw this.lastTransactionError; + const t = this.readVersions; + // For each mutation, note that the doc was written. + this.mutations.forEach((e => { + t.delete(e.key.toString()); + })), + // For each document that was read but not written to, we want to perform + // a `verify` operation. + t.forEach(((t, e) => { + const r = DocumentKey.fromPath(e); + this.mutations.push(new __PRIVATE_VerifyMutation(r, this.precondition(r))); + })), await __PRIVATE_invokeCommitRpc(this.datastore, this.mutations), this.committed = !0; + } + recordVersion(t) { + let e; + if (t.isFoundDocument()) e = t.version; else { + if (!t.isNoDocument()) throw fail(50498, { + Rt: t.constructor.name + }); + // Represent a deleted doc using SnapshotVersion.min(). + e = SnapshotVersion.min(); + } + const r = this.readVersions.get(t.key.toString()); + if (r) { + if (!e.isEqual(r)) + // This transaction will fail no matter what. + throw new FirestoreError(C, "Document version changed between two reads."); + } else this.readVersions.set(t.key.toString(), e); + } + /** + * Returns the version of this document when it was read in this transaction, + * as a precondition, or no precondition if it was not read. + */ precondition(t) { + const e = this.readVersions.get(t.toString()); + return !this.writtenDocs.has(t.toString()) && e ? e.isEqual(SnapshotVersion.min()) ? Precondition.exists(!1) : Precondition.updateTime(e) : Precondition.none(); + } + /** + * Returns the precondition for a document if the operation is an update. + */ preconditionForUpdate(t) { + const e = this.readVersions.get(t.toString()); + // The first time a document is written, we want to take into account the + // read time and existence + if (!this.writtenDocs.has(t.toString()) && e) { + if (e.isEqual(SnapshotVersion.min())) + // The document doesn't exist, so fail the transaction. + // This has to be validated locally because you can't send a + // precondition that a document does not exist without changing the + // semantics of the backend write to be an insert. This is the reverse + // of what we want, since we want to assert that the document doesn't + // exist but then send the update and have it fail. Since we can't + // express that to the backend, we have to validate locally. + // Note: this can change once we can send separate verify writes in the + // transaction. + throw new FirestoreError(y, "Can't update a document that doesn't exist."); + // Document exists, base precondition on document update time. + return Precondition.updateTime(e); + } + // Document was not read, so we just use the preconditions for a blind + // update. + return Precondition.exists(!0); + } + write(t) { + this.ensureCommitNotCalled(), this.mutations.push(t); + } + ensureCommitNotCalled() {} +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const ht = { + maxAttempts: 5 +}; + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * TransactionRunner encapsulates the logic needed to run and retry transactions + * with backoff. + */ +class __PRIVATE_TransactionRunner { + constructor(t, e, r, n, i) { + this.asyncQueue = t, this.datastore = e, this.options = r, this.updateFunction = n, + this.deferred = i, this.Vt = r.maxAttempts, this.It = new __PRIVATE_ExponentialBackoff(this.asyncQueue, "transaction_retry" /* TimerId.TransactionRetry */); + } + /** Runs the transaction and sets the result on deferred. */ yt() { + this.Vt -= 1, this.gt(); + } + gt() { + this.It.Z((async () => { + const t = new Transaction$1(this.datastore), e = this.wt(t); + e && e.then((e => { + this.asyncQueue.enqueueAndForget((() => t.commit().then((() => { + this.deferred.resolve(e); + })).catch((t => { + this.Ft(t); + })))); + })).catch((t => { + this.Ft(t); + })); + })); + } + wt(t) { + try { + const e = this.updateFunction(t); + return !__PRIVATE_isNullOrUndefined(e) && e.catch && e.then ? e : (this.deferred.reject(Error("Transaction callback must return a Promise")), + null); + } catch (t) { + // Do not retry errors thrown by user provided updateFunction. + return this.deferred.reject(t), null; + } + } + Ft(t) { + this.Vt > 0 && this.vt(t) ? (this.Vt -= 1, this.asyncQueue.enqueueAndForget((() => (this.gt(), + Promise.resolve())))) : this.deferred.reject(t); + } + vt(t) { + if ("FirebaseError" === t?.name) { + // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and + // non-matching document versions with ABORTED. These errors should be retried. + const e = t.code; + return "aborted" === e || "failed-precondition" === e || "already-exists" === e || ! + /** + * Determines whether an error code represents a permanent error when received + * in response to a non-write operation. + * + * See isPermanentWriteError for classifying write errors. + */ + function __PRIVATE_isPermanentError(t) { + switch (t) { + case V: + return fail(64938); + + case I: + case p: + case g: + case b: + case q: + case B: + // Unauthenticated means something went wrong with our token and we need + // to retry with new credentials which will happen automatically. + case D: + return !1; + + case y: + case w: + case F: + case v: + case S: + // Aborted might be retried in some scenarios, but that is dependent on + // the context and should handled individually by the calling code. + // See https://cloud.google.com/apis/design/errors. + case C: + case N: + case O: + case $: + return !0; + + default: + return fail(15467, { + code: t + }); + } + }(e); + } + return !1; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** The Platform's 'document' implementation or null if not available. */ function getDocument() { + // `document` is not always available, e.g. in ReactNative and WebWorkers. + // eslint-disable-next-line no-restricted-globals + return "undefined" != typeof document ? document : null; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents an operation scheduled to be run in the future on an AsyncQueue. + * + * It is created via DelayedOperation.createAndSchedule(). + * + * Supports cancellation (via cancel()) and early execution (via skipDelay()). + * + * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type + * in newer versions of TypeScript defines `finally`, which is not available in + * IE. + */ class DelayedOperation { + constructor(t, e, r, n, i) { + this.asyncQueue = t, this.timerId = e, this.targetTimeMs = r, this.op = n, this.removalCallback = i, + this.deferred = new __PRIVATE_Deferred, this.then = this.deferred.promise.then.bind(this.deferred.promise), + // It's normal for the deferred promise to be canceled (due to cancellation) + // and so we attach a dummy catch callback to avoid + // 'UnhandledPromiseRejectionWarning' log spam. + this.deferred.promise.catch((t => {})); + } + get promise() { + return this.deferred.promise; + } + /** + * Creates and returns a DelayedOperation that has been scheduled to be + * executed on the provided asyncQueue after the provided delayMs. + * + * @param asyncQueue - The queue to schedule the operation on. + * @param id - A Timer ID identifying the type of operation this is. + * @param delayMs - The delay (ms) before the operation should be scheduled. + * @param op - The operation to run. + * @param removalCallback - A callback to be called synchronously once the + * operation is executed or canceled, notifying the AsyncQueue to remove it + * from its delayedOperations list. + * PORTING NOTE: This exists to prevent making removeDelayedOperation() and + * the DelayedOperation class public. + */ static createAndSchedule(t, e, r, n, i) { + const s = Date.now() + r, o = new DelayedOperation(t, e, s, n, i); + return o.start(r), o; + } + /** + * Starts the timer. This is called immediately after construction by + * createAndSchedule(). + */ start(t) { + this.timerHandle = setTimeout((() => this.handleDelayElapsed()), t); + } + /** + * Queues the operation to run immediately (if it hasn't already been run or + * canceled). + */ skipDelay() { + return this.handleDelayElapsed(); + } + /** + * Cancels the operation if it hasn't already been executed or canceled. The + * promise will be rejected. + * + * As long as the operation has not yet been run, calling cancel() provides a + * guarantee that the operation will not be run. + */ cancel(t) { + null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new FirestoreError(I, "Operation cancelled" + (t ? ": " + t : "")))); + } + handleDelayElapsed() { + this.asyncQueue.enqueueAndForget((() => null !== this.timerHandle ? (this.clearTimeout(), + this.op().then((t => this.deferred.resolve(t)))) : Promise.resolve())); + } + clearTimeout() { + null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle), + this.timerHandle = null); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const ft = "AsyncQueue"; + +class __PRIVATE_AsyncQueueImpl { + constructor(t = Promise.resolve()) { + // A list of retryable operations. Retryable operations are run in order and + // retried with backoff. + this.Dt = [], + // Is this AsyncQueue being shut down? Once it is set to true, it will not + // be changed again. + this.bt = !1, + // Operations scheduled to be queued in the future. Operations are + // automatically removed after they are run or canceled. + this.St = [], + // visible for testing + this.Ct = null, + // Flag set while there's an outstanding AsyncQueue operation, used for + // assertion sanity-checks. + this.Nt = !1, + // Enabled during shutdown on Safari to prevent future access to IndexedDB. + this.Ot = !1, + // List of TimerIds to fast-forward delays for. + this.qt = [], + // Backoff timer used to schedule retries for retryable operations + this.It = new __PRIVATE_ExponentialBackoff(this, "async_queue_retry" /* TimerId.AsyncQueueRetry */), + // Visibility handler that triggers an immediate retry of all retryable + // operations. Meant to speed up recovery when we regain file system access + // after page comes into foreground. + this.Bt = () => { + const t = getDocument(); + t && __PRIVATE_logDebug(ft, "Visibility state changed to " + t.visibilityState), + this.It.tt(); + }, this.$t = t; + const e = getDocument(); + e && "function" == typeof e.addEventListener && e.addEventListener("visibilitychange", this.Bt); + } + get isShuttingDown() { + return this.bt; + } + /** + * Adds a new operation to the queue without waiting for it to complete (i.e. + * we ignore the Promise result). + */ enqueueAndForget(t) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.enqueue(t); + } + enqueueAndForgetEvenWhileRestricted(t) { + this.Qt(), + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.kt(t); + } + enterRestrictedMode(t) { + if (!this.bt) { + this.bt = !0, this.Ot = t || !1; + const e = getDocument(); + e && "function" == typeof e.removeEventListener && e.removeEventListener("visibilitychange", this.Bt); + } + } + enqueue(t) { + if (this.Qt(), this.bt) + // Return a Promise which never resolves. + return new Promise((() => {})); + // Create a deferred Promise that we can return to the callee. This + // allows us to return a "hanging Promise" only to the callee and still + // advance the queue even when the operation is not run. + const e = new __PRIVATE_Deferred; + return this.kt((() => this.bt && this.Ot ? Promise.resolve() : (t().then(e.resolve, e.reject), + e.promise))).then((() => e.promise)); + } + enqueueRetryable(t) { + this.enqueueAndForget((() => (this.Dt.push(t), this.Lt()))); + } + /** + * Runs the next operation from the retryable queue. If the operation fails, + * reschedules with backoff. + */ async Lt() { + if (0 !== this.Dt.length) { + try { + await this.Dt[0](), this.Dt.shift(), this.It.reset(); + } catch (t) { + if (! + /** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** Verifies whether `e` is an IndexedDbTransactionError. */ + function __PRIVATE_isIndexedDbTransactionError(t) { + // Use name equality, as instanceof checks on errors don't work with errors + // that wrap other errors. + return "IndexedDbTransactionError" === t.name; + }(t)) throw t; + // Failure will be handled by AsyncQueue + __PRIVATE_logDebug(ft, "Operation failed with retryable error: " + t); + } + this.Dt.length > 0 && + // If there are additional operations, we re-schedule `retryNextOp()`. + // This is necessary to run retryable operations that failed during + // their initial attempt since we don't know whether they are already + // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1` + // needs to be re-run, we will run `op1`, `op1`, `op2` using the + // already enqueued calls to `retryNextOp()`. `op3()` will then run in the + // call scheduled here. + // Since `backoffAndRun()` cancels an existing backoff and schedules a + // new backoff on every call, there is only ever a single additional + // operation in the queue. + this.It.Z((() => this.Lt())); + } + } + kt(t) { + const e = this.$t.then((() => (this.Nt = !0, t().catch((t => { + this.Ct = t, this.Nt = !1; + // Re-throw the error so that this.tail becomes a rejected Promise and + // all further attempts to chain (via .then) will just short-circuit + // and return the rejected Promise. + throw __PRIVATE_logError("INTERNAL UNHANDLED ERROR: ", __PRIVATE_getMessageOrStack(t)), + t; + })).then((t => (this.Nt = !1, t)))))); + return this.$t = e, e; + } + enqueueAfterDelay(t, e, r) { + this.Qt(), + // Fast-forward delays for timerIds that have been overridden. + this.qt.indexOf(t) > -1 && (e = 0); + const n = DelayedOperation.createAndSchedule(this, t, e, r, (t => this.Mt(t))); + return this.St.push(n), n; + } + Qt() { + this.Ct && fail(47125, { + xt: __PRIVATE_getMessageOrStack(this.Ct) + }); + } + verifyOperationInProgress() {} + /** + * Waits until all currently queued tasks are finished executing. Delayed + * operations are not run. + */ async Ut() { + // Operations in the queue prior to draining may have enqueued additional + // operations. Keep draining the queue until the tail is no longer advanced, + // which indicates that no more new operations were enqueued and that all + // operations were executed. + let t; + do { + t = this.$t, await t; + } while (t !== this.$t); + } + /** + * For Tests: Determine if a delayed operation with a particular TimerId + * exists. + */ jt(t) { + for (const e of this.St) if (e.timerId === t) return !0; + return !1; + } + /** + * For Tests: Runs some or all delayed operations early. + * + * @param lastTimerId - Delayed operations up to and including this TimerId + * will be drained. Pass TimerId.All to run all delayed operations. + * @returns a Promise that resolves once all operations have been run. + */ zt(t) { + // Note that draining may generate more delayed ops, so we do that first. + return this.Ut().then((() => { + // Run ops in the same order they'd run if they ran naturally. + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ + this.St.sort(((t, e) => t.targetTimeMs - e.targetTimeMs)); + for (const e of this.St) if (e.skipDelay(), "all" /* TimerId.All */ !== t && e.timerId === t) break; + return this.Ut(); + })); + } + /** + * For Tests: Skip all subsequent delays for a timer id. + */ Wt(t) { + this.qt.push(t); + } + /** Called once a DelayedOperation is run or canceled. */ Mt(t) { + // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small. + const e = this.St.indexOf(t); + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ this.St.splice(e, 1); + } +} + +/** + * Chrome includes Error.message in Error.stack. Other browsers do not. + * This returns expected output of message + stack when available. + * @param error - Error or FirestoreError + */ +function __PRIVATE_getMessageOrStack(t) { + let e = t.message || ""; + return t.stack && (e = t.stack.includes(t.message) ? t.stack : t.message + "\n" + t.stack), + e; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the +// legacy SDK. +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ class Transaction { + /** @hideconstructor */ + constructor(t, e) { + this._firestore = t, this._transaction = e, this._dataReader = __PRIVATE_newUserDataReader(t); + } + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ get(t) { + const e = __PRIVATE_validateReference(t, this._firestore), r = new __PRIVATE_LiteUserDataWriter(this._firestore); + return this._transaction.lookup([ e._key ]).then((t => { + if (!t || 1 !== t.length) return fail(24041); + const n = t[0]; + if (n.isFoundDocument()) return new DocumentSnapshot(this._firestore, r, n.key, n, e.converter); + if (n.isNoDocument()) return new DocumentSnapshot(this._firestore, r, e._key, null, e.converter); + throw fail(18433, { + doc: n + }); + })); + } + set(t, e, r) { + const n = __PRIVATE_validateReference(t, this._firestore), i = __PRIVATE_applyFirestoreDataConverter(n.converter, e, r), s = __PRIVATE_parseSetData(this._dataReader, "Transaction.set", n._key, i, null !== n.converter, r); + return this._transaction.set(n._key, s), this; + } + update(t, e, r, ...n) { + const i = __PRIVATE_validateReference(t, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + let s; + return s = "string" == typeof (e = getModularInstance(e)) || e instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(this._dataReader, "Transaction.update", i._key, e, r, n) : __PRIVATE_parseUpdateData(this._dataReader, "Transaction.update", i._key, e), + this._transaction.update(i._key, s), this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `Transaction` instance. Used for chaining method calls. + */ delete(t) { + const e = __PRIVATE_validateReference(t, this._firestore); + return this._transaction.delete(e._key), this; + } +} + +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ function runTransaction(t, e, r) { + const n = __PRIVATE_getDatastore(t = __PRIVATE_cast(t, Firestore)), i = { + ...ht, + ...r + }; + !function __PRIVATE_validateTransactionOptions(t) { + if (t.maxAttempts < 1) throw new FirestoreError(y, "Max attempts must be at least 1"); + }(i); + const s = new __PRIVATE_Deferred; + return new __PRIVATE_TransactionRunner(function __PRIVATE_newAsyncQueue() { + return new __PRIVATE_AsyncQueueImpl; + }(), n, i, (r => e(new Transaction(t, r))), s).yt(), s.promise; +} + +/** + * Firestore Lite + * + * @remarks Firestore Lite is a small online-only SDK that allows read + * and write access to your Firestore database. All operations connect + * directly to the backend, and `onSnapshot()` APIs are not supported. + * @packageDocumentation + */ !function __PRIVATE_registerFirestore() { + !function __PRIVATE_setSDKVersion(t) { + A = t; + }(`${SDK_VERSION}_lite`), _registerComponent(new Component("firestore/lite", ((t, {instanceIdentifier: e, options: r}) => { + const n = t.getProvider("app").getImmediate(), i = new Firestore(new __PRIVATE_LiteAuthCredentialsProvider(t.getProvider("auth-internal")), new __PRIVATE_LiteAppCheckTokenProvider(n, t.getProvider("app-check-internal")), function __PRIVATE_databaseIdFromApp(t, e) { + if (!Object.prototype.hasOwnProperty.apply(t.options, [ "projectId" ])) throw new FirestoreError(y, '"projectId" not provided in firebase.initializeApp.'); + return new DatabaseId(t.options.projectId, e); + }(n, e), n); + return r && i._setSettings(r), i; + }), "PUBLIC").setMultipleInstances(!0)), + // RUNTIME_ENV and BUILD_TARGET are replaced by real values during the compilation + registerVersion("firestore-lite", P, ""), registerVersion("firestore-lite", P, "esm2020"); +}(); + +export { AggregateField, AggregateQuerySnapshot, Bytes, CollectionReference, DocumentReference, DocumentSnapshot, FieldPath, FieldValue, Firestore, FirestoreError, GeoPoint, Query, QueryCompositeFilterConstraint, QueryConstraint, QueryDocumentSnapshot, QueryEndAtConstraint, QueryFieldFilterConstraint, QueryLimitConstraint, QueryOrderByConstraint, QuerySnapshot, QueryStartAtConstraint, Timestamp, Transaction, VectorValue, WriteBatch, addDoc, aggregateFieldEqual, aggregateQuerySnapshotEqual, and, arrayRemove, arrayUnion, average, collection, collectionGroup, connectFirestoreEmulator, count, deleteDoc, deleteField, doc, documentId, endAt, endBefore, getAggregate, getCount, getDoc, getDocs, getFirestore, increment, initializeFirestore, limit, limitToLast, or, orderBy, query, queryEqual, refEqual, runTransaction, serverTimestamp, setDoc, setLogLevel, snapshotEqual, startAfter, startAt, sum, terminate, updateDoc, vector, where, writeBatch }; +//# sourceMappingURL=index.browser.esm.js.map diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/index.browser.esm.js.map b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.browser.esm.js.map new file mode 100644 index 0000000..be96617 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.browser.esm.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.browser.esm.js","sources":["../../src/auth/user.ts","../../src/core/version.ts","../../src/util/log.ts","../../src/platform/browser/format_json.ts","../../src/util/assert.ts","../../src/util/error.ts","../../src/util/promise.ts","../../src/api/credentials.ts","../../src/core/database_info.ts","../../src/platform/browser/random_bytes.ts","../../src/util/misc.ts","../../src/model/path.ts","../../src/model/document_key.ts","../../src/util/input_validation.ts","../../src/api/long_polling_options.ts","../../src/util/debug_uid.ts","../../src/util/types.ts","../../src/remote/rest_connection.ts","../../src/remote/rpc_error.ts","../../src/platform/browser_lite/fetch_connection.ts","../../src/core/aggregate.ts","../../src/util/obj.ts","../../src/util/base64_decode_error.ts","../../src/util/byte_string.ts","../../src/platform/browser/base64.ts","../../src/model/normalize.ts","../../src/util/json_validation.ts","../../src/lite-api/timestamp.ts","../../src/model/server_timestamps.ts","../../src/model/values.ts","../../src/core/bound.ts","../../src/core/filter.ts","../../src/core/order_by.ts","../../src/core/snapshot_version.ts","../../src/util/sorted_map.ts","../../src/util/sorted_set.ts","../../src/model/field_mask.ts","../../src/model/object_value.ts","../../src/model/document.ts","../../src/core/target.ts","../../src/core/query.ts","../../src/remote/number_serializer.ts","../../src/model/transform_operation.ts","../../src/model/mutation.ts","../../src/remote/serializer.ts","../../src/platform/browser/serializer.ts","../../src/remote/backoff.ts","../../src/remote/datastore.ts","../../src/lite-api/components.ts","../../src/platform/browser_lite/connection.ts","../../src/local/lru_garbage_collector_impl.ts","../../src/lite-api/settings.ts","../../src/local/lru_garbage_collector.ts","../../src/lite-api/database.ts","../../src/lite-api/aggregate_types.ts","../../src/lite-api/reference.ts","../../src/lite-api/bytes.ts","../../src/lite-api/field_path.ts","../../src/lite-api/field_value.ts","../../src/lite-api/geo_point.ts","../../src/lite-api/vector_value.ts","../../src/util/array.ts","../../src/lite-api/user_data_reader.ts","../../src/lite-api/snapshot.ts","../../src/lite-api/query.ts","../../src/lite-api/user_data_writer.ts","../../src/lite-api/reference_impl.ts","../../src/lite-api/aggregate.ts","../../src/lite-api/field_value_impl.ts","../../src/lite-api/write_batch.ts","../../src/core/transaction.ts","../../src/core/transaction_options.ts","../../src/core/transaction_runner.ts","../../src/platform/browser/dom.ts","../../src/util/async_queue.ts","../../src/util/async_queue_impl.ts","../../src/local/simple_db.ts","../../src/lite-api/transaction.ts","../../lite/register.ts","../../lite/index.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Simple wrapper around a nullable UID. Mostly exists to make code more\n * readable.\n */\nexport class User {\n /** A user with a null UID. */\n static readonly UNAUTHENTICATED = new User(null);\n\n // TODO(mikelehen): Look into getting a proper uid-equivalent for\n // non-FirebaseAuth providers.\n static readonly GOOGLE_CREDENTIALS = new User('google-credentials-uid');\n static readonly FIRST_PARTY = new User('first-party-uid');\n static readonly MOCK_USER = new User('mock-user');\n\n constructor(readonly uid: string | null) {}\n\n isAuthenticated(): boolean {\n return this.uid != null;\n }\n\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */\n toKey(): string {\n if (this.isAuthenticated()) {\n return 'uid:' + this.uid;\n } else {\n return 'anonymous-user';\n }\n }\n\n isEqual(otherUser: User): boolean {\n return otherUser.uid === this.uid;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The semver (www.semver.org) version of the SDK. */\nimport { version } from '../../../firebase/package.json';\nexport let SDK_VERSION = version;\nexport function setSDKVersion(version: string): void {\n SDK_VERSION = version;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel, LogLevelString } from '@firebase/logger';\n\nimport { SDK_VERSION } from '../core/version';\nimport { formatJSON } from '../platform/format_json';\n\nexport { LogLevel, LogLevelString };\n\nconst logClient = new Logger('@firebase/firestore');\n\n// Helper methods are needed because variables can't be exported as read/write\nexport function getLogLevel(): LogLevel {\n return logClient.logLevel;\n}\n\n/**\n * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).\n *\n * @param logLevel - The verbosity you set for activity and error logging. Can\n * be any of the following values:\n *\n *
    \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 *\n * @param code generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(\n code: number,\n message: string,\n context?: Record\n): never;\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 *\n * @param id generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(id: number, context?: Record): never;\n\nexport function fail(\n id: number,\n messageOrContext?: string | Record,\n context?: Record\n): never {\n let message = 'Unexpected state';\n if (typeof messageOrContext === 'string') {\n message = messageOrContext;\n } else {\n context = messageOrContext;\n }\n _fail(id, message, context);\n}\n\nfunction _fail(\n id: number,\n failure: string,\n context?: Record\n): never {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n let message = `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ${failure} (ID: ${id.toString(\n 16\n )})`;\n if (context !== undefined) {\n try {\n const stringContext = JSON.stringify(context);\n message += ' CONTEXT: ' + stringContext;\n } catch (e) {\n message += ' CONTEXT: ' + context;\n }\n }\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 *\n * @param id generate a new unique value with `yarn assertion-idgenerate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n assertion: boolean,\n id: number,\n message: string,\n context?: Record\n): asserts assertion;\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 *\n * @param id generate a new unique value with `yarn assertion-id:generate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n assertion: boolean,\n id: number,\n context?: Record\n): asserts assertion;\n\nexport function hardAssert(\n assertion: boolean,\n id: number,\n messageOrContext?: string | Record,\n context?: Record\n): asserts assertion {\n let message = 'Unexpected state';\n if (typeof messageOrContext === 'string') {\n message = messageOrContext;\n } else {\n context = messageOrContext;\n }\n\n if (!assertion) {\n _fail(id, message, context);\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(0xdeb6, 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 { FirebaseApp, _isFirebaseServerApp } from '@firebase/app';\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 0xa539,\n 'Invalid tokenData returned from getToken()',\n { 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 0xa540,\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 0x7c5d,\n 'Invalid tokenData returned from getToken()',\n { 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 0x0807,\n 'Received invalid UID',\n { 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 private serverAppAppCheckToken: string | null = null;\n\n constructor(\n app: FirebaseApp,\n private appCheckProvider: Provider\n ) {\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n }\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n hardAssert(\n this.tokenListener === undefined,\n 0x0db8,\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 if (this.serverAppAppCheckToken) {\n return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n }\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 0xae0e,\n 'Invalid tokenResult returned from getToken()',\n { 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 private serverAppAppCheckToken: string | null = null;\n\n constructor(\n app: FirebaseApp,\n private appCheckProvider: Provider\n ) {\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n appCheckProvider.onInit(appCheck => {\n this.appCheck = appCheck;\n });\n }\n\n getToken(): Promise {\n if (this.serverAppAppCheckToken) {\n return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n }\n\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 0x0d8e,\n 'Invalid tokenResult returned from getToken()',\n { 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","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 readonly isUsingEmulator: 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 { 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\n/** Compare strings in UTF-8 encoded byte order */\nexport function compareUtf8Strings(left: string, right: string): number {\n // Find the first differing character (a.k.a. \"UTF-16 code unit\") in the two strings and,\n // if found, use that character to determine the relative ordering of the two strings as a\n // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by\n // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8\n // and UTF-16 happen to represent Unicode code points.\n //\n // After finding the first pair of differing characters, there are two cases:\n //\n // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or\n // both are surrogates from a surrogate pair (that collectively represent code points greater\n // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the\n // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is\n // sufficient.\n //\n // Case 2: One character is a surrogate and the other is not. In this case the surrogate-\n // containing string is always ordered after the non-surrogate. This is because surrogates are\n // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations\n // and are lexicographically greater than the 1, 2, or 3-byte representations of code points\n // less than or equal to 0xFFFF.\n //\n // An example of why Case 2 is required is comparing the following two Unicode code points:\n //\n // |-----------------------|------------|---------------------|-----------------|\n // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding |\n // |-----------------------|------------|---------------------|-----------------|\n // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD |\n // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 |\n // |-----------------------|------------|---------------------|-----------------|\n //\n // A lexicographical comparison of the UTF-8 encodings of these code points would order\n // \"Replacement Character\" _before_ \"Grinning Face\" because 0xEF is less than 0xF0. However, a\n // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously\n // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out,\n // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate\n // pair with those that do not.\n const length = Math.min(left.length, right.length);\n for (let i = 0; i < length; i++) {\n const leftChar = left.charAt(i);\n const rightChar = right.charAt(i);\n if (leftChar !== rightChar) {\n return isSurrogate(leftChar) === isSurrogate(rightChar)\n ? primitiveComparator(leftChar, rightChar)\n : isSurrogate(leftChar)\n ? 1\n : -1;\n }\n }\n\n // Use the lengths of the strings to determine the overall comparison result since either the\n // strings were equal or one is a prefix of the other.\n return primitiveComparator(left.length, right.length);\n}\n\nconst MIN_SURROGATE = 0xd800;\nconst MAX_SURROGATE = 0xdfff;\n\nexport function isSurrogate(s: string): boolean {\n debugAssert(s.length === 1, `s.length == ${s.length}, but expected 1`);\n const c = s.charCodeAt(0);\n return c >= MIN_SURROGATE && c <= MAX_SURROGATE;\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 { Integer } from '@firebase/webchannel-wrapper/bloom-blob';\n\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { compareUtf8Strings, primitiveComparator } from '../util/misc';\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(0x027d, 'offset out of range', {\n offset,\n range: segments.length\n });\n }\n\n if (length === undefined) {\n length = segments.length - offset;\n } else if (length > segments.length - offset) {\n fail(0x06d2, 'length out of range', {\n length,\n range: segments.length - offset\n });\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 /**\n * Compare 2 paths segment by segment, prioritizing numeric IDs\n * (e.g., \"__id123__\") in numeric ascending order, followed by string\n * segments in lexicographical order.\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 comparison = BasePath.compareSegments(p1.get(i), p2.get(i));\n if (comparison !== 0) {\n return comparison;\n }\n }\n return primitiveComparator(p1.length, p2.length);\n }\n\n private static compareSegments(lhs: string, rhs: string): number {\n const isLhsNumeric = BasePath.isNumericId(lhs);\n const isRhsNumeric = BasePath.isNumericId(rhs);\n\n if (isLhsNumeric && !isRhsNumeric) {\n // Only lhs is numeric\n return -1;\n } else if (!isLhsNumeric && isRhsNumeric) {\n // Only rhs is numeric\n return 1;\n } else if (isLhsNumeric && isRhsNumeric) {\n // both numeric\n return BasePath.extractNumericId(lhs).compare(\n BasePath.extractNumericId(rhs)\n );\n } else {\n // both non-numeric\n return compareUtf8Strings(lhs, rhs);\n }\n }\n\n // Checks if a segment is a numeric ID (starts with \"__id\" and ends with \"__\").\n private static isNumericId(segment: string): boolean {\n return segment.startsWith('__id') && segment.endsWith('__');\n }\n\n private static extractNumericId(segment: string): Integer {\n return Integer.fromString(segment.substring(4, segment.length - 2));\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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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(0x3029, 'Unknown wrong type', { 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 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 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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isCloudWorkstation } from '@firebase/util';\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 const { host } = new URL(url);\n const forwardCredentials = isCloudWorkstation(host);\n return this.performRPCRequest(\n rpcName,\n url,\n headers,\n req,\n forwardCredentials\n ).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 _forwardCredentials: boolean\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 { 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(0xfdaa, '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(0x3c6b, '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(0x999b, '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(0x3019, '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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Token } from '../../api/credentials';\nimport { Stream } from '../../remote/connection';\nimport { RestConnection } from '../../remote/rest_connection';\nimport { mapCodeFromHttpStatus } from '../../remote/rpc_error';\nimport { FirestoreError } from '../../util/error';\nimport { StringMap } from '../../util/types';\n\n/**\n * A Rest-based connection that relies on the native HTTP stack\n * (e.g. `fetch` or a polyfill).\n */\nexport class FetchConnection extends RestConnection {\n openStream(\n rpcName: string,\n token: Token | null\n ): Stream {\n throw new Error('Not supported by FetchConnection');\n }\n\n protected async performRPCRequest(\n rpcName: string,\n url: string,\n headers: StringMap,\n body: Req,\n forwardCredentials: boolean\n ): Promise {\n const requestJson = JSON.stringify(body);\n let response: Response;\n\n try {\n const fetchArgs: RequestInit = {\n method: 'POST',\n headers,\n body: requestJson\n };\n if (forwardCredentials) {\n fetchArgs.credentials = 'include';\n }\n response = await fetch(url, fetchArgs);\n } catch (e) {\n const err = e as { status: number | undefined; statusText: string };\n throw new FirestoreError(\n mapCodeFromHttpStatus(err.status),\n 'Request failed with error: ' + err.statusText\n );\n }\n\n if (!response.ok) {\n let errorResponse = await response.json();\n if (Array.isArray(errorResponse)) {\n errorResponse = errorResponse[0];\n }\n const errorMessage = errorResponse?.error?.message;\n throw new FirestoreError(\n mapCodeFromHttpStatus(response.status),\n `Request failed with error: ${errorMessage ?? response.statusText}`\n );\n }\n\n return response.json();\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 { FieldPath } from '../model/path';\n\n/**\n * Union type representing the aggregate type to be performed.\n */\nexport type AggregateType = 'count' | 'avg' | 'sum';\n\n/**\n * Represents an Aggregate to be performed over a query result set.\n */\nexport interface Aggregate {\n readonly fieldPath?: FieldPath;\n readonly alias: string;\n readonly aggregateType: AggregateType;\n}\n\n/**\n * Concrete implementation of the Aggregate type.\n */\nexport class AggregateImpl implements Aggregate {\n constructor(\n readonly alias: string,\n readonly aggregateType: AggregateType,\n readonly fieldPath?: 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 './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 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, 0x986a, '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, 0xb5de, 'invalid timestamp', {\n timestamp: date\n });\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 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isPlainObject } from '../util/input_validation';\n\nimport { Code, FirestoreError } from './error';\n\n/**\n * A list of data types Firestore objects may serialize in their toJSON implemenetations.\n * @private\n * @internal\n */\nexport type JsonTypeDesc =\n | 'object'\n | 'string'\n | 'number'\n | 'boolean'\n | 'null'\n | 'undefined';\n\n/**\n * An association of JsonTypeDesc values to their native types.\n * @private\n * @internal\n */\nexport type TSType = T extends 'object'\n ? object\n : T extends 'string'\n ? string\n : T extends 'number'\n ? number\n : T extends 'boolean'\n ? boolean\n : T extends 'null'\n ? null\n : T extends 'undefined'\n ? undefined\n : never;\n\n/**\n * The representation of a JSON object property name and its type value.\n * @private\n * @internal\n */\nexport interface Property {\n value?: TSType;\n typeString: JsonTypeDesc;\n}\n\n/**\n * A type Firestore data types may use to define the fields used in their JSON serialization.\n * @private\n * @internal\n */\nexport interface JsonSchema {\n [key: string]: Property;\n}\n\n/**\n * Associates the JSON property type to the native type and sets them to be Required.\n * @private\n * @internal\n */\nexport type Json = {\n [K in keyof T]: Required['value'];\n};\n\n/**\n * Helper function to define a JSON schema {@link Property}.\n * @private\n * @internal\n */\nexport function property(\n typeString: T,\n optionalValue?: TSType\n): Property {\n const result: Property = {\n typeString\n };\n if (optionalValue) {\n result.value = optionalValue;\n }\n return result;\n}\n\n/**\n * Validates the JSON object based on the provided schema, and narrows the type to the provided\n * JSON schema.\n * @private\n * @internal\n *\n * @param json A JSON object to validate.\n * @param scheme a {@link JsonSchema} that defines the properties to validate.\n * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise.\n */\nexport function validateJSON(\n json: object,\n schema: S\n): json is Json {\n if (!isPlainObject(json)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'JSON must be an object');\n }\n let error: string | undefined = undefined;\n for (const key in schema) {\n if (schema[key]) {\n const typeString = schema[key].typeString;\n const value: { value: unknown } | undefined =\n 'value' in schema[key] ? { value: schema[key].value } : undefined;\n if (!(key in json)) {\n error = `JSON missing required field: '${key}'`;\n break;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const fieldValue = (json as any)[key];\n if (typeString && typeof fieldValue !== typeString) {\n error = `JSON field '${key}' must be a ${typeString}.`;\n break;\n } else if (value !== undefined && fieldValue !== value.value) {\n error = `Expected '${key}' field to equal '${value.value}'`;\n break;\n }\n }\n }\n if (error) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, error);\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 { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\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 static _jsonSchemaVersion: string = 'firestore/timestamp/1.0';\n static _jsonSchema = {\n type: property('string', Timestamp._jsonSchemaVersion),\n seconds: property('number'),\n nanoseconds: property('number')\n };\n\n /**\n * Returns a JSON-serializable representation of this `Timestamp`.\n */\n toJSON(): { seconds: number; nanoseconds: number; type: string } {\n return {\n type: Timestamp._jsonSchemaVersion,\n seconds: this.seconds,\n nanoseconds: this.nanoseconds\n };\n }\n\n /**\n * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}.\n */\n static fromJSON(json: object): Timestamp {\n if (validateJSON(json, Timestamp._jsonSchema)) {\n return new Timestamp(json.seconds, json.nanoseconds);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Timestamp from JSON.'\n );\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 {\n arrayEquals,\n compareUtf8Strings,\n primitiveComparator\n} 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(0x6e87, 'Invalid value type', { 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(0xcbf8, 'Unexpected value type', { 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 compareUtf8Strings(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(0x5ae0, '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 = compareUtf8Strings(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(0xee4d, 'Invalid value type', { 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(0x34ae, 'Invalid value type', { 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(0x8c66, 'Invalid value type', { 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(0xf207, 'Invalid value type', { 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 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 { 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 other.nullValue === undefined &&\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(0xb8a2, 'Unknown FieldFilter operator', {\n operator: this.op\n });\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(0x4bef, '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 (\n other !== null &&\n other.nullValue === undefined &&\n !arrayValueContains(this.value.arrayValue!, other)\n );\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 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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 './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(0xaad2, 'Red node has red child', {\n key: this.key,\n value: this.value\n });\n }\n if (this.right.isRed()) {\n throw fail(0x3721, 'Right child of (`key`, `value`) is red', {\n key: this.key,\n value: this.value\n });\n }\n const blackDepth = (this.left as LLRBNode).check();\n if (blackDepth !== (this.right as LLRBNode).check()) {\n throw fail(0x6d2d, '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(0xe1a6, 'LLRBEmptyNode has no key.');\n }\n get value(): never {\n throw fail(0x3f0d, 'LLRBEmptyNode has no value.');\n }\n get color(): never {\n throw fail(0x4157, 'LLRBEmptyNode has no color.');\n }\n get left(): never {\n throw fail(0x741e, 'LLRBEmptyNode has no left child.');\n }\n get right(): never {\n throw fail(0x901e, '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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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(\n 0xa786,\n \"Trying to compare documents on fields that don't exist\"\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(0x4d4e, 'Unknown direction', { direction: orderBy.dir });\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 { 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 0x7f90,\n 'server transform result count should match field transform count',\n {\n serverTransformResultCount: serverTransformResults.length,\n fieldTransformCount: fieldTransforms.length\n }\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 { 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\n/**\n * Returns a Timestamp typed object given protobuf timestamp value.\n */\nexport function 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 0xe30b,\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 0x3f41,\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, 0xc050, \"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 0x27ce,\n 'Tried to deserialize invalid key',\n { 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 0x71a3,\n 'tried to deserialize invalid key',\n { 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 0xaa33,\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 0x0f36,\n 'Tried to deserialize a missing document from a found document.'\n );\n hardAssert(\n !!result.readTime,\n 0x5995,\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(0x1c42, 'invalid batch get response', { 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(0x2d51, 'Unknown change type', { 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(0x9991, '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(0x40d7, 'Unknown mutation type', {\n mutationType: mutation.type\n });\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(0x05b7, 'unknown mutation proto', { 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(0x6b69, '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 0x3811,\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(0x51c2, 'Unknown transform', {\n transform: fieldTransform.transform\n });\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 0x40f6,\n 'Unknown server value transform proto',\n { 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(0x40c8, 'Unknown transform proto', { 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 0x07ae,\n 'DocumentsTarget contained other than 1 document',\n {\n count\n }\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 0xfe26,\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(0x713b, '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(0x7591, 'Unknown filter', { 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(0xe2fe, 'Unspecified operator');\n default:\n return fail(0xc54a, '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(0x0402, '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(0xd65d, 'Unrecognized filter type', { 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(0xef81, 'Unspecified filter');\n default:\n return fail(0xed36, '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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 } 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, 0xd7c2, 'Missing entity in write response for `key`', {\n key\n });\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 0xfcd7,\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 settings.isUsingEmulator\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';\n\nimport { FetchConnection } from './fetch_connection';\n\nexport { newConnectivityMonitor } from '../browser/connection';\n\n/** Initializes the HTTP connection for the REST API. */\nexport function newConnection(databaseInfo: DatabaseInfo): Connection {\n return new FetchConnection(databaseInfo);\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\nimport { EmulatorMockTokenOptions } from '@firebase/util';\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 emulatorOptions?: { mockUserToken?: EmulatorMockTokenOptions | string };\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 readonly isUsingEmulator: boolean;\n\n // Can be a google-auth-library or gapi client.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n credentials?: any;\n\n constructor(settings: PrivateSettings) {\n if (settings.host === undefined) {\n if (settings.ssl !== undefined) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't provide ssl option if host option is not set\"\n );\n }\n this.host = DEFAULT_HOST;\n this.ssl = DEFAULT_SSL;\n } else {\n this.host = settings.host;\n this.ssl = settings.ssl ?? DEFAULT_SSL;\n }\n this.isUsingEmulator = settings.emulatorOptions !== undefined;\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 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 deepEqual,\n EmulatorMockTokenOptions,\n getDefaultEmulatorHostnameAndPort,\n isCloudWorkstation,\n pingServer,\n updateEmulatorBanner\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 private _emulatorOptions: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {};\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 this._emulatorOptions = settings.emulatorOptions || {};\n\n if (settings.credentials !== undefined) {\n this._authCredentials = makeAuthCredentialsProvider(settings.credentials);\n }\n }\n\n _getSettings(): FirestoreSettingsImpl {\n return this._settings;\n }\n\n _getEmulatorOptions(): { mockUserToken?: EmulatorMockTokenOptions | string } {\n return this._emulatorOptions;\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 useSsl = isCloudWorkstation(host);\n const settings = firestore._getSettings();\n const existingConfig = {\n ...settings,\n emulatorOptions: firestore._getEmulatorOptions()\n };\n const newHostSetting = `${host}:${port}`;\n if (useSsl) {\n void pingServer(`https://${newHostSetting}`);\n updateEmulatorBanner('Firestore', true);\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 const newConfig = {\n ...settings,\n host: newHostSetting,\n ssl: useSsl,\n emulatorOptions: options\n };\n // No-op if the new configuration matches the current configuration. This supports SSR\n // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice.\n if (deepEqual(newConfig, existingConfig)) {\n return;\n }\n\n firestore._setSettings(newConfig);\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 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 { AggregateType } from '../core/aggregate';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\n\nimport { average, count, sum } from './aggregate';\nimport { DocumentData, Query } from './reference';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\nexport { AggregateType };\n\n/**\n * Represents an aggregation that can be performed by Firestore.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport class AggregateField {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateField';\n\n /** Indicates the aggregation operation of this AggregateField. */\n readonly aggregateType: AggregateType;\n\n /**\n * Create a new AggregateField\n * @param aggregateType Specifies the type of aggregation operation to perform.\n * @param _internalFieldPath Optionally specifies the field that is aggregated.\n * @internal\n */\n constructor(\n aggregateType: AggregateType = 'count',\n readonly _internalFieldPath?: InternalFieldPath\n ) {\n this.aggregateType = aggregateType;\n }\n}\n\n/**\n * The union of all `AggregateField` types that are supported by Firestore.\n */\nexport type AggregateFieldType =\n | ReturnType\n | ReturnType\n | ReturnType;\n\n/**\n * Specifies a set of aggregations and their aliases.\n */\nexport interface AggregateSpec {\n [field: string]: AggregateFieldType;\n}\n\n/**\n * A type whose keys are taken from an `AggregateSpec`, and whose values are the\n * result of the aggregation performed by the corresponding `AggregateField`\n * from the input `AggregateSpec`.\n */\nexport type AggregateSpecData = {\n [P in keyof T]: T[P] extends AggregateField ? U : never;\n};\n\n/**\n * The results of executing an aggregation query.\n */\nexport class AggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateQuerySnapshot';\n\n /**\n * The underlying query over which the aggregations recorded in this\n * `AggregateQuerySnapshot` were performed.\n */\n readonly query: Query;\n\n /** @hideconstructor */\n constructor(\n query: Query,\n private readonly _userDataWriter: AbstractUserDataWriter,\n private readonly _data: ApiClientObjectMap\n ) {\n this.query = query;\n }\n\n /**\n * Returns the results of the aggregations performed over the underlying\n * query.\n *\n * The keys of the returned object will be the same as those of the\n * `AggregateSpec` object specified to the aggregation method, and the values\n * will be the corresponding aggregation result.\n *\n * @returns The results of the aggregations performed over the underlying\n * query.\n */\n data(): AggregateSpecData {\n return this._userDataWriter.convertObjectMap(\n this._data\n ) as AggregateSpecData;\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 {\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';\n// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_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 static _jsonSchemaVersion: string = 'firestore/documentReference/1.0';\n static _jsonSchema = {\n type: property('string', DocumentReference._jsonSchemaVersion),\n referencePath: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `DocumentReference` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: DocumentReference._jsonSchemaVersion,\n referencePath: this._key.toString()\n };\n }\n\n /**\n * Builds a `DocumentReference` instance from a JSON object created by\n * {@link DocumentReference.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json a JSON object represention of a `DocumentReference` instance\n * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(firestore: Firestore, json: object): DocumentReference;\n /**\n * Builds a `DocumentReference` instance from a JSON object created by\n * {@link DocumentReference.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json a JSON object represention of a `DocumentReference` instance\n * @param converter - Converts objects to and from Firestore.\n * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON<\n NewAppModelType = DocumentData,\n NewDbModelType extends DocumentData = DocumentData\n >(\n firestore: Firestore,\n json: object,\n converter: FirestoreDataConverter\n ): DocumentReference;\n static fromJSON<\n NewAppModelType = DocumentData,\n NewDbModelType extends DocumentData = DocumentData\n >(\n firestore: Firestore,\n json: object,\n converter?: FirestoreDataConverter\n ): DocumentReference {\n if (validateJSON(json, DocumentReference._jsonSchema)) {\n return new DocumentReference(\n firestore,\n converter ? converter : null,\n new DocumentKey(ResourcePath.fromString(json.referencePath))\n );\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Bytes from JSON.'\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 { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\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 static _jsonSchemaVersion: string = 'firestore/bytes/1.0';\n static _jsonSchema = {\n type: property('string', Bytes._jsonSchemaVersion),\n bytes: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `Bytes` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: Bytes._jsonSchemaVersion,\n bytes: this.toBase64()\n };\n }\n\n /**\n * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}.\n *\n * @param json a JSON object represention of a `Bytes` instance\n * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): Bytes {\n if (validateJSON(json, Bytes._jsonSchema)) {\n return Bytes.fromBase64String(json.bytes);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Bytes from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n 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';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\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 /**\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 static _jsonSchemaVersion: string = 'firestore/geoPoint/1.0';\n static _jsonSchema = {\n type: property('string', GeoPoint._jsonSchemaVersion),\n latitude: property('number'),\n longitude: property('number')\n };\n\n /**\n * Returns a JSON-serializable representation of this `GeoPoint` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): { latitude: number; longitude: number; type: string } {\n return {\n latitude: this._lat,\n longitude: this._long,\n type: GeoPoint._jsonSchemaVersion\n };\n }\n\n /**\n * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}.\n *\n * @param json a JSON object represention of a `GeoPoint` instance\n * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): GeoPoint {\n if (validateJSON(json, GeoPoint._jsonSchema)) {\n return new GeoPoint(json.latitude, json.longitude);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating GeoPoint from JSON.'\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';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\n\n/**\n * Represents a vector type in Firestore documents.\n * Create an instance with {@link 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` values have the same raw number arrays, returns `false` otherwise.\n */\n isEqual(other: VectorValue): boolean {\n return isPrimitiveArrayEqual(this._values, other._values);\n }\n\n static _jsonSchemaVersion: string = 'firestore/vectorValue/1.0';\n static _jsonSchema = {\n type: property('string', VectorValue._jsonSchemaVersion),\n vectorValues: property('object')\n };\n\n /**\n * Returns a JSON-serializable representation of this `VectorValue` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: VectorValue._jsonSchemaVersion,\n vectorValues: this._values\n };\n }\n\n /**\n * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}.\n *\n * @param json a JSON object represention of a `VectorValue` instance.\n * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): VectorValue {\n if (validateJSON(json, VectorValue._jsonSchema)) {\n if (\n Array.isArray(json.vectorValues) &&\n json.vectorValues.every(element => typeof element === 'number')\n ) {\n return new VectorValue(json.vectorValues);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Expected 'vectorValues' field to be a number array\"\n );\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Timestamp from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Returns 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(0x9c4b, 'Unexpected case for UserDataSource', {\n dataSource\n });\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\nexport function 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(0xf2a2, 'Invalid value type', {\n value\n });\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 0x25d8,\n 'ReferenceValue is not valid',\n { name }\n );\n const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3));\n const key = new DocumentKey(resourcePath.popFirst(5));\n\n if (!databaseId.isEqual(expectedDatabaseId)) {\n // TODO(b/64130202): Somehow support foreign references.\n logError(\n `Document ${key} contains a document ` +\n `reference within a different database (` +\n `${databaseId.projectId}/${databaseId.database}) which is not ` +\n `supported. It will be treated as a reference in the current ` +\n `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` +\n `instead.`\n );\n }\n return key;\n }\n\n protected abstract convertReference(name: string): unknown;\n\n protected abstract convertBytes(bytes: ByteString): unknown;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData as PublicDocumentData,\n SetOptions as PublicSetOptions\n} from '@firebase/firestore-types';\nimport { getModularInstance } from '@firebase/util';\n\nimport { LimitType } from '../core/query';\nimport { DeleteMutation, Precondition } from '../model/mutation';\nimport {\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc,\n invokeRunQueryRpc\n} from '../remote/datastore';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { cast } from '../util/input_validation';\n\nimport { Bytes } from './bytes';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { validateHasExplicitOrderByForLimitToLast } from './query';\nimport {\n CollectionReference,\n doc,\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot\n} from './snapshot';\nimport {\n newUserDataReader,\n ParsedUpdateData,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converts custom model object of type T into `DocumentData` by applying the\n * converter if it exists.\n *\n * This function is used when converting user objects to `DocumentData`\n * because we want to provide the user with a more specific error message if\n * their `set()` or fails due to invalid data originating from a `toFirestore()`\n * call.\n */\nexport function applyFirestoreDataConverter(\n converter: UntypedFirestoreDataConverter | null,\n value: WithFieldValue | PartialWithFieldValue,\n options?: PublicSetOptions\n): PublicDocumentData {\n let convertedValue;\n if (converter) {\n if (options && (options.merge || options.mergeFields)) {\n // Cast to `any` in order to satisfy the union type constraint on\n // toFirestore().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n convertedValue = (converter as any).toFirestore(value, options);\n } else {\n convertedValue = converter.toFirestore(value as WithFieldValue);\n }\n } else {\n convertedValue = value as PublicDocumentData;\n }\n return convertedValue;\n}\n\nexport class LiteUserDataWriter extends AbstractUserDataWriter {\n constructor(protected firestore: Firestore) {\n super();\n }\n\n protected convertBytes(bytes: ByteString): Bytes {\n return new Bytes(bytes);\n }\n\n protected convertReference(name: string): DocumentReference {\n const key = this.convertDocumentKey(name, this.firestore._databaseId);\n return new DocumentReference(this.firestore, /* converter= */ null, key);\n }\n}\n\n/**\n * Reads the document referred to by the specified document reference.\n *\n * All documents are directly fetched from the server, even if the document was\n * previously read or modified. Recent modifications are only reflected in the\n * retrieved `DocumentSnapshot` if they have already been applied by the\n * backend. If the client is offline, the read fails. If you like to use\n * caching or see local modifications, please use the full Firestore SDK.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the current\n * document contents.\n */\nexport function getDoc(\n reference: DocumentReference\n): Promise> {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n const userDataWriter = new LiteUserDataWriter(reference.firestore);\n\n return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then(\n result => {\n hardAssert(\n result.length === 1,\n 0x3d02,\n 'Expected a single document result'\n );\n const document = result[0];\n return new DocumentSnapshot(\n reference.firestore,\n userDataWriter,\n reference._key,\n document.isFoundDocument() ? document : null,\n reference.converter\n );\n }\n );\n}\n\n/**\n * Executes the query and returns the results as a {@link QuerySnapshot}.\n *\n * All queries are executed directly by the server, even if the query was\n * previously executed. Recent modifications are only reflected in the retrieved\n * results if they have already been applied by the backend. If the client is\n * offline, the operation fails. To see previously cached result and local\n * modifications, use the full Firestore SDK.\n *\n * @param query - The `Query` to execute.\n * @returns A Promise that will be resolved with the results of the query.\n */\nexport function getDocs(\n query: Query\n): Promise> {\n query = cast>(query, Query);\n validateHasExplicitOrderByForLimitToLast(query._query);\n\n const datastore = getDatastore(query.firestore);\n const userDataWriter = new LiteUserDataWriter(query.firestore);\n return invokeRunQueryRpc(datastore, query._query).then(result => {\n const docs = result.map(\n doc =>\n new QueryDocumentSnapshot(\n query.firestore,\n userDataWriter,\n doc.key,\n doc,\n query.converter\n )\n );\n\n if (query._query.limitType === LimitType.Last) {\n // Limit to last queries reverse the orderBy constraint that was\n // specified by the user. As such, we need to reverse the order of the\n // results to return the documents in the expected order.\n docs.reverse();\n }\n\n return new QuerySnapshot(query, docs);\n });\n}\n\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\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 * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\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 convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data,\n options\n );\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'setDoc',\n reference._key,\n convertedValue,\n reference.converter !== null,\n options\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference`. The update will fail if applied to a document that does\n * not exist.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\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 * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\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 dataReader = newUserDataReader(reference.firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed: ParsedUpdateData;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData\n );\n }\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.exists(true))\n ]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * The deletion will only be reflected in document reads that occur after the\n * returned promise resolves. If the client is offline, the\n * delete fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to delete.\n * @returns A `Promise` resolved once the document has been successfully\n * deleted from the backend.\n */\nexport function deleteDoc(\n reference: DocumentReference\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n new DeleteMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend.\n */\nexport function addDoc(\n reference: CollectionReference,\n data: WithFieldValue\n): Promise> {\n reference = cast>(\n reference,\n CollectionReference\n );\n const docRef = doc(reference);\n\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data as PartialWithFieldValue\n );\n\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'addDoc',\n docRef._key,\n convertedValue,\n docRef.converter !== null,\n {}\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(docRef._key, Precondition.exists(false))\n ]).then(() => docRef);\n}\n","/**\n * @license\n * Copyright 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 { deepEqual } from '@firebase/util';\n\nimport { AggregateImpl } from '../core/aggregate';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { invokeRunAggregationQueryRpc } from '../remote/datastore';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport {\n AggregateField,\n AggregateQuerySnapshot,\n AggregateSpec\n} from './aggregate_types';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { DocumentData, Query, queryEqual } from './reference';\nimport { LiteUserDataWriter } from './reference_impl';\nimport { fieldPathFromArgument } from './user_data_reader';\n\n/**\n * Calculates the number of documents in the result set of the given query\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can\n * count the documents in cases where the result set is prohibitively large to\n * download entirely (thousands of documents).\n *\n * @param query The query whose result set size is calculated.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */\nexport function getCount(\n query: Query\n): Promise<\n AggregateQuerySnapshot<\n { count: AggregateField },\n AppModelType,\n DbModelType\n >\n> {\n const countQuerySpec: { count: AggregateField } = {\n count: count()\n };\n\n return getAggregate(query, countQuerySpec);\n}\n\n/**\n * Calculates the specified aggregations over the documents in the result\n * set of the given query without actually downloading the documents.\n *\n * Using this function to perform aggregations is efficient because only the\n * final aggregation values, not the documents' data, are downloaded. This\n * function can perform aggregations of the documents in cases where the result\n * set is prohibitively large to download entirely (thousands of documents).\n *\n * @param query The query whose result set is aggregated over.\n * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates\n * to perform over the result set. The AggregateSpec specifies aliases for each\n * aggregate, which can be used to retrieve the aggregate result.\n * @example\n * ```typescript\n * const aggregateSnapshot = await getAggregate(query, {\n * countOfDocs: count(),\n * totalHours: sum('hours'),\n * averageScore: average('score')\n * });\n *\n * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;\n * const totalHours: number = aggregateSnapshot.data().totalHours;\n * const averageScore: number | null = aggregateSnapshot.data().averageScore;\n * ```\n */\nexport function getAggregate<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n aggregateSpec: AggregateSpecType\n): Promise<\n AggregateQuerySnapshot\n> {\n const firestore = cast(query.firestore, Firestore);\n const datastore = getDatastore(firestore);\n\n const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n\n // Run the aggregation and convert the results\n return invokeRunAggregationQueryRpc(\n datastore,\n query._query,\n internalAggregates\n ).then(aggregateResult =>\n convertToAggregateQuerySnapshot(firestore, query, aggregateResult)\n );\n}\n\nfunction convertToAggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n query: Query,\n aggregateResult: ApiClientObjectMap\n): AggregateQuerySnapshot {\n const userDataWriter = new LiteUserDataWriter(firestore);\n const querySnapshot = new AggregateQuerySnapshot<\n AggregateSpecType,\n AppModelType,\n DbModelType\n >(query, userDataWriter, aggregateResult);\n return querySnapshot;\n}\n\n/**\n * Create an AggregateField object that can be used to compute the sum of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to sum across the result set.\n */\nexport function sum(field: string | FieldPath): AggregateField {\n return new AggregateField('sum', fieldPathFromArgument('sum', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the average of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to average across the result set.\n */\nexport function average(\n field: string | FieldPath\n): AggregateField {\n return new AggregateField('avg', fieldPathFromArgument('average', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the count of\n * documents in the result set of a query.\n */\nexport function count(): AggregateField {\n return new AggregateField('count');\n}\n\n/**\n * Compares two 'AggregateField` instances for equality.\n *\n * @param left Compare this AggregateField to the `right`.\n * @param right Compare this AggregateField to the `left`.\n */\nexport function aggregateFieldEqual(\n left: AggregateField,\n right: AggregateField\n): boolean {\n return (\n left instanceof AggregateField &&\n right instanceof AggregateField &&\n left.aggregateType === right.aggregateType &&\n left._internalFieldPath?.canonicalString() ===\n right._internalFieldPath?.canonicalString()\n );\n}\n\n/**\n * Compares two `AggregateQuerySnapshot` instances for equality.\n *\n * Two `AggregateQuerySnapshot` instances are considered \"equal\" if they have\n * underlying queries that compare equal, and the same data.\n *\n * @param left - The first `AggregateQuerySnapshot` to compare.\n * @param right - The second `AggregateQuerySnapshot` to compare.\n *\n * @returns `true` if the objects are \"equal\", as defined above, or `false`\n * otherwise.\n */\nexport function aggregateQuerySnapshotEqual<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n left: AggregateQuerySnapshot,\n right: AggregateQuerySnapshot\n): boolean {\n return (\n queryEqual(left.query, right.query) && deepEqual(left.data(), right.data())\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldValue } from './field_value';\nimport {\n ArrayRemoveFieldValueImpl,\n ArrayUnionFieldValueImpl,\n DeleteFieldValueImpl,\n NumericIncrementFieldValueImpl,\n ServerTimestampFieldValueImpl\n} from './user_data_reader';\nimport { VectorValue } from './vector_value';\n\n/**\n * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or\n * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.\n */\nexport function deleteField(): FieldValue {\n return new DeleteFieldValueImpl('deleteField');\n}\n\n/**\n * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to\n * include a server-generated timestamp in the written data.\n */\nexport function serverTimestamp(): FieldValue {\n return new ServerTimestampFieldValueImpl('serverTimestamp');\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array\n * value that already exists on the server. Each specified element that doesn't\n * already exist in the array will be added to the end. If the field being\n * modified is not already an array it will be overwritten with an array\n * containing exactly the specified elements.\n *\n * @param elements - The elements to union into the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`.\n */\nexport function arrayUnion(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayUnionFieldValueImpl('arrayUnion', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link (setDoc:1)} or {@link\n * updateDoc:1} that tells the server to remove the given elements from any\n * array value that already exists on the server. All instances of each element\n * specified will be removed from the array. If the field being modified is not\n * already an array it will be overwritten with an empty array.\n *\n * @param elements - The elements to remove from the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function arrayRemove(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayRemoveFieldValueImpl('arrayRemove', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by\n * the given value.\n *\n * If either the operand or the current field value uses floating point\n * precision, all arithmetic follows IEEE 754 semantics. If both values are\n * integers, values outside of JavaScript's safe number range\n * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to\n * precision loss. Furthermore, once processed by the Firestore backend, all\n * integer operations are capped between -2^63 and 2^63-1.\n *\n * If the current field value is not of type `number`, or if the field does not\n * yet exist, the transformation sets the field to the given value.\n *\n * @param n - The value to increment by.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function increment(n: number): FieldValue {\n return new NumericIncrementFieldValueImpl('increment', n);\n}\n\n/**\n * Creates a new `VectorValue` constructed with a copy of the given array of numbers.\n *\n * @param values - Create a `VectorValue` instance with a copy of this array of numbers.\n *\n * @returns A new `VectorValue` constructed with a copy of the given array of numbers.\n */\nexport function vector(values?: number[]): VectorValue {\n return new VectorValue(values);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Compat, getModularInstance } from '@firebase/util';\n\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { invokeCommitRpc } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport { applyFirestoreDataConverter } from './reference_impl';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\n\n/**\n * A write batch, used to perform multiple writes as a single atomic unit.\n *\n * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It\n * provides methods for adding writes to the write batch. None of the writes\n * will be committed (or visible locally) until {@link WriteBatch.commit} is\n * called.\n */\nexport class WriteBatch {\n // This is the lite version of the WriteBatch API used in the legacy SDK. The\n // class is a close copy but takes different input types.\n\n private readonly _dataReader: UserDataReader;\n private _mutations = [] as Mutation[];\n private _committed = false;\n\n /** @hideconstructor */\n constructor(\n private readonly _firestore: Firestore,\n private readonly _commitHandler: (m: Mutation[]) => Promise\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): WriteBatch;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): WriteBatch;\n set(\n documentRef: DocumentReference,\n data: WithFieldValue | PartialWithFieldValue,\n options?: SetOptions\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n data,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'WriteBatch.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._mutations.push(parsed.toMutation(ref._key, Precondition.none()));\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): WriteBatch;\n /**\n * Updates fields in the document referred to by this {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be update by providing dot-separated field path strings\n * or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._mutations.push(\n parsed.toMutation(ref._key, Precondition.exists(true))\n );\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n this._mutations = this._mutations.concat(\n new DeleteMutation(ref._key, Precondition.none())\n );\n return this;\n }\n\n /**\n * Commits all of the writes in this write batch as a single atomic unit.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `Promise` resolved once all of the writes in the batch have been\n * successfully written to the backend as an atomic unit (note that it won't\n * resolve while you're offline).\n */\n commit(): Promise {\n this._verifyNotCommitted();\n this._committed = true;\n if (this._mutations.length > 0) {\n return this._commitHandler(this._mutations);\n }\n\n return Promise.resolve();\n }\n\n private _verifyNotCommitted(): void {\n if (this._committed) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A write batch can no longer be used after commit() ' +\n 'has been called.'\n );\n }\n }\n}\n\nexport function validateReference<\n AppModelType,\n DbModelType extends DocumentData\n>(\n documentRef:\n | DocumentReference\n | Compat>,\n firestore: Firestore\n): DocumentReference {\n documentRef = getModularInstance(documentRef);\n\n if (documentRef.firestore !== firestore) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Provided document reference is from a different Firestore instance.'\n );\n } else {\n return documentRef as DocumentReference;\n }\n}\n\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single WriteBatch\n * is 500.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `WriteBatch` that can be used to atomically execute multiple\n * writes.\n */\nexport function writeBatch(firestore: Firestore): WriteBatch {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n return new WriteBatch(firestore, writes =>\n invokeCommitRpc(datastore, writes)\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParsedSetData, ParsedUpdateData } from '../lite-api/user_data_reader';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n DeleteMutation,\n Mutation,\n Precondition,\n VerifyMutation\n} from '../model/mutation';\nimport {\n Datastore,\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc\n} from '../remote/datastore';\nimport { fail, debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { SnapshotVersion } from './snapshot_version';\n\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nexport class Transaction {\n // The version of each document that was read during this transaction.\n private readVersions = new Map();\n private mutations: Mutation[] = [];\n private committed = false;\n\n /**\n * A deferred usage error that occurred previously in this transaction that\n * will cause the transaction to fail once it actually commits.\n */\n private lastTransactionError: FirestoreError | null = null;\n\n /**\n * Set of documents that have been written in the transaction.\n *\n * When there's more than one write to the same key in a transaction, any\n * writes after the first are handled differently.\n */\n private writtenDocs: Set = new Set();\n\n constructor(private datastore: Datastore) {}\n\n async lookup(keys: DocumentKey[]): Promise {\n this.ensureCommitNotCalled();\n\n if (this.mutations.length > 0) {\n this.lastTransactionError = new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Firestore transactions require all reads to be executed before all writes.'\n );\n throw this.lastTransactionError;\n }\n const docs = await invokeBatchGetDocumentsRpc(this.datastore, keys);\n docs.forEach(doc => this.recordVersion(doc));\n return docs;\n }\n\n set(key: DocumentKey, data: ParsedSetData): void {\n this.write(data.toMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n update(key: DocumentKey, data: ParsedUpdateData): void {\n try {\n this.write(data.toMutation(key, this.preconditionForUpdate(key)));\n } catch (e) {\n this.lastTransactionError = e as FirestoreError | null;\n }\n this.writtenDocs.add(key.toString());\n }\n\n delete(key: DocumentKey): void {\n this.write(new DeleteMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n async commit(): Promise {\n this.ensureCommitNotCalled();\n\n if (this.lastTransactionError) {\n throw this.lastTransactionError;\n }\n const unwritten = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach(mutation => {\n unwritten.delete(mutation.key.toString());\n });\n // For each document that was read but not written to, we want to perform\n // a `verify` operation.\n unwritten.forEach((_, path) => {\n const key = DocumentKey.fromPath(path);\n this.mutations.push(new VerifyMutation(key, this.precondition(key)));\n });\n await invokeCommitRpc(this.datastore, this.mutations);\n this.committed = true;\n }\n\n private recordVersion(doc: Document): void {\n let docVersion: SnapshotVersion;\n\n if (doc.isFoundDocument()) {\n docVersion = doc.version;\n } else if (doc.isNoDocument()) {\n // Represent a deleted doc using SnapshotVersion.min().\n docVersion = SnapshotVersion.min();\n } else {\n throw fail(0xc542, 'Document in a transaction was a ', {\n documentName: doc.constructor.name\n });\n }\n\n const existingVersion = this.readVersions.get(doc.key.toString());\n if (existingVersion) {\n if (!docVersion.isEqual(existingVersion)) {\n // This transaction will fail no matter what.\n throw new FirestoreError(\n Code.ABORTED,\n 'Document version changed between two reads.'\n );\n }\n } else {\n this.readVersions.set(doc.key.toString(), docVersion);\n }\n }\n\n /**\n * Returns the version of this document when it was read in this transaction,\n * as a precondition, or no precondition if it was not read.\n */\n private precondition(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n return Precondition.exists(false);\n } else {\n return Precondition.updateTime(version);\n }\n } else {\n return Precondition.none();\n }\n }\n\n /**\n * Returns the precondition for a document if the operation is an update.\n */\n private preconditionForUpdate(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n // The first time a document is written, we want to take into account the\n // read time and existence\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n // The document doesn't exist, so fail the transaction.\n\n // This has to be validated locally because you can't send a\n // precondition that a document does not exist without changing the\n // semantics of the backend write to be an insert. This is the reverse\n // of what we want, since we want to assert that the document doesn't\n // exist but then send the update and have it fail. Since we can't\n // express that to the backend, we have to validate locally.\n\n // Note: this can change once we can send separate verify writes in the\n // transaction.\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't update a document that doesn't exist.\"\n );\n }\n // Document exists, base precondition on document update time.\n return Precondition.updateTime(version);\n } else {\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return Precondition.exists(true);\n }\n }\n\n private write(mutation: Mutation): void {\n this.ensureCommitNotCalled();\n this.mutations.push(mutation);\n }\n\n private ensureCommitNotCalled(): void {\n debugAssert(\n !this.committed,\n 'A transaction object cannot be used after its update callback has been invoked.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\n\nexport const DEFAULT_TRANSACTION_OPTIONS: TransactionOptions = {\n maxAttempts: 5\n};\n\n/**\n * Options to customize transaction behavior.\n */\nexport declare interface TransactionOptions {\n /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */\n readonly maxAttempts: number;\n}\n\nexport function validateTransactionOptions(options: TransactionOptions): void {\n if (options.maxAttempts < 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Max attempts must be at least 1'\n );\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ExponentialBackoff } from '../remote/backoff';\nimport { Datastore } from '../remote/datastore';\nimport { isPermanentError } from '../remote/rpc_error';\nimport { AsyncQueue, TimerId } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport { Deferred } from '../util/promise';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Transaction } from './transaction';\nimport { TransactionOptions } from './transaction_options';\n\n/**\n * TransactionRunner encapsulates the logic needed to run and retry transactions\n * with backoff.\n */\nexport class TransactionRunner {\n private attemptsRemaining: number;\n private backoff: ExponentialBackoff;\n\n constructor(\n private readonly asyncQueue: AsyncQueue,\n private readonly datastore: Datastore,\n private readonly options: TransactionOptions,\n private readonly updateFunction: (transaction: Transaction) => Promise,\n private readonly deferred: Deferred\n ) {\n this.attemptsRemaining = options.maxAttempts;\n this.backoff = new ExponentialBackoff(\n this.asyncQueue,\n TimerId.TransactionRetry\n );\n }\n\n /** Runs the transaction and sets the result on deferred. */\n run(): void {\n this.attemptsRemaining -= 1;\n this.runWithBackOff();\n }\n\n private runWithBackOff(): void {\n this.backoff.backoffAndRun(async () => {\n const transaction = new Transaction(this.datastore);\n const userPromise = this.tryRunUpdateFunction(transaction);\n if (userPromise) {\n userPromise\n .then(result => {\n this.asyncQueue.enqueueAndForget(() => {\n return transaction\n .commit()\n .then(() => {\n this.deferred.resolve(result);\n })\n .catch(commitError => {\n this.handleTransactionError(commitError);\n });\n });\n })\n .catch(userPromiseError => {\n this.handleTransactionError(userPromiseError);\n });\n }\n });\n }\n\n private tryRunUpdateFunction(transaction: Transaction): Promise | null {\n try {\n const userPromise = this.updateFunction(transaction);\n if (\n isNullOrUndefined(userPromise) ||\n !userPromise.catch ||\n !userPromise.then\n ) {\n this.deferred.reject(\n Error('Transaction callback must return a Promise')\n );\n return null;\n }\n return userPromise;\n } catch (error) {\n // Do not retry errors thrown by user provided updateFunction.\n this.deferred.reject(error as Error);\n return null;\n }\n }\n\n private handleTransactionError(error: Error): void {\n if (this.attemptsRemaining > 0 && this.isRetryableTransactionError(error)) {\n this.attemptsRemaining -= 1;\n this.asyncQueue.enqueueAndForget(() => {\n this.runWithBackOff();\n return Promise.resolve();\n });\n } else {\n this.deferred.reject(error);\n }\n }\n\n private isRetryableTransactionError(error: Error | undefined): boolean {\n if (error?.name === 'FirebaseError') {\n // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and\n // non-matching document versions with ABORTED. These errors should be retried.\n const code = (error as FirestoreError).code;\n return (\n code === 'aborted' ||\n code === 'failed-precondition' ||\n code === 'already-exists' ||\n !isPermanentError(code)\n );\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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(0xb815, 'AsyncQueue is already failed', {\n messageOrStack: getMessageOrStack(this.failure)\n });\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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getGlobal, 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 `indexedDB` are guarded by SimpleDb.isAvailable() and getGlobal()\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 lastClosedDbVersion: number | null = null;\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 const globals = getGlobal();\n return wrapRequest(\n globals.indexedDB.deleteDatabase(name)\n ).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\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport {\n DEFAULT_TRANSACTION_OPTIONS,\n TransactionOptions as TransactionOptionsInternal,\n validateTransactionOptions\n} from '../core/transaction_options';\nimport { TransactionRunner } from '../core/transaction_runner';\nimport { fail } from '../util/assert';\nimport { newAsyncQueue } from '../util/async_queue_impl';\nimport { cast } from '../util/input_validation';\nimport { Deferred } from '../util/promise';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n applyFirestoreDataConverter,\n LiteUserDataWriter\n} from './reference_impl';\nimport { DocumentSnapshot } from './snapshot';\nimport { TransactionOptions } from './transaction_options';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\nimport { validateReference } from './write_batch';\n\n// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the\n// legacy SDK.\n\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nexport class Transaction {\n // This is the tree-shakeable version of the Transaction class used in the\n // legacy SDK. The class is a close copy but takes different input and output\n // types. The firestore-exp SDK further extends this class to return its API\n // type.\n\n private readonly _dataReader: UserDataReader;\n\n /** @hideconstructor */\n constructor(\n protected readonly _firestore: Firestore,\n private readonly _transaction: InternalTransaction\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */\n get(\n documentRef: DocumentReference\n ): Promise> {\n const ref = validateReference(documentRef, this._firestore);\n const userDataWriter = new LiteUserDataWriter(this._firestore);\n return this._transaction.lookup([ref._key]).then(docs => {\n if (!docs || docs.length !== 1) {\n return fail(0x5de9, 'Mismatch in docs returned from document lookup.');\n }\n const doc = docs[0];\n if (doc.isFoundDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n doc.key,\n doc,\n ref.converter\n );\n } else if (doc.isNoDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n ref._key,\n null,\n ref.converter\n );\n } else {\n throw fail(\n 0x4801,\n 'BatchGetDocumentsRequest returned unexpected document',\n {\n doc\n }\n );\n }\n });\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): this;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): this;\n set(\n documentRef: DocumentReference,\n value: PartialWithFieldValue,\n options?: SetOptions\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n value,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'Transaction.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._transaction.set(ref._key, parsed);\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): this;\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key/value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._transaction.update(ref._key, parsed);\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n this._transaction.delete(ref._key);\n return this;\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */\nexport function runTransaction(\n firestore: Firestore,\n updateFunction: (transaction: Transaction) => Promise,\n options?: TransactionOptions\n): Promise {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n const optionsWithDefaults: TransactionOptionsInternal = {\n ...DEFAULT_TRANSACTION_OPTIONS,\n ...options\n };\n validateTransactionOptions(optionsWithDefaults);\n const deferred = new Deferred();\n new TransactionRunner(\n newAsyncQueue(),\n datastore,\n optionsWithDefaults,\n internalTransaction =>\n updateFunction(new Transaction(firestore, internalTransaction)),\n deferred\n ).run();\n return deferred.promise;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 { version } from '../package.json';\nimport {\n LiteAppCheckTokenProvider,\n LiteAuthCredentialsProvider\n} from '../src/api/credentials';\nimport { databaseIdFromApp } from '../src/core/database_info';\nimport { setSDKVersion } from '../src/core/version';\nimport { Firestore } from '../src/lite-api/database';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore/lite': Firestore;\n }\n}\n\nexport function registerFirestore(): void {\n setSDKVersion(`${SDK_VERSION}_lite`);\n _registerComponent(\n new Component(\n 'firestore/lite',\n (container, { instanceIdentifier: databaseId, options: settings }) => {\n const app = container.getProvider('app').getImmediate()!;\n const firestoreInstance = new Firestore(\n new LiteAuthCredentialsProvider(\n container.getProvider('auth-internal')\n ),\n new LiteAppCheckTokenProvider(\n app,\n container.getProvider('app-check-internal')\n ),\n databaseIdFromApp(app, databaseId),\n app\n );\n if (settings) {\n firestoreInstance._setSettings(settings);\n }\n return firestoreInstance;\n },\n 'PUBLIC' as ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n // RUNTIME_ENV and BUILD_TARGET are replaced by real values during the compilation\n registerVersion('firestore-lite', version, '__RUNTIME_ENV__');\n registerVersion('firestore-lite', version, '__BUILD_TARGET__');\n}\n","/**\n * Firestore Lite\n *\n * @remarks Firestore Lite is a small online-only SDK that allows read\n * and write access to your Firestore database. All operations connect\n * directly to the backend, and `onSnapshot()` APIs are not supported.\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 { registerFirestore } from './register';\nregisterFirestore();\n\nexport {\n aggregateQuerySnapshotEqual,\n getCount,\n getAggregate,\n count,\n sum,\n average,\n aggregateFieldEqual\n} from '../src/lite-api/aggregate';\n\nexport {\n AggregateField,\n AggregateFieldType,\n AggregateSpec,\n AggregateSpecData,\n AggregateQuerySnapshot,\n AggregateType\n} from '../src/lite-api/aggregate_types';\n\nexport { FirestoreSettings as Settings } from '../src/lite-api/settings';\n\nexport {\n Firestore as Firestore,\n EmulatorMockTokenOptions,\n initializeFirestore,\n getFirestore,\n terminate,\n connectFirestoreEmulator\n} from '../src/lite-api/database';\n\nexport {\n DocumentData,\n UpdateData,\n WithFieldValue,\n PartialWithFieldValue,\n SetOptions,\n DocumentReference,\n Query,\n CollectionReference,\n collection,\n collectionGroup,\n doc,\n refEqual,\n queryEqual\n} from '../src/lite-api/reference';\n\nexport {\n and,\n endAt,\n endBefore,\n startAt,\n startAfter,\n limit,\n limitToLast,\n where,\n or,\n orderBy,\n query,\n QueryConstraint,\n QueryConstraintType,\n QueryCompositeFilterConstraint,\n QueryFilterConstraint,\n QueryFieldFilterConstraint,\n QueryOrderByConstraint,\n QueryLimitConstraint,\n QueryNonFilterConstraint,\n QueryStartAtConstraint,\n QueryEndAtConstraint,\n OrderByDirection,\n WhereFilterOp\n} from '../src/lite-api/query';\n\nexport {\n addDoc,\n deleteDoc,\n updateDoc,\n setDoc,\n getDoc,\n getDocs\n} from '../src/lite-api/reference_impl';\n\nexport {\n Primitive,\n NestedUpdateFields,\n ChildUpdateFields,\n AddPrefixToKeys,\n UnionToIntersection\n} from '../src/lite-api/types';\n\n// TODO(firestorelite): Add tests when Queries are usable\nexport { FieldPath, documentId } from '../src/lite-api/field_path';\n\n// TODO(firestorelite): Add tests when setDoc() is available\nexport { FieldValue } from '../src/lite-api/field_value';\n\nexport {\n increment,\n arrayRemove,\n arrayUnion,\n serverTimestamp,\n deleteField,\n vector\n} from '../src/lite-api/field_value_impl';\n\nexport {\n FirestoreDataConverter,\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot,\n snapshotEqual\n} from '../src/lite-api/snapshot';\n\nexport { VectorValue } from '../src/lite-api/vector_value';\n\nexport { WriteBatch, writeBatch } from '../src/lite-api/write_batch';\n\nexport { TransactionOptions } from '../src/lite-api/transaction_options';\n\nexport { Transaction, runTransaction } from '../src/lite-api/transaction';\n\nexport { setLogLevel, LogLevelString as LogLevel } from '../src/util/log';\n\nexport { Bytes } from '../src/lite-api/bytes';\n\nexport { GeoPoint } from '../src/lite-api/geo_point';\n\nexport { Timestamp } from '../src/lite-api/timestamp';\n\nexport { FirestoreErrorCode, FirestoreError } from '../src/util/error';\n"],"names":["User","constructor","uid","this","isAuthenticated","toKey","isEqual","otherUser","UNAUTHENTICATED","GOOGLE_CREDENTIALS","FIRST_PARTY","MOCK_USER","SDK_VERSION","__PRIVATE_logClient","Logger","setLogLevel","logLevel","__PRIVATE_logDebug","msg","obj","LogLevel","DEBUG","args","map","__PRIVATE_argToString","debug","__PRIVATE_logError","ERROR","error","__PRIVATE_logWarn","WARN","warn","__PRIVATE_formatJSON","value","JSON","stringify","e","fail","id","__PRIVATE_messageOrContext","context","message","__PRIVATE__fail","__PRIVATE_failure","toString","undefined","Error","__PRIVATE_hardAssert","assertion","__PRIVATE_debugCast","Code","FirestoreError","FirebaseError","code","super","name","__PRIVATE_Deferred","promise","Promise","resolve","reject","__PRIVATE_OAuthToken","user","type","headers","Map","set","__PRIVATE_EmptyAuthCredentialsProvider","getToken","invalidateToken","start","asyncQueue","changeListener","enqueueRetryable","shutdown","__PRIVATE_EmulatorAuthCredentialsProvider","token","__PRIVATE_LiteAuthCredentialsProvider","__PRIVATE_authProvider","auth","onInit","then","__PRIVATE_tokenData","accessToken","getUid","__PRIVATE_FirstPartyToken","__PRIVATE_sessionIndex","__PRIVATE_iamToken","__PRIVATE_authTokenFactory","__PRIVATE_getAuthToken","__PRIVATE__headers","__PRIVATE_authHeaderTokenValue","__PRIVATE_FirstPartyAuthCredentialsProvider","AppCheckToken","length","__PRIVATE_LiteAppCheckTokenProvider","app","__PRIVATE_appCheckProvider","appCheck","__PRIVATE_serverAppAppCheckToken","_isFirebaseServerApp","settings","appCheckToken","tokenResult","DatabaseInfo","databaseId","appId","persistenceKey","host","ssl","forceLongPolling","autoDetectLongPolling","longPollingOptions","useFetchStreams","isUsingEmulator","__PRIVATE_DEFAULT_DATABASE_NAME","DatabaseId","projectId","database","empty","isDefaultDatabase","other","__PRIVATE_randomBytes","__PRIVATE_nBytes","crypto","self","bytes","Uint8Array","getRandomValues","__PRIVATE_i","Math","floor","random","__PRIVATE_AutoId","newId","__PRIVATE_chars","__PRIVATE_maxMultiple","__PRIVATE_autoId","charAt","__PRIVATE_primitiveComparator","left","right","__PRIVATE_compareUtf8Strings","min","__PRIVATE_leftChar","__PRIVATE_rightChar","__PRIVATE_isSurrogate","__PRIVATE_MIN_SURROGATE","__PRIVATE_MAX_SURROGATE","s","c","charCodeAt","__PRIVATE_arrayEquals","comparator","every","index","__PRIVATE_DOCUMENT_KEY_NAME","BasePath","segments","offset","range","len","child","nameOrPath","slice","limit","forEach","segment","push","construct","popFirst","size","popLast","firstSegment","lastSegment","get","isEmpty","isPrefixOf","isImmediateParentOf","potentialChild","fn","end","toArray","p1","p2","comparison","compareSegments","__PRIVATE_lhs","__PRIVATE_rhs","__PRIVATE_isLhsNumeric","isNumericId","__PRIVATE_isRhsNumeric","extractNumericId","compare","startsWith","endsWith","Integer","fromString","substring","ResourcePath","canonicalString","join","toUriEncodedString","encodeURIComponent","pathComponents","path","indexOf","split","filter","emptyPath","__PRIVATE_identifierRegExp","FieldPath","isValidIdentifier","test","str","replace","isKeyField","keyField","fromServerFormat","current","__PRIVATE_addCurrentSegment","__PRIVATE_inBackticks","next","DocumentKey","fromPath","fromName","collectionGroup","hasCollectionId","collectionId","getCollectionGroup","getCollectionPath","k1","k2","isDocumentKey","fromSegments","__PRIVATE_validateNonEmptyArgument","__PRIVATE_functionName","__PRIVATE_argumentName","__PRIVATE_argument","__PRIVATE_validateDocumentPath","__PRIVATE_validateCollectionPath","__PRIVATE_isPlainObject","input","Object","getPrototypeOf","prototype","__PRIVATE_valueDescription","Array","__PRIVATE_customObjectName","__PRIVATE_tryGetCustomObjectType","__PRIVATE_cast","_delegate","description","__PRIVATE_validatePositiveNumber","n","__PRIVATE_cloneLongPollingOptions","options","clone","timeoutSeconds","__PRIVATE_lastUniqueDebugId","__PRIVATE_generateUniqueDebugId","__PRIVATE_generateInitialUniqueDebugId","round","__PRIVATE_maxResult","__PRIVATE_isNullOrUndefined","__PRIVATE_isNegativeZero","__PRIVATE_LOG_TAG","__PRIVATE_RPC_NAME_URL_MAPPING","__PRIVATE_RestConnection","__PRIVATE_shouldResourcePathBeIncludedInRequest","databaseInfo","proto","__PRIVATE_baseUrl","__PRIVATE_databasePath","__PRIVATE_requestParams","__PRIVATE_invokeRPC","__PRIVATE_rpcName","__PRIVATE_req","__PRIVATE_authToken","streamId","url","__PRIVATE_makeUrl","__PRIVATE_modifyHeadersForRequest","URL","__PRIVATE_forwardCredentials","isCloudWorkstation","__PRIVATE_performRPCRequest","response","err","__PRIVATE_invokeStreamingRPC","request","__PRIVATE_expectedResponseCount","__PRIVATE_getGoogApiClientValue","key","__PRIVATE_urlRpcName","terminate","__PRIVATE_RpcCode","RpcCode","__PRIVATE_mapCodeFromHttpStatus","status","__PRIVATE_FetchConnection","__PRIVATE_openStream","body","__PRIVATE_requestJson","__PRIVATE_fetchArgs","method","credentials","fetch","statusText","ok","__PRIVATE_errorResponse","json","isArray","__PRIVATE_errorMessage","__PRIVATE_AggregateImpl","alias","aggregateType","fieldPath","__PRIVATE_objectSize","count","hasOwnProperty","call","__PRIVATE_Base64DecodeError","ByteString","binaryString","fromBase64String","base64","__PRIVATE_decodeBase64","__PRIVATE_encoded","atob","DOMException","fromUint8Array","array","__PRIVATE_binaryStringFromUint8Array","String","fromCharCode","Symbol","iterator","done","toBase64","__PRIVATE_encodeBase64","raw","btoa","toUint8Array","__PRIVATE_uint8ArrayFromBinaryString","buffer","approximateByteSize","compareTo","EMPTY_BYTE_STRING","__PRIVATE_ISO_TIMESTAMP_REG_EXP","RegExp","__PRIVATE_normalizeTimestamp","date","nanos","__PRIVATE_fraction","exec","timestamp","__PRIVATE_nanoStr","substr","Number","__PRIVATE_parsedDate","Date","seconds","getTime","__PRIVATE_normalizeNumber","__PRIVATE_normalizeByteString","blob","property","typeString","__PRIVATE_optionalValue","result","__PRIVATE_validateJSON","__PRIVATE_schema","__PRIVATE_fieldValue","__PRIVATE_MIN_SECONDS","__PRIVATE_MS_TO_NANOS","Timestamp","now","fromMillis","fromDate","milliseconds","nanoseconds","toDate","toMillis","_compareTo","toJSON","_jsonSchemaVersion","fromJSON","_jsonSchema","valueOf","__PRIVATE_adjustedSeconds","padStart","__PRIVATE_isServerTimestamp","mapValue","fields","stringValue","__PRIVATE_getPreviousValue","previousValue","__PRIVATE_getLocalWriteTime","localWriteTime","timestampValue","__PRIVATE_TYPE_KEY","__PRIVATE_MAX_VALUE_TYPE","MAX_VALUE","__type__","__PRIVATE_VECTOR_VALUE_SENTINEL","__PRIVATE_VECTOR_MAP_VECTORS_KEY","__PRIVATE_typeOrder","__PRIVATE_isMaxValue","__PRIVATE_isVectorValue","__PRIVATE_valueEquals","__PRIVATE_leftType","booleanValue","__PRIVATE_timestampEquals","__PRIVATE_leftTimestamp","__PRIVATE_rightTimestamp","__PRIVATE_blobEquals","bytesValue","referenceValue","__PRIVATE_geoPointEquals","geoPointValue","latitude","longitude","__PRIVATE_numberEquals","integerValue","__PRIVATE_n1","doubleValue","__PRIVATE_n2","isNaN","arrayValue","values","__PRIVATE_objectEquals","__PRIVATE_leftMap","__PRIVATE_rightMap","__PRIVATE_arrayValueContains","__PRIVATE_haystack","__PRIVATE_needle","find","v","__PRIVATE_valueCompare","__PRIVATE_rightType","__PRIVATE_compareNumbers","__PRIVATE_leftNumber","__PRIVATE_rightNumber","__PRIVATE_compareTimestamps","__PRIVATE_compareBlobs","__PRIVATE_leftBytes","__PRIVATE_rightBytes","__PRIVATE_compareReferences","__PRIVATE_leftPath","__PRIVATE_rightPath","__PRIVATE_leftSegments","__PRIVATE_rightSegments","__PRIVATE_compareGeoPoints","__PRIVATE_compareArrays","__PRIVATE_compareVectors","__PRIVATE_leftArrayValue","__PRIVATE_rightArrayValue","__PRIVATE_lengthCompare","__PRIVATE_compareMaps","__PRIVATE_leftKeys","keys","__PRIVATE_rightKeys","sort","__PRIVATE_keyCompare","__PRIVATE_leftArray","__PRIVATE_rightArray","__PRIVATE_refValue","__PRIVATE_isNullValue","__PRIVATE_isNanValue","__PRIVATE_isMapValue","__PRIVATE_deepClone","source","target","val","Bound","position","inclusive","__PRIVATE_boundEquals","Filter","FieldFilter","field","op","create","createKeyFieldInFilter","__PRIVATE_KeyFieldFilter","__PRIVATE_ArrayContainsFilter","__PRIVATE_InFilter","__PRIVATE_NotInFilter","__PRIVATE_ArrayContainsAnyFilter","__PRIVATE_KeyFieldInFilter","__PRIVATE_KeyFieldNotInFilter","matches","doc","data","nullValue","matchesComparison","operator","isInequality","getFlattenedFilters","getFilters","CompositeFilter","filters","__PRIVATE_memoizedFlattenedFilters","__PRIVATE_compositeFilterIsConjunction","compositeFilter","reduce","__PRIVATE_subfilter","concat","assign","__PRIVATE_filterEquals","__PRIVATE_f1","__PRIVATE_f2","__PRIVATE_fieldFilterEquals","__PRIVATE_compositeFilterEquals","__PRIVATE_f1Filter","__PRIVATE_extractDocumentKeysFromArrayValue","some","OrderBy","dir","__PRIVATE_orderByEquals","SnapshotVersion","fromTimestamp","max","toMicroseconds","toTimestamp","SortedMap","root","LLRBNode","EMPTY","insert","copy","BLACK","remove","node","cmp","__PRIVATE_prunedNodes","minKey","maxKey","inorderTraversal","action","k","__PRIVATE_descriptions","reverseTraversal","getIterator","SortedMapIterator","getIteratorFrom","getReverseIterator","getReverseIteratorFrom","startKey","isReverse","nodeStack","getNext","pop","hasNext","peek","color","RED","fixUp","removeMin","isRed","moveRedLeft","__PRIVATE_smallest","rotateRight","moveRedRight","rotateLeft","colorFlip","__PRIVATE_nl","__PRIVATE_nr","checkMaxDepth","__PRIVATE_blackDepth","check","pow","LLRBEmptyNode","SortedSet","has","elem","first","last","cb","forEachInRange","iter","forEachWhile","firstAfterOrEqual","SortedSetIterator","add","unionWith","__PRIVATE_thisIt","__PRIVATE_otherIt","__PRIVATE_thisElem","__PRIVATE_otherElem","__PRIVATE_res","targetId","FieldMask","extraFields","__PRIVATE_mergedMaskSet","covers","__PRIVATE_fieldMaskPath","l","r","ObjectValue","__PRIVATE_currentLevel","getFieldsMap","setAll","parent","__PRIVATE_upserts","__PRIVATE_deletes","__PRIVATE_fieldsMap","applyChanges","__PRIVATE_nestedValue","__PRIVATE_inserts","MutableDocument","documentType","version","readTime","createTime","documentState","newInvalidDocument","documentKey","newFoundDocument","newNoDocument","newUnknownDocument","convertToFoundDocument","convertToNoDocument","convertToUnknownDocument","setHasCommittedMutations","setHasLocalMutations","setReadTime","hasLocalMutations","hasCommittedMutations","hasPendingWrites","isValidDocument","isFoundDocument","isNoDocument","isUnknownDocument","mutableCopy","__PRIVATE_TargetImpl","orderBy","startAt","endAt","__PRIVATE_memoizedCanonicalId","__PRIVATE_newTarget","__PRIVATE_QueryImpl","explicitOrderBy","limitType","__PRIVATE_memoizedNormalizedOrderBy","__PRIVATE_memoizedTarget","__PRIVATE_memoizedAggregateTarget","__PRIVATE_isCollectionGroupQuery","query","__PRIVATE_queryNormalizedOrderBy","__PRIVATE_queryImpl","__PRIVATE_fieldsNormalized","Set","__PRIVATE_lastDirection","__PRIVATE_inequalityFields","__PRIVATE_getInequalityFilterFields","__PRIVATE_queryToTarget","__PRIVATE__queryToTarget","__PRIVATE_orderBys","__PRIVATE_queryWithAddedFilter","__PRIVATE_newFilters","__PRIVATE_queryEquals","__PRIVATE_targetEquals","__PRIVATE_toDouble","serializer","useProto3Json","Infinity","toNumber","isSafeInteger","isInteger","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","__PRIVATE_toInteger","TransformOperation","_","__PRIVATE_ServerTimestampTransform","__PRIVATE_ArrayUnionTransformOperation","elements","__PRIVATE_ArrayRemoveTransformOperation","__PRIVATE_NumericIncrementTransformOperation","__PRIVATE_operand","FieldTransform","transform","Precondition","updateTime","exists","none","isNone","Mutation","__PRIVATE_SetMutation","precondition","fieldTransforms","getFieldMask","__PRIVATE_PatchMutation","fieldMask","__PRIVATE_DeleteMutation","__PRIVATE_VerifyMutation","__PRIVATE_DIRECTIONS","__PRIVATE_dirs","__PRIVATE_OPERATORS","__PRIVATE_ops","__PRIVATE_COMPOSITE_OPERATORS","JsonProtoSerializer","toISOString","__PRIVATE_toBytes","__PRIVATE_toVersion","__PRIVATE_fromVersion","__PRIVATE_toResourceName","__PRIVATE_toResourcePath","__PRIVATE_resourcePath","__PRIVATE_fullyQualifiedPrefixPath","__PRIVATE_toName","__PRIVATE_resource","__PRIVATE_fromResourceName","__PRIVATE_isValidResourceName","__PRIVATE_extractLocalPathFromResourceName","__PRIVATE_resourceName","__PRIVATE_toMutationDocument","__PRIVATE_fromBatchGetDocumentsResponse","__PRIVATE_fromFound","found","__PRIVATE_fromMissing","missing","toMutation","mutation","update","delete","updateMask","__PRIVATE_toDocumentMask","__PRIVATE_mutationType","verify","updateTransforms","__PRIVATE_toFieldTransform","__PRIVATE_fieldTransform","setToServerValue","appendMissingElements","removeAllFromArray","increment","currentDocument","__PRIVATE_toPrecondition","__PRIVATE_toQueryTarget","__PRIVATE_queryTarget","structuredQuery","from","allDescendants","__PRIVATE_toQueryPath","where","__PRIVATE_toFilters","__PRIVATE_toFilter","__PRIVATE_toOrder","order","__PRIVATE_toPropertyOrder","__PRIVATE_toFieldPathReference","direction","__PRIVATE_toDirection","__PRIVATE_toInt32Proto","__PRIVATE_toStartAtCursor","cursor","before","__PRIVATE_toEndAtCursor","__PRIVATE_toOperatorName","__PRIVATE_toCompositeOperatorName","__PRIVATE_toUnaryOrFieldFilter","unaryFilter","fieldFilter","__PRIVATE_toCompositeFilter","__PRIVATE_protos","__PRIVATE_canonicalFields","fieldPaths","__PRIVATE_newSerializer","__PRIVATE_ExponentialBackoff","__PRIVATE_queue","timerId","__PRIVATE_initialDelayMs","__PRIVATE_backoffFactor","__PRIVATE_maxDelayMs","__PRIVATE_currentBaseMs","__PRIVATE_timerPromise","reset","__PRIVATE_resetToMax","__PRIVATE_backoffAndRun","cancel","__PRIVATE_desiredDelayWithJitterMs","__PRIVATE_jitterDelayMs","__PRIVATE_delaySoFarMs","__PRIVATE_lastAttemptTime","__PRIVATE_remainingDelayMs","enqueueAfterDelay","__PRIVATE_skipBackoff","skipDelay","Datastore","__PRIVATE_DatastoreImpl","authCredentials","appCheckCredentials","connection","__PRIVATE_terminated","__PRIVATE_verifyInitialized","all","catch","async","__PRIVATE_invokeCommitRpc","datastore","mutations","__PRIVATE_datastoreImpl","writes","m","__PRIVATE_invokeBatchGetDocumentsRpc","documents","docs","__PRIVATE_invokeRunQueryRpc","M","document","__PRIVATE_fromDocument","__PRIVATE_invokeRunAggregationQueryRpc","__PRIVATE_aggregates","nt","__PRIVATE_aliasMap","__PRIVATE_toRunAggregationQueryRequest","__PRIVATE_skipAliasing","aggregations","__PRIVATE_aggregationNum","__PRIVATE_aggregate","__PRIVATE_serverAlias","avg","sum","structuredAggregationQuery","__PRIVATE_queryToAggregateTarget","__PRIVATE_filteredResult","__PRIVATE_unmappedAggregateFields","aggregateFields","__PRIVATE_accumulator","__PRIVATE_datastoreInstances","__PRIVATE_getDatastore","firestore","_terminated","__PRIVATE_newConnection","__PRIVATE_makeDatabaseInfo","experimentalForceLongPolling","experimentalAutoDetectLongPolling","experimentalLongPollingOptions","_databaseId","_persistenceKey","_freezeSettings","__PRIVATE_newDatastore","_authCredentials","_appCheckCredentials","__PRIVATE_LRU_MINIMUM_CACHE_SIZE_BYTES","__PRIVATE_DEFAULT_HOST","__PRIVATE_DEFAULT_SSL","FirestoreSettingsImpl","emulatorOptions","ignoreUndefinedProperties","localCache","cacheSizeBytes","__PRIVATE_validateIsNotUsedTogether","optionName1","argument1","optionName2","argument2","__PRIVATE_validateLongPollingOptions","__PRIVATE_longPollingOptionsEqual","__PRIVATE_options1","__PRIVATE_options2","Firestore","_app","_settings","_settingsFrozen","_emulatorOptions","_terminateTask","_initialized","_setSettings","__PRIVATE_makeAuthCredentialsProvider","_getSettings","_getEmulatorOptions","_delete","_terminate","_restart","__PRIVATE_removeComponents","initializeFirestore","provider","_getProvider","isInitialized","initialize","instanceIdentifier","getFirestore","__PRIVATE_appOrDatabaseId","__PRIVATE_optionalDatabaseId","getApp","db","getImmediate","identifier","__PRIVATE_emulator","getDefaultEmulatorHostnameAndPort","connectFirestoreEmulator","port","__PRIVATE_useSsl","__PRIVATE_existingConfig","__PRIVATE_newHostSetting","pingServer","updateEmulatorBanner","__PRIVATE_newConfig","deepEqual","mockUserToken","createMockUserToken","sub","user_id","_removeServiceInstance","AggregateField","_internalFieldPath","AggregateQuerySnapshot","_userDataWriter","_data","convertObjectMap","Query","converter","_query","withConverter","DocumentReference","_key","_path","CollectionReference","referencePath","__PRIVATE_newQueryForPath","parentPath","collection","pathSegments","getModularInstance","__PRIVATE_absolutePath","__PRIVATE_newQueryForCollectionGroup","arguments","refEqual","queryEqual","Bytes","byteString","_byteString","fieldNames","_internalPath","__PRIVATE_InternalFieldPath","documentId","FieldValue","_methodName","GeoPoint","isFinite","_lat","_long","VectorValue","_values","__PRIVATE_isPrimitiveArrayEqual","vectorValues","element","__PRIVATE_RESERVED_FIELD_REGEX","ParsedSetData","ParsedUpdateData","__PRIVATE_isWrite","__PRIVATE_dataSource","__PRIVATE_ParseContextImpl","__PRIVATE_validatePath","__PRIVATE_contextWith","configuration","__PRIVATE_childContextForField","__PRIVATE_childPath","__PRIVATE_arrayElement","__PRIVATE_validatePathSegment","__PRIVATE_childContextForFieldPath","__PRIVATE_childContextForArray","__PRIVATE_createError","reason","methodName","__PRIVATE_hasConverter","__PRIVATE_targetDoc","contains","__PRIVATE_UserDataReader","__PRIVATE_createContext","__PRIVATE_newUserDataReader","__PRIVATE_parseSetData","__PRIVATE_userDataReader","merge","mergeFields","__PRIVATE_validatePlainObject","__PRIVATE_updateData","__PRIVATE_parseObject","__PRIVATE_validatedFieldPaths","__PRIVATE_stringOrFieldPath","__PRIVATE_fieldPathFromArgument","__PRIVATE_fieldMaskContains","__PRIVATE_DeleteFieldValueImpl","_toFieldTransform","__PRIVATE_createSentinelChildContext","__PRIVATE_ServerTimestampFieldValueImpl","__PRIVATE_ArrayUnionFieldValueImpl","__PRIVATE__elements","__PRIVATE_parseContext","__PRIVATE_parsedElements","__PRIVATE_parseData","arrayUnion","__PRIVATE_ArrayRemoveFieldValueImpl","__PRIVATE_NumericIncrementFieldValueImpl","__PRIVATE__operand","__PRIVATE_numericIncrement","__PRIVATE_parseUpdateData","__PRIVATE_fieldMaskPaths","__PRIVATE_fieldPathFromDotSeparatedString","__PRIVATE_childContext","__PRIVATE_parsedValue","mask","__PRIVATE_parseUpdateVarargs","moreFieldsAndValues","__PRIVATE_parseQueryValue","__PRIVATE_allowArrays","__PRIVATE_looksLikeJsonObject","__PRIVATE_parseSentinelFieldValue","__PRIVATE_parseArray","__PRIVATE_entryIndex","entry","__PRIVATE_parsedEntry","__PRIVATE_parseScalarValue","__PRIVATE_thisDb","__PRIVATE_otherDb","__PRIVATE_parseVectorValue","__PRIVATE_FIELD_PATH_RESERVED","search","__PRIVATE_hasPath","__PRIVATE_hasDocument","DocumentSnapshot","_firestore","_document","_converter","ref","snapshot","QueryDocumentSnapshot","fromFirestore","convertValue","QuerySnapshot","_docs","callback","thisArg","snapshotEqual","arg","AppliableConstraint","QueryConstraint","__PRIVATE_queryConstraint","__PRIVATE_additionalQueryConstraints","queryConstraints","__PRIVATE_validateQueryConstraintArray","__PRIVATE_compositeFilterCount","QueryCompositeFilterConstraint","__PRIVATE_fieldFilterCount","QueryFieldFilterConstraint","constraint","_apply","_field","_op","_value","_create","_parse","__PRIVATE_validateNewFieldFilter","__PRIVATE_reader","__PRIVATE_newQueryFilter","__PRIVATE_dataReader","__PRIVATE_validateDisjunctiveFilterElements","__PRIVATE_referenceList","__PRIVATE_parseDocumentIdValue","opStr","_queryConstraints","__PRIVATE_parsedFilters","__PRIVATE_parsedFilter","_getOperator","__PRIVATE_validateNewFilter","__PRIVATE_testQuery","__PRIVATE_subFilters","__PRIVATE_subFilter","_getQueryConstraints","or","__PRIVATE_validateQueryFilterConstraint","and","QueryOrderByConstraint","_direction","__PRIVATE_newQueryOrderBy","__PRIVATE_queryWithAddedOrderBy","__PRIVATE_newOrderBy","directionStr","QueryLimitConstraint","_limit","_limitType","__PRIVATE_queryWithLimit","limitToLast","QueryStartAtConstraint","_docOrFields","_inclusive","bound","__PRIVATE_newQueryBoundFromDocOrFields","__PRIVATE_queryWithStartAt","__PRIVATE_docOrFields","startAfter","QueryEndAtConstraint","__PRIVATE_queryWithEndAt","endBefore","__PRIVATE_newQueryBoundFromDocument","components","__PRIVATE_newQueryBoundFromFields","__PRIVATE_rawValue","__PRIVATE_wrapped","__PRIVATE_documentIdValue","__PRIVATE_conflictingOp","__PRIVATE_findOpInsideFilters","__PRIVATE_operators","__PRIVATE_conflictingOps","AbstractUserDataWriter","serverTimestampBehavior","convertTimestamp","convertServerTimestamp","convertBytes","convertReference","convertGeoPoint","convertArray","convertObject","convertVectorValue","__PRIVATE_normalizedValue","convertDocumentKey","expectedDatabaseId","__PRIVATE_applyFirestoreDataConverter","__PRIVATE_convertedValue","toFirestore","__PRIVATE_LiteUserDataWriter","getDoc","reference","userDataWriter","getDocs","__PRIVATE_validateHasExplicitOrderByForLimitToLast","reverse","setDoc","__PRIVATE_parsed","updateDoc","__PRIVATE_fieldOrUpdateData","deleteDoc","addDoc","__PRIVATE_docRef","getCount","getAggregate","aggregateSpec","__PRIVATE_internalAggregates","__PRIVATE_mapToArray","__PRIVATE_aggregateResult","__PRIVATE_convertToAggregateQuerySnapshot","__PRIVATE_querySnapshot","average","aggregateFieldEqual","aggregateQuerySnapshotEqual","deleteField","serverTimestamp","arrayRemove","vector","WriteBatch","_commitHandler","_mutations","_committed","_dataReader","documentRef","_verifyNotCommitted","__PRIVATE_validateReference","commit","writeBatch","Transaction","readVersions","committed","lastTransactionError","writtenDocs","lookup","ensureCommitNotCalled","recordVersion","write","preconditionForUpdate","__PRIVATE_unwritten","__PRIVATE_docVersion","__PRIVATE_documentName","__PRIVATE_existingVersion","__PRIVATE_DEFAULT_TRANSACTION_OPTIONS","maxAttempts","__PRIVATE_TransactionRunner","updateFunction","deferred","__PRIVATE_attemptsRemaining","__PRIVATE_backoff","__PRIVATE_run","__PRIVATE_runWithBackOff","transaction","__PRIVATE_userPromise","__PRIVATE_tryRunUpdateFunction","enqueueAndForget","__PRIVATE_commitError","__PRIVATE_handleTransactionError","__PRIVATE_userPromiseError","__PRIVATE_isRetryableTransactionError","__PRIVATE_isPermanentError","getDocument","DelayedOperation","targetTimeMs","removalCallback","bind","createAndSchedule","delayMs","__PRIVATE_targetTime","__PRIVATE_delayedOp","timerHandle","setTimeout","handleDelayElapsed","clearTimeout","__PRIVATE_AsyncQueueImpl","__PRIVATE_tail","__PRIVATE_retryableOps","__PRIVATE__isShuttingDown","__PRIVATE_delayedOperations","__PRIVATE_operationInProgress","__PRIVATE_skipNonRestrictedTasks","__PRIVATE_timerIdsToSkip","__PRIVATE_visibilityHandler","visibilityState","addEventListener","isShuttingDown","enqueue","enqueueAndForgetEvenWhileRestricted","__PRIVATE_verifyNotFailed","__PRIVATE_enqueueInternal","enterRestrictedMode","purgeExistingTasks","removeEventListener","task","__PRIVATE_retryNextOp","shift","__PRIVATE_isIndexedDbTransactionError","__PRIVATE_newTail","__PRIVATE_getMessageOrStack","__PRIVATE_removedOp","__PRIVATE_removeDelayedOperation","__PRIVATE_messageOrStack","verifyOperationInProgress","__PRIVATE_drain","__PRIVATE_currentTail","__PRIVATE_containsDelayedOperation","__PRIVATE_runAllDelayedOperationsUntil","__PRIVATE_lastTimerId","a","b","__PRIVATE_skipDelaysForTimerId","splice","stack","includes","_transaction","runTransaction","__PRIVATE_optionsWithDefaults","__PRIVATE_validateTransactionOptions","__PRIVATE_newAsyncQueue","__PRIVATE_internalTransaction","__PRIVATE_registerFirestore","__PRIVATE_setSDKVersion","_registerComponent","Component","container","getProvider","__PRIVATE_firestoreInstance","__PRIVATE_databaseIdFromApp","apply","setMultipleInstances","registerVersion"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAqBaA,IAAAA,MAAAA,IAAAA,CAAAA;AAUX,IAAA,WAAAC,CAAqBC,CAAAA,EAAAA;AAAAC,QAAAA,IAAAA,CAAGD,GAAHA,GAAAA,CAAAA,CAAAA;AAAsB,KAAA;IAE3C,eAAAE,GAAAA;AACE,QAAA,OAAmB,QAAZD,IAAKD,CAAAA,GAAAA,CAAAA;AACb,KAAA;;;;WAMD,KAAAG,GAAAA;AACE,QAAA,OAAIF,IAAKC,CAAAA,eAAAA,EAAAA,GACA,MAASD,GAAAA,IAAAA,CAAKD,GAEd,GAAA,gBAAA,CAAA;AAEV,KAAA;AAED,IAAA,OAAAI,CAAQC,CAAAA,EAAAA;QACN,OAAOA,CAAAA,CAAUL,QAAQC,IAAKD,CAAAA,GAAAA,CAAAA;AAC/B,KAAA;;;+BA5BeM,IAAAA,CAAAA,eAAAA,GAAkB,IAAIR,IAAK,CAAA,IAAA,CAAA;;;AAI3BA,IAAAA,CAAAS,qBAAqB,IAAIT,IAAAA,CAAK,2BAC9BA,IAAAU,CAAAA,WAAAA,GAAc,IAAIV,IAAK,CAAA,iBAAA,CAAA;AACvBA,IAAAW,CAAAA,SAAAA,GAAY,IAAIX,IAAK,CAAA,WAAA,CAAA,CAAA;;;;;;;;;;;;;;;;;;ACVhC,IAAIY,CAAAA,GAAAA,QAAAA,CAAAA;;;;;;;;;;;;;;;;;;ACKX,MAAMC,CAAAA,GAAY,IAAIC,MAAO,CAAA,qBAAA,CAAA,CAAA;;;;;;;;;;;;;;AAoBvB,IAAA,SAAUC,WAAYC,CAAAA,CAAAA,EAAAA;AAC1BH,IAAAA,CAAAA,CAAUE,W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,CACAsB,EAAAA,CAAAA,EAAAA;YAEA,IAAK6H,CAAAA,MAAAA,CAAOE,SAAU2E,CAAAA,cAAAA,CAAe86B,KAAM9oC,CAAAA,CAAAA,CAAIgK,OAAS,EAAA,EAAC,WACvD,EAAA,CAAA,EAAA,MAAM,IAAI7M,cAAAA,CACRD,CACA,EAAA,qDAAA,CAAA,CAAA;AAIJ,YAAA,OAAO,IAAIkE,UAAAA,CAAWpB,CAAIgK,CAAAA,OAAAA,CAAQ3I,SAAYC,EAAAA,CAAAA,CAAAA,CAAAA;AAChD,SsE3CUunC,CAAkB7oC,GAAKS,CACvBT,CAAAA,EAAAA,CAAAA,CAAAA,CAAAA;QAKF,OAHIK,CAAAA,IACFuoC,CAAkBrY,CAAAA,YAAAA,CAAalwB,CAE1BuoC,CAAAA,EAAAA,CAAAA,CAAAA;AAAiB,KAAA,GAE1B,UACAG,oBAAqB,CAAA,CAAA,CAAA,CAAA,CAAA;;AAGzBC,IAAAA,eAAAA,CAAgB,gBAAkB3oB,EAAAA,CAAAA,EAAS,EAC3C2oB,CAAAA,EAAAA,eAAAA,CAAgB,kBAAkB3oB,CAAS,EAAA,SAAA,CAAA,CAAA;AAC7C,CCzCAioB,EAAAA;;;;"} \ No newline at end of file diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/index.cjs.js b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.cjs.js new file mode 100644 index 0000000..e8ab979 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.cjs.js @@ -0,0 +1,7660 @@ +import { _registerComponent, registerVersion, _isFirebaseServerApp, _getProvider, getApp, _removeServiceInstance, SDK_VERSION } from '@firebase/app'; +import { Component } from '@firebase/component'; +import { Logger, LogLevel } from '@firebase/logger'; +import { FirebaseError, getDefaultEmulatorHostnameAndPort, isCloudWorkstation, pingServer, updateEmulatorBanner, deepEqual, createMockUserToken, getModularInstance } from '@firebase/util'; +import { Integer } from '@firebase/webchannel-wrapper/bloom-blob'; + +const P = "4.9.2"; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Simple wrapper around a nullable UID. Mostly exists to make code more + * readable. + */ class User { + constructor(t) { + this.uid = t; + } + isAuthenticated() { + return null != this.uid; + } + /** + * Returns a key representing this user, suitable for inclusion in a + * dictionary. + */ toKey() { + return this.isAuthenticated() ? "uid:" + this.uid : "anonymous-user"; + } + isEqual(t) { + return t.uid === this.uid; + } +} + +/** A user with a null UID. */ User.UNAUTHENTICATED = new User(null), +// TODO(mikelehen): Look into getting a proper uid-equivalent for +// non-FirebaseAuth providers. +User.GOOGLE_CREDENTIALS = new User("google-credentials-uid"), User.FIRST_PARTY = new User("first-party-uid"), +User.MOCK_USER = new User("mock-user"); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let A = "12.3.0"; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const R = new Logger("@firebase/firestore"); + +/** + * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). + * + * @param logLevel - The verbosity you set for activity and error logging. Can + * be any of the following values: + * + *
    + *
  • `debug` for the most verbose logging level, primarily for + * debugging.
  • + *
  • `error` to log errors only.
  • + *
  • `silent` to turn off logging.
  • + *
+ */ function setLogLevel(t) { + R.setLogLevel(t); +} + +function __PRIVATE_logDebug(t, ...e) { + if (R.logLevel <= LogLevel.DEBUG) { + const r = e.map(__PRIVATE_argToString); + R.debug(`Firestore (${A}): ${t}`, ...r); + } +} + +function __PRIVATE_logError(t, ...e) { + if (R.logLevel <= LogLevel.ERROR) { + const r = e.map(__PRIVATE_argToString); + R.error(`Firestore (${A}): ${t}`, ...r); + } +} + +/** + * @internal + */ function __PRIVATE_logWarn(t, ...e) { + if (R.logLevel <= LogLevel.WARN) { + const r = e.map(__PRIVATE_argToString); + R.warn(`Firestore (${A}): ${t}`, ...r); + } +} + +/** + * Converts an additional log parameter to a string representation. + */ function __PRIVATE_argToString(t) { + if ("string" == typeof t) return t; + try { + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** Formats an object as a JSON string, suitable for logging. */ + return function __PRIVATE_formatJSON(t) { + return JSON.stringify(t); + }(t); + } catch (e) { + // Converting to JSON failed, just log the object directly + return t; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function fail(t, e, r) { + let n = "Unexpected state"; + "string" == typeof e ? n = e : r = e, __PRIVATE__fail(t, n, r); +} + +function __PRIVATE__fail(t, e, r) { + // Log the failure in addition to throw an exception, just in case the + // exception is swallowed. + let n = `FIRESTORE (${A}) INTERNAL ASSERTION FAILED: ${e} (ID: ${t.toString(16)})`; + if (void 0 !== r) try { + n += " CONTEXT: " + JSON.stringify(r); + } catch (t) { + n += " CONTEXT: " + r; + } + // NOTE: We don't use FirestoreError here because these are internal failures + // that cannot be handled by the user. (Also it would create a circular + // dependency between the error and assert modules which doesn't work.) + throw __PRIVATE_logError(n), new Error(n); +} + +function __PRIVATE_hardAssert(t, e, r, n) { + let i = "Unexpected state"; + "string" == typeof r ? i = r : n = r, t || __PRIVATE__fail(e, i, n); +} + +/** + * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an + * instance of `T` before casting. + */ function __PRIVATE_debugCast(t, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +e) { + return t; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const V = "ok", I = "cancelled", p = "unknown", y = "invalid-argument", g = "deadline-exceeded", w = "not-found", F = "already-exists", v = "permission-denied", D = "unauthenticated", b = "resource-exhausted", S = "failed-precondition", C = "aborted", N = "out-of-range", O = "unimplemented", q = "internal", B = "unavailable", $ = "data-loss"; + +/** An error returned by a Firestore operation. */ class FirestoreError extends FirebaseError { + /** @hideconstructor */ + constructor( + /** + * The backend error code associated with this error. + */ + t, + /** + * A custom error description. + */ + e) { + super(t, e), this.code = t, this.message = e, + // HACK: We write a toString property directly because Error is not a real + // class and so inheritance does not work correctly. We could alternatively + // do the same "back-door inheritance" trick that FirebaseError does. + this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_Deferred { + constructor() { + this.promise = new Promise(((t, e) => { + this.resolve = t, this.reject = e; + })); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_OAuthToken { + constructor(t, e) { + this.user = e, this.type = "OAuth", this.headers = new Map, this.headers.set("Authorization", `Bearer ${t}`); + } +} + +/** + * A CredentialsProvider that always yields an empty token. + * @internal + */ class __PRIVATE_EmptyAuthCredentialsProvider { + getToken() { + return Promise.resolve(null); + } + invalidateToken() {} + start(t, e) { + // Fire with initial user. + t.enqueueRetryable((() => e(User.UNAUTHENTICATED))); + } + shutdown() {} +} + +/** + * A CredentialsProvider that always returns a constant token. Used for + * emulator token mocking. + */ class __PRIVATE_EmulatorAuthCredentialsProvider { + constructor(t) { + this.token = t, + /** + * Stores the listener registered with setChangeListener() + * This isn't actually necessary since the UID never changes, but we use this + * to verify the listen contract is adhered to in tests. + */ + this.changeListener = null; + } + getToken() { + return Promise.resolve(this.token); + } + invalidateToken() {} + start(t, e) { + this.changeListener = e, + // Fire with initial user. + t.enqueueRetryable((() => e(this.token.user))); + } + shutdown() { + this.changeListener = null; + } +} + +/** Credential provider for the Lite SDK. */ class __PRIVATE_LiteAuthCredentialsProvider { + constructor(t) { + this.auth = null, t.onInit((t => { + this.auth = t; + })); + } + getToken() { + return this.auth ? this.auth.getToken().then((t => t ? (__PRIVATE_hardAssert("string" == typeof t.accessToken, 42297, { + t: t + }), new __PRIVATE_OAuthToken(t.accessToken, new User(this.auth.getUid()))) : null)) : Promise.resolve(null); + } + invalidateToken() {} + start(t, e) {} + shutdown() {} +} + +/* + * FirstPartyToken provides a fresh token each time its value + * is requested, because if the token is too old, requests will be rejected. + * Technically this may no longer be necessary since the SDK should gracefully + * recover from unauthenticated errors (see b/33147818 for context), but it's + * safer to keep the implementation as-is. + */ class __PRIVATE_FirstPartyToken { + constructor(t, e, r) { + this.i = t, this.o = e, this.u = r, this.type = "FirstParty", this.user = User.FIRST_PARTY, + this.l = new Map; + } + /** + * Gets an authorization token, using a provided factory function, or return + * null. + */ h() { + return this.u ? this.u() : null; + } + get headers() { + this.l.set("X-Goog-AuthUser", this.i); + // Use array notation to prevent minification + const t = this.h(); + return t && this.l.set("Authorization", t), this.o && this.l.set("X-Goog-Iam-Authorization-Token", this.o), + this.l; + } +} + +/* + * Provides user credentials required for the Firestore JavaScript SDK + * to authenticate the user, using technique that is only available + * to applications hosted by Google. + */ class __PRIVATE_FirstPartyAuthCredentialsProvider { + constructor(t, e, r) { + this.i = t, this.o = e, this.u = r; + } + getToken() { + return Promise.resolve(new __PRIVATE_FirstPartyToken(this.i, this.o, this.u)); + } + start(t, e) { + // Fire with initial uid. + t.enqueueRetryable((() => e(User.FIRST_PARTY))); + } + shutdown() {} + invalidateToken() {} +} + +class AppCheckToken { + constructor(t) { + this.value = t, this.type = "AppCheck", this.headers = new Map, t && t.length > 0 && this.headers.set("x-firebase-appcheck", this.value); + } +} + +/** AppCheck token provider for the Lite SDK. */ class __PRIVATE_LiteAppCheckTokenProvider { + constructor(e, r) { + this.m = r, this.appCheck = null, this.T = null, _isFirebaseServerApp(e) && e.settings.appCheckToken && (this.T = e.settings.appCheckToken), + r.onInit((t => { + this.appCheck = t; + })); + } + getToken() { + return this.T ? Promise.resolve(new AppCheckToken(this.T)) : this.appCheck ? this.appCheck.getToken().then((t => t ? (__PRIVATE_hardAssert("string" == typeof t.token, 3470, { + tokenResult: t + }), new AppCheckToken(t.token)) : null)) : Promise.resolve(null); + } + invalidateToken() {} + start(t, e) {} + shutdown() {} +} + +/** + * Builds a CredentialsProvider depending on the type of + * the credentials passed in. + */ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class DatabaseInfo { + /** + * Constructs a DatabaseInfo using the provided host, databaseId and + * persistenceKey. + * + * @param databaseId - The database to use. + * @param appId - The Firebase App Id. + * @param persistenceKey - A unique identifier for this Firestore's local + * storage (used in conjunction with the databaseId). + * @param host - The Firestore backend host to connect to. + * @param ssl - Whether to use SSL when connecting. + * @param forceLongPolling - Whether to use the forceLongPolling option + * when using WebChannel as the network transport. + * @param autoDetectLongPolling - Whether to use the detectBufferingProxy + * option when using WebChannel as the network transport. + * @param longPollingOptions Options that configure long-polling. + * @param useFetchStreams Whether to use the Fetch API instead of + * XMLHTTPRequest + */ + constructor(t, e, r, n, i, s, o, a, u, _) { + this.databaseId = t, this.appId = e, this.persistenceKey = r, this.host = n, this.ssl = i, + this.forceLongPolling = s, this.autoDetectLongPolling = o, this.longPollingOptions = a, + this.useFetchStreams = u, this.isUsingEmulator = _; + } +} + +/** The default database name for a project. */ const Q = "(default)"; + +/** + * Represents the database ID a Firestore client is associated with. + * @internal + */ class DatabaseId { + constructor(t, e) { + this.projectId = t, this.database = e || Q; + } + static empty() { + return new DatabaseId("", ""); + } + get isDefaultDatabase() { + return this.database === Q; + } + isEqual(t) { + return t instanceof DatabaseId && t.projectId === this.projectId && t.database === this.database; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Generates `nBytes` of random bytes. + * + * If `nBytes < 0` , an error will be thrown. + */ +function __PRIVATE_randomBytes(t) { + // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available. + const e = + // eslint-disable-next-line @typescript-eslint/no-explicit-any + "undefined" != typeof self && (self.crypto || self.msCrypto), r = new Uint8Array(t); + if (e && "function" == typeof e.getRandomValues) e.getRandomValues(r); else + // Falls back to Math.random + for (let e = 0; e < t; e++) r[e] = Math.floor(256 * Math.random()); + return r; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A utility class for generating unique alphanumeric IDs of a specified length. + * + * @internal + * Exported internally for testing purposes. + */ class __PRIVATE_AutoId { + static newId() { + // Alphanumeric characters + const t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", e = 62 * Math.floor(256 / 62); + // The largest byte value that is a multiple of `char.length`. + let r = ""; + for (;r.length < 20; ) { + const n = __PRIVATE_randomBytes(40); + for (let i = 0; i < n.length; ++i) + // Only accept values that are [0, maxMultiple), this ensures they can + // be evenly mapped to indices of `chars` via a modulo operation. + r.length < 20 && n[i] < e && (r += t.charAt(n[i] % 62)); + } + return r; + } +} + +function __PRIVATE_primitiveComparator(t, e) { + return t < e ? -1 : t > e ? 1 : 0; +} + +/** Compare strings in UTF-8 encoded byte order */ function __PRIVATE_compareUtf8Strings(t, e) { + // Find the first differing character (a.k.a. "UTF-16 code unit") in the two strings and, + // if found, use that character to determine the relative ordering of the two strings as a + // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by + // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8 + // and UTF-16 happen to represent Unicode code points. + // After finding the first pair of differing characters, there are two cases: + // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or + // both are surrogates from a surrogate pair (that collectively represent code points greater + // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the + // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is + // sufficient. + // Case 2: One character is a surrogate and the other is not. In this case the surrogate- + // containing string is always ordered after the non-surrogate. This is because surrogates are + // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations + // and are lexicographically greater than the 1, 2, or 3-byte representations of code points + // less than or equal to 0xFFFF. + // An example of why Case 2 is required is comparing the following two Unicode code points: + // |-----------------------|------------|---------------------|-----------------| + // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding | + // |-----------------------|------------|---------------------|-----------------| + // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD | + // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 | + // |-----------------------|------------|---------------------|-----------------| + // A lexicographical comparison of the UTF-8 encodings of these code points would order + // "Replacement Character" _before_ "Grinning Face" because 0xEF is less than 0xF0. However, a + // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously + // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out, + // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate + // pair with those that do not. + const r = Math.min(t.length, e.length); + for (let n = 0; n < r; n++) { + const r = t.charAt(n), i = e.charAt(n); + if (r !== i) return __PRIVATE_isSurrogate(r) === __PRIVATE_isSurrogate(i) ? __PRIVATE_primitiveComparator(r, i) : __PRIVATE_isSurrogate(r) ? 1 : -1; + } + // Use the lengths of the strings to determine the overall comparison result since either the + // strings were equal or one is a prefix of the other. + return __PRIVATE_primitiveComparator(t.length, e.length); +} + +const k = 55296, L = 57343; + +function __PRIVATE_isSurrogate(t) { + const e = t.charCodeAt(0); + return e >= k && e <= L; +} + +/** Helper to compare arrays using isEqual(). */ function __PRIVATE_arrayEquals(t, e, r) { + return t.length === e.length && t.every(((t, n) => r(t, e[n]))); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const M = "__name__"; + +/** + * Path represents an ordered sequence of string segments. + */ class BasePath { + constructor(t, e, r) { + void 0 === e ? e = 0 : e > t.length && fail(637, { + offset: e, + range: t.length + }), void 0 === r ? r = t.length - e : r > t.length - e && fail(1746, { + length: r, + range: t.length - e + }), this.segments = t, this.offset = e, this.len = r; + } + get length() { + return this.len; + } + isEqual(t) { + return 0 === BasePath.comparator(this, t); + } + child(t) { + const e = this.segments.slice(this.offset, this.limit()); + return t instanceof BasePath ? t.forEach((t => { + e.push(t); + })) : e.push(t), this.construct(e); + } + /** The index of one past the last segment of the path. */ limit() { + return this.offset + this.length; + } + popFirst(t) { + return t = void 0 === t ? 1 : t, this.construct(this.segments, this.offset + t, this.length - t); + } + popLast() { + return this.construct(this.segments, this.offset, this.length - 1); + } + firstSegment() { + return this.segments[this.offset]; + } + lastSegment() { + return this.get(this.length - 1); + } + get(t) { + return this.segments[this.offset + t]; + } + isEmpty() { + return 0 === this.length; + } + isPrefixOf(t) { + if (t.length < this.length) return !1; + for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1; + return !0; + } + isImmediateParentOf(t) { + if (this.length + 1 !== t.length) return !1; + for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1; + return !0; + } + forEach(t) { + for (let e = this.offset, r = this.limit(); e < r; e++) t(this.segments[e]); + } + toArray() { + return this.segments.slice(this.offset, this.limit()); + } + /** + * Compare 2 paths segment by segment, prioritizing numeric IDs + * (e.g., "__id123__") in numeric ascending order, followed by string + * segments in lexicographical order. + */ static comparator(t, e) { + const r = Math.min(t.length, e.length); + for (let n = 0; n < r; n++) { + const r = BasePath.compareSegments(t.get(n), e.get(n)); + if (0 !== r) return r; + } + return __PRIVATE_primitiveComparator(t.length, e.length); + } + static compareSegments(t, e) { + const r = BasePath.isNumericId(t), n = BasePath.isNumericId(e); + return r && !n ? -1 : !r && n ? 1 : r && n ? BasePath.extractNumericId(t).compare(BasePath.extractNumericId(e)) : __PRIVATE_compareUtf8Strings(t, e); + } + // Checks if a segment is a numeric ID (starts with "__id" and ends with "__"). + static isNumericId(t) { + return t.startsWith("__id") && t.endsWith("__"); + } + static extractNumericId(t) { + return Integer.fromString(t.substring(4, t.length - 2)); + } +} + +/** + * A slash-separated path for navigating resources (documents and collections) + * within Firestore. + * + * @internal + */ class ResourcePath extends BasePath { + construct(t, e, r) { + return new ResourcePath(t, e, r); + } + canonicalString() { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + return this.toArray().join("/"); + } + toString() { + return this.canonicalString(); + } + /** + * Returns a string representation of this path + * where each path segment has been encoded with + * `encodeURIComponent`. + */ toUriEncodedString() { + return this.toArray().map(encodeURIComponent).join("/"); + } + /** + * Creates a resource path from the given slash-delimited string. If multiple + * arguments are provided, all components are combined. Leading and trailing + * slashes from all components are ignored. + */ static fromString(...t) { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + const e = []; + for (const r of t) { + if (r.indexOf("//") >= 0) throw new FirestoreError(y, `Invalid segment (${r}). Paths must not contain // in them.`); + // Strip leading and trailing slashed. + e.push(...r.split("/").filter((t => t.length > 0))); + } + return new ResourcePath(e); + } + static emptyPath() { + return new ResourcePath([]); + } +} + +const x = /^[_a-zA-Z][_a-zA-Z0-9]*$/; + +/** + * A dot-separated path for navigating sub-objects within a document. + * @internal + */ class FieldPath$1 extends BasePath { + construct(t, e, r) { + return new FieldPath$1(t, e, r); + } + /** + * Returns true if the string could be used as a segment in a field path + * without escaping. + */ static isValidIdentifier(t) { + return x.test(t); + } + canonicalString() { + return this.toArray().map((t => (t = t.replace(/\\/g, "\\\\").replace(/`/g, "\\`"), + FieldPath$1.isValidIdentifier(t) || (t = "`" + t + "`"), t))).join("."); + } + toString() { + return this.canonicalString(); + } + /** + * Returns true if this field references the key of a document. + */ isKeyField() { + return 1 === this.length && this.get(0) === M; + } + /** + * The field designating the key of a document. + */ static keyField() { + return new FieldPath$1([ M ]); + } + /** + * Parses a field string from the given server-formatted string. + * + * - Splitting the empty string is not allowed (for now at least). + * - Empty segments within the string (e.g. if there are two consecutive + * separators) are not allowed. + * + * TODO(b/37244157): we should make this more strict. Right now, it allows + * non-identifier path components, even if they aren't escaped. + */ static fromServerFormat(t) { + const e = []; + let r = "", n = 0; + const __PRIVATE_addCurrentSegment = () => { + if (0 === r.length) throw new FirestoreError(y, `Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`); + e.push(r), r = ""; + }; + let i = !1; + for (;n < t.length; ) { + const e = t[n]; + if ("\\" === e) { + if (n + 1 === t.length) throw new FirestoreError(y, "Path has trailing escape character: " + t); + const e = t[n + 1]; + if ("\\" !== e && "." !== e && "`" !== e) throw new FirestoreError(y, "Path has invalid escape sequence: " + t); + r += e, n += 2; + } else "`" === e ? (i = !i, n++) : "." !== e || i ? (r += e, n++) : (__PRIVATE_addCurrentSegment(), + n++); + } + if (__PRIVATE_addCurrentSegment(), i) throw new FirestoreError(y, "Unterminated ` in path: " + t); + return new FieldPath$1(e); + } + static emptyPath() { + return new FieldPath$1([]); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @internal + */ class DocumentKey { + constructor(t) { + this.path = t; + } + static fromPath(t) { + return new DocumentKey(ResourcePath.fromString(t)); + } + static fromName(t) { + return new DocumentKey(ResourcePath.fromString(t).popFirst(5)); + } + static empty() { + return new DocumentKey(ResourcePath.emptyPath()); + } + get collectionGroup() { + return this.path.popLast().lastSegment(); + } + /** Returns true if the document is in the specified collectionId. */ hasCollectionId(t) { + return this.path.length >= 2 && this.path.get(this.path.length - 2) === t; + } + /** Returns the collection group (i.e. the name of the parent collection) for this key. */ getCollectionGroup() { + return this.path.get(this.path.length - 2); + } + /** Returns the fully qualified path to the parent collection. */ getCollectionPath() { + return this.path.popLast(); + } + isEqual(t) { + return null !== t && 0 === ResourcePath.comparator(this.path, t.path); + } + toString() { + return this.path.toString(); + } + static comparator(t, e) { + return ResourcePath.comparator(t.path, e.path); + } + static isDocumentKey(t) { + return t.length % 2 == 0; + } + /** + * Creates and returns a new document key with the given segments. + * + * @param segments - The segments of the path to the document + * @returns A new instance of DocumentKey + */ static fromSegments(t) { + return new DocumentKey(new ResourcePath(t.slice())); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_validateNonEmptyArgument(t, e, r) { + if (!r) throw new FirestoreError(y, `Function ${t}() cannot be called with an empty ${e}.`); +} + +/** + * Validates that two boolean options are not set at the same time. + * @internal + */ +/** + * Validates that `path` refers to a document (indicated by the fact it contains + * an even numbers of segments). + */ +function __PRIVATE_validateDocumentPath(t) { + if (!DocumentKey.isDocumentKey(t)) throw new FirestoreError(y, `Invalid document reference. Document references must have an even number of segments, but ${t} has ${t.length}.`); +} + +/** + * Validates that `path` refers to a collection (indicated by the fact it + * contains an odd numbers of segments). + */ function __PRIVATE_validateCollectionPath(t) { + if (DocumentKey.isDocumentKey(t)) throw new FirestoreError(y, `Invalid collection reference. Collection references must have an odd number of segments, but ${t} has ${t.length}.`); +} + +/** + * Returns true if it's a non-null object without a custom prototype + * (i.e. excludes Array, Date, etc.). + */ function __PRIVATE_isPlainObject(t) { + return "object" == typeof t && null !== t && (Object.getPrototypeOf(t) === Object.prototype || null === Object.getPrototypeOf(t)); +} + +/** Returns a string describing the type / value of the provided input. */ function __PRIVATE_valueDescription(t) { + if (void 0 === t) return "undefined"; + if (null === t) return "null"; + if ("string" == typeof t) return t.length > 20 && (t = `${t.substring(0, 20)}...`), + JSON.stringify(t); + if ("number" == typeof t || "boolean" == typeof t) return "" + t; + if ("object" == typeof t) { + if (t instanceof Array) return "an array"; + { + const e = + /** try to get the constructor name for an object. */ + function __PRIVATE_tryGetCustomObjectType(t) { + if (t.constructor) return t.constructor.name; + return null; + } + /** + * Casts `obj` to `T`, optionally unwrapping Compat types to expose the + * underlying instance. Throws if `obj` is not an instance of `T`. + * + * This cast is used in the Lite and Full SDK to verify instance types for + * arguments passed to the public API. + * @internal + */ (t); + return e ? `a custom ${e} object` : "an object"; + } + } + return "function" == typeof t ? "a function" : fail(12329, { + type: typeof t + }); +} + +function __PRIVATE_cast(t, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +e) { + if ("_delegate" in t && ( + // Unwrap Compat types + // eslint-disable-next-line @typescript-eslint/no-explicit-any + t = t._delegate), !(t instanceof e)) { + if (e.name === t.constructor.name) throw new FirestoreError(y, "Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?"); + { + const r = __PRIVATE_valueDescription(t); + throw new FirestoreError(y, `Expected type '${e.name}', but it was: ${r}`); + } + } + return t; +} + +function __PRIVATE_validatePositiveNumber(t, e) { + if (e <= 0) throw new FirestoreError(y, `Function ${t}() requires a positive number, but it was: ${e}.`); +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Compares two `ExperimentalLongPollingOptions` objects for equality. + */ +/** + * Creates and returns a new `ExperimentalLongPollingOptions` with the same + * option values as the given instance. + */ +function __PRIVATE_cloneLongPollingOptions(t) { + const e = {}; + return void 0 !== t.timeoutSeconds && (e.timeoutSeconds = t.timeoutSeconds), e; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The value returned from the most recent invocation of + * `generateUniqueDebugId()`, or null if it has never been invoked. + */ let U = null; + +/** + * Generates and returns an initial value for `lastUniqueDebugId`. + * + * The returned value is randomly selected from a range of integers that are + * represented as 8 hexadecimal digits. This means that (within reason) any + * numbers generated by incrementing the returned number by 1 will also be + * represented by 8 hexadecimal digits. This leads to all "IDs" having the same + * length when converted to a hexadecimal string, making reading logs containing + * these IDs easier to follow. And since the return value is randomly selected + * it will help to differentiate between logs from different executions. + */ +/** + * Generates and returns a unique ID as a hexadecimal string. + * + * The returned ID is intended to be used in debug logging messages to help + * correlate log messages that may be spatially separated in the logs, but + * logically related. For example, a network connection could include the same + * "debug ID" string in all of its log messages to help trace a specific + * connection over time. + * + * @return the 10-character generated ID (e.g. "0xa1b2c3d4"). + */ +function __PRIVATE_generateUniqueDebugId() { + return null === U ? U = function __PRIVATE_generateInitialUniqueDebugId() { + return 268435456 + Math.round(2147483648 * Math.random()); + }() : U++, "0x" + U.toString(16); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns whether a variable is either undefined or null. + */ function __PRIVATE_isNullOrUndefined(t) { + return null == t; +} + +/** Returns whether the value represents -0. */ function __PRIVATE_isNegativeZero(t) { + // Detect if the value is -0.0. Based on polyfill from + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is + return 0 === t && 1 / t == -1 / 0; +} + +/** + * Returns whether a value is an integer and in the safe integer range + * @param value - The value to test for being an integer and in the safe range + */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const j = "RestConnection", z = { + BatchGetDocuments: "batchGet", + Commit: "commit", + RunQuery: "runQuery", + RunAggregationQuery: "runAggregationQuery" +}; + +/** + * Maps RPC names to the corresponding REST endpoint name. + * + * We use array notation to avoid mangling. + */ +/** + * Base class for all Rest-based connections to the backend (WebChannel and + * HTTP). + */ +class __PRIVATE_RestConnection { + get P() { + // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine + // where to run the query, and expect the `request` to NOT specify the "path". + return !1; + } + constructor(t) { + this.databaseInfo = t, this.databaseId = t.databaseId; + const e = t.ssl ? "https" : "http", r = encodeURIComponent(this.databaseId.projectId), n = encodeURIComponent(this.databaseId.database); + this.A = e + "://" + t.host, this.R = `projects/${r}/databases/${n}`, this.V = this.databaseId.database === Q ? `project_id=${r}` : `project_id=${r}&database_id=${n}`; + } + I(t, e, r, n, i) { + const s = __PRIVATE_generateUniqueDebugId(), o = this.p(t, e.toUriEncodedString()); + __PRIVATE_logDebug(j, `Sending RPC '${t}' ${s}:`, o, r); + const a = { + "google-cloud-resource-prefix": this.R, + "x-goog-request-params": this.V + }; + this.F(a, n, i); + const {host: u} = new URL(o), _ = isCloudWorkstation(u); + return this.v(t, o, a, r, _).then((e => (__PRIVATE_logDebug(j, `Received RPC '${t}' ${s}: `, e), + e)), (e => { + throw __PRIVATE_logWarn(j, `RPC '${t}' ${s} failed with error: `, e, "url: ", o, "request:", r), + e; + })); + } + D(t, e, r, n, i, s) { + // The REST API automatically aggregates all of the streamed results, so we + // can just use the normal invoke() method. + return this.I(t, e, r, n, i); + } + /** + * Modifies the headers for a request, adding any authorization token if + * present and any additional headers for the request. + */ F(t, e, r) { + t["X-Goog-Api-Client"] = + // SDK_VERSION is updated to different value at runtime depending on the entry point, + // so we need to get its value when we need it in a function. + function __PRIVATE_getGoogApiClientValue() { + return "gl-js/ fire/" + A; + }(), + // Content-Type: text/plain will avoid preflight requests which might + // mess with CORS and redirects by proxies. If we add custom headers + // we will need to change this code to potentially use the $httpOverwrite + // parameter supported by ESF to avoid triggering preflight requests. + t["Content-Type"] = "text/plain", this.databaseInfo.appId && (t["X-Firebase-GMPID"] = this.databaseInfo.appId), + e && e.headers.forEach(((e, r) => t[r] = e)), r && r.headers.forEach(((e, r) => t[r] = e)); + } + p(t, e) { + const r = z[t]; + return `${this.A}/v1/${e}:${r}`; + } + /** + * Closes and cleans up any resources associated with the connection. This + * implementation is a no-op because there are no resources associated + * with the RestConnection that need to be cleaned up. + */ terminate() { + // No-op + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Error Codes describing the different ways GRPC can fail. These are copied + * directly from GRPC's sources here: + * + * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h + * + * Important! The names of these identifiers matter because the string forms + * are used for reverse lookups from the webchannel stream. Do NOT change the + * names of these identifiers or change this into a const enum. + */ var W, K; + +/** + * Converts an HTTP Status Code to the equivalent error code. + * + * @param status - An HTTP Status Code, like 200, 404, 503, etc. + * @returns The equivalent Code. Unknown status codes are mapped to + * Code.UNKNOWN. + */ +function __PRIVATE_mapCodeFromHttpStatus(t) { + if (void 0 === t) return __PRIVATE_logError("RPC_ERROR", "HTTP error has no status"), + p; + // The canonical error codes for Google APIs [1] specify mapping onto HTTP + // status codes but the mapping is not bijective. In each case of ambiguity + // this function chooses a primary error. + + // [1] + // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto + switch (t) { + case 200: + // OK + return V; + + case 400: + // Bad Request + return S; + + // Other possibilities based on the forward mapping + // return Code.INVALID_ARGUMENT; + // return Code.OUT_OF_RANGE; + case 401: + // Unauthorized + return D; + + case 403: + // Forbidden + return v; + + case 404: + // Not Found + return w; + + case 409: + // Conflict + return C; + + // Other possibilities: + // return Code.ALREADY_EXISTS; + case 416: + // Range Not Satisfiable + return N; + + case 429: + // Too Many Requests + return b; + + case 499: + // Client Closed Request + return I; + + case 500: + // Internal Server Error + return p; + + // Other possibilities: + // return Code.INTERNAL; + // return Code.DATA_LOSS; + case 501: + // Unimplemented + return O; + + case 503: + // Service Unavailable + return B; + + case 504: + // Gateway Timeout + return g; + + default: + return t >= 200 && t < 300 ? V : t >= 400 && t < 500 ? S : t >= 500 && t < 600 ? q : p; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A Rest-based connection that relies on the native HTTP stack + * (e.g. `fetch` or a polyfill). + */ (K = W || (W = {}))[K.OK = 0] = "OK", K[K.CANCELLED = 1] = "CANCELLED", K[K.UNKNOWN = 2] = "UNKNOWN", +K[K.INVALID_ARGUMENT = 3] = "INVALID_ARGUMENT", K[K.DEADLINE_EXCEEDED = 4] = "DEADLINE_EXCEEDED", +K[K.NOT_FOUND = 5] = "NOT_FOUND", K[K.ALREADY_EXISTS = 6] = "ALREADY_EXISTS", K[K.PERMISSION_DENIED = 7] = "PERMISSION_DENIED", +K[K.UNAUTHENTICATED = 16] = "UNAUTHENTICATED", K[K.RESOURCE_EXHAUSTED = 8] = "RESOURCE_EXHAUSTED", +K[K.FAILED_PRECONDITION = 9] = "FAILED_PRECONDITION", K[K.ABORTED = 10] = "ABORTED", +K[K.OUT_OF_RANGE = 11] = "OUT_OF_RANGE", K[K.UNIMPLEMENTED = 12] = "UNIMPLEMENTED", +K[K.INTERNAL = 13] = "INTERNAL", K[K.UNAVAILABLE = 14] = "UNAVAILABLE", K[K.DATA_LOSS = 15] = "DATA_LOSS"; + +class __PRIVATE_FetchConnection extends __PRIVATE_RestConnection { + S(t, e) { + throw new Error("Not supported by FetchConnection"); + } + async v(t, e, r, n, i) { + const s = JSON.stringify(n); + let o; + try { + const t = { + method: "POST", + headers: r, + body: s + }; + i && (t.credentials = "include"), o = await fetch(e, t); + } catch (t) { + const e = t; + throw new FirestoreError(__PRIVATE_mapCodeFromHttpStatus(e.status), "Request failed with error: " + e.statusText); + } + if (!o.ok) { + let t = await o.json(); + Array.isArray(t) && (t = t[0]); + const e = t?.error?.message; + throw new FirestoreError(__PRIVATE_mapCodeFromHttpStatus(o.status), `Request failed with error: ${e ?? o.statusText}`); + } + return o.json(); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Initializes the HTTP connection for the REST API. */ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Concrete implementation of the Aggregate type. + */ +class __PRIVATE_AggregateImpl { + constructor(t, e, r) { + this.alias = t, this.aggregateType = e, this.fieldPath = r; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_objectSize(t) { + let e = 0; + for (const r in t) Object.prototype.hasOwnProperty.call(t, r) && e++; + return e; +} + +function forEach(t, e) { + for (const r in t) Object.prototype.hasOwnProperty.call(t, r) && e(r, t[r]); +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An error encountered while decoding base64 string. + */ +class __PRIVATE_Base64DecodeError extends Error { + constructor() { + super(...arguments), this.name = "Base64DecodeError"; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Converts a Base64 encoded string to a binary string. */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Immutable class that represents a "proto" byte string. + * + * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when + * sent on the wire. This class abstracts away this differentiation by holding + * the proto byte string in a common class that must be converted into a string + * before being sent as a proto. + * @internal + */ +class ByteString { + constructor(t) { + this.binaryString = t; + } + static fromBase64String(t) { + const e = function __PRIVATE_decodeBase64(t) { + try { + return atob(t); + } catch (t) { + // Check that `DOMException` is defined before using it to avoid + // "ReferenceError: Property 'DOMException' doesn't exist" in react-native. + // (https://github.com/firebase/firebase-js-sdk/issues/7115) + throw "undefined" != typeof DOMException && t instanceof DOMException ? new __PRIVATE_Base64DecodeError("Invalid base64 string: " + t) : t; + } + } + /** Converts a binary string to a Base64 encoded string. */ (t); + return new ByteString(e); + } + static fromUint8Array(t) { + // TODO(indexing); Remove the copy of the byte string here as this method + // is frequently called during indexing. + const e = + /** + * Helper function to convert an Uint8array to a binary string. + */ + function __PRIVATE_binaryStringFromUint8Array(t) { + let e = ""; + for (let r = 0; r < t.length; ++r) e += String.fromCharCode(t[r]); + return e; + } + /** + * Helper function to convert a binary string to an Uint8Array. + */ (t); + return new ByteString(e); + } + [Symbol.iterator]() { + let t = 0; + return { + next: () => t < this.binaryString.length ? { + value: this.binaryString.charCodeAt(t++), + done: !1 + } : { + value: void 0, + done: !0 + } + }; + } + toBase64() { + return function __PRIVATE_encodeBase64(t) { + return btoa(t); + }(this.binaryString); + } + toUint8Array() { + return function __PRIVATE_uint8ArrayFromBinaryString(t) { + const e = new Uint8Array(t.length); + for (let r = 0; r < t.length; r++) e[r] = t.charCodeAt(r); + return e; + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + // A RegExp matching ISO 8601 UTC timestamps with optional fraction. + (this.binaryString); + } + approximateByteSize() { + return 2 * this.binaryString.length; + } + compareTo(t) { + return __PRIVATE_primitiveComparator(this.binaryString, t.binaryString); + } + isEqual(t) { + return this.binaryString === t.binaryString; + } +} + +ByteString.EMPTY_BYTE_STRING = new ByteString(""); + +const G = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/); + +/** + * Converts the possible Proto values for a timestamp value into a "seconds and + * nanos" representation. + */ function __PRIVATE_normalizeTimestamp(t) { + // The json interface (for the browser) will return an iso timestamp string, + // while the proto js library (for node) will return a + // google.protobuf.Timestamp instance. + if (__PRIVATE_hardAssert(!!t, 39018), "string" == typeof t) { + // The date string can have higher precision (nanos) than the Date class + // (millis), so we do some custom parsing here. + // Parse the nanos right out of the string. + let e = 0; + const r = G.exec(t); + if (__PRIVATE_hardAssert(!!r, 46558, { + timestamp: t + }), r[1]) { + // Pad the fraction out to 9 digits (nanos). + let t = r[1]; + t = (t + "000000000").substr(0, 9), e = Number(t); + } + // Parse the date to get the seconds. + const n = new Date(t); + return { + seconds: Math.floor(n.getTime() / 1e3), + nanos: e + }; + } + return { + seconds: __PRIVATE_normalizeNumber(t.seconds), + nanos: __PRIVATE_normalizeNumber(t.nanos) + }; +} + +/** + * Converts the possible Proto types for numbers into a JavaScript number. + * Returns 0 if the value is not numeric. + */ function __PRIVATE_normalizeNumber(t) { + // TODO(bjornick): Handle int64 greater than 53 bits. + return "number" == typeof t ? t : "string" == typeof t ? Number(t) : 0; +} + +/** Converts the possible Proto types for Blobs into a ByteString. */ function __PRIVATE_normalizeByteString(t) { + return "string" == typeof t ? ByteString.fromBase64String(t) : ByteString.fromUint8Array(t); +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Helper function to define a JSON schema {@link Property}. + * @private + * @internal + */ function property(t, e) { + const r = { + typeString: t + }; + return e && (r.value = e), r; +} + +/** + * Validates the JSON object based on the provided schema, and narrows the type to the provided + * JSON schema. + * @private + * @internal + * + * @param json A JSON object to validate. + * @param scheme a {@link JsonSchema} that defines the properties to validate. + * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise. + */ function __PRIVATE_validateJSON(t, e) { + if (!__PRIVATE_isPlainObject(t)) throw new FirestoreError(y, "JSON must be an object"); + let r; + for (const n in e) if (e[n]) { + const i = e[n].typeString, s = "value" in e[n] ? { + value: e[n].value + } : void 0; + if (!(n in t)) { + r = `JSON missing required field: '${n}'`; + break; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const o = t[n]; + if (i && typeof o !== i) { + r = `JSON field '${n}' must be a ${i}.`; + break; + } + if (void 0 !== s && o !== s.value) { + r = `Expected '${n}' field to equal '${s.value}'`; + break; + } + } + if (r) throw new FirestoreError(y, r); + return !0; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z). +const J = -62135596800, H = 1e6; + +// Number of nanoseconds in a millisecond. +/** + * A `Timestamp` represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. + * + * It is encoded using the Proleptic Gregorian Calendar which extends the + * Gregorian calendar backwards to year one. It is encoded assuming all minutes + * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59.999999999Z. + * + * For examples and further specifications, refer to the + * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. + */ +class Timestamp { + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns a new timestamp representing the current date. + */ + static now() { + return Timestamp.fromMillis(Date.now()); + } + /** + * Creates a new timestamp from the given date. + * + * @param date - The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the given + * date. + */ static fromDate(t) { + return Timestamp.fromMillis(t.getTime()); + } + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds - Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the given + * number of milliseconds. + */ static fromMillis(t) { + const e = Math.floor(t / 1e3), r = Math.floor((t - 1e3 * e) * H); + return new Timestamp(e, r); + } + /** + * Creates a new timestamp. + * + * @param seconds - The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds - The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + t, + /** + * The fractions of a second at nanosecond resolution.* + */ + e) { + if (this.seconds = t, this.nanoseconds = e, e < 0) throw new FirestoreError(y, "Timestamp nanoseconds out of range: " + e); + if (e >= 1e9) throw new FirestoreError(y, "Timestamp nanoseconds out of range: " + e); + if (t < J) throw new FirestoreError(y, "Timestamp seconds out of range: " + t); + // This will break in the year 10,000. + if (t >= 253402300800) throw new FirestoreError(y, "Timestamp seconds out of range: " + t); + } + /** + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ toDate() { + return new Date(this.toMillis()); + } + /** + * Converts a `Timestamp` to a numeric timestamp (in milliseconds since + * epoch). This operation causes a loss of precision. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ toMillis() { + return 1e3 * this.seconds + this.nanoseconds / H; + } + _compareTo(t) { + return this.seconds === t.seconds ? __PRIVATE_primitiveComparator(this.nanoseconds, t.nanoseconds) : __PRIVATE_primitiveComparator(this.seconds, t.seconds); + } + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other - The `Timestamp` to compare against. + * @returns true if this `Timestamp` is equal to the provided one. + */ isEqual(t) { + return t.seconds === this.seconds && t.nanoseconds === this.nanoseconds; + } + /** Returns a textual representation of this `Timestamp`. */ toString() { + return "Timestamp(seconds=" + this.seconds + ", nanoseconds=" + this.nanoseconds + ")"; + } + /** + * Returns a JSON-serializable representation of this `Timestamp`. + */ toJSON() { + return { + type: Timestamp._jsonSchemaVersion, + seconds: this.seconds, + nanoseconds: this.nanoseconds + }; + } + /** + * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}. + */ static fromJSON(t) { + if (__PRIVATE_validateJSON(t, Timestamp._jsonSchema)) return new Timestamp(t.seconds, t.nanoseconds); + } + /** + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. + */ valueOf() { + // This method returns a string of the form . where + // is translated to have a non-negative value and both + // and are left-padded with zeroes to be a consistent length. + // Strings with this format then have a lexicographical ordering that matches + // the expected ordering. The translation is done to avoid having + // a leading negative sign (i.e. a leading '-' character) in its string + // representation, which would affect its lexicographical ordering. + const t = this.seconds - J; + // Note: Up to 12 decimal digits are required to represent all valid + // 'seconds' values. + return String(t).padStart(12, "0") + "." + String(this.nanoseconds).padStart(9, "0"); + } +} + +Timestamp._jsonSchemaVersion = "firestore/timestamp/1.0", Timestamp._jsonSchema = { + type: property("string", Timestamp._jsonSchemaVersion), + seconds: property("number"), + nanoseconds: property("number") +}; + +function __PRIVATE_isServerTimestamp(t) { + const e = (t?.mapValue?.fields || {}).__type__?.stringValue; + return "server_timestamp" === e; +} + +/** + * Returns the value of the field before this ServerTimestamp was set. + * + * Preserving the previous values allows the user to display the last resoled + * value until the backend responds with the timestamp. + */ function __PRIVATE_getPreviousValue(t) { + const e = t.mapValue.fields.__previous_value__; + return __PRIVATE_isServerTimestamp(e) ? __PRIVATE_getPreviousValue(e) : e; +} + +/** + * Returns the local time at which this timestamp was first set. + */ function __PRIVATE_getLocalWriteTime(t) { + const e = __PRIVATE_normalizeTimestamp(t.mapValue.fields.__local_write_time__.timestampValue); + return new Timestamp(e.seconds, e.nanos); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const Y = "__type__", Z = "__max__", X = { + fields: { + __type__: { + stringValue: Z + } + } +}, tt = "__vector__", et = "value"; + +/** Extracts the backend's type order for the provided value. */ +function __PRIVATE_typeOrder(t) { + return "nullValue" in t ? 0 /* TypeOrder.NullValue */ : "booleanValue" in t ? 1 /* TypeOrder.BooleanValue */ : "integerValue" in t || "doubleValue" in t ? 2 /* TypeOrder.NumberValue */ : "timestampValue" in t ? 3 /* TypeOrder.TimestampValue */ : "stringValue" in t ? 5 /* TypeOrder.StringValue */ : "bytesValue" in t ? 6 /* TypeOrder.BlobValue */ : "referenceValue" in t ? 7 /* TypeOrder.RefValue */ : "geoPointValue" in t ? 8 /* TypeOrder.GeoPointValue */ : "arrayValue" in t ? 9 /* TypeOrder.ArrayValue */ : "mapValue" in t ? __PRIVATE_isServerTimestamp(t) ? 4 /* TypeOrder.ServerTimestampValue */ : + /** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ + function __PRIVATE_isMaxValue(t) { + return (((t.mapValue || {}).fields || {}).__type__ || {}).stringValue === Z; + } + /** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Represents a bound of a query. + * + * The bound is specified with the given components representing a position and + * whether it's just before or just after the position (relative to whatever the + * query order is). + * + * The position represents a logical index position for a query. It's a prefix + * of values for the (potentially implicit) order by clauses of a query. + * + * Bound provides a function to determine whether a document comes before or + * after a bound. This is influenced by whether the position is just before or + * just after the provided values. + */ (t) ? 9007199254740991 /* TypeOrder.MaxValue */ : + /** Returns true if `value` is a VetorValue. */ + function __PRIVATE_isVectorValue(t) { + const e = (t?.mapValue?.fields || {})[Y]?.stringValue; + return e === tt; + } + /** Creates a deep copy of `source`. */ (t) ? 10 /* TypeOrder.VectorValue */ : 11 /* TypeOrder.ObjectValue */ : fail(28295, { + value: t + }); +} + +/** Tests `left` and `right` for equality based on the backend semantics. */ function __PRIVATE_valueEquals(t, e) { + if (t === e) return !0; + const r = __PRIVATE_typeOrder(t); + if (r !== __PRIVATE_typeOrder(e)) return !1; + switch (r) { + case 0 /* TypeOrder.NullValue */ : + case 9007199254740991 /* TypeOrder.MaxValue */ : + return !0; + + case 1 /* TypeOrder.BooleanValue */ : + return t.booleanValue === e.booleanValue; + + case 4 /* TypeOrder.ServerTimestampValue */ : + return __PRIVATE_getLocalWriteTime(t).isEqual(__PRIVATE_getLocalWriteTime(e)); + + case 3 /* TypeOrder.TimestampValue */ : + return function __PRIVATE_timestampEquals(t, e) { + if ("string" == typeof t.timestampValue && "string" == typeof e.timestampValue && t.timestampValue.length === e.timestampValue.length) + // Use string equality for ISO 8601 timestamps + return t.timestampValue === e.timestampValue; + const r = __PRIVATE_normalizeTimestamp(t.timestampValue), n = __PRIVATE_normalizeTimestamp(e.timestampValue); + return r.seconds === n.seconds && r.nanos === n.nanos; + }(t, e); + + case 5 /* TypeOrder.StringValue */ : + return t.stringValue === e.stringValue; + + case 6 /* TypeOrder.BlobValue */ : + return function __PRIVATE_blobEquals(t, e) { + return __PRIVATE_normalizeByteString(t.bytesValue).isEqual(__PRIVATE_normalizeByteString(e.bytesValue)); + }(t, e); + + case 7 /* TypeOrder.RefValue */ : + return t.referenceValue === e.referenceValue; + + case 8 /* TypeOrder.GeoPointValue */ : + return function __PRIVATE_geoPointEquals(t, e) { + return __PRIVATE_normalizeNumber(t.geoPointValue.latitude) === __PRIVATE_normalizeNumber(e.geoPointValue.latitude) && __PRIVATE_normalizeNumber(t.geoPointValue.longitude) === __PRIVATE_normalizeNumber(e.geoPointValue.longitude); + }(t, e); + + case 2 /* TypeOrder.NumberValue */ : + return function __PRIVATE_numberEquals(t, e) { + if ("integerValue" in t && "integerValue" in e) return __PRIVATE_normalizeNumber(t.integerValue) === __PRIVATE_normalizeNumber(e.integerValue); + if ("doubleValue" in t && "doubleValue" in e) { + const r = __PRIVATE_normalizeNumber(t.doubleValue), n = __PRIVATE_normalizeNumber(e.doubleValue); + return r === n ? __PRIVATE_isNegativeZero(r) === __PRIVATE_isNegativeZero(n) : isNaN(r) && isNaN(n); + } + return !1; + }(t, e); + + case 9 /* TypeOrder.ArrayValue */ : + return __PRIVATE_arrayEquals(t.arrayValue.values || [], e.arrayValue.values || [], __PRIVATE_valueEquals); + + case 10 /* TypeOrder.VectorValue */ : + case 11 /* TypeOrder.ObjectValue */ : + return function __PRIVATE_objectEquals(t, e) { + const r = t.mapValue.fields || {}, n = e.mapValue.fields || {}; + if (__PRIVATE_objectSize(r) !== __PRIVATE_objectSize(n)) return !1; + for (const t in r) if (r.hasOwnProperty(t) && (void 0 === n[t] || !__PRIVATE_valueEquals(r[t], n[t]))) return !1; + return !0; + } + /** Returns true if the ArrayValue contains the specified element. */ (t, e); + + default: + return fail(52216, { + left: t + }); + } +} + +function __PRIVATE_arrayValueContains(t, e) { + return void 0 !== (t.values || []).find((t => __PRIVATE_valueEquals(t, e))); +} + +function __PRIVATE_valueCompare(t, e) { + if (t === e) return 0; + const r = __PRIVATE_typeOrder(t), n = __PRIVATE_typeOrder(e); + if (r !== n) return __PRIVATE_primitiveComparator(r, n); + switch (r) { + case 0 /* TypeOrder.NullValue */ : + case 9007199254740991 /* TypeOrder.MaxValue */ : + return 0; + + case 1 /* TypeOrder.BooleanValue */ : + return __PRIVATE_primitiveComparator(t.booleanValue, e.booleanValue); + + case 2 /* TypeOrder.NumberValue */ : + return function __PRIVATE_compareNumbers(t, e) { + const r = __PRIVATE_normalizeNumber(t.integerValue || t.doubleValue), n = __PRIVATE_normalizeNumber(e.integerValue || e.doubleValue); + return r < n ? -1 : r > n ? 1 : r === n ? 0 : + // one or both are NaN. + isNaN(r) ? isNaN(n) ? 0 : -1 : 1; + }(t, e); + + case 3 /* TypeOrder.TimestampValue */ : + return __PRIVATE_compareTimestamps(t.timestampValue, e.timestampValue); + + case 4 /* TypeOrder.ServerTimestampValue */ : + return __PRIVATE_compareTimestamps(__PRIVATE_getLocalWriteTime(t), __PRIVATE_getLocalWriteTime(e)); + + case 5 /* TypeOrder.StringValue */ : + return __PRIVATE_compareUtf8Strings(t.stringValue, e.stringValue); + + case 6 /* TypeOrder.BlobValue */ : + return function __PRIVATE_compareBlobs(t, e) { + const r = __PRIVATE_normalizeByteString(t), n = __PRIVATE_normalizeByteString(e); + return r.compareTo(n); + }(t.bytesValue, e.bytesValue); + + case 7 /* TypeOrder.RefValue */ : + return function __PRIVATE_compareReferences(t, e) { + const r = t.split("/"), n = e.split("/"); + for (let t = 0; t < r.length && t < n.length; t++) { + const e = __PRIVATE_primitiveComparator(r[t], n[t]); + if (0 !== e) return e; + } + return __PRIVATE_primitiveComparator(r.length, n.length); + }(t.referenceValue, e.referenceValue); + + case 8 /* TypeOrder.GeoPointValue */ : + return function __PRIVATE_compareGeoPoints(t, e) { + const r = __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(t.latitude), __PRIVATE_normalizeNumber(e.latitude)); + if (0 !== r) return r; + return __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(t.longitude), __PRIVATE_normalizeNumber(e.longitude)); + }(t.geoPointValue, e.geoPointValue); + + case 9 /* TypeOrder.ArrayValue */ : + return __PRIVATE_compareArrays(t.arrayValue, e.arrayValue); + + case 10 /* TypeOrder.VectorValue */ : + return function __PRIVATE_compareVectors(t, e) { + const r = t.fields || {}, n = e.fields || {}, i = r[et]?.arrayValue, s = n[et]?.arrayValue, o = __PRIVATE_primitiveComparator(i?.values?.length || 0, s?.values?.length || 0); + if (0 !== o) return o; + return __PRIVATE_compareArrays(i, s); + }(t.mapValue, e.mapValue); + + case 11 /* TypeOrder.ObjectValue */ : + return function __PRIVATE_compareMaps(t, e) { + if (t === X && e === X) return 0; + if (t === X) return 1; + if (e === X) return -1; + const r = t.fields || {}, n = Object.keys(r), i = e.fields || {}, s = Object.keys(i); + // Even though MapValues are likely sorted correctly based on their insertion + // order (e.g. when received from the backend), local modifications can bring + // elements out of order. We need to re-sort the elements to ensure that + // canonical IDs are independent of insertion order. + n.sort(), s.sort(); + for (let t = 0; t < n.length && t < s.length; ++t) { + const e = __PRIVATE_compareUtf8Strings(n[t], s[t]); + if (0 !== e) return e; + const o = __PRIVATE_valueCompare(r[n[t]], i[s[t]]); + if (0 !== o) return o; + } + return __PRIVATE_primitiveComparator(n.length, s.length); + } + /** Returns a reference value for the provided database and key. */ (t.mapValue, e.mapValue); + + default: + throw fail(23264, { + C: r + }); + } +} + +function __PRIVATE_compareTimestamps(t, e) { + if ("string" == typeof t && "string" == typeof e && t.length === e.length) return __PRIVATE_primitiveComparator(t, e); + const r = __PRIVATE_normalizeTimestamp(t), n = __PRIVATE_normalizeTimestamp(e), i = __PRIVATE_primitiveComparator(r.seconds, n.seconds); + return 0 !== i ? i : __PRIVATE_primitiveComparator(r.nanos, n.nanos); +} + +function __PRIVATE_compareArrays(t, e) { + const r = t.values || [], n = e.values || []; + for (let t = 0; t < r.length && t < n.length; ++t) { + const e = __PRIVATE_valueCompare(r[t], n[t]); + if (e) return e; + } + return __PRIVATE_primitiveComparator(r.length, n.length); +} + +function __PRIVATE_refValue(t, e) { + return { + referenceValue: `projects/${t.projectId}/databases/${t.database}/documents/${e.path.canonicalString()}` + }; +} + +/** Returns true if `value` is an ArrayValue. */ function isArray(t) { + return !!t && "arrayValue" in t; +} + +/** Returns true if `value` is a NullValue. */ function __PRIVATE_isNullValue(t) { + return !!t && "nullValue" in t; +} + +/** Returns true if `value` is NaN. */ function __PRIVATE_isNanValue(t) { + return !!t && "doubleValue" in t && isNaN(Number(t.doubleValue)); +} + +/** Returns true if `value` is a MapValue. */ function __PRIVATE_isMapValue(t) { + return !!t && "mapValue" in t; +} + +function __PRIVATE_deepClone(t) { + if (t.geoPointValue) return { + geoPointValue: { + ...t.geoPointValue + } + }; + if (t.timestampValue && "object" == typeof t.timestampValue) return { + timestampValue: { + ...t.timestampValue + } + }; + if (t.mapValue) { + const e = { + mapValue: { + fields: {} + } + }; + return forEach(t.mapValue.fields, ((t, r) => e.mapValue.fields[t] = __PRIVATE_deepClone(r))), + e; + } + if (t.arrayValue) { + const e = { + arrayValue: { + values: [] + } + }; + for (let r = 0; r < (t.arrayValue.values || []).length; ++r) e.arrayValue.values[r] = __PRIVATE_deepClone(t.arrayValue.values[r]); + return e; + } + return { + ...t + }; +} + +class Bound { + constructor(t, e) { + this.position = t, this.inclusive = e; + } +} + +function __PRIVATE_boundEquals(t, e) { + if (null === t) return null === e; + if (null === e) return !1; + if (t.inclusive !== e.inclusive || t.position.length !== e.position.length) return !1; + for (let r = 0; r < t.position.length; r++) { + if (!__PRIVATE_valueEquals(t.position[r], e.position[r])) return !1; + } + return !0; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class Filter {} + +class FieldFilter extends Filter { + constructor(t, e, r) { + super(), this.field = t, this.op = e, this.value = r; + } + /** + * Creates a filter based on the provided arguments. + */ static create(t, e, r) { + return t.isKeyField() ? "in" /* Operator.IN */ === e || "not-in" /* Operator.NOT_IN */ === e ? this.createKeyFieldInFilter(t, e, r) : new __PRIVATE_KeyFieldFilter(t, e, r) : "array-contains" /* Operator.ARRAY_CONTAINS */ === e ? new __PRIVATE_ArrayContainsFilter(t, r) : "in" /* Operator.IN */ === e ? new __PRIVATE_InFilter(t, r) : "not-in" /* Operator.NOT_IN */ === e ? new __PRIVATE_NotInFilter(t, r) : "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === e ? new __PRIVATE_ArrayContainsAnyFilter(t, r) : new FieldFilter(t, e, r); + } + static createKeyFieldInFilter(t, e, r) { + return "in" /* Operator.IN */ === e ? new __PRIVATE_KeyFieldInFilter(t, r) : new __PRIVATE_KeyFieldNotInFilter(t, r); + } + matches(t) { + const e = t.data.field(this.field); + // Types do not have to match in NOT_EQUAL filters. + return "!=" /* Operator.NOT_EQUAL */ === this.op ? null !== e && void 0 === e.nullValue && this.matchesComparison(__PRIVATE_valueCompare(e, this.value)) : null !== e && __PRIVATE_typeOrder(this.value) === __PRIVATE_typeOrder(e) && this.matchesComparison(__PRIVATE_valueCompare(e, this.value)); + // Only compare types with matching backend order (such as double and int). + } + matchesComparison(t) { + switch (this.op) { + case "<" /* Operator.LESS_THAN */ : + return t < 0; + + case "<=" /* Operator.LESS_THAN_OR_EQUAL */ : + return t <= 0; + + case "==" /* Operator.EQUAL */ : + return 0 === t; + + case "!=" /* Operator.NOT_EQUAL */ : + return 0 !== t; + + case ">" /* Operator.GREATER_THAN */ : + return t > 0; + + case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ : + return t >= 0; + + default: + return fail(47266, { + operator: this.op + }); + } + } + isInequality() { + return [ "<" /* Operator.LESS_THAN */ , "<=" /* Operator.LESS_THAN_OR_EQUAL */ , ">" /* Operator.GREATER_THAN */ , ">=" /* Operator.GREATER_THAN_OR_EQUAL */ , "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ].indexOf(this.op) >= 0; + } + getFlattenedFilters() { + return [ this ]; + } + getFilters() { + return [ this ]; + } +} + +class CompositeFilter extends Filter { + constructor(t, e) { + super(), this.filters = t, this.op = e, this.N = null; + } + /** + * Creates a filter based on the provided arguments. + */ static create(t, e) { + return new CompositeFilter(t, e); + } + matches(t) { + return function __PRIVATE_compositeFilterIsConjunction(t) { + return "and" /* CompositeOperator.AND */ === t.op; + }(this) ? void 0 === this.filters.find((e => !e.matches(t))) : void 0 !== this.filters.find((e => e.matches(t))); + } + getFlattenedFilters() { + return null !== this.N || (this.N = this.filters.reduce(((t, e) => t.concat(e.getFlattenedFilters())), [])), + this.N; + } + // Returns a mutable copy of `this.filters` + getFilters() { + return Object.assign([], this.filters); + } +} + +function __PRIVATE_filterEquals(t, e) { + return t instanceof FieldFilter ? function __PRIVATE_fieldFilterEquals(t, e) { + return e instanceof FieldFilter && t.op === e.op && t.field.isEqual(e.field) && __PRIVATE_valueEquals(t.value, e.value); + }(t, e) : t instanceof CompositeFilter ? function __PRIVATE_compositeFilterEquals(t, e) { + if (e instanceof CompositeFilter && t.op === e.op && t.filters.length === e.filters.length) { + return t.filters.reduce(((t, r, n) => t && __PRIVATE_filterEquals(r, e.filters[n])), !0); + } + return !1; + } + /** Filter that matches on key fields (i.e. '__name__'). */ (t, e) : void fail(19439); +} + +class __PRIVATE_KeyFieldFilter extends FieldFilter { + constructor(t, e, r) { + super(t, e, r), this.key = DocumentKey.fromName(r.referenceValue); + } + matches(t) { + const e = DocumentKey.comparator(t.key, this.key); + return this.matchesComparison(e); + } +} + +/** Filter that matches on key fields within an array. */ class __PRIVATE_KeyFieldInFilter extends FieldFilter { + constructor(t, e) { + super(t, "in" /* Operator.IN */ , e), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue("in" /* Operator.IN */ , e); + } + matches(t) { + return this.keys.some((e => e.isEqual(t.key))); + } +} + +/** Filter that matches on key fields not present within an array. */ class __PRIVATE_KeyFieldNotInFilter extends FieldFilter { + constructor(t, e) { + super(t, "not-in" /* Operator.NOT_IN */ , e), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue("not-in" /* Operator.NOT_IN */ , e); + } + matches(t) { + return !this.keys.some((e => e.isEqual(t.key))); + } +} + +function __PRIVATE_extractDocumentKeysFromArrayValue(t, e) { + return (e.arrayValue?.values || []).map((t => DocumentKey.fromName(t.referenceValue))); +} + +/** A Filter that implements the array-contains operator. */ class __PRIVATE_ArrayContainsFilter extends FieldFilter { + constructor(t, e) { + super(t, "array-contains" /* Operator.ARRAY_CONTAINS */ , e); + } + matches(t) { + const e = t.data.field(this.field); + return isArray(e) && __PRIVATE_arrayValueContains(e.arrayValue, this.value); + } +} + +/** A Filter that implements the IN operator. */ class __PRIVATE_InFilter extends FieldFilter { + constructor(t, e) { + super(t, "in" /* Operator.IN */ , e); + } + matches(t) { + const e = t.data.field(this.field); + return null !== e && __PRIVATE_arrayValueContains(this.value.arrayValue, e); + } +} + +/** A Filter that implements the not-in operator. */ class __PRIVATE_NotInFilter extends FieldFilter { + constructor(t, e) { + super(t, "not-in" /* Operator.NOT_IN */ , e); + } + matches(t) { + if (__PRIVATE_arrayValueContains(this.value.arrayValue, { + nullValue: "NULL_VALUE" + })) return !1; + const e = t.data.field(this.field); + return null !== e && void 0 === e.nullValue && !__PRIVATE_arrayValueContains(this.value.arrayValue, e); + } +} + +/** A Filter that implements the array-contains-any operator. */ class __PRIVATE_ArrayContainsAnyFilter extends FieldFilter { + constructor(t, e) { + super(t, "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , e); + } + matches(t) { + const e = t.data.field(this.field); + return !(!isArray(e) || !e.arrayValue.values) && e.arrayValue.values.some((t => __PRIVATE_arrayValueContains(this.value.arrayValue, t))); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An ordering on a field, in some Direction. Direction defaults to ASCENDING. + */ class OrderBy { + constructor(t, e = "asc" /* Direction.ASCENDING */) { + this.field = t, this.dir = e; + } +} + +function __PRIVATE_orderByEquals(t, e) { + return t.dir === e.dir && t.field.isEqual(e.field); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A version of a document in Firestore. This corresponds to the version + * timestamp, such as update_time or read_time. + */ class SnapshotVersion { + static fromTimestamp(t) { + return new SnapshotVersion(t); + } + static min() { + return new SnapshotVersion(new Timestamp(0, 0)); + } + static max() { + return new SnapshotVersion(new Timestamp(253402300799, 999999999)); + } + constructor(t) { + this.timestamp = t; + } + compareTo(t) { + return this.timestamp._compareTo(t.timestamp); + } + isEqual(t) { + return this.timestamp.isEqual(t.timestamp); + } + /** Returns a number representation of the version for use in spec tests. */ toMicroseconds() { + // Convert to microseconds. + return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3; + } + toString() { + return "SnapshotVersion(" + this.timestamp.toString() + ")"; + } + toTimestamp() { + return this.timestamp; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// An immutable sorted map implementation, based on a Left-leaning Red-Black +// tree. +class SortedMap { + constructor(t, e) { + this.comparator = t, this.root = e || LLRBNode.EMPTY; + } + // Returns a copy of the map, with the specified key/value added or replaced. + insert(t, e) { + return new SortedMap(this.comparator, this.root.insert(t, e, this.comparator).copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns a copy of the map, with the specified key removed. + remove(t) { + return new SortedMap(this.comparator, this.root.remove(t, this.comparator).copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns the value of the node with the given key, or null. + get(t) { + let e = this.root; + for (;!e.isEmpty(); ) { + const r = this.comparator(t, e.key); + if (0 === r) return e.value; + r < 0 ? e = e.left : r > 0 && (e = e.right); + } + return null; + } + // Returns the index of the element in this sorted map, or -1 if it doesn't + // exist. + indexOf(t) { + // Number of nodes that were pruned when descending right + let e = 0, r = this.root; + for (;!r.isEmpty(); ) { + const n = this.comparator(t, r.key); + if (0 === n) return e + r.left.size; + n < 0 ? r = r.left : ( + // Count all nodes left of the node plus the node itself + e += r.left.size + 1, r = r.right); + } + // Node not found + return -1; + } + isEmpty() { + return this.root.isEmpty(); + } + // Returns the total number of nodes in the map. + get size() { + return this.root.size; + } + // Returns the minimum key in the map. + minKey() { + return this.root.minKey(); + } + // Returns the maximum key in the map. + maxKey() { + return this.root.maxKey(); + } + // Traverses the map in key order and calls the specified action function + // for each key/value pair. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(t) { + return this.root.inorderTraversal(t); + } + forEach(t) { + this.inorderTraversal(((e, r) => (t(e, r), !1))); + } + toString() { + const t = []; + return this.inorderTraversal(((e, r) => (t.push(`${e}:${r}`), !1))), `{${t.join(", ")}}`; + } + // Traverses the map in reverse key order and calls the specified action + // function for each key/value pair. If action returns true, traversal is + // aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(t) { + return this.root.reverseTraversal(t); + } + // Returns an iterator over the SortedMap. + getIterator() { + return new SortedMapIterator(this.root, null, this.comparator, !1); + } + getIteratorFrom(t) { + return new SortedMapIterator(this.root, t, this.comparator, !1); + } + getReverseIterator() { + return new SortedMapIterator(this.root, null, this.comparator, !0); + } + getReverseIteratorFrom(t) { + return new SortedMapIterator(this.root, t, this.comparator, !0); + } +} + + // end SortedMap +// An iterator over an LLRBNode. +class SortedMapIterator { + constructor(t, e, r, n) { + this.isReverse = n, this.nodeStack = []; + let i = 1; + for (;!t.isEmpty(); ) if (i = e ? r(t.key, e) : 1, + // flip the comparison if we're going in reverse + e && n && (i *= -1), i < 0) + // This node is less than our start key. ignore it + t = this.isReverse ? t.left : t.right; else { + if (0 === i) { + // This node is exactly equal to our start key. Push it on the stack, + // but stop iterating; + this.nodeStack.push(t); + break; + } + // This node is greater than our start key, add it to the stack and move + // to the next one + this.nodeStack.push(t), t = this.isReverse ? t.right : t.left; + } + } + getNext() { + let t = this.nodeStack.pop(); + const e = { + key: t.key, + value: t.value + }; + if (this.isReverse) for (t = t.left; !t.isEmpty(); ) this.nodeStack.push(t), t = t.right; else for (t = t.right; !t.isEmpty(); ) this.nodeStack.push(t), + t = t.left; + return e; + } + hasNext() { + return this.nodeStack.length > 0; + } + peek() { + if (0 === this.nodeStack.length) return null; + const t = this.nodeStack[this.nodeStack.length - 1]; + return { + key: t.key, + value: t.value + }; + } +} + + // end SortedMapIterator +// Represents a node in a Left-leaning Red-Black tree. +class LLRBNode { + constructor(t, e, r, n, i) { + this.key = t, this.value = e, this.color = null != r ? r : LLRBNode.RED, this.left = null != n ? n : LLRBNode.EMPTY, + this.right = null != i ? i : LLRBNode.EMPTY, this.size = this.left.size + 1 + this.right.size; + } + // Returns a copy of the current node, optionally replacing pieces of it. + copy(t, e, r, n, i) { + return new LLRBNode(null != t ? t : this.key, null != e ? e : this.value, null != r ? r : this.color, null != n ? n : this.left, null != i ? i : this.right); + } + isEmpty() { + return !1; + } + // Traverses the tree in key order and calls the specified action function + // for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(t) { + return this.left.inorderTraversal(t) || t(this.key, this.value) || this.right.inorderTraversal(t); + } + // Traverses the tree in reverse key order and calls the specified action + // function for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(t) { + return this.right.reverseTraversal(t) || t(this.key, this.value) || this.left.reverseTraversal(t); + } + // Returns the minimum node in the tree. + min() { + return this.left.isEmpty() ? this : this.left.min(); + } + // Returns the maximum key in the tree. + minKey() { + return this.min().key; + } + // Returns the maximum key in the tree. + maxKey() { + return this.right.isEmpty() ? this.key : this.right.maxKey(); + } + // Returns new tree, with the key/value added. + insert(t, e, r) { + let n = this; + const i = r(t, n.key); + return n = i < 0 ? n.copy(null, null, null, n.left.insert(t, e, r), null) : 0 === i ? n.copy(null, e, null, null, null) : n.copy(null, null, null, null, n.right.insert(t, e, r)), + n.fixUp(); + } + removeMin() { + if (this.left.isEmpty()) return LLRBNode.EMPTY; + let t = this; + return t.left.isRed() || t.left.left.isRed() || (t = t.moveRedLeft()), t = t.copy(null, null, null, t.left.removeMin(), null), + t.fixUp(); + } + // Returns new tree, with the specified item removed. + remove(t, e) { + let r, n = this; + if (e(t, n.key) < 0) n.left.isEmpty() || n.left.isRed() || n.left.left.isRed() || (n = n.moveRedLeft()), + n = n.copy(null, null, null, n.left.remove(t, e), null); else { + if (n.left.isRed() && (n = n.rotateRight()), n.right.isEmpty() || n.right.isRed() || n.right.left.isRed() || (n = n.moveRedRight()), + 0 === e(t, n.key)) { + if (n.right.isEmpty()) return LLRBNode.EMPTY; + r = n.right.min(), n = n.copy(r.key, r.value, null, null, n.right.removeMin()); + } + n = n.copy(null, null, null, null, n.right.remove(t, e)); + } + return n.fixUp(); + } + isRed() { + return this.color; + } + // Returns new tree after performing any needed rotations. + fixUp() { + let t = this; + return t.right.isRed() && !t.left.isRed() && (t = t.rotateLeft()), t.left.isRed() && t.left.left.isRed() && (t = t.rotateRight()), + t.left.isRed() && t.right.isRed() && (t = t.colorFlip()), t; + } + moveRedLeft() { + let t = this.colorFlip(); + return t.right.left.isRed() && (t = t.copy(null, null, null, null, t.right.rotateRight()), + t = t.rotateLeft(), t = t.colorFlip()), t; + } + moveRedRight() { + let t = this.colorFlip(); + return t.left.left.isRed() && (t = t.rotateRight(), t = t.colorFlip()), t; + } + rotateLeft() { + const t = this.copy(null, null, LLRBNode.RED, null, this.right.left); + return this.right.copy(null, null, this.color, t, null); + } + rotateRight() { + const t = this.copy(null, null, LLRBNode.RED, this.left.right, null); + return this.left.copy(null, null, this.color, null, t); + } + colorFlip() { + const t = this.left.copy(null, null, !this.left.color, null, null), e = this.right.copy(null, null, !this.right.color, null, null); + return this.copy(null, null, !this.color, t, e); + } + // For testing. + checkMaxDepth() { + const t = this.check(); + return Math.pow(2, t) <= this.size + 1; + } + // In a balanced RB tree, the black-depth (number of black nodes) from root to + // leaves is equal on both sides. This function verifies that or asserts. + check() { + if (this.isRed() && this.left.isRed()) throw fail(43730, { + key: this.key, + value: this.value + }); + if (this.right.isRed()) throw fail(14113, { + key: this.key, + value: this.value + }); + const t = this.left.check(); + if (t !== this.right.check()) throw fail(27949); + return t + (this.isRed() ? 0 : 1); + } +} + + // end LLRBNode +// Empty node is shared between all LLRB trees. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +LLRBNode.EMPTY = null, LLRBNode.RED = !0, LLRBNode.BLACK = !1; + +// end LLRBEmptyNode +LLRBNode.EMPTY = new +// Represents an empty node (a leaf node in the Red-Black Tree). +class LLRBEmptyNode { + constructor() { + this.size = 0; + } + get key() { + throw fail(57766); + } + get value() { + throw fail(16141); + } + get color() { + throw fail(16727); + } + get left() { + throw fail(29726); + } + get right() { + throw fail(36894); + } + // Returns a copy of the current node. + copy(t, e, r, n, i) { + return this; + } + // Returns a copy of the tree, with the specified key/value added. + insert(t, e, r) { + return new LLRBNode(t, e); + } + // Returns a copy of the tree, with the specified key removed. + remove(t, e) { + return this; + } + isEmpty() { + return !0; + } + inorderTraversal(t) { + return !1; + } + reverseTraversal(t) { + return !1; + } + minKey() { + return null; + } + maxKey() { + return null; + } + isRed() { + return !1; + } + // For testing. + checkMaxDepth() { + return !0; + } + check() { + return 0; + } +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * SortedSet is an immutable (copy-on-write) collection that holds elements + * in order specified by the provided comparator. + * + * NOTE: if provided comparator returns 0 for two elements, we consider them to + * be equal! + */ +class SortedSet { + constructor(t) { + this.comparator = t, this.data = new SortedMap(this.comparator); + } + has(t) { + return null !== this.data.get(t); + } + first() { + return this.data.minKey(); + } + last() { + return this.data.maxKey(); + } + get size() { + return this.data.size; + } + indexOf(t) { + return this.data.indexOf(t); + } + /** Iterates elements in order defined by "comparator" */ forEach(t) { + this.data.inorderTraversal(((e, r) => (t(e), !1))); + } + /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ forEachInRange(t, e) { + const r = this.data.getIteratorFrom(t[0]); + for (;r.hasNext(); ) { + const n = r.getNext(); + if (this.comparator(n.key, t[1]) >= 0) return; + e(n.key); + } + } + /** + * Iterates over `elem`s such that: start <= elem until false is returned. + */ forEachWhile(t, e) { + let r; + for (r = void 0 !== e ? this.data.getIteratorFrom(e) : this.data.getIterator(); r.hasNext(); ) { + if (!t(r.getNext().key)) return; + } + } + /** Finds the least element greater than or equal to `elem`. */ firstAfterOrEqual(t) { + const e = this.data.getIteratorFrom(t); + return e.hasNext() ? e.getNext().key : null; + } + getIterator() { + return new SortedSetIterator(this.data.getIterator()); + } + getIteratorFrom(t) { + return new SortedSetIterator(this.data.getIteratorFrom(t)); + } + /** Inserts or updates an element */ add(t) { + return this.copy(this.data.remove(t).insert(t, !0)); + } + /** Deletes an element */ delete(t) { + return this.has(t) ? this.copy(this.data.remove(t)) : this; + } + isEmpty() { + return this.data.isEmpty(); + } + unionWith(t) { + let e = this; + // Make sure `result` always refers to the larger one of the two sets. + return e.size < t.size && (e = t, t = this), t.forEach((t => { + e = e.add(t); + })), e; + } + isEqual(t) { + if (!(t instanceof SortedSet)) return !1; + if (this.size !== t.size) return !1; + const e = this.data.getIterator(), r = t.data.getIterator(); + for (;e.hasNext(); ) { + const t = e.getNext().key, n = r.getNext().key; + if (0 !== this.comparator(t, n)) return !1; + } + return !0; + } + toArray() { + const t = []; + return this.forEach((e => { + t.push(e); + })), t; + } + toString() { + const t = []; + return this.forEach((e => t.push(e))), "SortedSet(" + t.toString() + ")"; + } + copy(t) { + const e = new SortedSet(this.comparator); + return e.data = t, e; + } +} + +class SortedSetIterator { + constructor(t) { + this.iter = t; + } + getNext() { + return this.iter.getNext().key; + } + hasNext() { + return this.iter.hasNext(); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provides a set of fields that can be used to partially patch a document. + * FieldMask is used in conjunction with ObjectValue. + * Examples: + * foo - Overwrites foo entirely with the provided value. If foo is not + * present in the companion ObjectValue, the field is deleted. + * foo.bar - Overwrites only the field bar of the object foo. + * If foo is not an object, foo is replaced with an object + * containing foo + */ class FieldMask { + constructor(t) { + this.fields = t, + // TODO(dimond): validation of FieldMask + // Sort the field mask to support `FieldMask.isEqual()` and assert below. + t.sort(FieldPath$1.comparator); + } + static empty() { + return new FieldMask([]); + } + /** + * Returns a new FieldMask object that is the result of adding all the given + * fields paths to this field mask. + */ unionWith(t) { + let e = new SortedSet(FieldPath$1.comparator); + for (const t of this.fields) e = e.add(t); + for (const r of t) e = e.add(r); + return new FieldMask(e.toArray()); + } + /** + * Verifies that `fieldPath` is included by at least one field in this field + * mask. + * + * This is an O(n) operation, where `n` is the size of the field mask. + */ covers(t) { + for (const e of this.fields) if (e.isPrefixOf(t)) return !0; + return !1; + } + isEqual(t) { + return __PRIVATE_arrayEquals(this.fields, t.fields, ((t, e) => t.isEqual(e))); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An ObjectValue represents a MapValue in the Firestore Proto and offers the + * ability to add and remove fields (via the ObjectValueBuilder). + */ class ObjectValue { + constructor(t) { + this.value = t; + } + static empty() { + return new ObjectValue({ + mapValue: {} + }); + } + /** + * Returns the value at the given path or null. + * + * @param path - the path to search + * @returns The value at the path or null if the path is not set. + */ field(t) { + if (t.isEmpty()) return this.value; + { + let e = this.value; + for (let r = 0; r < t.length - 1; ++r) if (e = (e.mapValue.fields || {})[t.get(r)], + !__PRIVATE_isMapValue(e)) return null; + return e = (e.mapValue.fields || {})[t.lastSegment()], e || null; + } + } + /** + * Sets the field to the provided value. + * + * @param path - The field path to set. + * @param value - The value to set. + */ set(t, e) { + this.getFieldsMap(t.popLast())[t.lastSegment()] = __PRIVATE_deepClone(e); + } + /** + * Sets the provided fields to the provided values. + * + * @param data - A map of fields to values (or null for deletes). + */ setAll(t) { + let e = FieldPath$1.emptyPath(), r = {}, n = []; + t.forEach(((t, i) => { + if (!e.isImmediateParentOf(i)) { + // Insert the accumulated changes at this parent location + const t = this.getFieldsMap(e); + this.applyChanges(t, r, n), r = {}, n = [], e = i.popLast(); + } + t ? r[i.lastSegment()] = __PRIVATE_deepClone(t) : n.push(i.lastSegment()); + })); + const i = this.getFieldsMap(e); + this.applyChanges(i, r, n); + } + /** + * Removes the field at the specified path. If there is no field at the + * specified path, nothing is changed. + * + * @param path - The field path to remove. + */ delete(t) { + const e = this.field(t.popLast()); + __PRIVATE_isMapValue(e) && e.mapValue.fields && delete e.mapValue.fields[t.lastSegment()]; + } + isEqual(t) { + return __PRIVATE_valueEquals(this.value, t.value); + } + /** + * Returns the map that contains the leaf element of `path`. If the parent + * entry does not yet exist, or if it is not a map, a new map will be created. + */ getFieldsMap(t) { + let e = this.value; + e.mapValue.fields || (e.mapValue = { + fields: {} + }); + for (let r = 0; r < t.length; ++r) { + let n = e.mapValue.fields[t.get(r)]; + __PRIVATE_isMapValue(n) && n.mapValue.fields || (n = { + mapValue: { + fields: {} + } + }, e.mapValue.fields[t.get(r)] = n), e = n; + } + return e.mapValue.fields; + } + /** + * Modifies `fieldsMap` by adding, replacing or deleting the specified + * entries. + */ applyChanges(t, e, r) { + forEach(e, ((e, r) => t[e] = r)); + for (const e of r) delete t[e]; + } + clone() { + return new ObjectValue(__PRIVATE_deepClone(this.value)); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a document in Firestore with a key, version, data and whether it + * has local mutations applied to it. + * + * Documents can transition between states via `convertToFoundDocument()`, + * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does + * not transition to one of these states even after all mutations have been + * applied, `isValidDocument()` returns false and the document should be removed + * from all views. + */ class MutableDocument { + constructor(t, e, r, n, i, s, o) { + this.key = t, this.documentType = e, this.version = r, this.readTime = n, this.createTime = i, + this.data = s, this.documentState = o; + } + /** + * Creates a document with no known version or data, but which can serve as + * base document for mutations. + */ static newInvalidDocument(t) { + return new MutableDocument(t, 0 /* DocumentType.INVALID */ , + /* version */ SnapshotVersion.min(), + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist with the given data at the + * given version. + */ static newFoundDocument(t, e, r, n) { + return new MutableDocument(t, 1 /* DocumentType.FOUND_DOCUMENT */ , + /* version */ e, + /* readTime */ SnapshotVersion.min(), + /* createTime */ r, n, 0 /* DocumentState.SYNCED */); + } + /** Creates a new document that is known to not exist at the given version. */ static newNoDocument(t, e) { + return new MutableDocument(t, 2 /* DocumentType.NO_DOCUMENT */ , + /* version */ e, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist at the given version but + * whose data is not known (e.g. a document that was updated without a known + * base document). + */ static newUnknownDocument(t, e) { + return new MutableDocument(t, 3 /* DocumentType.UNKNOWN_DOCUMENT */ , + /* version */ e, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */); + } + /** + * Changes the document type to indicate that it exists and that its version + * and data are known. + */ convertToFoundDocument(t, e) { + // If a document is switching state from being an invalid or deleted + // document to a valid (FOUND_DOCUMENT) document, either due to receiving an + // update from Watch or due to applying a local set mutation on top + // of a deleted document, our best guess about its createTime would be the + // version at which the document transitioned to a FOUND_DOCUMENT. + return !this.createTime.isEqual(SnapshotVersion.min()) || 2 /* DocumentType.NO_DOCUMENT */ !== this.documentType && 0 /* DocumentType.INVALID */ !== this.documentType || (this.createTime = t), + this.version = t, this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */ , this.data = e, + this.documentState = 0 /* DocumentState.SYNCED */ , this; + } + /** + * Changes the document type to indicate that it doesn't exist at the given + * version. + */ convertToNoDocument(t) { + return this.version = t, this.documentType = 2 /* DocumentType.NO_DOCUMENT */ , + this.data = ObjectValue.empty(), this.documentState = 0 /* DocumentState.SYNCED */ , + this; + } + /** + * Changes the document type to indicate that it exists at a given version but + * that its data is not known (e.g. a document that was updated without a known + * base document). + */ convertToUnknownDocument(t) { + return this.version = t, this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */ , + this.data = ObjectValue.empty(), this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , + this; + } + setHasCommittedMutations() { + return this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , this; + } + setHasLocalMutations() { + return this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ , this.version = SnapshotVersion.min(), + this; + } + setReadTime(t) { + return this.readTime = t, this; + } + get hasLocalMutations() { + return 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ === this.documentState; + } + get hasCommittedMutations() { + return 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ === this.documentState; + } + get hasPendingWrites() { + return this.hasLocalMutations || this.hasCommittedMutations; + } + isValidDocument() { + return 0 /* DocumentType.INVALID */ !== this.documentType; + } + isFoundDocument() { + return 1 /* DocumentType.FOUND_DOCUMENT */ === this.documentType; + } + isNoDocument() { + return 2 /* DocumentType.NO_DOCUMENT */ === this.documentType; + } + isUnknownDocument() { + return 3 /* DocumentType.UNKNOWN_DOCUMENT */ === this.documentType; + } + isEqual(t) { + return t instanceof MutableDocument && this.key.isEqual(t.key) && this.version.isEqual(t.version) && this.documentType === t.documentType && this.documentState === t.documentState && this.data.isEqual(t.data); + } + mutableCopy() { + return new MutableDocument(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState); + } + toString() { + return `Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`; + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Visible for testing +class __PRIVATE_TargetImpl { + constructor(t, e = null, r = [], n = [], i = null, s = null, o = null) { + this.path = t, this.collectionGroup = e, this.orderBy = r, this.filters = n, this.limit = i, + this.startAt = s, this.endAt = o, this.O = null; + } +} + +/** + * Initializes a Target with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + * + * NOTE: you should always construct `Target` from `Query.toTarget` instead of + * using this factory method, because `Query` provides an implicit `orderBy` + * property. + */ function __PRIVATE_newTarget(t, e = null, r = [], n = [], i = null, s = null, o = null) { + return new __PRIVATE_TargetImpl(t, e, r, n, i, s, o); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Query encapsulates all the query attributes we support in the SDK. It can + * be run against the LocalStore, as well as be converted to a `Target` to + * query the RemoteStore results. + * + * Visible for testing. + */ +class __PRIVATE_QueryImpl { + /** + * Initializes a Query with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + */ + constructor(t, e = null, r = [], n = [], i = null, s = "F" /* LimitType.First */ , o = null, a = null) { + this.path = t, this.collectionGroup = e, this.explicitOrderBy = r, this.filters = n, + this.limit = i, this.limitType = s, this.startAt = o, this.endAt = a, this.q = null, + // The corresponding `Target` of this `Query` instance, for use with + // non-aggregate queries. + this.B = null, + // The corresponding `Target` of this `Query` instance, for use with + // aggregate queries. Unlike targets for non-aggregate queries, + // aggregate query targets do not contain normalized order-bys, they only + // contain explicit order-bys. + this.$ = null, this.startAt, this.endAt; + } +} + +/** Creates a new Query for a query that matches all documents at `path` */ +/** + * Returns whether the query matches a collection group rather than a specific + * collection. + */ +function __PRIVATE_isCollectionGroupQuery(t) { + return null !== t.collectionGroup; +} + +/** + * Returns the normalized order-by constraint that is used to execute the Query, + * which can be different from the order-by constraints the user provided (e.g. + * the SDK and backend always orders by `__name__`). The normalized order-by + * includes implicit order-bys in addition to the explicit user provided + * order-bys. + */ function __PRIVATE_queryNormalizedOrderBy(t) { + const e = __PRIVATE_debugCast(t); + if (null === e.q) { + e.q = []; + const t = new Set; + // Any explicit order by fields should be added as is. + for (const r of e.explicitOrderBy) e.q.push(r), t.add(r.field.canonicalString()); + // The order of the implicit ordering always matches the last explicit order by. + const r = e.explicitOrderBy.length > 0 ? e.explicitOrderBy[e.explicitOrderBy.length - 1].dir : "asc" /* Direction.ASCENDING */ , n = + // Returns the sorted set of inequality filter fields used in this query. + function __PRIVATE_getInequalityFilterFields(t) { + let e = new SortedSet(FieldPath$1.comparator); + return t.filters.forEach((t => { + t.getFlattenedFilters().forEach((t => { + t.isInequality() && (e = e.add(t.field)); + })); + })), e; + } + /** + * Creates a new Query for a collection group query that matches all documents + * within the provided collection group. + */ (e); + // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical + // order. When there are multiple inequality filters on the same field, the field should be added + // only once. + // Note: `SortedSet` sorts the key field before other fields. However, we want the key + // field to be sorted last. + n.forEach((n => { + t.has(n.canonicalString()) || n.isKeyField() || e.q.push(new OrderBy(n, r)); + })), + // Add the document key field to the last if it is not explicitly ordered. + t.has(FieldPath$1.keyField().canonicalString()) || e.q.push(new OrderBy(FieldPath$1.keyField(), r)); + } + return e.q; +} + +/** + * Converts this `Query` instance to its corresponding `Target` representation. + */ function __PRIVATE_queryToTarget(t) { + const e = __PRIVATE_debugCast(t); + return e.B || (e.B = __PRIVATE__queryToTarget(e, __PRIVATE_queryNormalizedOrderBy(t))), + e.B; +} + +/** + * Converts this `Query` instance to its corresponding `Target` representation, + * for use within an aggregate query. Unlike targets for non-aggregate queries, + * aggregate query targets do not contain normalized order-bys, they only + * contain explicit order-bys. + */ function __PRIVATE__queryToTarget(t, e) { + if ("F" /* LimitType.First */ === t.limitType) return __PRIVATE_newTarget(t.path, t.collectionGroup, e, t.filters, t.limit, t.startAt, t.endAt); + { + // Flip the orderBy directions since we want the last results + e = e.map((t => { + const e = "desc" /* Direction.DESCENDING */ === t.dir ? "asc" /* Direction.ASCENDING */ : "desc" /* Direction.DESCENDING */; + return new OrderBy(t.field, e); + })); + // We need to swap the cursors to match the now-flipped query ordering. + const r = t.endAt ? new Bound(t.endAt.position, t.endAt.inclusive) : null, n = t.startAt ? new Bound(t.startAt.position, t.startAt.inclusive) : null; + // Now return as a LimitType.First query. + return __PRIVATE_newTarget(t.path, t.collectionGroup, e, t.filters, t.limit, r, n); + } +} + +function __PRIVATE_queryWithAddedFilter(t, e) { + const r = t.filters.concat([ e ]); + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, t.explicitOrderBy.slice(), r, t.limit, t.limitType, t.startAt, t.endAt); +} + +function __PRIVATE_queryEquals(t, e) { + return function __PRIVATE_targetEquals(t, e) { + if (t.limit !== e.limit) return !1; + if (t.orderBy.length !== e.orderBy.length) return !1; + for (let r = 0; r < t.orderBy.length; r++) if (!__PRIVATE_orderByEquals(t.orderBy[r], e.orderBy[r])) return !1; + if (t.filters.length !== e.filters.length) return !1; + for (let r = 0; r < t.filters.length; r++) if (!__PRIVATE_filterEquals(t.filters[r], e.filters[r])) return !1; + return t.collectionGroup === e.collectionGroup && !!t.path.isEqual(e.path) && !!__PRIVATE_boundEquals(t.startAt, e.startAt) && __PRIVATE_boundEquals(t.endAt, e.endAt); + }(__PRIVATE_queryToTarget(t), __PRIVATE_queryToTarget(e)) && t.limitType === e.limitType; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns an DoubleValue for `value` that is encoded based the serializer's + * `useProto3Json` setting. + */ function __PRIVATE_toDouble(t, e) { + if (t.useProto3Json) { + if (isNaN(e)) return { + doubleValue: "NaN" + }; + if (e === 1 / 0) return { + doubleValue: "Infinity" + }; + if (e === -1 / 0) return { + doubleValue: "-Infinity" + }; + } + return { + doubleValue: __PRIVATE_isNegativeZero(e) ? "-0" : e + }; +} + +/** + * Returns an IntegerValue for `value`. + */ +/** + * Returns a value for a number that's appropriate to put into a proto. + * The return value is an IntegerValue if it can safely represent the value, + * otherwise a DoubleValue is returned. + */ +function toNumber(t, e) { + return function isSafeInteger(t) { + return "number" == typeof t && Number.isInteger(t) && !__PRIVATE_isNegativeZero(t) && t <= Number.MAX_SAFE_INTEGER && t >= Number.MIN_SAFE_INTEGER; + }(e) ? function __PRIVATE_toInteger(t) { + return { + integerValue: "" + t + }; + }(e) : __PRIVATE_toDouble(t, e); +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Used to represent a field transform on a mutation. */ class TransformOperation { + constructor() { + // Make sure that the structural type of `TransformOperation` is unique. + // See https://github.com/microsoft/TypeScript/issues/5451 + this._ = void 0; + } +} + +/** Transforms a value into a server-generated timestamp. */ class __PRIVATE_ServerTimestampTransform extends TransformOperation {} + +/** Transforms an array value via a union operation. */ class __PRIVATE_ArrayUnionTransformOperation extends TransformOperation { + constructor(t) { + super(), this.elements = t; + } +} + +/** Transforms an array value via a remove operation. */ class __PRIVATE_ArrayRemoveTransformOperation extends TransformOperation { + constructor(t) { + super(), this.elements = t; + } +} + +/** + * Implements the backend semantics for locally computed NUMERIC_ADD (increment) + * transforms. Converts all field values to integers or doubles, but unlike the + * backend does not cap integer values at 2^63. Instead, JavaScript number + * arithmetic is used and precision loss can occur for values greater than 2^53. + */ class __PRIVATE_NumericIncrementTransformOperation extends TransformOperation { + constructor(t, e) { + super(), this.serializer = t, this.k = e; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** A field path and the TransformOperation to perform upon it. */ class FieldTransform { + constructor(t, e) { + this.field = t, this.transform = e; + } +} + +/** + * Encodes a precondition for a mutation. This follows the model that the + * backend accepts with the special case of an explicit "empty" precondition + * (meaning no precondition). + */ class Precondition { + constructor(t, e) { + this.updateTime = t, this.exists = e; + } + /** Creates a new empty Precondition. */ static none() { + return new Precondition; + } + /** Creates a new Precondition with an exists flag. */ static exists(t) { + return new Precondition(void 0, t); + } + /** Creates a new Precondition based on a version a document exists at. */ static updateTime(t) { + return new Precondition(t); + } + /** Returns whether this Precondition is empty. */ get isNone() { + return void 0 === this.updateTime && void 0 === this.exists; + } + isEqual(t) { + return this.exists === t.exists && (this.updateTime ? !!t.updateTime && this.updateTime.isEqual(t.updateTime) : !t.updateTime); + } +} + +/** + * A mutation describes a self-contained change to a document. Mutations can + * create, replace, delete, and update subsets of documents. + * + * Mutations not only act on the value of the document but also its version. + * + * For local mutations (mutations that haven't been committed yet), we preserve + * the existing version for Set and Patch mutations. For Delete mutations, we + * reset the version to 0. + * + * Here's the expected transition table. + * + * MUTATION APPLIED TO RESULTS IN + * + * SetMutation Document(v3) Document(v3) + * SetMutation NoDocument(v3) Document(v0) + * SetMutation InvalidDocument(v0) Document(v0) + * PatchMutation Document(v3) Document(v3) + * PatchMutation NoDocument(v3) NoDocument(v3) + * PatchMutation InvalidDocument(v0) UnknownDocument(v3) + * DeleteMutation Document(v3) NoDocument(v0) + * DeleteMutation NoDocument(v3) NoDocument(v0) + * DeleteMutation InvalidDocument(v0) NoDocument(v0) + * + * For acknowledged mutations, we use the updateTime of the WriteResponse as + * the resulting version for Set and Patch mutations. As deletes have no + * explicit update time, we use the commitTime of the WriteResponse for + * Delete mutations. + * + * If a mutation is acknowledged by the backend but fails the precondition check + * locally, we transition to an `UnknownDocument` and rely on Watch to send us + * the updated version. + * + * Field transforms are used only with Patch and Set Mutations. We use the + * `updateTransforms` message to store transforms, rather than the `transforms`s + * messages. + * + * ## Subclassing Notes + * + * Every type of mutation needs to implement its own applyToRemoteDocument() and + * applyToLocalView() to implement the actual behavior of applying the mutation + * to some source document (see `setMutationApplyToRemoteDocument()` for an + * example). + */ class Mutation {} + +/** + * A mutation that creates or replaces the document at the given key with the + * object value contents. + */ class __PRIVATE_SetMutation extends Mutation { + constructor(t, e, r, n = []) { + super(), this.key = t, this.value = e, this.precondition = r, this.fieldTransforms = n, + this.type = 0 /* MutationType.Set */; + } + getFieldMask() { + return null; + } +} + +/** + * A mutation that modifies fields of the document at the given key with the + * given values. The values are applied through a field mask: + * + * * When a field is in both the mask and the values, the corresponding field + * is updated. + * * When a field is in neither the mask nor the values, the corresponding + * field is unmodified. + * * When a field is in the mask but not in the values, the corresponding field + * is deleted. + * * When a field is not in the mask but is in the values, the values map is + * ignored. + */ class __PRIVATE_PatchMutation extends Mutation { + constructor(t, e, r, n, i = []) { + super(), this.key = t, this.data = e, this.fieldMask = r, this.precondition = n, + this.fieldTransforms = i, this.type = 1 /* MutationType.Patch */; + } + getFieldMask() { + return this.fieldMask; + } +} + +/** A mutation that deletes the document at the given key. */ class __PRIVATE_DeleteMutation extends Mutation { + constructor(t, e) { + super(), this.key = t, this.precondition = e, this.type = 2 /* MutationType.Delete */ , + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } +} + +/** + * A mutation that verifies the existence of the document at the given key with + * the provided precondition. + * + * The `verify` operation is only used in Transactions, and this class serves + * primarily to facilitate serialization into protos. + */ class __PRIVATE_VerifyMutation extends Mutation { + constructor(t, e) { + super(), this.key = t, this.precondition = e, this.type = 3 /* MutationType.Verify */ , + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const rt = (() => { + const t = { + asc: "ASCENDING", + desc: "DESCENDING" + }; + return t; +})(), nt = (() => { + const t = { + "<": "LESS_THAN", + "<=": "LESS_THAN_OR_EQUAL", + ">": "GREATER_THAN", + ">=": "GREATER_THAN_OR_EQUAL", + "==": "EQUAL", + "!=": "NOT_EQUAL", + "array-contains": "ARRAY_CONTAINS", + in: "IN", + "not-in": "NOT_IN", + "array-contains-any": "ARRAY_CONTAINS_ANY" + }; + return t; +})(), it = (() => { + const t = { + and: "AND", + or: "OR" + }; + return t; +})(); + +/** + * This class generates JsonObject values for the Datastore API suitable for + * sending to either GRPC stub methods or via the JSON/HTTP REST API. + * + * The serializer supports both Protobuf.js and Proto3 JSON formats. By + * setting `useProto3Json` to true, the serializer will use the Proto3 JSON + * format. + * + * For a description of the Proto3 JSON format check + * https://developers.google.com/protocol-buffers/docs/proto3#json + * + * TODO(klimt): We can remove the databaseId argument if we keep the full + * resource name in documents. + */ +class JsonProtoSerializer { + constructor(t, e) { + this.databaseId = t, this.useProto3Json = e; + } +} + +/** + * Returns a value for a number (or null) that's appropriate to put into + * a google.protobuf.Int32Value proto. + * DO NOT USE THIS FOR ANYTHING ELSE. + * This method cheats. It's typed as returning "number" because that's what + * our generated proto interfaces say Int32Value must be. But GRPC actually + * expects a { value: } struct. + */ +/** + * Returns a value for a Date that's appropriate to put into a proto. + */ +function toTimestamp(t, e) { + if (t.useProto3Json) { + return `${new Date(1e3 * e.seconds).toISOString().replace(/\.\d*/, "").replace("Z", "")}.${("000000000" + e.nanoseconds).slice(-9)}Z`; + } + return { + seconds: "" + e.seconds, + nanos: e.nanoseconds + }; +} + +/** + * Returns a Timestamp typed object given protobuf timestamp value. + */ +/** + * Returns a value for bytes that's appropriate to put in a proto. + * + * Visible for testing. + */ +function __PRIVATE_toBytes(t, e) { + return t.useProto3Json ? e.toBase64() : e.toUint8Array(); +} + +function __PRIVATE_toVersion(t, e) { + return toTimestamp(t, e.toTimestamp()); +} + +function __PRIVATE_fromVersion(t) { + return __PRIVATE_hardAssert(!!t, 49232), SnapshotVersion.fromTimestamp(function fromTimestamp(t) { + const e = __PRIVATE_normalizeTimestamp(t); + return new Timestamp(e.seconds, e.nanos); + }(t)); +} + +function __PRIVATE_toResourceName(t, e) { + return __PRIVATE_toResourcePath(t, e).canonicalString(); +} + +function __PRIVATE_toResourcePath(t, e) { + const r = function __PRIVATE_fullyQualifiedPrefixPath(t) { + return new ResourcePath([ "projects", t.projectId, "databases", t.database ]); + }(t).child("documents"); + return void 0 === e ? r : r.child(e); +} + +function __PRIVATE_toName(t, e) { + return __PRIVATE_toResourceName(t.databaseId, e.path); +} + +function fromName(t, e) { + const r = function __PRIVATE_fromResourceName(t) { + const e = ResourcePath.fromString(t); + return __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(e), 10190, { + key: e.toString() + }), e; + }(e); + if (r.get(1) !== t.databaseId.projectId) throw new FirestoreError(y, "Tried to deserialize key from different project: " + r.get(1) + " vs " + t.databaseId.projectId); + if (r.get(3) !== t.databaseId.database) throw new FirestoreError(y, "Tried to deserialize key from different database: " + r.get(3) + " vs " + t.databaseId.database); + return new DocumentKey(function __PRIVATE_extractLocalPathFromResourceName(t) { + return __PRIVATE_hardAssert(t.length > 4 && "documents" === t.get(4), 29091, { + key: t.toString() + }), t.popFirst(5); + } + /** Creates a Document proto from key and fields (but no create/update time) */ (r)); +} + +function __PRIVATE_toMutationDocument(t, e, r) { + return { + name: __PRIVATE_toName(t, e), + fields: r.value.mapValue.fields + }; +} + +function __PRIVATE_fromBatchGetDocumentsResponse(t, e) { + return "found" in e ? function __PRIVATE_fromFound(t, e) { + __PRIVATE_hardAssert(!!e.found, 43571), e.found.name, e.found.updateTime; + const r = fromName(t, e.found.name), n = __PRIVATE_fromVersion(e.found.updateTime), i = e.found.createTime ? __PRIVATE_fromVersion(e.found.createTime) : SnapshotVersion.min(), s = new ObjectValue({ + mapValue: { + fields: e.found.fields + } + }); + return MutableDocument.newFoundDocument(r, n, i, s); + }(t, e) : "missing" in e ? function __PRIVATE_fromMissing(t, e) { + __PRIVATE_hardAssert(!!e.missing, 3894), __PRIVATE_hardAssert(!!e.readTime, 22933); + const r = fromName(t, e.missing), n = __PRIVATE_fromVersion(e.readTime); + return MutableDocument.newNoDocument(r, n); + }(t, e) : fail(7234, { + result: e + }); +} + +function toMutation(t, e) { + let r; + if (e instanceof __PRIVATE_SetMutation) r = { + update: __PRIVATE_toMutationDocument(t, e.key, e.value) + }; else if (e instanceof __PRIVATE_DeleteMutation) r = { + delete: __PRIVATE_toName(t, e.key) + }; else if (e instanceof __PRIVATE_PatchMutation) r = { + update: __PRIVATE_toMutationDocument(t, e.key, e.data), + updateMask: __PRIVATE_toDocumentMask(e.fieldMask) + }; else { + if (!(e instanceof __PRIVATE_VerifyMutation)) return fail(16599, { + L: e.type + }); + r = { + verify: __PRIVATE_toName(t, e.key) + }; + } + return e.fieldTransforms.length > 0 && (r.updateTransforms = e.fieldTransforms.map((t => function __PRIVATE_toFieldTransform(t, e) { + const r = e.transform; + if (r instanceof __PRIVATE_ServerTimestampTransform) return { + fieldPath: e.field.canonicalString(), + setToServerValue: "REQUEST_TIME" + }; + if (r instanceof __PRIVATE_ArrayUnionTransformOperation) return { + fieldPath: e.field.canonicalString(), + appendMissingElements: { + values: r.elements + } + }; + if (r instanceof __PRIVATE_ArrayRemoveTransformOperation) return { + fieldPath: e.field.canonicalString(), + removeAllFromArray: { + values: r.elements + } + }; + if (r instanceof __PRIVATE_NumericIncrementTransformOperation) return { + fieldPath: e.field.canonicalString(), + increment: r.k + }; + throw fail(20930, { + transform: e.transform + }); + }(0, t)))), e.precondition.isNone || (r.currentDocument = function __PRIVATE_toPrecondition(t, e) { + return void 0 !== e.updateTime ? { + updateTime: __PRIVATE_toVersion(t, e.updateTime) + } : void 0 !== e.exists ? { + exists: e.exists + } : fail(27497); + }(t, e.precondition)), r; +} + +function __PRIVATE_toQueryTarget(t, e) { + // Dissect the path into parent, collectionId, and optional key filter. + const r = { + structuredQuery: {} + }, n = e.path; + let i; + null !== e.collectionGroup ? (i = n, r.structuredQuery.from = [ { + collectionId: e.collectionGroup, + allDescendants: !0 + } ]) : (i = n.popLast(), r.structuredQuery.from = [ { + collectionId: n.lastSegment() + } ]), r.parent = function __PRIVATE_toQueryPath(t, e) { + return __PRIVATE_toResourceName(t.databaseId, e); + }(t, i); + const s = function __PRIVATE_toFilters(t) { + if (0 === t.length) return; + return __PRIVATE_toFilter(CompositeFilter.create(t, "and" /* CompositeOperator.AND */)); + }(e.filters); + s && (r.structuredQuery.where = s); + const o = function __PRIVATE_toOrder(t) { + if (0 === t.length) return; + return t.map((t => + // visible for testing + function __PRIVATE_toPropertyOrder(t) { + return { + field: __PRIVATE_toFieldPathReference(t.field), + direction: __PRIVATE_toDirection(t.dir) + }; + } + // visible for testing + (t))); + }(e.orderBy); + o && (r.structuredQuery.orderBy = o); + const a = function __PRIVATE_toInt32Proto(t, e) { + return t.useProto3Json || __PRIVATE_isNullOrUndefined(e) ? e : { + value: e + }; + }(t, e.limit); + return null !== a && (r.structuredQuery.limit = a), e.startAt && (r.structuredQuery.startAt = function __PRIVATE_toStartAtCursor(t) { + return { + before: t.inclusive, + values: t.position + }; + }(e.startAt)), e.endAt && (r.structuredQuery.endAt = function __PRIVATE_toEndAtCursor(t) { + return { + before: !t.inclusive, + values: t.position + }; + } + // visible for testing + (e.endAt)), { + M: r, + parent: i + }; +} + +function __PRIVATE_toDirection(t) { + return rt[t]; +} + +// visible for testing +function __PRIVATE_toOperatorName(t) { + return nt[t]; +} + +function __PRIVATE_toCompositeOperatorName(t) { + return it[t]; +} + +function __PRIVATE_toFieldPathReference(t) { + return { + fieldPath: t.canonicalString() + }; +} + +function __PRIVATE_toFilter(t) { + return t instanceof FieldFilter ? function __PRIVATE_toUnaryOrFieldFilter(t) { + if ("==" /* Operator.EQUAL */ === t.op) { + if (__PRIVATE_isNanValue(t.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: "IS_NAN" + } + }; + if (__PRIVATE_isNullValue(t.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: "IS_NULL" + } + }; + } else if ("!=" /* Operator.NOT_EQUAL */ === t.op) { + if (__PRIVATE_isNanValue(t.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: "IS_NOT_NAN" + } + }; + if (__PRIVATE_isNullValue(t.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: "IS_NOT_NULL" + } + }; + } + return { + fieldFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: __PRIVATE_toOperatorName(t.op), + value: t.value + } + }; + }(t) : t instanceof CompositeFilter ? function __PRIVATE_toCompositeFilter(t) { + const e = t.getFilters().map((t => __PRIVATE_toFilter(t))); + if (1 === e.length) return e[0]; + return { + compositeFilter: { + op: __PRIVATE_toCompositeOperatorName(t.op), + filters: e + } + }; + }(t) : fail(54877, { + filter: t + }); +} + +function __PRIVATE_toDocumentMask(t) { + const e = []; + return t.fields.forEach((t => e.push(t.canonicalString()))), { + fieldPaths: e + }; +} + +function __PRIVATE_isValidResourceName(t) { + // Resource names have at least 4 components (project ID, database ID) + return t.length >= 4 && "projects" === t.get(0) && "databases" === t.get(2); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_newSerializer(t) { + return new JsonProtoSerializer(t, /* useProto3Json= */ !0); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A helper for running delayed tasks following an exponential backoff curve + * between attempts. + * + * Each delay is made up of a "base" delay which follows the exponential + * backoff curve, and a +/- 50% "jitter" that is calculated and added to the + * base delay. This prevents clients from accidentally synchronizing their + * delays causing spikes of load to the backend. + */ +class __PRIVATE_ExponentialBackoff { + constructor( + /** + * The AsyncQueue to run backoff operations on. + */ + t, + /** + * The ID to use when scheduling backoff operations on the AsyncQueue. + */ + e, + /** + * The initial delay (used as the base delay on the first retry attempt). + * Note that jitter will still be applied, so the actual delay could be as + * little as 0.5*initialDelayMs. + */ + r = 1e3 + /** + * The multiplier to use to determine the extended base delay after each + * attempt. + */ , n = 1.5 + /** + * The maximum base delay after which no further backoff is performed. + * Note that jitter will still be applied, so the actual delay could be as + * much as 1.5*maxDelayMs. + */ , i = 6e4) { + this.U = t, this.timerId = e, this.j = r, this.W = n, this.K = i, this.G = 0, this.J = null, + /** The last backoff attempt, as epoch milliseconds. */ + this.H = Date.now(), this.reset(); + } + /** + * Resets the backoff delay. + * + * The very next backoffAndWait() will have no delay. If it is called again + * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and + * subsequent ones will increase according to the backoffFactor. + */ reset() { + this.G = 0; + } + /** + * Resets the backoff delay to the maximum delay (e.g. for use after a + * RESOURCE_EXHAUSTED error). + */ Y() { + this.G = this.K; + } + /** + * Returns a promise that resolves after currentDelayMs, and increases the + * delay for any subsequent attempts. If there was a pending backoff operation + * already, it will be canceled. + */ Z(t) { + // Cancel any pending backoff operation. + this.cancel(); + // First schedule using the current base (which may be 0 and should be + // honored as such). + const e = Math.floor(this.G + this.X()), r = Math.max(0, Date.now() - this.H), n = Math.max(0, e - r); + // Guard against lastAttemptTime being in the future due to a clock change. + n > 0 && __PRIVATE_logDebug("ExponentialBackoff", `Backing off for ${n} ms (base delay: ${this.G} ms, delay with jitter: ${e} ms, last attempt: ${r} ms ago)`), + this.J = this.U.enqueueAfterDelay(this.timerId, n, (() => (this.H = Date.now(), + t()))), + // Apply backoff factor to determine next delay and ensure it is within + // bounds. + this.G *= this.W, this.G < this.j && (this.G = this.j), this.G > this.K && (this.G = this.K); + } + tt() { + null !== this.J && (this.J.skipDelay(), this.J = null); + } + cancel() { + null !== this.J && (this.J.cancel(), this.J = null); + } + /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ X() { + return (Math.random() - .5) * this.G; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Datastore and its related methods are a wrapper around the external Google + * Cloud Datastore grpc API, which provides an interface that is more convenient + * for the rest of the client SDK architecture to consume. + */ class Datastore {} + +/** + * An implementation of Datastore that exposes additional state for internal + * consumption. + */ class __PRIVATE_DatastoreImpl extends Datastore { + constructor(t, e, r, n) { + super(), this.authCredentials = t, this.appCheckCredentials = e, this.connection = r, + this.serializer = n, this.et = !1; + } + rt() { + if (this.et) throw new FirestoreError(S, "The client has already been terminated."); + } + /** Invokes the provided RPC with auth and AppCheck tokens. */ I(t, e, r, n) { + return this.rt(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([i, s]) => this.connection.I(t, __PRIVATE_toResourcePath(e, r), n, i, s))).catch((t => { + throw "FirebaseError" === t.name ? (t.code === D && (this.authCredentials.invalidateToken(), + this.appCheckCredentials.invalidateToken()), t) : new FirestoreError(p, t.toString()); + })); + } + /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ D(t, e, r, n, i) { + return this.rt(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([s, o]) => this.connection.D(t, __PRIVATE_toResourcePath(e, r), n, s, o, i))).catch((t => { + throw "FirebaseError" === t.name ? (t.code === D && (this.authCredentials.invalidateToken(), + this.appCheckCredentials.invalidateToken()), t) : new FirestoreError(p, t.toString()); + })); + } + terminate() { + this.et = !0, this.connection.terminate(); + } +} + +// TODO(firestorexp): Make sure there is only one Datastore instance per +// firestore-exp client. +async function __PRIVATE_invokeCommitRpc(t, e) { + const r = __PRIVATE_debugCast(t), n = { + writes: e.map((t => toMutation(r.serializer, t))) + }; + await r.I("Commit", r.serializer.databaseId, ResourcePath.emptyPath(), n); +} + +async function __PRIVATE_invokeBatchGetDocumentsRpc(t, e) { + const r = __PRIVATE_debugCast(t), n = { + documents: e.map((t => __PRIVATE_toName(r.serializer, t))) + }, i = await r.D("BatchGetDocuments", r.serializer.databaseId, ResourcePath.emptyPath(), n, e.length), s = new Map; + i.forEach((t => { + const e = __PRIVATE_fromBatchGetDocumentsResponse(r.serializer, t); + s.set(e.key.toString(), e); + })); + const o = []; + return e.forEach((t => { + const e = s.get(t.toString()); + __PRIVATE_hardAssert(!!e, 55234, { + key: t + }), o.push(e); + })), o; +} + +async function __PRIVATE_invokeRunQueryRpc(t, e) { + const r = __PRIVATE_debugCast(t), {M: n, parent: i} = __PRIVATE_toQueryTarget(r.serializer, __PRIVATE_queryToTarget(e)); + return (await r.D("RunQuery", r.serializer.databaseId, i, { + structuredQuery: n.structuredQuery + })).filter((t => !!t.document)).map((t => function __PRIVATE_fromDocument(t, e, r) { + const n = fromName(t, e.name), i = __PRIVATE_fromVersion(e.updateTime), s = e.createTime ? __PRIVATE_fromVersion(e.createTime) : SnapshotVersion.min(), o = new ObjectValue({ + mapValue: { + fields: e.fields + } + }), a = MutableDocument.newFoundDocument(n, i, s, o); + return r && a.setHasCommittedMutations(), r ? a.setHasCommittedMutations() : a; + }(r.serializer, t.document, void 0))); +} + +async function __PRIVATE_invokeRunAggregationQueryRpc(t, e, r) { + const n = __PRIVATE_debugCast(t), {request: i, nt: s, parent: o} = function __PRIVATE_toRunAggregationQueryRequest(t, e, r, n) { + const {M: i, parent: s} = __PRIVATE_toQueryTarget(t, e), o = {}, a = []; + let u = 0; + return r.forEach((t => { + // Map all client-side aliases to a unique short-form + // alias. This avoids issues with client-side aliases that + // exceed the 1500-byte string size limit. + const e = n ? t.alias : "aggregate_" + u++; + o[e] = t.alias, "count" === t.aggregateType ? a.push({ + alias: e, + count: {} + }) : "avg" === t.aggregateType ? a.push({ + alias: e, + avg: { + field: __PRIVATE_toFieldPathReference(t.fieldPath) + } + }) : "sum" === t.aggregateType && a.push({ + alias: e, + sum: { + field: __PRIVATE_toFieldPathReference(t.fieldPath) + } + }); + })), { + request: { + structuredAggregationQuery: { + aggregations: a, + structuredQuery: i.structuredQuery + }, + parent: i.parent + }, + nt: o, + parent: s + }; + }(n.serializer, function __PRIVATE_queryToAggregateTarget(t) { + const e = __PRIVATE_debugCast(t); + return e.$ || ( + // Do not include implicit order-bys for aggregate queries. + e.$ = __PRIVATE__queryToTarget(e, t.explicitOrderBy)), e.$; + }(e), r); + n.connection.P || delete i.parent; + const a = (await n.D("RunAggregationQuery", n.serializer.databaseId, o, i, + /*expectedResponseCount=*/ 1)).filter((t => !!t.result)); + // Omit RunAggregationQueryResponse that only contain readTimes. + __PRIVATE_hardAssert(1 === a.length, 64727); + // Remap the short-form aliases that were sent to the server + // to the client-side aliases. Users will access the results + // using the client-side alias. + const u = a[0].result?.aggregateFields; + return Object.keys(u).reduce(((t, e) => (t[s[e]] = u[e], t)), {}); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const st = "ComponentProvider", ot = new Map; + +/** + * An instance map that ensures only one Datastore exists per Firestore + * instance. + */ +/** + * Returns an initialized and started Datastore for the given Firestore + * instance. Callers must invoke removeComponents() when the Firestore + * instance is terminated. + */ +function __PRIVATE_getDatastore(t) { + if (t._terminated) throw new FirestoreError(S, "The client has already been terminated."); + if (!ot.has(t)) { + __PRIVATE_logDebug(st, "Initializing Datastore"); + const e = function __PRIVATE_newConnection(t) { + return new __PRIVATE_FetchConnection(t); + }(function __PRIVATE_makeDatabaseInfo(t, e, r, n) { + return new DatabaseInfo(t, e, r, n.host, n.ssl, n.experimentalForceLongPolling, n.experimentalAutoDetectLongPolling, __PRIVATE_cloneLongPollingOptions(n.experimentalLongPollingOptions), n.useFetchStreams, n.isUsingEmulator); + } + /** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ (t._databaseId, t.app.options.appId || "", t._persistenceKey, t._freezeSettings())), r = __PRIVATE_newSerializer(t._databaseId), n = function __PRIVATE_newDatastore(t, e, r, n) { + return new __PRIVATE_DatastoreImpl(t, e, r, n); + }(t._authCredentials, t._appCheckCredentials, e, r); + ot.set(t, n); + } + return ot.get(t); +} + +/** + * Removes all components associated with the provided instance. Must be called + * when the `Firestore` instance is terminated. + */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const at = 1048576, ut = "firestore.googleapis.com", _t = !0; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// settings() defaults: +/** + * A concrete type describing all the values that can be applied via a + * user-supplied `FirestoreSettings` object. This is a separate type so that + * defaults can be supplied and the value can be checked for equality. + */ +class FirestoreSettingsImpl { + constructor(t) { + if (void 0 === t.host) { + if (void 0 !== t.ssl) throw new FirestoreError(y, "Can't provide ssl option if host option is not set"); + this.host = ut, this.ssl = _t; + } else this.host = t.host, this.ssl = t.ssl ?? _t; + if (this.isUsingEmulator = void 0 !== t.emulatorOptions, this.credentials = t.credentials, + this.ignoreUndefinedProperties = !!t.ignoreUndefinedProperties, this.localCache = t.localCache, + void 0 === t.cacheSizeBytes) this.cacheSizeBytes = 41943040; else { + if (-1 !== t.cacheSizeBytes && t.cacheSizeBytes < at) throw new FirestoreError(y, "cacheSizeBytes must be at least 1048576"); + this.cacheSizeBytes = t.cacheSizeBytes; + } + !function __PRIVATE_validateIsNotUsedTogether(t, e, r, n) { + if (!0 === e && !0 === n) throw new FirestoreError(y, `${t} and ${r} cannot be used together.`); + }("experimentalForceLongPolling", t.experimentalForceLongPolling, "experimentalAutoDetectLongPolling", t.experimentalAutoDetectLongPolling), + this.experimentalForceLongPolling = !!t.experimentalForceLongPolling, this.experimentalForceLongPolling ? this.experimentalAutoDetectLongPolling = !1 : void 0 === t.experimentalAutoDetectLongPolling ? this.experimentalAutoDetectLongPolling = true : + // For backwards compatibility, coerce the value to boolean even though + // the TypeScript compiler has narrowed the type to boolean already. + // noinspection PointlessBooleanExpressionJS + this.experimentalAutoDetectLongPolling = !!t.experimentalAutoDetectLongPolling, + this.experimentalLongPollingOptions = __PRIVATE_cloneLongPollingOptions(t.experimentalLongPollingOptions ?? {}), + function __PRIVATE_validateLongPollingOptions(t) { + if (void 0 !== t.timeoutSeconds) { + if (isNaN(t.timeoutSeconds)) throw new FirestoreError(y, `invalid long polling timeout: ${t.timeoutSeconds} (must not be NaN)`); + if (t.timeoutSeconds < 5) throw new FirestoreError(y, `invalid long polling timeout: ${t.timeoutSeconds} (minimum allowed value is 5)`); + if (t.timeoutSeconds > 30) throw new FirestoreError(y, `invalid long polling timeout: ${t.timeoutSeconds} (maximum allowed value is 30)`); + } + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ (this.experimentalLongPollingOptions), this.useFetchStreams = !!t.useFetchStreams; + } + isEqual(t) { + return this.host === t.host && this.ssl === t.ssl && this.credentials === t.credentials && this.cacheSizeBytes === t.cacheSizeBytes && this.experimentalForceLongPolling === t.experimentalForceLongPolling && this.experimentalAutoDetectLongPolling === t.experimentalAutoDetectLongPolling && function __PRIVATE_longPollingOptionsEqual(t, e) { + return t.timeoutSeconds === e.timeoutSeconds; + }(this.experimentalLongPollingOptions, t.experimentalLongPollingOptions) && this.ignoreUndefinedProperties === t.ignoreUndefinedProperties && this.useFetchStreams === t.useFetchStreams; + } +} + +class Firestore { + /** @hideconstructor */ + constructor(t, e, r, n) { + this._authCredentials = t, this._appCheckCredentials = e, this._databaseId = r, + this._app = n, + /** + * Whether it's a Firestore or Firestore Lite instance. + */ + this.type = "firestore-lite", this._persistenceKey = "(lite)", this._settings = new FirestoreSettingsImpl({}), + this._settingsFrozen = !1, this._emulatorOptions = {}, + // A task that is assigned when the terminate() is invoked and resolved when + // all components have shut down. Otherwise, Firestore is not terminated, + // which can mean either the FirestoreClient is in the process of starting, + // or restarting. + this._terminateTask = "notTerminated"; + } + /** + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service + * instance. + */ get app() { + if (!this._app) throw new FirestoreError(S, "Firestore was not initialized using the Firebase SDK. 'app' is not available"); + return this._app; + } + get _initialized() { + return this._settingsFrozen; + } + get _terminated() { + return "notTerminated" !== this._terminateTask; + } + _setSettings(t) { + if (this._settingsFrozen) throw new FirestoreError(S, "Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object."); + this._settings = new FirestoreSettingsImpl(t), this._emulatorOptions = t.emulatorOptions || {}, + void 0 !== t.credentials && (this._authCredentials = function __PRIVATE_makeAuthCredentialsProvider(t) { + if (!t) return new __PRIVATE_EmptyAuthCredentialsProvider; + switch (t.type) { + case "firstParty": + return new __PRIVATE_FirstPartyAuthCredentialsProvider(t.sessionIndex || "0", t.iamToken || null, t.authTokenFactory || null); + + case "provider": + return t.client; + + default: + throw new FirestoreError(y, "makeAuthCredentialsProvider failed due to invalid credential type"); + } + }(t.credentials)); + } + _getSettings() { + return this._settings; + } + _getEmulatorOptions() { + return this._emulatorOptions; + } + _freezeSettings() { + return this._settingsFrozen = !0, this._settings; + } + _delete() { + // The `_terminateTask` must be assigned future that completes when + // terminate is complete. The existence of this future puts SDK in state + // that will not accept further API interaction. + return "notTerminated" === this._terminateTask && (this._terminateTask = this._terminate()), + this._terminateTask; + } + async _restart() { + // The `_terminateTask` must equal 'notTerminated' after restart to + // signal that client is in a state that accepts API calls. + "notTerminated" === this._terminateTask ? await this._terminate() : this._terminateTask = "notTerminated"; + } + /** Returns a JSON-serializable representation of this `Firestore` instance. */ toJSON() { + return { + app: this._app, + databaseId: this._databaseId, + settings: this._settings + }; + } + /** + * Terminates all components used by this client. Subclasses can override + * this method to clean up their own dependencies, but must also call this + * method. + * + * Only ever called once. + */ _terminate() { + return function __PRIVATE_removeComponents(t) { + const e = ot.get(t); + e && (__PRIVATE_logDebug(st, "Removing Datastore"), ot.delete(t), e.terminate()); + }(this), Promise.resolve(); + } +} + +function initializeFirestore(t, e, r) { + r || (r = Q); + const n = _getProvider(t, "firestore/lite"); + if (n.isInitialized(r)) throw new FirestoreError(S, "Firestore can only be initialized once per app."); + return n.initialize({ + options: e, + instanceIdentifier: r + }); +} + +function getFirestore(t, r) { + const n = "object" == typeof t ? t : getApp(), i = "string" == typeof t ? t : r || "(default)", s = _getProvider(n, "firestore/lite").getImmediate({ + identifier: i + }); + if (!s._initialized) { + const t = getDefaultEmulatorHostnameAndPort("firestore"); + t && connectFirestoreEmulator(s, ...t); + } + return s; +} + +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ function connectFirestoreEmulator(t, e, r, n = {}) { + t = __PRIVATE_cast(t, Firestore); + const i = isCloudWorkstation(e), s = t._getSettings(), o = { + ...s, + emulatorOptions: t._getEmulatorOptions() + }, a = `${e}:${r}`; + i && (pingServer(`https://${a}`), updateEmulatorBanner("Firestore", !0)), s.host !== ut && s.host !== a && __PRIVATE_logWarn("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."); + const u = { + ...s, + host: a, + ssl: i, + emulatorOptions: n + }; + // No-op if the new configuration matches the current configuration. This supports SSR + // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice. + if (!deepEqual(u, o) && (t._setSettings(u), n.mockUserToken)) { + let e, r; + if ("string" == typeof n.mockUserToken) e = n.mockUserToken, r = User.MOCK_USER; else { + // Let createMockUserToken validate first (catches common mistakes like + // invalid field "uid" and missing field "sub" / "user_id".) + e = createMockUserToken(n.mockUserToken, t._app?.options.projectId); + const i = n.mockUserToken.sub || n.mockUserToken.user_id; + if (!i) throw new FirestoreError(y, "mockUserToken must contain 'sub' or 'user_id' field!"); + r = new User(i); + } + t._authCredentials = new __PRIVATE_EmulatorAuthCredentialsProvider(new __PRIVATE_OAuthToken(e, r)); + } +} + +/** + * Terminates the provided `Firestore` instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` functions + * may be used. Any other function will throw a `FirestoreError`. Termination + * does not cancel any pending writes, and any promises that are awaiting a + * response from the server will not be resolved. + * + * To restart after termination, create a new instance of `Firestore` with + * {@link (getFirestore:1)}. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all of + * its resources or in combination with {@link clearIndexedDbPersistence} to + * ensure that all local state is destroyed between test runs. + * + * @param firestore - The `Firestore` instance to terminate. + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ function terminate(t) { + return t = __PRIVATE_cast(t, Firestore), _removeServiceInstance(t.app, "firestore/lite"), t._delete(); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents an aggregation that can be performed by Firestore. + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +class AggregateField { + /** + * Create a new AggregateField + * @param aggregateType Specifies the type of aggregation operation to perform. + * @param _internalFieldPath Optionally specifies the field that is aggregated. + * @internal + */ + constructor(t = "count", e) { + this._internalFieldPath = e, + /** A type string to uniquely identify instances of this class. */ + this.type = "AggregateField", this.aggregateType = t; + } +} + +/** + * The results of executing an aggregation query. + */ class AggregateQuerySnapshot { + /** @hideconstructor */ + constructor(t, e, r) { + this._userDataWriter = e, this._data = r, + /** A type string to uniquely identify instances of this class. */ + this.type = "AggregateQuerySnapshot", this.query = t; + } + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ data() { + return this._userDataWriter.convertObjectMap(this._data); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `Query` refers to a query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ class Query { + // This is the lite version of the Query class in the main SDK. + /** @hideconstructor protected */ + constructor(t, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + e, r) { + this.converter = e, this._query = r, + /** The type of this Firestore reference. */ + this.type = "query", this.firestore = t; + } + withConverter(t) { + return new Query(this.firestore, t, this._query); + } +} + +/** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. + */ class DocumentReference { + /** @hideconstructor */ + constructor(t, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + e, r) { + this.converter = e, this._key = r, + /** The type of this Firestore reference. */ + this.type = "document", this.firestore = t; + } + get _path() { + return this._key.path; + } + /** + * The document's identifier within its collection. + */ get id() { + return this._key.path.lastSegment(); + } + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ get path() { + return this._key.path.canonicalString(); + } + /** + * The collection this `DocumentReference` belongs to. + */ get parent() { + return new CollectionReference(this.firestore, this.converter, this._key.path.popLast()); + } + withConverter(t) { + return new DocumentReference(this.firestore, t, this._key); + } + /** + * Returns a JSON-serializable representation of this `DocumentReference` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + type: DocumentReference._jsonSchemaVersion, + referencePath: this._key.toString() + }; + } + static fromJSON(t, e, r) { + if (__PRIVATE_validateJSON(e, DocumentReference._jsonSchema)) return new DocumentReference(t, r || null, new DocumentKey(ResourcePath.fromString(e.referencePath))); + } +} + +DocumentReference._jsonSchemaVersion = "firestore/documentReference/1.0", DocumentReference._jsonSchema = { + type: property("string", DocumentReference._jsonSchemaVersion), + referencePath: property("string") +}; + +/** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using {@link (query:1)}). + */ +class CollectionReference extends Query { + /** @hideconstructor */ + constructor(t, e, r) { + super(t, e, function __PRIVATE_newQueryForPath(t) { + return new __PRIVATE_QueryImpl(t); + }(r)), this._path = r, + /** The type of this Firestore reference. */ + this.type = "collection"; + } + /** The collection's identifier. */ get id() { + return this._query.path.lastSegment(); + } + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ get path() { + return this._query.path.canonicalString(); + } + /** + * A reference to the containing `DocumentReference` if this is a + * subcollection. If this isn't a subcollection, the reference is null. + */ get parent() { + const t = this._path.popLast(); + return t.isEmpty() ? null : new DocumentReference(this.firestore, + /* converter= */ null, new DocumentKey(t)); + } + withConverter(t) { + return new CollectionReference(this.firestore, t, this._path); + } +} + +function collection(t, e, ...r) { + if (t = getModularInstance(t), __PRIVATE_validateNonEmptyArgument("collection", "path", e), t instanceof Firestore) { + const n = ResourcePath.fromString(e, ...r); + return __PRIVATE_validateCollectionPath(n), new CollectionReference(t, /* converter= */ null, n); + } + { + if (!(t instanceof DocumentReference || t instanceof CollectionReference)) throw new FirestoreError(y, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore"); + const n = t._path.child(ResourcePath.fromString(e, ...r)); + return __PRIVATE_validateCollectionPath(n), new CollectionReference(t.firestore, + /* converter= */ null, n); + } +} + +// TODO(firestorelite): Consider using ErrorFactory - +// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106 +/** + * Creates and returns a new `Query` instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given `collectionId`. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param collectionId - Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `Query`. + */ function collectionGroup(t, e) { + if (t = __PRIVATE_cast(t, Firestore), __PRIVATE_validateNonEmptyArgument("collectionGroup", "collection id", e), + e.indexOf("/") >= 0) throw new FirestoreError(y, `Invalid collection ID '${e}' passed to function collectionGroup(). Collection IDs must not contain '/'.`); + return new Query(t, + /* converter= */ null, function __PRIVATE_newQueryForCollectionGroup(t) { + return new __PRIVATE_QueryImpl(ResourcePath.emptyPath(), t); + }(e)); +} + +function doc(t, e, ...r) { + if (t = getModularInstance(t), + // We allow omission of 'pathString' but explicitly prohibit passing in both + // 'undefined' and 'null'. + 1 === arguments.length && (e = __PRIVATE_AutoId.newId()), __PRIVATE_validateNonEmptyArgument("doc", "path", e), + t instanceof Firestore) { + const n = ResourcePath.fromString(e, ...r); + return __PRIVATE_validateDocumentPath(n), new DocumentReference(t, + /* converter= */ null, new DocumentKey(n)); + } + { + if (!(t instanceof DocumentReference || t instanceof CollectionReference)) throw new FirestoreError(y, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore"); + const n = t._path.child(ResourcePath.fromString(e, ...r)); + return __PRIVATE_validateDocumentPath(n), new DocumentReference(t.firestore, t instanceof CollectionReference ? t.converter : null, new DocumentKey(n)); + } +} + +/** + * Returns true if the provided references are equal. + * + * @param left - A reference to compare. + * @param right - A reference to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ function refEqual(t, e) { + return t = getModularInstance(t), e = getModularInstance(e), (t instanceof DocumentReference || t instanceof CollectionReference) && (e instanceof DocumentReference || e instanceof CollectionReference) && (t.firestore === e.firestore && t.path === e.path && t.converter === e.converter); +} + +/** + * Returns true if the provided queries point to the same collection and apply + * the same constraints. + * + * @param left - A `Query` to compare. + * @param right - A `Query` to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ function queryEqual(t, e) { + return t = getModularInstance(t), e = getModularInstance(e), t instanceof Query && e instanceof Query && (t.firestore === e.firestore && __PRIVATE_queryEquals(t._query, e._query) && t.converter === e.converter); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing an array of bytes. + */ class Bytes { + /** @hideconstructor */ + constructor(t) { + this._byteString = t; + } + /** + * Creates a new `Bytes` object from the given Base64 string, converting it to + * bytes. + * + * @param base64 - The Base64 string used to create the `Bytes` object. + */ static fromBase64String(t) { + try { + return new Bytes(ByteString.fromBase64String(t)); + } catch (t) { + throw new FirestoreError(y, "Failed to construct data from Base64 string: " + t); + } + } + /** + * Creates a new `Bytes` object from the given Uint8Array. + * + * @param array - The Uint8Array used to create the `Bytes` object. + */ static fromUint8Array(t) { + return new Bytes(ByteString.fromUint8Array(t)); + } + /** + * Returns the underlying bytes as a Base64-encoded string. + * + * @returns The Base64-encoded string created from the `Bytes` object. + */ toBase64() { + return this._byteString.toBase64(); + } + /** + * Returns the underlying bytes in a new `Uint8Array`. + * + * @returns The Uint8Array created from the `Bytes` object. + */ toUint8Array() { + return this._byteString.toUint8Array(); + } + /** + * Returns a string representation of the `Bytes` object. + * + * @returns A string representation of the `Bytes` object. + */ toString() { + return "Bytes(base64: " + this.toBase64() + ")"; + } + /** + * Returns true if this `Bytes` object is equal to the provided one. + * + * @param other - The `Bytes` object to compare against. + * @returns true if this `Bytes` object is equal to the provided one. + */ isEqual(t) { + return this._byteString.isEqual(t._byteString); + } + /** + * Returns a JSON-serializable representation of this `Bytes` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + type: Bytes._jsonSchemaVersion, + bytes: this.toBase64() + }; + } + /** + * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}. + * + * @param json a JSON object represention of a `Bytes` instance + * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ static fromJSON(t) { + if (__PRIVATE_validateJSON(t, Bytes._jsonSchema)) return Bytes.fromBase64String(t.bytes); + } +} + +Bytes._jsonSchemaVersion = "firestore/bytes/1.0", Bytes._jsonSchema = { + type: property("string", Bytes._jsonSchemaVersion), + bytes: property("string") +}; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `FieldPath` refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + * + * Create a `FieldPath` by providing field names. If more than one field + * name is provided, the path will point to a nested field in a document. + */ +class FieldPath { + /** + * Creates a `FieldPath` from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames - A list of field names. + */ + constructor(...t) { + for (let e = 0; e < t.length; ++e) if (0 === t[e].length) throw new FirestoreError(y, "Invalid field name at argument $(i + 1). Field names must not be empty."); + this._internalPath = new FieldPath$1(t); + } + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other - The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ isEqual(t) { + return this._internalPath.isEqual(t._internalPath); + } +} + +/** + * Returns a special sentinel `FieldPath` to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ function documentId() { + return new FieldPath(M); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Sentinel values that can be used when writing document fields with `set()` + * or `update()`. + */ class FieldValue { + /** + * @param _methodName - The public API endpoint that returns this class. + * @hideconstructor + */ + constructor(t) { + this._methodName = t; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ class GeoPoint { + /** + * Creates a new immutable `GeoPoint` object with the provided latitude and + * longitude values. + * @param latitude - The latitude as number between -90 and 90. + * @param longitude - The longitude as number between -180 and 180. + */ + constructor(t, e) { + if (!isFinite(t) || t < -90 || t > 90) throw new FirestoreError(y, "Latitude must be a number between -90 and 90, but was: " + t); + if (!isFinite(e) || e < -180 || e > 180) throw new FirestoreError(y, "Longitude must be a number between -180 and 180, but was: " + e); + this._lat = t, this._long = e; + } + /** + * The latitude of this `GeoPoint` instance. + */ get latitude() { + return this._lat; + } + /** + * The longitude of this `GeoPoint` instance. + */ get longitude() { + return this._long; + } + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other - The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ isEqual(t) { + return this._lat === t._lat && this._long === t._long; + } + /** + * Actually private to JS consumers of our API, so this function is prefixed + * with an underscore. + */ _compareTo(t) { + return __PRIVATE_primitiveComparator(this._lat, t._lat) || __PRIVATE_primitiveComparator(this._long, t._long); + } + /** + * Returns a JSON-serializable representation of this `GeoPoint` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + latitude: this._lat, + longitude: this._long, + type: GeoPoint._jsonSchemaVersion + }; + } + /** + * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}. + * + * @param json a JSON object represention of a `GeoPoint` instance + * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ static fromJSON(t) { + if (__PRIVATE_validateJSON(t, GeoPoint._jsonSchema)) return new GeoPoint(t.latitude, t.longitude); + } +} + +GeoPoint._jsonSchemaVersion = "firestore/geoPoint/1.0", GeoPoint._jsonSchema = { + type: property("string", GeoPoint._jsonSchemaVersion), + latitude: property("number"), + longitude: property("number") +}; + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link vector}. + * + * @class VectorValue + */ +class VectorValue { + /** + * @private + * @internal + */ + constructor(t) { + // Making a copy of the parameter. + this._values = (t || []).map((t => t)); + } + /** + * Returns a copy of the raw number array form of the vector. + */ toArray() { + return this._values.map((t => t)); + } + /** + * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise. + */ isEqual(t) { + /** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Verifies equality for an array of primitives. + * + * @private + * @internal + * @param left Array of primitives. + * @param right Array of primitives. + * @return True if arrays are equal. + */ + return function __PRIVATE_isPrimitiveArrayEqual(t, e) { + if (t.length !== e.length) return !1; + for (let r = 0; r < t.length; ++r) if (t[r] !== e[r]) return !1; + return !0; + }(this._values, t._values); + } + /** + * Returns a JSON-serializable representation of this `VectorValue` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + type: VectorValue._jsonSchemaVersion, + vectorValues: this._values + }; + } + /** + * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}. + * + * @param json a JSON object represention of a `VectorValue` instance. + * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ static fromJSON(t) { + if (__PRIVATE_validateJSON(t, VectorValue._jsonSchema)) { + if (Array.isArray(t.vectorValues) && t.vectorValues.every((t => "number" == typeof t))) return new VectorValue(t.vectorValues); + throw new FirestoreError(y, "Expected 'vectorValues' field to be a number array"); + } + } +} + +VectorValue._jsonSchemaVersion = "firestore/vectorValue/1.0", VectorValue._jsonSchema = { + type: property("string", VectorValue._jsonSchemaVersion), + vectorValues: property("object") +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const ct = /^__.*__$/; + +/** The result of parsing document data (e.g. for a setData call). */ class ParsedSetData { + constructor(t, e, r) { + this.data = t, this.fieldMask = e, this.fieldTransforms = r; + } + toMutation(t, e) { + return null !== this.fieldMask ? new __PRIVATE_PatchMutation(t, this.data, this.fieldMask, e, this.fieldTransforms) : new __PRIVATE_SetMutation(t, this.data, e, this.fieldTransforms); + } +} + +/** The result of parsing "update" data (i.e. for an updateData call). */ class ParsedUpdateData { + constructor(t, + // The fieldMask does not include document transforms. + e, r) { + this.data = t, this.fieldMask = e, this.fieldTransforms = r; + } + toMutation(t, e) { + return new __PRIVATE_PatchMutation(t, this.data, this.fieldMask, e, this.fieldTransforms); + } +} + +function __PRIVATE_isWrite(t) { + switch (t) { + case 0 /* UserDataSource.Set */ : + // fall through + case 2 /* UserDataSource.MergeSet */ : + // fall through + case 1 /* UserDataSource.Update */ : + return !0; + + case 3 /* UserDataSource.Argument */ : + case 4 /* UserDataSource.ArrayArgument */ : + return !1; + + default: + throw fail(40011, { + it: t + }); + } +} + +/** A "context" object passed around while parsing user data. */ class __PRIVATE_ParseContextImpl { + /** + * Initializes a ParseContext with the given source and path. + * + * @param settings - The settings for the parser. + * @param databaseId - The database ID of the Firestore instance. + * @param serializer - The serializer to use to generate the Value proto. + * @param ignoreUndefinedProperties - Whether to ignore undefined properties + * rather than throw. + * @param fieldTransforms - A mutable list of field transforms encountered + * while parsing the data. + * @param fieldMask - A mutable list of field paths encountered while parsing + * the data. + * + * TODO(b/34871131): We don't support array paths right now, so path can be + * null to indicate the context represents any location within an array (in + * which case certain features will not work and errors will be somewhat + * compromised). + */ + constructor(t, e, r, n, i, s) { + this.settings = t, this.databaseId = e, this.serializer = r, this.ignoreUndefinedProperties = n, + // Minor hack: If fieldTransforms is undefined, we assume this is an + // external call and we need to validate the entire path. + void 0 === i && this.st(), this.fieldTransforms = i || [], this.fieldMask = s || []; + } + get path() { + return this.settings.path; + } + get it() { + return this.settings.it; + } + /** Returns a new context with the specified settings overwritten. */ ot(t) { + return new __PRIVATE_ParseContextImpl({ + ...this.settings, + ...t + }, this.databaseId, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask); + } + ut(t) { + const e = this.path?.child(t), r = this.ot({ + path: e, + _t: !1 + }); + return r.ct(t), r; + } + lt(t) { + const e = this.path?.child(t), r = this.ot({ + path: e, + _t: !1 + }); + return r.st(), r; + } + ht(t) { + // TODO(b/34871131): We don't support array paths right now; so make path + // undefined. + return this.ot({ + path: void 0, + _t: !0 + }); + } + ft(t) { + return __PRIVATE_createError(t, this.settings.methodName, this.settings.dt || !1, this.path, this.settings.Et); + } + /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ contains(t) { + return void 0 !== this.fieldMask.find((e => t.isPrefixOf(e))) || void 0 !== this.fieldTransforms.find((e => t.isPrefixOf(e.field))); + } + st() { + // TODO(b/34871131): Remove null check once we have proper paths for fields + // within arrays. + if (this.path) for (let t = 0; t < this.path.length; t++) this.ct(this.path.get(t)); + } + ct(t) { + if (0 === t.length) throw this.ft("Document fields must not be empty"); + if (__PRIVATE_isWrite(this.it) && ct.test(t)) throw this.ft('Document fields cannot begin and end with "__"'); + } +} + +/** + * Helper for parsing raw user input (provided via the API) into internal model + * classes. + */ class __PRIVATE_UserDataReader { + constructor(t, e, r) { + this.databaseId = t, this.ignoreUndefinedProperties = e, this.serializer = r || __PRIVATE_newSerializer(t); + } + /** Creates a new top-level parse context. */ Tt(t, e, r, n = !1) { + return new __PRIVATE_ParseContextImpl({ + it: t, + methodName: e, + Et: r, + path: FieldPath$1.emptyPath(), + _t: !1, + dt: n + }, this.databaseId, this.serializer, this.ignoreUndefinedProperties); + } +} + +function __PRIVATE_newUserDataReader(t) { + const e = t._freezeSettings(), r = __PRIVATE_newSerializer(t._databaseId); + return new __PRIVATE_UserDataReader(t._databaseId, !!e.ignoreUndefinedProperties, r); +} + +/** Parse document data from a set() call. */ function __PRIVATE_parseSetData(t, e, r, n, i, s = {}) { + const o = t.Tt(s.merge || s.mergeFields ? 2 /* UserDataSource.MergeSet */ : 0 /* UserDataSource.Set */ , e, r, i); + __PRIVATE_validatePlainObject("Data must be an object, but it was:", o, n); + const a = __PRIVATE_parseObject(n, o); + let u, _; + if (s.merge) u = new FieldMask(o.fieldMask), _ = o.fieldTransforms; else if (s.mergeFields) { + const t = []; + for (const n of s.mergeFields) { + const i = __PRIVATE_fieldPathFromArgument$1(e, n, r); + if (!o.contains(i)) throw new FirestoreError(y, `Field '${i}' is specified in your field mask but missing from your input data.`); + __PRIVATE_fieldMaskContains(t, i) || t.push(i); + } + u = new FieldMask(t), _ = o.fieldTransforms.filter((t => u.covers(t.field))); + } else u = null, _ = o.fieldTransforms; + return new ParsedSetData(new ObjectValue(a), u, _); +} + +class __PRIVATE_DeleteFieldValueImpl extends FieldValue { + _toFieldTransform(t) { + if (2 /* UserDataSource.MergeSet */ !== t.it) throw 1 /* UserDataSource.Update */ === t.it ? t.ft(`${this._methodName}() can only appear at the top level of your update data`) : t.ft(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`); + // No transform to add for a delete, but we need to add it to our + // fieldMask so it gets deleted. + return t.fieldMask.push(t.path), null; + } + isEqual(t) { + return t instanceof __PRIVATE_DeleteFieldValueImpl; + } +} + +/** + * Creates a child context for parsing SerializableFieldValues. + * + * This is different than calling `ParseContext.contextWith` because it keeps + * the fieldTransforms and fieldMask separate. + * + * The created context has its `dataSource` set to `UserDataSource.Argument`. + * Although these values are used with writes, any elements in these FieldValues + * are not considered writes since they cannot contain any FieldValue sentinels, + * etc. + * + * @param fieldValue - The sentinel FieldValue for which to create a child + * context. + * @param context - The parent context. + * @param arrayElement - Whether or not the FieldValue has an array. + */ function __PRIVATE_createSentinelChildContext(t, e, r) { + return new __PRIVATE_ParseContextImpl({ + it: 3 /* UserDataSource.Argument */ , + Et: e.settings.Et, + methodName: t._methodName, + _t: r + }, e.databaseId, e.serializer, e.ignoreUndefinedProperties); +} + +class __PRIVATE_ServerTimestampFieldValueImpl extends FieldValue { + _toFieldTransform(t) { + return new FieldTransform(t.path, new __PRIVATE_ServerTimestampTransform); + } + isEqual(t) { + return t instanceof __PRIVATE_ServerTimestampFieldValueImpl; + } +} + +class __PRIVATE_ArrayUnionFieldValueImpl extends FieldValue { + constructor(t, e) { + super(t), this.Pt = e; + } + _toFieldTransform(t) { + const e = __PRIVATE_createSentinelChildContext(this, t, + /*array=*/ !0), r = this.Pt.map((t => __PRIVATE_parseData(t, e))), n = new __PRIVATE_ArrayUnionTransformOperation(r); + return new FieldTransform(t.path, n); + } + isEqual(t) { + return t instanceof __PRIVATE_ArrayUnionFieldValueImpl && deepEqual(this.Pt, t.Pt); + } +} + +class __PRIVATE_ArrayRemoveFieldValueImpl extends FieldValue { + constructor(t, e) { + super(t), this.Pt = e; + } + _toFieldTransform(t) { + const e = __PRIVATE_createSentinelChildContext(this, t, + /*array=*/ !0), r = this.Pt.map((t => __PRIVATE_parseData(t, e))), n = new __PRIVATE_ArrayRemoveTransformOperation(r); + return new FieldTransform(t.path, n); + } + isEqual(t) { + return t instanceof __PRIVATE_ArrayRemoveFieldValueImpl && deepEqual(this.Pt, t.Pt); + } +} + +class __PRIVATE_NumericIncrementFieldValueImpl extends FieldValue { + constructor(t, e) { + super(t), this.At = e; + } + _toFieldTransform(t) { + const e = new __PRIVATE_NumericIncrementTransformOperation(t.serializer, toNumber(t.serializer, this.At)); + return new FieldTransform(t.path, e); + } + isEqual(t) { + return t instanceof __PRIVATE_NumericIncrementFieldValueImpl && this.At === t.At; + } +} + +/** Parse update data from an update() call. */ function __PRIVATE_parseUpdateData(t, e, r, n) { + const i = t.Tt(1 /* UserDataSource.Update */ , e, r); + __PRIVATE_validatePlainObject("Data must be an object, but it was:", i, n); + const s = [], o = ObjectValue.empty(); + forEach(n, ((t, n) => { + const a = __PRIVATE_fieldPathFromDotSeparatedString(e, t, r); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + n = getModularInstance(n); + const u = i.lt(a); + if (n instanceof __PRIVATE_DeleteFieldValueImpl) + // Add it to the field mask, but don't add anything to updateData. + s.push(a); else { + const t = __PRIVATE_parseData(n, u); + null != t && (s.push(a), o.set(a, t)); + } + })); + const a = new FieldMask(s); + return new ParsedUpdateData(o, a, i.fieldTransforms); +} + +/** Parse update data from a list of field/value arguments. */ function __PRIVATE_parseUpdateVarargs(t, e, r, n, i, s) { + const o = t.Tt(1 /* UserDataSource.Update */ , e, r), a = [ __PRIVATE_fieldPathFromArgument$1(e, n, r) ], u = [ i ]; + if (s.length % 2 != 0) throw new FirestoreError(y, `Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`); + for (let t = 0; t < s.length; t += 2) a.push(__PRIVATE_fieldPathFromArgument$1(e, s[t])), + u.push(s[t + 1]); + const _ = [], c = ObjectValue.empty(); + // We iterate in reverse order to pick the last value for a field if the + // user specified the field multiple times. + for (let t = a.length - 1; t >= 0; --t) if (!__PRIVATE_fieldMaskContains(_, a[t])) { + const e = a[t]; + let r = u[t]; + // For Compat types, we have to "extract" the underlying types before + // performing validation. + r = getModularInstance(r); + const n = o.lt(e); + if (r instanceof __PRIVATE_DeleteFieldValueImpl) + // Add it to the field mask, but don't add anything to updateData. + _.push(e); else { + const t = __PRIVATE_parseData(r, n); + null != t && (_.push(e), c.set(e, t)); + } + } + const l = new FieldMask(_); + return new ParsedUpdateData(c, l, o.fieldTransforms); +} + +/** + * Parse a "query value" (e.g. value in a where filter or a value in a cursor + * bound). + * + * @param allowArrays - Whether the query value is an array that may directly + * contain additional arrays (e.g. the operand of an `in` query). + */ function __PRIVATE_parseQueryValue(t, e, r, n = !1) { + return __PRIVATE_parseData(r, t.Tt(n ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */ , e)); +} + +/** + * Parses user data to Protobuf Values. + * + * @param input - Data to be parsed. + * @param context - A context object representing the current path being parsed, + * the source of the data being parsed, etc. + * @returns The parsed value, or null if the value was a FieldValue sentinel + * that should not be included in the resulting parsed data. + */ function __PRIVATE_parseData(t, e) { + if (__PRIVATE_looksLikeJsonObject( + // Unwrap the API type from the Compat SDK. This will return the API type + // from firestore-exp. + t = getModularInstance(t))) return __PRIVATE_validatePlainObject("Unsupported field value:", e, t), + __PRIVATE_parseObject(t, e); + if (t instanceof FieldValue) + // FieldValues usually parse into transforms (except deleteField()) + // in which case we do not want to include this field in our parsed data + // (as doing so will overwrite the field directly prior to the transform + // trying to transform it). So we don't add this location to + // context.fieldMask and we return null as our parsing result. + /** + * "Parses" the provided FieldValueImpl, adding any necessary transforms to + * context.fieldTransforms. + */ + return function __PRIVATE_parseSentinelFieldValue(t, e) { + // Sentinels are only supported with writes, and not within arrays. + if (!__PRIVATE_isWrite(e.it)) throw e.ft(`${t._methodName}() can only be used with update() and set()`); + if (!e.path) throw e.ft(`${t._methodName}() is not currently supported inside arrays`); + const r = t._toFieldTransform(e); + r && e.fieldTransforms.push(r); + } + /** + * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue) + * + * @returns The parsed value + */ (t, e), null; + if (void 0 === t && e.ignoreUndefinedProperties) + // If the input is undefined it can never participate in the fieldMask, so + // don't handle this below. If `ignoreUndefinedProperties` is false, + // `parseScalarValue` will reject an undefined value. + return null; + if ( + // If context.path is null we are inside an array and we don't support + // field mask paths more granular than the top-level array. + e.path && e.fieldMask.push(e.path), t instanceof Array) { + // TODO(b/34871131): Include the path containing the array in the error + // message. + // In the case of IN queries, the parsed data is an array (representing + // the set of values to be included for the IN query) that may directly + // contain additional arrays (each representing an individual field + // value), so we disable this validation. + if (e.settings._t && 4 /* UserDataSource.ArrayArgument */ !== e.it) throw e.ft("Nested arrays are not supported"); + return function __PRIVATE_parseArray(t, e) { + const r = []; + let n = 0; + for (const i of t) { + let t = __PRIVATE_parseData(i, e.ht(n)); + null == t && ( + // Just include nulls in the array for fields being replaced with a + // sentinel. + t = { + nullValue: "NULL_VALUE" + }), r.push(t), n++; + } + return { + arrayValue: { + values: r + } + }; + }(t, e); + } + return function __PRIVATE_parseScalarValue(t, e) { + if (null === (t = getModularInstance(t))) return { + nullValue: "NULL_VALUE" + }; + if ("number" == typeof t) return toNumber(e.serializer, t); + if ("boolean" == typeof t) return { + booleanValue: t + }; + if ("string" == typeof t) return { + stringValue: t + }; + if (t instanceof Date) { + const r = Timestamp.fromDate(t); + return { + timestampValue: toTimestamp(e.serializer, r) + }; + } + if (t instanceof Timestamp) { + // Firestore backend truncates precision down to microseconds. To ensure + // offline mode works the same with regards to truncation, perform the + // truncation immediately without waiting for the backend to do that. + const r = new Timestamp(t.seconds, 1e3 * Math.floor(t.nanoseconds / 1e3)); + return { + timestampValue: toTimestamp(e.serializer, r) + }; + } + if (t instanceof GeoPoint) return { + geoPointValue: { + latitude: t.latitude, + longitude: t.longitude + } + }; + if (t instanceof Bytes) return { + bytesValue: __PRIVATE_toBytes(e.serializer, t._byteString) + }; + if (t instanceof DocumentReference) { + const r = e.databaseId, n = t.firestore._databaseId; + if (!n.isEqual(r)) throw e.ft(`Document reference is for database ${n.projectId}/${n.database} but should be for database ${r.projectId}/${r.database}`); + return { + referenceValue: __PRIVATE_toResourceName(t.firestore._databaseId || e.databaseId, t._key.path) + }; + } + if (t instanceof VectorValue) + /** + * Creates a new VectorValue proto value (using the internal format). + */ + return function __PRIVATE_parseVectorValue(t, e) { + const r = { + fields: { + [Y]: { + stringValue: tt + }, + [et]: { + arrayValue: { + values: t.toArray().map((t => { + if ("number" != typeof t) throw e.ft("VectorValues must only contain numeric values."); + return __PRIVATE_toDouble(e.serializer, t); + })) + } + } + } + }; + return { + mapValue: r + }; + } + /** + * Checks whether an object looks like a JSON object that should be converted + * into a struct. Normal class/prototype instances are considered to look like + * JSON objects since they should be converted to a struct value. Arrays, Dates, + * GeoPoints, etc. are not considered to look like JSON objects since they map + * to specific FieldValue types other than ObjectValue. + */ (t, e); + throw e.ft(`Unsupported field value: ${__PRIVATE_valueDescription(t)}`); + }(t, e); +} + +function __PRIVATE_parseObject(t, e) { + const r = {}; + return !function isEmpty(t) { + for (const e in t) if (Object.prototype.hasOwnProperty.call(t, e)) return !1; + return !0; + }(t) ? forEach(t, ((t, n) => { + const i = __PRIVATE_parseData(n, e.ut(t)); + null != i && (r[t] = i); + })) : + // If we encounter an empty object, we explicitly add it to the update + // mask to ensure that the server creates a map entry. + e.path && e.path.length > 0 && e.fieldMask.push(e.path), { + mapValue: { + fields: r + } + }; +} + +function __PRIVATE_looksLikeJsonObject(t) { + return !("object" != typeof t || null === t || t instanceof Array || t instanceof Date || t instanceof Timestamp || t instanceof GeoPoint || t instanceof Bytes || t instanceof DocumentReference || t instanceof FieldValue || t instanceof VectorValue); +} + +function __PRIVATE_validatePlainObject(t, e, r) { + if (!__PRIVATE_looksLikeJsonObject(r) || !__PRIVATE_isPlainObject(r)) { + const n = __PRIVATE_valueDescription(r); + throw "an object" === n ? e.ft(t + " a custom object") : e.ft(t + " " + n); + } +} + +/** + * Helper that calls fromDotSeparatedString() but wraps any error thrown. + */ function __PRIVATE_fieldPathFromArgument$1(t, e, r) { + if (( + // If required, replace the FieldPath Compat class with the firestore-exp + // FieldPath. + e = getModularInstance(e)) instanceof FieldPath) return e._internalPath; + if ("string" == typeof e) return __PRIVATE_fieldPathFromDotSeparatedString(t, e); + throw __PRIVATE_createError("Field path arguments must be of type string or ", t, + /* hasConverter= */ !1, + /* path= */ void 0, r); +} + +/** + * Matches any characters in a field path string that are reserved. + */ const lt = new RegExp("[~\\*/\\[\\]]"); + +/** + * Wraps fromDotSeparatedString with an error message about the method that + * was thrown. + * @param methodName - The publicly visible method name + * @param path - The dot-separated string form of a field path which will be + * split on dots. + * @param targetDoc - The document against which the field path will be + * evaluated. + */ function __PRIVATE_fieldPathFromDotSeparatedString(t, e, r) { + if (e.search(lt) >= 0) throw __PRIVATE_createError(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`, t, + /* hasConverter= */ !1, + /* path= */ void 0, r); + try { + return new FieldPath(...e.split("."))._internalPath; + } catch (n) { + throw __PRIVATE_createError(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`, t, + /* hasConverter= */ !1, + /* path= */ void 0, r); + } +} + +function __PRIVATE_createError(t, e, r, n, i) { + const s = n && !n.isEmpty(), o = void 0 !== i; + let a = `Function ${e}() called with invalid data`; + r && (a += " (via `toFirestore()`)"), a += ". "; + let u = ""; + return (s || o) && (u += " (found", s && (u += ` in field ${n}`), o && (u += ` in document ${i}`), + u += ")"), new FirestoreError(y, a + t + u); +} + +/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ function __PRIVATE_fieldMaskContains(t, e) { + return t.some((t => t.isEqual(e))); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ class DocumentSnapshot { + // Note: This class is stripped down version of the DocumentSnapshot in + // the legacy SDK. The changes are: + // - No support for SnapshotMetadata. + // - No support for SnapshotOptions. + /** @hideconstructor protected */ + constructor(t, e, r, n, i) { + this._firestore = t, this._userDataWriter = e, this._key = r, this._document = n, + this._converter = i; + } + /** Property of the `DocumentSnapshot` that provides the document's ID. */ get id() { + return this._key.path.lastSegment(); + } + /** + * The `DocumentReference` for the document included in the `DocumentSnapshot`. + */ get ref() { + return new DocumentReference(this._firestore, this._converter, this._key); + } + /** + * Signals whether or not the document at the snapshot's location exists. + * + * @returns true if the document exists. + */ exists() { + return null !== this._document; + } + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * @returns An `Object` containing all fields in the document or `undefined` + * if the document doesn't exist. + */ data() { + if (this._document) { + if (this._converter) { + // We only want to use the converter and create a new DocumentSnapshot + // if a converter has been provided. + const t = new QueryDocumentSnapshot(this._firestore, this._userDataWriter, this._key, this._document, + /* converter= */ null); + return this._converter.fromFirestore(t); + } + return this._userDataWriter.convertValue(this._document.data.value); + } + } + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + // We are using `any` here to avoid an explicit cast by our users. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get(t) { + if (this._document) { + const e = this._document.data.field(__PRIVATE_fieldPathFromArgument("DocumentSnapshot.get", t)); + if (null !== e) return this._userDataWriter.convertValue(e); + } + } +} + +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * @override + * @returns An `Object` containing all fields in the document. + */ + data() { + return super.data(); + } +} + +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ class QuerySnapshot { + /** @hideconstructor */ + constructor(t, e) { + this._docs = e, this.query = t; + } + /** An array of all the documents in the `QuerySnapshot`. */ get docs() { + return [ ...this._docs ]; + } + /** The number of documents in the `QuerySnapshot`. */ get size() { + return this.docs.length; + } + /** True if there are no documents in the `QuerySnapshot`. */ get empty() { + return 0 === this.docs.length; + } + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ forEach(t, e) { + this._docs.forEach(t, e); + } +} + +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ function snapshotEqual(t, e) { + return t = getModularInstance(t), e = getModularInstance(e), t instanceof DocumentSnapshot && e instanceof DocumentSnapshot ? t._firestore === e._firestore && t._key.isEqual(e._key) && (null === t._document ? null === e._document : t._document.isEqual(e._document)) && t._converter === e._converter : t instanceof QuerySnapshot && e instanceof QuerySnapshot && (queryEqual(t.query, e.query) && __PRIVATE_arrayEquals(t.docs, e.docs, snapshotEqual)); +} + +/** + * Helper that calls `fromDotSeparatedString()` but wraps any error thrown. + */ function __PRIVATE_fieldPathFromArgument(t, e) { + return "string" == typeof e ? __PRIVATE_fieldPathFromDotSeparatedString(t, e) : e instanceof FieldPath ? e._internalPath : e._delegate._internalPath; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An `AppliableConstraint` is an abstraction of a constraint that can be applied + * to a Firestore query. + */ +class AppliableConstraint {} + +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Firestore query. `QueryConstraint`s are created by invoking {@link where}, + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that + * also contains this `QueryConstraint`. + */ class QueryConstraint extends AppliableConstraint {} + +function query(t, e, ...r) { + let n = []; + e instanceof AppliableConstraint && n.push(e), n = n.concat(r), function __PRIVATE_validateQueryConstraintArray(t) { + const e = t.filter((t => t instanceof QueryCompositeFilterConstraint)).length, r = t.filter((t => t instanceof QueryFieldFilterConstraint)).length; + if (e > 1 || e > 0 && r > 0) throw new FirestoreError(y, "InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`."); + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Converts Firestore's internal types to the JavaScript types that we expose + * to the user. + * + * @internal + */ (n); + for (const e of n) t = e._apply(t); + return t; +} + +/** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ class QueryFieldFilterConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(t, e, r) { + super(), this._field = t, this._op = e, this._value = r, + /** The type of this query constraint */ + this.type = "where"; + } + static _create(t, e, r) { + return new QueryFieldFilterConstraint(t, e, r); + } + _apply(t) { + const e = this._parse(t); + return __PRIVATE_validateNewFieldFilter(t._query, e), new Query(t.firestore, t.converter, __PRIVATE_queryWithAddedFilter(t._query, e)); + } + _parse(t) { + const e = __PRIVATE_newUserDataReader(t.firestore), r = function __PRIVATE_newQueryFilter(t, e, r, n, i, s, o) { + let a; + if (i.isKeyField()) { + if ("array-contains" /* Operator.ARRAY_CONTAINS */ === s || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === s) throw new FirestoreError(y, `Invalid Query. You can't perform '${s}' queries on documentId().`); + if ("in" /* Operator.IN */ === s || "not-in" /* Operator.NOT_IN */ === s) { + __PRIVATE_validateDisjunctiveFilterElements(o, s); + const e = []; + for (const r of o) e.push(__PRIVATE_parseDocumentIdValue(n, t, r)); + a = { + arrayValue: { + values: e + } + }; + } else a = __PRIVATE_parseDocumentIdValue(n, t, o); + } else "in" /* Operator.IN */ !== s && "not-in" /* Operator.NOT_IN */ !== s && "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ !== s || __PRIVATE_validateDisjunctiveFilterElements(o, s), + a = __PRIVATE_parseQueryValue(r, e, o, + /* allowArrays= */ "in" /* Operator.IN */ === s || "not-in" /* Operator.NOT_IN */ === s); + const u = FieldFilter.create(i, s, a); + return u; + }(t._query, "where", e, t.firestore._databaseId, this._field, this._op, this._value); + return r; + } +} + +/** + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. + * + * @param fieldPath - The path to compare + * @param opStr - The operation string (e.g "<", "<=", "==", "<", + * "<=", "!="). + * @param value - The value for comparison + * @returns The created {@link QueryFieldFilterConstraint}. + */ function where(t, e, r) { + const n = e, i = __PRIVATE_fieldPathFromArgument("where", t); + return QueryFieldFilterConstraint._create(i, n, r); +} + +/** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ class QueryCompositeFilterConstraint extends AppliableConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + t, e) { + super(), this.type = t, this._queryConstraints = e; + } + static _create(t, e) { + return new QueryCompositeFilterConstraint(t, e); + } + _parse(t) { + const e = this._queryConstraints.map((e => e._parse(t))).filter((t => t.getFilters().length > 0)); + return 1 === e.length ? e[0] : CompositeFilter.create(e, this._getOperator()); + } + _apply(t) { + const e = this._parse(t); + return 0 === e.getFilters().length ? t : (function __PRIVATE_validateNewFilter(t, e) { + let r = t; + const n = e.getFlattenedFilters(); + for (const t of n) __PRIVATE_validateNewFieldFilter(r, t), r = __PRIVATE_queryWithAddedFilter(r, t); + } + // Checks if any of the provided filter operators are included in the given list of filters and + // returns the first one that is, or null if none are. + (t._query, e), new Query(t.firestore, t.converter, __PRIVATE_queryWithAddedFilter(t._query, e))); + } + _getQueryConstraints() { + return this._queryConstraints; + } + _getOperator() { + return "and" === this.type ? "and" /* CompositeOperator.AND */ : "or" /* CompositeOperator.OR */; + } +} + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ function or(...t) { + // Only support QueryFilterConstraints + return t.forEach((t => __PRIVATE_validateQueryFilterConstraint("or", t))), QueryCompositeFilterConstraint._create("or" /* CompositeOperator.OR */ , t); +} + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ function and(...t) { + // Only support QueryFilterConstraints + return t.forEach((t => __PRIVATE_validateQueryFilterConstraint("and", t))), QueryCompositeFilterConstraint._create("and" /* CompositeOperator.AND */ , t); +} + +/** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ class QueryOrderByConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(t, e) { + super(), this._field = t, this._direction = e, + /** The type of this query constraint */ + this.type = "orderBy"; + } + static _create(t, e) { + return new QueryOrderByConstraint(t, e); + } + _apply(t) { + const e = function __PRIVATE_newQueryOrderBy(t, e, r) { + if (null !== t.startAt) throw new FirestoreError(y, "Invalid query. You must not call startAt() or startAfter() before calling orderBy()."); + if (null !== t.endAt) throw new FirestoreError(y, "Invalid query. You must not call endAt() or endBefore() before calling orderBy()."); + const n = new OrderBy(e, r); + return n; + } + /** + * Create a `Bound` from a query and a document. + * + * Note that the `Bound` will always include the key of the document + * and so only the provided document will compare equal to the returned + * position. + * + * Will throw if the document does not contain all fields of the order by + * of the query or if any of the fields in the order by are an uncommitted + * server timestamp. + */ (t._query, this._field, this._direction); + return new Query(t.firestore, t.converter, function __PRIVATE_queryWithAddedOrderBy(t, e) { + // TODO(dimond): validate that orderBy does not list the same key twice. + const r = t.explicitOrderBy.concat([ e ]); + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, r, t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt); + }(t._query, e)); + } +} + +/** + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the + * specified field, optionally in descending order instead of ascending. + * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * + * @param fieldPath - The field to sort by. + * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @returns The created {@link QueryOrderByConstraint}. + */ function orderBy(t, e = "asc") { + const r = e, n = __PRIVATE_fieldPathFromArgument("orderBy", t); + return QueryOrderByConstraint._create(n, r); +} + +/** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ class QueryLimitConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + t, e, r) { + super(), this.type = t, this._limit = e, this._limitType = r; + } + static _create(t, e, r) { + return new QueryLimitConstraint(t, e, r); + } + _apply(t) { + return new Query(t.firestore, t.converter, function __PRIVATE_queryWithLimit(t, e, r) { + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), e, r, t.startAt, t.endAt); + }(t._query, this._limit, this._limitType)); + } +} + +/** + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ function limit(t) { + return __PRIVATE_validatePositiveNumber("limit", t), QueryLimitConstraint._create("limit", t, "F" /* LimitType.First */); +} + +/** + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. + * + * You must specify at least one `orderBy` clause for `limitToLast` queries, + * otherwise an exception will be thrown during execution. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ function limitToLast(t) { + return __PRIVATE_validatePositiveNumber("limitToLast", t), QueryLimitConstraint._create("limitToLast", t, "L" /* LimitType.Last */); +} + +/** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ class QueryStartAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + t, e, r) { + super(), this.type = t, this._docOrFields = e, this._inclusive = r; + } + static _create(t, e, r) { + return new QueryStartAtConstraint(t, e, r); + } + _apply(t) { + const e = __PRIVATE_newQueryBoundFromDocOrFields(t, this.type, this._docOrFields, this._inclusive); + return new Query(t.firestore, t.converter, function __PRIVATE_queryWithStartAt(t, e) { + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, e, t.endAt); + }(t._query, e)); + } +} + +function startAt(...t) { + return QueryStartAtConstraint._create("startAt", t, + /*inclusive=*/ !0); +} + +function startAfter(...t) { + return QueryStartAtConstraint._create("startAfter", t, + /*inclusive=*/ !1); +} + +/** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ class QueryEndAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + t, e, r) { + super(), this.type = t, this._docOrFields = e, this._inclusive = r; + } + static _create(t, e, r) { + return new QueryEndAtConstraint(t, e, r); + } + _apply(t) { + const e = __PRIVATE_newQueryBoundFromDocOrFields(t, this.type, this._docOrFields, this._inclusive); + return new Query(t.firestore, t.converter, function __PRIVATE_queryWithEndAt(t, e) { + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, e); + }(t._query, e)); + } +} + +function endBefore(...t) { + return QueryEndAtConstraint._create("endBefore", t, + /*inclusive=*/ !1); +} + +function endAt(...t) { + return QueryEndAtConstraint._create("endAt", t, + /*inclusive=*/ !0); +} + +/** Helper function to create a bound from a document or fields */ function __PRIVATE_newQueryBoundFromDocOrFields(t, e, r, n) { + if (r[0] = getModularInstance(r[0]), r[0] instanceof DocumentSnapshot) return function __PRIVATE_newQueryBoundFromDocument(t, e, r, n, i) { + if (!n) throw new FirestoreError(w, `Can't use a DocumentSnapshot that doesn't exist for ${r}().`); + const s = []; + // Because people expect to continue/end a query at the exact document + // provided, we need to use the implicit sort order rather than the explicit + // sort order, because it's guaranteed to contain the document key. That way + // the position becomes unambiguous and the query continues/ends exactly at + // the provided document. Without the key (by using the explicit sort + // orders), multiple documents could match the position, yielding duplicate + // results. + for (const r of __PRIVATE_queryNormalizedOrderBy(t)) if (r.field.isKeyField()) s.push(__PRIVATE_refValue(e, n.key)); else { + const t = n.data.field(r.field); + if (__PRIVATE_isServerTimestamp(t)) throw new FirestoreError(y, 'Invalid query. You are trying to start or end a query using a document for which the field "' + r.field + '" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)'); + if (null === t) { + const t = r.field.canonicalString(); + throw new FirestoreError(y, `Invalid query. You are trying to start or end a query using a document for which the field '${t}' (used as the orderBy) does not exist.`); + } + s.push(t); + } + return new Bound(s, i); + } + /** + * Converts a list of field values to a `Bound` for the given query. + */ (t._query, t.firestore._databaseId, e, r[0]._document, n); + { + const i = __PRIVATE_newUserDataReader(t.firestore); + return function __PRIVATE_newQueryBoundFromFields(t, e, r, n, i, s) { + // Use explicit order by's because it has to match the query the user made + const o = t.explicitOrderBy; + if (i.length > o.length) throw new FirestoreError(y, `Too many arguments provided to ${n}(). The number of arguments must be less than or equal to the number of orderBy() clauses`); + const a = []; + for (let s = 0; s < i.length; s++) { + const u = i[s]; + if (o[s].field.isKeyField()) { + if ("string" != typeof u) throw new FirestoreError(y, `Invalid query. Expected a string for document ID in ${n}(), but got a ${typeof u}`); + if (!__PRIVATE_isCollectionGroupQuery(t) && -1 !== u.indexOf("/")) throw new FirestoreError(y, `Invalid query. When querying a collection and ordering by documentId(), the value passed to ${n}() must be a plain document ID, but '${u}' contains a slash.`); + const r = t.path.child(ResourcePath.fromString(u)); + if (!DocumentKey.isDocumentKey(r)) throw new FirestoreError(y, `Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${n}() must result in a valid document path, but '${r}' is not because it contains an odd number of segments.`); + const i = new DocumentKey(r); + a.push(__PRIVATE_refValue(e, i)); + } else { + const t = __PRIVATE_parseQueryValue(r, n, u); + a.push(t); + } + } + return new Bound(a, s); + } + /** + * Parses the given `documentIdValue` into a `ReferenceValue`, throwing + * appropriate errors if the value is anything other than a `DocumentReference` + * or `string`, or if the string is malformed. + */ (t._query, t.firestore._databaseId, i, e, r, n); + } +} + +function __PRIVATE_parseDocumentIdValue(t, e, r) { + if ("string" == typeof (r = getModularInstance(r))) { + if ("" === r) throw new FirestoreError(y, "Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string."); + if (!__PRIVATE_isCollectionGroupQuery(e) && -1 !== r.indexOf("/")) throw new FirestoreError(y, `Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${r}' contains a '/' character.`); + const n = e.path.child(ResourcePath.fromString(r)); + if (!DocumentKey.isDocumentKey(n)) throw new FirestoreError(y, `Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${n}' is not because it has an odd number of segments (${n.length}).`); + return __PRIVATE_refValue(t, new DocumentKey(n)); + } + if (r instanceof DocumentReference) return __PRIVATE_refValue(t, r._key); + throw new FirestoreError(y, `Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${__PRIVATE_valueDescription(r)}.`); +} + +/** + * Validates that the value passed into a disjunctive filter satisfies all + * array requirements. + */ function __PRIVATE_validateDisjunctiveFilterElements(t, e) { + if (!Array.isArray(t) || 0 === t.length) throw new FirestoreError(y, `Invalid Query. A non-empty array is required for '${e.toString()}' filters.`); +} + +/** + * Given an operator, returns the set of operators that cannot be used with it. + * + * This is not a comprehensive check, and this function should be removed in the + * long term. Validations should occur in the Firestore backend. + * + * Operators in a query must adhere to the following set of rules: + * 1. Only one inequality per query. + * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators. + */ function __PRIVATE_validateNewFieldFilter(t, e) { + const r = function __PRIVATE_findOpInsideFilters(t, e) { + for (const r of t) for (const t of r.getFlattenedFilters()) if (e.indexOf(t.op) >= 0) return t.op; + return null; + }(t.filters, function __PRIVATE_conflictingOps(t) { + switch (t) { + case "!=" /* Operator.NOT_EQUAL */ : + return [ "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ]; + + case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ : + case "in" /* Operator.IN */ : + return [ "not-in" /* Operator.NOT_IN */ ]; + + case "not-in" /* Operator.NOT_IN */ : + return [ "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , "in" /* Operator.IN */ , "not-in" /* Operator.NOT_IN */ , "!=" /* Operator.NOT_EQUAL */ ]; + + default: + return []; + } + }(e.op)); + if (null !== r) + // Special case when it's a duplicate op to give a slightly clearer error message. + throw r === e.op ? new FirestoreError(y, `Invalid query. You cannot use more than one '${e.op.toString()}' filter.`) : new FirestoreError(y, `Invalid query. You cannot use '${e.op.toString()}' filters with '${r.toString()}' filters.`); +} + +function __PRIVATE_validateQueryFilterConstraint(t, e) { + if (!(e instanceof QueryFieldFilterConstraint || e instanceof QueryCompositeFilterConstraint)) throw new FirestoreError(y, `Function ${t}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`); +} + +class AbstractUserDataWriter { + convertValue(t, e = "none") { + switch (__PRIVATE_typeOrder(t)) { + case 0 /* TypeOrder.NullValue */ : + return null; + + case 1 /* TypeOrder.BooleanValue */ : + return t.booleanValue; + + case 2 /* TypeOrder.NumberValue */ : + return __PRIVATE_normalizeNumber(t.integerValue || t.doubleValue); + + case 3 /* TypeOrder.TimestampValue */ : + return this.convertTimestamp(t.timestampValue); + + case 4 /* TypeOrder.ServerTimestampValue */ : + return this.convertServerTimestamp(t, e); + + case 5 /* TypeOrder.StringValue */ : + return t.stringValue; + + case 6 /* TypeOrder.BlobValue */ : + return this.convertBytes(__PRIVATE_normalizeByteString(t.bytesValue)); + + case 7 /* TypeOrder.RefValue */ : + return this.convertReference(t.referenceValue); + + case 8 /* TypeOrder.GeoPointValue */ : + return this.convertGeoPoint(t.geoPointValue); + + case 9 /* TypeOrder.ArrayValue */ : + return this.convertArray(t.arrayValue, e); + + case 11 /* TypeOrder.ObjectValue */ : + return this.convertObject(t.mapValue, e); + + case 10 /* TypeOrder.VectorValue */ : + return this.convertVectorValue(t.mapValue); + + default: + throw fail(62114, { + value: t + }); + } + } + convertObject(t, e) { + return this.convertObjectMap(t.fields, e); + } + /** + * @internal + */ convertObjectMap(t, e = "none") { + const r = {}; + return forEach(t, ((t, n) => { + r[t] = this.convertValue(n, e); + })), r; + } + /** + * @internal + */ convertVectorValue(t) { + const e = t.fields?.[et].arrayValue?.values?.map((t => __PRIVATE_normalizeNumber(t.doubleValue))); + return new VectorValue(e); + } + convertGeoPoint(t) { + return new GeoPoint(__PRIVATE_normalizeNumber(t.latitude), __PRIVATE_normalizeNumber(t.longitude)); + } + convertArray(t, e) { + return (t.values || []).map((t => this.convertValue(t, e))); + } + convertServerTimestamp(t, e) { + switch (e) { + case "previous": + const r = __PRIVATE_getPreviousValue(t); + return null == r ? null : this.convertValue(r, e); + + case "estimate": + return this.convertTimestamp(__PRIVATE_getLocalWriteTime(t)); + + default: + return null; + } + } + convertTimestamp(t) { + const e = __PRIVATE_normalizeTimestamp(t); + return new Timestamp(e.seconds, e.nanos); + } + convertDocumentKey(t, e) { + const r = ResourcePath.fromString(t); + __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(r), 9688, { + name: t + }); + const n = new DatabaseId(r.get(1), r.get(3)), i = new DocumentKey(r.popFirst(5)); + return n.isEqual(e) || + // TODO(b/64130202): Somehow support foreign references. + __PRIVATE_logError(`Document ${i} contains a document reference within a different database (${n.projectId}/${n.database}) which is not supported. It will be treated as a reference in the current database (${e.projectId}/${e.database}) instead.`), + i; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Converts custom model object of type T into `DocumentData` by applying the + * converter if it exists. + * + * This function is used when converting user objects to `DocumentData` + * because we want to provide the user with a more specific error message if + * their `set()` or fails due to invalid data originating from a `toFirestore()` + * call. + */ function __PRIVATE_applyFirestoreDataConverter(t, e, r) { + let n; + // Cast to `any` in order to satisfy the union type constraint on + // toFirestore(). + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return n = t ? r && (r.merge || r.mergeFields) ? t.toFirestore(e, r) : t.toFirestore(e) : e, + n; +} + +class __PRIVATE_LiteUserDataWriter extends AbstractUserDataWriter { + constructor(t) { + super(), this.firestore = t; + } + convertBytes(t) { + return new Bytes(t); + } + convertReference(t) { + const e = this.convertDocumentKey(t, this.firestore._databaseId); + return new DocumentReference(this.firestore, /* converter= */ null, e); + } +} + +/** + * Reads the document referred to by the specified document reference. + * + * All documents are directly fetched from the server, even if the document was + * previously read or modified. Recent modifications are only reflected in the + * retrieved `DocumentSnapshot` if they have already been applied by the + * backend. If the client is offline, the read fails. If you like to use + * caching or see local modifications, please use the full Firestore SDK. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the current + * document contents. + */ function getDoc(t) { + const e = __PRIVATE_getDatastore((t = __PRIVATE_cast(t, DocumentReference)).firestore), r = new __PRIVATE_LiteUserDataWriter(t.firestore); + return __PRIVATE_invokeBatchGetDocumentsRpc(e, [ t._key ]).then((e => { + __PRIVATE_hardAssert(1 === e.length, 15618); + const n = e[0]; + return new DocumentSnapshot(t.firestore, r, t._key, n.isFoundDocument() ? n : null, t.converter); + })); +} + +/** + * Executes the query and returns the results as a {@link QuerySnapshot}. + * + * All queries are executed directly by the server, even if the query was + * previously executed. Recent modifications are only reflected in the retrieved + * results if they have already been applied by the backend. If the client is + * offline, the operation fails. To see previously cached result and local + * modifications, use the full Firestore SDK. + * + * @param query - The `Query` to execute. + * @returns A Promise that will be resolved with the results of the query. + */ function getDocs(t) { + (function __PRIVATE_validateHasExplicitOrderByForLimitToLast(t) { + if ("L" /* LimitType.Last */ === t.limitType && 0 === t.explicitOrderBy.length) throw new FirestoreError(O, "limitToLast() queries require specifying at least one orderBy() clause"); + })((t = __PRIVATE_cast(t, Query))._query); + const e = __PRIVATE_getDatastore(t.firestore), r = new __PRIVATE_LiteUserDataWriter(t.firestore); + return __PRIVATE_invokeRunQueryRpc(e, t._query).then((e => { + const n = e.map((e => new QueryDocumentSnapshot(t.firestore, r, e.key, e, t.converter))); + return "L" /* LimitType.Last */ === t._query.limitType && + // Limit to last queries reverse the orderBy constraint that was + // specified by the user. As such, we need to reverse the order of the + // results to return the documents in the expected order. + n.reverse(), new QuerySnapshot(t, n); + })); +} + +function setDoc(t, e, r) { + const n = __PRIVATE_applyFirestoreDataConverter((t = __PRIVATE_cast(t, DocumentReference)).converter, e, r), i = __PRIVATE_parseSetData(__PRIVATE_newUserDataReader(t.firestore), "setDoc", t._key, n, null !== t.converter, r); + return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore(t.firestore), [ i.toMutation(t._key, Precondition.none()) ]); +} + +function updateDoc(t, e, r, ...n) { + const i = __PRIVATE_newUserDataReader((t = __PRIVATE_cast(t, DocumentReference)).firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + let s; + s = "string" == typeof (e = getModularInstance(e)) || e instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(i, "updateDoc", t._key, e, r, n) : __PRIVATE_parseUpdateData(i, "updateDoc", t._key, e); + return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore(t.firestore), [ s.toMutation(t._key, Precondition.exists(!0)) ]); +} + +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * The deletion will only be reflected in document reads that occur after the + * returned promise resolves. If the client is offline, the + * delete fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to delete. + * @returns A `Promise` resolved once the document has been successfully + * deleted from the backend. + */ function deleteDoc(t) { + return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore((t = __PRIVATE_cast(t, DocumentReference)).firestore), [ new __PRIVATE_DeleteMutation(t._key, Precondition.none()) ]); +} + +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend. + */ function addDoc(t, e) { + const r = doc(t = __PRIVATE_cast(t, CollectionReference)), n = __PRIVATE_applyFirestoreDataConverter(t.converter, e), i = __PRIVATE_parseSetData(__PRIVATE_newUserDataReader(t.firestore), "addDoc", r._key, n, null !== r.converter, {}); + return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore(t.firestore), [ i.toMutation(r._key, Precondition.exists(!1)) ]).then((() => r)); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ function getCount(t) { + return getAggregate(t, { + count: count() + }); +} + +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregate(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ function getAggregate(t, e) { + const r = __PRIVATE_cast(t.firestore, Firestore), n = __PRIVATE_getDatastore(r), i = function __PRIVATE_mapToArray(t, e) { + const r = []; + for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && r.push(e(t[n], n, t)); + return r; + }(e, ((t, e) => new __PRIVATE_AggregateImpl(e, t.aggregateType, t._internalFieldPath))); + // Run the aggregation and convert the results + return __PRIVATE_invokeRunAggregationQueryRpc(n, t._query, i).then((e => function __PRIVATE_convertToAggregateQuerySnapshot(t, e, r) { + const n = new __PRIVATE_LiteUserDataWriter(t), i = new AggregateQuerySnapshot(e, n, r); + return i; + } + /** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ (r, t, e))); +} + +function sum(t) { + return new AggregateField("sum", __PRIVATE_fieldPathFromArgument$1("sum", t)); +} + +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ function average(t) { + return new AggregateField("avg", __PRIVATE_fieldPathFromArgument$1("average", t)); +} + +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ function count() { + return new AggregateField("count"); +} + +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ function aggregateFieldEqual(t, e) { + return t instanceof AggregateField && e instanceof AggregateField && t.aggregateType === e.aggregateType && t._internalFieldPath?.canonicalString() === e._internalFieldPath?.canonicalString(); +} + +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ function aggregateQuerySnapshotEqual(t, e) { + return queryEqual(t.query, e.query) && deepEqual(t.data(), e.data()); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. + */ function deleteField() { + return new __PRIVATE_DeleteFieldValueImpl("deleteField"); +} + +/** + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to + * include a server-generated timestamp in the written data. + */ function serverTimestamp() { + return new __PRIVATE_ServerTimestampFieldValueImpl("serverTimestamp"); +} + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array + * value that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements - The elements to union into the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()`. + */ function arrayUnion(...t) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new __PRIVATE_ArrayUnionFieldValueImpl("arrayUnion", t); +} + +/** + * Returns a special value that can be used with {@link (setDoc:1)} or {@link + * updateDoc:1} that tells the server to remove the given elements from any + * array value that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is not + * already an array it will be overwritten with an empty array. + * + * @param elements - The elements to remove from the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ function arrayRemove(...t) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new __PRIVATE_ArrayRemoveFieldValueImpl("arrayRemove", t); +} + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by + * the given value. + * + * If either the operand or the current field value uses floating point + * precision, all arithmetic follows IEEE 754 semantics. If both values are + * integers, values outside of JavaScript's safe number range + * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to + * precision loss. Furthermore, once processed by the Firestore backend, all + * integer operations are capped between -2^63 and 2^63-1. + * + * If the current field value is not of type `number`, or if the field does not + * yet exist, the transformation sets the field to the given value. + * + * @param n - The value to increment by. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ function increment(t) { + return new __PRIVATE_NumericIncrementFieldValueImpl("increment", t); +} + +/** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ function vector(t) { + return new VectorValue(t); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It + * provides methods for adding writes to the write batch. None of the writes + * will be committed (or visible locally) until {@link WriteBatch.commit} is + * called. + */ class WriteBatch { + /** @hideconstructor */ + constructor(t, e) { + this._firestore = t, this._commitHandler = e, this._mutations = [], this._committed = !1, + this._dataReader = __PRIVATE_newUserDataReader(t); + } + set(t, e, r) { + this._verifyNotCommitted(); + const n = __PRIVATE_validateReference(t, this._firestore), i = __PRIVATE_applyFirestoreDataConverter(n.converter, e, r), s = __PRIVATE_parseSetData(this._dataReader, "WriteBatch.set", n._key, i, null !== n.converter, r); + return this._mutations.push(s.toMutation(n._key, Precondition.none())), this; + } + update(t, e, r, ...n) { + this._verifyNotCommitted(); + const i = __PRIVATE_validateReference(t, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + let s; + return s = "string" == typeof (e = getModularInstance(e)) || e instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(this._dataReader, "WriteBatch.update", i._key, e, r, n) : __PRIVATE_parseUpdateData(this._dataReader, "WriteBatch.update", i._key, e), + this._mutations.push(s.toMutation(i._key, Precondition.exists(!0))), this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ delete(t) { + this._verifyNotCommitted(); + const e = __PRIVATE_validateReference(t, this._firestore); + return this._mutations = this._mutations.concat(new __PRIVATE_DeleteMutation(e._key, Precondition.none())), + this; + } + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `Promise` resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit (note that it won't + * resolve while you're offline). + */ commit() { + return this._verifyNotCommitted(), this._committed = !0, this._mutations.length > 0 ? this._commitHandler(this._mutations) : Promise.resolve(); + } + _verifyNotCommitted() { + if (this._committed) throw new FirestoreError(S, "A write batch can no longer be used after commit() has been called."); + } +} + +function __PRIVATE_validateReference(t, e) { + if ((t = getModularInstance(t)).firestore !== e) throw new FirestoreError(y, "Provided document reference is from a different Firestore instance."); + return t; +} + +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single WriteBatch + * is 500. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `WriteBatch` that can be used to atomically execute multiple + * writes. + */ function writeBatch(t) { + const e = __PRIVATE_getDatastore(t = __PRIVATE_cast(t, Firestore)); + return new WriteBatch(t, (t => __PRIVATE_invokeCommitRpc(e, t))); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Internal transaction object responsible for accumulating the mutations to + * perform and the base versions for any documents read. + */ class Transaction$1 { + constructor(t) { + this.datastore = t, + // The version of each document that was read during this transaction. + this.readVersions = new Map, this.mutations = [], this.committed = !1, + /** + * A deferred usage error that occurred previously in this transaction that + * will cause the transaction to fail once it actually commits. + */ + this.lastTransactionError = null, + /** + * Set of documents that have been written in the transaction. + * + * When there's more than one write to the same key in a transaction, any + * writes after the first are handled differently. + */ + this.writtenDocs = new Set; + } + async lookup(t) { + if (this.ensureCommitNotCalled(), this.mutations.length > 0) throw this.lastTransactionError = new FirestoreError(y, "Firestore transactions require all reads to be executed before all writes."), + this.lastTransactionError; + const e = await __PRIVATE_invokeBatchGetDocumentsRpc(this.datastore, t); + return e.forEach((t => this.recordVersion(t))), e; + } + set(t, e) { + this.write(e.toMutation(t, this.precondition(t))), this.writtenDocs.add(t.toString()); + } + update(t, e) { + try { + this.write(e.toMutation(t, this.preconditionForUpdate(t))); + } catch (t) { + this.lastTransactionError = t; + } + this.writtenDocs.add(t.toString()); + } + delete(t) { + this.write(new __PRIVATE_DeleteMutation(t, this.precondition(t))), this.writtenDocs.add(t.toString()); + } + async commit() { + if (this.ensureCommitNotCalled(), this.lastTransactionError) throw this.lastTransactionError; + const t = this.readVersions; + // For each mutation, note that the doc was written. + this.mutations.forEach((e => { + t.delete(e.key.toString()); + })), + // For each document that was read but not written to, we want to perform + // a `verify` operation. + t.forEach(((t, e) => { + const r = DocumentKey.fromPath(e); + this.mutations.push(new __PRIVATE_VerifyMutation(r, this.precondition(r))); + })), await __PRIVATE_invokeCommitRpc(this.datastore, this.mutations), this.committed = !0; + } + recordVersion(t) { + let e; + if (t.isFoundDocument()) e = t.version; else { + if (!t.isNoDocument()) throw fail(50498, { + Rt: t.constructor.name + }); + // Represent a deleted doc using SnapshotVersion.min(). + e = SnapshotVersion.min(); + } + const r = this.readVersions.get(t.key.toString()); + if (r) { + if (!e.isEqual(r)) + // This transaction will fail no matter what. + throw new FirestoreError(C, "Document version changed between two reads."); + } else this.readVersions.set(t.key.toString(), e); + } + /** + * Returns the version of this document when it was read in this transaction, + * as a precondition, or no precondition if it was not read. + */ precondition(t) { + const e = this.readVersions.get(t.toString()); + return !this.writtenDocs.has(t.toString()) && e ? e.isEqual(SnapshotVersion.min()) ? Precondition.exists(!1) : Precondition.updateTime(e) : Precondition.none(); + } + /** + * Returns the precondition for a document if the operation is an update. + */ preconditionForUpdate(t) { + const e = this.readVersions.get(t.toString()); + // The first time a document is written, we want to take into account the + // read time and existence + if (!this.writtenDocs.has(t.toString()) && e) { + if (e.isEqual(SnapshotVersion.min())) + // The document doesn't exist, so fail the transaction. + // This has to be validated locally because you can't send a + // precondition that a document does not exist without changing the + // semantics of the backend write to be an insert. This is the reverse + // of what we want, since we want to assert that the document doesn't + // exist but then send the update and have it fail. Since we can't + // express that to the backend, we have to validate locally. + // Note: this can change once we can send separate verify writes in the + // transaction. + throw new FirestoreError(y, "Can't update a document that doesn't exist."); + // Document exists, base precondition on document update time. + return Precondition.updateTime(e); + } + // Document was not read, so we just use the preconditions for a blind + // update. + return Precondition.exists(!0); + } + write(t) { + this.ensureCommitNotCalled(), this.mutations.push(t); + } + ensureCommitNotCalled() {} +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const ht = { + maxAttempts: 5 +}; + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * TransactionRunner encapsulates the logic needed to run and retry transactions + * with backoff. + */ +class __PRIVATE_TransactionRunner { + constructor(t, e, r, n, i) { + this.asyncQueue = t, this.datastore = e, this.options = r, this.updateFunction = n, + this.deferred = i, this.Vt = r.maxAttempts, this.It = new __PRIVATE_ExponentialBackoff(this.asyncQueue, "transaction_retry" /* TimerId.TransactionRetry */); + } + /** Runs the transaction and sets the result on deferred. */ yt() { + this.Vt -= 1, this.gt(); + } + gt() { + this.It.Z((async () => { + const t = new Transaction$1(this.datastore), e = this.wt(t); + e && e.then((e => { + this.asyncQueue.enqueueAndForget((() => t.commit().then((() => { + this.deferred.resolve(e); + })).catch((t => { + this.Ft(t); + })))); + })).catch((t => { + this.Ft(t); + })); + })); + } + wt(t) { + try { + const e = this.updateFunction(t); + return !__PRIVATE_isNullOrUndefined(e) && e.catch && e.then ? e : (this.deferred.reject(Error("Transaction callback must return a Promise")), + null); + } catch (t) { + // Do not retry errors thrown by user provided updateFunction. + return this.deferred.reject(t), null; + } + } + Ft(t) { + this.Vt > 0 && this.vt(t) ? (this.Vt -= 1, this.asyncQueue.enqueueAndForget((() => (this.gt(), + Promise.resolve())))) : this.deferred.reject(t); + } + vt(t) { + if ("FirebaseError" === t?.name) { + // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and + // non-matching document versions with ABORTED. These errors should be retried. + const e = t.code; + return "aborted" === e || "failed-precondition" === e || "already-exists" === e || ! + /** + * Determines whether an error code represents a permanent error when received + * in response to a non-write operation. + * + * See isPermanentWriteError for classifying write errors. + */ + function __PRIVATE_isPermanentError(t) { + switch (t) { + case V: + return fail(64938); + + case I: + case p: + case g: + case b: + case q: + case B: + // Unauthenticated means something went wrong with our token and we need + // to retry with new credentials which will happen automatically. + case D: + return !1; + + case y: + case w: + case F: + case v: + case S: + // Aborted might be retried in some scenarios, but that is dependent on + // the context and should handled individually by the calling code. + // See https://cloud.google.com/apis/design/errors. + case C: + case N: + case O: + case $: + return !0; + + default: + return fail(15467, { + code: t + }); + } + }(e); + } + return !1; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** The Platform's 'document' implementation or null if not available. */ function getDocument() { + // `document` is not always available, e.g. in ReactNative and WebWorkers. + // eslint-disable-next-line no-restricted-globals + return "undefined" != typeof document ? document : null; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents an operation scheduled to be run in the future on an AsyncQueue. + * + * It is created via DelayedOperation.createAndSchedule(). + * + * Supports cancellation (via cancel()) and early execution (via skipDelay()). + * + * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type + * in newer versions of TypeScript defines `finally`, which is not available in + * IE. + */ class DelayedOperation { + constructor(t, e, r, n, i) { + this.asyncQueue = t, this.timerId = e, this.targetTimeMs = r, this.op = n, this.removalCallback = i, + this.deferred = new __PRIVATE_Deferred, this.then = this.deferred.promise.then.bind(this.deferred.promise), + // It's normal for the deferred promise to be canceled (due to cancellation) + // and so we attach a dummy catch callback to avoid + // 'UnhandledPromiseRejectionWarning' log spam. + this.deferred.promise.catch((t => {})); + } + get promise() { + return this.deferred.promise; + } + /** + * Creates and returns a DelayedOperation that has been scheduled to be + * executed on the provided asyncQueue after the provided delayMs. + * + * @param asyncQueue - The queue to schedule the operation on. + * @param id - A Timer ID identifying the type of operation this is. + * @param delayMs - The delay (ms) before the operation should be scheduled. + * @param op - The operation to run. + * @param removalCallback - A callback to be called synchronously once the + * operation is executed or canceled, notifying the AsyncQueue to remove it + * from its delayedOperations list. + * PORTING NOTE: This exists to prevent making removeDelayedOperation() and + * the DelayedOperation class public. + */ static createAndSchedule(t, e, r, n, i) { + const s = Date.now() + r, o = new DelayedOperation(t, e, s, n, i); + return o.start(r), o; + } + /** + * Starts the timer. This is called immediately after construction by + * createAndSchedule(). + */ start(t) { + this.timerHandle = setTimeout((() => this.handleDelayElapsed()), t); + } + /** + * Queues the operation to run immediately (if it hasn't already been run or + * canceled). + */ skipDelay() { + return this.handleDelayElapsed(); + } + /** + * Cancels the operation if it hasn't already been executed or canceled. The + * promise will be rejected. + * + * As long as the operation has not yet been run, calling cancel() provides a + * guarantee that the operation will not be run. + */ cancel(t) { + null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new FirestoreError(I, "Operation cancelled" + (t ? ": " + t : "")))); + } + handleDelayElapsed() { + this.asyncQueue.enqueueAndForget((() => null !== this.timerHandle ? (this.clearTimeout(), + this.op().then((t => this.deferred.resolve(t)))) : Promise.resolve())); + } + clearTimeout() { + null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle), + this.timerHandle = null); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const ft = "AsyncQueue"; + +class __PRIVATE_AsyncQueueImpl { + constructor(t = Promise.resolve()) { + // A list of retryable operations. Retryable operations are run in order and + // retried with backoff. + this.Dt = [], + // Is this AsyncQueue being shut down? Once it is set to true, it will not + // be changed again. + this.bt = !1, + // Operations scheduled to be queued in the future. Operations are + // automatically removed after they are run or canceled. + this.St = [], + // visible for testing + this.Ct = null, + // Flag set while there's an outstanding AsyncQueue operation, used for + // assertion sanity-checks. + this.Nt = !1, + // Enabled during shutdown on Safari to prevent future access to IndexedDB. + this.Ot = !1, + // List of TimerIds to fast-forward delays for. + this.qt = [], + // Backoff timer used to schedule retries for retryable operations + this.It = new __PRIVATE_ExponentialBackoff(this, "async_queue_retry" /* TimerId.AsyncQueueRetry */), + // Visibility handler that triggers an immediate retry of all retryable + // operations. Meant to speed up recovery when we regain file system access + // after page comes into foreground. + this.Bt = () => { + const t = getDocument(); + t && __PRIVATE_logDebug(ft, "Visibility state changed to " + t.visibilityState), + this.It.tt(); + }, this.$t = t; + const e = getDocument(); + e && "function" == typeof e.addEventListener && e.addEventListener("visibilitychange", this.Bt); + } + get isShuttingDown() { + return this.bt; + } + /** + * Adds a new operation to the queue without waiting for it to complete (i.e. + * we ignore the Promise result). + */ enqueueAndForget(t) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.enqueue(t); + } + enqueueAndForgetEvenWhileRestricted(t) { + this.Qt(), + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.kt(t); + } + enterRestrictedMode(t) { + if (!this.bt) { + this.bt = !0, this.Ot = t || !1; + const e = getDocument(); + e && "function" == typeof e.removeEventListener && e.removeEventListener("visibilitychange", this.Bt); + } + } + enqueue(t) { + if (this.Qt(), this.bt) + // Return a Promise which never resolves. + return new Promise((() => {})); + // Create a deferred Promise that we can return to the callee. This + // allows us to return a "hanging Promise" only to the callee and still + // advance the queue even when the operation is not run. + const e = new __PRIVATE_Deferred; + return this.kt((() => this.bt && this.Ot ? Promise.resolve() : (t().then(e.resolve, e.reject), + e.promise))).then((() => e.promise)); + } + enqueueRetryable(t) { + this.enqueueAndForget((() => (this.Dt.push(t), this.Lt()))); + } + /** + * Runs the next operation from the retryable queue. If the operation fails, + * reschedules with backoff. + */ async Lt() { + if (0 !== this.Dt.length) { + try { + await this.Dt[0](), this.Dt.shift(), this.It.reset(); + } catch (t) { + if (! + /** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** Verifies whether `e` is an IndexedDbTransactionError. */ + function __PRIVATE_isIndexedDbTransactionError(t) { + // Use name equality, as instanceof checks on errors don't work with errors + // that wrap other errors. + return "IndexedDbTransactionError" === t.name; + }(t)) throw t; + // Failure will be handled by AsyncQueue + __PRIVATE_logDebug(ft, "Operation failed with retryable error: " + t); + } + this.Dt.length > 0 && + // If there are additional operations, we re-schedule `retryNextOp()`. + // This is necessary to run retryable operations that failed during + // their initial attempt since we don't know whether they are already + // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1` + // needs to be re-run, we will run `op1`, `op1`, `op2` using the + // already enqueued calls to `retryNextOp()`. `op3()` will then run in the + // call scheduled here. + // Since `backoffAndRun()` cancels an existing backoff and schedules a + // new backoff on every call, there is only ever a single additional + // operation in the queue. + this.It.Z((() => this.Lt())); + } + } + kt(t) { + const e = this.$t.then((() => (this.Nt = !0, t().catch((t => { + this.Ct = t, this.Nt = !1; + // Re-throw the error so that this.tail becomes a rejected Promise and + // all further attempts to chain (via .then) will just short-circuit + // and return the rejected Promise. + throw __PRIVATE_logError("INTERNAL UNHANDLED ERROR: ", __PRIVATE_getMessageOrStack(t)), + t; + })).then((t => (this.Nt = !1, t)))))); + return this.$t = e, e; + } + enqueueAfterDelay(t, e, r) { + this.Qt(), + // Fast-forward delays for timerIds that have been overridden. + this.qt.indexOf(t) > -1 && (e = 0); + const n = DelayedOperation.createAndSchedule(this, t, e, r, (t => this.Mt(t))); + return this.St.push(n), n; + } + Qt() { + this.Ct && fail(47125, { + xt: __PRIVATE_getMessageOrStack(this.Ct) + }); + } + verifyOperationInProgress() {} + /** + * Waits until all currently queued tasks are finished executing. Delayed + * operations are not run. + */ async Ut() { + // Operations in the queue prior to draining may have enqueued additional + // operations. Keep draining the queue until the tail is no longer advanced, + // which indicates that no more new operations were enqueued and that all + // operations were executed. + let t; + do { + t = this.$t, await t; + } while (t !== this.$t); + } + /** + * For Tests: Determine if a delayed operation with a particular TimerId + * exists. + */ jt(t) { + for (const e of this.St) if (e.timerId === t) return !0; + return !1; + } + /** + * For Tests: Runs some or all delayed operations early. + * + * @param lastTimerId - Delayed operations up to and including this TimerId + * will be drained. Pass TimerId.All to run all delayed operations. + * @returns a Promise that resolves once all operations have been run. + */ zt(t) { + // Note that draining may generate more delayed ops, so we do that first. + return this.Ut().then((() => { + // Run ops in the same order they'd run if they ran naturally. + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ + this.St.sort(((t, e) => t.targetTimeMs - e.targetTimeMs)); + for (const e of this.St) if (e.skipDelay(), "all" /* TimerId.All */ !== t && e.timerId === t) break; + return this.Ut(); + })); + } + /** + * For Tests: Skip all subsequent delays for a timer id. + */ Wt(t) { + this.qt.push(t); + } + /** Called once a DelayedOperation is run or canceled. */ Mt(t) { + // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small. + const e = this.St.indexOf(t); + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ this.St.splice(e, 1); + } +} + +/** + * Chrome includes Error.message in Error.stack. Other browsers do not. + * This returns expected output of message + stack when available. + * @param error - Error or FirestoreError + */ +function __PRIVATE_getMessageOrStack(t) { + let e = t.message || ""; + return t.stack && (e = t.stack.includes(t.message) ? t.stack : t.message + "\n" + t.stack), + e; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the +// legacy SDK. +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ class Transaction { + /** @hideconstructor */ + constructor(t, e) { + this._firestore = t, this._transaction = e, this._dataReader = __PRIVATE_newUserDataReader(t); + } + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ get(t) { + const e = __PRIVATE_validateReference(t, this._firestore), r = new __PRIVATE_LiteUserDataWriter(this._firestore); + return this._transaction.lookup([ e._key ]).then((t => { + if (!t || 1 !== t.length) return fail(24041); + const n = t[0]; + if (n.isFoundDocument()) return new DocumentSnapshot(this._firestore, r, n.key, n, e.converter); + if (n.isNoDocument()) return new DocumentSnapshot(this._firestore, r, e._key, null, e.converter); + throw fail(18433, { + doc: n + }); + })); + } + set(t, e, r) { + const n = __PRIVATE_validateReference(t, this._firestore), i = __PRIVATE_applyFirestoreDataConverter(n.converter, e, r), s = __PRIVATE_parseSetData(this._dataReader, "Transaction.set", n._key, i, null !== n.converter, r); + return this._transaction.set(n._key, s), this; + } + update(t, e, r, ...n) { + const i = __PRIVATE_validateReference(t, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + let s; + return s = "string" == typeof (e = getModularInstance(e)) || e instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(this._dataReader, "Transaction.update", i._key, e, r, n) : __PRIVATE_parseUpdateData(this._dataReader, "Transaction.update", i._key, e), + this._transaction.update(i._key, s), this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `Transaction` instance. Used for chaining method calls. + */ delete(t) { + const e = __PRIVATE_validateReference(t, this._firestore); + return this._transaction.delete(e._key), this; + } +} + +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ function runTransaction(t, e, r) { + const n = __PRIVATE_getDatastore(t = __PRIVATE_cast(t, Firestore)), i = { + ...ht, + ...r + }; + !function __PRIVATE_validateTransactionOptions(t) { + if (t.maxAttempts < 1) throw new FirestoreError(y, "Max attempts must be at least 1"); + }(i); + const s = new __PRIVATE_Deferred; + return new __PRIVATE_TransactionRunner(function __PRIVATE_newAsyncQueue() { + return new __PRIVATE_AsyncQueueImpl; + }(), n, i, (r => e(new Transaction(t, r))), s).yt(), s.promise; +} + +/** + * Firestore Lite + * + * @remarks Firestore Lite is a small online-only SDK that allows read + * and write access to your Firestore database. All operations connect + * directly to the backend, and `onSnapshot()` APIs are not supported. + * @packageDocumentation + */ !function __PRIVATE_registerFirestore() { + !function __PRIVATE_setSDKVersion(t) { + A = t; + }(`${SDK_VERSION}_lite`), _registerComponent(new Component("firestore/lite", ((t, {instanceIdentifier: e, options: r}) => { + const n = t.getProvider("app").getImmediate(), i = new Firestore(new __PRIVATE_LiteAuthCredentialsProvider(t.getProvider("auth-internal")), new __PRIVATE_LiteAppCheckTokenProvider(n, t.getProvider("app-check-internal")), function __PRIVATE_databaseIdFromApp(t, e) { + if (!Object.prototype.hasOwnProperty.apply(t.options, [ "projectId" ])) throw new FirestoreError(y, '"projectId" not provided in firebase.initializeApp.'); + return new DatabaseId(t.options.projectId, e); + }(n, e), n); + return r && i._setSettings(r), i; + }), "PUBLIC").setMultipleInstances(!0)), + // RUNTIME_ENV and BUILD_TARGET are replaced by real values during the compilation + registerVersion("firestore-lite", P, ""), registerVersion("firestore-lite", P, "cjs2020"); +}(); + +export { AggregateField, AggregateQuerySnapshot, Bytes, CollectionReference, DocumentReference, DocumentSnapshot, FieldPath, FieldValue, Firestore, FirestoreError, GeoPoint, Query, QueryCompositeFilterConstraint, QueryConstraint, QueryDocumentSnapshot, QueryEndAtConstraint, QueryFieldFilterConstraint, QueryLimitConstraint, QueryOrderByConstraint, QuerySnapshot, QueryStartAtConstraint, Timestamp, Transaction, VectorValue, WriteBatch, addDoc, aggregateFieldEqual, aggregateQuerySnapshotEqual, and, arrayRemove, arrayUnion, average, collection, collectionGroup, connectFirestoreEmulator, count, deleteDoc, deleteField, doc, documentId, endAt, endBefore, getAggregate, getCount, getDoc, getDocs, getFirestore, increment, initializeFirestore, limit, limitToLast, or, orderBy, query, queryEqual, refEqual, runTransaction, serverTimestamp, setDoc, setLogLevel, snapshotEqual, startAfter, startAt, sum, terminate, updateDoc, vector, where, writeBatch }; +//# sourceMappingURL=index.cjs.js.map diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/index.cjs.js.map b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.cjs.js.map new file mode 100644 index 0000000..2820a3b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.cjs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.cjs.js","sources":["../../src/auth/user.ts","../../src/core/version.ts","../../src/util/log.ts","../../src/platform/browser/format_json.ts","../../src/util/assert.ts","../../src/util/error.ts","../../src/util/promise.ts","../../src/api/credentials.ts","../../src/core/database_info.ts","../../src/platform/browser/random_bytes.ts","../../src/util/misc.ts","../../src/model/path.ts","../../src/model/document_key.ts","../../src/util/input_validation.ts","../../src/api/long_polling_options.ts","../../src/util/debug_uid.ts","../../src/util/types.ts","../../src/remote/rest_connection.ts","../../src/remote/rpc_error.ts","../../src/platform/browser_lite/fetch_connection.ts","../../src/core/aggregate.ts","../../src/util/obj.ts","../../src/util/base64_decode_error.ts","../../src/util/byte_string.ts","../../src/platform/browser/base64.ts","../../src/model/normalize.ts","../../src/util/json_validation.ts","../../src/lite-api/timestamp.ts","../../src/model/server_timestamps.ts","../../src/model/values.ts","../../src/core/bound.ts","../../src/core/filter.ts","../../src/core/order_by.ts","../../src/core/snapshot_version.ts","../../src/util/sorted_map.ts","../../src/util/sorted_set.ts","../../src/model/field_mask.ts","../../src/model/object_value.ts","../../src/model/document.ts","../../src/core/target.ts","../../src/core/query.ts","../../src/remote/number_serializer.ts","../../src/model/transform_operation.ts","../../src/model/mutation.ts","../../src/remote/serializer.ts","../../src/platform/browser/serializer.ts","../../src/remote/backoff.ts","../../src/remote/datastore.ts","../../src/lite-api/components.ts","../../src/platform/browser_lite/connection.ts","../../src/local/lru_garbage_collector_impl.ts","../../src/lite-api/settings.ts","../../src/local/lru_garbage_collector.ts","../../src/lite-api/database.ts","../../src/lite-api/aggregate_types.ts","../../src/lite-api/reference.ts","../../src/lite-api/bytes.ts","../../src/lite-api/field_path.ts","../../src/lite-api/field_value.ts","../../src/lite-api/geo_point.ts","../../src/lite-api/vector_value.ts","../../src/util/array.ts","../../src/lite-api/user_data_reader.ts","../../src/lite-api/snapshot.ts","../../src/lite-api/query.ts","../../src/lite-api/user_data_writer.ts","../../src/lite-api/reference_impl.ts","../../src/lite-api/aggregate.ts","../../src/lite-api/field_value_impl.ts","../../src/lite-api/write_batch.ts","../../src/core/transaction.ts","../../src/core/transaction_options.ts","../../src/core/transaction_runner.ts","../../src/platform/browser/dom.ts","../../src/util/async_queue.ts","../../src/util/async_queue_impl.ts","../../src/local/simple_db.ts","../../src/lite-api/transaction.ts","../../lite/register.ts","../../lite/index.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Simple wrapper around a nullable UID. Mostly exists to make code more\n * readable.\n */\nexport class User {\n /** A user with a null UID. */\n static readonly UNAUTHENTICATED = new User(null);\n\n // TODO(mikelehen): Look into getting a proper uid-equivalent for\n // non-FirebaseAuth providers.\n static readonly GOOGLE_CREDENTIALS = new User('google-credentials-uid');\n static readonly FIRST_PARTY = new User('first-party-uid');\n static readonly MOCK_USER = new User('mock-user');\n\n constructor(readonly uid: string | null) {}\n\n isAuthenticated(): boolean {\n return this.uid != null;\n }\n\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */\n toKey(): string {\n if (this.isAuthenticated()) {\n return 'uid:' + this.uid;\n } else {\n return 'anonymous-user';\n }\n }\n\n isEqual(otherUser: User): boolean {\n return otherUser.uid === this.uid;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The semver (www.semver.org) version of the SDK. */\nimport { version } from '../../../firebase/package.json';\nexport let SDK_VERSION = version;\nexport function setSDKVersion(version: string): void {\n SDK_VERSION = version;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel, LogLevelString } from '@firebase/logger';\n\nimport { SDK_VERSION } from '../core/version';\nimport { formatJSON } from '../platform/format_json';\n\nexport { LogLevel, LogLevelString };\n\nconst logClient = new Logger('@firebase/firestore');\n\n// Helper methods are needed because variables can't be exported as read/write\nexport function getLogLevel(): LogLevel {\n return logClient.logLevel;\n}\n\n/**\n * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).\n *\n * @param logLevel - The verbosity you set for activity and error logging. Can\n * be any of the following values:\n *\n *
    \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 *\n * @param code generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(\n code: number,\n message: string,\n context?: Record\n): never;\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 *\n * @param id generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(id: number, context?: Record): never;\n\nexport function fail(\n id: number,\n messageOrContext?: string | Record,\n context?: Record\n): never {\n let message = 'Unexpected state';\n if (typeof messageOrContext === 'string') {\n message = messageOrContext;\n } else {\n context = messageOrContext;\n }\n _fail(id, message, context);\n}\n\nfunction _fail(\n id: number,\n failure: string,\n context?: Record\n): never {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n let message = `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ${failure} (ID: ${id.toString(\n 16\n )})`;\n if (context !== undefined) {\n try {\n const stringContext = JSON.stringify(context);\n message += ' CONTEXT: ' + stringContext;\n } catch (e) {\n message += ' CONTEXT: ' + context;\n }\n }\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 *\n * @param id generate a new unique value with `yarn assertion-idgenerate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n assertion: boolean,\n id: number,\n message: string,\n context?: Record\n): asserts assertion;\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 *\n * @param id generate a new unique value with `yarn assertion-id:generate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n assertion: boolean,\n id: number,\n context?: Record\n): asserts assertion;\n\nexport function hardAssert(\n assertion: boolean,\n id: number,\n messageOrContext?: string | Record,\n context?: Record\n): asserts assertion {\n let message = 'Unexpected state';\n if (typeof messageOrContext === 'string') {\n message = messageOrContext;\n } else {\n context = messageOrContext;\n }\n\n if (!assertion) {\n _fail(id, message, context);\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(0xdeb6, 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 { FirebaseApp, _isFirebaseServerApp } from '@firebase/app';\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 0xa539,\n 'Invalid tokenData returned from getToken()',\n { 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 0xa540,\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 0x7c5d,\n 'Invalid tokenData returned from getToken()',\n { 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 0x0807,\n 'Received invalid UID',\n { 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 private serverAppAppCheckToken: string | null = null;\n\n constructor(\n app: FirebaseApp,\n private appCheckProvider: Provider\n ) {\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n }\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n hardAssert(\n this.tokenListener === undefined,\n 0x0db8,\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 if (this.serverAppAppCheckToken) {\n return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n }\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 0xae0e,\n 'Invalid tokenResult returned from getToken()',\n { 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 private serverAppAppCheckToken: string | null = null;\n\n constructor(\n app: FirebaseApp,\n private appCheckProvider: Provider\n ) {\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n appCheckProvider.onInit(appCheck => {\n this.appCheck = appCheck;\n });\n }\n\n getToken(): Promise {\n if (this.serverAppAppCheckToken) {\n return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n }\n\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 0x0d8e,\n 'Invalid tokenResult returned from getToken()',\n { 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","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 readonly isUsingEmulator: 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 { 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\n/** Compare strings in UTF-8 encoded byte order */\nexport function compareUtf8Strings(left: string, right: string): number {\n // Find the first differing character (a.k.a. \"UTF-16 code unit\") in the two strings and,\n // if found, use that character to determine the relative ordering of the two strings as a\n // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by\n // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8\n // and UTF-16 happen to represent Unicode code points.\n //\n // After finding the first pair of differing characters, there are two cases:\n //\n // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or\n // both are surrogates from a surrogate pair (that collectively represent code points greater\n // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the\n // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is\n // sufficient.\n //\n // Case 2: One character is a surrogate and the other is not. In this case the surrogate-\n // containing string is always ordered after the non-surrogate. This is because surrogates are\n // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations\n // and are lexicographically greater than the 1, 2, or 3-byte representations of code points\n // less than or equal to 0xFFFF.\n //\n // An example of why Case 2 is required is comparing the following two Unicode code points:\n //\n // |-----------------------|------------|---------------------|-----------------|\n // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding |\n // |-----------------------|------------|---------------------|-----------------|\n // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD |\n // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 |\n // |-----------------------|------------|---------------------|-----------------|\n //\n // A lexicographical comparison of the UTF-8 encodings of these code points would order\n // \"Replacement Character\" _before_ \"Grinning Face\" because 0xEF is less than 0xF0. However, a\n // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously\n // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out,\n // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate\n // pair with those that do not.\n const length = Math.min(left.length, right.length);\n for (let i = 0; i < length; i++) {\n const leftChar = left.charAt(i);\n const rightChar = right.charAt(i);\n if (leftChar !== rightChar) {\n return isSurrogate(leftChar) === isSurrogate(rightChar)\n ? primitiveComparator(leftChar, rightChar)\n : isSurrogate(leftChar)\n ? 1\n : -1;\n }\n }\n\n // Use the lengths of the strings to determine the overall comparison result since either the\n // strings were equal or one is a prefix of the other.\n return primitiveComparator(left.length, right.length);\n}\n\nconst MIN_SURROGATE = 0xd800;\nconst MAX_SURROGATE = 0xdfff;\n\nexport function isSurrogate(s: string): boolean {\n debugAssert(s.length === 1, `s.length == ${s.length}, but expected 1`);\n const c = s.charCodeAt(0);\n return c >= MIN_SURROGATE && c <= MAX_SURROGATE;\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 { Integer } from '@firebase/webchannel-wrapper/bloom-blob';\n\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { compareUtf8Strings, primitiveComparator } from '../util/misc';\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(0x027d, 'offset out of range', {\n offset,\n range: segments.length\n });\n }\n\n if (length === undefined) {\n length = segments.length - offset;\n } else if (length > segments.length - offset) {\n fail(0x06d2, 'length out of range', {\n length,\n range: segments.length - offset\n });\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 /**\n * Compare 2 paths segment by segment, prioritizing numeric IDs\n * (e.g., \"__id123__\") in numeric ascending order, followed by string\n * segments in lexicographical order.\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 comparison = BasePath.compareSegments(p1.get(i), p2.get(i));\n if (comparison !== 0) {\n return comparison;\n }\n }\n return primitiveComparator(p1.length, p2.length);\n }\n\n private static compareSegments(lhs: string, rhs: string): number {\n const isLhsNumeric = BasePath.isNumericId(lhs);\n const isRhsNumeric = BasePath.isNumericId(rhs);\n\n if (isLhsNumeric && !isRhsNumeric) {\n // Only lhs is numeric\n return -1;\n } else if (!isLhsNumeric && isRhsNumeric) {\n // Only rhs is numeric\n return 1;\n } else if (isLhsNumeric && isRhsNumeric) {\n // both numeric\n return BasePath.extractNumericId(lhs).compare(\n BasePath.extractNumericId(rhs)\n );\n } else {\n // both non-numeric\n return compareUtf8Strings(lhs, rhs);\n }\n }\n\n // Checks if a segment is a numeric ID (starts with \"__id\" and ends with \"__\").\n private static isNumericId(segment: string): boolean {\n return segment.startsWith('__id') && segment.endsWith('__');\n }\n\n private static extractNumericId(segment: string): Integer {\n return Integer.fromString(segment.substring(4, segment.length - 2));\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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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(0x3029, 'Unknown wrong type', { 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 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 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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isCloudWorkstation } from '@firebase/util';\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 const { host } = new URL(url);\n const forwardCredentials = isCloudWorkstation(host);\n return this.performRPCRequest(\n rpcName,\n url,\n headers,\n req,\n forwardCredentials\n ).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 _forwardCredentials: boolean\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 { 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(0xfdaa, '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(0x3c6b, '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(0x999b, '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(0x3019, '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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Token } from '../../api/credentials';\nimport { Stream } from '../../remote/connection';\nimport { RestConnection } from '../../remote/rest_connection';\nimport { mapCodeFromHttpStatus } from '../../remote/rpc_error';\nimport { FirestoreError } from '../../util/error';\nimport { StringMap } from '../../util/types';\n\n/**\n * A Rest-based connection that relies on the native HTTP stack\n * (e.g. `fetch` or a polyfill).\n */\nexport class FetchConnection extends RestConnection {\n openStream(\n rpcName: string,\n token: Token | null\n ): Stream {\n throw new Error('Not supported by FetchConnection');\n }\n\n protected async performRPCRequest(\n rpcName: string,\n url: string,\n headers: StringMap,\n body: Req,\n forwardCredentials: boolean\n ): Promise {\n const requestJson = JSON.stringify(body);\n let response: Response;\n\n try {\n const fetchArgs: RequestInit = {\n method: 'POST',\n headers,\n body: requestJson\n };\n if (forwardCredentials) {\n fetchArgs.credentials = 'include';\n }\n response = await fetch(url, fetchArgs);\n } catch (e) {\n const err = e as { status: number | undefined; statusText: string };\n throw new FirestoreError(\n mapCodeFromHttpStatus(err.status),\n 'Request failed with error: ' + err.statusText\n );\n }\n\n if (!response.ok) {\n let errorResponse = await response.json();\n if (Array.isArray(errorResponse)) {\n errorResponse = errorResponse[0];\n }\n const errorMessage = errorResponse?.error?.message;\n throw new FirestoreError(\n mapCodeFromHttpStatus(response.status),\n `Request failed with error: ${errorMessage ?? response.statusText}`\n );\n }\n\n return response.json();\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 { FieldPath } from '../model/path';\n\n/**\n * Union type representing the aggregate type to be performed.\n */\nexport type AggregateType = 'count' | 'avg' | 'sum';\n\n/**\n * Represents an Aggregate to be performed over a query result set.\n */\nexport interface Aggregate {\n readonly fieldPath?: FieldPath;\n readonly alias: string;\n readonly aggregateType: AggregateType;\n}\n\n/**\n * Concrete implementation of the Aggregate type.\n */\nexport class AggregateImpl implements Aggregate {\n constructor(\n readonly alias: string,\n readonly aggregateType: AggregateType,\n readonly fieldPath?: 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 './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 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, 0x986a, '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, 0xb5de, 'invalid timestamp', {\n timestamp: date\n });\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 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isPlainObject } from '../util/input_validation';\n\nimport { Code, FirestoreError } from './error';\n\n/**\n * A list of data types Firestore objects may serialize in their toJSON implemenetations.\n * @private\n * @internal\n */\nexport type JsonTypeDesc =\n | 'object'\n | 'string'\n | 'number'\n | 'boolean'\n | 'null'\n | 'undefined';\n\n/**\n * An association of JsonTypeDesc values to their native types.\n * @private\n * @internal\n */\nexport type TSType = T extends 'object'\n ? object\n : T extends 'string'\n ? string\n : T extends 'number'\n ? number\n : T extends 'boolean'\n ? boolean\n : T extends 'null'\n ? null\n : T extends 'undefined'\n ? undefined\n : never;\n\n/**\n * The representation of a JSON object property name and its type value.\n * @private\n * @internal\n */\nexport interface Property {\n value?: TSType;\n typeString: JsonTypeDesc;\n}\n\n/**\n * A type Firestore data types may use to define the fields used in their JSON serialization.\n * @private\n * @internal\n */\nexport interface JsonSchema {\n [key: string]: Property;\n}\n\n/**\n * Associates the JSON property type to the native type and sets them to be Required.\n * @private\n * @internal\n */\nexport type Json = {\n [K in keyof T]: Required['value'];\n};\n\n/**\n * Helper function to define a JSON schema {@link Property}.\n * @private\n * @internal\n */\nexport function property(\n typeString: T,\n optionalValue?: TSType\n): Property {\n const result: Property = {\n typeString\n };\n if (optionalValue) {\n result.value = optionalValue;\n }\n return result;\n}\n\n/**\n * Validates the JSON object based on the provided schema, and narrows the type to the provided\n * JSON schema.\n * @private\n * @internal\n *\n * @param json A JSON object to validate.\n * @param scheme a {@link JsonSchema} that defines the properties to validate.\n * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise.\n */\nexport function validateJSON(\n json: object,\n schema: S\n): json is Json {\n if (!isPlainObject(json)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'JSON must be an object');\n }\n let error: string | undefined = undefined;\n for (const key in schema) {\n if (schema[key]) {\n const typeString = schema[key].typeString;\n const value: { value: unknown } | undefined =\n 'value' in schema[key] ? { value: schema[key].value } : undefined;\n if (!(key in json)) {\n error = `JSON missing required field: '${key}'`;\n break;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const fieldValue = (json as any)[key];\n if (typeString && typeof fieldValue !== typeString) {\n error = `JSON field '${key}' must be a ${typeString}.`;\n break;\n } else if (value !== undefined && fieldValue !== value.value) {\n error = `Expected '${key}' field to equal '${value.value}'`;\n break;\n }\n }\n }\n if (error) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, error);\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 { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\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 static _jsonSchemaVersion: string = 'firestore/timestamp/1.0';\n static _jsonSchema = {\n type: property('string', Timestamp._jsonSchemaVersion),\n seconds: property('number'),\n nanoseconds: property('number')\n };\n\n /**\n * Returns a JSON-serializable representation of this `Timestamp`.\n */\n toJSON(): { seconds: number; nanoseconds: number; type: string } {\n return {\n type: Timestamp._jsonSchemaVersion,\n seconds: this.seconds,\n nanoseconds: this.nanoseconds\n };\n }\n\n /**\n * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}.\n */\n static fromJSON(json: object): Timestamp {\n if (validateJSON(json, Timestamp._jsonSchema)) {\n return new Timestamp(json.seconds, json.nanoseconds);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Timestamp from JSON.'\n );\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 {\n arrayEquals,\n compareUtf8Strings,\n primitiveComparator\n} 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(0x6e87, 'Invalid value type', { 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(0xcbf8, 'Unexpected value type', { 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 compareUtf8Strings(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(0x5ae0, '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 = compareUtf8Strings(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(0xee4d, 'Invalid value type', { 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(0x34ae, 'Invalid value type', { 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(0x8c66, 'Invalid value type', { 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(0xf207, 'Invalid value type', { 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 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 { 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 other.nullValue === undefined &&\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(0xb8a2, 'Unknown FieldFilter operator', {\n operator: this.op\n });\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(0x4bef, '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 (\n other !== null &&\n other.nullValue === undefined &&\n !arrayValueContains(this.value.arrayValue!, other)\n );\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 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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 './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(0xaad2, 'Red node has red child', {\n key: this.key,\n value: this.value\n });\n }\n if (this.right.isRed()) {\n throw fail(0x3721, 'Right child of (`key`, `value`) is red', {\n key: this.key,\n value: this.value\n });\n }\n const blackDepth = (this.left as LLRBNode).check();\n if (blackDepth !== (this.right as LLRBNode).check()) {\n throw fail(0x6d2d, '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(0xe1a6, 'LLRBEmptyNode has no key.');\n }\n get value(): never {\n throw fail(0x3f0d, 'LLRBEmptyNode has no value.');\n }\n get color(): never {\n throw fail(0x4157, 'LLRBEmptyNode has no color.');\n }\n get left(): never {\n throw fail(0x741e, 'LLRBEmptyNode has no left child.');\n }\n get right(): never {\n throw fail(0x901e, '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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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(\n 0xa786,\n \"Trying to compare documents on fields that don't exist\"\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(0x4d4e, 'Unknown direction', { direction: orderBy.dir });\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 { 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 0x7f90,\n 'server transform result count should match field transform count',\n {\n serverTransformResultCount: serverTransformResults.length,\n fieldTransformCount: fieldTransforms.length\n }\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 { 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\n/**\n * Returns a Timestamp typed object given protobuf timestamp value.\n */\nexport function 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 0xe30b,\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 0x3f41,\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, 0xc050, \"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 0x27ce,\n 'Tried to deserialize invalid key',\n { 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 0x71a3,\n 'tried to deserialize invalid key',\n { 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 0xaa33,\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 0x0f36,\n 'Tried to deserialize a missing document from a found document.'\n );\n hardAssert(\n !!result.readTime,\n 0x5995,\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(0x1c42, 'invalid batch get response', { 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(0x2d51, 'Unknown change type', { 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(0x9991, '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(0x40d7, 'Unknown mutation type', {\n mutationType: mutation.type\n });\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(0x05b7, 'unknown mutation proto', { 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(0x6b69, '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 0x3811,\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(0x51c2, 'Unknown transform', {\n transform: fieldTransform.transform\n });\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 0x40f6,\n 'Unknown server value transform proto',\n { 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(0x40c8, 'Unknown transform proto', { 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 0x07ae,\n 'DocumentsTarget contained other than 1 document',\n {\n count\n }\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 0xfe26,\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(0x713b, '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(0x7591, 'Unknown filter', { 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(0xe2fe, 'Unspecified operator');\n default:\n return fail(0xc54a, '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(0x0402, '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(0xd65d, 'Unrecognized filter type', { 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(0xef81, 'Unspecified filter');\n default:\n return fail(0xed36, '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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 } 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, 0xd7c2, 'Missing entity in write response for `key`', {\n key\n });\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 0xfcd7,\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 settings.isUsingEmulator\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';\n\nimport { FetchConnection } from './fetch_connection';\n\nexport { newConnectivityMonitor } from '../browser/connection';\n\n/** Initializes the HTTP connection for the REST API. */\nexport function newConnection(databaseInfo: DatabaseInfo): Connection {\n return new FetchConnection(databaseInfo);\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\nimport { EmulatorMockTokenOptions } from '@firebase/util';\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 emulatorOptions?: { mockUserToken?: EmulatorMockTokenOptions | string };\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 readonly isUsingEmulator: boolean;\n\n // Can be a google-auth-library or gapi client.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n credentials?: any;\n\n constructor(settings: PrivateSettings) {\n if (settings.host === undefined) {\n if (settings.ssl !== undefined) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't provide ssl option if host option is not set\"\n );\n }\n this.host = DEFAULT_HOST;\n this.ssl = DEFAULT_SSL;\n } else {\n this.host = settings.host;\n this.ssl = settings.ssl ?? DEFAULT_SSL;\n }\n this.isUsingEmulator = settings.emulatorOptions !== undefined;\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 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 deepEqual,\n EmulatorMockTokenOptions,\n getDefaultEmulatorHostnameAndPort,\n isCloudWorkstation,\n pingServer,\n updateEmulatorBanner\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 private _emulatorOptions: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {};\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 this._emulatorOptions = settings.emulatorOptions || {};\n\n if (settings.credentials !== undefined) {\n this._authCredentials = makeAuthCredentialsProvider(settings.credentials);\n }\n }\n\n _getSettings(): FirestoreSettingsImpl {\n return this._settings;\n }\n\n _getEmulatorOptions(): { mockUserToken?: EmulatorMockTokenOptions | string } {\n return this._emulatorOptions;\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 useSsl = isCloudWorkstation(host);\n const settings = firestore._getSettings();\n const existingConfig = {\n ...settings,\n emulatorOptions: firestore._getEmulatorOptions()\n };\n const newHostSetting = `${host}:${port}`;\n if (useSsl) {\n void pingServer(`https://${newHostSetting}`);\n updateEmulatorBanner('Firestore', true);\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 const newConfig = {\n ...settings,\n host: newHostSetting,\n ssl: useSsl,\n emulatorOptions: options\n };\n // No-op if the new configuration matches the current configuration. This supports SSR\n // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice.\n if (deepEqual(newConfig, existingConfig)) {\n return;\n }\n\n firestore._setSettings(newConfig);\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 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 { AggregateType } from '../core/aggregate';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\n\nimport { average, count, sum } from './aggregate';\nimport { DocumentData, Query } from './reference';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\nexport { AggregateType };\n\n/**\n * Represents an aggregation that can be performed by Firestore.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport class AggregateField {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateField';\n\n /** Indicates the aggregation operation of this AggregateField. */\n readonly aggregateType: AggregateType;\n\n /**\n * Create a new AggregateField\n * @param aggregateType Specifies the type of aggregation operation to perform.\n * @param _internalFieldPath Optionally specifies the field that is aggregated.\n * @internal\n */\n constructor(\n aggregateType: AggregateType = 'count',\n readonly _internalFieldPath?: InternalFieldPath\n ) {\n this.aggregateType = aggregateType;\n }\n}\n\n/**\n * The union of all `AggregateField` types that are supported by Firestore.\n */\nexport type AggregateFieldType =\n | ReturnType\n | ReturnType\n | ReturnType;\n\n/**\n * Specifies a set of aggregations and their aliases.\n */\nexport interface AggregateSpec {\n [field: string]: AggregateFieldType;\n}\n\n/**\n * A type whose keys are taken from an `AggregateSpec`, and whose values are the\n * result of the aggregation performed by the corresponding `AggregateField`\n * from the input `AggregateSpec`.\n */\nexport type AggregateSpecData = {\n [P in keyof T]: T[P] extends AggregateField ? U : never;\n};\n\n/**\n * The results of executing an aggregation query.\n */\nexport class AggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateQuerySnapshot';\n\n /**\n * The underlying query over which the aggregations recorded in this\n * `AggregateQuerySnapshot` were performed.\n */\n readonly query: Query;\n\n /** @hideconstructor */\n constructor(\n query: Query,\n private readonly _userDataWriter: AbstractUserDataWriter,\n private readonly _data: ApiClientObjectMap\n ) {\n this.query = query;\n }\n\n /**\n * Returns the results of the aggregations performed over the underlying\n * query.\n *\n * The keys of the returned object will be the same as those of the\n * `AggregateSpec` object specified to the aggregation method, and the values\n * will be the corresponding aggregation result.\n *\n * @returns The results of the aggregations performed over the underlying\n * query.\n */\n data(): AggregateSpecData {\n return this._userDataWriter.convertObjectMap(\n this._data\n ) as AggregateSpecData;\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 {\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';\n// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_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 static _jsonSchemaVersion: string = 'firestore/documentReference/1.0';\n static _jsonSchema = {\n type: property('string', DocumentReference._jsonSchemaVersion),\n referencePath: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `DocumentReference` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: DocumentReference._jsonSchemaVersion,\n referencePath: this._key.toString()\n };\n }\n\n /**\n * Builds a `DocumentReference` instance from a JSON object created by\n * {@link DocumentReference.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json a JSON object represention of a `DocumentReference` instance\n * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(firestore: Firestore, json: object): DocumentReference;\n /**\n * Builds a `DocumentReference` instance from a JSON object created by\n * {@link DocumentReference.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json a JSON object represention of a `DocumentReference` instance\n * @param converter - Converts objects to and from Firestore.\n * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON<\n NewAppModelType = DocumentData,\n NewDbModelType extends DocumentData = DocumentData\n >(\n firestore: Firestore,\n json: object,\n converter: FirestoreDataConverter\n ): DocumentReference;\n static fromJSON<\n NewAppModelType = DocumentData,\n NewDbModelType extends DocumentData = DocumentData\n >(\n firestore: Firestore,\n json: object,\n converter?: FirestoreDataConverter\n ): DocumentReference {\n if (validateJSON(json, DocumentReference._jsonSchema)) {\n return new DocumentReference(\n firestore,\n converter ? converter : null,\n new DocumentKey(ResourcePath.fromString(json.referencePath))\n );\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Bytes from JSON.'\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 { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\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 static _jsonSchemaVersion: string = 'firestore/bytes/1.0';\n static _jsonSchema = {\n type: property('string', Bytes._jsonSchemaVersion),\n bytes: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `Bytes` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: Bytes._jsonSchemaVersion,\n bytes: this.toBase64()\n };\n }\n\n /**\n * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}.\n *\n * @param json a JSON object represention of a `Bytes` instance\n * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): Bytes {\n if (validateJSON(json, Bytes._jsonSchema)) {\n return Bytes.fromBase64String(json.bytes);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Bytes from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n 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';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\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 /**\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 static _jsonSchemaVersion: string = 'firestore/geoPoint/1.0';\n static _jsonSchema = {\n type: property('string', GeoPoint._jsonSchemaVersion),\n latitude: property('number'),\n longitude: property('number')\n };\n\n /**\n * Returns a JSON-serializable representation of this `GeoPoint` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): { latitude: number; longitude: number; type: string } {\n return {\n latitude: this._lat,\n longitude: this._long,\n type: GeoPoint._jsonSchemaVersion\n };\n }\n\n /**\n * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}.\n *\n * @param json a JSON object represention of a `GeoPoint` instance\n * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): GeoPoint {\n if (validateJSON(json, GeoPoint._jsonSchema)) {\n return new GeoPoint(json.latitude, json.longitude);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating GeoPoint from JSON.'\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';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\n\n/**\n * Represents a vector type in Firestore documents.\n * Create an instance with {@link 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` values have the same raw number arrays, returns `false` otherwise.\n */\n isEqual(other: VectorValue): boolean {\n return isPrimitiveArrayEqual(this._values, other._values);\n }\n\n static _jsonSchemaVersion: string = 'firestore/vectorValue/1.0';\n static _jsonSchema = {\n type: property('string', VectorValue._jsonSchemaVersion),\n vectorValues: property('object')\n };\n\n /**\n * Returns a JSON-serializable representation of this `VectorValue` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: VectorValue._jsonSchemaVersion,\n vectorValues: this._values\n };\n }\n\n /**\n * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}.\n *\n * @param json a JSON object represention of a `VectorValue` instance.\n * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): VectorValue {\n if (validateJSON(json, VectorValue._jsonSchema)) {\n if (\n Array.isArray(json.vectorValues) &&\n json.vectorValues.every(element => typeof element === 'number')\n ) {\n return new VectorValue(json.vectorValues);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Expected 'vectorValues' field to be a number array\"\n );\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Timestamp from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Returns 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(0x9c4b, 'Unexpected case for UserDataSource', {\n dataSource\n });\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\nexport function 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(0xf2a2, 'Invalid value type', {\n value\n });\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 0x25d8,\n 'ReferenceValue is not valid',\n { name }\n );\n const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3));\n const key = new DocumentKey(resourcePath.popFirst(5));\n\n if (!databaseId.isEqual(expectedDatabaseId)) {\n // TODO(b/64130202): Somehow support foreign references.\n logError(\n `Document ${key} contains a document ` +\n `reference within a different database (` +\n `${databaseId.projectId}/${databaseId.database}) which is not ` +\n `supported. It will be treated as a reference in the current ` +\n `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` +\n `instead.`\n );\n }\n return key;\n }\n\n protected abstract convertReference(name: string): unknown;\n\n protected abstract convertBytes(bytes: ByteString): unknown;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData as PublicDocumentData,\n SetOptions as PublicSetOptions\n} from '@firebase/firestore-types';\nimport { getModularInstance } from '@firebase/util';\n\nimport { LimitType } from '../core/query';\nimport { DeleteMutation, Precondition } from '../model/mutation';\nimport {\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc,\n invokeRunQueryRpc\n} from '../remote/datastore';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { cast } from '../util/input_validation';\n\nimport { Bytes } from './bytes';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { validateHasExplicitOrderByForLimitToLast } from './query';\nimport {\n CollectionReference,\n doc,\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot\n} from './snapshot';\nimport {\n newUserDataReader,\n ParsedUpdateData,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converts custom model object of type T into `DocumentData` by applying the\n * converter if it exists.\n *\n * This function is used when converting user objects to `DocumentData`\n * because we want to provide the user with a more specific error message if\n * their `set()` or fails due to invalid data originating from a `toFirestore()`\n * call.\n */\nexport function applyFirestoreDataConverter(\n converter: UntypedFirestoreDataConverter | null,\n value: WithFieldValue | PartialWithFieldValue,\n options?: PublicSetOptions\n): PublicDocumentData {\n let convertedValue;\n if (converter) {\n if (options && (options.merge || options.mergeFields)) {\n // Cast to `any` in order to satisfy the union type constraint on\n // toFirestore().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n convertedValue = (converter as any).toFirestore(value, options);\n } else {\n convertedValue = converter.toFirestore(value as WithFieldValue);\n }\n } else {\n convertedValue = value as PublicDocumentData;\n }\n return convertedValue;\n}\n\nexport class LiteUserDataWriter extends AbstractUserDataWriter {\n constructor(protected firestore: Firestore) {\n super();\n }\n\n protected convertBytes(bytes: ByteString): Bytes {\n return new Bytes(bytes);\n }\n\n protected convertReference(name: string): DocumentReference {\n const key = this.convertDocumentKey(name, this.firestore._databaseId);\n return new DocumentReference(this.firestore, /* converter= */ null, key);\n }\n}\n\n/**\n * Reads the document referred to by the specified document reference.\n *\n * All documents are directly fetched from the server, even if the document was\n * previously read or modified. Recent modifications are only reflected in the\n * retrieved `DocumentSnapshot` if they have already been applied by the\n * backend. If the client is offline, the read fails. If you like to use\n * caching or see local modifications, please use the full Firestore SDK.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the current\n * document contents.\n */\nexport function getDoc(\n reference: DocumentReference\n): Promise> {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n const userDataWriter = new LiteUserDataWriter(reference.firestore);\n\n return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then(\n result => {\n hardAssert(\n result.length === 1,\n 0x3d02,\n 'Expected a single document result'\n );\n const document = result[0];\n return new DocumentSnapshot(\n reference.firestore,\n userDataWriter,\n reference._key,\n document.isFoundDocument() ? document : null,\n reference.converter\n );\n }\n );\n}\n\n/**\n * Executes the query and returns the results as a {@link QuerySnapshot}.\n *\n * All queries are executed directly by the server, even if the query was\n * previously executed. Recent modifications are only reflected in the retrieved\n * results if they have already been applied by the backend. If the client is\n * offline, the operation fails. To see previously cached result and local\n * modifications, use the full Firestore SDK.\n *\n * @param query - The `Query` to execute.\n * @returns A Promise that will be resolved with the results of the query.\n */\nexport function getDocs(\n query: Query\n): Promise> {\n query = cast>(query, Query);\n validateHasExplicitOrderByForLimitToLast(query._query);\n\n const datastore = getDatastore(query.firestore);\n const userDataWriter = new LiteUserDataWriter(query.firestore);\n return invokeRunQueryRpc(datastore, query._query).then(result => {\n const docs = result.map(\n doc =>\n new QueryDocumentSnapshot(\n query.firestore,\n userDataWriter,\n doc.key,\n doc,\n query.converter\n )\n );\n\n if (query._query.limitType === LimitType.Last) {\n // Limit to last queries reverse the orderBy constraint that was\n // specified by the user. As such, we need to reverse the order of the\n // results to return the documents in the expected order.\n docs.reverse();\n }\n\n return new QuerySnapshot(query, docs);\n });\n}\n\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\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 * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\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 convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data,\n options\n );\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'setDoc',\n reference._key,\n convertedValue,\n reference.converter !== null,\n options\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference`. The update will fail if applied to a document that does\n * not exist.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\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 * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\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 dataReader = newUserDataReader(reference.firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed: ParsedUpdateData;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData\n );\n }\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.exists(true))\n ]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * The deletion will only be reflected in document reads that occur after the\n * returned promise resolves. If the client is offline, the\n * delete fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to delete.\n * @returns A `Promise` resolved once the document has been successfully\n * deleted from the backend.\n */\nexport function deleteDoc(\n reference: DocumentReference\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n new DeleteMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend.\n */\nexport function addDoc(\n reference: CollectionReference,\n data: WithFieldValue\n): Promise> {\n reference = cast>(\n reference,\n CollectionReference\n );\n const docRef = doc(reference);\n\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data as PartialWithFieldValue\n );\n\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'addDoc',\n docRef._key,\n convertedValue,\n docRef.converter !== null,\n {}\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(docRef._key, Precondition.exists(false))\n ]).then(() => docRef);\n}\n","/**\n * @license\n * Copyright 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 { deepEqual } from '@firebase/util';\n\nimport { AggregateImpl } from '../core/aggregate';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { invokeRunAggregationQueryRpc } from '../remote/datastore';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport {\n AggregateField,\n AggregateQuerySnapshot,\n AggregateSpec\n} from './aggregate_types';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { DocumentData, Query, queryEqual } from './reference';\nimport { LiteUserDataWriter } from './reference_impl';\nimport { fieldPathFromArgument } from './user_data_reader';\n\n/**\n * Calculates the number of documents in the result set of the given query\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can\n * count the documents in cases where the result set is prohibitively large to\n * download entirely (thousands of documents).\n *\n * @param query The query whose result set size is calculated.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */\nexport function getCount(\n query: Query\n): Promise<\n AggregateQuerySnapshot<\n { count: AggregateField },\n AppModelType,\n DbModelType\n >\n> {\n const countQuerySpec: { count: AggregateField } = {\n count: count()\n };\n\n return getAggregate(query, countQuerySpec);\n}\n\n/**\n * Calculates the specified aggregations over the documents in the result\n * set of the given query without actually downloading the documents.\n *\n * Using this function to perform aggregations is efficient because only the\n * final aggregation values, not the documents' data, are downloaded. This\n * function can perform aggregations of the documents in cases where the result\n * set is prohibitively large to download entirely (thousands of documents).\n *\n * @param query The query whose result set is aggregated over.\n * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates\n * to perform over the result set. The AggregateSpec specifies aliases for each\n * aggregate, which can be used to retrieve the aggregate result.\n * @example\n * ```typescript\n * const aggregateSnapshot = await getAggregate(query, {\n * countOfDocs: count(),\n * totalHours: sum('hours'),\n * averageScore: average('score')\n * });\n *\n * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;\n * const totalHours: number = aggregateSnapshot.data().totalHours;\n * const averageScore: number | null = aggregateSnapshot.data().averageScore;\n * ```\n */\nexport function getAggregate<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n aggregateSpec: AggregateSpecType\n): Promise<\n AggregateQuerySnapshot\n> {\n const firestore = cast(query.firestore, Firestore);\n const datastore = getDatastore(firestore);\n\n const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n\n // Run the aggregation and convert the results\n return invokeRunAggregationQueryRpc(\n datastore,\n query._query,\n internalAggregates\n ).then(aggregateResult =>\n convertToAggregateQuerySnapshot(firestore, query, aggregateResult)\n );\n}\n\nfunction convertToAggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n query: Query,\n aggregateResult: ApiClientObjectMap\n): AggregateQuerySnapshot {\n const userDataWriter = new LiteUserDataWriter(firestore);\n const querySnapshot = new AggregateQuerySnapshot<\n AggregateSpecType,\n AppModelType,\n DbModelType\n >(query, userDataWriter, aggregateResult);\n return querySnapshot;\n}\n\n/**\n * Create an AggregateField object that can be used to compute the sum of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to sum across the result set.\n */\nexport function sum(field: string | FieldPath): AggregateField {\n return new AggregateField('sum', fieldPathFromArgument('sum', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the average of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to average across the result set.\n */\nexport function average(\n field: string | FieldPath\n): AggregateField {\n return new AggregateField('avg', fieldPathFromArgument('average', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the count of\n * documents in the result set of a query.\n */\nexport function count(): AggregateField {\n return new AggregateField('count');\n}\n\n/**\n * Compares two 'AggregateField` instances for equality.\n *\n * @param left Compare this AggregateField to the `right`.\n * @param right Compare this AggregateField to the `left`.\n */\nexport function aggregateFieldEqual(\n left: AggregateField,\n right: AggregateField\n): boolean {\n return (\n left instanceof AggregateField &&\n right instanceof AggregateField &&\n left.aggregateType === right.aggregateType &&\n left._internalFieldPath?.canonicalString() ===\n right._internalFieldPath?.canonicalString()\n );\n}\n\n/**\n * Compares two `AggregateQuerySnapshot` instances for equality.\n *\n * Two `AggregateQuerySnapshot` instances are considered \"equal\" if they have\n * underlying queries that compare equal, and the same data.\n *\n * @param left - The first `AggregateQuerySnapshot` to compare.\n * @param right - The second `AggregateQuerySnapshot` to compare.\n *\n * @returns `true` if the objects are \"equal\", as defined above, or `false`\n * otherwise.\n */\nexport function aggregateQuerySnapshotEqual<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n left: AggregateQuerySnapshot,\n right: AggregateQuerySnapshot\n): boolean {\n return (\n queryEqual(left.query, right.query) && deepEqual(left.data(), right.data())\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldValue } from './field_value';\nimport {\n ArrayRemoveFieldValueImpl,\n ArrayUnionFieldValueImpl,\n DeleteFieldValueImpl,\n NumericIncrementFieldValueImpl,\n ServerTimestampFieldValueImpl\n} from './user_data_reader';\nimport { VectorValue } from './vector_value';\n\n/**\n * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or\n * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.\n */\nexport function deleteField(): FieldValue {\n return new DeleteFieldValueImpl('deleteField');\n}\n\n/**\n * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to\n * include a server-generated timestamp in the written data.\n */\nexport function serverTimestamp(): FieldValue {\n return new ServerTimestampFieldValueImpl('serverTimestamp');\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array\n * value that already exists on the server. Each specified element that doesn't\n * already exist in the array will be added to the end. If the field being\n * modified is not already an array it will be overwritten with an array\n * containing exactly the specified elements.\n *\n * @param elements - The elements to union into the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`.\n */\nexport function arrayUnion(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayUnionFieldValueImpl('arrayUnion', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link (setDoc:1)} or {@link\n * updateDoc:1} that tells the server to remove the given elements from any\n * array value that already exists on the server. All instances of each element\n * specified will be removed from the array. If the field being modified is not\n * already an array it will be overwritten with an empty array.\n *\n * @param elements - The elements to remove from the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function arrayRemove(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayRemoveFieldValueImpl('arrayRemove', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by\n * the given value.\n *\n * If either the operand or the current field value uses floating point\n * precision, all arithmetic follows IEEE 754 semantics. If both values are\n * integers, values outside of JavaScript's safe number range\n * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to\n * precision loss. Furthermore, once processed by the Firestore backend, all\n * integer operations are capped between -2^63 and 2^63-1.\n *\n * If the current field value is not of type `number`, or if the field does not\n * yet exist, the transformation sets the field to the given value.\n *\n * @param n - The value to increment by.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function increment(n: number): FieldValue {\n return new NumericIncrementFieldValueImpl('increment', n);\n}\n\n/**\n * Creates a new `VectorValue` constructed with a copy of the given array of numbers.\n *\n * @param values - Create a `VectorValue` instance with a copy of this array of numbers.\n *\n * @returns A new `VectorValue` constructed with a copy of the given array of numbers.\n */\nexport function vector(values?: number[]): VectorValue {\n return new VectorValue(values);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Compat, getModularInstance } from '@firebase/util';\n\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { invokeCommitRpc } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport { applyFirestoreDataConverter } from './reference_impl';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\n\n/**\n * A write batch, used to perform multiple writes as a single atomic unit.\n *\n * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It\n * provides methods for adding writes to the write batch. None of the writes\n * will be committed (or visible locally) until {@link WriteBatch.commit} is\n * called.\n */\nexport class WriteBatch {\n // This is the lite version of the WriteBatch API used in the legacy SDK. The\n // class is a close copy but takes different input types.\n\n private readonly _dataReader: UserDataReader;\n private _mutations = [] as Mutation[];\n private _committed = false;\n\n /** @hideconstructor */\n constructor(\n private readonly _firestore: Firestore,\n private readonly _commitHandler: (m: Mutation[]) => Promise\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): WriteBatch;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): WriteBatch;\n set(\n documentRef: DocumentReference,\n data: WithFieldValue | PartialWithFieldValue,\n options?: SetOptions\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n data,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'WriteBatch.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._mutations.push(parsed.toMutation(ref._key, Precondition.none()));\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): WriteBatch;\n /**\n * Updates fields in the document referred to by this {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be update by providing dot-separated field path strings\n * or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._mutations.push(\n parsed.toMutation(ref._key, Precondition.exists(true))\n );\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n this._mutations = this._mutations.concat(\n new DeleteMutation(ref._key, Precondition.none())\n );\n return this;\n }\n\n /**\n * Commits all of the writes in this write batch as a single atomic unit.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `Promise` resolved once all of the writes in the batch have been\n * successfully written to the backend as an atomic unit (note that it won't\n * resolve while you're offline).\n */\n commit(): Promise {\n this._verifyNotCommitted();\n this._committed = true;\n if (this._mutations.length > 0) {\n return this._commitHandler(this._mutations);\n }\n\n return Promise.resolve();\n }\n\n private _verifyNotCommitted(): void {\n if (this._committed) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A write batch can no longer be used after commit() ' +\n 'has been called.'\n );\n }\n }\n}\n\nexport function validateReference<\n AppModelType,\n DbModelType extends DocumentData\n>(\n documentRef:\n | DocumentReference\n | Compat>,\n firestore: Firestore\n): DocumentReference {\n documentRef = getModularInstance(documentRef);\n\n if (documentRef.firestore !== firestore) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Provided document reference is from a different Firestore instance.'\n );\n } else {\n return documentRef as DocumentReference;\n }\n}\n\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single WriteBatch\n * is 500.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `WriteBatch` that can be used to atomically execute multiple\n * writes.\n */\nexport function writeBatch(firestore: Firestore): WriteBatch {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n return new WriteBatch(firestore, writes =>\n invokeCommitRpc(datastore, writes)\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParsedSetData, ParsedUpdateData } from '../lite-api/user_data_reader';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n DeleteMutation,\n Mutation,\n Precondition,\n VerifyMutation\n} from '../model/mutation';\nimport {\n Datastore,\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc\n} from '../remote/datastore';\nimport { fail, debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { SnapshotVersion } from './snapshot_version';\n\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nexport class Transaction {\n // The version of each document that was read during this transaction.\n private readVersions = new Map();\n private mutations: Mutation[] = [];\n private committed = false;\n\n /**\n * A deferred usage error that occurred previously in this transaction that\n * will cause the transaction to fail once it actually commits.\n */\n private lastTransactionError: FirestoreError | null = null;\n\n /**\n * Set of documents that have been written in the transaction.\n *\n * When there's more than one write to the same key in a transaction, any\n * writes after the first are handled differently.\n */\n private writtenDocs: Set = new Set();\n\n constructor(private datastore: Datastore) {}\n\n async lookup(keys: DocumentKey[]): Promise {\n this.ensureCommitNotCalled();\n\n if (this.mutations.length > 0) {\n this.lastTransactionError = new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Firestore transactions require all reads to be executed before all writes.'\n );\n throw this.lastTransactionError;\n }\n const docs = await invokeBatchGetDocumentsRpc(this.datastore, keys);\n docs.forEach(doc => this.recordVersion(doc));\n return docs;\n }\n\n set(key: DocumentKey, data: ParsedSetData): void {\n this.write(data.toMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n update(key: DocumentKey, data: ParsedUpdateData): void {\n try {\n this.write(data.toMutation(key, this.preconditionForUpdate(key)));\n } catch (e) {\n this.lastTransactionError = e as FirestoreError | null;\n }\n this.writtenDocs.add(key.toString());\n }\n\n delete(key: DocumentKey): void {\n this.write(new DeleteMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n async commit(): Promise {\n this.ensureCommitNotCalled();\n\n if (this.lastTransactionError) {\n throw this.lastTransactionError;\n }\n const unwritten = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach(mutation => {\n unwritten.delete(mutation.key.toString());\n });\n // For each document that was read but not written to, we want to perform\n // a `verify` operation.\n unwritten.forEach((_, path) => {\n const key = DocumentKey.fromPath(path);\n this.mutations.push(new VerifyMutation(key, this.precondition(key)));\n });\n await invokeCommitRpc(this.datastore, this.mutations);\n this.committed = true;\n }\n\n private recordVersion(doc: Document): void {\n let docVersion: SnapshotVersion;\n\n if (doc.isFoundDocument()) {\n docVersion = doc.version;\n } else if (doc.isNoDocument()) {\n // Represent a deleted doc using SnapshotVersion.min().\n docVersion = SnapshotVersion.min();\n } else {\n throw fail(0xc542, 'Document in a transaction was a ', {\n documentName: doc.constructor.name\n });\n }\n\n const existingVersion = this.readVersions.get(doc.key.toString());\n if (existingVersion) {\n if (!docVersion.isEqual(existingVersion)) {\n // This transaction will fail no matter what.\n throw new FirestoreError(\n Code.ABORTED,\n 'Document version changed between two reads.'\n );\n }\n } else {\n this.readVersions.set(doc.key.toString(), docVersion);\n }\n }\n\n /**\n * Returns the version of this document when it was read in this transaction,\n * as a precondition, or no precondition if it was not read.\n */\n private precondition(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n return Precondition.exists(false);\n } else {\n return Precondition.updateTime(version);\n }\n } else {\n return Precondition.none();\n }\n }\n\n /**\n * Returns the precondition for a document if the operation is an update.\n */\n private preconditionForUpdate(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n // The first time a document is written, we want to take into account the\n // read time and existence\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n // The document doesn't exist, so fail the transaction.\n\n // This has to be validated locally because you can't send a\n // precondition that a document does not exist without changing the\n // semantics of the backend write to be an insert. This is the reverse\n // of what we want, since we want to assert that the document doesn't\n // exist but then send the update and have it fail. Since we can't\n // express that to the backend, we have to validate locally.\n\n // Note: this can change once we can send separate verify writes in the\n // transaction.\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't update a document that doesn't exist.\"\n );\n }\n // Document exists, base precondition on document update time.\n return Precondition.updateTime(version);\n } else {\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return Precondition.exists(true);\n }\n }\n\n private write(mutation: Mutation): void {\n this.ensureCommitNotCalled();\n this.mutations.push(mutation);\n }\n\n private ensureCommitNotCalled(): void {\n debugAssert(\n !this.committed,\n 'A transaction object cannot be used after its update callback has been invoked.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\n\nexport const DEFAULT_TRANSACTION_OPTIONS: TransactionOptions = {\n maxAttempts: 5\n};\n\n/**\n * Options to customize transaction behavior.\n */\nexport declare interface TransactionOptions {\n /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */\n readonly maxAttempts: number;\n}\n\nexport function validateTransactionOptions(options: TransactionOptions): void {\n if (options.maxAttempts < 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Max attempts must be at least 1'\n );\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ExponentialBackoff } from '../remote/backoff';\nimport { Datastore } from '../remote/datastore';\nimport { isPermanentError } from '../remote/rpc_error';\nimport { AsyncQueue, TimerId } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport { Deferred } from '../util/promise';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Transaction } from './transaction';\nimport { TransactionOptions } from './transaction_options';\n\n/**\n * TransactionRunner encapsulates the logic needed to run and retry transactions\n * with backoff.\n */\nexport class TransactionRunner {\n private attemptsRemaining: number;\n private backoff: ExponentialBackoff;\n\n constructor(\n private readonly asyncQueue: AsyncQueue,\n private readonly datastore: Datastore,\n private readonly options: TransactionOptions,\n private readonly updateFunction: (transaction: Transaction) => Promise,\n private readonly deferred: Deferred\n ) {\n this.attemptsRemaining = options.maxAttempts;\n this.backoff = new ExponentialBackoff(\n this.asyncQueue,\n TimerId.TransactionRetry\n );\n }\n\n /** Runs the transaction and sets the result on deferred. */\n run(): void {\n this.attemptsRemaining -= 1;\n this.runWithBackOff();\n }\n\n private runWithBackOff(): void {\n this.backoff.backoffAndRun(async () => {\n const transaction = new Transaction(this.datastore);\n const userPromise = this.tryRunUpdateFunction(transaction);\n if (userPromise) {\n userPromise\n .then(result => {\n this.asyncQueue.enqueueAndForget(() => {\n return transaction\n .commit()\n .then(() => {\n this.deferred.resolve(result);\n })\n .catch(commitError => {\n this.handleTransactionError(commitError);\n });\n });\n })\n .catch(userPromiseError => {\n this.handleTransactionError(userPromiseError);\n });\n }\n });\n }\n\n private tryRunUpdateFunction(transaction: Transaction): Promise | null {\n try {\n const userPromise = this.updateFunction(transaction);\n if (\n isNullOrUndefined(userPromise) ||\n !userPromise.catch ||\n !userPromise.then\n ) {\n this.deferred.reject(\n Error('Transaction callback must return a Promise')\n );\n return null;\n }\n return userPromise;\n } catch (error) {\n // Do not retry errors thrown by user provided updateFunction.\n this.deferred.reject(error as Error);\n return null;\n }\n }\n\n private handleTransactionError(error: Error): void {\n if (this.attemptsRemaining > 0 && this.isRetryableTransactionError(error)) {\n this.attemptsRemaining -= 1;\n this.asyncQueue.enqueueAndForget(() => {\n this.runWithBackOff();\n return Promise.resolve();\n });\n } else {\n this.deferred.reject(error);\n }\n }\n\n private isRetryableTransactionError(error: Error | undefined): boolean {\n if (error?.name === 'FirebaseError') {\n // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and\n // non-matching document versions with ABORTED. These errors should be retried.\n const code = (error as FirestoreError).code;\n return (\n code === 'aborted' ||\n code === 'failed-precondition' ||\n code === 'already-exists' ||\n !isPermanentError(code)\n );\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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(0xb815, 'AsyncQueue is already failed', {\n messageOrStack: getMessageOrStack(this.failure)\n });\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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getGlobal, 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 `indexedDB` are guarded by SimpleDb.isAvailable() and getGlobal()\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 lastClosedDbVersion: number | null = null;\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 const globals = getGlobal();\n return wrapRequest(\n globals.indexedDB.deleteDatabase(name)\n ).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\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport {\n DEFAULT_TRANSACTION_OPTIONS,\n TransactionOptions as TransactionOptionsInternal,\n validateTransactionOptions\n} from '../core/transaction_options';\nimport { TransactionRunner } from '../core/transaction_runner';\nimport { fail } from '../util/assert';\nimport { newAsyncQueue } from '../util/async_queue_impl';\nimport { cast } from '../util/input_validation';\nimport { Deferred } from '../util/promise';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n applyFirestoreDataConverter,\n LiteUserDataWriter\n} from './reference_impl';\nimport { DocumentSnapshot } from './snapshot';\nimport { TransactionOptions } from './transaction_options';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\nimport { validateReference } from './write_batch';\n\n// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the\n// legacy SDK.\n\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nexport class Transaction {\n // This is the tree-shakeable version of the Transaction class used in the\n // legacy SDK. The class is a close copy but takes different input and output\n // types. The firestore-exp SDK further extends this class to return its API\n // type.\n\n private readonly _dataReader: UserDataReader;\n\n /** @hideconstructor */\n constructor(\n protected readonly _firestore: Firestore,\n private readonly _transaction: InternalTransaction\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */\n get(\n documentRef: DocumentReference\n ): Promise> {\n const ref = validateReference(documentRef, this._firestore);\n const userDataWriter = new LiteUserDataWriter(this._firestore);\n return this._transaction.lookup([ref._key]).then(docs => {\n if (!docs || docs.length !== 1) {\n return fail(0x5de9, 'Mismatch in docs returned from document lookup.');\n }\n const doc = docs[0];\n if (doc.isFoundDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n doc.key,\n doc,\n ref.converter\n );\n } else if (doc.isNoDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n ref._key,\n null,\n ref.converter\n );\n } else {\n throw fail(\n 0x4801,\n 'BatchGetDocumentsRequest returned unexpected document',\n {\n doc\n }\n );\n }\n });\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): this;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): this;\n set(\n documentRef: DocumentReference,\n value: PartialWithFieldValue,\n options?: SetOptions\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n value,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'Transaction.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._transaction.set(ref._key, parsed);\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): this;\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key/value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._transaction.update(ref._key, parsed);\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n this._transaction.delete(ref._key);\n return this;\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */\nexport function runTransaction(\n firestore: Firestore,\n updateFunction: (transaction: Transaction) => Promise,\n options?: TransactionOptions\n): Promise {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n const optionsWithDefaults: TransactionOptionsInternal = {\n ...DEFAULT_TRANSACTION_OPTIONS,\n ...options\n };\n validateTransactionOptions(optionsWithDefaults);\n const deferred = new Deferred();\n new TransactionRunner(\n newAsyncQueue(),\n datastore,\n optionsWithDefaults,\n internalTransaction =>\n updateFunction(new Transaction(firestore, internalTransaction)),\n deferred\n ).run();\n return deferred.promise;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 { version } from '../package.json';\nimport {\n LiteAppCheckTokenProvider,\n LiteAuthCredentialsProvider\n} from '../src/api/credentials';\nimport { databaseIdFromApp } from '../src/core/database_info';\nimport { setSDKVersion } from '../src/core/version';\nimport { Firestore } from '../src/lite-api/database';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore/lite': Firestore;\n }\n}\n\nexport function registerFirestore(): void {\n setSDKVersion(`${SDK_VERSION}_lite`);\n _registerComponent(\n new Component(\n 'firestore/lite',\n (container, { instanceIdentifier: databaseId, options: settings }) => {\n const app = container.getProvider('app').getImmediate()!;\n const firestoreInstance = new Firestore(\n new LiteAuthCredentialsProvider(\n container.getProvider('auth-internal')\n ),\n new LiteAppCheckTokenProvider(\n app,\n container.getProvider('app-check-internal')\n ),\n databaseIdFromApp(app, databaseId),\n app\n );\n if (settings) {\n firestoreInstance._setSettings(settings);\n }\n return firestoreInstance;\n },\n 'PUBLIC' as ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n // RUNTIME_ENV and BUILD_TARGET are replaced by real values during the compilation\n registerVersion('firestore-lite', version, '__RUNTIME_ENV__');\n registerVersion('firestore-lite', version, '__BUILD_TARGET__');\n}\n","/**\n * Firestore Lite\n *\n * @remarks Firestore Lite is a small online-only SDK that allows read\n * and write access to your Firestore database. All operations connect\n * directly to the backend, and `onSnapshot()` APIs are not supported.\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 { registerFirestore } from './register';\nregisterFirestore();\n\nexport {\n aggregateQuerySnapshotEqual,\n getCount,\n getAggregate,\n count,\n sum,\n average,\n aggregateFieldEqual\n} from '../src/lite-api/aggregate';\n\nexport {\n AggregateField,\n AggregateFieldType,\n AggregateSpec,\n AggregateSpecData,\n AggregateQuerySnapshot,\n AggregateType\n} from '../src/lite-api/aggregate_types';\n\nexport { FirestoreSettings as Settings } from '../src/lite-api/settings';\n\nexport {\n Firestore as Firestore,\n EmulatorMockTokenOptions,\n initializeFirestore,\n getFirestore,\n terminate,\n connectFirestoreEmulator\n} from '../src/lite-api/database';\n\nexport {\n DocumentData,\n UpdateData,\n WithFieldValue,\n PartialWithFieldValue,\n SetOptions,\n DocumentReference,\n Query,\n CollectionReference,\n collection,\n collectionGroup,\n doc,\n refEqual,\n queryEqual\n} from '../src/lite-api/reference';\n\nexport {\n and,\n endAt,\n endBefore,\n startAt,\n startAfter,\n limit,\n limitToLast,\n where,\n or,\n orderBy,\n query,\n QueryConstraint,\n QueryConstraintType,\n QueryCompositeFilterConstraint,\n QueryFilterConstraint,\n QueryFieldFilterConstraint,\n QueryOrderByConstraint,\n QueryLimitConstraint,\n QueryNonFilterConstraint,\n QueryStartAtConstraint,\n QueryEndAtConstraint,\n OrderByDirection,\n WhereFilterOp\n} from '../src/lite-api/query';\n\nexport {\n addDoc,\n deleteDoc,\n updateDoc,\n setDoc,\n getDoc,\n getDocs\n} from '../src/lite-api/reference_impl';\n\nexport {\n Primitive,\n NestedUpdateFields,\n ChildUpdateFields,\n AddPrefixToKeys,\n UnionToIntersection\n} from '../src/lite-api/types';\n\n// TODO(firestorelite): Add tests when Queries are usable\nexport { FieldPath, documentId } from '../src/lite-api/field_path';\n\n// TODO(firestorelite): Add tests when setDoc() is available\nexport { FieldValue } from '../src/lite-api/field_value';\n\nexport {\n increment,\n arrayRemove,\n arrayUnion,\n serverTimestamp,\n deleteField,\n vector\n} from '../src/lite-api/field_value_impl';\n\nexport {\n FirestoreDataConverter,\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot,\n snapshotEqual\n} from '../src/lite-api/snapshot';\n\nexport { VectorValue } from '../src/lite-api/vector_value';\n\nexport { WriteBatch, writeBatch } from '../src/lite-api/write_batch';\n\nexport { TransactionOptions } from '../src/lite-api/transaction_options';\n\nexport { Transaction, runTransaction } from '../src/lite-api/transaction';\n\nexport { setLogLevel, LogLevelString as LogLevel } from '../src/util/log';\n\nexport { Bytes } from '../src/lite-api/bytes';\n\nexport { GeoPoint } from '../src/lite-api/geo_point';\n\nexport { Timestamp } from '../src/lite-api/timestamp';\n\nexport { FirestoreErrorCode, FirestoreError } from '../src/util/error';\n"],"names":["User","constructor","uid","this","isAuthenticated","toKey","isEqual","otherUser","UNAUTHENTICATED","GOOGLE_CREDENTIALS","FIRST_PARTY","MOCK_USER","SDK_VERSION","__PRIVATE_logClient","Logger","setLogLevel","logLevel","__PRIVATE_logDebug","msg","obj","LogLevel","DEBUG","args","map","__PRIVATE_argToString","debug","__PRIVATE_logError","ERROR","error","__PRIVATE_logWarn","WARN","warn","__PRIVATE_formatJSON","value","JSON","stringify","e","fail","id","__PRIVATE_messageOrContext","context","message","__PRIVATE__fail","__PRIVATE_failure","toString","undefined","Error","__PRIVATE_hardAssert","assertion","__PRIVATE_debugCast","Code","FirestoreError","FirebaseError","code","super","name","__PRIVATE_Deferred","promise","Promise","resolve","reject","__PRIVATE_OAuthToken","user","type","headers","Map","set","__PRIVATE_EmptyAuthCredentialsProvider","getToken","invalidateToken","start","asyncQueue","changeListener","enqueueRetryable","shutdown","__PRIVATE_EmulatorAuthCredentialsProvider","token","__PRIVATE_LiteAuthCredentialsProvider","__PRIVATE_authProvider","auth","onInit","then","__PRIVATE_tokenData","accessToken","getUid","__PRIVATE_FirstPartyToken","__PRIVATE_sessionIndex","__PRIVATE_iamToken","__PRIVATE_authTokenFactory","__PRIVATE_getAuthToken","__PRIVATE__headers","__PRIVATE_authHeaderTokenValue","__PRIVATE_FirstPartyAuthCredentialsProvider","AppCheckToken","length","__PRIVATE_LiteAppCheckTokenProvider","app","__PRIVATE_appCheckProvider","appCheck","__PRIVATE_serverAppAppCheckToken","_isFirebaseServerApp","settings","appCheckToken","tokenResult","DatabaseInfo","databaseId","appId","persistenceKey","host","ssl","forceLongPolling","autoDetectLongPolling","longPollingOptions","useFetchStreams","isUsingEmulator","__PRIVATE_DEFAULT_DATABASE_NAME","DatabaseId","projectId","database","empty","isDefaultDatabase","other","__PRIVATE_randomBytes","__PRIVATE_nBytes","crypto","self","bytes","Uint8Array","getRandomValues","__PRIVATE_i","Math","floor","random","__PRIVATE_AutoId","newId","__PRIVATE_chars","__PRIVATE_maxMultiple","__PRIVATE_autoId","charAt","__PRIVATE_primitiveComparator","left","right","__PRIVATE_compareUtf8Strings","min","__PRIVATE_leftChar","__PRIVATE_rightChar","__PRIVATE_isSurrogate","__PRIVATE_MIN_SURROGATE","__PRIVATE_MAX_SURROGATE","s","c","charCodeAt","__PRIVATE_arrayEquals","comparator","every","index","__PRIVATE_DOCUMENT_KEY_NAME","BasePath","segments","offset","range","len","child","nameOrPath","slice","limit","forEach","segment","push","construct","popFirst","size","popLast","firstSegment","lastSegment","get","isEmpty","isPrefixOf","isImmediateParentOf","potentialChild","fn","end","toArray","p1","p2","comparison","compareSegments","__PRIVATE_lhs","__PRIVATE_rhs","__PRIVATE_isLhsNumeric","isNumericId","__PRIVATE_isRhsNumeric","extractNumericId","compare","startsWith","endsWith","Integer","fromString","substring","ResourcePath","canonicalString","join","toUriEncodedString","encodeURIComponent","pathComponents","path","indexOf","split","filter","emptyPath","__PRIVATE_identifierRegExp","FieldPath","isValidIdentifier","test","str","replace","isKeyField","keyField","fromServerFormat","current","__PRIVATE_addCurrentSegment","__PRIVATE_inBackticks","next","DocumentKey","fromPath","fromName","collectionGroup","hasCollectionId","collectionId","getCollectionGroup","getCollectionPath","k1","k2","isDocumentKey","fromSegments","__PRIVATE_validateNonEmptyArgument","__PRIVATE_functionName","__PRIVATE_argumentName","__PRIVATE_argument","__PRIVATE_validateDocumentPath","__PRIVATE_validateCollectionPath","__PRIVATE_isPlainObject","input","Object","getPrototypeOf","prototype","__PRIVATE_valueDescription","Array","__PRIVATE_customObjectName","__PRIVATE_tryGetCustomObjectType","__PRIVATE_cast","_delegate","description","__PRIVATE_validatePositiveNumber","n","__PRIVATE_cloneLongPollingOptions","options","clone","timeoutSeconds","__PRIVATE_lastUniqueDebugId","__PRIVATE_generateUniqueDebugId","__PRIVATE_generateInitialUniqueDebugId","round","__PRIVATE_maxResult","__PRIVATE_isNullOrUndefined","__PRIVATE_isNegativeZero","__PRIVATE_LOG_TAG","__PRIVATE_RPC_NAME_URL_MAPPING","__PRIVATE_RestConnection","__PRIVATE_shouldResourcePathBeIncludedInRequest","databaseInfo","proto","__PRIVATE_baseUrl","__PRIVATE_databasePath","__PRIVATE_requestParams","__PRIVATE_invokeRPC","__PRIVATE_rpcName","__PRIVATE_req","__PRIVATE_authToken","streamId","url","__PRIVATE_makeUrl","__PRIVATE_modifyHeadersForRequest","URL","__PRIVATE_forwardCredentials","isCloudWorkstation","__PRIVATE_performRPCRequest","response","err","__PRIVATE_invokeStreamingRPC","request","__PRIVATE_expectedResponseCount","__PRIVATE_getGoogApiClientValue","key","__PRIVATE_urlRpcName","terminate","__PRIVATE_RpcCode","RpcCode","__PRIVATE_mapCodeFromHttpStatus","status","__PRIVATE_FetchConnection","__PRIVATE_openStream","body","__PRIVATE_requestJson","__PRIVATE_fetchArgs","method","credentials","fetch","statusText","ok","__PRIVATE_errorResponse","json","isArray","__PRIVATE_errorMessage","__PRIVATE_AggregateImpl","alias","aggregateType","fieldPath","__PRIVATE_objectSize","count","hasOwnProperty","call","__PRIVATE_Base64DecodeError","ByteString","binaryString","fromBase64String","base64","__PRIVATE_decodeBase64","__PRIVATE_encoded","atob","DOMException","fromUint8Array","array","__PRIVATE_binaryStringFromUint8Array","String","fromCharCode","Symbol","iterator","done","toBase64","__PRIVATE_encodeBase64","raw","btoa","toUint8Array","__PRIVATE_uint8ArrayFromBinaryString","buffer","approximateByteSize","compareTo","EMPTY_BYTE_STRING","__PRIVATE_ISO_TIMESTAMP_REG_EXP","RegExp","__PRIVATE_normalizeTimestamp","date","nanos","__PRIVATE_fraction","exec","timestamp","__PRIVATE_nanoStr","substr","Number","__PRIVATE_parsedDate","Date","seconds","getTime","__PRIVATE_normalizeNumber","__PRIVATE_normalizeByteString","blob","property","typeString","__PRIVATE_optionalValue","result","__PRIVATE_validateJSON","__PRIVATE_schema","__PRIVATE_fieldValue","__PRIVATE_MIN_SECONDS","__PRIVATE_MS_TO_NANOS","Timestamp","now","fromMillis","fromDate","milliseconds","nanoseconds","toDate","toMillis","_compareTo","toJSON","_jsonSchemaVersion","fromJSON","_jsonSchema","valueOf","__PRIVATE_adjustedSeconds","padStart","__PRIVATE_isServerTimestamp","mapValue","fields","stringValue","__PRIVATE_getPreviousValue","previousValue","__PRIVATE_getLocalWriteTime","localWriteTime","timestampValue","__PRIVATE_TYPE_KEY","__PRIVATE_MAX_VALUE_TYPE","MAX_VALUE","__type__","__PRIVATE_VECTOR_VALUE_SENTINEL","__PRIVATE_VECTOR_MAP_VECTORS_KEY","__PRIVATE_typeOrder","__PRIVATE_isMaxValue","__PRIVATE_isVectorValue","__PRIVATE_valueEquals","__PRIVATE_leftType","booleanValue","__PRIVATE_timestampEquals","__PRIVATE_leftTimestamp","__PRIVATE_rightTimestamp","__PRIVATE_blobEquals","bytesValue","referenceValue","__PRIVATE_geoPointEquals","geoPointValue","latitude","longitude","__PRIVATE_numberEquals","integerValue","__PRIVATE_n1","doubleValue","__PRIVATE_n2","isNaN","arrayValue","values","__PRIVATE_objectEquals","__PRIVATE_leftMap","__PRIVATE_rightMap","__PRIVATE_arrayValueContains","__PRIVATE_haystack","__PRIVATE_needle","find","v","__PRIVATE_valueCompare","__PRIVATE_rightType","__PRIVATE_compareNumbers","__PRIVATE_leftNumber","__PRIVATE_rightNumber","__PRIVATE_compareTimestamps","__PRIVATE_compareBlobs","__PRIVATE_leftBytes","__PRIVATE_rightBytes","__PRIVATE_compareReferences","__PRIVATE_leftPath","__PRIVATE_rightPath","__PRIVATE_leftSegments","__PRIVATE_rightSegments","__PRIVATE_compareGeoPoints","__PRIVATE_compareArrays","__PRIVATE_compareVectors","__PRIVATE_leftArrayValue","__PRIVATE_rightArrayValue","__PRIVATE_lengthCompare","__PRIVATE_compareMaps","__PRIVATE_leftKeys","keys","__PRIVATE_rightKeys","sort","__PRIVATE_keyCompare","__PRIVATE_leftArray","__PRIVATE_rightArray","__PRIVATE_refValue","__PRIVATE_isNullValue","__PRIVATE_isNanValue","__PRIVATE_isMapValue","__PRIVATE_deepClone","source","target","val","Bound","position","inclusive","__PRIVATE_boundEquals","Filter","FieldFilter","field","op","create","createKeyFieldInFilter","__PRIVATE_KeyFieldFilter","__PRIVATE_ArrayContainsFilter","__PRIVATE_InFilter","__PRIVATE_NotInFilter","__PRIVATE_ArrayContainsAnyFilter","__PRIVATE_KeyFieldInFilter","__PRIVATE_KeyFieldNotInFilter","matches","doc","data","nullValue","matchesComparison","operator","isInequality","getFlattenedFilters","getFilters","CompositeFilter","filters","__PRIVATE_memoizedFlattenedFilters","__PRIVATE_compositeFilterIsConjunction","compositeFilter","reduce","__PRIVATE_subfilter","concat","assign","__PRIVATE_filterEquals","__PRIVATE_f1","__PRIVATE_f2","__PRIVATE_fieldFilterEquals","__PRIVATE_compositeFilterEquals","__PRIVATE_f1Filter","__PRIVATE_extractDocumentKeysFromArrayValue","some","OrderBy","dir","__PRIVATE_orderByEquals","SnapshotVersion","fromTimestamp","max","toMicroseconds","toTimestamp","SortedMap","root","LLRBNode","EMPTY","insert","copy","BLACK","remove","node","cmp","__PRIVATE_prunedNodes","minKey","maxKey","inorderTraversal","action","k","__PRIVATE_descriptions","reverseTraversal","getIterator","SortedMapIterator","getIteratorFrom","getReverseIterator","getReverseIteratorFrom","startKey","isReverse","nodeStack","getNext","pop","hasNext","peek","color","RED","fixUp","removeMin","isRed","moveRedLeft","__PRIVATE_smallest","rotateRight","moveRedRight","rotateLeft","colorFlip","__PRIVATE_nl","__PRIVATE_nr","checkMaxDepth","__PRIVATE_blackDepth","check","pow","LLRBEmptyNode","SortedSet","has","elem","first","last","cb","forEachInRange","iter","forEachWhile","firstAfterOrEqual","SortedSetIterator","add","unionWith","__PRIVATE_thisIt","__PRIVATE_otherIt","__PRIVATE_thisElem","__PRIVATE_otherElem","__PRIVATE_res","targetId","FieldMask","extraFields","__PRIVATE_mergedMaskSet","covers","__PRIVATE_fieldMaskPath","l","r","ObjectValue","__PRIVATE_currentLevel","getFieldsMap","setAll","parent","__PRIVATE_upserts","__PRIVATE_deletes","__PRIVATE_fieldsMap","applyChanges","__PRIVATE_nestedValue","__PRIVATE_inserts","MutableDocument","documentType","version","readTime","createTime","documentState","newInvalidDocument","documentKey","newFoundDocument","newNoDocument","newUnknownDocument","convertToFoundDocument","convertToNoDocument","convertToUnknownDocument","setHasCommittedMutations","setHasLocalMutations","setReadTime","hasLocalMutations","hasCommittedMutations","hasPendingWrites","isValidDocument","isFoundDocument","isNoDocument","isUnknownDocument","mutableCopy","__PRIVATE_TargetImpl","orderBy","startAt","endAt","__PRIVATE_memoizedCanonicalId","__PRIVATE_newTarget","__PRIVATE_QueryImpl","explicitOrderBy","limitType","__PRIVATE_memoizedNormalizedOrderBy","__PRIVATE_memoizedTarget","__PRIVATE_memoizedAggregateTarget","__PRIVATE_isCollectionGroupQuery","query","__PRIVATE_queryNormalizedOrderBy","__PRIVATE_queryImpl","__PRIVATE_fieldsNormalized","Set","__PRIVATE_lastDirection","__PRIVATE_inequalityFields","__PRIVATE_getInequalityFilterFields","__PRIVATE_queryToTarget","__PRIVATE__queryToTarget","__PRIVATE_orderBys","__PRIVATE_queryWithAddedFilter","__PRIVATE_newFilters","__PRIVATE_queryEquals","__PRIVATE_targetEquals","__PRIVATE_toDouble","serializer","useProto3Json","Infinity","toNumber","isSafeInteger","isInteger","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","__PRIVATE_toInteger","TransformOperation","_","__PRIVATE_ServerTimestampTransform","__PRIVATE_ArrayUnionTransformOperation","elements","__PRIVATE_ArrayRemoveTransformOperation","__PRIVATE_NumericIncrementTransformOperation","__PRIVATE_operand","FieldTransform","transform","Precondition","updateTime","exists","none","isNone","Mutation","__PRIVATE_SetMutation","precondition","fieldTransforms","getFieldMask","__PRIVATE_PatchMutation","fieldMask","__PRIVATE_DeleteMutation","__PRIVATE_VerifyMutation","__PRIVATE_DIRECTIONS","__PRIVATE_dirs","__PRIVATE_OPERATORS","__PRIVATE_ops","__PRIVATE_COMPOSITE_OPERATORS","JsonProtoSerializer","toISOString","__PRIVATE_toBytes","__PRIVATE_toVersion","__PRIVATE_fromVersion","__PRIVATE_toResourceName","__PRIVATE_toResourcePath","__PRIVATE_resourcePath","__PRIVATE_fullyQualifiedPrefixPath","__PRIVATE_toName","__PRIVATE_resource","__PRIVATE_fromResourceName","__PRIVATE_isValidResourceName","__PRIVATE_extractLocalPathFromResourceName","__PRIVATE_resourceName","__PRIVATE_toMutationDocument","__PRIVATE_fromBatchGetDocumentsResponse","__PRIVATE_fromFound","found","__PRIVATE_fromMissing","missing","toMutation","mutation","update","delete","updateMask","__PRIVATE_toDocumentMask","__PRIVATE_mutationType","verify","updateTransforms","__PRIVATE_toFieldTransform","__PRIVATE_fieldTransform","setToServerValue","appendMissingElements","removeAllFromArray","increment","currentDocument","__PRIVATE_toPrecondition","__PRIVATE_toQueryTarget","__PRIVATE_queryTarget","structuredQuery","from","allDescendants","__PRIVATE_toQueryPath","where","__PRIVATE_toFilters","__PRIVATE_toFilter","__PRIVATE_toOrder","order","__PRIVATE_toPropertyOrder","__PRIVATE_toFieldPathReference","direction","__PRIVATE_toDirection","__PRIVATE_toInt32Proto","__PRIVATE_toStartAtCursor","cursor","before","__PRIVATE_toEndAtCursor","__PRIVATE_toOperatorName","__PRIVATE_toCompositeOperatorName","__PRIVATE_toUnaryOrFieldFilter","unaryFilter","fieldFilter","__PRIVATE_toCompositeFilter","__PRIVATE_protos","__PRIVATE_canonicalFields","fieldPaths","__PRIVATE_newSerializer","__PRIVATE_ExponentialBackoff","__PRIVATE_queue","timerId","__PRIVATE_initialDelayMs","__PRIVATE_backoffFactor","__PRIVATE_maxDelayMs","__PRIVATE_currentBaseMs","__PRIVATE_timerPromise","reset","__PRIVATE_resetToMax","__PRIVATE_backoffAndRun","cancel","__PRIVATE_desiredDelayWithJitterMs","__PRIVATE_jitterDelayMs","__PRIVATE_delaySoFarMs","__PRIVATE_lastAttemptTime","__PRIVATE_remainingDelayMs","enqueueAfterDelay","__PRIVATE_skipBackoff","skipDelay","Datastore","__PRIVATE_DatastoreImpl","authCredentials","appCheckCredentials","connection","__PRIVATE_terminated","__PRIVATE_verifyInitialized","all","catch","async","__PRIVATE_invokeCommitRpc","datastore","mutations","__PRIVATE_datastoreImpl","writes","m","__PRIVATE_invokeBatchGetDocumentsRpc","documents","docs","__PRIVATE_invokeRunQueryRpc","M","document","__PRIVATE_fromDocument","__PRIVATE_invokeRunAggregationQueryRpc","__PRIVATE_aggregates","nt","__PRIVATE_aliasMap","__PRIVATE_toRunAggregationQueryRequest","__PRIVATE_skipAliasing","aggregations","__PRIVATE_aggregationNum","__PRIVATE_aggregate","__PRIVATE_serverAlias","avg","sum","structuredAggregationQuery","__PRIVATE_queryToAggregateTarget","__PRIVATE_filteredResult","__PRIVATE_unmappedAggregateFields","aggregateFields","__PRIVATE_accumulator","__PRIVATE_datastoreInstances","__PRIVATE_getDatastore","firestore","_terminated","__PRIVATE_newConnection","__PRIVATE_makeDatabaseInfo","experimentalForceLongPolling","experimentalAutoDetectLongPolling","experimentalLongPollingOptions","_databaseId","_persistenceKey","_freezeSettings","__PRIVATE_newDatastore","_authCredentials","_appCheckCredentials","__PRIVATE_LRU_MINIMUM_CACHE_SIZE_BYTES","__PRIVATE_DEFAULT_HOST","__PRIVATE_DEFAULT_SSL","FirestoreSettingsImpl","emulatorOptions","ignoreUndefinedProperties","localCache","cacheSizeBytes","__PRIVATE_validateIsNotUsedTogether","optionName1","argument1","optionName2","argument2","__PRIVATE_validateLongPollingOptions","__PRIVATE_longPollingOptionsEqual","__PRIVATE_options1","__PRIVATE_options2","Firestore","_app","_settings","_settingsFrozen","_emulatorOptions","_terminateTask","_initialized","_setSettings","__PRIVATE_makeAuthCredentialsProvider","_getSettings","_getEmulatorOptions","_delete","_terminate","_restart","__PRIVATE_removeComponents","initializeFirestore","provider","_getProvider","isInitialized","initialize","instanceIdentifier","getFirestore","__PRIVATE_appOrDatabaseId","__PRIVATE_optionalDatabaseId","getApp","db","getImmediate","identifier","__PRIVATE_emulator","getDefaultEmulatorHostnameAndPort","connectFirestoreEmulator","port","__PRIVATE_useSsl","__PRIVATE_existingConfig","__PRIVATE_newHostSetting","pingServer","updateEmulatorBanner","__PRIVATE_newConfig","deepEqual","mockUserToken","createMockUserToken","sub","user_id","_removeServiceInstance","AggregateField","_internalFieldPath","AggregateQuerySnapshot","_userDataWriter","_data","convertObjectMap","Query","converter","_query","withConverter","DocumentReference","_key","_path","CollectionReference","referencePath","__PRIVATE_newQueryForPath","parentPath","collection","pathSegments","getModularInstance","__PRIVATE_absolutePath","__PRIVATE_newQueryForCollectionGroup","arguments","refEqual","queryEqual","Bytes","byteString","_byteString","fieldNames","_internalPath","__PRIVATE_InternalFieldPath","documentId","FieldValue","_methodName","GeoPoint","isFinite","_lat","_long","VectorValue","_values","__PRIVATE_isPrimitiveArrayEqual","vectorValues","element","__PRIVATE_RESERVED_FIELD_REGEX","ParsedSetData","ParsedUpdateData","__PRIVATE_isWrite","__PRIVATE_dataSource","__PRIVATE_ParseContextImpl","__PRIVATE_validatePath","__PRIVATE_contextWith","configuration","__PRIVATE_childContextForField","__PRIVATE_childPath","__PRIVATE_arrayElement","__PRIVATE_validatePathSegment","__PRIVATE_childContextForFieldPath","__PRIVATE_childContextForArray","__PRIVATE_createError","reason","methodName","__PRIVATE_hasConverter","__PRIVATE_targetDoc","contains","__PRIVATE_UserDataReader","__PRIVATE_createContext","__PRIVATE_newUserDataReader","__PRIVATE_parseSetData","__PRIVATE_userDataReader","merge","mergeFields","__PRIVATE_validatePlainObject","__PRIVATE_updateData","__PRIVATE_parseObject","__PRIVATE_validatedFieldPaths","__PRIVATE_stringOrFieldPath","__PRIVATE_fieldPathFromArgument","__PRIVATE_fieldMaskContains","__PRIVATE_DeleteFieldValueImpl","_toFieldTransform","__PRIVATE_createSentinelChildContext","__PRIVATE_ServerTimestampFieldValueImpl","__PRIVATE_ArrayUnionFieldValueImpl","__PRIVATE__elements","__PRIVATE_parseContext","__PRIVATE_parsedElements","__PRIVATE_parseData","arrayUnion","__PRIVATE_ArrayRemoveFieldValueImpl","__PRIVATE_NumericIncrementFieldValueImpl","__PRIVATE__operand","__PRIVATE_numericIncrement","__PRIVATE_parseUpdateData","__PRIVATE_fieldMaskPaths","__PRIVATE_fieldPathFromDotSeparatedString","__PRIVATE_childContext","__PRIVATE_parsedValue","mask","__PRIVATE_parseUpdateVarargs","moreFieldsAndValues","__PRIVATE_parseQueryValue","__PRIVATE_allowArrays","__PRIVATE_looksLikeJsonObject","__PRIVATE_parseSentinelFieldValue","__PRIVATE_parseArray","__PRIVATE_entryIndex","entry","__PRIVATE_parsedEntry","__PRIVATE_parseScalarValue","__PRIVATE_thisDb","__PRIVATE_otherDb","__PRIVATE_parseVectorValue","__PRIVATE_FIELD_PATH_RESERVED","search","__PRIVATE_hasPath","__PRIVATE_hasDocument","DocumentSnapshot","_firestore","_document","_converter","ref","snapshot","QueryDocumentSnapshot","fromFirestore","convertValue","QuerySnapshot","_docs","callback","thisArg","snapshotEqual","arg","AppliableConstraint","QueryConstraint","__PRIVATE_queryConstraint","__PRIVATE_additionalQueryConstraints","queryConstraints","__PRIVATE_validateQueryConstraintArray","__PRIVATE_compositeFilterCount","QueryCompositeFilterConstraint","__PRIVATE_fieldFilterCount","QueryFieldFilterConstraint","constraint","_apply","_field","_op","_value","_create","_parse","__PRIVATE_validateNewFieldFilter","__PRIVATE_reader","__PRIVATE_newQueryFilter","__PRIVATE_dataReader","__PRIVATE_validateDisjunctiveFilterElements","__PRIVATE_referenceList","__PRIVATE_parseDocumentIdValue","opStr","_queryConstraints","__PRIVATE_parsedFilters","__PRIVATE_parsedFilter","_getOperator","__PRIVATE_validateNewFilter","__PRIVATE_testQuery","__PRIVATE_subFilters","__PRIVATE_subFilter","_getQueryConstraints","or","__PRIVATE_validateQueryFilterConstraint","and","QueryOrderByConstraint","_direction","__PRIVATE_newQueryOrderBy","__PRIVATE_queryWithAddedOrderBy","__PRIVATE_newOrderBy","directionStr","QueryLimitConstraint","_limit","_limitType","__PRIVATE_queryWithLimit","limitToLast","QueryStartAtConstraint","_docOrFields","_inclusive","bound","__PRIVATE_newQueryBoundFromDocOrFields","__PRIVATE_queryWithStartAt","__PRIVATE_docOrFields","startAfter","QueryEndAtConstraint","__PRIVATE_queryWithEndAt","endBefore","__PRIVATE_newQueryBoundFromDocument","components","__PRIVATE_newQueryBoundFromFields","__PRIVATE_rawValue","__PRIVATE_wrapped","__PRIVATE_documentIdValue","__PRIVATE_conflictingOp","__PRIVATE_findOpInsideFilters","__PRIVATE_operators","__PRIVATE_conflictingOps","AbstractUserDataWriter","serverTimestampBehavior","convertTimestamp","convertServerTimestamp","convertBytes","convertReference","convertGeoPoint","convertArray","convertObject","convertVectorValue","__PRIVATE_normalizedValue","convertDocumentKey","expectedDatabaseId","__PRIVATE_applyFirestoreDataConverter","__PRIVATE_convertedValue","toFirestore","__PRIVATE_LiteUserDataWriter","getDoc","reference","userDataWriter","getDocs","__PRIVATE_validateHasExplicitOrderByForLimitToLast","reverse","setDoc","__PRIVATE_parsed","updateDoc","__PRIVATE_fieldOrUpdateData","deleteDoc","addDoc","__PRIVATE_docRef","getCount","getAggregate","aggregateSpec","__PRIVATE_internalAggregates","__PRIVATE_mapToArray","__PRIVATE_aggregateResult","__PRIVATE_convertToAggregateQuerySnapshot","__PRIVATE_querySnapshot","average","aggregateFieldEqual","aggregateQuerySnapshotEqual","deleteField","serverTimestamp","arrayRemove","vector","WriteBatch","_commitHandler","_mutations","_committed","_dataReader","documentRef","_verifyNotCommitted","__PRIVATE_validateReference","commit","writeBatch","Transaction","readVersions","committed","lastTransactionError","writtenDocs","lookup","ensureCommitNotCalled","recordVersion","write","preconditionForUpdate","__PRIVATE_unwritten","__PRIVATE_docVersion","__PRIVATE_documentName","__PRIVATE_existingVersion","__PRIVATE_DEFAULT_TRANSACTION_OPTIONS","maxAttempts","__PRIVATE_TransactionRunner","updateFunction","deferred","__PRIVATE_attemptsRemaining","__PRIVATE_backoff","__PRIVATE_run","__PRIVATE_runWithBackOff","transaction","__PRIVATE_userPromise","__PRIVATE_tryRunUpdateFunction","enqueueAndForget","__PRIVATE_commitError","__PRIVATE_handleTransactionError","__PRIVATE_userPromiseError","__PRIVATE_isRetryableTransactionError","__PRIVATE_isPermanentError","getDocument","DelayedOperation","targetTimeMs","removalCallback","bind","createAndSchedule","delayMs","__PRIVATE_targetTime","__PRIVATE_delayedOp","timerHandle","setTimeout","handleDelayElapsed","clearTimeout","__PRIVATE_AsyncQueueImpl","__PRIVATE_tail","__PRIVATE_retryableOps","__PRIVATE__isShuttingDown","__PRIVATE_delayedOperations","__PRIVATE_operationInProgress","__PRIVATE_skipNonRestrictedTasks","__PRIVATE_timerIdsToSkip","__PRIVATE_visibilityHandler","visibilityState","addEventListener","isShuttingDown","enqueue","enqueueAndForgetEvenWhileRestricted","__PRIVATE_verifyNotFailed","__PRIVATE_enqueueInternal","enterRestrictedMode","purgeExistingTasks","removeEventListener","task","__PRIVATE_retryNextOp","shift","__PRIVATE_isIndexedDbTransactionError","__PRIVATE_newTail","__PRIVATE_getMessageOrStack","__PRIVATE_removedOp","__PRIVATE_removeDelayedOperation","__PRIVATE_messageOrStack","verifyOperationInProgress","__PRIVATE_drain","__PRIVATE_currentTail","__PRIVATE_containsDelayedOperation","__PRIVATE_runAllDelayedOperationsUntil","__PRIVATE_lastTimerId","a","b","__PRIVATE_skipDelaysForTimerId","splice","stack","includes","_transaction","runTransaction","__PRIVATE_optionsWithDefaults","__PRIVATE_validateTransactionOptions","__PRIVATE_newAsyncQueue","__PRIVATE_internalTransaction","__PRIVATE_registerFirestore","__PRIVATE_setSDKVersion","_registerComponent","Component","container","getProvider","__PRIVATE_firestoreInstance","__PRIVATE_databaseIdFromApp","apply","setMultipleInstances","registerVersion"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAqBaA,IAAAA,MAAAA,IAAAA,CAAAA;AAUX,IAAA,WAAAC,CAAqBC,CAAAA,EAAAA;AAAAC,QAAAA,IAAAA,CAAGD,GAAHA,GAAAA,CAAAA,CAAAA;AAAsB,KAAA;IAE3C,eAAAE,GAAAA;AACE,QAAA,OAAmB,QAAZD,IAAKD,CAAAA,GAAAA,CAAAA;AACb,KAAA;;;;WAMD,KAAAG,GAAAA;AACE,QAAA,OAAIF,IAAKC,CAAAA,eAAAA,EAAAA,GACA,MAASD,GAAAA,IAAA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,CAAA,CAAA,CAAA,CAAA,CAAA;;AAGzBC,IAAAA,eAAAA,CAAgB,gBAAkB3oB,EAAAA,CAAAA,EAAS,EAC3C2oB,CAAAA,EAAAA,eAAAA,CAAgB,kBAAkB3oB,CAAS,EAAA,SAAA,CAAA,CAAA;AAC7C,CCzCAioB,EAAAA;;;;"} \ No newline at end of file diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/index.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.d.ts new file mode 100644 index 0000000..a6d5c1f --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.d.ts @@ -0,0 +1,2030 @@ +/** + * Firestore Lite + * + * @remarks Firestore Lite is a small online-only SDK that allows read + * and write access to your Firestore database. All operations connect + * directly to the backend, and `onSnapshot()` APIs are not supported. + * @packageDocumentation + */ +import { FirebaseApp } from '@firebase/app'; +import { LogLevelString as LogLevel } from '@firebase/logger'; +import { EmulatorMockTokenOptions } from '@firebase/util'; +import { FirebaseError } from '@firebase/util'; + +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend. + */ +export declare function addDoc(reference: CollectionReference, data: WithFieldValue): Promise>; +/** + * Returns a new map where every key is prefixed with the outer key appended + * to a dot. + */ +export declare type AddPrefixToKeys> = { + [K in keyof T & string as `${Prefix}.${K}`]+?: string extends K ? any : T[K]; +}; +/** + * Represents an aggregation that can be performed by Firestore. + */ +export declare class AggregateField { + /** A type string to uniquely identify instances of this class. */ + readonly type = "AggregateField"; + /** Indicates the aggregation operation of this AggregateField. */ + readonly aggregateType: AggregateType; +} +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ +export declare function aggregateFieldEqual(left: AggregateField, right: AggregateField): boolean; +/** + * The union of all `AggregateField` types that are supported by Firestore. + */ +export declare type AggregateFieldType = ReturnType | ReturnType | ReturnType; +/** + * The results of executing an aggregation query. + */ +export declare class AggregateQuerySnapshot { + /** A type string to uniquely identify instances of this class. */ + readonly type = "AggregateQuerySnapshot"; + /** + * The underlying query over which the aggregations recorded in this + * `AggregateQuerySnapshot` were performed. + */ + readonly query: Query; + private constructor(); + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ + data(): AggregateSpecData; +} +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ +export declare function aggregateQuerySnapshotEqual(left: AggregateQuerySnapshot, right: AggregateQuerySnapshot): boolean; +/** + * Specifies a set of aggregations and their aliases. + */ +export declare interface AggregateSpec { + [field: string]: AggregateFieldType; +} +/** + * A type whose keys are taken from an `AggregateSpec`, and whose values are the + * result of the aggregation performed by the corresponding `AggregateField` + * from the input `AggregateSpec`. + */ +export declare type AggregateSpecData = { + [P in keyof T]: T[P] extends AggregateField ? U : never; +}; +/** + * Union type representing the aggregate type to be performed. + */ +export declare type AggregateType = 'count' | 'avg' | 'sum'; +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +export declare function and(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; +/** + * Returns a special value that can be used with {@link (setDoc:1)} or {@link + * updateDoc:1} that tells the server to remove the given elements from any + * array value that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is not + * already an array it will be overwritten with an empty array. + * + * @param elements - The elements to remove from the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +export declare function arrayRemove(...elements: unknown[]): FieldValue; +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array + * value that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements - The elements to union into the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()`. + */ +export declare function arrayUnion(...elements: unknown[]): FieldValue; +/* Excluded from this release type: AuthTokenFactory */ +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ +export declare function average(field: string | FieldPath): AggregateField; +/** + * An immutable object representing an array of bytes. + */ +export declare class Bytes { + private constructor(); + /** + * Creates a new `Bytes` object from the given Base64 string, converting it to + * bytes. + * + * @param base64 - The Base64 string used to create the `Bytes` object. + */ + static fromBase64String(base64: string): Bytes; + /** + * Creates a new `Bytes` object from the given Uint8Array. + * + * @param array - The Uint8Array used to create the `Bytes` object. + */ + static fromUint8Array(array: Uint8Array): Bytes; + /** + * Returns the underlying bytes as a Base64-encoded string. + * + * @returns The Base64-encoded string created from the `Bytes` object. + */ + toBase64(): string; + /** + * Returns the underlying bytes in a new `Uint8Array`. + * + * @returns The Uint8Array created from the `Bytes` object. + */ + toUint8Array(): Uint8Array; + /** + * Returns a string representation of the `Bytes` object. + * + * @returns A string representation of the `Bytes` object. + */ + toString(): string; + /** + * Returns true if this `Bytes` object is equal to the provided one. + * + * @param other - The `Bytes` object to compare against. + * @returns true if this `Bytes` object is equal to the provided one. + */ + isEqual(other: Bytes): boolean; + /** + * Returns a JSON-serializable representation of this `Bytes` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}. + * + * @param json a JSON object represention of a `Bytes` instance + * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): Bytes; +} +/** + * Helper for calculating the nested fields for a given type T1. This is needed + * to distribute union types such as `undefined | {...}` (happens for optional + * props) or `{a: A} | {b: B}`. + * + * In this use case, `V` is used to distribute the union types of `T[K]` on + * `Record`, since `T[K]` is evaluated as an expression and not distributed. + * + * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types + */ +export declare type ChildUpdateFields = V extends Record ? AddPrefixToKeys> : never; +/** + * Gets a `CollectionReference` instance that refers to the collection at + * the specified absolute path. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments to apply relative to the first + * argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(firestore: Firestore, path: string, ...pathSegments: string[]): CollectionReference; +/** + * Gets a `CollectionReference` instance that refers to a subcollection of + * `reference` at the specified relative path. + * + * @param reference - A reference to a collection. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments to apply relative to the first + * argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(reference: CollectionReference, path: string, ...pathSegments: string[]): CollectionReference; +/** + * Gets a `CollectionReference` instance that refers to a subcollection of + * `reference` at the specified relative path. + * + * @param reference - A reference to a Firestore document. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(reference: DocumentReference, path: string, ...pathSegments: string[]): CollectionReference; +/** + * Creates and returns a new `Query` instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given `collectionId`. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param collectionId - Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `Query`. + */ +export declare function collectionGroup(firestore: Firestore, collectionId: string): Query; +/** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using {@link (query:1)}). + */ +export declare class CollectionReference extends Query { + /** The type of this Firestore reference. */ + readonly type = "collection"; + private constructor(); + /** The collection's identifier. */ + get id(): string; + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ + get path(): string; + /** + * A reference to the containing `DocumentReference` if this is a + * subcollection. If this isn't a subcollection, the reference is null. + */ + get parent(): DocumentReference | null; + /** + * Applies a custom data converter to this `CollectionReference`, allowing you + * to use your own custom model objects with Firestore. When you call {@link + * addDoc} with the returned `CollectionReference` instance, the provided + * converter will convert between Firestore data of type `NewDbModelType` and + * your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `CollectionReference` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter): CollectionReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `CollectionReference` that does not + * use a converter. + */ + withConverter(converter: null): CollectionReference; +} +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ +export declare function connectFirestoreEmulator(firestore: Firestore, host: string, port: number, options?: { + mockUserToken?: EmulatorMockTokenOptions | string; +}): void; +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ +export declare function count(): AggregateField; +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * The deletion will only be reflected in document reads that occur after the + * returned promise resolves. If the client is offline, the + * delete fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to delete. + * @returns A `Promise` resolved once the document has been successfully + * deleted from the backend. + */ +export declare function deleteDoc(reference: DocumentReference): Promise; +/** + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. + */ +export declare function deleteField(): FieldValue; +/** + * Gets a `DocumentReference` instance that refers to the document at the + * specified absolute path. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param path - A slash-separated path to a document. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(firestore: Firestore, path: string, ...pathSegments: string[]): DocumentReference; +/** + * Gets a `DocumentReference` instance that refers to a document within + * `reference` at the specified relative path. If no path is specified, an + * automatically-generated unique ID will be used for the returned + * `DocumentReference`. + * + * @param reference - A reference to a collection. + * @param path - A slash-separated path to a document. Has to be omitted to use + * auto-generated IDs. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(reference: CollectionReference, path?: string, ...pathSegments: string[]): DocumentReference; +/** + * Gets a `DocumentReference` instance that refers to a document within + * `reference` at the specified relative path. + * + * @param reference - A reference to a Firestore document. + * @param path - A slash-separated path to a document. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(reference: DocumentReference, path: string, ...pathSegments: string[]): DocumentReference; +/** + * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to + * values. + */ +export declare interface DocumentData { + /** A mapping between a field and its value. */ + [field: string]: any; +} +/** + * Returns a special sentinel `FieldPath` to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ +export declare function documentId(): FieldPath; +/** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. + */ +export declare class DocumentReference { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter | null; + /** The type of this Firestore reference. */ + readonly type = "document"; + /** + * The {@link Firestore} instance the document is in. + * This is useful for performing transactions, for example. + */ + readonly firestore: Firestore; + private constructor(); + /** + * The document's identifier within its collection. + */ + get id(): string; + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ + get path(): string; + /** + * The collection this `DocumentReference` belongs to. + */ + get parent(): CollectionReference; + /** + * Applies a custom data converter to this `DocumentReference`, allowing you + * to use your own custom model objects with Firestore. When you call {@link + * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference` + * instance, the provided converter will convert between Firestore data of + * type `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `DocumentReference` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter): DocumentReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `DocumentReference` that does not + * use a converter. + */ + withConverter(converter: null): DocumentReference; + /** + * Returns a JSON-serializable representation of this `DocumentReference` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `DocumentReference` instance from a JSON object created by + * {@link DocumentReference.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json a JSON object represention of a `DocumentReference` instance + * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(firestore: Firestore, json: object): DocumentReference; + /** + * Builds a `DocumentReference` instance from a JSON object created by + * {@link DocumentReference.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json a JSON object represention of a `DocumentReference` instance + * @param converter - Converts objects to and from Firestore. + * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(firestore: Firestore, json: object, converter: FirestoreDataConverter): DocumentReference; +} +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ +export declare class DocumentSnapshot { + protected constructor(); + /** Property of the `DocumentSnapshot` that provides the document's ID. */ + get id(): string; + /** + * The `DocumentReference` for the document included in the `DocumentSnapshot`. + */ + get ref(): DocumentReference; + /** + * Signals whether or not the document at the snapshot's location exists. + * + * @returns true if the document exists. + */ + exists(): this is QueryDocumentSnapshot; + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * @returns An `Object` containing all fields in the document or `undefined` + * if the document doesn't exist. + */ + data(): AppModelType | undefined; + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + get(fieldPath: string | FieldPath): any; +} +export { EmulatorMockTokenOptions }; +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided document (inclusive). The end position is relative to the order + * of the query. The document must contain all of the fields provided in the + * orderBy of the query. + * + * @param snapshot - The snapshot of the document to end at. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endAt(snapshot: DocumentSnapshot): QueryEndAtConstraint; +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided fields relative to the order of the query. The order of the field + * values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to end this query at, in order + * of the query's order by. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endAt(...fieldValues: unknown[]): QueryEndAtConstraint; +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided document (exclusive). The end position is relative to the + * order of the query. The document must contain all of the fields provided in + * the orderBy of the query. + * + * @param snapshot - The snapshot of the document to end before. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endBefore(snapshot: DocumentSnapshot): QueryEndAtConstraint; +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to end this query before, in order + * of the query's order by. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endBefore(...fieldValues: unknown[]): QueryEndAtConstraint; +/** + * A `FieldPath` refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + * + * Create a `FieldPath` by providing field names. If more than one field + * name is provided, the path will point to a nested field in a document. + */ +export declare class FieldPath { + /** + * Creates a `FieldPath` from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames - A list of field names. + */ + constructor(...fieldNames: string[]); + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other - The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ + isEqual(other: FieldPath): boolean; +} +/** + * Sentinel values that can be used when writing document fields with `set()` + * or `update()`. + */ +export declare abstract class FieldValue { + private constructor(); + /** Compares `FieldValue`s for equality. */ + abstract isEqual(other: FieldValue): boolean; +} +/* Excluded from this release type: _FirebaseService */ +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ +export declare class Firestore { + /** + * Whether it's a Firestore or Firestore Lite instance. + */ + type: 'firestore-lite' | 'firestore'; + private constructor(); + /** + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service + * instance. + */ + get app(): FirebaseApp; + /** Returns a JSON-serializable representation of this `Firestore` instance. */ + toJSON(): object; +} +/** + * Converter used by `withConverter()` to transform user objects of type + * `AppModelType` into Firestore data of type `DbModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * In this context, an "AppModel" is a class that is used in an application to + * package together related information and functionality. Such a class could, + * for example, have properties with complex, nested data types, properties used + * for memoization, properties of types not supported by Firestore (such as + * `symbol` and `bigint`), and helper functions that perform compound + * operations. Such classes are not suitable and/or possible to store into a + * Firestore database. Instead, instances of such classes need to be converted + * to "plain old JavaScript objects" (POJOs) with exclusively primitive + * properties, potentially nested inside other POJOs or arrays of POJOs. In this + * context, this type is referred to as the "DbModel" and would be an object + * suitable for persisting into Firestore. For convenience, applications can + * implement `FirestoreDataConverter` and register the converter with Firestore + * objects, such as `DocumentReference` or `Query`, to automatically convert + * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel` + * to `AppModel` when retrieving from Firestore. + * + * @example + * + * Simple Example + * + * ```typescript + * const numberConverter = { + * toFirestore(value: WithFieldValue) { + * return { value }; + * }, + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) { + * return snapshot.data(options).value as number; + * } + * }; + * + * async function simpleDemo(db: Firestore): Promise { + * const documentRef = doc(db, 'values/value123').withConverter(numberConverter); + * + * // converters are used with `setDoc`, `addDoc`, and `getDoc` + * await setDoc(documentRef, 42); + * const snapshot1 = await getDoc(documentRef); + * assertEqual(snapshot1.data(), 42); + * + * // converters are not used when writing data with `updateDoc` + * await updateDoc(documentRef, { value: 999 }); + * const snapshot2 = await getDoc(documentRef); + * assertEqual(snapshot2.data(), 999); + * } + * ``` + * + * Advanced Example + * + * ```typescript + * // The Post class is a model that is used by our application. + * // This class may have properties and methods that are specific + * // to our application execution, which do not need to be persisted + * // to Firestore. + * class Post { + * constructor( + * readonly title: string, + * readonly author: string, + * readonly lastUpdatedMillis: number + * ) {} + * toString(): string { + * return `${this.title} by ${this.author}`; + * } + * } + * + * // The PostDbModel represents how we want our posts to be stored + * // in Firestore. This DbModel has different properties (`ttl`, + * // `aut`, and `lut`) from the Post class we use in our application. + * interface PostDbModel { + * ttl: string; + * aut: { firstName: string; lastName: string }; + * lut: Timestamp; + * } + * + * // The `PostConverter` implements `FirestoreDataConverter` and specifies + * // how the Firestore SDK can convert `Post` objects to `PostDbModel` + * // objects and vice versa. + * class PostConverter implements FirestoreDataConverter { + * toFirestore(post: WithFieldValue): WithFieldValue { + * return { + * ttl: post.title, + * aut: this._autFromAuthor(post.author), + * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis) + * }; + * } + * + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post { + * const data = snapshot.data(options) as PostDbModel; + * const author = `${data.aut.firstName} ${data.aut.lastName}`; + * return new Post(data.ttl, author, data.lut.toMillis()); + * } + * + * _autFromAuthor( + * author: string | FieldValue + * ): { firstName: string; lastName: string } | FieldValue { + * if (typeof author !== 'string') { + * // `author` is a FieldValue, so just return it. + * return author; + * } + * const [firstName, lastName] = author.split(' '); + * return {firstName, lastName}; + * } + * + * _lutFromLastUpdatedMillis( + * lastUpdatedMillis: number | FieldValue + * ): Timestamp | FieldValue { + * if (typeof lastUpdatedMillis !== 'number') { + * // `lastUpdatedMillis` must be a FieldValue, so just return it. + * return lastUpdatedMillis; + * } + * return Timestamp.fromMillis(lastUpdatedMillis); + * } + * } + * + * async function advancedDemo(db: Firestore): Promise { + * // Create a `DocumentReference` with a `FirestoreDataConverter`. + * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter()); + * + * // The `data` argument specified to `setDoc()` is type checked by the + * // TypeScript compiler to be compatible with `Post`. Since the `data` + * // argument is typed as `WithFieldValue` rather than just `Post`, + * // this allows properties of the `data` argument to also be special + * // Firestore values that perform server-side mutations, such as + * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`. + * await setDoc(documentRef, { + * title: 'My Life', + * author: 'Foo Bar', + * lastUpdatedMillis: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `setDoc()` is _not_ compatible with `WithFieldValue`. This + * // type checking prevents the caller from specifying objects with incorrect + * // properties or property values. + * // @ts-expect-error "Argument of type { ttl: string; } is not assignable + * // to parameter of type WithFieldValue" + * await setDoc(documentRef, { ttl: 'The Title' }); + * + * // When retrieving a document with `getDoc()` the `DocumentSnapshot` + * // object's `data()` method returns a `Post`, rather than a generic object, + * // which would have been returned if the `DocumentReference` did _not_ have a + * // `FirestoreDataConverter` attached to it. + * const snapshot1: DocumentSnapshot = await getDoc(documentRef); + * const post1: Post = snapshot1.data()!; + * if (post1) { + * assertEqual(post1.title, 'My Life'); + * assertEqual(post1.author, 'Foo Bar'); + * } + * + * // The `data` argument specified to `updateDoc()` is type checked by the + * // TypeScript compiler to be compatible with `PostDbModel`. Note that + * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`, + * // the `data` argument to `updateDoc()` must be compatible with + * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed + * // as `WithFieldValue` rather than just `PostDbModel`, this + * // allows properties of the `data` argument to also be those special + * // Firestore values, like `arrayRemove()`, `deleteField()`, and + * // `serverTimestamp()`. + * await updateDoc(documentRef, { + * 'aut.firstName': 'NewFirstName', + * lut: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `updateDoc()` is _not_ compatible with `WithFieldValue`. + * // This type checking prevents the caller from specifying objects with + * // incorrect properties or property values. + * // @ts-expect-error "Argument of type { title: string; } is not assignable + * // to parameter of type WithFieldValue" + * await updateDoc(documentRef, { title: 'New Title' }); + * const snapshot2: DocumentSnapshot = await getDoc(documentRef); + * const post2: Post = snapshot2.data()!; + * if (post2) { + * assertEqual(post2.title, 'My Life'); + * assertEqual(post2.author, 'NewFirstName Bar'); + * } + * } + * ``` + */ +export declare interface FirestoreDataConverter { + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link @firebase/firestore/lite#(setDoc:1)}, + * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and + * {@link @firebase/firestore/lite#(Transaction.set:1)}. + * + * The `WithFieldValue` type extends `T` to also allow FieldValues such as + * {@link (deleteField:1)} to be used as property values. + */ + toFirestore(modelObject: WithFieldValue): WithFieldValue; + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link @firebase/firestore/lite#(setDoc:1)}, + * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and + * {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true` + * or `mergeFields`. + * + * The `PartialWithFieldValue` type extends `Partial` to allow + * FieldValues such as {@link (arrayUnion:1)} to be used as property values. + * It also supports nested `Partial` by allowing nested fields to be + * omitted. + */ + toFirestore(modelObject: PartialWithFieldValue, options: SetOptions): PartialWithFieldValue; + /** + * Called by the Firestore SDK to convert Firestore data into an object of + * type `AppModelType`. You can access your data by calling: + * `snapshot.data()`. + * + * + * Generally, the data returned from `snapshot.data()` can be cast to + * `DbModelType`; however, this is not guaranteed because Firestore does not + * enforce a schema on the database. For example, writes from a previous + * version of the application or writes from another client that did not use a + * type converter could have written data with different properties and/or + * property types. The implementation will need to choose whether to + * gracefully recover from non-conforming data or throw an error. + * + * @param snapshot - A `QueryDocumentSnapshot` containing your data and + * metadata. + */ + fromFirestore(snapshot: QueryDocumentSnapshot): AppModelType; +} +/** An error returned by a Firestore operation. */ +export declare class FirestoreError extends FirebaseError { + /** + * The backend error code associated with this error. + */ + readonly code: FirestoreErrorCode; + /** + * A custom error description. + */ + readonly message: string; + /** The stack of the error. */ + readonly stack?: string; + private constructor(); +} +/** + * The set of Firestore status codes. The codes are the same at the ones + * exposed by gRPC here: + * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md + * + * Possible values: + * - 'cancelled': The operation was cancelled (typically by the caller). + * - 'unknown': Unknown error or an error from a different error domain. + * - 'invalid-argument': Client specified an invalid argument. Note that this + * differs from 'failed-precondition'. 'invalid-argument' indicates + * arguments that are problematic regardless of the state of the system + * (e.g. an invalid field name). + * - 'deadline-exceeded': Deadline expired before operation could complete. + * For operations that change the state of the system, this error may be + * returned even if the operation has completed successfully. For example, + * a successful response from a server could have been delayed long enough + * for the deadline to expire. + * - 'not-found': Some requested document was not found. + * - 'already-exists': Some document that we attempted to create already + * exists. + * - 'permission-denied': The caller does not have permission to execute the + * specified operation. + * - 'resource-exhausted': Some resource has been exhausted, perhaps a + * per-user quota, or perhaps the entire file system is out of space. + * - 'failed-precondition': Operation was rejected because the system is not + * in a state required for the operation's execution. + * - 'aborted': The operation was aborted, typically due to a concurrency + * issue like transaction aborts, etc. + * - 'out-of-range': Operation was attempted past the valid range. + * - 'unimplemented': Operation is not implemented or not supported/enabled. + * - 'internal': Internal errors. Means some invariants expected by + * underlying system has been broken. If you see one of these errors, + * something is very broken. + * - 'unavailable': The service is currently unavailable. This is most likely + * a transient condition and may be corrected by retrying with a backoff. + * - 'data-loss': Unrecoverable data loss or corruption. + * - 'unauthenticated': The request does not have valid authentication + * credentials for the operation. + */ +export declare type FirestoreErrorCode = 'cancelled' | 'unknown' | 'invalid-argument' | 'deadline-exceeded' | 'not-found' | 'already-exists' | 'permission-denied' | 'resource-exhausted' | 'failed-precondition' | 'aborted' | 'out-of-range' | 'unimplemented' | 'internal' | 'unavailable' | 'data-loss' | 'unauthenticated'; +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ +export declare class GeoPoint { + /** + * Creates a new immutable `GeoPoint` object with the provided latitude and + * longitude values. + * @param latitude - The latitude as number between -90 and 90. + * @param longitude - The longitude as number between -180 and 180. + */ + constructor(latitude: number, longitude: number); + /** + * The latitude of this `GeoPoint` instance. + */ + get latitude(): number; + /** + * The longitude of this `GeoPoint` instance. + */ + get longitude(): number; + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other - The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ + isEqual(other: GeoPoint): boolean; + /** + * Returns a JSON-serializable representation of this `GeoPoint` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): { + latitude: number; + longitude: number; + type: string; + }; + /** + * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}. + * + * @param json a JSON object represention of a `GeoPoint` instance + * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): GeoPoint; +} +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregate(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ +export declare function getAggregate(query: Query, aggregateSpec: AggregateSpecType): Promise>; +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ +export declare function getCount(query: Query): Promise; +}, AppModelType, DbModelType>>; +/** + * Reads the document referred to by the specified document reference. + * + * All documents are directly fetched from the server, even if the document was + * previously read or modified. Recent modifications are only reflected in the + * retrieved `DocumentSnapshot` if they have already been applied by the + * backend. If the client is offline, the read fails. If you like to use + * caching or see local modifications, please use the full Firestore SDK. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the current + * document contents. + */ +export declare function getDoc(reference: DocumentReference): Promise>; +/** + * Executes the query and returns the results as a {@link QuerySnapshot}. + * + * All queries are executed directly by the server, even if the query was + * previously executed. Recent modifications are only reflected in the retrieved + * results if they have already been applied by the backend. If the client is + * offline, the operation fails. To see previously cached result and local + * modifications, use the full Firestore SDK. + * + * @param query - The `Query` to execute. + * @returns A Promise that will be resolved with the results of the query. + */ +export declare function getDocs(query: Query): Promise>; +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @returns The {@link Firestore} instance of the provided app. + */ +export declare function getFirestore(): Firestore; +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @returns The {@link Firestore} instance of the provided app. + */ +export declare function getFirestore(app: FirebaseApp): Firestore; +/** + * Returns the existing {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param databaseId - The name of the database. + * @returns The {@link Firestore} instance of the provided app. + * @beta + */ +export declare function getFirestore(databaseId: string): Firestore; +/** + * Returns the existing {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @param databaseId - The name of the database. + * @returns The {@link Firestore} instance of the provided app. + * @beta + */ +export declare function getFirestore(app: FirebaseApp, databaseId: string): Firestore; +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by + * the given value. + * + * If either the operand or the current field value uses floating point + * precision, all arithmetic follows IEEE 754 semantics. If both values are + * integers, values outside of JavaScript's safe number range + * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to + * precision loss. Furthermore, once processed by the Firestore backend, all + * integer operations are capped between -2^63 and 2^63-1. + * + * If the current field value is not of type `number`, or if the field does not + * yet exist, the transformation sets the field to the given value. + * + * @param n - The value to increment by. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +export declare function increment(n: number): FieldValue; +/** + * Initializes a new instance of Cloud Firestore with the provided settings. + * Can only be called before any other functions, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will + * be associated. + * @param settings - A settings object to configure the `Firestore` instance. + * @returns A newly initialized `Firestore` instance. + */ +export declare function initializeFirestore(app: FirebaseApp, settings: Settings): Firestore; +/** + * Initializes a new instance of Cloud Firestore with the provided settings. + * Can only be called before any other functions, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will + * be associated. + * @param settings - A settings object to configure the `Firestore` instance. + * @param databaseId - The name of the database. + * @returns A newly initialized `Firestore` instance. + * @beta + */ +export declare function initializeFirestore(app: FirebaseApp, settings: Settings, databaseId?: string): Firestore; +/** + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +export declare function limit(limit: number): QueryLimitConstraint; +/** + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. + * + * You must specify at least one `orderBy` clause for `limitToLast` queries, + * otherwise an exception will be thrown during execution. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +export declare function limitToLast(limit: number): QueryLimitConstraint; +export { LogLevel }; +/** + * For each field (e.g. 'bar'), find all nested keys (e.g. {'bar.baz': T1, + * 'bar.qux': T2}). Intersect them together to make a single map containing + * all possible keys that are all marked as optional + */ +export declare type NestedUpdateFields> = UnionToIntersection<{ + [K in keyof T & string]: ChildUpdateFields; +}[keyof T & string]>; +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +export declare function or(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; +/** + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the + * specified field, optionally in descending order instead of ascending. + * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * + * @param fieldPath - The field to sort by. + * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @returns The created {@link QueryOrderByConstraint}. + */ +export declare function orderBy(fieldPath: string | FieldPath, directionStr?: OrderByDirection): QueryOrderByConstraint; +/** + * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc' + * (descending or ascending). + */ +export declare type OrderByDirection = 'desc' | 'asc'; +/** + * Similar to TypeScript's `Partial`, but allows nested fields to be + * omitted and FieldValues to be passed in as property values. + */ +export declare type PartialWithFieldValue = Partial | (T extends Primitive ? T : T extends {} ? { + [K in keyof T]?: PartialWithFieldValue | FieldValue; +} : never); +/** + * These types primarily exist to support the `UpdateData`, + * `WithFieldValue`, and `PartialWithFieldValue` types and are not consumed + * directly by the end developer. + */ +/** Primitive types. */ +export declare type Primitive = string | number | boolean | undefined | null; +/** + * A `Query` refers to a query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ +export declare class Query { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter | null; + /** The type of this Firestore reference. */ + readonly type: 'query' | 'collection'; + /** + * The `Firestore` instance for the Firestore database (useful for performing + * transactions, etc.). + */ + readonly firestore: Firestore; + protected constructor(); + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `Query` that does not use a + * converter. + */ + withConverter(converter: null): Query; + /** + * Applies a custom data converter to this query, allowing you to use your own + * custom model objects with Firestore. When you call {@link getDocs} with + * the returned query, the provided converter will convert between Firestore + * data of type `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `Query` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter): Query; +} +/** + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. + * + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to + * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or + * {@link or}. + * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to + * apply (e.g. {@link orderBy}, {@link limit}). + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query(query: Query, compositeFilter: QueryCompositeFilterConstraint, ...queryConstraints: QueryNonFilterConstraint[]): Query; +/** + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. + * + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param queryConstraints - The list of {@link QueryConstraint}s to apply. + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query(query: Query, ...queryConstraints: QueryConstraint[]): Query; +/** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ +export declare class QueryCompositeFilterConstraint { + /** The type of this query constraint */ + readonly type: 'or' | 'and'; +} +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Firestore query. `QueryConstraint`s are created by invoking {@link where}, + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that + * also contains this `QueryConstraint`. + */ +export declare abstract class QueryConstraint { + /** The type of this query constraint */ + abstract readonly type: QueryConstraintType; +} +/** Describes the different query constraints available in this SDK. */ +export declare type QueryConstraintType = 'where' | 'orderBy' | 'limit' | 'limitToLast' | 'startAt' | 'startAfter' | 'endAt' | 'endBefore'; +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ +export declare class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * @override + * @returns An `Object` containing all fields in the document. + */ + data(): AppModelType; +} +/** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ +export declare class QueryEndAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'endBefore' | 'endAt'; +} +/** + * Returns true if the provided queries point to the same collection and apply + * the same constraints. + * + * @param left - A `Query` to compare. + * @param right - A `Query` to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +export declare function queryEqual(left: Query, right: Query): boolean; +/** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ +export declare class QueryFieldFilterConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type = "where"; +} +/** + * `QueryFilterConstraint` is a helper union type that represents + * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}. + */ +export declare type QueryFilterConstraint = QueryFieldFilterConstraint | QueryCompositeFilterConstraint; +/** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ +export declare class QueryLimitConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'limit' | 'limitToLast'; +} +/** + * `QueryNonFilterConstraint` is a helper union type that represents + * QueryConstraints which are used to narrow or order the set of documents, + * but that do not explicitly filter on a document field. + * `QueryNonFilterConstraint`s are created by invoking {@link orderBy}, + * {@link (startAt:1)}, {@link (startAfter:1)}, {@link (endBefore:1)}, {@link (endAt:1)}, + * {@link limit} or {@link limitToLast} and can then be passed to {@link (query:1)} + * to create a new query instance that also contains the `QueryConstraint`. + */ +export declare type QueryNonFilterConstraint = QueryOrderByConstraint | QueryLimitConstraint | QueryStartAtConstraint | QueryEndAtConstraint; +/** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ +export declare class QueryOrderByConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type = "orderBy"; +} +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ +export declare class QuerySnapshot { + /** + * The query on which you called {@link getDocs} in order to get this + * `QuerySnapshot`. + */ + readonly query: Query; + private constructor(); + /** An array of all the documents in the `QuerySnapshot`. */ + get docs(): Array>; + /** The number of documents in the `QuerySnapshot`. */ + get size(): number; + /** True if there are no documents in the `QuerySnapshot`. */ + get empty(): boolean; + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ + forEach(callback: (result: QueryDocumentSnapshot) => void, thisArg?: unknown): void; +} +/** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ +export declare class QueryStartAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'startAt' | 'startAfter'; +} +/** + * Returns true if the provided references are equal. + * + * @param left - A reference to compare. + * @param right - A reference to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +export declare function refEqual(left: DocumentReference | CollectionReference, right: DocumentReference | CollectionReference): boolean; +/* Excluded from this release type: ResourcePath */ +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ +export declare function runTransaction(firestore: Firestore, updateFunction: (transaction: Transaction) => Promise, options?: TransactionOptions): Promise; +/** + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to + * include a server-generated timestamp in the written data. + */ +export declare function serverTimestamp(): FieldValue; +/** + * Writes to the document referred to by the specified `DocumentReference`. If + * the document does not yet exist, it will be created. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function setDoc(reference: DocumentReference, data: WithFieldValue): Promise; +/** + * Writes to the document referred to by the specified `DocumentReference`. If + * the document does not yet exist, it will be created. If you provide `merge` + * or `mergeFields`, the provided data can be merged into an existing document. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function setDoc(reference: DocumentReference, data: PartialWithFieldValue, options: SetOptions): Promise; +/** + * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). + * + * @param logLevel - The verbosity you set for activity and error logging. Can + * be any of the following values: + * + *
    + *
  • `debug` for the most verbose logging level, primarily for + * debugging.
  • + *
  • `error` to log errors only.
  • + *
  • `silent` to turn off logging.
  • + *
+ */ +export declare function setLogLevel(logLevel: LogLevel): void; +/** + * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link + * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be + * configured to perform granular merges instead of overwriting the target + * documents in their entirety by providing a `SetOptions` with `merge: true`. + * + * @param merge - Changes the behavior of a `setDoc()` call to only replace the + * values specified in its data argument. Fields omitted from the `setDoc()` + * call remain untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace + * the specified field paths. Any field path that is not specified is ignored + * and remains untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + */ +export declare type SetOptions = { + readonly merge?: boolean; +} | { + readonly mergeFields?: Array; +}; +/** + * Specifies custom configurations for your Cloud Firestore instance. + * You must set these before invoking any other methods. + */ +export declare interface Settings { + /** The hostname to connect to. */ + host?: string; + /** Whether to use SSL when connecting. */ + ssl?: boolean; + /** + * Whether to skip nested properties that are set to `undefined` during + * object serialization. If set to `true`, these properties are skipped + * and not written to Firestore. If set to `false` or omitted, the SDK + * throws an exception when it encounters properties of type `undefined`. + */ + ignoreUndefinedProperties?: boolean; +} +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ +export declare function snapshotEqual(left: DocumentSnapshot | QuerySnapshot, right: DocumentSnapshot | QuerySnapshot): boolean; +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided document (exclusive). The starting position is + * relative to the order of the query. The document must contain all of the + * fields provided in the orderBy of the query. + * + * @param snapshot - The snapshot of the document to start after. + * @returns A {@link QueryStartAtConstraint} to pass to `query()` + */ +export declare function startAfter(snapshot: DocumentSnapshot): QueryStartAtConstraint; +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided fields relative to the order of the query. The order + * of the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to start this query after, in order + * of the query's order by. + * @returns A {@link QueryStartAtConstraint} to pass to `query()` + */ +export declare function startAfter(...fieldValues: unknown[]): QueryStartAtConstraint; +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided document (inclusive). The starting position is relative + * to the order of the query. The document must contain all of the fields + * provided in the `orderBy` of this query. + * + * @param snapshot - The snapshot of the document to start at. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. + */ +export declare function startAt(snapshot: DocumentSnapshot): QueryStartAtConstraint; +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to start this query at, in order + * of the query's order by. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. + */ +export declare function startAt(...fieldValues: unknown[]): QueryStartAtConstraint; +/** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ +export declare function sum(field: string | FieldPath): AggregateField; +/** + * Terminates the provided `Firestore` instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` functions + * may be used. Any other function will throw a `FirestoreError`. Termination + * does not cancel any pending writes, and any promises that are awaiting a + * response from the server will not be resolved. + * + * To restart after termination, create a new instance of `Firestore` with + * {@link (getFirestore:1)}. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all of + * its resources or in combination with {@link clearIndexedDbPersistence} to + * ensure that all local state is destroyed between test runs. + * + * @param firestore - The `Firestore` instance to terminate. + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ +export declare function terminate(firestore: Firestore): Promise; +/** + * A `Timestamp` represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. + * + * It is encoded using the Proleptic Gregorian Calendar which extends the + * Gregorian calendar backwards to year one. It is encoded assuming all minutes + * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59.999999999Z. + * + * For examples and further specifications, refer to the + * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. + */ +export declare class Timestamp { + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + readonly seconds: number; + /** + * The fractions of a second at nanosecond resolution.* + */ + readonly nanoseconds: number; + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns a new timestamp representing the current date. + */ + static now(): Timestamp; + /** + * Creates a new timestamp from the given date. + * + * @param date - The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the given + * date. + */ + static fromDate(date: Date): Timestamp; + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds - Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the given + * number of milliseconds. + */ + static fromMillis(milliseconds: number): Timestamp; + /** + * Creates a new timestamp. + * + * @param seconds - The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds - The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ + constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + seconds: number, + /** + * The fractions of a second at nanosecond resolution.* + */ + nanoseconds: number); + /** + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ + toDate(): Date; + /** + * Converts a `Timestamp` to a numeric timestamp (in milliseconds since + * epoch). This operation causes a loss of precision. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ + toMillis(): number; + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other - The `Timestamp` to compare against. + * @returns true if this `Timestamp` is equal to the provided one. + */ + isEqual(other: Timestamp): boolean; + /** Returns a textual representation of this `Timestamp`. */ + toString(): string; + /** + * Returns a JSON-serializable representation of this `Timestamp`. + */ + toJSON(): { + seconds: number; + nanoseconds: number; + type: string; + }; + /** + * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}. + */ + static fromJSON(json: object): Timestamp; + /** + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. + */ + valueOf(): string; +} +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ +export declare class Transaction { + private constructor(); + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ + get(documentRef: DocumentReference): Promise>; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: WithFieldValue): this; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * If you provide `merge` or `mergeFields`, the provided data can be merged + * into an existing document. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: PartialWithFieldValue, options: SetOptions): this; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * @param documentRef - A reference to the document to be updated. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, data: UpdateData): this; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * @param documentRef - A reference to the document to be updated. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key/value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): this; + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + delete(documentRef: DocumentReference): this; +} +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options to customize transaction behavior. + */ +export declare interface TransactionOptions { + /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */ + readonly maxAttempts?: number; +} +/** + * Given a union type `U = T1 | T2 | ...`, returns an intersected type + * `(T1 & T2 & ...)`. + * + * Uses distributive conditional types and inference from conditional types. + * This works because multiple candidates for the same type variable in + * contra-variant positions causes an intersection type to be inferred. + * https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-inference-in-conditional-types + * https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type + */ +export declare type UnionToIntersection = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never; +/** + * Update data (for use with {@link (updateDoc:1)}) that consists of field paths + * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots + * reference nested fields within the document. FieldValues can be passed in + * as property values. + */ +export declare type UpdateData = T extends Primitive ? T : T extends {} ? { + [K in keyof T]?: UpdateData | FieldValue; +} & NestedUpdateFields : Partial; +/** + * Updates fields in the document referred to by the specified + * `DocumentReference`. The update will fail if applied to a document that does + * not exist. + * + * The result of this update will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * update fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to update. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function updateDoc(reference: DocumentReference, data: UpdateData): Promise; +/** + * Updates fields in the document referred to by the specified + * `DocumentReference` The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * The result of this update will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * update fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to update. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function updateDoc(reference: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): Promise; +/** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ +export declare function vector(values?: number[]): VectorValue; +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link vector}. + * + * @class VectorValue + */ +export declare class VectorValue { + /* Excluded from this release type: __constructor */ + /** + * Returns a copy of the raw number array form of the vector. + */ + toArray(): number[]; + /** + * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise. + */ + isEqual(other: VectorValue): boolean; + /** + * Returns a JSON-serializable representation of this `VectorValue` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}. + * + * @param json a JSON object represention of a `VectorValue` instance. + * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): VectorValue; +} +/** + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. + * + * @param fieldPath - The path to compare + * @param opStr - The operation string (e.g "<", "<=", "==", "<", + * "<=", "!="). + * @param value - The value for comparison + * @returns The created {@link QueryFieldFilterConstraint}. + */ +export declare function where(fieldPath: string | FieldPath, opStr: WhereFilterOp, value: unknown): QueryFieldFilterConstraint; +/** + * Filter conditions in a {@link where} clause are specified using the + * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in', + * 'array-contains-any', and 'not-in'. + */ +export declare type WhereFilterOp = '<' | '<=' | '==' | '!=' | '>=' | '>' | 'array-contains' | 'in' | 'array-contains-any' | 'not-in'; +/** + * Allows FieldValues to be passed in as a property value while maintaining + * type safety. + */ +export declare type WithFieldValue = T | (T extends Primitive ? T : T extends {} ? { + [K in keyof T]: WithFieldValue | FieldValue; +} : never); +/** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It + * provides methods for adding writes to the write batch. None of the writes + * will be committed (or visible locally) until {@link WriteBatch.commit} is + * called. + */ +export declare class WriteBatch { + private constructor(); + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: WithFieldValue): WriteBatch; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * If you provide `merge` or `mergeFields`, the provided data can be merged + * into an existing document. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: PartialWithFieldValue, options: SetOptions): WriteBatch; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * @param documentRef - A reference to the document to be updated. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, data: UpdateData): WriteBatch; + /** + * Updates fields in the document referred to by this {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be update by providing dot-separated field path strings + * or by providing `FieldPath` objects. + * + * @param documentRef - A reference to the document to be updated. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): WriteBatch; + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + delete(documentRef: DocumentReference): WriteBatch; + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `Promise` resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit (note that it won't + * resolve while you're offline). + */ + commit(): Promise; +} +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single WriteBatch + * is 500. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `WriteBatch` that can be used to atomically execute multiple + * writes. + */ +export declare function writeBatch(firestore: Firestore): WriteBatch; +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.cjs.js b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.cjs.js new file mode 100644 index 0000000..7f23198 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.cjs.js @@ -0,0 +1,9870 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var app = require('@firebase/app'); +var component = require('@firebase/component'); +var logger = require('@firebase/logger'); +var util$1 = require('util'); +var util = require('@firebase/util'); +var bloomBlob = require('@firebase/webchannel-wrapper/bloom-blob'); +var crypto = require('crypto'); + +const version$1 = "4.9.2"; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Simple wrapper around a nullable UID. Mostly exists to make code more + * readable. + */ +class User { + constructor(uid) { + this.uid = uid; + } + isAuthenticated() { + return this.uid != null; + } + /** + * Returns a key representing this user, suitable for inclusion in a + * dictionary. + */ + toKey() { + if (this.isAuthenticated()) { + return 'uid:' + this.uid; + } + else { + return 'anonymous-user'; + } + } + isEqual(otherUser) { + return otherUser.uid === this.uid; + } +} +/** A user with a null UID. */ +User.UNAUTHENTICATED = new User(null); +// TODO(mikelehen): Look into getting a proper uid-equivalent for +// non-FirebaseAuth providers. +User.GOOGLE_CREDENTIALS = new User('google-credentials-uid'); +User.FIRST_PARTY = new User('first-party-uid'); +User.MOCK_USER = new User('mock-user'); + +const version = "12.3.0"; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let SDK_VERSION = version; +function setSDKVersion(version) { + SDK_VERSION = version; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Formats an object as a JSON string, suitable for logging. */ +function formatJSON(value) { + // util.inspect() results in much more readable output than JSON.stringify() + return util$1.inspect(value, { depth: 100 }); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const logClient = new logger.Logger('@firebase/firestore'); +/** + * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). + * + * @param logLevel - The verbosity you set for activity and error logging. Can + * be any of the following values: + * + *
    + *
  • `debug` for the most verbose logging level, primarily for + * debugging.
  • + *
  • `error` to log errors only.
  • + *
  • `silent` to turn off logging.
  • + *
+ */ +function setLogLevel(logLevel) { + logClient.setLogLevel(logLevel); +} +function logDebug(msg, ...obj) { + if (logClient.logLevel <= logger.LogLevel.DEBUG) { + const args = obj.map(argToString); + logClient.debug(`Firestore (${SDK_VERSION}): ${msg}`, ...args); + } +} +function logError(msg, ...obj) { + if (logClient.logLevel <= logger.LogLevel.ERROR) { + const args = obj.map(argToString); + logClient.error(`Firestore (${SDK_VERSION}): ${msg}`, ...args); + } +} +/** + * @internal + */ +function logWarn(msg, ...obj) { + if (logClient.logLevel <= logger.LogLevel.WARN) { + const args = obj.map(argToString); + logClient.warn(`Firestore (${SDK_VERSION}): ${msg}`, ...args); + } +} +/** + * Converts an additional log parameter to a string representation. + */ +function argToString(obj) { + if (typeof obj === 'string') { + return obj; + } + else { + try { + return formatJSON(obj); + } + catch (e) { + // Converting to JSON failed, just log the object directly + return obj; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function fail(id, messageOrContext, context) { + let message = 'Unexpected state'; + if (typeof messageOrContext === 'string') { + message = messageOrContext; + } + else { + context = messageOrContext; + } + _fail(id, message, context); +} +function _fail(id, failure, context) { + // Log the failure in addition to throw an exception, just in case the + // exception is swallowed. + let message = `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ${failure} (ID: ${id.toString(16)})`; + if (context !== undefined) { + try { + const stringContext = JSON.stringify(context); + message += ' CONTEXT: ' + stringContext; + } + catch (e) { + message += ' CONTEXT: ' + context; + } + } + logError(message); + // NOTE: We don't use FirestoreError here because these are internal failures + // that cannot be handled by the user. (Also it would create a circular + // dependency between the error and assert modules which doesn't work.) + throw new Error(message); +} +function hardAssert(assertion, id, messageOrContext, context) { + let message = 'Unexpected state'; + if (typeof messageOrContext === 'string') { + message = messageOrContext; + } + else { + context = messageOrContext; + } + if (!assertion) { + _fail(id, message, context); + } +} +/** + * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an + * instance of `T` before casting. + */ +function debugCast(obj, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +constructor) { + return obj; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const Code = { + // Causes are copied from: + // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h + /** Not an error; returned on success. */ + OK: 'ok', + /** The operation was cancelled (typically by the caller). */ + CANCELLED: 'cancelled', + /** Unknown error or an error from a different error domain. */ + UNKNOWN: 'unknown', + /** + * Client specified an invalid argument. Note that this differs from + * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are + * problematic regardless of the state of the system (e.g., a malformed file + * name). + */ + INVALID_ARGUMENT: 'invalid-argument', + /** + * Deadline expired before operation could complete. For operations that + * change the state of the system, this error may be returned even if the + * operation has completed successfully. For example, a successful response + * from a server could have been delayed long enough for the deadline to + * expire. + */ + DEADLINE_EXCEEDED: 'deadline-exceeded', + /** Some requested entity (e.g., file or directory) was not found. */ + NOT_FOUND: 'not-found', + /** + * Some entity that we attempted to create (e.g., file or directory) already + * exists. + */ + ALREADY_EXISTS: 'already-exists', + /** + * The caller does not have permission to execute the specified operation. + * PERMISSION_DENIED must not be used for rejections caused by exhausting + * some resource (use RESOURCE_EXHAUSTED instead for those errors). + * PERMISSION_DENIED must not be used if the caller cannot be identified + * (use UNAUTHENTICATED instead for those errors). + */ + PERMISSION_DENIED: 'permission-denied', + /** + * The request does not have valid authentication credentials for the + * operation. + */ + UNAUTHENTICATED: 'unauthenticated', + /** + * Some resource has been exhausted, perhaps a per-user quota, or perhaps the + * entire file system is out of space. + */ + RESOURCE_EXHAUSTED: 'resource-exhausted', + /** + * Operation was rejected because the system is not in a state required for + * the operation's execution. For example, directory to be deleted may be + * non-empty, an rmdir operation is applied to a non-directory, etc. + * + * A litmus test that may help a service implementor in deciding + * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: + * (a) Use UNAVAILABLE if the client can retry just the failing call. + * (b) Use ABORTED if the client should retry at a higher-level + * (e.g., restarting a read-modify-write sequence). + * (c) Use FAILED_PRECONDITION if the client should not retry until + * the system state has been explicitly fixed. E.g., if an "rmdir" + * fails because the directory is non-empty, FAILED_PRECONDITION + * should be returned since the client should not retry unless + * they have first fixed up the directory by deleting files from it. + * (d) Use FAILED_PRECONDITION if the client performs conditional + * REST Get/Update/Delete on a resource and the resource on the + * server does not match the condition. E.g., conflicting + * read-modify-write on the same resource. + */ + FAILED_PRECONDITION: 'failed-precondition', + /** + * The operation was aborted, typically due to a concurrency issue like + * sequencer check failures, transaction aborts, etc. + * + * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, + * and UNAVAILABLE. + */ + ABORTED: 'aborted', + /** + * Operation was attempted past the valid range. E.g., seeking or reading + * past end of file. + * + * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed + * if the system state changes. For example, a 32-bit file system will + * generate INVALID_ARGUMENT if asked to read at an offset that is not in the + * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from + * an offset past the current file size. + * + * There is a fair bit of overlap between FAILED_PRECONDITION and + * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) + * when it applies so that callers who are iterating through a space can + * easily look for an OUT_OF_RANGE error to detect when they are done. + */ + OUT_OF_RANGE: 'out-of-range', + /** Operation is not implemented or not supported/enabled in this service. */ + UNIMPLEMENTED: 'unimplemented', + /** + * Internal errors. Means some invariants expected by underlying System has + * been broken. If you see one of these errors, Something is very broken. + */ + INTERNAL: 'internal', + /** + * The service is currently unavailable. This is a most likely a transient + * condition and may be corrected by retrying with a backoff. + * + * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, + * and UNAVAILABLE. + */ + UNAVAILABLE: 'unavailable', + /** Unrecoverable data loss or corruption. */ + DATA_LOSS: 'data-loss' +}; +/** An error returned by a Firestore operation. */ +class FirestoreError extends util.FirebaseError { + /** @hideconstructor */ + constructor( + /** + * The backend error code associated with this error. + */ + code, + /** + * A custom error description. + */ + message) { + super(code, message); + this.code = code; + this.message = message; + // HACK: We write a toString property directly because Error is not a real + // class and so inheritance does not work correctly. We could alternatively + // do the same "back-door inheritance" trick that FirebaseError does. + this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Deferred { + constructor() { + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + }); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class OAuthToken { + constructor(value, user) { + this.user = user; + this.type = 'OAuth'; + this.headers = new Map(); + this.headers.set('Authorization', `Bearer ${value}`); + } +} +/** + * A CredentialsProvider that always yields an empty token. + * @internal + */ +class EmptyAuthCredentialsProvider { + getToken() { + return Promise.resolve(null); + } + invalidateToken() { } + start(asyncQueue, changeListener) { + // Fire with initial user. + asyncQueue.enqueueRetryable(() => changeListener(User.UNAUTHENTICATED)); + } + shutdown() { } +} +/** + * A CredentialsProvider that always returns a constant token. Used for + * emulator token mocking. + */ +class EmulatorAuthCredentialsProvider { + constructor(token) { + this.token = token; + /** + * Stores the listener registered with setChangeListener() + * This isn't actually necessary since the UID never changes, but we use this + * to verify the listen contract is adhered to in tests. + */ + this.changeListener = null; + } + getToken() { + return Promise.resolve(this.token); + } + invalidateToken() { } + start(asyncQueue, changeListener) { + this.changeListener = changeListener; + // Fire with initial user. + asyncQueue.enqueueRetryable(() => changeListener(this.token.user)); + } + shutdown() { + this.changeListener = null; + } +} +/** Credential provider for the Lite SDK. */ +class LiteAuthCredentialsProvider { + constructor(authProvider) { + this.auth = null; + authProvider.onInit(auth => { + this.auth = auth; + }); + } + getToken() { + if (!this.auth) { + return Promise.resolve(null); + } + return this.auth.getToken().then(tokenData => { + if (tokenData) { + hardAssert(typeof tokenData.accessToken === 'string', 0xa539, { tokenData }); + return new OAuthToken(tokenData.accessToken, new User(this.auth.getUid())); + } + else { + return null; + } + }); + } + invalidateToken() { } + start(asyncQueue, changeListener) { } + shutdown() { } +} +/* + * FirstPartyToken provides a fresh token each time its value + * is requested, because if the token is too old, requests will be rejected. + * Technically this may no longer be necessary since the SDK should gracefully + * recover from unauthenticated errors (see b/33147818 for context), but it's + * safer to keep the implementation as-is. + */ +class FirstPartyToken { + constructor(sessionIndex, iamToken, authTokenFactory) { + this.sessionIndex = sessionIndex; + this.iamToken = iamToken; + this.authTokenFactory = authTokenFactory; + this.type = 'FirstParty'; + this.user = User.FIRST_PARTY; + this._headers = new Map(); + } + /** + * Gets an authorization token, using a provided factory function, or return + * null. + */ + getAuthToken() { + if (this.authTokenFactory) { + return this.authTokenFactory(); + } + else { + return null; + } + } + get headers() { + this._headers.set('X-Goog-AuthUser', this.sessionIndex); + // Use array notation to prevent minification + const authHeaderTokenValue = this.getAuthToken(); + if (authHeaderTokenValue) { + this._headers.set('Authorization', authHeaderTokenValue); + } + if (this.iamToken) { + this._headers.set('X-Goog-Iam-Authorization-Token', this.iamToken); + } + return this._headers; + } +} +/* + * Provides user credentials required for the Firestore JavaScript SDK + * to authenticate the user, using technique that is only available + * to applications hosted by Google. + */ +class FirstPartyAuthCredentialsProvider { + constructor(sessionIndex, iamToken, authTokenFactory) { + this.sessionIndex = sessionIndex; + this.iamToken = iamToken; + this.authTokenFactory = authTokenFactory; + } + getToken() { + return Promise.resolve(new FirstPartyToken(this.sessionIndex, this.iamToken, this.authTokenFactory)); + } + start(asyncQueue, changeListener) { + // Fire with initial uid. + asyncQueue.enqueueRetryable(() => changeListener(User.FIRST_PARTY)); + } + shutdown() { } + invalidateToken() { } +} +class AppCheckToken { + constructor(value) { + this.value = value; + this.type = 'AppCheck'; + this.headers = new Map(); + if (value && value.length > 0) { + this.headers.set('x-firebase-appcheck', this.value); + } + } +} +/** AppCheck token provider for the Lite SDK. */ +class LiteAppCheckTokenProvider { + constructor(app$1, appCheckProvider) { + this.appCheckProvider = appCheckProvider; + this.appCheck = null; + this.serverAppAppCheckToken = null; + if (app._isFirebaseServerApp(app$1) && app$1.settings.appCheckToken) { + this.serverAppAppCheckToken = app$1.settings.appCheckToken; + } + appCheckProvider.onInit(appCheck => { + this.appCheck = appCheck; + }); + } + getToken() { + if (this.serverAppAppCheckToken) { + return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken)); + } + if (!this.appCheck) { + return Promise.resolve(null); + } + return this.appCheck.getToken().then(tokenResult => { + if (tokenResult) { + hardAssert(typeof tokenResult.token === 'string', 0x0d8e, { tokenResult }); + return new AppCheckToken(tokenResult.token); + } + else { + return null; + } + }); + } + invalidateToken() { } + start(asyncQueue, changeListener) { } + shutdown() { } +} +/** + * Builds a CredentialsProvider depending on the type of + * the credentials passed in. + */ +function makeAuthCredentialsProvider(credentials) { + if (!credentials) { + return new EmptyAuthCredentialsProvider(); + } + switch (credentials['type']) { + case 'firstParty': + return new FirstPartyAuthCredentialsProvider(credentials['sessionIndex'] || '0', credentials['iamToken'] || null, credentials['authTokenFactory'] || null); + case 'provider': + return credentials['client']; + default: + throw new FirestoreError(Code.INVALID_ARGUMENT, 'makeAuthCredentialsProvider failed due to invalid credential type'); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class DatabaseInfo { + /** + * Constructs a DatabaseInfo using the provided host, databaseId and + * persistenceKey. + * + * @param databaseId - The database to use. + * @param appId - The Firebase App Id. + * @param persistenceKey - A unique identifier for this Firestore's local + * storage (used in conjunction with the databaseId). + * @param host - The Firestore backend host to connect to. + * @param ssl - Whether to use SSL when connecting. + * @param forceLongPolling - Whether to use the forceLongPolling option + * when using WebChannel as the network transport. + * @param autoDetectLongPolling - Whether to use the detectBufferingProxy + * option when using WebChannel as the network transport. + * @param longPollingOptions Options that configure long-polling. + * @param useFetchStreams Whether to use the Fetch API instead of + * XMLHTTPRequest + */ + constructor(databaseId, appId, persistenceKey, host, ssl, forceLongPolling, autoDetectLongPolling, longPollingOptions, useFetchStreams, isUsingEmulator) { + this.databaseId = databaseId; + this.appId = appId; + this.persistenceKey = persistenceKey; + this.host = host; + this.ssl = ssl; + this.forceLongPolling = forceLongPolling; + this.autoDetectLongPolling = autoDetectLongPolling; + this.longPollingOptions = longPollingOptions; + this.useFetchStreams = useFetchStreams; + this.isUsingEmulator = isUsingEmulator; + } +} +/** The default database name for a project. */ +const DEFAULT_DATABASE_NAME = '(default)'; +/** + * Represents the database ID a Firestore client is associated with. + * @internal + */ +class DatabaseId { + constructor(projectId, database) { + this.projectId = projectId; + this.database = database ? database : DEFAULT_DATABASE_NAME; + } + static empty() { + return new DatabaseId('', ''); + } + get isDefaultDatabase() { + return this.database === DEFAULT_DATABASE_NAME; + } + isEqual(other) { + return (other instanceof DatabaseId && + other.projectId === this.projectId && + other.database === this.database); + } +} +function databaseIdFromApp(app, database) { + if (!Object.prototype.hasOwnProperty.apply(app.options, ['projectId'])) { + throw new FirestoreError(Code.INVALID_ARGUMENT, '"projectId" not provided in firebase.initializeApp.'); + } + return new DatabaseId(app.options.projectId, database); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Generates `nBytes` of random bytes. + * + * If `nBytes < 0` , an error will be thrown. + */ +function randomBytes(nBytes) { + return crypto.randomBytes(nBytes); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A utility class for generating unique alphanumeric IDs of a specified length. + * + * @internal + * Exported internally for testing purposes. + */ +class AutoId { + static newId() { + // Alphanumeric characters + const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + // The largest byte value that is a multiple of `char.length`. + const maxMultiple = Math.floor(256 / chars.length) * chars.length; + let autoId = ''; + const targetLength = 20; + while (autoId.length < targetLength) { + const bytes = randomBytes(40); + for (let i = 0; i < bytes.length; ++i) { + // Only accept values that are [0, maxMultiple), this ensures they can + // be evenly mapped to indices of `chars` via a modulo operation. + if (autoId.length < targetLength && bytes[i] < maxMultiple) { + autoId += chars.charAt(bytes[i] % chars.length); + } + } + } + return autoId; + } +} +function primitiveComparator(left, right) { + if (left < right) { + return -1; + } + if (left > right) { + return 1; + } + return 0; +} +/** Compare strings in UTF-8 encoded byte order */ +function compareUtf8Strings(left, right) { + // Find the first differing character (a.k.a. "UTF-16 code unit") in the two strings and, + // if found, use that character to determine the relative ordering of the two strings as a + // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by + // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8 + // and UTF-16 happen to represent Unicode code points. + // + // After finding the first pair of differing characters, there are two cases: + // + // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or + // both are surrogates from a surrogate pair (that collectively represent code points greater + // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the + // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is + // sufficient. + // + // Case 2: One character is a surrogate and the other is not. In this case the surrogate- + // containing string is always ordered after the non-surrogate. This is because surrogates are + // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations + // and are lexicographically greater than the 1, 2, or 3-byte representations of code points + // less than or equal to 0xFFFF. + // + // An example of why Case 2 is required is comparing the following two Unicode code points: + // + // |-----------------------|------------|---------------------|-----------------| + // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding | + // |-----------------------|------------|---------------------|-----------------| + // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD | + // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 | + // |-----------------------|------------|---------------------|-----------------| + // + // A lexicographical comparison of the UTF-8 encodings of these code points would order + // "Replacement Character" _before_ "Grinning Face" because 0xEF is less than 0xF0. However, a + // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously + // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out, + // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate + // pair with those that do not. + const length = Math.min(left.length, right.length); + for (let i = 0; i < length; i++) { + const leftChar = left.charAt(i); + const rightChar = right.charAt(i); + if (leftChar !== rightChar) { + return isSurrogate(leftChar) === isSurrogate(rightChar) + ? primitiveComparator(leftChar, rightChar) + : isSurrogate(leftChar) + ? 1 + : -1; + } + } + // Use the lengths of the strings to determine the overall comparison result since either the + // strings were equal or one is a prefix of the other. + return primitiveComparator(left.length, right.length); +} +const MIN_SURROGATE = 0xd800; +const MAX_SURROGATE = 0xdfff; +function isSurrogate(s) { + const c = s.charCodeAt(0); + return c >= MIN_SURROGATE && c <= MAX_SURROGATE; +} +/** Helper to compare arrays using isEqual(). */ +function arrayEquals(left, right, comparator) { + if (left.length !== right.length) { + return false; + } + return left.every((value, index) => comparator(value, right[index])); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const DOCUMENT_KEY_NAME = '__name__'; +/** + * Path represents an ordered sequence of string segments. + */ +class BasePath { + constructor(segments, offset, length) { + if (offset === undefined) { + offset = 0; + } + else if (offset > segments.length) { + fail(0x027d, { + offset, + range: segments.length + }); + } + if (length === undefined) { + length = segments.length - offset; + } + else if (length > segments.length - offset) { + fail(0x06d2, { + length, + range: segments.length - offset + }); + } + this.segments = segments; + this.offset = offset; + this.len = length; + } + get length() { + return this.len; + } + isEqual(other) { + return BasePath.comparator(this, other) === 0; + } + child(nameOrPath) { + const segments = this.segments.slice(this.offset, this.limit()); + if (nameOrPath instanceof BasePath) { + nameOrPath.forEach(segment => { + segments.push(segment); + }); + } + else { + segments.push(nameOrPath); + } + return this.construct(segments); + } + /** The index of one past the last segment of the path. */ + limit() { + return this.offset + this.length; + } + popFirst(size) { + size = size === undefined ? 1 : size; + return this.construct(this.segments, this.offset + size, this.length - size); + } + popLast() { + return this.construct(this.segments, this.offset, this.length - 1); + } + firstSegment() { + return this.segments[this.offset]; + } + lastSegment() { + return this.get(this.length - 1); + } + get(index) { + return this.segments[this.offset + index]; + } + isEmpty() { + return this.length === 0; + } + isPrefixOf(other) { + if (other.length < this.length) { + return false; + } + for (let i = 0; i < this.length; i++) { + if (this.get(i) !== other.get(i)) { + return false; + } + } + return true; + } + isImmediateParentOf(potentialChild) { + if (this.length + 1 !== potentialChild.length) { + return false; + } + for (let i = 0; i < this.length; i++) { + if (this.get(i) !== potentialChild.get(i)) { + return false; + } + } + return true; + } + forEach(fn) { + for (let i = this.offset, end = this.limit(); i < end; i++) { + fn(this.segments[i]); + } + } + toArray() { + return this.segments.slice(this.offset, this.limit()); + } + /** + * Compare 2 paths segment by segment, prioritizing numeric IDs + * (e.g., "__id123__") in numeric ascending order, followed by string + * segments in lexicographical order. + */ + static comparator(p1, p2) { + const len = Math.min(p1.length, p2.length); + for (let i = 0; i < len; i++) { + const comparison = BasePath.compareSegments(p1.get(i), p2.get(i)); + if (comparison !== 0) { + return comparison; + } + } + return primitiveComparator(p1.length, p2.length); + } + static compareSegments(lhs, rhs) { + const isLhsNumeric = BasePath.isNumericId(lhs); + const isRhsNumeric = BasePath.isNumericId(rhs); + if (isLhsNumeric && !isRhsNumeric) { + // Only lhs is numeric + return -1; + } + else if (!isLhsNumeric && isRhsNumeric) { + // Only rhs is numeric + return 1; + } + else if (isLhsNumeric && isRhsNumeric) { + // both numeric + return BasePath.extractNumericId(lhs).compare(BasePath.extractNumericId(rhs)); + } + else { + // both non-numeric + return compareUtf8Strings(lhs, rhs); + } + } + // Checks if a segment is a numeric ID (starts with "__id" and ends with "__"). + static isNumericId(segment) { + return segment.startsWith('__id') && segment.endsWith('__'); + } + static extractNumericId(segment) { + return bloomBlob.Integer.fromString(segment.substring(4, segment.length - 2)); + } +} +/** + * A slash-separated path for navigating resources (documents and collections) + * within Firestore. + * + * @internal + */ +class ResourcePath extends BasePath { + construct(segments, offset, length) { + return new ResourcePath(segments, offset, length); + } + canonicalString() { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + return this.toArray().join('/'); + } + toString() { + return this.canonicalString(); + } + /** + * Returns a string representation of this path + * where each path segment has been encoded with + * `encodeURIComponent`. + */ + toUriEncodedString() { + return this.toArray().map(encodeURIComponent).join('/'); + } + /** + * Creates a resource path from the given slash-delimited string. If multiple + * arguments are provided, all components are combined. Leading and trailing + * slashes from all components are ignored. + */ + static fromString(...pathComponents) { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + const segments = []; + for (const path of pathComponents) { + if (path.indexOf('//') >= 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid segment (${path}). Paths must not contain // in them.`); + } + // Strip leading and trailing slashed. + segments.push(...path.split('/').filter(segment => segment.length > 0)); + } + return new ResourcePath(segments); + } + static emptyPath() { + return new ResourcePath([]); + } +} +const identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/; +/** + * A dot-separated path for navigating sub-objects within a document. + * @internal + */ +class FieldPath$1 extends BasePath { + construct(segments, offset, length) { + return new FieldPath$1(segments, offset, length); + } + /** + * Returns true if the string could be used as a segment in a field path + * without escaping. + */ + static isValidIdentifier(segment) { + return identifierRegExp.test(segment); + } + canonicalString() { + return this.toArray() + .map(str => { + str = str.replace(/\\/g, '\\\\').replace(/`/g, '\\`'); + if (!FieldPath$1.isValidIdentifier(str)) { + str = '`' + str + '`'; + } + return str; + }) + .join('.'); + } + toString() { + return this.canonicalString(); + } + /** + * Returns true if this field references the key of a document. + */ + isKeyField() { + return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME; + } + /** + * The field designating the key of a document. + */ + static keyField() { + return new FieldPath$1([DOCUMENT_KEY_NAME]); + } + /** + * Parses a field string from the given server-formatted string. + * + * - Splitting the empty string is not allowed (for now at least). + * - Empty segments within the string (e.g. if there are two consecutive + * separators) are not allowed. + * + * TODO(b/37244157): we should make this more strict. Right now, it allows + * non-identifier path components, even if they aren't escaped. + */ + static fromServerFormat(path) { + const segments = []; + let current = ''; + let i = 0; + const addCurrentSegment = () => { + if (current.length === 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid field path (${path}). Paths must not be empty, begin ` + + `with '.', end with '.', or contain '..'`); + } + segments.push(current); + current = ''; + }; + let inBackticks = false; + while (i < path.length) { + const c = path[i]; + if (c === '\\') { + if (i + 1 === path.length) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has trailing escape character: ' + path); + } + const next = path[i + 1]; + if (!(next === '\\' || next === '.' || next === '`')) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has invalid escape sequence: ' + path); + } + current += next; + i += 2; + } + else if (c === '`') { + inBackticks = !inBackticks; + i++; + } + else if (c === '.' && !inBackticks) { + addCurrentSegment(); + i++; + } + else { + current += c; + i++; + } + } + addCurrentSegment(); + if (inBackticks) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Unterminated ` in path: ' + path); + } + return new FieldPath$1(segments); + } + static emptyPath() { + return new FieldPath$1([]); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @internal + */ +class DocumentKey { + constructor(path) { + this.path = path; + } + static fromPath(path) { + return new DocumentKey(ResourcePath.fromString(path)); + } + static fromName(name) { + return new DocumentKey(ResourcePath.fromString(name).popFirst(5)); + } + static empty() { + return new DocumentKey(ResourcePath.emptyPath()); + } + get collectionGroup() { + return this.path.popLast().lastSegment(); + } + /** Returns true if the document is in the specified collectionId. */ + hasCollectionId(collectionId) { + return (this.path.length >= 2 && + this.path.get(this.path.length - 2) === collectionId); + } + /** Returns the collection group (i.e. the name of the parent collection) for this key. */ + getCollectionGroup() { + return this.path.get(this.path.length - 2); + } + /** Returns the fully qualified path to the parent collection. */ + getCollectionPath() { + return this.path.popLast(); + } + isEqual(other) { + return (other !== null && ResourcePath.comparator(this.path, other.path) === 0); + } + toString() { + return this.path.toString(); + } + static comparator(k1, k2) { + return ResourcePath.comparator(k1.path, k2.path); + } + static isDocumentKey(path) { + return path.length % 2 === 0; + } + /** + * Creates and returns a new document key with the given segments. + * + * @param segments - The segments of the path to the document + * @returns A new instance of DocumentKey + */ + static fromSegments(segments) { + return new DocumentKey(new ResourcePath(segments.slice())); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function validateNonEmptyArgument(functionName, argumentName, argument) { + if (!argument) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${functionName}() cannot be called with an empty ${argumentName}.`); + } +} +/** + * Validates that two boolean options are not set at the same time. + * @internal + */ +function validateIsNotUsedTogether(optionName1, argument1, optionName2, argument2) { + if (argument1 === true && argument2 === true) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `${optionName1} and ${optionName2} cannot be used together.`); + } +} +/** + * Validates that `path` refers to a document (indicated by the fact it contains + * an even numbers of segments). + */ +function validateDocumentPath(path) { + if (!DocumentKey.isDocumentKey(path)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid document reference. Document references must have an even number of segments, but ${path} has ${path.length}.`); + } +} +/** + * Validates that `path` refers to a collection (indicated by the fact it + * contains an odd numbers of segments). + */ +function validateCollectionPath(path) { + if (DocumentKey.isDocumentKey(path)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid collection reference. Collection references must have an odd number of segments, but ${path} has ${path.length}.`); + } +} +/** + * Returns true if it's a non-null object without a custom prototype + * (i.e. excludes Array, Date, etc.). + */ +function isPlainObject(input) { + return (typeof input === 'object' && + input !== null && + (Object.getPrototypeOf(input) === Object.prototype || + Object.getPrototypeOf(input) === null)); +} +/** Returns a string describing the type / value of the provided input. */ +function valueDescription(input) { + if (input === undefined) { + return 'undefined'; + } + else if (input === null) { + return 'null'; + } + else if (typeof input === 'string') { + if (input.length > 20) { + input = `${input.substring(0, 20)}...`; + } + return JSON.stringify(input); + } + else if (typeof input === 'number' || typeof input === 'boolean') { + return '' + input; + } + else if (typeof input === 'object') { + if (input instanceof Array) { + return 'an array'; + } + else { + const customObjectName = tryGetCustomObjectType(input); + if (customObjectName) { + return `a custom ${customObjectName} object`; + } + else { + return 'an object'; + } + } + } + else if (typeof input === 'function') { + return 'a function'; + } + else { + return fail(0x3029, { type: typeof input }); + } +} +/** try to get the constructor name for an object. */ +function tryGetCustomObjectType(input) { + if (input.constructor) { + return input.constructor.name; + } + return null; +} +/** + * Casts `obj` to `T`, optionally unwrapping Compat types to expose the + * underlying instance. Throws if `obj` is not an instance of `T`. + * + * This cast is used in the Lite and Full SDK to verify instance types for + * arguments passed to the public API. + * @internal + */ +function cast(obj, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +constructor) { + if ('_delegate' in obj) { + // Unwrap Compat types + // eslint-disable-next-line @typescript-eslint/no-explicit-any + obj = obj._delegate; + } + if (!(obj instanceof constructor)) { + if (constructor.name === obj.constructor.name) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Type does not match the expected instance. Did you pass a ' + + `reference from a different Firestore SDK?`); + } + else { + const description = valueDescription(obj); + throw new FirestoreError(Code.INVALID_ARGUMENT, `Expected type '${constructor.name}', but it was: ${description}`); + } + } + return obj; +} +function validatePositiveNumber(functionName, n) { + if (n <= 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${functionName}() requires a positive number, but it was: ${n}.`); + } +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Compares two `ExperimentalLongPollingOptions` objects for equality. + */ +function longPollingOptionsEqual(options1, options2) { + return options1.timeoutSeconds === options2.timeoutSeconds; +} +/** + * Creates and returns a new `ExperimentalLongPollingOptions` with the same + * option values as the given instance. + */ +function cloneLongPollingOptions(options) { + const clone = {}; + if (options.timeoutSeconds !== undefined) { + clone.timeoutSeconds = options.timeoutSeconds; + } + return clone; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The value returned from the most recent invocation of + * `generateUniqueDebugId()`, or null if it has never been invoked. + */ +let lastUniqueDebugId = null; +/** + * Generates and returns an initial value for `lastUniqueDebugId`. + * + * The returned value is randomly selected from a range of integers that are + * represented as 8 hexadecimal digits. This means that (within reason) any + * numbers generated by incrementing the returned number by 1 will also be + * represented by 8 hexadecimal digits. This leads to all "IDs" having the same + * length when converted to a hexadecimal string, making reading logs containing + * these IDs easier to follow. And since the return value is randomly selected + * it will help to differentiate between logs from different executions. + */ +function generateInitialUniqueDebugId() { + const minResult = 0x10000000; + const maxResult = 0x90000000; + const resultRange = maxResult - minResult; + const resultOffset = Math.round(resultRange * Math.random()); + return minResult + resultOffset; +} +/** + * Generates and returns a unique ID as a hexadecimal string. + * + * The returned ID is intended to be used in debug logging messages to help + * correlate log messages that may be spatially separated in the logs, but + * logically related. For example, a network connection could include the same + * "debug ID" string in all of its log messages to help trace a specific + * connection over time. + * + * @return the 10-character generated ID (e.g. "0xa1b2c3d4"). + */ +function generateUniqueDebugId() { + if (lastUniqueDebugId === null) { + lastUniqueDebugId = generateInitialUniqueDebugId(); + } + else { + lastUniqueDebugId++; + } + return '0x' + lastUniqueDebugId.toString(16); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$3 = 'RestConnection'; +/** + * Maps RPC names to the corresponding REST endpoint name. + * + * We use array notation to avoid mangling. + */ +const RPC_NAME_URL_MAPPING = {}; +RPC_NAME_URL_MAPPING['BatchGetDocuments'] = 'batchGet'; +RPC_NAME_URL_MAPPING['Commit'] = 'commit'; +RPC_NAME_URL_MAPPING['RunQuery'] = 'runQuery'; +RPC_NAME_URL_MAPPING['RunAggregationQuery'] = 'runAggregationQuery'; +const RPC_URL_VERSION = 'v1'; +// SDK_VERSION is updated to different value at runtime depending on the entry point, +// so we need to get its value when we need it in a function. +function getGoogApiClientValue() { + return 'gl-js/ fire/' + SDK_VERSION; +} +/** + * Base class for all Rest-based connections to the backend (WebChannel and + * HTTP). + */ +class RestConnection { + get shouldResourcePathBeIncludedInRequest() { + // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine + // where to run the query, and expect the `request` to NOT specify the "path". + return false; + } + constructor(databaseInfo) { + this.databaseInfo = databaseInfo; + this.databaseId = databaseInfo.databaseId; + const proto = databaseInfo.ssl ? 'https' : 'http'; + const projectId = encodeURIComponent(this.databaseId.projectId); + const databaseId = encodeURIComponent(this.databaseId.database); + this.baseUrl = proto + '://' + databaseInfo.host; + this.databasePath = `projects/${projectId}/databases/${databaseId}`; + this.requestParams = + this.databaseId.database === DEFAULT_DATABASE_NAME + ? `project_id=${projectId}` + : `project_id=${projectId}&database_id=${databaseId}`; + } + invokeRPC(rpcName, path, req, authToken, appCheckToken) { + const streamId = generateUniqueDebugId(); + const url = this.makeUrl(rpcName, path.toUriEncodedString()); + logDebug(LOG_TAG$3, `Sending RPC '${rpcName}' ${streamId}:`, url, req); + const headers = { + 'google-cloud-resource-prefix': this.databasePath, + 'x-goog-request-params': this.requestParams + }; + this.modifyHeadersForRequest(headers, authToken, appCheckToken); + const { host } = new URL(url); + const forwardCredentials = util.isCloudWorkstation(host); + return this.performRPCRequest(rpcName, url, headers, req, forwardCredentials).then(response => { + logDebug(LOG_TAG$3, `Received RPC '${rpcName}' ${streamId}: `, response); + return response; + }, (err) => { + logWarn(LOG_TAG$3, `RPC '${rpcName}' ${streamId} failed with error: `, err, 'url: ', url, 'request:', req); + throw err; + }); + } + invokeStreamingRPC(rpcName, path, request, authToken, appCheckToken, expectedResponseCount) { + // The REST API automatically aggregates all of the streamed results, so we + // can just use the normal invoke() method. + return this.invokeRPC(rpcName, path, request, authToken, appCheckToken); + } + /** + * Modifies the headers for a request, adding any authorization token if + * present and any additional headers for the request. + */ + modifyHeadersForRequest(headers, authToken, appCheckToken) { + headers['X-Goog-Api-Client'] = getGoogApiClientValue(); + // Content-Type: text/plain will avoid preflight requests which might + // mess with CORS and redirects by proxies. If we add custom headers + // we will need to change this code to potentially use the $httpOverwrite + // parameter supported by ESF to avoid triggering preflight requests. + headers['Content-Type'] = 'text/plain'; + if (this.databaseInfo.appId) { + headers['X-Firebase-GMPID'] = this.databaseInfo.appId; + } + if (authToken) { + authToken.headers.forEach((value, key) => (headers[key] = value)); + } + if (appCheckToken) { + appCheckToken.headers.forEach((value, key) => (headers[key] = value)); + } + } + makeUrl(rpcName, path) { + const urlRpcName = RPC_NAME_URL_MAPPING[rpcName]; + return `${this.baseUrl}/${RPC_URL_VERSION}/${path}:${urlRpcName}`; + } + /** + * Closes and cleans up any resources associated with the connection. This + * implementation is a no-op because there are no resources associated + * with the RestConnection that need to be cleaned up. + */ + terminate() { + // No-op + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Error Codes describing the different ways GRPC can fail. These are copied + * directly from GRPC's sources here: + * + * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h + * + * Important! The names of these identifiers matter because the string forms + * are used for reverse lookups from the webchannel stream. Do NOT change the + * names of these identifiers or change this into a const enum. + */ +var RpcCode; +(function (RpcCode) { + RpcCode[RpcCode["OK"] = 0] = "OK"; + RpcCode[RpcCode["CANCELLED"] = 1] = "CANCELLED"; + RpcCode[RpcCode["UNKNOWN"] = 2] = "UNKNOWN"; + RpcCode[RpcCode["INVALID_ARGUMENT"] = 3] = "INVALID_ARGUMENT"; + RpcCode[RpcCode["DEADLINE_EXCEEDED"] = 4] = "DEADLINE_EXCEEDED"; + RpcCode[RpcCode["NOT_FOUND"] = 5] = "NOT_FOUND"; + RpcCode[RpcCode["ALREADY_EXISTS"] = 6] = "ALREADY_EXISTS"; + RpcCode[RpcCode["PERMISSION_DENIED"] = 7] = "PERMISSION_DENIED"; + RpcCode[RpcCode["UNAUTHENTICATED"] = 16] = "UNAUTHENTICATED"; + RpcCode[RpcCode["RESOURCE_EXHAUSTED"] = 8] = "RESOURCE_EXHAUSTED"; + RpcCode[RpcCode["FAILED_PRECONDITION"] = 9] = "FAILED_PRECONDITION"; + RpcCode[RpcCode["ABORTED"] = 10] = "ABORTED"; + RpcCode[RpcCode["OUT_OF_RANGE"] = 11] = "OUT_OF_RANGE"; + RpcCode[RpcCode["UNIMPLEMENTED"] = 12] = "UNIMPLEMENTED"; + RpcCode[RpcCode["INTERNAL"] = 13] = "INTERNAL"; + RpcCode[RpcCode["UNAVAILABLE"] = 14] = "UNAVAILABLE"; + RpcCode[RpcCode["DATA_LOSS"] = 15] = "DATA_LOSS"; +})(RpcCode || (RpcCode = {})); +/** + * Determines whether an error code represents a permanent error when received + * in response to a non-write operation. + * + * See isPermanentWriteError for classifying write errors. + */ +function isPermanentError(code) { + switch (code) { + case Code.OK: + return fail(0xfdaa); + case Code.CANCELLED: + case Code.UNKNOWN: + case Code.DEADLINE_EXCEEDED: + case Code.RESOURCE_EXHAUSTED: + case Code.INTERNAL: + case Code.UNAVAILABLE: + // Unauthenticated means something went wrong with our token and we need + // to retry with new credentials which will happen automatically. + case Code.UNAUTHENTICATED: + return false; + case Code.INVALID_ARGUMENT: + case Code.NOT_FOUND: + case Code.ALREADY_EXISTS: + case Code.PERMISSION_DENIED: + case Code.FAILED_PRECONDITION: + // Aborted might be retried in some scenarios, but that is dependent on + // the context and should handled individually by the calling code. + // See https://cloud.google.com/apis/design/errors. + case Code.ABORTED: + case Code.OUT_OF_RANGE: + case Code.UNIMPLEMENTED: + case Code.DATA_LOSS: + return true; + default: + return fail(0x3c6b, { code }); + } +} +/** + * Converts an HTTP Status Code to the equivalent error code. + * + * @param status - An HTTP Status Code, like 200, 404, 503, etc. + * @returns The equivalent Code. Unknown status codes are mapped to + * Code.UNKNOWN. + */ +function mapCodeFromHttpStatus(status) { + if (status === undefined) { + logError('RPC_ERROR', 'HTTP error has no status'); + return Code.UNKNOWN; + } + // The canonical error codes for Google APIs [1] specify mapping onto HTTP + // status codes but the mapping is not bijective. In each case of ambiguity + // this function chooses a primary error. + // + // [1] + // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto + switch (status) { + case 200: // OK + return Code.OK; + case 400: // Bad Request + return Code.FAILED_PRECONDITION; + // Other possibilities based on the forward mapping + // return Code.INVALID_ARGUMENT; + // return Code.OUT_OF_RANGE; + case 401: // Unauthorized + return Code.UNAUTHENTICATED; + case 403: // Forbidden + return Code.PERMISSION_DENIED; + case 404: // Not Found + return Code.NOT_FOUND; + case 409: // Conflict + return Code.ABORTED; + // Other possibilities: + // return Code.ALREADY_EXISTS; + case 416: // Range Not Satisfiable + return Code.OUT_OF_RANGE; + case 429: // Too Many Requests + return Code.RESOURCE_EXHAUSTED; + case 499: // Client Closed Request + return Code.CANCELLED; + case 500: // Internal Server Error + return Code.UNKNOWN; + // Other possibilities: + // return Code.INTERNAL; + // return Code.DATA_LOSS; + case 501: // Unimplemented + return Code.UNIMPLEMENTED; + case 503: // Service Unavailable + return Code.UNAVAILABLE; + case 504: // Gateway Timeout + return Code.DEADLINE_EXCEEDED; + default: + if (status >= 200 && status < 300) { + return Code.OK; + } + if (status >= 400 && status < 500) { + return Code.FAILED_PRECONDITION; + } + if (status >= 500 && status < 600) { + return Code.INTERNAL; + } + return Code.UNKNOWN; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A Rest-based connection that relies on the native HTTP stack + * (e.g. `fetch` or a polyfill). + */ +class FetchConnection extends RestConnection { + openStream(rpcName, token) { + throw new Error('Not supported by FetchConnection'); + } + async performRPCRequest(rpcName, url, headers, body, forwardCredentials) { + const requestJson = JSON.stringify(body); + let response; + try { + const fetchArgs = { + method: 'POST', + headers, + body: requestJson + }; + if (forwardCredentials) { + fetchArgs.credentials = 'include'; + } + response = await fetch(url, fetchArgs); + } + catch (e) { + const err = e; + throw new FirestoreError(mapCodeFromHttpStatus(err.status), 'Request failed with error: ' + err.statusText); + } + if (!response.ok) { + let errorResponse = await response.json(); + if (Array.isArray(errorResponse)) { + errorResponse = errorResponse[0]; + } + const errorMessage = errorResponse?.error?.message; + throw new FirestoreError(mapCodeFromHttpStatus(response.status), `Request failed with error: ${errorMessage ?? response.statusText}`); + } + return response.json(); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Initializes the HTTP connection for the REST API. */ +function newConnection(databaseInfo) { + return new FetchConnection(databaseInfo); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function objectSize(obj) { + let count = 0; + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + count++; + } + } + return count; +} +function forEach(obj, fn) { + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + fn(key, obj[key]); + } + } +} +function mapToArray(obj, fn) { + const result = []; + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + result.push(fn(obj[key], key, obj)); + } + } + return result; +} +function isEmpty(obj) { + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + return false; + } + } + return true; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns whether a variable is either undefined or null. + */ +function isNullOrUndefined(value) { + return value === null || value === undefined; +} +/** Returns whether the value represents -0. */ +function isNegativeZero(value) { + // Detect if the value is -0.0. Based on polyfill from + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is + return value === 0 && 1 / value === 1 / -0; +} +/** + * Returns whether a value is an integer and in the safe integer range + * @param value - The value to test for being an integer and in the safe range + */ +function isSafeInteger(value) { + return (typeof value === 'number' && + Number.isInteger(value) && + !isNegativeZero(value) && + value <= Number.MAX_SAFE_INTEGER && + value >= Number.MIN_SAFE_INTEGER); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Converts a Base64 encoded string to a binary string. */ +function decodeBase64(encoded) { + // Note: We used to validate the base64 string here via a regular expression. + // This was removed to improve the performance of indexing. + return Buffer.from(encoded, 'base64').toString('binary'); +} +/** Converts a binary string to a Base64 encoded string. */ +function encodeBase64(raw) { + return Buffer.from(raw, 'binary').toString('base64'); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Immutable class that represents a "proto" byte string. + * + * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when + * sent on the wire. This class abstracts away this differentiation by holding + * the proto byte string in a common class that must be converted into a string + * before being sent as a proto. + * @internal + */ +class ByteString { + constructor(binaryString) { + this.binaryString = binaryString; + } + static fromBase64String(base64) { + const binaryString = decodeBase64(base64); + return new ByteString(binaryString); + } + static fromUint8Array(array) { + // TODO(indexing); Remove the copy of the byte string here as this method + // is frequently called during indexing. + const binaryString = binaryStringFromUint8Array(array); + return new ByteString(binaryString); + } + [Symbol.iterator]() { + let i = 0; + return { + next: () => { + if (i < this.binaryString.length) { + return { value: this.binaryString.charCodeAt(i++), done: false }; + } + else { + return { value: undefined, done: true }; + } + } + }; + } + toBase64() { + return encodeBase64(this.binaryString); + } + toUint8Array() { + return uint8ArrayFromBinaryString(this.binaryString); + } + approximateByteSize() { + return this.binaryString.length * 2; + } + compareTo(other) { + return primitiveComparator(this.binaryString, other.binaryString); + } + isEqual(other) { + return this.binaryString === other.binaryString; + } +} +ByteString.EMPTY_BYTE_STRING = new ByteString(''); +/** + * Helper function to convert an Uint8array to a binary string. + */ +function binaryStringFromUint8Array(array) { + let binaryString = ''; + for (let i = 0; i < array.length; ++i) { + binaryString += String.fromCharCode(array[i]); + } + return binaryString; +} +/** + * Helper function to convert a binary string to an Uint8Array. + */ +function uint8ArrayFromBinaryString(binaryString) { + const buffer = new Uint8Array(binaryString.length); + for (let i = 0; i < binaryString.length; i++) { + buffer[i] = binaryString.charCodeAt(i); + } + return buffer; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// A RegExp matching ISO 8601 UTC timestamps with optional fraction. +const ISO_TIMESTAMP_REG_EXP = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/); +/** + * Converts the possible Proto values for a timestamp value into a "seconds and + * nanos" representation. + */ +function normalizeTimestamp(date) { + hardAssert(!!date, 0x986a); + // The json interface (for the browser) will return an iso timestamp string, + // while the proto js library (for node) will return a + // google.protobuf.Timestamp instance. + if (typeof date === 'string') { + // The date string can have higher precision (nanos) than the Date class + // (millis), so we do some custom parsing here. + // Parse the nanos right out of the string. + let nanos = 0; + const fraction = ISO_TIMESTAMP_REG_EXP.exec(date); + hardAssert(!!fraction, 0xb5de, { + timestamp: date + }); + if (fraction[1]) { + // Pad the fraction out to 9 digits (nanos). + let nanoStr = fraction[1]; + nanoStr = (nanoStr + '000000000').substr(0, 9); + nanos = Number(nanoStr); + } + // Parse the date to get the seconds. + const parsedDate = new Date(date); + const seconds = Math.floor(parsedDate.getTime() / 1000); + return { seconds, nanos }; + } + else { + // TODO(b/37282237): Use strings for Proto3 timestamps + // assert(!this.options.useProto3Json, + // 'The timestamp instance format requires Proto JS.'); + const seconds = normalizeNumber(date.seconds); + const nanos = normalizeNumber(date.nanos); + return { seconds, nanos }; + } +} +/** + * Converts the possible Proto types for numbers into a JavaScript number. + * Returns 0 if the value is not numeric. + */ +function normalizeNumber(value) { + // TODO(bjornick): Handle int64 greater than 53 bits. + if (typeof value === 'number') { + return value; + } + else if (typeof value === 'string') { + return Number(value); + } + else { + return 0; + } +} +/** Converts the possible Proto types for Blobs into a ByteString. */ +function normalizeByteString(blob) { + if (typeof blob === 'string') { + return ByteString.fromBase64String(blob); + } + else { + return ByteString.fromUint8Array(blob); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Helper function to define a JSON schema {@link Property}. + * @private + * @internal + */ +function property(typeString, optionalValue) { + const result = { + typeString + }; + if (optionalValue) { + result.value = optionalValue; + } + return result; +} +/** + * Validates the JSON object based on the provided schema, and narrows the type to the provided + * JSON schema. + * @private + * @internal + * + * @param json A JSON object to validate. + * @param scheme a {@link JsonSchema} that defines the properties to validate. + * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise. + */ +function validateJSON(json, schema) { + if (!isPlainObject(json)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'JSON must be an object'); + } + let error = undefined; + for (const key in schema) { + if (schema[key]) { + const typeString = schema[key].typeString; + const value = 'value' in schema[key] ? { value: schema[key].value } : undefined; + if (!(key in json)) { + error = `JSON missing required field: '${key}'`; + break; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const fieldValue = json[key]; + if (typeString && typeof fieldValue !== typeString) { + error = `JSON field '${key}' must be a ${typeString}.`; + break; + } + else if (value !== undefined && fieldValue !== value.value) { + error = `Expected '${key}' field to equal '${value.value}'`; + break; + } + } + } + if (error) { + throw new FirestoreError(Code.INVALID_ARGUMENT, error); + } + return true; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z). +const MIN_SECONDS = -62135596800; +// Number of nanoseconds in a millisecond. +const MS_TO_NANOS = 1e6; +/** + * A `Timestamp` represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. + * + * It is encoded using the Proleptic Gregorian Calendar which extends the + * Gregorian calendar backwards to year one. It is encoded assuming all minutes + * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59.999999999Z. + * + * For examples and further specifications, refer to the + * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. + */ +class Timestamp { + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns a new timestamp representing the current date. + */ + static now() { + return Timestamp.fromMillis(Date.now()); + } + /** + * Creates a new timestamp from the given date. + * + * @param date - The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the given + * date. + */ + static fromDate(date) { + return Timestamp.fromMillis(date.getTime()); + } + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds - Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the given + * number of milliseconds. + */ + static fromMillis(milliseconds) { + const seconds = Math.floor(milliseconds / 1000); + const nanos = Math.floor((milliseconds - seconds * 1000) * MS_TO_NANOS); + return new Timestamp(seconds, nanos); + } + /** + * Creates a new timestamp. + * + * @param seconds - The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds - The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ + constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + seconds, + /** + * The fractions of a second at nanosecond resolution.* + */ + nanoseconds) { + this.seconds = seconds; + this.nanoseconds = nanoseconds; + if (nanoseconds < 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp nanoseconds out of range: ' + nanoseconds); + } + if (nanoseconds >= 1e9) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp nanoseconds out of range: ' + nanoseconds); + } + if (seconds < MIN_SECONDS) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp seconds out of range: ' + seconds); + } + // This will break in the year 10,000. + if (seconds >= 253402300800) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp seconds out of range: ' + seconds); + } + } + /** + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ + toDate() { + return new Date(this.toMillis()); + } + /** + * Converts a `Timestamp` to a numeric timestamp (in milliseconds since + * epoch). This operation causes a loss of precision. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ + toMillis() { + return this.seconds * 1000 + this.nanoseconds / MS_TO_NANOS; + } + _compareTo(other) { + if (this.seconds === other.seconds) { + return primitiveComparator(this.nanoseconds, other.nanoseconds); + } + return primitiveComparator(this.seconds, other.seconds); + } + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other - The `Timestamp` to compare against. + * @returns true if this `Timestamp` is equal to the provided one. + */ + isEqual(other) { + return (other.seconds === this.seconds && other.nanoseconds === this.nanoseconds); + } + /** Returns a textual representation of this `Timestamp`. */ + toString() { + return ('Timestamp(seconds=' + + this.seconds + + ', nanoseconds=' + + this.nanoseconds + + ')'); + } + /** + * Returns a JSON-serializable representation of this `Timestamp`. + */ + toJSON() { + return { + type: Timestamp._jsonSchemaVersion, + seconds: this.seconds, + nanoseconds: this.nanoseconds + }; + } + /** + * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}. + */ + static fromJSON(json) { + if (validateJSON(json, Timestamp._jsonSchema)) { + return new Timestamp(json.seconds, json.nanoseconds); + } + } + /** + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. + */ + valueOf() { + // This method returns a string of the form . where + // is translated to have a non-negative value and both + // and are left-padded with zeroes to be a consistent length. + // Strings with this format then have a lexicographical ordering that matches + // the expected ordering. The translation is done to avoid having + // a leading negative sign (i.e. a leading '-' character) in its string + // representation, which would affect its lexicographical ordering. + const adjustedSeconds = this.seconds - MIN_SECONDS; + // Note: Up to 12 decimal digits are required to represent all valid + // 'seconds' values. + const formattedSeconds = String(adjustedSeconds).padStart(12, '0'); + const formattedNanoseconds = String(this.nanoseconds).padStart(9, '0'); + return formattedSeconds + '.' + formattedNanoseconds; + } +} +Timestamp._jsonSchemaVersion = 'firestore/timestamp/1.0'; +Timestamp._jsonSchema = { + type: property('string', Timestamp._jsonSchemaVersion), + seconds: property('number'), + nanoseconds: property('number') +}; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a locally-applied ServerTimestamp. + * + * Server Timestamps are backed by MapValues that contain an internal field + * `__type__` with a value of `server_timestamp`. The previous value and local + * write time are stored in its `__previous_value__` and `__local_write_time__` + * fields respectively. + * + * Notes: + * - ServerTimestampValue instances are created as the result of applying a + * transform. They can only exist in the local view of a document. Therefore + * they do not need to be parsed or serialized. + * - When evaluated locally (e.g. for snapshot.data()), they by default + * evaluate to `null`. This behavior can be configured by passing custom + * FieldValueOptions to value(). + * - With respect to other ServerTimestampValues, they sort by their + * localWriteTime. + */ +const SERVER_TIMESTAMP_SENTINEL = 'server_timestamp'; +const TYPE_KEY$1 = '__type__'; +const PREVIOUS_VALUE_KEY = '__previous_value__'; +const LOCAL_WRITE_TIME_KEY = '__local_write_time__'; +function isServerTimestamp(value) { + const type = (value?.mapValue?.fields || {})[TYPE_KEY$1]?.stringValue; + return type === SERVER_TIMESTAMP_SENTINEL; +} +/** + * Returns the value of the field before this ServerTimestamp was set. + * + * Preserving the previous values allows the user to display the last resoled + * value until the backend responds with the timestamp. + */ +function getPreviousValue(value) { + const previousValue = value.mapValue.fields[PREVIOUS_VALUE_KEY]; + if (isServerTimestamp(previousValue)) { + return getPreviousValue(previousValue); + } + return previousValue; +} +/** + * Returns the local time at which this timestamp was first set. + */ +function getLocalWriteTime(value) { + const localWriteTime = normalizeTimestamp(value.mapValue.fields[LOCAL_WRITE_TIME_KEY].timestampValue); + return new Timestamp(localWriteTime.seconds, localWriteTime.nanos); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const TYPE_KEY = '__type__'; +const MAX_VALUE_TYPE = '__max__'; +const MAX_VALUE = { + mapValue: { + fields: { + '__type__': { stringValue: MAX_VALUE_TYPE } + } + } +}; +const VECTOR_VALUE_SENTINEL = '__vector__'; +const VECTOR_MAP_VECTORS_KEY = 'value'; +/** Extracts the backend's type order for the provided value. */ +function typeOrder(value) { + if ('nullValue' in value) { + return 0 /* TypeOrder.NullValue */; + } + else if ('booleanValue' in value) { + return 1 /* TypeOrder.BooleanValue */; + } + else if ('integerValue' in value || 'doubleValue' in value) { + return 2 /* TypeOrder.NumberValue */; + } + else if ('timestampValue' in value) { + return 3 /* TypeOrder.TimestampValue */; + } + else if ('stringValue' in value) { + return 5 /* TypeOrder.StringValue */; + } + else if ('bytesValue' in value) { + return 6 /* TypeOrder.BlobValue */; + } + else if ('referenceValue' in value) { + return 7 /* TypeOrder.RefValue */; + } + else if ('geoPointValue' in value) { + return 8 /* TypeOrder.GeoPointValue */; + } + else if ('arrayValue' in value) { + return 9 /* TypeOrder.ArrayValue */; + } + else if ('mapValue' in value) { + if (isServerTimestamp(value)) { + return 4 /* TypeOrder.ServerTimestampValue */; + } + else if (isMaxValue(value)) { + return 9007199254740991 /* TypeOrder.MaxValue */; + } + else if (isVectorValue(value)) { + return 10 /* TypeOrder.VectorValue */; + } + return 11 /* TypeOrder.ObjectValue */; + } + else { + return fail(0x6e87, { value }); + } +} +/** Tests `left` and `right` for equality based on the backend semantics. */ +function valueEquals(left, right) { + if (left === right) { + return true; + } + const leftType = typeOrder(left); + const rightType = typeOrder(right); + if (leftType !== rightType) { + return false; + } + switch (leftType) { + case 0 /* TypeOrder.NullValue */: + return true; + case 1 /* TypeOrder.BooleanValue */: + return left.booleanValue === right.booleanValue; + case 4 /* TypeOrder.ServerTimestampValue */: + return getLocalWriteTime(left).isEqual(getLocalWriteTime(right)); + case 3 /* TypeOrder.TimestampValue */: + return timestampEquals(left, right); + case 5 /* TypeOrder.StringValue */: + return left.stringValue === right.stringValue; + case 6 /* TypeOrder.BlobValue */: + return blobEquals(left, right); + case 7 /* TypeOrder.RefValue */: + return left.referenceValue === right.referenceValue; + case 8 /* TypeOrder.GeoPointValue */: + return geoPointEquals(left, right); + case 2 /* TypeOrder.NumberValue */: + return numberEquals(left, right); + case 9 /* TypeOrder.ArrayValue */: + return arrayEquals(left.arrayValue.values || [], right.arrayValue.values || [], valueEquals); + case 10 /* TypeOrder.VectorValue */: + case 11 /* TypeOrder.ObjectValue */: + return objectEquals(left, right); + case 9007199254740991 /* TypeOrder.MaxValue */: + return true; + default: + return fail(0xcbf8, { left }); + } +} +function timestampEquals(left, right) { + if (typeof left.timestampValue === 'string' && + typeof right.timestampValue === 'string' && + left.timestampValue.length === right.timestampValue.length) { + // Use string equality for ISO 8601 timestamps + return left.timestampValue === right.timestampValue; + } + const leftTimestamp = normalizeTimestamp(left.timestampValue); + const rightTimestamp = normalizeTimestamp(right.timestampValue); + return (leftTimestamp.seconds === rightTimestamp.seconds && + leftTimestamp.nanos === rightTimestamp.nanos); +} +function geoPointEquals(left, right) { + return (normalizeNumber(left.geoPointValue.latitude) === + normalizeNumber(right.geoPointValue.latitude) && + normalizeNumber(left.geoPointValue.longitude) === + normalizeNumber(right.geoPointValue.longitude)); +} +function blobEquals(left, right) { + return normalizeByteString(left.bytesValue).isEqual(normalizeByteString(right.bytesValue)); +} +function numberEquals(left, right) { + if ('integerValue' in left && 'integerValue' in right) { + return (normalizeNumber(left.integerValue) === normalizeNumber(right.integerValue)); + } + else if ('doubleValue' in left && 'doubleValue' in right) { + const n1 = normalizeNumber(left.doubleValue); + const n2 = normalizeNumber(right.doubleValue); + if (n1 === n2) { + return isNegativeZero(n1) === isNegativeZero(n2); + } + else { + return isNaN(n1) && isNaN(n2); + } + } + return false; +} +function objectEquals(left, right) { + const leftMap = left.mapValue.fields || {}; + const rightMap = right.mapValue.fields || {}; + if (objectSize(leftMap) !== objectSize(rightMap)) { + return false; + } + for (const key in leftMap) { + if (leftMap.hasOwnProperty(key)) { + if (rightMap[key] === undefined || + !valueEquals(leftMap[key], rightMap[key])) { + return false; + } + } + } + return true; +} +/** Returns true if the ArrayValue contains the specified element. */ +function arrayValueContains(haystack, needle) { + return ((haystack.values || []).find(v => valueEquals(v, needle)) !== undefined); +} +function valueCompare(left, right) { + if (left === right) { + return 0; + } + const leftType = typeOrder(left); + const rightType = typeOrder(right); + if (leftType !== rightType) { + return primitiveComparator(leftType, rightType); + } + switch (leftType) { + case 0 /* TypeOrder.NullValue */: + case 9007199254740991 /* TypeOrder.MaxValue */: + return 0; + case 1 /* TypeOrder.BooleanValue */: + return primitiveComparator(left.booleanValue, right.booleanValue); + case 2 /* TypeOrder.NumberValue */: + return compareNumbers(left, right); + case 3 /* TypeOrder.TimestampValue */: + return compareTimestamps(left.timestampValue, right.timestampValue); + case 4 /* TypeOrder.ServerTimestampValue */: + return compareTimestamps(getLocalWriteTime(left), getLocalWriteTime(right)); + case 5 /* TypeOrder.StringValue */: + return compareUtf8Strings(left.stringValue, right.stringValue); + case 6 /* TypeOrder.BlobValue */: + return compareBlobs(left.bytesValue, right.bytesValue); + case 7 /* TypeOrder.RefValue */: + return compareReferences(left.referenceValue, right.referenceValue); + case 8 /* TypeOrder.GeoPointValue */: + return compareGeoPoints(left.geoPointValue, right.geoPointValue); + case 9 /* TypeOrder.ArrayValue */: + return compareArrays(left.arrayValue, right.arrayValue); + case 10 /* TypeOrder.VectorValue */: + return compareVectors(left.mapValue, right.mapValue); + case 11 /* TypeOrder.ObjectValue */: + return compareMaps(left.mapValue, right.mapValue); + default: + throw fail(0x5ae0, { leftType }); + } +} +function compareNumbers(left, right) { + const leftNumber = normalizeNumber(left.integerValue || left.doubleValue); + const rightNumber = normalizeNumber(right.integerValue || right.doubleValue); + if (leftNumber < rightNumber) { + return -1; + } + else if (leftNumber > rightNumber) { + return 1; + } + else if (leftNumber === rightNumber) { + return 0; + } + else { + // one or both are NaN. + if (isNaN(leftNumber)) { + return isNaN(rightNumber) ? 0 : -1; + } + else { + return 1; + } + } +} +function compareTimestamps(left, right) { + if (typeof left === 'string' && + typeof right === 'string' && + left.length === right.length) { + return primitiveComparator(left, right); + } + const leftTimestamp = normalizeTimestamp(left); + const rightTimestamp = normalizeTimestamp(right); + const comparison = primitiveComparator(leftTimestamp.seconds, rightTimestamp.seconds); + if (comparison !== 0) { + return comparison; + } + return primitiveComparator(leftTimestamp.nanos, rightTimestamp.nanos); +} +function compareReferences(leftPath, rightPath) { + const leftSegments = leftPath.split('/'); + const rightSegments = rightPath.split('/'); + for (let i = 0; i < leftSegments.length && i < rightSegments.length; i++) { + const comparison = primitiveComparator(leftSegments[i], rightSegments[i]); + if (comparison !== 0) { + return comparison; + } + } + return primitiveComparator(leftSegments.length, rightSegments.length); +} +function compareGeoPoints(left, right) { + const comparison = primitiveComparator(normalizeNumber(left.latitude), normalizeNumber(right.latitude)); + if (comparison !== 0) { + return comparison; + } + return primitiveComparator(normalizeNumber(left.longitude), normalizeNumber(right.longitude)); +} +function compareBlobs(left, right) { + const leftBytes = normalizeByteString(left); + const rightBytes = normalizeByteString(right); + return leftBytes.compareTo(rightBytes); +} +function compareArrays(left, right) { + const leftArray = left.values || []; + const rightArray = right.values || []; + for (let i = 0; i < leftArray.length && i < rightArray.length; ++i) { + const compare = valueCompare(leftArray[i], rightArray[i]); + if (compare) { + return compare; + } + } + return primitiveComparator(leftArray.length, rightArray.length); +} +function compareVectors(left, right) { + const leftMap = left.fields || {}; + const rightMap = right.fields || {}; + // The vector is a map, but only vector value is compared. + const leftArrayValue = leftMap[VECTOR_MAP_VECTORS_KEY]?.arrayValue; + const rightArrayValue = rightMap[VECTOR_MAP_VECTORS_KEY]?.arrayValue; + const lengthCompare = primitiveComparator(leftArrayValue?.values?.length || 0, rightArrayValue?.values?.length || 0); + if (lengthCompare !== 0) { + return lengthCompare; + } + return compareArrays(leftArrayValue, rightArrayValue); +} +function compareMaps(left, right) { + if (left === MAX_VALUE.mapValue && right === MAX_VALUE.mapValue) { + return 0; + } + else if (left === MAX_VALUE.mapValue) { + return 1; + } + else if (right === MAX_VALUE.mapValue) { + return -1; + } + const leftMap = left.fields || {}; + const leftKeys = Object.keys(leftMap); + const rightMap = right.fields || {}; + const rightKeys = Object.keys(rightMap); + // Even though MapValues are likely sorted correctly based on their insertion + // order (e.g. when received from the backend), local modifications can bring + // elements out of order. We need to re-sort the elements to ensure that + // canonical IDs are independent of insertion order. + leftKeys.sort(); + rightKeys.sort(); + for (let i = 0; i < leftKeys.length && i < rightKeys.length; ++i) { + const keyCompare = compareUtf8Strings(leftKeys[i], rightKeys[i]); + if (keyCompare !== 0) { + return keyCompare; + } + const compare = valueCompare(leftMap[leftKeys[i]], rightMap[rightKeys[i]]); + if (compare !== 0) { + return compare; + } + } + return primitiveComparator(leftKeys.length, rightKeys.length); +} +/** Returns a reference value for the provided database and key. */ +function refValue(databaseId, key) { + return { + referenceValue: `projects/${databaseId.projectId}/databases/${databaseId.database}/documents/${key.path.canonicalString()}` + }; +} +/** Returns true if `value` is an ArrayValue. */ +function isArray(value) { + return !!value && 'arrayValue' in value; +} +/** Returns true if `value` is a NullValue. */ +function isNullValue(value) { + return !!value && 'nullValue' in value; +} +/** Returns true if `value` is NaN. */ +function isNanValue(value) { + return !!value && 'doubleValue' in value && isNaN(Number(value.doubleValue)); +} +/** Returns true if `value` is a MapValue. */ +function isMapValue(value) { + return !!value && 'mapValue' in value; +} +/** Returns true if `value` is a VetorValue. */ +function isVectorValue(value) { + const type = (value?.mapValue?.fields || {})[TYPE_KEY]?.stringValue; + return type === VECTOR_VALUE_SENTINEL; +} +/** Creates a deep copy of `source`. */ +function deepClone(source) { + if (source.geoPointValue) { + return { geoPointValue: { ...source.geoPointValue } }; + } + else if (source.timestampValue && + typeof source.timestampValue === 'object') { + return { timestampValue: { ...source.timestampValue } }; + } + else if (source.mapValue) { + const target = { mapValue: { fields: {} } }; + forEach(source.mapValue.fields, (key, val) => (target.mapValue.fields[key] = deepClone(val))); + return target; + } + else if (source.arrayValue) { + const target = { arrayValue: { values: [] } }; + for (let i = 0; i < (source.arrayValue.values || []).length; ++i) { + target.arrayValue.values[i] = deepClone(source.arrayValue.values[i]); + } + return target; + } + else { + return { ...source }; + } +} +/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ +function isMaxValue(value) { + return ((((value.mapValue || {}).fields || {})['__type__'] || {}).stringValue === + MAX_VALUE_TYPE); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a bound of a query. + * + * The bound is specified with the given components representing a position and + * whether it's just before or just after the position (relative to whatever the + * query order is). + * + * The position represents a logical index position for a query. It's a prefix + * of values for the (potentially implicit) order by clauses of a query. + * + * Bound provides a function to determine whether a document comes before or + * after a bound. This is influenced by whether the position is just before or + * just after the provided values. + */ +class Bound { + constructor(position, inclusive) { + this.position = position; + this.inclusive = inclusive; + } +} +function boundEquals(left, right) { + if (left === null) { + return right === null; + } + else if (right === null) { + return false; + } + if (left.inclusive !== right.inclusive || + left.position.length !== right.position.length) { + return false; + } + for (let i = 0; i < left.position.length; i++) { + const leftPosition = left.position[i]; + const rightPosition = right.position[i]; + if (!valueEquals(leftPosition, rightPosition)) { + return false; + } + } + return true; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Filter { +} +class FieldFilter extends Filter { + constructor(field, op, value) { + super(); + this.field = field; + this.op = op; + this.value = value; + } + /** + * Creates a filter based on the provided arguments. + */ + static create(field, op, value) { + if (field.isKeyField()) { + if (op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */) { + return this.createKeyFieldInFilter(field, op, value); + } + else { + return new KeyFieldFilter(field, op, value); + } + } + else if (op === "array-contains" /* Operator.ARRAY_CONTAINS */) { + return new ArrayContainsFilter(field, value); + } + else if (op === "in" /* Operator.IN */) { + return new InFilter(field, value); + } + else if (op === "not-in" /* Operator.NOT_IN */) { + return new NotInFilter(field, value); + } + else if (op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) { + return new ArrayContainsAnyFilter(field, value); + } + else { + return new FieldFilter(field, op, value); + } + } + static createKeyFieldInFilter(field, op, value) { + return op === "in" /* Operator.IN */ + ? new KeyFieldInFilter(field, value) + : new KeyFieldNotInFilter(field, value); + } + matches(doc) { + const other = doc.data.field(this.field); + // Types do not have to match in NOT_EQUAL filters. + if (this.op === "!=" /* Operator.NOT_EQUAL */) { + return (other !== null && + other.nullValue === undefined && + this.matchesComparison(valueCompare(other, this.value))); + } + // Only compare types with matching backend order (such as double and int). + return (other !== null && + typeOrder(this.value) === typeOrder(other) && + this.matchesComparison(valueCompare(other, this.value))); + } + matchesComparison(comparison) { + switch (this.op) { + case "<" /* Operator.LESS_THAN */: + return comparison < 0; + case "<=" /* Operator.LESS_THAN_OR_EQUAL */: + return comparison <= 0; + case "==" /* Operator.EQUAL */: + return comparison === 0; + case "!=" /* Operator.NOT_EQUAL */: + return comparison !== 0; + case ">" /* Operator.GREATER_THAN */: + return comparison > 0; + case ">=" /* Operator.GREATER_THAN_OR_EQUAL */: + return comparison >= 0; + default: + return fail(0xb8a2, { + operator: this.op + }); + } + } + isInequality() { + return ([ + "<" /* Operator.LESS_THAN */, + "<=" /* Operator.LESS_THAN_OR_EQUAL */, + ">" /* Operator.GREATER_THAN */, + ">=" /* Operator.GREATER_THAN_OR_EQUAL */, + "!=" /* Operator.NOT_EQUAL */, + "not-in" /* Operator.NOT_IN */ + ].indexOf(this.op) >= 0); + } + getFlattenedFilters() { + return [this]; + } + getFilters() { + return [this]; + } +} +class CompositeFilter extends Filter { + constructor(filters, op) { + super(); + this.filters = filters; + this.op = op; + this.memoizedFlattenedFilters = null; + } + /** + * Creates a filter based on the provided arguments. + */ + static create(filters, op) { + return new CompositeFilter(filters, op); + } + matches(doc) { + if (compositeFilterIsConjunction(this)) { + // For conjunctions, all filters must match, so return false if any filter doesn't match. + return this.filters.find(filter => !filter.matches(doc)) === undefined; + } + else { + // For disjunctions, at least one filter should match. + return this.filters.find(filter => filter.matches(doc)) !== undefined; + } + } + getFlattenedFilters() { + if (this.memoizedFlattenedFilters !== null) { + return this.memoizedFlattenedFilters; + } + this.memoizedFlattenedFilters = this.filters.reduce((result, subfilter) => { + return result.concat(subfilter.getFlattenedFilters()); + }, []); + return this.memoizedFlattenedFilters; + } + // Returns a mutable copy of `this.filters` + getFilters() { + return Object.assign([], this.filters); + } +} +function compositeFilterIsConjunction(compositeFilter) { + return compositeFilter.op === "and" /* CompositeOperator.AND */; +} +function filterEquals(f1, f2) { + if (f1 instanceof FieldFilter) { + return fieldFilterEquals(f1, f2); + } + else if (f1 instanceof CompositeFilter) { + return compositeFilterEquals(f1, f2); + } + else { + fail(0x4bef); + } +} +function fieldFilterEquals(f1, f2) { + return (f2 instanceof FieldFilter && + f1.op === f2.op && + f1.field.isEqual(f2.field) && + valueEquals(f1.value, f2.value)); +} +function compositeFilterEquals(f1, f2) { + if (f2 instanceof CompositeFilter && + f1.op === f2.op && + f1.filters.length === f2.filters.length) { + const subFiltersMatch = f1.filters.reduce((result, f1Filter, index) => result && filterEquals(f1Filter, f2.filters[index]), true); + return subFiltersMatch; + } + return false; +} +/** Filter that matches on key fields (i.e. '__name__'). */ +class KeyFieldFilter extends FieldFilter { + constructor(field, op, value) { + super(field, op, value); + this.key = DocumentKey.fromName(value.referenceValue); + } + matches(doc) { + const comparison = DocumentKey.comparator(doc.key, this.key); + return this.matchesComparison(comparison); + } +} +/** Filter that matches on key fields within an array. */ +class KeyFieldInFilter extends FieldFilter { + constructor(field, value) { + super(field, "in" /* Operator.IN */, value); + this.keys = extractDocumentKeysFromArrayValue("in" /* Operator.IN */, value); + } + matches(doc) { + return this.keys.some(key => key.isEqual(doc.key)); + } +} +/** Filter that matches on key fields not present within an array. */ +class KeyFieldNotInFilter extends FieldFilter { + constructor(field, value) { + super(field, "not-in" /* Operator.NOT_IN */, value); + this.keys = extractDocumentKeysFromArrayValue("not-in" /* Operator.NOT_IN */, value); + } + matches(doc) { + return !this.keys.some(key => key.isEqual(doc.key)); + } +} +function extractDocumentKeysFromArrayValue(op, value) { + return (value.arrayValue?.values || []).map(v => { + return DocumentKey.fromName(v.referenceValue); + }); +} +/** A Filter that implements the array-contains operator. */ +class ArrayContainsFilter extends FieldFilter { + constructor(field, value) { + super(field, "array-contains" /* Operator.ARRAY_CONTAINS */, value); + } + matches(doc) { + const other = doc.data.field(this.field); + return isArray(other) && arrayValueContains(other.arrayValue, this.value); + } +} +/** A Filter that implements the IN operator. */ +class InFilter extends FieldFilter { + constructor(field, value) { + super(field, "in" /* Operator.IN */, value); + } + matches(doc) { + const other = doc.data.field(this.field); + return other !== null && arrayValueContains(this.value.arrayValue, other); + } +} +/** A Filter that implements the not-in operator. */ +class NotInFilter extends FieldFilter { + constructor(field, value) { + super(field, "not-in" /* Operator.NOT_IN */, value); + } + matches(doc) { + if (arrayValueContains(this.value.arrayValue, { nullValue: 'NULL_VALUE' })) { + return false; + } + const other = doc.data.field(this.field); + return (other !== null && + other.nullValue === undefined && + !arrayValueContains(this.value.arrayValue, other)); + } +} +/** A Filter that implements the array-contains-any operator. */ +class ArrayContainsAnyFilter extends FieldFilter { + constructor(field, value) { + super(field, "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */, value); + } + matches(doc) { + const other = doc.data.field(this.field); + if (!isArray(other) || !other.arrayValue.values) { + return false; + } + return other.arrayValue.values.some(val => arrayValueContains(this.value.arrayValue, val)); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An ordering on a field, in some Direction. Direction defaults to ASCENDING. + */ +class OrderBy { + constructor(field, dir = "asc" /* Direction.ASCENDING */) { + this.field = field; + this.dir = dir; + } +} +function orderByEquals(left, right) { + return left.dir === right.dir && left.field.isEqual(right.field); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A version of a document in Firestore. This corresponds to the version + * timestamp, such as update_time or read_time. + */ +class SnapshotVersion { + static fromTimestamp(value) { + return new SnapshotVersion(value); + } + static min() { + return new SnapshotVersion(new Timestamp(0, 0)); + } + static max() { + return new SnapshotVersion(new Timestamp(253402300799, 1e9 - 1)); + } + constructor(timestamp) { + this.timestamp = timestamp; + } + compareTo(other) { + return this.timestamp._compareTo(other.timestamp); + } + isEqual(other) { + return this.timestamp.isEqual(other.timestamp); + } + /** Returns a number representation of the version for use in spec tests. */ + toMicroseconds() { + // Convert to microseconds. + return this.timestamp.seconds * 1e6 + this.timestamp.nanoseconds / 1000; + } + toString() { + return 'SnapshotVersion(' + this.timestamp.toString() + ')'; + } + toTimestamp() { + return this.timestamp; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// An immutable sorted map implementation, based on a Left-leaning Red-Black +// tree. +class SortedMap { + constructor(comparator, root) { + this.comparator = comparator; + this.root = root ? root : LLRBNode.EMPTY; + } + // Returns a copy of the map, with the specified key/value added or replaced. + insert(key, value) { + return new SortedMap(this.comparator, this.root + .insert(key, value, this.comparator) + .copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns a copy of the map, with the specified key removed. + remove(key) { + return new SortedMap(this.comparator, this.root + .remove(key, this.comparator) + .copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns the value of the node with the given key, or null. + get(key) { + let node = this.root; + while (!node.isEmpty()) { + const cmp = this.comparator(key, node.key); + if (cmp === 0) { + return node.value; + } + else if (cmp < 0) { + node = node.left; + } + else if (cmp > 0) { + node = node.right; + } + } + return null; + } + // Returns the index of the element in this sorted map, or -1 if it doesn't + // exist. + indexOf(key) { + // Number of nodes that were pruned when descending right + let prunedNodes = 0; + let node = this.root; + while (!node.isEmpty()) { + const cmp = this.comparator(key, node.key); + if (cmp === 0) { + return prunedNodes + node.left.size; + } + else if (cmp < 0) { + node = node.left; + } + else { + // Count all nodes left of the node plus the node itself + prunedNodes += node.left.size + 1; + node = node.right; + } + } + // Node not found + return -1; + } + isEmpty() { + return this.root.isEmpty(); + } + // Returns the total number of nodes in the map. + get size() { + return this.root.size; + } + // Returns the minimum key in the map. + minKey() { + return this.root.minKey(); + } + // Returns the maximum key in the map. + maxKey() { + return this.root.maxKey(); + } + // Traverses the map in key order and calls the specified action function + // for each key/value pair. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(action) { + return this.root.inorderTraversal(action); + } + forEach(fn) { + this.inorderTraversal((k, v) => { + fn(k, v); + return false; + }); + } + toString() { + const descriptions = []; + this.inorderTraversal((k, v) => { + descriptions.push(`${k}:${v}`); + return false; + }); + return `{${descriptions.join(', ')}}`; + } + // Traverses the map in reverse key order and calls the specified action + // function for each key/value pair. If action returns true, traversal is + // aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(action) { + return this.root.reverseTraversal(action); + } + // Returns an iterator over the SortedMap. + getIterator() { + return new SortedMapIterator(this.root, null, this.comparator, false); + } + getIteratorFrom(key) { + return new SortedMapIterator(this.root, key, this.comparator, false); + } + getReverseIterator() { + return new SortedMapIterator(this.root, null, this.comparator, true); + } + getReverseIteratorFrom(key) { + return new SortedMapIterator(this.root, key, this.comparator, true); + } +} // end SortedMap +// An iterator over an LLRBNode. +class SortedMapIterator { + constructor(node, startKey, comparator, isReverse) { + this.isReverse = isReverse; + this.nodeStack = []; + let cmp = 1; + while (!node.isEmpty()) { + cmp = startKey ? comparator(node.key, startKey) : 1; + // flip the comparison if we're going in reverse + if (startKey && isReverse) { + cmp *= -1; + } + if (cmp < 0) { + // This node is less than our start key. ignore it + if (this.isReverse) { + node = node.left; + } + else { + node = node.right; + } + } + else if (cmp === 0) { + // This node is exactly equal to our start key. Push it on the stack, + // but stop iterating; + this.nodeStack.push(node); + break; + } + else { + // This node is greater than our start key, add it to the stack and move + // to the next one + this.nodeStack.push(node); + if (this.isReverse) { + node = node.right; + } + else { + node = node.left; + } + } + } + } + getNext() { + let node = this.nodeStack.pop(); + const result = { key: node.key, value: node.value }; + if (this.isReverse) { + node = node.left; + while (!node.isEmpty()) { + this.nodeStack.push(node); + node = node.right; + } + } + else { + node = node.right; + while (!node.isEmpty()) { + this.nodeStack.push(node); + node = node.left; + } + } + return result; + } + hasNext() { + return this.nodeStack.length > 0; + } + peek() { + if (this.nodeStack.length === 0) { + return null; + } + const node = this.nodeStack[this.nodeStack.length - 1]; + return { key: node.key, value: node.value }; + } +} // end SortedMapIterator +// Represents a node in a Left-leaning Red-Black tree. +class LLRBNode { + constructor(key, value, color, left, right) { + this.key = key; + this.value = value; + this.color = color != null ? color : LLRBNode.RED; + this.left = left != null ? left : LLRBNode.EMPTY; + this.right = right != null ? right : LLRBNode.EMPTY; + this.size = this.left.size + 1 + this.right.size; + } + // Returns a copy of the current node, optionally replacing pieces of it. + copy(key, value, color, left, right) { + return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right); + } + isEmpty() { + return false; + } + // Traverses the tree in key order and calls the specified action function + // for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(action) { + return (this.left.inorderTraversal(action) || + action(this.key, this.value) || + this.right.inorderTraversal(action)); + } + // Traverses the tree in reverse key order and calls the specified action + // function for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(action) { + return (this.right.reverseTraversal(action) || + action(this.key, this.value) || + this.left.reverseTraversal(action)); + } + // Returns the minimum node in the tree. + min() { + if (this.left.isEmpty()) { + return this; + } + else { + return this.left.min(); + } + } + // Returns the maximum key in the tree. + minKey() { + return this.min().key; + } + // Returns the maximum key in the tree. + maxKey() { + if (this.right.isEmpty()) { + return this.key; + } + else { + return this.right.maxKey(); + } + } + // Returns new tree, with the key/value added. + insert(key, value, comparator) { + let n = this; + const cmp = comparator(key, n.key); + if (cmp < 0) { + n = n.copy(null, null, null, n.left.insert(key, value, comparator), null); + } + else if (cmp === 0) { + n = n.copy(null, value, null, null, null); + } + else { + n = n.copy(null, null, null, null, n.right.insert(key, value, comparator)); + } + return n.fixUp(); + } + removeMin() { + if (this.left.isEmpty()) { + return LLRBNode.EMPTY; + } + let n = this; + if (!n.left.isRed() && !n.left.left.isRed()) { + n = n.moveRedLeft(); + } + n = n.copy(null, null, null, n.left.removeMin(), null); + return n.fixUp(); + } + // Returns new tree, with the specified item removed. + remove(key, comparator) { + let smallest; + let n = this; + if (comparator(key, n.key) < 0) { + if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) { + n = n.moveRedLeft(); + } + n = n.copy(null, null, null, n.left.remove(key, comparator), null); + } + else { + if (n.left.isRed()) { + n = n.rotateRight(); + } + if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) { + n = n.moveRedRight(); + } + if (comparator(key, n.key) === 0) { + if (n.right.isEmpty()) { + return LLRBNode.EMPTY; + } + else { + smallest = n.right.min(); + n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin()); + } + } + n = n.copy(null, null, null, null, n.right.remove(key, comparator)); + } + return n.fixUp(); + } + isRed() { + return this.color; + } + // Returns new tree after performing any needed rotations. + fixUp() { + let n = this; + if (n.right.isRed() && !n.left.isRed()) { + n = n.rotateLeft(); + } + if (n.left.isRed() && n.left.left.isRed()) { + n = n.rotateRight(); + } + if (n.left.isRed() && n.right.isRed()) { + n = n.colorFlip(); + } + return n; + } + moveRedLeft() { + let n = this.colorFlip(); + if (n.right.left.isRed()) { + n = n.copy(null, null, null, null, n.right.rotateRight()); + n = n.rotateLeft(); + n = n.colorFlip(); + } + return n; + } + moveRedRight() { + let n = this.colorFlip(); + if (n.left.left.isRed()) { + n = n.rotateRight(); + n = n.colorFlip(); + } + return n; + } + rotateLeft() { + const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left); + return this.right.copy(null, null, this.color, nl, null); + } + rotateRight() { + const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null); + return this.left.copy(null, null, this.color, null, nr); + } + colorFlip() { + const left = this.left.copy(null, null, !this.left.color, null, null); + const right = this.right.copy(null, null, !this.right.color, null, null); + return this.copy(null, null, !this.color, left, right); + } + // For testing. + checkMaxDepth() { + const blackDepth = this.check(); + if (Math.pow(2.0, blackDepth) <= this.size + 1) { + return true; + } + else { + return false; + } + } + // In a balanced RB tree, the black-depth (number of black nodes) from root to + // leaves is equal on both sides. This function verifies that or asserts. + check() { + if (this.isRed() && this.left.isRed()) { + throw fail(0xaad2, { + key: this.key, + value: this.value + }); + } + if (this.right.isRed()) { + throw fail(0x3721, { + key: this.key, + value: this.value + }); + } + const blackDepth = this.left.check(); + if (blackDepth !== this.right.check()) { + throw fail(0x6d2d); + } + else { + return blackDepth + (this.isRed() ? 0 : 1); + } + } +} // end LLRBNode +// Empty node is shared between all LLRB trees. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +LLRBNode.EMPTY = null; +LLRBNode.RED = true; +LLRBNode.BLACK = false; +// Represents an empty node (a leaf node in the Red-Black Tree). +class LLRBEmptyNode { + constructor() { + this.size = 0; + } + get key() { + throw fail(0xe1a6); + } + get value() { + throw fail(0x3f0d); + } + get color() { + throw fail(0x4157); + } + get left() { + throw fail(0x741e); + } + get right() { + throw fail(0x901e); + } + // Returns a copy of the current node. + copy(key, value, color, left, right) { + return this; + } + // Returns a copy of the tree, with the specified key/value added. + insert(key, value, comparator) { + return new LLRBNode(key, value); + } + // Returns a copy of the tree, with the specified key removed. + remove(key, comparator) { + return this; + } + isEmpty() { + return true; + } + inorderTraversal(action) { + return false; + } + reverseTraversal(action) { + return false; + } + minKey() { + return null; + } + maxKey() { + return null; + } + isRed() { + return false; + } + // For testing. + checkMaxDepth() { + return true; + } + check() { + return 0; + } +} // end LLRBEmptyNode +LLRBNode.EMPTY = new LLRBEmptyNode(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * SortedSet is an immutable (copy-on-write) collection that holds elements + * in order specified by the provided comparator. + * + * NOTE: if provided comparator returns 0 for two elements, we consider them to + * be equal! + */ +class SortedSet { + constructor(comparator) { + this.comparator = comparator; + this.data = new SortedMap(this.comparator); + } + has(elem) { + return this.data.get(elem) !== null; + } + first() { + return this.data.minKey(); + } + last() { + return this.data.maxKey(); + } + get size() { + return this.data.size; + } + indexOf(elem) { + return this.data.indexOf(elem); + } + /** Iterates elements in order defined by "comparator" */ + forEach(cb) { + this.data.inorderTraversal((k, v) => { + cb(k); + return false; + }); + } + /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ + forEachInRange(range, cb) { + const iter = this.data.getIteratorFrom(range[0]); + while (iter.hasNext()) { + const elem = iter.getNext(); + if (this.comparator(elem.key, range[1]) >= 0) { + return; + } + cb(elem.key); + } + } + /** + * Iterates over `elem`s such that: start <= elem until false is returned. + */ + forEachWhile(cb, start) { + let iter; + if (start !== undefined) { + iter = this.data.getIteratorFrom(start); + } + else { + iter = this.data.getIterator(); + } + while (iter.hasNext()) { + const elem = iter.getNext(); + const result = cb(elem.key); + if (!result) { + return; + } + } + } + /** Finds the least element greater than or equal to `elem`. */ + firstAfterOrEqual(elem) { + const iter = this.data.getIteratorFrom(elem); + return iter.hasNext() ? iter.getNext().key : null; + } + getIterator() { + return new SortedSetIterator(this.data.getIterator()); + } + getIteratorFrom(key) { + return new SortedSetIterator(this.data.getIteratorFrom(key)); + } + /** Inserts or updates an element */ + add(elem) { + return this.copy(this.data.remove(elem).insert(elem, true)); + } + /** Deletes an element */ + delete(elem) { + if (!this.has(elem)) { + return this; + } + return this.copy(this.data.remove(elem)); + } + isEmpty() { + return this.data.isEmpty(); + } + unionWith(other) { + let result = this; + // Make sure `result` always refers to the larger one of the two sets. + if (result.size < other.size) { + result = other; + other = this; + } + other.forEach(elem => { + result = result.add(elem); + }); + return result; + } + isEqual(other) { + if (!(other instanceof SortedSet)) { + return false; + } + if (this.size !== other.size) { + return false; + } + const thisIt = this.data.getIterator(); + const otherIt = other.data.getIterator(); + while (thisIt.hasNext()) { + const thisElem = thisIt.getNext().key; + const otherElem = otherIt.getNext().key; + if (this.comparator(thisElem, otherElem) !== 0) { + return false; + } + } + return true; + } + toArray() { + const res = []; + this.forEach(targetId => { + res.push(targetId); + }); + return res; + } + toString() { + const result = []; + this.forEach(elem => result.push(elem)); + return 'SortedSet(' + result.toString() + ')'; + } + copy(data) { + const result = new SortedSet(this.comparator); + result.data = data; + return result; + } +} +class SortedSetIterator { + constructor(iter) { + this.iter = iter; + } + getNext() { + return this.iter.getNext().key; + } + hasNext() { + return this.iter.hasNext(); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provides a set of fields that can be used to partially patch a document. + * FieldMask is used in conjunction with ObjectValue. + * Examples: + * foo - Overwrites foo entirely with the provided value. If foo is not + * present in the companion ObjectValue, the field is deleted. + * foo.bar - Overwrites only the field bar of the object foo. + * If foo is not an object, foo is replaced with an object + * containing foo + */ +class FieldMask { + constructor(fields) { + this.fields = fields; + // TODO(dimond): validation of FieldMask + // Sort the field mask to support `FieldMask.isEqual()` and assert below. + fields.sort(FieldPath$1.comparator); + } + static empty() { + return new FieldMask([]); + } + /** + * Returns a new FieldMask object that is the result of adding all the given + * fields paths to this field mask. + */ + unionWith(extraFields) { + let mergedMaskSet = new SortedSet(FieldPath$1.comparator); + for (const fieldPath of this.fields) { + mergedMaskSet = mergedMaskSet.add(fieldPath); + } + for (const fieldPath of extraFields) { + mergedMaskSet = mergedMaskSet.add(fieldPath); + } + return new FieldMask(mergedMaskSet.toArray()); + } + /** + * Verifies that `fieldPath` is included by at least one field in this field + * mask. + * + * This is an O(n) operation, where `n` is the size of the field mask. + */ + covers(fieldPath) { + for (const fieldMaskPath of this.fields) { + if (fieldMaskPath.isPrefixOf(fieldPath)) { + return true; + } + } + return false; + } + isEqual(other) { + return arrayEquals(this.fields, other.fields, (l, r) => l.isEqual(r)); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An ObjectValue represents a MapValue in the Firestore Proto and offers the + * ability to add and remove fields (via the ObjectValueBuilder). + */ +class ObjectValue { + constructor(value) { + this.value = value; + } + static empty() { + return new ObjectValue({ mapValue: {} }); + } + /** + * Returns the value at the given path or null. + * + * @param path - the path to search + * @returns The value at the path or null if the path is not set. + */ + field(path) { + if (path.isEmpty()) { + return this.value; + } + else { + let currentLevel = this.value; + for (let i = 0; i < path.length - 1; ++i) { + currentLevel = (currentLevel.mapValue.fields || {})[path.get(i)]; + if (!isMapValue(currentLevel)) { + return null; + } + } + currentLevel = (currentLevel.mapValue.fields || {})[path.lastSegment()]; + return currentLevel || null; + } + } + /** + * Sets the field to the provided value. + * + * @param path - The field path to set. + * @param value - The value to set. + */ + set(path, value) { + const fieldsMap = this.getFieldsMap(path.popLast()); + fieldsMap[path.lastSegment()] = deepClone(value); + } + /** + * Sets the provided fields to the provided values. + * + * @param data - A map of fields to values (or null for deletes). + */ + setAll(data) { + let parent = FieldPath$1.emptyPath(); + let upserts = {}; + let deletes = []; + data.forEach((value, path) => { + if (!parent.isImmediateParentOf(path)) { + // Insert the accumulated changes at this parent location + const fieldsMap = this.getFieldsMap(parent); + this.applyChanges(fieldsMap, upserts, deletes); + upserts = {}; + deletes = []; + parent = path.popLast(); + } + if (value) { + upserts[path.lastSegment()] = deepClone(value); + } + else { + deletes.push(path.lastSegment()); + } + }); + const fieldsMap = this.getFieldsMap(parent); + this.applyChanges(fieldsMap, upserts, deletes); + } + /** + * Removes the field at the specified path. If there is no field at the + * specified path, nothing is changed. + * + * @param path - The field path to remove. + */ + delete(path) { + const nestedValue = this.field(path.popLast()); + if (isMapValue(nestedValue) && nestedValue.mapValue.fields) { + delete nestedValue.mapValue.fields[path.lastSegment()]; + } + } + isEqual(other) { + return valueEquals(this.value, other.value); + } + /** + * Returns the map that contains the leaf element of `path`. If the parent + * entry does not yet exist, or if it is not a map, a new map will be created. + */ + getFieldsMap(path) { + let current = this.value; + if (!current.mapValue.fields) { + current.mapValue = { fields: {} }; + } + for (let i = 0; i < path.length; ++i) { + let next = current.mapValue.fields[path.get(i)]; + if (!isMapValue(next) || !next.mapValue.fields) { + next = { mapValue: { fields: {} } }; + current.mapValue.fields[path.get(i)] = next; + } + current = next; + } + return current.mapValue.fields; + } + /** + * Modifies `fieldsMap` by adding, replacing or deleting the specified + * entries. + */ + applyChanges(fieldsMap, inserts, deletes) { + forEach(inserts, (key, val) => (fieldsMap[key] = val)); + for (const field of deletes) { + delete fieldsMap[field]; + } + } + clone() { + return new ObjectValue(deepClone(this.value)); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a document in Firestore with a key, version, data and whether it + * has local mutations applied to it. + * + * Documents can transition between states via `convertToFoundDocument()`, + * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does + * not transition to one of these states even after all mutations have been + * applied, `isValidDocument()` returns false and the document should be removed + * from all views. + */ +class MutableDocument { + constructor(key, documentType, version, readTime, createTime, data, documentState) { + this.key = key; + this.documentType = documentType; + this.version = version; + this.readTime = readTime; + this.createTime = createTime; + this.data = data; + this.documentState = documentState; + } + /** + * Creates a document with no known version or data, but which can serve as + * base document for mutations. + */ + static newInvalidDocument(documentKey) { + return new MutableDocument(documentKey, 0 /* DocumentType.INVALID */, + /* version */ SnapshotVersion.min(), + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist with the given data at the + * given version. + */ + static newFoundDocument(documentKey, version, createTime, value) { + return new MutableDocument(documentKey, 1 /* DocumentType.FOUND_DOCUMENT */, + /* version */ version, + /* readTime */ SnapshotVersion.min(), + /* createTime */ createTime, value, 0 /* DocumentState.SYNCED */); + } + /** Creates a new document that is known to not exist at the given version. */ + static newNoDocument(documentKey, version) { + return new MutableDocument(documentKey, 2 /* DocumentType.NO_DOCUMENT */, + /* version */ version, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist at the given version but + * whose data is not known (e.g. a document that was updated without a known + * base document). + */ + static newUnknownDocument(documentKey, version) { + return new MutableDocument(documentKey, 3 /* DocumentType.UNKNOWN_DOCUMENT */, + /* version */ version, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */); + } + /** + * Changes the document type to indicate that it exists and that its version + * and data are known. + */ + convertToFoundDocument(version, value) { + // If a document is switching state from being an invalid or deleted + // document to a valid (FOUND_DOCUMENT) document, either due to receiving an + // update from Watch or due to applying a local set mutation on top + // of a deleted document, our best guess about its createTime would be the + // version at which the document transitioned to a FOUND_DOCUMENT. + if (this.createTime.isEqual(SnapshotVersion.min()) && + (this.documentType === 2 /* DocumentType.NO_DOCUMENT */ || + this.documentType === 0 /* DocumentType.INVALID */)) { + this.createTime = version; + } + this.version = version; + this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */; + this.data = value; + this.documentState = 0 /* DocumentState.SYNCED */; + return this; + } + /** + * Changes the document type to indicate that it doesn't exist at the given + * version. + */ + convertToNoDocument(version) { + this.version = version; + this.documentType = 2 /* DocumentType.NO_DOCUMENT */; + this.data = ObjectValue.empty(); + this.documentState = 0 /* DocumentState.SYNCED */; + return this; + } + /** + * Changes the document type to indicate that it exists at a given version but + * that its data is not known (e.g. a document that was updated without a known + * base document). + */ + convertToUnknownDocument(version) { + this.version = version; + this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */; + this.data = ObjectValue.empty(); + this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */; + return this; + } + setHasCommittedMutations() { + this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */; + return this; + } + setHasLocalMutations() { + this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */; + this.version = SnapshotVersion.min(); + return this; + } + setReadTime(readTime) { + this.readTime = readTime; + return this; + } + get hasLocalMutations() { + return this.documentState === 1 /* DocumentState.HAS_LOCAL_MUTATIONS */; + } + get hasCommittedMutations() { + return this.documentState === 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */; + } + get hasPendingWrites() { + return this.hasLocalMutations || this.hasCommittedMutations; + } + isValidDocument() { + return this.documentType !== 0 /* DocumentType.INVALID */; + } + isFoundDocument() { + return this.documentType === 1 /* DocumentType.FOUND_DOCUMENT */; + } + isNoDocument() { + return this.documentType === 2 /* DocumentType.NO_DOCUMENT */; + } + isUnknownDocument() { + return this.documentType === 3 /* DocumentType.UNKNOWN_DOCUMENT */; + } + isEqual(other) { + return (other instanceof MutableDocument && + this.key.isEqual(other.key) && + this.version.isEqual(other.version) && + this.documentType === other.documentType && + this.documentState === other.documentState && + this.data.isEqual(other.data)); + } + mutableCopy() { + return new MutableDocument(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState); + } + toString() { + return (`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, ` + + `{createTime: ${this.createTime}}), ` + + `{documentType: ${this.documentType}}), ` + + `{documentState: ${this.documentState}})`); + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Visible for testing +class TargetImpl { + constructor(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) { + this.path = path; + this.collectionGroup = collectionGroup; + this.orderBy = orderBy; + this.filters = filters; + this.limit = limit; + this.startAt = startAt; + this.endAt = endAt; + this.memoizedCanonicalId = null; + } +} +/** + * Initializes a Target with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + * + * NOTE: you should always construct `Target` from `Query.toTarget` instead of + * using this factory method, because `Query` provides an implicit `orderBy` + * property. + */ +function newTarget(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) { + return new TargetImpl(path, collectionGroup, orderBy, filters, limit, startAt, endAt); +} +function targetEquals(left, right) { + if (left.limit !== right.limit) { + return false; + } + if (left.orderBy.length !== right.orderBy.length) { + return false; + } + for (let i = 0; i < left.orderBy.length; i++) { + if (!orderByEquals(left.orderBy[i], right.orderBy[i])) { + return false; + } + } + if (left.filters.length !== right.filters.length) { + return false; + } + for (let i = 0; i < left.filters.length; i++) { + if (!filterEquals(left.filters[i], right.filters[i])) { + return false; + } + } + if (left.collectionGroup !== right.collectionGroup) { + return false; + } + if (!left.path.isEqual(right.path)) { + return false; + } + if (!boundEquals(left.startAt, right.startAt)) { + return false; + } + return boundEquals(left.endAt, right.endAt); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Query encapsulates all the query attributes we support in the SDK. It can + * be run against the LocalStore, as well as be converted to a `Target` to + * query the RemoteStore results. + * + * Visible for testing. + */ +class QueryImpl { + /** + * Initializes a Query with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + */ + constructor(path, collectionGroup = null, explicitOrderBy = [], filters = [], limit = null, limitType = "F" /* LimitType.First */, startAt = null, endAt = null) { + this.path = path; + this.collectionGroup = collectionGroup; + this.explicitOrderBy = explicitOrderBy; + this.filters = filters; + this.limit = limit; + this.limitType = limitType; + this.startAt = startAt; + this.endAt = endAt; + this.memoizedNormalizedOrderBy = null; + // The corresponding `Target` of this `Query` instance, for use with + // non-aggregate queries. + this.memoizedTarget = null; + // The corresponding `Target` of this `Query` instance, for use with + // aggregate queries. Unlike targets for non-aggregate queries, + // aggregate query targets do not contain normalized order-bys, they only + // contain explicit order-bys. + this.memoizedAggregateTarget = null; + if (this.startAt) ; + if (this.endAt) ; + } +} +/** Creates a new Query for a query that matches all documents at `path` */ +function newQueryForPath(path) { + return new QueryImpl(path); +} +// Returns the sorted set of inequality filter fields used in this query. +function getInequalityFilterFields(query) { + let result = new SortedSet(FieldPath$1.comparator); + query.filters.forEach((filter) => { + const subFilters = filter.getFlattenedFilters(); + subFilters.forEach((filter) => { + if (filter.isInequality()) { + result = result.add(filter.field); + } + }); + }); + return result; +} +/** + * Creates a new Query for a collection group query that matches all documents + * within the provided collection group. + */ +function newQueryForCollectionGroup(collectionId) { + return new QueryImpl(ResourcePath.emptyPath(), collectionId); +} +/** + * Returns whether the query matches a collection group rather than a specific + * collection. + */ +function isCollectionGroupQuery(query) { + return query.collectionGroup !== null; +} +/** + * Returns the normalized order-by constraint that is used to execute the Query, + * which can be different from the order-by constraints the user provided (e.g. + * the SDK and backend always orders by `__name__`). The normalized order-by + * includes implicit order-bys in addition to the explicit user provided + * order-bys. + */ +function queryNormalizedOrderBy(query) { + const queryImpl = debugCast(query); + if (queryImpl.memoizedNormalizedOrderBy === null) { + queryImpl.memoizedNormalizedOrderBy = []; + const fieldsNormalized = new Set(); + // Any explicit order by fields should be added as is. + for (const orderBy of queryImpl.explicitOrderBy) { + queryImpl.memoizedNormalizedOrderBy.push(orderBy); + fieldsNormalized.add(orderBy.field.canonicalString()); + } + // The order of the implicit ordering always matches the last explicit order by. + const lastDirection = queryImpl.explicitOrderBy.length > 0 + ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1].dir + : "asc" /* Direction.ASCENDING */; + // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical + // order. When there are multiple inequality filters on the same field, the field should be added + // only once. + // Note: `SortedSet` sorts the key field before other fields. However, we want the key + // field to be sorted last. + const inequalityFields = getInequalityFilterFields(queryImpl); + inequalityFields.forEach(field => { + if (!fieldsNormalized.has(field.canonicalString()) && + !field.isKeyField()) { + queryImpl.memoizedNormalizedOrderBy.push(new OrderBy(field, lastDirection)); + } + }); + // Add the document key field to the last if it is not explicitly ordered. + if (!fieldsNormalized.has(FieldPath$1.keyField().canonicalString())) { + queryImpl.memoizedNormalizedOrderBy.push(new OrderBy(FieldPath$1.keyField(), lastDirection)); + } + } + return queryImpl.memoizedNormalizedOrderBy; +} +/** + * Converts this `Query` instance to its corresponding `Target` representation. + */ +function queryToTarget(query) { + const queryImpl = debugCast(query); + if (!queryImpl.memoizedTarget) { + queryImpl.memoizedTarget = _queryToTarget(queryImpl, queryNormalizedOrderBy(query)); + } + return queryImpl.memoizedTarget; +} +/** + * Converts this `Query` instance to its corresponding `Target` representation, + * for use within an aggregate query. Unlike targets for non-aggregate queries, + * aggregate query targets do not contain normalized order-bys, they only + * contain explicit order-bys. + */ +function queryToAggregateTarget(query) { + const queryImpl = debugCast(query); + if (!queryImpl.memoizedAggregateTarget) { + // Do not include implicit order-bys for aggregate queries. + queryImpl.memoizedAggregateTarget = _queryToTarget(queryImpl, query.explicitOrderBy); + } + return queryImpl.memoizedAggregateTarget; +} +function _queryToTarget(queryImpl, orderBys) { + if (queryImpl.limitType === "F" /* LimitType.First */) { + return newTarget(queryImpl.path, queryImpl.collectionGroup, orderBys, queryImpl.filters, queryImpl.limit, queryImpl.startAt, queryImpl.endAt); + } + else { + // Flip the orderBy directions since we want the last results + orderBys = orderBys.map(orderBy => { + const dir = orderBy.dir === "desc" /* Direction.DESCENDING */ + ? "asc" /* Direction.ASCENDING */ + : "desc" /* Direction.DESCENDING */; + return new OrderBy(orderBy.field, dir); + }); + // We need to swap the cursors to match the now-flipped query ordering. + const startAt = queryImpl.endAt + ? new Bound(queryImpl.endAt.position, queryImpl.endAt.inclusive) + : null; + const endAt = queryImpl.startAt + ? new Bound(queryImpl.startAt.position, queryImpl.startAt.inclusive) + : null; + // Now return as a LimitType.First query. + return newTarget(queryImpl.path, queryImpl.collectionGroup, orderBys, queryImpl.filters, queryImpl.limit, startAt, endAt); + } +} +function queryWithAddedFilter(query, filter) { + const newFilters = query.filters.concat([filter]); + return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), newFilters, query.limit, query.limitType, query.startAt, query.endAt); +} +function queryWithAddedOrderBy(query, orderBy) { + // TODO(dimond): validate that orderBy does not list the same key twice. + const newOrderBy = query.explicitOrderBy.concat([orderBy]); + return new QueryImpl(query.path, query.collectionGroup, newOrderBy, query.filters.slice(), query.limit, query.limitType, query.startAt, query.endAt); +} +function queryWithLimit(query, limit, limitType) { + return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), limit, limitType, query.startAt, query.endAt); +} +function queryWithStartAt(query, bound) { + return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, bound, query.endAt); +} +function queryWithEndAt(query, bound) { + return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, query.startAt, bound); +} +function queryEquals(left, right) { + return (targetEquals(queryToTarget(left), queryToTarget(right)) && + left.limitType === right.limitType); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns an DoubleValue for `value` that is encoded based the serializer's + * `useProto3Json` setting. + */ +function toDouble(serializer, value) { + if (serializer.useProto3Json) { + if (isNaN(value)) { + return { doubleValue: 'NaN' }; + } + else if (value === Infinity) { + return { doubleValue: 'Infinity' }; + } + else if (value === -Infinity) { + return { doubleValue: '-Infinity' }; + } + } + return { doubleValue: isNegativeZero(value) ? '-0' : value }; +} +/** + * Returns an IntegerValue for `value`. + */ +function toInteger(value) { + return { integerValue: '' + value }; +} +/** + * Returns a value for a number that's appropriate to put into a proto. + * The return value is an IntegerValue if it can safely represent the value, + * otherwise a DoubleValue is returned. + */ +function toNumber(serializer, value) { + return isSafeInteger(value) ? toInteger(value) : toDouble(serializer, value); +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Used to represent a field transform on a mutation. */ +class TransformOperation { + constructor() { + // Make sure that the structural type of `TransformOperation` is unique. + // See https://github.com/microsoft/TypeScript/issues/5451 + this._ = undefined; + } +} +/** Transforms a value into a server-generated timestamp. */ +class ServerTimestampTransform extends TransformOperation { +} +/** Transforms an array value via a union operation. */ +class ArrayUnionTransformOperation extends TransformOperation { + constructor(elements) { + super(); + this.elements = elements; + } +} +/** Transforms an array value via a remove operation. */ +class ArrayRemoveTransformOperation extends TransformOperation { + constructor(elements) { + super(); + this.elements = elements; + } +} +/** + * Implements the backend semantics for locally computed NUMERIC_ADD (increment) + * transforms. Converts all field values to integers or doubles, but unlike the + * backend does not cap integer values at 2^63. Instead, JavaScript number + * arithmetic is used and precision loss can occur for values greater than 2^53. + */ +class NumericIncrementTransformOperation extends TransformOperation { + constructor(serializer, operand) { + super(); + this.serializer = serializer; + this.operand = operand; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** A field path and the TransformOperation to perform upon it. */ +class FieldTransform { + constructor(field, transform) { + this.field = field; + this.transform = transform; + } +} +/** + * Encodes a precondition for a mutation. This follows the model that the + * backend accepts with the special case of an explicit "empty" precondition + * (meaning no precondition). + */ +class Precondition { + constructor(updateTime, exists) { + this.updateTime = updateTime; + this.exists = exists; + } + /** Creates a new empty Precondition. */ + static none() { + return new Precondition(); + } + /** Creates a new Precondition with an exists flag. */ + static exists(exists) { + return new Precondition(undefined, exists); + } + /** Creates a new Precondition based on a version a document exists at. */ + static updateTime(version) { + return new Precondition(version); + } + /** Returns whether this Precondition is empty. */ + get isNone() { + return this.updateTime === undefined && this.exists === undefined; + } + isEqual(other) { + return (this.exists === other.exists && + (this.updateTime + ? !!other.updateTime && this.updateTime.isEqual(other.updateTime) + : !other.updateTime)); + } +} +/** + * A mutation describes a self-contained change to a document. Mutations can + * create, replace, delete, and update subsets of documents. + * + * Mutations not only act on the value of the document but also its version. + * + * For local mutations (mutations that haven't been committed yet), we preserve + * the existing version for Set and Patch mutations. For Delete mutations, we + * reset the version to 0. + * + * Here's the expected transition table. + * + * MUTATION APPLIED TO RESULTS IN + * + * SetMutation Document(v3) Document(v3) + * SetMutation NoDocument(v3) Document(v0) + * SetMutation InvalidDocument(v0) Document(v0) + * PatchMutation Document(v3) Document(v3) + * PatchMutation NoDocument(v3) NoDocument(v3) + * PatchMutation InvalidDocument(v0) UnknownDocument(v3) + * DeleteMutation Document(v3) NoDocument(v0) + * DeleteMutation NoDocument(v3) NoDocument(v0) + * DeleteMutation InvalidDocument(v0) NoDocument(v0) + * + * For acknowledged mutations, we use the updateTime of the WriteResponse as + * the resulting version for Set and Patch mutations. As deletes have no + * explicit update time, we use the commitTime of the WriteResponse for + * Delete mutations. + * + * If a mutation is acknowledged by the backend but fails the precondition check + * locally, we transition to an `UnknownDocument` and rely on Watch to send us + * the updated version. + * + * Field transforms are used only with Patch and Set Mutations. We use the + * `updateTransforms` message to store transforms, rather than the `transforms`s + * messages. + * + * ## Subclassing Notes + * + * Every type of mutation needs to implement its own applyToRemoteDocument() and + * applyToLocalView() to implement the actual behavior of applying the mutation + * to some source document (see `setMutationApplyToRemoteDocument()` for an + * example). + */ +class Mutation { +} +/** + * A mutation that creates or replaces the document at the given key with the + * object value contents. + */ +class SetMutation extends Mutation { + constructor(key, value, precondition, fieldTransforms = []) { + super(); + this.key = key; + this.value = value; + this.precondition = precondition; + this.fieldTransforms = fieldTransforms; + this.type = 0 /* MutationType.Set */; + } + getFieldMask() { + return null; + } +} +/** + * A mutation that modifies fields of the document at the given key with the + * given values. The values are applied through a field mask: + * + * * When a field is in both the mask and the values, the corresponding field + * is updated. + * * When a field is in neither the mask nor the values, the corresponding + * field is unmodified. + * * When a field is in the mask but not in the values, the corresponding field + * is deleted. + * * When a field is not in the mask but is in the values, the values map is + * ignored. + */ +class PatchMutation extends Mutation { + constructor(key, data, fieldMask, precondition, fieldTransforms = []) { + super(); + this.key = key; + this.data = data; + this.fieldMask = fieldMask; + this.precondition = precondition; + this.fieldTransforms = fieldTransforms; + this.type = 1 /* MutationType.Patch */; + } + getFieldMask() { + return this.fieldMask; + } +} +/** A mutation that deletes the document at the given key. */ +class DeleteMutation extends Mutation { + constructor(key, precondition) { + super(); + this.key = key; + this.precondition = precondition; + this.type = 2 /* MutationType.Delete */; + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } +} +/** + * A mutation that verifies the existence of the document at the given key with + * the provided precondition. + * + * The `verify` operation is only used in Transactions, and this class serves + * primarily to facilitate serialization into protos. + */ +class VerifyMutation extends Mutation { + constructor(key, precondition) { + super(); + this.key = key; + this.precondition = precondition; + this.type = 3 /* MutationType.Verify */; + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const DIRECTIONS = (() => { + const dirs = {}; + dirs["asc" /* Direction.ASCENDING */] = 'ASCENDING'; + dirs["desc" /* Direction.DESCENDING */] = 'DESCENDING'; + return dirs; +})(); +const OPERATORS = (() => { + const ops = {}; + ops["<" /* Operator.LESS_THAN */] = 'LESS_THAN'; + ops["<=" /* Operator.LESS_THAN_OR_EQUAL */] = 'LESS_THAN_OR_EQUAL'; + ops[">" /* Operator.GREATER_THAN */] = 'GREATER_THAN'; + ops[">=" /* Operator.GREATER_THAN_OR_EQUAL */] = 'GREATER_THAN_OR_EQUAL'; + ops["==" /* Operator.EQUAL */] = 'EQUAL'; + ops["!=" /* Operator.NOT_EQUAL */] = 'NOT_EQUAL'; + ops["array-contains" /* Operator.ARRAY_CONTAINS */] = 'ARRAY_CONTAINS'; + ops["in" /* Operator.IN */] = 'IN'; + ops["not-in" /* Operator.NOT_IN */] = 'NOT_IN'; + ops["array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */] = 'ARRAY_CONTAINS_ANY'; + return ops; +})(); +const COMPOSITE_OPERATORS = (() => { + const ops = {}; + ops["and" /* CompositeOperator.AND */] = 'AND'; + ops["or" /* CompositeOperator.OR */] = 'OR'; + return ops; +})(); +function assertPresent(value, description) { +} +/** + * This class generates JsonObject values for the Datastore API suitable for + * sending to either GRPC stub methods or via the JSON/HTTP REST API. + * + * The serializer supports both Protobuf.js and Proto3 JSON formats. By + * setting `useProto3Json` to true, the serializer will use the Proto3 JSON + * format. + * + * For a description of the Proto3 JSON format check + * https://developers.google.com/protocol-buffers/docs/proto3#json + * + * TODO(klimt): We can remove the databaseId argument if we keep the full + * resource name in documents. + */ +class JsonProtoSerializer { + constructor(databaseId, useProto3Json) { + this.databaseId = databaseId; + this.useProto3Json = useProto3Json; + } +} +/** + * Returns a value for a number (or null) that's appropriate to put into + * a google.protobuf.Int32Value proto. + * DO NOT USE THIS FOR ANYTHING ELSE. + * This method cheats. It's typed as returning "number" because that's what + * our generated proto interfaces say Int32Value must be. But GRPC actually + * expects a { value: } struct. + */ +function toInt32Proto(serializer, val) { + if (serializer.useProto3Json || isNullOrUndefined(val)) { + return val; + } + else { + return { value: val }; + } +} +/** + * Returns a value for a Date that's appropriate to put into a proto. + */ +function toTimestamp(serializer, timestamp) { + if (serializer.useProto3Json) { + // Serialize to ISO-8601 date format, but with full nano resolution. + // Since JS Date has only millis, let's only use it for the seconds and + // then manually add the fractions to the end. + const jsDateStr = new Date(timestamp.seconds * 1000).toISOString(); + // Remove .xxx frac part and Z in the end. + const strUntilSeconds = jsDateStr.replace(/\.\d*/, '').replace('Z', ''); + // Pad the fraction out to 9 digits (nanos). + const nanoStr = ('000000000' + timestamp.nanoseconds).slice(-9); + return `${strUntilSeconds}.${nanoStr}Z`; + } + else { + return { + seconds: '' + timestamp.seconds, + nanos: timestamp.nanoseconds + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }; + } +} +/** + * Returns a Timestamp typed object given protobuf timestamp value. + */ +function fromTimestamp(date) { + const timestamp = normalizeTimestamp(date); + return new Timestamp(timestamp.seconds, timestamp.nanos); +} +/** + * Returns a value for bytes that's appropriate to put in a proto. + * + * Visible for testing. + */ +function toBytes(serializer, bytes) { + if (serializer.useProto3Json) { + return bytes.toBase64(); + } + else { + return bytes.toUint8Array(); + } +} +function toVersion(serializer, version) { + return toTimestamp(serializer, version.toTimestamp()); +} +function fromVersion(version) { + hardAssert(!!version, 0xc050); + return SnapshotVersion.fromTimestamp(fromTimestamp(version)); +} +function toResourceName(databaseId, path) { + return toResourcePath(databaseId, path).canonicalString(); +} +function toResourcePath(databaseId, path) { + const resourcePath = fullyQualifiedPrefixPath(databaseId).child('documents'); + return path === undefined ? resourcePath : resourcePath.child(path); +} +function fromResourceName(name) { + const resource = ResourcePath.fromString(name); + hardAssert(isValidResourceName(resource), 0x27ce, { key: resource.toString() }); + return resource; +} +function toName(serializer, key) { + return toResourceName(serializer.databaseId, key.path); +} +function fromName(serializer, name) { + const resource = fromResourceName(name); + if (resource.get(1) !== serializer.databaseId.projectId) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Tried to deserialize key from different project: ' + + resource.get(1) + + ' vs ' + + serializer.databaseId.projectId); + } + if (resource.get(3) !== serializer.databaseId.database) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Tried to deserialize key from different database: ' + + resource.get(3) + + ' vs ' + + serializer.databaseId.database); + } + return new DocumentKey(extractLocalPathFromResourceName(resource)); +} +function toQueryPath(serializer, path) { + return toResourceName(serializer.databaseId, path); +} +function fullyQualifiedPrefixPath(databaseId) { + return new ResourcePath([ + 'projects', + databaseId.projectId, + 'databases', + databaseId.database + ]); +} +function extractLocalPathFromResourceName(resourceName) { + hardAssert(resourceName.length > 4 && resourceName.get(4) === 'documents', 0x71a3, { key: resourceName.toString() }); + return resourceName.popFirst(5); +} +/** Creates a Document proto from key and fields (but no create/update time) */ +function toMutationDocument(serializer, key, fields) { + return { + name: toName(serializer, key), + fields: fields.value.mapValue.fields + }; +} +function fromDocument(serializer, document, hasCommittedMutations) { + const key = fromName(serializer, document.name); + const version = fromVersion(document.updateTime); + // If we read a document from persistence that is missing createTime, it's due + // to older SDK versions not storing this information. In such cases, we'll + // set the createTime to zero. This can be removed in the long term. + const createTime = document.createTime + ? fromVersion(document.createTime) + : SnapshotVersion.min(); + const data = new ObjectValue({ mapValue: { fields: document.fields } }); + const result = MutableDocument.newFoundDocument(key, version, createTime, data); + if (hasCommittedMutations) { + result.setHasCommittedMutations(); + } + return hasCommittedMutations ? result.setHasCommittedMutations() : result; +} +function fromFound(serializer, doc) { + hardAssert(!!doc.found, 0xaa33); + assertPresent(doc.found.name); + assertPresent(doc.found.updateTime); + const key = fromName(serializer, doc.found.name); + const version = fromVersion(doc.found.updateTime); + const createTime = doc.found.createTime + ? fromVersion(doc.found.createTime) + : SnapshotVersion.min(); + const data = new ObjectValue({ mapValue: { fields: doc.found.fields } }); + return MutableDocument.newFoundDocument(key, version, createTime, data); +} +function fromMissing(serializer, result) { + hardAssert(!!result.missing, 0x0f36); + hardAssert(!!result.readTime, 0x5995); + const key = fromName(serializer, result.missing); + const version = fromVersion(result.readTime); + return MutableDocument.newNoDocument(key, version); +} +function fromBatchGetDocumentsResponse(serializer, result) { + if ('found' in result) { + return fromFound(serializer, result); + } + else if ('missing' in result) { + return fromMissing(serializer, result); + } + return fail(0x1c42, { result }); +} +function toMutation(serializer, mutation) { + let result; + if (mutation instanceof SetMutation) { + result = { + update: toMutationDocument(serializer, mutation.key, mutation.value) + }; + } + else if (mutation instanceof DeleteMutation) { + result = { delete: toName(serializer, mutation.key) }; + } + else if (mutation instanceof PatchMutation) { + result = { + update: toMutationDocument(serializer, mutation.key, mutation.data), + updateMask: toDocumentMask(mutation.fieldMask) + }; + } + else if (mutation instanceof VerifyMutation) { + result = { + verify: toName(serializer, mutation.key) + }; + } + else { + return fail(0x40d7, { + mutationType: mutation.type + }); + } + if (mutation.fieldTransforms.length > 0) { + result.updateTransforms = mutation.fieldTransforms.map(transform => toFieldTransform(serializer, transform)); + } + if (!mutation.precondition.isNone) { + result.currentDocument = toPrecondition(serializer, mutation.precondition); + } + return result; +} +function toPrecondition(serializer, precondition) { + if (precondition.updateTime !== undefined) { + return { + updateTime: toVersion(serializer, precondition.updateTime) + }; + } + else if (precondition.exists !== undefined) { + return { exists: precondition.exists }; + } + else { + return fail(0x6b69); + } +} +function toFieldTransform(serializer, fieldTransform) { + const transform = fieldTransform.transform; + if (transform instanceof ServerTimestampTransform) { + return { + fieldPath: fieldTransform.field.canonicalString(), + setToServerValue: 'REQUEST_TIME' + }; + } + else if (transform instanceof ArrayUnionTransformOperation) { + return { + fieldPath: fieldTransform.field.canonicalString(), + appendMissingElements: { + values: transform.elements + } + }; + } + else if (transform instanceof ArrayRemoveTransformOperation) { + return { + fieldPath: fieldTransform.field.canonicalString(), + removeAllFromArray: { + values: transform.elements + } + }; + } + else if (transform instanceof NumericIncrementTransformOperation) { + return { + fieldPath: fieldTransform.field.canonicalString(), + increment: transform.operand + }; + } + else { + throw fail(0x51c2, { + transform: fieldTransform.transform + }); + } +} +function toQueryTarget(serializer, target) { + // Dissect the path into parent, collectionId, and optional key filter. + const queryTarget = { structuredQuery: {} }; + const path = target.path; + let parent; + if (target.collectionGroup !== null) { + parent = path; + queryTarget.structuredQuery.from = [ + { + collectionId: target.collectionGroup, + allDescendants: true + } + ]; + } + else { + parent = path.popLast(); + queryTarget.structuredQuery.from = [{ collectionId: path.lastSegment() }]; + } + queryTarget.parent = toQueryPath(serializer, parent); + const where = toFilters(target.filters); + if (where) { + queryTarget.structuredQuery.where = where; + } + const orderBy = toOrder(target.orderBy); + if (orderBy) { + queryTarget.structuredQuery.orderBy = orderBy; + } + const limit = toInt32Proto(serializer, target.limit); + if (limit !== null) { + queryTarget.structuredQuery.limit = limit; + } + if (target.startAt) { + queryTarget.structuredQuery.startAt = toStartAtCursor(target.startAt); + } + if (target.endAt) { + queryTarget.structuredQuery.endAt = toEndAtCursor(target.endAt); + } + return { queryTarget, parent }; +} +function toRunAggregationQueryRequest(serializer, target, aggregates, skipAliasing) { + const { queryTarget, parent } = toQueryTarget(serializer, target); + const aliasMap = {}; + const aggregations = []; + let aggregationNum = 0; + aggregates.forEach(aggregate => { + // Map all client-side aliases to a unique short-form + // alias. This avoids issues with client-side aliases that + // exceed the 1500-byte string size limit. + const serverAlias = skipAliasing + ? aggregate.alias + : `aggregate_${aggregationNum++}`; + aliasMap[serverAlias] = aggregate.alias; + if (aggregate.aggregateType === 'count') { + aggregations.push({ + alias: serverAlias, + count: {} + }); + } + else if (aggregate.aggregateType === 'avg') { + aggregations.push({ + alias: serverAlias, + avg: { + field: toFieldPathReference(aggregate.fieldPath) + } + }); + } + else if (aggregate.aggregateType === 'sum') { + aggregations.push({ + alias: serverAlias, + sum: { + field: toFieldPathReference(aggregate.fieldPath) + } + }); + } + }); + return { + request: { + structuredAggregationQuery: { + aggregations, + structuredQuery: queryTarget.structuredQuery + }, + parent: queryTarget.parent + }, + aliasMap, + parent + }; +} +function toFilters(filters) { + if (filters.length === 0) { + return; + } + return toFilter(CompositeFilter.create(filters, "and" /* CompositeOperator.AND */)); +} +function toOrder(orderBys) { + if (orderBys.length === 0) { + return; + } + return orderBys.map(order => toPropertyOrder(order)); +} +function toStartAtCursor(cursor) { + return { + before: cursor.inclusive, + values: cursor.position + }; +} +function toEndAtCursor(cursor) { + return { + before: !cursor.inclusive, + values: cursor.position + }; +} +// visible for testing +function toDirection(dir) { + return DIRECTIONS[dir]; +} +// visible for testing +function toOperatorName(op) { + return OPERATORS[op]; +} +function toCompositeOperatorName(op) { + return COMPOSITE_OPERATORS[op]; +} +function toFieldPathReference(path) { + return { fieldPath: path.canonicalString() }; +} +// visible for testing +function toPropertyOrder(orderBy) { + return { + field: toFieldPathReference(orderBy.field), + direction: toDirection(orderBy.dir) + }; +} +// visible for testing +function toFilter(filter) { + if (filter instanceof FieldFilter) { + return toUnaryOrFieldFilter(filter); + } + else if (filter instanceof CompositeFilter) { + return toCompositeFilter(filter); + } + else { + return fail(0xd65d, { filter }); + } +} +function toCompositeFilter(filter) { + const protos = filter.getFilters().map(filter => toFilter(filter)); + if (protos.length === 1) { + return protos[0]; + } + return { + compositeFilter: { + op: toCompositeOperatorName(filter.op), + filters: protos + } + }; +} +function toUnaryOrFieldFilter(filter) { + if (filter.op === "==" /* Operator.EQUAL */) { + if (isNanValue(filter.value)) { + return { + unaryFilter: { + field: toFieldPathReference(filter.field), + op: 'IS_NAN' + } + }; + } + else if (isNullValue(filter.value)) { + return { + unaryFilter: { + field: toFieldPathReference(filter.field), + op: 'IS_NULL' + } + }; + } + } + else if (filter.op === "!=" /* Operator.NOT_EQUAL */) { + if (isNanValue(filter.value)) { + return { + unaryFilter: { + field: toFieldPathReference(filter.field), + op: 'IS_NOT_NAN' + } + }; + } + else if (isNullValue(filter.value)) { + return { + unaryFilter: { + field: toFieldPathReference(filter.field), + op: 'IS_NOT_NULL' + } + }; + } + } + return { + fieldFilter: { + field: toFieldPathReference(filter.field), + op: toOperatorName(filter.op), + value: filter.value + } + }; +} +function toDocumentMask(fieldMask) { + const canonicalFields = []; + fieldMask.fields.forEach(field => canonicalFields.push(field.canonicalString())); + return { + fieldPaths: canonicalFields + }; +} +function isValidResourceName(path) { + // Resource names have at least 4 components (project ID, database ID) + return (path.length >= 4 && + path.get(0) === 'projects' && + path.get(2) === 'databases'); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function newSerializer(databaseId) { + return new JsonProtoSerializer(databaseId, /* useProto3Json= */ true); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$2 = 'ExponentialBackoff'; +/** + * Initial backoff time in milliseconds after an error. + * Set to 1s according to https://cloud.google.com/apis/design/errors. + */ +const DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000; +const DEFAULT_BACKOFF_FACTOR = 1.5; +/** Maximum backoff time in milliseconds */ +const DEFAULT_BACKOFF_MAX_DELAY_MS = 60 * 1000; +/** + * A helper for running delayed tasks following an exponential backoff curve + * between attempts. + * + * Each delay is made up of a "base" delay which follows the exponential + * backoff curve, and a +/- 50% "jitter" that is calculated and added to the + * base delay. This prevents clients from accidentally synchronizing their + * delays causing spikes of load to the backend. + */ +class ExponentialBackoff { + constructor( + /** + * The AsyncQueue to run backoff operations on. + */ + queue, + /** + * The ID to use when scheduling backoff operations on the AsyncQueue. + */ + timerId, + /** + * The initial delay (used as the base delay on the first retry attempt). + * Note that jitter will still be applied, so the actual delay could be as + * little as 0.5*initialDelayMs. + */ + initialDelayMs = DEFAULT_BACKOFF_INITIAL_DELAY_MS, + /** + * The multiplier to use to determine the extended base delay after each + * attempt. + */ + backoffFactor = DEFAULT_BACKOFF_FACTOR, + /** + * The maximum base delay after which no further backoff is performed. + * Note that jitter will still be applied, so the actual delay could be as + * much as 1.5*maxDelayMs. + */ + maxDelayMs = DEFAULT_BACKOFF_MAX_DELAY_MS) { + this.queue = queue; + this.timerId = timerId; + this.initialDelayMs = initialDelayMs; + this.backoffFactor = backoffFactor; + this.maxDelayMs = maxDelayMs; + this.currentBaseMs = 0; + this.timerPromise = null; + /** The last backoff attempt, as epoch milliseconds. */ + this.lastAttemptTime = Date.now(); + this.reset(); + } + /** + * Resets the backoff delay. + * + * The very next backoffAndWait() will have no delay. If it is called again + * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and + * subsequent ones will increase according to the backoffFactor. + */ + reset() { + this.currentBaseMs = 0; + } + /** + * Resets the backoff delay to the maximum delay (e.g. for use after a + * RESOURCE_EXHAUSTED error). + */ + resetToMax() { + this.currentBaseMs = this.maxDelayMs; + } + /** + * Returns a promise that resolves after currentDelayMs, and increases the + * delay for any subsequent attempts. If there was a pending backoff operation + * already, it will be canceled. + */ + backoffAndRun(op) { + // Cancel any pending backoff operation. + this.cancel(); + // First schedule using the current base (which may be 0 and should be + // honored as such). + const desiredDelayWithJitterMs = Math.floor(this.currentBaseMs + this.jitterDelayMs()); + // Guard against lastAttemptTime being in the future due to a clock change. + const delaySoFarMs = Math.max(0, Date.now() - this.lastAttemptTime); + // Guard against the backoff delay already being past. + const remainingDelayMs = Math.max(0, desiredDelayWithJitterMs - delaySoFarMs); + if (remainingDelayMs > 0) { + logDebug(LOG_TAG$2, `Backing off for ${remainingDelayMs} ms ` + + `(base delay: ${this.currentBaseMs} ms, ` + + `delay with jitter: ${desiredDelayWithJitterMs} ms, ` + + `last attempt: ${delaySoFarMs} ms ago)`); + } + this.timerPromise = this.queue.enqueueAfterDelay(this.timerId, remainingDelayMs, () => { + this.lastAttemptTime = Date.now(); + return op(); + }); + // Apply backoff factor to determine next delay and ensure it is within + // bounds. + this.currentBaseMs *= this.backoffFactor; + if (this.currentBaseMs < this.initialDelayMs) { + this.currentBaseMs = this.initialDelayMs; + } + if (this.currentBaseMs > this.maxDelayMs) { + this.currentBaseMs = this.maxDelayMs; + } + } + skipBackoff() { + if (this.timerPromise !== null) { + this.timerPromise.skipDelay(); + this.timerPromise = null; + } + } + cancel() { + if (this.timerPromise !== null) { + this.timerPromise.cancel(); + this.timerPromise = null; + } + } + /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ + jitterDelayMs() { + return (Math.random() - 0.5) * this.currentBaseMs; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Datastore and its related methods are a wrapper around the external Google + * Cloud Datastore grpc API, which provides an interface that is more convenient + * for the rest of the client SDK architecture to consume. + */ +class Datastore { +} +/** + * An implementation of Datastore that exposes additional state for internal + * consumption. + */ +class DatastoreImpl extends Datastore { + constructor(authCredentials, appCheckCredentials, connection, serializer) { + super(); + this.authCredentials = authCredentials; + this.appCheckCredentials = appCheckCredentials; + this.connection = connection; + this.serializer = serializer; + this.terminated = false; + } + verifyInitialized() { + if (this.terminated) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'The client has already been terminated.'); + } + } + /** Invokes the provided RPC with auth and AppCheck tokens. */ + invokeRPC(rpcName, databaseId, resourcePath, request) { + this.verifyInitialized(); + return Promise.all([ + this.authCredentials.getToken(), + this.appCheckCredentials.getToken() + ]) + .then(([authToken, appCheckToken]) => { + return this.connection.invokeRPC(rpcName, toResourcePath(databaseId, resourcePath), request, authToken, appCheckToken); + }) + .catch((error) => { + if (error.name === 'FirebaseError') { + if (error.code === Code.UNAUTHENTICATED) { + this.authCredentials.invalidateToken(); + this.appCheckCredentials.invalidateToken(); + } + throw error; + } + else { + throw new FirestoreError(Code.UNKNOWN, error.toString()); + } + }); + } + /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ + invokeStreamingRPC(rpcName, databaseId, resourcePath, request, expectedResponseCount) { + this.verifyInitialized(); + return Promise.all([ + this.authCredentials.getToken(), + this.appCheckCredentials.getToken() + ]) + .then(([authToken, appCheckToken]) => { + return this.connection.invokeStreamingRPC(rpcName, toResourcePath(databaseId, resourcePath), request, authToken, appCheckToken, expectedResponseCount); + }) + .catch((error) => { + if (error.name === 'FirebaseError') { + if (error.code === Code.UNAUTHENTICATED) { + this.authCredentials.invalidateToken(); + this.appCheckCredentials.invalidateToken(); + } + throw error; + } + else { + throw new FirestoreError(Code.UNKNOWN, error.toString()); + } + }); + } + terminate() { + this.terminated = true; + this.connection.terminate(); + } +} +// TODO(firestorexp): Make sure there is only one Datastore instance per +// firestore-exp client. +function newDatastore(authCredentials, appCheckCredentials, connection, serializer) { + return new DatastoreImpl(authCredentials, appCheckCredentials, connection, serializer); +} +async function invokeCommitRpc(datastore, mutations) { + const datastoreImpl = debugCast(datastore); + const request = { + writes: mutations.map(m => toMutation(datastoreImpl.serializer, m)) + }; + await datastoreImpl.invokeRPC('Commit', datastoreImpl.serializer.databaseId, ResourcePath.emptyPath(), request); +} +async function invokeBatchGetDocumentsRpc(datastore, keys) { + const datastoreImpl = debugCast(datastore); + const request = { + documents: keys.map(k => toName(datastoreImpl.serializer, k)) + }; + const response = await datastoreImpl.invokeStreamingRPC('BatchGetDocuments', datastoreImpl.serializer.databaseId, ResourcePath.emptyPath(), request, keys.length); + const docs = new Map(); + response.forEach(proto => { + const doc = fromBatchGetDocumentsResponse(datastoreImpl.serializer, proto); + docs.set(doc.key.toString(), doc); + }); + const result = []; + keys.forEach(key => { + const doc = docs.get(key.toString()); + hardAssert(!!doc, 0xd7c2, { + key + }); + result.push(doc); + }); + return result; +} +async function invokeRunQueryRpc(datastore, query) { + const datastoreImpl = debugCast(datastore); + const { queryTarget, parent } = toQueryTarget(datastoreImpl.serializer, queryToTarget(query)); + const response = await datastoreImpl.invokeStreamingRPC('RunQuery', datastoreImpl.serializer.databaseId, parent, { + structuredQuery: queryTarget.structuredQuery + }); + return (response + // Omit RunQueryResponses that only contain readTimes. + .filter(proto => !!proto.document) + .map(proto => fromDocument(datastoreImpl.serializer, proto.document, undefined))); +} +async function invokeRunAggregationQueryRpc(datastore, query, aggregates) { + const datastoreImpl = debugCast(datastore); + const { request, aliasMap, parent } = toRunAggregationQueryRequest(datastoreImpl.serializer, queryToAggregateTarget(query), aggregates); + if (!datastoreImpl.connection.shouldResourcePathBeIncludedInRequest) { + delete request.parent; + } + const response = await datastoreImpl.invokeStreamingRPC('RunAggregationQuery', datastoreImpl.serializer.databaseId, parent, request, + /*expectedResponseCount=*/ 1); + // Omit RunAggregationQueryResponse that only contain readTimes. + const filteredResult = response.filter(proto => !!proto.result); + hardAssert(filteredResult.length === 1, 0xfcd7); + // Remap the short-form aliases that were sent to the server + // to the client-side aliases. Users will access the results + // using the client-side alias. + const unmappedAggregateFields = filteredResult[0].result?.aggregateFields; + const remappedFields = Object.keys(unmappedAggregateFields).reduce((accumulator, key) => { + accumulator[aliasMap[key]] = unmappedAggregateFields[key]; + return accumulator; + }, {}); + return remappedFields; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$1 = 'ComponentProvider'; +/** + * An instance map that ensures only one Datastore exists per Firestore + * instance. + */ +const datastoreInstances = new Map(); +/** + * Returns an initialized and started Datastore for the given Firestore + * instance. Callers must invoke removeComponents() when the Firestore + * instance is terminated. + */ +function getDatastore(firestore) { + if (firestore._terminated) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'The client has already been terminated.'); + } + if (!datastoreInstances.has(firestore)) { + logDebug(LOG_TAG$1, 'Initializing Datastore'); + const databaseInfo = makeDatabaseInfo(firestore._databaseId, firestore.app.options.appId || '', firestore._persistenceKey, firestore._freezeSettings()); + const connection = newConnection(databaseInfo); + const serializer = newSerializer(firestore._databaseId); + const datastore = newDatastore(firestore._authCredentials, firestore._appCheckCredentials, connection, serializer); + datastoreInstances.set(firestore, datastore); + } + return datastoreInstances.get(firestore); +} +/** + * Removes all components associated with the provided instance. Must be called + * when the `Firestore` instance is terminated. + */ +function removeComponents(firestore) { + const datastore = datastoreInstances.get(firestore); + if (datastore) { + logDebug(LOG_TAG$1, 'Removing Datastore'); + datastoreInstances.delete(firestore); + datastore.terminate(); + } +} +function makeDatabaseInfo(databaseId, appId, persistenceKey, settings) { + return new DatabaseInfo(databaseId, appId, persistenceKey, settings.host, settings.ssl, settings.experimentalForceLongPolling, settings.experimentalAutoDetectLongPolling, cloneLongPollingOptions(settings.experimentalLongPollingOptions), settings.useFetchStreams, settings.isUsingEmulator); +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LRU_COLLECTION_DISABLED = -1; +const LRU_DEFAULT_CACHE_SIZE_BYTES = 40 * 1024 * 1024; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Verifies whether `e` is an IndexedDbTransactionError. */ +function isIndexedDbTransactionError(e) { + // Use name equality, as instanceof checks on errors don't work with errors + // that wrap other errors. + return e.name === 'IndexedDbTransactionError'; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LRU_MINIMUM_CACHE_SIZE_BYTES = 1 * 1024 * 1024; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// settings() defaults: +const DEFAULT_HOST = 'firestore.googleapis.com'; +const DEFAULT_SSL = true; +// The minimum long-polling timeout is hardcoded on the server. The value here +// should be kept in sync with the value used by the server, as the server will +// silently ignore a value below the minimum and fall back to the default. +// Googlers see b/266868871 for relevant discussion. +const MIN_LONG_POLLING_TIMEOUT_SECONDS = 5; +// No maximum long-polling timeout is configured in the server, and defaults to +// 30 seconds, which is what Watch appears to use. +// Googlers see b/266868871 for relevant discussion. +const MAX_LONG_POLLING_TIMEOUT_SECONDS = 30; +// Whether long-polling auto-detected is enabled by default. +const DEFAULT_AUTO_DETECT_LONG_POLLING = true; +/** + * A concrete type describing all the values that can be applied via a + * user-supplied `FirestoreSettings` object. This is a separate type so that + * defaults can be supplied and the value can be checked for equality. + */ +class FirestoreSettingsImpl { + constructor(settings) { + if (settings.host === undefined) { + if (settings.ssl !== undefined) { + throw new FirestoreError(Code.INVALID_ARGUMENT, "Can't provide ssl option if host option is not set"); + } + this.host = DEFAULT_HOST; + this.ssl = DEFAULT_SSL; + } + else { + this.host = settings.host; + this.ssl = settings.ssl ?? DEFAULT_SSL; + } + this.isUsingEmulator = settings.emulatorOptions !== undefined; + this.credentials = settings.credentials; + this.ignoreUndefinedProperties = !!settings.ignoreUndefinedProperties; + this.localCache = settings.localCache; + if (settings.cacheSizeBytes === undefined) { + this.cacheSizeBytes = LRU_DEFAULT_CACHE_SIZE_BYTES; + } + else { + if (settings.cacheSizeBytes !== LRU_COLLECTION_DISABLED && + settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`); + } + else { + this.cacheSizeBytes = settings.cacheSizeBytes; + } + } + validateIsNotUsedTogether('experimentalForceLongPolling', settings.experimentalForceLongPolling, 'experimentalAutoDetectLongPolling', settings.experimentalAutoDetectLongPolling); + this.experimentalForceLongPolling = !!settings.experimentalForceLongPolling; + if (this.experimentalForceLongPolling) { + this.experimentalAutoDetectLongPolling = false; + } + else if (settings.experimentalAutoDetectLongPolling === undefined) { + this.experimentalAutoDetectLongPolling = DEFAULT_AUTO_DETECT_LONG_POLLING; + } + else { + // For backwards compatibility, coerce the value to boolean even though + // the TypeScript compiler has narrowed the type to boolean already. + // noinspection PointlessBooleanExpressionJS + this.experimentalAutoDetectLongPolling = + !!settings.experimentalAutoDetectLongPolling; + } + this.experimentalLongPollingOptions = cloneLongPollingOptions(settings.experimentalLongPollingOptions ?? {}); + validateLongPollingOptions(this.experimentalLongPollingOptions); + this.useFetchStreams = !!settings.useFetchStreams; + } + isEqual(other) { + return (this.host === other.host && + this.ssl === other.ssl && + this.credentials === other.credentials && + this.cacheSizeBytes === other.cacheSizeBytes && + this.experimentalForceLongPolling === + other.experimentalForceLongPolling && + this.experimentalAutoDetectLongPolling === + other.experimentalAutoDetectLongPolling && + longPollingOptionsEqual(this.experimentalLongPollingOptions, other.experimentalLongPollingOptions) && + this.ignoreUndefinedProperties === other.ignoreUndefinedProperties && + this.useFetchStreams === other.useFetchStreams); + } +} +function validateLongPollingOptions(options) { + if (options.timeoutSeconds !== undefined) { + if (isNaN(options.timeoutSeconds)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `invalid long polling timeout: ` + + `${options.timeoutSeconds} (must not be NaN)`); + } + if (options.timeoutSeconds < MIN_LONG_POLLING_TIMEOUT_SECONDS) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `invalid long polling timeout: ${options.timeoutSeconds} ` + + `(minimum allowed value is ${MIN_LONG_POLLING_TIMEOUT_SECONDS})`); + } + if (options.timeoutSeconds > MAX_LONG_POLLING_TIMEOUT_SECONDS) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `invalid long polling timeout: ${options.timeoutSeconds} ` + + `(maximum allowed value is ${MAX_LONG_POLLING_TIMEOUT_SECONDS})`); + } + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ +class Firestore { + /** @hideconstructor */ + constructor(_authCredentials, _appCheckCredentials, _databaseId, _app) { + this._authCredentials = _authCredentials; + this._appCheckCredentials = _appCheckCredentials; + this._databaseId = _databaseId; + this._app = _app; + /** + * Whether it's a Firestore or Firestore Lite instance. + */ + this.type = 'firestore-lite'; + this._persistenceKey = '(lite)'; + this._settings = new FirestoreSettingsImpl({}); + this._settingsFrozen = false; + this._emulatorOptions = {}; + // A task that is assigned when the terminate() is invoked and resolved when + // all components have shut down. Otherwise, Firestore is not terminated, + // which can mean either the FirestoreClient is in the process of starting, + // or restarting. + this._terminateTask = 'notTerminated'; + } + /** + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service + * instance. + */ + get app() { + if (!this._app) { + throw new FirestoreError(Code.FAILED_PRECONDITION, "Firestore was not initialized using the Firebase SDK. 'app' is " + + 'not available'); + } + return this._app; + } + get _initialized() { + return this._settingsFrozen; + } + get _terminated() { + return this._terminateTask !== 'notTerminated'; + } + _setSettings(settings) { + if (this._settingsFrozen) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore has already been started and its settings can no longer ' + + 'be changed. You can only modify settings before calling any other ' + + 'methods on a Firestore object.'); + } + this._settings = new FirestoreSettingsImpl(settings); + this._emulatorOptions = settings.emulatorOptions || {}; + if (settings.credentials !== undefined) { + this._authCredentials = makeAuthCredentialsProvider(settings.credentials); + } + } + _getSettings() { + return this._settings; + } + _getEmulatorOptions() { + return this._emulatorOptions; + } + _freezeSettings() { + this._settingsFrozen = true; + return this._settings; + } + _delete() { + // The `_terminateTask` must be assigned future that completes when + // terminate is complete. The existence of this future puts SDK in state + // that will not accept further API interaction. + if (this._terminateTask === 'notTerminated') { + this._terminateTask = this._terminate(); + } + return this._terminateTask; + } + async _restart() { + // The `_terminateTask` must equal 'notTerminated' after restart to + // signal that client is in a state that accepts API calls. + if (this._terminateTask === 'notTerminated') { + await this._terminate(); + } + else { + this._terminateTask = 'notTerminated'; + } + } + /** Returns a JSON-serializable representation of this `Firestore` instance. */ + toJSON() { + return { + app: this._app, + databaseId: this._databaseId, + settings: this._settings + }; + } + /** + * Terminates all components used by this client. Subclasses can override + * this method to clean up their own dependencies, but must also call this + * method. + * + * Only ever called once. + */ + _terminate() { + removeComponents(this); + return Promise.resolve(); + } +} +function initializeFirestore(app$1, settings, databaseId) { + if (!databaseId) { + databaseId = DEFAULT_DATABASE_NAME; + } + const provider = app._getProvider(app$1, 'firestore/lite'); + if (provider.isInitialized(databaseId)) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore can only be initialized once per app.'); + } + return provider.initialize({ + options: settings, + instanceIdentifier: databaseId + }); +} +function getFirestore(appOrDatabaseId, optionalDatabaseId) { + const app$1 = typeof appOrDatabaseId === 'object' ? appOrDatabaseId : app.getApp(); + const databaseId = typeof appOrDatabaseId === 'string' + ? appOrDatabaseId + : optionalDatabaseId || '(default)'; + const db = app._getProvider(app$1, 'firestore/lite').getImmediate({ + identifier: databaseId + }); + if (!db._initialized) { + const emulator = util.getDefaultEmulatorHostnameAndPort('firestore'); + if (emulator) { + connectFirestoreEmulator(db, ...emulator); + } + } + return db; +} +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ +function connectFirestoreEmulator(firestore, host, port, options = {}) { + firestore = cast(firestore, Firestore); + const useSsl = util.isCloudWorkstation(host); + const settings = firestore._getSettings(); + const existingConfig = { + ...settings, + emulatorOptions: firestore._getEmulatorOptions() + }; + const newHostSetting = `${host}:${port}`; + if (useSsl) { + void util.pingServer(`https://${newHostSetting}`); + util.updateEmulatorBanner('Firestore', true); + } + if (settings.host !== DEFAULT_HOST && settings.host !== newHostSetting) { + logWarn('Host has been set in both settings() and connectFirestoreEmulator(), emulator host ' + + 'will be used.'); + } + const newConfig = { + ...settings, + host: newHostSetting, + ssl: useSsl, + emulatorOptions: options + }; + // No-op if the new configuration matches the current configuration. This supports SSR + // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice. + if (util.deepEqual(newConfig, existingConfig)) { + return; + } + firestore._setSettings(newConfig); + if (options.mockUserToken) { + let token; + let user; + if (typeof options.mockUserToken === 'string') { + token = options.mockUserToken; + user = User.MOCK_USER; + } + else { + // Let createMockUserToken validate first (catches common mistakes like + // invalid field "uid" and missing field "sub" / "user_id".) + token = util.createMockUserToken(options.mockUserToken, firestore._app?.options.projectId); + const uid = options.mockUserToken.sub || options.mockUserToken.user_id; + if (!uid) { + throw new FirestoreError(Code.INVALID_ARGUMENT, "mockUserToken must contain 'sub' or 'user_id' field!"); + } + user = new User(uid); + } + firestore._authCredentials = new EmulatorAuthCredentialsProvider(new OAuthToken(token, user)); + } +} +/** + * Terminates the provided `Firestore` instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` functions + * may be used. Any other function will throw a `FirestoreError`. Termination + * does not cancel any pending writes, and any promises that are awaiting a + * response from the server will not be resolved. + * + * To restart after termination, create a new instance of `Firestore` with + * {@link (getFirestore:1)}. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all of + * its resources or in combination with {@link clearIndexedDbPersistence} to + * ensure that all local state is destroyed between test runs. + * + * @param firestore - The `Firestore` instance to terminate. + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ +function terminate(firestore) { + firestore = cast(firestore, Firestore); + app._removeServiceInstance(firestore.app, 'firestore/lite'); + return firestore._delete(); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function registerFirestore() { + setSDKVersion(`${app.SDK_VERSION}_lite`); + app._registerComponent(new component.Component('firestore/lite', (container, { instanceIdentifier: databaseId, options: settings }) => { + const app = container.getProvider('app').getImmediate(); + const firestoreInstance = new Firestore(new LiteAuthCredentialsProvider(container.getProvider('auth-internal')), new LiteAppCheckTokenProvider(app, container.getProvider('app-check-internal')), databaseIdFromApp(app, databaseId), app); + if (settings) { + firestoreInstance._setSettings(settings); + } + return firestoreInstance; + }, 'PUBLIC').setMultipleInstances(true)); + // RUNTIME_ENV and BUILD_TARGET are replaced by real values during the compilation + app.registerVersion('firestore-lite', version$1, 'node'); + app.registerVersion('firestore-lite', version$1, 'cjs2020'); +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Concrete implementation of the Aggregate type. + */ +class AggregateImpl { + constructor(alias, aggregateType, fieldPath) { + this.alias = alias; + this.aggregateType = aggregateType; + this.fieldPath = fieldPath; + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents an aggregation that can be performed by Firestore. + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +class AggregateField { + /** + * Create a new AggregateField + * @param aggregateType Specifies the type of aggregation operation to perform. + * @param _internalFieldPath Optionally specifies the field that is aggregated. + * @internal + */ + constructor(aggregateType = 'count', _internalFieldPath) { + this._internalFieldPath = _internalFieldPath; + /** A type string to uniquely identify instances of this class. */ + this.type = 'AggregateField'; + this.aggregateType = aggregateType; + } +} +/** + * The results of executing an aggregation query. + */ +class AggregateQuerySnapshot { + /** @hideconstructor */ + constructor(query, _userDataWriter, _data) { + this._userDataWriter = _userDataWriter; + this._data = _data; + /** A type string to uniquely identify instances of this class. */ + this.type = 'AggregateQuerySnapshot'; + this.query = query; + } + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ + data() { + return this._userDataWriter.convertObjectMap(this._data); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `Query` refers to a query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ +class Query { + // This is the lite version of the Query class in the main SDK. + /** @hideconstructor protected */ + constructor(firestore, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter, _query) { + this.converter = converter; + this._query = _query; + /** The type of this Firestore reference. */ + this.type = 'query'; + this.firestore = firestore; + } + withConverter(converter) { + return new Query(this.firestore, converter, this._query); + } +} +/** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. + */ +class DocumentReference { + /** @hideconstructor */ + constructor(firestore, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter, _key) { + this.converter = converter; + this._key = _key; + /** The type of this Firestore reference. */ + this.type = 'document'; + this.firestore = firestore; + } + get _path() { + return this._key.path; + } + /** + * The document's identifier within its collection. + */ + get id() { + return this._key.path.lastSegment(); + } + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ + get path() { + return this._key.path.canonicalString(); + } + /** + * The collection this `DocumentReference` belongs to. + */ + get parent() { + return new CollectionReference(this.firestore, this.converter, this._key.path.popLast()); + } + withConverter(converter) { + return new DocumentReference(this.firestore, converter, this._key); + } + /** + * Returns a JSON-serializable representation of this `DocumentReference` instance. + * + * @returns a JSON representation of this object. + */ + toJSON() { + return { + type: DocumentReference._jsonSchemaVersion, + referencePath: this._key.toString() + }; + } + static fromJSON(firestore, json, converter) { + if (validateJSON(json, DocumentReference._jsonSchema)) { + return new DocumentReference(firestore, converter ? converter : null, new DocumentKey(ResourcePath.fromString(json.referencePath))); + } + } +} +DocumentReference._jsonSchemaVersion = 'firestore/documentReference/1.0'; +DocumentReference._jsonSchema = { + type: property('string', DocumentReference._jsonSchemaVersion), + referencePath: property('string') +}; +/** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using {@link (query:1)}). + */ +class CollectionReference extends Query { + /** @hideconstructor */ + constructor(firestore, converter, _path) { + super(firestore, converter, newQueryForPath(_path)); + this._path = _path; + /** The type of this Firestore reference. */ + this.type = 'collection'; + } + /** The collection's identifier. */ + get id() { + return this._query.path.lastSegment(); + } + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ + get path() { + return this._query.path.canonicalString(); + } + /** + * A reference to the containing `DocumentReference` if this is a + * subcollection. If this isn't a subcollection, the reference is null. + */ + get parent() { + const parentPath = this._path.popLast(); + if (parentPath.isEmpty()) { + return null; + } + else { + return new DocumentReference(this.firestore, + /* converter= */ null, new DocumentKey(parentPath)); + } + } + withConverter(converter) { + return new CollectionReference(this.firestore, converter, this._path); + } +} +function collection(parent, path, ...pathSegments) { + parent = util.getModularInstance(parent); + validateNonEmptyArgument('collection', 'path', path); + if (parent instanceof Firestore) { + const absolutePath = ResourcePath.fromString(path, ...pathSegments); + validateCollectionPath(absolutePath); + return new CollectionReference(parent, /* converter= */ null, absolutePath); + } + else { + if (!(parent instanceof DocumentReference) && + !(parent instanceof CollectionReference)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Expected first argument to collection() to be a CollectionReference, ' + + 'a DocumentReference or FirebaseFirestore'); + } + const absolutePath = parent._path.child(ResourcePath.fromString(path, ...pathSegments)); + validateCollectionPath(absolutePath); + return new CollectionReference(parent.firestore, + /* converter= */ null, absolutePath); + } +} +// TODO(firestorelite): Consider using ErrorFactory - +// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106 +/** + * Creates and returns a new `Query` instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given `collectionId`. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param collectionId - Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `Query`. + */ +function collectionGroup(firestore, collectionId) { + firestore = cast(firestore, Firestore); + validateNonEmptyArgument('collectionGroup', 'collection id', collectionId); + if (collectionId.indexOf('/') >= 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid collection ID '${collectionId}' passed to function ` + + `collectionGroup(). Collection IDs must not contain '/'.`); + } + return new Query(firestore, + /* converter= */ null, newQueryForCollectionGroup(collectionId)); +} +function doc(parent, path, ...pathSegments) { + parent = util.getModularInstance(parent); + // We allow omission of 'pathString' but explicitly prohibit passing in both + // 'undefined' and 'null'. + if (arguments.length === 1) { + path = AutoId.newId(); + } + validateNonEmptyArgument('doc', 'path', path); + if (parent instanceof Firestore) { + const absolutePath = ResourcePath.fromString(path, ...pathSegments); + validateDocumentPath(absolutePath); + return new DocumentReference(parent, + /* converter= */ null, new DocumentKey(absolutePath)); + } + else { + if (!(parent instanceof DocumentReference) && + !(parent instanceof CollectionReference)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Expected first argument to collection() to be a CollectionReference, ' + + 'a DocumentReference or FirebaseFirestore'); + } + const absolutePath = parent._path.child(ResourcePath.fromString(path, ...pathSegments)); + validateDocumentPath(absolutePath); + return new DocumentReference(parent.firestore, parent instanceof CollectionReference ? parent.converter : null, new DocumentKey(absolutePath)); + } +} +/** + * Returns true if the provided references are equal. + * + * @param left - A reference to compare. + * @param right - A reference to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +function refEqual(left, right) { + left = util.getModularInstance(left); + right = util.getModularInstance(right); + if ((left instanceof DocumentReference || + left instanceof CollectionReference) && + (right instanceof DocumentReference || right instanceof CollectionReference)) { + return (left.firestore === right.firestore && + left.path === right.path && + left.converter === right.converter); + } + return false; +} +/** + * Returns true if the provided queries point to the same collection and apply + * the same constraints. + * + * @param left - A `Query` to compare. + * @param right - A `Query` to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +function queryEqual(left, right) { + left = util.getModularInstance(left); + right = util.getModularInstance(right); + if (left instanceof Query && right instanceof Query) { + return (left.firestore === right.firestore && + queryEquals(left._query, right._query) && + left.converter === right.converter); + } + return false; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing an array of bytes. + */ +class Bytes { + /** @hideconstructor */ + constructor(byteString) { + this._byteString = byteString; + } + /** + * Creates a new `Bytes` object from the given Base64 string, converting it to + * bytes. + * + * @param base64 - The Base64 string used to create the `Bytes` object. + */ + static fromBase64String(base64) { + try { + return new Bytes(ByteString.fromBase64String(base64)); + } + catch (e) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Failed to construct data from Base64 string: ' + e); + } + } + /** + * Creates a new `Bytes` object from the given Uint8Array. + * + * @param array - The Uint8Array used to create the `Bytes` object. + */ + static fromUint8Array(array) { + return new Bytes(ByteString.fromUint8Array(array)); + } + /** + * Returns the underlying bytes as a Base64-encoded string. + * + * @returns The Base64-encoded string created from the `Bytes` object. + */ + toBase64() { + return this._byteString.toBase64(); + } + /** + * Returns the underlying bytes in a new `Uint8Array`. + * + * @returns The Uint8Array created from the `Bytes` object. + */ + toUint8Array() { + return this._byteString.toUint8Array(); + } + /** + * Returns a string representation of the `Bytes` object. + * + * @returns A string representation of the `Bytes` object. + */ + toString() { + return 'Bytes(base64: ' + this.toBase64() + ')'; + } + /** + * Returns true if this `Bytes` object is equal to the provided one. + * + * @param other - The `Bytes` object to compare against. + * @returns true if this `Bytes` object is equal to the provided one. + */ + isEqual(other) { + return this._byteString.isEqual(other._byteString); + } + /** + * Returns a JSON-serializable representation of this `Bytes` instance. + * + * @returns a JSON representation of this object. + */ + toJSON() { + return { + type: Bytes._jsonSchemaVersion, + bytes: this.toBase64() + }; + } + /** + * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}. + * + * @param json a JSON object represention of a `Bytes` instance + * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json) { + if (validateJSON(json, Bytes._jsonSchema)) { + return Bytes.fromBase64String(json.bytes); + } + } +} +Bytes._jsonSchemaVersion = 'firestore/bytes/1.0'; +Bytes._jsonSchema = { + type: property('string', Bytes._jsonSchemaVersion), + bytes: property('string') +}; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `FieldPath` refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + * + * Create a `FieldPath` by providing field names. If more than one field + * name is provided, the path will point to a nested field in a document. + */ +class FieldPath { + /** + * Creates a `FieldPath` from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames - A list of field names. + */ + constructor(...fieldNames) { + for (let i = 0; i < fieldNames.length; ++i) { + if (fieldNames[i].length === 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid field name at argument $(i + 1). ` + + 'Field names must not be empty.'); + } + } + this._internalPath = new FieldPath$1(fieldNames); + } + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other - The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ + isEqual(other) { + return this._internalPath.isEqual(other._internalPath); + } +} +/** + * Returns a special sentinel `FieldPath` to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ +function documentId() { + return new FieldPath(DOCUMENT_KEY_NAME); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Sentinel values that can be used when writing document fields with `set()` + * or `update()`. + */ +class FieldValue { + /** + * @param _methodName - The public API endpoint that returns this class. + * @hideconstructor + */ + constructor(_methodName) { + this._methodName = _methodName; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ +class GeoPoint { + /** + * Creates a new immutable `GeoPoint` object with the provided latitude and + * longitude values. + * @param latitude - The latitude as number between -90 and 90. + * @param longitude - The longitude as number between -180 and 180. + */ + constructor(latitude, longitude) { + if (!isFinite(latitude) || latitude < -90 || latitude > 90) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Latitude must be a number between -90 and 90, but was: ' + latitude); + } + if (!isFinite(longitude) || longitude < -180 || longitude > 180) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Longitude must be a number between -180 and 180, but was: ' + longitude); + } + this._lat = latitude; + this._long = longitude; + } + /** + * The latitude of this `GeoPoint` instance. + */ + get latitude() { + return this._lat; + } + /** + * The longitude of this `GeoPoint` instance. + */ + get longitude() { + return this._long; + } + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other - The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ + isEqual(other) { + return this._lat === other._lat && this._long === other._long; + } + /** + * Actually private to JS consumers of our API, so this function is prefixed + * with an underscore. + */ + _compareTo(other) { + return (primitiveComparator(this._lat, other._lat) || + primitiveComparator(this._long, other._long)); + } + /** + * Returns a JSON-serializable representation of this `GeoPoint` instance. + * + * @returns a JSON representation of this object. + */ + toJSON() { + return { + latitude: this._lat, + longitude: this._long, + type: GeoPoint._jsonSchemaVersion + }; + } + /** + * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}. + * + * @param json a JSON object represention of a `GeoPoint` instance + * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json) { + if (validateJSON(json, GeoPoint._jsonSchema)) { + return new GeoPoint(json.latitude, json.longitude); + } + } +} +GeoPoint._jsonSchemaVersion = 'firestore/geoPoint/1.0'; +GeoPoint._jsonSchema = { + type: property('string', GeoPoint._jsonSchemaVersion), + latitude: property('number'), + longitude: property('number') +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Verifies equality for an array of primitives. + * + * @private + * @internal + * @param left Array of primitives. + * @param right Array of primitives. + * @return True if arrays are equal. + */ +function isPrimitiveArrayEqual(left, right) { + if (left.length !== right.length) { + return false; + } + for (let i = 0; i < left.length; ++i) { + if (left[i] !== right[i]) { + return false; + } + } + return true; +} + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link vector}. + * + * @class VectorValue + */ +class VectorValue { + /** + * @private + * @internal + */ + constructor(values) { + // Making a copy of the parameter. + this._values = (values || []).map(n => n); + } + /** + * Returns a copy of the raw number array form of the vector. + */ + toArray() { + return this._values.map(n => n); + } + /** + * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise. + */ + isEqual(other) { + return isPrimitiveArrayEqual(this._values, other._values); + } + /** + * Returns a JSON-serializable representation of this `VectorValue` instance. + * + * @returns a JSON representation of this object. + */ + toJSON() { + return { + type: VectorValue._jsonSchemaVersion, + vectorValues: this._values + }; + } + /** + * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}. + * + * @param json a JSON object represention of a `VectorValue` instance. + * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json) { + if (validateJSON(json, VectorValue._jsonSchema)) { + if (Array.isArray(json.vectorValues) && + json.vectorValues.every(element => typeof element === 'number')) { + return new VectorValue(json.vectorValues); + } + throw new FirestoreError(Code.INVALID_ARGUMENT, "Expected 'vectorValues' field to be a number array"); + } + } +} +VectorValue._jsonSchemaVersion = 'firestore/vectorValue/1.0'; +VectorValue._jsonSchema = { + type: property('string', VectorValue._jsonSchemaVersion), + vectorValues: property('object') +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const RESERVED_FIELD_REGEX = /^__.*__$/; +/** The result of parsing document data (e.g. for a setData call). */ +class ParsedSetData { + constructor(data, fieldMask, fieldTransforms) { + this.data = data; + this.fieldMask = fieldMask; + this.fieldTransforms = fieldTransforms; + } + toMutation(key, precondition) { + if (this.fieldMask !== null) { + return new PatchMutation(key, this.data, this.fieldMask, precondition, this.fieldTransforms); + } + else { + return new SetMutation(key, this.data, precondition, this.fieldTransforms); + } + } +} +/** The result of parsing "update" data (i.e. for an updateData call). */ +class ParsedUpdateData { + constructor(data, + // The fieldMask does not include document transforms. + fieldMask, fieldTransforms) { + this.data = data; + this.fieldMask = fieldMask; + this.fieldTransforms = fieldTransforms; + } + toMutation(key, precondition) { + return new PatchMutation(key, this.data, this.fieldMask, precondition, this.fieldTransforms); + } +} +function isWrite(dataSource) { + switch (dataSource) { + case 0 /* UserDataSource.Set */: // fall through + case 2 /* UserDataSource.MergeSet */: // fall through + case 1 /* UserDataSource.Update */: + return true; + case 3 /* UserDataSource.Argument */: + case 4 /* UserDataSource.ArrayArgument */: + return false; + default: + throw fail(0x9c4b, { + dataSource + }); + } +} +/** A "context" object passed around while parsing user data. */ +class ParseContextImpl { + /** + * Initializes a ParseContext with the given source and path. + * + * @param settings - The settings for the parser. + * @param databaseId - The database ID of the Firestore instance. + * @param serializer - The serializer to use to generate the Value proto. + * @param ignoreUndefinedProperties - Whether to ignore undefined properties + * rather than throw. + * @param fieldTransforms - A mutable list of field transforms encountered + * while parsing the data. + * @param fieldMask - A mutable list of field paths encountered while parsing + * the data. + * + * TODO(b/34871131): We don't support array paths right now, so path can be + * null to indicate the context represents any location within an array (in + * which case certain features will not work and errors will be somewhat + * compromised). + */ + constructor(settings, databaseId, serializer, ignoreUndefinedProperties, fieldTransforms, fieldMask) { + this.settings = settings; + this.databaseId = databaseId; + this.serializer = serializer; + this.ignoreUndefinedProperties = ignoreUndefinedProperties; + // Minor hack: If fieldTransforms is undefined, we assume this is an + // external call and we need to validate the entire path. + if (fieldTransforms === undefined) { + this.validatePath(); + } + this.fieldTransforms = fieldTransforms || []; + this.fieldMask = fieldMask || []; + } + get path() { + return this.settings.path; + } + get dataSource() { + return this.settings.dataSource; + } + /** Returns a new context with the specified settings overwritten. */ + contextWith(configuration) { + return new ParseContextImpl({ ...this.settings, ...configuration }, this.databaseId, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask); + } + childContextForField(field) { + const childPath = this.path?.child(field); + const context = this.contextWith({ path: childPath, arrayElement: false }); + context.validatePathSegment(field); + return context; + } + childContextForFieldPath(field) { + const childPath = this.path?.child(field); + const context = this.contextWith({ path: childPath, arrayElement: false }); + context.validatePath(); + return context; + } + childContextForArray(index) { + // TODO(b/34871131): We don't support array paths right now; so make path + // undefined. + return this.contextWith({ path: undefined, arrayElement: true }); + } + createError(reason) { + return createError(reason, this.settings.methodName, this.settings.hasConverter || false, this.path, this.settings.targetDoc); + } + /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ + contains(fieldPath) { + return (this.fieldMask.find(field => fieldPath.isPrefixOf(field)) !== undefined || + this.fieldTransforms.find(transform => fieldPath.isPrefixOf(transform.field)) !== undefined); + } + validatePath() { + // TODO(b/34871131): Remove null check once we have proper paths for fields + // within arrays. + if (!this.path) { + return; + } + for (let i = 0; i < this.path.length; i++) { + this.validatePathSegment(this.path.get(i)); + } + } + validatePathSegment(segment) { + if (segment.length === 0) { + throw this.createError('Document fields must not be empty'); + } + if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) { + throw this.createError('Document fields cannot begin and end with "__"'); + } + } +} +/** + * Helper for parsing raw user input (provided via the API) into internal model + * classes. + */ +class UserDataReader { + constructor(databaseId, ignoreUndefinedProperties, serializer) { + this.databaseId = databaseId; + this.ignoreUndefinedProperties = ignoreUndefinedProperties; + this.serializer = serializer || newSerializer(databaseId); + } + /** Creates a new top-level parse context. */ + createContext(dataSource, methodName, targetDoc, hasConverter = false) { + return new ParseContextImpl({ + dataSource, + methodName, + targetDoc, + path: FieldPath$1.emptyPath(), + arrayElement: false, + hasConverter + }, this.databaseId, this.serializer, this.ignoreUndefinedProperties); + } +} +function newUserDataReader(firestore) { + const settings = firestore._freezeSettings(); + const serializer = newSerializer(firestore._databaseId); + return new UserDataReader(firestore._databaseId, !!settings.ignoreUndefinedProperties, serializer); +} +/** Parse document data from a set() call. */ +function parseSetData(userDataReader, methodName, targetDoc, input, hasConverter, options = {}) { + const context = userDataReader.createContext(options.merge || options.mergeFields + ? 2 /* UserDataSource.MergeSet */ + : 0 /* UserDataSource.Set */, methodName, targetDoc, hasConverter); + validatePlainObject('Data must be an object, but it was:', context, input); + const updateData = parseObject(input, context); + let fieldMask; + let fieldTransforms; + if (options.merge) { + fieldMask = new FieldMask(context.fieldMask); + fieldTransforms = context.fieldTransforms; + } + else if (options.mergeFields) { + const validatedFieldPaths = []; + for (const stringOrFieldPath of options.mergeFields) { + const fieldPath = fieldPathFromArgument$1(methodName, stringOrFieldPath, targetDoc); + if (!context.contains(fieldPath)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Field '${fieldPath}' is specified in your field mask but missing from your input data.`); + } + if (!fieldMaskContains(validatedFieldPaths, fieldPath)) { + validatedFieldPaths.push(fieldPath); + } + } + fieldMask = new FieldMask(validatedFieldPaths); + fieldTransforms = context.fieldTransforms.filter(transform => fieldMask.covers(transform.field)); + } + else { + fieldMask = null; + fieldTransforms = context.fieldTransforms; + } + return new ParsedSetData(new ObjectValue(updateData), fieldMask, fieldTransforms); +} +class DeleteFieldValueImpl extends FieldValue { + _toFieldTransform(context) { + if (context.dataSource === 2 /* UserDataSource.MergeSet */) { + // No transform to add for a delete, but we need to add it to our + // fieldMask so it gets deleted. + context.fieldMask.push(context.path); + } + else if (context.dataSource === 1 /* UserDataSource.Update */) { + throw context.createError(`${this._methodName}() can only appear at the top level ` + + 'of your update data'); + } + else { + // We shouldn't encounter delete sentinels for queries or non-merge set() calls. + throw context.createError(`${this._methodName}() cannot be used with set() unless you pass ` + + '{merge:true}'); + } + return null; + } + isEqual(other) { + return other instanceof DeleteFieldValueImpl; + } +} +/** + * Creates a child context for parsing SerializableFieldValues. + * + * This is different than calling `ParseContext.contextWith` because it keeps + * the fieldTransforms and fieldMask separate. + * + * The created context has its `dataSource` set to `UserDataSource.Argument`. + * Although these values are used with writes, any elements in these FieldValues + * are not considered writes since they cannot contain any FieldValue sentinels, + * etc. + * + * @param fieldValue - The sentinel FieldValue for which to create a child + * context. + * @param context - The parent context. + * @param arrayElement - Whether or not the FieldValue has an array. + */ +function createSentinelChildContext(fieldValue, context, arrayElement) { + return new ParseContextImpl({ + dataSource: 3 /* UserDataSource.Argument */, + targetDoc: context.settings.targetDoc, + methodName: fieldValue._methodName, + arrayElement + }, context.databaseId, context.serializer, context.ignoreUndefinedProperties); +} +class ServerTimestampFieldValueImpl extends FieldValue { + _toFieldTransform(context) { + return new FieldTransform(context.path, new ServerTimestampTransform()); + } + isEqual(other) { + return other instanceof ServerTimestampFieldValueImpl; + } +} +class ArrayUnionFieldValueImpl extends FieldValue { + constructor(methodName, _elements) { + super(methodName); + this._elements = _elements; + } + _toFieldTransform(context) { + const parseContext = createSentinelChildContext(this, context, + /*array=*/ true); + const parsedElements = this._elements.map(element => parseData(element, parseContext)); + const arrayUnion = new ArrayUnionTransformOperation(parsedElements); + return new FieldTransform(context.path, arrayUnion); + } + isEqual(other) { + return (other instanceof ArrayUnionFieldValueImpl && + util.deepEqual(this._elements, other._elements)); + } +} +class ArrayRemoveFieldValueImpl extends FieldValue { + constructor(methodName, _elements) { + super(methodName); + this._elements = _elements; + } + _toFieldTransform(context) { + const parseContext = createSentinelChildContext(this, context, + /*array=*/ true); + const parsedElements = this._elements.map(element => parseData(element, parseContext)); + const arrayUnion = new ArrayRemoveTransformOperation(parsedElements); + return new FieldTransform(context.path, arrayUnion); + } + isEqual(other) { + return (other instanceof ArrayRemoveFieldValueImpl && + util.deepEqual(this._elements, other._elements)); + } +} +class NumericIncrementFieldValueImpl extends FieldValue { + constructor(methodName, _operand) { + super(methodName); + this._operand = _operand; + } + _toFieldTransform(context) { + const numericIncrement = new NumericIncrementTransformOperation(context.serializer, toNumber(context.serializer, this._operand)); + return new FieldTransform(context.path, numericIncrement); + } + isEqual(other) { + return (other instanceof NumericIncrementFieldValueImpl && + this._operand === other._operand); + } +} +/** Parse update data from an update() call. */ +function parseUpdateData(userDataReader, methodName, targetDoc, input) { + const context = userDataReader.createContext(1 /* UserDataSource.Update */, methodName, targetDoc); + validatePlainObject('Data must be an object, but it was:', context, input); + const fieldMaskPaths = []; + const updateData = ObjectValue.empty(); + forEach(input, (key, value) => { + const path = fieldPathFromDotSeparatedString(methodName, key, targetDoc); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + value = util.getModularInstance(value); + const childContext = context.childContextForFieldPath(path); + if (value instanceof DeleteFieldValueImpl) { + // Add it to the field mask, but don't add anything to updateData. + fieldMaskPaths.push(path); + } + else { + const parsedValue = parseData(value, childContext); + if (parsedValue != null) { + fieldMaskPaths.push(path); + updateData.set(path, parsedValue); + } + } + }); + const mask = new FieldMask(fieldMaskPaths); + return new ParsedUpdateData(updateData, mask, context.fieldTransforms); +} +/** Parse update data from a list of field/value arguments. */ +function parseUpdateVarargs(userDataReader, methodName, targetDoc, field, value, moreFieldsAndValues) { + const context = userDataReader.createContext(1 /* UserDataSource.Update */, methodName, targetDoc); + const keys = [fieldPathFromArgument$1(methodName, field, targetDoc)]; + const values = [value]; + if (moreFieldsAndValues.length % 2 !== 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${methodName}() needs to be called with an even number ` + + 'of arguments that alternate between field names and values.'); + } + for (let i = 0; i < moreFieldsAndValues.length; i += 2) { + keys.push(fieldPathFromArgument$1(methodName, moreFieldsAndValues[i])); + values.push(moreFieldsAndValues[i + 1]); + } + const fieldMaskPaths = []; + const updateData = ObjectValue.empty(); + // We iterate in reverse order to pick the last value for a field if the + // user specified the field multiple times. + for (let i = keys.length - 1; i >= 0; --i) { + if (!fieldMaskContains(fieldMaskPaths, keys[i])) { + const path = keys[i]; + let value = values[i]; + // For Compat types, we have to "extract" the underlying types before + // performing validation. + value = util.getModularInstance(value); + const childContext = context.childContextForFieldPath(path); + if (value instanceof DeleteFieldValueImpl) { + // Add it to the field mask, but don't add anything to updateData. + fieldMaskPaths.push(path); + } + else { + const parsedValue = parseData(value, childContext); + if (parsedValue != null) { + fieldMaskPaths.push(path); + updateData.set(path, parsedValue); + } + } + } + } + const mask = new FieldMask(fieldMaskPaths); + return new ParsedUpdateData(updateData, mask, context.fieldTransforms); +} +/** + * Parse a "query value" (e.g. value in a where filter or a value in a cursor + * bound). + * + * @param allowArrays - Whether the query value is an array that may directly + * contain additional arrays (e.g. the operand of an `in` query). + */ +function parseQueryValue(userDataReader, methodName, input, allowArrays = false) { + const context = userDataReader.createContext(allowArrays ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */, methodName); + const parsed = parseData(input, context); + return parsed; +} +/** + * Parses user data to Protobuf Values. + * + * @param input - Data to be parsed. + * @param context - A context object representing the current path being parsed, + * the source of the data being parsed, etc. + * @returns The parsed value, or null if the value was a FieldValue sentinel + * that should not be included in the resulting parsed data. + */ +function parseData(input, context) { + // Unwrap the API type from the Compat SDK. This will return the API type + // from firestore-exp. + input = util.getModularInstance(input); + if (looksLikeJsonObject(input)) { + validatePlainObject('Unsupported field value:', context, input); + return parseObject(input, context); + } + else if (input instanceof FieldValue) { + // FieldValues usually parse into transforms (except deleteField()) + // in which case we do not want to include this field in our parsed data + // (as doing so will overwrite the field directly prior to the transform + // trying to transform it). So we don't add this location to + // context.fieldMask and we return null as our parsing result. + parseSentinelFieldValue(input, context); + return null; + } + else if (input === undefined && context.ignoreUndefinedProperties) { + // If the input is undefined it can never participate in the fieldMask, so + // don't handle this below. If `ignoreUndefinedProperties` is false, + // `parseScalarValue` will reject an undefined value. + return null; + } + else { + // If context.path is null we are inside an array and we don't support + // field mask paths more granular than the top-level array. + if (context.path) { + context.fieldMask.push(context.path); + } + if (input instanceof Array) { + // TODO(b/34871131): Include the path containing the array in the error + // message. + // In the case of IN queries, the parsed data is an array (representing + // the set of values to be included for the IN query) that may directly + // contain additional arrays (each representing an individual field + // value), so we disable this validation. + if (context.settings.arrayElement && + context.dataSource !== 4 /* UserDataSource.ArrayArgument */) { + throw context.createError('Nested arrays are not supported'); + } + return parseArray(input, context); + } + else { + return parseScalarValue(input, context); + } + } +} +function parseObject(obj, context) { + const fields = {}; + if (isEmpty(obj)) { + // If we encounter an empty object, we explicitly add it to the update + // mask to ensure that the server creates a map entry. + if (context.path && context.path.length > 0) { + context.fieldMask.push(context.path); + } + } + else { + forEach(obj, (key, val) => { + const parsedValue = parseData(val, context.childContextForField(key)); + if (parsedValue != null) { + fields[key] = parsedValue; + } + }); + } + return { mapValue: { fields } }; +} +function parseArray(array, context) { + const values = []; + let entryIndex = 0; + for (const entry of array) { + let parsedEntry = parseData(entry, context.childContextForArray(entryIndex)); + if (parsedEntry == null) { + // Just include nulls in the array for fields being replaced with a + // sentinel. + parsedEntry = { nullValue: 'NULL_VALUE' }; + } + values.push(parsedEntry); + entryIndex++; + } + return { arrayValue: { values } }; +} +/** + * "Parses" the provided FieldValueImpl, adding any necessary transforms to + * context.fieldTransforms. + */ +function parseSentinelFieldValue(value, context) { + // Sentinels are only supported with writes, and not within arrays. + if (!isWrite(context.dataSource)) { + throw context.createError(`${value._methodName}() can only be used with update() and set()`); + } + if (!context.path) { + throw context.createError(`${value._methodName}() is not currently supported inside arrays`); + } + const fieldTransform = value._toFieldTransform(context); + if (fieldTransform) { + context.fieldTransforms.push(fieldTransform); + } +} +/** + * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue) + * + * @returns The parsed value + */ +function parseScalarValue(value, context) { + value = util.getModularInstance(value); + if (value === null) { + return { nullValue: 'NULL_VALUE' }; + } + else if (typeof value === 'number') { + return toNumber(context.serializer, value); + } + else if (typeof value === 'boolean') { + return { booleanValue: value }; + } + else if (typeof value === 'string') { + return { stringValue: value }; + } + else if (value instanceof Date) { + const timestamp = Timestamp.fromDate(value); + return { + timestampValue: toTimestamp(context.serializer, timestamp) + }; + } + else if (value instanceof Timestamp) { + // Firestore backend truncates precision down to microseconds. To ensure + // offline mode works the same with regards to truncation, perform the + // truncation immediately without waiting for the backend to do that. + const timestamp = new Timestamp(value.seconds, Math.floor(value.nanoseconds / 1000) * 1000); + return { + timestampValue: toTimestamp(context.serializer, timestamp) + }; + } + else if (value instanceof GeoPoint) { + return { + geoPointValue: { + latitude: value.latitude, + longitude: value.longitude + } + }; + } + else if (value instanceof Bytes) { + return { bytesValue: toBytes(context.serializer, value._byteString) }; + } + else if (value instanceof DocumentReference) { + const thisDb = context.databaseId; + const otherDb = value.firestore._databaseId; + if (!otherDb.isEqual(thisDb)) { + throw context.createError('Document reference is for database ' + + `${otherDb.projectId}/${otherDb.database} but should be ` + + `for database ${thisDb.projectId}/${thisDb.database}`); + } + return { + referenceValue: toResourceName(value.firestore._databaseId || context.databaseId, value._key.path) + }; + } + else if (value instanceof VectorValue) { + return parseVectorValue(value, context); + } + else { + throw context.createError(`Unsupported field value: ${valueDescription(value)}`); + } +} +/** + * Creates a new VectorValue proto value (using the internal format). + */ +function parseVectorValue(value, context) { + const mapValue = { + fields: { + [TYPE_KEY]: { + stringValue: VECTOR_VALUE_SENTINEL + }, + [VECTOR_MAP_VECTORS_KEY]: { + arrayValue: { + values: value.toArray().map(value => { + if (typeof value !== 'number') { + throw context.createError('VectorValues must only contain numeric values.'); + } + return toDouble(context.serializer, value); + }) + } + } + } + }; + return { mapValue }; +} +/** + * Checks whether an object looks like a JSON object that should be converted + * into a struct. Normal class/prototype instances are considered to look like + * JSON objects since they should be converted to a struct value. Arrays, Dates, + * GeoPoints, etc. are not considered to look like JSON objects since they map + * to specific FieldValue types other than ObjectValue. + */ +function looksLikeJsonObject(input) { + return (typeof input === 'object' && + input !== null && + !(input instanceof Array) && + !(input instanceof Date) && + !(input instanceof Timestamp) && + !(input instanceof GeoPoint) && + !(input instanceof Bytes) && + !(input instanceof DocumentReference) && + !(input instanceof FieldValue) && + !(input instanceof VectorValue)); +} +function validatePlainObject(message, context, input) { + if (!looksLikeJsonObject(input) || !isPlainObject(input)) { + const description = valueDescription(input); + if (description === 'an object') { + // Massage the error if it was an object. + throw context.createError(message + ' a custom object'); + } + else { + throw context.createError(message + ' ' + description); + } + } +} +/** + * Helper that calls fromDotSeparatedString() but wraps any error thrown. + */ +function fieldPathFromArgument$1(methodName, path, targetDoc) { + // If required, replace the FieldPath Compat class with the firestore-exp + // FieldPath. + path = util.getModularInstance(path); + if (path instanceof FieldPath) { + return path._internalPath; + } + else if (typeof path === 'string') { + return fieldPathFromDotSeparatedString(methodName, path); + } + else { + const message = 'Field path arguments must be of type string or '; + throw createError(message, methodName, + /* hasConverter= */ false, + /* path= */ undefined, targetDoc); + } +} +/** + * Matches any characters in a field path string that are reserved. + */ +const FIELD_PATH_RESERVED = new RegExp('[~\\*/\\[\\]]'); +/** + * Wraps fromDotSeparatedString with an error message about the method that + * was thrown. + * @param methodName - The publicly visible method name + * @param path - The dot-separated string form of a field path which will be + * split on dots. + * @param targetDoc - The document against which the field path will be + * evaluated. + */ +function fieldPathFromDotSeparatedString(methodName, path, targetDoc) { + const found = path.search(FIELD_PATH_RESERVED); + if (found >= 0) { + throw createError(`Invalid field path (${path}). Paths must not contain ` + + `'~', '*', '/', '[', or ']'`, methodName, + /* hasConverter= */ false, + /* path= */ undefined, targetDoc); + } + try { + return new FieldPath(...path.split('.'))._internalPath; + } + catch (e) { + throw createError(`Invalid field path (${path}). Paths must not be empty, ` + + `begin with '.', end with '.', or contain '..'`, methodName, + /* hasConverter= */ false, + /* path= */ undefined, targetDoc); + } +} +function createError(reason, methodName, hasConverter, path, targetDoc) { + const hasPath = path && !path.isEmpty(); + const hasDocument = targetDoc !== undefined; + let message = `Function ${methodName}() called with invalid data`; + if (hasConverter) { + message += ' (via `toFirestore()`)'; + } + message += '. '; + let description = ''; + if (hasPath || hasDocument) { + description += ' (found'; + if (hasPath) { + description += ` in field ${path}`; + } + if (hasDocument) { + description += ` in document ${targetDoc}`; + } + description += ')'; + } + return new FirestoreError(Code.INVALID_ARGUMENT, message + reason + description); +} +/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ +function fieldMaskContains(haystack, needle) { + return haystack.some(v => v.isEqual(needle)); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ +class DocumentSnapshot { + // Note: This class is stripped down version of the DocumentSnapshot in + // the legacy SDK. The changes are: + // - No support for SnapshotMetadata. + // - No support for SnapshotOptions. + /** @hideconstructor protected */ + constructor(_firestore, _userDataWriter, _key, _document, _converter) { + this._firestore = _firestore; + this._userDataWriter = _userDataWriter; + this._key = _key; + this._document = _document; + this._converter = _converter; + } + /** Property of the `DocumentSnapshot` that provides the document's ID. */ + get id() { + return this._key.path.lastSegment(); + } + /** + * The `DocumentReference` for the document included in the `DocumentSnapshot`. + */ + get ref() { + return new DocumentReference(this._firestore, this._converter, this._key); + } + /** + * Signals whether or not the document at the snapshot's location exists. + * + * @returns true if the document exists. + */ + exists() { + return this._document !== null; + } + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * @returns An `Object` containing all fields in the document or `undefined` + * if the document doesn't exist. + */ + data() { + if (!this._document) { + return undefined; + } + else if (this._converter) { + // We only want to use the converter and create a new DocumentSnapshot + // if a converter has been provided. + const snapshot = new QueryDocumentSnapshot(this._firestore, this._userDataWriter, this._key, this._document, + /* converter= */ null); + return this._converter.fromFirestore(snapshot); + } + else { + return this._userDataWriter.convertValue(this._document.data.value); + } + } + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + // We are using `any` here to avoid an explicit cast by our users. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get(fieldPath) { + if (this._document) { + const value = this._document.data.field(fieldPathFromArgument('DocumentSnapshot.get', fieldPath)); + if (value !== null) { + return this._userDataWriter.convertValue(value); + } + } + return undefined; + } +} +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ +class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * @override + * @returns An `Object` containing all fields in the document. + */ + data() { + return super.data(); + } +} +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ +class QuerySnapshot { + /** @hideconstructor */ + constructor(_query, _docs) { + this._docs = _docs; + this.query = _query; + } + /** An array of all the documents in the `QuerySnapshot`. */ + get docs() { + return [...this._docs]; + } + /** The number of documents in the `QuerySnapshot`. */ + get size() { + return this.docs.length; + } + /** True if there are no documents in the `QuerySnapshot`. */ + get empty() { + return this.docs.length === 0; + } + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ + forEach(callback, thisArg) { + this._docs.forEach(callback, thisArg); + } +} +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ +function snapshotEqual(left, right) { + left = util.getModularInstance(left); + right = util.getModularInstance(right); + if (left instanceof DocumentSnapshot && right instanceof DocumentSnapshot) { + return (left._firestore === right._firestore && + left._key.isEqual(right._key) && + (left._document === null + ? right._document === null + : left._document.isEqual(right._document)) && + left._converter === right._converter); + } + else if (left instanceof QuerySnapshot && right instanceof QuerySnapshot) { + return (queryEqual(left.query, right.query) && + arrayEquals(left.docs, right.docs, snapshotEqual)); + } + return false; +} +/** + * Helper that calls `fromDotSeparatedString()` but wraps any error thrown. + */ +function fieldPathFromArgument(methodName, arg) { + if (typeof arg === 'string') { + return fieldPathFromDotSeparatedString(methodName, arg); + } + else if (arg instanceof FieldPath) { + return arg._internalPath; + } + else { + return arg._delegate._internalPath; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function validateHasExplicitOrderByForLimitToLast(query) { + if (query.limitType === "L" /* LimitType.Last */ && + query.explicitOrderBy.length === 0) { + throw new FirestoreError(Code.UNIMPLEMENTED, 'limitToLast() queries require specifying at least one orderBy() clause'); + } +} +/** + * An `AppliableConstraint` is an abstraction of a constraint that can be applied + * to a Firestore query. + */ +class AppliableConstraint { +} +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Firestore query. `QueryConstraint`s are created by invoking {@link where}, + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that + * also contains this `QueryConstraint`. + */ +class QueryConstraint extends AppliableConstraint { +} +function query(query, queryConstraint, ...additionalQueryConstraints) { + let queryConstraints = []; + if (queryConstraint instanceof AppliableConstraint) { + queryConstraints.push(queryConstraint); + } + queryConstraints = queryConstraints.concat(additionalQueryConstraints); + validateQueryConstraintArray(queryConstraints); + for (const constraint of queryConstraints) { + query = constraint._apply(query); + } + return query; +} +/** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ +class QueryFieldFilterConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(_field, _op, _value) { + super(); + this._field = _field; + this._op = _op; + this._value = _value; + /** The type of this query constraint */ + this.type = 'where'; + } + static _create(_field, _op, _value) { + return new QueryFieldFilterConstraint(_field, _op, _value); + } + _apply(query) { + const filter = this._parse(query); + validateNewFieldFilter(query._query, filter); + return new Query(query.firestore, query.converter, queryWithAddedFilter(query._query, filter)); + } + _parse(query) { + const reader = newUserDataReader(query.firestore); + const filter = newQueryFilter(query._query, 'where', reader, query.firestore._databaseId, this._field, this._op, this._value); + return filter; + } +} +/** + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. + * + * @param fieldPath - The path to compare + * @param opStr - The operation string (e.g "<", "<=", "==", "<", + * "<=", "!="). + * @param value - The value for comparison + * @returns The created {@link QueryFieldFilterConstraint}. + */ +function where(fieldPath, opStr, value) { + const op = opStr; + const field = fieldPathFromArgument('where', fieldPath); + return QueryFieldFilterConstraint._create(field, op, value); +} +/** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ +class QueryCompositeFilterConstraint extends AppliableConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + type, _queryConstraints) { + super(); + this.type = type; + this._queryConstraints = _queryConstraints; + } + static _create(type, _queryConstraints) { + return new QueryCompositeFilterConstraint(type, _queryConstraints); + } + _parse(query) { + const parsedFilters = this._queryConstraints + .map(queryConstraint => { + return queryConstraint._parse(query); + }) + .filter(parsedFilter => parsedFilter.getFilters().length > 0); + if (parsedFilters.length === 1) { + return parsedFilters[0]; + } + return CompositeFilter.create(parsedFilters, this._getOperator()); + } + _apply(query) { + const parsedFilter = this._parse(query); + if (parsedFilter.getFilters().length === 0) { + // Return the existing query if not adding any more filters (e.g. an empty + // composite filter). + return query; + } + validateNewFilter(query._query, parsedFilter); + return new Query(query.firestore, query.converter, queryWithAddedFilter(query._query, parsedFilter)); + } + _getQueryConstraints() { + return this._queryConstraints; + } + _getOperator() { + return this.type === 'and' ? "and" /* CompositeOperator.AND */ : "or" /* CompositeOperator.OR */; + } +} +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +function or(...queryConstraints) { + // Only support QueryFilterConstraints + queryConstraints.forEach(queryConstraint => validateQueryFilterConstraint('or', queryConstraint)); + return QueryCompositeFilterConstraint._create("or" /* CompositeOperator.OR */, queryConstraints); +} +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +function and(...queryConstraints) { + // Only support QueryFilterConstraints + queryConstraints.forEach(queryConstraint => validateQueryFilterConstraint('and', queryConstraint)); + return QueryCompositeFilterConstraint._create("and" /* CompositeOperator.AND */, queryConstraints); +} +/** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ +class QueryOrderByConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(_field, _direction) { + super(); + this._field = _field; + this._direction = _direction; + /** The type of this query constraint */ + this.type = 'orderBy'; + } + static _create(_field, _direction) { + return new QueryOrderByConstraint(_field, _direction); + } + _apply(query) { + const orderBy = newQueryOrderBy(query._query, this._field, this._direction); + return new Query(query.firestore, query.converter, queryWithAddedOrderBy(query._query, orderBy)); + } +} +/** + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the + * specified field, optionally in descending order instead of ascending. + * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * + * @param fieldPath - The field to sort by. + * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @returns The created {@link QueryOrderByConstraint}. + */ +function orderBy(fieldPath, directionStr = 'asc') { + const direction = directionStr; + const path = fieldPathFromArgument('orderBy', fieldPath); + return QueryOrderByConstraint._create(path, direction); +} +/** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ +class QueryLimitConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + type, _limit, _limitType) { + super(); + this.type = type; + this._limit = _limit; + this._limitType = _limitType; + } + static _create(type, _limit, _limitType) { + return new QueryLimitConstraint(type, _limit, _limitType); + } + _apply(query) { + return new Query(query.firestore, query.converter, queryWithLimit(query._query, this._limit, this._limitType)); + } +} +/** + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +function limit(limit) { + validatePositiveNumber('limit', limit); + return QueryLimitConstraint._create('limit', limit, "F" /* LimitType.First */); +} +/** + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. + * + * You must specify at least one `orderBy` clause for `limitToLast` queries, + * otherwise an exception will be thrown during execution. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +function limitToLast(limit) { + validatePositiveNumber('limitToLast', limit); + return QueryLimitConstraint._create('limitToLast', limit, "L" /* LimitType.Last */); +} +/** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ +class QueryStartAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + type, _docOrFields, _inclusive) { + super(); + this.type = type; + this._docOrFields = _docOrFields; + this._inclusive = _inclusive; + } + static _create(type, _docOrFields, _inclusive) { + return new QueryStartAtConstraint(type, _docOrFields, _inclusive); + } + _apply(query) { + const bound = newQueryBoundFromDocOrFields(query, this.type, this._docOrFields, this._inclusive); + return new Query(query.firestore, query.converter, queryWithStartAt(query._query, bound)); + } +} +function startAt(...docOrFields) { + return QueryStartAtConstraint._create('startAt', docOrFields, + /*inclusive=*/ true); +} +function startAfter(...docOrFields) { + return QueryStartAtConstraint._create('startAfter', docOrFields, + /*inclusive=*/ false); +} +/** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ +class QueryEndAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + type, _docOrFields, _inclusive) { + super(); + this.type = type; + this._docOrFields = _docOrFields; + this._inclusive = _inclusive; + } + static _create(type, _docOrFields, _inclusive) { + return new QueryEndAtConstraint(type, _docOrFields, _inclusive); + } + _apply(query) { + const bound = newQueryBoundFromDocOrFields(query, this.type, this._docOrFields, this._inclusive); + return new Query(query.firestore, query.converter, queryWithEndAt(query._query, bound)); + } +} +function endBefore(...docOrFields) { + return QueryEndAtConstraint._create('endBefore', docOrFields, + /*inclusive=*/ false); +} +function endAt(...docOrFields) { + return QueryEndAtConstraint._create('endAt', docOrFields, + /*inclusive=*/ true); +} +/** Helper function to create a bound from a document or fields */ +function newQueryBoundFromDocOrFields(query, methodName, docOrFields, inclusive) { + docOrFields[0] = util.getModularInstance(docOrFields[0]); + if (docOrFields[0] instanceof DocumentSnapshot) { + return newQueryBoundFromDocument(query._query, query.firestore._databaseId, methodName, docOrFields[0]._document, inclusive); + } + else { + const reader = newUserDataReader(query.firestore); + return newQueryBoundFromFields(query._query, query.firestore._databaseId, reader, methodName, docOrFields, inclusive); + } +} +function newQueryFilter(query, methodName, dataReader, databaseId, fieldPath, op, value) { + let fieldValue; + if (fieldPath.isKeyField()) { + if (op === "array-contains" /* Operator.ARRAY_CONTAINS */ || op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid Query. You can't perform '${op}' queries on documentId().`); + } + else if (op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */) { + validateDisjunctiveFilterElements(value, op); + const referenceList = []; + for (const arrayValue of value) { + referenceList.push(parseDocumentIdValue(databaseId, query, arrayValue)); + } + fieldValue = { arrayValue: { values: referenceList } }; + } + else { + fieldValue = parseDocumentIdValue(databaseId, query, value); + } + } + else { + if (op === "in" /* Operator.IN */ || + op === "not-in" /* Operator.NOT_IN */ || + op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) { + validateDisjunctiveFilterElements(value, op); + } + fieldValue = parseQueryValue(dataReader, methodName, value, + /* allowArrays= */ op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */); + } + const filter = FieldFilter.create(fieldPath, op, fieldValue); + return filter; +} +function newQueryOrderBy(query, fieldPath, direction) { + if (query.startAt !== null) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call startAt() or startAfter() before ' + + 'calling orderBy().'); + } + if (query.endAt !== null) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call endAt() or endBefore() before ' + + 'calling orderBy().'); + } + const orderBy = new OrderBy(fieldPath, direction); + return orderBy; +} +/** + * Create a `Bound` from a query and a document. + * + * Note that the `Bound` will always include the key of the document + * and so only the provided document will compare equal to the returned + * position. + * + * Will throw if the document does not contain all fields of the order by + * of the query or if any of the fields in the order by are an uncommitted + * server timestamp. + */ +function newQueryBoundFromDocument(query, databaseId, methodName, doc, inclusive) { + if (!doc) { + throw new FirestoreError(Code.NOT_FOUND, `Can't use a DocumentSnapshot that doesn't exist for ` + + `${methodName}().`); + } + const components = []; + // Because people expect to continue/end a query at the exact document + // provided, we need to use the implicit sort order rather than the explicit + // sort order, because it's guaranteed to contain the document key. That way + // the position becomes unambiguous and the query continues/ends exactly at + // the provided document. Without the key (by using the explicit sort + // orders), multiple documents could match the position, yielding duplicate + // results. + for (const orderBy of queryNormalizedOrderBy(query)) { + if (orderBy.field.isKeyField()) { + components.push(refValue(databaseId, doc.key)); + } + else { + const value = doc.data.field(orderBy.field); + if (isServerTimestamp(value)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You are trying to start or end a query using a ' + + 'document for which the field "' + + orderBy.field + + '" is an uncommitted server timestamp. (Since the value of ' + + 'this field is unknown, you cannot start/end a query with it.)'); + } + else if (value !== null) { + components.push(value); + } + else { + const field = orderBy.field.canonicalString(); + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. You are trying to start or end a query using a ` + + `document for which the field '${field}' (used as the ` + + `orderBy) does not exist.`); + } + } + } + return new Bound(components, inclusive); +} +/** + * Converts a list of field values to a `Bound` for the given query. + */ +function newQueryBoundFromFields(query, databaseId, dataReader, methodName, values, inclusive) { + // Use explicit order by's because it has to match the query the user made + const orderBy = query.explicitOrderBy; + if (values.length > orderBy.length) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Too many arguments provided to ${methodName}(). ` + + `The number of arguments must be less than or equal to the ` + + `number of orderBy() clauses`); + } + const components = []; + for (let i = 0; i < values.length; i++) { + const rawValue = values[i]; + const orderByComponent = orderBy[i]; + if (orderByComponent.field.isKeyField()) { + if (typeof rawValue !== 'string') { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. Expected a string for document ID in ` + + `${methodName}(), but got a ${typeof rawValue}`); + } + if (!isCollectionGroupQuery(query) && rawValue.indexOf('/') !== -1) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection and ordering by documentId(), ` + + `the value passed to ${methodName}() must be a plain document ID, but ` + + `'${rawValue}' contains a slash.`); + } + const path = query.path.child(ResourcePath.fromString(rawValue)); + if (!DocumentKey.isDocumentKey(path)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection group and ordering by ` + + `documentId(), the value passed to ${methodName}() must result in a ` + + `valid document path, but '${path}' is not because it contains an odd number ` + + `of segments.`); + } + const key = new DocumentKey(path); + components.push(refValue(databaseId, key)); + } + else { + const wrapped = parseQueryValue(dataReader, methodName, rawValue); + components.push(wrapped); + } + } + return new Bound(components, inclusive); +} +/** + * Parses the given `documentIdValue` into a `ReferenceValue`, throwing + * appropriate errors if the value is anything other than a `DocumentReference` + * or `string`, or if the string is malformed. + */ +function parseDocumentIdValue(databaseId, query, documentIdValue) { + documentIdValue = util.getModularInstance(documentIdValue); + if (typeof documentIdValue === 'string') { + if (documentIdValue === '') { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. When querying with documentId(), you ' + + 'must provide a valid document ID, but it was an empty string.'); + } + if (!isCollectionGroupQuery(query) && documentIdValue.indexOf('/') !== -1) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection by ` + + `documentId(), you must provide a plain document ID, but ` + + `'${documentIdValue}' contains a '/' character.`); + } + const path = query.path.child(ResourcePath.fromString(documentIdValue)); + if (!DocumentKey.isDocumentKey(path)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection group by ` + + `documentId(), the value provided must result in a valid document path, ` + + `but '${path}' is not because it has an odd number of segments (${path.length}).`); + } + return refValue(databaseId, new DocumentKey(path)); + } + else if (documentIdValue instanceof DocumentReference) { + return refValue(databaseId, documentIdValue._key); + } + else { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying with documentId(), you must provide a valid ` + + `string or a DocumentReference, but it was: ` + + `${valueDescription(documentIdValue)}.`); + } +} +/** + * Validates that the value passed into a disjunctive filter satisfies all + * array requirements. + */ +function validateDisjunctiveFilterElements(value, operator) { + if (!Array.isArray(value) || value.length === 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid Query. A non-empty array is required for ' + + `'${operator.toString()}' filters.`); + } +} +/** + * Given an operator, returns the set of operators that cannot be used with it. + * + * This is not a comprehensive check, and this function should be removed in the + * long term. Validations should occur in the Firestore backend. + * + * Operators in a query must adhere to the following set of rules: + * 1. Only one inequality per query. + * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators. + */ +function conflictingOps(op) { + switch (op) { + case "!=" /* Operator.NOT_EQUAL */: + return ["!=" /* Operator.NOT_EQUAL */, "not-in" /* Operator.NOT_IN */]; + case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */: + case "in" /* Operator.IN */: + return ["not-in" /* Operator.NOT_IN */]; + case "not-in" /* Operator.NOT_IN */: + return [ + "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */, + "in" /* Operator.IN */, + "not-in" /* Operator.NOT_IN */, + "!=" /* Operator.NOT_EQUAL */ + ]; + default: + return []; + } +} +function validateNewFieldFilter(query, fieldFilter) { + const conflictingOp = findOpInsideFilters(query.filters, conflictingOps(fieldFilter.op)); + if (conflictingOp !== null) { + // Special case when it's a duplicate op to give a slightly clearer error message. + if (conflictingOp === fieldFilter.op) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You cannot use more than one ' + + `'${fieldFilter.op.toString()}' filter.`); + } + else { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. You cannot use '${fieldFilter.op.toString()}' filters ` + + `with '${conflictingOp.toString()}' filters.`); + } + } +} +function validateNewFilter(query, filter) { + let testQuery = query; + const subFilters = filter.getFlattenedFilters(); + for (const subFilter of subFilters) { + validateNewFieldFilter(testQuery, subFilter); + testQuery = queryWithAddedFilter(testQuery, subFilter); + } +} +// Checks if any of the provided filter operators are included in the given list of filters and +// returns the first one that is, or null if none are. +function findOpInsideFilters(filters, operators) { + for (const filter of filters) { + for (const fieldFilter of filter.getFlattenedFilters()) { + if (operators.indexOf(fieldFilter.op) >= 0) { + return fieldFilter.op; + } + } + } + return null; +} +function validateQueryFilterConstraint(functionName, queryConstraint) { + if (!(queryConstraint instanceof QueryFieldFilterConstraint) && + !(queryConstraint instanceof QueryCompositeFilterConstraint)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${functionName}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`); + } +} +function validateQueryConstraintArray(queryConstraint) { + const compositeFilterCount = queryConstraint.filter(filter => filter instanceof QueryCompositeFilterConstraint).length; + const fieldFilterCount = queryConstraint.filter(filter => filter instanceof QueryFieldFilterConstraint).length; + if (compositeFilterCount > 1 || + (compositeFilterCount > 0 && fieldFilterCount > 0)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'InvalidQuery. When using composite filters, you cannot use ' + + 'more than one filter at the top level. Consider nesting the multiple ' + + 'filters within an `and(...)` statement. For example: ' + + 'change `query(query, where(...), or(...))` to ' + + '`query(query, and(where(...), or(...)))`.'); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Converts Firestore's internal types to the JavaScript types that we expose + * to the user. + * + * @internal + */ +class AbstractUserDataWriter { + convertValue(value, serverTimestampBehavior = 'none') { + switch (typeOrder(value)) { + case 0 /* TypeOrder.NullValue */: + return null; + case 1 /* TypeOrder.BooleanValue */: + return value.booleanValue; + case 2 /* TypeOrder.NumberValue */: + return normalizeNumber(value.integerValue || value.doubleValue); + case 3 /* TypeOrder.TimestampValue */: + return this.convertTimestamp(value.timestampValue); + case 4 /* TypeOrder.ServerTimestampValue */: + return this.convertServerTimestamp(value, serverTimestampBehavior); + case 5 /* TypeOrder.StringValue */: + return value.stringValue; + case 6 /* TypeOrder.BlobValue */: + return this.convertBytes(normalizeByteString(value.bytesValue)); + case 7 /* TypeOrder.RefValue */: + return this.convertReference(value.referenceValue); + case 8 /* TypeOrder.GeoPointValue */: + return this.convertGeoPoint(value.geoPointValue); + case 9 /* TypeOrder.ArrayValue */: + return this.convertArray(value.arrayValue, serverTimestampBehavior); + case 11 /* TypeOrder.ObjectValue */: + return this.convertObject(value.mapValue, serverTimestampBehavior); + case 10 /* TypeOrder.VectorValue */: + return this.convertVectorValue(value.mapValue); + default: + throw fail(0xf2a2, { + value + }); + } + } + convertObject(mapValue, serverTimestampBehavior) { + return this.convertObjectMap(mapValue.fields, serverTimestampBehavior); + } + /** + * @internal + */ + convertObjectMap(fields, serverTimestampBehavior = 'none') { + const result = {}; + forEach(fields, (key, value) => { + result[key] = this.convertValue(value, serverTimestampBehavior); + }); + return result; + } + /** + * @internal + */ + convertVectorValue(mapValue) { + const values = mapValue.fields?.[VECTOR_MAP_VECTORS_KEY].arrayValue?.values?.map(value => { + return normalizeNumber(value.doubleValue); + }); + return new VectorValue(values); + } + convertGeoPoint(value) { + return new GeoPoint(normalizeNumber(value.latitude), normalizeNumber(value.longitude)); + } + convertArray(arrayValue, serverTimestampBehavior) { + return (arrayValue.values || []).map(value => this.convertValue(value, serverTimestampBehavior)); + } + convertServerTimestamp(value, serverTimestampBehavior) { + switch (serverTimestampBehavior) { + case 'previous': + const previousValue = getPreviousValue(value); + if (previousValue == null) { + return null; + } + return this.convertValue(previousValue, serverTimestampBehavior); + case 'estimate': + return this.convertTimestamp(getLocalWriteTime(value)); + default: + return null; + } + } + convertTimestamp(value) { + const normalizedValue = normalizeTimestamp(value); + return new Timestamp(normalizedValue.seconds, normalizedValue.nanos); + } + convertDocumentKey(name, expectedDatabaseId) { + const resourcePath = ResourcePath.fromString(name); + hardAssert(isValidResourceName(resourcePath), 0x25d8, { name }); + const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3)); + const key = new DocumentKey(resourcePath.popFirst(5)); + if (!databaseId.isEqual(expectedDatabaseId)) { + // TODO(b/64130202): Somehow support foreign references. + logError(`Document ${key} contains a document ` + + `reference within a different database (` + + `${databaseId.projectId}/${databaseId.database}) which is not ` + + `supported. It will be treated as a reference in the current ` + + `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` + + `instead.`); + } + return key; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Converts custom model object of type T into `DocumentData` by applying the + * converter if it exists. + * + * This function is used when converting user objects to `DocumentData` + * because we want to provide the user with a more specific error message if + * their `set()` or fails due to invalid data originating from a `toFirestore()` + * call. + */ +function applyFirestoreDataConverter(converter, value, options) { + let convertedValue; + if (converter) { + if (options && (options.merge || options.mergeFields)) { + // Cast to `any` in order to satisfy the union type constraint on + // toFirestore(). + // eslint-disable-next-line @typescript-eslint/no-explicit-any + convertedValue = converter.toFirestore(value, options); + } + else { + convertedValue = converter.toFirestore(value); + } + } + else { + convertedValue = value; + } + return convertedValue; +} +class LiteUserDataWriter extends AbstractUserDataWriter { + constructor(firestore) { + super(); + this.firestore = firestore; + } + convertBytes(bytes) { + return new Bytes(bytes); + } + convertReference(name) { + const key = this.convertDocumentKey(name, this.firestore._databaseId); + return new DocumentReference(this.firestore, /* converter= */ null, key); + } +} +/** + * Reads the document referred to by the specified document reference. + * + * All documents are directly fetched from the server, even if the document was + * previously read or modified. Recent modifications are only reflected in the + * retrieved `DocumentSnapshot` if they have already been applied by the + * backend. If the client is offline, the read fails. If you like to use + * caching or see local modifications, please use the full Firestore SDK. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the current + * document contents. + */ +function getDoc(reference) { + reference = cast(reference, DocumentReference); + const datastore = getDatastore(reference.firestore); + const userDataWriter = new LiteUserDataWriter(reference.firestore); + return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then(result => { + hardAssert(result.length === 1, 0x3d02); + const document = result[0]; + return new DocumentSnapshot(reference.firestore, userDataWriter, reference._key, document.isFoundDocument() ? document : null, reference.converter); + }); +} +/** + * Executes the query and returns the results as a {@link QuerySnapshot}. + * + * All queries are executed directly by the server, even if the query was + * previously executed. Recent modifications are only reflected in the retrieved + * results if they have already been applied by the backend. If the client is + * offline, the operation fails. To see previously cached result and local + * modifications, use the full Firestore SDK. + * + * @param query - The `Query` to execute. + * @returns A Promise that will be resolved with the results of the query. + */ +function getDocs(query) { + query = cast(query, Query); + validateHasExplicitOrderByForLimitToLast(query._query); + const datastore = getDatastore(query.firestore); + const userDataWriter = new LiteUserDataWriter(query.firestore); + return invokeRunQueryRpc(datastore, query._query).then(result => { + const docs = result.map(doc => new QueryDocumentSnapshot(query.firestore, userDataWriter, doc.key, doc, query.converter)); + if (query._query.limitType === "L" /* LimitType.Last */) { + // Limit to last queries reverse the orderBy constraint that was + // specified by the user. As such, we need to reverse the order of the + // results to return the documents in the expected order. + docs.reverse(); + } + return new QuerySnapshot(query, docs); + }); +} +function setDoc(reference, data, options) { + reference = cast(reference, DocumentReference); + const convertedValue = applyFirestoreDataConverter(reference.converter, data, options); + const dataReader = newUserDataReader(reference.firestore); + const parsed = parseSetData(dataReader, 'setDoc', reference._key, convertedValue, reference.converter !== null, options); + const datastore = getDatastore(reference.firestore); + return invokeCommitRpc(datastore, [ + parsed.toMutation(reference._key, Precondition.none()) + ]); +} +function updateDoc(reference, fieldOrUpdateData, value, ...moreFieldsAndValues) { + reference = cast(reference, DocumentReference); + const dataReader = newUserDataReader(reference.firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + fieldOrUpdateData = util.getModularInstance(fieldOrUpdateData); + let parsed; + if (typeof fieldOrUpdateData === 'string' || + fieldOrUpdateData instanceof FieldPath) { + parsed = parseUpdateVarargs(dataReader, 'updateDoc', reference._key, fieldOrUpdateData, value, moreFieldsAndValues); + } + else { + parsed = parseUpdateData(dataReader, 'updateDoc', reference._key, fieldOrUpdateData); + } + const datastore = getDatastore(reference.firestore); + return invokeCommitRpc(datastore, [ + parsed.toMutation(reference._key, Precondition.exists(true)) + ]); +} +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * The deletion will only be reflected in document reads that occur after the + * returned promise resolves. If the client is offline, the + * delete fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to delete. + * @returns A `Promise` resolved once the document has been successfully + * deleted from the backend. + */ +function deleteDoc(reference) { + reference = cast(reference, DocumentReference); + const datastore = getDatastore(reference.firestore); + return invokeCommitRpc(datastore, [ + new DeleteMutation(reference._key, Precondition.none()) + ]); +} +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend. + */ +function addDoc(reference, data) { + reference = cast(reference, CollectionReference); + const docRef = doc(reference); + const convertedValue = applyFirestoreDataConverter(reference.converter, data); + const dataReader = newUserDataReader(reference.firestore); + const parsed = parseSetData(dataReader, 'addDoc', docRef._key, convertedValue, docRef.converter !== null, {}); + const datastore = getDatastore(reference.firestore); + return invokeCommitRpc(datastore, [ + parsed.toMutation(docRef._key, Precondition.exists(false)) + ]).then(() => docRef); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ +function getCount(query) { + const countQuerySpec = { + count: count() + }; + return getAggregate(query, countQuerySpec); +} +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregate(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ +function getAggregate(query, aggregateSpec) { + const firestore = cast(query.firestore, Firestore); + const datastore = getDatastore(firestore); + const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => { + return new AggregateImpl(alias, aggregate.aggregateType, aggregate._internalFieldPath); + }); + // Run the aggregation and convert the results + return invokeRunAggregationQueryRpc(datastore, query._query, internalAggregates).then(aggregateResult => convertToAggregateQuerySnapshot(firestore, query, aggregateResult)); +} +function convertToAggregateQuerySnapshot(firestore, query, aggregateResult) { + const userDataWriter = new LiteUserDataWriter(firestore); + const querySnapshot = new AggregateQuerySnapshot(query, userDataWriter, aggregateResult); + return querySnapshot; +} +/** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ +function sum(field) { + return new AggregateField('sum', fieldPathFromArgument$1('sum', field)); +} +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ +function average(field) { + return new AggregateField('avg', fieldPathFromArgument$1('average', field)); +} +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ +function count() { + return new AggregateField('count'); +} +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ +function aggregateFieldEqual(left, right) { + return (left instanceof AggregateField && + right instanceof AggregateField && + left.aggregateType === right.aggregateType && + left._internalFieldPath?.canonicalString() === + right._internalFieldPath?.canonicalString()); +} +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ +function aggregateQuerySnapshotEqual(left, right) { + return (queryEqual(left.query, right.query) && util.deepEqual(left.data(), right.data())); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. + */ +function deleteField() { + return new DeleteFieldValueImpl('deleteField'); +} +/** + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to + * include a server-generated timestamp in the written data. + */ +function serverTimestamp() { + return new ServerTimestampFieldValueImpl('serverTimestamp'); +} +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array + * value that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements - The elements to union into the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()`. + */ +function arrayUnion(...elements) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new ArrayUnionFieldValueImpl('arrayUnion', elements); +} +/** + * Returns a special value that can be used with {@link (setDoc:1)} or {@link + * updateDoc:1} that tells the server to remove the given elements from any + * array value that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is not + * already an array it will be overwritten with an empty array. + * + * @param elements - The elements to remove from the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +function arrayRemove(...elements) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new ArrayRemoveFieldValueImpl('arrayRemove', elements); +} +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by + * the given value. + * + * If either the operand or the current field value uses floating point + * precision, all arithmetic follows IEEE 754 semantics. If both values are + * integers, values outside of JavaScript's safe number range + * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to + * precision loss. Furthermore, once processed by the Firestore backend, all + * integer operations are capped between -2^63 and 2^63-1. + * + * If the current field value is not of type `number`, or if the field does not + * yet exist, the transformation sets the field to the given value. + * + * @param n - The value to increment by. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +function increment(n) { + return new NumericIncrementFieldValueImpl('increment', n); +} +/** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ +function vector(values) { + return new VectorValue(values); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It + * provides methods for adding writes to the write batch. None of the writes + * will be committed (or visible locally) until {@link WriteBatch.commit} is + * called. + */ +class WriteBatch { + /** @hideconstructor */ + constructor(_firestore, _commitHandler) { + this._firestore = _firestore; + this._commitHandler = _commitHandler; + this._mutations = []; + this._committed = false; + this._dataReader = newUserDataReader(_firestore); + } + set(documentRef, data, options) { + this._verifyNotCommitted(); + const ref = validateReference(documentRef, this._firestore); + const convertedValue = applyFirestoreDataConverter(ref.converter, data, options); + const parsed = parseSetData(this._dataReader, 'WriteBatch.set', ref._key, convertedValue, ref.converter !== null, options); + this._mutations.push(parsed.toMutation(ref._key, Precondition.none())); + return this; + } + update(documentRef, fieldOrUpdateData, value, ...moreFieldsAndValues) { + this._verifyNotCommitted(); + const ref = validateReference(documentRef, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + fieldOrUpdateData = util.getModularInstance(fieldOrUpdateData); + let parsed; + if (typeof fieldOrUpdateData === 'string' || + fieldOrUpdateData instanceof FieldPath) { + parsed = parseUpdateVarargs(this._dataReader, 'WriteBatch.update', ref._key, fieldOrUpdateData, value, moreFieldsAndValues); + } + else { + parsed = parseUpdateData(this._dataReader, 'WriteBatch.update', ref._key, fieldOrUpdateData); + } + this._mutations.push(parsed.toMutation(ref._key, Precondition.exists(true))); + return this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + delete(documentRef) { + this._verifyNotCommitted(); + const ref = validateReference(documentRef, this._firestore); + this._mutations = this._mutations.concat(new DeleteMutation(ref._key, Precondition.none())); + return this; + } + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `Promise` resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit (note that it won't + * resolve while you're offline). + */ + commit() { + this._verifyNotCommitted(); + this._committed = true; + if (this._mutations.length > 0) { + return this._commitHandler(this._mutations); + } + return Promise.resolve(); + } + _verifyNotCommitted() { + if (this._committed) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'A write batch can no longer be used after commit() ' + + 'has been called.'); + } + } +} +function validateReference(documentRef, firestore) { + documentRef = util.getModularInstance(documentRef); + if (documentRef.firestore !== firestore) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Provided document reference is from a different Firestore instance.'); + } + else { + return documentRef; + } +} +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single WriteBatch + * is 500. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `WriteBatch` that can be used to atomically execute multiple + * writes. + */ +function writeBatch(firestore) { + firestore = cast(firestore, Firestore); + const datastore = getDatastore(firestore); + return new WriteBatch(firestore, writes => invokeCommitRpc(datastore, writes)); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const DEFAULT_TRANSACTION_OPTIONS = { + maxAttempts: 5 +}; +function validateTransactionOptions(options) { + if (options.maxAttempts < 1) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Max attempts must be at least 1'); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Internal transaction object responsible for accumulating the mutations to + * perform and the base versions for any documents read. + */ +class Transaction$1 { + constructor(datastore) { + this.datastore = datastore; + // The version of each document that was read during this transaction. + this.readVersions = new Map(); + this.mutations = []; + this.committed = false; + /** + * A deferred usage error that occurred previously in this transaction that + * will cause the transaction to fail once it actually commits. + */ + this.lastTransactionError = null; + /** + * Set of documents that have been written in the transaction. + * + * When there's more than one write to the same key in a transaction, any + * writes after the first are handled differently. + */ + this.writtenDocs = new Set(); + } + async lookup(keys) { + this.ensureCommitNotCalled(); + if (this.mutations.length > 0) { + this.lastTransactionError = new FirestoreError(Code.INVALID_ARGUMENT, 'Firestore transactions require all reads to be executed before all writes.'); + throw this.lastTransactionError; + } + const docs = await invokeBatchGetDocumentsRpc(this.datastore, keys); + docs.forEach(doc => this.recordVersion(doc)); + return docs; + } + set(key, data) { + this.write(data.toMutation(key, this.precondition(key))); + this.writtenDocs.add(key.toString()); + } + update(key, data) { + try { + this.write(data.toMutation(key, this.preconditionForUpdate(key))); + } + catch (e) { + this.lastTransactionError = e; + } + this.writtenDocs.add(key.toString()); + } + delete(key) { + this.write(new DeleteMutation(key, this.precondition(key))); + this.writtenDocs.add(key.toString()); + } + async commit() { + this.ensureCommitNotCalled(); + if (this.lastTransactionError) { + throw this.lastTransactionError; + } + const unwritten = this.readVersions; + // For each mutation, note that the doc was written. + this.mutations.forEach(mutation => { + unwritten.delete(mutation.key.toString()); + }); + // For each document that was read but not written to, we want to perform + // a `verify` operation. + unwritten.forEach((_, path) => { + const key = DocumentKey.fromPath(path); + this.mutations.push(new VerifyMutation(key, this.precondition(key))); + }); + await invokeCommitRpc(this.datastore, this.mutations); + this.committed = true; + } + recordVersion(doc) { + let docVersion; + if (doc.isFoundDocument()) { + docVersion = doc.version; + } + else if (doc.isNoDocument()) { + // Represent a deleted doc using SnapshotVersion.min(). + docVersion = SnapshotVersion.min(); + } + else { + throw fail(0xc542, { + documentName: doc.constructor.name + }); + } + const existingVersion = this.readVersions.get(doc.key.toString()); + if (existingVersion) { + if (!docVersion.isEqual(existingVersion)) { + // This transaction will fail no matter what. + throw new FirestoreError(Code.ABORTED, 'Document version changed between two reads.'); + } + } + else { + this.readVersions.set(doc.key.toString(), docVersion); + } + } + /** + * Returns the version of this document when it was read in this transaction, + * as a precondition, or no precondition if it was not read. + */ + precondition(key) { + const version = this.readVersions.get(key.toString()); + if (!this.writtenDocs.has(key.toString()) && version) { + if (version.isEqual(SnapshotVersion.min())) { + return Precondition.exists(false); + } + else { + return Precondition.updateTime(version); + } + } + else { + return Precondition.none(); + } + } + /** + * Returns the precondition for a document if the operation is an update. + */ + preconditionForUpdate(key) { + const version = this.readVersions.get(key.toString()); + // The first time a document is written, we want to take into account the + // read time and existence + if (!this.writtenDocs.has(key.toString()) && version) { + if (version.isEqual(SnapshotVersion.min())) { + // The document doesn't exist, so fail the transaction. + // This has to be validated locally because you can't send a + // precondition that a document does not exist without changing the + // semantics of the backend write to be an insert. This is the reverse + // of what we want, since we want to assert that the document doesn't + // exist but then send the update and have it fail. Since we can't + // express that to the backend, we have to validate locally. + // Note: this can change once we can send separate verify writes in the + // transaction. + throw new FirestoreError(Code.INVALID_ARGUMENT, "Can't update a document that doesn't exist."); + } + // Document exists, base precondition on document update time. + return Precondition.updateTime(version); + } + else { + // Document was not read, so we just use the preconditions for a blind + // update. + return Precondition.exists(true); + } + } + write(mutation) { + this.ensureCommitNotCalled(); + this.mutations.push(mutation); + } + ensureCommitNotCalled() { + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * TransactionRunner encapsulates the logic needed to run and retry transactions + * with backoff. + */ +class TransactionRunner { + constructor(asyncQueue, datastore, options, updateFunction, deferred) { + this.asyncQueue = asyncQueue; + this.datastore = datastore; + this.options = options; + this.updateFunction = updateFunction; + this.deferred = deferred; + this.attemptsRemaining = options.maxAttempts; + this.backoff = new ExponentialBackoff(this.asyncQueue, "transaction_retry" /* TimerId.TransactionRetry */); + } + /** Runs the transaction and sets the result on deferred. */ + run() { + this.attemptsRemaining -= 1; + this.runWithBackOff(); + } + runWithBackOff() { + this.backoff.backoffAndRun(async () => { + const transaction = new Transaction$1(this.datastore); + const userPromise = this.tryRunUpdateFunction(transaction); + if (userPromise) { + userPromise + .then(result => { + this.asyncQueue.enqueueAndForget(() => { + return transaction + .commit() + .then(() => { + this.deferred.resolve(result); + }) + .catch(commitError => { + this.handleTransactionError(commitError); + }); + }); + }) + .catch(userPromiseError => { + this.handleTransactionError(userPromiseError); + }); + } + }); + } + tryRunUpdateFunction(transaction) { + try { + const userPromise = this.updateFunction(transaction); + if (isNullOrUndefined(userPromise) || + !userPromise.catch || + !userPromise.then) { + this.deferred.reject(Error('Transaction callback must return a Promise')); + return null; + } + return userPromise; + } + catch (error) { + // Do not retry errors thrown by user provided updateFunction. + this.deferred.reject(error); + return null; + } + } + handleTransactionError(error) { + if (this.attemptsRemaining > 0 && this.isRetryableTransactionError(error)) { + this.attemptsRemaining -= 1; + this.asyncQueue.enqueueAndForget(() => { + this.runWithBackOff(); + return Promise.resolve(); + }); + } + else { + this.deferred.reject(error); + } + } + isRetryableTransactionError(error) { + if (error?.name === 'FirebaseError') { + // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and + // non-matching document versions with ABORTED. These errors should be retried. + const code = error.code; + return (code === 'aborted' || + code === 'failed-precondition' || + code === 'already-exists' || + !isPermanentError(code)); + } + return false; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents an operation scheduled to be run in the future on an AsyncQueue. + * + * It is created via DelayedOperation.createAndSchedule(). + * + * Supports cancellation (via cancel()) and early execution (via skipDelay()). + * + * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type + * in newer versions of TypeScript defines `finally`, which is not available in + * IE. + */ +class DelayedOperation { + constructor(asyncQueue, timerId, targetTimeMs, op, removalCallback) { + this.asyncQueue = asyncQueue; + this.timerId = timerId; + this.targetTimeMs = targetTimeMs; + this.op = op; + this.removalCallback = removalCallback; + this.deferred = new Deferred(); + this.then = this.deferred.promise.then.bind(this.deferred.promise); + // It's normal for the deferred promise to be canceled (due to cancellation) + // and so we attach a dummy catch callback to avoid + // 'UnhandledPromiseRejectionWarning' log spam. + this.deferred.promise.catch(err => { }); + } + get promise() { + return this.deferred.promise; + } + /** + * Creates and returns a DelayedOperation that has been scheduled to be + * executed on the provided asyncQueue after the provided delayMs. + * + * @param asyncQueue - The queue to schedule the operation on. + * @param id - A Timer ID identifying the type of operation this is. + * @param delayMs - The delay (ms) before the operation should be scheduled. + * @param op - The operation to run. + * @param removalCallback - A callback to be called synchronously once the + * operation is executed or canceled, notifying the AsyncQueue to remove it + * from its delayedOperations list. + * PORTING NOTE: This exists to prevent making removeDelayedOperation() and + * the DelayedOperation class public. + */ + static createAndSchedule(asyncQueue, timerId, delayMs, op, removalCallback) { + const targetTime = Date.now() + delayMs; + const delayedOp = new DelayedOperation(asyncQueue, timerId, targetTime, op, removalCallback); + delayedOp.start(delayMs); + return delayedOp; + } + /** + * Starts the timer. This is called immediately after construction by + * createAndSchedule(). + */ + start(delayMs) { + this.timerHandle = setTimeout(() => this.handleDelayElapsed(), delayMs); + } + /** + * Queues the operation to run immediately (if it hasn't already been run or + * canceled). + */ + skipDelay() { + return this.handleDelayElapsed(); + } + /** + * Cancels the operation if it hasn't already been executed or canceled. The + * promise will be rejected. + * + * As long as the operation has not yet been run, calling cancel() provides a + * guarantee that the operation will not be run. + */ + cancel(reason) { + if (this.timerHandle !== null) { + this.clearTimeout(); + this.deferred.reject(new FirestoreError(Code.CANCELLED, 'Operation cancelled' + (reason ? ': ' + reason : ''))); + } + } + handleDelayElapsed() { + this.asyncQueue.enqueueAndForget(() => { + if (this.timerHandle !== null) { + this.clearTimeout(); + return this.op().then(result => { + return this.deferred.resolve(result); + }); + } + else { + return Promise.resolve(); + } + }); + } + clearTimeout() { + if (this.timerHandle !== null) { + this.removalCallback(this); + clearTimeout(this.timerHandle); + this.timerHandle = null; + } + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG = 'AsyncQueue'; +class AsyncQueueImpl { + constructor(tail = Promise.resolve()) { + // A list of retryable operations. Retryable operations are run in order and + // retried with backoff. + this.retryableOps = []; + // Is this AsyncQueue being shut down? Once it is set to true, it will not + // be changed again. + this._isShuttingDown = false; + // Operations scheduled to be queued in the future. Operations are + // automatically removed after they are run or canceled. + this.delayedOperations = []; + // visible for testing + this.failure = null; + // Flag set while there's an outstanding AsyncQueue operation, used for + // assertion sanity-checks. + this.operationInProgress = false; + // Enabled during shutdown on Safari to prevent future access to IndexedDB. + this.skipNonRestrictedTasks = false; + // List of TimerIds to fast-forward delays for. + this.timerIdsToSkip = []; + // Backoff timer used to schedule retries for retryable operations + this.backoff = new ExponentialBackoff(this, "async_queue_retry" /* TimerId.AsyncQueueRetry */); + // Visibility handler that triggers an immediate retry of all retryable + // operations. Meant to speed up recovery when we regain file system access + // after page comes into foreground. + this.visibilityHandler = () => { + this.backoff.skipBackoff(); + }; + this.tail = tail; + } + get isShuttingDown() { + return this._isShuttingDown; + } + /** + * Adds a new operation to the queue without waiting for it to complete (i.e. + * we ignore the Promise result). + */ + enqueueAndForget(op) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.enqueue(op); + } + enqueueAndForgetEvenWhileRestricted(op) { + this.verifyNotFailed(); + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.enqueueInternal(op); + } + enterRestrictedMode(purgeExistingTasks) { + if (!this._isShuttingDown) { + this._isShuttingDown = true; + this.skipNonRestrictedTasks = purgeExistingTasks || false; + } + } + enqueue(op) { + this.verifyNotFailed(); + if (this._isShuttingDown) { + // Return a Promise which never resolves. + return new Promise(() => { }); + } + // Create a deferred Promise that we can return to the callee. This + // allows us to return a "hanging Promise" only to the callee and still + // advance the queue even when the operation is not run. + const task = new Deferred(); + return this.enqueueInternal(() => { + if (this._isShuttingDown && this.skipNonRestrictedTasks) { + // We do not resolve 'task' + return Promise.resolve(); + } + op().then(task.resolve, task.reject); + return task.promise; + }).then(() => task.promise); + } + enqueueRetryable(op) { + this.enqueueAndForget(() => { + this.retryableOps.push(op); + return this.retryNextOp(); + }); + } + /** + * Runs the next operation from the retryable queue. If the operation fails, + * reschedules with backoff. + */ + async retryNextOp() { + if (this.retryableOps.length === 0) { + return; + } + try { + await this.retryableOps[0](); + this.retryableOps.shift(); + this.backoff.reset(); + } + catch (e) { + if (isIndexedDbTransactionError(e)) { + logDebug(LOG_TAG, 'Operation failed with retryable error: ' + e); + } + else { + throw e; // Failure will be handled by AsyncQueue + } + } + if (this.retryableOps.length > 0) { + // If there are additional operations, we re-schedule `retryNextOp()`. + // This is necessary to run retryable operations that failed during + // their initial attempt since we don't know whether they are already + // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1` + // needs to be re-run, we will run `op1`, `op1`, `op2` using the + // already enqueued calls to `retryNextOp()`. `op3()` will then run in the + // call scheduled here. + // Since `backoffAndRun()` cancels an existing backoff and schedules a + // new backoff on every call, there is only ever a single additional + // operation in the queue. + this.backoff.backoffAndRun(() => this.retryNextOp()); + } + } + enqueueInternal(op) { + const newTail = this.tail.then(() => { + this.operationInProgress = true; + return op() + .catch((error) => { + this.failure = error; + this.operationInProgress = false; + const message = getMessageOrStack(error); + logError('INTERNAL UNHANDLED ERROR: ', message); + // Re-throw the error so that this.tail becomes a rejected Promise and + // all further attempts to chain (via .then) will just short-circuit + // and return the rejected Promise. + throw error; + }) + .then(result => { + this.operationInProgress = false; + return result; + }); + }); + this.tail = newTail; + return newTail; + } + enqueueAfterDelay(timerId, delayMs, op) { + this.verifyNotFailed(); + // Fast-forward delays for timerIds that have been overridden. + if (this.timerIdsToSkip.indexOf(timerId) > -1) { + delayMs = 0; + } + const delayedOp = DelayedOperation.createAndSchedule(this, timerId, delayMs, op, removedOp => this.removeDelayedOperation(removedOp)); + this.delayedOperations.push(delayedOp); + return delayedOp; + } + verifyNotFailed() { + if (this.failure) { + fail(0xb815, { + messageOrStack: getMessageOrStack(this.failure) + }); + } + } + verifyOperationInProgress() { + } + /** + * Waits until all currently queued tasks are finished executing. Delayed + * operations are not run. + */ + async drain() { + // Operations in the queue prior to draining may have enqueued additional + // operations. Keep draining the queue until the tail is no longer advanced, + // which indicates that no more new operations were enqueued and that all + // operations were executed. + let currentTail; + do { + currentTail = this.tail; + await currentTail; + } while (currentTail !== this.tail); + } + /** + * For Tests: Determine if a delayed operation with a particular TimerId + * exists. + */ + containsDelayedOperation(timerId) { + for (const op of this.delayedOperations) { + if (op.timerId === timerId) { + return true; + } + } + return false; + } + /** + * For Tests: Runs some or all delayed operations early. + * + * @param lastTimerId - Delayed operations up to and including this TimerId + * will be drained. Pass TimerId.All to run all delayed operations. + * @returns a Promise that resolves once all operations have been run. + */ + runAllDelayedOperationsUntil(lastTimerId) { + // Note that draining may generate more delayed ops, so we do that first. + return this.drain().then(() => { + // Run ops in the same order they'd run if they ran naturally. + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ + this.delayedOperations.sort((a, b) => a.targetTimeMs - b.targetTimeMs); + for (const op of this.delayedOperations) { + op.skipDelay(); + if (lastTimerId !== "all" /* TimerId.All */ && op.timerId === lastTimerId) { + break; + } + } + return this.drain(); + }); + } + /** + * For Tests: Skip all subsequent delays for a timer id. + */ + skipDelaysForTimerId(timerId) { + this.timerIdsToSkip.push(timerId); + } + /** Called once a DelayedOperation is run or canceled. */ + removeDelayedOperation(op) { + // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small. + const index = this.delayedOperations.indexOf(op); + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ + this.delayedOperations.splice(index, 1); + } +} +function newAsyncQueue() { + return new AsyncQueueImpl(); +} +/** + * Chrome includes Error.message in Error.stack. Other browsers do not. + * This returns expected output of message + stack when available. + * @param error - Error or FirestoreError + */ +function getMessageOrStack(error) { + let message = error.message || ''; + if (error.stack) { + if (error.stack.includes(error.message)) { + message = error.stack; + } + else { + message = error.message + '\n' + error.stack; + } + } + return message; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the +// legacy SDK. +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ +class Transaction { + /** @hideconstructor */ + constructor(_firestore, _transaction) { + this._firestore = _firestore; + this._transaction = _transaction; + this._dataReader = newUserDataReader(_firestore); + } + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ + get(documentRef) { + const ref = validateReference(documentRef, this._firestore); + const userDataWriter = new LiteUserDataWriter(this._firestore); + return this._transaction.lookup([ref._key]).then(docs => { + if (!docs || docs.length !== 1) { + return fail(0x5de9); + } + const doc = docs[0]; + if (doc.isFoundDocument()) { + return new DocumentSnapshot(this._firestore, userDataWriter, doc.key, doc, ref.converter); + } + else if (doc.isNoDocument()) { + return new DocumentSnapshot(this._firestore, userDataWriter, ref._key, null, ref.converter); + } + else { + throw fail(0x4801, { + doc + }); + } + }); + } + set(documentRef, value, options) { + const ref = validateReference(documentRef, this._firestore); + const convertedValue = applyFirestoreDataConverter(ref.converter, value, options); + const parsed = parseSetData(this._dataReader, 'Transaction.set', ref._key, convertedValue, ref.converter !== null, options); + this._transaction.set(ref._key, parsed); + return this; + } + update(documentRef, fieldOrUpdateData, value, ...moreFieldsAndValues) { + const ref = validateReference(documentRef, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + fieldOrUpdateData = util.getModularInstance(fieldOrUpdateData); + let parsed; + if (typeof fieldOrUpdateData === 'string' || + fieldOrUpdateData instanceof FieldPath) { + parsed = parseUpdateVarargs(this._dataReader, 'Transaction.update', ref._key, fieldOrUpdateData, value, moreFieldsAndValues); + } + else { + parsed = parseUpdateData(this._dataReader, 'Transaction.update', ref._key, fieldOrUpdateData); + } + this._transaction.update(ref._key, parsed); + return this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + delete(documentRef) { + const ref = validateReference(documentRef, this._firestore); + this._transaction.delete(ref._key); + return this; + } +} +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ +function runTransaction(firestore, updateFunction, options) { + firestore = cast(firestore, Firestore); + const datastore = getDatastore(firestore); + const optionsWithDefaults = { + ...DEFAULT_TRANSACTION_OPTIONS, + ...options + }; + validateTransactionOptions(optionsWithDefaults); + const deferred = new Deferred(); + new TransactionRunner(newAsyncQueue(), datastore, optionsWithDefaults, internalTransaction => updateFunction(new Transaction(firestore, internalTransaction)), deferred).run(); + return deferred.promise; +} + +/** + * Firestore Lite + * + * @remarks Firestore Lite is a small online-only SDK that allows read + * and write access to your Firestore database. All operations connect + * directly to the backend, and `onSnapshot()` APIs are not supported. + * @packageDocumentation + */ +registerFirestore(); + +exports.AggregateField = AggregateField; +exports.AggregateQuerySnapshot = AggregateQuerySnapshot; +exports.Bytes = Bytes; +exports.CollectionReference = CollectionReference; +exports.DocumentReference = DocumentReference; +exports.DocumentSnapshot = DocumentSnapshot; +exports.FieldPath = FieldPath; +exports.FieldValue = FieldValue; +exports.Firestore = Firestore; +exports.FirestoreError = FirestoreError; +exports.GeoPoint = GeoPoint; +exports.Query = Query; +exports.QueryCompositeFilterConstraint = QueryCompositeFilterConstraint; +exports.QueryConstraint = QueryConstraint; +exports.QueryDocumentSnapshot = QueryDocumentSnapshot; +exports.QueryEndAtConstraint = QueryEndAtConstraint; +exports.QueryFieldFilterConstraint = QueryFieldFilterConstraint; +exports.QueryLimitConstraint = QueryLimitConstraint; +exports.QueryOrderByConstraint = QueryOrderByConstraint; +exports.QuerySnapshot = QuerySnapshot; +exports.QueryStartAtConstraint = QueryStartAtConstraint; +exports.Timestamp = Timestamp; +exports.Transaction = Transaction; +exports.VectorValue = VectorValue; +exports.WriteBatch = WriteBatch; +exports.addDoc = addDoc; +exports.aggregateFieldEqual = aggregateFieldEqual; +exports.aggregateQuerySnapshotEqual = aggregateQuerySnapshotEqual; +exports.and = and; +exports.arrayRemove = arrayRemove; +exports.arrayUnion = arrayUnion; +exports.average = average; +exports.collection = collection; +exports.collectionGroup = collectionGroup; +exports.connectFirestoreEmulator = connectFirestoreEmulator; +exports.count = count; +exports.deleteDoc = deleteDoc; +exports.deleteField = deleteField; +exports.doc = doc; +exports.documentId = documentId; +exports.endAt = endAt; +exports.endBefore = endBefore; +exports.getAggregate = getAggregate; +exports.getCount = getCount; +exports.getDoc = getDoc; +exports.getDocs = getDocs; +exports.getFirestore = getFirestore; +exports.increment = increment; +exports.initializeFirestore = initializeFirestore; +exports.limit = limit; +exports.limitToLast = limitToLast; +exports.or = or; +exports.orderBy = orderBy; +exports.query = query; +exports.queryEqual = queryEqual; +exports.refEqual = refEqual; +exports.runTransaction = runTransaction; +exports.serverTimestamp = serverTimestamp; +exports.setDoc = setDoc; +exports.setLogLevel = setLogLevel; +exports.snapshotEqual = snapshotEqual; +exports.startAfter = startAfter; +exports.startAt = startAt; +exports.sum = sum; +exports.terminate = terminate; +exports.updateDoc = updateDoc; +exports.vector = vector; +exports.where = where; +exports.writeBatch = writeBatch; +//# sourceMappingURL=index.node.cjs.js.map diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.cjs.js.map b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.cjs.js.map new file mode 100644 index 0000000..105f83b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.cjs.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.node.cjs.js","sources":["../../src/auth/user.ts","../../src/core/version.ts","../../src/platform/node/format_json.ts","../../src/util/log.ts","../../src/util/assert.ts","../../src/util/error.ts","../../src/util/promise.ts","../../src/api/credentials.ts","../../src/core/database_info.ts","../../src/platform/node/random_bytes.ts","../../src/util/misc.ts","../../src/model/path.ts","../../src/model/document_key.ts","../../src/util/input_validation.ts","../../src/api/long_polling_options.ts","../../src/util/debug_uid.ts","../../src/remote/rest_connection.ts","../../src/remote/rpc_error.ts","../../src/platform/browser_lite/fetch_connection.ts","../../src/platform/node_lite/connection.ts","../../src/util/obj.ts","../../src/util/types.ts","../../src/platform/node/base64.ts","../../src/util/byte_string.ts","../../src/model/normalize.ts","../../src/util/json_validation.ts","../../src/lite-api/timestamp.ts","../../src/model/server_timestamps.ts","../../src/model/values.ts","../../src/core/bound.ts","../../src/core/filter.ts","../../src/core/order_by.ts","../../src/core/snapshot_version.ts","../../src/util/sorted_map.ts","../../src/util/sorted_set.ts","../../src/model/field_mask.ts","../../src/model/object_value.ts","../../src/model/document.ts","../../src/core/target.ts","../../src/core/query.ts","../../src/remote/number_serializer.ts","../../src/model/transform_operation.ts","../../src/model/mutation.ts","../../src/remote/serializer.ts","../../src/platform/browser/serializer.ts","../../src/remote/backoff.ts","../../src/remote/datastore.ts","../../src/lite-api/components.ts","../../src/local/lru_garbage_collector.ts","../../src/local/simple_db.ts","../../src/local/lru_garbage_collector_impl.ts","../../src/lite-api/settings.ts","../../src/lite-api/database.ts","../../lite/register.ts","../../src/core/aggregate.ts","../../src/lite-api/aggregate_types.ts","../../src/lite-api/reference.ts","../../src/lite-api/bytes.ts","../../src/lite-api/field_path.ts","../../src/lite-api/field_value.ts","../../src/lite-api/geo_point.ts","../../src/util/array.ts","../../src/lite-api/vector_value.ts","../../src/lite-api/user_data_reader.ts","../../src/lite-api/snapshot.ts","../../src/lite-api/query.ts","../../src/lite-api/user_data_writer.ts","../../src/lite-api/reference_impl.ts","../../src/lite-api/aggregate.ts","../../src/lite-api/field_value_impl.ts","../../src/lite-api/write_batch.ts","../../src/core/transaction_options.ts","../../src/core/transaction.ts","../../src/core/transaction_runner.ts","../../src/util/async_queue.ts","../../src/util/async_queue_impl.ts","../../src/lite-api/transaction.ts","../../lite/index.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Simple wrapper around a nullable UID. Mostly exists to make code more\n * readable.\n */\nexport class User {\n /** A user with a null UID. */\n static readonly UNAUTHENTICATED = new User(null);\n\n // TODO(mikelehen): Look into getting a proper uid-equivalent for\n // non-FirebaseAuth providers.\n static readonly GOOGLE_CREDENTIALS = new User('google-credentials-uid');\n static readonly FIRST_PARTY = new User('first-party-uid');\n static readonly MOCK_USER = new User('mock-user');\n\n constructor(readonly uid: string | null) {}\n\n isAuthenticated(): boolean {\n return this.uid != null;\n }\n\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */\n toKey(): string {\n if (this.isAuthenticated()) {\n return 'uid:' + this.uid;\n } else {\n return 'anonymous-user';\n }\n }\n\n isEqual(otherUser: User): boolean {\n return otherUser.uid === this.uid;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The semver (www.semver.org) version of the SDK. */\nimport { version } from '../../../firebase/package.json';\nexport let SDK_VERSION = version;\nexport function setSDKVersion(version: string): void {\n SDK_VERSION = version;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { inspect } from 'util';\n\n/** Formats an object as a JSON string, suitable for logging. */\nexport function formatJSON(value: unknown): string {\n // util.inspect() results in much more readable output than JSON.stringify()\n return inspect(value, { depth: 100 });\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel, LogLevelString } from '@firebase/logger';\n\nimport { SDK_VERSION } from '../core/version';\nimport { formatJSON } from '../platform/format_json';\n\nexport { LogLevel, LogLevelString };\n\nconst logClient = new Logger('@firebase/firestore');\n\n// Helper methods are needed because variables can't be exported as read/write\nexport function getLogLevel(): LogLevel {\n return logClient.logLevel;\n}\n\n/**\n * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).\n *\n * @param logLevel - The verbosity you set for activity and error logging. Can\n * be any of the following values:\n *\n *
    \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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 *\n * @param code generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(\n code: number,\n message: string,\n context?: Record\n): never;\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 *\n * @param id generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(id: number, context?: Record): never;\n\nexport function fail(\n id: number,\n messageOrContext?: string | Record,\n context?: Record\n): never {\n let message = 'Unexpected state';\n if (typeof messageOrContext === 'string') {\n message = messageOrContext;\n } else {\n context = messageOrContext;\n }\n _fail(id, message, context);\n}\n\nfunction _fail(\n id: number,\n failure: string,\n context?: Record\n): never {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n let message = `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ${failure} (ID: ${id.toString(\n 16\n )})`;\n if (context !== undefined) {\n try {\n const stringContext = JSON.stringify(context);\n message += ' CONTEXT: ' + stringContext;\n } catch (e) {\n message += ' CONTEXT: ' + context;\n }\n }\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 *\n * @param id generate a new unique value with `yarn assertion-idgenerate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n assertion: boolean,\n id: number,\n message: string,\n context?: Record\n): asserts assertion;\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 *\n * @param id generate a new unique value with `yarn assertion-id:generate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n assertion: boolean,\n id: number,\n context?: Record\n): asserts assertion;\n\nexport function hardAssert(\n assertion: boolean,\n id: number,\n messageOrContext?: string | Record,\n context?: Record\n): asserts assertion {\n let message = 'Unexpected state';\n if (typeof messageOrContext === 'string') {\n message = messageOrContext;\n } else {\n context = messageOrContext;\n }\n\n if (!assertion) {\n _fail(id, message, context);\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(0xdeb6, 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 { FirebaseApp, _isFirebaseServerApp } from '@firebase/app';\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 0xa539,\n 'Invalid tokenData returned from getToken()',\n { 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 0xa540,\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 0x7c5d,\n 'Invalid tokenData returned from getToken()',\n { 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 0x0807,\n 'Received invalid UID',\n { 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 private serverAppAppCheckToken: string | null = null;\n\n constructor(\n app: FirebaseApp,\n private appCheckProvider: Provider\n ) {\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n }\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n hardAssert(\n this.tokenListener === undefined,\n 0x0db8,\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 if (this.serverAppAppCheckToken) {\n return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n }\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 0xae0e,\n 'Invalid tokenResult returned from getToken()',\n { 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 private serverAppAppCheckToken: string | null = null;\n\n constructor(\n app: FirebaseApp,\n private appCheckProvider: Provider\n ) {\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n appCheckProvider.onInit(appCheck => {\n this.appCheck = appCheck;\n });\n }\n\n getToken(): Promise {\n if (this.serverAppAppCheckToken) {\n return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n }\n\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 0x0d8e,\n 'Invalid tokenResult returned from getToken()',\n { 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","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 readonly isUsingEmulator: 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 { randomBytes as generateRandomBytes } from 'crypto';\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 return generateRandomBytes(nBytes);\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\n/** Compare strings in UTF-8 encoded byte order */\nexport function compareUtf8Strings(left: string, right: string): number {\n // Find the first differing character (a.k.a. \"UTF-16 code unit\") in the two strings and,\n // if found, use that character to determine the relative ordering of the two strings as a\n // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by\n // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8\n // and UTF-16 happen to represent Unicode code points.\n //\n // After finding the first pair of differing characters, there are two cases:\n //\n // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or\n // both are surrogates from a surrogate pair (that collectively represent code points greater\n // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the\n // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is\n // sufficient.\n //\n // Case 2: One character is a surrogate and the other is not. In this case the surrogate-\n // containing string is always ordered after the non-surrogate. This is because surrogates are\n // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations\n // and are lexicographically greater than the 1, 2, or 3-byte representations of code points\n // less than or equal to 0xFFFF.\n //\n // An example of why Case 2 is required is comparing the following two Unicode code points:\n //\n // |-----------------------|------------|---------------------|-----------------|\n // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding |\n // |-----------------------|------------|---------------------|-----------------|\n // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD |\n // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 |\n // |-----------------------|------------|---------------------|-----------------|\n //\n // A lexicographical comparison of the UTF-8 encodings of these code points would order\n // \"Replacement Character\" _before_ \"Grinning Face\" because 0xEF is less than 0xF0. However, a\n // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously\n // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out,\n // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate\n // pair with those that do not.\n const length = Math.min(left.length, right.length);\n for (let i = 0; i < length; i++) {\n const leftChar = left.charAt(i);\n const rightChar = right.charAt(i);\n if (leftChar !== rightChar) {\n return isSurrogate(leftChar) === isSurrogate(rightChar)\n ? primitiveComparator(leftChar, rightChar)\n : isSurrogate(leftChar)\n ? 1\n : -1;\n }\n }\n\n // Use the lengths of the strings to determine the overall comparison result since either the\n // strings were equal or one is a prefix of the other.\n return primitiveComparator(left.length, right.length);\n}\n\nconst MIN_SURROGATE = 0xd800;\nconst MAX_SURROGATE = 0xdfff;\n\nexport function isSurrogate(s: string): boolean {\n debugAssert(s.length === 1, `s.length == ${s.length}, but expected 1`);\n const c = s.charCodeAt(0);\n return c >= MIN_SURROGATE && c <= MAX_SURROGATE;\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 { Integer } from '@firebase/webchannel-wrapper/bloom-blob';\n\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { compareUtf8Strings, primitiveComparator } from '../util/misc';\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(0x027d, 'offset out of range', {\n offset,\n range: segments.length\n });\n }\n\n if (length === undefined) {\n length = segments.length - offset;\n } else if (length > segments.length - offset) {\n fail(0x06d2, 'length out of range', {\n length,\n range: segments.length - offset\n });\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 /**\n * Compare 2 paths segment by segment, prioritizing numeric IDs\n * (e.g., \"__id123__\") in numeric ascending order, followed by string\n * segments in lexicographical order.\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 comparison = BasePath.compareSegments(p1.get(i), p2.get(i));\n if (comparison !== 0) {\n return comparison;\n }\n }\n return primitiveComparator(p1.length, p2.length);\n }\n\n private static compareSegments(lhs: string, rhs: string): number {\n const isLhsNumeric = BasePath.isNumericId(lhs);\n const isRhsNumeric = BasePath.isNumericId(rhs);\n\n if (isLhsNumeric && !isRhsNumeric) {\n // Only lhs is numeric\n return -1;\n } else if (!isLhsNumeric && isRhsNumeric) {\n // Only rhs is numeric\n return 1;\n } else if (isLhsNumeric && isRhsNumeric) {\n // both numeric\n return BasePath.extractNumericId(lhs).compare(\n BasePath.extractNumericId(rhs)\n );\n } else {\n // both non-numeric\n return compareUtf8Strings(lhs, rhs);\n }\n }\n\n // Checks if a segment is a numeric ID (starts with \"__id\" and ends with \"__\").\n private static isNumericId(segment: string): boolean {\n return segment.startsWith('__id') && segment.endsWith('__');\n }\n\n private static extractNumericId(segment: string): Integer {\n return Integer.fromString(segment.substring(4, segment.length - 2));\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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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(0x3029, 'Unknown wrong type', { 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 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 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 { isCloudWorkstation } from '@firebase/util';\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 const { host } = new URL(url);\n const forwardCredentials = isCloudWorkstation(host);\n return this.performRPCRequest(\n rpcName,\n url,\n headers,\n req,\n forwardCredentials\n ).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 _forwardCredentials: boolean\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 { 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(0xfdaa, '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(0x3c6b, '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(0x999b, '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(0x3019, '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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Token } from '../../api/credentials';\nimport { Stream } from '../../remote/connection';\nimport { RestConnection } from '../../remote/rest_connection';\nimport { mapCodeFromHttpStatus } from '../../remote/rpc_error';\nimport { FirestoreError } from '../../util/error';\nimport { StringMap } from '../../util/types';\n\n/**\n * A Rest-based connection that relies on the native HTTP stack\n * (e.g. `fetch` or a polyfill).\n */\nexport class FetchConnection extends RestConnection {\n openStream(\n rpcName: string,\n token: Token | null\n ): Stream {\n throw new Error('Not supported by FetchConnection');\n }\n\n protected async performRPCRequest(\n rpcName: string,\n url: string,\n headers: StringMap,\n body: Req,\n forwardCredentials: boolean\n ): Promise {\n const requestJson = JSON.stringify(body);\n let response: Response;\n\n try {\n const fetchArgs: RequestInit = {\n method: 'POST',\n headers,\n body: requestJson\n };\n if (forwardCredentials) {\n fetchArgs.credentials = 'include';\n }\n response = await fetch(url, fetchArgs);\n } catch (e) {\n const err = e as { status: number | undefined; statusText: string };\n throw new FirestoreError(\n mapCodeFromHttpStatus(err.status),\n 'Request failed with error: ' + err.statusText\n );\n }\n\n if (!response.ok) {\n let errorResponse = await response.json();\n if (Array.isArray(errorResponse)) {\n errorResponse = errorResponse[0];\n }\n const errorMessage = errorResponse?.error?.message;\n throw new FirestoreError(\n mapCodeFromHttpStatus(response.status),\n `Request failed with error: ${errorMessage ?? response.statusText}`\n );\n }\n\n return response.json();\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 { FetchConnection } from '../browser_lite/fetch_connection';\n\nexport { newConnectivityMonitor } from '../browser/connection';\n\n/** Initializes the HTTP connection for the REST API. */\nexport function newConnection(databaseInfo: DatabaseInfo): Connection {\n return new FetchConnection(databaseInfo);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from './assert';\n\nexport interface Dict {\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\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Converts a Base64 encoded string to a binary string. */\n\nexport function decodeBase64(encoded: string): string {\n // Note: We used to validate the base64 string here via a regular expression.\n // This was removed to improve the performance of indexing.\n return Buffer.from(encoded, 'base64').toString('binary');\n}\n\n/** Converts a binary string to a Base64 encoded string. */\nexport function encodeBase64(raw: string): string {\n return Buffer.from(raw, 'binary').toString('base64');\n}\n\n/** True if and only if the Base64 conversion functions are available. */\nexport function isBase64Available(): boolean {\n return true;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 { 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, 0x986a, '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, 0xb5de, 'invalid timestamp', {\n timestamp: date\n });\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 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isPlainObject } from '../util/input_validation';\n\nimport { Code, FirestoreError } from './error';\n\n/**\n * A list of data types Firestore objects may serialize in their toJSON implemenetations.\n * @private\n * @internal\n */\nexport type JsonTypeDesc =\n | 'object'\n | 'string'\n | 'number'\n | 'boolean'\n | 'null'\n | 'undefined';\n\n/**\n * An association of JsonTypeDesc values to their native types.\n * @private\n * @internal\n */\nexport type TSType = T extends 'object'\n ? object\n : T extends 'string'\n ? string\n : T extends 'number'\n ? number\n : T extends 'boolean'\n ? boolean\n : T extends 'null'\n ? null\n : T extends 'undefined'\n ? undefined\n : never;\n\n/**\n * The representation of a JSON object property name and its type value.\n * @private\n * @internal\n */\nexport interface Property {\n value?: TSType;\n typeString: JsonTypeDesc;\n}\n\n/**\n * A type Firestore data types may use to define the fields used in their JSON serialization.\n * @private\n * @internal\n */\nexport interface JsonSchema {\n [key: string]: Property;\n}\n\n/**\n * Associates the JSON property type to the native type and sets them to be Required.\n * @private\n * @internal\n */\nexport type Json = {\n [K in keyof T]: Required['value'];\n};\n\n/**\n * Helper function to define a JSON schema {@link Property}.\n * @private\n * @internal\n */\nexport function property(\n typeString: T,\n optionalValue?: TSType\n): Property {\n const result: Property = {\n typeString\n };\n if (optionalValue) {\n result.value = optionalValue;\n }\n return result;\n}\n\n/**\n * Validates the JSON object based on the provided schema, and narrows the type to the provided\n * JSON schema.\n * @private\n * @internal\n *\n * @param json A JSON object to validate.\n * @param scheme a {@link JsonSchema} that defines the properties to validate.\n * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise.\n */\nexport function validateJSON(\n json: object,\n schema: S\n): json is Json {\n if (!isPlainObject(json)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'JSON must be an object');\n }\n let error: string | undefined = undefined;\n for (const key in schema) {\n if (schema[key]) {\n const typeString = schema[key].typeString;\n const value: { value: unknown } | undefined =\n 'value' in schema[key] ? { value: schema[key].value } : undefined;\n if (!(key in json)) {\n error = `JSON missing required field: '${key}'`;\n break;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const fieldValue = (json as any)[key];\n if (typeString && typeof fieldValue !== typeString) {\n error = `JSON field '${key}' must be a ${typeString}.`;\n break;\n } else if (value !== undefined && fieldValue !== value.value) {\n error = `Expected '${key}' field to equal '${value.value}'`;\n break;\n }\n }\n }\n if (error) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, error);\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 { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\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 static _jsonSchemaVersion: string = 'firestore/timestamp/1.0';\n static _jsonSchema = {\n type: property('string', Timestamp._jsonSchemaVersion),\n seconds: property('number'),\n nanoseconds: property('number')\n };\n\n /**\n * Returns a JSON-serializable representation of this `Timestamp`.\n */\n toJSON(): { seconds: number; nanoseconds: number; type: string } {\n return {\n type: Timestamp._jsonSchemaVersion,\n seconds: this.seconds,\n nanoseconds: this.nanoseconds\n };\n }\n\n /**\n * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}.\n */\n static fromJSON(json: object): Timestamp {\n if (validateJSON(json, Timestamp._jsonSchema)) {\n return new Timestamp(json.seconds, json.nanoseconds);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Timestamp from JSON.'\n );\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 {\n arrayEquals,\n compareUtf8Strings,\n primitiveComparator\n} 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(0x6e87, 'Invalid value type', { 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(0xcbf8, 'Unexpected value type', { 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 compareUtf8Strings(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(0x5ae0, '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 = compareUtf8Strings(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(0xee4d, 'Invalid value type', { 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(0x34ae, 'Invalid value type', { 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(0x8c66, 'Invalid value type', { 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(0xf207, 'Invalid value type', { 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 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 { 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 other.nullValue === undefined &&\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(0xb8a2, 'Unknown FieldFilter operator', {\n operator: this.op\n });\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(0x4bef, '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 (\n other !== null &&\n other.nullValue === undefined &&\n !arrayValueContains(this.value.arrayValue!, other)\n );\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 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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 './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(0xaad2, 'Red node has red child', {\n key: this.key,\n value: this.value\n });\n }\n if (this.right.isRed()) {\n throw fail(0x3721, 'Right child of (`key`, `value`) is red', {\n key: this.key,\n value: this.value\n });\n }\n const blackDepth = (this.left as LLRBNode).check();\n if (blackDepth !== (this.right as LLRBNode).check()) {\n throw fail(0x6d2d, '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(0xe1a6, 'LLRBEmptyNode has no key.');\n }\n get value(): never {\n throw fail(0x3f0d, 'LLRBEmptyNode has no value.');\n }\n get color(): never {\n throw fail(0x4157, 'LLRBEmptyNode has no color.');\n }\n get left(): never {\n throw fail(0x741e, 'LLRBEmptyNode has no left child.');\n }\n get right(): never {\n throw fail(0x901e, '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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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(\n 0xa786,\n \"Trying to compare documents on fields that don't exist\"\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(0x4d4e, 'Unknown direction', { direction: orderBy.dir });\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 { 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 0x7f90,\n 'server transform result count should match field transform count',\n {\n serverTransformResultCount: serverTransformResults.length,\n fieldTransformCount: fieldTransforms.length\n }\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 { 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\n/**\n * Returns a Timestamp typed object given protobuf timestamp value.\n */\nexport function 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 0xe30b,\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 0x3f41,\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, 0xc050, \"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 0x27ce,\n 'Tried to deserialize invalid key',\n { 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 0x71a3,\n 'tried to deserialize invalid key',\n { 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 0xaa33,\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 0x0f36,\n 'Tried to deserialize a missing document from a found document.'\n );\n hardAssert(\n !!result.readTime,\n 0x5995,\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(0x1c42, 'invalid batch get response', { 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(0x2d51, 'Unknown change type', { 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(0x9991, '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(0x40d7, 'Unknown mutation type', {\n mutationType: mutation.type\n });\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(0x05b7, 'unknown mutation proto', { 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(0x6b69, '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 0x3811,\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(0x51c2, 'Unknown transform', {\n transform: fieldTransform.transform\n });\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 0x40f6,\n 'Unknown server value transform proto',\n { 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(0x40c8, 'Unknown transform proto', { 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 0x07ae,\n 'DocumentsTarget contained other than 1 document',\n {\n count\n }\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 0xfe26,\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(0x713b, '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(0x7591, 'Unknown filter', { 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(0xe2fe, 'Unspecified operator');\n default:\n return fail(0xc54a, '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(0x0402, '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(0xd65d, 'Unrecognized filter type', { 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(0xef81, 'Unspecified filter');\n default:\n return fail(0xed36, '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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 } 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, 0xd7c2, 'Missing entity in write response for `key`', {\n key\n });\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 0xfcd7,\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 settings.isUsingEmulator\n );\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequenceNumber, 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 { getGlobal, 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 `indexedDB` are guarded by SimpleDb.isAvailable() and getGlobal()\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 lastClosedDbVersion: number | null = null;\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 const globals = getGlobal();\n return wrapRequest(\n globals.indexedDB.deleteDatabase(name)\n ).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\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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\nimport { EmulatorMockTokenOptions } from '@firebase/util';\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 emulatorOptions?: { mockUserToken?: EmulatorMockTokenOptions | string };\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 readonly isUsingEmulator: boolean;\n\n // Can be a google-auth-library or gapi client.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n credentials?: any;\n\n constructor(settings: PrivateSettings) {\n if (settings.host === undefined) {\n if (settings.ssl !== undefined) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't provide ssl option if host option is not set\"\n );\n }\n this.host = DEFAULT_HOST;\n this.ssl = DEFAULT_SSL;\n } else {\n this.host = settings.host;\n this.ssl = settings.ssl ?? DEFAULT_SSL;\n }\n this.isUsingEmulator = settings.emulatorOptions !== undefined;\n\n this.credentials = settings.credentials;\n this.ignoreUndefinedProperties = !!settings.ignoreUndefinedProperties;\n this.localCache = settings.localCache;\n\n if (settings.cacheSizeBytes === undefined) {\n this.cacheSizeBytes = LRU_DEFAULT_CACHE_SIZE_BYTES;\n } else {\n if (\n settings.cacheSizeBytes !== LRU_COLLECTION_DISABLED &&\n settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`\n );\n } else {\n this.cacheSizeBytes = settings.cacheSizeBytes;\n }\n }\n\n validateIsNotUsedTogether(\n 'experimentalForceLongPolling',\n settings.experimentalForceLongPolling,\n 'experimentalAutoDetectLongPolling',\n settings.experimentalAutoDetectLongPolling\n );\n\n this.experimentalForceLongPolling = !!settings.experimentalForceLongPolling;\n\n if (this.experimentalForceLongPolling) {\n this.experimentalAutoDetectLongPolling = false;\n } else if (settings.experimentalAutoDetectLongPolling === undefined) {\n this.experimentalAutoDetectLongPolling = DEFAULT_AUTO_DETECT_LONG_POLLING;\n } else {\n // For backwards compatibility, coerce the value to boolean even though\n // the TypeScript compiler has narrowed the type to boolean already.\n // noinspection PointlessBooleanExpressionJS\n this.experimentalAutoDetectLongPolling =\n !!settings.experimentalAutoDetectLongPolling;\n }\n\n this.experimentalLongPollingOptions = cloneLongPollingOptions(\n settings.experimentalLongPollingOptions ?? {}\n );\n validateLongPollingOptions(this.experimentalLongPollingOptions);\n\n this.useFetchStreams = !!settings.useFetchStreams;\n }\n\n isEqual(other: FirestoreSettingsImpl): boolean {\n return (\n this.host === other.host &&\n this.ssl === other.ssl &&\n this.credentials === other.credentials &&\n this.cacheSizeBytes === other.cacheSizeBytes &&\n this.experimentalForceLongPolling ===\n other.experimentalForceLongPolling &&\n this.experimentalAutoDetectLongPolling ===\n other.experimentalAutoDetectLongPolling &&\n longPollingOptionsEqual(\n this.experimentalLongPollingOptions,\n other.experimentalLongPollingOptions\n ) &&\n this.ignoreUndefinedProperties === other.ignoreUndefinedProperties &&\n this.useFetchStreams === other.useFetchStreams\n );\n }\n}\n\nfunction validateLongPollingOptions(\n options: ExperimentalLongPollingOptions\n): void {\n if (options.timeoutSeconds !== undefined) {\n if (isNaN(options.timeoutSeconds)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ` +\n `${options.timeoutSeconds} (must not be NaN)`\n );\n }\n if (options.timeoutSeconds < MIN_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(minimum allowed value is ${MIN_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n if (options.timeoutSeconds > MAX_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(maximum allowed value is ${MAX_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _getProvider,\n _removeServiceInstance,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport {\n createMockUserToken,\n deepEqual,\n EmulatorMockTokenOptions,\n getDefaultEmulatorHostnameAndPort,\n isCloudWorkstation,\n pingServer,\n updateEmulatorBanner\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 private _emulatorOptions: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {};\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 this._emulatorOptions = settings.emulatorOptions || {};\n\n if (settings.credentials !== undefined) {\n this._authCredentials = makeAuthCredentialsProvider(settings.credentials);\n }\n }\n\n _getSettings(): FirestoreSettingsImpl {\n return this._settings;\n }\n\n _getEmulatorOptions(): { mockUserToken?: EmulatorMockTokenOptions | string } {\n return this._emulatorOptions;\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 useSsl = isCloudWorkstation(host);\n const settings = firestore._getSettings();\n const existingConfig = {\n ...settings,\n emulatorOptions: firestore._getEmulatorOptions()\n };\n const newHostSetting = `${host}:${port}`;\n if (useSsl) {\n void pingServer(`https://${newHostSetting}`);\n updateEmulatorBanner('Firestore', true);\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 const newConfig = {\n ...settings,\n host: newHostSetting,\n ssl: useSsl,\n emulatorOptions: options\n };\n // No-op if the new configuration matches the current configuration. This supports SSR\n // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice.\n if (deepEqual(newConfig, existingConfig)) {\n return;\n }\n\n firestore._setSettings(newConfig);\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 {\n _registerComponent,\n registerVersion,\n SDK_VERSION\n} from '@firebase/app';\nimport { Component, ComponentType } from '@firebase/component';\n\nimport { version } from '../package.json';\nimport {\n LiteAppCheckTokenProvider,\n LiteAuthCredentialsProvider\n} from '../src/api/credentials';\nimport { databaseIdFromApp } from '../src/core/database_info';\nimport { setSDKVersion } from '../src/core/version';\nimport { Firestore } from '../src/lite-api/database';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore/lite': Firestore;\n }\n}\n\nexport function registerFirestore(): void {\n setSDKVersion(`${SDK_VERSION}_lite`);\n _registerComponent(\n new Component(\n 'firestore/lite',\n (container, { instanceIdentifier: databaseId, options: settings }) => {\n const app = container.getProvider('app').getImmediate()!;\n const firestoreInstance = new Firestore(\n new LiteAuthCredentialsProvider(\n container.getProvider('auth-internal')\n ),\n new LiteAppCheckTokenProvider(\n app,\n container.getProvider('app-check-internal')\n ),\n databaseIdFromApp(app, databaseId),\n app\n );\n if (settings) {\n firestoreInstance._setSettings(settings);\n }\n return firestoreInstance;\n },\n 'PUBLIC' as ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n // RUNTIME_ENV and BUILD_TARGET are replaced by real values during the compilation\n registerVersion('firestore-lite', version, '__RUNTIME_ENV__');\n registerVersion('firestore-lite', version, '__BUILD_TARGET__');\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 { FieldPath } from '../model/path';\n\n/**\n * Union type representing the aggregate type to be performed.\n */\nexport type AggregateType = 'count' | 'avg' | 'sum';\n\n/**\n * Represents an Aggregate to be performed over a query result set.\n */\nexport interface Aggregate {\n readonly fieldPath?: FieldPath;\n readonly alias: string;\n readonly aggregateType: AggregateType;\n}\n\n/**\n * Concrete implementation of the Aggregate type.\n */\nexport class AggregateImpl implements Aggregate {\n constructor(\n readonly alias: string,\n readonly aggregateType: AggregateType,\n readonly fieldPath?: FieldPath\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 { AggregateType } from '../core/aggregate';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\n\nimport { average, count, sum } from './aggregate';\nimport { DocumentData, Query } from './reference';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\nexport { AggregateType };\n\n/**\n * Represents an aggregation that can be performed by Firestore.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport class AggregateField {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateField';\n\n /** Indicates the aggregation operation of this AggregateField. */\n readonly aggregateType: AggregateType;\n\n /**\n * Create a new AggregateField\n * @param aggregateType Specifies the type of aggregation operation to perform.\n * @param _internalFieldPath Optionally specifies the field that is aggregated.\n * @internal\n */\n constructor(\n aggregateType: AggregateType = 'count',\n readonly _internalFieldPath?: InternalFieldPath\n ) {\n this.aggregateType = aggregateType;\n }\n}\n\n/**\n * The union of all `AggregateField` types that are supported by Firestore.\n */\nexport type AggregateFieldType =\n | ReturnType\n | ReturnType\n | ReturnType;\n\n/**\n * Specifies a set of aggregations and their aliases.\n */\nexport interface AggregateSpec {\n [field: string]: AggregateFieldType;\n}\n\n/**\n * A type whose keys are taken from an `AggregateSpec`, and whose values are the\n * result of the aggregation performed by the corresponding `AggregateField`\n * from the input `AggregateSpec`.\n */\nexport type AggregateSpecData = {\n [P in keyof T]: T[P] extends AggregateField ? U : never;\n};\n\n/**\n * The results of executing an aggregation query.\n */\nexport class AggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateQuerySnapshot';\n\n /**\n * The underlying query over which the aggregations recorded in this\n * `AggregateQuerySnapshot` were performed.\n */\n readonly query: Query;\n\n /** @hideconstructor */\n constructor(\n query: Query,\n private readonly _userDataWriter: AbstractUserDataWriter,\n private readonly _data: ApiClientObjectMap\n ) {\n this.query = query;\n }\n\n /**\n * Returns the results of the aggregations performed over the underlying\n * query.\n *\n * The keys of the returned object will be the same as those of the\n * `AggregateSpec` object specified to the aggregation method, and the values\n * will be the corresponding aggregation result.\n *\n * @returns The results of the aggregations performed over the underlying\n * query.\n */\n data(): AggregateSpecData {\n return this._userDataWriter.convertObjectMap(\n this._data\n ) as AggregateSpecData;\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 {\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';\n// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_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 static _jsonSchemaVersion: string = 'firestore/documentReference/1.0';\n static _jsonSchema = {\n type: property('string', DocumentReference._jsonSchemaVersion),\n referencePath: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `DocumentReference` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: DocumentReference._jsonSchemaVersion,\n referencePath: this._key.toString()\n };\n }\n\n /**\n * Builds a `DocumentReference` instance from a JSON object created by\n * {@link DocumentReference.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json a JSON object represention of a `DocumentReference` instance\n * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(firestore: Firestore, json: object): DocumentReference;\n /**\n * Builds a `DocumentReference` instance from a JSON object created by\n * {@link DocumentReference.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json a JSON object represention of a `DocumentReference` instance\n * @param converter - Converts objects to and from Firestore.\n * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON<\n NewAppModelType = DocumentData,\n NewDbModelType extends DocumentData = DocumentData\n >(\n firestore: Firestore,\n json: object,\n converter: FirestoreDataConverter\n ): DocumentReference;\n static fromJSON<\n NewAppModelType = DocumentData,\n NewDbModelType extends DocumentData = DocumentData\n >(\n firestore: Firestore,\n json: object,\n converter?: FirestoreDataConverter\n ): DocumentReference {\n if (validateJSON(json, DocumentReference._jsonSchema)) {\n return new DocumentReference(\n firestore,\n converter ? converter : null,\n new DocumentKey(ResourcePath.fromString(json.referencePath))\n );\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Bytes from JSON.'\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 { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\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 static _jsonSchemaVersion: string = 'firestore/bytes/1.0';\n static _jsonSchema = {\n type: property('string', Bytes._jsonSchemaVersion),\n bytes: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `Bytes` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: Bytes._jsonSchemaVersion,\n bytes: this.toBase64()\n };\n }\n\n /**\n * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}.\n *\n * @param json a JSON object represention of a `Bytes` instance\n * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): Bytes {\n if (validateJSON(json, Bytes._jsonSchema)) {\n return Bytes.fromBase64String(json.bytes);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Bytes from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n 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';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\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 /**\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 static _jsonSchemaVersion: string = 'firestore/geoPoint/1.0';\n static _jsonSchema = {\n type: property('string', GeoPoint._jsonSchemaVersion),\n latitude: property('number'),\n longitude: property('number')\n };\n\n /**\n * Returns a JSON-serializable representation of this `GeoPoint` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): { latitude: number; longitude: number; type: string } {\n return {\n latitude: this._lat,\n longitude: this._long,\n type: GeoPoint._jsonSchemaVersion\n };\n }\n\n /**\n * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}.\n *\n * @param json a JSON object represention of a `GeoPoint` instance\n * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): GeoPoint {\n if (validateJSON(json, GeoPoint._jsonSchema)) {\n return new GeoPoint(json.latitude, json.longitude);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating GeoPoint from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Returns 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 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';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\n\n/**\n * Represents a vector type in Firestore documents.\n * Create an instance with {@link 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` values have the same raw number arrays, returns `false` otherwise.\n */\n isEqual(other: VectorValue): boolean {\n return isPrimitiveArrayEqual(this._values, other._values);\n }\n\n static _jsonSchemaVersion: string = 'firestore/vectorValue/1.0';\n static _jsonSchema = {\n type: property('string', VectorValue._jsonSchemaVersion),\n vectorValues: property('object')\n };\n\n /**\n * Returns a JSON-serializable representation of this `VectorValue` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: VectorValue._jsonSchemaVersion,\n vectorValues: this._values\n };\n }\n\n /**\n * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}.\n *\n * @param json a JSON object represention of a `VectorValue` instance.\n * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): VectorValue {\n if (validateJSON(json, VectorValue._jsonSchema)) {\n if (\n Array.isArray(json.vectorValues) &&\n json.vectorValues.every(element => typeof element === 'number')\n ) {\n return new VectorValue(json.vectorValues);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Expected 'vectorValues' field to be a number array\"\n );\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Timestamp from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData,\n FieldPath as PublicFieldPath,\n SetOptions\n} from '@firebase/firestore-types';\nimport { Compat, deepEqual, getModularInstance } from '@firebase/util';\n\nimport { ParseContext } from '../api/parse_context';\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n FieldTransform,\n Mutation,\n PatchMutation,\n Precondition,\n SetMutation\n} from '../model/mutation';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform\n} from '../model/transform_operation';\nimport {\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(0x9c4b, 'Unexpected case for UserDataSource', {\n dataSource\n });\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\nexport function 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(0xf2a2, 'Invalid value type', {\n value\n });\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 0x25d8,\n 'ReferenceValue is not valid',\n { name }\n );\n const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3));\n const key = new DocumentKey(resourcePath.popFirst(5));\n\n if (!databaseId.isEqual(expectedDatabaseId)) {\n // TODO(b/64130202): Somehow support foreign references.\n logError(\n `Document ${key} contains a document ` +\n `reference within a different database (` +\n `${databaseId.projectId}/${databaseId.database}) which is not ` +\n `supported. It will be treated as a reference in the current ` +\n `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` +\n `instead.`\n );\n }\n return key;\n }\n\n protected abstract convertReference(name: string): unknown;\n\n protected abstract convertBytes(bytes: ByteString): unknown;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData as PublicDocumentData,\n SetOptions as PublicSetOptions\n} from '@firebase/firestore-types';\nimport { getModularInstance } from '@firebase/util';\n\nimport { LimitType } from '../core/query';\nimport { DeleteMutation, Precondition } from '../model/mutation';\nimport {\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc,\n invokeRunQueryRpc\n} from '../remote/datastore';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { cast } from '../util/input_validation';\n\nimport { Bytes } from './bytes';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { validateHasExplicitOrderByForLimitToLast } from './query';\nimport {\n CollectionReference,\n doc,\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot\n} from './snapshot';\nimport {\n newUserDataReader,\n ParsedUpdateData,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converts custom model object of type T into `DocumentData` by applying the\n * converter if it exists.\n *\n * This function is used when converting user objects to `DocumentData`\n * because we want to provide the user with a more specific error message if\n * their `set()` or fails due to invalid data originating from a `toFirestore()`\n * call.\n */\nexport function applyFirestoreDataConverter(\n converter: UntypedFirestoreDataConverter | null,\n value: WithFieldValue | PartialWithFieldValue,\n options?: PublicSetOptions\n): PublicDocumentData {\n let convertedValue;\n if (converter) {\n if (options && (options.merge || options.mergeFields)) {\n // Cast to `any` in order to satisfy the union type constraint on\n // toFirestore().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n convertedValue = (converter as any).toFirestore(value, options);\n } else {\n convertedValue = converter.toFirestore(value as WithFieldValue);\n }\n } else {\n convertedValue = value as PublicDocumentData;\n }\n return convertedValue;\n}\n\nexport class LiteUserDataWriter extends AbstractUserDataWriter {\n constructor(protected firestore: Firestore) {\n super();\n }\n\n protected convertBytes(bytes: ByteString): Bytes {\n return new Bytes(bytes);\n }\n\n protected convertReference(name: string): DocumentReference {\n const key = this.convertDocumentKey(name, this.firestore._databaseId);\n return new DocumentReference(this.firestore, /* converter= */ null, key);\n }\n}\n\n/**\n * Reads the document referred to by the specified document reference.\n *\n * All documents are directly fetched from the server, even if the document was\n * previously read or modified. Recent modifications are only reflected in the\n * retrieved `DocumentSnapshot` if they have already been applied by the\n * backend. If the client is offline, the read fails. If you like to use\n * caching or see local modifications, please use the full Firestore SDK.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the current\n * document contents.\n */\nexport function getDoc(\n reference: DocumentReference\n): Promise> {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n const userDataWriter = new LiteUserDataWriter(reference.firestore);\n\n return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then(\n result => {\n hardAssert(\n result.length === 1,\n 0x3d02,\n 'Expected a single document result'\n );\n const document = result[0];\n return new DocumentSnapshot(\n reference.firestore,\n userDataWriter,\n reference._key,\n document.isFoundDocument() ? document : null,\n reference.converter\n );\n }\n );\n}\n\n/**\n * Executes the query and returns the results as a {@link QuerySnapshot}.\n *\n * All queries are executed directly by the server, even if the query was\n * previously executed. Recent modifications are only reflected in the retrieved\n * results if they have already been applied by the backend. If the client is\n * offline, the operation fails. To see previously cached result and local\n * modifications, use the full Firestore SDK.\n *\n * @param query - The `Query` to execute.\n * @returns A Promise that will be resolved with the results of the query.\n */\nexport function getDocs(\n query: Query\n): Promise> {\n query = cast>(query, Query);\n validateHasExplicitOrderByForLimitToLast(query._query);\n\n const datastore = getDatastore(query.firestore);\n const userDataWriter = new LiteUserDataWriter(query.firestore);\n return invokeRunQueryRpc(datastore, query._query).then(result => {\n const docs = result.map(\n doc =>\n new QueryDocumentSnapshot(\n query.firestore,\n userDataWriter,\n doc.key,\n doc,\n query.converter\n )\n );\n\n if (query._query.limitType === LimitType.Last) {\n // Limit to last queries reverse the orderBy constraint that was\n // specified by the user. As such, we need to reverse the order of the\n // results to return the documents in the expected order.\n docs.reverse();\n }\n\n return new QuerySnapshot(query, docs);\n });\n}\n\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\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 * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\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 convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data,\n options\n );\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'setDoc',\n reference._key,\n convertedValue,\n reference.converter !== null,\n options\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference`. The update will fail if applied to a document that does\n * not exist.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\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 * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\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 dataReader = newUserDataReader(reference.firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed: ParsedUpdateData;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData\n );\n }\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.exists(true))\n ]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * The deletion will only be reflected in document reads that occur after the\n * returned promise resolves. If the client is offline, the\n * delete fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to delete.\n * @returns A `Promise` resolved once the document has been successfully\n * deleted from the backend.\n */\nexport function deleteDoc(\n reference: DocumentReference\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n new DeleteMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend.\n */\nexport function addDoc(\n reference: CollectionReference,\n data: WithFieldValue\n): Promise> {\n reference = cast>(\n reference,\n CollectionReference\n );\n const docRef = doc(reference);\n\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data as PartialWithFieldValue\n );\n\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'addDoc',\n docRef._key,\n convertedValue,\n docRef.converter !== null,\n {}\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(docRef._key, Precondition.exists(false))\n ]).then(() => docRef);\n}\n","/**\n * @license\n * Copyright 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 { deepEqual } from '@firebase/util';\n\nimport { AggregateImpl } from '../core/aggregate';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { invokeRunAggregationQueryRpc } from '../remote/datastore';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport {\n AggregateField,\n AggregateQuerySnapshot,\n AggregateSpec\n} from './aggregate_types';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { DocumentData, Query, queryEqual } from './reference';\nimport { LiteUserDataWriter } from './reference_impl';\nimport { fieldPathFromArgument } from './user_data_reader';\n\n/**\n * Calculates the number of documents in the result set of the given query\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can\n * count the documents in cases where the result set is prohibitively large to\n * download entirely (thousands of documents).\n *\n * @param query The query whose result set size is calculated.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */\nexport function getCount(\n query: Query\n): Promise<\n AggregateQuerySnapshot<\n { count: AggregateField },\n AppModelType,\n DbModelType\n >\n> {\n const countQuerySpec: { count: AggregateField } = {\n count: count()\n };\n\n return getAggregate(query, countQuerySpec);\n}\n\n/**\n * Calculates the specified aggregations over the documents in the result\n * set of the given query without actually downloading the documents.\n *\n * Using this function to perform aggregations is efficient because only the\n * final aggregation values, not the documents' data, are downloaded. This\n * function can perform aggregations of the documents in cases where the result\n * set is prohibitively large to download entirely (thousands of documents).\n *\n * @param query The query whose result set is aggregated over.\n * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates\n * to perform over the result set. The AggregateSpec specifies aliases for each\n * aggregate, which can be used to retrieve the aggregate result.\n * @example\n * ```typescript\n * const aggregateSnapshot = await getAggregate(query, {\n * countOfDocs: count(),\n * totalHours: sum('hours'),\n * averageScore: average('score')\n * });\n *\n * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;\n * const totalHours: number = aggregateSnapshot.data().totalHours;\n * const averageScore: number | null = aggregateSnapshot.data().averageScore;\n * ```\n */\nexport function getAggregate<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n aggregateSpec: AggregateSpecType\n): Promise<\n AggregateQuerySnapshot\n> {\n const firestore = cast(query.firestore, Firestore);\n const datastore = getDatastore(firestore);\n\n const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n\n // Run the aggregation and convert the results\n return invokeRunAggregationQueryRpc(\n datastore,\n query._query,\n internalAggregates\n ).then(aggregateResult =>\n convertToAggregateQuerySnapshot(firestore, query, aggregateResult)\n );\n}\n\nfunction convertToAggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n query: Query,\n aggregateResult: ApiClientObjectMap\n): AggregateQuerySnapshot {\n const userDataWriter = new LiteUserDataWriter(firestore);\n const querySnapshot = new AggregateQuerySnapshot<\n AggregateSpecType,\n AppModelType,\n DbModelType\n >(query, userDataWriter, aggregateResult);\n return querySnapshot;\n}\n\n/**\n * Create an AggregateField object that can be used to compute the sum of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to sum across the result set.\n */\nexport function sum(field: string | FieldPath): AggregateField {\n return new AggregateField('sum', fieldPathFromArgument('sum', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the average of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to average across the result set.\n */\nexport function average(\n field: string | FieldPath\n): AggregateField {\n return new AggregateField('avg', fieldPathFromArgument('average', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the count of\n * documents in the result set of a query.\n */\nexport function count(): AggregateField {\n return new AggregateField('count');\n}\n\n/**\n * Compares two 'AggregateField` instances for equality.\n *\n * @param left Compare this AggregateField to the `right`.\n * @param right Compare this AggregateField to the `left`.\n */\nexport function aggregateFieldEqual(\n left: AggregateField,\n right: AggregateField\n): boolean {\n return (\n left instanceof AggregateField &&\n right instanceof AggregateField &&\n left.aggregateType === right.aggregateType &&\n left._internalFieldPath?.canonicalString() ===\n right._internalFieldPath?.canonicalString()\n );\n}\n\n/**\n * Compares two `AggregateQuerySnapshot` instances for equality.\n *\n * Two `AggregateQuerySnapshot` instances are considered \"equal\" if they have\n * underlying queries that compare equal, and the same data.\n *\n * @param left - The first `AggregateQuerySnapshot` to compare.\n * @param right - The second `AggregateQuerySnapshot` to compare.\n *\n * @returns `true` if the objects are \"equal\", as defined above, or `false`\n * otherwise.\n */\nexport function aggregateQuerySnapshotEqual<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n left: AggregateQuerySnapshot,\n right: AggregateQuerySnapshot\n): boolean {\n return (\n queryEqual(left.query, right.query) && deepEqual(left.data(), right.data())\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldValue } from './field_value';\nimport {\n ArrayRemoveFieldValueImpl,\n ArrayUnionFieldValueImpl,\n DeleteFieldValueImpl,\n NumericIncrementFieldValueImpl,\n ServerTimestampFieldValueImpl\n} from './user_data_reader';\nimport { VectorValue } from './vector_value';\n\n/**\n * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or\n * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.\n */\nexport function deleteField(): FieldValue {\n return new DeleteFieldValueImpl('deleteField');\n}\n\n/**\n * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to\n * include a server-generated timestamp in the written data.\n */\nexport function serverTimestamp(): FieldValue {\n return new ServerTimestampFieldValueImpl('serverTimestamp');\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array\n * value that already exists on the server. Each specified element that doesn't\n * already exist in the array will be added to the end. If the field being\n * modified is not already an array it will be overwritten with an array\n * containing exactly the specified elements.\n *\n * @param elements - The elements to union into the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`.\n */\nexport function arrayUnion(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayUnionFieldValueImpl('arrayUnion', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link (setDoc:1)} or {@link\n * updateDoc:1} that tells the server to remove the given elements from any\n * array value that already exists on the server. All instances of each element\n * specified will be removed from the array. If the field being modified is not\n * already an array it will be overwritten with an empty array.\n *\n * @param elements - The elements to remove from the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function arrayRemove(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayRemoveFieldValueImpl('arrayRemove', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by\n * the given value.\n *\n * If either the operand or the current field value uses floating point\n * precision, all arithmetic follows IEEE 754 semantics. If both values are\n * integers, values outside of JavaScript's safe number range\n * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to\n * precision loss. Furthermore, once processed by the Firestore backend, all\n * integer operations are capped between -2^63 and 2^63-1.\n *\n * If the current field value is not of type `number`, or if the field does not\n * yet exist, the transformation sets the field to the given value.\n *\n * @param n - The value to increment by.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function increment(n: number): FieldValue {\n return new NumericIncrementFieldValueImpl('increment', n);\n}\n\n/**\n * Creates a new `VectorValue` constructed with a copy of the given array of numbers.\n *\n * @param values - Create a `VectorValue` instance with a copy of this array of numbers.\n *\n * @returns A new `VectorValue` constructed with a copy of the given array of numbers.\n */\nexport function vector(values?: number[]): VectorValue {\n return new VectorValue(values);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Compat, getModularInstance } from '@firebase/util';\n\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { invokeCommitRpc } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport { applyFirestoreDataConverter } from './reference_impl';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\n\n/**\n * A write batch, used to perform multiple writes as a single atomic unit.\n *\n * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It\n * provides methods for adding writes to the write batch. None of the writes\n * will be committed (or visible locally) until {@link WriteBatch.commit} is\n * called.\n */\nexport class WriteBatch {\n // This is the lite version of the WriteBatch API used in the legacy SDK. The\n // class is a close copy but takes different input types.\n\n private readonly _dataReader: UserDataReader;\n private _mutations = [] as Mutation[];\n private _committed = false;\n\n /** @hideconstructor */\n constructor(\n private readonly _firestore: Firestore,\n private readonly _commitHandler: (m: Mutation[]) => Promise\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): WriteBatch;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): WriteBatch;\n set(\n documentRef: DocumentReference,\n data: WithFieldValue | PartialWithFieldValue,\n options?: SetOptions\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n data,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'WriteBatch.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._mutations.push(parsed.toMutation(ref._key, Precondition.none()));\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): WriteBatch;\n /**\n * Updates fields in the document referred to by this {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be update by providing dot-separated field path strings\n * or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._mutations.push(\n parsed.toMutation(ref._key, Precondition.exists(true))\n );\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n this._mutations = this._mutations.concat(\n new DeleteMutation(ref._key, Precondition.none())\n );\n return this;\n }\n\n /**\n * Commits all of the writes in this write batch as a single atomic unit.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `Promise` resolved once all of the writes in the batch have been\n * successfully written to the backend as an atomic unit (note that it won't\n * resolve while you're offline).\n */\n commit(): Promise {\n this._verifyNotCommitted();\n this._committed = true;\n if (this._mutations.length > 0) {\n return this._commitHandler(this._mutations);\n }\n\n return Promise.resolve();\n }\n\n private _verifyNotCommitted(): void {\n if (this._committed) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A write batch can no longer be used after commit() ' +\n 'has been called.'\n );\n }\n }\n}\n\nexport function validateReference<\n AppModelType,\n DbModelType extends DocumentData\n>(\n documentRef:\n | DocumentReference\n | Compat>,\n firestore: Firestore\n): DocumentReference {\n documentRef = getModularInstance(documentRef);\n\n if (documentRef.firestore !== firestore) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Provided document reference is from a different Firestore instance.'\n );\n } else {\n return documentRef as DocumentReference;\n }\n}\n\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single WriteBatch\n * is 500.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `WriteBatch` that can be used to atomically execute multiple\n * writes.\n */\nexport function writeBatch(firestore: Firestore): WriteBatch {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n return new WriteBatch(firestore, writes =>\n invokeCommitRpc(datastore, writes)\n );\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\n\nexport const DEFAULT_TRANSACTION_OPTIONS: TransactionOptions = {\n maxAttempts: 5\n};\n\n/**\n * Options to customize transaction behavior.\n */\nexport declare interface TransactionOptions {\n /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */\n readonly maxAttempts: number;\n}\n\nexport function validateTransactionOptions(options: TransactionOptions): void {\n if (options.maxAttempts < 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Max attempts must be at least 1'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParsedSetData, ParsedUpdateData } from '../lite-api/user_data_reader';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n DeleteMutation,\n Mutation,\n Precondition,\n VerifyMutation\n} from '../model/mutation';\nimport {\n Datastore,\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc\n} from '../remote/datastore';\nimport { fail, debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { SnapshotVersion } from './snapshot_version';\n\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nexport class Transaction {\n // The version of each document that was read during this transaction.\n private readVersions = new Map();\n private mutations: Mutation[] = [];\n private committed = false;\n\n /**\n * A deferred usage error that occurred previously in this transaction that\n * will cause the transaction to fail once it actually commits.\n */\n private lastTransactionError: FirestoreError | null = null;\n\n /**\n * Set of documents that have been written in the transaction.\n *\n * When there's more than one write to the same key in a transaction, any\n * writes after the first are handled differently.\n */\n private writtenDocs: Set = new Set();\n\n constructor(private datastore: Datastore) {}\n\n async lookup(keys: DocumentKey[]): Promise {\n this.ensureCommitNotCalled();\n\n if (this.mutations.length > 0) {\n this.lastTransactionError = new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Firestore transactions require all reads to be executed before all writes.'\n );\n throw this.lastTransactionError;\n }\n const docs = await invokeBatchGetDocumentsRpc(this.datastore, keys);\n docs.forEach(doc => this.recordVersion(doc));\n return docs;\n }\n\n set(key: DocumentKey, data: ParsedSetData): void {\n this.write(data.toMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n update(key: DocumentKey, data: ParsedUpdateData): void {\n try {\n this.write(data.toMutation(key, this.preconditionForUpdate(key)));\n } catch (e) {\n this.lastTransactionError = e as FirestoreError | null;\n }\n this.writtenDocs.add(key.toString());\n }\n\n delete(key: DocumentKey): void {\n this.write(new DeleteMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n async commit(): Promise {\n this.ensureCommitNotCalled();\n\n if (this.lastTransactionError) {\n throw this.lastTransactionError;\n }\n const unwritten = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach(mutation => {\n unwritten.delete(mutation.key.toString());\n });\n // For each document that was read but not written to, we want to perform\n // a `verify` operation.\n unwritten.forEach((_, path) => {\n const key = DocumentKey.fromPath(path);\n this.mutations.push(new VerifyMutation(key, this.precondition(key)));\n });\n await invokeCommitRpc(this.datastore, this.mutations);\n this.committed = true;\n }\n\n private recordVersion(doc: Document): void {\n let docVersion: SnapshotVersion;\n\n if (doc.isFoundDocument()) {\n docVersion = doc.version;\n } else if (doc.isNoDocument()) {\n // Represent a deleted doc using SnapshotVersion.min().\n docVersion = SnapshotVersion.min();\n } else {\n throw fail(0xc542, 'Document in a transaction was a ', {\n documentName: doc.constructor.name\n });\n }\n\n const existingVersion = this.readVersions.get(doc.key.toString());\n if (existingVersion) {\n if (!docVersion.isEqual(existingVersion)) {\n // This transaction will fail no matter what.\n throw new FirestoreError(\n Code.ABORTED,\n 'Document version changed between two reads.'\n );\n }\n } else {\n this.readVersions.set(doc.key.toString(), docVersion);\n }\n }\n\n /**\n * Returns the version of this document when it was read in this transaction,\n * as a precondition, or no precondition if it was not read.\n */\n private precondition(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n return Precondition.exists(false);\n } else {\n return Precondition.updateTime(version);\n }\n } else {\n return Precondition.none();\n }\n }\n\n /**\n * Returns the precondition for a document if the operation is an update.\n */\n private preconditionForUpdate(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n // The first time a document is written, we want to take into account the\n // read time and existence\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n // The document doesn't exist, so fail the transaction.\n\n // This has to be validated locally because you can't send a\n // precondition that a document does not exist without changing the\n // semantics of the backend write to be an insert. This is the reverse\n // of what we want, since we want to assert that the document doesn't\n // exist but then send the update and have it fail. Since we can't\n // express that to the backend, we have to validate locally.\n\n // Note: this can change once we can send separate verify writes in the\n // transaction.\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't update a document that doesn't exist.\"\n );\n }\n // Document exists, base precondition on document update time.\n return Precondition.updateTime(version);\n } else {\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return Precondition.exists(true);\n }\n }\n\n private write(mutation: Mutation): void {\n this.ensureCommitNotCalled();\n this.mutations.push(mutation);\n }\n\n private ensureCommitNotCalled(): void {\n debugAssert(\n !this.committed,\n 'A transaction object cannot be used after its update callback has been invoked.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ExponentialBackoff } from '../remote/backoff';\nimport { Datastore } from '../remote/datastore';\nimport { isPermanentError } from '../remote/rpc_error';\nimport { AsyncQueue, TimerId } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport { Deferred } from '../util/promise';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Transaction } from './transaction';\nimport { TransactionOptions } from './transaction_options';\n\n/**\n * TransactionRunner encapsulates the logic needed to run and retry transactions\n * with backoff.\n */\nexport class TransactionRunner {\n private attemptsRemaining: number;\n private backoff: ExponentialBackoff;\n\n constructor(\n private readonly asyncQueue: AsyncQueue,\n private readonly datastore: Datastore,\n private readonly options: TransactionOptions,\n private readonly updateFunction: (transaction: Transaction) => Promise,\n private readonly deferred: Deferred\n ) {\n this.attemptsRemaining = options.maxAttempts;\n this.backoff = new ExponentialBackoff(\n this.asyncQueue,\n TimerId.TransactionRetry\n );\n }\n\n /** Runs the transaction and sets the result on deferred. */\n run(): void {\n this.attemptsRemaining -= 1;\n this.runWithBackOff();\n }\n\n private runWithBackOff(): void {\n this.backoff.backoffAndRun(async () => {\n const transaction = new Transaction(this.datastore);\n const userPromise = this.tryRunUpdateFunction(transaction);\n if (userPromise) {\n userPromise\n .then(result => {\n this.asyncQueue.enqueueAndForget(() => {\n return transaction\n .commit()\n .then(() => {\n this.deferred.resolve(result);\n })\n .catch(commitError => {\n this.handleTransactionError(commitError);\n });\n });\n })\n .catch(userPromiseError => {\n this.handleTransactionError(userPromiseError);\n });\n }\n });\n }\n\n private tryRunUpdateFunction(transaction: Transaction): Promise | null {\n try {\n const userPromise = this.updateFunction(transaction);\n if (\n isNullOrUndefined(userPromise) ||\n !userPromise.catch ||\n !userPromise.then\n ) {\n this.deferred.reject(\n Error('Transaction callback must return a Promise')\n );\n return null;\n }\n return userPromise;\n } catch (error) {\n // Do not retry errors thrown by user provided updateFunction.\n this.deferred.reject(error as Error);\n return null;\n }\n }\n\n private handleTransactionError(error: Error): void {\n if (this.attemptsRemaining > 0 && this.isRetryableTransactionError(error)) {\n this.attemptsRemaining -= 1;\n this.asyncQueue.enqueueAndForget(() => {\n this.runWithBackOff();\n return Promise.resolve();\n });\n } else {\n this.deferred.reject(error);\n }\n }\n\n private isRetryableTransactionError(error: Error | undefined): boolean {\n if (error?.name === 'FirebaseError') {\n // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and\n // non-matching document versions with ABORTED. These errors should be retried.\n const code = (error as FirestoreError).code;\n return (\n code === 'aborted' ||\n code === 'failed-precondition' ||\n code === 'already-exists' ||\n !isPermanentError(code)\n );\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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(0xb815, 'AsyncQueue is already failed', {\n messageOrStack: getMessageOrStack(this.failure)\n });\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 { getModularInstance } from '@firebase/util';\n\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport {\n DEFAULT_TRANSACTION_OPTIONS,\n TransactionOptions as TransactionOptionsInternal,\n validateTransactionOptions\n} from '../core/transaction_options';\nimport { TransactionRunner } from '../core/transaction_runner';\nimport { fail } from '../util/assert';\nimport { newAsyncQueue } from '../util/async_queue_impl';\nimport { cast } from '../util/input_validation';\nimport { Deferred } from '../util/promise';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n applyFirestoreDataConverter,\n LiteUserDataWriter\n} from './reference_impl';\nimport { DocumentSnapshot } from './snapshot';\nimport { TransactionOptions } from './transaction_options';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\nimport { validateReference } from './write_batch';\n\n// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the\n// legacy SDK.\n\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nexport class Transaction {\n // This is the tree-shakeable version of the Transaction class used in the\n // legacy SDK. The class is a close copy but takes different input and output\n // types. The firestore-exp SDK further extends this class to return its API\n // type.\n\n private readonly _dataReader: UserDataReader;\n\n /** @hideconstructor */\n constructor(\n protected readonly _firestore: Firestore,\n private readonly _transaction: InternalTransaction\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */\n get(\n documentRef: DocumentReference\n ): Promise> {\n const ref = validateReference(documentRef, this._firestore);\n const userDataWriter = new LiteUserDataWriter(this._firestore);\n return this._transaction.lookup([ref._key]).then(docs => {\n if (!docs || docs.length !== 1) {\n return fail(0x5de9, 'Mismatch in docs returned from document lookup.');\n }\n const doc = docs[0];\n if (doc.isFoundDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n doc.key,\n doc,\n ref.converter\n );\n } else if (doc.isNoDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n ref._key,\n null,\n ref.converter\n );\n } else {\n throw fail(\n 0x4801,\n 'BatchGetDocumentsRequest returned unexpected document',\n {\n doc\n }\n );\n }\n });\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): this;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): this;\n set(\n documentRef: DocumentReference,\n value: PartialWithFieldValue,\n options?: SetOptions\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n value,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'Transaction.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._transaction.set(ref._key, parsed);\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): this;\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key/value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._transaction.update(ref._key, parsed);\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n this._transaction.delete(ref._key);\n return this;\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */\nexport function runTransaction(\n firestore: Firestore,\n updateFunction: (transaction: Transaction) => Promise,\n options?: TransactionOptions\n): Promise {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n const optionsWithDefaults: TransactionOptionsInternal = {\n ...DEFAULT_TRANSACTION_OPTIONS,\n ...options\n };\n validateTransactionOptions(optionsWithDefaults);\n const deferred = new Deferred();\n new TransactionRunner(\n newAsyncQueue(),\n datastore,\n optionsWithDefaults,\n internalTransaction =>\n updateFunction(new Transaction(firestore, internalTransaction)),\n deferred\n ).run();\n return deferred.promise;\n}\n","/**\n * Firestore Lite\n *\n * @remarks Firestore Lite is a small online-only SDK that allows read\n * and write access to your Firestore database. All operations connect\n * directly to the backend, and `onSnapshot()` APIs are not supported.\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 { registerFirestore } from './register';\nregisterFirestore();\n\nexport {\n aggregateQuerySnapshotEqual,\n getCount,\n getAggregate,\n count,\n sum,\n average,\n aggregateFieldEqual\n} from '../src/lite-api/aggregate';\n\nexport {\n AggregateField,\n AggregateFieldType,\n AggregateSpec,\n AggregateSpecData,\n AggregateQuerySnapshot,\n AggregateType\n} from '../src/lite-api/aggregate_types';\n\nexport { FirestoreSettings as Settings } from '../src/lite-api/settings';\n\nexport {\n Firestore as Firestore,\n EmulatorMockTokenOptions,\n initializeFirestore,\n getFirestore,\n terminate,\n connectFirestoreEmulator\n} from '../src/lite-api/database';\n\nexport {\n DocumentData,\n UpdateData,\n WithFieldValue,\n PartialWithFieldValue,\n SetOptions,\n DocumentReference,\n Query,\n CollectionReference,\n collection,\n collectionGroup,\n doc,\n refEqual,\n queryEqual\n} from '../src/lite-api/reference';\n\nexport {\n and,\n endAt,\n endBefore,\n startAt,\n startAfter,\n limit,\n limitToLast,\n where,\n or,\n orderBy,\n query,\n QueryConstraint,\n QueryConstraintType,\n QueryCompositeFilterConstraint,\n QueryFilterConstraint,\n QueryFieldFilterConstraint,\n QueryOrderByConstraint,\n QueryLimitConstraint,\n QueryNonFilterConstraint,\n QueryStartAtConstraint,\n QueryEndAtConstraint,\n OrderByDirection,\n WhereFilterOp\n} from '../src/lite-api/query';\n\nexport {\n addDoc,\n deleteDoc,\n updateDoc,\n setDoc,\n getDoc,\n getDocs\n} from '../src/lite-api/reference_impl';\n\nexport {\n Primitive,\n NestedUpdateFields,\n ChildUpdateFields,\n AddPrefixToKeys,\n UnionToIntersection\n} from '../src/lite-api/types';\n\n// TODO(firestorelite): Add tests when Queries are usable\nexport { FieldPath, documentId } from '../src/lite-api/field_path';\n\n// TODO(firestorelite): Add tests when setDoc() is available\nexport { FieldValue } from '../src/lite-api/field_value';\n\nexport {\n increment,\n arrayRemove,\n arrayUnion,\n serverTimestamp,\n deleteField,\n vector\n} from '../src/lite-api/field_value_impl';\n\nexport {\n FirestoreDataConverter,\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot,\n snapshotEqual\n} from '../src/lite-api/snapshot';\n\nexport { VectorValue } from '../src/lite-api/vector_value';\n\nexport { WriteBatch, writeBatch } from '../src/lite-api/write_batch';\n\nexport { TransactionOptions } from '../src/lite-api/transaction_options';\n\nexport { Transaction, runTransaction } from '../src/lite-api/transaction';\n\nexport { setLogLevel, LogLevelString as LogLevel } from '../src/util/log';\n\nexport { Bytes } from '../src/lite-api/bytes';\n\nexport { GeoPoint } from '../src/lite-api/geo_point';\n\nexport { Timestamp } from '../src/lite-api/timestamp';\n\nexport { FirestoreErrorCode, FirestoreError } from '../src/util/error';\n"],"names":["inspect","Logger","LogLevel","FirebaseError","app","_isFirebaseServerApp","generateRandomBytes","Integer","FieldPath","LOG_TAG","isCloudWorkstation","TYPE_KEY","_getProvider","getApp","getDefaultEmulatorHostnameAndPort","pingServer","updateEmulatorBanner","deepEqual","createMockUserToken","_removeServiceInstance","SDK_VERSION","_registerComponent","Component","registerVersion","version","getModularInstance","InternalFieldPath","fieldPathFromArgument","Transaction"],"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kBG;AACa,SAAA,cAAc,CAC5B,SAAoB,EACpB,cAAwD,EACxD,OAA4B,EAAA;AAE5B,IAAA,SAAS,GAAG,IAAI,CAAC,SAAS,EAAE,SAAS,CAAC,CAAC;AACvC,IAAA,MAAM,SAAS,GAAG,YAAY,CAAC,SAAS,CAAC,CAAC;AAC1C,IAAA,MAAM,mBAAmB,GAA+B;AACtD,QAAA,GAAG,2BAA2B;AAC9B,QAAA,GAAG,OAAO;KACX,CAAC;IACF,0BAA0B,CAAC,mBAAmB,CAAC,CAAC;AAChD,IAAA,MAAM,QAAQ,GAAG,IAAI,QAAQ,EAAK,CAAC;AACnC,IAAA,IAAI,iBAAiB,CACnB,aAAa,EAAE,EACf,SAAS,EACT,mBAAmB,EACnB,mBAAmB,IACjB,cAAc,CAAC,IAAI,WAAW,CAAC,SAAS,EAAE,mBAAmB,CAAC,CAAC,EACjE,QAAQ,CACT,CAAC,GAAG,EAAE,CAAC;IACR,OAAO,QAAQ,CAAC,OAAO,CAAC;AAC1B,CAAA;;ACvTA;;;;;;;AAOG;AAoBH,iBAAiB,EAAE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.mjs b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.mjs new file mode 100644 index 0000000..7a3a3a8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.mjs @@ -0,0 +1,9798 @@ +import { _getProvider, getApp, _removeServiceInstance, _registerComponent, registerVersion, _isFirebaseServerApp, SDK_VERSION as SDK_VERSION$1 } from '@firebase/app'; +import { Component } from '@firebase/component'; +import { Logger, LogLevel } from '@firebase/logger'; +import { inspect } from 'util'; +import { FirebaseError, getDefaultEmulatorHostnameAndPort, isCloudWorkstation, pingServer, updateEmulatorBanner, deepEqual, createMockUserToken, getModularInstance } from '@firebase/util'; +import { Integer } from '@firebase/webchannel-wrapper/bloom-blob'; +import { randomBytes as randomBytes$1 } from 'crypto'; + +const version$1 = "4.9.2"; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Simple wrapper around a nullable UID. Mostly exists to make code more + * readable. + */ +class User { + constructor(uid) { + this.uid = uid; + } + isAuthenticated() { + return this.uid != null; + } + /** + * Returns a key representing this user, suitable for inclusion in a + * dictionary. + */ + toKey() { + if (this.isAuthenticated()) { + return 'uid:' + this.uid; + } + else { + return 'anonymous-user'; + } + } + isEqual(otherUser) { + return otherUser.uid === this.uid; + } +} +/** A user with a null UID. */ +User.UNAUTHENTICATED = new User(null); +// TODO(mikelehen): Look into getting a proper uid-equivalent for +// non-FirebaseAuth providers. +User.GOOGLE_CREDENTIALS = new User('google-credentials-uid'); +User.FIRST_PARTY = new User('first-party-uid'); +User.MOCK_USER = new User('mock-user'); + +const version = "12.3.0"; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let SDK_VERSION = version; +function setSDKVersion(version) { + SDK_VERSION = version; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Formats an object as a JSON string, suitable for logging. */ +function formatJSON(value) { + // util.inspect() results in much more readable output than JSON.stringify() + return inspect(value, { depth: 100 }); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const logClient = new Logger('@firebase/firestore'); +/** + * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). + * + * @param logLevel - The verbosity you set for activity and error logging. Can + * be any of the following values: + * + *
    + *
  • `debug` for the most verbose logging level, primarily for + * debugging.
  • + *
  • `error` to log errors only.
  • + *
  • `silent` to turn off logging.
  • + *
+ */ +function setLogLevel(logLevel) { + logClient.setLogLevel(logLevel); +} +function logDebug(msg, ...obj) { + if (logClient.logLevel <= LogLevel.DEBUG) { + const args = obj.map(argToString); + logClient.debug(`Firestore (${SDK_VERSION}): ${msg}`, ...args); + } +} +function logError(msg, ...obj) { + if (logClient.logLevel <= LogLevel.ERROR) { + const args = obj.map(argToString); + logClient.error(`Firestore (${SDK_VERSION}): ${msg}`, ...args); + } +} +/** + * @internal + */ +function logWarn(msg, ...obj) { + if (logClient.logLevel <= LogLevel.WARN) { + const args = obj.map(argToString); + logClient.warn(`Firestore (${SDK_VERSION}): ${msg}`, ...args); + } +} +/** + * Converts an additional log parameter to a string representation. + */ +function argToString(obj) { + if (typeof obj === 'string') { + return obj; + } + else { + try { + return formatJSON(obj); + } + catch (e) { + // Converting to JSON failed, just log the object directly + return obj; + } + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function fail(id, messageOrContext, context) { + let message = 'Unexpected state'; + if (typeof messageOrContext === 'string') { + message = messageOrContext; + } + else { + context = messageOrContext; + } + _fail(id, message, context); +} +function _fail(id, failure, context) { + // Log the failure in addition to throw an exception, just in case the + // exception is swallowed. + let message = `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ${failure} (ID: ${id.toString(16)})`; + if (context !== undefined) { + try { + const stringContext = JSON.stringify(context); + message += ' CONTEXT: ' + stringContext; + } + catch (e) { + message += ' CONTEXT: ' + context; + } + } + logError(message); + // NOTE: We don't use FirestoreError here because these are internal failures + // that cannot be handled by the user. (Also it would create a circular + // dependency between the error and assert modules which doesn't work.) + throw new Error(message); +} +function hardAssert(assertion, id, messageOrContext, context) { + let message = 'Unexpected state'; + if (typeof messageOrContext === 'string') { + message = messageOrContext; + } + else { + context = messageOrContext; + } + if (!assertion) { + _fail(id, message, context); + } +} +/** + * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an + * instance of `T` before casting. + */ +function debugCast(obj, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +constructor) { + return obj; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const Code = { + // Causes are copied from: + // https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h + /** Not an error; returned on success. */ + OK: 'ok', + /** The operation was cancelled (typically by the caller). */ + CANCELLED: 'cancelled', + /** Unknown error or an error from a different error domain. */ + UNKNOWN: 'unknown', + /** + * Client specified an invalid argument. Note that this differs from + * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are + * problematic regardless of the state of the system (e.g., a malformed file + * name). + */ + INVALID_ARGUMENT: 'invalid-argument', + /** + * Deadline expired before operation could complete. For operations that + * change the state of the system, this error may be returned even if the + * operation has completed successfully. For example, a successful response + * from a server could have been delayed long enough for the deadline to + * expire. + */ + DEADLINE_EXCEEDED: 'deadline-exceeded', + /** Some requested entity (e.g., file or directory) was not found. */ + NOT_FOUND: 'not-found', + /** + * Some entity that we attempted to create (e.g., file or directory) already + * exists. + */ + ALREADY_EXISTS: 'already-exists', + /** + * The caller does not have permission to execute the specified operation. + * PERMISSION_DENIED must not be used for rejections caused by exhausting + * some resource (use RESOURCE_EXHAUSTED instead for those errors). + * PERMISSION_DENIED must not be used if the caller cannot be identified + * (use UNAUTHENTICATED instead for those errors). + */ + PERMISSION_DENIED: 'permission-denied', + /** + * The request does not have valid authentication credentials for the + * operation. + */ + UNAUTHENTICATED: 'unauthenticated', + /** + * Some resource has been exhausted, perhaps a per-user quota, or perhaps the + * entire file system is out of space. + */ + RESOURCE_EXHAUSTED: 'resource-exhausted', + /** + * Operation was rejected because the system is not in a state required for + * the operation's execution. For example, directory to be deleted may be + * non-empty, an rmdir operation is applied to a non-directory, etc. + * + * A litmus test that may help a service implementor in deciding + * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: + * (a) Use UNAVAILABLE if the client can retry just the failing call. + * (b) Use ABORTED if the client should retry at a higher-level + * (e.g., restarting a read-modify-write sequence). + * (c) Use FAILED_PRECONDITION if the client should not retry until + * the system state has been explicitly fixed. E.g., if an "rmdir" + * fails because the directory is non-empty, FAILED_PRECONDITION + * should be returned since the client should not retry unless + * they have first fixed up the directory by deleting files from it. + * (d) Use FAILED_PRECONDITION if the client performs conditional + * REST Get/Update/Delete on a resource and the resource on the + * server does not match the condition. E.g., conflicting + * read-modify-write on the same resource. + */ + FAILED_PRECONDITION: 'failed-precondition', + /** + * The operation was aborted, typically due to a concurrency issue like + * sequencer check failures, transaction aborts, etc. + * + * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, + * and UNAVAILABLE. + */ + ABORTED: 'aborted', + /** + * Operation was attempted past the valid range. E.g., seeking or reading + * past end of file. + * + * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed + * if the system state changes. For example, a 32-bit file system will + * generate INVALID_ARGUMENT if asked to read at an offset that is not in the + * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from + * an offset past the current file size. + * + * There is a fair bit of overlap between FAILED_PRECONDITION and + * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) + * when it applies so that callers who are iterating through a space can + * easily look for an OUT_OF_RANGE error to detect when they are done. + */ + OUT_OF_RANGE: 'out-of-range', + /** Operation is not implemented or not supported/enabled in this service. */ + UNIMPLEMENTED: 'unimplemented', + /** + * Internal errors. Means some invariants expected by underlying System has + * been broken. If you see one of these errors, Something is very broken. + */ + INTERNAL: 'internal', + /** + * The service is currently unavailable. This is a most likely a transient + * condition and may be corrected by retrying with a backoff. + * + * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, + * and UNAVAILABLE. + */ + UNAVAILABLE: 'unavailable', + /** Unrecoverable data loss or corruption. */ + DATA_LOSS: 'data-loss' +}; +/** An error returned by a Firestore operation. */ +class FirestoreError extends FirebaseError { + /** @hideconstructor */ + constructor( + /** + * The backend error code associated with this error. + */ + code, + /** + * A custom error description. + */ + message) { + super(code, message); + this.code = code; + this.message = message; + // HACK: We write a toString property directly because Error is not a real + // class and so inheritance does not work correctly. We could alternatively + // do the same "back-door inheritance" trick that FirebaseError does. + this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Deferred { + constructor() { + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + }); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class OAuthToken { + constructor(value, user) { + this.user = user; + this.type = 'OAuth'; + this.headers = new Map(); + this.headers.set('Authorization', `Bearer ${value}`); + } +} +/** + * A CredentialsProvider that always yields an empty token. + * @internal + */ +class EmptyAuthCredentialsProvider { + getToken() { + return Promise.resolve(null); + } + invalidateToken() { } + start(asyncQueue, changeListener) { + // Fire with initial user. + asyncQueue.enqueueRetryable(() => changeListener(User.UNAUTHENTICATED)); + } + shutdown() { } +} +/** + * A CredentialsProvider that always returns a constant token. Used for + * emulator token mocking. + */ +class EmulatorAuthCredentialsProvider { + constructor(token) { + this.token = token; + /** + * Stores the listener registered with setChangeListener() + * This isn't actually necessary since the UID never changes, but we use this + * to verify the listen contract is adhered to in tests. + */ + this.changeListener = null; + } + getToken() { + return Promise.resolve(this.token); + } + invalidateToken() { } + start(asyncQueue, changeListener) { + this.changeListener = changeListener; + // Fire with initial user. + asyncQueue.enqueueRetryable(() => changeListener(this.token.user)); + } + shutdown() { + this.changeListener = null; + } +} +/** Credential provider for the Lite SDK. */ +class LiteAuthCredentialsProvider { + constructor(authProvider) { + this.auth = null; + authProvider.onInit(auth => { + this.auth = auth; + }); + } + getToken() { + if (!this.auth) { + return Promise.resolve(null); + } + return this.auth.getToken().then(tokenData => { + if (tokenData) { + hardAssert(typeof tokenData.accessToken === 'string', 0xa539, { tokenData }); + return new OAuthToken(tokenData.accessToken, new User(this.auth.getUid())); + } + else { + return null; + } + }); + } + invalidateToken() { } + start(asyncQueue, changeListener) { } + shutdown() { } +} +/* + * FirstPartyToken provides a fresh token each time its value + * is requested, because if the token is too old, requests will be rejected. + * Technically this may no longer be necessary since the SDK should gracefully + * recover from unauthenticated errors (see b/33147818 for context), but it's + * safer to keep the implementation as-is. + */ +class FirstPartyToken { + constructor(sessionIndex, iamToken, authTokenFactory) { + this.sessionIndex = sessionIndex; + this.iamToken = iamToken; + this.authTokenFactory = authTokenFactory; + this.type = 'FirstParty'; + this.user = User.FIRST_PARTY; + this._headers = new Map(); + } + /** + * Gets an authorization token, using a provided factory function, or return + * null. + */ + getAuthToken() { + if (this.authTokenFactory) { + return this.authTokenFactory(); + } + else { + return null; + } + } + get headers() { + this._headers.set('X-Goog-AuthUser', this.sessionIndex); + // Use array notation to prevent minification + const authHeaderTokenValue = this.getAuthToken(); + if (authHeaderTokenValue) { + this._headers.set('Authorization', authHeaderTokenValue); + } + if (this.iamToken) { + this._headers.set('X-Goog-Iam-Authorization-Token', this.iamToken); + } + return this._headers; + } +} +/* + * Provides user credentials required for the Firestore JavaScript SDK + * to authenticate the user, using technique that is only available + * to applications hosted by Google. + */ +class FirstPartyAuthCredentialsProvider { + constructor(sessionIndex, iamToken, authTokenFactory) { + this.sessionIndex = sessionIndex; + this.iamToken = iamToken; + this.authTokenFactory = authTokenFactory; + } + getToken() { + return Promise.resolve(new FirstPartyToken(this.sessionIndex, this.iamToken, this.authTokenFactory)); + } + start(asyncQueue, changeListener) { + // Fire with initial uid. + asyncQueue.enqueueRetryable(() => changeListener(User.FIRST_PARTY)); + } + shutdown() { } + invalidateToken() { } +} +class AppCheckToken { + constructor(value) { + this.value = value; + this.type = 'AppCheck'; + this.headers = new Map(); + if (value && value.length > 0) { + this.headers.set('x-firebase-appcheck', this.value); + } + } +} +/** AppCheck token provider for the Lite SDK. */ +class LiteAppCheckTokenProvider { + constructor(app, appCheckProvider) { + this.appCheckProvider = appCheckProvider; + this.appCheck = null; + this.serverAppAppCheckToken = null; + if (_isFirebaseServerApp(app) && app.settings.appCheckToken) { + this.serverAppAppCheckToken = app.settings.appCheckToken; + } + appCheckProvider.onInit(appCheck => { + this.appCheck = appCheck; + }); + } + getToken() { + if (this.serverAppAppCheckToken) { + return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken)); + } + if (!this.appCheck) { + return Promise.resolve(null); + } + return this.appCheck.getToken().then(tokenResult => { + if (tokenResult) { + hardAssert(typeof tokenResult.token === 'string', 0x0d8e, { tokenResult }); + return new AppCheckToken(tokenResult.token); + } + else { + return null; + } + }); + } + invalidateToken() { } + start(asyncQueue, changeListener) { } + shutdown() { } +} +/** + * Builds a CredentialsProvider depending on the type of + * the credentials passed in. + */ +function makeAuthCredentialsProvider(credentials) { + if (!credentials) { + return new EmptyAuthCredentialsProvider(); + } + switch (credentials['type']) { + case 'firstParty': + return new FirstPartyAuthCredentialsProvider(credentials['sessionIndex'] || '0', credentials['iamToken'] || null, credentials['authTokenFactory'] || null); + case 'provider': + return credentials['client']; + default: + throw new FirestoreError(Code.INVALID_ARGUMENT, 'makeAuthCredentialsProvider failed due to invalid credential type'); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class DatabaseInfo { + /** + * Constructs a DatabaseInfo using the provided host, databaseId and + * persistenceKey. + * + * @param databaseId - The database to use. + * @param appId - The Firebase App Id. + * @param persistenceKey - A unique identifier for this Firestore's local + * storage (used in conjunction with the databaseId). + * @param host - The Firestore backend host to connect to. + * @param ssl - Whether to use SSL when connecting. + * @param forceLongPolling - Whether to use the forceLongPolling option + * when using WebChannel as the network transport. + * @param autoDetectLongPolling - Whether to use the detectBufferingProxy + * option when using WebChannel as the network transport. + * @param longPollingOptions Options that configure long-polling. + * @param useFetchStreams Whether to use the Fetch API instead of + * XMLHTTPRequest + */ + constructor(databaseId, appId, persistenceKey, host, ssl, forceLongPolling, autoDetectLongPolling, longPollingOptions, useFetchStreams, isUsingEmulator) { + this.databaseId = databaseId; + this.appId = appId; + this.persistenceKey = persistenceKey; + this.host = host; + this.ssl = ssl; + this.forceLongPolling = forceLongPolling; + this.autoDetectLongPolling = autoDetectLongPolling; + this.longPollingOptions = longPollingOptions; + this.useFetchStreams = useFetchStreams; + this.isUsingEmulator = isUsingEmulator; + } +} +/** The default database name for a project. */ +const DEFAULT_DATABASE_NAME = '(default)'; +/** + * Represents the database ID a Firestore client is associated with. + * @internal + */ +class DatabaseId { + constructor(projectId, database) { + this.projectId = projectId; + this.database = database ? database : DEFAULT_DATABASE_NAME; + } + static empty() { + return new DatabaseId('', ''); + } + get isDefaultDatabase() { + return this.database === DEFAULT_DATABASE_NAME; + } + isEqual(other) { + return (other instanceof DatabaseId && + other.projectId === this.projectId && + other.database === this.database); + } +} +function databaseIdFromApp(app, database) { + if (!Object.prototype.hasOwnProperty.apply(app.options, ['projectId'])) { + throw new FirestoreError(Code.INVALID_ARGUMENT, '"projectId" not provided in firebase.initializeApp.'); + } + return new DatabaseId(app.options.projectId, database); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Generates `nBytes` of random bytes. + * + * If `nBytes < 0` , an error will be thrown. + */ +function randomBytes(nBytes) { + return randomBytes$1(nBytes); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A utility class for generating unique alphanumeric IDs of a specified length. + * + * @internal + * Exported internally for testing purposes. + */ +class AutoId { + static newId() { + // Alphanumeric characters + const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + // The largest byte value that is a multiple of `char.length`. + const maxMultiple = Math.floor(256 / chars.length) * chars.length; + let autoId = ''; + const targetLength = 20; + while (autoId.length < targetLength) { + const bytes = randomBytes(40); + for (let i = 0; i < bytes.length; ++i) { + // Only accept values that are [0, maxMultiple), this ensures they can + // be evenly mapped to indices of `chars` via a modulo operation. + if (autoId.length < targetLength && bytes[i] < maxMultiple) { + autoId += chars.charAt(bytes[i] % chars.length); + } + } + } + return autoId; + } +} +function primitiveComparator(left, right) { + if (left < right) { + return -1; + } + if (left > right) { + return 1; + } + return 0; +} +/** Compare strings in UTF-8 encoded byte order */ +function compareUtf8Strings(left, right) { + // Find the first differing character (a.k.a. "UTF-16 code unit") in the two strings and, + // if found, use that character to determine the relative ordering of the two strings as a + // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by + // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8 + // and UTF-16 happen to represent Unicode code points. + // + // After finding the first pair of differing characters, there are two cases: + // + // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or + // both are surrogates from a surrogate pair (that collectively represent code points greater + // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the + // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is + // sufficient. + // + // Case 2: One character is a surrogate and the other is not. In this case the surrogate- + // containing string is always ordered after the non-surrogate. This is because surrogates are + // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations + // and are lexicographically greater than the 1, 2, or 3-byte representations of code points + // less than or equal to 0xFFFF. + // + // An example of why Case 2 is required is comparing the following two Unicode code points: + // + // |-----------------------|------------|---------------------|-----------------| + // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding | + // |-----------------------|------------|---------------------|-----------------| + // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD | + // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 | + // |-----------------------|------------|---------------------|-----------------| + // + // A lexicographical comparison of the UTF-8 encodings of these code points would order + // "Replacement Character" _before_ "Grinning Face" because 0xEF is less than 0xF0. However, a + // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously + // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out, + // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate + // pair with those that do not. + const length = Math.min(left.length, right.length); + for (let i = 0; i < length; i++) { + const leftChar = left.charAt(i); + const rightChar = right.charAt(i); + if (leftChar !== rightChar) { + return isSurrogate(leftChar) === isSurrogate(rightChar) + ? primitiveComparator(leftChar, rightChar) + : isSurrogate(leftChar) + ? 1 + : -1; + } + } + // Use the lengths of the strings to determine the overall comparison result since either the + // strings were equal or one is a prefix of the other. + return primitiveComparator(left.length, right.length); +} +const MIN_SURROGATE = 0xd800; +const MAX_SURROGATE = 0xdfff; +function isSurrogate(s) { + const c = s.charCodeAt(0); + return c >= MIN_SURROGATE && c <= MAX_SURROGATE; +} +/** Helper to compare arrays using isEqual(). */ +function arrayEquals(left, right, comparator) { + if (left.length !== right.length) { + return false; + } + return left.every((value, index) => comparator(value, right[index])); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const DOCUMENT_KEY_NAME = '__name__'; +/** + * Path represents an ordered sequence of string segments. + */ +class BasePath { + constructor(segments, offset, length) { + if (offset === undefined) { + offset = 0; + } + else if (offset > segments.length) { + fail(0x027d, { + offset, + range: segments.length + }); + } + if (length === undefined) { + length = segments.length - offset; + } + else if (length > segments.length - offset) { + fail(0x06d2, { + length, + range: segments.length - offset + }); + } + this.segments = segments; + this.offset = offset; + this.len = length; + } + get length() { + return this.len; + } + isEqual(other) { + return BasePath.comparator(this, other) === 0; + } + child(nameOrPath) { + const segments = this.segments.slice(this.offset, this.limit()); + if (nameOrPath instanceof BasePath) { + nameOrPath.forEach(segment => { + segments.push(segment); + }); + } + else { + segments.push(nameOrPath); + } + return this.construct(segments); + } + /** The index of one past the last segment of the path. */ + limit() { + return this.offset + this.length; + } + popFirst(size) { + size = size === undefined ? 1 : size; + return this.construct(this.segments, this.offset + size, this.length - size); + } + popLast() { + return this.construct(this.segments, this.offset, this.length - 1); + } + firstSegment() { + return this.segments[this.offset]; + } + lastSegment() { + return this.get(this.length - 1); + } + get(index) { + return this.segments[this.offset + index]; + } + isEmpty() { + return this.length === 0; + } + isPrefixOf(other) { + if (other.length < this.length) { + return false; + } + for (let i = 0; i < this.length; i++) { + if (this.get(i) !== other.get(i)) { + return false; + } + } + return true; + } + isImmediateParentOf(potentialChild) { + if (this.length + 1 !== potentialChild.length) { + return false; + } + for (let i = 0; i < this.length; i++) { + if (this.get(i) !== potentialChild.get(i)) { + return false; + } + } + return true; + } + forEach(fn) { + for (let i = this.offset, end = this.limit(); i < end; i++) { + fn(this.segments[i]); + } + } + toArray() { + return this.segments.slice(this.offset, this.limit()); + } + /** + * Compare 2 paths segment by segment, prioritizing numeric IDs + * (e.g., "__id123__") in numeric ascending order, followed by string + * segments in lexicographical order. + */ + static comparator(p1, p2) { + const len = Math.min(p1.length, p2.length); + for (let i = 0; i < len; i++) { + const comparison = BasePath.compareSegments(p1.get(i), p2.get(i)); + if (comparison !== 0) { + return comparison; + } + } + return primitiveComparator(p1.length, p2.length); + } + static compareSegments(lhs, rhs) { + const isLhsNumeric = BasePath.isNumericId(lhs); + const isRhsNumeric = BasePath.isNumericId(rhs); + if (isLhsNumeric && !isRhsNumeric) { + // Only lhs is numeric + return -1; + } + else if (!isLhsNumeric && isRhsNumeric) { + // Only rhs is numeric + return 1; + } + else if (isLhsNumeric && isRhsNumeric) { + // both numeric + return BasePath.extractNumericId(lhs).compare(BasePath.extractNumericId(rhs)); + } + else { + // both non-numeric + return compareUtf8Strings(lhs, rhs); + } + } + // Checks if a segment is a numeric ID (starts with "__id" and ends with "__"). + static isNumericId(segment) { + return segment.startsWith('__id') && segment.endsWith('__'); + } + static extractNumericId(segment) { + return Integer.fromString(segment.substring(4, segment.length - 2)); + } +} +/** + * A slash-separated path for navigating resources (documents and collections) + * within Firestore. + * + * @internal + */ +class ResourcePath extends BasePath { + construct(segments, offset, length) { + return new ResourcePath(segments, offset, length); + } + canonicalString() { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + return this.toArray().join('/'); + } + toString() { + return this.canonicalString(); + } + /** + * Returns a string representation of this path + * where each path segment has been encoded with + * `encodeURIComponent`. + */ + toUriEncodedString() { + return this.toArray().map(encodeURIComponent).join('/'); + } + /** + * Creates a resource path from the given slash-delimited string. If multiple + * arguments are provided, all components are combined. Leading and trailing + * slashes from all components are ignored. + */ + static fromString(...pathComponents) { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + const segments = []; + for (const path of pathComponents) { + if (path.indexOf('//') >= 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid segment (${path}). Paths must not contain // in them.`); + } + // Strip leading and trailing slashed. + segments.push(...path.split('/').filter(segment => segment.length > 0)); + } + return new ResourcePath(segments); + } + static emptyPath() { + return new ResourcePath([]); + } +} +const identifierRegExp = /^[_a-zA-Z][_a-zA-Z0-9]*$/; +/** + * A dot-separated path for navigating sub-objects within a document. + * @internal + */ +class FieldPath$1 extends BasePath { + construct(segments, offset, length) { + return new FieldPath$1(segments, offset, length); + } + /** + * Returns true if the string could be used as a segment in a field path + * without escaping. + */ + static isValidIdentifier(segment) { + return identifierRegExp.test(segment); + } + canonicalString() { + return this.toArray() + .map(str => { + str = str.replace(/\\/g, '\\\\').replace(/`/g, '\\`'); + if (!FieldPath$1.isValidIdentifier(str)) { + str = '`' + str + '`'; + } + return str; + }) + .join('.'); + } + toString() { + return this.canonicalString(); + } + /** + * Returns true if this field references the key of a document. + */ + isKeyField() { + return this.length === 1 && this.get(0) === DOCUMENT_KEY_NAME; + } + /** + * The field designating the key of a document. + */ + static keyField() { + return new FieldPath$1([DOCUMENT_KEY_NAME]); + } + /** + * Parses a field string from the given server-formatted string. + * + * - Splitting the empty string is not allowed (for now at least). + * - Empty segments within the string (e.g. if there are two consecutive + * separators) are not allowed. + * + * TODO(b/37244157): we should make this more strict. Right now, it allows + * non-identifier path components, even if they aren't escaped. + */ + static fromServerFormat(path) { + const segments = []; + let current = ''; + let i = 0; + const addCurrentSegment = () => { + if (current.length === 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid field path (${path}). Paths must not be empty, begin ` + + `with '.', end with '.', or contain '..'`); + } + segments.push(current); + current = ''; + }; + let inBackticks = false; + while (i < path.length) { + const c = path[i]; + if (c === '\\') { + if (i + 1 === path.length) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has trailing escape character: ' + path); + } + const next = path[i + 1]; + if (!(next === '\\' || next === '.' || next === '`')) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Path has invalid escape sequence: ' + path); + } + current += next; + i += 2; + } + else if (c === '`') { + inBackticks = !inBackticks; + i++; + } + else if (c === '.' && !inBackticks) { + addCurrentSegment(); + i++; + } + else { + current += c; + i++; + } + } + addCurrentSegment(); + if (inBackticks) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Unterminated ` in path: ' + path); + } + return new FieldPath$1(segments); + } + static emptyPath() { + return new FieldPath$1([]); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @internal + */ +class DocumentKey { + constructor(path) { + this.path = path; + } + static fromPath(path) { + return new DocumentKey(ResourcePath.fromString(path)); + } + static fromName(name) { + return new DocumentKey(ResourcePath.fromString(name).popFirst(5)); + } + static empty() { + return new DocumentKey(ResourcePath.emptyPath()); + } + get collectionGroup() { + return this.path.popLast().lastSegment(); + } + /** Returns true if the document is in the specified collectionId. */ + hasCollectionId(collectionId) { + return (this.path.length >= 2 && + this.path.get(this.path.length - 2) === collectionId); + } + /** Returns the collection group (i.e. the name of the parent collection) for this key. */ + getCollectionGroup() { + return this.path.get(this.path.length - 2); + } + /** Returns the fully qualified path to the parent collection. */ + getCollectionPath() { + return this.path.popLast(); + } + isEqual(other) { + return (other !== null && ResourcePath.comparator(this.path, other.path) === 0); + } + toString() { + return this.path.toString(); + } + static comparator(k1, k2) { + return ResourcePath.comparator(k1.path, k2.path); + } + static isDocumentKey(path) { + return path.length % 2 === 0; + } + /** + * Creates and returns a new document key with the given segments. + * + * @param segments - The segments of the path to the document + * @returns A new instance of DocumentKey + */ + static fromSegments(segments) { + return new DocumentKey(new ResourcePath(segments.slice())); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function validateNonEmptyArgument(functionName, argumentName, argument) { + if (!argument) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${functionName}() cannot be called with an empty ${argumentName}.`); + } +} +/** + * Validates that two boolean options are not set at the same time. + * @internal + */ +function validateIsNotUsedTogether(optionName1, argument1, optionName2, argument2) { + if (argument1 === true && argument2 === true) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `${optionName1} and ${optionName2} cannot be used together.`); + } +} +/** + * Validates that `path` refers to a document (indicated by the fact it contains + * an even numbers of segments). + */ +function validateDocumentPath(path) { + if (!DocumentKey.isDocumentKey(path)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid document reference. Document references must have an even number of segments, but ${path} has ${path.length}.`); + } +} +/** + * Validates that `path` refers to a collection (indicated by the fact it + * contains an odd numbers of segments). + */ +function validateCollectionPath(path) { + if (DocumentKey.isDocumentKey(path)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid collection reference. Collection references must have an odd number of segments, but ${path} has ${path.length}.`); + } +} +/** + * Returns true if it's a non-null object without a custom prototype + * (i.e. excludes Array, Date, etc.). + */ +function isPlainObject(input) { + return (typeof input === 'object' && + input !== null && + (Object.getPrototypeOf(input) === Object.prototype || + Object.getPrototypeOf(input) === null)); +} +/** Returns a string describing the type / value of the provided input. */ +function valueDescription(input) { + if (input === undefined) { + return 'undefined'; + } + else if (input === null) { + return 'null'; + } + else if (typeof input === 'string') { + if (input.length > 20) { + input = `${input.substring(0, 20)}...`; + } + return JSON.stringify(input); + } + else if (typeof input === 'number' || typeof input === 'boolean') { + return '' + input; + } + else if (typeof input === 'object') { + if (input instanceof Array) { + return 'an array'; + } + else { + const customObjectName = tryGetCustomObjectType(input); + if (customObjectName) { + return `a custom ${customObjectName} object`; + } + else { + return 'an object'; + } + } + } + else if (typeof input === 'function') { + return 'a function'; + } + else { + return fail(0x3029, { type: typeof input }); + } +} +/** try to get the constructor name for an object. */ +function tryGetCustomObjectType(input) { + if (input.constructor) { + return input.constructor.name; + } + return null; +} +/** + * Casts `obj` to `T`, optionally unwrapping Compat types to expose the + * underlying instance. Throws if `obj` is not an instance of `T`. + * + * This cast is used in the Lite and Full SDK to verify instance types for + * arguments passed to the public API. + * @internal + */ +function cast(obj, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +constructor) { + if ('_delegate' in obj) { + // Unwrap Compat types + // eslint-disable-next-line @typescript-eslint/no-explicit-any + obj = obj._delegate; + } + if (!(obj instanceof constructor)) { + if (constructor.name === obj.constructor.name) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Type does not match the expected instance. Did you pass a ' + + `reference from a different Firestore SDK?`); + } + else { + const description = valueDescription(obj); + throw new FirestoreError(Code.INVALID_ARGUMENT, `Expected type '${constructor.name}', but it was: ${description}`); + } + } + return obj; +} +function validatePositiveNumber(functionName, n) { + if (n <= 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${functionName}() requires a positive number, but it was: ${n}.`); + } +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Compares two `ExperimentalLongPollingOptions` objects for equality. + */ +function longPollingOptionsEqual(options1, options2) { + return options1.timeoutSeconds === options2.timeoutSeconds; +} +/** + * Creates and returns a new `ExperimentalLongPollingOptions` with the same + * option values as the given instance. + */ +function cloneLongPollingOptions(options) { + const clone = {}; + if (options.timeoutSeconds !== undefined) { + clone.timeoutSeconds = options.timeoutSeconds; + } + return clone; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The value returned from the most recent invocation of + * `generateUniqueDebugId()`, or null if it has never been invoked. + */ +let lastUniqueDebugId = null; +/** + * Generates and returns an initial value for `lastUniqueDebugId`. + * + * The returned value is randomly selected from a range of integers that are + * represented as 8 hexadecimal digits. This means that (within reason) any + * numbers generated by incrementing the returned number by 1 will also be + * represented by 8 hexadecimal digits. This leads to all "IDs" having the same + * length when converted to a hexadecimal string, making reading logs containing + * these IDs easier to follow. And since the return value is randomly selected + * it will help to differentiate between logs from different executions. + */ +function generateInitialUniqueDebugId() { + const minResult = 0x10000000; + const maxResult = 0x90000000; + const resultRange = maxResult - minResult; + const resultOffset = Math.round(resultRange * Math.random()); + return minResult + resultOffset; +} +/** + * Generates and returns a unique ID as a hexadecimal string. + * + * The returned ID is intended to be used in debug logging messages to help + * correlate log messages that may be spatially separated in the logs, but + * logically related. For example, a network connection could include the same + * "debug ID" string in all of its log messages to help trace a specific + * connection over time. + * + * @return the 10-character generated ID (e.g. "0xa1b2c3d4"). + */ +function generateUniqueDebugId() { + if (lastUniqueDebugId === null) { + lastUniqueDebugId = generateInitialUniqueDebugId(); + } + else { + lastUniqueDebugId++; + } + return '0x' + lastUniqueDebugId.toString(16); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$3 = 'RestConnection'; +/** + * Maps RPC names to the corresponding REST endpoint name. + * + * We use array notation to avoid mangling. + */ +const RPC_NAME_URL_MAPPING = {}; +RPC_NAME_URL_MAPPING['BatchGetDocuments'] = 'batchGet'; +RPC_NAME_URL_MAPPING['Commit'] = 'commit'; +RPC_NAME_URL_MAPPING['RunQuery'] = 'runQuery'; +RPC_NAME_URL_MAPPING['RunAggregationQuery'] = 'runAggregationQuery'; +const RPC_URL_VERSION = 'v1'; +// SDK_VERSION is updated to different value at runtime depending on the entry point, +// so we need to get its value when we need it in a function. +function getGoogApiClientValue() { + return 'gl-js/ fire/' + SDK_VERSION; +} +/** + * Base class for all Rest-based connections to the backend (WebChannel and + * HTTP). + */ +class RestConnection { + get shouldResourcePathBeIncludedInRequest() { + // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine + // where to run the query, and expect the `request` to NOT specify the "path". + return false; + } + constructor(databaseInfo) { + this.databaseInfo = databaseInfo; + this.databaseId = databaseInfo.databaseId; + const proto = databaseInfo.ssl ? 'https' : 'http'; + const projectId = encodeURIComponent(this.databaseId.projectId); + const databaseId = encodeURIComponent(this.databaseId.database); + this.baseUrl = proto + '://' + databaseInfo.host; + this.databasePath = `projects/${projectId}/databases/${databaseId}`; + this.requestParams = + this.databaseId.database === DEFAULT_DATABASE_NAME + ? `project_id=${projectId}` + : `project_id=${projectId}&database_id=${databaseId}`; + } + invokeRPC(rpcName, path, req, authToken, appCheckToken) { + const streamId = generateUniqueDebugId(); + const url = this.makeUrl(rpcName, path.toUriEncodedString()); + logDebug(LOG_TAG$3, `Sending RPC '${rpcName}' ${streamId}:`, url, req); + const headers = { + 'google-cloud-resource-prefix': this.databasePath, + 'x-goog-request-params': this.requestParams + }; + this.modifyHeadersForRequest(headers, authToken, appCheckToken); + const { host } = new URL(url); + const forwardCredentials = isCloudWorkstation(host); + return this.performRPCRequest(rpcName, url, headers, req, forwardCredentials).then(response => { + logDebug(LOG_TAG$3, `Received RPC '${rpcName}' ${streamId}: `, response); + return response; + }, (err) => { + logWarn(LOG_TAG$3, `RPC '${rpcName}' ${streamId} failed with error: `, err, 'url: ', url, 'request:', req); + throw err; + }); + } + invokeStreamingRPC(rpcName, path, request, authToken, appCheckToken, expectedResponseCount) { + // The REST API automatically aggregates all of the streamed results, so we + // can just use the normal invoke() method. + return this.invokeRPC(rpcName, path, request, authToken, appCheckToken); + } + /** + * Modifies the headers for a request, adding any authorization token if + * present and any additional headers for the request. + */ + modifyHeadersForRequest(headers, authToken, appCheckToken) { + headers['X-Goog-Api-Client'] = getGoogApiClientValue(); + // Content-Type: text/plain will avoid preflight requests which might + // mess with CORS and redirects by proxies. If we add custom headers + // we will need to change this code to potentially use the $httpOverwrite + // parameter supported by ESF to avoid triggering preflight requests. + headers['Content-Type'] = 'text/plain'; + if (this.databaseInfo.appId) { + headers['X-Firebase-GMPID'] = this.databaseInfo.appId; + } + if (authToken) { + authToken.headers.forEach((value, key) => (headers[key] = value)); + } + if (appCheckToken) { + appCheckToken.headers.forEach((value, key) => (headers[key] = value)); + } + } + makeUrl(rpcName, path) { + const urlRpcName = RPC_NAME_URL_MAPPING[rpcName]; + return `${this.baseUrl}/${RPC_URL_VERSION}/${path}:${urlRpcName}`; + } + /** + * Closes and cleans up any resources associated with the connection. This + * implementation is a no-op because there are no resources associated + * with the RestConnection that need to be cleaned up. + */ + terminate() { + // No-op + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Error Codes describing the different ways GRPC can fail. These are copied + * directly from GRPC's sources here: + * + * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h + * + * Important! The names of these identifiers matter because the string forms + * are used for reverse lookups from the webchannel stream. Do NOT change the + * names of these identifiers or change this into a const enum. + */ +var RpcCode; +(function (RpcCode) { + RpcCode[RpcCode["OK"] = 0] = "OK"; + RpcCode[RpcCode["CANCELLED"] = 1] = "CANCELLED"; + RpcCode[RpcCode["UNKNOWN"] = 2] = "UNKNOWN"; + RpcCode[RpcCode["INVALID_ARGUMENT"] = 3] = "INVALID_ARGUMENT"; + RpcCode[RpcCode["DEADLINE_EXCEEDED"] = 4] = "DEADLINE_EXCEEDED"; + RpcCode[RpcCode["NOT_FOUND"] = 5] = "NOT_FOUND"; + RpcCode[RpcCode["ALREADY_EXISTS"] = 6] = "ALREADY_EXISTS"; + RpcCode[RpcCode["PERMISSION_DENIED"] = 7] = "PERMISSION_DENIED"; + RpcCode[RpcCode["UNAUTHENTICATED"] = 16] = "UNAUTHENTICATED"; + RpcCode[RpcCode["RESOURCE_EXHAUSTED"] = 8] = "RESOURCE_EXHAUSTED"; + RpcCode[RpcCode["FAILED_PRECONDITION"] = 9] = "FAILED_PRECONDITION"; + RpcCode[RpcCode["ABORTED"] = 10] = "ABORTED"; + RpcCode[RpcCode["OUT_OF_RANGE"] = 11] = "OUT_OF_RANGE"; + RpcCode[RpcCode["UNIMPLEMENTED"] = 12] = "UNIMPLEMENTED"; + RpcCode[RpcCode["INTERNAL"] = 13] = "INTERNAL"; + RpcCode[RpcCode["UNAVAILABLE"] = 14] = "UNAVAILABLE"; + RpcCode[RpcCode["DATA_LOSS"] = 15] = "DATA_LOSS"; +})(RpcCode || (RpcCode = {})); +/** + * Determines whether an error code represents a permanent error when received + * in response to a non-write operation. + * + * See isPermanentWriteError for classifying write errors. + */ +function isPermanentError(code) { + switch (code) { + case Code.OK: + return fail(0xfdaa); + case Code.CANCELLED: + case Code.UNKNOWN: + case Code.DEADLINE_EXCEEDED: + case Code.RESOURCE_EXHAUSTED: + case Code.INTERNAL: + case Code.UNAVAILABLE: + // Unauthenticated means something went wrong with our token and we need + // to retry with new credentials which will happen automatically. + case Code.UNAUTHENTICATED: + return false; + case Code.INVALID_ARGUMENT: + case Code.NOT_FOUND: + case Code.ALREADY_EXISTS: + case Code.PERMISSION_DENIED: + case Code.FAILED_PRECONDITION: + // Aborted might be retried in some scenarios, but that is dependent on + // the context and should handled individually by the calling code. + // See https://cloud.google.com/apis/design/errors. + case Code.ABORTED: + case Code.OUT_OF_RANGE: + case Code.UNIMPLEMENTED: + case Code.DATA_LOSS: + return true; + default: + return fail(0x3c6b, { code }); + } +} +/** + * Converts an HTTP Status Code to the equivalent error code. + * + * @param status - An HTTP Status Code, like 200, 404, 503, etc. + * @returns The equivalent Code. Unknown status codes are mapped to + * Code.UNKNOWN. + */ +function mapCodeFromHttpStatus(status) { + if (status === undefined) { + logError('RPC_ERROR', 'HTTP error has no status'); + return Code.UNKNOWN; + } + // The canonical error codes for Google APIs [1] specify mapping onto HTTP + // status codes but the mapping is not bijective. In each case of ambiguity + // this function chooses a primary error. + // + // [1] + // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto + switch (status) { + case 200: // OK + return Code.OK; + case 400: // Bad Request + return Code.FAILED_PRECONDITION; + // Other possibilities based on the forward mapping + // return Code.INVALID_ARGUMENT; + // return Code.OUT_OF_RANGE; + case 401: // Unauthorized + return Code.UNAUTHENTICATED; + case 403: // Forbidden + return Code.PERMISSION_DENIED; + case 404: // Not Found + return Code.NOT_FOUND; + case 409: // Conflict + return Code.ABORTED; + // Other possibilities: + // return Code.ALREADY_EXISTS; + case 416: // Range Not Satisfiable + return Code.OUT_OF_RANGE; + case 429: // Too Many Requests + return Code.RESOURCE_EXHAUSTED; + case 499: // Client Closed Request + return Code.CANCELLED; + case 500: // Internal Server Error + return Code.UNKNOWN; + // Other possibilities: + // return Code.INTERNAL; + // return Code.DATA_LOSS; + case 501: // Unimplemented + return Code.UNIMPLEMENTED; + case 503: // Service Unavailable + return Code.UNAVAILABLE; + case 504: // Gateway Timeout + return Code.DEADLINE_EXCEEDED; + default: + if (status >= 200 && status < 300) { + return Code.OK; + } + if (status >= 400 && status < 500) { + return Code.FAILED_PRECONDITION; + } + if (status >= 500 && status < 600) { + return Code.INTERNAL; + } + return Code.UNKNOWN; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A Rest-based connection that relies on the native HTTP stack + * (e.g. `fetch` or a polyfill). + */ +class FetchConnection extends RestConnection { + openStream(rpcName, token) { + throw new Error('Not supported by FetchConnection'); + } + async performRPCRequest(rpcName, url, headers, body, forwardCredentials) { + const requestJson = JSON.stringify(body); + let response; + try { + const fetchArgs = { + method: 'POST', + headers, + body: requestJson + }; + if (forwardCredentials) { + fetchArgs.credentials = 'include'; + } + response = await fetch(url, fetchArgs); + } + catch (e) { + const err = e; + throw new FirestoreError(mapCodeFromHttpStatus(err.status), 'Request failed with error: ' + err.statusText); + } + if (!response.ok) { + let errorResponse = await response.json(); + if (Array.isArray(errorResponse)) { + errorResponse = errorResponse[0]; + } + const errorMessage = errorResponse?.error?.message; + throw new FirestoreError(mapCodeFromHttpStatus(response.status), `Request failed with error: ${errorMessage ?? response.statusText}`); + } + return response.json(); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Initializes the HTTP connection for the REST API. */ +function newConnection(databaseInfo) { + return new FetchConnection(databaseInfo); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function objectSize(obj) { + let count = 0; + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + count++; + } + } + return count; +} +function forEach(obj, fn) { + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + fn(key, obj[key]); + } + } +} +function mapToArray(obj, fn) { + const result = []; + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + result.push(fn(obj[key], key, obj)); + } + } + return result; +} +function isEmpty(obj) { + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + return false; + } + } + return true; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns whether a variable is either undefined or null. + */ +function isNullOrUndefined(value) { + return value === null || value === undefined; +} +/** Returns whether the value represents -0. */ +function isNegativeZero(value) { + // Detect if the value is -0.0. Based on polyfill from + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is + return value === 0 && 1 / value === 1 / -0; +} +/** + * Returns whether a value is an integer and in the safe integer range + * @param value - The value to test for being an integer and in the safe range + */ +function isSafeInteger(value) { + return (typeof value === 'number' && + Number.isInteger(value) && + !isNegativeZero(value) && + value <= Number.MAX_SAFE_INTEGER && + value >= Number.MIN_SAFE_INTEGER); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Converts a Base64 encoded string to a binary string. */ +function decodeBase64(encoded) { + // Note: We used to validate the base64 string here via a regular expression. + // This was removed to improve the performance of indexing. + return Buffer.from(encoded, 'base64').toString('binary'); +} +/** Converts a binary string to a Base64 encoded string. */ +function encodeBase64(raw) { + return Buffer.from(raw, 'binary').toString('base64'); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Immutable class that represents a "proto" byte string. + * + * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when + * sent on the wire. This class abstracts away this differentiation by holding + * the proto byte string in a common class that must be converted into a string + * before being sent as a proto. + * @internal + */ +class ByteString { + constructor(binaryString) { + this.binaryString = binaryString; + } + static fromBase64String(base64) { + const binaryString = decodeBase64(base64); + return new ByteString(binaryString); + } + static fromUint8Array(array) { + // TODO(indexing); Remove the copy of the byte string here as this method + // is frequently called during indexing. + const binaryString = binaryStringFromUint8Array(array); + return new ByteString(binaryString); + } + [Symbol.iterator]() { + let i = 0; + return { + next: () => { + if (i < this.binaryString.length) { + return { value: this.binaryString.charCodeAt(i++), done: false }; + } + else { + return { value: undefined, done: true }; + } + } + }; + } + toBase64() { + return encodeBase64(this.binaryString); + } + toUint8Array() { + return uint8ArrayFromBinaryString(this.binaryString); + } + approximateByteSize() { + return this.binaryString.length * 2; + } + compareTo(other) { + return primitiveComparator(this.binaryString, other.binaryString); + } + isEqual(other) { + return this.binaryString === other.binaryString; + } +} +ByteString.EMPTY_BYTE_STRING = new ByteString(''); +/** + * Helper function to convert an Uint8array to a binary string. + */ +function binaryStringFromUint8Array(array) { + let binaryString = ''; + for (let i = 0; i < array.length; ++i) { + binaryString += String.fromCharCode(array[i]); + } + return binaryString; +} +/** + * Helper function to convert a binary string to an Uint8Array. + */ +function uint8ArrayFromBinaryString(binaryString) { + const buffer = new Uint8Array(binaryString.length); + for (let i = 0; i < binaryString.length; i++) { + buffer[i] = binaryString.charCodeAt(i); + } + return buffer; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// A RegExp matching ISO 8601 UTC timestamps with optional fraction. +const ISO_TIMESTAMP_REG_EXP = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/); +/** + * Converts the possible Proto values for a timestamp value into a "seconds and + * nanos" representation. + */ +function normalizeTimestamp(date) { + hardAssert(!!date, 0x986a); + // The json interface (for the browser) will return an iso timestamp string, + // while the proto js library (for node) will return a + // google.protobuf.Timestamp instance. + if (typeof date === 'string') { + // The date string can have higher precision (nanos) than the Date class + // (millis), so we do some custom parsing here. + // Parse the nanos right out of the string. + let nanos = 0; + const fraction = ISO_TIMESTAMP_REG_EXP.exec(date); + hardAssert(!!fraction, 0xb5de, { + timestamp: date + }); + if (fraction[1]) { + // Pad the fraction out to 9 digits (nanos). + let nanoStr = fraction[1]; + nanoStr = (nanoStr + '000000000').substr(0, 9); + nanos = Number(nanoStr); + } + // Parse the date to get the seconds. + const parsedDate = new Date(date); + const seconds = Math.floor(parsedDate.getTime() / 1000); + return { seconds, nanos }; + } + else { + // TODO(b/37282237): Use strings for Proto3 timestamps + // assert(!this.options.useProto3Json, + // 'The timestamp instance format requires Proto JS.'); + const seconds = normalizeNumber(date.seconds); + const nanos = normalizeNumber(date.nanos); + return { seconds, nanos }; + } +} +/** + * Converts the possible Proto types for numbers into a JavaScript number. + * Returns 0 if the value is not numeric. + */ +function normalizeNumber(value) { + // TODO(bjornick): Handle int64 greater than 53 bits. + if (typeof value === 'number') { + return value; + } + else if (typeof value === 'string') { + return Number(value); + } + else { + return 0; + } +} +/** Converts the possible Proto types for Blobs into a ByteString. */ +function normalizeByteString(blob) { + if (typeof blob === 'string') { + return ByteString.fromBase64String(blob); + } + else { + return ByteString.fromUint8Array(blob); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Helper function to define a JSON schema {@link Property}. + * @private + * @internal + */ +function property(typeString, optionalValue) { + const result = { + typeString + }; + if (optionalValue) { + result.value = optionalValue; + } + return result; +} +/** + * Validates the JSON object based on the provided schema, and narrows the type to the provided + * JSON schema. + * @private + * @internal + * + * @param json A JSON object to validate. + * @param scheme a {@link JsonSchema} that defines the properties to validate. + * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise. + */ +function validateJSON(json, schema) { + if (!isPlainObject(json)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'JSON must be an object'); + } + let error = undefined; + for (const key in schema) { + if (schema[key]) { + const typeString = schema[key].typeString; + const value = 'value' in schema[key] ? { value: schema[key].value } : undefined; + if (!(key in json)) { + error = `JSON missing required field: '${key}'`; + break; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const fieldValue = json[key]; + if (typeString && typeof fieldValue !== typeString) { + error = `JSON field '${key}' must be a ${typeString}.`; + break; + } + else if (value !== undefined && fieldValue !== value.value) { + error = `Expected '${key}' field to equal '${value.value}'`; + break; + } + } + } + if (error) { + throw new FirestoreError(Code.INVALID_ARGUMENT, error); + } + return true; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z). +const MIN_SECONDS = -62135596800; +// Number of nanoseconds in a millisecond. +const MS_TO_NANOS = 1e6; +/** + * A `Timestamp` represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. + * + * It is encoded using the Proleptic Gregorian Calendar which extends the + * Gregorian calendar backwards to year one. It is encoded assuming all minutes + * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59.999999999Z. + * + * For examples and further specifications, refer to the + * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. + */ +class Timestamp { + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns a new timestamp representing the current date. + */ + static now() { + return Timestamp.fromMillis(Date.now()); + } + /** + * Creates a new timestamp from the given date. + * + * @param date - The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the given + * date. + */ + static fromDate(date) { + return Timestamp.fromMillis(date.getTime()); + } + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds - Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the given + * number of milliseconds. + */ + static fromMillis(milliseconds) { + const seconds = Math.floor(milliseconds / 1000); + const nanos = Math.floor((milliseconds - seconds * 1000) * MS_TO_NANOS); + return new Timestamp(seconds, nanos); + } + /** + * Creates a new timestamp. + * + * @param seconds - The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds - The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ + constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + seconds, + /** + * The fractions of a second at nanosecond resolution.* + */ + nanoseconds) { + this.seconds = seconds; + this.nanoseconds = nanoseconds; + if (nanoseconds < 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp nanoseconds out of range: ' + nanoseconds); + } + if (nanoseconds >= 1e9) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp nanoseconds out of range: ' + nanoseconds); + } + if (seconds < MIN_SECONDS) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp seconds out of range: ' + seconds); + } + // This will break in the year 10,000. + if (seconds >= 253402300800) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Timestamp seconds out of range: ' + seconds); + } + } + /** + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ + toDate() { + return new Date(this.toMillis()); + } + /** + * Converts a `Timestamp` to a numeric timestamp (in milliseconds since + * epoch). This operation causes a loss of precision. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ + toMillis() { + return this.seconds * 1000 + this.nanoseconds / MS_TO_NANOS; + } + _compareTo(other) { + if (this.seconds === other.seconds) { + return primitiveComparator(this.nanoseconds, other.nanoseconds); + } + return primitiveComparator(this.seconds, other.seconds); + } + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other - The `Timestamp` to compare against. + * @returns true if this `Timestamp` is equal to the provided one. + */ + isEqual(other) { + return (other.seconds === this.seconds && other.nanoseconds === this.nanoseconds); + } + /** Returns a textual representation of this `Timestamp`. */ + toString() { + return ('Timestamp(seconds=' + + this.seconds + + ', nanoseconds=' + + this.nanoseconds + + ')'); + } + /** + * Returns a JSON-serializable representation of this `Timestamp`. + */ + toJSON() { + return { + type: Timestamp._jsonSchemaVersion, + seconds: this.seconds, + nanoseconds: this.nanoseconds + }; + } + /** + * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}. + */ + static fromJSON(json) { + if (validateJSON(json, Timestamp._jsonSchema)) { + return new Timestamp(json.seconds, json.nanoseconds); + } + } + /** + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. + */ + valueOf() { + // This method returns a string of the form . where + // is translated to have a non-negative value and both + // and are left-padded with zeroes to be a consistent length. + // Strings with this format then have a lexicographical ordering that matches + // the expected ordering. The translation is done to avoid having + // a leading negative sign (i.e. a leading '-' character) in its string + // representation, which would affect its lexicographical ordering. + const adjustedSeconds = this.seconds - MIN_SECONDS; + // Note: Up to 12 decimal digits are required to represent all valid + // 'seconds' values. + const formattedSeconds = String(adjustedSeconds).padStart(12, '0'); + const formattedNanoseconds = String(this.nanoseconds).padStart(9, '0'); + return formattedSeconds + '.' + formattedNanoseconds; + } +} +Timestamp._jsonSchemaVersion = 'firestore/timestamp/1.0'; +Timestamp._jsonSchema = { + type: property('string', Timestamp._jsonSchemaVersion), + seconds: property('number'), + nanoseconds: property('number') +}; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a locally-applied ServerTimestamp. + * + * Server Timestamps are backed by MapValues that contain an internal field + * `__type__` with a value of `server_timestamp`. The previous value and local + * write time are stored in its `__previous_value__` and `__local_write_time__` + * fields respectively. + * + * Notes: + * - ServerTimestampValue instances are created as the result of applying a + * transform. They can only exist in the local view of a document. Therefore + * they do not need to be parsed or serialized. + * - When evaluated locally (e.g. for snapshot.data()), they by default + * evaluate to `null`. This behavior can be configured by passing custom + * FieldValueOptions to value(). + * - With respect to other ServerTimestampValues, they sort by their + * localWriteTime. + */ +const SERVER_TIMESTAMP_SENTINEL = 'server_timestamp'; +const TYPE_KEY$1 = '__type__'; +const PREVIOUS_VALUE_KEY = '__previous_value__'; +const LOCAL_WRITE_TIME_KEY = '__local_write_time__'; +function isServerTimestamp(value) { + const type = (value?.mapValue?.fields || {})[TYPE_KEY$1]?.stringValue; + return type === SERVER_TIMESTAMP_SENTINEL; +} +/** + * Returns the value of the field before this ServerTimestamp was set. + * + * Preserving the previous values allows the user to display the last resoled + * value until the backend responds with the timestamp. + */ +function getPreviousValue(value) { + const previousValue = value.mapValue.fields[PREVIOUS_VALUE_KEY]; + if (isServerTimestamp(previousValue)) { + return getPreviousValue(previousValue); + } + return previousValue; +} +/** + * Returns the local time at which this timestamp was first set. + */ +function getLocalWriteTime(value) { + const localWriteTime = normalizeTimestamp(value.mapValue.fields[LOCAL_WRITE_TIME_KEY].timestampValue); + return new Timestamp(localWriteTime.seconds, localWriteTime.nanos); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const TYPE_KEY = '__type__'; +const MAX_VALUE_TYPE = '__max__'; +const MAX_VALUE = { + mapValue: { + fields: { + '__type__': { stringValue: MAX_VALUE_TYPE } + } + } +}; +const VECTOR_VALUE_SENTINEL = '__vector__'; +const VECTOR_MAP_VECTORS_KEY = 'value'; +/** Extracts the backend's type order for the provided value. */ +function typeOrder(value) { + if ('nullValue' in value) { + return 0 /* TypeOrder.NullValue */; + } + else if ('booleanValue' in value) { + return 1 /* TypeOrder.BooleanValue */; + } + else if ('integerValue' in value || 'doubleValue' in value) { + return 2 /* TypeOrder.NumberValue */; + } + else if ('timestampValue' in value) { + return 3 /* TypeOrder.TimestampValue */; + } + else if ('stringValue' in value) { + return 5 /* TypeOrder.StringValue */; + } + else if ('bytesValue' in value) { + return 6 /* TypeOrder.BlobValue */; + } + else if ('referenceValue' in value) { + return 7 /* TypeOrder.RefValue */; + } + else if ('geoPointValue' in value) { + return 8 /* TypeOrder.GeoPointValue */; + } + else if ('arrayValue' in value) { + return 9 /* TypeOrder.ArrayValue */; + } + else if ('mapValue' in value) { + if (isServerTimestamp(value)) { + return 4 /* TypeOrder.ServerTimestampValue */; + } + else if (isMaxValue(value)) { + return 9007199254740991 /* TypeOrder.MaxValue */; + } + else if (isVectorValue(value)) { + return 10 /* TypeOrder.VectorValue */; + } + return 11 /* TypeOrder.ObjectValue */; + } + else { + return fail(0x6e87, { value }); + } +} +/** Tests `left` and `right` for equality based on the backend semantics. */ +function valueEquals(left, right) { + if (left === right) { + return true; + } + const leftType = typeOrder(left); + const rightType = typeOrder(right); + if (leftType !== rightType) { + return false; + } + switch (leftType) { + case 0 /* TypeOrder.NullValue */: + return true; + case 1 /* TypeOrder.BooleanValue */: + return left.booleanValue === right.booleanValue; + case 4 /* TypeOrder.ServerTimestampValue */: + return getLocalWriteTime(left).isEqual(getLocalWriteTime(right)); + case 3 /* TypeOrder.TimestampValue */: + return timestampEquals(left, right); + case 5 /* TypeOrder.StringValue */: + return left.stringValue === right.stringValue; + case 6 /* TypeOrder.BlobValue */: + return blobEquals(left, right); + case 7 /* TypeOrder.RefValue */: + return left.referenceValue === right.referenceValue; + case 8 /* TypeOrder.GeoPointValue */: + return geoPointEquals(left, right); + case 2 /* TypeOrder.NumberValue */: + return numberEquals(left, right); + case 9 /* TypeOrder.ArrayValue */: + return arrayEquals(left.arrayValue.values || [], right.arrayValue.values || [], valueEquals); + case 10 /* TypeOrder.VectorValue */: + case 11 /* TypeOrder.ObjectValue */: + return objectEquals(left, right); + case 9007199254740991 /* TypeOrder.MaxValue */: + return true; + default: + return fail(0xcbf8, { left }); + } +} +function timestampEquals(left, right) { + if (typeof left.timestampValue === 'string' && + typeof right.timestampValue === 'string' && + left.timestampValue.length === right.timestampValue.length) { + // Use string equality for ISO 8601 timestamps + return left.timestampValue === right.timestampValue; + } + const leftTimestamp = normalizeTimestamp(left.timestampValue); + const rightTimestamp = normalizeTimestamp(right.timestampValue); + return (leftTimestamp.seconds === rightTimestamp.seconds && + leftTimestamp.nanos === rightTimestamp.nanos); +} +function geoPointEquals(left, right) { + return (normalizeNumber(left.geoPointValue.latitude) === + normalizeNumber(right.geoPointValue.latitude) && + normalizeNumber(left.geoPointValue.longitude) === + normalizeNumber(right.geoPointValue.longitude)); +} +function blobEquals(left, right) { + return normalizeByteString(left.bytesValue).isEqual(normalizeByteString(right.bytesValue)); +} +function numberEquals(left, right) { + if ('integerValue' in left && 'integerValue' in right) { + return (normalizeNumber(left.integerValue) === normalizeNumber(right.integerValue)); + } + else if ('doubleValue' in left && 'doubleValue' in right) { + const n1 = normalizeNumber(left.doubleValue); + const n2 = normalizeNumber(right.doubleValue); + if (n1 === n2) { + return isNegativeZero(n1) === isNegativeZero(n2); + } + else { + return isNaN(n1) && isNaN(n2); + } + } + return false; +} +function objectEquals(left, right) { + const leftMap = left.mapValue.fields || {}; + const rightMap = right.mapValue.fields || {}; + if (objectSize(leftMap) !== objectSize(rightMap)) { + return false; + } + for (const key in leftMap) { + if (leftMap.hasOwnProperty(key)) { + if (rightMap[key] === undefined || + !valueEquals(leftMap[key], rightMap[key])) { + return false; + } + } + } + return true; +} +/** Returns true if the ArrayValue contains the specified element. */ +function arrayValueContains(haystack, needle) { + return ((haystack.values || []).find(v => valueEquals(v, needle)) !== undefined); +} +function valueCompare(left, right) { + if (left === right) { + return 0; + } + const leftType = typeOrder(left); + const rightType = typeOrder(right); + if (leftType !== rightType) { + return primitiveComparator(leftType, rightType); + } + switch (leftType) { + case 0 /* TypeOrder.NullValue */: + case 9007199254740991 /* TypeOrder.MaxValue */: + return 0; + case 1 /* TypeOrder.BooleanValue */: + return primitiveComparator(left.booleanValue, right.booleanValue); + case 2 /* TypeOrder.NumberValue */: + return compareNumbers(left, right); + case 3 /* TypeOrder.TimestampValue */: + return compareTimestamps(left.timestampValue, right.timestampValue); + case 4 /* TypeOrder.ServerTimestampValue */: + return compareTimestamps(getLocalWriteTime(left), getLocalWriteTime(right)); + case 5 /* TypeOrder.StringValue */: + return compareUtf8Strings(left.stringValue, right.stringValue); + case 6 /* TypeOrder.BlobValue */: + return compareBlobs(left.bytesValue, right.bytesValue); + case 7 /* TypeOrder.RefValue */: + return compareReferences(left.referenceValue, right.referenceValue); + case 8 /* TypeOrder.GeoPointValue */: + return compareGeoPoints(left.geoPointValue, right.geoPointValue); + case 9 /* TypeOrder.ArrayValue */: + return compareArrays(left.arrayValue, right.arrayValue); + case 10 /* TypeOrder.VectorValue */: + return compareVectors(left.mapValue, right.mapValue); + case 11 /* TypeOrder.ObjectValue */: + return compareMaps(left.mapValue, right.mapValue); + default: + throw fail(0x5ae0, { leftType }); + } +} +function compareNumbers(left, right) { + const leftNumber = normalizeNumber(left.integerValue || left.doubleValue); + const rightNumber = normalizeNumber(right.integerValue || right.doubleValue); + if (leftNumber < rightNumber) { + return -1; + } + else if (leftNumber > rightNumber) { + return 1; + } + else if (leftNumber === rightNumber) { + return 0; + } + else { + // one or both are NaN. + if (isNaN(leftNumber)) { + return isNaN(rightNumber) ? 0 : -1; + } + else { + return 1; + } + } +} +function compareTimestamps(left, right) { + if (typeof left === 'string' && + typeof right === 'string' && + left.length === right.length) { + return primitiveComparator(left, right); + } + const leftTimestamp = normalizeTimestamp(left); + const rightTimestamp = normalizeTimestamp(right); + const comparison = primitiveComparator(leftTimestamp.seconds, rightTimestamp.seconds); + if (comparison !== 0) { + return comparison; + } + return primitiveComparator(leftTimestamp.nanos, rightTimestamp.nanos); +} +function compareReferences(leftPath, rightPath) { + const leftSegments = leftPath.split('/'); + const rightSegments = rightPath.split('/'); + for (let i = 0; i < leftSegments.length && i < rightSegments.length; i++) { + const comparison = primitiveComparator(leftSegments[i], rightSegments[i]); + if (comparison !== 0) { + return comparison; + } + } + return primitiveComparator(leftSegments.length, rightSegments.length); +} +function compareGeoPoints(left, right) { + const comparison = primitiveComparator(normalizeNumber(left.latitude), normalizeNumber(right.latitude)); + if (comparison !== 0) { + return comparison; + } + return primitiveComparator(normalizeNumber(left.longitude), normalizeNumber(right.longitude)); +} +function compareBlobs(left, right) { + const leftBytes = normalizeByteString(left); + const rightBytes = normalizeByteString(right); + return leftBytes.compareTo(rightBytes); +} +function compareArrays(left, right) { + const leftArray = left.values || []; + const rightArray = right.values || []; + for (let i = 0; i < leftArray.length && i < rightArray.length; ++i) { + const compare = valueCompare(leftArray[i], rightArray[i]); + if (compare) { + return compare; + } + } + return primitiveComparator(leftArray.length, rightArray.length); +} +function compareVectors(left, right) { + const leftMap = left.fields || {}; + const rightMap = right.fields || {}; + // The vector is a map, but only vector value is compared. + const leftArrayValue = leftMap[VECTOR_MAP_VECTORS_KEY]?.arrayValue; + const rightArrayValue = rightMap[VECTOR_MAP_VECTORS_KEY]?.arrayValue; + const lengthCompare = primitiveComparator(leftArrayValue?.values?.length || 0, rightArrayValue?.values?.length || 0); + if (lengthCompare !== 0) { + return lengthCompare; + } + return compareArrays(leftArrayValue, rightArrayValue); +} +function compareMaps(left, right) { + if (left === MAX_VALUE.mapValue && right === MAX_VALUE.mapValue) { + return 0; + } + else if (left === MAX_VALUE.mapValue) { + return 1; + } + else if (right === MAX_VALUE.mapValue) { + return -1; + } + const leftMap = left.fields || {}; + const leftKeys = Object.keys(leftMap); + const rightMap = right.fields || {}; + const rightKeys = Object.keys(rightMap); + // Even though MapValues are likely sorted correctly based on their insertion + // order (e.g. when received from the backend), local modifications can bring + // elements out of order. We need to re-sort the elements to ensure that + // canonical IDs are independent of insertion order. + leftKeys.sort(); + rightKeys.sort(); + for (let i = 0; i < leftKeys.length && i < rightKeys.length; ++i) { + const keyCompare = compareUtf8Strings(leftKeys[i], rightKeys[i]); + if (keyCompare !== 0) { + return keyCompare; + } + const compare = valueCompare(leftMap[leftKeys[i]], rightMap[rightKeys[i]]); + if (compare !== 0) { + return compare; + } + } + return primitiveComparator(leftKeys.length, rightKeys.length); +} +/** Returns a reference value for the provided database and key. */ +function refValue(databaseId, key) { + return { + referenceValue: `projects/${databaseId.projectId}/databases/${databaseId.database}/documents/${key.path.canonicalString()}` + }; +} +/** Returns true if `value` is an ArrayValue. */ +function isArray(value) { + return !!value && 'arrayValue' in value; +} +/** Returns true if `value` is a NullValue. */ +function isNullValue(value) { + return !!value && 'nullValue' in value; +} +/** Returns true if `value` is NaN. */ +function isNanValue(value) { + return !!value && 'doubleValue' in value && isNaN(Number(value.doubleValue)); +} +/** Returns true if `value` is a MapValue. */ +function isMapValue(value) { + return !!value && 'mapValue' in value; +} +/** Returns true if `value` is a VetorValue. */ +function isVectorValue(value) { + const type = (value?.mapValue?.fields || {})[TYPE_KEY]?.stringValue; + return type === VECTOR_VALUE_SENTINEL; +} +/** Creates a deep copy of `source`. */ +function deepClone(source) { + if (source.geoPointValue) { + return { geoPointValue: { ...source.geoPointValue } }; + } + else if (source.timestampValue && + typeof source.timestampValue === 'object') { + return { timestampValue: { ...source.timestampValue } }; + } + else if (source.mapValue) { + const target = { mapValue: { fields: {} } }; + forEach(source.mapValue.fields, (key, val) => (target.mapValue.fields[key] = deepClone(val))); + return target; + } + else if (source.arrayValue) { + const target = { arrayValue: { values: [] } }; + for (let i = 0; i < (source.arrayValue.values || []).length; ++i) { + target.arrayValue.values[i] = deepClone(source.arrayValue.values[i]); + } + return target; + } + else { + return { ...source }; + } +} +/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ +function isMaxValue(value) { + return ((((value.mapValue || {}).fields || {})['__type__'] || {}).stringValue === + MAX_VALUE_TYPE); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a bound of a query. + * + * The bound is specified with the given components representing a position and + * whether it's just before or just after the position (relative to whatever the + * query order is). + * + * The position represents a logical index position for a query. It's a prefix + * of values for the (potentially implicit) order by clauses of a query. + * + * Bound provides a function to determine whether a document comes before or + * after a bound. This is influenced by whether the position is just before or + * just after the provided values. + */ +class Bound { + constructor(position, inclusive) { + this.position = position; + this.inclusive = inclusive; + } +} +function boundEquals(left, right) { + if (left === null) { + return right === null; + } + else if (right === null) { + return false; + } + if (left.inclusive !== right.inclusive || + left.position.length !== right.position.length) { + return false; + } + for (let i = 0; i < left.position.length; i++) { + const leftPosition = left.position[i]; + const rightPosition = right.position[i]; + if (!valueEquals(leftPosition, rightPosition)) { + return false; + } + } + return true; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class Filter { +} +class FieldFilter extends Filter { + constructor(field, op, value) { + super(); + this.field = field; + this.op = op; + this.value = value; + } + /** + * Creates a filter based on the provided arguments. + */ + static create(field, op, value) { + if (field.isKeyField()) { + if (op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */) { + return this.createKeyFieldInFilter(field, op, value); + } + else { + return new KeyFieldFilter(field, op, value); + } + } + else if (op === "array-contains" /* Operator.ARRAY_CONTAINS */) { + return new ArrayContainsFilter(field, value); + } + else if (op === "in" /* Operator.IN */) { + return new InFilter(field, value); + } + else if (op === "not-in" /* Operator.NOT_IN */) { + return new NotInFilter(field, value); + } + else if (op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) { + return new ArrayContainsAnyFilter(field, value); + } + else { + return new FieldFilter(field, op, value); + } + } + static createKeyFieldInFilter(field, op, value) { + return op === "in" /* Operator.IN */ + ? new KeyFieldInFilter(field, value) + : new KeyFieldNotInFilter(field, value); + } + matches(doc) { + const other = doc.data.field(this.field); + // Types do not have to match in NOT_EQUAL filters. + if (this.op === "!=" /* Operator.NOT_EQUAL */) { + return (other !== null && + other.nullValue === undefined && + this.matchesComparison(valueCompare(other, this.value))); + } + // Only compare types with matching backend order (such as double and int). + return (other !== null && + typeOrder(this.value) === typeOrder(other) && + this.matchesComparison(valueCompare(other, this.value))); + } + matchesComparison(comparison) { + switch (this.op) { + case "<" /* Operator.LESS_THAN */: + return comparison < 0; + case "<=" /* Operator.LESS_THAN_OR_EQUAL */: + return comparison <= 0; + case "==" /* Operator.EQUAL */: + return comparison === 0; + case "!=" /* Operator.NOT_EQUAL */: + return comparison !== 0; + case ">" /* Operator.GREATER_THAN */: + return comparison > 0; + case ">=" /* Operator.GREATER_THAN_OR_EQUAL */: + return comparison >= 0; + default: + return fail(0xb8a2, { + operator: this.op + }); + } + } + isInequality() { + return ([ + "<" /* Operator.LESS_THAN */, + "<=" /* Operator.LESS_THAN_OR_EQUAL */, + ">" /* Operator.GREATER_THAN */, + ">=" /* Operator.GREATER_THAN_OR_EQUAL */, + "!=" /* Operator.NOT_EQUAL */, + "not-in" /* Operator.NOT_IN */ + ].indexOf(this.op) >= 0); + } + getFlattenedFilters() { + return [this]; + } + getFilters() { + return [this]; + } +} +class CompositeFilter extends Filter { + constructor(filters, op) { + super(); + this.filters = filters; + this.op = op; + this.memoizedFlattenedFilters = null; + } + /** + * Creates a filter based on the provided arguments. + */ + static create(filters, op) { + return new CompositeFilter(filters, op); + } + matches(doc) { + if (compositeFilterIsConjunction(this)) { + // For conjunctions, all filters must match, so return false if any filter doesn't match. + return this.filters.find(filter => !filter.matches(doc)) === undefined; + } + else { + // For disjunctions, at least one filter should match. + return this.filters.find(filter => filter.matches(doc)) !== undefined; + } + } + getFlattenedFilters() { + if (this.memoizedFlattenedFilters !== null) { + return this.memoizedFlattenedFilters; + } + this.memoizedFlattenedFilters = this.filters.reduce((result, subfilter) => { + return result.concat(subfilter.getFlattenedFilters()); + }, []); + return this.memoizedFlattenedFilters; + } + // Returns a mutable copy of `this.filters` + getFilters() { + return Object.assign([], this.filters); + } +} +function compositeFilterIsConjunction(compositeFilter) { + return compositeFilter.op === "and" /* CompositeOperator.AND */; +} +function filterEquals(f1, f2) { + if (f1 instanceof FieldFilter) { + return fieldFilterEquals(f1, f2); + } + else if (f1 instanceof CompositeFilter) { + return compositeFilterEquals(f1, f2); + } + else { + fail(0x4bef); + } +} +function fieldFilterEquals(f1, f2) { + return (f2 instanceof FieldFilter && + f1.op === f2.op && + f1.field.isEqual(f2.field) && + valueEquals(f1.value, f2.value)); +} +function compositeFilterEquals(f1, f2) { + if (f2 instanceof CompositeFilter && + f1.op === f2.op && + f1.filters.length === f2.filters.length) { + const subFiltersMatch = f1.filters.reduce((result, f1Filter, index) => result && filterEquals(f1Filter, f2.filters[index]), true); + return subFiltersMatch; + } + return false; +} +/** Filter that matches on key fields (i.e. '__name__'). */ +class KeyFieldFilter extends FieldFilter { + constructor(field, op, value) { + super(field, op, value); + this.key = DocumentKey.fromName(value.referenceValue); + } + matches(doc) { + const comparison = DocumentKey.comparator(doc.key, this.key); + return this.matchesComparison(comparison); + } +} +/** Filter that matches on key fields within an array. */ +class KeyFieldInFilter extends FieldFilter { + constructor(field, value) { + super(field, "in" /* Operator.IN */, value); + this.keys = extractDocumentKeysFromArrayValue("in" /* Operator.IN */, value); + } + matches(doc) { + return this.keys.some(key => key.isEqual(doc.key)); + } +} +/** Filter that matches on key fields not present within an array. */ +class KeyFieldNotInFilter extends FieldFilter { + constructor(field, value) { + super(field, "not-in" /* Operator.NOT_IN */, value); + this.keys = extractDocumentKeysFromArrayValue("not-in" /* Operator.NOT_IN */, value); + } + matches(doc) { + return !this.keys.some(key => key.isEqual(doc.key)); + } +} +function extractDocumentKeysFromArrayValue(op, value) { + return (value.arrayValue?.values || []).map(v => { + return DocumentKey.fromName(v.referenceValue); + }); +} +/** A Filter that implements the array-contains operator. */ +class ArrayContainsFilter extends FieldFilter { + constructor(field, value) { + super(field, "array-contains" /* Operator.ARRAY_CONTAINS */, value); + } + matches(doc) { + const other = doc.data.field(this.field); + return isArray(other) && arrayValueContains(other.arrayValue, this.value); + } +} +/** A Filter that implements the IN operator. */ +class InFilter extends FieldFilter { + constructor(field, value) { + super(field, "in" /* Operator.IN */, value); + } + matches(doc) { + const other = doc.data.field(this.field); + return other !== null && arrayValueContains(this.value.arrayValue, other); + } +} +/** A Filter that implements the not-in operator. */ +class NotInFilter extends FieldFilter { + constructor(field, value) { + super(field, "not-in" /* Operator.NOT_IN */, value); + } + matches(doc) { + if (arrayValueContains(this.value.arrayValue, { nullValue: 'NULL_VALUE' })) { + return false; + } + const other = doc.data.field(this.field); + return (other !== null && + other.nullValue === undefined && + !arrayValueContains(this.value.arrayValue, other)); + } +} +/** A Filter that implements the array-contains-any operator. */ +class ArrayContainsAnyFilter extends FieldFilter { + constructor(field, value) { + super(field, "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */, value); + } + matches(doc) { + const other = doc.data.field(this.field); + if (!isArray(other) || !other.arrayValue.values) { + return false; + } + return other.arrayValue.values.some(val => arrayValueContains(this.value.arrayValue, val)); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An ordering on a field, in some Direction. Direction defaults to ASCENDING. + */ +class OrderBy { + constructor(field, dir = "asc" /* Direction.ASCENDING */) { + this.field = field; + this.dir = dir; + } +} +function orderByEquals(left, right) { + return left.dir === right.dir && left.field.isEqual(right.field); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A version of a document in Firestore. This corresponds to the version + * timestamp, such as update_time or read_time. + */ +class SnapshotVersion { + static fromTimestamp(value) { + return new SnapshotVersion(value); + } + static min() { + return new SnapshotVersion(new Timestamp(0, 0)); + } + static max() { + return new SnapshotVersion(new Timestamp(253402300799, 1e9 - 1)); + } + constructor(timestamp) { + this.timestamp = timestamp; + } + compareTo(other) { + return this.timestamp._compareTo(other.timestamp); + } + isEqual(other) { + return this.timestamp.isEqual(other.timestamp); + } + /** Returns a number representation of the version for use in spec tests. */ + toMicroseconds() { + // Convert to microseconds. + return this.timestamp.seconds * 1e6 + this.timestamp.nanoseconds / 1000; + } + toString() { + return 'SnapshotVersion(' + this.timestamp.toString() + ')'; + } + toTimestamp() { + return this.timestamp; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// An immutable sorted map implementation, based on a Left-leaning Red-Black +// tree. +class SortedMap { + constructor(comparator, root) { + this.comparator = comparator; + this.root = root ? root : LLRBNode.EMPTY; + } + // Returns a copy of the map, with the specified key/value added or replaced. + insert(key, value) { + return new SortedMap(this.comparator, this.root + .insert(key, value, this.comparator) + .copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns a copy of the map, with the specified key removed. + remove(key) { + return new SortedMap(this.comparator, this.root + .remove(key, this.comparator) + .copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns the value of the node with the given key, or null. + get(key) { + let node = this.root; + while (!node.isEmpty()) { + const cmp = this.comparator(key, node.key); + if (cmp === 0) { + return node.value; + } + else if (cmp < 0) { + node = node.left; + } + else if (cmp > 0) { + node = node.right; + } + } + return null; + } + // Returns the index of the element in this sorted map, or -1 if it doesn't + // exist. + indexOf(key) { + // Number of nodes that were pruned when descending right + let prunedNodes = 0; + let node = this.root; + while (!node.isEmpty()) { + const cmp = this.comparator(key, node.key); + if (cmp === 0) { + return prunedNodes + node.left.size; + } + else if (cmp < 0) { + node = node.left; + } + else { + // Count all nodes left of the node plus the node itself + prunedNodes += node.left.size + 1; + node = node.right; + } + } + // Node not found + return -1; + } + isEmpty() { + return this.root.isEmpty(); + } + // Returns the total number of nodes in the map. + get size() { + return this.root.size; + } + // Returns the minimum key in the map. + minKey() { + return this.root.minKey(); + } + // Returns the maximum key in the map. + maxKey() { + return this.root.maxKey(); + } + // Traverses the map in key order and calls the specified action function + // for each key/value pair. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(action) { + return this.root.inorderTraversal(action); + } + forEach(fn) { + this.inorderTraversal((k, v) => { + fn(k, v); + return false; + }); + } + toString() { + const descriptions = []; + this.inorderTraversal((k, v) => { + descriptions.push(`${k}:${v}`); + return false; + }); + return `{${descriptions.join(', ')}}`; + } + // Traverses the map in reverse key order and calls the specified action + // function for each key/value pair. If action returns true, traversal is + // aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(action) { + return this.root.reverseTraversal(action); + } + // Returns an iterator over the SortedMap. + getIterator() { + return new SortedMapIterator(this.root, null, this.comparator, false); + } + getIteratorFrom(key) { + return new SortedMapIterator(this.root, key, this.comparator, false); + } + getReverseIterator() { + return new SortedMapIterator(this.root, null, this.comparator, true); + } + getReverseIteratorFrom(key) { + return new SortedMapIterator(this.root, key, this.comparator, true); + } +} // end SortedMap +// An iterator over an LLRBNode. +class SortedMapIterator { + constructor(node, startKey, comparator, isReverse) { + this.isReverse = isReverse; + this.nodeStack = []; + let cmp = 1; + while (!node.isEmpty()) { + cmp = startKey ? comparator(node.key, startKey) : 1; + // flip the comparison if we're going in reverse + if (startKey && isReverse) { + cmp *= -1; + } + if (cmp < 0) { + // This node is less than our start key. ignore it + if (this.isReverse) { + node = node.left; + } + else { + node = node.right; + } + } + else if (cmp === 0) { + // This node is exactly equal to our start key. Push it on the stack, + // but stop iterating; + this.nodeStack.push(node); + break; + } + else { + // This node is greater than our start key, add it to the stack and move + // to the next one + this.nodeStack.push(node); + if (this.isReverse) { + node = node.right; + } + else { + node = node.left; + } + } + } + } + getNext() { + let node = this.nodeStack.pop(); + const result = { key: node.key, value: node.value }; + if (this.isReverse) { + node = node.left; + while (!node.isEmpty()) { + this.nodeStack.push(node); + node = node.right; + } + } + else { + node = node.right; + while (!node.isEmpty()) { + this.nodeStack.push(node); + node = node.left; + } + } + return result; + } + hasNext() { + return this.nodeStack.length > 0; + } + peek() { + if (this.nodeStack.length === 0) { + return null; + } + const node = this.nodeStack[this.nodeStack.length - 1]; + return { key: node.key, value: node.value }; + } +} // end SortedMapIterator +// Represents a node in a Left-leaning Red-Black tree. +class LLRBNode { + constructor(key, value, color, left, right) { + this.key = key; + this.value = value; + this.color = color != null ? color : LLRBNode.RED; + this.left = left != null ? left : LLRBNode.EMPTY; + this.right = right != null ? right : LLRBNode.EMPTY; + this.size = this.left.size + 1 + this.right.size; + } + // Returns a copy of the current node, optionally replacing pieces of it. + copy(key, value, color, left, right) { + return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right); + } + isEmpty() { + return false; + } + // Traverses the tree in key order and calls the specified action function + // for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(action) { + return (this.left.inorderTraversal(action) || + action(this.key, this.value) || + this.right.inorderTraversal(action)); + } + // Traverses the tree in reverse key order and calls the specified action + // function for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(action) { + return (this.right.reverseTraversal(action) || + action(this.key, this.value) || + this.left.reverseTraversal(action)); + } + // Returns the minimum node in the tree. + min() { + if (this.left.isEmpty()) { + return this; + } + else { + return this.left.min(); + } + } + // Returns the maximum key in the tree. + minKey() { + return this.min().key; + } + // Returns the maximum key in the tree. + maxKey() { + if (this.right.isEmpty()) { + return this.key; + } + else { + return this.right.maxKey(); + } + } + // Returns new tree, with the key/value added. + insert(key, value, comparator) { + let n = this; + const cmp = comparator(key, n.key); + if (cmp < 0) { + n = n.copy(null, null, null, n.left.insert(key, value, comparator), null); + } + else if (cmp === 0) { + n = n.copy(null, value, null, null, null); + } + else { + n = n.copy(null, null, null, null, n.right.insert(key, value, comparator)); + } + return n.fixUp(); + } + removeMin() { + if (this.left.isEmpty()) { + return LLRBNode.EMPTY; + } + let n = this; + if (!n.left.isRed() && !n.left.left.isRed()) { + n = n.moveRedLeft(); + } + n = n.copy(null, null, null, n.left.removeMin(), null); + return n.fixUp(); + } + // Returns new tree, with the specified item removed. + remove(key, comparator) { + let smallest; + let n = this; + if (comparator(key, n.key) < 0) { + if (!n.left.isEmpty() && !n.left.isRed() && !n.left.left.isRed()) { + n = n.moveRedLeft(); + } + n = n.copy(null, null, null, n.left.remove(key, comparator), null); + } + else { + if (n.left.isRed()) { + n = n.rotateRight(); + } + if (!n.right.isEmpty() && !n.right.isRed() && !n.right.left.isRed()) { + n = n.moveRedRight(); + } + if (comparator(key, n.key) === 0) { + if (n.right.isEmpty()) { + return LLRBNode.EMPTY; + } + else { + smallest = n.right.min(); + n = n.copy(smallest.key, smallest.value, null, null, n.right.removeMin()); + } + } + n = n.copy(null, null, null, null, n.right.remove(key, comparator)); + } + return n.fixUp(); + } + isRed() { + return this.color; + } + // Returns new tree after performing any needed rotations. + fixUp() { + let n = this; + if (n.right.isRed() && !n.left.isRed()) { + n = n.rotateLeft(); + } + if (n.left.isRed() && n.left.left.isRed()) { + n = n.rotateRight(); + } + if (n.left.isRed() && n.right.isRed()) { + n = n.colorFlip(); + } + return n; + } + moveRedLeft() { + let n = this.colorFlip(); + if (n.right.left.isRed()) { + n = n.copy(null, null, null, null, n.right.rotateRight()); + n = n.rotateLeft(); + n = n.colorFlip(); + } + return n; + } + moveRedRight() { + let n = this.colorFlip(); + if (n.left.left.isRed()) { + n = n.rotateRight(); + n = n.colorFlip(); + } + return n; + } + rotateLeft() { + const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left); + return this.right.copy(null, null, this.color, nl, null); + } + rotateRight() { + const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null); + return this.left.copy(null, null, this.color, null, nr); + } + colorFlip() { + const left = this.left.copy(null, null, !this.left.color, null, null); + const right = this.right.copy(null, null, !this.right.color, null, null); + return this.copy(null, null, !this.color, left, right); + } + // For testing. + checkMaxDepth() { + const blackDepth = this.check(); + if (Math.pow(2.0, blackDepth) <= this.size + 1) { + return true; + } + else { + return false; + } + } + // In a balanced RB tree, the black-depth (number of black nodes) from root to + // leaves is equal on both sides. This function verifies that or asserts. + check() { + if (this.isRed() && this.left.isRed()) { + throw fail(0xaad2, { + key: this.key, + value: this.value + }); + } + if (this.right.isRed()) { + throw fail(0x3721, { + key: this.key, + value: this.value + }); + } + const blackDepth = this.left.check(); + if (blackDepth !== this.right.check()) { + throw fail(0x6d2d); + } + else { + return blackDepth + (this.isRed() ? 0 : 1); + } + } +} // end LLRBNode +// Empty node is shared between all LLRB trees. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +LLRBNode.EMPTY = null; +LLRBNode.RED = true; +LLRBNode.BLACK = false; +// Represents an empty node (a leaf node in the Red-Black Tree). +class LLRBEmptyNode { + constructor() { + this.size = 0; + } + get key() { + throw fail(0xe1a6); + } + get value() { + throw fail(0x3f0d); + } + get color() { + throw fail(0x4157); + } + get left() { + throw fail(0x741e); + } + get right() { + throw fail(0x901e); + } + // Returns a copy of the current node. + copy(key, value, color, left, right) { + return this; + } + // Returns a copy of the tree, with the specified key/value added. + insert(key, value, comparator) { + return new LLRBNode(key, value); + } + // Returns a copy of the tree, with the specified key removed. + remove(key, comparator) { + return this; + } + isEmpty() { + return true; + } + inorderTraversal(action) { + return false; + } + reverseTraversal(action) { + return false; + } + minKey() { + return null; + } + maxKey() { + return null; + } + isRed() { + return false; + } + // For testing. + checkMaxDepth() { + return true; + } + check() { + return 0; + } +} // end LLRBEmptyNode +LLRBNode.EMPTY = new LLRBEmptyNode(); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * SortedSet is an immutable (copy-on-write) collection that holds elements + * in order specified by the provided comparator. + * + * NOTE: if provided comparator returns 0 for two elements, we consider them to + * be equal! + */ +class SortedSet { + constructor(comparator) { + this.comparator = comparator; + this.data = new SortedMap(this.comparator); + } + has(elem) { + return this.data.get(elem) !== null; + } + first() { + return this.data.minKey(); + } + last() { + return this.data.maxKey(); + } + get size() { + return this.data.size; + } + indexOf(elem) { + return this.data.indexOf(elem); + } + /** Iterates elements in order defined by "comparator" */ + forEach(cb) { + this.data.inorderTraversal((k, v) => { + cb(k); + return false; + }); + } + /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ + forEachInRange(range, cb) { + const iter = this.data.getIteratorFrom(range[0]); + while (iter.hasNext()) { + const elem = iter.getNext(); + if (this.comparator(elem.key, range[1]) >= 0) { + return; + } + cb(elem.key); + } + } + /** + * Iterates over `elem`s such that: start <= elem until false is returned. + */ + forEachWhile(cb, start) { + let iter; + if (start !== undefined) { + iter = this.data.getIteratorFrom(start); + } + else { + iter = this.data.getIterator(); + } + while (iter.hasNext()) { + const elem = iter.getNext(); + const result = cb(elem.key); + if (!result) { + return; + } + } + } + /** Finds the least element greater than or equal to `elem`. */ + firstAfterOrEqual(elem) { + const iter = this.data.getIteratorFrom(elem); + return iter.hasNext() ? iter.getNext().key : null; + } + getIterator() { + return new SortedSetIterator(this.data.getIterator()); + } + getIteratorFrom(key) { + return new SortedSetIterator(this.data.getIteratorFrom(key)); + } + /** Inserts or updates an element */ + add(elem) { + return this.copy(this.data.remove(elem).insert(elem, true)); + } + /** Deletes an element */ + delete(elem) { + if (!this.has(elem)) { + return this; + } + return this.copy(this.data.remove(elem)); + } + isEmpty() { + return this.data.isEmpty(); + } + unionWith(other) { + let result = this; + // Make sure `result` always refers to the larger one of the two sets. + if (result.size < other.size) { + result = other; + other = this; + } + other.forEach(elem => { + result = result.add(elem); + }); + return result; + } + isEqual(other) { + if (!(other instanceof SortedSet)) { + return false; + } + if (this.size !== other.size) { + return false; + } + const thisIt = this.data.getIterator(); + const otherIt = other.data.getIterator(); + while (thisIt.hasNext()) { + const thisElem = thisIt.getNext().key; + const otherElem = otherIt.getNext().key; + if (this.comparator(thisElem, otherElem) !== 0) { + return false; + } + } + return true; + } + toArray() { + const res = []; + this.forEach(targetId => { + res.push(targetId); + }); + return res; + } + toString() { + const result = []; + this.forEach(elem => result.push(elem)); + return 'SortedSet(' + result.toString() + ')'; + } + copy(data) { + const result = new SortedSet(this.comparator); + result.data = data; + return result; + } +} +class SortedSetIterator { + constructor(iter) { + this.iter = iter; + } + getNext() { + return this.iter.getNext().key; + } + hasNext() { + return this.iter.hasNext(); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provides a set of fields that can be used to partially patch a document. + * FieldMask is used in conjunction with ObjectValue. + * Examples: + * foo - Overwrites foo entirely with the provided value. If foo is not + * present in the companion ObjectValue, the field is deleted. + * foo.bar - Overwrites only the field bar of the object foo. + * If foo is not an object, foo is replaced with an object + * containing foo + */ +class FieldMask { + constructor(fields) { + this.fields = fields; + // TODO(dimond): validation of FieldMask + // Sort the field mask to support `FieldMask.isEqual()` and assert below. + fields.sort(FieldPath$1.comparator); + } + static empty() { + return new FieldMask([]); + } + /** + * Returns a new FieldMask object that is the result of adding all the given + * fields paths to this field mask. + */ + unionWith(extraFields) { + let mergedMaskSet = new SortedSet(FieldPath$1.comparator); + for (const fieldPath of this.fields) { + mergedMaskSet = mergedMaskSet.add(fieldPath); + } + for (const fieldPath of extraFields) { + mergedMaskSet = mergedMaskSet.add(fieldPath); + } + return new FieldMask(mergedMaskSet.toArray()); + } + /** + * Verifies that `fieldPath` is included by at least one field in this field + * mask. + * + * This is an O(n) operation, where `n` is the size of the field mask. + */ + covers(fieldPath) { + for (const fieldMaskPath of this.fields) { + if (fieldMaskPath.isPrefixOf(fieldPath)) { + return true; + } + } + return false; + } + isEqual(other) { + return arrayEquals(this.fields, other.fields, (l, r) => l.isEqual(r)); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An ObjectValue represents a MapValue in the Firestore Proto and offers the + * ability to add and remove fields (via the ObjectValueBuilder). + */ +class ObjectValue { + constructor(value) { + this.value = value; + } + static empty() { + return new ObjectValue({ mapValue: {} }); + } + /** + * Returns the value at the given path or null. + * + * @param path - the path to search + * @returns The value at the path or null if the path is not set. + */ + field(path) { + if (path.isEmpty()) { + return this.value; + } + else { + let currentLevel = this.value; + for (let i = 0; i < path.length - 1; ++i) { + currentLevel = (currentLevel.mapValue.fields || {})[path.get(i)]; + if (!isMapValue(currentLevel)) { + return null; + } + } + currentLevel = (currentLevel.mapValue.fields || {})[path.lastSegment()]; + return currentLevel || null; + } + } + /** + * Sets the field to the provided value. + * + * @param path - The field path to set. + * @param value - The value to set. + */ + set(path, value) { + const fieldsMap = this.getFieldsMap(path.popLast()); + fieldsMap[path.lastSegment()] = deepClone(value); + } + /** + * Sets the provided fields to the provided values. + * + * @param data - A map of fields to values (or null for deletes). + */ + setAll(data) { + let parent = FieldPath$1.emptyPath(); + let upserts = {}; + let deletes = []; + data.forEach((value, path) => { + if (!parent.isImmediateParentOf(path)) { + // Insert the accumulated changes at this parent location + const fieldsMap = this.getFieldsMap(parent); + this.applyChanges(fieldsMap, upserts, deletes); + upserts = {}; + deletes = []; + parent = path.popLast(); + } + if (value) { + upserts[path.lastSegment()] = deepClone(value); + } + else { + deletes.push(path.lastSegment()); + } + }); + const fieldsMap = this.getFieldsMap(parent); + this.applyChanges(fieldsMap, upserts, deletes); + } + /** + * Removes the field at the specified path. If there is no field at the + * specified path, nothing is changed. + * + * @param path - The field path to remove. + */ + delete(path) { + const nestedValue = this.field(path.popLast()); + if (isMapValue(nestedValue) && nestedValue.mapValue.fields) { + delete nestedValue.mapValue.fields[path.lastSegment()]; + } + } + isEqual(other) { + return valueEquals(this.value, other.value); + } + /** + * Returns the map that contains the leaf element of `path`. If the parent + * entry does not yet exist, or if it is not a map, a new map will be created. + */ + getFieldsMap(path) { + let current = this.value; + if (!current.mapValue.fields) { + current.mapValue = { fields: {} }; + } + for (let i = 0; i < path.length; ++i) { + let next = current.mapValue.fields[path.get(i)]; + if (!isMapValue(next) || !next.mapValue.fields) { + next = { mapValue: { fields: {} } }; + current.mapValue.fields[path.get(i)] = next; + } + current = next; + } + return current.mapValue.fields; + } + /** + * Modifies `fieldsMap` by adding, replacing or deleting the specified + * entries. + */ + applyChanges(fieldsMap, inserts, deletes) { + forEach(inserts, (key, val) => (fieldsMap[key] = val)); + for (const field of deletes) { + delete fieldsMap[field]; + } + } + clone() { + return new ObjectValue(deepClone(this.value)); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a document in Firestore with a key, version, data and whether it + * has local mutations applied to it. + * + * Documents can transition between states via `convertToFoundDocument()`, + * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does + * not transition to one of these states even after all mutations have been + * applied, `isValidDocument()` returns false and the document should be removed + * from all views. + */ +class MutableDocument { + constructor(key, documentType, version, readTime, createTime, data, documentState) { + this.key = key; + this.documentType = documentType; + this.version = version; + this.readTime = readTime; + this.createTime = createTime; + this.data = data; + this.documentState = documentState; + } + /** + * Creates a document with no known version or data, but which can serve as + * base document for mutations. + */ + static newInvalidDocument(documentKey) { + return new MutableDocument(documentKey, 0 /* DocumentType.INVALID */, + /* version */ SnapshotVersion.min(), + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist with the given data at the + * given version. + */ + static newFoundDocument(documentKey, version, createTime, value) { + return new MutableDocument(documentKey, 1 /* DocumentType.FOUND_DOCUMENT */, + /* version */ version, + /* readTime */ SnapshotVersion.min(), + /* createTime */ createTime, value, 0 /* DocumentState.SYNCED */); + } + /** Creates a new document that is known to not exist at the given version. */ + static newNoDocument(documentKey, version) { + return new MutableDocument(documentKey, 2 /* DocumentType.NO_DOCUMENT */, + /* version */ version, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist at the given version but + * whose data is not known (e.g. a document that was updated without a known + * base document). + */ + static newUnknownDocument(documentKey, version) { + return new MutableDocument(documentKey, 3 /* DocumentType.UNKNOWN_DOCUMENT */, + /* version */ version, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */); + } + /** + * Changes the document type to indicate that it exists and that its version + * and data are known. + */ + convertToFoundDocument(version, value) { + // If a document is switching state from being an invalid or deleted + // document to a valid (FOUND_DOCUMENT) document, either due to receiving an + // update from Watch or due to applying a local set mutation on top + // of a deleted document, our best guess about its createTime would be the + // version at which the document transitioned to a FOUND_DOCUMENT. + if (this.createTime.isEqual(SnapshotVersion.min()) && + (this.documentType === 2 /* DocumentType.NO_DOCUMENT */ || + this.documentType === 0 /* DocumentType.INVALID */)) { + this.createTime = version; + } + this.version = version; + this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */; + this.data = value; + this.documentState = 0 /* DocumentState.SYNCED */; + return this; + } + /** + * Changes the document type to indicate that it doesn't exist at the given + * version. + */ + convertToNoDocument(version) { + this.version = version; + this.documentType = 2 /* DocumentType.NO_DOCUMENT */; + this.data = ObjectValue.empty(); + this.documentState = 0 /* DocumentState.SYNCED */; + return this; + } + /** + * Changes the document type to indicate that it exists at a given version but + * that its data is not known (e.g. a document that was updated without a known + * base document). + */ + convertToUnknownDocument(version) { + this.version = version; + this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */; + this.data = ObjectValue.empty(); + this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */; + return this; + } + setHasCommittedMutations() { + this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */; + return this; + } + setHasLocalMutations() { + this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */; + this.version = SnapshotVersion.min(); + return this; + } + setReadTime(readTime) { + this.readTime = readTime; + return this; + } + get hasLocalMutations() { + return this.documentState === 1 /* DocumentState.HAS_LOCAL_MUTATIONS */; + } + get hasCommittedMutations() { + return this.documentState === 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */; + } + get hasPendingWrites() { + return this.hasLocalMutations || this.hasCommittedMutations; + } + isValidDocument() { + return this.documentType !== 0 /* DocumentType.INVALID */; + } + isFoundDocument() { + return this.documentType === 1 /* DocumentType.FOUND_DOCUMENT */; + } + isNoDocument() { + return this.documentType === 2 /* DocumentType.NO_DOCUMENT */; + } + isUnknownDocument() { + return this.documentType === 3 /* DocumentType.UNKNOWN_DOCUMENT */; + } + isEqual(other) { + return (other instanceof MutableDocument && + this.key.isEqual(other.key) && + this.version.isEqual(other.version) && + this.documentType === other.documentType && + this.documentState === other.documentState && + this.data.isEqual(other.data)); + } + mutableCopy() { + return new MutableDocument(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState); + } + toString() { + return (`Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, ` + + `{createTime: ${this.createTime}}), ` + + `{documentType: ${this.documentType}}), ` + + `{documentState: ${this.documentState}})`); + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Visible for testing +class TargetImpl { + constructor(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) { + this.path = path; + this.collectionGroup = collectionGroup; + this.orderBy = orderBy; + this.filters = filters; + this.limit = limit; + this.startAt = startAt; + this.endAt = endAt; + this.memoizedCanonicalId = null; + } +} +/** + * Initializes a Target with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + * + * NOTE: you should always construct `Target` from `Query.toTarget` instead of + * using this factory method, because `Query` provides an implicit `orderBy` + * property. + */ +function newTarget(path, collectionGroup = null, orderBy = [], filters = [], limit = null, startAt = null, endAt = null) { + return new TargetImpl(path, collectionGroup, orderBy, filters, limit, startAt, endAt); +} +function targetEquals(left, right) { + if (left.limit !== right.limit) { + return false; + } + if (left.orderBy.length !== right.orderBy.length) { + return false; + } + for (let i = 0; i < left.orderBy.length; i++) { + if (!orderByEquals(left.orderBy[i], right.orderBy[i])) { + return false; + } + } + if (left.filters.length !== right.filters.length) { + return false; + } + for (let i = 0; i < left.filters.length; i++) { + if (!filterEquals(left.filters[i], right.filters[i])) { + return false; + } + } + if (left.collectionGroup !== right.collectionGroup) { + return false; + } + if (!left.path.isEqual(right.path)) { + return false; + } + if (!boundEquals(left.startAt, right.startAt)) { + return false; + } + return boundEquals(left.endAt, right.endAt); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Query encapsulates all the query attributes we support in the SDK. It can + * be run against the LocalStore, as well as be converted to a `Target` to + * query the RemoteStore results. + * + * Visible for testing. + */ +class QueryImpl { + /** + * Initializes a Query with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + */ + constructor(path, collectionGroup = null, explicitOrderBy = [], filters = [], limit = null, limitType = "F" /* LimitType.First */, startAt = null, endAt = null) { + this.path = path; + this.collectionGroup = collectionGroup; + this.explicitOrderBy = explicitOrderBy; + this.filters = filters; + this.limit = limit; + this.limitType = limitType; + this.startAt = startAt; + this.endAt = endAt; + this.memoizedNormalizedOrderBy = null; + // The corresponding `Target` of this `Query` instance, for use with + // non-aggregate queries. + this.memoizedTarget = null; + // The corresponding `Target` of this `Query` instance, for use with + // aggregate queries. Unlike targets for non-aggregate queries, + // aggregate query targets do not contain normalized order-bys, they only + // contain explicit order-bys. + this.memoizedAggregateTarget = null; + if (this.startAt) ; + if (this.endAt) ; + } +} +/** Creates a new Query for a query that matches all documents at `path` */ +function newQueryForPath(path) { + return new QueryImpl(path); +} +// Returns the sorted set of inequality filter fields used in this query. +function getInequalityFilterFields(query) { + let result = new SortedSet(FieldPath$1.comparator); + query.filters.forEach((filter) => { + const subFilters = filter.getFlattenedFilters(); + subFilters.forEach((filter) => { + if (filter.isInequality()) { + result = result.add(filter.field); + } + }); + }); + return result; +} +/** + * Creates a new Query for a collection group query that matches all documents + * within the provided collection group. + */ +function newQueryForCollectionGroup(collectionId) { + return new QueryImpl(ResourcePath.emptyPath(), collectionId); +} +/** + * Returns whether the query matches a collection group rather than a specific + * collection. + */ +function isCollectionGroupQuery(query) { + return query.collectionGroup !== null; +} +/** + * Returns the normalized order-by constraint that is used to execute the Query, + * which can be different from the order-by constraints the user provided (e.g. + * the SDK and backend always orders by `__name__`). The normalized order-by + * includes implicit order-bys in addition to the explicit user provided + * order-bys. + */ +function queryNormalizedOrderBy(query) { + const queryImpl = debugCast(query); + if (queryImpl.memoizedNormalizedOrderBy === null) { + queryImpl.memoizedNormalizedOrderBy = []; + const fieldsNormalized = new Set(); + // Any explicit order by fields should be added as is. + for (const orderBy of queryImpl.explicitOrderBy) { + queryImpl.memoizedNormalizedOrderBy.push(orderBy); + fieldsNormalized.add(orderBy.field.canonicalString()); + } + // The order of the implicit ordering always matches the last explicit order by. + const lastDirection = queryImpl.explicitOrderBy.length > 0 + ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1].dir + : "asc" /* Direction.ASCENDING */; + // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical + // order. When there are multiple inequality filters on the same field, the field should be added + // only once. + // Note: `SortedSet` sorts the key field before other fields. However, we want the key + // field to be sorted last. + const inequalityFields = getInequalityFilterFields(queryImpl); + inequalityFields.forEach(field => { + if (!fieldsNormalized.has(field.canonicalString()) && + !field.isKeyField()) { + queryImpl.memoizedNormalizedOrderBy.push(new OrderBy(field, lastDirection)); + } + }); + // Add the document key field to the last if it is not explicitly ordered. + if (!fieldsNormalized.has(FieldPath$1.keyField().canonicalString())) { + queryImpl.memoizedNormalizedOrderBy.push(new OrderBy(FieldPath$1.keyField(), lastDirection)); + } + } + return queryImpl.memoizedNormalizedOrderBy; +} +/** + * Converts this `Query` instance to its corresponding `Target` representation. + */ +function queryToTarget(query) { + const queryImpl = debugCast(query); + if (!queryImpl.memoizedTarget) { + queryImpl.memoizedTarget = _queryToTarget(queryImpl, queryNormalizedOrderBy(query)); + } + return queryImpl.memoizedTarget; +} +/** + * Converts this `Query` instance to its corresponding `Target` representation, + * for use within an aggregate query. Unlike targets for non-aggregate queries, + * aggregate query targets do not contain normalized order-bys, they only + * contain explicit order-bys. + */ +function queryToAggregateTarget(query) { + const queryImpl = debugCast(query); + if (!queryImpl.memoizedAggregateTarget) { + // Do not include implicit order-bys for aggregate queries. + queryImpl.memoizedAggregateTarget = _queryToTarget(queryImpl, query.explicitOrderBy); + } + return queryImpl.memoizedAggregateTarget; +} +function _queryToTarget(queryImpl, orderBys) { + if (queryImpl.limitType === "F" /* LimitType.First */) { + return newTarget(queryImpl.path, queryImpl.collectionGroup, orderBys, queryImpl.filters, queryImpl.limit, queryImpl.startAt, queryImpl.endAt); + } + else { + // Flip the orderBy directions since we want the last results + orderBys = orderBys.map(orderBy => { + const dir = orderBy.dir === "desc" /* Direction.DESCENDING */ + ? "asc" /* Direction.ASCENDING */ + : "desc" /* Direction.DESCENDING */; + return new OrderBy(orderBy.field, dir); + }); + // We need to swap the cursors to match the now-flipped query ordering. + const startAt = queryImpl.endAt + ? new Bound(queryImpl.endAt.position, queryImpl.endAt.inclusive) + : null; + const endAt = queryImpl.startAt + ? new Bound(queryImpl.startAt.position, queryImpl.startAt.inclusive) + : null; + // Now return as a LimitType.First query. + return newTarget(queryImpl.path, queryImpl.collectionGroup, orderBys, queryImpl.filters, queryImpl.limit, startAt, endAt); + } +} +function queryWithAddedFilter(query, filter) { + const newFilters = query.filters.concat([filter]); + return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), newFilters, query.limit, query.limitType, query.startAt, query.endAt); +} +function queryWithAddedOrderBy(query, orderBy) { + // TODO(dimond): validate that orderBy does not list the same key twice. + const newOrderBy = query.explicitOrderBy.concat([orderBy]); + return new QueryImpl(query.path, query.collectionGroup, newOrderBy, query.filters.slice(), query.limit, query.limitType, query.startAt, query.endAt); +} +function queryWithLimit(query, limit, limitType) { + return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), limit, limitType, query.startAt, query.endAt); +} +function queryWithStartAt(query, bound) { + return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, bound, query.endAt); +} +function queryWithEndAt(query, bound) { + return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), query.filters.slice(), query.limit, query.limitType, query.startAt, bound); +} +function queryEquals(left, right) { + return (targetEquals(queryToTarget(left), queryToTarget(right)) && + left.limitType === right.limitType); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns an DoubleValue for `value` that is encoded based the serializer's + * `useProto3Json` setting. + */ +function toDouble(serializer, value) { + if (serializer.useProto3Json) { + if (isNaN(value)) { + return { doubleValue: 'NaN' }; + } + else if (value === Infinity) { + return { doubleValue: 'Infinity' }; + } + else if (value === -Infinity) { + return { doubleValue: '-Infinity' }; + } + } + return { doubleValue: isNegativeZero(value) ? '-0' : value }; +} +/** + * Returns an IntegerValue for `value`. + */ +function toInteger(value) { + return { integerValue: '' + value }; +} +/** + * Returns a value for a number that's appropriate to put into a proto. + * The return value is an IntegerValue if it can safely represent the value, + * otherwise a DoubleValue is returned. + */ +function toNumber(serializer, value) { + return isSafeInteger(value) ? toInteger(value) : toDouble(serializer, value); +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Used to represent a field transform on a mutation. */ +class TransformOperation { + constructor() { + // Make sure that the structural type of `TransformOperation` is unique. + // See https://github.com/microsoft/TypeScript/issues/5451 + this._ = undefined; + } +} +/** Transforms a value into a server-generated timestamp. */ +class ServerTimestampTransform extends TransformOperation { +} +/** Transforms an array value via a union operation. */ +class ArrayUnionTransformOperation extends TransformOperation { + constructor(elements) { + super(); + this.elements = elements; + } +} +/** Transforms an array value via a remove operation. */ +class ArrayRemoveTransformOperation extends TransformOperation { + constructor(elements) { + super(); + this.elements = elements; + } +} +/** + * Implements the backend semantics for locally computed NUMERIC_ADD (increment) + * transforms. Converts all field values to integers or doubles, but unlike the + * backend does not cap integer values at 2^63. Instead, JavaScript number + * arithmetic is used and precision loss can occur for values greater than 2^53. + */ +class NumericIncrementTransformOperation extends TransformOperation { + constructor(serializer, operand) { + super(); + this.serializer = serializer; + this.operand = operand; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** A field path and the TransformOperation to perform upon it. */ +class FieldTransform { + constructor(field, transform) { + this.field = field; + this.transform = transform; + } +} +/** + * Encodes a precondition for a mutation. This follows the model that the + * backend accepts with the special case of an explicit "empty" precondition + * (meaning no precondition). + */ +class Precondition { + constructor(updateTime, exists) { + this.updateTime = updateTime; + this.exists = exists; + } + /** Creates a new empty Precondition. */ + static none() { + return new Precondition(); + } + /** Creates a new Precondition with an exists flag. */ + static exists(exists) { + return new Precondition(undefined, exists); + } + /** Creates a new Precondition based on a version a document exists at. */ + static updateTime(version) { + return new Precondition(version); + } + /** Returns whether this Precondition is empty. */ + get isNone() { + return this.updateTime === undefined && this.exists === undefined; + } + isEqual(other) { + return (this.exists === other.exists && + (this.updateTime + ? !!other.updateTime && this.updateTime.isEqual(other.updateTime) + : !other.updateTime)); + } +} +/** + * A mutation describes a self-contained change to a document. Mutations can + * create, replace, delete, and update subsets of documents. + * + * Mutations not only act on the value of the document but also its version. + * + * For local mutations (mutations that haven't been committed yet), we preserve + * the existing version for Set and Patch mutations. For Delete mutations, we + * reset the version to 0. + * + * Here's the expected transition table. + * + * MUTATION APPLIED TO RESULTS IN + * + * SetMutation Document(v3) Document(v3) + * SetMutation NoDocument(v3) Document(v0) + * SetMutation InvalidDocument(v0) Document(v0) + * PatchMutation Document(v3) Document(v3) + * PatchMutation NoDocument(v3) NoDocument(v3) + * PatchMutation InvalidDocument(v0) UnknownDocument(v3) + * DeleteMutation Document(v3) NoDocument(v0) + * DeleteMutation NoDocument(v3) NoDocument(v0) + * DeleteMutation InvalidDocument(v0) NoDocument(v0) + * + * For acknowledged mutations, we use the updateTime of the WriteResponse as + * the resulting version for Set and Patch mutations. As deletes have no + * explicit update time, we use the commitTime of the WriteResponse for + * Delete mutations. + * + * If a mutation is acknowledged by the backend but fails the precondition check + * locally, we transition to an `UnknownDocument` and rely on Watch to send us + * the updated version. + * + * Field transforms are used only with Patch and Set Mutations. We use the + * `updateTransforms` message to store transforms, rather than the `transforms`s + * messages. + * + * ## Subclassing Notes + * + * Every type of mutation needs to implement its own applyToRemoteDocument() and + * applyToLocalView() to implement the actual behavior of applying the mutation + * to some source document (see `setMutationApplyToRemoteDocument()` for an + * example). + */ +class Mutation { +} +/** + * A mutation that creates or replaces the document at the given key with the + * object value contents. + */ +class SetMutation extends Mutation { + constructor(key, value, precondition, fieldTransforms = []) { + super(); + this.key = key; + this.value = value; + this.precondition = precondition; + this.fieldTransforms = fieldTransforms; + this.type = 0 /* MutationType.Set */; + } + getFieldMask() { + return null; + } +} +/** + * A mutation that modifies fields of the document at the given key with the + * given values. The values are applied through a field mask: + * + * * When a field is in both the mask and the values, the corresponding field + * is updated. + * * When a field is in neither the mask nor the values, the corresponding + * field is unmodified. + * * When a field is in the mask but not in the values, the corresponding field + * is deleted. + * * When a field is not in the mask but is in the values, the values map is + * ignored. + */ +class PatchMutation extends Mutation { + constructor(key, data, fieldMask, precondition, fieldTransforms = []) { + super(); + this.key = key; + this.data = data; + this.fieldMask = fieldMask; + this.precondition = precondition; + this.fieldTransforms = fieldTransforms; + this.type = 1 /* MutationType.Patch */; + } + getFieldMask() { + return this.fieldMask; + } +} +/** A mutation that deletes the document at the given key. */ +class DeleteMutation extends Mutation { + constructor(key, precondition) { + super(); + this.key = key; + this.precondition = precondition; + this.type = 2 /* MutationType.Delete */; + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } +} +/** + * A mutation that verifies the existence of the document at the given key with + * the provided precondition. + * + * The `verify` operation is only used in Transactions, and this class serves + * primarily to facilitate serialization into protos. + */ +class VerifyMutation extends Mutation { + constructor(key, precondition) { + super(); + this.key = key; + this.precondition = precondition; + this.type = 3 /* MutationType.Verify */; + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const DIRECTIONS = (() => { + const dirs = {}; + dirs["asc" /* Direction.ASCENDING */] = 'ASCENDING'; + dirs["desc" /* Direction.DESCENDING */] = 'DESCENDING'; + return dirs; +})(); +const OPERATORS = (() => { + const ops = {}; + ops["<" /* Operator.LESS_THAN */] = 'LESS_THAN'; + ops["<=" /* Operator.LESS_THAN_OR_EQUAL */] = 'LESS_THAN_OR_EQUAL'; + ops[">" /* Operator.GREATER_THAN */] = 'GREATER_THAN'; + ops[">=" /* Operator.GREATER_THAN_OR_EQUAL */] = 'GREATER_THAN_OR_EQUAL'; + ops["==" /* Operator.EQUAL */] = 'EQUAL'; + ops["!=" /* Operator.NOT_EQUAL */] = 'NOT_EQUAL'; + ops["array-contains" /* Operator.ARRAY_CONTAINS */] = 'ARRAY_CONTAINS'; + ops["in" /* Operator.IN */] = 'IN'; + ops["not-in" /* Operator.NOT_IN */] = 'NOT_IN'; + ops["array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */] = 'ARRAY_CONTAINS_ANY'; + return ops; +})(); +const COMPOSITE_OPERATORS = (() => { + const ops = {}; + ops["and" /* CompositeOperator.AND */] = 'AND'; + ops["or" /* CompositeOperator.OR */] = 'OR'; + return ops; +})(); +function assertPresent(value, description) { +} +/** + * This class generates JsonObject values for the Datastore API suitable for + * sending to either GRPC stub methods or via the JSON/HTTP REST API. + * + * The serializer supports both Protobuf.js and Proto3 JSON formats. By + * setting `useProto3Json` to true, the serializer will use the Proto3 JSON + * format. + * + * For a description of the Proto3 JSON format check + * https://developers.google.com/protocol-buffers/docs/proto3#json + * + * TODO(klimt): We can remove the databaseId argument if we keep the full + * resource name in documents. + */ +class JsonProtoSerializer { + constructor(databaseId, useProto3Json) { + this.databaseId = databaseId; + this.useProto3Json = useProto3Json; + } +} +/** + * Returns a value for a number (or null) that's appropriate to put into + * a google.protobuf.Int32Value proto. + * DO NOT USE THIS FOR ANYTHING ELSE. + * This method cheats. It's typed as returning "number" because that's what + * our generated proto interfaces say Int32Value must be. But GRPC actually + * expects a { value: } struct. + */ +function toInt32Proto(serializer, val) { + if (serializer.useProto3Json || isNullOrUndefined(val)) { + return val; + } + else { + return { value: val }; + } +} +/** + * Returns a value for a Date that's appropriate to put into a proto. + */ +function toTimestamp(serializer, timestamp) { + if (serializer.useProto3Json) { + // Serialize to ISO-8601 date format, but with full nano resolution. + // Since JS Date has only millis, let's only use it for the seconds and + // then manually add the fractions to the end. + const jsDateStr = new Date(timestamp.seconds * 1000).toISOString(); + // Remove .xxx frac part and Z in the end. + const strUntilSeconds = jsDateStr.replace(/\.\d*/, '').replace('Z', ''); + // Pad the fraction out to 9 digits (nanos). + const nanoStr = ('000000000' + timestamp.nanoseconds).slice(-9); + return `${strUntilSeconds}.${nanoStr}Z`; + } + else { + return { + seconds: '' + timestamp.seconds, + nanos: timestamp.nanoseconds + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }; + } +} +/** + * Returns a Timestamp typed object given protobuf timestamp value. + */ +function fromTimestamp(date) { + const timestamp = normalizeTimestamp(date); + return new Timestamp(timestamp.seconds, timestamp.nanos); +} +/** + * Returns a value for bytes that's appropriate to put in a proto. + * + * Visible for testing. + */ +function toBytes(serializer, bytes) { + if (serializer.useProto3Json) { + return bytes.toBase64(); + } + else { + return bytes.toUint8Array(); + } +} +function toVersion(serializer, version) { + return toTimestamp(serializer, version.toTimestamp()); +} +function fromVersion(version) { + hardAssert(!!version, 0xc050); + return SnapshotVersion.fromTimestamp(fromTimestamp(version)); +} +function toResourceName(databaseId, path) { + return toResourcePath(databaseId, path).canonicalString(); +} +function toResourcePath(databaseId, path) { + const resourcePath = fullyQualifiedPrefixPath(databaseId).child('documents'); + return path === undefined ? resourcePath : resourcePath.child(path); +} +function fromResourceName(name) { + const resource = ResourcePath.fromString(name); + hardAssert(isValidResourceName(resource), 0x27ce, { key: resource.toString() }); + return resource; +} +function toName(serializer, key) { + return toResourceName(serializer.databaseId, key.path); +} +function fromName(serializer, name) { + const resource = fromResourceName(name); + if (resource.get(1) !== serializer.databaseId.projectId) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Tried to deserialize key from different project: ' + + resource.get(1) + + ' vs ' + + serializer.databaseId.projectId); + } + if (resource.get(3) !== serializer.databaseId.database) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Tried to deserialize key from different database: ' + + resource.get(3) + + ' vs ' + + serializer.databaseId.database); + } + return new DocumentKey(extractLocalPathFromResourceName(resource)); +} +function toQueryPath(serializer, path) { + return toResourceName(serializer.databaseId, path); +} +function fullyQualifiedPrefixPath(databaseId) { + return new ResourcePath([ + 'projects', + databaseId.projectId, + 'databases', + databaseId.database + ]); +} +function extractLocalPathFromResourceName(resourceName) { + hardAssert(resourceName.length > 4 && resourceName.get(4) === 'documents', 0x71a3, { key: resourceName.toString() }); + return resourceName.popFirst(5); +} +/** Creates a Document proto from key and fields (but no create/update time) */ +function toMutationDocument(serializer, key, fields) { + return { + name: toName(serializer, key), + fields: fields.value.mapValue.fields + }; +} +function fromDocument(serializer, document, hasCommittedMutations) { + const key = fromName(serializer, document.name); + const version = fromVersion(document.updateTime); + // If we read a document from persistence that is missing createTime, it's due + // to older SDK versions not storing this information. In such cases, we'll + // set the createTime to zero. This can be removed in the long term. + const createTime = document.createTime + ? fromVersion(document.createTime) + : SnapshotVersion.min(); + const data = new ObjectValue({ mapValue: { fields: document.fields } }); + const result = MutableDocument.newFoundDocument(key, version, createTime, data); + if (hasCommittedMutations) { + result.setHasCommittedMutations(); + } + return hasCommittedMutations ? result.setHasCommittedMutations() : result; +} +function fromFound(serializer, doc) { + hardAssert(!!doc.found, 0xaa33); + assertPresent(doc.found.name); + assertPresent(doc.found.updateTime); + const key = fromName(serializer, doc.found.name); + const version = fromVersion(doc.found.updateTime); + const createTime = doc.found.createTime + ? fromVersion(doc.found.createTime) + : SnapshotVersion.min(); + const data = new ObjectValue({ mapValue: { fields: doc.found.fields } }); + return MutableDocument.newFoundDocument(key, version, createTime, data); +} +function fromMissing(serializer, result) { + hardAssert(!!result.missing, 0x0f36); + hardAssert(!!result.readTime, 0x5995); + const key = fromName(serializer, result.missing); + const version = fromVersion(result.readTime); + return MutableDocument.newNoDocument(key, version); +} +function fromBatchGetDocumentsResponse(serializer, result) { + if ('found' in result) { + return fromFound(serializer, result); + } + else if ('missing' in result) { + return fromMissing(serializer, result); + } + return fail(0x1c42, { result }); +} +function toMutation(serializer, mutation) { + let result; + if (mutation instanceof SetMutation) { + result = { + update: toMutationDocument(serializer, mutation.key, mutation.value) + }; + } + else if (mutation instanceof DeleteMutation) { + result = { delete: toName(serializer, mutation.key) }; + } + else if (mutation instanceof PatchMutation) { + result = { + update: toMutationDocument(serializer, mutation.key, mutation.data), + updateMask: toDocumentMask(mutation.fieldMask) + }; + } + else if (mutation instanceof VerifyMutation) { + result = { + verify: toName(serializer, mutation.key) + }; + } + else { + return fail(0x40d7, { + mutationType: mutation.type + }); + } + if (mutation.fieldTransforms.length > 0) { + result.updateTransforms = mutation.fieldTransforms.map(transform => toFieldTransform(serializer, transform)); + } + if (!mutation.precondition.isNone) { + result.currentDocument = toPrecondition(serializer, mutation.precondition); + } + return result; +} +function toPrecondition(serializer, precondition) { + if (precondition.updateTime !== undefined) { + return { + updateTime: toVersion(serializer, precondition.updateTime) + }; + } + else if (precondition.exists !== undefined) { + return { exists: precondition.exists }; + } + else { + return fail(0x6b69); + } +} +function toFieldTransform(serializer, fieldTransform) { + const transform = fieldTransform.transform; + if (transform instanceof ServerTimestampTransform) { + return { + fieldPath: fieldTransform.field.canonicalString(), + setToServerValue: 'REQUEST_TIME' + }; + } + else if (transform instanceof ArrayUnionTransformOperation) { + return { + fieldPath: fieldTransform.field.canonicalString(), + appendMissingElements: { + values: transform.elements + } + }; + } + else if (transform instanceof ArrayRemoveTransformOperation) { + return { + fieldPath: fieldTransform.field.canonicalString(), + removeAllFromArray: { + values: transform.elements + } + }; + } + else if (transform instanceof NumericIncrementTransformOperation) { + return { + fieldPath: fieldTransform.field.canonicalString(), + increment: transform.operand + }; + } + else { + throw fail(0x51c2, { + transform: fieldTransform.transform + }); + } +} +function toQueryTarget(serializer, target) { + // Dissect the path into parent, collectionId, and optional key filter. + const queryTarget = { structuredQuery: {} }; + const path = target.path; + let parent; + if (target.collectionGroup !== null) { + parent = path; + queryTarget.structuredQuery.from = [ + { + collectionId: target.collectionGroup, + allDescendants: true + } + ]; + } + else { + parent = path.popLast(); + queryTarget.structuredQuery.from = [{ collectionId: path.lastSegment() }]; + } + queryTarget.parent = toQueryPath(serializer, parent); + const where = toFilters(target.filters); + if (where) { + queryTarget.structuredQuery.where = where; + } + const orderBy = toOrder(target.orderBy); + if (orderBy) { + queryTarget.structuredQuery.orderBy = orderBy; + } + const limit = toInt32Proto(serializer, target.limit); + if (limit !== null) { + queryTarget.structuredQuery.limit = limit; + } + if (target.startAt) { + queryTarget.structuredQuery.startAt = toStartAtCursor(target.startAt); + } + if (target.endAt) { + queryTarget.structuredQuery.endAt = toEndAtCursor(target.endAt); + } + return { queryTarget, parent }; +} +function toRunAggregationQueryRequest(serializer, target, aggregates, skipAliasing) { + const { queryTarget, parent } = toQueryTarget(serializer, target); + const aliasMap = {}; + const aggregations = []; + let aggregationNum = 0; + aggregates.forEach(aggregate => { + // Map all client-side aliases to a unique short-form + // alias. This avoids issues with client-side aliases that + // exceed the 1500-byte string size limit. + const serverAlias = skipAliasing + ? aggregate.alias + : `aggregate_${aggregationNum++}`; + aliasMap[serverAlias] = aggregate.alias; + if (aggregate.aggregateType === 'count') { + aggregations.push({ + alias: serverAlias, + count: {} + }); + } + else if (aggregate.aggregateType === 'avg') { + aggregations.push({ + alias: serverAlias, + avg: { + field: toFieldPathReference(aggregate.fieldPath) + } + }); + } + else if (aggregate.aggregateType === 'sum') { + aggregations.push({ + alias: serverAlias, + sum: { + field: toFieldPathReference(aggregate.fieldPath) + } + }); + } + }); + return { + request: { + structuredAggregationQuery: { + aggregations, + structuredQuery: queryTarget.structuredQuery + }, + parent: queryTarget.parent + }, + aliasMap, + parent + }; +} +function toFilters(filters) { + if (filters.length === 0) { + return; + } + return toFilter(CompositeFilter.create(filters, "and" /* CompositeOperator.AND */)); +} +function toOrder(orderBys) { + if (orderBys.length === 0) { + return; + } + return orderBys.map(order => toPropertyOrder(order)); +} +function toStartAtCursor(cursor) { + return { + before: cursor.inclusive, + values: cursor.position + }; +} +function toEndAtCursor(cursor) { + return { + before: !cursor.inclusive, + values: cursor.position + }; +} +// visible for testing +function toDirection(dir) { + return DIRECTIONS[dir]; +} +// visible for testing +function toOperatorName(op) { + return OPERATORS[op]; +} +function toCompositeOperatorName(op) { + return COMPOSITE_OPERATORS[op]; +} +function toFieldPathReference(path) { + return { fieldPath: path.canonicalString() }; +} +// visible for testing +function toPropertyOrder(orderBy) { + return { + field: toFieldPathReference(orderBy.field), + direction: toDirection(orderBy.dir) + }; +} +// visible for testing +function toFilter(filter) { + if (filter instanceof FieldFilter) { + return toUnaryOrFieldFilter(filter); + } + else if (filter instanceof CompositeFilter) { + return toCompositeFilter(filter); + } + else { + return fail(0xd65d, { filter }); + } +} +function toCompositeFilter(filter) { + const protos = filter.getFilters().map(filter => toFilter(filter)); + if (protos.length === 1) { + return protos[0]; + } + return { + compositeFilter: { + op: toCompositeOperatorName(filter.op), + filters: protos + } + }; +} +function toUnaryOrFieldFilter(filter) { + if (filter.op === "==" /* Operator.EQUAL */) { + if (isNanValue(filter.value)) { + return { + unaryFilter: { + field: toFieldPathReference(filter.field), + op: 'IS_NAN' + } + }; + } + else if (isNullValue(filter.value)) { + return { + unaryFilter: { + field: toFieldPathReference(filter.field), + op: 'IS_NULL' + } + }; + } + } + else if (filter.op === "!=" /* Operator.NOT_EQUAL */) { + if (isNanValue(filter.value)) { + return { + unaryFilter: { + field: toFieldPathReference(filter.field), + op: 'IS_NOT_NAN' + } + }; + } + else if (isNullValue(filter.value)) { + return { + unaryFilter: { + field: toFieldPathReference(filter.field), + op: 'IS_NOT_NULL' + } + }; + } + } + return { + fieldFilter: { + field: toFieldPathReference(filter.field), + op: toOperatorName(filter.op), + value: filter.value + } + }; +} +function toDocumentMask(fieldMask) { + const canonicalFields = []; + fieldMask.fields.forEach(field => canonicalFields.push(field.canonicalString())); + return { + fieldPaths: canonicalFields + }; +} +function isValidResourceName(path) { + // Resource names have at least 4 components (project ID, database ID) + return (path.length >= 4 && + path.get(0) === 'projects' && + path.get(2) === 'databases'); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function newSerializer(databaseId) { + return new JsonProtoSerializer(databaseId, /* useProto3Json= */ true); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$2 = 'ExponentialBackoff'; +/** + * Initial backoff time in milliseconds after an error. + * Set to 1s according to https://cloud.google.com/apis/design/errors. + */ +const DEFAULT_BACKOFF_INITIAL_DELAY_MS = 1000; +const DEFAULT_BACKOFF_FACTOR = 1.5; +/** Maximum backoff time in milliseconds */ +const DEFAULT_BACKOFF_MAX_DELAY_MS = 60 * 1000; +/** + * A helper for running delayed tasks following an exponential backoff curve + * between attempts. + * + * Each delay is made up of a "base" delay which follows the exponential + * backoff curve, and a +/- 50% "jitter" that is calculated and added to the + * base delay. This prevents clients from accidentally synchronizing their + * delays causing spikes of load to the backend. + */ +class ExponentialBackoff { + constructor( + /** + * The AsyncQueue to run backoff operations on. + */ + queue, + /** + * The ID to use when scheduling backoff operations on the AsyncQueue. + */ + timerId, + /** + * The initial delay (used as the base delay on the first retry attempt). + * Note that jitter will still be applied, so the actual delay could be as + * little as 0.5*initialDelayMs. + */ + initialDelayMs = DEFAULT_BACKOFF_INITIAL_DELAY_MS, + /** + * The multiplier to use to determine the extended base delay after each + * attempt. + */ + backoffFactor = DEFAULT_BACKOFF_FACTOR, + /** + * The maximum base delay after which no further backoff is performed. + * Note that jitter will still be applied, so the actual delay could be as + * much as 1.5*maxDelayMs. + */ + maxDelayMs = DEFAULT_BACKOFF_MAX_DELAY_MS) { + this.queue = queue; + this.timerId = timerId; + this.initialDelayMs = initialDelayMs; + this.backoffFactor = backoffFactor; + this.maxDelayMs = maxDelayMs; + this.currentBaseMs = 0; + this.timerPromise = null; + /** The last backoff attempt, as epoch milliseconds. */ + this.lastAttemptTime = Date.now(); + this.reset(); + } + /** + * Resets the backoff delay. + * + * The very next backoffAndWait() will have no delay. If it is called again + * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and + * subsequent ones will increase according to the backoffFactor. + */ + reset() { + this.currentBaseMs = 0; + } + /** + * Resets the backoff delay to the maximum delay (e.g. for use after a + * RESOURCE_EXHAUSTED error). + */ + resetToMax() { + this.currentBaseMs = this.maxDelayMs; + } + /** + * Returns a promise that resolves after currentDelayMs, and increases the + * delay for any subsequent attempts. If there was a pending backoff operation + * already, it will be canceled. + */ + backoffAndRun(op) { + // Cancel any pending backoff operation. + this.cancel(); + // First schedule using the current base (which may be 0 and should be + // honored as such). + const desiredDelayWithJitterMs = Math.floor(this.currentBaseMs + this.jitterDelayMs()); + // Guard against lastAttemptTime being in the future due to a clock change. + const delaySoFarMs = Math.max(0, Date.now() - this.lastAttemptTime); + // Guard against the backoff delay already being past. + const remainingDelayMs = Math.max(0, desiredDelayWithJitterMs - delaySoFarMs); + if (remainingDelayMs > 0) { + logDebug(LOG_TAG$2, `Backing off for ${remainingDelayMs} ms ` + + `(base delay: ${this.currentBaseMs} ms, ` + + `delay with jitter: ${desiredDelayWithJitterMs} ms, ` + + `last attempt: ${delaySoFarMs} ms ago)`); + } + this.timerPromise = this.queue.enqueueAfterDelay(this.timerId, remainingDelayMs, () => { + this.lastAttemptTime = Date.now(); + return op(); + }); + // Apply backoff factor to determine next delay and ensure it is within + // bounds. + this.currentBaseMs *= this.backoffFactor; + if (this.currentBaseMs < this.initialDelayMs) { + this.currentBaseMs = this.initialDelayMs; + } + if (this.currentBaseMs > this.maxDelayMs) { + this.currentBaseMs = this.maxDelayMs; + } + } + skipBackoff() { + if (this.timerPromise !== null) { + this.timerPromise.skipDelay(); + this.timerPromise = null; + } + } + cancel() { + if (this.timerPromise !== null) { + this.timerPromise.cancel(); + this.timerPromise = null; + } + } + /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ + jitterDelayMs() { + return (Math.random() - 0.5) * this.currentBaseMs; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Datastore and its related methods are a wrapper around the external Google + * Cloud Datastore grpc API, which provides an interface that is more convenient + * for the rest of the client SDK architecture to consume. + */ +class Datastore { +} +/** + * An implementation of Datastore that exposes additional state for internal + * consumption. + */ +class DatastoreImpl extends Datastore { + constructor(authCredentials, appCheckCredentials, connection, serializer) { + super(); + this.authCredentials = authCredentials; + this.appCheckCredentials = appCheckCredentials; + this.connection = connection; + this.serializer = serializer; + this.terminated = false; + } + verifyInitialized() { + if (this.terminated) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'The client has already been terminated.'); + } + } + /** Invokes the provided RPC with auth and AppCheck tokens. */ + invokeRPC(rpcName, databaseId, resourcePath, request) { + this.verifyInitialized(); + return Promise.all([ + this.authCredentials.getToken(), + this.appCheckCredentials.getToken() + ]) + .then(([authToken, appCheckToken]) => { + return this.connection.invokeRPC(rpcName, toResourcePath(databaseId, resourcePath), request, authToken, appCheckToken); + }) + .catch((error) => { + if (error.name === 'FirebaseError') { + if (error.code === Code.UNAUTHENTICATED) { + this.authCredentials.invalidateToken(); + this.appCheckCredentials.invalidateToken(); + } + throw error; + } + else { + throw new FirestoreError(Code.UNKNOWN, error.toString()); + } + }); + } + /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ + invokeStreamingRPC(rpcName, databaseId, resourcePath, request, expectedResponseCount) { + this.verifyInitialized(); + return Promise.all([ + this.authCredentials.getToken(), + this.appCheckCredentials.getToken() + ]) + .then(([authToken, appCheckToken]) => { + return this.connection.invokeStreamingRPC(rpcName, toResourcePath(databaseId, resourcePath), request, authToken, appCheckToken, expectedResponseCount); + }) + .catch((error) => { + if (error.name === 'FirebaseError') { + if (error.code === Code.UNAUTHENTICATED) { + this.authCredentials.invalidateToken(); + this.appCheckCredentials.invalidateToken(); + } + throw error; + } + else { + throw new FirestoreError(Code.UNKNOWN, error.toString()); + } + }); + } + terminate() { + this.terminated = true; + this.connection.terminate(); + } +} +// TODO(firestorexp): Make sure there is only one Datastore instance per +// firestore-exp client. +function newDatastore(authCredentials, appCheckCredentials, connection, serializer) { + return new DatastoreImpl(authCredentials, appCheckCredentials, connection, serializer); +} +async function invokeCommitRpc(datastore, mutations) { + const datastoreImpl = debugCast(datastore); + const request = { + writes: mutations.map(m => toMutation(datastoreImpl.serializer, m)) + }; + await datastoreImpl.invokeRPC('Commit', datastoreImpl.serializer.databaseId, ResourcePath.emptyPath(), request); +} +async function invokeBatchGetDocumentsRpc(datastore, keys) { + const datastoreImpl = debugCast(datastore); + const request = { + documents: keys.map(k => toName(datastoreImpl.serializer, k)) + }; + const response = await datastoreImpl.invokeStreamingRPC('BatchGetDocuments', datastoreImpl.serializer.databaseId, ResourcePath.emptyPath(), request, keys.length); + const docs = new Map(); + response.forEach(proto => { + const doc = fromBatchGetDocumentsResponse(datastoreImpl.serializer, proto); + docs.set(doc.key.toString(), doc); + }); + const result = []; + keys.forEach(key => { + const doc = docs.get(key.toString()); + hardAssert(!!doc, 0xd7c2, { + key + }); + result.push(doc); + }); + return result; +} +async function invokeRunQueryRpc(datastore, query) { + const datastoreImpl = debugCast(datastore); + const { queryTarget, parent } = toQueryTarget(datastoreImpl.serializer, queryToTarget(query)); + const response = await datastoreImpl.invokeStreamingRPC('RunQuery', datastoreImpl.serializer.databaseId, parent, { + structuredQuery: queryTarget.structuredQuery + }); + return (response + // Omit RunQueryResponses that only contain readTimes. + .filter(proto => !!proto.document) + .map(proto => fromDocument(datastoreImpl.serializer, proto.document, undefined))); +} +async function invokeRunAggregationQueryRpc(datastore, query, aggregates) { + const datastoreImpl = debugCast(datastore); + const { request, aliasMap, parent } = toRunAggregationQueryRequest(datastoreImpl.serializer, queryToAggregateTarget(query), aggregates); + if (!datastoreImpl.connection.shouldResourcePathBeIncludedInRequest) { + delete request.parent; + } + const response = await datastoreImpl.invokeStreamingRPC('RunAggregationQuery', datastoreImpl.serializer.databaseId, parent, request, + /*expectedResponseCount=*/ 1); + // Omit RunAggregationQueryResponse that only contain readTimes. + const filteredResult = response.filter(proto => !!proto.result); + hardAssert(filteredResult.length === 1, 0xfcd7); + // Remap the short-form aliases that were sent to the server + // to the client-side aliases. Users will access the results + // using the client-side alias. + const unmappedAggregateFields = filteredResult[0].result?.aggregateFields; + const remappedFields = Object.keys(unmappedAggregateFields).reduce((accumulator, key) => { + accumulator[aliasMap[key]] = unmappedAggregateFields[key]; + return accumulator; + }, {}); + return remappedFields; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG$1 = 'ComponentProvider'; +/** + * An instance map that ensures only one Datastore exists per Firestore + * instance. + */ +const datastoreInstances = new Map(); +/** + * Returns an initialized and started Datastore for the given Firestore + * instance. Callers must invoke removeComponents() when the Firestore + * instance is terminated. + */ +function getDatastore(firestore) { + if (firestore._terminated) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'The client has already been terminated.'); + } + if (!datastoreInstances.has(firestore)) { + logDebug(LOG_TAG$1, 'Initializing Datastore'); + const databaseInfo = makeDatabaseInfo(firestore._databaseId, firestore.app.options.appId || '', firestore._persistenceKey, firestore._freezeSettings()); + const connection = newConnection(databaseInfo); + const serializer = newSerializer(firestore._databaseId); + const datastore = newDatastore(firestore._authCredentials, firestore._appCheckCredentials, connection, serializer); + datastoreInstances.set(firestore, datastore); + } + return datastoreInstances.get(firestore); +} +/** + * Removes all components associated with the provided instance. Must be called + * when the `Firestore` instance is terminated. + */ +function removeComponents(firestore) { + const datastore = datastoreInstances.get(firestore); + if (datastore) { + logDebug(LOG_TAG$1, 'Removing Datastore'); + datastoreInstances.delete(firestore); + datastore.terminate(); + } +} +function makeDatabaseInfo(databaseId, appId, persistenceKey, settings) { + return new DatabaseInfo(databaseId, appId, persistenceKey, settings.host, settings.ssl, settings.experimentalForceLongPolling, settings.experimentalAutoDetectLongPolling, cloneLongPollingOptions(settings.experimentalLongPollingOptions), settings.useFetchStreams, settings.isUsingEmulator); +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LRU_COLLECTION_DISABLED = -1; +const LRU_DEFAULT_CACHE_SIZE_BYTES = 40 * 1024 * 1024; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Verifies whether `e` is an IndexedDbTransactionError. */ +function isIndexedDbTransactionError(e) { + // Use name equality, as instanceof checks on errors don't work with errors + // that wrap other errors. + return e.name === 'IndexedDbTransactionError'; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LRU_MINIMUM_CACHE_SIZE_BYTES = 1 * 1024 * 1024; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// settings() defaults: +const DEFAULT_HOST = 'firestore.googleapis.com'; +const DEFAULT_SSL = true; +// The minimum long-polling timeout is hardcoded on the server. The value here +// should be kept in sync with the value used by the server, as the server will +// silently ignore a value below the minimum and fall back to the default. +// Googlers see b/266868871 for relevant discussion. +const MIN_LONG_POLLING_TIMEOUT_SECONDS = 5; +// No maximum long-polling timeout is configured in the server, and defaults to +// 30 seconds, which is what Watch appears to use. +// Googlers see b/266868871 for relevant discussion. +const MAX_LONG_POLLING_TIMEOUT_SECONDS = 30; +// Whether long-polling auto-detected is enabled by default. +const DEFAULT_AUTO_DETECT_LONG_POLLING = true; +/** + * A concrete type describing all the values that can be applied via a + * user-supplied `FirestoreSettings` object. This is a separate type so that + * defaults can be supplied and the value can be checked for equality. + */ +class FirestoreSettingsImpl { + constructor(settings) { + if (settings.host === undefined) { + if (settings.ssl !== undefined) { + throw new FirestoreError(Code.INVALID_ARGUMENT, "Can't provide ssl option if host option is not set"); + } + this.host = DEFAULT_HOST; + this.ssl = DEFAULT_SSL; + } + else { + this.host = settings.host; + this.ssl = settings.ssl ?? DEFAULT_SSL; + } + this.isUsingEmulator = settings.emulatorOptions !== undefined; + this.credentials = settings.credentials; + this.ignoreUndefinedProperties = !!settings.ignoreUndefinedProperties; + this.localCache = settings.localCache; + if (settings.cacheSizeBytes === undefined) { + this.cacheSizeBytes = LRU_DEFAULT_CACHE_SIZE_BYTES; + } + else { + if (settings.cacheSizeBytes !== LRU_COLLECTION_DISABLED && + settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`); + } + else { + this.cacheSizeBytes = settings.cacheSizeBytes; + } + } + validateIsNotUsedTogether('experimentalForceLongPolling', settings.experimentalForceLongPolling, 'experimentalAutoDetectLongPolling', settings.experimentalAutoDetectLongPolling); + this.experimentalForceLongPolling = !!settings.experimentalForceLongPolling; + if (this.experimentalForceLongPolling) { + this.experimentalAutoDetectLongPolling = false; + } + else if (settings.experimentalAutoDetectLongPolling === undefined) { + this.experimentalAutoDetectLongPolling = DEFAULT_AUTO_DETECT_LONG_POLLING; + } + else { + // For backwards compatibility, coerce the value to boolean even though + // the TypeScript compiler has narrowed the type to boolean already. + // noinspection PointlessBooleanExpressionJS + this.experimentalAutoDetectLongPolling = + !!settings.experimentalAutoDetectLongPolling; + } + this.experimentalLongPollingOptions = cloneLongPollingOptions(settings.experimentalLongPollingOptions ?? {}); + validateLongPollingOptions(this.experimentalLongPollingOptions); + this.useFetchStreams = !!settings.useFetchStreams; + } + isEqual(other) { + return (this.host === other.host && + this.ssl === other.ssl && + this.credentials === other.credentials && + this.cacheSizeBytes === other.cacheSizeBytes && + this.experimentalForceLongPolling === + other.experimentalForceLongPolling && + this.experimentalAutoDetectLongPolling === + other.experimentalAutoDetectLongPolling && + longPollingOptionsEqual(this.experimentalLongPollingOptions, other.experimentalLongPollingOptions) && + this.ignoreUndefinedProperties === other.ignoreUndefinedProperties && + this.useFetchStreams === other.useFetchStreams); + } +} +function validateLongPollingOptions(options) { + if (options.timeoutSeconds !== undefined) { + if (isNaN(options.timeoutSeconds)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `invalid long polling timeout: ` + + `${options.timeoutSeconds} (must not be NaN)`); + } + if (options.timeoutSeconds < MIN_LONG_POLLING_TIMEOUT_SECONDS) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `invalid long polling timeout: ${options.timeoutSeconds} ` + + `(minimum allowed value is ${MIN_LONG_POLLING_TIMEOUT_SECONDS})`); + } + if (options.timeoutSeconds > MAX_LONG_POLLING_TIMEOUT_SECONDS) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `invalid long polling timeout: ${options.timeoutSeconds} ` + + `(maximum allowed value is ${MAX_LONG_POLLING_TIMEOUT_SECONDS})`); + } + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ +class Firestore { + /** @hideconstructor */ + constructor(_authCredentials, _appCheckCredentials, _databaseId, _app) { + this._authCredentials = _authCredentials; + this._appCheckCredentials = _appCheckCredentials; + this._databaseId = _databaseId; + this._app = _app; + /** + * Whether it's a Firestore or Firestore Lite instance. + */ + this.type = 'firestore-lite'; + this._persistenceKey = '(lite)'; + this._settings = new FirestoreSettingsImpl({}); + this._settingsFrozen = false; + this._emulatorOptions = {}; + // A task that is assigned when the terminate() is invoked and resolved when + // all components have shut down. Otherwise, Firestore is not terminated, + // which can mean either the FirestoreClient is in the process of starting, + // or restarting. + this._terminateTask = 'notTerminated'; + } + /** + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service + * instance. + */ + get app() { + if (!this._app) { + throw new FirestoreError(Code.FAILED_PRECONDITION, "Firestore was not initialized using the Firebase SDK. 'app' is " + + 'not available'); + } + return this._app; + } + get _initialized() { + return this._settingsFrozen; + } + get _terminated() { + return this._terminateTask !== 'notTerminated'; + } + _setSettings(settings) { + if (this._settingsFrozen) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore has already been started and its settings can no longer ' + + 'be changed. You can only modify settings before calling any other ' + + 'methods on a Firestore object.'); + } + this._settings = new FirestoreSettingsImpl(settings); + this._emulatorOptions = settings.emulatorOptions || {}; + if (settings.credentials !== undefined) { + this._authCredentials = makeAuthCredentialsProvider(settings.credentials); + } + } + _getSettings() { + return this._settings; + } + _getEmulatorOptions() { + return this._emulatorOptions; + } + _freezeSettings() { + this._settingsFrozen = true; + return this._settings; + } + _delete() { + // The `_terminateTask` must be assigned future that completes when + // terminate is complete. The existence of this future puts SDK in state + // that will not accept further API interaction. + if (this._terminateTask === 'notTerminated') { + this._terminateTask = this._terminate(); + } + return this._terminateTask; + } + async _restart() { + // The `_terminateTask` must equal 'notTerminated' after restart to + // signal that client is in a state that accepts API calls. + if (this._terminateTask === 'notTerminated') { + await this._terminate(); + } + else { + this._terminateTask = 'notTerminated'; + } + } + /** Returns a JSON-serializable representation of this `Firestore` instance. */ + toJSON() { + return { + app: this._app, + databaseId: this._databaseId, + settings: this._settings + }; + } + /** + * Terminates all components used by this client. Subclasses can override + * this method to clean up their own dependencies, but must also call this + * method. + * + * Only ever called once. + */ + _terminate() { + removeComponents(this); + return Promise.resolve(); + } +} +function initializeFirestore(app, settings, databaseId) { + if (!databaseId) { + databaseId = DEFAULT_DATABASE_NAME; + } + const provider = _getProvider(app, 'firestore/lite'); + if (provider.isInitialized(databaseId)) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'Firestore can only be initialized once per app.'); + } + return provider.initialize({ + options: settings, + instanceIdentifier: databaseId + }); +} +function getFirestore(appOrDatabaseId, optionalDatabaseId) { + const app = typeof appOrDatabaseId === 'object' ? appOrDatabaseId : getApp(); + const databaseId = typeof appOrDatabaseId === 'string' + ? appOrDatabaseId + : optionalDatabaseId || '(default)'; + const db = _getProvider(app, 'firestore/lite').getImmediate({ + identifier: databaseId + }); + if (!db._initialized) { + const emulator = getDefaultEmulatorHostnameAndPort('firestore'); + if (emulator) { + connectFirestoreEmulator(db, ...emulator); + } + } + return db; +} +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ +function connectFirestoreEmulator(firestore, host, port, options = {}) { + firestore = cast(firestore, Firestore); + const useSsl = isCloudWorkstation(host); + const settings = firestore._getSettings(); + const existingConfig = { + ...settings, + emulatorOptions: firestore._getEmulatorOptions() + }; + const newHostSetting = `${host}:${port}`; + if (useSsl) { + void pingServer(`https://${newHostSetting}`); + updateEmulatorBanner('Firestore', true); + } + if (settings.host !== DEFAULT_HOST && settings.host !== newHostSetting) { + logWarn('Host has been set in both settings() and connectFirestoreEmulator(), emulator host ' + + 'will be used.'); + } + const newConfig = { + ...settings, + host: newHostSetting, + ssl: useSsl, + emulatorOptions: options + }; + // No-op if the new configuration matches the current configuration. This supports SSR + // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice. + if (deepEqual(newConfig, existingConfig)) { + return; + } + firestore._setSettings(newConfig); + if (options.mockUserToken) { + let token; + let user; + if (typeof options.mockUserToken === 'string') { + token = options.mockUserToken; + user = User.MOCK_USER; + } + else { + // Let createMockUserToken validate first (catches common mistakes like + // invalid field "uid" and missing field "sub" / "user_id".) + token = createMockUserToken(options.mockUserToken, firestore._app?.options.projectId); + const uid = options.mockUserToken.sub || options.mockUserToken.user_id; + if (!uid) { + throw new FirestoreError(Code.INVALID_ARGUMENT, "mockUserToken must contain 'sub' or 'user_id' field!"); + } + user = new User(uid); + } + firestore._authCredentials = new EmulatorAuthCredentialsProvider(new OAuthToken(token, user)); + } +} +/** + * Terminates the provided `Firestore` instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` functions + * may be used. Any other function will throw a `FirestoreError`. Termination + * does not cancel any pending writes, and any promises that are awaiting a + * response from the server will not be resolved. + * + * To restart after termination, create a new instance of `Firestore` with + * {@link (getFirestore:1)}. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all of + * its resources or in combination with {@link clearIndexedDbPersistence} to + * ensure that all local state is destroyed between test runs. + * + * @param firestore - The `Firestore` instance to terminate. + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ +function terminate(firestore) { + firestore = cast(firestore, Firestore); + _removeServiceInstance(firestore.app, 'firestore/lite'); + return firestore._delete(); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function registerFirestore() { + setSDKVersion(`${SDK_VERSION$1}_lite`); + _registerComponent(new Component('firestore/lite', (container, { instanceIdentifier: databaseId, options: settings }) => { + const app = container.getProvider('app').getImmediate(); + const firestoreInstance = new Firestore(new LiteAuthCredentialsProvider(container.getProvider('auth-internal')), new LiteAppCheckTokenProvider(app, container.getProvider('app-check-internal')), databaseIdFromApp(app, databaseId), app); + if (settings) { + firestoreInstance._setSettings(settings); + } + return firestoreInstance; + }, 'PUBLIC').setMultipleInstances(true)); + // RUNTIME_ENV and BUILD_TARGET are replaced by real values during the compilation + registerVersion('firestore-lite', version$1, 'node'); + registerVersion('firestore-lite', version$1, 'esm2020'); +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Concrete implementation of the Aggregate type. + */ +class AggregateImpl { + constructor(alias, aggregateType, fieldPath) { + this.alias = alias; + this.aggregateType = aggregateType; + this.fieldPath = fieldPath; + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents an aggregation that can be performed by Firestore. + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +class AggregateField { + /** + * Create a new AggregateField + * @param aggregateType Specifies the type of aggregation operation to perform. + * @param _internalFieldPath Optionally specifies the field that is aggregated. + * @internal + */ + constructor(aggregateType = 'count', _internalFieldPath) { + this._internalFieldPath = _internalFieldPath; + /** A type string to uniquely identify instances of this class. */ + this.type = 'AggregateField'; + this.aggregateType = aggregateType; + } +} +/** + * The results of executing an aggregation query. + */ +class AggregateQuerySnapshot { + /** @hideconstructor */ + constructor(query, _userDataWriter, _data) { + this._userDataWriter = _userDataWriter; + this._data = _data; + /** A type string to uniquely identify instances of this class. */ + this.type = 'AggregateQuerySnapshot'; + this.query = query; + } + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ + data() { + return this._userDataWriter.convertObjectMap(this._data); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `Query` refers to a query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ +class Query { + // This is the lite version of the Query class in the main SDK. + /** @hideconstructor protected */ + constructor(firestore, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter, _query) { + this.converter = converter; + this._query = _query; + /** The type of this Firestore reference. */ + this.type = 'query'; + this.firestore = firestore; + } + withConverter(converter) { + return new Query(this.firestore, converter, this._query); + } +} +/** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. + */ +class DocumentReference { + /** @hideconstructor */ + constructor(firestore, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter, _key) { + this.converter = converter; + this._key = _key; + /** The type of this Firestore reference. */ + this.type = 'document'; + this.firestore = firestore; + } + get _path() { + return this._key.path; + } + /** + * The document's identifier within its collection. + */ + get id() { + return this._key.path.lastSegment(); + } + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ + get path() { + return this._key.path.canonicalString(); + } + /** + * The collection this `DocumentReference` belongs to. + */ + get parent() { + return new CollectionReference(this.firestore, this.converter, this._key.path.popLast()); + } + withConverter(converter) { + return new DocumentReference(this.firestore, converter, this._key); + } + /** + * Returns a JSON-serializable representation of this `DocumentReference` instance. + * + * @returns a JSON representation of this object. + */ + toJSON() { + return { + type: DocumentReference._jsonSchemaVersion, + referencePath: this._key.toString() + }; + } + static fromJSON(firestore, json, converter) { + if (validateJSON(json, DocumentReference._jsonSchema)) { + return new DocumentReference(firestore, converter ? converter : null, new DocumentKey(ResourcePath.fromString(json.referencePath))); + } + } +} +DocumentReference._jsonSchemaVersion = 'firestore/documentReference/1.0'; +DocumentReference._jsonSchema = { + type: property('string', DocumentReference._jsonSchemaVersion), + referencePath: property('string') +}; +/** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using {@link (query:1)}). + */ +class CollectionReference extends Query { + /** @hideconstructor */ + constructor(firestore, converter, _path) { + super(firestore, converter, newQueryForPath(_path)); + this._path = _path; + /** The type of this Firestore reference. */ + this.type = 'collection'; + } + /** The collection's identifier. */ + get id() { + return this._query.path.lastSegment(); + } + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ + get path() { + return this._query.path.canonicalString(); + } + /** + * A reference to the containing `DocumentReference` if this is a + * subcollection. If this isn't a subcollection, the reference is null. + */ + get parent() { + const parentPath = this._path.popLast(); + if (parentPath.isEmpty()) { + return null; + } + else { + return new DocumentReference(this.firestore, + /* converter= */ null, new DocumentKey(parentPath)); + } + } + withConverter(converter) { + return new CollectionReference(this.firestore, converter, this._path); + } +} +function collection(parent, path, ...pathSegments) { + parent = getModularInstance(parent); + validateNonEmptyArgument('collection', 'path', path); + if (parent instanceof Firestore) { + const absolutePath = ResourcePath.fromString(path, ...pathSegments); + validateCollectionPath(absolutePath); + return new CollectionReference(parent, /* converter= */ null, absolutePath); + } + else { + if (!(parent instanceof DocumentReference) && + !(parent instanceof CollectionReference)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Expected first argument to collection() to be a CollectionReference, ' + + 'a DocumentReference or FirebaseFirestore'); + } + const absolutePath = parent._path.child(ResourcePath.fromString(path, ...pathSegments)); + validateCollectionPath(absolutePath); + return new CollectionReference(parent.firestore, + /* converter= */ null, absolutePath); + } +} +// TODO(firestorelite): Consider using ErrorFactory - +// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106 +/** + * Creates and returns a new `Query` instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given `collectionId`. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param collectionId - Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `Query`. + */ +function collectionGroup(firestore, collectionId) { + firestore = cast(firestore, Firestore); + validateNonEmptyArgument('collectionGroup', 'collection id', collectionId); + if (collectionId.indexOf('/') >= 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid collection ID '${collectionId}' passed to function ` + + `collectionGroup(). Collection IDs must not contain '/'.`); + } + return new Query(firestore, + /* converter= */ null, newQueryForCollectionGroup(collectionId)); +} +function doc(parent, path, ...pathSegments) { + parent = getModularInstance(parent); + // We allow omission of 'pathString' but explicitly prohibit passing in both + // 'undefined' and 'null'. + if (arguments.length === 1) { + path = AutoId.newId(); + } + validateNonEmptyArgument('doc', 'path', path); + if (parent instanceof Firestore) { + const absolutePath = ResourcePath.fromString(path, ...pathSegments); + validateDocumentPath(absolutePath); + return new DocumentReference(parent, + /* converter= */ null, new DocumentKey(absolutePath)); + } + else { + if (!(parent instanceof DocumentReference) && + !(parent instanceof CollectionReference)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Expected first argument to collection() to be a CollectionReference, ' + + 'a DocumentReference or FirebaseFirestore'); + } + const absolutePath = parent._path.child(ResourcePath.fromString(path, ...pathSegments)); + validateDocumentPath(absolutePath); + return new DocumentReference(parent.firestore, parent instanceof CollectionReference ? parent.converter : null, new DocumentKey(absolutePath)); + } +} +/** + * Returns true if the provided references are equal. + * + * @param left - A reference to compare. + * @param right - A reference to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +function refEqual(left, right) { + left = getModularInstance(left); + right = getModularInstance(right); + if ((left instanceof DocumentReference || + left instanceof CollectionReference) && + (right instanceof DocumentReference || right instanceof CollectionReference)) { + return (left.firestore === right.firestore && + left.path === right.path && + left.converter === right.converter); + } + return false; +} +/** + * Returns true if the provided queries point to the same collection and apply + * the same constraints. + * + * @param left - A `Query` to compare. + * @param right - A `Query` to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +function queryEqual(left, right) { + left = getModularInstance(left); + right = getModularInstance(right); + if (left instanceof Query && right instanceof Query) { + return (left.firestore === right.firestore && + queryEquals(left._query, right._query) && + left.converter === right.converter); + } + return false; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing an array of bytes. + */ +class Bytes { + /** @hideconstructor */ + constructor(byteString) { + this._byteString = byteString; + } + /** + * Creates a new `Bytes` object from the given Base64 string, converting it to + * bytes. + * + * @param base64 - The Base64 string used to create the `Bytes` object. + */ + static fromBase64String(base64) { + try { + return new Bytes(ByteString.fromBase64String(base64)); + } + catch (e) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Failed to construct data from Base64 string: ' + e); + } + } + /** + * Creates a new `Bytes` object from the given Uint8Array. + * + * @param array - The Uint8Array used to create the `Bytes` object. + */ + static fromUint8Array(array) { + return new Bytes(ByteString.fromUint8Array(array)); + } + /** + * Returns the underlying bytes as a Base64-encoded string. + * + * @returns The Base64-encoded string created from the `Bytes` object. + */ + toBase64() { + return this._byteString.toBase64(); + } + /** + * Returns the underlying bytes in a new `Uint8Array`. + * + * @returns The Uint8Array created from the `Bytes` object. + */ + toUint8Array() { + return this._byteString.toUint8Array(); + } + /** + * Returns a string representation of the `Bytes` object. + * + * @returns A string representation of the `Bytes` object. + */ + toString() { + return 'Bytes(base64: ' + this.toBase64() + ')'; + } + /** + * Returns true if this `Bytes` object is equal to the provided one. + * + * @param other - The `Bytes` object to compare against. + * @returns true if this `Bytes` object is equal to the provided one. + */ + isEqual(other) { + return this._byteString.isEqual(other._byteString); + } + /** + * Returns a JSON-serializable representation of this `Bytes` instance. + * + * @returns a JSON representation of this object. + */ + toJSON() { + return { + type: Bytes._jsonSchemaVersion, + bytes: this.toBase64() + }; + } + /** + * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}. + * + * @param json a JSON object represention of a `Bytes` instance + * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json) { + if (validateJSON(json, Bytes._jsonSchema)) { + return Bytes.fromBase64String(json.bytes); + } + } +} +Bytes._jsonSchemaVersion = 'firestore/bytes/1.0'; +Bytes._jsonSchema = { + type: property('string', Bytes._jsonSchemaVersion), + bytes: property('string') +}; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `FieldPath` refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + * + * Create a `FieldPath` by providing field names. If more than one field + * name is provided, the path will point to a nested field in a document. + */ +class FieldPath { + /** + * Creates a `FieldPath` from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames - A list of field names. + */ + constructor(...fieldNames) { + for (let i = 0; i < fieldNames.length; ++i) { + if (fieldNames[i].length === 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid field name at argument $(i + 1). ` + + 'Field names must not be empty.'); + } + } + this._internalPath = new FieldPath$1(fieldNames); + } + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other - The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ + isEqual(other) { + return this._internalPath.isEqual(other._internalPath); + } +} +/** + * Returns a special sentinel `FieldPath` to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ +function documentId() { + return new FieldPath(DOCUMENT_KEY_NAME); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Sentinel values that can be used when writing document fields with `set()` + * or `update()`. + */ +class FieldValue { + /** + * @param _methodName - The public API endpoint that returns this class. + * @hideconstructor + */ + constructor(_methodName) { + this._methodName = _methodName; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ +class GeoPoint { + /** + * Creates a new immutable `GeoPoint` object with the provided latitude and + * longitude values. + * @param latitude - The latitude as number between -90 and 90. + * @param longitude - The longitude as number between -180 and 180. + */ + constructor(latitude, longitude) { + if (!isFinite(latitude) || latitude < -90 || latitude > 90) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Latitude must be a number between -90 and 90, but was: ' + latitude); + } + if (!isFinite(longitude) || longitude < -180 || longitude > 180) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Longitude must be a number between -180 and 180, but was: ' + longitude); + } + this._lat = latitude; + this._long = longitude; + } + /** + * The latitude of this `GeoPoint` instance. + */ + get latitude() { + return this._lat; + } + /** + * The longitude of this `GeoPoint` instance. + */ + get longitude() { + return this._long; + } + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other - The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ + isEqual(other) { + return this._lat === other._lat && this._long === other._long; + } + /** + * Actually private to JS consumers of our API, so this function is prefixed + * with an underscore. + */ + _compareTo(other) { + return (primitiveComparator(this._lat, other._lat) || + primitiveComparator(this._long, other._long)); + } + /** + * Returns a JSON-serializable representation of this `GeoPoint` instance. + * + * @returns a JSON representation of this object. + */ + toJSON() { + return { + latitude: this._lat, + longitude: this._long, + type: GeoPoint._jsonSchemaVersion + }; + } + /** + * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}. + * + * @param json a JSON object represention of a `GeoPoint` instance + * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json) { + if (validateJSON(json, GeoPoint._jsonSchema)) { + return new GeoPoint(json.latitude, json.longitude); + } + } +} +GeoPoint._jsonSchemaVersion = 'firestore/geoPoint/1.0'; +GeoPoint._jsonSchema = { + type: property('string', GeoPoint._jsonSchemaVersion), + latitude: property('number'), + longitude: property('number') +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Verifies equality for an array of primitives. + * + * @private + * @internal + * @param left Array of primitives. + * @param right Array of primitives. + * @return True if arrays are equal. + */ +function isPrimitiveArrayEqual(left, right) { + if (left.length !== right.length) { + return false; + } + for (let i = 0; i < left.length; ++i) { + if (left[i] !== right[i]) { + return false; + } + } + return true; +} + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link vector}. + * + * @class VectorValue + */ +class VectorValue { + /** + * @private + * @internal + */ + constructor(values) { + // Making a copy of the parameter. + this._values = (values || []).map(n => n); + } + /** + * Returns a copy of the raw number array form of the vector. + */ + toArray() { + return this._values.map(n => n); + } + /** + * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise. + */ + isEqual(other) { + return isPrimitiveArrayEqual(this._values, other._values); + } + /** + * Returns a JSON-serializable representation of this `VectorValue` instance. + * + * @returns a JSON representation of this object. + */ + toJSON() { + return { + type: VectorValue._jsonSchemaVersion, + vectorValues: this._values + }; + } + /** + * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}. + * + * @param json a JSON object represention of a `VectorValue` instance. + * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json) { + if (validateJSON(json, VectorValue._jsonSchema)) { + if (Array.isArray(json.vectorValues) && + json.vectorValues.every(element => typeof element === 'number')) { + return new VectorValue(json.vectorValues); + } + throw new FirestoreError(Code.INVALID_ARGUMENT, "Expected 'vectorValues' field to be a number array"); + } + } +} +VectorValue._jsonSchemaVersion = 'firestore/vectorValue/1.0'; +VectorValue._jsonSchema = { + type: property('string', VectorValue._jsonSchemaVersion), + vectorValues: property('object') +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const RESERVED_FIELD_REGEX = /^__.*__$/; +/** The result of parsing document data (e.g. for a setData call). */ +class ParsedSetData { + constructor(data, fieldMask, fieldTransforms) { + this.data = data; + this.fieldMask = fieldMask; + this.fieldTransforms = fieldTransforms; + } + toMutation(key, precondition) { + if (this.fieldMask !== null) { + return new PatchMutation(key, this.data, this.fieldMask, precondition, this.fieldTransforms); + } + else { + return new SetMutation(key, this.data, precondition, this.fieldTransforms); + } + } +} +/** The result of parsing "update" data (i.e. for an updateData call). */ +class ParsedUpdateData { + constructor(data, + // The fieldMask does not include document transforms. + fieldMask, fieldTransforms) { + this.data = data; + this.fieldMask = fieldMask; + this.fieldTransforms = fieldTransforms; + } + toMutation(key, precondition) { + return new PatchMutation(key, this.data, this.fieldMask, precondition, this.fieldTransforms); + } +} +function isWrite(dataSource) { + switch (dataSource) { + case 0 /* UserDataSource.Set */: // fall through + case 2 /* UserDataSource.MergeSet */: // fall through + case 1 /* UserDataSource.Update */: + return true; + case 3 /* UserDataSource.Argument */: + case 4 /* UserDataSource.ArrayArgument */: + return false; + default: + throw fail(0x9c4b, { + dataSource + }); + } +} +/** A "context" object passed around while parsing user data. */ +class ParseContextImpl { + /** + * Initializes a ParseContext with the given source and path. + * + * @param settings - The settings for the parser. + * @param databaseId - The database ID of the Firestore instance. + * @param serializer - The serializer to use to generate the Value proto. + * @param ignoreUndefinedProperties - Whether to ignore undefined properties + * rather than throw. + * @param fieldTransforms - A mutable list of field transforms encountered + * while parsing the data. + * @param fieldMask - A mutable list of field paths encountered while parsing + * the data. + * + * TODO(b/34871131): We don't support array paths right now, so path can be + * null to indicate the context represents any location within an array (in + * which case certain features will not work and errors will be somewhat + * compromised). + */ + constructor(settings, databaseId, serializer, ignoreUndefinedProperties, fieldTransforms, fieldMask) { + this.settings = settings; + this.databaseId = databaseId; + this.serializer = serializer; + this.ignoreUndefinedProperties = ignoreUndefinedProperties; + // Minor hack: If fieldTransforms is undefined, we assume this is an + // external call and we need to validate the entire path. + if (fieldTransforms === undefined) { + this.validatePath(); + } + this.fieldTransforms = fieldTransforms || []; + this.fieldMask = fieldMask || []; + } + get path() { + return this.settings.path; + } + get dataSource() { + return this.settings.dataSource; + } + /** Returns a new context with the specified settings overwritten. */ + contextWith(configuration) { + return new ParseContextImpl({ ...this.settings, ...configuration }, this.databaseId, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask); + } + childContextForField(field) { + const childPath = this.path?.child(field); + const context = this.contextWith({ path: childPath, arrayElement: false }); + context.validatePathSegment(field); + return context; + } + childContextForFieldPath(field) { + const childPath = this.path?.child(field); + const context = this.contextWith({ path: childPath, arrayElement: false }); + context.validatePath(); + return context; + } + childContextForArray(index) { + // TODO(b/34871131): We don't support array paths right now; so make path + // undefined. + return this.contextWith({ path: undefined, arrayElement: true }); + } + createError(reason) { + return createError(reason, this.settings.methodName, this.settings.hasConverter || false, this.path, this.settings.targetDoc); + } + /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ + contains(fieldPath) { + return (this.fieldMask.find(field => fieldPath.isPrefixOf(field)) !== undefined || + this.fieldTransforms.find(transform => fieldPath.isPrefixOf(transform.field)) !== undefined); + } + validatePath() { + // TODO(b/34871131): Remove null check once we have proper paths for fields + // within arrays. + if (!this.path) { + return; + } + for (let i = 0; i < this.path.length; i++) { + this.validatePathSegment(this.path.get(i)); + } + } + validatePathSegment(segment) { + if (segment.length === 0) { + throw this.createError('Document fields must not be empty'); + } + if (isWrite(this.dataSource) && RESERVED_FIELD_REGEX.test(segment)) { + throw this.createError('Document fields cannot begin and end with "__"'); + } + } +} +/** + * Helper for parsing raw user input (provided via the API) into internal model + * classes. + */ +class UserDataReader { + constructor(databaseId, ignoreUndefinedProperties, serializer) { + this.databaseId = databaseId; + this.ignoreUndefinedProperties = ignoreUndefinedProperties; + this.serializer = serializer || newSerializer(databaseId); + } + /** Creates a new top-level parse context. */ + createContext(dataSource, methodName, targetDoc, hasConverter = false) { + return new ParseContextImpl({ + dataSource, + methodName, + targetDoc, + path: FieldPath$1.emptyPath(), + arrayElement: false, + hasConverter + }, this.databaseId, this.serializer, this.ignoreUndefinedProperties); + } +} +function newUserDataReader(firestore) { + const settings = firestore._freezeSettings(); + const serializer = newSerializer(firestore._databaseId); + return new UserDataReader(firestore._databaseId, !!settings.ignoreUndefinedProperties, serializer); +} +/** Parse document data from a set() call. */ +function parseSetData(userDataReader, methodName, targetDoc, input, hasConverter, options = {}) { + const context = userDataReader.createContext(options.merge || options.mergeFields + ? 2 /* UserDataSource.MergeSet */ + : 0 /* UserDataSource.Set */, methodName, targetDoc, hasConverter); + validatePlainObject('Data must be an object, but it was:', context, input); + const updateData = parseObject(input, context); + let fieldMask; + let fieldTransforms; + if (options.merge) { + fieldMask = new FieldMask(context.fieldMask); + fieldTransforms = context.fieldTransforms; + } + else if (options.mergeFields) { + const validatedFieldPaths = []; + for (const stringOrFieldPath of options.mergeFields) { + const fieldPath = fieldPathFromArgument$1(methodName, stringOrFieldPath, targetDoc); + if (!context.contains(fieldPath)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Field '${fieldPath}' is specified in your field mask but missing from your input data.`); + } + if (!fieldMaskContains(validatedFieldPaths, fieldPath)) { + validatedFieldPaths.push(fieldPath); + } + } + fieldMask = new FieldMask(validatedFieldPaths); + fieldTransforms = context.fieldTransforms.filter(transform => fieldMask.covers(transform.field)); + } + else { + fieldMask = null; + fieldTransforms = context.fieldTransforms; + } + return new ParsedSetData(new ObjectValue(updateData), fieldMask, fieldTransforms); +} +class DeleteFieldValueImpl extends FieldValue { + _toFieldTransform(context) { + if (context.dataSource === 2 /* UserDataSource.MergeSet */) { + // No transform to add for a delete, but we need to add it to our + // fieldMask so it gets deleted. + context.fieldMask.push(context.path); + } + else if (context.dataSource === 1 /* UserDataSource.Update */) { + throw context.createError(`${this._methodName}() can only appear at the top level ` + + 'of your update data'); + } + else { + // We shouldn't encounter delete sentinels for queries or non-merge set() calls. + throw context.createError(`${this._methodName}() cannot be used with set() unless you pass ` + + '{merge:true}'); + } + return null; + } + isEqual(other) { + return other instanceof DeleteFieldValueImpl; + } +} +/** + * Creates a child context for parsing SerializableFieldValues. + * + * This is different than calling `ParseContext.contextWith` because it keeps + * the fieldTransforms and fieldMask separate. + * + * The created context has its `dataSource` set to `UserDataSource.Argument`. + * Although these values are used with writes, any elements in these FieldValues + * are not considered writes since they cannot contain any FieldValue sentinels, + * etc. + * + * @param fieldValue - The sentinel FieldValue for which to create a child + * context. + * @param context - The parent context. + * @param arrayElement - Whether or not the FieldValue has an array. + */ +function createSentinelChildContext(fieldValue, context, arrayElement) { + return new ParseContextImpl({ + dataSource: 3 /* UserDataSource.Argument */, + targetDoc: context.settings.targetDoc, + methodName: fieldValue._methodName, + arrayElement + }, context.databaseId, context.serializer, context.ignoreUndefinedProperties); +} +class ServerTimestampFieldValueImpl extends FieldValue { + _toFieldTransform(context) { + return new FieldTransform(context.path, new ServerTimestampTransform()); + } + isEqual(other) { + return other instanceof ServerTimestampFieldValueImpl; + } +} +class ArrayUnionFieldValueImpl extends FieldValue { + constructor(methodName, _elements) { + super(methodName); + this._elements = _elements; + } + _toFieldTransform(context) { + const parseContext = createSentinelChildContext(this, context, + /*array=*/ true); + const parsedElements = this._elements.map(element => parseData(element, parseContext)); + const arrayUnion = new ArrayUnionTransformOperation(parsedElements); + return new FieldTransform(context.path, arrayUnion); + } + isEqual(other) { + return (other instanceof ArrayUnionFieldValueImpl && + deepEqual(this._elements, other._elements)); + } +} +class ArrayRemoveFieldValueImpl extends FieldValue { + constructor(methodName, _elements) { + super(methodName); + this._elements = _elements; + } + _toFieldTransform(context) { + const parseContext = createSentinelChildContext(this, context, + /*array=*/ true); + const parsedElements = this._elements.map(element => parseData(element, parseContext)); + const arrayUnion = new ArrayRemoveTransformOperation(parsedElements); + return new FieldTransform(context.path, arrayUnion); + } + isEqual(other) { + return (other instanceof ArrayRemoveFieldValueImpl && + deepEqual(this._elements, other._elements)); + } +} +class NumericIncrementFieldValueImpl extends FieldValue { + constructor(methodName, _operand) { + super(methodName); + this._operand = _operand; + } + _toFieldTransform(context) { + const numericIncrement = new NumericIncrementTransformOperation(context.serializer, toNumber(context.serializer, this._operand)); + return new FieldTransform(context.path, numericIncrement); + } + isEqual(other) { + return (other instanceof NumericIncrementFieldValueImpl && + this._operand === other._operand); + } +} +/** Parse update data from an update() call. */ +function parseUpdateData(userDataReader, methodName, targetDoc, input) { + const context = userDataReader.createContext(1 /* UserDataSource.Update */, methodName, targetDoc); + validatePlainObject('Data must be an object, but it was:', context, input); + const fieldMaskPaths = []; + const updateData = ObjectValue.empty(); + forEach(input, (key, value) => { + const path = fieldPathFromDotSeparatedString(methodName, key, targetDoc); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + value = getModularInstance(value); + const childContext = context.childContextForFieldPath(path); + if (value instanceof DeleteFieldValueImpl) { + // Add it to the field mask, but don't add anything to updateData. + fieldMaskPaths.push(path); + } + else { + const parsedValue = parseData(value, childContext); + if (parsedValue != null) { + fieldMaskPaths.push(path); + updateData.set(path, parsedValue); + } + } + }); + const mask = new FieldMask(fieldMaskPaths); + return new ParsedUpdateData(updateData, mask, context.fieldTransforms); +} +/** Parse update data from a list of field/value arguments. */ +function parseUpdateVarargs(userDataReader, methodName, targetDoc, field, value, moreFieldsAndValues) { + const context = userDataReader.createContext(1 /* UserDataSource.Update */, methodName, targetDoc); + const keys = [fieldPathFromArgument$1(methodName, field, targetDoc)]; + const values = [value]; + if (moreFieldsAndValues.length % 2 !== 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${methodName}() needs to be called with an even number ` + + 'of arguments that alternate between field names and values.'); + } + for (let i = 0; i < moreFieldsAndValues.length; i += 2) { + keys.push(fieldPathFromArgument$1(methodName, moreFieldsAndValues[i])); + values.push(moreFieldsAndValues[i + 1]); + } + const fieldMaskPaths = []; + const updateData = ObjectValue.empty(); + // We iterate in reverse order to pick the last value for a field if the + // user specified the field multiple times. + for (let i = keys.length - 1; i >= 0; --i) { + if (!fieldMaskContains(fieldMaskPaths, keys[i])) { + const path = keys[i]; + let value = values[i]; + // For Compat types, we have to "extract" the underlying types before + // performing validation. + value = getModularInstance(value); + const childContext = context.childContextForFieldPath(path); + if (value instanceof DeleteFieldValueImpl) { + // Add it to the field mask, but don't add anything to updateData. + fieldMaskPaths.push(path); + } + else { + const parsedValue = parseData(value, childContext); + if (parsedValue != null) { + fieldMaskPaths.push(path); + updateData.set(path, parsedValue); + } + } + } + } + const mask = new FieldMask(fieldMaskPaths); + return new ParsedUpdateData(updateData, mask, context.fieldTransforms); +} +/** + * Parse a "query value" (e.g. value in a where filter or a value in a cursor + * bound). + * + * @param allowArrays - Whether the query value is an array that may directly + * contain additional arrays (e.g. the operand of an `in` query). + */ +function parseQueryValue(userDataReader, methodName, input, allowArrays = false) { + const context = userDataReader.createContext(allowArrays ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */, methodName); + const parsed = parseData(input, context); + return parsed; +} +/** + * Parses user data to Protobuf Values. + * + * @param input - Data to be parsed. + * @param context - A context object representing the current path being parsed, + * the source of the data being parsed, etc. + * @returns The parsed value, or null if the value was a FieldValue sentinel + * that should not be included in the resulting parsed data. + */ +function parseData(input, context) { + // Unwrap the API type from the Compat SDK. This will return the API type + // from firestore-exp. + input = getModularInstance(input); + if (looksLikeJsonObject(input)) { + validatePlainObject('Unsupported field value:', context, input); + return parseObject(input, context); + } + else if (input instanceof FieldValue) { + // FieldValues usually parse into transforms (except deleteField()) + // in which case we do not want to include this field in our parsed data + // (as doing so will overwrite the field directly prior to the transform + // trying to transform it). So we don't add this location to + // context.fieldMask and we return null as our parsing result. + parseSentinelFieldValue(input, context); + return null; + } + else if (input === undefined && context.ignoreUndefinedProperties) { + // If the input is undefined it can never participate in the fieldMask, so + // don't handle this below. If `ignoreUndefinedProperties` is false, + // `parseScalarValue` will reject an undefined value. + return null; + } + else { + // If context.path is null we are inside an array and we don't support + // field mask paths more granular than the top-level array. + if (context.path) { + context.fieldMask.push(context.path); + } + if (input instanceof Array) { + // TODO(b/34871131): Include the path containing the array in the error + // message. + // In the case of IN queries, the parsed data is an array (representing + // the set of values to be included for the IN query) that may directly + // contain additional arrays (each representing an individual field + // value), so we disable this validation. + if (context.settings.arrayElement && + context.dataSource !== 4 /* UserDataSource.ArrayArgument */) { + throw context.createError('Nested arrays are not supported'); + } + return parseArray(input, context); + } + else { + return parseScalarValue(input, context); + } + } +} +function parseObject(obj, context) { + const fields = {}; + if (isEmpty(obj)) { + // If we encounter an empty object, we explicitly add it to the update + // mask to ensure that the server creates a map entry. + if (context.path && context.path.length > 0) { + context.fieldMask.push(context.path); + } + } + else { + forEach(obj, (key, val) => { + const parsedValue = parseData(val, context.childContextForField(key)); + if (parsedValue != null) { + fields[key] = parsedValue; + } + }); + } + return { mapValue: { fields } }; +} +function parseArray(array, context) { + const values = []; + let entryIndex = 0; + for (const entry of array) { + let parsedEntry = parseData(entry, context.childContextForArray(entryIndex)); + if (parsedEntry == null) { + // Just include nulls in the array for fields being replaced with a + // sentinel. + parsedEntry = { nullValue: 'NULL_VALUE' }; + } + values.push(parsedEntry); + entryIndex++; + } + return { arrayValue: { values } }; +} +/** + * "Parses" the provided FieldValueImpl, adding any necessary transforms to + * context.fieldTransforms. + */ +function parseSentinelFieldValue(value, context) { + // Sentinels are only supported with writes, and not within arrays. + if (!isWrite(context.dataSource)) { + throw context.createError(`${value._methodName}() can only be used with update() and set()`); + } + if (!context.path) { + throw context.createError(`${value._methodName}() is not currently supported inside arrays`); + } + const fieldTransform = value._toFieldTransform(context); + if (fieldTransform) { + context.fieldTransforms.push(fieldTransform); + } +} +/** + * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue) + * + * @returns The parsed value + */ +function parseScalarValue(value, context) { + value = getModularInstance(value); + if (value === null) { + return { nullValue: 'NULL_VALUE' }; + } + else if (typeof value === 'number') { + return toNumber(context.serializer, value); + } + else if (typeof value === 'boolean') { + return { booleanValue: value }; + } + else if (typeof value === 'string') { + return { stringValue: value }; + } + else if (value instanceof Date) { + const timestamp = Timestamp.fromDate(value); + return { + timestampValue: toTimestamp(context.serializer, timestamp) + }; + } + else if (value instanceof Timestamp) { + // Firestore backend truncates precision down to microseconds. To ensure + // offline mode works the same with regards to truncation, perform the + // truncation immediately without waiting for the backend to do that. + const timestamp = new Timestamp(value.seconds, Math.floor(value.nanoseconds / 1000) * 1000); + return { + timestampValue: toTimestamp(context.serializer, timestamp) + }; + } + else if (value instanceof GeoPoint) { + return { + geoPointValue: { + latitude: value.latitude, + longitude: value.longitude + } + }; + } + else if (value instanceof Bytes) { + return { bytesValue: toBytes(context.serializer, value._byteString) }; + } + else if (value instanceof DocumentReference) { + const thisDb = context.databaseId; + const otherDb = value.firestore._databaseId; + if (!otherDb.isEqual(thisDb)) { + throw context.createError('Document reference is for database ' + + `${otherDb.projectId}/${otherDb.database} but should be ` + + `for database ${thisDb.projectId}/${thisDb.database}`); + } + return { + referenceValue: toResourceName(value.firestore._databaseId || context.databaseId, value._key.path) + }; + } + else if (value instanceof VectorValue) { + return parseVectorValue(value, context); + } + else { + throw context.createError(`Unsupported field value: ${valueDescription(value)}`); + } +} +/** + * Creates a new VectorValue proto value (using the internal format). + */ +function parseVectorValue(value, context) { + const mapValue = { + fields: { + [TYPE_KEY]: { + stringValue: VECTOR_VALUE_SENTINEL + }, + [VECTOR_MAP_VECTORS_KEY]: { + arrayValue: { + values: value.toArray().map(value => { + if (typeof value !== 'number') { + throw context.createError('VectorValues must only contain numeric values.'); + } + return toDouble(context.serializer, value); + }) + } + } + } + }; + return { mapValue }; +} +/** + * Checks whether an object looks like a JSON object that should be converted + * into a struct. Normal class/prototype instances are considered to look like + * JSON objects since they should be converted to a struct value. Arrays, Dates, + * GeoPoints, etc. are not considered to look like JSON objects since they map + * to specific FieldValue types other than ObjectValue. + */ +function looksLikeJsonObject(input) { + return (typeof input === 'object' && + input !== null && + !(input instanceof Array) && + !(input instanceof Date) && + !(input instanceof Timestamp) && + !(input instanceof GeoPoint) && + !(input instanceof Bytes) && + !(input instanceof DocumentReference) && + !(input instanceof FieldValue) && + !(input instanceof VectorValue)); +} +function validatePlainObject(message, context, input) { + if (!looksLikeJsonObject(input) || !isPlainObject(input)) { + const description = valueDescription(input); + if (description === 'an object') { + // Massage the error if it was an object. + throw context.createError(message + ' a custom object'); + } + else { + throw context.createError(message + ' ' + description); + } + } +} +/** + * Helper that calls fromDotSeparatedString() but wraps any error thrown. + */ +function fieldPathFromArgument$1(methodName, path, targetDoc) { + // If required, replace the FieldPath Compat class with the firestore-exp + // FieldPath. + path = getModularInstance(path); + if (path instanceof FieldPath) { + return path._internalPath; + } + else if (typeof path === 'string') { + return fieldPathFromDotSeparatedString(methodName, path); + } + else { + const message = 'Field path arguments must be of type string or '; + throw createError(message, methodName, + /* hasConverter= */ false, + /* path= */ undefined, targetDoc); + } +} +/** + * Matches any characters in a field path string that are reserved. + */ +const FIELD_PATH_RESERVED = new RegExp('[~\\*/\\[\\]]'); +/** + * Wraps fromDotSeparatedString with an error message about the method that + * was thrown. + * @param methodName - The publicly visible method name + * @param path - The dot-separated string form of a field path which will be + * split on dots. + * @param targetDoc - The document against which the field path will be + * evaluated. + */ +function fieldPathFromDotSeparatedString(methodName, path, targetDoc) { + const found = path.search(FIELD_PATH_RESERVED); + if (found >= 0) { + throw createError(`Invalid field path (${path}). Paths must not contain ` + + `'~', '*', '/', '[', or ']'`, methodName, + /* hasConverter= */ false, + /* path= */ undefined, targetDoc); + } + try { + return new FieldPath(...path.split('.'))._internalPath; + } + catch (e) { + throw createError(`Invalid field path (${path}). Paths must not be empty, ` + + `begin with '.', end with '.', or contain '..'`, methodName, + /* hasConverter= */ false, + /* path= */ undefined, targetDoc); + } +} +function createError(reason, methodName, hasConverter, path, targetDoc) { + const hasPath = path && !path.isEmpty(); + const hasDocument = targetDoc !== undefined; + let message = `Function ${methodName}() called with invalid data`; + if (hasConverter) { + message += ' (via `toFirestore()`)'; + } + message += '. '; + let description = ''; + if (hasPath || hasDocument) { + description += ' (found'; + if (hasPath) { + description += ` in field ${path}`; + } + if (hasDocument) { + description += ` in document ${targetDoc}`; + } + description += ')'; + } + return new FirestoreError(Code.INVALID_ARGUMENT, message + reason + description); +} +/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ +function fieldMaskContains(haystack, needle) { + return haystack.some(v => v.isEqual(needle)); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ +class DocumentSnapshot { + // Note: This class is stripped down version of the DocumentSnapshot in + // the legacy SDK. The changes are: + // - No support for SnapshotMetadata. + // - No support for SnapshotOptions. + /** @hideconstructor protected */ + constructor(_firestore, _userDataWriter, _key, _document, _converter) { + this._firestore = _firestore; + this._userDataWriter = _userDataWriter; + this._key = _key; + this._document = _document; + this._converter = _converter; + } + /** Property of the `DocumentSnapshot` that provides the document's ID. */ + get id() { + return this._key.path.lastSegment(); + } + /** + * The `DocumentReference` for the document included in the `DocumentSnapshot`. + */ + get ref() { + return new DocumentReference(this._firestore, this._converter, this._key); + } + /** + * Signals whether or not the document at the snapshot's location exists. + * + * @returns true if the document exists. + */ + exists() { + return this._document !== null; + } + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * @returns An `Object` containing all fields in the document or `undefined` + * if the document doesn't exist. + */ + data() { + if (!this._document) { + return undefined; + } + else if (this._converter) { + // We only want to use the converter and create a new DocumentSnapshot + // if a converter has been provided. + const snapshot = new QueryDocumentSnapshot(this._firestore, this._userDataWriter, this._key, this._document, + /* converter= */ null); + return this._converter.fromFirestore(snapshot); + } + else { + return this._userDataWriter.convertValue(this._document.data.value); + } + } + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + // We are using `any` here to avoid an explicit cast by our users. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get(fieldPath) { + if (this._document) { + const value = this._document.data.field(fieldPathFromArgument('DocumentSnapshot.get', fieldPath)); + if (value !== null) { + return this._userDataWriter.convertValue(value); + } + } + return undefined; + } +} +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ +class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * @override + * @returns An `Object` containing all fields in the document. + */ + data() { + return super.data(); + } +} +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ +class QuerySnapshot { + /** @hideconstructor */ + constructor(_query, _docs) { + this._docs = _docs; + this.query = _query; + } + /** An array of all the documents in the `QuerySnapshot`. */ + get docs() { + return [...this._docs]; + } + /** The number of documents in the `QuerySnapshot`. */ + get size() { + return this.docs.length; + } + /** True if there are no documents in the `QuerySnapshot`. */ + get empty() { + return this.docs.length === 0; + } + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ + forEach(callback, thisArg) { + this._docs.forEach(callback, thisArg); + } +} +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ +function snapshotEqual(left, right) { + left = getModularInstance(left); + right = getModularInstance(right); + if (left instanceof DocumentSnapshot && right instanceof DocumentSnapshot) { + return (left._firestore === right._firestore && + left._key.isEqual(right._key) && + (left._document === null + ? right._document === null + : left._document.isEqual(right._document)) && + left._converter === right._converter); + } + else if (left instanceof QuerySnapshot && right instanceof QuerySnapshot) { + return (queryEqual(left.query, right.query) && + arrayEquals(left.docs, right.docs, snapshotEqual)); + } + return false; +} +/** + * Helper that calls `fromDotSeparatedString()` but wraps any error thrown. + */ +function fieldPathFromArgument(methodName, arg) { + if (typeof arg === 'string') { + return fieldPathFromDotSeparatedString(methodName, arg); + } + else if (arg instanceof FieldPath) { + return arg._internalPath; + } + else { + return arg._delegate._internalPath; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function validateHasExplicitOrderByForLimitToLast(query) { + if (query.limitType === "L" /* LimitType.Last */ && + query.explicitOrderBy.length === 0) { + throw new FirestoreError(Code.UNIMPLEMENTED, 'limitToLast() queries require specifying at least one orderBy() clause'); + } +} +/** + * An `AppliableConstraint` is an abstraction of a constraint that can be applied + * to a Firestore query. + */ +class AppliableConstraint { +} +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Firestore query. `QueryConstraint`s are created by invoking {@link where}, + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that + * also contains this `QueryConstraint`. + */ +class QueryConstraint extends AppliableConstraint { +} +function query(query, queryConstraint, ...additionalQueryConstraints) { + let queryConstraints = []; + if (queryConstraint instanceof AppliableConstraint) { + queryConstraints.push(queryConstraint); + } + queryConstraints = queryConstraints.concat(additionalQueryConstraints); + validateQueryConstraintArray(queryConstraints); + for (const constraint of queryConstraints) { + query = constraint._apply(query); + } + return query; +} +/** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ +class QueryFieldFilterConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(_field, _op, _value) { + super(); + this._field = _field; + this._op = _op; + this._value = _value; + /** The type of this query constraint */ + this.type = 'where'; + } + static _create(_field, _op, _value) { + return new QueryFieldFilterConstraint(_field, _op, _value); + } + _apply(query) { + const filter = this._parse(query); + validateNewFieldFilter(query._query, filter); + return new Query(query.firestore, query.converter, queryWithAddedFilter(query._query, filter)); + } + _parse(query) { + const reader = newUserDataReader(query.firestore); + const filter = newQueryFilter(query._query, 'where', reader, query.firestore._databaseId, this._field, this._op, this._value); + return filter; + } +} +/** + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. + * + * @param fieldPath - The path to compare + * @param opStr - The operation string (e.g "<", "<=", "==", "<", + * "<=", "!="). + * @param value - The value for comparison + * @returns The created {@link QueryFieldFilterConstraint}. + */ +function where(fieldPath, opStr, value) { + const op = opStr; + const field = fieldPathFromArgument('where', fieldPath); + return QueryFieldFilterConstraint._create(field, op, value); +} +/** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ +class QueryCompositeFilterConstraint extends AppliableConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + type, _queryConstraints) { + super(); + this.type = type; + this._queryConstraints = _queryConstraints; + } + static _create(type, _queryConstraints) { + return new QueryCompositeFilterConstraint(type, _queryConstraints); + } + _parse(query) { + const parsedFilters = this._queryConstraints + .map(queryConstraint => { + return queryConstraint._parse(query); + }) + .filter(parsedFilter => parsedFilter.getFilters().length > 0); + if (parsedFilters.length === 1) { + return parsedFilters[0]; + } + return CompositeFilter.create(parsedFilters, this._getOperator()); + } + _apply(query) { + const parsedFilter = this._parse(query); + if (parsedFilter.getFilters().length === 0) { + // Return the existing query if not adding any more filters (e.g. an empty + // composite filter). + return query; + } + validateNewFilter(query._query, parsedFilter); + return new Query(query.firestore, query.converter, queryWithAddedFilter(query._query, parsedFilter)); + } + _getQueryConstraints() { + return this._queryConstraints; + } + _getOperator() { + return this.type === 'and' ? "and" /* CompositeOperator.AND */ : "or" /* CompositeOperator.OR */; + } +} +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +function or(...queryConstraints) { + // Only support QueryFilterConstraints + queryConstraints.forEach(queryConstraint => validateQueryFilterConstraint('or', queryConstraint)); + return QueryCompositeFilterConstraint._create("or" /* CompositeOperator.OR */, queryConstraints); +} +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +function and(...queryConstraints) { + // Only support QueryFilterConstraints + queryConstraints.forEach(queryConstraint => validateQueryFilterConstraint('and', queryConstraint)); + return QueryCompositeFilterConstraint._create("and" /* CompositeOperator.AND */, queryConstraints); +} +/** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ +class QueryOrderByConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(_field, _direction) { + super(); + this._field = _field; + this._direction = _direction; + /** The type of this query constraint */ + this.type = 'orderBy'; + } + static _create(_field, _direction) { + return new QueryOrderByConstraint(_field, _direction); + } + _apply(query) { + const orderBy = newQueryOrderBy(query._query, this._field, this._direction); + return new Query(query.firestore, query.converter, queryWithAddedOrderBy(query._query, orderBy)); + } +} +/** + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the + * specified field, optionally in descending order instead of ascending. + * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * + * @param fieldPath - The field to sort by. + * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @returns The created {@link QueryOrderByConstraint}. + */ +function orderBy(fieldPath, directionStr = 'asc') { + const direction = directionStr; + const path = fieldPathFromArgument('orderBy', fieldPath); + return QueryOrderByConstraint._create(path, direction); +} +/** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ +class QueryLimitConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + type, _limit, _limitType) { + super(); + this.type = type; + this._limit = _limit; + this._limitType = _limitType; + } + static _create(type, _limit, _limitType) { + return new QueryLimitConstraint(type, _limit, _limitType); + } + _apply(query) { + return new Query(query.firestore, query.converter, queryWithLimit(query._query, this._limit, this._limitType)); + } +} +/** + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +function limit(limit) { + validatePositiveNumber('limit', limit); + return QueryLimitConstraint._create('limit', limit, "F" /* LimitType.First */); +} +/** + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. + * + * You must specify at least one `orderBy` clause for `limitToLast` queries, + * otherwise an exception will be thrown during execution. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +function limitToLast(limit) { + validatePositiveNumber('limitToLast', limit); + return QueryLimitConstraint._create('limitToLast', limit, "L" /* LimitType.Last */); +} +/** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ +class QueryStartAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + type, _docOrFields, _inclusive) { + super(); + this.type = type; + this._docOrFields = _docOrFields; + this._inclusive = _inclusive; + } + static _create(type, _docOrFields, _inclusive) { + return new QueryStartAtConstraint(type, _docOrFields, _inclusive); + } + _apply(query) { + const bound = newQueryBoundFromDocOrFields(query, this.type, this._docOrFields, this._inclusive); + return new Query(query.firestore, query.converter, queryWithStartAt(query._query, bound)); + } +} +function startAt(...docOrFields) { + return QueryStartAtConstraint._create('startAt', docOrFields, + /*inclusive=*/ true); +} +function startAfter(...docOrFields) { + return QueryStartAtConstraint._create('startAfter', docOrFields, + /*inclusive=*/ false); +} +/** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ +class QueryEndAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + type, _docOrFields, _inclusive) { + super(); + this.type = type; + this._docOrFields = _docOrFields; + this._inclusive = _inclusive; + } + static _create(type, _docOrFields, _inclusive) { + return new QueryEndAtConstraint(type, _docOrFields, _inclusive); + } + _apply(query) { + const bound = newQueryBoundFromDocOrFields(query, this.type, this._docOrFields, this._inclusive); + return new Query(query.firestore, query.converter, queryWithEndAt(query._query, bound)); + } +} +function endBefore(...docOrFields) { + return QueryEndAtConstraint._create('endBefore', docOrFields, + /*inclusive=*/ false); +} +function endAt(...docOrFields) { + return QueryEndAtConstraint._create('endAt', docOrFields, + /*inclusive=*/ true); +} +/** Helper function to create a bound from a document or fields */ +function newQueryBoundFromDocOrFields(query, methodName, docOrFields, inclusive) { + docOrFields[0] = getModularInstance(docOrFields[0]); + if (docOrFields[0] instanceof DocumentSnapshot) { + return newQueryBoundFromDocument(query._query, query.firestore._databaseId, methodName, docOrFields[0]._document, inclusive); + } + else { + const reader = newUserDataReader(query.firestore); + return newQueryBoundFromFields(query._query, query.firestore._databaseId, reader, methodName, docOrFields, inclusive); + } +} +function newQueryFilter(query, methodName, dataReader, databaseId, fieldPath, op, value) { + let fieldValue; + if (fieldPath.isKeyField()) { + if (op === "array-contains" /* Operator.ARRAY_CONTAINS */ || op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid Query. You can't perform '${op}' queries on documentId().`); + } + else if (op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */) { + validateDisjunctiveFilterElements(value, op); + const referenceList = []; + for (const arrayValue of value) { + referenceList.push(parseDocumentIdValue(databaseId, query, arrayValue)); + } + fieldValue = { arrayValue: { values: referenceList } }; + } + else { + fieldValue = parseDocumentIdValue(databaseId, query, value); + } + } + else { + if (op === "in" /* Operator.IN */ || + op === "not-in" /* Operator.NOT_IN */ || + op === "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */) { + validateDisjunctiveFilterElements(value, op); + } + fieldValue = parseQueryValue(dataReader, methodName, value, + /* allowArrays= */ op === "in" /* Operator.IN */ || op === "not-in" /* Operator.NOT_IN */); + } + const filter = FieldFilter.create(fieldPath, op, fieldValue); + return filter; +} +function newQueryOrderBy(query, fieldPath, direction) { + if (query.startAt !== null) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call startAt() or startAfter() before ' + + 'calling orderBy().'); + } + if (query.endAt !== null) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You must not call endAt() or endBefore() before ' + + 'calling orderBy().'); + } + const orderBy = new OrderBy(fieldPath, direction); + return orderBy; +} +/** + * Create a `Bound` from a query and a document. + * + * Note that the `Bound` will always include the key of the document + * and so only the provided document will compare equal to the returned + * position. + * + * Will throw if the document does not contain all fields of the order by + * of the query or if any of the fields in the order by are an uncommitted + * server timestamp. + */ +function newQueryBoundFromDocument(query, databaseId, methodName, doc, inclusive) { + if (!doc) { + throw new FirestoreError(Code.NOT_FOUND, `Can't use a DocumentSnapshot that doesn't exist for ` + + `${methodName}().`); + } + const components = []; + // Because people expect to continue/end a query at the exact document + // provided, we need to use the implicit sort order rather than the explicit + // sort order, because it's guaranteed to contain the document key. That way + // the position becomes unambiguous and the query continues/ends exactly at + // the provided document. Without the key (by using the explicit sort + // orders), multiple documents could match the position, yielding duplicate + // results. + for (const orderBy of queryNormalizedOrderBy(query)) { + if (orderBy.field.isKeyField()) { + components.push(refValue(databaseId, doc.key)); + } + else { + const value = doc.data.field(orderBy.field); + if (isServerTimestamp(value)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You are trying to start or end a query using a ' + + 'document for which the field "' + + orderBy.field + + '" is an uncommitted server timestamp. (Since the value of ' + + 'this field is unknown, you cannot start/end a query with it.)'); + } + else if (value !== null) { + components.push(value); + } + else { + const field = orderBy.field.canonicalString(); + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. You are trying to start or end a query using a ` + + `document for which the field '${field}' (used as the ` + + `orderBy) does not exist.`); + } + } + } + return new Bound(components, inclusive); +} +/** + * Converts a list of field values to a `Bound` for the given query. + */ +function newQueryBoundFromFields(query, databaseId, dataReader, methodName, values, inclusive) { + // Use explicit order by's because it has to match the query the user made + const orderBy = query.explicitOrderBy; + if (values.length > orderBy.length) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Too many arguments provided to ${methodName}(). ` + + `The number of arguments must be less than or equal to the ` + + `number of orderBy() clauses`); + } + const components = []; + for (let i = 0; i < values.length; i++) { + const rawValue = values[i]; + const orderByComponent = orderBy[i]; + if (orderByComponent.field.isKeyField()) { + if (typeof rawValue !== 'string') { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. Expected a string for document ID in ` + + `${methodName}(), but got a ${typeof rawValue}`); + } + if (!isCollectionGroupQuery(query) && rawValue.indexOf('/') !== -1) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection and ordering by documentId(), ` + + `the value passed to ${methodName}() must be a plain document ID, but ` + + `'${rawValue}' contains a slash.`); + } + const path = query.path.child(ResourcePath.fromString(rawValue)); + if (!DocumentKey.isDocumentKey(path)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection group and ordering by ` + + `documentId(), the value passed to ${methodName}() must result in a ` + + `valid document path, but '${path}' is not because it contains an odd number ` + + `of segments.`); + } + const key = new DocumentKey(path); + components.push(refValue(databaseId, key)); + } + else { + const wrapped = parseQueryValue(dataReader, methodName, rawValue); + components.push(wrapped); + } + } + return new Bound(components, inclusive); +} +/** + * Parses the given `documentIdValue` into a `ReferenceValue`, throwing + * appropriate errors if the value is anything other than a `DocumentReference` + * or `string`, or if the string is malformed. + */ +function parseDocumentIdValue(databaseId, query, documentIdValue) { + documentIdValue = getModularInstance(documentIdValue); + if (typeof documentIdValue === 'string') { + if (documentIdValue === '') { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. When querying with documentId(), you ' + + 'must provide a valid document ID, but it was an empty string.'); + } + if (!isCollectionGroupQuery(query) && documentIdValue.indexOf('/') !== -1) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection by ` + + `documentId(), you must provide a plain document ID, but ` + + `'${documentIdValue}' contains a '/' character.`); + } + const path = query.path.child(ResourcePath.fromString(documentIdValue)); + if (!DocumentKey.isDocumentKey(path)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying a collection group by ` + + `documentId(), the value provided must result in a valid document path, ` + + `but '${path}' is not because it has an odd number of segments (${path.length}).`); + } + return refValue(databaseId, new DocumentKey(path)); + } + else if (documentIdValue instanceof DocumentReference) { + return refValue(databaseId, documentIdValue._key); + } + else { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. When querying with documentId(), you must provide a valid ` + + `string or a DocumentReference, but it was: ` + + `${valueDescription(documentIdValue)}.`); + } +} +/** + * Validates that the value passed into a disjunctive filter satisfies all + * array requirements. + */ +function validateDisjunctiveFilterElements(value, operator) { + if (!Array.isArray(value) || value.length === 0) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid Query. A non-empty array is required for ' + + `'${operator.toString()}' filters.`); + } +} +/** + * Given an operator, returns the set of operators that cannot be used with it. + * + * This is not a comprehensive check, and this function should be removed in the + * long term. Validations should occur in the Firestore backend. + * + * Operators in a query must adhere to the following set of rules: + * 1. Only one inequality per query. + * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators. + */ +function conflictingOps(op) { + switch (op) { + case "!=" /* Operator.NOT_EQUAL */: + return ["!=" /* Operator.NOT_EQUAL */, "not-in" /* Operator.NOT_IN */]; + case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */: + case "in" /* Operator.IN */: + return ["not-in" /* Operator.NOT_IN */]; + case "not-in" /* Operator.NOT_IN */: + return [ + "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */, + "in" /* Operator.IN */, + "not-in" /* Operator.NOT_IN */, + "!=" /* Operator.NOT_EQUAL */ + ]; + default: + return []; + } +} +function validateNewFieldFilter(query, fieldFilter) { + const conflictingOp = findOpInsideFilters(query.filters, conflictingOps(fieldFilter.op)); + if (conflictingOp !== null) { + // Special case when it's a duplicate op to give a slightly clearer error message. + if (conflictingOp === fieldFilter.op) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. You cannot use more than one ' + + `'${fieldFilter.op.toString()}' filter.`); + } + else { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. You cannot use '${fieldFilter.op.toString()}' filters ` + + `with '${conflictingOp.toString()}' filters.`); + } + } +} +function validateNewFilter(query, filter) { + let testQuery = query; + const subFilters = filter.getFlattenedFilters(); + for (const subFilter of subFilters) { + validateNewFieldFilter(testQuery, subFilter); + testQuery = queryWithAddedFilter(testQuery, subFilter); + } +} +// Checks if any of the provided filter operators are included in the given list of filters and +// returns the first one that is, or null if none are. +function findOpInsideFilters(filters, operators) { + for (const filter of filters) { + for (const fieldFilter of filter.getFlattenedFilters()) { + if (operators.indexOf(fieldFilter.op) >= 0) { + return fieldFilter.op; + } + } + } + return null; +} +function validateQueryFilterConstraint(functionName, queryConstraint) { + if (!(queryConstraint instanceof QueryFieldFilterConstraint) && + !(queryConstraint instanceof QueryCompositeFilterConstraint)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, `Function ${functionName}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`); + } +} +function validateQueryConstraintArray(queryConstraint) { + const compositeFilterCount = queryConstraint.filter(filter => filter instanceof QueryCompositeFilterConstraint).length; + const fieldFilterCount = queryConstraint.filter(filter => filter instanceof QueryFieldFilterConstraint).length; + if (compositeFilterCount > 1 || + (compositeFilterCount > 0 && fieldFilterCount > 0)) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'InvalidQuery. When using composite filters, you cannot use ' + + 'more than one filter at the top level. Consider nesting the multiple ' + + 'filters within an `and(...)` statement. For example: ' + + 'change `query(query, where(...), or(...))` to ' + + '`query(query, and(where(...), or(...)))`.'); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Converts Firestore's internal types to the JavaScript types that we expose + * to the user. + * + * @internal + */ +class AbstractUserDataWriter { + convertValue(value, serverTimestampBehavior = 'none') { + switch (typeOrder(value)) { + case 0 /* TypeOrder.NullValue */: + return null; + case 1 /* TypeOrder.BooleanValue */: + return value.booleanValue; + case 2 /* TypeOrder.NumberValue */: + return normalizeNumber(value.integerValue || value.doubleValue); + case 3 /* TypeOrder.TimestampValue */: + return this.convertTimestamp(value.timestampValue); + case 4 /* TypeOrder.ServerTimestampValue */: + return this.convertServerTimestamp(value, serverTimestampBehavior); + case 5 /* TypeOrder.StringValue */: + return value.stringValue; + case 6 /* TypeOrder.BlobValue */: + return this.convertBytes(normalizeByteString(value.bytesValue)); + case 7 /* TypeOrder.RefValue */: + return this.convertReference(value.referenceValue); + case 8 /* TypeOrder.GeoPointValue */: + return this.convertGeoPoint(value.geoPointValue); + case 9 /* TypeOrder.ArrayValue */: + return this.convertArray(value.arrayValue, serverTimestampBehavior); + case 11 /* TypeOrder.ObjectValue */: + return this.convertObject(value.mapValue, serverTimestampBehavior); + case 10 /* TypeOrder.VectorValue */: + return this.convertVectorValue(value.mapValue); + default: + throw fail(0xf2a2, { + value + }); + } + } + convertObject(mapValue, serverTimestampBehavior) { + return this.convertObjectMap(mapValue.fields, serverTimestampBehavior); + } + /** + * @internal + */ + convertObjectMap(fields, serverTimestampBehavior = 'none') { + const result = {}; + forEach(fields, (key, value) => { + result[key] = this.convertValue(value, serverTimestampBehavior); + }); + return result; + } + /** + * @internal + */ + convertVectorValue(mapValue) { + const values = mapValue.fields?.[VECTOR_MAP_VECTORS_KEY].arrayValue?.values?.map(value => { + return normalizeNumber(value.doubleValue); + }); + return new VectorValue(values); + } + convertGeoPoint(value) { + return new GeoPoint(normalizeNumber(value.latitude), normalizeNumber(value.longitude)); + } + convertArray(arrayValue, serverTimestampBehavior) { + return (arrayValue.values || []).map(value => this.convertValue(value, serverTimestampBehavior)); + } + convertServerTimestamp(value, serverTimestampBehavior) { + switch (serverTimestampBehavior) { + case 'previous': + const previousValue = getPreviousValue(value); + if (previousValue == null) { + return null; + } + return this.convertValue(previousValue, serverTimestampBehavior); + case 'estimate': + return this.convertTimestamp(getLocalWriteTime(value)); + default: + return null; + } + } + convertTimestamp(value) { + const normalizedValue = normalizeTimestamp(value); + return new Timestamp(normalizedValue.seconds, normalizedValue.nanos); + } + convertDocumentKey(name, expectedDatabaseId) { + const resourcePath = ResourcePath.fromString(name); + hardAssert(isValidResourceName(resourcePath), 0x25d8, { name }); + const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3)); + const key = new DocumentKey(resourcePath.popFirst(5)); + if (!databaseId.isEqual(expectedDatabaseId)) { + // TODO(b/64130202): Somehow support foreign references. + logError(`Document ${key} contains a document ` + + `reference within a different database (` + + `${databaseId.projectId}/${databaseId.database}) which is not ` + + `supported. It will be treated as a reference in the current ` + + `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` + + `instead.`); + } + return key; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Converts custom model object of type T into `DocumentData` by applying the + * converter if it exists. + * + * This function is used when converting user objects to `DocumentData` + * because we want to provide the user with a more specific error message if + * their `set()` or fails due to invalid data originating from a `toFirestore()` + * call. + */ +function applyFirestoreDataConverter(converter, value, options) { + let convertedValue; + if (converter) { + if (options && (options.merge || options.mergeFields)) { + // Cast to `any` in order to satisfy the union type constraint on + // toFirestore(). + // eslint-disable-next-line @typescript-eslint/no-explicit-any + convertedValue = converter.toFirestore(value, options); + } + else { + convertedValue = converter.toFirestore(value); + } + } + else { + convertedValue = value; + } + return convertedValue; +} +class LiteUserDataWriter extends AbstractUserDataWriter { + constructor(firestore) { + super(); + this.firestore = firestore; + } + convertBytes(bytes) { + return new Bytes(bytes); + } + convertReference(name) { + const key = this.convertDocumentKey(name, this.firestore._databaseId); + return new DocumentReference(this.firestore, /* converter= */ null, key); + } +} +/** + * Reads the document referred to by the specified document reference. + * + * All documents are directly fetched from the server, even if the document was + * previously read or modified. Recent modifications are only reflected in the + * retrieved `DocumentSnapshot` if they have already been applied by the + * backend. If the client is offline, the read fails. If you like to use + * caching or see local modifications, please use the full Firestore SDK. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the current + * document contents. + */ +function getDoc(reference) { + reference = cast(reference, DocumentReference); + const datastore = getDatastore(reference.firestore); + const userDataWriter = new LiteUserDataWriter(reference.firestore); + return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then(result => { + hardAssert(result.length === 1, 0x3d02); + const document = result[0]; + return new DocumentSnapshot(reference.firestore, userDataWriter, reference._key, document.isFoundDocument() ? document : null, reference.converter); + }); +} +/** + * Executes the query and returns the results as a {@link QuerySnapshot}. + * + * All queries are executed directly by the server, even if the query was + * previously executed. Recent modifications are only reflected in the retrieved + * results if they have already been applied by the backend. If the client is + * offline, the operation fails. To see previously cached result and local + * modifications, use the full Firestore SDK. + * + * @param query - The `Query` to execute. + * @returns A Promise that will be resolved with the results of the query. + */ +function getDocs(query) { + query = cast(query, Query); + validateHasExplicitOrderByForLimitToLast(query._query); + const datastore = getDatastore(query.firestore); + const userDataWriter = new LiteUserDataWriter(query.firestore); + return invokeRunQueryRpc(datastore, query._query).then(result => { + const docs = result.map(doc => new QueryDocumentSnapshot(query.firestore, userDataWriter, doc.key, doc, query.converter)); + if (query._query.limitType === "L" /* LimitType.Last */) { + // Limit to last queries reverse the orderBy constraint that was + // specified by the user. As such, we need to reverse the order of the + // results to return the documents in the expected order. + docs.reverse(); + } + return new QuerySnapshot(query, docs); + }); +} +function setDoc(reference, data, options) { + reference = cast(reference, DocumentReference); + const convertedValue = applyFirestoreDataConverter(reference.converter, data, options); + const dataReader = newUserDataReader(reference.firestore); + const parsed = parseSetData(dataReader, 'setDoc', reference._key, convertedValue, reference.converter !== null, options); + const datastore = getDatastore(reference.firestore); + return invokeCommitRpc(datastore, [ + parsed.toMutation(reference._key, Precondition.none()) + ]); +} +function updateDoc(reference, fieldOrUpdateData, value, ...moreFieldsAndValues) { + reference = cast(reference, DocumentReference); + const dataReader = newUserDataReader(reference.firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + fieldOrUpdateData = getModularInstance(fieldOrUpdateData); + let parsed; + if (typeof fieldOrUpdateData === 'string' || + fieldOrUpdateData instanceof FieldPath) { + parsed = parseUpdateVarargs(dataReader, 'updateDoc', reference._key, fieldOrUpdateData, value, moreFieldsAndValues); + } + else { + parsed = parseUpdateData(dataReader, 'updateDoc', reference._key, fieldOrUpdateData); + } + const datastore = getDatastore(reference.firestore); + return invokeCommitRpc(datastore, [ + parsed.toMutation(reference._key, Precondition.exists(true)) + ]); +} +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * The deletion will only be reflected in document reads that occur after the + * returned promise resolves. If the client is offline, the + * delete fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to delete. + * @returns A `Promise` resolved once the document has been successfully + * deleted from the backend. + */ +function deleteDoc(reference) { + reference = cast(reference, DocumentReference); + const datastore = getDatastore(reference.firestore); + return invokeCommitRpc(datastore, [ + new DeleteMutation(reference._key, Precondition.none()) + ]); +} +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend. + */ +function addDoc(reference, data) { + reference = cast(reference, CollectionReference); + const docRef = doc(reference); + const convertedValue = applyFirestoreDataConverter(reference.converter, data); + const dataReader = newUserDataReader(reference.firestore); + const parsed = parseSetData(dataReader, 'addDoc', docRef._key, convertedValue, docRef.converter !== null, {}); + const datastore = getDatastore(reference.firestore); + return invokeCommitRpc(datastore, [ + parsed.toMutation(docRef._key, Precondition.exists(false)) + ]).then(() => docRef); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ +function getCount(query) { + const countQuerySpec = { + count: count() + }; + return getAggregate(query, countQuerySpec); +} +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregate(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ +function getAggregate(query, aggregateSpec) { + const firestore = cast(query.firestore, Firestore); + const datastore = getDatastore(firestore); + const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => { + return new AggregateImpl(alias, aggregate.aggregateType, aggregate._internalFieldPath); + }); + // Run the aggregation and convert the results + return invokeRunAggregationQueryRpc(datastore, query._query, internalAggregates).then(aggregateResult => convertToAggregateQuerySnapshot(firestore, query, aggregateResult)); +} +function convertToAggregateQuerySnapshot(firestore, query, aggregateResult) { + const userDataWriter = new LiteUserDataWriter(firestore); + const querySnapshot = new AggregateQuerySnapshot(query, userDataWriter, aggregateResult); + return querySnapshot; +} +/** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ +function sum(field) { + return new AggregateField('sum', fieldPathFromArgument$1('sum', field)); +} +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ +function average(field) { + return new AggregateField('avg', fieldPathFromArgument$1('average', field)); +} +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ +function count() { + return new AggregateField('count'); +} +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ +function aggregateFieldEqual(left, right) { + return (left instanceof AggregateField && + right instanceof AggregateField && + left.aggregateType === right.aggregateType && + left._internalFieldPath?.canonicalString() === + right._internalFieldPath?.canonicalString()); +} +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ +function aggregateQuerySnapshotEqual(left, right) { + return (queryEqual(left.query, right.query) && deepEqual(left.data(), right.data())); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. + */ +function deleteField() { + return new DeleteFieldValueImpl('deleteField'); +} +/** + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to + * include a server-generated timestamp in the written data. + */ +function serverTimestamp() { + return new ServerTimestampFieldValueImpl('serverTimestamp'); +} +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array + * value that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements - The elements to union into the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()`. + */ +function arrayUnion(...elements) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new ArrayUnionFieldValueImpl('arrayUnion', elements); +} +/** + * Returns a special value that can be used with {@link (setDoc:1)} or {@link + * updateDoc:1} that tells the server to remove the given elements from any + * array value that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is not + * already an array it will be overwritten with an empty array. + * + * @param elements - The elements to remove from the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +function arrayRemove(...elements) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new ArrayRemoveFieldValueImpl('arrayRemove', elements); +} +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by + * the given value. + * + * If either the operand or the current field value uses floating point + * precision, all arithmetic follows IEEE 754 semantics. If both values are + * integers, values outside of JavaScript's safe number range + * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to + * precision loss. Furthermore, once processed by the Firestore backend, all + * integer operations are capped between -2^63 and 2^63-1. + * + * If the current field value is not of type `number`, or if the field does not + * yet exist, the transformation sets the field to the given value. + * + * @param n - The value to increment by. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +function increment(n) { + return new NumericIncrementFieldValueImpl('increment', n); +} +/** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ +function vector(values) { + return new VectorValue(values); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It + * provides methods for adding writes to the write batch. None of the writes + * will be committed (or visible locally) until {@link WriteBatch.commit} is + * called. + */ +class WriteBatch { + /** @hideconstructor */ + constructor(_firestore, _commitHandler) { + this._firestore = _firestore; + this._commitHandler = _commitHandler; + this._mutations = []; + this._committed = false; + this._dataReader = newUserDataReader(_firestore); + } + set(documentRef, data, options) { + this._verifyNotCommitted(); + const ref = validateReference(documentRef, this._firestore); + const convertedValue = applyFirestoreDataConverter(ref.converter, data, options); + const parsed = parseSetData(this._dataReader, 'WriteBatch.set', ref._key, convertedValue, ref.converter !== null, options); + this._mutations.push(parsed.toMutation(ref._key, Precondition.none())); + return this; + } + update(documentRef, fieldOrUpdateData, value, ...moreFieldsAndValues) { + this._verifyNotCommitted(); + const ref = validateReference(documentRef, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + fieldOrUpdateData = getModularInstance(fieldOrUpdateData); + let parsed; + if (typeof fieldOrUpdateData === 'string' || + fieldOrUpdateData instanceof FieldPath) { + parsed = parseUpdateVarargs(this._dataReader, 'WriteBatch.update', ref._key, fieldOrUpdateData, value, moreFieldsAndValues); + } + else { + parsed = parseUpdateData(this._dataReader, 'WriteBatch.update', ref._key, fieldOrUpdateData); + } + this._mutations.push(parsed.toMutation(ref._key, Precondition.exists(true))); + return this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + delete(documentRef) { + this._verifyNotCommitted(); + const ref = validateReference(documentRef, this._firestore); + this._mutations = this._mutations.concat(new DeleteMutation(ref._key, Precondition.none())); + return this; + } + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `Promise` resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit (note that it won't + * resolve while you're offline). + */ + commit() { + this._verifyNotCommitted(); + this._committed = true; + if (this._mutations.length > 0) { + return this._commitHandler(this._mutations); + } + return Promise.resolve(); + } + _verifyNotCommitted() { + if (this._committed) { + throw new FirestoreError(Code.FAILED_PRECONDITION, 'A write batch can no longer be used after commit() ' + + 'has been called.'); + } + } +} +function validateReference(documentRef, firestore) { + documentRef = getModularInstance(documentRef); + if (documentRef.firestore !== firestore) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Provided document reference is from a different Firestore instance.'); + } + else { + return documentRef; + } +} +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single WriteBatch + * is 500. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `WriteBatch` that can be used to atomically execute multiple + * writes. + */ +function writeBatch(firestore) { + firestore = cast(firestore, Firestore); + const datastore = getDatastore(firestore); + return new WriteBatch(firestore, writes => invokeCommitRpc(datastore, writes)); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const DEFAULT_TRANSACTION_OPTIONS = { + maxAttempts: 5 +}; +function validateTransactionOptions(options) { + if (options.maxAttempts < 1) { + throw new FirestoreError(Code.INVALID_ARGUMENT, 'Max attempts must be at least 1'); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Internal transaction object responsible for accumulating the mutations to + * perform and the base versions for any documents read. + */ +class Transaction$1 { + constructor(datastore) { + this.datastore = datastore; + // The version of each document that was read during this transaction. + this.readVersions = new Map(); + this.mutations = []; + this.committed = false; + /** + * A deferred usage error that occurred previously in this transaction that + * will cause the transaction to fail once it actually commits. + */ + this.lastTransactionError = null; + /** + * Set of documents that have been written in the transaction. + * + * When there's more than one write to the same key in a transaction, any + * writes after the first are handled differently. + */ + this.writtenDocs = new Set(); + } + async lookup(keys) { + this.ensureCommitNotCalled(); + if (this.mutations.length > 0) { + this.lastTransactionError = new FirestoreError(Code.INVALID_ARGUMENT, 'Firestore transactions require all reads to be executed before all writes.'); + throw this.lastTransactionError; + } + const docs = await invokeBatchGetDocumentsRpc(this.datastore, keys); + docs.forEach(doc => this.recordVersion(doc)); + return docs; + } + set(key, data) { + this.write(data.toMutation(key, this.precondition(key))); + this.writtenDocs.add(key.toString()); + } + update(key, data) { + try { + this.write(data.toMutation(key, this.preconditionForUpdate(key))); + } + catch (e) { + this.lastTransactionError = e; + } + this.writtenDocs.add(key.toString()); + } + delete(key) { + this.write(new DeleteMutation(key, this.precondition(key))); + this.writtenDocs.add(key.toString()); + } + async commit() { + this.ensureCommitNotCalled(); + if (this.lastTransactionError) { + throw this.lastTransactionError; + } + const unwritten = this.readVersions; + // For each mutation, note that the doc was written. + this.mutations.forEach(mutation => { + unwritten.delete(mutation.key.toString()); + }); + // For each document that was read but not written to, we want to perform + // a `verify` operation. + unwritten.forEach((_, path) => { + const key = DocumentKey.fromPath(path); + this.mutations.push(new VerifyMutation(key, this.precondition(key))); + }); + await invokeCommitRpc(this.datastore, this.mutations); + this.committed = true; + } + recordVersion(doc) { + let docVersion; + if (doc.isFoundDocument()) { + docVersion = doc.version; + } + else if (doc.isNoDocument()) { + // Represent a deleted doc using SnapshotVersion.min(). + docVersion = SnapshotVersion.min(); + } + else { + throw fail(0xc542, { + documentName: doc.constructor.name + }); + } + const existingVersion = this.readVersions.get(doc.key.toString()); + if (existingVersion) { + if (!docVersion.isEqual(existingVersion)) { + // This transaction will fail no matter what. + throw new FirestoreError(Code.ABORTED, 'Document version changed between two reads.'); + } + } + else { + this.readVersions.set(doc.key.toString(), docVersion); + } + } + /** + * Returns the version of this document when it was read in this transaction, + * as a precondition, or no precondition if it was not read. + */ + precondition(key) { + const version = this.readVersions.get(key.toString()); + if (!this.writtenDocs.has(key.toString()) && version) { + if (version.isEqual(SnapshotVersion.min())) { + return Precondition.exists(false); + } + else { + return Precondition.updateTime(version); + } + } + else { + return Precondition.none(); + } + } + /** + * Returns the precondition for a document if the operation is an update. + */ + preconditionForUpdate(key) { + const version = this.readVersions.get(key.toString()); + // The first time a document is written, we want to take into account the + // read time and existence + if (!this.writtenDocs.has(key.toString()) && version) { + if (version.isEqual(SnapshotVersion.min())) { + // The document doesn't exist, so fail the transaction. + // This has to be validated locally because you can't send a + // precondition that a document does not exist without changing the + // semantics of the backend write to be an insert. This is the reverse + // of what we want, since we want to assert that the document doesn't + // exist but then send the update and have it fail. Since we can't + // express that to the backend, we have to validate locally. + // Note: this can change once we can send separate verify writes in the + // transaction. + throw new FirestoreError(Code.INVALID_ARGUMENT, "Can't update a document that doesn't exist."); + } + // Document exists, base precondition on document update time. + return Precondition.updateTime(version); + } + else { + // Document was not read, so we just use the preconditions for a blind + // update. + return Precondition.exists(true); + } + } + write(mutation) { + this.ensureCommitNotCalled(); + this.mutations.push(mutation); + } + ensureCommitNotCalled() { + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * TransactionRunner encapsulates the logic needed to run and retry transactions + * with backoff. + */ +class TransactionRunner { + constructor(asyncQueue, datastore, options, updateFunction, deferred) { + this.asyncQueue = asyncQueue; + this.datastore = datastore; + this.options = options; + this.updateFunction = updateFunction; + this.deferred = deferred; + this.attemptsRemaining = options.maxAttempts; + this.backoff = new ExponentialBackoff(this.asyncQueue, "transaction_retry" /* TimerId.TransactionRetry */); + } + /** Runs the transaction and sets the result on deferred. */ + run() { + this.attemptsRemaining -= 1; + this.runWithBackOff(); + } + runWithBackOff() { + this.backoff.backoffAndRun(async () => { + const transaction = new Transaction$1(this.datastore); + const userPromise = this.tryRunUpdateFunction(transaction); + if (userPromise) { + userPromise + .then(result => { + this.asyncQueue.enqueueAndForget(() => { + return transaction + .commit() + .then(() => { + this.deferred.resolve(result); + }) + .catch(commitError => { + this.handleTransactionError(commitError); + }); + }); + }) + .catch(userPromiseError => { + this.handleTransactionError(userPromiseError); + }); + } + }); + } + tryRunUpdateFunction(transaction) { + try { + const userPromise = this.updateFunction(transaction); + if (isNullOrUndefined(userPromise) || + !userPromise.catch || + !userPromise.then) { + this.deferred.reject(Error('Transaction callback must return a Promise')); + return null; + } + return userPromise; + } + catch (error) { + // Do not retry errors thrown by user provided updateFunction. + this.deferred.reject(error); + return null; + } + } + handleTransactionError(error) { + if (this.attemptsRemaining > 0 && this.isRetryableTransactionError(error)) { + this.attemptsRemaining -= 1; + this.asyncQueue.enqueueAndForget(() => { + this.runWithBackOff(); + return Promise.resolve(); + }); + } + else { + this.deferred.reject(error); + } + } + isRetryableTransactionError(error) { + if (error?.name === 'FirebaseError') { + // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and + // non-matching document versions with ABORTED. These errors should be retried. + const code = error.code; + return (code === 'aborted' || + code === 'failed-precondition' || + code === 'already-exists' || + !isPermanentError(code)); + } + return false; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents an operation scheduled to be run in the future on an AsyncQueue. + * + * It is created via DelayedOperation.createAndSchedule(). + * + * Supports cancellation (via cancel()) and early execution (via skipDelay()). + * + * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type + * in newer versions of TypeScript defines `finally`, which is not available in + * IE. + */ +class DelayedOperation { + constructor(asyncQueue, timerId, targetTimeMs, op, removalCallback) { + this.asyncQueue = asyncQueue; + this.timerId = timerId; + this.targetTimeMs = targetTimeMs; + this.op = op; + this.removalCallback = removalCallback; + this.deferred = new Deferred(); + this.then = this.deferred.promise.then.bind(this.deferred.promise); + // It's normal for the deferred promise to be canceled (due to cancellation) + // and so we attach a dummy catch callback to avoid + // 'UnhandledPromiseRejectionWarning' log spam. + this.deferred.promise.catch(err => { }); + } + get promise() { + return this.deferred.promise; + } + /** + * Creates and returns a DelayedOperation that has been scheduled to be + * executed on the provided asyncQueue after the provided delayMs. + * + * @param asyncQueue - The queue to schedule the operation on. + * @param id - A Timer ID identifying the type of operation this is. + * @param delayMs - The delay (ms) before the operation should be scheduled. + * @param op - The operation to run. + * @param removalCallback - A callback to be called synchronously once the + * operation is executed or canceled, notifying the AsyncQueue to remove it + * from its delayedOperations list. + * PORTING NOTE: This exists to prevent making removeDelayedOperation() and + * the DelayedOperation class public. + */ + static createAndSchedule(asyncQueue, timerId, delayMs, op, removalCallback) { + const targetTime = Date.now() + delayMs; + const delayedOp = new DelayedOperation(asyncQueue, timerId, targetTime, op, removalCallback); + delayedOp.start(delayMs); + return delayedOp; + } + /** + * Starts the timer. This is called immediately after construction by + * createAndSchedule(). + */ + start(delayMs) { + this.timerHandle = setTimeout(() => this.handleDelayElapsed(), delayMs); + } + /** + * Queues the operation to run immediately (if it hasn't already been run or + * canceled). + */ + skipDelay() { + return this.handleDelayElapsed(); + } + /** + * Cancels the operation if it hasn't already been executed or canceled. The + * promise will be rejected. + * + * As long as the operation has not yet been run, calling cancel() provides a + * guarantee that the operation will not be run. + */ + cancel(reason) { + if (this.timerHandle !== null) { + this.clearTimeout(); + this.deferred.reject(new FirestoreError(Code.CANCELLED, 'Operation cancelled' + (reason ? ': ' + reason : ''))); + } + } + handleDelayElapsed() { + this.asyncQueue.enqueueAndForget(() => { + if (this.timerHandle !== null) { + this.clearTimeout(); + return this.op().then(result => { + return this.deferred.resolve(result); + }); + } + else { + return Promise.resolve(); + } + }); + } + clearTimeout() { + if (this.timerHandle !== null) { + this.removalCallback(this); + clearTimeout(this.timerHandle); + this.timerHandle = null; + } + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const LOG_TAG = 'AsyncQueue'; +class AsyncQueueImpl { + constructor(tail = Promise.resolve()) { + // A list of retryable operations. Retryable operations are run in order and + // retried with backoff. + this.retryableOps = []; + // Is this AsyncQueue being shut down? Once it is set to true, it will not + // be changed again. + this._isShuttingDown = false; + // Operations scheduled to be queued in the future. Operations are + // automatically removed after they are run or canceled. + this.delayedOperations = []; + // visible for testing + this.failure = null; + // Flag set while there's an outstanding AsyncQueue operation, used for + // assertion sanity-checks. + this.operationInProgress = false; + // Enabled during shutdown on Safari to prevent future access to IndexedDB. + this.skipNonRestrictedTasks = false; + // List of TimerIds to fast-forward delays for. + this.timerIdsToSkip = []; + // Backoff timer used to schedule retries for retryable operations + this.backoff = new ExponentialBackoff(this, "async_queue_retry" /* TimerId.AsyncQueueRetry */); + // Visibility handler that triggers an immediate retry of all retryable + // operations. Meant to speed up recovery when we regain file system access + // after page comes into foreground. + this.visibilityHandler = () => { + this.backoff.skipBackoff(); + }; + this.tail = tail; + } + get isShuttingDown() { + return this._isShuttingDown; + } + /** + * Adds a new operation to the queue without waiting for it to complete (i.e. + * we ignore the Promise result). + */ + enqueueAndForget(op) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.enqueue(op); + } + enqueueAndForgetEvenWhileRestricted(op) { + this.verifyNotFailed(); + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.enqueueInternal(op); + } + enterRestrictedMode(purgeExistingTasks) { + if (!this._isShuttingDown) { + this._isShuttingDown = true; + this.skipNonRestrictedTasks = purgeExistingTasks || false; + } + } + enqueue(op) { + this.verifyNotFailed(); + if (this._isShuttingDown) { + // Return a Promise which never resolves. + return new Promise(() => { }); + } + // Create a deferred Promise that we can return to the callee. This + // allows us to return a "hanging Promise" only to the callee and still + // advance the queue even when the operation is not run. + const task = new Deferred(); + return this.enqueueInternal(() => { + if (this._isShuttingDown && this.skipNonRestrictedTasks) { + // We do not resolve 'task' + return Promise.resolve(); + } + op().then(task.resolve, task.reject); + return task.promise; + }).then(() => task.promise); + } + enqueueRetryable(op) { + this.enqueueAndForget(() => { + this.retryableOps.push(op); + return this.retryNextOp(); + }); + } + /** + * Runs the next operation from the retryable queue. If the operation fails, + * reschedules with backoff. + */ + async retryNextOp() { + if (this.retryableOps.length === 0) { + return; + } + try { + await this.retryableOps[0](); + this.retryableOps.shift(); + this.backoff.reset(); + } + catch (e) { + if (isIndexedDbTransactionError(e)) { + logDebug(LOG_TAG, 'Operation failed with retryable error: ' + e); + } + else { + throw e; // Failure will be handled by AsyncQueue + } + } + if (this.retryableOps.length > 0) { + // If there are additional operations, we re-schedule `retryNextOp()`. + // This is necessary to run retryable operations that failed during + // their initial attempt since we don't know whether they are already + // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1` + // needs to be re-run, we will run `op1`, `op1`, `op2` using the + // already enqueued calls to `retryNextOp()`. `op3()` will then run in the + // call scheduled here. + // Since `backoffAndRun()` cancels an existing backoff and schedules a + // new backoff on every call, there is only ever a single additional + // operation in the queue. + this.backoff.backoffAndRun(() => this.retryNextOp()); + } + } + enqueueInternal(op) { + const newTail = this.tail.then(() => { + this.operationInProgress = true; + return op() + .catch((error) => { + this.failure = error; + this.operationInProgress = false; + const message = getMessageOrStack(error); + logError('INTERNAL UNHANDLED ERROR: ', message); + // Re-throw the error so that this.tail becomes a rejected Promise and + // all further attempts to chain (via .then) will just short-circuit + // and return the rejected Promise. + throw error; + }) + .then(result => { + this.operationInProgress = false; + return result; + }); + }); + this.tail = newTail; + return newTail; + } + enqueueAfterDelay(timerId, delayMs, op) { + this.verifyNotFailed(); + // Fast-forward delays for timerIds that have been overridden. + if (this.timerIdsToSkip.indexOf(timerId) > -1) { + delayMs = 0; + } + const delayedOp = DelayedOperation.createAndSchedule(this, timerId, delayMs, op, removedOp => this.removeDelayedOperation(removedOp)); + this.delayedOperations.push(delayedOp); + return delayedOp; + } + verifyNotFailed() { + if (this.failure) { + fail(0xb815, { + messageOrStack: getMessageOrStack(this.failure) + }); + } + } + verifyOperationInProgress() { + } + /** + * Waits until all currently queued tasks are finished executing. Delayed + * operations are not run. + */ + async drain() { + // Operations in the queue prior to draining may have enqueued additional + // operations. Keep draining the queue until the tail is no longer advanced, + // which indicates that no more new operations were enqueued and that all + // operations were executed. + let currentTail; + do { + currentTail = this.tail; + await currentTail; + } while (currentTail !== this.tail); + } + /** + * For Tests: Determine if a delayed operation with a particular TimerId + * exists. + */ + containsDelayedOperation(timerId) { + for (const op of this.delayedOperations) { + if (op.timerId === timerId) { + return true; + } + } + return false; + } + /** + * For Tests: Runs some or all delayed operations early. + * + * @param lastTimerId - Delayed operations up to and including this TimerId + * will be drained. Pass TimerId.All to run all delayed operations. + * @returns a Promise that resolves once all operations have been run. + */ + runAllDelayedOperationsUntil(lastTimerId) { + // Note that draining may generate more delayed ops, so we do that first. + return this.drain().then(() => { + // Run ops in the same order they'd run if they ran naturally. + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ + this.delayedOperations.sort((a, b) => a.targetTimeMs - b.targetTimeMs); + for (const op of this.delayedOperations) { + op.skipDelay(); + if (lastTimerId !== "all" /* TimerId.All */ && op.timerId === lastTimerId) { + break; + } + } + return this.drain(); + }); + } + /** + * For Tests: Skip all subsequent delays for a timer id. + */ + skipDelaysForTimerId(timerId) { + this.timerIdsToSkip.push(timerId); + } + /** Called once a DelayedOperation is run or canceled. */ + removeDelayedOperation(op) { + // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small. + const index = this.delayedOperations.indexOf(op); + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ + this.delayedOperations.splice(index, 1); + } +} +function newAsyncQueue() { + return new AsyncQueueImpl(); +} +/** + * Chrome includes Error.message in Error.stack. Other browsers do not. + * This returns expected output of message + stack when available. + * @param error - Error or FirestoreError + */ +function getMessageOrStack(error) { + let message = error.message || ''; + if (error.stack) { + if (error.stack.includes(error.message)) { + message = error.stack; + } + else { + message = error.message + '\n' + error.stack; + } + } + return message; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the +// legacy SDK. +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ +class Transaction { + /** @hideconstructor */ + constructor(_firestore, _transaction) { + this._firestore = _firestore; + this._transaction = _transaction; + this._dataReader = newUserDataReader(_firestore); + } + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ + get(documentRef) { + const ref = validateReference(documentRef, this._firestore); + const userDataWriter = new LiteUserDataWriter(this._firestore); + return this._transaction.lookup([ref._key]).then(docs => { + if (!docs || docs.length !== 1) { + return fail(0x5de9); + } + const doc = docs[0]; + if (doc.isFoundDocument()) { + return new DocumentSnapshot(this._firestore, userDataWriter, doc.key, doc, ref.converter); + } + else if (doc.isNoDocument()) { + return new DocumentSnapshot(this._firestore, userDataWriter, ref._key, null, ref.converter); + } + else { + throw fail(0x4801, { + doc + }); + } + }); + } + set(documentRef, value, options) { + const ref = validateReference(documentRef, this._firestore); + const convertedValue = applyFirestoreDataConverter(ref.converter, value, options); + const parsed = parseSetData(this._dataReader, 'Transaction.set', ref._key, convertedValue, ref.converter !== null, options); + this._transaction.set(ref._key, parsed); + return this; + } + update(documentRef, fieldOrUpdateData, value, ...moreFieldsAndValues) { + const ref = validateReference(documentRef, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + fieldOrUpdateData = getModularInstance(fieldOrUpdateData); + let parsed; + if (typeof fieldOrUpdateData === 'string' || + fieldOrUpdateData instanceof FieldPath) { + parsed = parseUpdateVarargs(this._dataReader, 'Transaction.update', ref._key, fieldOrUpdateData, value, moreFieldsAndValues); + } + else { + parsed = parseUpdateData(this._dataReader, 'Transaction.update', ref._key, fieldOrUpdateData); + } + this._transaction.update(ref._key, parsed); + return this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + delete(documentRef) { + const ref = validateReference(documentRef, this._firestore); + this._transaction.delete(ref._key); + return this; + } +} +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ +function runTransaction(firestore, updateFunction, options) { + firestore = cast(firestore, Firestore); + const datastore = getDatastore(firestore); + const optionsWithDefaults = { + ...DEFAULT_TRANSACTION_OPTIONS, + ...options + }; + validateTransactionOptions(optionsWithDefaults); + const deferred = new Deferred(); + new TransactionRunner(newAsyncQueue(), datastore, optionsWithDefaults, internalTransaction => updateFunction(new Transaction(firestore, internalTransaction)), deferred).run(); + return deferred.promise; +} + +/** + * Firestore Lite + * + * @remarks Firestore Lite is a small online-only SDK that allows read + * and write access to your Firestore database. All operations connect + * directly to the backend, and `onSnapshot()` APIs are not supported. + * @packageDocumentation + */ +registerFirestore(); + +export { AggregateField, AggregateQuerySnapshot, Bytes, CollectionReference, DocumentReference, DocumentSnapshot, FieldPath, FieldValue, Firestore, FirestoreError, GeoPoint, Query, QueryCompositeFilterConstraint, QueryConstraint, QueryDocumentSnapshot, QueryEndAtConstraint, QueryFieldFilterConstraint, QueryLimitConstraint, QueryOrderByConstraint, QuerySnapshot, QueryStartAtConstraint, Timestamp, Transaction, VectorValue, WriteBatch, addDoc, aggregateFieldEqual, aggregateQuerySnapshotEqual, and, arrayRemove, arrayUnion, average, collection, collectionGroup, connectFirestoreEmulator, count, deleteDoc, deleteField, doc, documentId, endAt, endBefore, getAggregate, getCount, getDoc, getDocs, getFirestore, increment, initializeFirestore, limit, limitToLast, or, orderBy, query, queryEqual, refEqual, runTransaction, serverTimestamp, setDoc, setLogLevel, snapshotEqual, startAfter, startAt, sum, terminate, updateDoc, vector, where, writeBatch }; +//# sourceMappingURL=index.node.mjs.map diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.mjs.map b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.mjs.map new file mode 100644 index 0000000..721a689 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.node.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.node.mjs","sources":["../../src/auth/user.ts","../../src/core/version.ts","../../src/platform/node/format_json.ts","../../src/util/log.ts","../../src/util/assert.ts","../../src/util/error.ts","../../src/util/promise.ts","../../src/api/credentials.ts","../../src/core/database_info.ts","../../src/platform/node/random_bytes.ts","../../src/util/misc.ts","../../src/model/path.ts","../../src/model/document_key.ts","../../src/util/input_validation.ts","../../src/api/long_polling_options.ts","../../src/util/debug_uid.ts","../../src/remote/rest_connection.ts","../../src/remote/rpc_error.ts","../../src/platform/browser_lite/fetch_connection.ts","../../src/platform/node_lite/connection.ts","../../src/util/obj.ts","../../src/util/types.ts","../../src/platform/node/base64.ts","../../src/util/byte_string.ts","../../src/model/normalize.ts","../../src/util/json_validation.ts","../../src/lite-api/timestamp.ts","../../src/model/server_timestamps.ts","../../src/model/values.ts","../../src/core/bound.ts","../../src/core/filter.ts","../../src/core/order_by.ts","../../src/core/snapshot_version.ts","../../src/util/sorted_map.ts","../../src/util/sorted_set.ts","../../src/model/field_mask.ts","../../src/model/object_value.ts","../../src/model/document.ts","../../src/core/target.ts","../../src/core/query.ts","../../src/remote/number_serializer.ts","../../src/model/transform_operation.ts","../../src/model/mutation.ts","../../src/remote/serializer.ts","../../src/platform/browser/serializer.ts","../../src/remote/backoff.ts","../../src/remote/datastore.ts","../../src/lite-api/components.ts","../../src/local/lru_garbage_collector.ts","../../src/local/simple_db.ts","../../src/local/lru_garbage_collector_impl.ts","../../src/lite-api/settings.ts","../../src/lite-api/database.ts","../../lite/register.ts","../../src/core/aggregate.ts","../../src/lite-api/aggregate_types.ts","../../src/lite-api/reference.ts","../../src/lite-api/bytes.ts","../../src/lite-api/field_path.ts","../../src/lite-api/field_value.ts","../../src/lite-api/geo_point.ts","../../src/util/array.ts","../../src/lite-api/vector_value.ts","../../src/lite-api/user_data_reader.ts","../../src/lite-api/snapshot.ts","../../src/lite-api/query.ts","../../src/lite-api/user_data_writer.ts","../../src/lite-api/reference_impl.ts","../../src/lite-api/aggregate.ts","../../src/lite-api/field_value_impl.ts","../../src/lite-api/write_batch.ts","../../src/core/transaction_options.ts","../../src/core/transaction.ts","../../src/core/transaction_runner.ts","../../src/util/async_queue.ts","../../src/util/async_queue_impl.ts","../../src/lite-api/transaction.ts","../../lite/index.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Simple wrapper around a nullable UID. Mostly exists to make code more\n * readable.\n */\nexport class User {\n /** A user with a null UID. */\n static readonly UNAUTHENTICATED = new User(null);\n\n // TODO(mikelehen): Look into getting a proper uid-equivalent for\n // non-FirebaseAuth providers.\n static readonly GOOGLE_CREDENTIALS = new User('google-credentials-uid');\n static readonly FIRST_PARTY = new User('first-party-uid');\n static readonly MOCK_USER = new User('mock-user');\n\n constructor(readonly uid: string | null) {}\n\n isAuthenticated(): boolean {\n return this.uid != null;\n }\n\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */\n toKey(): string {\n if (this.isAuthenticated()) {\n return 'uid:' + this.uid;\n } else {\n return 'anonymous-user';\n }\n }\n\n isEqual(otherUser: User): boolean {\n return otherUser.uid === this.uid;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The semver (www.semver.org) version of the SDK. */\nimport { version } from '../../../firebase/package.json';\nexport let SDK_VERSION = version;\nexport function setSDKVersion(version: string): void {\n SDK_VERSION = version;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { inspect } from 'util';\n\n/** Formats an object as a JSON string, suitable for logging. */\nexport function formatJSON(value: unknown): string {\n // util.inspect() results in much more readable output than JSON.stringify()\n return inspect(value, { depth: 100 });\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel, LogLevelString } from '@firebase/logger';\n\nimport { SDK_VERSION } from '../core/version';\nimport { formatJSON } from '../platform/format_json';\n\nexport { LogLevel, LogLevelString };\n\nconst logClient = new Logger('@firebase/firestore');\n\n// Helper methods are needed because variables can't be exported as read/write\nexport function getLogLevel(): LogLevel {\n return logClient.logLevel;\n}\n\n/**\n * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).\n *\n * @param logLevel - The verbosity you set for activity and error logging. Can\n * be any of the following values:\n *\n *
    \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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 *\n * @param code generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(\n code: number,\n message: string,\n context?: Record\n): never;\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 *\n * @param id generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(id: number, context?: Record): never;\n\nexport function fail(\n id: number,\n messageOrContext?: string | Record,\n context?: Record\n): never {\n let message = 'Unexpected state';\n if (typeof messageOrContext === 'string') {\n message = messageOrContext;\n } else {\n context = messageOrContext;\n }\n _fail(id, message, context);\n}\n\nfunction _fail(\n id: number,\n failure: string,\n context?: Record\n): never {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n let message = `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ${failure} (ID: ${id.toString(\n 16\n )})`;\n if (context !== undefined) {\n try {\n const stringContext = JSON.stringify(context);\n message += ' CONTEXT: ' + stringContext;\n } catch (e) {\n message += ' CONTEXT: ' + context;\n }\n }\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 *\n * @param id generate a new unique value with `yarn assertion-idgenerate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n assertion: boolean,\n id: number,\n message: string,\n context?: Record\n): asserts assertion;\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 *\n * @param id generate a new unique value with `yarn assertion-id:generate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n assertion: boolean,\n id: number,\n context?: Record\n): asserts assertion;\n\nexport function hardAssert(\n assertion: boolean,\n id: number,\n messageOrContext?: string | Record,\n context?: Record\n): asserts assertion {\n let message = 'Unexpected state';\n if (typeof messageOrContext === 'string') {\n message = messageOrContext;\n } else {\n context = messageOrContext;\n }\n\n if (!assertion) {\n _fail(id, message, context);\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(0xdeb6, 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 { FirebaseApp, _isFirebaseServerApp } from '@firebase/app';\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 0xa539,\n 'Invalid tokenData returned from getToken()',\n { 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 0xa540,\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 0x7c5d,\n 'Invalid tokenData returned from getToken()',\n { 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 0x0807,\n 'Received invalid UID',\n { 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 private serverAppAppCheckToken: string | null = null;\n\n constructor(\n app: FirebaseApp,\n private appCheckProvider: Provider\n ) {\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n }\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n hardAssert(\n this.tokenListener === undefined,\n 0x0db8,\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 if (this.serverAppAppCheckToken) {\n return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n }\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 0xae0e,\n 'Invalid tokenResult returned from getToken()',\n { 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 private serverAppAppCheckToken: string | null = null;\n\n constructor(\n app: FirebaseApp,\n private appCheckProvider: Provider\n ) {\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n appCheckProvider.onInit(appCheck => {\n this.appCheck = appCheck;\n });\n }\n\n getToken(): Promise {\n if (this.serverAppAppCheckToken) {\n return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n }\n\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 0x0d8e,\n 'Invalid tokenResult returned from getToken()',\n { 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","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 readonly isUsingEmulator: 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 { randomBytes as generateRandomBytes } from 'crypto';\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 return generateRandomBytes(nBytes);\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\n/** Compare strings in UTF-8 encoded byte order */\nexport function compareUtf8Strings(left: string, right: string): number {\n // Find the first differing character (a.k.a. \"UTF-16 code unit\") in the two strings and,\n // if found, use that character to determine the relative ordering of the two strings as a\n // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by\n // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8\n // and UTF-16 happen to represent Unicode code points.\n //\n // After finding the first pair of differing characters, there are two cases:\n //\n // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or\n // both are surrogates from a surrogate pair (that collectively represent code points greater\n // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the\n // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is\n // sufficient.\n //\n // Case 2: One character is a surrogate and the other is not. In this case the surrogate-\n // containing string is always ordered after the non-surrogate. This is because surrogates are\n // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations\n // and are lexicographically greater than the 1, 2, or 3-byte representations of code points\n // less than or equal to 0xFFFF.\n //\n // An example of why Case 2 is required is comparing the following two Unicode code points:\n //\n // |-----------------------|------------|---------------------|-----------------|\n // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding |\n // |-----------------------|------------|---------------------|-----------------|\n // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD |\n // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 |\n // |-----------------------|------------|---------------------|-----------------|\n //\n // A lexicographical comparison of the UTF-8 encodings of these code points would order\n // \"Replacement Character\" _before_ \"Grinning Face\" because 0xEF is less than 0xF0. However, a\n // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously\n // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out,\n // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate\n // pair with those that do not.\n const length = Math.min(left.length, right.length);\n for (let i = 0; i < length; i++) {\n const leftChar = left.charAt(i);\n const rightChar = right.charAt(i);\n if (leftChar !== rightChar) {\n return isSurrogate(leftChar) === isSurrogate(rightChar)\n ? primitiveComparator(leftChar, rightChar)\n : isSurrogate(leftChar)\n ? 1\n : -1;\n }\n }\n\n // Use the lengths of the strings to determine the overall comparison result since either the\n // strings were equal or one is a prefix of the other.\n return primitiveComparator(left.length, right.length);\n}\n\nconst MIN_SURROGATE = 0xd800;\nconst MAX_SURROGATE = 0xdfff;\n\nexport function isSurrogate(s: string): boolean {\n debugAssert(s.length === 1, `s.length == ${s.length}, but expected 1`);\n const c = s.charCodeAt(0);\n return c >= MIN_SURROGATE && c <= MAX_SURROGATE;\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 { Integer } from '@firebase/webchannel-wrapper/bloom-blob';\n\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { compareUtf8Strings, primitiveComparator } from '../util/misc';\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(0x027d, 'offset out of range', {\n offset,\n range: segments.length\n });\n }\n\n if (length === undefined) {\n length = segments.length - offset;\n } else if (length > segments.length - offset) {\n fail(0x06d2, 'length out of range', {\n length,\n range: segments.length - offset\n });\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 /**\n * Compare 2 paths segment by segment, prioritizing numeric IDs\n * (e.g., \"__id123__\") in numeric ascending order, followed by string\n * segments in lexicographical order.\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 comparison = BasePath.compareSegments(p1.get(i), p2.get(i));\n if (comparison !== 0) {\n return comparison;\n }\n }\n return primitiveComparator(p1.length, p2.length);\n }\n\n private static compareSegments(lhs: string, rhs: string): number {\n const isLhsNumeric = BasePath.isNumericId(lhs);\n const isRhsNumeric = BasePath.isNumericId(rhs);\n\n if (isLhsNumeric && !isRhsNumeric) {\n // Only lhs is numeric\n return -1;\n } else if (!isLhsNumeric && isRhsNumeric) {\n // Only rhs is numeric\n return 1;\n } else if (isLhsNumeric && isRhsNumeric) {\n // both numeric\n return BasePath.extractNumericId(lhs).compare(\n BasePath.extractNumericId(rhs)\n );\n } else {\n // both non-numeric\n return compareUtf8Strings(lhs, rhs);\n }\n }\n\n // Checks if a segment is a numeric ID (starts with \"__id\" and ends with \"__\").\n private static isNumericId(segment: string): boolean {\n return segment.startsWith('__id') && segment.endsWith('__');\n }\n\n private static extractNumericId(segment: string): Integer {\n return Integer.fromString(segment.substring(4, segment.length - 2));\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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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(0x3029, 'Unknown wrong type', { 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 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 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 { isCloudWorkstation } from '@firebase/util';\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 const { host } = new URL(url);\n const forwardCredentials = isCloudWorkstation(host);\n return this.performRPCRequest(\n rpcName,\n url,\n headers,\n req,\n forwardCredentials\n ).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 _forwardCredentials: boolean\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 { 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(0xfdaa, '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(0x3c6b, '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(0x999b, '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(0x3019, '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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Token } from '../../api/credentials';\nimport { Stream } from '../../remote/connection';\nimport { RestConnection } from '../../remote/rest_connection';\nimport { mapCodeFromHttpStatus } from '../../remote/rpc_error';\nimport { FirestoreError } from '../../util/error';\nimport { StringMap } from '../../util/types';\n\n/**\n * A Rest-based connection that relies on the native HTTP stack\n * (e.g. `fetch` or a polyfill).\n */\nexport class FetchConnection extends RestConnection {\n openStream(\n rpcName: string,\n token: Token | null\n ): Stream {\n throw new Error('Not supported by FetchConnection');\n }\n\n protected async performRPCRequest(\n rpcName: string,\n url: string,\n headers: StringMap,\n body: Req,\n forwardCredentials: boolean\n ): Promise {\n const requestJson = JSON.stringify(body);\n let response: Response;\n\n try {\n const fetchArgs: RequestInit = {\n method: 'POST',\n headers,\n body: requestJson\n };\n if (forwardCredentials) {\n fetchArgs.credentials = 'include';\n }\n response = await fetch(url, fetchArgs);\n } catch (e) {\n const err = e as { status: number | undefined; statusText: string };\n throw new FirestoreError(\n mapCodeFromHttpStatus(err.status),\n 'Request failed with error: ' + err.statusText\n );\n }\n\n if (!response.ok) {\n let errorResponse = await response.json();\n if (Array.isArray(errorResponse)) {\n errorResponse = errorResponse[0];\n }\n const errorMessage = errorResponse?.error?.message;\n throw new FirestoreError(\n mapCodeFromHttpStatus(response.status),\n `Request failed with error: ${errorMessage ?? response.statusText}`\n );\n }\n\n return response.json();\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 { FetchConnection } from '../browser_lite/fetch_connection';\n\nexport { newConnectivityMonitor } from '../browser/connection';\n\n/** Initializes the HTTP connection for the REST API. */\nexport function newConnection(databaseInfo: DatabaseInfo): Connection {\n return new FetchConnection(databaseInfo);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from './assert';\n\nexport interface Dict {\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\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** Converts a Base64 encoded string to a binary string. */\n\nexport function decodeBase64(encoded: string): string {\n // Note: We used to validate the base64 string here via a regular expression.\n // This was removed to improve the performance of indexing.\n return Buffer.from(encoded, 'base64').toString('binary');\n}\n\n/** Converts a binary string to a Base64 encoded string. */\nexport function encodeBase64(raw: string): string {\n return Buffer.from(raw, 'binary').toString('base64');\n}\n\n/** True if and only if the Base64 conversion functions are available. */\nexport function isBase64Available(): boolean {\n return true;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 { 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, 0x986a, '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, 0xb5de, 'invalid timestamp', {\n timestamp: date\n });\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 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isPlainObject } from '../util/input_validation';\n\nimport { Code, FirestoreError } from './error';\n\n/**\n * A list of data types Firestore objects may serialize in their toJSON implemenetations.\n * @private\n * @internal\n */\nexport type JsonTypeDesc =\n | 'object'\n | 'string'\n | 'number'\n | 'boolean'\n | 'null'\n | 'undefined';\n\n/**\n * An association of JsonTypeDesc values to their native types.\n * @private\n * @internal\n */\nexport type TSType = T extends 'object'\n ? object\n : T extends 'string'\n ? string\n : T extends 'number'\n ? number\n : T extends 'boolean'\n ? boolean\n : T extends 'null'\n ? null\n : T extends 'undefined'\n ? undefined\n : never;\n\n/**\n * The representation of a JSON object property name and its type value.\n * @private\n * @internal\n */\nexport interface Property {\n value?: TSType;\n typeString: JsonTypeDesc;\n}\n\n/**\n * A type Firestore data types may use to define the fields used in their JSON serialization.\n * @private\n * @internal\n */\nexport interface JsonSchema {\n [key: string]: Property;\n}\n\n/**\n * Associates the JSON property type to the native type and sets them to be Required.\n * @private\n * @internal\n */\nexport type Json = {\n [K in keyof T]: Required['value'];\n};\n\n/**\n * Helper function to define a JSON schema {@link Property}.\n * @private\n * @internal\n */\nexport function property(\n typeString: T,\n optionalValue?: TSType\n): Property {\n const result: Property = {\n typeString\n };\n if (optionalValue) {\n result.value = optionalValue;\n }\n return result;\n}\n\n/**\n * Validates the JSON object based on the provided schema, and narrows the type to the provided\n * JSON schema.\n * @private\n * @internal\n *\n * @param json A JSON object to validate.\n * @param scheme a {@link JsonSchema} that defines the properties to validate.\n * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise.\n */\nexport function validateJSON(\n json: object,\n schema: S\n): json is Json {\n if (!isPlainObject(json)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'JSON must be an object');\n }\n let error: string | undefined = undefined;\n for (const key in schema) {\n if (schema[key]) {\n const typeString = schema[key].typeString;\n const value: { value: unknown } | undefined =\n 'value' in schema[key] ? { value: schema[key].value } : undefined;\n if (!(key in json)) {\n error = `JSON missing required field: '${key}'`;\n break;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const fieldValue = (json as any)[key];\n if (typeString && typeof fieldValue !== typeString) {\n error = `JSON field '${key}' must be a ${typeString}.`;\n break;\n } else if (value !== undefined && fieldValue !== value.value) {\n error = `Expected '${key}' field to equal '${value.value}'`;\n break;\n }\n }\n }\n if (error) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, error);\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 { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\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 static _jsonSchemaVersion: string = 'firestore/timestamp/1.0';\n static _jsonSchema = {\n type: property('string', Timestamp._jsonSchemaVersion),\n seconds: property('number'),\n nanoseconds: property('number')\n };\n\n /**\n * Returns a JSON-serializable representation of this `Timestamp`.\n */\n toJSON(): { seconds: number; nanoseconds: number; type: string } {\n return {\n type: Timestamp._jsonSchemaVersion,\n seconds: this.seconds,\n nanoseconds: this.nanoseconds\n };\n }\n\n /**\n * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}.\n */\n static fromJSON(json: object): Timestamp {\n if (validateJSON(json, Timestamp._jsonSchema)) {\n return new Timestamp(json.seconds, json.nanoseconds);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Timestamp from JSON.'\n );\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 {\n arrayEquals,\n compareUtf8Strings,\n primitiveComparator\n} 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(0x6e87, 'Invalid value type', { 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(0xcbf8, 'Unexpected value type', { 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 compareUtf8Strings(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(0x5ae0, '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 = compareUtf8Strings(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(0xee4d, 'Invalid value type', { 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(0x34ae, 'Invalid value type', { 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(0x8c66, 'Invalid value type', { 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(0xf207, 'Invalid value type', { 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 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 { 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 other.nullValue === undefined &&\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(0xb8a2, 'Unknown FieldFilter operator', {\n operator: this.op\n });\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(0x4bef, '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 (\n other !== null &&\n other.nullValue === undefined &&\n !arrayValueContains(this.value.arrayValue!, other)\n );\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 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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 './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(0xaad2, 'Red node has red child', {\n key: this.key,\n value: this.value\n });\n }\n if (this.right.isRed()) {\n throw fail(0x3721, 'Right child of (`key`, `value`) is red', {\n key: this.key,\n value: this.value\n });\n }\n const blackDepth = (this.left as LLRBNode).check();\n if (blackDepth !== (this.right as LLRBNode).check()) {\n throw fail(0x6d2d, '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(0xe1a6, 'LLRBEmptyNode has no key.');\n }\n get value(): never {\n throw fail(0x3f0d, 'LLRBEmptyNode has no value.');\n }\n get color(): never {\n throw fail(0x4157, 'LLRBEmptyNode has no color.');\n }\n get left(): never {\n throw fail(0x741e, 'LLRBEmptyNode has no left child.');\n }\n get right(): never {\n throw fail(0x901e, '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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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(\n 0xa786,\n \"Trying to compare documents on fields that don't exist\"\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(0x4d4e, 'Unknown direction', { direction: orderBy.dir });\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 { 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 0x7f90,\n 'server transform result count should match field transform count',\n {\n serverTransformResultCount: serverTransformResults.length,\n fieldTransformCount: fieldTransforms.length\n }\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 { 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\n/**\n * Returns a Timestamp typed object given protobuf timestamp value.\n */\nexport function 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 0xe30b,\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 0x3f41,\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, 0xc050, \"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 0x27ce,\n 'Tried to deserialize invalid key',\n { 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 0x71a3,\n 'tried to deserialize invalid key',\n { 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 0xaa33,\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 0x0f36,\n 'Tried to deserialize a missing document from a found document.'\n );\n hardAssert(\n !!result.readTime,\n 0x5995,\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(0x1c42, 'invalid batch get response', { 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(0x2d51, 'Unknown change type', { 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(0x9991, '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(0x40d7, 'Unknown mutation type', {\n mutationType: mutation.type\n });\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(0x05b7, 'unknown mutation proto', { 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(0x6b69, '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 0x3811,\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(0x51c2, 'Unknown transform', {\n transform: fieldTransform.transform\n });\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 0x40f6,\n 'Unknown server value transform proto',\n { 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(0x40c8, 'Unknown transform proto', { 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 0x07ae,\n 'DocumentsTarget contained other than 1 document',\n {\n count\n }\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 0xfe26,\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(0x713b, '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(0x7591, 'Unknown filter', { 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(0xe2fe, 'Unspecified operator');\n default:\n return fail(0xc54a, '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(0x0402, '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(0xd65d, 'Unrecognized filter type', { 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(0xef81, 'Unspecified filter');\n default:\n return fail(0xed36, '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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 } 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, 0xd7c2, 'Missing entity in write response for `key`', {\n key\n });\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 0xfcd7,\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 settings.isUsingEmulator\n );\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ListenSequenceNumber, 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 { getGlobal, 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 `indexedDB` are guarded by SimpleDb.isAvailable() and getGlobal()\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 lastClosedDbVersion: number | null = null;\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 const globals = getGlobal();\n return wrapRequest(\n globals.indexedDB.deleteDatabase(name)\n ).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\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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\nimport { EmulatorMockTokenOptions } from '@firebase/util';\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 emulatorOptions?: { mockUserToken?: EmulatorMockTokenOptions | string };\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 readonly isUsingEmulator: boolean;\n\n // Can be a google-auth-library or gapi client.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n credentials?: any;\n\n constructor(settings: PrivateSettings) {\n if (settings.host === undefined) {\n if (settings.ssl !== undefined) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't provide ssl option if host option is not set\"\n );\n }\n this.host = DEFAULT_HOST;\n this.ssl = DEFAULT_SSL;\n } else {\n this.host = settings.host;\n this.ssl = settings.ssl ?? DEFAULT_SSL;\n }\n this.isUsingEmulator = settings.emulatorOptions !== undefined;\n\n this.credentials = settings.credentials;\n this.ignoreUndefinedProperties = !!settings.ignoreUndefinedProperties;\n this.localCache = settings.localCache;\n\n if (settings.cacheSizeBytes === undefined) {\n this.cacheSizeBytes = LRU_DEFAULT_CACHE_SIZE_BYTES;\n } else {\n if (\n settings.cacheSizeBytes !== LRU_COLLECTION_DISABLED &&\n settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`\n );\n } else {\n this.cacheSizeBytes = settings.cacheSizeBytes;\n }\n }\n\n validateIsNotUsedTogether(\n 'experimentalForceLongPolling',\n settings.experimentalForceLongPolling,\n 'experimentalAutoDetectLongPolling',\n settings.experimentalAutoDetectLongPolling\n );\n\n this.experimentalForceLongPolling = !!settings.experimentalForceLongPolling;\n\n if (this.experimentalForceLongPolling) {\n this.experimentalAutoDetectLongPolling = false;\n } else if (settings.experimentalAutoDetectLongPolling === undefined) {\n this.experimentalAutoDetectLongPolling = DEFAULT_AUTO_DETECT_LONG_POLLING;\n } else {\n // For backwards compatibility, coerce the value to boolean even though\n // the TypeScript compiler has narrowed the type to boolean already.\n // noinspection PointlessBooleanExpressionJS\n this.experimentalAutoDetectLongPolling =\n !!settings.experimentalAutoDetectLongPolling;\n }\n\n this.experimentalLongPollingOptions = cloneLongPollingOptions(\n settings.experimentalLongPollingOptions ?? {}\n );\n validateLongPollingOptions(this.experimentalLongPollingOptions);\n\n this.useFetchStreams = !!settings.useFetchStreams;\n }\n\n isEqual(other: FirestoreSettingsImpl): boolean {\n return (\n this.host === other.host &&\n this.ssl === other.ssl &&\n this.credentials === other.credentials &&\n this.cacheSizeBytes === other.cacheSizeBytes &&\n this.experimentalForceLongPolling ===\n other.experimentalForceLongPolling &&\n this.experimentalAutoDetectLongPolling ===\n other.experimentalAutoDetectLongPolling &&\n longPollingOptionsEqual(\n this.experimentalLongPollingOptions,\n other.experimentalLongPollingOptions\n ) &&\n this.ignoreUndefinedProperties === other.ignoreUndefinedProperties &&\n this.useFetchStreams === other.useFetchStreams\n );\n }\n}\n\nfunction validateLongPollingOptions(\n options: ExperimentalLongPollingOptions\n): void {\n if (options.timeoutSeconds !== undefined) {\n if (isNaN(options.timeoutSeconds)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ` +\n `${options.timeoutSeconds} (must not be NaN)`\n );\n }\n if (options.timeoutSeconds < MIN_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(minimum allowed value is ${MIN_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n if (options.timeoutSeconds > MAX_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(maximum allowed value is ${MAX_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _getProvider,\n _removeServiceInstance,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport {\n createMockUserToken,\n deepEqual,\n EmulatorMockTokenOptions,\n getDefaultEmulatorHostnameAndPort,\n isCloudWorkstation,\n pingServer,\n updateEmulatorBanner\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 private _emulatorOptions: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {};\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 this._emulatorOptions = settings.emulatorOptions || {};\n\n if (settings.credentials !== undefined) {\n this._authCredentials = makeAuthCredentialsProvider(settings.credentials);\n }\n }\n\n _getSettings(): FirestoreSettingsImpl {\n return this._settings;\n }\n\n _getEmulatorOptions(): { mockUserToken?: EmulatorMockTokenOptions | string } {\n return this._emulatorOptions;\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 useSsl = isCloudWorkstation(host);\n const settings = firestore._getSettings();\n const existingConfig = {\n ...settings,\n emulatorOptions: firestore._getEmulatorOptions()\n };\n const newHostSetting = `${host}:${port}`;\n if (useSsl) {\n void pingServer(`https://${newHostSetting}`);\n updateEmulatorBanner('Firestore', true);\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 const newConfig = {\n ...settings,\n host: newHostSetting,\n ssl: useSsl,\n emulatorOptions: options\n };\n // No-op if the new configuration matches the current configuration. This supports SSR\n // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice.\n if (deepEqual(newConfig, existingConfig)) {\n return;\n }\n\n firestore._setSettings(newConfig);\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 {\n _registerComponent,\n registerVersion,\n SDK_VERSION\n} from '@firebase/app';\nimport { Component, ComponentType } from '@firebase/component';\n\nimport { version } from '../package.json';\nimport {\n LiteAppCheckTokenProvider,\n LiteAuthCredentialsProvider\n} from '../src/api/credentials';\nimport { databaseIdFromApp } from '../src/core/database_info';\nimport { setSDKVersion } from '../src/core/version';\nimport { Firestore } from '../src/lite-api/database';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore/lite': Firestore;\n }\n}\n\nexport function registerFirestore(): void {\n setSDKVersion(`${SDK_VERSION}_lite`);\n _registerComponent(\n new Component(\n 'firestore/lite',\n (container, { instanceIdentifier: databaseId, options: settings }) => {\n const app = container.getProvider('app').getImmediate()!;\n const firestoreInstance = new Firestore(\n new LiteAuthCredentialsProvider(\n container.getProvider('auth-internal')\n ),\n new LiteAppCheckTokenProvider(\n app,\n container.getProvider('app-check-internal')\n ),\n databaseIdFromApp(app, databaseId),\n app\n );\n if (settings) {\n firestoreInstance._setSettings(settings);\n }\n return firestoreInstance;\n },\n 'PUBLIC' as ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n // RUNTIME_ENV and BUILD_TARGET are replaced by real values during the compilation\n registerVersion('firestore-lite', version, '__RUNTIME_ENV__');\n registerVersion('firestore-lite', version, '__BUILD_TARGET__');\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 { FieldPath } from '../model/path';\n\n/**\n * Union type representing the aggregate type to be performed.\n */\nexport type AggregateType = 'count' | 'avg' | 'sum';\n\n/**\n * Represents an Aggregate to be performed over a query result set.\n */\nexport interface Aggregate {\n readonly fieldPath?: FieldPath;\n readonly alias: string;\n readonly aggregateType: AggregateType;\n}\n\n/**\n * Concrete implementation of the Aggregate type.\n */\nexport class AggregateImpl implements Aggregate {\n constructor(\n readonly alias: string,\n readonly aggregateType: AggregateType,\n readonly fieldPath?: FieldPath\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 { AggregateType } from '../core/aggregate';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\n\nimport { average, count, sum } from './aggregate';\nimport { DocumentData, Query } from './reference';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\nexport { AggregateType };\n\n/**\n * Represents an aggregation that can be performed by Firestore.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport class AggregateField {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateField';\n\n /** Indicates the aggregation operation of this AggregateField. */\n readonly aggregateType: AggregateType;\n\n /**\n * Create a new AggregateField\n * @param aggregateType Specifies the type of aggregation operation to perform.\n * @param _internalFieldPath Optionally specifies the field that is aggregated.\n * @internal\n */\n constructor(\n aggregateType: AggregateType = 'count',\n readonly _internalFieldPath?: InternalFieldPath\n ) {\n this.aggregateType = aggregateType;\n }\n}\n\n/**\n * The union of all `AggregateField` types that are supported by Firestore.\n */\nexport type AggregateFieldType =\n | ReturnType\n | ReturnType\n | ReturnType;\n\n/**\n * Specifies a set of aggregations and their aliases.\n */\nexport interface AggregateSpec {\n [field: string]: AggregateFieldType;\n}\n\n/**\n * A type whose keys are taken from an `AggregateSpec`, and whose values are the\n * result of the aggregation performed by the corresponding `AggregateField`\n * from the input `AggregateSpec`.\n */\nexport type AggregateSpecData = {\n [P in keyof T]: T[P] extends AggregateField ? U : never;\n};\n\n/**\n * The results of executing an aggregation query.\n */\nexport class AggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateQuerySnapshot';\n\n /**\n * The underlying query over which the aggregations recorded in this\n * `AggregateQuerySnapshot` were performed.\n */\n readonly query: Query;\n\n /** @hideconstructor */\n constructor(\n query: Query,\n private readonly _userDataWriter: AbstractUserDataWriter,\n private readonly _data: ApiClientObjectMap\n ) {\n this.query = query;\n }\n\n /**\n * Returns the results of the aggregations performed over the underlying\n * query.\n *\n * The keys of the returned object will be the same as those of the\n * `AggregateSpec` object specified to the aggregation method, and the values\n * will be the corresponding aggregation result.\n *\n * @returns The results of the aggregations performed over the underlying\n * query.\n */\n data(): AggregateSpecData {\n return this._userDataWriter.convertObjectMap(\n this._data\n ) as AggregateSpecData;\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 {\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';\n// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_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 static _jsonSchemaVersion: string = 'firestore/documentReference/1.0';\n static _jsonSchema = {\n type: property('string', DocumentReference._jsonSchemaVersion),\n referencePath: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `DocumentReference` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: DocumentReference._jsonSchemaVersion,\n referencePath: this._key.toString()\n };\n }\n\n /**\n * Builds a `DocumentReference` instance from a JSON object created by\n * {@link DocumentReference.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json a JSON object represention of a `DocumentReference` instance\n * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(firestore: Firestore, json: object): DocumentReference;\n /**\n * Builds a `DocumentReference` instance from a JSON object created by\n * {@link DocumentReference.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json a JSON object represention of a `DocumentReference` instance\n * @param converter - Converts objects to and from Firestore.\n * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON<\n NewAppModelType = DocumentData,\n NewDbModelType extends DocumentData = DocumentData\n >(\n firestore: Firestore,\n json: object,\n converter: FirestoreDataConverter\n ): DocumentReference;\n static fromJSON<\n NewAppModelType = DocumentData,\n NewDbModelType extends DocumentData = DocumentData\n >(\n firestore: Firestore,\n json: object,\n converter?: FirestoreDataConverter\n ): DocumentReference {\n if (validateJSON(json, DocumentReference._jsonSchema)) {\n return new DocumentReference(\n firestore,\n converter ? converter : null,\n new DocumentKey(ResourcePath.fromString(json.referencePath))\n );\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Bytes from JSON.'\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 { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\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 static _jsonSchemaVersion: string = 'firestore/bytes/1.0';\n static _jsonSchema = {\n type: property('string', Bytes._jsonSchemaVersion),\n bytes: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `Bytes` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: Bytes._jsonSchemaVersion,\n bytes: this.toBase64()\n };\n }\n\n /**\n * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}.\n *\n * @param json a JSON object represention of a `Bytes` instance\n * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): Bytes {\n if (validateJSON(json, Bytes._jsonSchema)) {\n return Bytes.fromBase64String(json.bytes);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Bytes from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n 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';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\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 /**\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 static _jsonSchemaVersion: string = 'firestore/geoPoint/1.0';\n static _jsonSchema = {\n type: property('string', GeoPoint._jsonSchemaVersion),\n latitude: property('number'),\n longitude: property('number')\n };\n\n /**\n * Returns a JSON-serializable representation of this `GeoPoint` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): { latitude: number; longitude: number; type: string } {\n return {\n latitude: this._lat,\n longitude: this._long,\n type: GeoPoint._jsonSchemaVersion\n };\n }\n\n /**\n * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}.\n *\n * @param json a JSON object represention of a `GeoPoint` instance\n * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): GeoPoint {\n if (validateJSON(json, GeoPoint._jsonSchema)) {\n return new GeoPoint(json.latitude, json.longitude);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating GeoPoint from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Returns 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 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';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\n\n/**\n * Represents a vector type in Firestore documents.\n * Create an instance with {@link 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` values have the same raw number arrays, returns `false` otherwise.\n */\n isEqual(other: VectorValue): boolean {\n return isPrimitiveArrayEqual(this._values, other._values);\n }\n\n static _jsonSchemaVersion: string = 'firestore/vectorValue/1.0';\n static _jsonSchema = {\n type: property('string', VectorValue._jsonSchemaVersion),\n vectorValues: property('object')\n };\n\n /**\n * Returns a JSON-serializable representation of this `VectorValue` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: VectorValue._jsonSchemaVersion,\n vectorValues: this._values\n };\n }\n\n /**\n * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}.\n *\n * @param json a JSON object represention of a `VectorValue` instance.\n * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): VectorValue {\n if (validateJSON(json, VectorValue._jsonSchema)) {\n if (\n Array.isArray(json.vectorValues) &&\n json.vectorValues.every(element => typeof element === 'number')\n ) {\n return new VectorValue(json.vectorValues);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Expected 'vectorValues' field to be a number array\"\n );\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Timestamp from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData,\n FieldPath as PublicFieldPath,\n SetOptions\n} from '@firebase/firestore-types';\nimport { Compat, deepEqual, getModularInstance } from '@firebase/util';\n\nimport { ParseContext } from '../api/parse_context';\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n FieldTransform,\n Mutation,\n PatchMutation,\n Precondition,\n SetMutation\n} from '../model/mutation';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform\n} from '../model/transform_operation';\nimport {\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(0x9c4b, 'Unexpected case for UserDataSource', {\n dataSource\n });\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\nexport function 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(0xf2a2, 'Invalid value type', {\n value\n });\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 0x25d8,\n 'ReferenceValue is not valid',\n { name }\n );\n const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3));\n const key = new DocumentKey(resourcePath.popFirst(5));\n\n if (!databaseId.isEqual(expectedDatabaseId)) {\n // TODO(b/64130202): Somehow support foreign references.\n logError(\n `Document ${key} contains a document ` +\n `reference within a different database (` +\n `${databaseId.projectId}/${databaseId.database}) which is not ` +\n `supported. It will be treated as a reference in the current ` +\n `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` +\n `instead.`\n );\n }\n return key;\n }\n\n protected abstract convertReference(name: string): unknown;\n\n protected abstract convertBytes(bytes: ByteString): unknown;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData as PublicDocumentData,\n SetOptions as PublicSetOptions\n} from '@firebase/firestore-types';\nimport { getModularInstance } from '@firebase/util';\n\nimport { LimitType } from '../core/query';\nimport { DeleteMutation, Precondition } from '../model/mutation';\nimport {\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc,\n invokeRunQueryRpc\n} from '../remote/datastore';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { cast } from '../util/input_validation';\n\nimport { Bytes } from './bytes';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { validateHasExplicitOrderByForLimitToLast } from './query';\nimport {\n CollectionReference,\n doc,\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot\n} from './snapshot';\nimport {\n newUserDataReader,\n ParsedUpdateData,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converts custom model object of type T into `DocumentData` by applying the\n * converter if it exists.\n *\n * This function is used when converting user objects to `DocumentData`\n * because we want to provide the user with a more specific error message if\n * their `set()` or fails due to invalid data originating from a `toFirestore()`\n * call.\n */\nexport function applyFirestoreDataConverter(\n converter: UntypedFirestoreDataConverter | null,\n value: WithFieldValue | PartialWithFieldValue,\n options?: PublicSetOptions\n): PublicDocumentData {\n let convertedValue;\n if (converter) {\n if (options && (options.merge || options.mergeFields)) {\n // Cast to `any` in order to satisfy the union type constraint on\n // toFirestore().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n convertedValue = (converter as any).toFirestore(value, options);\n } else {\n convertedValue = converter.toFirestore(value as WithFieldValue);\n }\n } else {\n convertedValue = value as PublicDocumentData;\n }\n return convertedValue;\n}\n\nexport class LiteUserDataWriter extends AbstractUserDataWriter {\n constructor(protected firestore: Firestore) {\n super();\n }\n\n protected convertBytes(bytes: ByteString): Bytes {\n return new Bytes(bytes);\n }\n\n protected convertReference(name: string): DocumentReference {\n const key = this.convertDocumentKey(name, this.firestore._databaseId);\n return new DocumentReference(this.firestore, /* converter= */ null, key);\n }\n}\n\n/**\n * Reads the document referred to by the specified document reference.\n *\n * All documents are directly fetched from the server, even if the document was\n * previously read or modified. Recent modifications are only reflected in the\n * retrieved `DocumentSnapshot` if they have already been applied by the\n * backend. If the client is offline, the read fails. If you like to use\n * caching or see local modifications, please use the full Firestore SDK.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the current\n * document contents.\n */\nexport function getDoc(\n reference: DocumentReference\n): Promise> {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n const userDataWriter = new LiteUserDataWriter(reference.firestore);\n\n return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then(\n result => {\n hardAssert(\n result.length === 1,\n 0x3d02,\n 'Expected a single document result'\n );\n const document = result[0];\n return new DocumentSnapshot(\n reference.firestore,\n userDataWriter,\n reference._key,\n document.isFoundDocument() ? document : null,\n reference.converter\n );\n }\n );\n}\n\n/**\n * Executes the query and returns the results as a {@link QuerySnapshot}.\n *\n * All queries are executed directly by the server, even if the query was\n * previously executed. Recent modifications are only reflected in the retrieved\n * results if they have already been applied by the backend. If the client is\n * offline, the operation fails. To see previously cached result and local\n * modifications, use the full Firestore SDK.\n *\n * @param query - The `Query` to execute.\n * @returns A Promise that will be resolved with the results of the query.\n */\nexport function getDocs(\n query: Query\n): Promise> {\n query = cast>(query, Query);\n validateHasExplicitOrderByForLimitToLast(query._query);\n\n const datastore = getDatastore(query.firestore);\n const userDataWriter = new LiteUserDataWriter(query.firestore);\n return invokeRunQueryRpc(datastore, query._query).then(result => {\n const docs = result.map(\n doc =>\n new QueryDocumentSnapshot(\n query.firestore,\n userDataWriter,\n doc.key,\n doc,\n query.converter\n )\n );\n\n if (query._query.limitType === LimitType.Last) {\n // Limit to last queries reverse the orderBy constraint that was\n // specified by the user. As such, we need to reverse the order of the\n // results to return the documents in the expected order.\n docs.reverse();\n }\n\n return new QuerySnapshot(query, docs);\n });\n}\n\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\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 * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\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 convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data,\n options\n );\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'setDoc',\n reference._key,\n convertedValue,\n reference.converter !== null,\n options\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference`. The update will fail if applied to a document that does\n * not exist.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\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 * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\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 dataReader = newUserDataReader(reference.firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed: ParsedUpdateData;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData\n );\n }\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.exists(true))\n ]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * The deletion will only be reflected in document reads that occur after the\n * returned promise resolves. If the client is offline, the\n * delete fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to delete.\n * @returns A `Promise` resolved once the document has been successfully\n * deleted from the backend.\n */\nexport function deleteDoc(\n reference: DocumentReference\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n new DeleteMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend.\n */\nexport function addDoc(\n reference: CollectionReference,\n data: WithFieldValue\n): Promise> {\n reference = cast>(\n reference,\n CollectionReference\n );\n const docRef = doc(reference);\n\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data as PartialWithFieldValue\n );\n\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'addDoc',\n docRef._key,\n convertedValue,\n docRef.converter !== null,\n {}\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(docRef._key, Precondition.exists(false))\n ]).then(() => docRef);\n}\n","/**\n * @license\n * Copyright 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 { deepEqual } from '@firebase/util';\n\nimport { AggregateImpl } from '../core/aggregate';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { invokeRunAggregationQueryRpc } from '../remote/datastore';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport {\n AggregateField,\n AggregateQuerySnapshot,\n AggregateSpec\n} from './aggregate_types';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { DocumentData, Query, queryEqual } from './reference';\nimport { LiteUserDataWriter } from './reference_impl';\nimport { fieldPathFromArgument } from './user_data_reader';\n\n/**\n * Calculates the number of documents in the result set of the given query\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can\n * count the documents in cases where the result set is prohibitively large to\n * download entirely (thousands of documents).\n *\n * @param query The query whose result set size is calculated.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */\nexport function getCount(\n query: Query\n): Promise<\n AggregateQuerySnapshot<\n { count: AggregateField },\n AppModelType,\n DbModelType\n >\n> {\n const countQuerySpec: { count: AggregateField } = {\n count: count()\n };\n\n return getAggregate(query, countQuerySpec);\n}\n\n/**\n * Calculates the specified aggregations over the documents in the result\n * set of the given query without actually downloading the documents.\n *\n * Using this function to perform aggregations is efficient because only the\n * final aggregation values, not the documents' data, are downloaded. This\n * function can perform aggregations of the documents in cases where the result\n * set is prohibitively large to download entirely (thousands of documents).\n *\n * @param query The query whose result set is aggregated over.\n * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates\n * to perform over the result set. The AggregateSpec specifies aliases for each\n * aggregate, which can be used to retrieve the aggregate result.\n * @example\n * ```typescript\n * const aggregateSnapshot = await getAggregate(query, {\n * countOfDocs: count(),\n * totalHours: sum('hours'),\n * averageScore: average('score')\n * });\n *\n * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;\n * const totalHours: number = aggregateSnapshot.data().totalHours;\n * const averageScore: number | null = aggregateSnapshot.data().averageScore;\n * ```\n */\nexport function getAggregate<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n aggregateSpec: AggregateSpecType\n): Promise<\n AggregateQuerySnapshot\n> {\n const firestore = cast(query.firestore, Firestore);\n const datastore = getDatastore(firestore);\n\n const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n\n // Run the aggregation and convert the results\n return invokeRunAggregationQueryRpc(\n datastore,\n query._query,\n internalAggregates\n ).then(aggregateResult =>\n convertToAggregateQuerySnapshot(firestore, query, aggregateResult)\n );\n}\n\nfunction convertToAggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n query: Query,\n aggregateResult: ApiClientObjectMap\n): AggregateQuerySnapshot {\n const userDataWriter = new LiteUserDataWriter(firestore);\n const querySnapshot = new AggregateQuerySnapshot<\n AggregateSpecType,\n AppModelType,\n DbModelType\n >(query, userDataWriter, aggregateResult);\n return querySnapshot;\n}\n\n/**\n * Create an AggregateField object that can be used to compute the sum of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to sum across the result set.\n */\nexport function sum(field: string | FieldPath): AggregateField {\n return new AggregateField('sum', fieldPathFromArgument('sum', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the average of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to average across the result set.\n */\nexport function average(\n field: string | FieldPath\n): AggregateField {\n return new AggregateField('avg', fieldPathFromArgument('average', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the count of\n * documents in the result set of a query.\n */\nexport function count(): AggregateField {\n return new AggregateField('count');\n}\n\n/**\n * Compares two 'AggregateField` instances for equality.\n *\n * @param left Compare this AggregateField to the `right`.\n * @param right Compare this AggregateField to the `left`.\n */\nexport function aggregateFieldEqual(\n left: AggregateField,\n right: AggregateField\n): boolean {\n return (\n left instanceof AggregateField &&\n right instanceof AggregateField &&\n left.aggregateType === right.aggregateType &&\n left._internalFieldPath?.canonicalString() ===\n right._internalFieldPath?.canonicalString()\n );\n}\n\n/**\n * Compares two `AggregateQuerySnapshot` instances for equality.\n *\n * Two `AggregateQuerySnapshot` instances are considered \"equal\" if they have\n * underlying queries that compare equal, and the same data.\n *\n * @param left - The first `AggregateQuerySnapshot` to compare.\n * @param right - The second `AggregateQuerySnapshot` to compare.\n *\n * @returns `true` if the objects are \"equal\", as defined above, or `false`\n * otherwise.\n */\nexport function aggregateQuerySnapshotEqual<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n left: AggregateQuerySnapshot,\n right: AggregateQuerySnapshot\n): boolean {\n return (\n queryEqual(left.query, right.query) && deepEqual(left.data(), right.data())\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldValue } from './field_value';\nimport {\n ArrayRemoveFieldValueImpl,\n ArrayUnionFieldValueImpl,\n DeleteFieldValueImpl,\n NumericIncrementFieldValueImpl,\n ServerTimestampFieldValueImpl\n} from './user_data_reader';\nimport { VectorValue } from './vector_value';\n\n/**\n * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or\n * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.\n */\nexport function deleteField(): FieldValue {\n return new DeleteFieldValueImpl('deleteField');\n}\n\n/**\n * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to\n * include a server-generated timestamp in the written data.\n */\nexport function serverTimestamp(): FieldValue {\n return new ServerTimestampFieldValueImpl('serverTimestamp');\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array\n * value that already exists on the server. Each specified element that doesn't\n * already exist in the array will be added to the end. If the field being\n * modified is not already an array it will be overwritten with an array\n * containing exactly the specified elements.\n *\n * @param elements - The elements to union into the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`.\n */\nexport function arrayUnion(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayUnionFieldValueImpl('arrayUnion', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link (setDoc:1)} or {@link\n * updateDoc:1} that tells the server to remove the given elements from any\n * array value that already exists on the server. All instances of each element\n * specified will be removed from the array. If the field being modified is not\n * already an array it will be overwritten with an empty array.\n *\n * @param elements - The elements to remove from the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function arrayRemove(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayRemoveFieldValueImpl('arrayRemove', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by\n * the given value.\n *\n * If either the operand or the current field value uses floating point\n * precision, all arithmetic follows IEEE 754 semantics. If both values are\n * integers, values outside of JavaScript's safe number range\n * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to\n * precision loss. Furthermore, once processed by the Firestore backend, all\n * integer operations are capped between -2^63 and 2^63-1.\n *\n * If the current field value is not of type `number`, or if the field does not\n * yet exist, the transformation sets the field to the given value.\n *\n * @param n - The value to increment by.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function increment(n: number): FieldValue {\n return new NumericIncrementFieldValueImpl('increment', n);\n}\n\n/**\n * Creates a new `VectorValue` constructed with a copy of the given array of numbers.\n *\n * @param values - Create a `VectorValue` instance with a copy of this array of numbers.\n *\n * @returns A new `VectorValue` constructed with a copy of the given array of numbers.\n */\nexport function vector(values?: number[]): VectorValue {\n return new VectorValue(values);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Compat, getModularInstance } from '@firebase/util';\n\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { invokeCommitRpc } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport { applyFirestoreDataConverter } from './reference_impl';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\n\n/**\n * A write batch, used to perform multiple writes as a single atomic unit.\n *\n * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It\n * provides methods for adding writes to the write batch. None of the writes\n * will be committed (or visible locally) until {@link WriteBatch.commit} is\n * called.\n */\nexport class WriteBatch {\n // This is the lite version of the WriteBatch API used in the legacy SDK. The\n // class is a close copy but takes different input types.\n\n private readonly _dataReader: UserDataReader;\n private _mutations = [] as Mutation[];\n private _committed = false;\n\n /** @hideconstructor */\n constructor(\n private readonly _firestore: Firestore,\n private readonly _commitHandler: (m: Mutation[]) => Promise\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): WriteBatch;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): WriteBatch;\n set(\n documentRef: DocumentReference,\n data: WithFieldValue | PartialWithFieldValue,\n options?: SetOptions\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n data,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'WriteBatch.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._mutations.push(parsed.toMutation(ref._key, Precondition.none()));\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): WriteBatch;\n /**\n * Updates fields in the document referred to by this {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be update by providing dot-separated field path strings\n * or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._mutations.push(\n parsed.toMutation(ref._key, Precondition.exists(true))\n );\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n this._mutations = this._mutations.concat(\n new DeleteMutation(ref._key, Precondition.none())\n );\n return this;\n }\n\n /**\n * Commits all of the writes in this write batch as a single atomic unit.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `Promise` resolved once all of the writes in the batch have been\n * successfully written to the backend as an atomic unit (note that it won't\n * resolve while you're offline).\n */\n commit(): Promise {\n this._verifyNotCommitted();\n this._committed = true;\n if (this._mutations.length > 0) {\n return this._commitHandler(this._mutations);\n }\n\n return Promise.resolve();\n }\n\n private _verifyNotCommitted(): void {\n if (this._committed) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A write batch can no longer be used after commit() ' +\n 'has been called.'\n );\n }\n }\n}\n\nexport function validateReference<\n AppModelType,\n DbModelType extends DocumentData\n>(\n documentRef:\n | DocumentReference\n | Compat>,\n firestore: Firestore\n): DocumentReference {\n documentRef = getModularInstance(documentRef);\n\n if (documentRef.firestore !== firestore) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Provided document reference is from a different Firestore instance.'\n );\n } else {\n return documentRef as DocumentReference;\n }\n}\n\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single WriteBatch\n * is 500.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `WriteBatch` that can be used to atomically execute multiple\n * writes.\n */\nexport function writeBatch(firestore: Firestore): WriteBatch {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n return new WriteBatch(firestore, writes =>\n invokeCommitRpc(datastore, writes)\n );\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\n\nexport const DEFAULT_TRANSACTION_OPTIONS: TransactionOptions = {\n maxAttempts: 5\n};\n\n/**\n * Options to customize transaction behavior.\n */\nexport declare interface TransactionOptions {\n /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */\n readonly maxAttempts: number;\n}\n\nexport function validateTransactionOptions(options: TransactionOptions): void {\n if (options.maxAttempts < 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Max attempts must be at least 1'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParsedSetData, ParsedUpdateData } from '../lite-api/user_data_reader';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n DeleteMutation,\n Mutation,\n Precondition,\n VerifyMutation\n} from '../model/mutation';\nimport {\n Datastore,\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc\n} from '../remote/datastore';\nimport { fail, debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { SnapshotVersion } from './snapshot_version';\n\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nexport class Transaction {\n // The version of each document that was read during this transaction.\n private readVersions = new Map();\n private mutations: Mutation[] = [];\n private committed = false;\n\n /**\n * A deferred usage error that occurred previously in this transaction that\n * will cause the transaction to fail once it actually commits.\n */\n private lastTransactionError: FirestoreError | null = null;\n\n /**\n * Set of documents that have been written in the transaction.\n *\n * When there's more than one write to the same key in a transaction, any\n * writes after the first are handled differently.\n */\n private writtenDocs: Set = new Set();\n\n constructor(private datastore: Datastore) {}\n\n async lookup(keys: DocumentKey[]): Promise {\n this.ensureCommitNotCalled();\n\n if (this.mutations.length > 0) {\n this.lastTransactionError = new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Firestore transactions require all reads to be executed before all writes.'\n );\n throw this.lastTransactionError;\n }\n const docs = await invokeBatchGetDocumentsRpc(this.datastore, keys);\n docs.forEach(doc => this.recordVersion(doc));\n return docs;\n }\n\n set(key: DocumentKey, data: ParsedSetData): void {\n this.write(data.toMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n update(key: DocumentKey, data: ParsedUpdateData): void {\n try {\n this.write(data.toMutation(key, this.preconditionForUpdate(key)));\n } catch (e) {\n this.lastTransactionError = e as FirestoreError | null;\n }\n this.writtenDocs.add(key.toString());\n }\n\n delete(key: DocumentKey): void {\n this.write(new DeleteMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n async commit(): Promise {\n this.ensureCommitNotCalled();\n\n if (this.lastTransactionError) {\n throw this.lastTransactionError;\n }\n const unwritten = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach(mutation => {\n unwritten.delete(mutation.key.toString());\n });\n // For each document that was read but not written to, we want to perform\n // a `verify` operation.\n unwritten.forEach((_, path) => {\n const key = DocumentKey.fromPath(path);\n this.mutations.push(new VerifyMutation(key, this.precondition(key)));\n });\n await invokeCommitRpc(this.datastore, this.mutations);\n this.committed = true;\n }\n\n private recordVersion(doc: Document): void {\n let docVersion: SnapshotVersion;\n\n if (doc.isFoundDocument()) {\n docVersion = doc.version;\n } else if (doc.isNoDocument()) {\n // Represent a deleted doc using SnapshotVersion.min().\n docVersion = SnapshotVersion.min();\n } else {\n throw fail(0xc542, 'Document in a transaction was a ', {\n documentName: doc.constructor.name\n });\n }\n\n const existingVersion = this.readVersions.get(doc.key.toString());\n if (existingVersion) {\n if (!docVersion.isEqual(existingVersion)) {\n // This transaction will fail no matter what.\n throw new FirestoreError(\n Code.ABORTED,\n 'Document version changed between two reads.'\n );\n }\n } else {\n this.readVersions.set(doc.key.toString(), docVersion);\n }\n }\n\n /**\n * Returns the version of this document when it was read in this transaction,\n * as a precondition, or no precondition if it was not read.\n */\n private precondition(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n return Precondition.exists(false);\n } else {\n return Precondition.updateTime(version);\n }\n } else {\n return Precondition.none();\n }\n }\n\n /**\n * Returns the precondition for a document if the operation is an update.\n */\n private preconditionForUpdate(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n // The first time a document is written, we want to take into account the\n // read time and existence\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n // The document doesn't exist, so fail the transaction.\n\n // This has to be validated locally because you can't send a\n // precondition that a document does not exist without changing the\n // semantics of the backend write to be an insert. This is the reverse\n // of what we want, since we want to assert that the document doesn't\n // exist but then send the update and have it fail. Since we can't\n // express that to the backend, we have to validate locally.\n\n // Note: this can change once we can send separate verify writes in the\n // transaction.\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't update a document that doesn't exist.\"\n );\n }\n // Document exists, base precondition on document update time.\n return Precondition.updateTime(version);\n } else {\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return Precondition.exists(true);\n }\n }\n\n private write(mutation: Mutation): void {\n this.ensureCommitNotCalled();\n this.mutations.push(mutation);\n }\n\n private ensureCommitNotCalled(): void {\n debugAssert(\n !this.committed,\n 'A transaction object cannot be used after its update callback has been invoked.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ExponentialBackoff } from '../remote/backoff';\nimport { Datastore } from '../remote/datastore';\nimport { isPermanentError } from '../remote/rpc_error';\nimport { AsyncQueue, TimerId } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport { Deferred } from '../util/promise';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Transaction } from './transaction';\nimport { TransactionOptions } from './transaction_options';\n\n/**\n * TransactionRunner encapsulates the logic needed to run and retry transactions\n * with backoff.\n */\nexport class TransactionRunner {\n private attemptsRemaining: number;\n private backoff: ExponentialBackoff;\n\n constructor(\n private readonly asyncQueue: AsyncQueue,\n private readonly datastore: Datastore,\n private readonly options: TransactionOptions,\n private readonly updateFunction: (transaction: Transaction) => Promise,\n private readonly deferred: Deferred\n ) {\n this.attemptsRemaining = options.maxAttempts;\n this.backoff = new ExponentialBackoff(\n this.asyncQueue,\n TimerId.TransactionRetry\n );\n }\n\n /** Runs the transaction and sets the result on deferred. */\n run(): void {\n this.attemptsRemaining -= 1;\n this.runWithBackOff();\n }\n\n private runWithBackOff(): void {\n this.backoff.backoffAndRun(async () => {\n const transaction = new Transaction(this.datastore);\n const userPromise = this.tryRunUpdateFunction(transaction);\n if (userPromise) {\n userPromise\n .then(result => {\n this.asyncQueue.enqueueAndForget(() => {\n return transaction\n .commit()\n .then(() => {\n this.deferred.resolve(result);\n })\n .catch(commitError => {\n this.handleTransactionError(commitError);\n });\n });\n })\n .catch(userPromiseError => {\n this.handleTransactionError(userPromiseError);\n });\n }\n });\n }\n\n private tryRunUpdateFunction(transaction: Transaction): Promise | null {\n try {\n const userPromise = this.updateFunction(transaction);\n if (\n isNullOrUndefined(userPromise) ||\n !userPromise.catch ||\n !userPromise.then\n ) {\n this.deferred.reject(\n Error('Transaction callback must return a Promise')\n );\n return null;\n }\n return userPromise;\n } catch (error) {\n // Do not retry errors thrown by user provided updateFunction.\n this.deferred.reject(error as Error);\n return null;\n }\n }\n\n private handleTransactionError(error: Error): void {\n if (this.attemptsRemaining > 0 && this.isRetryableTransactionError(error)) {\n this.attemptsRemaining -= 1;\n this.asyncQueue.enqueueAndForget(() => {\n this.runWithBackOff();\n return Promise.resolve();\n });\n } else {\n this.deferred.reject(error);\n }\n }\n\n private isRetryableTransactionError(error: Error | undefined): boolean {\n if (error?.name === 'FirebaseError') {\n // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and\n // non-matching document versions with ABORTED. These errors should be retried.\n const code = (error as FirestoreError).code;\n return (\n code === 'aborted' ||\n code === 'failed-precondition' ||\n code === 'already-exists' ||\n !isPermanentError(code)\n );\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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(0xb815, 'AsyncQueue is already failed', {\n messageOrStack: getMessageOrStack(this.failure)\n });\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 { getModularInstance } from '@firebase/util';\n\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport {\n DEFAULT_TRANSACTION_OPTIONS,\n TransactionOptions as TransactionOptionsInternal,\n validateTransactionOptions\n} from '../core/transaction_options';\nimport { TransactionRunner } from '../core/transaction_runner';\nimport { fail } from '../util/assert';\nimport { newAsyncQueue } from '../util/async_queue_impl';\nimport { cast } from '../util/input_validation';\nimport { Deferred } from '../util/promise';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n applyFirestoreDataConverter,\n LiteUserDataWriter\n} from './reference_impl';\nimport { DocumentSnapshot } from './snapshot';\nimport { TransactionOptions } from './transaction_options';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\nimport { validateReference } from './write_batch';\n\n// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the\n// legacy SDK.\n\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nexport class Transaction {\n // This is the tree-shakeable version of the Transaction class used in the\n // legacy SDK. The class is a close copy but takes different input and output\n // types. The firestore-exp SDK further extends this class to return its API\n // type.\n\n private readonly _dataReader: UserDataReader;\n\n /** @hideconstructor */\n constructor(\n protected readonly _firestore: Firestore,\n private readonly _transaction: InternalTransaction\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */\n get(\n documentRef: DocumentReference\n ): Promise> {\n const ref = validateReference(documentRef, this._firestore);\n const userDataWriter = new LiteUserDataWriter(this._firestore);\n return this._transaction.lookup([ref._key]).then(docs => {\n if (!docs || docs.length !== 1) {\n return fail(0x5de9, 'Mismatch in docs returned from document lookup.');\n }\n const doc = docs[0];\n if (doc.isFoundDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n doc.key,\n doc,\n ref.converter\n );\n } else if (doc.isNoDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n ref._key,\n null,\n ref.converter\n );\n } else {\n throw fail(\n 0x4801,\n 'BatchGetDocumentsRequest returned unexpected document',\n {\n doc\n }\n );\n }\n });\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): this;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): this;\n set(\n documentRef: DocumentReference,\n value: PartialWithFieldValue,\n options?: SetOptions\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n value,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'Transaction.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._transaction.set(ref._key, parsed);\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): this;\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key/value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._transaction.update(ref._key, parsed);\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n this._transaction.delete(ref._key);\n return this;\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */\nexport function runTransaction(\n firestore: Firestore,\n updateFunction: (transaction: Transaction) => Promise,\n options?: TransactionOptions\n): Promise {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n const optionsWithDefaults: TransactionOptionsInternal = {\n ...DEFAULT_TRANSACTION_OPTIONS,\n ...options\n };\n validateTransactionOptions(optionsWithDefaults);\n const deferred = new Deferred();\n new TransactionRunner(\n newAsyncQueue(),\n datastore,\n optionsWithDefaults,\n internalTransaction =>\n updateFunction(new Transaction(firestore, internalTransaction)),\n deferred\n ).run();\n return deferred.promise;\n}\n","/**\n * Firestore Lite\n *\n * @remarks Firestore Lite is a small online-only SDK that allows read\n * and write access to your Firestore database. All operations connect\n * directly to the backend, and `onSnapshot()` APIs are not supported.\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 { registerFirestore } from './register';\nregisterFirestore();\n\nexport {\n aggregateQuerySnapshotEqual,\n getCount,\n getAggregate,\n count,\n sum,\n average,\n aggregateFieldEqual\n} from '../src/lite-api/aggregate';\n\nexport {\n AggregateField,\n AggregateFieldType,\n AggregateSpec,\n AggregateSpecData,\n AggregateQuerySnapshot,\n AggregateType\n} from '../src/lite-api/aggregate_types';\n\nexport { FirestoreSettings as Settings } from '../src/lite-api/settings';\n\nexport {\n Firestore as Firestore,\n EmulatorMockTokenOptions,\n initializeFirestore,\n getFirestore,\n terminate,\n connectFirestoreEmulator\n} from '../src/lite-api/database';\n\nexport {\n DocumentData,\n UpdateData,\n WithFieldValue,\n PartialWithFieldValue,\n SetOptions,\n DocumentReference,\n Query,\n CollectionReference,\n collection,\n collectionGroup,\n doc,\n refEqual,\n queryEqual\n} from '../src/lite-api/reference';\n\nexport {\n and,\n endAt,\n endBefore,\n startAt,\n startAfter,\n limit,\n limitToLast,\n where,\n or,\n orderBy,\n query,\n QueryConstraint,\n QueryConstraintType,\n QueryCompositeFilterConstraint,\n QueryFilterConstraint,\n QueryFieldFilterConstraint,\n QueryOrderByConstraint,\n QueryLimitConstraint,\n QueryNonFilterConstraint,\n QueryStartAtConstraint,\n QueryEndAtConstraint,\n OrderByDirection,\n WhereFilterOp\n} from '../src/lite-api/query';\n\nexport {\n addDoc,\n deleteDoc,\n updateDoc,\n setDoc,\n getDoc,\n getDocs\n} from '../src/lite-api/reference_impl';\n\nexport {\n Primitive,\n NestedUpdateFields,\n ChildUpdateFields,\n AddPrefixToKeys,\n UnionToIntersection\n} from '../src/lite-api/types';\n\n// TODO(firestorelite): Add tests when Queries are usable\nexport { FieldPath, documentId } from '../src/lite-api/field_path';\n\n// TODO(firestorelite): Add tests when setDoc() is available\nexport { FieldValue } from '../src/lite-api/field_value';\n\nexport {\n increment,\n arrayRemove,\n arrayUnion,\n serverTimestamp,\n deleteField,\n vector\n} from '../src/lite-api/field_value_impl';\n\nexport {\n FirestoreDataConverter,\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot,\n snapshotEqual\n} from '../src/lite-api/snapshot';\n\nexport { VectorValue } from '../src/lite-api/vector_value';\n\nexport { WriteBatch, writeBatch } from '../src/lite-api/write_batch';\n\nexport { TransactionOptions } from '../src/lite-api/transaction_options';\n\nexport { Transaction, runTransaction } from '../src/lite-api/transaction';\n\nexport { setLogLevel, LogLevelString as LogLevel } from '../src/util/log';\n\nexport { Bytes } from '../src/lite-api/bytes';\n\nexport { GeoPoint } from '../src/lite-api/geo_point';\n\nexport { Timestamp } from '../src/lite-api/timestamp';\n\nexport { FirestoreErrorCode, FirestoreError } from '../src/util/error';\n"],"names":["generateRandomBytes","FieldPath","LOG_TAG","TYPE_KEY","SDK_VERSION","version","InternalFieldPath","fieldPathFromArgument","Transaction"],"mappings":";;;;;;;;;;AAAA;;;;;;;;;;;;;;;AAeG;AAEH;;;AAGG;AACU,MAAA,IAAI,CAAA;AAUf,IAAA,WAAA,CAAqB,GAAkB,EAAA;AAAlB,QAAA,IAAG,CAAA,GAAA,GAAH,GAAG,CAAe;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,2BAA2B;AAC9B,QAAA,GAAG,OAAO;KACX,CAAC;IACF,0BAA0B,CAAC,mBAAmB,CAAC,CAAC;AAChD,IAAA,MAAM,QAAQ,GAAG,IAAI,QAAQ,EAAK,CAAC;AACnC,IAAA,IAAI,iBAAiB,CACnB,aAAa,EAAE,EACf,SAAS,EACT,mBAAmB,EACnB,mBAAmB,IACjB,cAAc,CAAC,IAAI,WAAW,CAAC,SAAS,EAAE,mBAAmB,CAAC,CAAC,EACjE,QAAQ,CACT,CAAC,GAAG,EAAE,CAAC;IACR,OAAO,QAAQ,CAAC,OAAO,CAAC;AAC1B,CAAA;;ACvTA;;;;;;;AAOG;AAoBH,iBAAiB,EAAE;;;;"} \ No newline at end of file diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/index.rn.esm.js b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.rn.esm.js new file mode 100644 index 0000000..d0db455 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.rn.esm.js @@ -0,0 +1,7672 @@ +import { _isFirebaseServerApp as t, _getProvider, getApp as e, _removeServiceInstance as r, _registerComponent as n, registerVersion as i, SDK_VERSION as s } from "@firebase/app"; + +import { Component as o } from "@firebase/component"; + +import { Logger as a, LogLevel as u } from "@firebase/logger"; + +import { FirebaseError as _, isCloudWorkstation as c, base64 as l, DecodeBase64StringError as h, getDefaultEmulatorHostnameAndPort as f, pingServer as d, updateEmulatorBanner as m, deepEqual as E, createMockUserToken as T, getModularInstance as P } from "@firebase/util"; + +import { Integer as A } from "@firebase/webchannel-wrapper/bloom-blob"; + +const R = "4.9.2"; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Simple wrapper around a nullable UID. Mostly exists to make code more + * readable. + */ class User { + constructor(t) { + this.uid = t; + } + isAuthenticated() { + return null != this.uid; + } + /** + * Returns a key representing this user, suitable for inclusion in a + * dictionary. + */ toKey() { + return this.isAuthenticated() ? "uid:" + this.uid : "anonymous-user"; + } + isEqual(t) { + return t.uid === this.uid; + } +} + +/** A user with a null UID. */ User.UNAUTHENTICATED = new User(null), +// TODO(mikelehen): Look into getting a proper uid-equivalent for +// non-FirebaseAuth providers. +User.GOOGLE_CREDENTIALS = new User("google-credentials-uid"), User.FIRST_PARTY = new User("first-party-uid"), +User.MOCK_USER = new User("mock-user"); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let V = "12.3.0"; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const I = new a("@firebase/firestore"); + +/** + * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). + * + * @param logLevel - The verbosity you set for activity and error logging. Can + * be any of the following values: + * + *
    + *
  • `debug` for the most verbose logging level, primarily for + * debugging.
  • + *
  • `error` to log errors only.
  • + *
  • `silent` to turn off logging.
  • + *
+ */ function setLogLevel(t) { + I.setLogLevel(t); +} + +function __PRIVATE_logDebug(t, ...e) { + if (I.logLevel <= u.DEBUG) { + const r = e.map(__PRIVATE_argToString); + I.debug(`Firestore (${V}): ${t}`, ...r); + } +} + +function __PRIVATE_logError(t, ...e) { + if (I.logLevel <= u.ERROR) { + const r = e.map(__PRIVATE_argToString); + I.error(`Firestore (${V}): ${t}`, ...r); + } +} + +/** + * @internal + */ function __PRIVATE_logWarn(t, ...e) { + if (I.logLevel <= u.WARN) { + const r = e.map(__PRIVATE_argToString); + I.warn(`Firestore (${V}): ${t}`, ...r); + } +} + +/** + * Converts an additional log parameter to a string representation. + */ function __PRIVATE_argToString(t) { + if ("string" == typeof t) return t; + try { + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** Formats an object as a JSON string, suitable for logging. */ + return function __PRIVATE_formatJSON(t) { + return JSON.stringify(t); + }(t); + } catch (e) { + // Converting to JSON failed, just log the object directly + return t; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function fail(t, e, r) { + let n = "Unexpected state"; + "string" == typeof e ? n = e : r = e, __PRIVATE__fail(t, n, r); +} + +function __PRIVATE__fail(t, e, r) { + // Log the failure in addition to throw an exception, just in case the + // exception is swallowed. + let n = `FIRESTORE (${V}) INTERNAL ASSERTION FAILED: ${e} (ID: ${t.toString(16)})`; + if (void 0 !== r) try { + n += " CONTEXT: " + JSON.stringify(r); + } catch (t) { + n += " CONTEXT: " + r; + } + // NOTE: We don't use FirestoreError here because these are internal failures + // that cannot be handled by the user. (Also it would create a circular + // dependency between the error and assert modules which doesn't work.) + throw __PRIVATE_logError(n), new Error(n); +} + +function __PRIVATE_hardAssert(t, e, r, n) { + let i = "Unexpected state"; + "string" == typeof r ? i = r : n = r, t || __PRIVATE__fail(e, i, n); +} + +/** + * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an + * instance of `T` before casting. + */ function __PRIVATE_debugCast(t, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +e) { + return t; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const p = "ok", y = "cancelled", g = "unknown", w = "invalid-argument", F = "deadline-exceeded", v = "not-found", D = "already-exists", b = "permission-denied", S = "unauthenticated", C = "resource-exhausted", N = "failed-precondition", O = "aborted", q = "out-of-range", B = "unimplemented", $ = "internal", Q = "unavailable", k = "data-loss"; + +/** An error returned by a Firestore operation. */ class FirestoreError extends _ { + /** @hideconstructor */ + constructor( + /** + * The backend error code associated with this error. + */ + t, + /** + * A custom error description. + */ + e) { + super(t, e), this.code = t, this.message = e, + // HACK: We write a toString property directly because Error is not a real + // class and so inheritance does not work correctly. We could alternatively + // do the same "back-door inheritance" trick that FirebaseError does. + this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_Deferred { + constructor() { + this.promise = new Promise(((t, e) => { + this.resolve = t, this.reject = e; + })); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class __PRIVATE_OAuthToken { + constructor(t, e) { + this.user = e, this.type = "OAuth", this.headers = new Map, this.headers.set("Authorization", `Bearer ${t}`); + } +} + +/** + * A CredentialsProvider that always yields an empty token. + * @internal + */ class __PRIVATE_EmptyAuthCredentialsProvider { + getToken() { + return Promise.resolve(null); + } + invalidateToken() {} + start(t, e) { + // Fire with initial user. + t.enqueueRetryable((() => e(User.UNAUTHENTICATED))); + } + shutdown() {} +} + +/** + * A CredentialsProvider that always returns a constant token. Used for + * emulator token mocking. + */ class __PRIVATE_EmulatorAuthCredentialsProvider { + constructor(t) { + this.token = t, + /** + * Stores the listener registered with setChangeListener() + * This isn't actually necessary since the UID never changes, but we use this + * to verify the listen contract is adhered to in tests. + */ + this.changeListener = null; + } + getToken() { + return Promise.resolve(this.token); + } + invalidateToken() {} + start(t, e) { + this.changeListener = e, + // Fire with initial user. + t.enqueueRetryable((() => e(this.token.user))); + } + shutdown() { + this.changeListener = null; + } +} + +/** Credential provider for the Lite SDK. */ class __PRIVATE_LiteAuthCredentialsProvider { + constructor(t) { + this.auth = null, t.onInit((t => { + this.auth = t; + })); + } + getToken() { + return this.auth ? this.auth.getToken().then((t => t ? (__PRIVATE_hardAssert("string" == typeof t.accessToken, 42297, { + t: t + }), new __PRIVATE_OAuthToken(t.accessToken, new User(this.auth.getUid()))) : null)) : Promise.resolve(null); + } + invalidateToken() {} + start(t, e) {} + shutdown() {} +} + +/* + * FirstPartyToken provides a fresh token each time its value + * is requested, because if the token is too old, requests will be rejected. + * Technically this may no longer be necessary since the SDK should gracefully + * recover from unauthenticated errors (see b/33147818 for context), but it's + * safer to keep the implementation as-is. + */ class __PRIVATE_FirstPartyToken { + constructor(t, e, r) { + this.i = t, this.o = e, this.u = r, this.type = "FirstParty", this.user = User.FIRST_PARTY, + this.l = new Map; + } + /** + * Gets an authorization token, using a provided factory function, or return + * null. + */ h() { + return this.u ? this.u() : null; + } + get headers() { + this.l.set("X-Goog-AuthUser", this.i); + // Use array notation to prevent minification + const t = this.h(); + return t && this.l.set("Authorization", t), this.o && this.l.set("X-Goog-Iam-Authorization-Token", this.o), + this.l; + } +} + +/* + * Provides user credentials required for the Firestore JavaScript SDK + * to authenticate the user, using technique that is only available + * to applications hosted by Google. + */ class __PRIVATE_FirstPartyAuthCredentialsProvider { + constructor(t, e, r) { + this.i = t, this.o = e, this.u = r; + } + getToken() { + return Promise.resolve(new __PRIVATE_FirstPartyToken(this.i, this.o, this.u)); + } + start(t, e) { + // Fire with initial uid. + t.enqueueRetryable((() => e(User.FIRST_PARTY))); + } + shutdown() {} + invalidateToken() {} +} + +class AppCheckToken { + constructor(t) { + this.value = t, this.type = "AppCheck", this.headers = new Map, t && t.length > 0 && this.headers.set("x-firebase-appcheck", this.value); + } +} + +/** AppCheck token provider for the Lite SDK. */ class __PRIVATE_LiteAppCheckTokenProvider { + constructor(e, r) { + this.m = r, this.appCheck = null, this.T = null, t(e) && e.settings.appCheckToken && (this.T = e.settings.appCheckToken), + r.onInit((t => { + this.appCheck = t; + })); + } + getToken() { + return this.T ? Promise.resolve(new AppCheckToken(this.T)) : this.appCheck ? this.appCheck.getToken().then((t => t ? (__PRIVATE_hardAssert("string" == typeof t.token, 3470, { + tokenResult: t + }), new AppCheckToken(t.token)) : null)) : Promise.resolve(null); + } + invalidateToken() {} + start(t, e) {} + shutdown() {} +} + +/** + * Builds a CredentialsProvider depending on the type of + * the credentials passed in. + */ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +class DatabaseInfo { + /** + * Constructs a DatabaseInfo using the provided host, databaseId and + * persistenceKey. + * + * @param databaseId - The database to use. + * @param appId - The Firebase App Id. + * @param persistenceKey - A unique identifier for this Firestore's local + * storage (used in conjunction with the databaseId). + * @param host - The Firestore backend host to connect to. + * @param ssl - Whether to use SSL when connecting. + * @param forceLongPolling - Whether to use the forceLongPolling option + * when using WebChannel as the network transport. + * @param autoDetectLongPolling - Whether to use the detectBufferingProxy + * option when using WebChannel as the network transport. + * @param longPollingOptions Options that configure long-polling. + * @param useFetchStreams Whether to use the Fetch API instead of + * XMLHTTPRequest + */ + constructor(t, e, r, n, i, s, o, a, u, _) { + this.databaseId = t, this.appId = e, this.persistenceKey = r, this.host = n, this.ssl = i, + this.forceLongPolling = s, this.autoDetectLongPolling = o, this.longPollingOptions = a, + this.useFetchStreams = u, this.isUsingEmulator = _; + } +} + +/** The default database name for a project. */ const L = "(default)"; + +/** + * Represents the database ID a Firestore client is associated with. + * @internal + */ class DatabaseId { + constructor(t, e) { + this.projectId = t, this.database = e || L; + } + static empty() { + return new DatabaseId("", ""); + } + get isDefaultDatabase() { + return this.database === L; + } + isEqual(t) { + return t instanceof DatabaseId && t.projectId === this.projectId && t.database === this.database; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Generates `nBytes` of random bytes. + * + * If `nBytes < 0` , an error will be thrown. + */ +function __PRIVATE_randomBytes(t) { + // Polyfills for IE and WebWorker by using `self` and `msCrypto` when `crypto` is not available. + const e = + // eslint-disable-next-line @typescript-eslint/no-explicit-any + "undefined" != typeof self && (self.crypto || self.msCrypto), r = new Uint8Array(t); + if (e && "function" == typeof e.getRandomValues) e.getRandomValues(r); else + // Falls back to Math.random + for (let e = 0; e < t; e++) r[e] = Math.floor(256 * Math.random()); + return r; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A utility class for generating unique alphanumeric IDs of a specified length. + * + * @internal + * Exported internally for testing purposes. + */ class __PRIVATE_AutoId { + static newId() { + // Alphanumeric characters + const t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", e = 62 * Math.floor(256 / 62); + // The largest byte value that is a multiple of `char.length`. + let r = ""; + for (;r.length < 20; ) { + const n = __PRIVATE_randomBytes(40); + for (let i = 0; i < n.length; ++i) + // Only accept values that are [0, maxMultiple), this ensures they can + // be evenly mapped to indices of `chars` via a modulo operation. + r.length < 20 && n[i] < e && (r += t.charAt(n[i] % 62)); + } + return r; + } +} + +function __PRIVATE_primitiveComparator(t, e) { + return t < e ? -1 : t > e ? 1 : 0; +} + +/** Compare strings in UTF-8 encoded byte order */ function __PRIVATE_compareUtf8Strings(t, e) { + // Find the first differing character (a.k.a. "UTF-16 code unit") in the two strings and, + // if found, use that character to determine the relative ordering of the two strings as a + // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by + // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8 + // and UTF-16 happen to represent Unicode code points. + // After finding the first pair of differing characters, there are two cases: + // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or + // both are surrogates from a surrogate pair (that collectively represent code points greater + // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the + // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is + // sufficient. + // Case 2: One character is a surrogate and the other is not. In this case the surrogate- + // containing string is always ordered after the non-surrogate. This is because surrogates are + // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations + // and are lexicographically greater than the 1, 2, or 3-byte representations of code points + // less than or equal to 0xFFFF. + // An example of why Case 2 is required is comparing the following two Unicode code points: + // |-----------------------|------------|---------------------|-----------------| + // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding | + // |-----------------------|------------|---------------------|-----------------| + // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD | + // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 | + // |-----------------------|------------|---------------------|-----------------| + // A lexicographical comparison of the UTF-8 encodings of these code points would order + // "Replacement Character" _before_ "Grinning Face" because 0xEF is less than 0xF0. However, a + // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously + // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out, + // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate + // pair with those that do not. + const r = Math.min(t.length, e.length); + for (let n = 0; n < r; n++) { + const r = t.charAt(n), i = e.charAt(n); + if (r !== i) return __PRIVATE_isSurrogate(r) === __PRIVATE_isSurrogate(i) ? __PRIVATE_primitiveComparator(r, i) : __PRIVATE_isSurrogate(r) ? 1 : -1; + } + // Use the lengths of the strings to determine the overall comparison result since either the + // strings were equal or one is a prefix of the other. + return __PRIVATE_primitiveComparator(t.length, e.length); +} + +const M = 55296, x = 57343; + +function __PRIVATE_isSurrogate(t) { + const e = t.charCodeAt(0); + return e >= M && e <= x; +} + +/** Helper to compare arrays using isEqual(). */ function __PRIVATE_arrayEquals(t, e, r) { + return t.length === e.length && t.every(((t, n) => r(t, e[n]))); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const U = "__name__"; + +/** + * Path represents an ordered sequence of string segments. + */ class BasePath { + constructor(t, e, r) { + void 0 === e ? e = 0 : e > t.length && fail(637, { + offset: e, + range: t.length + }), void 0 === r ? r = t.length - e : r > t.length - e && fail(1746, { + length: r, + range: t.length - e + }), this.segments = t, this.offset = e, this.len = r; + } + get length() { + return this.len; + } + isEqual(t) { + return 0 === BasePath.comparator(this, t); + } + child(t) { + const e = this.segments.slice(this.offset, this.limit()); + return t instanceof BasePath ? t.forEach((t => { + e.push(t); + })) : e.push(t), this.construct(e); + } + /** The index of one past the last segment of the path. */ limit() { + return this.offset + this.length; + } + popFirst(t) { + return t = void 0 === t ? 1 : t, this.construct(this.segments, this.offset + t, this.length - t); + } + popLast() { + return this.construct(this.segments, this.offset, this.length - 1); + } + firstSegment() { + return this.segments[this.offset]; + } + lastSegment() { + return this.get(this.length - 1); + } + get(t) { + return this.segments[this.offset + t]; + } + isEmpty() { + return 0 === this.length; + } + isPrefixOf(t) { + if (t.length < this.length) return !1; + for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1; + return !0; + } + isImmediateParentOf(t) { + if (this.length + 1 !== t.length) return !1; + for (let e = 0; e < this.length; e++) if (this.get(e) !== t.get(e)) return !1; + return !0; + } + forEach(t) { + for (let e = this.offset, r = this.limit(); e < r; e++) t(this.segments[e]); + } + toArray() { + return this.segments.slice(this.offset, this.limit()); + } + /** + * Compare 2 paths segment by segment, prioritizing numeric IDs + * (e.g., "__id123__") in numeric ascending order, followed by string + * segments in lexicographical order. + */ static comparator(t, e) { + const r = Math.min(t.length, e.length); + for (let n = 0; n < r; n++) { + const r = BasePath.compareSegments(t.get(n), e.get(n)); + if (0 !== r) return r; + } + return __PRIVATE_primitiveComparator(t.length, e.length); + } + static compareSegments(t, e) { + const r = BasePath.isNumericId(t), n = BasePath.isNumericId(e); + return r && !n ? -1 : !r && n ? 1 : r && n ? BasePath.extractNumericId(t).compare(BasePath.extractNumericId(e)) : __PRIVATE_compareUtf8Strings(t, e); + } + // Checks if a segment is a numeric ID (starts with "__id" and ends with "__"). + static isNumericId(t) { + return t.startsWith("__id") && t.endsWith("__"); + } + static extractNumericId(t) { + return A.fromString(t.substring(4, t.length - 2)); + } +} + +/** + * A slash-separated path for navigating resources (documents and collections) + * within Firestore. + * + * @internal + */ class ResourcePath extends BasePath { + construct(t, e, r) { + return new ResourcePath(t, e, r); + } + canonicalString() { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + return this.toArray().join("/"); + } + toString() { + return this.canonicalString(); + } + /** + * Returns a string representation of this path + * where each path segment has been encoded with + * `encodeURIComponent`. + */ toUriEncodedString() { + return this.toArray().map(encodeURIComponent).join("/"); + } + /** + * Creates a resource path from the given slash-delimited string. If multiple + * arguments are provided, all components are combined. Leading and trailing + * slashes from all components are ignored. + */ static fromString(...t) { + // NOTE: The client is ignorant of any path segments containing escape + // sequences (e.g. __id123__) and just passes them through raw (they exist + // for legacy reasons and should not be used frequently). + const e = []; + for (const r of t) { + if (r.indexOf("//") >= 0) throw new FirestoreError(w, `Invalid segment (${r}). Paths must not contain // in them.`); + // Strip leading and trailing slashed. + e.push(...r.split("/").filter((t => t.length > 0))); + } + return new ResourcePath(e); + } + static emptyPath() { + return new ResourcePath([]); + } +} + +const j = /^[_a-zA-Z][_a-zA-Z0-9]*$/; + +/** + * A dot-separated path for navigating sub-objects within a document. + * @internal + */ class FieldPath$1 extends BasePath { + construct(t, e, r) { + return new FieldPath$1(t, e, r); + } + /** + * Returns true if the string could be used as a segment in a field path + * without escaping. + */ static isValidIdentifier(t) { + return j.test(t); + } + canonicalString() { + return this.toArray().map((t => (t = t.replace(/\\/g, "\\\\").replace(/`/g, "\\`"), + FieldPath$1.isValidIdentifier(t) || (t = "`" + t + "`"), t))).join("."); + } + toString() { + return this.canonicalString(); + } + /** + * Returns true if this field references the key of a document. + */ isKeyField() { + return 1 === this.length && this.get(0) === U; + } + /** + * The field designating the key of a document. + */ static keyField() { + return new FieldPath$1([ U ]); + } + /** + * Parses a field string from the given server-formatted string. + * + * - Splitting the empty string is not allowed (for now at least). + * - Empty segments within the string (e.g. if there are two consecutive + * separators) are not allowed. + * + * TODO(b/37244157): we should make this more strict. Right now, it allows + * non-identifier path components, even if they aren't escaped. + */ static fromServerFormat(t) { + const e = []; + let r = "", n = 0; + const __PRIVATE_addCurrentSegment = () => { + if (0 === r.length) throw new FirestoreError(w, `Invalid field path (${t}). Paths must not be empty, begin with '.', end with '.', or contain '..'`); + e.push(r), r = ""; + }; + let i = !1; + for (;n < t.length; ) { + const e = t[n]; + if ("\\" === e) { + if (n + 1 === t.length) throw new FirestoreError(w, "Path has trailing escape character: " + t); + const e = t[n + 1]; + if ("\\" !== e && "." !== e && "`" !== e) throw new FirestoreError(w, "Path has invalid escape sequence: " + t); + r += e, n += 2; + } else "`" === e ? (i = !i, n++) : "." !== e || i ? (r += e, n++) : (__PRIVATE_addCurrentSegment(), + n++); + } + if (__PRIVATE_addCurrentSegment(), i) throw new FirestoreError(w, "Unterminated ` in path: " + t); + return new FieldPath$1(e); + } + static emptyPath() { + return new FieldPath$1([]); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @internal + */ class DocumentKey { + constructor(t) { + this.path = t; + } + static fromPath(t) { + return new DocumentKey(ResourcePath.fromString(t)); + } + static fromName(t) { + return new DocumentKey(ResourcePath.fromString(t).popFirst(5)); + } + static empty() { + return new DocumentKey(ResourcePath.emptyPath()); + } + get collectionGroup() { + return this.path.popLast().lastSegment(); + } + /** Returns true if the document is in the specified collectionId. */ hasCollectionId(t) { + return this.path.length >= 2 && this.path.get(this.path.length - 2) === t; + } + /** Returns the collection group (i.e. the name of the parent collection) for this key. */ getCollectionGroup() { + return this.path.get(this.path.length - 2); + } + /** Returns the fully qualified path to the parent collection. */ getCollectionPath() { + return this.path.popLast(); + } + isEqual(t) { + return null !== t && 0 === ResourcePath.comparator(this.path, t.path); + } + toString() { + return this.path.toString(); + } + static comparator(t, e) { + return ResourcePath.comparator(t.path, e.path); + } + static isDocumentKey(t) { + return t.length % 2 == 0; + } + /** + * Creates and returns a new document key with the given segments. + * + * @param segments - The segments of the path to the document + * @returns A new instance of DocumentKey + */ static fromSegments(t) { + return new DocumentKey(new ResourcePath(t.slice())); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_validateNonEmptyArgument(t, e, r) { + if (!r) throw new FirestoreError(w, `Function ${t}() cannot be called with an empty ${e}.`); +} + +/** + * Validates that two boolean options are not set at the same time. + * @internal + */ +/** + * Validates that `path` refers to a document (indicated by the fact it contains + * an even numbers of segments). + */ +function __PRIVATE_validateDocumentPath(t) { + if (!DocumentKey.isDocumentKey(t)) throw new FirestoreError(w, `Invalid document reference. Document references must have an even number of segments, but ${t} has ${t.length}.`); +} + +/** + * Validates that `path` refers to a collection (indicated by the fact it + * contains an odd numbers of segments). + */ function __PRIVATE_validateCollectionPath(t) { + if (DocumentKey.isDocumentKey(t)) throw new FirestoreError(w, `Invalid collection reference. Collection references must have an odd number of segments, but ${t} has ${t.length}.`); +} + +/** + * Returns true if it's a non-null object without a custom prototype + * (i.e. excludes Array, Date, etc.). + */ function __PRIVATE_isPlainObject(t) { + return "object" == typeof t && null !== t && (Object.getPrototypeOf(t) === Object.prototype || null === Object.getPrototypeOf(t)); +} + +/** Returns a string describing the type / value of the provided input. */ function __PRIVATE_valueDescription(t) { + if (void 0 === t) return "undefined"; + if (null === t) return "null"; + if ("string" == typeof t) return t.length > 20 && (t = `${t.substring(0, 20)}...`), + JSON.stringify(t); + if ("number" == typeof t || "boolean" == typeof t) return "" + t; + if ("object" == typeof t) { + if (t instanceof Array) return "an array"; + { + const e = + /** try to get the constructor name for an object. */ + function __PRIVATE_tryGetCustomObjectType(t) { + if (t.constructor) return t.constructor.name; + return null; + } + /** + * Casts `obj` to `T`, optionally unwrapping Compat types to expose the + * underlying instance. Throws if `obj` is not an instance of `T`. + * + * This cast is used in the Lite and Full SDK to verify instance types for + * arguments passed to the public API. + * @internal + */ (t); + return e ? `a custom ${e} object` : "an object"; + } + } + return "function" == typeof t ? "a function" : fail(12329, { + type: typeof t + }); +} + +function __PRIVATE_cast(t, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +e) { + if ("_delegate" in t && ( + // Unwrap Compat types + // eslint-disable-next-line @typescript-eslint/no-explicit-any + t = t._delegate), !(t instanceof e)) { + if (e.name === t.constructor.name) throw new FirestoreError(w, "Type does not match the expected instance. Did you pass a reference from a different Firestore SDK?"); + { + const r = __PRIVATE_valueDescription(t); + throw new FirestoreError(w, `Expected type '${e.name}', but it was: ${r}`); + } + } + return t; +} + +function __PRIVATE_validatePositiveNumber(t, e) { + if (e <= 0) throw new FirestoreError(w, `Function ${t}() requires a positive number, but it was: ${e}.`); +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Compares two `ExperimentalLongPollingOptions` objects for equality. + */ +/** + * Creates and returns a new `ExperimentalLongPollingOptions` with the same + * option values as the given instance. + */ +function __PRIVATE_cloneLongPollingOptions(t) { + const e = {}; + return void 0 !== t.timeoutSeconds && (e.timeoutSeconds = t.timeoutSeconds), e; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The value returned from the most recent invocation of + * `generateUniqueDebugId()`, or null if it has never been invoked. + */ let z = null; + +/** + * Generates and returns an initial value for `lastUniqueDebugId`. + * + * The returned value is randomly selected from a range of integers that are + * represented as 8 hexadecimal digits. This means that (within reason) any + * numbers generated by incrementing the returned number by 1 will also be + * represented by 8 hexadecimal digits. This leads to all "IDs" having the same + * length when converted to a hexadecimal string, making reading logs containing + * these IDs easier to follow. And since the return value is randomly selected + * it will help to differentiate between logs from different executions. + */ +/** + * Generates and returns a unique ID as a hexadecimal string. + * + * The returned ID is intended to be used in debug logging messages to help + * correlate log messages that may be spatially separated in the logs, but + * logically related. For example, a network connection could include the same + * "debug ID" string in all of its log messages to help trace a specific + * connection over time. + * + * @return the 10-character generated ID (e.g. "0xa1b2c3d4"). + */ +function __PRIVATE_generateUniqueDebugId() { + return null === z ? z = function __PRIVATE_generateInitialUniqueDebugId() { + return 268435456 + Math.round(2147483648 * Math.random()); + }() : z++, "0x" + z.toString(16); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns whether a variable is either undefined or null. + */ function __PRIVATE_isNullOrUndefined(t) { + return null == t; +} + +/** Returns whether the value represents -0. */ function __PRIVATE_isNegativeZero(t) { + // Detect if the value is -0.0. Based on polyfill from + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is + return 0 === t && 1 / t == -1 / 0; +} + +/** + * Returns whether a value is an integer and in the safe integer range + * @param value - The value to test for being an integer and in the safe range + */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const W = "RestConnection", K = { + BatchGetDocuments: "batchGet", + Commit: "commit", + RunQuery: "runQuery", + RunAggregationQuery: "runAggregationQuery" +}; + +/** + * Maps RPC names to the corresponding REST endpoint name. + * + * We use array notation to avoid mangling. + */ +/** + * Base class for all Rest-based connections to the backend (WebChannel and + * HTTP). + */ +class __PRIVATE_RestConnection { + get P() { + // Both `invokeRPC()` and `invokeStreamingRPC()` use their `path` arguments to determine + // where to run the query, and expect the `request` to NOT specify the "path". + return !1; + } + constructor(t) { + this.databaseInfo = t, this.databaseId = t.databaseId; + const e = t.ssl ? "https" : "http", r = encodeURIComponent(this.databaseId.projectId), n = encodeURIComponent(this.databaseId.database); + this.A = e + "://" + t.host, this.R = `projects/${r}/databases/${n}`, this.V = this.databaseId.database === L ? `project_id=${r}` : `project_id=${r}&database_id=${n}`; + } + I(t, e, r, n, i) { + const s = __PRIVATE_generateUniqueDebugId(), o = this.p(t, e.toUriEncodedString()); + __PRIVATE_logDebug(W, `Sending RPC '${t}' ${s}:`, o, r); + const a = { + "google-cloud-resource-prefix": this.R, + "x-goog-request-params": this.V + }; + this.F(a, n, i); + const {host: u} = new URL(o), _ = c(u); + return this.v(t, o, a, r, _).then((e => (__PRIVATE_logDebug(W, `Received RPC '${t}' ${s}: `, e), + e)), (e => { + throw __PRIVATE_logWarn(W, `RPC '${t}' ${s} failed with error: `, e, "url: ", o, "request:", r), + e; + })); + } + D(t, e, r, n, i, s) { + // The REST API automatically aggregates all of the streamed results, so we + // can just use the normal invoke() method. + return this.I(t, e, r, n, i); + } + /** + * Modifies the headers for a request, adding any authorization token if + * present and any additional headers for the request. + */ F(t, e, r) { + t["X-Goog-Api-Client"] = + // SDK_VERSION is updated to different value at runtime depending on the entry point, + // so we need to get its value when we need it in a function. + function __PRIVATE_getGoogApiClientValue() { + return "gl-js/ fire/" + V; + }(), + // Content-Type: text/plain will avoid preflight requests which might + // mess with CORS and redirects by proxies. If we add custom headers + // we will need to change this code to potentially use the $httpOverwrite + // parameter supported by ESF to avoid triggering preflight requests. + t["Content-Type"] = "text/plain", this.databaseInfo.appId && (t["X-Firebase-GMPID"] = this.databaseInfo.appId), + e && e.headers.forEach(((e, r) => t[r] = e)), r && r.headers.forEach(((e, r) => t[r] = e)); + } + p(t, e) { + const r = K[t]; + return `${this.A}/v1/${e}:${r}`; + } + /** + * Closes and cleans up any resources associated with the connection. This + * implementation is a no-op because there are no resources associated + * with the RestConnection that need to be cleaned up. + */ terminate() { + // No-op + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Error Codes describing the different ways GRPC can fail. These are copied + * directly from GRPC's sources here: + * + * https://github.com/grpc/grpc/blob/bceec94ea4fc5f0085d81235d8e1c06798dc341a/include/grpc%2B%2B/impl/codegen/status_code_enum.h + * + * Important! The names of these identifiers matter because the string forms + * are used for reverse lookups from the webchannel stream. Do NOT change the + * names of these identifiers or change this into a const enum. + */ var G, J; + +/** + * Converts an HTTP Status Code to the equivalent error code. + * + * @param status - An HTTP Status Code, like 200, 404, 503, etc. + * @returns The equivalent Code. Unknown status codes are mapped to + * Code.UNKNOWN. + */ +function __PRIVATE_mapCodeFromHttpStatus(t) { + if (void 0 === t) return __PRIVATE_logError("RPC_ERROR", "HTTP error has no status"), + g; + // The canonical error codes for Google APIs [1] specify mapping onto HTTP + // status codes but the mapping is not bijective. In each case of ambiguity + // this function chooses a primary error. + + // [1] + // https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto + switch (t) { + case 200: + // OK + return p; + + case 400: + // Bad Request + return N; + + // Other possibilities based on the forward mapping + // return Code.INVALID_ARGUMENT; + // return Code.OUT_OF_RANGE; + case 401: + // Unauthorized + return S; + + case 403: + // Forbidden + return b; + + case 404: + // Not Found + return v; + + case 409: + // Conflict + return O; + + // Other possibilities: + // return Code.ALREADY_EXISTS; + case 416: + // Range Not Satisfiable + return q; + + case 429: + // Too Many Requests + return C; + + case 499: + // Client Closed Request + return y; + + case 500: + // Internal Server Error + return g; + + // Other possibilities: + // return Code.INTERNAL; + // return Code.DATA_LOSS; + case 501: + // Unimplemented + return B; + + case 503: + // Service Unavailable + return Q; + + case 504: + // Gateway Timeout + return F; + + default: + return t >= 200 && t < 300 ? p : t >= 400 && t < 500 ? N : t >= 500 && t < 600 ? $ : g; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A Rest-based connection that relies on the native HTTP stack + * (e.g. `fetch` or a polyfill). + */ (J = G || (G = {}))[J.OK = 0] = "OK", J[J.CANCELLED = 1] = "CANCELLED", J[J.UNKNOWN = 2] = "UNKNOWN", +J[J.INVALID_ARGUMENT = 3] = "INVALID_ARGUMENT", J[J.DEADLINE_EXCEEDED = 4] = "DEADLINE_EXCEEDED", +J[J.NOT_FOUND = 5] = "NOT_FOUND", J[J.ALREADY_EXISTS = 6] = "ALREADY_EXISTS", J[J.PERMISSION_DENIED = 7] = "PERMISSION_DENIED", +J[J.UNAUTHENTICATED = 16] = "UNAUTHENTICATED", J[J.RESOURCE_EXHAUSTED = 8] = "RESOURCE_EXHAUSTED", +J[J.FAILED_PRECONDITION = 9] = "FAILED_PRECONDITION", J[J.ABORTED = 10] = "ABORTED", +J[J.OUT_OF_RANGE = 11] = "OUT_OF_RANGE", J[J.UNIMPLEMENTED = 12] = "UNIMPLEMENTED", +J[J.INTERNAL = 13] = "INTERNAL", J[J.UNAVAILABLE = 14] = "UNAVAILABLE", J[J.DATA_LOSS = 15] = "DATA_LOSS"; + +class __PRIVATE_FetchConnection extends __PRIVATE_RestConnection { + S(t, e) { + throw new Error("Not supported by FetchConnection"); + } + async v(t, e, r, n, i) { + const s = JSON.stringify(n); + let o; + try { + const t = { + method: "POST", + headers: r, + body: s + }; + i && (t.credentials = "include"), o = await fetch(e, t); + } catch (t) { + const e = t; + throw new FirestoreError(__PRIVATE_mapCodeFromHttpStatus(e.status), "Request failed with error: " + e.statusText); + } + if (!o.ok) { + let t = await o.json(); + Array.isArray(t) && (t = t[0]); + const e = t?.error?.message; + throw new FirestoreError(__PRIVATE_mapCodeFromHttpStatus(o.status), `Request failed with error: ${e ?? o.statusText}`); + } + return o.json(); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Initializes the HTTP connection for the REST API. */ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Concrete implementation of the Aggregate type. + */ +class __PRIVATE_AggregateImpl { + constructor(t, e, r) { + this.alias = t, this.aggregateType = e, this.fieldPath = r; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_objectSize(t) { + let e = 0; + for (const r in t) Object.prototype.hasOwnProperty.call(t, r) && e++; + return e; +} + +function forEach(t, e) { + for (const r in t) Object.prototype.hasOwnProperty.call(t, r) && e(r, t[r]); +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An error encountered while decoding base64 string. + */ +class __PRIVATE_Base64DecodeError extends Error { + constructor() { + super(...arguments), this.name = "Base64DecodeError"; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// WebSafe uses a different URL-encoding safe alphabet that doesn't match +// the encoding used on the backend. +const H = !1; + +/** Converts a Base64 encoded string to a binary string. */ function __PRIVATE_decodeBase64(t) { + try { + return String.fromCharCode.apply(null, + // We use `decodeStringToByteArray()` instead of `decodeString()` since + // `decodeString()` returns Unicode strings, which doesn't match the values + // returned by `atob()`'s Latin1 representation. + l.decodeStringToByteArray(t, H)); + } catch (t) { + throw t instanceof h ? new __PRIVATE_Base64DecodeError("Invalid base64 string: " + t) : t; + } +} + +/** Converts a binary string to a Base64 encoded string. */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Immutable class that represents a "proto" byte string. + * + * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when + * sent on the wire. This class abstracts away this differentiation by holding + * the proto byte string in a common class that must be converted into a string + * before being sent as a proto. + * @internal + */ +class ByteString { + constructor(t) { + this.binaryString = t; + } + static fromBase64String(t) { + const e = __PRIVATE_decodeBase64(t); + return new ByteString(e); + } + static fromUint8Array(t) { + // TODO(indexing); Remove the copy of the byte string here as this method + // is frequently called during indexing. + const e = + /** + * Helper function to convert an Uint8array to a binary string. + */ + function __PRIVATE_binaryStringFromUint8Array(t) { + let e = ""; + for (let r = 0; r < t.length; ++r) e += String.fromCharCode(t[r]); + return e; + } + /** + * Helper function to convert a binary string to an Uint8Array. + */ (t); + return new ByteString(e); + } + [Symbol.iterator]() { + let t = 0; + return { + next: () => t < this.binaryString.length ? { + value: this.binaryString.charCodeAt(t++), + done: !1 + } : { + value: void 0, + done: !0 + } + }; + } + toBase64() { + return function __PRIVATE_encodeBase64(t) { + const e = []; + for (let r = 0; r < t.length; r++) e[r] = t.charCodeAt(r); + return l.encodeByteArray(e, H); + }(this.binaryString); + } + toUint8Array() { + return function __PRIVATE_uint8ArrayFromBinaryString(t) { + const e = new Uint8Array(t.length); + for (let r = 0; r < t.length; r++) e[r] = t.charCodeAt(r); + return e; + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + // A RegExp matching ISO 8601 UTC timestamps with optional fraction. + (this.binaryString); + } + approximateByteSize() { + return 2 * this.binaryString.length; + } + compareTo(t) { + return __PRIVATE_primitiveComparator(this.binaryString, t.binaryString); + } + isEqual(t) { + return this.binaryString === t.binaryString; + } +} + +ByteString.EMPTY_BYTE_STRING = new ByteString(""); + +const Y = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/); + +/** + * Converts the possible Proto values for a timestamp value into a "seconds and + * nanos" representation. + */ function __PRIVATE_normalizeTimestamp(t) { + // The json interface (for the browser) will return an iso timestamp string, + // while the proto js library (for node) will return a + // google.protobuf.Timestamp instance. + if (__PRIVATE_hardAssert(!!t, 39018), "string" == typeof t) { + // The date string can have higher precision (nanos) than the Date class + // (millis), so we do some custom parsing here. + // Parse the nanos right out of the string. + let e = 0; + const r = Y.exec(t); + if (__PRIVATE_hardAssert(!!r, 46558, { + timestamp: t + }), r[1]) { + // Pad the fraction out to 9 digits (nanos). + let t = r[1]; + t = (t + "000000000").substr(0, 9), e = Number(t); + } + // Parse the date to get the seconds. + const n = new Date(t); + return { + seconds: Math.floor(n.getTime() / 1e3), + nanos: e + }; + } + return { + seconds: __PRIVATE_normalizeNumber(t.seconds), + nanos: __PRIVATE_normalizeNumber(t.nanos) + }; +} + +/** + * Converts the possible Proto types for numbers into a JavaScript number. + * Returns 0 if the value is not numeric. + */ function __PRIVATE_normalizeNumber(t) { + // TODO(bjornick): Handle int64 greater than 53 bits. + return "number" == typeof t ? t : "string" == typeof t ? Number(t) : 0; +} + +/** Converts the possible Proto types for Blobs into a ByteString. */ function __PRIVATE_normalizeByteString(t) { + return "string" == typeof t ? ByteString.fromBase64String(t) : ByteString.fromUint8Array(t); +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Helper function to define a JSON schema {@link Property}. + * @private + * @internal + */ function property(t, e) { + const r = { + typeString: t + }; + return e && (r.value = e), r; +} + +/** + * Validates the JSON object based on the provided schema, and narrows the type to the provided + * JSON schema. + * @private + * @internal + * + * @param json A JSON object to validate. + * @param scheme a {@link JsonSchema} that defines the properties to validate. + * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise. + */ function __PRIVATE_validateJSON(t, e) { + if (!__PRIVATE_isPlainObject(t)) throw new FirestoreError(w, "JSON must be an object"); + let r; + for (const n in e) if (e[n]) { + const i = e[n].typeString, s = "value" in e[n] ? { + value: e[n].value + } : void 0; + if (!(n in t)) { + r = `JSON missing required field: '${n}'`; + break; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const o = t[n]; + if (i && typeof o !== i) { + r = `JSON field '${n}' must be a ${i}.`; + break; + } + if (void 0 !== s && o !== s.value) { + r = `Expected '${n}' field to equal '${s.value}'`; + break; + } + } + if (r) throw new FirestoreError(w, r); + return !0; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// The earliest date supported by Firestore timestamps (0001-01-01T00:00:00Z). +const Z = -62135596800, X = 1e6; + +// Number of nanoseconds in a millisecond. +/** + * A `Timestamp` represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. + * + * It is encoded using the Proleptic Gregorian Calendar which extends the + * Gregorian calendar backwards to year one. It is encoded assuming all minutes + * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59.999999999Z. + * + * For examples and further specifications, refer to the + * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. + */ +class Timestamp { + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns a new timestamp representing the current date. + */ + static now() { + return Timestamp.fromMillis(Date.now()); + } + /** + * Creates a new timestamp from the given date. + * + * @param date - The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the given + * date. + */ static fromDate(t) { + return Timestamp.fromMillis(t.getTime()); + } + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds - Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the given + * number of milliseconds. + */ static fromMillis(t) { + const e = Math.floor(t / 1e3), r = Math.floor((t - 1e3 * e) * X); + return new Timestamp(e, r); + } + /** + * Creates a new timestamp. + * + * @param seconds - The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds - The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + t, + /** + * The fractions of a second at nanosecond resolution.* + */ + e) { + if (this.seconds = t, this.nanoseconds = e, e < 0) throw new FirestoreError(w, "Timestamp nanoseconds out of range: " + e); + if (e >= 1e9) throw new FirestoreError(w, "Timestamp nanoseconds out of range: " + e); + if (t < Z) throw new FirestoreError(w, "Timestamp seconds out of range: " + t); + // This will break in the year 10,000. + if (t >= 253402300800) throw new FirestoreError(w, "Timestamp seconds out of range: " + t); + } + /** + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ toDate() { + return new Date(this.toMillis()); + } + /** + * Converts a `Timestamp` to a numeric timestamp (in milliseconds since + * epoch). This operation causes a loss of precision. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ toMillis() { + return 1e3 * this.seconds + this.nanoseconds / X; + } + _compareTo(t) { + return this.seconds === t.seconds ? __PRIVATE_primitiveComparator(this.nanoseconds, t.nanoseconds) : __PRIVATE_primitiveComparator(this.seconds, t.seconds); + } + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other - The `Timestamp` to compare against. + * @returns true if this `Timestamp` is equal to the provided one. + */ isEqual(t) { + return t.seconds === this.seconds && t.nanoseconds === this.nanoseconds; + } + /** Returns a textual representation of this `Timestamp`. */ toString() { + return "Timestamp(seconds=" + this.seconds + ", nanoseconds=" + this.nanoseconds + ")"; + } + /** + * Returns a JSON-serializable representation of this `Timestamp`. + */ toJSON() { + return { + type: Timestamp._jsonSchemaVersion, + seconds: this.seconds, + nanoseconds: this.nanoseconds + }; + } + /** + * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}. + */ static fromJSON(t) { + if (__PRIVATE_validateJSON(t, Timestamp._jsonSchema)) return new Timestamp(t.seconds, t.nanoseconds); + } + /** + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. + */ valueOf() { + // This method returns a string of the form . where + // is translated to have a non-negative value and both + // and are left-padded with zeroes to be a consistent length. + // Strings with this format then have a lexicographical ordering that matches + // the expected ordering. The translation is done to avoid having + // a leading negative sign (i.e. a leading '-' character) in its string + // representation, which would affect its lexicographical ordering. + const t = this.seconds - Z; + // Note: Up to 12 decimal digits are required to represent all valid + // 'seconds' values. + return String(t).padStart(12, "0") + "." + String(this.nanoseconds).padStart(9, "0"); + } +} + +Timestamp._jsonSchemaVersion = "firestore/timestamp/1.0", Timestamp._jsonSchema = { + type: property("string", Timestamp._jsonSchemaVersion), + seconds: property("number"), + nanoseconds: property("number") +}; + +function __PRIVATE_isServerTimestamp(t) { + const e = (t?.mapValue?.fields || {}).__type__?.stringValue; + return "server_timestamp" === e; +} + +/** + * Returns the value of the field before this ServerTimestamp was set. + * + * Preserving the previous values allows the user to display the last resoled + * value until the backend responds with the timestamp. + */ function __PRIVATE_getPreviousValue(t) { + const e = t.mapValue.fields.__previous_value__; + return __PRIVATE_isServerTimestamp(e) ? __PRIVATE_getPreviousValue(e) : e; +} + +/** + * Returns the local time at which this timestamp was first set. + */ function __PRIVATE_getLocalWriteTime(t) { + const e = __PRIVATE_normalizeTimestamp(t.mapValue.fields.__local_write_time__.timestampValue); + return new Timestamp(e.seconds, e.nanos); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const tt = "__type__", et = "__max__", rt = { + fields: { + __type__: { + stringValue: et + } + } +}, nt = "__vector__", it = "value"; + +/** Extracts the backend's type order for the provided value. */ +function __PRIVATE_typeOrder(t) { + return "nullValue" in t ? 0 /* TypeOrder.NullValue */ : "booleanValue" in t ? 1 /* TypeOrder.BooleanValue */ : "integerValue" in t || "doubleValue" in t ? 2 /* TypeOrder.NumberValue */ : "timestampValue" in t ? 3 /* TypeOrder.TimestampValue */ : "stringValue" in t ? 5 /* TypeOrder.StringValue */ : "bytesValue" in t ? 6 /* TypeOrder.BlobValue */ : "referenceValue" in t ? 7 /* TypeOrder.RefValue */ : "geoPointValue" in t ? 8 /* TypeOrder.GeoPointValue */ : "arrayValue" in t ? 9 /* TypeOrder.ArrayValue */ : "mapValue" in t ? __PRIVATE_isServerTimestamp(t) ? 4 /* TypeOrder.ServerTimestampValue */ : + /** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ + function __PRIVATE_isMaxValue(t) { + return (((t.mapValue || {}).fields || {}).__type__ || {}).stringValue === et; + } + /** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Represents a bound of a query. + * + * The bound is specified with the given components representing a position and + * whether it's just before or just after the position (relative to whatever the + * query order is). + * + * The position represents a logical index position for a query. It's a prefix + * of values for the (potentially implicit) order by clauses of a query. + * + * Bound provides a function to determine whether a document comes before or + * after a bound. This is influenced by whether the position is just before or + * just after the provided values. + */ (t) ? 9007199254740991 /* TypeOrder.MaxValue */ : + /** Returns true if `value` is a VetorValue. */ + function __PRIVATE_isVectorValue(t) { + const e = (t?.mapValue?.fields || {})[tt]?.stringValue; + return e === nt; + } + /** Creates a deep copy of `source`. */ (t) ? 10 /* TypeOrder.VectorValue */ : 11 /* TypeOrder.ObjectValue */ : fail(28295, { + value: t + }); +} + +/** Tests `left` and `right` for equality based on the backend semantics. */ function __PRIVATE_valueEquals(t, e) { + if (t === e) return !0; + const r = __PRIVATE_typeOrder(t); + if (r !== __PRIVATE_typeOrder(e)) return !1; + switch (r) { + case 0 /* TypeOrder.NullValue */ : + case 9007199254740991 /* TypeOrder.MaxValue */ : + return !0; + + case 1 /* TypeOrder.BooleanValue */ : + return t.booleanValue === e.booleanValue; + + case 4 /* TypeOrder.ServerTimestampValue */ : + return __PRIVATE_getLocalWriteTime(t).isEqual(__PRIVATE_getLocalWriteTime(e)); + + case 3 /* TypeOrder.TimestampValue */ : + return function __PRIVATE_timestampEquals(t, e) { + if ("string" == typeof t.timestampValue && "string" == typeof e.timestampValue && t.timestampValue.length === e.timestampValue.length) + // Use string equality for ISO 8601 timestamps + return t.timestampValue === e.timestampValue; + const r = __PRIVATE_normalizeTimestamp(t.timestampValue), n = __PRIVATE_normalizeTimestamp(e.timestampValue); + return r.seconds === n.seconds && r.nanos === n.nanos; + }(t, e); + + case 5 /* TypeOrder.StringValue */ : + return t.stringValue === e.stringValue; + + case 6 /* TypeOrder.BlobValue */ : + return function __PRIVATE_blobEquals(t, e) { + return __PRIVATE_normalizeByteString(t.bytesValue).isEqual(__PRIVATE_normalizeByteString(e.bytesValue)); + }(t, e); + + case 7 /* TypeOrder.RefValue */ : + return t.referenceValue === e.referenceValue; + + case 8 /* TypeOrder.GeoPointValue */ : + return function __PRIVATE_geoPointEquals(t, e) { + return __PRIVATE_normalizeNumber(t.geoPointValue.latitude) === __PRIVATE_normalizeNumber(e.geoPointValue.latitude) && __PRIVATE_normalizeNumber(t.geoPointValue.longitude) === __PRIVATE_normalizeNumber(e.geoPointValue.longitude); + }(t, e); + + case 2 /* TypeOrder.NumberValue */ : + return function __PRIVATE_numberEquals(t, e) { + if ("integerValue" in t && "integerValue" in e) return __PRIVATE_normalizeNumber(t.integerValue) === __PRIVATE_normalizeNumber(e.integerValue); + if ("doubleValue" in t && "doubleValue" in e) { + const r = __PRIVATE_normalizeNumber(t.doubleValue), n = __PRIVATE_normalizeNumber(e.doubleValue); + return r === n ? __PRIVATE_isNegativeZero(r) === __PRIVATE_isNegativeZero(n) : isNaN(r) && isNaN(n); + } + return !1; + }(t, e); + + case 9 /* TypeOrder.ArrayValue */ : + return __PRIVATE_arrayEquals(t.arrayValue.values || [], e.arrayValue.values || [], __PRIVATE_valueEquals); + + case 10 /* TypeOrder.VectorValue */ : + case 11 /* TypeOrder.ObjectValue */ : + return function __PRIVATE_objectEquals(t, e) { + const r = t.mapValue.fields || {}, n = e.mapValue.fields || {}; + if (__PRIVATE_objectSize(r) !== __PRIVATE_objectSize(n)) return !1; + for (const t in r) if (r.hasOwnProperty(t) && (void 0 === n[t] || !__PRIVATE_valueEquals(r[t], n[t]))) return !1; + return !0; + } + /** Returns true if the ArrayValue contains the specified element. */ (t, e); + + default: + return fail(52216, { + left: t + }); + } +} + +function __PRIVATE_arrayValueContains(t, e) { + return void 0 !== (t.values || []).find((t => __PRIVATE_valueEquals(t, e))); +} + +function __PRIVATE_valueCompare(t, e) { + if (t === e) return 0; + const r = __PRIVATE_typeOrder(t), n = __PRIVATE_typeOrder(e); + if (r !== n) return __PRIVATE_primitiveComparator(r, n); + switch (r) { + case 0 /* TypeOrder.NullValue */ : + case 9007199254740991 /* TypeOrder.MaxValue */ : + return 0; + + case 1 /* TypeOrder.BooleanValue */ : + return __PRIVATE_primitiveComparator(t.booleanValue, e.booleanValue); + + case 2 /* TypeOrder.NumberValue */ : + return function __PRIVATE_compareNumbers(t, e) { + const r = __PRIVATE_normalizeNumber(t.integerValue || t.doubleValue), n = __PRIVATE_normalizeNumber(e.integerValue || e.doubleValue); + return r < n ? -1 : r > n ? 1 : r === n ? 0 : + // one or both are NaN. + isNaN(r) ? isNaN(n) ? 0 : -1 : 1; + }(t, e); + + case 3 /* TypeOrder.TimestampValue */ : + return __PRIVATE_compareTimestamps(t.timestampValue, e.timestampValue); + + case 4 /* TypeOrder.ServerTimestampValue */ : + return __PRIVATE_compareTimestamps(__PRIVATE_getLocalWriteTime(t), __PRIVATE_getLocalWriteTime(e)); + + case 5 /* TypeOrder.StringValue */ : + return __PRIVATE_compareUtf8Strings(t.stringValue, e.stringValue); + + case 6 /* TypeOrder.BlobValue */ : + return function __PRIVATE_compareBlobs(t, e) { + const r = __PRIVATE_normalizeByteString(t), n = __PRIVATE_normalizeByteString(e); + return r.compareTo(n); + }(t.bytesValue, e.bytesValue); + + case 7 /* TypeOrder.RefValue */ : + return function __PRIVATE_compareReferences(t, e) { + const r = t.split("/"), n = e.split("/"); + for (let t = 0; t < r.length && t < n.length; t++) { + const e = __PRIVATE_primitiveComparator(r[t], n[t]); + if (0 !== e) return e; + } + return __PRIVATE_primitiveComparator(r.length, n.length); + }(t.referenceValue, e.referenceValue); + + case 8 /* TypeOrder.GeoPointValue */ : + return function __PRIVATE_compareGeoPoints(t, e) { + const r = __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(t.latitude), __PRIVATE_normalizeNumber(e.latitude)); + if (0 !== r) return r; + return __PRIVATE_primitiveComparator(__PRIVATE_normalizeNumber(t.longitude), __PRIVATE_normalizeNumber(e.longitude)); + }(t.geoPointValue, e.geoPointValue); + + case 9 /* TypeOrder.ArrayValue */ : + return __PRIVATE_compareArrays(t.arrayValue, e.arrayValue); + + case 10 /* TypeOrder.VectorValue */ : + return function __PRIVATE_compareVectors(t, e) { + const r = t.fields || {}, n = e.fields || {}, i = r[it]?.arrayValue, s = n[it]?.arrayValue, o = __PRIVATE_primitiveComparator(i?.values?.length || 0, s?.values?.length || 0); + if (0 !== o) return o; + return __PRIVATE_compareArrays(i, s); + }(t.mapValue, e.mapValue); + + case 11 /* TypeOrder.ObjectValue */ : + return function __PRIVATE_compareMaps(t, e) { + if (t === rt && e === rt) return 0; + if (t === rt) return 1; + if (e === rt) return -1; + const r = t.fields || {}, n = Object.keys(r), i = e.fields || {}, s = Object.keys(i); + // Even though MapValues are likely sorted correctly based on their insertion + // order (e.g. when received from the backend), local modifications can bring + // elements out of order. We need to re-sort the elements to ensure that + // canonical IDs are independent of insertion order. + n.sort(), s.sort(); + for (let t = 0; t < n.length && t < s.length; ++t) { + const e = __PRIVATE_compareUtf8Strings(n[t], s[t]); + if (0 !== e) return e; + const o = __PRIVATE_valueCompare(r[n[t]], i[s[t]]); + if (0 !== o) return o; + } + return __PRIVATE_primitiveComparator(n.length, s.length); + } + /** Returns a reference value for the provided database and key. */ (t.mapValue, e.mapValue); + + default: + throw fail(23264, { + C: r + }); + } +} + +function __PRIVATE_compareTimestamps(t, e) { + if ("string" == typeof t && "string" == typeof e && t.length === e.length) return __PRIVATE_primitiveComparator(t, e); + const r = __PRIVATE_normalizeTimestamp(t), n = __PRIVATE_normalizeTimestamp(e), i = __PRIVATE_primitiveComparator(r.seconds, n.seconds); + return 0 !== i ? i : __PRIVATE_primitiveComparator(r.nanos, n.nanos); +} + +function __PRIVATE_compareArrays(t, e) { + const r = t.values || [], n = e.values || []; + for (let t = 0; t < r.length && t < n.length; ++t) { + const e = __PRIVATE_valueCompare(r[t], n[t]); + if (e) return e; + } + return __PRIVATE_primitiveComparator(r.length, n.length); +} + +function __PRIVATE_refValue(t, e) { + return { + referenceValue: `projects/${t.projectId}/databases/${t.database}/documents/${e.path.canonicalString()}` + }; +} + +/** Returns true if `value` is an ArrayValue. */ function isArray(t) { + return !!t && "arrayValue" in t; +} + +/** Returns true if `value` is a NullValue. */ function __PRIVATE_isNullValue(t) { + return !!t && "nullValue" in t; +} + +/** Returns true if `value` is NaN. */ function __PRIVATE_isNanValue(t) { + return !!t && "doubleValue" in t && isNaN(Number(t.doubleValue)); +} + +/** Returns true if `value` is a MapValue. */ function __PRIVATE_isMapValue(t) { + return !!t && "mapValue" in t; +} + +function __PRIVATE_deepClone(t) { + if (t.geoPointValue) return { + geoPointValue: { + ...t.geoPointValue + } + }; + if (t.timestampValue && "object" == typeof t.timestampValue) return { + timestampValue: { + ...t.timestampValue + } + }; + if (t.mapValue) { + const e = { + mapValue: { + fields: {} + } + }; + return forEach(t.mapValue.fields, ((t, r) => e.mapValue.fields[t] = __PRIVATE_deepClone(r))), + e; + } + if (t.arrayValue) { + const e = { + arrayValue: { + values: [] + } + }; + for (let r = 0; r < (t.arrayValue.values || []).length; ++r) e.arrayValue.values[r] = __PRIVATE_deepClone(t.arrayValue.values[r]); + return e; + } + return { + ...t + }; +} + +class Bound { + constructor(t, e) { + this.position = t, this.inclusive = e; + } +} + +function __PRIVATE_boundEquals(t, e) { + if (null === t) return null === e; + if (null === e) return !1; + if (t.inclusive !== e.inclusive || t.position.length !== e.position.length) return !1; + for (let r = 0; r < t.position.length; r++) { + if (!__PRIVATE_valueEquals(t.position[r], e.position[r])) return !1; + } + return !0; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ class Filter {} + +class FieldFilter extends Filter { + constructor(t, e, r) { + super(), this.field = t, this.op = e, this.value = r; + } + /** + * Creates a filter based on the provided arguments. + */ static create(t, e, r) { + return t.isKeyField() ? "in" /* Operator.IN */ === e || "not-in" /* Operator.NOT_IN */ === e ? this.createKeyFieldInFilter(t, e, r) : new __PRIVATE_KeyFieldFilter(t, e, r) : "array-contains" /* Operator.ARRAY_CONTAINS */ === e ? new __PRIVATE_ArrayContainsFilter(t, r) : "in" /* Operator.IN */ === e ? new __PRIVATE_InFilter(t, r) : "not-in" /* Operator.NOT_IN */ === e ? new __PRIVATE_NotInFilter(t, r) : "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === e ? new __PRIVATE_ArrayContainsAnyFilter(t, r) : new FieldFilter(t, e, r); + } + static createKeyFieldInFilter(t, e, r) { + return "in" /* Operator.IN */ === e ? new __PRIVATE_KeyFieldInFilter(t, r) : new __PRIVATE_KeyFieldNotInFilter(t, r); + } + matches(t) { + const e = t.data.field(this.field); + // Types do not have to match in NOT_EQUAL filters. + return "!=" /* Operator.NOT_EQUAL */ === this.op ? null !== e && void 0 === e.nullValue && this.matchesComparison(__PRIVATE_valueCompare(e, this.value)) : null !== e && __PRIVATE_typeOrder(this.value) === __PRIVATE_typeOrder(e) && this.matchesComparison(__PRIVATE_valueCompare(e, this.value)); + // Only compare types with matching backend order (such as double and int). + } + matchesComparison(t) { + switch (this.op) { + case "<" /* Operator.LESS_THAN */ : + return t < 0; + + case "<=" /* Operator.LESS_THAN_OR_EQUAL */ : + return t <= 0; + + case "==" /* Operator.EQUAL */ : + return 0 === t; + + case "!=" /* Operator.NOT_EQUAL */ : + return 0 !== t; + + case ">" /* Operator.GREATER_THAN */ : + return t > 0; + + case ">=" /* Operator.GREATER_THAN_OR_EQUAL */ : + return t >= 0; + + default: + return fail(47266, { + operator: this.op + }); + } + } + isInequality() { + return [ "<" /* Operator.LESS_THAN */ , "<=" /* Operator.LESS_THAN_OR_EQUAL */ , ">" /* Operator.GREATER_THAN */ , ">=" /* Operator.GREATER_THAN_OR_EQUAL */ , "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ].indexOf(this.op) >= 0; + } + getFlattenedFilters() { + return [ this ]; + } + getFilters() { + return [ this ]; + } +} + +class CompositeFilter extends Filter { + constructor(t, e) { + super(), this.filters = t, this.op = e, this.N = null; + } + /** + * Creates a filter based on the provided arguments. + */ static create(t, e) { + return new CompositeFilter(t, e); + } + matches(t) { + return function __PRIVATE_compositeFilterIsConjunction(t) { + return "and" /* CompositeOperator.AND */ === t.op; + }(this) ? void 0 === this.filters.find((e => !e.matches(t))) : void 0 !== this.filters.find((e => e.matches(t))); + } + getFlattenedFilters() { + return null !== this.N || (this.N = this.filters.reduce(((t, e) => t.concat(e.getFlattenedFilters())), [])), + this.N; + } + // Returns a mutable copy of `this.filters` + getFilters() { + return Object.assign([], this.filters); + } +} + +function __PRIVATE_filterEquals(t, e) { + return t instanceof FieldFilter ? function __PRIVATE_fieldFilterEquals(t, e) { + return e instanceof FieldFilter && t.op === e.op && t.field.isEqual(e.field) && __PRIVATE_valueEquals(t.value, e.value); + }(t, e) : t instanceof CompositeFilter ? function __PRIVATE_compositeFilterEquals(t, e) { + if (e instanceof CompositeFilter && t.op === e.op && t.filters.length === e.filters.length) { + return t.filters.reduce(((t, r, n) => t && __PRIVATE_filterEquals(r, e.filters[n])), !0); + } + return !1; + } + /** Filter that matches on key fields (i.e. '__name__'). */ (t, e) : void fail(19439); +} + +class __PRIVATE_KeyFieldFilter extends FieldFilter { + constructor(t, e, r) { + super(t, e, r), this.key = DocumentKey.fromName(r.referenceValue); + } + matches(t) { + const e = DocumentKey.comparator(t.key, this.key); + return this.matchesComparison(e); + } +} + +/** Filter that matches on key fields within an array. */ class __PRIVATE_KeyFieldInFilter extends FieldFilter { + constructor(t, e) { + super(t, "in" /* Operator.IN */ , e), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue("in" /* Operator.IN */ , e); + } + matches(t) { + return this.keys.some((e => e.isEqual(t.key))); + } +} + +/** Filter that matches on key fields not present within an array. */ class __PRIVATE_KeyFieldNotInFilter extends FieldFilter { + constructor(t, e) { + super(t, "not-in" /* Operator.NOT_IN */ , e), this.keys = __PRIVATE_extractDocumentKeysFromArrayValue("not-in" /* Operator.NOT_IN */ , e); + } + matches(t) { + return !this.keys.some((e => e.isEqual(t.key))); + } +} + +function __PRIVATE_extractDocumentKeysFromArrayValue(t, e) { + return (e.arrayValue?.values || []).map((t => DocumentKey.fromName(t.referenceValue))); +} + +/** A Filter that implements the array-contains operator. */ class __PRIVATE_ArrayContainsFilter extends FieldFilter { + constructor(t, e) { + super(t, "array-contains" /* Operator.ARRAY_CONTAINS */ , e); + } + matches(t) { + const e = t.data.field(this.field); + return isArray(e) && __PRIVATE_arrayValueContains(e.arrayValue, this.value); + } +} + +/** A Filter that implements the IN operator. */ class __PRIVATE_InFilter extends FieldFilter { + constructor(t, e) { + super(t, "in" /* Operator.IN */ , e); + } + matches(t) { + const e = t.data.field(this.field); + return null !== e && __PRIVATE_arrayValueContains(this.value.arrayValue, e); + } +} + +/** A Filter that implements the not-in operator. */ class __PRIVATE_NotInFilter extends FieldFilter { + constructor(t, e) { + super(t, "not-in" /* Operator.NOT_IN */ , e); + } + matches(t) { + if (__PRIVATE_arrayValueContains(this.value.arrayValue, { + nullValue: "NULL_VALUE" + })) return !1; + const e = t.data.field(this.field); + return null !== e && void 0 === e.nullValue && !__PRIVATE_arrayValueContains(this.value.arrayValue, e); + } +} + +/** A Filter that implements the array-contains-any operator. */ class __PRIVATE_ArrayContainsAnyFilter extends FieldFilter { + constructor(t, e) { + super(t, "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , e); + } + matches(t) { + const e = t.data.field(this.field); + return !(!isArray(e) || !e.arrayValue.values) && e.arrayValue.values.some((t => __PRIVATE_arrayValueContains(this.value.arrayValue, t))); + } +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An ordering on a field, in some Direction. Direction defaults to ASCENDING. + */ class OrderBy { + constructor(t, e = "asc" /* Direction.ASCENDING */) { + this.field = t, this.dir = e; + } +} + +function __PRIVATE_orderByEquals(t, e) { + return t.dir === e.dir && t.field.isEqual(e.field); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A version of a document in Firestore. This corresponds to the version + * timestamp, such as update_time or read_time. + */ class SnapshotVersion { + static fromTimestamp(t) { + return new SnapshotVersion(t); + } + static min() { + return new SnapshotVersion(new Timestamp(0, 0)); + } + static max() { + return new SnapshotVersion(new Timestamp(253402300799, 999999999)); + } + constructor(t) { + this.timestamp = t; + } + compareTo(t) { + return this.timestamp._compareTo(t.timestamp); + } + isEqual(t) { + return this.timestamp.isEqual(t.timestamp); + } + /** Returns a number representation of the version for use in spec tests. */ toMicroseconds() { + // Convert to microseconds. + return 1e6 * this.timestamp.seconds + this.timestamp.nanoseconds / 1e3; + } + toString() { + return "SnapshotVersion(" + this.timestamp.toString() + ")"; + } + toTimestamp() { + return this.timestamp; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// An immutable sorted map implementation, based on a Left-leaning Red-Black +// tree. +class SortedMap { + constructor(t, e) { + this.comparator = t, this.root = e || LLRBNode.EMPTY; + } + // Returns a copy of the map, with the specified key/value added or replaced. + insert(t, e) { + return new SortedMap(this.comparator, this.root.insert(t, e, this.comparator).copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns a copy of the map, with the specified key removed. + remove(t) { + return new SortedMap(this.comparator, this.root.remove(t, this.comparator).copy(null, null, LLRBNode.BLACK, null, null)); + } + // Returns the value of the node with the given key, or null. + get(t) { + let e = this.root; + for (;!e.isEmpty(); ) { + const r = this.comparator(t, e.key); + if (0 === r) return e.value; + r < 0 ? e = e.left : r > 0 && (e = e.right); + } + return null; + } + // Returns the index of the element in this sorted map, or -1 if it doesn't + // exist. + indexOf(t) { + // Number of nodes that were pruned when descending right + let e = 0, r = this.root; + for (;!r.isEmpty(); ) { + const n = this.comparator(t, r.key); + if (0 === n) return e + r.left.size; + n < 0 ? r = r.left : ( + // Count all nodes left of the node plus the node itself + e += r.left.size + 1, r = r.right); + } + // Node not found + return -1; + } + isEmpty() { + return this.root.isEmpty(); + } + // Returns the total number of nodes in the map. + get size() { + return this.root.size; + } + // Returns the minimum key in the map. + minKey() { + return this.root.minKey(); + } + // Returns the maximum key in the map. + maxKey() { + return this.root.maxKey(); + } + // Traverses the map in key order and calls the specified action function + // for each key/value pair. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(t) { + return this.root.inorderTraversal(t); + } + forEach(t) { + this.inorderTraversal(((e, r) => (t(e, r), !1))); + } + toString() { + const t = []; + return this.inorderTraversal(((e, r) => (t.push(`${e}:${r}`), !1))), `{${t.join(", ")}}`; + } + // Traverses the map in reverse key order and calls the specified action + // function for each key/value pair. If action returns true, traversal is + // aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(t) { + return this.root.reverseTraversal(t); + } + // Returns an iterator over the SortedMap. + getIterator() { + return new SortedMapIterator(this.root, null, this.comparator, !1); + } + getIteratorFrom(t) { + return new SortedMapIterator(this.root, t, this.comparator, !1); + } + getReverseIterator() { + return new SortedMapIterator(this.root, null, this.comparator, !0); + } + getReverseIteratorFrom(t) { + return new SortedMapIterator(this.root, t, this.comparator, !0); + } +} + + // end SortedMap +// An iterator over an LLRBNode. +class SortedMapIterator { + constructor(t, e, r, n) { + this.isReverse = n, this.nodeStack = []; + let i = 1; + for (;!t.isEmpty(); ) if (i = e ? r(t.key, e) : 1, + // flip the comparison if we're going in reverse + e && n && (i *= -1), i < 0) + // This node is less than our start key. ignore it + t = this.isReverse ? t.left : t.right; else { + if (0 === i) { + // This node is exactly equal to our start key. Push it on the stack, + // but stop iterating; + this.nodeStack.push(t); + break; + } + // This node is greater than our start key, add it to the stack and move + // to the next one + this.nodeStack.push(t), t = this.isReverse ? t.right : t.left; + } + } + getNext() { + let t = this.nodeStack.pop(); + const e = { + key: t.key, + value: t.value + }; + if (this.isReverse) for (t = t.left; !t.isEmpty(); ) this.nodeStack.push(t), t = t.right; else for (t = t.right; !t.isEmpty(); ) this.nodeStack.push(t), + t = t.left; + return e; + } + hasNext() { + return this.nodeStack.length > 0; + } + peek() { + if (0 === this.nodeStack.length) return null; + const t = this.nodeStack[this.nodeStack.length - 1]; + return { + key: t.key, + value: t.value + }; + } +} + + // end SortedMapIterator +// Represents a node in a Left-leaning Red-Black tree. +class LLRBNode { + constructor(t, e, r, n, i) { + this.key = t, this.value = e, this.color = null != r ? r : LLRBNode.RED, this.left = null != n ? n : LLRBNode.EMPTY, + this.right = null != i ? i : LLRBNode.EMPTY, this.size = this.left.size + 1 + this.right.size; + } + // Returns a copy of the current node, optionally replacing pieces of it. + copy(t, e, r, n, i) { + return new LLRBNode(null != t ? t : this.key, null != e ? e : this.value, null != r ? r : this.color, null != n ? n : this.left, null != i ? i : this.right); + } + isEmpty() { + return !1; + } + // Traverses the tree in key order and calls the specified action function + // for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + inorderTraversal(t) { + return this.left.inorderTraversal(t) || t(this.key, this.value) || this.right.inorderTraversal(t); + } + // Traverses the tree in reverse key order and calls the specified action + // function for each node. If action returns true, traversal is aborted. + // Returns the first truthy value returned by action, or the last falsey + // value returned by action. + reverseTraversal(t) { + return this.right.reverseTraversal(t) || t(this.key, this.value) || this.left.reverseTraversal(t); + } + // Returns the minimum node in the tree. + min() { + return this.left.isEmpty() ? this : this.left.min(); + } + // Returns the maximum key in the tree. + minKey() { + return this.min().key; + } + // Returns the maximum key in the tree. + maxKey() { + return this.right.isEmpty() ? this.key : this.right.maxKey(); + } + // Returns new tree, with the key/value added. + insert(t, e, r) { + let n = this; + const i = r(t, n.key); + return n = i < 0 ? n.copy(null, null, null, n.left.insert(t, e, r), null) : 0 === i ? n.copy(null, e, null, null, null) : n.copy(null, null, null, null, n.right.insert(t, e, r)), + n.fixUp(); + } + removeMin() { + if (this.left.isEmpty()) return LLRBNode.EMPTY; + let t = this; + return t.left.isRed() || t.left.left.isRed() || (t = t.moveRedLeft()), t = t.copy(null, null, null, t.left.removeMin(), null), + t.fixUp(); + } + // Returns new tree, with the specified item removed. + remove(t, e) { + let r, n = this; + if (e(t, n.key) < 0) n.left.isEmpty() || n.left.isRed() || n.left.left.isRed() || (n = n.moveRedLeft()), + n = n.copy(null, null, null, n.left.remove(t, e), null); else { + if (n.left.isRed() && (n = n.rotateRight()), n.right.isEmpty() || n.right.isRed() || n.right.left.isRed() || (n = n.moveRedRight()), + 0 === e(t, n.key)) { + if (n.right.isEmpty()) return LLRBNode.EMPTY; + r = n.right.min(), n = n.copy(r.key, r.value, null, null, n.right.removeMin()); + } + n = n.copy(null, null, null, null, n.right.remove(t, e)); + } + return n.fixUp(); + } + isRed() { + return this.color; + } + // Returns new tree after performing any needed rotations. + fixUp() { + let t = this; + return t.right.isRed() && !t.left.isRed() && (t = t.rotateLeft()), t.left.isRed() && t.left.left.isRed() && (t = t.rotateRight()), + t.left.isRed() && t.right.isRed() && (t = t.colorFlip()), t; + } + moveRedLeft() { + let t = this.colorFlip(); + return t.right.left.isRed() && (t = t.copy(null, null, null, null, t.right.rotateRight()), + t = t.rotateLeft(), t = t.colorFlip()), t; + } + moveRedRight() { + let t = this.colorFlip(); + return t.left.left.isRed() && (t = t.rotateRight(), t = t.colorFlip()), t; + } + rotateLeft() { + const t = this.copy(null, null, LLRBNode.RED, null, this.right.left); + return this.right.copy(null, null, this.color, t, null); + } + rotateRight() { + const t = this.copy(null, null, LLRBNode.RED, this.left.right, null); + return this.left.copy(null, null, this.color, null, t); + } + colorFlip() { + const t = this.left.copy(null, null, !this.left.color, null, null), e = this.right.copy(null, null, !this.right.color, null, null); + return this.copy(null, null, !this.color, t, e); + } + // For testing. + checkMaxDepth() { + const t = this.check(); + return Math.pow(2, t) <= this.size + 1; + } + // In a balanced RB tree, the black-depth (number of black nodes) from root to + // leaves is equal on both sides. This function verifies that or asserts. + check() { + if (this.isRed() && this.left.isRed()) throw fail(43730, { + key: this.key, + value: this.value + }); + if (this.right.isRed()) throw fail(14113, { + key: this.key, + value: this.value + }); + const t = this.left.check(); + if (t !== this.right.check()) throw fail(27949); + return t + (this.isRed() ? 0 : 1); + } +} + + // end LLRBNode +// Empty node is shared between all LLRB trees. +// eslint-disable-next-line @typescript-eslint/no-explicit-any +LLRBNode.EMPTY = null, LLRBNode.RED = !0, LLRBNode.BLACK = !1; + +// end LLRBEmptyNode +LLRBNode.EMPTY = new +// Represents an empty node (a leaf node in the Red-Black Tree). +class LLRBEmptyNode { + constructor() { + this.size = 0; + } + get key() { + throw fail(57766); + } + get value() { + throw fail(16141); + } + get color() { + throw fail(16727); + } + get left() { + throw fail(29726); + } + get right() { + throw fail(36894); + } + // Returns a copy of the current node. + copy(t, e, r, n, i) { + return this; + } + // Returns a copy of the tree, with the specified key/value added. + insert(t, e, r) { + return new LLRBNode(t, e); + } + // Returns a copy of the tree, with the specified key removed. + remove(t, e) { + return this; + } + isEmpty() { + return !0; + } + inorderTraversal(t) { + return !1; + } + reverseTraversal(t) { + return !1; + } + minKey() { + return null; + } + maxKey() { + return null; + } + isRed() { + return !1; + } + // For testing. + checkMaxDepth() { + return !0; + } + check() { + return 0; + } +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * SortedSet is an immutable (copy-on-write) collection that holds elements + * in order specified by the provided comparator. + * + * NOTE: if provided comparator returns 0 for two elements, we consider them to + * be equal! + */ +class SortedSet { + constructor(t) { + this.comparator = t, this.data = new SortedMap(this.comparator); + } + has(t) { + return null !== this.data.get(t); + } + first() { + return this.data.minKey(); + } + last() { + return this.data.maxKey(); + } + get size() { + return this.data.size; + } + indexOf(t) { + return this.data.indexOf(t); + } + /** Iterates elements in order defined by "comparator" */ forEach(t) { + this.data.inorderTraversal(((e, r) => (t(e), !1))); + } + /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ forEachInRange(t, e) { + const r = this.data.getIteratorFrom(t[0]); + for (;r.hasNext(); ) { + const n = r.getNext(); + if (this.comparator(n.key, t[1]) >= 0) return; + e(n.key); + } + } + /** + * Iterates over `elem`s such that: start <= elem until false is returned. + */ forEachWhile(t, e) { + let r; + for (r = void 0 !== e ? this.data.getIteratorFrom(e) : this.data.getIterator(); r.hasNext(); ) { + if (!t(r.getNext().key)) return; + } + } + /** Finds the least element greater than or equal to `elem`. */ firstAfterOrEqual(t) { + const e = this.data.getIteratorFrom(t); + return e.hasNext() ? e.getNext().key : null; + } + getIterator() { + return new SortedSetIterator(this.data.getIterator()); + } + getIteratorFrom(t) { + return new SortedSetIterator(this.data.getIteratorFrom(t)); + } + /** Inserts or updates an element */ add(t) { + return this.copy(this.data.remove(t).insert(t, !0)); + } + /** Deletes an element */ delete(t) { + return this.has(t) ? this.copy(this.data.remove(t)) : this; + } + isEmpty() { + return this.data.isEmpty(); + } + unionWith(t) { + let e = this; + // Make sure `result` always refers to the larger one of the two sets. + return e.size < t.size && (e = t, t = this), t.forEach((t => { + e = e.add(t); + })), e; + } + isEqual(t) { + if (!(t instanceof SortedSet)) return !1; + if (this.size !== t.size) return !1; + const e = this.data.getIterator(), r = t.data.getIterator(); + for (;e.hasNext(); ) { + const t = e.getNext().key, n = r.getNext().key; + if (0 !== this.comparator(t, n)) return !1; + } + return !0; + } + toArray() { + const t = []; + return this.forEach((e => { + t.push(e); + })), t; + } + toString() { + const t = []; + return this.forEach((e => t.push(e))), "SortedSet(" + t.toString() + ")"; + } + copy(t) { + const e = new SortedSet(this.comparator); + return e.data = t, e; + } +} + +class SortedSetIterator { + constructor(t) { + this.iter = t; + } + getNext() { + return this.iter.getNext().key; + } + hasNext() { + return this.iter.hasNext(); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Provides a set of fields that can be used to partially patch a document. + * FieldMask is used in conjunction with ObjectValue. + * Examples: + * foo - Overwrites foo entirely with the provided value. If foo is not + * present in the companion ObjectValue, the field is deleted. + * foo.bar - Overwrites only the field bar of the object foo. + * If foo is not an object, foo is replaced with an object + * containing foo + */ class FieldMask { + constructor(t) { + this.fields = t, + // TODO(dimond): validation of FieldMask + // Sort the field mask to support `FieldMask.isEqual()` and assert below. + t.sort(FieldPath$1.comparator); + } + static empty() { + return new FieldMask([]); + } + /** + * Returns a new FieldMask object that is the result of adding all the given + * fields paths to this field mask. + */ unionWith(t) { + let e = new SortedSet(FieldPath$1.comparator); + for (const t of this.fields) e = e.add(t); + for (const r of t) e = e.add(r); + return new FieldMask(e.toArray()); + } + /** + * Verifies that `fieldPath` is included by at least one field in this field + * mask. + * + * This is an O(n) operation, where `n` is the size of the field mask. + */ covers(t) { + for (const e of this.fields) if (e.isPrefixOf(t)) return !0; + return !1; + } + isEqual(t) { + return __PRIVATE_arrayEquals(this.fields, t.fields, ((t, e) => t.isEqual(e))); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An ObjectValue represents a MapValue in the Firestore Proto and offers the + * ability to add and remove fields (via the ObjectValueBuilder). + */ class ObjectValue { + constructor(t) { + this.value = t; + } + static empty() { + return new ObjectValue({ + mapValue: {} + }); + } + /** + * Returns the value at the given path or null. + * + * @param path - the path to search + * @returns The value at the path or null if the path is not set. + */ field(t) { + if (t.isEmpty()) return this.value; + { + let e = this.value; + for (let r = 0; r < t.length - 1; ++r) if (e = (e.mapValue.fields || {})[t.get(r)], + !__PRIVATE_isMapValue(e)) return null; + return e = (e.mapValue.fields || {})[t.lastSegment()], e || null; + } + } + /** + * Sets the field to the provided value. + * + * @param path - The field path to set. + * @param value - The value to set. + */ set(t, e) { + this.getFieldsMap(t.popLast())[t.lastSegment()] = __PRIVATE_deepClone(e); + } + /** + * Sets the provided fields to the provided values. + * + * @param data - A map of fields to values (or null for deletes). + */ setAll(t) { + let e = FieldPath$1.emptyPath(), r = {}, n = []; + t.forEach(((t, i) => { + if (!e.isImmediateParentOf(i)) { + // Insert the accumulated changes at this parent location + const t = this.getFieldsMap(e); + this.applyChanges(t, r, n), r = {}, n = [], e = i.popLast(); + } + t ? r[i.lastSegment()] = __PRIVATE_deepClone(t) : n.push(i.lastSegment()); + })); + const i = this.getFieldsMap(e); + this.applyChanges(i, r, n); + } + /** + * Removes the field at the specified path. If there is no field at the + * specified path, nothing is changed. + * + * @param path - The field path to remove. + */ delete(t) { + const e = this.field(t.popLast()); + __PRIVATE_isMapValue(e) && e.mapValue.fields && delete e.mapValue.fields[t.lastSegment()]; + } + isEqual(t) { + return __PRIVATE_valueEquals(this.value, t.value); + } + /** + * Returns the map that contains the leaf element of `path`. If the parent + * entry does not yet exist, or if it is not a map, a new map will be created. + */ getFieldsMap(t) { + let e = this.value; + e.mapValue.fields || (e.mapValue = { + fields: {} + }); + for (let r = 0; r < t.length; ++r) { + let n = e.mapValue.fields[t.get(r)]; + __PRIVATE_isMapValue(n) && n.mapValue.fields || (n = { + mapValue: { + fields: {} + } + }, e.mapValue.fields[t.get(r)] = n), e = n; + } + return e.mapValue.fields; + } + /** + * Modifies `fieldsMap` by adding, replacing or deleting the specified + * entries. + */ applyChanges(t, e, r) { + forEach(e, ((e, r) => t[e] = r)); + for (const e of r) delete t[e]; + } + clone() { + return new ObjectValue(__PRIVATE_deepClone(this.value)); + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a document in Firestore with a key, version, data and whether it + * has local mutations applied to it. + * + * Documents can transition between states via `convertToFoundDocument()`, + * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does + * not transition to one of these states even after all mutations have been + * applied, `isValidDocument()` returns false and the document should be removed + * from all views. + */ class MutableDocument { + constructor(t, e, r, n, i, s, o) { + this.key = t, this.documentType = e, this.version = r, this.readTime = n, this.createTime = i, + this.data = s, this.documentState = o; + } + /** + * Creates a document with no known version or data, but which can serve as + * base document for mutations. + */ static newInvalidDocument(t) { + return new MutableDocument(t, 0 /* DocumentType.INVALID */ , + /* version */ SnapshotVersion.min(), + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist with the given data at the + * given version. + */ static newFoundDocument(t, e, r, n) { + return new MutableDocument(t, 1 /* DocumentType.FOUND_DOCUMENT */ , + /* version */ e, + /* readTime */ SnapshotVersion.min(), + /* createTime */ r, n, 0 /* DocumentState.SYNCED */); + } + /** Creates a new document that is known to not exist at the given version. */ static newNoDocument(t, e) { + return new MutableDocument(t, 2 /* DocumentType.NO_DOCUMENT */ , + /* version */ e, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 0 /* DocumentState.SYNCED */); + } + /** + * Creates a new document that is known to exist at the given version but + * whose data is not known (e.g. a document that was updated without a known + * base document). + */ static newUnknownDocument(t, e) { + return new MutableDocument(t, 3 /* DocumentType.UNKNOWN_DOCUMENT */ , + /* version */ e, + /* readTime */ SnapshotVersion.min(), + /* createTime */ SnapshotVersion.min(), ObjectValue.empty(), 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */); + } + /** + * Changes the document type to indicate that it exists and that its version + * and data are known. + */ convertToFoundDocument(t, e) { + // If a document is switching state from being an invalid or deleted + // document to a valid (FOUND_DOCUMENT) document, either due to receiving an + // update from Watch or due to applying a local set mutation on top + // of a deleted document, our best guess about its createTime would be the + // version at which the document transitioned to a FOUND_DOCUMENT. + return !this.createTime.isEqual(SnapshotVersion.min()) || 2 /* DocumentType.NO_DOCUMENT */ !== this.documentType && 0 /* DocumentType.INVALID */ !== this.documentType || (this.createTime = t), + this.version = t, this.documentType = 1 /* DocumentType.FOUND_DOCUMENT */ , this.data = e, + this.documentState = 0 /* DocumentState.SYNCED */ , this; + } + /** + * Changes the document type to indicate that it doesn't exist at the given + * version. + */ convertToNoDocument(t) { + return this.version = t, this.documentType = 2 /* DocumentType.NO_DOCUMENT */ , + this.data = ObjectValue.empty(), this.documentState = 0 /* DocumentState.SYNCED */ , + this; + } + /** + * Changes the document type to indicate that it exists at a given version but + * that its data is not known (e.g. a document that was updated without a known + * base document). + */ convertToUnknownDocument(t) { + return this.version = t, this.documentType = 3 /* DocumentType.UNKNOWN_DOCUMENT */ , + this.data = ObjectValue.empty(), this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , + this; + } + setHasCommittedMutations() { + return this.documentState = 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ , this; + } + setHasLocalMutations() { + return this.documentState = 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ , this.version = SnapshotVersion.min(), + this; + } + setReadTime(t) { + return this.readTime = t, this; + } + get hasLocalMutations() { + return 1 /* DocumentState.HAS_LOCAL_MUTATIONS */ === this.documentState; + } + get hasCommittedMutations() { + return 2 /* DocumentState.HAS_COMMITTED_MUTATIONS */ === this.documentState; + } + get hasPendingWrites() { + return this.hasLocalMutations || this.hasCommittedMutations; + } + isValidDocument() { + return 0 /* DocumentType.INVALID */ !== this.documentType; + } + isFoundDocument() { + return 1 /* DocumentType.FOUND_DOCUMENT */ === this.documentType; + } + isNoDocument() { + return 2 /* DocumentType.NO_DOCUMENT */ === this.documentType; + } + isUnknownDocument() { + return 3 /* DocumentType.UNKNOWN_DOCUMENT */ === this.documentType; + } + isEqual(t) { + return t instanceof MutableDocument && this.key.isEqual(t.key) && this.version.isEqual(t.version) && this.documentType === t.documentType && this.documentState === t.documentState && this.data.isEqual(t.data); + } + mutableCopy() { + return new MutableDocument(this.key, this.documentType, this.version, this.readTime, this.createTime, this.data.clone(), this.documentState); + } + toString() { + return `Document(${this.key}, ${this.version}, ${JSON.stringify(this.data.value)}, {createTime: ${this.createTime}}), {documentType: ${this.documentType}}), {documentState: ${this.documentState}})`; + } +} + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Visible for testing +class __PRIVATE_TargetImpl { + constructor(t, e = null, r = [], n = [], i = null, s = null, o = null) { + this.path = t, this.collectionGroup = e, this.orderBy = r, this.filters = n, this.limit = i, + this.startAt = s, this.endAt = o, this.O = null; + } +} + +/** + * Initializes a Target with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + * + * NOTE: you should always construct `Target` from `Query.toTarget` instead of + * using this factory method, because `Query` provides an implicit `orderBy` + * property. + */ function __PRIVATE_newTarget(t, e = null, r = [], n = [], i = null, s = null, o = null) { + return new __PRIVATE_TargetImpl(t, e, r, n, i, s, o); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Query encapsulates all the query attributes we support in the SDK. It can + * be run against the LocalStore, as well as be converted to a `Target` to + * query the RemoteStore results. + * + * Visible for testing. + */ +class __PRIVATE_QueryImpl { + /** + * Initializes a Query with a path and optional additional query constraints. + * Path must currently be empty if this is a collection group query. + */ + constructor(t, e = null, r = [], n = [], i = null, s = "F" /* LimitType.First */ , o = null, a = null) { + this.path = t, this.collectionGroup = e, this.explicitOrderBy = r, this.filters = n, + this.limit = i, this.limitType = s, this.startAt = o, this.endAt = a, this.q = null, + // The corresponding `Target` of this `Query` instance, for use with + // non-aggregate queries. + this.B = null, + // The corresponding `Target` of this `Query` instance, for use with + // aggregate queries. Unlike targets for non-aggregate queries, + // aggregate query targets do not contain normalized order-bys, they only + // contain explicit order-bys. + this.$ = null, this.startAt, this.endAt; + } +} + +/** Creates a new Query for a query that matches all documents at `path` */ +/** + * Returns whether the query matches a collection group rather than a specific + * collection. + */ +function __PRIVATE_isCollectionGroupQuery(t) { + return null !== t.collectionGroup; +} + +/** + * Returns the normalized order-by constraint that is used to execute the Query, + * which can be different from the order-by constraints the user provided (e.g. + * the SDK and backend always orders by `__name__`). The normalized order-by + * includes implicit order-bys in addition to the explicit user provided + * order-bys. + */ function __PRIVATE_queryNormalizedOrderBy(t) { + const e = __PRIVATE_debugCast(t); + if (null === e.q) { + e.q = []; + const t = new Set; + // Any explicit order by fields should be added as is. + for (const r of e.explicitOrderBy) e.q.push(r), t.add(r.field.canonicalString()); + // The order of the implicit ordering always matches the last explicit order by. + const r = e.explicitOrderBy.length > 0 ? e.explicitOrderBy[e.explicitOrderBy.length - 1].dir : "asc" /* Direction.ASCENDING */ , n = + // Returns the sorted set of inequality filter fields used in this query. + function __PRIVATE_getInequalityFilterFields(t) { + let e = new SortedSet(FieldPath$1.comparator); + return t.filters.forEach((t => { + t.getFlattenedFilters().forEach((t => { + t.isInequality() && (e = e.add(t.field)); + })); + })), e; + } + /** + * Creates a new Query for a collection group query that matches all documents + * within the provided collection group. + */ (e); + // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical + // order. When there are multiple inequality filters on the same field, the field should be added + // only once. + // Note: `SortedSet` sorts the key field before other fields. However, we want the key + // field to be sorted last. + n.forEach((n => { + t.has(n.canonicalString()) || n.isKeyField() || e.q.push(new OrderBy(n, r)); + })), + // Add the document key field to the last if it is not explicitly ordered. + t.has(FieldPath$1.keyField().canonicalString()) || e.q.push(new OrderBy(FieldPath$1.keyField(), r)); + } + return e.q; +} + +/** + * Converts this `Query` instance to its corresponding `Target` representation. + */ function __PRIVATE_queryToTarget(t) { + const e = __PRIVATE_debugCast(t); + return e.B || (e.B = __PRIVATE__queryToTarget(e, __PRIVATE_queryNormalizedOrderBy(t))), + e.B; +} + +/** + * Converts this `Query` instance to its corresponding `Target` representation, + * for use within an aggregate query. Unlike targets for non-aggregate queries, + * aggregate query targets do not contain normalized order-bys, they only + * contain explicit order-bys. + */ function __PRIVATE__queryToTarget(t, e) { + if ("F" /* LimitType.First */ === t.limitType) return __PRIVATE_newTarget(t.path, t.collectionGroup, e, t.filters, t.limit, t.startAt, t.endAt); + { + // Flip the orderBy directions since we want the last results + e = e.map((t => { + const e = "desc" /* Direction.DESCENDING */ === t.dir ? "asc" /* Direction.ASCENDING */ : "desc" /* Direction.DESCENDING */; + return new OrderBy(t.field, e); + })); + // We need to swap the cursors to match the now-flipped query ordering. + const r = t.endAt ? new Bound(t.endAt.position, t.endAt.inclusive) : null, n = t.startAt ? new Bound(t.startAt.position, t.startAt.inclusive) : null; + // Now return as a LimitType.First query. + return __PRIVATE_newTarget(t.path, t.collectionGroup, e, t.filters, t.limit, r, n); + } +} + +function __PRIVATE_queryWithAddedFilter(t, e) { + const r = t.filters.concat([ e ]); + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, t.explicitOrderBy.slice(), r, t.limit, t.limitType, t.startAt, t.endAt); +} + +function __PRIVATE_queryEquals(t, e) { + return function __PRIVATE_targetEquals(t, e) { + if (t.limit !== e.limit) return !1; + if (t.orderBy.length !== e.orderBy.length) return !1; + for (let r = 0; r < t.orderBy.length; r++) if (!__PRIVATE_orderByEquals(t.orderBy[r], e.orderBy[r])) return !1; + if (t.filters.length !== e.filters.length) return !1; + for (let r = 0; r < t.filters.length; r++) if (!__PRIVATE_filterEquals(t.filters[r], e.filters[r])) return !1; + return t.collectionGroup === e.collectionGroup && !!t.path.isEqual(e.path) && !!__PRIVATE_boundEquals(t.startAt, e.startAt) && __PRIVATE_boundEquals(t.endAt, e.endAt); + }(__PRIVATE_queryToTarget(t), __PRIVATE_queryToTarget(e)) && t.limitType === e.limitType; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns an DoubleValue for `value` that is encoded based the serializer's + * `useProto3Json` setting. + */ function __PRIVATE_toDouble(t, e) { + if (t.useProto3Json) { + if (isNaN(e)) return { + doubleValue: "NaN" + }; + if (e === 1 / 0) return { + doubleValue: "Infinity" + }; + if (e === -1 / 0) return { + doubleValue: "-Infinity" + }; + } + return { + doubleValue: __PRIVATE_isNegativeZero(e) ? "-0" : e + }; +} + +/** + * Returns an IntegerValue for `value`. + */ +/** + * Returns a value for a number that's appropriate to put into a proto. + * The return value is an IntegerValue if it can safely represent the value, + * otherwise a DoubleValue is returned. + */ +function toNumber(t, e) { + return function isSafeInteger(t) { + return "number" == typeof t && Number.isInteger(t) && !__PRIVATE_isNegativeZero(t) && t <= Number.MAX_SAFE_INTEGER && t >= Number.MIN_SAFE_INTEGER; + }(e) ? function __PRIVATE_toInteger(t) { + return { + integerValue: "" + t + }; + }(e) : __PRIVATE_toDouble(t, e); +} + +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Used to represent a field transform on a mutation. */ class TransformOperation { + constructor() { + // Make sure that the structural type of `TransformOperation` is unique. + // See https://github.com/microsoft/TypeScript/issues/5451 + this._ = void 0; + } +} + +/** Transforms a value into a server-generated timestamp. */ class __PRIVATE_ServerTimestampTransform extends TransformOperation {} + +/** Transforms an array value via a union operation. */ class __PRIVATE_ArrayUnionTransformOperation extends TransformOperation { + constructor(t) { + super(), this.elements = t; + } +} + +/** Transforms an array value via a remove operation. */ class __PRIVATE_ArrayRemoveTransformOperation extends TransformOperation { + constructor(t) { + super(), this.elements = t; + } +} + +/** + * Implements the backend semantics for locally computed NUMERIC_ADD (increment) + * transforms. Converts all field values to integers or doubles, but unlike the + * backend does not cap integer values at 2^63. Instead, JavaScript number + * arithmetic is used and precision loss can occur for values greater than 2^53. + */ class __PRIVATE_NumericIncrementTransformOperation extends TransformOperation { + constructor(t, e) { + super(), this.serializer = t, this.k = e; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** A field path and the TransformOperation to perform upon it. */ class FieldTransform { + constructor(t, e) { + this.field = t, this.transform = e; + } +} + +/** + * Encodes a precondition for a mutation. This follows the model that the + * backend accepts with the special case of an explicit "empty" precondition + * (meaning no precondition). + */ class Precondition { + constructor(t, e) { + this.updateTime = t, this.exists = e; + } + /** Creates a new empty Precondition. */ static none() { + return new Precondition; + } + /** Creates a new Precondition with an exists flag. */ static exists(t) { + return new Precondition(void 0, t); + } + /** Creates a new Precondition based on a version a document exists at. */ static updateTime(t) { + return new Precondition(t); + } + /** Returns whether this Precondition is empty. */ get isNone() { + return void 0 === this.updateTime && void 0 === this.exists; + } + isEqual(t) { + return this.exists === t.exists && (this.updateTime ? !!t.updateTime && this.updateTime.isEqual(t.updateTime) : !t.updateTime); + } +} + +/** + * A mutation describes a self-contained change to a document. Mutations can + * create, replace, delete, and update subsets of documents. + * + * Mutations not only act on the value of the document but also its version. + * + * For local mutations (mutations that haven't been committed yet), we preserve + * the existing version for Set and Patch mutations. For Delete mutations, we + * reset the version to 0. + * + * Here's the expected transition table. + * + * MUTATION APPLIED TO RESULTS IN + * + * SetMutation Document(v3) Document(v3) + * SetMutation NoDocument(v3) Document(v0) + * SetMutation InvalidDocument(v0) Document(v0) + * PatchMutation Document(v3) Document(v3) + * PatchMutation NoDocument(v3) NoDocument(v3) + * PatchMutation InvalidDocument(v0) UnknownDocument(v3) + * DeleteMutation Document(v3) NoDocument(v0) + * DeleteMutation NoDocument(v3) NoDocument(v0) + * DeleteMutation InvalidDocument(v0) NoDocument(v0) + * + * For acknowledged mutations, we use the updateTime of the WriteResponse as + * the resulting version for Set and Patch mutations. As deletes have no + * explicit update time, we use the commitTime of the WriteResponse for + * Delete mutations. + * + * If a mutation is acknowledged by the backend but fails the precondition check + * locally, we transition to an `UnknownDocument` and rely on Watch to send us + * the updated version. + * + * Field transforms are used only with Patch and Set Mutations. We use the + * `updateTransforms` message to store transforms, rather than the `transforms`s + * messages. + * + * ## Subclassing Notes + * + * Every type of mutation needs to implement its own applyToRemoteDocument() and + * applyToLocalView() to implement the actual behavior of applying the mutation + * to some source document (see `setMutationApplyToRemoteDocument()` for an + * example). + */ class Mutation {} + +/** + * A mutation that creates or replaces the document at the given key with the + * object value contents. + */ class __PRIVATE_SetMutation extends Mutation { + constructor(t, e, r, n = []) { + super(), this.key = t, this.value = e, this.precondition = r, this.fieldTransforms = n, + this.type = 0 /* MutationType.Set */; + } + getFieldMask() { + return null; + } +} + +/** + * A mutation that modifies fields of the document at the given key with the + * given values. The values are applied through a field mask: + * + * * When a field is in both the mask and the values, the corresponding field + * is updated. + * * When a field is in neither the mask nor the values, the corresponding + * field is unmodified. + * * When a field is in the mask but not in the values, the corresponding field + * is deleted. + * * When a field is not in the mask but is in the values, the values map is + * ignored. + */ class __PRIVATE_PatchMutation extends Mutation { + constructor(t, e, r, n, i = []) { + super(), this.key = t, this.data = e, this.fieldMask = r, this.precondition = n, + this.fieldTransforms = i, this.type = 1 /* MutationType.Patch */; + } + getFieldMask() { + return this.fieldMask; + } +} + +/** A mutation that deletes the document at the given key. */ class __PRIVATE_DeleteMutation extends Mutation { + constructor(t, e) { + super(), this.key = t, this.precondition = e, this.type = 2 /* MutationType.Delete */ , + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } +} + +/** + * A mutation that verifies the existence of the document at the given key with + * the provided precondition. + * + * The `verify` operation is only used in Transactions, and this class serves + * primarily to facilitate serialization into protos. + */ class __PRIVATE_VerifyMutation extends Mutation { + constructor(t, e) { + super(), this.key = t, this.precondition = e, this.type = 3 /* MutationType.Verify */ , + this.fieldTransforms = []; + } + getFieldMask() { + return null; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const st = (() => { + const t = { + asc: "ASCENDING", + desc: "DESCENDING" + }; + return t; +})(), ot = (() => { + const t = { + "<": "LESS_THAN", + "<=": "LESS_THAN_OR_EQUAL", + ">": "GREATER_THAN", + ">=": "GREATER_THAN_OR_EQUAL", + "==": "EQUAL", + "!=": "NOT_EQUAL", + "array-contains": "ARRAY_CONTAINS", + in: "IN", + "not-in": "NOT_IN", + "array-contains-any": "ARRAY_CONTAINS_ANY" + }; + return t; +})(), at = (() => { + const t = { + and: "AND", + or: "OR" + }; + return t; +})(); + +/** + * This class generates JsonObject values for the Datastore API suitable for + * sending to either GRPC stub methods or via the JSON/HTTP REST API. + * + * The serializer supports both Protobuf.js and Proto3 JSON formats. By + * setting `useProto3Json` to true, the serializer will use the Proto3 JSON + * format. + * + * For a description of the Proto3 JSON format check + * https://developers.google.com/protocol-buffers/docs/proto3#json + * + * TODO(klimt): We can remove the databaseId argument if we keep the full + * resource name in documents. + */ +class JsonProtoSerializer { + constructor(t, e) { + this.databaseId = t, this.useProto3Json = e; + } +} + +/** + * Returns a value for a number (or null) that's appropriate to put into + * a google.protobuf.Int32Value proto. + * DO NOT USE THIS FOR ANYTHING ELSE. + * This method cheats. It's typed as returning "number" because that's what + * our generated proto interfaces say Int32Value must be. But GRPC actually + * expects a { value: } struct. + */ +/** + * Returns a value for a Date that's appropriate to put into a proto. + */ +function toTimestamp(t, e) { + if (t.useProto3Json) { + return `${new Date(1e3 * e.seconds).toISOString().replace(/\.\d*/, "").replace("Z", "")}.${("000000000" + e.nanoseconds).slice(-9)}Z`; + } + return { + seconds: "" + e.seconds, + nanos: e.nanoseconds + }; +} + +/** + * Returns a Timestamp typed object given protobuf timestamp value. + */ +/** + * Returns a value for bytes that's appropriate to put in a proto. + * + * Visible for testing. + */ +function __PRIVATE_toBytes(t, e) { + return t.useProto3Json ? e.toBase64() : e.toUint8Array(); +} + +function __PRIVATE_toVersion(t, e) { + return toTimestamp(t, e.toTimestamp()); +} + +function __PRIVATE_fromVersion(t) { + return __PRIVATE_hardAssert(!!t, 49232), SnapshotVersion.fromTimestamp(function fromTimestamp(t) { + const e = __PRIVATE_normalizeTimestamp(t); + return new Timestamp(e.seconds, e.nanos); + }(t)); +} + +function __PRIVATE_toResourceName(t, e) { + return __PRIVATE_toResourcePath(t, e).canonicalString(); +} + +function __PRIVATE_toResourcePath(t, e) { + const r = function __PRIVATE_fullyQualifiedPrefixPath(t) { + return new ResourcePath([ "projects", t.projectId, "databases", t.database ]); + }(t).child("documents"); + return void 0 === e ? r : r.child(e); +} + +function __PRIVATE_toName(t, e) { + return __PRIVATE_toResourceName(t.databaseId, e.path); +} + +function fromName(t, e) { + const r = function __PRIVATE_fromResourceName(t) { + const e = ResourcePath.fromString(t); + return __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(e), 10190, { + key: e.toString() + }), e; + }(e); + if (r.get(1) !== t.databaseId.projectId) throw new FirestoreError(w, "Tried to deserialize key from different project: " + r.get(1) + " vs " + t.databaseId.projectId); + if (r.get(3) !== t.databaseId.database) throw new FirestoreError(w, "Tried to deserialize key from different database: " + r.get(3) + " vs " + t.databaseId.database); + return new DocumentKey(function __PRIVATE_extractLocalPathFromResourceName(t) { + return __PRIVATE_hardAssert(t.length > 4 && "documents" === t.get(4), 29091, { + key: t.toString() + }), t.popFirst(5); + } + /** Creates a Document proto from key and fields (but no create/update time) */ (r)); +} + +function __PRIVATE_toMutationDocument(t, e, r) { + return { + name: __PRIVATE_toName(t, e), + fields: r.value.mapValue.fields + }; +} + +function __PRIVATE_fromBatchGetDocumentsResponse(t, e) { + return "found" in e ? function __PRIVATE_fromFound(t, e) { + __PRIVATE_hardAssert(!!e.found, 43571), e.found.name, e.found.updateTime; + const r = fromName(t, e.found.name), n = __PRIVATE_fromVersion(e.found.updateTime), i = e.found.createTime ? __PRIVATE_fromVersion(e.found.createTime) : SnapshotVersion.min(), s = new ObjectValue({ + mapValue: { + fields: e.found.fields + } + }); + return MutableDocument.newFoundDocument(r, n, i, s); + }(t, e) : "missing" in e ? function __PRIVATE_fromMissing(t, e) { + __PRIVATE_hardAssert(!!e.missing, 3894), __PRIVATE_hardAssert(!!e.readTime, 22933); + const r = fromName(t, e.missing), n = __PRIVATE_fromVersion(e.readTime); + return MutableDocument.newNoDocument(r, n); + }(t, e) : fail(7234, { + result: e + }); +} + +function toMutation(t, e) { + let r; + if (e instanceof __PRIVATE_SetMutation) r = { + update: __PRIVATE_toMutationDocument(t, e.key, e.value) + }; else if (e instanceof __PRIVATE_DeleteMutation) r = { + delete: __PRIVATE_toName(t, e.key) + }; else if (e instanceof __PRIVATE_PatchMutation) r = { + update: __PRIVATE_toMutationDocument(t, e.key, e.data), + updateMask: __PRIVATE_toDocumentMask(e.fieldMask) + }; else { + if (!(e instanceof __PRIVATE_VerifyMutation)) return fail(16599, { + L: e.type + }); + r = { + verify: __PRIVATE_toName(t, e.key) + }; + } + return e.fieldTransforms.length > 0 && (r.updateTransforms = e.fieldTransforms.map((t => function __PRIVATE_toFieldTransform(t, e) { + const r = e.transform; + if (r instanceof __PRIVATE_ServerTimestampTransform) return { + fieldPath: e.field.canonicalString(), + setToServerValue: "REQUEST_TIME" + }; + if (r instanceof __PRIVATE_ArrayUnionTransformOperation) return { + fieldPath: e.field.canonicalString(), + appendMissingElements: { + values: r.elements + } + }; + if (r instanceof __PRIVATE_ArrayRemoveTransformOperation) return { + fieldPath: e.field.canonicalString(), + removeAllFromArray: { + values: r.elements + } + }; + if (r instanceof __PRIVATE_NumericIncrementTransformOperation) return { + fieldPath: e.field.canonicalString(), + increment: r.k + }; + throw fail(20930, { + transform: e.transform + }); + }(0, t)))), e.precondition.isNone || (r.currentDocument = function __PRIVATE_toPrecondition(t, e) { + return void 0 !== e.updateTime ? { + updateTime: __PRIVATE_toVersion(t, e.updateTime) + } : void 0 !== e.exists ? { + exists: e.exists + } : fail(27497); + }(t, e.precondition)), r; +} + +function __PRIVATE_toQueryTarget(t, e) { + // Dissect the path into parent, collectionId, and optional key filter. + const r = { + structuredQuery: {} + }, n = e.path; + let i; + null !== e.collectionGroup ? (i = n, r.structuredQuery.from = [ { + collectionId: e.collectionGroup, + allDescendants: !0 + } ]) : (i = n.popLast(), r.structuredQuery.from = [ { + collectionId: n.lastSegment() + } ]), r.parent = function __PRIVATE_toQueryPath(t, e) { + return __PRIVATE_toResourceName(t.databaseId, e); + }(t, i); + const s = function __PRIVATE_toFilters(t) { + if (0 === t.length) return; + return __PRIVATE_toFilter(CompositeFilter.create(t, "and" /* CompositeOperator.AND */)); + }(e.filters); + s && (r.structuredQuery.where = s); + const o = function __PRIVATE_toOrder(t) { + if (0 === t.length) return; + return t.map((t => + // visible for testing + function __PRIVATE_toPropertyOrder(t) { + return { + field: __PRIVATE_toFieldPathReference(t.field), + direction: __PRIVATE_toDirection(t.dir) + }; + } + // visible for testing + (t))); + }(e.orderBy); + o && (r.structuredQuery.orderBy = o); + const a = function __PRIVATE_toInt32Proto(t, e) { + return t.useProto3Json || __PRIVATE_isNullOrUndefined(e) ? e : { + value: e + }; + }(t, e.limit); + return null !== a && (r.structuredQuery.limit = a), e.startAt && (r.structuredQuery.startAt = function __PRIVATE_toStartAtCursor(t) { + return { + before: t.inclusive, + values: t.position + }; + }(e.startAt)), e.endAt && (r.structuredQuery.endAt = function __PRIVATE_toEndAtCursor(t) { + return { + before: !t.inclusive, + values: t.position + }; + } + // visible for testing + (e.endAt)), { + M: r, + parent: i + }; +} + +function __PRIVATE_toDirection(t) { + return st[t]; +} + +// visible for testing +function __PRIVATE_toOperatorName(t) { + return ot[t]; +} + +function __PRIVATE_toCompositeOperatorName(t) { + return at[t]; +} + +function __PRIVATE_toFieldPathReference(t) { + return { + fieldPath: t.canonicalString() + }; +} + +function __PRIVATE_toFilter(t) { + return t instanceof FieldFilter ? function __PRIVATE_toUnaryOrFieldFilter(t) { + if ("==" /* Operator.EQUAL */ === t.op) { + if (__PRIVATE_isNanValue(t.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: "IS_NAN" + } + }; + if (__PRIVATE_isNullValue(t.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: "IS_NULL" + } + }; + } else if ("!=" /* Operator.NOT_EQUAL */ === t.op) { + if (__PRIVATE_isNanValue(t.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: "IS_NOT_NAN" + } + }; + if (__PRIVATE_isNullValue(t.value)) return { + unaryFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: "IS_NOT_NULL" + } + }; + } + return { + fieldFilter: { + field: __PRIVATE_toFieldPathReference(t.field), + op: __PRIVATE_toOperatorName(t.op), + value: t.value + } + }; + }(t) : t instanceof CompositeFilter ? function __PRIVATE_toCompositeFilter(t) { + const e = t.getFilters().map((t => __PRIVATE_toFilter(t))); + if (1 === e.length) return e[0]; + return { + compositeFilter: { + op: __PRIVATE_toCompositeOperatorName(t.op), + filters: e + } + }; + }(t) : fail(54877, { + filter: t + }); +} + +function __PRIVATE_toDocumentMask(t) { + const e = []; + return t.fields.forEach((t => e.push(t.canonicalString()))), { + fieldPaths: e + }; +} + +function __PRIVATE_isValidResourceName(t) { + // Resource names have at least 4 components (project ID, database ID) + return t.length >= 4 && "projects" === t.get(0) && "databases" === t.get(2); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ function __PRIVATE_newSerializer(t) { + return new JsonProtoSerializer(t, /* useProto3Json= */ !0); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A helper for running delayed tasks following an exponential backoff curve + * between attempts. + * + * Each delay is made up of a "base" delay which follows the exponential + * backoff curve, and a +/- 50% "jitter" that is calculated and added to the + * base delay. This prevents clients from accidentally synchronizing their + * delays causing spikes of load to the backend. + */ +class __PRIVATE_ExponentialBackoff { + constructor( + /** + * The AsyncQueue to run backoff operations on. + */ + t, + /** + * The ID to use when scheduling backoff operations on the AsyncQueue. + */ + e, + /** + * The initial delay (used as the base delay on the first retry attempt). + * Note that jitter will still be applied, so the actual delay could be as + * little as 0.5*initialDelayMs. + */ + r = 1e3 + /** + * The multiplier to use to determine the extended base delay after each + * attempt. + */ , n = 1.5 + /** + * The maximum base delay after which no further backoff is performed. + * Note that jitter will still be applied, so the actual delay could be as + * much as 1.5*maxDelayMs. + */ , i = 6e4) { + this.U = t, this.timerId = e, this.j = r, this.W = n, this.K = i, this.G = 0, this.J = null, + /** The last backoff attempt, as epoch milliseconds. */ + this.H = Date.now(), this.reset(); + } + /** + * Resets the backoff delay. + * + * The very next backoffAndWait() will have no delay. If it is called again + * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and + * subsequent ones will increase according to the backoffFactor. + */ reset() { + this.G = 0; + } + /** + * Resets the backoff delay to the maximum delay (e.g. for use after a + * RESOURCE_EXHAUSTED error). + */ Y() { + this.G = this.K; + } + /** + * Returns a promise that resolves after currentDelayMs, and increases the + * delay for any subsequent attempts. If there was a pending backoff operation + * already, it will be canceled. + */ Z(t) { + // Cancel any pending backoff operation. + this.cancel(); + // First schedule using the current base (which may be 0 and should be + // honored as such). + const e = Math.floor(this.G + this.X()), r = Math.max(0, Date.now() - this.H), n = Math.max(0, e - r); + // Guard against lastAttemptTime being in the future due to a clock change. + n > 0 && __PRIVATE_logDebug("ExponentialBackoff", `Backing off for ${n} ms (base delay: ${this.G} ms, delay with jitter: ${e} ms, last attempt: ${r} ms ago)`), + this.J = this.U.enqueueAfterDelay(this.timerId, n, (() => (this.H = Date.now(), + t()))), + // Apply backoff factor to determine next delay and ensure it is within + // bounds. + this.G *= this.W, this.G < this.j && (this.G = this.j), this.G > this.K && (this.G = this.K); + } + tt() { + null !== this.J && (this.J.skipDelay(), this.J = null); + } + cancel() { + null !== this.J && (this.J.cancel(), this.J = null); + } + /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ X() { + return (Math.random() - .5) * this.G; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Datastore and its related methods are a wrapper around the external Google + * Cloud Datastore grpc API, which provides an interface that is more convenient + * for the rest of the client SDK architecture to consume. + */ class Datastore {} + +/** + * An implementation of Datastore that exposes additional state for internal + * consumption. + */ class __PRIVATE_DatastoreImpl extends Datastore { + constructor(t, e, r, n) { + super(), this.authCredentials = t, this.appCheckCredentials = e, this.connection = r, + this.serializer = n, this.et = !1; + } + rt() { + if (this.et) throw new FirestoreError(N, "The client has already been terminated."); + } + /** Invokes the provided RPC with auth and AppCheck tokens. */ I(t, e, r, n) { + return this.rt(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([i, s]) => this.connection.I(t, __PRIVATE_toResourcePath(e, r), n, i, s))).catch((t => { + throw "FirebaseError" === t.name ? (t.code === S && (this.authCredentials.invalidateToken(), + this.appCheckCredentials.invalidateToken()), t) : new FirestoreError(g, t.toString()); + })); + } + /** Invokes the provided RPC with streamed results with auth and AppCheck tokens. */ D(t, e, r, n, i) { + return this.rt(), Promise.all([ this.authCredentials.getToken(), this.appCheckCredentials.getToken() ]).then((([s, o]) => this.connection.D(t, __PRIVATE_toResourcePath(e, r), n, s, o, i))).catch((t => { + throw "FirebaseError" === t.name ? (t.code === S && (this.authCredentials.invalidateToken(), + this.appCheckCredentials.invalidateToken()), t) : new FirestoreError(g, t.toString()); + })); + } + terminate() { + this.et = !0, this.connection.terminate(); + } +} + +// TODO(firestorexp): Make sure there is only one Datastore instance per +// firestore-exp client. +async function __PRIVATE_invokeCommitRpc(t, e) { + const r = __PRIVATE_debugCast(t), n = { + writes: e.map((t => toMutation(r.serializer, t))) + }; + await r.I("Commit", r.serializer.databaseId, ResourcePath.emptyPath(), n); +} + +async function __PRIVATE_invokeBatchGetDocumentsRpc(t, e) { + const r = __PRIVATE_debugCast(t), n = { + documents: e.map((t => __PRIVATE_toName(r.serializer, t))) + }, i = await r.D("BatchGetDocuments", r.serializer.databaseId, ResourcePath.emptyPath(), n, e.length), s = new Map; + i.forEach((t => { + const e = __PRIVATE_fromBatchGetDocumentsResponse(r.serializer, t); + s.set(e.key.toString(), e); + })); + const o = []; + return e.forEach((t => { + const e = s.get(t.toString()); + __PRIVATE_hardAssert(!!e, 55234, { + key: t + }), o.push(e); + })), o; +} + +async function __PRIVATE_invokeRunQueryRpc(t, e) { + const r = __PRIVATE_debugCast(t), {M: n, parent: i} = __PRIVATE_toQueryTarget(r.serializer, __PRIVATE_queryToTarget(e)); + return (await r.D("RunQuery", r.serializer.databaseId, i, { + structuredQuery: n.structuredQuery + })).filter((t => !!t.document)).map((t => function __PRIVATE_fromDocument(t, e, r) { + const n = fromName(t, e.name), i = __PRIVATE_fromVersion(e.updateTime), s = e.createTime ? __PRIVATE_fromVersion(e.createTime) : SnapshotVersion.min(), o = new ObjectValue({ + mapValue: { + fields: e.fields + } + }), a = MutableDocument.newFoundDocument(n, i, s, o); + return r && a.setHasCommittedMutations(), r ? a.setHasCommittedMutations() : a; + }(r.serializer, t.document, void 0))); +} + +async function __PRIVATE_invokeRunAggregationQueryRpc(t, e, r) { + const n = __PRIVATE_debugCast(t), {request: i, nt: s, parent: o} = function __PRIVATE_toRunAggregationQueryRequest(t, e, r, n) { + const {M: i, parent: s} = __PRIVATE_toQueryTarget(t, e), o = {}, a = []; + let u = 0; + return r.forEach((t => { + // Map all client-side aliases to a unique short-form + // alias. This avoids issues with client-side aliases that + // exceed the 1500-byte string size limit. + const e = n ? t.alias : "aggregate_" + u++; + o[e] = t.alias, "count" === t.aggregateType ? a.push({ + alias: e, + count: {} + }) : "avg" === t.aggregateType ? a.push({ + alias: e, + avg: { + field: __PRIVATE_toFieldPathReference(t.fieldPath) + } + }) : "sum" === t.aggregateType && a.push({ + alias: e, + sum: { + field: __PRIVATE_toFieldPathReference(t.fieldPath) + } + }); + })), { + request: { + structuredAggregationQuery: { + aggregations: a, + structuredQuery: i.structuredQuery + }, + parent: i.parent + }, + nt: o, + parent: s + }; + }(n.serializer, function __PRIVATE_queryToAggregateTarget(t) { + const e = __PRIVATE_debugCast(t); + return e.$ || ( + // Do not include implicit order-bys for aggregate queries. + e.$ = __PRIVATE__queryToTarget(e, t.explicitOrderBy)), e.$; + }(e), r); + n.connection.P || delete i.parent; + const a = (await n.D("RunAggregationQuery", n.serializer.databaseId, o, i, + /*expectedResponseCount=*/ 1)).filter((t => !!t.result)); + // Omit RunAggregationQueryResponse that only contain readTimes. + __PRIVATE_hardAssert(1 === a.length, 64727); + // Remap the short-form aliases that were sent to the server + // to the client-side aliases. Users will access the results + // using the client-side alias. + const u = a[0].result?.aggregateFields; + return Object.keys(u).reduce(((t, e) => (t[s[e]] = u[e], t)), {}); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const ut = "ComponentProvider", _t = new Map; + +/** + * An instance map that ensures only one Datastore exists per Firestore + * instance. + */ +/** + * Returns an initialized and started Datastore for the given Firestore + * instance. Callers must invoke removeComponents() when the Firestore + * instance is terminated. + */ +function __PRIVATE_getDatastore(t) { + if (t._terminated) throw new FirestoreError(N, "The client has already been terminated."); + if (!_t.has(t)) { + __PRIVATE_logDebug(ut, "Initializing Datastore"); + const e = function __PRIVATE_newConnection(t) { + return new __PRIVATE_FetchConnection(t); + }(function __PRIVATE_makeDatabaseInfo(t, e, r, n) { + return new DatabaseInfo(t, e, r, n.host, n.ssl, n.experimentalForceLongPolling, n.experimentalAutoDetectLongPolling, __PRIVATE_cloneLongPollingOptions(n.experimentalLongPollingOptions), n.useFetchStreams, n.isUsingEmulator); + } + /** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ (t._databaseId, t.app.options.appId || "", t._persistenceKey, t._freezeSettings())), r = __PRIVATE_newSerializer(t._databaseId), n = function __PRIVATE_newDatastore(t, e, r, n) { + return new __PRIVATE_DatastoreImpl(t, e, r, n); + }(t._authCredentials, t._appCheckCredentials, e, r); + _t.set(t, n); + } + return _t.get(t); +} + +/** + * Removes all components associated with the provided instance. Must be called + * when the `Firestore` instance is terminated. + */ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const ct = 1048576, lt = "firestore.googleapis.com", ht = !0; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// settings() defaults: +/** + * A concrete type describing all the values that can be applied via a + * user-supplied `FirestoreSettings` object. This is a separate type so that + * defaults can be supplied and the value can be checked for equality. + */ +class FirestoreSettingsImpl { + constructor(t) { + if (void 0 === t.host) { + if (void 0 !== t.ssl) throw new FirestoreError(w, "Can't provide ssl option if host option is not set"); + this.host = lt, this.ssl = ht; + } else this.host = t.host, this.ssl = t.ssl ?? ht; + if (this.isUsingEmulator = void 0 !== t.emulatorOptions, this.credentials = t.credentials, + this.ignoreUndefinedProperties = !!t.ignoreUndefinedProperties, this.localCache = t.localCache, + void 0 === t.cacheSizeBytes) this.cacheSizeBytes = 41943040; else { + if (-1 !== t.cacheSizeBytes && t.cacheSizeBytes < ct) throw new FirestoreError(w, "cacheSizeBytes must be at least 1048576"); + this.cacheSizeBytes = t.cacheSizeBytes; + } + !function __PRIVATE_validateIsNotUsedTogether(t, e, r, n) { + if (!0 === e && !0 === n) throw new FirestoreError(w, `${t} and ${r} cannot be used together.`); + }("experimentalForceLongPolling", t.experimentalForceLongPolling, "experimentalAutoDetectLongPolling", t.experimentalAutoDetectLongPolling), + this.experimentalForceLongPolling = !!t.experimentalForceLongPolling, this.experimentalForceLongPolling ? this.experimentalAutoDetectLongPolling = !1 : void 0 === t.experimentalAutoDetectLongPolling ? this.experimentalAutoDetectLongPolling = true : + // For backwards compatibility, coerce the value to boolean even though + // the TypeScript compiler has narrowed the type to boolean already. + // noinspection PointlessBooleanExpressionJS + this.experimentalAutoDetectLongPolling = !!t.experimentalAutoDetectLongPolling, + this.experimentalLongPollingOptions = __PRIVATE_cloneLongPollingOptions(t.experimentalLongPollingOptions ?? {}), + function __PRIVATE_validateLongPollingOptions(t) { + if (void 0 !== t.timeoutSeconds) { + if (isNaN(t.timeoutSeconds)) throw new FirestoreError(w, `invalid long polling timeout: ${t.timeoutSeconds} (must not be NaN)`); + if (t.timeoutSeconds < 5) throw new FirestoreError(w, `invalid long polling timeout: ${t.timeoutSeconds} (minimum allowed value is 5)`); + if (t.timeoutSeconds > 30) throw new FirestoreError(w, `invalid long polling timeout: ${t.timeoutSeconds} (maximum allowed value is 30)`); + } + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ (this.experimentalLongPollingOptions), this.useFetchStreams = !!t.useFetchStreams; + } + isEqual(t) { + return this.host === t.host && this.ssl === t.ssl && this.credentials === t.credentials && this.cacheSizeBytes === t.cacheSizeBytes && this.experimentalForceLongPolling === t.experimentalForceLongPolling && this.experimentalAutoDetectLongPolling === t.experimentalAutoDetectLongPolling && function __PRIVATE_longPollingOptionsEqual(t, e) { + return t.timeoutSeconds === e.timeoutSeconds; + }(this.experimentalLongPollingOptions, t.experimentalLongPollingOptions) && this.ignoreUndefinedProperties === t.ignoreUndefinedProperties && this.useFetchStreams === t.useFetchStreams; + } +} + +class Firestore { + /** @hideconstructor */ + constructor(t, e, r, n) { + this._authCredentials = t, this._appCheckCredentials = e, this._databaseId = r, + this._app = n, + /** + * Whether it's a Firestore or Firestore Lite instance. + */ + this.type = "firestore-lite", this._persistenceKey = "(lite)", this._settings = new FirestoreSettingsImpl({}), + this._settingsFrozen = !1, this._emulatorOptions = {}, + // A task that is assigned when the terminate() is invoked and resolved when + // all components have shut down. Otherwise, Firestore is not terminated, + // which can mean either the FirestoreClient is in the process of starting, + // or restarting. + this._terminateTask = "notTerminated"; + } + /** + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service + * instance. + */ get app() { + if (!this._app) throw new FirestoreError(N, "Firestore was not initialized using the Firebase SDK. 'app' is not available"); + return this._app; + } + get _initialized() { + return this._settingsFrozen; + } + get _terminated() { + return "notTerminated" !== this._terminateTask; + } + _setSettings(t) { + if (this._settingsFrozen) throw new FirestoreError(N, "Firestore has already been started and its settings can no longer be changed. You can only modify settings before calling any other methods on a Firestore object."); + this._settings = new FirestoreSettingsImpl(t), this._emulatorOptions = t.emulatorOptions || {}, + void 0 !== t.credentials && (this._authCredentials = function __PRIVATE_makeAuthCredentialsProvider(t) { + if (!t) return new __PRIVATE_EmptyAuthCredentialsProvider; + switch (t.type) { + case "firstParty": + return new __PRIVATE_FirstPartyAuthCredentialsProvider(t.sessionIndex || "0", t.iamToken || null, t.authTokenFactory || null); + + case "provider": + return t.client; + + default: + throw new FirestoreError(w, "makeAuthCredentialsProvider failed due to invalid credential type"); + } + }(t.credentials)); + } + _getSettings() { + return this._settings; + } + _getEmulatorOptions() { + return this._emulatorOptions; + } + _freezeSettings() { + return this._settingsFrozen = !0, this._settings; + } + _delete() { + // The `_terminateTask` must be assigned future that completes when + // terminate is complete. The existence of this future puts SDK in state + // that will not accept further API interaction. + return "notTerminated" === this._terminateTask && (this._terminateTask = this._terminate()), + this._terminateTask; + } + async _restart() { + // The `_terminateTask` must equal 'notTerminated' after restart to + // signal that client is in a state that accepts API calls. + "notTerminated" === this._terminateTask ? await this._terminate() : this._terminateTask = "notTerminated"; + } + /** Returns a JSON-serializable representation of this `Firestore` instance. */ toJSON() { + return { + app: this._app, + databaseId: this._databaseId, + settings: this._settings + }; + } + /** + * Terminates all components used by this client. Subclasses can override + * this method to clean up their own dependencies, but must also call this + * method. + * + * Only ever called once. + */ _terminate() { + return function __PRIVATE_removeComponents(t) { + const e = _t.get(t); + e && (__PRIVATE_logDebug(ut, "Removing Datastore"), _t.delete(t), e.terminate()); + }(this), Promise.resolve(); + } +} + +function initializeFirestore(t, e, r) { + r || (r = L); + const n = _getProvider(t, "firestore/lite"); + if (n.isInitialized(r)) throw new FirestoreError(N, "Firestore can only be initialized once per app."); + return n.initialize({ + options: e, + instanceIdentifier: r + }); +} + +function getFirestore(t, r) { + const n = "object" == typeof t ? t : e(), i = "string" == typeof t ? t : r || "(default)", s = _getProvider(n, "firestore/lite").getImmediate({ + identifier: i + }); + if (!s._initialized) { + const t = f("firestore"); + t && connectFirestoreEmulator(s, ...t); + } + return s; +} + +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ function connectFirestoreEmulator(t, e, r, n = {}) { + t = __PRIVATE_cast(t, Firestore); + const i = c(e), s = t._getSettings(), o = { + ...s, + emulatorOptions: t._getEmulatorOptions() + }, a = `${e}:${r}`; + i && (d(`https://${a}`), m("Firestore", !0)), s.host !== lt && s.host !== a && __PRIVATE_logWarn("Host has been set in both settings() and connectFirestoreEmulator(), emulator host will be used."); + const u = { + ...s, + host: a, + ssl: i, + emulatorOptions: n + }; + // No-op if the new configuration matches the current configuration. This supports SSR + // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice. + if (!E(u, o) && (t._setSettings(u), n.mockUserToken)) { + let e, r; + if ("string" == typeof n.mockUserToken) e = n.mockUserToken, r = User.MOCK_USER; else { + // Let createMockUserToken validate first (catches common mistakes like + // invalid field "uid" and missing field "sub" / "user_id".) + e = T(n.mockUserToken, t._app?.options.projectId); + const i = n.mockUserToken.sub || n.mockUserToken.user_id; + if (!i) throw new FirestoreError(w, "mockUserToken must contain 'sub' or 'user_id' field!"); + r = new User(i); + } + t._authCredentials = new __PRIVATE_EmulatorAuthCredentialsProvider(new __PRIVATE_OAuthToken(e, r)); + } +} + +/** + * Terminates the provided `Firestore` instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` functions + * may be used. Any other function will throw a `FirestoreError`. Termination + * does not cancel any pending writes, and any promises that are awaiting a + * response from the server will not be resolved. + * + * To restart after termination, create a new instance of `Firestore` with + * {@link (getFirestore:1)}. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all of + * its resources or in combination with {@link clearIndexedDbPersistence} to + * ensure that all local state is destroyed between test runs. + * + * @param firestore - The `Firestore` instance to terminate. + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ function terminate(t) { + return t = __PRIVATE_cast(t, Firestore), r(t.app, "firestore/lite"), t._delete(); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents an aggregation that can be performed by Firestore. + */ +// eslint-disable-next-line @typescript-eslint/no-unused-vars +class AggregateField { + /** + * Create a new AggregateField + * @param aggregateType Specifies the type of aggregation operation to perform. + * @param _internalFieldPath Optionally specifies the field that is aggregated. + * @internal + */ + constructor(t = "count", e) { + this._internalFieldPath = e, + /** A type string to uniquely identify instances of this class. */ + this.type = "AggregateField", this.aggregateType = t; + } +} + +/** + * The results of executing an aggregation query. + */ class AggregateQuerySnapshot { + /** @hideconstructor */ + constructor(t, e, r) { + this._userDataWriter = e, this._data = r, + /** A type string to uniquely identify instances of this class. */ + this.type = "AggregateQuerySnapshot", this.query = t; + } + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ data() { + return this._userDataWriter.convertObjectMap(this._data); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `Query` refers to a query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ class Query { + // This is the lite version of the Query class in the main SDK. + /** @hideconstructor protected */ + constructor(t, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + e, r) { + this.converter = e, this._query = r, + /** The type of this Firestore reference. */ + this.type = "query", this.firestore = t; + } + withConverter(t) { + return new Query(this.firestore, t, this._query); + } +} + +/** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. + */ class DocumentReference { + /** @hideconstructor */ + constructor(t, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + e, r) { + this.converter = e, this._key = r, + /** The type of this Firestore reference. */ + this.type = "document", this.firestore = t; + } + get _path() { + return this._key.path; + } + /** + * The document's identifier within its collection. + */ get id() { + return this._key.path.lastSegment(); + } + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ get path() { + return this._key.path.canonicalString(); + } + /** + * The collection this `DocumentReference` belongs to. + */ get parent() { + return new CollectionReference(this.firestore, this.converter, this._key.path.popLast()); + } + withConverter(t) { + return new DocumentReference(this.firestore, t, this._key); + } + /** + * Returns a JSON-serializable representation of this `DocumentReference` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + type: DocumentReference._jsonSchemaVersion, + referencePath: this._key.toString() + }; + } + static fromJSON(t, e, r) { + if (__PRIVATE_validateJSON(e, DocumentReference._jsonSchema)) return new DocumentReference(t, r || null, new DocumentKey(ResourcePath.fromString(e.referencePath))); + } +} + +DocumentReference._jsonSchemaVersion = "firestore/documentReference/1.0", DocumentReference._jsonSchema = { + type: property("string", DocumentReference._jsonSchemaVersion), + referencePath: property("string") +}; + +/** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using {@link (query:1)}). + */ +class CollectionReference extends Query { + /** @hideconstructor */ + constructor(t, e, r) { + super(t, e, function __PRIVATE_newQueryForPath(t) { + return new __PRIVATE_QueryImpl(t); + }(r)), this._path = r, + /** The type of this Firestore reference. */ + this.type = "collection"; + } + /** The collection's identifier. */ get id() { + return this._query.path.lastSegment(); + } + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ get path() { + return this._query.path.canonicalString(); + } + /** + * A reference to the containing `DocumentReference` if this is a + * subcollection. If this isn't a subcollection, the reference is null. + */ get parent() { + const t = this._path.popLast(); + return t.isEmpty() ? null : new DocumentReference(this.firestore, + /* converter= */ null, new DocumentKey(t)); + } + withConverter(t) { + return new CollectionReference(this.firestore, t, this._path); + } +} + +function collection(t, e, ...r) { + if (t = P(t), __PRIVATE_validateNonEmptyArgument("collection", "path", e), t instanceof Firestore) { + const n = ResourcePath.fromString(e, ...r); + return __PRIVATE_validateCollectionPath(n), new CollectionReference(t, /* converter= */ null, n); + } + { + if (!(t instanceof DocumentReference || t instanceof CollectionReference)) throw new FirestoreError(w, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore"); + const n = t._path.child(ResourcePath.fromString(e, ...r)); + return __PRIVATE_validateCollectionPath(n), new CollectionReference(t.firestore, + /* converter= */ null, n); + } +} + +// TODO(firestorelite): Consider using ErrorFactory - +// https://github.com/firebase/firebase-js-sdk/blob/0131e1f/packages/util/src/errors.ts#L106 +/** + * Creates and returns a new `Query` instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given `collectionId`. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param collectionId - Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `Query`. + */ function collectionGroup(t, e) { + if (t = __PRIVATE_cast(t, Firestore), __PRIVATE_validateNonEmptyArgument("collectionGroup", "collection id", e), + e.indexOf("/") >= 0) throw new FirestoreError(w, `Invalid collection ID '${e}' passed to function collectionGroup(). Collection IDs must not contain '/'.`); + return new Query(t, + /* converter= */ null, function __PRIVATE_newQueryForCollectionGroup(t) { + return new __PRIVATE_QueryImpl(ResourcePath.emptyPath(), t); + }(e)); +} + +function doc(t, e, ...r) { + if (t = P(t), + // We allow omission of 'pathString' but explicitly prohibit passing in both + // 'undefined' and 'null'. + 1 === arguments.length && (e = __PRIVATE_AutoId.newId()), __PRIVATE_validateNonEmptyArgument("doc", "path", e), + t instanceof Firestore) { + const n = ResourcePath.fromString(e, ...r); + return __PRIVATE_validateDocumentPath(n), new DocumentReference(t, + /* converter= */ null, new DocumentKey(n)); + } + { + if (!(t instanceof DocumentReference || t instanceof CollectionReference)) throw new FirestoreError(w, "Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore"); + const n = t._path.child(ResourcePath.fromString(e, ...r)); + return __PRIVATE_validateDocumentPath(n), new DocumentReference(t.firestore, t instanceof CollectionReference ? t.converter : null, new DocumentKey(n)); + } +} + +/** + * Returns true if the provided references are equal. + * + * @param left - A reference to compare. + * @param right - A reference to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ function refEqual(t, e) { + return t = P(t), e = P(e), (t instanceof DocumentReference || t instanceof CollectionReference) && (e instanceof DocumentReference || e instanceof CollectionReference) && (t.firestore === e.firestore && t.path === e.path && t.converter === e.converter); +} + +/** + * Returns true if the provided queries point to the same collection and apply + * the same constraints. + * + * @param left - A `Query` to compare. + * @param right - A `Query` to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ function queryEqual(t, e) { + return t = P(t), e = P(e), t instanceof Query && e instanceof Query && (t.firestore === e.firestore && __PRIVATE_queryEquals(t._query, e._query) && t.converter === e.converter); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing an array of bytes. + */ class Bytes { + /** @hideconstructor */ + constructor(t) { + this._byteString = t; + } + /** + * Creates a new `Bytes` object from the given Base64 string, converting it to + * bytes. + * + * @param base64 - The Base64 string used to create the `Bytes` object. + */ static fromBase64String(t) { + try { + return new Bytes(ByteString.fromBase64String(t)); + } catch (t) { + throw new FirestoreError(w, "Failed to construct data from Base64 string: " + t); + } + } + /** + * Creates a new `Bytes` object from the given Uint8Array. + * + * @param array - The Uint8Array used to create the `Bytes` object. + */ static fromUint8Array(t) { + return new Bytes(ByteString.fromUint8Array(t)); + } + /** + * Returns the underlying bytes as a Base64-encoded string. + * + * @returns The Base64-encoded string created from the `Bytes` object. + */ toBase64() { + return this._byteString.toBase64(); + } + /** + * Returns the underlying bytes in a new `Uint8Array`. + * + * @returns The Uint8Array created from the `Bytes` object. + */ toUint8Array() { + return this._byteString.toUint8Array(); + } + /** + * Returns a string representation of the `Bytes` object. + * + * @returns A string representation of the `Bytes` object. + */ toString() { + return "Bytes(base64: " + this.toBase64() + ")"; + } + /** + * Returns true if this `Bytes` object is equal to the provided one. + * + * @param other - The `Bytes` object to compare against. + * @returns true if this `Bytes` object is equal to the provided one. + */ isEqual(t) { + return this._byteString.isEqual(t._byteString); + } + /** + * Returns a JSON-serializable representation of this `Bytes` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + type: Bytes._jsonSchemaVersion, + bytes: this.toBase64() + }; + } + /** + * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}. + * + * @param json a JSON object represention of a `Bytes` instance + * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ static fromJSON(t) { + if (__PRIVATE_validateJSON(t, Bytes._jsonSchema)) return Bytes.fromBase64String(t.bytes); + } +} + +Bytes._jsonSchemaVersion = "firestore/bytes/1.0", Bytes._jsonSchema = { + type: property("string", Bytes._jsonSchemaVersion), + bytes: property("string") +}; + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `FieldPath` refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + * + * Create a `FieldPath` by providing field names. If more than one field + * name is provided, the path will point to a nested field in a document. + */ +class FieldPath { + /** + * Creates a `FieldPath` from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames - A list of field names. + */ + constructor(...t) { + for (let e = 0; e < t.length; ++e) if (0 === t[e].length) throw new FirestoreError(w, "Invalid field name at argument $(i + 1). Field names must not be empty."); + this._internalPath = new FieldPath$1(t); + } + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other - The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ isEqual(t) { + return this._internalPath.isEqual(t._internalPath); + } +} + +/** + * Returns a special sentinel `FieldPath` to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ function documentId() { + return new FieldPath(U); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Sentinel values that can be used when writing document fields with `set()` + * or `update()`. + */ class FieldValue { + /** + * @param _methodName - The public API endpoint that returns this class. + * @hideconstructor + */ + constructor(t) { + this._methodName = t; + } +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ class GeoPoint { + /** + * Creates a new immutable `GeoPoint` object with the provided latitude and + * longitude values. + * @param latitude - The latitude as number between -90 and 90. + * @param longitude - The longitude as number between -180 and 180. + */ + constructor(t, e) { + if (!isFinite(t) || t < -90 || t > 90) throw new FirestoreError(w, "Latitude must be a number between -90 and 90, but was: " + t); + if (!isFinite(e) || e < -180 || e > 180) throw new FirestoreError(w, "Longitude must be a number between -180 and 180, but was: " + e); + this._lat = t, this._long = e; + } + /** + * The latitude of this `GeoPoint` instance. + */ get latitude() { + return this._lat; + } + /** + * The longitude of this `GeoPoint` instance. + */ get longitude() { + return this._long; + } + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other - The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ isEqual(t) { + return this._lat === t._lat && this._long === t._long; + } + /** + * Actually private to JS consumers of our API, so this function is prefixed + * with an underscore. + */ _compareTo(t) { + return __PRIVATE_primitiveComparator(this._lat, t._lat) || __PRIVATE_primitiveComparator(this._long, t._long); + } + /** + * Returns a JSON-serializable representation of this `GeoPoint` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + latitude: this._lat, + longitude: this._long, + type: GeoPoint._jsonSchemaVersion + }; + } + /** + * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}. + * + * @param json a JSON object represention of a `GeoPoint` instance + * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ static fromJSON(t) { + if (__PRIVATE_validateJSON(t, GeoPoint._jsonSchema)) return new GeoPoint(t.latitude, t.longitude); + } +} + +GeoPoint._jsonSchemaVersion = "firestore/geoPoint/1.0", GeoPoint._jsonSchema = { + type: property("string", GeoPoint._jsonSchemaVersion), + latitude: property("number"), + longitude: property("number") +}; + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link vector}. + * + * @class VectorValue + */ +class VectorValue { + /** + * @private + * @internal + */ + constructor(t) { + // Making a copy of the parameter. + this._values = (t || []).map((t => t)); + } + /** + * Returns a copy of the raw number array form of the vector. + */ toArray() { + return this._values.map((t => t)); + } + /** + * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise. + */ isEqual(t) { + /** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Verifies equality for an array of primitives. + * + * @private + * @internal + * @param left Array of primitives. + * @param right Array of primitives. + * @return True if arrays are equal. + */ + return function __PRIVATE_isPrimitiveArrayEqual(t, e) { + if (t.length !== e.length) return !1; + for (let r = 0; r < t.length; ++r) if (t[r] !== e[r]) return !1; + return !0; + }(this._values, t._values); + } + /** + * Returns a JSON-serializable representation of this `VectorValue` instance. + * + * @returns a JSON representation of this object. + */ toJSON() { + return { + type: VectorValue._jsonSchemaVersion, + vectorValues: this._values + }; + } + /** + * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}. + * + * @param json a JSON object represention of a `VectorValue` instance. + * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ static fromJSON(t) { + if (__PRIVATE_validateJSON(t, VectorValue._jsonSchema)) { + if (Array.isArray(t.vectorValues) && t.vectorValues.every((t => "number" == typeof t))) return new VectorValue(t.vectorValues); + throw new FirestoreError(w, "Expected 'vectorValues' field to be a number array"); + } + } +} + +VectorValue._jsonSchemaVersion = "firestore/vectorValue/1.0", VectorValue._jsonSchema = { + type: property("string", VectorValue._jsonSchemaVersion), + vectorValues: property("object") +}; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const ft = /^__.*__$/; + +/** The result of parsing document data (e.g. for a setData call). */ class ParsedSetData { + constructor(t, e, r) { + this.data = t, this.fieldMask = e, this.fieldTransforms = r; + } + toMutation(t, e) { + return null !== this.fieldMask ? new __PRIVATE_PatchMutation(t, this.data, this.fieldMask, e, this.fieldTransforms) : new __PRIVATE_SetMutation(t, this.data, e, this.fieldTransforms); + } +} + +/** The result of parsing "update" data (i.e. for an updateData call). */ class ParsedUpdateData { + constructor(t, + // The fieldMask does not include document transforms. + e, r) { + this.data = t, this.fieldMask = e, this.fieldTransforms = r; + } + toMutation(t, e) { + return new __PRIVATE_PatchMutation(t, this.data, this.fieldMask, e, this.fieldTransforms); + } +} + +function __PRIVATE_isWrite(t) { + switch (t) { + case 0 /* UserDataSource.Set */ : + // fall through + case 2 /* UserDataSource.MergeSet */ : + // fall through + case 1 /* UserDataSource.Update */ : + return !0; + + case 3 /* UserDataSource.Argument */ : + case 4 /* UserDataSource.ArrayArgument */ : + return !1; + + default: + throw fail(40011, { + it: t + }); + } +} + +/** A "context" object passed around while parsing user data. */ class __PRIVATE_ParseContextImpl { + /** + * Initializes a ParseContext with the given source and path. + * + * @param settings - The settings for the parser. + * @param databaseId - The database ID of the Firestore instance. + * @param serializer - The serializer to use to generate the Value proto. + * @param ignoreUndefinedProperties - Whether to ignore undefined properties + * rather than throw. + * @param fieldTransforms - A mutable list of field transforms encountered + * while parsing the data. + * @param fieldMask - A mutable list of field paths encountered while parsing + * the data. + * + * TODO(b/34871131): We don't support array paths right now, so path can be + * null to indicate the context represents any location within an array (in + * which case certain features will not work and errors will be somewhat + * compromised). + */ + constructor(t, e, r, n, i, s) { + this.settings = t, this.databaseId = e, this.serializer = r, this.ignoreUndefinedProperties = n, + // Minor hack: If fieldTransforms is undefined, we assume this is an + // external call and we need to validate the entire path. + void 0 === i && this.st(), this.fieldTransforms = i || [], this.fieldMask = s || []; + } + get path() { + return this.settings.path; + } + get it() { + return this.settings.it; + } + /** Returns a new context with the specified settings overwritten. */ ot(t) { + return new __PRIVATE_ParseContextImpl({ + ...this.settings, + ...t + }, this.databaseId, this.serializer, this.ignoreUndefinedProperties, this.fieldTransforms, this.fieldMask); + } + ut(t) { + const e = this.path?.child(t), r = this.ot({ + path: e, + _t: !1 + }); + return r.ct(t), r; + } + lt(t) { + const e = this.path?.child(t), r = this.ot({ + path: e, + _t: !1 + }); + return r.st(), r; + } + ht(t) { + // TODO(b/34871131): We don't support array paths right now; so make path + // undefined. + return this.ot({ + path: void 0, + _t: !0 + }); + } + ft(t) { + return __PRIVATE_createError(t, this.settings.methodName, this.settings.dt || !1, this.path, this.settings.Et); + } + /** Returns 'true' if 'fieldPath' was traversed when creating this context. */ contains(t) { + return void 0 !== this.fieldMask.find((e => t.isPrefixOf(e))) || void 0 !== this.fieldTransforms.find((e => t.isPrefixOf(e.field))); + } + st() { + // TODO(b/34871131): Remove null check once we have proper paths for fields + // within arrays. + if (this.path) for (let t = 0; t < this.path.length; t++) this.ct(this.path.get(t)); + } + ct(t) { + if (0 === t.length) throw this.ft("Document fields must not be empty"); + if (__PRIVATE_isWrite(this.it) && ft.test(t)) throw this.ft('Document fields cannot begin and end with "__"'); + } +} + +/** + * Helper for parsing raw user input (provided via the API) into internal model + * classes. + */ class __PRIVATE_UserDataReader { + constructor(t, e, r) { + this.databaseId = t, this.ignoreUndefinedProperties = e, this.serializer = r || __PRIVATE_newSerializer(t); + } + /** Creates a new top-level parse context. */ Tt(t, e, r, n = !1) { + return new __PRIVATE_ParseContextImpl({ + it: t, + methodName: e, + Et: r, + path: FieldPath$1.emptyPath(), + _t: !1, + dt: n + }, this.databaseId, this.serializer, this.ignoreUndefinedProperties); + } +} + +function __PRIVATE_newUserDataReader(t) { + const e = t._freezeSettings(), r = __PRIVATE_newSerializer(t._databaseId); + return new __PRIVATE_UserDataReader(t._databaseId, !!e.ignoreUndefinedProperties, r); +} + +/** Parse document data from a set() call. */ function __PRIVATE_parseSetData(t, e, r, n, i, s = {}) { + const o = t.Tt(s.merge || s.mergeFields ? 2 /* UserDataSource.MergeSet */ : 0 /* UserDataSource.Set */ , e, r, i); + __PRIVATE_validatePlainObject("Data must be an object, but it was:", o, n); + const a = __PRIVATE_parseObject(n, o); + let u, _; + if (s.merge) u = new FieldMask(o.fieldMask), _ = o.fieldTransforms; else if (s.mergeFields) { + const t = []; + for (const n of s.mergeFields) { + const i = __PRIVATE_fieldPathFromArgument$1(e, n, r); + if (!o.contains(i)) throw new FirestoreError(w, `Field '${i}' is specified in your field mask but missing from your input data.`); + __PRIVATE_fieldMaskContains(t, i) || t.push(i); + } + u = new FieldMask(t), _ = o.fieldTransforms.filter((t => u.covers(t.field))); + } else u = null, _ = o.fieldTransforms; + return new ParsedSetData(new ObjectValue(a), u, _); +} + +class __PRIVATE_DeleteFieldValueImpl extends FieldValue { + _toFieldTransform(t) { + if (2 /* UserDataSource.MergeSet */ !== t.it) throw 1 /* UserDataSource.Update */ === t.it ? t.ft(`${this._methodName}() can only appear at the top level of your update data`) : t.ft(`${this._methodName}() cannot be used with set() unless you pass {merge:true}`); + // No transform to add for a delete, but we need to add it to our + // fieldMask so it gets deleted. + return t.fieldMask.push(t.path), null; + } + isEqual(t) { + return t instanceof __PRIVATE_DeleteFieldValueImpl; + } +} + +/** + * Creates a child context for parsing SerializableFieldValues. + * + * This is different than calling `ParseContext.contextWith` because it keeps + * the fieldTransforms and fieldMask separate. + * + * The created context has its `dataSource` set to `UserDataSource.Argument`. + * Although these values are used with writes, any elements in these FieldValues + * are not considered writes since they cannot contain any FieldValue sentinels, + * etc. + * + * @param fieldValue - The sentinel FieldValue for which to create a child + * context. + * @param context - The parent context. + * @param arrayElement - Whether or not the FieldValue has an array. + */ function __PRIVATE_createSentinelChildContext(t, e, r) { + return new __PRIVATE_ParseContextImpl({ + it: 3 /* UserDataSource.Argument */ , + Et: e.settings.Et, + methodName: t._methodName, + _t: r + }, e.databaseId, e.serializer, e.ignoreUndefinedProperties); +} + +class __PRIVATE_ServerTimestampFieldValueImpl extends FieldValue { + _toFieldTransform(t) { + return new FieldTransform(t.path, new __PRIVATE_ServerTimestampTransform); + } + isEqual(t) { + return t instanceof __PRIVATE_ServerTimestampFieldValueImpl; + } +} + +class __PRIVATE_ArrayUnionFieldValueImpl extends FieldValue { + constructor(t, e) { + super(t), this.Pt = e; + } + _toFieldTransform(t) { + const e = __PRIVATE_createSentinelChildContext(this, t, + /*array=*/ !0), r = this.Pt.map((t => __PRIVATE_parseData(t, e))), n = new __PRIVATE_ArrayUnionTransformOperation(r); + return new FieldTransform(t.path, n); + } + isEqual(t) { + return t instanceof __PRIVATE_ArrayUnionFieldValueImpl && E(this.Pt, t.Pt); + } +} + +class __PRIVATE_ArrayRemoveFieldValueImpl extends FieldValue { + constructor(t, e) { + super(t), this.Pt = e; + } + _toFieldTransform(t) { + const e = __PRIVATE_createSentinelChildContext(this, t, + /*array=*/ !0), r = this.Pt.map((t => __PRIVATE_parseData(t, e))), n = new __PRIVATE_ArrayRemoveTransformOperation(r); + return new FieldTransform(t.path, n); + } + isEqual(t) { + return t instanceof __PRIVATE_ArrayRemoveFieldValueImpl && E(this.Pt, t.Pt); + } +} + +class __PRIVATE_NumericIncrementFieldValueImpl extends FieldValue { + constructor(t, e) { + super(t), this.At = e; + } + _toFieldTransform(t) { + const e = new __PRIVATE_NumericIncrementTransformOperation(t.serializer, toNumber(t.serializer, this.At)); + return new FieldTransform(t.path, e); + } + isEqual(t) { + return t instanceof __PRIVATE_NumericIncrementFieldValueImpl && this.At === t.At; + } +} + +/** Parse update data from an update() call. */ function __PRIVATE_parseUpdateData(t, e, r, n) { + const i = t.Tt(1 /* UserDataSource.Update */ , e, r); + __PRIVATE_validatePlainObject("Data must be an object, but it was:", i, n); + const s = [], o = ObjectValue.empty(); + forEach(n, ((t, n) => { + const a = __PRIVATE_fieldPathFromDotSeparatedString(e, t, r); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + n = P(n); + const u = i.lt(a); + if (n instanceof __PRIVATE_DeleteFieldValueImpl) + // Add it to the field mask, but don't add anything to updateData. + s.push(a); else { + const t = __PRIVATE_parseData(n, u); + null != t && (s.push(a), o.set(a, t)); + } + })); + const a = new FieldMask(s); + return new ParsedUpdateData(o, a, i.fieldTransforms); +} + +/** Parse update data from a list of field/value arguments. */ function __PRIVATE_parseUpdateVarargs(t, e, r, n, i, s) { + const o = t.Tt(1 /* UserDataSource.Update */ , e, r), a = [ __PRIVATE_fieldPathFromArgument$1(e, n, r) ], u = [ i ]; + if (s.length % 2 != 0) throw new FirestoreError(w, `Function ${e}() needs to be called with an even number of arguments that alternate between field names and values.`); + for (let t = 0; t < s.length; t += 2) a.push(__PRIVATE_fieldPathFromArgument$1(e, s[t])), + u.push(s[t + 1]); + const _ = [], c = ObjectValue.empty(); + // We iterate in reverse order to pick the last value for a field if the + // user specified the field multiple times. + for (let t = a.length - 1; t >= 0; --t) if (!__PRIVATE_fieldMaskContains(_, a[t])) { + const e = a[t]; + let r = u[t]; + // For Compat types, we have to "extract" the underlying types before + // performing validation. + r = P(r); + const n = o.lt(e); + if (r instanceof __PRIVATE_DeleteFieldValueImpl) + // Add it to the field mask, but don't add anything to updateData. + _.push(e); else { + const t = __PRIVATE_parseData(r, n); + null != t && (_.push(e), c.set(e, t)); + } + } + const l = new FieldMask(_); + return new ParsedUpdateData(c, l, o.fieldTransforms); +} + +/** + * Parse a "query value" (e.g. value in a where filter or a value in a cursor + * bound). + * + * @param allowArrays - Whether the query value is an array that may directly + * contain additional arrays (e.g. the operand of an `in` query). + */ function __PRIVATE_parseQueryValue(t, e, r, n = !1) { + return __PRIVATE_parseData(r, t.Tt(n ? 4 /* UserDataSource.ArrayArgument */ : 3 /* UserDataSource.Argument */ , e)); +} + +/** + * Parses user data to Protobuf Values. + * + * @param input - Data to be parsed. + * @param context - A context object representing the current path being parsed, + * the source of the data being parsed, etc. + * @returns The parsed value, or null if the value was a FieldValue sentinel + * that should not be included in the resulting parsed data. + */ function __PRIVATE_parseData(t, e) { + if (__PRIVATE_looksLikeJsonObject( + // Unwrap the API type from the Compat SDK. This will return the API type + // from firestore-exp. + t = P(t))) return __PRIVATE_validatePlainObject("Unsupported field value:", e, t), + __PRIVATE_parseObject(t, e); + if (t instanceof FieldValue) + // FieldValues usually parse into transforms (except deleteField()) + // in which case we do not want to include this field in our parsed data + // (as doing so will overwrite the field directly prior to the transform + // trying to transform it). So we don't add this location to + // context.fieldMask and we return null as our parsing result. + /** + * "Parses" the provided FieldValueImpl, adding any necessary transforms to + * context.fieldTransforms. + */ + return function __PRIVATE_parseSentinelFieldValue(t, e) { + // Sentinels are only supported with writes, and not within arrays. + if (!__PRIVATE_isWrite(e.it)) throw e.ft(`${t._methodName}() can only be used with update() and set()`); + if (!e.path) throw e.ft(`${t._methodName}() is not currently supported inside arrays`); + const r = t._toFieldTransform(e); + r && e.fieldTransforms.push(r); + } + /** + * Helper to parse a scalar value (i.e. not an Object, Array, or FieldValue) + * + * @returns The parsed value + */ (t, e), null; + if (void 0 === t && e.ignoreUndefinedProperties) + // If the input is undefined it can never participate in the fieldMask, so + // don't handle this below. If `ignoreUndefinedProperties` is false, + // `parseScalarValue` will reject an undefined value. + return null; + if ( + // If context.path is null we are inside an array and we don't support + // field mask paths more granular than the top-level array. + e.path && e.fieldMask.push(e.path), t instanceof Array) { + // TODO(b/34871131): Include the path containing the array in the error + // message. + // In the case of IN queries, the parsed data is an array (representing + // the set of values to be included for the IN query) that may directly + // contain additional arrays (each representing an individual field + // value), so we disable this validation. + if (e.settings._t && 4 /* UserDataSource.ArrayArgument */ !== e.it) throw e.ft("Nested arrays are not supported"); + return function __PRIVATE_parseArray(t, e) { + const r = []; + let n = 0; + for (const i of t) { + let t = __PRIVATE_parseData(i, e.ht(n)); + null == t && ( + // Just include nulls in the array for fields being replaced with a + // sentinel. + t = { + nullValue: "NULL_VALUE" + }), r.push(t), n++; + } + return { + arrayValue: { + values: r + } + }; + }(t, e); + } + return function __PRIVATE_parseScalarValue(t, e) { + if (null === (t = P(t))) return { + nullValue: "NULL_VALUE" + }; + if ("number" == typeof t) return toNumber(e.serializer, t); + if ("boolean" == typeof t) return { + booleanValue: t + }; + if ("string" == typeof t) return { + stringValue: t + }; + if (t instanceof Date) { + const r = Timestamp.fromDate(t); + return { + timestampValue: toTimestamp(e.serializer, r) + }; + } + if (t instanceof Timestamp) { + // Firestore backend truncates precision down to microseconds. To ensure + // offline mode works the same with regards to truncation, perform the + // truncation immediately without waiting for the backend to do that. + const r = new Timestamp(t.seconds, 1e3 * Math.floor(t.nanoseconds / 1e3)); + return { + timestampValue: toTimestamp(e.serializer, r) + }; + } + if (t instanceof GeoPoint) return { + geoPointValue: { + latitude: t.latitude, + longitude: t.longitude + } + }; + if (t instanceof Bytes) return { + bytesValue: __PRIVATE_toBytes(e.serializer, t._byteString) + }; + if (t instanceof DocumentReference) { + const r = e.databaseId, n = t.firestore._databaseId; + if (!n.isEqual(r)) throw e.ft(`Document reference is for database ${n.projectId}/${n.database} but should be for database ${r.projectId}/${r.database}`); + return { + referenceValue: __PRIVATE_toResourceName(t.firestore._databaseId || e.databaseId, t._key.path) + }; + } + if (t instanceof VectorValue) + /** + * Creates a new VectorValue proto value (using the internal format). + */ + return function __PRIVATE_parseVectorValue(t, e) { + const r = { + fields: { + [tt]: { + stringValue: nt + }, + [it]: { + arrayValue: { + values: t.toArray().map((t => { + if ("number" != typeof t) throw e.ft("VectorValues must only contain numeric values."); + return __PRIVATE_toDouble(e.serializer, t); + })) + } + } + } + }; + return { + mapValue: r + }; + } + /** + * Checks whether an object looks like a JSON object that should be converted + * into a struct. Normal class/prototype instances are considered to look like + * JSON objects since they should be converted to a struct value. Arrays, Dates, + * GeoPoints, etc. are not considered to look like JSON objects since they map + * to specific FieldValue types other than ObjectValue. + */ (t, e); + throw e.ft(`Unsupported field value: ${__PRIVATE_valueDescription(t)}`); + }(t, e); +} + +function __PRIVATE_parseObject(t, e) { + const r = {}; + return !function isEmpty(t) { + for (const e in t) if (Object.prototype.hasOwnProperty.call(t, e)) return !1; + return !0; + }(t) ? forEach(t, ((t, n) => { + const i = __PRIVATE_parseData(n, e.ut(t)); + null != i && (r[t] = i); + })) : + // If we encounter an empty object, we explicitly add it to the update + // mask to ensure that the server creates a map entry. + e.path && e.path.length > 0 && e.fieldMask.push(e.path), { + mapValue: { + fields: r + } + }; +} + +function __PRIVATE_looksLikeJsonObject(t) { + return !("object" != typeof t || null === t || t instanceof Array || t instanceof Date || t instanceof Timestamp || t instanceof GeoPoint || t instanceof Bytes || t instanceof DocumentReference || t instanceof FieldValue || t instanceof VectorValue); +} + +function __PRIVATE_validatePlainObject(t, e, r) { + if (!__PRIVATE_looksLikeJsonObject(r) || !__PRIVATE_isPlainObject(r)) { + const n = __PRIVATE_valueDescription(r); + throw "an object" === n ? e.ft(t + " a custom object") : e.ft(t + " " + n); + } +} + +/** + * Helper that calls fromDotSeparatedString() but wraps any error thrown. + */ function __PRIVATE_fieldPathFromArgument$1(t, e, r) { + if (( + // If required, replace the FieldPath Compat class with the firestore-exp + // FieldPath. + e = P(e)) instanceof FieldPath) return e._internalPath; + if ("string" == typeof e) return __PRIVATE_fieldPathFromDotSeparatedString(t, e); + throw __PRIVATE_createError("Field path arguments must be of type string or ", t, + /* hasConverter= */ !1, + /* path= */ void 0, r); +} + +/** + * Matches any characters in a field path string that are reserved. + */ const dt = new RegExp("[~\\*/\\[\\]]"); + +/** + * Wraps fromDotSeparatedString with an error message about the method that + * was thrown. + * @param methodName - The publicly visible method name + * @param path - The dot-separated string form of a field path which will be + * split on dots. + * @param targetDoc - The document against which the field path will be + * evaluated. + */ function __PRIVATE_fieldPathFromDotSeparatedString(t, e, r) { + if (e.search(dt) >= 0) throw __PRIVATE_createError(`Invalid field path (${e}). Paths must not contain '~', '*', '/', '[', or ']'`, t, + /* hasConverter= */ !1, + /* path= */ void 0, r); + try { + return new FieldPath(...e.split("."))._internalPath; + } catch (n) { + throw __PRIVATE_createError(`Invalid field path (${e}). Paths must not be empty, begin with '.', end with '.', or contain '..'`, t, + /* hasConverter= */ !1, + /* path= */ void 0, r); + } +} + +function __PRIVATE_createError(t, e, r, n, i) { + const s = n && !n.isEmpty(), o = void 0 !== i; + let a = `Function ${e}() called with invalid data`; + r && (a += " (via `toFirestore()`)"), a += ". "; + let u = ""; + return (s || o) && (u += " (found", s && (u += ` in field ${n}`), o && (u += ` in document ${i}`), + u += ")"), new FirestoreError(w, a + t + u); +} + +/** Checks `haystack` if FieldPath `needle` is present. Runs in O(n). */ function __PRIVATE_fieldMaskContains(t, e) { + return t.some((t => t.isEqual(e))); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ class DocumentSnapshot { + // Note: This class is stripped down version of the DocumentSnapshot in + // the legacy SDK. The changes are: + // - No support for SnapshotMetadata. + // - No support for SnapshotOptions. + /** @hideconstructor protected */ + constructor(t, e, r, n, i) { + this._firestore = t, this._userDataWriter = e, this._key = r, this._document = n, + this._converter = i; + } + /** Property of the `DocumentSnapshot` that provides the document's ID. */ get id() { + return this._key.path.lastSegment(); + } + /** + * The `DocumentReference` for the document included in the `DocumentSnapshot`. + */ get ref() { + return new DocumentReference(this._firestore, this._converter, this._key); + } + /** + * Signals whether or not the document at the snapshot's location exists. + * + * @returns true if the document exists. + */ exists() { + return null !== this._document; + } + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * @returns An `Object` containing all fields in the document or `undefined` + * if the document doesn't exist. + */ data() { + if (this._document) { + if (this._converter) { + // We only want to use the converter and create a new DocumentSnapshot + // if a converter has been provided. + const t = new QueryDocumentSnapshot(this._firestore, this._userDataWriter, this._key, this._document, + /* converter= */ null); + return this._converter.fromFirestore(t); + } + return this._userDataWriter.convertValue(this._document.data.value); + } + } + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + // We are using `any` here to avoid an explicit cast by our users. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + get(t) { + if (this._document) { + const e = this._document.data.field(__PRIVATE_fieldPathFromArgument("DocumentSnapshot.get", t)); + if (null !== e) return this._userDataWriter.convertValue(e); + } + } +} + +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * @override + * @returns An `Object` containing all fields in the document. + */ + data() { + return super.data(); + } +} + +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ class QuerySnapshot { + /** @hideconstructor */ + constructor(t, e) { + this._docs = e, this.query = t; + } + /** An array of all the documents in the `QuerySnapshot`. */ get docs() { + return [ ...this._docs ]; + } + /** The number of documents in the `QuerySnapshot`. */ get size() { + return this.docs.length; + } + /** True if there are no documents in the `QuerySnapshot`. */ get empty() { + return 0 === this.docs.length; + } + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ forEach(t, e) { + this._docs.forEach(t, e); + } +} + +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ function snapshotEqual(t, e) { + return t = P(t), e = P(e), t instanceof DocumentSnapshot && e instanceof DocumentSnapshot ? t._firestore === e._firestore && t._key.isEqual(e._key) && (null === t._document ? null === e._document : t._document.isEqual(e._document)) && t._converter === e._converter : t instanceof QuerySnapshot && e instanceof QuerySnapshot && (queryEqual(t.query, e.query) && __PRIVATE_arrayEquals(t.docs, e.docs, snapshotEqual)); +} + +/** + * Helper that calls `fromDotSeparatedString()` but wraps any error thrown. + */ function __PRIVATE_fieldPathFromArgument(t, e) { + return "string" == typeof e ? __PRIVATE_fieldPathFromDotSeparatedString(t, e) : e instanceof FieldPath ? e._internalPath : e._delegate._internalPath; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An `AppliableConstraint` is an abstraction of a constraint that can be applied + * to a Firestore query. + */ +class AppliableConstraint {} + +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Firestore query. `QueryConstraint`s are created by invoking {@link where}, + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that + * also contains this `QueryConstraint`. + */ class QueryConstraint extends AppliableConstraint {} + +function query(t, e, ...r) { + let n = []; + e instanceof AppliableConstraint && n.push(e), n = n.concat(r), function __PRIVATE_validateQueryConstraintArray(t) { + const e = t.filter((t => t instanceof QueryCompositeFilterConstraint)).length, r = t.filter((t => t instanceof QueryFieldFilterConstraint)).length; + if (e > 1 || e > 0 && r > 0) throw new FirestoreError(w, "InvalidQuery. When using composite filters, you cannot use more than one filter at the top level. Consider nesting the multiple filters within an `and(...)` statement. For example: change `query(query, where(...), or(...))` to `query(query, and(where(...), or(...)))`."); + } + /** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** + * Converts Firestore's internal types to the JavaScript types that we expose + * to the user. + * + * @internal + */ (n); + for (const e of n) t = e._apply(t); + return t; +} + +/** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ class QueryFieldFilterConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(t, e, r) { + super(), this._field = t, this._op = e, this._value = r, + /** The type of this query constraint */ + this.type = "where"; + } + static _create(t, e, r) { + return new QueryFieldFilterConstraint(t, e, r); + } + _apply(t) { + const e = this._parse(t); + return __PRIVATE_validateNewFieldFilter(t._query, e), new Query(t.firestore, t.converter, __PRIVATE_queryWithAddedFilter(t._query, e)); + } + _parse(t) { + const e = __PRIVATE_newUserDataReader(t.firestore), r = function __PRIVATE_newQueryFilter(t, e, r, n, i, s, o) { + let a; + if (i.isKeyField()) { + if ("array-contains" /* Operator.ARRAY_CONTAINS */ === s || "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ === s) throw new FirestoreError(w, `Invalid Query. You can't perform '${s}' queries on documentId().`); + if ("in" /* Operator.IN */ === s || "not-in" /* Operator.NOT_IN */ === s) { + __PRIVATE_validateDisjunctiveFilterElements(o, s); + const e = []; + for (const r of o) e.push(__PRIVATE_parseDocumentIdValue(n, t, r)); + a = { + arrayValue: { + values: e + } + }; + } else a = __PRIVATE_parseDocumentIdValue(n, t, o); + } else "in" /* Operator.IN */ !== s && "not-in" /* Operator.NOT_IN */ !== s && "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ !== s || __PRIVATE_validateDisjunctiveFilterElements(o, s), + a = __PRIVATE_parseQueryValue(r, e, o, + /* allowArrays= */ "in" /* Operator.IN */ === s || "not-in" /* Operator.NOT_IN */ === s); + const u = FieldFilter.create(i, s, a); + return u; + }(t._query, "where", e, t.firestore._databaseId, this._field, this._op, this._value); + return r; + } +} + +/** + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. + * + * @param fieldPath - The path to compare + * @param opStr - The operation string (e.g "<", "<=", "==", "<", + * "<=", "!="). + * @param value - The value for comparison + * @returns The created {@link QueryFieldFilterConstraint}. + */ function where(t, e, r) { + const n = e, i = __PRIVATE_fieldPathFromArgument("where", t); + return QueryFieldFilterConstraint._create(i, n, r); +} + +/** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ class QueryCompositeFilterConstraint extends AppliableConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + t, e) { + super(), this.type = t, this._queryConstraints = e; + } + static _create(t, e) { + return new QueryCompositeFilterConstraint(t, e); + } + _parse(t) { + const e = this._queryConstraints.map((e => e._parse(t))).filter((t => t.getFilters().length > 0)); + return 1 === e.length ? e[0] : CompositeFilter.create(e, this._getOperator()); + } + _apply(t) { + const e = this._parse(t); + return 0 === e.getFilters().length ? t : (function __PRIVATE_validateNewFilter(t, e) { + let r = t; + const n = e.getFlattenedFilters(); + for (const t of n) __PRIVATE_validateNewFieldFilter(r, t), r = __PRIVATE_queryWithAddedFilter(r, t); + } + // Checks if any of the provided filter operators are included in the given list of filters and + // returns the first one that is, or null if none are. + (t._query, e), new Query(t.firestore, t.converter, __PRIVATE_queryWithAddedFilter(t._query, e))); + } + _getQueryConstraints() { + return this._queryConstraints; + } + _getOperator() { + return "and" === this.type ? "and" /* CompositeOperator.AND */ : "or" /* CompositeOperator.OR */; + } +} + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ function or(...t) { + // Only support QueryFilterConstraints + return t.forEach((t => __PRIVATE_validateQueryFilterConstraint("or", t))), QueryCompositeFilterConstraint._create("or" /* CompositeOperator.OR */ , t); +} + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ function and(...t) { + // Only support QueryFilterConstraints + return t.forEach((t => __PRIVATE_validateQueryFilterConstraint("and", t))), QueryCompositeFilterConstraint._create("and" /* CompositeOperator.AND */ , t); +} + +/** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ class QueryOrderByConstraint extends QueryConstraint { + /** + * @internal + */ + constructor(t, e) { + super(), this._field = t, this._direction = e, + /** The type of this query constraint */ + this.type = "orderBy"; + } + static _create(t, e) { + return new QueryOrderByConstraint(t, e); + } + _apply(t) { + const e = function __PRIVATE_newQueryOrderBy(t, e, r) { + if (null !== t.startAt) throw new FirestoreError(w, "Invalid query. You must not call startAt() or startAfter() before calling orderBy()."); + if (null !== t.endAt) throw new FirestoreError(w, "Invalid query. You must not call endAt() or endBefore() before calling orderBy()."); + const n = new OrderBy(e, r); + return n; + } + /** + * Create a `Bound` from a query and a document. + * + * Note that the `Bound` will always include the key of the document + * and so only the provided document will compare equal to the returned + * position. + * + * Will throw if the document does not contain all fields of the order by + * of the query or if any of the fields in the order by are an uncommitted + * server timestamp. + */ (t._query, this._field, this._direction); + return new Query(t.firestore, t.converter, function __PRIVATE_queryWithAddedOrderBy(t, e) { + // TODO(dimond): validate that orderBy does not list the same key twice. + const r = t.explicitOrderBy.concat([ e ]); + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, r, t.filters.slice(), t.limit, t.limitType, t.startAt, t.endAt); + }(t._query, e)); + } +} + +/** + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the + * specified field, optionally in descending order instead of ascending. + * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * + * @param fieldPath - The field to sort by. + * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @returns The created {@link QueryOrderByConstraint}. + */ function orderBy(t, e = "asc") { + const r = e, n = __PRIVATE_fieldPathFromArgument("orderBy", t); + return QueryOrderByConstraint._create(n, r); +} + +/** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ class QueryLimitConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + t, e, r) { + super(), this.type = t, this._limit = e, this._limitType = r; + } + static _create(t, e, r) { + return new QueryLimitConstraint(t, e, r); + } + _apply(t) { + return new Query(t.firestore, t.converter, function __PRIVATE_queryWithLimit(t, e, r) { + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), e, r, t.startAt, t.endAt); + }(t._query, this._limit, this._limitType)); + } +} + +/** + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ function limit(t) { + return __PRIVATE_validatePositiveNumber("limit", t), QueryLimitConstraint._create("limit", t, "F" /* LimitType.First */); +} + +/** + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. + * + * You must specify at least one `orderBy` clause for `limitToLast` queries, + * otherwise an exception will be thrown during execution. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ function limitToLast(t) { + return __PRIVATE_validatePositiveNumber("limitToLast", t), QueryLimitConstraint._create("limitToLast", t, "L" /* LimitType.Last */); +} + +/** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ class QueryStartAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + t, e, r) { + super(), this.type = t, this._docOrFields = e, this._inclusive = r; + } + static _create(t, e, r) { + return new QueryStartAtConstraint(t, e, r); + } + _apply(t) { + const e = __PRIVATE_newQueryBoundFromDocOrFields(t, this.type, this._docOrFields, this._inclusive); + return new Query(t.firestore, t.converter, function __PRIVATE_queryWithStartAt(t, e) { + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, e, t.endAt); + }(t._query, e)); + } +} + +function startAt(...t) { + return QueryStartAtConstraint._create("startAt", t, + /*inclusive=*/ !0); +} + +function startAfter(...t) { + return QueryStartAtConstraint._create("startAfter", t, + /*inclusive=*/ !1); +} + +/** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ class QueryEndAtConstraint extends QueryConstraint { + /** + * @internal + */ + constructor( + /** The type of this query constraint */ + t, e, r) { + super(), this.type = t, this._docOrFields = e, this._inclusive = r; + } + static _create(t, e, r) { + return new QueryEndAtConstraint(t, e, r); + } + _apply(t) { + const e = __PRIVATE_newQueryBoundFromDocOrFields(t, this.type, this._docOrFields, this._inclusive); + return new Query(t.firestore, t.converter, function __PRIVATE_queryWithEndAt(t, e) { + return new __PRIVATE_QueryImpl(t.path, t.collectionGroup, t.explicitOrderBy.slice(), t.filters.slice(), t.limit, t.limitType, t.startAt, e); + }(t._query, e)); + } +} + +function endBefore(...t) { + return QueryEndAtConstraint._create("endBefore", t, + /*inclusive=*/ !1); +} + +function endAt(...t) { + return QueryEndAtConstraint._create("endAt", t, + /*inclusive=*/ !0); +} + +/** Helper function to create a bound from a document or fields */ function __PRIVATE_newQueryBoundFromDocOrFields(t, e, r, n) { + if (r[0] = P(r[0]), r[0] instanceof DocumentSnapshot) return function __PRIVATE_newQueryBoundFromDocument(t, e, r, n, i) { + if (!n) throw new FirestoreError(v, `Can't use a DocumentSnapshot that doesn't exist for ${r}().`); + const s = []; + // Because people expect to continue/end a query at the exact document + // provided, we need to use the implicit sort order rather than the explicit + // sort order, because it's guaranteed to contain the document key. That way + // the position becomes unambiguous and the query continues/ends exactly at + // the provided document. Without the key (by using the explicit sort + // orders), multiple documents could match the position, yielding duplicate + // results. + for (const r of __PRIVATE_queryNormalizedOrderBy(t)) if (r.field.isKeyField()) s.push(__PRIVATE_refValue(e, n.key)); else { + const t = n.data.field(r.field); + if (__PRIVATE_isServerTimestamp(t)) throw new FirestoreError(w, 'Invalid query. You are trying to start or end a query using a document for which the field "' + r.field + '" is an uncommitted server timestamp. (Since the value of this field is unknown, you cannot start/end a query with it.)'); + if (null === t) { + const t = r.field.canonicalString(); + throw new FirestoreError(w, `Invalid query. You are trying to start or end a query using a document for which the field '${t}' (used as the orderBy) does not exist.`); + } + s.push(t); + } + return new Bound(s, i); + } + /** + * Converts a list of field values to a `Bound` for the given query. + */ (t._query, t.firestore._databaseId, e, r[0]._document, n); + { + const i = __PRIVATE_newUserDataReader(t.firestore); + return function __PRIVATE_newQueryBoundFromFields(t, e, r, n, i, s) { + // Use explicit order by's because it has to match the query the user made + const o = t.explicitOrderBy; + if (i.length > o.length) throw new FirestoreError(w, `Too many arguments provided to ${n}(). The number of arguments must be less than or equal to the number of orderBy() clauses`); + const a = []; + for (let s = 0; s < i.length; s++) { + const u = i[s]; + if (o[s].field.isKeyField()) { + if ("string" != typeof u) throw new FirestoreError(w, `Invalid query. Expected a string for document ID in ${n}(), but got a ${typeof u}`); + if (!__PRIVATE_isCollectionGroupQuery(t) && -1 !== u.indexOf("/")) throw new FirestoreError(w, `Invalid query. When querying a collection and ordering by documentId(), the value passed to ${n}() must be a plain document ID, but '${u}' contains a slash.`); + const r = t.path.child(ResourcePath.fromString(u)); + if (!DocumentKey.isDocumentKey(r)) throw new FirestoreError(w, `Invalid query. When querying a collection group and ordering by documentId(), the value passed to ${n}() must result in a valid document path, but '${r}' is not because it contains an odd number of segments.`); + const i = new DocumentKey(r); + a.push(__PRIVATE_refValue(e, i)); + } else { + const t = __PRIVATE_parseQueryValue(r, n, u); + a.push(t); + } + } + return new Bound(a, s); + } + /** + * Parses the given `documentIdValue` into a `ReferenceValue`, throwing + * appropriate errors if the value is anything other than a `DocumentReference` + * or `string`, or if the string is malformed. + */ (t._query, t.firestore._databaseId, i, e, r, n); + } +} + +function __PRIVATE_parseDocumentIdValue(t, e, r) { + if ("string" == typeof (r = P(r))) { + if ("" === r) throw new FirestoreError(w, "Invalid query. When querying with documentId(), you must provide a valid document ID, but it was an empty string."); + if (!__PRIVATE_isCollectionGroupQuery(e) && -1 !== r.indexOf("/")) throw new FirestoreError(w, `Invalid query. When querying a collection by documentId(), you must provide a plain document ID, but '${r}' contains a '/' character.`); + const n = e.path.child(ResourcePath.fromString(r)); + if (!DocumentKey.isDocumentKey(n)) throw new FirestoreError(w, `Invalid query. When querying a collection group by documentId(), the value provided must result in a valid document path, but '${n}' is not because it has an odd number of segments (${n.length}).`); + return __PRIVATE_refValue(t, new DocumentKey(n)); + } + if (r instanceof DocumentReference) return __PRIVATE_refValue(t, r._key); + throw new FirestoreError(w, `Invalid query. When querying with documentId(), you must provide a valid string or a DocumentReference, but it was: ${__PRIVATE_valueDescription(r)}.`); +} + +/** + * Validates that the value passed into a disjunctive filter satisfies all + * array requirements. + */ function __PRIVATE_validateDisjunctiveFilterElements(t, e) { + if (!Array.isArray(t) || 0 === t.length) throw new FirestoreError(w, `Invalid Query. A non-empty array is required for '${e.toString()}' filters.`); +} + +/** + * Given an operator, returns the set of operators that cannot be used with it. + * + * This is not a comprehensive check, and this function should be removed in the + * long term. Validations should occur in the Firestore backend. + * + * Operators in a query must adhere to the following set of rules: + * 1. Only one inequality per query. + * 2. `NOT_IN` cannot be used with array, disjunctive, or `NOT_EQUAL` operators. + */ function __PRIVATE_validateNewFieldFilter(t, e) { + const r = function __PRIVATE_findOpInsideFilters(t, e) { + for (const r of t) for (const t of r.getFlattenedFilters()) if (e.indexOf(t.op) >= 0) return t.op; + return null; + }(t.filters, function __PRIVATE_conflictingOps(t) { + switch (t) { + case "!=" /* Operator.NOT_EQUAL */ : + return [ "!=" /* Operator.NOT_EQUAL */ , "not-in" /* Operator.NOT_IN */ ]; + + case "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ : + case "in" /* Operator.IN */ : + return [ "not-in" /* Operator.NOT_IN */ ]; + + case "not-in" /* Operator.NOT_IN */ : + return [ "array-contains-any" /* Operator.ARRAY_CONTAINS_ANY */ , "in" /* Operator.IN */ , "not-in" /* Operator.NOT_IN */ , "!=" /* Operator.NOT_EQUAL */ ]; + + default: + return []; + } + }(e.op)); + if (null !== r) + // Special case when it's a duplicate op to give a slightly clearer error message. + throw r === e.op ? new FirestoreError(w, `Invalid query. You cannot use more than one '${e.op.toString()}' filter.`) : new FirestoreError(w, `Invalid query. You cannot use '${e.op.toString()}' filters with '${r.toString()}' filters.`); +} + +function __PRIVATE_validateQueryFilterConstraint(t, e) { + if (!(e instanceof QueryFieldFilterConstraint || e instanceof QueryCompositeFilterConstraint)) throw new FirestoreError(w, `Function ${t}() requires AppliableConstraints created with a call to 'where(...)', 'or(...)', or 'and(...)'.`); +} + +class AbstractUserDataWriter { + convertValue(t, e = "none") { + switch (__PRIVATE_typeOrder(t)) { + case 0 /* TypeOrder.NullValue */ : + return null; + + case 1 /* TypeOrder.BooleanValue */ : + return t.booleanValue; + + case 2 /* TypeOrder.NumberValue */ : + return __PRIVATE_normalizeNumber(t.integerValue || t.doubleValue); + + case 3 /* TypeOrder.TimestampValue */ : + return this.convertTimestamp(t.timestampValue); + + case 4 /* TypeOrder.ServerTimestampValue */ : + return this.convertServerTimestamp(t, e); + + case 5 /* TypeOrder.StringValue */ : + return t.stringValue; + + case 6 /* TypeOrder.BlobValue */ : + return this.convertBytes(__PRIVATE_normalizeByteString(t.bytesValue)); + + case 7 /* TypeOrder.RefValue */ : + return this.convertReference(t.referenceValue); + + case 8 /* TypeOrder.GeoPointValue */ : + return this.convertGeoPoint(t.geoPointValue); + + case 9 /* TypeOrder.ArrayValue */ : + return this.convertArray(t.arrayValue, e); + + case 11 /* TypeOrder.ObjectValue */ : + return this.convertObject(t.mapValue, e); + + case 10 /* TypeOrder.VectorValue */ : + return this.convertVectorValue(t.mapValue); + + default: + throw fail(62114, { + value: t + }); + } + } + convertObject(t, e) { + return this.convertObjectMap(t.fields, e); + } + /** + * @internal + */ convertObjectMap(t, e = "none") { + const r = {}; + return forEach(t, ((t, n) => { + r[t] = this.convertValue(n, e); + })), r; + } + /** + * @internal + */ convertVectorValue(t) { + const e = t.fields?.[it].arrayValue?.values?.map((t => __PRIVATE_normalizeNumber(t.doubleValue))); + return new VectorValue(e); + } + convertGeoPoint(t) { + return new GeoPoint(__PRIVATE_normalizeNumber(t.latitude), __PRIVATE_normalizeNumber(t.longitude)); + } + convertArray(t, e) { + return (t.values || []).map((t => this.convertValue(t, e))); + } + convertServerTimestamp(t, e) { + switch (e) { + case "previous": + const r = __PRIVATE_getPreviousValue(t); + return null == r ? null : this.convertValue(r, e); + + case "estimate": + return this.convertTimestamp(__PRIVATE_getLocalWriteTime(t)); + + default: + return null; + } + } + convertTimestamp(t) { + const e = __PRIVATE_normalizeTimestamp(t); + return new Timestamp(e.seconds, e.nanos); + } + convertDocumentKey(t, e) { + const r = ResourcePath.fromString(t); + __PRIVATE_hardAssert(__PRIVATE_isValidResourceName(r), 9688, { + name: t + }); + const n = new DatabaseId(r.get(1), r.get(3)), i = new DocumentKey(r.popFirst(5)); + return n.isEqual(e) || + // TODO(b/64130202): Somehow support foreign references. + __PRIVATE_logError(`Document ${i} contains a document reference within a different database (${n.projectId}/${n.database}) which is not supported. It will be treated as a reference in the current database (${e.projectId}/${e.database}) instead.`), + i; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Converts custom model object of type T into `DocumentData` by applying the + * converter if it exists. + * + * This function is used when converting user objects to `DocumentData` + * because we want to provide the user with a more specific error message if + * their `set()` or fails due to invalid data originating from a `toFirestore()` + * call. + */ function __PRIVATE_applyFirestoreDataConverter(t, e, r) { + let n; + // Cast to `any` in order to satisfy the union type constraint on + // toFirestore(). + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return n = t ? r && (r.merge || r.mergeFields) ? t.toFirestore(e, r) : t.toFirestore(e) : e, + n; +} + +class __PRIVATE_LiteUserDataWriter extends AbstractUserDataWriter { + constructor(t) { + super(), this.firestore = t; + } + convertBytes(t) { + return new Bytes(t); + } + convertReference(t) { + const e = this.convertDocumentKey(t, this.firestore._databaseId); + return new DocumentReference(this.firestore, /* converter= */ null, e); + } +} + +/** + * Reads the document referred to by the specified document reference. + * + * All documents are directly fetched from the server, even if the document was + * previously read or modified. Recent modifications are only reflected in the + * retrieved `DocumentSnapshot` if they have already been applied by the + * backend. If the client is offline, the read fails. If you like to use + * caching or see local modifications, please use the full Firestore SDK. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the current + * document contents. + */ function getDoc(t) { + const e = __PRIVATE_getDatastore((t = __PRIVATE_cast(t, DocumentReference)).firestore), r = new __PRIVATE_LiteUserDataWriter(t.firestore); + return __PRIVATE_invokeBatchGetDocumentsRpc(e, [ t._key ]).then((e => { + __PRIVATE_hardAssert(1 === e.length, 15618); + const n = e[0]; + return new DocumentSnapshot(t.firestore, r, t._key, n.isFoundDocument() ? n : null, t.converter); + })); +} + +/** + * Executes the query and returns the results as a {@link QuerySnapshot}. + * + * All queries are executed directly by the server, even if the query was + * previously executed. Recent modifications are only reflected in the retrieved + * results if they have already been applied by the backend. If the client is + * offline, the operation fails. To see previously cached result and local + * modifications, use the full Firestore SDK. + * + * @param query - The `Query` to execute. + * @returns A Promise that will be resolved with the results of the query. + */ function getDocs(t) { + (function __PRIVATE_validateHasExplicitOrderByForLimitToLast(t) { + if ("L" /* LimitType.Last */ === t.limitType && 0 === t.explicitOrderBy.length) throw new FirestoreError(B, "limitToLast() queries require specifying at least one orderBy() clause"); + })((t = __PRIVATE_cast(t, Query))._query); + const e = __PRIVATE_getDatastore(t.firestore), r = new __PRIVATE_LiteUserDataWriter(t.firestore); + return __PRIVATE_invokeRunQueryRpc(e, t._query).then((e => { + const n = e.map((e => new QueryDocumentSnapshot(t.firestore, r, e.key, e, t.converter))); + return "L" /* LimitType.Last */ === t._query.limitType && + // Limit to last queries reverse the orderBy constraint that was + // specified by the user. As such, we need to reverse the order of the + // results to return the documents in the expected order. + n.reverse(), new QuerySnapshot(t, n); + })); +} + +function setDoc(t, e, r) { + const n = __PRIVATE_applyFirestoreDataConverter((t = __PRIVATE_cast(t, DocumentReference)).converter, e, r), i = __PRIVATE_parseSetData(__PRIVATE_newUserDataReader(t.firestore), "setDoc", t._key, n, null !== t.converter, r); + return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore(t.firestore), [ i.toMutation(t._key, Precondition.none()) ]); +} + +function updateDoc(t, e, r, ...n) { + const i = __PRIVATE_newUserDataReader((t = __PRIVATE_cast(t, DocumentReference)).firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + let s; + s = "string" == typeof (e = P(e)) || e instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(i, "updateDoc", t._key, e, r, n) : __PRIVATE_parseUpdateData(i, "updateDoc", t._key, e); + return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore(t.firestore), [ s.toMutation(t._key, Precondition.exists(!0)) ]); +} + +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * The deletion will only be reflected in document reads that occur after the + * returned promise resolves. If the client is offline, the + * delete fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to delete. + * @returns A `Promise` resolved once the document has been successfully + * deleted from the backend. + */ function deleteDoc(t) { + return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore((t = __PRIVATE_cast(t, DocumentReference)).firestore), [ new __PRIVATE_DeleteMutation(t._key, Precondition.none()) ]); +} + +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend. + */ function addDoc(t, e) { + const r = doc(t = __PRIVATE_cast(t, CollectionReference)), n = __PRIVATE_applyFirestoreDataConverter(t.converter, e), i = __PRIVATE_parseSetData(__PRIVATE_newUserDataReader(t.firestore), "addDoc", r._key, n, null !== r.converter, {}); + return __PRIVATE_invokeCommitRpc(__PRIVATE_getDatastore(t.firestore), [ i.toMutation(r._key, Precondition.exists(!1)) ]).then((() => r)); +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ function getCount(t) { + return getAggregate(t, { + count: count() + }); +} + +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregate(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ function getAggregate(t, e) { + const r = __PRIVATE_cast(t.firestore, Firestore), n = __PRIVATE_getDatastore(r), i = function __PRIVATE_mapToArray(t, e) { + const r = []; + for (const n in t) Object.prototype.hasOwnProperty.call(t, n) && r.push(e(t[n], n, t)); + return r; + }(e, ((t, e) => new __PRIVATE_AggregateImpl(e, t.aggregateType, t._internalFieldPath))); + // Run the aggregation and convert the results + return __PRIVATE_invokeRunAggregationQueryRpc(n, t._query, i).then((e => function __PRIVATE_convertToAggregateQuerySnapshot(t, e, r) { + const n = new __PRIVATE_LiteUserDataWriter(t), i = new AggregateQuerySnapshot(e, n, r); + return i; + } + /** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ (r, t, e))); +} + +function sum(t) { + return new AggregateField("sum", __PRIVATE_fieldPathFromArgument$1("sum", t)); +} + +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ function average(t) { + return new AggregateField("avg", __PRIVATE_fieldPathFromArgument$1("average", t)); +} + +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ function count() { + return new AggregateField("count"); +} + +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ function aggregateFieldEqual(t, e) { + return t instanceof AggregateField && e instanceof AggregateField && t.aggregateType === e.aggregateType && t._internalFieldPath?.canonicalString() === e._internalFieldPath?.canonicalString(); +} + +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ function aggregateQuerySnapshotEqual(t, e) { + return queryEqual(t.query, e.query) && E(t.data(), e.data()); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. + */ function deleteField() { + return new __PRIVATE_DeleteFieldValueImpl("deleteField"); +} + +/** + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to + * include a server-generated timestamp in the written data. + */ function serverTimestamp() { + return new __PRIVATE_ServerTimestampFieldValueImpl("serverTimestamp"); +} + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array + * value that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements - The elements to union into the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()`. + */ function arrayUnion(...t) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new __PRIVATE_ArrayUnionFieldValueImpl("arrayUnion", t); +} + +/** + * Returns a special value that can be used with {@link (setDoc:1)} or {@link + * updateDoc:1} that tells the server to remove the given elements from any + * array value that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is not + * already an array it will be overwritten with an empty array. + * + * @param elements - The elements to remove from the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ function arrayRemove(...t) { + // NOTE: We don't actually parse the data until it's used in set() or + // update() since we'd need the Firestore instance to do this. + return new __PRIVATE_ArrayRemoveFieldValueImpl("arrayRemove", t); +} + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by + * the given value. + * + * If either the operand or the current field value uses floating point + * precision, all arithmetic follows IEEE 754 semantics. If both values are + * integers, values outside of JavaScript's safe number range + * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to + * precision loss. Furthermore, once processed by the Firestore backend, all + * integer operations are capped between -2^63 and 2^63-1. + * + * If the current field value is not of type `number`, or if the field does not + * yet exist, the transformation sets the field to the given value. + * + * @param n - The value to increment by. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ function increment(t) { + return new __PRIVATE_NumericIncrementFieldValueImpl("increment", t); +} + +/** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ function vector(t) { + return new VectorValue(t); +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It + * provides methods for adding writes to the write batch. None of the writes + * will be committed (or visible locally) until {@link WriteBatch.commit} is + * called. + */ class WriteBatch { + /** @hideconstructor */ + constructor(t, e) { + this._firestore = t, this._commitHandler = e, this._mutations = [], this._committed = !1, + this._dataReader = __PRIVATE_newUserDataReader(t); + } + set(t, e, r) { + this._verifyNotCommitted(); + const n = __PRIVATE_validateReference(t, this._firestore), i = __PRIVATE_applyFirestoreDataConverter(n.converter, e, r), s = __PRIVATE_parseSetData(this._dataReader, "WriteBatch.set", n._key, i, null !== n.converter, r); + return this._mutations.push(s.toMutation(n._key, Precondition.none())), this; + } + update(t, e, r, ...n) { + this._verifyNotCommitted(); + const i = __PRIVATE_validateReference(t, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + let s; + return s = "string" == typeof (e = P(e)) || e instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(this._dataReader, "WriteBatch.update", i._key, e, r, n) : __PRIVATE_parseUpdateData(this._dataReader, "WriteBatch.update", i._key, e), + this._mutations.push(s.toMutation(i._key, Precondition.exists(!0))), this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ delete(t) { + this._verifyNotCommitted(); + const e = __PRIVATE_validateReference(t, this._firestore); + return this._mutations = this._mutations.concat(new __PRIVATE_DeleteMutation(e._key, Precondition.none())), + this; + } + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `Promise` resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit (note that it won't + * resolve while you're offline). + */ commit() { + return this._verifyNotCommitted(), this._committed = !0, this._mutations.length > 0 ? this._commitHandler(this._mutations) : Promise.resolve(); + } + _verifyNotCommitted() { + if (this._committed) throw new FirestoreError(N, "A write batch can no longer be used after commit() has been called."); + } +} + +function __PRIVATE_validateReference(t, e) { + if ((t = P(t)).firestore !== e) throw new FirestoreError(w, "Provided document reference is from a different Firestore instance."); + return t; +} + +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single WriteBatch + * is 500. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `WriteBatch` that can be used to atomically execute multiple + * writes. + */ function writeBatch(t) { + const e = __PRIVATE_getDatastore(t = __PRIVATE_cast(t, Firestore)); + return new WriteBatch(t, (t => __PRIVATE_invokeCommitRpc(e, t))); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Internal transaction object responsible for accumulating the mutations to + * perform and the base versions for any documents read. + */ class Transaction$1 { + constructor(t) { + this.datastore = t, + // The version of each document that was read during this transaction. + this.readVersions = new Map, this.mutations = [], this.committed = !1, + /** + * A deferred usage error that occurred previously in this transaction that + * will cause the transaction to fail once it actually commits. + */ + this.lastTransactionError = null, + /** + * Set of documents that have been written in the transaction. + * + * When there's more than one write to the same key in a transaction, any + * writes after the first are handled differently. + */ + this.writtenDocs = new Set; + } + async lookup(t) { + if (this.ensureCommitNotCalled(), this.mutations.length > 0) throw this.lastTransactionError = new FirestoreError(w, "Firestore transactions require all reads to be executed before all writes."), + this.lastTransactionError; + const e = await __PRIVATE_invokeBatchGetDocumentsRpc(this.datastore, t); + return e.forEach((t => this.recordVersion(t))), e; + } + set(t, e) { + this.write(e.toMutation(t, this.precondition(t))), this.writtenDocs.add(t.toString()); + } + update(t, e) { + try { + this.write(e.toMutation(t, this.preconditionForUpdate(t))); + } catch (t) { + this.lastTransactionError = t; + } + this.writtenDocs.add(t.toString()); + } + delete(t) { + this.write(new __PRIVATE_DeleteMutation(t, this.precondition(t))), this.writtenDocs.add(t.toString()); + } + async commit() { + if (this.ensureCommitNotCalled(), this.lastTransactionError) throw this.lastTransactionError; + const t = this.readVersions; + // For each mutation, note that the doc was written. + this.mutations.forEach((e => { + t.delete(e.key.toString()); + })), + // For each document that was read but not written to, we want to perform + // a `verify` operation. + t.forEach(((t, e) => { + const r = DocumentKey.fromPath(e); + this.mutations.push(new __PRIVATE_VerifyMutation(r, this.precondition(r))); + })), await __PRIVATE_invokeCommitRpc(this.datastore, this.mutations), this.committed = !0; + } + recordVersion(t) { + let e; + if (t.isFoundDocument()) e = t.version; else { + if (!t.isNoDocument()) throw fail(50498, { + Rt: t.constructor.name + }); + // Represent a deleted doc using SnapshotVersion.min(). + e = SnapshotVersion.min(); + } + const r = this.readVersions.get(t.key.toString()); + if (r) { + if (!e.isEqual(r)) + // This transaction will fail no matter what. + throw new FirestoreError(O, "Document version changed between two reads."); + } else this.readVersions.set(t.key.toString(), e); + } + /** + * Returns the version of this document when it was read in this transaction, + * as a precondition, or no precondition if it was not read. + */ precondition(t) { + const e = this.readVersions.get(t.toString()); + return !this.writtenDocs.has(t.toString()) && e ? e.isEqual(SnapshotVersion.min()) ? Precondition.exists(!1) : Precondition.updateTime(e) : Precondition.none(); + } + /** + * Returns the precondition for a document if the operation is an update. + */ preconditionForUpdate(t) { + const e = this.readVersions.get(t.toString()); + // The first time a document is written, we want to take into account the + // read time and existence + if (!this.writtenDocs.has(t.toString()) && e) { + if (e.isEqual(SnapshotVersion.min())) + // The document doesn't exist, so fail the transaction. + // This has to be validated locally because you can't send a + // precondition that a document does not exist without changing the + // semantics of the backend write to be an insert. This is the reverse + // of what we want, since we want to assert that the document doesn't + // exist but then send the update and have it fail. Since we can't + // express that to the backend, we have to validate locally. + // Note: this can change once we can send separate verify writes in the + // transaction. + throw new FirestoreError(w, "Can't update a document that doesn't exist."); + // Document exists, base precondition on document update time. + return Precondition.updateTime(e); + } + // Document was not read, so we just use the preconditions for a blind + // update. + return Precondition.exists(!0); + } + write(t) { + this.ensureCommitNotCalled(), this.mutations.push(t); + } + ensureCommitNotCalled() {} +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const mt = { + maxAttempts: 5 +}; + +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * TransactionRunner encapsulates the logic needed to run and retry transactions + * with backoff. + */ +class __PRIVATE_TransactionRunner { + constructor(t, e, r, n, i) { + this.asyncQueue = t, this.datastore = e, this.options = r, this.updateFunction = n, + this.deferred = i, this.Vt = r.maxAttempts, this.It = new __PRIVATE_ExponentialBackoff(this.asyncQueue, "transaction_retry" /* TimerId.TransactionRetry */); + } + /** Runs the transaction and sets the result on deferred. */ yt() { + this.Vt -= 1, this.gt(); + } + gt() { + this.It.Z((async () => { + const t = new Transaction$1(this.datastore), e = this.wt(t); + e && e.then((e => { + this.asyncQueue.enqueueAndForget((() => t.commit().then((() => { + this.deferred.resolve(e); + })).catch((t => { + this.Ft(t); + })))); + })).catch((t => { + this.Ft(t); + })); + })); + } + wt(t) { + try { + const e = this.updateFunction(t); + return !__PRIVATE_isNullOrUndefined(e) && e.catch && e.then ? e : (this.deferred.reject(Error("Transaction callback must return a Promise")), + null); + } catch (t) { + // Do not retry errors thrown by user provided updateFunction. + return this.deferred.reject(t), null; + } + } + Ft(t) { + this.Vt > 0 && this.vt(t) ? (this.Vt -= 1, this.asyncQueue.enqueueAndForget((() => (this.gt(), + Promise.resolve())))) : this.deferred.reject(t); + } + vt(t) { + if ("FirebaseError" === t?.name) { + // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and + // non-matching document versions with ABORTED. These errors should be retried. + const e = t.code; + return "aborted" === e || "failed-precondition" === e || "already-exists" === e || ! + /** + * Determines whether an error code represents a permanent error when received + * in response to a non-write operation. + * + * See isPermanentWriteError for classifying write errors. + */ + function __PRIVATE_isPermanentError(t) { + switch (t) { + case p: + return fail(64938); + + case y: + case g: + case F: + case C: + case $: + case Q: + // Unauthenticated means something went wrong with our token and we need + // to retry with new credentials which will happen automatically. + case S: + return !1; + + case w: + case v: + case D: + case b: + case N: + // Aborted might be retried in some scenarios, but that is dependent on + // the context and should handled individually by the calling code. + // See https://cloud.google.com/apis/design/errors. + case O: + case q: + case B: + case k: + return !0; + + default: + return fail(15467, { + code: t + }); + } + }(e); + } + return !1; + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** The Platform's 'document' implementation or null if not available. */ function getDocument() { + // `document` is not always available, e.g. in ReactNative and WebWorkers. + // eslint-disable-next-line no-restricted-globals + return "undefined" != typeof document ? document : null; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Represents an operation scheduled to be run in the future on an AsyncQueue. + * + * It is created via DelayedOperation.createAndSchedule(). + * + * Supports cancellation (via cancel()) and early execution (via skipDelay()). + * + * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type + * in newer versions of TypeScript defines `finally`, which is not available in + * IE. + */ class DelayedOperation { + constructor(t, e, r, n, i) { + this.asyncQueue = t, this.timerId = e, this.targetTimeMs = r, this.op = n, this.removalCallback = i, + this.deferred = new __PRIVATE_Deferred, this.then = this.deferred.promise.then.bind(this.deferred.promise), + // It's normal for the deferred promise to be canceled (due to cancellation) + // and so we attach a dummy catch callback to avoid + // 'UnhandledPromiseRejectionWarning' log spam. + this.deferred.promise.catch((t => {})); + } + get promise() { + return this.deferred.promise; + } + /** + * Creates and returns a DelayedOperation that has been scheduled to be + * executed on the provided asyncQueue after the provided delayMs. + * + * @param asyncQueue - The queue to schedule the operation on. + * @param id - A Timer ID identifying the type of operation this is. + * @param delayMs - The delay (ms) before the operation should be scheduled. + * @param op - The operation to run. + * @param removalCallback - A callback to be called synchronously once the + * operation is executed or canceled, notifying the AsyncQueue to remove it + * from its delayedOperations list. + * PORTING NOTE: This exists to prevent making removeDelayedOperation() and + * the DelayedOperation class public. + */ static createAndSchedule(t, e, r, n, i) { + const s = Date.now() + r, o = new DelayedOperation(t, e, s, n, i); + return o.start(r), o; + } + /** + * Starts the timer. This is called immediately after construction by + * createAndSchedule(). + */ start(t) { + this.timerHandle = setTimeout((() => this.handleDelayElapsed()), t); + } + /** + * Queues the operation to run immediately (if it hasn't already been run or + * canceled). + */ skipDelay() { + return this.handleDelayElapsed(); + } + /** + * Cancels the operation if it hasn't already been executed or canceled. The + * promise will be rejected. + * + * As long as the operation has not yet been run, calling cancel() provides a + * guarantee that the operation will not be run. + */ cancel(t) { + null !== this.timerHandle && (this.clearTimeout(), this.deferred.reject(new FirestoreError(y, "Operation cancelled" + (t ? ": " + t : "")))); + } + handleDelayElapsed() { + this.asyncQueue.enqueueAndForget((() => null !== this.timerHandle ? (this.clearTimeout(), + this.op().then((t => this.deferred.resolve(t)))) : Promise.resolve())); + } + clearTimeout() { + null !== this.timerHandle && (this.removalCallback(this), clearTimeout(this.timerHandle), + this.timerHandle = null); + } +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ const Et = "AsyncQueue"; + +class __PRIVATE_AsyncQueueImpl { + constructor(t = Promise.resolve()) { + // A list of retryable operations. Retryable operations are run in order and + // retried with backoff. + this.Dt = [], + // Is this AsyncQueue being shut down? Once it is set to true, it will not + // be changed again. + this.bt = !1, + // Operations scheduled to be queued in the future. Operations are + // automatically removed after they are run or canceled. + this.St = [], + // visible for testing + this.Ct = null, + // Flag set while there's an outstanding AsyncQueue operation, used for + // assertion sanity-checks. + this.Nt = !1, + // Enabled during shutdown on Safari to prevent future access to IndexedDB. + this.Ot = !1, + // List of TimerIds to fast-forward delays for. + this.qt = [], + // Backoff timer used to schedule retries for retryable operations + this.It = new __PRIVATE_ExponentialBackoff(this, "async_queue_retry" /* TimerId.AsyncQueueRetry */), + // Visibility handler that triggers an immediate retry of all retryable + // operations. Meant to speed up recovery when we regain file system access + // after page comes into foreground. + this.Bt = () => { + const t = getDocument(); + t && __PRIVATE_logDebug(Et, "Visibility state changed to " + t.visibilityState), + this.It.tt(); + }, this.$t = t; + const e = getDocument(); + e && "function" == typeof e.addEventListener && e.addEventListener("visibilitychange", this.Bt); + } + get isShuttingDown() { + return this.bt; + } + /** + * Adds a new operation to the queue without waiting for it to complete (i.e. + * we ignore the Promise result). + */ enqueueAndForget(t) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.enqueue(t); + } + enqueueAndForgetEvenWhileRestricted(t) { + this.Qt(), + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.kt(t); + } + enterRestrictedMode(t) { + if (!this.bt) { + this.bt = !0, this.Ot = t || !1; + const e = getDocument(); + e && "function" == typeof e.removeEventListener && e.removeEventListener("visibilitychange", this.Bt); + } + } + enqueue(t) { + if (this.Qt(), this.bt) + // Return a Promise which never resolves. + return new Promise((() => {})); + // Create a deferred Promise that we can return to the callee. This + // allows us to return a "hanging Promise" only to the callee and still + // advance the queue even when the operation is not run. + const e = new __PRIVATE_Deferred; + return this.kt((() => this.bt && this.Ot ? Promise.resolve() : (t().then(e.resolve, e.reject), + e.promise))).then((() => e.promise)); + } + enqueueRetryable(t) { + this.enqueueAndForget((() => (this.Dt.push(t), this.Lt()))); + } + /** + * Runs the next operation from the retryable queue. If the operation fails, + * reschedules with backoff. + */ async Lt() { + if (0 !== this.Dt.length) { + try { + await this.Dt[0](), this.Dt.shift(), this.It.reset(); + } catch (t) { + if (! + /** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + /** Verifies whether `e` is an IndexedDbTransactionError. */ + function __PRIVATE_isIndexedDbTransactionError(t) { + // Use name equality, as instanceof checks on errors don't work with errors + // that wrap other errors. + return "IndexedDbTransactionError" === t.name; + }(t)) throw t; + // Failure will be handled by AsyncQueue + __PRIVATE_logDebug(Et, "Operation failed with retryable error: " + t); + } + this.Dt.length > 0 && + // If there are additional operations, we re-schedule `retryNextOp()`. + // This is necessary to run retryable operations that failed during + // their initial attempt since we don't know whether they are already + // enqueued. If, for example, `op1`, `op2`, `op3` are enqueued and `op1` + // needs to be re-run, we will run `op1`, `op1`, `op2` using the + // already enqueued calls to `retryNextOp()`. `op3()` will then run in the + // call scheduled here. + // Since `backoffAndRun()` cancels an existing backoff and schedules a + // new backoff on every call, there is only ever a single additional + // operation in the queue. + this.It.Z((() => this.Lt())); + } + } + kt(t) { + const e = this.$t.then((() => (this.Nt = !0, t().catch((t => { + this.Ct = t, this.Nt = !1; + // Re-throw the error so that this.tail becomes a rejected Promise and + // all further attempts to chain (via .then) will just short-circuit + // and return the rejected Promise. + throw __PRIVATE_logError("INTERNAL UNHANDLED ERROR: ", __PRIVATE_getMessageOrStack(t)), + t; + })).then((t => (this.Nt = !1, t)))))); + return this.$t = e, e; + } + enqueueAfterDelay(t, e, r) { + this.Qt(), + // Fast-forward delays for timerIds that have been overridden. + this.qt.indexOf(t) > -1 && (e = 0); + const n = DelayedOperation.createAndSchedule(this, t, e, r, (t => this.Mt(t))); + return this.St.push(n), n; + } + Qt() { + this.Ct && fail(47125, { + xt: __PRIVATE_getMessageOrStack(this.Ct) + }); + } + verifyOperationInProgress() {} + /** + * Waits until all currently queued tasks are finished executing. Delayed + * operations are not run. + */ async Ut() { + // Operations in the queue prior to draining may have enqueued additional + // operations. Keep draining the queue until the tail is no longer advanced, + // which indicates that no more new operations were enqueued and that all + // operations were executed. + let t; + do { + t = this.$t, await t; + } while (t !== this.$t); + } + /** + * For Tests: Determine if a delayed operation with a particular TimerId + * exists. + */ jt(t) { + for (const e of this.St) if (e.timerId === t) return !0; + return !1; + } + /** + * For Tests: Runs some or all delayed operations early. + * + * @param lastTimerId - Delayed operations up to and including this TimerId + * will be drained. Pass TimerId.All to run all delayed operations. + * @returns a Promise that resolves once all operations have been run. + */ zt(t) { + // Note that draining may generate more delayed ops, so we do that first. + return this.Ut().then((() => { + // Run ops in the same order they'd run if they ran naturally. + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ + this.St.sort(((t, e) => t.targetTimeMs - e.targetTimeMs)); + for (const e of this.St) if (e.skipDelay(), "all" /* TimerId.All */ !== t && e.timerId === t) break; + return this.Ut(); + })); + } + /** + * For Tests: Skip all subsequent delays for a timer id. + */ Wt(t) { + this.qt.push(t); + } + /** Called once a DelayedOperation is run or canceled. */ Mt(t) { + // NOTE: indexOf / slice are O(n), but delayedOperations is expected to be small. + const e = this.St.indexOf(t); + /* eslint-disable-next-line @typescript-eslint/no-floating-promises */ this.St.splice(e, 1); + } +} + +/** + * Chrome includes Error.message in Error.stack. Other browsers do not. + * This returns expected output of message + stack when available. + * @param error - Error or FirestoreError + */ +function __PRIVATE_getMessageOrStack(t) { + let e = t.message || ""; + return t.stack && (e = t.stack.includes(t.message) ? t.stack : t.message + "\n" + t.stack), + e; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the +// legacy SDK. +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ class Transaction { + /** @hideconstructor */ + constructor(t, e) { + this._firestore = t, this._transaction = e, this._dataReader = __PRIVATE_newUserDataReader(t); + } + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ get(t) { + const e = __PRIVATE_validateReference(t, this._firestore), r = new __PRIVATE_LiteUserDataWriter(this._firestore); + return this._transaction.lookup([ e._key ]).then((t => { + if (!t || 1 !== t.length) return fail(24041); + const n = t[0]; + if (n.isFoundDocument()) return new DocumentSnapshot(this._firestore, r, n.key, n, e.converter); + if (n.isNoDocument()) return new DocumentSnapshot(this._firestore, r, e._key, null, e.converter); + throw fail(18433, { + doc: n + }); + })); + } + set(t, e, r) { + const n = __PRIVATE_validateReference(t, this._firestore), i = __PRIVATE_applyFirestoreDataConverter(n.converter, e, r), s = __PRIVATE_parseSetData(this._dataReader, "Transaction.set", n._key, i, null !== n.converter, r); + return this._transaction.set(n._key, s), this; + } + update(t, e, r, ...n) { + const i = __PRIVATE_validateReference(t, this._firestore); + // For Compat types, we have to "extract" the underlying types before + // performing validation. + let s; + return s = "string" == typeof (e = P(e)) || e instanceof FieldPath ? __PRIVATE_parseUpdateVarargs(this._dataReader, "Transaction.update", i._key, e, r, n) : __PRIVATE_parseUpdateData(this._dataReader, "Transaction.update", i._key, e), + this._transaction.update(i._key, s), this; + } + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `Transaction` instance. Used for chaining method calls. + */ delete(t) { + const e = __PRIVATE_validateReference(t, this._firestore); + return this._transaction.delete(e._key), this; + } +} + +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ function runTransaction(t, e, r) { + const n = __PRIVATE_getDatastore(t = __PRIVATE_cast(t, Firestore)), i = { + ...mt, + ...r + }; + !function __PRIVATE_validateTransactionOptions(t) { + if (t.maxAttempts < 1) throw new FirestoreError(w, "Max attempts must be at least 1"); + }(i); + const s = new __PRIVATE_Deferred; + return new __PRIVATE_TransactionRunner(function __PRIVATE_newAsyncQueue() { + return new __PRIVATE_AsyncQueueImpl; + }(), n, i, (r => e(new Transaction(t, r))), s).yt(), s.promise; +} + +/** + * Firestore Lite + * + * @remarks Firestore Lite is a small online-only SDK that allows read + * and write access to your Firestore database. All operations connect + * directly to the backend, and `onSnapshot()` APIs are not supported. + * @packageDocumentation + */ !function __PRIVATE_registerFirestore() { + !function __PRIVATE_setSDKVersion(t) { + V = t; + }(`${s}_lite`), n(new o("firestore/lite", ((t, {instanceIdentifier: e, options: r}) => { + const n = t.getProvider("app").getImmediate(), i = new Firestore(new __PRIVATE_LiteAuthCredentialsProvider(t.getProvider("auth-internal")), new __PRIVATE_LiteAppCheckTokenProvider(n, t.getProvider("app-check-internal")), function __PRIVATE_databaseIdFromApp(t, e) { + if (!Object.prototype.hasOwnProperty.apply(t.options, [ "projectId" ])) throw new FirestoreError(w, '"projectId" not provided in firebase.initializeApp.'); + return new DatabaseId(t.options.projectId, e); + }(n, e), n); + return r && i._setSettings(r), i; + }), "PUBLIC").setMultipleInstances(!0)), + // RUNTIME_ENV and BUILD_TARGET are replaced by real values during the compilation + i("firestore-lite", R, "rn"), i("firestore-lite", R, "esm2020"); +}(); + +export { AggregateField, AggregateQuerySnapshot, Bytes, CollectionReference, DocumentReference, DocumentSnapshot, FieldPath, FieldValue, Firestore, FirestoreError, GeoPoint, Query, QueryCompositeFilterConstraint, QueryConstraint, QueryDocumentSnapshot, QueryEndAtConstraint, QueryFieldFilterConstraint, QueryLimitConstraint, QueryOrderByConstraint, QuerySnapshot, QueryStartAtConstraint, Timestamp, Transaction, VectorValue, WriteBatch, addDoc, aggregateFieldEqual, aggregateQuerySnapshotEqual, and, arrayRemove, arrayUnion, average, collection, collectionGroup, connectFirestoreEmulator, count, deleteDoc, deleteField, doc, documentId, endAt, endBefore, getAggregate, getCount, getDoc, getDocs, getFirestore, increment, initializeFirestore, limit, limitToLast, or, orderBy, query, queryEqual, refEqual, runTransaction, serverTimestamp, setDoc, setLogLevel, snapshotEqual, startAfter, startAt, sum, terminate, updateDoc, vector, where, writeBatch }; +//# sourceMappingURL=index.rn.esm.js.map diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/index.rn.esm.js.map b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.rn.esm.js.map new file mode 100644 index 0000000..f2bcc16 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/index.rn.esm.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.rn.esm.js","sources":["../../src/auth/user.ts","../../src/core/version.ts","../../src/util/log.ts","../../src/platform/browser/format_json.ts","../../src/util/assert.ts","../../src/util/error.ts","../../src/util/promise.ts","../../src/api/credentials.ts","../../src/core/database_info.ts","../../src/platform/browser/random_bytes.ts","../../src/util/misc.ts","../../src/model/path.ts","../../src/model/document_key.ts","../../src/util/input_validation.ts","../../src/api/long_polling_options.ts","../../src/util/debug_uid.ts","../../src/util/types.ts","../../src/remote/rest_connection.ts","../../src/remote/rpc_error.ts","../../src/platform/browser_lite/fetch_connection.ts","../../src/core/aggregate.ts","../../src/util/obj.ts","../../src/util/base64_decode_error.ts","../../src/platform/rn/base64.ts","../../src/util/byte_string.ts","../../src/model/normalize.ts","../../src/util/json_validation.ts","../../src/lite-api/timestamp.ts","../../src/model/server_timestamps.ts","../../src/model/values.ts","../../src/core/bound.ts","../../src/core/filter.ts","../../src/core/order_by.ts","../../src/core/snapshot_version.ts","../../src/util/sorted_map.ts","../../src/util/sorted_set.ts","../../src/model/field_mask.ts","../../src/model/object_value.ts","../../src/model/document.ts","../../src/core/target.ts","../../src/core/query.ts","../../src/remote/number_serializer.ts","../../src/model/transform_operation.ts","../../src/model/mutation.ts","../../src/remote/serializer.ts","../../src/platform/browser/serializer.ts","../../src/remote/backoff.ts","../../src/remote/datastore.ts","../../src/lite-api/components.ts","../../src/platform/browser_lite/connection.ts","../../src/local/lru_garbage_collector_impl.ts","../../src/lite-api/settings.ts","../../src/local/lru_garbage_collector.ts","../../src/lite-api/database.ts","../../src/lite-api/aggregate_types.ts","../../src/lite-api/reference.ts","../../src/lite-api/bytes.ts","../../src/lite-api/field_path.ts","../../src/lite-api/field_value.ts","../../src/lite-api/geo_point.ts","../../src/lite-api/vector_value.ts","../../src/util/array.ts","../../src/lite-api/user_data_reader.ts","../../src/lite-api/snapshot.ts","../../src/lite-api/query.ts","../../src/lite-api/user_data_writer.ts","../../src/lite-api/reference_impl.ts","../../src/lite-api/aggregate.ts","../../src/lite-api/field_value_impl.ts","../../src/lite-api/write_batch.ts","../../src/core/transaction.ts","../../src/core/transaction_options.ts","../../src/core/transaction_runner.ts","../../src/platform/browser/dom.ts","../../src/util/async_queue.ts","../../src/util/async_queue_impl.ts","../../src/local/simple_db.ts","../../src/lite-api/transaction.ts","../../lite/register.ts","../../lite/index.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Simple wrapper around a nullable UID. Mostly exists to make code more\n * readable.\n */\nexport class User {\n /** A user with a null UID. */\n static readonly UNAUTHENTICATED = new User(null);\n\n // TODO(mikelehen): Look into getting a proper uid-equivalent for\n // non-FirebaseAuth providers.\n static readonly GOOGLE_CREDENTIALS = new User('google-credentials-uid');\n static readonly FIRST_PARTY = new User('first-party-uid');\n static readonly MOCK_USER = new User('mock-user');\n\n constructor(readonly uid: string | null) {}\n\n isAuthenticated(): boolean {\n return this.uid != null;\n }\n\n /**\n * Returns a key representing this user, suitable for inclusion in a\n * dictionary.\n */\n toKey(): string {\n if (this.isAuthenticated()) {\n return 'uid:' + this.uid;\n } else {\n return 'anonymous-user';\n }\n }\n\n isEqual(otherUser: User): boolean {\n return otherUser.uid === this.uid;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** The semver (www.semver.org) version of the SDK. */\nimport { version } from '../../../firebase/package.json';\nexport let SDK_VERSION = version;\nexport function setSDKVersion(version: string): void {\n SDK_VERSION = version;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Logger, LogLevel, LogLevelString } from '@firebase/logger';\n\nimport { SDK_VERSION } from '../core/version';\nimport { formatJSON } from '../platform/format_json';\n\nexport { LogLevel, LogLevelString };\n\nconst logClient = new Logger('@firebase/firestore');\n\n// Helper methods are needed because variables can't be exported as read/write\nexport function getLogLevel(): LogLevel {\n return logClient.logLevel;\n}\n\n/**\n * Sets the verbosity of Cloud Firestore logs (debug, error, or silent).\n *\n * @param logLevel - The verbosity you set for activity and error logging. Can\n * be any of the following values:\n *\n *
    \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 *\n * @param code generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(\n code: number,\n message: string,\n context?: Record\n): never;\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 *\n * @param id generate a new unique value with `yarn assertion-id:generate`\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function fail(id: number, context?: Record): never;\n\nexport function fail(\n id: number,\n messageOrContext?: string | Record,\n context?: Record\n): never {\n let message = 'Unexpected state';\n if (typeof messageOrContext === 'string') {\n message = messageOrContext;\n } else {\n context = messageOrContext;\n }\n _fail(id, message, context);\n}\n\nfunction _fail(\n id: number,\n failure: string,\n context?: Record\n): never {\n // Log the failure in addition to throw an exception, just in case the\n // exception is swallowed.\n let message = `FIRESTORE (${SDK_VERSION}) INTERNAL ASSERTION FAILED: ${failure} (ID: ${id.toString(\n 16\n )})`;\n if (context !== undefined) {\n try {\n const stringContext = JSON.stringify(context);\n message += ' CONTEXT: ' + stringContext;\n } catch (e) {\n message += ' CONTEXT: ' + context;\n }\n }\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 *\n * @param id generate a new unique value with `yarn assertion-idgenerate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n assertion: boolean,\n id: number,\n message: string,\n context?: Record\n): asserts assertion;\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 *\n * @param id generate a new unique value with `yarn assertion-id:generate`.\n * Search for an existing value using `yarn assertion-id:find X`\n */\nexport function hardAssert(\n assertion: boolean,\n id: number,\n context?: Record\n): asserts assertion;\n\nexport function hardAssert(\n assertion: boolean,\n id: number,\n messageOrContext?: string | Record,\n context?: Record\n): asserts assertion {\n let message = 'Unexpected state';\n if (typeof messageOrContext === 'string') {\n message = messageOrContext;\n } else {\n context = messageOrContext;\n }\n\n if (!assertion) {\n _fail(id, message, context);\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(0xdeb6, 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 { FirebaseApp, _isFirebaseServerApp } from '@firebase/app';\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 0xa539,\n 'Invalid tokenData returned from getToken()',\n { 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 0xa540,\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 0x7c5d,\n 'Invalid tokenData returned from getToken()',\n { 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 0x0807,\n 'Received invalid UID',\n { 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 private serverAppAppCheckToken: string | null = null;\n\n constructor(\n app: FirebaseApp,\n private appCheckProvider: Provider\n ) {\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n }\n\n start(\n asyncQueue: AsyncQueue,\n changeListener: CredentialChangeListener\n ): void {\n hardAssert(\n this.tokenListener === undefined,\n 0x0db8,\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 if (this.serverAppAppCheckToken) {\n return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n }\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 0xae0e,\n 'Invalid tokenResult returned from getToken()',\n { 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 private serverAppAppCheckToken: string | null = null;\n\n constructor(\n app: FirebaseApp,\n private appCheckProvider: Provider\n ) {\n if (_isFirebaseServerApp(app) && app.settings.appCheckToken) {\n this.serverAppAppCheckToken = app.settings.appCheckToken;\n }\n appCheckProvider.onInit(appCheck => {\n this.appCheck = appCheck;\n });\n }\n\n getToken(): Promise {\n if (this.serverAppAppCheckToken) {\n return Promise.resolve(new AppCheckToken(this.serverAppAppCheckToken));\n }\n\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 0x0d8e,\n 'Invalid tokenResult returned from getToken()',\n { 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","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 readonly isUsingEmulator: 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 { 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\n/** Compare strings in UTF-8 encoded byte order */\nexport function compareUtf8Strings(left: string, right: string): number {\n // Find the first differing character (a.k.a. \"UTF-16 code unit\") in the two strings and,\n // if found, use that character to determine the relative ordering of the two strings as a\n // whole. Comparing UTF-16 strings in UTF-8 byte order can be done simply and efficiently by\n // comparing the UTF-16 code units (chars). This serendipitously works because of the way UTF-8\n // and UTF-16 happen to represent Unicode code points.\n //\n // After finding the first pair of differing characters, there are two cases:\n //\n // Case 1: Both characters are non-surrogates (code points less than or equal to 0xFFFF) or\n // both are surrogates from a surrogate pair (that collectively represent code points greater\n // than 0xFFFF). In this case their numeric order as UTF-16 code units is the same as the\n // lexicographical order of their corresponding UTF-8 byte sequences. A direct comparison is\n // sufficient.\n //\n // Case 2: One character is a surrogate and the other is not. In this case the surrogate-\n // containing string is always ordered after the non-surrogate. This is because surrogates are\n // used to represent code points greater than 0xFFFF which have 4-byte UTF-8 representations\n // and are lexicographically greater than the 1, 2, or 3-byte representations of code points\n // less than or equal to 0xFFFF.\n //\n // An example of why Case 2 is required is comparing the following two Unicode code points:\n //\n // |-----------------------|------------|---------------------|-----------------|\n // | Name | Code Point | UTF-8 Encoding | UTF-16 Encoding |\n // |-----------------------|------------|---------------------|-----------------|\n // | Replacement Character | U+FFFD | 0xEF 0xBF 0xBD | 0xFFFD |\n // | Grinning Face | U+1F600 | 0xF0 0x9F 0x98 0x80 | 0xD83D 0xDE00 |\n // |-----------------------|------------|---------------------|-----------------|\n //\n // A lexicographical comparison of the UTF-8 encodings of these code points would order\n // \"Replacement Character\" _before_ \"Grinning Face\" because 0xEF is less than 0xF0. However, a\n // direct comparison of the UTF-16 code units, as would be done in case 1, would erroneously\n // produce the _opposite_ ordering, because 0xFFFD is _greater than_ 0xD83D. As it turns out,\n // this relative ordering holds for all comparisons of UTF-16 code points requiring a surrogate\n // pair with those that do not.\n const length = Math.min(left.length, right.length);\n for (let i = 0; i < length; i++) {\n const leftChar = left.charAt(i);\n const rightChar = right.charAt(i);\n if (leftChar !== rightChar) {\n return isSurrogate(leftChar) === isSurrogate(rightChar)\n ? primitiveComparator(leftChar, rightChar)\n : isSurrogate(leftChar)\n ? 1\n : -1;\n }\n }\n\n // Use the lengths of the strings to determine the overall comparison result since either the\n // strings were equal or one is a prefix of the other.\n return primitiveComparator(left.length, right.length);\n}\n\nconst MIN_SURROGATE = 0xd800;\nconst MAX_SURROGATE = 0xdfff;\n\nexport function isSurrogate(s: string): boolean {\n debugAssert(s.length === 1, `s.length == ${s.length}, but expected 1`);\n const c = s.charCodeAt(0);\n return c >= MIN_SURROGATE && c <= MAX_SURROGATE;\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 { Integer } from '@firebase/webchannel-wrapper/bloom-blob';\n\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\nimport { compareUtf8Strings, primitiveComparator } from '../util/misc';\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(0x027d, 'offset out of range', {\n offset,\n range: segments.length\n });\n }\n\n if (length === undefined) {\n length = segments.length - offset;\n } else if (length > segments.length - offset) {\n fail(0x06d2, 'length out of range', {\n length,\n range: segments.length - offset\n });\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 /**\n * Compare 2 paths segment by segment, prioritizing numeric IDs\n * (e.g., \"__id123__\") in numeric ascending order, followed by string\n * segments in lexicographical order.\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 comparison = BasePath.compareSegments(p1.get(i), p2.get(i));\n if (comparison !== 0) {\n return comparison;\n }\n }\n return primitiveComparator(p1.length, p2.length);\n }\n\n private static compareSegments(lhs: string, rhs: string): number {\n const isLhsNumeric = BasePath.isNumericId(lhs);\n const isRhsNumeric = BasePath.isNumericId(rhs);\n\n if (isLhsNumeric && !isRhsNumeric) {\n // Only lhs is numeric\n return -1;\n } else if (!isLhsNumeric && isRhsNumeric) {\n // Only rhs is numeric\n return 1;\n } else if (isLhsNumeric && isRhsNumeric) {\n // both numeric\n return BasePath.extractNumericId(lhs).compare(\n BasePath.extractNumericId(rhs)\n );\n } else {\n // both non-numeric\n return compareUtf8Strings(lhs, rhs);\n }\n }\n\n // Checks if a segment is a numeric ID (starts with \"__id\" and ends with \"__\").\n private static isNumericId(segment: string): boolean {\n return segment.startsWith('__id') && segment.endsWith('__');\n }\n\n private static extractNumericId(segment: string): Integer {\n return Integer.fromString(segment.substring(4, segment.length - 2));\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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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(0x3029, 'Unknown wrong type', { 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 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 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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isCloudWorkstation } from '@firebase/util';\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 const { host } = new URL(url);\n const forwardCredentials = isCloudWorkstation(host);\n return this.performRPCRequest(\n rpcName,\n url,\n headers,\n req,\n forwardCredentials\n ).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 _forwardCredentials: boolean\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 { 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(0xfdaa, '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(0x3c6b, '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(0x999b, '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(0x3019, '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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Token } from '../../api/credentials';\nimport { Stream } from '../../remote/connection';\nimport { RestConnection } from '../../remote/rest_connection';\nimport { mapCodeFromHttpStatus } from '../../remote/rpc_error';\nimport { FirestoreError } from '../../util/error';\nimport { StringMap } from '../../util/types';\n\n/**\n * A Rest-based connection that relies on the native HTTP stack\n * (e.g. `fetch` or a polyfill).\n */\nexport class FetchConnection extends RestConnection {\n openStream(\n rpcName: string,\n token: Token | null\n ): Stream {\n throw new Error('Not supported by FetchConnection');\n }\n\n protected async performRPCRequest(\n rpcName: string,\n url: string,\n headers: StringMap,\n body: Req,\n forwardCredentials: boolean\n ): Promise {\n const requestJson = JSON.stringify(body);\n let response: Response;\n\n try {\n const fetchArgs: RequestInit = {\n method: 'POST',\n headers,\n body: requestJson\n };\n if (forwardCredentials) {\n fetchArgs.credentials = 'include';\n }\n response = await fetch(url, fetchArgs);\n } catch (e) {\n const err = e as { status: number | undefined; statusText: string };\n throw new FirestoreError(\n mapCodeFromHttpStatus(err.status),\n 'Request failed with error: ' + err.statusText\n );\n }\n\n if (!response.ok) {\n let errorResponse = await response.json();\n if (Array.isArray(errorResponse)) {\n errorResponse = errorResponse[0];\n }\n const errorMessage = errorResponse?.error?.message;\n throw new FirestoreError(\n mapCodeFromHttpStatus(response.status),\n `Request failed with error: ${errorMessage ?? response.statusText}`\n );\n }\n\n return response.json();\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 { FieldPath } from '../model/path';\n\n/**\n * Union type representing the aggregate type to be performed.\n */\nexport type AggregateType = 'count' | 'avg' | 'sum';\n\n/**\n * Represents an Aggregate to be performed over a query result set.\n */\nexport interface Aggregate {\n readonly fieldPath?: FieldPath;\n readonly alias: string;\n readonly aggregateType: AggregateType;\n}\n\n/**\n * Concrete implementation of the Aggregate type.\n */\nexport class AggregateImpl implements Aggregate {\n constructor(\n readonly alias: string,\n readonly aggregateType: AggregateType,\n readonly fieldPath?: 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 './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 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 { base64, DecodeBase64StringError } from '@firebase/util';\n\nimport { Base64DecodeError } from '../../util/base64_decode_error';\n\n// WebSafe uses a different URL-encoding safe alphabet that doesn't match\n// the encoding used on the backend.\nconst WEB_SAFE = false;\n\n/** Converts a Base64 encoded string to a binary string. */\nexport function decodeBase64(encoded: string): string {\n try {\n return String.fromCharCode.apply(\n null,\n // We use `decodeStringToByteArray()` instead of `decodeString()` since\n // `decodeString()` returns Unicode strings, which doesn't match the values\n // returned by `atob()`'s Latin1 representation.\n base64.decodeStringToByteArray(encoded, WEB_SAFE)\n );\n } catch (e) {\n if (e instanceof DecodeBase64StringError) {\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 const bytes: number[] = [];\n for (let i = 0; i < raw.length; i++) {\n bytes[i] = raw.charCodeAt(i);\n }\n return base64.encodeByteArray(bytes, WEB_SAFE);\n}\n\n/** True if and only if the Base64 conversion functions are available. */\nexport function isBase64Available(): boolean {\n return true;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 { 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, 0x986a, '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, 0xb5de, 'invalid timestamp', {\n timestamp: date\n });\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 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isPlainObject } from '../util/input_validation';\n\nimport { Code, FirestoreError } from './error';\n\n/**\n * A list of data types Firestore objects may serialize in their toJSON implemenetations.\n * @private\n * @internal\n */\nexport type JsonTypeDesc =\n | 'object'\n | 'string'\n | 'number'\n | 'boolean'\n | 'null'\n | 'undefined';\n\n/**\n * An association of JsonTypeDesc values to their native types.\n * @private\n * @internal\n */\nexport type TSType = T extends 'object'\n ? object\n : T extends 'string'\n ? string\n : T extends 'number'\n ? number\n : T extends 'boolean'\n ? boolean\n : T extends 'null'\n ? null\n : T extends 'undefined'\n ? undefined\n : never;\n\n/**\n * The representation of a JSON object property name and its type value.\n * @private\n * @internal\n */\nexport interface Property {\n value?: TSType;\n typeString: JsonTypeDesc;\n}\n\n/**\n * A type Firestore data types may use to define the fields used in their JSON serialization.\n * @private\n * @internal\n */\nexport interface JsonSchema {\n [key: string]: Property;\n}\n\n/**\n * Associates the JSON property type to the native type and sets them to be Required.\n * @private\n * @internal\n */\nexport type Json = {\n [K in keyof T]: Required['value'];\n};\n\n/**\n * Helper function to define a JSON schema {@link Property}.\n * @private\n * @internal\n */\nexport function property(\n typeString: T,\n optionalValue?: TSType\n): Property {\n const result: Property = {\n typeString\n };\n if (optionalValue) {\n result.value = optionalValue;\n }\n return result;\n}\n\n/**\n * Validates the JSON object based on the provided schema, and narrows the type to the provided\n * JSON schema.\n * @private\n * @internal\n *\n * @param json A JSON object to validate.\n * @param scheme a {@link JsonSchema} that defines the properties to validate.\n * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise.\n */\nexport function validateJSON(\n json: object,\n schema: S\n): json is Json {\n if (!isPlainObject(json)) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, 'JSON must be an object');\n }\n let error: string | undefined = undefined;\n for (const key in schema) {\n if (schema[key]) {\n const typeString = schema[key].typeString;\n const value: { value: unknown } | undefined =\n 'value' in schema[key] ? { value: schema[key].value } : undefined;\n if (!(key in json)) {\n error = `JSON missing required field: '${key}'`;\n break;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const fieldValue = (json as any)[key];\n if (typeString && typeof fieldValue !== typeString) {\n error = `JSON field '${key}' must be a ${typeString}.`;\n break;\n } else if (value !== undefined && fieldValue !== value.value) {\n error = `Expected '${key}' field to equal '${value.value}'`;\n break;\n }\n }\n }\n if (error) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, error);\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 { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\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 static _jsonSchemaVersion: string = 'firestore/timestamp/1.0';\n static _jsonSchema = {\n type: property('string', Timestamp._jsonSchemaVersion),\n seconds: property('number'),\n nanoseconds: property('number')\n };\n\n /**\n * Returns a JSON-serializable representation of this `Timestamp`.\n */\n toJSON(): { seconds: number; nanoseconds: number; type: string } {\n return {\n type: Timestamp._jsonSchemaVersion,\n seconds: this.seconds,\n nanoseconds: this.nanoseconds\n };\n }\n\n /**\n * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}.\n */\n static fromJSON(json: object): Timestamp {\n if (validateJSON(json, Timestamp._jsonSchema)) {\n return new Timestamp(json.seconds, json.nanoseconds);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Timestamp from JSON.'\n );\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 {\n arrayEquals,\n compareUtf8Strings,\n primitiveComparator\n} 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(0x6e87, 'Invalid value type', { 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(0xcbf8, 'Unexpected value type', { 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 compareUtf8Strings(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(0x5ae0, '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 = compareUtf8Strings(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(0xee4d, 'Invalid value type', { 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(0x34ae, 'Invalid value type', { 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(0x8c66, 'Invalid value type', { 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(0xf207, 'Invalid value type', { 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 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 { 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 other.nullValue === undefined &&\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(0xb8a2, 'Unknown FieldFilter operator', {\n operator: this.op\n });\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(0x4bef, '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 (\n other !== null &&\n other.nullValue === undefined &&\n !arrayValueContains(this.value.arrayValue!, other)\n );\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 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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 './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(0xaad2, 'Red node has red child', {\n key: this.key,\n value: this.value\n });\n }\n if (this.right.isRed()) {\n throw fail(0x3721, 'Right child of (`key`, `value`) is red', {\n key: this.key,\n value: this.value\n });\n }\n const blackDepth = (this.left as LLRBNode).check();\n if (blackDepth !== (this.right as LLRBNode).check()) {\n throw fail(0x6d2d, '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(0xe1a6, 'LLRBEmptyNode has no key.');\n }\n get value(): never {\n throw fail(0x3f0d, 'LLRBEmptyNode has no value.');\n }\n get color(): never {\n throw fail(0x4157, 'LLRBEmptyNode has no color.');\n }\n get left(): never {\n throw fail(0x741e, 'LLRBEmptyNode has no left child.');\n }\n get right(): never {\n throw fail(0x901e, '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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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(\n 0xa786,\n \"Trying to compare documents on fields that don't exist\"\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(0x4d4e, 'Unknown direction', { direction: orderBy.dir });\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 { 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 0x7f90,\n 'server transform result count should match field transform count',\n {\n serverTransformResultCount: serverTransformResults.length,\n fieldTransformCount: fieldTransforms.length\n }\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 { 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\n/**\n * Returns a Timestamp typed object given protobuf timestamp value.\n */\nexport function 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 0xe30b,\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 0x3f41,\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, 0xc050, \"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 0x27ce,\n 'Tried to deserialize invalid key',\n { 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 0x71a3,\n 'tried to deserialize invalid key',\n { 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 0xaa33,\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 0x0f36,\n 'Tried to deserialize a missing document from a found document.'\n );\n hardAssert(\n !!result.readTime,\n 0x5995,\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(0x1c42, 'invalid batch get response', { 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(0x2d51, 'Unknown change type', { 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(0x9991, '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(0x40d7, 'Unknown mutation type', {\n mutationType: mutation.type\n });\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(0x05b7, 'unknown mutation proto', { 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(0x6b69, '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 0x3811,\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(0x51c2, 'Unknown transform', {\n transform: fieldTransform.transform\n });\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 0x40f6,\n 'Unknown server value transform proto',\n { 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(0x40c8, 'Unknown transform proto', { 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 0x07ae,\n 'DocumentsTarget contained other than 1 document',\n {\n count\n }\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 0xfe26,\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(0x713b, '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(0x7591, 'Unknown filter', { 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(0xe2fe, 'Unspecified operator');\n default:\n return fail(0xc54a, '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(0x0402, '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(0xd65d, 'Unrecognized filter type', { 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(0xef81, 'Unspecified filter');\n default:\n return fail(0xed36, '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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 } 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, 0xd7c2, 'Missing entity in write response for `key`', {\n key\n });\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 0xfcd7,\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 settings.isUsingEmulator\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';\n\nimport { FetchConnection } from './fetch_connection';\n\nexport { newConnectivityMonitor } from '../browser/connection';\n\n/** Initializes the HTTP connection for the REST API. */\nexport function newConnection(databaseInfo: DatabaseInfo): Connection {\n return new FetchConnection(databaseInfo);\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\nimport { EmulatorMockTokenOptions } from '@firebase/util';\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 emulatorOptions?: { mockUserToken?: EmulatorMockTokenOptions | string };\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 readonly isUsingEmulator: boolean;\n\n // Can be a google-auth-library or gapi client.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n credentials?: any;\n\n constructor(settings: PrivateSettings) {\n if (settings.host === undefined) {\n if (settings.ssl !== undefined) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't provide ssl option if host option is not set\"\n );\n }\n this.host = DEFAULT_HOST;\n this.ssl = DEFAULT_SSL;\n } else {\n this.host = settings.host;\n this.ssl = settings.ssl ?? DEFAULT_SSL;\n }\n this.isUsingEmulator = settings.emulatorOptions !== undefined;\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 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 deepEqual,\n EmulatorMockTokenOptions,\n getDefaultEmulatorHostnameAndPort,\n isCloudWorkstation,\n pingServer,\n updateEmulatorBanner\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 private _emulatorOptions: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {};\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 this._emulatorOptions = settings.emulatorOptions || {};\n\n if (settings.credentials !== undefined) {\n this._authCredentials = makeAuthCredentialsProvider(settings.credentials);\n }\n }\n\n _getSettings(): FirestoreSettingsImpl {\n return this._settings;\n }\n\n _getEmulatorOptions(): { mockUserToken?: EmulatorMockTokenOptions | string } {\n return this._emulatorOptions;\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 useSsl = isCloudWorkstation(host);\n const settings = firestore._getSettings();\n const existingConfig = {\n ...settings,\n emulatorOptions: firestore._getEmulatorOptions()\n };\n const newHostSetting = `${host}:${port}`;\n if (useSsl) {\n void pingServer(`https://${newHostSetting}`);\n updateEmulatorBanner('Firestore', true);\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 const newConfig = {\n ...settings,\n host: newHostSetting,\n ssl: useSsl,\n emulatorOptions: options\n };\n // No-op if the new configuration matches the current configuration. This supports SSR\n // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice.\n if (deepEqual(newConfig, existingConfig)) {\n return;\n }\n\n firestore._setSettings(newConfig);\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 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 { AggregateType } from '../core/aggregate';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\n\nimport { average, count, sum } from './aggregate';\nimport { DocumentData, Query } from './reference';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\nexport { AggregateType };\n\n/**\n * Represents an aggregation that can be performed by Firestore.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport class AggregateField {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateField';\n\n /** Indicates the aggregation operation of this AggregateField. */\n readonly aggregateType: AggregateType;\n\n /**\n * Create a new AggregateField\n * @param aggregateType Specifies the type of aggregation operation to perform.\n * @param _internalFieldPath Optionally specifies the field that is aggregated.\n * @internal\n */\n constructor(\n aggregateType: AggregateType = 'count',\n readonly _internalFieldPath?: InternalFieldPath\n ) {\n this.aggregateType = aggregateType;\n }\n}\n\n/**\n * The union of all `AggregateField` types that are supported by Firestore.\n */\nexport type AggregateFieldType =\n | ReturnType\n | ReturnType\n | ReturnType;\n\n/**\n * Specifies a set of aggregations and their aliases.\n */\nexport interface AggregateSpec {\n [field: string]: AggregateFieldType;\n}\n\n/**\n * A type whose keys are taken from an `AggregateSpec`, and whose values are the\n * result of the aggregation performed by the corresponding `AggregateField`\n * from the input `AggregateSpec`.\n */\nexport type AggregateSpecData = {\n [P in keyof T]: T[P] extends AggregateField ? U : never;\n};\n\n/**\n * The results of executing an aggregation query.\n */\nexport class AggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateQuerySnapshot';\n\n /**\n * The underlying query over which the aggregations recorded in this\n * `AggregateQuerySnapshot` were performed.\n */\n readonly query: Query;\n\n /** @hideconstructor */\n constructor(\n query: Query,\n private readonly _userDataWriter: AbstractUserDataWriter,\n private readonly _data: ApiClientObjectMap\n ) {\n this.query = query;\n }\n\n /**\n * Returns the results of the aggregations performed over the underlying\n * query.\n *\n * The keys of the returned object will be the same as those of the\n * `AggregateSpec` object specified to the aggregation method, and the values\n * will be the corresponding aggregation result.\n *\n * @returns The results of the aggregations performed over the underlying\n * query.\n */\n data(): AggregateSpecData {\n return this._userDataWriter.convertObjectMap(\n this._data\n ) as AggregateSpecData;\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 {\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';\n// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_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 static _jsonSchemaVersion: string = 'firestore/documentReference/1.0';\n static _jsonSchema = {\n type: property('string', DocumentReference._jsonSchemaVersion),\n referencePath: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `DocumentReference` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: DocumentReference._jsonSchemaVersion,\n referencePath: this._key.toString()\n };\n }\n\n /**\n * Builds a `DocumentReference` instance from a JSON object created by\n * {@link DocumentReference.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json a JSON object represention of a `DocumentReference` instance\n * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(firestore: Firestore, json: object): DocumentReference;\n /**\n * Builds a `DocumentReference` instance from a JSON object created by\n * {@link DocumentReference.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json a JSON object represention of a `DocumentReference` instance\n * @param converter - Converts objects to and from Firestore.\n * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON<\n NewAppModelType = DocumentData,\n NewDbModelType extends DocumentData = DocumentData\n >(\n firestore: Firestore,\n json: object,\n converter: FirestoreDataConverter\n ): DocumentReference;\n static fromJSON<\n NewAppModelType = DocumentData,\n NewDbModelType extends DocumentData = DocumentData\n >(\n firestore: Firestore,\n json: object,\n converter?: FirestoreDataConverter\n ): DocumentReference {\n if (validateJSON(json, DocumentReference._jsonSchema)) {\n return new DocumentReference(\n firestore,\n converter ? converter : null,\n new DocumentKey(ResourcePath.fromString(json.referencePath))\n );\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Bytes from JSON.'\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 { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\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 static _jsonSchemaVersion: string = 'firestore/bytes/1.0';\n static _jsonSchema = {\n type: property('string', Bytes._jsonSchemaVersion),\n bytes: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `Bytes` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: Bytes._jsonSchemaVersion,\n bytes: this.toBase64()\n };\n }\n\n /**\n * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}.\n *\n * @param json a JSON object represention of a `Bytes` instance\n * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): Bytes {\n if (validateJSON(json, Bytes._jsonSchema)) {\n return Bytes.fromBase64String(json.bytes);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Bytes from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n 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';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\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 /**\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 static _jsonSchemaVersion: string = 'firestore/geoPoint/1.0';\n static _jsonSchema = {\n type: property('string', GeoPoint._jsonSchemaVersion),\n latitude: property('number'),\n longitude: property('number')\n };\n\n /**\n * Returns a JSON-serializable representation of this `GeoPoint` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): { latitude: number; longitude: number; type: string } {\n return {\n latitude: this._lat,\n longitude: this._long,\n type: GeoPoint._jsonSchemaVersion\n };\n }\n\n /**\n * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}.\n *\n * @param json a JSON object represention of a `GeoPoint` instance\n * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): GeoPoint {\n if (validateJSON(json, GeoPoint._jsonSchema)) {\n return new GeoPoint(json.latitude, json.longitude);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating GeoPoint from JSON.'\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';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\n\n/**\n * Represents a vector type in Firestore documents.\n * Create an instance with {@link 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` values have the same raw number arrays, returns `false` otherwise.\n */\n isEqual(other: VectorValue): boolean {\n return isPrimitiveArrayEqual(this._values, other._values);\n }\n\n static _jsonSchemaVersion: string = 'firestore/vectorValue/1.0';\n static _jsonSchema = {\n type: property('string', VectorValue._jsonSchemaVersion),\n vectorValues: property('object')\n };\n\n /**\n * Returns a JSON-serializable representation of this `VectorValue` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: VectorValue._jsonSchemaVersion,\n vectorValues: this._values\n };\n }\n\n /**\n * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}.\n *\n * @param json a JSON object represention of a `VectorValue` instance.\n * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): VectorValue {\n if (validateJSON(json, VectorValue._jsonSchema)) {\n if (\n Array.isArray(json.vectorValues) &&\n json.vectorValues.every(element => typeof element === 'number')\n ) {\n return new VectorValue(json.vectorValues);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Expected 'vectorValues' field to be a number array\"\n );\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Timestamp from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * Returns 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(0x9c4b, 'Unexpected case for UserDataSource', {\n dataSource\n });\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\nexport function 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(0xf2a2, 'Invalid value type', {\n value\n });\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 0x25d8,\n 'ReferenceValue is not valid',\n { name }\n );\n const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3));\n const key = new DocumentKey(resourcePath.popFirst(5));\n\n if (!databaseId.isEqual(expectedDatabaseId)) {\n // TODO(b/64130202): Somehow support foreign references.\n logError(\n `Document ${key} contains a document ` +\n `reference within a different database (` +\n `${databaseId.projectId}/${databaseId.database}) which is not ` +\n `supported. It will be treated as a reference in the current ` +\n `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` +\n `instead.`\n );\n }\n return key;\n }\n\n protected abstract convertReference(name: string): unknown;\n\n protected abstract convertBytes(bytes: ByteString): unknown;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData as PublicDocumentData,\n SetOptions as PublicSetOptions\n} from '@firebase/firestore-types';\nimport { getModularInstance } from '@firebase/util';\n\nimport { LimitType } from '../core/query';\nimport { DeleteMutation, Precondition } from '../model/mutation';\nimport {\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc,\n invokeRunQueryRpc\n} from '../remote/datastore';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { cast } from '../util/input_validation';\n\nimport { Bytes } from './bytes';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { validateHasExplicitOrderByForLimitToLast } from './query';\nimport {\n CollectionReference,\n doc,\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot\n} from './snapshot';\nimport {\n newUserDataReader,\n ParsedUpdateData,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converts custom model object of type T into `DocumentData` by applying the\n * converter if it exists.\n *\n * This function is used when converting user objects to `DocumentData`\n * because we want to provide the user with a more specific error message if\n * their `set()` or fails due to invalid data originating from a `toFirestore()`\n * call.\n */\nexport function applyFirestoreDataConverter(\n converter: UntypedFirestoreDataConverter | null,\n value: WithFieldValue | PartialWithFieldValue,\n options?: PublicSetOptions\n): PublicDocumentData {\n let convertedValue;\n if (converter) {\n if (options && (options.merge || options.mergeFields)) {\n // Cast to `any` in order to satisfy the union type constraint on\n // toFirestore().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n convertedValue = (converter as any).toFirestore(value, options);\n } else {\n convertedValue = converter.toFirestore(value as WithFieldValue);\n }\n } else {\n convertedValue = value as PublicDocumentData;\n }\n return convertedValue;\n}\n\nexport class LiteUserDataWriter extends AbstractUserDataWriter {\n constructor(protected firestore: Firestore) {\n super();\n }\n\n protected convertBytes(bytes: ByteString): Bytes {\n return new Bytes(bytes);\n }\n\n protected convertReference(name: string): DocumentReference {\n const key = this.convertDocumentKey(name, this.firestore._databaseId);\n return new DocumentReference(this.firestore, /* converter= */ null, key);\n }\n}\n\n/**\n * Reads the document referred to by the specified document reference.\n *\n * All documents are directly fetched from the server, even if the document was\n * previously read or modified. Recent modifications are only reflected in the\n * retrieved `DocumentSnapshot` if they have already been applied by the\n * backend. If the client is offline, the read fails. If you like to use\n * caching or see local modifications, please use the full Firestore SDK.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the current\n * document contents.\n */\nexport function getDoc(\n reference: DocumentReference\n): Promise> {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n const userDataWriter = new LiteUserDataWriter(reference.firestore);\n\n return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then(\n result => {\n hardAssert(\n result.length === 1,\n 0x3d02,\n 'Expected a single document result'\n );\n const document = result[0];\n return new DocumentSnapshot(\n reference.firestore,\n userDataWriter,\n reference._key,\n document.isFoundDocument() ? document : null,\n reference.converter\n );\n }\n );\n}\n\n/**\n * Executes the query and returns the results as a {@link QuerySnapshot}.\n *\n * All queries are executed directly by the server, even if the query was\n * previously executed. Recent modifications are only reflected in the retrieved\n * results if they have already been applied by the backend. If the client is\n * offline, the operation fails. To see previously cached result and local\n * modifications, use the full Firestore SDK.\n *\n * @param query - The `Query` to execute.\n * @returns A Promise that will be resolved with the results of the query.\n */\nexport function getDocs(\n query: Query\n): Promise> {\n query = cast>(query, Query);\n validateHasExplicitOrderByForLimitToLast(query._query);\n\n const datastore = getDatastore(query.firestore);\n const userDataWriter = new LiteUserDataWriter(query.firestore);\n return invokeRunQueryRpc(datastore, query._query).then(result => {\n const docs = result.map(\n doc =>\n new QueryDocumentSnapshot(\n query.firestore,\n userDataWriter,\n doc.key,\n doc,\n query.converter\n )\n );\n\n if (query._query.limitType === LimitType.Last) {\n // Limit to last queries reverse the orderBy constraint that was\n // specified by the user. As such, we need to reverse the order of the\n // results to return the documents in the expected order.\n docs.reverse();\n }\n\n return new QuerySnapshot(query, docs);\n });\n}\n\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\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 * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\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 convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data,\n options\n );\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'setDoc',\n reference._key,\n convertedValue,\n reference.converter !== null,\n options\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference`. The update will fail if applied to a document that does\n * not exist.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\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 * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\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 dataReader = newUserDataReader(reference.firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed: ParsedUpdateData;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData\n );\n }\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.exists(true))\n ]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * The deletion will only be reflected in document reads that occur after the\n * returned promise resolves. If the client is offline, the\n * delete fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to delete.\n * @returns A `Promise` resolved once the document has been successfully\n * deleted from the backend.\n */\nexport function deleteDoc(\n reference: DocumentReference\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n new DeleteMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend.\n */\nexport function addDoc(\n reference: CollectionReference,\n data: WithFieldValue\n): Promise> {\n reference = cast>(\n reference,\n CollectionReference\n );\n const docRef = doc(reference);\n\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data as PartialWithFieldValue\n );\n\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'addDoc',\n docRef._key,\n convertedValue,\n docRef.converter !== null,\n {}\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(docRef._key, Precondition.exists(false))\n ]).then(() => docRef);\n}\n","/**\n * @license\n * Copyright 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 { deepEqual } from '@firebase/util';\n\nimport { AggregateImpl } from '../core/aggregate';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { invokeRunAggregationQueryRpc } from '../remote/datastore';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport {\n AggregateField,\n AggregateQuerySnapshot,\n AggregateSpec\n} from './aggregate_types';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { DocumentData, Query, queryEqual } from './reference';\nimport { LiteUserDataWriter } from './reference_impl';\nimport { fieldPathFromArgument } from './user_data_reader';\n\n/**\n * Calculates the number of documents in the result set of the given query\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can\n * count the documents in cases where the result set is prohibitively large to\n * download entirely (thousands of documents).\n *\n * @param query The query whose result set size is calculated.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */\nexport function getCount(\n query: Query\n): Promise<\n AggregateQuerySnapshot<\n { count: AggregateField },\n AppModelType,\n DbModelType\n >\n> {\n const countQuerySpec: { count: AggregateField } = {\n count: count()\n };\n\n return getAggregate(query, countQuerySpec);\n}\n\n/**\n * Calculates the specified aggregations over the documents in the result\n * set of the given query without actually downloading the documents.\n *\n * Using this function to perform aggregations is efficient because only the\n * final aggregation values, not the documents' data, are downloaded. This\n * function can perform aggregations of the documents in cases where the result\n * set is prohibitively large to download entirely (thousands of documents).\n *\n * @param query The query whose result set is aggregated over.\n * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates\n * to perform over the result set. The AggregateSpec specifies aliases for each\n * aggregate, which can be used to retrieve the aggregate result.\n * @example\n * ```typescript\n * const aggregateSnapshot = await getAggregate(query, {\n * countOfDocs: count(),\n * totalHours: sum('hours'),\n * averageScore: average('score')\n * });\n *\n * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;\n * const totalHours: number = aggregateSnapshot.data().totalHours;\n * const averageScore: number | null = aggregateSnapshot.data().averageScore;\n * ```\n */\nexport function getAggregate<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n aggregateSpec: AggregateSpecType\n): Promise<\n AggregateQuerySnapshot\n> {\n const firestore = cast(query.firestore, Firestore);\n const datastore = getDatastore(firestore);\n\n const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n\n // Run the aggregation and convert the results\n return invokeRunAggregationQueryRpc(\n datastore,\n query._query,\n internalAggregates\n ).then(aggregateResult =>\n convertToAggregateQuerySnapshot(firestore, query, aggregateResult)\n );\n}\n\nfunction convertToAggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n query: Query,\n aggregateResult: ApiClientObjectMap\n): AggregateQuerySnapshot {\n const userDataWriter = new LiteUserDataWriter(firestore);\n const querySnapshot = new AggregateQuerySnapshot<\n AggregateSpecType,\n AppModelType,\n DbModelType\n >(query, userDataWriter, aggregateResult);\n return querySnapshot;\n}\n\n/**\n * Create an AggregateField object that can be used to compute the sum of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to sum across the result set.\n */\nexport function sum(field: string | FieldPath): AggregateField {\n return new AggregateField('sum', fieldPathFromArgument('sum', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the average of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to average across the result set.\n */\nexport function average(\n field: string | FieldPath\n): AggregateField {\n return new AggregateField('avg', fieldPathFromArgument('average', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the count of\n * documents in the result set of a query.\n */\nexport function count(): AggregateField {\n return new AggregateField('count');\n}\n\n/**\n * Compares two 'AggregateField` instances for equality.\n *\n * @param left Compare this AggregateField to the `right`.\n * @param right Compare this AggregateField to the `left`.\n */\nexport function aggregateFieldEqual(\n left: AggregateField,\n right: AggregateField\n): boolean {\n return (\n left instanceof AggregateField &&\n right instanceof AggregateField &&\n left.aggregateType === right.aggregateType &&\n left._internalFieldPath?.canonicalString() ===\n right._internalFieldPath?.canonicalString()\n );\n}\n\n/**\n * Compares two `AggregateQuerySnapshot` instances for equality.\n *\n * Two `AggregateQuerySnapshot` instances are considered \"equal\" if they have\n * underlying queries that compare equal, and the same data.\n *\n * @param left - The first `AggregateQuerySnapshot` to compare.\n * @param right - The second `AggregateQuerySnapshot` to compare.\n *\n * @returns `true` if the objects are \"equal\", as defined above, or `false`\n * otherwise.\n */\nexport function aggregateQuerySnapshotEqual<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n left: AggregateQuerySnapshot,\n right: AggregateQuerySnapshot\n): boolean {\n return (\n queryEqual(left.query, right.query) && deepEqual(left.data(), right.data())\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldValue } from './field_value';\nimport {\n ArrayRemoveFieldValueImpl,\n ArrayUnionFieldValueImpl,\n DeleteFieldValueImpl,\n NumericIncrementFieldValueImpl,\n ServerTimestampFieldValueImpl\n} from './user_data_reader';\nimport { VectorValue } from './vector_value';\n\n/**\n * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or\n * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.\n */\nexport function deleteField(): FieldValue {\n return new DeleteFieldValueImpl('deleteField');\n}\n\n/**\n * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to\n * include a server-generated timestamp in the written data.\n */\nexport function serverTimestamp(): FieldValue {\n return new ServerTimestampFieldValueImpl('serverTimestamp');\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array\n * value that already exists on the server. Each specified element that doesn't\n * already exist in the array will be added to the end. If the field being\n * modified is not already an array it will be overwritten with an array\n * containing exactly the specified elements.\n *\n * @param elements - The elements to union into the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`.\n */\nexport function arrayUnion(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayUnionFieldValueImpl('arrayUnion', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link (setDoc:1)} or {@link\n * updateDoc:1} that tells the server to remove the given elements from any\n * array value that already exists on the server. All instances of each element\n * specified will be removed from the array. If the field being modified is not\n * already an array it will be overwritten with an empty array.\n *\n * @param elements - The elements to remove from the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function arrayRemove(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayRemoveFieldValueImpl('arrayRemove', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by\n * the given value.\n *\n * If either the operand or the current field value uses floating point\n * precision, all arithmetic follows IEEE 754 semantics. If both values are\n * integers, values outside of JavaScript's safe number range\n * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to\n * precision loss. Furthermore, once processed by the Firestore backend, all\n * integer operations are capped between -2^63 and 2^63-1.\n *\n * If the current field value is not of type `number`, or if the field does not\n * yet exist, the transformation sets the field to the given value.\n *\n * @param n - The value to increment by.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function increment(n: number): FieldValue {\n return new NumericIncrementFieldValueImpl('increment', n);\n}\n\n/**\n * Creates a new `VectorValue` constructed with a copy of the given array of numbers.\n *\n * @param values - Create a `VectorValue` instance with a copy of this array of numbers.\n *\n * @returns A new `VectorValue` constructed with a copy of the given array of numbers.\n */\nexport function vector(values?: number[]): VectorValue {\n return new VectorValue(values);\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Compat, getModularInstance } from '@firebase/util';\n\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { invokeCommitRpc } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport { applyFirestoreDataConverter } from './reference_impl';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\n\n/**\n * A write batch, used to perform multiple writes as a single atomic unit.\n *\n * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It\n * provides methods for adding writes to the write batch. None of the writes\n * will be committed (or visible locally) until {@link WriteBatch.commit} is\n * called.\n */\nexport class WriteBatch {\n // This is the lite version of the WriteBatch API used in the legacy SDK. The\n // class is a close copy but takes different input types.\n\n private readonly _dataReader: UserDataReader;\n private _mutations = [] as Mutation[];\n private _committed = false;\n\n /** @hideconstructor */\n constructor(\n private readonly _firestore: Firestore,\n private readonly _commitHandler: (m: Mutation[]) => Promise\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): WriteBatch;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): WriteBatch;\n set(\n documentRef: DocumentReference,\n data: WithFieldValue | PartialWithFieldValue,\n options?: SetOptions\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n data,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'WriteBatch.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._mutations.push(parsed.toMutation(ref._key, Precondition.none()));\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): WriteBatch;\n /**\n * Updates fields in the document referred to by this {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be update by providing dot-separated field path strings\n * or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._mutations.push(\n parsed.toMutation(ref._key, Precondition.exists(true))\n );\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n this._mutations = this._mutations.concat(\n new DeleteMutation(ref._key, Precondition.none())\n );\n return this;\n }\n\n /**\n * Commits all of the writes in this write batch as a single atomic unit.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `Promise` resolved once all of the writes in the batch have been\n * successfully written to the backend as an atomic unit (note that it won't\n * resolve while you're offline).\n */\n commit(): Promise {\n this._verifyNotCommitted();\n this._committed = true;\n if (this._mutations.length > 0) {\n return this._commitHandler(this._mutations);\n }\n\n return Promise.resolve();\n }\n\n private _verifyNotCommitted(): void {\n if (this._committed) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A write batch can no longer be used after commit() ' +\n 'has been called.'\n );\n }\n }\n}\n\nexport function validateReference<\n AppModelType,\n DbModelType extends DocumentData\n>(\n documentRef:\n | DocumentReference\n | Compat>,\n firestore: Firestore\n): DocumentReference {\n documentRef = getModularInstance(documentRef);\n\n if (documentRef.firestore !== firestore) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Provided document reference is from a different Firestore instance.'\n );\n } else {\n return documentRef as DocumentReference;\n }\n}\n\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single WriteBatch\n * is 500.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `WriteBatch` that can be used to atomically execute multiple\n * writes.\n */\nexport function writeBatch(firestore: Firestore): WriteBatch {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n return new WriteBatch(firestore, writes =>\n invokeCommitRpc(datastore, writes)\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParsedSetData, ParsedUpdateData } from '../lite-api/user_data_reader';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n DeleteMutation,\n Mutation,\n Precondition,\n VerifyMutation\n} from '../model/mutation';\nimport {\n Datastore,\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc\n} from '../remote/datastore';\nimport { fail, debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { SnapshotVersion } from './snapshot_version';\n\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nexport class Transaction {\n // The version of each document that was read during this transaction.\n private readVersions = new Map();\n private mutations: Mutation[] = [];\n private committed = false;\n\n /**\n * A deferred usage error that occurred previously in this transaction that\n * will cause the transaction to fail once it actually commits.\n */\n private lastTransactionError: FirestoreError | null = null;\n\n /**\n * Set of documents that have been written in the transaction.\n *\n * When there's more than one write to the same key in a transaction, any\n * writes after the first are handled differently.\n */\n private writtenDocs: Set = new Set();\n\n constructor(private datastore: Datastore) {}\n\n async lookup(keys: DocumentKey[]): Promise {\n this.ensureCommitNotCalled();\n\n if (this.mutations.length > 0) {\n this.lastTransactionError = new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Firestore transactions require all reads to be executed before all writes.'\n );\n throw this.lastTransactionError;\n }\n const docs = await invokeBatchGetDocumentsRpc(this.datastore, keys);\n docs.forEach(doc => this.recordVersion(doc));\n return docs;\n }\n\n set(key: DocumentKey, data: ParsedSetData): void {\n this.write(data.toMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n update(key: DocumentKey, data: ParsedUpdateData): void {\n try {\n this.write(data.toMutation(key, this.preconditionForUpdate(key)));\n } catch (e) {\n this.lastTransactionError = e as FirestoreError | null;\n }\n this.writtenDocs.add(key.toString());\n }\n\n delete(key: DocumentKey): void {\n this.write(new DeleteMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n async commit(): Promise {\n this.ensureCommitNotCalled();\n\n if (this.lastTransactionError) {\n throw this.lastTransactionError;\n }\n const unwritten = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach(mutation => {\n unwritten.delete(mutation.key.toString());\n });\n // For each document that was read but not written to, we want to perform\n // a `verify` operation.\n unwritten.forEach((_, path) => {\n const key = DocumentKey.fromPath(path);\n this.mutations.push(new VerifyMutation(key, this.precondition(key)));\n });\n await invokeCommitRpc(this.datastore, this.mutations);\n this.committed = true;\n }\n\n private recordVersion(doc: Document): void {\n let docVersion: SnapshotVersion;\n\n if (doc.isFoundDocument()) {\n docVersion = doc.version;\n } else if (doc.isNoDocument()) {\n // Represent a deleted doc using SnapshotVersion.min().\n docVersion = SnapshotVersion.min();\n } else {\n throw fail(0xc542, 'Document in a transaction was a ', {\n documentName: doc.constructor.name\n });\n }\n\n const existingVersion = this.readVersions.get(doc.key.toString());\n if (existingVersion) {\n if (!docVersion.isEqual(existingVersion)) {\n // This transaction will fail no matter what.\n throw new FirestoreError(\n Code.ABORTED,\n 'Document version changed between two reads.'\n );\n }\n } else {\n this.readVersions.set(doc.key.toString(), docVersion);\n }\n }\n\n /**\n * Returns the version of this document when it was read in this transaction,\n * as a precondition, or no precondition if it was not read.\n */\n private precondition(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n return Precondition.exists(false);\n } else {\n return Precondition.updateTime(version);\n }\n } else {\n return Precondition.none();\n }\n }\n\n /**\n * Returns the precondition for a document if the operation is an update.\n */\n private preconditionForUpdate(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n // The first time a document is written, we want to take into account the\n // read time and existence\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n // The document doesn't exist, so fail the transaction.\n\n // This has to be validated locally because you can't send a\n // precondition that a document does not exist without changing the\n // semantics of the backend write to be an insert. This is the reverse\n // of what we want, since we want to assert that the document doesn't\n // exist but then send the update and have it fail. Since we can't\n // express that to the backend, we have to validate locally.\n\n // Note: this can change once we can send separate verify writes in the\n // transaction.\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't update a document that doesn't exist.\"\n );\n }\n // Document exists, base precondition on document update time.\n return Precondition.updateTime(version);\n } else {\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return Precondition.exists(true);\n }\n }\n\n private write(mutation: Mutation): void {\n this.ensureCommitNotCalled();\n this.mutations.push(mutation);\n }\n\n private ensureCommitNotCalled(): void {\n debugAssert(\n !this.committed,\n 'A transaction object cannot be used after its update callback has been invoked.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\n\nexport const DEFAULT_TRANSACTION_OPTIONS: TransactionOptions = {\n maxAttempts: 5\n};\n\n/**\n * Options to customize transaction behavior.\n */\nexport declare interface TransactionOptions {\n /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */\n readonly maxAttempts: number;\n}\n\nexport function validateTransactionOptions(options: TransactionOptions): void {\n if (options.maxAttempts < 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Max attempts must be at least 1'\n );\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ExponentialBackoff } from '../remote/backoff';\nimport { Datastore } from '../remote/datastore';\nimport { isPermanentError } from '../remote/rpc_error';\nimport { AsyncQueue, TimerId } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport { Deferred } from '../util/promise';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Transaction } from './transaction';\nimport { TransactionOptions } from './transaction_options';\n\n/**\n * TransactionRunner encapsulates the logic needed to run and retry transactions\n * with backoff.\n */\nexport class TransactionRunner {\n private attemptsRemaining: number;\n private backoff: ExponentialBackoff;\n\n constructor(\n private readonly asyncQueue: AsyncQueue,\n private readonly datastore: Datastore,\n private readonly options: TransactionOptions,\n private readonly updateFunction: (transaction: Transaction) => Promise,\n private readonly deferred: Deferred\n ) {\n this.attemptsRemaining = options.maxAttempts;\n this.backoff = new ExponentialBackoff(\n this.asyncQueue,\n TimerId.TransactionRetry\n );\n }\n\n /** Runs the transaction and sets the result on deferred. */\n run(): void {\n this.attemptsRemaining -= 1;\n this.runWithBackOff();\n }\n\n private runWithBackOff(): void {\n this.backoff.backoffAndRun(async () => {\n const transaction = new Transaction(this.datastore);\n const userPromise = this.tryRunUpdateFunction(transaction);\n if (userPromise) {\n userPromise\n .then(result => {\n this.asyncQueue.enqueueAndForget(() => {\n return transaction\n .commit()\n .then(() => {\n this.deferred.resolve(result);\n })\n .catch(commitError => {\n this.handleTransactionError(commitError);\n });\n });\n })\n .catch(userPromiseError => {\n this.handleTransactionError(userPromiseError);\n });\n }\n });\n }\n\n private tryRunUpdateFunction(transaction: Transaction): Promise | null {\n try {\n const userPromise = this.updateFunction(transaction);\n if (\n isNullOrUndefined(userPromise) ||\n !userPromise.catch ||\n !userPromise.then\n ) {\n this.deferred.reject(\n Error('Transaction callback must return a Promise')\n );\n return null;\n }\n return userPromise;\n } catch (error) {\n // Do not retry errors thrown by user provided updateFunction.\n this.deferred.reject(error as Error);\n return null;\n }\n }\n\n private handleTransactionError(error: Error): void {\n if (this.attemptsRemaining > 0 && this.isRetryableTransactionError(error)) {\n this.attemptsRemaining -= 1;\n this.asyncQueue.enqueueAndForget(() => {\n this.runWithBackOff();\n return Promise.resolve();\n });\n } else {\n this.deferred.reject(error);\n }\n }\n\n private isRetryableTransactionError(error: Error | undefined): boolean {\n if (error?.name === 'FirebaseError') {\n // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and\n // non-matching document versions with ABORTED. These errors should be retried.\n const code = (error as FirestoreError).code;\n return (\n code === 'aborted' ||\n code === 'failed-precondition' ||\n code === 'already-exists' ||\n !isPermanentError(code)\n );\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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(0xb815, 'AsyncQueue is already failed', {\n messageOrStack: getMessageOrStack(this.failure)\n });\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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getGlobal, 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 `indexedDB` are guarded by SimpleDb.isAvailable() and getGlobal()\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 lastClosedDbVersion: number | null = null;\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 const globals = getGlobal();\n return wrapRequest(\n globals.indexedDB.deleteDatabase(name)\n ).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\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport {\n DEFAULT_TRANSACTION_OPTIONS,\n TransactionOptions as TransactionOptionsInternal,\n validateTransactionOptions\n} from '../core/transaction_options';\nimport { TransactionRunner } from '../core/transaction_runner';\nimport { fail } from '../util/assert';\nimport { newAsyncQueue } from '../util/async_queue_impl';\nimport { cast } from '../util/input_validation';\nimport { Deferred } from '../util/promise';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n applyFirestoreDataConverter,\n LiteUserDataWriter\n} from './reference_impl';\nimport { DocumentSnapshot } from './snapshot';\nimport { TransactionOptions } from './transaction_options';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\nimport { validateReference } from './write_batch';\n\n// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the\n// legacy SDK.\n\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nexport class Transaction {\n // This is the tree-shakeable version of the Transaction class used in the\n // legacy SDK. The class is a close copy but takes different input and output\n // types. The firestore-exp SDK further extends this class to return its API\n // type.\n\n private readonly _dataReader: UserDataReader;\n\n /** @hideconstructor */\n constructor(\n protected readonly _firestore: Firestore,\n private readonly _transaction: InternalTransaction\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */\n get(\n documentRef: DocumentReference\n ): Promise> {\n const ref = validateReference(documentRef, this._firestore);\n const userDataWriter = new LiteUserDataWriter(this._firestore);\n return this._transaction.lookup([ref._key]).then(docs => {\n if (!docs || docs.length !== 1) {\n return fail(0x5de9, 'Mismatch in docs returned from document lookup.');\n }\n const doc = docs[0];\n if (doc.isFoundDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n doc.key,\n doc,\n ref.converter\n );\n } else if (doc.isNoDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n ref._key,\n null,\n ref.converter\n );\n } else {\n throw fail(\n 0x4801,\n 'BatchGetDocumentsRequest returned unexpected document',\n {\n doc\n }\n );\n }\n });\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): this;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): this;\n set(\n documentRef: DocumentReference,\n value: PartialWithFieldValue,\n options?: SetOptions\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n value,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'Transaction.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._transaction.set(ref._key, parsed);\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): this;\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key/value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._transaction.update(ref._key, parsed);\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n this._transaction.delete(ref._key);\n return this;\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */\nexport function runTransaction(\n firestore: Firestore,\n updateFunction: (transaction: Transaction) => Promise,\n options?: TransactionOptions\n): Promise {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n const optionsWithDefaults: TransactionOptionsInternal = {\n ...DEFAULT_TRANSACTION_OPTIONS,\n ...options\n };\n validateTransactionOptions(optionsWithDefaults);\n const deferred = new Deferred();\n new TransactionRunner(\n newAsyncQueue(),\n datastore,\n optionsWithDefaults,\n internalTransaction =>\n updateFunction(new Transaction(firestore, internalTransaction)),\n deferred\n ).run();\n return deferred.promise;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 { version } from '../package.json';\nimport {\n LiteAppCheckTokenProvider,\n LiteAuthCredentialsProvider\n} from '../src/api/credentials';\nimport { databaseIdFromApp } from '../src/core/database_info';\nimport { setSDKVersion } from '../src/core/version';\nimport { Firestore } from '../src/lite-api/database';\n\ndeclare module '@firebase/component' {\n interface NameServiceMapping {\n 'firestore/lite': Firestore;\n }\n}\n\nexport function registerFirestore(): void {\n setSDKVersion(`${SDK_VERSION}_lite`);\n _registerComponent(\n new Component(\n 'firestore/lite',\n (container, { instanceIdentifier: databaseId, options: settings }) => {\n const app = container.getProvider('app').getImmediate()!;\n const firestoreInstance = new Firestore(\n new LiteAuthCredentialsProvider(\n container.getProvider('auth-internal')\n ),\n new LiteAppCheckTokenProvider(\n app,\n container.getProvider('app-check-internal')\n ),\n databaseIdFromApp(app, databaseId),\n app\n );\n if (settings) {\n firestoreInstance._setSettings(settings);\n }\n return firestoreInstance;\n },\n 'PUBLIC' as ComponentType.PUBLIC\n ).setMultipleInstances(true)\n );\n // RUNTIME_ENV and BUILD_TARGET are replaced by real values during the compilation\n registerVersion('firestore-lite', version, '__RUNTIME_ENV__');\n registerVersion('firestore-lite', version, '__BUILD_TARGET__');\n}\n","/**\n * Firestore Lite\n *\n * @remarks Firestore Lite is a small online-only SDK that allows read\n * and write access to your Firestore database. All operations connect\n * directly to the backend, and `onSnapshot()` APIs are not supported.\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 { registerFirestore } from './register';\nregisterFirestore();\n\nexport {\n aggregateQuerySnapshotEqual,\n getCount,\n getAggregate,\n count,\n sum,\n average,\n aggregateFieldEqual\n} from '../src/lite-api/aggregate';\n\nexport {\n AggregateField,\n AggregateFieldType,\n AggregateSpec,\n AggregateSpecData,\n AggregateQuerySnapshot,\n AggregateType\n} from '../src/lite-api/aggregate_types';\n\nexport { FirestoreSettings as Settings } from '../src/lite-api/settings';\n\nexport {\n Firestore as Firestore,\n EmulatorMockTokenOptions,\n initializeFirestore,\n getFirestore,\n terminate,\n connectFirestoreEmulator\n} from '../src/lite-api/database';\n\nexport {\n DocumentData,\n UpdateData,\n WithFieldValue,\n PartialWithFieldValue,\n SetOptions,\n DocumentReference,\n Query,\n CollectionReference,\n collection,\n collectionGroup,\n doc,\n refEqual,\n queryEqual\n} from '../src/lite-api/reference';\n\nexport {\n and,\n endAt,\n endBefore,\n startAt,\n startAfter,\n limit,\n limitToLast,\n where,\n or,\n orderBy,\n query,\n QueryConstraint,\n QueryConstraintType,\n QueryCompositeFilterConstraint,\n QueryFilterConstraint,\n QueryFieldFilterConstraint,\n QueryOrderByConstraint,\n QueryLimitConstraint,\n QueryNonFilterConstraint,\n QueryStartAtConstraint,\n QueryEndAtConstraint,\n OrderByDirection,\n WhereFilterOp\n} from '../src/lite-api/query';\n\nexport {\n addDoc,\n deleteDoc,\n updateDoc,\n setDoc,\n getDoc,\n getDocs\n} from '../src/lite-api/reference_impl';\n\nexport {\n Primitive,\n NestedUpdateFields,\n ChildUpdateFields,\n AddPrefixToKeys,\n UnionToIntersection\n} from '../src/lite-api/types';\n\n// TODO(firestorelite): Add tests when Queries are usable\nexport { FieldPath, documentId } from '../src/lite-api/field_path';\n\n// TODO(firestorelite): Add tests when setDoc() is available\nexport { FieldValue } from '../src/lite-api/field_value';\n\nexport {\n increment,\n arrayRemove,\n arrayUnion,\n serverTimestamp,\n deleteField,\n vector\n} from '../src/lite-api/field_value_impl';\n\nexport {\n FirestoreDataConverter,\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot,\n snapshotEqual\n} from '../src/lite-api/snapshot';\n\nexport { VectorValue } from '../src/lite-api/vector_value';\n\nexport { WriteBatch, writeBatch } from '../src/lite-api/write_batch';\n\nexport { TransactionOptions } from '../src/lite-api/transaction_options';\n\nexport { Transaction, runTransaction } from '../src/lite-api/transaction';\n\nexport { setLogLevel, LogLevelString as LogLevel } from '../src/util/log';\n\nexport { Bytes } from '../src/lite-api/bytes';\n\nexport { GeoPoint } from '../src/lite-api/geo_point';\n\nexport { Timestamp } from '../src/lite-api/timestamp';\n\nexport { FirestoreErrorCode, FirestoreError } from '../src/util/error';\n"],"names":["User","constructor","uid","this","isAuthenticated","toKey","isEqual","otherUser","UNAUTHENTICATED","GOOGLE_CREDENTIALS","FIRST_PARTY","MOCK_USER","SDK_VERSION","__PRIVATE_logClient","Logger","setLogLevel","logLevel","__PRIVATE_logDebug","msg","obj","LogLevel","DEBUG","args","map","__PRIVATE_argToString","debug","__PRIVATE_logError","ERROR","error","__PRIVATE_logWarn","WARN","warn","__PRIVATE_formatJSON","value","JSON","stringify","e","fail","id","__PRIVATE_messageOrContext","context","message","__PRIVATE__fail","__PRIVATE_failure","toString","undefined","Error","__PRIVATE_hardAssert","assertion","__PRIVATE_debugCast","Code","FirestoreError","FirebaseError","code","super","name","__PRIVATE_Deferred","promise","Promise","resolve","reject","__PRIVATE_OAuthToken","user","type","headers","Map","set","__PRIVATE_EmptyAuthCredentialsProvider","getToken","invalidateToken","start","asyncQueue","changeListener","enqueueRetryable","shutdown","__PRIVATE_EmulatorAuthCredentialsProvider","token","__PRIVATE_LiteAuthCredentialsProvider","__PRIVATE_authProvider","auth","onInit","then","__PRIVATE_tokenData","accessToken","getUid","__PRIVATE_FirstPartyToken","__PRIVATE_sessionIndex","__PRIVATE_iamToken","__PRIVATE_authTokenFactory","__PRIVATE_getAuthToken","__PRIVATE__headers","__PRIVATE_authHeaderTokenValue","__PRIVATE_FirstPartyAuthCredentialsProvider","AppCheckToken","length","__PRIVATE_LiteAppCheckTokenProvider","app","__PRIVATE_appCheckProvider","appCheck","__PRIVATE_serverAppAppCheckToken","_isFirebaseServerApp","settings","appCheckToken","tokenResult","DatabaseInfo","databaseId","appId","persistenceKey","host","ssl","forceLongPolling","autoDetectLongPolling","longPollingOptions","useFetchStreams","isUsingEmulator","__PRIVATE_DEFAULT_DATABASE_NAME","DatabaseId","projectId","database","empty","isDefaultDatabase","other","__PRIVATE_randomBytes","__PRIVATE_nBytes","crypto","self","bytes","Uint8Array","getRandomValues","__PRIVATE_i","Math","floor","random","__PRIVATE_AutoId","newId","__PRIVATE_chars","__PRIVATE_maxMultiple","__PRIVATE_autoId","charAt","__PRIVATE_primitiveComparator","left","right","__PRIVATE_compareUtf8Strings","min","__PRIVATE_leftChar","__PRIVATE_rightChar","__PRIVATE_isSurrogate","__PRIVATE_MIN_SURROGATE","__PRIVATE_MAX_SURROGATE","s","c","charCodeAt","__PRIVATE_arrayEquals","comparator","every","index","__PRIVATE_DOCUMENT_KEY_NAME","BasePath","segments","offset","range","len","child","nameOrPath","slice","limit","forEach","segment","push","construct","popFirst","size","popLast","firstSegment","lastSegment","get","isEmpty","isPrefixOf","isImmediateParentOf","potentialChild","fn","end","toArray","p1","p2","comparison","compareSegments","__PRIVATE_lhs","__PRIVATE_rhs","__PRIVATE_isLhsNumeric","isNumericId","__PRIVATE_isRhsNumeric","extractNumericId","compare","startsWith","endsWith","Integer","fromString","substring","ResourcePath","canonicalString","join","toUriEncodedString","encodeURIComponent","pathComponents","path","indexOf","split","filter","emptyPath","__PRIVATE_identifierRegExp","FieldPath","isValidIdentifier","test","str","replace","isKeyField","keyField","fromServerFormat","current","__PRIVATE_addCurrentSegment","__PRIVATE_inBackticks","next","DocumentKey","fromPath","fromName","collectionGroup","hasCollectionId","collectionId","getCollectionGroup","getCollectionPath","k1","k2","isDocumentKey","fromSegments","__PRIVATE_validateNonEmptyArgument","__PRIVATE_functionName","__PRIVATE_argumentName","__PRIVATE_argument","__PRIVATE_validateDocumentPath","__PRIVATE_validateCollectionPath","__PRIVATE_isPlainObject","input","Object","getPrototypeOf","prototype","__PRIVATE_valueDescription","Array","__PRIVATE_customObjectName","__PRIVATE_tryGetCustomObjectType","__PRIVATE_cast","_delegate","description","__PRIVATE_validatePositiveNumber","n","__PRIVATE_cloneLongPollingOptions","options","clone","timeoutSeconds","__PRIVATE_lastUniqueDebugId","__PRIVATE_generateUniqueDebugId","__PRIVATE_generateInitialUniqueDebugId","round","__PRIVATE_maxResult","__PRIVATE_isNullOrUndefined","__PRIVATE_isNegativeZero","__PRIVATE_LOG_TAG","__PRIVATE_RPC_NAME_URL_MAPPING","__PRIVATE_RestConnection","__PRIVATE_shouldResourcePathBeIncludedInRequest","databaseInfo","proto","__PRIVATE_baseUrl","__PRIVATE_databasePath","__PRIVATE_requestParams","__PRIVATE_invokeRPC","__PRIVATE_rpcName","__PRIVATE_req","__PRIVATE_authToken","streamId","url","__PRIVATE_makeUrl","__PRIVATE_modifyHeadersForRequest","URL","__PRIVATE_forwardCredentials","isCloudWorkstation","__PRIVATE_performRPCRequest","response","err","__PRIVATE_invokeStreamingRPC","request","__PRIVATE_expectedResponseCount","__PRIVATE_getGoogApiClientValue","key","__PRIVATE_urlRpcName","terminate","__PRIVATE_RpcCode","RpcCode","__PRIVATE_mapCodeFromHttpStatus","status","__PRIVATE_FetchConnection","__PRIVATE_openStream","body","__PRIVATE_requestJson","__PRIVATE_fetchArgs","method","credentials","fetch","statusText","ok","__PRIVATE_errorResponse","json","isArray","__PRIVATE_errorMessage","__PRIVATE_AggregateImpl","alias","aggregateType","fieldPath","__PRIVATE_objectSize","count","hasOwnProperty","call","__PRIVATE_Base64DecodeError","__PRIVATE_WEB_SAFE","__PRIVATE_decodeBase64","__PRIVATE_encoded","String","fromCharCode","apply","base64","decodeStringToByteArray","DecodeBase64StringError","ByteString","binaryString","fromBase64String","fromUint8Array","array","__PRIVATE_binaryStringFromUint8Array","Symbol","iterator","done","toBase64","__PRIVATE_encodeBase64","raw","encodeByteArray","toUint8Array","__PRIVATE_uint8ArrayFromBinaryString","buffer","approximateByteSize","compareTo","EMPTY_BYTE_STRING","__PRIVATE_ISO_TIMESTAMP_REG_EXP","RegExp","__PRIVATE_normalizeTimestamp","date","nanos","__PRIVATE_fraction","exec","timestamp","__PRIVATE_nanoStr","substr","Number","__PRIVATE_parsedDate","Date","seconds","getTime","__PRIVATE_normalizeNumber","__PRIVATE_normalizeByteString","blob","property","typeString","__PRIVATE_optionalValue","result","__PRIVATE_validateJSON","__PRIVATE_schema","__PRIVATE_fieldValue","__PRIVATE_MIN_SECONDS","__PRIVATE_MS_TO_NANOS","Timestamp","now","fromMillis","fromDate","milliseconds","nanoseconds","toDate","toMillis","_compareTo","toJSON","_jsonSchemaVersion","fromJSON","_jsonSchema","valueOf","__PRIVATE_adjustedSeconds","padStart","__PRIVATE_isServerTimestamp","mapValue","fields","stringValue","__PRIVATE_getPreviousValue","previousValue","__PRIVATE_getLocalWriteTime","localWriteTime","timestampValue","__PRIVATE_TYPE_KEY","__PRIVATE_MAX_VALUE_TYPE","MAX_VALUE","__type__","__PRIVATE_VECTOR_VALUE_SENTINEL","__PRIVATE_VECTOR_MAP_VECTORS_KEY","__PRIVATE_typeOrder","__PRIVATE_isMaxValue","__PRIVATE_isVectorValue","__PRIVATE_valueEquals","__PRIVATE_leftType","booleanValue","__PRIVATE_timestampEquals","__PRIVATE_leftTimestamp","__PRIVATE_rightTimestamp","__PRIVATE_blobEquals","bytesValue","referenceValue","__PRIVATE_geoPointEquals","geoPointValue","latitude","longitude","__PRIVATE_numberEquals","integerValue","__PRIVATE_n1","doubleValue","__PRIVATE_n2","isNaN","arrayValue","values","__PRIVATE_objectEquals","__PRIVATE_leftMap","__PRIVATE_rightMap","__PRIVATE_arrayValueContains","__PRIVATE_haystack","__PRIVATE_needle","find","v","__PRIVATE_valueCompare","__PRIVATE_rightType","__PRIVATE_compareNumbers","__PRIVATE_leftNumber","__PRIVATE_rightNumber","__PRIVATE_compareTimestamps","__PRIVATE_compareBlobs","__PRIVATE_leftBytes","__PRIVATE_rightBytes","__PRIVATE_compareReferences","__PRIVATE_leftPath","__PRIVATE_rightPath","__PRIVATE_leftSegments","__PRIVATE_rightSegments","__PRIVATE_compareGeoPoints","__PRIVATE_compareArrays","__PRIVATE_compareVectors","__PRIVATE_leftArrayValue","__PRIVATE_rightArrayValue","__PRIVATE_lengthCompare","__PRIVATE_compareMaps","__PRIVATE_leftKeys","keys","__PRIVATE_rightKeys","sort","__PRIVATE_keyCompare","__PRIVATE_leftArray","__PRIVATE_rightArray","__PRIVATE_refValue","__PRIVATE_isNullValue","__PRIVATE_isNanValue","__PRIVATE_isMapValue","__PRIVATE_deepClone","source","target","val","Bound","position","inclusive","__PRIVATE_boundEquals","Filter","FieldFilter","field","op","create","createKeyFieldInFilter","__PRIVATE_KeyFieldFilter","__PRIVATE_ArrayContainsFilter","__PRIVATE_InFilter","__PRIVATE_NotInFilter","__PRIVATE_ArrayContainsAnyFilter","__PRIVATE_KeyFieldInFilter","__PRIVATE_KeyFieldNotInFilter","matches","doc","data","nullValue","matchesComparison","operator","isInequality","getFlattenedFilters","getFilters","CompositeFilter","filters","__PRIVATE_memoizedFlattenedFilters","__PRIVATE_compositeFilterIsConjunction","compositeFilter","reduce","__PRIVATE_subfilter","concat","assign","__PRIVATE_filterEquals","__PRIVATE_f1","__PRIVATE_f2","__PRIVATE_fieldFilterEquals","__PRIVATE_compositeFilterEquals","__PRIVATE_f1Filter","__PRIVATE_extractDocumentKeysFromArrayValue","some","OrderBy","dir","__PRIVATE_orderByEquals","SnapshotVersion","fromTimestamp","max","toMicroseconds","toTimestamp","SortedMap","root","LLRBNode","EMPTY","insert","copy","BLACK","remove","node","cmp","__PRIVATE_prunedNodes","minKey","maxKey","inorderTraversal","action","k","__PRIVATE_descriptions","reverseTraversal","getIterator","SortedMapIterator","getIteratorFrom","getReverseIterator","getReverseIteratorFrom","startKey","isReverse","nodeStack","getNext","pop","hasNext","peek","color","RED","fixUp","removeMin","isRed","moveRedLeft","__PRIVATE_smallest","rotateRight","moveRedRight","rotateLeft","colorFlip","__PRIVATE_nl","__PRIVATE_nr","checkMaxDepth","__PRIVATE_blackDepth","check","pow","LLRBEmptyNode","SortedSet","has","elem","first","last","cb","forEachInRange","iter","forEachWhile","firstAfterOrEqual","SortedSetIterator","add","unionWith","__PRIVATE_thisIt","__PRIVATE_otherIt","__PRIVATE_thisElem","__PRIVATE_otherElem","__PRIVATE_res","targetId","FieldMask","extraFields","__PRIVATE_mergedMaskSet","covers","__PRIVATE_fieldMaskPath","l","r","ObjectValue","__PRIVATE_currentLevel","getFieldsMap","setAll","parent","__PRIVATE_upserts","__PRIVATE_deletes","__PRIVATE_fieldsMap","applyChanges","__PRIVATE_nestedValue","__PRIVATE_inserts","MutableDocument","documentType","version","readTime","createTime","documentState","newInvalidDocument","documentKey","newFoundDocument","newNoDocument","newUnknownDocument","convertToFoundDocument","convertToNoDocument","convertToUnknownDocument","setHasCommittedMutations","setHasLocalMutations","setReadTime","hasLocalMutations","hasCommittedMutations","hasPendingWrites","isValidDocument","isFoundDocument","isNoDocument","isUnknownDocument","mutableCopy","__PRIVATE_TargetImpl","orderBy","startAt","endAt","__PRIVATE_memoizedCanonicalId","__PRIVATE_newTarget","__PRIVATE_QueryImpl","explicitOrderBy","limitType","__PRIVATE_memoizedNormalizedOrderBy","__PRIVATE_memoizedTarget","__PRIVATE_memoizedAggregateTarget","__PRIVATE_isCollectionGroupQuery","query","__PRIVATE_queryNormalizedOrderBy","__PRIVATE_queryImpl","__PRIVATE_fieldsNormalized","Set","__PRIVATE_lastDirection","__PRIVATE_inequalityFields","__PRIVATE_getInequalityFilterFields","__PRIVATE_queryToTarget","__PRIVATE__queryToTarget","__PRIVATE_orderBys","__PRIVATE_queryWithAddedFilter","__PRIVATE_newFilters","__PRIVATE_queryEquals","__PRIVATE_targetEquals","__PRIVATE_toDouble","serializer","useProto3Json","Infinity","toNumber","isSafeInteger","isInteger","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","__PRIVATE_toInteger","TransformOperation","_","__PRIVATE_ServerTimestampTransform","__PRIVATE_ArrayUnionTransformOperation","elements","__PRIVATE_ArrayRemoveTransformOperation","__PRIVATE_NumericIncrementTransformOperation","__PRIVATE_operand","FieldTransform","transform","Precondition","updateTime","exists","none","isNone","Mutation","__PRIVATE_SetMutation","precondition","fieldTransforms","getFieldMask","__PRIVATE_PatchMutation","fieldMask","__PRIVATE_DeleteMutation","__PRIVATE_VerifyMutation","__PRIVATE_DIRECTIONS","__PRIVATE_dirs","__PRIVATE_OPERATORS","__PRIVATE_ops","__PRIVATE_COMPOSITE_OPERATORS","JsonProtoSerializer","toISOString","__PRIVATE_toBytes","__PRIVATE_toVersion","__PRIVATE_fromVersion","__PRIVATE_toResourceName","__PRIVATE_toResourcePath","__PRIVATE_resourcePath","__PRIVATE_fullyQualifiedPrefixPath","__PRIVATE_toName","__PRIVATE_resource","__PRIVATE_fromResourceName","__PRIVATE_isValidResourceName","__PRIVATE_extractLocalPathFromResourceName","__PRIVATE_resourceName","__PRIVATE_toMutationDocument","__PRIVATE_fromBatchGetDocumentsResponse","__PRIVATE_fromFound","found","__PRIVATE_fromMissing","missing","toMutation","mutation","update","delete","updateMask","__PRIVATE_toDocumentMask","__PRIVATE_mutationType","verify","updateTransforms","__PRIVATE_toFieldTransform","__PRIVATE_fieldTransform","setToServerValue","appendMissingElements","removeAllFromArray","increment","currentDocument","__PRIVATE_toPrecondition","__PRIVATE_toQueryTarget","__PRIVATE_queryTarget","structuredQuery","from","allDescendants","__PRIVATE_toQueryPath","where","__PRIVATE_toFilters","__PRIVATE_toFilter","__PRIVATE_toOrder","order","__PRIVATE_toPropertyOrder","__PRIVATE_toFieldPathReference","direction","__PRIVATE_toDirection","__PRIVATE_toInt32Proto","__PRIVATE_toStartAtCursor","cursor","before","__PRIVATE_toEndAtCursor","__PRIVATE_toOperatorName","__PRIVATE_toCompositeOperatorName","__PRIVATE_toUnaryOrFieldFilter","unaryFilter","fieldFilter","__PRIVATE_toCompositeFilter","__PRIVATE_protos","__PRIVATE_canonicalFields","fieldPaths","__PRIVATE_newSerializer","__PRIVATE_ExponentialBackoff","__PRIVATE_queue","timerId","__PRIVATE_initialDelayMs","__PRIVATE_backoffFactor","__PRIVATE_maxDelayMs","__PRIVATE_currentBaseMs","__PRIVATE_timerPromise","reset","__PRIVATE_resetToMax","__PRIVATE_backoffAndRun","cancel","__PRIVATE_desiredDelayWithJitterMs","__PRIVATE_jitterDelayMs","__PRIVATE_delaySoFarMs","__PRIVATE_lastAttemptTime","__PRIVATE_remainingDelayMs","enqueueAfterDelay","__PRIVATE_skipBackoff","skipDelay","Datastore","__PRIVATE_DatastoreImpl","authCredentials","appCheckCredentials","connection","__PRIVATE_terminated","__PRIVATE_verifyInitialized","all","catch","async","__PRIVATE_invokeCommitRpc","datastore","mutations","__PRIVATE_datastoreImpl","writes","m","__PRIVATE_invokeBatchGetDocumentsRpc","documents","docs","__PRIVATE_invokeRunQueryRpc","M","document","__PRIVATE_fromDocument","__PRIVATE_invokeRunAggregationQueryRpc","__PRIVATE_aggregates","nt","__PRIVATE_aliasMap","__PRIVATE_toRunAggregationQueryRequest","__PRIVATE_skipAliasing","aggregations","__PRIVATE_aggregationNum","__PRIVATE_aggregate","__PRIVATE_serverAlias","avg","sum","structuredAggregationQuery","__PRIVATE_queryToAggregateTarget","__PRIVATE_filteredResult","__PRIVATE_unmappedAggregateFields","aggregateFields","__PRIVATE_accumulator","__PRIVATE_datastoreInstances","__PRIVATE_getDatastore","firestore","_terminated","__PRIVATE_newConnection","__PRIVATE_makeDatabaseInfo","experimentalForceLongPolling","experimentalAutoDetectLongPolling","experimentalLongPollingOptions","_databaseId","_persistenceKey","_freezeSettings","__PRIVATE_newDatastore","_authCredentials","_appCheckCredentials","__PRIVATE_LRU_MINIMUM_CACHE_SIZE_BYTES","__PRIVATE_DEFAULT_HOST","__PRIVATE_DEFAULT_SSL","FirestoreSettingsImpl","emulatorOptions","ignoreUndefinedProperties","localCache","cacheSizeBytes","__PRIVATE_validateIsNotUsedTogether","optionName1","argument1","optionName2","argument2","__PRIVATE_validateLongPollingOptions","__PRIVATE_longPollingOptionsEqual","__PRIVATE_options1","__PRIVATE_options2","Firestore","_app","_settings","_settingsFrozen","_emulatorOptions","_terminateTask","_initialized","_setSettings","__PRIVATE_makeAuthCredentialsProvider","_getSettings","_getEmulatorOptions","_delete","_terminate","_restart","__PRIVATE_removeComponents","initializeFirestore","provider","_getProvider","isInitialized","initialize","instanceIdentifier","getFirestore","__PRIVATE_appOrDatabaseId","__PRIVATE_optionalDatabaseId","getApp","db","getImmediate","identifier","__PRIVATE_emulator","getDefaultEmulatorHostnameAndPort","connectFirestoreEmulator","port","__PRIVATE_useSsl","__PRIVATE_existingConfig","__PRIVATE_newHostSetting","pingServer","updateEmulatorBanner","__PRIVATE_newConfig","deepEqual","mockUserToken","createMockUserToken","sub","user_id","_removeServiceInstance","AggregateField","_internalFieldPath","AggregateQuerySnapshot","_userDataWriter","_data","convertObjectMap","Query","converter","_query","withConverter","DocumentReference","_key","_path","CollectionReference","referencePath","__PRIVATE_newQueryForPath","parentPath","collection","pathSegments","getModularInstance","__PRIVATE_absolutePath","__PRIVATE_newQueryForCollectionGroup","arguments","refEqual","queryEqual","Bytes","byteString","_byteString","fieldNames","_internalPath","__PRIVATE_InternalFieldPath","documentId","FieldValue","_methodName","GeoPoint","isFinite","_lat","_long","VectorValue","_values","__PRIVATE_isPrimitiveArrayEqual","vectorValues","element","__PRIVATE_RESERVED_FIELD_REGEX","ParsedSetData","ParsedUpdateData","__PRIVATE_isWrite","__PRIVATE_dataSource","__PRIVATE_ParseContextImpl","__PRIVATE_validatePath","__PRIVATE_contextWith","configuration","__PRIVATE_childContextForField","__PRIVATE_childPath","__PRIVATE_arrayElement","__PRIVATE_validatePathSegment","__PRIVATE_childContextForFieldPath","__PRIVATE_childContextForArray","__PRIVATE_createError","reason","methodName","__PRIVATE_hasConverter","__PRIVATE_targetDoc","contains","__PRIVATE_UserDataReader","__PRIVATE_createContext","__PRIVATE_newUserDataReader","__PRIVATE_parseSetData","__PRIVATE_userDataReader","merge","mergeFields","__PRIVATE_validatePlainObject","__PRIVATE_updateData","__PRIVATE_parseObject","__PRIVATE_validatedFieldPaths","__PRIVATE_stringOrFieldPath","__PRIVATE_fieldPathFromArgument","__PRIVATE_fieldMaskContains","__PRIVATE_DeleteFieldValueImpl","_toFieldTransform","__PRIVATE_createSentinelChildContext","__PRIVATE_ServerTimestampFieldValueImpl","__PRIVATE_ArrayUnionFieldValueImpl","__PRIVATE__elements","__PRIVATE_parseContext","__PRIVATE_parsedElements","__PRIVATE_parseData","arrayUnion","__PRIVATE_ArrayRemoveFieldValueImpl","__PRIVATE_NumericIncrementFieldValueImpl","__PRIVATE__operand","__PRIVATE_numericIncrement","__PRIVATE_parseUpdateData","__PRIVATE_fieldMaskPaths","__PRIVATE_fieldPathFromDotSeparatedString","__PRIVATE_childContext","__PRIVATE_parsedValue","mask","__PRIVATE_parseUpdateVarargs","moreFieldsAndValues","__PRIVATE_parseQueryValue","__PRIVATE_allowArrays","__PRIVATE_looksLikeJsonObject","__PRIVATE_parseSentinelFieldValue","__PRIVATE_parseArray","__PRIVATE_entryIndex","entry","__PRIVATE_parsedEntry","__PRIVATE_parseScalarValue","__PRIVATE_thisDb","__PRIVATE_otherDb","__PRIVATE_parseVectorValue","__PRIVATE_FIELD_PATH_RESERVED","search","__PRIVATE_hasPath","__PRIVATE_hasDocument","DocumentSnapshot","_firestore","_document","_converter","ref","snapshot","QueryDocumentSnapshot","fromFirestore","convertValue","QuerySnapshot","_docs","callback","thisArg","snapshotEqual","arg","AppliableConstraint","QueryConstraint","__PRIVATE_queryConstraint","__PRIVATE_additionalQueryConstraints","queryConstraints","__PRIVATE_validateQueryConstraintArray","__PRIVATE_compositeFilterCount","QueryCompositeFilterConstraint","__PRIVATE_fieldFilterCount","QueryFieldFilterConstraint","constraint","_apply","_field","_op","_value","_create","_parse","__PRIVATE_validateNewFieldFilter","__PRIVATE_reader","__PRIVATE_newQueryFilter","__PRIVATE_dataReader","__PRIVATE_validateDisjunctiveFilterElements","__PRIVATE_referenceList","__PRIVATE_parseDocumentIdValue","opStr","_queryConstraints","__PRIVATE_parsedFilters","__PRIVATE_parsedFilter","_getOperator","__PRIVATE_validateNewFilter","__PRIVATE_testQuery","__PRIVATE_subFilters","__PRIVATE_subFilter","_getQueryConstraints","or","__PRIVATE_validateQueryFilterConstraint","and","QueryOrderByConstraint","_direction","__PRIVATE_newQueryOrderBy","__PRIVATE_queryWithAddedOrderBy","__PRIVATE_newOrderBy","directionStr","QueryLimitConstraint","_limit","_limitType","__PRIVATE_queryWithLimit","limitToLast","QueryStartAtConstraint","_docOrFields","_inclusive","bound","__PRIVATE_newQueryBoundFromDocOrFields","__PRIVATE_queryWithStartAt","__PRIVATE_docOrFields","startAfter","QueryEndAtConstraint","__PRIVATE_queryWithEndAt","endBefore","__PRIVATE_newQueryBoundFromDocument","components","__PRIVATE_newQueryBoundFromFields","__PRIVATE_rawValue","__PRIVATE_wrapped","__PRIVATE_documentIdValue","__PRIVATE_conflictingOp","__PRIVATE_findOpInsideFilters","__PRIVATE_operators","__PRIVATE_conflictingOps","AbstractUserDataWriter","serverTimestampBehavior","convertTimestamp","convertServerTimestamp","convertBytes","convertReference","convertGeoPoint","convertArray","convertObject","convertVectorValue","__PRIVATE_normalizedValue","convertDocumentKey","expectedDatabaseId","__PRIVATE_applyFirestoreDataConverter","__PRIVATE_convertedValue","toFirestore","__PRIVATE_LiteUserDataWriter","getDoc","reference","userDataWriter","getDocs","__PRIVATE_validateHasExplicitOrderByForLimitToLast","reverse","setDoc","__PRIVATE_parsed","updateDoc","__PRIVATE_fieldOrUpdateData","deleteDoc","addDoc","__PRIVATE_docRef","getCount","getAggregate","aggregateSpec","__PRIVATE_internalAggregates","__PRIVATE_mapToArray","__PRIVATE_aggregateResult","__PRIVATE_convertToAggregateQuerySnapshot","__PRIVATE_querySnapshot","average","aggregateFieldEqual","aggregateQuerySnapshotEqual","deleteField","serverTimestamp","arrayRemove","vector","WriteBatch","_commitHandler","_mutations","_committed","_dataReader","documentRef","_verifyNotCommitted","__PRIVATE_validateReference","commit","writeBatch","Transaction","readVersions","committed","lastTransactionError","writtenDocs","lookup","ensureCommitNotCalled","recordVersion","write","preconditionForUpdate","__PRIVATE_unwritten","__PRIVATE_docVersion","__PRIVATE_documentName","__PRIVATE_existingVersion","__PRIVATE_DEFAULT_TRANSACTION_OPTIONS","maxAttempts","__PRIVATE_TransactionRunner","updateFunction","deferred","__PRIVATE_attemptsRemaining","__PRIVATE_backoff","__PRIVATE_run","__PRIVATE_runWithBackOff","transaction","__PRIVATE_userPromise","__PRIVATE_tryRunUpdateFunction","enqueueAndForget","__PRIVATE_commitError","__PRIVATE_handleTransactionError","__PRIVATE_userPromiseError","__PRIVATE_isRetryableTransactionError","__PRIVATE_isPermanentError","getDocument","DelayedOperation","targetTimeMs","removalCallback","bind","createAndSchedule","delayMs","__PRIVATE_targetTime","__PRIVATE_delayedOp","timerHandle","setTimeout","handleDelayElapsed","clearTimeout","__PRIVATE_AsyncQueueImpl","__PRIVATE_tail","__PRIVATE_retryableOps","__PRIVATE__isShuttingDown","__PRIVATE_delayedOperations","__PRIVATE_operationInProgress","__PRIVATE_skipNonRestrictedTasks","__PRIVATE_timerIdsToSkip","__PRIVATE_visibilityHandler","visibilityState","addEventListener","isShuttingDown","enqueue","enqueueAndForgetEvenWhileRestricted","__PRIVATE_verifyNotFailed","__PRIVATE_enqueueInternal","enterRestrictedMode","purgeExistingTasks","removeEventListener","task","__PRIVATE_retryNextOp","shift","__PRIVATE_isIndexedDbTransactionError","__PRIVATE_newTail","__PRIVATE_getMessageOrStack","__PRIVATE_removedOp","__PRIVATE_removeDelayedOperation","__PRIVATE_messageOrStack","verifyOperationInProgress","__PRIVATE_drain","__PRIVATE_currentTail","__PRIVATE_containsDelayedOperation","__PRIVATE_runAllDelayedOperationsUntil","__PRIVATE_lastTimerId","a","b","__PRIVATE_skipDelaysForTimerId","splice","stack","includes","_transaction","runTransaction","__PRIVATE_optionsWithDefaults","__PRIVATE_validateTransactionOptions","__PRIVATE_newAsyncQueue","__PRIVATE_internalTransaction","__PRIVATE_registerFirestore","__PRIVATE_setSDKVersion","_registerComponent","Component","container","getProvider","__PRIVATE_firestoreInstance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C5B,IAAIrxB,sCACF+pC,EAAUC,YAAY,mBAExB,IAAI9oC,oCACFC,GACA4oC,EAAUC,YAAY,wBtEiClB,SAAAE,4BACd/oC,GACAsB;YAEA,KAAK6H,OAAOE,UAAU2E,eAAeQ,MAAMxO,EAAIgK,SAAS,EAAC,gBACvD,MAAM,IAAI7M,eACRD,GACA;YAIJ,OAAO,IAAIkE,WAAWpB,EAAIgK,QAAQ3I,WAAYC;AAChD,SsE3CUynC,CAAkB/oC,GAAKS,IACvBT;QAKF,OAHIK,KACFyoC,EAAkBrY,aAAapwB,IAE1ByoC;AAAiB,QAE1B,UACAE,sBAAqB;;IAGzBC,EAAgB,kBAAkB1oB,GAAS,OAC3C0oB,EAAgB,kBAAkB1oB,GAAS;AAC7C,CCzCAioB;;"} \ No newline at end of file diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/internal.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/internal.d.ts new file mode 100644 index 0000000..4e493ac --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/internal.d.ts @@ -0,0 +1,6201 @@ +/** + * Firestore Lite + * + * @remarks Firestore Lite is a small online-only SDK that allows read + * and write access to your Firestore database. All operations connect + * directly to the backend, and `onSnapshot()` APIs are not supported. + * @packageDocumentation + */ + +import { DocumentData as DocumentData_2 } from '@firebase/firestore-types'; +import { EmulatorMockTokenOptions } from '@firebase/util'; +import { FirebaseApp } from '@firebase/app'; +import { FirebaseError } from '@firebase/util'; +import { _FirebaseService } from '@firebase/app'; +import { LogLevelString as LogLevel } from '@firebase/logger'; +import { SetOptions as SetOptions_2 } from '@firebase/firestore-types'; + +/** + * Converts Firestore's internal types to the JavaScript types that we expose + * to the user. + * + * @internal + */ +declare abstract class AbstractUserDataWriter { + convertValue(value: Value, serverTimestampBehavior?: ServerTimestampBehavior): unknown; + private convertObject; + /** + * @internal + */ + convertObjectMap(fields: ApiClientObjectMap | undefined, serverTimestampBehavior?: ServerTimestampBehavior): DocumentData_2; + /** + * @internal + */ + convertVectorValue(mapValue: MapValue): VectorValue; + private convertGeoPoint; + private convertArray; + private convertServerTimestamp; + private convertTimestamp; + protected convertDocumentKey(name: string, expectedDatabaseId: DatabaseId): DocumentKey; + protected abstract convertReference(name: string): unknown; + protected abstract convertBytes(bytes: ByteString): unknown; +} + +/** + * Describes a map whose keys are active target ids. We do not care about the type of the + * values. + */ +declare type ActiveTargets = SortedMap; + +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend. + */ +export declare function addDoc(reference: CollectionReference, data: WithFieldValue): Promise>; + +/** + * Returns a new map where every key is prefixed with the outer key appended + * to a dot. + */ +export declare type AddPrefixToKeys> = { + [K in keyof T & string as `${Prefix}.${K}`]+?: string extends K ? any : T[K]; +}; + +/** + * Represents an aggregation that can be performed by Firestore. + */ +export declare class AggregateField { + readonly _internalFieldPath?: FieldPath_2 | undefined; + /** A type string to uniquely identify instances of this class. */ + readonly type = "AggregateField"; + /** Indicates the aggregation operation of this AggregateField. */ + readonly aggregateType: AggregateType; + /** + * Create a new AggregateField + * @param aggregateType Specifies the type of aggregation operation to perform. + * @param _internalFieldPath Optionally specifies the field that is aggregated. + * @internal + */ + constructor(aggregateType?: AggregateType, _internalFieldPath?: FieldPath_2 | undefined); +} + +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ +export declare function aggregateFieldEqual(left: AggregateField, right: AggregateField): boolean; + +/** + * The union of all `AggregateField` types that are supported by Firestore. + */ +export declare type AggregateFieldType = ReturnType | ReturnType | ReturnType; + +/** + * The results of executing an aggregation query. + */ +export declare class AggregateQuerySnapshot { + private readonly _userDataWriter; + private readonly _data; + /** A type string to uniquely identify instances of this class. */ + readonly type = "AggregateQuerySnapshot"; + /** + * The underlying query over which the aggregations recorded in this + * `AggregateQuerySnapshot` were performed. + */ + readonly query: Query; + /** @hideconstructor */ + constructor(query: Query, _userDataWriter: AbstractUserDataWriter, _data: ApiClientObjectMap); + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ + data(): AggregateSpecData; +} + +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ +export declare function aggregateQuerySnapshotEqual(left: AggregateQuerySnapshot, right: AggregateQuerySnapshot): boolean; + +/** + * Specifies a set of aggregations and their aliases. + */ +export declare interface AggregateSpec { + [field: string]: AggregateFieldType; +} + +/** + * A type whose keys are taken from an `AggregateSpec`, and whose values are the + * result of the aggregation performed by the corresponding `AggregateField` + * from the input `AggregateSpec`. + */ +export declare type AggregateSpecData = { + [P in keyof T]: T[P] extends AggregateField ? U : never; +}; + +/** + * Union type representing the aggregate type to be performed. + */ +export declare type AggregateType = 'count' | 'avg' | 'sum'; + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +export declare function and(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; + +declare interface ApiClientObjectMap { + [k: string]: T; +} + +/** + * An `AppliableConstraint` is an abstraction of a constraint that can be applied + * to a Firestore query. + */ +declare abstract class AppliableConstraint { + /** + * Takes the provided {@link Query} and returns a copy of the {@link Query} with this + * {@link AppliableConstraint} applied. + */ + abstract _apply(query: Query): Query; +} + +/** + * Returns a special value that can be used with {@link (setDoc:1)} or {@link + * updateDoc:1} that tells the server to remove the given elements from any + * array value that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is not + * already an array it will be overwritten with an empty array. + * + * @param elements - The elements to remove from the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +export declare function arrayRemove(...elements: unknown[]): FieldValue; + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array + * value that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements - The elements to union into the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()`. + */ +export declare function arrayUnion(...elements: unknown[]): FieldValue; + +declare interface AsyncQueue { + readonly isShuttingDown: boolean; + /** + * Adds a new operation to the queue without waiting for it to complete (i.e. + * we ignore the Promise result). + */ + enqueueAndForget(op: () => Promise): void; + /** + * Regardless if the queue has initialized shutdown, adds a new operation to the + * queue without waiting for it to complete (i.e. we ignore the Promise result). + */ + enqueueAndForgetEvenWhileRestricted(op: () => Promise): void; + /** + * Initialize the shutdown of this queue. Once this method is called, the + * only possible way to request running an operation is through + * `enqueueEvenWhileRestricted()`. + * + * @param purgeExistingTasks Whether already enqueued tasked should be + * rejected (unless enqueued with `enqueueEvenWhileRestricted()`). Defaults + * to false. + */ + enterRestrictedMode(purgeExistingTasks?: boolean): void; + /** + * Adds a new operation to the queue. Returns a promise that will be resolved + * when the promise returned by the new operation is (with its value). + */ + enqueue(op: () => Promise): Promise; + /** + * Enqueue a retryable operation. + * + * A retryable operation is rescheduled with backoff if it fails with a + * IndexedDbTransactionError (the error type used by SimpleDb). All + * retryable operations are executed in order and only run if all prior + * operations were retried successfully. + */ + enqueueRetryable(op: () => Promise): void; + /** + * Schedules an operation to be queued on the AsyncQueue once the specified + * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel + * or fast-forward the operation prior to its running. + */ + enqueueAfterDelay(timerId: TimerId, delayMs: number, op: () => Promise): DelayedOperation; + /** + * Verifies there's an operation currently in-progress on the AsyncQueue. + * Unfortunately we can't verify that the running code is in the promise chain + * of that operation, so this isn't a foolproof check, but it should be enough + * to catch some bugs. + */ + verifyOperationInProgress(): void; +} + +/** + * @internal + */ +declare type AuthTokenFactory = () => string; + +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ +export declare function average(field: string | FieldPath): AggregateField; + +/** + * Path represents an ordered sequence of string segments. + */ +declare abstract class BasePath> { + private segments; + private offset; + private len; + constructor(segments: string[], offset?: number, length?: number); + /** + * Abstract constructor method to construct an instance of B with the given + * parameters. + */ + protected abstract construct(segments: string[], offset?: number, length?: number): B; + /** + * Returns a String representation. + * + * Implementing classes are required to provide deterministic implementations as + * the String representation is used to obtain canonical Query IDs. + */ + abstract toString(): string; + get length(): number; + isEqual(other: B): boolean; + child(nameOrPath: string | B): B; + /** The index of one past the last segment of the path. */ + private limit; + popFirst(size?: number): B; + popLast(): B; + firstSegment(): string; + lastSegment(): string; + get(index: number): string; + isEmpty(): boolean; + isPrefixOf(other: this): boolean; + isImmediateParentOf(potentialChild: this): boolean; + forEach(fn: (segment: string) => void): void; + toArray(): string[]; + /** + * Compare 2 paths segment by segment, prioritizing numeric IDs + * (e.g., "__id123__") in numeric ascending order, followed by string + * segments in lexicographical order. + */ + static comparator>(p1: BasePath, p2: BasePath): number; + private static compareSegments; + private static isNumericId; + private static extractNumericId; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * BatchID is a locally assigned ID for a batch of mutations that have been + * applied. + */ +declare type BatchId = number; + +/** + * Represents a bound of a query. + * + * The bound is specified with the given components representing a position and + * whether it's just before or just after the position (relative to whatever the + * query order is). + * + * The position represents a logical index position for a query. It's a prefix + * of values for the (potentially implicit) order by clauses of a query. + * + * Bound provides a function to determine whether a document comes before or + * after a bound. This is influenced by whether the position is just before or + * just after the provided values. + */ +declare class Bound { + readonly position: Value[]; + readonly inclusive: boolean; + constructor(position: Value[], inclusive: boolean); +} + +/** + * Provides interfaces to save and read Firestore bundles. + */ +declare interface BundleCache { + /** + * Gets the saved `BundleMetadata` for a given `bundleId`, returns undefined + * if no bundle metadata is found under the given id. + */ + getBundleMetadata(transaction: PersistenceTransaction, bundleId: string): PersistencePromise; + /** + * Saves a `BundleMetadata` from a bundle into local storage, using its id as + * the persistent key. + */ + saveBundleMetadata(transaction: PersistenceTransaction, metadata: BundleMetadata_2): PersistencePromise; + /** + * Gets a saved `NamedQuery` for the given query name. Returns undefined if + * no queries are found under the given name. + */ + getNamedQuery(transaction: PersistenceTransaction, queryName: string): PersistencePromise; + /** + * Saves a `NamedQuery` from a bundle, using its name as the persistent key. + */ + saveNamedQuery(transaction: PersistenceTransaction, query: NamedQuery_2): PersistencePromise; +} + +/** Properties of a BundledQuery. */ +declare interface BundledQuery { + /** BundledQuery parent */ + parent?: string | null; + /** BundledQuery structuredQuery */ + structuredQuery?: StructuredQuery | null; + /** BundledQuery limitType */ + limitType?: LimitType_2 | null; +} + +/** + * Represents a Firestore bundle saved by the SDK in its local storage. + */ +declare interface BundleMetadata { + /** + * Id of the bundle. It is used together with `createTime` to determine if a + * bundle has been loaded by the SDK. + */ + readonly id: string; + /** Schema version of the bundle. */ + readonly version: number; + /** + * Set to the snapshot version of the bundle if created by the Server SDKs. + * Otherwise set to SnapshotVersion.MIN. + */ + readonly createTime: SnapshotVersion; +} + +/** Properties of a BundleMetadata. */ +declare interface BundleMetadata_2 { + /** BundleMetadata id */ + id?: string | null; + /** BundleMetadata createTime */ + createTime?: Timestamp_2 | null; + /** BundleMetadata version */ + version?: number | null; + /** BundleMetadata totalDocuments */ + totalDocuments?: number | null; + /** BundleMetadata totalBytes */ + totalBytes?: number | null; +} + +/** + * An immutable object representing an array of bytes. + */ +export declare class Bytes { + _byteString: ByteString; + /** @hideconstructor */ + constructor(byteString: ByteString); + /** + * Creates a new `Bytes` object from the given Base64 string, converting it to + * bytes. + * + * @param base64 - The Base64 string used to create the `Bytes` object. + */ + static fromBase64String(base64: string): Bytes; + /** + * Creates a new `Bytes` object from the given Uint8Array. + * + * @param array - The Uint8Array used to create the `Bytes` object. + */ + static fromUint8Array(array: Uint8Array): Bytes; + /** + * Returns the underlying bytes as a Base64-encoded string. + * + * @returns The Base64-encoded string created from the `Bytes` object. + */ + toBase64(): string; + /** + * Returns the underlying bytes in a new `Uint8Array`. + * + * @returns The Uint8Array created from the `Bytes` object. + */ + toUint8Array(): Uint8Array; + /** + * Returns a string representation of the `Bytes` object. + * + * @returns A string representation of the `Bytes` object. + */ + toString(): string; + /** + * Returns true if this `Bytes` object is equal to the provided one. + * + * @param other - The `Bytes` object to compare against. + * @returns true if this `Bytes` object is equal to the provided one. + */ + isEqual(other: Bytes): boolean; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + bytes: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `Bytes` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}. + * + * @param json a JSON object represention of a `Bytes` instance + * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): Bytes; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Immutable class that represents a "proto" byte string. + * + * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when + * sent on the wire. This class abstracts away this differentiation by holding + * the proto byte string in a common class that must be converted into a string + * before being sent as a proto. + * @internal + */ +declare class ByteString { + private readonly binaryString; + static readonly EMPTY_BYTE_STRING: ByteString; + private constructor(); + static fromBase64String(base64: string): ByteString; + static fromUint8Array(array: Uint8Array): ByteString; + [Symbol.iterator](): Iterator; + toBase64(): string; + toUint8Array(): Uint8Array; + approximateByteSize(): number; + compareTo(other: ByteString): number; + isEqual(other: ByteString): boolean; +} + +declare const enum ChangeType { + Added = 0, + Removed = 1, + Modified = 2, + Metadata = 3 +} + +/** + * Helper for calculating the nested fields for a given type T1. This is needed + * to distribute union types such as `undefined | {...}` (happens for optional + * props) or `{a: A} | {b: B}`. + * + * In this use case, `V` is used to distribute the union types of `T[K]` on + * `Record`, since `T[K]` is evaluated as an expression and not distributed. + * + * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types + */ +export declare type ChildUpdateFields = V extends Record ? AddPrefixToKeys> : never; + +/** + * A randomly-generated key assigned to each Firestore instance at startup. + */ +declare type ClientId = string; + +/** + * Gets a `CollectionReference` instance that refers to the collection at + * the specified absolute path. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments to apply relative to the first + * argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(firestore: Firestore, path: string, ...pathSegments: string[]): CollectionReference; + +/** + * Gets a `CollectionReference` instance that refers to a subcollection of + * `reference` at the specified relative path. + * + * @param reference - A reference to a collection. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments to apply relative to the first + * argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(reference: CollectionReference, path: string, ...pathSegments: string[]): CollectionReference; + +/** + * Gets a `CollectionReference` instance that refers to a subcollection of + * `reference` at the specified relative path. + * + * @param reference - A reference to a Firestore document. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(reference: DocumentReference, path: string, ...pathSegments: string[]): CollectionReference; + +/** + * Creates and returns a new `Query` instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given `collectionId`. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param collectionId - Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `Query`. + */ +export declare function collectionGroup(firestore: Firestore, collectionId: string): Query; + +/** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using {@link (query:1)}). + */ +export declare class CollectionReference extends Query { + readonly _path: ResourcePath; + /** The type of this Firestore reference. */ + readonly type = "collection"; + /** @hideconstructor */ + constructor(firestore: Firestore, converter: FirestoreDataConverter | null, _path: ResourcePath); + /** The collection's identifier. */ + get id(): string; + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ + get path(): string; + /** + * A reference to the containing `DocumentReference` if this is a + * subcollection. If this isn't a subcollection, the reference is null. + */ + get parent(): DocumentReference | null; + /** + * Applies a custom data converter to this `CollectionReference`, allowing you + * to use your own custom model objects with Firestore. When you call {@link + * addDoc} with the returned `CollectionReference` instance, the provided + * converter will convert between Firestore data of type `NewDbModelType` and + * your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `CollectionReference` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter): CollectionReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `CollectionReference` that does not + * use a converter. + */ + withConverter(converter: null): CollectionReference; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +declare type Comparator = (key1: K, key2: K) => number; + +declare interface ComponentConfiguration { + asyncQueue: AsyncQueue; + databaseInfo: DatabaseInfo; + authCredentials: CredentialsProvider; + appCheckCredentials: CredentialsProvider; + clientId: ClientId; + initialUser: User; + maxConcurrentLimboResolutions: number; +} + +declare type CompositeFilterOp = 'OPERATOR_UNSPECIFIED' | 'AND' | 'OR'; + +declare const enum CompositeOperator { + OR = "or", + AND = "and" +} + +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ +export declare function connectFirestoreEmulator(firestore: Firestore, host: string, port: number, options?: { + mockUserToken?: EmulatorMockTokenOptions | string; +}): void; + +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ +export declare function count(): AggregateField; + +/** + * A Listener for credential change events. The listener should fetch a new + * token and may need to invalidate other state if the current user has also + * changed. + */ +declare type CredentialChangeListener = (credential: T) => Promise; + +/** + * Provides methods for getting the uid and token for the current user and + * listening for changes. + */ +declare interface CredentialsProvider { + /** + * Starts the credentials provider and specifies a listener to be notified of + * credential changes (sign-in / sign-out, token changes). It is immediately + * called once with the initial user. + * + * The change listener is invoked on the provided AsyncQueue. + */ + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + /** Requests a token for the current user. */ + getToken(): Promise; + /** + * Marks the last retrieved token as invalid, making the next GetToken request + * force-refresh the token. + */ + invalidateToken(): void; + shutdown(): void; +} + +/** Settings for private credentials */ +declare type CredentialsSettings = FirstPartyCredentialsSettings | ProviderCredentialsSettings; + +/** + * Represents the database ID a Firestore client is associated with. + * @internal + */ +declare class DatabaseId { + readonly projectId: string; + readonly database: string; + constructor(projectId: string, database?: string); + static empty(): DatabaseId; + get isDefaultDatabase(): boolean; + isEqual(other: {}): boolean; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +declare class DatabaseInfo { + readonly databaseId: DatabaseId; + readonly appId: string; + readonly persistenceKey: string; + readonly host: string; + readonly ssl: boolean; + readonly forceLongPolling: boolean; + readonly autoDetectLongPolling: boolean; + readonly longPollingOptions: ExperimentalLongPollingOptions; + readonly useFetchStreams: boolean; + readonly isUsingEmulator: boolean; + /** + * Constructs a DatabaseInfo using the provided host, databaseId and + * persistenceKey. + * + * @param databaseId - The database to use. + * @param appId - The Firebase App Id. + * @param persistenceKey - A unique identifier for this Firestore's local + * storage (used in conjunction with the databaseId). + * @param host - The Firestore backend host to connect to. + * @param ssl - Whether to use SSL when connecting. + * @param forceLongPolling - Whether to use the forceLongPolling option + * when using WebChannel as the network transport. + * @param autoDetectLongPolling - Whether to use the detectBufferingProxy + * option when using WebChannel as the network transport. + * @param longPollingOptions Options that configure long-polling. + * @param useFetchStreams Whether to use the Fetch API instead of + * XMLHTTPRequest + */ + constructor(databaseId: DatabaseId, appId: string, persistenceKey: string, host: string, ssl: boolean, forceLongPolling: boolean, autoDetectLongPolling: boolean, longPollingOptions: ExperimentalLongPollingOptions, useFetchStreams: boolean, isUsingEmulator: boolean); +} + +/** + * Datastore and its related methods are a wrapper around the external Google + * Cloud Datastore grpc API, which provides an interface that is more convenient + * for the rest of the client SDK architecture to consume. + */ +declare abstract class Datastore { + abstract terminate(): void; + abstract serializer: JsonProtoSerializer; +} + +/** + * Represents an operation scheduled to be run in the future on an AsyncQueue. + * + * It is created via DelayedOperation.createAndSchedule(). + * + * Supports cancellation (via cancel()) and early execution (via skipDelay()). + * + * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type + * in newer versions of TypeScript defines `finally`, which is not available in + * IE. + */ +declare class DelayedOperation implements PromiseLike { + private readonly asyncQueue; + readonly timerId: TimerId; + readonly targetTimeMs: number; + private readonly op; + private readonly removalCallback; + private timerHandle; + private readonly deferred; + private constructor(); + get promise(): Promise; + /** + * Creates and returns a DelayedOperation that has been scheduled to be + * executed on the provided asyncQueue after the provided delayMs. + * + * @param asyncQueue - The queue to schedule the operation on. + * @param id - A Timer ID identifying the type of operation this is. + * @param delayMs - The delay (ms) before the operation should be scheduled. + * @param op - The operation to run. + * @param removalCallback - A callback to be called synchronously once the + * operation is executed or canceled, notifying the AsyncQueue to remove it + * from its delayedOperations list. + * PORTING NOTE: This exists to prevent making removeDelayedOperation() and + * the DelayedOperation class public. + */ + static createAndSchedule(asyncQueue: AsyncQueue, timerId: TimerId, delayMs: number, op: () => Promise, removalCallback: (op: DelayedOperation) => void): DelayedOperation; + /** + * Starts the timer. This is called immediately after construction by + * createAndSchedule(). + */ + private start; + /** + * Queues the operation to run immediately (if it hasn't already been run or + * canceled). + */ + skipDelay(): void; + /** + * Cancels the operation if it hasn't already been executed or canceled. The + * promise will be rejected. + * + * As long as the operation has not yet been run, calling cancel() provides a + * guarantee that the operation will not be run. + */ + cancel(reason?: string): void; + then: (onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined) => Promise; + private handleDelayElapsed; + private clearTimeout; +} + +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * The deletion will only be reflected in document reads that occur after the + * returned promise resolves. If the client is offline, the + * delete fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to delete. + * @returns A `Promise` resolved once the document has been successfully + * deleted from the backend. + */ +export declare function deleteDoc(reference: DocumentReference): Promise; + +/** + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. + */ +export declare function deleteField(): FieldValue; + +/** + * The direction of sorting in an order by. + */ +declare const enum Direction { + ASCENDING = "asc", + DESCENDING = "desc" +} + +/** + * Gets a `DocumentReference` instance that refers to the document at the + * specified absolute path. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param path - A slash-separated path to a document. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(firestore: Firestore, path: string, ...pathSegments: string[]): DocumentReference; + +/** + * Gets a `DocumentReference` instance that refers to a document within + * `reference` at the specified relative path. If no path is specified, an + * automatically-generated unique ID will be used for the returned + * `DocumentReference`. + * + * @param reference - A reference to a collection. + * @param path - A slash-separated path to a document. Has to be omitted to use + * auto-generated IDs. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(reference: CollectionReference, path?: string, ...pathSegments: string[]): DocumentReference; + +/** + * Gets a `DocumentReference` instance that refers to a document within + * `reference` at the specified relative path. + * + * @param reference - A reference to a Firestore document. + * @param path - A slash-separated path to a document. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(reference: DocumentReference, path: string, ...pathSegments: string[]): DocumentReference; + +/** + * Represents a document in Firestore with a key, version, data and whether the + * data has local mutations applied to it. + */ +declare interface Document_2 { + /** The key for this document */ + readonly key: DocumentKey; + /** + * The version of this document if it exists or a version at which this + * document was guaranteed to not exist. + */ + readonly version: SnapshotVersion; + /** + * The timestamp at which this document was read from the remote server. Uses + * `SnapshotVersion.min()` for documents created by the user. + */ + readonly readTime: SnapshotVersion; + /** + * The timestamp at which the document was created. This value increases + * monotonically when a document is deleted then recreated. It can also be + * compared to `createTime` of other documents and the `readTime` of a query. + */ + readonly createTime: SnapshotVersion; + /** The underlying data of this document or an empty value if no data exists. */ + readonly data: ObjectValue; + /** Returns whether local mutations were applied via the mutation queue. */ + readonly hasLocalMutations: boolean; + /** Returns whether mutations were applied based on a write acknowledgment. */ + readonly hasCommittedMutations: boolean; + /** + * Whether this document had a local mutation applied that has not yet been + * acknowledged by Watch. + */ + readonly hasPendingWrites: boolean; + /** + * Returns whether this document is valid (i.e. it is an entry in the + * RemoteDocumentCache, was created by a mutation or read from the backend). + */ + isValidDocument(): boolean; + /** + * Returns whether the document exists and its data is known at the current + * version. + */ + isFoundDocument(): boolean; + /** + * Returns whether the document is known to not exist at the current version. + */ + isNoDocument(): boolean; + /** + * Returns whether the document exists and its data is unknown at the current + * version. + */ + isUnknownDocument(): boolean; + isEqual(other: Document_2 | null | undefined): boolean; + /** Creates a mutable copy of this document. */ + mutableCopy(): MutableDocument; + toString(): string; +} + +declare type DocumentComparator = (doc1: Document_2, doc2: Document_2) => number; + +/** + * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to + * values. + */ +export declare interface DocumentData { + /** A mapping between a field and its value. */ + [field: string]: any; +} + +/** + * Returns a special sentinel `FieldPath` to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ +export declare function documentId(): FieldPath; + +/** + * @internal + */ +declare class DocumentKey { + readonly path: ResourcePath; + constructor(path: ResourcePath); + static fromPath(path: string): DocumentKey; + static fromName(name: string): DocumentKey; + static empty(): DocumentKey; + get collectionGroup(): string; + /** Returns true if the document is in the specified collectionId. */ + hasCollectionId(collectionId: string): boolean; + /** Returns the collection group (i.e. the name of the parent collection) for this key. */ + getCollectionGroup(): string; + /** Returns the fully qualified path to the parent collection. */ + getCollectionPath(): ResourcePath; + isEqual(other: DocumentKey | null): boolean; + toString(): string; + static comparator(k1: DocumentKey, k2: DocumentKey): number; + static isDocumentKey(path: ResourcePath): boolean; + /** + * Creates and returns a new document key with the given segments. + * + * @param segments - The segments of the path to the document + * @returns A new instance of DocumentKey + */ + static fromSegments(segments: string[]): DocumentKey; +} + +declare type DocumentKeyMap = ObjectMap; + +declare type DocumentKeySet = SortedSet; + +declare type DocumentMap = SortedMap; + +/** + * Provides methods to read and write document overlays. + * + * An overlay is a saved mutation, that gives a local view of a document when + * applied to the remote version of the document. + * + * Each overlay stores the largest batch ID that is included in the overlay, + * which allows us to remove the overlay once all batches leading up to it have + * been acknowledged. + */ +declare interface DocumentOverlayCache { + /** + * Gets the saved overlay mutation for the given document key. + * Returns null if there is no overlay for that key. + */ + getOverlay(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; + /** + * Gets the saved overlay mutation for the given document keys. Skips keys for + * which there are no overlays. + */ + getOverlays(transaction: PersistenceTransaction, keys: DocumentKey[]): PersistencePromise; + /** + * Saves the given document mutation map to persistence as overlays. + * All overlays will have their largest batch id set to `largestBatchId`. + */ + saveOverlays(transaction: PersistenceTransaction, largestBatchId: number, overlays: MutationMap): PersistencePromise; + /** Removes overlays for the given document keys and batch ID. */ + removeOverlaysForBatchId(transaction: PersistenceTransaction, documentKeys: DocumentKeySet, batchId: number): PersistencePromise; + /** + * Returns all saved overlays for the given collection. + * + * @param transaction - The persistence transaction to use for this operation. + * @param collection - The collection path to get the overlays for. + * @param sinceBatchId - The minimum batch ID to filter by (exclusive). + * Only overlays that contain a change past `sinceBatchId` are returned. + * @returns Mapping of each document key in the collection to its overlay. + */ + getOverlaysForCollection(transaction: PersistenceTransaction, collection: ResourcePath, sinceBatchId: number): PersistencePromise; + /** + * Returns `count` overlays with a batch ID higher than `sinceBatchId` for the + * provided collection group, processed by ascending batch ID. The method + * always returns all overlays for a batch even if the last batch contains + * more documents than the remaining limit. + * + * @param transaction - The persistence transaction used for this operation. + * @param collectionGroup - The collection group to get the overlays for. + * @param sinceBatchId - The minimum batch ID to filter by (exclusive). + * Only overlays that contain a change past `sinceBatchId` are returned. + * @param count - The number of overlays to return. Can be exceeded if the last + * batch contains more entries. + * @return Mapping of each document key in the collection group to its overlay. + */ + getOverlaysForCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, sinceBatchId: number, count: number): PersistencePromise; +} + +/** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. + */ +export declare class DocumentReference { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter | null; + readonly _key: DocumentKey; + /** The type of this Firestore reference. */ + readonly type = "document"; + /** + * The {@link Firestore} instance the document is in. + * This is useful for performing transactions, for example. + */ + readonly firestore: Firestore; + /** @hideconstructor */ + constructor(firestore: Firestore, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter: FirestoreDataConverter | null, _key: DocumentKey); + get _path(): ResourcePath; + /** + * The document's identifier within its collection. + */ + get id(): string; + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ + get path(): string; + /** + * The collection this `DocumentReference` belongs to. + */ + get parent(): CollectionReference; + /** + * Applies a custom data converter to this `DocumentReference`, allowing you + * to use your own custom model objects with Firestore. When you call {@link + * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference` + * instance, the provided converter will convert between Firestore data of + * type `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `DocumentReference` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter): DocumentReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `DocumentReference` that does not + * use a converter. + */ + withConverter(converter: null): DocumentReference; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + referencePath: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `DocumentReference` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `DocumentReference` instance from a JSON object created by + * {@link DocumentReference.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json a JSON object represention of a `DocumentReference` instance + * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(firestore: Firestore, json: object): DocumentReference; + /** + * Builds a `DocumentReference` instance from a JSON object created by + * {@link DocumentReference.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json a JSON object represention of a `DocumentReference` instance + * @param converter - Converts objects to and from Firestore. + * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(firestore: Firestore, json: object, converter: FirestoreDataConverter): DocumentReference; +} + +/** + * DocumentSet is an immutable (copy-on-write) collection that holds documents + * in order specified by the provided comparator. We always add a document key + * comparator on top of what is provided to guarantee document equality based on + * the key. + */ +declare class DocumentSet { + /** + * Returns an empty copy of the existing DocumentSet, using the same + * comparator. + */ + static emptySet(oldSet: DocumentSet): DocumentSet; + private comparator; + private keyedMap; + private sortedSet; + /** The default ordering is by key if the comparator is omitted */ + constructor(comp?: DocumentComparator); + has(key: DocumentKey): boolean; + get(key: DocumentKey): Document_2 | null; + first(): Document_2 | null; + last(): Document_2 | null; + isEmpty(): boolean; + /** + * Returns the index of the provided key in the document set, or -1 if the + * document key is not present in the set; + */ + indexOf(key: DocumentKey): number; + get size(): number; + /** Iterates documents in order defined by "comparator" */ + forEach(cb: (doc: Document_2) => void): void; + /** Inserts or updates a document with the same key */ + add(doc: Document_2): DocumentSet; + /** Deletes a document with a given key */ + delete(key: DocumentKey): DocumentSet; + isEqual(other: DocumentSet | null | undefined): boolean; + toString(): string; + private copy; +} + +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ +export declare class DocumentSnapshot { + _firestore: Firestore; + _userDataWriter: AbstractUserDataWriter; + _key: DocumentKey; + _document: Document_2 | null; + _converter: UntypedFirestoreDataConverter | null; + /** @hideconstructor protected */ + constructor(_firestore: Firestore, _userDataWriter: AbstractUserDataWriter, _key: DocumentKey, _document: Document_2 | null, _converter: UntypedFirestoreDataConverter | null); + /** Property of the `DocumentSnapshot` that provides the document's ID. */ + get id(): string; + /** + * The `DocumentReference` for the document included in the `DocumentSnapshot`. + */ + get ref(): DocumentReference; + /** + * Signals whether or not the document at the snapshot's location exists. + * + * @returns true if the document exists. + */ + exists(): this is QueryDocumentSnapshot; + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * @returns An `Object` containing all fields in the document or `undefined` + * if the document doesn't exist. + */ + data(): AppModelType | undefined; + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + get(fieldPath: string | FieldPath): any; +} + +declare type DocumentVersionMap = SortedMap; + +declare interface DocumentViewChange { + type: ChangeType; + doc: Document_2; +} +export { EmulatorMockTokenOptions } + +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided document (inclusive). The end position is relative to the order + * of the query. The document must contain all of the fields provided in the + * orderBy of the query. + * + * @param snapshot - The snapshot of the document to end at. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endAt(snapshot: DocumentSnapshot): QueryEndAtConstraint; + +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided fields relative to the order of the query. The order of the field + * values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to end this query at, in order + * of the query's order by. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endAt(...fieldValues: unknown[]): QueryEndAtConstraint; + +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided document (exclusive). The end position is relative to the + * order of the query. The document must contain all of the fields provided in + * the orderBy of the query. + * + * @param snapshot - The snapshot of the document to end before. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endBefore(snapshot: DocumentSnapshot): QueryEndAtConstraint; + +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to end this query before, in order + * of the query's order by. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endBefore(...fieldValues: unknown[]): QueryEndAtConstraint; + +declare interface Entry { + key: K; + value: V; +} + +/** + * EventManager is responsible for mapping queries to query event emitters. + * It handles "fan-out". -- Identical queries will re-use the same watch on the + * backend. + * + * PORTING NOTE: On Web, EventManager `onListen` and `onUnlisten` need to be + * assigned to SyncEngine's `listen()` and `unlisten()` API before usage. This + * allows users to tree-shake the Watch logic. + */ +declare interface EventManager { + onListen?: (query: Query_2, enableRemoteListen: boolean) => Promise; + onUnlisten?: (query: Query_2, disableRemoteListen: boolean) => Promise; + onFirstRemoteStoreListen?: (query: Query_2) => Promise; + onLastRemoteStoreUnlisten?: (query: Query_2) => Promise; + terminate(): void; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options that configure the SDK’s underlying network transport (WebChannel) + * when long-polling is used. + * + * Note: This interface is "experimental" and is subject to change. + * + * See `FirestoreSettings.experimentalAutoDetectLongPolling`, + * `FirestoreSettings.experimentalForceLongPolling`, and + * `FirestoreSettings.experimentalLongPollingOptions`. + */ +declare interface ExperimentalLongPollingOptions { + /** + * The desired maximum timeout interval, in seconds, to complete a + * long-polling GET response. Valid values are between 5 and 30, inclusive. + * Floating point values are allowed and will be rounded to the nearest + * millisecond. + * + * By default, when long-polling is used the "hanging GET" request sent by + * the client times out after 30 seconds. To request a different timeout + * from the server, set this setting with the desired timeout. + * + * Changing the default timeout may be useful, for example, if the buffering + * proxy that necessitated enabling long-polling in the first place has a + * shorter timeout for hanging GET requests, in which case setting the + * long-polling timeout to a shorter value, such as 25 seconds, may fix + * prematurely-closed hanging GET requests. + * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987. + */ + timeoutSeconds?: number; +} + +declare class FieldFilter extends Filter { + readonly field: FieldPath_2; + readonly op: Operator; + readonly value: Value; + protected constructor(field: FieldPath_2, op: Operator, value: Value); + /** + * Creates a filter based on the provided arguments. + */ + static create(field: FieldPath_2, op: Operator, value: Value): FieldFilter; + private static createKeyFieldInFilter; + matches(doc: Document_2): boolean; + protected matchesComparison(comparison: number): boolean; + isInequality(): boolean; + getFlattenedFilters(): readonly FieldFilter[]; + getFilters(): Filter[]; +} + +declare type FieldFilterOp = 'OPERATOR_UNSPECIFIED' | 'LESS_THAN' | 'LESS_THAN_OR_EQUAL' | 'GREATER_THAN' | 'GREATER_THAN_OR_EQUAL' | 'EQUAL' | 'NOT_EQUAL' | 'ARRAY_CONTAINS' | 'IN' | 'ARRAY_CONTAINS_ANY' | 'NOT_IN'; + +/** + * An index definition for field indexes in Firestore. + * + * Every index is associated with a collection. The definition contains a list + * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or + * `CONTAINS` for ArrayContains/ArrayContainsAny queries). + * + * Unlike the backend, the SDK does not differentiate between collection or + * collection group-scoped indices. Every index can be used for both single + * collection and collection group queries. + */ +declare class FieldIndex { + /** + * The index ID. Returns -1 if the index ID is not available (e.g. the index + * has not yet been persisted). + */ + readonly indexId: number; + /** The collection ID this index applies to. */ + readonly collectionGroup: string; + /** The field segments for this index. */ + readonly fields: IndexSegment[]; + /** Shows how up-to-date the index is for the current user. */ + readonly indexState: IndexState; + /** An ID for an index that has not yet been added to persistence. */ + static UNKNOWN_ID: number; + constructor( + /** + * The index ID. Returns -1 if the index ID is not available (e.g. the index + * has not yet been persisted). + */ + indexId: number, + /** The collection ID this index applies to. */ + collectionGroup: string, + /** The field segments for this index. */ + fields: IndexSegment[], + /** Shows how up-to-date the index is for the current user. */ + indexState: IndexState); +} + +/** + * Provides a set of fields that can be used to partially patch a document. + * FieldMask is used in conjunction with ObjectValue. + * Examples: + * foo - Overwrites foo entirely with the provided value. If foo is not + * present in the companion ObjectValue, the field is deleted. + * foo.bar - Overwrites only the field bar of the object foo. + * If foo is not an object, foo is replaced with an object + * containing foo + */ +declare class FieldMask { + readonly fields: FieldPath_2[]; + constructor(fields: FieldPath_2[]); + static empty(): FieldMask; + /** + * Returns a new FieldMask object that is the result of adding all the given + * fields paths to this field mask. + */ + unionWith(extraFields: FieldPath_2[]): FieldMask; + /** + * Verifies that `fieldPath` is included by at least one field in this field + * mask. + * + * This is an O(n) operation, where `n` is the size of the field mask. + */ + covers(fieldPath: FieldPath_2): boolean; + isEqual(other: FieldMask): boolean; +} + +/** + * A `FieldPath` refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + * + * Create a `FieldPath` by providing field names. If more than one field + * name is provided, the path will point to a nested field in a document. + */ +export declare class FieldPath { + /** Internal representation of a Firestore field path. */ + readonly _internalPath: FieldPath_2; + /** + * Creates a `FieldPath` from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames - A list of field names. + */ + constructor(...fieldNames: string[]); + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other - The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ + isEqual(other: FieldPath): boolean; +} + +/** + * A dot-separated path for navigating sub-objects within a document. + * @internal + */ +declare class FieldPath_2 extends BasePath { + protected construct(segments: string[], offset?: number, length?: number): FieldPath_2; + /** + * Returns true if the string could be used as a segment in a field path + * without escaping. + */ + private static isValidIdentifier; + canonicalString(): string; + toString(): string; + /** + * Returns true if this field references the key of a document. + */ + isKeyField(): boolean; + /** + * The field designating the key of a document. + */ + static keyField(): FieldPath_2; + /** + * Parses a field string from the given server-formatted string. + * + * - Splitting the empty string is not allowed (for now at least). + * - Empty segments within the string (e.g. if there are two consecutive + * separators) are not allowed. + * + * TODO(b/37244157): we should make this more strict. Right now, it allows + * non-identifier path components, even if they aren't escaped. + */ + static fromServerFormat(path: string): FieldPath_2; + static emptyPath(): FieldPath_2; +} + +/** A field path and the TransformOperation to perform upon it. */ +declare class FieldTransform { + readonly field: FieldPath_2; + readonly transform: TransformOperation; + constructor(field: FieldPath_2, transform: TransformOperation); +} + +declare type FieldTransformSetToServerValue = 'SERVER_VALUE_UNSPECIFIED' | 'REQUEST_TIME'; + +/** + * Sentinel values that can be used when writing document fields with `set()` + * or `update()`. + */ +export declare abstract class FieldValue { + _methodName: string; + /** + * @param _methodName - The public API endpoint that returns this class. + * @hideconstructor + */ + constructor(_methodName: string); + /** Compares `FieldValue`s for equality. */ + abstract isEqual(other: FieldValue): boolean; + abstract _toFieldTransform(context: ParseContext): FieldTransform | null; +} + +declare abstract class Filter { + abstract matches(doc: Document_2): boolean; + abstract getFlattenedFilters(): readonly FieldFilter[]; + abstract getFilters(): Filter[]; +} + +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ +export declare class Firestore implements FirestoreService { + _authCredentials: CredentialsProvider; + _appCheckCredentials: CredentialsProvider; + readonly _databaseId: DatabaseId; + readonly _app?: FirebaseApp | undefined; + /** + * Whether it's a Firestore or Firestore Lite instance. + */ + type: 'firestore-lite' | 'firestore'; + readonly _persistenceKey: string; + private _settings; + private _settingsFrozen; + private _emulatorOptions; + private _terminateTask; + /** @hideconstructor */ + constructor(_authCredentials: CredentialsProvider, _appCheckCredentials: CredentialsProvider, _databaseId: DatabaseId, _app?: FirebaseApp | undefined); + /** + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service + * instance. + */ + get app(): FirebaseApp; + get _initialized(): boolean; + get _terminated(): boolean; + _setSettings(settings: PrivateSettings): void; + _getSettings(): FirestoreSettingsImpl; + _getEmulatorOptions(): { + mockUserToken?: EmulatorMockTokenOptions | string; + }; + _freezeSettings(): FirestoreSettingsImpl; + _delete(): Promise; + _restart(): Promise; + /** Returns a JSON-serializable representation of this `Firestore` instance. */ + toJSON(): object; + /** + * Terminates all components used by this client. Subclasses can override + * this method to clean up their own dependencies, but must also call this + * method. + * + * Only ever called once. + */ + protected _terminate(): Promise; +} + +/** + * Converter used by `withConverter()` to transform user objects of type + * `AppModelType` into Firestore data of type `DbModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * In this context, an "AppModel" is a class that is used in an application to + * package together related information and functionality. Such a class could, + * for example, have properties with complex, nested data types, properties used + * for memoization, properties of types not supported by Firestore (such as + * `symbol` and `bigint`), and helper functions that perform compound + * operations. Such classes are not suitable and/or possible to store into a + * Firestore database. Instead, instances of such classes need to be converted + * to "plain old JavaScript objects" (POJOs) with exclusively primitive + * properties, potentially nested inside other POJOs or arrays of POJOs. In this + * context, this type is referred to as the "DbModel" and would be an object + * suitable for persisting into Firestore. For convenience, applications can + * implement `FirestoreDataConverter` and register the converter with Firestore + * objects, such as `DocumentReference` or `Query`, to automatically convert + * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel` + * to `AppModel` when retrieving from Firestore. + * + * @example + * + * Simple Example + * + * ```typescript + * const numberConverter = { + * toFirestore(value: WithFieldValue) { + * return { value }; + * }, + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) { + * return snapshot.data(options).value as number; + * } + * }; + * + * async function simpleDemo(db: Firestore): Promise { + * const documentRef = doc(db, 'values/value123').withConverter(numberConverter); + * + * // converters are used with `setDoc`, `addDoc`, and `getDoc` + * await setDoc(documentRef, 42); + * const snapshot1 = await getDoc(documentRef); + * assertEqual(snapshot1.data(), 42); + * + * // converters are not used when writing data with `updateDoc` + * await updateDoc(documentRef, { value: 999 }); + * const snapshot2 = await getDoc(documentRef); + * assertEqual(snapshot2.data(), 999); + * } + * ``` + * + * Advanced Example + * + * ```typescript + * // The Post class is a model that is used by our application. + * // This class may have properties and methods that are specific + * // to our application execution, which do not need to be persisted + * // to Firestore. + * class Post { + * constructor( + * readonly title: string, + * readonly author: string, + * readonly lastUpdatedMillis: number + * ) {} + * toString(): string { + * return `${this.title} by ${this.author}`; + * } + * } + * + * // The PostDbModel represents how we want our posts to be stored + * // in Firestore. This DbModel has different properties (`ttl`, + * // `aut`, and `lut`) from the Post class we use in our application. + * interface PostDbModel { + * ttl: string; + * aut: { firstName: string; lastName: string }; + * lut: Timestamp; + * } + * + * // The `PostConverter` implements `FirestoreDataConverter` and specifies + * // how the Firestore SDK can convert `Post` objects to `PostDbModel` + * // objects and vice versa. + * class PostConverter implements FirestoreDataConverter { + * toFirestore(post: WithFieldValue): WithFieldValue { + * return { + * ttl: post.title, + * aut: this._autFromAuthor(post.author), + * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis) + * }; + * } + * + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post { + * const data = snapshot.data(options) as PostDbModel; + * const author = `${data.aut.firstName} ${data.aut.lastName}`; + * return new Post(data.ttl, author, data.lut.toMillis()); + * } + * + * _autFromAuthor( + * author: string | FieldValue + * ): { firstName: string; lastName: string } | FieldValue { + * if (typeof author !== 'string') { + * // `author` is a FieldValue, so just return it. + * return author; + * } + * const [firstName, lastName] = author.split(' '); + * return {firstName, lastName}; + * } + * + * _lutFromLastUpdatedMillis( + * lastUpdatedMillis: number | FieldValue + * ): Timestamp | FieldValue { + * if (typeof lastUpdatedMillis !== 'number') { + * // `lastUpdatedMillis` must be a FieldValue, so just return it. + * return lastUpdatedMillis; + * } + * return Timestamp.fromMillis(lastUpdatedMillis); + * } + * } + * + * async function advancedDemo(db: Firestore): Promise { + * // Create a `DocumentReference` with a `FirestoreDataConverter`. + * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter()); + * + * // The `data` argument specified to `setDoc()` is type checked by the + * // TypeScript compiler to be compatible with `Post`. Since the `data` + * // argument is typed as `WithFieldValue` rather than just `Post`, + * // this allows properties of the `data` argument to also be special + * // Firestore values that perform server-side mutations, such as + * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`. + * await setDoc(documentRef, { + * title: 'My Life', + * author: 'Foo Bar', + * lastUpdatedMillis: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `setDoc()` is _not_ compatible with `WithFieldValue`. This + * // type checking prevents the caller from specifying objects with incorrect + * // properties or property values. + * // @ts-expect-error "Argument of type { ttl: string; } is not assignable + * // to parameter of type WithFieldValue" + * await setDoc(documentRef, { ttl: 'The Title' }); + * + * // When retrieving a document with `getDoc()` the `DocumentSnapshot` + * // object's `data()` method returns a `Post`, rather than a generic object, + * // which would have been returned if the `DocumentReference` did _not_ have a + * // `FirestoreDataConverter` attached to it. + * const snapshot1: DocumentSnapshot = await getDoc(documentRef); + * const post1: Post = snapshot1.data()!; + * if (post1) { + * assertEqual(post1.title, 'My Life'); + * assertEqual(post1.author, 'Foo Bar'); + * } + * + * // The `data` argument specified to `updateDoc()` is type checked by the + * // TypeScript compiler to be compatible with `PostDbModel`. Note that + * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`, + * // the `data` argument to `updateDoc()` must be compatible with + * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed + * // as `WithFieldValue` rather than just `PostDbModel`, this + * // allows properties of the `data` argument to also be those special + * // Firestore values, like `arrayRemove()`, `deleteField()`, and + * // `serverTimestamp()`. + * await updateDoc(documentRef, { + * 'aut.firstName': 'NewFirstName', + * lut: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `updateDoc()` is _not_ compatible with `WithFieldValue`. + * // This type checking prevents the caller from specifying objects with + * // incorrect properties or property values. + * // @ts-expect-error "Argument of type { title: string; } is not assignable + * // to parameter of type WithFieldValue" + * await updateDoc(documentRef, { title: 'New Title' }); + * const snapshot2: DocumentSnapshot = await getDoc(documentRef); + * const post2: Post = snapshot2.data()!; + * if (post2) { + * assertEqual(post2.title, 'My Life'); + * assertEqual(post2.author, 'NewFirstName Bar'); + * } + * } + * ``` + */ +export declare interface FirestoreDataConverter { + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link @firebase/firestore/lite#(setDoc:1)}, + * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and + * {@link @firebase/firestore/lite#(Transaction.set:1)}. + * + * The `WithFieldValue` type extends `T` to also allow FieldValues such as + * {@link (deleteField:1)} to be used as property values. + */ + toFirestore(modelObject: WithFieldValue): WithFieldValue; + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link @firebase/firestore/lite#(setDoc:1)}, + * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and + * {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true` + * or `mergeFields`. + * + * The `PartialWithFieldValue` type extends `Partial` to allow + * FieldValues such as {@link (arrayUnion:1)} to be used as property values. + * It also supports nested `Partial` by allowing nested fields to be + * omitted. + */ + toFirestore(modelObject: PartialWithFieldValue, options: SetOptions): PartialWithFieldValue; + /** + * Called by the Firestore SDK to convert Firestore data into an object of + * type `AppModelType`. You can access your data by calling: + * `snapshot.data()`. + * + * + * Generally, the data returned from `snapshot.data()` can be cast to + * `DbModelType`; however, this is not guaranteed because Firestore does not + * enforce a schema on the database. For example, writes from a previous + * version of the application or writes from another client that did not use a + * type converter could have written data with different properties and/or + * property types. The implementation will need to choose whether to + * gracefully recover from non-conforming data or throw an error. + * + * @param snapshot - A `QueryDocumentSnapshot` containing your data and + * metadata. + */ + fromFirestore(snapshot: QueryDocumentSnapshot): AppModelType; +} + +/** An error returned by a Firestore operation. */ +export declare class FirestoreError extends FirebaseError { + /** + * The backend error code associated with this error. + */ + readonly code: FirestoreErrorCode; + /** + * A custom error description. + */ + readonly message: string; + /** The stack of the error. */ + readonly stack?: string; + /** @hideconstructor */ + constructor( + /** + * The backend error code associated with this error. + */ + code: FirestoreErrorCode, + /** + * A custom error description. + */ + message: string); +} + +/** + * The set of Firestore status codes. The codes are the same at the ones + * exposed by gRPC here: + * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md + * + * Possible values: + * - 'cancelled': The operation was cancelled (typically by the caller). + * - 'unknown': Unknown error or an error from a different error domain. + * - 'invalid-argument': Client specified an invalid argument. Note that this + * differs from 'failed-precondition'. 'invalid-argument' indicates + * arguments that are problematic regardless of the state of the system + * (e.g. an invalid field name). + * - 'deadline-exceeded': Deadline expired before operation could complete. + * For operations that change the state of the system, this error may be + * returned even if the operation has completed successfully. For example, + * a successful response from a server could have been delayed long enough + * for the deadline to expire. + * - 'not-found': Some requested document was not found. + * - 'already-exists': Some document that we attempted to create already + * exists. + * - 'permission-denied': The caller does not have permission to execute the + * specified operation. + * - 'resource-exhausted': Some resource has been exhausted, perhaps a + * per-user quota, or perhaps the entire file system is out of space. + * - 'failed-precondition': Operation was rejected because the system is not + * in a state required for the operation's execution. + * - 'aborted': The operation was aborted, typically due to a concurrency + * issue like transaction aborts, etc. + * - 'out-of-range': Operation was attempted past the valid range. + * - 'unimplemented': Operation is not implemented or not supported/enabled. + * - 'internal': Internal errors. Means some invariants expected by + * underlying system has been broken. If you see one of these errors, + * something is very broken. + * - 'unavailable': The service is currently unavailable. This is most likely + * a transient condition and may be corrected by retrying with a backoff. + * - 'data-loss': Unrecoverable data loss or corruption. + * - 'unauthenticated': The request does not have valid authentication + * credentials for the operation. + */ +export declare type FirestoreErrorCode = 'cancelled' | 'unknown' | 'invalid-argument' | 'deadline-exceeded' | 'not-found' | 'already-exists' | 'permission-denied' | 'resource-exhausted' | 'failed-precondition' | 'aborted' | 'out-of-range' | 'unimplemented' | 'internal' | 'unavailable' | 'data-loss' | 'unauthenticated'; + +/** + * Union type from all supported SDK cache layer. + */ +declare type FirestoreLocalCache = MemoryLocalCache | PersistentLocalCache; + +/** + * An interface implemented by FirebaseFirestore that provides compatibility + * with the usage in this file. + * + * This interface mainly exists to remove a cyclic dependency. + */ +declare interface FirestoreService extends _FirebaseService { + _authCredentials: CredentialsProvider; + _appCheckCredentials: CredentialsProvider; + _persistenceKey: string; + _databaseId: DatabaseId; + _terminated: boolean; + _freezeSettings(): FirestoreSettingsImpl; +} + +/** + * A concrete type describing all the values that can be applied via a + * user-supplied `FirestoreSettings` object. This is a separate type so that + * defaults can be supplied and the value can be checked for equality. + */ +declare class FirestoreSettingsImpl { + /** The hostname to connect to. */ + readonly host: string; + /** Whether to use SSL when connecting. */ + readonly ssl: boolean; + readonly cacheSizeBytes: number; + readonly experimentalForceLongPolling: boolean; + readonly experimentalAutoDetectLongPolling: boolean; + readonly experimentalLongPollingOptions: ExperimentalLongPollingOptions; + readonly ignoreUndefinedProperties: boolean; + readonly useFetchStreams: boolean; + readonly localCache?: FirestoreLocalCache; + readonly isUsingEmulator: boolean; + credentials?: any; + constructor(settings: PrivateSettings); + isEqual(other: FirestoreSettingsImpl): boolean; +} + +declare namespace firestoreV1ApiClientInterfaces { + interface ArrayValue { + values?: Value[]; + } + interface BatchGetDocumentsRequest { + database?: string; + documents?: string[]; + mask?: DocumentMask; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface BatchGetDocumentsResponse { + found?: Document; + missing?: string; + transaction?: string; + readTime?: string; + } + interface BeginTransactionRequest { + options?: TransactionOptions; + } + interface BeginTransactionResponse { + transaction?: string; + } + interface CollectionSelector { + collectionId?: string; + allDescendants?: boolean; + } + interface CommitRequest { + database?: string; + writes?: Write[]; + transaction?: string; + } + interface CommitResponse { + writeResults?: WriteResult[]; + commitTime?: string; + } + interface CompositeFilter { + op?: CompositeFilterOp; + filters?: Filter[]; + } + interface Cursor { + values?: Value[]; + before?: boolean; + } + interface Document { + name?: string; + fields?: ApiClientObjectMap; + createTime?: Timestamp_2; + updateTime?: Timestamp_2; + } + interface DocumentChange { + document?: Document; + targetIds?: number[]; + removedTargetIds?: number[]; + } + interface DocumentDelete { + document?: string; + removedTargetIds?: number[]; + readTime?: Timestamp_2; + } + interface DocumentMask { + fieldPaths?: string[]; + } + interface DocumentRemove { + document?: string; + removedTargetIds?: number[]; + readTime?: string; + } + interface DocumentTransform { + document?: string; + fieldTransforms?: FieldTransform[]; + } + interface DocumentsTarget { + documents?: string[]; + } + interface Empty { + } + interface ExistenceFilter { + targetId?: number; + count?: number; + unchangedNames?: BloomFilter; + } + interface BloomFilter { + bits?: BitSequence; + hashCount?: number; + } + interface BitSequence { + bitmap?: string | Uint8Array; + padding?: number; + } + interface FieldFilter { + field?: FieldReference; + op?: FieldFilterOp; + value?: Value; + } + interface FieldReference { + fieldPath?: string; + } + interface FieldTransform { + fieldPath?: string; + setToServerValue?: FieldTransformSetToServerValue; + appendMissingElements?: ArrayValue; + removeAllFromArray?: ArrayValue; + increment?: Value; + } + interface Filter { + compositeFilter?: CompositeFilter; + fieldFilter?: FieldFilter; + unaryFilter?: UnaryFilter; + } + interface Index { + name?: string; + collectionId?: string; + fields?: IndexField[]; + state?: IndexState_2; + } + interface IndexField { + fieldPath?: string; + mode?: IndexFieldMode; + } + interface LatLng { + latitude?: number; + longitude?: number; + } + interface ListCollectionIdsRequest { + pageSize?: number; + pageToken?: string; + } + interface ListCollectionIdsResponse { + collectionIds?: string[]; + nextPageToken?: string; + } + interface ListDocumentsResponse { + documents?: Document[]; + nextPageToken?: string; + } + interface ListIndexesResponse { + indexes?: Index[]; + nextPageToken?: string; + } + interface ListenRequest { + addTarget?: Target; + removeTarget?: number; + labels?: ApiClientObjectMap; + } + interface ListenResponse { + targetChange?: TargetChange; + documentChange?: DocumentChange; + documentDelete?: DocumentDelete; + documentRemove?: DocumentRemove; + filter?: ExistenceFilter; + } + interface MapValue { + fields?: ApiClientObjectMap; + } + interface Operation { + name?: string; + metadata?: ApiClientObjectMap; + done?: boolean; + error?: Status; + response?: ApiClientObjectMap; + } + interface Order { + field?: FieldReference; + direction?: OrderDirection; + } + interface Precondition { + exists?: boolean; + updateTime?: Timestamp_2; + } + interface Projection { + fields?: FieldReference[]; + } + interface QueryTarget { + parent?: string; + structuredQuery?: StructuredQuery; + } + interface ReadOnly { + readTime?: string; + } + interface ReadWrite { + retryTransaction?: string; + } + interface RollbackRequest { + transaction?: string; + } + interface RunQueryRequest { + parent?: string; + structuredQuery?: StructuredQuery; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface RunQueryResponse { + transaction?: string; + document?: Document; + readTime?: string; + skippedResults?: number; + } + interface RunAggregationQueryRequest { + parent?: string; + structuredAggregationQuery?: StructuredAggregationQuery; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface RunAggregationQueryResponse { + result?: AggregationResult; + transaction?: string; + readTime?: string; + } + interface AggregationResult { + aggregateFields?: ApiClientObjectMap; + } + interface StructuredAggregationQuery { + structuredQuery?: StructuredQuery; + aggregations?: Aggregation[]; + } + interface Aggregation { + count?: Count; + sum?: Sum; + avg?: Avg; + alias?: string; + } + interface Count { + upTo?: number; + } + interface Sum { + field?: FieldReference; + } + interface Avg { + field?: FieldReference; + } + interface Status { + code?: number; + message?: string; + details?: Array>; + } + interface StructuredQuery { + select?: Projection; + from?: CollectionSelector[]; + where?: Filter; + orderBy?: Order[]; + startAt?: Cursor; + endAt?: Cursor; + offset?: number; + limit?: number | { + value: number; + }; + } + interface Target { + query?: QueryTarget; + documents?: DocumentsTarget; + resumeToken?: string | Uint8Array; + readTime?: Timestamp_2; + targetId?: number; + once?: boolean; + expectedCount?: number | { + value: number; + }; + } + interface TargetChange { + targetChangeType?: TargetChangeTargetChangeType; + targetIds?: number[]; + cause?: Status; + resumeToken?: string | Uint8Array; + readTime?: Timestamp_2; + } + interface TransactionOptions { + readOnly?: ReadOnly; + readWrite?: ReadWrite; + } + interface UnaryFilter { + op?: UnaryFilterOp; + field?: FieldReference; + } + interface Value { + nullValue?: ValueNullValue; + booleanValue?: boolean; + integerValue?: string | number; + doubleValue?: string | number; + timestampValue?: Timestamp_2; + stringValue?: string; + bytesValue?: string | Uint8Array; + referenceValue?: string; + geoPointValue?: LatLng; + arrayValue?: ArrayValue; + mapValue?: MapValue; + } + interface Write { + update?: Document; + delete?: string; + verify?: string; + transform?: DocumentTransform; + updateMask?: DocumentMask; + updateTransforms?: FieldTransform[]; + currentDocument?: Precondition; + } + interface WriteRequest { + streamId?: string; + writes?: Write[]; + streamToken?: string | Uint8Array; + labels?: ApiClientObjectMap; + } + interface WriteResponse { + streamId?: string; + streamToken?: string | Uint8Array; + writeResults?: WriteResult[]; + commitTime?: Timestamp_2; + } + interface WriteResult { + updateTime?: Timestamp_2; + transformResults?: Value[]; + } +} + +/** + * @internal + */ +declare interface FirstPartyCredentialsSettings { + ['type']: 'firstParty'; + ['sessionIndex']: string; + ['iamToken']: string | null; + ['authTokenFactory']: AuthTokenFactory | null; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +declare type FulfilledHandler = ((result: T) => R | PersistencePromise) | null; + +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ +export declare class GeoPoint { + private _lat; + private _long; + /** + * Creates a new immutable `GeoPoint` object with the provided latitude and + * longitude values. + * @param latitude - The latitude as number between -90 and 90. + * @param longitude - The longitude as number between -180 and 180. + */ + constructor(latitude: number, longitude: number); + /** + * The latitude of this `GeoPoint` instance. + */ + get latitude(): number; + /** + * The longitude of this `GeoPoint` instance. + */ + get longitude(): number; + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other - The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ + isEqual(other: GeoPoint): boolean; + /** + * Actually private to JS consumers of our API, so this function is prefixed + * with an underscore. + */ + _compareTo(other: GeoPoint): number; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + latitude: Property<"number">; + longitude: Property<"number">; + }; + /** + * Returns a JSON-serializable representation of this `GeoPoint` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): { + latitude: number; + longitude: number; + type: string; + }; + /** + * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}. + * + * @param json a JSON object represention of a `GeoPoint` instance + * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): GeoPoint; +} + +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregate(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ +export declare function getAggregate(query: Query, aggregateSpec: AggregateSpecType): Promise>; + +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ +export declare function getCount(query: Query): Promise; +}, AppModelType, DbModelType>>; + +/** + * Reads the document referred to by the specified document reference. + * + * All documents are directly fetched from the server, even if the document was + * previously read or modified. Recent modifications are only reflected in the + * retrieved `DocumentSnapshot` if they have already been applied by the + * backend. If the client is offline, the read fails. If you like to use + * caching or see local modifications, please use the full Firestore SDK. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the current + * document contents. + */ +export declare function getDoc(reference: DocumentReference): Promise>; + +/** + * Executes the query and returns the results as a {@link QuerySnapshot}. + * + * All queries are executed directly by the server, even if the query was + * previously executed. Recent modifications are only reflected in the retrieved + * results if they have already been applied by the backend. If the client is + * offline, the operation fails. To see previously cached result and local + * modifications, use the full Firestore SDK. + * + * @param query - The `Query` to execute. + * @returns A Promise that will be resolved with the results of the query. + */ +export declare function getDocs(query: Query): Promise>; + +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @returns The {@link Firestore} instance of the provided app. + */ +export declare function getFirestore(): Firestore; + +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @returns The {@link Firestore} instance of the provided app. + */ +export declare function getFirestore(app: FirebaseApp): Firestore; + +/** + * Returns the existing {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param databaseId - The name of the database. + * @returns The {@link Firestore} instance of the provided app. + * @beta + */ +export declare function getFirestore(databaseId: string): Firestore; + +/** + * Returns the existing {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @param databaseId - The name of the database. + * @returns The {@link Firestore} instance of the provided app. + * @beta + */ +export declare function getFirestore(app: FirebaseApp, databaseId: string): Firestore; + +/** + * General purpose cache for global values. + * + * Global state that cuts across components should be saved here. Following are contained herein: + * + * `sessionToken` tracks server interaction across Listen and Write streams. This facilitates cache + * synchronization and invalidation. + */ +declare interface GlobalsCache { + /** + * Gets session token. + */ + getSessionToken(transaction: PersistenceTransaction): PersistencePromise; + /** + * Sets session token. + * + * @param sessionToken - The new session token. + */ + setSessionToken(transaction: PersistenceTransaction, sessionToken: ByteString): PersistencePromise; +} + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by + * the given value. + * + * If either the operand or the current field value uses floating point + * precision, all arithmetic follows IEEE 754 semantics. If both values are + * integers, values outside of JavaScript's safe number range + * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to + * precision loss. Furthermore, once processed by the Firestore backend, all + * integer operations are capped between -2^63 and 2^63-1. + * + * If the current field value is not of type `number`, or if the field does not + * yet exist, the transformation sets the field to the given value. + * + * @param n - The value to increment by. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +export declare function increment(n: number): FieldValue; + +declare type IndexFieldMode = 'MODE_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING'; + +/** The type of the index, e.g. for which type of query it can be used. */ +declare const enum IndexKind { + /** + * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries. + */ + ASCENDING = 0, + /** + * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries. + */ + DESCENDING = 1, + /** Contains index. Can be used for ArrayContains and ArrayContainsAny. */ + CONTAINS = 2 +} + +/** + * Represents a set of indexes that are used to execute queries efficiently. + * + * Currently the only index is a [collection id] => [parent path] index, used + * to execute Collection Group queries. + */ +declare interface IndexManager { + /** + * Creates an index entry mapping the collectionId (last segment of the path) + * to the parent path (either the containing document location or the empty + * path for root-level collections). Index entries can be retrieved via + * getCollectionParents(). + * + * NOTE: Currently we don't remove index entries. If this ends up being an + * issue we can devise some sort of GC strategy. + */ + addToCollectionParentIndex(transaction: PersistenceTransaction, collectionPath: ResourcePath): PersistencePromise; + /** + * Retrieves all parent locations containing the given collectionId, as a + * list of paths (each path being either a document location or the empty + * path for a root-level collection). + */ + getCollectionParents(transaction: PersistenceTransaction, collectionId: string): PersistencePromise; + /** + * Adds a field path index. + * + * Values for this index are persisted via the index backfill, which runs + * asynchronously in the background. Once the first values are written, + * an index can be used to serve partial results for any matching queries. + * Any unindexed portion of the database will continue to be served via + * collection scons. + */ + addFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + /** Removes the given field index and deletes all index values. */ + deleteFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + /** Removes all field indexes and deletes all index values. */ + deleteAllFieldIndexes(transaction: PersistenceTransaction): PersistencePromise; + /** Creates a full matched field index which serves the given target. */ + createTargetIndexes(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Returns a list of field indexes that correspond to the specified collection + * group. + * + * @param collectionGroup The collection group to get matching field indexes + * for. + * @return A collection of field indexes for the specified collection group. + */ + getFieldIndexes(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise; + /** Returns all configured field indexes. */ + getFieldIndexes(transaction: PersistenceTransaction): PersistencePromise; + /** + * Returns the type of index (if any) that can be used to serve the given + * target. + */ + getIndexType(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Returns the documents that match the given target based on the provided + * index or `null` if the target does not have a matching index. + */ + getDocumentsMatchingTarget(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Returns the next collection group to update. Returns `null` if no group + * exists. + */ + getNextCollectionGroupToUpdate(transaction: PersistenceTransaction): PersistencePromise; + /** + * Sets the collection group's latest read time. + * + * This method updates the index offset for all field indices for the + * collection group and increments their sequence number. Subsequent calls to + * `getNextCollectionGroupToUpdate()` will return a different collection group + * (unless only one collection group is configured). + */ + updateCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset): PersistencePromise; + /** Updates the index entries for the provided documents. */ + updateIndexEntries(transaction: PersistenceTransaction, documents: DocumentMap): PersistencePromise; + /** + * Iterates over all field indexes that are used to serve the given target, + * and returns the minimum offset of them all. + */ + getMinOffset(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** Returns the minimum offset for the given collection group. */ + getMinOffsetFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise; +} + +/** + * Stores the latest read time, document and batch ID that were processed for an + * index. + */ +declare class IndexOffset { + /** + * The latest read time version that has been indexed by Firestore for this + * field index. + */ + readonly readTime: SnapshotVersion; + /** + * The key of the last document that was indexed for this query. Use + * `DocumentKey.empty()` if no document has been indexed. + */ + readonly documentKey: DocumentKey; + readonly largestBatchId: number; + constructor( + /** + * The latest read time version that has been indexed by Firestore for this + * field index. + */ + readTime: SnapshotVersion, + /** + * The key of the last document that was indexed for this query. Use + * `DocumentKey.empty()` if no document has been indexed. + */ + documentKey: DocumentKey, largestBatchId: number); + /** Returns an offset that sorts before all regular offsets. */ + static min(): IndexOffset; + /** Returns an offset that sorts after all regular offsets. */ + static max(): IndexOffset; +} + +/** An index component consisting of field path and index type. */ +declare class IndexSegment { + /** The field path of the component. */ + readonly fieldPath: FieldPath_2; + /** The fields sorting order. */ + readonly kind: IndexKind; + constructor( + /** The field path of the component. */ + fieldPath: FieldPath_2, + /** The fields sorting order. */ + kind: IndexKind); +} + +/** + * Stores the "high water mark" that indicates how updated the Index is for the + * current user. + */ +declare class IndexState { + /** + * Indicates when the index was last updated (relative to other indexes). + */ + readonly sequenceNumber: number; + /** The the latest indexed read time, document and batch id. */ + readonly offset: IndexOffset; + constructor( + /** + * Indicates when the index was last updated (relative to other indexes). + */ + sequenceNumber: number, + /** The the latest indexed read time, document and batch id. */ + offset: IndexOffset); + /** The state of an index that has not yet been backfilled. */ + static empty(): IndexState; +} + +declare type IndexState_2 = 'STATE_UNSPECIFIED' | 'CREATING' | 'READY' | 'ERROR'; + +/** Represents the index state as it relates to a particular target. */ +declare const enum IndexType { + /** Indicates that no index could be found for serving the target. */ + NONE = 0, + /** + * Indicates that only a "partial index" could be found for serving the + * target. A partial index is one which does not have a segment for every + * filter/orderBy in the target. + */ + PARTIAL = 1, + /** + * Indicates that a "full index" could be found for serving the target. A full + * index is one which has a segment for every filter/orderBy in the target. + */ + FULL = 2 +} + +/** + * Initializes a new instance of Cloud Firestore with the provided settings. + * Can only be called before any other functions, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will + * be associated. + * @param settings - A settings object to configure the `Firestore` instance. + * @returns A newly initialized `Firestore` instance. + */ +export declare function initializeFirestore(app: FirebaseApp, settings: Settings): Firestore; + +/** + * Initializes a new instance of Cloud Firestore with the provided settings. + * Can only be called before any other functions, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will + * be associated. + * @param settings - A settings object to configure the `Firestore` instance. + * @param databaseId - The name of the database. + * @returns A newly initialized `Firestore` instance. + * @beta + */ +export declare function initializeFirestore(app: FirebaseApp, settings: Settings, databaseId?: string): Firestore; + +/** + * This class generates JsonObject values for the Datastore API suitable for + * sending to either GRPC stub methods or via the JSON/HTTP REST API. + * + * The serializer supports both Protobuf.js and Proto3 JSON formats. By + * setting `useProto3Json` to true, the serializer will use the Proto3 JSON + * format. + * + * For a description of the Proto3 JSON format check + * https://developers.google.com/protocol-buffers/docs/proto3#json + * + * TODO(klimt): We can remove the databaseId argument if we keep the full + * resource name in documents. + */ +declare class JsonProtoSerializer implements Serializer { + readonly databaseId: DatabaseId; + readonly useProto3Json: boolean; + constructor(databaseId: DatabaseId, useProto3Json: boolean); +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A list of data types Firestore objects may serialize in their toJSON implemenetations. + * @private + * @internal + */ +declare type JsonTypeDesc = 'object' | 'string' | 'number' | 'boolean' | 'null' | 'undefined'; + +declare type Kind = 'memory' | 'persistent'; + +/** + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +export declare function limit(limit: number): QueryLimitConstraint; + +/** + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. + * + * You must specify at least one `orderBy` clause for `limitToLast` queries, + * otherwise an exception will be thrown during execution. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +export declare function limitToLast(limit: number): QueryLimitConstraint; + +declare const enum LimitType { + First = "F", + Last = "L" +} + +/** LimitType enum. */ +declare type LimitType_2 = 'FIRST' | 'LAST'; + +declare type ListenSequenceNumber = number; + +declare class LLRBEmptyNode { + get key(): never; + get value(): never; + get color(): never; + get left(): never; + get right(): never; + size: number; + copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode | LLRBEmptyNode | null, right: LLRBNode | LLRBEmptyNode | null): LLRBEmptyNode; + insert(key: K, value: V, comparator: Comparator): LLRBNode; + remove(key: K, comparator: Comparator): LLRBEmptyNode; + isEmpty(): boolean; + inorderTraversal(action: (k: K, v: V) => boolean): boolean; + reverseTraversal(action: (k: K, v: V) => boolean): boolean; + minKey(): K | null; + maxKey(): K | null; + isRed(): boolean; + checkMaxDepth(): boolean; + protected check(): 0; +} + +declare class LLRBNode { + key: K; + value: V; + readonly color: boolean; + readonly left: LLRBNode | LLRBEmptyNode; + readonly right: LLRBNode | LLRBEmptyNode; + readonly size: number; + static EMPTY: LLRBEmptyNode; + static RED: boolean; + static BLACK: boolean; + constructor(key: K, value: V, color?: boolean, left?: LLRBNode | LLRBEmptyNode, right?: LLRBNode | LLRBEmptyNode); + copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode | LLRBEmptyNode | null, right: LLRBNode | LLRBEmptyNode | null): LLRBNode; + isEmpty(): boolean; + inorderTraversal(action: (k: K, v: V) => T): T; + reverseTraversal(action: (k: K, v: V) => T): T; + private min; + minKey(): K | null; + maxKey(): K | null; + insert(key: K, value: V, comparator: Comparator): LLRBNode; + private removeMin; + remove(key: K, comparator: Comparator): LLRBNode | LLRBEmptyNode; + isRed(): boolean; + private fixUp; + private moveRedLeft; + private moveRedRight; + private rotateLeft; + private rotateRight; + private colorFlip; + checkMaxDepth(): boolean; + protected check(): number; +} + +/** + * A readonly view of the local state of all documents we're tracking (i.e. we + * have a cached version in remoteDocumentCache or local mutations for the + * document). The view is computed by applying the mutations in the + * MutationQueue to the RemoteDocumentCache. + */ +declare class LocalDocumentsView { + readonly remoteDocumentCache: RemoteDocumentCache; + readonly mutationQueue: MutationQueue; + readonly documentOverlayCache: DocumentOverlayCache; + readonly indexManager: IndexManager; + constructor(remoteDocumentCache: RemoteDocumentCache, mutationQueue: MutationQueue, documentOverlayCache: DocumentOverlayCache, indexManager: IndexManager); + /** + * Get the local view of the document identified by `key`. + * + * @returns Local view of the document or null if we don't have any cached + * state for it. + */ + getDocument(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; + /** + * Gets the local view of the documents identified by `keys`. + * + * If we don't have cached state for a document in `keys`, a NoDocument will + * be stored for that key in the resulting set. + */ + getDocuments(transaction: PersistenceTransaction, keys: DocumentKeySet): PersistencePromise; + /** + * Similar to `getDocuments`, but creates the local view from the given + * `baseDocs` without retrieving documents from the local store. + * + * @param transaction - The transaction this operation is scoped to. + * @param docs - The documents to apply local mutations to get the local views. + * @param existenceStateChanged - The set of document keys whose existence state + * is changed. This is useful to determine if some documents overlay needs + * to be recalculated. + */ + getLocalViewOfDocuments(transaction: PersistenceTransaction, docs: MutableDocumentMap, existenceStateChanged?: DocumentKeySet): PersistencePromise; + /** + * Gets the overlayed documents for the given document map, which will include + * the local view of those documents and a `FieldMask` indicating which fields + * are mutated locally, `null` if overlay is a Set or Delete mutation. + */ + getOverlayedDocuments(transaction: PersistenceTransaction, docs: MutableDocumentMap): PersistencePromise; + /** + * Fetches the overlays for {@code docs} and adds them to provided overlay map + * if the map does not already contain an entry for the given document key. + */ + private populateOverlays; + /** + * Computes the local view for the given documents. + * + * @param docs - The documents to compute views for. It also has the base + * version of the documents. + * @param overlays - The overlays that need to be applied to the given base + * version of the documents. + * @param existenceStateChanged - A set of documents whose existence states + * might have changed. This is used to determine if we need to re-calculate + * overlays from mutation queues. + * @return A map represents the local documents view. + */ + computeViews(transaction: PersistenceTransaction, docs: MutableDocumentMap, overlays: OverlayMap, existenceStateChanged: DocumentKeySet): PersistencePromise; + private recalculateAndSaveOverlays; + /** + * Recalculates overlays by reading the documents from remote document cache + * first, and saves them after they are calculated. + */ + recalculateAndSaveOverlaysForDocumentKeys(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise>; + /** + * Performs a query against the local view of all documents. + * + * @param transaction - The persistence transaction. + * @param query - The query to match documents against. + * @param offset - Read time and key to start scanning by (exclusive). + * @param context - A optional tracker to keep a record of important details + * during database local query execution. + */ + getDocumentsMatchingQuery(transaction: PersistenceTransaction, query: Query_2, offset: IndexOffset, context?: QueryContext): PersistencePromise; + /** + * Given a collection group, returns the next documents that follow the provided offset, along + * with an updated batch ID. + * + *

The documents returned by this method are ordered by remote version from the provided + * offset. If there are no more remote documents after the provided offset, documents with + * mutations in order of batch id from the offset are returned. Since all documents in a batch are + * returned together, the total number of documents returned can exceed {@code count}. + * + * @param transaction + * @param collectionGroup The collection group for the documents. + * @param offset The offset to index into. + * @param count The number of documents to return + * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id. + */ + getNextDocuments(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset, count: number): PersistencePromise; + private getDocumentsMatchingDocumentQuery; + private getDocumentsMatchingCollectionGroupQuery; + private getDocumentsMatchingCollectionQuery; +} + +declare interface LocalStore { + collectGarbage(garbageCollector: LruGarbageCollector): Promise; + /** Manages the list of active field and collection indices. */ + indexManager: IndexManager; + /** + * The "local" view of all documents (layering mutationQueue on top of + * remoteDocumentCache). + */ + localDocuments: LocalDocumentsView; +} + +/** The result of a write to the local store. */ +declare interface LocalWriteResult { + batchId: BatchId; + changes: DocumentMap; +} +export { LogLevel } + +declare interface LruGarbageCollector { + readonly params: LruParams; + collect(txn: PersistenceTransaction, activeTargetIds: ActiveTargets): PersistencePromise; + /** Given a percentile of target to collect, returns the number of targets to collect. */ + calculateTargetCount(txn: PersistenceTransaction, percentile: number): PersistencePromise; + /** Returns the nth sequence number, counting in order from the smallest. */ + nthSequenceNumber(txn: PersistenceTransaction, n: number): PersistencePromise; + /** + * Removes documents that have a sequence number equal to or less than the + * upper bound and are not otherwise pinned. + */ + removeOrphanedDocuments(txn: PersistenceTransaction, upperBound: ListenSequenceNumber): PersistencePromise; + getCacheSize(txn: PersistenceTransaction): PersistencePromise; + /** + * Removes targets with a sequence number equal to or less than the given + * upper bound, and removes document associations with those targets. + */ + removeTargets(txn: PersistenceTransaction, upperBound: ListenSequenceNumber, activeTargetIds: ActiveTargets): PersistencePromise; +} + +declare class LruParams { + readonly cacheSizeCollectionThreshold: number; + readonly percentileToCollect: number; + readonly maximumSequenceNumbersToCollect: number; + private static readonly DEFAULT_COLLECTION_PERCENTILE; + private static readonly DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT; + static withCacheSize(cacheSize: number): LruParams; + static readonly DEFAULT: LruParams; + static readonly DISABLED: LruParams; + constructor(cacheSizeCollectionThreshold: number, percentileToCollect: number, maximumSequenceNumbersToCollect: number); +} + +/** + * Describes the results of a garbage collection run. `didRun` will be set to + * `false` if collection was skipped (either it is disabled or the cache size + * has not hit the threshold). If collection ran, the other fields will be + * filled in with the details of the results. + */ +declare interface LruResults { + readonly didRun: boolean; + readonly sequenceNumbersCollected: number; + readonly targetsRemoved: number; + readonly documentsRemoved: number; +} + +declare type MapValue = firestoreV1ApiClientInterfaces.MapValue; + +/** + * Provides an in-memory cache to the SDK. This is the default cache unless explicitly + * configured otherwise. + * + * To use, create an instance using the factory function {@link memoryLocalCache()}, then + * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using + * the settings object. + */ +declare type MemoryLocalCache = { + kind: 'memory'; + /** + * @internal + */ + _onlineComponentProvider: OnlineComponentProviderFactory; + /** + * @internal + */ + _offlineComponentProvider: OfflineComponentProviderFactory; +}; + +/** + * Represents a document in Firestore with a key, version, data and whether it + * has local mutations applied to it. + * + * Documents can transition between states via `convertToFoundDocument()`, + * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does + * not transition to one of these states even after all mutations have been + * applied, `isValidDocument()` returns false and the document should be removed + * from all views. + */ +declare class MutableDocument implements Document_2 { + readonly key: DocumentKey; + private documentType; + version: SnapshotVersion; + readTime: SnapshotVersion; + createTime: SnapshotVersion; + data: ObjectValue; + private documentState; + private constructor(); + /** + * Creates a document with no known version or data, but which can serve as + * base document for mutations. + */ + static newInvalidDocument(documentKey: DocumentKey): MutableDocument; + /** + * Creates a new document that is known to exist with the given data at the + * given version. + */ + static newFoundDocument(documentKey: DocumentKey, version: SnapshotVersion, createTime: SnapshotVersion, value: ObjectValue): MutableDocument; + /** Creates a new document that is known to not exist at the given version. */ + static newNoDocument(documentKey: DocumentKey, version: SnapshotVersion): MutableDocument; + /** + * Creates a new document that is known to exist at the given version but + * whose data is not known (e.g. a document that was updated without a known + * base document). + */ + static newUnknownDocument(documentKey: DocumentKey, version: SnapshotVersion): MutableDocument; + /** + * Changes the document type to indicate that it exists and that its version + * and data are known. + */ + convertToFoundDocument(version: SnapshotVersion, value: ObjectValue): MutableDocument; + /** + * Changes the document type to indicate that it doesn't exist at the given + * version. + */ + convertToNoDocument(version: SnapshotVersion): MutableDocument; + /** + * Changes the document type to indicate that it exists at a given version but + * that its data is not known (e.g. a document that was updated without a known + * base document). + */ + convertToUnknownDocument(version: SnapshotVersion): MutableDocument; + setHasCommittedMutations(): MutableDocument; + setHasLocalMutations(): MutableDocument; + setReadTime(readTime: SnapshotVersion): MutableDocument; + get hasLocalMutations(): boolean; + get hasCommittedMutations(): boolean; + get hasPendingWrites(): boolean; + isValidDocument(): boolean; + isFoundDocument(): boolean; + isNoDocument(): boolean; + isUnknownDocument(): boolean; + isEqual(other: Document_2 | null | undefined): boolean; + mutableCopy(): MutableDocument; + toString(): string; +} + +/** Miscellaneous collection types / constants. */ +declare type MutableDocumentMap = SortedMap; + +/** + * A mutation describes a self-contained change to a document. Mutations can + * create, replace, delete, and update subsets of documents. + * + * Mutations not only act on the value of the document but also its version. + * + * For local mutations (mutations that haven't been committed yet), we preserve + * the existing version for Set and Patch mutations. For Delete mutations, we + * reset the version to 0. + * + * Here's the expected transition table. + * + * MUTATION APPLIED TO RESULTS IN + * + * SetMutation Document(v3) Document(v3) + * SetMutation NoDocument(v3) Document(v0) + * SetMutation InvalidDocument(v0) Document(v0) + * PatchMutation Document(v3) Document(v3) + * PatchMutation NoDocument(v3) NoDocument(v3) + * PatchMutation InvalidDocument(v0) UnknownDocument(v3) + * DeleteMutation Document(v3) NoDocument(v0) + * DeleteMutation NoDocument(v3) NoDocument(v0) + * DeleteMutation InvalidDocument(v0) NoDocument(v0) + * + * For acknowledged mutations, we use the updateTime of the WriteResponse as + * the resulting version for Set and Patch mutations. As deletes have no + * explicit update time, we use the commitTime of the WriteResponse for + * Delete mutations. + * + * If a mutation is acknowledged by the backend but fails the precondition check + * locally, we transition to an `UnknownDocument` and rely on Watch to send us + * the updated version. + * + * Field transforms are used only with Patch and Set Mutations. We use the + * `updateTransforms` message to store transforms, rather than the `transforms`s + * messages. + * + * ## Subclassing Notes + * + * Every type of mutation needs to implement its own applyToRemoteDocument() and + * applyToLocalView() to implement the actual behavior of applying the mutation + * to some source document (see `setMutationApplyToRemoteDocument()` for an + * example). + */ +declare abstract class Mutation { + abstract readonly type: MutationType; + abstract readonly key: DocumentKey; + abstract readonly precondition: Precondition; + abstract readonly fieldTransforms: FieldTransform[]; + /** + * Returns a `FieldMask` representing the fields that will be changed by + * applying this mutation. Returns `null` if the mutation will overwrite the + * entire document. + */ + abstract getFieldMask(): FieldMask | null; +} + +/** + * A batch of mutations that will be sent as one unit to the backend. + */ +declare class MutationBatch { + batchId: BatchId; + localWriteTime: Timestamp; + baseMutations: Mutation[]; + mutations: Mutation[]; + /** + * @param batchId - The unique ID of this mutation batch. + * @param localWriteTime - The original write time of this mutation. + * @param baseMutations - Mutations that are used to populate the base + * values when this mutation is applied locally. This can be used to locally + * overwrite values that are persisted in the remote document cache. Base + * mutations are never sent to the backend. + * @param mutations - The user-provided mutations in this mutation batch. + * User-provided mutations are applied both locally and remotely on the + * backend. + */ + constructor(batchId: BatchId, localWriteTime: Timestamp, baseMutations: Mutation[], mutations: Mutation[]); + /** + * Applies all the mutations in this MutationBatch to the specified document + * to compute the state of the remote document + * + * @param document - The document to apply mutations to. + * @param batchResult - The result of applying the MutationBatch to the + * backend. + */ + applyToRemoteDocument(document: MutableDocument, batchResult: MutationBatchResult): void; + /** + * Computes the local view of a document given all the mutations in this + * batch. + * + * @param document - The document to apply mutations to. + * @param mutatedFields - Fields that have been updated before applying this mutation batch. + * @returns A `FieldMask` representing all the fields that are mutated. + */ + applyToLocalView(document: MutableDocument, mutatedFields: FieldMask | null): FieldMask | null; + /** + * Computes the local view for all provided documents given the mutations in + * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to + * replace all the mutation applications. + */ + applyToLocalDocumentSet(documentMap: OverlayedDocumentMap, documentsWithoutRemoteVersion: DocumentKeySet): MutationMap; + keys(): DocumentKeySet; + isEqual(other: MutationBatch): boolean; +} + +/** The result of applying a mutation batch to the backend. */ +declare class MutationBatchResult { + readonly batch: MutationBatch; + readonly commitVersion: SnapshotVersion; + readonly mutationResults: MutationResult[]; + /** + * A pre-computed mapping from each mutated document to the resulting + * version. + */ + readonly docVersions: DocumentVersionMap; + private constructor(); + /** + * Creates a new MutationBatchResult for the given batch and results. There + * must be one result for each mutation in the batch. This static factory + * caches a document=>version mapping (docVersions). + */ + static from(batch: MutationBatch, commitVersion: SnapshotVersion, results: MutationResult[]): MutationBatchResult; +} + +declare type MutationMap = DocumentKeyMap; + +/** A queue of mutations to apply to the remote store. */ +declare interface MutationQueue { + /** Returns true if this queue contains no mutation batches. */ + checkEmpty(transaction: PersistenceTransaction): PersistencePromise; + /** + * Creates a new mutation batch and adds it to this mutation queue. + * + * @param transaction - The transaction this operation is scoped to. + * @param localWriteTime - The original write time of this mutation. + * @param baseMutations - Mutations that are used to populate the base values + * when this mutation is applied locally. These mutations are used to locally + * overwrite values that are persisted in the remote document cache. + * @param mutations - The user-provided mutations in this mutation batch. + */ + addMutationBatch(transaction: PersistenceTransaction, localWriteTime: Timestamp, baseMutations: Mutation[], mutations: Mutation[]): PersistencePromise; + /** + * Loads the mutation batch with the given batchId. + */ + lookupMutationBatch(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + /** + * Gets the first unacknowledged mutation batch after the passed in batchId + * in the mutation queue or null if empty. + * + * @param batchId - The batch to search after, or BATCHID_UNKNOWN for the + * first mutation in the queue. + * + * @returns the next mutation or null if there wasn't one. + */ + getNextMutationBatchAfterBatchId(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + /** + * Gets the largest (latest) batch id in mutation queue for the current user + * that is pending server response, returns `BATCHID_UNKNOWN` if the queue is + * empty. + * + * @returns the largest batch id in the mutation queue that is not + * acknowledged. + */ + getHighestUnacknowledgedBatchId(transaction: PersistenceTransaction): PersistencePromise; + /** Gets all mutation batches in the mutation queue. */ + getAllMutationBatches(transaction: PersistenceTransaction): PersistencePromise; + /** + * Finds all mutation batches that could possibly affect the given + * document key. Not all mutations in a batch will necessarily affect the + * document key, so when looping through the batch you'll need to check that + * the mutation itself matches the key. + * + * Batches are guaranteed to be in sorted order. + * + * Note that because of this requirement implementations are free to return + * mutation batches that don't contain the document key at all if it's + * convenient. + */ + getAllMutationBatchesAffectingDocumentKey(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + /** + * Finds all mutation batches that could possibly affect the given set of + * document keys. Not all mutations in a batch will necessarily affect each + * key, so when looping through the batch you'll need to check that the + * mutation itself matches the key. + * + * Batches are guaranteed to be in sorted order. + * + * Note that because of this requirement implementations are free to return + * mutation batches that don't contain any of the document keys at all if it's + * convenient. + */ + getAllMutationBatchesAffectingDocumentKeys(transaction: PersistenceTransaction, documentKeys: SortedMap): PersistencePromise; + /** + * Finds all mutation batches that could affect the results for the given + * query. Not all mutations in a batch will necessarily affect the query, so + * when looping through the batch you'll need to check that the mutation + * itself matches the query. + * + * Batches are guaranteed to be in sorted order. + * + * Note that because of this requirement implementations are free to return + * mutation batches that don't match the query at all if it's convenient. + * + * NOTE: A PatchMutation does not need to include all fields in the query + * filter criteria in order to be a match (but any fields it does contain do + * need to match). + */ + getAllMutationBatchesAffectingQuery(transaction: PersistenceTransaction, query: Query_2): PersistencePromise; + /** + * Removes the given mutation batch from the queue. This is useful in two + * circumstances: + * + * + Removing an applied mutation from the head of the queue + * + Removing a rejected mutation from anywhere in the queue + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMutationBatch(transaction: PersistenceTransaction, batch: MutationBatch): PersistencePromise; + /** + * Performs a consistency check, examining the mutation queue for any + * leaks, if possible. + */ + performConsistencyCheck(transaction: PersistenceTransaction): PersistencePromise; +} + +/** The result of successfully applying a mutation to the backend. */ +declare class MutationResult { + /** + * The version at which the mutation was committed: + * + * - For most operations, this is the updateTime in the WriteResult. + * - For deletes, the commitTime of the WriteResponse (because deletes are + * not stored and have no updateTime). + * + * Note that these versions can be different: No-op writes will not change + * the updateTime even though the commitTime advances. + */ + readonly version: SnapshotVersion; + /** + * The resulting fields returned from the backend after a mutation + * containing field transforms has been committed. Contains one FieldValue + * for each FieldTransform that was in the mutation. + * + * Will be empty if the mutation did not contain any field transforms. + */ + readonly transformResults: Array; + constructor( + /** + * The version at which the mutation was committed: + * + * - For most operations, this is the updateTime in the WriteResult. + * - For deletes, the commitTime of the WriteResponse (because deletes are + * not stored and have no updateTime). + * + * Note that these versions can be different: No-op writes will not change + * the updateTime even though the commitTime advances. + */ + version: SnapshotVersion, + /** + * The resulting fields returned from the backend after a mutation + * containing field transforms has been committed. Contains one FieldValue + * for each FieldTransform that was in the mutation. + * + * Will be empty if the mutation did not contain any field transforms. + */ + transformResults: Array); +} + +declare const enum MutationType { + Set = 0, + Patch = 1, + Delete = 2, + Verify = 3 +} + +/** + * Represents a Query saved by the SDK in its local storage. + */ +declare interface NamedQuery { + /** The name of the query. */ + readonly name: string; + /** The underlying query associated with `name`. */ + readonly query: Query_2; + /** The time at which the results for this query were read. */ + readonly readTime: SnapshotVersion; +} + +/** Properties of a NamedQuery. */ +declare interface NamedQuery_2 { + /** NamedQuery name */ + name?: string | null; + /** NamedQuery bundledQuery */ + bundledQuery?: BundledQuery | null; + /** NamedQuery readTime */ + readTime?: Timestamp_2 | null; +} + +/** + * For each field (e.g. 'bar'), find all nested keys (e.g. {'bar.baz': T1, + * 'bar.qux': T2}). Intersect them together to make a single map containing + * all possible keys that are all marked as optional + */ +export declare type NestedUpdateFields> = UnionToIntersection<{ + [K in keyof T & string]: ChildUpdateFields; +}[keyof T & string]>; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A map implementation that uses objects as keys. Objects must have an + * associated equals function and must be immutable. Entries in the map are + * stored together with the key being produced from the mapKeyFn. This map + * automatically handles collisions of keys. + */ +declare class ObjectMap { + private mapKeyFn; + private equalsFn; + /** + * The inner map for a key/value pair. Due to the possibility of collisions we + * keep a list of entries that we do a linear search through to find an actual + * match. Note that collisions should be rare, so we still expect near + * constant time lookups in practice. + */ + private inner; + /** The number of entries stored in the map */ + private innerSize; + constructor(mapKeyFn: (key: KeyType) => string, equalsFn: (l: KeyType, r: KeyType) => boolean); + /** Get a value for this key, or undefined if it does not exist. */ + get(key: KeyType): ValueType | undefined; + has(key: KeyType): boolean; + /** Put this key and value in the map. */ + set(key: KeyType, value: ValueType): void; + /** + * Remove this key from the map. Returns a boolean if anything was deleted. + */ + delete(key: KeyType): boolean; + forEach(fn: (key: KeyType, val: ValueType) => void): void; + isEmpty(): boolean; + size(): number; +} + +/** + * An ObjectValue represents a MapValue in the Firestore Proto and offers the + * ability to add and remove fields (via the ObjectValueBuilder). + */ +declare class ObjectValue { + readonly value: { + mapValue: MapValue; + }; + constructor(value: { + mapValue: MapValue; + }); + static empty(): ObjectValue; + /** + * Returns the value at the given path or null. + * + * @param path - the path to search + * @returns The value at the path or null if the path is not set. + */ + field(path: FieldPath_2): Value | null; + /** + * Sets the field to the provided value. + * + * @param path - The field path to set. + * @param value - The value to set. + */ + set(path: FieldPath_2, value: Value): void; + /** + * Sets the provided fields to the provided values. + * + * @param data - A map of fields to values (or null for deletes). + */ + setAll(data: Map): void; + /** + * Removes the field at the specified path. If there is no field at the + * specified path, nothing is changed. + * + * @param path - The field path to remove. + */ + delete(path: FieldPath_2): void; + isEqual(other: ObjectValue): boolean; + /** + * Returns the map that contains the leaf element of `path`. If the parent + * entry does not yet exist, or if it is not a map, a new map will be created. + */ + private getFieldsMap; + /** + * Modifies `fieldsMap` by adding, replacing or deleting the specified + * entries. + */ + private applyChanges; + clone(): ObjectValue; +} + +/** + * Initializes and wires components that are needed to interface with the local + * cache. Implementations override `initialize()` to provide all components. + */ +declare interface OfflineComponentProvider { + readonly kind: Kind; + persistence: Persistence; + sharedClientState: SharedClientState; + localStore: LocalStore; + gcScheduler: Scheduler | null; + indexBackfillerScheduler: Scheduler | null; + synchronizeTabs: boolean; + initialize(cfg: ComponentConfiguration): Promise; + terminate(): Promise; +} + +declare interface OfflineComponentProviderFactory { + build(onlineComponents: OnlineComponentProvider): OfflineComponentProvider; +} + +/** + * Initializes and wires the components that are needed to interface with the + * network. + */ +declare class OnlineComponentProvider { + static readonly provider: OnlineComponentProviderFactory; + protected localStore: LocalStore; + protected sharedClientState: SharedClientState; + datastore: Datastore; + eventManager: EventManager; + remoteStore: RemoteStore; + syncEngine: SyncEngine; + initialize(offlineComponentProvider: OfflineComponentProvider, cfg: ComponentConfiguration): Promise; + createEventManager(cfg: ComponentConfiguration): EventManager; + createDatastore(cfg: ComponentConfiguration): Datastore; + createRemoteStore(cfg: ComponentConfiguration): RemoteStore; + createSyncEngine(cfg: ComponentConfiguration, startAsPrimary: boolean): SyncEngine; + terminate(): Promise; +} + +declare interface OnlineComponentProviderFactory { + build(): OnlineComponentProvider; +} + +/** + * Describes the online state of the Firestore client. Note that this does not + * indicate whether or not the remote store is trying to connect or not. This is + * primarily used by the View / EventManager code to change their behavior while + * offline (e.g. get() calls shouldn't wait for data from the server and + * snapshot events should set metadata.isFromCache=true). + * + * The string values should not be changed since they are persisted in + * WebStorage. + */ +declare const enum OnlineState { + /** + * The Firestore client is in an unknown online state. This means the client + * is either not actively trying to establish a connection or it is currently + * trying to establish a connection, but it has not succeeded or failed yet. + * Higher-level components should not operate in offline mode. + */ + Unknown = "Unknown", + /** + * The client is connected and the connections are healthy. This state is + * reached after a successful connection and there has been at least one + * successful message received from the backends. + */ + Online = "Online", + /** + * The client is either trying to establish a connection but failing, or it + * has been explicitly marked offline via a call to disableNetwork(). + * Higher-level components should operate in offline mode. + */ + Offline = "Offline" +} + +declare const enum Operator { + LESS_THAN = "<", + LESS_THAN_OR_EQUAL = "<=", + EQUAL = "==", + NOT_EQUAL = "!=", + GREATER_THAN = ">", + GREATER_THAN_OR_EQUAL = ">=", + ARRAY_CONTAINS = "array-contains", + IN = "in", + NOT_IN = "not-in", + ARRAY_CONTAINS_ANY = "array-contains-any" +} + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +export declare function or(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; + +/** + * An ordering on a field, in some Direction. Direction defaults to ASCENDING. + */ +declare class OrderBy { + readonly field: FieldPath_2; + readonly dir: Direction; + constructor(field: FieldPath_2, dir?: Direction); +} + +/** + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the + * specified field, optionally in descending order instead of ascending. + * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * + * @param fieldPath - The field to sort by. + * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @returns The created {@link QueryOrderByConstraint}. + */ +export declare function orderBy(fieldPath: string | FieldPath, directionStr?: OrderByDirection): QueryOrderByConstraint; + +/** + * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc' + * (descending or ascending). + */ +export declare type OrderByDirection = 'desc' | 'asc'; + +declare type OrderDirection = 'DIRECTION_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING'; + +/** + * Representation of an overlay computed by Firestore. + * + * Holds information about a mutation and the largest batch id in Firestore when + * the mutation was created. + */ +declare class Overlay { + readonly largestBatchId: number; + readonly mutation: Mutation; + constructor(largestBatchId: number, mutation: Mutation); + getKey(): DocumentKey; + isEqual(other: Overlay | null): boolean; + toString(): string; +} + +/** + * Represents a local view (overlay) of a document, and the fields that are + * locally mutated. + */ +declare class OverlayedDocument { + readonly overlayedDocument: Document_2; + /** + * The fields that are locally mutated by patch mutations. + * + * If the overlayed document is from set or delete mutations, this is `null`. + * If there is no overlay (mutation) for the document, this is an empty `FieldMask`. + */ + readonly mutatedFields: FieldMask | null; + constructor(overlayedDocument: Document_2, + /** + * The fields that are locally mutated by patch mutations. + * + * If the overlayed document is from set or delete mutations, this is `null`. + * If there is no overlay (mutation) for the document, this is an empty `FieldMask`. + */ + mutatedFields: FieldMask | null); +} + +declare type OverlayedDocumentMap = DocumentKeyMap; + +declare type OverlayMap = DocumentKeyMap; + +declare interface ParseContext { + readonly databaseId: DatabaseId; + readonly ignoreUndefinedProperties: boolean; +} + +/** The result of parsing document data (e.g. for a setData call). */ +declare class ParsedSetData { + readonly data: ObjectValue; + readonly fieldMask: FieldMask | null; + readonly fieldTransforms: FieldTransform[]; + constructor(data: ObjectValue, fieldMask: FieldMask | null, fieldTransforms: FieldTransform[]); + toMutation(key: DocumentKey, precondition: Precondition): Mutation; +} + +/** The result of parsing "update" data (i.e. for an updateData call). */ +declare class ParsedUpdateData { + readonly data: ObjectValue; + readonly fieldMask: FieldMask; + readonly fieldTransforms: FieldTransform[]; + constructor(data: ObjectValue, fieldMask: FieldMask, fieldTransforms: FieldTransform[]); + toMutation(key: DocumentKey, precondition: Precondition): Mutation; +} + +/** + * Similar to TypeScript's `Partial`, but allows nested fields to be + * omitted and FieldValues to be passed in as property values. + */ +export declare type PartialWithFieldValue = Partial | (T extends Primitive ? T : T extends {} ? { + [K in keyof T]?: PartialWithFieldValue | FieldValue; +} : never); + +/** + * Persistence is the lowest-level shared interface to persistent storage in + * Firestore. + * + * Persistence is used to create MutationQueue and RemoteDocumentCache + * instances backed by persistence (which might be in-memory or LevelDB). + * + * Persistence also exposes an API to create and run PersistenceTransactions + * against persistence. All read / write operations must be wrapped in a + * transaction. Implementations of PersistenceTransaction / Persistence only + * need to guarantee that writes made against the transaction are not made to + * durable storage until the transaction resolves its PersistencePromise. + * Since memory-only storage components do not alter durable storage, they are + * free to ignore the transaction. + * + * This contract is enough to allow the LocalStore be be written + * independently of whether or not the stored state actually is durably + * persisted. If persistent storage is enabled, writes are grouped together to + * avoid inconsistent state that could cause crashes. + * + * Concretely, when persistent storage is enabled, the persistent versions of + * MutationQueue, RemoteDocumentCache, and others (the mutators) will + * defer their writes into a transaction. Once the local store has completed + * one logical operation, it commits the transaction. + * + * When persistent storage is disabled, the non-persistent versions of the + * mutators ignore the transaction. This short-cut is allowed because + * memory-only storage leaves no state so it cannot be inconsistent. + * + * This simplifies the implementations of the mutators and allows memory-only + * implementations to supplement the persistent ones without requiring any + * special dual-store implementation of Persistence. The cost is that the + * LocalStore needs to be slightly careful about the order of its reads and + * writes in order to avoid relying on being able to read back uncommitted + * writes. + */ +declare interface Persistence { + /** + * Whether or not this persistence instance has been started. + */ + readonly started: boolean; + readonly referenceDelegate: ReferenceDelegate; + /** Starts persistence. */ + start(): Promise; + /** + * Releases any resources held during eager shutdown. + */ + shutdown(): Promise; + /** + * Registers a listener that gets called when the database receives a + * version change event indicating that it has deleted. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setDatabaseDeletedListener(databaseDeletedListener: () => Promise): void; + /** + * Adjusts the current network state in the client's metadata, potentially + * affecting the primary lease. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setNetworkEnabled(networkEnabled: boolean): void; + /** + * Returns GlobalCache representing a general purpose cache for global values. + */ + getGlobalsCache(): GlobalsCache; + /** + * Returns a MutationQueue representing the persisted mutations for the + * given user. + * + * Note: The implementation is free to return the same instance every time + * this is called for a given user. In particular, the memory-backed + * implementation does this to emulate the persisted implementation to the + * extent possible (e.g. in the case of uid switching from + * sally=>jack=>sally, sally's mutation queue will be preserved). + */ + getMutationQueue(user: User, indexManager: IndexManager): MutationQueue; + /** + * Returns a TargetCache representing the persisted cache of targets. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getTargetCache(): TargetCache; + /** + * Returns a RemoteDocumentCache representing the persisted cache of remote + * documents. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getRemoteDocumentCache(): RemoteDocumentCache; + /** + * Returns a BundleCache representing the persisted cache of loaded bundles. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getBundleCache(): BundleCache; + /** + * Returns an IndexManager instance that manages our persisted query indexes. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getIndexManager(user: User): IndexManager; + /** + * Returns a DocumentOverlayCache representing the documents that are mutated + * locally. + */ + getDocumentOverlayCache(user: User): DocumentOverlayCache; + /** + * Performs an operation inside a persistence transaction. Any reads or writes + * against persistence must be performed within a transaction. Writes will be + * committed atomically once the transaction completes. + * + * Persistence operations are asynchronous and therefore the provided + * transactionOperation must return a PersistencePromise. When it is resolved, + * the transaction will be committed and the Promise returned by this method + * will resolve. + * + * @param action - A description of the action performed by this transaction, + * used for logging. + * @param mode - The underlying mode of the IndexedDb transaction. Can be + * 'readonly', 'readwrite' or 'readwrite-primary'. Transactions marked + * 'readwrite-primary' can only be executed by the primary client. In this + * mode, the transactionOperation will not be run if the primary lease cannot + * be acquired and the returned promise will be rejected with a + * FAILED_PRECONDITION error. + * @param transactionOperation - The operation to run inside a transaction. + * @returns A `Promise` that is resolved once the transaction completes. + */ + runTransaction(action: string, mode: PersistenceTransactionMode, transactionOperation: (transaction: PersistenceTransaction) => PersistencePromise): Promise; +} + +/** + * PersistencePromise is essentially a re-implementation of Promise except + * it has a .next() method instead of .then() and .next() and .catch() callbacks + * are executed synchronously when a PersistencePromise resolves rather than + * asynchronously (Promise implementations use setImmediate() or similar). + * + * This is necessary to interoperate with IndexedDB which will automatically + * commit transactions if control is returned to the event loop without + * synchronously initiating another operation on the transaction. + * + * NOTE: .then() and .catch() only allow a single consumer, unlike normal + * Promises. + */ +declare class PersistencePromise { + private nextCallback; + private catchCallback; + private result; + private error; + private isDone; + private callbackAttached; + constructor(callback: (resolve: Resolver, reject: Rejector) => void); + catch(fn: (error: Error) => R | PersistencePromise): PersistencePromise; + next(nextFn?: FulfilledHandler, catchFn?: RejectedHandler): PersistencePromise; + toPromise(): Promise; + private wrapUserFunction; + private wrapSuccess; + private wrapFailure; + static resolve(): PersistencePromise; + static resolve(result: R): PersistencePromise; + static reject(error: Error): PersistencePromise; + static waitFor(all: { + forEach: (cb: (el: PersistencePromise) => void) => void; + }): PersistencePromise; + /** + * Given an array of predicate functions that asynchronously evaluate to a + * boolean, implements a short-circuiting `or` between the results. Predicates + * will be evaluated until one of them returns `true`, then stop. The final + * result will be whether any of them returned `true`. + */ + static or(predicates: Array<() => PersistencePromise>): PersistencePromise; + /** + * Given an iterable, call the given function on each element in the + * collection and wait for all of the resulting concurrent PersistencePromises + * to resolve. + */ + static forEach(collection: { + forEach: (cb: (r: R, s: S) => void) => void; + }, f: ((r: R, s: S) => PersistencePromise) | ((r: R) => PersistencePromise)): PersistencePromise; + static forEach(collection: { + forEach: (cb: (r: R) => void) => void; + }, f: (r: R) => PersistencePromise): PersistencePromise; + /** + * Concurrently map all array elements through asynchronous function. + */ + static mapArray(array: T[], f: (t: T) => PersistencePromise): PersistencePromise; + /** + * An alternative to recursive PersistencePromise calls, that avoids + * potential memory problems from unbounded chains of promises. + * + * The `action` will be called repeatedly while `condition` is true. + */ + static doWhile(condition: () => boolean, action: () => PersistencePromise): PersistencePromise; +} + +/** + * A base class representing a persistence transaction, encapsulating both the + * transaction's sequence numbers as well as a list of onCommitted listeners. + * + * When you call Persistence.runTransaction(), it will create a transaction and + * pass it to your callback. You then pass it to any method that operates + * on persistence. + */ +declare abstract class PersistenceTransaction { + private readonly onCommittedListeners; + abstract readonly currentSequenceNumber: ListenSequenceNumber; + addOnCommittedListener(listener: () => void): void; + raiseOnCommittedEvent(): void; +} + +/** The different modes supported by `Persistence.runTransaction()`. */ +declare type PersistenceTransactionMode = 'readonly' | 'readwrite' | 'readwrite-primary'; + +/** + * Provides a persistent cache backed by IndexedDb to the SDK. + * + * To use, create an instance using the factory function {@link persistentLocalCache()}, then + * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using + * the settings object. + */ +declare type PersistentLocalCache = { + kind: 'persistent'; + /** + * @internal + */ + _onlineComponentProvider: OnlineComponentProviderFactory; + /** + * @internal + */ + _offlineComponentProvider: OfflineComponentProviderFactory; +}; + +/** + * Encodes a precondition for a mutation. This follows the model that the + * backend accepts with the special case of an explicit "empty" precondition + * (meaning no precondition). + */ +declare class Precondition { + readonly updateTime?: SnapshotVersion | undefined; + readonly exists?: boolean | undefined; + private constructor(); + /** Creates a new empty Precondition. */ + static none(): Precondition; + /** Creates a new Precondition with an exists flag. */ + static exists(exists: boolean): Precondition; + /** Creates a new Precondition based on a version a document exists at. */ + static updateTime(version: SnapshotVersion): Precondition; + /** Returns whether this Precondition is empty. */ + get isNone(): boolean; + isEqual(other: Precondition): boolean; +} + +/** + * These types primarily exist to support the `UpdateData`, + * `WithFieldValue`, and `PartialWithFieldValue` types and are not consumed + * directly by the end developer. + */ +/** Primitive types. */ +export declare type Primitive = string | number | boolean | undefined | null; + +/** + * @internal + * Undocumented, private additional settings not exposed in our public API. + */ +declare interface PrivateSettings extends Settings { + credentials?: CredentialsSettings; + cacheSizeBytes?: number; + experimentalForceLongPolling?: boolean; + experimentalAutoDetectLongPolling?: boolean; + experimentalLongPollingOptions?: ExperimentalLongPollingOptions; + useFetchStreams?: boolean; + emulatorOptions?: { + mockUserToken?: EmulatorMockTokenOptions | string; + }; + localCache?: FirestoreLocalCache; +} + +/** + * The representation of a JSON object property name and its type value. + * @private + * @internal + */ +declare interface Property { + value?: TSType; + typeString: JsonTypeDesc; +} + +declare interface ProviderCredentialsSettings { + ['type']: 'provider'; + ['client']: CredentialsProvider; +} + +/** + * A `Query` refers to a query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ +export declare class Query { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter | null; + readonly _query: Query_2; + /** The type of this Firestore reference. */ + readonly type: 'query' | 'collection'; + /** + * The `Firestore` instance for the Firestore database (useful for performing + * transactions, etc.). + */ + readonly firestore: Firestore; + /** @hideconstructor protected */ + constructor(firestore: Firestore, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter: FirestoreDataConverter | null, _query: Query_2); + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `Query` that does not use a + * converter. + */ + withConverter(converter: null): Query; + /** + * Applies a custom data converter to this query, allowing you to use your own + * custom model objects with Firestore. When you call {@link getDocs} with + * the returned query, the provided converter will convert between Firestore + * data of type `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `Query` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter): Query; +} + +/** + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. + * + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to + * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or + * {@link or}. + * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to + * apply (e.g. {@link orderBy}, {@link limit}). + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query(query: Query, compositeFilter: QueryCompositeFilterConstraint, ...queryConstraints: QueryNonFilterConstraint[]): Query; + +/** + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. + * + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param queryConstraints - The list of {@link QueryConstraint}s to apply. + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query(query: Query, ...queryConstraints: QueryConstraint[]): Query; + +/** + * The Query interface defines all external properties of a query. + * + * QueryImpl implements this interface to provide memoization for `queryNormalizedOrderBy` + * and `queryToTarget`. + */ +declare interface Query_2 { + readonly path: ResourcePath; + readonly collectionGroup: string | null; + readonly explicitOrderBy: OrderBy[]; + readonly filters: Filter[]; + readonly limit: number | null; + readonly limitType: LimitType; + readonly startAt: Bound | null; + readonly endAt: Bound | null; +} + +/** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ +export declare class QueryCompositeFilterConstraint extends AppliableConstraint { + /** The type of this query constraint */ + readonly type: 'or' | 'and'; + private readonly _queryConstraints; + /** + * @internal + */ + protected constructor( + /** The type of this query constraint */ + type: 'or' | 'and', _queryConstraints: QueryFilterConstraint[]); + static _create(type: 'or' | 'and', _queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; + _parse(query: Query): Filter; + _apply(query: Query): Query; + _getQueryConstraints(): readonly AppliableConstraint[]; + _getOperator(): CompositeOperator; +} + +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Firestore query. `QueryConstraint`s are created by invoking {@link where}, + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that + * also contains this `QueryConstraint`. + */ +export declare abstract class QueryConstraint extends AppliableConstraint { + /** The type of this query constraint */ + abstract readonly type: QueryConstraintType; + /** + * Takes the provided {@link Query} and returns a copy of the {@link Query} with this + * {@link AppliableConstraint} applied. + */ + abstract _apply(query: Query): Query; +} + +/** Describes the different query constraints available in this SDK. */ +export declare type QueryConstraintType = 'where' | 'orderBy' | 'limit' | 'limitToLast' | 'startAt' | 'startAfter' | 'endAt' | 'endBefore'; + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A tracker to keep a record of important details during database local query + * execution. + */ +declare class QueryContext { + /** + * Counts the number of documents passed through during local query execution. + */ + private _documentReadCount; + get documentReadCount(): number; + incrementDocumentReadCount(amount: number): void; +} + +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ +export declare class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * @override + * @returns An `Object` containing all fields in the document. + */ + data(): AppModelType; +} + +/** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ +export declare class QueryEndAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'endBefore' | 'endAt'; + private readonly _docOrFields; + private readonly _inclusive; + /** + * @internal + */ + protected constructor( + /** The type of this query constraint */ + type: 'endBefore' | 'endAt', _docOrFields: Array>, _inclusive: boolean); + static _create(type: 'endBefore' | 'endAt', _docOrFields: Array>, _inclusive: boolean): QueryEndAtConstraint; + _apply(query: Query): Query; +} + +/** + * Returns true if the provided queries point to the same collection and apply + * the same constraints. + * + * @param left - A `Query` to compare. + * @param right - A `Query` to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +export declare function queryEqual(left: Query, right: Query): boolean; + +/** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ +export declare class QueryFieldFilterConstraint extends QueryConstraint { + private readonly _field; + private _op; + private _value; + /** The type of this query constraint */ + readonly type = "where"; + /** + * @internal + */ + protected constructor(_field: FieldPath_2, _op: Operator, _value: unknown); + static _create(_field: FieldPath_2, _op: Operator, _value: unknown): QueryFieldFilterConstraint; + _apply(query: Query): Query; + _parse(query: Query): FieldFilter; +} + +/** + * `QueryFilterConstraint` is a helper union type that represents + * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}. + */ +export declare type QueryFilterConstraint = QueryFieldFilterConstraint | QueryCompositeFilterConstraint; + +/** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ +export declare class QueryLimitConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'limit' | 'limitToLast'; + private readonly _limit; + private readonly _limitType; + /** + * @internal + */ + protected constructor( + /** The type of this query constraint */ + type: 'limit' | 'limitToLast', _limit: number, _limitType: LimitType); + static _create(type: 'limit' | 'limitToLast', _limit: number, _limitType: LimitType): QueryLimitConstraint; + _apply(query: Query): Query; +} + +/** + * `QueryNonFilterConstraint` is a helper union type that represents + * QueryConstraints which are used to narrow or order the set of documents, + * but that do not explicitly filter on a document field. + * `QueryNonFilterConstraint`s are created by invoking {@link orderBy}, + * {@link (startAt:1)}, {@link (startAfter:1)}, {@link (endBefore:1)}, {@link (endAt:1)}, + * {@link limit} or {@link limitToLast} and can then be passed to {@link (query:1)} + * to create a new query instance that also contains the `QueryConstraint`. + */ +export declare type QueryNonFilterConstraint = QueryOrderByConstraint | QueryLimitConstraint | QueryStartAtConstraint | QueryEndAtConstraint; + +/** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ +export declare class QueryOrderByConstraint extends QueryConstraint { + private readonly _field; + private _direction; + /** The type of this query constraint */ + readonly type = "orderBy"; + /** + * @internal + */ + protected constructor(_field: FieldPath_2, _direction: Direction); + static _create(_field: FieldPath_2, _direction: Direction): QueryOrderByConstraint; + _apply(query: Query): Query; +} + +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ +export declare class QuerySnapshot { + readonly _docs: Array>; + /** + * The query on which you called {@link getDocs} in order to get this + * `QuerySnapshot`. + */ + readonly query: Query; + /** @hideconstructor */ + constructor(_query: Query, _docs: Array>); + /** An array of all the documents in the `QuerySnapshot`. */ + get docs(): Array>; + /** The number of documents in the `QuerySnapshot`. */ + get size(): number; + /** True if there are no documents in the `QuerySnapshot`. */ + get empty(): boolean; + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ + forEach(callback: (result: QueryDocumentSnapshot) => void, thisArg?: unknown): void; +} + +/** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ +export declare class QueryStartAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'startAt' | 'startAfter'; + private readonly _docOrFields; + private readonly _inclusive; + /** + * @internal + */ + protected constructor( + /** The type of this query constraint */ + type: 'startAt' | 'startAfter', _docOrFields: Array>, _inclusive: boolean); + static _create(type: 'startAt' | 'startAfter', _docOrFields: Array>, _inclusive: boolean): QueryStartAtConstraint; + _apply(query: Query): Query; +} + +/** The different states of a watch target. */ +declare type QueryTargetState = 'not-current' | 'current' | 'rejected'; + +/** + * Returns true if the provided references are equal. + * + * @param left - A reference to compare. + * @param right - A reference to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +export declare function refEqual(left: DocumentReference | CollectionReference, right: DocumentReference | CollectionReference): boolean; + +/** + * A ReferenceDelegate instance handles all of the hooks into the document-reference lifecycle. This + * includes being added to a target, being removed from a target, being subject to mutation, and + * being mutated by the user. + * + * Different implementations may do different things with each of these events. Not every + * implementation needs to do something with every lifecycle hook. + * + * PORTING NOTE: since sequence numbers are attached to transactions in this + * client, the ReferenceDelegate does not need to deal in transactional + * semantics (onTransactionStarted/Committed()), nor does it need to track and + * generate sequence numbers (getCurrentSequenceNumber()). + */ +declare interface ReferenceDelegate { + /** Notify the delegate that the given document was added to a target. */ + addReference(txn: PersistenceTransaction, targetId: TargetId, doc: DocumentKey): PersistencePromise; + /** Notify the delegate that the given document was removed from a target. */ + removeReference(txn: PersistenceTransaction, targetId: TargetId, doc: DocumentKey): PersistencePromise; + /** + * Notify the delegate that a target was removed. The delegate may, but is not obligated to, + * actually delete the target and associated data. + */ + removeTarget(txn: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Notify the delegate that a document may no longer be part of any views or + * have any mutations associated. + */ + markPotentiallyOrphaned(txn: PersistenceTransaction, doc: DocumentKey): PersistencePromise; + /** Notify the delegate that a limbo document was updated. */ + updateLimboDocument(txn: PersistenceTransaction, doc: DocumentKey): PersistencePromise; +} + +declare type RejectedHandler = ((reason: Error) => R | PersistencePromise) | null; + +declare type Rejector = (error: Error) => void; + +/** + * Represents cached documents received from the remote backend. + * + * The cache is keyed by DocumentKey and entries in the cache are + * MutableDocuments, meaning we can cache both actual documents as well as + * documents that are known to not exist. + */ +declare interface RemoteDocumentCache { + /** Sets the index manager to use for managing the collectionGroup index. */ + setIndexManager(indexManager: IndexManager): void; + /** + * Looks up an entry in the cache. + * + * @param documentKey - The key of the entry to look up.* + * @returns The cached document entry. Returns an invalid document if the + * document is not cached. + */ + getEntry(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + /** + * Looks up a set of entries in the cache. + * + * @param documentKeys - The keys of the entries to look up. + * @returns The cached document entries indexed by key. If an entry is not + * cached, the corresponding key will be mapped to an invalid document. + */ + getEntries(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise; + /** + * Returns the documents matching the given query + * + * @param query - The query to match documents against. + * @param offset - The offset to start the scan at (exclusive). + * @param context - A optional tracker to keep a record of important details + * during database local query execution. + * @returns The set of matching documents. + */ + getDocumentsMatchingQuery(transaction: PersistenceTransaction, query: Query_2, offset: IndexOffset, mutatedDocs: OverlayMap, context?: QueryContext): PersistencePromise; + /** + * Looks up the next `limit` documents for a collection group based on the + * provided offset. The ordering is based on the document's read time and key. + * + * @param collectionGroup - The collection group to scan. + * @param offset - The offset to start the scan at (exclusive). + * @param limit - The maximum number of results to return. + * @returns The set of matching documents. + */ + getAllFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset, limit: number): PersistencePromise; + /** + * Provides access to add or update the contents of the cache. The buffer + * handles proper size accounting for the change. + * + * Multi-Tab Note: This should only be called by the primary client. + * + * @param options - Specify `trackRemovals` to create sentinel entries for + * removed documents, which allows removals to be tracked by + * `getNewDocumentChanges()`. + */ + newChangeBuffer(options?: { + trackRemovals: boolean; + }): RemoteDocumentChangeBuffer; + /** + * Get an estimate of the size of the document cache. Note that for eager + * garbage collection, we don't track sizes so this will return 0. + */ + getSize(transaction: PersistenceTransaction): PersistencePromise; +} + +/** + * An in-memory buffer of entries to be written to a RemoteDocumentCache. + * It can be used to batch up a set of changes to be written to the cache, but + * additionally supports reading entries back with the `getEntry()` method, + * falling back to the underlying RemoteDocumentCache if no entry is + * buffered. + * + * Entries added to the cache *must* be read first. This is to facilitate + * calculating the size delta of the pending changes. + * + * PORTING NOTE: This class was implemented then removed from other platforms. + * If byte-counting ends up being needed on the other platforms, consider + * porting this class as part of that implementation work. + */ +declare abstract class RemoteDocumentChangeBuffer { + protected changes: ObjectMap; + private changesApplied; + protected abstract getFromCache(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + protected abstract getAllFromCache(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise; + protected abstract applyChanges(transaction: PersistenceTransaction): PersistencePromise; + /** + * Buffers a `RemoteDocumentCache.addEntry()` call. + * + * You can only modify documents that have already been retrieved via + * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). + */ + addEntry(document: MutableDocument): void; + /** + * Buffers a `RemoteDocumentCache.removeEntry()` call. + * + * You can only remove documents that have already been retrieved via + * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). + */ + removeEntry(key: DocumentKey, readTime: SnapshotVersion): void; + /** + * Looks up an entry in the cache. The buffered changes will first be checked, + * and if no buffered change applies, this will forward to + * `RemoteDocumentCache.getEntry()`. + * + * @param transaction - The transaction in which to perform any persistence + * operations. + * @param documentKey - The key of the entry to look up. + * @returns The cached document or an invalid document if we have nothing + * cached. + */ + getEntry(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + /** + * Looks up several entries in the cache, forwarding to + * `RemoteDocumentCache.getEntry()`. + * + * @param transaction - The transaction in which to perform any persistence + * operations. + * @param documentKeys - The keys of the entries to look up. + * @returns A map of cached documents, indexed by key. If an entry cannot be + * found, the corresponding key will be mapped to an invalid document. + */ + getEntries(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise; + /** + * Applies buffered changes to the underlying RemoteDocumentCache, using + * the provided transaction. + */ + apply(transaction: PersistenceTransaction): PersistencePromise; + /** Helper to assert this.changes is not null */ + protected assertNotApplied(): void; +} + +/** + * An event from the RemoteStore. It is split into targetChanges (changes to the + * state or the set of documents in our watched targets) and documentUpdates + * (changes to the actual documents). + */ +declare class RemoteEvent { + /** + * The snapshot version this event brings us up to, or MIN if not set. + */ + readonly snapshotVersion: SnapshotVersion; + /** + * A map from target to changes to the target. See TargetChange. + */ + readonly targetChanges: Map; + /** + * A map of targets that is known to be inconsistent, and the purpose for + * re-listening. Listens for these targets should be re-established without + * resume tokens. + */ + readonly targetMismatches: SortedMap; + /** + * A set of which documents have changed or been deleted, along with the + * doc's new values (if not deleted). + */ + readonly documentUpdates: MutableDocumentMap; + /** + * A set of which document updates are due only to limbo resolution targets. + */ + readonly resolvedLimboDocuments: DocumentKeySet; + constructor( + /** + * The snapshot version this event brings us up to, or MIN if not set. + */ + snapshotVersion: SnapshotVersion, + /** + * A map from target to changes to the target. See TargetChange. + */ + targetChanges: Map, + /** + * A map of targets that is known to be inconsistent, and the purpose for + * re-listening. Listens for these targets should be re-established without + * resume tokens. + */ + targetMismatches: SortedMap, + /** + * A set of which documents have changed or been deleted, along with the + * doc's new values (if not deleted). + */ + documentUpdates: MutableDocumentMap, + /** + * A set of which document updates are due only to limbo resolution targets. + */ + resolvedLimboDocuments: DocumentKeySet); + /** + * HACK: Views require RemoteEvents in order to determine whether the view is + * CURRENT, but secondary tabs don't receive remote events. So this method is + * used to create a synthesized RemoteEvent that can be used to apply a + * CURRENT status change to a View, for queries executed in a different tab. + */ + static createSynthesizedRemoteEventForCurrentChange(targetId: TargetId, current: boolean, resumeToken: ByteString): RemoteEvent; +} + +/** + * RemoteStore - An interface to remotely stored data, basically providing a + * wrapper around the Datastore that is more reliable for the rest of the + * system. + * + * RemoteStore is responsible for maintaining the connection to the server. + * - maintaining a list of active listens. + * - reconnecting when the connection is dropped. + * - resuming all the active listens on reconnect. + * + * RemoteStore handles all incoming events from the Datastore. + * - listening to the watch stream and repackaging the events as RemoteEvents + * - notifying SyncEngine of any changes to the active listens. + * + * RemoteStore takes writes from other components and handles them reliably. + * - pulling pending mutations from LocalStore and sending them to Datastore. + * - retrying mutations that failed because of network problems. + * - acking mutations to the SyncEngine once they are accepted or rejected. + */ +declare interface RemoteStore { + /** + * SyncEngine to notify of watch and write events. This must be set + * immediately after construction. + */ + remoteSyncer: RemoteSyncer; +} + +/** + * An interface that describes the actions the RemoteStore needs to perform on + * a cooperating synchronization engine. + */ +declare interface RemoteSyncer { + /** + * Applies one remote event to the sync engine, notifying any views of the + * changes, and releasing any pending mutation batches that would become + * visible because of the snapshot version the remote event contains. + */ + applyRemoteEvent?(remoteEvent: RemoteEvent): Promise; + /** + * Rejects the listen for the given targetID. This can be triggered by the + * backend for any active target. + * + * @param targetId - The targetID corresponds to one previously initiated by + * the user as part of TargetData passed to listen() on RemoteStore. + * @param error - A description of the condition that has forced the rejection. + * Nearly always this will be an indication that the user is no longer + * authorized to see the data matching the target. + */ + rejectListen?(targetId: TargetId, error: FirestoreError): Promise; + /** + * Applies the result of a successful write of a mutation batch to the sync + * engine, emitting snapshots in any views that the mutation applies to, and + * removing the batch from the mutation queue. + */ + applySuccessfulWrite?(result: MutationBatchResult): Promise; + /** + * Rejects the batch, removing the batch from the mutation queue, recomputing + * the local view of any documents affected by the batch and then, emitting + * snapshots with the reverted value. + */ + rejectFailedWrite?(batchId: BatchId, error: FirestoreError): Promise; + /** + * Returns the set of remote document keys for the given target ID. This list + * includes the documents that were assigned to the target when we received + * the last snapshot. + */ + getRemoteKeysForTarget?(targetId: TargetId): DocumentKeySet; + /** + * Updates all local state to match the pending mutations for the given user. + * May be called repeatedly for the same user. + */ + handleCredentialChange?(user: User): Promise; +} + +declare type Resolver = (value?: T) => void; + +/** + * A slash-separated path for navigating resources (documents and collections) + * within Firestore. + * + * @internal + */ +declare class ResourcePath extends BasePath { + protected construct(segments: string[], offset?: number, length?: number): ResourcePath; + canonicalString(): string; + toString(): string; + /** + * Returns a string representation of this path + * where each path segment has been encoded with + * `encodeURIComponent`. + */ + toUriEncodedString(): string; + /** + * Creates a resource path from the given slash-delimited string. If multiple + * arguments are provided, all components are combined. Leading and trailing + * slashes from all components are ignored. + */ + static fromString(...pathComponents: string[]): ResourcePath; + static emptyPath(): ResourcePath; +} + +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ +export declare function runTransaction(firestore: Firestore, updateFunction: (transaction: Transaction) => Promise, options?: TransactionOptions): Promise; + +/** + * Interface to schedule periodic tasks within SDK. + */ +declare interface Scheduler { + readonly started: boolean; + start(): void; + stop(): void; +} + +/** Base interface for the Serializer implementation. */ +declare interface Serializer { + readonly useProto3Json: boolean; +} + +/** + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to + * include a server-generated timestamp in the written data. + */ +export declare function serverTimestamp(): FieldValue; + +declare type ServerTimestampBehavior = 'estimate' | 'previous' | 'none'; + +/** + * Writes to the document referred to by the specified `DocumentReference`. If + * the document does not yet exist, it will be created. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function setDoc(reference: DocumentReference, data: WithFieldValue): Promise; + +/** + * Writes to the document referred to by the specified `DocumentReference`. If + * the document does not yet exist, it will be created. If you provide `merge` + * or `mergeFields`, the provided data can be merged into an existing document. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function setDoc(reference: DocumentReference, data: PartialWithFieldValue, options: SetOptions): Promise; + +/** + * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). + * + * @param logLevel - The verbosity you set for activity and error logging. Can + * be any of the following values: + * + *

    + *
  • `debug` for the most verbose logging level, primarily for + * debugging.
  • + *
  • `error` to log errors only.
  • + *
  • `silent` to turn off logging.
  • + *
+ */ +export declare function setLogLevel(logLevel: LogLevel): void; + +/** + * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link + * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be + * configured to perform granular merges instead of overwriting the target + * documents in their entirety by providing a `SetOptions` with `merge: true`. + * + * @param merge - Changes the behavior of a `setDoc()` call to only replace the + * values specified in its data argument. Fields omitted from the `setDoc()` + * call remain untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace + * the specified field paths. Any field path that is not specified is ignored + * and remains untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + */ +export declare type SetOptions = { + readonly merge?: boolean; +} | { + readonly mergeFields?: Array; +}; + +/** + * Specifies custom configurations for your Cloud Firestore instance. + * You must set these before invoking any other methods. + */ +export declare interface Settings { + /** The hostname to connect to. */ + host?: string; + /** Whether to use SSL when connecting. */ + ssl?: boolean; + /** + * Whether to skip nested properties that are set to `undefined` during + * object serialization. If set to `true`, these properties are skipped + * and not written to Firestore. If set to `false` or omitted, the SDK + * throws an exception when it encounters properties of type `undefined`. + */ + ignoreUndefinedProperties?: boolean; +} + +/** + * A `SharedClientState` keeps track of the global state of the mutations + * and query targets for all active clients with the same persistence key (i.e. + * project ID and FirebaseApp name). It relays local changes to other clients + * and updates its local state as new state is observed. + * + * `SharedClientState` is primarily used for synchronization in Multi-Tab + * environments. Each tab is responsible for registering its active query + * targets and mutations. `SharedClientState` will then notify the listener + * assigned to `.syncEngine` for updates to mutations and queries that + * originated in other clients. + * + * To receive notifications, `.syncEngine` and `.onlineStateHandler` has to be + * assigned before calling `start()`. + */ +declare interface SharedClientState { + onlineStateHandler: ((onlineState: OnlineState) => void) | null; + sequenceNumberHandler: ((sequenceNumber: ListenSequenceNumber) => void) | null; + /** Registers the Mutation Batch ID of a newly pending mutation. */ + addPendingMutation(batchId: BatchId): void; + /** + * Records that a pending mutation has been acknowledged or rejected. + * Called by the primary client to notify secondary clients of mutation + * results as they come back from the backend. + */ + updateMutationState(batchId: BatchId, state: 'acknowledged' | 'rejected', error?: FirestoreError): void; + /** + * Associates a new Query Target ID with the local Firestore client. Returns + * the new query state for the query (which can be 'current' if the query is + * already associated with another tab). + * + * If the target id is already associated with local client, the method simply + * returns its `QueryTargetState`. + */ + addLocalQueryTarget(targetId: TargetId, addToActiveTargetIds?: boolean): QueryTargetState; + /** Removes the Query Target ID association from the local client. */ + removeLocalQueryTarget(targetId: TargetId): void; + /** Checks whether the target is associated with the local client. */ + isLocalQueryTarget(targetId: TargetId): boolean; + /** + * Processes an update to a query target. + * + * Called by the primary client to notify secondary clients of document + * changes or state transitions that affect the provided query target. + */ + updateQueryState(targetId: TargetId, state: QueryTargetState, error?: FirestoreError): void; + /** + * Removes the target's metadata entry. + * + * Called by the primary client when all clients stopped listening to a query + * target. + */ + clearQueryState(targetId: TargetId): void; + /** + * Gets the active Query Targets IDs for all active clients. + * + * The implementation for this may require O(n) runtime, where 'n' is the size + * of the result set. + */ + getAllActiveQueryTargets(): SortedSet; + /** + * Checks whether the provided target ID is currently being listened to by + * any of the active clients. + * + * The implementation may require O(n*log m) runtime, where 'n' is the number + * of clients and 'm' the number of targets. + */ + isActiveQueryTarget(targetId: TargetId): boolean; + /** + * Starts the SharedClientState, reads existing client data and registers + * listeners for updates to new and existing clients. + */ + start(): Promise; + /** Shuts down the `SharedClientState` and its listeners. */ + shutdown(): void; + /** + * Changes the active user and removes all existing user-specific data. The + * user change does not call back into SyncEngine (for example, no mutations + * will be marked as removed). + */ + handleUserChange(user: User, removedBatchIds: BatchId[], addedBatchIds: BatchId[]): void; + /** Changes the shared online state of all clients. */ + setOnlineState(onlineState: OnlineState): void; + writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void; + /** + * Notifies other clients when remote documents have changed due to loading + * a bundle. + * + * @param collectionGroups The collection groups affected by this bundle. + */ + notifyBundleLoaded(collectionGroups: Set): void; +} + +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ +export declare function snapshotEqual(left: DocumentSnapshot | QuerySnapshot, right: DocumentSnapshot | QuerySnapshot): boolean; + +/** + * A version of a document in Firestore. This corresponds to the version + * timestamp, such as update_time or read_time. + */ +declare class SnapshotVersion { + private timestamp; + static fromTimestamp(value: Timestamp): SnapshotVersion; + static min(): SnapshotVersion; + static max(): SnapshotVersion; + private constructor(); + compareTo(other: SnapshotVersion): number; + isEqual(other: SnapshotVersion): boolean; + /** Returns a number representation of the version for use in spec tests. */ + toMicroseconds(): number; + toString(): string; + toTimestamp(): Timestamp; +} + +declare class SortedMap { + comparator: Comparator; + root: LLRBNode | LLRBEmptyNode; + constructor(comparator: Comparator, root?: LLRBNode | LLRBEmptyNode); + insert(key: K, value: V): SortedMap; + remove(key: K): SortedMap; + get(key: K): V | null; + indexOf(key: K): number; + isEmpty(): boolean; + get size(): number; + minKey(): K | null; + maxKey(): K | null; + inorderTraversal(action: (k: K, v: V) => T): T; + forEach(fn: (k: K, v: V) => void): void; + toString(): string; + reverseTraversal(action: (k: K, v: V) => T): T; + getIterator(): SortedMapIterator; + getIteratorFrom(key: K): SortedMapIterator; + getReverseIterator(): SortedMapIterator; + getReverseIteratorFrom(key: K): SortedMapIterator; +} + +declare class SortedMapIterator { + private isReverse; + private nodeStack; + constructor(node: LLRBNode | LLRBEmptyNode, startKey: K | null, comparator: Comparator, isReverse: boolean); + getNext(): Entry; + hasNext(): boolean; + peek(): Entry | null; +} + +/** + * SortedSet is an immutable (copy-on-write) collection that holds elements + * in order specified by the provided comparator. + * + * NOTE: if provided comparator returns 0 for two elements, we consider them to + * be equal! + */ +declare class SortedSet { + private comparator; + private data; + constructor(comparator: (left: T, right: T) => number); + has(elem: T): boolean; + first(): T | null; + last(): T | null; + get size(): number; + indexOf(elem: T): number; + /** Iterates elements in order defined by "comparator" */ + forEach(cb: (elem: T) => void): void; + /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ + forEachInRange(range: [T, T], cb: (elem: T) => void): void; + /** + * Iterates over `elem`s such that: start <= elem until false is returned. + */ + forEachWhile(cb: (elem: T) => boolean, start?: T): void; + /** Finds the least element greater than or equal to `elem`. */ + firstAfterOrEqual(elem: T): T | null; + getIterator(): SortedSetIterator; + getIteratorFrom(key: T): SortedSetIterator; + /** Inserts or updates an element */ + add(elem: T): SortedSet; + /** Deletes an element */ + delete(elem: T): SortedSet; + isEmpty(): boolean; + unionWith(other: SortedSet): SortedSet; + isEqual(other: SortedSet): boolean; + toArray(): T[]; + toString(): string; + private copy; +} + +declare class SortedSetIterator { + private iter; + constructor(iter: SortedMapIterator); + getNext(): T; + hasNext(): boolean; +} + +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided document (exclusive). The starting position is + * relative to the order of the query. The document must contain all of the + * fields provided in the orderBy of the query. + * + * @param snapshot - The snapshot of the document to start after. + * @returns A {@link QueryStartAtConstraint} to pass to `query()` + */ +export declare function startAfter(snapshot: DocumentSnapshot): QueryStartAtConstraint; + +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided fields relative to the order of the query. The order + * of the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to start this query after, in order + * of the query's order by. + * @returns A {@link QueryStartAtConstraint} to pass to `query()` + */ +export declare function startAfter(...fieldValues: unknown[]): QueryStartAtConstraint; + +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided document (inclusive). The starting position is relative + * to the order of the query. The document must contain all of the fields + * provided in the `orderBy` of this query. + * + * @param snapshot - The snapshot of the document to start at. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. + */ +export declare function startAt(snapshot: DocumentSnapshot): QueryStartAtConstraint; + +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to start this query at, in order + * of the query's order by. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. + */ +export declare function startAt(...fieldValues: unknown[]): QueryStartAtConstraint; + +declare type StructuredQuery = firestoreV1ApiClientInterfaces.StructuredQuery; + +/** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ +export declare function sum(field: string | FieldPath): AggregateField; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * SyncEngine is the central controller in the client SDK architecture. It is + * the glue code between the EventManager, LocalStore, and RemoteStore. Some of + * SyncEngine's responsibilities include: + * 1. Coordinating client requests and remote events between the EventManager + * and the local and remote data stores. + * 2. Managing a View object for each query, providing the unified view between + * the local and remote data stores. + * 3. Notifying the RemoteStore when the LocalStore has new mutations in its + * queue that need sending to the backend. + * + * The SyncEngine’s methods should only ever be called by methods running in the + * global async queue. + * + * PORTING NOTE: On Web, SyncEngine does not have an explicit subscribe() + * function. Instead, it directly depends on EventManager's tree-shakeable API + * (via `ensureWatchStream()`). + */ +declare interface SyncEngine { + isPrimaryClient: boolean; +} + +/** + * A Target represents the WatchTarget representation of a Query, which is used + * by the LocalStore and the RemoteStore to keep track of and to execute + * backend queries. While a Query can represent multiple Targets, each Targets + * maps to a single WatchTarget in RemoteStore and a single TargetData entry + * in persistence. + */ +declare interface Target { + readonly path: ResourcePath; + readonly collectionGroup: string | null; + readonly orderBy: OrderBy[]; + readonly filters: Filter[]; + readonly limit: number | null; + readonly startAt: Bound | null; + readonly endAt: Bound | null; +} + +/** + * Represents cached targets received from the remote backend. + * + * The cache is keyed by `Target` and entries in the cache are `TargetData` + * instances. + */ +declare interface TargetCache { + /** + * A global snapshot version representing the last consistent snapshot we + * received from the backend. This is monotonically increasing and any + * snapshots received from the backend prior to this version (e.g. for targets + * resumed with a resume_token) should be suppressed (buffered) until the + * backend has caught up to this snapshot version again. This prevents our + * cache from ever going backwards in time. + * + * This is updated whenever our we get a TargetChange with a read_time and + * empty target_ids. + */ + getLastRemoteSnapshotVersion(transaction: PersistenceTransaction): PersistencePromise; + /** + * @returns The highest sequence number observed, including any that might be + * persisted on-disk. + */ + getHighestSequenceNumber(transaction: PersistenceTransaction): PersistencePromise; + /** + * Call provided function with each `TargetData` that we have cached. + */ + forEachTarget(txn: PersistenceTransaction, f: (q: TargetData) => void): PersistencePromise; + /** + * Set the highest listen sequence number and optionally updates the + * snapshot version of the last consistent snapshot received from the backend + * (see getLastRemoteSnapshotVersion() for more details). + * + * @param highestListenSequenceNumber - The new maximum listen sequence number. + * @param lastRemoteSnapshotVersion - The new snapshot version. Optional. + */ + setTargetsMetadata(transaction: PersistenceTransaction, highestListenSequenceNumber: number, lastRemoteSnapshotVersion?: SnapshotVersion): PersistencePromise; + /** + * Adds an entry in the cache. + * + * The cache key is extracted from `targetData.target`. The key must not already + * exist in the cache. + * + * @param targetData - A TargetData instance to put in the cache. + */ + addTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Updates an entry in the cache. + * + * The cache key is extracted from `targetData.target`. The entry must already + * exist in the cache, and it will be replaced. + * @param targetData - The TargetData to be replaced into the cache. + */ + updateTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Removes the cached entry for the given target data. It is an error to remove + * a target data that does not exist. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * The number of targets currently in the cache. + */ + getTargetCount(transaction: PersistenceTransaction): PersistencePromise; + /** + * Looks up a TargetData entry by target. + * + * @param target - The query target corresponding to the entry to look up. + * @returns The cached TargetData entry, or null if the cache has no entry for + * the target. + */ + getTargetData(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Adds the given document keys to cached query results of the given target + * ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + addMatchingKeys(transaction: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + /** + * Removes the given document keys from the cached query results of the + * given target ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMatchingKeys(transaction: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + /** + * Removes all the keys in the query results of the given target ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMatchingKeysForTargetId(transaction: PersistenceTransaction, targetId: TargetId): PersistencePromise; + /** + * Returns the document keys that match the provided target ID. + */ + getMatchingKeysForTargetId(transaction: PersistenceTransaction, targetId: TargetId): PersistencePromise; + /** + * Returns a new target ID that is higher than any query in the cache. If + * there are no queries in the cache, returns the first valid target ID. + * Allocated target IDs are persisted and `allocateTargetId()` will never + * return the same ID twice. + */ + allocateTargetId(transaction: PersistenceTransaction): PersistencePromise; + containsKey(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; +} + +/** + * A TargetChange specifies the set of changes for a specific target as part of + * a RemoteEvent. These changes track which documents are added, modified or + * removed, as well as the target's resume token and whether the target is + * marked CURRENT. + * The actual changes *to* documents are not part of the TargetChange since + * documents may be part of multiple targets. + */ +declare class TargetChange { + /** + * An opaque, server-assigned token that allows watching a query to be resumed + * after disconnecting without retransmitting all the data that matches the + * query. The resume token essentially identifies a point in time from which + * the server should resume sending results. + */ + readonly resumeToken: ByteString; + /** + * The "current" (synced) status of this target. Note that "current" + * has special meaning in the RPC protocol that implies that a target is + * both up-to-date and consistent with the rest of the watch stream. + */ + readonly current: boolean; + /** + * The set of documents that were newly assigned to this target as part of + * this remote event. + */ + readonly addedDocuments: DocumentKeySet; + /** + * The set of documents that were already assigned to this target but received + * an update during this remote event. + */ + readonly modifiedDocuments: DocumentKeySet; + /** + * The set of documents that were removed from this target as part of this + * remote event. + */ + readonly removedDocuments: DocumentKeySet; + constructor( + /** + * An opaque, server-assigned token that allows watching a query to be resumed + * after disconnecting without retransmitting all the data that matches the + * query. The resume token essentially identifies a point in time from which + * the server should resume sending results. + */ + resumeToken: ByteString, + /** + * The "current" (synced) status of this target. Note that "current" + * has special meaning in the RPC protocol that implies that a target is + * both up-to-date and consistent with the rest of the watch stream. + */ + current: boolean, + /** + * The set of documents that were newly assigned to this target as part of + * this remote event. + */ + addedDocuments: DocumentKeySet, + /** + * The set of documents that were already assigned to this target but received + * an update during this remote event. + */ + modifiedDocuments: DocumentKeySet, + /** + * The set of documents that were removed from this target as part of this + * remote event. + */ + removedDocuments: DocumentKeySet); + /** + * This method is used to create a synthesized TargetChanges that can be used to + * apply a CURRENT status change to a View (for queries executed in a different + * tab) or for new queries (to raise snapshots with correct CURRENT status). + */ + static createSynthesizedTargetChangeForCurrentChange(targetId: TargetId, current: boolean, resumeToken: ByteString): TargetChange; +} + +declare type TargetChangeTargetChangeType = 'NO_CHANGE' | 'ADD' | 'REMOVE' | 'CURRENT' | 'RESET'; + +/** + * An immutable set of metadata that the local store tracks for each target. + */ +declare class TargetData { + /** The target being listened to. */ + readonly target: Target; + /** + * The target ID to which the target corresponds; Assigned by the + * LocalStore for user listens and by the SyncEngine for limbo watches. + */ + readonly targetId: TargetId; + /** The purpose of the target. */ + readonly purpose: TargetPurpose; + /** + * The sequence number of the last transaction during which this target data + * was modified. + */ + readonly sequenceNumber: ListenSequenceNumber; + /** The latest snapshot version seen for this target. */ + readonly snapshotVersion: SnapshotVersion; + /** + * The maximum snapshot version at which the associated view + * contained no limbo documents. + */ + readonly lastLimboFreeSnapshotVersion: SnapshotVersion; + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + readonly resumeToken: ByteString; + /** + * The number of documents that last matched the query at the resume token or + * read time. Documents are counted only when making a listen request with + * resume token or read time, otherwise, keep it null. + */ + readonly expectedCount: number | null; + constructor( + /** The target being listened to. */ + target: Target, + /** + * The target ID to which the target corresponds; Assigned by the + * LocalStore for user listens and by the SyncEngine for limbo watches. + */ + targetId: TargetId, + /** The purpose of the target. */ + purpose: TargetPurpose, + /** + * The sequence number of the last transaction during which this target data + * was modified. + */ + sequenceNumber: ListenSequenceNumber, + /** The latest snapshot version seen for this target. */ + snapshotVersion?: SnapshotVersion, + /** + * The maximum snapshot version at which the associated view + * contained no limbo documents. + */ + lastLimboFreeSnapshotVersion?: SnapshotVersion, + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + resumeToken?: ByteString, + /** + * The number of documents that last matched the query at the resume token or + * read time. Documents are counted only when making a listen request with + * resume token or read time, otherwise, keep it null. + */ + expectedCount?: number | null); + /** Creates a new target data instance with an updated sequence number. */ + withSequenceNumber(sequenceNumber: number): TargetData; + /** + * Creates a new target data instance with an updated resume token and + * snapshot version. + */ + withResumeToken(resumeToken: ByteString, snapshotVersion: SnapshotVersion): TargetData; + /** + * Creates a new target data instance with an updated expected count. + */ + withExpectedCount(expectedCount: number): TargetData; + /** + * Creates a new target data instance with an updated last limbo free + * snapshot version number. + */ + withLastLimboFreeSnapshotVersion(lastLimboFreeSnapshotVersion: SnapshotVersion): TargetData; +} + +/** + * A locally-assigned ID used to refer to a target being watched via the + * Watch service. + */ +declare type TargetId = number; + +/** An enumeration of the different purposes we have for targets. */ +declare const enum TargetPurpose { + /** A regular, normal query target. */ + Listen = "TargetPurposeListen", + /** + * The query target was used to refill a query after an existence filter + * mismatch. + */ + ExistenceFilterMismatch = "TargetPurposeExistenceFilterMismatch", + /** + * The query target was used if the query is the result of a false positive in + * the bloom filter. + */ + ExistenceFilterMismatchBloom = "TargetPurposeExistenceFilterMismatchBloom", + /** The query target was used to resolve a limbo document. */ + LimboResolution = "TargetPurposeLimboResolution" +} + +/** + * Terminates the provided `Firestore` instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` functions + * may be used. Any other function will throw a `FirestoreError`. Termination + * does not cancel any pending writes, and any promises that are awaiting a + * response from the server will not be resolved. + * + * To restart after termination, create a new instance of `Firestore` with + * {@link (getFirestore:1)}. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all of + * its resources or in combination with {@link clearIndexedDbPersistence} to + * ensure that all local state is destroyed between test runs. + * + * @param firestore - The `Firestore` instance to terminate. + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ +export declare function terminate(firestore: Firestore): Promise; + +/** + * Wellknown "timer" IDs used when scheduling delayed operations on the + * AsyncQueue. These IDs can then be used from tests to check for the presence + * of operations or to run them early. + * + * The string values are used when encoding these timer IDs in JSON spec tests. + */ +declare const enum TimerId { + /** All can be used with runDelayedOperationsEarly() to run all timers. */ + All = "all", + /** + * The following 5 timers are used in persistent_stream.ts for the listen and + * write streams. The "Idle" timer is used to close the stream due to + * inactivity. The "ConnectionBackoff" timer is used to restart a stream once + * the appropriate backoff delay has elapsed. The health check is used to mark + * a stream healthy if it has not received an error during its initial setup. + */ + ListenStreamIdle = "listen_stream_idle", + ListenStreamConnectionBackoff = "listen_stream_connection_backoff", + WriteStreamIdle = "write_stream_idle", + WriteStreamConnectionBackoff = "write_stream_connection_backoff", + HealthCheckTimeout = "health_check_timeout", + /** + * A timer used in online_state_tracker.ts to transition from + * OnlineState.Unknown to Offline after a set timeout, rather than waiting + * indefinitely for success or failure. + */ + OnlineStateTimeout = "online_state_timeout", + /** + * A timer used to update the client metadata in IndexedDb, which is used + * to determine the primary leaseholder. + */ + ClientMetadataRefresh = "client_metadata_refresh", + /** A timer used to periodically attempt LRU Garbage collection */ + LruGarbageCollection = "lru_garbage_collection", + /** + * A timer used to retry transactions. Since there can be multiple concurrent + * transactions, multiple of these may be in the queue at a given time. + */ + TransactionRetry = "transaction_retry", + /** + * A timer used to retry operations scheduled via retryable AsyncQueue + * operations. + */ + AsyncQueueRetry = "async_queue_retry", + /** + * A timer used to periodically attempt index backfill. + */ + IndexBackfill = "index_backfill" +} + +/** + * A `Timestamp` represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. + * + * It is encoded using the Proleptic Gregorian Calendar which extends the + * Gregorian calendar backwards to year one. It is encoded assuming all minutes + * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59.999999999Z. + * + * For examples and further specifications, refer to the + * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. + */ +export declare class Timestamp { + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + readonly seconds: number; + /** + * The fractions of a second at nanosecond resolution.* + */ + readonly nanoseconds: number; + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns a new timestamp representing the current date. + */ + static now(): Timestamp; + /** + * Creates a new timestamp from the given date. + * + * @param date - The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the given + * date. + */ + static fromDate(date: Date): Timestamp; + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds - Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the given + * number of milliseconds. + */ + static fromMillis(milliseconds: number): Timestamp; + /** + * Creates a new timestamp. + * + * @param seconds - The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds - The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ + constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + seconds: number, + /** + * The fractions of a second at nanosecond resolution.* + */ + nanoseconds: number); + /** + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ + toDate(): Date; + /** + * Converts a `Timestamp` to a numeric timestamp (in milliseconds since + * epoch). This operation causes a loss of precision. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ + toMillis(): number; + _compareTo(other: Timestamp): number; + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other - The `Timestamp` to compare against. + * @returns true if this `Timestamp` is equal to the provided one. + */ + isEqual(other: Timestamp): boolean; + /** Returns a textual representation of this `Timestamp`. */ + toString(): string; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + seconds: Property<"number">; + nanoseconds: Property<"number">; + }; + /** + * Returns a JSON-serializable representation of this `Timestamp`. + */ + toJSON(): { + seconds: number; + nanoseconds: number; + type: string; + }; + /** + * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}. + */ + static fromJSON(json: object): Timestamp; + /** + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. + */ + valueOf(): string; +} + +declare type Timestamp_2 = string | { + seconds?: string | number; + nanos?: number; +}; + +declare interface Token { + /** Type of token. */ + type: TokenType; + /** + * The user with which the token is associated (used for persisting user + * state on disk, etc.). + * This will be null for Tokens of the type 'AppCheck'. + */ + user?: User; + /** Header values to set for this token */ + headers: Map; +} + +declare type TokenType = 'OAuth' | 'FirstParty' | 'AppCheck'; + +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ +export declare class Transaction { + protected readonly _firestore: Firestore; + private readonly _transaction; + private readonly _dataReader; + /** @hideconstructor */ + constructor(_firestore: Firestore, _transaction: Transaction_2); + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ + get(documentRef: DocumentReference): Promise>; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: WithFieldValue): this; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * If you provide `merge` or `mergeFields`, the provided data can be merged + * into an existing document. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: PartialWithFieldValue, options: SetOptions): this; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * @param documentRef - A reference to the document to be updated. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, data: UpdateData): this; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * @param documentRef - A reference to the document to be updated. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key/value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): this; + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + delete(documentRef: DocumentReference): this; +} + +/** + * Internal transaction object responsible for accumulating the mutations to + * perform and the base versions for any documents read. + */ +declare class Transaction_2 { + private datastore; + private readVersions; + private mutations; + private committed; + /** + * A deferred usage error that occurred previously in this transaction that + * will cause the transaction to fail once it actually commits. + */ + private lastTransactionError; + /** + * Set of documents that have been written in the transaction. + * + * When there's more than one write to the same key in a transaction, any + * writes after the first are handled differently. + */ + private writtenDocs; + constructor(datastore: Datastore); + lookup(keys: DocumentKey[]): Promise; + set(key: DocumentKey, data: ParsedSetData): void; + update(key: DocumentKey, data: ParsedUpdateData): void; + delete(key: DocumentKey): void; + commit(): Promise; + private recordVersion; + /** + * Returns the version of this document when it was read in this transaction, + * as a precondition, or no precondition if it was not read. + */ + private precondition; + /** + * Returns the precondition for a document if the operation is an update. + */ + private preconditionForUpdate; + private write; + private ensureCommitNotCalled; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options to customize transaction behavior. + */ +export declare interface TransactionOptions { + /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */ + readonly maxAttempts?: number; +} + +/** Used to represent a field transform on a mutation. */ +declare class TransformOperation { + private _; +} + +/** + * An association of JsonTypeDesc values to their native types. + * @private + * @internal + */ +declare type TSType = T extends 'object' ? object : T extends 'string' ? string : T extends 'number' ? number : T extends 'boolean' ? boolean : T extends 'null' ? null : T extends 'undefined' ? undefined : never; + +declare type UnaryFilterOp = 'OPERATOR_UNSPECIFIED' | 'IS_NAN' | 'IS_NULL' | 'IS_NOT_NAN' | 'IS_NOT_NULL'; + +/** + * Given a union type `U = T1 | T2 | ...`, returns an intersected type + * `(T1 & T2 & ...)`. + * + * Uses distributive conditional types and inference from conditional types. + * This works because multiple candidates for the same type variable in + * contra-variant positions causes an intersection type to be inferred. + * https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-inference-in-conditional-types + * https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type + */ +export declare type UnionToIntersection = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never; + +/** + * An untyped Firestore Data Converter interface that is shared between the + * lite, firestore-exp and classic SDK. + */ +declare interface UntypedFirestoreDataConverter { + toFirestore(modelObject: WithFieldValue): WithFieldValue; + toFirestore(modelObject: PartialWithFieldValue, options: SetOptions_2): PartialWithFieldValue; + fromFirestore(snapshot: unknown, options?: unknown): AppModelType; +} + +/** + * Update data (for use with {@link (updateDoc:1)}) that consists of field paths + * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots + * reference nested fields within the document. FieldValues can be passed in + * as property values. + */ +export declare type UpdateData = T extends Primitive ? T : T extends {} ? { + [K in keyof T]?: UpdateData | FieldValue; +} & NestedUpdateFields : Partial; + +/** + * Updates fields in the document referred to by the specified + * `DocumentReference`. The update will fail if applied to a document that does + * not exist. + * + * The result of this update will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * update fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to update. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function updateDoc(reference: DocumentReference, data: UpdateData): Promise; + +/** + * Updates fields in the document referred to by the specified + * `DocumentReference` The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * The result of this update will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * update fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to update. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function updateDoc(reference: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): Promise; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Simple wrapper around a nullable UID. Mostly exists to make code more + * readable. + */ +declare class User { + readonly uid: string | null; + /** A user with a null UID. */ + static readonly UNAUTHENTICATED: User; + static readonly GOOGLE_CREDENTIALS: User; + static readonly FIRST_PARTY: User; + static readonly MOCK_USER: User; + constructor(uid: string | null); + isAuthenticated(): boolean; + /** + * Returns a key representing this user, suitable for inclusion in a + * dictionary. + */ + toKey(): string; + isEqual(otherUser: User): boolean; +} + +declare type Value = firestoreV1ApiClientInterfaces.Value; + +declare type ValueNullValue = 'NULL_VALUE'; + +/** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ +export declare function vector(values?: number[]): VectorValue; + +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link vector}. + * + * @class VectorValue + */ +export declare class VectorValue { + private readonly _values; + /** + * @private + * @internal + */ + constructor(values: number[] | undefined); + /** + * Returns a copy of the raw number array form of the vector. + */ + toArray(): number[]; + /** + * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise. + */ + isEqual(other: VectorValue): boolean; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + vectorValues: Property<"object">; + }; + /** + * Returns a JSON-serializable representation of this `VectorValue` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}. + * + * @param json a JSON object represention of a `VectorValue` instance. + * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): VectorValue; +} + +declare class ViewSnapshot { + readonly query: Query_2; + readonly docs: DocumentSet; + readonly oldDocs: DocumentSet; + readonly docChanges: DocumentViewChange[]; + readonly mutatedKeys: DocumentKeySet; + readonly fromCache: boolean; + readonly syncStateChanged: boolean; + readonly excludesMetadataChanges: boolean; + readonly hasCachedResults: boolean; + constructor(query: Query_2, docs: DocumentSet, oldDocs: DocumentSet, docChanges: DocumentViewChange[], mutatedKeys: DocumentKeySet, fromCache: boolean, syncStateChanged: boolean, excludesMetadataChanges: boolean, hasCachedResults: boolean); + /** Returns a view snapshot as if all documents in the snapshot were added. */ + static fromInitialDocuments(query: Query_2, documents: DocumentSet, mutatedKeys: DocumentKeySet, fromCache: boolean, hasCachedResults: boolean): ViewSnapshot; + get hasPendingWrites(): boolean; + isEqual(other: ViewSnapshot): boolean; +} + +/** + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. + * + * @param fieldPath - The path to compare + * @param opStr - The operation string (e.g "<", "<=", "==", "<", + * "<=", "!="). + * @param value - The value for comparison + * @returns The created {@link QueryFieldFilterConstraint}. + */ +export declare function where(fieldPath: string | FieldPath, opStr: WhereFilterOp, value: unknown): QueryFieldFilterConstraint; + +/** + * Filter conditions in a {@link where} clause are specified using the + * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in', + * 'array-contains-any', and 'not-in'. + */ +export declare type WhereFilterOp = '<' | '<=' | '==' | '!=' | '>=' | '>' | 'array-contains' | 'in' | 'array-contains-any' | 'not-in'; + +/** + * Allows FieldValues to be passed in as a property value while maintaining + * type safety. + */ +export declare type WithFieldValue = T | (T extends Primitive ? T : T extends {} ? { + [K in keyof T]: WithFieldValue | FieldValue; +} : never); + +/** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It + * provides methods for adding writes to the write batch. None of the writes + * will be committed (or visible locally) until {@link WriteBatch.commit} is + * called. + */ +export declare class WriteBatch { + private readonly _firestore; + private readonly _commitHandler; + private readonly _dataReader; + private _mutations; + private _committed; + /** @hideconstructor */ + constructor(_firestore: Firestore, _commitHandler: (m: Mutation[]) => Promise); + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: WithFieldValue): WriteBatch; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * If you provide `merge` or `mergeFields`, the provided data can be merged + * into an existing document. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: PartialWithFieldValue, options: SetOptions): WriteBatch; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * @param documentRef - A reference to the document to be updated. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, data: UpdateData): WriteBatch; + /** + * Updates fields in the document referred to by this {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be update by providing dot-separated field path strings + * or by providing `FieldPath` objects. + * + * @param documentRef - A reference to the document to be updated. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): WriteBatch; + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + delete(documentRef: DocumentReference): WriteBatch; + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `Promise` resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit (note that it won't + * resolve while you're offline). + */ + commit(): Promise; + private _verifyNotCommitted; +} + +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single WriteBatch + * is 500. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `WriteBatch` that can be used to atomically execute multiple + * writes. + */ +export declare function writeBatch(firestore: Firestore): WriteBatch; + +export { } diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/private.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/private.d.ts new file mode 100644 index 0000000..bae2be6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/private.d.ts @@ -0,0 +1,5939 @@ +/** + * Firestore Lite + * + * @remarks Firestore Lite is a small online-only SDK that allows read + * and write access to your Firestore database. All operations connect + * directly to the backend, and `onSnapshot()` APIs are not supported. + * @packageDocumentation + */ + +import { DocumentData as DocumentData_2 } from '@firebase/firestore-types'; +import { EmulatorMockTokenOptions } from '@firebase/util'; +import { FirebaseApp } from '@firebase/app'; +import { FirebaseError } from '@firebase/util'; +import { LogLevelString as LogLevel } from '@firebase/logger'; +import { SetOptions as SetOptions_2 } from '@firebase/firestore-types'; + +/* Excluded from this release type: AbstractUserDataWriter */ + +/** + * Describes a map whose keys are active target ids. We do not care about the type of the + * values. + */ +declare type ActiveTargets = SortedMap; + +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend. + */ +export declare function addDoc(reference: CollectionReference, data: WithFieldValue): Promise>; + +/** + * Returns a new map where every key is prefixed with the outer key appended + * to a dot. + */ +export declare type AddPrefixToKeys> = { + [K in keyof T & string as `${Prefix}.${K}`]+?: string extends K ? any : T[K]; +}; + +/** + * Represents an aggregation that can be performed by Firestore. + */ +export declare class AggregateField { + readonly _internalFieldPath?: FieldPath_2 | undefined; + /** A type string to uniquely identify instances of this class. */ + readonly type = "AggregateField"; + /** Indicates the aggregation operation of this AggregateField. */ + readonly aggregateType: AggregateType; + /* Excluded from this release type: __constructor */ +} + +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ +export declare function aggregateFieldEqual(left: AggregateField, right: AggregateField): boolean; + +/** + * The union of all `AggregateField` types that are supported by Firestore. + */ +export declare type AggregateFieldType = ReturnType | ReturnType | ReturnType; + +/** + * The results of executing an aggregation query. + */ +export declare class AggregateQuerySnapshot { + private readonly _userDataWriter; + private readonly _data; + /** A type string to uniquely identify instances of this class. */ + readonly type = "AggregateQuerySnapshot"; + /** + * The underlying query over which the aggregations recorded in this + * `AggregateQuerySnapshot` were performed. + */ + readonly query: Query; + /** @hideconstructor */ + constructor(query: Query, _userDataWriter: AbstractUserDataWriter, _data: ApiClientObjectMap); + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ + data(): AggregateSpecData; +} + +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ +export declare function aggregateQuerySnapshotEqual(left: AggregateQuerySnapshot, right: AggregateQuerySnapshot): boolean; + +/** + * Specifies a set of aggregations and their aliases. + */ +export declare interface AggregateSpec { + [field: string]: AggregateFieldType; +} + +/** + * A type whose keys are taken from an `AggregateSpec`, and whose values are the + * result of the aggregation performed by the corresponding `AggregateField` + * from the input `AggregateSpec`. + */ +export declare type AggregateSpecData = { + [P in keyof T]: T[P] extends AggregateField ? U : never; +}; + +/** + * Union type representing the aggregate type to be performed. + */ +export declare type AggregateType = 'count' | 'avg' | 'sum'; + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +export declare function and(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; + +declare interface ApiClientObjectMap { + [k: string]: T; +} + +/** + * An `AppliableConstraint` is an abstraction of a constraint that can be applied + * to a Firestore query. + */ +declare abstract class AppliableConstraint { + /** + * Takes the provided {@link Query} and returns a copy of the {@link Query} with this + * {@link AppliableConstraint} applied. + */ + abstract _apply(query: Query): Query; +} + +/** + * Returns a special value that can be used with {@link (setDoc:1)} or {@link + * updateDoc:1} that tells the server to remove the given elements from any + * array value that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is not + * already an array it will be overwritten with an empty array. + * + * @param elements - The elements to remove from the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +export declare function arrayRemove(...elements: unknown[]): FieldValue; + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array + * value that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements - The elements to union into the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()`. + */ +export declare function arrayUnion(...elements: unknown[]): FieldValue; + +declare interface AsyncQueue { + readonly isShuttingDown: boolean; + /** + * Adds a new operation to the queue without waiting for it to complete (i.e. + * we ignore the Promise result). + */ + enqueueAndForget(op: () => Promise): void; + /** + * Regardless if the queue has initialized shutdown, adds a new operation to the + * queue without waiting for it to complete (i.e. we ignore the Promise result). + */ + enqueueAndForgetEvenWhileRestricted(op: () => Promise): void; + /** + * Initialize the shutdown of this queue. Once this method is called, the + * only possible way to request running an operation is through + * `enqueueEvenWhileRestricted()`. + * + * @param purgeExistingTasks Whether already enqueued tasked should be + * rejected (unless enqueued with `enqueueEvenWhileRestricted()`). Defaults + * to false. + */ + enterRestrictedMode(purgeExistingTasks?: boolean): void; + /** + * Adds a new operation to the queue. Returns a promise that will be resolved + * when the promise returned by the new operation is (with its value). + */ + enqueue(op: () => Promise): Promise; + /** + * Enqueue a retryable operation. + * + * A retryable operation is rescheduled with backoff if it fails with a + * IndexedDbTransactionError (the error type used by SimpleDb). All + * retryable operations are executed in order and only run if all prior + * operations were retried successfully. + */ + enqueueRetryable(op: () => Promise): void; + /** + * Schedules an operation to be queued on the AsyncQueue once the specified + * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel + * or fast-forward the operation prior to its running. + */ + enqueueAfterDelay(timerId: TimerId, delayMs: number, op: () => Promise): DelayedOperation; + /** + * Verifies there's an operation currently in-progress on the AsyncQueue. + * Unfortunately we can't verify that the running code is in the promise chain + * of that operation, so this isn't a foolproof check, but it should be enough + * to catch some bugs. + */ + verifyOperationInProgress(): void; +} + +/* Excluded from this release type: AuthTokenFactory */ + +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ +export declare function average(field: string | FieldPath): AggregateField; + +/** + * Path represents an ordered sequence of string segments. + */ +declare abstract class BasePath> { + private segments; + private offset; + private len; + constructor(segments: string[], offset?: number, length?: number); + /** + * Abstract constructor method to construct an instance of B with the given + * parameters. + */ + protected abstract construct(segments: string[], offset?: number, length?: number): B; + /** + * Returns a String representation. + * + * Implementing classes are required to provide deterministic implementations as + * the String representation is used to obtain canonical Query IDs. + */ + abstract toString(): string; + get length(): number; + isEqual(other: B): boolean; + child(nameOrPath: string | B): B; + /** The index of one past the last segment of the path. */ + private limit; + popFirst(size?: number): B; + popLast(): B; + firstSegment(): string; + lastSegment(): string; + get(index: number): string; + isEmpty(): boolean; + isPrefixOf(other: this): boolean; + isImmediateParentOf(potentialChild: this): boolean; + forEach(fn: (segment: string) => void): void; + toArray(): string[]; + /** + * Compare 2 paths segment by segment, prioritizing numeric IDs + * (e.g., "__id123__") in numeric ascending order, followed by string + * segments in lexicographical order. + */ + static comparator>(p1: BasePath, p2: BasePath): number; + private static compareSegments; + private static isNumericId; + private static extractNumericId; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * BatchID is a locally assigned ID for a batch of mutations that have been + * applied. + */ +declare type BatchId = number; + +/** + * Represents a bound of a query. + * + * The bound is specified with the given components representing a position and + * whether it's just before or just after the position (relative to whatever the + * query order is). + * + * The position represents a logical index position for a query. It's a prefix + * of values for the (potentially implicit) order by clauses of a query. + * + * Bound provides a function to determine whether a document comes before or + * after a bound. This is influenced by whether the position is just before or + * just after the provided values. + */ +declare class Bound { + readonly position: Value[]; + readonly inclusive: boolean; + constructor(position: Value[], inclusive: boolean); +} + +/** + * Provides interfaces to save and read Firestore bundles. + */ +declare interface BundleCache { + /** + * Gets the saved `BundleMetadata` for a given `bundleId`, returns undefined + * if no bundle metadata is found under the given id. + */ + getBundleMetadata(transaction: PersistenceTransaction, bundleId: string): PersistencePromise; + /** + * Saves a `BundleMetadata` from a bundle into local storage, using its id as + * the persistent key. + */ + saveBundleMetadata(transaction: PersistenceTransaction, metadata: BundleMetadata_2): PersistencePromise; + /** + * Gets a saved `NamedQuery` for the given query name. Returns undefined if + * no queries are found under the given name. + */ + getNamedQuery(transaction: PersistenceTransaction, queryName: string): PersistencePromise; + /** + * Saves a `NamedQuery` from a bundle, using its name as the persistent key. + */ + saveNamedQuery(transaction: PersistenceTransaction, query: NamedQuery_2): PersistencePromise; +} + +/** Properties of a BundledQuery. */ +declare interface BundledQuery { + /** BundledQuery parent */ + parent?: string | null; + /** BundledQuery structuredQuery */ + structuredQuery?: StructuredQuery | null; + /** BundledQuery limitType */ + limitType?: LimitType_2 | null; +} + +/** + * Represents a Firestore bundle saved by the SDK in its local storage. + */ +declare interface BundleMetadata { + /** + * Id of the bundle. It is used together with `createTime` to determine if a + * bundle has been loaded by the SDK. + */ + readonly id: string; + /** Schema version of the bundle. */ + readonly version: number; + /** + * Set to the snapshot version of the bundle if created by the Server SDKs. + * Otherwise set to SnapshotVersion.MIN. + */ + readonly createTime: SnapshotVersion; +} + +/** Properties of a BundleMetadata. */ +declare interface BundleMetadata_2 { + /** BundleMetadata id */ + id?: string | null; + /** BundleMetadata createTime */ + createTime?: Timestamp_2 | null; + /** BundleMetadata version */ + version?: number | null; + /** BundleMetadata totalDocuments */ + totalDocuments?: number | null; + /** BundleMetadata totalBytes */ + totalBytes?: number | null; +} + +/** + * An immutable object representing an array of bytes. + */ +export declare class Bytes { + _byteString: ByteString; + /** @hideconstructor */ + constructor(byteString: ByteString); + /** + * Creates a new `Bytes` object from the given Base64 string, converting it to + * bytes. + * + * @param base64 - The Base64 string used to create the `Bytes` object. + */ + static fromBase64String(base64: string): Bytes; + /** + * Creates a new `Bytes` object from the given Uint8Array. + * + * @param array - The Uint8Array used to create the `Bytes` object. + */ + static fromUint8Array(array: Uint8Array): Bytes; + /** + * Returns the underlying bytes as a Base64-encoded string. + * + * @returns The Base64-encoded string created from the `Bytes` object. + */ + toBase64(): string; + /** + * Returns the underlying bytes in a new `Uint8Array`. + * + * @returns The Uint8Array created from the `Bytes` object. + */ + toUint8Array(): Uint8Array; + /** + * Returns a string representation of the `Bytes` object. + * + * @returns A string representation of the `Bytes` object. + */ + toString(): string; + /** + * Returns true if this `Bytes` object is equal to the provided one. + * + * @param other - The `Bytes` object to compare against. + * @returns true if this `Bytes` object is equal to the provided one. + */ + isEqual(other: Bytes): boolean; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + bytes: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `Bytes` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}. + * + * @param json a JSON object represention of a `Bytes` instance + * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): Bytes; +} + +/* Excluded from this release type: ByteString */ + +declare const enum ChangeType { + Added = 0, + Removed = 1, + Modified = 2, + Metadata = 3 +} + +/** + * Helper for calculating the nested fields for a given type T1. This is needed + * to distribute union types such as `undefined | {...}` (happens for optional + * props) or `{a: A} | {b: B}`. + * + * In this use case, `V` is used to distribute the union types of `T[K]` on + * `Record`, since `T[K]` is evaluated as an expression and not distributed. + * + * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types + */ +export declare type ChildUpdateFields = V extends Record ? AddPrefixToKeys> : never; + +/** + * A randomly-generated key assigned to each Firestore instance at startup. + */ +declare type ClientId = string; + +/** + * Gets a `CollectionReference` instance that refers to the collection at + * the specified absolute path. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments to apply relative to the first + * argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(firestore: Firestore, path: string, ...pathSegments: string[]): CollectionReference; + +/** + * Gets a `CollectionReference` instance that refers to a subcollection of + * `reference` at the specified relative path. + * + * @param reference - A reference to a collection. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments to apply relative to the first + * argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(reference: CollectionReference, path: string, ...pathSegments: string[]): CollectionReference; + +/** + * Gets a `CollectionReference` instance that refers to a subcollection of + * `reference` at the specified relative path. + * + * @param reference - A reference to a Firestore document. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(reference: DocumentReference, path: string, ...pathSegments: string[]): CollectionReference; + +/** + * Creates and returns a new `Query` instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given `collectionId`. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param collectionId - Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `Query`. + */ +export declare function collectionGroup(firestore: Firestore, collectionId: string): Query; + +/** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using {@link (query:1)}). + */ +export declare class CollectionReference extends Query { + readonly _path: ResourcePath; + /** The type of this Firestore reference. */ + readonly type = "collection"; + /** @hideconstructor */ + constructor(firestore: Firestore, converter: FirestoreDataConverter | null, _path: ResourcePath); + /** The collection's identifier. */ + get id(): string; + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ + get path(): string; + /** + * A reference to the containing `DocumentReference` if this is a + * subcollection. If this isn't a subcollection, the reference is null. + */ + get parent(): DocumentReference | null; + /** + * Applies a custom data converter to this `CollectionReference`, allowing you + * to use your own custom model objects with Firestore. When you call {@link + * addDoc} with the returned `CollectionReference` instance, the provided + * converter will convert between Firestore data of type `NewDbModelType` and + * your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `CollectionReference` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter): CollectionReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `CollectionReference` that does not + * use a converter. + */ + withConverter(converter: null): CollectionReference; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +declare type Comparator = (key1: K, key2: K) => number; + +declare interface ComponentConfiguration { + asyncQueue: AsyncQueue; + databaseInfo: DatabaseInfo; + authCredentials: CredentialsProvider; + appCheckCredentials: CredentialsProvider; + clientId: ClientId; + initialUser: User; + maxConcurrentLimboResolutions: number; +} + +declare type CompositeFilterOp = 'OPERATOR_UNSPECIFIED' | 'AND' | 'OR'; + +declare const enum CompositeOperator { + OR = "or", + AND = "and" +} + +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ +export declare function connectFirestoreEmulator(firestore: Firestore, host: string, port: number, options?: { + mockUserToken?: EmulatorMockTokenOptions | string; +}): void; + +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ +export declare function count(): AggregateField; + +/** + * A Listener for credential change events. The listener should fetch a new + * token and may need to invalidate other state if the current user has also + * changed. + */ +declare type CredentialChangeListener = (credential: T) => Promise; + +/** + * Provides methods for getting the uid and token for the current user and + * listening for changes. + */ +declare interface CredentialsProvider { + /** + * Starts the credentials provider and specifies a listener to be notified of + * credential changes (sign-in / sign-out, token changes). It is immediately + * called once with the initial user. + * + * The change listener is invoked on the provided AsyncQueue. + */ + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + /** Requests a token for the current user. */ + getToken(): Promise; + /** + * Marks the last retrieved token as invalid, making the next GetToken request + * force-refresh the token. + */ + invalidateToken(): void; + shutdown(): void; +} + +/** Settings for private credentials */ +declare type CredentialsSettings = FirstPartyCredentialsSettings | ProviderCredentialsSettings; + +/* Excluded from this release type: DatabaseId */ + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +declare class DatabaseInfo { + readonly databaseId: DatabaseId; + readonly appId: string; + readonly persistenceKey: string; + readonly host: string; + readonly ssl: boolean; + readonly forceLongPolling: boolean; + readonly autoDetectLongPolling: boolean; + readonly longPollingOptions: ExperimentalLongPollingOptions; + readonly useFetchStreams: boolean; + readonly isUsingEmulator: boolean; + /** + * Constructs a DatabaseInfo using the provided host, databaseId and + * persistenceKey. + * + * @param databaseId - The database to use. + * @param appId - The Firebase App Id. + * @param persistenceKey - A unique identifier for this Firestore's local + * storage (used in conjunction with the databaseId). + * @param host - The Firestore backend host to connect to. + * @param ssl - Whether to use SSL when connecting. + * @param forceLongPolling - Whether to use the forceLongPolling option + * when using WebChannel as the network transport. + * @param autoDetectLongPolling - Whether to use the detectBufferingProxy + * option when using WebChannel as the network transport. + * @param longPollingOptions Options that configure long-polling. + * @param useFetchStreams Whether to use the Fetch API instead of + * XMLHTTPRequest + */ + constructor(databaseId: DatabaseId, appId: string, persistenceKey: string, host: string, ssl: boolean, forceLongPolling: boolean, autoDetectLongPolling: boolean, longPollingOptions: ExperimentalLongPollingOptions, useFetchStreams: boolean, isUsingEmulator: boolean); +} + +/** + * Datastore and its related methods are a wrapper around the external Google + * Cloud Datastore grpc API, which provides an interface that is more convenient + * for the rest of the client SDK architecture to consume. + */ +declare abstract class Datastore { + abstract terminate(): void; + abstract serializer: JsonProtoSerializer; +} + +/** + * Represents an operation scheduled to be run in the future on an AsyncQueue. + * + * It is created via DelayedOperation.createAndSchedule(). + * + * Supports cancellation (via cancel()) and early execution (via skipDelay()). + * + * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type + * in newer versions of TypeScript defines `finally`, which is not available in + * IE. + */ +declare class DelayedOperation implements PromiseLike { + private readonly asyncQueue; + readonly timerId: TimerId; + readonly targetTimeMs: number; + private readonly op; + private readonly removalCallback; + private timerHandle; + private readonly deferred; + private constructor(); + get promise(): Promise; + /** + * Creates and returns a DelayedOperation that has been scheduled to be + * executed on the provided asyncQueue after the provided delayMs. + * + * @param asyncQueue - The queue to schedule the operation on. + * @param id - A Timer ID identifying the type of operation this is. + * @param delayMs - The delay (ms) before the operation should be scheduled. + * @param op - The operation to run. + * @param removalCallback - A callback to be called synchronously once the + * operation is executed or canceled, notifying the AsyncQueue to remove it + * from its delayedOperations list. + * PORTING NOTE: This exists to prevent making removeDelayedOperation() and + * the DelayedOperation class public. + */ + static createAndSchedule(asyncQueue: AsyncQueue, timerId: TimerId, delayMs: number, op: () => Promise, removalCallback: (op: DelayedOperation) => void): DelayedOperation; + /** + * Starts the timer. This is called immediately after construction by + * createAndSchedule(). + */ + private start; + /** + * Queues the operation to run immediately (if it hasn't already been run or + * canceled). + */ + skipDelay(): void; + /** + * Cancels the operation if it hasn't already been executed or canceled. The + * promise will be rejected. + * + * As long as the operation has not yet been run, calling cancel() provides a + * guarantee that the operation will not be run. + */ + cancel(reason?: string): void; + then: (onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined) => Promise; + private handleDelayElapsed; + private clearTimeout; +} + +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * The deletion will only be reflected in document reads that occur after the + * returned promise resolves. If the client is offline, the + * delete fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to delete. + * @returns A `Promise` resolved once the document has been successfully + * deleted from the backend. + */ +export declare function deleteDoc(reference: DocumentReference): Promise; + +/** + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. + */ +export declare function deleteField(): FieldValue; + +/** + * The direction of sorting in an order by. + */ +declare const enum Direction { + ASCENDING = "asc", + DESCENDING = "desc" +} + +/** + * Gets a `DocumentReference` instance that refers to the document at the + * specified absolute path. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param path - A slash-separated path to a document. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(firestore: Firestore, path: string, ...pathSegments: string[]): DocumentReference; + +/** + * Gets a `DocumentReference` instance that refers to a document within + * `reference` at the specified relative path. If no path is specified, an + * automatically-generated unique ID will be used for the returned + * `DocumentReference`. + * + * @param reference - A reference to a collection. + * @param path - A slash-separated path to a document. Has to be omitted to use + * auto-generated IDs. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(reference: CollectionReference, path?: string, ...pathSegments: string[]): DocumentReference; + +/** + * Gets a `DocumentReference` instance that refers to a document within + * `reference` at the specified relative path. + * + * @param reference - A reference to a Firestore document. + * @param path - A slash-separated path to a document. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(reference: DocumentReference, path: string, ...pathSegments: string[]): DocumentReference; + +/** + * Represents a document in Firestore with a key, version, data and whether the + * data has local mutations applied to it. + */ +declare interface Document_2 { + /** The key for this document */ + readonly key: DocumentKey; + /** + * The version of this document if it exists or a version at which this + * document was guaranteed to not exist. + */ + readonly version: SnapshotVersion; + /** + * The timestamp at which this document was read from the remote server. Uses + * `SnapshotVersion.min()` for documents created by the user. + */ + readonly readTime: SnapshotVersion; + /** + * The timestamp at which the document was created. This value increases + * monotonically when a document is deleted then recreated. It can also be + * compared to `createTime` of other documents and the `readTime` of a query. + */ + readonly createTime: SnapshotVersion; + /** The underlying data of this document or an empty value if no data exists. */ + readonly data: ObjectValue; + /** Returns whether local mutations were applied via the mutation queue. */ + readonly hasLocalMutations: boolean; + /** Returns whether mutations were applied based on a write acknowledgment. */ + readonly hasCommittedMutations: boolean; + /** + * Whether this document had a local mutation applied that has not yet been + * acknowledged by Watch. + */ + readonly hasPendingWrites: boolean; + /** + * Returns whether this document is valid (i.e. it is an entry in the + * RemoteDocumentCache, was created by a mutation or read from the backend). + */ + isValidDocument(): boolean; + /** + * Returns whether the document exists and its data is known at the current + * version. + */ + isFoundDocument(): boolean; + /** + * Returns whether the document is known to not exist at the current version. + */ + isNoDocument(): boolean; + /** + * Returns whether the document exists and its data is unknown at the current + * version. + */ + isUnknownDocument(): boolean; + isEqual(other: Document_2 | null | undefined): boolean; + /** Creates a mutable copy of this document. */ + mutableCopy(): MutableDocument; + toString(): string; +} + +declare type DocumentComparator = (doc1: Document_2, doc2: Document_2) => number; + +/** + * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to + * values. + */ +export declare interface DocumentData { + /** A mapping between a field and its value. */ + [field: string]: any; +} + +/** + * Returns a special sentinel `FieldPath` to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ +export declare function documentId(): FieldPath; + +/* Excluded from this release type: DocumentKey */ + +declare type DocumentKeyMap = ObjectMap; + +declare type DocumentKeySet = SortedSet; + +declare type DocumentMap = SortedMap; + +/** + * Provides methods to read and write document overlays. + * + * An overlay is a saved mutation, that gives a local view of a document when + * applied to the remote version of the document. + * + * Each overlay stores the largest batch ID that is included in the overlay, + * which allows us to remove the overlay once all batches leading up to it have + * been acknowledged. + */ +declare interface DocumentOverlayCache { + /** + * Gets the saved overlay mutation for the given document key. + * Returns null if there is no overlay for that key. + */ + getOverlay(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; + /** + * Gets the saved overlay mutation for the given document keys. Skips keys for + * which there are no overlays. + */ + getOverlays(transaction: PersistenceTransaction, keys: DocumentKey[]): PersistencePromise; + /** + * Saves the given document mutation map to persistence as overlays. + * All overlays will have their largest batch id set to `largestBatchId`. + */ + saveOverlays(transaction: PersistenceTransaction, largestBatchId: number, overlays: MutationMap): PersistencePromise; + /** Removes overlays for the given document keys and batch ID. */ + removeOverlaysForBatchId(transaction: PersistenceTransaction, documentKeys: DocumentKeySet, batchId: number): PersistencePromise; + /** + * Returns all saved overlays for the given collection. + * + * @param transaction - The persistence transaction to use for this operation. + * @param collection - The collection path to get the overlays for. + * @param sinceBatchId - The minimum batch ID to filter by (exclusive). + * Only overlays that contain a change past `sinceBatchId` are returned. + * @returns Mapping of each document key in the collection to its overlay. + */ + getOverlaysForCollection(transaction: PersistenceTransaction, collection: ResourcePath, sinceBatchId: number): PersistencePromise; + /** + * Returns `count` overlays with a batch ID higher than `sinceBatchId` for the + * provided collection group, processed by ascending batch ID. The method + * always returns all overlays for a batch even if the last batch contains + * more documents than the remaining limit. + * + * @param transaction - The persistence transaction used for this operation. + * @param collectionGroup - The collection group to get the overlays for. + * @param sinceBatchId - The minimum batch ID to filter by (exclusive). + * Only overlays that contain a change past `sinceBatchId` are returned. + * @param count - The number of overlays to return. Can be exceeded if the last + * batch contains more entries. + * @return Mapping of each document key in the collection group to its overlay. + */ + getOverlaysForCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, sinceBatchId: number, count: number): PersistencePromise; +} + +/** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. + */ +export declare class DocumentReference { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter | null; + readonly _key: DocumentKey; + /** The type of this Firestore reference. */ + readonly type = "document"; + /** + * The {@link Firestore} instance the document is in. + * This is useful for performing transactions, for example. + */ + readonly firestore: Firestore; + /** @hideconstructor */ + constructor(firestore: Firestore, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter: FirestoreDataConverter | null, _key: DocumentKey); + get _path(): ResourcePath; + /** + * The document's identifier within its collection. + */ + get id(): string; + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ + get path(): string; + /** + * The collection this `DocumentReference` belongs to. + */ + get parent(): CollectionReference; + /** + * Applies a custom data converter to this `DocumentReference`, allowing you + * to use your own custom model objects with Firestore. When you call {@link + * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference` + * instance, the provided converter will convert between Firestore data of + * type `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `DocumentReference` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter): DocumentReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `DocumentReference` that does not + * use a converter. + */ + withConverter(converter: null): DocumentReference; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + referencePath: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `DocumentReference` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `DocumentReference` instance from a JSON object created by + * {@link DocumentReference.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json a JSON object represention of a `DocumentReference` instance + * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(firestore: Firestore, json: object): DocumentReference; + /** + * Builds a `DocumentReference` instance from a JSON object created by + * {@link DocumentReference.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json a JSON object represention of a `DocumentReference` instance + * @param converter - Converts objects to and from Firestore. + * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(firestore: Firestore, json: object, converter: FirestoreDataConverter): DocumentReference; +} + +/** + * DocumentSet is an immutable (copy-on-write) collection that holds documents + * in order specified by the provided comparator. We always add a document key + * comparator on top of what is provided to guarantee document equality based on + * the key. + */ +declare class DocumentSet { + /** + * Returns an empty copy of the existing DocumentSet, using the same + * comparator. + */ + static emptySet(oldSet: DocumentSet): DocumentSet; + private comparator; + private keyedMap; + private sortedSet; + /** The default ordering is by key if the comparator is omitted */ + constructor(comp?: DocumentComparator); + has(key: DocumentKey): boolean; + get(key: DocumentKey): Document_2 | null; + first(): Document_2 | null; + last(): Document_2 | null; + isEmpty(): boolean; + /** + * Returns the index of the provided key in the document set, or -1 if the + * document key is not present in the set; + */ + indexOf(key: DocumentKey): number; + get size(): number; + /** Iterates documents in order defined by "comparator" */ + forEach(cb: (doc: Document_2) => void): void; + /** Inserts or updates a document with the same key */ + add(doc: Document_2): DocumentSet; + /** Deletes a document with a given key */ + delete(key: DocumentKey): DocumentSet; + isEqual(other: DocumentSet | null | undefined): boolean; + toString(): string; + private copy; +} + +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ +export declare class DocumentSnapshot { + _firestore: Firestore; + _userDataWriter: AbstractUserDataWriter; + _key: DocumentKey; + _document: Document_2 | null; + _converter: UntypedFirestoreDataConverter | null; + /** @hideconstructor protected */ + constructor(_firestore: Firestore, _userDataWriter: AbstractUserDataWriter, _key: DocumentKey, _document: Document_2 | null, _converter: UntypedFirestoreDataConverter | null); + /** Property of the `DocumentSnapshot` that provides the document's ID. */ + get id(): string; + /** + * The `DocumentReference` for the document included in the `DocumentSnapshot`. + */ + get ref(): DocumentReference; + /** + * Signals whether or not the document at the snapshot's location exists. + * + * @returns true if the document exists. + */ + exists(): this is QueryDocumentSnapshot; + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * @returns An `Object` containing all fields in the document or `undefined` + * if the document doesn't exist. + */ + data(): AppModelType | undefined; + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + get(fieldPath: string | FieldPath): any; +} + +declare type DocumentVersionMap = SortedMap; + +declare interface DocumentViewChange { + type: ChangeType; + doc: Document_2; +} +export { EmulatorMockTokenOptions } + +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided document (inclusive). The end position is relative to the order + * of the query. The document must contain all of the fields provided in the + * orderBy of the query. + * + * @param snapshot - The snapshot of the document to end at. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endAt(snapshot: DocumentSnapshot): QueryEndAtConstraint; + +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided fields relative to the order of the query. The order of the field + * values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to end this query at, in order + * of the query's order by. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endAt(...fieldValues: unknown[]): QueryEndAtConstraint; + +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided document (exclusive). The end position is relative to the + * order of the query. The document must contain all of the fields provided in + * the orderBy of the query. + * + * @param snapshot - The snapshot of the document to end before. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endBefore(snapshot: DocumentSnapshot): QueryEndAtConstraint; + +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to end this query before, in order + * of the query's order by. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endBefore(...fieldValues: unknown[]): QueryEndAtConstraint; + +declare interface Entry { + key: K; + value: V; +} + +/** + * EventManager is responsible for mapping queries to query event emitters. + * It handles "fan-out". -- Identical queries will re-use the same watch on the + * backend. + * + * PORTING NOTE: On Web, EventManager `onListen` and `onUnlisten` need to be + * assigned to SyncEngine's `listen()` and `unlisten()` API before usage. This + * allows users to tree-shake the Watch logic. + */ +declare interface EventManager { + onListen?: (query: Query_2, enableRemoteListen: boolean) => Promise; + onUnlisten?: (query: Query_2, disableRemoteListen: boolean) => Promise; + onFirstRemoteStoreListen?: (query: Query_2) => Promise; + onLastRemoteStoreUnlisten?: (query: Query_2) => Promise; + terminate(): void; +} + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options that configure the SDK’s underlying network transport (WebChannel) + * when long-polling is used. + * + * Note: This interface is "experimental" and is subject to change. + * + * See `FirestoreSettings.experimentalAutoDetectLongPolling`, + * `FirestoreSettings.experimentalForceLongPolling`, and + * `FirestoreSettings.experimentalLongPollingOptions`. + */ +declare interface ExperimentalLongPollingOptions { + /** + * The desired maximum timeout interval, in seconds, to complete a + * long-polling GET response. Valid values are between 5 and 30, inclusive. + * Floating point values are allowed and will be rounded to the nearest + * millisecond. + * + * By default, when long-polling is used the "hanging GET" request sent by + * the client times out after 30 seconds. To request a different timeout + * from the server, set this setting with the desired timeout. + * + * Changing the default timeout may be useful, for example, if the buffering + * proxy that necessitated enabling long-polling in the first place has a + * shorter timeout for hanging GET requests, in which case setting the + * long-polling timeout to a shorter value, such as 25 seconds, may fix + * prematurely-closed hanging GET requests. + * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987. + */ + timeoutSeconds?: number; +} + +declare class FieldFilter extends Filter { + readonly field: FieldPath_2; + readonly op: Operator; + readonly value: Value; + protected constructor(field: FieldPath_2, op: Operator, value: Value); + /** + * Creates a filter based on the provided arguments. + */ + static create(field: FieldPath_2, op: Operator, value: Value): FieldFilter; + private static createKeyFieldInFilter; + matches(doc: Document_2): boolean; + protected matchesComparison(comparison: number): boolean; + isInequality(): boolean; + getFlattenedFilters(): readonly FieldFilter[]; + getFilters(): Filter[]; +} + +declare type FieldFilterOp = 'OPERATOR_UNSPECIFIED' | 'LESS_THAN' | 'LESS_THAN_OR_EQUAL' | 'GREATER_THAN' | 'GREATER_THAN_OR_EQUAL' | 'EQUAL' | 'NOT_EQUAL' | 'ARRAY_CONTAINS' | 'IN' | 'ARRAY_CONTAINS_ANY' | 'NOT_IN'; + +/** + * An index definition for field indexes in Firestore. + * + * Every index is associated with a collection. The definition contains a list + * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or + * `CONTAINS` for ArrayContains/ArrayContainsAny queries). + * + * Unlike the backend, the SDK does not differentiate between collection or + * collection group-scoped indices. Every index can be used for both single + * collection and collection group queries. + */ +declare class FieldIndex { + /** + * The index ID. Returns -1 if the index ID is not available (e.g. the index + * has not yet been persisted). + */ + readonly indexId: number; + /** The collection ID this index applies to. */ + readonly collectionGroup: string; + /** The field segments for this index. */ + readonly fields: IndexSegment[]; + /** Shows how up-to-date the index is for the current user. */ + readonly indexState: IndexState; + /** An ID for an index that has not yet been added to persistence. */ + static UNKNOWN_ID: number; + constructor( + /** + * The index ID. Returns -1 if the index ID is not available (e.g. the index + * has not yet been persisted). + */ + indexId: number, + /** The collection ID this index applies to. */ + collectionGroup: string, + /** The field segments for this index. */ + fields: IndexSegment[], + /** Shows how up-to-date the index is for the current user. */ + indexState: IndexState); +} + +/** + * Provides a set of fields that can be used to partially patch a document. + * FieldMask is used in conjunction with ObjectValue. + * Examples: + * foo - Overwrites foo entirely with the provided value. If foo is not + * present in the companion ObjectValue, the field is deleted. + * foo.bar - Overwrites only the field bar of the object foo. + * If foo is not an object, foo is replaced with an object + * containing foo + */ +declare class FieldMask { + readonly fields: FieldPath_2[]; + constructor(fields: FieldPath_2[]); + static empty(): FieldMask; + /** + * Returns a new FieldMask object that is the result of adding all the given + * fields paths to this field mask. + */ + unionWith(extraFields: FieldPath_2[]): FieldMask; + /** + * Verifies that `fieldPath` is included by at least one field in this field + * mask. + * + * This is an O(n) operation, where `n` is the size of the field mask. + */ + covers(fieldPath: FieldPath_2): boolean; + isEqual(other: FieldMask): boolean; +} + +/** + * A `FieldPath` refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + * + * Create a `FieldPath` by providing field names. If more than one field + * name is provided, the path will point to a nested field in a document. + */ +export declare class FieldPath { + /** Internal representation of a Firestore field path. */ + readonly _internalPath: FieldPath_2; + /** + * Creates a `FieldPath` from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames - A list of field names. + */ + constructor(...fieldNames: string[]); + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other - The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ + isEqual(other: FieldPath): boolean; +} + +/* Excluded from this release type: FieldPath_2 */ + +/** A field path and the TransformOperation to perform upon it. */ +declare class FieldTransform { + readonly field: FieldPath_2; + readonly transform: TransformOperation; + constructor(field: FieldPath_2, transform: TransformOperation); +} + +declare type FieldTransformSetToServerValue = 'SERVER_VALUE_UNSPECIFIED' | 'REQUEST_TIME'; + +/** + * Sentinel values that can be used when writing document fields with `set()` + * or `update()`. + */ +export declare abstract class FieldValue { + _methodName: string; + /** + * @param _methodName - The public API endpoint that returns this class. + * @hideconstructor + */ + constructor(_methodName: string); + /** Compares `FieldValue`s for equality. */ + abstract isEqual(other: FieldValue): boolean; + abstract _toFieldTransform(context: ParseContext): FieldTransform | null; +} + +declare abstract class Filter { + abstract matches(doc: Document_2): boolean; + abstract getFlattenedFilters(): readonly FieldFilter[]; + abstract getFilters(): Filter[]; +} + +/* Excluded from this release type: _FirebaseService */ + +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ +export declare class Firestore implements FirestoreService { + _authCredentials: CredentialsProvider; + _appCheckCredentials: CredentialsProvider; + readonly _databaseId: DatabaseId; + readonly _app?: FirebaseApp | undefined; + /** + * Whether it's a Firestore or Firestore Lite instance. + */ + type: 'firestore-lite' | 'firestore'; + readonly _persistenceKey: string; + private _settings; + private _settingsFrozen; + private _emulatorOptions; + private _terminateTask; + /** @hideconstructor */ + constructor(_authCredentials: CredentialsProvider, _appCheckCredentials: CredentialsProvider, _databaseId: DatabaseId, _app?: FirebaseApp | undefined); + /** + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service + * instance. + */ + get app(): FirebaseApp; + get _initialized(): boolean; + get _terminated(): boolean; + _setSettings(settings: PrivateSettings): void; + _getSettings(): FirestoreSettingsImpl; + _getEmulatorOptions(): { + mockUserToken?: EmulatorMockTokenOptions | string; + }; + _freezeSettings(): FirestoreSettingsImpl; + _delete(): Promise; + _restart(): Promise; + /** Returns a JSON-serializable representation of this `Firestore` instance. */ + toJSON(): object; + /** + * Terminates all components used by this client. Subclasses can override + * this method to clean up their own dependencies, but must also call this + * method. + * + * Only ever called once. + */ + protected _terminate(): Promise; +} + +/** + * Converter used by `withConverter()` to transform user objects of type + * `AppModelType` into Firestore data of type `DbModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * In this context, an "AppModel" is a class that is used in an application to + * package together related information and functionality. Such a class could, + * for example, have properties with complex, nested data types, properties used + * for memoization, properties of types not supported by Firestore (such as + * `symbol` and `bigint`), and helper functions that perform compound + * operations. Such classes are not suitable and/or possible to store into a + * Firestore database. Instead, instances of such classes need to be converted + * to "plain old JavaScript objects" (POJOs) with exclusively primitive + * properties, potentially nested inside other POJOs or arrays of POJOs. In this + * context, this type is referred to as the "DbModel" and would be an object + * suitable for persisting into Firestore. For convenience, applications can + * implement `FirestoreDataConverter` and register the converter with Firestore + * objects, such as `DocumentReference` or `Query`, to automatically convert + * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel` + * to `AppModel` when retrieving from Firestore. + * + * @example + * + * Simple Example + * + * ```typescript + * const numberConverter = { + * toFirestore(value: WithFieldValue) { + * return { value }; + * }, + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) { + * return snapshot.data(options).value as number; + * } + * }; + * + * async function simpleDemo(db: Firestore): Promise { + * const documentRef = doc(db, 'values/value123').withConverter(numberConverter); + * + * // converters are used with `setDoc`, `addDoc`, and `getDoc` + * await setDoc(documentRef, 42); + * const snapshot1 = await getDoc(documentRef); + * assertEqual(snapshot1.data(), 42); + * + * // converters are not used when writing data with `updateDoc` + * await updateDoc(documentRef, { value: 999 }); + * const snapshot2 = await getDoc(documentRef); + * assertEqual(snapshot2.data(), 999); + * } + * ``` + * + * Advanced Example + * + * ```typescript + * // The Post class is a model that is used by our application. + * // This class may have properties and methods that are specific + * // to our application execution, which do not need to be persisted + * // to Firestore. + * class Post { + * constructor( + * readonly title: string, + * readonly author: string, + * readonly lastUpdatedMillis: number + * ) {} + * toString(): string { + * return `${this.title} by ${this.author}`; + * } + * } + * + * // The PostDbModel represents how we want our posts to be stored + * // in Firestore. This DbModel has different properties (`ttl`, + * // `aut`, and `lut`) from the Post class we use in our application. + * interface PostDbModel { + * ttl: string; + * aut: { firstName: string; lastName: string }; + * lut: Timestamp; + * } + * + * // The `PostConverter` implements `FirestoreDataConverter` and specifies + * // how the Firestore SDK can convert `Post` objects to `PostDbModel` + * // objects and vice versa. + * class PostConverter implements FirestoreDataConverter { + * toFirestore(post: WithFieldValue): WithFieldValue { + * return { + * ttl: post.title, + * aut: this._autFromAuthor(post.author), + * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis) + * }; + * } + * + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post { + * const data = snapshot.data(options) as PostDbModel; + * const author = `${data.aut.firstName} ${data.aut.lastName}`; + * return new Post(data.ttl, author, data.lut.toMillis()); + * } + * + * _autFromAuthor( + * author: string | FieldValue + * ): { firstName: string; lastName: string } | FieldValue { + * if (typeof author !== 'string') { + * // `author` is a FieldValue, so just return it. + * return author; + * } + * const [firstName, lastName] = author.split(' '); + * return {firstName, lastName}; + * } + * + * _lutFromLastUpdatedMillis( + * lastUpdatedMillis: number | FieldValue + * ): Timestamp | FieldValue { + * if (typeof lastUpdatedMillis !== 'number') { + * // `lastUpdatedMillis` must be a FieldValue, so just return it. + * return lastUpdatedMillis; + * } + * return Timestamp.fromMillis(lastUpdatedMillis); + * } + * } + * + * async function advancedDemo(db: Firestore): Promise { + * // Create a `DocumentReference` with a `FirestoreDataConverter`. + * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter()); + * + * // The `data` argument specified to `setDoc()` is type checked by the + * // TypeScript compiler to be compatible with `Post`. Since the `data` + * // argument is typed as `WithFieldValue` rather than just `Post`, + * // this allows properties of the `data` argument to also be special + * // Firestore values that perform server-side mutations, such as + * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`. + * await setDoc(documentRef, { + * title: 'My Life', + * author: 'Foo Bar', + * lastUpdatedMillis: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `setDoc()` is _not_ compatible with `WithFieldValue`. This + * // type checking prevents the caller from specifying objects with incorrect + * // properties or property values. + * // @ts-expect-error "Argument of type { ttl: string; } is not assignable + * // to parameter of type WithFieldValue" + * await setDoc(documentRef, { ttl: 'The Title' }); + * + * // When retrieving a document with `getDoc()` the `DocumentSnapshot` + * // object's `data()` method returns a `Post`, rather than a generic object, + * // which would have been returned if the `DocumentReference` did _not_ have a + * // `FirestoreDataConverter` attached to it. + * const snapshot1: DocumentSnapshot = await getDoc(documentRef); + * const post1: Post = snapshot1.data()!; + * if (post1) { + * assertEqual(post1.title, 'My Life'); + * assertEqual(post1.author, 'Foo Bar'); + * } + * + * // The `data` argument specified to `updateDoc()` is type checked by the + * // TypeScript compiler to be compatible with `PostDbModel`. Note that + * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`, + * // the `data` argument to `updateDoc()` must be compatible with + * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed + * // as `WithFieldValue` rather than just `PostDbModel`, this + * // allows properties of the `data` argument to also be those special + * // Firestore values, like `arrayRemove()`, `deleteField()`, and + * // `serverTimestamp()`. + * await updateDoc(documentRef, { + * 'aut.firstName': 'NewFirstName', + * lut: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `updateDoc()` is _not_ compatible with `WithFieldValue`. + * // This type checking prevents the caller from specifying objects with + * // incorrect properties or property values. + * // @ts-expect-error "Argument of type { title: string; } is not assignable + * // to parameter of type WithFieldValue" + * await updateDoc(documentRef, { title: 'New Title' }); + * const snapshot2: DocumentSnapshot = await getDoc(documentRef); + * const post2: Post = snapshot2.data()!; + * if (post2) { + * assertEqual(post2.title, 'My Life'); + * assertEqual(post2.author, 'NewFirstName Bar'); + * } + * } + * ``` + */ +export declare interface FirestoreDataConverter { + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link @firebase/firestore/lite#(setDoc:1)}, + * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and + * {@link @firebase/firestore/lite#(Transaction.set:1)}. + * + * The `WithFieldValue` type extends `T` to also allow FieldValues such as + * {@link (deleteField:1)} to be used as property values. + */ + toFirestore(modelObject: WithFieldValue): WithFieldValue; + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link @firebase/firestore/lite#(setDoc:1)}, + * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and + * {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true` + * or `mergeFields`. + * + * The `PartialWithFieldValue` type extends `Partial` to allow + * FieldValues such as {@link (arrayUnion:1)} to be used as property values. + * It also supports nested `Partial` by allowing nested fields to be + * omitted. + */ + toFirestore(modelObject: PartialWithFieldValue, options: SetOptions): PartialWithFieldValue; + /** + * Called by the Firestore SDK to convert Firestore data into an object of + * type `AppModelType`. You can access your data by calling: + * `snapshot.data()`. + * + * + * Generally, the data returned from `snapshot.data()` can be cast to + * `DbModelType`; however, this is not guaranteed because Firestore does not + * enforce a schema on the database. For example, writes from a previous + * version of the application or writes from another client that did not use a + * type converter could have written data with different properties and/or + * property types. The implementation will need to choose whether to + * gracefully recover from non-conforming data or throw an error. + * + * @param snapshot - A `QueryDocumentSnapshot` containing your data and + * metadata. + */ + fromFirestore(snapshot: QueryDocumentSnapshot): AppModelType; +} + +/** An error returned by a Firestore operation. */ +export declare class FirestoreError extends FirebaseError { + /** + * The backend error code associated with this error. + */ + readonly code: FirestoreErrorCode; + /** + * A custom error description. + */ + readonly message: string; + /** The stack of the error. */ + readonly stack?: string; + /** @hideconstructor */ + constructor( + /** + * The backend error code associated with this error. + */ + code: FirestoreErrorCode, + /** + * A custom error description. + */ + message: string); +} + +/** + * The set of Firestore status codes. The codes are the same at the ones + * exposed by gRPC here: + * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md + * + * Possible values: + * - 'cancelled': The operation was cancelled (typically by the caller). + * - 'unknown': Unknown error or an error from a different error domain. + * - 'invalid-argument': Client specified an invalid argument. Note that this + * differs from 'failed-precondition'. 'invalid-argument' indicates + * arguments that are problematic regardless of the state of the system + * (e.g. an invalid field name). + * - 'deadline-exceeded': Deadline expired before operation could complete. + * For operations that change the state of the system, this error may be + * returned even if the operation has completed successfully. For example, + * a successful response from a server could have been delayed long enough + * for the deadline to expire. + * - 'not-found': Some requested document was not found. + * - 'already-exists': Some document that we attempted to create already + * exists. + * - 'permission-denied': The caller does not have permission to execute the + * specified operation. + * - 'resource-exhausted': Some resource has been exhausted, perhaps a + * per-user quota, or perhaps the entire file system is out of space. + * - 'failed-precondition': Operation was rejected because the system is not + * in a state required for the operation's execution. + * - 'aborted': The operation was aborted, typically due to a concurrency + * issue like transaction aborts, etc. + * - 'out-of-range': Operation was attempted past the valid range. + * - 'unimplemented': Operation is not implemented or not supported/enabled. + * - 'internal': Internal errors. Means some invariants expected by + * underlying system has been broken. If you see one of these errors, + * something is very broken. + * - 'unavailable': The service is currently unavailable. This is most likely + * a transient condition and may be corrected by retrying with a backoff. + * - 'data-loss': Unrecoverable data loss or corruption. + * - 'unauthenticated': The request does not have valid authentication + * credentials for the operation. + */ +export declare type FirestoreErrorCode = 'cancelled' | 'unknown' | 'invalid-argument' | 'deadline-exceeded' | 'not-found' | 'already-exists' | 'permission-denied' | 'resource-exhausted' | 'failed-precondition' | 'aborted' | 'out-of-range' | 'unimplemented' | 'internal' | 'unavailable' | 'data-loss' | 'unauthenticated'; + +/** + * Union type from all supported SDK cache layer. + */ +declare type FirestoreLocalCache = MemoryLocalCache | PersistentLocalCache; + +/** + * An interface implemented by FirebaseFirestore that provides compatibility + * with the usage in this file. + * + * This interface mainly exists to remove a cyclic dependency. + */ +declare interface FirestoreService extends _FirebaseService { + _authCredentials: CredentialsProvider; + _appCheckCredentials: CredentialsProvider; + _persistenceKey: string; + _databaseId: DatabaseId; + _terminated: boolean; + _freezeSettings(): FirestoreSettingsImpl; +} + +/** + * A concrete type describing all the values that can be applied via a + * user-supplied `FirestoreSettings` object. This is a separate type so that + * defaults can be supplied and the value can be checked for equality. + */ +declare class FirestoreSettingsImpl { + /** The hostname to connect to. */ + readonly host: string; + /** Whether to use SSL when connecting. */ + readonly ssl: boolean; + readonly cacheSizeBytes: number; + readonly experimentalForceLongPolling: boolean; + readonly experimentalAutoDetectLongPolling: boolean; + readonly experimentalLongPollingOptions: ExperimentalLongPollingOptions; + readonly ignoreUndefinedProperties: boolean; + readonly useFetchStreams: boolean; + readonly localCache?: FirestoreLocalCache; + readonly isUsingEmulator: boolean; + credentials?: any; + constructor(settings: PrivateSettings); + isEqual(other: FirestoreSettingsImpl): boolean; +} + +declare namespace firestoreV1ApiClientInterfaces { + interface ArrayValue { + values?: Value[]; + } + interface BatchGetDocumentsRequest { + database?: string; + documents?: string[]; + mask?: DocumentMask; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface BatchGetDocumentsResponse { + found?: Document; + missing?: string; + transaction?: string; + readTime?: string; + } + interface BeginTransactionRequest { + options?: TransactionOptions; + } + interface BeginTransactionResponse { + transaction?: string; + } + interface CollectionSelector { + collectionId?: string; + allDescendants?: boolean; + } + interface CommitRequest { + database?: string; + writes?: Write[]; + transaction?: string; + } + interface CommitResponse { + writeResults?: WriteResult[]; + commitTime?: string; + } + interface CompositeFilter { + op?: CompositeFilterOp; + filters?: Filter[]; + } + interface Cursor { + values?: Value[]; + before?: boolean; + } + interface Document { + name?: string; + fields?: ApiClientObjectMap; + createTime?: Timestamp_2; + updateTime?: Timestamp_2; + } + interface DocumentChange { + document?: Document; + targetIds?: number[]; + removedTargetIds?: number[]; + } + interface DocumentDelete { + document?: string; + removedTargetIds?: number[]; + readTime?: Timestamp_2; + } + interface DocumentMask { + fieldPaths?: string[]; + } + interface DocumentRemove { + document?: string; + removedTargetIds?: number[]; + readTime?: string; + } + interface DocumentTransform { + document?: string; + fieldTransforms?: FieldTransform[]; + } + interface DocumentsTarget { + documents?: string[]; + } + interface Empty { + } + interface ExistenceFilter { + targetId?: number; + count?: number; + unchangedNames?: BloomFilter; + } + interface BloomFilter { + bits?: BitSequence; + hashCount?: number; + } + interface BitSequence { + bitmap?: string | Uint8Array; + padding?: number; + } + interface FieldFilter { + field?: FieldReference; + op?: FieldFilterOp; + value?: Value; + } + interface FieldReference { + fieldPath?: string; + } + interface FieldTransform { + fieldPath?: string; + setToServerValue?: FieldTransformSetToServerValue; + appendMissingElements?: ArrayValue; + removeAllFromArray?: ArrayValue; + increment?: Value; + } + interface Filter { + compositeFilter?: CompositeFilter; + fieldFilter?: FieldFilter; + unaryFilter?: UnaryFilter; + } + interface Index { + name?: string; + collectionId?: string; + fields?: IndexField[]; + state?: IndexState_2; + } + interface IndexField { + fieldPath?: string; + mode?: IndexFieldMode; + } + interface LatLng { + latitude?: number; + longitude?: number; + } + interface ListCollectionIdsRequest { + pageSize?: number; + pageToken?: string; + } + interface ListCollectionIdsResponse { + collectionIds?: string[]; + nextPageToken?: string; + } + interface ListDocumentsResponse { + documents?: Document[]; + nextPageToken?: string; + } + interface ListIndexesResponse { + indexes?: Index[]; + nextPageToken?: string; + } + interface ListenRequest { + addTarget?: Target; + removeTarget?: number; + labels?: ApiClientObjectMap; + } + interface ListenResponse { + targetChange?: TargetChange; + documentChange?: DocumentChange; + documentDelete?: DocumentDelete; + documentRemove?: DocumentRemove; + filter?: ExistenceFilter; + } + interface MapValue { + fields?: ApiClientObjectMap; + } + interface Operation { + name?: string; + metadata?: ApiClientObjectMap; + done?: boolean; + error?: Status; + response?: ApiClientObjectMap; + } + interface Order { + field?: FieldReference; + direction?: OrderDirection; + } + interface Precondition { + exists?: boolean; + updateTime?: Timestamp_2; + } + interface Projection { + fields?: FieldReference[]; + } + interface QueryTarget { + parent?: string; + structuredQuery?: StructuredQuery; + } + interface ReadOnly { + readTime?: string; + } + interface ReadWrite { + retryTransaction?: string; + } + interface RollbackRequest { + transaction?: string; + } + interface RunQueryRequest { + parent?: string; + structuredQuery?: StructuredQuery; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface RunQueryResponse { + transaction?: string; + document?: Document; + readTime?: string; + skippedResults?: number; + } + interface RunAggregationQueryRequest { + parent?: string; + structuredAggregationQuery?: StructuredAggregationQuery; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface RunAggregationQueryResponse { + result?: AggregationResult; + transaction?: string; + readTime?: string; + } + interface AggregationResult { + aggregateFields?: ApiClientObjectMap; + } + interface StructuredAggregationQuery { + structuredQuery?: StructuredQuery; + aggregations?: Aggregation[]; + } + interface Aggregation { + count?: Count; + sum?: Sum; + avg?: Avg; + alias?: string; + } + interface Count { + upTo?: number; + } + interface Sum { + field?: FieldReference; + } + interface Avg { + field?: FieldReference; + } + interface Status { + code?: number; + message?: string; + details?: Array>; + } + interface StructuredQuery { + select?: Projection; + from?: CollectionSelector[]; + where?: Filter; + orderBy?: Order[]; + startAt?: Cursor; + endAt?: Cursor; + offset?: number; + limit?: number | { + value: number; + }; + } + interface Target { + query?: QueryTarget; + documents?: DocumentsTarget; + resumeToken?: string | Uint8Array; + readTime?: Timestamp_2; + targetId?: number; + once?: boolean; + expectedCount?: number | { + value: number; + }; + } + interface TargetChange { + targetChangeType?: TargetChangeTargetChangeType; + targetIds?: number[]; + cause?: Status; + resumeToken?: string | Uint8Array; + readTime?: Timestamp_2; + } + interface TransactionOptions { + readOnly?: ReadOnly; + readWrite?: ReadWrite; + } + interface UnaryFilter { + op?: UnaryFilterOp; + field?: FieldReference; + } + interface Value { + nullValue?: ValueNullValue; + booleanValue?: boolean; + integerValue?: string | number; + doubleValue?: string | number; + timestampValue?: Timestamp_2; + stringValue?: string; + bytesValue?: string | Uint8Array; + referenceValue?: string; + geoPointValue?: LatLng; + arrayValue?: ArrayValue; + mapValue?: MapValue; + } + interface Write { + update?: Document; + delete?: string; + verify?: string; + transform?: DocumentTransform; + updateMask?: DocumentMask; + updateTransforms?: FieldTransform[]; + currentDocument?: Precondition; + } + interface WriteRequest { + streamId?: string; + writes?: Write[]; + streamToken?: string | Uint8Array; + labels?: ApiClientObjectMap; + } + interface WriteResponse { + streamId?: string; + streamToken?: string | Uint8Array; + writeResults?: WriteResult[]; + commitTime?: Timestamp_2; + } + interface WriteResult { + updateTime?: Timestamp_2; + transformResults?: Value[]; + } +} + +/* Excluded from this release type: FirstPartyCredentialsSettings */ + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +declare type FulfilledHandler = ((result: T) => R | PersistencePromise) | null; + +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ +export declare class GeoPoint { + private _lat; + private _long; + /** + * Creates a new immutable `GeoPoint` object with the provided latitude and + * longitude values. + * @param latitude - The latitude as number between -90 and 90. + * @param longitude - The longitude as number between -180 and 180. + */ + constructor(latitude: number, longitude: number); + /** + * The latitude of this `GeoPoint` instance. + */ + get latitude(): number; + /** + * The longitude of this `GeoPoint` instance. + */ + get longitude(): number; + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other - The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ + isEqual(other: GeoPoint): boolean; + /** + * Actually private to JS consumers of our API, so this function is prefixed + * with an underscore. + */ + _compareTo(other: GeoPoint): number; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + latitude: Property<"number">; + longitude: Property<"number">; + }; + /** + * Returns a JSON-serializable representation of this `GeoPoint` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): { + latitude: number; + longitude: number; + type: string; + }; + /** + * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}. + * + * @param json a JSON object represention of a `GeoPoint` instance + * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): GeoPoint; +} + +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregate(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ +export declare function getAggregate(query: Query, aggregateSpec: AggregateSpecType): Promise>; + +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ +export declare function getCount(query: Query): Promise; +}, AppModelType, DbModelType>>; + +/** + * Reads the document referred to by the specified document reference. + * + * All documents are directly fetched from the server, even if the document was + * previously read or modified. Recent modifications are only reflected in the + * retrieved `DocumentSnapshot` if they have already been applied by the + * backend. If the client is offline, the read fails. If you like to use + * caching or see local modifications, please use the full Firestore SDK. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the current + * document contents. + */ +export declare function getDoc(reference: DocumentReference): Promise>; + +/** + * Executes the query and returns the results as a {@link QuerySnapshot}. + * + * All queries are executed directly by the server, even if the query was + * previously executed. Recent modifications are only reflected in the retrieved + * results if they have already been applied by the backend. If the client is + * offline, the operation fails. To see previously cached result and local + * modifications, use the full Firestore SDK. + * + * @param query - The `Query` to execute. + * @returns A Promise that will be resolved with the results of the query. + */ +export declare function getDocs(query: Query): Promise>; + +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @returns The {@link Firestore} instance of the provided app. + */ +export declare function getFirestore(): Firestore; + +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @returns The {@link Firestore} instance of the provided app. + */ +export declare function getFirestore(app: FirebaseApp): Firestore; + +/** + * Returns the existing {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param databaseId - The name of the database. + * @returns The {@link Firestore} instance of the provided app. + * @beta + */ +export declare function getFirestore(databaseId: string): Firestore; + +/** + * Returns the existing {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @param databaseId - The name of the database. + * @returns The {@link Firestore} instance of the provided app. + * @beta + */ +export declare function getFirestore(app: FirebaseApp, databaseId: string): Firestore; + +/** + * General purpose cache for global values. + * + * Global state that cuts across components should be saved here. Following are contained herein: + * + * `sessionToken` tracks server interaction across Listen and Write streams. This facilitates cache + * synchronization and invalidation. + */ +declare interface GlobalsCache { + /** + * Gets session token. + */ + getSessionToken(transaction: PersistenceTransaction): PersistencePromise; + /** + * Sets session token. + * + * @param sessionToken - The new session token. + */ + setSessionToken(transaction: PersistenceTransaction, sessionToken: ByteString): PersistencePromise; +} + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by + * the given value. + * + * If either the operand or the current field value uses floating point + * precision, all arithmetic follows IEEE 754 semantics. If both values are + * integers, values outside of JavaScript's safe number range + * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to + * precision loss. Furthermore, once processed by the Firestore backend, all + * integer operations are capped between -2^63 and 2^63-1. + * + * If the current field value is not of type `number`, or if the field does not + * yet exist, the transformation sets the field to the given value. + * + * @param n - The value to increment by. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +export declare function increment(n: number): FieldValue; + +declare type IndexFieldMode = 'MODE_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING'; + +/** The type of the index, e.g. for which type of query it can be used. */ +declare const enum IndexKind { + /** + * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries. + */ + ASCENDING = 0, + /** + * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries. + */ + DESCENDING = 1, + /** Contains index. Can be used for ArrayContains and ArrayContainsAny. */ + CONTAINS = 2 +} + +/** + * Represents a set of indexes that are used to execute queries efficiently. + * + * Currently the only index is a [collection id] => [parent path] index, used + * to execute Collection Group queries. + */ +declare interface IndexManager { + /** + * Creates an index entry mapping the collectionId (last segment of the path) + * to the parent path (either the containing document location or the empty + * path for root-level collections). Index entries can be retrieved via + * getCollectionParents(). + * + * NOTE: Currently we don't remove index entries. If this ends up being an + * issue we can devise some sort of GC strategy. + */ + addToCollectionParentIndex(transaction: PersistenceTransaction, collectionPath: ResourcePath): PersistencePromise; + /** + * Retrieves all parent locations containing the given collectionId, as a + * list of paths (each path being either a document location or the empty + * path for a root-level collection). + */ + getCollectionParents(transaction: PersistenceTransaction, collectionId: string): PersistencePromise; + /** + * Adds a field path index. + * + * Values for this index are persisted via the index backfill, which runs + * asynchronously in the background. Once the first values are written, + * an index can be used to serve partial results for any matching queries. + * Any unindexed portion of the database will continue to be served via + * collection scons. + */ + addFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + /** Removes the given field index and deletes all index values. */ + deleteFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + /** Removes all field indexes and deletes all index values. */ + deleteAllFieldIndexes(transaction: PersistenceTransaction): PersistencePromise; + /** Creates a full matched field index which serves the given target. */ + createTargetIndexes(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Returns a list of field indexes that correspond to the specified collection + * group. + * + * @param collectionGroup The collection group to get matching field indexes + * for. + * @return A collection of field indexes for the specified collection group. + */ + getFieldIndexes(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise; + /** Returns all configured field indexes. */ + getFieldIndexes(transaction: PersistenceTransaction): PersistencePromise; + /** + * Returns the type of index (if any) that can be used to serve the given + * target. + */ + getIndexType(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Returns the documents that match the given target based on the provided + * index or `null` if the target does not have a matching index. + */ + getDocumentsMatchingTarget(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Returns the next collection group to update. Returns `null` if no group + * exists. + */ + getNextCollectionGroupToUpdate(transaction: PersistenceTransaction): PersistencePromise; + /** + * Sets the collection group's latest read time. + * + * This method updates the index offset for all field indices for the + * collection group and increments their sequence number. Subsequent calls to + * `getNextCollectionGroupToUpdate()` will return a different collection group + * (unless only one collection group is configured). + */ + updateCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset): PersistencePromise; + /** Updates the index entries for the provided documents. */ + updateIndexEntries(transaction: PersistenceTransaction, documents: DocumentMap): PersistencePromise; + /** + * Iterates over all field indexes that are used to serve the given target, + * and returns the minimum offset of them all. + */ + getMinOffset(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** Returns the minimum offset for the given collection group. */ + getMinOffsetFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise; +} + +/** + * Stores the latest read time, document and batch ID that were processed for an + * index. + */ +declare class IndexOffset { + /** + * The latest read time version that has been indexed by Firestore for this + * field index. + */ + readonly readTime: SnapshotVersion; + /** + * The key of the last document that was indexed for this query. Use + * `DocumentKey.empty()` if no document has been indexed. + */ + readonly documentKey: DocumentKey; + readonly largestBatchId: number; + constructor( + /** + * The latest read time version that has been indexed by Firestore for this + * field index. + */ + readTime: SnapshotVersion, + /** + * The key of the last document that was indexed for this query. Use + * `DocumentKey.empty()` if no document has been indexed. + */ + documentKey: DocumentKey, largestBatchId: number); + /** Returns an offset that sorts before all regular offsets. */ + static min(): IndexOffset; + /** Returns an offset that sorts after all regular offsets. */ + static max(): IndexOffset; +} + +/** An index component consisting of field path and index type. */ +declare class IndexSegment { + /** The field path of the component. */ + readonly fieldPath: FieldPath_2; + /** The fields sorting order. */ + readonly kind: IndexKind; + constructor( + /** The field path of the component. */ + fieldPath: FieldPath_2, + /** The fields sorting order. */ + kind: IndexKind); +} + +/** + * Stores the "high water mark" that indicates how updated the Index is for the + * current user. + */ +declare class IndexState { + /** + * Indicates when the index was last updated (relative to other indexes). + */ + readonly sequenceNumber: number; + /** The the latest indexed read time, document and batch id. */ + readonly offset: IndexOffset; + constructor( + /** + * Indicates when the index was last updated (relative to other indexes). + */ + sequenceNumber: number, + /** The the latest indexed read time, document and batch id. */ + offset: IndexOffset); + /** The state of an index that has not yet been backfilled. */ + static empty(): IndexState; +} + +declare type IndexState_2 = 'STATE_UNSPECIFIED' | 'CREATING' | 'READY' | 'ERROR'; + +/** Represents the index state as it relates to a particular target. */ +declare const enum IndexType { + /** Indicates that no index could be found for serving the target. */ + NONE = 0, + /** + * Indicates that only a "partial index" could be found for serving the + * target. A partial index is one which does not have a segment for every + * filter/orderBy in the target. + */ + PARTIAL = 1, + /** + * Indicates that a "full index" could be found for serving the target. A full + * index is one which has a segment for every filter/orderBy in the target. + */ + FULL = 2 +} + +/** + * Initializes a new instance of Cloud Firestore with the provided settings. + * Can only be called before any other functions, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will + * be associated. + * @param settings - A settings object to configure the `Firestore` instance. + * @returns A newly initialized `Firestore` instance. + */ +export declare function initializeFirestore(app: FirebaseApp, settings: Settings): Firestore; + +/** + * Initializes a new instance of Cloud Firestore with the provided settings. + * Can only be called before any other functions, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the `Firestore` instance will + * be associated. + * @param settings - A settings object to configure the `Firestore` instance. + * @param databaseId - The name of the database. + * @returns A newly initialized `Firestore` instance. + * @beta + */ +export declare function initializeFirestore(app: FirebaseApp, settings: Settings, databaseId?: string): Firestore; + +/** + * This class generates JsonObject values for the Datastore API suitable for + * sending to either GRPC stub methods or via the JSON/HTTP REST API. + * + * The serializer supports both Protobuf.js and Proto3 JSON formats. By + * setting `useProto3Json` to true, the serializer will use the Proto3 JSON + * format. + * + * For a description of the Proto3 JSON format check + * https://developers.google.com/protocol-buffers/docs/proto3#json + * + * TODO(klimt): We can remove the databaseId argument if we keep the full + * resource name in documents. + */ +declare class JsonProtoSerializer implements Serializer { + readonly databaseId: DatabaseId; + readonly useProto3Json: boolean; + constructor(databaseId: DatabaseId, useProto3Json: boolean); +} + +/* Excluded from this release type: JsonTypeDesc */ + +declare type Kind = 'memory' | 'persistent'; + +/** + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +export declare function limit(limit: number): QueryLimitConstraint; + +/** + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. + * + * You must specify at least one `orderBy` clause for `limitToLast` queries, + * otherwise an exception will be thrown during execution. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +export declare function limitToLast(limit: number): QueryLimitConstraint; + +declare const enum LimitType { + First = "F", + Last = "L" +} + +/** LimitType enum. */ +declare type LimitType_2 = 'FIRST' | 'LAST'; + +declare type ListenSequenceNumber = number; + +declare class LLRBEmptyNode { + get key(): never; + get value(): never; + get color(): never; + get left(): never; + get right(): never; + size: number; + copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode | LLRBEmptyNode | null, right: LLRBNode | LLRBEmptyNode | null): LLRBEmptyNode; + insert(key: K, value: V, comparator: Comparator): LLRBNode; + remove(key: K, comparator: Comparator): LLRBEmptyNode; + isEmpty(): boolean; + inorderTraversal(action: (k: K, v: V) => boolean): boolean; + reverseTraversal(action: (k: K, v: V) => boolean): boolean; + minKey(): K | null; + maxKey(): K | null; + isRed(): boolean; + checkMaxDepth(): boolean; + protected check(): 0; +} + +declare class LLRBNode { + key: K; + value: V; + readonly color: boolean; + readonly left: LLRBNode | LLRBEmptyNode; + readonly right: LLRBNode | LLRBEmptyNode; + readonly size: number; + static EMPTY: LLRBEmptyNode; + static RED: boolean; + static BLACK: boolean; + constructor(key: K, value: V, color?: boolean, left?: LLRBNode | LLRBEmptyNode, right?: LLRBNode | LLRBEmptyNode); + copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode | LLRBEmptyNode | null, right: LLRBNode | LLRBEmptyNode | null): LLRBNode; + isEmpty(): boolean; + inorderTraversal(action: (k: K, v: V) => T): T; + reverseTraversal(action: (k: K, v: V) => T): T; + private min; + minKey(): K | null; + maxKey(): K | null; + insert(key: K, value: V, comparator: Comparator): LLRBNode; + private removeMin; + remove(key: K, comparator: Comparator): LLRBNode | LLRBEmptyNode; + isRed(): boolean; + private fixUp; + private moveRedLeft; + private moveRedRight; + private rotateLeft; + private rotateRight; + private colorFlip; + checkMaxDepth(): boolean; + protected check(): number; +} + +/** + * A readonly view of the local state of all documents we're tracking (i.e. we + * have a cached version in remoteDocumentCache or local mutations for the + * document). The view is computed by applying the mutations in the + * MutationQueue to the RemoteDocumentCache. + */ +declare class LocalDocumentsView { + readonly remoteDocumentCache: RemoteDocumentCache; + readonly mutationQueue: MutationQueue; + readonly documentOverlayCache: DocumentOverlayCache; + readonly indexManager: IndexManager; + constructor(remoteDocumentCache: RemoteDocumentCache, mutationQueue: MutationQueue, documentOverlayCache: DocumentOverlayCache, indexManager: IndexManager); + /** + * Get the local view of the document identified by `key`. + * + * @returns Local view of the document or null if we don't have any cached + * state for it. + */ + getDocument(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; + /** + * Gets the local view of the documents identified by `keys`. + * + * If we don't have cached state for a document in `keys`, a NoDocument will + * be stored for that key in the resulting set. + */ + getDocuments(transaction: PersistenceTransaction, keys: DocumentKeySet): PersistencePromise; + /** + * Similar to `getDocuments`, but creates the local view from the given + * `baseDocs` without retrieving documents from the local store. + * + * @param transaction - The transaction this operation is scoped to. + * @param docs - The documents to apply local mutations to get the local views. + * @param existenceStateChanged - The set of document keys whose existence state + * is changed. This is useful to determine if some documents overlay needs + * to be recalculated. + */ + getLocalViewOfDocuments(transaction: PersistenceTransaction, docs: MutableDocumentMap, existenceStateChanged?: DocumentKeySet): PersistencePromise; + /** + * Gets the overlayed documents for the given document map, which will include + * the local view of those documents and a `FieldMask` indicating which fields + * are mutated locally, `null` if overlay is a Set or Delete mutation. + */ + getOverlayedDocuments(transaction: PersistenceTransaction, docs: MutableDocumentMap): PersistencePromise; + /** + * Fetches the overlays for {@code docs} and adds them to provided overlay map + * if the map does not already contain an entry for the given document key. + */ + private populateOverlays; + /** + * Computes the local view for the given documents. + * + * @param docs - The documents to compute views for. It also has the base + * version of the documents. + * @param overlays - The overlays that need to be applied to the given base + * version of the documents. + * @param existenceStateChanged - A set of documents whose existence states + * might have changed. This is used to determine if we need to re-calculate + * overlays from mutation queues. + * @return A map represents the local documents view. + */ + computeViews(transaction: PersistenceTransaction, docs: MutableDocumentMap, overlays: OverlayMap, existenceStateChanged: DocumentKeySet): PersistencePromise; + private recalculateAndSaveOverlays; + /** + * Recalculates overlays by reading the documents from remote document cache + * first, and saves them after they are calculated. + */ + recalculateAndSaveOverlaysForDocumentKeys(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise>; + /** + * Performs a query against the local view of all documents. + * + * @param transaction - The persistence transaction. + * @param query - The query to match documents against. + * @param offset - Read time and key to start scanning by (exclusive). + * @param context - A optional tracker to keep a record of important details + * during database local query execution. + */ + getDocumentsMatchingQuery(transaction: PersistenceTransaction, query: Query_2, offset: IndexOffset, context?: QueryContext): PersistencePromise; + /** + * Given a collection group, returns the next documents that follow the provided offset, along + * with an updated batch ID. + * + *

The documents returned by this method are ordered by remote version from the provided + * offset. If there are no more remote documents after the provided offset, documents with + * mutations in order of batch id from the offset are returned. Since all documents in a batch are + * returned together, the total number of documents returned can exceed {@code count}. + * + * @param transaction + * @param collectionGroup The collection group for the documents. + * @param offset The offset to index into. + * @param count The number of documents to return + * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id. + */ + getNextDocuments(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset, count: number): PersistencePromise; + private getDocumentsMatchingDocumentQuery; + private getDocumentsMatchingCollectionGroupQuery; + private getDocumentsMatchingCollectionQuery; +} + +declare interface LocalStore { + collectGarbage(garbageCollector: LruGarbageCollector): Promise; + /** Manages the list of active field and collection indices. */ + indexManager: IndexManager; + /** + * The "local" view of all documents (layering mutationQueue on top of + * remoteDocumentCache). + */ + localDocuments: LocalDocumentsView; +} + +/** The result of a write to the local store. */ +declare interface LocalWriteResult { + batchId: BatchId; + changes: DocumentMap; +} +export { LogLevel } + +declare interface LruGarbageCollector { + readonly params: LruParams; + collect(txn: PersistenceTransaction, activeTargetIds: ActiveTargets): PersistencePromise; + /** Given a percentile of target to collect, returns the number of targets to collect. */ + calculateTargetCount(txn: PersistenceTransaction, percentile: number): PersistencePromise; + /** Returns the nth sequence number, counting in order from the smallest. */ + nthSequenceNumber(txn: PersistenceTransaction, n: number): PersistencePromise; + /** + * Removes documents that have a sequence number equal to or less than the + * upper bound and are not otherwise pinned. + */ + removeOrphanedDocuments(txn: PersistenceTransaction, upperBound: ListenSequenceNumber): PersistencePromise; + getCacheSize(txn: PersistenceTransaction): PersistencePromise; + /** + * Removes targets with a sequence number equal to or less than the given + * upper bound, and removes document associations with those targets. + */ + removeTargets(txn: PersistenceTransaction, upperBound: ListenSequenceNumber, activeTargetIds: ActiveTargets): PersistencePromise; +} + +declare class LruParams { + readonly cacheSizeCollectionThreshold: number; + readonly percentileToCollect: number; + readonly maximumSequenceNumbersToCollect: number; + private static readonly DEFAULT_COLLECTION_PERCENTILE; + private static readonly DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT; + static withCacheSize(cacheSize: number): LruParams; + static readonly DEFAULT: LruParams; + static readonly DISABLED: LruParams; + constructor(cacheSizeCollectionThreshold: number, percentileToCollect: number, maximumSequenceNumbersToCollect: number); +} + +/** + * Describes the results of a garbage collection run. `didRun` will be set to + * `false` if collection was skipped (either it is disabled or the cache size + * has not hit the threshold). If collection ran, the other fields will be + * filled in with the details of the results. + */ +declare interface LruResults { + readonly didRun: boolean; + readonly sequenceNumbersCollected: number; + readonly targetsRemoved: number; + readonly documentsRemoved: number; +} + +declare type MapValue = firestoreV1ApiClientInterfaces.MapValue; + +/** + * Provides an in-memory cache to the SDK. This is the default cache unless explicitly + * configured otherwise. + * + * To use, create an instance using the factory function {@link memoryLocalCache()}, then + * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using + * the settings object. + */ +declare type MemoryLocalCache = { + kind: 'memory'; + /* Excluded from this release type: _onlineComponentProvider */ + /* Excluded from this release type: _offlineComponentProvider */ +}; + +/** + * Represents a document in Firestore with a key, version, data and whether it + * has local mutations applied to it. + * + * Documents can transition between states via `convertToFoundDocument()`, + * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does + * not transition to one of these states even after all mutations have been + * applied, `isValidDocument()` returns false and the document should be removed + * from all views. + */ +declare class MutableDocument implements Document_2 { + readonly key: DocumentKey; + private documentType; + version: SnapshotVersion; + readTime: SnapshotVersion; + createTime: SnapshotVersion; + data: ObjectValue; + private documentState; + private constructor(); + /** + * Creates a document with no known version or data, but which can serve as + * base document for mutations. + */ + static newInvalidDocument(documentKey: DocumentKey): MutableDocument; + /** + * Creates a new document that is known to exist with the given data at the + * given version. + */ + static newFoundDocument(documentKey: DocumentKey, version: SnapshotVersion, createTime: SnapshotVersion, value: ObjectValue): MutableDocument; + /** Creates a new document that is known to not exist at the given version. */ + static newNoDocument(documentKey: DocumentKey, version: SnapshotVersion): MutableDocument; + /** + * Creates a new document that is known to exist at the given version but + * whose data is not known (e.g. a document that was updated without a known + * base document). + */ + static newUnknownDocument(documentKey: DocumentKey, version: SnapshotVersion): MutableDocument; + /** + * Changes the document type to indicate that it exists and that its version + * and data are known. + */ + convertToFoundDocument(version: SnapshotVersion, value: ObjectValue): MutableDocument; + /** + * Changes the document type to indicate that it doesn't exist at the given + * version. + */ + convertToNoDocument(version: SnapshotVersion): MutableDocument; + /** + * Changes the document type to indicate that it exists at a given version but + * that its data is not known (e.g. a document that was updated without a known + * base document). + */ + convertToUnknownDocument(version: SnapshotVersion): MutableDocument; + setHasCommittedMutations(): MutableDocument; + setHasLocalMutations(): MutableDocument; + setReadTime(readTime: SnapshotVersion): MutableDocument; + get hasLocalMutations(): boolean; + get hasCommittedMutations(): boolean; + get hasPendingWrites(): boolean; + isValidDocument(): boolean; + isFoundDocument(): boolean; + isNoDocument(): boolean; + isUnknownDocument(): boolean; + isEqual(other: Document_2 | null | undefined): boolean; + mutableCopy(): MutableDocument; + toString(): string; +} + +/** Miscellaneous collection types / constants. */ +declare type MutableDocumentMap = SortedMap; + +/** + * A mutation describes a self-contained change to a document. Mutations can + * create, replace, delete, and update subsets of documents. + * + * Mutations not only act on the value of the document but also its version. + * + * For local mutations (mutations that haven't been committed yet), we preserve + * the existing version for Set and Patch mutations. For Delete mutations, we + * reset the version to 0. + * + * Here's the expected transition table. + * + * MUTATION APPLIED TO RESULTS IN + * + * SetMutation Document(v3) Document(v3) + * SetMutation NoDocument(v3) Document(v0) + * SetMutation InvalidDocument(v0) Document(v0) + * PatchMutation Document(v3) Document(v3) + * PatchMutation NoDocument(v3) NoDocument(v3) + * PatchMutation InvalidDocument(v0) UnknownDocument(v3) + * DeleteMutation Document(v3) NoDocument(v0) + * DeleteMutation NoDocument(v3) NoDocument(v0) + * DeleteMutation InvalidDocument(v0) NoDocument(v0) + * + * For acknowledged mutations, we use the updateTime of the WriteResponse as + * the resulting version for Set and Patch mutations. As deletes have no + * explicit update time, we use the commitTime of the WriteResponse for + * Delete mutations. + * + * If a mutation is acknowledged by the backend but fails the precondition check + * locally, we transition to an `UnknownDocument` and rely on Watch to send us + * the updated version. + * + * Field transforms are used only with Patch and Set Mutations. We use the + * `updateTransforms` message to store transforms, rather than the `transforms`s + * messages. + * + * ## Subclassing Notes + * + * Every type of mutation needs to implement its own applyToRemoteDocument() and + * applyToLocalView() to implement the actual behavior of applying the mutation + * to some source document (see `setMutationApplyToRemoteDocument()` for an + * example). + */ +declare abstract class Mutation { + abstract readonly type: MutationType; + abstract readonly key: DocumentKey; + abstract readonly precondition: Precondition; + abstract readonly fieldTransforms: FieldTransform[]; + /** + * Returns a `FieldMask` representing the fields that will be changed by + * applying this mutation. Returns `null` if the mutation will overwrite the + * entire document. + */ + abstract getFieldMask(): FieldMask | null; +} + +/** + * A batch of mutations that will be sent as one unit to the backend. + */ +declare class MutationBatch { + batchId: BatchId; + localWriteTime: Timestamp; + baseMutations: Mutation[]; + mutations: Mutation[]; + /** + * @param batchId - The unique ID of this mutation batch. + * @param localWriteTime - The original write time of this mutation. + * @param baseMutations - Mutations that are used to populate the base + * values when this mutation is applied locally. This can be used to locally + * overwrite values that are persisted in the remote document cache. Base + * mutations are never sent to the backend. + * @param mutations - The user-provided mutations in this mutation batch. + * User-provided mutations are applied both locally and remotely on the + * backend. + */ + constructor(batchId: BatchId, localWriteTime: Timestamp, baseMutations: Mutation[], mutations: Mutation[]); + /** + * Applies all the mutations in this MutationBatch to the specified document + * to compute the state of the remote document + * + * @param document - The document to apply mutations to. + * @param batchResult - The result of applying the MutationBatch to the + * backend. + */ + applyToRemoteDocument(document: MutableDocument, batchResult: MutationBatchResult): void; + /** + * Computes the local view of a document given all the mutations in this + * batch. + * + * @param document - The document to apply mutations to. + * @param mutatedFields - Fields that have been updated before applying this mutation batch. + * @returns A `FieldMask` representing all the fields that are mutated. + */ + applyToLocalView(document: MutableDocument, mutatedFields: FieldMask | null): FieldMask | null; + /** + * Computes the local view for all provided documents given the mutations in + * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to + * replace all the mutation applications. + */ + applyToLocalDocumentSet(documentMap: OverlayedDocumentMap, documentsWithoutRemoteVersion: DocumentKeySet): MutationMap; + keys(): DocumentKeySet; + isEqual(other: MutationBatch): boolean; +} + +/** The result of applying a mutation batch to the backend. */ +declare class MutationBatchResult { + readonly batch: MutationBatch; + readonly commitVersion: SnapshotVersion; + readonly mutationResults: MutationResult[]; + /** + * A pre-computed mapping from each mutated document to the resulting + * version. + */ + readonly docVersions: DocumentVersionMap; + private constructor(); + /** + * Creates a new MutationBatchResult for the given batch and results. There + * must be one result for each mutation in the batch. This static factory + * caches a document=>version mapping (docVersions). + */ + static from(batch: MutationBatch, commitVersion: SnapshotVersion, results: MutationResult[]): MutationBatchResult; +} + +declare type MutationMap = DocumentKeyMap; + +/** A queue of mutations to apply to the remote store. */ +declare interface MutationQueue { + /** Returns true if this queue contains no mutation batches. */ + checkEmpty(transaction: PersistenceTransaction): PersistencePromise; + /** + * Creates a new mutation batch and adds it to this mutation queue. + * + * @param transaction - The transaction this operation is scoped to. + * @param localWriteTime - The original write time of this mutation. + * @param baseMutations - Mutations that are used to populate the base values + * when this mutation is applied locally. These mutations are used to locally + * overwrite values that are persisted in the remote document cache. + * @param mutations - The user-provided mutations in this mutation batch. + */ + addMutationBatch(transaction: PersistenceTransaction, localWriteTime: Timestamp, baseMutations: Mutation[], mutations: Mutation[]): PersistencePromise; + /** + * Loads the mutation batch with the given batchId. + */ + lookupMutationBatch(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + /** + * Gets the first unacknowledged mutation batch after the passed in batchId + * in the mutation queue or null if empty. + * + * @param batchId - The batch to search after, or BATCHID_UNKNOWN for the + * first mutation in the queue. + * + * @returns the next mutation or null if there wasn't one. + */ + getNextMutationBatchAfterBatchId(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + /** + * Gets the largest (latest) batch id in mutation queue for the current user + * that is pending server response, returns `BATCHID_UNKNOWN` if the queue is + * empty. + * + * @returns the largest batch id in the mutation queue that is not + * acknowledged. + */ + getHighestUnacknowledgedBatchId(transaction: PersistenceTransaction): PersistencePromise; + /** Gets all mutation batches in the mutation queue. */ + getAllMutationBatches(transaction: PersistenceTransaction): PersistencePromise; + /** + * Finds all mutation batches that could possibly affect the given + * document key. Not all mutations in a batch will necessarily affect the + * document key, so when looping through the batch you'll need to check that + * the mutation itself matches the key. + * + * Batches are guaranteed to be in sorted order. + * + * Note that because of this requirement implementations are free to return + * mutation batches that don't contain the document key at all if it's + * convenient. + */ + getAllMutationBatchesAffectingDocumentKey(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + /** + * Finds all mutation batches that could possibly affect the given set of + * document keys. Not all mutations in a batch will necessarily affect each + * key, so when looping through the batch you'll need to check that the + * mutation itself matches the key. + * + * Batches are guaranteed to be in sorted order. + * + * Note that because of this requirement implementations are free to return + * mutation batches that don't contain any of the document keys at all if it's + * convenient. + */ + getAllMutationBatchesAffectingDocumentKeys(transaction: PersistenceTransaction, documentKeys: SortedMap): PersistencePromise; + /** + * Finds all mutation batches that could affect the results for the given + * query. Not all mutations in a batch will necessarily affect the query, so + * when looping through the batch you'll need to check that the mutation + * itself matches the query. + * + * Batches are guaranteed to be in sorted order. + * + * Note that because of this requirement implementations are free to return + * mutation batches that don't match the query at all if it's convenient. + * + * NOTE: A PatchMutation does not need to include all fields in the query + * filter criteria in order to be a match (but any fields it does contain do + * need to match). + */ + getAllMutationBatchesAffectingQuery(transaction: PersistenceTransaction, query: Query_2): PersistencePromise; + /** + * Removes the given mutation batch from the queue. This is useful in two + * circumstances: + * + * + Removing an applied mutation from the head of the queue + * + Removing a rejected mutation from anywhere in the queue + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMutationBatch(transaction: PersistenceTransaction, batch: MutationBatch): PersistencePromise; + /** + * Performs a consistency check, examining the mutation queue for any + * leaks, if possible. + */ + performConsistencyCheck(transaction: PersistenceTransaction): PersistencePromise; +} + +/** The result of successfully applying a mutation to the backend. */ +declare class MutationResult { + /** + * The version at which the mutation was committed: + * + * - For most operations, this is the updateTime in the WriteResult. + * - For deletes, the commitTime of the WriteResponse (because deletes are + * not stored and have no updateTime). + * + * Note that these versions can be different: No-op writes will not change + * the updateTime even though the commitTime advances. + */ + readonly version: SnapshotVersion; + /** + * The resulting fields returned from the backend after a mutation + * containing field transforms has been committed. Contains one FieldValue + * for each FieldTransform that was in the mutation. + * + * Will be empty if the mutation did not contain any field transforms. + */ + readonly transformResults: Array; + constructor( + /** + * The version at which the mutation was committed: + * + * - For most operations, this is the updateTime in the WriteResult. + * - For deletes, the commitTime of the WriteResponse (because deletes are + * not stored and have no updateTime). + * + * Note that these versions can be different: No-op writes will not change + * the updateTime even though the commitTime advances. + */ + version: SnapshotVersion, + /** + * The resulting fields returned from the backend after a mutation + * containing field transforms has been committed. Contains one FieldValue + * for each FieldTransform that was in the mutation. + * + * Will be empty if the mutation did not contain any field transforms. + */ + transformResults: Array); +} + +declare const enum MutationType { + Set = 0, + Patch = 1, + Delete = 2, + Verify = 3 +} + +/** + * Represents a Query saved by the SDK in its local storage. + */ +declare interface NamedQuery { + /** The name of the query. */ + readonly name: string; + /** The underlying query associated with `name`. */ + readonly query: Query_2; + /** The time at which the results for this query were read. */ + readonly readTime: SnapshotVersion; +} + +/** Properties of a NamedQuery. */ +declare interface NamedQuery_2 { + /** NamedQuery name */ + name?: string | null; + /** NamedQuery bundledQuery */ + bundledQuery?: BundledQuery | null; + /** NamedQuery readTime */ + readTime?: Timestamp_2 | null; +} + +/** + * For each field (e.g. 'bar'), find all nested keys (e.g. {'bar.baz': T1, + * 'bar.qux': T2}). Intersect them together to make a single map containing + * all possible keys that are all marked as optional + */ +export declare type NestedUpdateFields> = UnionToIntersection<{ + [K in keyof T & string]: ChildUpdateFields; +}[keyof T & string]>; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A map implementation that uses objects as keys. Objects must have an + * associated equals function and must be immutable. Entries in the map are + * stored together with the key being produced from the mapKeyFn. This map + * automatically handles collisions of keys. + */ +declare class ObjectMap { + private mapKeyFn; + private equalsFn; + /** + * The inner map for a key/value pair. Due to the possibility of collisions we + * keep a list of entries that we do a linear search through to find an actual + * match. Note that collisions should be rare, so we still expect near + * constant time lookups in practice. + */ + private inner; + /** The number of entries stored in the map */ + private innerSize; + constructor(mapKeyFn: (key: KeyType) => string, equalsFn: (l: KeyType, r: KeyType) => boolean); + /** Get a value for this key, or undefined if it does not exist. */ + get(key: KeyType): ValueType | undefined; + has(key: KeyType): boolean; + /** Put this key and value in the map. */ + set(key: KeyType, value: ValueType): void; + /** + * Remove this key from the map. Returns a boolean if anything was deleted. + */ + delete(key: KeyType): boolean; + forEach(fn: (key: KeyType, val: ValueType) => void): void; + isEmpty(): boolean; + size(): number; +} + +/** + * An ObjectValue represents a MapValue in the Firestore Proto and offers the + * ability to add and remove fields (via the ObjectValueBuilder). + */ +declare class ObjectValue { + readonly value: { + mapValue: MapValue; + }; + constructor(value: { + mapValue: MapValue; + }); + static empty(): ObjectValue; + /** + * Returns the value at the given path or null. + * + * @param path - the path to search + * @returns The value at the path or null if the path is not set. + */ + field(path: FieldPath_2): Value | null; + /** + * Sets the field to the provided value. + * + * @param path - The field path to set. + * @param value - The value to set. + */ + set(path: FieldPath_2, value: Value): void; + /** + * Sets the provided fields to the provided values. + * + * @param data - A map of fields to values (or null for deletes). + */ + setAll(data: Map): void; + /** + * Removes the field at the specified path. If there is no field at the + * specified path, nothing is changed. + * + * @param path - The field path to remove. + */ + delete(path: FieldPath_2): void; + isEqual(other: ObjectValue): boolean; + /** + * Returns the map that contains the leaf element of `path`. If the parent + * entry does not yet exist, or if it is not a map, a new map will be created. + */ + private getFieldsMap; + /** + * Modifies `fieldsMap` by adding, replacing or deleting the specified + * entries. + */ + private applyChanges; + clone(): ObjectValue; +} + +/** + * Initializes and wires components that are needed to interface with the local + * cache. Implementations override `initialize()` to provide all components. + */ +declare interface OfflineComponentProvider { + readonly kind: Kind; + persistence: Persistence; + sharedClientState: SharedClientState; + localStore: LocalStore; + gcScheduler: Scheduler | null; + indexBackfillerScheduler: Scheduler | null; + synchronizeTabs: boolean; + initialize(cfg: ComponentConfiguration): Promise; + terminate(): Promise; +} + +declare interface OfflineComponentProviderFactory { + build(onlineComponents: OnlineComponentProvider): OfflineComponentProvider; +} + +/** + * Initializes and wires the components that are needed to interface with the + * network. + */ +declare class OnlineComponentProvider { + static readonly provider: OnlineComponentProviderFactory; + protected localStore: LocalStore; + protected sharedClientState: SharedClientState; + datastore: Datastore; + eventManager: EventManager; + remoteStore: RemoteStore; + syncEngine: SyncEngine; + initialize(offlineComponentProvider: OfflineComponentProvider, cfg: ComponentConfiguration): Promise; + createEventManager(cfg: ComponentConfiguration): EventManager; + createDatastore(cfg: ComponentConfiguration): Datastore; + createRemoteStore(cfg: ComponentConfiguration): RemoteStore; + createSyncEngine(cfg: ComponentConfiguration, startAsPrimary: boolean): SyncEngine; + terminate(): Promise; +} + +declare interface OnlineComponentProviderFactory { + build(): OnlineComponentProvider; +} + +/** + * Describes the online state of the Firestore client. Note that this does not + * indicate whether or not the remote store is trying to connect or not. This is + * primarily used by the View / EventManager code to change their behavior while + * offline (e.g. get() calls shouldn't wait for data from the server and + * snapshot events should set metadata.isFromCache=true). + * + * The string values should not be changed since they are persisted in + * WebStorage. + */ +declare const enum OnlineState { + /** + * The Firestore client is in an unknown online state. This means the client + * is either not actively trying to establish a connection or it is currently + * trying to establish a connection, but it has not succeeded or failed yet. + * Higher-level components should not operate in offline mode. + */ + Unknown = "Unknown", + /** + * The client is connected and the connections are healthy. This state is + * reached after a successful connection and there has been at least one + * successful message received from the backends. + */ + Online = "Online", + /** + * The client is either trying to establish a connection but failing, or it + * has been explicitly marked offline via a call to disableNetwork(). + * Higher-level components should operate in offline mode. + */ + Offline = "Offline" +} + +declare const enum Operator { + LESS_THAN = "<", + LESS_THAN_OR_EQUAL = "<=", + EQUAL = "==", + NOT_EQUAL = "!=", + GREATER_THAN = ">", + GREATER_THAN_OR_EQUAL = ">=", + ARRAY_CONTAINS = "array-contains", + IN = "in", + NOT_IN = "not-in", + ARRAY_CONTAINS_ANY = "array-contains-any" +} + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +export declare function or(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; + +/** + * An ordering on a field, in some Direction. Direction defaults to ASCENDING. + */ +declare class OrderBy { + readonly field: FieldPath_2; + readonly dir: Direction; + constructor(field: FieldPath_2, dir?: Direction); +} + +/** + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the + * specified field, optionally in descending order instead of ascending. + * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * + * @param fieldPath - The field to sort by. + * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @returns The created {@link QueryOrderByConstraint}. + */ +export declare function orderBy(fieldPath: string | FieldPath, directionStr?: OrderByDirection): QueryOrderByConstraint; + +/** + * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc' + * (descending or ascending). + */ +export declare type OrderByDirection = 'desc' | 'asc'; + +declare type OrderDirection = 'DIRECTION_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING'; + +/** + * Representation of an overlay computed by Firestore. + * + * Holds information about a mutation and the largest batch id in Firestore when + * the mutation was created. + */ +declare class Overlay { + readonly largestBatchId: number; + readonly mutation: Mutation; + constructor(largestBatchId: number, mutation: Mutation); + getKey(): DocumentKey; + isEqual(other: Overlay | null): boolean; + toString(): string; +} + +/** + * Represents a local view (overlay) of a document, and the fields that are + * locally mutated. + */ +declare class OverlayedDocument { + readonly overlayedDocument: Document_2; + /** + * The fields that are locally mutated by patch mutations. + * + * If the overlayed document is from set or delete mutations, this is `null`. + * If there is no overlay (mutation) for the document, this is an empty `FieldMask`. + */ + readonly mutatedFields: FieldMask | null; + constructor(overlayedDocument: Document_2, + /** + * The fields that are locally mutated by patch mutations. + * + * If the overlayed document is from set or delete mutations, this is `null`. + * If there is no overlay (mutation) for the document, this is an empty `FieldMask`. + */ + mutatedFields: FieldMask | null); +} + +declare type OverlayedDocumentMap = DocumentKeyMap; + +declare type OverlayMap = DocumentKeyMap; + +declare interface ParseContext { + readonly databaseId: DatabaseId; + readonly ignoreUndefinedProperties: boolean; +} + +/** The result of parsing document data (e.g. for a setData call). */ +declare class ParsedSetData { + readonly data: ObjectValue; + readonly fieldMask: FieldMask | null; + readonly fieldTransforms: FieldTransform[]; + constructor(data: ObjectValue, fieldMask: FieldMask | null, fieldTransforms: FieldTransform[]); + toMutation(key: DocumentKey, precondition: Precondition): Mutation; +} + +/** The result of parsing "update" data (i.e. for an updateData call). */ +declare class ParsedUpdateData { + readonly data: ObjectValue; + readonly fieldMask: FieldMask; + readonly fieldTransforms: FieldTransform[]; + constructor(data: ObjectValue, fieldMask: FieldMask, fieldTransforms: FieldTransform[]); + toMutation(key: DocumentKey, precondition: Precondition): Mutation; +} + +/** + * Similar to TypeScript's `Partial`, but allows nested fields to be + * omitted and FieldValues to be passed in as property values. + */ +export declare type PartialWithFieldValue = Partial | (T extends Primitive ? T : T extends {} ? { + [K in keyof T]?: PartialWithFieldValue | FieldValue; +} : never); + +/** + * Persistence is the lowest-level shared interface to persistent storage in + * Firestore. + * + * Persistence is used to create MutationQueue and RemoteDocumentCache + * instances backed by persistence (which might be in-memory or LevelDB). + * + * Persistence also exposes an API to create and run PersistenceTransactions + * against persistence. All read / write operations must be wrapped in a + * transaction. Implementations of PersistenceTransaction / Persistence only + * need to guarantee that writes made against the transaction are not made to + * durable storage until the transaction resolves its PersistencePromise. + * Since memory-only storage components do not alter durable storage, they are + * free to ignore the transaction. + * + * This contract is enough to allow the LocalStore be be written + * independently of whether or not the stored state actually is durably + * persisted. If persistent storage is enabled, writes are grouped together to + * avoid inconsistent state that could cause crashes. + * + * Concretely, when persistent storage is enabled, the persistent versions of + * MutationQueue, RemoteDocumentCache, and others (the mutators) will + * defer their writes into a transaction. Once the local store has completed + * one logical operation, it commits the transaction. + * + * When persistent storage is disabled, the non-persistent versions of the + * mutators ignore the transaction. This short-cut is allowed because + * memory-only storage leaves no state so it cannot be inconsistent. + * + * This simplifies the implementations of the mutators and allows memory-only + * implementations to supplement the persistent ones without requiring any + * special dual-store implementation of Persistence. The cost is that the + * LocalStore needs to be slightly careful about the order of its reads and + * writes in order to avoid relying on being able to read back uncommitted + * writes. + */ +declare interface Persistence { + /** + * Whether or not this persistence instance has been started. + */ + readonly started: boolean; + readonly referenceDelegate: ReferenceDelegate; + /** Starts persistence. */ + start(): Promise; + /** + * Releases any resources held during eager shutdown. + */ + shutdown(): Promise; + /** + * Registers a listener that gets called when the database receives a + * version change event indicating that it has deleted. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setDatabaseDeletedListener(databaseDeletedListener: () => Promise): void; + /** + * Adjusts the current network state in the client's metadata, potentially + * affecting the primary lease. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setNetworkEnabled(networkEnabled: boolean): void; + /** + * Returns GlobalCache representing a general purpose cache for global values. + */ + getGlobalsCache(): GlobalsCache; + /** + * Returns a MutationQueue representing the persisted mutations for the + * given user. + * + * Note: The implementation is free to return the same instance every time + * this is called for a given user. In particular, the memory-backed + * implementation does this to emulate the persisted implementation to the + * extent possible (e.g. in the case of uid switching from + * sally=>jack=>sally, sally's mutation queue will be preserved). + */ + getMutationQueue(user: User, indexManager: IndexManager): MutationQueue; + /** + * Returns a TargetCache representing the persisted cache of targets. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getTargetCache(): TargetCache; + /** + * Returns a RemoteDocumentCache representing the persisted cache of remote + * documents. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getRemoteDocumentCache(): RemoteDocumentCache; + /** + * Returns a BundleCache representing the persisted cache of loaded bundles. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getBundleCache(): BundleCache; + /** + * Returns an IndexManager instance that manages our persisted query indexes. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getIndexManager(user: User): IndexManager; + /** + * Returns a DocumentOverlayCache representing the documents that are mutated + * locally. + */ + getDocumentOverlayCache(user: User): DocumentOverlayCache; + /** + * Performs an operation inside a persistence transaction. Any reads or writes + * against persistence must be performed within a transaction. Writes will be + * committed atomically once the transaction completes. + * + * Persistence operations are asynchronous and therefore the provided + * transactionOperation must return a PersistencePromise. When it is resolved, + * the transaction will be committed and the Promise returned by this method + * will resolve. + * + * @param action - A description of the action performed by this transaction, + * used for logging. + * @param mode - The underlying mode of the IndexedDb transaction. Can be + * 'readonly', 'readwrite' or 'readwrite-primary'. Transactions marked + * 'readwrite-primary' can only be executed by the primary client. In this + * mode, the transactionOperation will not be run if the primary lease cannot + * be acquired and the returned promise will be rejected with a + * FAILED_PRECONDITION error. + * @param transactionOperation - The operation to run inside a transaction. + * @returns A `Promise` that is resolved once the transaction completes. + */ + runTransaction(action: string, mode: PersistenceTransactionMode, transactionOperation: (transaction: PersistenceTransaction) => PersistencePromise): Promise; +} + +/** + * PersistencePromise is essentially a re-implementation of Promise except + * it has a .next() method instead of .then() and .next() and .catch() callbacks + * are executed synchronously when a PersistencePromise resolves rather than + * asynchronously (Promise implementations use setImmediate() or similar). + * + * This is necessary to interoperate with IndexedDB which will automatically + * commit transactions if control is returned to the event loop without + * synchronously initiating another operation on the transaction. + * + * NOTE: .then() and .catch() only allow a single consumer, unlike normal + * Promises. + */ +declare class PersistencePromise { + private nextCallback; + private catchCallback; + private result; + private error; + private isDone; + private callbackAttached; + constructor(callback: (resolve: Resolver, reject: Rejector) => void); + catch(fn: (error: Error) => R | PersistencePromise): PersistencePromise; + next(nextFn?: FulfilledHandler, catchFn?: RejectedHandler): PersistencePromise; + toPromise(): Promise; + private wrapUserFunction; + private wrapSuccess; + private wrapFailure; + static resolve(): PersistencePromise; + static resolve(result: R): PersistencePromise; + static reject(error: Error): PersistencePromise; + static waitFor(all: { + forEach: (cb: (el: PersistencePromise) => void) => void; + }): PersistencePromise; + /** + * Given an array of predicate functions that asynchronously evaluate to a + * boolean, implements a short-circuiting `or` between the results. Predicates + * will be evaluated until one of them returns `true`, then stop. The final + * result will be whether any of them returned `true`. + */ + static or(predicates: Array<() => PersistencePromise>): PersistencePromise; + /** + * Given an iterable, call the given function on each element in the + * collection and wait for all of the resulting concurrent PersistencePromises + * to resolve. + */ + static forEach(collection: { + forEach: (cb: (r: R, s: S) => void) => void; + }, f: ((r: R, s: S) => PersistencePromise) | ((r: R) => PersistencePromise)): PersistencePromise; + static forEach(collection: { + forEach: (cb: (r: R) => void) => void; + }, f: (r: R) => PersistencePromise): PersistencePromise; + /** + * Concurrently map all array elements through asynchronous function. + */ + static mapArray(array: T[], f: (t: T) => PersistencePromise): PersistencePromise; + /** + * An alternative to recursive PersistencePromise calls, that avoids + * potential memory problems from unbounded chains of promises. + * + * The `action` will be called repeatedly while `condition` is true. + */ + static doWhile(condition: () => boolean, action: () => PersistencePromise): PersistencePromise; +} + +/** + * A base class representing a persistence transaction, encapsulating both the + * transaction's sequence numbers as well as a list of onCommitted listeners. + * + * When you call Persistence.runTransaction(), it will create a transaction and + * pass it to your callback. You then pass it to any method that operates + * on persistence. + */ +declare abstract class PersistenceTransaction { + private readonly onCommittedListeners; + abstract readonly currentSequenceNumber: ListenSequenceNumber; + addOnCommittedListener(listener: () => void): void; + raiseOnCommittedEvent(): void; +} + +/** The different modes supported by `Persistence.runTransaction()`. */ +declare type PersistenceTransactionMode = 'readonly' | 'readwrite' | 'readwrite-primary'; + +/** + * Provides a persistent cache backed by IndexedDb to the SDK. + * + * To use, create an instance using the factory function {@link persistentLocalCache()}, then + * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using + * the settings object. + */ +declare type PersistentLocalCache = { + kind: 'persistent'; + /* Excluded from this release type: _onlineComponentProvider */ + /* Excluded from this release type: _offlineComponentProvider */ +}; + +/** + * Encodes a precondition for a mutation. This follows the model that the + * backend accepts with the special case of an explicit "empty" precondition + * (meaning no precondition). + */ +declare class Precondition { + readonly updateTime?: SnapshotVersion | undefined; + readonly exists?: boolean | undefined; + private constructor(); + /** Creates a new empty Precondition. */ + static none(): Precondition; + /** Creates a new Precondition with an exists flag. */ + static exists(exists: boolean): Precondition; + /** Creates a new Precondition based on a version a document exists at. */ + static updateTime(version: SnapshotVersion): Precondition; + /** Returns whether this Precondition is empty. */ + get isNone(): boolean; + isEqual(other: Precondition): boolean; +} + +/** + * These types primarily exist to support the `UpdateData`, + * `WithFieldValue`, and `PartialWithFieldValue` types and are not consumed + * directly by the end developer. + */ +/** Primitive types. */ +export declare type Primitive = string | number | boolean | undefined | null; + +/* Excluded from this release type: PrivateSettings */ + +/* Excluded from this release type: Property */ + +declare interface ProviderCredentialsSettings { + ['type']: 'provider'; + ['client']: CredentialsProvider; +} + +/** + * A `Query` refers to a query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ +export declare class Query { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter | null; + readonly _query: Query_2; + /** The type of this Firestore reference. */ + readonly type: 'query' | 'collection'; + /** + * The `Firestore` instance for the Firestore database (useful for performing + * transactions, etc.). + */ + readonly firestore: Firestore; + /** @hideconstructor protected */ + constructor(firestore: Firestore, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter: FirestoreDataConverter | null, _query: Query_2); + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `Query` that does not use a + * converter. + */ + withConverter(converter: null): Query; + /** + * Applies a custom data converter to this query, allowing you to use your own + * custom model objects with Firestore. When you call {@link getDocs} with + * the returned query, the provided converter will convert between Firestore + * data of type `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `Query` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter): Query; +} + +/** + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. + * + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to + * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or + * {@link or}. + * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to + * apply (e.g. {@link orderBy}, {@link limit}). + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query(query: Query, compositeFilter: QueryCompositeFilterConstraint, ...queryConstraints: QueryNonFilterConstraint[]): Query; + +/** + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. + * + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param queryConstraints - The list of {@link QueryConstraint}s to apply. + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query(query: Query, ...queryConstraints: QueryConstraint[]): Query; + +/** + * The Query interface defines all external properties of a query. + * + * QueryImpl implements this interface to provide memoization for `queryNormalizedOrderBy` + * and `queryToTarget`. + */ +declare interface Query_2 { + readonly path: ResourcePath; + readonly collectionGroup: string | null; + readonly explicitOrderBy: OrderBy[]; + readonly filters: Filter[]; + readonly limit: number | null; + readonly limitType: LimitType; + readonly startAt: Bound | null; + readonly endAt: Bound | null; +} + +/** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ +export declare class QueryCompositeFilterConstraint extends AppliableConstraint { + /** The type of this query constraint */ + readonly type: 'or' | 'and'; + private readonly _queryConstraints; + /* Excluded from this release type: __constructor */ + static _create(type: 'or' | 'and', _queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; + _parse(query: Query): Filter; + _apply(query: Query): Query; + _getQueryConstraints(): readonly AppliableConstraint[]; + _getOperator(): CompositeOperator; +} + +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Firestore query. `QueryConstraint`s are created by invoking {@link where}, + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that + * also contains this `QueryConstraint`. + */ +export declare abstract class QueryConstraint extends AppliableConstraint { + /** The type of this query constraint */ + abstract readonly type: QueryConstraintType; + /** + * Takes the provided {@link Query} and returns a copy of the {@link Query} with this + * {@link AppliableConstraint} applied. + */ + abstract _apply(query: Query): Query; +} + +/** Describes the different query constraints available in this SDK. */ +export declare type QueryConstraintType = 'where' | 'orderBy' | 'limit' | 'limitToLast' | 'startAt' | 'startAfter' | 'endAt' | 'endBefore'; + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A tracker to keep a record of important details during database local query + * execution. + */ +declare class QueryContext { + /** + * Counts the number of documents passed through during local query execution. + */ + private _documentReadCount; + get documentReadCount(): number; + incrementDocumentReadCount(amount: number): void; +} + +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ +export declare class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * @override + * @returns An `Object` containing all fields in the document. + */ + data(): AppModelType; +} + +/** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ +export declare class QueryEndAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'endBefore' | 'endAt'; + private readonly _docOrFields; + private readonly _inclusive; + /* Excluded from this release type: __constructor */ + static _create(type: 'endBefore' | 'endAt', _docOrFields: Array>, _inclusive: boolean): QueryEndAtConstraint; + _apply(query: Query): Query; +} + +/** + * Returns true if the provided queries point to the same collection and apply + * the same constraints. + * + * @param left - A `Query` to compare. + * @param right - A `Query` to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +export declare function queryEqual(left: Query, right: Query): boolean; + +/** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ +export declare class QueryFieldFilterConstraint extends QueryConstraint { + private readonly _field; + private _op; + private _value; + /** The type of this query constraint */ + readonly type = "where"; + /* Excluded from this release type: __constructor */ + static _create(_field: FieldPath_2, _op: Operator, _value: unknown): QueryFieldFilterConstraint; + _apply(query: Query): Query; + _parse(query: Query): FieldFilter; +} + +/** + * `QueryFilterConstraint` is a helper union type that represents + * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}. + */ +export declare type QueryFilterConstraint = QueryFieldFilterConstraint | QueryCompositeFilterConstraint; + +/** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ +export declare class QueryLimitConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'limit' | 'limitToLast'; + private readonly _limit; + private readonly _limitType; + /* Excluded from this release type: __constructor */ + static _create(type: 'limit' | 'limitToLast', _limit: number, _limitType: LimitType): QueryLimitConstraint; + _apply(query: Query): Query; +} + +/** + * `QueryNonFilterConstraint` is a helper union type that represents + * QueryConstraints which are used to narrow or order the set of documents, + * but that do not explicitly filter on a document field. + * `QueryNonFilterConstraint`s are created by invoking {@link orderBy}, + * {@link (startAt:1)}, {@link (startAfter:1)}, {@link (endBefore:1)}, {@link (endAt:1)}, + * {@link limit} or {@link limitToLast} and can then be passed to {@link (query:1)} + * to create a new query instance that also contains the `QueryConstraint`. + */ +export declare type QueryNonFilterConstraint = QueryOrderByConstraint | QueryLimitConstraint | QueryStartAtConstraint | QueryEndAtConstraint; + +/** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ +export declare class QueryOrderByConstraint extends QueryConstraint { + private readonly _field; + private _direction; + /** The type of this query constraint */ + readonly type = "orderBy"; + /* Excluded from this release type: __constructor */ + static _create(_field: FieldPath_2, _direction: Direction): QueryOrderByConstraint; + _apply(query: Query): Query; +} + +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ +export declare class QuerySnapshot { + readonly _docs: Array>; + /** + * The query on which you called {@link getDocs} in order to get this + * `QuerySnapshot`. + */ + readonly query: Query; + /** @hideconstructor */ + constructor(_query: Query, _docs: Array>); + /** An array of all the documents in the `QuerySnapshot`. */ + get docs(): Array>; + /** The number of documents in the `QuerySnapshot`. */ + get size(): number; + /** True if there are no documents in the `QuerySnapshot`. */ + get empty(): boolean; + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ + forEach(callback: (result: QueryDocumentSnapshot) => void, thisArg?: unknown): void; +} + +/** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ +export declare class QueryStartAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'startAt' | 'startAfter'; + private readonly _docOrFields; + private readonly _inclusive; + /* Excluded from this release type: __constructor */ + static _create(type: 'startAt' | 'startAfter', _docOrFields: Array>, _inclusive: boolean): QueryStartAtConstraint; + _apply(query: Query): Query; +} + +/** The different states of a watch target. */ +declare type QueryTargetState = 'not-current' | 'current' | 'rejected'; + +/** + * Returns true if the provided references are equal. + * + * @param left - A reference to compare. + * @param right - A reference to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +export declare function refEqual(left: DocumentReference | CollectionReference, right: DocumentReference | CollectionReference): boolean; + +/** + * A ReferenceDelegate instance handles all of the hooks into the document-reference lifecycle. This + * includes being added to a target, being removed from a target, being subject to mutation, and + * being mutated by the user. + * + * Different implementations may do different things with each of these events. Not every + * implementation needs to do something with every lifecycle hook. + * + * PORTING NOTE: since sequence numbers are attached to transactions in this + * client, the ReferenceDelegate does not need to deal in transactional + * semantics (onTransactionStarted/Committed()), nor does it need to track and + * generate sequence numbers (getCurrentSequenceNumber()). + */ +declare interface ReferenceDelegate { + /** Notify the delegate that the given document was added to a target. */ + addReference(txn: PersistenceTransaction, targetId: TargetId, doc: DocumentKey): PersistencePromise; + /** Notify the delegate that the given document was removed from a target. */ + removeReference(txn: PersistenceTransaction, targetId: TargetId, doc: DocumentKey): PersistencePromise; + /** + * Notify the delegate that a target was removed. The delegate may, but is not obligated to, + * actually delete the target and associated data. + */ + removeTarget(txn: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Notify the delegate that a document may no longer be part of any views or + * have any mutations associated. + */ + markPotentiallyOrphaned(txn: PersistenceTransaction, doc: DocumentKey): PersistencePromise; + /** Notify the delegate that a limbo document was updated. */ + updateLimboDocument(txn: PersistenceTransaction, doc: DocumentKey): PersistencePromise; +} + +declare type RejectedHandler = ((reason: Error) => R | PersistencePromise) | null; + +declare type Rejector = (error: Error) => void; + +/** + * Represents cached documents received from the remote backend. + * + * The cache is keyed by DocumentKey and entries in the cache are + * MutableDocuments, meaning we can cache both actual documents as well as + * documents that are known to not exist. + */ +declare interface RemoteDocumentCache { + /** Sets the index manager to use for managing the collectionGroup index. */ + setIndexManager(indexManager: IndexManager): void; + /** + * Looks up an entry in the cache. + * + * @param documentKey - The key of the entry to look up.* + * @returns The cached document entry. Returns an invalid document if the + * document is not cached. + */ + getEntry(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + /** + * Looks up a set of entries in the cache. + * + * @param documentKeys - The keys of the entries to look up. + * @returns The cached document entries indexed by key. If an entry is not + * cached, the corresponding key will be mapped to an invalid document. + */ + getEntries(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise; + /** + * Returns the documents matching the given query + * + * @param query - The query to match documents against. + * @param offset - The offset to start the scan at (exclusive). + * @param context - A optional tracker to keep a record of important details + * during database local query execution. + * @returns The set of matching documents. + */ + getDocumentsMatchingQuery(transaction: PersistenceTransaction, query: Query_2, offset: IndexOffset, mutatedDocs: OverlayMap, context?: QueryContext): PersistencePromise; + /** + * Looks up the next `limit` documents for a collection group based on the + * provided offset. The ordering is based on the document's read time and key. + * + * @param collectionGroup - The collection group to scan. + * @param offset - The offset to start the scan at (exclusive). + * @param limit - The maximum number of results to return. + * @returns The set of matching documents. + */ + getAllFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset, limit: number): PersistencePromise; + /** + * Provides access to add or update the contents of the cache. The buffer + * handles proper size accounting for the change. + * + * Multi-Tab Note: This should only be called by the primary client. + * + * @param options - Specify `trackRemovals` to create sentinel entries for + * removed documents, which allows removals to be tracked by + * `getNewDocumentChanges()`. + */ + newChangeBuffer(options?: { + trackRemovals: boolean; + }): RemoteDocumentChangeBuffer; + /** + * Get an estimate of the size of the document cache. Note that for eager + * garbage collection, we don't track sizes so this will return 0. + */ + getSize(transaction: PersistenceTransaction): PersistencePromise; +} + +/** + * An in-memory buffer of entries to be written to a RemoteDocumentCache. + * It can be used to batch up a set of changes to be written to the cache, but + * additionally supports reading entries back with the `getEntry()` method, + * falling back to the underlying RemoteDocumentCache if no entry is + * buffered. + * + * Entries added to the cache *must* be read first. This is to facilitate + * calculating the size delta of the pending changes. + * + * PORTING NOTE: This class was implemented then removed from other platforms. + * If byte-counting ends up being needed on the other platforms, consider + * porting this class as part of that implementation work. + */ +declare abstract class RemoteDocumentChangeBuffer { + protected changes: ObjectMap; + private changesApplied; + protected abstract getFromCache(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + protected abstract getAllFromCache(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise; + protected abstract applyChanges(transaction: PersistenceTransaction): PersistencePromise; + /** + * Buffers a `RemoteDocumentCache.addEntry()` call. + * + * You can only modify documents that have already been retrieved via + * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). + */ + addEntry(document: MutableDocument): void; + /** + * Buffers a `RemoteDocumentCache.removeEntry()` call. + * + * You can only remove documents that have already been retrieved via + * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). + */ + removeEntry(key: DocumentKey, readTime: SnapshotVersion): void; + /** + * Looks up an entry in the cache. The buffered changes will first be checked, + * and if no buffered change applies, this will forward to + * `RemoteDocumentCache.getEntry()`. + * + * @param transaction - The transaction in which to perform any persistence + * operations. + * @param documentKey - The key of the entry to look up. + * @returns The cached document or an invalid document if we have nothing + * cached. + */ + getEntry(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + /** + * Looks up several entries in the cache, forwarding to + * `RemoteDocumentCache.getEntry()`. + * + * @param transaction - The transaction in which to perform any persistence + * operations. + * @param documentKeys - The keys of the entries to look up. + * @returns A map of cached documents, indexed by key. If an entry cannot be + * found, the corresponding key will be mapped to an invalid document. + */ + getEntries(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise; + /** + * Applies buffered changes to the underlying RemoteDocumentCache, using + * the provided transaction. + */ + apply(transaction: PersistenceTransaction): PersistencePromise; + /** Helper to assert this.changes is not null */ + protected assertNotApplied(): void; +} + +/** + * An event from the RemoteStore. It is split into targetChanges (changes to the + * state or the set of documents in our watched targets) and documentUpdates + * (changes to the actual documents). + */ +declare class RemoteEvent { + /** + * The snapshot version this event brings us up to, or MIN if not set. + */ + readonly snapshotVersion: SnapshotVersion; + /** + * A map from target to changes to the target. See TargetChange. + */ + readonly targetChanges: Map; + /** + * A map of targets that is known to be inconsistent, and the purpose for + * re-listening. Listens for these targets should be re-established without + * resume tokens. + */ + readonly targetMismatches: SortedMap; + /** + * A set of which documents have changed or been deleted, along with the + * doc's new values (if not deleted). + */ + readonly documentUpdates: MutableDocumentMap; + /** + * A set of which document updates are due only to limbo resolution targets. + */ + readonly resolvedLimboDocuments: DocumentKeySet; + constructor( + /** + * The snapshot version this event brings us up to, or MIN if not set. + */ + snapshotVersion: SnapshotVersion, + /** + * A map from target to changes to the target. See TargetChange. + */ + targetChanges: Map, + /** + * A map of targets that is known to be inconsistent, and the purpose for + * re-listening. Listens for these targets should be re-established without + * resume tokens. + */ + targetMismatches: SortedMap, + /** + * A set of which documents have changed or been deleted, along with the + * doc's new values (if not deleted). + */ + documentUpdates: MutableDocumentMap, + /** + * A set of which document updates are due only to limbo resolution targets. + */ + resolvedLimboDocuments: DocumentKeySet); + /** + * HACK: Views require RemoteEvents in order to determine whether the view is + * CURRENT, but secondary tabs don't receive remote events. So this method is + * used to create a synthesized RemoteEvent that can be used to apply a + * CURRENT status change to a View, for queries executed in a different tab. + */ + static createSynthesizedRemoteEventForCurrentChange(targetId: TargetId, current: boolean, resumeToken: ByteString): RemoteEvent; +} + +/** + * RemoteStore - An interface to remotely stored data, basically providing a + * wrapper around the Datastore that is more reliable for the rest of the + * system. + * + * RemoteStore is responsible for maintaining the connection to the server. + * - maintaining a list of active listens. + * - reconnecting when the connection is dropped. + * - resuming all the active listens on reconnect. + * + * RemoteStore handles all incoming events from the Datastore. + * - listening to the watch stream and repackaging the events as RemoteEvents + * - notifying SyncEngine of any changes to the active listens. + * + * RemoteStore takes writes from other components and handles them reliably. + * - pulling pending mutations from LocalStore and sending them to Datastore. + * - retrying mutations that failed because of network problems. + * - acking mutations to the SyncEngine once they are accepted or rejected. + */ +declare interface RemoteStore { + /** + * SyncEngine to notify of watch and write events. This must be set + * immediately after construction. + */ + remoteSyncer: RemoteSyncer; +} + +/** + * An interface that describes the actions the RemoteStore needs to perform on + * a cooperating synchronization engine. + */ +declare interface RemoteSyncer { + /** + * Applies one remote event to the sync engine, notifying any views of the + * changes, and releasing any pending mutation batches that would become + * visible because of the snapshot version the remote event contains. + */ + applyRemoteEvent?(remoteEvent: RemoteEvent): Promise; + /** + * Rejects the listen for the given targetID. This can be triggered by the + * backend for any active target. + * + * @param targetId - The targetID corresponds to one previously initiated by + * the user as part of TargetData passed to listen() on RemoteStore. + * @param error - A description of the condition that has forced the rejection. + * Nearly always this will be an indication that the user is no longer + * authorized to see the data matching the target. + */ + rejectListen?(targetId: TargetId, error: FirestoreError): Promise; + /** + * Applies the result of a successful write of a mutation batch to the sync + * engine, emitting snapshots in any views that the mutation applies to, and + * removing the batch from the mutation queue. + */ + applySuccessfulWrite?(result: MutationBatchResult): Promise; + /** + * Rejects the batch, removing the batch from the mutation queue, recomputing + * the local view of any documents affected by the batch and then, emitting + * snapshots with the reverted value. + */ + rejectFailedWrite?(batchId: BatchId, error: FirestoreError): Promise; + /** + * Returns the set of remote document keys for the given target ID. This list + * includes the documents that were assigned to the target when we received + * the last snapshot. + */ + getRemoteKeysForTarget?(targetId: TargetId): DocumentKeySet; + /** + * Updates all local state to match the pending mutations for the given user. + * May be called repeatedly for the same user. + */ + handleCredentialChange?(user: User): Promise; +} + +declare type Resolver = (value?: T) => void; + +/* Excluded from this release type: ResourcePath */ + +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ +export declare function runTransaction(firestore: Firestore, updateFunction: (transaction: Transaction) => Promise, options?: TransactionOptions): Promise; + +/** + * Interface to schedule periodic tasks within SDK. + */ +declare interface Scheduler { + readonly started: boolean; + start(): void; + stop(): void; +} + +/** Base interface for the Serializer implementation. */ +declare interface Serializer { + readonly useProto3Json: boolean; +} + +/** + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to + * include a server-generated timestamp in the written data. + */ +export declare function serverTimestamp(): FieldValue; + +declare type ServerTimestampBehavior = 'estimate' | 'previous' | 'none'; + +/** + * Writes to the document referred to by the specified `DocumentReference`. If + * the document does not yet exist, it will be created. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function setDoc(reference: DocumentReference, data: WithFieldValue): Promise; + +/** + * Writes to the document referred to by the specified `DocumentReference`. If + * the document does not yet exist, it will be created. If you provide `merge` + * or `mergeFields`, the provided data can be merged into an existing document. + * + * The result of this write will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function setDoc(reference: DocumentReference, data: PartialWithFieldValue, options: SetOptions): Promise; + +/** + * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). + * + * @param logLevel - The verbosity you set for activity and error logging. Can + * be any of the following values: + * + *

    + *
  • `debug` for the most verbose logging level, primarily for + * debugging.
  • + *
  • `error` to log errors only.
  • + *
  • `silent` to turn off logging.
  • + *
+ */ +export declare function setLogLevel(logLevel: LogLevel): void; + +/** + * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link + * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be + * configured to perform granular merges instead of overwriting the target + * documents in their entirety by providing a `SetOptions` with `merge: true`. + * + * @param merge - Changes the behavior of a `setDoc()` call to only replace the + * values specified in its data argument. Fields omitted from the `setDoc()` + * call remain untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace + * the specified field paths. Any field path that is not specified is ignored + * and remains untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + */ +export declare type SetOptions = { + readonly merge?: boolean; +} | { + readonly mergeFields?: Array; +}; + +/** + * Specifies custom configurations for your Cloud Firestore instance. + * You must set these before invoking any other methods. + */ +export declare interface Settings { + /** The hostname to connect to. */ + host?: string; + /** Whether to use SSL when connecting. */ + ssl?: boolean; + /** + * Whether to skip nested properties that are set to `undefined` during + * object serialization. If set to `true`, these properties are skipped + * and not written to Firestore. If set to `false` or omitted, the SDK + * throws an exception when it encounters properties of type `undefined`. + */ + ignoreUndefinedProperties?: boolean; +} + +/** + * A `SharedClientState` keeps track of the global state of the mutations + * and query targets for all active clients with the same persistence key (i.e. + * project ID and FirebaseApp name). It relays local changes to other clients + * and updates its local state as new state is observed. + * + * `SharedClientState` is primarily used for synchronization in Multi-Tab + * environments. Each tab is responsible for registering its active query + * targets and mutations. `SharedClientState` will then notify the listener + * assigned to `.syncEngine` for updates to mutations and queries that + * originated in other clients. + * + * To receive notifications, `.syncEngine` and `.onlineStateHandler` has to be + * assigned before calling `start()`. + */ +declare interface SharedClientState { + onlineStateHandler: ((onlineState: OnlineState) => void) | null; + sequenceNumberHandler: ((sequenceNumber: ListenSequenceNumber) => void) | null; + /** Registers the Mutation Batch ID of a newly pending mutation. */ + addPendingMutation(batchId: BatchId): void; + /** + * Records that a pending mutation has been acknowledged or rejected. + * Called by the primary client to notify secondary clients of mutation + * results as they come back from the backend. + */ + updateMutationState(batchId: BatchId, state: 'acknowledged' | 'rejected', error?: FirestoreError): void; + /** + * Associates a new Query Target ID with the local Firestore client. Returns + * the new query state for the query (which can be 'current' if the query is + * already associated with another tab). + * + * If the target id is already associated with local client, the method simply + * returns its `QueryTargetState`. + */ + addLocalQueryTarget(targetId: TargetId, addToActiveTargetIds?: boolean): QueryTargetState; + /** Removes the Query Target ID association from the local client. */ + removeLocalQueryTarget(targetId: TargetId): void; + /** Checks whether the target is associated with the local client. */ + isLocalQueryTarget(targetId: TargetId): boolean; + /** + * Processes an update to a query target. + * + * Called by the primary client to notify secondary clients of document + * changes or state transitions that affect the provided query target. + */ + updateQueryState(targetId: TargetId, state: QueryTargetState, error?: FirestoreError): void; + /** + * Removes the target's metadata entry. + * + * Called by the primary client when all clients stopped listening to a query + * target. + */ + clearQueryState(targetId: TargetId): void; + /** + * Gets the active Query Targets IDs for all active clients. + * + * The implementation for this may require O(n) runtime, where 'n' is the size + * of the result set. + */ + getAllActiveQueryTargets(): SortedSet; + /** + * Checks whether the provided target ID is currently being listened to by + * any of the active clients. + * + * The implementation may require O(n*log m) runtime, where 'n' is the number + * of clients and 'm' the number of targets. + */ + isActiveQueryTarget(targetId: TargetId): boolean; + /** + * Starts the SharedClientState, reads existing client data and registers + * listeners for updates to new and existing clients. + */ + start(): Promise; + /** Shuts down the `SharedClientState` and its listeners. */ + shutdown(): void; + /** + * Changes the active user and removes all existing user-specific data. The + * user change does not call back into SyncEngine (for example, no mutations + * will be marked as removed). + */ + handleUserChange(user: User, removedBatchIds: BatchId[], addedBatchIds: BatchId[]): void; + /** Changes the shared online state of all clients. */ + setOnlineState(onlineState: OnlineState): void; + writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void; + /** + * Notifies other clients when remote documents have changed due to loading + * a bundle. + * + * @param collectionGroups The collection groups affected by this bundle. + */ + notifyBundleLoaded(collectionGroups: Set): void; +} + +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ +export declare function snapshotEqual(left: DocumentSnapshot | QuerySnapshot, right: DocumentSnapshot | QuerySnapshot): boolean; + +/** + * A version of a document in Firestore. This corresponds to the version + * timestamp, such as update_time or read_time. + */ +declare class SnapshotVersion { + private timestamp; + static fromTimestamp(value: Timestamp): SnapshotVersion; + static min(): SnapshotVersion; + static max(): SnapshotVersion; + private constructor(); + compareTo(other: SnapshotVersion): number; + isEqual(other: SnapshotVersion): boolean; + /** Returns a number representation of the version for use in spec tests. */ + toMicroseconds(): number; + toString(): string; + toTimestamp(): Timestamp; +} + +declare class SortedMap { + comparator: Comparator; + root: LLRBNode | LLRBEmptyNode; + constructor(comparator: Comparator, root?: LLRBNode | LLRBEmptyNode); + insert(key: K, value: V): SortedMap; + remove(key: K): SortedMap; + get(key: K): V | null; + indexOf(key: K): number; + isEmpty(): boolean; + get size(): number; + minKey(): K | null; + maxKey(): K | null; + inorderTraversal(action: (k: K, v: V) => T): T; + forEach(fn: (k: K, v: V) => void): void; + toString(): string; + reverseTraversal(action: (k: K, v: V) => T): T; + getIterator(): SortedMapIterator; + getIteratorFrom(key: K): SortedMapIterator; + getReverseIterator(): SortedMapIterator; + getReverseIteratorFrom(key: K): SortedMapIterator; +} + +declare class SortedMapIterator { + private isReverse; + private nodeStack; + constructor(node: LLRBNode | LLRBEmptyNode, startKey: K | null, comparator: Comparator, isReverse: boolean); + getNext(): Entry; + hasNext(): boolean; + peek(): Entry | null; +} + +/** + * SortedSet is an immutable (copy-on-write) collection that holds elements + * in order specified by the provided comparator. + * + * NOTE: if provided comparator returns 0 for two elements, we consider them to + * be equal! + */ +declare class SortedSet { + private comparator; + private data; + constructor(comparator: (left: T, right: T) => number); + has(elem: T): boolean; + first(): T | null; + last(): T | null; + get size(): number; + indexOf(elem: T): number; + /** Iterates elements in order defined by "comparator" */ + forEach(cb: (elem: T) => void): void; + /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ + forEachInRange(range: [T, T], cb: (elem: T) => void): void; + /** + * Iterates over `elem`s such that: start <= elem until false is returned. + */ + forEachWhile(cb: (elem: T) => boolean, start?: T): void; + /** Finds the least element greater than or equal to `elem`. */ + firstAfterOrEqual(elem: T): T | null; + getIterator(): SortedSetIterator; + getIteratorFrom(key: T): SortedSetIterator; + /** Inserts or updates an element */ + add(elem: T): SortedSet; + /** Deletes an element */ + delete(elem: T): SortedSet; + isEmpty(): boolean; + unionWith(other: SortedSet): SortedSet; + isEqual(other: SortedSet): boolean; + toArray(): T[]; + toString(): string; + private copy; +} + +declare class SortedSetIterator { + private iter; + constructor(iter: SortedMapIterator); + getNext(): T; + hasNext(): boolean; +} + +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided document (exclusive). The starting position is + * relative to the order of the query. The document must contain all of the + * fields provided in the orderBy of the query. + * + * @param snapshot - The snapshot of the document to start after. + * @returns A {@link QueryStartAtConstraint} to pass to `query()` + */ +export declare function startAfter(snapshot: DocumentSnapshot): QueryStartAtConstraint; + +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided fields relative to the order of the query. The order + * of the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to start this query after, in order + * of the query's order by. + * @returns A {@link QueryStartAtConstraint} to pass to `query()` + */ +export declare function startAfter(...fieldValues: unknown[]): QueryStartAtConstraint; + +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided document (inclusive). The starting position is relative + * to the order of the query. The document must contain all of the fields + * provided in the `orderBy` of this query. + * + * @param snapshot - The snapshot of the document to start at. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. + */ +export declare function startAt(snapshot: DocumentSnapshot): QueryStartAtConstraint; + +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to start this query at, in order + * of the query's order by. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. + */ +export declare function startAt(...fieldValues: unknown[]): QueryStartAtConstraint; + +declare type StructuredQuery = firestoreV1ApiClientInterfaces.StructuredQuery; + +/** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ +export declare function sum(field: string | FieldPath): AggregateField; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * SyncEngine is the central controller in the client SDK architecture. It is + * the glue code between the EventManager, LocalStore, and RemoteStore. Some of + * SyncEngine's responsibilities include: + * 1. Coordinating client requests and remote events between the EventManager + * and the local and remote data stores. + * 2. Managing a View object for each query, providing the unified view between + * the local and remote data stores. + * 3. Notifying the RemoteStore when the LocalStore has new mutations in its + * queue that need sending to the backend. + * + * The SyncEngine’s methods should only ever be called by methods running in the + * global async queue. + * + * PORTING NOTE: On Web, SyncEngine does not have an explicit subscribe() + * function. Instead, it directly depends on EventManager's tree-shakeable API + * (via `ensureWatchStream()`). + */ +declare interface SyncEngine { + isPrimaryClient: boolean; +} + +/** + * A Target represents the WatchTarget representation of a Query, which is used + * by the LocalStore and the RemoteStore to keep track of and to execute + * backend queries. While a Query can represent multiple Targets, each Targets + * maps to a single WatchTarget in RemoteStore and a single TargetData entry + * in persistence. + */ +declare interface Target { + readonly path: ResourcePath; + readonly collectionGroup: string | null; + readonly orderBy: OrderBy[]; + readonly filters: Filter[]; + readonly limit: number | null; + readonly startAt: Bound | null; + readonly endAt: Bound | null; +} + +/** + * Represents cached targets received from the remote backend. + * + * The cache is keyed by `Target` and entries in the cache are `TargetData` + * instances. + */ +declare interface TargetCache { + /** + * A global snapshot version representing the last consistent snapshot we + * received from the backend. This is monotonically increasing and any + * snapshots received from the backend prior to this version (e.g. for targets + * resumed with a resume_token) should be suppressed (buffered) until the + * backend has caught up to this snapshot version again. This prevents our + * cache from ever going backwards in time. + * + * This is updated whenever our we get a TargetChange with a read_time and + * empty target_ids. + */ + getLastRemoteSnapshotVersion(transaction: PersistenceTransaction): PersistencePromise; + /** + * @returns The highest sequence number observed, including any that might be + * persisted on-disk. + */ + getHighestSequenceNumber(transaction: PersistenceTransaction): PersistencePromise; + /** + * Call provided function with each `TargetData` that we have cached. + */ + forEachTarget(txn: PersistenceTransaction, f: (q: TargetData) => void): PersistencePromise; + /** + * Set the highest listen sequence number and optionally updates the + * snapshot version of the last consistent snapshot received from the backend + * (see getLastRemoteSnapshotVersion() for more details). + * + * @param highestListenSequenceNumber - The new maximum listen sequence number. + * @param lastRemoteSnapshotVersion - The new snapshot version. Optional. + */ + setTargetsMetadata(transaction: PersistenceTransaction, highestListenSequenceNumber: number, lastRemoteSnapshotVersion?: SnapshotVersion): PersistencePromise; + /** + * Adds an entry in the cache. + * + * The cache key is extracted from `targetData.target`. The key must not already + * exist in the cache. + * + * @param targetData - A TargetData instance to put in the cache. + */ + addTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Updates an entry in the cache. + * + * The cache key is extracted from `targetData.target`. The entry must already + * exist in the cache, and it will be replaced. + * @param targetData - The TargetData to be replaced into the cache. + */ + updateTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Removes the cached entry for the given target data. It is an error to remove + * a target data that does not exist. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * The number of targets currently in the cache. + */ + getTargetCount(transaction: PersistenceTransaction): PersistencePromise; + /** + * Looks up a TargetData entry by target. + * + * @param target - The query target corresponding to the entry to look up. + * @returns The cached TargetData entry, or null if the cache has no entry for + * the target. + */ + getTargetData(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Adds the given document keys to cached query results of the given target + * ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + addMatchingKeys(transaction: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + /** + * Removes the given document keys from the cached query results of the + * given target ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMatchingKeys(transaction: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + /** + * Removes all the keys in the query results of the given target ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMatchingKeysForTargetId(transaction: PersistenceTransaction, targetId: TargetId): PersistencePromise; + /** + * Returns the document keys that match the provided target ID. + */ + getMatchingKeysForTargetId(transaction: PersistenceTransaction, targetId: TargetId): PersistencePromise; + /** + * Returns a new target ID that is higher than any query in the cache. If + * there are no queries in the cache, returns the first valid target ID. + * Allocated target IDs are persisted and `allocateTargetId()` will never + * return the same ID twice. + */ + allocateTargetId(transaction: PersistenceTransaction): PersistencePromise; + containsKey(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; +} + +/** + * A TargetChange specifies the set of changes for a specific target as part of + * a RemoteEvent. These changes track which documents are added, modified or + * removed, as well as the target's resume token and whether the target is + * marked CURRENT. + * The actual changes *to* documents are not part of the TargetChange since + * documents may be part of multiple targets. + */ +declare class TargetChange { + /** + * An opaque, server-assigned token that allows watching a query to be resumed + * after disconnecting without retransmitting all the data that matches the + * query. The resume token essentially identifies a point in time from which + * the server should resume sending results. + */ + readonly resumeToken: ByteString; + /** + * The "current" (synced) status of this target. Note that "current" + * has special meaning in the RPC protocol that implies that a target is + * both up-to-date and consistent with the rest of the watch stream. + */ + readonly current: boolean; + /** + * The set of documents that were newly assigned to this target as part of + * this remote event. + */ + readonly addedDocuments: DocumentKeySet; + /** + * The set of documents that were already assigned to this target but received + * an update during this remote event. + */ + readonly modifiedDocuments: DocumentKeySet; + /** + * The set of documents that were removed from this target as part of this + * remote event. + */ + readonly removedDocuments: DocumentKeySet; + constructor( + /** + * An opaque, server-assigned token that allows watching a query to be resumed + * after disconnecting without retransmitting all the data that matches the + * query. The resume token essentially identifies a point in time from which + * the server should resume sending results. + */ + resumeToken: ByteString, + /** + * The "current" (synced) status of this target. Note that "current" + * has special meaning in the RPC protocol that implies that a target is + * both up-to-date and consistent with the rest of the watch stream. + */ + current: boolean, + /** + * The set of documents that were newly assigned to this target as part of + * this remote event. + */ + addedDocuments: DocumentKeySet, + /** + * The set of documents that were already assigned to this target but received + * an update during this remote event. + */ + modifiedDocuments: DocumentKeySet, + /** + * The set of documents that were removed from this target as part of this + * remote event. + */ + removedDocuments: DocumentKeySet); + /** + * This method is used to create a synthesized TargetChanges that can be used to + * apply a CURRENT status change to a View (for queries executed in a different + * tab) or for new queries (to raise snapshots with correct CURRENT status). + */ + static createSynthesizedTargetChangeForCurrentChange(targetId: TargetId, current: boolean, resumeToken: ByteString): TargetChange; +} + +declare type TargetChangeTargetChangeType = 'NO_CHANGE' | 'ADD' | 'REMOVE' | 'CURRENT' | 'RESET'; + +/** + * An immutable set of metadata that the local store tracks for each target. + */ +declare class TargetData { + /** The target being listened to. */ + readonly target: Target; + /** + * The target ID to which the target corresponds; Assigned by the + * LocalStore for user listens and by the SyncEngine for limbo watches. + */ + readonly targetId: TargetId; + /** The purpose of the target. */ + readonly purpose: TargetPurpose; + /** + * The sequence number of the last transaction during which this target data + * was modified. + */ + readonly sequenceNumber: ListenSequenceNumber; + /** The latest snapshot version seen for this target. */ + readonly snapshotVersion: SnapshotVersion; + /** + * The maximum snapshot version at which the associated view + * contained no limbo documents. + */ + readonly lastLimboFreeSnapshotVersion: SnapshotVersion; + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + readonly resumeToken: ByteString; + /** + * The number of documents that last matched the query at the resume token or + * read time. Documents are counted only when making a listen request with + * resume token or read time, otherwise, keep it null. + */ + readonly expectedCount: number | null; + constructor( + /** The target being listened to. */ + target: Target, + /** + * The target ID to which the target corresponds; Assigned by the + * LocalStore for user listens and by the SyncEngine for limbo watches. + */ + targetId: TargetId, + /** The purpose of the target. */ + purpose: TargetPurpose, + /** + * The sequence number of the last transaction during which this target data + * was modified. + */ + sequenceNumber: ListenSequenceNumber, + /** The latest snapshot version seen for this target. */ + snapshotVersion?: SnapshotVersion, + /** + * The maximum snapshot version at which the associated view + * contained no limbo documents. + */ + lastLimboFreeSnapshotVersion?: SnapshotVersion, + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + resumeToken?: ByteString, + /** + * The number of documents that last matched the query at the resume token or + * read time. Documents are counted only when making a listen request with + * resume token or read time, otherwise, keep it null. + */ + expectedCount?: number | null); + /** Creates a new target data instance with an updated sequence number. */ + withSequenceNumber(sequenceNumber: number): TargetData; + /** + * Creates a new target data instance with an updated resume token and + * snapshot version. + */ + withResumeToken(resumeToken: ByteString, snapshotVersion: SnapshotVersion): TargetData; + /** + * Creates a new target data instance with an updated expected count. + */ + withExpectedCount(expectedCount: number): TargetData; + /** + * Creates a new target data instance with an updated last limbo free + * snapshot version number. + */ + withLastLimboFreeSnapshotVersion(lastLimboFreeSnapshotVersion: SnapshotVersion): TargetData; +} + +/** + * A locally-assigned ID used to refer to a target being watched via the + * Watch service. + */ +declare type TargetId = number; + +/** An enumeration of the different purposes we have for targets. */ +declare const enum TargetPurpose { + /** A regular, normal query target. */ + Listen = "TargetPurposeListen", + /** + * The query target was used to refill a query after an existence filter + * mismatch. + */ + ExistenceFilterMismatch = "TargetPurposeExistenceFilterMismatch", + /** + * The query target was used if the query is the result of a false positive in + * the bloom filter. + */ + ExistenceFilterMismatchBloom = "TargetPurposeExistenceFilterMismatchBloom", + /** The query target was used to resolve a limbo document. */ + LimboResolution = "TargetPurposeLimboResolution" +} + +/** + * Terminates the provided `Firestore` instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` functions + * may be used. Any other function will throw a `FirestoreError`. Termination + * does not cancel any pending writes, and any promises that are awaiting a + * response from the server will not be resolved. + * + * To restart after termination, create a new instance of `Firestore` with + * {@link (getFirestore:1)}. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all of + * its resources or in combination with {@link clearIndexedDbPersistence} to + * ensure that all local state is destroyed between test runs. + * + * @param firestore - The `Firestore` instance to terminate. + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ +export declare function terminate(firestore: Firestore): Promise; + +/** + * Wellknown "timer" IDs used when scheduling delayed operations on the + * AsyncQueue. These IDs can then be used from tests to check for the presence + * of operations or to run them early. + * + * The string values are used when encoding these timer IDs in JSON spec tests. + */ +declare const enum TimerId { + /** All can be used with runDelayedOperationsEarly() to run all timers. */ + All = "all", + /** + * The following 5 timers are used in persistent_stream.ts for the listen and + * write streams. The "Idle" timer is used to close the stream due to + * inactivity. The "ConnectionBackoff" timer is used to restart a stream once + * the appropriate backoff delay has elapsed. The health check is used to mark + * a stream healthy if it has not received an error during its initial setup. + */ + ListenStreamIdle = "listen_stream_idle", + ListenStreamConnectionBackoff = "listen_stream_connection_backoff", + WriteStreamIdle = "write_stream_idle", + WriteStreamConnectionBackoff = "write_stream_connection_backoff", + HealthCheckTimeout = "health_check_timeout", + /** + * A timer used in online_state_tracker.ts to transition from + * OnlineState.Unknown to Offline after a set timeout, rather than waiting + * indefinitely for success or failure. + */ + OnlineStateTimeout = "online_state_timeout", + /** + * A timer used to update the client metadata in IndexedDb, which is used + * to determine the primary leaseholder. + */ + ClientMetadataRefresh = "client_metadata_refresh", + /** A timer used to periodically attempt LRU Garbage collection */ + LruGarbageCollection = "lru_garbage_collection", + /** + * A timer used to retry transactions. Since there can be multiple concurrent + * transactions, multiple of these may be in the queue at a given time. + */ + TransactionRetry = "transaction_retry", + /** + * A timer used to retry operations scheduled via retryable AsyncQueue + * operations. + */ + AsyncQueueRetry = "async_queue_retry", + /** + * A timer used to periodically attempt index backfill. + */ + IndexBackfill = "index_backfill" +} + +/** + * A `Timestamp` represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. + * + * It is encoded using the Proleptic Gregorian Calendar which extends the + * Gregorian calendar backwards to year one. It is encoded assuming all minutes + * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59.999999999Z. + * + * For examples and further specifications, refer to the + * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. + */ +export declare class Timestamp { + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + readonly seconds: number; + /** + * The fractions of a second at nanosecond resolution.* + */ + readonly nanoseconds: number; + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns a new timestamp representing the current date. + */ + static now(): Timestamp; + /** + * Creates a new timestamp from the given date. + * + * @param date - The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the given + * date. + */ + static fromDate(date: Date): Timestamp; + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds - Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the given + * number of milliseconds. + */ + static fromMillis(milliseconds: number): Timestamp; + /** + * Creates a new timestamp. + * + * @param seconds - The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds - The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ + constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + seconds: number, + /** + * The fractions of a second at nanosecond resolution.* + */ + nanoseconds: number); + /** + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ + toDate(): Date; + /** + * Converts a `Timestamp` to a numeric timestamp (in milliseconds since + * epoch). This operation causes a loss of precision. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ + toMillis(): number; + _compareTo(other: Timestamp): number; + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other - The `Timestamp` to compare against. + * @returns true if this `Timestamp` is equal to the provided one. + */ + isEqual(other: Timestamp): boolean; + /** Returns a textual representation of this `Timestamp`. */ + toString(): string; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + seconds: Property<"number">; + nanoseconds: Property<"number">; + }; + /** + * Returns a JSON-serializable representation of this `Timestamp`. + */ + toJSON(): { + seconds: number; + nanoseconds: number; + type: string; + }; + /** + * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}. + */ + static fromJSON(json: object): Timestamp; + /** + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. + */ + valueOf(): string; +} + +declare type Timestamp_2 = string | { + seconds?: string | number; + nanos?: number; +}; + +declare interface Token { + /** Type of token. */ + type: TokenType; + /** + * The user with which the token is associated (used for persisting user + * state on disk, etc.). + * This will be null for Tokens of the type 'AppCheck'. + */ + user?: User; + /** Header values to set for this token */ + headers: Map; +} + +declare type TokenType = 'OAuth' | 'FirstParty' | 'AppCheck'; + +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ +export declare class Transaction { + protected readonly _firestore: Firestore; + private readonly _transaction; + private readonly _dataReader; + /** @hideconstructor */ + constructor(_firestore: Firestore, _transaction: Transaction_2); + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ + get(documentRef: DocumentReference): Promise>; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: WithFieldValue): this; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * If you provide `merge` or `mergeFields`, the provided data can be merged + * into an existing document. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: PartialWithFieldValue, options: SetOptions): this; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * @param documentRef - A reference to the document to be updated. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, data: UpdateData): this; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * @param documentRef - A reference to the document to be updated. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key/value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): this; + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + delete(documentRef: DocumentReference): this; +} + +/** + * Internal transaction object responsible for accumulating the mutations to + * perform and the base versions for any documents read. + */ +declare class Transaction_2 { + private datastore; + private readVersions; + private mutations; + private committed; + /** + * A deferred usage error that occurred previously in this transaction that + * will cause the transaction to fail once it actually commits. + */ + private lastTransactionError; + /** + * Set of documents that have been written in the transaction. + * + * When there's more than one write to the same key in a transaction, any + * writes after the first are handled differently. + */ + private writtenDocs; + constructor(datastore: Datastore); + lookup(keys: DocumentKey[]): Promise; + set(key: DocumentKey, data: ParsedSetData): void; + update(key: DocumentKey, data: ParsedUpdateData): void; + delete(key: DocumentKey): void; + commit(): Promise; + private recordVersion; + /** + * Returns the version of this document when it was read in this transaction, + * as a precondition, or no precondition if it was not read. + */ + private precondition; + /** + * Returns the precondition for a document if the operation is an update. + */ + private preconditionForUpdate; + private write; + private ensureCommitNotCalled; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options to customize transaction behavior. + */ +export declare interface TransactionOptions { + /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */ + readonly maxAttempts?: number; +} + +/** Used to represent a field transform on a mutation. */ +declare class TransformOperation { + private _; +} + +/* Excluded from this release type: TSType */ + +declare type UnaryFilterOp = 'OPERATOR_UNSPECIFIED' | 'IS_NAN' | 'IS_NULL' | 'IS_NOT_NAN' | 'IS_NOT_NULL'; + +/** + * Given a union type `U = T1 | T2 | ...`, returns an intersected type + * `(T1 & T2 & ...)`. + * + * Uses distributive conditional types and inference from conditional types. + * This works because multiple candidates for the same type variable in + * contra-variant positions causes an intersection type to be inferred. + * https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-inference-in-conditional-types + * https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type + */ +export declare type UnionToIntersection = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never; + +/** + * An untyped Firestore Data Converter interface that is shared between the + * lite, firestore-exp and classic SDK. + */ +declare interface UntypedFirestoreDataConverter { + toFirestore(modelObject: WithFieldValue): WithFieldValue; + toFirestore(modelObject: PartialWithFieldValue, options: SetOptions_2): PartialWithFieldValue; + fromFirestore(snapshot: unknown, options?: unknown): AppModelType; +} + +/** + * Update data (for use with {@link (updateDoc:1)}) that consists of field paths + * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots + * reference nested fields within the document. FieldValues can be passed in + * as property values. + */ +export declare type UpdateData = T extends Primitive ? T : T extends {} ? { + [K in keyof T]?: UpdateData | FieldValue; +} & NestedUpdateFields : Partial; + +/** + * Updates fields in the document referred to by the specified + * `DocumentReference`. The update will fail if applied to a document that does + * not exist. + * + * The result of this update will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * update fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to update. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function updateDoc(reference: DocumentReference, data: UpdateData): Promise; + +/** + * Updates fields in the document referred to by the specified + * `DocumentReference` The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * The result of this update will only be reflected in document reads that occur + * after the returned promise resolves. If the client is offline, the + * update fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @param reference - A reference to the document to update. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend. + */ +export declare function updateDoc(reference: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): Promise; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Simple wrapper around a nullable UID. Mostly exists to make code more + * readable. + */ +declare class User { + readonly uid: string | null; + /** A user with a null UID. */ + static readonly UNAUTHENTICATED: User; + static readonly GOOGLE_CREDENTIALS: User; + static readonly FIRST_PARTY: User; + static readonly MOCK_USER: User; + constructor(uid: string | null); + isAuthenticated(): boolean; + /** + * Returns a key representing this user, suitable for inclusion in a + * dictionary. + */ + toKey(): string; + isEqual(otherUser: User): boolean; +} + +declare type Value = firestoreV1ApiClientInterfaces.Value; + +declare type ValueNullValue = 'NULL_VALUE'; + +/** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ +export declare function vector(values?: number[]): VectorValue; + +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link vector}. + * + * @class VectorValue + */ +export declare class VectorValue { + private readonly _values; + /* Excluded from this release type: __constructor */ + /** + * Returns a copy of the raw number array form of the vector. + */ + toArray(): number[]; + /** + * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise. + */ + isEqual(other: VectorValue): boolean; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + vectorValues: Property<"object">; + }; + /** + * Returns a JSON-serializable representation of this `VectorValue` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}. + * + * @param json a JSON object represention of a `VectorValue` instance. + * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): VectorValue; +} + +declare class ViewSnapshot { + readonly query: Query_2; + readonly docs: DocumentSet; + readonly oldDocs: DocumentSet; + readonly docChanges: DocumentViewChange[]; + readonly mutatedKeys: DocumentKeySet; + readonly fromCache: boolean; + readonly syncStateChanged: boolean; + readonly excludesMetadataChanges: boolean; + readonly hasCachedResults: boolean; + constructor(query: Query_2, docs: DocumentSet, oldDocs: DocumentSet, docChanges: DocumentViewChange[], mutatedKeys: DocumentKeySet, fromCache: boolean, syncStateChanged: boolean, excludesMetadataChanges: boolean, hasCachedResults: boolean); + /** Returns a view snapshot as if all documents in the snapshot were added. */ + static fromInitialDocuments(query: Query_2, documents: DocumentSet, mutatedKeys: DocumentKeySet, fromCache: boolean, hasCachedResults: boolean): ViewSnapshot; + get hasPendingWrites(): boolean; + isEqual(other: ViewSnapshot): boolean; +} + +/** + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. + * + * @param fieldPath - The path to compare + * @param opStr - The operation string (e.g "<", "<=", "==", "<", + * "<=", "!="). + * @param value - The value for comparison + * @returns The created {@link QueryFieldFilterConstraint}. + */ +export declare function where(fieldPath: string | FieldPath, opStr: WhereFilterOp, value: unknown): QueryFieldFilterConstraint; + +/** + * Filter conditions in a {@link where} clause are specified using the + * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in', + * 'array-contains-any', and 'not-in'. + */ +export declare type WhereFilterOp = '<' | '<=' | '==' | '!=' | '>=' | '>' | 'array-contains' | 'in' | 'array-contains-any' | 'not-in'; + +/** + * Allows FieldValues to be passed in as a property value while maintaining + * type safety. + */ +export declare type WithFieldValue = T | (T extends Primitive ? T : T extends {} ? { + [K in keyof T]: WithFieldValue | FieldValue; +} : never); + +/** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It + * provides methods for adding writes to the write batch. None of the writes + * will be committed (or visible locally) until {@link WriteBatch.commit} is + * called. + */ +export declare class WriteBatch { + private readonly _firestore; + private readonly _commitHandler; + private readonly _dataReader; + private _mutations; + private _committed; + /** @hideconstructor */ + constructor(_firestore: Firestore, _commitHandler: (m: Mutation[]) => Promise); + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: WithFieldValue): WriteBatch; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * If you provide `merge` or `mergeFields`, the provided data can be merged + * into an existing document. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: PartialWithFieldValue, options: SetOptions): WriteBatch; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * @param documentRef - A reference to the document to be updated. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, data: UpdateData): WriteBatch; + /** + * Updates fields in the document referred to by this {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be update by providing dot-separated field path strings + * or by providing `FieldPath` objects. + * + * @param documentRef - A reference to the document to be updated. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): WriteBatch; + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + delete(documentRef: DocumentReference): WriteBatch; + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `Promise` resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit (note that it won't + * resolve while you're offline). + */ + commit(): Promise; + private _verifyNotCommitted; +} + +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single WriteBatch + * is 500. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `WriteBatch` that can be used to atomically execute multiple + * writes. + */ +export declare function writeBatch(firestore: Firestore): WriteBatch; + +export { } diff --git a/frontend-old/node_modules/@firebase/firestore/dist/private.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/private.d.ts new file mode 100644 index 0000000..eacea36 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/private.d.ts @@ -0,0 +1,7590 @@ +/** + * Cloud Firestore + * + * @packageDocumentation + */ + +import { DocumentData as DocumentData_2 } from '@firebase/firestore-types'; +import { EmulatorMockTokenOptions } from '@firebase/util'; +import { FirebaseApp } from '@firebase/app'; +import { FirebaseError } from '@firebase/util'; +import { LogLevelString as LogLevel } from '@firebase/logger'; +import { SetOptions as SetOptions_2 } from '@firebase/firestore-types'; + +/* Excluded from this release type: AbstractUserDataWriter */ + +/** + * Describes a map whose keys are active target ids. We do not care about the type of the + * values. + */ +declare type ActiveTargets = SortedMap; + +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend (Note that it + * won't resolve while you're offline). + */ +export declare function addDoc(reference: CollectionReference, data: WithFieldValue): Promise>; + +/** + * Returns a new map where every key is prefixed with the outer key appended + * to a dot. + */ +export declare type AddPrefixToKeys> = { + [K in keyof T & string as `${Prefix}.${K}`]+?: string extends K ? any : T[K]; +}; + +/** + * Represents an aggregation that can be performed by Firestore. + */ +export declare class AggregateField { + readonly _internalFieldPath?: _FieldPath | undefined; + /** A type string to uniquely identify instances of this class. */ + readonly type = "AggregateField"; + /** Indicates the aggregation operation of this AggregateField. */ + readonly aggregateType: AggregateType; + /* Excluded from this release type: __constructor */ +} + +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ +export declare function aggregateFieldEqual(left: AggregateField, right: AggregateField): boolean; + +/** + * The union of all `AggregateField` types that are supported by Firestore. + */ +export declare type AggregateFieldType = ReturnType | ReturnType | ReturnType; + +/** + * The results of executing an aggregation query. + */ +export declare class AggregateQuerySnapshot { + private readonly _userDataWriter; + private readonly _data; + /** A type string to uniquely identify instances of this class. */ + readonly type = "AggregateQuerySnapshot"; + /** + * The underlying query over which the aggregations recorded in this + * `AggregateQuerySnapshot` were performed. + */ + readonly query: Query; + /** @hideconstructor */ + constructor(query: Query, _userDataWriter: AbstractUserDataWriter, _data: ApiClientObjectMap); + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ + data(): AggregateSpecData; +} + +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ +export declare function aggregateQuerySnapshotEqual(left: AggregateQuerySnapshot, right: AggregateQuerySnapshot): boolean; + +/** + * Specifies a set of aggregations and their aliases. + */ +export declare interface AggregateSpec { + [field: string]: AggregateFieldType; +} + +/** + * A type whose keys are taken from an `AggregateSpec`, and whose values are the + * result of the aggregation performed by the corresponding `AggregateField` + * from the input `AggregateSpec`. + */ +export declare type AggregateSpecData = { + [P in keyof T]: T[P] extends AggregateField ? U : never; +}; + +/** + * Union type representing the aggregate type to be performed. + */ +export declare type AggregateType = 'count' | 'avg' | 'sum'; + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +export declare function and(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; + +declare interface ApiClientObjectMap { + [k: string]: T; +} + +/** + * An `AppliableConstraint` is an abstraction of a constraint that can be applied + * to a Firestore query. + */ +declare abstract class AppliableConstraint { + /** + * Takes the provided {@link Query} and returns a copy of the {@link Query} with this + * {@link AppliableConstraint} applied. + */ + abstract _apply(query: Query): Query; +} + +/** + * Returns a special value that can be used with {@link (setDoc:1)} or {@link + * updateDoc:1} that tells the server to remove the given elements from any + * array value that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is not + * already an array it will be overwritten with an empty array. + * + * @param elements - The elements to remove from the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +export declare function arrayRemove(...elements: unknown[]): FieldValue; + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array + * value that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements - The elements to union into the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()`. + */ +export declare function arrayUnion(...elements: unknown[]): FieldValue; + +declare interface AsyncQueue { + readonly isShuttingDown: boolean; + /** + * Adds a new operation to the queue without waiting for it to complete (i.e. + * we ignore the Promise result). + */ + enqueueAndForget(op: () => Promise): void; + /** + * Regardless if the queue has initialized shutdown, adds a new operation to the + * queue without waiting for it to complete (i.e. we ignore the Promise result). + */ + enqueueAndForgetEvenWhileRestricted(op: () => Promise): void; + /** + * Initialize the shutdown of this queue. Once this method is called, the + * only possible way to request running an operation is through + * `enqueueEvenWhileRestricted()`. + * + * @param purgeExistingTasks Whether already enqueued tasked should be + * rejected (unless enqueued with `enqueueEvenWhileRestricted()`). Defaults + * to false. + */ + enterRestrictedMode(purgeExistingTasks?: boolean): void; + /** + * Adds a new operation to the queue. Returns a promise that will be resolved + * when the promise returned by the new operation is (with its value). + */ + enqueue(op: () => Promise): Promise; + /** + * Enqueue a retryable operation. + * + * A retryable operation is rescheduled with backoff if it fails with a + * IndexedDbTransactionError (the error type used by SimpleDb). All + * retryable operations are executed in order and only run if all prior + * operations were retried successfully. + */ + enqueueRetryable(op: () => Promise): void; + /** + * Schedules an operation to be queued on the AsyncQueue once the specified + * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel + * or fast-forward the operation prior to its running. + */ + enqueueAfterDelay(timerId: TimerId, delayMs: number, op: () => Promise): DelayedOperation; + /** + * Verifies there's an operation currently in-progress on the AsyncQueue. + * Unfortunately we can't verify that the running code is in the promise chain + * of that operation, so this isn't a foolproof check, but it should be enough + * to catch some bugs. + */ + verifyOperationInProgress(): void; +} + +/* Excluded from this release type: AuthTokenFactory */ + +/* Excluded from this release type: _AutoId */ + +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ +export declare function average(field: string | FieldPath): AggregateField; + +/** + * Path represents an ordered sequence of string segments. + */ +declare abstract class BasePath> { + private segments; + private offset; + private len; + constructor(segments: string[], offset?: number, length?: number); + /** + * Abstract constructor method to construct an instance of B with the given + * parameters. + */ + protected abstract construct(segments: string[], offset?: number, length?: number): B; + /** + * Returns a String representation. + * + * Implementing classes are required to provide deterministic implementations as + * the String representation is used to obtain canonical Query IDs. + */ + abstract toString(): string; + get length(): number; + isEqual(other: B): boolean; + child(nameOrPath: string | B): B; + /** The index of one past the last segment of the path. */ + private limit; + popFirst(size?: number): B; + popLast(): B; + firstSegment(): string; + lastSegment(): string; + get(index: number): string; + isEmpty(): boolean; + isPrefixOf(other: this): boolean; + isImmediateParentOf(potentialChild: this): boolean; + forEach(fn: (segment: string) => void): void; + toArray(): string[]; + /** + * Compare 2 paths segment by segment, prioritizing numeric IDs + * (e.g., "__id123__") in numeric ascending order, followed by string + * segments in lexicographical order. + */ + static comparator>(p1: BasePath, p2: BasePath): number; + private static compareSegments; + private static isNumericId; + private static extractNumericId; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * BatchID is a locally assigned ID for a batch of mutations that have been + * applied. + */ +declare type BatchId = number; + +/** + * Represents a bound of a query. + * + * The bound is specified with the given components representing a position and + * whether it's just before or just after the position (relative to whatever the + * query order is). + * + * The position represents a logical index position for a query. It's a prefix + * of values for the (potentially implicit) order by clauses of a query. + * + * Bound provides a function to determine whether a document comes before or + * after a bound. This is influenced by whether the position is just before or + * just after the provided values. + */ +declare class Bound { + readonly position: Value[]; + readonly inclusive: boolean; + constructor(position: Value[], inclusive: boolean); +} + +/** + * Provides interfaces to save and read Firestore bundles. + */ +declare interface BundleCache { + /** + * Gets the saved `BundleMetadata` for a given `bundleId`, returns undefined + * if no bundle metadata is found under the given id. + */ + getBundleMetadata(transaction: PersistenceTransaction, bundleId: string): PersistencePromise; + /** + * Saves a `BundleMetadata` from a bundle into local storage, using its id as + * the persistent key. + */ + saveBundleMetadata(transaction: PersistenceTransaction, metadata: BundleMetadata_2): PersistencePromise; + /** + * Gets a saved `NamedQuery` for the given query name. Returns undefined if + * no queries are found under the given name. + */ + getNamedQuery(transaction: PersistenceTransaction, queryName: string): PersistencePromise; + /** + * Saves a `NamedQuery` from a bundle, using its name as the persistent key. + */ + saveNamedQuery(transaction: PersistenceTransaction, query: NamedQuery_2): PersistencePromise; +} + +/** Properties of a BundledQuery. */ +declare interface BundledQuery { + /** BundledQuery parent */ + parent?: string | null; + /** BundledQuery structuredQuery */ + structuredQuery?: StructuredQuery | null; + /** BundledQuery limitType */ + limitType?: LimitType_2 | null; +} + +/** + * Represents a Firestore bundle saved by the SDK in its local storage. + */ +declare interface BundleMetadata { + /** + * Id of the bundle. It is used together with `createTime` to determine if a + * bundle has been loaded by the SDK. + */ + readonly id: string; + /** Schema version of the bundle. */ + readonly version: number; + /** + * Set to the snapshot version of the bundle if created by the Server SDKs. + * Otherwise set to SnapshotVersion.MIN. + */ + readonly createTime: SnapshotVersion; +} + +/** Properties of a BundleMetadata. */ +declare interface BundleMetadata_2 { + /** BundleMetadata id */ + id?: string | null; + /** BundleMetadata createTime */ + createTime?: Timestamp_2 | null; + /** BundleMetadata version */ + version?: number | null; + /** BundleMetadata totalDocuments */ + totalDocuments?: number | null; + /** BundleMetadata totalBytes */ + totalBytes?: number | null; +} + +/** + * An immutable object representing an array of bytes. + */ +export declare class Bytes { + _byteString: _ByteString; + /** @hideconstructor */ + constructor(byteString: _ByteString); + /** + * Creates a new `Bytes` object from the given Base64 string, converting it to + * bytes. + * + * @param base64 - The Base64 string used to create the `Bytes` object. + */ + static fromBase64String(base64: string): Bytes; + /** + * Creates a new `Bytes` object from the given Uint8Array. + * + * @param array - The Uint8Array used to create the `Bytes` object. + */ + static fromUint8Array(array: Uint8Array): Bytes; + /** + * Returns the underlying bytes as a Base64-encoded string. + * + * @returns The Base64-encoded string created from the `Bytes` object. + */ + toBase64(): string; + /** + * Returns the underlying bytes in a new `Uint8Array`. + * + * @returns The Uint8Array created from the `Bytes` object. + */ + toUint8Array(): Uint8Array; + /** + * Returns a string representation of the `Bytes` object. + * + * @returns A string representation of the `Bytes` object. + */ + toString(): string; + /** + * Returns true if this `Bytes` object is equal to the provided one. + * + * @param other - The `Bytes` object to compare against. + * @returns true if this `Bytes` object is equal to the provided one. + */ + isEqual(other: Bytes): boolean; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + bytes: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `Bytes` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}. + * + * @param json a JSON object represention of a `Bytes` instance + * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): Bytes; +} + +/* Excluded from this release type: _ByteString */ + +/** + * Constant used to indicate the LRU garbage collection should be disabled. + * Set this value as the `cacheSizeBytes` on the settings passed to the + * {@link Firestore} instance. + */ +export declare const CACHE_SIZE_UNLIMITED = -1; + +/* Excluded from this release type: _cast */ + +declare const enum ChangeType { + Added = 0, + Removed = 1, + Modified = 2, + Metadata = 3 +} + +/** + * Helper for calculating the nested fields for a given type T1. This is needed + * to distribute union types such as `undefined | {...}` (happens for optional + * props) or `{a: A} | {b: B}`. + * + * In this use case, `V` is used to distribute the union types of `T[K]` on + * `Record`, since `T[K]` is evaluated as an expression and not distributed. + * + * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types + */ +export declare type ChildUpdateFields = V extends Record ? AddPrefixToKeys> : never; + +/** + * Clears the persistent storage. This includes pending writes and cached + * documents. + * + * Must be called while the {@link Firestore} instance is not started (after the app is + * terminated or when the app is first initialized). On startup, this function + * must be called before other functions (other than {@link + * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore} + * instance is still running, the promise will be rejected with the error code + * of `failed-precondition`. + * + * Note: `clearIndexedDbPersistence()` is primarily intended to help write + * reliable tests that use Cloud Firestore. It uses an efficient mechanism for + * dropping existing data but does not attempt to securely overwrite or + * otherwise make cached data unrecoverable. For applications that are sensitive + * to the disclosure of cached data in between user sessions, we strongly + * recommend not enabling persistence at all. + * + * @param firestore - The {@link Firestore} instance to clear persistence for. + * @returns A `Promise` that is resolved when the persistent storage is + * cleared. Otherwise, the promise is rejected with an error. + */ +export declare function clearIndexedDbPersistence(firestore: Firestore): Promise; + +/** + * A randomly-generated key assigned to each Firestore instance at startup. + */ +declare type ClientId = string; + +/** + * Gets a `CollectionReference` instance that refers to the collection at + * the specified absolute path. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments to apply relative to the first + * argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(firestore: Firestore_2, path: string, ...pathSegments: string[]): CollectionReference; + +/** + * Gets a `CollectionReference` instance that refers to a subcollection of + * `reference` at the specified relative path. + * + * @param reference - A reference to a collection. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments to apply relative to the first + * argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(reference: CollectionReference, path: string, ...pathSegments: string[]): CollectionReference; + +/** + * Gets a `CollectionReference` instance that refers to a subcollection of + * `reference` at the specified relative path. + * + * @param reference - A reference to a Firestore document. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(reference: DocumentReference, path: string, ...pathSegments: string[]): CollectionReference; + +/** + * Creates and returns a new `Query` instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given `collectionId`. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param collectionId - Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `Query`. + */ +export declare function collectionGroup(firestore: Firestore_2, collectionId: string): Query; + +/** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using {@link (query:1)}). + */ +export declare class CollectionReference extends Query { + readonly _path: _ResourcePath; + /** The type of this Firestore reference. */ + readonly type = "collection"; + /** @hideconstructor */ + constructor(firestore: Firestore_2, converter: FirestoreDataConverter_2 | null, _path: _ResourcePath); + /** The collection's identifier. */ + get id(): string; + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ + get path(): string; + /** + * A reference to the containing `DocumentReference` if this is a + * subcollection. If this isn't a subcollection, the reference is null. + */ + get parent(): DocumentReference | null; + /** + * Applies a custom data converter to this `CollectionReference`, allowing you + * to use your own custom model objects with Firestore. When you call {@link + * addDoc} with the returned `CollectionReference` instance, the provided + * converter will convert between Firestore data of type `NewDbModelType` and + * your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `CollectionReference` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter_2): CollectionReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `CollectionReference` that does not + * use a converter. + */ + withConverter(converter: null): CollectionReference; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +declare type Comparator = (key1: K, key2: K) => number; + +declare interface ComponentConfiguration { + asyncQueue: AsyncQueue; + databaseInfo: DatabaseInfo; + authCredentials: CredentialsProvider; + appCheckCredentials: CredentialsProvider; + clientId: ClientId; + initialUser: User; + maxConcurrentLimboResolutions: number; +} + +declare type CompositeFilterOp = 'OPERATOR_UNSPECIFIED' | 'AND' | 'OR'; + +declare const enum CompositeOperator { + OR = "or", + AND = "and" +} + +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ +export declare function connectFirestoreEmulator(firestore: Firestore_2, host: string, port: number, options?: { + mockUserToken?: EmulatorMockTokenOptions | string; +}): void; + +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ +export declare function count(): AggregateField; + +/** + * A Listener for credential change events. The listener should fetch a new + * token and may need to invalidate other state if the current user has also + * changed. + */ +declare type CredentialChangeListener = (credential: T) => Promise; + +/** + * Provides methods for getting the uid and token for the current user and + * listening for changes. + */ +declare interface CredentialsProvider { + /** + * Starts the credentials provider and specifies a listener to be notified of + * credential changes (sign-in / sign-out, token changes). It is immediately + * called once with the initial user. + * + * The change listener is invoked on the provided AsyncQueue. + */ + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + /** Requests a token for the current user. */ + getToken(): Promise; + /** + * Marks the last retrieved token as invalid, making the next GetToken request + * force-refresh the token. + */ + invalidateToken(): void; + shutdown(): void; +} + +/** Settings for private credentials */ +declare type CredentialsSettings = FirstPartyCredentialsSettings | ProviderCredentialsSettings; + +/* Excluded from this release type: _DatabaseId */ + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +declare class DatabaseInfo { + readonly databaseId: _DatabaseId; + readonly appId: string; + readonly persistenceKey: string; + readonly host: string; + readonly ssl: boolean; + readonly forceLongPolling: boolean; + readonly autoDetectLongPolling: boolean; + readonly longPollingOptions: ExperimentalLongPollingOptions; + readonly useFetchStreams: boolean; + readonly isUsingEmulator: boolean; + /** + * Constructs a DatabaseInfo using the provided host, databaseId and + * persistenceKey. + * + * @param databaseId - The database to use. + * @param appId - The Firebase App Id. + * @param persistenceKey - A unique identifier for this Firestore's local + * storage (used in conjunction with the databaseId). + * @param host - The Firestore backend host to connect to. + * @param ssl - Whether to use SSL when connecting. + * @param forceLongPolling - Whether to use the forceLongPolling option + * when using WebChannel as the network transport. + * @param autoDetectLongPolling - Whether to use the detectBufferingProxy + * option when using WebChannel as the network transport. + * @param longPollingOptions Options that configure long-polling. + * @param useFetchStreams Whether to use the Fetch API instead of + * XMLHTTPRequest + */ + constructor(databaseId: _DatabaseId, appId: string, persistenceKey: string, host: string, ssl: boolean, forceLongPolling: boolean, autoDetectLongPolling: boolean, longPollingOptions: ExperimentalLongPollingOptions, useFetchStreams: boolean, isUsingEmulator: boolean); +} + +/** + * Datastore and its related methods are a wrapper around the external Google + * Cloud Datastore grpc API, which provides an interface that is more convenient + * for the rest of the client SDK architecture to consume. + */ +declare abstract class Datastore { + abstract terminate(): void; + abstract serializer: JsonProtoSerializer; +} + +/* Excluded from this release type: _debugAssert */ + +/** + * Represents an operation scheduled to be run in the future on an AsyncQueue. + * + * It is created via DelayedOperation.createAndSchedule(). + * + * Supports cancellation (via cancel()) and early execution (via skipDelay()). + * + * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type + * in newer versions of TypeScript defines `finally`, which is not available in + * IE. + */ +declare class DelayedOperation implements PromiseLike { + private readonly asyncQueue; + readonly timerId: TimerId; + readonly targetTimeMs: number; + private readonly op; + private readonly removalCallback; + private timerHandle; + private readonly deferred; + private constructor(); + get promise(): Promise; + /** + * Creates and returns a DelayedOperation that has been scheduled to be + * executed on the provided asyncQueue after the provided delayMs. + * + * @param asyncQueue - The queue to schedule the operation on. + * @param id - A Timer ID identifying the type of operation this is. + * @param delayMs - The delay (ms) before the operation should be scheduled. + * @param op - The operation to run. + * @param removalCallback - A callback to be called synchronously once the + * operation is executed or canceled, notifying the AsyncQueue to remove it + * from its delayedOperations list. + * PORTING NOTE: This exists to prevent making removeDelayedOperation() and + * the DelayedOperation class public. + */ + static createAndSchedule(asyncQueue: AsyncQueue, timerId: TimerId, delayMs: number, op: () => Promise, removalCallback: (op: DelayedOperation) => void): DelayedOperation; + /** + * Starts the timer. This is called immediately after construction by + * createAndSchedule(). + */ + private start; + /** + * Queues the operation to run immediately (if it hasn't already been run or + * canceled). + */ + skipDelay(): void; + /** + * Cancels the operation if it hasn't already been executed or canceled. The + * promise will be rejected. + * + * As long as the operation has not yet been run, calling cancel() provides a + * guarantee that the operation will not be run. + */ + cancel(reason?: string): void; + then: (onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined) => Promise; + private handleDelayElapsed; + private clearTimeout; +} + +/** + * Removes all persistent cache indexes. + * + * Please note this function will also deletes indexes generated by + * `setIndexConfiguration()`, which is deprecated. + */ +export declare function deleteAllPersistentCacheIndexes(indexManager: PersistentCacheIndexManager): void; + +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * @param reference - A reference to the document to delete. + * @returns A Promise resolved once the document has been successfully + * deleted from the backend (note that it won't resolve while you're offline). + */ +export declare function deleteDoc(reference: DocumentReference): Promise; + +/** + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. + */ +export declare function deleteField(): FieldValue; + +/** + * The direction of sorting in an order by. + */ +declare const enum Direction { + ASCENDING = "asc", + DESCENDING = "desc" +} + +/** + * Disables network usage for this instance. It can be re-enabled via {@link + * enableNetwork}. While the network is disabled, any snapshot listeners, + * `getDoc()` or `getDocs()` calls will return results from cache, and any write + * operations will be queued until the network is restored. + * + * @returns A `Promise` that is resolved once the network has been disabled. + */ +export declare function disableNetwork(firestore: Firestore): Promise; + +/** + * Stops creating persistent cache indexes automatically for local query + * execution. The indexes which have been created by calling + * `enablePersistentCacheIndexAutoCreation()` still take effect. + */ +export declare function disablePersistentCacheIndexAutoCreation(indexManager: PersistentCacheIndexManager): void; + +/** + * Gets a `DocumentReference` instance that refers to the document at the + * specified absolute path. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param path - A slash-separated path to a document. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(firestore: Firestore_2, path: string, ...pathSegments: string[]): DocumentReference; + +/** + * Gets a `DocumentReference` instance that refers to a document within + * `reference` at the specified relative path. If no path is specified, an + * automatically-generated unique ID will be used for the returned + * `DocumentReference`. + * + * @param reference - A reference to a collection. + * @param path - A slash-separated path to a document. Has to be omitted to use + * auto-generated IDs. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(reference: CollectionReference, path?: string, ...pathSegments: string[]): DocumentReference; + +/** + * Gets a `DocumentReference` instance that refers to a document within + * `reference` at the specified relative path. + * + * @param reference - A reference to a Firestore document. + * @param path - A slash-separated path to a document. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(reference: DocumentReference, path: string, ...pathSegments: string[]): DocumentReference; + +/** + * Represents a document in Firestore with a key, version, data and whether the + * data has local mutations applied to it. + */ +declare interface Document_2 { + /** The key for this document */ + readonly key: _DocumentKey; + /** + * The version of this document if it exists or a version at which this + * document was guaranteed to not exist. + */ + readonly version: SnapshotVersion; + /** + * The timestamp at which this document was read from the remote server. Uses + * `SnapshotVersion.min()` for documents created by the user. + */ + readonly readTime: SnapshotVersion; + /** + * The timestamp at which the document was created. This value increases + * monotonically when a document is deleted then recreated. It can also be + * compared to `createTime` of other documents and the `readTime` of a query. + */ + readonly createTime: SnapshotVersion; + /** The underlying data of this document or an empty value if no data exists. */ + readonly data: ObjectValue; + /** Returns whether local mutations were applied via the mutation queue. */ + readonly hasLocalMutations: boolean; + /** Returns whether mutations were applied based on a write acknowledgment. */ + readonly hasCommittedMutations: boolean; + /** + * Whether this document had a local mutation applied that has not yet been + * acknowledged by Watch. + */ + readonly hasPendingWrites: boolean; + /** + * Returns whether this document is valid (i.e. it is an entry in the + * RemoteDocumentCache, was created by a mutation or read from the backend). + */ + isValidDocument(): boolean; + /** + * Returns whether the document exists and its data is known at the current + * version. + */ + isFoundDocument(): boolean; + /** + * Returns whether the document is known to not exist at the current version. + */ + isNoDocument(): boolean; + /** + * Returns whether the document exists and its data is unknown at the current + * version. + */ + isUnknownDocument(): boolean; + isEqual(other: Document_2 | null | undefined): boolean; + /** Creates a mutable copy of this document. */ + mutableCopy(): MutableDocument; + toString(): string; +} + +/** + * A `DocumentChange` represents a change to the documents matching a query. + * It contains the document affected and the type of change that occurred. + */ +export declare interface DocumentChange { + /** The type of change ('added', 'modified', or 'removed'). */ + readonly type: DocumentChangeType; + /** The document affected by this change. */ + readonly doc: QueryDocumentSnapshot; + /** + * The index of the changed document in the result set immediately prior to + * this `DocumentChange` (i.e. supposing that all prior `DocumentChange` objects + * have been applied). Is `-1` for 'added' events. + */ + readonly oldIndex: number; + /** + * The index of the changed document in the result set immediately after + * this `DocumentChange` (i.e. supposing that all prior `DocumentChange` + * objects and the current `DocumentChange` object have been applied). + * Is -1 for 'removed' events. + */ + readonly newIndex: number; +} + +/** + * The type of a `DocumentChange` may be 'added', 'removed', or 'modified'. + */ +export declare type DocumentChangeType = 'added' | 'removed' | 'modified'; + +declare type DocumentComparator = (doc1: Document_2, doc2: Document_2) => number; + +/** + * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to + * values. + */ +export declare interface DocumentData { + /** A mapping between a field and its value. */ + [field: string]: any; +} + +/** + * Returns a special sentinel `FieldPath` to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ +export declare function documentId(): FieldPath; + +/* Excluded from this release type: _DocumentKey */ + +declare type DocumentKeyMap = ObjectMap<_DocumentKey, T>; + +declare type DocumentKeySet = SortedSet<_DocumentKey>; + +declare type DocumentMap = SortedMap<_DocumentKey, Document_2>; + +/** + * Provides methods to read and write document overlays. + * + * An overlay is a saved mutation, that gives a local view of a document when + * applied to the remote version of the document. + * + * Each overlay stores the largest batch ID that is included in the overlay, + * which allows us to remove the overlay once all batches leading up to it have + * been acknowledged. + */ +declare interface DocumentOverlayCache { + /** + * Gets the saved overlay mutation for the given document key. + * Returns null if there is no overlay for that key. + */ + getOverlay(transaction: PersistenceTransaction, key: _DocumentKey): PersistencePromise; + /** + * Gets the saved overlay mutation for the given document keys. Skips keys for + * which there are no overlays. + */ + getOverlays(transaction: PersistenceTransaction, keys: _DocumentKey[]): PersistencePromise; + /** + * Saves the given document mutation map to persistence as overlays. + * All overlays will have their largest batch id set to `largestBatchId`. + */ + saveOverlays(transaction: PersistenceTransaction, largestBatchId: number, overlays: MutationMap): PersistencePromise; + /** Removes overlays for the given document keys and batch ID. */ + removeOverlaysForBatchId(transaction: PersistenceTransaction, documentKeys: DocumentKeySet, batchId: number): PersistencePromise; + /** + * Returns all saved overlays for the given collection. + * + * @param transaction - The persistence transaction to use for this operation. + * @param collection - The collection path to get the overlays for. + * @param sinceBatchId - The minimum batch ID to filter by (exclusive). + * Only overlays that contain a change past `sinceBatchId` are returned. + * @returns Mapping of each document key in the collection to its overlay. + */ + getOverlaysForCollection(transaction: PersistenceTransaction, collection: _ResourcePath, sinceBatchId: number): PersistencePromise; + /** + * Returns `count` overlays with a batch ID higher than `sinceBatchId` for the + * provided collection group, processed by ascending batch ID. The method + * always returns all overlays for a batch even if the last batch contains + * more documents than the remaining limit. + * + * @param transaction - The persistence transaction used for this operation. + * @param collectionGroup - The collection group to get the overlays for. + * @param sinceBatchId - The minimum batch ID to filter by (exclusive). + * Only overlays that contain a change past `sinceBatchId` are returned. + * @param count - The number of overlays to return. Can be exceeded if the last + * batch contains more entries. + * @return Mapping of each document key in the collection group to its overlay. + */ + getOverlaysForCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, sinceBatchId: number, count: number): PersistencePromise; +} + +/** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. + */ +export declare class DocumentReference { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter_2 | null; + readonly _key: _DocumentKey; + /** The type of this Firestore reference. */ + readonly type = "document"; + /** + * The {@link Firestore} instance the document is in. + * This is useful for performing transactions, for example. + */ + readonly firestore: Firestore_2; + /** @hideconstructor */ + constructor(firestore: Firestore_2, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter: FirestoreDataConverter_2 | null, _key: _DocumentKey); + get _path(): _ResourcePath; + /** + * The document's identifier within its collection. + */ + get id(): string; + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ + get path(): string; + /** + * The collection this `DocumentReference` belongs to. + */ + get parent(): CollectionReference; + /** + * Applies a custom data converter to this `DocumentReference`, allowing you + * to use your own custom model objects with Firestore. When you call {@link + * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference` + * instance, the provided converter will convert between Firestore data of + * type `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `DocumentReference` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter_2): DocumentReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `DocumentReference` that does not + * use a converter. + */ + withConverter(converter: null): DocumentReference; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + referencePath: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `DocumentReference` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `DocumentReference` instance from a JSON object created by + * {@link DocumentReference.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json a JSON object represention of a `DocumentReference` instance + * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(firestore: Firestore_2, json: object): DocumentReference; + /** + * Builds a `DocumentReference` instance from a JSON object created by + * {@link DocumentReference.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json a JSON object represention of a `DocumentReference` instance + * @param converter - Converts objects to and from Firestore. + * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(firestore: Firestore_2, json: object, converter: FirestoreDataConverter_2): DocumentReference; +} + +/** + * DocumentSet is an immutable (copy-on-write) collection that holds documents + * in order specified by the provided comparator. We always add a document key + * comparator on top of what is provided to guarantee document equality based on + * the key. + */ +declare class DocumentSet { + /** + * Returns an empty copy of the existing DocumentSet, using the same + * comparator. + */ + static emptySet(oldSet: DocumentSet): DocumentSet; + private comparator; + private keyedMap; + private sortedSet; + /** The default ordering is by key if the comparator is omitted */ + constructor(comp?: DocumentComparator); + has(key: _DocumentKey): boolean; + get(key: _DocumentKey): Document_2 | null; + first(): Document_2 | null; + last(): Document_2 | null; + isEmpty(): boolean; + /** + * Returns the index of the provided key in the document set, or -1 if the + * document key is not present in the set; + */ + indexOf(key: _DocumentKey): number; + get size(): number; + /** Iterates documents in order defined by "comparator" */ + forEach(cb: (doc: Document_2) => void): void; + /** Inserts or updates a document with the same key */ + add(doc: Document_2): DocumentSet; + /** Deletes a document with a given key */ + delete(key: _DocumentKey): DocumentSet; + isEqual(other: DocumentSet | null | undefined): boolean; + toString(): string; + private copy; +} + +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ +export declare class DocumentSnapshot extends DocumentSnapshot_2 { + readonly _firestore: Firestore; + private readonly _firestoreImpl; + /** + * Metadata about the `DocumentSnapshot`, including information about its + * source and local modifications. + */ + readonly metadata: SnapshotMetadata; + /** @hideconstructor protected */ + constructor(_firestore: Firestore, userDataWriter: AbstractUserDataWriter, key: _DocumentKey, document: Document_2 | null, metadata: SnapshotMetadata, converter: UntypedFirestoreDataConverter | null); + /** + * Returns whether or not the data exists. True if the document exists. + */ + exists(): this is QueryDocumentSnapshot; + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * By default, `serverTimestamp()` values that have not yet been + * set to their final value will be returned as `null`. You can override + * this by passing an options object. + * + * @param options - An options object to configure how data is retrieved from + * the snapshot (for example the desired behavior for server timestamps that + * have not yet been set to their final value). + * @returns An `Object` containing all fields in the document or `undefined` if + * the document doesn't exist. + */ + data(options?: SnapshotOptions): AppModelType | undefined; + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * By default, a `serverTimestamp()` that has not yet been set to + * its final value will be returned as `null`. You can override this by + * passing an options object. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @param options - An options object to configure how the field is retrieved + * from the snapshot (for example the desired behavior for server timestamps + * that have not yet been set to their final value). + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + get(fieldPath: string | FieldPath, options?: SnapshotOptions): any; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + bundleSource: Property<"string">; + bundleName: Property<"string">; + bundle: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `DocumentSnapshot` instance. + * + * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this + * `DocumentSnapshot` has pending writes. + */ + toJSON(): object; +} + +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ +declare class DocumentSnapshot_2 { + _firestore: Firestore_2; + _userDataWriter: AbstractUserDataWriter; + _key: _DocumentKey; + _document: Document_2 | null; + _converter: UntypedFirestoreDataConverter | null; + /** @hideconstructor protected */ + constructor(_firestore: Firestore_2, _userDataWriter: AbstractUserDataWriter, _key: _DocumentKey, _document: Document_2 | null, _converter: UntypedFirestoreDataConverter | null); + /** Property of the `DocumentSnapshot` that provides the document's ID. */ + get id(): string; + /** + * The `DocumentReference` for the document included in the `DocumentSnapshot`. + */ + get ref(): DocumentReference; + /** + * Signals whether or not the document at the snapshot's location exists. + * + * @returns true if the document exists. + */ + exists(): this is QueryDocumentSnapshot_2; + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * @returns An `Object` containing all fields in the document or `undefined` + * if the document doesn't exist. + */ + data(): AppModelType | undefined; + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + get(fieldPath: string | FieldPath): any; +} + +/** + * Builds a `DocumentSnapshot` instance from a JSON object created by + * {@link DocumentSnapshot.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json - a JSON object represention of a `DocumentSnapshot` instance. + * @returns an instance of {@link DocumentSnapshot} if the JSON object could be + * parsed. Throws a {@link FirestoreError} if an error occurs. + */ +export declare function documentSnapshotFromJSON(db: Firestore, json: object): DocumentSnapshot; + +/** + * Builds a `DocumentSnapshot` instance from a JSON object created by + * {@link DocumentSnapshot.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json - a JSON object represention of a `DocumentSnapshot` instance. + * @param converter - Converts objects to and from Firestore. + * @returns an instance of {@link DocumentSnapshot} if the JSON object could be + * parsed. Throws a {@link FirestoreError} if an error occurs. + */ +export declare function documentSnapshotFromJSON(db: Firestore, json: object, converter: FirestoreDataConverter): DocumentSnapshot; + +declare type DocumentVersionMap = SortedMap<_DocumentKey, SnapshotVersion>; + +declare interface DocumentViewChange { + type: ChangeType; + doc: Document_2; +} + +/* Excluded from this release type: _EmptyAppCheckTokenProvider */ + +/* Excluded from this release type: _EmptyAuthCredentialsProvider */ +export { EmulatorMockTokenOptions } + +/** + * Attempts to enable persistent storage, if possible. + * + * On failure, `enableIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. + * + * * failed-precondition: The app is already open in another browser tab. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. + * + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. + * + * Note: `enableIndexedDbPersistence()` must be called before any other functions + * (other than {@link initializeFirestore}, {@link (getFirestore:1)} or + * {@link clearIndexedDbPersistence}. + * + * Persistence cannot be used in a Node.js environment. + * + * @param firestore - The {@link Firestore} instance to enable persistence for. + * @param persistenceSettings - Optional settings object to configure + * persistence. + * @returns A `Promise` that represents successfully enabling persistent storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on IndexedDb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. + */ +export declare function enableIndexedDbPersistence(firestore: Firestore, persistenceSettings?: PersistenceSettings): Promise; + +/** + * Attempts to enable multi-tab persistent storage, if possible. If enabled + * across all tabs, all operations share access to local persistence, including + * shared execution of queries and latency-compensated local document updates + * across all connected instances. + * + * On failure, `enableMultiTabIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. + * + * * failed-precondition: The app is already open in another browser tab and + * multi-tab is not enabled. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. + * + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. + * + * @param firestore - The {@link Firestore} instance to enable persistence for. + * @returns A `Promise` that represents successfully enabling persistent + * storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on indexeddb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. + */ +export declare function enableMultiTabIndexedDbPersistence(firestore: Firestore): Promise; + +/** + * Re-enables use of the network for this {@link Firestore} instance after a prior + * call to {@link disableNetwork}. + * + * @returns A `Promise` that is resolved once the network has been enabled. + */ +export declare function enableNetwork(firestore: Firestore): Promise; + +/** + * Enables the SDK to create persistent cache indexes automatically for local + * query execution when the SDK believes cache indexes can help improve + * performance. + * + * This feature is disabled by default. + */ +export declare function enablePersistentCacheIndexAutoCreation(indexManager: PersistentCacheIndexManager): void; + +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided document (inclusive). The end position is relative to the order + * of the query. The document must contain all of the fields provided in the + * orderBy of the query. + * + * @param snapshot - The snapshot of the document to end at. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endAt(snapshot: DocumentSnapshot_2): QueryEndAtConstraint; + +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided fields relative to the order of the query. The order of the field + * values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to end this query at, in order + * of the query's order by. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endAt(...fieldValues: unknown[]): QueryEndAtConstraint; + +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided document (exclusive). The end position is relative to the + * order of the query. The document must contain all of the fields provided in + * the orderBy of the query. + * + * @param snapshot - The snapshot of the document to end before. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endBefore(snapshot: DocumentSnapshot_2): QueryEndAtConstraint; + +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to end this query before, in order + * of the query's order by. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endBefore(...fieldValues: unknown[]): QueryEndAtConstraint; + +/* Excluded from this release type: ensureFirestoreConfigured */ + +declare interface Entry { + key: K; + value: V; +} + +/** + * EventManager is responsible for mapping queries to query event emitters. + * It handles "fan-out". -- Identical queries will re-use the same watch on the + * backend. + * + * PORTING NOTE: On Web, EventManager `onListen` and `onUnlisten` need to be + * assigned to SyncEngine's `listen()` and `unlisten()` API before usage. This + * allows users to tree-shake the Watch logic. + */ +declare interface EventManager { + onListen?: (query: Query_2, enableRemoteListen: boolean) => Promise; + onUnlisten?: (query: Query_2, disableRemoteListen: boolean) => Promise; + onFirstRemoteStoreListen?: (query: Query_2) => Promise; + onLastRemoteStoreUnlisten?: (query: Query_2) => Promise; + terminate(): void; +} + +/* Excluded from this release type: executeWrite */ + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options that configure the SDK’s underlying network transport (WebChannel) + * when long-polling is used. + * + * Note: This interface is "experimental" and is subject to change. + * + * See `FirestoreSettings.experimentalAutoDetectLongPolling`, + * `FirestoreSettings.experimentalForceLongPolling`, and + * `FirestoreSettings.experimentalLongPollingOptions`. + */ +export declare interface ExperimentalLongPollingOptions { + /** + * The desired maximum timeout interval, in seconds, to complete a + * long-polling GET response. Valid values are between 5 and 30, inclusive. + * Floating point values are allowed and will be rounded to the nearest + * millisecond. + * + * By default, when long-polling is used the "hanging GET" request sent by + * the client times out after 30 seconds. To request a different timeout + * from the server, set this setting with the desired timeout. + * + * Changing the default timeout may be useful, for example, if the buffering + * proxy that necessitated enabling long-polling in the first place has a + * shorter timeout for hanging GET requests, in which case setting the + * long-polling timeout to a shorter value, such as 25 seconds, may fix + * prematurely-closed hanging GET requests. + * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987. + */ + timeoutSeconds?: number; +} + +declare class FieldFilter extends Filter { + readonly field: _FieldPath; + readonly op: Operator; + readonly value: Value; + protected constructor(field: _FieldPath, op: Operator, value: Value); + /** + * Creates a filter based on the provided arguments. + */ + static create(field: _FieldPath, op: Operator, value: Value): FieldFilter; + private static createKeyFieldInFilter; + matches(doc: Document_2): boolean; + protected matchesComparison(comparison: number): boolean; + isInequality(): boolean; + getFlattenedFilters(): readonly FieldFilter[]; + getFilters(): Filter[]; +} + +declare type FieldFilterOp = 'OPERATOR_UNSPECIFIED' | 'LESS_THAN' | 'LESS_THAN_OR_EQUAL' | 'GREATER_THAN' | 'GREATER_THAN_OR_EQUAL' | 'EQUAL' | 'NOT_EQUAL' | 'ARRAY_CONTAINS' | 'IN' | 'ARRAY_CONTAINS_ANY' | 'NOT_IN'; + +/** + * An index definition for field indexes in Firestore. + * + * Every index is associated with a collection. The definition contains a list + * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or + * `CONTAINS` for ArrayContains/ArrayContainsAny queries). + * + * Unlike the backend, the SDK does not differentiate between collection or + * collection group-scoped indices. Every index can be used for both single + * collection and collection group queries. + */ +declare class FieldIndex { + /** + * The index ID. Returns -1 if the index ID is not available (e.g. the index + * has not yet been persisted). + */ + readonly indexId: number; + /** The collection ID this index applies to. */ + readonly collectionGroup: string; + /** The field segments for this index. */ + readonly fields: IndexSegment[]; + /** Shows how up-to-date the index is for the current user. */ + readonly indexState: IndexState; + /** An ID for an index that has not yet been added to persistence. */ + static UNKNOWN_ID: number; + constructor( + /** + * The index ID. Returns -1 if the index ID is not available (e.g. the index + * has not yet been persisted). + */ + indexId: number, + /** The collection ID this index applies to. */ + collectionGroup: string, + /** The field segments for this index. */ + fields: IndexSegment[], + /** Shows how up-to-date the index is for the current user. */ + indexState: IndexState); +} + +/** + * Provides a set of fields that can be used to partially patch a document. + * FieldMask is used in conjunction with ObjectValue. + * Examples: + * foo - Overwrites foo entirely with the provided value. If foo is not + * present in the companion ObjectValue, the field is deleted. + * foo.bar - Overwrites only the field bar of the object foo. + * If foo is not an object, foo is replaced with an object + * containing foo + */ +declare class FieldMask { + readonly fields: _FieldPath[]; + constructor(fields: _FieldPath[]); + static empty(): FieldMask; + /** + * Returns a new FieldMask object that is the result of adding all the given + * fields paths to this field mask. + */ + unionWith(extraFields: _FieldPath[]): FieldMask; + /** + * Verifies that `fieldPath` is included by at least one field in this field + * mask. + * + * This is an O(n) operation, where `n` is the size of the field mask. + */ + covers(fieldPath: _FieldPath): boolean; + isEqual(other: FieldMask): boolean; +} + +/** + * A `FieldPath` refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + * + * Create a `FieldPath` by providing field names. If more than one field + * name is provided, the path will point to a nested field in a document. + */ +export declare class FieldPath { + /** Internal representation of a Firestore field path. */ + readonly _internalPath: _FieldPath; + /** + * Creates a `FieldPath` from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames - A list of field names. + */ + constructor(...fieldNames: string[]); + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other - The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ + isEqual(other: FieldPath): boolean; +} + +/* Excluded from this release type: _FieldPath */ + +/** A field path and the TransformOperation to perform upon it. */ +declare class FieldTransform { + readonly field: _FieldPath; + readonly transform: TransformOperation; + constructor(field: _FieldPath, transform: TransformOperation); +} + +declare type FieldTransformSetToServerValue = 'SERVER_VALUE_UNSPECIFIED' | 'REQUEST_TIME'; + +/** + * Sentinel values that can be used when writing document fields with `set()` + * or `update()`. + */ +export declare abstract class FieldValue { + _methodName: string; + /** + * @param _methodName - The public API endpoint that returns this class. + * @hideconstructor + */ + constructor(_methodName: string); + /** Compares `FieldValue`s for equality. */ + abstract isEqual(other: FieldValue): boolean; + abstract _toFieldTransform(context: ParseContext): FieldTransform | null; +} + +declare abstract class Filter { + abstract matches(doc: Document_2): boolean; + abstract getFlattenedFilters(): readonly FieldFilter[]; + abstract getFilters(): Filter[]; +} + +/* Excluded from this release type: _FirebaseService */ + +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ +export declare class Firestore extends Firestore_2 { + /** + * Whether it's a {@link Firestore} or Firestore Lite instance. + */ + type: 'firestore-lite' | 'firestore'; + _queue: AsyncQueue; + readonly _persistenceKey: string; + _firestoreClient: FirestoreClient | undefined; + _componentsProvider?: { + _offline: OfflineComponentProviderFactory; + _online: OnlineComponentProviderFactory; + }; + /** @hideconstructor */ + constructor(authCredentialsProvider: CredentialsProvider, appCheckCredentialsProvider: CredentialsProvider, databaseId: _DatabaseId, app?: FirebaseApp); + protected _terminate(): Promise; +} + +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ +declare class Firestore_2 implements FirestoreService { + _authCredentials: CredentialsProvider; + _appCheckCredentials: CredentialsProvider; + readonly _databaseId: _DatabaseId; + readonly _app?: FirebaseApp | undefined; + /** + * Whether it's a Firestore or Firestore Lite instance. + */ + type: 'firestore-lite' | 'firestore'; + readonly _persistenceKey: string; + private _settings; + private _settingsFrozen; + private _emulatorOptions; + private _terminateTask; + /** @hideconstructor */ + constructor(_authCredentials: CredentialsProvider, _appCheckCredentials: CredentialsProvider, _databaseId: _DatabaseId, _app?: FirebaseApp | undefined); + /** + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service + * instance. + */ + get app(): FirebaseApp; + get _initialized(): boolean; + get _terminated(): boolean; + _setSettings(settings: PrivateSettings): void; + _getSettings(): FirestoreSettingsImpl; + _getEmulatorOptions(): { + mockUserToken?: EmulatorMockTokenOptions | string; + }; + _freezeSettings(): FirestoreSettingsImpl; + _delete(): Promise; + _restart(): Promise; + /** Returns a JSON-serializable representation of this `Firestore` instance. */ + toJSON(): object; + /** + * Terminates all components used by this client. Subclasses can override + * this method to clean up their own dependencies, but must also call this + * method. + * + * Only ever called once. + */ + protected _terminate(): Promise; +} + +/** + * FirestoreClient is a top-level class that constructs and owns all of the // + * pieces of the client SDK architecture. It is responsible for creating the // + * async queue that is shared by all of the other components in the system. // + */ +declare class FirestoreClient { + private authCredentials; + private appCheckCredentials; + /** + * Asynchronous queue responsible for all of our internal processing. When + * we get incoming work from the user (via public API) or the network + * (incoming GRPC messages), we should always schedule onto this queue. + * This ensures all of our work is properly serialized (e.g. we don't + * start processing a new operation while the previous one is waiting for + * an async I/O to complete). + */ + asyncQueue: AsyncQueue; + private databaseInfo; + private user; + private readonly clientId; + private authCredentialListener; + private appCheckCredentialListener; + _uninitializedComponentsProvider?: { + _offline: OfflineComponentProvider; + _online: OnlineComponentProvider; + }; + _offlineComponents?: OfflineComponentProvider; + _onlineComponents?: OnlineComponentProvider; + constructor(authCredentials: CredentialsProvider, appCheckCredentials: CredentialsProvider, + /** + * Asynchronous queue responsible for all of our internal processing. When + * we get incoming work from the user (via public API) or the network + * (incoming GRPC messages), we should always schedule onto this queue. + * This ensures all of our work is properly serialized (e.g. we don't + * start processing a new operation while the previous one is waiting for + * an async I/O to complete). + */ + asyncQueue: AsyncQueue, databaseInfo: DatabaseInfo, componentProvider?: { + _offline: OfflineComponentProvider; + _online: OnlineComponentProvider; + }); + get configuration(): ComponentConfiguration; + setCredentialChangeListener(listener: (user: User) => Promise): void; + setAppCheckTokenChangeListener(listener: (appCheckToken: string, user: User) => Promise): void; + terminate(): Promise; +} + +/** + * Converter used by `withConverter()` to transform user objects of type + * `AppModelType` into Firestore data of type `DbModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * In this context, an "AppModel" is a class that is used in an application to + * package together related information and functionality. Such a class could, + * for example, have properties with complex, nested data types, properties used + * for memoization, properties of types not supported by Firestore (such as + * `symbol` and `bigint`), and helper functions that perform compound + * operations. Such classes are not suitable and/or possible to store into a + * Firestore database. Instead, instances of such classes need to be converted + * to "plain old JavaScript objects" (POJOs) with exclusively primitive + * properties, potentially nested inside other POJOs or arrays of POJOs. In this + * context, this type is referred to as the "DbModel" and would be an object + * suitable for persisting into Firestore. For convenience, applications can + * implement `FirestoreDataConverter` and register the converter with Firestore + * objects, such as `DocumentReference` or `Query`, to automatically convert + * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel` + * to `AppModel` when retrieving from Firestore. + * + * @example + * + * Simple Example + * + * ```typescript + * const numberConverter = { + * toFirestore(value: WithFieldValue) { + * return { value }; + * }, + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) { + * return snapshot.data(options).value as number; + * } + * }; + * + * async function simpleDemo(db: Firestore): Promise { + * const documentRef = doc(db, 'values/value123').withConverter(numberConverter); + * + * // converters are used with `setDoc`, `addDoc`, and `getDoc` + * await setDoc(documentRef, 42); + * const snapshot1 = await getDoc(documentRef); + * assertEqual(snapshot1.data(), 42); + * + * // converters are not used when writing data with `updateDoc` + * await updateDoc(documentRef, { value: 999 }); + * const snapshot2 = await getDoc(documentRef); + * assertEqual(snapshot2.data(), 999); + * } + * ``` + * + * Advanced Example + * + * ```typescript + * // The Post class is a model that is used by our application. + * // This class may have properties and methods that are specific + * // to our application execution, which do not need to be persisted + * // to Firestore. + * class Post { + * constructor( + * readonly title: string, + * readonly author: string, + * readonly lastUpdatedMillis: number + * ) {} + * toString(): string { + * return `${this.title} by ${this.author}`; + * } + * } + * + * // The PostDbModel represents how we want our posts to be stored + * // in Firestore. This DbModel has different properties (`ttl`, + * // `aut`, and `lut`) from the Post class we use in our application. + * interface PostDbModel { + * ttl: string; + * aut: { firstName: string; lastName: string }; + * lut: Timestamp; + * } + * + * // The `PostConverter` implements `FirestoreDataConverter` and specifies + * // how the Firestore SDK can convert `Post` objects to `PostDbModel` + * // objects and vice versa. + * class PostConverter implements FirestoreDataConverter { + * toFirestore(post: WithFieldValue): WithFieldValue { + * return { + * ttl: post.title, + * aut: this._autFromAuthor(post.author), + * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis) + * }; + * } + * + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post { + * const data = snapshot.data(options) as PostDbModel; + * const author = `${data.aut.firstName} ${data.aut.lastName}`; + * return new Post(data.ttl, author, data.lut.toMillis()); + * } + * + * _autFromAuthor( + * author: string | FieldValue + * ): { firstName: string; lastName: string } | FieldValue { + * if (typeof author !== 'string') { + * // `author` is a FieldValue, so just return it. + * return author; + * } + * const [firstName, lastName] = author.split(' '); + * return {firstName, lastName}; + * } + * + * _lutFromLastUpdatedMillis( + * lastUpdatedMillis: number | FieldValue + * ): Timestamp | FieldValue { + * if (typeof lastUpdatedMillis !== 'number') { + * // `lastUpdatedMillis` must be a FieldValue, so just return it. + * return lastUpdatedMillis; + * } + * return Timestamp.fromMillis(lastUpdatedMillis); + * } + * } + * + * async function advancedDemo(db: Firestore): Promise { + * // Create a `DocumentReference` with a `FirestoreDataConverter`. + * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter()); + * + * // The `data` argument specified to `setDoc()` is type checked by the + * // TypeScript compiler to be compatible with `Post`. Since the `data` + * // argument is typed as `WithFieldValue` rather than just `Post`, + * // this allows properties of the `data` argument to also be special + * // Firestore values that perform server-side mutations, such as + * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`. + * await setDoc(documentRef, { + * title: 'My Life', + * author: 'Foo Bar', + * lastUpdatedMillis: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `setDoc()` is _not_ compatible with `WithFieldValue`. This + * // type checking prevents the caller from specifying objects with incorrect + * // properties or property values. + * // @ts-expect-error "Argument of type { ttl: string; } is not assignable + * // to parameter of type WithFieldValue" + * await setDoc(documentRef, { ttl: 'The Title' }); + * + * // When retrieving a document with `getDoc()` the `DocumentSnapshot` + * // object's `data()` method returns a `Post`, rather than a generic object, + * // which would have been returned if the `DocumentReference` did _not_ have a + * // `FirestoreDataConverter` attached to it. + * const snapshot1: DocumentSnapshot = await getDoc(documentRef); + * const post1: Post = snapshot1.data()!; + * if (post1) { + * assertEqual(post1.title, 'My Life'); + * assertEqual(post1.author, 'Foo Bar'); + * } + * + * // The `data` argument specified to `updateDoc()` is type checked by the + * // TypeScript compiler to be compatible with `PostDbModel`. Note that + * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`, + * // the `data` argument to `updateDoc()` must be compatible with + * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed + * // as `WithFieldValue` rather than just `PostDbModel`, this + * // allows properties of the `data` argument to also be those special + * // Firestore values, like `arrayRemove()`, `deleteField()`, and + * // `serverTimestamp()`. + * await updateDoc(documentRef, { + * 'aut.firstName': 'NewFirstName', + * lut: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `updateDoc()` is _not_ compatible with `WithFieldValue`. + * // This type checking prevents the caller from specifying objects with + * // incorrect properties or property values. + * // @ts-expect-error "Argument of type { title: string; } is not assignable + * // to parameter of type WithFieldValue" + * await updateDoc(documentRef, { title: 'New Title' }); + * const snapshot2: DocumentSnapshot = await getDoc(documentRef); + * const post2: Post = snapshot2.data()!; + * if (post2) { + * assertEqual(post2.title, 'My Life'); + * assertEqual(post2.author, 'NewFirstName Bar'); + * } + * } + * ``` + */ +export declare interface FirestoreDataConverter extends FirestoreDataConverter_2 { + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. To use `set()` + * with `merge` and `mergeFields`, `toFirestore()` must be defined with + * `PartialWithFieldValue`. + * + * The `WithFieldValue` type extends `T` to also allow FieldValues such as + * {@link (deleteField:1)} to be used as property values. + */ + toFirestore(modelObject: WithFieldValue): WithFieldValue; + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link (setDoc:1)}, {@link (WriteBatch.set:1)} and + * {@link (Transaction.set:1)} with `merge:true` or `mergeFields`. + * + * The `PartialWithFieldValue` type extends `Partial` to allow + * FieldValues such as {@link (arrayUnion:1)} to be used as property values. + * It also supports nested `Partial` by allowing nested fields to be + * omitted. + */ + toFirestore(modelObject: PartialWithFieldValue, options: SetOptions): PartialWithFieldValue; + /** + * Called by the Firestore SDK to convert Firestore data into an object of + * type `AppModelType`. You can access your data by calling: + * `snapshot.data(options)`. + * + * Generally, the data returned from `snapshot.data()` can be cast to + * `DbModelType`; however, this is not guaranteed because Firestore does not + * enforce a schema on the database. For example, writes from a previous + * version of the application or writes from another client that did not use a + * type converter could have written data with different properties and/or + * property types. The implementation will need to choose whether to + * gracefully recover from non-conforming data or throw an error. + * + * To override this method, see {@link (FirestoreDataConverter.fromFirestore:1)}. + * + * @param snapshot - A `QueryDocumentSnapshot` containing your data and metadata. + * @param options - The `SnapshotOptions` from the initial call to `data()`. + */ + fromFirestore(snapshot: QueryDocumentSnapshot, options?: SnapshotOptions): AppModelType; +} + +/** + * Converter used by `withConverter()` to transform user objects of type + * `AppModelType` into Firestore data of type `DbModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * In this context, an "AppModel" is a class that is used in an application to + * package together related information and functionality. Such a class could, + * for example, have properties with complex, nested data types, properties used + * for memoization, properties of types not supported by Firestore (such as + * `symbol` and `bigint`), and helper functions that perform compound + * operations. Such classes are not suitable and/or possible to store into a + * Firestore database. Instead, instances of such classes need to be converted + * to "plain old JavaScript objects" (POJOs) with exclusively primitive + * properties, potentially nested inside other POJOs or arrays of POJOs. In this + * context, this type is referred to as the "DbModel" and would be an object + * suitable for persisting into Firestore. For convenience, applications can + * implement `FirestoreDataConverter` and register the converter with Firestore + * objects, such as `DocumentReference` or `Query`, to automatically convert + * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel` + * to `AppModel` when retrieving from Firestore. + * + * @example + * + * Simple Example + * + * ```typescript + * const numberConverter = { + * toFirestore(value: WithFieldValue) { + * return { value }; + * }, + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) { + * return snapshot.data(options).value as number; + * } + * }; + * + * async function simpleDemo(db: Firestore): Promise { + * const documentRef = doc(db, 'values/value123').withConverter(numberConverter); + * + * // converters are used with `setDoc`, `addDoc`, and `getDoc` + * await setDoc(documentRef, 42); + * const snapshot1 = await getDoc(documentRef); + * assertEqual(snapshot1.data(), 42); + * + * // converters are not used when writing data with `updateDoc` + * await updateDoc(documentRef, { value: 999 }); + * const snapshot2 = await getDoc(documentRef); + * assertEqual(snapshot2.data(), 999); + * } + * ``` + * + * Advanced Example + * + * ```typescript + * // The Post class is a model that is used by our application. + * // This class may have properties and methods that are specific + * // to our application execution, which do not need to be persisted + * // to Firestore. + * class Post { + * constructor( + * readonly title: string, + * readonly author: string, + * readonly lastUpdatedMillis: number + * ) {} + * toString(): string { + * return `${this.title} by ${this.author}`; + * } + * } + * + * // The PostDbModel represents how we want our posts to be stored + * // in Firestore. This DbModel has different properties (`ttl`, + * // `aut`, and `lut`) from the Post class we use in our application. + * interface PostDbModel { + * ttl: string; + * aut: { firstName: string; lastName: string }; + * lut: Timestamp; + * } + * + * // The `PostConverter` implements `FirestoreDataConverter` and specifies + * // how the Firestore SDK can convert `Post` objects to `PostDbModel` + * // objects and vice versa. + * class PostConverter implements FirestoreDataConverter { + * toFirestore(post: WithFieldValue): WithFieldValue { + * return { + * ttl: post.title, + * aut: this._autFromAuthor(post.author), + * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis) + * }; + * } + * + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post { + * const data = snapshot.data(options) as PostDbModel; + * const author = `${data.aut.firstName} ${data.aut.lastName}`; + * return new Post(data.ttl, author, data.lut.toMillis()); + * } + * + * _autFromAuthor( + * author: string | FieldValue + * ): { firstName: string; lastName: string } | FieldValue { + * if (typeof author !== 'string') { + * // `author` is a FieldValue, so just return it. + * return author; + * } + * const [firstName, lastName] = author.split(' '); + * return {firstName, lastName}; + * } + * + * _lutFromLastUpdatedMillis( + * lastUpdatedMillis: number | FieldValue + * ): Timestamp | FieldValue { + * if (typeof lastUpdatedMillis !== 'number') { + * // `lastUpdatedMillis` must be a FieldValue, so just return it. + * return lastUpdatedMillis; + * } + * return Timestamp.fromMillis(lastUpdatedMillis); + * } + * } + * + * async function advancedDemo(db: Firestore): Promise { + * // Create a `DocumentReference` with a `FirestoreDataConverter`. + * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter()); + * + * // The `data` argument specified to `setDoc()` is type checked by the + * // TypeScript compiler to be compatible with `Post`. Since the `data` + * // argument is typed as `WithFieldValue` rather than just `Post`, + * // this allows properties of the `data` argument to also be special + * // Firestore values that perform server-side mutations, such as + * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`. + * await setDoc(documentRef, { + * title: 'My Life', + * author: 'Foo Bar', + * lastUpdatedMillis: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `setDoc()` is _not_ compatible with `WithFieldValue`. This + * // type checking prevents the caller from specifying objects with incorrect + * // properties or property values. + * // @ts-expect-error "Argument of type { ttl: string; } is not assignable + * // to parameter of type WithFieldValue" + * await setDoc(documentRef, { ttl: 'The Title' }); + * + * // When retrieving a document with `getDoc()` the `DocumentSnapshot` + * // object's `data()` method returns a `Post`, rather than a generic object, + * // which would have been returned if the `DocumentReference` did _not_ have a + * // `FirestoreDataConverter` attached to it. + * const snapshot1: DocumentSnapshot = await getDoc(documentRef); + * const post1: Post = snapshot1.data()!; + * if (post1) { + * assertEqual(post1.title, 'My Life'); + * assertEqual(post1.author, 'Foo Bar'); + * } + * + * // The `data` argument specified to `updateDoc()` is type checked by the + * // TypeScript compiler to be compatible with `PostDbModel`. Note that + * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`, + * // the `data` argument to `updateDoc()` must be compatible with + * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed + * // as `WithFieldValue` rather than just `PostDbModel`, this + * // allows properties of the `data` argument to also be those special + * // Firestore values, like `arrayRemove()`, `deleteField()`, and + * // `serverTimestamp()`. + * await updateDoc(documentRef, { + * 'aut.firstName': 'NewFirstName', + * lut: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `updateDoc()` is _not_ compatible with `WithFieldValue`. + * // This type checking prevents the caller from specifying objects with + * // incorrect properties or property values. + * // @ts-expect-error "Argument of type { title: string; } is not assignable + * // to parameter of type WithFieldValue" + * await updateDoc(documentRef, { title: 'New Title' }); + * const snapshot2: DocumentSnapshot = await getDoc(documentRef); + * const post2: Post = snapshot2.data()!; + * if (post2) { + * assertEqual(post2.title, 'My Life'); + * assertEqual(post2.author, 'NewFirstName Bar'); + * } + * } + * ``` + */ +declare interface FirestoreDataConverter_2 { + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link @firebase/firestore/lite#(setDoc:1)}, + * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and + * {@link @firebase/firestore/lite#(Transaction.set:1)}. + * + * The `WithFieldValue` type extends `T` to also allow FieldValues such as + * {@link (deleteField:1)} to be used as property values. + */ + toFirestore(modelObject: WithFieldValue): WithFieldValue; + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link @firebase/firestore/lite#(setDoc:1)}, + * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and + * {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true` + * or `mergeFields`. + * + * The `PartialWithFieldValue` type extends `Partial` to allow + * FieldValues such as {@link (arrayUnion:1)} to be used as property values. + * It also supports nested `Partial` by allowing nested fields to be + * omitted. + */ + toFirestore(modelObject: PartialWithFieldValue, options: SetOptions): PartialWithFieldValue; + /** + * Called by the Firestore SDK to convert Firestore data into an object of + * type `AppModelType`. You can access your data by calling: + * `snapshot.data()`. + * + * + * Generally, the data returned from `snapshot.data()` can be cast to + * `DbModelType`; however, this is not guaranteed because Firestore does not + * enforce a schema on the database. For example, writes from a previous + * version of the application or writes from another client that did not use a + * type converter could have written data with different properties and/or + * property types. The implementation will need to choose whether to + * gracefully recover from non-conforming data or throw an error. + * + * @param snapshot - A `QueryDocumentSnapshot` containing your data and + * metadata. + */ + fromFirestore(snapshot: QueryDocumentSnapshot_2): AppModelType; +} + +/** An error returned by a Firestore operation. */ +export declare class FirestoreError extends FirebaseError { + /** + * The backend error code associated with this error. + */ + readonly code: FirestoreErrorCode; + /** + * A custom error description. + */ + readonly message: string; + /** The stack of the error. */ + readonly stack?: string; + /** @hideconstructor */ + constructor( + /** + * The backend error code associated with this error. + */ + code: FirestoreErrorCode, + /** + * A custom error description. + */ + message: string); +} + +/** + * The set of Firestore status codes. The codes are the same at the ones + * exposed by gRPC here: + * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md + * + * Possible values: + * - 'cancelled': The operation was cancelled (typically by the caller). + * - 'unknown': Unknown error or an error from a different error domain. + * - 'invalid-argument': Client specified an invalid argument. Note that this + * differs from 'failed-precondition'. 'invalid-argument' indicates + * arguments that are problematic regardless of the state of the system + * (e.g. an invalid field name). + * - 'deadline-exceeded': Deadline expired before operation could complete. + * For operations that change the state of the system, this error may be + * returned even if the operation has completed successfully. For example, + * a successful response from a server could have been delayed long enough + * for the deadline to expire. + * - 'not-found': Some requested document was not found. + * - 'already-exists': Some document that we attempted to create already + * exists. + * - 'permission-denied': The caller does not have permission to execute the + * specified operation. + * - 'resource-exhausted': Some resource has been exhausted, perhaps a + * per-user quota, or perhaps the entire file system is out of space. + * - 'failed-precondition': Operation was rejected because the system is not + * in a state required for the operation's execution. + * - 'aborted': The operation was aborted, typically due to a concurrency + * issue like transaction aborts, etc. + * - 'out-of-range': Operation was attempted past the valid range. + * - 'unimplemented': Operation is not implemented or not supported/enabled. + * - 'internal': Internal errors. Means some invariants expected by + * underlying system has been broken. If you see one of these errors, + * something is very broken. + * - 'unavailable': The service is currently unavailable. This is most likely + * a transient condition and may be corrected by retrying with a backoff. + * - 'data-loss': Unrecoverable data loss or corruption. + * - 'unauthenticated': The request does not have valid authentication + * credentials for the operation. + */ +export declare type FirestoreErrorCode = 'cancelled' | 'unknown' | 'invalid-argument' | 'deadline-exceeded' | 'not-found' | 'already-exists' | 'permission-denied' | 'resource-exhausted' | 'failed-precondition' | 'aborted' | 'out-of-range' | 'unimplemented' | 'internal' | 'unavailable' | 'data-loss' | 'unauthenticated'; + +/** + * Union type from all supported SDK cache layer. + */ +export declare type FirestoreLocalCache = MemoryLocalCache | PersistentLocalCache; + +/** + * An interface implemented by FirebaseFirestore that provides compatibility + * with the usage in this file. + * + * This interface mainly exists to remove a cyclic dependency. + */ +declare interface FirestoreService extends _FirebaseService { + _authCredentials: CredentialsProvider; + _appCheckCredentials: CredentialsProvider; + _persistenceKey: string; + _databaseId: _DatabaseId; + _terminated: boolean; + _freezeSettings(): FirestoreSettingsImpl; +} + +/** + * Specifies custom configurations for your Cloud Firestore instance. + * You must set these before invoking any other methods. + */ +export declare interface FirestoreSettings extends FirestoreSettings_2 { + /** + * NOTE: This field will be deprecated in a future major release. Use `cache` field + * instead to specify cache size, and other cache configurations. + * + * An approximate cache size threshold for the on-disk data. If the cache + * grows beyond this size, Firestore will start removing data that hasn't been + * recently used. The size is not a guarantee that the cache will stay below + * that size, only that if the cache exceeds the given size, cleanup will be + * attempted. + * + * The default value is 40 MB. The threshold must be set to at least 1 MB, and + * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection. + */ + cacheSizeBytes?: number; + /** + * Specifies the cache used by the SDK. Available options are `MemoryLocalCache` + * and `PersistentLocalCache`, each with different configuration options. + * + * When unspecified, `MemoryLocalCache` will be used by default. + * + * NOTE: setting this field and `cacheSizeBytes` at the same time will throw + * exception during SDK initialization. Instead, using the configuration in + * the `FirestoreLocalCache` object to specify the cache size. + */ + localCache?: FirestoreLocalCache; + /** + * Forces the SDK’s underlying network transport (WebChannel) to use + * long-polling. Each response from the backend will be closed immediately + * after the backend sends data (by default responses are kept open in + * case the backend has more data to send). This avoids incompatibility + * issues with certain proxies, antivirus software, etc. that incorrectly + * buffer traffic indefinitely. Use of this option will cause some + * performance degradation though. + * + * This setting cannot be used with `experimentalAutoDetectLongPolling` and + * may be removed in a future release. If you find yourself using it to + * work around a specific network reliability issue, please tell us about + * it in https://github.com/firebase/firebase-js-sdk/issues/1674. + * + * This setting cannot be used in a Node.js environment. + */ + experimentalForceLongPolling?: boolean; + /** + * Configures the SDK's underlying transport (WebChannel) to automatically + * detect if long-polling should be used. This is very similar to + * `experimentalForceLongPolling`, but only uses long-polling if required. + * + * After having had a default value of `false` since its inception in 2019, + * the default value of this setting was changed in May 2023 to `true` in + * v9.22.0 of the Firebase JavaScript SDK. That is, auto-detection of long + * polling is now enabled by default. To disable it, set this setting to + * `false`, and please open a GitHub issue to share the problems that + * motivated you disabling long-polling auto-detection. + * + * This setting cannot be used in a Node.js environment. + */ + experimentalAutoDetectLongPolling?: boolean; + /** + * Options that configure the SDK’s underlying network transport (WebChannel) + * when long-polling is used. + * + * These options are only used if `experimentalForceLongPolling` is true or if + * `experimentalAutoDetectLongPolling` is true and the auto-detection + * determined that long-polling was needed. Otherwise, these options have no + * effect. + */ + experimentalLongPollingOptions?: ExperimentalLongPollingOptions; +} + +/** + * Specifies custom configurations for your Cloud Firestore instance. + * You must set these before invoking any other methods. + */ +declare interface FirestoreSettings_2 { + /** The hostname to connect to. */ + host?: string; + /** Whether to use SSL when connecting. */ + ssl?: boolean; + /** + * Whether to skip nested properties that are set to `undefined` during + * object serialization. If set to `true`, these properties are skipped + * and not written to Firestore. If set to `false` or omitted, the SDK + * throws an exception when it encounters properties of type `undefined`. + */ + ignoreUndefinedProperties?: boolean; +} + +/** + * A concrete type describing all the values that can be applied via a + * user-supplied `FirestoreSettings` object. This is a separate type so that + * defaults can be supplied and the value can be checked for equality. + */ +declare class FirestoreSettingsImpl { + /** The hostname to connect to. */ + readonly host: string; + /** Whether to use SSL when connecting. */ + readonly ssl: boolean; + readonly cacheSizeBytes: number; + readonly experimentalForceLongPolling: boolean; + readonly experimentalAutoDetectLongPolling: boolean; + readonly experimentalLongPollingOptions: ExperimentalLongPollingOptions; + readonly ignoreUndefinedProperties: boolean; + readonly useFetchStreams: boolean; + readonly localCache?: FirestoreLocalCache; + readonly isUsingEmulator: boolean; + credentials?: any; + constructor(settings: PrivateSettings); + isEqual(other: FirestoreSettingsImpl): boolean; +} + +declare namespace firestoreV1ApiClientInterfaces { + interface ArrayValue { + values?: Value[]; + } + interface BatchGetDocumentsRequest { + database?: string; + documents?: string[]; + mask?: DocumentMask; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface BatchGetDocumentsResponse { + found?: Document; + missing?: string; + transaction?: string; + readTime?: string; + } + interface BeginTransactionRequest { + options?: TransactionOptions; + } + interface BeginTransactionResponse { + transaction?: string; + } + interface CollectionSelector { + collectionId?: string; + allDescendants?: boolean; + } + interface CommitRequest { + database?: string; + writes?: Write[]; + transaction?: string; + } + interface CommitResponse { + writeResults?: WriteResult[]; + commitTime?: string; + } + interface CompositeFilter { + op?: CompositeFilterOp; + filters?: Filter[]; + } + interface Cursor { + values?: Value[]; + before?: boolean; + } + interface Document { + name?: string; + fields?: ApiClientObjectMap; + createTime?: Timestamp_2; + updateTime?: Timestamp_2; + } + interface DocumentChange { + document?: Document; + targetIds?: number[]; + removedTargetIds?: number[]; + } + interface DocumentDelete { + document?: string; + removedTargetIds?: number[]; + readTime?: Timestamp_2; + } + interface DocumentMask { + fieldPaths?: string[]; + } + interface DocumentRemove { + document?: string; + removedTargetIds?: number[]; + readTime?: string; + } + interface DocumentTransform { + document?: string; + fieldTransforms?: FieldTransform[]; + } + interface DocumentsTarget { + documents?: string[]; + } + interface Empty { + } + interface ExistenceFilter { + targetId?: number; + count?: number; + unchangedNames?: BloomFilter; + } + interface BloomFilter { + bits?: BitSequence; + hashCount?: number; + } + interface BitSequence { + bitmap?: string | Uint8Array; + padding?: number; + } + interface FieldFilter { + field?: FieldReference; + op?: FieldFilterOp; + value?: Value; + } + interface FieldReference { + fieldPath?: string; + } + interface FieldTransform { + fieldPath?: string; + setToServerValue?: FieldTransformSetToServerValue; + appendMissingElements?: ArrayValue; + removeAllFromArray?: ArrayValue; + increment?: Value; + } + interface Filter { + compositeFilter?: CompositeFilter; + fieldFilter?: FieldFilter; + unaryFilter?: UnaryFilter; + } + interface Index { + name?: string; + collectionId?: string; + fields?: IndexField[]; + state?: IndexState_2; + } + interface IndexField { + fieldPath?: string; + mode?: IndexFieldMode; + } + interface LatLng { + latitude?: number; + longitude?: number; + } + interface ListCollectionIdsRequest { + pageSize?: number; + pageToken?: string; + } + interface ListCollectionIdsResponse { + collectionIds?: string[]; + nextPageToken?: string; + } + interface ListDocumentsResponse { + documents?: Document[]; + nextPageToken?: string; + } + interface ListIndexesResponse { + indexes?: Index[]; + nextPageToken?: string; + } + interface ListenRequest { + addTarget?: Target; + removeTarget?: number; + labels?: ApiClientObjectMap; + } + interface ListenResponse { + targetChange?: TargetChange; + documentChange?: DocumentChange; + documentDelete?: DocumentDelete; + documentRemove?: DocumentRemove; + filter?: ExistenceFilter; + } + interface MapValue { + fields?: ApiClientObjectMap; + } + interface Operation { + name?: string; + metadata?: ApiClientObjectMap; + done?: boolean; + error?: Status; + response?: ApiClientObjectMap; + } + interface Order { + field?: FieldReference; + direction?: OrderDirection; + } + interface Precondition { + exists?: boolean; + updateTime?: Timestamp_2; + } + interface Projection { + fields?: FieldReference[]; + } + interface QueryTarget { + parent?: string; + structuredQuery?: StructuredQuery; + } + interface ReadOnly { + readTime?: string; + } + interface ReadWrite { + retryTransaction?: string; + } + interface RollbackRequest { + transaction?: string; + } + interface RunQueryRequest { + parent?: string; + structuredQuery?: StructuredQuery; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface RunQueryResponse { + transaction?: string; + document?: Document; + readTime?: string; + skippedResults?: number; + } + interface RunAggregationQueryRequest { + parent?: string; + structuredAggregationQuery?: StructuredAggregationQuery; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface RunAggregationQueryResponse { + result?: AggregationResult; + transaction?: string; + readTime?: string; + } + interface AggregationResult { + aggregateFields?: ApiClientObjectMap; + } + interface StructuredAggregationQuery { + structuredQuery?: StructuredQuery; + aggregations?: Aggregation[]; + } + interface Aggregation { + count?: Count; + sum?: Sum; + avg?: Avg; + alias?: string; + } + interface Count { + upTo?: number; + } + interface Sum { + field?: FieldReference; + } + interface Avg { + field?: FieldReference; + } + interface Status { + code?: number; + message?: string; + details?: Array>; + } + interface StructuredQuery { + select?: Projection; + from?: CollectionSelector[]; + where?: Filter; + orderBy?: Order[]; + startAt?: Cursor; + endAt?: Cursor; + offset?: number; + limit?: number | { + value: number; + }; + } + interface Target { + query?: QueryTarget; + documents?: DocumentsTarget; + resumeToken?: string | Uint8Array; + readTime?: Timestamp_2; + targetId?: number; + once?: boolean; + expectedCount?: number | { + value: number; + }; + } + interface TargetChange { + targetChangeType?: TargetChangeTargetChangeType; + targetIds?: number[]; + cause?: Status; + resumeToken?: string | Uint8Array; + readTime?: Timestamp_2; + } + interface TransactionOptions { + readOnly?: ReadOnly; + readWrite?: ReadWrite; + } + interface UnaryFilter { + op?: UnaryFilterOp; + field?: FieldReference; + } + interface Value { + nullValue?: ValueNullValue; + booleanValue?: boolean; + integerValue?: string | number; + doubleValue?: string | number; + timestampValue?: Timestamp_2; + stringValue?: string; + bytesValue?: string | Uint8Array; + referenceValue?: string; + geoPointValue?: LatLng; + arrayValue?: ArrayValue; + mapValue?: MapValue; + } + interface Write { + update?: Document; + delete?: string; + verify?: string; + transform?: DocumentTransform; + updateMask?: DocumentMask; + updateTransforms?: FieldTransform[]; + currentDocument?: Precondition; + } + interface WriteRequest { + streamId?: string; + writes?: Write[]; + streamToken?: string | Uint8Array; + labels?: ApiClientObjectMap; + } + interface WriteResponse { + streamId?: string; + streamToken?: string | Uint8Array; + writeResults?: WriteResult[]; + commitTime?: Timestamp_2; + } + interface WriteResult { + updateTime?: Timestamp_2; + transformResults?: Value[]; + } +} + +/* Excluded from this release type: FirstPartyCredentialsSettings */ + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +declare type FulfilledHandler = ((result: T) => R | PersistencePromise) | null; + +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ +export declare class GeoPoint { + private _lat; + private _long; + /** + * Creates a new immutable `GeoPoint` object with the provided latitude and + * longitude values. + * @param latitude - The latitude as number between -90 and 90. + * @param longitude - The longitude as number between -180 and 180. + */ + constructor(latitude: number, longitude: number); + /** + * The latitude of this `GeoPoint` instance. + */ + get latitude(): number; + /** + * The longitude of this `GeoPoint` instance. + */ + get longitude(): number; + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other - The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ + isEqual(other: GeoPoint): boolean; + /** + * Actually private to JS consumers of our API, so this function is prefixed + * with an underscore. + */ + _compareTo(other: GeoPoint): number; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + latitude: Property<"number">; + longitude: Property<"number">; + }; + /** + * Returns a JSON-serializable representation of this `GeoPoint` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): { + latitude: number; + longitude: number; + type: string; + }; + /** + * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}. + * + * @param json a JSON object represention of a `GeoPoint` instance + * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): GeoPoint; +} + +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregateFromServer(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ +export declare function getAggregateFromServer(query: Query, aggregateSpec: AggregateSpecType): Promise>; + +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ +export declare function getCountFromServer(query: Query): Promise; +}, AppModelType, DbModelType>>; + +/** + * Reads the document referred to by this `DocumentReference`. + * + * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting + * for data from the server, but it may return cached data or fail if you are + * offline and the server cannot be reached. To specify this behavior, invoke + * {@link getDocFromCache} or {@link getDocFromServer}. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +export declare function getDoc(reference: DocumentReference): Promise>; + +/** + * Reads the document referred to by this `DocumentReference` from cache. + * Returns an error if the document is not currently cached. + * + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +export declare function getDocFromCache(reference: DocumentReference): Promise>; + +/** + * Reads the document referred to by this `DocumentReference` from the server. + * Returns an error if the network is not available. + * + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +export declare function getDocFromServer(reference: DocumentReference): Promise>; + +/** + * Executes the query and returns the results as a `QuerySnapshot`. + * + * Note: `getDocs()` attempts to provide up-to-date data when possible by + * waiting for data from the server, but it may return cached data or fail if + * you are offline and the server cannot be reached. To specify this behavior, + * invoke {@link getDocsFromCache} or {@link getDocsFromServer}. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +export declare function getDocs(query: Query): Promise>; + +/** + * Executes the query and returns the results as a `QuerySnapshot` from cache. + * Returns an empty result set if no documents matching the query are currently + * cached. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +export declare function getDocsFromCache(query: Query): Promise>; + +/** + * Executes the query and returns the results as a `QuerySnapshot` from the + * server. Returns an error if the network is not available. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +export declare function getDocsFromServer(query: Query): Promise>; + +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @returns The default {@link Firestore} instance of the default app. + */ +export declare function getFirestore(): Firestore; + +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @returns The default {@link Firestore} instance of the provided app. + */ +export declare function getFirestore(app: FirebaseApp): Firestore; + +/** + * Returns the existing named {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param databaseId - The name of the database. + * @returns The named {@link Firestore} instance of the default app. + * @beta + */ +export declare function getFirestore(databaseId: string): Firestore; + +/** + * Returns the existing named {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @param databaseId - The name of the database. + * @returns The named {@link Firestore} instance of the provided app. + * @beta + */ +export declare function getFirestore(app: FirebaseApp, databaseId: string): Firestore; + +/** + * Returns the PersistentCache Index Manager used by the given `Firestore` + * object. + * + * @return The `PersistentCacheIndexManager` instance, or `null` if local + * persistent storage is not in use. + */ +export declare function getPersistentCacheIndexManager(firestore: Firestore): PersistentCacheIndexManager | null; + +/** + * General purpose cache for global values. + * + * Global state that cuts across components should be saved here. Following are contained herein: + * + * `sessionToken` tracks server interaction across Listen and Write streams. This facilitates cache + * synchronization and invalidation. + */ +declare interface GlobalsCache { + /** + * Gets session token. + */ + getSessionToken(transaction: PersistenceTransaction): PersistencePromise<_ByteString>; + /** + * Sets session token. + * + * @param sessionToken - The new session token. + */ + setSessionToken(transaction: PersistenceTransaction, sessionToken: _ByteString): PersistencePromise; +} + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by + * the given value. + * + * If either the operand or the current field value uses floating point + * precision, all arithmetic follows IEEE 754 semantics. If both values are + * integers, values outside of JavaScript's safe number range + * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to + * precision loss. Furthermore, once processed by the Firestore backend, all + * integer operations are capped between -2^63 and 2^63-1. + * + * If the current field value is not of type `number`, or if the field does not + * yet exist, the transformation sets the field to the given value. + * + * @param n - The value to increment by. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +export declare function increment(n: number): FieldValue; + +/** + * The SDK definition of a Firestore index. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare interface Index { + /** The ID of the collection to index. */ + readonly collectionGroup: string; + /** A list of fields to index. */ + readonly fields?: IndexField[]; + [key: string]: unknown; +} + +/** + * A list of Firestore indexes to speed up local query execution. + * + * See {@link https://firebase.google.com/docs/reference/firestore/indexes/#json_format | JSON Format} + * for a description of the format of the index definition. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare interface IndexConfiguration { + /** A list of all Firestore indexes. */ + readonly indexes?: Index[]; + [key: string]: unknown; +} + +/** + * A single field element in an index configuration. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare interface IndexField { + /** The field path to index. */ + readonly fieldPath: string; + /** + * What type of array index to create. Set to `CONTAINS` for `array-contains` + * and `array-contains-any` indexes. + * + * Only one of `arrayConfig` or `order` should be set; + */ + readonly arrayConfig?: 'CONTAINS'; + /** + * What type of array index to create. Set to `ASCENDING` or 'DESCENDING` for + * `==`, `!=`, `<=`, `<=`, `in` and `not-in` filters. + * + * Only one of `arrayConfig` or `order` should be set. + */ + readonly order?: 'ASCENDING' | 'DESCENDING'; + [key: string]: unknown; +} + +declare type IndexFieldMode = 'MODE_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING'; + +/** The type of the index, e.g. for which type of query it can be used. */ +declare const enum IndexKind { + /** + * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries. + */ + ASCENDING = 0, + /** + * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries. + */ + DESCENDING = 1, + /** Contains index. Can be used for ArrayContains and ArrayContainsAny. */ + CONTAINS = 2 +} + +/** + * Represents a set of indexes that are used to execute queries efficiently. + * + * Currently the only index is a [collection id] => [parent path] index, used + * to execute Collection Group queries. + */ +declare interface IndexManager { + /** + * Creates an index entry mapping the collectionId (last segment of the path) + * to the parent path (either the containing document location or the empty + * path for root-level collections). Index entries can be retrieved via + * getCollectionParents(). + * + * NOTE: Currently we don't remove index entries. If this ends up being an + * issue we can devise some sort of GC strategy. + */ + addToCollectionParentIndex(transaction: PersistenceTransaction, collectionPath: _ResourcePath): PersistencePromise; + /** + * Retrieves all parent locations containing the given collectionId, as a + * list of paths (each path being either a document location or the empty + * path for a root-level collection). + */ + getCollectionParents(transaction: PersistenceTransaction, collectionId: string): PersistencePromise<_ResourcePath[]>; + /** + * Adds a field path index. + * + * Values for this index are persisted via the index backfill, which runs + * asynchronously in the background. Once the first values are written, + * an index can be used to serve partial results for any matching queries. + * Any unindexed portion of the database will continue to be served via + * collection scons. + */ + addFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + /** Removes the given field index and deletes all index values. */ + deleteFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + /** Removes all field indexes and deletes all index values. */ + deleteAllFieldIndexes(transaction: PersistenceTransaction): PersistencePromise; + /** Creates a full matched field index which serves the given target. */ + createTargetIndexes(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Returns a list of field indexes that correspond to the specified collection + * group. + * + * @param collectionGroup The collection group to get matching field indexes + * for. + * @return A collection of field indexes for the specified collection group. + */ + getFieldIndexes(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise; + /** Returns all configured field indexes. */ + getFieldIndexes(transaction: PersistenceTransaction): PersistencePromise; + /** + * Returns the type of index (if any) that can be used to serve the given + * target. + */ + getIndexType(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Returns the documents that match the given target based on the provided + * index or `null` if the target does not have a matching index. + */ + getDocumentsMatchingTarget(transaction: PersistenceTransaction, target: Target): PersistencePromise<_DocumentKey[] | null>; + /** + * Returns the next collection group to update. Returns `null` if no group + * exists. + */ + getNextCollectionGroupToUpdate(transaction: PersistenceTransaction): PersistencePromise; + /** + * Sets the collection group's latest read time. + * + * This method updates the index offset for all field indices for the + * collection group and increments their sequence number. Subsequent calls to + * `getNextCollectionGroupToUpdate()` will return a different collection group + * (unless only one collection group is configured). + */ + updateCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset): PersistencePromise; + /** Updates the index entries for the provided documents. */ + updateIndexEntries(transaction: PersistenceTransaction, documents: DocumentMap): PersistencePromise; + /** + * Iterates over all field indexes that are used to serve the given target, + * and returns the minimum offset of them all. + */ + getMinOffset(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** Returns the minimum offset for the given collection group. */ + getMinOffsetFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise; +} + +/** + * Stores the latest read time, document and batch ID that were processed for an + * index. + */ +declare class IndexOffset { + /** + * The latest read time version that has been indexed by Firestore for this + * field index. + */ + readonly readTime: SnapshotVersion; + /** + * The key of the last document that was indexed for this query. Use + * `DocumentKey.empty()` if no document has been indexed. + */ + readonly documentKey: _DocumentKey; + readonly largestBatchId: number; + constructor( + /** + * The latest read time version that has been indexed by Firestore for this + * field index. + */ + readTime: SnapshotVersion, + /** + * The key of the last document that was indexed for this query. Use + * `DocumentKey.empty()` if no document has been indexed. + */ + documentKey: _DocumentKey, largestBatchId: number); + /** Returns an offset that sorts before all regular offsets. */ + static min(): IndexOffset; + /** Returns an offset that sorts after all regular offsets. */ + static max(): IndexOffset; +} + +/** An index component consisting of field path and index type. */ +declare class IndexSegment { + /** The field path of the component. */ + readonly fieldPath: _FieldPath; + /** The fields sorting order. */ + readonly kind: IndexKind; + constructor( + /** The field path of the component. */ + fieldPath: _FieldPath, + /** The fields sorting order. */ + kind: IndexKind); +} + +/** + * Stores the "high water mark" that indicates how updated the Index is for the + * current user. + */ +declare class IndexState { + /** + * Indicates when the index was last updated (relative to other indexes). + */ + readonly sequenceNumber: number; + /** The the latest indexed read time, document and batch id. */ + readonly offset: IndexOffset; + constructor( + /** + * Indicates when the index was last updated (relative to other indexes). + */ + sequenceNumber: number, + /** The the latest indexed read time, document and batch id. */ + offset: IndexOffset); + /** The state of an index that has not yet been backfilled. */ + static empty(): IndexState; +} + +declare type IndexState_2 = 'STATE_UNSPECIFIED' | 'CREATING' | 'READY' | 'ERROR'; + +/** Represents the index state as it relates to a particular target. */ +declare const enum IndexType { + /** Indicates that no index could be found for serving the target. */ + NONE = 0, + /** + * Indicates that only a "partial index" could be found for serving the + * target. A partial index is one which does not have a segment for every + * filter/orderBy in the target. + */ + PARTIAL = 1, + /** + * Indicates that a "full index" could be found for serving the target. A full + * index is one which has a segment for every filter/orderBy in the target. + */ + FULL = 2 +} + +/** + * Initializes a new instance of {@link Firestore} with the provided settings. + * Can only be called before any other function, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will + * be associated. + * @param settings - A settings object to configure the {@link Firestore} instance. + * @param databaseId - The name of the database. + * @returns A newly initialized {@link Firestore} instance. + */ +export declare function initializeFirestore(app: FirebaseApp, settings: FirestoreSettings, databaseId?: string): Firestore; + +/* Excluded from this release type: _internalAggregationQueryToProtoRunAggregationQueryRequest */ + +/* Excluded from this release type: _internalQueryToProtoQueryTarget */ + +/* Excluded from this release type: _isBase64Available */ + +/** + * This class generates JsonObject values for the Datastore API suitable for + * sending to either GRPC stub methods or via the JSON/HTTP REST API. + * + * The serializer supports both Protobuf.js and Proto3 JSON formats. By + * setting `useProto3Json` to true, the serializer will use the Proto3 JSON + * format. + * + * For a description of the Proto3 JSON format check + * https://developers.google.com/protocol-buffers/docs/proto3#json + * + * TODO(klimt): We can remove the databaseId argument if we keep the full + * resource name in documents. + */ +declare class JsonProtoSerializer implements Serializer { + readonly databaseId: _DatabaseId; + readonly useProto3Json: boolean; + constructor(databaseId: _DatabaseId, useProto3Json: boolean); +} + +/* Excluded from this release type: JsonTypeDesc */ + +declare type Kind = 'memory' | 'persistent'; + +/** + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +export declare function limit(limit: number): QueryLimitConstraint; + +/** + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. + * + * You must specify at least one `orderBy` clause for `limitToLast` queries, + * otherwise an exception will be thrown during execution. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +export declare function limitToLast(limit: number): QueryLimitConstraint; + +declare const enum LimitType { + First = "F", + Last = "L" +} + +/** LimitType enum. */ +declare type LimitType_2 = 'FIRST' | 'LAST'; + +declare type ListenSequenceNumber = number; + +/** + * Describe the source a query listens to. + * + * Set to `default` to listen to both cache and server changes. Set to `cache` + * to listen to changes in cache only. + */ +export declare type ListenSource = 'default' | 'cache'; + +declare class LLRBEmptyNode { + get key(): never; + get value(): never; + get color(): never; + get left(): never; + get right(): never; + size: number; + copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode | LLRBEmptyNode | null, right: LLRBNode | LLRBEmptyNode | null): LLRBEmptyNode; + insert(key: K, value: V, comparator: Comparator): LLRBNode; + remove(key: K, comparator: Comparator): LLRBEmptyNode; + isEmpty(): boolean; + inorderTraversal(action: (k: K, v: V) => boolean): boolean; + reverseTraversal(action: (k: K, v: V) => boolean): boolean; + minKey(): K | null; + maxKey(): K | null; + isRed(): boolean; + checkMaxDepth(): boolean; + protected check(): 0; +} + +declare class LLRBNode { + key: K; + value: V; + readonly color: boolean; + readonly left: LLRBNode | LLRBEmptyNode; + readonly right: LLRBNode | LLRBEmptyNode; + readonly size: number; + static EMPTY: LLRBEmptyNode; + static RED: boolean; + static BLACK: boolean; + constructor(key: K, value: V, color?: boolean, left?: LLRBNode | LLRBEmptyNode, right?: LLRBNode | LLRBEmptyNode); + copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode | LLRBEmptyNode | null, right: LLRBNode | LLRBEmptyNode | null): LLRBNode; + isEmpty(): boolean; + inorderTraversal(action: (k: K, v: V) => T): T; + reverseTraversal(action: (k: K, v: V) => T): T; + private min; + minKey(): K | null; + maxKey(): K | null; + insert(key: K, value: V, comparator: Comparator): LLRBNode; + private removeMin; + remove(key: K, comparator: Comparator): LLRBNode | LLRBEmptyNode; + isRed(): boolean; + private fixUp; + private moveRedLeft; + private moveRedRight; + private rotateLeft; + private rotateRight; + private colorFlip; + checkMaxDepth(): boolean; + protected check(): number; +} + +/** + * Loads a Firestore bundle into the local cache. + * + * @param firestore - The {@link Firestore} instance to load bundles for. + * @param bundleData - An object representing the bundle to be loaded. Valid + * objects are `ArrayBuffer`, `ReadableStream` or `string`. + * + * @returns A `LoadBundleTask` object, which notifies callers with progress + * updates, and completion or error events. It can be used as a + * `Promise`. + */ +export declare function loadBundle(firestore: Firestore, bundleData: ReadableStream | ArrayBuffer | string): LoadBundleTask; + +/** + * Represents the task of loading a Firestore bundle. It provides progress of bundle + * loading, as well as task completion and error events. + * + * The API is compatible with `Promise`. + */ +export declare class LoadBundleTask implements PromiseLike { + private _progressObserver; + private _taskCompletionResolver; + private _lastProgress; + /** + * Registers functions to listen to bundle loading progress events. + * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur + * each time a Firestore document is loaded from the bundle. + * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the + * error, and there should be no more updates after this. + * @param complete - Called when the loading task is complete. + */ + onProgress(next?: (progress: LoadBundleTaskProgress) => unknown, error?: (err: Error) => unknown, complete?: () => void): void; + /** + * Implements the `Promise.catch` interface. + * + * @param onRejected - Called when an error occurs during bundle loading. + */ + catch(onRejected: (a: Error) => R | PromiseLike): Promise; + /** + * Implements the `Promise.then` interface. + * + * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update. + * The update will always have its `taskState` set to `"Success"`. + * @param onRejected - Called when an error occurs during bundle loading. + */ + then(onFulfilled?: (a: LoadBundleTaskProgress) => T | PromiseLike, onRejected?: (a: Error) => R | PromiseLike): Promise; + /** + * Notifies all observers that bundle loading has completed, with a provided + * `LoadBundleTaskProgress` object. + * + * @private + */ + _completeWith(progress: LoadBundleTaskProgress): void; + /** + * Notifies all observers that bundle loading has failed, with a provided + * `Error` as the reason. + * + * @private + */ + _failWith(error: FirestoreError): void; + /** + * Notifies a progress update of loading a bundle. + * @param progress - The new progress. + * + * @private + */ + _updateProgress(progress: LoadBundleTaskProgress): void; +} + +/** + * Represents a progress update or a final state from loading bundles. + */ +export declare interface LoadBundleTaskProgress { + /** How many documents have been loaded. */ + documentsLoaded: number; + /** How many documents are in the bundle being loaded. */ + totalDocuments: number; + /** How many bytes have been loaded. */ + bytesLoaded: number; + /** How many bytes are in the bundle being loaded. */ + totalBytes: number; + /** Current task state. */ + taskState: TaskState; +} + +/** + * A readonly view of the local state of all documents we're tracking (i.e. we + * have a cached version in remoteDocumentCache or local mutations for the + * document). The view is computed by applying the mutations in the + * MutationQueue to the RemoteDocumentCache. + */ +declare class LocalDocumentsView { + readonly remoteDocumentCache: RemoteDocumentCache; + readonly mutationQueue: MutationQueue; + readonly documentOverlayCache: DocumentOverlayCache; + readonly indexManager: IndexManager; + constructor(remoteDocumentCache: RemoteDocumentCache, mutationQueue: MutationQueue, documentOverlayCache: DocumentOverlayCache, indexManager: IndexManager); + /** + * Get the local view of the document identified by `key`. + * + * @returns Local view of the document or null if we don't have any cached + * state for it. + */ + getDocument(transaction: PersistenceTransaction, key: _DocumentKey): PersistencePromise; + /** + * Gets the local view of the documents identified by `keys`. + * + * If we don't have cached state for a document in `keys`, a NoDocument will + * be stored for that key in the resulting set. + */ + getDocuments(transaction: PersistenceTransaction, keys: DocumentKeySet): PersistencePromise; + /** + * Similar to `getDocuments`, but creates the local view from the given + * `baseDocs` without retrieving documents from the local store. + * + * @param transaction - The transaction this operation is scoped to. + * @param docs - The documents to apply local mutations to get the local views. + * @param existenceStateChanged - The set of document keys whose existence state + * is changed. This is useful to determine if some documents overlay needs + * to be recalculated. + */ + getLocalViewOfDocuments(transaction: PersistenceTransaction, docs: MutableDocumentMap, existenceStateChanged?: DocumentKeySet): PersistencePromise; + /** + * Gets the overlayed documents for the given document map, which will include + * the local view of those documents and a `FieldMask` indicating which fields + * are mutated locally, `null` if overlay is a Set or Delete mutation. + */ + getOverlayedDocuments(transaction: PersistenceTransaction, docs: MutableDocumentMap): PersistencePromise; + /** + * Fetches the overlays for {@code docs} and adds them to provided overlay map + * if the map does not already contain an entry for the given document key. + */ + private populateOverlays; + /** + * Computes the local view for the given documents. + * + * @param docs - The documents to compute views for. It also has the base + * version of the documents. + * @param overlays - The overlays that need to be applied to the given base + * version of the documents. + * @param existenceStateChanged - A set of documents whose existence states + * might have changed. This is used to determine if we need to re-calculate + * overlays from mutation queues. + * @return A map represents the local documents view. + */ + computeViews(transaction: PersistenceTransaction, docs: MutableDocumentMap, overlays: OverlayMap, existenceStateChanged: DocumentKeySet): PersistencePromise; + private recalculateAndSaveOverlays; + /** + * Recalculates overlays by reading the documents from remote document cache + * first, and saves them after they are calculated. + */ + recalculateAndSaveOverlaysForDocumentKeys(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise>; + /** + * Performs a query against the local view of all documents. + * + * @param transaction - The persistence transaction. + * @param query - The query to match documents against. + * @param offset - Read time and key to start scanning by (exclusive). + * @param context - A optional tracker to keep a record of important details + * during database local query execution. + */ + getDocumentsMatchingQuery(transaction: PersistenceTransaction, query: Query_2, offset: IndexOffset, context?: QueryContext): PersistencePromise; + /** + * Given a collection group, returns the next documents that follow the provided offset, along + * with an updated batch ID. + * + *

The documents returned by this method are ordered by remote version from the provided + * offset. If there are no more remote documents after the provided offset, documents with + * mutations in order of batch id from the offset are returned. Since all documents in a batch are + * returned together, the total number of documents returned can exceed {@code count}. + * + * @param transaction + * @param collectionGroup The collection group for the documents. + * @param offset The offset to index into. + * @param count The number of documents to return + * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id. + */ + getNextDocuments(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset, count: number): PersistencePromise; + private getDocumentsMatchingDocumentQuery; + private getDocumentsMatchingCollectionGroupQuery; + private getDocumentsMatchingCollectionQuery; +} + +declare interface LocalStore { + collectGarbage(garbageCollector: LruGarbageCollector): Promise; + /** Manages the list of active field and collection indices. */ + indexManager: IndexManager; + /** + * The "local" view of all documents (layering mutationQueue on top of + * remoteDocumentCache). + */ + localDocuments: LocalDocumentsView; +} + +/** The result of a write to the local store. */ +declare interface LocalWriteResult { + batchId: BatchId; + changes: DocumentMap; +} +export { LogLevel } + +/* Excluded from this release type: _logWarn */ + +declare interface LruGarbageCollector { + readonly params: LruParams; + collect(txn: PersistenceTransaction, activeTargetIds: ActiveTargets): PersistencePromise; + /** Given a percentile of target to collect, returns the number of targets to collect. */ + calculateTargetCount(txn: PersistenceTransaction, percentile: number): PersistencePromise; + /** Returns the nth sequence number, counting in order from the smallest. */ + nthSequenceNumber(txn: PersistenceTransaction, n: number): PersistencePromise; + /** + * Removes documents that have a sequence number equal to or less than the + * upper bound and are not otherwise pinned. + */ + removeOrphanedDocuments(txn: PersistenceTransaction, upperBound: ListenSequenceNumber): PersistencePromise; + getCacheSize(txn: PersistenceTransaction): PersistencePromise; + /** + * Removes targets with a sequence number equal to or less than the given + * upper bound, and removes document associations with those targets. + */ + removeTargets(txn: PersistenceTransaction, upperBound: ListenSequenceNumber, activeTargetIds: ActiveTargets): PersistencePromise; +} + +declare class LruParams { + readonly cacheSizeCollectionThreshold: number; + readonly percentileToCollect: number; + readonly maximumSequenceNumbersToCollect: number; + private static readonly DEFAULT_COLLECTION_PERCENTILE; + private static readonly DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT; + static withCacheSize(cacheSize: number): LruParams; + static readonly DEFAULT: LruParams; + static readonly DISABLED: LruParams; + constructor(cacheSizeCollectionThreshold: number, percentileToCollect: number, maximumSequenceNumbersToCollect: number); +} + +/** + * Describes the results of a garbage collection run. `didRun` will be set to + * `false` if collection was skipped (either it is disabled or the cache size + * has not hit the threshold). If collection ran, the other fields will be + * filled in with the details of the results. + */ +declare interface LruResults { + readonly didRun: boolean; + readonly sequenceNumbersCollected: number; + readonly targetsRemoved: number; + readonly documentsRemoved: number; +} + +declare type MapValue = firestoreV1ApiClientInterfaces.MapValue; + +/** + * An settings object to configure an `MemoryLocalCache` instance. + */ +export declare type MemoryCacheSettings = { + /** + * The garbage collector to use, for the memory cache layer. + * A `MemoryEagerGarbageCollector` is used when this is undefined. + */ + garbageCollector?: MemoryGarbageCollector; +}; + +/** + * A garbage collector deletes documents whenever they are not part of any + * active queries, and have no local mutations attached to them. + * + * This collector tries to ensure lowest memory footprints from the SDK, + * at the risk of documents not being cached for offline queries or for + * direct queries to the cache. + * + * Use factory function {@link memoryEagerGarbageCollector()} to create an + * instance of this collector. + */ +export declare type MemoryEagerGarbageCollector = { + kind: 'memoryEager'; + /* Excluded from this release type: _offlineComponentProvider */ +}; + +/** + * Creates an instance of `MemoryEagerGarbageCollector`. This is also the + * default garbage collector unless it is explicitly specified otherwise. + */ +export declare function memoryEagerGarbageCollector(): MemoryEagerGarbageCollector; + +/** + * Union type from all support garbage collectors for memory local cache. + */ +export declare type MemoryGarbageCollector = MemoryEagerGarbageCollector | MemoryLruGarbageCollector; + +/** + * Provides an in-memory cache to the SDK. This is the default cache unless explicitly + * configured otherwise. + * + * To use, create an instance using the factory function {@link memoryLocalCache()}, then + * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using + * the settings object. + */ +export declare type MemoryLocalCache = { + kind: 'memory'; + /* Excluded from this release type: _onlineComponentProvider */ + /* Excluded from this release type: _offlineComponentProvider */ +}; + +/** + * Creates an instance of `MemoryLocalCache`. The instance can be set to + * `FirestoreSettings.cache` to tell the SDK which cache layer to use. + */ +export declare function memoryLocalCache(settings?: MemoryCacheSettings): MemoryLocalCache; + +/** + * A garbage collector deletes Least-Recently-Used documents in multiple + * batches. + * + * This collector is configured with a target size, and will only perform + * collection when the cached documents exceed the target size. It avoids + * querying backend repeated for the same query or document, at the risk + * of having a larger memory footprint. + * + * Use factory function {@link memoryLruGarbageCollector()} to create a + * instance of this collector. + */ +export declare type MemoryLruGarbageCollector = { + kind: 'memoryLru'; + /* Excluded from this release type: _offlineComponentProvider */ +}; + +/** + * Creates an instance of `MemoryLruGarbageCollector`. + * + * A target size can be specified as part of the setting parameter. The + * collector will start deleting documents once the cache size exceeds + * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes). + */ +export declare function memoryLruGarbageCollector(settings?: { + cacheSizeBytes?: number; +}): MemoryLruGarbageCollector; + +/** + * Represents a document in Firestore with a key, version, data and whether it + * has local mutations applied to it. + * + * Documents can transition between states via `convertToFoundDocument()`, + * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does + * not transition to one of these states even after all mutations have been + * applied, `isValidDocument()` returns false and the document should be removed + * from all views. + */ +declare class MutableDocument implements Document_2 { + readonly key: _DocumentKey; + private documentType; + version: SnapshotVersion; + readTime: SnapshotVersion; + createTime: SnapshotVersion; + data: ObjectValue; + private documentState; + private constructor(); + /** + * Creates a document with no known version or data, but which can serve as + * base document for mutations. + */ + static newInvalidDocument(documentKey: _DocumentKey): MutableDocument; + /** + * Creates a new document that is known to exist with the given data at the + * given version. + */ + static newFoundDocument(documentKey: _DocumentKey, version: SnapshotVersion, createTime: SnapshotVersion, value: ObjectValue): MutableDocument; + /** Creates a new document that is known to not exist at the given version. */ + static newNoDocument(documentKey: _DocumentKey, version: SnapshotVersion): MutableDocument; + /** + * Creates a new document that is known to exist at the given version but + * whose data is not known (e.g. a document that was updated without a known + * base document). + */ + static newUnknownDocument(documentKey: _DocumentKey, version: SnapshotVersion): MutableDocument; + /** + * Changes the document type to indicate that it exists and that its version + * and data are known. + */ + convertToFoundDocument(version: SnapshotVersion, value: ObjectValue): MutableDocument; + /** + * Changes the document type to indicate that it doesn't exist at the given + * version. + */ + convertToNoDocument(version: SnapshotVersion): MutableDocument; + /** + * Changes the document type to indicate that it exists at a given version but + * that its data is not known (e.g. a document that was updated without a known + * base document). + */ + convertToUnknownDocument(version: SnapshotVersion): MutableDocument; + setHasCommittedMutations(): MutableDocument; + setHasLocalMutations(): MutableDocument; + setReadTime(readTime: SnapshotVersion): MutableDocument; + get hasLocalMutations(): boolean; + get hasCommittedMutations(): boolean; + get hasPendingWrites(): boolean; + isValidDocument(): boolean; + isFoundDocument(): boolean; + isNoDocument(): boolean; + isUnknownDocument(): boolean; + isEqual(other: Document_2 | null | undefined): boolean; + mutableCopy(): MutableDocument; + toString(): string; +} + +/** Miscellaneous collection types / constants. */ +declare type MutableDocumentMap = SortedMap<_DocumentKey, MutableDocument>; + +/** + * A mutation describes a self-contained change to a document. Mutations can + * create, replace, delete, and update subsets of documents. + * + * Mutations not only act on the value of the document but also its version. + * + * For local mutations (mutations that haven't been committed yet), we preserve + * the existing version for Set and Patch mutations. For Delete mutations, we + * reset the version to 0. + * + * Here's the expected transition table. + * + * MUTATION APPLIED TO RESULTS IN + * + * SetMutation Document(v3) Document(v3) + * SetMutation NoDocument(v3) Document(v0) + * SetMutation InvalidDocument(v0) Document(v0) + * PatchMutation Document(v3) Document(v3) + * PatchMutation NoDocument(v3) NoDocument(v3) + * PatchMutation InvalidDocument(v0) UnknownDocument(v3) + * DeleteMutation Document(v3) NoDocument(v0) + * DeleteMutation NoDocument(v3) NoDocument(v0) + * DeleteMutation InvalidDocument(v0) NoDocument(v0) + * + * For acknowledged mutations, we use the updateTime of the WriteResponse as + * the resulting version for Set and Patch mutations. As deletes have no + * explicit update time, we use the commitTime of the WriteResponse for + * Delete mutations. + * + * If a mutation is acknowledged by the backend but fails the precondition check + * locally, we transition to an `UnknownDocument` and rely on Watch to send us + * the updated version. + * + * Field transforms are used only with Patch and Set Mutations. We use the + * `updateTransforms` message to store transforms, rather than the `transforms`s + * messages. + * + * ## Subclassing Notes + * + * Every type of mutation needs to implement its own applyToRemoteDocument() and + * applyToLocalView() to implement the actual behavior of applying the mutation + * to some source document (see `setMutationApplyToRemoteDocument()` for an + * example). + */ +declare abstract class Mutation { + abstract readonly type: MutationType; + abstract readonly key: _DocumentKey; + abstract readonly precondition: Precondition; + abstract readonly fieldTransforms: FieldTransform[]; + /** + * Returns a `FieldMask` representing the fields that will be changed by + * applying this mutation. Returns `null` if the mutation will overwrite the + * entire document. + */ + abstract getFieldMask(): FieldMask | null; +} + +/** + * A batch of mutations that will be sent as one unit to the backend. + */ +declare class MutationBatch { + batchId: BatchId; + localWriteTime: Timestamp; + baseMutations: Mutation[]; + mutations: Mutation[]; + /** + * @param batchId - The unique ID of this mutation batch. + * @param localWriteTime - The original write time of this mutation. + * @param baseMutations - Mutations that are used to populate the base + * values when this mutation is applied locally. This can be used to locally + * overwrite values that are persisted in the remote document cache. Base + * mutations are never sent to the backend. + * @param mutations - The user-provided mutations in this mutation batch. + * User-provided mutations are applied both locally and remotely on the + * backend. + */ + constructor(batchId: BatchId, localWriteTime: Timestamp, baseMutations: Mutation[], mutations: Mutation[]); + /** + * Applies all the mutations in this MutationBatch to the specified document + * to compute the state of the remote document + * + * @param document - The document to apply mutations to. + * @param batchResult - The result of applying the MutationBatch to the + * backend. + */ + applyToRemoteDocument(document: MutableDocument, batchResult: MutationBatchResult): void; + /** + * Computes the local view of a document given all the mutations in this + * batch. + * + * @param document - The document to apply mutations to. + * @param mutatedFields - Fields that have been updated before applying this mutation batch. + * @returns A `FieldMask` representing all the fields that are mutated. + */ + applyToLocalView(document: MutableDocument, mutatedFields: FieldMask | null): FieldMask | null; + /** + * Computes the local view for all provided documents given the mutations in + * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to + * replace all the mutation applications. + */ + applyToLocalDocumentSet(documentMap: OverlayedDocumentMap, documentsWithoutRemoteVersion: DocumentKeySet): MutationMap; + keys(): DocumentKeySet; + isEqual(other: MutationBatch): boolean; +} + +/** The result of applying a mutation batch to the backend. */ +declare class MutationBatchResult { + readonly batch: MutationBatch; + readonly commitVersion: SnapshotVersion; + readonly mutationResults: MutationResult[]; + /** + * A pre-computed mapping from each mutated document to the resulting + * version. + */ + readonly docVersions: DocumentVersionMap; + private constructor(); + /** + * Creates a new MutationBatchResult for the given batch and results. There + * must be one result for each mutation in the batch. This static factory + * caches a document=>version mapping (docVersions). + */ + static from(batch: MutationBatch, commitVersion: SnapshotVersion, results: MutationResult[]): MutationBatchResult; +} + +declare type MutationMap = DocumentKeyMap; + +/** A queue of mutations to apply to the remote store. */ +declare interface MutationQueue { + /** Returns true if this queue contains no mutation batches. */ + checkEmpty(transaction: PersistenceTransaction): PersistencePromise; + /** + * Creates a new mutation batch and adds it to this mutation queue. + * + * @param transaction - The transaction this operation is scoped to. + * @param localWriteTime - The original write time of this mutation. + * @param baseMutations - Mutations that are used to populate the base values + * when this mutation is applied locally. These mutations are used to locally + * overwrite values that are persisted in the remote document cache. + * @param mutations - The user-provided mutations in this mutation batch. + */ + addMutationBatch(transaction: PersistenceTransaction, localWriteTime: Timestamp, baseMutations: Mutation[], mutations: Mutation[]): PersistencePromise; + /** + * Loads the mutation batch with the given batchId. + */ + lookupMutationBatch(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + /** + * Gets the first unacknowledged mutation batch after the passed in batchId + * in the mutation queue or null if empty. + * + * @param batchId - The batch to search after, or BATCHID_UNKNOWN for the + * first mutation in the queue. + * + * @returns the next mutation or null if there wasn't one. + */ + getNextMutationBatchAfterBatchId(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + /** + * Gets the largest (latest) batch id in mutation queue for the current user + * that is pending server response, returns `BATCHID_UNKNOWN` if the queue is + * empty. + * + * @returns the largest batch id in the mutation queue that is not + * acknowledged. + */ + getHighestUnacknowledgedBatchId(transaction: PersistenceTransaction): PersistencePromise; + /** Gets all mutation batches in the mutation queue. */ + getAllMutationBatches(transaction: PersistenceTransaction): PersistencePromise; + /** + * Finds all mutation batches that could possibly affect the given + * document key. Not all mutations in a batch will necessarily affect the + * document key, so when looping through the batch you'll need to check that + * the mutation itself matches the key. + * + * Batches are guaranteed to be in sorted order. + * + * Note that because of this requirement implementations are free to return + * mutation batches that don't contain the document key at all if it's + * convenient. + */ + getAllMutationBatchesAffectingDocumentKey(transaction: PersistenceTransaction, documentKey: _DocumentKey): PersistencePromise; + /** + * Finds all mutation batches that could possibly affect the given set of + * document keys. Not all mutations in a batch will necessarily affect each + * key, so when looping through the batch you'll need to check that the + * mutation itself matches the key. + * + * Batches are guaranteed to be in sorted order. + * + * Note that because of this requirement implementations are free to return + * mutation batches that don't contain any of the document keys at all if it's + * convenient. + */ + getAllMutationBatchesAffectingDocumentKeys(transaction: PersistenceTransaction, documentKeys: SortedMap<_DocumentKey, unknown>): PersistencePromise; + /** + * Finds all mutation batches that could affect the results for the given + * query. Not all mutations in a batch will necessarily affect the query, so + * when looping through the batch you'll need to check that the mutation + * itself matches the query. + * + * Batches are guaranteed to be in sorted order. + * + * Note that because of this requirement implementations are free to return + * mutation batches that don't match the query at all if it's convenient. + * + * NOTE: A PatchMutation does not need to include all fields in the query + * filter criteria in order to be a match (but any fields it does contain do + * need to match). + */ + getAllMutationBatchesAffectingQuery(transaction: PersistenceTransaction, query: Query_2): PersistencePromise; + /** + * Removes the given mutation batch from the queue. This is useful in two + * circumstances: + * + * + Removing an applied mutation from the head of the queue + * + Removing a rejected mutation from anywhere in the queue + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMutationBatch(transaction: PersistenceTransaction, batch: MutationBatch): PersistencePromise; + /** + * Performs a consistency check, examining the mutation queue for any + * leaks, if possible. + */ + performConsistencyCheck(transaction: PersistenceTransaction): PersistencePromise; +} + +/** The result of successfully applying a mutation to the backend. */ +declare class MutationResult { + /** + * The version at which the mutation was committed: + * + * - For most operations, this is the updateTime in the WriteResult. + * - For deletes, the commitTime of the WriteResponse (because deletes are + * not stored and have no updateTime). + * + * Note that these versions can be different: No-op writes will not change + * the updateTime even though the commitTime advances. + */ + readonly version: SnapshotVersion; + /** + * The resulting fields returned from the backend after a mutation + * containing field transforms has been committed. Contains one FieldValue + * for each FieldTransform that was in the mutation. + * + * Will be empty if the mutation did not contain any field transforms. + */ + readonly transformResults: Array; + constructor( + /** + * The version at which the mutation was committed: + * + * - For most operations, this is the updateTime in the WriteResult. + * - For deletes, the commitTime of the WriteResponse (because deletes are + * not stored and have no updateTime). + * + * Note that these versions can be different: No-op writes will not change + * the updateTime even though the commitTime advances. + */ + version: SnapshotVersion, + /** + * The resulting fields returned from the backend after a mutation + * containing field transforms has been committed. Contains one FieldValue + * for each FieldTransform that was in the mutation. + * + * Will be empty if the mutation did not contain any field transforms. + */ + transformResults: Array); +} + +declare const enum MutationType { + Set = 0, + Patch = 1, + Delete = 2, + Verify = 3 +} + +/** + * Represents a Query saved by the SDK in its local storage. + */ +declare interface NamedQuery { + /** The name of the query. */ + readonly name: string; + /** The underlying query associated with `name`. */ + readonly query: Query_2; + /** The time at which the results for this query were read. */ + readonly readTime: SnapshotVersion; +} + +/** + * Reads a Firestore {@link Query} from local cache, identified by the given + * name. + * + * The named queries are packaged into bundles on the server side (along + * with resulting documents), and loaded to local cache using `loadBundle`. Once + * in local cache, use this method to extract a {@link Query} by name. + * + * @param firestore - The {@link Firestore} instance to read the query from. + * @param name - The name of the query. + * @returns A `Promise` that is resolved with the Query or `null`. + */ +export declare function namedQuery(firestore: Firestore, name: string): Promise; + +/** Properties of a NamedQuery. */ +declare interface NamedQuery_2 { + /** NamedQuery name */ + name?: string | null; + /** NamedQuery bundledQuery */ + bundledQuery?: BundledQuery | null; + /** NamedQuery readTime */ + readTime?: Timestamp_2 | null; +} + +/** + * For each field (e.g. 'bar'), find all nested keys (e.g. {'bar.baz': T1, + * 'bar.qux': T2}). Intersect them together to make a single map containing + * all possible keys that are all marked as optional + */ +export declare type NestedUpdateFields> = UnionToIntersection<{ + [K in keyof T & string]: ChildUpdateFields; +}[keyof T & string]>; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A map implementation that uses objects as keys. Objects must have an + * associated equals function and must be immutable. Entries in the map are + * stored together with the key being produced from the mapKeyFn. This map + * automatically handles collisions of keys. + */ +declare class ObjectMap { + private mapKeyFn; + private equalsFn; + /** + * The inner map for a key/value pair. Due to the possibility of collisions we + * keep a list of entries that we do a linear search through to find an actual + * match. Note that collisions should be rare, so we still expect near + * constant time lookups in practice. + */ + private inner; + /** The number of entries stored in the map */ + private innerSize; + constructor(mapKeyFn: (key: KeyType) => string, equalsFn: (l: KeyType, r: KeyType) => boolean); + /** Get a value for this key, or undefined if it does not exist. */ + get(key: KeyType): ValueType | undefined; + has(key: KeyType): boolean; + /** Put this key and value in the map. */ + set(key: KeyType, value: ValueType): void; + /** + * Remove this key from the map. Returns a boolean if anything was deleted. + */ + delete(key: KeyType): boolean; + forEach(fn: (key: KeyType, val: ValueType) => void): void; + isEmpty(): boolean; + size(): number; +} + +/** + * An ObjectValue represents a MapValue in the Firestore Proto and offers the + * ability to add and remove fields (via the ObjectValueBuilder). + */ +declare class ObjectValue { + readonly value: { + mapValue: MapValue; + }; + constructor(value: { + mapValue: MapValue; + }); + static empty(): ObjectValue; + /** + * Returns the value at the given path or null. + * + * @param path - the path to search + * @returns The value at the path or null if the path is not set. + */ + field(path: _FieldPath): Value | null; + /** + * Sets the field to the provided value. + * + * @param path - The field path to set. + * @param value - The value to set. + */ + set(path: _FieldPath, value: Value): void; + /** + * Sets the provided fields to the provided values. + * + * @param data - A map of fields to values (or null for deletes). + */ + setAll(data: Map<_FieldPath, Value | null>): void; + /** + * Removes the field at the specified path. If there is no field at the + * specified path, nothing is changed. + * + * @param path - The field path to remove. + */ + delete(path: _FieldPath): void; + isEqual(other: ObjectValue): boolean; + /** + * Returns the map that contains the leaf element of `path`. If the parent + * entry does not yet exist, or if it is not a map, a new map will be created. + */ + private getFieldsMap; + /** + * Modifies `fieldsMap` by adding, replacing or deleting the specified + * entries. + */ + private applyChanges; + clone(): ObjectValue; +} + +/** + * Initializes and wires components that are needed to interface with the local + * cache. Implementations override `initialize()` to provide all components. + */ +declare interface OfflineComponentProvider { + readonly kind: Kind; + persistence: Persistence; + sharedClientState: SharedClientState; + localStore: LocalStore; + gcScheduler: Scheduler | null; + indexBackfillerScheduler: Scheduler | null; + synchronizeTabs: boolean; + initialize(cfg: ComponentConfiguration): Promise; + terminate(): Promise; +} + +declare interface OfflineComponentProviderFactory { + build(onlineComponents: OnlineComponentProvider): OfflineComponentProvider; +} + +/** + * Initializes and wires the components that are needed to interface with the + * network. + */ +declare class OnlineComponentProvider { + static readonly provider: OnlineComponentProviderFactory; + protected localStore: LocalStore; + protected sharedClientState: SharedClientState; + datastore: Datastore; + eventManager: EventManager; + remoteStore: RemoteStore; + syncEngine: SyncEngine; + initialize(offlineComponentProvider: OfflineComponentProvider, cfg: ComponentConfiguration): Promise; + createEventManager(cfg: ComponentConfiguration): EventManager; + createDatastore(cfg: ComponentConfiguration): Datastore; + createRemoteStore(cfg: ComponentConfiguration): RemoteStore; + createSyncEngine(cfg: ComponentConfiguration, startAsPrimary: boolean): SyncEngine; + terminate(): Promise; +} + +declare interface OnlineComponentProviderFactory { + build(): OnlineComponentProvider; +} + +/** + * Describes the online state of the Firestore client. Note that this does not + * indicate whether or not the remote store is trying to connect or not. This is + * primarily used by the View / EventManager code to change their behavior while + * offline (e.g. get() calls shouldn't wait for data from the server and + * snapshot events should set metadata.isFromCache=true). + * + * The string values should not be changed since they are persisted in + * WebStorage. + */ +declare const enum OnlineState { + /** + * The Firestore client is in an unknown online state. This means the client + * is either not actively trying to establish a connection or it is currently + * trying to establish a connection, but it has not succeeded or failed yet. + * Higher-level components should not operate in offline mode. + */ + Unknown = "Unknown", + /** + * The client is connected and the connections are healthy. This state is + * reached after a successful connection and there has been at least one + * successful message received from the backends. + */ + Online = "Online", + /** + * The client is either trying to establish a connection but failing, or it + * has been explicitly marked offline via a call to disableNetwork(). + * Higher-level components should operate in offline mode. + */ + Offline = "Offline" +} + +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshot(reference: DocumentReference, observer: { + next?: (snapshot: DocumentSnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}): Unsubscribe; + +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshot(reference: DocumentReference, options: SnapshotListenOptions, observer: { + next?: (snapshot: DocumentSnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}): Unsubscribe; + +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(reference: DocumentReference, onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe; + +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param options - Options controlling the listen behavior. + * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(reference: DocumentReference, options: SnapshotListenOptions, onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe; + +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The + * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(query: Query, observer: { + next?: (snapshot: QuerySnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}): Unsubscribe; + +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The + * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(query: Query, options: SnapshotListenOptions, observer: { + next?: (snapshot: QuerySnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}): Unsubscribe; + +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The + * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(query: Query, onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe; + +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The + * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param options - Options controlling the listen behavior. + * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(query: Query, options: SnapshotListenOptions, onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe; + +/** + * Attaches a listener for `QuerySnapshot` events based on data generated by invoking + * {@link QuerySnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. + * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void, converter?: FirestoreDataConverter): Unsubscribe; + +/** + * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking + * {@link DocumentSnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. + * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are + * never ending. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void, converter?: FirestoreDataConverter): Unsubscribe; + +/** + * Attaches a listener for `QuerySnapshot` events based on data generated by invoking + * {@link QuerySnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, options: SnapshotListenOptions, onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void, converter?: FirestoreDataConverter): Unsubscribe; + +/** + * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking + * {@link DocumentSnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks + * or pass a single observer object with `next` and `error` callbacks. The listener can be cancelled + * by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, options: SnapshotListenOptions, onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void, converter?: FirestoreDataConverter): Unsubscribe; + +/** + * Attaches a listener for `QuerySnapshot` events based on QuerySnapshot data generated by invoking + * {@link QuerySnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, observer: { + next: (snapshot: QuerySnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}, converter?: FirestoreDataConverter): Unsubscribe; + +/** + * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking + * {@link DocumentSnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks + * or pass a single observer object with `next` and `error` callbacks. The listener can be cancelled + * by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, observer: { + next: (snapshot: DocumentSnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}, converter?: FirestoreDataConverter): Unsubscribe; + +/** + * Attaches a listener for `QuerySnapshot` events based on QuerySnapshot data generated by invoking + * {@link QuerySnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, options: SnapshotListenOptions, observer: { + next: (snapshot: QuerySnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}, converter?: FirestoreDataConverter): Unsubscribe; + +/** + * Attaches a listener for `DocumentSnapshot` events based on QuerySnapshot data generated by + * invoking {@link DocumentSnapshot.toJSON} You may either pass individual `onNext` and `onError` + * callbacks or pass a single observer object with `next` and `error` callbacks. The listener can be + * cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, options: SnapshotListenOptions, observer: { + next: (snapshot: DocumentSnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}, converter?: FirestoreDataConverter): Unsubscribe; + +/** + * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync + * event indicates that all listeners affected by a given change have fired, + * even if a single server-generated change affects multiple listeners. + * + * NOTE: The snapshots-in-sync event only indicates that listeners are in sync + * with each other, but does not relate to whether those snapshots are in sync + * with the server. Use SnapshotMetadata in the individual listeners to + * determine if a snapshot is from the cache or the server. + * + * @param firestore - The instance of Firestore for synchronizing snapshots. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel the snapshot + * listener. + */ +export declare function onSnapshotsInSync(firestore: Firestore, observer: { + next?: (value: void) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}): Unsubscribe; + +/** + * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync + * event indicates that all listeners affected by a given change have fired, + * even if a single server-generated change affects multiple listeners. + * + * NOTE: The snapshots-in-sync event only indicates that listeners are in sync + * with each other, but does not relate to whether those snapshots are in sync + * with the server. Use `SnapshotMetadata` in the individual listeners to + * determine if a snapshot is from the cache or the server. + * + * @param firestore - The `Firestore` instance for synchronizing snapshots. + * @param onSync - A callback to be called every time all snapshot listeners are + * in sync with each other. + * @returns An unsubscribe function that can be called to cancel the snapshot + * listener. + */ +export declare function onSnapshotsInSync(firestore: Firestore, onSync: () => void): Unsubscribe; + +declare const enum Operator { + LESS_THAN = "<", + LESS_THAN_OR_EQUAL = "<=", + EQUAL = "==", + NOT_EQUAL = "!=", + GREATER_THAN = ">", + GREATER_THAN_OR_EQUAL = ">=", + ARRAY_CONTAINS = "array-contains", + IN = "in", + NOT_IN = "not-in", + ARRAY_CONTAINS_ANY = "array-contains-any" +} + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +export declare function or(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; + +/** + * An ordering on a field, in some Direction. Direction defaults to ASCENDING. + */ +declare class OrderBy { + readonly field: _FieldPath; + readonly dir: Direction; + constructor(field: _FieldPath, dir?: Direction); +} + +/** + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the + * specified field, optionally in descending order instead of ascending. + * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * + * @param fieldPath - The field to sort by. + * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @returns The created {@link QueryOrderByConstraint}. + */ +export declare function orderBy(fieldPath: string | FieldPath, directionStr?: OrderByDirection): QueryOrderByConstraint; + +/** + * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc' + * (descending or ascending). + */ +export declare type OrderByDirection = 'desc' | 'asc'; + +declare type OrderDirection = 'DIRECTION_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING'; + +/** + * Representation of an overlay computed by Firestore. + * + * Holds information about a mutation and the largest batch id in Firestore when + * the mutation was created. + */ +declare class Overlay { + readonly largestBatchId: number; + readonly mutation: Mutation; + constructor(largestBatchId: number, mutation: Mutation); + getKey(): _DocumentKey; + isEqual(other: Overlay | null): boolean; + toString(): string; +} + +/** + * Represents a local view (overlay) of a document, and the fields that are + * locally mutated. + */ +declare class OverlayedDocument { + readonly overlayedDocument: Document_2; + /** + * The fields that are locally mutated by patch mutations. + * + * If the overlayed document is from set or delete mutations, this is `null`. + * If there is no overlay (mutation) for the document, this is an empty `FieldMask`. + */ + readonly mutatedFields: FieldMask | null; + constructor(overlayedDocument: Document_2, + /** + * The fields that are locally mutated by patch mutations. + * + * If the overlayed document is from set or delete mutations, this is `null`. + * If there is no overlay (mutation) for the document, this is an empty `FieldMask`. + */ + mutatedFields: FieldMask | null); +} + +declare type OverlayedDocumentMap = DocumentKeyMap; + +declare type OverlayMap = DocumentKeyMap; + +declare interface ParseContext { + readonly databaseId: _DatabaseId; + readonly ignoreUndefinedProperties: boolean; +} + +/** The result of parsing document data (e.g. for a setData call). */ +declare class ParsedSetData { + readonly data: ObjectValue; + readonly fieldMask: FieldMask | null; + readonly fieldTransforms: FieldTransform[]; + constructor(data: ObjectValue, fieldMask: FieldMask | null, fieldTransforms: FieldTransform[]); + toMutation(key: _DocumentKey, precondition: Precondition): Mutation; +} + +/** The result of parsing "update" data (i.e. for an updateData call). */ +declare class ParsedUpdateData { + readonly data: ObjectValue; + readonly fieldMask: FieldMask; + readonly fieldTransforms: FieldTransform[]; + constructor(data: ObjectValue, fieldMask: FieldMask, fieldTransforms: FieldTransform[]); + toMutation(key: _DocumentKey, precondition: Precondition): Mutation; +} + +/** + * Similar to TypeScript's `Partial`, but allows nested fields to be + * omitted and FieldValues to be passed in as property values. + */ +export declare type PartialWithFieldValue = Partial | (T extends Primitive ? T : T extends {} ? { + [K in keyof T]?: PartialWithFieldValue | FieldValue; +} : never); + +/** + * Persistence is the lowest-level shared interface to persistent storage in + * Firestore. + * + * Persistence is used to create MutationQueue and RemoteDocumentCache + * instances backed by persistence (which might be in-memory or LevelDB). + * + * Persistence also exposes an API to create and run PersistenceTransactions + * against persistence. All read / write operations must be wrapped in a + * transaction. Implementations of PersistenceTransaction / Persistence only + * need to guarantee that writes made against the transaction are not made to + * durable storage until the transaction resolves its PersistencePromise. + * Since memory-only storage components do not alter durable storage, they are + * free to ignore the transaction. + * + * This contract is enough to allow the LocalStore be be written + * independently of whether or not the stored state actually is durably + * persisted. If persistent storage is enabled, writes are grouped together to + * avoid inconsistent state that could cause crashes. + * + * Concretely, when persistent storage is enabled, the persistent versions of + * MutationQueue, RemoteDocumentCache, and others (the mutators) will + * defer their writes into a transaction. Once the local store has completed + * one logical operation, it commits the transaction. + * + * When persistent storage is disabled, the non-persistent versions of the + * mutators ignore the transaction. This short-cut is allowed because + * memory-only storage leaves no state so it cannot be inconsistent. + * + * This simplifies the implementations of the mutators and allows memory-only + * implementations to supplement the persistent ones without requiring any + * special dual-store implementation of Persistence. The cost is that the + * LocalStore needs to be slightly careful about the order of its reads and + * writes in order to avoid relying on being able to read back uncommitted + * writes. + */ +declare interface Persistence { + /** + * Whether or not this persistence instance has been started. + */ + readonly started: boolean; + readonly referenceDelegate: ReferenceDelegate; + /** Starts persistence. */ + start(): Promise; + /** + * Releases any resources held during eager shutdown. + */ + shutdown(): Promise; + /** + * Registers a listener that gets called when the database receives a + * version change event indicating that it has deleted. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setDatabaseDeletedListener(databaseDeletedListener: () => Promise): void; + /** + * Adjusts the current network state in the client's metadata, potentially + * affecting the primary lease. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setNetworkEnabled(networkEnabled: boolean): void; + /** + * Returns GlobalCache representing a general purpose cache for global values. + */ + getGlobalsCache(): GlobalsCache; + /** + * Returns a MutationQueue representing the persisted mutations for the + * given user. + * + * Note: The implementation is free to return the same instance every time + * this is called for a given user. In particular, the memory-backed + * implementation does this to emulate the persisted implementation to the + * extent possible (e.g. in the case of uid switching from + * sally=>jack=>sally, sally's mutation queue will be preserved). + */ + getMutationQueue(user: User, indexManager: IndexManager): MutationQueue; + /** + * Returns a TargetCache representing the persisted cache of targets. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getTargetCache(): TargetCache; + /** + * Returns a RemoteDocumentCache representing the persisted cache of remote + * documents. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getRemoteDocumentCache(): RemoteDocumentCache; + /** + * Returns a BundleCache representing the persisted cache of loaded bundles. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getBundleCache(): BundleCache; + /** + * Returns an IndexManager instance that manages our persisted query indexes. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getIndexManager(user: User): IndexManager; + /** + * Returns a DocumentOverlayCache representing the documents that are mutated + * locally. + */ + getDocumentOverlayCache(user: User): DocumentOverlayCache; + /** + * Performs an operation inside a persistence transaction. Any reads or writes + * against persistence must be performed within a transaction. Writes will be + * committed atomically once the transaction completes. + * + * Persistence operations are asynchronous and therefore the provided + * transactionOperation must return a PersistencePromise. When it is resolved, + * the transaction will be committed and the Promise returned by this method + * will resolve. + * + * @param action - A description of the action performed by this transaction, + * used for logging. + * @param mode - The underlying mode of the IndexedDb transaction. Can be + * 'readonly', 'readwrite' or 'readwrite-primary'. Transactions marked + * 'readwrite-primary' can only be executed by the primary client. In this + * mode, the transactionOperation will not be run if the primary lease cannot + * be acquired and the returned promise will be rejected with a + * FAILED_PRECONDITION error. + * @param transactionOperation - The operation to run inside a transaction. + * @returns A `Promise` that is resolved once the transaction completes. + */ + runTransaction(action: string, mode: PersistenceTransactionMode, transactionOperation: (transaction: PersistenceTransaction) => PersistencePromise): Promise; +} + +/** + * PersistencePromise is essentially a re-implementation of Promise except + * it has a .next() method instead of .then() and .next() and .catch() callbacks + * are executed synchronously when a PersistencePromise resolves rather than + * asynchronously (Promise implementations use setImmediate() or similar). + * + * This is necessary to interoperate with IndexedDB which will automatically + * commit transactions if control is returned to the event loop without + * synchronously initiating another operation on the transaction. + * + * NOTE: .then() and .catch() only allow a single consumer, unlike normal + * Promises. + */ +declare class PersistencePromise { + private nextCallback; + private catchCallback; + private result; + private error; + private isDone; + private callbackAttached; + constructor(callback: (resolve: Resolver, reject: Rejector) => void); + catch(fn: (error: Error) => R | PersistencePromise): PersistencePromise; + next(nextFn?: FulfilledHandler, catchFn?: RejectedHandler): PersistencePromise; + toPromise(): Promise; + private wrapUserFunction; + private wrapSuccess; + private wrapFailure; + static resolve(): PersistencePromise; + static resolve(result: R): PersistencePromise; + static reject(error: Error): PersistencePromise; + static waitFor(all: { + forEach: (cb: (el: PersistencePromise) => void) => void; + }): PersistencePromise; + /** + * Given an array of predicate functions that asynchronously evaluate to a + * boolean, implements a short-circuiting `or` between the results. Predicates + * will be evaluated until one of them returns `true`, then stop. The final + * result will be whether any of them returned `true`. + */ + static or(predicates: Array<() => PersistencePromise>): PersistencePromise; + /** + * Given an iterable, call the given function on each element in the + * collection and wait for all of the resulting concurrent PersistencePromises + * to resolve. + */ + static forEach(collection: { + forEach: (cb: (r: R, s: S) => void) => void; + }, f: ((r: R, s: S) => PersistencePromise) | ((r: R) => PersistencePromise)): PersistencePromise; + static forEach(collection: { + forEach: (cb: (r: R) => void) => void; + }, f: (r: R) => PersistencePromise): PersistencePromise; + /** + * Concurrently map all array elements through asynchronous function. + */ + static mapArray(array: T[], f: (t: T) => PersistencePromise): PersistencePromise; + /** + * An alternative to recursive PersistencePromise calls, that avoids + * potential memory problems from unbounded chains of promises. + * + * The `action` will be called repeatedly while `condition` is true. + */ + static doWhile(condition: () => boolean, action: () => PersistencePromise): PersistencePromise; +} + +/** + * Settings that can be passed to `enableIndexedDbPersistence()` to configure + * Firestore persistence. + * + * Persistence cannot be used in a Node.js environment. + */ +export declare interface PersistenceSettings { + /** + * Whether to force enable persistence for the client. This cannot be used + * with multi-tab synchronization and is primarily intended for use with Web + * Workers. Setting this to `true` will enable persistence, but cause other + * tabs using persistence to fail. + */ + forceOwnership?: boolean; +} + +/** + * A base class representing a persistence transaction, encapsulating both the + * transaction's sequence numbers as well as a list of onCommitted listeners. + * + * When you call Persistence.runTransaction(), it will create a transaction and + * pass it to your callback. You then pass it to any method that operates + * on persistence. + */ +declare abstract class PersistenceTransaction { + private readonly onCommittedListeners; + abstract readonly currentSequenceNumber: ListenSequenceNumber; + addOnCommittedListener(listener: () => void): void; + raiseOnCommittedEvent(): void; +} + +/** The different modes supported by `Persistence.runTransaction()`. */ +declare type PersistenceTransactionMode = 'readonly' | 'readwrite' | 'readwrite-primary'; + +/** + * A `PersistentCacheIndexManager` for configuring persistent cache indexes used + * for local query execution. + * + * To use, call `getPersistentCacheIndexManager()` to get an instance. + */ +export declare class PersistentCacheIndexManager { + readonly _firestore: Firestore; + /** A type string to uniquely identify instances of this class. */ + readonly type: 'PersistentCacheIndexManager'; + /** @hideconstructor */ + constructor(_firestore: Firestore); +} + +/** + * An settings object to configure an `PersistentLocalCache` instance. + * + * Persistent cache cannot be used in a Node.js environment. + */ +export declare type PersistentCacheSettings = { + /** + * An approximate cache size threshold for the on-disk data. If the cache + * grows beyond this size, Firestore will start removing data that hasn't been + * recently used. The SDK does not guarantee that the cache will stay below + * that size, only that if the cache exceeds the given size, cleanup will be + * attempted. + * + * The default value is 40 MB. The threshold must be set to at least 1 MB, and + * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection. + */ + cacheSizeBytes?: number; + /** + * Specifies how multiple tabs/windows will be managed by the SDK. + */ + tabManager?: PersistentTabManager; +}; + +/** + * Provides a persistent cache backed by IndexedDb to the SDK. + * + * To use, create an instance using the factory function {@link persistentLocalCache()}, then + * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using + * the settings object. + */ +export declare type PersistentLocalCache = { + kind: 'persistent'; + /* Excluded from this release type: _onlineComponentProvider */ + /* Excluded from this release type: _offlineComponentProvider */ +}; + +/** + * Creates an instance of `PersistentLocalCache`. The instance can be set to + * `FirestoreSettings.cache` to tell the SDK which cache layer to use. + * + * Persistent cache cannot be used in a Node.js environment. + */ +export declare function persistentLocalCache(settings?: PersistentCacheSettings): PersistentLocalCache; + +/** + * A tab manager supporting multiple tabs. SDK will synchronize queries and + * mutations done across all tabs using the SDK. + */ +export declare type PersistentMultipleTabManager = { + kind: 'PersistentMultipleTab'; + /* Excluded from this release type: _initialize */ + /* Excluded from this release type: _onlineComponentProvider */ + /* Excluded from this release type: _offlineComponentProvider */ +}; + +/** + * Creates an instance of `PersistentMultipleTabManager`. + */ +export declare function persistentMultipleTabManager(): PersistentMultipleTabManager; + +/** + * A tab manager supporting only one tab, no synchronization will be + * performed across tabs. + */ +export declare type PersistentSingleTabManager = { + kind: 'persistentSingleTab'; + /* Excluded from this release type: _initialize */ + /* Excluded from this release type: _onlineComponentProvider */ + /* Excluded from this release type: _offlineComponentProvider */ +}; + +/** + * Creates an instance of `PersistentSingleTabManager`. + * + * @param settings Configures the created tab manager. + */ +export declare function persistentSingleTabManager(settings: PersistentSingleTabManagerSettings | undefined): PersistentSingleTabManager; + +/** + * Type to configure an `PersistentSingleTabManager` instance. + */ +export declare type PersistentSingleTabManagerSettings = { + /** + * Whether to force-enable persistent (IndexedDB) cache for the client. This + * cannot be used with multi-tab synchronization and is primarily intended for + * use with Web Workers. Setting this to `true` will enable IndexedDB, but cause + * other tabs using IndexedDB cache to fail. + */ + forceOwnership?: boolean; +}; + +/** + * A union of all available tab managers. + */ +export declare type PersistentTabManager = PersistentSingleTabManager | PersistentMultipleTabManager; + +/** + * Encodes a precondition for a mutation. This follows the model that the + * backend accepts with the special case of an explicit "empty" precondition + * (meaning no precondition). + */ +declare class Precondition { + readonly updateTime?: SnapshotVersion | undefined; + readonly exists?: boolean | undefined; + private constructor(); + /** Creates a new empty Precondition. */ + static none(): Precondition; + /** Creates a new Precondition with an exists flag. */ + static exists(exists: boolean): Precondition; + /** Creates a new Precondition based on a version a document exists at. */ + static updateTime(version: SnapshotVersion): Precondition; + /** Returns whether this Precondition is empty. */ + get isNone(): boolean; + isEqual(other: Precondition): boolean; +} + +/** + * These types primarily exist to support the `UpdateData`, + * `WithFieldValue`, and `PartialWithFieldValue` types and are not consumed + * directly by the end developer. + */ +/** Primitive types. */ +export declare type Primitive = string | number | boolean | undefined | null; + +/* Excluded from this release type: PrivateSettings */ + +/* Excluded from this release type: Property */ + +declare interface ProviderCredentialsSettings { + ['type']: 'provider'; + ['client']: CredentialsProvider; +} + +/** + * A `Query` refers to a query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ +export declare class Query { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter_2 | null; + readonly _query: Query_2; + /** The type of this Firestore reference. */ + readonly type: 'query' | 'collection'; + /** + * The `Firestore` instance for the Firestore database (useful for performing + * transactions, etc.). + */ + readonly firestore: Firestore_2; + /** @hideconstructor protected */ + constructor(firestore: Firestore_2, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter: FirestoreDataConverter_2 | null, _query: Query_2); + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `Query` that does not use a + * converter. + */ + withConverter(converter: null): Query; + /** + * Applies a custom data converter to this query, allowing you to use your own + * custom model objects with Firestore. When you call {@link getDocs} with + * the returned query, the provided converter will convert between Firestore + * data of type `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `Query` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter_2): Query; +} + +/** + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. + * + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to + * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or + * {@link or}. + * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to + * apply (e.g. {@link orderBy}, {@link limit}). + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query(query: Query, compositeFilter: QueryCompositeFilterConstraint, ...queryConstraints: QueryNonFilterConstraint[]): Query; + +/** + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. + * + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param queryConstraints - The list of {@link QueryConstraint}s to apply. + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query(query: Query, ...queryConstraints: QueryConstraint[]): Query; + +/** + * The Query interface defines all external properties of a query. + * + * QueryImpl implements this interface to provide memoization for `queryNormalizedOrderBy` + * and `queryToTarget`. + */ +declare interface Query_2 { + readonly path: _ResourcePath; + readonly collectionGroup: string | null; + readonly explicitOrderBy: OrderBy[]; + readonly filters: Filter[]; + readonly limit: number | null; + readonly limitType: LimitType; + readonly startAt: Bound | null; + readonly endAt: Bound | null; +} + +/** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ +export declare class QueryCompositeFilterConstraint extends AppliableConstraint { + /** The type of this query constraint */ + readonly type: 'or' | 'and'; + private readonly _queryConstraints; + /* Excluded from this release type: __constructor */ + static _create(type: 'or' | 'and', _queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; + _parse(query: Query): Filter; + _apply(query: Query): Query; + _getQueryConstraints(): readonly AppliableConstraint[]; + _getOperator(): CompositeOperator; +} + +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Firestore query. `QueryConstraint`s are created by invoking {@link where}, + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that + * also contains this `QueryConstraint`. + */ +export declare abstract class QueryConstraint extends AppliableConstraint { + /** The type of this query constraint */ + abstract readonly type: QueryConstraintType; + /** + * Takes the provided {@link Query} and returns a copy of the {@link Query} with this + * {@link AppliableConstraint} applied. + */ + abstract _apply(query: Query): Query; +} + +/** Describes the different query constraints available in this SDK. */ +export declare type QueryConstraintType = 'where' | 'orderBy' | 'limit' | 'limitToLast' | 'startAt' | 'startAfter' | 'endAt' | 'endBefore'; + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A tracker to keep a record of important details during database local query + * execution. + */ +declare class QueryContext { + /** + * Counts the number of documents passed through during local query execution. + */ + private _documentReadCount; + get documentReadCount(): number; + incrementDocumentReadCount(amount: number): void; +} + +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ +export declare class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * By default, `serverTimestamp()` values that have not yet been + * set to their final value will be returned as `null`. You can override + * this by passing an options object. + * + * @override + * @param options - An options object to configure how data is retrieved from + * the snapshot (for example the desired behavior for server timestamps that + * have not yet been set to their final value). + * @returns An `Object` containing all fields in the document. + */ + data(options?: SnapshotOptions): AppModelType; +} + +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ +declare class QueryDocumentSnapshot_2 extends DocumentSnapshot_2 { + /** + * Retrieves all fields in the document as an `Object`. + * + * @override + * @returns An `Object` containing all fields in the document. + */ + data(): AppModelType; +} + +/** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ +export declare class QueryEndAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'endBefore' | 'endAt'; + private readonly _docOrFields; + private readonly _inclusive; + /* Excluded from this release type: __constructor */ + static _create(type: 'endBefore' | 'endAt', _docOrFields: Array>, _inclusive: boolean): QueryEndAtConstraint; + _apply(query: Query): Query; +} + +/** + * Returns true if the provided queries point to the same collection and apply + * the same constraints. + * + * @param left - A `Query` to compare. + * @param right - A `Query` to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +export declare function queryEqual(left: Query, right: Query): boolean; + +/** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ +export declare class QueryFieldFilterConstraint extends QueryConstraint { + private readonly _field; + private _op; + private _value; + /** The type of this query constraint */ + readonly type = "where"; + /* Excluded from this release type: __constructor */ + static _create(_field: _FieldPath, _op: Operator, _value: unknown): QueryFieldFilterConstraint; + _apply(query: Query): Query; + _parse(query: Query): FieldFilter; +} + +/** + * `QueryFilterConstraint` is a helper union type that represents + * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}. + */ +export declare type QueryFilterConstraint = QueryFieldFilterConstraint | QueryCompositeFilterConstraint; + +/** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ +export declare class QueryLimitConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'limit' | 'limitToLast'; + private readonly _limit; + private readonly _limitType; + /* Excluded from this release type: __constructor */ + static _create(type: 'limit' | 'limitToLast', _limit: number, _limitType: LimitType): QueryLimitConstraint; + _apply(query: Query): Query; +} + +/** + * `QueryNonFilterConstraint` is a helper union type that represents + * QueryConstraints which are used to narrow or order the set of documents, + * but that do not explicitly filter on a document field. + * `QueryNonFilterConstraint`s are created by invoking {@link orderBy}, + * {@link (startAt:1)}, {@link (startAfter:1)}, {@link (endBefore:1)}, {@link (endAt:1)}, + * {@link limit} or {@link limitToLast} and can then be passed to {@link (query:1)} + * to create a new query instance that also contains the `QueryConstraint`. + */ +export declare type QueryNonFilterConstraint = QueryOrderByConstraint | QueryLimitConstraint | QueryStartAtConstraint | QueryEndAtConstraint; + +/** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ +export declare class QueryOrderByConstraint extends QueryConstraint { + private readonly _field; + private _direction; + /** The type of this query constraint */ + readonly type = "orderBy"; + /* Excluded from this release type: __constructor */ + static _create(_field: _FieldPath, _direction: Direction): QueryOrderByConstraint; + _apply(query: Query): Query; +} + +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ +export declare class QuerySnapshot { + readonly _firestore: Firestore; + readonly _userDataWriter: AbstractUserDataWriter; + readonly _snapshot: ViewSnapshot; + /** + * Metadata about this snapshot, concerning its source and if it has local + * modifications. + */ + readonly metadata: SnapshotMetadata; + /** + * The query on which you called `get` or `onSnapshot` in order to get this + * `QuerySnapshot`. + */ + readonly query: Query; + private _cachedChanges?; + private _cachedChangesIncludeMetadataChanges?; + /** @hideconstructor */ + constructor(_firestore: Firestore, _userDataWriter: AbstractUserDataWriter, query: Query, _snapshot: ViewSnapshot); + /** An array of all the documents in the `QuerySnapshot`. */ + get docs(): Array>; + /** The number of documents in the `QuerySnapshot`. */ + get size(): number; + /** True if there are no documents in the `QuerySnapshot`. */ + get empty(): boolean; + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ + forEach(callback: (result: QueryDocumentSnapshot) => void, thisArg?: unknown): void; + /** + * Returns an array of the documents changes since the last snapshot. If this + * is the first snapshot, all documents will be in the list as 'added' + * changes. + * + * @param options - `SnapshotListenOptions` that control whether metadata-only + * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger + * snapshot events. + */ + docChanges(options?: SnapshotListenOptions): Array>; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + bundleSource: Property<"string">; + bundleName: Property<"string">; + bundle: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `QuerySnapshot` instance. + * + * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this + * `QuerySnapshot` has pending writes. + */ + toJSON(): object; +} + +/** + * Builds a `QuerySnapshot` instance from a JSON object created by + * {@link QuerySnapshot.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json - a JSON object represention of a `QuerySnapshot` instance. + * @returns an instance of {@link QuerySnapshot} if the JSON object could be + * parsed. Throws a {@link FirestoreError} if an error occurs. + */ +export declare function querySnapshotFromJSON(db: Firestore, json: object): QuerySnapshot; + +/** + * Builds a `QuerySnapshot` instance from a JSON object created by + * {@link QuerySnapshot.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json - a JSON object represention of a `QuerySnapshot` instance. + * @param converter - Converts objects to and from Firestore. + * @returns an instance of {@link QuerySnapshot} if the JSON object could be + * parsed. Throws a {@link FirestoreError} if an error occurs. + */ +export declare function querySnapshotFromJSON(db: Firestore, json: object, converter: FirestoreDataConverter): QuerySnapshot; + +/** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ +export declare class QueryStartAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'startAt' | 'startAfter'; + private readonly _docOrFields; + private readonly _inclusive; + /* Excluded from this release type: __constructor */ + static _create(type: 'startAt' | 'startAfter', _docOrFields: Array>, _inclusive: boolean): QueryStartAtConstraint; + _apply(query: Query): Query; +} + +/** The different states of a watch target. */ +declare type QueryTargetState = 'not-current' | 'current' | 'rejected'; + +/** + * Returns true if the provided references are equal. + * + * @param left - A reference to compare. + * @param right - A reference to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +export declare function refEqual(left: DocumentReference | CollectionReference, right: DocumentReference | CollectionReference): boolean; + +/** + * A ReferenceDelegate instance handles all of the hooks into the document-reference lifecycle. This + * includes being added to a target, being removed from a target, being subject to mutation, and + * being mutated by the user. + * + * Different implementations may do different things with each of these events. Not every + * implementation needs to do something with every lifecycle hook. + * + * PORTING NOTE: since sequence numbers are attached to transactions in this + * client, the ReferenceDelegate does not need to deal in transactional + * semantics (onTransactionStarted/Committed()), nor does it need to track and + * generate sequence numbers (getCurrentSequenceNumber()). + */ +declare interface ReferenceDelegate { + /** Notify the delegate that the given document was added to a target. */ + addReference(txn: PersistenceTransaction, targetId: TargetId, doc: _DocumentKey): PersistencePromise; + /** Notify the delegate that the given document was removed from a target. */ + removeReference(txn: PersistenceTransaction, targetId: TargetId, doc: _DocumentKey): PersistencePromise; + /** + * Notify the delegate that a target was removed. The delegate may, but is not obligated to, + * actually delete the target and associated data. + */ + removeTarget(txn: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Notify the delegate that a document may no longer be part of any views or + * have any mutations associated. + */ + markPotentiallyOrphaned(txn: PersistenceTransaction, doc: _DocumentKey): PersistencePromise; + /** Notify the delegate that a limbo document was updated. */ + updateLimboDocument(txn: PersistenceTransaction, doc: _DocumentKey): PersistencePromise; +} + +declare type RejectedHandler = ((reason: Error) => R | PersistencePromise) | null; + +declare type Rejector = (error: Error) => void; + +/** + * Represents cached documents received from the remote backend. + * + * The cache is keyed by DocumentKey and entries in the cache are + * MutableDocuments, meaning we can cache both actual documents as well as + * documents that are known to not exist. + */ +declare interface RemoteDocumentCache { + /** Sets the index manager to use for managing the collectionGroup index. */ + setIndexManager(indexManager: IndexManager): void; + /** + * Looks up an entry in the cache. + * + * @param documentKey - The key of the entry to look up.* + * @returns The cached document entry. Returns an invalid document if the + * document is not cached. + */ + getEntry(transaction: PersistenceTransaction, documentKey: _DocumentKey): PersistencePromise; + /** + * Looks up a set of entries in the cache. + * + * @param documentKeys - The keys of the entries to look up. + * @returns The cached document entries indexed by key. If an entry is not + * cached, the corresponding key will be mapped to an invalid document. + */ + getEntries(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise; + /** + * Returns the documents matching the given query + * + * @param query - The query to match documents against. + * @param offset - The offset to start the scan at (exclusive). + * @param context - A optional tracker to keep a record of important details + * during database local query execution. + * @returns The set of matching documents. + */ + getDocumentsMatchingQuery(transaction: PersistenceTransaction, query: Query_2, offset: IndexOffset, mutatedDocs: OverlayMap, context?: QueryContext): PersistencePromise; + /** + * Looks up the next `limit` documents for a collection group based on the + * provided offset. The ordering is based on the document's read time and key. + * + * @param collectionGroup - The collection group to scan. + * @param offset - The offset to start the scan at (exclusive). + * @param limit - The maximum number of results to return. + * @returns The set of matching documents. + */ + getAllFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset, limit: number): PersistencePromise; + /** + * Provides access to add or update the contents of the cache. The buffer + * handles proper size accounting for the change. + * + * Multi-Tab Note: This should only be called by the primary client. + * + * @param options - Specify `trackRemovals` to create sentinel entries for + * removed documents, which allows removals to be tracked by + * `getNewDocumentChanges()`. + */ + newChangeBuffer(options?: { + trackRemovals: boolean; + }): RemoteDocumentChangeBuffer; + /** + * Get an estimate of the size of the document cache. Note that for eager + * garbage collection, we don't track sizes so this will return 0. + */ + getSize(transaction: PersistenceTransaction): PersistencePromise; +} + +/** + * An in-memory buffer of entries to be written to a RemoteDocumentCache. + * It can be used to batch up a set of changes to be written to the cache, but + * additionally supports reading entries back with the `getEntry()` method, + * falling back to the underlying RemoteDocumentCache if no entry is + * buffered. + * + * Entries added to the cache *must* be read first. This is to facilitate + * calculating the size delta of the pending changes. + * + * PORTING NOTE: This class was implemented then removed from other platforms. + * If byte-counting ends up being needed on the other platforms, consider + * porting this class as part of that implementation work. + */ +declare abstract class RemoteDocumentChangeBuffer { + protected changes: ObjectMap<_DocumentKey, MutableDocument>; + private changesApplied; + protected abstract getFromCache(transaction: PersistenceTransaction, documentKey: _DocumentKey): PersistencePromise; + protected abstract getAllFromCache(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise; + protected abstract applyChanges(transaction: PersistenceTransaction): PersistencePromise; + /** + * Buffers a `RemoteDocumentCache.addEntry()` call. + * + * You can only modify documents that have already been retrieved via + * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). + */ + addEntry(document: MutableDocument): void; + /** + * Buffers a `RemoteDocumentCache.removeEntry()` call. + * + * You can only remove documents that have already been retrieved via + * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). + */ + removeEntry(key: _DocumentKey, readTime: SnapshotVersion): void; + /** + * Looks up an entry in the cache. The buffered changes will first be checked, + * and if no buffered change applies, this will forward to + * `RemoteDocumentCache.getEntry()`. + * + * @param transaction - The transaction in which to perform any persistence + * operations. + * @param documentKey - The key of the entry to look up. + * @returns The cached document or an invalid document if we have nothing + * cached. + */ + getEntry(transaction: PersistenceTransaction, documentKey: _DocumentKey): PersistencePromise; + /** + * Looks up several entries in the cache, forwarding to + * `RemoteDocumentCache.getEntry()`. + * + * @param transaction - The transaction in which to perform any persistence + * operations. + * @param documentKeys - The keys of the entries to look up. + * @returns A map of cached documents, indexed by key. If an entry cannot be + * found, the corresponding key will be mapped to an invalid document. + */ + getEntries(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise; + /** + * Applies buffered changes to the underlying RemoteDocumentCache, using + * the provided transaction. + */ + apply(transaction: PersistenceTransaction): PersistencePromise; + /** Helper to assert this.changes is not null */ + protected assertNotApplied(): void; +} + +/** + * An event from the RemoteStore. It is split into targetChanges (changes to the + * state or the set of documents in our watched targets) and documentUpdates + * (changes to the actual documents). + */ +declare class RemoteEvent { + /** + * The snapshot version this event brings us up to, or MIN if not set. + */ + readonly snapshotVersion: SnapshotVersion; + /** + * A map from target to changes to the target. See TargetChange. + */ + readonly targetChanges: Map; + /** + * A map of targets that is known to be inconsistent, and the purpose for + * re-listening. Listens for these targets should be re-established without + * resume tokens. + */ + readonly targetMismatches: SortedMap; + /** + * A set of which documents have changed or been deleted, along with the + * doc's new values (if not deleted). + */ + readonly documentUpdates: MutableDocumentMap; + /** + * A set of which document updates are due only to limbo resolution targets. + */ + readonly resolvedLimboDocuments: DocumentKeySet; + constructor( + /** + * The snapshot version this event brings us up to, or MIN if not set. + */ + snapshotVersion: SnapshotVersion, + /** + * A map from target to changes to the target. See TargetChange. + */ + targetChanges: Map, + /** + * A map of targets that is known to be inconsistent, and the purpose for + * re-listening. Listens for these targets should be re-established without + * resume tokens. + */ + targetMismatches: SortedMap, + /** + * A set of which documents have changed or been deleted, along with the + * doc's new values (if not deleted). + */ + documentUpdates: MutableDocumentMap, + /** + * A set of which document updates are due only to limbo resolution targets. + */ + resolvedLimboDocuments: DocumentKeySet); + /** + * HACK: Views require RemoteEvents in order to determine whether the view is + * CURRENT, but secondary tabs don't receive remote events. So this method is + * used to create a synthesized RemoteEvent that can be used to apply a + * CURRENT status change to a View, for queries executed in a different tab. + */ + static createSynthesizedRemoteEventForCurrentChange(targetId: TargetId, current: boolean, resumeToken: _ByteString): RemoteEvent; +} + +/** + * RemoteStore - An interface to remotely stored data, basically providing a + * wrapper around the Datastore that is more reliable for the rest of the + * system. + * + * RemoteStore is responsible for maintaining the connection to the server. + * - maintaining a list of active listens. + * - reconnecting when the connection is dropped. + * - resuming all the active listens on reconnect. + * + * RemoteStore handles all incoming events from the Datastore. + * - listening to the watch stream and repackaging the events as RemoteEvents + * - notifying SyncEngine of any changes to the active listens. + * + * RemoteStore takes writes from other components and handles them reliably. + * - pulling pending mutations from LocalStore and sending them to Datastore. + * - retrying mutations that failed because of network problems. + * - acking mutations to the SyncEngine once they are accepted or rejected. + */ +declare interface RemoteStore { + /** + * SyncEngine to notify of watch and write events. This must be set + * immediately after construction. + */ + remoteSyncer: RemoteSyncer; +} + +/** + * An interface that describes the actions the RemoteStore needs to perform on + * a cooperating synchronization engine. + */ +declare interface RemoteSyncer { + /** + * Applies one remote event to the sync engine, notifying any views of the + * changes, and releasing any pending mutation batches that would become + * visible because of the snapshot version the remote event contains. + */ + applyRemoteEvent?(remoteEvent: RemoteEvent): Promise; + /** + * Rejects the listen for the given targetID. This can be triggered by the + * backend for any active target. + * + * @param targetId - The targetID corresponds to one previously initiated by + * the user as part of TargetData passed to listen() on RemoteStore. + * @param error - A description of the condition that has forced the rejection. + * Nearly always this will be an indication that the user is no longer + * authorized to see the data matching the target. + */ + rejectListen?(targetId: TargetId, error: FirestoreError): Promise; + /** + * Applies the result of a successful write of a mutation batch to the sync + * engine, emitting snapshots in any views that the mutation applies to, and + * removing the batch from the mutation queue. + */ + applySuccessfulWrite?(result: MutationBatchResult): Promise; + /** + * Rejects the batch, removing the batch from the mutation queue, recomputing + * the local view of any documents affected by the batch and then, emitting + * snapshots with the reverted value. + */ + rejectFailedWrite?(batchId: BatchId, error: FirestoreError): Promise; + /** + * Returns the set of remote document keys for the given target ID. This list + * includes the documents that were assigned to the target when we received + * the last snapshot. + */ + getRemoteKeysForTarget?(targetId: TargetId): DocumentKeySet; + /** + * Updates all local state to match the pending mutations for the given user. + * May be called repeatedly for the same user. + */ + handleCredentialChange?(user: User): Promise; +} + +declare type Resolver = (value?: T) => void; + +/* Excluded from this release type: _ResourcePath */ + +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ +export declare function runTransaction(firestore: Firestore, updateFunction: (transaction: Transaction) => Promise, options?: TransactionOptions): Promise; + +/** + * Interface to schedule periodic tasks within SDK. + */ +declare interface Scheduler { + readonly started: boolean; + start(): void; + stop(): void; +} + +/** Base interface for the Serializer implementation. */ +declare interface Serializer { + readonly useProto3Json: boolean; +} + +/** + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to + * include a server-generated timestamp in the written data. + */ +export declare function serverTimestamp(): FieldValue; + +declare type ServerTimestampBehavior = 'estimate' | 'previous' | 'none'; + +/** + * Writes to the document referred to by this `DocumentReference`. If the + * document does not yet exist, it will be created. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +export declare function setDoc(reference: DocumentReference, data: WithFieldValue): Promise; + +/** + * Writes to the document referred to by the specified `DocumentReference`. If + * the document does not yet exist, it will be created. If you provide `merge` + * or `mergeFields`, the provided data can be merged into an existing document. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @returns A Promise resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +export declare function setDoc(reference: DocumentReference, data: PartialWithFieldValue, options: SetOptions): Promise; + +/** + * Configures indexing for local query execution. Any previous index + * configuration is overridden. The `Promise` resolves once the index + * configuration has been persisted. + * + * The index entries themselves are created asynchronously. You can continue to + * use queries that require indexing even if the indices are not yet available. + * Query execution will automatically start using the index once the index + * entries have been written. + * + * Indexes are only supported with IndexedDb persistence. If IndexedDb is not + * enabled, any index configuration is ignored. + * + * @param firestore - The {@link Firestore} instance to configure indexes for. + * @param configuration -The index definition. + * @throws FirestoreError if the JSON format is invalid. + * @returns A `Promise` that resolves once all indices are successfully + * configured. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare function setIndexConfiguration(firestore: Firestore, configuration: IndexConfiguration): Promise; + +/** + * Configures indexing for local query execution. Any previous index + * configuration is overridden. The `Promise` resolves once the index + * configuration has been persisted. + * + * The index entries themselves are created asynchronously. You can continue to + * use queries that require indexing even if the indices are not yet available. + * Query execution will automatically start using the index once the index + * entries have been written. + * + * Indexes are only supported with IndexedDb persistence. Invoke either + * `enableIndexedDbPersistence()` or `enableMultiTabIndexedDbPersistence()` + * before setting an index configuration. If IndexedDb is not enabled, any + * index configuration is ignored. + * + * The method accepts the JSON format exported by the Firebase CLI (`firebase + * firestore:indexes`). If the JSON format is invalid, this method throws an + * error. + * + * @param firestore - The {@link Firestore} instance to configure indexes for. + * @param json -The JSON format exported by the Firebase CLI. + * @throws FirestoreError if the JSON format is invalid. + * @returns A `Promise` that resolves once all indices are successfully + * configured. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare function setIndexConfiguration(firestore: Firestore, json: string): Promise; + +/** + * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). + * + * @param logLevel - The verbosity you set for activity and error logging. Can + * be any of the following values: + * + *

    + *
  • `debug` for the most verbose logging level, primarily for + * debugging.
  • + *
  • `error` to log errors only.
  • + *
  • `silent` to turn off logging.
  • + *
+ */ +export declare function setLogLevel(logLevel: LogLevel): void; + +/** + * An options object that configures the behavior of {@link @firebase/firestore/lite#(setDoc:1)}, {@link + * @firebase/firestore/lite#(WriteBatch.set:1)} and {@link @firebase/firestore/lite#(Transaction.set:1)} calls. These calls can be + * configured to perform granular merges instead of overwriting the target + * documents in their entirety by providing a `SetOptions` with `merge: true`. + * + * @param merge - Changes the behavior of a `setDoc()` call to only replace the + * values specified in its data argument. Fields omitted from the `setDoc()` + * call remain untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + * @param mergeFields - Changes the behavior of `setDoc()` calls to only replace + * the specified field paths. Any field path that is not specified is ignored + * and remains untouched. If your input sets any field to an empty map, all + * nested fields are overwritten. + */ +export declare type SetOptions = { + readonly merge?: boolean; +} | { + readonly mergeFields?: Array; +}; + +/** + * A `SharedClientState` keeps track of the global state of the mutations + * and query targets for all active clients with the same persistence key (i.e. + * project ID and FirebaseApp name). It relays local changes to other clients + * and updates its local state as new state is observed. + * + * `SharedClientState` is primarily used for synchronization in Multi-Tab + * environments. Each tab is responsible for registering its active query + * targets and mutations. `SharedClientState` will then notify the listener + * assigned to `.syncEngine` for updates to mutations and queries that + * originated in other clients. + * + * To receive notifications, `.syncEngine` and `.onlineStateHandler` has to be + * assigned before calling `start()`. + */ +declare interface SharedClientState { + onlineStateHandler: ((onlineState: OnlineState) => void) | null; + sequenceNumberHandler: ((sequenceNumber: ListenSequenceNumber) => void) | null; + /** Registers the Mutation Batch ID of a newly pending mutation. */ + addPendingMutation(batchId: BatchId): void; + /** + * Records that a pending mutation has been acknowledged or rejected. + * Called by the primary client to notify secondary clients of mutation + * results as they come back from the backend. + */ + updateMutationState(batchId: BatchId, state: 'acknowledged' | 'rejected', error?: FirestoreError): void; + /** + * Associates a new Query Target ID with the local Firestore client. Returns + * the new query state for the query (which can be 'current' if the query is + * already associated with another tab). + * + * If the target id is already associated with local client, the method simply + * returns its `QueryTargetState`. + */ + addLocalQueryTarget(targetId: TargetId, addToActiveTargetIds?: boolean): QueryTargetState; + /** Removes the Query Target ID association from the local client. */ + removeLocalQueryTarget(targetId: TargetId): void; + /** Checks whether the target is associated with the local client. */ + isLocalQueryTarget(targetId: TargetId): boolean; + /** + * Processes an update to a query target. + * + * Called by the primary client to notify secondary clients of document + * changes or state transitions that affect the provided query target. + */ + updateQueryState(targetId: TargetId, state: QueryTargetState, error?: FirestoreError): void; + /** + * Removes the target's metadata entry. + * + * Called by the primary client when all clients stopped listening to a query + * target. + */ + clearQueryState(targetId: TargetId): void; + /** + * Gets the active Query Targets IDs for all active clients. + * + * The implementation for this may require O(n) runtime, where 'n' is the size + * of the result set. + */ + getAllActiveQueryTargets(): SortedSet; + /** + * Checks whether the provided target ID is currently being listened to by + * any of the active clients. + * + * The implementation may require O(n*log m) runtime, where 'n' is the number + * of clients and 'm' the number of targets. + */ + isActiveQueryTarget(targetId: TargetId): boolean; + /** + * Starts the SharedClientState, reads existing client data and registers + * listeners for updates to new and existing clients. + */ + start(): Promise; + /** Shuts down the `SharedClientState` and its listeners. */ + shutdown(): void; + /** + * Changes the active user and removes all existing user-specific data. The + * user change does not call back into SyncEngine (for example, no mutations + * will be marked as removed). + */ + handleUserChange(user: User, removedBatchIds: BatchId[], addedBatchIds: BatchId[]): void; + /** Changes the shared online state of all clients. */ + setOnlineState(onlineState: OnlineState): void; + writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void; + /** + * Notifies other clients when remote documents have changed due to loading + * a bundle. + * + * @param collectionGroups The collection groups affected by this bundle. + */ + notifyBundleLoaded(collectionGroups: Set): void; +} + +/** + * Returns true if the provided snapshots are equal. + * + * @param left - A snapshot to compare. + * @param right - A snapshot to compare. + * @returns true if the snapshots are equal. + */ +export declare function snapshotEqual(left: DocumentSnapshot | QuerySnapshot, right: DocumentSnapshot | QuerySnapshot): boolean; + +/** + * An options object that can be passed to {@link (onSnapshot:1)} and {@link + * QuerySnapshot.docChanges} to control which types of changes to include in the + * result set. + */ +export declare interface SnapshotListenOptions { + /** + * Include a change even if only the metadata of the query or of a document + * changed. Default is false. + */ + readonly includeMetadataChanges?: boolean; + /** + * Set the source the query listens to. Default to "default", which + * listens to both cache and server. + */ + readonly source?: ListenSource; +} + +/** + * Metadata about a snapshot, describing the state of the snapshot. + */ +export declare class SnapshotMetadata { + /** + * True if the snapshot contains the result of local writes (for example + * `set()` or `update()` calls) that have not yet been committed to the + * backend. If your listener has opted into metadata updates (via + * `SnapshotListenOptions`) you will receive another snapshot with + * `hasPendingWrites` equal to false once the writes have been committed to + * the backend. + */ + readonly hasPendingWrites: boolean; + /** + * True if the snapshot was created from cached data rather than guaranteed + * up-to-date server data. If your listener has opted into metadata updates + * (via `SnapshotListenOptions`) you will receive another snapshot with + * `fromCache` set to false once the client has received up-to-date data from + * the backend. + */ + readonly fromCache: boolean; + /** @hideconstructor */ + constructor(hasPendingWrites: boolean, fromCache: boolean); + /** + * Returns true if this `SnapshotMetadata` is equal to the provided one. + * + * @param other - The `SnapshotMetadata` to compare against. + * @returns true if this `SnapshotMetadata` is equal to the provided one. + */ + isEqual(other: SnapshotMetadata): boolean; +} + +/** + * Options that configure how data is retrieved from a `DocumentSnapshot` (for + * example the desired behavior for server timestamps that have not yet been set + * to their final value). + */ +export declare interface SnapshotOptions { + /** + * If set, controls the return value for server timestamps that have not yet + * been set to their final value. + * + * By specifying 'estimate', pending server timestamps return an estimate + * based on the local clock. This estimate will differ from the final value + * and cause these values to change once the server result becomes available. + * + * By specifying 'previous', pending timestamps will be ignored and return + * their previous value instead. + * + * If omitted or set to 'none', `null` will be returned by default until the + * server value becomes available. + */ + readonly serverTimestamps?: 'estimate' | 'previous' | 'none'; +} + +/** + * A version of a document in Firestore. This corresponds to the version + * timestamp, such as update_time or read_time. + */ +declare class SnapshotVersion { + private timestamp; + static fromTimestamp(value: Timestamp): SnapshotVersion; + static min(): SnapshotVersion; + static max(): SnapshotVersion; + private constructor(); + compareTo(other: SnapshotVersion): number; + isEqual(other: SnapshotVersion): boolean; + /** Returns a number representation of the version for use in spec tests. */ + toMicroseconds(): number; + toString(): string; + toTimestamp(): Timestamp; +} + +declare class SortedMap { + comparator: Comparator; + root: LLRBNode | LLRBEmptyNode; + constructor(comparator: Comparator, root?: LLRBNode | LLRBEmptyNode); + insert(key: K, value: V): SortedMap; + remove(key: K): SortedMap; + get(key: K): V | null; + indexOf(key: K): number; + isEmpty(): boolean; + get size(): number; + minKey(): K | null; + maxKey(): K | null; + inorderTraversal(action: (k: K, v: V) => T): T; + forEach(fn: (k: K, v: V) => void): void; + toString(): string; + reverseTraversal(action: (k: K, v: V) => T): T; + getIterator(): SortedMapIterator; + getIteratorFrom(key: K): SortedMapIterator; + getReverseIterator(): SortedMapIterator; + getReverseIteratorFrom(key: K): SortedMapIterator; +} + +declare class SortedMapIterator { + private isReverse; + private nodeStack; + constructor(node: LLRBNode | LLRBEmptyNode, startKey: K | null, comparator: Comparator, isReverse: boolean); + getNext(): Entry; + hasNext(): boolean; + peek(): Entry | null; +} + +/** + * SortedSet is an immutable (copy-on-write) collection that holds elements + * in order specified by the provided comparator. + * + * NOTE: if provided comparator returns 0 for two elements, we consider them to + * be equal! + */ +declare class SortedSet { + private comparator; + private data; + constructor(comparator: (left: T, right: T) => number); + has(elem: T): boolean; + first(): T | null; + last(): T | null; + get size(): number; + indexOf(elem: T): number; + /** Iterates elements in order defined by "comparator" */ + forEach(cb: (elem: T) => void): void; + /** Iterates over `elem`s such that: range[0] <= elem < range[1]. */ + forEachInRange(range: [T, T], cb: (elem: T) => void): void; + /** + * Iterates over `elem`s such that: start <= elem until false is returned. + */ + forEachWhile(cb: (elem: T) => boolean, start?: T): void; + /** Finds the least element greater than or equal to `elem`. */ + firstAfterOrEqual(elem: T): T | null; + getIterator(): SortedSetIterator; + getIteratorFrom(key: T): SortedSetIterator; + /** Inserts or updates an element */ + add(elem: T): SortedSet; + /** Deletes an element */ + delete(elem: T): SortedSet; + isEmpty(): boolean; + unionWith(other: SortedSet): SortedSet; + isEqual(other: SortedSet): boolean; + toArray(): T[]; + toString(): string; + private copy; +} + +declare class SortedSetIterator { + private iter; + constructor(iter: SortedMapIterator); + getNext(): T; + hasNext(): boolean; +} + +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided document (exclusive). The starting position is + * relative to the order of the query. The document must contain all of the + * fields provided in the orderBy of the query. + * + * @param snapshot - The snapshot of the document to start after. + * @returns A {@link QueryStartAtConstraint} to pass to `query()` + */ +export declare function startAfter(snapshot: DocumentSnapshot_2): QueryStartAtConstraint; + +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start after the provided fields relative to the order of the query. The order + * of the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to start this query after, in order + * of the query's order by. + * @returns A {@link QueryStartAtConstraint} to pass to `query()` + */ +export declare function startAfter(...fieldValues: unknown[]): QueryStartAtConstraint; + +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided document (inclusive). The starting position is relative + * to the order of the query. The document must contain all of the fields + * provided in the `orderBy` of this query. + * + * @param snapshot - The snapshot of the document to start at. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. + */ +export declare function startAt(snapshot: DocumentSnapshot_2): QueryStartAtConstraint; + +/** + * Creates a {@link QueryStartAtConstraint} that modifies the result set to + * start at the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to start this query at, in order + * of the query's order by. + * @returns A {@link QueryStartAtConstraint} to pass to `query()`. + */ +export declare function startAt(...fieldValues: unknown[]): QueryStartAtConstraint; + +declare type StructuredQuery = firestoreV1ApiClientInterfaces.StructuredQuery; + +/** + * Create an AggregateField object that can be used to compute the sum of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to sum across the result set. + */ +export declare function sum(field: string | FieldPath): AggregateField; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * SyncEngine is the central controller in the client SDK architecture. It is + * the glue code between the EventManager, LocalStore, and RemoteStore. Some of + * SyncEngine's responsibilities include: + * 1. Coordinating client requests and remote events between the EventManager + * and the local and remote data stores. + * 2. Managing a View object for each query, providing the unified view between + * the local and remote data stores. + * 3. Notifying the RemoteStore when the LocalStore has new mutations in its + * queue that need sending to the backend. + * + * The SyncEngine’s methods should only ever be called by methods running in the + * global async queue. + * + * PORTING NOTE: On Web, SyncEngine does not have an explicit subscribe() + * function. Instead, it directly depends on EventManager's tree-shakeable API + * (via `ensureWatchStream()`). + */ +declare interface SyncEngine { + isPrimaryClient: boolean; +} + +/** + * A Target represents the WatchTarget representation of a Query, which is used + * by the LocalStore and the RemoteStore to keep track of and to execute + * backend queries. While a Query can represent multiple Targets, each Targets + * maps to a single WatchTarget in RemoteStore and a single TargetData entry + * in persistence. + */ +declare interface Target { + readonly path: _ResourcePath; + readonly collectionGroup: string | null; + readonly orderBy: OrderBy[]; + readonly filters: Filter[]; + readonly limit: number | null; + readonly startAt: Bound | null; + readonly endAt: Bound | null; +} + +/** + * Represents cached targets received from the remote backend. + * + * The cache is keyed by `Target` and entries in the cache are `TargetData` + * instances. + */ +declare interface TargetCache { + /** + * A global snapshot version representing the last consistent snapshot we + * received from the backend. This is monotonically increasing and any + * snapshots received from the backend prior to this version (e.g. for targets + * resumed with a resume_token) should be suppressed (buffered) until the + * backend has caught up to this snapshot version again. This prevents our + * cache from ever going backwards in time. + * + * This is updated whenever our we get a TargetChange with a read_time and + * empty target_ids. + */ + getLastRemoteSnapshotVersion(transaction: PersistenceTransaction): PersistencePromise; + /** + * @returns The highest sequence number observed, including any that might be + * persisted on-disk. + */ + getHighestSequenceNumber(transaction: PersistenceTransaction): PersistencePromise; + /** + * Call provided function with each `TargetData` that we have cached. + */ + forEachTarget(txn: PersistenceTransaction, f: (q: TargetData) => void): PersistencePromise; + /** + * Set the highest listen sequence number and optionally updates the + * snapshot version of the last consistent snapshot received from the backend + * (see getLastRemoteSnapshotVersion() for more details). + * + * @param highestListenSequenceNumber - The new maximum listen sequence number. + * @param lastRemoteSnapshotVersion - The new snapshot version. Optional. + */ + setTargetsMetadata(transaction: PersistenceTransaction, highestListenSequenceNumber: number, lastRemoteSnapshotVersion?: SnapshotVersion): PersistencePromise; + /** + * Adds an entry in the cache. + * + * The cache key is extracted from `targetData.target`. The key must not already + * exist in the cache. + * + * @param targetData - A TargetData instance to put in the cache. + */ + addTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Updates an entry in the cache. + * + * The cache key is extracted from `targetData.target`. The entry must already + * exist in the cache, and it will be replaced. + * @param targetData - The TargetData to be replaced into the cache. + */ + updateTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Removes the cached entry for the given target data. It is an error to remove + * a target data that does not exist. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * The number of targets currently in the cache. + */ + getTargetCount(transaction: PersistenceTransaction): PersistencePromise; + /** + * Looks up a TargetData entry by target. + * + * @param target - The query target corresponding to the entry to look up. + * @returns The cached TargetData entry, or null if the cache has no entry for + * the target. + */ + getTargetData(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Adds the given document keys to cached query results of the given target + * ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + addMatchingKeys(transaction: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + /** + * Removes the given document keys from the cached query results of the + * given target ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMatchingKeys(transaction: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + /** + * Removes all the keys in the query results of the given target ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMatchingKeysForTargetId(transaction: PersistenceTransaction, targetId: TargetId): PersistencePromise; + /** + * Returns the document keys that match the provided target ID. + */ + getMatchingKeysForTargetId(transaction: PersistenceTransaction, targetId: TargetId): PersistencePromise; + /** + * Returns a new target ID that is higher than any query in the cache. If + * there are no queries in the cache, returns the first valid target ID. + * Allocated target IDs are persisted and `allocateTargetId()` will never + * return the same ID twice. + */ + allocateTargetId(transaction: PersistenceTransaction): PersistencePromise; + containsKey(transaction: PersistenceTransaction, key: _DocumentKey): PersistencePromise; +} + +/** + * A TargetChange specifies the set of changes for a specific target as part of + * a RemoteEvent. These changes track which documents are added, modified or + * removed, as well as the target's resume token and whether the target is + * marked CURRENT. + * The actual changes *to* documents are not part of the TargetChange since + * documents may be part of multiple targets. + */ +declare class TargetChange { + /** + * An opaque, server-assigned token that allows watching a query to be resumed + * after disconnecting without retransmitting all the data that matches the + * query. The resume token essentially identifies a point in time from which + * the server should resume sending results. + */ + readonly resumeToken: _ByteString; + /** + * The "current" (synced) status of this target. Note that "current" + * has special meaning in the RPC protocol that implies that a target is + * both up-to-date and consistent with the rest of the watch stream. + */ + readonly current: boolean; + /** + * The set of documents that were newly assigned to this target as part of + * this remote event. + */ + readonly addedDocuments: DocumentKeySet; + /** + * The set of documents that were already assigned to this target but received + * an update during this remote event. + */ + readonly modifiedDocuments: DocumentKeySet; + /** + * The set of documents that were removed from this target as part of this + * remote event. + */ + readonly removedDocuments: DocumentKeySet; + constructor( + /** + * An opaque, server-assigned token that allows watching a query to be resumed + * after disconnecting without retransmitting all the data that matches the + * query. The resume token essentially identifies a point in time from which + * the server should resume sending results. + */ + resumeToken: _ByteString, + /** + * The "current" (synced) status of this target. Note that "current" + * has special meaning in the RPC protocol that implies that a target is + * both up-to-date and consistent with the rest of the watch stream. + */ + current: boolean, + /** + * The set of documents that were newly assigned to this target as part of + * this remote event. + */ + addedDocuments: DocumentKeySet, + /** + * The set of documents that were already assigned to this target but received + * an update during this remote event. + */ + modifiedDocuments: DocumentKeySet, + /** + * The set of documents that were removed from this target as part of this + * remote event. + */ + removedDocuments: DocumentKeySet); + /** + * This method is used to create a synthesized TargetChanges that can be used to + * apply a CURRENT status change to a View (for queries executed in a different + * tab) or for new queries (to raise snapshots with correct CURRENT status). + */ + static createSynthesizedTargetChangeForCurrentChange(targetId: TargetId, current: boolean, resumeToken: _ByteString): TargetChange; +} + +declare type TargetChangeTargetChangeType = 'NO_CHANGE' | 'ADD' | 'REMOVE' | 'CURRENT' | 'RESET'; + +/** + * An immutable set of metadata that the local store tracks for each target. + */ +declare class TargetData { + /** The target being listened to. */ + readonly target: Target; + /** + * The target ID to which the target corresponds; Assigned by the + * LocalStore for user listens and by the SyncEngine for limbo watches. + */ + readonly targetId: TargetId; + /** The purpose of the target. */ + readonly purpose: TargetPurpose; + /** + * The sequence number of the last transaction during which this target data + * was modified. + */ + readonly sequenceNumber: ListenSequenceNumber; + /** The latest snapshot version seen for this target. */ + readonly snapshotVersion: SnapshotVersion; + /** + * The maximum snapshot version at which the associated view + * contained no limbo documents. + */ + readonly lastLimboFreeSnapshotVersion: SnapshotVersion; + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + readonly resumeToken: _ByteString; + /** + * The number of documents that last matched the query at the resume token or + * read time. Documents are counted only when making a listen request with + * resume token or read time, otherwise, keep it null. + */ + readonly expectedCount: number | null; + constructor( + /** The target being listened to. */ + target: Target, + /** + * The target ID to which the target corresponds; Assigned by the + * LocalStore for user listens and by the SyncEngine for limbo watches. + */ + targetId: TargetId, + /** The purpose of the target. */ + purpose: TargetPurpose, + /** + * The sequence number of the last transaction during which this target data + * was modified. + */ + sequenceNumber: ListenSequenceNumber, + /** The latest snapshot version seen for this target. */ + snapshotVersion?: SnapshotVersion, + /** + * The maximum snapshot version at which the associated view + * contained no limbo documents. + */ + lastLimboFreeSnapshotVersion?: SnapshotVersion, + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + resumeToken?: _ByteString, + /** + * The number of documents that last matched the query at the resume token or + * read time. Documents are counted only when making a listen request with + * resume token or read time, otherwise, keep it null. + */ + expectedCount?: number | null); + /** Creates a new target data instance with an updated sequence number. */ + withSequenceNumber(sequenceNumber: number): TargetData; + /** + * Creates a new target data instance with an updated resume token and + * snapshot version. + */ + withResumeToken(resumeToken: _ByteString, snapshotVersion: SnapshotVersion): TargetData; + /** + * Creates a new target data instance with an updated expected count. + */ + withExpectedCount(expectedCount: number): TargetData; + /** + * Creates a new target data instance with an updated last limbo free + * snapshot version number. + */ + withLastLimboFreeSnapshotVersion(lastLimboFreeSnapshotVersion: SnapshotVersion): TargetData; +} + +/** + * A locally-assigned ID used to refer to a target being watched via the + * Watch service. + */ +declare type TargetId = number; + +/** An enumeration of the different purposes we have for targets. */ +declare const enum TargetPurpose { + /** A regular, normal query target. */ + Listen = "TargetPurposeListen", + /** + * The query target was used to refill a query after an existence filter + * mismatch. + */ + ExistenceFilterMismatch = "TargetPurposeExistenceFilterMismatch", + /** + * The query target was used if the query is the result of a false positive in + * the bloom filter. + */ + ExistenceFilterMismatchBloom = "TargetPurposeExistenceFilterMismatchBloom", + /** The query target was used to resolve a limbo document. */ + LimboResolution = "TargetPurposeLimboResolution" +} + +/** + * Represents the state of bundle loading tasks. + * + * Both 'Error' and 'Success' are sinking state: task will abort or complete and there will + * be no more updates after they are reported. + */ +export declare type TaskState = 'Error' | 'Running' | 'Success'; + +/** + * Terminates the provided {@link Firestore} instance. + * + * After calling `terminate()` only the `clearIndexedDbPersistence()` function + * may be used. Any other function will throw a `FirestoreError`. + * + * To restart after termination, create a new instance of FirebaseFirestore with + * {@link (getFirestore:1)}. + * + * Termination does not cancel any pending writes, and any promises that are + * awaiting a response from the server will not be resolved. If you have + * persistence enabled, the next time you start this instance, it will resume + * sending these writes to the server. + * + * Note: Under normal circumstances, calling `terminate()` is not required. This + * function is useful only when you want to force this instance to release all + * of its resources or in combination with `clearIndexedDbPersistence()` to + * ensure that all local state is destroyed between test runs. + * + * @returns A `Promise` that is resolved when the instance has been successfully + * terminated. + */ +export declare function terminate(firestore: Firestore): Promise; + +/* Excluded from this release type: _TestingHooks */ + +/* Excluded from this release type: _TestingHooksExistenceFilterMismatchCallback */ + +/* Excluded from this release type: _TestingHooksExistenceFilterMismatchInfo */ + +/** + * Wellknown "timer" IDs used when scheduling delayed operations on the + * AsyncQueue. These IDs can then be used from tests to check for the presence + * of operations or to run them early. + * + * The string values are used when encoding these timer IDs in JSON spec tests. + */ +declare const enum TimerId { + /** All can be used with runDelayedOperationsEarly() to run all timers. */ + All = "all", + /** + * The following 5 timers are used in persistent_stream.ts for the listen and + * write streams. The "Idle" timer is used to close the stream due to + * inactivity. The "ConnectionBackoff" timer is used to restart a stream once + * the appropriate backoff delay has elapsed. The health check is used to mark + * a stream healthy if it has not received an error during its initial setup. + */ + ListenStreamIdle = "listen_stream_idle", + ListenStreamConnectionBackoff = "listen_stream_connection_backoff", + WriteStreamIdle = "write_stream_idle", + WriteStreamConnectionBackoff = "write_stream_connection_backoff", + HealthCheckTimeout = "health_check_timeout", + /** + * A timer used in online_state_tracker.ts to transition from + * OnlineState.Unknown to Offline after a set timeout, rather than waiting + * indefinitely for success or failure. + */ + OnlineStateTimeout = "online_state_timeout", + /** + * A timer used to update the client metadata in IndexedDb, which is used + * to determine the primary leaseholder. + */ + ClientMetadataRefresh = "client_metadata_refresh", + /** A timer used to periodically attempt LRU Garbage collection */ + LruGarbageCollection = "lru_garbage_collection", + /** + * A timer used to retry transactions. Since there can be multiple concurrent + * transactions, multiple of these may be in the queue at a given time. + */ + TransactionRetry = "transaction_retry", + /** + * A timer used to retry operations scheduled via retryable AsyncQueue + * operations. + */ + AsyncQueueRetry = "async_queue_retry", + /** + * A timer used to periodically attempt index backfill. + */ + IndexBackfill = "index_backfill" +} + +/** + * A `Timestamp` represents a point in time independent of any time zone or + * calendar, represented as seconds and fractions of seconds at nanosecond + * resolution in UTC Epoch time. + * + * It is encoded using the Proleptic Gregorian Calendar which extends the + * Gregorian calendar backwards to year one. It is encoded assuming all minutes + * are 60 seconds long, i.e. leap seconds are "smeared" so that no leap second + * table is needed for interpretation. Range is from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59.999999999Z. + * + * For examples and further specifications, refer to the + * {@link https://github.com/google/protobuf/blob/master/src/google/protobuf/timestamp.proto | Timestamp definition}. + */ +export declare class Timestamp { + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + readonly seconds: number; + /** + * The fractions of a second at nanosecond resolution.* + */ + readonly nanoseconds: number; + /** + * Creates a new timestamp with the current date, with millisecond precision. + * + * @returns a new timestamp representing the current date. + */ + static now(): Timestamp; + /** + * Creates a new timestamp from the given date. + * + * @param date - The date to initialize the `Timestamp` from. + * @returns A new `Timestamp` representing the same point in time as the given + * date. + */ + static fromDate(date: Date): Timestamp; + /** + * Creates a new timestamp from the given number of milliseconds. + * + * @param milliseconds - Number of milliseconds since Unix epoch + * 1970-01-01T00:00:00Z. + * @returns A new `Timestamp` representing the same point in time as the given + * number of milliseconds. + */ + static fromMillis(milliseconds: number): Timestamp; + /** + * Creates a new timestamp. + * + * @param seconds - The number of seconds of UTC time since Unix epoch + * 1970-01-01T00:00:00Z. Must be from 0001-01-01T00:00:00Z to + * 9999-12-31T23:59:59Z inclusive. + * @param nanoseconds - The non-negative fractions of a second at nanosecond + * resolution. Negative second values with fractions must still have + * non-negative nanoseconds values that count forward in time. Must be + * from 0 to 999,999,999 inclusive. + */ + constructor( + /** + * The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z. + */ + seconds: number, + /** + * The fractions of a second at nanosecond resolution.* + */ + nanoseconds: number); + /** + * Converts a `Timestamp` to a JavaScript `Date` object. This conversion + * causes a loss of precision since `Date` objects only support millisecond + * precision. + * + * @returns JavaScript `Date` object representing the same point in time as + * this `Timestamp`, with millisecond precision. + */ + toDate(): Date; + /** + * Converts a `Timestamp` to a numeric timestamp (in milliseconds since + * epoch). This operation causes a loss of precision. + * + * @returns The point in time corresponding to this timestamp, represented as + * the number of milliseconds since Unix epoch 1970-01-01T00:00:00Z. + */ + toMillis(): number; + _compareTo(other: Timestamp): number; + /** + * Returns true if this `Timestamp` is equal to the provided one. + * + * @param other - The `Timestamp` to compare against. + * @returns true if this `Timestamp` is equal to the provided one. + */ + isEqual(other: Timestamp): boolean; + /** Returns a textual representation of this `Timestamp`. */ + toString(): string; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + seconds: Property<"number">; + nanoseconds: Property<"number">; + }; + /** + * Returns a JSON-serializable representation of this `Timestamp`. + */ + toJSON(): { + seconds: number; + nanoseconds: number; + type: string; + }; + /** + * Builds a `Timestamp` instance from a JSON object created by {@link Timestamp.toJSON}. + */ + static fromJSON(json: object): Timestamp; + /** + * Converts this object to a primitive string, which allows `Timestamp` objects + * to be compared using the `>`, `<=`, `>=` and `>` operators. + */ + valueOf(): string; +} + +declare type Timestamp_2 = string | { + seconds?: string | number; + nanos?: number; +}; + +declare interface Token { + /** Type of token. */ + type: TokenType; + /** + * The user with which the token is associated (used for persisting user + * state on disk, etc.). + * This will be null for Tokens of the type 'AppCheck'. + */ + user?: User; + /** Header values to set for this token */ + headers: Map; +} + +declare type TokenType = 'OAuth' | 'FirstParty' | 'AppCheck'; + +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ +export declare class Transaction extends Transaction_2 { + protected readonly _firestore: Firestore; + /** @hideconstructor */ + constructor(_firestore: Firestore, _transaction: Transaction_3); + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ + get(documentRef: DocumentReference): Promise>; +} + +/** + * A reference to a transaction. + * + * The `Transaction` object passed to a transaction's `updateFunction` provides + * the methods to read and write data within the transaction context. See + * {@link runTransaction}. + */ +declare class Transaction_2 { + protected readonly _firestore: Firestore_2; + private readonly _transaction; + private readonly _dataReader; + /** @hideconstructor */ + constructor(_firestore: Firestore_2, _transaction: Transaction_3); + /** + * Reads the document referenced by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be read. + * @returns A `DocumentSnapshot` with the read data. + */ + get(documentRef: DocumentReference): Promise>; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: WithFieldValue): this; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * If you provide `merge` or `mergeFields`, the provided data can be merged + * into an existing document. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: PartialWithFieldValue, options: SetOptions): this; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * @param documentRef - A reference to the document to be updated. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, data: UpdateData): this; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * @param documentRef - A reference to the document to be updated. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key/value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): this; + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `Transaction` instance. Used for chaining method calls. + */ + delete(documentRef: DocumentReference): this; +} + +/** + * Internal transaction object responsible for accumulating the mutations to + * perform and the base versions for any documents read. + */ +declare class Transaction_3 { + private datastore; + private readVersions; + private mutations; + private committed; + /** + * A deferred usage error that occurred previously in this transaction that + * will cause the transaction to fail once it actually commits. + */ + private lastTransactionError; + /** + * Set of documents that have been written in the transaction. + * + * When there's more than one write to the same key in a transaction, any + * writes after the first are handled differently. + */ + private writtenDocs; + constructor(datastore: Datastore); + lookup(keys: _DocumentKey[]): Promise; + set(key: _DocumentKey, data: ParsedSetData): void; + update(key: _DocumentKey, data: ParsedUpdateData): void; + delete(key: _DocumentKey): void; + commit(): Promise; + private recordVersion; + /** + * Returns the version of this document when it was read in this transaction, + * as a precondition, or no precondition if it was not read. + */ + private precondition; + /** + * Returns the precondition for a document if the operation is an update. + */ + private preconditionForUpdate; + private write; + private ensureCommitNotCalled; +} + +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options to customize transaction behavior. + */ +export declare interface TransactionOptions { + /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */ + readonly maxAttempts?: number; +} + +/** Used to represent a field transform on a mutation. */ +declare class TransformOperation { + private _; +} + +/* Excluded from this release type: TSType */ + +declare type UnaryFilterOp = 'OPERATOR_UNSPECIFIED' | 'IS_NAN' | 'IS_NULL' | 'IS_NOT_NAN' | 'IS_NOT_NULL'; + +/** + * Given a union type `U = T1 | T2 | ...`, returns an intersected type + * `(T1 & T2 & ...)`. + * + * Uses distributive conditional types and inference from conditional types. + * This works because multiple candidates for the same type variable in + * contra-variant positions causes an intersection type to be inferred. + * https://www.typescriptlang.org/docs/handbook/advanced-types.html#type-inference-in-conditional-types + * https://stackoverflow.com/questions/50374908/transform-union-type-to-intersection-type + */ +export declare type UnionToIntersection = (U extends unknown ? (k: U) => void : never) extends (k: infer I) => void ? I : never; + +/** + * A function returned by `onSnapshot()` that removes the listener when invoked. + */ +export declare interface Unsubscribe { + /** Removes the listener when invoked. */ + (): void; +} + +/** + * An untyped Firestore Data Converter interface that is shared between the + * lite, firestore-exp and classic SDK. + */ +declare interface UntypedFirestoreDataConverter { + toFirestore(modelObject: WithFieldValue): WithFieldValue; + toFirestore(modelObject: PartialWithFieldValue, options: SetOptions_2): PartialWithFieldValue; + fromFirestore(snapshot: unknown, options?: unknown): AppModelType; +} + +/** + * Update data (for use with {@link (updateDoc:1)}) that consists of field paths + * (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots + * reference nested fields within the document. FieldValues can be passed in + * as property values. + */ +export declare type UpdateData = T extends Primitive ? T : T extends {} ? { + [K in keyof T]?: UpdateData | FieldValue; +} & NestedUpdateFields : Partial; + +/** + * Updates fields in the document referred to by the specified + * `DocumentReference`. The update will fail if applied to a document that does + * not exist. + * + * @param reference - A reference to the document to update. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +export declare function updateDoc(reference: DocumentReference, data: UpdateData): Promise; + +/** + * Updates fields in the document referred to by the specified + * `DocumentReference` The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be updated by providing dot-separated field path + * strings or by providing `FieldPath` objects. + * + * @param reference - A reference to the document to update. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +export declare function updateDoc(reference: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): Promise; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Simple wrapper around a nullable UID. Mostly exists to make code more + * readable. + */ +declare class User { + readonly uid: string | null; + /** A user with a null UID. */ + static readonly UNAUTHENTICATED: User; + static readonly GOOGLE_CREDENTIALS: User; + static readonly FIRST_PARTY: User; + static readonly MOCK_USER: User; + constructor(uid: string | null); + isAuthenticated(): boolean; + /** + * Returns a key representing this user, suitable for inclusion in a + * dictionary. + */ + toKey(): string; + isEqual(otherUser: User): boolean; +} + +/* Excluded from this release type: _validateIsNotUsedTogether */ + +declare type Value = firestoreV1ApiClientInterfaces.Value; + +declare type ValueNullValue = 'NULL_VALUE'; + +/** + * Creates a new `VectorValue` constructed with a copy of the given array of numbers. + * + * @param values - Create a `VectorValue` instance with a copy of this array of numbers. + * + * @returns A new `VectorValue` constructed with a copy of the given array of numbers. + */ +export declare function vector(values?: number[]): VectorValue; + +/** + * Represents a vector type in Firestore documents. + * Create an instance with {@link vector}. + * + * @class VectorValue + */ +export declare class VectorValue { + private readonly _values; + /* Excluded from this release type: __constructor */ + /** + * Returns a copy of the raw number array form of the vector. + */ + toArray(): number[]; + /** + * Returns `true` if the two `VectorValue` values have the same raw number arrays, returns `false` otherwise. + */ + isEqual(other: VectorValue): boolean; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + vectorValues: Property<"object">; + }; + /** + * Returns a JSON-serializable representation of this `VectorValue` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}. + * + * @param json a JSON object represention of a `VectorValue` instance. + * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): VectorValue; +} + +declare class ViewSnapshot { + readonly query: Query_2; + readonly docs: DocumentSet; + readonly oldDocs: DocumentSet; + readonly docChanges: DocumentViewChange[]; + readonly mutatedKeys: DocumentKeySet; + readonly fromCache: boolean; + readonly syncStateChanged: boolean; + readonly excludesMetadataChanges: boolean; + readonly hasCachedResults: boolean; + constructor(query: Query_2, docs: DocumentSet, oldDocs: DocumentSet, docChanges: DocumentViewChange[], mutatedKeys: DocumentKeySet, fromCache: boolean, syncStateChanged: boolean, excludesMetadataChanges: boolean, hasCachedResults: boolean); + /** Returns a view snapshot as if all documents in the snapshot were added. */ + static fromInitialDocuments(query: Query_2, documents: DocumentSet, mutatedKeys: DocumentKeySet, fromCache: boolean, hasCachedResults: boolean): ViewSnapshot; + get hasPendingWrites(): boolean; + isEqual(other: ViewSnapshot): boolean; +} + +/** + * Waits until all currently pending writes for the active user have been + * acknowledged by the backend. + * + * The returned promise resolves immediately if there are no outstanding writes. + * Otherwise, the promise waits for all previously issued writes (including + * those written in a previous app session), but it does not wait for writes + * that were added after the function is called. If you want to wait for + * additional writes, call `waitForPendingWrites()` again. + * + * Any outstanding `waitForPendingWrites()` promises are rejected during user + * changes. + * + * @returns A `Promise` which resolves when all currently pending writes have been + * acknowledged by the backend. + */ +export declare function waitForPendingWrites(firestore: Firestore): Promise; + +/** + * Creates a {@link QueryFieldFilterConstraint} that enforces that documents + * must contain the specified field and that the value should satisfy the + * relation constraint provided. + * + * @param fieldPath - The path to compare + * @param opStr - The operation string (e.g "<", "<=", "==", "<", + * "<=", "!="). + * @param value - The value for comparison + * @returns The created {@link QueryFieldFilterConstraint}. + */ +export declare function where(fieldPath: string | FieldPath, opStr: WhereFilterOp, value: unknown): QueryFieldFilterConstraint; + +/** + * Filter conditions in a {@link where} clause are specified using the + * strings '<', '<=', '==', '!=', '>=', '>', 'array-contains', 'in', + * 'array-contains-any', and 'not-in'. + */ +export declare type WhereFilterOp = '<' | '<=' | '==' | '!=' | '>=' | '>' | 'array-contains' | 'in' | 'array-contains-any' | 'not-in'; + +/** + * Allows FieldValues to be passed in as a property value while maintaining + * type safety. + */ +export declare type WithFieldValue = T | (T extends Primitive ? T : T extends {} ? { + [K in keyof T]: WithFieldValue | FieldValue; +} : never); + +/** + * A write batch, used to perform multiple writes as a single atomic unit. + * + * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It + * provides methods for adding writes to the write batch. None of the writes + * will be committed (or visible locally) until {@link WriteBatch.commit} is + * called. + */ +export declare class WriteBatch { + private readonly _firestore; + private readonly _commitHandler; + private readonly _dataReader; + private _mutations; + private _committed; + /** @hideconstructor */ + constructor(_firestore: Firestore_2, _commitHandler: (m: Mutation[]) => Promise); + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: WithFieldValue): WriteBatch; + /** + * Writes to the document referred to by the provided {@link + * DocumentReference}. If the document does not exist yet, it will be created. + * If you provide `merge` or `mergeFields`, the provided data can be merged + * into an existing document. + * + * @param documentRef - A reference to the document to be set. + * @param data - An object of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @throws Error - If the provided input is not a valid Firestore document. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + set(documentRef: DocumentReference, data: PartialWithFieldValue, options: SetOptions): WriteBatch; + /** + * Updates fields in the document referred to by the provided {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * @param documentRef - A reference to the document to be updated. + * @param data - An object containing the fields and values with which to + * update the document. Fields can contain dots to reference nested fields + * within the document. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, data: UpdateData): WriteBatch; + /** + * Updates fields in the document referred to by this {@link + * DocumentReference}. The update will fail if applied to a document that does + * not exist. + * + * Nested fields can be update by providing dot-separated field path strings + * or by providing `FieldPath` objects. + * + * @param documentRef - A reference to the document to be updated. + * @param field - The first field to update. + * @param value - The first value. + * @param moreFieldsAndValues - Additional key value pairs. + * @throws Error - If the provided input is not valid Firestore data. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + update(documentRef: DocumentReference, field: string | FieldPath, value: unknown, ...moreFieldsAndValues: unknown[]): WriteBatch; + /** + * Deletes the document referred to by the provided {@link DocumentReference}. + * + * @param documentRef - A reference to the document to be deleted. + * @returns This `WriteBatch` instance. Used for chaining method calls. + */ + delete(documentRef: DocumentReference): WriteBatch; + /** + * Commits all of the writes in this write batch as a single atomic unit. + * + * The result of these writes will only be reflected in document reads that + * occur after the returned promise resolves. If the client is offline, the + * write fails. If you would like to see local modifications or buffer writes + * until the client is online, use the full Firestore SDK. + * + * @returns A `Promise` resolved once all of the writes in the batch have been + * successfully written to the backend as an atomic unit (note that it won't + * resolve while you're offline). + */ + commit(): Promise; + private _verifyNotCommitted; +} + +/** + * Creates a write batch, used for performing multiple writes as a single + * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch} + * is 500. + * + * Unlike transactions, write batches are persisted offline and therefore are + * preferable when you don't need to condition your writes on read data. + * + * @returns A {@link WriteBatch} that can be used to atomically execute multiple + * writes. + */ +export declare function writeBatch(firestore: Firestore): WriteBatch; + +export { } diff --git a/frontend-old/node_modules/@firebase/firestore/lite/package.json b/frontend-old/node_modules/@firebase/firestore/lite/package.json new file mode 100644 index 0000000..5744f1d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/lite/package.json @@ -0,0 +1,14 @@ +{ + "name": "@firebase/firestore-lite", + "description": "A lite version of the Firestore SDK", + "main": "../dist/lite/index.node.cjs.js", + "main-esm": "../dist/lite/index.node.mjs", + "module": "../dist/lite/index.browser.esm.js", + "browser": "../dist/lite/index.browser.esm.js", + "react-native": "../dist/lite/index.rn.esm.js", + "typings": "../dist/lite/index.d.ts", + "private": true, + "engines": { + "node": ">=20.0.0" + } +} diff --git a/frontend-old/node_modules/@firebase/firestore/package.json b/frontend-old/node_modules/@firebase/firestore/package.json new file mode 100644 index 0000000..b1abd09 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/package.json @@ -0,0 +1,150 @@ +{ + "name": "@firebase/firestore", + "version": "4.9.2", + "engines": { + "node": ">=20.0.0" + }, + "description": "The Cloud Firestore component of the Firebase JS SDK.", + "author": "Firebase (https://firebase.google.com/)", + "scripts": { + "bundle": "rollup -c", + "prebuild": "tsc --emitDeclarationOnly --declaration -p tsconfig.json; yarn api-report", + "build": "run-p --npm-path npm build:lite build:main", + "build:release": "yarn build && yarn typings:public", + "build:scripts": "tsc -moduleResolution node --module commonjs scripts/*.ts && ls scripts/*.js | xargs -I % sh -c 'terser % -o %'", + "build:deps": "lerna run --scope @firebase/firestore --include-dependencies build", + "build:main": "rollup -c rollup.config.js", + "build:lite": "rollup -c rollup.config.lite.js", + "build:debug": "rollup -c rollup.config.debug.js", + "predev": "yarn prebuild", + "dev": "rollup -c -w", + "lint": "eslint -c .eslintrc.js '**/*.ts' --ignore-path '../../.gitignore'", + "lint:fix": "eslint --fix -c .eslintrc.js '**/*.ts' --ignore-path '../../.gitignore'", + "prettier": "prettier --write '*.js' '@(lite|src|test|scripts)/**/*.ts' 'test/unit/remote/bloom_filter_golden_test_data/*.json'", + "test:lite": "ts-node ./scripts/run-tests.ts --emulator --platform node_lite --main=lite/index.ts 'test/lite/**/*.test.ts'", + "test:lite:prod": "ts-node ./scripts/run-tests.ts --platform node_lite --main=lite/index.ts 'test/lite/**/*.test.ts'", + "test:lite:prod:nameddb": "ts-node ./scripts/run-tests.ts --platform node_lite --databaseId=test-db --main=lite/index.ts 'test/lite/**/*.test.ts'", + "test:lite:browser": "karma start --lite", + "test:lite:browser:nameddb": "karma start --lite --databaseId=test-db", + "test:lite:browser:debug": "karma start --browsers=Chrome --lite --auto-watch", + "test": "run-s --npm-path npm lint assertion-id:check test:all", + "test:ci": "node ../../scripts/run_tests_in_ci.js -s test:all:ci", + "test:all:ci": "run-s --npm-path npm test:browser test:travis test:lite:browser test:browser:prod:nameddb test:lite:browser:nameddb", + "test:all": "run-p --npm-path npm test:browser test:lite:browser test:travis test:minified test:browser:prod:nameddb test:lite:browser:nameddb", + "test:browser": "karma start", + "test:browser:emulator:debug": "karma start --browsers=Chrome --targetBackend=emulator", + "test:browser:emulator": "karma start --targetBackend=emulator", + "test:browser:nightly": "karma start --targetBackend=nightly", + "test:browser:prod": "karma start --targetBackend=prod", + "test:webkit:prod": "BROWSERS=WebkitHeadless karma start --targetBackend=prod", + "test:webkit:unit": "BROWSERS=WebkitHeadless karma start --unit --targetBackend=prod", + "test:browser:prod:nameddb": "karma start --targetBackend=prod --databaseId=test-db", + "test:browser:unit": "karma start --unit", + "test:browser:debug": "karma start --browsers=Chrome --auto-watch", + "test:node": "ts-node ./scripts/run-tests.ts --main=test/register.ts --emulator 'test/{,!(browser|lite)/**/}*.test.ts'", + "test:node:prod": "ts-node ./scripts/run-tests.ts --main=test/register.ts 'test/{,!(browser|lite)/**/}*.test.ts'", + "test:node:prod:nameddb": "ts-node ./scripts/run-tests.ts --main=test/register.ts --databaseId=test-db 'test/{,!(browser|lite)/**/}*.test.ts'", + "test:node:persistence": "ts-node ./scripts/run-tests.ts --main=test/register.ts --persistence --emulator 'test/{,!(browser|lite)/**/}*.test.ts'", + "test:node:persistence:prod": "ts-node ./scripts/run-tests.ts --main=test/register.ts --persistence 'test/{,!(browser|lite)/**/}*.test.ts'", + "test:travis": "ts-node --compiler-options='{\"module\":\"commonjs\"}' ../../scripts/emulator-testing/firestore-test-runner.ts", + "test:minified": "(cd ../../integration/firestore ; yarn test)", + "trusted-type-check": "tsec -p tsconfig.json --noEmit", + "api-report:main": "TS_NODE_COMPILER_OPTIONS='{\"module\":\"commonjs\"}' ts-node ../../repo-scripts/prune-dts/extract-public-api.ts --package firestore --packageRoot . --typescriptDts ./dist/firestore/src/index.d.ts --rollupDts ./dist/private.d.ts --untrimmedRollupDts ./dist/internal.d.ts --publicDts ./dist/index.d.ts", + "api-report:lite": "TS_NODE_COMPILER_OPTIONS='{\"module\":\"commonjs\"}' ts-node ../../repo-scripts/prune-dts/extract-public-api.ts --package firestore-lite --packageRoot . --typescriptDts ./dist/firestore/lite/index.d.ts --rollupDts ./dist/lite/private.d.ts --untrimmedRollupDts ./dist/lite/internal.d.ts --publicDts ./dist/lite/index.d.ts", + "api-report:api-json": "rm -rf temp && api-extractor run --local --verbose", + "api-report": "run-s --npm-path npm api-report:main api-report:lite && yarn api-report:api-json", + "doc": "api-documenter markdown --input temp --output docs", + "typings:public": "node ../../scripts/build/use_typings.js ./dist/index.d.ts", + "assertion-id:check": "ts-node scripts/assertion-id-tool.ts --dir=src --check", + "assertion-id:new": "ts-node scripts/assertion-id-tool.ts --dir=src --new", + "assertion-id:list": "ts-node scripts/assertion-id-tool.ts --dir=src --list", + "assertion-id:find": "ts-node scripts/assertion-id-tool.ts --dir=src --find" + }, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "node": { + "require": "./dist/index.node.cjs.js", + "import": "./dist/index.node.mjs" + }, + "react-native": "./dist/index.rn.js", + "browser": { + "require": "./dist/index.cjs.js", + "import": "./dist/index.esm.js" + }, + "default": "./dist/index.esm.js" + }, + "./lite": { + "types": "./dist/lite/index.d.ts", + "node": { + "require": "./dist/lite/index.node.cjs.js", + "import": "./dist/lite/index.node.mjs" + }, + "react-native": "./dist/lite/index.rn.esm.js", + "browser": { + "require": "./dist/lite/index.cjs.js", + "import": "./dist/lite/index.browser.esm.js" + }, + "default": "./dist/lite/index.browser.esm.js" + }, + "./package.json": "./package.json" + }, + "main": "dist/index.node.cjs.js", + "main-esm": "dist/index.node.mjs", + "react-native": "dist/index.rn.js", + "browser": "dist/index.esm.js", + "module": "dist/index.esm.js", + "license": "Apache-2.0", + "files": [ + "dist", + "lite/package.json" + ], + "dependencies": { + "@firebase/component": "0.7.0", + "@firebase/logger": "0.5.0", + "@firebase/util": "1.13.0", + "@firebase/webchannel-wrapper": "1.0.5", + "@grpc/grpc-js": "~1.9.0", + "@grpc/proto-loader": "^0.7.8", + "tslib": "^2.1.0" + }, + "peerDependencies": { + "@firebase/app": "0.x" + }, + "devDependencies": { + "@firebase/app": "0.14.3", + "@firebase/app-compat": "0.5.3", + "@firebase/auth": "1.11.0", + "@rollup/plugin-alias": "5.1.1", + "@rollup/plugin-json": "6.1.0", + "@types/eslint": "7.29.0", + "chai-exclude": "2.1.1", + "json-stable-stringify": "1.2.1", + "protobufjs": "7.4.0", + "rollup": "2.79.2", + "rollup-plugin-copy": "3.5.0", + "rollup-plugin-copy-assets": "2.0.3", + "rollup-plugin-replace": "2.2.0", + "rollup-plugin-sourcemaps": "0.6.3", + "@rollup/plugin-terser": "0.4.4", + "rollup-plugin-typescript2": "0.36.0", + "rollup-plugin-dts": "5.3.1", + "ts-node": "10.9.2", + "typescript": "5.5.4" + }, + "repository": { + "directory": "packages/firestore", + "type": "git", + "url": "git+https://github.com/firebase/firebase-js-sdk.git" + }, + "bugs": { + "url": "https://github.com/firebase/firebase-js-sdk/issues" + }, + "typings": "./dist/index.d.ts", + "nyc": { + "extension": [ + ".ts" + ], + "reportDir": "./coverage/node" + } +} -- cgit v1.2.3

The documents returned by this method are ordered by remote version from the provided + * offset. If there are no more remote documents after the provided offset, documents with + * mutations in order of batch id from the offset are returned. Since all documents in a batch are + * returned together, the total number of documents returned can exceed {@code count}. + * + * @param transaction + * @param collectionGroup The collection group for the documents. + * @param offset The offset to index into. + * @param count The number of documents to return + * @return A LocalWriteResult with the documents that follow the provided offset and the last processed batch id. + */ + getNextDocuments(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset, count: number): PersistencePromise; + private getDocumentsMatchingDocumentQuery; + private getDocumentsMatchingCollectionGroupQuery; + private getDocumentsMatchingCollectionQuery; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_serializer.d.ts new file mode 100644 index 0000000..88599b4 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_serializer.d.ts @@ -0,0 +1,80 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BundleMetadata, NamedQuery } from '../core/bundle'; +import { Query } from '../core/query'; +import { SnapshotVersion } from '../core/snapshot_version'; +import { MutableDocument } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { FieldIndex, IndexOffset } from '../model/field_index'; +import { MutationBatch } from '../model/mutation_batch'; +import { Overlay } from '../model/overlay'; +import { BundledQuery as ProtoBundledQuery, BundleMetadata as ProtoBundleMetadata, NamedQuery as ProtoNamedQuery } from '../protos/firestore_bundle_proto'; +import { JsonProtoSerializer } from '../remote/serializer'; +import { DbBundle, DbDocumentOverlay, DbIndexConfiguration, DbIndexState, DbMutationBatch, DbNamedQuery, DbRemoteDocument, DbTarget, DbTimestamp } from './indexeddb_schema'; +import { DbDocumentOverlayKey, DbTimestampKey } from './indexeddb_sentinels'; +import { TargetData } from './target_data'; +/** Serializer for values stored in the LocalStore. */ +export declare class LocalSerializer { + readonly remoteSerializer: JsonProtoSerializer; + constructor(remoteSerializer: JsonProtoSerializer); +} +/** Decodes a remote document from storage locally to a Document. */ +export declare function fromDbRemoteDocument(localSerializer: LocalSerializer, remoteDoc: DbRemoteDocument): MutableDocument; +/** Encodes a document for storage locally. */ +export declare function toDbRemoteDocument(localSerializer: LocalSerializer, document: MutableDocument): DbRemoteDocument; +export declare function toDbTimestampKey(snapshotVersion: SnapshotVersion): DbTimestampKey; +export declare function fromDbTimestampKey(dbTimestampKey: DbTimestampKey): SnapshotVersion; +export declare function toDbTimestamp(snapshotVersion: SnapshotVersion): DbTimestamp; +/** Encodes a batch of mutations into a DbMutationBatch for local storage. */ +export declare function toDbMutationBatch(localSerializer: LocalSerializer, userId: string, batch: MutationBatch): DbMutationBatch; +/** Decodes a DbMutationBatch into a MutationBatch */ +export declare function fromDbMutationBatch(localSerializer: LocalSerializer, dbBatch: DbMutationBatch): MutationBatch; +/** Decodes a DbTarget into TargetData */ +export declare function fromDbTarget(dbTarget: DbTarget): TargetData; +/** Encodes TargetData into a DbTarget for storage locally. */ +export declare function toDbTarget(localSerializer: LocalSerializer, targetData: TargetData): DbTarget; +/** Encodes a DbBundle to a BundleMetadata object. */ +export declare function fromDbBundle(dbBundle: DbBundle): BundleMetadata; +/** Encodes a BundleMetadata to a DbBundle. */ +export declare function toDbBundle(metadata: ProtoBundleMetadata): DbBundle; +/** Encodes a DbNamedQuery to a NamedQuery. */ +export declare function fromDbNamedQuery(dbNamedQuery: DbNamedQuery): NamedQuery; +/** Encodes a NamedQuery from a bundle proto to a DbNamedQuery. */ +export declare function toDbNamedQuery(query: ProtoNamedQuery): DbNamedQuery; +/** + * Encodes a `BundledQuery` from bundle proto to a Query object. + * + * This reconstructs the original query used to build the bundle being loaded, + * including features exists only in SDKs (for example: limit-to-last). + */ +export declare function fromBundledQuery(bundledQuery: ProtoBundledQuery): Query; +/** Encodes a NamedQuery proto object to a NamedQuery model object. */ +export declare function fromProtoNamedQuery(namedQuery: ProtoNamedQuery): NamedQuery; +/** Decodes a BundleMetadata proto into a BundleMetadata object. */ +export declare function fromBundleMetadata(metadata: ProtoBundleMetadata): BundleMetadata; +/** Encodes a DbDocumentOverlay object to an Overlay model object. */ +export declare function fromDbDocumentOverlay(localSerializer: LocalSerializer, dbDocumentOverlay: DbDocumentOverlay): Overlay; +/** Decodes an Overlay model object into a DbDocumentOverlay object. */ +export declare function toDbDocumentOverlay(localSerializer: LocalSerializer, userId: string, overlay: Overlay): DbDocumentOverlay; +/** + * Returns the DbDocumentOverlayKey corresponding to the given user and + * document key. + */ +export declare function toDbDocumentOverlayKey(userId: string, docKey: DocumentKey): DbDocumentOverlayKey; +export declare function toDbIndexConfiguration(index: FieldIndex): DbIndexConfiguration; +export declare function fromDbIndexConfiguration(index: DbIndexConfiguration, state: DbIndexState | null): FieldIndex; +export declare function toDbIndexState(indexId: number, uid: string, sequenceNumber: number, offset: IndexOffset): DbIndexState; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_store.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_store.d.ts new file mode 100644 index 0000000..2284d7d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_store.d.ts @@ -0,0 +1,41 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirestoreError } from '../util/error'; +import { IndexManager } from './index_manager'; +import { LocalDocumentsView } from './local_documents_view'; +import { LruGarbageCollector, LruResults } from './lru_garbage_collector'; +export interface LocalStore { + collectGarbage(garbageCollector: LruGarbageCollector): Promise; + /** Manages the list of active field and collection indices. */ + indexManager: IndexManager; + /** + * The "local" view of all documents (layering mutationQueue on top of + * remoteDocumentCache). + */ + localDocuments: LocalDocumentsView; +} +/** + * Verifies the error thrown by a LocalStore operation. If a LocalStore + * operation fails because the primary lease has been taken by another client, + * we ignore the error (the persistence layer will immediately call + * `applyPrimaryLease` to propagate the primary state change). All other errors + * are re-thrown. + * + * @param err - An error returned by a LocalStore operation. + * @returns A Promise that resolves after we recovered, or the original error. + */ +export declare function ignoreIfPrimaryLeaseLoss(err: FirestoreError): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_store_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_store_impl.d.ts new file mode 100644 index 0000000..1b86e0d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_store_impl.d.ts @@ -0,0 +1,208 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { BundleConverter, BundledDocuments, NamedQuery } from '../core/bundle'; +import { Query } from '../core/query'; +import { SnapshotVersion } from '../core/snapshot_version'; +import { Target } from '../core/target'; +import { BatchId, TargetId } from '../core/types'; +import { DocumentKeySet, DocumentMap } from '../model/collections'; +import { Document } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { FieldIndex } from '../model/field_index'; +import { Mutation } from '../model/mutation'; +import { MutationBatch, MutationBatchResult } from '../model/mutation_batch'; +import { BundleMetadata, NamedQuery as ProtoNamedQuery } from '../protos/firestore_bundle_proto'; +import { RemoteEvent } from '../remote/remote_event'; +import { JsonProtoSerializer } from '../remote/serializer'; +import { LocalStore } from './local_store'; +import { LocalViewChanges } from './local_view_changes'; +import { Persistence } from './persistence'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +import { QueryEngine } from './query_engine'; +import { ClientId } from './shared_client_state'; +import { TargetData } from './target_data'; +export declare const LOG_TAG = "LocalStore"; +/** The result of a write to the local store. */ +export interface LocalWriteResult { + batchId: BatchId; + changes: DocumentMap; +} +/** The result of a user-change operation in the local store. */ +export interface UserChangeResult { + readonly affectedDocuments: DocumentMap; + readonly removedBatchIds: BatchId[]; + readonly addedBatchIds: BatchId[]; +} +/** The result of executing a query against the local store. */ +export interface QueryResult { + readonly documents: DocumentMap; + readonly remoteKeys: DocumentKeySet; +} +export declare function newLocalStore( +/** Manages our in-memory or durable persistence. */ +persistence: Persistence, queryEngine: QueryEngine, initialUser: User, serializer: JsonProtoSerializer): LocalStore; +/** + * Tells the LocalStore that the currently authenticated user has changed. + * + * In response the local store switches the mutation queue to the new user and + * returns any resulting document changes. + */ +export declare function localStoreHandleUserChange(localStore: LocalStore, user: User): Promise; +export declare function localStoreWriteLocally(localStore: LocalStore, mutations: Mutation[]): Promise; +/** + * Acknowledges the given batch. + * + * On the happy path when a batch is acknowledged, the local store will + * + * + remove the batch from the mutation queue; + * + apply the changes to the remote document cache; + * + recalculate the latency compensated view implied by those changes (there + * may be mutations in the queue that affect the documents but haven't been + * acknowledged yet); and + * + give the changed documents back the sync engine + * + * @returns The resulting (modified) documents. + */ +export declare function localStoreAcknowledgeBatch(localStore: LocalStore, batchResult: MutationBatchResult): Promise; +/** + * Removes mutations from the MutationQueue for the specified batch; + * LocalDocuments will be recalculated. + * + * @returns The resulting modified documents. + */ +export declare function localStoreRejectBatch(localStore: LocalStore, batchId: BatchId): Promise; +/** + * Returns the largest (latest) batch id in mutation queue that is pending + * server response. + * + * Returns `BATCHID_UNKNOWN` if the queue is empty. + */ +export declare function localStoreGetHighestUnacknowledgedBatchId(localStore: LocalStore): Promise; +/** + * Returns the last consistent snapshot processed (used by the RemoteStore to + * determine whether to buffer incoming snapshots from the backend). + */ +export declare function localStoreGetLastRemoteSnapshotVersion(localStore: LocalStore): Promise; +/** + * Updates the "ground-state" (remote) documents. We assume that the remote + * event reflects any write batches that have been acknowledged or rejected + * (i.e. we do not re-apply local mutations to updates from this event). + * + * LocalDocuments are re-calculated if there are remaining mutations in the + * queue. + */ +export declare function localStoreApplyRemoteEventToLocalCache(localStore: LocalStore, remoteEvent: RemoteEvent): Promise; +/** + * Notifies local store of the changed views to locally pin documents. + */ +export declare function localStoreNotifyLocalViewChanges(localStore: LocalStore, viewChanges: LocalViewChanges[]): Promise; +/** + * Gets the mutation batch after the passed in batchId in the mutation queue + * or null if empty. + * @param afterBatchId - If provided, the batch to search after. + * @returns The next mutation or null if there wasn't one. + */ +export declare function localStoreGetNextMutationBatch(localStore: LocalStore, afterBatchId?: BatchId): Promise; +/** + * Reads the current value of a Document with a given key or null if not + * found - used for testing. + */ +export declare function localStoreReadDocument(localStore: LocalStore, key: DocumentKey): Promise; +/** + * Assigns the given target an internal ID so that its results can be pinned so + * they don't get GC'd. A target must be allocated in the local store before + * the store can be used to manage its view. + * + * Allocating an already allocated `Target` will return the existing `TargetData` + * for that `Target`. + */ +export declare function localStoreAllocateTarget(localStore: LocalStore, target: Target): Promise; +/** + * Returns the TargetData as seen by the LocalStore, including updates that may + * have not yet been persisted to the TargetCache. + */ +export declare function localStoreGetTargetData(localStore: LocalStore, transaction: PersistenceTransaction, target: Target): PersistencePromise; +/** + * Unpins all the documents associated with the given target. If + * `keepPersistedTargetData` is set to false and Eager GC enabled, the method + * directly removes the associated target data from the target cache. + * + * Releasing a non-existing `Target` is a no-op. + */ +export declare function localStoreReleaseTarget(localStore: LocalStore, targetId: number, keepPersistedTargetData: boolean): Promise; +/** + * Runs the specified query against the local store and returns the results, + * potentially taking advantage of query data from previous executions (such + * as the set of remote keys). + * + * @param usePreviousResults - Whether results from previous executions can + * be used to optimize this query execution. + */ +export declare function localStoreExecuteQuery(localStore: LocalStore, query: Query, usePreviousResults: boolean): Promise; +/** Returns the local view of the documents affected by a mutation batch. */ +export declare function localStoreLookupMutationDocuments(localStore: LocalStore, batchId: BatchId): Promise; +export declare function localStoreRemoveCachedMutationBatchMetadata(localStore: LocalStore, batchId: BatchId): void; +export declare function localStoreGetActiveClients(localStore: LocalStore): Promise; +export declare function localStoreGetCachedTarget(localStore: LocalStore, targetId: TargetId): Promise; +/** + * Returns the set of documents that have been updated since the last call. + * If this is the first call, returns the set of changes since client + * initialization. Further invocations will return document that have changed + * since the prior call. + */ +export declare function localStoreGetNewDocumentChanges(localStore: LocalStore, collectionGroup: string): Promise; +/** + * Applies the documents from a bundle to the "ground-state" (remote) + * documents. + * + * LocalDocuments are re-calculated if there are remaining mutations in the + * queue. + */ +export declare function localStoreApplyBundledDocuments(localStore: LocalStore, bundleConverter: BundleConverter, documents: BundledDocuments, bundleName: string): Promise; +/** + * Returns a promise of a boolean to indicate if the given bundle has already + * been loaded and the create time is newer than the current loading bundle. + */ +export declare function localStoreHasNewerBundle(localStore: LocalStore, bundleMetadata: BundleMetadata): Promise; +/** + * Saves the given `BundleMetadata` to local persistence. + */ +export declare function localStoreSaveBundle(localStore: LocalStore, bundleMetadata: BundleMetadata): Promise; +/** + * Returns a promise of a `NamedQuery` associated with given query name. Promise + * resolves to undefined if no persisted data can be found. + */ +export declare function localStoreGetNamedQuery(localStore: LocalStore, queryName: string): Promise; +/** + * Saves the given `NamedQuery` to local persistence. + */ +export declare function localStoreSaveNamedQuery(localStore: LocalStore, query: ProtoNamedQuery, documents?: DocumentKeySet): Promise; +export declare function localStoreConfigureFieldIndexes(localStore: LocalStore, newFieldIndexes: FieldIndex[]): Promise; +export declare function localStoreSetIndexAutoCreationEnabled(localStore: LocalStore, isEnabled: boolean): void; +export declare function localStoreDeleteAllFieldIndexes(localStore: LocalStore): Promise; +/** + * Test-only hooks into the SDK for use exclusively by tests. + */ +export declare class TestingHooks { + private constructor(); + static setIndexAutoCreationSettings(localStore: LocalStore, settings: { + indexAutoCreationMinCollectionSize?: number; + relativeIndexReadCostPerDocument?: number; + }): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_view_changes.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_view_changes.d.ts new file mode 100644 index 0000000..0448fb1 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/local_view_changes.d.ts @@ -0,0 +1,32 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { TargetId } from '../core/types'; +import { ViewSnapshot } from '../core/view_snapshot'; +import { DocumentKeySet } from '../model/collections'; +/** + * A set of changes to what documents are currently in view and out of view for + * a given query. These changes are sent to the LocalStore by the View (via + * the SyncEngine) and are used to pin / unpin documents as appropriate. + */ +export declare class LocalViewChanges { + readonly targetId: TargetId; + readonly fromCache: boolean; + readonly addedKeys: DocumentKeySet; + readonly removedKeys: DocumentKeySet; + constructor(targetId: TargetId, fromCache: boolean, addedKeys: DocumentKeySet, removedKeys: DocumentKeySet); + static fromSnapshot(targetId: TargetId, viewSnapshot: ViewSnapshot): LocalViewChanges; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/lru_garbage_collector.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/lru_garbage_collector.d.ts new file mode 100644 index 0000000..9ba755c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/lru_garbage_collector.d.ts @@ -0,0 +1,102 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ListenSequenceNumber, TargetId } from '../core/types'; +import { SortedMap } from '../util/sorted_map'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +import { TargetData } from './target_data'; +/** + * Describes a map whose keys are active target ids. We do not care about the type of the + * values. + */ +export type ActiveTargets = SortedMap; +export declare const GC_DID_NOT_RUN: LruResults; +export declare const LRU_COLLECTION_DISABLED = -1; +export declare const LRU_DEFAULT_CACHE_SIZE_BYTES: number; +export declare class LruParams { + readonly cacheSizeCollectionThreshold: number; + readonly percentileToCollect: number; + readonly maximumSequenceNumbersToCollect: number; + private static readonly DEFAULT_COLLECTION_PERCENTILE; + private static readonly DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT; + static withCacheSize(cacheSize: number): LruParams; + static readonly DEFAULT: LruParams; + static readonly DISABLED: LruParams; + constructor(cacheSizeCollectionThreshold: number, percentileToCollect: number, maximumSequenceNumbersToCollect: number); +} +export interface LruGarbageCollector { + readonly params: LruParams; + collect(txn: PersistenceTransaction, activeTargetIds: ActiveTargets): PersistencePromise; + /** Given a percentile of target to collect, returns the number of targets to collect. */ + calculateTargetCount(txn: PersistenceTransaction, percentile: number): PersistencePromise; + /** Returns the nth sequence number, counting in order from the smallest. */ + nthSequenceNumber(txn: PersistenceTransaction, n: number): PersistencePromise; + /** + * Removes documents that have a sequence number equal to or less than the + * upper bound and are not otherwise pinned. + */ + removeOrphanedDocuments(txn: PersistenceTransaction, upperBound: ListenSequenceNumber): PersistencePromise; + getCacheSize(txn: PersistenceTransaction): PersistencePromise; + /** + * Removes targets with a sequence number equal to or less than the given + * upper bound, and removes document associations with those targets. + */ + removeTargets(txn: PersistenceTransaction, upperBound: ListenSequenceNumber, activeTargetIds: ActiveTargets): PersistencePromise; +} +/** + * Describes the results of a garbage collection run. `didRun` will be set to + * `false` if collection was skipped (either it is disabled or the cache size + * has not hit the threshold). If collection ran, the other fields will be + * filled in with the details of the results. + */ +export interface LruResults { + readonly didRun: boolean; + readonly sequenceNumbersCollected: number; + readonly targetsRemoved: number; + readonly documentsRemoved: number; +} +/** + * Persistence layers intending to use LRU Garbage collection should have + * reference delegates that implement this interface. This interface defines the + * operations that the LRU garbage collector needs from the persistence layer. + */ +export interface LruDelegate { + readonly garbageCollector: LruGarbageCollector; + /** Enumerates all the targets in the TargetCache. */ + forEachTarget(txn: PersistenceTransaction, f: (target: TargetData) => void): PersistencePromise; + getSequenceNumberCount(txn: PersistenceTransaction): PersistencePromise; + /** + * Enumerates sequence numbers for documents not associated with a target. + * Note that this may include duplicate sequence numbers. + */ + forEachOrphanedDocumentSequenceNumber(txn: PersistenceTransaction, f: (sequenceNumber: ListenSequenceNumber) => void): PersistencePromise; + /** + * Removes all targets that have a sequence number less than or equal to + * `upperBound`, and are not present in the `activeTargetIds` set. + * + * @returns the number of targets removed. + */ + removeTargets(txn: PersistenceTransaction, upperBound: ListenSequenceNumber, activeTargetIds: ActiveTargets): PersistencePromise; + /** + * Removes all unreferenced documents from the cache that have a sequence + * number less than or equal to the given `upperBound`. + * + * @returns the number of documents removed. + */ + removeOrphanedDocuments(txn: PersistenceTransaction, upperBound: ListenSequenceNumber): PersistencePromise; + getCacheSize(txn: PersistenceTransaction): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/lru_garbage_collector_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/lru_garbage_collector_impl.d.ts new file mode 100644 index 0000000..f4ab1a5 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/lru_garbage_collector_impl.d.ts @@ -0,0 +1,37 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AsyncQueue } from '../util/async_queue'; +import { LocalStore } from './local_store'; +import { LruDelegate, LruGarbageCollector, LruParams } from './lru_garbage_collector'; +import { Scheduler } from './persistence'; +export declare const LRU_MINIMUM_CACHE_SIZE_BYTES: number; +/** + * This class is responsible for the scheduling of LRU garbage collection. It handles checking + * whether or not GC is enabled, as well as which delay to use before the next run. + */ +export declare class LruScheduler implements Scheduler { + private readonly garbageCollector; + private readonly asyncQueue; + private readonly localStore; + private gcTask; + constructor(garbageCollector: LruGarbageCollector, asyncQueue: AsyncQueue, localStore: LocalStore); + start(): void; + stop(): void; + get started(): boolean; + private scheduleGC; +} +export declare function newLruGarbageCollector(delegate: LruDelegate, params: LruParams): LruGarbageCollector; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_bundle_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_bundle_cache.d.ts new file mode 100644 index 0000000..972d4fc --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_bundle_cache.d.ts @@ -0,0 +1,32 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BundleMetadata, NamedQuery } from '../core/bundle'; +import { NamedQuery as ProtoNamedQuery, BundleMetadata as ProtoBundleMetadata } from '../protos/firestore_bundle_proto'; +import { BundleCache } from './bundle_cache'; +import { LocalSerializer } from './local_serializer'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +export declare class MemoryBundleCache implements BundleCache { + private serializer; + private bundles; + private namedQueries; + constructor(serializer: LocalSerializer); + getBundleMetadata(transaction: PersistenceTransaction, bundleId: string): PersistencePromise; + saveBundleMetadata(transaction: PersistenceTransaction, bundleMetadata: ProtoBundleMetadata): PersistencePromise; + getNamedQuery(transaction: PersistenceTransaction, queryName: string): PersistencePromise; + saveNamedQuery(transaction: PersistenceTransaction, query: ProtoNamedQuery): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_document_overlay_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_document_overlay_cache.d.ts new file mode 100644 index 0000000..b6ee945 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_document_overlay_cache.d.ts @@ -0,0 +1,37 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentKeySet, MutationMap, OverlayMap } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { Overlay } from '../model/overlay'; +import { ResourcePath } from '../model/path'; +import { DocumentOverlayCache } from './document_overlay_cache'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** + * An in-memory implementation of DocumentOverlayCache. + */ +export declare class MemoryDocumentOverlayCache implements DocumentOverlayCache { + private overlays; + private overlayByBatchId; + getOverlay(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; + getOverlays(transaction: PersistenceTransaction, keys: DocumentKey[]): PersistencePromise; + saveOverlays(transaction: PersistenceTransaction, largestBatchId: number, overlays: MutationMap): PersistencePromise; + removeOverlaysForBatchId(transaction: PersistenceTransaction, documentKeys: DocumentKeySet, batchId: number): PersistencePromise; + getOverlaysForCollection(transaction: PersistenceTransaction, collection: ResourcePath, sinceBatchId: number): PersistencePromise; + getOverlaysForCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, sinceBatchId: number, count: number): PersistencePromise; + private saveOverlay; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_globals_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_globals_cache.d.ts new file mode 100644 index 0000000..9877c67 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_globals_cache.d.ts @@ -0,0 +1,25 @@ +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ByteString } from '../util/byte_string'; +import { GlobalsCache } from './globals_cache'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +export declare class MemoryGlobalsCache implements GlobalsCache { + private sessionToken; + getSessionToken(transaction: PersistenceTransaction): PersistencePromise; + setSessionToken(transaction: PersistenceTransaction, sessionToken: ByteString): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_index_manager.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_index_manager.d.ts new file mode 100644 index 0000000..14ffd3d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_index_manager.d.ts @@ -0,0 +1,55 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Target } from '../core/target'; +import { DocumentMap } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { FieldIndex, IndexOffset } from '../model/field_index'; +import { ResourcePath } from '../model/path'; +import { IndexManager, IndexType } from './index_manager'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** + * An in-memory implementation of IndexManager. + */ +export declare class MemoryIndexManager implements IndexManager { + private collectionParentIndex; + addToCollectionParentIndex(transaction: PersistenceTransaction, collectionPath: ResourcePath): PersistencePromise; + getCollectionParents(transaction: PersistenceTransaction, collectionId: string): PersistencePromise; + addFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + deleteFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + deleteAllFieldIndexes(transaction: PersistenceTransaction): PersistencePromise; + createTargetIndexes(transaction: PersistenceTransaction, target: Target): PersistencePromise; + getDocumentsMatchingTarget(transaction: PersistenceTransaction, target: Target): PersistencePromise; + getIndexType(transaction: PersistenceTransaction, target: Target): PersistencePromise; + getFieldIndexes(transaction: PersistenceTransaction, collectionGroup?: string): PersistencePromise; + getNextCollectionGroupToUpdate(transaction: PersistenceTransaction): PersistencePromise; + getMinOffset(transaction: PersistenceTransaction, target: Target): PersistencePromise; + getMinOffsetFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise; + updateCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset): PersistencePromise; + updateIndexEntries(transaction: PersistenceTransaction, documents: DocumentMap): PersistencePromise; +} +/** + * Internal implementation of the collection-parent index exposed by MemoryIndexManager. + * Also used for in-memory caching by IndexedDbIndexManager and initial index population + * in indexeddb_schema.ts + */ +export declare class MemoryCollectionParentIndex { + private index; + add(collectionPath: ResourcePath): boolean; + has(collectionPath: ResourcePath): boolean; + getEntries(collectionId: string): ResourcePath[]; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_mutation_queue.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_mutation_queue.d.ts new file mode 100644 index 0000000..ad685f9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_mutation_queue.d.ts @@ -0,0 +1,80 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Query } from '../core/query'; +import { BatchId } from '../core/types'; +import { Timestamp } from '../lite-api/timestamp'; +import { DocumentKey } from '../model/document_key'; +import { Mutation } from '../model/mutation'; +import { MutationBatch } from '../model/mutation_batch'; +import { SortedMap } from '../util/sorted_map'; +import { IndexManager } from './index_manager'; +import { MutationQueue } from './mutation_queue'; +import { ReferenceDelegate } from './persistence'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +export declare class MemoryMutationQueue implements MutationQueue { + private readonly indexManager; + private readonly referenceDelegate; + /** + * The set of all mutations that have been sent but not yet been applied to + * the backend. + */ + private mutationQueue; + /** Next value to use when assigning sequential IDs to each mutation batch. */ + private nextBatchId; + /** An ordered mapping between documents and the mutations batch IDs. */ + private batchesByDocumentKey; + constructor(indexManager: IndexManager, referenceDelegate: ReferenceDelegate); + checkEmpty(transaction: PersistenceTransaction): PersistencePromise; + addMutationBatch(transaction: PersistenceTransaction, localWriteTime: Timestamp, baseMutations: Mutation[], mutations: Mutation[]): PersistencePromise; + lookupMutationBatch(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + getNextMutationBatchAfterBatchId(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + getHighestUnacknowledgedBatchId(): PersistencePromise; + getAllMutationBatches(transaction: PersistenceTransaction): PersistencePromise; + getAllMutationBatchesAffectingDocumentKey(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + getAllMutationBatchesAffectingDocumentKeys(transaction: PersistenceTransaction, documentKeys: SortedMap): PersistencePromise; + getAllMutationBatchesAffectingQuery(transaction: PersistenceTransaction, query: Query): PersistencePromise; + private findMutationBatches; + removeMutationBatch(transaction: PersistenceTransaction, batch: MutationBatch): PersistencePromise; + removeCachedMutationKeys(batchId: BatchId): void; + containsKey(txn: PersistenceTransaction, key: DocumentKey): PersistencePromise; + performConsistencyCheck(txn: PersistenceTransaction): PersistencePromise; + /** + * Finds the index of the given batchId in the mutation queue and asserts that + * the resulting index is within the bounds of the queue. + * + * @param batchId - The batchId to search for + * @param action - A description of what the caller is doing, phrased in passive + * form (e.g. "acknowledged" in a routine that acknowledges batches). + */ + private indexOfExistingBatchId; + /** + * Finds the index of the given batchId in the mutation queue. This operation + * is O(1). + * + * @returns The computed index of the batch with the given batchId, based on + * the state of the queue. Note this index can be negative if the requested + * batchId has already been removed from the queue or past the end of the + * queue if the batchId is larger than the last added batch. + */ + private indexOfBatchId; + /** + * A version of lookupMutationBatch that doesn't return a promise, this makes + * other functions that uses this code easier to read and more efficient. + */ + private findMutationBatch; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_persistence.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_persistence.d.ts new file mode 100644 index 0000000..051c94b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_persistence.d.ts @@ -0,0 +1,134 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { ListenSequenceNumber, TargetId } from '../core/types'; +import { Document } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { JsonProtoSerializer } from '../remote/serializer'; +import { DocumentOverlayCache } from './document_overlay_cache'; +import { GlobalsCache } from './globals_cache'; +import { IndexManager } from './index_manager'; +import { ActiveTargets, LruDelegate, LruGarbageCollector, LruParams } from './lru_garbage_collector'; +import { MemoryBundleCache } from './memory_bundle_cache'; +import { MemoryIndexManager } from './memory_index_manager'; +import { MemoryRemoteDocumentCache } from './memory_remote_document_cache'; +import { MemoryTargetCache } from './memory_target_cache'; +import { MutationQueue } from './mutation_queue'; +import { Persistence, ReferenceDelegate } from './persistence'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction, PersistenceTransactionMode } from './persistence_transaction'; +import { TargetData } from './target_data'; +/** + * A memory-backed instance of Persistence. Data is stored only in RAM and + * not persisted across sessions. + */ +export declare class MemoryPersistence implements Persistence { + /** + * Note that these are retained here to make it easier to write tests + * affecting both the in-memory and IndexedDB-backed persistence layers. Tests + * can create a new LocalStore wrapping this Persistence instance and this + * will make the in-memory persistence layer behave as if it were actually + * persisting values. + */ + private readonly indexManager; + private readonly globalsCache; + private mutationQueues; + private overlays; + private readonly remoteDocumentCache; + private readonly targetCache; + private readonly bundleCache; + private readonly listenSequence; + private serializer; + private _started; + readonly referenceDelegate: MemoryReferenceDelegate; + /** + * The constructor accepts a factory for creating a reference delegate. This + * allows both the delegate and this instance to have strong references to + * each other without having nullable fields that would then need to be + * checked or asserted on every access. + */ + constructor(referenceDelegateFactory: (p: MemoryPersistence) => MemoryReferenceDelegate, serializer: JsonProtoSerializer); + start(): Promise; + shutdown(): Promise; + get started(): boolean; + setDatabaseDeletedListener(): void; + setNetworkEnabled(): void; + getIndexManager(user: User): MemoryIndexManager; + getDocumentOverlayCache(user: User): DocumentOverlayCache; + getMutationQueue(user: User, indexManager: IndexManager): MutationQueue; + getGlobalsCache(): GlobalsCache; + getTargetCache(): MemoryTargetCache; + getRemoteDocumentCache(): MemoryRemoteDocumentCache; + getBundleCache(): MemoryBundleCache; + runTransaction(action: string, mode: PersistenceTransactionMode, transactionOperation: (transaction: PersistenceTransaction) => PersistencePromise): Promise; + mutationQueuesContainKey(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; +} +/** + * Memory persistence is not actually transactional, but future implementations + * may have transaction-scoped state. + */ +export declare class MemoryTransaction extends PersistenceTransaction { + readonly currentSequenceNumber: ListenSequenceNumber; + constructor(currentSequenceNumber: ListenSequenceNumber); +} +export interface MemoryReferenceDelegate extends ReferenceDelegate { + documentSize(doc: Document): number; + onTransactionStarted(): void; + onTransactionCommitted(txn: PersistenceTransaction): PersistencePromise; +} +export declare class MemoryEagerDelegate implements MemoryReferenceDelegate { + private readonly persistence; + /** Tracks all documents that are active in Query views. */ + private localViewReferences; + /** The list of documents that are potentially GCed after each transaction. */ + private _orphanedDocuments; + private constructor(); + static factory(persistence: MemoryPersistence): MemoryEagerDelegate; + private get orphanedDocuments(); + addReference(txn: PersistenceTransaction, targetId: TargetId, key: DocumentKey): PersistencePromise; + removeReference(txn: PersistenceTransaction, targetId: TargetId, key: DocumentKey): PersistencePromise; + markPotentiallyOrphaned(txn: PersistenceTransaction, key: DocumentKey): PersistencePromise; + removeTarget(txn: PersistenceTransaction, targetData: TargetData): PersistencePromise; + onTransactionStarted(): void; + onTransactionCommitted(txn: PersistenceTransaction): PersistencePromise; + updateLimboDocument(txn: PersistenceTransaction, key: DocumentKey): PersistencePromise; + documentSize(doc: Document): number; + private isReferenced; +} +export declare class MemoryLruDelegate implements ReferenceDelegate, LruDelegate { + private readonly persistence; + private orphanedSequenceNumbers; + readonly garbageCollector: LruGarbageCollector; + constructor(persistence: MemoryPersistence, lruParams: LruParams); + static factory(persistence: MemoryPersistence, lruParams: LruParams): MemoryLruDelegate; + onTransactionStarted(): void; + onTransactionCommitted(txn: PersistenceTransaction): PersistencePromise; + forEachTarget(txn: PersistenceTransaction, f: (q: TargetData) => void): PersistencePromise; + getSequenceNumberCount(txn: PersistenceTransaction): PersistencePromise; + private orphanedDocumentCount; + forEachOrphanedDocumentSequenceNumber(txn: PersistenceTransaction, f: (sequenceNumber: ListenSequenceNumber) => void): PersistencePromise; + removeTargets(txn: PersistenceTransaction, upperBound: ListenSequenceNumber, activeTargetIds: ActiveTargets): PersistencePromise; + removeOrphanedDocuments(txn: PersistenceTransaction, upperBound: ListenSequenceNumber): PersistencePromise; + markPotentiallyOrphaned(txn: PersistenceTransaction, key: DocumentKey): PersistencePromise; + removeTarget(txn: PersistenceTransaction, targetData: TargetData): PersistencePromise; + addReference(txn: PersistenceTransaction, targetId: TargetId, key: DocumentKey): PersistencePromise; + removeReference(txn: PersistenceTransaction, targetId: TargetId, key: DocumentKey): PersistencePromise; + updateLimboDocument(txn: PersistenceTransaction, key: DocumentKey): PersistencePromise; + documentSize(document: Document): number; + private isPinned; + getCacheSize(txn: PersistenceTransaction): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_remote_document_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_remote_document_cache.d.ts new file mode 100644 index 0000000..7752914 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_remote_document_cache.d.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Document } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +import { RemoteDocumentCache } from './remote_document_cache'; +export type DocumentSizer = (doc: Document) => number; +export interface MemoryRemoteDocumentCache extends RemoteDocumentCache { + forEachDocumentKey(transaction: PersistenceTransaction, f: (key: DocumentKey) => PersistencePromise): PersistencePromise; +} +/** + * Creates a new memory-only RemoteDocumentCache. + * + * @param sizer - Used to assess the size of a document. For eager GC, this is + * expected to just return 0 to avoid unnecessarily doing the work of + * calculating the size. + */ +export declare function newMemoryRemoteDocumentCache(sizer: DocumentSizer): MemoryRemoteDocumentCache; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_target_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_target_cache.d.ts new file mode 100644 index 0000000..4539d62 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/memory_target_cache.d.ts @@ -0,0 +1,65 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { Target } from '../core/target'; +import { ListenSequenceNumber, TargetId } from '../core/types'; +import { DocumentKeySet } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { ActiveTargets } from './lru_garbage_collector'; +import { Persistence } from './persistence'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +import { TargetCache } from './target_cache'; +import { TargetData } from './target_data'; +export declare class MemoryTargetCache implements TargetCache { + private readonly persistence; + /** + * Maps a target to the data about that target + */ + private targets; + /** The last received snapshot version. */ + private lastRemoteSnapshotVersion; + /** The highest numbered target ID encountered. */ + private highestTargetId; + /** The highest sequence number encountered. */ + private highestSequenceNumber; + /** + * A ordered bidirectional mapping between documents and the remote target + * IDs. + */ + private references; + private targetCount; + private targetIdGenerator; + constructor(persistence: Persistence); + forEachTarget(txn: PersistenceTransaction, f: (q: TargetData) => void): PersistencePromise; + getLastRemoteSnapshotVersion(transaction: PersistenceTransaction): PersistencePromise; + getHighestSequenceNumber(transaction: PersistenceTransaction): PersistencePromise; + allocateTargetId(transaction: PersistenceTransaction): PersistencePromise; + setTargetsMetadata(transaction: PersistenceTransaction, highestListenSequenceNumber: number, lastRemoteSnapshotVersion?: SnapshotVersion): PersistencePromise; + private saveTargetData; + addTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + updateTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + removeTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + removeTargets(transaction: PersistenceTransaction, upperBound: ListenSequenceNumber, activeTargetIds: ActiveTargets): PersistencePromise; + getTargetCount(transaction: PersistenceTransaction): PersistencePromise; + getTargetData(transaction: PersistenceTransaction, target: Target): PersistencePromise; + addMatchingKeys(txn: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + removeMatchingKeys(txn: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + removeMatchingKeysForTargetId(txn: PersistenceTransaction, targetId: TargetId): PersistencePromise; + getMatchingKeysForTargetId(txn: PersistenceTransaction, targetId: TargetId): PersistencePromise; + containsKey(txn: PersistenceTransaction, key: DocumentKey): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/mutation_queue.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/mutation_queue.d.ts new file mode 100644 index 0000000..2f7b2dd --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/mutation_queue.d.ts @@ -0,0 +1,123 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Query } from '../core/query'; +import { BatchId } from '../core/types'; +import { Timestamp } from '../lite-api/timestamp'; +import { DocumentKey } from '../model/document_key'; +import { Mutation } from '../model/mutation'; +import { MutationBatch } from '../model/mutation_batch'; +import { SortedMap } from '../util/sorted_map'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** A queue of mutations to apply to the remote store. */ +export interface MutationQueue { + /** Returns true if this queue contains no mutation batches. */ + checkEmpty(transaction: PersistenceTransaction): PersistencePromise; + /** + * Creates a new mutation batch and adds it to this mutation queue. + * + * @param transaction - The transaction this operation is scoped to. + * @param localWriteTime - The original write time of this mutation. + * @param baseMutations - Mutations that are used to populate the base values + * when this mutation is applied locally. These mutations are used to locally + * overwrite values that are persisted in the remote document cache. + * @param mutations - The user-provided mutations in this mutation batch. + */ + addMutationBatch(transaction: PersistenceTransaction, localWriteTime: Timestamp, baseMutations: Mutation[], mutations: Mutation[]): PersistencePromise; + /** + * Loads the mutation batch with the given batchId. + */ + lookupMutationBatch(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + /** + * Gets the first unacknowledged mutation batch after the passed in batchId + * in the mutation queue or null if empty. + * + * @param batchId - The batch to search after, or BATCHID_UNKNOWN for the + * first mutation in the queue. + * + * @returns the next mutation or null if there wasn't one. + */ + getNextMutationBatchAfterBatchId(transaction: PersistenceTransaction, batchId: BatchId): PersistencePromise; + /** + * Gets the largest (latest) batch id in mutation queue for the current user + * that is pending server response, returns `BATCHID_UNKNOWN` if the queue is + * empty. + * + * @returns the largest batch id in the mutation queue that is not + * acknowledged. + */ + getHighestUnacknowledgedBatchId(transaction: PersistenceTransaction): PersistencePromise; + /** Gets all mutation batches in the mutation queue. */ + getAllMutationBatches(transaction: PersistenceTransaction): PersistencePromise; + /** + * Finds all mutation batches that could possibly affect the given + * document key. Not all mutations in a batch will necessarily affect the + * document key, so when looping through the batch you'll need to check that + * the mutation itself matches the key. + * + * Batches are guaranteed to be in sorted order. + * + * Note that because of this requirement implementations are free to return + * mutation batches that don't contain the document key at all if it's + * convenient. + */ + getAllMutationBatchesAffectingDocumentKey(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + /** + * Finds all mutation batches that could possibly affect the given set of + * document keys. Not all mutations in a batch will necessarily affect each + * key, so when looping through the batch you'll need to check that the + * mutation itself matches the key. + * + * Batches are guaranteed to be in sorted order. + * + * Note that because of this requirement implementations are free to return + * mutation batches that don't contain any of the document keys at all if it's + * convenient. + */ + getAllMutationBatchesAffectingDocumentKeys(transaction: PersistenceTransaction, documentKeys: SortedMap): PersistencePromise; + /** + * Finds all mutation batches that could affect the results for the given + * query. Not all mutations in a batch will necessarily affect the query, so + * when looping through the batch you'll need to check that the mutation + * itself matches the query. + * + * Batches are guaranteed to be in sorted order. + * + * Note that because of this requirement implementations are free to return + * mutation batches that don't match the query at all if it's convenient. + * + * NOTE: A PatchMutation does not need to include all fields in the query + * filter criteria in order to be a match (but any fields it does contain do + * need to match). + */ + getAllMutationBatchesAffectingQuery(transaction: PersistenceTransaction, query: Query): PersistencePromise; + /** + * Removes the given mutation batch from the queue. This is useful in two + * circumstances: + * + * + Removing an applied mutation from the head of the queue + * + Removing a rejected mutation from anywhere in the queue + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMutationBatch(transaction: PersistenceTransaction, batch: MutationBatch): PersistencePromise; + /** + * Performs a consistency check, examining the mutation queue for any + * leaks, if possible. + */ + performConsistencyCheck(transaction: PersistenceTransaction): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/overlayed_document.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/overlayed_document.d.ts new file mode 100644 index 0000000..56a3286 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/overlayed_document.d.ts @@ -0,0 +1,40 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Document } from '../model/document'; +import { FieldMask } from '../model/field_mask'; +/** + * Represents a local view (overlay) of a document, and the fields that are + * locally mutated. + */ +export declare class OverlayedDocument { + readonly overlayedDocument: Document; + /** + * The fields that are locally mutated by patch mutations. + * + * If the overlayed document is from set or delete mutations, this is `null`. + * If there is no overlay (mutation) for the document, this is an empty `FieldMask`. + */ + readonly mutatedFields: FieldMask | null; + constructor(overlayedDocument: Document, + /** + * The fields that are locally mutated by patch mutations. + * + * If the overlayed document is from set or delete mutations, this is `null`. + * If there is no overlay (mutation) for the document, this is an empty `FieldMask`. + */ + mutatedFields: FieldMask | null); +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/persistence.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/persistence.d.ts new file mode 100644 index 0000000..0360173 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/persistence.d.ts @@ -0,0 +1,217 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { TargetId } from '../core/types'; +import { DocumentKey } from '../model/document_key'; +import { BundleCache } from './bundle_cache'; +import { DocumentOverlayCache } from './document_overlay_cache'; +import { GlobalsCache } from './globals_cache'; +import { IndexManager } from './index_manager'; +import { MutationQueue } from './mutation_queue'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction, PersistenceTransactionMode } from './persistence_transaction'; +import { RemoteDocumentCache } from './remote_document_cache'; +import { TargetCache } from './target_cache'; +import { TargetData } from './target_data'; +/** + * Callback type for primary state notifications. This callback can be + * registered with the persistence layer to get notified when we transition from + * primary to secondary state and vice versa. + * + * Note: Instances can only toggle between Primary and Secondary state if + * IndexedDB persistence is enabled and multiple clients are active. If this + * listener is registered with MemoryPersistence, the callback will be called + * exactly once marking the current instance as Primary. + */ +export type PrimaryStateListener = (isPrimary: boolean) => Promise; +/** + * A ReferenceDelegate instance handles all of the hooks into the document-reference lifecycle. This + * includes being added to a target, being removed from a target, being subject to mutation, and + * being mutated by the user. + * + * Different implementations may do different things with each of these events. Not every + * implementation needs to do something with every lifecycle hook. + * + * PORTING NOTE: since sequence numbers are attached to transactions in this + * client, the ReferenceDelegate does not need to deal in transactional + * semantics (onTransactionStarted/Committed()), nor does it need to track and + * generate sequence numbers (getCurrentSequenceNumber()). + */ +export interface ReferenceDelegate { + /** Notify the delegate that the given document was added to a target. */ + addReference(txn: PersistenceTransaction, targetId: TargetId, doc: DocumentKey): PersistencePromise; + /** Notify the delegate that the given document was removed from a target. */ + removeReference(txn: PersistenceTransaction, targetId: TargetId, doc: DocumentKey): PersistencePromise; + /** + * Notify the delegate that a target was removed. The delegate may, but is not obligated to, + * actually delete the target and associated data. + */ + removeTarget(txn: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Notify the delegate that a document may no longer be part of any views or + * have any mutations associated. + */ + markPotentiallyOrphaned(txn: PersistenceTransaction, doc: DocumentKey): PersistencePromise; + /** Notify the delegate that a limbo document was updated. */ + updateLimboDocument(txn: PersistenceTransaction, doc: DocumentKey): PersistencePromise; +} +/** + * Persistence is the lowest-level shared interface to persistent storage in + * Firestore. + * + * Persistence is used to create MutationQueue and RemoteDocumentCache + * instances backed by persistence (which might be in-memory or LevelDB). + * + * Persistence also exposes an API to create and run PersistenceTransactions + * against persistence. All read / write operations must be wrapped in a + * transaction. Implementations of PersistenceTransaction / Persistence only + * need to guarantee that writes made against the transaction are not made to + * durable storage until the transaction resolves its PersistencePromise. + * Since memory-only storage components do not alter durable storage, they are + * free to ignore the transaction. + * + * This contract is enough to allow the LocalStore be be written + * independently of whether or not the stored state actually is durably + * persisted. If persistent storage is enabled, writes are grouped together to + * avoid inconsistent state that could cause crashes. + * + * Concretely, when persistent storage is enabled, the persistent versions of + * MutationQueue, RemoteDocumentCache, and others (the mutators) will + * defer their writes into a transaction. Once the local store has completed + * one logical operation, it commits the transaction. + * + * When persistent storage is disabled, the non-persistent versions of the + * mutators ignore the transaction. This short-cut is allowed because + * memory-only storage leaves no state so it cannot be inconsistent. + * + * This simplifies the implementations of the mutators and allows memory-only + * implementations to supplement the persistent ones without requiring any + * special dual-store implementation of Persistence. The cost is that the + * LocalStore needs to be slightly careful about the order of its reads and + * writes in order to avoid relying on being able to read back uncommitted + * writes. + */ +export interface Persistence { + /** + * Whether or not this persistence instance has been started. + */ + readonly started: boolean; + readonly referenceDelegate: ReferenceDelegate; + /** Starts persistence. */ + start(): Promise; + /** + * Releases any resources held during eager shutdown. + */ + shutdown(): Promise; + /** + * Registers a listener that gets called when the database receives a + * version change event indicating that it has deleted. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setDatabaseDeletedListener(databaseDeletedListener: () => Promise): void; + /** + * Adjusts the current network state in the client's metadata, potentially + * affecting the primary lease. + * + * PORTING NOTE: This is only used for Web multi-tab. + */ + setNetworkEnabled(networkEnabled: boolean): void; + /** + * Returns GlobalCache representing a general purpose cache for global values. + */ + getGlobalsCache(): GlobalsCache; + /** + * Returns a MutationQueue representing the persisted mutations for the + * given user. + * + * Note: The implementation is free to return the same instance every time + * this is called for a given user. In particular, the memory-backed + * implementation does this to emulate the persisted implementation to the + * extent possible (e.g. in the case of uid switching from + * sally=>jack=>sally, sally's mutation queue will be preserved). + */ + getMutationQueue(user: User, indexManager: IndexManager): MutationQueue; + /** + * Returns a TargetCache representing the persisted cache of targets. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getTargetCache(): TargetCache; + /** + * Returns a RemoteDocumentCache representing the persisted cache of remote + * documents. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getRemoteDocumentCache(): RemoteDocumentCache; + /** + * Returns a BundleCache representing the persisted cache of loaded bundles. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getBundleCache(): BundleCache; + /** + * Returns an IndexManager instance that manages our persisted query indexes. + * + * Note: The implementation is free to return the same instance every time + * this is called. In particular, the memory-backed implementation does this + * to emulate the persisted implementation to the extent possible. + */ + getIndexManager(user: User): IndexManager; + /** + * Returns a DocumentOverlayCache representing the documents that are mutated + * locally. + */ + getDocumentOverlayCache(user: User): DocumentOverlayCache; + /** + * Performs an operation inside a persistence transaction. Any reads or writes + * against persistence must be performed within a transaction. Writes will be + * committed atomically once the transaction completes. + * + * Persistence operations are asynchronous and therefore the provided + * transactionOperation must return a PersistencePromise. When it is resolved, + * the transaction will be committed and the Promise returned by this method + * will resolve. + * + * @param action - A description of the action performed by this transaction, + * used for logging. + * @param mode - The underlying mode of the IndexedDb transaction. Can be + * 'readonly', 'readwrite' or 'readwrite-primary'. Transactions marked + * 'readwrite-primary' can only be executed by the primary client. In this + * mode, the transactionOperation will not be run if the primary lease cannot + * be acquired and the returned promise will be rejected with a + * FAILED_PRECONDITION error. + * @param transactionOperation - The operation to run inside a transaction. + * @returns A `Promise` that is resolved once the transaction completes. + */ + runTransaction(action: string, mode: PersistenceTransactionMode, transactionOperation: (transaction: PersistenceTransaction) => PersistencePromise): Promise; +} +/** + * Interface to schedule periodic tasks within SDK. + */ +export interface Scheduler { + readonly started: boolean; + start(): void; + stop(): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/persistence_promise.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/persistence_promise.d.ts new file mode 100644 index 0000000..3803123 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/persistence_promise.d.ts @@ -0,0 +1,83 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export type FulfilledHandler = ((result: T) => R | PersistencePromise) | null; +export type RejectedHandler = ((reason: Error) => R | PersistencePromise) | null; +export type Resolver = (value?: T) => void; +export type Rejector = (error: Error) => void; +/** + * PersistencePromise is essentially a re-implementation of Promise except + * it has a .next() method instead of .then() and .next() and .catch() callbacks + * are executed synchronously when a PersistencePromise resolves rather than + * asynchronously (Promise implementations use setImmediate() or similar). + * + * This is necessary to interoperate with IndexedDB which will automatically + * commit transactions if control is returned to the event loop without + * synchronously initiating another operation on the transaction. + * + * NOTE: .then() and .catch() only allow a single consumer, unlike normal + * Promises. + */ +export declare class PersistencePromise { + private nextCallback; + private catchCallback; + private result; + private error; + private isDone; + private callbackAttached; + constructor(callback: (resolve: Resolver, reject: Rejector) => void); + catch(fn: (error: Error) => R | PersistencePromise): PersistencePromise; + next(nextFn?: FulfilledHandler, catchFn?: RejectedHandler): PersistencePromise; + toPromise(): Promise; + private wrapUserFunction; + private wrapSuccess; + private wrapFailure; + static resolve(): PersistencePromise; + static resolve(result: R): PersistencePromise; + static reject(error: Error): PersistencePromise; + static waitFor(all: { + forEach: (cb: (el: PersistencePromise) => void) => void; + }): PersistencePromise; + /** + * Given an array of predicate functions that asynchronously evaluate to a + * boolean, implements a short-circuiting `or` between the results. Predicates + * will be evaluated until one of them returns `true`, then stop. The final + * result will be whether any of them returned `true`. + */ + static or(predicates: Array<() => PersistencePromise>): PersistencePromise; + /** + * Given an iterable, call the given function on each element in the + * collection and wait for all of the resulting concurrent PersistencePromises + * to resolve. + */ + static forEach(collection: { + forEach: (cb: (r: R, s: S) => void) => void; + }, f: ((r: R, s: S) => PersistencePromise) | ((r: R) => PersistencePromise)): PersistencePromise; + static forEach(collection: { + forEach: (cb: (r: R) => void) => void; + }, f: (r: R) => PersistencePromise): PersistencePromise; + /** + * Concurrently map all array elements through asynchronous function. + */ + static mapArray(array: T[], f: (t: T) => PersistencePromise): PersistencePromise; + /** + * An alternative to recursive PersistencePromise calls, that avoids + * potential memory problems from unbounded chains of promises. + * + * The `action` will be called repeatedly while `condition` is true. + */ + static doWhile(condition: () => boolean, action: () => PersistencePromise): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/persistence_transaction.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/persistence_transaction.d.ts new file mode 100644 index 0000000..d4da8b6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/persistence_transaction.d.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ListenSequenceNumber } from '../core/types'; +export declare const PRIMARY_LEASE_LOST_ERROR_MSG: string; +/** The different modes supported by `Persistence.runTransaction()`. */ +export type PersistenceTransactionMode = 'readonly' | 'readwrite' | 'readwrite-primary'; +/** + * A base class representing a persistence transaction, encapsulating both the + * transaction's sequence numbers as well as a list of onCommitted listeners. + * + * When you call Persistence.runTransaction(), it will create a transaction and + * pass it to your callback. You then pass it to any method that operates + * on persistence. + */ +export declare abstract class PersistenceTransaction { + private readonly onCommittedListeners; + abstract readonly currentSequenceNumber: ListenSequenceNumber; + addOnCommittedListener(listener: () => void): void; + raiseOnCommittedEvent(): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/query_context.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/query_context.d.ts new file mode 100644 index 0000000..aeff2fa --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/query_context.d.ts @@ -0,0 +1,28 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A tracker to keep a record of important details during database local query + * execution. + */ +export declare class QueryContext { + /** + * Counts the number of documents passed through during local query execution. + */ + private _documentReadCount; + get documentReadCount(): number; + incrementDocumentReadCount(amount: number): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/query_engine.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/query_engine.d.ts new file mode 100644 index 0000000..58148f1 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/query_engine.d.ts @@ -0,0 +1,110 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Query } from '../core/query'; +import { SnapshotVersion } from '../core/snapshot_version'; +import { DocumentKeySet, DocumentMap } from '../model/collections'; +import { IndexManager } from './index_manager'; +import { LocalDocumentsView } from './local_documents_view'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +import { QueryContext } from './query_context'; +/** + * The Firestore query engine. + * + * Firestore queries can be executed in three modes. The Query Engine determines + * what mode to use based on what data is persisted. The mode only determines + * the runtime complexity of the query - the result set is equivalent across all + * implementations. + * + * The Query engine will use indexed-based execution if a user has configured + * any index that can be used to execute query (via `setIndexConfiguration()`). + * Otherwise, the engine will try to optimize the query by re-using a previously + * persisted query result. If that is not possible, the query will be executed + * via a full collection scan. + * + * Index-based execution is the default when available. The query engine + * supports partial indexed execution and merges the result from the index + * lookup with documents that have not yet been indexed. The index evaluation + * matches the backend's format and as such, the SDK can use indexing for all + * queries that the backend supports. + * + * If no index exists, the query engine tries to take advantage of the target + * document mapping in the TargetCache. These mappings exists for all queries + * that have been synced with the backend at least once and allow the query + * engine to only read documents that previously matched a query plus any + * documents that were edited after the query was last listened to. + * + * There are some cases when this optimization is not guaranteed to produce + * the same results as full collection scans. In these cases, query + * processing falls back to full scans. These cases are: + * + * - Limit queries where a document that matched the query previously no longer + * matches the query. + * + * - Limit queries where a document edit may cause the document to sort below + * another document that is in the local cache. + * + * - Queries that have never been CURRENT or free of limbo documents. + */ +export declare class QueryEngine { + private localDocumentsView; + private indexManager; + private initialized; + indexAutoCreationEnabled: boolean; + /** + * SDK only decides whether it should create index when collection size is + * larger than this. + */ + indexAutoCreationMinCollectionSize: number; + relativeIndexReadCostPerDocument: number; + /** Sets the document view to query against. */ + initialize(localDocuments: LocalDocumentsView, indexManager: IndexManager): void; + /** Returns all local documents matching the specified query. */ + getDocumentsMatchingQuery(transaction: PersistenceTransaction, query: Query, lastLimboFreeSnapshotVersion: SnapshotVersion, remoteKeys: DocumentKeySet): PersistencePromise; + createCacheIndexes(transaction: PersistenceTransaction, query: Query, context: QueryContext, resultSize: number): PersistencePromise; + /** + * Performs an indexed query that evaluates the query based on a collection's + * persisted index values. Returns `null` if an index is not available. + */ + private performQueryUsingIndex; + /** + * Performs a query based on the target's persisted query mapping. Returns + * `null` if the mapping is not available or cannot be used. + */ + private performQueryUsingRemoteKeys; + /** Applies the query filter and sorting to the provided documents. */ + private applyQuery; + /** + * Determines if a limit query needs to be refilled from cache, making it + * ineligible for index-free execution. + * + * @param query - The query. + * @param sortedPreviousResults - The documents that matched the query when it + * was last synchronized, sorted by the query's comparator. + * @param remoteKeys - The document keys that matched the query at the last + * snapshot. + * @param limboFreeSnapshotVersion - The version of the snapshot when the + * query was last synchronized. + */ + private needsRefill; + private executeFullCollectionScan; + /** + * Combines the results from an indexed execution with the remaining documents + * that have not yet been indexed. + */ + private appendRemainingResults; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/reference_set.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/reference_set.d.ts new file mode 100644 index 0000000..5ff71dc --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/reference_set.d.ts @@ -0,0 +1,68 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BatchId, TargetId } from '../core/types'; +import { DocumentKeySet } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +/** + * A collection of references to a document from some kind of numbered entity + * (either a target ID or batch ID). As references are added to or removed from + * the set corresponding events are emitted to a registered garbage collector. + * + * Each reference is represented by a DocumentReference object. Each of them + * contains enough information to uniquely identify the reference. They are all + * stored primarily in a set sorted by key. A document is considered garbage if + * there's no references in that set (this can be efficiently checked thanks to + * sorting by key). + * + * ReferenceSet also keeps a secondary set that contains references sorted by + * IDs. This one is used to efficiently implement removal of all references by + * some target ID. + */ +export declare class ReferenceSet { + private refsByKey; + private refsByTarget; + /** Returns true if the reference set contains no references. */ + isEmpty(): boolean; + /** Adds a reference to the given document key for the given ID. */ + addReference(key: DocumentKey, id: TargetId | BatchId): void; + /** Add references to the given document keys for the given ID. */ + addReferences(keys: DocumentKeySet, id: TargetId | BatchId): void; + /** + * Removes a reference to the given document key for the given + * ID. + */ + removeReference(key: DocumentKey, id: TargetId | BatchId): void; + removeReferences(keys: DocumentKeySet, id: TargetId | BatchId): void; + /** + * Clears all references with a given ID. Calls removeRef() for each key + * removed. + */ + removeReferencesForId(id: TargetId | BatchId): DocumentKey[]; + removeAllReferences(): void; + private removeRef; + referencesForId(id: TargetId | BatchId): DocumentKeySet; + containsKey(key: DocumentKey): boolean; +} +export declare class DocReference { + key: DocumentKey; + targetOrBatchId: TargetId | BatchId; + constructor(key: DocumentKey, targetOrBatchId: TargetId | BatchId); + /** Compare by key then by ID */ + static compareByKey(left: DocReference, right: DocReference): number; + /** Compare by ID then by key */ + static compareByTargetId(left: DocReference, right: DocReference): number; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/remote_document_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/remote_document_cache.d.ts new file mode 100644 index 0000000..abb9f3b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/remote_document_cache.d.ts @@ -0,0 +1,91 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Query } from '../core/query'; +import { DocumentKeySet, MutableDocumentMap, OverlayMap } from '../model/collections'; +import { MutableDocument } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { IndexOffset } from '../model/field_index'; +import { IndexManager } from './index_manager'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +import { QueryContext } from './query_context'; +import { RemoteDocumentChangeBuffer } from './remote_document_change_buffer'; +/** + * Represents cached documents received from the remote backend. + * + * The cache is keyed by DocumentKey and entries in the cache are + * MutableDocuments, meaning we can cache both actual documents as well as + * documents that are known to not exist. + */ +export interface RemoteDocumentCache { + /** Sets the index manager to use for managing the collectionGroup index. */ + setIndexManager(indexManager: IndexManager): void; + /** + * Looks up an entry in the cache. + * + * @param documentKey - The key of the entry to look up.* + * @returns The cached document entry. Returns an invalid document if the + * document is not cached. + */ + getEntry(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + /** + * Looks up a set of entries in the cache. + * + * @param documentKeys - The keys of the entries to look up. + * @returns The cached document entries indexed by key. If an entry is not + * cached, the corresponding key will be mapped to an invalid document. + */ + getEntries(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise; + /** + * Returns the documents matching the given query + * + * @param query - The query to match documents against. + * @param offset - The offset to start the scan at (exclusive). + * @param context - A optional tracker to keep a record of important details + * during database local query execution. + * @returns The set of matching documents. + */ + getDocumentsMatchingQuery(transaction: PersistenceTransaction, query: Query, offset: IndexOffset, mutatedDocs: OverlayMap, context?: QueryContext): PersistencePromise; + /** + * Looks up the next `limit` documents for a collection group based on the + * provided offset. The ordering is based on the document's read time and key. + * + * @param collectionGroup - The collection group to scan. + * @param offset - The offset to start the scan at (exclusive). + * @param limit - The maximum number of results to return. + * @returns The set of matching documents. + */ + getAllFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset, limit: number): PersistencePromise; + /** + * Provides access to add or update the contents of the cache. The buffer + * handles proper size accounting for the change. + * + * Multi-Tab Note: This should only be called by the primary client. + * + * @param options - Specify `trackRemovals` to create sentinel entries for + * removed documents, which allows removals to be tracked by + * `getNewDocumentChanges()`. + */ + newChangeBuffer(options?: { + trackRemovals: boolean; + }): RemoteDocumentChangeBuffer; + /** + * Get an estimate of the size of the document cache. Note that for eager + * garbage collection, we don't track sizes so this will return 0. + */ + getSize(transaction: PersistenceTransaction): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/remote_document_change_buffer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/remote_document_change_buffer.d.ts new file mode 100644 index 0000000..3b8a1fa --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/remote_document_change_buffer.d.ts @@ -0,0 +1,88 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { DocumentKeySet, MutableDocumentMap } from '../model/collections'; +import { MutableDocument } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { ObjectMap } from '../util/obj_map'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +/** + * An in-memory buffer of entries to be written to a RemoteDocumentCache. + * It can be used to batch up a set of changes to be written to the cache, but + * additionally supports reading entries back with the `getEntry()` method, + * falling back to the underlying RemoteDocumentCache if no entry is + * buffered. + * + * Entries added to the cache *must* be read first. This is to facilitate + * calculating the size delta of the pending changes. + * + * PORTING NOTE: This class was implemented then removed from other platforms. + * If byte-counting ends up being needed on the other platforms, consider + * porting this class as part of that implementation work. + */ +export declare abstract class RemoteDocumentChangeBuffer { + protected changes: ObjectMap; + private changesApplied; + protected abstract getFromCache(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + protected abstract getAllFromCache(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise; + protected abstract applyChanges(transaction: PersistenceTransaction): PersistencePromise; + /** + * Buffers a `RemoteDocumentCache.addEntry()` call. + * + * You can only modify documents that have already been retrieved via + * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). + */ + addEntry(document: MutableDocument): void; + /** + * Buffers a `RemoteDocumentCache.removeEntry()` call. + * + * You can only remove documents that have already been retrieved via + * `getEntry()/getEntries()` (enforced via IndexedDbs `apply()`). + */ + removeEntry(key: DocumentKey, readTime: SnapshotVersion): void; + /** + * Looks up an entry in the cache. The buffered changes will first be checked, + * and if no buffered change applies, this will forward to + * `RemoteDocumentCache.getEntry()`. + * + * @param transaction - The transaction in which to perform any persistence + * operations. + * @param documentKey - The key of the entry to look up. + * @returns The cached document or an invalid document if we have nothing + * cached. + */ + getEntry(transaction: PersistenceTransaction, documentKey: DocumentKey): PersistencePromise; + /** + * Looks up several entries in the cache, forwarding to + * `RemoteDocumentCache.getEntry()`. + * + * @param transaction - The transaction in which to perform any persistence + * operations. + * @param documentKeys - The keys of the entries to look up. + * @returns A map of cached documents, indexed by key. If an entry cannot be + * found, the corresponding key will be mapped to an invalid document. + */ + getEntries(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise; + /** + * Applies buffered changes to the underlying RemoteDocumentCache, using + * the provided transaction. + */ + apply(transaction: PersistenceTransaction): PersistencePromise; + /** Helper to assert this.changes is not null */ + protected assertNotApplied(): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/shared_client_state.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/shared_client_state.d.ts new file mode 100644 index 0000000..98efa94 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/shared_client_state.d.ts @@ -0,0 +1,312 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { BatchId, ListenSequenceNumber, MutationBatchState, OnlineState, TargetId } from '../core/types'; +import { TargetIdSet } from '../model/collections'; +import { AsyncQueue } from '../util/async_queue'; +import { FirestoreError } from '../util/error'; +import { SortedSet } from '../util/sorted_set'; +import { WindowLike } from '../util/types'; +import { QueryTargetState, SharedClientStateSyncer } from './shared_client_state_syncer'; +/** + * A randomly-generated key assigned to each Firestore instance at startup. + */ +export type ClientId = string; +/** + * A `SharedClientState` keeps track of the global state of the mutations + * and query targets for all active clients with the same persistence key (i.e. + * project ID and FirebaseApp name). It relays local changes to other clients + * and updates its local state as new state is observed. + * + * `SharedClientState` is primarily used for synchronization in Multi-Tab + * environments. Each tab is responsible for registering its active query + * targets and mutations. `SharedClientState` will then notify the listener + * assigned to `.syncEngine` for updates to mutations and queries that + * originated in other clients. + * + * To receive notifications, `.syncEngine` and `.onlineStateHandler` has to be + * assigned before calling `start()`. + */ +export interface SharedClientState { + onlineStateHandler: ((onlineState: OnlineState) => void) | null; + sequenceNumberHandler: ((sequenceNumber: ListenSequenceNumber) => void) | null; + /** Registers the Mutation Batch ID of a newly pending mutation. */ + addPendingMutation(batchId: BatchId): void; + /** + * Records that a pending mutation has been acknowledged or rejected. + * Called by the primary client to notify secondary clients of mutation + * results as they come back from the backend. + */ + updateMutationState(batchId: BatchId, state: 'acknowledged' | 'rejected', error?: FirestoreError): void; + /** + * Associates a new Query Target ID with the local Firestore client. Returns + * the new query state for the query (which can be 'current' if the query is + * already associated with another tab). + * + * If the target id is already associated with local client, the method simply + * returns its `QueryTargetState`. + */ + addLocalQueryTarget(targetId: TargetId, addToActiveTargetIds?: boolean): QueryTargetState; + /** Removes the Query Target ID association from the local client. */ + removeLocalQueryTarget(targetId: TargetId): void; + /** Checks whether the target is associated with the local client. */ + isLocalQueryTarget(targetId: TargetId): boolean; + /** + * Processes an update to a query target. + * + * Called by the primary client to notify secondary clients of document + * changes or state transitions that affect the provided query target. + */ + updateQueryState(targetId: TargetId, state: QueryTargetState, error?: FirestoreError): void; + /** + * Removes the target's metadata entry. + * + * Called by the primary client when all clients stopped listening to a query + * target. + */ + clearQueryState(targetId: TargetId): void; + /** + * Gets the active Query Targets IDs for all active clients. + * + * The implementation for this may require O(n) runtime, where 'n' is the size + * of the result set. + */ + getAllActiveQueryTargets(): SortedSet; + /** + * Checks whether the provided target ID is currently being listened to by + * any of the active clients. + * + * The implementation may require O(n*log m) runtime, where 'n' is the number + * of clients and 'm' the number of targets. + */ + isActiveQueryTarget(targetId: TargetId): boolean; + /** + * Starts the SharedClientState, reads existing client data and registers + * listeners for updates to new and existing clients. + */ + start(): Promise; + /** Shuts down the `SharedClientState` and its listeners. */ + shutdown(): void; + /** + * Changes the active user and removes all existing user-specific data. The + * user change does not call back into SyncEngine (for example, no mutations + * will be marked as removed). + */ + handleUserChange(user: User, removedBatchIds: BatchId[], addedBatchIds: BatchId[]): void; + /** Changes the shared online state of all clients. */ + setOnlineState(onlineState: OnlineState): void; + writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void; + /** + * Notifies other clients when remote documents have changed due to loading + * a bundle. + * + * @param collectionGroups The collection groups affected by this bundle. + */ + notifyBundleLoaded(collectionGroups: Set): void; +} +/** + * Holds the state of a mutation batch, including its user ID, batch ID and + * whether the batch is 'pending', 'acknowledged' or 'rejected'. + */ +export declare class MutationMetadata { + readonly user: User; + readonly batchId: BatchId; + readonly state: MutationBatchState; + readonly error?: FirestoreError | undefined; + constructor(user: User, batchId: BatchId, state: MutationBatchState, error?: FirestoreError | undefined); + /** + * Parses a MutationMetadata from its JSON representation in WebStorage. + * Logs a warning and returns null if the format of the data is not valid. + */ + static fromWebStorageEntry(user: User, batchId: BatchId, value: string): MutationMetadata | null; + toWebStorageJSON(): string; +} +/** + * Holds the state of a query target, including its target ID and whether the + * target is 'not-current', 'current' or 'rejected'. + */ +export declare class QueryTargetMetadata { + readonly targetId: TargetId; + readonly state: QueryTargetState; + readonly error?: FirestoreError | undefined; + constructor(targetId: TargetId, state: QueryTargetState, error?: FirestoreError | undefined); + /** + * Parses a QueryTargetMetadata from its JSON representation in WebStorage. + * Logs a warning and returns null if the format of the data is not valid. + */ + static fromWebStorageEntry(targetId: TargetId, value: string): QueryTargetMetadata | null; + toWebStorageJSON(): string; +} +/** + * Metadata state of a single client denoting the query targets it is actively + * listening to the watch. + */ +export interface ClientState { + readonly activeTargetIds: TargetIdSet; +} +/** + * This class represents the online state for all clients participating in + * multi-tab. The online state is only written to by the primary client, and + * used in secondary clients to update their query views. + */ +export declare class SharedOnlineState { + readonly clientId: string; + readonly onlineState: OnlineState; + constructor(clientId: string, onlineState: OnlineState); + /** + * Parses a SharedOnlineState from its JSON representation in WebStorage. + * Logs a warning and returns null if the format of the data is not valid. + */ + static fromWebStorageEntry(value: string): SharedOnlineState | null; +} +/** + * Metadata state of the local client. Unlike `RemoteClientState`, this class is + * mutable and keeps track of all pending mutations, which allows us to + * update the range of pending mutation batch IDs as new mutations are added or + * removed. + * + * The data in `LocalClientState` is not read from WebStorage and instead + * updated via its instance methods. The updated state can be serialized via + * `toWebStorageJSON()`. + */ +export declare class LocalClientState implements ClientState { + activeTargetIds: SortedSet; + addQueryTarget(targetId: TargetId): void; + removeQueryTarget(targetId: TargetId): void; + /** + * Converts this entry into a JSON-encoded format we can use for WebStorage. + * Does not encode `clientId` as it is part of the key in WebStorage. + */ + toWebStorageJSON(): string; +} +/** + * `WebStorageSharedClientState` uses WebStorage (window.localStorage) as the + * backing store for the SharedClientState. It keeps track of all active + * clients and supports modifications of the local client's data. + */ +export declare class WebStorageSharedClientState implements SharedClientState { + private readonly window; + private readonly queue; + private readonly persistenceKey; + private readonly localClientId; + syncEngine: SharedClientStateSyncer | null; + onlineStateHandler: ((onlineState: OnlineState) => void) | null; + sequenceNumberHandler: ((sequenceNumber: ListenSequenceNumber) => void) | null; + private readonly storage; + private readonly localClientStorageKey; + private readonly sequenceNumberKey; + private readonly storageListener; + private readonly onlineStateKey; + private readonly bundleLoadedKey; + private readonly clientStateKeyRe; + private readonly mutationBatchKeyRe; + private readonly queryTargetKeyRe; + private activeClients; + private started; + private currentUser; + /** + * Captures WebStorage events that occur before `start()` is called. These + * events are replayed once `WebStorageSharedClientState` is started. + */ + private earlyEvents; + constructor(window: WindowLike, queue: AsyncQueue, persistenceKey: string, localClientId: ClientId, initialUser: User); + /** Returns 'true' if WebStorage is available in the current environment. */ + static isAvailable(window: WindowLike | null): window is WindowLike; + start(): Promise; + writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void; + getAllActiveQueryTargets(): TargetIdSet; + isActiveQueryTarget(targetId: TargetId): boolean; + addPendingMutation(batchId: BatchId): void; + updateMutationState(batchId: BatchId, state: 'acknowledged' | 'rejected', error?: FirestoreError): void; + addLocalQueryTarget(targetId: TargetId, addToActiveTargetIds?: boolean): QueryTargetState; + removeLocalQueryTarget(targetId: TargetId): void; + isLocalQueryTarget(targetId: TargetId): boolean; + clearQueryState(targetId: TargetId): void; + updateQueryState(targetId: TargetId, state: QueryTargetState, error?: FirestoreError): void; + handleUserChange(user: User, removedBatchIds: BatchId[], addedBatchIds: BatchId[]): void; + setOnlineState(onlineState: OnlineState): void; + notifyBundleLoaded(collectionGroups: Set): void; + shutdown(): void; + private getItem; + private setItem; + private removeItem; + private handleWebStorageEvent; + private get localClientState(); + private persistClientState; + private persistMutationState; + private removeMutationState; + private persistOnlineState; + private persistQueryTargetState; + private persistBundleLoadedState; + /** + * Parses a client state key in WebStorage. Returns null if the key does not + * match the expected key format. + */ + private fromWebStorageClientStateKey; + /** + * Parses a client state in WebStorage. Returns 'null' if the value could not + * be parsed. + */ + private fromWebStorageClientState; + /** + * Parses a mutation batch state in WebStorage. Returns 'null' if the value + * could not be parsed. + */ + private fromWebStorageMutationMetadata; + /** + * Parses a query target state from WebStorage. Returns 'null' if the value + * could not be parsed. + */ + private fromWebStorageQueryTargetMetadata; + /** + * Parses an online state from WebStorage. Returns 'null' if the value + * could not be parsed. + */ + private fromWebStorageOnlineState; + private fromWebStoreBundleLoadedState; + private handleMutationBatchEvent; + private handleQueryTargetEvent; + private handleClientStateEvent; + private handleOnlineStateEvent; + private extractActiveQueryTargets; +} +/** + * `MemorySharedClientState` is a simple implementation of SharedClientState for + * clients using memory persistence. The state in this class remains fully + * isolated and no synchronization is performed. + */ +export declare class MemorySharedClientState implements SharedClientState { + private localState; + private queryState; + onlineStateHandler: ((onlineState: OnlineState) => void) | null; + sequenceNumberHandler: ((sequenceNumber: ListenSequenceNumber) => void) | null; + addPendingMutation(batchId: BatchId): void; + updateMutationState(batchId: BatchId, state: 'acknowledged' | 'rejected', error?: FirestoreError): void; + addLocalQueryTarget(targetId: TargetId, addToActiveTargetIds?: boolean): QueryTargetState; + updateQueryState(targetId: TargetId, state: QueryTargetState, error?: FirestoreError): void; + removeLocalQueryTarget(targetId: TargetId): void; + isLocalQueryTarget(targetId: TargetId): boolean; + clearQueryState(targetId: TargetId): void; + getAllActiveQueryTargets(): TargetIdSet; + isActiveQueryTarget(targetId: TargetId): boolean; + start(): Promise; + handleUserChange(user: User, removedBatchIds: BatchId[], addedBatchIds: BatchId[]): void; + setOnlineState(onlineState: OnlineState): void; + shutdown(): void; + writeSequenceNumber(sequenceNumber: ListenSequenceNumber): void; + notifyBundleLoaded(collectionGroups: Set): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/shared_client_state_schema.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/shared_client_state_schema.d.ts new file mode 100644 index 0000000..b856116 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/shared_client_state_schema.d.ts @@ -0,0 +1,84 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { BatchId, MutationBatchState, TargetId } from '../core/types'; +import { ClientId } from './shared_client_state'; +import { QueryTargetState } from './shared_client_state_syncer'; +export declare const CLIENT_STATE_KEY_PREFIX = "firestore_clients"; +/** Assembles the key for a client state in WebStorage */ +export declare function createWebStorageClientStateKey(persistenceKey: string, clientId: ClientId): string; +/** + * The JSON representation of a clients's metadata as used during WebStorage + * serialization. The ClientId is omitted here as it is encoded as part of the + * key. + */ +export interface ClientStateSchema { + activeTargetIds: number[]; + updateTimeMs: number; +} +export declare const MUTATION_BATCH_KEY_PREFIX = "firestore_mutations"; +/** Assembles the key for a mutation batch in WebStorage */ +export declare function createWebStorageMutationBatchKey(persistenceKey: string, user: User, batchId: BatchId): string; +/** + * The JSON representation of a mutation batch's metadata as used during + * WebStorage serialization. The UserId and BatchId is omitted as it is + * encoded as part of the key. + */ +export interface MutationMetadataSchema { + state: MutationBatchState; + error?: { + code: string; + message: string; + }; + updateTimeMs: number; +} +export declare const QUERY_TARGET_KEY_PREFIX = "firestore_targets"; +/** Assembles the key for a query state in WebStorage */ +export declare function createWebStorageQueryTargetMetadataKey(persistenceKey: string, targetId: TargetId): string; +/** + * The JSON representation of a query target's state as used during WebStorage + * serialization. The TargetId is omitted as it is encoded as part of the key. + */ +export interface QueryTargetStateSchema { + state: QueryTargetState; + error?: { + code: string; + message: string; + }; + updateTimeMs: number; +} +export declare const ONLINE_STATE_KEY_PREFIX = "firestore_online_state"; +/** Assembles the key for the online state of the primary tab. */ +export declare function createWebStorageOnlineStateKey(persistenceKey: string): string; +export declare const BUNDLE_LOADED_KEY_PREFIX = "firestore_bundle_loaded_v2"; +export declare function createBundleLoadedKey(persistenceKey: string): string; +/** + * The JSON representation of the system's online state, as written by the + * primary client. + */ +export interface SharedOnlineStateSchema { + /** + * The clientId of the client that wrote this onlineState value. Tracked so + * that on startup, clients can check if this client is still active when + * determining whether to apply this value or not. + */ + readonly clientId: string; + readonly onlineState: string; +} +export declare const SEQUENCE_NUMBER_KEY_PREFIX = "firestore_sequence_number"; +/** Assembles the key for the current sequence number. */ +export declare function createWebStorageSequenceNumberKey(persistenceKey: string): string; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/shared_client_state_syncer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/shared_client_state_syncer.d.ts new file mode 100644 index 0000000..edc4a1b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/shared_client_state_syncer.d.ts @@ -0,0 +1,40 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BatchId, MutationBatchState, TargetId } from '../core/types'; +import { FirestoreError } from '../util/error'; +import { ClientId } from './shared_client_state'; +/** The different states of a watch target. */ +export type QueryTargetState = 'not-current' | 'current' | 'rejected'; +/** + * An interface that describes the actions the SharedClientState class needs to + * perform on a cooperating synchronization engine. + */ +export interface SharedClientStateSyncer { + /** Applies a mutation state to an existing batch. */ + applyBatchState(batchId: BatchId, state: MutationBatchState, error?: FirestoreError): Promise; + /** Applies a query target change from a different tab. */ + applyTargetState(targetId: TargetId, state: QueryTargetState, error?: FirestoreError): Promise; + /** Adds or removes Watch targets for queries from different tabs. */ + applyActiveTargetsChange(added: TargetId[], removed: TargetId[]): Promise; + /** Returns the IDs of the clients that are currently active. */ + getActiveClients(): Promise; + /** + * Retrieves newly changed documents from remote document cache and raises + * snapshots if needed. + */ + synchronizeWithChangedDocuments(collectionGroup: string): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/simple_db.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/simple_db.d.ts new file mode 100644 index 0000000..edaef3b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/simple_db.d.ts @@ -0,0 +1,233 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirestoreError } from '../util/error'; +import { PersistencePromise } from './persistence_promise'; +type SimpleDbTransactionMode = 'readonly' | 'readwrite'; +export interface SimpleDbSchemaConverter { + createOrUpgrade(db: IDBDatabase, txn: IDBTransaction, fromVersion: number, toVersion: number): PersistencePromise; +} +/** + * Wraps an IDBTransaction and exposes a store() method to get a handle to a + * specific object store. + */ +export declare class SimpleDbTransaction { + private readonly action; + private readonly transaction; + private aborted; + /** + * A `Promise` that resolves with the result of the IndexedDb transaction. + */ + private readonly completionDeferred; + static open(db: IDBDatabase, action: string, mode: IDBTransactionMode, objectStoreNames: string[]): SimpleDbTransaction; + constructor(action: string, transaction: IDBTransaction); + get completionPromise(): Promise; + abort(error?: Error): void; + maybeCommit(): void; + /** + * Returns a SimpleDbStore for the specified store. All + * operations performed on the SimpleDbStore happen within the context of this + * transaction and it cannot be used anymore once the transaction is + * completed. + * + * Note that we can't actually enforce that the KeyType and ValueType are + * correct, but they allow type safety through the rest of the consuming code. + */ + store(storeName: string): SimpleDbStore; +} +/** + * Provides a wrapper around IndexedDb with a simplified interface that uses + * Promise-like return values to chain operations. Real promises cannot be used + * since .then() continuations are executed asynchronously (e.g. via + * .setImmediate), which would cause IndexedDB to end the transaction. + * See PersistencePromise for more details. + */ +export declare class SimpleDb { + private readonly name; + private readonly version; + private readonly schemaConverter; + private db?; + private lastClosedDbVersion; + private versionchangelistener?; + /** Deletes the specified database. */ + static delete(name: string): Promise; + /** Returns true if IndexedDB is available in the current environment. */ + static isAvailable(): boolean; + /** + * Returns true if the backing IndexedDB store is the Node IndexedDBShim + * (see https://github.com/axemclion/IndexedDBShim). + */ + static isMockPersistence(): boolean; + /** Helper to get a typed SimpleDbStore from a transaction. */ + static getStore(txn: SimpleDbTransaction, store: string): SimpleDbStore; + /** Parse User Agent to determine iOS version. Returns -1 if not found. */ + static getIOSVersion(ua: string): number; + constructor(name: string, version: number, schemaConverter: SimpleDbSchemaConverter); + /** + * Opens the specified database, creating or upgrading it if necessary. + */ + ensureDb(action: string): Promise; + setVersionChangeListener(versionChangeListener: (event: IDBVersionChangeEvent) => void): void; + runTransaction(action: string, mode: SimpleDbTransactionMode, objectStores: string[], transactionFn: (transaction: SimpleDbTransaction) => PersistencePromise): Promise; + close(): void; +} +/** Parse User Agent to determine Android version. Returns -1 if not found. */ +export declare function getAndroidVersion(ua: string): number; +/** + * A controller for iterating over a key range or index. It allows an iterate + * callback to delete the currently-referenced object, or jump to a new key + * within the key range or index. + */ +export declare class IterationController { + private dbCursor; + private shouldStop; + private nextKey; + constructor(dbCursor: IDBCursorWithValue); + get isDone(): boolean; + get skipToKey(): IDBValidKey | null; + set cursor(value: IDBCursorWithValue); + /** + * This function can be called to stop iteration at any point. + */ + done(): void; + /** + * This function can be called to skip to that next key, which could be + * an index or a primary key. + */ + skip(key: IDBValidKey): void; + /** + * Delete the current cursor value from the object store. + * + * NOTE: You CANNOT do this with a keysOnly query. + */ + delete(): PersistencePromise; +} +/** + * Callback used with iterate() method. + */ +export type IterateCallback = (key: KeyType, value: ValueType, control: IterationController) => void | PersistencePromise; +/** Options available to the iterate() method. */ +export interface IterateOptions { + /** Index to iterate over (else primary keys will be iterated) */ + index?: string; + /** IndexedDB Range to iterate over (else entire store will be iterated) */ + range?: IDBKeyRange; + /** If true, values aren't read while iterating. */ + keysOnly?: boolean; + /** If true, iterate over the store in reverse. */ + reverse?: boolean; +} +/** An error that wraps exceptions that thrown during IndexedDB execution. */ +export declare class IndexedDbTransactionError extends FirestoreError { + name: string; + constructor(actionName: string, cause: Error | string); +} +/** Verifies whether `e` is an IndexedDbTransactionError. */ +export declare function isIndexedDbTransactionError(e: Error): boolean; +/** + * A wrapper around an IDBObjectStore providing an API that: + * + * 1) Has generic KeyType / ValueType parameters to provide strongly-typed + * methods for acting against the object store. + * 2) Deals with IndexedDB's onsuccess / onerror event callbacks, making every + * method return a PersistencePromise instead. + * 3) Provides a higher-level API to avoid needing to do excessive wrapping of + * intermediate IndexedDB types (IDBCursorWithValue, etc.) + */ +export declare class SimpleDbStore { + private store; + constructor(store: IDBObjectStore); + /** + * Writes a value into the Object Store. + * + * @param key - Optional explicit key to use when writing the object, else the + * key will be auto-assigned (e.g. via the defined keyPath for the store). + * @param value - The object to write. + */ + put(value: ValueType): PersistencePromise; + put(key: KeyType, value: ValueType): PersistencePromise; + /** + * Adds a new value into an Object Store and returns the new key. Similar to + * IndexedDb's `add()`, this method will fail on primary key collisions. + * + * @param value - The object to write. + * @returns The key of the value to add. + */ + add(value: ValueType): PersistencePromise; + /** + * Gets the object with the specified key from the specified store, or null + * if no object exists with the specified key. + * + * @key The key of the object to get. + * @returns The object with the specified key or null if no object exists. + */ + get(key: KeyType): PersistencePromise; + delete(key: KeyType | IDBKeyRange): PersistencePromise; + /** + * If we ever need more of the count variants, we can add overloads. For now, + * all we need is to count everything in a store. + * + * Returns the number of rows in the store. + */ + count(): PersistencePromise; + /** Loads all elements from the object store. */ + loadAll(): PersistencePromise; + /** Loads all elements for the index range from the object store. */ + loadAll(range: IDBKeyRange): PersistencePromise; + /** Loads all elements ordered by the given index. */ + loadAll(index: string): PersistencePromise; + /** + * Loads all elements from the object store that fall into the provided in the + * index range for the given index. + */ + loadAll(index: string, range: IDBKeyRange): PersistencePromise; + /** + * Loads the first `count` elements from the provided index range. Loads all + * elements if no limit is provided. + */ + loadFirst(range: IDBKeyRange, count: number | null): PersistencePromise; + deleteAll(): PersistencePromise; + deleteAll(range: IDBKeyRange): PersistencePromise; + deleteAll(index: string, range: IDBKeyRange): PersistencePromise; + /** + * Iterates over keys and values in an object store. + * + * @param options - Options specifying how to iterate the objects in the + * store. + * @param callback - will be called for each iterated object. Iteration can be + * canceled at any point by calling the doneFn passed to the callback. + * The callback can return a PersistencePromise if it performs async + * operations but note that iteration will continue without waiting for them + * to complete. + * @returns A PersistencePromise that resolves once all PersistencePromises + * returned by callbacks resolve. + */ + iterate(callback: IterateCallback): PersistencePromise; + iterate(options: IterateOptions, callback: IterateCallback): PersistencePromise; + /** + * Iterates over a store, but waits for the given callback to complete for + * each entry before iterating the next entry. This allows the callback to do + * asynchronous work to determine if this iteration should continue. + * + * The provided callback should return `true` to continue iteration, and + * `false` otherwise. + */ + iterateSerial(callback: (k: KeyType, v: ValueType) => PersistencePromise): PersistencePromise; + private iterateCursor; + private options; + private cursor; +} +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/target_cache.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/target_cache.d.ts new file mode 100644 index 0000000..218c805 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/target_cache.d.ts @@ -0,0 +1,130 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { Target } from '../core/target'; +import { ListenSequenceNumber, TargetId } from '../core/types'; +import { DocumentKeySet } from '../model/collections'; +import { DocumentKey } from '../model/document_key'; +import { PersistencePromise } from './persistence_promise'; +import { PersistenceTransaction } from './persistence_transaction'; +import { TargetData } from './target_data'; +/** + * Represents cached targets received from the remote backend. + * + * The cache is keyed by `Target` and entries in the cache are `TargetData` + * instances. + */ +export interface TargetCache { + /** + * A global snapshot version representing the last consistent snapshot we + * received from the backend. This is monotonically increasing and any + * snapshots received from the backend prior to this version (e.g. for targets + * resumed with a resume_token) should be suppressed (buffered) until the + * backend has caught up to this snapshot version again. This prevents our + * cache from ever going backwards in time. + * + * This is updated whenever our we get a TargetChange with a read_time and + * empty target_ids. + */ + getLastRemoteSnapshotVersion(transaction: PersistenceTransaction): PersistencePromise; + /** + * @returns The highest sequence number observed, including any that might be + * persisted on-disk. + */ + getHighestSequenceNumber(transaction: PersistenceTransaction): PersistencePromise; + /** + * Call provided function with each `TargetData` that we have cached. + */ + forEachTarget(txn: PersistenceTransaction, f: (q: TargetData) => void): PersistencePromise; + /** + * Set the highest listen sequence number and optionally updates the + * snapshot version of the last consistent snapshot received from the backend + * (see getLastRemoteSnapshotVersion() for more details). + * + * @param highestListenSequenceNumber - The new maximum listen sequence number. + * @param lastRemoteSnapshotVersion - The new snapshot version. Optional. + */ + setTargetsMetadata(transaction: PersistenceTransaction, highestListenSequenceNumber: number, lastRemoteSnapshotVersion?: SnapshotVersion): PersistencePromise; + /** + * Adds an entry in the cache. + * + * The cache key is extracted from `targetData.target`. The key must not already + * exist in the cache. + * + * @param targetData - A TargetData instance to put in the cache. + */ + addTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Updates an entry in the cache. + * + * The cache key is extracted from `targetData.target`. The entry must already + * exist in the cache, and it will be replaced. + * @param targetData - The TargetData to be replaced into the cache. + */ + updateTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * Removes the cached entry for the given target data. It is an error to remove + * a target data that does not exist. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeTargetData(transaction: PersistenceTransaction, targetData: TargetData): PersistencePromise; + /** + * The number of targets currently in the cache. + */ + getTargetCount(transaction: PersistenceTransaction): PersistencePromise; + /** + * Looks up a TargetData entry by target. + * + * @param target - The query target corresponding to the entry to look up. + * @returns The cached TargetData entry, or null if the cache has no entry for + * the target. + */ + getTargetData(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Adds the given document keys to cached query results of the given target + * ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + addMatchingKeys(transaction: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + /** + * Removes the given document keys from the cached query results of the + * given target ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMatchingKeys(transaction: PersistenceTransaction, keys: DocumentKeySet, targetId: TargetId): PersistencePromise; + /** + * Removes all the keys in the query results of the given target ID. + * + * Multi-Tab Note: This operation should only be called by the primary client. + */ + removeMatchingKeysForTargetId(transaction: PersistenceTransaction, targetId: TargetId): PersistencePromise; + /** + * Returns the document keys that match the provided target ID. + */ + getMatchingKeysForTargetId(transaction: PersistenceTransaction, targetId: TargetId): PersistencePromise; + /** + * Returns a new target ID that is higher than any query in the cache. If + * there are no queries in the cache, returns the first valid target ID. + * Allocated target IDs are persisted and `allocateTargetId()` will never + * return the same ID twice. + */ + allocateTargetId(transaction: PersistenceTransaction): PersistencePromise; + containsKey(transaction: PersistenceTransaction, key: DocumentKey): PersistencePromise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/target_data.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/target_data.d.ts new file mode 100644 index 0000000..595a334 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/local/target_data.d.ts @@ -0,0 +1,127 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { Target } from '../core/target'; +import { ListenSequenceNumber, TargetId } from '../core/types'; +import { ByteString } from '../util/byte_string'; +/** An enumeration of the different purposes we have for targets. */ +export declare const enum TargetPurpose { + /** A regular, normal query target. */ + Listen = "TargetPurposeListen", + /** + * The query target was used to refill a query after an existence filter + * mismatch. + */ + ExistenceFilterMismatch = "TargetPurposeExistenceFilterMismatch", + /** + * The query target was used if the query is the result of a false positive in + * the bloom filter. + */ + ExistenceFilterMismatchBloom = "TargetPurposeExistenceFilterMismatchBloom", + /** The query target was used to resolve a limbo document. */ + LimboResolution = "TargetPurposeLimboResolution" +} +/** + * An immutable set of metadata that the local store tracks for each target. + */ +export declare class TargetData { + /** The target being listened to. */ + readonly target: Target; + /** + * The target ID to which the target corresponds; Assigned by the + * LocalStore for user listens and by the SyncEngine for limbo watches. + */ + readonly targetId: TargetId; + /** The purpose of the target. */ + readonly purpose: TargetPurpose; + /** + * The sequence number of the last transaction during which this target data + * was modified. + */ + readonly sequenceNumber: ListenSequenceNumber; + /** The latest snapshot version seen for this target. */ + readonly snapshotVersion: SnapshotVersion; + /** + * The maximum snapshot version at which the associated view + * contained no limbo documents. + */ + readonly lastLimboFreeSnapshotVersion: SnapshotVersion; + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + readonly resumeToken: ByteString; + /** + * The number of documents that last matched the query at the resume token or + * read time. Documents are counted only when making a listen request with + * resume token or read time, otherwise, keep it null. + */ + readonly expectedCount: number | null; + constructor( + /** The target being listened to. */ + target: Target, + /** + * The target ID to which the target corresponds; Assigned by the + * LocalStore for user listens and by the SyncEngine for limbo watches. + */ + targetId: TargetId, + /** The purpose of the target. */ + purpose: TargetPurpose, + /** + * The sequence number of the last transaction during which this target data + * was modified. + */ + sequenceNumber: ListenSequenceNumber, + /** The latest snapshot version seen for this target. */ + snapshotVersion?: SnapshotVersion, + /** + * The maximum snapshot version at which the associated view + * contained no limbo documents. + */ + lastLimboFreeSnapshotVersion?: SnapshotVersion, + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + resumeToken?: ByteString, + /** + * The number of documents that last matched the query at the resume token or + * read time. Documents are counted only when making a listen request with + * resume token or read time, otherwise, keep it null. + */ + expectedCount?: number | null); + /** Creates a new target data instance with an updated sequence number. */ + withSequenceNumber(sequenceNumber: number): TargetData; + /** + * Creates a new target data instance with an updated resume token and + * snapshot version. + */ + withResumeToken(resumeToken: ByteString, snapshotVersion: SnapshotVersion): TargetData; + /** + * Creates a new target data instance with an updated expected count. + */ + withExpectedCount(expectedCount: number): TargetData; + /** + * Creates a new target data instance with an updated last limbo free + * snapshot version number. + */ + withLastLimboFreeSnapshotVersion(lastLimboFreeSnapshotVersion: SnapshotVersion): TargetData; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/collections.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/collections.d.ts new file mode 100644 index 0000000..999c4ea --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/collections.d.ts @@ -0,0 +1,50 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { TargetId } from '../core/types'; +import { OverlayedDocument } from '../local/overlayed_document'; +import { ObjectMap } from '../util/obj_map'; +import { SortedMap } from '../util/sorted_map'; +import { SortedSet } from '../util/sorted_set'; +import { Document, MutableDocument } from './document'; +import { DocumentKey } from './document_key'; +import { Mutation } from './mutation'; +import { Overlay } from './overlay'; +/** Miscellaneous collection types / constants. */ +export type MutableDocumentMap = SortedMap; +export declare function mutableDocumentMap(): MutableDocumentMap; +export interface DocumentSizeEntries { + documents: MutableDocumentMap; + sizeMap: SortedMap; +} +export type DocumentMap = SortedMap; +export declare function documentMap(...docs: Document[]): DocumentMap; +export type OverlayedDocumentMap = DocumentKeyMap; +export declare function newOverlayedDocumentMap(): OverlayedDocumentMap; +export declare function convertOverlayedDocumentMapToDocumentMap(collection: OverlayedDocumentMap): DocumentMap; +export type OverlayMap = DocumentKeyMap; +export declare function newOverlayMap(): OverlayMap; +export type MutationMap = DocumentKeyMap; +export declare function newMutationMap(): MutationMap; +export type DocumentKeyMap = ObjectMap; +export declare function newDocumentKeyMap(): DocumentKeyMap; +export type DocumentVersionMap = SortedMap; +export declare function documentVersionMap(): DocumentVersionMap; +export type DocumentKeySet = SortedSet; +export declare function documentKeySet(...keys: DocumentKey[]): DocumentKeySet; +export type TargetIdSet = SortedSet; +export declare function targetIdSet(): SortedSet; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document.d.ts new file mode 100644 index 0000000..66ba3f3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document.d.ts @@ -0,0 +1,150 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { DocumentKey } from './document_key'; +import { ObjectValue } from './object_value'; +import { FieldPath } from './path'; +/** + * Represents a document in Firestore with a key, version, data and whether the + * data has local mutations applied to it. + */ +export interface Document { + /** The key for this document */ + readonly key: DocumentKey; + /** + * The version of this document if it exists or a version at which this + * document was guaranteed to not exist. + */ + readonly version: SnapshotVersion; + /** + * The timestamp at which this document was read from the remote server. Uses + * `SnapshotVersion.min()` for documents created by the user. + */ + readonly readTime: SnapshotVersion; + /** + * The timestamp at which the document was created. This value increases + * monotonically when a document is deleted then recreated. It can also be + * compared to `createTime` of other documents and the `readTime` of a query. + */ + readonly createTime: SnapshotVersion; + /** The underlying data of this document or an empty value if no data exists. */ + readonly data: ObjectValue; + /** Returns whether local mutations were applied via the mutation queue. */ + readonly hasLocalMutations: boolean; + /** Returns whether mutations were applied based on a write acknowledgment. */ + readonly hasCommittedMutations: boolean; + /** + * Whether this document had a local mutation applied that has not yet been + * acknowledged by Watch. + */ + readonly hasPendingWrites: boolean; + /** + * Returns whether this document is valid (i.e. it is an entry in the + * RemoteDocumentCache, was created by a mutation or read from the backend). + */ + isValidDocument(): boolean; + /** + * Returns whether the document exists and its data is known at the current + * version. + */ + isFoundDocument(): boolean; + /** + * Returns whether the document is known to not exist at the current version. + */ + isNoDocument(): boolean; + /** + * Returns whether the document exists and its data is unknown at the current + * version. + */ + isUnknownDocument(): boolean; + isEqual(other: Document | null | undefined): boolean; + /** Creates a mutable copy of this document. */ + mutableCopy(): MutableDocument; + toString(): string; +} +/** + * Represents a document in Firestore with a key, version, data and whether it + * has local mutations applied to it. + * + * Documents can transition between states via `convertToFoundDocument()`, + * `convertToNoDocument()` and `convertToUnknownDocument()`. If a document does + * not transition to one of these states even after all mutations have been + * applied, `isValidDocument()` returns false and the document should be removed + * from all views. + */ +export declare class MutableDocument implements Document { + readonly key: DocumentKey; + private documentType; + version: SnapshotVersion; + readTime: SnapshotVersion; + createTime: SnapshotVersion; + data: ObjectValue; + private documentState; + private constructor(); + /** + * Creates a document with no known version or data, but which can serve as + * base document for mutations. + */ + static newInvalidDocument(documentKey: DocumentKey): MutableDocument; + /** + * Creates a new document that is known to exist with the given data at the + * given version. + */ + static newFoundDocument(documentKey: DocumentKey, version: SnapshotVersion, createTime: SnapshotVersion, value: ObjectValue): MutableDocument; + /** Creates a new document that is known to not exist at the given version. */ + static newNoDocument(documentKey: DocumentKey, version: SnapshotVersion): MutableDocument; + /** + * Creates a new document that is known to exist at the given version but + * whose data is not known (e.g. a document that was updated without a known + * base document). + */ + static newUnknownDocument(documentKey: DocumentKey, version: SnapshotVersion): MutableDocument; + /** + * Changes the document type to indicate that it exists and that its version + * and data are known. + */ + convertToFoundDocument(version: SnapshotVersion, value: ObjectValue): MutableDocument; + /** + * Changes the document type to indicate that it doesn't exist at the given + * version. + */ + convertToNoDocument(version: SnapshotVersion): MutableDocument; + /** + * Changes the document type to indicate that it exists at a given version but + * that its data is not known (e.g. a document that was updated without a known + * base document). + */ + convertToUnknownDocument(version: SnapshotVersion): MutableDocument; + setHasCommittedMutations(): MutableDocument; + setHasLocalMutations(): MutableDocument; + setReadTime(readTime: SnapshotVersion): MutableDocument; + get hasLocalMutations(): boolean; + get hasCommittedMutations(): boolean; + get hasPendingWrites(): boolean; + isValidDocument(): boolean; + isFoundDocument(): boolean; + isNoDocument(): boolean; + isUnknownDocument(): boolean; + isEqual(other: Document | null | undefined): boolean; + mutableCopy(): MutableDocument; + toString(): string; +} +/** + * Compares the value for field `field` in the provided documents. Throws if + * the field does not exist in both documents. + */ +export declare function compareDocumentsByField(field: FieldPath, d1: Document, d2: Document): number; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document_comparator.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document_comparator.d.ts new file mode 100644 index 0000000..100ed19 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document_comparator.d.ts @@ -0,0 +1,19 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Document } from './document'; +export type DocumentComparator = (doc1: Document, doc2: Document) => number; +export declare function compareByKey(doc1: Document, doc2: Document): number; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document_key.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document_key.d.ts new file mode 100644 index 0000000..4c95b57 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document_key.d.ts @@ -0,0 +1,45 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ResourcePath } from './path'; +/** + * @internal + */ +export declare class DocumentKey { + readonly path: ResourcePath; + constructor(path: ResourcePath); + static fromPath(path: string): DocumentKey; + static fromName(name: string): DocumentKey; + static empty(): DocumentKey; + get collectionGroup(): string; + /** Returns true if the document is in the specified collectionId. */ + hasCollectionId(collectionId: string): boolean; + /** Returns the collection group (i.e. the name of the parent collection) for this key. */ + getCollectionGroup(): string; + /** Returns the fully qualified path to the parent collection. */ + getCollectionPath(): ResourcePath; + isEqual(other: DocumentKey | null): boolean; + toString(): string; + static comparator(k1: DocumentKey, k2: DocumentKey): number; + static isDocumentKey(path: ResourcePath): boolean; + /** + * Creates and returns a new document key with the given segments. + * + * @param segments - The segments of the path to the document + * @returns A new instance of DocumentKey + */ + static fromSegments(segments: string[]): DocumentKey; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document_set.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document_set.d.ts new file mode 100644 index 0000000..5dc7ebd --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/document_set.d.ts @@ -0,0 +1,57 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Document } from './document'; +import { DocumentComparator } from './document_comparator'; +import { DocumentKey } from './document_key'; +/** + * DocumentSet is an immutable (copy-on-write) collection that holds documents + * in order specified by the provided comparator. We always add a document key + * comparator on top of what is provided to guarantee document equality based on + * the key. + */ +export declare class DocumentSet { + /** + * Returns an empty copy of the existing DocumentSet, using the same + * comparator. + */ + static emptySet(oldSet: DocumentSet): DocumentSet; + private comparator; + private keyedMap; + private sortedSet; + /** The default ordering is by key if the comparator is omitted */ + constructor(comp?: DocumentComparator); + has(key: DocumentKey): boolean; + get(key: DocumentKey): Document | null; + first(): Document | null; + last(): Document | null; + isEmpty(): boolean; + /** + * Returns the index of the provided key in the document set, or -1 if the + * document key is not present in the set; + */ + indexOf(key: DocumentKey): number; + get size(): number; + /** Iterates documents in order defined by "comparator" */ + forEach(cb: (doc: Document) => void): void; + /** Inserts or updates a document with the same key */ + add(doc: Document): DocumentSet; + /** Deletes a document with a given key */ + delete(key: DocumentKey): DocumentSet; + isEqual(other: DocumentSet | null | undefined): boolean; + toString(): string; + private copy; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/field_index.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/field_index.d.ts new file mode 100644 index 0000000..1f4ccb0 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/field_index.d.ts @@ -0,0 +1,171 @@ +/** + * @license + * Copyright 2021 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { Document } from './document'; +import { DocumentKey } from './document_key'; +import { FieldPath } from './path'; +/** + * The initial mutation batch id for each index. Gets updated during index + * backfill. + */ +export declare const INITIAL_LARGEST_BATCH_ID = -1; +/** + * The initial sequence number for each index. Gets updated during index + * backfill. + */ +export declare const INITIAL_SEQUENCE_NUMBER = 0; +/** + * An index definition for field indexes in Firestore. + * + * Every index is associated with a collection. The definition contains a list + * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or + * `CONTAINS` for ArrayContains/ArrayContainsAny queries). + * + * Unlike the backend, the SDK does not differentiate between collection or + * collection group-scoped indices. Every index can be used for both single + * collection and collection group queries. + */ +export declare class FieldIndex { + /** + * The index ID. Returns -1 if the index ID is not available (e.g. the index + * has not yet been persisted). + */ + readonly indexId: number; + /** The collection ID this index applies to. */ + readonly collectionGroup: string; + /** The field segments for this index. */ + readonly fields: IndexSegment[]; + /** Shows how up-to-date the index is for the current user. */ + readonly indexState: IndexState; + /** An ID for an index that has not yet been added to persistence. */ + static UNKNOWN_ID: number; + constructor( + /** + * The index ID. Returns -1 if the index ID is not available (e.g. the index + * has not yet been persisted). + */ + indexId: number, + /** The collection ID this index applies to. */ + collectionGroup: string, + /** The field segments for this index. */ + fields: IndexSegment[], + /** Shows how up-to-date the index is for the current user. */ + indexState: IndexState); +} +/** Returns the ArrayContains/ArrayContainsAny segment for this index. */ +export declare function fieldIndexGetArraySegment(fieldIndex: FieldIndex): IndexSegment | undefined; +/** Returns all directional (ascending/descending) segments for this index. */ +export declare function fieldIndexGetDirectionalSegments(fieldIndex: FieldIndex): IndexSegment[]; +/** + * Returns the order of the document key component for the given index. + * + * PORTING NOTE: This is only used in the Web IndexedDb implementation. + */ +export declare function fieldIndexGetKeyOrder(fieldIndex: FieldIndex): IndexKind; +/** + * Compares indexes by collection group and segments. Ignores update time and + * index ID. + */ +export declare function fieldIndexSemanticComparator(left: FieldIndex, right: FieldIndex): number; +/** Returns a debug representation of the field index */ +export declare function fieldIndexToString(fieldIndex: FieldIndex): string; +/** The type of the index, e.g. for which type of query it can be used. */ +export declare const enum IndexKind { + /** + * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries. + */ + ASCENDING = 0, + /** + * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries. + */ + DESCENDING = 1, + /** Contains index. Can be used for ArrayContains and ArrayContainsAny. */ + CONTAINS = 2 +} +/** An index component consisting of field path and index type. */ +export declare class IndexSegment { + /** The field path of the component. */ + readonly fieldPath: FieldPath; + /** The fields sorting order. */ + readonly kind: IndexKind; + constructor( + /** The field path of the component. */ + fieldPath: FieldPath, + /** The fields sorting order. */ + kind: IndexKind); +} +/** + * Stores the "high water mark" that indicates how updated the Index is for the + * current user. + */ +export declare class IndexState { + /** + * Indicates when the index was last updated (relative to other indexes). + */ + readonly sequenceNumber: number; + /** The the latest indexed read time, document and batch id. */ + readonly offset: IndexOffset; + constructor( + /** + * Indicates when the index was last updated (relative to other indexes). + */ + sequenceNumber: number, + /** The the latest indexed read time, document and batch id. */ + offset: IndexOffset); + /** The state of an index that has not yet been backfilled. */ + static empty(): IndexState; +} +/** + * Creates an offset that matches all documents with a read time higher than + * `readTime`. + */ +export declare function newIndexOffsetSuccessorFromReadTime(readTime: SnapshotVersion, largestBatchId: number): IndexOffset; +/** Creates a new offset based on the provided document. */ +export declare function newIndexOffsetFromDocument(document: Document): IndexOffset; +/** + * Stores the latest read time, document and batch ID that were processed for an + * index. + */ +export declare class IndexOffset { + /** + * The latest read time version that has been indexed by Firestore for this + * field index. + */ + readonly readTime: SnapshotVersion; + /** + * The key of the last document that was indexed for this query. Use + * `DocumentKey.empty()` if no document has been indexed. + */ + readonly documentKey: DocumentKey; + readonly largestBatchId: number; + constructor( + /** + * The latest read time version that has been indexed by Firestore for this + * field index. + */ + readTime: SnapshotVersion, + /** + * The key of the last document that was indexed for this query. Use + * `DocumentKey.empty()` if no document has been indexed. + */ + documentKey: DocumentKey, largestBatchId: number); + /** Returns an offset that sorts before all regular offsets. */ + static min(): IndexOffset; + /** Returns an offset that sorts after all regular offsets. */ + static max(): IndexOffset; +} +export declare function indexOffsetComparator(left: IndexOffset, right: IndexOffset): number; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/field_mask.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/field_mask.d.ts new file mode 100644 index 0000000..555ea0d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/field_mask.d.ts @@ -0,0 +1,45 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FieldPath } from './path'; +/** + * Provides a set of fields that can be used to partially patch a document. + * FieldMask is used in conjunction with ObjectValue. + * Examples: + * foo - Overwrites foo entirely with the provided value. If foo is not + * present in the companion ObjectValue, the field is deleted. + * foo.bar - Overwrites only the field bar of the object foo. + * If foo is not an object, foo is replaced with an object + * containing foo + */ +export declare class FieldMask { + readonly fields: FieldPath[]; + constructor(fields: FieldPath[]); + static empty(): FieldMask; + /** + * Returns a new FieldMask object that is the result of adding all the given + * fields paths to this field mask. + */ + unionWith(extraFields: FieldPath[]): FieldMask; + /** + * Verifies that `fieldPath` is included by at least one field in this field + * mask. + * + * This is an O(n) operation, where `n` is the size of the field mask. + */ + covers(fieldPath: FieldPath): boolean; + isEqual(other: FieldMask): boolean; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/mutation.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/mutation.d.ts new file mode 100644 index 0000000..9dd68b9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/mutation.d.ts @@ -0,0 +1,270 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { Timestamp } from '../lite-api/timestamp'; +import { Value as ProtoValue } from '../protos/firestore_proto_api'; +import { Document, MutableDocument } from './document'; +import { DocumentKey } from './document_key'; +import { FieldMask } from './field_mask'; +import { ObjectValue } from './object_value'; +import { FieldPath } from './path'; +import { TransformOperation } from './transform_operation'; +/** A field path and the TransformOperation to perform upon it. */ +export declare class FieldTransform { + readonly field: FieldPath; + readonly transform: TransformOperation; + constructor(field: FieldPath, transform: TransformOperation); +} +export declare function fieldTransformEquals(left: FieldTransform, right: FieldTransform): boolean; +export declare function fieldTransformsAreEqual(left?: FieldTransform[], right?: FieldTransform[]): boolean; +/** The result of successfully applying a mutation to the backend. */ +export declare class MutationResult { + /** + * The version at which the mutation was committed: + * + * - For most operations, this is the updateTime in the WriteResult. + * - For deletes, the commitTime of the WriteResponse (because deletes are + * not stored and have no updateTime). + * + * Note that these versions can be different: No-op writes will not change + * the updateTime even though the commitTime advances. + */ + readonly version: SnapshotVersion; + /** + * The resulting fields returned from the backend after a mutation + * containing field transforms has been committed. Contains one FieldValue + * for each FieldTransform that was in the mutation. + * + * Will be empty if the mutation did not contain any field transforms. + */ + readonly transformResults: Array; + constructor( + /** + * The version at which the mutation was committed: + * + * - For most operations, this is the updateTime in the WriteResult. + * - For deletes, the commitTime of the WriteResponse (because deletes are + * not stored and have no updateTime). + * + * Note that these versions can be different: No-op writes will not change + * the updateTime even though the commitTime advances. + */ + version: SnapshotVersion, + /** + * The resulting fields returned from the backend after a mutation + * containing field transforms has been committed. Contains one FieldValue + * for each FieldTransform that was in the mutation. + * + * Will be empty if the mutation did not contain any field transforms. + */ + transformResults: Array); +} +export declare const enum MutationType { + Set = 0, + Patch = 1, + Delete = 2, + Verify = 3 +} +/** + * Encodes a precondition for a mutation. This follows the model that the + * backend accepts with the special case of an explicit "empty" precondition + * (meaning no precondition). + */ +export declare class Precondition { + readonly updateTime?: SnapshotVersion | undefined; + readonly exists?: boolean | undefined; + private constructor(); + /** Creates a new empty Precondition. */ + static none(): Precondition; + /** Creates a new Precondition with an exists flag. */ + static exists(exists: boolean): Precondition; + /** Creates a new Precondition based on a version a document exists at. */ + static updateTime(version: SnapshotVersion): Precondition; + /** Returns whether this Precondition is empty. */ + get isNone(): boolean; + isEqual(other: Precondition): boolean; +} +/** Returns true if the preconditions is valid for the given document. */ +export declare function preconditionIsValidForDocument(precondition: Precondition, document: MutableDocument): boolean; +/** + * A mutation describes a self-contained change to a document. Mutations can + * create, replace, delete, and update subsets of documents. + * + * Mutations not only act on the value of the document but also its version. + * + * For local mutations (mutations that haven't been committed yet), we preserve + * the existing version for Set and Patch mutations. For Delete mutations, we + * reset the version to 0. + * + * Here's the expected transition table. + * + * MUTATION APPLIED TO RESULTS IN + * + * SetMutation Document(v3) Document(v3) + * SetMutation NoDocument(v3) Document(v0) + * SetMutation InvalidDocument(v0) Document(v0) + * PatchMutation Document(v3) Document(v3) + * PatchMutation NoDocument(v3) NoDocument(v3) + * PatchMutation InvalidDocument(v0) UnknownDocument(v3) + * DeleteMutation Document(v3) NoDocument(v0) + * DeleteMutation NoDocument(v3) NoDocument(v0) + * DeleteMutation InvalidDocument(v0) NoDocument(v0) + * + * For acknowledged mutations, we use the updateTime of the WriteResponse as + * the resulting version for Set and Patch mutations. As deletes have no + * explicit update time, we use the commitTime of the WriteResponse for + * Delete mutations. + * + * If a mutation is acknowledged by the backend but fails the precondition check + * locally, we transition to an `UnknownDocument` and rely on Watch to send us + * the updated version. + * + * Field transforms are used only with Patch and Set Mutations. We use the + * `updateTransforms` message to store transforms, rather than the `transforms`s + * messages. + * + * ## Subclassing Notes + * + * Every type of mutation needs to implement its own applyToRemoteDocument() and + * applyToLocalView() to implement the actual behavior of applying the mutation + * to some source document (see `setMutationApplyToRemoteDocument()` for an + * example). + */ +export declare abstract class Mutation { + abstract readonly type: MutationType; + abstract readonly key: DocumentKey; + abstract readonly precondition: Precondition; + abstract readonly fieldTransforms: FieldTransform[]; + /** + * Returns a `FieldMask` representing the fields that will be changed by + * applying this mutation. Returns `null` if the mutation will overwrite the + * entire document. + */ + abstract getFieldMask(): FieldMask | null; +} +/** + * A utility method to calculate a `Mutation` representing the overlay from the + * final state of the document, and a `FieldMask` representing the fields that + * are mutated by the local mutations. + */ +export declare function calculateOverlayMutation(doc: MutableDocument, mask: FieldMask | null): Mutation | null; +/** + * Applies this mutation to the given document for the purposes of computing a + * new remote document. If the input document doesn't match the expected state + * (e.g. it is invalid or outdated), the document type may transition to + * unknown. + * + * @param mutation - The mutation to apply. + * @param document - The document to mutate. The input document can be an + * invalid document if the client has no knowledge of the pre-mutation state + * of the document. + * @param mutationResult - The result of applying the mutation from the backend. + */ +export declare function mutationApplyToRemoteDocument(mutation: Mutation, document: MutableDocument, mutationResult: MutationResult): void; +/** + * Applies this mutation to the given document for the purposes of computing + * the new local view of a document. If the input document doesn't match the + * expected state, the document is not modified. + * + * @param mutation - The mutation to apply. + * @param document - The document to mutate. The input document can be an + * invalid document if the client has no knowledge of the pre-mutation state + * of the document. + * @param previousMask - The fields that have been updated before applying this mutation. + * @param localWriteTime - A timestamp indicating the local write time of the + * batch this mutation is a part of. + * @returns A `FieldMask` representing the fields that are changed by applying this mutation. + */ +export declare function mutationApplyToLocalView(mutation: Mutation, document: MutableDocument, previousMask: FieldMask | null, localWriteTime: Timestamp): FieldMask | null; +/** + * If this mutation is not idempotent, returns the base value to persist with + * this mutation. If a base value is returned, the mutation is always applied + * to this base value, even if document has already been updated. + * + * The base value is a sparse object that consists of only the document + * fields for which this mutation contains a non-idempotent transformation + * (e.g. a numeric increment). The provided value guarantees consistent + * behavior for non-idempotent transforms and allow us to return the same + * latency-compensated value even if the backend has already applied the + * mutation. The base value is null for idempotent mutations, as they can be + * re-played even if the backend has already applied them. + * + * @returns a base value to store along with the mutation, or null for + * idempotent mutations. + */ +export declare function mutationExtractBaseValue(mutation: Mutation, document: Document): ObjectValue | null; +export declare function mutationEquals(left: Mutation, right: Mutation): boolean; +/** + * A mutation that creates or replaces the document at the given key with the + * object value contents. + */ +export declare class SetMutation extends Mutation { + readonly key: DocumentKey; + readonly value: ObjectValue; + readonly precondition: Precondition; + readonly fieldTransforms: FieldTransform[]; + constructor(key: DocumentKey, value: ObjectValue, precondition: Precondition, fieldTransforms?: FieldTransform[]); + readonly type: MutationType; + getFieldMask(): FieldMask | null; +} +/** + * A mutation that modifies fields of the document at the given key with the + * given values. The values are applied through a field mask: + * + * * When a field is in both the mask and the values, the corresponding field + * is updated. + * * When a field is in neither the mask nor the values, the corresponding + * field is unmodified. + * * When a field is in the mask but not in the values, the corresponding field + * is deleted. + * * When a field is not in the mask but is in the values, the values map is + * ignored. + */ +export declare class PatchMutation extends Mutation { + readonly key: DocumentKey; + readonly data: ObjectValue; + readonly fieldMask: FieldMask; + readonly precondition: Precondition; + readonly fieldTransforms: FieldTransform[]; + constructor(key: DocumentKey, data: ObjectValue, fieldMask: FieldMask, precondition: Precondition, fieldTransforms?: FieldTransform[]); + readonly type: MutationType; + getFieldMask(): FieldMask | null; +} +/** A mutation that deletes the document at the given key. */ +export declare class DeleteMutation extends Mutation { + readonly key: DocumentKey; + readonly precondition: Precondition; + constructor(key: DocumentKey, precondition: Precondition); + readonly type: MutationType; + readonly fieldTransforms: FieldTransform[]; + getFieldMask(): FieldMask | null; +} +/** + * A mutation that verifies the existence of the document at the given key with + * the provided precondition. + * + * The `verify` operation is only used in Transactions, and this class serves + * primarily to facilitate serialization into protos. + */ +export declare class VerifyMutation extends Mutation { + readonly key: DocumentKey; + readonly precondition: Precondition; + constructor(key: DocumentKey, precondition: Precondition); + readonly type: MutationType; + readonly fieldTransforms: FieldTransform[]; + getFieldMask(): FieldMask | null; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/mutation_batch.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/mutation_batch.d.ts new file mode 100644 index 0000000..c05b01e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/mutation_batch.d.ts @@ -0,0 +1,88 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { BatchId } from '../core/types'; +import { Timestamp } from '../lite-api/timestamp'; +import { DocumentKeySet, MutationMap, DocumentVersionMap, OverlayedDocumentMap } from './collections'; +import { MutableDocument } from './document'; +import { FieldMask } from './field_mask'; +import { Mutation, MutationResult } from './mutation'; +/** + * A batch of mutations that will be sent as one unit to the backend. + */ +export declare class MutationBatch { + batchId: BatchId; + localWriteTime: Timestamp; + baseMutations: Mutation[]; + mutations: Mutation[]; + /** + * @param batchId - The unique ID of this mutation batch. + * @param localWriteTime - The original write time of this mutation. + * @param baseMutations - Mutations that are used to populate the base + * values when this mutation is applied locally. This can be used to locally + * overwrite values that are persisted in the remote document cache. Base + * mutations are never sent to the backend. + * @param mutations - The user-provided mutations in this mutation batch. + * User-provided mutations are applied both locally and remotely on the + * backend. + */ + constructor(batchId: BatchId, localWriteTime: Timestamp, baseMutations: Mutation[], mutations: Mutation[]); + /** + * Applies all the mutations in this MutationBatch to the specified document + * to compute the state of the remote document + * + * @param document - The document to apply mutations to. + * @param batchResult - The result of applying the MutationBatch to the + * backend. + */ + applyToRemoteDocument(document: MutableDocument, batchResult: MutationBatchResult): void; + /** + * Computes the local view of a document given all the mutations in this + * batch. + * + * @param document - The document to apply mutations to. + * @param mutatedFields - Fields that have been updated before applying this mutation batch. + * @returns A `FieldMask` representing all the fields that are mutated. + */ + applyToLocalView(document: MutableDocument, mutatedFields: FieldMask | null): FieldMask | null; + /** + * Computes the local view for all provided documents given the mutations in + * this batch. Returns a `DocumentKey` to `Mutation` map which can be used to + * replace all the mutation applications. + */ + applyToLocalDocumentSet(documentMap: OverlayedDocumentMap, documentsWithoutRemoteVersion: DocumentKeySet): MutationMap; + keys(): DocumentKeySet; + isEqual(other: MutationBatch): boolean; +} +/** The result of applying a mutation batch to the backend. */ +export declare class MutationBatchResult { + readonly batch: MutationBatch; + readonly commitVersion: SnapshotVersion; + readonly mutationResults: MutationResult[]; + /** + * A pre-computed mapping from each mutated document to the resulting + * version. + */ + readonly docVersions: DocumentVersionMap; + private constructor(); + /** + * Creates a new MutationBatchResult for the given batch and results. There + * must be one result for each mutation in the batch. This static factory + * caches a document=>version mapping (docVersions). + */ + static from(batch: MutationBatch, commitVersion: SnapshotVersion, results: MutationResult[]): MutationBatchResult; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/normalize.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/normalize.d.ts new file mode 100644 index 0000000..c279ba7 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/normalize.d.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Timestamp } from '../protos/firestore_proto_api'; +import { ByteString } from '../util/byte_string'; +/** + * Converts the possible Proto values for a timestamp value into a "seconds and + * nanos" representation. + */ +export declare function normalizeTimestamp(date: Timestamp): { + seconds: number; + nanos: number; +}; +/** + * Converts the possible Proto types for numbers into a JavaScript number. + * Returns 0 if the value is not numeric. + */ +export declare function normalizeNumber(value: number | string | undefined): number; +/** Converts the possible Proto types for Blobs into a ByteString. */ +export declare function normalizeByteString(blob: string | Uint8Array): ByteString; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/object_value.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/object_value.d.ts new file mode 100644 index 0000000..d299e86 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/object_value.d.ts @@ -0,0 +1,78 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { MapValue as ProtoMapValue, Value as ProtoValue } from '../protos/firestore_proto_api'; +import { FieldMask } from './field_mask'; +import { FieldPath } from './path'; +export interface JsonObject { + [name: string]: T; +} +/** + * An ObjectValue represents a MapValue in the Firestore Proto and offers the + * ability to add and remove fields (via the ObjectValueBuilder). + */ +export declare class ObjectValue { + readonly value: { + mapValue: ProtoMapValue; + }; + constructor(value: { + mapValue: ProtoMapValue; + }); + static empty(): ObjectValue; + /** + * Returns the value at the given path or null. + * + * @param path - the path to search + * @returns The value at the path or null if the path is not set. + */ + field(path: FieldPath): ProtoValue | null; + /** + * Sets the field to the provided value. + * + * @param path - The field path to set. + * @param value - The value to set. + */ + set(path: FieldPath, value: ProtoValue): void; + /** + * Sets the provided fields to the provided values. + * + * @param data - A map of fields to values (or null for deletes). + */ + setAll(data: Map): void; + /** + * Removes the field at the specified path. If there is no field at the + * specified path, nothing is changed. + * + * @param path - The field path to remove. + */ + delete(path: FieldPath): void; + isEqual(other: ObjectValue): boolean; + /** + * Returns the map that contains the leaf element of `path`. If the parent + * entry does not yet exist, or if it is not a map, a new map will be created. + */ + private getFieldsMap; + /** + * Modifies `fieldsMap` by adding, replacing or deleting the specified + * entries. + */ + private applyChanges; + clone(): ObjectValue; +} +/** + * Returns a FieldMask built from all fields in a MapValue. + */ +export declare function extractFieldMask(value: ProtoMapValue): FieldMask; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/overlay.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/overlay.d.ts new file mode 100644 index 0000000..ef90621 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/overlay.d.ts @@ -0,0 +1,32 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DocumentKey } from './document_key'; +import { Mutation } from './mutation'; +/** + * Representation of an overlay computed by Firestore. + * + * Holds information about a mutation and the largest batch id in Firestore when + * the mutation was created. + */ +export declare class Overlay { + readonly largestBatchId: number; + readonly mutation: Mutation; + constructor(largestBatchId: number, mutation: Mutation); + getKey(): DocumentKey; + isEqual(other: Overlay | null): boolean; + toString(): string; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/path.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/path.d.ts new file mode 100644 index 0000000..a33f0e8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/path.d.ts @@ -0,0 +1,121 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare const DOCUMENT_KEY_NAME = "__name__"; +/** + * Path represents an ordered sequence of string segments. + */ +declare abstract class BasePath> { + private segments; + private offset; + private len; + constructor(segments: string[], offset?: number, length?: number); + /** + * Abstract constructor method to construct an instance of B with the given + * parameters. + */ + protected abstract construct(segments: string[], offset?: number, length?: number): B; + /** + * Returns a String representation. + * + * Implementing classes are required to provide deterministic implementations as + * the String representation is used to obtain canonical Query IDs. + */ + abstract toString(): string; + get length(): number; + isEqual(other: B): boolean; + child(nameOrPath: string | B): B; + /** The index of one past the last segment of the path. */ + private limit; + popFirst(size?: number): B; + popLast(): B; + firstSegment(): string; + lastSegment(): string; + get(index: number): string; + isEmpty(): boolean; + isPrefixOf(other: this): boolean; + isImmediateParentOf(potentialChild: this): boolean; + forEach(fn: (segment: string) => void): void; + toArray(): string[]; + /** + * Compare 2 paths segment by segment, prioritizing numeric IDs + * (e.g., "__id123__") in numeric ascending order, followed by string + * segments in lexicographical order. + */ + static comparator>(p1: BasePath, p2: BasePath): number; + private static compareSegments; + private static isNumericId; + private static extractNumericId; +} +/** + * A slash-separated path for navigating resources (documents and collections) + * within Firestore. + * + * @internal + */ +export declare class ResourcePath extends BasePath { + protected construct(segments: string[], offset?: number, length?: number): ResourcePath; + canonicalString(): string; + toString(): string; + /** + * Returns a string representation of this path + * where each path segment has been encoded with + * `encodeURIComponent`. + */ + toUriEncodedString(): string; + /** + * Creates a resource path from the given slash-delimited string. If multiple + * arguments are provided, all components are combined. Leading and trailing + * slashes from all components are ignored. + */ + static fromString(...pathComponents: string[]): ResourcePath; + static emptyPath(): ResourcePath; +} +/** + * A dot-separated path for navigating sub-objects within a document. + * @internal + */ +export declare class FieldPath extends BasePath { + protected construct(segments: string[], offset?: number, length?: number): FieldPath; + /** + * Returns true if the string could be used as a segment in a field path + * without escaping. + */ + private static isValidIdentifier; + canonicalString(): string; + toString(): string; + /** + * Returns true if this field references the key of a document. + */ + isKeyField(): boolean; + /** + * The field designating the key of a document. + */ + static keyField(): FieldPath; + /** + * Parses a field string from the given server-formatted string. + * + * - Splitting the empty string is not allowed (for now at least). + * - Empty segments within the string (e.g. if there are two consecutive + * separators) are not allowed. + * + * TODO(b/37244157): we should make this more strict. Right now, it allows + * non-identifier path components, even if they aren't escaped. + */ + static fromServerFormat(path: string): FieldPath; + static emptyPath(): FieldPath; +} +export {}; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/server_timestamps.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/server_timestamps.d.ts new file mode 100644 index 0000000..d4e8c4a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/server_timestamps.d.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Timestamp } from '../lite-api/timestamp'; +import { Value as ProtoValue } from '../protos/firestore_proto_api'; +export declare function isServerTimestamp(value: ProtoValue | null): boolean; +/** + * Creates a new ServerTimestamp proto value (using the internal format). + */ +export declare function serverTimestamp(localWriteTime: Timestamp, previousValue: ProtoValue | null): ProtoValue; +/** + * Returns the value of the field before this ServerTimestamp was set. + * + * Preserving the previous values allows the user to display the last resoled + * value until the backend responds with the timestamp. + */ +export declare function getPreviousValue(value: ProtoValue): ProtoValue | null; +/** + * Returns the local time at which this timestamp was first set. + */ +export declare function getLocalWriteTime(value: ProtoValue): Timestamp; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/target_index_matcher.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/target_index_matcher.d.ts new file mode 100644 index 0000000..d313f1e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/target_index_matcher.d.ts @@ -0,0 +1,76 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Target } from '../core/target'; +import { FieldIndex } from './field_index'; +/** + * A light query planner for Firestore. + * + * This class matches a `FieldIndex` against a Firestore Query `Target`. It + * determines whether a given index can be used to serve the specified target. + * + * The following table showcases some possible index configurations: + * + * Query | Index + * ----------------------------------------------------------------------------- + * where('a', '==', 'a').where('b', '==', 'b') | a ASC, b DESC + * where('a', '==', 'a').where('b', '==', 'b') | a ASC + * where('a', '==', 'a').where('b', '==', 'b') | b DESC + * where('a', '>=', 'a').orderBy('a') | a ASC + * where('a', '>=', 'a').orderBy('a', 'desc') | a DESC + * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC, b ASC + * where('a', '>=', 'a').orderBy('a').orderBy('b') | a ASC + * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS, b ASCENDING + * where('a', 'array-contains', 'a').orderBy('b') | a CONTAINS + */ +export declare class TargetIndexMatcher { + private readonly collectionId; + private inequalityFilters; + private readonly equalityFilters; + private readonly orderBys; + constructor(target: Target); + get hasMultipleInequality(): boolean; + /** + * Returns whether the index can be used to serve the TargetIndexMatcher's + * target. + * + * An index is considered capable of serving the target when: + * - The target uses all index segments for its filters and orderBy clauses. + * The target can have additional filter and orderBy clauses, but not + * fewer. + * - If an ArrayContains/ArrayContainsAnyfilter is used, the index must also + * have a corresponding `CONTAINS` segment. + * - All directional index segments can be mapped to the target as a series of + * equality filters, a single inequality filter and a series of orderBy + * clauses. + * - The segments that represent the equality filters may appear out of order. + * - The optional segment for the inequality filter must appear after all + * equality segments. + * - The segments that represent that orderBy clause of the target must appear + * in order after all equality and inequality segments. Single orderBy + * clauses cannot be skipped, but a continuous orderBy suffix may be + * omitted. + */ + servedByIndex(index: FieldIndex): boolean; + /** + * Returns a full matched field index for this target. Currently multiple + * inequality query is not supported so function returns null. + */ + buildTargetIndex(): FieldIndex | null; + private hasMatchingEqualityFilter; + private matchesFilter; + private matchesOrderBy; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/transform_operation.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/transform_operation.d.ts new file mode 100644 index 0000000..be1e0f3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/transform_operation.d.ts @@ -0,0 +1,75 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Timestamp } from '../lite-api/timestamp'; +import { Value as ProtoValue } from '../protos/firestore_proto_api'; +import { Serializer } from '../remote/number_serializer'; +/** Used to represent a field transform on a mutation. */ +export declare class TransformOperation { + private _; +} +/** + * Computes the local transform result against the provided `previousValue`, + * optionally using the provided localWriteTime. + */ +export declare function applyTransformOperationToLocalView(transform: TransformOperation, previousValue: ProtoValue | null, localWriteTime: Timestamp): ProtoValue; +/** + * Computes a final transform result after the transform has been acknowledged + * by the server, potentially using the server-provided transformResult. + */ +export declare function applyTransformOperationToRemoteDocument(transform: TransformOperation, previousValue: ProtoValue | null, transformResult: ProtoValue | null): ProtoValue; +/** + * If this transform operation is not idempotent, returns the base value to + * persist for this transform. If a base value is returned, the transform + * operation is always applied to this base value, even if document has + * already been updated. + * + * Base values provide consistent behavior for non-idempotent transforms and + * allow us to return the same latency-compensated value even if the backend + * has already applied the transform operation. The base value is null for + * idempotent transforms, as they can be re-played even if the backend has + * already applied them. + * + * @returns a base value to store along with the mutation, or null for + * idempotent transforms. + */ +export declare function computeTransformOperationBaseValue(transform: TransformOperation, previousValue: ProtoValue | null): ProtoValue | null; +export declare function transformOperationEquals(left: TransformOperation, right: TransformOperation): boolean; +/** Transforms a value into a server-generated timestamp. */ +export declare class ServerTimestampTransform extends TransformOperation { +} +/** Transforms an array value via a union operation. */ +export declare class ArrayUnionTransformOperation extends TransformOperation { + readonly elements: ProtoValue[]; + constructor(elements: ProtoValue[]); +} +/** Transforms an array value via a remove operation. */ +export declare class ArrayRemoveTransformOperation extends TransformOperation { + readonly elements: ProtoValue[]; + constructor(elements: ProtoValue[]); +} +/** + * Implements the backend semantics for locally computed NUMERIC_ADD (increment) + * transforms. Converts all field values to integers or doubles, but unlike the + * backend does not cap integer values at 2^63. Instead, JavaScript number + * arithmetic is used and precision loss can occur for values greater than 2^53. + */ +export declare class NumericIncrementTransformOperation extends TransformOperation { + readonly serializer: Serializer; + readonly operand: ProtoValue; + constructor(serializer: Serializer, operand: ProtoValue); +} +export declare function applyNumericIncrementTransformOperationToLocalView(transform: NumericIncrementTransformOperation, previousValue: ProtoValue | null): ProtoValue; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/type_order.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/type_order.d.ts new file mode 100644 index 0000000..bb09c39 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/type_order.d.ts @@ -0,0 +1,38 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * All the different kinds of values that can be stored in fields in + * a document. The types of the same comparison order should be defined + * together as a group. The order of each group is defined by the Firestore + * backend and is available at: + * https://firebase.google.com/docs/firestore/manage-data/data-types + */ +export declare const enum TypeOrder { + NullValue = 0, + BooleanValue = 1, + NumberValue = 2, + TimestampValue = 3, + ServerTimestampValue = 4, + StringValue = 5, + BlobValue = 6, + RefValue = 7, + GeoPointValue = 8, + ArrayValue = 9, + VectorValue = 10, + ObjectValue = 11, + MaxValue = 9007199254740991 +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/values.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/values.d.ts new file mode 100644 index 0000000..94b377f --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/model/values.d.ts @@ -0,0 +1,114 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseId } from '../core/database_info'; +import { ArrayValue, MapValue, Value as ProtoValue, Value } from '../protos/firestore_proto_api'; +import { DocumentKey } from './document_key'; +import { TypeOrder } from './type_order'; +export declare const TYPE_KEY = "__type__"; +export declare const MAX_VALUE: Value; +export declare const VECTOR_VALUE_SENTINEL = "__vector__"; +export declare const VECTOR_MAP_VECTORS_KEY = "value"; +export declare const MIN_VALUE: Value; +/** Extracts the backend's type order for the provided value. */ +export declare function typeOrder(value: Value): TypeOrder; +/** Tests `left` and `right` for equality based on the backend semantics. */ +export declare function valueEquals(left: Value, right: Value): boolean; +export declare function numberEquals(left: Value, right: Value): boolean; +/** Returns true if the ArrayValue contains the specified element. */ +export declare function arrayValueContains(haystack: ArrayValue, needle: Value): boolean; +export declare function valueCompare(left: Value, right: Value): number; +/** + * Generates the canonical ID for the provided field value (as used in Target + * serialization). + */ +export declare function canonicalId(value: Value): string; +/** + * Returns an approximate (and wildly inaccurate) in-memory size for the field + * value. + * + * The memory size takes into account only the actual user data as it resides + * in memory and ignores object overhead. + */ +export declare function estimateByteSize(value: Value): number; +/** Returns a reference value for the provided database and key. */ +export declare function refValue(databaseId: DatabaseId, key: DocumentKey): Value; +/** Returns true if `value` is an IntegerValue . */ +export declare function isInteger(value?: Value | null): value is { + integerValue: string | number; +}; +/** Returns true if `value` is a DoubleValue. */ +export declare function isDouble(value?: Value | null): value is { + doubleValue: string | number; +}; +/** Returns true if `value` is either an IntegerValue or a DoubleValue. */ +export declare function isNumber(value?: Value | null): boolean; +/** Returns true if `value` is an ArrayValue. */ +export declare function isArray(value?: Value | null): value is { + arrayValue: ArrayValue; +}; +/** Returns true if `value` is a ReferenceValue. */ +export declare function isReferenceValue(value?: Value | null): value is { + referenceValue: string; +}; +/** Returns true if `value` is a NullValue. */ +export declare function isNullValue(value?: Value | null): value is { + nullValue: 'NULL_VALUE'; +}; +/** Returns true if `value` is NaN. */ +export declare function isNanValue(value?: Value | null): value is { + doubleValue: 'NaN' | number; +}; +/** Returns true if `value` is a MapValue. */ +export declare function isMapValue(value?: Value | null): value is { + mapValue: MapValue; +}; +/** Returns true if `value` is a VetorValue. */ +export declare function isVectorValue(value: ProtoValue | null): boolean; +/** Creates a deep copy of `source`. */ +export declare function deepClone(source: Value): Value; +/** Returns true if the Value represents the canonical {@link #MAX_VALUE} . */ +export declare function isMaxValue(value: Value): boolean; +export declare const MIN_VECTOR_VALUE: { + mapValue: { + fields: { + __type__: { + stringValue: string; + }; + value: { + arrayValue: {}; + }; + }; + }; +}; +/** Returns the lowest value for the given value type (inclusive). */ +export declare function valuesGetLowerBound(value: Value): Value; +/** Returns the largest value for the given value type (exclusive). */ +export declare function valuesGetUpperBound(value: Value): Value; +export declare function lowerBoundCompare(left: { + value: Value; + inclusive: boolean; +}, right: { + value: Value; + inclusive: boolean; +}): number; +export declare function upperBoundCompare(left: { + value: Value; + inclusive: boolean; +}, right: { + value: Value; + inclusive: boolean; +}): number; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/base64.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/base64.d.ts new file mode 100644 index 0000000..999f234 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/base64.d.ts @@ -0,0 +1,25 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Converts a Base64 encoded string to a binary string. */ +export declare function decodeBase64(encoded: string): string; +/** Converts a binary string to a Base64 encoded string. */ +export declare function encodeBase64(raw: string): string; +/** + * True if and only if the Base64 conversion functions are available. + * @internal + */ +export declare function isBase64Available(): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/base64.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/base64.d.ts new file mode 100644 index 0000000..9ea2985 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/base64.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Converts a Base64 encoded string to a binary string. */ +export declare function decodeBase64(encoded: string): string; +/** Converts a binary string to a Base64 encoded string. */ +export declare function encodeBase64(raw: string): string; +/** True if and only if the Base64 conversion functions are available. */ +export declare function isBase64Available(): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/byte_stream_reader.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/byte_stream_reader.d.ts new file mode 100644 index 0000000..2b95861 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/byte_stream_reader.d.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BundleSource } from '../../util/bundle_reader'; +/** + * On web, a `ReadableStream` is wrapped around by a `ByteStreamReader`. + */ +export declare function toByteStreamReader(source: BundleSource, bytesPerRead: number): ReadableStreamDefaultReader; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/connection.d.ts new file mode 100644 index 0000000..9e35cd8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/connection.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseInfo } from '../../core/database_info'; +import { Connection } from '../../remote/connection'; +import { ConnectivityMonitor } from '../../remote/connectivity_monitor'; +/** Initializes the WebChannelConnection for the browser. */ +export declare function newConnection(databaseInfo: DatabaseInfo): Connection; +/** Return the Platform-specific connectivity monitor. */ +export declare function newConnectivityMonitor(): ConnectivityMonitor; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/connectivity_monitor.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/connectivity_monitor.d.ts new file mode 100644 index 0000000..0f14bb7 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/connectivity_monitor.d.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ConnectivityMonitor, NetworkStatus } from '../../remote/connectivity_monitor'; +/** + * Browser implementation of ConnectivityMonitor. + */ +export declare class BrowserConnectivityMonitor implements ConnectivityMonitor { + private readonly networkAvailableListener; + private readonly networkUnavailableListener; + private callbacks; + constructor(); + addCallback(callback: (status: NetworkStatus) => void): void; + shutdown(): void; + private configureNetworkMonitoring; + private onNetworkAvailable; + private onNetworkUnavailable; + /** Checks that all used attributes of window are available. */ + static isAvailable(): boolean; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/dom.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/dom.d.ts new file mode 100644 index 0000000..d2a5319 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/dom.d.ts @@ -0,0 +1,20 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** The Platform's 'window' implementation or null if not available. */ +export declare function getWindow(): Window | null; +/** The Platform's 'document' implementation or null if not available. */ +export declare function getDocument(): Document | null; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/format_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/format_json.d.ts new file mode 100644 index 0000000..5e5f7ad --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/format_json.d.ts @@ -0,0 +1,18 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Formats an object as a JSON string, suitable for logging. */ +export declare function formatJSON(value: unknown): string; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/random_bytes.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/random_bytes.d.ts new file mode 100644 index 0000000..672e612 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/random_bytes.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Generates `nBytes` of random bytes. + * + * If `nBytes < 0` , an error will be thrown. + */ +export declare function randomBytes(nBytes: number): Uint8Array; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/serializer.d.ts new file mode 100644 index 0000000..839e680 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/serializer.d.ts @@ -0,0 +1,20 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Return the Platform-specific serializer monitor. */ +import { DatabaseId } from '../../core/database_info'; +import { JsonProtoSerializer } from '../../remote/serializer'; +export declare function newSerializer(databaseId: DatabaseId): JsonProtoSerializer; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/snapshot_to_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/snapshot_to_json.d.ts new file mode 100644 index 0000000..6a75f06 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/snapshot_to_json.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Return the Platform-specific build JSON bundle implementations. */ +import { Firestore } from '../../api/database'; +import { Query } from '../../core/query'; +import { DocumentData } from '../../lite-api/reference'; +import { Document } from '../../model/document'; +export declare function buildDocumentSnapshotJsonBundle(db: Firestore, document: Document, docData: DocumentData, path: string): string; +export declare function buildQuerySnapshotJsonBundle(db: Firestore, query: Query, bundleName: string, parent: string, paths: string[], docs: Document[], documentData: DocumentData[]): string; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/text_serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/text_serializer.d.ts new file mode 100644 index 0000000..47213fb --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/text_serializer.d.ts @@ -0,0 +1,24 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An instance of the Platform's 'TextEncoder' implementation. + */ +export declare function newTextEncoder(): TextEncoder; +/** + * An instance of the Platform's 'TextDecoder' implementation. + */ +export declare function newTextDecoder(): TextDecoder; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/webchannel_connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/webchannel_connection.d.ts new file mode 100644 index 0000000..79117f7 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser/webchannel_connection.d.ts @@ -0,0 +1,47 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { WebChannel } from '@firebase/webchannel-wrapper/webchannel-blob'; +import { Token } from '../../api/credentials'; +import { DatabaseInfo } from '../../core/database_info'; +import { Stream } from '../../remote/connection'; +import { RestConnection } from '../../remote/rest_connection'; +import { StringMap } from '../../util/types'; +export declare class WebChannelConnection extends RestConnection { + private readonly forceLongPolling; + private readonly autoDetectLongPolling; + private readonly useFetchStreams; + private readonly longPollingOptions; + /** A collection of open WebChannel instances */ + private openWebChannels; + constructor(info: DatabaseInfo); + protected performRPCRequest(rpcName: string, url: string, headers: StringMap, body: Req, _forwardCredentials: boolean): Promise; + openStream(rpcName: string, authToken: Token | null, appCheckToken: Token | null): Stream; + /** + * Closes and cleans up any resources associated with the connection. + */ + terminate(): void; + /** + * Add a WebChannel instance to the collection of open instances. + * @param webChannel + */ + addOpenWebChannel(webChannel: WebChannel): void; + /** + * Remove a WebChannel instance from the collection of open instances. + * @param webChannel + */ + removeOpenWebChannel(webChannel: WebChannel): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/base64.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/base64.d.ts new file mode 100644 index 0000000..ae35760 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/base64.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser/base64'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/byte_stream_reader.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/byte_stream_reader.d.ts new file mode 100644 index 0000000..c91280a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/byte_stream_reader.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser/byte_stream_reader'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/connection.d.ts new file mode 100644 index 0000000..b347f61 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/connection.d.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseInfo } from '../../core/database_info'; +import { Connection } from '../../remote/connection'; +export { newConnectivityMonitor } from '../browser/connection'; +/** Initializes the HTTP connection for the REST API. */ +export declare function newConnection(databaseInfo: DatabaseInfo): Connection; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/dom.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/dom.d.ts new file mode 100644 index 0000000..778555d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/dom.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser/dom'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/fetch_connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/fetch_connection.d.ts new file mode 100644 index 0000000..88105c0 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/fetch_connection.d.ts @@ -0,0 +1,28 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Token } from '../../api/credentials'; +import { Stream } from '../../remote/connection'; +import { RestConnection } from '../../remote/rest_connection'; +import { StringMap } from '../../util/types'; +/** + * A Rest-based connection that relies on the native HTTP stack + * (e.g. `fetch` or a polyfill). + */ +export declare class FetchConnection extends RestConnection { + openStream(rpcName: string, token: Token | null): Stream; + protected performRPCRequest(rpcName: string, url: string, headers: StringMap, body: Req, forwardCredentials: boolean): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/format_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/format_json.d.ts new file mode 100644 index 0000000..a9a0b71 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/format_json.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser/format_json'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/random_bytes.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/random_bytes.d.ts new file mode 100644 index 0000000..52e5798 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/random_bytes.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser/random_bytes'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/serializer.d.ts new file mode 100644 index 0000000..609f24f --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/serializer.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser/serializer'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/snapshot_to_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/snapshot_to_json.d.ts new file mode 100644 index 0000000..2ed408c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/snapshot_to_json.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser/snapshot_to_json'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/text_serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/text_serializer.d.ts new file mode 100644 index 0000000..a032af0 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/browser_lite/text_serializer.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser/text_serializer'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/byte_stream_reader.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/byte_stream_reader.d.ts new file mode 100644 index 0000000..566291c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/byte_stream_reader.d.ts @@ -0,0 +1,18 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BundleSource } from '../util/bundle_reader'; +export declare function toByteStreamReader(source: BundleSource, bytesPerRead?: number): ReadableStreamDefaultReader; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/connection.d.ts new file mode 100644 index 0000000..0fba574 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/connection.d.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseInfo } from '../core/database_info'; +import { Connection } from '../remote/connection'; +import { ConnectivityMonitor } from '../remote/connectivity_monitor'; +export declare function newConnectivityMonitor(): ConnectivityMonitor; +export declare function newConnection(databaseInfo: DatabaseInfo): Connection; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/dom.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/dom.d.ts new file mode 100644 index 0000000..d2a5319 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/dom.d.ts @@ -0,0 +1,20 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** The Platform's 'window' implementation or null if not available. */ +export declare function getWindow(): Window | null; +/** The Platform's 'document' implementation or null if not available. */ +export declare function getDocument(): Document | null; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/format_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/format_json.d.ts new file mode 100644 index 0000000..5e5f7ad --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/format_json.d.ts @@ -0,0 +1,18 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Formats an object as a JSON string, suitable for logging. */ +export declare function formatJSON(value: unknown): string; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/base64.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/base64.d.ts new file mode 100644 index 0000000..9ea2985 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/base64.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Converts a Base64 encoded string to a binary string. */ +export declare function decodeBase64(encoded: string): string; +/** Converts a binary string to a Base64 encoded string. */ +export declare function encodeBase64(raw: string): string; +/** True if and only if the Base64 conversion functions are available. */ +export declare function isBase64Available(): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/byte_stream_reader.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/byte_stream_reader.d.ts new file mode 100644 index 0000000..efbd79a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/byte_stream_reader.d.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BundleSource } from '../../util/bundle_reader'; +/** + * On Node, only supported data source is a `Uint8Array` for now. + */ +export declare function toByteStreamReader(source: BundleSource, bytesPerRead: number): ReadableStreamDefaultReader; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/connection.d.ts new file mode 100644 index 0000000..3be3c14 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/connection.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseInfo } from '../../core/database_info'; +import { Connection } from '../../remote/connection'; +import { ConnectivityMonitor } from '../../remote/connectivity_monitor'; +/** Loads the GRPC stack */ +export declare function newConnection(databaseInfo: DatabaseInfo): Connection; +/** Return the Platform-specific connectivity monitor. */ +export declare function newConnectivityMonitor(): ConnectivityMonitor; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/dom.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/dom.d.ts new file mode 100644 index 0000000..d2a5319 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/dom.d.ts @@ -0,0 +1,20 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** The Platform's 'window' implementation or null if not available. */ +export declare function getWindow(): Window | null; +/** The Platform's 'document' implementation or null if not available. */ +export declare function getDocument(): Document | null; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/format_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/format_json.d.ts new file mode 100644 index 0000000..5e5f7ad --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/format_json.d.ts @@ -0,0 +1,18 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Formats an object as a JSON string, suitable for logging. */ +export declare function formatJSON(value: unknown): string; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/grpc_connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/grpc_connection.d.ts new file mode 100644 index 0000000..30cd921 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/grpc_connection.d.ts @@ -0,0 +1,43 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as grpc from '@grpc/grpc-js'; +import { Token } from '../../api/credentials'; +import { DatabaseInfo } from '../../core/database_info'; +import { ResourcePath } from '../../model/path'; +import { Connection, Stream } from '../../remote/connection'; +/** + * A Connection implemented by GRPC-Node. + */ +export declare class GrpcConnection implements Connection { + private databaseInfo; + private readonly databasePath; + private readonly firestore; + private cachedStub; + get shouldResourcePathBeIncludedInRequest(): boolean; + constructor(protos: grpc.GrpcObject, databaseInfo: DatabaseInfo); + private ensureActiveStub; + invokeRPC(rpcName: string, path: ResourcePath, request: Req, authToken: Token | null, appCheckToken: Token | null): Promise; + invokeStreamingRPC(rpcName: string, path: ResourcePath, request: Req, authToken: Token | null, appCheckToken: Token | null, expectedResponseCount?: number): Promise; + openStream(rpcName: string, authToken: Token | null, appCheckToken: Token | null): Stream; + /** + * Closes and cleans up any resources associated with the GrpcConnection. + * If a gRPC client has been generated for this connection, the gRPC client + * is closed. Failure to call terminate on a GrpcConnection can result + * in leaked resources of the gRPC client. + */ + terminate(): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/load_protos.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/load_protos.d.ts new file mode 100644 index 0000000..f05a0e6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/load_protos.d.ts @@ -0,0 +1,28 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import * as grpc from '@grpc/grpc-js'; +import { IConversionOptions, Root } from 'protobufjs'; +/** Used by tests so we can match @grpc/proto-loader behavior. */ +export declare const protoLoaderOptions: IConversionOptions; +/** + * Loads the protocol buffer definitions for Firestore. + * + * @returns The GrpcObject representing our protos. + */ +export declare function loadProtos(): grpc.GrpcObject; +/** Used by tests so we can directly create ProtobufJS proto message objects from JSON protos. */ +export declare function loadRawProtos(): Root; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/random_bytes.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/random_bytes.d.ts new file mode 100644 index 0000000..672e612 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/random_bytes.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Generates `nBytes` of random bytes. + * + * If `nBytes < 0` , an error will be thrown. + */ +export declare function randomBytes(nBytes: number): Uint8Array; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/serializer.d.ts new file mode 100644 index 0000000..839e680 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/serializer.d.ts @@ -0,0 +1,20 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Return the Platform-specific serializer monitor. */ +import { DatabaseId } from '../../core/database_info'; +import { JsonProtoSerializer } from '../../remote/serializer'; +export declare function newSerializer(databaseId: DatabaseId): JsonProtoSerializer; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/snapshot_to_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/snapshot_to_json.d.ts new file mode 100644 index 0000000..6a75f06 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/snapshot_to_json.d.ts @@ -0,0 +1,23 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Return the Platform-specific build JSON bundle implementations. */ +import { Firestore } from '../../api/database'; +import { Query } from '../../core/query'; +import { DocumentData } from '../../lite-api/reference'; +import { Document } from '../../model/document'; +export declare function buildDocumentSnapshotJsonBundle(db: Firestore, document: Document, docData: DocumentData, path: string): string; +export declare function buildQuerySnapshotJsonBundle(db: Firestore, query: Query, bundleName: string, parent: string, paths: string[], docs: Document[], documentData: DocumentData[]): string; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/text_serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/text_serializer.d.ts new file mode 100644 index 0000000..f88ff0c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node/text_serializer.d.ts @@ -0,0 +1,25 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { TextDecoder, TextEncoder } from 'util'; +/** + * An instance of the Platform's 'TextEncoder' implementation. + */ +export declare function newTextEncoder(): TextEncoder; +/** + * An instance of the Platform's 'TextDecoder' implementation. + */ +export declare function newTextDecoder(): TextDecoder; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/base64.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/base64.d.ts new file mode 100644 index 0000000..2d95aff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/base64.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../node/base64'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/byte_stream_reader.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/byte_stream_reader.d.ts new file mode 100644 index 0000000..543020e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/byte_stream_reader.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../node/byte_stream_reader'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/connection.d.ts new file mode 100644 index 0000000..b347f61 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/connection.d.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseInfo } from '../../core/database_info'; +import { Connection } from '../../remote/connection'; +export { newConnectivityMonitor } from '../browser/connection'; +/** Initializes the HTTP connection for the REST API. */ +export declare function newConnection(databaseInfo: DatabaseInfo): Connection; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/dom.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/dom.d.ts new file mode 100644 index 0000000..6c880e0 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/dom.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../node/dom'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/format_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/format_json.d.ts new file mode 100644 index 0000000..428b6d9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/format_json.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../node/format_json'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/random_bytes.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/random_bytes.d.ts new file mode 100644 index 0000000..132614e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/random_bytes.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../node/random_bytes'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/serializer.d.ts new file mode 100644 index 0000000..dcf50ac --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/serializer.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser_lite/serializer'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/snapshot_to_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/snapshot_to_json.d.ts new file mode 100644 index 0000000..c85016c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/snapshot_to_json.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../node/snapshot_to_json'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/text_serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/text_serializer.d.ts new file mode 100644 index 0000000..3a5069e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/node_lite/text_serializer.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser_lite/text_serializer'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/random_bytes.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/random_bytes.d.ts new file mode 100644 index 0000000..672e612 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/random_bytes.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Generates `nBytes` of random bytes. + * + * If `nBytes < 0` , an error will be thrown. + */ +export declare function randomBytes(nBytes: number): Uint8Array; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/base64.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/base64.d.ts new file mode 100644 index 0000000..9ea2985 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/base64.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Converts a Base64 encoded string to a binary string. */ +export declare function decodeBase64(encoded: string): string; +/** Converts a binary string to a Base64 encoded string. */ +export declare function encodeBase64(raw: string): string; +/** True if and only if the Base64 conversion functions are available. */ +export declare function isBase64Available(): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/byte_stream_reader.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/byte_stream_reader.d.ts new file mode 100644 index 0000000..939290b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/byte_stream_reader.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { toByteStreamReader } from '../browser/byte_stream_reader'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/connection.d.ts new file mode 100644 index 0000000..da831d6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/connection.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { newConnection, newConnectivityMonitor } from '../browser/connection'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/dom.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/dom.d.ts new file mode 100644 index 0000000..4c629fc --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/dom.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { getWindow, getDocument } from '../browser/dom'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/format_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/format_json.d.ts new file mode 100644 index 0000000..d1d3dc7 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/format_json.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { formatJSON } from '../browser/format_json'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/random_bytes.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/random_bytes.d.ts new file mode 100644 index 0000000..6774017 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/random_bytes.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { randomBytes } from '../browser/random_bytes'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/serializer.d.ts new file mode 100644 index 0000000..c7a81ae --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/serializer.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { newSerializer } from '../browser/serializer'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/snapshot_to_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/snapshot_to_json.d.ts new file mode 100644 index 0000000..8ab87f6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/snapshot_to_json.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { buildDocumentSnapshotJsonBundle, buildQuerySnapshotJsonBundle } from '../browser/snapshot_to_json'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/text_serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/text_serializer.d.ts new file mode 100644 index 0000000..efcbff3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn/text_serializer.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { newTextEncoder, newTextDecoder } from '../browser/text_serializer'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/base64.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/base64.d.ts new file mode 100644 index 0000000..3d236cd --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/base64.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../rn/base64'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/byte_stream_reader.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/byte_stream_reader.d.ts new file mode 100644 index 0000000..9206b65 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/byte_stream_reader.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../rn/byte_stream_reader'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/connection.d.ts new file mode 100644 index 0000000..6509c0c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/connection.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser_lite/connection'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/dom.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/dom.d.ts new file mode 100644 index 0000000..0469362 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/dom.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../rn/dom'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/format_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/format_json.d.ts new file mode 100644 index 0000000..0a17cf8 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/format_json.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../rn/format_json'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/random_bytes.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/random_bytes.d.ts new file mode 100644 index 0000000..8ca59f3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/random_bytes.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../rn/random_bytes'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/serializer.d.ts new file mode 100644 index 0000000..dcf50ac --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/serializer.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser_lite/serializer'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/snapshot_to_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/snapshot_to_json.d.ts new file mode 100644 index 0000000..939290b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/snapshot_to_json.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export { toByteStreamReader } from '../browser/byte_stream_reader'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/text_serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/text_serializer.d.ts new file mode 100644 index 0000000..3a5069e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/rn_lite/text_serializer.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export * from '../browser_lite/text_serializer'; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/serializer.d.ts new file mode 100644 index 0000000..25f5533 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/serializer.d.ts @@ -0,0 +1,19 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseId } from '../core/database_info'; +import { JsonProtoSerializer } from '../remote/serializer'; +export declare function newSerializer(databaseId: DatabaseId): JsonProtoSerializer; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/snapshot_to_json.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/snapshot_to_json.d.ts new file mode 100644 index 0000000..83eadf0 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/snapshot_to_json.d.ts @@ -0,0 +1,28 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Firestore } from '../api/database'; +import { Query } from '../core/query'; +import { DocumentData } from '../lite-api/reference'; +import { Document } from '../model/document'; +/** + * Constructs the bundle data for a DocumentSnapshot used in its toJSON serialization. + */ +export declare function buildDocumentSnapshotJsonBundle(db: Firestore, document: Document, docData: DocumentData, path: string): string; +/** + * Constructs the bundle data for a QuerySnapshot used in its toJSON serialization. + */ +export declare function buildQuerySnapshotJsonBundle(db: Firestore, query: Query, bundleName: string, parent: string, paths: string[], docs: Document[], documentData: DocumentData[]): string; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/text_serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/text_serializer.d.ts new file mode 100644 index 0000000..47213fb --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/platform/text_serializer.d.ts @@ -0,0 +1,24 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An instance of the Platform's 'TextEncoder' implementation. + */ +export declare function newTextEncoder(): TextEncoder; +/** + * An instance of the Platform's 'TextDecoder' implementation. + */ +export declare function newTextDecoder(): TextDecoder; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/protos/firestore_bundle_proto.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/protos/firestore_bundle_proto.d.ts new file mode 100644 index 0000000..e3f7740 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/protos/firestore_bundle_proto.d.ts @@ -0,0 +1,72 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { StructuredQuery, Timestamp, Document } from './firestore_proto_api'; +/** Properties of a BundledQuery. */ +export interface BundledQuery { + /** BundledQuery parent */ + parent?: string | null; + /** BundledQuery structuredQuery */ + structuredQuery?: StructuredQuery | null; + /** BundledQuery limitType */ + limitType?: LimitType | null; +} +/** LimitType enum. */ +export type LimitType = 'FIRST' | 'LAST'; +/** Properties of a NamedQuery. */ +export interface NamedQuery { + /** NamedQuery name */ + name?: string | null; + /** NamedQuery bundledQuery */ + bundledQuery?: BundledQuery | null; + /** NamedQuery readTime */ + readTime?: Timestamp | null; +} +/** Properties of a BundledDocumentMetadata. */ +export interface BundledDocumentMetadata { + /** BundledDocumentMetadata name */ + name?: string | null; + /** BundledDocumentMetadata readTime */ + readTime?: Timestamp | null; + /** BundledDocumentMetadata exists */ + exists?: boolean | null; + /** The names of the queries in this bundle that this document matches to. */ + queries?: string[]; +} +/** Properties of a BundleMetadata. */ +export interface BundleMetadata { + /** BundleMetadata id */ + id?: string | null; + /** BundleMetadata createTime */ + createTime?: Timestamp | null; + /** BundleMetadata version */ + version?: number | null; + /** BundleMetadata totalDocuments */ + totalDocuments?: number | null; + /** BundleMetadata totalBytes */ + totalBytes?: number | null; +} +/** Properties of a BundleElement. */ +export interface BundleElement { + /** BundleElement metadata */ + metadata?: BundleMetadata | null; + /** BundleElement namedQuery */ + namedQuery?: NamedQuery | null; + /** BundleElement documentMetadata */ + documentMetadata?: BundledDocumentMetadata | null; + /** BundleElement document */ + document?: Document | null; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/protos/firestore_proto_api.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/protos/firestore_proto_api.d.ts new file mode 100644 index 0000000..5f37ee6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/protos/firestore_proto_api.d.ts @@ -0,0 +1,836 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare type ApiClientHookFactory = any; +export declare type PromiseRequestService = any; +export interface ApiClientObjectMap { + [k: string]: T; +} +export declare type Timestamp = string | { + seconds?: string | number; + nanos?: number; +}; +export declare type CompositeFilterOp = 'OPERATOR_UNSPECIFIED' | 'AND' | 'OR'; +export interface ICompositeFilterOpEnum { + OPERATOR_UNSPECIFIED: CompositeFilterOp; + AND: CompositeFilterOp; + values(): CompositeFilterOp[]; +} +export declare const CompositeFilterOpEnum: ICompositeFilterOpEnum; +export declare type FieldFilterOp = 'OPERATOR_UNSPECIFIED' | 'LESS_THAN' | 'LESS_THAN_OR_EQUAL' | 'GREATER_THAN' | 'GREATER_THAN_OR_EQUAL' | 'EQUAL' | 'NOT_EQUAL' | 'ARRAY_CONTAINS' | 'IN' | 'ARRAY_CONTAINS_ANY' | 'NOT_IN'; +export interface IFieldFilterOpEnum { + OPERATOR_UNSPECIFIED: FieldFilterOp; + LESS_THAN: FieldFilterOp; + LESS_THAN_OR_EQUAL: FieldFilterOp; + GREATER_THAN: FieldFilterOp; + GREATER_THAN_OR_EQUAL: FieldFilterOp; + EQUAL: FieldFilterOp; + NOT_EQUAL: FieldFilterOp; + ARRAY_CONTAINS: FieldFilterOp; + IN: FieldFilterOp; + ARRAY_CONTAINS_ANY: FieldFilterOp; + NOT_IN: FieldFilterOp; + values(): FieldFilterOp[]; +} +export declare const FieldFilterOpEnum: IFieldFilterOpEnum; +export declare type FieldTransformSetToServerValue = 'SERVER_VALUE_UNSPECIFIED' | 'REQUEST_TIME'; +export interface IFieldTransformSetToServerValueEnum { + SERVER_VALUE_UNSPECIFIED: FieldTransformSetToServerValue; + REQUEST_TIME: FieldTransformSetToServerValue; + values(): FieldTransformSetToServerValue[]; +} +export declare const FieldTransformSetToServerValueEnum: IFieldTransformSetToServerValueEnum; +export declare type IndexFieldMode = 'MODE_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING'; +export interface IIndexFieldModeEnum { + MODE_UNSPECIFIED: IndexFieldMode; + ASCENDING: IndexFieldMode; + DESCENDING: IndexFieldMode; + values(): IndexFieldMode[]; +} +export declare const IndexFieldModeEnum: IIndexFieldModeEnum; +export declare type IndexState = 'STATE_UNSPECIFIED' | 'CREATING' | 'READY' | 'ERROR'; +export interface IIndexStateEnum { + STATE_UNSPECIFIED: IndexState; + CREATING: IndexState; + READY: IndexState; + ERROR: IndexState; + values(): IndexState[]; +} +export declare const IndexStateEnum: IIndexStateEnum; +export declare type OrderDirection = 'DIRECTION_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING'; +export interface IOrderDirectionEnum { + DIRECTION_UNSPECIFIED: OrderDirection; + ASCENDING: OrderDirection; + DESCENDING: OrderDirection; + values(): OrderDirection[]; +} +export declare const OrderDirectionEnum: IOrderDirectionEnum; +export declare type TargetChangeTargetChangeType = 'NO_CHANGE' | 'ADD' | 'REMOVE' | 'CURRENT' | 'RESET'; +export interface ITargetChangeTargetChangeTypeEnum { + NO_CHANGE: TargetChangeTargetChangeType; + ADD: TargetChangeTargetChangeType; + REMOVE: TargetChangeTargetChangeType; + CURRENT: TargetChangeTargetChangeType; + RESET: TargetChangeTargetChangeType; + values(): TargetChangeTargetChangeType[]; +} +export declare const TargetChangeTargetChangeTypeEnum: ITargetChangeTargetChangeTypeEnum; +export declare type UnaryFilterOp = 'OPERATOR_UNSPECIFIED' | 'IS_NAN' | 'IS_NULL' | 'IS_NOT_NAN' | 'IS_NOT_NULL'; +export interface IUnaryFilterOpEnum { + OPERATOR_UNSPECIFIED: UnaryFilterOp; + IS_NAN: UnaryFilterOp; + IS_NULL: UnaryFilterOp; + IS_NOT_NAN: UnaryFilterOp; + IS_NOT_NULL: UnaryFilterOp; + values(): UnaryFilterOp[]; +} +export declare const UnaryFilterOpEnum: IUnaryFilterOpEnum; +export declare type ValueNullValue = 'NULL_VALUE'; +export interface IValueNullValueEnum { + NULL_VALUE: ValueNullValue; + values(): ValueNullValue[]; +} +export declare const ValueNullValueEnum: IValueNullValueEnum; +export declare namespace firestoreV1ApiClientInterfaces { + interface ArrayValue { + values?: Value[]; + } + interface BatchGetDocumentsRequest { + database?: string; + documents?: string[]; + mask?: DocumentMask; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface BatchGetDocumentsResponse { + found?: Document; + missing?: string; + transaction?: string; + readTime?: string; + } + interface BeginTransactionRequest { + options?: TransactionOptions; + } + interface BeginTransactionResponse { + transaction?: string; + } + interface CollectionSelector { + collectionId?: string; + allDescendants?: boolean; + } + interface CommitRequest { + database?: string; + writes?: Write[]; + transaction?: string; + } + interface CommitResponse { + writeResults?: WriteResult[]; + commitTime?: string; + } + interface CompositeFilter { + op?: CompositeFilterOp; + filters?: Filter[]; + } + interface Cursor { + values?: Value[]; + before?: boolean; + } + interface Document { + name?: string; + fields?: ApiClientObjectMap; + createTime?: Timestamp; + updateTime?: Timestamp; + } + interface DocumentChange { + document?: Document; + targetIds?: number[]; + removedTargetIds?: number[]; + } + interface DocumentDelete { + document?: string; + removedTargetIds?: number[]; + readTime?: Timestamp; + } + interface DocumentMask { + fieldPaths?: string[]; + } + interface DocumentRemove { + document?: string; + removedTargetIds?: number[]; + readTime?: string; + } + interface DocumentTransform { + document?: string; + fieldTransforms?: FieldTransform[]; + } + interface DocumentsTarget { + documents?: string[]; + } + interface Empty { + } + interface ExistenceFilter { + targetId?: number; + count?: number; + unchangedNames?: BloomFilter; + } + interface BloomFilter { + bits?: BitSequence; + hashCount?: number; + } + interface BitSequence { + bitmap?: string | Uint8Array; + padding?: number; + } + interface FieldFilter { + field?: FieldReference; + op?: FieldFilterOp; + value?: Value; + } + interface FieldReference { + fieldPath?: string; + } + interface FieldTransform { + fieldPath?: string; + setToServerValue?: FieldTransformSetToServerValue; + appendMissingElements?: ArrayValue; + removeAllFromArray?: ArrayValue; + increment?: Value; + } + interface Filter { + compositeFilter?: CompositeFilter; + fieldFilter?: FieldFilter; + unaryFilter?: UnaryFilter; + } + interface Index { + name?: string; + collectionId?: string; + fields?: IndexField[]; + state?: IndexState; + } + interface IndexField { + fieldPath?: string; + mode?: IndexFieldMode; + } + interface LatLng { + latitude?: number; + longitude?: number; + } + interface ListCollectionIdsRequest { + pageSize?: number; + pageToken?: string; + } + interface ListCollectionIdsResponse { + collectionIds?: string[]; + nextPageToken?: string; + } + interface ListDocumentsResponse { + documents?: Document[]; + nextPageToken?: string; + } + interface ListIndexesResponse { + indexes?: Index[]; + nextPageToken?: string; + } + interface ListenRequest { + addTarget?: Target; + removeTarget?: number; + labels?: ApiClientObjectMap; + } + interface ListenResponse { + targetChange?: TargetChange; + documentChange?: DocumentChange; + documentDelete?: DocumentDelete; + documentRemove?: DocumentRemove; + filter?: ExistenceFilter; + } + interface MapValue { + fields?: ApiClientObjectMap; + } + interface Operation { + name?: string; + metadata?: ApiClientObjectMap; + done?: boolean; + error?: Status; + response?: ApiClientObjectMap; + } + interface Order { + field?: FieldReference; + direction?: OrderDirection; + } + interface Precondition { + exists?: boolean; + updateTime?: Timestamp; + } + interface Projection { + fields?: FieldReference[]; + } + interface QueryTarget { + parent?: string; + structuredQuery?: StructuredQuery; + } + interface ReadOnly { + readTime?: string; + } + interface ReadWrite { + retryTransaction?: string; + } + interface RollbackRequest { + transaction?: string; + } + interface RunQueryRequest { + parent?: string; + structuredQuery?: StructuredQuery; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface RunQueryResponse { + transaction?: string; + document?: Document; + readTime?: string; + skippedResults?: number; + } + interface RunAggregationQueryRequest { + parent?: string; + structuredAggregationQuery?: StructuredAggregationQuery; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface RunAggregationQueryResponse { + result?: AggregationResult; + transaction?: string; + readTime?: string; + } + interface AggregationResult { + aggregateFields?: ApiClientObjectMap; + } + interface StructuredAggregationQuery { + structuredQuery?: StructuredQuery; + aggregations?: Aggregation[]; + } + interface Aggregation { + count?: Count; + sum?: Sum; + avg?: Avg; + alias?: string; + } + interface Count { + upTo?: number; + } + interface Sum { + field?: FieldReference; + } + interface Avg { + field?: FieldReference; + } + interface Status { + code?: number; + message?: string; + details?: Array>; + } + interface StructuredQuery { + select?: Projection; + from?: CollectionSelector[]; + where?: Filter; + orderBy?: Order[]; + startAt?: Cursor; + endAt?: Cursor; + offset?: number; + limit?: number | { + value: number; + }; + } + interface Target { + query?: QueryTarget; + documents?: DocumentsTarget; + resumeToken?: string | Uint8Array; + readTime?: Timestamp; + targetId?: number; + once?: boolean; + expectedCount?: number | { + value: number; + }; + } + interface TargetChange { + targetChangeType?: TargetChangeTargetChangeType; + targetIds?: number[]; + cause?: Status; + resumeToken?: string | Uint8Array; + readTime?: Timestamp; + } + interface TransactionOptions { + readOnly?: ReadOnly; + readWrite?: ReadWrite; + } + interface UnaryFilter { + op?: UnaryFilterOp; + field?: FieldReference; + } + interface Value { + nullValue?: ValueNullValue; + booleanValue?: boolean; + integerValue?: string | number; + doubleValue?: string | number; + timestampValue?: Timestamp; + stringValue?: string; + bytesValue?: string | Uint8Array; + referenceValue?: string; + geoPointValue?: LatLng; + arrayValue?: ArrayValue; + mapValue?: MapValue; + } + interface Write { + update?: Document; + delete?: string; + verify?: string; + transform?: DocumentTransform; + updateMask?: DocumentMask; + updateTransforms?: FieldTransform[]; + currentDocument?: Precondition; + } + interface WriteRequest { + streamId?: string; + writes?: Write[]; + streamToken?: string | Uint8Array; + labels?: ApiClientObjectMap; + } + interface WriteResponse { + streamId?: string; + streamToken?: string | Uint8Array; + writeResults?: WriteResult[]; + commitTime?: Timestamp; + } + interface WriteResult { + updateTime?: Timestamp; + transformResults?: Value[]; + } +} +export declare type ArrayValue = firestoreV1ApiClientInterfaces.ArrayValue; +export declare type BatchGetDocumentsRequest = firestoreV1ApiClientInterfaces.BatchGetDocumentsRequest; +export declare type BatchGetDocumentsResponse = firestoreV1ApiClientInterfaces.BatchGetDocumentsResponse; +export declare type BeginTransactionRequest = firestoreV1ApiClientInterfaces.BeginTransactionRequest; +export declare type BeginTransactionResponse = firestoreV1ApiClientInterfaces.BeginTransactionResponse; +export declare type BloomFilter = firestoreV1ApiClientInterfaces.BloomFilter; +export declare type CollectionSelector = firestoreV1ApiClientInterfaces.CollectionSelector; +export declare type CommitRequest = firestoreV1ApiClientInterfaces.CommitRequest; +export declare type CommitResponse = firestoreV1ApiClientInterfaces.CommitResponse; +export declare type CompositeFilter = firestoreV1ApiClientInterfaces.CompositeFilter; +export declare type Cursor = firestoreV1ApiClientInterfaces.Cursor; +export declare type Document = firestoreV1ApiClientInterfaces.Document; +export declare type DocumentChange = firestoreV1ApiClientInterfaces.DocumentChange; +export declare type DocumentDelete = firestoreV1ApiClientInterfaces.DocumentDelete; +export declare type DocumentMask = firestoreV1ApiClientInterfaces.DocumentMask; +export declare type DocumentRemove = firestoreV1ApiClientInterfaces.DocumentRemove; +export declare type DocumentTransform = firestoreV1ApiClientInterfaces.DocumentTransform; +export declare type DocumentsTarget = firestoreV1ApiClientInterfaces.DocumentsTarget; +export declare type Empty = firestoreV1ApiClientInterfaces.Empty; +export declare type ExistenceFilter = firestoreV1ApiClientInterfaces.ExistenceFilter; +export declare type FieldFilter = firestoreV1ApiClientInterfaces.FieldFilter; +export declare type FieldReference = firestoreV1ApiClientInterfaces.FieldReference; +export declare type FieldTransform = firestoreV1ApiClientInterfaces.FieldTransform; +export declare type Filter = firestoreV1ApiClientInterfaces.Filter; +export declare type Index = firestoreV1ApiClientInterfaces.Index; +export declare type IndexField = firestoreV1ApiClientInterfaces.IndexField; +export declare type LatLng = firestoreV1ApiClientInterfaces.LatLng; +export declare type ListCollectionIdsRequest = firestoreV1ApiClientInterfaces.ListCollectionIdsRequest; +export declare type ListCollectionIdsResponse = firestoreV1ApiClientInterfaces.ListCollectionIdsResponse; +export declare type ListDocumentsResponse = firestoreV1ApiClientInterfaces.ListDocumentsResponse; +export declare type ListIndexesResponse = firestoreV1ApiClientInterfaces.ListIndexesResponse; +export declare type ListenRequest = firestoreV1ApiClientInterfaces.ListenRequest; +export declare type ListenResponse = firestoreV1ApiClientInterfaces.ListenResponse; +export declare type MapValue = firestoreV1ApiClientInterfaces.MapValue; +export declare type Operation = firestoreV1ApiClientInterfaces.Operation; +export declare type Order = firestoreV1ApiClientInterfaces.Order; +export declare type Precondition = firestoreV1ApiClientInterfaces.Precondition; +export declare type Projection = firestoreV1ApiClientInterfaces.Projection; +export declare type QueryTarget = firestoreV1ApiClientInterfaces.QueryTarget; +export declare type ReadOnly = firestoreV1ApiClientInterfaces.ReadOnly; +export declare type ReadWrite = firestoreV1ApiClientInterfaces.ReadWrite; +export declare type RollbackRequest = firestoreV1ApiClientInterfaces.RollbackRequest; +export declare type RunQueryRequest = firestoreV1ApiClientInterfaces.RunQueryRequest; +export declare type RunQueryResponse = firestoreV1ApiClientInterfaces.RunQueryResponse; +export declare type RunAggregationQueryRequest = firestoreV1ApiClientInterfaces.RunAggregationQueryRequest; +export declare type Aggregation = firestoreV1ApiClientInterfaces.Aggregation; +export declare type RunAggregationQueryResponse = firestoreV1ApiClientInterfaces.RunAggregationQueryResponse; +export declare type Status = firestoreV1ApiClientInterfaces.Status; +export declare type StructuredQuery = firestoreV1ApiClientInterfaces.StructuredQuery; +export declare type Target = firestoreV1ApiClientInterfaces.Target; +export declare type TargetChange = firestoreV1ApiClientInterfaces.TargetChange; +export declare type TransactionOptions = firestoreV1ApiClientInterfaces.TransactionOptions; +export declare type UnaryFilter = firestoreV1ApiClientInterfaces.UnaryFilter; +export declare type Value = firestoreV1ApiClientInterfaces.Value; +export declare type Write = firestoreV1ApiClientInterfaces.Write; +export declare type WriteRequest = firestoreV1ApiClientInterfaces.WriteRequest; +export declare type WriteResponse = firestoreV1ApiClientInterfaces.WriteResponse; +export declare type WriteResult = firestoreV1ApiClientInterfaces.WriteResult; +export declare type ProjectsDatabasesDocumentsApiClient$Xgafv = '1' | '2'; +export interface IProjectsDatabasesDocumentsApiClient$XgafvEnum { + 1: ProjectsDatabasesDocumentsApiClient$Xgafv; + 2: ProjectsDatabasesDocumentsApiClient$Xgafv; + values(): ProjectsDatabasesDocumentsApiClient$Xgafv[]; +} +export declare const ProjectsDatabasesDocumentsApiClient$XgafvEnum: IProjectsDatabasesDocumentsApiClient$XgafvEnum; +export declare type ProjectsDatabasesDocumentsApiClientAlt = 'json' | 'media' | 'proto'; +export interface IProjectsDatabasesDocumentsApiClientAltEnum { + JSON: ProjectsDatabasesDocumentsApiClientAlt; + MEDIA: ProjectsDatabasesDocumentsApiClientAlt; + PROTO: ProjectsDatabasesDocumentsApiClientAlt; + values(): ProjectsDatabasesDocumentsApiClientAlt[]; +} +export declare const ProjectsDatabasesDocumentsApiClientAltEnum: IProjectsDatabasesDocumentsApiClientAltEnum; +export interface ProjectsDatabasesDocumentsBatchGetNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; +} +export interface ProjectsDatabasesDocumentsBeginTransactionNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; +} +export interface ProjectsDatabasesDocumentsCommitNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; +} +export interface ProjectsDatabasesDocumentsCreateDocumentNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; + documentId?: string; + maskFieldPaths?: string[]; +} +export interface ProjectsDatabasesDocumentsDeleteNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; + currentDocumentExists?: boolean; + currentDocumentUpdateTime?: string; +} +export interface ProjectsDatabasesDocumentsGetNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; + maskFieldPaths?: string[]; + transaction?: string; + readTime?: string; +} +export interface ProjectsDatabasesDocumentsListCollectionIdsNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; +} +export interface ProjectsDatabasesDocumentsListNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; + pageSize?: number; + pageToken?: string; + orderBy?: string; + maskFieldPaths?: string[]; + transaction?: string; + readTime?: string; + showMissing?: boolean; +} +export interface ProjectsDatabasesDocumentsListenNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; +} +export interface ProjectsDatabasesDocumentsPatchNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; + updateMaskFieldPaths?: string[]; + maskFieldPaths?: string[]; + currentDocumentExists?: boolean; + currentDocumentUpdateTime?: string; +} +export interface ProjectsDatabasesDocumentsRollbackNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; +} +export interface ProjectsDatabasesDocumentsRunQueryNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; +} +export interface ProjectsDatabasesDocumentsWriteNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesDocumentsApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesDocumentsApiClient$Xgafv; +} +export declare abstract class ProjectsDatabasesDocumentsApiClient { + private constructor(); + abstract batchGet(database: string, $requestBody: BatchGetDocumentsRequest, __namedParams__?: ProjectsDatabasesDocumentsBatchGetNamedParameters & object): Promise; + abstract beginTransaction(database: string, $requestBody: BeginTransactionRequest, __namedParams__?: ProjectsDatabasesDocumentsBeginTransactionNamedParameters & object): Promise; + abstract commit(database: string, $requestBody: CommitRequest, __namedParams__?: ProjectsDatabasesDocumentsCommitNamedParameters & object): Promise; + abstract createDocument(parent: string, collectionId: string, $requestBody: Document, __namedParams__?: ProjectsDatabasesDocumentsCreateDocumentNamedParameters & object): Promise; + abstract delete(name: string, __namedParams__?: ProjectsDatabasesDocumentsDeleteNamedParameters & object): Promise; + abstract get(name: string, __namedParams__?: ProjectsDatabasesDocumentsGetNamedParameters & object): Promise; + abstract list(parent: string, collectionId: string, __namedParams__?: ProjectsDatabasesDocumentsListNamedParameters & object): Promise; + abstract listCollectionIds(parent: string, $requestBody: ListCollectionIdsRequest, __namedParams__?: ProjectsDatabasesDocumentsListCollectionIdsNamedParameters & object): Promise; + abstract listen(database: string, $requestBody: ListenRequest, __namedParams__?: ProjectsDatabasesDocumentsListenNamedParameters & object): Promise; + abstract patch(name: string, $requestBody: Document, __namedParams__?: ProjectsDatabasesDocumentsPatchNamedParameters & object): Promise; + abstract rollback(database: string, $requestBody: RollbackRequest, __namedParams__?: ProjectsDatabasesDocumentsRollbackNamedParameters & object): Promise; + abstract runQuery(parent: string, $requestBody: RunQueryRequest, __namedParams__?: ProjectsDatabasesDocumentsRunQueryNamedParameters & object): Promise; + abstract write(database: string, $requestBody: WriteRequest, __namedParams__?: ProjectsDatabasesDocumentsWriteNamedParameters & object): Promise; +} +export declare class ProjectsDatabasesDocumentsApiClientImpl implements ProjectsDatabasesDocumentsApiClient { + private gapiVersion; + private $apiClient; + constructor(gapiVersion: string, gapiRequestService: PromiseRequestService, apiClientHookFactory?: ApiClientHookFactory | null); + batchGet(database: string, $requestBody: BatchGetDocumentsRequest, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsBatchGetNamedParameters & object): Promise; + beginTransaction(database: string, $requestBody: BeginTransactionRequest, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsBeginTransactionNamedParameters & object): Promise; + commit(database: string, $requestBody: CommitRequest, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsCommitNamedParameters & object): Promise; + createDocument(parent: string, collectionId: string, $requestBody: Document, { $Xgafv, access_token, alt, bearer_token, callback, documentId, fields, key, maskFieldPaths, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsCreateDocumentNamedParameters & object): Promise; + delete(name: string, { $Xgafv, access_token, alt, bearer_token, callback, currentDocumentExists, currentDocumentUpdateTime, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsDeleteNamedParameters & object): Promise; + get(name: string, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, maskFieldPaths, oauth_token, pp, prettyPrint, quotaUser, readTime, transaction, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsGetNamedParameters & object): Promise; + list(parent: string, collectionId: string, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, maskFieldPaths, oauth_token, orderBy, pageSize, pageToken, pp, prettyPrint, quotaUser, readTime, showMissing, transaction, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsListNamedParameters & object): Promise; + listCollectionIds(parent: string, $requestBody: ListCollectionIdsRequest, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsListCollectionIdsNamedParameters & object): Promise; + listen(database: string, $requestBody: ListenRequest, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsListenNamedParameters & object): Promise; + patch(name: string, $requestBody: Document, { $Xgafv, access_token, alt, bearer_token, callback, currentDocumentExists, currentDocumentUpdateTime, fields, key, maskFieldPaths, oauth_token, pp, prettyPrint, quotaUser, updateMaskFieldPaths, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsPatchNamedParameters & object): Promise; + rollback(database: string, $requestBody: RollbackRequest, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsRollbackNamedParameters & object): Promise; + runQuery(parent: string, $requestBody: RunQueryRequest, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsRunQueryNamedParameters & object): Promise; + write(database: string, $requestBody: WriteRequest, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesDocumentsWriteNamedParameters & object): Promise; +} +export declare type ProjectsDatabasesIndexesApiClient$Xgafv = '1' | '2'; +export interface IProjectsDatabasesIndexesApiClient$XgafvEnum { + 1: ProjectsDatabasesIndexesApiClient$Xgafv; + 2: ProjectsDatabasesIndexesApiClient$Xgafv; + values(): ProjectsDatabasesIndexesApiClient$Xgafv[]; +} +export declare const ProjectsDatabasesIndexesApiClient$XgafvEnum: IProjectsDatabasesIndexesApiClient$XgafvEnum; +export declare type ProjectsDatabasesIndexesApiClientAlt = 'json' | 'media' | 'proto'; +export interface IProjectsDatabasesIndexesApiClientAltEnum { + JSON: ProjectsDatabasesIndexesApiClientAlt; + MEDIA: ProjectsDatabasesIndexesApiClientAlt; + PROTO: ProjectsDatabasesIndexesApiClientAlt; + values(): ProjectsDatabasesIndexesApiClientAlt[]; +} +export declare const ProjectsDatabasesIndexesApiClientAltEnum: IProjectsDatabasesIndexesApiClientAltEnum; +export interface ProjectsDatabasesIndexesCreateNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesIndexesApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesIndexesApiClient$Xgafv; +} +export interface ProjectsDatabasesIndexesDeleteNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesIndexesApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesIndexesApiClient$Xgafv; +} +export interface ProjectsDatabasesIndexesGetNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesIndexesApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesIndexesApiClient$Xgafv; +} +export interface ProjectsDatabasesIndexesListNamedParameters { + access_token?: string; + alt?: ProjectsDatabasesIndexesApiClientAlt; + bearer_token?: string; + callback?: string; + fields?: string; + key?: string; + oauth_token?: string; + pp?: boolean; + prettyPrint?: boolean; + quotaUser?: string; + upload_protocol?: string; + uploadType?: string; + $Xgafv?: ProjectsDatabasesIndexesApiClient$Xgafv; + filter?: string; + pageSize?: number; + pageToken?: string; +} +export declare abstract class ProjectsDatabasesIndexesApiClient { + private constructor(); + abstract create(parent: string, $requestBody: Index, __namedParams__?: ProjectsDatabasesIndexesCreateNamedParameters & object): Promise; + abstract delete(name: string, __namedParams__?: ProjectsDatabasesIndexesDeleteNamedParameters & object): Promise; + abstract get(name: string, __namedParams__?: ProjectsDatabasesIndexesGetNamedParameters & object): Promise; + abstract list(parent: string, __namedParams__?: ProjectsDatabasesIndexesListNamedParameters & object): Promise; +} +export declare class ProjectsDatabasesIndexesApiClientImpl implements ProjectsDatabasesIndexesApiClient { + private gapiVersion; + private $apiClient; + constructor(gapiVersion: string, gapiRequestService: PromiseRequestService, apiClientHookFactory?: ApiClientHookFactory | null); + create(parent: string, $requestBody: Index, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesIndexesCreateNamedParameters & object): Promise; + delete(name: string, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesIndexesDeleteNamedParameters & object): Promise; + get(name: string, { $Xgafv, access_token, alt, bearer_token, callback, fields, key, oauth_token, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesIndexesGetNamedParameters & object): Promise; + list(parent: string, { $Xgafv, access_token, alt, bearer_token, callback, fields, filter, key, oauth_token, pageSize, pageToken, pp, prettyPrint, quotaUser, uploadType, upload_protocol }?: ProjectsDatabasesIndexesListNamedParameters & object): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/register.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/register.d.ts new file mode 100644 index 0000000..6f9da17 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/register.d.ts @@ -0,0 +1,17 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare function registerFirestore(variant?: string, useFetchStreams?: boolean): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/backoff.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/backoff.d.ts new file mode 100644 index 0000000..cb0bc76 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/backoff.d.ts @@ -0,0 +1,106 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AsyncQueue, TimerId } from '../util/async_queue'; +/** + * A helper for running delayed tasks following an exponential backoff curve + * between attempts. + * + * Each delay is made up of a "base" delay which follows the exponential + * backoff curve, and a +/- 50% "jitter" that is calculated and added to the + * base delay. This prevents clients from accidentally synchronizing their + * delays causing spikes of load to the backend. + */ +export declare class ExponentialBackoff { + /** + * The AsyncQueue to run backoff operations on. + */ + private readonly queue; + /** + * The ID to use when scheduling backoff operations on the AsyncQueue. + */ + private readonly timerId; + /** + * The initial delay (used as the base delay on the first retry attempt). + * Note that jitter will still be applied, so the actual delay could be as + * little as 0.5*initialDelayMs. + */ + private readonly initialDelayMs; + /** + * The multiplier to use to determine the extended base delay after each + * attempt. + */ + private readonly backoffFactor; + /** + * The maximum base delay after which no further backoff is performed. + * Note that jitter will still be applied, so the actual delay could be as + * much as 1.5*maxDelayMs. + */ + private readonly maxDelayMs; + private currentBaseMs; + private timerPromise; + /** The last backoff attempt, as epoch milliseconds. */ + private lastAttemptTime; + constructor( + /** + * The AsyncQueue to run backoff operations on. + */ + queue: AsyncQueue, + /** + * The ID to use when scheduling backoff operations on the AsyncQueue. + */ + timerId: TimerId, + /** + * The initial delay (used as the base delay on the first retry attempt). + * Note that jitter will still be applied, so the actual delay could be as + * little as 0.5*initialDelayMs. + */ + initialDelayMs?: number, + /** + * The multiplier to use to determine the extended base delay after each + * attempt. + */ + backoffFactor?: number, + /** + * The maximum base delay after which no further backoff is performed. + * Note that jitter will still be applied, so the actual delay could be as + * much as 1.5*maxDelayMs. + */ + maxDelayMs?: number); + /** + * Resets the backoff delay. + * + * The very next backoffAndWait() will have no delay. If it is called again + * (i.e. due to an error), initialDelayMs (plus jitter) will be used, and + * subsequent ones will increase according to the backoffFactor. + */ + reset(): void; + /** + * Resets the backoff delay to the maximum delay (e.g. for use after a + * RESOURCE_EXHAUSTED error). + */ + resetToMax(): void; + /** + * Returns a promise that resolves after currentDelayMs, and increases the + * delay for any subsequent attempts. If there was a pending backoff operation + * already, it will be canceled. + */ + backoffAndRun(op: () => Promise): void; + skipBackoff(): void; + cancel(): void; + /** Returns a random value in the range [-currentBaseMs/2, currentBaseMs/2] */ + private jitterDelayMs; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/bloom_filter.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/bloom_filter.d.ts new file mode 100644 index 0000000..d80eb83 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/bloom_filter.d.ts @@ -0,0 +1,34 @@ +/** + * @license + * Copyright 2022 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +export declare class BloomFilter { + readonly bitmap: Uint8Array; + readonly padding: number; + readonly hashCount: number; + readonly bitCount: number; + private readonly bitCountInInteger; + constructor(bitmap: Uint8Array, padding: number, hashCount: number); + private getBitIndex; + private isBitSet; + mightContain(value: string): boolean; + /** Create bloom filter for testing purposes only. */ + static create(bitCount: number, hashCount: number, contains: string[]): BloomFilter; + private insert; + private setBit; +} +export declare class BloomFilterError extends Error { + readonly name = "BloomFilterError"; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/connection.d.ts new file mode 100644 index 0000000..87afea6 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/connection.d.ts @@ -0,0 +1,99 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Token } from '../api/credentials'; +import { ResourcePath } from '../model/path'; +import { FirestoreError } from '../util/error'; +/** + * A connected RPC interface to a remote Datastore. + * + * Responsible for maintaining a connection to the backend (and informing when + * that connection state changes via onConnectionStateChange) and sending RPCs + * when possible. + * + * The Connection is not responsible for queueing RPCs to the backend when + * the connection is down. + * + * RPC messages are expected to be JavaScript objects representing the JSON that + * would be sent over the REST/JSON API to Datastore or used as input to + * creating the equivalent protocol buffers for GRPC. + */ +export interface Connection { + /** + * Invokes an RPC by name, given a request message as a JavaScript object + * representing the JSON to send. + * + * @param rpcName - the name of the RPC to invoke + * @param path - the path to invoke this RPC on. An array of path segments + * that will be encoded and joined with path separators when required. + * @param request - the Raw JSON object encoding of the request message + * @param token - the Token to use for the RPC. + * @returns a Promise containing the JSON object encoding of the response + */ + invokeRPC(rpcName: string, path: ResourcePath, request: Req, authToken: Token | null, appCheckToken: Token | null): Promise; + /** + * Invokes a streaming RPC by name, given a request message as a JavaScript + * object representing the JSON to send. The responses will be consumed to + * completion and then returned as an array. + * + * @param rpcName - the name of the RPC to invoke + * @param path - the path to invoke this RPC on. An array of path segments + * that will be encoded and joined with path separators when required. + * @param request - the Raw JSON object encoding of the request message + * @param token - the Token to use for the RPC. + * @returns a Promise containing an array with the JSON object encodings of the + * responses + */ + invokeStreamingRPC(rpcName: string, path: ResourcePath, request: Req, authToken: Token | null, appCheckToken: Token | null, expectedResponseCount?: number): Promise; + /** + * Opens a stream to the given stream RPC endpoint. Returns a stream which + * will try to open itself. + * @param rpcName - the name of the RPC to open the stream on + * @param token - the Token to use for the RPC. + */ + openStream(rpcName: string, authToken: Token | null, appCheckToken: Token | null): Stream; + /** + * Returns whether or not the implementation requires that the "path" of the resource + * (a document or a collection) be present in the request message. If true, then the + * request message must include the path. If false, then the request message must NOT + * include the path. + */ + readonly shouldResourcePathBeIncludedInRequest: boolean; + /** + * Closes and cleans up any resources associated with the connection. Actual + * resources cleaned are implementation specific. Failure to call `terminate` + * on a connection may result in resource leaks. + */ + terminate(): void; +} +/** + * A bidirectional stream that can be used to send an receive messages. + * + * A stream can be closed locally with close() or can be closed remotely or + * through network errors. onClose is guaranteed to be called. onOpen will be + * called once the stream is ready to send messages (which may or may not be + * before an actual connection to the backend has been established). The + * onConnected event is called when an actual, physical connection with the + * backend has been established, and may occur before or after the onOpen event. + */ +export interface Stream { + onConnected(callback: () => void): void; + onOpen(callback: () => void): void; + onClose(callback: (err?: FirestoreError) => void): void; + onMessage(callback: (msg: O) => void): void; + send(msg: I): void; + close(): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/connectivity_monitor.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/connectivity_monitor.d.ts new file mode 100644 index 0000000..e02b7d2 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/connectivity_monitor.d.ts @@ -0,0 +1,47 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * The set of network states is deliberately simplified -- we only care about + * states such that transition between them should break currently + * established connections. + */ +export declare const enum NetworkStatus { + AVAILABLE = 0, + UNAVAILABLE = 1 +} +export type ConnectivityMonitorCallback = (status: NetworkStatus) => void; +/** + * A base class for monitoring changes in network connectivity; it is expected + * that each platform will have its own system-dependent implementation. + */ +export interface ConnectivityMonitor { + /** + * Adds a callback to be called when connectivity changes. + * + * Callbacks are not made on the initial state of connectivity, since this + * monitor is primarily used for resetting backoff in the remote store when + * connectivity changes. As such, the initial connectivity state is + * irrelevant here. + */ + addCallback(callback: ConnectivityMonitorCallback): void; + /** + * Stops monitoring connectivity. After this call completes, no further + * callbacks will be triggered. After shutdown() is called, no further calls + * are allowed on this instance. + */ + shutdown(): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/connectivity_monitor_noop.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/connectivity_monitor_noop.d.ts new file mode 100644 index 0000000..42bb25c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/connectivity_monitor_noop.d.ts @@ -0,0 +1,21 @@ +/** + * @license + * Copyright 2019 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ConnectivityMonitor, NetworkStatus } from './connectivity_monitor'; +export declare class NoopConnectivityMonitor implements ConnectivityMonitor { + addCallback(callback: (status: NetworkStatus) => void): void; + shutdown(): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/datastore.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/datastore.d.ts new file mode 100644 index 0000000..fe095c0 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/datastore.d.ts @@ -0,0 +1,44 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { CredentialsProvider } from '../api/credentials'; +import { User } from '../auth/user'; +import { Aggregate } from '../core/aggregate'; +import { Query } from '../core/query'; +import { Document } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { Mutation } from '../model/mutation'; +import { ApiClientObjectMap, Value } from '../protos/firestore_proto_api'; +import { AsyncQueue } from '../util/async_queue'; +import { Connection } from './connection'; +import { PersistentListenStream, PersistentWriteStream, WatchStreamListener, WriteStreamListener } from './persistent_stream'; +import { JsonProtoSerializer } from './serializer'; +/** + * Datastore and its related methods are a wrapper around the external Google + * Cloud Datastore grpc API, which provides an interface that is more convenient + * for the rest of the client SDK architecture to consume. + */ +export declare abstract class Datastore { + abstract terminate(): void; + abstract serializer: JsonProtoSerializer; +} +export declare function newDatastore(authCredentials: CredentialsProvider, appCheckCredentials: CredentialsProvider, connection: Connection, serializer: JsonProtoSerializer): Datastore; +export declare function invokeCommitRpc(datastore: Datastore, mutations: Mutation[]): Promise; +export declare function invokeBatchGetDocumentsRpc(datastore: Datastore, keys: DocumentKey[]): Promise; +export declare function invokeRunQueryRpc(datastore: Datastore, query: Query): Promise; +export declare function invokeRunAggregationQueryRpc(datastore: Datastore, query: Query, aggregates: Aggregate[]): Promise>; +export declare function newPersistentWriteStream(datastore: Datastore, queue: AsyncQueue, listener: WriteStreamListener): PersistentWriteStream; +export declare function newPersistentWatchStream(datastore: Datastore, queue: AsyncQueue, listener: WatchStreamListener): PersistentListenStream; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/existence_filter.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/existence_filter.d.ts new file mode 100644 index 0000000..10ed5e5 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/existence_filter.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BloomFilter as ProtoBloomFilter } from '../protos/firestore_proto_api'; +export declare class ExistenceFilter { + count: number; + unchangedNames?: ProtoBloomFilter | undefined; + constructor(count: number, unchangedNames?: ProtoBloomFilter | undefined); +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/internal_serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/internal_serializer.d.ts new file mode 100644 index 0000000..cd1f08d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/internal_serializer.d.ts @@ -0,0 +1,46 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AggregateSpec } from '../lite-api/aggregate_types'; +import { Query } from '../lite-api/reference'; +/** + * @internal + * @private + * + * This function is for internal use only. + * + * Returns the `QueryTarget` representation of the given query. Returns `null` + * if the Firestore client associated with the given query has not been + * initialized or has been terminated. + * + * @param query - The Query to convert to proto representation. + */ +export declare function _internalQueryToProtoQueryTarget(query: Query): any; +/** + * @internal + * @private + * + * This function is for internal use only. + * + * Returns `RunAggregationQueryRequest` which contains the proto representation + * of the given aggregation query request. Returns null if the Firestore client + * associated with the given query has not been initialized or has been + * terminated. + * + * @param query - The Query to convert to proto representation. + * @param aggregateSpec - The set of aggregations and their aliases. + */ +export declare function _internalAggregationQueryToProtoRunAggregationQueryRequest(query: Query, aggregateSpec: AggregateSpecType): any; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/number_serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/number_serializer.d.ts new file mode 100644 index 0000000..cec4398 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/number_serializer.d.ts @@ -0,0 +1,36 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Value as ProtoValue } from '../protos/firestore_proto_api'; +/** Base interface for the Serializer implementation. */ +export interface Serializer { + readonly useProto3Json: boolean; +} +/** + * Returns an DoubleValue for `value` that is encoded based the serializer's + * `useProto3Json` setting. + */ +export declare function toDouble(serializer: Serializer, value: number): ProtoValue; +/** + * Returns an IntegerValue for `value`. + */ +export declare function toInteger(value: number): ProtoValue; +/** + * Returns a value for a number that's appropriate to put into a proto. + * The return value is an IntegerValue if it can safely represent the value, + * otherwise a DoubleValue is returned. + */ +export declare function toNumber(serializer: Serializer, value: number): ProtoValue; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/online_state_tracker.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/online_state_tracker.d.ts new file mode 100644 index 0000000..8a9bf8d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/online_state_tracker.d.ts @@ -0,0 +1,81 @@ +/** + * @license + * Copyright 2018 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { OnlineState } from '../core/types'; +import { AsyncQueue } from '../util/async_queue'; +import { FirestoreError } from '../util/error'; +/** + * A component used by the RemoteStore to track the OnlineState (that is, + * whether or not the client as a whole should be considered to be online or + * offline), implementing the appropriate heuristics. + * + * In particular, when the client is trying to connect to the backend, we + * allow up to MAX_WATCH_STREAM_FAILURES within ONLINE_STATE_TIMEOUT_MS for + * a connection to succeed. If we have too many failures or the timeout elapses, + * then we set the OnlineState to Offline, and the client will behave as if + * it is offline (get()s will return cached data, etc.). + */ +export declare class OnlineStateTracker { + private asyncQueue; + private onlineStateHandler; + /** The current OnlineState. */ + private state; + /** + * A count of consecutive failures to open the stream. If it reaches the + * maximum defined by MAX_WATCH_STREAM_FAILURES, we'll set the OnlineState to + * Offline. + */ + private watchStreamFailures; + /** + * A timer that elapses after ONLINE_STATE_TIMEOUT_MS, at which point we + * transition from OnlineState.Unknown to OnlineState.Offline without waiting + * for the stream to actually fail (MAX_WATCH_STREAM_FAILURES times). + */ + private onlineStateTimer; + /** + * Whether the client should log a warning message if it fails to connect to + * the backend (initially true, cleared after a successful stream, or if we've + * logged the message already). + */ + private shouldWarnClientIsOffline; + constructor(asyncQueue: AsyncQueue, onlineStateHandler: (onlineState: OnlineState) => void); + /** + * Called by RemoteStore when a watch stream is started (including on each + * backoff attempt). + * + * If this is the first attempt, it sets the OnlineState to Unknown and starts + * the onlineStateTimer. + */ + handleWatchStreamStart(): void; + /** + * Updates our OnlineState as appropriate after the watch stream reports a + * failure. The first failure moves us to the 'Unknown' state. We then may + * allow multiple failures (based on MAX_WATCH_STREAM_FAILURES) before we + * actually transition to the 'Offline' state. + */ + handleWatchStreamFailure(error: FirestoreError): void; + /** + * Explicitly sets the OnlineState to the specified state. + * + * Note that this resets our timers / failure counters, etc. used by our + * Offline heuristics, so must not be used in place of + * handleWatchStreamStart() and handleWatchStreamFailure(). + */ + set(newState: OnlineState): void; + private setAndBroadcast; + private logClientOfflineWarningIfNecessary; + private clearOnlineStateTimer; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/persistent_stream.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/persistent_stream.d.ts new file mode 100644 index 0000000..aacaf2d --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/persistent_stream.d.ts @@ -0,0 +1,308 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { CredentialsProvider, Token } from '../api/credentials'; +import { User } from '../auth/user'; +import { SnapshotVersion } from '../core/snapshot_version'; +import { TargetId } from '../core/types'; +import { TargetData } from '../local/target_data'; +import { Mutation, MutationResult } from '../model/mutation'; +import { ListenRequest as ProtoListenRequest, ListenResponse as ProtoListenResponse, WriteRequest as ProtoWriteRequest, WriteResponse as ProtoWriteResponse } from '../protos/firestore_proto_api'; +import { AsyncQueue, TimerId } from '../util/async_queue'; +import { FirestoreError } from '../util/error'; +import { ExponentialBackoff } from './backoff'; +import { Connection, Stream } from './connection'; +import { JsonProtoSerializer } from './serializer'; +import { WatchChange } from './watch_change'; +export interface WriteRequest extends ProtoWriteRequest { + database?: string; +} +/** + * Provides a common interface that is shared by the listeners for stream + * events by the concrete implementation classes. + */ +export interface PersistentStreamListener { + /** + * Called after receiving an acknowledgement from the server, confirming that + * we are able to connect to it. + */ + onConnected: () => Promise; + /** + * Called after the stream was established and can accept outgoing + * messages + */ + onOpen: () => Promise; + /** + * Called after the stream has closed. If there was an error, the + * FirestoreError will be set. + */ + onClose: (err?: FirestoreError) => Promise; +} +/** + * A PersistentStream is an abstract base class that represents a streaming RPC + * to the Firestore backend. It's built on top of the connections own support + * for streaming RPCs, and adds several critical features for our clients: + * + * - Exponential backoff on failure + * - Authentication via CredentialsProvider + * - Dispatching all callbacks into the shared worker queue + * - Closing idle streams after 60 seconds of inactivity + * + * Subclasses of PersistentStream implement serialization of models to and + * from the JSON representation of the protocol buffers for a specific + * streaming RPC. + * + * ## Starting and Stopping + * + * Streaming RPCs are stateful and need to be start()ed before messages can + * be sent and received. The PersistentStream will call the onOpen() function + * of the listener once the stream is ready to accept requests. + * + * Should a start() fail, PersistentStream will call the registered onClose() + * listener with a FirestoreError indicating what went wrong. + * + * A PersistentStream can be started and stopped repeatedly. + * + * Generic types: + * SendType: The type of the outgoing message of the underlying + * connection stream + * ReceiveType: The type of the incoming message of the underlying + * connection stream + * ListenerType: The type of the listener that will be used for callbacks + */ +export declare abstract class PersistentStream { + private queue; + private idleTimerId; + private healthTimerId; + protected connection: Connection; + private authCredentialsProvider; + private appCheckCredentialsProvider; + protected listener: ListenerType; + private state; + /** + * A close count that's incremented every time the stream is closed; used by + * getCloseGuardedDispatcher() to invalidate callbacks that happen after + * close. + */ + private closeCount; + private idleTimer; + private healthCheck; + private stream; + protected backoff: ExponentialBackoff; + constructor(queue: AsyncQueue, connectionTimerId: TimerId, idleTimerId: TimerId, healthTimerId: TimerId, connection: Connection, authCredentialsProvider: CredentialsProvider, appCheckCredentialsProvider: CredentialsProvider, listener: ListenerType); + /** + * Count of response messages received. + */ + protected responseCount: number; + /** + * Returns true if start() has been called and no error has occurred. True + * indicates the stream is open or in the process of opening (which + * encompasses respecting backoff, getting auth tokens, and starting the + * actual RPC). Use isOpen() to determine if the stream is open and ready for + * outbound requests. + */ + isStarted(): boolean; + /** + * Returns true if the underlying RPC is open (the onOpen() listener has been + * called) and the stream is ready for outbound requests. + */ + isOpen(): boolean; + /** + * Starts the RPC. Only allowed if isStarted() returns false. The stream is + * not immediately ready for use: onOpen() will be invoked when the RPC is + * ready for outbound requests, at which point isOpen() will return true. + * + * When start returns, isStarted() will return true. + */ + start(): void; + /** + * Stops the RPC. This call is idempotent and allowed regardless of the + * current isStarted() state. + * + * When stop returns, isStarted() and isOpen() will both return false. + */ + stop(): Promise; + /** + * After an error the stream will usually back off on the next attempt to + * start it. If the error warrants an immediate restart of the stream, the + * sender can use this to indicate that the receiver should not back off. + * + * Each error will call the onClose() listener. That function can decide to + * inhibit backoff if required. + */ + inhibitBackoff(): void; + /** + * Marks this stream as idle. If no further actions are performed on the + * stream for one minute, the stream will automatically close itself and + * notify the stream's onClose() handler with Status.OK. The stream will then + * be in a !isStarted() state, requiring the caller to start the stream again + * before further use. + * + * Only streams that are in state 'Open' can be marked idle, as all other + * states imply pending network operations. + */ + markIdle(): void; + /** Sends a message to the underlying stream. */ + protected sendRequest(msg: SendType): void; + /** Called by the idle timer when the stream should close due to inactivity. */ + private handleIdleCloseTimer; + /** Marks the stream as active again. */ + private cancelIdleCheck; + /** Cancels the health check delayed operation. */ + private cancelHealthCheck; + /** + * Closes the stream and cleans up as necessary: + * + * * closes the underlying GRPC stream; + * * calls the onClose handler with the given 'error'; + * * sets internal stream state to 'finalState'; + * * adjusts the backoff timer based on the error + * + * A new stream can be opened by calling start(). + * + * @param finalState - the intended state of the stream after closing. + * @param error - the error the connection was closed with. + */ + private close; + /** + * Can be overridden to perform additional cleanup before the stream is closed. + * Calling super.tearDown() is not required. + */ + protected tearDown(): void; + /** + * Used by subclasses to start the concrete RPC and return the underlying + * connection stream. + */ + protected abstract startRpc(authToken: Token | null, appCheckToken: Token | null): Stream; + /** + * Called when the stream receives first message. + * The function will be called on the right queue and must return a Promise. + * @param message - The message received from the stream. + */ + protected abstract onFirst(message: ReceiveType): Promise; + /** + * Called on subsequent messages after the stream has received first message. + * The function will be called on the right queue and must return a Promise. + * @param message - The message received from the stream. + */ + protected abstract onNext(message: ReceiveType): Promise; + private auth; + private startStream; + private performBackoff; + handleStreamClose(error?: FirestoreError): Promise; + /** + * Returns a "dispatcher" function that dispatches operations onto the + * AsyncQueue but only runs them if closeCount remains unchanged. This allows + * us to turn auth / stream callbacks into no-ops if the stream is closed / + * re-opened, etc. + */ + private getCloseGuardedDispatcher; +} +/** Listener for the PersistentWatchStream */ +export interface WatchStreamListener extends PersistentStreamListener { + /** + * Called on a watchChange. The snapshot parameter will be MIN if the watch + * change did not have a snapshot associated with it. + */ + onWatchChange: (watchChange: WatchChange, snapshot: SnapshotVersion) => Promise; +} +/** + * A PersistentStream that implements the Listen RPC. + * + * Once the Listen stream has called the onOpen() listener, any number of + * listen() and unlisten() calls can be made to control what changes will be + * sent from the server for ListenResponses. + */ +export declare class PersistentListenStream extends PersistentStream { + private serializer; + constructor(queue: AsyncQueue, connection: Connection, authCredentials: CredentialsProvider, appCheckCredentials: CredentialsProvider, serializer: JsonProtoSerializer, listener: WatchStreamListener); + protected startRpc(authToken: Token | null, appCheckToken: Token | null): Stream; + protected onFirst(watchChangeProto: ProtoListenResponse): Promise; + protected onNext(watchChangeProto: ProtoListenResponse): Promise; + /** + * Registers interest in the results of the given target. If the target + * includes a resumeToken it will be included in the request. Results that + * affect the target will be streamed back as WatchChange messages that + * reference the targetId. + */ + watch(targetData: TargetData): void; + /** + * Unregisters interest in the results of the target associated with the + * given targetId. + */ + unwatch(targetId: TargetId): void; +} +/** Listener for the PersistentWriteStream */ +export interface WriteStreamListener extends PersistentStreamListener { + /** + * Called by the PersistentWriteStream upon a successful handshake response + * from the server, which is the receiver's cue to send any pending writes. + */ + onHandshakeComplete: () => Promise; + /** + * Called by the PersistentWriteStream upon receiving a StreamingWriteResponse + * from the server that contains a mutation result. + */ + onMutationResult: (commitVersion: SnapshotVersion, results: MutationResult[]) => Promise; +} +/** + * A Stream that implements the Write RPC. + * + * The Write RPC requires the caller to maintain special streamToken + * state in between calls, to help the server understand which responses the + * client has processed by the time the next request is made. Every response + * will contain a streamToken; this value must be passed to the next + * request. + * + * After calling start() on this stream, the next request must be a handshake, + * containing whatever streamToken is on hand. Once a response to this + * request is received, all pending mutations may be submitted. When + * submitting multiple batches of mutations at the same time, it's + * okay to use the same streamToken for the calls to writeMutations. + * + * TODO(b/33271235): Use proto types + */ +export declare class PersistentWriteStream extends PersistentStream { + private serializer; + constructor(queue: AsyncQueue, connection: Connection, authCredentials: CredentialsProvider, appCheckCredentials: CredentialsProvider, serializer: JsonProtoSerializer, listener: WriteStreamListener); + /** + * The last received stream token from the server, used to acknowledge which + * responses the client has processed. Stream tokens are opaque checkpoint + * markers whose only real value is their inclusion in the next request. + * + * PersistentWriteStream manages propagating this value from responses to the + * next request. + */ + private lastStreamToken; + /** + * Tracks whether or not a handshake has been successfully exchanged and + * the stream is ready to accept mutations. + */ + get handshakeComplete(): boolean; + start(): void; + protected tearDown(): void; + protected startRpc(authToken: Token | null, appCheckToken: Token | null): Stream; + protected onFirst(responseProto: ProtoWriteResponse): Promise; + protected onNext(responseProto: ProtoWriteResponse): Promise; + /** + * Sends an initial streamToken to the server, performing the handshake + * required to make the StreamingWrite RPC work. Subsequent + * calls should wait until onHandshakeComplete was called. + */ + writeHandshake(): void; + /** Sends a group of mutations to the Firestore backend to apply. */ + writeMutations(mutations: Mutation[]): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/remote_event.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/remote_event.d.ts new file mode 100644 index 0000000..9bafaf3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/remote_event.d.ts @@ -0,0 +1,156 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { SnapshotVersion } from '../core/snapshot_version'; +import { TargetId } from '../core/types'; +import { TargetPurpose } from '../local/target_data'; +import { DocumentKeySet, MutableDocumentMap } from '../model/collections'; +import { ByteString } from '../util/byte_string'; +import { SortedMap } from '../util/sorted_map'; +/** + * An event from the RemoteStore. It is split into targetChanges (changes to the + * state or the set of documents in our watched targets) and documentUpdates + * (changes to the actual documents). + */ +export declare class RemoteEvent { + /** + * The snapshot version this event brings us up to, or MIN if not set. + */ + readonly snapshotVersion: SnapshotVersion; + /** + * A map from target to changes to the target. See TargetChange. + */ + readonly targetChanges: Map; + /** + * A map of targets that is known to be inconsistent, and the purpose for + * re-listening. Listens for these targets should be re-established without + * resume tokens. + */ + readonly targetMismatches: SortedMap; + /** + * A set of which documents have changed or been deleted, along with the + * doc's new values (if not deleted). + */ + readonly documentUpdates: MutableDocumentMap; + /** + * A set of which document updates are due only to limbo resolution targets. + */ + readonly resolvedLimboDocuments: DocumentKeySet; + constructor( + /** + * The snapshot version this event brings us up to, or MIN if not set. + */ + snapshotVersion: SnapshotVersion, + /** + * A map from target to changes to the target. See TargetChange. + */ + targetChanges: Map, + /** + * A map of targets that is known to be inconsistent, and the purpose for + * re-listening. Listens for these targets should be re-established without + * resume tokens. + */ + targetMismatches: SortedMap, + /** + * A set of which documents have changed or been deleted, along with the + * doc's new values (if not deleted). + */ + documentUpdates: MutableDocumentMap, + /** + * A set of which document updates are due only to limbo resolution targets. + */ + resolvedLimboDocuments: DocumentKeySet); + /** + * HACK: Views require RemoteEvents in order to determine whether the view is + * CURRENT, but secondary tabs don't receive remote events. So this method is + * used to create a synthesized RemoteEvent that can be used to apply a + * CURRENT status change to a View, for queries executed in a different tab. + */ + static createSynthesizedRemoteEventForCurrentChange(targetId: TargetId, current: boolean, resumeToken: ByteString): RemoteEvent; +} +/** + * A TargetChange specifies the set of changes for a specific target as part of + * a RemoteEvent. These changes track which documents are added, modified or + * removed, as well as the target's resume token and whether the target is + * marked CURRENT. + * The actual changes *to* documents are not part of the TargetChange since + * documents may be part of multiple targets. + */ +export declare class TargetChange { + /** + * An opaque, server-assigned token that allows watching a query to be resumed + * after disconnecting without retransmitting all the data that matches the + * query. The resume token essentially identifies a point in time from which + * the server should resume sending results. + */ + readonly resumeToken: ByteString; + /** + * The "current" (synced) status of this target. Note that "current" + * has special meaning in the RPC protocol that implies that a target is + * both up-to-date and consistent with the rest of the watch stream. + */ + readonly current: boolean; + /** + * The set of documents that were newly assigned to this target as part of + * this remote event. + */ + readonly addedDocuments: DocumentKeySet; + /** + * The set of documents that were already assigned to this target but received + * an update during this remote event. + */ + readonly modifiedDocuments: DocumentKeySet; + /** + * The set of documents that were removed from this target as part of this + * remote event. + */ + readonly removedDocuments: DocumentKeySet; + constructor( + /** + * An opaque, server-assigned token that allows watching a query to be resumed + * after disconnecting without retransmitting all the data that matches the + * query. The resume token essentially identifies a point in time from which + * the server should resume sending results. + */ + resumeToken: ByteString, + /** + * The "current" (synced) status of this target. Note that "current" + * has special meaning in the RPC protocol that implies that a target is + * both up-to-date and consistent with the rest of the watch stream. + */ + current: boolean, + /** + * The set of documents that were newly assigned to this target as part of + * this remote event. + */ + addedDocuments: DocumentKeySet, + /** + * The set of documents that were already assigned to this target but received + * an update during this remote event. + */ + modifiedDocuments: DocumentKeySet, + /** + * The set of documents that were removed from this target as part of this + * remote event. + */ + removedDocuments: DocumentKeySet); + /** + * This method is used to create a synthesized TargetChanges that can be used to + * apply a CURRENT status change to a View (for queries executed in a different + * tab) or for new queries (to raise snapshots with correct CURRENT status). + */ + static createSynthesizedTargetChangeForCurrentChange(targetId: TargetId, current: boolean, resumeToken: ByteString): TargetChange; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/remote_store.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/remote_store.d.ts new file mode 100644 index 0000000..c6c2416 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/remote_store.d.ts @@ -0,0 +1,85 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { OnlineState, TargetId } from '../core/types'; +import { LocalStore } from '../local/local_store'; +import { TargetData } from '../local/target_data'; +import { AsyncQueue } from '../util/async_queue'; +import { ConnectivityMonitor } from './connectivity_monitor'; +import { Datastore } from './datastore'; +import { RemoteSyncer } from './remote_syncer'; +/** + * RemoteStore - An interface to remotely stored data, basically providing a + * wrapper around the Datastore that is more reliable for the rest of the + * system. + * + * RemoteStore is responsible for maintaining the connection to the server. + * - maintaining a list of active listens. + * - reconnecting when the connection is dropped. + * - resuming all the active listens on reconnect. + * + * RemoteStore handles all incoming events from the Datastore. + * - listening to the watch stream and repackaging the events as RemoteEvents + * - notifying SyncEngine of any changes to the active listens. + * + * RemoteStore takes writes from other components and handles them reliably. + * - pulling pending mutations from LocalStore and sending them to Datastore. + * - retrying mutations that failed because of network problems. + * - acking mutations to the SyncEngine once they are accepted or rejected. + */ +export interface RemoteStore { + /** + * SyncEngine to notify of watch and write events. This must be set + * immediately after construction. + */ + remoteSyncer: RemoteSyncer; +} +export declare function newRemoteStore(localStore: LocalStore, datastore: Datastore, asyncQueue: AsyncQueue, onlineStateHandler: (onlineState: OnlineState) => void, connectivityMonitor: ConnectivityMonitor): RemoteStore; +/** Re-enables the network. Idempotent. */ +export declare function remoteStoreEnableNetwork(remoteStore: RemoteStore): Promise; +/** + * Temporarily disables the network. The network can be re-enabled using + * enableNetwork(). + */ +export declare function remoteStoreDisableNetwork(remoteStore: RemoteStore): Promise; +export declare function remoteStoreShutdown(remoteStore: RemoteStore): Promise; +/** + * Starts new listen for the given target. Uses resume token if provided. It + * is a no-op if the target of given `TargetData` is already being listened to. + */ +export declare function remoteStoreListen(remoteStore: RemoteStore, targetData: TargetData): void; +/** + * Removes the listen from server. It is a no-op if the given target id is + * not being listened to. + */ +export declare function remoteStoreUnlisten(remoteStore: RemoteStore, targetId: TargetId): void; +export declare function canUseNetwork(remoteStore: RemoteStore): boolean; +/** + * Attempts to fill our write pipeline with writes from the LocalStore. + * + * Called internally to bootstrap or refill the write pipeline and by + * SyncEngine whenever there are new mutations to process. + * + * Starts the write stream if necessary. + */ +export declare function fillWritePipeline(remoteStore: RemoteStore): Promise; +export declare function outstandingWrites(remoteStore: RemoteStore): number; +export declare function remoteStoreHandleCredentialChange(remoteStore: RemoteStore, user: User): Promise; +/** + * Toggles the network state when the client gains or loses its primary lease. + */ +export declare function remoteStoreApplyPrimaryState(remoteStore: RemoteStore, isPrimary: boolean): Promise; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/remote_syncer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/remote_syncer.d.ts new file mode 100644 index 0000000..949bc21 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/remote_syncer.d.ts @@ -0,0 +1,68 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { User } from '../auth/user'; +import { BatchId, TargetId } from '../core/types'; +import { DocumentKeySet } from '../model/collections'; +import { MutationBatchResult } from '../model/mutation_batch'; +import { FirestoreError } from '../util/error'; +import { RemoteEvent } from './remote_event'; +/** + * An interface that describes the actions the RemoteStore needs to perform on + * a cooperating synchronization engine. + */ +export interface RemoteSyncer { + /** + * Applies one remote event to the sync engine, notifying any views of the + * changes, and releasing any pending mutation batches that would become + * visible because of the snapshot version the remote event contains. + */ + applyRemoteEvent?(remoteEvent: RemoteEvent): Promise; + /** + * Rejects the listen for the given targetID. This can be triggered by the + * backend for any active target. + * + * @param targetId - The targetID corresponds to one previously initiated by + * the user as part of TargetData passed to listen() on RemoteStore. + * @param error - A description of the condition that has forced the rejection. + * Nearly always this will be an indication that the user is no longer + * authorized to see the data matching the target. + */ + rejectListen?(targetId: TargetId, error: FirestoreError): Promise; + /** + * Applies the result of a successful write of a mutation batch to the sync + * engine, emitting snapshots in any views that the mutation applies to, and + * removing the batch from the mutation queue. + */ + applySuccessfulWrite?(result: MutationBatchResult): Promise; + /** + * Rejects the batch, removing the batch from the mutation queue, recomputing + * the local view of any documents affected by the batch and then, emitting + * snapshots with the reverted value. + */ + rejectFailedWrite?(batchId: BatchId, error: FirestoreError): Promise; + /** + * Returns the set of remote document keys for the given target ID. This list + * includes the documents that were assigned to the target when we received + * the last snapshot. + */ + getRemoteKeysForTarget?(targetId: TargetId): DocumentKeySet; + /** + * Updates all local state to match the pending mutations for the given user. + * May be called repeatedly for the same user. + */ + handleCredentialChange?(user: User): Promise; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/rest_connection.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/rest_connection.d.ts new file mode 100644 index 0000000..1e58386 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/rest_connection.d.ts @@ -0,0 +1,53 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Token } from '../api/credentials'; +import { DatabaseId, DatabaseInfo } from '../core/database_info'; +import { ResourcePath } from '../model/path'; +import { StringMap } from '../util/types'; +import { Connection, Stream } from './connection'; +/** + * Base class for all Rest-based connections to the backend (WebChannel and + * HTTP). + */ +export declare abstract class RestConnection implements Connection { + private readonly databaseInfo; + protected readonly databaseId: DatabaseId; + protected readonly baseUrl: string; + private readonly databasePath; + private readonly requestParams; + get shouldResourcePathBeIncludedInRequest(): boolean; + constructor(databaseInfo: DatabaseInfo); + invokeRPC(rpcName: string, path: ResourcePath, req: Req, authToken: Token | null, appCheckToken: Token | null): Promise; + invokeStreamingRPC(rpcName: string, path: ResourcePath, request: Req, authToken: Token | null, appCheckToken: Token | null, expectedResponseCount?: number): Promise; + abstract openStream(rpcName: string, authToken: Token | null, appCheckToken: Token | null): Stream; + /** + * Modifies the headers for a request, adding any authorization token if + * present and any additional headers for the request. + */ + protected modifyHeadersForRequest(headers: StringMap, authToken: Token | null, appCheckToken: Token | null): void; + /** + * Performs an RPC request using an implementation specific networking layer. + */ + protected abstract performRPCRequest(rpcName: string, url: string, headers: StringMap, body: Req, _forwardCredentials: boolean): Promise; + private makeUrl; + /** + * Closes and cleans up any resources associated with the connection. This + * implementation is a no-op because there are no resources associated + * with the RestConnection that need to be cleaned up. + */ + terminate(): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/rpc_error.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/rpc_error.d.ts new file mode 100644 index 0000000..90d075c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/rpc_error.d.ts @@ -0,0 +1,74 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Code } from '../util/error'; +/** + * Determines whether an error code represents a permanent error when received + * in response to a non-write operation. + * + * See isPermanentWriteError for classifying write errors. + */ +export declare function isPermanentError(code: Code): boolean; +/** + * Determines whether an error code represents a permanent error when received + * in response to a write operation. + * + * Write operations must be handled specially because as of b/119437764, ABORTED + * errors on the write stream should be retried too (even though ABORTED errors + * are not generally retryable). + * + * Note that during the initial handshake on the write stream an ABORTED error + * signals that we should discard our stream token (i.e. it is permanent). This + * means a handshake error should be classified with isPermanentError, above. + */ +export declare function isPermanentWriteError(code: Code): boolean; +/** + * Maps an error Code from a GRPC status identifier like 'NOT_FOUND'. + * + * @returns The Code equivalent to the given status string or undefined if + * there is no match. + */ +export declare function mapCodeFromRpcStatus(status: string): Code | undefined; +/** + * Maps an error Code from GRPC status code number, like 0, 1, or 14. These + * are not the same as HTTP status codes. + * + * @returns The Code equivalent to the given GRPC status code. Fails if there + * is no match. + */ +export declare function mapCodeFromRpcCode(code: number | undefined): Code; +/** + * Maps an RPC code from a Code. This is the reverse operation from + * mapCodeFromRpcCode and should really only be used in tests. + */ +export declare function mapRpcCodeFromCode(code: Code | undefined): number; +/** + * Converts an HTTP Status Code to the equivalent error code. + * + * @param status - An HTTP Status Code, like 200, 404, 503, etc. + * @returns The equivalent Code. Unknown status codes are mapped to + * Code.UNKNOWN. + */ +export declare function mapCodeFromHttpStatus(status?: number): Code; +/** + * Converts an HTTP response's error status to the equivalent error code. + * + * @param status - An HTTP error response status ("FAILED_PRECONDITION", + * "UNKNOWN", etc.) + * @returns The equivalent Code. Non-matching responses are mapped to + * Code.UNKNOWN. + */ +export declare function mapCodeFromHttpResponseErrorStatus(status: string): Code; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/serializer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/serializer.d.ts new file mode 100644 index 0000000..bb1aeb9 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/serializer.d.ts @@ -0,0 +1,124 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Aggregate } from '../core/aggregate'; +import { DatabaseId } from '../core/database_info'; +import { CompositeFilter, CompositeOperator, FieldFilter, Filter, Operator } from '../core/filter'; +import { Direction, OrderBy } from '../core/order_by'; +import { Query } from '../core/query'; +import { SnapshotVersion } from '../core/snapshot_version'; +import { Target } from '../core/target'; +import { Timestamp } from '../lite-api/timestamp'; +import { TargetData, TargetPurpose } from '../local/target_data'; +import { MutableDocument } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { FieldMask } from '../model/field_mask'; +import { Mutation, MutationResult } from '../model/mutation'; +import { ObjectValue } from '../model/object_value'; +import { FieldPath, ResourcePath } from '../model/path'; +import { ApiClientObjectMap as ProtoApiClientObjectMap, BatchGetDocumentsResponse as ProtoBatchGetDocumentsResponse, CompositeFilterOp as ProtoCompositeFilterOp, Document as ProtoDocument, DocumentMask as ProtoDocumentMask, DocumentsTarget as ProtoDocumentsTarget, FieldFilterOp as ProtoFieldFilterOp, FieldReference as ProtoFieldReference, Filter as ProtoFilter, ListenResponse as ProtoListenResponse, Order as ProtoOrder, OrderDirection as ProtoOrderDirection, QueryTarget as ProtoQueryTarget, RunAggregationQueryRequest as ProtoRunAggregationQueryRequest, Target as ProtoTarget, Timestamp as ProtoTimestamp, Write as ProtoWrite, WriteResult as ProtoWriteResult } from '../protos/firestore_proto_api'; +import { ByteString } from '../util/byte_string'; +import { Serializer } from './number_serializer'; +import { WatchChange } from './watch_change'; +/** + * This class generates JsonObject values for the Datastore API suitable for + * sending to either GRPC stub methods or via the JSON/HTTP REST API. + * + * The serializer supports both Protobuf.js and Proto3 JSON formats. By + * setting `useProto3Json` to true, the serializer will use the Proto3 JSON + * format. + * + * For a description of the Proto3 JSON format check + * https://developers.google.com/protocol-buffers/docs/proto3#json + * + * TODO(klimt): We can remove the databaseId argument if we keep the full + * resource name in documents. + */ +export declare class JsonProtoSerializer implements Serializer { + readonly databaseId: DatabaseId; + readonly useProto3Json: boolean; + constructor(databaseId: DatabaseId, useProto3Json: boolean); +} +/** + * Returns a value for a Date that's appropriate to put into a proto. + */ +export declare function toTimestamp(serializer: JsonProtoSerializer, timestamp: Timestamp): ProtoTimestamp; +/** + * Returns a Timestamp typed object given protobuf timestamp value. + */ +export declare function fromTimestamp(date: ProtoTimestamp): Timestamp; +/** + * Returns a value for bytes that's appropriate to put in a proto. + * + * Visible for testing. + */ +export declare function toBytes(serializer: JsonProtoSerializer, bytes: ByteString): string | Uint8Array; +/** + * Returns a ByteString based on the proto string value. + */ +export declare function fromBytes(serializer: JsonProtoSerializer, value: string | Uint8Array | undefined): ByteString; +export declare function toVersion(serializer: JsonProtoSerializer, version: SnapshotVersion): ProtoTimestamp; +export declare function fromVersion(version: ProtoTimestamp): SnapshotVersion; +export declare function toResourceName(databaseId: DatabaseId, path: ResourcePath): string; +export declare function toResourcePath(databaseId: DatabaseId, path?: ResourcePath): ResourcePath; +export declare function toName(serializer: JsonProtoSerializer, key: DocumentKey): string; +export declare function fromName(serializer: JsonProtoSerializer, name: string): DocumentKey; +export declare function getEncodedDatabaseId(serializer: JsonProtoSerializer): string; +/** Creates a Document proto from key and fields (but no create/update time) */ +export declare function toMutationDocument(serializer: JsonProtoSerializer, key: DocumentKey, fields: ObjectValue): ProtoDocument; +export declare function toDocument(serializer: JsonProtoSerializer, document: MutableDocument): ProtoDocument; +export declare function fromDocument(serializer: JsonProtoSerializer, document: ProtoDocument, hasCommittedMutations?: boolean): MutableDocument; +export declare function fromBatchGetDocumentsResponse(serializer: JsonProtoSerializer, result: ProtoBatchGetDocumentsResponse): MutableDocument; +export declare function fromWatchChange(serializer: JsonProtoSerializer, change: ProtoListenResponse): WatchChange; +export declare function versionFromListenResponse(change: ProtoListenResponse): SnapshotVersion; +export declare function toMutation(serializer: JsonProtoSerializer, mutation: Mutation): ProtoWrite; +export declare function fromMutation(serializer: JsonProtoSerializer, proto: ProtoWrite): Mutation; +export declare function fromWriteResults(protos: ProtoWriteResult[] | undefined, commitTime?: ProtoTimestamp): MutationResult[]; +export declare function toDocumentsTarget(serializer: JsonProtoSerializer, target: Target): ProtoDocumentsTarget; +export declare function fromDocumentsTarget(documentsTarget: ProtoDocumentsTarget): Target; +export declare function toQueryTarget(serializer: JsonProtoSerializer, target: Target): { + queryTarget: ProtoQueryTarget; + parent: ResourcePath; +}; +export declare function toRunAggregationQueryRequest(serializer: JsonProtoSerializer, target: Target, aggregates: Aggregate[], skipAliasing?: boolean): { + request: ProtoRunAggregationQueryRequest; + aliasMap: Record; + parent: ResourcePath; +}; +export declare function convertQueryTargetToQuery(target: ProtoQueryTarget): Query; +export declare function fromQueryTarget(target: ProtoQueryTarget): Target; +export declare function toListenRequestLabels(serializer: JsonProtoSerializer, targetData: TargetData): ProtoApiClientObjectMap | null; +export declare function toLabel(purpose: TargetPurpose): string | null; +export declare function toTarget(serializer: JsonProtoSerializer, targetData: TargetData): ProtoTarget; +export declare function toDirection(dir: Direction): ProtoOrderDirection; +export declare function fromDirection(dir: ProtoOrderDirection | undefined): Direction | undefined; +export declare function toOperatorName(op: Operator): ProtoFieldFilterOp; +export declare function toCompositeOperatorName(op: CompositeOperator): ProtoCompositeFilterOp; +export declare function fromOperatorName(op: ProtoFieldFilterOp): Operator; +export declare function fromCompositeOperatorName(op: ProtoCompositeFilterOp): CompositeOperator; +export declare function toFieldPathReference(path: FieldPath): ProtoFieldReference; +export declare function fromFieldPathReference(fieldReference: ProtoFieldReference): FieldPath; +export declare function toPropertyOrder(orderBy: OrderBy): ProtoOrder; +export declare function fromPropertyOrder(orderBy: ProtoOrder): OrderBy; +export declare function toFilter(filter: Filter): ProtoFilter; +export declare function toCompositeFilter(filter: CompositeFilter): ProtoFilter; +export declare function toUnaryOrFieldFilter(filter: FieldFilter): ProtoFilter; +export declare function fromUnaryFilter(filter: ProtoFilter): Filter; +export declare function fromFieldFilter(filter: ProtoFilter): FieldFilter; +export declare function fromCompositeFilter(filter: ProtoFilter): CompositeFilter; +export declare function toDocumentMask(fieldMask: FieldMask): ProtoDocumentMask; +export declare function fromDocumentMask(proto: ProtoDocumentMask): FieldMask; +export declare function isValidResourceName(path: ResourcePath): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/stream_bridge.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/stream_bridge.d.ts new file mode 100644 index 0000000..f17a080 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/stream_bridge.d.ts @@ -0,0 +1,45 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirestoreError } from '../util/error'; +import { Stream } from './connection'; +/** + * Provides a simple helper class that implements the Stream interface to + * bridge to other implementations that are streams but do not implement the + * interface. The stream callbacks are invoked with the callOn... methods. + */ +export declare class StreamBridge implements Stream { + private wrappedOnConnected; + private wrappedOnOpen; + private wrappedOnClose; + private wrappedOnMessage; + private sendFn; + private closeFn; + constructor(args: { + sendFn: (msg: I) => void; + closeFn: () => void; + }); + onConnected(callback: () => void): void; + onOpen(callback: () => void): void; + onClose(callback: (err?: FirestoreError) => void): void; + onMessage(callback: (msg: O) => void): void; + close(): void; + send(msg: I): void; + callOnConnected(): void; + callOnOpen(): void; + callOnClose(err?: FirestoreError): void; + callOnMessage(msg: O): void; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/watch_change.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/watch_change.d.ts new file mode 100644 index 0000000..1510515 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/remote/watch_change.d.ts @@ -0,0 +1,231 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { DatabaseId } from '../core/database_info'; +import { SnapshotVersion } from '../core/snapshot_version'; +import { TargetId } from '../core/types'; +import { TargetData } from '../local/target_data'; +import { DocumentKeySet } from '../model/collections'; +import { MutableDocument } from '../model/document'; +import { DocumentKey } from '../model/document_key'; +import { ByteString } from '../util/byte_string'; +import { FirestoreError } from '../util/error'; +import { ExistenceFilter } from './existence_filter'; +import { RemoteEvent } from './remote_event'; +/** + * Internal representation of the watcher API protocol buffers. + */ +export type WatchChange = DocumentWatchChange | WatchTargetChange | ExistenceFilterChange; +/** + * Represents a changed document and a list of target ids to which this change + * applies. + * + * If document has been deleted NoDocument will be provided. + */ +export declare class DocumentWatchChange { + /** The new document applies to all of these targets. */ + updatedTargetIds: TargetId[]; + /** The new document is removed from all of these targets. */ + removedTargetIds: TargetId[]; + /** The key of the document for this change. */ + key: DocumentKey; + /** + * The new document or NoDocument if it was deleted. Is null if the + * document went out of view without the server sending a new document. + */ + newDoc: MutableDocument | null; + constructor( + /** The new document applies to all of these targets. */ + updatedTargetIds: TargetId[], + /** The new document is removed from all of these targets. */ + removedTargetIds: TargetId[], + /** The key of the document for this change. */ + key: DocumentKey, + /** + * The new document or NoDocument if it was deleted. Is null if the + * document went out of view without the server sending a new document. + */ + newDoc: MutableDocument | null); +} +export declare class ExistenceFilterChange { + targetId: TargetId; + existenceFilter: ExistenceFilter; + constructor(targetId: TargetId, existenceFilter: ExistenceFilter); +} +export declare const enum WatchTargetChangeState { + NoChange = 0, + Added = 1, + Removed = 2, + Current = 3, + Reset = 4 +} +export declare class WatchTargetChange { + /** What kind of change occurred to the watch target. */ + state: WatchTargetChangeState; + /** The target IDs that were added/removed/set. */ + targetIds: TargetId[]; + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + resumeToken: ByteString; + /** An RPC error indicating why the watch failed. */ + cause: FirestoreError | null; + constructor( + /** What kind of change occurred to the watch target. */ + state: WatchTargetChangeState, + /** The target IDs that were added/removed/set. */ + targetIds: TargetId[], + /** + * An opaque, server-assigned token that allows watching a target to be + * resumed after disconnecting without retransmitting all the data that + * matches the target. The resume token essentially identifies a point in + * time from which the server should resume sending results. + */ + resumeToken?: ByteString, + /** An RPC error indicating why the watch failed. */ + cause?: FirestoreError | null); +} +/** + * Interface implemented by RemoteStore to expose target metadata to the + * WatchChangeAggregator. + */ +export interface TargetMetadataProvider { + /** + * Returns the set of remote document keys for the given target ID as of the + * last raised snapshot. + */ + getRemoteKeysForTarget(targetId: TargetId): DocumentKeySet; + /** + * Returns the TargetData for an active target ID or 'null' if this target + * has become inactive + */ + getTargetDataForTarget(targetId: TargetId): TargetData | null; + /** + * Returns the database ID of the Firestore instance. + */ + getDatabaseId(): DatabaseId; +} +/** + * A helper class to accumulate watch changes into a RemoteEvent. + */ +export declare class WatchChangeAggregator { + private metadataProvider; + constructor(metadataProvider: TargetMetadataProvider); + /** The internal state of all tracked targets. */ + private targetStates; + /** Keeps track of the documents to update since the last raised snapshot. */ + private pendingDocumentUpdates; + private pendingDocumentUpdatesByTarget; + /** A mapping of document keys to their set of target IDs. */ + private pendingDocumentTargetMapping; + /** + * A map of targets with existence filter mismatches. These targets are + * known to be inconsistent and their listens needs to be re-established by + * RemoteStore. + */ + private pendingTargetResets; + /** + * Processes and adds the DocumentWatchChange to the current set of changes. + */ + handleDocumentChange(docChange: DocumentWatchChange): void; + /** Processes and adds the WatchTargetChange to the current set of changes. */ + handleTargetChange(targetChange: WatchTargetChange): void; + /** + * Iterates over all targetIds that the watch change applies to: either the + * targetIds explicitly listed in the change or the targetIds of all currently + * active targets. + */ + forEachTarget(targetChange: WatchTargetChange, fn: (targetId: TargetId) => void): void; + /** + * Handles existence filters and synthesizes deletes for filter mismatches. + * Targets that are invalidated by filter mismatches are added to + * `pendingTargetResets`. + */ + handleExistenceFilter(watchChange: ExistenceFilterChange): void; + /** + * Parse the bloom filter from the "unchanged_names" field of an existence + * filter. + */ + private parseBloomFilter; + /** + * Apply bloom filter to remove the deleted documents, and return the + * application status. + */ + private applyBloomFilter; + /** + * Filter out removed documents based on bloom filter membership result and + * return number of documents removed. + */ + private filterRemovedDocuments; + /** + * Converts the currently accumulated state into a remote event at the + * provided snapshot version. Resets the accumulated changes before returning. + */ + createRemoteEvent(snapshotVersion: SnapshotVersion): RemoteEvent; + /** + * Adds the provided document to the internal list of document updates and + * its document key to the given target's mapping. + */ + addDocumentToTarget(targetId: TargetId, document: MutableDocument): void; + /** + * Removes the provided document from the target mapping. If the + * document no longer matches the target, but the document's state is still + * known (e.g. we know that the document was deleted or we received the change + * that caused the filter mismatch), the new document can be provided + * to update the remote document cache. + */ + removeDocumentFromTarget(targetId: TargetId, key: DocumentKey, updatedDocument: MutableDocument | null): void; + removeTarget(targetId: TargetId): void; + /** + * Returns the current count of documents in the target. This includes both + * the number of documents that the LocalStore considers to be part of the + * target as well as any accumulated changes. + */ + private getCurrentDocumentCountForTarget; + /** + * Increment the number of acks needed from watch before we can consider the + * server to be 'in-sync' with the client's active targets. + */ + recordPendingTargetRequest(targetId: TargetId): void; + private ensureTargetState; + private ensureDocumentTargetMapping; + private ensureDocumentUpdateByTarget; + /** + * Verifies that the user is still interested in this target (by calling + * `getTargetDataForTarget()`) and that we are not waiting for pending ADDs + * from watch. + */ + protected isActiveTarget(targetId: TargetId): boolean; + /** + * Returns the TargetData for an active target (i.e. a target that the user + * is still interested in that has no outstanding target change requests). + */ + protected targetDataForActiveTarget(targetId: TargetId): TargetData | null; + /** + * Resets the state of a Watch target to its initial state (e.g. sets + * 'current' to false, clears the resume token and removes its target mapping + * from all documents). + */ + private resetTarget; + /** + * Returns whether the LocalStore considers the document to be part of the + * specified target. + */ + private targetContainsDocument; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/array.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/array.d.ts new file mode 100644 index 0000000..8be6593 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/array.d.ts @@ -0,0 +1,70 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Returns true iff the array contains the value using strong equality. + */ +export declare function includes(array: T[], value: T): boolean; +/** + * Returns true iff the array contains any value matching the predicate + */ +export declare function some(array: T[], predicate: (t: T) => boolean): boolean; +/** + * Calls predicate function for each item in the array until the predicate + * returns true, at which point the index of that item is returned. If the + * predicate does not return true for any item, null is returned. + */ +export declare function findIndex(array: A[], predicate: (value: A) => boolean): number | null; +/** + * Compares two array for equality using comparator. The method computes the + * intersection and invokes `onAdd` for every element that is in `after` but not + * `before`. `onRemove` is invoked for every element in `before` but missing + * from `after`. + * + * The method creates a copy of both `before` and `after` and runs in O(n log + * n), where n is the size of the two lists. + * + * @param before - The elements that exist in the original array. + * @param after - The elements to diff against the original array. + * @param comparator - The comparator for the elements in before and after. + * @param onAdd - A function to invoke for every element that is part of ` + * after` but not `before`. + * @param onRemove - A function to invoke for every element that is part of + * `before` but not `after`. + */ +export declare function diffArrays(before: T[], after: T[], comparator: (l: T, r: T) => number, onAdd: (entry: T) => void, onRemove: (entry: T) => void): void; +/** + * Verifies equality for an array of objects using the `isEqual` interface. + * + * @private + * @internal + * @param left Array of objects supporting `isEqual`. + * @param right Array of objects supporting `isEqual`. + * @return True if arrays are equal. + */ +export declare function isArrayEqual boolean; +}>(left: T[], right: T[]): boolean; +/** + * Verifies equality for an array of primitives. + * + * @private + * @internal + * @param left Array of primitives. + * @param right Array of primitives. + * @return True if arrays are equal. + */ +export declare function isPrimitiveArrayEqual(left: T[], right: T[]): boolean; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/assert.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/assert.d.ts new file mode 100644 index 0000000..294b08a --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/assert.d.ts @@ -0,0 +1,78 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Unconditionally fails, throwing an Error with the given message. + * Messages are stripped in production builds. + * + * Returns `never` and can be used in expressions: + * @example + * let futureVar = fail('not implemented yet'); + * + * @param code generate a new unique value with `yarn assertion-id:generate` + * Search for an existing value using `yarn assertion-id:find X` + */ +export declare function fail(code: number, message: string, context?: Record): never; +/** + * Unconditionally fails, throwing an Error with the given message. + * Messages are stripped in production builds. + * + * Returns `never` and can be used in expressions: + * @example + * let futureVar = fail('not implemented yet'); + * + * @param id generate a new unique value with `yarn assertion-id:generate` + * Search for an existing value using `yarn assertion-id:find X` + */ +export declare function fail(id: number, context?: Record): never; +/** + * Fails if the given assertion condition is false, throwing an Error with the + * given message if it did. + * + * Messages are stripped in production builds. + * + * @param id generate a new unique value with `yarn assertion-idgenerate`. + * Search for an existing value using `yarn assertion-id:find X` + */ +export declare function hardAssert(assertion: boolean, id: number, message: string, context?: Record): asserts assertion; +/** + * Fails if the given assertion condition is false, throwing an Error with the + * given message if it did. + * + * Messages are stripped in production builds. + * + * @param id generate a new unique value with `yarn assertion-id:generate`. + * Search for an existing value using `yarn assertion-id:find X` + */ +export declare function hardAssert(assertion: boolean, id: number, context?: Record): asserts assertion; +/** + * Fails if the given assertion condition is false, throwing an Error with the + * given message if it did. + * + * The code of callsites invoking this function are stripped out in production + * builds. Any side-effects of code within the debugAssert() invocation will not + * happen in this case. + * + * @internal + */ +export declare function debugAssert(assertion: boolean, message: string): asserts assertion; +/** + * Casts `obj` to `T`. In non-production builds, verifies that `obj` is an + * instance of `T` before casting. + */ +export declare function debugCast(obj: object, constructor: { + new (...args: any[]): T; +}): T | never; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/async_observer.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/async_observer.d.ts new file mode 100644 index 0000000..21a965e --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/async_observer.d.ts @@ -0,0 +1,31 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Observer } from '../core/event_manager'; +import { FirestoreError } from './error'; +export declare class AsyncObserver implements Observer { + private observer; + /** + * When set to true, will not raise future events. Necessary to deal with + * async detachment of listener. + */ + private muted; + constructor(observer: Partial>); + next(value: T): void; + error(error: FirestoreError): void; + mute(): void; + private scheduleEvent; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/async_queue.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/async_queue.d.ts new file mode 100644 index 0000000..098746b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/async_queue.d.ts @@ -0,0 +1,180 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirestoreError } from './error'; +/** + * Wellknown "timer" IDs used when scheduling delayed operations on the + * AsyncQueue. These IDs can then be used from tests to check for the presence + * of operations or to run them early. + * + * The string values are used when encoding these timer IDs in JSON spec tests. + */ +export declare const enum TimerId { + /** All can be used with runDelayedOperationsEarly() to run all timers. */ + All = "all", + /** + * The following 5 timers are used in persistent_stream.ts for the listen and + * write streams. The "Idle" timer is used to close the stream due to + * inactivity. The "ConnectionBackoff" timer is used to restart a stream once + * the appropriate backoff delay has elapsed. The health check is used to mark + * a stream healthy if it has not received an error during its initial setup. + */ + ListenStreamIdle = "listen_stream_idle", + ListenStreamConnectionBackoff = "listen_stream_connection_backoff", + WriteStreamIdle = "write_stream_idle", + WriteStreamConnectionBackoff = "write_stream_connection_backoff", + HealthCheckTimeout = "health_check_timeout", + /** + * A timer used in online_state_tracker.ts to transition from + * OnlineState.Unknown to Offline after a set timeout, rather than waiting + * indefinitely for success or failure. + */ + OnlineStateTimeout = "online_state_timeout", + /** + * A timer used to update the client metadata in IndexedDb, which is used + * to determine the primary leaseholder. + */ + ClientMetadataRefresh = "client_metadata_refresh", + /** A timer used to periodically attempt LRU Garbage collection */ + LruGarbageCollection = "lru_garbage_collection", + /** + * A timer used to retry transactions. Since there can be multiple concurrent + * transactions, multiple of these may be in the queue at a given time. + */ + TransactionRetry = "transaction_retry", + /** + * A timer used to retry operations scheduled via retryable AsyncQueue + * operations. + */ + AsyncQueueRetry = "async_queue_retry", + /** + * A timer used to periodically attempt index backfill. + */ + IndexBackfill = "index_backfill" +} +/** + * Represents an operation scheduled to be run in the future on an AsyncQueue. + * + * It is created via DelayedOperation.createAndSchedule(). + * + * Supports cancellation (via cancel()) and early execution (via skipDelay()). + * + * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type + * in newer versions of TypeScript defines `finally`, which is not available in + * IE. + */ +export declare class DelayedOperation implements PromiseLike { + private readonly asyncQueue; + readonly timerId: TimerId; + readonly targetTimeMs: number; + private readonly op; + private readonly removalCallback; + private timerHandle; + private readonly deferred; + private constructor(); + get promise(): Promise; + /** + * Creates and returns a DelayedOperation that has been scheduled to be + * executed on the provided asyncQueue after the provided delayMs. + * + * @param asyncQueue - The queue to schedule the operation on. + * @param id - A Timer ID identifying the type of operation this is. + * @param delayMs - The delay (ms) before the operation should be scheduled. + * @param op - The operation to run. + * @param removalCallback - A callback to be called synchronously once the + * operation is executed or canceled, notifying the AsyncQueue to remove it + * from its delayedOperations list. + * PORTING NOTE: This exists to prevent making removeDelayedOperation() and + * the DelayedOperation class public. + */ + static createAndSchedule(asyncQueue: AsyncQueue, timerId: TimerId, delayMs: number, op: () => Promise, removalCallback: (op: DelayedOperation) => void): DelayedOperation; + /** + * Starts the timer. This is called immediately after construction by + * createAndSchedule(). + */ + private start; + /** + * Queues the operation to run immediately (if it hasn't already been run or + * canceled). + */ + skipDelay(): void; + /** + * Cancels the operation if it hasn't already been executed or canceled. The + * promise will be rejected. + * + * As long as the operation has not yet been run, calling cancel() provides a + * guarantee that the operation will not be run. + */ + cancel(reason?: string): void; + then: (onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined) => Promise; + private handleDelayElapsed; + private clearTimeout; +} +export interface AsyncQueue { + readonly isShuttingDown: boolean; + /** + * Adds a new operation to the queue without waiting for it to complete (i.e. + * we ignore the Promise result). + */ + enqueueAndForget(op: () => Promise): void; + /** + * Regardless if the queue has initialized shutdown, adds a new operation to the + * queue without waiting for it to complete (i.e. we ignore the Promise result). + */ + enqueueAndForgetEvenWhileRestricted(op: () => Promise): void; + /** + * Initialize the shutdown of this queue. Once this method is called, the + * only possible way to request running an operation is through + * `enqueueEvenWhileRestricted()`. + * + * @param purgeExistingTasks Whether already enqueued tasked should be + * rejected (unless enqueued with `enqueueEvenWhileRestricted()`). Defaults + * to false. + */ + enterRestrictedMode(purgeExistingTasks?: boolean): void; + /** + * Adds a new operation to the queue. Returns a promise that will be resolved + * when the promise returned by the new operation is (with its value). + */ + enqueue(op: () => Promise): Promise; + /** + * Enqueue a retryable operation. + * + * A retryable operation is rescheduled with backoff if it fails with a + * IndexedDbTransactionError (the error type used by SimpleDb). All + * retryable operations are executed in order and only run if all prior + * operations were retried successfully. + */ + enqueueRetryable(op: () => Promise): void; + /** + * Schedules an operation to be queued on the AsyncQueue once the specified + * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel + * or fast-forward the operation prior to its running. + */ + enqueueAfterDelay(timerId: TimerId, delayMs: number, op: () => Promise): DelayedOperation; + /** + * Verifies there's an operation currently in-progress on the AsyncQueue. + * Unfortunately we can't verify that the running code is in the promise chain + * of that operation, so this isn't a foolproof check, but it should be enough + * to catch some bugs. + */ + verifyOperationInProgress(): void; +} +/** + * Returns a FirestoreError that can be surfaced to the user if the provided + * error is an IndexedDbTransactionError. Re-throws the error otherwise. + */ +export declare function wrapInUserErrorIfRecoverable(e: Error, msg: string): FirestoreError; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/async_queue_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/async_queue_impl.d.ts new file mode 100644 index 0000000..6dedc85 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/async_queue_impl.d.ts @@ -0,0 +1,75 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { AsyncQueue, DelayedOperation, TimerId } from './async_queue'; +import { FirestoreError } from './error'; +export declare class AsyncQueueImpl implements AsyncQueue { + private tail; + private retryableOps; + private _isShuttingDown; + private delayedOperations; + failure: FirestoreError | null; + private operationInProgress; + private skipNonRestrictedTasks; + private timerIdsToSkip; + private backoff; + private visibilityHandler; + constructor(tail?: Promise); + get isShuttingDown(): boolean; + /** + * Adds a new operation to the queue without waiting for it to complete (i.e. + * we ignore the Promise result). + */ + enqueueAndForget(op: () => Promise): void; + enqueueAndForgetEvenWhileRestricted(op: () => Promise): void; + enterRestrictedMode(purgeExistingTasks?: boolean): void; + enqueue(op: () => Promise): Promise; + enqueueRetryable(op: () => Promise): void; + /** + * Runs the next operation from the retryable queue. If the operation fails, + * reschedules with backoff. + */ + private retryNextOp; + private enqueueInternal; + enqueueAfterDelay(timerId: TimerId, delayMs: number, op: () => Promise): DelayedOperation; + private verifyNotFailed; + verifyOperationInProgress(): void; + /** + * Waits until all currently queued tasks are finished executing. Delayed + * operations are not run. + */ + drain(): Promise; + /** + * For Tests: Determine if a delayed operation with a particular TimerId + * exists. + */ + containsDelayedOperation(timerId: TimerId): boolean; + /** + * For Tests: Runs some or all delayed operations early. + * + * @param lastTimerId - Delayed operations up to and including this TimerId + * will be drained. Pass TimerId.All to run all delayed operations. + * @returns a Promise that resolves once all operations have been run. + */ + runAllDelayedOperationsUntil(lastTimerId: TimerId): Promise; + /** + * For Tests: Skip all subsequent delays for a timer id. + */ + skipDelaysForTimerId(timerId: TimerId): void; + /** Called once a DelayedOperation is run or canceled. */ + private removeDelayedOperation; +} +export declare function newAsyncQueue(): AsyncQueue; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/base64_decode_error.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/base64_decode_error.d.ts new file mode 100644 index 0000000..18800ff --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/base64_decode_error.d.ts @@ -0,0 +1,22 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * An error encountered while decoding base64 string. + */ +export declare class Base64DecodeError extends Error { + readonly name = "Base64DecodeError"; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_builder_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_builder_impl.d.ts new file mode 100644 index 0000000..57e978c --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_builder_impl.d.ts @@ -0,0 +1,97 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { Firestore } from '../api/database'; +import { Query } from '../core/query'; +import { DocumentData } from '../lite-api/reference'; +import { Timestamp } from '../lite-api/timestamp'; +import { DocumentKey } from '../model/document_key'; +/** + * Builds a Firestore data bundle with results from the given document and query snapshots. + */ +export declare class BundleBuilder { + private firestore; + readonly bundleId: string; + private documents; + private namedQueries; + private latestReadTime; + private databaseId; + private readonly serializer; + private readonly userDataReader; + constructor(firestore: Firestore, bundleId: string); + /** + * Adds data from a DocumentSnapshot to the bundle. + * @internal + * @param docBundleData A DocumentSnapshotBundleData containing information from the + * DocumentSnapshot. Note we cannot accept a DocumentSnapshot directly due to a circular + * dependency error. + * @param queryName The name of the QuerySnapshot if this document is part of a Query. + */ + addBundleDocument(docBundleData: DocumentSnapshotBundleData, queryName?: string): void; + /** + * Adds data from a QuerySnapshot to the bundle. + * @internal + * @param docBundleData A QuerySnapshotBundleData containing information from the + * QuerySnapshot. Note we cannot accept a QuerySnapshot directly due to a circular + * dependency error. + */ + addBundleQuery(queryBundleData: QuerySnapshotBundleData): void; + /** + * Convert data from a DocumentSnapshot into the serialized form within a bundle. + * @private + * @internal + * @param docBundleData a DocumentSnapshotBundleData containing the data required to + * serialize a document. + */ + private toBundleDocument; + /** + * Converts a IBundleElement to a Buffer whose content is the length prefixed JSON representation + * of the element. + * @private + * @internal + * @param bundleElement A ProtoBundleElement that is expected to be Proto3 JSON compatible. + */ + private lengthPrefixedString; + /** + * Construct a serialized string containing document and query information that has previously + * been added to the BundleBuilder through the addBundleDocument and addBundleQuery methods. + * @internal + */ + build(): string; +} +/** + * Interface for an object that contains data required to bundle a DocumentSnapshot. + * @internal + */ +export interface DocumentSnapshotBundleData { + documentData: DocumentData; + documentKey: DocumentKey; + documentPath: string; + documentExists: boolean; + createdTime: Timestamp; + readTime?: Timestamp; + versionTime: Timestamp; +} +/** + * Interface for an object that contains data required to bundle a QuerySnapshot. + * @internal + */ +export interface QuerySnapshotBundleData { + name: string; + query: Query; + parent: string; + docBundleDataArray: DocumentSnapshotBundleData[]; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_reader.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_reader.d.ts new file mode 100644 index 0000000..cfe6dbd --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_reader.d.ts @@ -0,0 +1,67 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BundleElement, BundleMetadata } from '../protos/firestore_bundle_proto'; +import { JsonProtoSerializer } from '../remote/serializer'; +/** + * A complete element in the bundle stream, together with the byte length it + * occupies in the stream. + */ +export declare class SizedBundleElement { + readonly payload: BundleElement; + readonly byteLength: number; + constructor(payload: BundleElement, byteLength: number); + isBundleMetadata(): boolean; +} +export type BundleSource = ReadableStream | ArrayBuffer | Uint8Array; +/** + * A class representing a bundle. + * + * Takes a bundle stream or buffer, and presents abstractions to read bundled + * elements out of the underlying content. + */ +export interface BundleReader { + serializer: JsonProtoSerializer; + close(): Promise; + /** + * Returns the metadata of the bundle. + */ + getMetadata(): Promise; + /** + * Returns the next BundleElement (together with its byte size in the bundle) + * that has not been read from underlying ReadableStream. Returns null if we + * have reached the end of the stream. + */ + nextElement(): Promise; +} +/** + * A class representing a synchronized bundle reader. + * + * Takes a bundle string buffer, parses the data, and provides accessors to the data contained + * within it. + */ +export interface BundleReaderSync { + serializer: JsonProtoSerializer; + /** + * Returns the metadata of the bundle. + */ + getMetadata(): BundleMetadata; + /** + * Returns BundleElements parsed from the bundle. Returns an empty array if no bundle elements + * exist. + */ + getElements(): SizedBundleElement[]; +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_reader_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_reader_impl.d.ts new file mode 100644 index 0000000..0858a93 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_reader_impl.d.ts @@ -0,0 +1,19 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { JsonProtoSerializer } from '../remote/serializer'; +import { BundleReader } from './bundle_reader'; +export declare function newBundleReader(reader: ReadableStreamDefaultReader, serializer: JsonProtoSerializer): BundleReader; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_reader_sync_impl.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_reader_sync_impl.d.ts new file mode 100644 index 0000000..638497f --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/bundle_reader_sync_impl.d.ts @@ -0,0 +1,59 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { BundleMetadata } from '../protos/firestore_bundle_proto'; +import { JsonProtoSerializer } from '../remote/serializer'; +import { BundleReaderSync, SizedBundleElement } from './bundle_reader'; +/** + * A class that can parse a bundle form the string serialization of a bundle. + */ +export declare class BundleReaderSyncImpl implements BundleReaderSync { + private bundleData; + readonly serializer: JsonProtoSerializer; + private metadata; + private elements; + private cursor; + constructor(bundleData: string, serializer: JsonProtoSerializer); + getMetadata(): BundleMetadata; + getElements(): SizedBundleElement[]; + /** + * Parses the next element of the bundle. + * + * @returns a SizedBundleElement representation of the next element in the bundle, or null if + * no more elements exist. + */ + private nextElement; + /** + * Reads from a specified position from the bundleData string, for a specified + * number of bytes. + * + * @param length how many characters to read. + * @returns a string parsed from the bundle. + */ + private readJsonString; + /** + * Reads from the current cursor until the first '{'. + * + * @returns A string to integer represention of the parsed value. + * @throws An {@link Error} if the cursor has reached the end of the stream, since lengths + * prefix bundle objects. + */ + private readLength; +} +/** + * Creates an instance of BundleReader without exposing the BundleReaderSyncImpl class type. + */ +export declare function newBundleReaderSync(bundleData: string, serializer: JsonProtoSerializer): BundleReaderSync; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/byte_stream.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/byte_stream.d.ts new file mode 100644 index 0000000..72d8ed7 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/byte_stream.d.ts @@ -0,0 +1,29 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * How many bytes to read each time when `ReadableStreamReader.read()` is + * called. Only applicable for byte streams that we control (e.g. those backed + * by an UInt8Array). + */ +export declare const DEFAULT_BYTES_PER_READ = 10240; +/** + * Builds a `ByteStreamReader` from a UInt8Array. + * @param source - The data source to use. + * @param bytesPerRead - How many bytes each `read()` from the returned reader + * will read. + */ +export declare function toByteStreamReaderHelper(source: Uint8Array, bytesPerRead?: number): ReadableStreamDefaultReader; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/byte_string.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/byte_string.d.ts new file mode 100644 index 0000000..9aec389 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/byte_string.d.ts @@ -0,0 +1,46 @@ +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Immutable class that represents a "proto" byte string. + * + * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when + * sent on the wire. This class abstracts away this differentiation by holding + * the proto byte string in a common class that must be converted into a string + * before being sent as a proto. + * @internal + */ +export declare class ByteString { + private readonly binaryString; + static readonly EMPTY_BYTE_STRING: ByteString; + private constructor(); + static fromBase64String(base64: string): ByteString; + static fromUint8Array(array: Uint8Array): ByteString; + [Symbol.iterator](): Iterator; + toBase64(): string; + toUint8Array(): Uint8Array; + approximateByteSize(): number; + compareTo(other: ByteString): number; + isEqual(other: ByteString): boolean; +} +/** + * Helper function to convert an Uint8array to a binary string. + */ +export declare function binaryStringFromUint8Array(array: Uint8Array): string; +/** + * Helper function to convert a binary string to an Uint8Array. + */ +export declare function uint8ArrayFromBinaryString(binaryString: string): Uint8Array; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/debug_uid.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/debug_uid.d.ts new file mode 100644 index 0000000..b590233 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/debug_uid.d.ts @@ -0,0 +1,28 @@ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Generates and returns a unique ID as a hexadecimal string. + * + * The returned ID is intended to be used in debug logging messages to help + * correlate log messages that may be spatially separated in the logs, but + * logically related. For example, a network connection could include the same + * "debug ID" string in all of its log messages to help trace a specific + * connection over time. + * + * @return the 10-character generated ID (e.g. "0xa1b2c3d4"). + */ +export declare function generateUniqueDebugId(): string; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/error.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/error.d.ts new file mode 100644 index 0000000..e49c172 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/error.d.ts @@ -0,0 +1,195 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { FirebaseError } from '@firebase/util'; +/** + * The set of Firestore status codes. The codes are the same at the ones + * exposed by gRPC here: + * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md + * + * Possible values: + * - 'cancelled': The operation was cancelled (typically by the caller). + * - 'unknown': Unknown error or an error from a different error domain. + * - 'invalid-argument': Client specified an invalid argument. Note that this + * differs from 'failed-precondition'. 'invalid-argument' indicates + * arguments that are problematic regardless of the state of the system + * (e.g. an invalid field name). + * - 'deadline-exceeded': Deadline expired before operation could complete. + * For operations that change the state of the system, this error may be + * returned even if the operation has completed successfully. For example, + * a successful response from a server could have been delayed long enough + * for the deadline to expire. + * - 'not-found': Some requested document was not found. + * - 'already-exists': Some document that we attempted to create already + * exists. + * - 'permission-denied': The caller does not have permission to execute the + * specified operation. + * - 'resource-exhausted': Some resource has been exhausted, perhaps a + * per-user quota, or perhaps the entire file system is out of space. + * - 'failed-precondition': Operation was rejected because the system is not + * in a state required for the operation's execution. + * - 'aborted': The operation was aborted, typically due to a concurrency + * issue like transaction aborts, etc. + * - 'out-of-range': Operation was attempted past the valid range. + * - 'unimplemented': Operation is not implemented or not supported/enabled. + * - 'internal': Internal errors. Means some invariants expected by + * underlying system has been broken. If you see one of these errors, + * something is very broken. + * - 'unavailable': The service is currently unavailable. This is most likely + * a transient condition and may be corrected by retrying with a backoff. + * - 'data-loss': Unrecoverable data loss or corruption. + * - 'unauthenticated': The request does not have valid authentication + * credentials for the operation. + */ +export type FirestoreErrorCode = 'cancelled' | 'unknown' | 'invalid-argument' | 'deadline-exceeded' | 'not-found' | 'already-exists' | 'permission-denied' | 'resource-exhausted' | 'failed-precondition' | 'aborted' | 'out-of-range' | 'unimplemented' | 'internal' | 'unavailable' | 'data-loss' | 'unauthenticated'; +/** + * Error Codes describing the different ways Firestore can fail. These come + * directly from GRPC. + */ +export type Code = FirestoreErrorCode; +export declare const Code: { + /** Not an error; returned on success. */ + OK: FirestoreErrorCode; + /** The operation was cancelled (typically by the caller). */ + CANCELLED: FirestoreErrorCode; + /** Unknown error or an error from a different error domain. */ + UNKNOWN: FirestoreErrorCode; + /** + * Client specified an invalid argument. Note that this differs from + * FAILED_PRECONDITION. INVALID_ARGUMENT indicates arguments that are + * problematic regardless of the state of the system (e.g., a malformed file + * name). + */ + INVALID_ARGUMENT: FirestoreErrorCode; + /** + * Deadline expired before operation could complete. For operations that + * change the state of the system, this error may be returned even if the + * operation has completed successfully. For example, a successful response + * from a server could have been delayed long enough for the deadline to + * expire. + */ + DEADLINE_EXCEEDED: FirestoreErrorCode; + /** Some requested entity (e.g., file or directory) was not found. */ + NOT_FOUND: FirestoreErrorCode; + /** + * Some entity that we attempted to create (e.g., file or directory) already + * exists. + */ + ALREADY_EXISTS: FirestoreErrorCode; + /** + * The caller does not have permission to execute the specified operation. + * PERMISSION_DENIED must not be used for rejections caused by exhausting + * some resource (use RESOURCE_EXHAUSTED instead for those errors). + * PERMISSION_DENIED must not be used if the caller cannot be identified + * (use UNAUTHENTICATED instead for those errors). + */ + PERMISSION_DENIED: FirestoreErrorCode; + /** + * The request does not have valid authentication credentials for the + * operation. + */ + UNAUTHENTICATED: FirestoreErrorCode; + /** + * Some resource has been exhausted, perhaps a per-user quota, or perhaps the + * entire file system is out of space. + */ + RESOURCE_EXHAUSTED: FirestoreErrorCode; + /** + * Operation was rejected because the system is not in a state required for + * the operation's execution. For example, directory to be deleted may be + * non-empty, an rmdir operation is applied to a non-directory, etc. + * + * A litmus test that may help a service implementor in deciding + * between FAILED_PRECONDITION, ABORTED, and UNAVAILABLE: + * (a) Use UNAVAILABLE if the client can retry just the failing call. + * (b) Use ABORTED if the client should retry at a higher-level + * (e.g., restarting a read-modify-write sequence). + * (c) Use FAILED_PRECONDITION if the client should not retry until + * the system state has been explicitly fixed. E.g., if an "rmdir" + * fails because the directory is non-empty, FAILED_PRECONDITION + * should be returned since the client should not retry unless + * they have first fixed up the directory by deleting files from it. + * (d) Use FAILED_PRECONDITION if the client performs conditional + * REST Get/Update/Delete on a resource and the resource on the + * server does not match the condition. E.g., conflicting + * read-modify-write on the same resource. + */ + FAILED_PRECONDITION: FirestoreErrorCode; + /** + * The operation was aborted, typically due to a concurrency issue like + * sequencer check failures, transaction aborts, etc. + * + * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, + * and UNAVAILABLE. + */ + ABORTED: FirestoreErrorCode; + /** + * Operation was attempted past the valid range. E.g., seeking or reading + * past end of file. + * + * Unlike INVALID_ARGUMENT, this error indicates a problem that may be fixed + * if the system state changes. For example, a 32-bit file system will + * generate INVALID_ARGUMENT if asked to read at an offset that is not in the + * range [0,2^32-1], but it will generate OUT_OF_RANGE if asked to read from + * an offset past the current file size. + * + * There is a fair bit of overlap between FAILED_PRECONDITION and + * OUT_OF_RANGE. We recommend using OUT_OF_RANGE (the more specific error) + * when it applies so that callers who are iterating through a space can + * easily look for an OUT_OF_RANGE error to detect when they are done. + */ + OUT_OF_RANGE: FirestoreErrorCode; + /** Operation is not implemented or not supported/enabled in this service. */ + UNIMPLEMENTED: FirestoreErrorCode; + /** + * Internal errors. Means some invariants expected by underlying System has + * been broken. If you see one of these errors, Something is very broken. + */ + INTERNAL: FirestoreErrorCode; + /** + * The service is currently unavailable. This is a most likely a transient + * condition and may be corrected by retrying with a backoff. + * + * See litmus test above for deciding between FAILED_PRECONDITION, ABORTED, + * and UNAVAILABLE. + */ + UNAVAILABLE: FirestoreErrorCode; + /** Unrecoverable data loss or corruption. */ + DATA_LOSS: FirestoreErrorCode; +}; +/** An error returned by a Firestore operation. */ +export declare class FirestoreError extends FirebaseError { + /** + * The backend error code associated with this error. + */ + readonly code: FirestoreErrorCode; + /** + * A custom error description. + */ + readonly message: string; + /** The stack of the error. */ + readonly stack?: string; + /** @hideconstructor */ + constructor( + /** + * The backend error code associated with this error. + */ + code: FirestoreErrorCode, + /** + * A custom error description. + */ + message: string); +} diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/input_validation.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/input_validation.d.ts new file mode 100644 index 0000000..c62ae20 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/input_validation.d.ts @@ -0,0 +1,56 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { ResourcePath } from '../model/path'; +/** Types accepted by validateType() and related methods for validation. */ +export type ValidationType = 'undefined' | 'object' | 'function' | 'boolean' | 'number' | 'string' | 'non-empty string'; +export declare function validateNonEmptyArgument(functionName: string, argumentName: string, argument?: string): asserts argument is string; +/** + * Validates that two boolean options are not set at the same time. + * @internal + */ +export declare function validateIsNotUsedTogether(optionName1: string, argument1: boolean | undefined, optionName2: string, argument2: boolean | undefined): void; +/** + * Validates that `path` refers to a document (indicated by the fact it contains + * an even numbers of segments). + */ +export declare function validateDocumentPath(path: ResourcePath): void; +/** + * Validates that `path` refers to a collection (indicated by the fact it + * contains an odd numbers of segments). + */ +export declare function validateCollectionPath(path: ResourcePath): void; +/** + * Returns true if it's a non-null object without a custom prototype + * (i.e. excludes Array, Date, etc.). + */ +export declare function isPlainObject(input: unknown): boolean; +/** Returns a string describing the type / value of the provided input. */ +export declare function valueDescription(input: unknown): string; +/** try to get the constructor name for an object. */ +export declare function tryGetCustomObjectType(input: object): string | null; +/** + * Casts `obj` to `T`, optionally unwrapping Compat types to expose the + * underlying instance. Throws if `obj` is not an instance of `T`. + * + * This cast is used in the Lite and Full SDK to verify instance types for + * arguments passed to the public API. + * @internal + */ +export declare function cast(obj: object, constructor: { + new (...args: any[]): T; +}): T | never; +export declare function validatePositiveNumber(functionName: string, n: number): void; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/json_validation.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/json_validation.d.ts new file mode 100644 index 0000000..df52006 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/json_validation.d.ts @@ -0,0 +1,70 @@ +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A list of data types Firestore objects may serialize in their toJSON implemenetations. + * @private + * @internal + */ +export type JsonTypeDesc = 'object' | 'string' | 'number' | 'boolean' | 'null' | 'undefined'; +/** + * An association of JsonTypeDesc values to their native types. + * @private + * @internal + */ +export type TSType = T extends 'object' ? object : T extends 'string' ? string : T extends 'number' ? number : T extends 'boolean' ? boolean : T extends 'null' ? null : T extends 'undefined' ? undefined : never; +/** + * The representation of a JSON object property name and its type value. + * @private + * @internal + */ +export interface Property { + value?: TSType; + typeString: JsonTypeDesc; +} +/** + * A type Firestore data types may use to define the fields used in their JSON serialization. + * @private + * @internal + */ +export interface JsonSchema { + [key: string]: Property; +} +/** + * Associates the JSON property type to the native type and sets them to be Required. + * @private + * @internal + */ +export type Json = { + [K in keyof T]: Required['value']; +}; +/** + * Helper function to define a JSON schema {@link Property}. + * @private + * @internal + */ +export declare function property(typeString: T, optionalValue?: TSType): Property; +/** + * Validates the JSON object based on the provided schema, and narrows the type to the provided + * JSON schema. + * @private + * @internal + * + * @param json A JSON object to validate. + * @param scheme a {@link JsonSchema} that defines the properties to validate. + * @returns true if the JSON schema exists within the object. Throws a FirestoreError otherwise. + */ +export declare function validateJSON(json: object, schema: S): json is Json; diff --git a/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/log.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/log.d.ts new file mode 100644 index 0000000..f638baa --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/lite/firestore/src/util/log.d.ts @@ -0,0 +1,39 @@ +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { LogLevel, LogLevelString } from '@firebase/logger'; +export { LogLevel, LogLevelString }; +export declare function getLogLevel(): LogLevel; +/** + * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). + * + * @param logLevel - The verbosity you set for activity and error logging. Can + * be any of the following values: + * + *

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 0xd6db,\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\n/**\n * The smallest value representable by a 64-bit signed integer (long).\n */\nconst MIN_LONG_VALUE = '-9223372036854775808';\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 // Document keys are ordered first by numeric value (\"__id__\"),\n // then lexicographically by string value. Start the iterator at the minimum\n // possible Document key value.\n const prefix = new DocumentKey(\n collectionPath.child('__id' + MIN_LONG_VALUE + '__')\n );\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(0x251c, '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(\n 0xee44,\n 'orphanedDocuments is only valid during a transaction.'\n );\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isSafariOrWebkit } from '@firebase/util';\n\nimport { User } from '../auth/user';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { DocumentKeySet, documentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport {\n decodeResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { IndexedDbDocumentOverlayCache } from './indexeddb_document_overlay_cache';\nimport {\n dbDocumentSize,\n removeMutationBatch\n} from './indexeddb_mutation_batch_impl';\nimport { IndexedDbMutationQueue } from './indexeddb_mutation_queue';\nimport { newIndexedDbRemoteDocumentCache } from './indexeddb_remote_document_cache';\nimport {\n DbCollectionParent,\n DbDocumentMutation,\n DbMutationBatch,\n DbMutationQueue,\n DbRemoteDocument,\n DbRemoteDocumentGlobal,\n DbTarget,\n DbTargetDocument,\n DbTargetGlobal,\n SCHEMA_VERSION\n} from './indexeddb_schema';\nimport {\n DbRemoteDocument as DbRemoteDocumentLegacy,\n DbRemoteDocumentStore as DbRemoteDocumentStoreLegacy,\n DbRemoteDocumentKey as DbRemoteDocumentKeyLegacy\n} from './indexeddb_schema_legacy';\nimport {\n DbBundleKeyPath,\n DbBundleStore,\n DbClientMetadataKeyPath,\n DbClientMetadataStore,\n DbCollectionParentKey,\n DbCollectionParentKeyPath,\n DbCollectionParentStore,\n DbDocumentMutationKey,\n DbDocumentMutationStore,\n DbDocumentOverlayCollectionGroupOverlayIndex,\n DbDocumentOverlayCollectionGroupOverlayIndexPath,\n DbDocumentOverlayCollectionPathOverlayIndex,\n DbDocumentOverlayCollectionPathOverlayIndexPath,\n DbDocumentOverlayKeyPath,\n DbDocumentOverlayStore,\n DbGlobalsKeyPath,\n DbGlobalsStore,\n DbIndexConfigurationCollectionGroupIndex,\n DbIndexConfigurationCollectionGroupIndexPath,\n DbIndexConfigurationKeyPath,\n DbIndexConfigurationStore,\n DbIndexEntryDocumentKeyIndex,\n DbIndexEntryDocumentKeyIndexPath,\n DbIndexEntryKeyPath,\n DbIndexEntryStore,\n DbIndexStateKeyPath,\n DbIndexStateSequenceNumberIndex,\n DbIndexStateSequenceNumberIndexPath,\n DbIndexStateStore,\n DbMutationBatchKey,\n DbMutationBatchKeyPath,\n DbMutationBatchStore,\n DbMutationBatchUserMutationsIndex,\n DbMutationBatchUserMutationsKeyPath,\n DbMutationQueueKey,\n DbMutationQueueKeyPath,\n DbMutationQueueStore,\n DbNamedQueryKeyPath,\n DbNamedQueryStore,\n DbPrimaryClientStore,\n DbRemoteDocumentCollectionGroupIndex,\n DbRemoteDocumentCollectionGroupIndexPath,\n DbRemoteDocumentDocumentKeyIndex,\n DbRemoteDocumentDocumentKeyIndexPath,\n DbRemoteDocumentGlobalKey,\n DbRemoteDocumentGlobalStore,\n DbRemoteDocumentKey,\n DbRemoteDocumentKeyPath,\n DbRemoteDocumentStore,\n DbTargetDocumentDocumentTargetsIndex,\n DbTargetDocumentDocumentTargetsKeyPath,\n DbTargetDocumentKey,\n DbTargetDocumentKeyPath,\n DbTargetDocumentStore,\n DbTargetGlobalKey,\n DbTargetGlobalStore,\n DbTargetKey,\n DbTargetKeyPath,\n DbTargetQueryTargetsIndexName,\n DbTargetQueryTargetsKeyPath,\n DbTargetStore\n} from './indexeddb_sentinels';\nimport { IndexedDbTransaction } from './indexeddb_transaction';\nimport { LocalDocumentsView } from './local_documents_view';\nimport {\n fromDbMutationBatch,\n fromDbTarget,\n LocalSerializer,\n toDbTarget\n} from './local_serializer';\nimport { MemoryCollectionParentIndex } from './memory_index_manager';\nimport { MemoryEagerDelegate, MemoryPersistence } from './memory_persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { SimpleDbSchemaConverter, SimpleDbTransaction } from './simple_db';\n\n/** Performs database creation and schema upgrades. */\nexport class SchemaConverter implements SimpleDbSchemaConverter {\n constructor(private readonly serializer: LocalSerializer) {}\n\n /**\n * Performs database creation and schema upgrades.\n *\n * Note that in production, this method is only ever used to upgrade the schema\n * to SCHEMA_VERSION. Different values of toVersion are only used for testing\n * and local feature development.\n */\n createOrUpgrade(\n db: IDBDatabase,\n txn: IDBTransaction,\n fromVersion: number,\n toVersion: number\n ): PersistencePromise {\n debugAssert(\n fromVersion < toVersion &&\n fromVersion >= 0 &&\n toVersion <= SCHEMA_VERSION,\n `Unexpected schema upgrade from v${fromVersion} to v${toVersion}.`\n );\n\n const simpleDbTransaction = new SimpleDbTransaction('createOrUpgrade', txn);\n\n if (fromVersion < 1 && toVersion >= 1) {\n createPrimaryClientStore(db);\n createMutationQueue(db);\n createQueryCache(db);\n createLegacyRemoteDocumentCache(db);\n }\n\n // Migration 2 to populate the targetGlobal object no longer needed since\n // migration 3 unconditionally clears it.\n\n let p = PersistencePromise.resolve();\n if (fromVersion < 3 && toVersion >= 3) {\n // Brand new clients don't need to drop and recreate--only clients that\n // potentially have corrupt data.\n if (fromVersion !== 0) {\n dropQueryCache(db);\n createQueryCache(db);\n }\n p = p.next(() => writeEmptyTargetGlobalEntry(simpleDbTransaction));\n }\n\n if (fromVersion < 4 && toVersion >= 4) {\n if (fromVersion !== 0) {\n // Schema version 3 uses auto-generated keys to generate globally unique\n // mutation batch IDs (this was previously ensured internally by the\n // client). To migrate to the new schema, we have to read all mutations\n // and write them back out. We preserve the existing batch IDs to guarantee\n // consistency with other object stores. Any further mutation batch IDs will\n // be auto-generated.\n p = p.next(() =>\n upgradeMutationBatchSchemaAndMigrateData(db, simpleDbTransaction)\n );\n }\n\n p = p.next(() => {\n createClientMetadataStore(db);\n });\n }\n\n if (fromVersion < 5 && toVersion >= 5) {\n p = p.next(() => this.removeAcknowledgedMutations(simpleDbTransaction));\n }\n\n if (fromVersion < 6 && toVersion >= 6) {\n p = p.next(() => {\n createDocumentGlobalStore(db);\n return this.addDocumentGlobal(simpleDbTransaction);\n });\n }\n\n if (fromVersion < 7 && toVersion >= 7) {\n p = p.next(() => this.ensureSequenceNumbers(simpleDbTransaction));\n }\n\n if (fromVersion < 8 && toVersion >= 8) {\n p = p.next(() =>\n this.createCollectionParentIndex(db, simpleDbTransaction)\n );\n }\n\n if (fromVersion < 9 && toVersion >= 9) {\n p = p.next(() => {\n // Multi-Tab used to manage its own changelog, but this has been moved\n // to the DbRemoteDocument object store itself. Since the previous change\n // log only contained transient data, we can drop its object store.\n dropRemoteDocumentChangesStore(db);\n\n // Note: Schema version 9 used to create a read time index for the\n // RemoteDocumentCache. This is now done with schema version 13.\n });\n }\n\n if (fromVersion < 10 && toVersion >= 10) {\n p = p.next(() => this.rewriteCanonicalIds(simpleDbTransaction));\n }\n\n if (fromVersion < 11 && toVersion >= 11) {\n p = p.next(() => {\n createBundlesStore(db);\n createNamedQueriesStore(db);\n });\n }\n\n if (fromVersion < 12 && toVersion >= 12) {\n p = p.next(() => {\n createDocumentOverlayStore(db);\n });\n }\n\n if (fromVersion < 13 && toVersion >= 13) {\n p = p\n .next(() => createRemoteDocumentCache(db))\n .next(() => this.rewriteRemoteDocumentCache(db, simpleDbTransaction))\n .next(() => db.deleteObjectStore(DbRemoteDocumentStoreLegacy));\n }\n\n if (fromVersion < 14 && toVersion >= 14) {\n p = p.next(() => this.runOverlayMigration(db, simpleDbTransaction));\n }\n\n if (fromVersion < 15 && toVersion >= 15) {\n p = p.next(() => createFieldIndex(db));\n }\n\n if (fromVersion < 16 && toVersion >= 16) {\n // Clear the object stores to remove possibly corrupted index entries\n p = p\n .next(() => {\n const indexStateStore = txn.objectStore(DbIndexStateStore);\n indexStateStore.clear();\n })\n .next(() => {\n const indexEntryStore = txn.objectStore(DbIndexEntryStore);\n indexEntryStore.clear();\n });\n }\n\n if (fromVersion < 17 && toVersion >= 17) {\n p = p.next(() => {\n createGlobalsStore(db);\n });\n }\n\n if (fromVersion < 18 && toVersion >= 18) {\n // Clear the IndexEntryStores on WebKit and Safari to remove possibly\n // corrupted index entries\n if (isSafariOrWebkit()) {\n p = p\n .next(() => {\n const indexStateStore = txn.objectStore(DbIndexStateStore);\n indexStateStore.clear();\n })\n .next(() => {\n const indexEntryStore = txn.objectStore(DbIndexEntryStore);\n indexEntryStore.clear();\n });\n }\n }\n\n return p;\n }\n\n private addDocumentGlobal(\n txn: SimpleDbTransaction\n ): PersistencePromise {\n let byteSize = 0;\n return txn\n .store(\n DbRemoteDocumentStoreLegacy\n )\n .iterate((_, doc) => {\n byteSize += dbDocumentSize(doc);\n })\n .next(() => {\n const metadata: DbRemoteDocumentGlobal = { byteSize };\n return txn\n .store(\n DbRemoteDocumentGlobalStore\n )\n .put(DbRemoteDocumentGlobalKey, metadata);\n });\n }\n\n private removeAcknowledgedMutations(\n txn: SimpleDbTransaction\n ): PersistencePromise {\n const queuesStore = txn.store(\n DbMutationQueueStore\n );\n const mutationsStore = txn.store(\n DbMutationBatchStore\n );\n\n return queuesStore.loadAll().next(queues => {\n return PersistencePromise.forEach(queues, (queue: DbMutationQueue) => {\n const range = IDBKeyRange.bound(\n [queue.userId, BATCHID_UNKNOWN],\n [queue.userId, queue.lastAcknowledgedBatchId]\n );\n\n return mutationsStore\n .loadAll(DbMutationBatchUserMutationsIndex, range)\n .next(dbBatches => {\n return PersistencePromise.forEach(\n dbBatches,\n (dbBatch: DbMutationBatch) => {\n hardAssert(\n dbBatch.userId === queue.userId,\n 0x48da,\n `Cannot process batch from unexpected user`,\n { batchId: dbBatch.batchId }\n );\n const batch = fromDbMutationBatch(this.serializer, dbBatch);\n\n return removeMutationBatch(txn, queue.userId, batch).next(\n () => {}\n );\n }\n );\n });\n });\n });\n }\n\n /**\n * Ensures that every document in the remote document cache has a corresponding sentinel row\n * with a sequence number. Missing rows are given the most recently used sequence number.\n */\n private ensureSequenceNumbers(\n txn: SimpleDbTransaction\n ): PersistencePromise {\n const documentTargetStore = txn.store<\n DbTargetDocumentKey,\n DbTargetDocument\n >(DbTargetDocumentStore);\n const documentsStore = txn.store<\n DbRemoteDocumentKeyLegacy,\n DbRemoteDocumentKeyLegacy\n >(DbRemoteDocumentStoreLegacy);\n const globalTargetStore = txn.store(\n DbTargetGlobalStore\n );\n\n return globalTargetStore.get(DbTargetGlobalKey).next(metadata => {\n debugAssert(\n !!metadata,\n 'Metadata should have been written during the version 3 migration'\n );\n const writeSentinelKey = (\n path: ResourcePath\n ): PersistencePromise => {\n return documentTargetStore.put({\n targetId: 0,\n path: encodeResourcePath(path),\n sequenceNumber: metadata!.highestListenSequenceNumber!\n });\n };\n\n const promises: Array> = [];\n return documentsStore\n .iterate((key, doc) => {\n const path = new ResourcePath(key);\n const docSentinelKey = sentinelKey(path);\n promises.push(\n documentTargetStore.get(docSentinelKey).next(maybeSentinel => {\n if (!maybeSentinel) {\n return writeSentinelKey(path);\n } else {\n return PersistencePromise.resolve();\n }\n })\n );\n })\n .next(() => PersistencePromise.waitFor(promises));\n });\n }\n\n private createCollectionParentIndex(\n db: IDBDatabase,\n txn: SimpleDbTransaction\n ): PersistencePromise {\n // Create the index.\n db.createObjectStore(DbCollectionParentStore, {\n keyPath: DbCollectionParentKeyPath\n });\n\n const collectionParentsStore = txn.store<\n DbCollectionParentKey,\n DbCollectionParent\n >(DbCollectionParentStore);\n\n // Helper to add an index entry iff we haven't already written it.\n const cache = new MemoryCollectionParentIndex();\n const addEntry = (\n collectionPath: ResourcePath\n ): PersistencePromise | undefined => {\n if (cache.add(collectionPath)) {\n const collectionId = collectionPath.lastSegment();\n const parentPath = collectionPath.popLast();\n return collectionParentsStore.put({\n collectionId,\n parent: encodeResourcePath(parentPath)\n });\n }\n };\n\n // Index existing remote documents.\n return txn\n .store(\n DbRemoteDocumentStoreLegacy\n )\n .iterate({ keysOnly: true }, (pathSegments, _) => {\n const path = new ResourcePath(pathSegments);\n return addEntry(path.popLast());\n })\n .next(() => {\n // Index existing mutations.\n return txn\n .store(\n DbDocumentMutationStore\n )\n .iterate({ keysOnly: true }, ([userID, encodedPath, batchId], _) => {\n const path = decodeResourcePath(encodedPath);\n return addEntry(path.popLast());\n });\n });\n }\n\n private rewriteCanonicalIds(\n txn: SimpleDbTransaction\n ): PersistencePromise {\n const targetStore = txn.store(DbTargetStore);\n return targetStore.iterate((key, originalDbTarget) => {\n const originalTargetData = fromDbTarget(originalDbTarget);\n const updatedDbTarget = toDbTarget(this.serializer, originalTargetData);\n return targetStore.put(updatedDbTarget);\n });\n }\n\n private rewriteRemoteDocumentCache(\n db: IDBDatabase,\n transaction: SimpleDbTransaction\n ): PersistencePromise {\n const legacyRemoteDocumentStore = transaction.store<\n DbRemoteDocumentKeyLegacy,\n DbRemoteDocumentLegacy\n >(DbRemoteDocumentStoreLegacy);\n\n const writes: Array> = [];\n return legacyRemoteDocumentStore\n .iterate((_, legacyDocument) => {\n const remoteDocumentStore = transaction.store<\n DbRemoteDocumentKey,\n DbRemoteDocument\n >(DbRemoteDocumentStore);\n\n const path = extractKey(legacyDocument).path.toArray();\n const dbRemoteDocument = {\n prefixPath: path.slice(0, path.length - 2),\n collectionGroup: path[path.length - 2],\n documentId: path[path.length - 1],\n readTime: legacyDocument.readTime || [0, 0],\n unknownDocument: legacyDocument.unknownDocument,\n noDocument: legacyDocument.noDocument,\n document: legacyDocument.document,\n hasCommittedMutations: !!legacyDocument.hasCommittedMutations\n };\n writes.push(remoteDocumentStore.put(dbRemoteDocument));\n })\n .next(() => PersistencePromise.waitFor(writes));\n }\n\n private runOverlayMigration(\n db: IDBDatabase,\n transaction: SimpleDbTransaction\n ): PersistencePromise {\n const mutationsStore = transaction.store<\n DbMutationBatchKey,\n DbMutationBatch\n >(DbMutationBatchStore);\n\n const remoteDocumentCache = newIndexedDbRemoteDocumentCache(\n this.serializer\n );\n const memoryPersistence = new MemoryPersistence(\n MemoryEagerDelegate.factory,\n this.serializer.remoteSerializer\n );\n\n return mutationsStore.loadAll().next(dbBatches => {\n const userToDocumentSet = new Map();\n dbBatches.forEach(dbBatch => {\n let documentSet =\n userToDocumentSet.get(dbBatch.userId) ?? documentKeySet();\n const batch = fromDbMutationBatch(this.serializer, dbBatch);\n batch.keys().forEach(key => (documentSet = documentSet.add(key)));\n userToDocumentSet.set(dbBatch.userId, documentSet);\n });\n return PersistencePromise.forEach(\n userToDocumentSet,\n (allDocumentKeysForUser, userId) => {\n const user = new User(userId);\n const documentOverlayCache = IndexedDbDocumentOverlayCache.forUser(\n this.serializer,\n user\n );\n // NOTE: The index manager and the reference delegate are\n // irrelevant for the purpose of recalculating and saving\n // overlays. We can therefore simply use the memory\n // implementation.\n const indexManager = memoryPersistence.getIndexManager(user);\n const mutationQueue = IndexedDbMutationQueue.forUser(\n user,\n this.serializer,\n indexManager,\n memoryPersistence.referenceDelegate\n );\n const localDocumentsView = new LocalDocumentsView(\n remoteDocumentCache,\n mutationQueue,\n documentOverlayCache,\n indexManager\n );\n return localDocumentsView\n .recalculateAndSaveOverlaysForDocumentKeys(\n new IndexedDbTransaction(transaction, ListenSequence.INVALID),\n allDocumentKeysForUser\n )\n .next();\n }\n );\n });\n }\n}\n\nfunction sentinelKey(path: ResourcePath): DbTargetDocumentKey {\n return [0, encodeResourcePath(path)];\n}\n\nfunction createPrimaryClientStore(db: IDBDatabase): void {\n db.createObjectStore(DbPrimaryClientStore);\n}\n\nfunction createMutationQueue(db: IDBDatabase): void {\n db.createObjectStore(DbMutationQueueStore, {\n keyPath: DbMutationQueueKeyPath\n });\n\n const mutationBatchesStore = db.createObjectStore(DbMutationBatchStore, {\n keyPath: DbMutationBatchKeyPath,\n autoIncrement: true\n });\n mutationBatchesStore.createIndex(\n DbMutationBatchUserMutationsIndex,\n DbMutationBatchUserMutationsKeyPath,\n { unique: true }\n );\n\n db.createObjectStore(DbDocumentMutationStore);\n}\n\n/**\n * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads\n * and rewrites all data.\n */\nfunction upgradeMutationBatchSchemaAndMigrateData(\n db: IDBDatabase,\n txn: SimpleDbTransaction\n): PersistencePromise {\n const v1MutationsStore = txn.store<[string, number], DbMutationBatch>(\n DbMutationBatchStore\n );\n return v1MutationsStore.loadAll().next(existingMutations => {\n db.deleteObjectStore(DbMutationBatchStore);\n\n const mutationsStore = db.createObjectStore(DbMutationBatchStore, {\n keyPath: DbMutationBatchKeyPath,\n autoIncrement: true\n });\n mutationsStore.createIndex(\n DbMutationBatchUserMutationsIndex,\n DbMutationBatchUserMutationsKeyPath,\n { unique: true }\n );\n\n const v3MutationsStore = txn.store(\n DbMutationBatchStore\n );\n const writeAll = existingMutations.map(mutation =>\n v3MutationsStore.put(mutation)\n );\n\n return PersistencePromise.waitFor(writeAll);\n });\n}\n\nfunction createLegacyRemoteDocumentCache(db: IDBDatabase): void {\n db.createObjectStore(DbRemoteDocumentStoreLegacy);\n}\n\nfunction createRemoteDocumentCache(db: IDBDatabase): void {\n const remoteDocumentStore = db.createObjectStore(DbRemoteDocumentStore, {\n keyPath: DbRemoteDocumentKeyPath\n });\n remoteDocumentStore.createIndex(\n DbRemoteDocumentDocumentKeyIndex,\n DbRemoteDocumentDocumentKeyIndexPath\n );\n remoteDocumentStore.createIndex(\n DbRemoteDocumentCollectionGroupIndex,\n DbRemoteDocumentCollectionGroupIndexPath\n );\n}\n\nfunction createDocumentGlobalStore(db: IDBDatabase): void {\n db.createObjectStore(DbRemoteDocumentGlobalStore);\n}\n\nfunction createQueryCache(db: IDBDatabase): void {\n const targetDocumentsStore = db.createObjectStore(DbTargetDocumentStore, {\n keyPath: DbTargetDocumentKeyPath\n });\n targetDocumentsStore.createIndex(\n DbTargetDocumentDocumentTargetsIndex,\n DbTargetDocumentDocumentTargetsKeyPath,\n { unique: true }\n );\n\n const targetStore = db.createObjectStore(DbTargetStore, {\n keyPath: DbTargetKeyPath\n });\n\n // NOTE: This is unique only because the TargetId is the suffix.\n targetStore.createIndex(\n DbTargetQueryTargetsIndexName,\n DbTargetQueryTargetsKeyPath,\n { unique: true }\n );\n db.createObjectStore(DbTargetGlobalStore);\n}\n\nfunction dropQueryCache(db: IDBDatabase): void {\n db.deleteObjectStore(DbTargetDocumentStore);\n db.deleteObjectStore(DbTargetStore);\n db.deleteObjectStore(DbTargetGlobalStore);\n}\n\nfunction dropRemoteDocumentChangesStore(db: IDBDatabase): void {\n if (db.objectStoreNames.contains('remoteDocumentChanges')) {\n db.deleteObjectStore('remoteDocumentChanges');\n }\n}\n\n/**\n * Creates the target global singleton row.\n *\n * @param txn - The version upgrade transaction for indexeddb\n */\nfunction writeEmptyTargetGlobalEntry(\n txn: SimpleDbTransaction\n): PersistencePromise {\n const globalStore = txn.store(\n DbTargetGlobalStore\n );\n const metadata: DbTargetGlobal = {\n highestTargetId: 0,\n highestListenSequenceNumber: 0,\n lastRemoteSnapshotVersion: SnapshotVersion.min().toTimestamp(),\n targetCount: 0\n };\n return globalStore.put(DbTargetGlobalKey, metadata);\n}\n\nfunction createClientMetadataStore(db: IDBDatabase): void {\n db.createObjectStore(DbClientMetadataStore, {\n keyPath: DbClientMetadataKeyPath\n });\n}\n\nfunction createBundlesStore(db: IDBDatabase): void {\n db.createObjectStore(DbBundleStore, {\n keyPath: DbBundleKeyPath\n });\n}\n\nfunction createNamedQueriesStore(db: IDBDatabase): void {\n db.createObjectStore(DbNamedQueryStore, {\n keyPath: DbNamedQueryKeyPath\n });\n}\n\nfunction createFieldIndex(db: IDBDatabase): void {\n const indexConfigurationStore = db.createObjectStore(\n DbIndexConfigurationStore,\n {\n keyPath: DbIndexConfigurationKeyPath,\n autoIncrement: true\n }\n );\n indexConfigurationStore.createIndex(\n DbIndexConfigurationCollectionGroupIndex,\n DbIndexConfigurationCollectionGroupIndexPath,\n { unique: false }\n );\n\n const indexStateStore = db.createObjectStore(DbIndexStateStore, {\n keyPath: DbIndexStateKeyPath\n });\n indexStateStore.createIndex(\n DbIndexStateSequenceNumberIndex,\n DbIndexStateSequenceNumberIndexPath,\n { unique: false }\n );\n\n const indexEntryStore = db.createObjectStore(DbIndexEntryStore, {\n keyPath: DbIndexEntryKeyPath\n });\n indexEntryStore.createIndex(\n DbIndexEntryDocumentKeyIndex,\n DbIndexEntryDocumentKeyIndexPath,\n { unique: false }\n );\n}\n\nfunction createDocumentOverlayStore(db: IDBDatabase): void {\n const documentOverlayStore = db.createObjectStore(DbDocumentOverlayStore, {\n keyPath: DbDocumentOverlayKeyPath\n });\n documentOverlayStore.createIndex(\n DbDocumentOverlayCollectionPathOverlayIndex,\n DbDocumentOverlayCollectionPathOverlayIndexPath,\n { unique: false }\n );\n documentOverlayStore.createIndex(\n DbDocumentOverlayCollectionGroupOverlayIndex,\n DbDocumentOverlayCollectionGroupOverlayIndexPath,\n { unique: false }\n );\n}\n\nfunction createGlobalsStore(db: IDBDatabase): void {\n db.createObjectStore(DbGlobalsStore, {\n keyPath: DbGlobalsKeyPath\n });\n}\n\nfunction extractKey(remoteDoc: DbRemoteDocumentLegacy): DocumentKey {\n if (remoteDoc.document) {\n return new DocumentKey(\n ResourcePath.fromString(remoteDoc.document.name!).popFirst(5)\n );\n } else if (remoteDoc.noDocument) {\n return DocumentKey.fromSegments(remoteDoc.noDocument.path);\n } else if (remoteDoc.unknownDocument) {\n return DocumentKey.fromSegments(remoteDoc.unknownDocument.path);\n } else {\n return fail(0x8faf, 'Unexpected DbRemoteDocument');\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isSafari } from '@firebase/util';\n\nimport { User } from '../auth/user';\nimport { DatabaseId } from '../core/database_info';\nimport { ListenSequence, SequenceNumberSyncer } from '../core/listen_sequence';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logError } from '../util/log';\nimport { DocumentLike, WindowLike } from '../util/types';\n\nimport { BundleCache } from './bundle_cache';\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { GlobalsCache } from './globals_cache';\nimport { IndexManager } from './index_manager';\nimport { IndexedDbBundleCache } from './indexeddb_bundle_cache';\nimport { IndexedDbDocumentOverlayCache } from './indexeddb_document_overlay_cache';\nimport { IndexedDbGlobalsCache } from './indexeddb_globals_cache';\nimport { IndexedDbIndexManager } from './indexeddb_index_manager';\nimport { IndexedDbLruDelegateImpl } from './indexeddb_lru_delegate_impl';\nimport { IndexedDbMutationQueue } from './indexeddb_mutation_queue';\nimport {\n IndexedDbRemoteDocumentCache,\n newIndexedDbRemoteDocumentCache\n} from './indexeddb_remote_document_cache';\nimport {\n DbClientMetadata,\n DbPrimaryClient,\n SCHEMA_VERSION\n} from './indexeddb_schema';\nimport { SchemaConverter } from './indexeddb_schema_converter';\nimport {\n DbClientMetadataKey,\n DbClientMetadataStore,\n DbPrimaryClientKey,\n DbPrimaryClientStore,\n getObjectStores\n} from './indexeddb_sentinels';\nimport { IndexedDbTargetCache } from './indexeddb_target_cache';\nimport { getStore, IndexedDbTransaction } from './indexeddb_transaction';\nimport { LocalSerializer } from './local_serializer';\nimport { LruParams } from './lru_garbage_collector';\nimport { Persistence, PrimaryStateListener } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport {\n PersistenceTransaction,\n PersistenceTransactionMode,\n PRIMARY_LEASE_LOST_ERROR_MSG\n} from './persistence_transaction';\nimport { ClientId } from './shared_client_state';\nimport {\n isIndexedDbTransactionError,\n SimpleDb,\n SimpleDbStore\n} from './simple_db';\n\nconst LOG_TAG = 'IndexedDbPersistence';\n\n/**\n * Oldest acceptable age in milliseconds for client metadata before the client\n * is considered inactive and its associated data is garbage collected.\n */\nconst MAX_CLIENT_AGE_MS = 30 * 60 * 1000; // 30 minutes\n\n/**\n * Oldest acceptable metadata age for clients that may participate in the\n * primary lease election. Clients that have not updated their client metadata\n * within 5 seconds are not eligible to receive a primary lease.\n */\nconst MAX_PRIMARY_ELIGIBLE_AGE_MS = 5000;\n\n/**\n * The interval at which clients will update their metadata, including\n * refreshing their primary lease if held or potentially trying to acquire it if\n * not held.\n *\n * Primary clients may opportunistically refresh their metadata earlier\n * if they're already performing an IndexedDB operation.\n */\nconst CLIENT_METADATA_REFRESH_INTERVAL_MS = 4000;\n/** User-facing error when the primary lease is required but not available. */\nconst PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG =\n 'Failed to obtain exclusive access to the persistence layer. To allow ' +\n 'shared access, multi-tab synchronization has to be enabled in all tabs. ' +\n 'If you are using `experimentalForceOwningTab:true`, make sure that only ' +\n 'one tab has persistence enabled at any given time.';\nconst UNSUPPORTED_PLATFORM_ERROR_MSG =\n 'This platform is either missing IndexedDB or is known to have ' +\n 'an incomplete implementation. Offline persistence has been disabled.';\n\n// The format of the LocalStorage key that stores zombied client is:\n// firestore_zombie__\nconst ZOMBIED_CLIENTS_KEY_PREFIX = 'firestore_zombie';\n\n/**\n * The name of the main (and currently only) IndexedDB database. This name is\n * appended to the prefix provided to the IndexedDbPersistence constructor.\n */\nexport const MAIN_DATABASE = 'main';\n\n/**\n * An IndexedDB-backed instance of Persistence. Data is stored persistently\n * across sessions.\n *\n * On Web only, the Firestore SDKs support shared access to its persistence\n * layer. This allows multiple browser tabs to read and write to IndexedDb and\n * to synchronize state even without network connectivity. Shared access is\n * currently optional and not enabled unless all clients invoke\n * `enablePersistence()` with `{synchronizeTabs:true}`.\n *\n * In multi-tab mode, if multiple clients are active at the same time, the SDK\n * will designate one client as the \"primary client\". An effort is made to pick\n * a visible, network-connected and active client, and this client is\n * responsible for letting other clients know about its presence. The primary\n * client writes a unique client-generated identifier (the client ID) to\n * IndexedDb’s \"owner\" store every 4 seconds. If the primary client fails to\n * update this entry, another client can acquire the lease and take over as\n * primary.\n *\n * Some persistence operations in the SDK are designated as primary-client only\n * operations. This includes the acknowledgment of mutations and all updates of\n * remote documents. The effects of these operations are written to persistence\n * and then broadcast to other tabs via LocalStorage (see\n * `WebStorageSharedClientState`), which then refresh their state from\n * persistence.\n *\n * Similarly, the primary client listens to notifications sent by secondary\n * clients to discover persistence changes written by secondary clients, such as\n * the addition of new mutations and query targets.\n *\n * If multi-tab is not enabled and another tab already obtained the primary\n * lease, IndexedDbPersistence enters a failed state and all subsequent\n * operations will automatically fail.\n *\n * Additionally, there is an optimization so that when a tab is closed, the\n * primary lease is released immediately (this is especially important to make\n * sure that a refreshed tab is able to immediately re-acquire the primary\n * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload\n * since it is an asynchronous API. So in addition to attempting to give up the\n * lease, the leaseholder writes its client ID to a \"zombiedClient\" entry in\n * LocalStorage which acts as an indicator that another tab should go ahead and\n * take the primary lease immediately regardless of the current lease timestamp.\n *\n * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no\n * longer optional.\n */\nexport class IndexedDbPersistence implements Persistence {\n private simpleDb: SimpleDb;\n\n private listenSequence: ListenSequence | null = null;\n\n private _started = false;\n private isPrimary = false;\n private networkEnabled = true;\n private dbName: string;\n\n /** Our window.unload handler, if registered. */\n private windowUnloadHandler: (() => void) | null = null;\n private inForeground = false;\n\n private serializer: LocalSerializer;\n\n /** Our 'visibilitychange' listener if registered. */\n private documentVisibilityHandler: ((e?: Event) => void) | null = null;\n\n /** The client metadata refresh task. */\n private clientMetadataRefresher: DelayedOperation | null = null;\n\n /** The last time we garbage collected the client metadata object store. */\n private lastGarbageCollectionTime = Number.NEGATIVE_INFINITY;\n\n /** A listener to notify on primary state changes. */\n private primaryStateListener: PrimaryStateListener = _ => Promise.resolve();\n\n private readonly globalsCache: IndexedDbGlobalsCache;\n private readonly targetCache: IndexedDbTargetCache;\n private readonly remoteDocumentCache: IndexedDbRemoteDocumentCache;\n private readonly bundleCache: IndexedDbBundleCache;\n private readonly webStorage: Storage | null;\n readonly referenceDelegate: IndexedDbLruDelegateImpl;\n\n constructor(\n /**\n * Whether to synchronize the in-memory state of multiple tabs and share\n * access to local persistence.\n */\n private readonly allowTabSynchronization: boolean,\n\n private readonly persistenceKey: string,\n private readonly clientId: ClientId,\n lruParams: LruParams,\n private readonly queue: AsyncQueue,\n private readonly window: WindowLike | null,\n private readonly document: DocumentLike | null,\n serializer: JsonProtoSerializer,\n private readonly sequenceNumberSyncer: SequenceNumberSyncer,\n\n /**\n * If set to true, forcefully obtains database access. Existing tabs will\n * no longer be able to access IndexedDB.\n */\n private readonly forceOwningTab: boolean,\n private readonly schemaVersion = SCHEMA_VERSION\n ) {\n if (!IndexedDbPersistence.isAvailable()) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n UNSUPPORTED_PLATFORM_ERROR_MSG\n );\n }\n\n this.referenceDelegate = new IndexedDbLruDelegateImpl(this, lruParams);\n this.dbName = persistenceKey + MAIN_DATABASE;\n this.serializer = new LocalSerializer(serializer);\n this.simpleDb = new SimpleDb(\n this.dbName,\n this.schemaVersion,\n new SchemaConverter(this.serializer)\n );\n this.globalsCache = new IndexedDbGlobalsCache();\n this.targetCache = new IndexedDbTargetCache(\n this.referenceDelegate,\n this.serializer\n );\n this.remoteDocumentCache = newIndexedDbRemoteDocumentCache(this.serializer);\n this.bundleCache = new IndexedDbBundleCache();\n if (this.window && this.window.localStorage) {\n this.webStorage = this.window.localStorage;\n } else {\n this.webStorage = null;\n if (forceOwningTab === false) {\n logError(\n LOG_TAG,\n 'LocalStorage is unavailable. As a result, persistence may not work ' +\n 'reliably. In particular enablePersistence() could fail immediately ' +\n 'after refreshing the page.'\n );\n }\n }\n }\n\n /**\n * Attempt to start IndexedDb persistence.\n *\n * @returns Whether persistence was enabled.\n */\n start(): Promise {\n debugAssert(!this.started, 'IndexedDbPersistence double-started!');\n debugAssert(this.window !== null, \"Expected 'window' to be defined\");\n\n // NOTE: This is expected to fail sometimes (in the case of another tab\n // already having the persistence lock), so it's the first thing we should\n // do.\n return this.updateClientMetadataAndTryBecomePrimary()\n .then(() => {\n if (!this.isPrimary && !this.allowTabSynchronization) {\n // Fail `start()` if `synchronizeTabs` is disabled and we cannot\n // obtain the primary lease.\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG\n );\n }\n this.attachVisibilityHandler();\n this.attachWindowUnloadHook();\n\n this.scheduleClientMetadataAndPrimaryLeaseRefreshes();\n\n return this.runTransaction(\n 'getHighestListenSequenceNumber',\n 'readonly',\n txn => this.targetCache.getHighestSequenceNumber(txn)\n );\n })\n .then(highestListenSequenceNumber => {\n this.listenSequence = new ListenSequence(\n highestListenSequenceNumber,\n this.sequenceNumberSyncer\n );\n })\n .then(() => {\n this._started = true;\n })\n .catch(reason => {\n this.simpleDb && this.simpleDb.close();\n return Promise.reject(reason);\n });\n }\n\n /**\n * Registers a listener that gets called when the primary state of the\n * instance changes. Upon registering, this listener is invoked immediately\n * with the current primary state.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n setPrimaryStateListener(\n primaryStateListener: PrimaryStateListener\n ): Promise {\n this.primaryStateListener = async primaryState => {\n if (this.started) {\n return primaryStateListener(primaryState);\n }\n };\n return primaryStateListener(this.isPrimary);\n }\n\n /**\n * Registers a listener that gets called when the database receives a\n * version change event indicating that it has deleted.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n setDatabaseDeletedListener(\n databaseDeletedListener: () => Promise\n ): void {\n this.simpleDb.setVersionChangeListener(async event => {\n // Check if an attempt is made to delete IndexedDB.\n if (event.newVersion === null) {\n await databaseDeletedListener();\n }\n });\n }\n\n /**\n * Adjusts the current network state in the client's metadata, potentially\n * affecting the primary lease.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n setNetworkEnabled(networkEnabled: boolean): void {\n if (this.networkEnabled !== networkEnabled) {\n this.networkEnabled = networkEnabled;\n // Schedule a primary lease refresh for immediate execution. The eventual\n // lease update will be propagated via `primaryStateListener`.\n this.queue.enqueueAndForget(async () => {\n if (this.started) {\n await this.updateClientMetadataAndTryBecomePrimary();\n }\n });\n }\n }\n\n /**\n * Updates the client metadata in IndexedDb and attempts to either obtain or\n * extend the primary lease for the local client. Asynchronously notifies the\n * primary state listener if the client either newly obtained or released its\n * primary lease.\n */\n private updateClientMetadataAndTryBecomePrimary(): Promise {\n return this.runTransaction(\n 'updateClientMetadataAndTryBecomePrimary',\n 'readwrite',\n txn => {\n const metadataStore = clientMetadataStore(txn);\n return metadataStore\n .put({\n clientId: this.clientId,\n updateTimeMs: Date.now(),\n networkEnabled: this.networkEnabled,\n inForeground: this.inForeground\n })\n .next(() => {\n if (this.isPrimary) {\n return this.verifyPrimaryLease(txn).next(success => {\n if (!success) {\n this.isPrimary = false;\n this.queue.enqueueRetryable(() =>\n this.primaryStateListener(false)\n );\n }\n });\n }\n })\n .next(() => this.canActAsPrimary(txn))\n .next(canActAsPrimary => {\n if (this.isPrimary && !canActAsPrimary) {\n return this.releasePrimaryLeaseIfHeld(txn).next(() => false);\n } else if (canActAsPrimary) {\n return this.acquireOrExtendPrimaryLease(txn).next(() => true);\n } else {\n return /* canActAsPrimary= */ false;\n }\n });\n }\n )\n .catch(e => {\n if (isIndexedDbTransactionError(e)) {\n logDebug(LOG_TAG, 'Failed to extend owner lease: ', e);\n // Proceed with the existing state. Any subsequent access to\n // IndexedDB will verify the lease.\n return this.isPrimary;\n }\n\n if (!this.allowTabSynchronization) {\n throw e;\n }\n\n logDebug(\n LOG_TAG,\n 'Releasing owner lease after error during lease refresh',\n e\n );\n return /* isPrimary= */ false;\n })\n .then(isPrimary => {\n if (this.isPrimary !== isPrimary) {\n this.queue.enqueueRetryable(() =>\n this.primaryStateListener(isPrimary)\n );\n }\n this.isPrimary = isPrimary;\n });\n }\n\n private verifyPrimaryLease(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const store = primaryClientStore(txn);\n return store.get(DbPrimaryClientKey).next(primaryClient => {\n return PersistencePromise.resolve(this.isLocalClient(primaryClient));\n });\n }\n\n private removeClientMetadata(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const metadataStore = clientMetadataStore(txn);\n return metadataStore.delete(this.clientId);\n }\n\n /**\n * If the garbage collection threshold has passed, prunes the\n * RemoteDocumentChanges and the ClientMetadata store based on the last update\n * time of all clients.\n */\n private async maybeGarbageCollectMultiClientState(): Promise {\n if (\n this.isPrimary &&\n !this.isWithinAge(this.lastGarbageCollectionTime, MAX_CLIENT_AGE_MS)\n ) {\n this.lastGarbageCollectionTime = Date.now();\n\n const inactiveClients = await this.runTransaction(\n 'maybeGarbageCollectMultiClientState',\n 'readwrite-primary',\n txn => {\n const metadataStore = getStore(\n txn,\n DbClientMetadataStore\n );\n\n return metadataStore.loadAll().next(existingClients => {\n const active = this.filterActiveClients(\n existingClients,\n MAX_CLIENT_AGE_MS\n );\n const inactive = existingClients.filter(\n client => active.indexOf(client) === -1\n );\n\n // Delete metadata for clients that are no longer considered active.\n return PersistencePromise.forEach(\n inactive,\n (inactiveClient: DbClientMetadata) =>\n metadataStore.delete(inactiveClient.clientId)\n ).next(() => inactive);\n });\n }\n ).catch(() => {\n // Ignore primary lease violations or any other type of error. The next\n // primary will run `maybeGarbageCollectMultiClientState()` again.\n // We don't use `ignoreIfPrimaryLeaseLoss()` since we don't want to depend\n // on LocalStore.\n return [];\n });\n\n // Delete potential leftover entries that may continue to mark the\n // inactive clients as zombied in LocalStorage.\n // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for\n // the client atomically, but we can't. So we opt to delete the IndexedDb\n // entries first to avoid potentially reviving a zombied client.\n if (this.webStorage) {\n for (const inactiveClient of inactiveClients) {\n this.webStorage.removeItem(\n this.zombiedClientLocalStorageKey(inactiveClient.clientId)\n );\n }\n }\n }\n }\n\n /**\n * Schedules a recurring timer to update the client metadata and to either\n * extend or acquire the primary lease if the client is eligible.\n */\n private scheduleClientMetadataAndPrimaryLeaseRefreshes(): void {\n this.clientMetadataRefresher = this.queue.enqueueAfterDelay(\n TimerId.ClientMetadataRefresh,\n CLIENT_METADATA_REFRESH_INTERVAL_MS,\n () => {\n return this.updateClientMetadataAndTryBecomePrimary()\n .then(() => this.maybeGarbageCollectMultiClientState())\n .then(() => this.scheduleClientMetadataAndPrimaryLeaseRefreshes());\n }\n );\n }\n\n /** Checks whether `client` is the local client. */\n private isLocalClient(client: DbPrimaryClient | null): boolean {\n return client ? client.ownerId === this.clientId : false;\n }\n\n /**\n * Evaluate the state of all active clients and determine whether the local\n * client is or can act as the holder of the primary lease. Returns whether\n * the client is eligible for the lease, but does not actually acquire it.\n * May return 'false' even if there is no active leaseholder and another\n * (foreground) client should become leaseholder instead.\n */\n private canActAsPrimary(\n txn: PersistenceTransaction\n ): PersistencePromise {\n if (this.forceOwningTab) {\n return PersistencePromise.resolve(true);\n }\n const store = primaryClientStore(txn);\n return store\n .get(DbPrimaryClientKey)\n .next(currentPrimary => {\n const currentLeaseIsValid =\n currentPrimary !== null &&\n this.isWithinAge(\n currentPrimary.leaseTimestampMs,\n MAX_PRIMARY_ELIGIBLE_AGE_MS\n ) &&\n !this.isClientZombied(currentPrimary.ownerId);\n\n // A client is eligible for the primary lease if:\n // - its network is enabled and the client's tab is in the foreground.\n // - its network is enabled and no other client's tab is in the\n // foreground.\n // - every clients network is disabled and the client's tab is in the\n // foreground.\n // - every clients network is disabled and no other client's tab is in\n // the foreground.\n // - the `forceOwningTab` setting was passed in.\n if (currentLeaseIsValid) {\n if (this.isLocalClient(currentPrimary) && this.networkEnabled) {\n return true;\n }\n\n if (!this.isLocalClient(currentPrimary)) {\n if (!currentPrimary!.allowTabSynchronization) {\n // Fail the `canActAsPrimary` check if the current leaseholder has\n // not opted into multi-tab synchronization. If this happens at\n // client startup, we reject the Promise returned by\n // `enablePersistence()` and the user can continue to use Firestore\n // with in-memory persistence.\n // If this fails during a lease refresh, we will instead block the\n // AsyncQueue from executing further operations. Note that this is\n // acceptable since mixing & matching different `synchronizeTabs`\n // settings is not supported.\n //\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can\n // no longer be turned off.\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG\n );\n }\n\n return false;\n }\n }\n\n if (this.networkEnabled && this.inForeground) {\n return true;\n }\n\n return clientMetadataStore(txn)\n .loadAll()\n .next(existingClients => {\n // Process all existing clients and determine whether at least one of\n // them is better suited to obtain the primary lease.\n const preferredCandidate = this.filterActiveClients(\n existingClients,\n MAX_PRIMARY_ELIGIBLE_AGE_MS\n ).find(otherClient => {\n if (this.clientId !== otherClient.clientId) {\n const otherClientHasBetterNetworkState =\n !this.networkEnabled && otherClient.networkEnabled;\n const otherClientHasBetterVisibility =\n !this.inForeground && otherClient.inForeground;\n const otherClientHasSameNetworkState =\n this.networkEnabled === otherClient.networkEnabled;\n if (\n otherClientHasBetterNetworkState ||\n (otherClientHasBetterVisibility &&\n otherClientHasSameNetworkState)\n ) {\n return true;\n }\n }\n return false;\n });\n return preferredCandidate === undefined;\n });\n })\n .next(canActAsPrimary => {\n if (this.isPrimary !== canActAsPrimary) {\n logDebug(\n LOG_TAG,\n `Client ${\n canActAsPrimary ? 'is' : 'is not'\n } eligible for a primary lease.`\n );\n }\n return canActAsPrimary;\n });\n }\n\n async shutdown(): Promise {\n // The shutdown() operations are idempotent and can be called even when\n // start() aborted (e.g. because it couldn't acquire the persistence lease).\n this._started = false;\n\n this.markClientZombied();\n if (this.clientMetadataRefresher) {\n this.clientMetadataRefresher.cancel();\n this.clientMetadataRefresher = null;\n }\n this.detachVisibilityHandler();\n this.detachWindowUnloadHook();\n\n // Use `SimpleDb.runTransaction` directly to avoid failing if another tab\n // has obtained the primary lease.\n await this.simpleDb.runTransaction(\n 'shutdown',\n 'readwrite',\n [DbPrimaryClientStore, DbClientMetadataStore],\n simpleDbTxn => {\n const persistenceTransaction = new IndexedDbTransaction(\n simpleDbTxn,\n ListenSequence.INVALID\n );\n return this.releasePrimaryLeaseIfHeld(persistenceTransaction).next(() =>\n this.removeClientMetadata(persistenceTransaction)\n );\n }\n );\n this.simpleDb.close();\n\n // Remove the entry marking the client as zombied from LocalStorage since\n // we successfully deleted its metadata from IndexedDb.\n this.removeClientZombiedEntry();\n }\n\n /**\n * Returns clients that are not zombied and have an updateTime within the\n * provided threshold.\n */\n private filterActiveClients(\n clients: DbClientMetadata[],\n activityThresholdMs: number\n ): DbClientMetadata[] {\n return clients.filter(\n client =>\n this.isWithinAge(client.updateTimeMs, activityThresholdMs) &&\n !this.isClientZombied(client.clientId)\n );\n }\n\n /**\n * Returns the IDs of the clients that are currently active. If multi-tab\n * is not supported, returns an array that only contains the local client's\n * ID.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n getActiveClients(): Promise {\n return this.runTransaction('getActiveClients', 'readonly', txn => {\n return clientMetadataStore(txn)\n .loadAll()\n .next(clients =>\n this.filterActiveClients(clients, MAX_CLIENT_AGE_MS).map(\n clientMetadata => clientMetadata.clientId\n )\n );\n });\n }\n\n get started(): boolean {\n return this._started;\n }\n\n getGlobalsCache(): GlobalsCache {\n debugAssert(\n this.started,\n 'Cannot initialize GlobalsCache before persistence is started.'\n );\n return this.globalsCache;\n }\n\n getMutationQueue(\n user: User,\n indexManager: IndexManager\n ): IndexedDbMutationQueue {\n debugAssert(\n this.started,\n 'Cannot initialize MutationQueue before persistence is started.'\n );\n return IndexedDbMutationQueue.forUser(\n user,\n this.serializer,\n indexManager,\n this.referenceDelegate\n );\n }\n\n getTargetCache(): IndexedDbTargetCache {\n debugAssert(\n this.started,\n 'Cannot initialize TargetCache before persistence is started.'\n );\n return this.targetCache;\n }\n\n getRemoteDocumentCache(): IndexedDbRemoteDocumentCache {\n debugAssert(\n this.started,\n 'Cannot initialize RemoteDocumentCache before persistence is started.'\n );\n return this.remoteDocumentCache;\n }\n\n getIndexManager(user: User): IndexManager {\n debugAssert(\n this.started,\n 'Cannot initialize IndexManager before persistence is started.'\n );\n return new IndexedDbIndexManager(\n user,\n this.serializer.remoteSerializer.databaseId\n );\n }\n\n getDocumentOverlayCache(user: User): DocumentOverlayCache {\n debugAssert(\n this.started,\n 'Cannot initialize IndexedDbDocumentOverlayCache before persistence is started.'\n );\n return IndexedDbDocumentOverlayCache.forUser(this.serializer, user);\n }\n\n getBundleCache(): BundleCache {\n debugAssert(\n this.started,\n 'Cannot initialize BundleCache before persistence is started.'\n );\n return this.bundleCache;\n }\n\n runTransaction(\n action: string,\n mode: PersistenceTransactionMode,\n transactionOperation: (\n transaction: PersistenceTransaction\n ) => PersistencePromise\n ): Promise {\n logDebug(LOG_TAG, 'Starting transaction:', action);\n\n const simpleDbMode = mode === 'readonly' ? 'readonly' : 'readwrite';\n const objectStores = getObjectStores(this.schemaVersion);\n\n let persistenceTransaction: PersistenceTransaction;\n\n // Do all transactions as readwrite against all object stores, since we\n // are the only reader/writer.\n return this.simpleDb\n .runTransaction(action, simpleDbMode, objectStores, simpleDbTxn => {\n persistenceTransaction = new IndexedDbTransaction(\n simpleDbTxn,\n this.listenSequence\n ? this.listenSequence.next()\n : ListenSequence.INVALID\n );\n\n if (mode === 'readwrite-primary') {\n // While we merely verify that we have (or can acquire) the lease\n // immediately, we wait to extend the primary lease until after\n // executing transactionOperation(). This ensures that even if the\n // transactionOperation takes a long time, we'll use a recent\n // leaseTimestampMs in the extended (or newly acquired) lease.\n return this.verifyPrimaryLease(persistenceTransaction)\n .next(holdsPrimaryLease => {\n if (holdsPrimaryLease) {\n return /* holdsPrimaryLease= */ true;\n }\n return this.canActAsPrimary(persistenceTransaction);\n })\n .next(holdsPrimaryLease => {\n if (!holdsPrimaryLease) {\n logError(\n `Failed to obtain primary lease for action '${action}'.`\n );\n this.isPrimary = false;\n this.queue.enqueueRetryable(() =>\n this.primaryStateListener(false)\n );\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_LOST_ERROR_MSG\n );\n }\n return transactionOperation(persistenceTransaction);\n })\n .next(result => {\n return this.acquireOrExtendPrimaryLease(\n persistenceTransaction\n ).next(() => result);\n });\n } else {\n return this.verifyAllowTabSynchronization(\n persistenceTransaction\n ).next(() => transactionOperation(persistenceTransaction));\n }\n })\n .then(result => {\n persistenceTransaction.raiseOnCommittedEvent();\n return result;\n });\n }\n\n /**\n * Verifies that the current tab is the primary leaseholder or alternatively\n * that the leaseholder has opted into multi-tab synchronization.\n */\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer\n // be turned off.\n private verifyAllowTabSynchronization(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const store = primaryClientStore(txn);\n return store.get(DbPrimaryClientKey).next(currentPrimary => {\n const currentLeaseIsValid =\n currentPrimary !== null &&\n this.isWithinAge(\n currentPrimary.leaseTimestampMs,\n MAX_PRIMARY_ELIGIBLE_AGE_MS\n ) &&\n !this.isClientZombied(currentPrimary.ownerId);\n\n if (currentLeaseIsValid && !this.isLocalClient(currentPrimary)) {\n if (\n !this.forceOwningTab &&\n (!this.allowTabSynchronization ||\n !currentPrimary!.allowTabSynchronization)\n ) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG\n );\n }\n }\n });\n }\n\n /**\n * Obtains or extends the new primary lease for the local client. This\n * method does not verify that the client is eligible for this lease.\n */\n private acquireOrExtendPrimaryLease(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const newPrimary: DbPrimaryClient = {\n ownerId: this.clientId,\n allowTabSynchronization: this.allowTabSynchronization,\n leaseTimestampMs: Date.now()\n };\n return primaryClientStore(txn).put(DbPrimaryClientKey, newPrimary);\n }\n\n static isAvailable(): boolean {\n return SimpleDb.isAvailable();\n }\n\n /** Checks the primary lease and removes it if we are the current primary. */\n private releasePrimaryLeaseIfHeld(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const store = primaryClientStore(txn);\n return store.get(DbPrimaryClientKey).next(primaryClient => {\n if (this.isLocalClient(primaryClient)) {\n logDebug(LOG_TAG, 'Releasing primary lease.');\n return store.delete(DbPrimaryClientKey);\n } else {\n return PersistencePromise.resolve();\n }\n });\n }\n\n /** Verifies that `updateTimeMs` is within `maxAgeMs`. */\n private isWithinAge(updateTimeMs: number, maxAgeMs: number): boolean {\n const now = Date.now();\n const minAcceptable = now - maxAgeMs;\n const maxAcceptable = now;\n if (updateTimeMs < minAcceptable) {\n return false;\n } else if (updateTimeMs > maxAcceptable) {\n logError(\n `Detected an update time that is in the future: ${updateTimeMs} > ${maxAcceptable}`\n );\n return false;\n }\n\n return true;\n }\n\n private attachVisibilityHandler(): void {\n if (\n this.document !== null &&\n typeof this.document.addEventListener === 'function'\n ) {\n this.documentVisibilityHandler = () => {\n this.queue.enqueueAndForget(() => {\n this.inForeground = this.document!.visibilityState === 'visible';\n return this.updateClientMetadataAndTryBecomePrimary();\n });\n };\n\n this.document.addEventListener(\n 'visibilitychange',\n this.documentVisibilityHandler\n );\n\n this.inForeground = this.document.visibilityState === 'visible';\n }\n }\n\n private detachVisibilityHandler(): void {\n if (this.documentVisibilityHandler) {\n debugAssert(\n this.document !== null &&\n typeof this.document.addEventListener === 'function',\n \"Expected 'document.addEventListener' to be a function\"\n );\n this.document.removeEventListener(\n 'visibilitychange',\n this.documentVisibilityHandler\n );\n this.documentVisibilityHandler = null;\n }\n }\n\n /**\n * Attaches a window.unload handler that will synchronously write our\n * clientId to a \"zombie client id\" location in LocalStorage. This can be used\n * by tabs trying to acquire the primary lease to determine that the lease\n * is no longer valid even if the timestamp is recent. This is particularly\n * important for the refresh case (so the tab correctly re-acquires the\n * primary lease). LocalStorage is used for this rather than IndexedDb because\n * it is a synchronous API and so can be used reliably from an unload\n * handler.\n */\n private attachWindowUnloadHook(): void {\n if (typeof this.window?.addEventListener === 'function') {\n this.windowUnloadHandler = () => {\n // Note: In theory, this should be scheduled on the AsyncQueue since it\n // accesses internal state. We execute this code directly during shutdown\n // to make sure it gets a chance to run.\n this.markClientZombied();\n\n const safariIndexdbBugVersionRegex = /(?:Version|Mobile)\\/1[456]/;\n if (\n isSafari() &&\n (navigator.appVersion.match(safariIndexdbBugVersionRegex) ||\n navigator.userAgent.match(safariIndexdbBugVersionRegex))\n ) {\n // On Safari 14, 15, and 16, we do not run any cleanup actions as it might\n // trigger a bug that prevents Safari from re-opening IndexedDB during\n // the next page load.\n // See https://bugs.webkit.org/show_bug.cgi?id=226547\n this.queue.enterRestrictedMode(/* purgeExistingTasks= */ true);\n }\n\n this.queue.enqueueAndForget(() => {\n // Attempt graceful shutdown (including releasing our primary lease),\n // but there's no guarantee it will complete.\n return this.shutdown();\n });\n };\n this.window.addEventListener('pagehide', this.windowUnloadHandler);\n }\n }\n\n private detachWindowUnloadHook(): void {\n if (this.windowUnloadHandler) {\n debugAssert(\n typeof this.window?.removeEventListener === 'function',\n \"Expected 'window.removeEventListener' to be a function\"\n );\n this.window!.removeEventListener('pagehide', this.windowUnloadHandler);\n this.windowUnloadHandler = null;\n }\n }\n\n /**\n * Returns whether a client is \"zombied\" based on its LocalStorage entry.\n * Clients become zombied when their tab closes without running all of the\n * cleanup logic in `shutdown()`.\n */\n private isClientZombied(clientId: ClientId): boolean {\n try {\n const isZombied =\n this.webStorage?.getItem(\n this.zombiedClientLocalStorageKey(clientId)\n ) !== null;\n logDebug(\n LOG_TAG,\n `Client '${clientId}' ${\n isZombied ? 'is' : 'is not'\n } zombied in LocalStorage`\n );\n return isZombied;\n } catch (e) {\n // Gracefully handle if LocalStorage isn't working.\n logError(LOG_TAG, 'Failed to get zombied client id.', e);\n return false;\n }\n }\n\n /**\n * Record client as zombied (a client that had its tab closed). Zombied\n * clients are ignored during primary tab selection.\n */\n private markClientZombied(): void {\n if (!this.webStorage) {\n return;\n }\n try {\n this.webStorage.setItem(\n this.zombiedClientLocalStorageKey(this.clientId),\n String(Date.now())\n );\n } catch (e) {\n // Gracefully handle if LocalStorage isn't available / working.\n logError('Failed to set zombie client id.', e);\n }\n }\n\n /** Removes the zombied client entry if it exists. */\n private removeClientZombiedEntry(): void {\n if (!this.webStorage) {\n return;\n }\n try {\n this.webStorage.removeItem(\n this.zombiedClientLocalStorageKey(this.clientId)\n );\n } catch (e) {\n // Ignore\n }\n }\n\n private zombiedClientLocalStorageKey(clientId: ClientId): string {\n return `${ZOMBIED_CLIENTS_KEY_PREFIX}_${this.persistenceKey}_${clientId}`;\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the primary client object store.\n */\nfunction primaryClientStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbPrimaryClientStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the client metadata object store.\n */\nfunction clientMetadataStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbClientMetadataStore\n );\n}\n\n/**\n * Generates a string used as a prefix when storing data in IndexedDB and\n * LocalStorage.\n */\nexport function indexedDbStoragePrefix(\n databaseId: DatabaseId,\n persistenceKey: string\n): string {\n // Use two different prefix formats:\n //\n // * firestore / persistenceKey / projectID . databaseID / ...\n // * firestore / persistenceKey / projectID / ...\n //\n // projectIDs are DNS-compatible names and cannot contain dots\n // so there's no danger of collisions.\n let database = databaseId.projectId;\n if (!databaseId.isDefaultDatabase) {\n database += '.' + databaseId.database;\n }\n\n return 'firestore/' + persistenceKey + '/' + database + '/';\n}\n\nexport async function indexedDbClearPersistence(\n persistenceKey: string\n): Promise {\n if (!SimpleDb.isAvailable()) {\n return Promise.resolve();\n }\n const dbName = persistenceKey + MAIN_DATABASE;\n await SimpleDb.delete(dbName);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BatchId, ListenSequenceNumber, TargetId } from '../core/types';\nimport { IndexKind } from '../model/field_index';\nimport { BundledQuery } from '../protos/firestore_bundle_proto';\nimport {\n Document as ProtoDocument,\n DocumentsTarget as ProtoDocumentsTarget,\n QueryTarget as ProtoQueryTarget,\n Write as ProtoWrite\n} from '../protos/firestore_proto_api';\n\nimport { EncodedResourcePath } from './encoded_resource_path';\nimport { DbTimestampKey, KeySafeBytes } from './indexeddb_sentinels';\n\n/**\n * Schema Version for the Web client:\n * 1. Initial version including Mutation Queue, Query Cache, and Remote\n * Document Cache\n * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No\n * longer required because migration 3 unconditionally clears it.\n * 3. Dropped and re-created Query Cache to deal with cache corruption related\n * to limbo resolution. Addresses\n * https://github.com/firebase/firebase-ios-sdk/issues/1548\n * 4. Multi-Tab Support.\n * 5. Removal of held write acks.\n * 6. Create document global for tracking document cache size.\n * 7. Ensure every cached document has a sentinel row with a sequence number.\n * 8. Add collection-parent index for Collection Group queries.\n * 9. Change RemoteDocumentChanges store to be keyed by readTime rather than\n * an auto-incrementing ID. This is required for Index-Free queries.\n * 10. Rewrite the canonical IDs to the explicit Protobuf-based format.\n * 11. Add bundles and named_queries for bundle support.\n * 12. Add document overlays.\n * 13. Rewrite the keys of the remote document cache to allow for efficient\n * document lookup via `getAll()`.\n * 14. Add overlays.\n * 15. Add indexing support.\n * 16. Parse timestamp strings before creating index entries.\n * 17. TODO(tomandersen)\n * 18. Encode key safe representations of IndexEntry in DbIndexEntryStore.\n */\n\nexport const SCHEMA_VERSION = 18;\n\n/**\n * Wrapper class to store timestamps (seconds and nanos) in IndexedDb objects.\n */\nexport interface DbTimestamp {\n seconds: number;\n nanoseconds: number;\n}\n\n/**\n * A singleton object to be stored in the 'owner' store in IndexedDb.\n *\n * A given database can have a single primary tab assigned at a given time. That\n * tab must validate that it is still holding the primary lease before every\n * operation that requires locked access. The primary tab should regularly\n * write an updated timestamp to this lease to prevent other tabs from\n * \"stealing\" the primary lease\n */\nexport interface DbPrimaryClient {\n ownerId: string;\n /** Whether to allow shared access from multiple tabs. */\n allowTabSynchronization: boolean;\n leaseTimestampMs: number;\n}\n\n/**\n * An object to be stored in the 'mutationQueues' store in IndexedDb.\n *\n * Each user gets a single queue of MutationBatches to apply to the server.\n * DbMutationQueue tracks the metadata about the queue.\n */\nexport interface DbMutationQueue {\n /**\n * The normalized user ID to which this queue belongs.\n */\n userId: string;\n /**\n * An identifier for the highest numbered batch that has been acknowledged\n * by the server. All MutationBatches in this queue with batchIds less\n * than or equal to this value are considered to have been acknowledged by\n * the server.\n *\n * NOTE: this is deprecated and no longer used by the code.\n */\n lastAcknowledgedBatchId: number;\n /**\n * A stream token that was previously sent by the server.\n *\n * See StreamingWriteRequest in datastore.proto for more details about\n * usage.\n *\n * After sending this token, earlier tokens may not be used anymore so\n * only a single stream token is retained.\n *\n * NOTE: this is deprecated and no longer used by the code.\n */\n lastStreamToken: string;\n}\n\n/**\n * An object to be stored in the 'mutations' store in IndexedDb.\n *\n * Represents a batch of user-level mutations intended to be sent to the server\n * in a single write. Each user-level batch gets a separate DbMutationBatch\n * with a new batchId.\n */\nexport interface DbMutationBatch {\n /**\n * The normalized user ID to which this batch belongs.\n */\n userId: string;\n /**\n * An identifier for this batch, allocated using an auto-generated key.\n */\n batchId: BatchId;\n /**\n * The local write time of the batch, stored as milliseconds since the\n * epoch.\n */\n localWriteTimeMs: number;\n /**\n * A list of \"mutations\" that represent a partial base state from when this\n * write batch was initially created. During local application of the write\n * batch, these baseMutations are applied prior to the real writes in order\n * to override certain document fields from the remote document cache. This\n * is necessary in the case of non-idempotent writes (e.g. `increment()`\n * transforms) to make sure that the local view of the modified documents\n * doesn't flicker if the remote document cache receives the result of the\n * non-idempotent write before the write is removed from the queue.\n *\n * These mutations are never sent to the backend.\n */\n baseMutations?: ProtoWrite[];\n /**\n * A list of mutations to apply. All mutations will be applied atomically.\n *\n * Mutations are serialized via toMutation().\n */\n mutations: ProtoWrite[];\n}\n\n/**\n * An object to be stored in the 'documentMutations' store in IndexedDb.\n *\n * A manually maintained index of all the mutation batches that affect a given\n * document key. The rows in this table are references based on the contents of\n * DbMutationBatch.mutations.\n */\nexport interface DbDocumentMutation {}\n\n/**\n * Represents the known absence of a document at a particular version.\n * Stored in IndexedDb as part of a DbRemoteDocument object.\n */\nexport interface DbNoDocument {\n path: string[];\n readTime: DbTimestamp;\n}\n\n/**\n * Represents a document that is known to exist but whose data is unknown.\n * Stored in IndexedDb as part of a DbRemoteDocument object.\n */\nexport interface DbUnknownDocument {\n path: string[];\n version: DbTimestamp;\n}\n\n/**\n * An object to be stored in the 'remoteDocuments' store in IndexedDb.\n * It represents either:\n *\n * - A complete document.\n * - A \"no document\" representing a document that is known not to exist (at\n * some version).\n * - An \"unknown document\" representing a document that is known to exist (at\n * some version) but whose contents are unknown.\n *\n * The document key is split up across `prefixPath`, `collectionGroup` and\n * `documentId`.\n *\n * Note: This is the persisted equivalent of a MaybeDocument and could perhaps\n * be made more general if necessary.\n */\nexport interface DbRemoteDocument {\n /** The path to the document's collection (excluding). */\n prefixPath: string[];\n\n /** The collection ID the document is directly nested under. */\n collectionGroup: string;\n\n /** The document ID. */\n documentId: string;\n\n /** When the document was read from the backend. */\n readTime: DbTimestampKey;\n\n /**\n * Set to an instance of DbUnknownDocument if the data for a document is\n * not known, but it is known that a document exists at the specified\n * version (e.g. it had a successful update applied to it)\n */\n unknownDocument?: DbUnknownDocument;\n /**\n * Set to an instance of a DbNoDocument if it is known that no document\n * exists.\n */\n noDocument?: DbNoDocument;\n /**\n * Set to an instance of a Document if there's a cached version of the\n * document.\n */\n document?: ProtoDocument;\n /**\n * Documents that were written to the remote document store based on\n * a write acknowledgment are marked with `hasCommittedMutations`. These\n * documents are potentially inconsistent with the backend's copy and use\n * the write's commit version as their document version.\n */\n hasCommittedMutations: boolean;\n}\n\n/**\n * Contains a single entry that has metadata about the remote document cache.\n */\nexport interface DbRemoteDocumentGlobal {\n /**\n * Approximately the total size in bytes of all the\n * documents in the document cache.\n */\n byteSize: number;\n}\n\n/**\n * The persisted type for a query nested with in the 'targets' store in\n * IndexedDb. We use the proto definitions for these two kinds of queries in\n * order to avoid writing extra serialization logic.\n */\nexport type DbQuery = ProtoQueryTarget | ProtoDocumentsTarget;\n\n/**\n * An object to be stored in the 'targets' store in IndexedDb.\n *\n * This is based on and should be kept in sync with the proto used in the iOS\n * client.\n *\n * Each query the client listens to against the server is tracked on disk so\n * that the query can be efficiently resumed on restart.\n */\nexport interface DbTarget {\n /**\n * An auto-generated sequential numeric identifier for the query.\n *\n * Queries are stored using their canonicalId as the key, but these\n * canonicalIds can be quite long so we additionally assign a unique\n * queryId which can be used by referenced data structures (e.g.\n * indexes) to minimize the on-disk cost.\n */\n targetId: TargetId;\n /**\n * The canonical string representing this query. This is not unique.\n */\n canonicalId: string;\n /**\n * The last readTime received from the Watch Service for this query.\n *\n * This is the same value as TargetChange.read_time in the protos.\n */\n readTime: DbTimestamp;\n /**\n * An opaque, server-assigned token that allows watching a query to be\n * resumed after disconnecting without retransmitting all the data\n * that matches the query. The resume token essentially identifies a\n * point in time from which the server should resume sending results.\n *\n * This is related to the snapshotVersion in that the resumeToken\n * effectively also encodes that value, but the resumeToken is opaque\n * and sometimes encodes additional information.\n *\n * A consequence of this is that the resumeToken should be used when\n * asking the server to reason about where this client is in the watch\n * stream, but the client should use the snapshotVersion for its own\n * purposes.\n *\n * This is the same value as TargetChange.resume_token in the protos.\n */\n resumeToken: string;\n /**\n * A sequence number representing the last time this query was\n * listened to, used for garbage collection purposes.\n *\n * Conventionally this would be a timestamp value, but device-local\n * clocks are unreliable and they must be able to create new listens\n * even while disconnected. Instead this should be a monotonically\n * increasing number that's incremented on each listen call.\n *\n * This is different from the queryId since the queryId is an\n * immutable identifier assigned to the Query on first use while\n * lastListenSequenceNumber is updated every time the query is\n * listened to.\n */\n lastListenSequenceNumber: number;\n /**\n * Denotes the maximum snapshot version at which the associated query view\n * contained no limbo documents. Undefined for data written prior to\n * schema version 9.\n */\n lastLimboFreeSnapshotVersion?: DbTimestamp;\n /**\n * The query for this target.\n *\n * Because canonical ids are not unique we must store the actual query. We\n * use the proto to have an object we can persist without having to\n * duplicate translation logic to and from a `Query` object.\n */\n query: DbQuery;\n}\n\n/**\n * An object representing an association between a target and a document, or a\n * sentinel row marking the last sequence number at which a document was used.\n * Each document cached must have a corresponding sentinel row before lru\n * garbage collection is enabled.\n *\n * The target associations and sentinel rows are co-located so that orphaned\n * documents and their sequence numbers can be identified efficiently via a scan\n * of this store.\n */\nexport interface DbTargetDocument {\n /**\n * The targetId identifying a target or 0 for a sentinel row.\n */\n targetId: TargetId;\n /**\n * The path to the document, as encoded in the key.\n */\n path: EncodedResourcePath;\n /**\n * If this is a sentinel row, this should be the sequence number of the last\n * time the document specified by `path` was used. Otherwise, it should be\n * `undefined`.\n */\n sequenceNumber?: ListenSequenceNumber;\n}\n\n/**\n * A record of global state tracked across all Targets, tracked separately\n * to avoid the need for extra indexes.\n *\n * This should be kept in-sync with the proto used in the iOS client.\n */\nexport interface DbTargetGlobal {\n /**\n * The highest numbered target id across all targets.\n *\n * See DbTarget.targetId.\n */\n highestTargetId: TargetId;\n /**\n * The highest numbered lastListenSequenceNumber across all targets.\n *\n * See DbTarget.lastListenSequenceNumber.\n */\n highestListenSequenceNumber: number;\n /**\n * A global snapshot version representing the last consistent snapshot we\n * received from the backend. This is monotonically increasing and any\n * snapshots received from the backend prior to this version (e.g. for\n * targets resumed with a resumeToken) should be suppressed (buffered)\n * until the backend has caught up to this snapshot version again. This\n * prevents our cache from ever going backwards in time.\n */\n lastRemoteSnapshotVersion: DbTimestamp;\n /**\n * The number of targets persisted.\n */\n targetCount: number;\n}\n\n/**\n * An object representing an association between a Collection id (e.g. 'messages')\n * to a parent path (e.g. '/chats/123') that contains it as a (sub)collection.\n * This is used to efficiently find all collections to query when performing\n * a Collection Group query.\n */\nexport interface DbCollectionParent {\n /**\n * The collectionId (e.g. 'messages')\n */\n collectionId: string;\n /**\n * The path to the parent (either a document location or an empty path for\n * a root-level collection).\n */\n parent: EncodedResourcePath;\n}\n\n/**\n * A record of the metadata state of each client.\n *\n * PORTING NOTE: This is used to synchronize multi-tab state and does not need\n * to be ported to iOS or Android.\n */\nexport interface DbClientMetadata {\n // Note: Previous schema versions included a field\n // \"lastProcessedDocumentChangeId\". Don't use anymore.\n\n /** The auto-generated client id assigned at client startup. */\n clientId: string;\n /** The last time this state was updated. */\n updateTimeMs: number;\n /** Whether the client's network connection is enabled. */\n networkEnabled: boolean;\n /** Whether this client is running in a foreground tab. */\n inForeground: boolean;\n}\n\n/** An object representing a bundle loaded by the SDK. */\nexport interface DbBundle {\n /** The ID of the loaded bundle. */\n bundleId: string;\n /** The create time of the loaded bundle. */\n createTime: DbTimestamp;\n /** The schema version of the loaded bundle. */\n version: number;\n}\n\n/** An object representing a named query loaded by the SDK via a bundle. */\nexport interface DbNamedQuery {\n /** The name of the query. */\n name: string;\n /** The read time of the results saved in the bundle from the named query. */\n readTime: DbTimestamp;\n /** The query saved in the bundle. */\n bundledQuery: BundledQuery;\n}\n\n/** An object representing the global configuration for a field index. */\nexport interface DbIndexConfiguration {\n /**\n * The index id for this entry. Undefined for indexes that are not yet\n * persisted.\n */\n indexId?: number;\n /** The collection group this index belongs to. */\n collectionGroup: string;\n /** The fields to index for this index. */\n fields: Array<[name: string, kind: IndexKind]>;\n}\n\n/**\n * An object describing how up-to-date the index backfill is for each user and\n * index.\n */\nexport interface DbIndexState {\n /** The index id for this entry. */\n indexId: number;\n /** The user id for this entry. */\n uid: string;\n /**\n * A number that indicates when the index was last updated (relative to\n * other indexes).\n */\n sequenceNumber: number;\n /**\n * The latest read time that has been indexed by Firestore for this field\n * index. Set to `{seconds: 0, nanos: 0}` if no documents have been indexed.\n */\n readTime: DbTimestamp;\n /**\n * The last document that has been indexed for this field index. Empty if\n * no documents have been indexed.\n */\n documentKey: EncodedResourcePath;\n /**\n * The largest mutation batch id that has been processed for this index. -1\n * if no mutations have been indexed.\n */\n largestBatchId: number;\n}\n\n/** An object that stores the encoded entries for all documents and fields. */\nexport interface DbIndexEntry {\n // TODO(indexing): Consider just storing `orderedDocumentKey` and decoding\n // the ordered key into a document key. This would reduce storage space on\n // disk but require us to port parts of OrderedCodeReader.\n\n /** The index id for this entry. */\n indexId: number;\n /** The user id for this entry. */\n uid: string;\n /** The encoded array index value for this entry. */\n arrayValue: KeySafeBytes;\n /** The encoded directional value for equality and inequality filters. */\n directionalValue: KeySafeBytes;\n /**\n * The document key this entry points to. This entry is encoded by an ordered\n * encoder to match the key order of the index.\n */\n orderedDocumentKey: KeySafeBytes;\n /** The segments of the document key this entry points to. */\n documentKey: string[];\n}\n\n/**\n * An object representing a document overlay.\n */\nexport interface DbDocumentOverlay {\n /** The user ID to whom this overlay belongs. */\n userId: string;\n /** The path to the collection that contains the document. */\n collectionPath: string;\n /** The ID (key) of the document within the collection. */\n documentId: string;\n /** The collection group to which the document belongs. */\n collectionGroup: string;\n /** The largest batch ID that's been applied for this overlay. */\n largestBatchId: number;\n /** The overlay mutation. */\n overlayMutation: ProtoWrite;\n}\n\n/**\n * An object containing global name/value pair.\n */\nexport interface DbGlobals {\n /** Name is a globally unique identifier for a value. */\n name: string;\n /** Value is a general purpose storage for global data. */\n value: Uint8Array;\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(\n batch !== null,\n 0x90f9,\n 'Attempt to reject nonexistent batch!'\n );\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 0xbd9d,\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 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { BatchId, MutationBatchState, TargetId } from '../core/types';\nimport { debugAssert } from '../util/assert';\n\nimport { ClientId } from './shared_client_state';\nimport { QueryTargetState } from './shared_client_state_syncer';\n\n// The format of the LocalStorage key that stores the client state is:\n// firestore_clients__\nexport const CLIENT_STATE_KEY_PREFIX = 'firestore_clients';\n\n/** Assembles the key for a client state in WebStorage */\nexport function createWebStorageClientStateKey(\n persistenceKey: string,\n clientId: ClientId\n): string {\n debugAssert(\n clientId.indexOf('_') === -1,\n `Client key cannot contain '_', but was '${clientId}'`\n );\n\n return `${CLIENT_STATE_KEY_PREFIX}_${persistenceKey}_${clientId}`;\n}\n\n/**\n * The JSON representation of a clients's metadata as used during WebStorage\n * serialization. The ClientId is omitted here as it is encoded as part of the\n * key.\n */\nexport interface ClientStateSchema {\n activeTargetIds: number[];\n updateTimeMs: number;\n}\n\n// The format of the WebStorage key that stores the mutation state is:\n// firestore_mutations__\n// (for unauthenticated users)\n// or: firestore_mutations___\n//\n// 'user_uid' is last to avoid needing to escape '_' characters that it might\n// contain.\nexport const MUTATION_BATCH_KEY_PREFIX = 'firestore_mutations';\n\n/** Assembles the key for a mutation batch in WebStorage */\nexport function createWebStorageMutationBatchKey(\n persistenceKey: string,\n user: User,\n batchId: BatchId\n): string {\n let mutationKey = `${MUTATION_BATCH_KEY_PREFIX}_${persistenceKey}_${batchId}`;\n\n if (user.isAuthenticated()) {\n mutationKey += `_${user.uid}`;\n }\n\n return mutationKey;\n}\n\n/**\n * The JSON representation of a mutation batch's metadata as used during\n * WebStorage serialization. The UserId and BatchId is omitted as it is\n * encoded as part of the key.\n */\nexport interface MutationMetadataSchema {\n state: MutationBatchState;\n error?: { code: string; message: string }; // Only set when state === 'rejected'\n updateTimeMs: number;\n}\n\n// The format of the WebStorage key that stores a query target's metadata is:\n// firestore_targets__\nexport const QUERY_TARGET_KEY_PREFIX = 'firestore_targets';\n\n/** Assembles the key for a query state in WebStorage */\nexport function createWebStorageQueryTargetMetadataKey(\n persistenceKey: string,\n targetId: TargetId\n): string {\n return `${QUERY_TARGET_KEY_PREFIX}_${persistenceKey}_${targetId}`;\n}\n\n/**\n * The JSON representation of a query target's state as used during WebStorage\n * serialization. The TargetId is omitted as it is encoded as part of the key.\n */\nexport interface QueryTargetStateSchema {\n state: QueryTargetState;\n error?: { code: string; message: string }; // Only set when state === 'rejected'\n updateTimeMs: number;\n}\n\n// The WebStorage prefix that stores the primary tab's online state. The\n// format of the key is:\n// firestore_online_state_\nexport const ONLINE_STATE_KEY_PREFIX = 'firestore_online_state';\n\n/** Assembles the key for the online state of the primary tab. */\nexport function createWebStorageOnlineStateKey(persistenceKey: string): string {\n return `${ONLINE_STATE_KEY_PREFIX}_${persistenceKey}`;\n}\n\n// The WebStorage prefix that plays as a event to indicate the remote documents\n// might have changed due to some secondary tabs loading a bundle.\n// format of the key is:\n// firestore_bundle_loaded_v2_\n// The version ending with \"v2\" stores the list of modified collection groups.\nexport const BUNDLE_LOADED_KEY_PREFIX = 'firestore_bundle_loaded_v2';\nexport function createBundleLoadedKey(persistenceKey: string): string {\n return `${BUNDLE_LOADED_KEY_PREFIX}_${persistenceKey}`;\n}\n\n/**\n * The JSON representation of the system's online state, as written by the\n * primary client.\n */\nexport interface SharedOnlineStateSchema {\n /**\n * The clientId of the client that wrote this onlineState value. Tracked so\n * that on startup, clients can check if this client is still active when\n * determining whether to apply this value or not.\n */\n readonly clientId: string;\n readonly onlineState: string;\n}\n\n// The WebStorage key prefix for the key that stores the last sequence number allocated. The key\n// looks like 'firestore_sequence_number_'.\nexport const SEQUENCE_NUMBER_KEY_PREFIX = 'firestore_sequence_number';\n\n/** Assembles the key for the current sequence number. */\nexport function createWebStorageSequenceNumberKey(\n persistenceKey: string\n): string {\n return `${SEQUENCE_NUMBER_KEY_PREFIX}_${persistenceKey}`;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { ListenSequence } from '../core/listen_sequence';\nimport {\n BatchId,\n ListenSequenceNumber,\n MutationBatchState,\n OnlineState,\n TargetId\n} from '../core/types';\nimport { TargetIdSet, targetIdSet } from '../model/collections';\nimport { hardAssert, debugAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logError, logDebug } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport { isSafeInteger, WindowLike } from '../util/types';\n\nimport {\n CLIENT_STATE_KEY_PREFIX,\n ClientStateSchema,\n createBundleLoadedKey,\n createWebStorageClientStateKey,\n createWebStorageMutationBatchKey,\n createWebStorageOnlineStateKey,\n createWebStorageQueryTargetMetadataKey,\n createWebStorageSequenceNumberKey,\n MUTATION_BATCH_KEY_PREFIX,\n MutationMetadataSchema,\n QUERY_TARGET_KEY_PREFIX,\n QueryTargetStateSchema,\n SharedOnlineStateSchema\n} from './shared_client_state_schema';\nimport {\n QueryTargetState,\n SharedClientStateSyncer\n} from './shared_client_state_syncer';\n\nconst LOG_TAG = 'SharedClientState';\n\n/**\n * A randomly-generated key assigned to each Firestore instance at startup.\n */\nexport type ClientId = string;\n\n/**\n * A `SharedClientState` keeps track of the global state of the mutations\n * and query targets for all active clients with the same persistence key (i.e.\n * project ID and FirebaseApp name). It relays local changes to other clients\n * and updates its local state as new state is observed.\n *\n * `SharedClientState` is primarily used for synchronization in Multi-Tab\n * environments. Each tab is responsible for registering its active query\n * targets and mutations. `SharedClientState` will then notify the listener\n * assigned to `.syncEngine` for updates to mutations and queries that\n * originated in other clients.\n *\n * To receive notifications, `.syncEngine` and `.onlineStateHandler` has to be\n * assigned before calling `start()`.\n */\nexport interface SharedClientState {\n onlineStateHandler: ((onlineState: OnlineState) => void) | null;\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null;\n\n /** Registers the Mutation Batch ID of a newly pending mutation. */\n addPendingMutation(batchId: BatchId): void;\n\n /**\n * Records that a pending mutation has been acknowledged or rejected.\n * Called by the primary client to notify secondary clients of mutation\n * results as they come back from the backend.\n */\n updateMutationState(\n batchId: BatchId,\n state: 'acknowledged' | 'rejected',\n error?: FirestoreError\n ): void;\n\n /**\n * Associates a new Query Target ID with the local Firestore client. Returns\n * the new query state for the query (which can be 'current' if the query is\n * already associated with another tab).\n *\n * If the target id is already associated with local client, the method simply\n * returns its `QueryTargetState`.\n */\n addLocalQueryTarget(\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 0x77ac,\n 'Found non-numeric sequence number',\n { seqString }\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 { isCloudWorkstation } from '@firebase/util';\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 const { host } = new URL(url);\n const forwardCredentials = isCloudWorkstation(host);\n return this.performRPCRequest(\n rpcName,\n url,\n headers,\n req,\n forwardCredentials\n ).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 _forwardCredentials: boolean\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 /** A collection of open WebChannel instances */\n private openWebChannels: WebChannel[] = [];\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 _forwardCredentials: boolean\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 0x235f,\n 'RPC failed with unanticipated webchannel error. Giving up.',\n {\n rpcName,\n streamId,\n lastErrorCode: xhr.getLastErrorCode(),\n lastError: xhr.getLastError()\n }\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 this.addOpenWebChannel(channel);\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 this.removeOpenWebChannel(channel);\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. Name:`,\n err.name,\n 'Message:',\n err.message\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(\n !!msgData,\n 0x3fdd,\n 'Got a webchannel message without data.'\n );\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 as WebChannelError)?.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 * Closes and cleans up any resources associated with the connection.\n */\n terminate(): void {\n // If the Firestore instance is terminated, we will explicitly\n // close any remaining open WebChannel instances.\n this.openWebChannels.forEach(webChannel => webChannel.close());\n this.openWebChannels = [];\n }\n\n /**\n * Add a WebChannel instance to the collection of open instances.\n * @param webChannel\n */\n addOpenWebChannel(webChannel: WebChannel): void {\n this.openWebChannels.push(webChannel);\n }\n\n /**\n * Remove a WebChannel instance from the collection of open instances.\n * @param webChannel\n */\n removeOpenWebChannel(webChannel: WebChannel): void {\n this.openWebChannels = this.openWebChannels.filter(\n instance => instance === webChannel\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/** 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 0x7a5a,\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 0xda08,\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 0x3186,\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, 0xd7c2, 'Missing entity in write response for `key`', {\n key\n });\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 0xfcd7,\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 0xf76d,\n 'unsupported combination of changes: `change` after `oldChange`',\n {\n change,\n oldChange\n }\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n BundleElement,\n BundleMetadata\n} from '../protos/firestore_bundle_proto';\nimport { JsonProtoSerializer } from '../remote/serializer';\n\n/**\n * A complete element in the bundle stream, together with the byte length it\n * occupies in the stream.\n */\nexport class SizedBundleElement {\n constructor(\n public readonly payload: BundleElement,\n // How many bytes this element takes to store in the bundle.\n public readonly byteLength: number\n ) {}\n\n isBundleMetadata(): boolean {\n return 'metadata' in this.payload;\n }\n}\n\nexport type BundleSource =\n | ReadableStream\n | ArrayBuffer\n | Uint8Array;\n\n/**\n * A class representing a bundle.\n *\n * Takes a bundle stream or buffer, and presents abstractions to read bundled\n * elements out of the underlying content.\n */\nexport interface BundleReader {\n serializer: JsonProtoSerializer;\n\n close(): Promise;\n\n /**\n * Returns the metadata of the bundle.\n */\n getMetadata(): Promise;\n\n /**\n * Returns the next BundleElement (together with its byte size in the bundle)\n * that has not been read from underlying ReadableStream. Returns null if we\n * have reached the end of the stream.\n */\n nextElement(): Promise;\n}\n\n/**\n * A class representing a synchronized bundle reader.\n *\n * Takes a bundle string buffer, parses the data, and provides accessors to the data contained\n * within it.\n */\nexport interface BundleReaderSync {\n serializer: JsonProtoSerializer;\n\n /**\n * Returns the metadata of the bundle.\n */\n getMetadata(): BundleMetadata;\n\n /**\n * Returns BundleElements parsed from the bundle. Returns an empty array if no bundle elements\n * exist.\n */\n getElements(): SizedBundleElement[];\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LoadBundleTaskProgress } from '@firebase/firestore-types';\n\nimport { LocalStore } from '../local/local_store';\nimport {\n localStoreApplyBundledDocuments,\n localStoreSaveNamedQuery\n} from '../local/local_store_impl';\nimport { documentKeySet, DocumentKeySet } from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport {\n BundleMetadata as ProtoBundleMetadata,\n NamedQuery as ProtoNamedQuery\n} from '../protos/firestore_bundle_proto';\nimport { Timestamp as ApiTimestamp } from '../protos/firestore_proto_api';\nimport {\n fromDocument,\n fromName,\n fromVersion,\n JsonProtoSerializer\n} from '../remote/serializer';\nimport { debugAssert } from '../util/assert';\nimport { SizedBundleElement } from '../util/bundle_reader';\n\nimport {\n BundleConverter,\n BundledDocument,\n BundledDocuments,\n BundleLoadResult\n} from './bundle';\nimport { SnapshotVersion } from './snapshot_version';\n\n/**\n * Helper to convert objects from bundles to model objects in the SDK.\n */\nexport class BundleConverterImpl implements BundleConverter {\n constructor(private readonly serializer: JsonProtoSerializer) {}\n\n toDocumentKey(name: string): DocumentKey {\n return fromName(this.serializer, name);\n }\n\n /**\n * Converts a BundleDocument to a MutableDocument.\n */\n toMutableDocument(bundledDoc: BundledDocument): MutableDocument {\n if (bundledDoc.metadata.exists) {\n debugAssert(\n !!bundledDoc.document,\n 'Document is undefined when metadata.exist is true.'\n );\n return fromDocument(this.serializer, bundledDoc.document!, false);\n } else {\n return MutableDocument.newNoDocument(\n this.toDocumentKey(bundledDoc.metadata.name!),\n this.toSnapshotVersion(bundledDoc.metadata.readTime!)\n );\n }\n }\n\n toSnapshotVersion(time: ApiTimestamp): SnapshotVersion {\n return fromVersion(time);\n }\n}\n\n/**\n * A class to process the elements from a bundle, and optionally load them into local\n * storage and provide progress update while loading.\n */\nexport class BundleLoader {\n /** The current progress of loading */\n private progress: LoadBundleTaskProgress;\n /** Batched queries to be saved into storage */\n private _queries: ProtoNamedQuery[] = [];\n /** Batched documents to be saved into storage */\n private _documents: BundledDocuments = [];\n /** The collection groups affected by this bundle. */\n private collectionGroups = new Set();\n\n constructor(\n private bundleMetadata: ProtoBundleMetadata,\n private serializer: JsonProtoSerializer\n ) {\n this.progress = bundleInitialProgress(bundleMetadata);\n }\n\n /**\n * Returns the named queries that have been parsed from the SizeBundleElements added by\n * calling {@link adSizedElement}.\n */\n get queries(): ProtoNamedQuery[] {\n return this._queries;\n }\n\n /**\n * Returns the BundledDocuments that have been parsed from the SizeBundleElements added by\n * calling {@link addSizedElement}.\n */\n get documents(): BundledDocuments {\n return this._documents;\n }\n\n /**\n * Adds an element from the bundle to the loader.\n *\n * Returns a new progress if adding the element leads to a new progress,\n * otherwise returns null.\n */\n addSizedElement(element: SizedBundleElement): LoadBundleTaskProgress | null {\n debugAssert(!element.isBundleMetadata(), 'Unexpected bundle metadata.');\n\n this.progress.bytesLoaded += element.byteLength;\n\n let documentsLoaded = this.progress.documentsLoaded;\n\n if (element.payload.namedQuery) {\n this._queries.push(element.payload.namedQuery);\n } else if (element.payload.documentMetadata) {\n this._documents.push({ metadata: element.payload.documentMetadata });\n if (!element.payload.documentMetadata.exists) {\n ++documentsLoaded;\n }\n const path = ResourcePath.fromString(\n element.payload.documentMetadata.name!\n );\n debugAssert(\n path.length >= 2,\n 'The document name does not point to a document.'\n );\n this.collectionGroups.add(path.get(path.length - 2));\n } else if (element.payload.document) {\n debugAssert(\n this._documents.length > 0 &&\n this._documents[this._documents.length - 1].metadata.name ===\n element.payload.document.name,\n 'The document being added does not match the stored metadata.'\n );\n this._documents[this._documents.length - 1].document =\n element.payload.document;\n ++documentsLoaded;\n }\n\n if (documentsLoaded !== this.progress.documentsLoaded) {\n this.progress.documentsLoaded = documentsLoaded;\n return { ...this.progress };\n }\n\n return null;\n }\n\n private getQueryDocumentMapping(\n documents: BundledDocuments\n ): Map {\n const queryDocumentMap = new Map();\n const bundleConverter = new BundleConverterImpl(this.serializer);\n for (const bundleDoc of documents) {\n if (bundleDoc.metadata.queries) {\n const documentKey = bundleConverter.toDocumentKey(\n bundleDoc.metadata.name!\n );\n for (const queryName of bundleDoc.metadata.queries) {\n const documentKeys = (\n queryDocumentMap.get(queryName) || documentKeySet()\n ).add(documentKey);\n queryDocumentMap.set(queryName, documentKeys);\n }\n }\n }\n\n return queryDocumentMap;\n }\n\n /**\n * Update the progress to 'Success' and return the updated progress.\n */\n async completeAndStoreAsync(\n localStore: LocalStore\n ): Promise {\n debugAssert(\n this._documents[this._documents.length - 1]?.metadata.exists !== true ||\n !!this._documents[this._documents.length - 1].document,\n 'Bundled documents end with a document metadata element instead of a document.'\n );\n debugAssert(!!this.bundleMetadata.id, 'Bundle ID must be set.');\n\n const changedDocs = await localStoreApplyBundledDocuments(\n localStore,\n new BundleConverterImpl(this.serializer),\n this._documents,\n this.bundleMetadata.id!\n );\n\n const queryDocumentMap = this.getQueryDocumentMapping(this.documents);\n\n for (const q of this._queries) {\n await localStoreSaveNamedQuery(\n localStore,\n q,\n queryDocumentMap.get(q.name!)\n );\n }\n\n this.progress.taskState = 'Success';\n return {\n progress: this.progress,\n changedCollectionGroups: this.collectionGroups,\n changedDocs\n };\n }\n}\n\n/**\n * Returns a `LoadBundleTaskProgress` representing the initial progress of\n * loading a bundle.\n */\nexport function bundleInitialProgress(\n metadata: ProtoBundleMetadata\n): LoadBundleTaskProgress {\n return {\n taskState: 'Running',\n documentsLoaded: 0,\n bytesLoaded: 0,\n totalDocuments: metadata.totalDocuments!,\n totalBytes: metadata.totalBytes!\n };\n}\n\n/**\n * Returns a `LoadBundleTaskProgress` representing the progress that the loading\n * has succeeded.\n */\nexport function bundleSuccessProgress(\n metadata: ProtoBundleMetadata\n): LoadBundleTaskProgress {\n return {\n taskState: 'Success',\n documentsLoaded: metadata.totalDocuments!,\n bytesLoaded: metadata.totalBytes!,\n totalDocuments: metadata.totalDocuments!,\n totalBytes: metadata.totalBytes!\n };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { QueryResult } from '../local/local_store_impl';\nimport {\n documentKeySet,\n DocumentKeySet,\n DocumentMap\n} from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { DocumentSet } from '../model/document_set';\nimport { TargetChange } from '../remote/remote_event';\nimport { debugAssert, fail } from '../util/assert';\n\nimport { LimitType, newQueryComparator, Query, queryMatches } from './query';\nimport { OnlineState } from './types';\nimport {\n ChangeType,\n DocumentChangeSet,\n SyncState,\n ViewSnapshot\n} from './view_snapshot';\n\nexport type LimboDocumentChange = AddedLimboDocument | RemovedLimboDocument;\nexport class AddedLimboDocument {\n constructor(public key: DocumentKey) {}\n}\nexport class RemovedLimboDocument {\n constructor(public key: DocumentKey) {}\n}\n\n/** The result of applying a set of doc changes to a view. */\nexport interface ViewDocumentChanges {\n /** The new set of docs that should be in the view. */\n documentSet: DocumentSet;\n /** The diff of these docs with the previous set of docs. */\n changeSet: DocumentChangeSet;\n /**\n * Whether the set of documents passed in was not sufficient to calculate the\n * new state of the view and there needs to be another pass based on the\n * local cache.\n */\n needsRefill: boolean;\n\n mutatedKeys: DocumentKeySet;\n}\n\nexport interface ViewChange {\n snapshot?: ViewSnapshot;\n limboChanges: LimboDocumentChange[];\n}\n\n/**\n * View is responsible for computing the final merged truth of what docs are in\n * a query. It gets notified of local and remote changes to docs, and applies\n * the query filters and limits to determine the most correct possible results.\n */\nexport class View {\n private syncState: SyncState | null = null;\n private hasCachedResults: boolean = false;\n /**\n * A flag whether the view is current with the backend. A view is considered\n * current after it has seen the current flag from the backend and did not\n * lose consistency within the watch stream (e.g. because of an existence\n * filter mismatch).\n */\n private current = false;\n private documentSet: DocumentSet;\n /** Documents in the view but not in the remote target */\n private limboDocuments = documentKeySet();\n /** Document Keys that have local changes */\n private mutatedKeys = documentKeySet();\n /** Query comparator that defines the document order in this view. */\n private docComparator: (d1: Document, d2: Document) => number;\n\n constructor(\n private query: Query,\n /** Documents included in the remote target */\n private _syncedDocuments: DocumentKeySet\n ) {\n this.docComparator = newQueryComparator(query);\n this.documentSet = new DocumentSet(this.docComparator);\n }\n\n /**\n * The set of remote documents that the server has told us belongs to the target associated with\n * this view.\n */\n get syncedDocuments(): DocumentKeySet {\n return this._syncedDocuments;\n }\n\n /**\n * Iterates over a set of doc changes, applies the query limit, and computes\n * what the new results should be, what the changes were, and whether we may\n * need to go back to the local cache for more results. Does not make any\n * changes to the view.\n * @param docChanges - The doc changes to apply to this view.\n * @param previousChanges - If this is being called with a refill, then start\n * with this set of docs and changes instead of the current view.\n * @returns a new set of docs, changes, and refill flag.\n */\n computeDocChanges(\n docChanges: DocumentMap,\n previousChanges?: ViewDocumentChanges\n ): ViewDocumentChanges {\n const changeSet = previousChanges\n ? previousChanges.changeSet\n : new DocumentChangeSet();\n const oldDocumentSet = previousChanges\n ? previousChanges.documentSet\n : this.documentSet;\n let newMutatedKeys = previousChanges\n ? previousChanges.mutatedKeys\n : this.mutatedKeys;\n let newDocumentSet = oldDocumentSet;\n let needsRefill = false;\n\n // Track the last doc in a (full) limit. This is necessary, because some\n // update (a delete, or an update moving a doc past the old limit) might\n // mean there is some other document in the local cache that either should\n // come (1) between the old last limit doc and the new last document, in the\n // case of updates, or (2) after the new last document, in the case of\n // deletes. So we keep this doc at the old limit to compare the updates to.\n //\n // Note that this should never get used in a refill (when previousChanges is\n // set), because there will only be adds -- no deletes or updates.\n const lastDocInLimit =\n this.query.limitType === LimitType.First &&\n oldDocumentSet.size === this.query.limit\n ? oldDocumentSet.last()\n : null;\n const firstDocInLimit =\n this.query.limitType === LimitType.Last &&\n oldDocumentSet.size === this.query.limit\n ? oldDocumentSet.first()\n : null;\n\n docChanges.inorderTraversal((key, entry) => {\n const oldDoc = oldDocumentSet.get(key);\n const newDoc = queryMatches(this.query, entry) ? entry : null;\n\n const oldDocHadPendingMutations = oldDoc\n ? this.mutatedKeys.has(oldDoc.key)\n : false;\n const newDocHasPendingMutations = newDoc\n ? newDoc.hasLocalMutations ||\n // We only consider committed mutations for documents that were\n // mutated during the lifetime of the view.\n (this.mutatedKeys.has(newDoc.key) && newDoc.hasCommittedMutations)\n : false;\n\n let changeApplied = false;\n\n // Calculate change\n if (oldDoc && newDoc) {\n const docsEqual = oldDoc.data.isEqual(newDoc.data);\n if (!docsEqual) {\n if (!this.shouldWaitForSyncedDocument(oldDoc, newDoc)) {\n changeSet.track({\n type: ChangeType.Modified,\n doc: newDoc\n });\n changeApplied = true;\n\n if (\n (lastDocInLimit &&\n this.docComparator(newDoc, lastDocInLimit) > 0) ||\n (firstDocInLimit &&\n this.docComparator(newDoc, firstDocInLimit) < 0)\n ) {\n // This doc moved from inside the limit to outside the limit.\n // That means there may be some other doc in the local cache\n // that should be included instead.\n needsRefill = true;\n }\n }\n } else if (oldDocHadPendingMutations !== newDocHasPendingMutations) {\n changeSet.track({ type: ChangeType.Metadata, doc: newDoc });\n changeApplied = true;\n }\n } else if (!oldDoc && newDoc) {\n changeSet.track({ type: ChangeType.Added, doc: newDoc });\n changeApplied = true;\n } else if (oldDoc && !newDoc) {\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc });\n changeApplied = true;\n\n if (lastDocInLimit || firstDocInLimit) {\n // A doc was removed from a full limit query. We'll need to\n // requery from the local cache to see if we know about some other\n // doc that should be in the results.\n needsRefill = true;\n }\n }\n\n if (changeApplied) {\n if (newDoc) {\n newDocumentSet = newDocumentSet.add(newDoc);\n if (newDocHasPendingMutations) {\n newMutatedKeys = newMutatedKeys.add(key);\n } else {\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n } else {\n newDocumentSet = newDocumentSet.delete(key);\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n }\n });\n\n // Drop documents out to meet limit/limitToLast requirement.\n if (this.query.limit !== null) {\n while (newDocumentSet.size > this.query.limit!) {\n const oldDoc =\n this.query.limitType === LimitType.First\n ? newDocumentSet.last()\n : newDocumentSet.first();\n newDocumentSet = newDocumentSet.delete(oldDoc!.key);\n newMutatedKeys = newMutatedKeys.delete(oldDoc!.key);\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc! });\n }\n }\n\n debugAssert(\n !needsRefill || !previousChanges,\n 'View was refilled using docs that themselves needed refilling.'\n );\n return {\n documentSet: newDocumentSet,\n changeSet,\n needsRefill,\n mutatedKeys: newMutatedKeys\n };\n }\n\n private shouldWaitForSyncedDocument(\n oldDoc: Document,\n newDoc: Document\n ): boolean {\n // We suppress the initial change event for documents that were modified as\n // part of a write acknowledgment (e.g. when the value of a server transform\n // is applied) as Watch will send us the same document again.\n // By suppressing the event, we only raise two user visible events (one with\n // `hasPendingWrites` and the final state of the document) instead of three\n // (one with `hasPendingWrites`, the modified document with\n // `hasPendingWrites` and the final state of the document).\n return (\n oldDoc.hasLocalMutations &&\n newDoc.hasCommittedMutations &&\n !newDoc.hasLocalMutations\n );\n }\n\n /**\n * Updates the view with the given ViewDocumentChanges and optionally updates\n * limbo docs and sync state from the provided target change.\n * @param docChanges - The set of changes to make to the view's docs.\n * @param limboResolutionEnabled - Whether to update limbo documents based on\n * this change.\n * @param targetChange - A target change to apply for computing limbo docs and\n * sync state.\n * @param targetIsPendingReset - Whether the target is pending to reset due to\n * existence filter mismatch. If not explicitly specified, it is treated\n * equivalently to `false`.\n * @returns A new ViewChange with the given docs, changes, and sync state.\n */\n // PORTING NOTE: The iOS/Android clients always compute limbo document changes.\n applyChanges(\n docChanges: ViewDocumentChanges,\n limboResolutionEnabled: boolean,\n targetChange?: TargetChange,\n targetIsPendingReset?: boolean\n ): ViewChange {\n debugAssert(\n !docChanges.needsRefill,\n 'Cannot apply changes that need a refill'\n );\n const oldDocs = this.documentSet;\n this.documentSet = docChanges.documentSet;\n this.mutatedKeys = docChanges.mutatedKeys;\n // Sort changes based on type and query comparator\n const changes = docChanges.changeSet.getChanges();\n changes.sort((c1, c2) => {\n return (\n compareChangeType(c1.type, c2.type) ||\n this.docComparator(c1.doc, c2.doc)\n );\n });\n\n this.applyTargetChange(targetChange);\n\n targetIsPendingReset = targetIsPendingReset ?? false;\n const limboChanges =\n limboResolutionEnabled && !targetIsPendingReset\n ? this.updateLimboDocuments()\n : [];\n\n // We are at synced state if there is no limbo docs are waiting to be resolved, view is current\n // with the backend, and the query is not pending to reset due to existence filter mismatch.\n const synced =\n this.limboDocuments.size === 0 && this.current && !targetIsPendingReset;\n\n const newSyncState = synced ? SyncState.Synced : SyncState.Local;\n const syncStateChanged = newSyncState !== this.syncState;\n this.syncState = newSyncState;\n\n if (changes.length === 0 && !syncStateChanged) {\n // no changes\n return { limboChanges };\n } else {\n const snap: ViewSnapshot = new ViewSnapshot(\n this.query,\n docChanges.documentSet,\n oldDocs,\n changes,\n docChanges.mutatedKeys,\n newSyncState === SyncState.Local,\n syncStateChanged,\n /* excludesMetadataChanges= */ false,\n targetChange\n ? targetChange.resumeToken.approximateByteSize() > 0\n : false\n );\n return {\n snapshot: snap,\n limboChanges\n };\n }\n }\n\n /**\n * Applies an OnlineState change to the view, potentially generating a\n * ViewChange if the view's syncState changes as a result.\n */\n applyOnlineStateChange(onlineState: OnlineState): ViewChange {\n if (this.current && onlineState === OnlineState.Offline) {\n // If we're offline, set `current` to false and then call applyChanges()\n // to refresh our syncState and generate a ViewChange as appropriate. We\n // are guaranteed to get a new TargetChange that sets `current` back to\n // true once the client is back online.\n this.current = false;\n return this.applyChanges(\n {\n documentSet: this.documentSet,\n changeSet: new DocumentChangeSet(),\n mutatedKeys: this.mutatedKeys,\n needsRefill: false\n },\n /* limboResolutionEnabled= */ false\n );\n } else {\n // No effect, just return a no-op ViewChange.\n return { limboChanges: [] };\n }\n }\n\n /**\n * Returns whether the doc for the given key should be in limbo.\n */\n private shouldBeInLimbo(key: DocumentKey): boolean {\n // If the remote end says it's part of this query, it's not in limbo.\n if (this._syncedDocuments.has(key)) {\n return false;\n }\n // The local store doesn't think it's a result, so it shouldn't be in limbo.\n if (!this.documentSet.has(key)) {\n return false;\n }\n // If there are local changes to the doc, they might explain why the server\n // doesn't know that it's part of the query. So don't put it in limbo.\n // TODO(klimt): Ideally, we would only consider changes that might actually\n // affect this specific query.\n if (this.documentSet.get(key)!.hasLocalMutations) {\n return false;\n }\n // Everything else is in limbo.\n return true;\n }\n\n /**\n * Updates syncedDocuments, current, and limbo docs based on the given change.\n * Returns the list of changes to which docs are in limbo.\n */\n private applyTargetChange(targetChange?: TargetChange): void {\n if (targetChange) {\n targetChange.addedDocuments.forEach(\n key => (this._syncedDocuments = this._syncedDocuments.add(key))\n );\n targetChange.modifiedDocuments.forEach(key => {\n debugAssert(\n this._syncedDocuments.has(key),\n `Modified document ${key} not found in view.`\n );\n });\n targetChange.removedDocuments.forEach(\n key => (this._syncedDocuments = this._syncedDocuments.delete(key))\n );\n this.current = targetChange.current;\n }\n }\n\n private updateLimboDocuments(): LimboDocumentChange[] {\n // We can only determine limbo documents when we're in-sync with the server.\n if (!this.current) {\n return [];\n }\n\n // TODO(klimt): Do this incrementally so that it's not quadratic when\n // updating many documents.\n const oldLimboDocuments = this.limboDocuments;\n this.limboDocuments = documentKeySet();\n this.documentSet.forEach(doc => {\n if (this.shouldBeInLimbo(doc.key)) {\n this.limboDocuments = this.limboDocuments.add(doc.key);\n }\n });\n\n // Diff the new limbo docs with the old limbo docs.\n const changes: LimboDocumentChange[] = [];\n oldLimboDocuments.forEach(key => {\n if (!this.limboDocuments.has(key)) {\n changes.push(new RemovedLimboDocument(key));\n }\n });\n this.limboDocuments.forEach(key => {\n if (!oldLimboDocuments.has(key)) {\n changes.push(new AddedLimboDocument(key));\n }\n });\n return changes;\n }\n\n /**\n * Update the in-memory state of the current view with the state read from\n * persistence.\n *\n * We update the query view whenever a client's primary status changes:\n * - When a client transitions from primary to secondary, it can miss\n * LocalStorage updates and its query views may temporarily not be\n * synchronized with the state on disk.\n * - For secondary to primary transitions, the client needs to update the list\n * of `syncedDocuments` since secondary clients update their query views\n * based purely on synthesized RemoteEvents.\n *\n * @param queryResult.documents - The documents that match the query according\n * to the LocalStore.\n * @param queryResult.remoteKeys - The keys of the documents that match the\n * query according to the backend.\n *\n * @returns The ViewChange that resulted from this synchronization.\n */\n // PORTING NOTE: Multi-tab only.\n synchronizeWithPersistedState(queryResult: QueryResult): ViewChange {\n this._syncedDocuments = queryResult.remoteKeys;\n this.limboDocuments = documentKeySet();\n const docChanges = this.computeDocChanges(queryResult.documents);\n return this.applyChanges(docChanges, /* limboResolutionEnabled= */ true);\n }\n\n /**\n * Returns a view snapshot as if this query was just listened to. Contains\n * a document add for every existing document and the `fromCache` and\n * `hasPendingWrites` status of the already established view.\n */\n // PORTING NOTE: Multi-tab only.\n computeInitialSnapshot(): ViewSnapshot {\n return ViewSnapshot.fromInitialDocuments(\n this.query,\n this.documentSet,\n this.mutatedKeys,\n this.syncState === SyncState.Local,\n this.hasCachedResults\n );\n }\n}\n\nfunction compareChangeType(c1: ChangeType, c2: ChangeType): number {\n const order = (change: ChangeType): 0 | 1 | 2 => {\n switch (change) {\n case ChangeType.Added:\n return 1;\n case ChangeType.Modified:\n return 2;\n case ChangeType.Metadata:\n // A metadata change is converted to a modified change at the public\n // api layer. Since we sort by document key and then change type,\n // metadata and modified changes must be sorted equivalently.\n return 2;\n case ChangeType.Removed:\n return 0;\n default:\n return fail(0x4f35, '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 0x5858,\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 0x390f,\n 'Received change for limbo target document without add.'\n );\n } else if (targetChange.removedDocuments.size > 0) {\n hardAssert(\n limboResolution.receivedDocument,\n 0xa4f3,\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(0x4d4f, 'Unknown limbo change', { 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(0x1a40, `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(0xfa9b, '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(metadata, reader.serializer);\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.completeAndStoreAsync(syncEngine.localStore);\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 0xb743,\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from './assert';\n\n/**\n * How many bytes to read each time when `ReadableStreamReader.read()` is\n * called. Only applicable for byte streams that we control (e.g. those backed\n * by an UInt8Array).\n */\nexport const DEFAULT_BYTES_PER_READ = 10240;\n\n/**\n * Builds a `ByteStreamReader` from a UInt8Array.\n * @param source - The data source to use.\n * @param bytesPerRead - How many bytes each `read()` from the returned reader\n * will read.\n */\nexport function toByteStreamReaderHelper(\n source: Uint8Array,\n bytesPerRead: number = DEFAULT_BYTES_PER_READ\n): ReadableStreamDefaultReader {\n debugAssert(\n bytesPerRead > 0,\n `toByteStreamReader expects positive bytesPerRead, but got ${bytesPerRead}`\n );\n let readFrom = 0;\n // The TypeScript definition for ReadableStreamReader changed. We use\n // `any` here to allow this code to compile with different versions.\n // See https://github.com/microsoft/TypeScript/issues/42970\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const reader: any = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async read(): Promise {\n if (readFrom < source.byteLength) {\n const result = {\n value: source.slice(readFrom, readFrom + bytesPerRead),\n done: false\n } as const;\n readFrom += bytesPerRead;\n return result;\n }\n\n return { done: true };\n },\n async cancel(): Promise {},\n releaseLock() {},\n closed: Promise.resolve()\n };\n return reader;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Observer } from '../core/event_manager';\n\nimport { FirestoreError } from './error';\nimport { logError } from './log';\nimport { EventHandler } from './misc';\n\n/*\n * A wrapper implementation of Observer 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { newTextDecoder } from '../platform/text_serializer';\nimport { BundleMetadata } from '../protos/firestore_bundle_proto';\nimport { JsonProtoSerializer } from '../remote/serializer';\n\nimport { debugAssert } from './assert';\nimport { BundleReader, SizedBundleElement } from './bundle_reader';\nimport { Deferred } from './promise';\n\n/**\n * A class representing a bundle.\n *\n * Takes a bundle stream or buffer, and presents abstractions to read bundled\n * elements out of the underlying content.\n */\nclass BundleReaderImpl implements BundleReader {\n /** Cached bundle metadata. */\n private metadata: Deferred = new Deferred();\n /**\n * Internal buffer to hold bundle content, accumulating incomplete element\n * content.\n */\n private buffer: Uint8Array = new Uint8Array();\n /** The decoder used to parse binary data into strings. */\n private textDecoder: TextDecoder;\n\n constructor(\n /** The reader to read from underlying binary bundle data source. */\n private reader: ReadableStreamDefaultReader,\n readonly serializer: JsonProtoSerializer\n ) {\n this.textDecoder = newTextDecoder();\n // Read the metadata (which is the first element).\n this.nextElementImpl().then(\n element => {\n if (element && element.isBundleMetadata()) {\n this.metadata.resolve(element.payload.metadata!);\n } else {\n this.metadata.reject(\n new Error(`The first element of the bundle is not a metadata, it is\n ${JSON.stringify(element?.payload)}`)\n );\n }\n },\n error => this.metadata.reject(error)\n );\n }\n\n close(): Promise {\n return this.reader.cancel();\n }\n\n async getMetadata(): Promise {\n return this.metadata.promise;\n }\n\n async nextElement(): Promise {\n // Makes sure metadata is read before proceeding.\n await this.getMetadata();\n return this.nextElementImpl();\n }\n\n /**\n * Reads from the head of internal buffer, and pulling more data from\n * underlying stream if a complete element cannot be found, until an\n * element(including the prefixed length and the JSON string) is found.\n *\n * Once a complete element is read, it is dropped from internal buffer.\n *\n * Returns either the bundled element, or null if we have reached the end of\n * the stream.\n */\n private async nextElementImpl(): Promise {\n const lengthBuffer = await this.readLength();\n if (lengthBuffer === null) {\n return null;\n }\n\n const lengthString = this.textDecoder.decode(lengthBuffer);\n const length = Number(lengthString);\n if (isNaN(length)) {\n this.raiseError(`length string (${lengthString}) is not valid number`);\n }\n\n const jsonString = await this.readJsonString(length);\n\n return new SizedBundleElement(\n JSON.parse(jsonString),\n lengthBuffer.length + length\n );\n }\n\n /** First index of '{' from the underlying buffer. */\n private indexOfOpenBracket(): number {\n return this.buffer.findIndex(v => v === '{'.charCodeAt(0));\n }\n\n /**\n * Reads from the beginning of the internal buffer, until the first '{', and\n * return the content.\n *\n * If reached end of the stream, returns a null.\n */\n private async readLength(): Promise {\n while (this.indexOfOpenBracket() < 0) {\n const done = await this.pullMoreDataToBuffer();\n if (done) {\n break;\n }\n }\n\n // Broke out of the loop because underlying stream is closed, and there\n // happens to be no more data to process.\n if (this.buffer.length === 0) {\n return null;\n }\n\n const position = this.indexOfOpenBracket();\n // Broke out of the loop because underlying stream is closed, but still\n // cannot find an open bracket.\n if (position < 0) {\n this.raiseError(\n 'Reached the end of bundle when a length string is expected.'\n );\n }\n\n const result = this.buffer.slice(0, position);\n // Update the internal buffer to drop the read length.\n this.buffer = this.buffer.slice(position);\n return result;\n }\n\n /**\n * Reads from a specified position from the internal buffer, for a specified\n * number of bytes, pulling more data from the underlying stream if needed.\n *\n * Returns a string decoded from the read bytes.\n */\n private async readJsonString(length: number): Promise {\n while (this.buffer.length < length) {\n const done = await this.pullMoreDataToBuffer();\n if (done) {\n this.raiseError('Reached the end of bundle when more is expected.');\n }\n }\n\n const result = this.textDecoder.decode(this.buffer.slice(0, length));\n // Update the internal buffer to drop the read json string.\n this.buffer = this.buffer.slice(length);\n return result;\n }\n\n private raiseError(message: string): void {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.reader.cancel();\n throw new Error(`Invalid bundle format: ${message}`);\n }\n\n /**\n * Pulls more data from underlying stream to internal buffer.\n * Returns a boolean indicating whether the stream is finished.\n */\n private async pullMoreDataToBuffer(): Promise {\n const result = await this.reader.read();\n if (!result.done) {\n debugAssert(!!result.value, 'Read undefined when \"done\" is false.');\n const newBuffer = new Uint8Array(\n this.buffer.length + result.value!.length\n );\n newBuffer.set(this.buffer);\n newBuffer.set(result.value!, this.buffer.length);\n this.buffer = newBuffer;\n }\n return result.done;\n }\n}\n\nexport function newBundleReader(\n reader: ReadableStreamDefaultReader,\n serializer: JsonProtoSerializer\n): BundleReader {\n return new BundleReaderImpl(reader, serializer);\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 } from '../protos/firestore_bundle_proto';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { BundleReaderSync, SizedBundleElement } from './bundle_reader';\n\n/**\n * A class that can parse a bundle form the string serialization of a bundle.\n */\nexport class BundleReaderSyncImpl implements BundleReaderSync {\n private metadata: BundleMetadata;\n private elements: SizedBundleElement[];\n private cursor: number;\n constructor(\n private bundleData: string,\n readonly serializer: JsonProtoSerializer\n ) {\n this.cursor = 0;\n this.elements = [];\n\n let element = this.nextElement();\n if (element && element.isBundleMetadata()) {\n this.metadata = element as BundleMetadata;\n } else {\n throw new Error(`The first element of the bundle is not a metadata object, it is\n ${JSON.stringify(element?.payload)}`);\n }\n\n do {\n element = this.nextElement();\n if (element !== null) {\n this.elements.push(element);\n }\n } while (element !== null);\n }\n\n /* Returns the parsed metadata of the bundle. */\n getMetadata(): BundleMetadata {\n return this.metadata;\n }\n\n /* Returns the DocumentSnapshot or NamedQuery elements of the bundle. */\n getElements(): SizedBundleElement[] {\n return this.elements;\n }\n\n /**\n * Parses the next element of the bundle.\n *\n * @returns a SizedBundleElement representation of the next element in the bundle, or null if\n * no more elements exist.\n */\n private nextElement(): SizedBundleElement | null {\n if (this.cursor === this.bundleData.length) {\n return null;\n }\n const length: number = this.readLength();\n const jsonString = this.readJsonString(length);\n return new SizedBundleElement(JSON.parse(jsonString), length);\n }\n\n /**\n * Reads from a specified position from the bundleData string, for a specified\n * number of bytes.\n *\n * @param length how many characters to read.\n * @returns a string parsed from the bundle.\n */\n private readJsonString(length: number): string {\n if (this.cursor + length > this.bundleData.length) {\n throw new FirestoreError(\n Code.INTERNAL,\n 'Reached the end of bundle when more is expected.'\n );\n }\n const result = this.bundleData.slice(this.cursor, (this.cursor += length));\n return result;\n }\n\n /**\n * Reads from the current cursor until the first '{'.\n *\n * @returns A string to integer represention of the parsed value.\n * @throws An {@link Error} if the cursor has reached the end of the stream, since lengths\n * prefix bundle objects.\n */\n private readLength(): number {\n const startIndex = this.cursor;\n let curIndex = this.cursor;\n while (curIndex < this.bundleData.length) {\n if (this.bundleData[curIndex] === '{') {\n if (curIndex === startIndex) {\n throw new Error('First character is a bracket and not a number');\n }\n this.cursor = curIndex;\n return Number(this.bundleData.slice(startIndex, curIndex));\n }\n curIndex++;\n }\n throw new Error('Reached the end of bundle when more is expected.');\n }\n}\n\n/**\n * Creates an instance of BundleReader without exposing the BundleReaderSyncImpl class type.\n */\nexport function newBundleReaderSync(\n bundleData: string,\n serializer: JsonProtoSerializer\n): BundleReaderSync {\n return new BundleReaderSyncImpl(bundleData, serializer);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParsedSetData, ParsedUpdateData } from '../lite-api/user_data_reader';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n DeleteMutation,\n Mutation,\n Precondition,\n VerifyMutation\n} from '../model/mutation';\nimport {\n Datastore,\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc\n} from '../remote/datastore';\nimport { fail, debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { SnapshotVersion } from './snapshot_version';\n\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nexport class Transaction {\n // The version of each document that was read during this transaction.\n private readVersions = new Map();\n private mutations: Mutation[] = [];\n private committed = false;\n\n /**\n * A deferred usage error that occurred previously in this transaction that\n * will cause the transaction to fail once it actually commits.\n */\n private lastTransactionError: FirestoreError | null = null;\n\n /**\n * Set of documents that have been written in the transaction.\n *\n * When there's more than one write to the same key in a transaction, any\n * writes after the first are handled differently.\n */\n private writtenDocs: Set = new Set();\n\n constructor(private datastore: Datastore) {}\n\n async lookup(keys: DocumentKey[]): Promise {\n this.ensureCommitNotCalled();\n\n if (this.mutations.length > 0) {\n this.lastTransactionError = new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Firestore transactions require all reads to be executed before all writes.'\n );\n throw this.lastTransactionError;\n }\n const docs = await invokeBatchGetDocumentsRpc(this.datastore, keys);\n docs.forEach(doc => this.recordVersion(doc));\n return docs;\n }\n\n set(key: DocumentKey, data: ParsedSetData): void {\n this.write(data.toMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n update(key: DocumentKey, data: ParsedUpdateData): void {\n try {\n this.write(data.toMutation(key, this.preconditionForUpdate(key)));\n } catch (e) {\n this.lastTransactionError = e as FirestoreError | null;\n }\n this.writtenDocs.add(key.toString());\n }\n\n delete(key: DocumentKey): void {\n this.write(new DeleteMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n async commit(): Promise {\n this.ensureCommitNotCalled();\n\n if (this.lastTransactionError) {\n throw this.lastTransactionError;\n }\n const unwritten = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach(mutation => {\n unwritten.delete(mutation.key.toString());\n });\n // For each document that was read but not written to, we want to perform\n // a `verify` operation.\n unwritten.forEach((_, path) => {\n const key = DocumentKey.fromPath(path);\n this.mutations.push(new VerifyMutation(key, this.precondition(key)));\n });\n await invokeCommitRpc(this.datastore, this.mutations);\n this.committed = true;\n }\n\n private recordVersion(doc: Document): void {\n let docVersion: SnapshotVersion;\n\n if (doc.isFoundDocument()) {\n docVersion = doc.version;\n } else if (doc.isNoDocument()) {\n // Represent a deleted doc using SnapshotVersion.min().\n docVersion = SnapshotVersion.min();\n } else {\n throw fail(0xc542, 'Document in a transaction was a ', {\n documentName: doc.constructor.name\n });\n }\n\n const existingVersion = this.readVersions.get(doc.key.toString());\n if (existingVersion) {\n if (!docVersion.isEqual(existingVersion)) {\n // This transaction will fail no matter what.\n throw new FirestoreError(\n Code.ABORTED,\n 'Document version changed between two reads.'\n );\n }\n } else {\n this.readVersions.set(doc.key.toString(), docVersion);\n }\n }\n\n /**\n * Returns the version of this document when it was read in this transaction,\n * as a precondition, or no precondition if it was not read.\n */\n private precondition(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n return Precondition.exists(false);\n } else {\n return Precondition.updateTime(version);\n }\n } else {\n return Precondition.none();\n }\n }\n\n /**\n * Returns the precondition for a document if the operation is an update.\n */\n private preconditionForUpdate(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n // The first time a document is written, we want to take into account the\n // read time and existence\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n // The document doesn't exist, so fail the transaction.\n\n // This has to be validated locally because you can't send a\n // precondition that a document does not exist without changing the\n // semantics of the backend write to be an insert. This is the reverse\n // of what we want, since we want to assert that the document doesn't\n // exist but then send the update and have it fail. Since we can't\n // express that to the backend, we have to validate locally.\n\n // Note: this can change once we can send separate verify writes in the\n // transaction.\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't update a document that doesn't exist.\"\n );\n }\n // Document exists, base precondition on document update time.\n return Precondition.updateTime(version);\n } else {\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return Precondition.exists(true);\n }\n }\n\n private write(mutation: Mutation): void {\n this.ensureCommitNotCalled();\n this.mutations.push(mutation);\n }\n\n private ensureCommitNotCalled(): void {\n debugAssert(\n !this.committed,\n 'A transaction object cannot be used after its update callback has been invoked.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ExponentialBackoff } from '../remote/backoff';\nimport { Datastore } from '../remote/datastore';\nimport { isPermanentError } from '../remote/rpc_error';\nimport { AsyncQueue, TimerId } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport { Deferred } from '../util/promise';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Transaction } from './transaction';\nimport { TransactionOptions } from './transaction_options';\n\n/**\n * TransactionRunner encapsulates the logic needed to run and retry transactions\n * with backoff.\n */\nexport class TransactionRunner {\n private attemptsRemaining: number;\n private backoff: ExponentialBackoff;\n\n constructor(\n private readonly asyncQueue: AsyncQueue,\n private readonly datastore: Datastore,\n private readonly options: TransactionOptions,\n private readonly updateFunction: (transaction: Transaction) => Promise,\n private readonly deferred: Deferred\n ) {\n this.attemptsRemaining = options.maxAttempts;\n this.backoff = new ExponentialBackoff(\n this.asyncQueue,\n TimerId.TransactionRetry\n );\n }\n\n /** Runs the transaction and sets the result on deferred. */\n run(): void {\n this.attemptsRemaining -= 1;\n this.runWithBackOff();\n }\n\n private runWithBackOff(): void {\n this.backoff.backoffAndRun(async () => {\n const transaction = new Transaction(this.datastore);\n const userPromise = this.tryRunUpdateFunction(transaction);\n if (userPromise) {\n userPromise\n .then(result => {\n this.asyncQueue.enqueueAndForget(() => {\n return transaction\n .commit()\n .then(() => {\n this.deferred.resolve(result);\n })\n .catch(commitError => {\n this.handleTransactionError(commitError);\n });\n });\n })\n .catch(userPromiseError => {\n this.handleTransactionError(userPromiseError);\n });\n }\n });\n }\n\n private tryRunUpdateFunction(transaction: Transaction): Promise | null {\n try {\n const userPromise = this.updateFunction(transaction);\n if (\n isNullOrUndefined(userPromise) ||\n !userPromise.catch ||\n !userPromise.then\n ) {\n this.deferred.reject(\n Error('Transaction callback must return a Promise')\n );\n return null;\n }\n return userPromise;\n } catch (error) {\n // Do not retry errors thrown by user provided updateFunction.\n this.deferred.reject(error as Error);\n return null;\n }\n }\n\n private handleTransactionError(error: Error): void {\n if (this.attemptsRemaining > 0 && this.isRetryableTransactionError(error)) {\n this.attemptsRemaining -= 1;\n this.asyncQueue.enqueueAndForget(() => {\n this.runWithBackOff();\n return Promise.resolve();\n });\n } else {\n this.deferred.reject(error);\n }\n }\n\n private isRetryableTransactionError(error: Error | undefined): boolean {\n if (error?.name === 'FirebaseError') {\n // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and\n // non-matching document versions with ABORTED. These errors should be retried.\n const code = (error as FirestoreError).code;\n return (\n code === 'aborted' ||\n code === 'failed-precondition' ||\n code === 'already-exists' ||\n !isPermanentError(code)\n );\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GetOptions } from '@firebase/firestore-types';\n\nimport { LoadBundleTask } from '../api/bundle';\nimport {\n CredentialChangeListener,\n CredentialsProvider\n} from '../api/credentials';\nimport { User } from '../auth/user';\nimport { LocalStore } from '../local/local_store';\nimport {\n localStoreConfigureFieldIndexes,\n localStoreDeleteAllFieldIndexes,\n localStoreExecuteQuery,\n localStoreGetNamedQuery,\n localStoreHandleUserChange,\n localStoreReadDocument,\n localStoreSetIndexAutoCreationEnabled\n} from '../local/local_store_impl';\nimport { Persistence } from '../local/persistence';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldIndex } from '../model/field_index';\nimport { Mutation } from '../model/mutation';\nimport { toByteStreamReader } from '../platform/byte_stream_reader';\nimport { newSerializer } from '../platform/serializer';\nimport { newTextEncoder } from '../platform/text_serializer';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { Datastore, invokeRunAggregationQueryRpc } from '../remote/datastore';\nimport {\n RemoteStore,\n remoteStoreDisableNetwork,\n remoteStoreEnableNetwork,\n remoteStoreHandleCredentialChange\n} from '../remote/remote_store';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { debugAssert } from '../util/assert';\nimport { AsyncObserver } from '../util/async_observer';\nimport { AsyncQueue, wrapInUserErrorIfRecoverable } from '../util/async_queue';\nimport { BundleReader, BundleReaderSync } from '../util/bundle_reader';\nimport { newBundleReader } from '../util/bundle_reader_impl';\nimport { newBundleReaderSync } from '../util/bundle_reader_sync_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 LruGcMemoryOfflineComponentProvider,\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 LruGcMemoryOfflineComponentProvider(undefined)\n );\n }\n }\n\n return client._offlineComponents!;\n}\n\nexport async 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 createBundleReaderSync(\n bundleData: string,\n serializer: JsonProtoSerializer\n): BundleReaderSync {\n return newBundleReaderSync(bundleData, 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BundleSource } from '../../util/bundle_reader';\nimport { toByteStreamReaderHelper } from '../../util/byte_stream';\n\n/**\n * On web, a `ReadableStream` is wrapped around by a `ByteStreamReader`.\n */\nexport function toByteStreamReader(\n source: BundleSource,\n bytesPerRead: number\n): ReadableStreamDefaultReader {\n if (source instanceof Uint8Array) {\n return toByteStreamReaderHelper(source, bytesPerRead);\n }\n if (source instanceof ArrayBuffer) {\n return toByteStreamReaderHelper(new Uint8Array(source), bytesPerRead);\n }\n if (source instanceof ReadableStream) {\n return source.getReader();\n }\n throw new Error(\n 'Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream'\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 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 settings.isUsingEmulator\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 { EmulatorMockTokenOptions } from '@firebase/util';\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 emulatorOptions?: { mockUserToken?: EmulatorMockTokenOptions | string };\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 readonly isUsingEmulator: boolean;\n\n // Can be a google-auth-library or gapi client.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n credentials?: any;\n\n constructor(settings: PrivateSettings) {\n if (settings.host === undefined) {\n if (settings.ssl !== undefined) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't provide ssl option if host option is not set\"\n );\n }\n this.host = DEFAULT_HOST;\n this.ssl = DEFAULT_SSL;\n } else {\n this.host = settings.host;\n this.ssl = settings.ssl ?? DEFAULT_SSL;\n }\n this.isUsingEmulator = settings.emulatorOptions !== undefined;\n\n this.credentials = settings.credentials;\n this.ignoreUndefinedProperties = !!settings.ignoreUndefinedProperties;\n this.localCache = settings.localCache;\n\n if (settings.cacheSizeBytes === undefined) {\n this.cacheSizeBytes = LRU_DEFAULT_CACHE_SIZE_BYTES;\n } else {\n if (\n settings.cacheSizeBytes !== LRU_COLLECTION_DISABLED &&\n settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`\n );\n } else {\n this.cacheSizeBytes = settings.cacheSizeBytes;\n }\n }\n\n validateIsNotUsedTogether(\n 'experimentalForceLongPolling',\n settings.experimentalForceLongPolling,\n 'experimentalAutoDetectLongPolling',\n settings.experimentalAutoDetectLongPolling\n );\n\n this.experimentalForceLongPolling = !!settings.experimentalForceLongPolling;\n\n if (this.experimentalForceLongPolling) {\n this.experimentalAutoDetectLongPolling = false;\n } else if (settings.experimentalAutoDetectLongPolling === undefined) {\n this.experimentalAutoDetectLongPolling = DEFAULT_AUTO_DETECT_LONG_POLLING;\n } else {\n // For backwards compatibility, coerce the value to boolean even though\n // the TypeScript compiler has narrowed the type to boolean already.\n // noinspection PointlessBooleanExpressionJS\n this.experimentalAutoDetectLongPolling =\n !!settings.experimentalAutoDetectLongPolling;\n }\n\n this.experimentalLongPollingOptions = cloneLongPollingOptions(\n settings.experimentalLongPollingOptions ?? {}\n );\n validateLongPollingOptions(this.experimentalLongPollingOptions);\n\n this.useFetchStreams = !!settings.useFetchStreams;\n }\n\n isEqual(other: FirestoreSettingsImpl): boolean {\n return (\n this.host === other.host &&\n this.ssl === other.ssl &&\n this.credentials === other.credentials &&\n this.cacheSizeBytes === other.cacheSizeBytes &&\n this.experimentalForceLongPolling ===\n other.experimentalForceLongPolling &&\n this.experimentalAutoDetectLongPolling ===\n other.experimentalAutoDetectLongPolling &&\n longPollingOptionsEqual(\n this.experimentalLongPollingOptions,\n other.experimentalLongPollingOptions\n ) &&\n this.ignoreUndefinedProperties === other.ignoreUndefinedProperties &&\n this.useFetchStreams === other.useFetchStreams\n );\n }\n}\n\nfunction validateLongPollingOptions(\n options: ExperimentalLongPollingOptions\n): void {\n if (options.timeoutSeconds !== undefined) {\n if (isNaN(options.timeoutSeconds)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ` +\n `${options.timeoutSeconds} (must not be NaN)`\n );\n }\n if (options.timeoutSeconds < MIN_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(minimum allowed value is ${MIN_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n if (options.timeoutSeconds > MAX_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(maximum allowed value is ${MAX_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _getProvider,\n _removeServiceInstance,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport {\n createMockUserToken,\n deepEqual,\n EmulatorMockTokenOptions,\n getDefaultEmulatorHostnameAndPort,\n isCloudWorkstation,\n pingServer,\n updateEmulatorBanner\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 private _emulatorOptions: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {};\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 this._emulatorOptions = settings.emulatorOptions || {};\n\n if (settings.credentials !== undefined) {\n this._authCredentials = makeAuthCredentialsProvider(settings.credentials);\n }\n }\n\n _getSettings(): FirestoreSettingsImpl {\n return this._settings;\n }\n\n _getEmulatorOptions(): { mockUserToken?: EmulatorMockTokenOptions | string } {\n return this._emulatorOptions;\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 useSsl = isCloudWorkstation(host);\n const settings = firestore._getSettings();\n const existingConfig = {\n ...settings,\n emulatorOptions: firestore._getEmulatorOptions()\n };\n const newHostSetting = `${host}:${port}`;\n if (useSsl) {\n void pingServer(`https://${newHostSetting}`);\n updateEmulatorBanner('Firestore', true);\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 const newConfig = {\n ...settings,\n host: newHostSetting,\n ssl: useSsl,\n emulatorOptions: options\n };\n // No-op if the new configuration matches the current configuration. This supports SSR\n // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice.\n if (deepEqual(newConfig, existingConfig)) {\n return;\n }\n\n firestore._setSettings(newConfig);\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';\n// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_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 static _jsonSchemaVersion: string = 'firestore/documentReference/1.0';\n static _jsonSchema = {\n type: property('string', DocumentReference._jsonSchemaVersion),\n referencePath: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `DocumentReference` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: DocumentReference._jsonSchemaVersion,\n referencePath: this._key.toString()\n };\n }\n\n /**\n * Builds a `DocumentReference` instance from a JSON object created by\n * {@link DocumentReference.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json a JSON object represention of a `DocumentReference` instance\n * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(firestore: Firestore, json: object): DocumentReference;\n /**\n * Builds a `DocumentReference` instance from a JSON object created by\n * {@link DocumentReference.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json a JSON object represention of a `DocumentReference` instance\n * @param converter - Converts objects to and from Firestore.\n * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON<\n NewAppModelType = DocumentData,\n NewDbModelType extends DocumentData = DocumentData\n >(\n firestore: Firestore,\n json: object,\n converter: FirestoreDataConverter\n ): DocumentReference;\n static fromJSON<\n NewAppModelType = DocumentData,\n NewDbModelType extends DocumentData = DocumentData\n >(\n firestore: Firestore,\n json: object,\n converter?: FirestoreDataConverter\n ): DocumentReference {\n if (validateJSON(json, DocumentReference._jsonSchema)) {\n return new DocumentReference(\n firestore,\n converter ? converter : null,\n new DocumentKey(ResourcePath.fromString(json.referencePath))\n );\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Bytes from JSON.'\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(0xb815, 'AsyncQueue is already failed', {\n messageOrStack: getMessageOrStack(this.failure)\n });\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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { JsonObject } from '../model/object_value';\nimport { FirestoreError } from '../util/error';\n\n/**\n * Observer/Subscribe interfaces.\n */\nexport type NextFn = (value: T) => void;\nexport type ErrorFn = (error: FirestoreError) => void;\nexport type CompleteFn = () => void;\n\n// Allow for any of the Observer methods to be undefined.\nexport interface PartialObserver {\n next?: NextFn;\n error?: ErrorFn;\n complete?: CompleteFn;\n}\n\nexport function isPartialObserver(obj: unknown): obj is PartialObserver {\n return implementsAnyMethods(obj, ['next', 'error', 'complete']);\n}\n\n/**\n * Returns true if obj is an object and contains at least one of the specified\n * methods.\n */\nfunction implementsAnyMethods(obj: unknown, methods: string[]): boolean {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n\n const object = obj as JsonObject;\n for (const method of methods) {\n if (method in object && typeof object[method] === 'function') {\n return true;\n }\n }\n return false;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PartialObserver } from '../api/observer';\nimport { debugAssert } from '../util/assert';\nimport { FirestoreError } from '../util/error';\nimport { Deferred } from '../util/promise';\n\n/**\n * Represents the state of bundle loading tasks.\n *\n * Both 'Error' and 'Success' are sinking state: task will abort or complete and there will\n * be no more updates after they are reported.\n */\nexport type TaskState = 'Error' | 'Running' | 'Success';\n\n/**\n * Represents a progress update or a final state from loading bundles.\n */\nexport interface LoadBundleTaskProgress {\n /** How many documents have been loaded. */\n documentsLoaded: number;\n /** How many documents are in the bundle being loaded. */\n totalDocuments: number;\n /** How many bytes have been loaded. */\n bytesLoaded: number;\n /** How many bytes are in the bundle being loaded. */\n totalBytes: number;\n /** Current task state. */\n taskState: TaskState;\n}\n\n/**\n * Represents the task of loading a Firestore bundle. It provides progress of bundle\n * loading, as well as task completion and error events.\n *\n * The API is compatible with `Promise`.\n */\nexport class LoadBundleTask implements PromiseLike {\n private _progressObserver: PartialObserver = {};\n private _taskCompletionResolver = new Deferred();\n\n private _lastProgress: LoadBundleTaskProgress = {\n taskState: 'Running',\n totalBytes: 0,\n totalDocuments: 0,\n bytesLoaded: 0,\n documentsLoaded: 0\n };\n\n /**\n * Registers functions to listen to bundle loading progress events.\n * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur\n * each time a Firestore document is loaded from the bundle.\n * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the\n * error, and there should be no more updates after this.\n * @param complete - Called when the loading task is complete.\n */\n onProgress(\n next?: (progress: LoadBundleTaskProgress) => unknown,\n error?: (err: Error) => unknown,\n complete?: () => void\n ): void {\n this._progressObserver = {\n next,\n error,\n complete\n };\n }\n\n /**\n * Implements the `Promise.catch` interface.\n *\n * @param onRejected - Called when an error occurs during bundle loading.\n */\n catch(\n onRejected: (a: Error) => R | PromiseLike\n ): Promise {\n return this._taskCompletionResolver.promise.catch(onRejected);\n }\n\n /**\n * Implements the `Promise.then` interface.\n *\n * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update.\n * The update will always have its `taskState` set to `\"Success\"`.\n * @param onRejected - Called when an error occurs during bundle loading.\n */\n then(\n onFulfilled?: (a: LoadBundleTaskProgress) => T | PromiseLike,\n onRejected?: (a: Error) => R | PromiseLike\n ): Promise {\n return this._taskCompletionResolver.promise.then(onFulfilled, onRejected);\n }\n\n /**\n * Notifies all observers that bundle loading has completed, with a provided\n * `LoadBundleTaskProgress` object.\n *\n * @private\n */\n _completeWith(progress: LoadBundleTaskProgress): void {\n debugAssert(\n progress.taskState === 'Success',\n 'Task is not completed with Success.'\n );\n this._updateProgress(progress);\n if (this._progressObserver.complete) {\n this._progressObserver.complete();\n }\n\n this._taskCompletionResolver.resolve(progress);\n }\n\n /**\n * Notifies all observers that bundle loading has failed, with a provided\n * `Error` as the reason.\n *\n * @private\n */\n _failWith(error: FirestoreError): void {\n this._lastProgress.taskState = 'Error';\n\n if (this._progressObserver.next) {\n this._progressObserver.next(this._lastProgress);\n }\n\n if (this._progressObserver.error) {\n this._progressObserver.error(error);\n }\n\n this._taskCompletionResolver.reject(error);\n }\n\n /**\n * Notifies a progress update of loading a bundle.\n * @param progress - The new progress.\n *\n * @private\n */\n _updateProgress(progress: LoadBundleTaskProgress): void {\n debugAssert(\n this._lastProgress.taskState === 'Running',\n 'Cannot update progress on a completed or failed task'\n );\n\n this._lastProgress = progress;\n if (this._progressObserver.next) {\n this._progressObserver.next(progress);\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _getProvider,\n _removeServiceInstance,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport {\n deepEqual,\n getDefaultEmulatorHostnameAndPort,\n isCloudWorkstation,\n pingServer\n} 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 // Workaround to get cookies in Firebase Studio\n if (settings.host && isCloudWorkstation(settings.host)) {\n void pingServer(settings.host);\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 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 { AggregateType } from '../core/aggregate';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\n\nimport { average, count, sum } from './aggregate';\nimport { DocumentData, Query } from './reference';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\nexport { AggregateType };\n\n/**\n * Represents an aggregation that can be performed by Firestore.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport class AggregateField {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateField';\n\n /** Indicates the aggregation operation of this AggregateField. */\n readonly aggregateType: AggregateType;\n\n /**\n * Create a new AggregateField\n * @param aggregateType Specifies the type of aggregation operation to perform.\n * @param _internalFieldPath Optionally specifies the field that is aggregated.\n * @internal\n */\n constructor(\n aggregateType: AggregateType = 'count',\n readonly _internalFieldPath?: InternalFieldPath\n ) {\n this.aggregateType = aggregateType;\n }\n}\n\n/**\n * The union of all `AggregateField` types that are supported by Firestore.\n */\nexport type AggregateFieldType =\n | ReturnType\n | ReturnType\n | ReturnType;\n\n/**\n * Specifies a set of aggregations and their aliases.\n */\nexport interface AggregateSpec {\n [field: string]: AggregateFieldType;\n}\n\n/**\n * A type whose keys are taken from an `AggregateSpec`, and whose values are the\n * result of the aggregation performed by the corresponding `AggregateField`\n * from the input `AggregateSpec`.\n */\nexport type AggregateSpecData = {\n [P in keyof T]: T[P] extends AggregateField ? U : never;\n};\n\n/**\n * The results of executing an aggregation query.\n */\nexport class AggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateQuerySnapshot';\n\n /**\n * The underlying query over which the aggregations recorded in this\n * `AggregateQuerySnapshot` were performed.\n */\n readonly query: Query;\n\n /** @hideconstructor */\n constructor(\n query: Query,\n private readonly _userDataWriter: AbstractUserDataWriter,\n private readonly _data: ApiClientObjectMap\n ) {\n this.query = query;\n }\n\n /**\n * Returns the results of the aggregations performed over the underlying\n * query.\n *\n * The keys of the returned object will be the same as those of the\n * `AggregateSpec` object specified to the aggregation method, and the values\n * will be the corresponding aggregation result.\n *\n * @returns The results of the aggregations performed over the underlying\n * query.\n */\n data(): AggregateSpecData {\n return this._userDataWriter.convertObjectMap(\n this._data\n ) as AggregateSpecData;\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// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\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 static _jsonSchemaVersion: string = 'firestore/bytes/1.0';\n static _jsonSchema = {\n type: property('string', Bytes._jsonSchemaVersion),\n bytes: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `Bytes` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: Bytes._jsonSchemaVersion,\n bytes: this.toBase64()\n };\n }\n\n /**\n * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}.\n *\n * @param json a JSON object represention of a `Bytes` instance\n * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): Bytes {\n if (validateJSON(json, Bytes._jsonSchema)) {\n return Bytes.fromBase64String(json.bytes);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Bytes from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n 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';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\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 /**\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 static _jsonSchemaVersion: string = 'firestore/geoPoint/1.0';\n static _jsonSchema = {\n type: property('string', GeoPoint._jsonSchemaVersion),\n latitude: property('number'),\n longitude: property('number')\n };\n\n /**\n * Returns a JSON-serializable representation of this `GeoPoint` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): { latitude: number; longitude: number; type: string } {\n return {\n latitude: this._lat,\n longitude: this._long,\n type: GeoPoint._jsonSchemaVersion\n };\n }\n\n /**\n * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}.\n *\n * @param json a JSON object represention of a `GeoPoint` instance\n * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): GeoPoint {\n if (validateJSON(json, GeoPoint._jsonSchema)) {\n return new GeoPoint(json.latitude, json.longitude);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating GeoPoint from JSON.'\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';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\n\n/**\n * Represents a vector type in Firestore documents.\n * Create an instance with {@link 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` values have the same raw number arrays, returns `false` otherwise.\n */\n isEqual(other: VectorValue): boolean {\n return isPrimitiveArrayEqual(this._values, other._values);\n }\n\n static _jsonSchemaVersion: string = 'firestore/vectorValue/1.0';\n static _jsonSchema = {\n type: property('string', VectorValue._jsonSchemaVersion),\n vectorValues: property('object')\n };\n\n /**\n * Returns a JSON-serializable representation of this `VectorValue` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: VectorValue._jsonSchemaVersion,\n vectorValues: this._values\n };\n }\n\n /**\n * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}.\n *\n * @param json a JSON object represention of a `VectorValue` instance.\n * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): VectorValue {\n if (validateJSON(json, VectorValue._jsonSchema)) {\n if (\n Array.isArray(json.vectorValues) &&\n json.vectorValues.every(element => typeof element === 'number')\n ) {\n return new VectorValue(json.vectorValues);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Expected 'vectorValues' field to be a number array\"\n );\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Timestamp from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData,\n FieldPath as PublicFieldPath,\n SetOptions\n} from '@firebase/firestore-types';\nimport { Compat, deepEqual, getModularInstance } from '@firebase/util';\n\nimport { ParseContext } from '../api/parse_context';\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n FieldTransform,\n Mutation,\n PatchMutation,\n Precondition,\n SetMutation\n} from '../model/mutation';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform\n} from '../model/transform_operation';\nimport {\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(0x9c4b, 'Unexpected case for UserDataSource', {\n dataSource\n });\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\nexport function 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(0xf2a2, 'Invalid value type', {\n value\n });\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 0x25d8,\n 'ReferenceValue is not valid',\n { name }\n );\n const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3));\n const key = new DocumentKey(resourcePath.popFirst(5));\n\n if (!databaseId.isEqual(expectedDatabaseId)) {\n // TODO(b/64130202): Somehow support foreign references.\n logError(\n `Document ${key} contains a document ` +\n `reference within a different database (` +\n `${databaseId.projectId}/${databaseId.database}) which is not ` +\n `supported. It will be treated as a reference in the current ` +\n `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` +\n `instead.`\n );\n }\n return key;\n }\n\n protected abstract convertReference(name: string): unknown;\n\n protected abstract convertBytes(bytes: ByteString): unknown;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData as PublicDocumentData,\n SetOptions as PublicSetOptions\n} from '@firebase/firestore-types';\nimport { getModularInstance } from '@firebase/util';\n\nimport { LimitType } from '../core/query';\nimport { DeleteMutation, Precondition } from '../model/mutation';\nimport {\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc,\n invokeRunQueryRpc\n} from '../remote/datastore';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { cast } from '../util/input_validation';\n\nimport { Bytes } from './bytes';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { validateHasExplicitOrderByForLimitToLast } from './query';\nimport {\n CollectionReference,\n doc,\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot\n} from './snapshot';\nimport {\n newUserDataReader,\n ParsedUpdateData,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converts custom model object of type T into `DocumentData` by applying the\n * converter if it exists.\n *\n * This function is used when converting user objects to `DocumentData`\n * because we want to provide the user with a more specific error message if\n * their `set()` or fails due to invalid data originating from a `toFirestore()`\n * call.\n */\nexport function applyFirestoreDataConverter(\n converter: UntypedFirestoreDataConverter | null,\n value: WithFieldValue | PartialWithFieldValue,\n options?: PublicSetOptions\n): PublicDocumentData {\n let convertedValue;\n if (converter) {\n if (options && (options.merge || options.mergeFields)) {\n // Cast to `any` in order to satisfy the union type constraint on\n // toFirestore().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n convertedValue = (converter as any).toFirestore(value, options);\n } else {\n convertedValue = converter.toFirestore(value as WithFieldValue);\n }\n } else {\n convertedValue = value as PublicDocumentData;\n }\n return convertedValue;\n}\n\nexport class LiteUserDataWriter extends AbstractUserDataWriter {\n constructor(protected firestore: Firestore) {\n super();\n }\n\n protected convertBytes(bytes: ByteString): Bytes {\n return new Bytes(bytes);\n }\n\n protected convertReference(name: string): DocumentReference {\n const key = this.convertDocumentKey(name, this.firestore._databaseId);\n return new DocumentReference(this.firestore, /* converter= */ null, key);\n }\n}\n\n/**\n * Reads the document referred to by the specified document reference.\n *\n * All documents are directly fetched from the server, even if the document was\n * previously read or modified. Recent modifications are only reflected in the\n * retrieved `DocumentSnapshot` if they have already been applied by the\n * backend. If the client is offline, the read fails. If you like to use\n * caching or see local modifications, please use the full Firestore SDK.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the current\n * document contents.\n */\nexport function getDoc(\n reference: DocumentReference\n): Promise> {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n const userDataWriter = new LiteUserDataWriter(reference.firestore);\n\n return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then(\n result => {\n hardAssert(\n result.length === 1,\n 0x3d02,\n 'Expected a single document result'\n );\n const document = result[0];\n return new DocumentSnapshot(\n reference.firestore,\n userDataWriter,\n reference._key,\n document.isFoundDocument() ? document : null,\n reference.converter\n );\n }\n );\n}\n\n/**\n * Executes the query and returns the results as a {@link QuerySnapshot}.\n *\n * All queries are executed directly by the server, even if the query was\n * previously executed. Recent modifications are only reflected in the retrieved\n * results if they have already been applied by the backend. If the client is\n * offline, the operation fails. To see previously cached result and local\n * modifications, use the full Firestore SDK.\n *\n * @param query - The `Query` to execute.\n * @returns A Promise that will be resolved with the results of the query.\n */\nexport function getDocs(\n query: Query\n): Promise> {\n query = cast>(query, Query);\n validateHasExplicitOrderByForLimitToLast(query._query);\n\n const datastore = getDatastore(query.firestore);\n const userDataWriter = new LiteUserDataWriter(query.firestore);\n return invokeRunQueryRpc(datastore, query._query).then(result => {\n const docs = result.map(\n doc =>\n new QueryDocumentSnapshot(\n query.firestore,\n userDataWriter,\n doc.key,\n doc,\n query.converter\n )\n );\n\n if (query._query.limitType === LimitType.Last) {\n // Limit to last queries reverse the orderBy constraint that was\n // specified by the user. As such, we need to reverse the order of the\n // results to return the documents in the expected order.\n docs.reverse();\n }\n\n return new QuerySnapshot(query, docs);\n });\n}\n\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\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 * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\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 convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data,\n options\n );\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'setDoc',\n reference._key,\n convertedValue,\n reference.converter !== null,\n options\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference`. The update will fail if applied to a document that does\n * not exist.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\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 * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\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 dataReader = newUserDataReader(reference.firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed: ParsedUpdateData;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData\n );\n }\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.exists(true))\n ]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * The deletion will only be reflected in document reads that occur after the\n * returned promise resolves. If the client is offline, the\n * delete fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to delete.\n * @returns A `Promise` resolved once the document has been successfully\n * deleted from the backend.\n */\nexport function deleteDoc(\n reference: DocumentReference\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n new DeleteMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend.\n */\nexport function addDoc(\n reference: CollectionReference,\n data: WithFieldValue\n): Promise> {\n reference = cast>(\n reference,\n CollectionReference\n );\n const docRef = doc(reference);\n\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data as PartialWithFieldValue\n );\n\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'addDoc',\n docRef._key,\n convertedValue,\n docRef.converter !== null,\n {}\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(docRef._key, Precondition.exists(false))\n ]).then(() => docRef);\n}\n","/**\n * @license\n * Copyright 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 { deepEqual } from '@firebase/util';\n\nimport { AggregateImpl } from '../core/aggregate';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { invokeRunAggregationQueryRpc } from '../remote/datastore';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport {\n AggregateField,\n AggregateQuerySnapshot,\n AggregateSpec\n} from './aggregate_types';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { DocumentData, Query, queryEqual } from './reference';\nimport { LiteUserDataWriter } from './reference_impl';\nimport { fieldPathFromArgument } from './user_data_reader';\n\n/**\n * Calculates the number of documents in the result set of the given query\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can\n * count the documents in cases where the result set is prohibitively large to\n * download entirely (thousands of documents).\n *\n * @param query The query whose result set size is calculated.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */\nexport function getCount(\n query: Query\n): Promise<\n AggregateQuerySnapshot<\n { count: AggregateField },\n AppModelType,\n DbModelType\n >\n> {\n const countQuerySpec: { count: AggregateField } = {\n count: count()\n };\n\n return getAggregate(query, countQuerySpec);\n}\n\n/**\n * Calculates the specified aggregations over the documents in the result\n * set of the given query without actually downloading the documents.\n *\n * Using this function to perform aggregations is efficient because only the\n * final aggregation values, not the documents' data, are downloaded. This\n * function can perform aggregations of the documents in cases where the result\n * set is prohibitively large to download entirely (thousands of documents).\n *\n * @param query The query whose result set is aggregated over.\n * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates\n * to perform over the result set. The AggregateSpec specifies aliases for each\n * aggregate, which can be used to retrieve the aggregate result.\n * @example\n * ```typescript\n * const aggregateSnapshot = await getAggregate(query, {\n * countOfDocs: count(),\n * totalHours: sum('hours'),\n * averageScore: average('score')\n * });\n *\n * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;\n * const totalHours: number = aggregateSnapshot.data().totalHours;\n * const averageScore: number | null = aggregateSnapshot.data().averageScore;\n * ```\n */\nexport function getAggregate<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n aggregateSpec: AggregateSpecType\n): Promise<\n AggregateQuerySnapshot\n> {\n const firestore = cast(query.firestore, Firestore);\n const datastore = getDatastore(firestore);\n\n const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n\n // Run the aggregation and convert the results\n return invokeRunAggregationQueryRpc(\n datastore,\n query._query,\n internalAggregates\n ).then(aggregateResult =>\n convertToAggregateQuerySnapshot(firestore, query, aggregateResult)\n );\n}\n\nfunction convertToAggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n query: Query,\n aggregateResult: ApiClientObjectMap\n): AggregateQuerySnapshot {\n const userDataWriter = new LiteUserDataWriter(firestore);\n const querySnapshot = new AggregateQuerySnapshot<\n AggregateSpecType,\n AppModelType,\n DbModelType\n >(query, userDataWriter, aggregateResult);\n return querySnapshot;\n}\n\n/**\n * Create an AggregateField object that can be used to compute the sum of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to sum across the result set.\n */\nexport function sum(field: string | FieldPath): AggregateField {\n return new AggregateField('sum', fieldPathFromArgument('sum', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the average of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to average across the result set.\n */\nexport function average(\n field: string | FieldPath\n): AggregateField {\n return new AggregateField('avg', fieldPathFromArgument('average', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the count of\n * documents in the result set of a query.\n */\nexport function count(): AggregateField {\n return new AggregateField('count');\n}\n\n/**\n * Compares two 'AggregateField` instances for equality.\n *\n * @param left Compare this AggregateField to the `right`.\n * @param right Compare this AggregateField to the `left`.\n */\nexport function aggregateFieldEqual(\n left: AggregateField,\n right: AggregateField\n): boolean {\n return (\n left instanceof AggregateField &&\n right instanceof AggregateField &&\n left.aggregateType === right.aggregateType &&\n left._internalFieldPath?.canonicalString() ===\n right._internalFieldPath?.canonicalString()\n );\n}\n\n/**\n * Compares two `AggregateQuerySnapshot` instances for equality.\n *\n * Two `AggregateQuerySnapshot` instances are considered \"equal\" if they have\n * underlying queries that compare equal, and the same data.\n *\n * @param left - The first `AggregateQuerySnapshot` to compare.\n * @param right - The second `AggregateQuerySnapshot` to compare.\n *\n * @returns `true` if the objects are \"equal\", as defined above, or `false`\n * otherwise.\n */\nexport function aggregateQuerySnapshotEqual<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n left: AggregateQuerySnapshot,\n right: AggregateQuerySnapshot\n): boolean {\n return (\n queryEqual(left.query, right.query) && deepEqual(left.data(), right.data())\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 { BundleLoader } from '../core/bundle_impl';\nimport { createBundleReaderSync } from '../core/firestore_client';\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 { LiteUserDataWriter } from '../lite-api/reference_impl';\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 { fromBundledQuery } from '../local/local_serializer';\nimport { documentKeySet } from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { DocumentSet } from '../model/document_set';\nimport { ResourcePath } from '../model/path';\nimport { newSerializer } from '../platform/serializer';\nimport {\n buildQuerySnapshotJsonBundle,\n buildDocumentSnapshotJsonBundle\n} from '../platform/snapshot_to_json';\nimport { fromDocument } from '../remote/serializer';\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\nimport { AutoId } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { SnapshotListenOptions } from './reference_impl';\n\nconst NOT_SUPPORTED = 'NOT SUPPORTED';\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 static _jsonSchemaVersion: string = 'firestore/documentSnapshot/1.0';\n static _jsonSchema = {\n type: property('string', DocumentSnapshot._jsonSchemaVersion),\n bundleSource: property('string', 'DocumentSnapshot'),\n bundleName: property('string'),\n bundle: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `DocumentSnapshot` instance.\n *\n * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this\n * `DocumentSnapshot` has pending writes.\n */\n toJSON(): object {\n if (this.metadata.hasPendingWrites) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'DocumentSnapshot.toJSON() attempted to serialize a document with pending writes. ' +\n 'Await waitForPendingWrites() before invoking toJSON().'\n );\n }\n const document = this._document;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: any = {};\n result['type'] = DocumentSnapshot._jsonSchemaVersion;\n result['bundle'] = '';\n result['bundleSource'] = 'DocumentSnapshot';\n result['bundleName'] = this._key.toString();\n\n if (\n !document ||\n !document.isValidDocument() ||\n !document.isFoundDocument()\n ) {\n return result;\n }\n const documentData = this._userDataWriter.convertObjectMap(\n document.data.value.mapValue.fields,\n 'previous'\n );\n result['bundle'] = buildDocumentSnapshotJsonBundle(\n this._firestore,\n document,\n documentData,\n this.ref.path\n );\n return result;\n }\n}\n\n/**\n * Builds a `DocumentSnapshot` instance from a JSON object created by\n * {@link DocumentSnapshot.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json - a JSON object represention of a `DocumentSnapshot` instance.\n * @returns an instance of {@link DocumentSnapshot} if the JSON object could be\n * parsed. Throws a {@link FirestoreError} if an error occurs.\n */\nexport function documentSnapshotFromJSON(\n db: Firestore,\n json: object\n): DocumentSnapshot;\n/**\n * Builds a `DocumentSnapshot` instance from a JSON object created by\n * {@link DocumentSnapshot.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json - a JSON object represention of a `DocumentSnapshot` instance.\n * @param converter - Converts objects to and from Firestore.\n * @returns an instance of {@link DocumentSnapshot} if the JSON object could be\n * parsed. Throws a {@link FirestoreError} if an error occurs.\n */\nexport function documentSnapshotFromJSON<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n>(\n db: Firestore,\n json: object,\n converter: FirestoreDataConverter\n): DocumentSnapshot;\nexport function documentSnapshotFromJSON<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n>(\n db: Firestore,\n json: object,\n converter?: FirestoreDataConverter\n): DocumentSnapshot {\n if (validateJSON(json, DocumentSnapshot._jsonSchema)) {\n if (json.bundle === NOT_SUPPORTED) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'The provided JSON object was created in a client environment, which is not supported.'\n );\n }\n // Parse the bundle data.\n const serializer = newSerializer(db._databaseId);\n const bundleReader = createBundleReaderSync(json.bundle, serializer);\n const elements = bundleReader.getElements();\n const bundleLoader: BundleLoader = new BundleLoader(\n bundleReader.getMetadata(),\n serializer\n );\n for (const element of elements) {\n bundleLoader.addSizedElement(element);\n }\n\n // Ensure that we have the correct number of documents in the bundle.\n const bundledDocuments = bundleLoader.documents;\n if (bundledDocuments.length !== 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Expected bundle data to contain 1 document, but it contains ${bundledDocuments.length} documents.`\n );\n }\n\n // Build out the internal document data.\n const document = fromDocument(serializer, bundledDocuments[0].document!);\n const documentKey = new DocumentKey(\n ResourcePath.fromString(json.bundleName)\n );\n\n // Return the external facing DocumentSnapshot.\n return new DocumentSnapshot(\n db,\n new LiteUserDataWriter(db),\n documentKey,\n document,\n new SnapshotMetadata(\n /* hasPendingWrites= */ false,\n /* fromCache= */ false\n ),\n converter ? converter : null\n );\n }\n throw new FirestoreError(\n Code.INTERNAL,\n 'Unexpected error creating DocumentSnapshot from JSON.'\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 static _jsonSchemaVersion: string = 'firestore/querySnapshot/1.0';\n static _jsonSchema = {\n type: property('string', QuerySnapshot._jsonSchemaVersion),\n bundleSource: property('string', 'QuerySnapshot'),\n bundleName: property('string'),\n bundle: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `QuerySnapshot` instance.\n *\n * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this\n * `QuerySnapshot` has pending writes.\n */\n toJSON(): object {\n if (this.metadata.hasPendingWrites) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'QuerySnapshot.toJSON() attempted to serialize a document with pending writes. ' +\n 'Await waitForPendingWrites() before invoking toJSON().'\n );\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: any = {};\n result['type'] = QuerySnapshot._jsonSchemaVersion;\n result['bundleSource'] = 'QuerySnapshot';\n result['bundleName'] = AutoId.newId();\n\n const databaseId = this._firestore._databaseId.database;\n const projectId = this._firestore._databaseId.projectId;\n const parent = `projects/${projectId}/databases/${databaseId}/documents`;\n const documents: Document[] = [];\n const documentData: DocumentData[] = [];\n const paths: string[] = [];\n\n this.docs.forEach(doc => {\n if (doc._document === null) {\n return;\n }\n documents.push(doc._document);\n documentData.push(\n this._userDataWriter.convertObjectMap(\n doc._document.data.value.mapValue.fields,\n 'previous'\n )\n );\n paths.push(doc.ref.path);\n });\n result['bundle'] = buildQuerySnapshotJsonBundle(\n this._firestore,\n this.query._query,\n result['bundleName'],\n parent,\n paths,\n documents,\n documentData\n );\n return result;\n }\n}\n\n/**\n * Builds a `QuerySnapshot` instance from a JSON object created by\n * {@link QuerySnapshot.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json - a JSON object represention of a `QuerySnapshot` instance.\n * @returns an instance of {@link QuerySnapshot} if the JSON object could be\n * parsed. Throws a {@link FirestoreError} if an error occurs.\n */\nexport function querySnapshotFromJSON(\n db: Firestore,\n json: object\n): QuerySnapshot;\n/**\n * Builds a `QuerySnapshot` instance from a JSON object created by\n * {@link QuerySnapshot.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json - a JSON object represention of a `QuerySnapshot` instance.\n * @param converter - Converts objects to and from Firestore.\n * @returns an instance of {@link QuerySnapshot} if the JSON object could be\n * parsed. Throws a {@link FirestoreError} if an error occurs.\n */\nexport function querySnapshotFromJSON<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n>(\n db: Firestore,\n json: object,\n converter: FirestoreDataConverter\n): QuerySnapshot;\nexport function querySnapshotFromJSON<\n AppModelType,\n DbModelType extends DocumentData\n>(\n db: Firestore,\n json: object,\n converter?: FirestoreDataConverter\n): QuerySnapshot {\n if (validateJSON(json, QuerySnapshot._jsonSchema)) {\n if (json.bundle === NOT_SUPPORTED) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'The provided JSON object was created in a client environment, which is not supported.'\n );\n }\n // Parse the bundle data.\n const serializer = newSerializer(db._databaseId);\n const bundleReader = createBundleReaderSync(json.bundle, serializer);\n const elements = bundleReader.getElements();\n const bundleLoader: BundleLoader = new BundleLoader(\n bundleReader.getMetadata(),\n serializer\n );\n for (const element of elements) {\n bundleLoader.addSizedElement(element);\n }\n\n if (bundleLoader.queries.length !== 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Snapshot data expected 1 query but found ${bundleLoader.queries.length} queries.`\n );\n }\n\n // Create an internal Query object from the named query in the bundle.\n const query = fromBundledQuery(bundleLoader.queries[0].bundledQuery!);\n\n // Construct the arrays of document data for the query.\n const bundledDocuments = bundleLoader.documents;\n let documentSet = new DocumentSet();\n bundledDocuments.map(bundledDocument => {\n const document = fromDocument(serializer, bundledDocument.document!);\n documentSet = documentSet.add(document);\n });\n // Create a view snapshot of the query and documents.\n const viewSnapshot = ViewSnapshot.fromInitialDocuments(\n query,\n documentSet,\n documentKeySet() /* Zero mutated keys signifies no pending writes. */,\n /* fromCache= */ false,\n /* hasCachedResults= */ false\n );\n\n // Create an external Query object, required to construct the QuerySnapshot.\n const externalQuery = new Query(\n db,\n converter ? converter : null,\n query\n );\n\n // Return a new QuerySnapshot with all of the collected data.\n return new QuerySnapshot(\n db,\n new LiteUserDataWriter(db),\n externalQuery,\n viewSnapshot\n );\n }\n throw new FirestoreError(\n Code.INTERNAL,\n 'Unexpected error creating QuerySnapshot from JSON.'\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(0xf03d, '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 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 build JSON bundle implementations. */\nimport { Firestore } from '../../api/database';\nimport { Query } from '../../core/query';\nimport { DocumentData } from '../../lite-api/reference';\nimport { Document } from '../../model/document';\n\nexport function buildDocumentSnapshotJsonBundle(\n db: Firestore,\n document: Document,\n docData: DocumentData,\n path: string\n): string {\n return 'NOT SUPPORTED';\n}\n\nexport function buildQuerySnapshotJsonBundle(\n db: Firestore,\n query: Query,\n bundleName: string,\n parent: string,\n paths: string[],\n docs: Document[],\n documentData: DocumentData[]\n): string {\n return 'NOT SUPPORTED';\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 { loadBundle, namedQuery } from '../api/database';\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 { DocumentKey } from '../model/document_key';\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { debugAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport {\n DocumentSnapshot,\n FirestoreDataConverter,\n QuerySnapshot,\n SnapshotMetadata\n} 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @returns An unsubscribe function that can be called to cancel 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @returns An unsubscribe function that can be called to cancel 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The\n * listener can be cancelled by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The\n * listener can be cancelled by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The\n * listener can be cancelled by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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` is available.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @returns An unsubscribe function that can be called to cancel 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The\n * listener can be cancelled by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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` is available.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @returns An unsubscribe function that can be called to cancel 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 // onSnapshot for Query or Document.\n reference = getModularInstance(reference);\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 }\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 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/**\n * Attaches a listener for `QuerySnapshot` events based on data generated by invoking\n * {@link QuerySnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks or\n * pass a single observer 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 never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}.\n * @param onNext - A callback to be called every time a new `QuerySnapshot` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n onNext: (snapshot: QuerySnapshot) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void,\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking\n * {@link DocumentSnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or\n * pass a single observer 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 never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}.\n * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are\n * never ending.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n onNext: (snapshot: DocumentSnapshot) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void,\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events based on data generated by invoking\n * {@link QuerySnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or\n * pass a single observer 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 never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param onNext - A callback to be called every time a new `QuerySnapshot` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n options: SnapshotListenOptions,\n onNext: (snapshot: QuerySnapshot) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void,\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking\n * {@link DocumentSnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks\n * or pass a single observer object with `next` and `error` callbacks. The listener can be cancelled\n * by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n options: SnapshotListenOptions,\n onNext: (snapshot: DocumentSnapshot) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void,\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events based on QuerySnapshot data generated by invoking\n * {@link QuerySnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or\n * pass a single observer 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 never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n observer: {\n next: (snapshot: QuerySnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n },\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking\n * {@link DocumentSnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks\n * or pass a single observer object with `next` and `error` callbacks. The listener can be cancelled\n * by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n observer: {\n next: (snapshot: DocumentSnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n },\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events based on QuerySnapshot data generated by invoking\n * {@link QuerySnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks or\n * pass a single observer 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 never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n options: SnapshotListenOptions,\n observer: {\n next: (snapshot: QuerySnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n },\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events based on QuerySnapshot data generated by\n * invoking {@link DocumentSnapshot.toJSON} You may either pass individual `onNext` and `onError`\n * callbacks or pass a single observer object with `next` and `error` callbacks. The listener can be\n * cancelled by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n options: SnapshotListenOptions,\n observer: {\n next: (snapshot: DocumentSnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n },\n converter?: FirestoreDataConverter\n): Unsubscribe;\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(reference: Firestore, snapshotJson: object, ...args: unknown[]): Unsubscribe {\n const db = getModularInstance(reference);\n const json = normalizeSnapshotJsonFields(snapshotJson);\n if (json.error) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, json.error);\n }\n let curArg = 0;\n let options: SnapshotListenOptions | undefined = undefined;\n if (typeof args[curArg] === 'object' && !isPartialObserver(args[curArg])) {\n options = args[curArg++] as SnapshotListenOptions;\n }\n\n if (json.bundleSource === 'QuerySnapshot') {\n let observer: {\n next: (snapshot: QuerySnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n } | null = null;\n if (typeof args[curArg] === 'object' && isPartialObserver(args[curArg])) {\n const userObserver = args[curArg++] as PartialObserver<\n QuerySnapshot\n >;\n observer = {\n next: userObserver.next!,\n error: userObserver.error,\n complete: userObserver.complete\n };\n } else {\n observer = {\n next: args[curArg++] as (\n snapshot: QuerySnapshot\n ) => void,\n error: args[curArg++] as (error: FirestoreError) => void,\n complete: args[curArg++] as () => void\n };\n }\n return onSnapshotQuerySnapshotBundle(\n db,\n json,\n options,\n observer!,\n args[curArg] as FirestoreDataConverter\n );\n } else if (json.bundleSource === 'DocumentSnapshot') {\n let observer: {\n next: (snapshot: DocumentSnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n } | null = null;\n if (typeof args[curArg] === 'object' && isPartialObserver(args[curArg])) {\n const userObserver = args[curArg++] as PartialObserver<\n DocumentSnapshot\n >;\n observer = {\n next: userObserver.next!,\n error: userObserver.error,\n complete: userObserver.complete\n };\n } else {\n observer = {\n next: args[curArg++] as (\n snapshot: DocumentSnapshot\n ) => void,\n error: args[curArg++] as (error: FirestoreError) => void,\n complete: args[curArg++] as () => void\n };\n }\n return onSnapshotDocumentSnapshotBundle(\n db,\n json,\n options,\n observer!,\n args[curArg] as FirestoreDataConverter\n );\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `unsupported bundle source: ${json.bundleSource}`\n );\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/**\n * Ensures the data required to construct an {@link onSnapshot} listener exist in a `snapshotJson`\n * object that originates from {@link DocumentSnapshot.toJSON} or {@link Querysnapshot.toJSON}. The\n * data is normalized into a typed object.\n *\n * @param snapshotJson - The JSON object that the app provided to {@link onSnapshot}.\n * @returns A normalized object that contains all of the required bundle JSON fields. If\n * {@link snapshotJson} doesn't contain the required fields, or if the fields exist as empty\n * strings, then the {@link snapshotJson.error} field will be a non empty string.\n *\n * @internal\n */\nfunction normalizeSnapshotJsonFields(snapshotJson: object): {\n bundle: string;\n bundleName: string;\n bundleSource: string;\n error?: string;\n} {\n const result: {\n bundle: string;\n bundleName: string;\n bundleSource: string;\n error?: string;\n } = {\n bundle: '',\n bundleName: '',\n bundleSource: ''\n };\n const requiredKeys = ['bundle', 'bundleName', 'bundleSource'];\n for (const key of requiredKeys) {\n if (!(key in snapshotJson)) {\n result.error = `snapshotJson missing required field: ${key}`;\n break;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const value = (snapshotJson as any)[key];\n if (typeof value !== 'string') {\n result.error = `snapshotJson field '${key}' must be a string.`;\n break;\n }\n if (value.length === 0) {\n result.error = `snapshotJson field '${key}' cannot be an empty string.`;\n break;\n }\n if (key === 'bundle') {\n result.bundle = value;\n } else if (key === 'bundleName') {\n result.bundleName = value;\n } else if (key === 'bundleSource') {\n result.bundleSource = value;\n }\n }\n return result;\n}\n\n/**\n * Loads the bundle in a separate task and then invokes {@link onSnapshot} with a\n * {@link DocumentReference} for the document in the bundle.\n *\n * @param firestore - The {@link Firestore} instance for the {@link onSnapshot} operation request.\n * @param json - The JSON bundle to load, produced by {@link DocumentSnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot\n * listener.\n *\n * @internal\n */\nfunction onSnapshotDocumentSnapshotBundle<\n AppModelType,\n DbModelType extends DocumentData\n>(\n db: Firestore,\n json: { bundle: string; bundleName: string; bundleSource: string },\n options: SnapshotListenOptions | undefined,\n observer: {\n next: (snapshot: DocumentSnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n },\n converter?: FirestoreDataConverter\n): Unsubscribe {\n let unsubscribed: boolean = false;\n let internalUnsubscribe: Unsubscribe | undefined;\n const loadTask = loadBundle(db, json.bundle);\n loadTask\n .then(() => {\n if (!unsubscribed) {\n const docReference = new DocumentReference(\n db,\n converter ? converter : null,\n DocumentKey.fromPath(json.bundleName)\n );\n internalUnsubscribe = onSnapshot(\n docReference as DocumentReference,\n options ? options : {},\n observer\n );\n }\n })\n .catch(e => {\n if (observer.error) {\n observer.error(e);\n }\n return () => {};\n });\n return () => {\n if (unsubscribed) {\n return;\n }\n unsubscribed = true;\n if (internalUnsubscribe) {\n internalUnsubscribe();\n }\n };\n}\n\n/**\n * Loads the bundle in a separate task and then invokes {@link onSnapshot} with a\n * {@link Query} that represents the Query in the bundle.\n *\n * @param firestore - The {@link Firestore} instance for the {@link onSnapshot} operation request.\n * @param json - The JSON bundle to load, produced by {@link QuerySnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot\n * listener.\n *\n * @internal\n */\nfunction onSnapshotQuerySnapshotBundle<\n AppModelType,\n DbModelType extends DocumentData\n>(\n db: Firestore,\n json: { bundle: string; bundleName: string; bundleSource: string },\n options: SnapshotListenOptions | undefined,\n observer: {\n next: (snapshot: QuerySnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n },\n converter?: FirestoreDataConverter\n): Unsubscribe {\n let unsubscribed: boolean = false;\n let internalUnsubscribe: Unsubscribe | undefined;\n const loadTask = loadBundle(db, json.bundle);\n loadTask\n .then(() => namedQuery(db, json.bundleName))\n .then(query => {\n if (query && !unsubscribed) {\n const realQuery: Query = (query as Query)!;\n if (converter) {\n realQuery.withConverter(converter);\n }\n internalUnsubscribe = onSnapshot(\n query as Query,\n options ? options : {},\n observer\n );\n }\n })\n .catch(e => {\n if (observer.error) {\n observer.error(e);\n }\n return () => {};\n });\n return () => {\n if (unsubscribed) {\n return;\n }\n unsubscribed = true;\n if (internalUnsubscribe) {\n internalUnsubscribe();\n }\n };\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AggregateField, AggregateSpec, DocumentData, Query } from '../api';\nimport { AggregateImpl } from '../core/aggregate';\nimport { firestoreClientRunAggregateQuery } from '../core/firestore_client';\nimport { count } from '../lite-api/aggregate';\nimport { AggregateQuerySnapshot } from '../lite-api/aggregate_types';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport { ExpUserDataWriter } from './reference_impl';\n\nexport {\n aggregateQuerySnapshotEqual,\n count,\n sum,\n average,\n aggregateFieldEqual\n} from '../lite-api/aggregate';\n\n/**\n * Calculates the number of documents in the result set of the given query\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can\n * count the documents in cases where the result set is prohibitively large to\n * download entirely (thousands of documents).\n *\n * The result received from the server is presented, unaltered, without\n * considering any local state. That is, documents in the local cache are not\n * taken into consideration, neither are local modifications not yet\n * synchronized with the server. Previously-downloaded results, if any, are not\n * used. Every invocation of this function necessarily involves a round trip to\n * the server.\n *\n * @param query The query whose result set size is calculated.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */\nexport function getCountFromServer<\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query\n): Promise<\n AggregateQuerySnapshot<\n { count: AggregateField },\n AppModelType,\n DbModelType\n >\n> {\n const countQuerySpec: { count: AggregateField } = {\n count: count()\n };\n\n return getAggregateFromServer(query, countQuerySpec);\n}\n\n/**\n * Calculates the specified aggregations over the documents in the result\n * set of the given query without actually downloading the documents.\n *\n * Using this function to perform aggregations is efficient because only the\n * final aggregation values, not the documents' data, are downloaded. This\n * function can perform aggregations of the documents in cases where the result\n * set is prohibitively large to download entirely (thousands of documents).\n *\n * The result received from the server is presented, unaltered, without\n * considering any local state. That is, documents in the local cache are not\n * taken into consideration, neither are local modifications not yet\n * synchronized with the server. Previously-downloaded results, if any, are not\n * used. Every invocation of this function necessarily involves a round trip to\n * the server.\n *\n * @param query The query whose result set is aggregated over.\n * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates\n * to perform over the result set. The AggregateSpec specifies aliases for each\n * aggregate, which can be used to retrieve the aggregate result.\n * @example\n * ```typescript\n * const aggregateSnapshot = await getAggregateFromServer(query, {\n * countOfDocs: count(),\n * totalHours: sum('hours'),\n * averageScore: average('score')\n * });\n *\n * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;\n * const totalHours: number = aggregateSnapshot.data().totalHours;\n * const averageScore: number | null = aggregateSnapshot.data().averageScore;\n * ```\n */\nexport function getAggregateFromServer<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n aggregateSpec: AggregateSpecType\n): Promise<\n AggregateQuerySnapshot\n> {\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n\n const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n\n // Run the aggregation and convert the results\n return firestoreClientRunAggregateQuery(\n client,\n query._query,\n internalAggregates\n ).then(aggregateResult =>\n convertToAggregateQuerySnapshot(firestore, query, aggregateResult)\n );\n}\n\n/**\n * Converts the core aggregation result to an `AggregateQuerySnapshot`\n * that can be returned to the consumer.\n * @param query\n * @param aggregateResult Core aggregation result\n * @internal\n */\nfunction convertToAggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n query: Query,\n aggregateResult: ApiClientObjectMap\n): AggregateQuerySnapshot {\n const userDataWriter = new ExpUserDataWriter(firestore);\n const querySnapshot = new AggregateQuerySnapshot<\n AggregateSpecType,\n AppModelType,\n DbModelType\n >(query, userDataWriter, aggregateResult);\n return querySnapshot;\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 IndexedDbOfflineComponentProvider,\n LruGcMemoryOfflineComponentProvider,\n MemoryOfflineComponentProvider,\n MultiTabOfflineComponentProvider,\n OfflineComponentProviderFactory,\n OnlineComponentProviderFactory,\n OnlineComponentProvider\n} from '../core/component_provider';\n\n/* eslint @typescript-eslint/consistent-type-definitions: [\"error\", \"type\"] */\n/**\n * Provides an in-memory cache to the SDK. This is the default cache unless explicitly\n * configured otherwise.\n *\n * To use, create an instance using the factory function {@link memoryLocalCache()}, then\n * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using\n * the settings object.\n */\nexport type MemoryLocalCache = {\n kind: 'memory';\n /**\n * @internal\n */\n _onlineComponentProvider: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n};\n\nclass MemoryLocalCacheImpl implements MemoryLocalCache {\n kind: 'memory' = 'memory';\n /**\n * @internal\n */\n _onlineComponentProvider: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n\n constructor(settings?: MemoryCacheSettings) {\n this._onlineComponentProvider = OnlineComponentProvider.provider;\n if (settings?.garbageCollector) {\n this._offlineComponentProvider =\n settings.garbageCollector._offlineComponentProvider;\n } else {\n this._offlineComponentProvider = {\n build: () => new LruGcMemoryOfflineComponentProvider(undefined)\n };\n }\n }\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n}\n\n/**\n * Provides a persistent cache backed by IndexedDb to the SDK.\n *\n * To use, create an instance using the factory function {@link persistentLocalCache()}, then\n * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using\n * the settings object.\n */\nexport type PersistentLocalCache = {\n kind: 'persistent';\n /**\n * @internal\n */\n _onlineComponentProvider: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n};\n\nclass PersistentLocalCacheImpl implements PersistentLocalCache {\n kind: 'persistent' = 'persistent';\n /**\n * @internal\n */\n _onlineComponentProvider: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n\n constructor(settings: PersistentCacheSettings | undefined) {\n let tabManager: PersistentTabManager;\n if (settings?.tabManager) {\n settings.tabManager._initialize(settings);\n tabManager = settings.tabManager;\n } else {\n tabManager = persistentSingleTabManager(undefined);\n tabManager._initialize(settings);\n }\n this._onlineComponentProvider = tabManager._onlineComponentProvider!;\n this._offlineComponentProvider = tabManager._offlineComponentProvider!;\n }\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n}\n\n/**\n * Union type from all supported SDK cache layer.\n */\nexport type FirestoreLocalCache = MemoryLocalCache | PersistentLocalCache;\n\n/**\n * Union type from all support garbage collectors for memory local cache.\n */\nexport type MemoryGarbageCollector =\n | MemoryEagerGarbageCollector\n | MemoryLruGarbageCollector;\n\n/**\n * A garbage collector deletes documents whenever they are not part of any\n * active queries, and have no local mutations attached to them.\n *\n * This collector tries to ensure lowest memory footprints from the SDK,\n * at the risk of documents not being cached for offline queries or for\n * direct queries to the cache.\n *\n * Use factory function {@link memoryEagerGarbageCollector()} to create an\n * instance of this collector.\n */\nexport type MemoryEagerGarbageCollector = {\n kind: 'memoryEager';\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n};\n\n/**\n * A garbage collector deletes Least-Recently-Used documents in multiple\n * batches.\n *\n * This collector is configured with a target size, and will only perform\n * collection when the cached documents exceed the target size. It avoids\n * querying backend repeated for the same query or document, at the risk\n * of having a larger memory footprint.\n *\n * Use factory function {@link memoryLruGarbageCollector()} to create a\n * instance of this collector.\n */\nexport type MemoryLruGarbageCollector = {\n kind: 'memoryLru';\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n};\n\nclass MemoryEagerGarbageCollectorImpl implements MemoryEagerGarbageCollector {\n kind: 'memoryEager' = 'memoryEager';\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n\n constructor() {\n this._offlineComponentProvider = MemoryOfflineComponentProvider.provider;\n }\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n}\n\nclass MemoryLruGarbageCollectorImpl implements MemoryLruGarbageCollector {\n kind: 'memoryLru' = 'memoryLru';\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n\n constructor(cacheSize?: number) {\n this._offlineComponentProvider = {\n build: () => new LruGcMemoryOfflineComponentProvider(cacheSize)\n };\n }\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n}\n\n/**\n * Creates an instance of `MemoryEagerGarbageCollector`. This is also the\n * default garbage collector unless it is explicitly specified otherwise.\n */\nexport function memoryEagerGarbageCollector(): MemoryEagerGarbageCollector {\n return new MemoryEagerGarbageCollectorImpl();\n}\n\n/**\n * Creates an instance of `MemoryLruGarbageCollector`.\n *\n * A target size can be specified as part of the setting parameter. The\n * collector will start deleting documents once the cache size exceeds\n * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes).\n */\nexport function memoryLruGarbageCollector(settings?: {\n cacheSizeBytes?: number;\n}): MemoryLruGarbageCollector {\n return new MemoryLruGarbageCollectorImpl(settings?.cacheSizeBytes);\n}\n\n/**\n * An settings object to configure an `MemoryLocalCache` instance.\n */\nexport type MemoryCacheSettings = {\n /**\n * The garbage collector to use, for the memory cache layer.\n * A `MemoryEagerGarbageCollector` is used when this is undefined.\n */\n garbageCollector?: MemoryGarbageCollector;\n};\n\n/**\n * Creates an instance of `MemoryLocalCache`. The instance can be set to\n * `FirestoreSettings.cache` to tell the SDK which cache layer to use.\n */\nexport function memoryLocalCache(\n settings?: MemoryCacheSettings\n): MemoryLocalCache {\n return new MemoryLocalCacheImpl(settings);\n}\n\n/**\n * An settings object to configure an `PersistentLocalCache` instance.\n *\n * Persistent cache cannot be used in a Node.js environment.\n */\nexport type PersistentCacheSettings = {\n /**\n * An approximate cache size threshold for the on-disk data. If the cache\n * grows beyond this size, Firestore will start removing data that hasn't been\n * recently used. The SDK does not guarantee that the cache will stay below\n * that size, only that if the cache exceeds the given size, cleanup will be\n * attempted.\n *\n * The default value is 40 MB. The threshold must be set to at least 1 MB, and\n * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection.\n */\n cacheSizeBytes?: number;\n\n /**\n * Specifies how multiple tabs/windows will be managed by the SDK.\n */\n tabManager?: PersistentTabManager;\n};\n\n/**\n * Creates an instance of `PersistentLocalCache`. The instance can be set to\n * `FirestoreSettings.cache` to tell the SDK which cache layer to use.\n *\n * Persistent cache cannot be used in a Node.js environment.\n */\nexport function persistentLocalCache(\n settings?: PersistentCacheSettings\n): PersistentLocalCache {\n return new PersistentLocalCacheImpl(settings);\n}\n\n/**\n * A tab manager supporting only one tab, no synchronization will be\n * performed across tabs.\n */\nexport type PersistentSingleTabManager = {\n kind: 'persistentSingleTab';\n /**\n * @internal\n */\n _initialize: (\n settings: Omit | undefined\n ) => void;\n /**\n * @internal\n */\n _onlineComponentProvider?: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider?: OfflineComponentProviderFactory;\n};\n\nclass SingleTabManagerImpl implements PersistentSingleTabManager {\n kind: 'persistentSingleTab' = 'persistentSingleTab';\n\n /**\n * @internal\n */\n _onlineComponentProvider?: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider?: OfflineComponentProviderFactory;\n\n constructor(private forceOwnership?: boolean) {}\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n\n /**\n * @internal\n */\n _initialize(\n settings: Omit | undefined\n ): void {\n this._onlineComponentProvider = OnlineComponentProvider.provider;\n this._offlineComponentProvider = {\n build: (onlineComponents: OnlineComponentProvider) =>\n new IndexedDbOfflineComponentProvider(\n onlineComponents,\n settings?.cacheSizeBytes,\n this.forceOwnership\n )\n };\n }\n}\n\n/**\n * A tab manager supporting multiple tabs. SDK will synchronize queries and\n * mutations done across all tabs using the SDK.\n */\nexport type PersistentMultipleTabManager = {\n kind: 'PersistentMultipleTab';\n /**\n * @internal\n */\n _initialize: (settings: Omit) => void;\n /**\n * @internal\n */\n _onlineComponentProvider?: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n\n _offlineComponentProvider?: OfflineComponentProviderFactory;\n};\n\nclass MultiTabManagerImpl implements PersistentMultipleTabManager {\n kind: 'PersistentMultipleTab' = 'PersistentMultipleTab';\n\n /**\n * @internal\n */\n _onlineComponentProvider?: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider?: OfflineComponentProviderFactory;\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n\n /**\n * @internal\n */\n _initialize(\n settings: Omit | undefined\n ): void {\n this._onlineComponentProvider = OnlineComponentProvider.provider;\n this._offlineComponentProvider = {\n build: (onlineComponents: OnlineComponentProvider) =>\n new MultiTabOfflineComponentProvider(\n onlineComponents,\n settings?.cacheSizeBytes\n )\n };\n }\n}\n\n/**\n * A union of all available tab managers.\n */\nexport type PersistentTabManager =\n | PersistentSingleTabManager\n | PersistentMultipleTabManager;\n\n/**\n * Type to configure an `PersistentSingleTabManager` instance.\n */\nexport type PersistentSingleTabManagerSettings = {\n /**\n * Whether to force-enable persistent (IndexedDB) cache for the client. This\n * cannot be used with multi-tab synchronization and is primarily intended for\n * use with Web Workers. Setting this to `true` will enable IndexedDB, but cause\n * other tabs using IndexedDB cache to fail.\n */\n forceOwnership?: boolean;\n};\n/**\n * Creates an instance of `PersistentSingleTabManager`.\n *\n * @param settings Configures the created tab manager.\n */\nexport function persistentSingleTabManager(\n settings: PersistentSingleTabManagerSettings | undefined\n): PersistentSingleTabManager {\n return new SingleTabManagerImpl(settings?.forceOwnership);\n}\n\n/**\n * Creates an instance of `PersistentMultipleTabManager`.\n */\nexport function persistentMultipleTabManager(): PersistentMultipleTabManager {\n return new MultiTabManagerImpl();\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\n\nexport const DEFAULT_TRANSACTION_OPTIONS: TransactionOptions = {\n maxAttempts: 5\n};\n\n/**\n * Options to customize transaction behavior.\n */\nexport declare interface TransactionOptions {\n /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */\n readonly maxAttempts: number;\n}\n\nexport function validateTransactionOptions(options: TransactionOptions): void {\n if (options.maxAttempts < 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Max attempts must be at least 1'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Compat, getModularInstance } from '@firebase/util';\n\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { invokeCommitRpc } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport { applyFirestoreDataConverter } from './reference_impl';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\n\n/**\n * A write batch, used to perform multiple writes as a single atomic unit.\n *\n * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It\n * provides methods for adding writes to the write batch. None of the writes\n * will be committed (or visible locally) until {@link WriteBatch.commit} is\n * called.\n */\nexport class WriteBatch {\n // This is the lite version of the WriteBatch API used in the legacy SDK. The\n // class is a close copy but takes different input types.\n\n private readonly _dataReader: UserDataReader;\n private _mutations = [] as Mutation[];\n private _committed = false;\n\n /** @hideconstructor */\n constructor(\n private readonly _firestore: Firestore,\n private readonly _commitHandler: (m: Mutation[]) => Promise\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): WriteBatch;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): WriteBatch;\n set(\n documentRef: DocumentReference,\n data: WithFieldValue | PartialWithFieldValue,\n options?: SetOptions\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n data,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'WriteBatch.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._mutations.push(parsed.toMutation(ref._key, Precondition.none()));\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): WriteBatch;\n /**\n * Updates fields in the document referred to by this {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be update by providing dot-separated field path strings\n * or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._mutations.push(\n parsed.toMutation(ref._key, Precondition.exists(true))\n );\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n this._mutations = this._mutations.concat(\n new DeleteMutation(ref._key, Precondition.none())\n );\n return this;\n }\n\n /**\n * Commits all of the writes in this write batch as a single atomic unit.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `Promise` resolved once all of the writes in the batch have been\n * successfully written to the backend as an atomic unit (note that it won't\n * resolve while you're offline).\n */\n commit(): Promise {\n this._verifyNotCommitted();\n this._committed = true;\n if (this._mutations.length > 0) {\n return this._commitHandler(this._mutations);\n }\n\n return Promise.resolve();\n }\n\n private _verifyNotCommitted(): void {\n if (this._committed) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A write batch can no longer be used after commit() ' +\n 'has been called.'\n );\n }\n }\n}\n\nexport function validateReference<\n AppModelType,\n DbModelType extends DocumentData\n>(\n documentRef:\n | DocumentReference\n | Compat>,\n firestore: Firestore\n): DocumentReference {\n documentRef = getModularInstance(documentRef);\n\n if (documentRef.firestore !== firestore) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Provided document reference is from a different Firestore instance.'\n );\n } else {\n return documentRef as DocumentReference;\n }\n}\n\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single WriteBatch\n * is 500.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `WriteBatch` that can be used to atomically execute multiple\n * writes.\n */\nexport function writeBatch(firestore: Firestore): WriteBatch {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n return new WriteBatch(firestore, writes =>\n invokeCommitRpc(datastore, writes)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport {\n DEFAULT_TRANSACTION_OPTIONS,\n TransactionOptions as TransactionOptionsInternal,\n validateTransactionOptions\n} from '../core/transaction_options';\nimport { TransactionRunner } from '../core/transaction_runner';\nimport { fail } from '../util/assert';\nimport { newAsyncQueue } from '../util/async_queue_impl';\nimport { cast } from '../util/input_validation';\nimport { Deferred } from '../util/promise';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n applyFirestoreDataConverter,\n LiteUserDataWriter\n} from './reference_impl';\nimport { DocumentSnapshot } from './snapshot';\nimport { TransactionOptions } from './transaction_options';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\nimport { validateReference } from './write_batch';\n\n// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the\n// legacy SDK.\n\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nexport class Transaction {\n // This is the tree-shakeable version of the Transaction class used in the\n // legacy SDK. The class is a close copy but takes different input and output\n // types. The firestore-exp SDK further extends this class to return its API\n // type.\n\n private readonly _dataReader: UserDataReader;\n\n /** @hideconstructor */\n constructor(\n protected readonly _firestore: Firestore,\n private readonly _transaction: InternalTransaction\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */\n get(\n documentRef: DocumentReference\n ): Promise> {\n const ref = validateReference(documentRef, this._firestore);\n const userDataWriter = new LiteUserDataWriter(this._firestore);\n return this._transaction.lookup([ref._key]).then(docs => {\n if (!docs || docs.length !== 1) {\n return fail(0x5de9, 'Mismatch in docs returned from document lookup.');\n }\n const doc = docs[0];\n if (doc.isFoundDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n doc.key,\n doc,\n ref.converter\n );\n } else if (doc.isNoDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n ref._key,\n null,\n ref.converter\n );\n } else {\n throw fail(\n 0x4801,\n 'BatchGetDocumentsRequest returned unexpected document',\n {\n doc\n }\n );\n }\n });\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): this;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): this;\n set(\n documentRef: DocumentReference,\n value: PartialWithFieldValue,\n options?: SetOptions\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n value,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'Transaction.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._transaction.set(ref._key, parsed);\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): this;\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key/value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._transaction.update(ref._key, parsed);\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n this._transaction.delete(ref._key);\n return this;\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */\nexport function runTransaction(\n firestore: Firestore,\n updateFunction: (transaction: Transaction) => Promise,\n options?: TransactionOptions\n): Promise {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n const optionsWithDefaults: TransactionOptionsInternal = {\n ...DEFAULT_TRANSACTION_OPTIONS,\n ...options\n };\n validateTransactionOptions(optionsWithDefaults);\n const deferred = new Deferred();\n new TransactionRunner(\n newAsyncQueue(),\n datastore,\n optionsWithDefaults,\n internalTransaction =>\n updateFunction(new Transaction(firestore, internalTransaction)),\n deferred\n ).run();\n return deferred.promise;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { firestoreClientTransaction } from '../core/firestore_client';\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport {\n TransactionOptions as TransactionOptionsInternal,\n DEFAULT_TRANSACTION_OPTIONS,\n validateTransactionOptions\n} from '../core/transaction_options';\nimport { DocumentData, DocumentReference } from '../lite-api/reference';\nimport { Transaction as LiteTransaction } from '../lite-api/transaction';\nimport { validateReference } from '../lite-api/write_batch';\nimport { cast } from '../util/input_validation';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport { ExpUserDataWriter } from './reference_impl';\nimport { DocumentSnapshot, SnapshotMetadata } from './snapshot';\nimport { TransactionOptions } from './transaction_options';\n\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nexport class Transaction extends LiteTransaction {\n // This class implements the same logic as the Transaction API in the Lite SDK\n // but is subclassed in order to return its own DocumentSnapshot types.\n\n /** @hideconstructor */\n constructor(\n protected readonly _firestore: Firestore,\n _transaction: InternalTransaction\n ) {\n super(_firestore, _transaction);\n }\n\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */\n get(\n documentRef: DocumentReference\n ): Promise> {\n const ref = validateReference(documentRef, this._firestore);\n const userDataWriter = new ExpUserDataWriter(this._firestore);\n return super\n .get(documentRef)\n .then(\n liteDocumentSnapshot =>\n new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n ref._key,\n liteDocumentSnapshot._document,\n new SnapshotMetadata(\n /* hasPendingWrites= */ false,\n /* fromCache= */ false\n ),\n ref.converter\n )\n );\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */\nexport function runTransaction(\n firestore: Firestore,\n updateFunction: (transaction: Transaction) => Promise,\n options?: TransactionOptions\n): Promise {\n firestore = cast(firestore, Firestore);\n const optionsWithDefaults: TransactionOptionsInternal = {\n ...DEFAULT_TRANSACTION_OPTIONS,\n ...options\n };\n validateTransactionOptions(optionsWithDefaults);\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientTransaction(\n client,\n internalTransaction =>\n updateFunction(new Transaction(firestore, internalTransaction)),\n optionsWithDefaults\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldValue } from './field_value';\nimport {\n ArrayRemoveFieldValueImpl,\n ArrayUnionFieldValueImpl,\n DeleteFieldValueImpl,\n NumericIncrementFieldValueImpl,\n ServerTimestampFieldValueImpl\n} from './user_data_reader';\nimport { VectorValue } from './vector_value';\n\n/**\n * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or\n * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.\n */\nexport function deleteField(): FieldValue {\n return new DeleteFieldValueImpl('deleteField');\n}\n\n/**\n * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to\n * include a server-generated timestamp in the written data.\n */\nexport function serverTimestamp(): FieldValue {\n return new ServerTimestampFieldValueImpl('serverTimestamp');\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array\n * value that already exists on the server. Each specified element that doesn't\n * already exist in the array will be added to the end. If the field being\n * modified is not already an array it will be overwritten with an array\n * containing exactly the specified elements.\n *\n * @param elements - The elements to union into the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`.\n */\nexport function arrayUnion(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayUnionFieldValueImpl('arrayUnion', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link (setDoc:1)} or {@link\n * updateDoc:1} that tells the server to remove the given elements from any\n * array value that already exists on the server. All instances of each element\n * specified will be removed from the array. If the field being modified is not\n * already an array it will be overwritten with an empty array.\n *\n * @param elements - The elements to remove from the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function arrayRemove(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayRemoveFieldValueImpl('arrayRemove', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by\n * the given value.\n *\n * If either the operand or the current field value uses floating point\n * precision, all arithmetic follows IEEE 754 semantics. If both values are\n * integers, values outside of JavaScript's safe number range\n * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to\n * precision loss. Furthermore, once processed by the Firestore backend, all\n * integer operations are capped between -2^63 and 2^63-1.\n *\n * If the current field value is not of type `number`, or if the field does not\n * yet exist, the transformation sets the field to the given value.\n *\n * @param n - The value to increment by.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function increment(n: number): FieldValue {\n return new NumericIncrementFieldValueImpl('increment', n);\n}\n\n/**\n * Creates a new `VectorValue` constructed with a copy of the given array of numbers.\n *\n * @param values - Create a `VectorValue` instance with a copy of this array of numbers.\n *\n * @returns A new `VectorValue` constructed with a copy of the given array of numbers.\n */\nexport function vector(values?: number[]): VectorValue {\n return new VectorValue(values);\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 { WriteBatch } from '../lite-api/write_batch';\nimport { cast } from '../util/input_validation';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport { executeWrite } from './reference_impl';\n\nexport { WriteBatch };\n\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch}\n * is 500.\n *\n * Unlike transactions, write batches are persisted offline and therefore are\n * preferable when you don't need to condition your writes on read data.\n *\n * @returns A {@link WriteBatch} that can be used to atomically execute multiple\n * writes.\n */\nexport function writeBatch(firestore: Firestore): WriteBatch {\n firestore = cast(firestore, Firestore);\n ensureFirestoreConfigured(firestore);\n return new WriteBatch(firestore, mutations =>\n executeWrite(firestore, mutations)\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 { firestoreClientSetIndexConfiguration } from '../core/firestore_client';\nimport { fieldPathFromDotSeparatedString } from '../lite-api/user_data_reader';\nimport {\n FieldIndex,\n IndexKind,\n IndexSegment,\n IndexState\n} from '../model/field_index';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\nimport { logWarn } from '../util/log';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\n\nexport {\n connectFirestoreEmulator,\n EmulatorMockTokenOptions\n} from '../lite-api/database';\n\n/**\n * A single field element in an index configuration.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport interface IndexField {\n /** The field path to index. */\n readonly fieldPath: string;\n /**\n * What type of array index to create. Set to `CONTAINS` for `array-contains`\n * and `array-contains-any` indexes.\n *\n * Only one of `arrayConfig` or `order` should be set;\n */\n readonly arrayConfig?: 'CONTAINS';\n /**\n * What type of array index to create. Set to `ASCENDING` or 'DESCENDING` for\n * `==`, `!=`, `<=`, `<=`, `in` and `not-in` filters.\n *\n * Only one of `arrayConfig` or `order` should be set.\n */\n readonly order?: 'ASCENDING' | 'DESCENDING';\n\n [key: string]: unknown;\n}\n\n/**\n * The SDK definition of a Firestore index.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport interface Index {\n /** The ID of the collection to index. */\n readonly collectionGroup: string;\n /** A list of fields to index. */\n readonly fields?: IndexField[];\n\n [key: string]: unknown;\n}\n\n/**\n * A list of Firestore indexes to speed up local query execution.\n *\n * See {@link https://firebase.google.com/docs/reference/firestore/indexes/#json_format | JSON Format}\n * for a description of the format of the index definition.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport interface IndexConfiguration {\n /** A list of all Firestore indexes. */\n readonly indexes?: Index[];\n\n [key: string]: unknown;\n}\n\n/**\n * Configures indexing for local query execution. Any previous index\n * configuration is overridden. The `Promise` resolves once the index\n * configuration has been persisted.\n *\n * The index entries themselves are created asynchronously. You can continue to\n * use queries that require indexing even if the indices are not yet available.\n * Query execution will automatically start using the index once the index\n * entries have been written.\n *\n * Indexes are only supported with IndexedDb persistence. If IndexedDb is not\n * enabled, any index configuration is ignored.\n *\n * @param firestore - The {@link Firestore} instance to configure indexes for.\n * @param configuration -The index definition.\n * @throws FirestoreError if the JSON format is invalid.\n * @returns A `Promise` that resolves once all indices are successfully\n * configured.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport function setIndexConfiguration(\n firestore: Firestore,\n configuration: IndexConfiguration\n): Promise;\n\n/**\n * Configures indexing for local query execution. Any previous index\n * configuration is overridden. The `Promise` resolves once the index\n * configuration has been persisted.\n *\n * The index entries themselves are created asynchronously. You can continue to\n * use queries that require indexing even if the indices are not yet available.\n * Query execution will automatically start using the index once the index\n * entries have been written.\n *\n * Indexes are only supported with IndexedDb persistence. Invoke either\n * `enableIndexedDbPersistence()` or `enableMultiTabIndexedDbPersistence()`\n * before setting an index configuration. If IndexedDb is not enabled, any\n * index configuration is ignored.\n *\n * The method accepts the JSON format exported by the Firebase CLI (`firebase\n * firestore:indexes`). If the JSON format is invalid, this method throws an\n * error.\n *\n * @param firestore - The {@link Firestore} instance to configure indexes for.\n * @param json -The JSON format exported by the Firebase CLI.\n * @throws FirestoreError if the JSON format is invalid.\n * @returns A `Promise` that resolves once all indices are successfully\n * configured.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport function setIndexConfiguration(\n firestore: Firestore,\n json: string\n): Promise;\n\nexport function setIndexConfiguration(\n firestore: Firestore,\n jsonOrConfiguration: string | IndexConfiguration\n): Promise {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n if (\n !client._uninitializedComponentsProvider ||\n client._uninitializedComponentsProvider._offline.kind === 'memory'\n ) {\n // PORTING NOTE: We don't return an error if the user has not enabled\n // persistence since `enableIndexeddbPersistence()` can fail on the Web.\n logWarn('Cannot enable indexes when persistence is disabled');\n return Promise.resolve();\n }\n const parsedIndexes = parseIndexes(jsonOrConfiguration);\n return firestoreClientSetIndexConfiguration(client, parsedIndexes);\n}\n\nexport function parseIndexes(\n jsonOrConfiguration: string | IndexConfiguration\n): FieldIndex[] {\n const indexConfiguration =\n typeof jsonOrConfiguration === 'string'\n ? (tryParseJson(jsonOrConfiguration) as IndexConfiguration)\n : jsonOrConfiguration;\n const parsedIndexes: FieldIndex[] = [];\n\n if (Array.isArray(indexConfiguration.indexes)) {\n for (const index of indexConfiguration.indexes) {\n const collectionGroup = tryGetString(index, 'collectionGroup');\n\n const segments: IndexSegment[] = [];\n if (Array.isArray(index.fields)) {\n for (const field of index.fields) {\n const fieldPathString = tryGetString(field, 'fieldPath');\n const fieldPath = fieldPathFromDotSeparatedString(\n 'setIndexConfiguration',\n fieldPathString\n );\n\n if (field.arrayConfig === 'CONTAINS') {\n segments.push(new IndexSegment(fieldPath, IndexKind.CONTAINS));\n } else if (field.order === 'ASCENDING') {\n segments.push(new IndexSegment(fieldPath, IndexKind.ASCENDING));\n } else if (field.order === 'DESCENDING') {\n segments.push(new IndexSegment(fieldPath, IndexKind.DESCENDING));\n }\n }\n }\n\n parsedIndexes.push(\n new FieldIndex(\n FieldIndex.UNKNOWN_ID,\n collectionGroup,\n segments,\n IndexState.empty()\n )\n );\n }\n }\n return parsedIndexes;\n}\n\nfunction tryParseJson(json: string): Record {\n try {\n return JSON.parse(json);\n } catch (e) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Failed to parse JSON: ' + (e as Error)?.message\n );\n }\n}\n\nfunction tryGetString(data: Record, property: string): string {\n if (typeof data[property] !== 'string') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Missing string value for: ' + property\n );\n }\n return data[property] as string;\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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ensureFirestoreConfigured, Firestore } from '../api/database';\nimport { AggregateImpl } from '../core/aggregate';\nimport { queryToAggregateTarget, queryToTarget } from '../core/query';\nimport { AggregateSpec } from '../lite-api/aggregate_types';\nimport { Query } from '../lite-api/reference';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport { toQueryTarget, toRunAggregationQueryRequest } from './serializer';\n\n/**\n * @internal\n * @private\n *\n * This function is for internal use only.\n *\n * Returns the `QueryTarget` representation of the given query. Returns `null`\n * if the Firestore client associated with the given query has not been\n * initialized or has been terminated.\n *\n * @param query - The Query to convert to proto representation.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function _internalQueryToProtoQueryTarget(query: Query): any {\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const serializer = client._onlineComponents?.datastore.serializer;\n if (serializer === undefined) {\n return null;\n }\n return toQueryTarget(serializer!, queryToTarget(query._query)).queryTarget;\n}\n\n/**\n * @internal\n * @private\n *\n * This function is for internal use only.\n *\n * Returns `RunAggregationQueryRequest` which contains the proto representation\n * of the given aggregation query request. Returns null if the Firestore client\n * associated with the given query has not been initialized or has been\n * terminated.\n *\n * @param query - The Query to convert to proto representation.\n * @param aggregateSpec - The set of aggregations and their aliases.\n */\nexport function _internalAggregationQueryToProtoRunAggregationQueryRequest<\n AggregateSpecType extends AggregateSpec\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n>(query: Query, aggregateSpec: AggregateSpecType): any {\n const aggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const serializer = client._onlineComponents?.datastore.serializer;\n if (serializer === undefined) {\n return null;\n }\n\n return toRunAggregationQueryRequest(\n serializer!,\n queryToAggregateTarget(query._query),\n aggregates,\n /* skipAliasing= */ true\n ).request;\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 { Unsubscribe } from '../api/reference_impl';\n\nimport {\n setTestingHooksSpi,\n ExistenceFilterMismatchInfo,\n TestingHooksSpi\n} from './testing_hooks_spi';\n\n/**\n * Testing hooks for use by Firestore's integration test suite to reach into the\n * SDK internals to validate logic and behavior that is not visible from the\n * public API surface.\n *\n * @internal\n */\nexport class TestingHooks {\n private constructor() {\n throw new Error('instances of this class should not be created');\n }\n\n /**\n * Registers a callback to be notified when an existence filter mismatch\n * occurs in the Watch listen stream.\n *\n * The relative order in which callbacks are notified is unspecified; do not\n * rely on any particular ordering. If a given callback is registered multiple\n * times then it will be notified multiple times, once per registration.\n *\n * @param callback the callback to invoke upon existence filter mismatch.\n *\n * @return a function that, when called, unregisters the given callback; only\n * the first invocation of the returned function does anything; all subsequent\n * invocations do nothing.\n */\n static onExistenceFilterMismatch(\n callback: ExistenceFilterMismatchCallback\n ): Unsubscribe {\n return TestingHooksSpiImpl.instance.onExistenceFilterMismatch(callback);\n }\n}\n\n/**\n * The signature of callbacks registered with\n * `TestingUtils.onExistenceFilterMismatch()`.\n *\n * The return value, if any, is ignored.\n *\n * @internal\n */\nexport type ExistenceFilterMismatchCallback = (\n info: ExistenceFilterMismatchInfo\n) => unknown;\n\n/**\n * The implementation of `TestingHooksSpi`.\n */\nclass TestingHooksSpiImpl implements TestingHooksSpi {\n private readonly existenceFilterMismatchCallbacksById = new Map<\n Symbol,\n ExistenceFilterMismatchCallback\n >();\n\n private constructor() {}\n\n static get instance(): TestingHooksSpiImpl {\n if (!testingHooksSpiImplInstance) {\n testingHooksSpiImplInstance = new TestingHooksSpiImpl();\n setTestingHooksSpi(testingHooksSpiImplInstance);\n }\n return testingHooksSpiImplInstance;\n }\n\n notifyOnExistenceFilterMismatch(info: ExistenceFilterMismatchInfo): void {\n this.existenceFilterMismatchCallbacksById.forEach(callback =>\n callback(info)\n );\n }\n\n onExistenceFilterMismatch(\n callback: ExistenceFilterMismatchCallback\n ): Unsubscribe {\n const id = Symbol();\n const callbacks = this.existenceFilterMismatchCallbacksById;\n callbacks.set(id, callback);\n return () => callbacks.delete(id);\n }\n}\n\nlet testingHooksSpiImplInstance: TestingHooksSpiImpl | null = null;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 app,\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 esm, cjs, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\n}\n","/**\n * @license\n * Copyright 2021 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { registerFirestore } from './register';\n\nregisterFirestore('rn', /* useFetchStreams= */ false);\n\nexport * from './api';\n"],"names":["User","constructor","uid","this","isAuthenticated","toKey","isEqual","otherUser","UNAUTHENTICATED","GOOGLE_CREDENTIALS","FIRST_PARTY","MOCK_USER","SDK_VERSION","__PRIVATE_logClient","Logger","__PRIVATE_getLogLevel","logLevel","setLogLevel","__PRIVATE_logDebug","msg","obj","LogLevel","DEBUG","args","map","__PRIVATE_argToString","debug","__PRIVATE_logError","ERROR","error","__PRIVATE_logWarn","WARN","warn","__PRIVATE_formatJSON","value","JSON","stringify","e","fail","id","__PRIVATE_messageOrContext","context","message","__PRIVATE__fail","__PRIVATE_failure","toString","undefined","Error","__PRIVATE_hardAssert","assertion","__PRIVATE_debugAssert","__PRIVATE_debugCast","Code","OK","CANCELLED","UNKNOWN","INVALID_ARGUMENT","DEADLINE_EXCEEDED","NOT_FOUND","ALREADY_EXISTS","PERMISSION_DENIED","RESOURCE_EXHAUSTED","FAILED_PRECONDITION","ABORTED","OUT_OF_RANGE","UNIMPLEMENTED","INTERNAL","UNAVAILABLE","DATA_LOSS","FirestoreError","FirebaseError","code","super","name","__PRIVATE_Deferred","promise","Promise","resolve","reject","__PRIVATE_OAuthToken","user","type","headers","Map","set","__PRIVATE_EmptyAuthCredentialsProvider","getToken","invalidateToken","start","asyncQueue","changeListener","enqueueRetryable","shutdown","__PRIVATE_EmulatorAuthCredentialsProvider","token","__PRIVATE_FirebaseAuthCredentialsProvider","__PRIVATE_authProvider","currentUser","__PRIVATE_tokenCounter","forceRefresh","auth","__PRIVATE_tokenListener","__PRIVATE_lastTokenId","__PRIVATE_guardedChangeListener","__PRIVATE_nextToken","__PRIVATE_getUser","__PRIVATE_awaitNextToken","__PRIVATE_currentTokenAttempt","async","__PRIVATE_registerAuth","addAuthTokenListener","onInit","setTimeout","getImmediate","optional","__PRIVATE_initialTokenCounter","then","__PRIVATE_tokenData","accessToken","removeAuthTokenListener","__PRIVATE_currentUid","getUid","__PRIVATE_FirstPartyToken","__PRIVATE_sessionIndex","__PRIVATE_iamToken","__PRIVATE_authTokenFactory","__PRIVATE_getAuthToken","__PRIVATE__headers","__PRIVATE_authHeaderTokenValue","__PRIVATE_FirstPartyAuthCredentialsProvider","AppCheckToken","length","__PRIVATE_FirebaseAppCheckTokenProvider","app","__PRIVATE_appCheckProvider","appCheck","__PRIVATE_latestAppCheckToken","__PRIVATE_serverAppAppCheckToken","_isFirebaseServerApp","settings","appCheckToken","onTokenChanged","tokenResult","__PRIVATE_tokenUpdated","__PRIVATE_registerAppCheck","addTokenListener","removeTokenListener","__PRIVATE_EmptyAppCheckTokenProvider","__PRIVATE_randomBytes","__PRIVATE_nBytes","crypto","self","bytes","Uint8Array","getRandomValues","__PRIVATE_i","Math","floor","random","__PRIVATE_AutoId","newId","__PRIVATE_chars","__PRIVATE_maxMultiple","__PRIVATE_autoId","charAt","__PRIVATE_primitiveComparator","left","right","__PRIVATE_compareUtf8Strings","min","__PRIVATE_leftChar","__PRIVATE_rightChar","__PRIVATE_isSurrogate","__PRIVATE_MIN_SURROGATE","__PRIVATE_MAX_SURROGATE","s","c","charCodeAt","__PRIVATE_arrayEquals","comparator","every","index","__PRIVATE_immediateSuccessor","__PRIVATE_DOCUMENT_KEY_NAME","BasePath","segments","offset","range","len","other","child","nameOrPath","slice","limit","forEach","segment","push","construct","popFirst","size","popLast","firstSegment","lastSegment","get","isEmpty","isPrefixOf","isImmediateParentOf","potentialChild","fn","end","toArray","p1","p2","comparison","compareSegments","__PRIVATE_lhs","__PRIVATE_rhs","__PRIVATE_isLhsNumeric","isNumericId","__PRIVATE_isRhsNumeric","extractNumericId","compare","startsWith","endsWith","Integer","fromString","substring","ResourcePath","canonicalString","join","toUriEncodedString","encodeURIComponent","pathComponents","path","indexOf","split","filter","emptyPath","__PRIVATE_identifierRegExp","FieldPath","isValidIdentifier","test","str","replace","isKeyField","keyField","fromServerFormat","current","__PRIVATE_addCurrentSegment","__PRIVATE_inBackticks","next","DocumentKey","fromPath","fromName","empty","collectionGroup","hasCollectionId","collectionId","getCollectionGroup","getCollectionPath","k1","k2","isDocumentKey","fromSegments","__PRIVATE_validateNonEmptyArgument","__PRIVATE_functionName","__PRIVATE_argumentName","__PRIVATE_argument","__PRIVATE_validateIsNotUsedTogether","optionName1","argument1","optionName2","argument2","__PRIVATE_validateDocumentPath","__PRIVATE_validateCollectionPath","__PRIVATE_isPlainObject","input","Object","getPrototypeOf","prototype","__PRIVATE_valueDescription","Array","__PRIVATE_customObjectName","__PRIVATE_tryGetCustomObjectType","__PRIVATE_cast","_delegate","description","__PRIVATE_validatePositiveNumber","n","property","typeString","__PRIVATE_optionalValue","result","__PRIVATE_validateJSON","json","__PRIVATE_schema","key","__PRIVATE_fieldValue","__PRIVATE_MIN_SECONDS","__PRIVATE_MS_TO_NANOS","Timestamp","now","fromMillis","Date","fromDate","date","getTime","milliseconds","seconds","nanos","nanoseconds","toDate","toMillis","_compareTo","toJSON","_jsonSchemaVersion","fromJSON","_jsonSchema","valueOf","__PRIVATE_adjustedSeconds","String","padStart","SnapshotVersion","fromTimestamp","max","timestamp","compareTo","toMicroseconds","toTimestamp","__PRIVATE_INITIAL_LARGEST_BATCH_ID","FieldIndex","indexId","fields","indexState","__PRIVATE_fieldIndexGetArraySegment","__PRIVATE_fieldIndex","find","kind","__PRIVATE_fieldIndexGetDirectionalSegments","__PRIVATE_fieldIndexSemanticComparator","cmp","__PRIVATE_indexSegmentComparator","UNKNOWN_ID","IndexSegment","fieldPath","IndexState","sequenceNumber","IndexOffset","__PRIVATE_newIndexOffsetSuccessorFromReadTime","readTime","largestBatchId","__PRIVATE_successorSeconds","__PRIVATE_successorNanos","__PRIVATE_successor","__PRIVATE_newIndexOffsetFromDocument","document","documentKey","__PRIVATE_indexOffsetComparator","__PRIVATE_PRIMARY_LEASE_LOST_ERROR_MSG","PersistenceTransaction","onCommittedListeners","addOnCommittedListener","listener","raiseOnCommittedEvent","__PRIVATE_ignoreIfPrimaryLeaseLoss","err","PersistencePromise","callback","nextCallback","catchCallback","isDone","callbackAttached","nextFn","catchFn","wrapFailure","wrapSuccess","toPromise","wrapUserFunction","waitFor","all","expectedCount","__PRIVATE_resolvedCount","done","element","or","predicates","p","predicate","__PRIVATE_isTrue","collection","f","__PRIVATE_promises","r","call","mapArray","array","results","doWhile","condition","action","process","__PRIVATE_LOG_TAG","__PRIVATE_SimpleDbTransaction","open","db","mode","objectStoreNames","transaction","__PRIVATE_IndexedDbTransactionError","aborted","oncomplete","__PRIVATE_completionDeferred","onabort","onerror","event","__PRIVATE_checkForAndReportiOSError","target","__PRIVATE_completionPromise","abort","__PRIVATE_maybeCommit","__PRIVATE_maybeV3IndexedDb","commit","store","__PRIVATE_storeName","objectStore","__PRIVATE_SimpleDbStore","__PRIVATE_SimpleDb","__PRIVATE_wrapRequest","getGlobal","indexedDB","deleteDatabase","__PRIVATE_isAvailable","isIndexedDBAvailable","__PRIVATE_isMockPersistence","__PRIVATE_ua","getUA","__PRIVATE_iOSVersion","__PRIVATE_getIOSVersion","__PRIVATE_isUnsupportedIOS","__PRIVATE_androidVersion","__PRIVATE_getAndroidVersion","__PRIVATE_isUnsupportedAndroid","__PRIVATE_env","__PRIVATE_USE_MOCK_PERSISTENCE","__PRIVATE_getStore","txn","__PRIVATE_iOSVersionRegex","match","version","Number","__PRIVATE_schemaConverter","__PRIVATE_lastClosedDbVersion","__PRIVATE_ensureDb","request","onsuccess","onblocked","onupgradeneeded","oldVersion","__PRIVATE_createOrUpgrade","__PRIVATE_versionchangelistener","onversionchange","__PRIVATE_setVersionChangeListener","__PRIVATE_versionChangeListener","runTransaction","__PRIVATE_objectStores","__PRIVATE_transactionFn","__PRIVATE_readonly","__PRIVATE_attemptNumber","__PRIVATE_transactionFnResult","catch","__PRIVATE_retryable","close","__PRIVATE_androidVersionRegex","__PRIVATE_IterationController","__PRIVATE_dbCursor","__PRIVATE_shouldStop","__PRIVATE_nextKey","__PRIVATE_skipToKey","cursor","__PRIVATE_skip","delete","__PRIVATE_actionName","cause","__PRIVATE_isIndexedDbTransactionError","put","__PRIVATE_keyOrValue","add","count","__PRIVATE_loadAll","__PRIVATE_indexOrRange","__PRIVATE_iterateOptions","options","getAll","__PRIVATE_iterateCursor","__PRIVATE_loadFirst","__PRIVATE_deleteAll","__PRIVATE_keysOnly","control","__PRIVATE_iterate","__PRIVATE_optionsOrCallback","__PRIVATE_iterateSerial","__PRIVATE_cursorRequest","primaryKey","__PRIVATE_shouldContinue","continue","controller","__PRIVATE_userResult","__PRIVATE_userPromise","__PRIVATE_indexName","direction","reverse","openKeyCursor","openCursor","__PRIVATE_reportedIOSError","__PRIVATE_IOS_ERROR","__PRIVATE_newError","__PRIVATE_IndexBackfillerScheduler","__PRIVATE_backfiller","task","__PRIVATE_schedule","stop","cancel","started","delay","enqueueAfterDelay","__PRIVATE_documentsProcessed","__PRIVATE_backfill","__PRIVATE_IndexBackfiller","localStore","persistence","__PRIVATE_maxDocumentsToProcess","__PRIVATE_writeIndexEntries","__PRIVATE_processedCollectionGroups","Set","__PRIVATE_documentsRemaining","__PRIVATE_continueLoop","indexManager","getNextCollectionGroupToUpdate","has","__PRIVATE_writeEntriesForCollectionGroup","__PRIVATE_documentsRemainingUnderCap","getMinOffsetFromCollectionGroup","__PRIVATE_existingOffset","localDocuments","getNextDocuments","__PRIVATE_nextBatch","docs","changes","updateIndexEntries","__PRIVATE_getNewOffset","__PRIVATE_newOffset","updateCollectionGroup","__PRIVATE_lookupResult","__PRIVATE_maxOffset","batchId","__PRIVATE_ListenSequence","previousValue","__PRIVATE_sequenceNumberSyncer","sequenceNumberHandler","__PRIVATE_setPreviousValue","__PRIVATE_writeNewSequenceNumber","writeSequenceNumber","__PRIVATE_externalPreviousValue","__PRIVATE_nextValue","__PRIVATE_INVALID","__PRIVATE_BATCHID_UNKNOWN","__PRIVATE_isNullOrUndefined","__PRIVATE_isNegativeZero","isSafeInteger","isInteger","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","__PRIVATE_escapeChar","__PRIVATE_encodeResourcePath","__PRIVATE_encodeSeparator","__PRIVATE_encodeSegment","__PRIVATE_resultBuf","__PRIVATE_decodeResourcePath","__PRIVATE_lastReasonableEscapeIndex","__PRIVATE_segmentBuilder","__PRIVATE_currentPiece","DbRemoteDocumentStore","__PRIVATE_DbPrimaryClientStore","__PRIVATE_DbPrimaryClientKey","__PRIVATE_DbMutationQueueStore","__PRIVATE_DbMutationQueueKeyPath","__PRIVATE_DbMutationBatchStore","__PRIVATE_DbMutationBatchKeyPath","__PRIVATE_DbMutationBatchUserMutationsIndex","__PRIVATE_DbMutationBatchUserMutationsKeyPath","__PRIVATE_newDbDocumentMutationPrefixForPath","userId","__PRIVATE_newDbDocumentMutationKey","__PRIVATE_DbDocumentMutationPlaceholder","__PRIVATE_DbDocumentMutationStore","__PRIVATE_DbRemoteDocumentKeyPath","__PRIVATE_DbRemoteDocumentDocumentKeyIndex","__PRIVATE_DbRemoteDocumentDocumentKeyIndexPath","__PRIVATE_DbRemoteDocumentCollectionGroupIndex","__PRIVATE_DbRemoteDocumentCollectionGroupIndexPath","__PRIVATE_DbRemoteDocumentGlobalStore","__PRIVATE_DbRemoteDocumentGlobalKey","__PRIVATE_DbTargetStore","__PRIVATE_DbTargetQueryTargetsIndexName","__PRIVATE_DbTargetQueryTargetsKeyPath","__PRIVATE_DbTargetDocumentStore","__PRIVATE_DbTargetDocumentKeyPath","__PRIVATE_DbTargetDocumentDocumentTargetsIndex","__PRIVATE_DbTargetDocumentDocumentTargetsKeyPath","__PRIVATE_DbTargetGlobalKey","__PRIVATE_DbTargetGlobalStore","__PRIVATE_DbCollectionParentStore","__PRIVATE_DbCollectionParentKeyPath","__PRIVATE_DbClientMetadataStore","__PRIVATE_DbClientMetadataKeyPath","__PRIVATE_DbBundleStore","__PRIVATE_DbBundleKeyPath","__PRIVATE_DbNamedQueryStore","__PRIVATE_DbNamedQueryKeyPath","__PRIVATE_DbIndexConfigurationStore","__PRIVATE_DbIndexConfigurationKeyPath","__PRIVATE_DbIndexConfigurationCollectionGroupIndex","__PRIVATE_DbIndexConfigurationCollectionGroupIndexPath","__PRIVATE_DbIndexStateStore","__PRIVATE_DbIndexStateKeyPath","__PRIVATE_DbIndexStateSequenceNumberIndex","__PRIVATE_DbIndexStateSequenceNumberIndexPath","__PRIVATE_DbIndexEntryStore","__PRIVATE_DbIndexEntryKeyPath","__PRIVATE_DbIndexEntryDocumentKeyIndex","__PRIVATE_DbIndexEntryDocumentKeyIndexPath","__PRIVATE_DbDocumentOverlayStore","__PRIVATE_DbDocumentOverlayKeyPath","__PRIVATE_DbDocumentOverlayCollectionPathOverlayIndex","__PRIVATE_DbDocumentOverlayCollectionPathOverlayIndexPath","__PRIVATE_DbDocumentOverlayCollectionGroupOverlayIndex","__PRIVATE_DbDocumentOverlayCollectionGroupOverlayIndexPath","__PRIVATE_DbGlobalsStore","__PRIVATE_DbGlobalsKeyPath","__PRIVATE_V11_STORES","__PRIVATE_DbRemoteDocumentStoreLegacy","__PRIVATE_V12_STORES","__PRIVATE_V13_STORES","__PRIVATE_V14_STORES","__PRIVATE_V15_STORES","__PRIVATE_V16_STORES","__PRIVATE_V17_STORES","__PRIVATE_V18_STORES","__PRIVATE_IndexedDbTransaction","__PRIVATE_simpleDbTransaction","currentSequenceNumber","__PRIVATE_indexedDbTransaction","__PRIVATE_objectSize","hasOwnProperty","__PRIVATE_mapToArray","SortedMap","root","LLRBNode","EMPTY","insert","copy","BLACK","remove","node","__PRIVATE_prunedNodes","minKey","maxKey","inorderTraversal","k","v","__PRIVATE_descriptions","reverseTraversal","getIterator","SortedMapIterator","getIteratorFrom","getReverseIterator","getReverseIteratorFrom","startKey","isReverse","nodeStack","getNext","pop","hasNext","peek","color","RED","fixUp","removeMin","isRed","moveRedLeft","__PRIVATE_smallest","rotateRight","moveRedRight","rotateLeft","colorFlip","__PRIVATE_nl","__PRIVATE_nr","checkMaxDepth","__PRIVATE_blackDepth","check","pow","LLRBEmptyNode","SortedSet","data","elem","first","last","cb","forEachInRange","iter","forEachWhile","firstAfterOrEqual","SortedSetIterator","unionWith","__PRIVATE_thisIt","__PRIVATE_otherIt","__PRIVATE_thisElem","__PRIVATE_otherElem","__PRIVATE_res","targetId","__PRIVATE_advanceIterator","__PRIVATE_it","FieldMask","sort","extraFields","__PRIVATE_mergedMaskSet","covers","__PRIVATE_fieldMaskPath","l","__PRIVATE_Base64DecodeError","__PRIVATE_WEB_SAFE","__PRIVATE_decodeBase64","__PRIVATE_encoded","fromCharCode","apply","base64","decodeStringToByteArray","DecodeBase64StringError","__PRIVATE_isBase64Available","ByteString","binaryString","fromBase64String","fromUint8Array","__PRIVATE_binaryStringFromUint8Array","Symbol","iterator","toBase64","__PRIVATE_encodeBase64","raw","encodeByteArray","toUint8Array","__PRIVATE_uint8ArrayFromBinaryString","buffer","approximateByteSize","EMPTY_BYTE_STRING","__PRIVATE_ISO_TIMESTAMP_REG_EXP","RegExp","__PRIVATE_normalizeTimestamp","__PRIVATE_fraction","exec","__PRIVATE_nanoStr","substr","__PRIVATE_parsedDate","__PRIVATE_normalizeNumber","__PRIVATE_normalizeByteString","blob","__PRIVATE_SERVER_TIMESTAMP_SENTINEL","__PRIVATE_TYPE_KEY","__PRIVATE_PREVIOUS_VALUE_KEY","__PRIVATE_LOCAL_WRITE_TIME_KEY","__PRIVATE_isServerTimestamp","mapValue","stringValue","__PRIVATE_getPreviousValue","__PRIVATE_getLocalWriteTime","localWriteTime","timestampValue","DatabaseInfo","databaseId","appId","persistenceKey","host","ssl","forceLongPolling","autoDetectLongPolling","longPollingOptions","useFetchStreams","isUsingEmulator","__PRIVATE_DEFAULT_DATABASE_NAME","DatabaseId","projectId","database","isDefaultDatabase","__PRIVATE_MAX_VALUE_TYPE","MAX_VALUE","__type__","__PRIVATE_VECTOR_VALUE_SENTINEL","__PRIVATE_VECTOR_MAP_VECTORS_KEY","MIN_VALUE","nullValue","__PRIVATE_typeOrder","__PRIVATE_isMaxValue","__PRIVATE_isVectorValue","__PRIVATE_valueEquals","__PRIVATE_leftType","booleanValue","__PRIVATE_timestampEquals","__PRIVATE_leftTimestamp","__PRIVATE_rightTimestamp","__PRIVATE_blobEquals","bytesValue","referenceValue","__PRIVATE_geoPointEquals","geoPointValue","latitude","longitude","__PRIVATE_numberEquals","integerValue","__PRIVATE_n1","doubleValue","__PRIVATE_n2","isNaN","arrayValue","values","__PRIVATE_objectEquals","__PRIVATE_leftMap","__PRIVATE_rightMap","__PRIVATE_arrayValueContains","__PRIVATE_haystack","__PRIVATE_needle","__PRIVATE_valueCompare","__PRIVATE_rightType","__PRIVATE_compareNumbers","__PRIVATE_leftNumber","__PRIVATE_rightNumber","__PRIVATE_compareTimestamps","__PRIVATE_compareBlobs","__PRIVATE_leftBytes","__PRIVATE_rightBytes","__PRIVATE_compareReferences","__PRIVATE_leftPath","__PRIVATE_rightPath","__PRIVATE_leftSegments","__PRIVATE_rightSegments","__PRIVATE_compareGeoPoints","__PRIVATE_compareArrays","__PRIVATE_compareVectors","__PRIVATE_leftArrayValue","__PRIVATE_rightArrayValue","__PRIVATE_lengthCompare","__PRIVATE_compareMaps","__PRIVATE_leftKeys","keys","__PRIVATE_rightKeys","__PRIVATE_keyCompare","__PRIVATE_leftArray","__PRIVATE_rightArray","canonicalId","__PRIVATE_canonifyValue","__PRIVATE_canonifyTimestamp","__PRIVATE_normalizedTimestamp","__PRIVATE_canonifyByteString","byteString","__PRIVATE_canonifyReference","__PRIVATE_canonifyGeoPoint","__PRIVATE_geoPoint","__PRIVATE_canonifyArray","__PRIVATE_canonifyMap","__PRIVATE_sortedKeys","__PRIVATE_estimateByteSize","__PRIVATE_estimateArrayByteSize","reduce","__PRIVATE_previousSize","__PRIVATE_estimateMapByteSize","val","__PRIVATE_refValue","isArray","__PRIVATE_isNullValue","__PRIVATE_isNanValue","__PRIVATE_isMapValue","__PRIVATE_deepClone","source","__PRIVATE_MIN_VECTOR_VALUE","__PRIVATE_valuesGetLowerBound","NaN","__PRIVATE_valuesGetUpperBound","__PRIVATE_lowerBoundCompare","inclusive","__PRIVATE_upperBoundCompare","ObjectValue","field","__PRIVATE_currentLevel","getFieldsMap","setAll","parent","__PRIVATE_upserts","__PRIVATE_deletes","__PRIVATE_fieldsMap","applyChanges","__PRIVATE_nestedValue","__PRIVATE_inserts","clone","__PRIVATE_extractFieldMask","__PRIVATE_currentPath","__PRIVATE_nestedFields","__PRIVATE_nestedPath","MutableDocument","documentType","createTime","documentState","newInvalidDocument","newFoundDocument","newNoDocument","newUnknownDocument","convertToFoundDocument","convertToNoDocument","convertToUnknownDocument","setHasCommittedMutations","setHasLocalMutations","setReadTime","hasLocalMutations","hasCommittedMutations","hasPendingWrites","isValidDocument","isFoundDocument","isNoDocument","isUnknownDocument","mutableCopy","Bound","position","__PRIVATE_boundCompareToDocument","bound","orderBy","doc","__PRIVATE_orderByComponent","component","dir","__PRIVATE_boundEquals","OrderBy","__PRIVATE_orderByEquals","Filter","FieldFilter","op","create","createKeyFieldInFilter","__PRIVATE_KeyFieldFilter","__PRIVATE_ArrayContainsFilter","__PRIVATE_InFilter","__PRIVATE_NotInFilter","__PRIVATE_ArrayContainsAnyFilter","__PRIVATE_KeyFieldInFilter","__PRIVATE_KeyFieldNotInFilter","matches","matchesComparison","operator","isInequality","getFlattenedFilters","getFilters","CompositeFilter","filters","__PRIVATE_memoizedFlattenedFilters","__PRIVATE_compositeFilterIsConjunction","__PRIVATE_subfilter","concat","assign","compositeFilter","__PRIVATE_compositeFilterIsDisjunction","__PRIVATE_compositeFilterIsFlatConjunction","__PRIVATE_compositeFilterIsFlat","__PRIVATE_canonifyFilter","__PRIVATE_canonicalIdsString","__PRIVATE_filterEquals","__PRIVATE_f1","__PRIVATE_f2","__PRIVATE_fieldFilterEquals","__PRIVATE_compositeFilterEquals","__PRIVATE_f1Filter","__PRIVATE_compositeFilterWithAddedFilters","__PRIVATE_otherFilters","__PRIVATE_mergedFilters","__PRIVATE_stringifyFilter","__PRIVATE_stringifyFieldFilter","__PRIVATE_stringifyCompositeFilter","__PRIVATE_extractDocumentKeysFromArrayValue","some","__PRIVATE_TargetImpl","startAt","endAt","__PRIVATE_memoizedCanonicalId","__PRIVATE_newTarget","__PRIVATE_canonifyTarget","__PRIVATE_targetImpl","o","__PRIVATE_canonifyOrderBy","__PRIVATE_targetEquals","__PRIVATE_targetIsDocumentTarget","__PRIVATE_targetGetFieldFiltersForPath","__PRIVATE_targetGetAscendingBound","fieldFilter","__PRIVATE_filterValue","__PRIVATE_filterInclusive","__PRIVATE_cursorValue","__PRIVATE_targetGetDescendingBound","__PRIVATE_QueryImpl","explicitOrderBy","limitType","__PRIVATE_memoizedNormalizedOrderBy","__PRIVATE_memoizedTarget","__PRIVATE_memoizedAggregateTarget","__PRIVATE_newQuery","__PRIVATE_newQueryForPath","__PRIVATE_queryMatchesAllDocuments","query","__PRIVATE_isCollectionGroupQuery","__PRIVATE_queryNormalizedOrderBy","__PRIVATE_queryImpl","__PRIVATE_fieldsNormalized","__PRIVATE_lastDirection","__PRIVATE_inequalityFields","__PRIVATE_getInequalityFilterFields","__PRIVATE_queryToTarget","__PRIVATE__queryToTarget","__PRIVATE_queryToAggregateTarget","__PRIVATE_orderBys","__PRIVATE_queryWithAddedFilter","__PRIVATE_newFilters","__PRIVATE_queryWithLimit","__PRIVATE_queryEquals","__PRIVATE_canonifyQuery","__PRIVATE_stringifyQuery","__PRIVATE_stringifyTarget","__PRIVATE_stringifyOrderBy","__PRIVATE_queryMatches","__PRIVATE_queryMatchesPathAndCollectionGroup","__PRIVATE_docPath","__PRIVATE_queryMatchesOrderBy","__PRIVATE_queryMatchesFilters","__PRIVATE_queryMatchesBounds","__PRIVATE_boundSortsBeforeDocument","__PRIVATE_boundSortsAfterDocument","__PRIVATE_queryCollectionGroup","__PRIVATE_newQueryComparator","__PRIVATE_d1","__PRIVATE_d2","__PRIVATE_comparedOnKeyField","comp","__PRIVATE_compareDocs","__PRIVATE_compareDocumentsByField","v1","v2","ObjectMap","mapKeyFn","equalsFn","inner","innerSize","__PRIVATE_otherKey","splice","_","entries","__PRIVATE_EMPTY_MUTABLE_DOCUMENT_MAP","__PRIVATE_mutableDocumentMap","__PRIVATE_EMPTY_DOCUMENT_MAP","documentMap","__PRIVATE_convertOverlayedDocumentMapToDocumentMap","documents","overlayedDocument","__PRIVATE_newOverlayMap","__PRIVATE_newDocumentKeyMap","__PRIVATE_newMutationMap","__PRIVATE_EMPTY_DOCUMENT_VERSION_MAP","__PRIVATE_EMPTY_DOCUMENT_KEY_SET","__PRIVATE_documentKeySet","__PRIVATE_EMPTY_TARGET_ID_SET","__PRIVATE_targetIdSet","__PRIVATE_toDouble","serializer","useProto3Json","Infinity","__PRIVATE_toInteger","toNumber","TransformOperation","__PRIVATE_applyTransformOperationToLocalView","transform","__PRIVATE_ServerTimestampTransform","serverTimestamp","__PRIVATE_TYPE_KEY$1","__PRIVATE_ArrayUnionTransformOperation","__PRIVATE_applyArrayUnionTransformOperation","__PRIVATE_ArrayRemoveTransformOperation","__PRIVATE_applyArrayRemoveTransformOperation","__PRIVATE_applyNumericIncrementTransformOperationToLocalView","__PRIVATE_baseValue","__PRIVATE_computeTransformOperationBaseValue","sum","asNumber","__PRIVATE_operand","__PRIVATE_applyTransformOperationToRemoteDocument","__PRIVATE_transformResult","__PRIVATE_NumericIncrementTransformOperation","__PRIVATE_isNumber","__PRIVATE_isDouble","elements","__PRIVATE_coercedFieldValuesArray","__PRIVATE_toUnion","__PRIVATE_toRemove","FieldTransform","__PRIVATE_fieldTransformEquals","__PRIVATE_transformOperationEquals","MutationResult","transformResults","Precondition","updateTime","exists","none","isNone","__PRIVATE_preconditionIsValidForDocument","precondition","Mutation","__PRIVATE_calculateOverlayMutation","mask","__PRIVATE_DeleteMutation","__PRIVATE_SetMutation","__PRIVATE_docValue","__PRIVATE_patchValue","__PRIVATE_maskSet","__PRIVATE_PatchMutation","__PRIVATE_mutationApplyToRemoteDocument","mutation","__PRIVATE_mutationResult","__PRIVATE_setMutationApplyToRemoteDocument","__PRIVATE_newData","__PRIVATE_serverTransformResults","fieldTransforms","__PRIVATE_patchMutationApplyToRemoteDocument","__PRIVATE_getPatch","__PRIVATE_deleteMutationApplyToRemoteDocument","__PRIVATE_mutationApplyToLocalView","__PRIVATE_previousMask","__PRIVATE_setMutationApplyToLocalView","__PRIVATE_localTransformResults","__PRIVATE_patchMutationApplyToLocalView","fieldMask","__PRIVATE_deleteMutationApplyToLocalView","__PRIVATE_mutationExtractBaseValue","__PRIVATE_baseObject","__PRIVATE_fieldTransform","__PRIVATE_existingValue","__PRIVATE_coercedValue","__PRIVATE_mutationEquals","__PRIVATE_fieldTransformsAreEqual","getFieldMask","newValue","__PRIVATE_mutableDocument","__PRIVATE_serverTransformResultCount","__PRIVATE_fieldTransformCount","__PRIVATE_VerifyMutation","MutationBatch","baseMutations","mutations","applyToRemoteDocument","batchResult","mutationResults","applyToLocalView","mutatedFields","applyToLocalDocumentSet","documentsWithoutRemoteVersion","overlays","m","__PRIVATE_overlay","MutationBatchResult","batch","commitVersion","docVersions","from","__PRIVATE_mutationsSent","__PRIVATE_resultsReceived","__PRIVATE_versionMap","__PRIVATE_documentVersionMap","Overlay","getKey","__PRIVATE_AggregateImpl","alias","aggregateType","ExistenceFilter","unchangedNames","__PRIVATE_RpcCode","RpcCode","__PRIVATE_isPermanentError","__PRIVATE_mapCodeFromRpcCode","__PRIVATE_testingHooksSpi","__PRIVATE_newTextEncoder","TextEncoder","__PRIVATE_MAX_64_BIT_UNSIGNED_INTEGER","__PRIVATE_getMd5HashValue","__PRIVATE_encodedValue","encode","__PRIVATE_md5","Md5","update","digest","__PRIVATE_get64BitUints","Bytes","__PRIVATE_dataView","DataView","__PRIVATE_chunk1","getUint32","__PRIVATE_chunk2","__PRIVATE_chunk3","__PRIVATE_chunk4","BloomFilter","bitmap","padding","hashCount","__PRIVATE_BloomFilterError","__PRIVATE_bitCount","__PRIVATE_bitCountInInteger","fromNumber","__PRIVATE_getBitIndex","__PRIVATE_num1","__PRIVATE_num2","__PRIVATE_hashIndex","__PRIVATE_hashValue","multiply","getBits","modulo","__PRIVATE_isBitSet","mightContain","__PRIVATE_md5HashedValue","__PRIVATE_hash1","__PRIVATE_hash2","contains","ceil","bloomFilter","item","__PRIVATE_setBit","__PRIVATE_indexOfByte","RemoteEvent","snapshotVersion","targetChanges","targetMismatches","documentUpdates","resolvedLimboDocuments","createSynthesizedRemoteEventForCurrentChange","resumeToken","TargetChange","createSynthesizedTargetChangeForCurrentChange","addedDocuments","modifiedDocuments","removedDocuments","__PRIVATE_DocumentWatchChange","__PRIVATE_updatedTargetIds","removedTargetIds","__PRIVATE_newDoc","__PRIVATE_ExistenceFilterChange","__PRIVATE_existenceFilter","__PRIVATE_WatchTargetChange","state","targetIds","__PRIVATE_TargetState","__PRIVATE_pendingResponses","__PRIVATE_documentChanges","__PRIVATE_snapshotChangesMap","__PRIVATE__current","__PRIVATE__hasPendingChanges","__PRIVATE__resumeToken","__PRIVATE_isPending","__PRIVATE_hasPendingChanges","__PRIVATE_updateResumeToken","__PRIVATE_toTargetChange","changeType","__PRIVATE_clearPendingChanges","__PRIVATE_addDocumentChange","__PRIVATE_removeDocumentChange","__PRIVATE_recordPendingTargetRequest","__PRIVATE_recordTargetResponse","__PRIVATE_markCurrent","__PRIVATE_WatchChangeAggregator","__PRIVATE_metadataProvider","__PRIVATE_pendingDocumentUpdates","__PRIVATE_pendingDocumentUpdatesByTarget","__PRIVATE_documentTargetMap","__PRIVATE_pendingDocumentTargetMapping","__PRIVATE_pendingTargetResets","__PRIVATE_handleDocumentChange","__PRIVATE_docChange","__PRIVATE_addDocumentToTarget","__PRIVATE_removeDocumentFromTarget","__PRIVATE_handleTargetChange","targetChange","forEachTarget","__PRIVATE_targetState","__PRIVATE_ensureTargetState","__PRIVATE_isActiveTarget","removeTarget","__PRIVATE_resetTarget","__PRIVATE_targetStates","__PRIVATE_handleExistenceFilter","__PRIVATE_watchChange","targetData","__PRIVATE_targetDataForActiveTarget","__PRIVATE_currentSize","__PRIVATE_getCurrentDocumentCountForTarget","__PRIVATE_parseBloomFilter","status","__PRIVATE_applyBloomFilter","purpose","__PRIVATE_notifyOnExistenceFilterMismatch","__PRIVATE_createExistenceFilterMismatchInfoForTestingHooks","localCacheCount","__PRIVATE_bloomFilterStatus","existenceFilterCount","applied","bitmapLength","bits","__PRIVATE_getDatabaseId","__PRIVATE_normalizedBitmap","__PRIVATE_currentCount","__PRIVATE_filterRemovedDocuments","__PRIVATE_existingKeys","getRemoteKeysForTarget","__PRIVATE_removalCount","documentPath","__PRIVATE_createRemoteEvent","__PRIVATE_ensureDocumentUpdateByTarget","__PRIVATE_targetContainsDocument","__PRIVATE_targets","__PRIVATE_isOnlyLimboTarget","remoteEvent","__PRIVATE_ensureDocumentTargetMapping","__PRIVATE_updatedDocument","__PRIVATE_targetMapping","__PRIVATE_targetActive","__PRIVATE_getTargetDataForTarget","__PRIVATE_DIRECTIONS","__PRIVATE_dirs","__PRIVATE_OPERATORS","__PRIVATE_ops","__PRIVATE_COMPOSITE_OPERATORS","JsonProtoSerializer","__PRIVATE_toInt32Proto","toISOString","__PRIVATE_toBytes","__PRIVATE_toVersion","__PRIVATE_fromVersion","__PRIVATE_toResourceName","__PRIVATE_toResourcePath","__PRIVATE_resourcePath","__PRIVATE_fullyQualifiedPrefixPath","__PRIVATE_fromResourceName","__PRIVATE_resource","__PRIVATE_isValidResourceName","__PRIVATE_toName","__PRIVATE_extractLocalPathFromResourceName","__PRIVATE_toQueryPath","__PRIVATE_fromQueryPath","__PRIVATE_resourceName","__PRIVATE_getEncodedDatabaseId","__PRIVATE_toMutationDocument","__PRIVATE_fromDocument","__PRIVATE_fromBatchGetDocumentsResponse","__PRIVATE_fromFound","found","__PRIVATE_fromMissing","missing","__PRIVATE_fromWatchChange","__PRIVATE_change","__PRIVATE_fromWatchTargetChangeState","targetChangeType","__PRIVATE_fromBytes","Buffer","__PRIVATE_causeProto","__PRIVATE_fromRpcStatus","documentChange","__PRIVATE_entityChange","documentDelete","__PRIVATE_docDelete","documentRemove","__PRIVATE_docRemove","toMutation","updateMask","__PRIVATE_toDocumentMask","__PRIVATE_mutationType","verify","updateTransforms","__PRIVATE_toFieldTransform","setToServerValue","appendMissingElements","removeAllFromArray","increment","currentDocument","__PRIVATE_toPrecondition","__PRIVATE_fromMutation","proto","__PRIVATE_fromPrecondition","__PRIVATE_fromFieldTransform","__PRIVATE_fromDocumentMask","__PRIVATE_paths","fieldPaths","__PRIVATE_fromWriteResults","__PRIVATE_protos","commitTime","__PRIVATE_fromWriteResult","__PRIVATE_toDocumentsTarget","__PRIVATE_toQueryTarget","__PRIVATE_queryTarget","structuredQuery","allDescendants","where","__PRIVATE_toFilters","__PRIVATE_toFilter","__PRIVATE_toOrder","order","__PRIVATE_toPropertyOrder","__PRIVATE_toFieldPathReference","__PRIVATE_toDirection","__PRIVATE_toStartAtCursor","before","__PRIVATE_toEndAtCursor","__PRIVATE_toRunAggregationQueryRequest","__PRIVATE_aggregates","__PRIVATE_skipAliasing","ft","__PRIVATE_aliasMap","aggregations","__PRIVATE_aggregationNum","__PRIVATE_aggregate","__PRIVATE_serverAlias","avg","structuredAggregationQuery","__PRIVATE_convertQueryTargetToQuery","__PRIVATE_fromCount","__PRIVATE_filterBy","__PRIVATE_fromFilters","__PRIVATE_fromFilter","__PRIVATE_fromOrder","__PRIVATE_fromPropertyOrder","__PRIVATE_fromFieldPathReference","__PRIVATE_fromDirection","__PRIVATE_fromInt32Proto","__PRIVATE_fromStartAtCursor","__PRIVATE_fromEndAtCursor","__PRIVATE_toListenRequestLabels","__PRIVATE_toLabel","unaryFilter","__PRIVATE_fromUnaryFilter","__PRIVATE_nanField","__PRIVATE_nullField","__PRIVATE_notNanField","__PRIVATE_notNullField","__PRIVATE_fromFieldFilter","__PRIVATE_fromOperatorName","__PRIVATE_fromCompositeFilter","__PRIVATE_fromCompositeOperatorName","__PRIVATE_toOperatorName","__PRIVATE_toCompositeOperatorName","__PRIVATE_fieldReference","__PRIVATE_toUnaryOrFieldFilter","__PRIVATE_toCompositeFilter","__PRIVATE_canonicalFields","TargetData","lastLimboFreeSnapshotVersion","withSequenceNumber","withResumeToken","withExpectedCount","withLastLimboFreeSnapshotVersion","__PRIVATE_LocalSerializer","__PRIVATE_remoteSerializer","__PRIVATE_fromDbRemoteDocument","__PRIVATE_localSerializer","__PRIVATE_remoteDoc","noDocument","__PRIVATE_fromDbTimestamp","unknownDocument","__PRIVATE_fromDbTimestampKey","__PRIVATE_dbTimestampKey","__PRIVATE_toDbRemoteDocument","prefixPath","documentId","__PRIVATE_toDbTimestampKey","__PRIVATE_toDocument","__PRIVATE_toDbTimestamp","__PRIVATE_dbTimestamp","__PRIVATE_fromDbMutationBatch","__PRIVATE_dbBatch","__PRIVATE_currentMutation","__PRIVATE_transformMutation","localWriteTimeMs","__PRIVATE_fromDbTarget","__PRIVATE_dbTarget","__PRIVATE_isDocumentQuery","__PRIVATE_dbQuery","__PRIVATE_fromDocumentsTarget","__PRIVATE_documentsTarget","__PRIVATE_fromQueryTarget","lastListenSequenceNumber","__PRIVATE_toDbTarget","__PRIVATE_dbLastLimboFreeTimestamp","__PRIVATE_queryProto","__PRIVATE_fromBundledQuery","bundledQuery","__PRIVATE_fromDbDocumentOverlay","__PRIVATE_dbDocumentOverlay","overlayMutation","__PRIVATE_toDbDocumentOverlayKey","__PRIVATE_docKey","__PRIVATE_docId","__PRIVATE_toDbIndexState","__PRIVATE_IndexedDbBundleCache","getBundleMetadata","bundleId","__PRIVATE_bundlesStore","bundle","__PRIVATE_fromDbBundle","__PRIVATE_dbBundle","saveBundleMetadata","__PRIVATE_bundleMetadata","__PRIVATE_toDbBundle","metadata","getNamedQuery","queryName","__PRIVATE_namedQueriesStore","__PRIVATE_fromDbNamedQuery","__PRIVATE_dbNamedQuery","saveNamedQuery","__PRIVATE_toDbNamedQuery","__PRIVATE_IndexedDbDocumentOverlayCache","__PRIVATE_forUser","getOverlay","__PRIVATE_documentOverlayStore","__PRIVATE_dbOverlay","getOverlays","saveOverlays","__PRIVATE_saveOverlay","removeOverlaysForBatchId","documentKeys","__PRIVATE_collectionPaths","collectionPath","IDBKeyRange","getOverlaysForCollection","sinceBatchId","POSITIVE_INFINITY","__PRIVATE_dbOverlays","getOverlaysForCollectionGroup","__PRIVATE_currentBatchId","__PRIVATE_toDbDocumentOverlay","__PRIVATE_IndexedDbGlobalsCache","__PRIVATE_globalsStore","getSessionToken","global","setSessionToken","sessionToken","__PRIVATE_FirestoreIndexValueWriter","__PRIVATE_writeIndexValue","__PRIVATE_encoder","__PRIVATE_writeIndexValueAux","__PRIVATE_writeInfinity","__PRIVATE_indexValue","__PRIVATE_writeValueTypeLabel","__PRIVATE_writeNumber","__PRIVATE_writeString","__PRIVATE_writeIndexString","__PRIVATE_writeTruncationMarker","__PRIVATE_writeBytes","__PRIVATE_writeIndexEntityRef","__PRIVATE_writeIndexVector","__PRIVATE_writeIndexMap","__PRIVATE_writeIndexArray","__PRIVATE_stringIndexValue","__PRIVATE_writeUnlabeledIndexString","__PRIVATE_mapIndexValue","__PRIVATE_arrayIndexValue","__PRIVATE_ESCAPE2","__PRIVATE_numberOfLeadingZerosInByte","x","__PRIVATE_zeros","__PRIVATE_unsignedNumLength","__PRIVATE_numBits","__PRIVATE_numberOfLeadingZeros","__PRIVATE_leadingZeros","__PRIVATE_OrderedCodeWriter","__PRIVATE_writeBytesAscending","__PRIVATE_byte","__PRIVATE_writeByteAscending","__PRIVATE_writeSeparatorAscending","__PRIVATE_writeBytesDescending","__PRIVATE_writeByteDescending","__PRIVATE_writeSeparatorDescending","__PRIVATE_writeUtf8Ascending","__PRIVATE_sequence","charCode","__PRIVATE_codePoint","codePointAt","__PRIVATE_writeUtf8Descending","__PRIVATE_writeNumberAscending","__PRIVATE_toOrderedBits","__PRIVATE_ensureAvailable","__PRIVATE_writeNumberDescending","__PRIVATE_writeInfinityAscending","__PRIVATE_writeEscapedByteAscending","__PRIVATE_writeInfinityDescending","__PRIVATE_writeEscapedByteDescending","reset","seed","__PRIVATE_encodedBytes","__PRIVATE_doubleToLongBits","__PRIVATE_dv","ArrayBuffer","setFloat64","__PRIVATE_isNegative","b","__PRIVATE_masked","__PRIVATE_minCapacity","__PRIVATE_newLength","__PRIVATE_newBuffer","__PRIVATE_AscendingIndexByteEncoder","__PRIVATE_orderedCode","__PRIVATE_DescendingIndexByteEncoder","__PRIVATE_IndexByteEncoder","__PRIVATE_ascending","__PRIVATE_descending","__PRIVATE_forKind","__PRIVATE_IndexEntry","__PRIVATE__indexId","__PRIVATE__documentKey","__PRIVATE__arrayValue","__PRIVATE__directionalValue","__PRIVATE_currentLength","__PRIVATE_dbIndexEntry","orderedDocumentKey","__PRIVATE_encodeKeySafeBytes","directionalValue","__PRIVATE_dbIndexEntryKey","entry","__PRIVATE_indexEntryComparator","__PRIVATE_compareByteArrays","isSafariOrWebkit","__PRIVATE_encodeUint8ArrayToSortableString","__PRIVATE_decodeKeySafeBytes","__PRIVATE_decodeSortableStringToUint8Array","__PRIVATE_uint8array","__PRIVATE_TargetIndexMatcher","__PRIVATE_equalityFilters","__PRIVATE_inequalityFilters","__PRIVATE_hasMultipleInequality","__PRIVATE_servedByIndex","__PRIVATE_arraySegment","__PRIVATE_hasMatchingEqualityFilter","__PRIVATE_equalitySegments","__PRIVATE_segmentIndex","__PRIVATE_orderBysIndex","__PRIVATE_inequalityFilter","__PRIVATE_matchesFilter","__PRIVATE_matchesOrderBy","__PRIVATE_buildTargetIndex","__PRIVATE_uniqueFields","__PRIVATE_isArrayOperator","__PRIVATE_computeInExpansion","__PRIVATE_expandedFilters","__PRIVATE_getDnfTerms","__PRIVATE_computeDistributedNormalForm","__PRIVATE_isDisjunctiveNormalForm","__PRIVATE_isSingleFieldFilter","__PRIVATE_isFlatConjunction","__PRIVATE_isDisjunctionOfFieldFiltersAndFlatConjunctions","__PRIVATE_subFilter","__PRIVATE_newFilter","__PRIVATE_applyAssociation","__PRIVATE_runningResult","__PRIVATE_applyDistribution","__PRIVATE_applyDistributionFieldFilters","__PRIVATE_applyDistributionFieldAndCompositeFilters","__PRIVATE_applyDistributionCompositeFilters","__PRIVATE_disjunctionSide","__PRIVATE_otherSide","__PRIVATE_updatedFilters","__PRIVATE_newSubfilters","__PRIVATE_MemoryIndexManager","__PRIVATE_MemoryCollectionParentIndex","addToCollectionParentIndex","__PRIVATE_collectionParentIndex","getCollectionParents","getEntries","addFieldIndex","deleteFieldIndex","deleteAllFieldIndexes","createTargetIndexes","getDocumentsMatchingTarget","getIndexType","getFieldIndexes","getMinOffset","parentPath","__PRIVATE_existingParents","__PRIVATE_added","__PRIVATE_EMPTY_VALUE","__PRIVATE_IndexedDbIndexManager","t","__PRIVATE_collectionParentsCache","__PRIVATE_collectionParent","__PRIVATE_collectionParentsStore","__PRIVATE_parentPaths","indexes","__PRIVATE_indexConfigurationStore","__PRIVATE_dbIndex","__PRIVATE_toDbIndexConfiguration","states","__PRIVATE_indexStateStore","__PRIVATE_indexEntriesStore","__PRIVATE_getSubTargets","__PRIVATE_subTarget","__PRIVATE_indexEntries","__PRIVATE_canServeTarget","__PRIVATE_getFieldIndex","__PRIVATE_fieldIndexToString","__PRIVATE_arrayValues","__PRIVATE_targetGetArrayValues","__PRIVATE_notInValues","__PRIVATE_targetGetNotInValues","lowerBound","__PRIVATE_targetGetLowerBound","__PRIVATE_segmentBound","upperBound","__PRIVATE_targetGetUpperBound","__PRIVATE_lowerBoundEncoded","__PRIVATE_encodeBound","__PRIVATE_upperBoundEncoded","__PRIVATE_notInEncoded","__PRIVATE_encodeValues","__PRIVATE_indexRanges","__PRIVATE_generateIndexRanges","__PRIVATE_indexRange","__PRIVATE_subTargets","__PRIVATE_targetToDnfSubTargets","__PRIVATE_term","__PRIVATE_lowerBounds","__PRIVATE_lowerBoundInclusive","__PRIVATE_upperBounds","__PRIVATE_upperBoundInclusive","__PRIVATE_totalScans","__PRIVATE_scansPerArrayElement","__PRIVATE_encodeSingleElement","__PRIVATE_generateLowerBound","__PRIVATE_generateUpperBound","__PRIVATE_notInBound","__PRIVATE_notIn","createRange","__PRIVATE_targetIndexMatcher","candidate","__PRIVATE_indexType","__PRIVATE_targetGetSegmentCount","__PRIVATE_hasArraySegment","__PRIVATE_targetHasLimit","__PRIVATE_encodeDirectionalElements","__PRIVATE_directionalEncoder","__PRIVATE_INSTANCE","__PRIVATE_encodeDirectionalKey","__PRIVATE_fieldIndexGetKeyOrder","__PRIVATE_directionalSegments","__PRIVATE_encoders","__PRIVATE_valueIdx","__PRIVATE_isInFilter","__PRIVATE_expandIndexValues","__PRIVATE_getEncodedBytes","prefixes","__PRIVATE_arrayElement","prefix","__PRIVATE_clonedEncoder","__PRIVATE_indexConfigs","__PRIVATE_indexConfig","__PRIVATE_fromDbIndexConfiguration","__PRIVATE_decodedState","__PRIVATE_decodedSegments","__PRIVATE_getNextSequenceNumber","__PRIVATE_nextSequenceNumber","__PRIVATE_configs","config","__PRIVATE_memoizedIndexes","__PRIVATE_memoizedCollectionIndexes","__PRIVATE_fieldIndexes","__PRIVATE_getExistingIndexEntries","__PRIVATE_existingEntries","__PRIVATE_newEntries","__PRIVATE_computeIndexEntries","__PRIVATE_updateEntries","__PRIVATE_addIndexEntry","__PRIVATE_indexEntry","__PRIVATE_deleteIndexEntry","only","__PRIVATE_diffSortedSets","after","__PRIVATE_onAdd","__PRIVATE_onRemove","__PRIVATE_beforeIt","__PRIVATE_afterIt","__PRIVATE_beforeValue","__PRIVATE_afterValue","__PRIVATE_removed","lower","upper","el","__PRIVATE_bounds","__PRIVATE_notInValue","__PRIVATE_cmpToLower","__PRIVATE_cmpToUpper","__PRIVATE_ranges","__PRIVATE_isRangeMatchable","__PRIVATE_getMinOffsetFromFieldIndexes","__PRIVATE_minOffset","__PRIVATE_maxBatchId","__PRIVATE_GC_DID_NOT_RUN","didRun","sequenceNumbersCollected","targetsRemoved","documentsRemoved","__PRIVATE_LRU_DEFAULT_CACHE_SIZE_BYTES","LruParams","withCacheSize","cacheSize","DEFAULT_COLLECTION_PERCENTILE","DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT","cacheSizeCollectionThreshold","percentileToCollect","maximumSequenceNumbersToCollect","removeMutationBatch","__PRIVATE_mutationStore","__PRIVATE_indexTxn","__PRIVATE_numDeleted","__PRIVATE_removePromise","__PRIVATE_indexKey","__PRIVATE_dbDocumentSize","DEFAULT","DISABLED","__PRIVATE_IndexedDbMutationQueue","referenceDelegate","__PRIVATE_documentKeysByBatchId","checkEmpty","NEGATIVE_INFINITY","__PRIVATE_mutationsStore","addMutationBatch","__PRIVATE_documentStore","__PRIVATE_documentMutationsStore","__PRIVATE_toDbMutationBatch","__PRIVATE_serializedBaseMutations","__PRIVATE_serializedMutations","__PRIVATE_collectionParents","lookupMutationBatch","__PRIVATE_lookupMutationKeys","getNextMutationBatchAfterBatchId","__PRIVATE_nextBatchId","__PRIVATE_foundBatch","getHighestUnacknowledgedBatchId","getAllMutationBatches","__PRIVATE_dbBatches","getAllMutationBatchesAffectingDocumentKey","__PRIVATE_indexPrefix","__PRIVATE_indexStart","__PRIVATE_userID","__PRIVATE_encodedPath","getAllMutationBatchesAffectingDocumentKeys","__PRIVATE_uniqueBatchIDs","__PRIVATE_batchID","__PRIVATE_lookupMutationBatches","getAllMutationBatchesAffectingQuery","__PRIVATE_queryPath","__PRIVATE_immediateChildrenLength","__PRIVATE_batchIDs","__PRIVATE_removeCachedMutationKeys","markPotentiallyOrphaned","performConsistencyCheck","__PRIVATE_startRange","__PRIVATE_newDbDocumentMutationPrefixForUser","__PRIVATE_danglingMutationReferences","__PRIVATE_danglingKeys","containsKey","__PRIVATE_mutationQueueContainsKey","__PRIVATE_getMutationQueueMetadata","__PRIVATE_mutationQueuesStore","lastAcknowledgedBatchId","lastStreamToken","keyPath","__PRIVATE_TargetIdGenerator","__PRIVATE_lastId","__PRIVATE_forTargetCache","__PRIVATE_forSyncEngine","__PRIVATE_IndexedDbTargetCache","allocateTargetId","__PRIVATE_retrieveMetadata","__PRIVATE_targetIdGenerator","highestTargetId","__PRIVATE_saveMetadata","getLastRemoteSnapshotVersion","lastRemoteSnapshotVersion","getHighestSequenceNumber","__PRIVATE_targetGlobal","highestListenSequenceNumber","setTargetsMetadata","addTargetData","__PRIVATE_saveTargetData","targetCount","__PRIVATE_updateMetadataFromTargetData","updateTargetData","removeTargetData","removeMatchingKeysForTargetId","__PRIVATE_targetsStore","removeTargets","activeTargetIds","__PRIVATE_globalTargetStore","updated","getTargetCount","getTargetData","addMatchingKeys","__PRIVATE_documentTargetStore","addReference","removeMatchingKeys","removeReference","getMatchingKeysForTargetId","__PRIVATE_LRU_MINIMUM_CACHE_SIZE_BYTES","__PRIVATE_bufferEntryComparator","__PRIVATE_aSequence","__PRIVATE_aIndex","__PRIVATE_bSequence","__PRIVATE_bIndex","__PRIVATE_seqCmp","__PRIVATE_RollingSequenceNumberBuffer","__PRIVATE_maxElements","__PRIVATE_previousIndex","__PRIVATE_nextIndex","__PRIVATE_addElement","__PRIVATE_highestValue","maxValue","__PRIVATE_LruScheduler","garbageCollector","__PRIVATE_gcTask","params","__PRIVATE_scheduleGC","collectGarbage","__PRIVATE_LruGarbageCollectorImpl","__PRIVATE_delegate","calculateTargetCount","percentile","__PRIVATE_getSequenceNumberCount","nthSequenceNumber","__PRIVATE_forEachOrphanedDocumentSequenceNumber","removeOrphanedDocuments","collect","getCacheSize","__PRIVATE_runGarbageCollection","__PRIVATE_upperBoundSequenceNumber","__PRIVATE_sequenceNumbersToCollect","__PRIVATE_countedTargetsTs","__PRIVATE_foundUpperBoundTs","__PRIVATE_removedTargetsTs","__PRIVATE_removedDocumentsTs","__PRIVATE_startTs","__PRIVATE_sequenceNumbers","__PRIVATE_numTargetsRemoved","__PRIVATE_newLruGarbageCollector","__PRIVATE_IndexedDbLruDelegateImpl","__PRIVATE_docCountPromise","__PRIVATE_orphanedDocumentCount","getTargetCache","__PRIVATE_docCount","__PRIVATE_orphanedCount","__PRIVATE_forEachOrphanedDocument","__PRIVATE_writeSentinelKey","__PRIVATE_isPinned","__PRIVATE_mutationQueuesContainKey","__PRIVATE_changeBuffer","getRemoteDocumentCache","newChangeBuffer","__PRIVATE_documentCount","getEntry","removeEntry","__PRIVATE_sentinelKey","updateLimboDocument","__PRIVATE_nextPath","__PRIVATE_nextToReport","getSize","__PRIVATE_sentinelRow","RemoteDocumentChangeBuffer","changesApplied","addEntry","assertNotApplied","__PRIVATE_bufferedEntry","getFromCache","getAllFromCache","__PRIVATE_IndexedDbRemoteDocumentCacheImpl","setIndexManager","__PRIVATE_remoteDocumentsStore","__PRIVATE_dbReadTimeKey","updateMetadata","__PRIVATE_sizeDelta","getMetadata","byteSize","__PRIVATE_setMetadata","__PRIVATE_dbKey","__PRIVATE_dbRemoteDoc","__PRIVATE_maybeDecodeDocument","__PRIVATE_getSizedEntry","__PRIVATE_forEachDbEntry","__PRIVATE_getSizedEntries","__PRIVATE_sizeMap","__PRIVATE_dbKeyComparator","__PRIVATE_keyIter","__PRIVATE_potentialKey","getDocumentsMatchingQuery","mutatedDocs","__PRIVATE_endKey","__PRIVATE_dbRemoteDocs","incrementDocumentReadCount","getAllFromCollectionGroup","__PRIVATE_dbCollectionGroupKey","__PRIVATE_IndexedDbRemoteDocumentChangeBuffer","trackRemovals","__PRIVATE_documentGlobalStore","__PRIVATE_newIndexedDbRemoteDocumentCache","__PRIVATE_documentCache","__PRIVATE_previousDoc","__PRIVATE_documentStates","__PRIVATE_deletedDoc","__PRIVATE_getResult","OverlayedDocument","LocalDocumentsView","remoteDocumentCache","mutationQueue","documentOverlayCache","getDocument","getDocuments","getLocalViewOfDocuments","existenceStateChanged","populateOverlays","computeViews","__PRIVATE_computeViewsResult","getOverlayedDocuments","__PRIVATE_missingOverlays","__PRIVATE_recalculateDocuments","__PRIVATE_newOverlayedDocumentMap","recalculateAndSaveOverlays","__PRIVATE_recalculatedFields","__PRIVATE_masks","__PRIVATE_documentsByBatchId","key1","key2","__PRIVATE_processed","__PRIVATE_batches","__PRIVATE_baseDoc","__PRIVATE_newSet","recalculateAndSaveOverlaysForDocumentKeys","getDocumentsMatchingDocumentQuery","getDocumentsMatchingCollectionGroupQuery","getDocumentsMatchingCollectionQuery","__PRIVATE_originalDocs","__PRIVATE_overlaysPromise","__PRIVATE_modifiedDocs","__PRIVATE_localDocs","__PRIVATE_parents","__PRIVATE_collectionQuery","__PRIVATE_asCollectionQueryAtPath","__PRIVATE_remoteDocuments","__PRIVATE_MemoryBundleCache","__PRIVATE_bundles","__PRIVATE_fromBundleMetadata","__PRIVATE_namedQueries","__PRIVATE_fromProtoNamedQuery","namedQuery","__PRIVATE_MemoryDocumentOverlayCache","__PRIVATE_overlayByBatchId","__PRIVATE_immediateChildrenPathLength","__PRIVATE_batchIdToOverlays","__PRIVATE_overlaysForBatchId","__PRIVATE_batchIter","__PRIVATE_existing","__PRIVATE_MemoryGlobalsCache","__PRIVATE_ReferenceSet","__PRIVATE_refsByKey","__PRIVATE_DocReference","__PRIVATE_compareByKey","__PRIVATE_refsByTarget","__PRIVATE_compareByTargetId","ref","__PRIVATE_addReferences","__PRIVATE_removeRef","__PRIVATE_removeReferences","__PRIVATE_removeReferencesForId","__PRIVATE_emptyKey","__PRIVATE_startRef","__PRIVATE_endRef","__PRIVATE_removeAllReferences","__PRIVATE_referencesForId","__PRIVATE_firstRef","__PRIVATE_targetOrBatchId","__PRIVATE_MemoryMutationQueue","__PRIVATE_batchesByDocumentKey","__PRIVATE_findMutationBatch","__PRIVATE_rawIndex","__PRIVATE_indexOfBatchId","__PRIVATE_findMutationBatches","__PRIVATE_startPath","__PRIVATE_rowKeyPath","__PRIVATE_indexOfExistingBatchId","shift","__PRIVATE_references","__PRIVATE_MemoryRemoteDocumentCacheImpl","__PRIVATE_sizer","__PRIVATE_documentEntryMap","__PRIVATE_forEachDocumentKey","__PRIVATE_MemoryRemoteDocumentChangeBuffer","__PRIVATE_MemoryTargetCache","__PRIVATE_highestSequenceNumber","__PRIVATE_removals","__PRIVATE_matchingKeys","__PRIVATE_MemoryPersistence","__PRIVATE_referenceDelegateFactory","__PRIVATE_mutationQueues","__PRIVATE_listenSequence","__PRIVATE__started","__PRIVATE_globalsCache","__PRIVATE_targetCache","__PRIVATE_newMemoryRemoteDocumentCache","__PRIVATE_documentSize","__PRIVATE_bundleCache","setDatabaseDeletedListener","setNetworkEnabled","getIndexManager","getDocumentOverlayCache","getMutationQueue","__PRIVATE_queue","getGlobalsCache","getBundleCache","transactionOperation","__PRIVATE_MemoryTransaction","__PRIVATE_onTransactionStarted","__PRIVATE_onTransactionCommitted","__PRIVATE_MemoryEagerDelegate","__PRIVATE__orphanedDocuments","__PRIVATE_factory","__PRIVATE_orphanedDocuments","__PRIVATE_localViewReferences","cache","__PRIVATE_isReferenced","__PRIVATE_MemoryLruDelegate","__PRIVATE_lruParams","__PRIVATE_orphanedSequenceNumbers","__PRIVATE_orphanedAt","__PRIVATE_SchemaConverter","__PRIVATE_createPrimaryClientStore","createObjectStore","__PRIVATE_createMutationQueue","__PRIVATE_mutationBatchesStore","autoIncrement","createIndex","unique","__PRIVATE_createQueryCache","__PRIVATE_createLegacyRemoteDocumentCache","__PRIVATE_dropQueryCache","deleteObjectStore","__PRIVATE_writeEmptyTargetGlobalEntry","__PRIVATE_globalStore","__PRIVATE_upgradeMutationBatchSchemaAndMigrateData","__PRIVATE_v1MutationsStore","__PRIVATE_existingMutations","__PRIVATE_v3MutationsStore","__PRIVATE_writeAll","__PRIVATE_createClientMetadataStore","__PRIVATE_removeAcknowledgedMutations","__PRIVATE_createDocumentGlobalStore","__PRIVATE_addDocumentGlobal","__PRIVATE_ensureSequenceNumbers","__PRIVATE_createCollectionParentIndex","__PRIVATE_dropRemoteDocumentChangesStore","__PRIVATE_rewriteCanonicalIds","__PRIVATE_createBundlesStore","__PRIVATE_createNamedQueriesStore","__PRIVATE_createDocumentOverlayStore","__PRIVATE_createRemoteDocumentCache","__PRIVATE_remoteDocumentStore","__PRIVATE_rewriteRemoteDocumentCache","__PRIVATE_runOverlayMigration","__PRIVATE_createFieldIndex","__PRIVATE_indexEntryStore","clear","__PRIVATE_createGlobalsStore","__PRIVATE_queuesStore","__PRIVATE_queues","__PRIVATE_documentsStore","__PRIVATE_docSentinelKey","__PRIVATE_maybeSentinel","pathSegments","__PRIVATE_targetStore","__PRIVATE_originalDbTarget","__PRIVATE_originalTargetData","__PRIVATE_updatedDbTarget","__PRIVATE_legacyRemoteDocumentStore","writes","__PRIVATE_legacyDocument","__PRIVATE_extractKey","__PRIVATE_dbRemoteDocument","__PRIVATE_memoryPersistence","__PRIVATE_userToDocumentSet","__PRIVATE_documentSet","__PRIVATE_allDocumentKeysForUser","__PRIVATE_MAX_CLIENT_AGE_MS","__PRIVATE_MAX_PRIMARY_ELIGIBLE_AGE_MS","__PRIVATE_PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG","__PRIVATE_MAIN_DATABASE","__PRIVATE_IndexedDbPersistence","allowTabSynchronization","clientId","window","__PRIVATE_forceOwningTab","__PRIVATE_schemaVersion","isPrimary","networkEnabled","__PRIVATE_windowUnloadHandler","inForeground","__PRIVATE_documentVisibilityHandler","__PRIVATE_clientMetadataRefresher","__PRIVATE_primaryStateListener","__PRIVATE_dbName","__PRIVATE_simpleDb","localStorage","__PRIVATE_webStorage","__PRIVATE_updateClientMetadataAndTryBecomePrimary","__PRIVATE_attachVisibilityHandler","__PRIVATE_attachWindowUnloadHook","__PRIVATE_scheduleClientMetadataAndPrimaryLeaseRefreshes","reason","__PRIVATE_setPrimaryStateListener","__PRIVATE_primaryState","databaseDeletedListener","newVersion","enqueueAndForget","__PRIVATE_clientMetadataStore","updateTimeMs","__PRIVATE_verifyPrimaryLease","__PRIVATE_success","__PRIVATE_canActAsPrimary","__PRIVATE_releasePrimaryLeaseIfHeld","__PRIVATE_acquireOrExtendPrimaryLease","__PRIVATE_primaryClientStore","__PRIVATE_primaryClient","__PRIVATE_isLocalClient","__PRIVATE_removeClientMetadata","__PRIVATE_maybeGarbageCollectMultiClientState","__PRIVATE_isWithinAge","__PRIVATE_lastGarbageCollectionTime","__PRIVATE_inactiveClients","__PRIVATE_metadataStore","__PRIVATE_existingClients","active","__PRIVATE_filterActiveClients","__PRIVATE_inactive","__PRIVATE_client","__PRIVATE_inactiveClient","removeItem","__PRIVATE_zombiedClientLocalStorageKey","ownerId","__PRIVATE_currentPrimary","leaseTimestampMs","__PRIVATE_isClientZombied","__PRIVATE_otherClient","__PRIVATE_otherClientHasBetterNetworkState","__PRIVATE_otherClientHasBetterVisibility","__PRIVATE_otherClientHasSameNetworkState","__PRIVATE_markClientZombied","__PRIVATE_detachVisibilityHandler","__PRIVATE_detachWindowUnloadHook","__PRIVATE_simpleDbTxn","__PRIVATE_persistenceTransaction","__PRIVATE_removeClientZombiedEntry","__PRIVATE_clients","__PRIVATE_activityThresholdMs","__PRIVATE_getActiveClients","__PRIVATE_clientMetadata","__PRIVATE_simpleDbMode","__PRIVATE_getObjectStores","__PRIVATE_holdsPrimaryLease","__PRIVATE_verifyAllowTabSynchronization","__PRIVATE_newPrimary","__PRIVATE_maxAgeMs","addEventListener","visibilityState","removeEventListener","__PRIVATE_safariIndexdbBugVersionRegex","isSafari","navigator","appVersion","userAgent","enterRestrictedMode","__PRIVATE_isZombied","getItem","setItem","__PRIVATE_indexedDbStoragePrefix","__PRIVATE_LocalViewChanges","fromCache","__PRIVATE_addedKeys","__PRIVATE_removedKeys","__PRIVATE_fromSnapshot","__PRIVATE_viewSnapshot","docChanges","QueryContext","_documentReadCount","documentReadCount","amount","__PRIVATE_QueryEngine","__PRIVATE_initialized","__PRIVATE_indexAutoCreationEnabled","__PRIVATE_indexAutoCreationMinCollectionSize","__PRIVATE_relativeIndexReadCostPerDocument","__PRIVATE_getDefaultRelativeIndexReadCostPerDocument","initialize","__PRIVATE_localDocumentsView","__PRIVATE_remoteKeys","__PRIVATE_queryResult","__PRIVATE_performQueryUsingIndex","__PRIVATE_performQueryUsingRemoteKeys","__PRIVATE_executeFullCollectionScan","__PRIVATE_createCacheIndexes","__PRIVATE_resultSize","__PRIVATE_indexedDocuments","__PRIVATE_previousResults","__PRIVATE_applyQuery","__PRIVATE_needsRefill","__PRIVATE_appendRemainingResults","__PRIVATE_queryResults","__PRIVATE_maybeDoc","__PRIVATE_sortedPreviousResults","__PRIVATE_limboFreeSnapshotVersion","__PRIVATE_docAtLimitEdge","__PRIVATE_indexedResults","__PRIVATE_remainingResults","d","__PRIVATE_RESUME_TOKEN_MAX_AGE_MICROS","__PRIVATE_LocalStoreImpl","__PRIVATE_queryEngine","initialUser","__PRIVATE_targetDataByTarget","__PRIVATE_targetIdByTarget","__PRIVATE_initializeUserComponents","__PRIVATE_newLocalStore","__PRIVATE_localStoreHandleUserChange","__PRIVATE_localStoreImpl","__PRIVATE_oldBatches","__PRIVATE_promisedOldBatches","__PRIVATE_newBatches","removedBatchIds","addedBatchIds","__PRIVATE_changedKeys","__PRIVATE_affectedDocuments","__PRIVATE_localStoreAcknowledgeBatch","__PRIVATE_affected","__PRIVATE_documentBuffer","__PRIVATE_applyWriteToRemoteDocuments","__PRIVATE_docKeys","__PRIVATE_promiseChain","__PRIVATE_ackVersion","__PRIVATE_getKeysWithTransformResults","__PRIVATE_localStoreGetLastRemoteSnapshotVersion","__PRIVATE_localStoreApplyRemoteEventToLocalCache","__PRIVATE_remoteVersion","__PRIVATE_newTargetDataByTargetMap","__PRIVATE_oldTargetData","__PRIVATE_newTargetData","__PRIVATE_shouldPersistTargetData","__PRIVATE_timeDelta","__PRIVATE_changedDocs","__PRIVATE_existenceChangedKeys","__PRIVATE_populateDocumentChangeBuffer","__PRIVATE_changedDocuments","__PRIVATE_updateRemoteVersion","__PRIVATE_updatedKeys","__PRIVATE_existingDocs","__PRIVATE_existingDoc","__PRIVATE_localStoreGetNextMutationBatch","__PRIVATE_afterBatchId","__PRIVATE_localStoreAllocateTarget","__PRIVATE_cached","__PRIVATE_cachedTargetData","__PRIVATE_localStoreReleaseTarget","__PRIVATE_keepPersistedTargetData","__PRIVATE_localStoreExecuteQuery","__PRIVATE_usePreviousResults","__PRIVATE_localStoreGetTargetData","__PRIVATE_setMaxReadTime","__PRIVATE_localStoreGetCachedTarget","__PRIVATE_targetCacheImpl","__PRIVATE_localStoreGetNewDocumentChanges","__PRIVATE_collectionGroupReadTime","__PRIVATE_localStoreApplyBundledDocuments","__PRIVATE_bundleConverter","bundleName","__PRIVATE_bundleDoc","__PRIVATE_toDocumentKey","__PRIVATE_toMutableDocument","__PRIVATE_toSnapshotVersion","__PRIVATE_umbrellaTargetData","__PRIVATE_umbrellaTarget","__PRIVATE_documentChangeResult","__PRIVATE_localStoreSaveNamedQuery","__PRIVATE_allocated","CLIENT_STATE_KEY_PREFIX","createWebStorageClientStateKey","MUTATION_BATCH_KEY_PREFIX","createWebStorageMutationBatchKey","__PRIVATE_mutationKey","QUERY_TARGET_KEY_PREFIX","createWebStorageQueryTargetMetadataKey","__PRIVATE_MutationMetadata","__PRIVATE_fromWebStorageEntry","__PRIVATE_mutationBatch","parse","__PRIVATE_firestoreError","__PRIVATE_validData","__PRIVATE_toWebStorageJSON","__PRIVATE_batchMetadata","__PRIVATE_QueryTargetMetadata","__PRIVATE_RemoteClientState","__PRIVATE_clientState","__PRIVATE_activeTargetIdsSet","__PRIVATE_SharedOnlineState","onlineState","__PRIVATE_LocalClientState","__PRIVATE_addQueryTarget","__PRIVATE_removeQueryTarget","__PRIVATE_WebStorageSharedClientState","__PRIVATE_localClientId","syncEngine","onlineStateHandler","__PRIVATE_storageListener","__PRIVATE_handleWebStorageEvent","bind","__PRIVATE_activeClients","__PRIVATE_earlyEvents","__PRIVATE_escapedPersistenceKey","storage","__PRIVATE_localClientStorageKey","__PRIVATE_sequenceNumberKey","createWebStorageSequenceNumberKey","__PRIVATE_clientStateKeyRe","__PRIVATE_mutationBatchKeyRe","__PRIVATE_queryTargetKeyRe","__PRIVATE_onlineStateKey","createWebStorageOnlineStateKey","__PRIVATE_bundleLoadedKey","createBundleLoadedKey","__PRIVATE_storageItem","__PRIVATE_persistClientState","__PRIVATE_onlineStateJSON","__PRIVATE_fromWebStorageOnlineState","__PRIVATE_handleOnlineStateEvent","getAllActiveQueryTargets","__PRIVATE_extractActiveQueryTargets","isActiveQueryTarget","addPendingMutation","__PRIVATE_persistMutationState","updateMutationState","__PRIVATE_removeMutationState","addLocalQueryTarget","addToActiveTargetIds","__PRIVATE_queryState","__PRIVATE_localClientState","removeLocalQueryTarget","isLocalQueryTarget","clearQueryState","updateQueryState","__PRIVATE_persistQueryTargetState","handleUserChange","setOnlineState","__PRIVATE_persistOnlineState","notifyBundleLoaded","collectionGroups","__PRIVATE_persistBundleLoadedState","__PRIVATE_storageEvent","storageArea","__PRIVATE_fromWebStorageClientStateKey","__PRIVATE_handleClientStateEvent","__PRIVATE_fromWebStorageClientState","__PRIVATE_mutationMetadata","__PRIVATE_fromWebStorageMutationMetadata","__PRIVATE_handleMutationBatchEvent","__PRIVATE_queryTargetMetadata","__PRIVATE_fromWebStorageQueryTargetMetadata","__PRIVATE_handleQueryTargetEvent","__PRIVATE_fromWebStorageSequenceNumber","__PRIVATE_seqString","__PRIVATE_parsed","__PRIVATE_fromWebStoreBundleLoadedState","__PRIVATE_cg","__PRIVATE_synchronizeWithChangedDocuments","__PRIVATE_mutationState","__PRIVATE_targetKey","__PRIVATE_targetMetadata","__PRIVATE_applyBatchState","__PRIVATE_applyTargetState","__PRIVATE_updatedClients","__PRIVATE_existingTargets","__PRIVATE_newTargets","__PRIVATE_addedTargets","__PRIVATE_removedTargets","__PRIVATE_applyActiveTargetsChange","__PRIVATE_activeTargets","__PRIVATE_kev","__PRIVATE_MemorySharedClientState","__PRIVATE_localState","__PRIVATE_NoopConnectivityMonitor","__PRIVATE_addCallback","__PRIVATE_BrowserConnectivityMonitor","__PRIVATE_networkAvailableListener","__PRIVATE_onNetworkAvailable","__PRIVATE_networkUnavailableListener","__PRIVATE_onNetworkUnavailable","__PRIVATE_callbacks","__PRIVATE_configureNetworkMonitoring","__PRIVATE_lastUniqueDebugId","__PRIVATE_generateUniqueDebugId","__PRIVATE_generateInitialUniqueDebugId","round","__PRIVATE_maxResult","__PRIVATE_RPC_NAME_URL_MAPPING","__PRIVATE_RestConnection","__PRIVATE_shouldResourcePathBeIncludedInRequest","databaseInfo","__PRIVATE_baseUrl","__PRIVATE_databasePath","__PRIVATE_requestParams","__PRIVATE_invokeRPC","__PRIVATE_rpcName","__PRIVATE_req","__PRIVATE_authToken","streamId","url","__PRIVATE_makeUrl","__PRIVATE_modifyHeadersForRequest","URL","__PRIVATE_forwardCredentials","isCloudWorkstation","__PRIVATE_performRPCRequest","response","__PRIVATE_invokeStreamingRPC","__PRIVATE_expectedResponseCount","__PRIVATE_getGoogApiClientValue","__PRIVATE_urlRpcName","terminate","__PRIVATE_StreamBridge","__PRIVATE_sendFn","__PRIVATE_closeFn","__PRIVATE_onConnected","__PRIVATE_wrappedOnConnected","__PRIVATE_onOpen","__PRIVATE_wrappedOnOpen","__PRIVATE_onClose","__PRIVATE_wrappedOnClose","onMessage","__PRIVATE_wrappedOnMessage","send","__PRIVATE_callOnConnected","__PRIVATE_callOnOpen","__PRIVATE_callOnClose","__PRIVATE_callOnMessage","__PRIVATE_WebChannelConnection","info","__PRIVATE_openWebChannels","body","__PRIVATE__forwardCredentials","__PRIVATE_xhr","XhrIo","setWithCredentials","listenOnce","EventType","COMPLETE","getLastErrorCode","ErrorCode","NO_ERROR","getResponseJson","TIMEOUT","HTTP_ERROR","getStatus","getResponseText","__PRIVATE_responseError","__PRIVATE_firestoreErrorCode","__PRIVATE_mapCodeFromHttpResponseErrorStatus","__PRIVATE_serverError","toLowerCase","__PRIVATE_lastErrorCode","__PRIVATE_lastError","getLastError","__PRIVATE_requestString","__PRIVATE_openStream","__PRIVATE_urlParts","__PRIVATE_webchannelTransport","createWebChannelTransport","__PRIVATE_requestStats","getStatEventTarget","httpSessionIdParam","initMessageHeaders","messageUrlParams","sendRawJson","supportsCrossDomainXhr","internalChannelParams","forwardChannelRequestTimeoutMs","detectBufferingProxy","__PRIVATE_longPollingTimeoutSeconds","timeoutSeconds","longPollingTimeout","encodeInitMessageHeaders","channel","createWebChannel","__PRIVATE_addOpenWebChannel","__PRIVATE_opened","closed","__PRIVATE_streamBridge","__PRIVATE_unguardedEventListen","listen","param","WebChannel","OPEN","CLOSE","__PRIVATE_removeOpenWebChannel","MESSAGE","__PRIVATE_msgData","__PRIVATE_msgDataOrError","__PRIVATE_mapCodeFromRpcStatus","Event","STAT_EVENT","stat","Stat","PROXY","NOPROXY","__PRIVATE_webChannel","instance","__PRIVATE_getWindow","__PRIVATE_newSerializer","__PRIVATE_ExponentialBackoff","timerId","__PRIVATE_initialDelayMs","__PRIVATE_backoffFactor","__PRIVATE_maxDelayMs","__PRIVATE_currentBaseMs","__PRIVATE_timerPromise","__PRIVATE_resetToMax","__PRIVATE_backoffAndRun","__PRIVATE_desiredDelayWithJitterMs","__PRIVATE_jitterDelayMs","__PRIVATE_delaySoFarMs","__PRIVATE_lastAttemptTime","__PRIVATE_remainingDelayMs","__PRIVATE_skipBackoff","skipDelay","__PRIVATE_PersistentStream","__PRIVATE_connectionTimerId","__PRIVATE_idleTimerId","__PRIVATE_healthTimerId","connection","authCredentialsProvider","appCheckCredentialsProvider","__PRIVATE_closeCount","__PRIVATE_idleTimer","__PRIVATE_healthCheck","stream","__PRIVATE_responseCount","__PRIVATE_backoff","__PRIVATE_isStarted","__PRIVATE_isOpen","__PRIVATE_performBackoff","__PRIVATE_inhibitBackoff","__PRIVATE_markIdle","__PRIVATE_handleIdleCloseTimer","__PRIVATE_sendRequest","__PRIVATE_cancelIdleCheck","__PRIVATE_cancelHealthCheck","__PRIVATE_finalState","__PRIVATE_tearDown","__PRIVATE_dispatchIfNotClosed","__PRIVATE_getCloseGuardedDispatcher","__PRIVATE_startStream","__PRIVATE_rpcError","__PRIVATE_handleStreamClose","__PRIVATE_startRpc","__PRIVATE_onFirst","onNext","__PRIVATE_startCloseCount","__PRIVATE_PersistentListenStream","authCredentials","appCheckCredentials","__PRIVATE_watchChangeProto","snapshot","__PRIVATE_versionFromListenResponse","__PRIVATE_onWatchChange","__PRIVATE_watch","addTarget","__PRIVATE_toTarget","labels","__PRIVATE_unwatch","__PRIVATE_PersistentWriteStream","__PRIVATE_handshakeComplete","__PRIVATE_writeMutations","__PRIVATE_responseProto","streamToken","writeResults","__PRIVATE_onHandshakeComplete","__PRIVATE_onMutationResult","__PRIVATE_writeHandshake","Datastore","__PRIVATE_DatastoreImpl","__PRIVATE_terminated","__PRIVATE_verifyInitialized","__PRIVATE_OnlineStateTracker","__PRIVATE_watchStreamFailures","__PRIVATE_onlineStateTimer","__PRIVATE_shouldWarnClientIsOffline","__PRIVATE_handleWatchStreamStart","__PRIVATE_setAndBroadcast","__PRIVATE_logClientOfflineWarningIfNecessary","__PRIVATE_handleWatchStreamFailure","__PRIVATE_clearOnlineStateTimer","newState","details","__PRIVATE_RemoteStoreImpl","datastore","__PRIVATE_connectivityMonitor","remoteSyncer","__PRIVATE_writePipeline","__PRIVATE_onNetworkStatusChange","__PRIVATE_canUseNetwork","__PRIVATE_restartNetwork","remoteStore","__PRIVATE_remoteStoreImpl","__PRIVATE_offlineCauses","__PRIVATE_disableNetworkInternal","__PRIVATE_onlineStateTracker","__PRIVATE_enableNetworkInternal","__PRIVATE_networkStatusHandler","__PRIVATE_remoteStoreListen","__PRIVATE_listenTargets","__PRIVATE_shouldStartWatchStream","__PRIVATE_startWatchStream","__PRIVATE_ensureWatchStream","__PRIVATE_sendWatchRequest","__PRIVATE_remoteStoreUnlisten","__PRIVATE_watchStream","__PRIVATE_sendUnwatchRequest","__PRIVATE_watchChangeAggregator","__PRIVATE_cleanUpWatchStreamState","__PRIVATE_onWatchStreamConnected","__PRIVATE_onWatchStreamOpen","__PRIVATE_onWatchStreamClose","__PRIVATE_onWatchStreamChange","__PRIVATE_handleTargetError","rejectListen","__PRIVATE_disableNetworkUntilRecovery","__PRIVATE_raiseWatchSnapshot","__PRIVATE_targetPurpose","__PRIVATE_requestTargetData","applyRemoteEvent","__PRIVATE_executeWithRecovery","__PRIVATE_fillWritePipeline","__PRIVATE_writeStream","__PRIVATE_ensureWriteStream","__PRIVATE_lastBatchIdRetrieved","__PRIVATE_canAddToWritePipeline","__PRIVATE_addToWritePipeline","__PRIVATE_shouldStartWriteStream","__PRIVATE_startWriteStream","__PRIVATE_onWriteStreamOpen","__PRIVATE_onWriteHandshakeComplete","applySuccessfulWrite","__PRIVATE_onWriteStreamClose","__PRIVATE_handleWriteError","__PRIVATE_isPermanentWriteError","rejectFailedWrite","__PRIVATE_remoteStoreHandleCredentialChange","verifyOperationInProgress","__PRIVATE_usesNetwork","handleCredentialChange","__PRIVATE_remoteStoreApplyPrimaryState","__PRIVATE_newPersistentWatchStream","__PRIVATE_datastoreImpl","enabled","__PRIVATE_newPersistentWriteStream","DelayedOperation","targetTimeMs","removalCallback","deferred","createAndSchedule","delayMs","__PRIVATE_targetTime","__PRIVATE_delayedOp","timerHandle","handleDelayElapsed","clearTimeout","__PRIVATE_wrapInUserErrorIfRecoverable","DocumentSet","emptySet","oldSet","keyedMap","sortedSet","__PRIVATE_thisDoc","__PRIVATE_otherDoc","__PRIVATE_docStrings","__PRIVATE_DocumentChangeSet","__PRIVATE_changeMap","track","__PRIVATE_oldChange","__PRIVATE_getChanges","ViewSnapshot","oldDocs","mutatedKeys","syncStateChanged","excludesMetadataChanges","hasCachedResults","fromInitialDocuments","__PRIVATE_otherChanges","__PRIVATE_QueryListenersInfo","__PRIVATE_viewSnap","__PRIVATE_listeners","__PRIVATE_hasRemoteListeners","__PRIVATE_listensToRemoteStore","__PRIVATE_EventManagerImpl","queries","__PRIVATE_newQueriesObjectMap","__PRIVATE_errorAllTargets","eventManager","__PRIVATE_eventManagerImpl","__PRIVATE_queryInfo","onError","q","__PRIVATE_eventManagerListen","__PRIVATE_listenerAction","onListen","onFirstRemoteStoreListen","__PRIVATE_applyOnlineStateChange","__PRIVATE_onViewSnapshot","__PRIVATE_raiseSnapshotsInSyncEvent","__PRIVATE_eventManagerUnlisten","onUnlisten","onLastRemoteStoreUnlisten","__PRIVATE_eventManagerOnWatchChange","__PRIVATE_viewSnaps","__PRIVATE_raisedEvent","__PRIVATE_eventManagerOnWatchError","__PRIVATE_snapshotsInSyncListeners","observer","__PRIVATE_ListenerDataSource","ListenerDataSource","__PRIVATE_QueryListener","__PRIVATE_queryObserver","__PRIVATE_raisedInitialEvent","__PRIVATE_snap","includeMetadataChanges","__PRIVATE_shouldRaiseEvent","__PRIVATE_shouldRaiseInitialEvent","__PRIVATE_raiseInitialEvent","__PRIVATE_maybeOnline","__PRIVATE_waitForSyncWhenOnline","__PRIVATE_hasPendingWritesChanged","Cache","__PRIVATE_SizedBundleElement","__PRIVATE_payload","byteLength","__PRIVATE_isBundleMetadata","__PRIVATE_BundleConverterImpl","__PRIVATE_bundledDoc","time","__PRIVATE_BundleLoader","__PRIVATE__queries","__PRIVATE__documents","progress","__PRIVATE_bundleInitialProgress","__PRIVATE_addSizedElement","bytesLoaded","documentsLoaded","documentMetadata","__PRIVATE_getQueryDocumentMapping","__PRIVATE_queryDocumentMap","__PRIVATE_completeAndStoreAsync","taskState","__PRIVATE_changedCollectionGroups","totalDocuments","totalBytes","__PRIVATE_AddedLimboDocument","__PRIVATE_RemovedLimboDocument","__PRIVATE_View","__PRIVATE__syncedDocuments","__PRIVATE_syncState","__PRIVATE_limboDocuments","__PRIVATE_docComparator","__PRIVATE_syncedDocuments","__PRIVATE_computeDocChanges","__PRIVATE_previousChanges","__PRIVATE_changeSet","__PRIVATE_oldDocumentSet","__PRIVATE_newMutatedKeys","__PRIVATE_newDocumentSet","__PRIVATE_lastDocInLimit","__PRIVATE_firstDocInLimit","__PRIVATE_oldDoc","__PRIVATE_oldDocHadPendingMutations","__PRIVATE_newDocHasPendingMutations","__PRIVATE_changeApplied","__PRIVATE_shouldWaitForSyncedDocument","__PRIVATE_limboResolutionEnabled","__PRIVATE_targetIsPendingReset","__PRIVATE_c1","__PRIVATE_c2","__PRIVATE_compareChangeType","__PRIVATE_applyTargetChange","__PRIVATE_limboChanges","__PRIVATE_updateLimboDocuments","__PRIVATE_newSyncState","__PRIVATE_shouldBeInLimbo","__PRIVATE_oldLimboDocuments","__PRIVATE_synchronizeWithPersistedState","__PRIVATE_computeInitialSnapshot","__PRIVATE_QueryView","view","LimboResolution","__PRIVATE_receivedDocument","__PRIVATE_SyncEngineImpl","sharedClientState","maxConcurrentLimboResolutions","__PRIVATE_syncEngineListener","__PRIVATE_queryViewsByQuery","__PRIVATE_activeLimboTargetsByKey","__PRIVATE_mutationUserCallbacks","__PRIVATE__isPrimaryClient","isPrimaryClient","__PRIVATE_syncEngineListen","__PRIVATE_shouldListenToRemote","__PRIVATE_syncEngineImpl","__PRIVATE_ensureWatchCallbacks","__PRIVATE_queryView","__PRIVATE_allocateTargetAndMaybeListen","__PRIVATE_triggerRemoteStoreListen","__PRIVATE_shouldInitializeView","__PRIVATE_initializeViewAndComputeSnapshot","__PRIVATE_applyDocChanges","__PRIVATE_viewDocChanges","__PRIVATE_viewChange","__PRIVATE_updateTrackedLimbos","__PRIVATE_synthesizedTargetChange","__PRIVATE_queriesByTarget","__PRIVATE_syncEngineUnlisten","__PRIVATE_shouldUnlistenToRemote","__PRIVATE_removeAndCleanupTarget","__PRIVATE_triggerRemoteStoreUnlisten","__PRIVATE_syncEngineWrite","__PRIVATE_userCallback","__PRIVATE_syncEngineEnsureWriteCallbacks","__PRIVATE_localStoreWriteLocally","__PRIVATE_overlayedDocuments","__PRIVATE_remoteDocs","__PRIVATE_docsWithoutRemoteVersion","__PRIVATE_addMutationCallback","__PRIVATE_newCallbacks","__PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore","__PRIVATE_syncEngineApplyRemoteEvent","__PRIVATE_limboResolution","__PRIVATE_activeLimboResolutionsByTarget","__PRIVATE_syncEngineApplyOnlineStateChange","__PRIVATE_newViewSnapshots","__PRIVATE_eventManagerOnOnlineStateChange","__PRIVATE_syncEngineRejectListen","__PRIVATE_limboKey","__PRIVATE_pumpEnqueuedLimboResolutions","__PRIVATE_syncEngineApplySuccessfulWrite","__PRIVATE_mutationBatchResult","__PRIVATE_processUserCallback","__PRIVATE_triggerPendingWritesCallbacks","__PRIVATE_syncEngineRejectFailedWrite","__PRIVATE_localStoreRejectBatch","__PRIVATE_affectedKeys","__PRIVATE_syncEngineRegisterPendingWritesCallback","__PRIVATE_highestBatchId","__PRIVATE_localStoreGetHighestUnacknowledgedBatchId","__PRIVATE_pendingWritesCallbacks","__PRIVATE_onWatchError","__PRIVATE_limboDocumentRefs","__PRIVATE_removeLimboTarget","__PRIVATE_enqueuedLimboResolutions","__PRIVATE_limboTargetId","__PRIVATE_limboChange","__PRIVATE_trackLimboChange","__PRIVATE_keyString","__PRIVATE_limboTargetIdGenerator","__PRIVATE_newSnaps","__PRIVATE_docChangesInAllViews","__PRIVATE_queriesProcessed","__PRIVATE_isCurrent","__PRIVATE_localStoreNotifyLocalViewChanges","__PRIVATE_viewChanges","__PRIVATE_updatedTargetData","__PRIVATE_syncEngineHandleCredentialChange","__PRIVATE_rejectOutstandingPendingWritesCallbacks","__PRIVATE_errorMessage","__PRIVATE_syncEngineGetRemoteKeysForTarget","__PRIVATE_keySet","__PRIVATE_synchronizeViewAndComputeSnapshot","__PRIVATE_syncEngineSynchronizeWithChangedDocuments","__PRIVATE_syncEngineApplyBatchState","__PRIVATE_batchState","__PRIVATE_localStoreLookupMutationDocuments","__PRIVATE_mutationQueueImpl","__PRIVATE_localStoreRemoveCachedMutationBatchMetadata","__PRIVATE_syncEngineApplyPrimaryState","__PRIVATE_activeQueries","__PRIVATE_synchronizeQueryViewsAndRaiseSnapshots","__PRIVATE_resetLimboDocuments","__PRIVATE_transitionToPrimary","__PRIVATE_synthesizeTargetToQuery","__PRIVATE_syncEngineGetActiveClients","__PRIVATE_localStoreGetActiveClients","__PRIVATE_syncEngineApplyTargetState","__PRIVATE_synthesizedRemoteEvent","__PRIVATE_syncEngineApplyActiveTargetsChange","__PRIVATE_syncEngineLoadBundle","__PRIVATE_bundleReader","__PRIVATE_loadBundleImpl","__PRIVATE_reader","__PRIVATE_localStoreHasNewerBundle","__PRIVATE_currentReadTime","_completeWith","__PRIVATE_bundleSuccessProgress","_updateProgress","__PRIVATE_loader","__PRIVATE_nextElement","__PRIVATE_localStoreSaveBundle","_failWith","__PRIVATE_MemoryOfflineComponentProvider","synchronizeTabs","cfg","__PRIVATE_createSharedClientState","__PRIVATE_createPersistence","__PRIVATE_createLocalStore","gcScheduler","__PRIVATE_createGarbageCollectionScheduler","indexBackfillerScheduler","__PRIVATE_createIndexBackfillerScheduler","provider","build","__PRIVATE_LruGcMemoryOfflineComponentProvider","cacheSizeBytes","__PRIVATE_IndexedDbOfflineComponentProvider","__PRIVATE_onlineComponentProvider","forceOwnership","__PRIVATE_indexBackfiller","__PRIVATE_MultiTabOfflineComponentProvider","OnlineComponentProvider","offlineComponentProvider","createDatastore","createRemoteStore","createEventManager","createSyncEngine","__PRIVATE_newEventManager","__PRIVATE_newConnection","__PRIVATE_newDatastore","__PRIVATE_newRemoteStore","__PRIVATE_newConnectivityMonitor","startAsPrimary","__PRIVATE_newSyncEngine","__PRIVATE_remoteStoreShutdown","__PRIVATE_toByteStreamReaderHelper","__PRIVATE_bytesPerRead","__PRIVATE_readFrom","read","releaseLock","__PRIVATE_AsyncObserver","muted","__PRIVATE_scheduleEvent","__PRIVATE_mute","__PRIVATE_eventHandler","__PRIVATE_BundleReaderImpl","__PRIVATE_textDecoder","__PRIVATE_newTextDecoder","TextDecoder","__PRIVATE_nextElementImpl","__PRIVATE_lengthBuffer","__PRIVATE_readLength","__PRIVATE_lengthString","decode","__PRIVATE_raiseError","__PRIVATE_jsonString","__PRIVATE_readJsonString","__PRIVATE_indexOfOpenBracket","findIndex","__PRIVATE_pullMoreDataToBuffer","__PRIVATE_BundleReaderSyncImpl","bundleData","__PRIVATE_getElements","__PRIVATE_startIndex","__PRIVATE_curIndex","Transaction","readVersions","committed","lastTransactionError","writtenDocs","lookup","ensureCommitNotCalled","__PRIVATE_invokeBatchGetDocumentsRpc","recordVersion","write","preconditionForUpdate","__PRIVATE_unwritten","__PRIVATE_invokeCommitRpc","__PRIVATE_docVersion","__PRIVATE_documentName","__PRIVATE_existingVersion","__PRIVATE_TransactionRunner","updateFunction","__PRIVATE_attemptsRemaining","maxAttempts","__PRIVATE_run","__PRIVATE_runWithBackOff","__PRIVATE_tryRunUpdateFunction","__PRIVATE_commitError","__PRIVATE_handleTransactionError","__PRIVATE_userPromiseError","__PRIVATE_isRetryableTransactionError","FirestoreClient","componentProvider","authCredentialListener","appCheckCredentialListener","_uninitializedComponentsProvider","__PRIVATE_newAppCheckToken","configuration","setCredentialChangeListener","setAppCheckTokenChangeListener","enqueueAndForgetEvenWhileRestricted","_onlineComponents","_offlineComponents","__PRIVATE_setOfflineComponentProvider","__PRIVATE_setOnlineComponentProvider","__PRIVATE_offlineComponents","__PRIVATE_ensureOfflineComponents","_offline","__PRIVATE_canFallbackFromIndexedDbError","DOMException","__PRIVATE_ensureOnlineComponents","_online","__PRIVATE_getPersistence","__PRIVATE_getLocalStore","__PRIVATE_getRemoteStore","__PRIVATE_getSyncEngine","__PRIVATE_getDatastore","__PRIVATE_getEventManager","__PRIVATE_firestoreClientEnableNetwork","enqueue","__PRIVATE_remoteStoreEnableNetwork","__PRIVATE_firestoreClientDisableNetwork","__PRIVATE_remoteStoreDisableNetwork","__PRIVATE_firestoreClientGetDocumentFromLocalCache","__PRIVATE_readDocumentFromCache","__PRIVATE_localStoreReadDocument","__PRIVATE_firestoreClientGetDocumentViaSnapshotListener","__PRIVATE_readDocumentViaSnapshotListener","__PRIVATE_wrappedObserver","__PRIVATE_firestoreClientGetDocumentsFromLocalCache","__PRIVATE_executeQueryFromCache","__PRIVATE_firestoreClientGetDocumentsViaSnapshotListener","__PRIVATE_executeQueryViaSnapshotListener","__PRIVATE_firestoreClientRunAggregateQuery","__PRIVATE_invokeRunAggregationQueryRpc","gt","__PRIVATE_filteredResult","__PRIVATE_unmappedAggregateFields","aggregateFields","__PRIVATE_accumulator","__PRIVATE_firestoreClientAddSnapshotsInSyncListener","__PRIVATE_addSnapshotsInSyncListener","__PRIVATE_removeSnapshotsInSyncListener","__PRIVATE_firestoreClientLoadBundle","__PRIVATE_resultTask","__PRIVATE_createBundleReader","content","__PRIVATE_newBundleReader","__PRIVATE_toByteStreamReader","ReadableStream","getReader","__PRIVATE_firestoreClientGetNamedQuery","__PRIVATE_localStoreGetNamedQuery","__PRIVATE_createBundleReaderSync","__PRIVATE_newBundleReaderSync","__PRIVATE_firestoreClientSetIndexConfiguration","__PRIVATE_localStoreConfigureFieldIndexes","__PRIVATE_newFieldIndexes","__PRIVATE_oldFieldIndexes","__PRIVATE_diffArrays","__PRIVATE_bLen","__PRIVATE_aLen","a","__PRIVATE_firestoreClientSetPersistentCacheIndexAutoCreationEnabled","isEnabled","__PRIVATE_localStoreSetIndexAutoCreationEnabled","__PRIVATE_firestoreClientDeleteAllFieldIndexes","__PRIVATE_localStoreDeleteAllFieldIndexes","__PRIVATE_cloneLongPollingOptions","__PRIVATE_datastoreInstances","__PRIVATE_DEFAULT_HOST","__PRIVATE_DEFAULT_SSL","FirestoreSettingsImpl","emulatorOptions","credentials","ignoreUndefinedProperties","localCache","experimentalForceLongPolling","experimentalAutoDetectLongPolling","experimentalLongPollingOptions","__PRIVATE_validateLongPollingOptions","__PRIVATE_longPollingOptionsEqual","__PRIVATE_options1","__PRIVATE_options2","Firestore","_authCredentials","_appCheckCredentials","_databaseId","_app","_persistenceKey","_settings","_settingsFrozen","_emulatorOptions","_terminateTask","_initialized","_terminated","_setSettings","__PRIVATE_makeAuthCredentialsProvider","_getSettings","_getEmulatorOptions","_freezeSettings","_delete","_terminate","_restart","__PRIVATE_removeComponents","firestore","connectFirestoreEmulator","port","__PRIVATE_useSsl","__PRIVATE_existingConfig","__PRIVATE_newHostSetting","pingServer","updateEmulatorBanner","__PRIVATE_newConfig","deepEqual","mockUserToken","createMockUserToken","sub","user_id","Query","converter","_query","withConverter","DocumentReference","_key","_path","CollectionReference","referencePath","getModularInstance","__PRIVATE_absolutePath","__PRIVATE_newQueryForCollectionGroup","arguments","refEqual","queryEqual","__PRIVATE_AsyncQueueImpl","__PRIVATE_tail","__PRIVATE_retryableOps","__PRIVATE__isShuttingDown","__PRIVATE_delayedOperations","__PRIVATE_operationInProgress","__PRIVATE_skipNonRestrictedTasks","__PRIVATE_timerIdsToSkip","__PRIVATE_visibilityHandler","isShuttingDown","__PRIVATE_verifyNotFailed","__PRIVATE_enqueueInternal","purgeExistingTasks","__PRIVATE_retryNextOp","__PRIVATE_newTail","__PRIVATE_getMessageOrStack","__PRIVATE_removedOp","__PRIVATE_removeDelayedOperation","__PRIVATE_messageOrStack","__PRIVATE_drain","__PRIVATE_currentTail","__PRIVATE_containsDelayedOperation","__PRIVATE_runAllDelayedOperationsUntil","__PRIVATE_lastTimerId","__PRIVATE_skipDelaysForTimerId","stack","includes","__PRIVATE_isPartialObserver","__PRIVATE_implementsAnyMethods","__PRIVATE_methods","object","method","LoadBundleTask","_progressObserver","_taskCompletionResolver","_lastProgress","onProgress","complete","onRejected","onFulfilled","CACHE_SIZE_UNLIMITED","__PRIVATE_LiteFirestore","_queue","_firestoreClient","initializeFirestore","_getProvider","isInitialized","__PRIVATE_existingInstance","identifier","__PRIVATE_initialSettings","getOptions","instanceIdentifier","getFirestore","__PRIVATE_appOrDatabaseId","__PRIVATE_optionalDatabaseId","getApp","__PRIVATE_emulator","getDefaultEmulatorHostnameAndPort","ensureFirestoreConfigured","__PRIVATE_configureFirestore","__PRIVATE_makeDatabaseInfo","_componentsProvider","_offlineComponentProvider","_onlineComponentProvider","__PRIVATE_buildComponentProvider","__PRIVATE_componentsProvider","__PRIVATE_online","enableIndexedDbPersistence","persistenceSettings","__PRIVATE_setPersistenceProviders","onlineComponents","enableMultiTabIndexedDbPersistence","clearIndexedDbPersistence","__PRIVATE_indexedDbClearPersistence","waitForPendingWrites","__PRIVATE_firestoreClientWaitForPendingWrites","enableNetwork","disableNetwork","_removeServiceInstance","loadBundle","AggregateField","_internalFieldPath","AggregateQuerySnapshot","_userDataWriter","_data","convertObjectMap","_byteString","fieldNames","_internalPath","__PRIVATE_InternalFieldPath","FieldValue","_methodName","GeoPoint","isFinite","_lat","_long","VectorValue","_values","__PRIVATE_isPrimitiveArrayEqual","vectorValues","__PRIVATE_RESERVED_FIELD_REGEX","ParsedSetData","ParsedUpdateData","__PRIVATE_isWrite","__PRIVATE_dataSource","__PRIVATE_ParseContextImpl","__PRIVATE_validatePath","__PRIVATE_contextWith","__PRIVATE_childContextForField","__PRIVATE_childPath","__PRIVATE_validatePathSegment","__PRIVATE_childContextForFieldPath","__PRIVATE_childContextForArray","__PRIVATE_createError","methodName","__PRIVATE_hasConverter","__PRIVATE_targetDoc","__PRIVATE_UserDataReader","__PRIVATE_createContext","__PRIVATE_newUserDataReader","__PRIVATE_parseSetData","__PRIVATE_userDataReader","merge","mergeFields","__PRIVATE_validatePlainObject","__PRIVATE_updateData","__PRIVATE_parseObject","__PRIVATE_validatedFieldPaths","__PRIVATE_stringOrFieldPath","__PRIVATE_fieldPathFromArgument","__PRIVATE_fieldMaskContains","__PRIVATE_DeleteFieldValueImpl","_toFieldTransform","__PRIVATE_createSentinelChildContext","__PRIVATE_ServerTimestampFieldValueImpl","__PRIVATE_ArrayUnionFieldValueImpl","__PRIVATE__elements","__PRIVATE_parseContext","__PRIVATE_parsedElements","__PRIVATE_parseData","arrayUnion","__PRIVATE_ArrayRemoveFieldValueImpl","__PRIVATE_NumericIncrementFieldValueImpl","__PRIVATE__operand","__PRIVATE_numericIncrement","__PRIVATE_parseUpdateData","__PRIVATE_fieldMaskPaths","__PRIVATE_fieldPathFromDotSeparatedString","__PRIVATE_childContext","__PRIVATE_parsedValue","__PRIVATE_parseUpdateVarargs","moreFieldsAndValues","__PRIVATE_parseQueryValue","__PRIVATE_allowArrays","__PRIVATE_looksLikeJsonObject","__PRIVATE_parseSentinelFieldValue","__PRIVATE_parseArray","__PRIVATE_entryIndex","__PRIVATE_parsedEntry","__PRIVATE_parseScalarValue","__PRIVATE_thisDb","__PRIVATE_otherDb","__PRIVATE_parseVectorValue","__PRIVATE_FIELD_PATH_RESERVED","search","__PRIVATE_hasPath","__PRIVATE_hasDocument","DocumentSnapshot","_firestore","_document","_converter","QueryDocumentSnapshot","fromFirestore","convertValue","arg","__PRIVATE_validateHasExplicitOrderByForLimitToLast","AppliableConstraint","QueryConstraint","__PRIVATE_queryConstraint","__PRIVATE_additionalQueryConstraints","queryConstraints","__PRIVATE_validateQueryConstraintArray","__PRIVATE_compositeFilterCount","QueryCompositeFilterConstraint","__PRIVATE_fieldFilterCount","QueryFieldFilterConstraint","constraint","_apply","_field","_op","_value","_create","_parse","__PRIVATE_validateNewFieldFilter","__PRIVATE_newQueryFilter","__PRIVATE_dataReader","__PRIVATE_validateDisjunctiveFilterElements","__PRIVATE_referenceList","__PRIVATE_parseDocumentIdValue","opStr","_queryConstraints","__PRIVATE_parsedFilters","__PRIVATE_parsedFilter","_getOperator","__PRIVATE_validateNewFilter","__PRIVATE_testQuery","__PRIVATE_subFilters","_getQueryConstraints","__PRIVATE_validateQueryFilterConstraint","and","QueryOrderByConstraint","_direction","__PRIVATE_newQueryOrderBy","__PRIVATE_queryWithAddedOrderBy","__PRIVATE_newOrderBy","directionStr","QueryLimitConstraint","_limit","_limitType","limitToLast","QueryStartAtConstraint","_docOrFields","_inclusive","__PRIVATE_newQueryBoundFromDocOrFields","__PRIVATE_queryWithStartAt","__PRIVATE_docOrFields","startAfter","QueryEndAtConstraint","__PRIVATE_queryWithEndAt","endBefore","__PRIVATE_newQueryBoundFromDocument","components","__PRIVATE_newQueryBoundFromFields","__PRIVATE_rawValue","__PRIVATE_wrapped","__PRIVATE_documentIdValue","__PRIVATE_conflictingOp","__PRIVATE_findOpInsideFilters","__PRIVATE_operators","__PRIVATE_conflictingOps","AbstractUserDataWriter","serverTimestampBehavior","convertTimestamp","convertServerTimestamp","convertBytes","convertReference","convertGeoPoint","convertArray","convertObject","convertVectorValue","__PRIVATE_normalizedValue","convertDocumentKey","expectedDatabaseId","__PRIVATE_applyFirestoreDataConverter","__PRIVATE_convertedValue","toFirestore","__PRIVATE_LiteUserDataWriter","average","aggregateFieldEqual","aggregateQuerySnapshotEqual","__PRIVATE_NOT_SUPPORTED","SnapshotMetadata","__PRIVATE_LiteDocumentSnapshot","userDataWriter","_firestoreImpl","serverTimestamps","documentSnapshotFromJSON","__PRIVATE_bundleLoader","__PRIVATE_bundledDocuments","bundleSource","QuerySnapshot","_snapshot","thisArg","_cachedChanges","_cachedChangesIncludeMetadataChanges","__PRIVATE_changesFromSnapshot","__PRIVATE_querySnapshot","oldIndex","newIndex","__PRIVATE_indexTracker","__PRIVATE_resultChangeType","__PRIVATE_documentData","querySnapshotFromJSON","__PRIVATE_bundledDocument","__PRIVATE_externalQuery","snapshotEqual","getDoc","reference","__PRIVATE_convertToDocSnapshot","__PRIVATE_ExpUserDataWriter","getDocFromCache","getDocFromServer","getDocs","getDocsFromCache","getDocsFromServer","setDoc","executeWrite","updateDoc","__PRIVATE_fieldOrUpdateData","deleteDoc","addDoc","__PRIVATE_docRef","onSnapshot","__PRIVATE_currArg","__PRIVATE_internalOptions","__PRIVATE_userObserver","__PRIVATE_internalQuery","__PRIVATE_firestoreClientListen","onSnapshotResume","snapshotJson","__PRIVATE_normalizeSnapshotJsonFields","__PRIVATE_requiredKeys","__PRIVATE_curArg","__PRIVATE_onSnapshotQuerySnapshotBundle","__PRIVATE_internalUnsubscribe","__PRIVATE_unsubscribed","__PRIVATE_loadTask","__PRIVATE_onSnapshotDocumentSnapshotBundle","__PRIVATE_docReference","onSnapshotsInSync","__PRIVATE_firestoreClientWrite","getCountFromServer","getAggregateFromServer","aggregateSpec","__PRIVATE_internalAggregates","__PRIVATE_aggregateResult","__PRIVATE_convertToAggregateQuerySnapshot","__PRIVATE_MemoryLocalCacheImpl","__PRIVATE_PersistentLocalCacheImpl","tabManager","_initialize","persistentSingleTabManager","__PRIVATE_MemoryEagerGarbageCollectorImpl","__PRIVATE_MemoryLruGarbageCollectorImpl","memoryEagerGarbageCollector","memoryLruGarbageCollector","memoryLocalCache","persistentLocalCache","__PRIVATE_SingleTabManagerImpl","__PRIVATE_MultiTabManagerImpl","persistentMultipleTabManager","__PRIVATE_DEFAULT_TRANSACTION_OPTIONS","WriteBatch","_commitHandler","_mutations","_committed","_dataReader","documentRef","_verifyNotCommitted","__PRIVATE_validateReference","_transaction","__PRIVATE_LiteTransaction","__PRIVATE_liteDocumentSnapshot","__PRIVATE_optionsWithDefaults","__PRIVATE_validateTransactionOptions","__PRIVATE_firestoreClientTransaction","__PRIVATE_internalTransaction","deleteField","arrayRemove","vector","writeBatch","setIndexConfiguration","__PRIVATE_jsonOrConfiguration","__PRIVATE_parsedIndexes","__PRIVATE_parseIndexes","__PRIVATE_indexConfiguration","__PRIVATE_tryParseJson","__PRIVATE_tryGetString","arrayConfig","PersistentCacheIndexManager","getPersistentCacheIndexManager","__PRIVATE_cachedInstance","__PRIVATE_persistentCacheIndexManagerByFirestore","enablePersistentCacheIndexAutoCreation","__PRIVATE_setPersistentCacheIndexAutoCreationEnabled","disablePersistentCacheIndexAutoCreation","deleteAllPersistentCacheIndexes","WeakMap","_internalQueryToProtoQueryTarget","_internalAggregationQueryToProtoRunAggregationQueryRequest","TestingHooks","onExistenceFilterMismatch","__PRIVATE_TestingHooksSpiImpl","__PRIVATE_testingHooksSpiImplInstance","__PRIVATE_setTestingHooksSpi","__PRIVATE_existenceFilterMismatchCallbacksById","__PRIVATE_registerFirestore","variant","__PRIVATE_setSDKVersion","_registerComponent","Component","container","getProvider","__PRIVATE_firestoreInstance","__PRIVATE_databaseIdFromApp","setMultipleInstances","registerVersion"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;MAqBaA;IAUX,WAAAC,CAAqBC;QAAAC,KAAGD,MAAHA;AAAsB;IAE3C,eAAAE;QACE,OAAmB,QAAZD,KAAKD;AACb;;;;WAMD,KAAAG;QACE,OAAIF,KAAKC,oBACA,SAASD,KAAKD,MAEd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AAKisB,UACLsuD,IAAY38E,KAAKyjH;QAEvB,OADA9mC,EAAU13E,IAAI7C,GAAIwU,IACX,MAAM+lE,EAAU9+D,OAAOzb;AAC/B;;;AAGH,IAAImhH,KAA0D;;;;;;;;;;;;;;;;;cCvE9CG,4BACdC,GACA5yF,KAAkB;K1KhBd,SAAU6yF,wBAAc/nG;QAC5Bpb,IAAcob;AAChB,K0KgBE+nG,CAAcnjH,IACdojH,EACE,IAAIC,EACF,cACA,CAACC,IAAapV,oBAAoBp+E,GAAY/R,SAAShW;QACrD,MAAMN,IAAM67G,EAAUC,YAAY,OAAOl9G,gBACnCm9G,IAAoB,IAAI3b,UAC5B,IAAI1iG,0CACFm+G,EAAUC,YAAY,mBAExB,IAAI/7G,wCACFC,GACA67G,EAAUC,YAAY,wBtImClB,SAAAE,4BACdh8G,GACAkpB;YAEA,KAAKlgB,OAAOE,UAAUsX,eAAeiF,MAAMzlB,EAAIsW,SAAS,EAAC,gBACvD,MAAM,IAAIta,eACRjB,EAAKI,kBACL;YAIJ,OAAO,IAAI6tB,WAAWhpB,EAAIsW,QAAQ2S,WAAYC;AAChD,SsI7CU8yF,CAAkBh8G,GAAKqoB,IACvBroB;QAIF,OAFAM,IAAW;YAAEuoB;eAAoBvoB;WACjCy7G,EAAkB/a,aAAa1gG,IACxBy7G;AAAiB,QAE1B,UACAE,sBAAqB,KAEzBC,EAAgB9/G,GAAMuX,GAAS8nG;;IAE/BS,EAAgB9/G,GAAMuX,GAAS;AACjC,CC9CA6nG,CAAkB,8BAA6B;;"} \ No newline at end of file diff --git a/frontend-old/node_modules/@firebase/firestore/dist/internal.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/internal.d.ts new file mode 100644 index 0000000..2afa6be --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/internal.d.ts @@ -0,0 +1,8045 @@ +/** + * Cloud Firestore + * + * @packageDocumentation + */ + +import { DocumentData as DocumentData_2 } from '@firebase/firestore-types'; +import { EmulatorMockTokenOptions } from '@firebase/util'; +import { FirebaseApp } from '@firebase/app'; +import { FirebaseError } from '@firebase/util'; +import { _FirebaseService } from '@firebase/app'; +import { LogLevelString as LogLevel } from '@firebase/logger'; +import { SetOptions as SetOptions_2 } from '@firebase/firestore-types'; + +/** + * Converts Firestore's internal types to the JavaScript types that we expose + * to the user. + * + * @internal + */ +export declare abstract class AbstractUserDataWriter { + convertValue(value: Value, serverTimestampBehavior?: ServerTimestampBehavior): unknown; + private convertObject; + /** + * @internal + */ + convertObjectMap(fields: ApiClientObjectMap | undefined, serverTimestampBehavior?: ServerTimestampBehavior): DocumentData_2; + /** + * @internal + */ + convertVectorValue(mapValue: MapValue): VectorValue; + private convertGeoPoint; + private convertArray; + private convertServerTimestamp; + private convertTimestamp; + protected convertDocumentKey(name: string, expectedDatabaseId: _DatabaseId): _DocumentKey; + protected abstract convertReference(name: string): unknown; + protected abstract convertBytes(bytes: _ByteString): unknown; +} + +/** + * Describes a map whose keys are active target ids. We do not care about the type of the + * values. + */ +declare type ActiveTargets = SortedMap; + +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend (Note that it + * won't resolve while you're offline). + */ +export declare function addDoc(reference: CollectionReference, data: WithFieldValue): Promise>; + +/** + * Returns a new map where every key is prefixed with the outer key appended + * to a dot. + */ +export declare type AddPrefixToKeys> = { + [K in keyof T & string as `${Prefix}.${K}`]+?: string extends K ? any : T[K]; +}; + +/** + * Represents an aggregation that can be performed by Firestore. + */ +export declare class AggregateField { + readonly _internalFieldPath?: _FieldPath | undefined; + /** A type string to uniquely identify instances of this class. */ + readonly type = "AggregateField"; + /** Indicates the aggregation operation of this AggregateField. */ + readonly aggregateType: AggregateType; + /** + * Create a new AggregateField + * @param aggregateType Specifies the type of aggregation operation to perform. + * @param _internalFieldPath Optionally specifies the field that is aggregated. + * @internal + */ + constructor(aggregateType?: AggregateType, _internalFieldPath?: _FieldPath | undefined); +} + +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ +export declare function aggregateFieldEqual(left: AggregateField, right: AggregateField): boolean; + +/** + * The union of all `AggregateField` types that are supported by Firestore. + */ +export declare type AggregateFieldType = ReturnType | ReturnType | ReturnType; + +/** + * The results of executing an aggregation query. + */ +export declare class AggregateQuerySnapshot { + private readonly _userDataWriter; + private readonly _data; + /** A type string to uniquely identify instances of this class. */ + readonly type = "AggregateQuerySnapshot"; + /** + * The underlying query over which the aggregations recorded in this + * `AggregateQuerySnapshot` were performed. + */ + readonly query: Query; + /** @hideconstructor */ + constructor(query: Query, _userDataWriter: AbstractUserDataWriter, _data: ApiClientObjectMap); + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ + data(): AggregateSpecData; +} + +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ +export declare function aggregateQuerySnapshotEqual(left: AggregateQuerySnapshot, right: AggregateQuerySnapshot): boolean; + +/** + * Specifies a set of aggregations and their aliases. + */ +export declare interface AggregateSpec { + [field: string]: AggregateFieldType; +} + +/** + * A type whose keys are taken from an `AggregateSpec`, and whose values are the + * result of the aggregation performed by the corresponding `AggregateField` + * from the input `AggregateSpec`. + */ +export declare type AggregateSpecData = { + [P in keyof T]: T[P] extends AggregateField ? U : never; +}; + +/** + * Union type representing the aggregate type to be performed. + */ +export declare type AggregateType = 'count' | 'avg' | 'sum'; + +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +export declare function and(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; + +declare interface ApiClientObjectMap { + [k: string]: T; +} + +/** + * An `AppliableConstraint` is an abstraction of a constraint that can be applied + * to a Firestore query. + */ +declare abstract class AppliableConstraint { + /** + * Takes the provided {@link Query} and returns a copy of the {@link Query} with this + * {@link AppliableConstraint} applied. + */ + abstract _apply(query: Query): Query; +} + +/** + * Returns a special value that can be used with {@link (setDoc:1)} or {@link + * updateDoc:1} that tells the server to remove the given elements from any + * array value that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is not + * already an array it will be overwritten with an empty array. + * + * @param elements - The elements to remove from the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +export declare function arrayRemove(...elements: unknown[]): FieldValue; + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array + * value that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements - The elements to union into the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()`. + */ +export declare function arrayUnion(...elements: unknown[]): FieldValue; + +declare interface AsyncQueue { + readonly isShuttingDown: boolean; + /** + * Adds a new operation to the queue without waiting for it to complete (i.e. + * we ignore the Promise result). + */ + enqueueAndForget(op: () => Promise): void; + /** + * Regardless if the queue has initialized shutdown, adds a new operation to the + * queue without waiting for it to complete (i.e. we ignore the Promise result). + */ + enqueueAndForgetEvenWhileRestricted(op: () => Promise): void; + /** + * Initialize the shutdown of this queue. Once this method is called, the + * only possible way to request running an operation is through + * `enqueueEvenWhileRestricted()`. + * + * @param purgeExistingTasks Whether already enqueued tasked should be + * rejected (unless enqueued with `enqueueEvenWhileRestricted()`). Defaults + * to false. + */ + enterRestrictedMode(purgeExistingTasks?: boolean): void; + /** + * Adds a new operation to the queue. Returns a promise that will be resolved + * when the promise returned by the new operation is (with its value). + */ + enqueue(op: () => Promise): Promise; + /** + * Enqueue a retryable operation. + * + * A retryable operation is rescheduled with backoff if it fails with a + * IndexedDbTransactionError (the error type used by SimpleDb). All + * retryable operations are executed in order and only run if all prior + * operations were retried successfully. + */ + enqueueRetryable(op: () => Promise): void; + /** + * Schedules an operation to be queued on the AsyncQueue once the specified + * `delayMs` has elapsed. The returned DelayedOperation can be used to cancel + * or fast-forward the operation prior to its running. + */ + enqueueAfterDelay(timerId: TimerId, delayMs: number, op: () => Promise): DelayedOperation; + /** + * Verifies there's an operation currently in-progress on the AsyncQueue. + * Unfortunately we can't verify that the running code is in the promise chain + * of that operation, so this isn't a foolproof check, but it should be enough + * to catch some bugs. + */ + verifyOperationInProgress(): void; +} + +/** + * @internal + */ +export declare type AuthTokenFactory = () => string; + +/** + * A utility class for generating unique alphanumeric IDs of a specified length. + * + * @internal + * Exported internally for testing purposes. + */ +export declare class _AutoId { + static newId(): string; +} + +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ +export declare function average(field: string | FieldPath): AggregateField; + +/** + * Path represents an ordered sequence of string segments. + */ +declare abstract class BasePath> { + private segments; + private offset; + private len; + constructor(segments: string[], offset?: number, length?: number); + /** + * Abstract constructor method to construct an instance of B with the given + * parameters. + */ + protected abstract construct(segments: string[], offset?: number, length?: number): B; + /** + * Returns a String representation. + * + * Implementing classes are required to provide deterministic implementations as + * the String representation is used to obtain canonical Query IDs. + */ + abstract toString(): string; + get length(): number; + isEqual(other: B): boolean; + child(nameOrPath: string | B): B; + /** The index of one past the last segment of the path. */ + private limit; + popFirst(size?: number): B; + popLast(): B; + firstSegment(): string; + lastSegment(): string; + get(index: number): string; + isEmpty(): boolean; + isPrefixOf(other: this): boolean; + isImmediateParentOf(potentialChild: this): boolean; + forEach(fn: (segment: string) => void): void; + toArray(): string[]; + /** + * Compare 2 paths segment by segment, prioritizing numeric IDs + * (e.g., "__id123__") in numeric ascending order, followed by string + * segments in lexicographical order. + */ + static comparator>(p1: BasePath, p2: BasePath): number; + private static compareSegments; + private static isNumericId; + private static extractNumericId; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * BatchID is a locally assigned ID for a batch of mutations that have been + * applied. + */ +declare type BatchId = number; + +/** + * Represents a bound of a query. + * + * The bound is specified with the given components representing a position and + * whether it's just before or just after the position (relative to whatever the + * query order is). + * + * The position represents a logical index position for a query. It's a prefix + * of values for the (potentially implicit) order by clauses of a query. + * + * Bound provides a function to determine whether a document comes before or + * after a bound. This is influenced by whether the position is just before or + * just after the provided values. + */ +declare class Bound { + readonly position: Value[]; + readonly inclusive: boolean; + constructor(position: Value[], inclusive: boolean); +} + +/** + * Provides interfaces to save and read Firestore bundles. + */ +declare interface BundleCache { + /** + * Gets the saved `BundleMetadata` for a given `bundleId`, returns undefined + * if no bundle metadata is found under the given id. + */ + getBundleMetadata(transaction: PersistenceTransaction, bundleId: string): PersistencePromise; + /** + * Saves a `BundleMetadata` from a bundle into local storage, using its id as + * the persistent key. + */ + saveBundleMetadata(transaction: PersistenceTransaction, metadata: BundleMetadata_2): PersistencePromise; + /** + * Gets a saved `NamedQuery` for the given query name. Returns undefined if + * no queries are found under the given name. + */ + getNamedQuery(transaction: PersistenceTransaction, queryName: string): PersistencePromise; + /** + * Saves a `NamedQuery` from a bundle, using its name as the persistent key. + */ + saveNamedQuery(transaction: PersistenceTransaction, query: NamedQuery_2): PersistencePromise; +} + +/** Properties of a BundledQuery. */ +declare interface BundledQuery { + /** BundledQuery parent */ + parent?: string | null; + /** BundledQuery structuredQuery */ + structuredQuery?: StructuredQuery | null; + /** BundledQuery limitType */ + limitType?: LimitType_2 | null; +} + +/** + * Represents a Firestore bundle saved by the SDK in its local storage. + */ +declare interface BundleMetadata { + /** + * Id of the bundle. It is used together with `createTime` to determine if a + * bundle has been loaded by the SDK. + */ + readonly id: string; + /** Schema version of the bundle. */ + readonly version: number; + /** + * Set to the snapshot version of the bundle if created by the Server SDKs. + * Otherwise set to SnapshotVersion.MIN. + */ + readonly createTime: SnapshotVersion; +} + +/** Properties of a BundleMetadata. */ +declare interface BundleMetadata_2 { + /** BundleMetadata id */ + id?: string | null; + /** BundleMetadata createTime */ + createTime?: Timestamp_2 | null; + /** BundleMetadata version */ + version?: number | null; + /** BundleMetadata totalDocuments */ + totalDocuments?: number | null; + /** BundleMetadata totalBytes */ + totalBytes?: number | null; +} + +/** + * An immutable object representing an array of bytes. + */ +export declare class Bytes { + _byteString: _ByteString; + /** @hideconstructor */ + constructor(byteString: _ByteString); + /** + * Creates a new `Bytes` object from the given Base64 string, converting it to + * bytes. + * + * @param base64 - The Base64 string used to create the `Bytes` object. + */ + static fromBase64String(base64: string): Bytes; + /** + * Creates a new `Bytes` object from the given Uint8Array. + * + * @param array - The Uint8Array used to create the `Bytes` object. + */ + static fromUint8Array(array: Uint8Array): Bytes; + /** + * Returns the underlying bytes as a Base64-encoded string. + * + * @returns The Base64-encoded string created from the `Bytes` object. + */ + toBase64(): string; + /** + * Returns the underlying bytes in a new `Uint8Array`. + * + * @returns The Uint8Array created from the `Bytes` object. + */ + toUint8Array(): Uint8Array; + /** + * Returns a string representation of the `Bytes` object. + * + * @returns A string representation of the `Bytes` object. + */ + toString(): string; + /** + * Returns true if this `Bytes` object is equal to the provided one. + * + * @param other - The `Bytes` object to compare against. + * @returns true if this `Bytes` object is equal to the provided one. + */ + isEqual(other: Bytes): boolean; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + bytes: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `Bytes` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}. + * + * @param json a JSON object represention of a `Bytes` instance + * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): Bytes; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Immutable class that represents a "proto" byte string. + * + * Proto byte strings can either be Base64-encoded strings or Uint8Arrays when + * sent on the wire. This class abstracts away this differentiation by holding + * the proto byte string in a common class that must be converted into a string + * before being sent as a proto. + * @internal + */ +export declare class _ByteString { + private readonly binaryString; + static readonly EMPTY_BYTE_STRING: _ByteString; + private constructor(); + static fromBase64String(base64: string): _ByteString; + static fromUint8Array(array: Uint8Array): _ByteString; + [Symbol.iterator](): Iterator; + toBase64(): string; + toUint8Array(): Uint8Array; + approximateByteSize(): number; + compareTo(other: _ByteString): number; + isEqual(other: _ByteString): boolean; +} + +/** + * Constant used to indicate the LRU garbage collection should be disabled. + * Set this value as the `cacheSizeBytes` on the settings passed to the + * {@link Firestore} instance. + */ +export declare const CACHE_SIZE_UNLIMITED = -1; + +/** + * Casts `obj` to `T`, optionally unwrapping Compat types to expose the + * underlying instance. Throws if `obj` is not an instance of `T`. + * + * This cast is used in the Lite and Full SDK to verify instance types for + * arguments passed to the public API. + * @internal + */ +export declare function _cast(obj: object, constructor: { + new (...args: any[]): T; +}): T | never; + +declare const enum ChangeType { + Added = 0, + Removed = 1, + Modified = 2, + Metadata = 3 +} + +/** + * Helper for calculating the nested fields for a given type T1. This is needed + * to distribute union types such as `undefined | {...}` (happens for optional + * props) or `{a: A} | {b: B}`. + * + * In this use case, `V` is used to distribute the union types of `T[K]` on + * `Record`, since `T[K]` is evaluated as an expression and not distributed. + * + * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types + */ +export declare type ChildUpdateFields = V extends Record ? AddPrefixToKeys> : never; + +/** + * Clears the persistent storage. This includes pending writes and cached + * documents. + * + * Must be called while the {@link Firestore} instance is not started (after the app is + * terminated or when the app is first initialized). On startup, this function + * must be called before other functions (other than {@link + * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore} + * instance is still running, the promise will be rejected with the error code + * of `failed-precondition`. + * + * Note: `clearIndexedDbPersistence()` is primarily intended to help write + * reliable tests that use Cloud Firestore. It uses an efficient mechanism for + * dropping existing data but does not attempt to securely overwrite or + * otherwise make cached data unrecoverable. For applications that are sensitive + * to the disclosure of cached data in between user sessions, we strongly + * recommend not enabling persistence at all. + * + * @param firestore - The {@link Firestore} instance to clear persistence for. + * @returns A `Promise` that is resolved when the persistent storage is + * cleared. Otherwise, the promise is rejected with an error. + */ +export declare function clearIndexedDbPersistence(firestore: Firestore): Promise; + +/** + * A randomly-generated key assigned to each Firestore instance at startup. + */ +declare type ClientId = string; + +/** + * Gets a `CollectionReference` instance that refers to the collection at + * the specified absolute path. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments to apply relative to the first + * argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(firestore: Firestore_2, path: string, ...pathSegments: string[]): CollectionReference; + +/** + * Gets a `CollectionReference` instance that refers to a subcollection of + * `reference` at the specified relative path. + * + * @param reference - A reference to a collection. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments to apply relative to the first + * argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(reference: CollectionReference, path: string, ...pathSegments: string[]): CollectionReference; + +/** + * Gets a `CollectionReference` instance that refers to a subcollection of + * `reference` at the specified relative path. + * + * @param reference - A reference to a Firestore document. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(reference: DocumentReference, path: string, ...pathSegments: string[]): CollectionReference; + +/** + * Creates and returns a new `Query` instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given `collectionId`. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param collectionId - Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `Query`. + */ +export declare function collectionGroup(firestore: Firestore_2, collectionId: string): Query; + +/** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using {@link (query:1)}). + */ +export declare class CollectionReference extends Query { + readonly _path: _ResourcePath; + /** The type of this Firestore reference. */ + readonly type = "collection"; + /** @hideconstructor */ + constructor(firestore: Firestore_2, converter: FirestoreDataConverter_2 | null, _path: _ResourcePath); + /** The collection's identifier. */ + get id(): string; + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ + get path(): string; + /** + * A reference to the containing `DocumentReference` if this is a + * subcollection. If this isn't a subcollection, the reference is null. + */ + get parent(): DocumentReference | null; + /** + * Applies a custom data converter to this `CollectionReference`, allowing you + * to use your own custom model objects with Firestore. When you call {@link + * addDoc} with the returned `CollectionReference` instance, the provided + * converter will convert between Firestore data of type `NewDbModelType` and + * your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `CollectionReference` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter_2): CollectionReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `CollectionReference` that does not + * use a converter. + */ + withConverter(converter: null): CollectionReference; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +declare type Comparator = (key1: K, key2: K) => number; + +declare interface ComponentConfiguration { + asyncQueue: AsyncQueue; + databaseInfo: DatabaseInfo; + authCredentials: CredentialsProvider; + appCheckCredentials: CredentialsProvider; + clientId: ClientId; + initialUser: User; + maxConcurrentLimboResolutions: number; +} + +declare type CompositeFilterOp = 'OPERATOR_UNSPECIFIED' | 'AND' | 'OR'; + +declare const enum CompositeOperator { + OR = "or", + AND = "and" +} + +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ +export declare function connectFirestoreEmulator(firestore: Firestore_2, host: string, port: number, options?: { + mockUserToken?: EmulatorMockTokenOptions | string; +}): void; + +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ +export declare function count(): AggregateField; + +/** + * A Listener for credential change events. The listener should fetch a new + * token and may need to invalidate other state if the current user has also + * changed. + */ +declare type CredentialChangeListener = (credential: T) => Promise; + +/** + * Provides methods for getting the uid and token for the current user and + * listening for changes. + */ +declare interface CredentialsProvider { + /** + * Starts the credentials provider and specifies a listener to be notified of + * credential changes (sign-in / sign-out, token changes). It is immediately + * called once with the initial user. + * + * The change listener is invoked on the provided AsyncQueue. + */ + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + /** Requests a token for the current user. */ + getToken(): Promise; + /** + * Marks the last retrieved token as invalid, making the next GetToken request + * force-refresh the token. + */ + invalidateToken(): void; + shutdown(): void; +} + +/** Settings for private credentials */ +declare type CredentialsSettings = FirstPartyCredentialsSettings | ProviderCredentialsSettings; + +/** + * Represents the database ID a Firestore client is associated with. + * @internal + */ +export declare class _DatabaseId { + readonly projectId: string; + readonly database: string; + constructor(projectId: string, database?: string); + static empty(): _DatabaseId; + get isDefaultDatabase(): boolean; + isEqual(other: {}): boolean; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +declare class DatabaseInfo { + readonly databaseId: _DatabaseId; + readonly appId: string; + readonly persistenceKey: string; + readonly host: string; + readonly ssl: boolean; + readonly forceLongPolling: boolean; + readonly autoDetectLongPolling: boolean; + readonly longPollingOptions: ExperimentalLongPollingOptions; + readonly useFetchStreams: boolean; + readonly isUsingEmulator: boolean; + /** + * Constructs a DatabaseInfo using the provided host, databaseId and + * persistenceKey. + * + * @param databaseId - The database to use. + * @param appId - The Firebase App Id. + * @param persistenceKey - A unique identifier for this Firestore's local + * storage (used in conjunction with the databaseId). + * @param host - The Firestore backend host to connect to. + * @param ssl - Whether to use SSL when connecting. + * @param forceLongPolling - Whether to use the forceLongPolling option + * when using WebChannel as the network transport. + * @param autoDetectLongPolling - Whether to use the detectBufferingProxy + * option when using WebChannel as the network transport. + * @param longPollingOptions Options that configure long-polling. + * @param useFetchStreams Whether to use the Fetch API instead of + * XMLHTTPRequest + */ + constructor(databaseId: _DatabaseId, appId: string, persistenceKey: string, host: string, ssl: boolean, forceLongPolling: boolean, autoDetectLongPolling: boolean, longPollingOptions: ExperimentalLongPollingOptions, useFetchStreams: boolean, isUsingEmulator: boolean); +} + +/** + * Datastore and its related methods are a wrapper around the external Google + * Cloud Datastore grpc API, which provides an interface that is more convenient + * for the rest of the client SDK architecture to consume. + */ +declare abstract class Datastore { + abstract terminate(): void; + abstract serializer: JsonProtoSerializer; +} + +/** + * Fails if the given assertion condition is false, throwing an Error with the + * given message if it did. + * + * The code of callsites invoking this function are stripped out in production + * builds. Any side-effects of code within the debugAssert() invocation will not + * happen in this case. + * + * @internal + */ +export declare function _debugAssert(assertion: boolean, message: string): asserts assertion; + +/** + * Represents an operation scheduled to be run in the future on an AsyncQueue. + * + * It is created via DelayedOperation.createAndSchedule(). + * + * Supports cancellation (via cancel()) and early execution (via skipDelay()). + * + * Note: We implement `PromiseLike` instead of `Promise`, as the `Promise` type + * in newer versions of TypeScript defines `finally`, which is not available in + * IE. + */ +declare class DelayedOperation implements PromiseLike { + private readonly asyncQueue; + readonly timerId: TimerId; + readonly targetTimeMs: number; + private readonly op; + private readonly removalCallback; + private timerHandle; + private readonly deferred; + private constructor(); + get promise(): Promise; + /** + * Creates and returns a DelayedOperation that has been scheduled to be + * executed on the provided asyncQueue after the provided delayMs. + * + * @param asyncQueue - The queue to schedule the operation on. + * @param id - A Timer ID identifying the type of operation this is. + * @param delayMs - The delay (ms) before the operation should be scheduled. + * @param op - The operation to run. + * @param removalCallback - A callback to be called synchronously once the + * operation is executed or canceled, notifying the AsyncQueue to remove it + * from its delayedOperations list. + * PORTING NOTE: This exists to prevent making removeDelayedOperation() and + * the DelayedOperation class public. + */ + static createAndSchedule(asyncQueue: AsyncQueue, timerId: TimerId, delayMs: number, op: () => Promise, removalCallback: (op: DelayedOperation) => void): DelayedOperation; + /** + * Starts the timer. This is called immediately after construction by + * createAndSchedule(). + */ + private start; + /** + * Queues the operation to run immediately (if it hasn't already been run or + * canceled). + */ + skipDelay(): void; + /** + * Cancels the operation if it hasn't already been executed or canceled. The + * promise will be rejected. + * + * As long as the operation has not yet been run, calling cancel() provides a + * guarantee that the operation will not be run. + */ + cancel(reason?: string): void; + then: (onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null | undefined, onrejected?: ((reason: any) => TResult2 | PromiseLike) | null | undefined) => Promise; + private handleDelayElapsed; + private clearTimeout; +} + +/** + * Removes all persistent cache indexes. + * + * Please note this function will also deletes indexes generated by + * `setIndexConfiguration()`, which is deprecated. + */ +export declare function deleteAllPersistentCacheIndexes(indexManager: PersistentCacheIndexManager): void; + +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * @param reference - A reference to the document to delete. + * @returns A Promise resolved once the document has been successfully + * deleted from the backend (note that it won't resolve while you're offline). + */ +export declare function deleteDoc(reference: DocumentReference): Promise; + +/** + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. + */ +export declare function deleteField(): FieldValue; + +/** + * The direction of sorting in an order by. + */ +declare const enum Direction { + ASCENDING = "asc", + DESCENDING = "desc" +} + +/** + * Disables network usage for this instance. It can be re-enabled via {@link + * enableNetwork}. While the network is disabled, any snapshot listeners, + * `getDoc()` or `getDocs()` calls will return results from cache, and any write + * operations will be queued until the network is restored. + * + * @returns A `Promise` that is resolved once the network has been disabled. + */ +export declare function disableNetwork(firestore: Firestore): Promise; + +/** + * Stops creating persistent cache indexes automatically for local query + * execution. The indexes which have been created by calling + * `enablePersistentCacheIndexAutoCreation()` still take effect. + */ +export declare function disablePersistentCacheIndexAutoCreation(indexManager: PersistentCacheIndexManager): void; + +/** + * Gets a `DocumentReference` instance that refers to the document at the + * specified absolute path. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param path - A slash-separated path to a document. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(firestore: Firestore_2, path: string, ...pathSegments: string[]): DocumentReference; + +/** + * Gets a `DocumentReference` instance that refers to a document within + * `reference` at the specified relative path. If no path is specified, an + * automatically-generated unique ID will be used for the returned + * `DocumentReference`. + * + * @param reference - A reference to a collection. + * @param path - A slash-separated path to a document. Has to be omitted to use + * auto-generated IDs. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(reference: CollectionReference, path?: string, ...pathSegments: string[]): DocumentReference; + +/** + * Gets a `DocumentReference` instance that refers to a document within + * `reference` at the specified relative path. + * + * @param reference - A reference to a Firestore document. + * @param path - A slash-separated path to a document. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(reference: DocumentReference, path: string, ...pathSegments: string[]): DocumentReference; + +/** + * Represents a document in Firestore with a key, version, data and whether the + * data has local mutations applied to it. + */ +declare interface Document_2 { + /** The key for this document */ + readonly key: _DocumentKey; + /** + * The version of this document if it exists or a version at which this + * document was guaranteed to not exist. + */ + readonly version: SnapshotVersion; + /** + * The timestamp at which this document was read from the remote server. Uses + * `SnapshotVersion.min()` for documents created by the user. + */ + readonly readTime: SnapshotVersion; + /** + * The timestamp at which the document was created. This value increases + * monotonically when a document is deleted then recreated. It can also be + * compared to `createTime` of other documents and the `readTime` of a query. + */ + readonly createTime: SnapshotVersion; + /** The underlying data of this document or an empty value if no data exists. */ + readonly data: ObjectValue; + /** Returns whether local mutations were applied via the mutation queue. */ + readonly hasLocalMutations: boolean; + /** Returns whether mutations were applied based on a write acknowledgment. */ + readonly hasCommittedMutations: boolean; + /** + * Whether this document had a local mutation applied that has not yet been + * acknowledged by Watch. + */ + readonly hasPendingWrites: boolean; + /** + * Returns whether this document is valid (i.e. it is an entry in the + * RemoteDocumentCache, was created by a mutation or read from the backend). + */ + isValidDocument(): boolean; + /** + * Returns whether the document exists and its data is known at the current + * version. + */ + isFoundDocument(): boolean; + /** + * Returns whether the document is known to not exist at the current version. + */ + isNoDocument(): boolean; + /** + * Returns whether the document exists and its data is unknown at the current + * version. + */ + isUnknownDocument(): boolean; + isEqual(other: Document_2 | null | undefined): boolean; + /** Creates a mutable copy of this document. */ + mutableCopy(): MutableDocument; + toString(): string; +} + +/** + * A `DocumentChange` represents a change to the documents matching a query. + * It contains the document affected and the type of change that occurred. + */ +export declare interface DocumentChange { + /** The type of change ('added', 'modified', or 'removed'). */ + readonly type: DocumentChangeType; + /** The document affected by this change. */ + readonly doc: QueryDocumentSnapshot; + /** + * The index of the changed document in the result set immediately prior to + * this `DocumentChange` (i.e. supposing that all prior `DocumentChange` objects + * have been applied). Is `-1` for 'added' events. + */ + readonly oldIndex: number; + /** + * The index of the changed document in the result set immediately after + * this `DocumentChange` (i.e. supposing that all prior `DocumentChange` + * objects and the current `DocumentChange` object have been applied). + * Is -1 for 'removed' events. + */ + readonly newIndex: number; +} + +/** + * The type of a `DocumentChange` may be 'added', 'removed', or 'modified'. + */ +export declare type DocumentChangeType = 'added' | 'removed' | 'modified'; + +declare type DocumentComparator = (doc1: Document_2, doc2: Document_2) => number; + +/** + * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to + * values. + */ +export declare interface DocumentData { + /** A mapping between a field and its value. */ + [field: string]: any; +} + +/** + * Returns a special sentinel `FieldPath` to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ +export declare function documentId(): FieldPath; + +/** + * @internal + */ +export declare class _DocumentKey { + readonly path: _ResourcePath; + constructor(path: _ResourcePath); + static fromPath(path: string): _DocumentKey; + static fromName(name: string): _DocumentKey; + static empty(): _DocumentKey; + get collectionGroup(): string; + /** Returns true if the document is in the specified collectionId. */ + hasCollectionId(collectionId: string): boolean; + /** Returns the collection group (i.e. the name of the parent collection) for this key. */ + getCollectionGroup(): string; + /** Returns the fully qualified path to the parent collection. */ + getCollectionPath(): _ResourcePath; + isEqual(other: _DocumentKey | null): boolean; + toString(): string; + static comparator(k1: _DocumentKey, k2: _DocumentKey): number; + static isDocumentKey(path: _ResourcePath): boolean; + /** + * Creates and returns a new document key with the given segments. + * + * @param segments - The segments of the path to the document + * @returns A new instance of DocumentKey + */ + static fromSegments(segments: string[]): _DocumentKey; +} + +declare type DocumentKeyMap = ObjectMap<_DocumentKey, T>; + +declare type DocumentKeySet = SortedSet<_DocumentKey>; + +declare type DocumentMap = SortedMap<_DocumentKey, Document_2>; + +/** + * Provides methods to read and write document overlays. + * + * An overlay is a saved mutation, that gives a local view of a document when + * applied to the remote version of the document. + * + * Each overlay stores the largest batch ID that is included in the overlay, + * which allows us to remove the overlay once all batches leading up to it have + * been acknowledged. + */ +declare interface DocumentOverlayCache { + /** + * Gets the saved overlay mutation for the given document key. + * Returns null if there is no overlay for that key. + */ + getOverlay(transaction: PersistenceTransaction, key: _DocumentKey): PersistencePromise; + /** + * Gets the saved overlay mutation for the given document keys. Skips keys for + * which there are no overlays. + */ + getOverlays(transaction: PersistenceTransaction, keys: _DocumentKey[]): PersistencePromise; + /** + * Saves the given document mutation map to persistence as overlays. + * All overlays will have their largest batch id set to `largestBatchId`. + */ + saveOverlays(transaction: PersistenceTransaction, largestBatchId: number, overlays: MutationMap): PersistencePromise; + /** Removes overlays for the given document keys and batch ID. */ + removeOverlaysForBatchId(transaction: PersistenceTransaction, documentKeys: DocumentKeySet, batchId: number): PersistencePromise; + /** + * Returns all saved overlays for the given collection. + * + * @param transaction - The persistence transaction to use for this operation. + * @param collection - The collection path to get the overlays for. + * @param sinceBatchId - The minimum batch ID to filter by (exclusive). + * Only overlays that contain a change past `sinceBatchId` are returned. + * @returns Mapping of each document key in the collection to its overlay. + */ + getOverlaysForCollection(transaction: PersistenceTransaction, collection: _ResourcePath, sinceBatchId: number): PersistencePromise; + /** + * Returns `count` overlays with a batch ID higher than `sinceBatchId` for the + * provided collection group, processed by ascending batch ID. The method + * always returns all overlays for a batch even if the last batch contains + * more documents than the remaining limit. + * + * @param transaction - The persistence transaction used for this operation. + * @param collectionGroup - The collection group to get the overlays for. + * @param sinceBatchId - The minimum batch ID to filter by (exclusive). + * Only overlays that contain a change past `sinceBatchId` are returned. + * @param count - The number of overlays to return. Can be exceeded if the last + * batch contains more entries. + * @return Mapping of each document key in the collection group to its overlay. + */ + getOverlaysForCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, sinceBatchId: number, count: number): PersistencePromise; +} + +/** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. + */ +export declare class DocumentReference { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter_2 | null; + readonly _key: _DocumentKey; + /** The type of this Firestore reference. */ + readonly type = "document"; + /** + * The {@link Firestore} instance the document is in. + * This is useful for performing transactions, for example. + */ + readonly firestore: Firestore_2; + /** @hideconstructor */ + constructor(firestore: Firestore_2, + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + converter: FirestoreDataConverter_2 | null, _key: _DocumentKey); + get _path(): _ResourcePath; + /** + * The document's identifier within its collection. + */ + get id(): string; + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ + get path(): string; + /** + * The collection this `DocumentReference` belongs to. + */ + get parent(): CollectionReference; + /** + * Applies a custom data converter to this `DocumentReference`, allowing you + * to use your own custom model objects with Firestore. When you call {@link + * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference` + * instance, the provided converter will convert between Firestore data of + * type `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `DocumentReference` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter_2): DocumentReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `DocumentReference` that does not + * use a converter. + */ + withConverter(converter: null): DocumentReference; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + referencePath: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `DocumentReference` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `DocumentReference` instance from a JSON object created by + * {@link DocumentReference.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json a JSON object represention of a `DocumentReference` instance + * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(firestore: Firestore_2, json: object): DocumentReference; + /** + * Builds a `DocumentReference` instance from a JSON object created by + * {@link DocumentReference.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json a JSON object represention of a `DocumentReference` instance + * @param converter - Converts objects to and from Firestore. + * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(firestore: Firestore_2, json: object, converter: FirestoreDataConverter_2): DocumentReference; +} + +/** + * DocumentSet is an immutable (copy-on-write) collection that holds documents + * in order specified by the provided comparator. We always add a document key + * comparator on top of what is provided to guarantee document equality based on + * the key. + */ +declare class DocumentSet { + /** + * Returns an empty copy of the existing DocumentSet, using the same + * comparator. + */ + static emptySet(oldSet: DocumentSet): DocumentSet; + private comparator; + private keyedMap; + private sortedSet; + /** The default ordering is by key if the comparator is omitted */ + constructor(comp?: DocumentComparator); + has(key: _DocumentKey): boolean; + get(key: _DocumentKey): Document_2 | null; + first(): Document_2 | null; + last(): Document_2 | null; + isEmpty(): boolean; + /** + * Returns the index of the provided key in the document set, or -1 if the + * document key is not present in the set; + */ + indexOf(key: _DocumentKey): number; + get size(): number; + /** Iterates documents in order defined by "comparator" */ + forEach(cb: (doc: Document_2) => void): void; + /** Inserts or updates a document with the same key */ + add(doc: Document_2): DocumentSet; + /** Deletes a document with a given key */ + delete(key: _DocumentKey): DocumentSet; + isEqual(other: DocumentSet | null | undefined): boolean; + toString(): string; + private copy; +} + +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ +export declare class DocumentSnapshot extends DocumentSnapshot_2 { + readonly _firestore: Firestore; + private readonly _firestoreImpl; + /** + * Metadata about the `DocumentSnapshot`, including information about its + * source and local modifications. + */ + readonly metadata: SnapshotMetadata; + /** @hideconstructor protected */ + constructor(_firestore: Firestore, userDataWriter: AbstractUserDataWriter, key: _DocumentKey, document: Document_2 | null, metadata: SnapshotMetadata, converter: UntypedFirestoreDataConverter | null); + /** + * Returns whether or not the data exists. True if the document exists. + */ + exists(): this is QueryDocumentSnapshot; + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * By default, `serverTimestamp()` values that have not yet been + * set to their final value will be returned as `null`. You can override + * this by passing an options object. + * + * @param options - An options object to configure how data is retrieved from + * the snapshot (for example the desired behavior for server timestamps that + * have not yet been set to their final value). + * @returns An `Object` containing all fields in the document or `undefined` if + * the document doesn't exist. + */ + data(options?: SnapshotOptions): AppModelType | undefined; + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * By default, a `serverTimestamp()` that has not yet been set to + * its final value will be returned as `null`. You can override this by + * passing an options object. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @param options - An options object to configure how the field is retrieved + * from the snapshot (for example the desired behavior for server timestamps + * that have not yet been set to their final value). + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + get(fieldPath: string | FieldPath, options?: SnapshotOptions): any; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + bundleSource: Property<"string">; + bundleName: Property<"string">; + bundle: Property<"string">; + }; + /** + * Returns a JSON-serializable representation of this `DocumentSnapshot` instance. + * + * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this + * `DocumentSnapshot` has pending writes. + */ + toJSON(): object; +} + +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ +declare class DocumentSnapshot_2 { + _firestore: Firestore_2; + _userDataWriter: AbstractUserDataWriter; + _key: _DocumentKey; + _document: Document_2 | null; + _converter: UntypedFirestoreDataConverter | null; + /** @hideconstructor protected */ + constructor(_firestore: Firestore_2, _userDataWriter: AbstractUserDataWriter, _key: _DocumentKey, _document: Document_2 | null, _converter: UntypedFirestoreDataConverter | null); + /** Property of the `DocumentSnapshot` that provides the document's ID. */ + get id(): string; + /** + * The `DocumentReference` for the document included in the `DocumentSnapshot`. + */ + get ref(): DocumentReference; + /** + * Signals whether or not the document at the snapshot's location exists. + * + * @returns true if the document exists. + */ + exists(): this is QueryDocumentSnapshot_2; + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * @returns An `Object` containing all fields in the document or `undefined` + * if the document doesn't exist. + */ + data(): AppModelType | undefined; + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + get(fieldPath: string | FieldPath): any; +} + +/** + * Builds a `DocumentSnapshot` instance from a JSON object created by + * {@link DocumentSnapshot.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json - a JSON object represention of a `DocumentSnapshot` instance. + * @returns an instance of {@link DocumentSnapshot} if the JSON object could be + * parsed. Throws a {@link FirestoreError} if an error occurs. + */ +export declare function documentSnapshotFromJSON(db: Firestore, json: object): DocumentSnapshot; + +/** + * Builds a `DocumentSnapshot` instance from a JSON object created by + * {@link DocumentSnapshot.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json - a JSON object represention of a `DocumentSnapshot` instance. + * @param converter - Converts objects to and from Firestore. + * @returns an instance of {@link DocumentSnapshot} if the JSON object could be + * parsed. Throws a {@link FirestoreError} if an error occurs. + */ +export declare function documentSnapshotFromJSON(db: Firestore, json: object, converter: FirestoreDataConverter): DocumentSnapshot; + +declare type DocumentVersionMap = SortedMap<_DocumentKey, SnapshotVersion>; + +declare interface DocumentViewChange { + type: ChangeType; + doc: Document_2; +} + +/** + * An AppCheck token provider that always yields an empty token. + * @internal + */ +export declare class _EmptyAppCheckTokenProvider implements CredentialsProvider { + getToken(): Promise; + invalidateToken(): void; + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + shutdown(): void; +} + +/** + * A CredentialsProvider that always yields an empty token. + * @internal + */ +export declare class _EmptyAuthCredentialsProvider implements CredentialsProvider { + getToken(): Promise; + invalidateToken(): void; + start(asyncQueue: AsyncQueue, changeListener: CredentialChangeListener): void; + shutdown(): void; +} +export { EmulatorMockTokenOptions } + +/** + * Attempts to enable persistent storage, if possible. + * + * On failure, `enableIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. + * + * * failed-precondition: The app is already open in another browser tab. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. + * + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. + * + * Note: `enableIndexedDbPersistence()` must be called before any other functions + * (other than {@link initializeFirestore}, {@link (getFirestore:1)} or + * {@link clearIndexedDbPersistence}. + * + * Persistence cannot be used in a Node.js environment. + * + * @param firestore - The {@link Firestore} instance to enable persistence for. + * @param persistenceSettings - Optional settings object to configure + * persistence. + * @returns A `Promise` that represents successfully enabling persistent storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on IndexedDb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. + */ +export declare function enableIndexedDbPersistence(firestore: Firestore, persistenceSettings?: PersistenceSettings): Promise; + +/** + * Attempts to enable multi-tab persistent storage, if possible. If enabled + * across all tabs, all operations share access to local persistence, including + * shared execution of queries and latency-compensated local document updates + * across all connected instances. + * + * On failure, `enableMultiTabIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. + * + * * failed-precondition: The app is already open in another browser tab and + * multi-tab is not enabled. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. + * + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. + * + * @param firestore - The {@link Firestore} instance to enable persistence for. + * @returns A `Promise` that represents successfully enabling persistent + * storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on indexeddb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. + */ +export declare function enableMultiTabIndexedDbPersistence(firestore: Firestore): Promise; + +/** + * Re-enables use of the network for this {@link Firestore} instance after a prior + * call to {@link disableNetwork}. + * + * @returns A `Promise` that is resolved once the network has been enabled. + */ +export declare function enableNetwork(firestore: Firestore): Promise; + +/** + * Enables the SDK to create persistent cache indexes automatically for local + * query execution when the SDK believes cache indexes can help improve + * performance. + * + * This feature is disabled by default. + */ +export declare function enablePersistentCacheIndexAutoCreation(indexManager: PersistentCacheIndexManager): void; + +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided document (inclusive). The end position is relative to the order + * of the query. The document must contain all of the fields provided in the + * orderBy of the query. + * + * @param snapshot - The snapshot of the document to end at. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endAt(snapshot: DocumentSnapshot_2): QueryEndAtConstraint; + +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided fields relative to the order of the query. The order of the field + * values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to end this query at, in order + * of the query's order by. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endAt(...fieldValues: unknown[]): QueryEndAtConstraint; + +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided document (exclusive). The end position is relative to the + * order of the query. The document must contain all of the fields provided in + * the orderBy of the query. + * + * @param snapshot - The snapshot of the document to end before. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endBefore(snapshot: DocumentSnapshot_2): QueryEndAtConstraint; + +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to end this query before, in order + * of the query's order by. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endBefore(...fieldValues: unknown[]): QueryEndAtConstraint; + +/** + * @internal + */ +export declare function ensureFirestoreConfigured(firestore: Firestore): FirestoreClient; + +declare interface Entry { + key: K; + value: V; +} + +/** + * EventManager is responsible for mapping queries to query event emitters. + * It handles "fan-out". -- Identical queries will re-use the same watch on the + * backend. + * + * PORTING NOTE: On Web, EventManager `onListen` and `onUnlisten` need to be + * assigned to SyncEngine's `listen()` and `unlisten()` API before usage. This + * allows users to tree-shake the Watch logic. + */ +declare interface EventManager { + onListen?: (query: Query_2, enableRemoteListen: boolean) => Promise; + onUnlisten?: (query: Query_2, disableRemoteListen: boolean) => Promise; + onFirstRemoteStoreListen?: (query: Query_2) => Promise; + onLastRemoteStoreUnlisten?: (query: Query_2) => Promise; + terminate(): void; +} + +/** + * Locally writes `mutations` on the async queue. + * @internal + */ +export declare function executeWrite(firestore: Firestore, mutations: Mutation[]): Promise; + +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options that configure the SDK’s underlying network transport (WebChannel) + * when long-polling is used. + * + * Note: This interface is "experimental" and is subject to change. + * + * See `FirestoreSettings.experimentalAutoDetectLongPolling`, + * `FirestoreSettings.experimentalForceLongPolling`, and + * `FirestoreSettings.experimentalLongPollingOptions`. + */ +export declare interface ExperimentalLongPollingOptions { + /** + * The desired maximum timeout interval, in seconds, to complete a + * long-polling GET response. Valid values are between 5 and 30, inclusive. + * Floating point values are allowed and will be rounded to the nearest + * millisecond. + * + * By default, when long-polling is used the "hanging GET" request sent by + * the client times out after 30 seconds. To request a different timeout + * from the server, set this setting with the desired timeout. + * + * Changing the default timeout may be useful, for example, if the buffering + * proxy that necessitated enabling long-polling in the first place has a + * shorter timeout for hanging GET requests, in which case setting the + * long-polling timeout to a shorter value, such as 25 seconds, may fix + * prematurely-closed hanging GET requests. + * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987. + */ + timeoutSeconds?: number; +} + +declare class FieldFilter extends Filter { + readonly field: _FieldPath; + readonly op: Operator; + readonly value: Value; + protected constructor(field: _FieldPath, op: Operator, value: Value); + /** + * Creates a filter based on the provided arguments. + */ + static create(field: _FieldPath, op: Operator, value: Value): FieldFilter; + private static createKeyFieldInFilter; + matches(doc: Document_2): boolean; + protected matchesComparison(comparison: number): boolean; + isInequality(): boolean; + getFlattenedFilters(): readonly FieldFilter[]; + getFilters(): Filter[]; +} + +declare type FieldFilterOp = 'OPERATOR_UNSPECIFIED' | 'LESS_THAN' | 'LESS_THAN_OR_EQUAL' | 'GREATER_THAN' | 'GREATER_THAN_OR_EQUAL' | 'EQUAL' | 'NOT_EQUAL' | 'ARRAY_CONTAINS' | 'IN' | 'ARRAY_CONTAINS_ANY' | 'NOT_IN'; + +/** + * An index definition for field indexes in Firestore. + * + * Every index is associated with a collection. The definition contains a list + * of fields and their index kind (which can be `ASCENDING`, `DESCENDING` or + * `CONTAINS` for ArrayContains/ArrayContainsAny queries). + * + * Unlike the backend, the SDK does not differentiate between collection or + * collection group-scoped indices. Every index can be used for both single + * collection and collection group queries. + */ +declare class FieldIndex { + /** + * The index ID. Returns -1 if the index ID is not available (e.g. the index + * has not yet been persisted). + */ + readonly indexId: number; + /** The collection ID this index applies to. */ + readonly collectionGroup: string; + /** The field segments for this index. */ + readonly fields: IndexSegment[]; + /** Shows how up-to-date the index is for the current user. */ + readonly indexState: IndexState; + /** An ID for an index that has not yet been added to persistence. */ + static UNKNOWN_ID: number; + constructor( + /** + * The index ID. Returns -1 if the index ID is not available (e.g. the index + * has not yet been persisted). + */ + indexId: number, + /** The collection ID this index applies to. */ + collectionGroup: string, + /** The field segments for this index. */ + fields: IndexSegment[], + /** Shows how up-to-date the index is for the current user. */ + indexState: IndexState); +} + +/** + * Provides a set of fields that can be used to partially patch a document. + * FieldMask is used in conjunction with ObjectValue. + * Examples: + * foo - Overwrites foo entirely with the provided value. If foo is not + * present in the companion ObjectValue, the field is deleted. + * foo.bar - Overwrites only the field bar of the object foo. + * If foo is not an object, foo is replaced with an object + * containing foo + */ +declare class FieldMask { + readonly fields: _FieldPath[]; + constructor(fields: _FieldPath[]); + static empty(): FieldMask; + /** + * Returns a new FieldMask object that is the result of adding all the given + * fields paths to this field mask. + */ + unionWith(extraFields: _FieldPath[]): FieldMask; + /** + * Verifies that `fieldPath` is included by at least one field in this field + * mask. + * + * This is an O(n) operation, where `n` is the size of the field mask. + */ + covers(fieldPath: _FieldPath): boolean; + isEqual(other: FieldMask): boolean; +} + +/** + * A `FieldPath` refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + * + * Create a `FieldPath` by providing field names. If more than one field + * name is provided, the path will point to a nested field in a document. + */ +export declare class FieldPath { + /** Internal representation of a Firestore field path. */ + readonly _internalPath: _FieldPath; + /** + * Creates a `FieldPath` from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames - A list of field names. + */ + constructor(...fieldNames: string[]); + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other - The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ + isEqual(other: FieldPath): boolean; +} + +/** + * A dot-separated path for navigating sub-objects within a document. + * @internal + */ +export declare class _FieldPath extends BasePath<_FieldPath> { + protected construct(segments: string[], offset?: number, length?: number): _FieldPath; + /** + * Returns true if the string could be used as a segment in a field path + * without escaping. + */ + private static isValidIdentifier; + canonicalString(): string; + toString(): string; + /** + * Returns true if this field references the key of a document. + */ + isKeyField(): boolean; + /** + * The field designating the key of a document. + */ + static keyField(): _FieldPath; + /** + * Parses a field string from the given server-formatted string. + * + * - Splitting the empty string is not allowed (for now at least). + * - Empty segments within the string (e.g. if there are two consecutive + * separators) are not allowed. + * + * TODO(b/37244157): we should make this more strict. Right now, it allows + * non-identifier path components, even if they aren't escaped. + */ + static fromServerFormat(path: string): _FieldPath; + static emptyPath(): _FieldPath; +} + +/** A field path and the TransformOperation to perform upon it. */ +declare class FieldTransform { + readonly field: _FieldPath; + readonly transform: TransformOperation; + constructor(field: _FieldPath, transform: TransformOperation); +} + +declare type FieldTransformSetToServerValue = 'SERVER_VALUE_UNSPECIFIED' | 'REQUEST_TIME'; + +/** + * Sentinel values that can be used when writing document fields with `set()` + * or `update()`. + */ +export declare abstract class FieldValue { + _methodName: string; + /** + * @param _methodName - The public API endpoint that returns this class. + * @hideconstructor + */ + constructor(_methodName: string); + /** Compares `FieldValue`s for equality. */ + abstract isEqual(other: FieldValue): boolean; + abstract _toFieldTransform(context: ParseContext): FieldTransform | null; +} + +declare abstract class Filter { + abstract matches(doc: Document_2): boolean; + abstract getFlattenedFilters(): readonly FieldFilter[]; + abstract getFilters(): Filter[]; +} + +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ +export declare class Firestore extends Firestore_2 { + /** + * Whether it's a {@link Firestore} or Firestore Lite instance. + */ + type: 'firestore-lite' | 'firestore'; + _queue: AsyncQueue; + readonly _persistenceKey: string; + _firestoreClient: FirestoreClient | undefined; + _componentsProvider?: { + _offline: OfflineComponentProviderFactory; + _online: OnlineComponentProviderFactory; + }; + /** @hideconstructor */ + constructor(authCredentialsProvider: CredentialsProvider, appCheckCredentialsProvider: CredentialsProvider, databaseId: _DatabaseId, app?: FirebaseApp); + protected _terminate(): Promise; +} + +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ +declare class Firestore_2 implements FirestoreService { + _authCredentials: CredentialsProvider; + _appCheckCredentials: CredentialsProvider; + readonly _databaseId: _DatabaseId; + readonly _app?: FirebaseApp | undefined; + /** + * Whether it's a Firestore or Firestore Lite instance. + */ + type: 'firestore-lite' | 'firestore'; + readonly _persistenceKey: string; + private _settings; + private _settingsFrozen; + private _emulatorOptions; + private _terminateTask; + /** @hideconstructor */ + constructor(_authCredentials: CredentialsProvider, _appCheckCredentials: CredentialsProvider, _databaseId: _DatabaseId, _app?: FirebaseApp | undefined); + /** + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service + * instance. + */ + get app(): FirebaseApp; + get _initialized(): boolean; + get _terminated(): boolean; + _setSettings(settings: PrivateSettings): void; + _getSettings(): FirestoreSettingsImpl; + _getEmulatorOptions(): { + mockUserToken?: EmulatorMockTokenOptions | string; + }; + _freezeSettings(): FirestoreSettingsImpl; + _delete(): Promise; + _restart(): Promise; + /** Returns a JSON-serializable representation of this `Firestore` instance. */ + toJSON(): object; + /** + * Terminates all components used by this client. Subclasses can override + * this method to clean up their own dependencies, but must also call this + * method. + * + * Only ever called once. + */ + protected _terminate(): Promise; +} + +/** + * FirestoreClient is a top-level class that constructs and owns all of the // + * pieces of the client SDK architecture. It is responsible for creating the // + * async queue that is shared by all of the other components in the system. // + */ +declare class FirestoreClient { + private authCredentials; + private appCheckCredentials; + /** + * Asynchronous queue responsible for all of our internal processing. When + * we get incoming work from the user (via public API) or the network + * (incoming GRPC messages), we should always schedule onto this queue. + * This ensures all of our work is properly serialized (e.g. we don't + * start processing a new operation while the previous one is waiting for + * an async I/O to complete). + */ + asyncQueue: AsyncQueue; + private databaseInfo; + private user; + private readonly clientId; + private authCredentialListener; + private appCheckCredentialListener; + _uninitializedComponentsProvider?: { + _offline: OfflineComponentProvider; + _online: OnlineComponentProvider; + }; + _offlineComponents?: OfflineComponentProvider; + _onlineComponents?: OnlineComponentProvider; + constructor(authCredentials: CredentialsProvider, appCheckCredentials: CredentialsProvider, + /** + * Asynchronous queue responsible for all of our internal processing. When + * we get incoming work from the user (via public API) or the network + * (incoming GRPC messages), we should always schedule onto this queue. + * This ensures all of our work is properly serialized (e.g. we don't + * start processing a new operation while the previous one is waiting for + * an async I/O to complete). + */ + asyncQueue: AsyncQueue, databaseInfo: DatabaseInfo, componentProvider?: { + _offline: OfflineComponentProvider; + _online: OnlineComponentProvider; + }); + get configuration(): ComponentConfiguration; + setCredentialChangeListener(listener: (user: User) => Promise): void; + setAppCheckTokenChangeListener(listener: (appCheckToken: string, user: User) => Promise): void; + terminate(): Promise; +} + +/** + * Converter used by `withConverter()` to transform user objects of type + * `AppModelType` into Firestore data of type `DbModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * In this context, an "AppModel" is a class that is used in an application to + * package together related information and functionality. Such a class could, + * for example, have properties with complex, nested data types, properties used + * for memoization, properties of types not supported by Firestore (such as + * `symbol` and `bigint`), and helper functions that perform compound + * operations. Such classes are not suitable and/or possible to store into a + * Firestore database. Instead, instances of such classes need to be converted + * to "plain old JavaScript objects" (POJOs) with exclusively primitive + * properties, potentially nested inside other POJOs or arrays of POJOs. In this + * context, this type is referred to as the "DbModel" and would be an object + * suitable for persisting into Firestore. For convenience, applications can + * implement `FirestoreDataConverter` and register the converter with Firestore + * objects, such as `DocumentReference` or `Query`, to automatically convert + * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel` + * to `AppModel` when retrieving from Firestore. + * + * @example + * + * Simple Example + * + * ```typescript + * const numberConverter = { + * toFirestore(value: WithFieldValue) { + * return { value }; + * }, + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) { + * return snapshot.data(options).value as number; + * } + * }; + * + * async function simpleDemo(db: Firestore): Promise { + * const documentRef = doc(db, 'values/value123').withConverter(numberConverter); + * + * // converters are used with `setDoc`, `addDoc`, and `getDoc` + * await setDoc(documentRef, 42); + * const snapshot1 = await getDoc(documentRef); + * assertEqual(snapshot1.data(), 42); + * + * // converters are not used when writing data with `updateDoc` + * await updateDoc(documentRef, { value: 999 }); + * const snapshot2 = await getDoc(documentRef); + * assertEqual(snapshot2.data(), 999); + * } + * ``` + * + * Advanced Example + * + * ```typescript + * // The Post class is a model that is used by our application. + * // This class may have properties and methods that are specific + * // to our application execution, which do not need to be persisted + * // to Firestore. + * class Post { + * constructor( + * readonly title: string, + * readonly author: string, + * readonly lastUpdatedMillis: number + * ) {} + * toString(): string { + * return `${this.title} by ${this.author}`; + * } + * } + * + * // The PostDbModel represents how we want our posts to be stored + * // in Firestore. This DbModel has different properties (`ttl`, + * // `aut`, and `lut`) from the Post class we use in our application. + * interface PostDbModel { + * ttl: string; + * aut: { firstName: string; lastName: string }; + * lut: Timestamp; + * } + * + * // The `PostConverter` implements `FirestoreDataConverter` and specifies + * // how the Firestore SDK can convert `Post` objects to `PostDbModel` + * // objects and vice versa. + * class PostConverter implements FirestoreDataConverter { + * toFirestore(post: WithFieldValue): WithFieldValue { + * return { + * ttl: post.title, + * aut: this._autFromAuthor(post.author), + * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis) + * }; + * } + * + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post { + * const data = snapshot.data(options) as PostDbModel; + * const author = `${data.aut.firstName} ${data.aut.lastName}`; + * return new Post(data.ttl, author, data.lut.toMillis()); + * } + * + * _autFromAuthor( + * author: string | FieldValue + * ): { firstName: string; lastName: string } | FieldValue { + * if (typeof author !== 'string') { + * // `author` is a FieldValue, so just return it. + * return author; + * } + * const [firstName, lastName] = author.split(' '); + * return {firstName, lastName}; + * } + * + * _lutFromLastUpdatedMillis( + * lastUpdatedMillis: number | FieldValue + * ): Timestamp | FieldValue { + * if (typeof lastUpdatedMillis !== 'number') { + * // `lastUpdatedMillis` must be a FieldValue, so just return it. + * return lastUpdatedMillis; + * } + * return Timestamp.fromMillis(lastUpdatedMillis); + * } + * } + * + * async function advancedDemo(db: Firestore): Promise { + * // Create a `DocumentReference` with a `FirestoreDataConverter`. + * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter()); + * + * // The `data` argument specified to `setDoc()` is type checked by the + * // TypeScript compiler to be compatible with `Post`. Since the `data` + * // argument is typed as `WithFieldValue` rather than just `Post`, + * // this allows properties of the `data` argument to also be special + * // Firestore values that perform server-side mutations, such as + * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`. + * await setDoc(documentRef, { + * title: 'My Life', + * author: 'Foo Bar', + * lastUpdatedMillis: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `setDoc()` is _not_ compatible with `WithFieldValue`. This + * // type checking prevents the caller from specifying objects with incorrect + * // properties or property values. + * // @ts-expect-error "Argument of type { ttl: string; } is not assignable + * // to parameter of type WithFieldValue" + * await setDoc(documentRef, { ttl: 'The Title' }); + * + * // When retrieving a document with `getDoc()` the `DocumentSnapshot` + * // object's `data()` method returns a `Post`, rather than a generic object, + * // which would have been returned if the `DocumentReference` did _not_ have a + * // `FirestoreDataConverter` attached to it. + * const snapshot1: DocumentSnapshot = await getDoc(documentRef); + * const post1: Post = snapshot1.data()!; + * if (post1) { + * assertEqual(post1.title, 'My Life'); + * assertEqual(post1.author, 'Foo Bar'); + * } + * + * // The `data` argument specified to `updateDoc()` is type checked by the + * // TypeScript compiler to be compatible with `PostDbModel`. Note that + * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`, + * // the `data` argument to `updateDoc()` must be compatible with + * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed + * // as `WithFieldValue` rather than just `PostDbModel`, this + * // allows properties of the `data` argument to also be those special + * // Firestore values, like `arrayRemove()`, `deleteField()`, and + * // `serverTimestamp()`. + * await updateDoc(documentRef, { + * 'aut.firstName': 'NewFirstName', + * lut: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `updateDoc()` is _not_ compatible with `WithFieldValue`. + * // This type checking prevents the caller from specifying objects with + * // incorrect properties or property values. + * // @ts-expect-error "Argument of type { title: string; } is not assignable + * // to parameter of type WithFieldValue" + * await updateDoc(documentRef, { title: 'New Title' }); + * const snapshot2: DocumentSnapshot = await getDoc(documentRef); + * const post2: Post = snapshot2.data()!; + * if (post2) { + * assertEqual(post2.title, 'My Life'); + * assertEqual(post2.author, 'NewFirstName Bar'); + * } + * } + * ``` + */ +export declare interface FirestoreDataConverter extends FirestoreDataConverter_2 { + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. To use `set()` + * with `merge` and `mergeFields`, `toFirestore()` must be defined with + * `PartialWithFieldValue`. + * + * The `WithFieldValue` type extends `T` to also allow FieldValues such as + * {@link (deleteField:1)} to be used as property values. + */ + toFirestore(modelObject: WithFieldValue): WithFieldValue; + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link (setDoc:1)}, {@link (WriteBatch.set:1)} and + * {@link (Transaction.set:1)} with `merge:true` or `mergeFields`. + * + * The `PartialWithFieldValue` type extends `Partial` to allow + * FieldValues such as {@link (arrayUnion:1)} to be used as property values. + * It also supports nested `Partial` by allowing nested fields to be + * omitted. + */ + toFirestore(modelObject: PartialWithFieldValue, options: SetOptions): PartialWithFieldValue; + /** + * Called by the Firestore SDK to convert Firestore data into an object of + * type `AppModelType`. You can access your data by calling: + * `snapshot.data(options)`. + * + * Generally, the data returned from `snapshot.data()` can be cast to + * `DbModelType`; however, this is not guaranteed because Firestore does not + * enforce a schema on the database. For example, writes from a previous + * version of the application or writes from another client that did not use a + * type converter could have written data with different properties and/or + * property types. The implementation will need to choose whether to + * gracefully recover from non-conforming data or throw an error. + * + * To override this method, see {@link (FirestoreDataConverter.fromFirestore:1)}. + * + * @param snapshot - A `QueryDocumentSnapshot` containing your data and metadata. + * @param options - The `SnapshotOptions` from the initial call to `data()`. + */ + fromFirestore(snapshot: QueryDocumentSnapshot, options?: SnapshotOptions): AppModelType; +} + +/** + * Converter used by `withConverter()` to transform user objects of type + * `AppModelType` into Firestore data of type `DbModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * In this context, an "AppModel" is a class that is used in an application to + * package together related information and functionality. Such a class could, + * for example, have properties with complex, nested data types, properties used + * for memoization, properties of types not supported by Firestore (such as + * `symbol` and `bigint`), and helper functions that perform compound + * operations. Such classes are not suitable and/or possible to store into a + * Firestore database. Instead, instances of such classes need to be converted + * to "plain old JavaScript objects" (POJOs) with exclusively primitive + * properties, potentially nested inside other POJOs or arrays of POJOs. In this + * context, this type is referred to as the "DbModel" and would be an object + * suitable for persisting into Firestore. For convenience, applications can + * implement `FirestoreDataConverter` and register the converter with Firestore + * objects, such as `DocumentReference` or `Query`, to automatically convert + * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel` + * to `AppModel` when retrieving from Firestore. + * + * @example + * + * Simple Example + * + * ```typescript + * const numberConverter = { + * toFirestore(value: WithFieldValue) { + * return { value }; + * }, + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) { + * return snapshot.data(options).value as number; + * } + * }; + * + * async function simpleDemo(db: Firestore): Promise { + * const documentRef = doc(db, 'values/value123').withConverter(numberConverter); + * + * // converters are used with `setDoc`, `addDoc`, and `getDoc` + * await setDoc(documentRef, 42); + * const snapshot1 = await getDoc(documentRef); + * assertEqual(snapshot1.data(), 42); + * + * // converters are not used when writing data with `updateDoc` + * await updateDoc(documentRef, { value: 999 }); + * const snapshot2 = await getDoc(documentRef); + * assertEqual(snapshot2.data(), 999); + * } + * ``` + * + * Advanced Example + * + * ```typescript + * // The Post class is a model that is used by our application. + * // This class may have properties and methods that are specific + * // to our application execution, which do not need to be persisted + * // to Firestore. + * class Post { + * constructor( + * readonly title: string, + * readonly author: string, + * readonly lastUpdatedMillis: number + * ) {} + * toString(): string { + * return `${this.title} by ${this.author}`; + * } + * } + * + * // The PostDbModel represents how we want our posts to be stored + * // in Firestore. This DbModel has different properties (`ttl`, + * // `aut`, and `lut`) from the Post class we use in our application. + * interface PostDbModel { + * ttl: string; + * aut: { firstName: string; lastName: string }; + * lut: Timestamp; + * } + * + * // The `PostConverter` implements `FirestoreDataConverter` and specifies + * // how the Firestore SDK can convert `Post` objects to `PostDbModel` + * // objects and vice versa. + * class PostConverter implements FirestoreDataConverter { + * toFirestore(post: WithFieldValue): WithFieldValue { + * return { + * ttl: post.title, + * aut: this._autFromAuthor(post.author), + * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis) + * }; + * } + * + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post { + * const data = snapshot.data(options) as PostDbModel; + * const author = `${data.aut.firstName} ${data.aut.lastName}`; + * return new Post(data.ttl, author, data.lut.toMillis()); + * } + * + * _autFromAuthor( + * author: string | FieldValue + * ): { firstName: string; lastName: string } | FieldValue { + * if (typeof author !== 'string') { + * // `author` is a FieldValue, so just return it. + * return author; + * } + * const [firstName, lastName] = author.split(' '); + * return {firstName, lastName}; + * } + * + * _lutFromLastUpdatedMillis( + * lastUpdatedMillis: number | FieldValue + * ): Timestamp | FieldValue { + * if (typeof lastUpdatedMillis !== 'number') { + * // `lastUpdatedMillis` must be a FieldValue, so just return it. + * return lastUpdatedMillis; + * } + * return Timestamp.fromMillis(lastUpdatedMillis); + * } + * } + * + * async function advancedDemo(db: Firestore): Promise { + * // Create a `DocumentReference` with a `FirestoreDataConverter`. + * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter()); + * + * // The `data` argument specified to `setDoc()` is type checked by the + * // TypeScript compiler to be compatible with `Post`. Since the `data` + * // argument is typed as `WithFieldValue` rather than just `Post`, + * // this allows properties of the `data` argument to also be special + * // Firestore values that perform server-side mutations, such as + * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`. + * await setDoc(documentRef, { + * title: 'My Life', + * author: 'Foo Bar', + * lastUpdatedMillis: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `setDoc()` is _not_ compatible with `WithFieldValue`. This + * // type checking prevents the caller from specifying objects with incorrect + * // properties or property values. + * // @ts-expect-error "Argument of type { ttl: string; } is not assignable + * // to parameter of type WithFieldValue" + * await setDoc(documentRef, { ttl: 'The Title' }); + * + * // When retrieving a document with `getDoc()` the `DocumentSnapshot` + * // object's `data()` method returns a `Post`, rather than a generic object, + * // which would have been returned if the `DocumentReference` did _not_ have a + * // `FirestoreDataConverter` attached to it. + * const snapshot1: DocumentSnapshot = await getDoc(documentRef); + * const post1: Post = snapshot1.data()!; + * if (post1) { + * assertEqual(post1.title, 'My Life'); + * assertEqual(post1.author, 'Foo Bar'); + * } + * + * // The `data` argument specified to `updateDoc()` is type checked by the + * // TypeScript compiler to be compatible with `PostDbModel`. Note that + * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`, + * // the `data` argument to `updateDoc()` must be compatible with + * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed + * // as `WithFieldValue` rather than just `PostDbModel`, this + * // allows properties of the `data` argument to also be those special + * // Firestore values, like `arrayRemove()`, `deleteField()`, and + * // `serverTimestamp()`. + * await updateDoc(documentRef, { + * 'aut.firstName': 'NewFirstName', + * lut: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `updateDoc()` is _not_ compatible with `WithFieldValue`. + * // This type checking prevents the caller from specifying objects with + * // incorrect properties or property values. + * // @ts-expect-error "Argument of type { title: string; } is not assignable + * // to parameter of type WithFieldValue" + * await updateDoc(documentRef, { title: 'New Title' }); + * const snapshot2: DocumentSnapshot = await getDoc(documentRef); + * const post2: Post = snapshot2.data()!; + * if (post2) { + * assertEqual(post2.title, 'My Life'); + * assertEqual(post2.author, 'NewFirstName Bar'); + * } + * } + * ``` + */ +declare interface FirestoreDataConverter_2 { + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link @firebase/firestore/lite#(setDoc:1)}, + * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and + * {@link @firebase/firestore/lite#(Transaction.set:1)}. + * + * The `WithFieldValue` type extends `T` to also allow FieldValues such as + * {@link (deleteField:1)} to be used as property values. + */ + toFirestore(modelObject: WithFieldValue): WithFieldValue; + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link @firebase/firestore/lite#(setDoc:1)}, + * {@link @firebase/firestore/lite#(WriteBatch.set:1)} and + * {@link @firebase/firestore/lite#(Transaction.set:1)} with `merge:true` + * or `mergeFields`. + * + * The `PartialWithFieldValue` type extends `Partial` to allow + * FieldValues such as {@link (arrayUnion:1)} to be used as property values. + * It also supports nested `Partial` by allowing nested fields to be + * omitted. + */ + toFirestore(modelObject: PartialWithFieldValue, options: SetOptions): PartialWithFieldValue; + /** + * Called by the Firestore SDK to convert Firestore data into an object of + * type `AppModelType`. You can access your data by calling: + * `snapshot.data()`. + * + * + * Generally, the data returned from `snapshot.data()` can be cast to + * `DbModelType`; however, this is not guaranteed because Firestore does not + * enforce a schema on the database. For example, writes from a previous + * version of the application or writes from another client that did not use a + * type converter could have written data with different properties and/or + * property types. The implementation will need to choose whether to + * gracefully recover from non-conforming data or throw an error. + * + * @param snapshot - A `QueryDocumentSnapshot` containing your data and + * metadata. + */ + fromFirestore(snapshot: QueryDocumentSnapshot_2): AppModelType; +} + +/** An error returned by a Firestore operation. */ +export declare class FirestoreError extends FirebaseError { + /** + * The backend error code associated with this error. + */ + readonly code: FirestoreErrorCode; + /** + * A custom error description. + */ + readonly message: string; + /** The stack of the error. */ + readonly stack?: string; + /** @hideconstructor */ + constructor( + /** + * The backend error code associated with this error. + */ + code: FirestoreErrorCode, + /** + * A custom error description. + */ + message: string); +} + +/** + * The set of Firestore status codes. The codes are the same at the ones + * exposed by gRPC here: + * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md + * + * Possible values: + * - 'cancelled': The operation was cancelled (typically by the caller). + * - 'unknown': Unknown error or an error from a different error domain. + * - 'invalid-argument': Client specified an invalid argument. Note that this + * differs from 'failed-precondition'. 'invalid-argument' indicates + * arguments that are problematic regardless of the state of the system + * (e.g. an invalid field name). + * - 'deadline-exceeded': Deadline expired before operation could complete. + * For operations that change the state of the system, this error may be + * returned even if the operation has completed successfully. For example, + * a successful response from a server could have been delayed long enough + * for the deadline to expire. + * - 'not-found': Some requested document was not found. + * - 'already-exists': Some document that we attempted to create already + * exists. + * - 'permission-denied': The caller does not have permission to execute the + * specified operation. + * - 'resource-exhausted': Some resource has been exhausted, perhaps a + * per-user quota, or perhaps the entire file system is out of space. + * - 'failed-precondition': Operation was rejected because the system is not + * in a state required for the operation's execution. + * - 'aborted': The operation was aborted, typically due to a concurrency + * issue like transaction aborts, etc. + * - 'out-of-range': Operation was attempted past the valid range. + * - 'unimplemented': Operation is not implemented or not supported/enabled. + * - 'internal': Internal errors. Means some invariants expected by + * underlying system has been broken. If you see one of these errors, + * something is very broken. + * - 'unavailable': The service is currently unavailable. This is most likely + * a transient condition and may be corrected by retrying with a backoff. + * - 'data-loss': Unrecoverable data loss or corruption. + * - 'unauthenticated': The request does not have valid authentication + * credentials for the operation. + */ +export declare type FirestoreErrorCode = 'cancelled' | 'unknown' | 'invalid-argument' | 'deadline-exceeded' | 'not-found' | 'already-exists' | 'permission-denied' | 'resource-exhausted' | 'failed-precondition' | 'aborted' | 'out-of-range' | 'unimplemented' | 'internal' | 'unavailable' | 'data-loss' | 'unauthenticated'; + +/** + * Union type from all supported SDK cache layer. + */ +export declare type FirestoreLocalCache = MemoryLocalCache | PersistentLocalCache; + +/** + * An interface implemented by FirebaseFirestore that provides compatibility + * with the usage in this file. + * + * This interface mainly exists to remove a cyclic dependency. + */ +declare interface FirestoreService extends _FirebaseService { + _authCredentials: CredentialsProvider; + _appCheckCredentials: CredentialsProvider; + _persistenceKey: string; + _databaseId: _DatabaseId; + _terminated: boolean; + _freezeSettings(): FirestoreSettingsImpl; +} + +/** + * Specifies custom configurations for your Cloud Firestore instance. + * You must set these before invoking any other methods. + */ +export declare interface FirestoreSettings extends FirestoreSettings_2 { + /** + * NOTE: This field will be deprecated in a future major release. Use `cache` field + * instead to specify cache size, and other cache configurations. + * + * An approximate cache size threshold for the on-disk data. If the cache + * grows beyond this size, Firestore will start removing data that hasn't been + * recently used. The size is not a guarantee that the cache will stay below + * that size, only that if the cache exceeds the given size, cleanup will be + * attempted. + * + * The default value is 40 MB. The threshold must be set to at least 1 MB, and + * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection. + */ + cacheSizeBytes?: number; + /** + * Specifies the cache used by the SDK. Available options are `MemoryLocalCache` + * and `PersistentLocalCache`, each with different configuration options. + * + * When unspecified, `MemoryLocalCache` will be used by default. + * + * NOTE: setting this field and `cacheSizeBytes` at the same time will throw + * exception during SDK initialization. Instead, using the configuration in + * the `FirestoreLocalCache` object to specify the cache size. + */ + localCache?: FirestoreLocalCache; + /** + * Forces the SDK’s underlying network transport (WebChannel) to use + * long-polling. Each response from the backend will be closed immediately + * after the backend sends data (by default responses are kept open in + * case the backend has more data to send). This avoids incompatibility + * issues with certain proxies, antivirus software, etc. that incorrectly + * buffer traffic indefinitely. Use of this option will cause some + * performance degradation though. + * + * This setting cannot be used with `experimentalAutoDetectLongPolling` and + * may be removed in a future release. If you find yourself using it to + * work around a specific network reliability issue, please tell us about + * it in https://github.com/firebase/firebase-js-sdk/issues/1674. + * + * This setting cannot be used in a Node.js environment. + */ + experimentalForceLongPolling?: boolean; + /** + * Configures the SDK's underlying transport (WebChannel) to automatically + * detect if long-polling should be used. This is very similar to + * `experimentalForceLongPolling`, but only uses long-polling if required. + * + * After having had a default value of `false` since its inception in 2019, + * the default value of this setting was changed in May 2023 to `true` in + * v9.22.0 of the Firebase JavaScript SDK. That is, auto-detection of long + * polling is now enabled by default. To disable it, set this setting to + * `false`, and please open a GitHub issue to share the problems that + * motivated you disabling long-polling auto-detection. + * + * This setting cannot be used in a Node.js environment. + */ + experimentalAutoDetectLongPolling?: boolean; + /** + * Options that configure the SDK’s underlying network transport (WebChannel) + * when long-polling is used. + * + * These options are only used if `experimentalForceLongPolling` is true or if + * `experimentalAutoDetectLongPolling` is true and the auto-detection + * determined that long-polling was needed. Otherwise, these options have no + * effect. + */ + experimentalLongPollingOptions?: ExperimentalLongPollingOptions; +} + +/** + * Specifies custom configurations for your Cloud Firestore instance. + * You must set these before invoking any other methods. + */ +declare interface FirestoreSettings_2 { + /** The hostname to connect to. */ + host?: string; + /** Whether to use SSL when connecting. */ + ssl?: boolean; + /** + * Whether to skip nested properties that are set to `undefined` during + * object serialization. If set to `true`, these properties are skipped + * and not written to Firestore. If set to `false` or omitted, the SDK + * throws an exception when it encounters properties of type `undefined`. + */ + ignoreUndefinedProperties?: boolean; +} + +/** + * A concrete type describing all the values that can be applied via a + * user-supplied `FirestoreSettings` object. This is a separate type so that + * defaults can be supplied and the value can be checked for equality. + */ +declare class FirestoreSettingsImpl { + /** The hostname to connect to. */ + readonly host: string; + /** Whether to use SSL when connecting. */ + readonly ssl: boolean; + readonly cacheSizeBytes: number; + readonly experimentalForceLongPolling: boolean; + readonly experimentalAutoDetectLongPolling: boolean; + readonly experimentalLongPollingOptions: ExperimentalLongPollingOptions; + readonly ignoreUndefinedProperties: boolean; + readonly useFetchStreams: boolean; + readonly localCache?: FirestoreLocalCache; + readonly isUsingEmulator: boolean; + credentials?: any; + constructor(settings: PrivateSettings); + isEqual(other: FirestoreSettingsImpl): boolean; +} + +declare namespace firestoreV1ApiClientInterfaces { + interface ArrayValue { + values?: Value[]; + } + interface BatchGetDocumentsRequest { + database?: string; + documents?: string[]; + mask?: DocumentMask; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface BatchGetDocumentsResponse { + found?: Document; + missing?: string; + transaction?: string; + readTime?: string; + } + interface BeginTransactionRequest { + options?: TransactionOptions; + } + interface BeginTransactionResponse { + transaction?: string; + } + interface CollectionSelector { + collectionId?: string; + allDescendants?: boolean; + } + interface CommitRequest { + database?: string; + writes?: Write[]; + transaction?: string; + } + interface CommitResponse { + writeResults?: WriteResult[]; + commitTime?: string; + } + interface CompositeFilter { + op?: CompositeFilterOp; + filters?: Filter[]; + } + interface Cursor { + values?: Value[]; + before?: boolean; + } + interface Document { + name?: string; + fields?: ApiClientObjectMap; + createTime?: Timestamp_2; + updateTime?: Timestamp_2; + } + interface DocumentChange { + document?: Document; + targetIds?: number[]; + removedTargetIds?: number[]; + } + interface DocumentDelete { + document?: string; + removedTargetIds?: number[]; + readTime?: Timestamp_2; + } + interface DocumentMask { + fieldPaths?: string[]; + } + interface DocumentRemove { + document?: string; + removedTargetIds?: number[]; + readTime?: string; + } + interface DocumentTransform { + document?: string; + fieldTransforms?: FieldTransform[]; + } + interface DocumentsTarget { + documents?: string[]; + } + interface Empty { + } + interface ExistenceFilter { + targetId?: number; + count?: number; + unchangedNames?: BloomFilter; + } + interface BloomFilter { + bits?: BitSequence; + hashCount?: number; + } + interface BitSequence { + bitmap?: string | Uint8Array; + padding?: number; + } + interface FieldFilter { + field?: FieldReference; + op?: FieldFilterOp; + value?: Value; + } + interface FieldReference { + fieldPath?: string; + } + interface FieldTransform { + fieldPath?: string; + setToServerValue?: FieldTransformSetToServerValue; + appendMissingElements?: ArrayValue; + removeAllFromArray?: ArrayValue; + increment?: Value; + } + interface Filter { + compositeFilter?: CompositeFilter; + fieldFilter?: FieldFilter; + unaryFilter?: UnaryFilter; + } + interface Index { + name?: string; + collectionId?: string; + fields?: IndexField[]; + state?: IndexState_2; + } + interface IndexField { + fieldPath?: string; + mode?: IndexFieldMode; + } + interface LatLng { + latitude?: number; + longitude?: number; + } + interface ListCollectionIdsRequest { + pageSize?: number; + pageToken?: string; + } + interface ListCollectionIdsResponse { + collectionIds?: string[]; + nextPageToken?: string; + } + interface ListDocumentsResponse { + documents?: Document[]; + nextPageToken?: string; + } + interface ListIndexesResponse { + indexes?: Index[]; + nextPageToken?: string; + } + interface ListenRequest { + addTarget?: Target; + removeTarget?: number; + labels?: ApiClientObjectMap; + } + interface ListenResponse { + targetChange?: TargetChange; + documentChange?: DocumentChange; + documentDelete?: DocumentDelete; + documentRemove?: DocumentRemove; + filter?: ExistenceFilter; + } + interface MapValue { + fields?: ApiClientObjectMap; + } + interface Operation { + name?: string; + metadata?: ApiClientObjectMap; + done?: boolean; + error?: Status; + response?: ApiClientObjectMap; + } + interface Order { + field?: FieldReference; + direction?: OrderDirection; + } + interface Precondition { + exists?: boolean; + updateTime?: Timestamp_2; + } + interface Projection { + fields?: FieldReference[]; + } + interface QueryTarget { + parent?: string; + structuredQuery?: StructuredQuery; + } + interface ReadOnly { + readTime?: string; + } + interface ReadWrite { + retryTransaction?: string; + } + interface RollbackRequest { + transaction?: string; + } + interface RunQueryRequest { + parent?: string; + structuredQuery?: StructuredQuery; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface RunQueryResponse { + transaction?: string; + document?: Document; + readTime?: string; + skippedResults?: number; + } + interface RunAggregationQueryRequest { + parent?: string; + structuredAggregationQuery?: StructuredAggregationQuery; + transaction?: string; + newTransaction?: TransactionOptions; + readTime?: string; + } + interface RunAggregationQueryResponse { + result?: AggregationResult; + transaction?: string; + readTime?: string; + } + interface AggregationResult { + aggregateFields?: ApiClientObjectMap; + } + interface StructuredAggregationQuery { + structuredQuery?: StructuredQuery; + aggregations?: Aggregation[]; + } + interface Aggregation { + count?: Count; + sum?: Sum; + avg?: Avg; + alias?: string; + } + interface Count { + upTo?: number; + } + interface Sum { + field?: FieldReference; + } + interface Avg { + field?: FieldReference; + } + interface Status { + code?: number; + message?: string; + details?: Array>; + } + interface StructuredQuery { + select?: Projection; + from?: CollectionSelector[]; + where?: Filter; + orderBy?: Order[]; + startAt?: Cursor; + endAt?: Cursor; + offset?: number; + limit?: number | { + value: number; + }; + } + interface Target { + query?: QueryTarget; + documents?: DocumentsTarget; + resumeToken?: string | Uint8Array; + readTime?: Timestamp_2; + targetId?: number; + once?: boolean; + expectedCount?: number | { + value: number; + }; + } + interface TargetChange { + targetChangeType?: TargetChangeTargetChangeType; + targetIds?: number[]; + cause?: Status; + resumeToken?: string | Uint8Array; + readTime?: Timestamp_2; + } + interface TransactionOptions { + readOnly?: ReadOnly; + readWrite?: ReadWrite; + } + interface UnaryFilter { + op?: UnaryFilterOp; + field?: FieldReference; + } + interface Value { + nullValue?: ValueNullValue; + booleanValue?: boolean; + integerValue?: string | number; + doubleValue?: string | number; + timestampValue?: Timestamp_2; + stringValue?: string; + bytesValue?: string | Uint8Array; + referenceValue?: string; + geoPointValue?: LatLng; + arrayValue?: ArrayValue; + mapValue?: MapValue; + } + interface Write { + update?: Document; + delete?: string; + verify?: string; + transform?: DocumentTransform; + updateMask?: DocumentMask; + updateTransforms?: FieldTransform[]; + currentDocument?: Precondition; + } + interface WriteRequest { + streamId?: string; + writes?: Write[]; + streamToken?: string | Uint8Array; + labels?: ApiClientObjectMap; + } + interface WriteResponse { + streamId?: string; + streamToken?: string | Uint8Array; + writeResults?: WriteResult[]; + commitTime?: Timestamp_2; + } + interface WriteResult { + updateTime?: Timestamp_2; + transformResults?: Value[]; + } +} + +/** + * @internal + */ +export declare interface FirstPartyCredentialsSettings { + ['type']: 'firstParty'; + ['sessionIndex']: string; + ['iamToken']: string | null; + ['authTokenFactory']: AuthTokenFactory | null; +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +declare type FulfilledHandler = ((result: T) => R | PersistencePromise) | null; + +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ +export declare class GeoPoint { + private _lat; + private _long; + /** + * Creates a new immutable `GeoPoint` object with the provided latitude and + * longitude values. + * @param latitude - The latitude as number between -90 and 90. + * @param longitude - The longitude as number between -180 and 180. + */ + constructor(latitude: number, longitude: number); + /** + * The latitude of this `GeoPoint` instance. + */ + get latitude(): number; + /** + * The longitude of this `GeoPoint` instance. + */ + get longitude(): number; + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other - The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ + isEqual(other: GeoPoint): boolean; + /** + * Actually private to JS consumers of our API, so this function is prefixed + * with an underscore. + */ + _compareTo(other: GeoPoint): number; + static _jsonSchemaVersion: string; + static _jsonSchema: { + type: Property<"string">; + latitude: Property<"number">; + longitude: Property<"number">; + }; + /** + * Returns a JSON-serializable representation of this `GeoPoint` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): { + latitude: number; + longitude: number; + type: string; + }; + /** + * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}. + * + * @param json a JSON object represention of a `GeoPoint` instance + * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): GeoPoint; +} + +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregateFromServer(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ +export declare function getAggregateFromServer(query: Query, aggregateSpec: AggregateSpecType): Promise>; + +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ +export declare function getCountFromServer(query: Query): Promise; +}, AppModelType, DbModelType>>; + +/** + * Reads the document referred to by this `DocumentReference`. + * + * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting + * for data from the server, but it may return cached data or fail if you are + * offline and the server cannot be reached. To specify this behavior, invoke + * {@link getDocFromCache} or {@link getDocFromServer}. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +export declare function getDoc(reference: DocumentReference): Promise>; + +/** + * Reads the document referred to by this `DocumentReference` from cache. + * Returns an error if the document is not currently cached. + * + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +export declare function getDocFromCache(reference: DocumentReference): Promise>; + +/** + * Reads the document referred to by this `DocumentReference` from the server. + * Returns an error if the network is not available. + * + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +export declare function getDocFromServer(reference: DocumentReference): Promise>; + +/** + * Executes the query and returns the results as a `QuerySnapshot`. + * + * Note: `getDocs()` attempts to provide up-to-date data when possible by + * waiting for data from the server, but it may return cached data or fail if + * you are offline and the server cannot be reached. To specify this behavior, + * invoke {@link getDocsFromCache} or {@link getDocsFromServer}. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +export declare function getDocs(query: Query): Promise>; + +/** + * Executes the query and returns the results as a `QuerySnapshot` from cache. + * Returns an empty result set if no documents matching the query are currently + * cached. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +export declare function getDocsFromCache(query: Query): Promise>; + +/** + * Executes the query and returns the results as a `QuerySnapshot` from the + * server. Returns an error if the network is not available. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +export declare function getDocsFromServer(query: Query): Promise>; + +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @returns The default {@link Firestore} instance of the default app. + */ +export declare function getFirestore(): Firestore; + +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @returns The default {@link Firestore} instance of the provided app. + */ +export declare function getFirestore(app: FirebaseApp): Firestore; + +/** + * Returns the existing named {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param databaseId - The name of the database. + * @returns The named {@link Firestore} instance of the default app. + * @beta + */ +export declare function getFirestore(databaseId: string): Firestore; + +/** + * Returns the existing named {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @param databaseId - The name of the database. + * @returns The named {@link Firestore} instance of the provided app. + * @beta + */ +export declare function getFirestore(app: FirebaseApp, databaseId: string): Firestore; + +/** + * Returns the PersistentCache Index Manager used by the given `Firestore` + * object. + * + * @return The `PersistentCacheIndexManager` instance, or `null` if local + * persistent storage is not in use. + */ +export declare function getPersistentCacheIndexManager(firestore: Firestore): PersistentCacheIndexManager | null; + +/** + * General purpose cache for global values. + * + * Global state that cuts across components should be saved here. Following are contained herein: + * + * `sessionToken` tracks server interaction across Listen and Write streams. This facilitates cache + * synchronization and invalidation. + */ +declare interface GlobalsCache { + /** + * Gets session token. + */ + getSessionToken(transaction: PersistenceTransaction): PersistencePromise<_ByteString>; + /** + * Sets session token. + * + * @param sessionToken - The new session token. + */ + setSessionToken(transaction: PersistenceTransaction, sessionToken: _ByteString): PersistencePromise; +} + +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by + * the given value. + * + * If either the operand or the current field value uses floating point + * precision, all arithmetic follows IEEE 754 semantics. If both values are + * integers, values outside of JavaScript's safe number range + * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to + * precision loss. Furthermore, once processed by the Firestore backend, all + * integer operations are capped between -2^63 and 2^63-1. + * + * If the current field value is not of type `number`, or if the field does not + * yet exist, the transformation sets the field to the given value. + * + * @param n - The value to increment by. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +export declare function increment(n: number): FieldValue; + +/** + * The SDK definition of a Firestore index. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare interface Index { + /** The ID of the collection to index. */ + readonly collectionGroup: string; + /** A list of fields to index. */ + readonly fields?: IndexField[]; + [key: string]: unknown; +} + +/** + * A list of Firestore indexes to speed up local query execution. + * + * See {@link https://firebase.google.com/docs/reference/firestore/indexes/#json_format | JSON Format} + * for a description of the format of the index definition. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare interface IndexConfiguration { + /** A list of all Firestore indexes. */ + readonly indexes?: Index[]; + [key: string]: unknown; +} + +/** + * A single field element in an index configuration. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare interface IndexField { + /** The field path to index. */ + readonly fieldPath: string; + /** + * What type of array index to create. Set to `CONTAINS` for `array-contains` + * and `array-contains-any` indexes. + * + * Only one of `arrayConfig` or `order` should be set; + */ + readonly arrayConfig?: 'CONTAINS'; + /** + * What type of array index to create. Set to `ASCENDING` or 'DESCENDING` for + * `==`, `!=`, `<=`, `<=`, `in` and `not-in` filters. + * + * Only one of `arrayConfig` or `order` should be set. + */ + readonly order?: 'ASCENDING' | 'DESCENDING'; + [key: string]: unknown; +} + +declare type IndexFieldMode = 'MODE_UNSPECIFIED' | 'ASCENDING' | 'DESCENDING'; + +/** The type of the index, e.g. for which type of query it can be used. */ +declare const enum IndexKind { + /** + * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries. + */ + ASCENDING = 0, + /** + * Ordered index. Can be used for <, <=, ==, >=, >, !=, IN and NOT IN queries. + */ + DESCENDING = 1, + /** Contains index. Can be used for ArrayContains and ArrayContainsAny. */ + CONTAINS = 2 +} + +/** + * Represents a set of indexes that are used to execute queries efficiently. + * + * Currently the only index is a [collection id] => [parent path] index, used + * to execute Collection Group queries. + */ +declare interface IndexManager { + /** + * Creates an index entry mapping the collectionId (last segment of the path) + * to the parent path (either the containing document location or the empty + * path for root-level collections). Index entries can be retrieved via + * getCollectionParents(). + * + * NOTE: Currently we don't remove index entries. If this ends up being an + * issue we can devise some sort of GC strategy. + */ + addToCollectionParentIndex(transaction: PersistenceTransaction, collectionPath: _ResourcePath): PersistencePromise; + /** + * Retrieves all parent locations containing the given collectionId, as a + * list of paths (each path being either a document location or the empty + * path for a root-level collection). + */ + getCollectionParents(transaction: PersistenceTransaction, collectionId: string): PersistencePromise<_ResourcePath[]>; + /** + * Adds a field path index. + * + * Values for this index are persisted via the index backfill, which runs + * asynchronously in the background. Once the first values are written, + * an index can be used to serve partial results for any matching queries. + * Any unindexed portion of the database will continue to be served via + * collection scons. + */ + addFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + /** Removes the given field index and deletes all index values. */ + deleteFieldIndex(transaction: PersistenceTransaction, index: FieldIndex): PersistencePromise; + /** Removes all field indexes and deletes all index values. */ + deleteAllFieldIndexes(transaction: PersistenceTransaction): PersistencePromise; + /** Creates a full matched field index which serves the given target. */ + createTargetIndexes(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Returns a list of field indexes that correspond to the specified collection + * group. + * + * @param collectionGroup The collection group to get matching field indexes + * for. + * @return A collection of field indexes for the specified collection group. + */ + getFieldIndexes(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise; + /** Returns all configured field indexes. */ + getFieldIndexes(transaction: PersistenceTransaction): PersistencePromise; + /** + * Returns the type of index (if any) that can be used to serve the given + * target. + */ + getIndexType(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** + * Returns the documents that match the given target based on the provided + * index or `null` if the target does not have a matching index. + */ + getDocumentsMatchingTarget(transaction: PersistenceTransaction, target: Target): PersistencePromise<_DocumentKey[] | null>; + /** + * Returns the next collection group to update. Returns `null` if no group + * exists. + */ + getNextCollectionGroupToUpdate(transaction: PersistenceTransaction): PersistencePromise; + /** + * Sets the collection group's latest read time. + * + * This method updates the index offset for all field indices for the + * collection group and increments their sequence number. Subsequent calls to + * `getNextCollectionGroupToUpdate()` will return a different collection group + * (unless only one collection group is configured). + */ + updateCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string, offset: IndexOffset): PersistencePromise; + /** Updates the index entries for the provided documents. */ + updateIndexEntries(transaction: PersistenceTransaction, documents: DocumentMap): PersistencePromise; + /** + * Iterates over all field indexes that are used to serve the given target, + * and returns the minimum offset of them all. + */ + getMinOffset(transaction: PersistenceTransaction, target: Target): PersistencePromise; + /** Returns the minimum offset for the given collection group. */ + getMinOffsetFromCollectionGroup(transaction: PersistenceTransaction, collectionGroup: string): PersistencePromise; +} + +/** + * Stores the latest read time, document and batch ID that were processed for an + * index. + */ +declare class IndexOffset { + /** + * The latest read time version that has been indexed by Firestore for this + * field index. + */ + readonly readTime: SnapshotVersion; + /** + * The key of the last document that was indexed for this query. Use + * `DocumentKey.empty()` if no document has been indexed. + */ + readonly documentKey: _DocumentKey; + readonly largestBatchId: number; + constructor( + /** + * The latest read time version that has been indexed by Firestore for this + * field index. + */ + readTime: SnapshotVersion, + /** + * The key of the last document that was indexed for this query. Use + * `DocumentKey.empty()` if no document has been indexed. + */ + documentKey: _DocumentKey, largestBatchId: number); + /** Returns an offset that sorts before all regular offsets. */ + static min(): IndexOffset; + /** Returns an offset that sorts after all regular offsets. */ + static max(): IndexOffset; +} + +/** An index component consisting of field path and index type. */ +declare class IndexSegment { + /** The field path of the component. */ + readonly fieldPath: _FieldPath; + /** The fields sorting order. */ + readonly kind: IndexKind; + constructor( + /** The field path of the component. */ + fieldPath: _FieldPath, + /** The fields sorting order. */ + kind: IndexKind); +} + +/** + * Stores the "high water mark" that indicates how updated the Index is for the + * current user. + */ +declare class IndexState { + /** + * Indicates when the index was last updated (relative to other indexes). + */ + readonly sequenceNumber: number; + /** The the latest indexed read time, document and batch id. */ + readonly offset: IndexOffset; + constructor( + /** + * Indicates when the index was last updated (relative to other indexes). + */ + sequenceNumber: number, + /** The the latest indexed read time, document and batch id. */ + offset: IndexOffset); + /** The state of an index that has not yet been backfilled. */ + static empty(): IndexState; +} + +declare type IndexState_2 = 'STATE_UNSPECIFIED' | 'CREATING' | 'READY' | 'ERROR'; + +/** Represents the index state as it relates to a particular target. */ +declare const enum IndexType { + /** Indicates that no index could be found for serving the target. */ + NONE = 0, + /** + * Indicates that only a "partial index" could be found for serving the + * target. A partial index is one which does not have a segment for every + * filter/orderBy in the target. + */ + PARTIAL = 1, + /** + * Indicates that a "full index" could be found for serving the target. A full + * index is one which has a segment for every filter/orderBy in the target. + */ + FULL = 2 +} + +/** + * Initializes a new instance of {@link Firestore} with the provided settings. + * Can only be called before any other function, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will + * be associated. + * @param settings - A settings object to configure the {@link Firestore} instance. + * @param databaseId - The name of the database. + * @returns A newly initialized {@link Firestore} instance. + */ +export declare function initializeFirestore(app: FirebaseApp, settings: FirestoreSettings, databaseId?: string): Firestore; + +/** + * @internal + * @private + * + * This function is for internal use only. + * + * Returns `RunAggregationQueryRequest` which contains the proto representation + * of the given aggregation query request. Returns null if the Firestore client + * associated with the given query has not been initialized or has been + * terminated. + * + * @param query - The Query to convert to proto representation. + * @param aggregateSpec - The set of aggregations and their aliases. + */ +export declare function _internalAggregationQueryToProtoRunAggregationQueryRequest(query: Query, aggregateSpec: AggregateSpecType): any; + +/** + * @internal + * @private + * + * This function is for internal use only. + * + * Returns the `QueryTarget` representation of the given query. Returns `null` + * if the Firestore client associated with the given query has not been + * initialized or has been terminated. + * + * @param query - The Query to convert to proto representation. + */ +export declare function _internalQueryToProtoQueryTarget(query: Query): any; + +/** + * True if and only if the Base64 conversion functions are available. + * @internal + */ +export declare function _isBase64Available(): boolean; + +/** + * This class generates JsonObject values for the Datastore API suitable for + * sending to either GRPC stub methods or via the JSON/HTTP REST API. + * + * The serializer supports both Protobuf.js and Proto3 JSON formats. By + * setting `useProto3Json` to true, the serializer will use the Proto3 JSON + * format. + * + * For a description of the Proto3 JSON format check + * https://developers.google.com/protocol-buffers/docs/proto3#json + * + * TODO(klimt): We can remove the databaseId argument if we keep the full + * resource name in documents. + */ +declare class JsonProtoSerializer implements Serializer { + readonly databaseId: _DatabaseId; + readonly useProto3Json: boolean; + constructor(databaseId: _DatabaseId, useProto3Json: boolean); +} + +/** + * @license + * Copyright 2025 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * A list of data types Firestore objects may serialize in their toJSON implemenetations. + * @private + * @internal + */ +declare type JsonTypeDesc = 'object' | 'string' | 'number' | 'boolean' | 'null' | 'undefined'; + +declare type Kind = 'memory' | 'persistent'; + +/** + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +export declare function limit(limit: number): QueryLimitConstraint; + +/** + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. + * + * You must specify at least one `orderBy` clause for `limitToLast` queries, + * otherwise an exception will be thrown during execution. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +export declare function limitToLast(limit: number): QueryLimitConstraint; + +declare const enum LimitType { + First = "F", + Last = "L" +} + +/** LimitType enum. */ +declare type LimitType_2 = 'FIRST' | 'LAST'; + +declare type ListenSequenceNumber = number; + +/** + * Describe the source a query listens to. + * + * Set to `default` to listen to both cache and server changes. Set to `cache` + * to listen to changes in cache only. + */ +export declare type ListenSource = 'default' | 'cache'; + +declare class LLRBEmptyNode { + get key(): never; + get value(): never; + get color(): never; + get left(): never; + get right(): never; + size: number; + copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode | LLRBEmptyNode | null, right: LLRBNode | LLRBEmptyNode | null): LLRBEmptyNode; + insert(key: K, value: V, comparator: Comparator): LLRBNode; + remove(key: K, comparator: Comparator): LLRBEmptyNode; + isEmpty(): boolean; + inorderTraversal(action: (k: K, v: V) => boolean): boolean; + reverseTraversal(action: (k: K, v: V) => boolean): boolean; + minKey(): K | null; + maxKey(): K | null; + isRed(): boolean; + checkMaxDepth(): boolean; + protected check(): 0; +} + +declare class LLRBNode { + key: K; + value: V; + readonly color: boolean; + readonly left: LLRBNode | LLRBEmptyNode; + readonly right: LLRBNode | LLRBEmptyNode; + readonly size: number; + static EMPTY: LLRBEmptyNode; + static RED: boolean; + static BLACK: boolean; + constructor(key: K, value: V, color?: boolean, left?: LLRBNode | LLRBEmptyNode, right?: LLRBNode | LLRBEmptyNode); + copy(key: K | null, value: V | null, color: boolean | null, left: LLRBNode | LLRBEmptyNode | null, right: LLRBNode | LLRBEmptyNode | null): LLRBNode; + isEmpty(): boolean; + inorderTraversal(action: (k: K, v: V) => T): T; + reverseTraversal(action: (k: K, v: V) => T): T; + private min; + minKey(): K | null; + maxKey(): K | null; + insert(key: K, value: V, comparator: Comparator): LLRBNode; + private removeMin; + remove(key: K, comparator: Comparator): LLRBNode | LLRBEmptyNode; + isRed(): boolean; + private fixUp; + private moveRedLeft; + private moveRedRight; + private rotateLeft; + private rotateRight; + private colorFlip; + checkMaxDepth(): boolean; + protected check(): number; +} + +/** + * Loads a Firestore bundle into the local cache. + * + * @param firestore - The {@link Firestore} instance to load bundles for. + * @param bundleData - An object representing the bundle to be loaded. Valid + * objects are `ArrayBuffer`, `ReadableStream` or `string`. + * + * @returns A `LoadBundleTask` object, which notifies callers with progress + * updates, and completion or error events. It can be used as a + * `Promise`. + */ +export declare function loadBundle(firestore: Firestore, bundleData: ReadableStream | ArrayBuffer | string): LoadBundleTask; + +/** + * Represents the task of loading a Firestore bundle. It provides progress of bundle + * loading, as well as task completion and error events. + * + * The API is compatible with `Promise`. + */ +export declare class LoadBundleTask implements PromiseLike { + private _progressObserver; + private _taskCompletionResolver; + private _lastProgress; + /** + * Registers functions to listen to bundle loading progress events. + * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur + * each time a Firestore document is loaded from the bundle. + * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the + * error, and there should be no more updates after this. + * @param complete - Called when the loading task is complete. + */ + onProgress(next?: (progress: LoadBundleTaskProgress) => unknown, error?: (err: Error) => unknown, complete?: () => void): void; + /** + * Implements the `Promise.catch` interface. + * + * @param onRejected - Called when an error occurs during bundle loading. + */ + catch(onRejected: (a: Error) => R | PromiseLike): Promise; + /** + * Implements the `Promise.then` interface. + * + * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update. + * The update will always have its `taskState` set to `"Success"`. + * @param onRejected - Called when an error occurs during bundle loading. + */ + then(onFulfilled?: (a: LoadBundleTaskProgress) => T | PromiseLike, onRejected?: (a: Error) => R | PromiseLike): Promise; + /** + * Notifies all observers that bundle loading has completed, with a provided + * `LoadBundleTaskProgress` object. + * + * @private + */ + _completeWith(progress: LoadBundleTaskProgress): void; + /** + * Notifies all observers that bundle loading has failed, with a provided + * `Error` as the reason. + * + * @private + */ + _failWith(error: FirestoreError): void; + /** + * Notifies a progress update of loading a bundle. + * @param progress - The new progress. + * + * @private + */ + _updateProgress(progress: LoadBundleTaskProgress): void; +} + +/** + * Represents a progress update or a final state from loading bundles. + */ +export declare interface LoadBundleTaskProgress { + /** How many documents have been loaded. */ + documentsLoaded: number; + /** How many documents are in the bundle being loaded. */ + totalDocuments: number; + /** How many bytes have been loaded. */ + bytesLoaded: number; + /** How many bytes are in the bundle being loaded. */ + totalBytes: number; + /** Current task state. */ + taskState: TaskState; +} + +/** + * A readonly view of the local state of all documents we're tracking (i.e. we + * have a cached version in remoteDocumentCache or local mutations for the + * document). The view is computed by applying the mutations in the + * MutationQueue to the RemoteDocumentCache. + */ +declare class LocalDocumentsView { + readonly remoteDocumentCache: RemoteDocumentCache; + readonly mutationQueue: MutationQueue; + readonly documentOverlayCache: DocumentOverlayCache; + readonly indexManager: IndexManager; + constructor(remoteDocumentCache: RemoteDocumentCache, mutationQueue: MutationQueue, documentOverlayCache: DocumentOverlayCache, indexManager: IndexManager); + /** + * Get the local view of the document identified by `key`. + * + * @returns Local view of the document or null if we don't have any cached + * state for it. + */ + getDocument(transaction: PersistenceTransaction, key: _DocumentKey): PersistencePromise; + /** + * Gets the local view of the documents identified by `keys`. + * + * If we don't have cached state for a document in `keys`, a NoDocument will + * be stored for that key in the resulting set. + */ + getDocuments(transaction: PersistenceTransaction, keys: DocumentKeySet): PersistencePromise; + /** + * Similar to `getDocuments`, but creates the local view from the given + * `baseDocs` without retrieving documents from the local store. + * + * @param transaction - The transaction this operation is scoped to. + * @param docs - The documents to apply local mutations to get the local views. + * @param existenceStateChanged - The set of document keys whose existence state + * is changed. This is useful to determine if some documents overlay needs + * to be recalculated. + */ + getLocalViewOfDocuments(transaction: PersistenceTransaction, docs: MutableDocumentMap, existenceStateChanged?: DocumentKeySet): PersistencePromise; + /** + * Gets the overlayed documents for the given document map, which will include + * the local view of those documents and a `FieldMask` indicating which fields + * are mutated locally, `null` if overlay is a Set or Delete mutation. + */ + getOverlayedDocuments(transaction: PersistenceTransaction, docs: MutableDocumentMap): PersistencePromise; + /** + * Fetches the overlays for {@code docs} and adds them to provided overlay map + * if the map does not already contain an entry for the given document key. + */ + private populateOverlays; + /** + * Computes the local view for the given documents. + * + * @param docs - The documents to compute views for. It also has the base + * version of the documents. + * @param overlays - The overlays that need to be applied to the given base + * version of the documents. + * @param existenceStateChanged - A set of documents whose existence states + * might have changed. This is used to determine if we need to re-calculate + * overlays from mutation queues. + * @return A map represents the local documents view. + */ + computeViews(transaction: PersistenceTransaction, docs: MutableDocumentMap, overlays: OverlayMap, existenceStateChanged: DocumentKeySet): PersistencePromise; + private recalculateAndSaveOverlays; + /** + * Recalculates overlays by reading the documents from remote document cache + * first, and saves them after they are calculated. + */ + recalculateAndSaveOverlaysForDocumentKeys(transaction: PersistenceTransaction, documentKeys: DocumentKeySet): PersistencePromise>; + /** + * Performs a query against the local view of all documents. + * + * @param transaction - The persistence transaction. + * @param query - The query to match documents against. + * @param offset - Read time and key to start scanning by (exclusive). + * @param context - A optional tracker to keep a record of important details + * during database local query execution. + */ + getDocumentsMatchingQuery(transaction: PersistenceTransaction, query: Query_2, offset: IndexOffset, context?: QueryContext): PersistencePromise; + /** + * Given a collection group, returns the next documents that follow the provided offset, along + * with an updated batch ID. + * + *

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 0xd6db,\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\n/**\n * The smallest value representable by a 64-bit signed integer (long).\n */\nconst MIN_LONG_VALUE = '-9223372036854775808';\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 // Document keys are ordered first by numeric value (\"__id__\"),\n // then lexicographically by string value. Start the iterator at the minimum\n // possible Document key value.\n const prefix = new DocumentKey(\n collectionPath.child('__id' + MIN_LONG_VALUE + '__')\n );\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(0x251c, '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(\n 0xee44,\n 'orphanedDocuments is only valid during a transaction.'\n );\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isSafariOrWebkit } from '@firebase/util';\n\nimport { User } from '../auth/user';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { DocumentKeySet, documentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport {\n decodeResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { IndexedDbDocumentOverlayCache } from './indexeddb_document_overlay_cache';\nimport {\n dbDocumentSize,\n removeMutationBatch\n} from './indexeddb_mutation_batch_impl';\nimport { IndexedDbMutationQueue } from './indexeddb_mutation_queue';\nimport { newIndexedDbRemoteDocumentCache } from './indexeddb_remote_document_cache';\nimport {\n DbCollectionParent,\n DbDocumentMutation,\n DbMutationBatch,\n DbMutationQueue,\n DbRemoteDocument,\n DbRemoteDocumentGlobal,\n DbTarget,\n DbTargetDocument,\n DbTargetGlobal,\n SCHEMA_VERSION\n} from './indexeddb_schema';\nimport {\n DbRemoteDocument as DbRemoteDocumentLegacy,\n DbRemoteDocumentStore as DbRemoteDocumentStoreLegacy,\n DbRemoteDocumentKey as DbRemoteDocumentKeyLegacy\n} from './indexeddb_schema_legacy';\nimport {\n DbBundleKeyPath,\n DbBundleStore,\n DbClientMetadataKeyPath,\n DbClientMetadataStore,\n DbCollectionParentKey,\n DbCollectionParentKeyPath,\n DbCollectionParentStore,\n DbDocumentMutationKey,\n DbDocumentMutationStore,\n DbDocumentOverlayCollectionGroupOverlayIndex,\n DbDocumentOverlayCollectionGroupOverlayIndexPath,\n DbDocumentOverlayCollectionPathOverlayIndex,\n DbDocumentOverlayCollectionPathOverlayIndexPath,\n DbDocumentOverlayKeyPath,\n DbDocumentOverlayStore,\n DbGlobalsKeyPath,\n DbGlobalsStore,\n DbIndexConfigurationCollectionGroupIndex,\n DbIndexConfigurationCollectionGroupIndexPath,\n DbIndexConfigurationKeyPath,\n DbIndexConfigurationStore,\n DbIndexEntryDocumentKeyIndex,\n DbIndexEntryDocumentKeyIndexPath,\n DbIndexEntryKeyPath,\n DbIndexEntryStore,\n DbIndexStateKeyPath,\n DbIndexStateSequenceNumberIndex,\n DbIndexStateSequenceNumberIndexPath,\n DbIndexStateStore,\n DbMutationBatchKey,\n DbMutationBatchKeyPath,\n DbMutationBatchStore,\n DbMutationBatchUserMutationsIndex,\n DbMutationBatchUserMutationsKeyPath,\n DbMutationQueueKey,\n DbMutationQueueKeyPath,\n DbMutationQueueStore,\n DbNamedQueryKeyPath,\n DbNamedQueryStore,\n DbPrimaryClientStore,\n DbRemoteDocumentCollectionGroupIndex,\n DbRemoteDocumentCollectionGroupIndexPath,\n DbRemoteDocumentDocumentKeyIndex,\n DbRemoteDocumentDocumentKeyIndexPath,\n DbRemoteDocumentGlobalKey,\n DbRemoteDocumentGlobalStore,\n DbRemoteDocumentKey,\n DbRemoteDocumentKeyPath,\n DbRemoteDocumentStore,\n DbTargetDocumentDocumentTargetsIndex,\n DbTargetDocumentDocumentTargetsKeyPath,\n DbTargetDocumentKey,\n DbTargetDocumentKeyPath,\n DbTargetDocumentStore,\n DbTargetGlobalKey,\n DbTargetGlobalStore,\n DbTargetKey,\n DbTargetKeyPath,\n DbTargetQueryTargetsIndexName,\n DbTargetQueryTargetsKeyPath,\n DbTargetStore\n} from './indexeddb_sentinels';\nimport { IndexedDbTransaction } from './indexeddb_transaction';\nimport { LocalDocumentsView } from './local_documents_view';\nimport {\n fromDbMutationBatch,\n fromDbTarget,\n LocalSerializer,\n toDbTarget\n} from './local_serializer';\nimport { MemoryCollectionParentIndex } from './memory_index_manager';\nimport { MemoryEagerDelegate, MemoryPersistence } from './memory_persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { SimpleDbSchemaConverter, SimpleDbTransaction } from './simple_db';\n\n/** Performs database creation and schema upgrades. */\nexport class SchemaConverter implements SimpleDbSchemaConverter {\n constructor(private readonly serializer: LocalSerializer) {}\n\n /**\n * Performs database creation and schema upgrades.\n *\n * Note that in production, this method is only ever used to upgrade the schema\n * to SCHEMA_VERSION. Different values of toVersion are only used for testing\n * and local feature development.\n */\n createOrUpgrade(\n db: IDBDatabase,\n txn: IDBTransaction,\n fromVersion: number,\n toVersion: number\n ): PersistencePromise {\n debugAssert(\n fromVersion < toVersion &&\n fromVersion >= 0 &&\n toVersion <= SCHEMA_VERSION,\n `Unexpected schema upgrade from v${fromVersion} to v${toVersion}.`\n );\n\n const simpleDbTransaction = new SimpleDbTransaction('createOrUpgrade', txn);\n\n if (fromVersion < 1 && toVersion >= 1) {\n createPrimaryClientStore(db);\n createMutationQueue(db);\n createQueryCache(db);\n createLegacyRemoteDocumentCache(db);\n }\n\n // Migration 2 to populate the targetGlobal object no longer needed since\n // migration 3 unconditionally clears it.\n\n let p = PersistencePromise.resolve();\n if (fromVersion < 3 && toVersion >= 3) {\n // Brand new clients don't need to drop and recreate--only clients that\n // potentially have corrupt data.\n if (fromVersion !== 0) {\n dropQueryCache(db);\n createQueryCache(db);\n }\n p = p.next(() => writeEmptyTargetGlobalEntry(simpleDbTransaction));\n }\n\n if (fromVersion < 4 && toVersion >= 4) {\n if (fromVersion !== 0) {\n // Schema version 3 uses auto-generated keys to generate globally unique\n // mutation batch IDs (this was previously ensured internally by the\n // client). To migrate to the new schema, we have to read all mutations\n // and write them back out. We preserve the existing batch IDs to guarantee\n // consistency with other object stores. Any further mutation batch IDs will\n // be auto-generated.\n p = p.next(() =>\n upgradeMutationBatchSchemaAndMigrateData(db, simpleDbTransaction)\n );\n }\n\n p = p.next(() => {\n createClientMetadataStore(db);\n });\n }\n\n if (fromVersion < 5 && toVersion >= 5) {\n p = p.next(() => this.removeAcknowledgedMutations(simpleDbTransaction));\n }\n\n if (fromVersion < 6 && toVersion >= 6) {\n p = p.next(() => {\n createDocumentGlobalStore(db);\n return this.addDocumentGlobal(simpleDbTransaction);\n });\n }\n\n if (fromVersion < 7 && toVersion >= 7) {\n p = p.next(() => this.ensureSequenceNumbers(simpleDbTransaction));\n }\n\n if (fromVersion < 8 && toVersion >= 8) {\n p = p.next(() =>\n this.createCollectionParentIndex(db, simpleDbTransaction)\n );\n }\n\n if (fromVersion < 9 && toVersion >= 9) {\n p = p.next(() => {\n // Multi-Tab used to manage its own changelog, but this has been moved\n // to the DbRemoteDocument object store itself. Since the previous change\n // log only contained transient data, we can drop its object store.\n dropRemoteDocumentChangesStore(db);\n\n // Note: Schema version 9 used to create a read time index for the\n // RemoteDocumentCache. This is now done with schema version 13.\n });\n }\n\n if (fromVersion < 10 && toVersion >= 10) {\n p = p.next(() => this.rewriteCanonicalIds(simpleDbTransaction));\n }\n\n if (fromVersion < 11 && toVersion >= 11) {\n p = p.next(() => {\n createBundlesStore(db);\n createNamedQueriesStore(db);\n });\n }\n\n if (fromVersion < 12 && toVersion >= 12) {\n p = p.next(() => {\n createDocumentOverlayStore(db);\n });\n }\n\n if (fromVersion < 13 && toVersion >= 13) {\n p = p\n .next(() => createRemoteDocumentCache(db))\n .next(() => this.rewriteRemoteDocumentCache(db, simpleDbTransaction))\n .next(() => db.deleteObjectStore(DbRemoteDocumentStoreLegacy));\n }\n\n if (fromVersion < 14 && toVersion >= 14) {\n p = p.next(() => this.runOverlayMigration(db, simpleDbTransaction));\n }\n\n if (fromVersion < 15 && toVersion >= 15) {\n p = p.next(() => createFieldIndex(db));\n }\n\n if (fromVersion < 16 && toVersion >= 16) {\n // Clear the object stores to remove possibly corrupted index entries\n p = p\n .next(() => {\n const indexStateStore = txn.objectStore(DbIndexStateStore);\n indexStateStore.clear();\n })\n .next(() => {\n const indexEntryStore = txn.objectStore(DbIndexEntryStore);\n indexEntryStore.clear();\n });\n }\n\n if (fromVersion < 17 && toVersion >= 17) {\n p = p.next(() => {\n createGlobalsStore(db);\n });\n }\n\n if (fromVersion < 18 && toVersion >= 18) {\n // Clear the IndexEntryStores on WebKit and Safari to remove possibly\n // corrupted index entries\n if (isSafariOrWebkit()) {\n p = p\n .next(() => {\n const indexStateStore = txn.objectStore(DbIndexStateStore);\n indexStateStore.clear();\n })\n .next(() => {\n const indexEntryStore = txn.objectStore(DbIndexEntryStore);\n indexEntryStore.clear();\n });\n }\n }\n\n return p;\n }\n\n private addDocumentGlobal(\n txn: SimpleDbTransaction\n ): PersistencePromise {\n let byteSize = 0;\n return txn\n .store(\n DbRemoteDocumentStoreLegacy\n )\n .iterate((_, doc) => {\n byteSize += dbDocumentSize(doc);\n })\n .next(() => {\n const metadata: DbRemoteDocumentGlobal = { byteSize };\n return txn\n .store(\n DbRemoteDocumentGlobalStore\n )\n .put(DbRemoteDocumentGlobalKey, metadata);\n });\n }\n\n private removeAcknowledgedMutations(\n txn: SimpleDbTransaction\n ): PersistencePromise {\n const queuesStore = txn.store(\n DbMutationQueueStore\n );\n const mutationsStore = txn.store(\n DbMutationBatchStore\n );\n\n return queuesStore.loadAll().next(queues => {\n return PersistencePromise.forEach(queues, (queue: DbMutationQueue) => {\n const range = IDBKeyRange.bound(\n [queue.userId, BATCHID_UNKNOWN],\n [queue.userId, queue.lastAcknowledgedBatchId]\n );\n\n return mutationsStore\n .loadAll(DbMutationBatchUserMutationsIndex, range)\n .next(dbBatches => {\n return PersistencePromise.forEach(\n dbBatches,\n (dbBatch: DbMutationBatch) => {\n hardAssert(\n dbBatch.userId === queue.userId,\n 0x48da,\n `Cannot process batch from unexpected user`,\n { batchId: dbBatch.batchId }\n );\n const batch = fromDbMutationBatch(this.serializer, dbBatch);\n\n return removeMutationBatch(txn, queue.userId, batch).next(\n () => {}\n );\n }\n );\n });\n });\n });\n }\n\n /**\n * Ensures that every document in the remote document cache has a corresponding sentinel row\n * with a sequence number. Missing rows are given the most recently used sequence number.\n */\n private ensureSequenceNumbers(\n txn: SimpleDbTransaction\n ): PersistencePromise {\n const documentTargetStore = txn.store<\n DbTargetDocumentKey,\n DbTargetDocument\n >(DbTargetDocumentStore);\n const documentsStore = txn.store<\n DbRemoteDocumentKeyLegacy,\n DbRemoteDocumentKeyLegacy\n >(DbRemoteDocumentStoreLegacy);\n const globalTargetStore = txn.store(\n DbTargetGlobalStore\n );\n\n return globalTargetStore.get(DbTargetGlobalKey).next(metadata => {\n debugAssert(\n !!metadata,\n 'Metadata should have been written during the version 3 migration'\n );\n const writeSentinelKey = (\n path: ResourcePath\n ): PersistencePromise => {\n return documentTargetStore.put({\n targetId: 0,\n path: encodeResourcePath(path),\n sequenceNumber: metadata!.highestListenSequenceNumber!\n });\n };\n\n const promises: Array> = [];\n return documentsStore\n .iterate((key, doc) => {\n const path = new ResourcePath(key);\n const docSentinelKey = sentinelKey(path);\n promises.push(\n documentTargetStore.get(docSentinelKey).next(maybeSentinel => {\n if (!maybeSentinel) {\n return writeSentinelKey(path);\n } else {\n return PersistencePromise.resolve();\n }\n })\n );\n })\n .next(() => PersistencePromise.waitFor(promises));\n });\n }\n\n private createCollectionParentIndex(\n db: IDBDatabase,\n txn: SimpleDbTransaction\n ): PersistencePromise {\n // Create the index.\n db.createObjectStore(DbCollectionParentStore, {\n keyPath: DbCollectionParentKeyPath\n });\n\n const collectionParentsStore = txn.store<\n DbCollectionParentKey,\n DbCollectionParent\n >(DbCollectionParentStore);\n\n // Helper to add an index entry iff we haven't already written it.\n const cache = new MemoryCollectionParentIndex();\n const addEntry = (\n collectionPath: ResourcePath\n ): PersistencePromise | undefined => {\n if (cache.add(collectionPath)) {\n const collectionId = collectionPath.lastSegment();\n const parentPath = collectionPath.popLast();\n return collectionParentsStore.put({\n collectionId,\n parent: encodeResourcePath(parentPath)\n });\n }\n };\n\n // Index existing remote documents.\n return txn\n .store(\n DbRemoteDocumentStoreLegacy\n )\n .iterate({ keysOnly: true }, (pathSegments, _) => {\n const path = new ResourcePath(pathSegments);\n return addEntry(path.popLast());\n })\n .next(() => {\n // Index existing mutations.\n return txn\n .store(\n DbDocumentMutationStore\n )\n .iterate({ keysOnly: true }, ([userID, encodedPath, batchId], _) => {\n const path = decodeResourcePath(encodedPath);\n return addEntry(path.popLast());\n });\n });\n }\n\n private rewriteCanonicalIds(\n txn: SimpleDbTransaction\n ): PersistencePromise {\n const targetStore = txn.store(DbTargetStore);\n return targetStore.iterate((key, originalDbTarget) => {\n const originalTargetData = fromDbTarget(originalDbTarget);\n const updatedDbTarget = toDbTarget(this.serializer, originalTargetData);\n return targetStore.put(updatedDbTarget);\n });\n }\n\n private rewriteRemoteDocumentCache(\n db: IDBDatabase,\n transaction: SimpleDbTransaction\n ): PersistencePromise {\n const legacyRemoteDocumentStore = transaction.store<\n DbRemoteDocumentKeyLegacy,\n DbRemoteDocumentLegacy\n >(DbRemoteDocumentStoreLegacy);\n\n const writes: Array> = [];\n return legacyRemoteDocumentStore\n .iterate((_, legacyDocument) => {\n const remoteDocumentStore = transaction.store<\n DbRemoteDocumentKey,\n DbRemoteDocument\n >(DbRemoteDocumentStore);\n\n const path = extractKey(legacyDocument).path.toArray();\n const dbRemoteDocument = {\n prefixPath: path.slice(0, path.length - 2),\n collectionGroup: path[path.length - 2],\n documentId: path[path.length - 1],\n readTime: legacyDocument.readTime || [0, 0],\n unknownDocument: legacyDocument.unknownDocument,\n noDocument: legacyDocument.noDocument,\n document: legacyDocument.document,\n hasCommittedMutations: !!legacyDocument.hasCommittedMutations\n };\n writes.push(remoteDocumentStore.put(dbRemoteDocument));\n })\n .next(() => PersistencePromise.waitFor(writes));\n }\n\n private runOverlayMigration(\n db: IDBDatabase,\n transaction: SimpleDbTransaction\n ): PersistencePromise {\n const mutationsStore = transaction.store<\n DbMutationBatchKey,\n DbMutationBatch\n >(DbMutationBatchStore);\n\n const remoteDocumentCache = newIndexedDbRemoteDocumentCache(\n this.serializer\n );\n const memoryPersistence = new MemoryPersistence(\n MemoryEagerDelegate.factory,\n this.serializer.remoteSerializer\n );\n\n return mutationsStore.loadAll().next(dbBatches => {\n const userToDocumentSet = new Map();\n dbBatches.forEach(dbBatch => {\n let documentSet =\n userToDocumentSet.get(dbBatch.userId) ?? documentKeySet();\n const batch = fromDbMutationBatch(this.serializer, dbBatch);\n batch.keys().forEach(key => (documentSet = documentSet.add(key)));\n userToDocumentSet.set(dbBatch.userId, documentSet);\n });\n return PersistencePromise.forEach(\n userToDocumentSet,\n (allDocumentKeysForUser, userId) => {\n const user = new User(userId);\n const documentOverlayCache = IndexedDbDocumentOverlayCache.forUser(\n this.serializer,\n user\n );\n // NOTE: The index manager and the reference delegate are\n // irrelevant for the purpose of recalculating and saving\n // overlays. We can therefore simply use the memory\n // implementation.\n const indexManager = memoryPersistence.getIndexManager(user);\n const mutationQueue = IndexedDbMutationQueue.forUser(\n user,\n this.serializer,\n indexManager,\n memoryPersistence.referenceDelegate\n );\n const localDocumentsView = new LocalDocumentsView(\n remoteDocumentCache,\n mutationQueue,\n documentOverlayCache,\n indexManager\n );\n return localDocumentsView\n .recalculateAndSaveOverlaysForDocumentKeys(\n new IndexedDbTransaction(transaction, ListenSequence.INVALID),\n allDocumentKeysForUser\n )\n .next();\n }\n );\n });\n }\n}\n\nfunction sentinelKey(path: ResourcePath): DbTargetDocumentKey {\n return [0, encodeResourcePath(path)];\n}\n\nfunction createPrimaryClientStore(db: IDBDatabase): void {\n db.createObjectStore(DbPrimaryClientStore);\n}\n\nfunction createMutationQueue(db: IDBDatabase): void {\n db.createObjectStore(DbMutationQueueStore, {\n keyPath: DbMutationQueueKeyPath\n });\n\n const mutationBatchesStore = db.createObjectStore(DbMutationBatchStore, {\n keyPath: DbMutationBatchKeyPath,\n autoIncrement: true\n });\n mutationBatchesStore.createIndex(\n DbMutationBatchUserMutationsIndex,\n DbMutationBatchUserMutationsKeyPath,\n { unique: true }\n );\n\n db.createObjectStore(DbDocumentMutationStore);\n}\n\n/**\n * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads\n * and rewrites all data.\n */\nfunction upgradeMutationBatchSchemaAndMigrateData(\n db: IDBDatabase,\n txn: SimpleDbTransaction\n): PersistencePromise {\n const v1MutationsStore = txn.store<[string, number], DbMutationBatch>(\n DbMutationBatchStore\n );\n return v1MutationsStore.loadAll().next(existingMutations => {\n db.deleteObjectStore(DbMutationBatchStore);\n\n const mutationsStore = db.createObjectStore(DbMutationBatchStore, {\n keyPath: DbMutationBatchKeyPath,\n autoIncrement: true\n });\n mutationsStore.createIndex(\n DbMutationBatchUserMutationsIndex,\n DbMutationBatchUserMutationsKeyPath,\n { unique: true }\n );\n\n const v3MutationsStore = txn.store(\n DbMutationBatchStore\n );\n const writeAll = existingMutations.map(mutation =>\n v3MutationsStore.put(mutation)\n );\n\n return PersistencePromise.waitFor(writeAll);\n });\n}\n\nfunction createLegacyRemoteDocumentCache(db: IDBDatabase): void {\n db.createObjectStore(DbRemoteDocumentStoreLegacy);\n}\n\nfunction createRemoteDocumentCache(db: IDBDatabase): void {\n const remoteDocumentStore = db.createObjectStore(DbRemoteDocumentStore, {\n keyPath: DbRemoteDocumentKeyPath\n });\n remoteDocumentStore.createIndex(\n DbRemoteDocumentDocumentKeyIndex,\n DbRemoteDocumentDocumentKeyIndexPath\n );\n remoteDocumentStore.createIndex(\n DbRemoteDocumentCollectionGroupIndex,\n DbRemoteDocumentCollectionGroupIndexPath\n );\n}\n\nfunction createDocumentGlobalStore(db: IDBDatabase): void {\n db.createObjectStore(DbRemoteDocumentGlobalStore);\n}\n\nfunction createQueryCache(db: IDBDatabase): void {\n const targetDocumentsStore = db.createObjectStore(DbTargetDocumentStore, {\n keyPath: DbTargetDocumentKeyPath\n });\n targetDocumentsStore.createIndex(\n DbTargetDocumentDocumentTargetsIndex,\n DbTargetDocumentDocumentTargetsKeyPath,\n { unique: true }\n );\n\n const targetStore = db.createObjectStore(DbTargetStore, {\n keyPath: DbTargetKeyPath\n });\n\n // NOTE: This is unique only because the TargetId is the suffix.\n targetStore.createIndex(\n DbTargetQueryTargetsIndexName,\n DbTargetQueryTargetsKeyPath,\n { unique: true }\n );\n db.createObjectStore(DbTargetGlobalStore);\n}\n\nfunction dropQueryCache(db: IDBDatabase): void {\n db.deleteObjectStore(DbTargetDocumentStore);\n db.deleteObjectStore(DbTargetStore);\n db.deleteObjectStore(DbTargetGlobalStore);\n}\n\nfunction dropRemoteDocumentChangesStore(db: IDBDatabase): void {\n if (db.objectStoreNames.contains('remoteDocumentChanges')) {\n db.deleteObjectStore('remoteDocumentChanges');\n }\n}\n\n/**\n * Creates the target global singleton row.\n *\n * @param txn - The version upgrade transaction for indexeddb\n */\nfunction writeEmptyTargetGlobalEntry(\n txn: SimpleDbTransaction\n): PersistencePromise {\n const globalStore = txn.store(\n DbTargetGlobalStore\n );\n const metadata: DbTargetGlobal = {\n highestTargetId: 0,\n highestListenSequenceNumber: 0,\n lastRemoteSnapshotVersion: SnapshotVersion.min().toTimestamp(),\n targetCount: 0\n };\n return globalStore.put(DbTargetGlobalKey, metadata);\n}\n\nfunction createClientMetadataStore(db: IDBDatabase): void {\n db.createObjectStore(DbClientMetadataStore, {\n keyPath: DbClientMetadataKeyPath\n });\n}\n\nfunction createBundlesStore(db: IDBDatabase): void {\n db.createObjectStore(DbBundleStore, {\n keyPath: DbBundleKeyPath\n });\n}\n\nfunction createNamedQueriesStore(db: IDBDatabase): void {\n db.createObjectStore(DbNamedQueryStore, {\n keyPath: DbNamedQueryKeyPath\n });\n}\n\nfunction createFieldIndex(db: IDBDatabase): void {\n const indexConfigurationStore = db.createObjectStore(\n DbIndexConfigurationStore,\n {\n keyPath: DbIndexConfigurationKeyPath,\n autoIncrement: true\n }\n );\n indexConfigurationStore.createIndex(\n DbIndexConfigurationCollectionGroupIndex,\n DbIndexConfigurationCollectionGroupIndexPath,\n { unique: false }\n );\n\n const indexStateStore = db.createObjectStore(DbIndexStateStore, {\n keyPath: DbIndexStateKeyPath\n });\n indexStateStore.createIndex(\n DbIndexStateSequenceNumberIndex,\n DbIndexStateSequenceNumberIndexPath,\n { unique: false }\n );\n\n const indexEntryStore = db.createObjectStore(DbIndexEntryStore, {\n keyPath: DbIndexEntryKeyPath\n });\n indexEntryStore.createIndex(\n DbIndexEntryDocumentKeyIndex,\n DbIndexEntryDocumentKeyIndexPath,\n { unique: false }\n );\n}\n\nfunction createDocumentOverlayStore(db: IDBDatabase): void {\n const documentOverlayStore = db.createObjectStore(DbDocumentOverlayStore, {\n keyPath: DbDocumentOverlayKeyPath\n });\n documentOverlayStore.createIndex(\n DbDocumentOverlayCollectionPathOverlayIndex,\n DbDocumentOverlayCollectionPathOverlayIndexPath,\n { unique: false }\n );\n documentOverlayStore.createIndex(\n DbDocumentOverlayCollectionGroupOverlayIndex,\n DbDocumentOverlayCollectionGroupOverlayIndexPath,\n { unique: false }\n );\n}\n\nfunction createGlobalsStore(db: IDBDatabase): void {\n db.createObjectStore(DbGlobalsStore, {\n keyPath: DbGlobalsKeyPath\n });\n}\n\nfunction extractKey(remoteDoc: DbRemoteDocumentLegacy): DocumentKey {\n if (remoteDoc.document) {\n return new DocumentKey(\n ResourcePath.fromString(remoteDoc.document.name!).popFirst(5)\n );\n } else if (remoteDoc.noDocument) {\n return DocumentKey.fromSegments(remoteDoc.noDocument.path);\n } else if (remoteDoc.unknownDocument) {\n return DocumentKey.fromSegments(remoteDoc.unknownDocument.path);\n } else {\n return fail(0x8faf, 'Unexpected DbRemoteDocument');\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isSafari } from '@firebase/util';\n\nimport { User } from '../auth/user';\nimport { DatabaseId } from '../core/database_info';\nimport { ListenSequence, SequenceNumberSyncer } from '../core/listen_sequence';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logError } from '../util/log';\nimport { DocumentLike, WindowLike } from '../util/types';\n\nimport { BundleCache } from './bundle_cache';\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { GlobalsCache } from './globals_cache';\nimport { IndexManager } from './index_manager';\nimport { IndexedDbBundleCache } from './indexeddb_bundle_cache';\nimport { IndexedDbDocumentOverlayCache } from './indexeddb_document_overlay_cache';\nimport { IndexedDbGlobalsCache } from './indexeddb_globals_cache';\nimport { IndexedDbIndexManager } from './indexeddb_index_manager';\nimport { IndexedDbLruDelegateImpl } from './indexeddb_lru_delegate_impl';\nimport { IndexedDbMutationQueue } from './indexeddb_mutation_queue';\nimport {\n IndexedDbRemoteDocumentCache,\n newIndexedDbRemoteDocumentCache\n} from './indexeddb_remote_document_cache';\nimport {\n DbClientMetadata,\n DbPrimaryClient,\n SCHEMA_VERSION\n} from './indexeddb_schema';\nimport { SchemaConverter } from './indexeddb_schema_converter';\nimport {\n DbClientMetadataKey,\n DbClientMetadataStore,\n DbPrimaryClientKey,\n DbPrimaryClientStore,\n getObjectStores\n} from './indexeddb_sentinels';\nimport { IndexedDbTargetCache } from './indexeddb_target_cache';\nimport { getStore, IndexedDbTransaction } from './indexeddb_transaction';\nimport { LocalSerializer } from './local_serializer';\nimport { LruParams } from './lru_garbage_collector';\nimport { Persistence, PrimaryStateListener } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport {\n PersistenceTransaction,\n PersistenceTransactionMode,\n PRIMARY_LEASE_LOST_ERROR_MSG\n} from './persistence_transaction';\nimport { ClientId } from './shared_client_state';\nimport {\n isIndexedDbTransactionError,\n SimpleDb,\n SimpleDbStore\n} from './simple_db';\n\nconst LOG_TAG = 'IndexedDbPersistence';\n\n/**\n * Oldest acceptable age in milliseconds for client metadata before the client\n * is considered inactive and its associated data is garbage collected.\n */\nconst MAX_CLIENT_AGE_MS = 30 * 60 * 1000; // 30 minutes\n\n/**\n * Oldest acceptable metadata age for clients that may participate in the\n * primary lease election. Clients that have not updated their client metadata\n * within 5 seconds are not eligible to receive a primary lease.\n */\nconst MAX_PRIMARY_ELIGIBLE_AGE_MS = 5000;\n\n/**\n * The interval at which clients will update their metadata, including\n * refreshing their primary lease if held or potentially trying to acquire it if\n * not held.\n *\n * Primary clients may opportunistically refresh their metadata earlier\n * if they're already performing an IndexedDB operation.\n */\nconst CLIENT_METADATA_REFRESH_INTERVAL_MS = 4000;\n/** User-facing error when the primary lease is required but not available. */\nconst PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG =\n 'Failed to obtain exclusive access to the persistence layer. To allow ' +\n 'shared access, multi-tab synchronization has to be enabled in all tabs. ' +\n 'If you are using `experimentalForceOwningTab:true`, make sure that only ' +\n 'one tab has persistence enabled at any given time.';\nconst UNSUPPORTED_PLATFORM_ERROR_MSG =\n 'This platform is either missing IndexedDB or is known to have ' +\n 'an incomplete implementation. Offline persistence has been disabled.';\n\n// The format of the LocalStorage key that stores zombied client is:\n// firestore_zombie__\nconst ZOMBIED_CLIENTS_KEY_PREFIX = 'firestore_zombie';\n\n/**\n * The name of the main (and currently only) IndexedDB database. This name is\n * appended to the prefix provided to the IndexedDbPersistence constructor.\n */\nexport const MAIN_DATABASE = 'main';\n\n/**\n * An IndexedDB-backed instance of Persistence. Data is stored persistently\n * across sessions.\n *\n * On Web only, the Firestore SDKs support shared access to its persistence\n * layer. This allows multiple browser tabs to read and write to IndexedDb and\n * to synchronize state even without network connectivity. Shared access is\n * currently optional and not enabled unless all clients invoke\n * `enablePersistence()` with `{synchronizeTabs:true}`.\n *\n * In multi-tab mode, if multiple clients are active at the same time, the SDK\n * will designate one client as the \"primary client\". An effort is made to pick\n * a visible, network-connected and active client, and this client is\n * responsible for letting other clients know about its presence. The primary\n * client writes a unique client-generated identifier (the client ID) to\n * IndexedDb’s \"owner\" store every 4 seconds. If the primary client fails to\n * update this entry, another client can acquire the lease and take over as\n * primary.\n *\n * Some persistence operations in the SDK are designated as primary-client only\n * operations. This includes the acknowledgment of mutations and all updates of\n * remote documents. The effects of these operations are written to persistence\n * and then broadcast to other tabs via LocalStorage (see\n * `WebStorageSharedClientState`), which then refresh their state from\n * persistence.\n *\n * Similarly, the primary client listens to notifications sent by secondary\n * clients to discover persistence changes written by secondary clients, such as\n * the addition of new mutations and query targets.\n *\n * If multi-tab is not enabled and another tab already obtained the primary\n * lease, IndexedDbPersistence enters a failed state and all subsequent\n * operations will automatically fail.\n *\n * Additionally, there is an optimization so that when a tab is closed, the\n * primary lease is released immediately (this is especially important to make\n * sure that a refreshed tab is able to immediately re-acquire the primary\n * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload\n * since it is an asynchronous API. So in addition to attempting to give up the\n * lease, the leaseholder writes its client ID to a \"zombiedClient\" entry in\n * LocalStorage which acts as an indicator that another tab should go ahead and\n * take the primary lease immediately regardless of the current lease timestamp.\n *\n * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no\n * longer optional.\n */\nexport class IndexedDbPersistence implements Persistence {\n private simpleDb: SimpleDb;\n\n private listenSequence: ListenSequence | null = null;\n\n private _started = false;\n private isPrimary = false;\n private networkEnabled = true;\n private dbName: string;\n\n /** Our window.unload handler, if registered. */\n private windowUnloadHandler: (() => void) | null = null;\n private inForeground = false;\n\n private serializer: LocalSerializer;\n\n /** Our 'visibilitychange' listener if registered. */\n private documentVisibilityHandler: ((e?: Event) => void) | null = null;\n\n /** The client metadata refresh task. */\n private clientMetadataRefresher: DelayedOperation | null = null;\n\n /** The last time we garbage collected the client metadata object store. */\n private lastGarbageCollectionTime = Number.NEGATIVE_INFINITY;\n\n /** A listener to notify on primary state changes. */\n private primaryStateListener: PrimaryStateListener = _ => Promise.resolve();\n\n private readonly globalsCache: IndexedDbGlobalsCache;\n private readonly targetCache: IndexedDbTargetCache;\n private readonly remoteDocumentCache: IndexedDbRemoteDocumentCache;\n private readonly bundleCache: IndexedDbBundleCache;\n private readonly webStorage: Storage | null;\n readonly referenceDelegate: IndexedDbLruDelegateImpl;\n\n constructor(\n /**\n * Whether to synchronize the in-memory state of multiple tabs and share\n * access to local persistence.\n */\n private readonly allowTabSynchronization: boolean,\n\n private readonly persistenceKey: string,\n private readonly clientId: ClientId,\n lruParams: LruParams,\n private readonly queue: AsyncQueue,\n private readonly window: WindowLike | null,\n private readonly document: DocumentLike | null,\n serializer: JsonProtoSerializer,\n private readonly sequenceNumberSyncer: SequenceNumberSyncer,\n\n /**\n * If set to true, forcefully obtains database access. Existing tabs will\n * no longer be able to access IndexedDB.\n */\n private readonly forceOwningTab: boolean,\n private readonly schemaVersion = SCHEMA_VERSION\n ) {\n if (!IndexedDbPersistence.isAvailable()) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n UNSUPPORTED_PLATFORM_ERROR_MSG\n );\n }\n\n this.referenceDelegate = new IndexedDbLruDelegateImpl(this, lruParams);\n this.dbName = persistenceKey + MAIN_DATABASE;\n this.serializer = new LocalSerializer(serializer);\n this.simpleDb = new SimpleDb(\n this.dbName,\n this.schemaVersion,\n new SchemaConverter(this.serializer)\n );\n this.globalsCache = new IndexedDbGlobalsCache();\n this.targetCache = new IndexedDbTargetCache(\n this.referenceDelegate,\n this.serializer\n );\n this.remoteDocumentCache = newIndexedDbRemoteDocumentCache(this.serializer);\n this.bundleCache = new IndexedDbBundleCache();\n if (this.window && this.window.localStorage) {\n this.webStorage = this.window.localStorage;\n } else {\n this.webStorage = null;\n if (forceOwningTab === false) {\n logError(\n LOG_TAG,\n 'LocalStorage is unavailable. As a result, persistence may not work ' +\n 'reliably. In particular enablePersistence() could fail immediately ' +\n 'after refreshing the page.'\n );\n }\n }\n }\n\n /**\n * Attempt to start IndexedDb persistence.\n *\n * @returns Whether persistence was enabled.\n */\n start(): Promise {\n debugAssert(!this.started, 'IndexedDbPersistence double-started!');\n debugAssert(this.window !== null, \"Expected 'window' to be defined\");\n\n // NOTE: This is expected to fail sometimes (in the case of another tab\n // already having the persistence lock), so it's the first thing we should\n // do.\n return this.updateClientMetadataAndTryBecomePrimary()\n .then(() => {\n if (!this.isPrimary && !this.allowTabSynchronization) {\n // Fail `start()` if `synchronizeTabs` is disabled and we cannot\n // obtain the primary lease.\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG\n );\n }\n this.attachVisibilityHandler();\n this.attachWindowUnloadHook();\n\n this.scheduleClientMetadataAndPrimaryLeaseRefreshes();\n\n return this.runTransaction(\n 'getHighestListenSequenceNumber',\n 'readonly',\n txn => this.targetCache.getHighestSequenceNumber(txn)\n );\n })\n .then(highestListenSequenceNumber => {\n this.listenSequence = new ListenSequence(\n highestListenSequenceNumber,\n this.sequenceNumberSyncer\n );\n })\n .then(() => {\n this._started = true;\n })\n .catch(reason => {\n this.simpleDb && this.simpleDb.close();\n return Promise.reject(reason);\n });\n }\n\n /**\n * Registers a listener that gets called when the primary state of the\n * instance changes. Upon registering, this listener is invoked immediately\n * with the current primary state.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n setPrimaryStateListener(\n primaryStateListener: PrimaryStateListener\n ): Promise {\n this.primaryStateListener = async primaryState => {\n if (this.started) {\n return primaryStateListener(primaryState);\n }\n };\n return primaryStateListener(this.isPrimary);\n }\n\n /**\n * Registers a listener that gets called when the database receives a\n * version change event indicating that it has deleted.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n setDatabaseDeletedListener(\n databaseDeletedListener: () => Promise\n ): void {\n this.simpleDb.setVersionChangeListener(async event => {\n // Check if an attempt is made to delete IndexedDB.\n if (event.newVersion === null) {\n await databaseDeletedListener();\n }\n });\n }\n\n /**\n * Adjusts the current network state in the client's metadata, potentially\n * affecting the primary lease.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n setNetworkEnabled(networkEnabled: boolean): void {\n if (this.networkEnabled !== networkEnabled) {\n this.networkEnabled = networkEnabled;\n // Schedule a primary lease refresh for immediate execution. The eventual\n // lease update will be propagated via `primaryStateListener`.\n this.queue.enqueueAndForget(async () => {\n if (this.started) {\n await this.updateClientMetadataAndTryBecomePrimary();\n }\n });\n }\n }\n\n /**\n * Updates the client metadata in IndexedDb and attempts to either obtain or\n * extend the primary lease for the local client. Asynchronously notifies the\n * primary state listener if the client either newly obtained or released its\n * primary lease.\n */\n private updateClientMetadataAndTryBecomePrimary(): Promise {\n return this.runTransaction(\n 'updateClientMetadataAndTryBecomePrimary',\n 'readwrite',\n txn => {\n const metadataStore = clientMetadataStore(txn);\n return metadataStore\n .put({\n clientId: this.clientId,\n updateTimeMs: Date.now(),\n networkEnabled: this.networkEnabled,\n inForeground: this.inForeground\n })\n .next(() => {\n if (this.isPrimary) {\n return this.verifyPrimaryLease(txn).next(success => {\n if (!success) {\n this.isPrimary = false;\n this.queue.enqueueRetryable(() =>\n this.primaryStateListener(false)\n );\n }\n });\n }\n })\n .next(() => this.canActAsPrimary(txn))\n .next(canActAsPrimary => {\n if (this.isPrimary && !canActAsPrimary) {\n return this.releasePrimaryLeaseIfHeld(txn).next(() => false);\n } else if (canActAsPrimary) {\n return this.acquireOrExtendPrimaryLease(txn).next(() => true);\n } else {\n return /* canActAsPrimary= */ false;\n }\n });\n }\n )\n .catch(e => {\n if (isIndexedDbTransactionError(e)) {\n logDebug(LOG_TAG, 'Failed to extend owner lease: ', e);\n // Proceed with the existing state. Any subsequent access to\n // IndexedDB will verify the lease.\n return this.isPrimary;\n }\n\n if (!this.allowTabSynchronization) {\n throw e;\n }\n\n logDebug(\n LOG_TAG,\n 'Releasing owner lease after error during lease refresh',\n e\n );\n return /* isPrimary= */ false;\n })\n .then(isPrimary => {\n if (this.isPrimary !== isPrimary) {\n this.queue.enqueueRetryable(() =>\n this.primaryStateListener(isPrimary)\n );\n }\n this.isPrimary = isPrimary;\n });\n }\n\n private verifyPrimaryLease(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const store = primaryClientStore(txn);\n return store.get(DbPrimaryClientKey).next(primaryClient => {\n return PersistencePromise.resolve(this.isLocalClient(primaryClient));\n });\n }\n\n private removeClientMetadata(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const metadataStore = clientMetadataStore(txn);\n return metadataStore.delete(this.clientId);\n }\n\n /**\n * If the garbage collection threshold has passed, prunes the\n * RemoteDocumentChanges and the ClientMetadata store based on the last update\n * time of all clients.\n */\n private async maybeGarbageCollectMultiClientState(): Promise {\n if (\n this.isPrimary &&\n !this.isWithinAge(this.lastGarbageCollectionTime, MAX_CLIENT_AGE_MS)\n ) {\n this.lastGarbageCollectionTime = Date.now();\n\n const inactiveClients = await this.runTransaction(\n 'maybeGarbageCollectMultiClientState',\n 'readwrite-primary',\n txn => {\n const metadataStore = getStore(\n txn,\n DbClientMetadataStore\n );\n\n return metadataStore.loadAll().next(existingClients => {\n const active = this.filterActiveClients(\n existingClients,\n MAX_CLIENT_AGE_MS\n );\n const inactive = existingClients.filter(\n client => active.indexOf(client) === -1\n );\n\n // Delete metadata for clients that are no longer considered active.\n return PersistencePromise.forEach(\n inactive,\n (inactiveClient: DbClientMetadata) =>\n metadataStore.delete(inactiveClient.clientId)\n ).next(() => inactive);\n });\n }\n ).catch(() => {\n // Ignore primary lease violations or any other type of error. The next\n // primary will run `maybeGarbageCollectMultiClientState()` again.\n // We don't use `ignoreIfPrimaryLeaseLoss()` since we don't want to depend\n // on LocalStore.\n return [];\n });\n\n // Delete potential leftover entries that may continue to mark the\n // inactive clients as zombied in LocalStorage.\n // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for\n // the client atomically, but we can't. So we opt to delete the IndexedDb\n // entries first to avoid potentially reviving a zombied client.\n if (this.webStorage) {\n for (const inactiveClient of inactiveClients) {\n this.webStorage.removeItem(\n this.zombiedClientLocalStorageKey(inactiveClient.clientId)\n );\n }\n }\n }\n }\n\n /**\n * Schedules a recurring timer to update the client metadata and to either\n * extend or acquire the primary lease if the client is eligible.\n */\n private scheduleClientMetadataAndPrimaryLeaseRefreshes(): void {\n this.clientMetadataRefresher = this.queue.enqueueAfterDelay(\n TimerId.ClientMetadataRefresh,\n CLIENT_METADATA_REFRESH_INTERVAL_MS,\n () => {\n return this.updateClientMetadataAndTryBecomePrimary()\n .then(() => this.maybeGarbageCollectMultiClientState())\n .then(() => this.scheduleClientMetadataAndPrimaryLeaseRefreshes());\n }\n );\n }\n\n /** Checks whether `client` is the local client. */\n private isLocalClient(client: DbPrimaryClient | null): boolean {\n return client ? client.ownerId === this.clientId : false;\n }\n\n /**\n * Evaluate the state of all active clients and determine whether the local\n * client is or can act as the holder of the primary lease. Returns whether\n * the client is eligible for the lease, but does not actually acquire it.\n * May return 'false' even if there is no active leaseholder and another\n * (foreground) client should become leaseholder instead.\n */\n private canActAsPrimary(\n txn: PersistenceTransaction\n ): PersistencePromise {\n if (this.forceOwningTab) {\n return PersistencePromise.resolve(true);\n }\n const store = primaryClientStore(txn);\n return store\n .get(DbPrimaryClientKey)\n .next(currentPrimary => {\n const currentLeaseIsValid =\n currentPrimary !== null &&\n this.isWithinAge(\n currentPrimary.leaseTimestampMs,\n MAX_PRIMARY_ELIGIBLE_AGE_MS\n ) &&\n !this.isClientZombied(currentPrimary.ownerId);\n\n // A client is eligible for the primary lease if:\n // - its network is enabled and the client's tab is in the foreground.\n // - its network is enabled and no other client's tab is in the\n // foreground.\n // - every clients network is disabled and the client's tab is in the\n // foreground.\n // - every clients network is disabled and no other client's tab is in\n // the foreground.\n // - the `forceOwningTab` setting was passed in.\n if (currentLeaseIsValid) {\n if (this.isLocalClient(currentPrimary) && this.networkEnabled) {\n return true;\n }\n\n if (!this.isLocalClient(currentPrimary)) {\n if (!currentPrimary!.allowTabSynchronization) {\n // Fail the `canActAsPrimary` check if the current leaseholder has\n // not opted into multi-tab synchronization. If this happens at\n // client startup, we reject the Promise returned by\n // `enablePersistence()` and the user can continue to use Firestore\n // with in-memory persistence.\n // If this fails during a lease refresh, we will instead block the\n // AsyncQueue from executing further operations. Note that this is\n // acceptable since mixing & matching different `synchronizeTabs`\n // settings is not supported.\n //\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can\n // no longer be turned off.\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG\n );\n }\n\n return false;\n }\n }\n\n if (this.networkEnabled && this.inForeground) {\n return true;\n }\n\n return clientMetadataStore(txn)\n .loadAll()\n .next(existingClients => {\n // Process all existing clients and determine whether at least one of\n // them is better suited to obtain the primary lease.\n const preferredCandidate = this.filterActiveClients(\n existingClients,\n MAX_PRIMARY_ELIGIBLE_AGE_MS\n ).find(otherClient => {\n if (this.clientId !== otherClient.clientId) {\n const otherClientHasBetterNetworkState =\n !this.networkEnabled && otherClient.networkEnabled;\n const otherClientHasBetterVisibility =\n !this.inForeground && otherClient.inForeground;\n const otherClientHasSameNetworkState =\n this.networkEnabled === otherClient.networkEnabled;\n if (\n otherClientHasBetterNetworkState ||\n (otherClientHasBetterVisibility &&\n otherClientHasSameNetworkState)\n ) {\n return true;\n }\n }\n return false;\n });\n return preferredCandidate === undefined;\n });\n })\n .next(canActAsPrimary => {\n if (this.isPrimary !== canActAsPrimary) {\n logDebug(\n LOG_TAG,\n `Client ${\n canActAsPrimary ? 'is' : 'is not'\n } eligible for a primary lease.`\n );\n }\n return canActAsPrimary;\n });\n }\n\n async shutdown(): Promise {\n // The shutdown() operations are idempotent and can be called even when\n // start() aborted (e.g. because it couldn't acquire the persistence lease).\n this._started = false;\n\n this.markClientZombied();\n if (this.clientMetadataRefresher) {\n this.clientMetadataRefresher.cancel();\n this.clientMetadataRefresher = null;\n }\n this.detachVisibilityHandler();\n this.detachWindowUnloadHook();\n\n // Use `SimpleDb.runTransaction` directly to avoid failing if another tab\n // has obtained the primary lease.\n await this.simpleDb.runTransaction(\n 'shutdown',\n 'readwrite',\n [DbPrimaryClientStore, DbClientMetadataStore],\n simpleDbTxn => {\n const persistenceTransaction = new IndexedDbTransaction(\n simpleDbTxn,\n ListenSequence.INVALID\n );\n return this.releasePrimaryLeaseIfHeld(persistenceTransaction).next(() =>\n this.removeClientMetadata(persistenceTransaction)\n );\n }\n );\n this.simpleDb.close();\n\n // Remove the entry marking the client as zombied from LocalStorage since\n // we successfully deleted its metadata from IndexedDb.\n this.removeClientZombiedEntry();\n }\n\n /**\n * Returns clients that are not zombied and have an updateTime within the\n * provided threshold.\n */\n private filterActiveClients(\n clients: DbClientMetadata[],\n activityThresholdMs: number\n ): DbClientMetadata[] {\n return clients.filter(\n client =>\n this.isWithinAge(client.updateTimeMs, activityThresholdMs) &&\n !this.isClientZombied(client.clientId)\n );\n }\n\n /**\n * Returns the IDs of the clients that are currently active. If multi-tab\n * is not supported, returns an array that only contains the local client's\n * ID.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n getActiveClients(): Promise {\n return this.runTransaction('getActiveClients', 'readonly', txn => {\n return clientMetadataStore(txn)\n .loadAll()\n .next(clients =>\n this.filterActiveClients(clients, MAX_CLIENT_AGE_MS).map(\n clientMetadata => clientMetadata.clientId\n )\n );\n });\n }\n\n get started(): boolean {\n return this._started;\n }\n\n getGlobalsCache(): GlobalsCache {\n debugAssert(\n this.started,\n 'Cannot initialize GlobalsCache before persistence is started.'\n );\n return this.globalsCache;\n }\n\n getMutationQueue(\n user: User,\n indexManager: IndexManager\n ): IndexedDbMutationQueue {\n debugAssert(\n this.started,\n 'Cannot initialize MutationQueue before persistence is started.'\n );\n return IndexedDbMutationQueue.forUser(\n user,\n this.serializer,\n indexManager,\n this.referenceDelegate\n );\n }\n\n getTargetCache(): IndexedDbTargetCache {\n debugAssert(\n this.started,\n 'Cannot initialize TargetCache before persistence is started.'\n );\n return this.targetCache;\n }\n\n getRemoteDocumentCache(): IndexedDbRemoteDocumentCache {\n debugAssert(\n this.started,\n 'Cannot initialize RemoteDocumentCache before persistence is started.'\n );\n return this.remoteDocumentCache;\n }\n\n getIndexManager(user: User): IndexManager {\n debugAssert(\n this.started,\n 'Cannot initialize IndexManager before persistence is started.'\n );\n return new IndexedDbIndexManager(\n user,\n this.serializer.remoteSerializer.databaseId\n );\n }\n\n getDocumentOverlayCache(user: User): DocumentOverlayCache {\n debugAssert(\n this.started,\n 'Cannot initialize IndexedDbDocumentOverlayCache before persistence is started.'\n );\n return IndexedDbDocumentOverlayCache.forUser(this.serializer, user);\n }\n\n getBundleCache(): BundleCache {\n debugAssert(\n this.started,\n 'Cannot initialize BundleCache before persistence is started.'\n );\n return this.bundleCache;\n }\n\n runTransaction(\n action: string,\n mode: PersistenceTransactionMode,\n transactionOperation: (\n transaction: PersistenceTransaction\n ) => PersistencePromise\n ): Promise {\n logDebug(LOG_TAG, 'Starting transaction:', action);\n\n const simpleDbMode = mode === 'readonly' ? 'readonly' : 'readwrite';\n const objectStores = getObjectStores(this.schemaVersion);\n\n let persistenceTransaction: PersistenceTransaction;\n\n // Do all transactions as readwrite against all object stores, since we\n // are the only reader/writer.\n return this.simpleDb\n .runTransaction(action, simpleDbMode, objectStores, simpleDbTxn => {\n persistenceTransaction = new IndexedDbTransaction(\n simpleDbTxn,\n this.listenSequence\n ? this.listenSequence.next()\n : ListenSequence.INVALID\n );\n\n if (mode === 'readwrite-primary') {\n // While we merely verify that we have (or can acquire) the lease\n // immediately, we wait to extend the primary lease until after\n // executing transactionOperation(). This ensures that even if the\n // transactionOperation takes a long time, we'll use a recent\n // leaseTimestampMs in the extended (or newly acquired) lease.\n return this.verifyPrimaryLease(persistenceTransaction)\n .next(holdsPrimaryLease => {\n if (holdsPrimaryLease) {\n return /* holdsPrimaryLease= */ true;\n }\n return this.canActAsPrimary(persistenceTransaction);\n })\n .next(holdsPrimaryLease => {\n if (!holdsPrimaryLease) {\n logError(\n `Failed to obtain primary lease for action '${action}'.`\n );\n this.isPrimary = false;\n this.queue.enqueueRetryable(() =>\n this.primaryStateListener(false)\n );\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_LOST_ERROR_MSG\n );\n }\n return transactionOperation(persistenceTransaction);\n })\n .next(result => {\n return this.acquireOrExtendPrimaryLease(\n persistenceTransaction\n ).next(() => result);\n });\n } else {\n return this.verifyAllowTabSynchronization(\n persistenceTransaction\n ).next(() => transactionOperation(persistenceTransaction));\n }\n })\n .then(result => {\n persistenceTransaction.raiseOnCommittedEvent();\n return result;\n });\n }\n\n /**\n * Verifies that the current tab is the primary leaseholder or alternatively\n * that the leaseholder has opted into multi-tab synchronization.\n */\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer\n // be turned off.\n private verifyAllowTabSynchronization(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const store = primaryClientStore(txn);\n return store.get(DbPrimaryClientKey).next(currentPrimary => {\n const currentLeaseIsValid =\n currentPrimary !== null &&\n this.isWithinAge(\n currentPrimary.leaseTimestampMs,\n MAX_PRIMARY_ELIGIBLE_AGE_MS\n ) &&\n !this.isClientZombied(currentPrimary.ownerId);\n\n if (currentLeaseIsValid && !this.isLocalClient(currentPrimary)) {\n if (\n !this.forceOwningTab &&\n (!this.allowTabSynchronization ||\n !currentPrimary!.allowTabSynchronization)\n ) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG\n );\n }\n }\n });\n }\n\n /**\n * Obtains or extends the new primary lease for the local client. This\n * method does not verify that the client is eligible for this lease.\n */\n private acquireOrExtendPrimaryLease(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const newPrimary: DbPrimaryClient = {\n ownerId: this.clientId,\n allowTabSynchronization: this.allowTabSynchronization,\n leaseTimestampMs: Date.now()\n };\n return primaryClientStore(txn).put(DbPrimaryClientKey, newPrimary);\n }\n\n static isAvailable(): boolean {\n return SimpleDb.isAvailable();\n }\n\n /** Checks the primary lease and removes it if we are the current primary. */\n private releasePrimaryLeaseIfHeld(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const store = primaryClientStore(txn);\n return store.get(DbPrimaryClientKey).next(primaryClient => {\n if (this.isLocalClient(primaryClient)) {\n logDebug(LOG_TAG, 'Releasing primary lease.');\n return store.delete(DbPrimaryClientKey);\n } else {\n return PersistencePromise.resolve();\n }\n });\n }\n\n /** Verifies that `updateTimeMs` is within `maxAgeMs`. */\n private isWithinAge(updateTimeMs: number, maxAgeMs: number): boolean {\n const now = Date.now();\n const minAcceptable = now - maxAgeMs;\n const maxAcceptable = now;\n if (updateTimeMs < minAcceptable) {\n return false;\n } else if (updateTimeMs > maxAcceptable) {\n logError(\n `Detected an update time that is in the future: ${updateTimeMs} > ${maxAcceptable}`\n );\n return false;\n }\n\n return true;\n }\n\n private attachVisibilityHandler(): void {\n if (\n this.document !== null &&\n typeof this.document.addEventListener === 'function'\n ) {\n this.documentVisibilityHandler = () => {\n this.queue.enqueueAndForget(() => {\n this.inForeground = this.document!.visibilityState === 'visible';\n return this.updateClientMetadataAndTryBecomePrimary();\n });\n };\n\n this.document.addEventListener(\n 'visibilitychange',\n this.documentVisibilityHandler\n );\n\n this.inForeground = this.document.visibilityState === 'visible';\n }\n }\n\n private detachVisibilityHandler(): void {\n if (this.documentVisibilityHandler) {\n debugAssert(\n this.document !== null &&\n typeof this.document.addEventListener === 'function',\n \"Expected 'document.addEventListener' to be a function\"\n );\n this.document.removeEventListener(\n 'visibilitychange',\n this.documentVisibilityHandler\n );\n this.documentVisibilityHandler = null;\n }\n }\n\n /**\n * Attaches a window.unload handler that will synchronously write our\n * clientId to a \"zombie client id\" location in LocalStorage. This can be used\n * by tabs trying to acquire the primary lease to determine that the lease\n * is no longer valid even if the timestamp is recent. This is particularly\n * important for the refresh case (so the tab correctly re-acquires the\n * primary lease). LocalStorage is used for this rather than IndexedDb because\n * it is a synchronous API and so can be used reliably from an unload\n * handler.\n */\n private attachWindowUnloadHook(): void {\n if (typeof this.window?.addEventListener === 'function') {\n this.windowUnloadHandler = () => {\n // Note: In theory, this should be scheduled on the AsyncQueue since it\n // accesses internal state. We execute this code directly during shutdown\n // to make sure it gets a chance to run.\n this.markClientZombied();\n\n const safariIndexdbBugVersionRegex = /(?:Version|Mobile)\\/1[456]/;\n if (\n isSafari() &&\n (navigator.appVersion.match(safariIndexdbBugVersionRegex) ||\n navigator.userAgent.match(safariIndexdbBugVersionRegex))\n ) {\n // On Safari 14, 15, and 16, we do not run any cleanup actions as it might\n // trigger a bug that prevents Safari from re-opening IndexedDB during\n // the next page load.\n // See https://bugs.webkit.org/show_bug.cgi?id=226547\n this.queue.enterRestrictedMode(/* purgeExistingTasks= */ true);\n }\n\n this.queue.enqueueAndForget(() => {\n // Attempt graceful shutdown (including releasing our primary lease),\n // but there's no guarantee it will complete.\n return this.shutdown();\n });\n };\n this.window.addEventListener('pagehide', this.windowUnloadHandler);\n }\n }\n\n private detachWindowUnloadHook(): void {\n if (this.windowUnloadHandler) {\n debugAssert(\n typeof this.window?.removeEventListener === 'function',\n \"Expected 'window.removeEventListener' to be a function\"\n );\n this.window!.removeEventListener('pagehide', this.windowUnloadHandler);\n this.windowUnloadHandler = null;\n }\n }\n\n /**\n * Returns whether a client is \"zombied\" based on its LocalStorage entry.\n * Clients become zombied when their tab closes without running all of the\n * cleanup logic in `shutdown()`.\n */\n private isClientZombied(clientId: ClientId): boolean {\n try {\n const isZombied =\n this.webStorage?.getItem(\n this.zombiedClientLocalStorageKey(clientId)\n ) !== null;\n logDebug(\n LOG_TAG,\n `Client '${clientId}' ${\n isZombied ? 'is' : 'is not'\n } zombied in LocalStorage`\n );\n return isZombied;\n } catch (e) {\n // Gracefully handle if LocalStorage isn't working.\n logError(LOG_TAG, 'Failed to get zombied client id.', e);\n return false;\n }\n }\n\n /**\n * Record client as zombied (a client that had its tab closed). Zombied\n * clients are ignored during primary tab selection.\n */\n private markClientZombied(): void {\n if (!this.webStorage) {\n return;\n }\n try {\n this.webStorage.setItem(\n this.zombiedClientLocalStorageKey(this.clientId),\n String(Date.now())\n );\n } catch (e) {\n // Gracefully handle if LocalStorage isn't available / working.\n logError('Failed to set zombie client id.', e);\n }\n }\n\n /** Removes the zombied client entry if it exists. */\n private removeClientZombiedEntry(): void {\n if (!this.webStorage) {\n return;\n }\n try {\n this.webStorage.removeItem(\n this.zombiedClientLocalStorageKey(this.clientId)\n );\n } catch (e) {\n // Ignore\n }\n }\n\n private zombiedClientLocalStorageKey(clientId: ClientId): string {\n return `${ZOMBIED_CLIENTS_KEY_PREFIX}_${this.persistenceKey}_${clientId}`;\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the primary client object store.\n */\nfunction primaryClientStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbPrimaryClientStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the client metadata object store.\n */\nfunction clientMetadataStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbClientMetadataStore\n );\n}\n\n/**\n * Generates a string used as a prefix when storing data in IndexedDB and\n * LocalStorage.\n */\nexport function indexedDbStoragePrefix(\n databaseId: DatabaseId,\n persistenceKey: string\n): string {\n // Use two different prefix formats:\n //\n // * firestore / persistenceKey / projectID . databaseID / ...\n // * firestore / persistenceKey / projectID / ...\n //\n // projectIDs are DNS-compatible names and cannot contain dots\n // so there's no danger of collisions.\n let database = databaseId.projectId;\n if (!databaseId.isDefaultDatabase) {\n database += '.' + databaseId.database;\n }\n\n return 'firestore/' + persistenceKey + '/' + database + '/';\n}\n\nexport async function indexedDbClearPersistence(\n persistenceKey: string\n): Promise {\n if (!SimpleDb.isAvailable()) {\n return Promise.resolve();\n }\n const dbName = persistenceKey + MAIN_DATABASE;\n await SimpleDb.delete(dbName);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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(\n batch !== null,\n 0x90f9,\n 'Attempt to reject nonexistent batch!'\n );\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 0xbd9d,\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 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 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { BatchId, MutationBatchState, TargetId } from '../core/types';\nimport { debugAssert } from '../util/assert';\n\nimport { ClientId } from './shared_client_state';\nimport { QueryTargetState } from './shared_client_state_syncer';\n\n// The format of the LocalStorage key that stores the client state is:\n// firestore_clients__\nexport const CLIENT_STATE_KEY_PREFIX = 'firestore_clients';\n\n/** Assembles the key for a client state in WebStorage */\nexport function createWebStorageClientStateKey(\n persistenceKey: string,\n clientId: ClientId\n): string {\n debugAssert(\n clientId.indexOf('_') === -1,\n `Client key cannot contain '_', but was '${clientId}'`\n );\n\n return `${CLIENT_STATE_KEY_PREFIX}_${persistenceKey}_${clientId}`;\n}\n\n/**\n * The JSON representation of a clients's metadata as used during WebStorage\n * serialization. The ClientId is omitted here as it is encoded as part of the\n * key.\n */\nexport interface ClientStateSchema {\n activeTargetIds: number[];\n updateTimeMs: number;\n}\n\n// The format of the WebStorage key that stores the mutation state is:\n// firestore_mutations__\n// (for unauthenticated users)\n// or: firestore_mutations___\n//\n// 'user_uid' is last to avoid needing to escape '_' characters that it might\n// contain.\nexport const MUTATION_BATCH_KEY_PREFIX = 'firestore_mutations';\n\n/** Assembles the key for a mutation batch in WebStorage */\nexport function createWebStorageMutationBatchKey(\n persistenceKey: string,\n user: User,\n batchId: BatchId\n): string {\n let mutationKey = `${MUTATION_BATCH_KEY_PREFIX}_${persistenceKey}_${batchId}`;\n\n if (user.isAuthenticated()) {\n mutationKey += `_${user.uid}`;\n }\n\n return mutationKey;\n}\n\n/**\n * The JSON representation of a mutation batch's metadata as used during\n * WebStorage serialization. The UserId and BatchId is omitted as it is\n * encoded as part of the key.\n */\nexport interface MutationMetadataSchema {\n state: MutationBatchState;\n error?: { code: string; message: string }; // Only set when state === 'rejected'\n updateTimeMs: number;\n}\n\n// The format of the WebStorage key that stores a query target's metadata is:\n// firestore_targets__\nexport const QUERY_TARGET_KEY_PREFIX = 'firestore_targets';\n\n/** Assembles the key for a query state in WebStorage */\nexport function createWebStorageQueryTargetMetadataKey(\n persistenceKey: string,\n targetId: TargetId\n): string {\n return `${QUERY_TARGET_KEY_PREFIX}_${persistenceKey}_${targetId}`;\n}\n\n/**\n * The JSON representation of a query target's state as used during WebStorage\n * serialization. The TargetId is omitted as it is encoded as part of the key.\n */\nexport interface QueryTargetStateSchema {\n state: QueryTargetState;\n error?: { code: string; message: string }; // Only set when state === 'rejected'\n updateTimeMs: number;\n}\n\n// The WebStorage prefix that stores the primary tab's online state. The\n// format of the key is:\n// firestore_online_state_\nexport const ONLINE_STATE_KEY_PREFIX = 'firestore_online_state';\n\n/** Assembles the key for the online state of the primary tab. */\nexport function createWebStorageOnlineStateKey(persistenceKey: string): string {\n return `${ONLINE_STATE_KEY_PREFIX}_${persistenceKey}`;\n}\n\n// The WebStorage prefix that plays as a event to indicate the remote documents\n// might have changed due to some secondary tabs loading a bundle.\n// format of the key is:\n// firestore_bundle_loaded_v2_\n// The version ending with \"v2\" stores the list of modified collection groups.\nexport const BUNDLE_LOADED_KEY_PREFIX = 'firestore_bundle_loaded_v2';\nexport function createBundleLoadedKey(persistenceKey: string): string {\n return `${BUNDLE_LOADED_KEY_PREFIX}_${persistenceKey}`;\n}\n\n/**\n * The JSON representation of the system's online state, as written by the\n * primary client.\n */\nexport interface SharedOnlineStateSchema {\n /**\n * The clientId of the client that wrote this onlineState value. Tracked so\n * that on startup, clients can check if this client is still active when\n * determining whether to apply this value or not.\n */\n readonly clientId: string;\n readonly onlineState: string;\n}\n\n// The WebStorage key prefix for the key that stores the last sequence number allocated. The key\n// looks like 'firestore_sequence_number_'.\nexport const SEQUENCE_NUMBER_KEY_PREFIX = 'firestore_sequence_number';\n\n/** Assembles the key for the current sequence number. */\nexport function createWebStorageSequenceNumberKey(\n persistenceKey: string\n): string {\n return `${SEQUENCE_NUMBER_KEY_PREFIX}_${persistenceKey}`;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { ListenSequence } from '../core/listen_sequence';\nimport {\n BatchId,\n ListenSequenceNumber,\n MutationBatchState,\n OnlineState,\n TargetId\n} from '../core/types';\nimport { TargetIdSet, targetIdSet } from '../model/collections';\nimport { hardAssert, debugAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logError, logDebug } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport { isSafeInteger, WindowLike } from '../util/types';\n\nimport {\n CLIENT_STATE_KEY_PREFIX,\n ClientStateSchema,\n createBundleLoadedKey,\n createWebStorageClientStateKey,\n createWebStorageMutationBatchKey,\n createWebStorageOnlineStateKey,\n createWebStorageQueryTargetMetadataKey,\n createWebStorageSequenceNumberKey,\n MUTATION_BATCH_KEY_PREFIX,\n MutationMetadataSchema,\n QUERY_TARGET_KEY_PREFIX,\n QueryTargetStateSchema,\n SharedOnlineStateSchema\n} from './shared_client_state_schema';\nimport {\n QueryTargetState,\n SharedClientStateSyncer\n} from './shared_client_state_syncer';\n\nconst LOG_TAG = 'SharedClientState';\n\n/**\n * A randomly-generated key assigned to each Firestore instance at startup.\n */\nexport type ClientId = string;\n\n/**\n * A `SharedClientState` keeps track of the global state of the mutations\n * and query targets for all active clients with the same persistence key (i.e.\n * project ID and FirebaseApp name). It relays local changes to other clients\n * and updates its local state as new state is observed.\n *\n * `SharedClientState` is primarily used for synchronization in Multi-Tab\n * environments. Each tab is responsible for registering its active query\n * targets and mutations. `SharedClientState` will then notify the listener\n * assigned to `.syncEngine` for updates to mutations and queries that\n * originated in other clients.\n *\n * To receive notifications, `.syncEngine` and `.onlineStateHandler` has to be\n * assigned before calling `start()`.\n */\nexport interface SharedClientState {\n onlineStateHandler: ((onlineState: OnlineState) => void) | null;\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null;\n\n /** Registers the Mutation Batch ID of a newly pending mutation. */\n addPendingMutation(batchId: BatchId): void;\n\n /**\n * Records that a pending mutation has been acknowledged or rejected.\n * Called by the primary client to notify secondary clients of mutation\n * results as they come back from the backend.\n */\n updateMutationState(\n batchId: BatchId,\n state: 'acknowledged' | 'rejected',\n error?: FirestoreError\n ): void;\n\n /**\n * Associates a new Query Target ID with the local Firestore client. Returns\n * the new query state for the query (which can be 'current' if the query is\n * already associated with another tab).\n *\n * If the target id is already associated with local client, the method simply\n * returns its `QueryTargetState`.\n */\n addLocalQueryTarget(\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 0x77ac,\n 'Found non-numeric sequence number',\n { seqString }\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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 * Utilities for dealing with node.js-style APIs. See nodePromise for more\n * details.\n */\n\n/**\n * Creates a node-style callback that resolves or rejects a new Promise. The\n * callback is passed to the given action which can then use the callback as\n * a parameter to a node-style function.\n *\n * The intent is to directly bridge a node-style function (which takes a\n * callback) into a Promise without manually converting between the node-style\n * callback and the promise at each call.\n *\n * In effect it allows you to convert:\n *\n * @example\n * new Promise((resolve: (value?: fs.Stats) => void,\n * reject: (error?: any) => void) => {\n * fs.stat(path, (error?: any, stat?: fs.Stats) => {\n * if (error) {\n * reject(error);\n * } else {\n * resolve(stat);\n * }\n * });\n * });\n *\n * Into\n * @example\n * nodePromise((callback: NodeCallback) => {\n * fs.stat(path, callback);\n * });\n *\n * @param action - a function that takes a node-style callback as an argument\n * and then uses that callback to invoke some node-style API.\n * @returns a new Promise which will be rejected if the callback is given the\n * first Error parameter or will resolve to the value given otherwise.\n */\nexport function nodePromise(\n action: (callback: NodeCallback) => void\n): Promise {\n return new Promise(\n (resolve: (value: R) => void, reject: (error?: unknown) => void) => {\n action((error?: unknown, value?: R) => {\n if (error) {\n reject(error);\n } else {\n resolve(value!);\n }\n });\n }\n );\n}\n\n/**\n * A node-style callback which passes an Error as the first argument if there\n * was an error, or passes null and a proper value\n */\nexport interface NodeCallback {\n (error?: unknown, value?: R): void;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Note: We have to use a package import here to avoid build errors such as\n// https://github.com/firebase/firebase-js-sdk/issues/5983\nimport * as grpc from '@grpc/grpc-js';\n\nimport { Token } from '../../api/credentials';\nimport { DatabaseInfo } from '../../core/database_info';\nimport { SDK_VERSION } from '../../core/version';\nimport { ResourcePath } from '../../model/path';\nimport { Connection, Stream } from '../../remote/connection';\nimport { mapCodeFromRpcCode } from '../../remote/rpc_error';\nimport { StreamBridge } from '../../remote/stream_bridge';\nimport { hardAssert } from '../../util/assert';\nimport { generateUniqueDebugId } from '../../util/debug_uid';\nimport { FirestoreError } from '../../util/error';\nimport { logError, logDebug, logWarn } from '../../util/log';\nimport { NodeCallback, nodePromise } from '../../util/node_api';\nimport { Deferred } from '../../util/promise';\n\n// TODO: Fetch runtime version from grpc-js/package.json instead\n// when there's a cleaner way to dynamic require JSON in both Node ESM and CJS\nconst grpcVersion = '__GRPC_VERSION__';\n\nconst LOG_TAG = 'GrpcConnection';\nconst X_GOOG_API_CLIENT_VALUE = `gl-node/${process.versions.node} fire/${SDK_VERSION} grpc/${grpcVersion}`;\n\nfunction createMetadata(\n databasePath: string,\n authToken: Token | null,\n appCheckToken: Token | null,\n appId: string\n): grpc.Metadata {\n hardAssert(\n authToken === null || authToken.type === 'OAuth',\n 0x9048,\n 'If provided, token must be OAuth'\n );\n const metadata = new grpc.Metadata();\n if (authToken) {\n authToken.headers.forEach((value, key) => metadata.set(key, value));\n }\n if (appCheckToken) {\n appCheckToken.headers.forEach((value, key) => metadata.set(key, value));\n }\n if (appId) {\n metadata.set('X-Firebase-GMPID', appId);\n }\n metadata.set('X-Goog-Api-Client', X_GOOG_API_CLIENT_VALUE);\n // These headers are used to improve routing and project isolation by the\n // backend.\n // TODO(b/199767712): We are keeping 'Google-Cloud-Resource-Prefix' until Emulators can be\n // released with cl/428820046. Currently blocked because Emulators are now built with Java\n // 11 from Google3.\n metadata.set('Google-Cloud-Resource-Prefix', databasePath);\n metadata.set('x-goog-request-params', databasePath);\n return metadata;\n}\n\n// The type of these stubs is dynamically generated by the GRPC runtime\n// from the protocol buffer.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype GeneratedGrpcStub = any;\n\n/**\n * A Connection implemented by GRPC-Node.\n */\nexport class GrpcConnection implements Connection {\n private readonly databasePath: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private readonly firestore: any;\n\n // We cache stubs for the most-recently-used token.\n private cachedStub: GeneratedGrpcStub | null = null;\n\n get shouldResourcePathBeIncludedInRequest(): boolean {\n // Both `invokeRPC()` and `invokeStreamingRPC()` ignore their `path` arguments, and expect\n // the \"path\" to be part of the given `request`.\n return true;\n }\n\n constructor(protos: grpc.GrpcObject, private databaseInfo: DatabaseInfo) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.firestore = (protos as any)['google']['firestore']['v1'];\n this.databasePath = `projects/${databaseInfo.databaseId.projectId}/databases/${databaseInfo.databaseId.database}`;\n }\n\n private ensureActiveStub(): GeneratedGrpcStub {\n if (!this.cachedStub) {\n logDebug(LOG_TAG, 'Creating Firestore stub.');\n const credentials = this.databaseInfo.ssl\n ? grpc.credentials.createSsl()\n : grpc.credentials.createInsecure();\n this.cachedStub = new this.firestore.Firestore(\n this.databaseInfo.host,\n credentials\n );\n }\n return this.cachedStub;\n }\n\n invokeRPC(\n rpcName: string,\n path: ResourcePath,\n request: Req,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Promise {\n const streamId = generateUniqueDebugId();\n const stub = this.ensureActiveStub();\n const metadata = createMetadata(\n this.databasePath,\n authToken,\n appCheckToken,\n this.databaseInfo.appId\n );\n const jsonRequest = { database: this.databasePath, ...request };\n\n return nodePromise((callback: NodeCallback) => {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' ${streamId} invoked with request:`,\n request\n );\n return stub[rpcName](\n jsonRequest,\n metadata,\n (grpcError?: grpc.ServiceError, value?: Resp) => {\n if (grpcError) {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' ${streamId} failed with error:`,\n grpcError\n );\n callback(\n new FirestoreError(\n mapCodeFromRpcCode(grpcError.code),\n grpcError.message\n )\n );\n } else {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' ${streamId} completed with response:`,\n value\n );\n callback(undefined, value);\n }\n }\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 const streamId = generateUniqueDebugId();\n const results: Resp[] = [];\n const responseDeferred = new Deferred();\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' ${streamId} invoked (streaming) with request:`,\n request\n );\n const stub = this.ensureActiveStub();\n const metadata = createMetadata(\n this.databasePath,\n authToken,\n appCheckToken,\n this.databaseInfo.appId\n );\n const jsonRequest = { ...request, database: this.databasePath };\n const stream = stub[rpcName](jsonRequest, metadata);\n let callbackFired = false;\n stream.on('data', (response: Resp) => {\n logDebug(\n LOG_TAG,\n `RPC ${rpcName} ${streamId} received result:`,\n response\n );\n results.push(response);\n if (\n expectedResponseCount !== undefined &&\n results.length === expectedResponseCount\n ) {\n callbackFired = true;\n responseDeferred.resolve(results);\n }\n });\n stream.on('end', () => {\n logDebug(LOG_TAG, `RPC '${rpcName}' ${streamId} completed.`);\n if (!callbackFired) {\n callbackFired = true;\n responseDeferred.resolve(results);\n }\n });\n stream.on('error', (grpcError: grpc.ServiceError) => {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' ${streamId} failed with error:`,\n grpcError\n );\n const code = mapCodeFromRpcCode(grpcError.code);\n responseDeferred.reject(new FirestoreError(code, grpcError.message));\n });\n\n return responseDeferred.promise;\n }\n\n // TODO(mikelehen): This \"method\" is a monster. Should be refactored.\n openStream(\n rpcName: string,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream {\n const streamId = generateUniqueDebugId();\n const stub = this.ensureActiveStub();\n const metadata = createMetadata(\n this.databasePath,\n authToken,\n appCheckToken,\n this.databaseInfo.appId\n );\n const grpcStream = stub[rpcName](metadata);\n\n let closed = false;\n const close = (err?: FirestoreError): void => {\n if (!closed) {\n closed = true;\n stream.callOnClose(err);\n grpcStream.end();\n }\n };\n\n const stream = new StreamBridge({\n sendFn: (msg: Req) => {\n if (!closed) {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} sending:`,\n msg\n );\n try {\n grpcStream.write(msg);\n } catch (e) {\n // This probably means we didn't conform to the proto. Make sure to\n // log the message we sent.\n logError('Failure sending:', msg);\n logError('Error:', e);\n throw e;\n }\n } else {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} ` +\n 'not sending because gRPC stream is closed:',\n msg\n );\n }\n },\n closeFn: () => {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} closed locally via close().`\n );\n close();\n }\n });\n\n let onConnectedSent = false;\n grpcStream.on('data', (msg: Resp) => {\n if (!closed) {\n logDebug(LOG_TAG, `RPC '${rpcName}' stream ${streamId} received:`, msg);\n // Emulate the \"onConnected\" event that WebChannelConnection sends.\n if (!onConnectedSent) {\n stream.callOnConnected();\n onConnectedSent = true;\n }\n stream.callOnMessage(msg);\n }\n });\n\n grpcStream.on('end', () => {\n logDebug(LOG_TAG, `RPC '${rpcName}' stream ${streamId} ended.`);\n close();\n });\n\n grpcStream.on('error', (grpcError: grpc.ServiceError) => {\n if (!closed) {\n logWarn(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} error. Code:`,\n grpcError.code,\n 'Message:',\n grpcError.message\n );\n const code = mapCodeFromRpcCode(grpcError.code);\n close(new FirestoreError(code, grpcError.message));\n }\n });\n\n logDebug(\n LOG_TAG,\n `Opening RPC '${rpcName}' stream ${streamId} ` +\n `to ${this.databaseInfo.host}`\n );\n // TODO(dimond): Since grpc has no explicit open status (or does it?) we\n // simulate an onOpen in the next loop after the stream had it's listeners\n // registered\n setTimeout(() => {\n stream.callOnOpen();\n }, 0);\n\n return stream;\n }\n\n /**\n * Closes and cleans up any resources associated with the GrpcConnection.\n * If a gRPC client has been generated for this connection, the gRPC client\n * is closed. Failure to call terminate on a GrpcConnection can result\n * in leaked resources of the gRPC client.\n */\n terminate(): void {\n if (this.cachedStub) {\n this.cachedStub.close();\n this.cachedStub = undefined;\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 { join, resolve, isAbsolute } from 'path';\n\n// Note: We have to use a package import here to avoid build errors such as\n// https://github.com/firebase/firebase-js-sdk/issues/5983\n\nimport * as grpc from '@grpc/grpc-js';\nimport * as protoLoader from '@grpc/proto-loader';\n// only used in tests\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { IConversionOptions, Root } from 'protobufjs';\n\nimport * as protos from '../../protos/protos.json';\n\n/** Used by tests so we can match @grpc/proto-loader behavior. */\nexport const protoLoaderOptions: IConversionOptions = {\n longs: String,\n enums: String,\n defaults: true,\n oneofs: false\n};\n\n/**\n * Loads the protocol buffer definitions for Firestore.\n *\n * @returns The GrpcObject representing our protos.\n */\nexport function loadProtos(): grpc.GrpcObject {\n const packageDefinition = protoLoader.fromJSON(protos, protoLoaderOptions);\n return grpc.loadPackageDefinition(packageDefinition);\n}\n\n/** Used by tests so we can directly create ProtobufJS proto message objects from JSON protos. */\nexport function loadRawProtos(): Root {\n const root = resolve(\n __dirname,\n process.env.FIRESTORE_PROTO_ROOT || '../../protos'\n );\n const firestoreProtoFile = join(root, 'google/firestore/v1/firestore.proto');\n\n const protoRoot = new Root();\n // Override the resolvePath function to look for protos in the 'root'\n // directory.\n protoRoot.resolvePath = (origin: string, target: string) => {\n if (isAbsolute(target)) {\n return target;\n }\n return join(root, target);\n };\n\n protoRoot.loadSync(firestoreProtoFile);\n protoRoot.resolveAll();\n return protoRoot;\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 { GrpcConnection } from './grpc_connection';\nimport { loadProtos } from './load_protos';\n\n/** Loads the GRPC stack */\nexport function newConnection(databaseInfo: DatabaseInfo): Connection {\n const protos = loadProtos();\n return new GrpcConnection(protos, databaseInfo);\n}\n\n/** Return the Platform-specific connectivity monitor. */\nexport function newConnectivityMonitor(): ConnectivityMonitor {\n return new NoopConnectivityMonitor();\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 if (process.env.USE_MOCK_PERSISTENCE === 'YES') {\n // eslint-disable-next-line no-restricted-globals\n return window;\n }\n\n return null;\n}\n\n/** The Platform's 'document' implementation or null if not available. */\nexport function getDocument(): Document | null {\n return null;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** 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= */ false);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 0x7a5a,\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 0xda08,\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 0x3186,\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, 0xd7c2, 'Missing entity in write response for `key`', {\n key\n });\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 0xfcd7,\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 0xf76d,\n 'unsupported combination of changes: `change` after `oldChange`',\n {\n change,\n oldChange\n }\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 { 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LoadBundleTaskProgress } from '@firebase/firestore-types';\n\nimport { LocalStore } from '../local/local_store';\nimport {\n localStoreApplyBundledDocuments,\n localStoreSaveNamedQuery\n} from '../local/local_store_impl';\nimport { documentKeySet, DocumentKeySet } from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport {\n BundleMetadata as ProtoBundleMetadata,\n NamedQuery as ProtoNamedQuery\n} from '../protos/firestore_bundle_proto';\nimport { Timestamp as ApiTimestamp } from '../protos/firestore_proto_api';\nimport {\n fromDocument,\n fromName,\n fromVersion,\n JsonProtoSerializer\n} from '../remote/serializer';\nimport { debugAssert } from '../util/assert';\nimport { SizedBundleElement } from '../util/bundle_reader';\n\nimport {\n BundleConverter,\n BundledDocument,\n BundledDocuments,\n BundleLoadResult\n} from './bundle';\nimport { SnapshotVersion } from './snapshot_version';\n\n/**\n * Helper to convert objects from bundles to model objects in the SDK.\n */\nexport class BundleConverterImpl implements BundleConverter {\n constructor(private readonly serializer: JsonProtoSerializer) {}\n\n toDocumentKey(name: string): DocumentKey {\n return fromName(this.serializer, name);\n }\n\n /**\n * Converts a BundleDocument to a MutableDocument.\n */\n toMutableDocument(bundledDoc: BundledDocument): MutableDocument {\n if (bundledDoc.metadata.exists) {\n debugAssert(\n !!bundledDoc.document,\n 'Document is undefined when metadata.exist is true.'\n );\n return fromDocument(this.serializer, bundledDoc.document!, false);\n } else {\n return MutableDocument.newNoDocument(\n this.toDocumentKey(bundledDoc.metadata.name!),\n this.toSnapshotVersion(bundledDoc.metadata.readTime!)\n );\n }\n }\n\n toSnapshotVersion(time: ApiTimestamp): SnapshotVersion {\n return fromVersion(time);\n }\n}\n\n/**\n * A class to process the elements from a bundle, and optionally load them into local\n * storage and provide progress update while loading.\n */\nexport class BundleLoader {\n /** The current progress of loading */\n private progress: LoadBundleTaskProgress;\n /** Batched queries to be saved into storage */\n private _queries: ProtoNamedQuery[] = [];\n /** Batched documents to be saved into storage */\n private _documents: BundledDocuments = [];\n /** The collection groups affected by this bundle. */\n private collectionGroups = new Set();\n\n constructor(\n private bundleMetadata: ProtoBundleMetadata,\n private serializer: JsonProtoSerializer\n ) {\n this.progress = bundleInitialProgress(bundleMetadata);\n }\n\n /**\n * Returns the named queries that have been parsed from the SizeBundleElements added by\n * calling {@link adSizedElement}.\n */\n get queries(): ProtoNamedQuery[] {\n return this._queries;\n }\n\n /**\n * Returns the BundledDocuments that have been parsed from the SizeBundleElements added by\n * calling {@link addSizedElement}.\n */\n get documents(): BundledDocuments {\n return this._documents;\n }\n\n /**\n * Adds an element from the bundle to the loader.\n *\n * Returns a new progress if adding the element leads to a new progress,\n * otherwise returns null.\n */\n addSizedElement(element: SizedBundleElement): LoadBundleTaskProgress | null {\n debugAssert(!element.isBundleMetadata(), 'Unexpected bundle metadata.');\n\n this.progress.bytesLoaded += element.byteLength;\n\n let documentsLoaded = this.progress.documentsLoaded;\n\n if (element.payload.namedQuery) {\n this._queries.push(element.payload.namedQuery);\n } else if (element.payload.documentMetadata) {\n this._documents.push({ metadata: element.payload.documentMetadata });\n if (!element.payload.documentMetadata.exists) {\n ++documentsLoaded;\n }\n const path = ResourcePath.fromString(\n element.payload.documentMetadata.name!\n );\n debugAssert(\n path.length >= 2,\n 'The document name does not point to a document.'\n );\n this.collectionGroups.add(path.get(path.length - 2));\n } else if (element.payload.document) {\n debugAssert(\n this._documents.length > 0 &&\n this._documents[this._documents.length - 1].metadata.name ===\n element.payload.document.name,\n 'The document being added does not match the stored metadata.'\n );\n this._documents[this._documents.length - 1].document =\n element.payload.document;\n ++documentsLoaded;\n }\n\n if (documentsLoaded !== this.progress.documentsLoaded) {\n this.progress.documentsLoaded = documentsLoaded;\n return { ...this.progress };\n }\n\n return null;\n }\n\n private getQueryDocumentMapping(\n documents: BundledDocuments\n ): Map {\n const queryDocumentMap = new Map();\n const bundleConverter = new BundleConverterImpl(this.serializer);\n for (const bundleDoc of documents) {\n if (bundleDoc.metadata.queries) {\n const documentKey = bundleConverter.toDocumentKey(\n bundleDoc.metadata.name!\n );\n for (const queryName of bundleDoc.metadata.queries) {\n const documentKeys = (\n queryDocumentMap.get(queryName) || documentKeySet()\n ).add(documentKey);\n queryDocumentMap.set(queryName, documentKeys);\n }\n }\n }\n\n return queryDocumentMap;\n }\n\n /**\n * Update the progress to 'Success' and return the updated progress.\n */\n async completeAndStoreAsync(\n localStore: LocalStore\n ): Promise {\n debugAssert(\n this._documents[this._documents.length - 1]?.metadata.exists !== true ||\n !!this._documents[this._documents.length - 1].document,\n 'Bundled documents end with a document metadata element instead of a document.'\n );\n debugAssert(!!this.bundleMetadata.id, 'Bundle ID must be set.');\n\n const changedDocs = await localStoreApplyBundledDocuments(\n localStore,\n new BundleConverterImpl(this.serializer),\n this._documents,\n this.bundleMetadata.id!\n );\n\n const queryDocumentMap = this.getQueryDocumentMapping(this.documents);\n\n for (const q of this._queries) {\n await localStoreSaveNamedQuery(\n localStore,\n q,\n queryDocumentMap.get(q.name!)\n );\n }\n\n this.progress.taskState = 'Success';\n return {\n progress: this.progress,\n changedCollectionGroups: this.collectionGroups,\n changedDocs\n };\n }\n}\n\n/**\n * Returns a `LoadBundleTaskProgress` representing the initial progress of\n * loading a bundle.\n */\nexport function bundleInitialProgress(\n metadata: ProtoBundleMetadata\n): LoadBundleTaskProgress {\n return {\n taskState: 'Running',\n documentsLoaded: 0,\n bytesLoaded: 0,\n totalDocuments: metadata.totalDocuments!,\n totalBytes: metadata.totalBytes!\n };\n}\n\n/**\n * Returns a `LoadBundleTaskProgress` representing the progress that the loading\n * has succeeded.\n */\nexport function bundleSuccessProgress(\n metadata: ProtoBundleMetadata\n): LoadBundleTaskProgress {\n return {\n taskState: 'Success',\n documentsLoaded: metadata.totalDocuments!,\n bytesLoaded: metadata.totalBytes!,\n totalDocuments: metadata.totalDocuments!,\n totalBytes: metadata.totalBytes!\n };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { QueryResult } from '../local/local_store_impl';\nimport {\n documentKeySet,\n DocumentKeySet,\n DocumentMap\n} from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { DocumentSet } from '../model/document_set';\nimport { TargetChange } from '../remote/remote_event';\nimport { debugAssert, fail } from '../util/assert';\n\nimport { LimitType, newQueryComparator, Query, queryMatches } from './query';\nimport { OnlineState } from './types';\nimport {\n ChangeType,\n DocumentChangeSet,\n SyncState,\n ViewSnapshot\n} from './view_snapshot';\n\nexport type LimboDocumentChange = AddedLimboDocument | RemovedLimboDocument;\nexport class AddedLimboDocument {\n constructor(public key: DocumentKey) {}\n}\nexport class RemovedLimboDocument {\n constructor(public key: DocumentKey) {}\n}\n\n/** The result of applying a set of doc changes to a view. */\nexport interface ViewDocumentChanges {\n /** The new set of docs that should be in the view. */\n documentSet: DocumentSet;\n /** The diff of these docs with the previous set of docs. */\n changeSet: DocumentChangeSet;\n /**\n * Whether the set of documents passed in was not sufficient to calculate the\n * new state of the view and there needs to be another pass based on the\n * local cache.\n */\n needsRefill: boolean;\n\n mutatedKeys: DocumentKeySet;\n}\n\nexport interface ViewChange {\n snapshot?: ViewSnapshot;\n limboChanges: LimboDocumentChange[];\n}\n\n/**\n * View is responsible for computing the final merged truth of what docs are in\n * a query. It gets notified of local and remote changes to docs, and applies\n * the query filters and limits to determine the most correct possible results.\n */\nexport class View {\n private syncState: SyncState | null = null;\n private hasCachedResults: boolean = false;\n /**\n * A flag whether the view is current with the backend. A view is considered\n * current after it has seen the current flag from the backend and did not\n * lose consistency within the watch stream (e.g. because of an existence\n * filter mismatch).\n */\n private current = false;\n private documentSet: DocumentSet;\n /** Documents in the view but not in the remote target */\n private limboDocuments = documentKeySet();\n /** Document Keys that have local changes */\n private mutatedKeys = documentKeySet();\n /** Query comparator that defines the document order in this view. */\n private docComparator: (d1: Document, d2: Document) => number;\n\n constructor(\n private query: Query,\n /** Documents included in the remote target */\n private _syncedDocuments: DocumentKeySet\n ) {\n this.docComparator = newQueryComparator(query);\n this.documentSet = new DocumentSet(this.docComparator);\n }\n\n /**\n * The set of remote documents that the server has told us belongs to the target associated with\n * this view.\n */\n get syncedDocuments(): DocumentKeySet {\n return this._syncedDocuments;\n }\n\n /**\n * Iterates over a set of doc changes, applies the query limit, and computes\n * what the new results should be, what the changes were, and whether we may\n * need to go back to the local cache for more results. Does not make any\n * changes to the view.\n * @param docChanges - The doc changes to apply to this view.\n * @param previousChanges - If this is being called with a refill, then start\n * with this set of docs and changes instead of the current view.\n * @returns a new set of docs, changes, and refill flag.\n */\n computeDocChanges(\n docChanges: DocumentMap,\n previousChanges?: ViewDocumentChanges\n ): ViewDocumentChanges {\n const changeSet = previousChanges\n ? previousChanges.changeSet\n : new DocumentChangeSet();\n const oldDocumentSet = previousChanges\n ? previousChanges.documentSet\n : this.documentSet;\n let newMutatedKeys = previousChanges\n ? previousChanges.mutatedKeys\n : this.mutatedKeys;\n let newDocumentSet = oldDocumentSet;\n let needsRefill = false;\n\n // Track the last doc in a (full) limit. This is necessary, because some\n // update (a delete, or an update moving a doc past the old limit) might\n // mean there is some other document in the local cache that either should\n // come (1) between the old last limit doc and the new last document, in the\n // case of updates, or (2) after the new last document, in the case of\n // deletes. So we keep this doc at the old limit to compare the updates to.\n //\n // Note that this should never get used in a refill (when previousChanges is\n // set), because there will only be adds -- no deletes or updates.\n const lastDocInLimit =\n this.query.limitType === LimitType.First &&\n oldDocumentSet.size === this.query.limit\n ? oldDocumentSet.last()\n : null;\n const firstDocInLimit =\n this.query.limitType === LimitType.Last &&\n oldDocumentSet.size === this.query.limit\n ? oldDocumentSet.first()\n : null;\n\n docChanges.inorderTraversal((key, entry) => {\n const oldDoc = oldDocumentSet.get(key);\n const newDoc = queryMatches(this.query, entry) ? entry : null;\n\n const oldDocHadPendingMutations = oldDoc\n ? this.mutatedKeys.has(oldDoc.key)\n : false;\n const newDocHasPendingMutations = newDoc\n ? newDoc.hasLocalMutations ||\n // We only consider committed mutations for documents that were\n // mutated during the lifetime of the view.\n (this.mutatedKeys.has(newDoc.key) && newDoc.hasCommittedMutations)\n : false;\n\n let changeApplied = false;\n\n // Calculate change\n if (oldDoc && newDoc) {\n const docsEqual = oldDoc.data.isEqual(newDoc.data);\n if (!docsEqual) {\n if (!this.shouldWaitForSyncedDocument(oldDoc, newDoc)) {\n changeSet.track({\n type: ChangeType.Modified,\n doc: newDoc\n });\n changeApplied = true;\n\n if (\n (lastDocInLimit &&\n this.docComparator(newDoc, lastDocInLimit) > 0) ||\n (firstDocInLimit &&\n this.docComparator(newDoc, firstDocInLimit) < 0)\n ) {\n // This doc moved from inside the limit to outside the limit.\n // That means there may be some other doc in the local cache\n // that should be included instead.\n needsRefill = true;\n }\n }\n } else if (oldDocHadPendingMutations !== newDocHasPendingMutations) {\n changeSet.track({ type: ChangeType.Metadata, doc: newDoc });\n changeApplied = true;\n }\n } else if (!oldDoc && newDoc) {\n changeSet.track({ type: ChangeType.Added, doc: newDoc });\n changeApplied = true;\n } else if (oldDoc && !newDoc) {\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc });\n changeApplied = true;\n\n if (lastDocInLimit || firstDocInLimit) {\n // A doc was removed from a full limit query. We'll need to\n // requery from the local cache to see if we know about some other\n // doc that should be in the results.\n needsRefill = true;\n }\n }\n\n if (changeApplied) {\n if (newDoc) {\n newDocumentSet = newDocumentSet.add(newDoc);\n if (newDocHasPendingMutations) {\n newMutatedKeys = newMutatedKeys.add(key);\n } else {\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n } else {\n newDocumentSet = newDocumentSet.delete(key);\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n }\n });\n\n // Drop documents out to meet limit/limitToLast requirement.\n if (this.query.limit !== null) {\n while (newDocumentSet.size > this.query.limit!) {\n const oldDoc =\n this.query.limitType === LimitType.First\n ? newDocumentSet.last()\n : newDocumentSet.first();\n newDocumentSet = newDocumentSet.delete(oldDoc!.key);\n newMutatedKeys = newMutatedKeys.delete(oldDoc!.key);\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc! });\n }\n }\n\n debugAssert(\n !needsRefill || !previousChanges,\n 'View was refilled using docs that themselves needed refilling.'\n );\n return {\n documentSet: newDocumentSet,\n changeSet,\n needsRefill,\n mutatedKeys: newMutatedKeys\n };\n }\n\n private shouldWaitForSyncedDocument(\n oldDoc: Document,\n newDoc: Document\n ): boolean {\n // We suppress the initial change event for documents that were modified as\n // part of a write acknowledgment (e.g. when the value of a server transform\n // is applied) as Watch will send us the same document again.\n // By suppressing the event, we only raise two user visible events (one with\n // `hasPendingWrites` and the final state of the document) instead of three\n // (one with `hasPendingWrites`, the modified document with\n // `hasPendingWrites` and the final state of the document).\n return (\n oldDoc.hasLocalMutations &&\n newDoc.hasCommittedMutations &&\n !newDoc.hasLocalMutations\n );\n }\n\n /**\n * Updates the view with the given ViewDocumentChanges and optionally updates\n * limbo docs and sync state from the provided target change.\n * @param docChanges - The set of changes to make to the view's docs.\n * @param limboResolutionEnabled - Whether to update limbo documents based on\n * this change.\n * @param targetChange - A target change to apply for computing limbo docs and\n * sync state.\n * @param targetIsPendingReset - Whether the target is pending to reset due to\n * existence filter mismatch. If not explicitly specified, it is treated\n * equivalently to `false`.\n * @returns A new ViewChange with the given docs, changes, and sync state.\n */\n // PORTING NOTE: The iOS/Android clients always compute limbo document changes.\n applyChanges(\n docChanges: ViewDocumentChanges,\n limboResolutionEnabled: boolean,\n targetChange?: TargetChange,\n targetIsPendingReset?: boolean\n ): ViewChange {\n debugAssert(\n !docChanges.needsRefill,\n 'Cannot apply changes that need a refill'\n );\n const oldDocs = this.documentSet;\n this.documentSet = docChanges.documentSet;\n this.mutatedKeys = docChanges.mutatedKeys;\n // Sort changes based on type and query comparator\n const changes = docChanges.changeSet.getChanges();\n changes.sort((c1, c2) => {\n return (\n compareChangeType(c1.type, c2.type) ||\n this.docComparator(c1.doc, c2.doc)\n );\n });\n\n this.applyTargetChange(targetChange);\n\n targetIsPendingReset = targetIsPendingReset ?? false;\n const limboChanges =\n limboResolutionEnabled && !targetIsPendingReset\n ? this.updateLimboDocuments()\n : [];\n\n // We are at synced state if there is no limbo docs are waiting to be resolved, view is current\n // with the backend, and the query is not pending to reset due to existence filter mismatch.\n const synced =\n this.limboDocuments.size === 0 && this.current && !targetIsPendingReset;\n\n const newSyncState = synced ? SyncState.Synced : SyncState.Local;\n const syncStateChanged = newSyncState !== this.syncState;\n this.syncState = newSyncState;\n\n if (changes.length === 0 && !syncStateChanged) {\n // no changes\n return { limboChanges };\n } else {\n const snap: ViewSnapshot = new ViewSnapshot(\n this.query,\n docChanges.documentSet,\n oldDocs,\n changes,\n docChanges.mutatedKeys,\n newSyncState === SyncState.Local,\n syncStateChanged,\n /* excludesMetadataChanges= */ false,\n targetChange\n ? targetChange.resumeToken.approximateByteSize() > 0\n : false\n );\n return {\n snapshot: snap,\n limboChanges\n };\n }\n }\n\n /**\n * Applies an OnlineState change to the view, potentially generating a\n * ViewChange if the view's syncState changes as a result.\n */\n applyOnlineStateChange(onlineState: OnlineState): ViewChange {\n if (this.current && onlineState === OnlineState.Offline) {\n // If we're offline, set `current` to false and then call applyChanges()\n // to refresh our syncState and generate a ViewChange as appropriate. We\n // are guaranteed to get a new TargetChange that sets `current` back to\n // true once the client is back online.\n this.current = false;\n return this.applyChanges(\n {\n documentSet: this.documentSet,\n changeSet: new DocumentChangeSet(),\n mutatedKeys: this.mutatedKeys,\n needsRefill: false\n },\n /* limboResolutionEnabled= */ false\n );\n } else {\n // No effect, just return a no-op ViewChange.\n return { limboChanges: [] };\n }\n }\n\n /**\n * Returns whether the doc for the given key should be in limbo.\n */\n private shouldBeInLimbo(key: DocumentKey): boolean {\n // If the remote end says it's part of this query, it's not in limbo.\n if (this._syncedDocuments.has(key)) {\n return false;\n }\n // The local store doesn't think it's a result, so it shouldn't be in limbo.\n if (!this.documentSet.has(key)) {\n return false;\n }\n // If there are local changes to the doc, they might explain why the server\n // doesn't know that it's part of the query. So don't put it in limbo.\n // TODO(klimt): Ideally, we would only consider changes that might actually\n // affect this specific query.\n if (this.documentSet.get(key)!.hasLocalMutations) {\n return false;\n }\n // Everything else is in limbo.\n return true;\n }\n\n /**\n * Updates syncedDocuments, current, and limbo docs based on the given change.\n * Returns the list of changes to which docs are in limbo.\n */\n private applyTargetChange(targetChange?: TargetChange): void {\n if (targetChange) {\n targetChange.addedDocuments.forEach(\n key => (this._syncedDocuments = this._syncedDocuments.add(key))\n );\n targetChange.modifiedDocuments.forEach(key => {\n debugAssert(\n this._syncedDocuments.has(key),\n `Modified document ${key} not found in view.`\n );\n });\n targetChange.removedDocuments.forEach(\n key => (this._syncedDocuments = this._syncedDocuments.delete(key))\n );\n this.current = targetChange.current;\n }\n }\n\n private updateLimboDocuments(): LimboDocumentChange[] {\n // We can only determine limbo documents when we're in-sync with the server.\n if (!this.current) {\n return [];\n }\n\n // TODO(klimt): Do this incrementally so that it's not quadratic when\n // updating many documents.\n const oldLimboDocuments = this.limboDocuments;\n this.limboDocuments = documentKeySet();\n this.documentSet.forEach(doc => {\n if (this.shouldBeInLimbo(doc.key)) {\n this.limboDocuments = this.limboDocuments.add(doc.key);\n }\n });\n\n // Diff the new limbo docs with the old limbo docs.\n const changes: LimboDocumentChange[] = [];\n oldLimboDocuments.forEach(key => {\n if (!this.limboDocuments.has(key)) {\n changes.push(new RemovedLimboDocument(key));\n }\n });\n this.limboDocuments.forEach(key => {\n if (!oldLimboDocuments.has(key)) {\n changes.push(new AddedLimboDocument(key));\n }\n });\n return changes;\n }\n\n /**\n * Update the in-memory state of the current view with the state read from\n * persistence.\n *\n * We update the query view whenever a client's primary status changes:\n * - When a client transitions from primary to secondary, it can miss\n * LocalStorage updates and its query views may temporarily not be\n * synchronized with the state on disk.\n * - For secondary to primary transitions, the client needs to update the list\n * of `syncedDocuments` since secondary clients update their query views\n * based purely on synthesized RemoteEvents.\n *\n * @param queryResult.documents - The documents that match the query according\n * to the LocalStore.\n * @param queryResult.remoteKeys - The keys of the documents that match the\n * query according to the backend.\n *\n * @returns The ViewChange that resulted from this synchronization.\n */\n // PORTING NOTE: Multi-tab only.\n synchronizeWithPersistedState(queryResult: QueryResult): ViewChange {\n this._syncedDocuments = queryResult.remoteKeys;\n this.limboDocuments = documentKeySet();\n const docChanges = this.computeDocChanges(queryResult.documents);\n return this.applyChanges(docChanges, /* limboResolutionEnabled= */ true);\n }\n\n /**\n * Returns a view snapshot as if this query was just listened to. Contains\n * a document add for every existing document and the `fromCache` and\n * `hasPendingWrites` status of the already established view.\n */\n // PORTING NOTE: Multi-tab only.\n computeInitialSnapshot(): ViewSnapshot {\n return ViewSnapshot.fromInitialDocuments(\n this.query,\n this.documentSet,\n this.mutatedKeys,\n this.syncState === SyncState.Local,\n this.hasCachedResults\n );\n }\n}\n\nfunction compareChangeType(c1: ChangeType, c2: ChangeType): number {\n const order = (change: ChangeType): 0 | 1 | 2 => {\n switch (change) {\n case ChangeType.Added:\n return 1;\n case ChangeType.Modified:\n return 2;\n case ChangeType.Metadata:\n // A metadata change is converted to a modified change at the public\n // api layer. Since we sort by document key and then change type,\n // metadata and modified changes must be sorted equivalently.\n return 2;\n case ChangeType.Removed:\n return 0;\n default:\n return fail(0x4f35, '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 0x5858,\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 0x390f,\n 'Received change for limbo target document without add.'\n );\n } else if (targetChange.removedDocuments.size > 0) {\n hardAssert(\n limboResolution.receivedDocument,\n 0xa4f3,\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(0x4d4f, 'Unknown limbo change', { 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(0x1a40, `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(0xfa9b, '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(metadata, reader.serializer);\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.completeAndStoreAsync(syncEngine.localStore);\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 0xb743,\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 { debugAssert } from './assert';\n\n/**\n * How many bytes to read each time when `ReadableStreamReader.read()` is\n * called. Only applicable for byte streams that we control (e.g. those backed\n * by an UInt8Array).\n */\nexport const DEFAULT_BYTES_PER_READ = 10240;\n\n/**\n * Builds a `ByteStreamReader` from a UInt8Array.\n * @param source - The data source to use.\n * @param bytesPerRead - How many bytes each `read()` from the returned reader\n * will read.\n */\nexport function toByteStreamReaderHelper(\n source: Uint8Array,\n bytesPerRead: number = DEFAULT_BYTES_PER_READ\n): ReadableStreamDefaultReader {\n debugAssert(\n bytesPerRead > 0,\n `toByteStreamReader expects positive bytesPerRead, but got ${bytesPerRead}`\n );\n let readFrom = 0;\n // The TypeScript definition for ReadableStreamReader changed. We use\n // `any` here to allow this code to compile with different versions.\n // See https://github.com/microsoft/TypeScript/issues/42970\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const reader: any = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async read(): Promise {\n if (readFrom < source.byteLength) {\n const result = {\n value: source.slice(readFrom, readFrom + bytesPerRead),\n done: false\n } as const;\n readFrom += bytesPerRead;\n return result;\n }\n\n return { done: true };\n },\n async cancel(): Promise {},\n releaseLock() {},\n closed: Promise.resolve()\n };\n return reader;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BundleSource } from '../../util/bundle_reader';\nimport { toByteStreamReaderHelper } from '../../util/byte_stream';\nimport { Code, FirestoreError } from '../../util/error';\nimport { valueDescription } from '../../util/input_validation';\n\n/**\n * On Node, only supported data source is a `Uint8Array` for now.\n */\nexport function toByteStreamReader(\n source: BundleSource,\n bytesPerRead: number\n): ReadableStreamDefaultReader {\n if (!(source instanceof Uint8Array)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `NodePlatform.toByteStreamReader expects source to be Uint8Array, got ${valueDescription(\n source\n )}`\n );\n }\n return toByteStreamReaderHelper(source, bytesPerRead);\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n BundleElement,\n BundleMetadata\n} from '../protos/firestore_bundle_proto';\nimport { JsonProtoSerializer } from '../remote/serializer';\n\n/**\n * A complete element in the bundle stream, together with the byte length it\n * occupies in the stream.\n */\nexport class SizedBundleElement {\n constructor(\n public readonly payload: BundleElement,\n // How many bytes this element takes to store in the bundle.\n public readonly byteLength: number\n ) {}\n\n isBundleMetadata(): boolean {\n return 'metadata' in this.payload;\n }\n}\n\nexport type BundleSource =\n | ReadableStream\n | ArrayBuffer\n | Uint8Array;\n\n/**\n * A class representing a bundle.\n *\n * Takes a bundle stream or buffer, and presents abstractions to read bundled\n * elements out of the underlying content.\n */\nexport interface BundleReader {\n serializer: JsonProtoSerializer;\n\n close(): Promise;\n\n /**\n * Returns the metadata of the bundle.\n */\n getMetadata(): Promise;\n\n /**\n * Returns the next BundleElement (together with its byte size in the bundle)\n * that has not been read from underlying ReadableStream. Returns null if we\n * have reached the end of the stream.\n */\n nextElement(): Promise;\n}\n\n/**\n * A class representing a synchronized bundle reader.\n *\n * Takes a bundle string buffer, parses the data, and provides accessors to the data contained\n * within it.\n */\nexport interface BundleReaderSync {\n serializer: JsonProtoSerializer;\n\n /**\n * Returns the metadata of the bundle.\n */\n getMetadata(): BundleMetadata;\n\n /**\n * Returns BundleElements parsed from the bundle. Returns an empty array if no bundle elements\n * exist.\n */\n getElements(): SizedBundleElement[];\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { newTextDecoder } from '../platform/text_serializer';\nimport { BundleMetadata } from '../protos/firestore_bundle_proto';\nimport { JsonProtoSerializer } from '../remote/serializer';\n\nimport { debugAssert } from './assert';\nimport { BundleReader, SizedBundleElement } from './bundle_reader';\nimport { Deferred } from './promise';\n\n/**\n * A class representing a bundle.\n *\n * Takes a bundle stream or buffer, and presents abstractions to read bundled\n * elements out of the underlying content.\n */\nclass BundleReaderImpl implements BundleReader {\n /** Cached bundle metadata. */\n private metadata: Deferred = new Deferred();\n /**\n * Internal buffer to hold bundle content, accumulating incomplete element\n * content.\n */\n private buffer: Uint8Array = new Uint8Array();\n /** The decoder used to parse binary data into strings. */\n private textDecoder: TextDecoder;\n\n constructor(\n /** The reader to read from underlying binary bundle data source. */\n private reader: ReadableStreamDefaultReader,\n readonly serializer: JsonProtoSerializer\n ) {\n this.textDecoder = newTextDecoder();\n // Read the metadata (which is the first element).\n this.nextElementImpl().then(\n element => {\n if (element && element.isBundleMetadata()) {\n this.metadata.resolve(element.payload.metadata!);\n } else {\n this.metadata.reject(\n new Error(`The first element of the bundle is not a metadata, it is\n ${JSON.stringify(element?.payload)}`)\n );\n }\n },\n error => this.metadata.reject(error)\n );\n }\n\n close(): Promise {\n return this.reader.cancel();\n }\n\n async getMetadata(): Promise {\n return this.metadata.promise;\n }\n\n async nextElement(): Promise {\n // Makes sure metadata is read before proceeding.\n await this.getMetadata();\n return this.nextElementImpl();\n }\n\n /**\n * Reads from the head of internal buffer, and pulling more data from\n * underlying stream if a complete element cannot be found, until an\n * element(including the prefixed length and the JSON string) is found.\n *\n * Once a complete element is read, it is dropped from internal buffer.\n *\n * Returns either the bundled element, or null if we have reached the end of\n * the stream.\n */\n private async nextElementImpl(): Promise {\n const lengthBuffer = await this.readLength();\n if (lengthBuffer === null) {\n return null;\n }\n\n const lengthString = this.textDecoder.decode(lengthBuffer);\n const length = Number(lengthString);\n if (isNaN(length)) {\n this.raiseError(`length string (${lengthString}) is not valid number`);\n }\n\n const jsonString = await this.readJsonString(length);\n\n return new SizedBundleElement(\n JSON.parse(jsonString),\n lengthBuffer.length + length\n );\n }\n\n /** First index of '{' from the underlying buffer. */\n private indexOfOpenBracket(): number {\n return this.buffer.findIndex(v => v === '{'.charCodeAt(0));\n }\n\n /**\n * Reads from the beginning of the internal buffer, until the first '{', and\n * return the content.\n *\n * If reached end of the stream, returns a null.\n */\n private async readLength(): Promise {\n while (this.indexOfOpenBracket() < 0) {\n const done = await this.pullMoreDataToBuffer();\n if (done) {\n break;\n }\n }\n\n // Broke out of the loop because underlying stream is closed, and there\n // happens to be no more data to process.\n if (this.buffer.length === 0) {\n return null;\n }\n\n const position = this.indexOfOpenBracket();\n // Broke out of the loop because underlying stream is closed, but still\n // cannot find an open bracket.\n if (position < 0) {\n this.raiseError(\n 'Reached the end of bundle when a length string is expected.'\n );\n }\n\n const result = this.buffer.slice(0, position);\n // Update the internal buffer to drop the read length.\n this.buffer = this.buffer.slice(position);\n return result;\n }\n\n /**\n * Reads from a specified position from the internal buffer, for a specified\n * number of bytes, pulling more data from the underlying stream if needed.\n *\n * Returns a string decoded from the read bytes.\n */\n private async readJsonString(length: number): Promise {\n while (this.buffer.length < length) {\n const done = await this.pullMoreDataToBuffer();\n if (done) {\n this.raiseError('Reached the end of bundle when more is expected.');\n }\n }\n\n const result = this.textDecoder.decode(this.buffer.slice(0, length));\n // Update the internal buffer to drop the read json string.\n this.buffer = this.buffer.slice(length);\n return result;\n }\n\n private raiseError(message: string): void {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.reader.cancel();\n throw new Error(`Invalid bundle format: ${message}`);\n }\n\n /**\n * Pulls more data from underlying stream to internal buffer.\n * Returns a boolean indicating whether the stream is finished.\n */\n private async pullMoreDataToBuffer(): Promise {\n const result = await this.reader.read();\n if (!result.done) {\n debugAssert(!!result.value, 'Read undefined when \"done\" is false.');\n const newBuffer = new Uint8Array(\n this.buffer.length + result.value!.length\n );\n newBuffer.set(this.buffer);\n newBuffer.set(result.value!, this.buffer.length);\n this.buffer = newBuffer;\n }\n return result.done;\n }\n}\n\nexport function newBundleReader(\n reader: ReadableStreamDefaultReader,\n serializer: JsonProtoSerializer\n): BundleReader {\n return new BundleReaderImpl(reader, serializer);\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 } from '../protos/firestore_bundle_proto';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { BundleReaderSync, SizedBundleElement } from './bundle_reader';\n\n/**\n * A class that can parse a bundle form the string serialization of a bundle.\n */\nexport class BundleReaderSyncImpl implements BundleReaderSync {\n private metadata: BundleMetadata;\n private elements: SizedBundleElement[];\n private cursor: number;\n constructor(\n private bundleData: string,\n readonly serializer: JsonProtoSerializer\n ) {\n this.cursor = 0;\n this.elements = [];\n\n let element = this.nextElement();\n if (element && element.isBundleMetadata()) {\n this.metadata = element as BundleMetadata;\n } else {\n throw new Error(`The first element of the bundle is not a metadata object, it is\n ${JSON.stringify(element?.payload)}`);\n }\n\n do {\n element = this.nextElement();\n if (element !== null) {\n this.elements.push(element);\n }\n } while (element !== null);\n }\n\n /* Returns the parsed metadata of the bundle. */\n getMetadata(): BundleMetadata {\n return this.metadata;\n }\n\n /* Returns the DocumentSnapshot or NamedQuery elements of the bundle. */\n getElements(): SizedBundleElement[] {\n return this.elements;\n }\n\n /**\n * Parses the next element of the bundle.\n *\n * @returns a SizedBundleElement representation of the next element in the bundle, or null if\n * no more elements exist.\n */\n private nextElement(): SizedBundleElement | null {\n if (this.cursor === this.bundleData.length) {\n return null;\n }\n const length: number = this.readLength();\n const jsonString = this.readJsonString(length);\n return new SizedBundleElement(JSON.parse(jsonString), length);\n }\n\n /**\n * Reads from a specified position from the bundleData string, for a specified\n * number of bytes.\n *\n * @param length how many characters to read.\n * @returns a string parsed from the bundle.\n */\n private readJsonString(length: number): string {\n if (this.cursor + length > this.bundleData.length) {\n throw new FirestoreError(\n Code.INTERNAL,\n 'Reached the end of bundle when more is expected.'\n );\n }\n const result = this.bundleData.slice(this.cursor, (this.cursor += length));\n return result;\n }\n\n /**\n * Reads from the current cursor until the first '{'.\n *\n * @returns A string to integer represention of the parsed value.\n * @throws An {@link Error} if the cursor has reached the end of the stream, since lengths\n * prefix bundle objects.\n */\n private readLength(): number {\n const startIndex = this.cursor;\n let curIndex = this.cursor;\n while (curIndex < this.bundleData.length) {\n if (this.bundleData[curIndex] === '{') {\n if (curIndex === startIndex) {\n throw new Error('First character is a bracket and not a number');\n }\n this.cursor = curIndex;\n return Number(this.bundleData.slice(startIndex, curIndex));\n }\n curIndex++;\n }\n throw new Error('Reached the end of bundle when more is expected.');\n }\n}\n\n/**\n * Creates an instance of BundleReader without exposing the BundleReaderSyncImpl class type.\n */\nexport function newBundleReaderSync(\n bundleData: string,\n serializer: JsonProtoSerializer\n): BundleReaderSync {\n return new BundleReaderSyncImpl(bundleData, serializer);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParsedSetData, ParsedUpdateData } from '../lite-api/user_data_reader';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n DeleteMutation,\n Mutation,\n Precondition,\n VerifyMutation\n} from '../model/mutation';\nimport {\n Datastore,\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc\n} from '../remote/datastore';\nimport { fail, debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { SnapshotVersion } from './snapshot_version';\n\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nexport class Transaction {\n // The version of each document that was read during this transaction.\n private readVersions = new Map();\n private mutations: Mutation[] = [];\n private committed = false;\n\n /**\n * A deferred usage error that occurred previously in this transaction that\n * will cause the transaction to fail once it actually commits.\n */\n private lastTransactionError: FirestoreError | null = null;\n\n /**\n * Set of documents that have been written in the transaction.\n *\n * When there's more than one write to the same key in a transaction, any\n * writes after the first are handled differently.\n */\n private writtenDocs: Set = new Set();\n\n constructor(private datastore: Datastore) {}\n\n async lookup(keys: DocumentKey[]): Promise {\n this.ensureCommitNotCalled();\n\n if (this.mutations.length > 0) {\n this.lastTransactionError = new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Firestore transactions require all reads to be executed before all writes.'\n );\n throw this.lastTransactionError;\n }\n const docs = await invokeBatchGetDocumentsRpc(this.datastore, keys);\n docs.forEach(doc => this.recordVersion(doc));\n return docs;\n }\n\n set(key: DocumentKey, data: ParsedSetData): void {\n this.write(data.toMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n update(key: DocumentKey, data: ParsedUpdateData): void {\n try {\n this.write(data.toMutation(key, this.preconditionForUpdate(key)));\n } catch (e) {\n this.lastTransactionError = e as FirestoreError | null;\n }\n this.writtenDocs.add(key.toString());\n }\n\n delete(key: DocumentKey): void {\n this.write(new DeleteMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n async commit(): Promise {\n this.ensureCommitNotCalled();\n\n if (this.lastTransactionError) {\n throw this.lastTransactionError;\n }\n const unwritten = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach(mutation => {\n unwritten.delete(mutation.key.toString());\n });\n // For each document that was read but not written to, we want to perform\n // a `verify` operation.\n unwritten.forEach((_, path) => {\n const key = DocumentKey.fromPath(path);\n this.mutations.push(new VerifyMutation(key, this.precondition(key)));\n });\n await invokeCommitRpc(this.datastore, this.mutations);\n this.committed = true;\n }\n\n private recordVersion(doc: Document): void {\n let docVersion: SnapshotVersion;\n\n if (doc.isFoundDocument()) {\n docVersion = doc.version;\n } else if (doc.isNoDocument()) {\n // Represent a deleted doc using SnapshotVersion.min().\n docVersion = SnapshotVersion.min();\n } else {\n throw fail(0xc542, 'Document in a transaction was a ', {\n documentName: doc.constructor.name\n });\n }\n\n const existingVersion = this.readVersions.get(doc.key.toString());\n if (existingVersion) {\n if (!docVersion.isEqual(existingVersion)) {\n // This transaction will fail no matter what.\n throw new FirestoreError(\n Code.ABORTED,\n 'Document version changed between two reads.'\n );\n }\n } else {\n this.readVersions.set(doc.key.toString(), docVersion);\n }\n }\n\n /**\n * Returns the version of this document when it was read in this transaction,\n * as a precondition, or no precondition if it was not read.\n */\n private precondition(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n return Precondition.exists(false);\n } else {\n return Precondition.updateTime(version);\n }\n } else {\n return Precondition.none();\n }\n }\n\n /**\n * Returns the precondition for a document if the operation is an update.\n */\n private preconditionForUpdate(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n // The first time a document is written, we want to take into account the\n // read time and existence\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n // The document doesn't exist, so fail the transaction.\n\n // This has to be validated locally because you can't send a\n // precondition that a document does not exist without changing the\n // semantics of the backend write to be an insert. This is the reverse\n // of what we want, since we want to assert that the document doesn't\n // exist but then send the update and have it fail. Since we can't\n // express that to the backend, we have to validate locally.\n\n // Note: this can change once we can send separate verify writes in the\n // transaction.\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't update a document that doesn't exist.\"\n );\n }\n // Document exists, base precondition on document update time.\n return Precondition.updateTime(version);\n } else {\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return Precondition.exists(true);\n }\n }\n\n private write(mutation: Mutation): void {\n this.ensureCommitNotCalled();\n this.mutations.push(mutation);\n }\n\n private ensureCommitNotCalled(): void {\n debugAssert(\n !this.committed,\n 'A transaction object cannot be used after its update callback has been invoked.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ExponentialBackoff } from '../remote/backoff';\nimport { Datastore } from '../remote/datastore';\nimport { isPermanentError } from '../remote/rpc_error';\nimport { AsyncQueue, TimerId } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport { Deferred } from '../util/promise';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Transaction } from './transaction';\nimport { TransactionOptions } from './transaction_options';\n\n/**\n * TransactionRunner encapsulates the logic needed to run and retry transactions\n * with backoff.\n */\nexport class TransactionRunner {\n private attemptsRemaining: number;\n private backoff: ExponentialBackoff;\n\n constructor(\n private readonly asyncQueue: AsyncQueue,\n private readonly datastore: Datastore,\n private readonly options: TransactionOptions,\n private readonly updateFunction: (transaction: Transaction) => Promise,\n private readonly deferred: Deferred\n ) {\n this.attemptsRemaining = options.maxAttempts;\n this.backoff = new ExponentialBackoff(\n this.asyncQueue,\n TimerId.TransactionRetry\n );\n }\n\n /** Runs the transaction and sets the result on deferred. */\n run(): void {\n this.attemptsRemaining -= 1;\n this.runWithBackOff();\n }\n\n private runWithBackOff(): void {\n this.backoff.backoffAndRun(async () => {\n const transaction = new Transaction(this.datastore);\n const userPromise = this.tryRunUpdateFunction(transaction);\n if (userPromise) {\n userPromise\n .then(result => {\n this.asyncQueue.enqueueAndForget(() => {\n return transaction\n .commit()\n .then(() => {\n this.deferred.resolve(result);\n })\n .catch(commitError => {\n this.handleTransactionError(commitError);\n });\n });\n })\n .catch(userPromiseError => {\n this.handleTransactionError(userPromiseError);\n });\n }\n });\n }\n\n private tryRunUpdateFunction(transaction: Transaction): Promise | null {\n try {\n const userPromise = this.updateFunction(transaction);\n if (\n isNullOrUndefined(userPromise) ||\n !userPromise.catch ||\n !userPromise.then\n ) {\n this.deferred.reject(\n Error('Transaction callback must return a Promise')\n );\n return null;\n }\n return userPromise;\n } catch (error) {\n // Do not retry errors thrown by user provided updateFunction.\n this.deferred.reject(error as Error);\n return null;\n }\n }\n\n private handleTransactionError(error: Error): void {\n if (this.attemptsRemaining > 0 && this.isRetryableTransactionError(error)) {\n this.attemptsRemaining -= 1;\n this.asyncQueue.enqueueAndForget(() => {\n this.runWithBackOff();\n return Promise.resolve();\n });\n } else {\n this.deferred.reject(error);\n }\n }\n\n private isRetryableTransactionError(error: Error | undefined): boolean {\n if (error?.name === 'FirebaseError') {\n // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and\n // non-matching document versions with ABORTED. These errors should be retried.\n const code = (error as FirestoreError).code;\n return (\n code === 'aborted' ||\n code === 'failed-precondition' ||\n code === 'already-exists' ||\n !isPermanentError(code)\n );\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GetOptions } from '@firebase/firestore-types';\n\nimport { LoadBundleTask } from '../api/bundle';\nimport {\n CredentialChangeListener,\n CredentialsProvider\n} from '../api/credentials';\nimport { User } from '../auth/user';\nimport { LocalStore } from '../local/local_store';\nimport {\n localStoreConfigureFieldIndexes,\n localStoreDeleteAllFieldIndexes,\n localStoreExecuteQuery,\n localStoreGetNamedQuery,\n localStoreHandleUserChange,\n localStoreReadDocument,\n localStoreSetIndexAutoCreationEnabled\n} from '../local/local_store_impl';\nimport { Persistence } from '../local/persistence';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldIndex } from '../model/field_index';\nimport { Mutation } from '../model/mutation';\nimport { toByteStreamReader } from '../platform/byte_stream_reader';\nimport { newSerializer } from '../platform/serializer';\nimport { newTextEncoder } from '../platform/text_serializer';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { Datastore, invokeRunAggregationQueryRpc } from '../remote/datastore';\nimport {\n RemoteStore,\n remoteStoreDisableNetwork,\n remoteStoreEnableNetwork,\n remoteStoreHandleCredentialChange\n} from '../remote/remote_store';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { debugAssert } from '../util/assert';\nimport { AsyncObserver } from '../util/async_observer';\nimport { AsyncQueue, wrapInUserErrorIfRecoverable } from '../util/async_queue';\nimport { BundleReader, BundleReaderSync } from '../util/bundle_reader';\nimport { newBundleReader } from '../util/bundle_reader_impl';\nimport { newBundleReaderSync } from '../util/bundle_reader_sync_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 LruGcMemoryOfflineComponentProvider,\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 LruGcMemoryOfflineComponentProvider(undefined)\n );\n }\n }\n\n return client._offlineComponents!;\n}\n\nexport async 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 createBundleReaderSync(\n bundleData: string,\n serializer: JsonProtoSerializer\n): BundleReaderSync {\n return newBundleReaderSync(bundleData, 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 settings.isUsingEmulator\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 { EmulatorMockTokenOptions } from '@firebase/util';\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 emulatorOptions?: { mockUserToken?: EmulatorMockTokenOptions | string };\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 readonly isUsingEmulator: boolean;\n\n // Can be a google-auth-library or gapi client.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n credentials?: any;\n\n constructor(settings: PrivateSettings) {\n if (settings.host === undefined) {\n if (settings.ssl !== undefined) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't provide ssl option if host option is not set\"\n );\n }\n this.host = DEFAULT_HOST;\n this.ssl = DEFAULT_SSL;\n } else {\n this.host = settings.host;\n this.ssl = settings.ssl ?? DEFAULT_SSL;\n }\n this.isUsingEmulator = settings.emulatorOptions !== undefined;\n\n this.credentials = settings.credentials;\n this.ignoreUndefinedProperties = !!settings.ignoreUndefinedProperties;\n this.localCache = settings.localCache;\n\n if (settings.cacheSizeBytes === undefined) {\n this.cacheSizeBytes = LRU_DEFAULT_CACHE_SIZE_BYTES;\n } else {\n if (\n settings.cacheSizeBytes !== LRU_COLLECTION_DISABLED &&\n settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`\n );\n } else {\n this.cacheSizeBytes = settings.cacheSizeBytes;\n }\n }\n\n validateIsNotUsedTogether(\n 'experimentalForceLongPolling',\n settings.experimentalForceLongPolling,\n 'experimentalAutoDetectLongPolling',\n settings.experimentalAutoDetectLongPolling\n );\n\n this.experimentalForceLongPolling = !!settings.experimentalForceLongPolling;\n\n if (this.experimentalForceLongPolling) {\n this.experimentalAutoDetectLongPolling = false;\n } else if (settings.experimentalAutoDetectLongPolling === undefined) {\n this.experimentalAutoDetectLongPolling = DEFAULT_AUTO_DETECT_LONG_POLLING;\n } else {\n // For backwards compatibility, coerce the value to boolean even though\n // the TypeScript compiler has narrowed the type to boolean already.\n // noinspection PointlessBooleanExpressionJS\n this.experimentalAutoDetectLongPolling =\n !!settings.experimentalAutoDetectLongPolling;\n }\n\n this.experimentalLongPollingOptions = cloneLongPollingOptions(\n settings.experimentalLongPollingOptions ?? {}\n );\n validateLongPollingOptions(this.experimentalLongPollingOptions);\n\n this.useFetchStreams = !!settings.useFetchStreams;\n }\n\n isEqual(other: FirestoreSettingsImpl): boolean {\n return (\n this.host === other.host &&\n this.ssl === other.ssl &&\n this.credentials === other.credentials &&\n this.cacheSizeBytes === other.cacheSizeBytes &&\n this.experimentalForceLongPolling ===\n other.experimentalForceLongPolling &&\n this.experimentalAutoDetectLongPolling ===\n other.experimentalAutoDetectLongPolling &&\n longPollingOptionsEqual(\n this.experimentalLongPollingOptions,\n other.experimentalLongPollingOptions\n ) &&\n this.ignoreUndefinedProperties === other.ignoreUndefinedProperties &&\n this.useFetchStreams === other.useFetchStreams\n );\n }\n}\n\nfunction validateLongPollingOptions(\n options: ExperimentalLongPollingOptions\n): void {\n if (options.timeoutSeconds !== undefined) {\n if (isNaN(options.timeoutSeconds)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ` +\n `${options.timeoutSeconds} (must not be NaN)`\n );\n }\n if (options.timeoutSeconds < MIN_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(minimum allowed value is ${MIN_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n if (options.timeoutSeconds > MAX_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(maximum allowed value is ${MAX_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _getProvider,\n _removeServiceInstance,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport {\n createMockUserToken,\n deepEqual,\n EmulatorMockTokenOptions,\n getDefaultEmulatorHostnameAndPort,\n isCloudWorkstation,\n pingServer,\n updateEmulatorBanner\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 private _emulatorOptions: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {};\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 this._emulatorOptions = settings.emulatorOptions || {};\n\n if (settings.credentials !== undefined) {\n this._authCredentials = makeAuthCredentialsProvider(settings.credentials);\n }\n }\n\n _getSettings(): FirestoreSettingsImpl {\n return this._settings;\n }\n\n _getEmulatorOptions(): { mockUserToken?: EmulatorMockTokenOptions | string } {\n return this._emulatorOptions;\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 useSsl = isCloudWorkstation(host);\n const settings = firestore._getSettings();\n const existingConfig = {\n ...settings,\n emulatorOptions: firestore._getEmulatorOptions()\n };\n const newHostSetting = `${host}:${port}`;\n if (useSsl) {\n void pingServer(`https://${newHostSetting}`);\n updateEmulatorBanner('Firestore', true);\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 const newConfig = {\n ...settings,\n host: newHostSetting,\n ssl: useSsl,\n emulatorOptions: options\n };\n // No-op if the new configuration matches the current configuration. This supports SSR\n // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice.\n if (deepEqual(newConfig, existingConfig)) {\n return;\n }\n\n firestore._setSettings(newConfig);\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';\n// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_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 static _jsonSchemaVersion: string = 'firestore/documentReference/1.0';\n static _jsonSchema = {\n type: property('string', DocumentReference._jsonSchemaVersion),\n referencePath: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `DocumentReference` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: DocumentReference._jsonSchemaVersion,\n referencePath: this._key.toString()\n };\n }\n\n /**\n * Builds a `DocumentReference` instance from a JSON object created by\n * {@link DocumentReference.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json a JSON object represention of a `DocumentReference` instance\n * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(firestore: Firestore, json: object): DocumentReference;\n /**\n * Builds a `DocumentReference` instance from a JSON object created by\n * {@link DocumentReference.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json a JSON object represention of a `DocumentReference` instance\n * @param converter - Converts objects to and from Firestore.\n * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON<\n NewAppModelType = DocumentData,\n NewDbModelType extends DocumentData = DocumentData\n >(\n firestore: Firestore,\n json: object,\n converter: FirestoreDataConverter\n ): DocumentReference;\n static fromJSON<\n NewAppModelType = DocumentData,\n NewDbModelType extends DocumentData = DocumentData\n >(\n firestore: Firestore,\n json: object,\n converter?: FirestoreDataConverter\n ): DocumentReference {\n if (validateJSON(json, DocumentReference._jsonSchema)) {\n return new DocumentReference(\n firestore,\n converter ? converter : null,\n new DocumentKey(ResourcePath.fromString(json.referencePath))\n );\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Bytes from JSON.'\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(0xb815, 'AsyncQueue is already failed', {\n messageOrStack: getMessageOrStack(this.failure)\n });\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 { PartialObserver } from '../api/observer';\nimport { debugAssert } from '../util/assert';\nimport { FirestoreError } from '../util/error';\nimport { Deferred } from '../util/promise';\n\n/**\n * Represents the state of bundle loading tasks.\n *\n * Both 'Error' and 'Success' are sinking state: task will abort or complete and there will\n * be no more updates after they are reported.\n */\nexport type TaskState = 'Error' | 'Running' | 'Success';\n\n/**\n * Represents a progress update or a final state from loading bundles.\n */\nexport interface LoadBundleTaskProgress {\n /** How many documents have been loaded. */\n documentsLoaded: number;\n /** How many documents are in the bundle being loaded. */\n totalDocuments: number;\n /** How many bytes have been loaded. */\n bytesLoaded: number;\n /** How many bytes are in the bundle being loaded. */\n totalBytes: number;\n /** Current task state. */\n taskState: TaskState;\n}\n\n/**\n * Represents the task of loading a Firestore bundle. It provides progress of bundle\n * loading, as well as task completion and error events.\n *\n * The API is compatible with `Promise`.\n */\nexport class LoadBundleTask implements PromiseLike {\n private _progressObserver: PartialObserver = {};\n private _taskCompletionResolver = new Deferred();\n\n private _lastProgress: LoadBundleTaskProgress = {\n taskState: 'Running',\n totalBytes: 0,\n totalDocuments: 0,\n bytesLoaded: 0,\n documentsLoaded: 0\n };\n\n /**\n * Registers functions to listen to bundle loading progress events.\n * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur\n * each time a Firestore document is loaded from the bundle.\n * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the\n * error, and there should be no more updates after this.\n * @param complete - Called when the loading task is complete.\n */\n onProgress(\n next?: (progress: LoadBundleTaskProgress) => unknown,\n error?: (err: Error) => unknown,\n complete?: () => void\n ): void {\n this._progressObserver = {\n next,\n error,\n complete\n };\n }\n\n /**\n * Implements the `Promise.catch` interface.\n *\n * @param onRejected - Called when an error occurs during bundle loading.\n */\n catch(\n onRejected: (a: Error) => R | PromiseLike\n ): Promise {\n return this._taskCompletionResolver.promise.catch(onRejected);\n }\n\n /**\n * Implements the `Promise.then` interface.\n *\n * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update.\n * The update will always have its `taskState` set to `\"Success\"`.\n * @param onRejected - Called when an error occurs during bundle loading.\n */\n then(\n onFulfilled?: (a: LoadBundleTaskProgress) => T | PromiseLike,\n onRejected?: (a: Error) => R | PromiseLike\n ): Promise {\n return this._taskCompletionResolver.promise.then(onFulfilled, onRejected);\n }\n\n /**\n * Notifies all observers that bundle loading has completed, with a provided\n * `LoadBundleTaskProgress` object.\n *\n * @private\n */\n _completeWith(progress: LoadBundleTaskProgress): void {\n debugAssert(\n progress.taskState === 'Success',\n 'Task is not completed with Success.'\n );\n this._updateProgress(progress);\n if (this._progressObserver.complete) {\n this._progressObserver.complete();\n }\n\n this._taskCompletionResolver.resolve(progress);\n }\n\n /**\n * Notifies all observers that bundle loading has failed, with a provided\n * `Error` as the reason.\n *\n * @private\n */\n _failWith(error: FirestoreError): void {\n this._lastProgress.taskState = 'Error';\n\n if (this._progressObserver.next) {\n this._progressObserver.next(this._lastProgress);\n }\n\n if (this._progressObserver.error) {\n this._progressObserver.error(error);\n }\n\n this._taskCompletionResolver.reject(error);\n }\n\n /**\n * Notifies a progress update of loading a bundle.\n * @param progress - The new progress.\n *\n * @private\n */\n _updateProgress(progress: LoadBundleTaskProgress): void {\n debugAssert(\n this._lastProgress.taskState === 'Running',\n 'Cannot update progress on a completed or failed task'\n );\n\n this._lastProgress = progress;\n if (this._progressObserver.next) {\n this._progressObserver.next(progress);\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _getProvider,\n _removeServiceInstance,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport {\n deepEqual,\n getDefaultEmulatorHostnameAndPort,\n isCloudWorkstation,\n pingServer\n} 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 // Workaround to get cookies in Firebase Studio\n if (settings.host && isCloudWorkstation(settings.host)) {\n void pingServer(settings.host);\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 {\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 app,\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 esm, cjs, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\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 { FieldPath } from '../model/path';\n\n/**\n * Union type representing the aggregate type to be performed.\n */\nexport type AggregateType = 'count' | 'avg' | 'sum';\n\n/**\n * Represents an Aggregate to be performed over a query result set.\n */\nexport interface Aggregate {\n readonly fieldPath?: FieldPath;\n readonly alias: string;\n readonly aggregateType: AggregateType;\n}\n\n/**\n * Concrete implementation of the Aggregate type.\n */\nexport class AggregateImpl implements Aggregate {\n constructor(\n readonly alias: string,\n readonly aggregateType: AggregateType,\n readonly fieldPath?: FieldPath\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 { AggregateType } from '../core/aggregate';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\n\nimport { average, count, sum } from './aggregate';\nimport { DocumentData, Query } from './reference';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\nexport { AggregateType };\n\n/**\n * Represents an aggregation that can be performed by Firestore.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport class AggregateField {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateField';\n\n /** Indicates the aggregation operation of this AggregateField. */\n readonly aggregateType: AggregateType;\n\n /**\n * Create a new AggregateField\n * @param aggregateType Specifies the type of aggregation operation to perform.\n * @param _internalFieldPath Optionally specifies the field that is aggregated.\n * @internal\n */\n constructor(\n aggregateType: AggregateType = 'count',\n readonly _internalFieldPath?: InternalFieldPath\n ) {\n this.aggregateType = aggregateType;\n }\n}\n\n/**\n * The union of all `AggregateField` types that are supported by Firestore.\n */\nexport type AggregateFieldType =\n | ReturnType\n | ReturnType\n | ReturnType;\n\n/**\n * Specifies a set of aggregations and their aliases.\n */\nexport interface AggregateSpec {\n [field: string]: AggregateFieldType;\n}\n\n/**\n * A type whose keys are taken from an `AggregateSpec`, and whose values are the\n * result of the aggregation performed by the corresponding `AggregateField`\n * from the input `AggregateSpec`.\n */\nexport type AggregateSpecData = {\n [P in keyof T]: T[P] extends AggregateField ? U : never;\n};\n\n/**\n * The results of executing an aggregation query.\n */\nexport class AggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateQuerySnapshot';\n\n /**\n * The underlying query over which the aggregations recorded in this\n * `AggregateQuerySnapshot` were performed.\n */\n readonly query: Query;\n\n /** @hideconstructor */\n constructor(\n query: Query,\n private readonly _userDataWriter: AbstractUserDataWriter,\n private readonly _data: ApiClientObjectMap\n ) {\n this.query = query;\n }\n\n /**\n * Returns the results of the aggregations performed over the underlying\n * query.\n *\n * The keys of the returned object will be the same as those of the\n * `AggregateSpec` object specified to the aggregation method, and the values\n * will be the corresponding aggregation result.\n *\n * @returns The results of the aggregations performed over the underlying\n * query.\n */\n data(): AggregateSpecData {\n return this._userDataWriter.convertObjectMap(\n this._data\n ) as AggregateSpecData;\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// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\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 static _jsonSchemaVersion: string = 'firestore/bytes/1.0';\n static _jsonSchema = {\n type: property('string', Bytes._jsonSchemaVersion),\n bytes: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `Bytes` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: Bytes._jsonSchemaVersion,\n bytes: this.toBase64()\n };\n }\n\n /**\n * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}.\n *\n * @param json a JSON object represention of a `Bytes` instance\n * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): Bytes {\n if (validateJSON(json, Bytes._jsonSchema)) {\n return Bytes.fromBase64String(json.bytes);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Bytes from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n 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';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\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 /**\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 static _jsonSchemaVersion: string = 'firestore/geoPoint/1.0';\n static _jsonSchema = {\n type: property('string', GeoPoint._jsonSchemaVersion),\n latitude: property('number'),\n longitude: property('number')\n };\n\n /**\n * Returns a JSON-serializable representation of this `GeoPoint` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): { latitude: number; longitude: number; type: string } {\n return {\n latitude: this._lat,\n longitude: this._long,\n type: GeoPoint._jsonSchemaVersion\n };\n }\n\n /**\n * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}.\n *\n * @param json a JSON object represention of a `GeoPoint` instance\n * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): GeoPoint {\n if (validateJSON(json, GeoPoint._jsonSchema)) {\n return new GeoPoint(json.latitude, json.longitude);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating GeoPoint from JSON.'\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';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\n\n/**\n * Represents a vector type in Firestore documents.\n * Create an instance with {@link 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` values have the same raw number arrays, returns `false` otherwise.\n */\n isEqual(other: VectorValue): boolean {\n return isPrimitiveArrayEqual(this._values, other._values);\n }\n\n static _jsonSchemaVersion: string = 'firestore/vectorValue/1.0';\n static _jsonSchema = {\n type: property('string', VectorValue._jsonSchemaVersion),\n vectorValues: property('object')\n };\n\n /**\n * Returns a JSON-serializable representation of this `VectorValue` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: VectorValue._jsonSchemaVersion,\n vectorValues: this._values\n };\n }\n\n /**\n * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}.\n *\n * @param json a JSON object represention of a `VectorValue` instance.\n * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): VectorValue {\n if (validateJSON(json, VectorValue._jsonSchema)) {\n if (\n Array.isArray(json.vectorValues) &&\n json.vectorValues.every(element => typeof element === 'number')\n ) {\n return new VectorValue(json.vectorValues);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Expected 'vectorValues' field to be a number array\"\n );\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Timestamp from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData,\n FieldPath as PublicFieldPath,\n SetOptions\n} from '@firebase/firestore-types';\nimport { Compat, deepEqual, getModularInstance } from '@firebase/util';\n\nimport { ParseContext } from '../api/parse_context';\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n FieldTransform,\n Mutation,\n PatchMutation,\n Precondition,\n SetMutation\n} from '../model/mutation';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform\n} from '../model/transform_operation';\nimport {\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(0x9c4b, 'Unexpected case for UserDataSource', {\n dataSource\n });\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\nexport function 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(0xf2a2, 'Invalid value type', {\n value\n });\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 0x25d8,\n 'ReferenceValue is not valid',\n { name }\n );\n const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3));\n const key = new DocumentKey(resourcePath.popFirst(5));\n\n if (!databaseId.isEqual(expectedDatabaseId)) {\n // TODO(b/64130202): Somehow support foreign references.\n logError(\n `Document ${key} contains a document ` +\n `reference within a different database (` +\n `${databaseId.projectId}/${databaseId.database}) which is not ` +\n `supported. It will be treated as a reference in the current ` +\n `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` +\n `instead.`\n );\n }\n return key;\n }\n\n protected abstract convertReference(name: string): unknown;\n\n protected abstract convertBytes(bytes: ByteString): unknown;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData as PublicDocumentData,\n SetOptions as PublicSetOptions\n} from '@firebase/firestore-types';\nimport { getModularInstance } from '@firebase/util';\n\nimport { LimitType } from '../core/query';\nimport { DeleteMutation, Precondition } from '../model/mutation';\nimport {\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc,\n invokeRunQueryRpc\n} from '../remote/datastore';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { cast } from '../util/input_validation';\n\nimport { Bytes } from './bytes';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { validateHasExplicitOrderByForLimitToLast } from './query';\nimport {\n CollectionReference,\n doc,\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot\n} from './snapshot';\nimport {\n newUserDataReader,\n ParsedUpdateData,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converts custom model object of type T into `DocumentData` by applying the\n * converter if it exists.\n *\n * This function is used when converting user objects to `DocumentData`\n * because we want to provide the user with a more specific error message if\n * their `set()` or fails due to invalid data originating from a `toFirestore()`\n * call.\n */\nexport function applyFirestoreDataConverter(\n converter: UntypedFirestoreDataConverter | null,\n value: WithFieldValue | PartialWithFieldValue,\n options?: PublicSetOptions\n): PublicDocumentData {\n let convertedValue;\n if (converter) {\n if (options && (options.merge || options.mergeFields)) {\n // Cast to `any` in order to satisfy the union type constraint on\n // toFirestore().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n convertedValue = (converter as any).toFirestore(value, options);\n } else {\n convertedValue = converter.toFirestore(value as WithFieldValue);\n }\n } else {\n convertedValue = value as PublicDocumentData;\n }\n return convertedValue;\n}\n\nexport class LiteUserDataWriter extends AbstractUserDataWriter {\n constructor(protected firestore: Firestore) {\n super();\n }\n\n protected convertBytes(bytes: ByteString): Bytes {\n return new Bytes(bytes);\n }\n\n protected convertReference(name: string): DocumentReference {\n const key = this.convertDocumentKey(name, this.firestore._databaseId);\n return new DocumentReference(this.firestore, /* converter= */ null, key);\n }\n}\n\n/**\n * Reads the document referred to by the specified document reference.\n *\n * All documents are directly fetched from the server, even if the document was\n * previously read or modified. Recent modifications are only reflected in the\n * retrieved `DocumentSnapshot` if they have already been applied by the\n * backend. If the client is offline, the read fails. If you like to use\n * caching or see local modifications, please use the full Firestore SDK.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the current\n * document contents.\n */\nexport function getDoc(\n reference: DocumentReference\n): Promise> {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n const userDataWriter = new LiteUserDataWriter(reference.firestore);\n\n return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then(\n result => {\n hardAssert(\n result.length === 1,\n 0x3d02,\n 'Expected a single document result'\n );\n const document = result[0];\n return new DocumentSnapshot(\n reference.firestore,\n userDataWriter,\n reference._key,\n document.isFoundDocument() ? document : null,\n reference.converter\n );\n }\n );\n}\n\n/**\n * Executes the query and returns the results as a {@link QuerySnapshot}.\n *\n * All queries are executed directly by the server, even if the query was\n * previously executed. Recent modifications are only reflected in the retrieved\n * results if they have already been applied by the backend. If the client is\n * offline, the operation fails. To see previously cached result and local\n * modifications, use the full Firestore SDK.\n *\n * @param query - The `Query` to execute.\n * @returns A Promise that will be resolved with the results of the query.\n */\nexport function getDocs(\n query: Query\n): Promise> {\n query = cast>(query, Query);\n validateHasExplicitOrderByForLimitToLast(query._query);\n\n const datastore = getDatastore(query.firestore);\n const userDataWriter = new LiteUserDataWriter(query.firestore);\n return invokeRunQueryRpc(datastore, query._query).then(result => {\n const docs = result.map(\n doc =>\n new QueryDocumentSnapshot(\n query.firestore,\n userDataWriter,\n doc.key,\n doc,\n query.converter\n )\n );\n\n if (query._query.limitType === LimitType.Last) {\n // Limit to last queries reverse the orderBy constraint that was\n // specified by the user. As such, we need to reverse the order of the\n // results to return the documents in the expected order.\n docs.reverse();\n }\n\n return new QuerySnapshot(query, docs);\n });\n}\n\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\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 * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\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 convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data,\n options\n );\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'setDoc',\n reference._key,\n convertedValue,\n reference.converter !== null,\n options\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference`. The update will fail if applied to a document that does\n * not exist.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\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 * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\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 dataReader = newUserDataReader(reference.firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed: ParsedUpdateData;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData\n );\n }\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.exists(true))\n ]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * The deletion will only be reflected in document reads that occur after the\n * returned promise resolves. If the client is offline, the\n * delete fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to delete.\n * @returns A `Promise` resolved once the document has been successfully\n * deleted from the backend.\n */\nexport function deleteDoc(\n reference: DocumentReference\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n new DeleteMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend.\n */\nexport function addDoc(\n reference: CollectionReference,\n data: WithFieldValue\n): Promise> {\n reference = cast>(\n reference,\n CollectionReference\n );\n const docRef = doc(reference);\n\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data as PartialWithFieldValue\n );\n\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'addDoc',\n docRef._key,\n convertedValue,\n docRef.converter !== null,\n {}\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(docRef._key, Precondition.exists(false))\n ]).then(() => docRef);\n}\n","/**\n * @license\n * Copyright 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 { deepEqual } from '@firebase/util';\n\nimport { AggregateImpl } from '../core/aggregate';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { invokeRunAggregationQueryRpc } from '../remote/datastore';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport {\n AggregateField,\n AggregateQuerySnapshot,\n AggregateSpec\n} from './aggregate_types';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { DocumentData, Query, queryEqual } from './reference';\nimport { LiteUserDataWriter } from './reference_impl';\nimport { fieldPathFromArgument } from './user_data_reader';\n\n/**\n * Calculates the number of documents in the result set of the given query\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can\n * count the documents in cases where the result set is prohibitively large to\n * download entirely (thousands of documents).\n *\n * @param query The query whose result set size is calculated.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */\nexport function getCount(\n query: Query\n): Promise<\n AggregateQuerySnapshot<\n { count: AggregateField },\n AppModelType,\n DbModelType\n >\n> {\n const countQuerySpec: { count: AggregateField } = {\n count: count()\n };\n\n return getAggregate(query, countQuerySpec);\n}\n\n/**\n * Calculates the specified aggregations over the documents in the result\n * set of the given query without actually downloading the documents.\n *\n * Using this function to perform aggregations is efficient because only the\n * final aggregation values, not the documents' data, are downloaded. This\n * function can perform aggregations of the documents in cases where the result\n * set is prohibitively large to download entirely (thousands of documents).\n *\n * @param query The query whose result set is aggregated over.\n * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates\n * to perform over the result set. The AggregateSpec specifies aliases for each\n * aggregate, which can be used to retrieve the aggregate result.\n * @example\n * ```typescript\n * const aggregateSnapshot = await getAggregate(query, {\n * countOfDocs: count(),\n * totalHours: sum('hours'),\n * averageScore: average('score')\n * });\n *\n * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;\n * const totalHours: number = aggregateSnapshot.data().totalHours;\n * const averageScore: number | null = aggregateSnapshot.data().averageScore;\n * ```\n */\nexport function getAggregate<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n aggregateSpec: AggregateSpecType\n): Promise<\n AggregateQuerySnapshot\n> {\n const firestore = cast(query.firestore, Firestore);\n const datastore = getDatastore(firestore);\n\n const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n\n // Run the aggregation and convert the results\n return invokeRunAggregationQueryRpc(\n datastore,\n query._query,\n internalAggregates\n ).then(aggregateResult =>\n convertToAggregateQuerySnapshot(firestore, query, aggregateResult)\n );\n}\n\nfunction convertToAggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n query: Query,\n aggregateResult: ApiClientObjectMap\n): AggregateQuerySnapshot {\n const userDataWriter = new LiteUserDataWriter(firestore);\n const querySnapshot = new AggregateQuerySnapshot<\n AggregateSpecType,\n AppModelType,\n DbModelType\n >(query, userDataWriter, aggregateResult);\n return querySnapshot;\n}\n\n/**\n * Create an AggregateField object that can be used to compute the sum of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to sum across the result set.\n */\nexport function sum(field: string | FieldPath): AggregateField {\n return new AggregateField('sum', fieldPathFromArgument('sum', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the average of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to average across the result set.\n */\nexport function average(\n field: string | FieldPath\n): AggregateField {\n return new AggregateField('avg', fieldPathFromArgument('average', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the count of\n * documents in the result set of a query.\n */\nexport function count(): AggregateField {\n return new AggregateField('count');\n}\n\n/**\n * Compares two 'AggregateField` instances for equality.\n *\n * @param left Compare this AggregateField to the `right`.\n * @param right Compare this AggregateField to the `left`.\n */\nexport function aggregateFieldEqual(\n left: AggregateField,\n right: AggregateField\n): boolean {\n return (\n left instanceof AggregateField &&\n right instanceof AggregateField &&\n left.aggregateType === right.aggregateType &&\n left._internalFieldPath?.canonicalString() ===\n right._internalFieldPath?.canonicalString()\n );\n}\n\n/**\n * Compares two `AggregateQuerySnapshot` instances for equality.\n *\n * Two `AggregateQuerySnapshot` instances are considered \"equal\" if they have\n * underlying queries that compare equal, and the same data.\n *\n * @param left - The first `AggregateQuerySnapshot` to compare.\n * @param right - The second `AggregateQuerySnapshot` to compare.\n *\n * @returns `true` if the objects are \"equal\", as defined above, or `false`\n * otherwise.\n */\nexport function aggregateQuerySnapshotEqual<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n left: AggregateQuerySnapshot,\n right: AggregateQuerySnapshot\n): boolean {\n return (\n queryEqual(left.query, right.query) && deepEqual(left.data(), right.data())\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { JsonObject } from '../model/object_value';\nimport { FirestoreError } from '../util/error';\n\n/**\n * Observer/Subscribe interfaces.\n */\nexport type NextFn = (value: T) => void;\nexport type ErrorFn = (error: FirestoreError) => void;\nexport type CompleteFn = () => void;\n\n// Allow for any of the Observer methods to be undefined.\nexport interface PartialObserver {\n next?: NextFn;\n error?: ErrorFn;\n complete?: CompleteFn;\n}\n\nexport function isPartialObserver(obj: unknown): obj is PartialObserver {\n return implementsAnyMethods(obj, ['next', 'error', 'complete']);\n}\n\n/**\n * Returns true if obj is an object and contains at least one of the specified\n * methods.\n */\nfunction implementsAnyMethods(obj: unknown, methods: string[]): boolean {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n\n const object = obj as JsonObject;\n for (const method of methods) {\n if (method in object && typeof object[method] === 'function') {\n return true;\n }\n }\n return false;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { DatabaseId } from '../../../src/core/database_info';\nimport {\n LimitType,\n Query,\n queryToTarget,\n queryWithLimit\n} from '../../../src/core/query';\nimport { DocumentKey } from '../../../src/model/document_key';\nimport { newSerializer } from '../../../src/platform/serializer';\nimport { newTextEncoder } from '../../../src/platform/text_serializer';\nimport {\n BundleElement,\n LimitType as BundleLimitType\n} from '../../../src/protos/firestore_bundle_proto';\nimport * as api from '../../../src/protos/firestore_proto_api';\nimport { Value } from '../../../src/protos/firestore_proto_api';\nimport {\n JsonProtoSerializer,\n toName,\n toQueryTarget\n} from '../../../src/remote/serializer';\n\nexport const encoder = newTextEncoder();\n\nfunction lengthPrefixedString(o: {}): string {\n const str = JSON.stringify(o);\n const l = encoder.encode(str).byteLength;\n return `${l}${str}`;\n}\n\nexport class TestBundleBuilder {\n readonly elements: BundleElement[] = [];\n private serializer: JsonProtoSerializer;\n constructor(private databaseId: DatabaseId) {\n this.serializer = newSerializer(databaseId);\n }\n\n addDocumentMetadata(\n docKey: DocumentKey,\n readTime: api.Timestamp,\n exists: boolean\n ): TestBundleBuilder {\n this.elements.push({\n documentMetadata: {\n name: toName(this.serializer, docKey),\n readTime,\n exists\n }\n });\n return this;\n }\n addDocument(\n docKey: DocumentKey,\n createTime: api.Timestamp,\n updateTime: api.Timestamp,\n fields: api.ApiClientObjectMap\n ): TestBundleBuilder {\n this.elements.push({\n document: {\n name: toName(this.serializer, docKey),\n createTime,\n updateTime,\n fields\n }\n });\n return this;\n }\n\n addNamedQuery(\n name: string,\n readTime: api.Timestamp,\n query: Query\n ): TestBundleBuilder {\n let bundledLimitType: BundleLimitType | undefined = !!query.limit\n ? 'FIRST'\n : undefined;\n if (query.limitType === LimitType.Last) {\n query = queryWithLimit(query, query.limit!, LimitType.First);\n bundledLimitType = 'LAST';\n }\n const queryTarget = toQueryTarget(\n this.serializer,\n queryToTarget(query)\n ).queryTarget;\n this.elements.push({\n namedQuery: {\n name,\n readTime,\n bundledQuery: {\n parent: queryTarget.parent,\n structuredQuery: queryTarget.structuredQuery,\n limitType: bundledLimitType\n }\n }\n });\n return this;\n }\n\n getMetadataElement(\n id: string,\n createTime: api.Timestamp,\n version = 1\n ): BundleElement {\n let totalDocuments = 0;\n let totalBytes = 0;\n for (const element of this.elements) {\n if (element.documentMetadata && !element.documentMetadata.exists) {\n totalDocuments += 1;\n }\n if (element.document) {\n totalDocuments += 1;\n }\n totalBytes += encoder.encode(lengthPrefixedString(element)).byteLength;\n }\n\n return {\n metadata: {\n id,\n createTime,\n version,\n totalDocuments,\n totalBytes\n }\n };\n }\n\n build(id: string, createTime: api.Timestamp, version = 1): string {\n let result = '';\n for (const element of this.elements) {\n result += lengthPrefixedString(element);\n }\n return (\n lengthPrefixedString(this.getMetadataElement(id, createTime, version)) +\n result\n );\n }\n}\n\n// TODO(wuandy): Ideally, these should use `TestBundleBuilder` above.\nexport const meta: BundleElement = {\n metadata: {\n id: 'test-bundle',\n createTime: { seconds: 1577836805, nanos: 6 },\n version: 1,\n totalDocuments: 1,\n totalBytes: 416\n }\n};\nexport const metaString = lengthPrefixedString(meta);\n\nexport const doc1Meta: BundleElement = {\n documentMetadata: {\n name: 'projects/test-project/databases/(default)/documents/collectionId/doc1',\n readTime: { seconds: 5, nanos: 6 },\n exists: true\n }\n};\nexport const doc1MetaString = lengthPrefixedString(doc1Meta);\nexport const doc1: BundleElement = {\n document: {\n name: 'projects/test-project/databases/(default)/documents/collectionId/doc1',\n createTime: { seconds: 1, nanos: 2000000 },\n updateTime: { seconds: 3, nanos: 4000 },\n fields: { foo: { stringValue: 'value' }, bar: { integerValue: -42 } }\n }\n};\nexport const doc1String = lengthPrefixedString(doc1);\n\nexport const doc2Meta: BundleElement = {\n documentMetadata: {\n name: 'projects/test-project/databases/(default)/documents/collectionId/doc2',\n readTime: { seconds: 5, nanos: 6 },\n exists: true\n }\n};\nexport const doc2MetaString = lengthPrefixedString(doc2Meta);\nexport const doc2: BundleElement = {\n document: {\n name: 'projects/test-project/databases/(default)/documents/collectionId/doc2',\n createTime: { seconds: 1, nanos: 2000000 },\n updateTime: { seconds: 3, nanos: 4000 },\n fields: {\n foo: { stringValue: 'value1' },\n bar: { integerValue: 42 },\n emptyArray: { arrayValue: {} },\n emptyMap: { mapValue: {} }\n }\n }\n};\nexport const doc2String = lengthPrefixedString(doc2);\n\nexport const noDocMeta: BundleElement = {\n documentMetadata: {\n name: 'projects/test-project/databases/(default)/documents/collectionId/nodoc',\n readTime: { seconds: 5, nanos: 6 },\n exists: false\n }\n};\nexport const noDocMetaString = lengthPrefixedString(noDocMeta);\n\nexport const limitQuery: BundleElement = {\n namedQuery: {\n name: 'limitQuery',\n bundledQuery: {\n parent: 'projects/fireeats-97d5e/databases/(default)/documents',\n structuredQuery: {\n from: [{ collectionId: 'node_3.7.5_7Li7XoCjutvNxwD0tpo9' }],\n orderBy: [{ field: { fieldPath: 'sort' }, direction: 'DESCENDING' }],\n limit: { 'value': 1 }\n },\n limitType: 'FIRST'\n },\n readTime: { 'seconds': 1590011379, 'nanos': 191164000 }\n }\n};\nexport const limitQueryString = lengthPrefixedString(limitQuery);\nexport const limitToLastQuery: BundleElement = {\n namedQuery: {\n name: 'limitToLastQuery',\n bundledQuery: {\n parent: 'projects/fireeats-97d5e/databases/(default)/documents',\n structuredQuery: {\n from: [{ collectionId: 'node_3.7.5_7Li7XoCjutvNxwD0tpo9' }],\n orderBy: [{ field: { fieldPath: 'sort' }, direction: 'ASCENDING' }],\n limit: { 'value': 1 }\n },\n limitType: 'LAST'\n },\n readTime: { 'seconds': 1590011379, 'nanos': 543063000 }\n }\n};\nexport const limitToLastQueryString = lengthPrefixedString(limitToLastQuery);\n","/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 JsonProtoSerializer,\n fromTimestamp,\n toName,\n toQueryTarget,\n toTimestamp\n} from '../../src/remote/serializer';\nimport { encoder } from '../../test/unit/util/bundle_data';\nimport { Firestore } from '../api/database';\nimport { DatabaseId } from '../core/database_info';\nimport { Query, queryToTarget } from '../core/query';\nimport { DocumentData } from '../lite-api/reference';\nimport { Timestamp } from '../lite-api/timestamp';\nimport {\n parseObject,\n UserDataReader,\n UserDataSource\n} from '../lite-api/user_data_reader';\nimport { DocumentKey } from '../model/document_key';\nimport {\n BundledDocumentMetadata as ProtoBundledDocumentMetadata,\n BundleElement as ProtoBundleElement,\n BundleMetadata as ProtoBundleMetadata,\n NamedQuery as ProtoNamedQuery\n} from '../protos/firestore_bundle_proto';\nimport {\n Document as ProtoDocument,\n Document\n} from '../protos/firestore_proto_api';\n\nconst BUNDLE_VERSION = 1;\n\n/**\n * Builds a Firestore data bundle with results from the given document and query snapshots.\n */\nexport class BundleBuilder {\n // Resulting documents for the bundle, keyed by full document path.\n private documents: Map = new Map();\n // Named queries saved in the bundle, keyed by query name.\n private namedQueries: Map = new Map();\n\n // The latest read time among all bundled documents and queries.\n private latestReadTime = new Timestamp(0, 0);\n\n // Database identifier which is part of the serialized bundle.\n private databaseId: DatabaseId;\n\n // Tools to convert public data types into their serialized form.\n private readonly serializer: JsonProtoSerializer;\n private readonly userDataReader: UserDataReader;\n\n constructor(private firestore: Firestore, readonly bundleId: string) {\n this.databaseId = firestore._databaseId;\n\n // useProto3Json is true because the objects will be serialized to JSON string\n // before being written to the bundle buffer.\n this.serializer = new JsonProtoSerializer(\n this.databaseId,\n /*useProto3Json=*/ true\n );\n\n this.userDataReader = new UserDataReader(\n this.databaseId,\n true,\n this.serializer\n );\n }\n\n /**\n * Adds data from a DocumentSnapshot to the bundle.\n * @internal\n * @param docBundleData A DocumentSnapshotBundleData containing information from the\n * DocumentSnapshot. Note we cannot accept a DocumentSnapshot directly due to a circular\n * dependency error.\n * @param queryName The name of the QuerySnapshot if this document is part of a Query.\n */\n addBundleDocument(\n docBundleData: DocumentSnapshotBundleData,\n queryName?: string\n ): void {\n const originalDocument = this.documents.get(docBundleData.documentPath);\n const originalQueries = originalDocument?.metadata.queries;\n const docReadTime: Timestamp | undefined = docBundleData.readTime;\n const origDocReadTime: Timestamp | null = !!originalDocument?.metadata\n .readTime\n ? fromTimestamp(originalDocument.metadata.readTime)\n : null;\n\n const neitherHasReadTime: boolean = !docReadTime && origDocReadTime == null;\n const docIsNewer: boolean =\n docReadTime !== undefined &&\n (origDocReadTime == null || origDocReadTime < docReadTime);\n if (neitherHasReadTime || docIsNewer) {\n // Store document.\n this.documents.set(docBundleData.documentPath, {\n document: this.toBundleDocument(docBundleData),\n metadata: {\n name: toName(this.serializer, docBundleData.documentKey),\n readTime: !!docReadTime\n ? toTimestamp(this.serializer, docReadTime) // Convert Timestamp to proto format.\n : undefined,\n exists: docBundleData.documentExists\n }\n });\n }\n if (docReadTime && docReadTime > this.latestReadTime) {\n this.latestReadTime = docReadTime;\n }\n // Update `queries` to include both original and `queryName`.\n if (queryName) {\n const newDocument = this.documents.get(docBundleData.documentPath)!;\n newDocument.metadata.queries = originalQueries || [];\n newDocument.metadata.queries!.push(queryName);\n }\n }\n\n /**\n * Adds data from a QuerySnapshot to the bundle.\n * @internal\n * @param docBundleData A QuerySnapshotBundleData containing information from the\n * QuerySnapshot. Note we cannot accept a QuerySnapshot directly due to a circular\n * dependency error.\n */\n addBundleQuery(queryBundleData: QuerySnapshotBundleData): void {\n if (this.namedQueries.has(queryBundleData.name)) {\n throw new Error(`Query name conflict: ${name} has already been added.`);\n }\n let latestReadTime = new Timestamp(0, 0);\n for (const docBundleData of queryBundleData.docBundleDataArray) {\n this.addBundleDocument(docBundleData, queryBundleData.name);\n if (docBundleData.readTime && docBundleData.readTime > latestReadTime) {\n latestReadTime = docBundleData.readTime;\n }\n }\n const queryTarget = toQueryTarget(\n this.serializer,\n queryToTarget(queryBundleData.query)\n );\n const bundledQuery = {\n parent: queryBundleData.parent,\n structuredQuery: queryTarget.queryTarget.structuredQuery\n };\n this.namedQueries.set(queryBundleData.name, {\n name: queryBundleData.name,\n bundledQuery,\n readTime: toTimestamp(this.serializer, latestReadTime)\n });\n }\n\n /**\n * Convert data from a DocumentSnapshot into the serialized form within a bundle.\n * @private\n * @internal\n * @param docBundleData a DocumentSnapshotBundleData containing the data required to\n * serialize a document.\n */\n private toBundleDocument(\n docBundleData: DocumentSnapshotBundleData\n ): ProtoDocument {\n // a parse context is typically used for validating and parsing user data, but in this\n // case we are using it internally to convert DocumentData to Proto3 JSON\n const context = this.userDataReader.createContext(\n UserDataSource.ArrayArgument,\n 'internal toBundledDocument'\n );\n const proto3Fields = parseObject(docBundleData.documentData, context);\n\n return {\n name: toName(this.serializer, docBundleData.documentKey),\n fields: proto3Fields.mapValue.fields,\n updateTime: toTimestamp(this.serializer, docBundleData.versionTime),\n createTime: toTimestamp(this.serializer, docBundleData.createdTime)\n };\n }\n\n /**\n * Converts a IBundleElement to a Buffer whose content is the length prefixed JSON representation\n * of the element.\n * @private\n * @internal\n * @param bundleElement A ProtoBundleElement that is expected to be Proto3 JSON compatible.\n */\n private lengthPrefixedString(bundleElement: ProtoBundleElement): string {\n const str = JSON.stringify(bundleElement);\n // TODO: it's not ideal to have to re-encode all of these strings multiple times\n // It may be more performant to return a UInt8Array that is concatenated to other\n // UInt8Arrays instead of returning and concatenating strings and then\n // converting the full string to UInt8Array.\n const l = encoder.encode(str).byteLength;\n return `${l}${str}`;\n }\n\n /**\n * Construct a serialized string containing document and query information that has previously\n * been added to the BundleBuilder through the addBundleDocument and addBundleQuery methods.\n * @internal\n */\n build(): string {\n let bundleString = '';\n\n for (const namedQuery of this.namedQueries.values()) {\n bundleString += this.lengthPrefixedString({ namedQuery });\n }\n\n for (const bundledDocument of this.documents.values()) {\n const documentMetadata: ProtoBundledDocumentMetadata =\n bundledDocument.metadata;\n\n bundleString += this.lengthPrefixedString({ documentMetadata });\n // Write to the bundle if document exists.\n const document = bundledDocument.document;\n if (document) {\n bundleString += this.lengthPrefixedString({ document });\n }\n }\n\n const metadata: ProtoBundleMetadata = {\n id: this.bundleId,\n createTime: toTimestamp(this.serializer, this.latestReadTime),\n version: BUNDLE_VERSION,\n totalDocuments: this.documents.size,\n // TODO: it's not ideal to have to re-encode all of these strings multiple times\n totalBytes: encoder.encode(bundleString).length\n };\n // Prepends the metadata element to the bundleBuffer: `bundleBuffer` is the second argument to `Buffer.concat`.\n bundleString = this.lengthPrefixedString({ metadata }) + bundleString;\n\n return bundleString;\n }\n}\n\n/**\n * Interface for an object that contains data required to bundle a DocumentSnapshot.\n * @internal\n */\nexport interface DocumentSnapshotBundleData {\n documentData: DocumentData;\n documentKey: DocumentKey;\n documentPath: string;\n documentExists: boolean;\n createdTime: Timestamp;\n readTime?: Timestamp;\n versionTime: Timestamp;\n}\n\n/**\n * Interface for an object that contains data required to bundle a QuerySnapshot.\n * @internal\n */\nexport interface QuerySnapshotBundleData {\n name: string;\n query: Query;\n parent: string;\n docBundleDataArray: DocumentSnapshotBundleData[];\n}\n\n/**\n * Convenient class to hold both the metadata and the actual content of a document to be bundled.\n * @private\n * @internal\n */\nclass BundledDocument {\n constructor(\n readonly metadata: ProtoBundledDocumentMetadata,\n readonly document?: Document\n ) {}\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 build JSON bundle implementations. */\nimport { Firestore } from '../../api/database';\nimport { Query } from '../../core/query';\nimport { DocumentData } from '../../lite-api/reference';\nimport { Document } from '../../model/document';\nimport {\n BundleBuilder,\n DocumentSnapshotBundleData,\n QuerySnapshotBundleData\n} from '../../util/bundle_builder_impl';\nimport { AutoId } from '../../util/misc';\n\nexport function buildDocumentSnapshotJsonBundle(\n db: Firestore,\n document: Document,\n docData: DocumentData,\n path: string\n): string {\n const builder: BundleBuilder = new BundleBuilder(db, AutoId.newId());\n builder.addBundleDocument(\n documentToDocumentSnapshotBundleData(path, docData, document)\n );\n return builder.build();\n}\n\nexport function buildQuerySnapshotJsonBundle(\n db: Firestore,\n query: Query,\n bundleName: string,\n parent: string,\n paths: string[],\n docs: Document[],\n documentData: DocumentData[]\n): string {\n const docBundleDataArray: DocumentSnapshotBundleData[] = [];\n for (let i = 0; i < docs.length; i++) {\n docBundleDataArray.push(\n documentToDocumentSnapshotBundleData(paths[i], documentData[i], docs[i])\n );\n }\n const bundleData: QuerySnapshotBundleData = {\n name: bundleName,\n query,\n parent,\n docBundleDataArray\n };\n const builder: BundleBuilder = new BundleBuilder(db, bundleName);\n builder.addBundleQuery(bundleData);\n return builder.build();\n}\n\n// Formats Document data for bundling a DocumentSnapshot.\nfunction documentToDocumentSnapshotBundleData(\n path: string,\n documentData: DocumentData,\n document: Document\n): DocumentSnapshotBundleData {\n return {\n documentData,\n documentKey: document.mutableCopy().key,\n documentPath: path,\n documentExists: true,\n createdTime: document.createTime.toTimestamp(),\n readTime: document.readTime.toTimestamp(),\n versionTime: document.version.toTimestamp()\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 { BundleLoader } from '../core/bundle_impl';\nimport { createBundleReaderSync } from '../core/firestore_client';\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 { LiteUserDataWriter } from '../lite-api/reference_impl';\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 { fromBundledQuery } from '../local/local_serializer';\nimport { documentKeySet } from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { DocumentSet } from '../model/document_set';\nimport { ResourcePath } from '../model/path';\nimport { newSerializer } from '../platform/serializer';\nimport {\n buildQuerySnapshotJsonBundle,\n buildDocumentSnapshotJsonBundle\n} from '../platform/snapshot_to_json';\nimport { fromDocument } from '../remote/serializer';\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\nimport { AutoId } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { SnapshotListenOptions } from './reference_impl';\n\nconst NOT_SUPPORTED = 'NOT SUPPORTED';\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 static _jsonSchemaVersion: string = 'firestore/documentSnapshot/1.0';\n static _jsonSchema = {\n type: property('string', DocumentSnapshot._jsonSchemaVersion),\n bundleSource: property('string', 'DocumentSnapshot'),\n bundleName: property('string'),\n bundle: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `DocumentSnapshot` instance.\n *\n * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this\n * `DocumentSnapshot` has pending writes.\n */\n toJSON(): object {\n if (this.metadata.hasPendingWrites) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'DocumentSnapshot.toJSON() attempted to serialize a document with pending writes. ' +\n 'Await waitForPendingWrites() before invoking toJSON().'\n );\n }\n const document = this._document;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: any = {};\n result['type'] = DocumentSnapshot._jsonSchemaVersion;\n result['bundle'] = '';\n result['bundleSource'] = 'DocumentSnapshot';\n result['bundleName'] = this._key.toString();\n\n if (\n !document ||\n !document.isValidDocument() ||\n !document.isFoundDocument()\n ) {\n return result;\n }\n const documentData = this._userDataWriter.convertObjectMap(\n document.data.value.mapValue.fields,\n 'previous'\n );\n result['bundle'] = buildDocumentSnapshotJsonBundle(\n this._firestore,\n document,\n documentData,\n this.ref.path\n );\n return result;\n }\n}\n\n/**\n * Builds a `DocumentSnapshot` instance from a JSON object created by\n * {@link DocumentSnapshot.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json - a JSON object represention of a `DocumentSnapshot` instance.\n * @returns an instance of {@link DocumentSnapshot} if the JSON object could be\n * parsed. Throws a {@link FirestoreError} if an error occurs.\n */\nexport function documentSnapshotFromJSON(\n db: Firestore,\n json: object\n): DocumentSnapshot;\n/**\n * Builds a `DocumentSnapshot` instance from a JSON object created by\n * {@link DocumentSnapshot.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json - a JSON object represention of a `DocumentSnapshot` instance.\n * @param converter - Converts objects to and from Firestore.\n * @returns an instance of {@link DocumentSnapshot} if the JSON object could be\n * parsed. Throws a {@link FirestoreError} if an error occurs.\n */\nexport function documentSnapshotFromJSON<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n>(\n db: Firestore,\n json: object,\n converter: FirestoreDataConverter\n): DocumentSnapshot;\nexport function documentSnapshotFromJSON<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n>(\n db: Firestore,\n json: object,\n converter?: FirestoreDataConverter\n): DocumentSnapshot {\n if (validateJSON(json, DocumentSnapshot._jsonSchema)) {\n if (json.bundle === NOT_SUPPORTED) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'The provided JSON object was created in a client environment, which is not supported.'\n );\n }\n // Parse the bundle data.\n const serializer = newSerializer(db._databaseId);\n const bundleReader = createBundleReaderSync(json.bundle, serializer);\n const elements = bundleReader.getElements();\n const bundleLoader: BundleLoader = new BundleLoader(\n bundleReader.getMetadata(),\n serializer\n );\n for (const element of elements) {\n bundleLoader.addSizedElement(element);\n }\n\n // Ensure that we have the correct number of documents in the bundle.\n const bundledDocuments = bundleLoader.documents;\n if (bundledDocuments.length !== 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Expected bundle data to contain 1 document, but it contains ${bundledDocuments.length} documents.`\n );\n }\n\n // Build out the internal document data.\n const document = fromDocument(serializer, bundledDocuments[0].document!);\n const documentKey = new DocumentKey(\n ResourcePath.fromString(json.bundleName)\n );\n\n // Return the external facing DocumentSnapshot.\n return new DocumentSnapshot(\n db,\n new LiteUserDataWriter(db),\n documentKey,\n document,\n new SnapshotMetadata(\n /* hasPendingWrites= */ false,\n /* fromCache= */ false\n ),\n converter ? converter : null\n );\n }\n throw new FirestoreError(\n Code.INTERNAL,\n 'Unexpected error creating DocumentSnapshot from JSON.'\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 static _jsonSchemaVersion: string = 'firestore/querySnapshot/1.0';\n static _jsonSchema = {\n type: property('string', QuerySnapshot._jsonSchemaVersion),\n bundleSource: property('string', 'QuerySnapshot'),\n bundleName: property('string'),\n bundle: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `QuerySnapshot` instance.\n *\n * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this\n * `QuerySnapshot` has pending writes.\n */\n toJSON(): object {\n if (this.metadata.hasPendingWrites) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'QuerySnapshot.toJSON() attempted to serialize a document with pending writes. ' +\n 'Await waitForPendingWrites() before invoking toJSON().'\n );\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: any = {};\n result['type'] = QuerySnapshot._jsonSchemaVersion;\n result['bundleSource'] = 'QuerySnapshot';\n result['bundleName'] = AutoId.newId();\n\n const databaseId = this._firestore._databaseId.database;\n const projectId = this._firestore._databaseId.projectId;\n const parent = `projects/${projectId}/databases/${databaseId}/documents`;\n const documents: Document[] = [];\n const documentData: DocumentData[] = [];\n const paths: string[] = [];\n\n this.docs.forEach(doc => {\n if (doc._document === null) {\n return;\n }\n documents.push(doc._document);\n documentData.push(\n this._userDataWriter.convertObjectMap(\n doc._document.data.value.mapValue.fields,\n 'previous'\n )\n );\n paths.push(doc.ref.path);\n });\n result['bundle'] = buildQuerySnapshotJsonBundle(\n this._firestore,\n this.query._query,\n result['bundleName'],\n parent,\n paths,\n documents,\n documentData\n );\n return result;\n }\n}\n\n/**\n * Builds a `QuerySnapshot` instance from a JSON object created by\n * {@link QuerySnapshot.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json - a JSON object represention of a `QuerySnapshot` instance.\n * @returns an instance of {@link QuerySnapshot} if the JSON object could be\n * parsed. Throws a {@link FirestoreError} if an error occurs.\n */\nexport function querySnapshotFromJSON(\n db: Firestore,\n json: object\n): QuerySnapshot;\n/**\n * Builds a `QuerySnapshot` instance from a JSON object created by\n * {@link QuerySnapshot.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json - a JSON object represention of a `QuerySnapshot` instance.\n * @param converter - Converts objects to and from Firestore.\n * @returns an instance of {@link QuerySnapshot} if the JSON object could be\n * parsed. Throws a {@link FirestoreError} if an error occurs.\n */\nexport function querySnapshotFromJSON<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n>(\n db: Firestore,\n json: object,\n converter: FirestoreDataConverter\n): QuerySnapshot;\nexport function querySnapshotFromJSON<\n AppModelType,\n DbModelType extends DocumentData\n>(\n db: Firestore,\n json: object,\n converter?: FirestoreDataConverter\n): QuerySnapshot {\n if (validateJSON(json, QuerySnapshot._jsonSchema)) {\n if (json.bundle === NOT_SUPPORTED) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'The provided JSON object was created in a client environment, which is not supported.'\n );\n }\n // Parse the bundle data.\n const serializer = newSerializer(db._databaseId);\n const bundleReader = createBundleReaderSync(json.bundle, serializer);\n const elements = bundleReader.getElements();\n const bundleLoader: BundleLoader = new BundleLoader(\n bundleReader.getMetadata(),\n serializer\n );\n for (const element of elements) {\n bundleLoader.addSizedElement(element);\n }\n\n if (bundleLoader.queries.length !== 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Snapshot data expected 1 query but found ${bundleLoader.queries.length} queries.`\n );\n }\n\n // Create an internal Query object from the named query in the bundle.\n const query = fromBundledQuery(bundleLoader.queries[0].bundledQuery!);\n\n // Construct the arrays of document data for the query.\n const bundledDocuments = bundleLoader.documents;\n let documentSet = new DocumentSet();\n bundledDocuments.map(bundledDocument => {\n const document = fromDocument(serializer, bundledDocument.document!);\n documentSet = documentSet.add(document);\n });\n // Create a view snapshot of the query and documents.\n const viewSnapshot = ViewSnapshot.fromInitialDocuments(\n query,\n documentSet,\n documentKeySet() /* Zero mutated keys signifies no pending writes. */,\n /* fromCache= */ false,\n /* hasCachedResults= */ false\n );\n\n // Create an external Query object, required to construct the QuerySnapshot.\n const externalQuery = new Query(\n db,\n converter ? converter : null,\n query\n );\n\n // Return a new QuerySnapshot with all of the collected data.\n return new QuerySnapshot(\n db,\n new LiteUserDataWriter(db),\n externalQuery,\n viewSnapshot\n );\n }\n throw new FirestoreError(\n Code.INTERNAL,\n 'Unexpected error creating QuerySnapshot from JSON.'\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(0xf03d, '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 { loadBundle, namedQuery } from '../api/database';\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 { DocumentKey } from '../model/document_key';\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { debugAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport {\n DocumentSnapshot,\n FirestoreDataConverter,\n QuerySnapshot,\n SnapshotMetadata\n} 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @returns An unsubscribe function that can be called to cancel 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @returns An unsubscribe function that can be called to cancel 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The\n * listener can be cancelled by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The\n * listener can be cancelled by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The\n * listener can be cancelled by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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` is available.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @returns An unsubscribe function that can be called to cancel 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The\n * listener can be cancelled by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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` is available.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @returns An unsubscribe function that can be called to cancel 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 // onSnapshot for Query or Document.\n reference = getModularInstance(reference);\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 }\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 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/**\n * Attaches a listener for `QuerySnapshot` events based on data generated by invoking\n * {@link QuerySnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks or\n * pass a single observer 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 never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}.\n * @param onNext - A callback to be called every time a new `QuerySnapshot` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n onNext: (snapshot: QuerySnapshot) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void,\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking\n * {@link DocumentSnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or\n * pass a single observer 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 never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}.\n * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are\n * never ending.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n onNext: (snapshot: DocumentSnapshot) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void,\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events based on data generated by invoking\n * {@link QuerySnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or\n * pass a single observer 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 never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param onNext - A callback to be called every time a new `QuerySnapshot` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n options: SnapshotListenOptions,\n onNext: (snapshot: QuerySnapshot) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void,\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking\n * {@link DocumentSnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks\n * or pass a single observer object with `next` and `error` callbacks. The listener can be cancelled\n * by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n options: SnapshotListenOptions,\n onNext: (snapshot: DocumentSnapshot) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void,\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events based on QuerySnapshot data generated by invoking\n * {@link QuerySnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or\n * pass a single observer 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 never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n observer: {\n next: (snapshot: QuerySnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n },\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking\n * {@link DocumentSnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks\n * or pass a single observer object with `next` and `error` callbacks. The listener can be cancelled\n * by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n observer: {\n next: (snapshot: DocumentSnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n },\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events based on QuerySnapshot data generated by invoking\n * {@link QuerySnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks or\n * pass a single observer 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 never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n options: SnapshotListenOptions,\n observer: {\n next: (snapshot: QuerySnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n },\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events based on QuerySnapshot data generated by\n * invoking {@link DocumentSnapshot.toJSON} You may either pass individual `onNext` and `onError`\n * callbacks or pass a single observer object with `next` and `error` callbacks. The listener can be\n * cancelled by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n options: SnapshotListenOptions,\n observer: {\n next: (snapshot: DocumentSnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n },\n converter?: FirestoreDataConverter\n): Unsubscribe;\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(reference: Firestore, snapshotJson: object, ...args: unknown[]): Unsubscribe {\n const db = getModularInstance(reference);\n const json = normalizeSnapshotJsonFields(snapshotJson);\n if (json.error) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, json.error);\n }\n let curArg = 0;\n let options: SnapshotListenOptions | undefined = undefined;\n if (typeof args[curArg] === 'object' && !isPartialObserver(args[curArg])) {\n options = args[curArg++] as SnapshotListenOptions;\n }\n\n if (json.bundleSource === 'QuerySnapshot') {\n let observer: {\n next: (snapshot: QuerySnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n } | null = null;\n if (typeof args[curArg] === 'object' && isPartialObserver(args[curArg])) {\n const userObserver = args[curArg++] as PartialObserver<\n QuerySnapshot\n >;\n observer = {\n next: userObserver.next!,\n error: userObserver.error,\n complete: userObserver.complete\n };\n } else {\n observer = {\n next: args[curArg++] as (\n snapshot: QuerySnapshot\n ) => void,\n error: args[curArg++] as (error: FirestoreError) => void,\n complete: args[curArg++] as () => void\n };\n }\n return onSnapshotQuerySnapshotBundle(\n db,\n json,\n options,\n observer!,\n args[curArg] as FirestoreDataConverter\n );\n } else if (json.bundleSource === 'DocumentSnapshot') {\n let observer: {\n next: (snapshot: DocumentSnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n } | null = null;\n if (typeof args[curArg] === 'object' && isPartialObserver(args[curArg])) {\n const userObserver = args[curArg++] as PartialObserver<\n DocumentSnapshot\n >;\n observer = {\n next: userObserver.next!,\n error: userObserver.error,\n complete: userObserver.complete\n };\n } else {\n observer = {\n next: args[curArg++] as (\n snapshot: DocumentSnapshot\n ) => void,\n error: args[curArg++] as (error: FirestoreError) => void,\n complete: args[curArg++] as () => void\n };\n }\n return onSnapshotDocumentSnapshotBundle(\n db,\n json,\n options,\n observer!,\n args[curArg] as FirestoreDataConverter\n );\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `unsupported bundle source: ${json.bundleSource}`\n );\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/**\n * Ensures the data required to construct an {@link onSnapshot} listener exist in a `snapshotJson`\n * object that originates from {@link DocumentSnapshot.toJSON} or {@link Querysnapshot.toJSON}. The\n * data is normalized into a typed object.\n *\n * @param snapshotJson - The JSON object that the app provided to {@link onSnapshot}.\n * @returns A normalized object that contains all of the required bundle JSON fields. If\n * {@link snapshotJson} doesn't contain the required fields, or if the fields exist as empty\n * strings, then the {@link snapshotJson.error} field will be a non empty string.\n *\n * @internal\n */\nfunction normalizeSnapshotJsonFields(snapshotJson: object): {\n bundle: string;\n bundleName: string;\n bundleSource: string;\n error?: string;\n} {\n const result: {\n bundle: string;\n bundleName: string;\n bundleSource: string;\n error?: string;\n } = {\n bundle: '',\n bundleName: '',\n bundleSource: ''\n };\n const requiredKeys = ['bundle', 'bundleName', 'bundleSource'];\n for (const key of requiredKeys) {\n if (!(key in snapshotJson)) {\n result.error = `snapshotJson missing required field: ${key}`;\n break;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const value = (snapshotJson as any)[key];\n if (typeof value !== 'string') {\n result.error = `snapshotJson field '${key}' must be a string.`;\n break;\n }\n if (value.length === 0) {\n result.error = `snapshotJson field '${key}' cannot be an empty string.`;\n break;\n }\n if (key === 'bundle') {\n result.bundle = value;\n } else if (key === 'bundleName') {\n result.bundleName = value;\n } else if (key === 'bundleSource') {\n result.bundleSource = value;\n }\n }\n return result;\n}\n\n/**\n * Loads the bundle in a separate task and then invokes {@link onSnapshot} with a\n * {@link DocumentReference} for the document in the bundle.\n *\n * @param firestore - The {@link Firestore} instance for the {@link onSnapshot} operation request.\n * @param json - The JSON bundle to load, produced by {@link DocumentSnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot\n * listener.\n *\n * @internal\n */\nfunction onSnapshotDocumentSnapshotBundle<\n AppModelType,\n DbModelType extends DocumentData\n>(\n db: Firestore,\n json: { bundle: string; bundleName: string; bundleSource: string },\n options: SnapshotListenOptions | undefined,\n observer: {\n next: (snapshot: DocumentSnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n },\n converter?: FirestoreDataConverter\n): Unsubscribe {\n let unsubscribed: boolean = false;\n let internalUnsubscribe: Unsubscribe | undefined;\n const loadTask = loadBundle(db, json.bundle);\n loadTask\n .then(() => {\n if (!unsubscribed) {\n const docReference = new DocumentReference(\n db,\n converter ? converter : null,\n DocumentKey.fromPath(json.bundleName)\n );\n internalUnsubscribe = onSnapshot(\n docReference as DocumentReference,\n options ? options : {},\n observer\n );\n }\n })\n .catch(e => {\n if (observer.error) {\n observer.error(e);\n }\n return () => {};\n });\n return () => {\n if (unsubscribed) {\n return;\n }\n unsubscribed = true;\n if (internalUnsubscribe) {\n internalUnsubscribe();\n }\n };\n}\n\n/**\n * Loads the bundle in a separate task and then invokes {@link onSnapshot} with a\n * {@link Query} that represents the Query in the bundle.\n *\n * @param firestore - The {@link Firestore} instance for the {@link onSnapshot} operation request.\n * @param json - The JSON bundle to load, produced by {@link QuerySnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot\n * listener.\n *\n * @internal\n */\nfunction onSnapshotQuerySnapshotBundle<\n AppModelType,\n DbModelType extends DocumentData\n>(\n db: Firestore,\n json: { bundle: string; bundleName: string; bundleSource: string },\n options: SnapshotListenOptions | undefined,\n observer: {\n next: (snapshot: QuerySnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n },\n converter?: FirestoreDataConverter\n): Unsubscribe {\n let unsubscribed: boolean = false;\n let internalUnsubscribe: Unsubscribe | undefined;\n const loadTask = loadBundle(db, json.bundle);\n loadTask\n .then(() => namedQuery(db, json.bundleName))\n .then(query => {\n if (query && !unsubscribed) {\n const realQuery: Query = (query as Query)!;\n if (converter) {\n realQuery.withConverter(converter);\n }\n internalUnsubscribe = onSnapshot(\n query as Query,\n options ? options : {},\n observer\n );\n }\n })\n .catch(e => {\n if (observer.error) {\n observer.error(e);\n }\n return () => {};\n });\n return () => {\n if (unsubscribed) {\n return;\n }\n unsubscribed = true;\n if (internalUnsubscribe) {\n internalUnsubscribe();\n }\n };\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AggregateField, AggregateSpec, DocumentData, Query } from '../api';\nimport { AggregateImpl } from '../core/aggregate';\nimport { firestoreClientRunAggregateQuery } from '../core/firestore_client';\nimport { count } from '../lite-api/aggregate';\nimport { AggregateQuerySnapshot } from '../lite-api/aggregate_types';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport { ExpUserDataWriter } from './reference_impl';\n\nexport {\n aggregateQuerySnapshotEqual,\n count,\n sum,\n average,\n aggregateFieldEqual\n} from '../lite-api/aggregate';\n\n/**\n * Calculates the number of documents in the result set of the given query\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can\n * count the documents in cases where the result set is prohibitively large to\n * download entirely (thousands of documents).\n *\n * The result received from the server is presented, unaltered, without\n * considering any local state. That is, documents in the local cache are not\n * taken into consideration, neither are local modifications not yet\n * synchronized with the server. Previously-downloaded results, if any, are not\n * used. Every invocation of this function necessarily involves a round trip to\n * the server.\n *\n * @param query The query whose result set size is calculated.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */\nexport function getCountFromServer<\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query\n): Promise<\n AggregateQuerySnapshot<\n { count: AggregateField },\n AppModelType,\n DbModelType\n >\n> {\n const countQuerySpec: { count: AggregateField } = {\n count: count()\n };\n\n return getAggregateFromServer(query, countQuerySpec);\n}\n\n/**\n * Calculates the specified aggregations over the documents in the result\n * set of the given query without actually downloading the documents.\n *\n * Using this function to perform aggregations is efficient because only the\n * final aggregation values, not the documents' data, are downloaded. This\n * function can perform aggregations of the documents in cases where the result\n * set is prohibitively large to download entirely (thousands of documents).\n *\n * The result received from the server is presented, unaltered, without\n * considering any local state. That is, documents in the local cache are not\n * taken into consideration, neither are local modifications not yet\n * synchronized with the server. Previously-downloaded results, if any, are not\n * used. Every invocation of this function necessarily involves a round trip to\n * the server.\n *\n * @param query The query whose result set is aggregated over.\n * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates\n * to perform over the result set. The AggregateSpec specifies aliases for each\n * aggregate, which can be used to retrieve the aggregate result.\n * @example\n * ```typescript\n * const aggregateSnapshot = await getAggregateFromServer(query, {\n * countOfDocs: count(),\n * totalHours: sum('hours'),\n * averageScore: average('score')\n * });\n *\n * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;\n * const totalHours: number = aggregateSnapshot.data().totalHours;\n * const averageScore: number | null = aggregateSnapshot.data().averageScore;\n * ```\n */\nexport function getAggregateFromServer<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n aggregateSpec: AggregateSpecType\n): Promise<\n AggregateQuerySnapshot\n> {\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n\n const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n\n // Run the aggregation and convert the results\n return firestoreClientRunAggregateQuery(\n client,\n query._query,\n internalAggregates\n ).then(aggregateResult =>\n convertToAggregateQuerySnapshot(firestore, query, aggregateResult)\n );\n}\n\n/**\n * Converts the core aggregation result to an `AggregateQuerySnapshot`\n * that can be returned to the consumer.\n * @param query\n * @param aggregateResult Core aggregation result\n * @internal\n */\nfunction convertToAggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n query: Query,\n aggregateResult: ApiClientObjectMap\n): AggregateQuerySnapshot {\n const userDataWriter = new ExpUserDataWriter(firestore);\n const querySnapshot = new AggregateQuerySnapshot<\n AggregateSpecType,\n AppModelType,\n DbModelType\n >(query, userDataWriter, aggregateResult);\n return querySnapshot;\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 IndexedDbOfflineComponentProvider,\n LruGcMemoryOfflineComponentProvider,\n MemoryOfflineComponentProvider,\n MultiTabOfflineComponentProvider,\n OfflineComponentProviderFactory,\n OnlineComponentProviderFactory,\n OnlineComponentProvider\n} from '../core/component_provider';\n\n/* eslint @typescript-eslint/consistent-type-definitions: [\"error\", \"type\"] */\n/**\n * Provides an in-memory cache to the SDK. This is the default cache unless explicitly\n * configured otherwise.\n *\n * To use, create an instance using the factory function {@link memoryLocalCache()}, then\n * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using\n * the settings object.\n */\nexport type MemoryLocalCache = {\n kind: 'memory';\n /**\n * @internal\n */\n _onlineComponentProvider: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n};\n\nclass MemoryLocalCacheImpl implements MemoryLocalCache {\n kind: 'memory' = 'memory';\n /**\n * @internal\n */\n _onlineComponentProvider: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n\n constructor(settings?: MemoryCacheSettings) {\n this._onlineComponentProvider = OnlineComponentProvider.provider;\n if (settings?.garbageCollector) {\n this._offlineComponentProvider =\n settings.garbageCollector._offlineComponentProvider;\n } else {\n this._offlineComponentProvider = {\n build: () => new LruGcMemoryOfflineComponentProvider(undefined)\n };\n }\n }\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n}\n\n/**\n * Provides a persistent cache backed by IndexedDb to the SDK.\n *\n * To use, create an instance using the factory function {@link persistentLocalCache()}, then\n * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using\n * the settings object.\n */\nexport type PersistentLocalCache = {\n kind: 'persistent';\n /**\n * @internal\n */\n _onlineComponentProvider: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n};\n\nclass PersistentLocalCacheImpl implements PersistentLocalCache {\n kind: 'persistent' = 'persistent';\n /**\n * @internal\n */\n _onlineComponentProvider: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n\n constructor(settings: PersistentCacheSettings | undefined) {\n let tabManager: PersistentTabManager;\n if (settings?.tabManager) {\n settings.tabManager._initialize(settings);\n tabManager = settings.tabManager;\n } else {\n tabManager = persistentSingleTabManager(undefined);\n tabManager._initialize(settings);\n }\n this._onlineComponentProvider = tabManager._onlineComponentProvider!;\n this._offlineComponentProvider = tabManager._offlineComponentProvider!;\n }\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n}\n\n/**\n * Union type from all supported SDK cache layer.\n */\nexport type FirestoreLocalCache = MemoryLocalCache | PersistentLocalCache;\n\n/**\n * Union type from all support garbage collectors for memory local cache.\n */\nexport type MemoryGarbageCollector =\n | MemoryEagerGarbageCollector\n | MemoryLruGarbageCollector;\n\n/**\n * A garbage collector deletes documents whenever they are not part of any\n * active queries, and have no local mutations attached to them.\n *\n * This collector tries to ensure lowest memory footprints from the SDK,\n * at the risk of documents not being cached for offline queries or for\n * direct queries to the cache.\n *\n * Use factory function {@link memoryEagerGarbageCollector()} to create an\n * instance of this collector.\n */\nexport type MemoryEagerGarbageCollector = {\n kind: 'memoryEager';\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n};\n\n/**\n * A garbage collector deletes Least-Recently-Used documents in multiple\n * batches.\n *\n * This collector is configured with a target size, and will only perform\n * collection when the cached documents exceed the target size. It avoids\n * querying backend repeated for the same query or document, at the risk\n * of having a larger memory footprint.\n *\n * Use factory function {@link memoryLruGarbageCollector()} to create a\n * instance of this collector.\n */\nexport type MemoryLruGarbageCollector = {\n kind: 'memoryLru';\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n};\n\nclass MemoryEagerGarbageCollectorImpl implements MemoryEagerGarbageCollector {\n kind: 'memoryEager' = 'memoryEager';\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n\n constructor() {\n this._offlineComponentProvider = MemoryOfflineComponentProvider.provider;\n }\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n}\n\nclass MemoryLruGarbageCollectorImpl implements MemoryLruGarbageCollector {\n kind: 'memoryLru' = 'memoryLru';\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n\n constructor(cacheSize?: number) {\n this._offlineComponentProvider = {\n build: () => new LruGcMemoryOfflineComponentProvider(cacheSize)\n };\n }\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n}\n\n/**\n * Creates an instance of `MemoryEagerGarbageCollector`. This is also the\n * default garbage collector unless it is explicitly specified otherwise.\n */\nexport function memoryEagerGarbageCollector(): MemoryEagerGarbageCollector {\n return new MemoryEagerGarbageCollectorImpl();\n}\n\n/**\n * Creates an instance of `MemoryLruGarbageCollector`.\n *\n * A target size can be specified as part of the setting parameter. The\n * collector will start deleting documents once the cache size exceeds\n * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes).\n */\nexport function memoryLruGarbageCollector(settings?: {\n cacheSizeBytes?: number;\n}): MemoryLruGarbageCollector {\n return new MemoryLruGarbageCollectorImpl(settings?.cacheSizeBytes);\n}\n\n/**\n * An settings object to configure an `MemoryLocalCache` instance.\n */\nexport type MemoryCacheSettings = {\n /**\n * The garbage collector to use, for the memory cache layer.\n * A `MemoryEagerGarbageCollector` is used when this is undefined.\n */\n garbageCollector?: MemoryGarbageCollector;\n};\n\n/**\n * Creates an instance of `MemoryLocalCache`. The instance can be set to\n * `FirestoreSettings.cache` to tell the SDK which cache layer to use.\n */\nexport function memoryLocalCache(\n settings?: MemoryCacheSettings\n): MemoryLocalCache {\n return new MemoryLocalCacheImpl(settings);\n}\n\n/**\n * An settings object to configure an `PersistentLocalCache` instance.\n *\n * Persistent cache cannot be used in a Node.js environment.\n */\nexport type PersistentCacheSettings = {\n /**\n * An approximate cache size threshold for the on-disk data. If the cache\n * grows beyond this size, Firestore will start removing data that hasn't been\n * recently used. The SDK does not guarantee that the cache will stay below\n * that size, only that if the cache exceeds the given size, cleanup will be\n * attempted.\n *\n * The default value is 40 MB. The threshold must be set to at least 1 MB, and\n * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection.\n */\n cacheSizeBytes?: number;\n\n /**\n * Specifies how multiple tabs/windows will be managed by the SDK.\n */\n tabManager?: PersistentTabManager;\n};\n\n/**\n * Creates an instance of `PersistentLocalCache`. The instance can be set to\n * `FirestoreSettings.cache` to tell the SDK which cache layer to use.\n *\n * Persistent cache cannot be used in a Node.js environment.\n */\nexport function persistentLocalCache(\n settings?: PersistentCacheSettings\n): PersistentLocalCache {\n return new PersistentLocalCacheImpl(settings);\n}\n\n/**\n * A tab manager supporting only one tab, no synchronization will be\n * performed across tabs.\n */\nexport type PersistentSingleTabManager = {\n kind: 'persistentSingleTab';\n /**\n * @internal\n */\n _initialize: (\n settings: Omit | undefined\n ) => void;\n /**\n * @internal\n */\n _onlineComponentProvider?: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider?: OfflineComponentProviderFactory;\n};\n\nclass SingleTabManagerImpl implements PersistentSingleTabManager {\n kind: 'persistentSingleTab' = 'persistentSingleTab';\n\n /**\n * @internal\n */\n _onlineComponentProvider?: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider?: OfflineComponentProviderFactory;\n\n constructor(private forceOwnership?: boolean) {}\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n\n /**\n * @internal\n */\n _initialize(\n settings: Omit | undefined\n ): void {\n this._onlineComponentProvider = OnlineComponentProvider.provider;\n this._offlineComponentProvider = {\n build: (onlineComponents: OnlineComponentProvider) =>\n new IndexedDbOfflineComponentProvider(\n onlineComponents,\n settings?.cacheSizeBytes,\n this.forceOwnership\n )\n };\n }\n}\n\n/**\n * A tab manager supporting multiple tabs. SDK will synchronize queries and\n * mutations done across all tabs using the SDK.\n */\nexport type PersistentMultipleTabManager = {\n kind: 'PersistentMultipleTab';\n /**\n * @internal\n */\n _initialize: (settings: Omit) => void;\n /**\n * @internal\n */\n _onlineComponentProvider?: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n\n _offlineComponentProvider?: OfflineComponentProviderFactory;\n};\n\nclass MultiTabManagerImpl implements PersistentMultipleTabManager {\n kind: 'PersistentMultipleTab' = 'PersistentMultipleTab';\n\n /**\n * @internal\n */\n _onlineComponentProvider?: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider?: OfflineComponentProviderFactory;\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n\n /**\n * @internal\n */\n _initialize(\n settings: Omit | undefined\n ): void {\n this._onlineComponentProvider = OnlineComponentProvider.provider;\n this._offlineComponentProvider = {\n build: (onlineComponents: OnlineComponentProvider) =>\n new MultiTabOfflineComponentProvider(\n onlineComponents,\n settings?.cacheSizeBytes\n )\n };\n }\n}\n\n/**\n * A union of all available tab managers.\n */\nexport type PersistentTabManager =\n | PersistentSingleTabManager\n | PersistentMultipleTabManager;\n\n/**\n * Type to configure an `PersistentSingleTabManager` instance.\n */\nexport type PersistentSingleTabManagerSettings = {\n /**\n * Whether to force-enable persistent (IndexedDB) cache for the client. This\n * cannot be used with multi-tab synchronization and is primarily intended for\n * use with Web Workers. Setting this to `true` will enable IndexedDB, but cause\n * other tabs using IndexedDB cache to fail.\n */\n forceOwnership?: boolean;\n};\n/**\n * Creates an instance of `PersistentSingleTabManager`.\n *\n * @param settings Configures the created tab manager.\n */\nexport function persistentSingleTabManager(\n settings: PersistentSingleTabManagerSettings | undefined\n): PersistentSingleTabManager {\n return new SingleTabManagerImpl(settings?.forceOwnership);\n}\n\n/**\n * Creates an instance of `PersistentMultipleTabManager`.\n */\nexport function persistentMultipleTabManager(): PersistentMultipleTabManager {\n return new MultiTabManagerImpl();\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\n\nexport const DEFAULT_TRANSACTION_OPTIONS: TransactionOptions = {\n maxAttempts: 5\n};\n\n/**\n * Options to customize transaction behavior.\n */\nexport declare interface TransactionOptions {\n /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */\n readonly maxAttempts: number;\n}\n\nexport function validateTransactionOptions(options: TransactionOptions): void {\n if (options.maxAttempts < 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Max attempts must be at least 1'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Compat, getModularInstance } from '@firebase/util';\n\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { invokeCommitRpc } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport { applyFirestoreDataConverter } from './reference_impl';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\n\n/**\n * A write batch, used to perform multiple writes as a single atomic unit.\n *\n * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It\n * provides methods for adding writes to the write batch. None of the writes\n * will be committed (or visible locally) until {@link WriteBatch.commit} is\n * called.\n */\nexport class WriteBatch {\n // This is the lite version of the WriteBatch API used in the legacy SDK. The\n // class is a close copy but takes different input types.\n\n private readonly _dataReader: UserDataReader;\n private _mutations = [] as Mutation[];\n private _committed = false;\n\n /** @hideconstructor */\n constructor(\n private readonly _firestore: Firestore,\n private readonly _commitHandler: (m: Mutation[]) => Promise\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): WriteBatch;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): WriteBatch;\n set(\n documentRef: DocumentReference,\n data: WithFieldValue | PartialWithFieldValue,\n options?: SetOptions\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n data,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'WriteBatch.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._mutations.push(parsed.toMutation(ref._key, Precondition.none()));\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): WriteBatch;\n /**\n * Updates fields in the document referred to by this {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be update by providing dot-separated field path strings\n * or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._mutations.push(\n parsed.toMutation(ref._key, Precondition.exists(true))\n );\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n this._mutations = this._mutations.concat(\n new DeleteMutation(ref._key, Precondition.none())\n );\n return this;\n }\n\n /**\n * Commits all of the writes in this write batch as a single atomic unit.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `Promise` resolved once all of the writes in the batch have been\n * successfully written to the backend as an atomic unit (note that it won't\n * resolve while you're offline).\n */\n commit(): Promise {\n this._verifyNotCommitted();\n this._committed = true;\n if (this._mutations.length > 0) {\n return this._commitHandler(this._mutations);\n }\n\n return Promise.resolve();\n }\n\n private _verifyNotCommitted(): void {\n if (this._committed) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A write batch can no longer be used after commit() ' +\n 'has been called.'\n );\n }\n }\n}\n\nexport function validateReference<\n AppModelType,\n DbModelType extends DocumentData\n>(\n documentRef:\n | DocumentReference\n | Compat>,\n firestore: Firestore\n): DocumentReference {\n documentRef = getModularInstance(documentRef);\n\n if (documentRef.firestore !== firestore) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Provided document reference is from a different Firestore instance.'\n );\n } else {\n return documentRef as DocumentReference;\n }\n}\n\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single WriteBatch\n * is 500.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `WriteBatch` that can be used to atomically execute multiple\n * writes.\n */\nexport function writeBatch(firestore: Firestore): WriteBatch {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n return new WriteBatch(firestore, writes =>\n invokeCommitRpc(datastore, writes)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport {\n DEFAULT_TRANSACTION_OPTIONS,\n TransactionOptions as TransactionOptionsInternal,\n validateTransactionOptions\n} from '../core/transaction_options';\nimport { TransactionRunner } from '../core/transaction_runner';\nimport { fail } from '../util/assert';\nimport { newAsyncQueue } from '../util/async_queue_impl';\nimport { cast } from '../util/input_validation';\nimport { Deferred } from '../util/promise';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n applyFirestoreDataConverter,\n LiteUserDataWriter\n} from './reference_impl';\nimport { DocumentSnapshot } from './snapshot';\nimport { TransactionOptions } from './transaction_options';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\nimport { validateReference } from './write_batch';\n\n// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the\n// legacy SDK.\n\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nexport class Transaction {\n // This is the tree-shakeable version of the Transaction class used in the\n // legacy SDK. The class is a close copy but takes different input and output\n // types. The firestore-exp SDK further extends this class to return its API\n // type.\n\n private readonly _dataReader: UserDataReader;\n\n /** @hideconstructor */\n constructor(\n protected readonly _firestore: Firestore,\n private readonly _transaction: InternalTransaction\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */\n get(\n documentRef: DocumentReference\n ): Promise> {\n const ref = validateReference(documentRef, this._firestore);\n const userDataWriter = new LiteUserDataWriter(this._firestore);\n return this._transaction.lookup([ref._key]).then(docs => {\n if (!docs || docs.length !== 1) {\n return fail(0x5de9, 'Mismatch in docs returned from document lookup.');\n }\n const doc = docs[0];\n if (doc.isFoundDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n doc.key,\n doc,\n ref.converter\n );\n } else if (doc.isNoDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n ref._key,\n null,\n ref.converter\n );\n } else {\n throw fail(\n 0x4801,\n 'BatchGetDocumentsRequest returned unexpected document',\n {\n doc\n }\n );\n }\n });\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): this;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): this;\n set(\n documentRef: DocumentReference,\n value: PartialWithFieldValue,\n options?: SetOptions\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n value,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'Transaction.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._transaction.set(ref._key, parsed);\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): this;\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key/value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._transaction.update(ref._key, parsed);\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n this._transaction.delete(ref._key);\n return this;\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */\nexport function runTransaction(\n firestore: Firestore,\n updateFunction: (transaction: Transaction) => Promise,\n options?: TransactionOptions\n): Promise {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n const optionsWithDefaults: TransactionOptionsInternal = {\n ...DEFAULT_TRANSACTION_OPTIONS,\n ...options\n };\n validateTransactionOptions(optionsWithDefaults);\n const deferred = new Deferred();\n new TransactionRunner(\n newAsyncQueue(),\n datastore,\n optionsWithDefaults,\n internalTransaction =>\n updateFunction(new Transaction(firestore, internalTransaction)),\n deferred\n ).run();\n return deferred.promise;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { firestoreClientTransaction } from '../core/firestore_client';\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport {\n TransactionOptions as TransactionOptionsInternal,\n DEFAULT_TRANSACTION_OPTIONS,\n validateTransactionOptions\n} from '../core/transaction_options';\nimport { DocumentData, DocumentReference } from '../lite-api/reference';\nimport { Transaction as LiteTransaction } from '../lite-api/transaction';\nimport { validateReference } from '../lite-api/write_batch';\nimport { cast } from '../util/input_validation';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport { ExpUserDataWriter } from './reference_impl';\nimport { DocumentSnapshot, SnapshotMetadata } from './snapshot';\nimport { TransactionOptions } from './transaction_options';\n\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nexport class Transaction extends LiteTransaction {\n // This class implements the same logic as the Transaction API in the Lite SDK\n // but is subclassed in order to return its own DocumentSnapshot types.\n\n /** @hideconstructor */\n constructor(\n protected readonly _firestore: Firestore,\n _transaction: InternalTransaction\n ) {\n super(_firestore, _transaction);\n }\n\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */\n get(\n documentRef: DocumentReference\n ): Promise> {\n const ref = validateReference(documentRef, this._firestore);\n const userDataWriter = new ExpUserDataWriter(this._firestore);\n return super\n .get(documentRef)\n .then(\n liteDocumentSnapshot =>\n new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n ref._key,\n liteDocumentSnapshot._document,\n new SnapshotMetadata(\n /* hasPendingWrites= */ false,\n /* fromCache= */ false\n ),\n ref.converter\n )\n );\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */\nexport function runTransaction(\n firestore: Firestore,\n updateFunction: (transaction: Transaction) => Promise,\n options?: TransactionOptions\n): Promise {\n firestore = cast(firestore, Firestore);\n const optionsWithDefaults: TransactionOptionsInternal = {\n ...DEFAULT_TRANSACTION_OPTIONS,\n ...options\n };\n validateTransactionOptions(optionsWithDefaults);\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientTransaction(\n client,\n internalTransaction =>\n updateFunction(new Transaction(firestore, internalTransaction)),\n optionsWithDefaults\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldValue } from './field_value';\nimport {\n ArrayRemoveFieldValueImpl,\n ArrayUnionFieldValueImpl,\n DeleteFieldValueImpl,\n NumericIncrementFieldValueImpl,\n ServerTimestampFieldValueImpl\n} from './user_data_reader';\nimport { VectorValue } from './vector_value';\n\n/**\n * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or\n * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.\n */\nexport function deleteField(): FieldValue {\n return new DeleteFieldValueImpl('deleteField');\n}\n\n/**\n * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to\n * include a server-generated timestamp in the written data.\n */\nexport function serverTimestamp(): FieldValue {\n return new ServerTimestampFieldValueImpl('serverTimestamp');\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array\n * value that already exists on the server. Each specified element that doesn't\n * already exist in the array will be added to the end. If the field being\n * modified is not already an array it will be overwritten with an array\n * containing exactly the specified elements.\n *\n * @param elements - The elements to union into the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`.\n */\nexport function arrayUnion(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayUnionFieldValueImpl('arrayUnion', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link (setDoc:1)} or {@link\n * updateDoc:1} that tells the server to remove the given elements from any\n * array value that already exists on the server. All instances of each element\n * specified will be removed from the array. If the field being modified is not\n * already an array it will be overwritten with an empty array.\n *\n * @param elements - The elements to remove from the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function arrayRemove(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayRemoveFieldValueImpl('arrayRemove', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by\n * the given value.\n *\n * If either the operand or the current field value uses floating point\n * precision, all arithmetic follows IEEE 754 semantics. If both values are\n * integers, values outside of JavaScript's safe number range\n * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to\n * precision loss. Furthermore, once processed by the Firestore backend, all\n * integer operations are capped between -2^63 and 2^63-1.\n *\n * If the current field value is not of type `number`, or if the field does not\n * yet exist, the transformation sets the field to the given value.\n *\n * @param n - The value to increment by.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function increment(n: number): FieldValue {\n return new NumericIncrementFieldValueImpl('increment', n);\n}\n\n/**\n * Creates a new `VectorValue` constructed with a copy of the given array of numbers.\n *\n * @param values - Create a `VectorValue` instance with a copy of this array of numbers.\n *\n * @returns A new `VectorValue` constructed with a copy of the given array of numbers.\n */\nexport function vector(values?: number[]): VectorValue {\n return new VectorValue(values);\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 { WriteBatch } from '../lite-api/write_batch';\nimport { cast } from '../util/input_validation';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport { executeWrite } from './reference_impl';\n\nexport { WriteBatch };\n\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch}\n * is 500.\n *\n * Unlike transactions, write batches are persisted offline and therefore are\n * preferable when you don't need to condition your writes on read data.\n *\n * @returns A {@link WriteBatch} that can be used to atomically execute multiple\n * writes.\n */\nexport function writeBatch(firestore: Firestore): WriteBatch {\n firestore = cast(firestore, Firestore);\n ensureFirestoreConfigured(firestore);\n return new WriteBatch(firestore, mutations =>\n executeWrite(firestore, mutations)\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 { firestoreClientSetIndexConfiguration } from '../core/firestore_client';\nimport { fieldPathFromDotSeparatedString } from '../lite-api/user_data_reader';\nimport {\n FieldIndex,\n IndexKind,\n IndexSegment,\n IndexState\n} from '../model/field_index';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\nimport { logWarn } from '../util/log';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\n\nexport {\n connectFirestoreEmulator,\n EmulatorMockTokenOptions\n} from '../lite-api/database';\n\n/**\n * A single field element in an index configuration.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport interface IndexField {\n /** The field path to index. */\n readonly fieldPath: string;\n /**\n * What type of array index to create. Set to `CONTAINS` for `array-contains`\n * and `array-contains-any` indexes.\n *\n * Only one of `arrayConfig` or `order` should be set;\n */\n readonly arrayConfig?: 'CONTAINS';\n /**\n * What type of array index to create. Set to `ASCENDING` or 'DESCENDING` for\n * `==`, `!=`, `<=`, `<=`, `in` and `not-in` filters.\n *\n * Only one of `arrayConfig` or `order` should be set.\n */\n readonly order?: 'ASCENDING' | 'DESCENDING';\n\n [key: string]: unknown;\n}\n\n/**\n * The SDK definition of a Firestore index.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport interface Index {\n /** The ID of the collection to index. */\n readonly collectionGroup: string;\n /** A list of fields to index. */\n readonly fields?: IndexField[];\n\n [key: string]: unknown;\n}\n\n/**\n * A list of Firestore indexes to speed up local query execution.\n *\n * See {@link https://firebase.google.com/docs/reference/firestore/indexes/#json_format | JSON Format}\n * for a description of the format of the index definition.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport interface IndexConfiguration {\n /** A list of all Firestore indexes. */\n readonly indexes?: Index[];\n\n [key: string]: unknown;\n}\n\n/**\n * Configures indexing for local query execution. Any previous index\n * configuration is overridden. The `Promise` resolves once the index\n * configuration has been persisted.\n *\n * The index entries themselves are created asynchronously. You can continue to\n * use queries that require indexing even if the indices are not yet available.\n * Query execution will automatically start using the index once the index\n * entries have been written.\n *\n * Indexes are only supported with IndexedDb persistence. If IndexedDb is not\n * enabled, any index configuration is ignored.\n *\n * @param firestore - The {@link Firestore} instance to configure indexes for.\n * @param configuration -The index definition.\n * @throws FirestoreError if the JSON format is invalid.\n * @returns A `Promise` that resolves once all indices are successfully\n * configured.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport function setIndexConfiguration(\n firestore: Firestore,\n configuration: IndexConfiguration\n): Promise;\n\n/**\n * Configures indexing for local query execution. Any previous index\n * configuration is overridden. The `Promise` resolves once the index\n * configuration has been persisted.\n *\n * The index entries themselves are created asynchronously. You can continue to\n * use queries that require indexing even if the indices are not yet available.\n * Query execution will automatically start using the index once the index\n * entries have been written.\n *\n * Indexes are only supported with IndexedDb persistence. Invoke either\n * `enableIndexedDbPersistence()` or `enableMultiTabIndexedDbPersistence()`\n * before setting an index configuration. If IndexedDb is not enabled, any\n * index configuration is ignored.\n *\n * The method accepts the JSON format exported by the Firebase CLI (`firebase\n * firestore:indexes`). If the JSON format is invalid, this method throws an\n * error.\n *\n * @param firestore - The {@link Firestore} instance to configure indexes for.\n * @param json -The JSON format exported by the Firebase CLI.\n * @throws FirestoreError if the JSON format is invalid.\n * @returns A `Promise` that resolves once all indices are successfully\n * configured.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport function setIndexConfiguration(\n firestore: Firestore,\n json: string\n): Promise;\n\nexport function setIndexConfiguration(\n firestore: Firestore,\n jsonOrConfiguration: string | IndexConfiguration\n): Promise {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n if (\n !client._uninitializedComponentsProvider ||\n client._uninitializedComponentsProvider._offline.kind === 'memory'\n ) {\n // PORTING NOTE: We don't return an error if the user has not enabled\n // persistence since `enableIndexeddbPersistence()` can fail on the Web.\n logWarn('Cannot enable indexes when persistence is disabled');\n return Promise.resolve();\n }\n const parsedIndexes = parseIndexes(jsonOrConfiguration);\n return firestoreClientSetIndexConfiguration(client, parsedIndexes);\n}\n\nexport function parseIndexes(\n jsonOrConfiguration: string | IndexConfiguration\n): FieldIndex[] {\n const indexConfiguration =\n typeof jsonOrConfiguration === 'string'\n ? (tryParseJson(jsonOrConfiguration) as IndexConfiguration)\n : jsonOrConfiguration;\n const parsedIndexes: FieldIndex[] = [];\n\n if (Array.isArray(indexConfiguration.indexes)) {\n for (const index of indexConfiguration.indexes) {\n const collectionGroup = tryGetString(index, 'collectionGroup');\n\n const segments: IndexSegment[] = [];\n if (Array.isArray(index.fields)) {\n for (const field of index.fields) {\n const fieldPathString = tryGetString(field, 'fieldPath');\n const fieldPath = fieldPathFromDotSeparatedString(\n 'setIndexConfiguration',\n fieldPathString\n );\n\n if (field.arrayConfig === 'CONTAINS') {\n segments.push(new IndexSegment(fieldPath, IndexKind.CONTAINS));\n } else if (field.order === 'ASCENDING') {\n segments.push(new IndexSegment(fieldPath, IndexKind.ASCENDING));\n } else if (field.order === 'DESCENDING') {\n segments.push(new IndexSegment(fieldPath, IndexKind.DESCENDING));\n }\n }\n }\n\n parsedIndexes.push(\n new FieldIndex(\n FieldIndex.UNKNOWN_ID,\n collectionGroup,\n segments,\n IndexState.empty()\n )\n );\n }\n }\n return parsedIndexes;\n}\n\nfunction tryParseJson(json: string): Record {\n try {\n return JSON.parse(json);\n } catch (e) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Failed to parse JSON: ' + (e as Error)?.message\n );\n }\n}\n\nfunction tryGetString(data: Record, property: string): string {\n if (typeof data[property] !== 'string') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Missing string value for: ' + property\n );\n }\n return data[property] as string;\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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ensureFirestoreConfigured, Firestore } from '../api/database';\nimport { AggregateImpl } from '../core/aggregate';\nimport { queryToAggregateTarget, queryToTarget } from '../core/query';\nimport { AggregateSpec } from '../lite-api/aggregate_types';\nimport { Query } from '../lite-api/reference';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport { toQueryTarget, toRunAggregationQueryRequest } from './serializer';\n\n/**\n * @internal\n * @private\n *\n * This function is for internal use only.\n *\n * Returns the `QueryTarget` representation of the given query. Returns `null`\n * if the Firestore client associated with the given query has not been\n * initialized or has been terminated.\n *\n * @param query - The Query to convert to proto representation.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function _internalQueryToProtoQueryTarget(query: Query): any {\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const serializer = client._onlineComponents?.datastore.serializer;\n if (serializer === undefined) {\n return null;\n }\n return toQueryTarget(serializer!, queryToTarget(query._query)).queryTarget;\n}\n\n/**\n * @internal\n * @private\n *\n * This function is for internal use only.\n *\n * Returns `RunAggregationQueryRequest` which contains the proto representation\n * of the given aggregation query request. Returns null if the Firestore client\n * associated with the given query has not been initialized or has been\n * terminated.\n *\n * @param query - The Query to convert to proto representation.\n * @param aggregateSpec - The set of aggregations and their aliases.\n */\nexport function _internalAggregationQueryToProtoRunAggregationQueryRequest<\n AggregateSpecType extends AggregateSpec\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n>(query: Query, aggregateSpec: AggregateSpecType): any {\n const aggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const serializer = client._onlineComponents?.datastore.serializer;\n if (serializer === undefined) {\n return null;\n }\n\n return toRunAggregationQueryRequest(\n serializer!,\n queryToAggregateTarget(query._query),\n aggregates,\n /* skipAliasing= */ true\n ).request;\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 { Unsubscribe } from '../api/reference_impl';\n\nimport {\n setTestingHooksSpi,\n ExistenceFilterMismatchInfo,\n TestingHooksSpi\n} from './testing_hooks_spi';\n\n/**\n * Testing hooks for use by Firestore's integration test suite to reach into the\n * SDK internals to validate logic and behavior that is not visible from the\n * public API surface.\n *\n * @internal\n */\nexport class TestingHooks {\n private constructor() {\n throw new Error('instances of this class should not be created');\n }\n\n /**\n * Registers a callback to be notified when an existence filter mismatch\n * occurs in the Watch listen stream.\n *\n * The relative order in which callbacks are notified is unspecified; do not\n * rely on any particular ordering. If a given callback is registered multiple\n * times then it will be notified multiple times, once per registration.\n *\n * @param callback the callback to invoke upon existence filter mismatch.\n *\n * @return a function that, when called, unregisters the given callback; only\n * the first invocation of the returned function does anything; all subsequent\n * invocations do nothing.\n */\n static onExistenceFilterMismatch(\n callback: ExistenceFilterMismatchCallback\n ): Unsubscribe {\n return TestingHooksSpiImpl.instance.onExistenceFilterMismatch(callback);\n }\n}\n\n/**\n * The signature of callbacks registered with\n * `TestingUtils.onExistenceFilterMismatch()`.\n *\n * The return value, if any, is ignored.\n *\n * @internal\n */\nexport type ExistenceFilterMismatchCallback = (\n info: ExistenceFilterMismatchInfo\n) => unknown;\n\n/**\n * The implementation of `TestingHooksSpi`.\n */\nclass TestingHooksSpiImpl implements TestingHooksSpi {\n private readonly existenceFilterMismatchCallbacksById = new Map<\n Symbol,\n ExistenceFilterMismatchCallback\n >();\n\n private constructor() {}\n\n static get instance(): TestingHooksSpiImpl {\n if (!testingHooksSpiImplInstance) {\n testingHooksSpiImplInstance = new TestingHooksSpiImpl();\n setTestingHooksSpi(testingHooksSpiImplInstance);\n }\n return testingHooksSpiImplInstance;\n }\n\n notifyOnExistenceFilterMismatch(info: ExistenceFilterMismatchInfo): void {\n this.existenceFilterMismatchCallbacksById.forEach(callback =>\n callback(info)\n );\n }\n\n onExistenceFilterMismatch(\n callback: ExistenceFilterMismatchCallback\n ): Unsubscribe {\n const id = Symbol();\n const callbacks = this.existenceFilterMismatchCallbacksById;\n callbacks.set(id, callback);\n return () => callbacks.delete(id);\n }\n}\n\nlet testingHooksSpiImplInstance: TestingHooksSpiImpl | null = null;\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 { registerFirestore } from './register';\n\nregisterFirestore('node');\n\nexport * from './api';\n"],"names":["generateRandomBytes","MIN_SURROGATE","MAX_SURROGATE","FieldPath","LOG_TAG","DbRemoteDocumentStore","DbRemoteDocumentStoreLegacy","TYPE_KEY","serverTimestamp","isDocumentQuery","sentinelKey","protos","Transaction","Firestore","LiteFirestore","SDK_VERSION","name","version","InternalFieldPath","fieldPathFromArgument","DocumentSnapshot","QueryDocumentSnapshot","LiteDocumentSnapshot","LiteTransaction"],"mappings":";;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;AAeG;AAEH;;;AAGG;AACU,MAAA,IAAI,CAAA;AAUf,IAAA,WAAA,CAAqB,GAAkB,EAAA;AAAlB,QAAA,IAAG,CAAA,GAAA,GAAH,GAAG,CAAe;AAAI,KAAA;AAE3C,IAAA,eAAe,GAAA;AACb,QAAA,OAAO,IAAI,CAAC,GAAG,IAAI,IAAI,CAAC;AACzB,KAAA;AAED;;;AAGG;AACH,IAAA,KAAK,GAAA;AACH,QAAA,IAAI,IAAI,CAAC,eAAe,EAAE,EAAE;AAC1B,YAAA,OAAO,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC;AAC1B,SAAA;AAAM,aAAA;AACL,YAAA,OAAO,gBAAgB,CAAC;AACzB,SAAA;AACF,KAAA;AAED,IAAA,OAAO,CAAC,SAAe,EAAA;AACrB,QAAA,OAAO,SAAS,CAAC,GAAG,KAAK,IAAI,CAAC,GAAG,CAAC;AACnC,KAAA;;AA7BD;AACgB,IAAA,CAAA,eAAe,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC;AAEjD;AACA;AACgB,IAAA,CAAA,kBAAkB,GAAG,IAA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;AALiB,QAAA,IAAA,CAAA,oCAAoC,GAAG,IAAI,GAAG,EAG5D,CAAC;AAEoB,KAAA;AAExB,IAAA,WAAW,QAAQ,GAAA;QACjB,IAAI,CAAC,2BAA2B,EAAE;AAChC,YAAA,2BAA2B,GAAG,IAAI,mBAAmB,EAAE,CAAC;YACxD,kBAAkB,CAAC,2BAA2B,CAAC,CAAC;AACjD,SAAA;AACD,QAAA,OAAO,2BAA2B,CAAC;AACpC,KAAA;AAED,IAAA,+BAA+B,CAAC,IAAiC,EAAA;AAC/D,QAAA,IAAI,CAAC,oCAAoC,CAAC,OAAO,CAAC,QAAQ,IACxD,QAAQ,CAAC,IAAI,CAAC,CACf,CAAC;AACH,KAAA;AAED,IAAA,yBAAyB,CACvB,QAAyC,EAAA;AAEzC,QAAA,MAAM,EAAE,GAAG,MAAM,EAAE,CAAC;AACpB,QAAA,MAAM,SAAS,GAAG,IAAI,CAAC,oCAAoC,CAAC;AAC5D,QAAA,SAAS,CAAC,GAAG,CAAC,EAAE,EAAE,QAAQ,CAAC,CAAC;AAC5B,QAAA,OAAO,MAAM,SAAS,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;AACnC,KAAA;AACF,CAAA;AAED,IAAI,2BAA2B,GAA+B,IAAI,CAAA;;ACzGlE;;;;;;;;;;;;;;;AAeG;AAIH,iBAAiB,CAAC,MAAM,CAAC;;;;"} \ No newline at end of file diff --git a/frontend-old/node_modules/@firebase/firestore/dist/index.rn.js b/frontend-old/node_modules/@firebase/firestore/dist/index.rn.js new file mode 100644 index 0000000..fb896b3 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/index.rn.js @@ -0,0 +1,23143 @@ +import { _isFirebaseServerApp as e, _getProvider, getApp as t, _removeServiceInstance as n, _registerComponent as r, registerVersion as i, SDK_VERSION as s } from "@firebase/app"; + +import { Component as o } from "@firebase/component"; + +import { Logger as _, LogLevel as a } from "@firebase/logger"; + +import { FirebaseError as u, getGlobal as c, isIndexedDBAvailable as l, getUA as h, base64 as P, DecodeBase64StringError as T, isSafariOrWebkit as I, isSafari as E, isCloudWorkstation as d, pingServer as A, updateEmulatorBanner as R, deepEqual as V, createMockUserToken as m, getModularInstance as f, getDefaultEmulatorHostnameAndPort as g } from "@firebase/util"; + +import { Integer as p, Md5 as y } from "@firebase/webchannel-wrapper/bloom-blob"; + +import { XhrIo as w, EventType as S, ErrorCode as b, createWebChannelTransport as D, getStatEventTarget as C, WebChannel as v, Event as F, Stat as M } from "@firebase/webchannel-wrapper/webchannel-blob"; + +const x = "@firebase/firestore", O = "4.9.2"; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Simple wrapper around a nullable UID. Mostly exists to make code more + * readable. + */ +class User { + constructor(e) { + this.uid = e; + } + isAuthenticated() { + return null != this.uid; + } + /** + * Returns a key representing this user, suitable for inclusion in a + * dictionary. + */ toKey() { + return this.isAuthenticated() ? "uid:" + this.uid : "anonymous-user"; + } + isEqual(e) { + return e.uid === this.uid; + } +} + +/** A user with a null UID. */ User.UNAUTHENTICATED = new User(null), +// TODO(mikelehen): Look into getting a proper uid-equivalent for +// non-FirebaseAuth providers. +User.GOOGLE_CREDENTIALS = new User("google-credentials-uid"), User.FIRST_PARTY = new User("first-party-uid"), +User.MOCK_USER = new User("mock-user"); + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let N = "12.3.0"; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const B = new _("@firebase/firestore"); + +// Helper methods are needed because variables can't be exported as read/write +function __PRIVATE_getLogLevel() { + return B.logLevel; +} + +/** + * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). + * + * @param logLevel - The verbosity you set for activity and error logging. Can + * be any of the following values: + * + *

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 0xd6db,\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\n/**\n * The smallest value representable by a 64-bit signed integer (long).\n */\nconst MIN_LONG_VALUE = '-9223372036854775808';\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 // Document keys are ordered first by numeric value (\"__id__\"),\n // then lexicographically by string value. Start the iterator at the minimum\n // possible Document key value.\n const prefix = new DocumentKey(\n collectionPath.child('__id' + MIN_LONG_VALUE + '__')\n );\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(0x251c, '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(\n 0xee44,\n 'orphanedDocuments is only valid during a transaction.'\n );\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isSafariOrWebkit } from '@firebase/util';\n\nimport { User } from '../auth/user';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { DocumentKeySet, documentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport {\n decodeResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { IndexedDbDocumentOverlayCache } from './indexeddb_document_overlay_cache';\nimport {\n dbDocumentSize,\n removeMutationBatch\n} from './indexeddb_mutation_batch_impl';\nimport { IndexedDbMutationQueue } from './indexeddb_mutation_queue';\nimport { newIndexedDbRemoteDocumentCache } from './indexeddb_remote_document_cache';\nimport {\n DbCollectionParent,\n DbDocumentMutation,\n DbMutationBatch,\n DbMutationQueue,\n DbRemoteDocument,\n DbRemoteDocumentGlobal,\n DbTarget,\n DbTargetDocument,\n DbTargetGlobal,\n SCHEMA_VERSION\n} from './indexeddb_schema';\nimport {\n DbRemoteDocument as DbRemoteDocumentLegacy,\n DbRemoteDocumentStore as DbRemoteDocumentStoreLegacy,\n DbRemoteDocumentKey as DbRemoteDocumentKeyLegacy\n} from './indexeddb_schema_legacy';\nimport {\n DbBundleKeyPath,\n DbBundleStore,\n DbClientMetadataKeyPath,\n DbClientMetadataStore,\n DbCollectionParentKey,\n DbCollectionParentKeyPath,\n DbCollectionParentStore,\n DbDocumentMutationKey,\n DbDocumentMutationStore,\n DbDocumentOverlayCollectionGroupOverlayIndex,\n DbDocumentOverlayCollectionGroupOverlayIndexPath,\n DbDocumentOverlayCollectionPathOverlayIndex,\n DbDocumentOverlayCollectionPathOverlayIndexPath,\n DbDocumentOverlayKeyPath,\n DbDocumentOverlayStore,\n DbGlobalsKeyPath,\n DbGlobalsStore,\n DbIndexConfigurationCollectionGroupIndex,\n DbIndexConfigurationCollectionGroupIndexPath,\n DbIndexConfigurationKeyPath,\n DbIndexConfigurationStore,\n DbIndexEntryDocumentKeyIndex,\n DbIndexEntryDocumentKeyIndexPath,\n DbIndexEntryKeyPath,\n DbIndexEntryStore,\n DbIndexStateKeyPath,\n DbIndexStateSequenceNumberIndex,\n DbIndexStateSequenceNumberIndexPath,\n DbIndexStateStore,\n DbMutationBatchKey,\n DbMutationBatchKeyPath,\n DbMutationBatchStore,\n DbMutationBatchUserMutationsIndex,\n DbMutationBatchUserMutationsKeyPath,\n DbMutationQueueKey,\n DbMutationQueueKeyPath,\n DbMutationQueueStore,\n DbNamedQueryKeyPath,\n DbNamedQueryStore,\n DbPrimaryClientStore,\n DbRemoteDocumentCollectionGroupIndex,\n DbRemoteDocumentCollectionGroupIndexPath,\n DbRemoteDocumentDocumentKeyIndex,\n DbRemoteDocumentDocumentKeyIndexPath,\n DbRemoteDocumentGlobalKey,\n DbRemoteDocumentGlobalStore,\n DbRemoteDocumentKey,\n DbRemoteDocumentKeyPath,\n DbRemoteDocumentStore,\n DbTargetDocumentDocumentTargetsIndex,\n DbTargetDocumentDocumentTargetsKeyPath,\n DbTargetDocumentKey,\n DbTargetDocumentKeyPath,\n DbTargetDocumentStore,\n DbTargetGlobalKey,\n DbTargetGlobalStore,\n DbTargetKey,\n DbTargetKeyPath,\n DbTargetQueryTargetsIndexName,\n DbTargetQueryTargetsKeyPath,\n DbTargetStore\n} from './indexeddb_sentinels';\nimport { IndexedDbTransaction } from './indexeddb_transaction';\nimport { LocalDocumentsView } from './local_documents_view';\nimport {\n fromDbMutationBatch,\n fromDbTarget,\n LocalSerializer,\n toDbTarget\n} from './local_serializer';\nimport { MemoryCollectionParentIndex } from './memory_index_manager';\nimport { MemoryEagerDelegate, MemoryPersistence } from './memory_persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { SimpleDbSchemaConverter, SimpleDbTransaction } from './simple_db';\n\n/** Performs database creation and schema upgrades. */\nexport class SchemaConverter implements SimpleDbSchemaConverter {\n constructor(private readonly serializer: LocalSerializer) {}\n\n /**\n * Performs database creation and schema upgrades.\n *\n * Note that in production, this method is only ever used to upgrade the schema\n * to SCHEMA_VERSION. Different values of toVersion are only used for testing\n * and local feature development.\n */\n createOrUpgrade(\n db: IDBDatabase,\n txn: IDBTransaction,\n fromVersion: number,\n toVersion: number\n ): PersistencePromise {\n debugAssert(\n fromVersion < toVersion &&\n fromVersion >= 0 &&\n toVersion <= SCHEMA_VERSION,\n `Unexpected schema upgrade from v${fromVersion} to v${toVersion}.`\n );\n\n const simpleDbTransaction = new SimpleDbTransaction('createOrUpgrade', txn);\n\n if (fromVersion < 1 && toVersion >= 1) {\n createPrimaryClientStore(db);\n createMutationQueue(db);\n createQueryCache(db);\n createLegacyRemoteDocumentCache(db);\n }\n\n // Migration 2 to populate the targetGlobal object no longer needed since\n // migration 3 unconditionally clears it.\n\n let p = PersistencePromise.resolve();\n if (fromVersion < 3 && toVersion >= 3) {\n // Brand new clients don't need to drop and recreate--only clients that\n // potentially have corrupt data.\n if (fromVersion !== 0) {\n dropQueryCache(db);\n createQueryCache(db);\n }\n p = p.next(() => writeEmptyTargetGlobalEntry(simpleDbTransaction));\n }\n\n if (fromVersion < 4 && toVersion >= 4) {\n if (fromVersion !== 0) {\n // Schema version 3 uses auto-generated keys to generate globally unique\n // mutation batch IDs (this was previously ensured internally by the\n // client). To migrate to the new schema, we have to read all mutations\n // and write them back out. We preserve the existing batch IDs to guarantee\n // consistency with other object stores. Any further mutation batch IDs will\n // be auto-generated.\n p = p.next(() =>\n upgradeMutationBatchSchemaAndMigrateData(db, simpleDbTransaction)\n );\n }\n\n p = p.next(() => {\n createClientMetadataStore(db);\n });\n }\n\n if (fromVersion < 5 && toVersion >= 5) {\n p = p.next(() => this.removeAcknowledgedMutations(simpleDbTransaction));\n }\n\n if (fromVersion < 6 && toVersion >= 6) {\n p = p.next(() => {\n createDocumentGlobalStore(db);\n return this.addDocumentGlobal(simpleDbTransaction);\n });\n }\n\n if (fromVersion < 7 && toVersion >= 7) {\n p = p.next(() => this.ensureSequenceNumbers(simpleDbTransaction));\n }\n\n if (fromVersion < 8 && toVersion >= 8) {\n p = p.next(() =>\n this.createCollectionParentIndex(db, simpleDbTransaction)\n );\n }\n\n if (fromVersion < 9 && toVersion >= 9) {\n p = p.next(() => {\n // Multi-Tab used to manage its own changelog, but this has been moved\n // to the DbRemoteDocument object store itself. Since the previous change\n // log only contained transient data, we can drop its object store.\n dropRemoteDocumentChangesStore(db);\n\n // Note: Schema version 9 used to create a read time index for the\n // RemoteDocumentCache. This is now done with schema version 13.\n });\n }\n\n if (fromVersion < 10 && toVersion >= 10) {\n p = p.next(() => this.rewriteCanonicalIds(simpleDbTransaction));\n }\n\n if (fromVersion < 11 && toVersion >= 11) {\n p = p.next(() => {\n createBundlesStore(db);\n createNamedQueriesStore(db);\n });\n }\n\n if (fromVersion < 12 && toVersion >= 12) {\n p = p.next(() => {\n createDocumentOverlayStore(db);\n });\n }\n\n if (fromVersion < 13 && toVersion >= 13) {\n p = p\n .next(() => createRemoteDocumentCache(db))\n .next(() => this.rewriteRemoteDocumentCache(db, simpleDbTransaction))\n .next(() => db.deleteObjectStore(DbRemoteDocumentStoreLegacy));\n }\n\n if (fromVersion < 14 && toVersion >= 14) {\n p = p.next(() => this.runOverlayMigration(db, simpleDbTransaction));\n }\n\n if (fromVersion < 15 && toVersion >= 15) {\n p = p.next(() => createFieldIndex(db));\n }\n\n if (fromVersion < 16 && toVersion >= 16) {\n // Clear the object stores to remove possibly corrupted index entries\n p = p\n .next(() => {\n const indexStateStore = txn.objectStore(DbIndexStateStore);\n indexStateStore.clear();\n })\n .next(() => {\n const indexEntryStore = txn.objectStore(DbIndexEntryStore);\n indexEntryStore.clear();\n });\n }\n\n if (fromVersion < 17 && toVersion >= 17) {\n p = p.next(() => {\n createGlobalsStore(db);\n });\n }\n\n if (fromVersion < 18 && toVersion >= 18) {\n // Clear the IndexEntryStores on WebKit and Safari to remove possibly\n // corrupted index entries\n if (isSafariOrWebkit()) {\n p = p\n .next(() => {\n const indexStateStore = txn.objectStore(DbIndexStateStore);\n indexStateStore.clear();\n })\n .next(() => {\n const indexEntryStore = txn.objectStore(DbIndexEntryStore);\n indexEntryStore.clear();\n });\n }\n }\n\n return p;\n }\n\n private addDocumentGlobal(\n txn: SimpleDbTransaction\n ): PersistencePromise {\n let byteSize = 0;\n return txn\n .store(\n DbRemoteDocumentStoreLegacy\n )\n .iterate((_, doc) => {\n byteSize += dbDocumentSize(doc);\n })\n .next(() => {\n const metadata: DbRemoteDocumentGlobal = { byteSize };\n return txn\n .store(\n DbRemoteDocumentGlobalStore\n )\n .put(DbRemoteDocumentGlobalKey, metadata);\n });\n }\n\n private removeAcknowledgedMutations(\n txn: SimpleDbTransaction\n ): PersistencePromise {\n const queuesStore = txn.store(\n DbMutationQueueStore\n );\n const mutationsStore = txn.store(\n DbMutationBatchStore\n );\n\n return queuesStore.loadAll().next(queues => {\n return PersistencePromise.forEach(queues, (queue: DbMutationQueue) => {\n const range = IDBKeyRange.bound(\n [queue.userId, BATCHID_UNKNOWN],\n [queue.userId, queue.lastAcknowledgedBatchId]\n );\n\n return mutationsStore\n .loadAll(DbMutationBatchUserMutationsIndex, range)\n .next(dbBatches => {\n return PersistencePromise.forEach(\n dbBatches,\n (dbBatch: DbMutationBatch) => {\n hardAssert(\n dbBatch.userId === queue.userId,\n 0x48da,\n `Cannot process batch from unexpected user`,\n { batchId: dbBatch.batchId }\n );\n const batch = fromDbMutationBatch(this.serializer, dbBatch);\n\n return removeMutationBatch(txn, queue.userId, batch).next(\n () => {}\n );\n }\n );\n });\n });\n });\n }\n\n /**\n * Ensures that every document in the remote document cache has a corresponding sentinel row\n * with a sequence number. Missing rows are given the most recently used sequence number.\n */\n private ensureSequenceNumbers(\n txn: SimpleDbTransaction\n ): PersistencePromise {\n const documentTargetStore = txn.store<\n DbTargetDocumentKey,\n DbTargetDocument\n >(DbTargetDocumentStore);\n const documentsStore = txn.store<\n DbRemoteDocumentKeyLegacy,\n DbRemoteDocumentKeyLegacy\n >(DbRemoteDocumentStoreLegacy);\n const globalTargetStore = txn.store(\n DbTargetGlobalStore\n );\n\n return globalTargetStore.get(DbTargetGlobalKey).next(metadata => {\n debugAssert(\n !!metadata,\n 'Metadata should have been written during the version 3 migration'\n );\n const writeSentinelKey = (\n path: ResourcePath\n ): PersistencePromise => {\n return documentTargetStore.put({\n targetId: 0,\n path: encodeResourcePath(path),\n sequenceNumber: metadata!.highestListenSequenceNumber!\n });\n };\n\n const promises: Array> = [];\n return documentsStore\n .iterate((key, doc) => {\n const path = new ResourcePath(key);\n const docSentinelKey = sentinelKey(path);\n promises.push(\n documentTargetStore.get(docSentinelKey).next(maybeSentinel => {\n if (!maybeSentinel) {\n return writeSentinelKey(path);\n } else {\n return PersistencePromise.resolve();\n }\n })\n );\n })\n .next(() => PersistencePromise.waitFor(promises));\n });\n }\n\n private createCollectionParentIndex(\n db: IDBDatabase,\n txn: SimpleDbTransaction\n ): PersistencePromise {\n // Create the index.\n db.createObjectStore(DbCollectionParentStore, {\n keyPath: DbCollectionParentKeyPath\n });\n\n const collectionParentsStore = txn.store<\n DbCollectionParentKey,\n DbCollectionParent\n >(DbCollectionParentStore);\n\n // Helper to add an index entry iff we haven't already written it.\n const cache = new MemoryCollectionParentIndex();\n const addEntry = (\n collectionPath: ResourcePath\n ): PersistencePromise | undefined => {\n if (cache.add(collectionPath)) {\n const collectionId = collectionPath.lastSegment();\n const parentPath = collectionPath.popLast();\n return collectionParentsStore.put({\n collectionId,\n parent: encodeResourcePath(parentPath)\n });\n }\n };\n\n // Index existing remote documents.\n return txn\n .store(\n DbRemoteDocumentStoreLegacy\n )\n .iterate({ keysOnly: true }, (pathSegments, _) => {\n const path = new ResourcePath(pathSegments);\n return addEntry(path.popLast());\n })\n .next(() => {\n // Index existing mutations.\n return txn\n .store(\n DbDocumentMutationStore\n )\n .iterate({ keysOnly: true }, ([userID, encodedPath, batchId], _) => {\n const path = decodeResourcePath(encodedPath);\n return addEntry(path.popLast());\n });\n });\n }\n\n private rewriteCanonicalIds(\n txn: SimpleDbTransaction\n ): PersistencePromise {\n const targetStore = txn.store(DbTargetStore);\n return targetStore.iterate((key, originalDbTarget) => {\n const originalTargetData = fromDbTarget(originalDbTarget);\n const updatedDbTarget = toDbTarget(this.serializer, originalTargetData);\n return targetStore.put(updatedDbTarget);\n });\n }\n\n private rewriteRemoteDocumentCache(\n db: IDBDatabase,\n transaction: SimpleDbTransaction\n ): PersistencePromise {\n const legacyRemoteDocumentStore = transaction.store<\n DbRemoteDocumentKeyLegacy,\n DbRemoteDocumentLegacy\n >(DbRemoteDocumentStoreLegacy);\n\n const writes: Array> = [];\n return legacyRemoteDocumentStore\n .iterate((_, legacyDocument) => {\n const remoteDocumentStore = transaction.store<\n DbRemoteDocumentKey,\n DbRemoteDocument\n >(DbRemoteDocumentStore);\n\n const path = extractKey(legacyDocument).path.toArray();\n const dbRemoteDocument = {\n prefixPath: path.slice(0, path.length - 2),\n collectionGroup: path[path.length - 2],\n documentId: path[path.length - 1],\n readTime: legacyDocument.readTime || [0, 0],\n unknownDocument: legacyDocument.unknownDocument,\n noDocument: legacyDocument.noDocument,\n document: legacyDocument.document,\n hasCommittedMutations: !!legacyDocument.hasCommittedMutations\n };\n writes.push(remoteDocumentStore.put(dbRemoteDocument));\n })\n .next(() => PersistencePromise.waitFor(writes));\n }\n\n private runOverlayMigration(\n db: IDBDatabase,\n transaction: SimpleDbTransaction\n ): PersistencePromise {\n const mutationsStore = transaction.store<\n DbMutationBatchKey,\n DbMutationBatch\n >(DbMutationBatchStore);\n\n const remoteDocumentCache = newIndexedDbRemoteDocumentCache(\n this.serializer\n );\n const memoryPersistence = new MemoryPersistence(\n MemoryEagerDelegate.factory,\n this.serializer.remoteSerializer\n );\n\n return mutationsStore.loadAll().next(dbBatches => {\n const userToDocumentSet = new Map();\n dbBatches.forEach(dbBatch => {\n let documentSet =\n userToDocumentSet.get(dbBatch.userId) ?? documentKeySet();\n const batch = fromDbMutationBatch(this.serializer, dbBatch);\n batch.keys().forEach(key => (documentSet = documentSet.add(key)));\n userToDocumentSet.set(dbBatch.userId, documentSet);\n });\n return PersistencePromise.forEach(\n userToDocumentSet,\n (allDocumentKeysForUser, userId) => {\n const user = new User(userId);\n const documentOverlayCache = IndexedDbDocumentOverlayCache.forUser(\n this.serializer,\n user\n );\n // NOTE: The index manager and the reference delegate are\n // irrelevant for the purpose of recalculating and saving\n // overlays. We can therefore simply use the memory\n // implementation.\n const indexManager = memoryPersistence.getIndexManager(user);\n const mutationQueue = IndexedDbMutationQueue.forUser(\n user,\n this.serializer,\n indexManager,\n memoryPersistence.referenceDelegate\n );\n const localDocumentsView = new LocalDocumentsView(\n remoteDocumentCache,\n mutationQueue,\n documentOverlayCache,\n indexManager\n );\n return localDocumentsView\n .recalculateAndSaveOverlaysForDocumentKeys(\n new IndexedDbTransaction(transaction, ListenSequence.INVALID),\n allDocumentKeysForUser\n )\n .next();\n }\n );\n });\n }\n}\n\nfunction sentinelKey(path: ResourcePath): DbTargetDocumentKey {\n return [0, encodeResourcePath(path)];\n}\n\nfunction createPrimaryClientStore(db: IDBDatabase): void {\n db.createObjectStore(DbPrimaryClientStore);\n}\n\nfunction createMutationQueue(db: IDBDatabase): void {\n db.createObjectStore(DbMutationQueueStore, {\n keyPath: DbMutationQueueKeyPath\n });\n\n const mutationBatchesStore = db.createObjectStore(DbMutationBatchStore, {\n keyPath: DbMutationBatchKeyPath,\n autoIncrement: true\n });\n mutationBatchesStore.createIndex(\n DbMutationBatchUserMutationsIndex,\n DbMutationBatchUserMutationsKeyPath,\n { unique: true }\n );\n\n db.createObjectStore(DbDocumentMutationStore);\n}\n\n/**\n * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads\n * and rewrites all data.\n */\nfunction upgradeMutationBatchSchemaAndMigrateData(\n db: IDBDatabase,\n txn: SimpleDbTransaction\n): PersistencePromise {\n const v1MutationsStore = txn.store<[string, number], DbMutationBatch>(\n DbMutationBatchStore\n );\n return v1MutationsStore.loadAll().next(existingMutations => {\n db.deleteObjectStore(DbMutationBatchStore);\n\n const mutationsStore = db.createObjectStore(DbMutationBatchStore, {\n keyPath: DbMutationBatchKeyPath,\n autoIncrement: true\n });\n mutationsStore.createIndex(\n DbMutationBatchUserMutationsIndex,\n DbMutationBatchUserMutationsKeyPath,\n { unique: true }\n );\n\n const v3MutationsStore = txn.store(\n DbMutationBatchStore\n );\n const writeAll = existingMutations.map(mutation =>\n v3MutationsStore.put(mutation)\n );\n\n return PersistencePromise.waitFor(writeAll);\n });\n}\n\nfunction createLegacyRemoteDocumentCache(db: IDBDatabase): void {\n db.createObjectStore(DbRemoteDocumentStoreLegacy);\n}\n\nfunction createRemoteDocumentCache(db: IDBDatabase): void {\n const remoteDocumentStore = db.createObjectStore(DbRemoteDocumentStore, {\n keyPath: DbRemoteDocumentKeyPath\n });\n remoteDocumentStore.createIndex(\n DbRemoteDocumentDocumentKeyIndex,\n DbRemoteDocumentDocumentKeyIndexPath\n );\n remoteDocumentStore.createIndex(\n DbRemoteDocumentCollectionGroupIndex,\n DbRemoteDocumentCollectionGroupIndexPath\n );\n}\n\nfunction createDocumentGlobalStore(db: IDBDatabase): void {\n db.createObjectStore(DbRemoteDocumentGlobalStore);\n}\n\nfunction createQueryCache(db: IDBDatabase): void {\n const targetDocumentsStore = db.createObjectStore(DbTargetDocumentStore, {\n keyPath: DbTargetDocumentKeyPath\n });\n targetDocumentsStore.createIndex(\n DbTargetDocumentDocumentTargetsIndex,\n DbTargetDocumentDocumentTargetsKeyPath,\n { unique: true }\n );\n\n const targetStore = db.createObjectStore(DbTargetStore, {\n keyPath: DbTargetKeyPath\n });\n\n // NOTE: This is unique only because the TargetId is the suffix.\n targetStore.createIndex(\n DbTargetQueryTargetsIndexName,\n DbTargetQueryTargetsKeyPath,\n { unique: true }\n );\n db.createObjectStore(DbTargetGlobalStore);\n}\n\nfunction dropQueryCache(db: IDBDatabase): void {\n db.deleteObjectStore(DbTargetDocumentStore);\n db.deleteObjectStore(DbTargetStore);\n db.deleteObjectStore(DbTargetGlobalStore);\n}\n\nfunction dropRemoteDocumentChangesStore(db: IDBDatabase): void {\n if (db.objectStoreNames.contains('remoteDocumentChanges')) {\n db.deleteObjectStore('remoteDocumentChanges');\n }\n}\n\n/**\n * Creates the target global singleton row.\n *\n * @param txn - The version upgrade transaction for indexeddb\n */\nfunction writeEmptyTargetGlobalEntry(\n txn: SimpleDbTransaction\n): PersistencePromise {\n const globalStore = txn.store(\n DbTargetGlobalStore\n );\n const metadata: DbTargetGlobal = {\n highestTargetId: 0,\n highestListenSequenceNumber: 0,\n lastRemoteSnapshotVersion: SnapshotVersion.min().toTimestamp(),\n targetCount: 0\n };\n return globalStore.put(DbTargetGlobalKey, metadata);\n}\n\nfunction createClientMetadataStore(db: IDBDatabase): void {\n db.createObjectStore(DbClientMetadataStore, {\n keyPath: DbClientMetadataKeyPath\n });\n}\n\nfunction createBundlesStore(db: IDBDatabase): void {\n db.createObjectStore(DbBundleStore, {\n keyPath: DbBundleKeyPath\n });\n}\n\nfunction createNamedQueriesStore(db: IDBDatabase): void {\n db.createObjectStore(DbNamedQueryStore, {\n keyPath: DbNamedQueryKeyPath\n });\n}\n\nfunction createFieldIndex(db: IDBDatabase): void {\n const indexConfigurationStore = db.createObjectStore(\n DbIndexConfigurationStore,\n {\n keyPath: DbIndexConfigurationKeyPath,\n autoIncrement: true\n }\n );\n indexConfigurationStore.createIndex(\n DbIndexConfigurationCollectionGroupIndex,\n DbIndexConfigurationCollectionGroupIndexPath,\n { unique: false }\n );\n\n const indexStateStore = db.createObjectStore(DbIndexStateStore, {\n keyPath: DbIndexStateKeyPath\n });\n indexStateStore.createIndex(\n DbIndexStateSequenceNumberIndex,\n DbIndexStateSequenceNumberIndexPath,\n { unique: false }\n );\n\n const indexEntryStore = db.createObjectStore(DbIndexEntryStore, {\n keyPath: DbIndexEntryKeyPath\n });\n indexEntryStore.createIndex(\n DbIndexEntryDocumentKeyIndex,\n DbIndexEntryDocumentKeyIndexPath,\n { unique: false }\n );\n}\n\nfunction createDocumentOverlayStore(db: IDBDatabase): void {\n const documentOverlayStore = db.createObjectStore(DbDocumentOverlayStore, {\n keyPath: DbDocumentOverlayKeyPath\n });\n documentOverlayStore.createIndex(\n DbDocumentOverlayCollectionPathOverlayIndex,\n DbDocumentOverlayCollectionPathOverlayIndexPath,\n { unique: false }\n );\n documentOverlayStore.createIndex(\n DbDocumentOverlayCollectionGroupOverlayIndex,\n DbDocumentOverlayCollectionGroupOverlayIndexPath,\n { unique: false }\n );\n}\n\nfunction createGlobalsStore(db: IDBDatabase): void {\n db.createObjectStore(DbGlobalsStore, {\n keyPath: DbGlobalsKeyPath\n });\n}\n\nfunction extractKey(remoteDoc: DbRemoteDocumentLegacy): DocumentKey {\n if (remoteDoc.document) {\n return new DocumentKey(\n ResourcePath.fromString(remoteDoc.document.name!).popFirst(5)\n );\n } else if (remoteDoc.noDocument) {\n return DocumentKey.fromSegments(remoteDoc.noDocument.path);\n } else if (remoteDoc.unknownDocument) {\n return DocumentKey.fromSegments(remoteDoc.unknownDocument.path);\n } else {\n return fail(0x8faf, 'Unexpected DbRemoteDocument');\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isSafari } from '@firebase/util';\n\nimport { User } from '../auth/user';\nimport { DatabaseId } from '../core/database_info';\nimport { ListenSequence, SequenceNumberSyncer } from '../core/listen_sequence';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logError } from '../util/log';\nimport { DocumentLike, WindowLike } from '../util/types';\n\nimport { BundleCache } from './bundle_cache';\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { GlobalsCache } from './globals_cache';\nimport { IndexManager } from './index_manager';\nimport { IndexedDbBundleCache } from './indexeddb_bundle_cache';\nimport { IndexedDbDocumentOverlayCache } from './indexeddb_document_overlay_cache';\nimport { IndexedDbGlobalsCache } from './indexeddb_globals_cache';\nimport { IndexedDbIndexManager } from './indexeddb_index_manager';\nimport { IndexedDbLruDelegateImpl } from './indexeddb_lru_delegate_impl';\nimport { IndexedDbMutationQueue } from './indexeddb_mutation_queue';\nimport {\n IndexedDbRemoteDocumentCache,\n newIndexedDbRemoteDocumentCache\n} from './indexeddb_remote_document_cache';\nimport {\n DbClientMetadata,\n DbPrimaryClient,\n SCHEMA_VERSION\n} from './indexeddb_schema';\nimport { SchemaConverter } from './indexeddb_schema_converter';\nimport {\n DbClientMetadataKey,\n DbClientMetadataStore,\n DbPrimaryClientKey,\n DbPrimaryClientStore,\n getObjectStores\n} from './indexeddb_sentinels';\nimport { IndexedDbTargetCache } from './indexeddb_target_cache';\nimport { getStore, IndexedDbTransaction } from './indexeddb_transaction';\nimport { LocalSerializer } from './local_serializer';\nimport { LruParams } from './lru_garbage_collector';\nimport { Persistence, PrimaryStateListener } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport {\n PersistenceTransaction,\n PersistenceTransactionMode,\n PRIMARY_LEASE_LOST_ERROR_MSG\n} from './persistence_transaction';\nimport { ClientId } from './shared_client_state';\nimport {\n isIndexedDbTransactionError,\n SimpleDb,\n SimpleDbStore\n} from './simple_db';\n\nconst LOG_TAG = 'IndexedDbPersistence';\n\n/**\n * Oldest acceptable age in milliseconds for client metadata before the client\n * is considered inactive and its associated data is garbage collected.\n */\nconst MAX_CLIENT_AGE_MS = 30 * 60 * 1000; // 30 minutes\n\n/**\n * Oldest acceptable metadata age for clients that may participate in the\n * primary lease election. Clients that have not updated their client metadata\n * within 5 seconds are not eligible to receive a primary lease.\n */\nconst MAX_PRIMARY_ELIGIBLE_AGE_MS = 5000;\n\n/**\n * The interval at which clients will update their metadata, including\n * refreshing their primary lease if held or potentially trying to acquire it if\n * not held.\n *\n * Primary clients may opportunistically refresh their metadata earlier\n * if they're already performing an IndexedDB operation.\n */\nconst CLIENT_METADATA_REFRESH_INTERVAL_MS = 4000;\n/** User-facing error when the primary lease is required but not available. */\nconst PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG =\n 'Failed to obtain exclusive access to the persistence layer. To allow ' +\n 'shared access, multi-tab synchronization has to be enabled in all tabs. ' +\n 'If you are using `experimentalForceOwningTab:true`, make sure that only ' +\n 'one tab has persistence enabled at any given time.';\nconst UNSUPPORTED_PLATFORM_ERROR_MSG =\n 'This platform is either missing IndexedDB or is known to have ' +\n 'an incomplete implementation. Offline persistence has been disabled.';\n\n// The format of the LocalStorage key that stores zombied client is:\n// firestore_zombie__\nconst ZOMBIED_CLIENTS_KEY_PREFIX = 'firestore_zombie';\n\n/**\n * The name of the main (and currently only) IndexedDB database. This name is\n * appended to the prefix provided to the IndexedDbPersistence constructor.\n */\nexport const MAIN_DATABASE = 'main';\n\n/**\n * An IndexedDB-backed instance of Persistence. Data is stored persistently\n * across sessions.\n *\n * On Web only, the Firestore SDKs support shared access to its persistence\n * layer. This allows multiple browser tabs to read and write to IndexedDb and\n * to synchronize state even without network connectivity. Shared access is\n * currently optional and not enabled unless all clients invoke\n * `enablePersistence()` with `{synchronizeTabs:true}`.\n *\n * In multi-tab mode, if multiple clients are active at the same time, the SDK\n * will designate one client as the \"primary client\". An effort is made to pick\n * a visible, network-connected and active client, and this client is\n * responsible for letting other clients know about its presence. The primary\n * client writes a unique client-generated identifier (the client ID) to\n * IndexedDb’s \"owner\" store every 4 seconds. If the primary client fails to\n * update this entry, another client can acquire the lease and take over as\n * primary.\n *\n * Some persistence operations in the SDK are designated as primary-client only\n * operations. This includes the acknowledgment of mutations and all updates of\n * remote documents. The effects of these operations are written to persistence\n * and then broadcast to other tabs via LocalStorage (see\n * `WebStorageSharedClientState`), which then refresh their state from\n * persistence.\n *\n * Similarly, the primary client listens to notifications sent by secondary\n * clients to discover persistence changes written by secondary clients, such as\n * the addition of new mutations and query targets.\n *\n * If multi-tab is not enabled and another tab already obtained the primary\n * lease, IndexedDbPersistence enters a failed state and all subsequent\n * operations will automatically fail.\n *\n * Additionally, there is an optimization so that when a tab is closed, the\n * primary lease is released immediately (this is especially important to make\n * sure that a refreshed tab is able to immediately re-acquire the primary\n * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload\n * since it is an asynchronous API. So in addition to attempting to give up the\n * lease, the leaseholder writes its client ID to a \"zombiedClient\" entry in\n * LocalStorage which acts as an indicator that another tab should go ahead and\n * take the primary lease immediately regardless of the current lease timestamp.\n *\n * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no\n * longer optional.\n */\nexport class IndexedDbPersistence implements Persistence {\n private simpleDb: SimpleDb;\n\n private listenSequence: ListenSequence | null = null;\n\n private _started = false;\n private isPrimary = false;\n private networkEnabled = true;\n private dbName: string;\n\n /** Our window.unload handler, if registered. */\n private windowUnloadHandler: (() => void) | null = null;\n private inForeground = false;\n\n private serializer: LocalSerializer;\n\n /** Our 'visibilitychange' listener if registered. */\n private documentVisibilityHandler: ((e?: Event) => void) | null = null;\n\n /** The client metadata refresh task. */\n private clientMetadataRefresher: DelayedOperation | null = null;\n\n /** The last time we garbage collected the client metadata object store. */\n private lastGarbageCollectionTime = Number.NEGATIVE_INFINITY;\n\n /** A listener to notify on primary state changes. */\n private primaryStateListener: PrimaryStateListener = _ => Promise.resolve();\n\n private readonly globalsCache: IndexedDbGlobalsCache;\n private readonly targetCache: IndexedDbTargetCache;\n private readonly remoteDocumentCache: IndexedDbRemoteDocumentCache;\n private readonly bundleCache: IndexedDbBundleCache;\n private readonly webStorage: Storage | null;\n readonly referenceDelegate: IndexedDbLruDelegateImpl;\n\n constructor(\n /**\n * Whether to synchronize the in-memory state of multiple tabs and share\n * access to local persistence.\n */\n private readonly allowTabSynchronization: boolean,\n\n private readonly persistenceKey: string,\n private readonly clientId: ClientId,\n lruParams: LruParams,\n private readonly queue: AsyncQueue,\n private readonly window: WindowLike | null,\n private readonly document: DocumentLike | null,\n serializer: JsonProtoSerializer,\n private readonly sequenceNumberSyncer: SequenceNumberSyncer,\n\n /**\n * If set to true, forcefully obtains database access. Existing tabs will\n * no longer be able to access IndexedDB.\n */\n private readonly forceOwningTab: boolean,\n private readonly schemaVersion = SCHEMA_VERSION\n ) {\n if (!IndexedDbPersistence.isAvailable()) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n UNSUPPORTED_PLATFORM_ERROR_MSG\n );\n }\n\n this.referenceDelegate = new IndexedDbLruDelegateImpl(this, lruParams);\n this.dbName = persistenceKey + MAIN_DATABASE;\n this.serializer = new LocalSerializer(serializer);\n this.simpleDb = new SimpleDb(\n this.dbName,\n this.schemaVersion,\n new SchemaConverter(this.serializer)\n );\n this.globalsCache = new IndexedDbGlobalsCache();\n this.targetCache = new IndexedDbTargetCache(\n this.referenceDelegate,\n this.serializer\n );\n this.remoteDocumentCache = newIndexedDbRemoteDocumentCache(this.serializer);\n this.bundleCache = new IndexedDbBundleCache();\n if (this.window && this.window.localStorage) {\n this.webStorage = this.window.localStorage;\n } else {\n this.webStorage = null;\n if (forceOwningTab === false) {\n logError(\n LOG_TAG,\n 'LocalStorage is unavailable. As a result, persistence may not work ' +\n 'reliably. In particular enablePersistence() could fail immediately ' +\n 'after refreshing the page.'\n );\n }\n }\n }\n\n /**\n * Attempt to start IndexedDb persistence.\n *\n * @returns Whether persistence was enabled.\n */\n start(): Promise {\n debugAssert(!this.started, 'IndexedDbPersistence double-started!');\n debugAssert(this.window !== null, \"Expected 'window' to be defined\");\n\n // NOTE: This is expected to fail sometimes (in the case of another tab\n // already having the persistence lock), so it's the first thing we should\n // do.\n return this.updateClientMetadataAndTryBecomePrimary()\n .then(() => {\n if (!this.isPrimary && !this.allowTabSynchronization) {\n // Fail `start()` if `synchronizeTabs` is disabled and we cannot\n // obtain the primary lease.\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG\n );\n }\n this.attachVisibilityHandler();\n this.attachWindowUnloadHook();\n\n this.scheduleClientMetadataAndPrimaryLeaseRefreshes();\n\n return this.runTransaction(\n 'getHighestListenSequenceNumber',\n 'readonly',\n txn => this.targetCache.getHighestSequenceNumber(txn)\n );\n })\n .then(highestListenSequenceNumber => {\n this.listenSequence = new ListenSequence(\n highestListenSequenceNumber,\n this.sequenceNumberSyncer\n );\n })\n .then(() => {\n this._started = true;\n })\n .catch(reason => {\n this.simpleDb && this.simpleDb.close();\n return Promise.reject(reason);\n });\n }\n\n /**\n * Registers a listener that gets called when the primary state of the\n * instance changes. Upon registering, this listener is invoked immediately\n * with the current primary state.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n setPrimaryStateListener(\n primaryStateListener: PrimaryStateListener\n ): Promise {\n this.primaryStateListener = async primaryState => {\n if (this.started) {\n return primaryStateListener(primaryState);\n }\n };\n return primaryStateListener(this.isPrimary);\n }\n\n /**\n * Registers a listener that gets called when the database receives a\n * version change event indicating that it has deleted.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n setDatabaseDeletedListener(\n databaseDeletedListener: () => Promise\n ): void {\n this.simpleDb.setVersionChangeListener(async event => {\n // Check if an attempt is made to delete IndexedDB.\n if (event.newVersion === null) {\n await databaseDeletedListener();\n }\n });\n }\n\n /**\n * Adjusts the current network state in the client's metadata, potentially\n * affecting the primary lease.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n setNetworkEnabled(networkEnabled: boolean): void {\n if (this.networkEnabled !== networkEnabled) {\n this.networkEnabled = networkEnabled;\n // Schedule a primary lease refresh for immediate execution. The eventual\n // lease update will be propagated via `primaryStateListener`.\n this.queue.enqueueAndForget(async () => {\n if (this.started) {\n await this.updateClientMetadataAndTryBecomePrimary();\n }\n });\n }\n }\n\n /**\n * Updates the client metadata in IndexedDb and attempts to either obtain or\n * extend the primary lease for the local client. Asynchronously notifies the\n * primary state listener if the client either newly obtained or released its\n * primary lease.\n */\n private updateClientMetadataAndTryBecomePrimary(): Promise {\n return this.runTransaction(\n 'updateClientMetadataAndTryBecomePrimary',\n 'readwrite',\n txn => {\n const metadataStore = clientMetadataStore(txn);\n return metadataStore\n .put({\n clientId: this.clientId,\n updateTimeMs: Date.now(),\n networkEnabled: this.networkEnabled,\n inForeground: this.inForeground\n })\n .next(() => {\n if (this.isPrimary) {\n return this.verifyPrimaryLease(txn).next(success => {\n if (!success) {\n this.isPrimary = false;\n this.queue.enqueueRetryable(() =>\n this.primaryStateListener(false)\n );\n }\n });\n }\n })\n .next(() => this.canActAsPrimary(txn))\n .next(canActAsPrimary => {\n if (this.isPrimary && !canActAsPrimary) {\n return this.releasePrimaryLeaseIfHeld(txn).next(() => false);\n } else if (canActAsPrimary) {\n return this.acquireOrExtendPrimaryLease(txn).next(() => true);\n } else {\n return /* canActAsPrimary= */ false;\n }\n });\n }\n )\n .catch(e => {\n if (isIndexedDbTransactionError(e)) {\n logDebug(LOG_TAG, 'Failed to extend owner lease: ', e);\n // Proceed with the existing state. Any subsequent access to\n // IndexedDB will verify the lease.\n return this.isPrimary;\n }\n\n if (!this.allowTabSynchronization) {\n throw e;\n }\n\n logDebug(\n LOG_TAG,\n 'Releasing owner lease after error during lease refresh',\n e\n );\n return /* isPrimary= */ false;\n })\n .then(isPrimary => {\n if (this.isPrimary !== isPrimary) {\n this.queue.enqueueRetryable(() =>\n this.primaryStateListener(isPrimary)\n );\n }\n this.isPrimary = isPrimary;\n });\n }\n\n private verifyPrimaryLease(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const store = primaryClientStore(txn);\n return store.get(DbPrimaryClientKey).next(primaryClient => {\n return PersistencePromise.resolve(this.isLocalClient(primaryClient));\n });\n }\n\n private removeClientMetadata(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const metadataStore = clientMetadataStore(txn);\n return metadataStore.delete(this.clientId);\n }\n\n /**\n * If the garbage collection threshold has passed, prunes the\n * RemoteDocumentChanges and the ClientMetadata store based on the last update\n * time of all clients.\n */\n private async maybeGarbageCollectMultiClientState(): Promise {\n if (\n this.isPrimary &&\n !this.isWithinAge(this.lastGarbageCollectionTime, MAX_CLIENT_AGE_MS)\n ) {\n this.lastGarbageCollectionTime = Date.now();\n\n const inactiveClients = await this.runTransaction(\n 'maybeGarbageCollectMultiClientState',\n 'readwrite-primary',\n txn => {\n const metadataStore = getStore(\n txn,\n DbClientMetadataStore\n );\n\n return metadataStore.loadAll().next(existingClients => {\n const active = this.filterActiveClients(\n existingClients,\n MAX_CLIENT_AGE_MS\n );\n const inactive = existingClients.filter(\n client => active.indexOf(client) === -1\n );\n\n // Delete metadata for clients that are no longer considered active.\n return PersistencePromise.forEach(\n inactive,\n (inactiveClient: DbClientMetadata) =>\n metadataStore.delete(inactiveClient.clientId)\n ).next(() => inactive);\n });\n }\n ).catch(() => {\n // Ignore primary lease violations or any other type of error. The next\n // primary will run `maybeGarbageCollectMultiClientState()` again.\n // We don't use `ignoreIfPrimaryLeaseLoss()` since we don't want to depend\n // on LocalStore.\n return [];\n });\n\n // Delete potential leftover entries that may continue to mark the\n // inactive clients as zombied in LocalStorage.\n // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for\n // the client atomically, but we can't. So we opt to delete the IndexedDb\n // entries first to avoid potentially reviving a zombied client.\n if (this.webStorage) {\n for (const inactiveClient of inactiveClients) {\n this.webStorage.removeItem(\n this.zombiedClientLocalStorageKey(inactiveClient.clientId)\n );\n }\n }\n }\n }\n\n /**\n * Schedules a recurring timer to update the client metadata and to either\n * extend or acquire the primary lease if the client is eligible.\n */\n private scheduleClientMetadataAndPrimaryLeaseRefreshes(): void {\n this.clientMetadataRefresher = this.queue.enqueueAfterDelay(\n TimerId.ClientMetadataRefresh,\n CLIENT_METADATA_REFRESH_INTERVAL_MS,\n () => {\n return this.updateClientMetadataAndTryBecomePrimary()\n .then(() => this.maybeGarbageCollectMultiClientState())\n .then(() => this.scheduleClientMetadataAndPrimaryLeaseRefreshes());\n }\n );\n }\n\n /** Checks whether `client` is the local client. */\n private isLocalClient(client: DbPrimaryClient | null): boolean {\n return client ? client.ownerId === this.clientId : false;\n }\n\n /**\n * Evaluate the state of all active clients and determine whether the local\n * client is or can act as the holder of the primary lease. Returns whether\n * the client is eligible for the lease, but does not actually acquire it.\n * May return 'false' even if there is no active leaseholder and another\n * (foreground) client should become leaseholder instead.\n */\n private canActAsPrimary(\n txn: PersistenceTransaction\n ): PersistencePromise {\n if (this.forceOwningTab) {\n return PersistencePromise.resolve(true);\n }\n const store = primaryClientStore(txn);\n return store\n .get(DbPrimaryClientKey)\n .next(currentPrimary => {\n const currentLeaseIsValid =\n currentPrimary !== null &&\n this.isWithinAge(\n currentPrimary.leaseTimestampMs,\n MAX_PRIMARY_ELIGIBLE_AGE_MS\n ) &&\n !this.isClientZombied(currentPrimary.ownerId);\n\n // A client is eligible for the primary lease if:\n // - its network is enabled and the client's tab is in the foreground.\n // - its network is enabled and no other client's tab is in the\n // foreground.\n // - every clients network is disabled and the client's tab is in the\n // foreground.\n // - every clients network is disabled and no other client's tab is in\n // the foreground.\n // - the `forceOwningTab` setting was passed in.\n if (currentLeaseIsValid) {\n if (this.isLocalClient(currentPrimary) && this.networkEnabled) {\n return true;\n }\n\n if (!this.isLocalClient(currentPrimary)) {\n if (!currentPrimary!.allowTabSynchronization) {\n // Fail the `canActAsPrimary` check if the current leaseholder has\n // not opted into multi-tab synchronization. If this happens at\n // client startup, we reject the Promise returned by\n // `enablePersistence()` and the user can continue to use Firestore\n // with in-memory persistence.\n // If this fails during a lease refresh, we will instead block the\n // AsyncQueue from executing further operations. Note that this is\n // acceptable since mixing & matching different `synchronizeTabs`\n // settings is not supported.\n //\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can\n // no longer be turned off.\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG\n );\n }\n\n return false;\n }\n }\n\n if (this.networkEnabled && this.inForeground) {\n return true;\n }\n\n return clientMetadataStore(txn)\n .loadAll()\n .next(existingClients => {\n // Process all existing clients and determine whether at least one of\n // them is better suited to obtain the primary lease.\n const preferredCandidate = this.filterActiveClients(\n existingClients,\n MAX_PRIMARY_ELIGIBLE_AGE_MS\n ).find(otherClient => {\n if (this.clientId !== otherClient.clientId) {\n const otherClientHasBetterNetworkState =\n !this.networkEnabled && otherClient.networkEnabled;\n const otherClientHasBetterVisibility =\n !this.inForeground && otherClient.inForeground;\n const otherClientHasSameNetworkState =\n this.networkEnabled === otherClient.networkEnabled;\n if (\n otherClientHasBetterNetworkState ||\n (otherClientHasBetterVisibility &&\n otherClientHasSameNetworkState)\n ) {\n return true;\n }\n }\n return false;\n });\n return preferredCandidate === undefined;\n });\n })\n .next(canActAsPrimary => {\n if (this.isPrimary !== canActAsPrimary) {\n logDebug(\n LOG_TAG,\n `Client ${\n canActAsPrimary ? 'is' : 'is not'\n } eligible for a primary lease.`\n );\n }\n return canActAsPrimary;\n });\n }\n\n async shutdown(): Promise {\n // The shutdown() operations are idempotent and can be called even when\n // start() aborted (e.g. because it couldn't acquire the persistence lease).\n this._started = false;\n\n this.markClientZombied();\n if (this.clientMetadataRefresher) {\n this.clientMetadataRefresher.cancel();\n this.clientMetadataRefresher = null;\n }\n this.detachVisibilityHandler();\n this.detachWindowUnloadHook();\n\n // Use `SimpleDb.runTransaction` directly to avoid failing if another tab\n // has obtained the primary lease.\n await this.simpleDb.runTransaction(\n 'shutdown',\n 'readwrite',\n [DbPrimaryClientStore, DbClientMetadataStore],\n simpleDbTxn => {\n const persistenceTransaction = new IndexedDbTransaction(\n simpleDbTxn,\n ListenSequence.INVALID\n );\n return this.releasePrimaryLeaseIfHeld(persistenceTransaction).next(() =>\n this.removeClientMetadata(persistenceTransaction)\n );\n }\n );\n this.simpleDb.close();\n\n // Remove the entry marking the client as zombied from LocalStorage since\n // we successfully deleted its metadata from IndexedDb.\n this.removeClientZombiedEntry();\n }\n\n /**\n * Returns clients that are not zombied and have an updateTime within the\n * provided threshold.\n */\n private filterActiveClients(\n clients: DbClientMetadata[],\n activityThresholdMs: number\n ): DbClientMetadata[] {\n return clients.filter(\n client =>\n this.isWithinAge(client.updateTimeMs, activityThresholdMs) &&\n !this.isClientZombied(client.clientId)\n );\n }\n\n /**\n * Returns the IDs of the clients that are currently active. If multi-tab\n * is not supported, returns an array that only contains the local client's\n * ID.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n getActiveClients(): Promise {\n return this.runTransaction('getActiveClients', 'readonly', txn => {\n return clientMetadataStore(txn)\n .loadAll()\n .next(clients =>\n this.filterActiveClients(clients, MAX_CLIENT_AGE_MS).map(\n clientMetadata => clientMetadata.clientId\n )\n );\n });\n }\n\n get started(): boolean {\n return this._started;\n }\n\n getGlobalsCache(): GlobalsCache {\n debugAssert(\n this.started,\n 'Cannot initialize GlobalsCache before persistence is started.'\n );\n return this.globalsCache;\n }\n\n getMutationQueue(\n user: User,\n indexManager: IndexManager\n ): IndexedDbMutationQueue {\n debugAssert(\n this.started,\n 'Cannot initialize MutationQueue before persistence is started.'\n );\n return IndexedDbMutationQueue.forUser(\n user,\n this.serializer,\n indexManager,\n this.referenceDelegate\n );\n }\n\n getTargetCache(): IndexedDbTargetCache {\n debugAssert(\n this.started,\n 'Cannot initialize TargetCache before persistence is started.'\n );\n return this.targetCache;\n }\n\n getRemoteDocumentCache(): IndexedDbRemoteDocumentCache {\n debugAssert(\n this.started,\n 'Cannot initialize RemoteDocumentCache before persistence is started.'\n );\n return this.remoteDocumentCache;\n }\n\n getIndexManager(user: User): IndexManager {\n debugAssert(\n this.started,\n 'Cannot initialize IndexManager before persistence is started.'\n );\n return new IndexedDbIndexManager(\n user,\n this.serializer.remoteSerializer.databaseId\n );\n }\n\n getDocumentOverlayCache(user: User): DocumentOverlayCache {\n debugAssert(\n this.started,\n 'Cannot initialize IndexedDbDocumentOverlayCache before persistence is started.'\n );\n return IndexedDbDocumentOverlayCache.forUser(this.serializer, user);\n }\n\n getBundleCache(): BundleCache {\n debugAssert(\n this.started,\n 'Cannot initialize BundleCache before persistence is started.'\n );\n return this.bundleCache;\n }\n\n runTransaction(\n action: string,\n mode: PersistenceTransactionMode,\n transactionOperation: (\n transaction: PersistenceTransaction\n ) => PersistencePromise\n ): Promise {\n logDebug(LOG_TAG, 'Starting transaction:', action);\n\n const simpleDbMode = mode === 'readonly' ? 'readonly' : 'readwrite';\n const objectStores = getObjectStores(this.schemaVersion);\n\n let persistenceTransaction: PersistenceTransaction;\n\n // Do all transactions as readwrite against all object stores, since we\n // are the only reader/writer.\n return this.simpleDb\n .runTransaction(action, simpleDbMode, objectStores, simpleDbTxn => {\n persistenceTransaction = new IndexedDbTransaction(\n simpleDbTxn,\n this.listenSequence\n ? this.listenSequence.next()\n : ListenSequence.INVALID\n );\n\n if (mode === 'readwrite-primary') {\n // While we merely verify that we have (or can acquire) the lease\n // immediately, we wait to extend the primary lease until after\n // executing transactionOperation(). This ensures that even if the\n // transactionOperation takes a long time, we'll use a recent\n // leaseTimestampMs in the extended (or newly acquired) lease.\n return this.verifyPrimaryLease(persistenceTransaction)\n .next(holdsPrimaryLease => {\n if (holdsPrimaryLease) {\n return /* holdsPrimaryLease= */ true;\n }\n return this.canActAsPrimary(persistenceTransaction);\n })\n .next(holdsPrimaryLease => {\n if (!holdsPrimaryLease) {\n logError(\n `Failed to obtain primary lease for action '${action}'.`\n );\n this.isPrimary = false;\n this.queue.enqueueRetryable(() =>\n this.primaryStateListener(false)\n );\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_LOST_ERROR_MSG\n );\n }\n return transactionOperation(persistenceTransaction);\n })\n .next(result => {\n return this.acquireOrExtendPrimaryLease(\n persistenceTransaction\n ).next(() => result);\n });\n } else {\n return this.verifyAllowTabSynchronization(\n persistenceTransaction\n ).next(() => transactionOperation(persistenceTransaction));\n }\n })\n .then(result => {\n persistenceTransaction.raiseOnCommittedEvent();\n return result;\n });\n }\n\n /**\n * Verifies that the current tab is the primary leaseholder or alternatively\n * that the leaseholder has opted into multi-tab synchronization.\n */\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer\n // be turned off.\n private verifyAllowTabSynchronization(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const store = primaryClientStore(txn);\n return store.get(DbPrimaryClientKey).next(currentPrimary => {\n const currentLeaseIsValid =\n currentPrimary !== null &&\n this.isWithinAge(\n currentPrimary.leaseTimestampMs,\n MAX_PRIMARY_ELIGIBLE_AGE_MS\n ) &&\n !this.isClientZombied(currentPrimary.ownerId);\n\n if (currentLeaseIsValid && !this.isLocalClient(currentPrimary)) {\n if (\n !this.forceOwningTab &&\n (!this.allowTabSynchronization ||\n !currentPrimary!.allowTabSynchronization)\n ) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG\n );\n }\n }\n });\n }\n\n /**\n * Obtains or extends the new primary lease for the local client. This\n * method does not verify that the client is eligible for this lease.\n */\n private acquireOrExtendPrimaryLease(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const newPrimary: DbPrimaryClient = {\n ownerId: this.clientId,\n allowTabSynchronization: this.allowTabSynchronization,\n leaseTimestampMs: Date.now()\n };\n return primaryClientStore(txn).put(DbPrimaryClientKey, newPrimary);\n }\n\n static isAvailable(): boolean {\n return SimpleDb.isAvailable();\n }\n\n /** Checks the primary lease and removes it if we are the current primary. */\n private releasePrimaryLeaseIfHeld(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const store = primaryClientStore(txn);\n return store.get(DbPrimaryClientKey).next(primaryClient => {\n if (this.isLocalClient(primaryClient)) {\n logDebug(LOG_TAG, 'Releasing primary lease.');\n return store.delete(DbPrimaryClientKey);\n } else {\n return PersistencePromise.resolve();\n }\n });\n }\n\n /** Verifies that `updateTimeMs` is within `maxAgeMs`. */\n private isWithinAge(updateTimeMs: number, maxAgeMs: number): boolean {\n const now = Date.now();\n const minAcceptable = now - maxAgeMs;\n const maxAcceptable = now;\n if (updateTimeMs < minAcceptable) {\n return false;\n } else if (updateTimeMs > maxAcceptable) {\n logError(\n `Detected an update time that is in the future: ${updateTimeMs} > ${maxAcceptable}`\n );\n return false;\n }\n\n return true;\n }\n\n private attachVisibilityHandler(): void {\n if (\n this.document !== null &&\n typeof this.document.addEventListener === 'function'\n ) {\n this.documentVisibilityHandler = () => {\n this.queue.enqueueAndForget(() => {\n this.inForeground = this.document!.visibilityState === 'visible';\n return this.updateClientMetadataAndTryBecomePrimary();\n });\n };\n\n this.document.addEventListener(\n 'visibilitychange',\n this.documentVisibilityHandler\n );\n\n this.inForeground = this.document.visibilityState === 'visible';\n }\n }\n\n private detachVisibilityHandler(): void {\n if (this.documentVisibilityHandler) {\n debugAssert(\n this.document !== null &&\n typeof this.document.addEventListener === 'function',\n \"Expected 'document.addEventListener' to be a function\"\n );\n this.document.removeEventListener(\n 'visibilitychange',\n this.documentVisibilityHandler\n );\n this.documentVisibilityHandler = null;\n }\n }\n\n /**\n * Attaches a window.unload handler that will synchronously write our\n * clientId to a \"zombie client id\" location in LocalStorage. This can be used\n * by tabs trying to acquire the primary lease to determine that the lease\n * is no longer valid even if the timestamp is recent. This is particularly\n * important for the refresh case (so the tab correctly re-acquires the\n * primary lease). LocalStorage is used for this rather than IndexedDb because\n * it is a synchronous API and so can be used reliably from an unload\n * handler.\n */\n private attachWindowUnloadHook(): void {\n if (typeof this.window?.addEventListener === 'function') {\n this.windowUnloadHandler = () => {\n // Note: In theory, this should be scheduled on the AsyncQueue since it\n // accesses internal state. We execute this code directly during shutdown\n // to make sure it gets a chance to run.\n this.markClientZombied();\n\n const safariIndexdbBugVersionRegex = /(?:Version|Mobile)\\/1[456]/;\n if (\n isSafari() &&\n (navigator.appVersion.match(safariIndexdbBugVersionRegex) ||\n navigator.userAgent.match(safariIndexdbBugVersionRegex))\n ) {\n // On Safari 14, 15, and 16, we do not run any cleanup actions as it might\n // trigger a bug that prevents Safari from re-opening IndexedDB during\n // the next page load.\n // See https://bugs.webkit.org/show_bug.cgi?id=226547\n this.queue.enterRestrictedMode(/* purgeExistingTasks= */ true);\n }\n\n this.queue.enqueueAndForget(() => {\n // Attempt graceful shutdown (including releasing our primary lease),\n // but there's no guarantee it will complete.\n return this.shutdown();\n });\n };\n this.window.addEventListener('pagehide', this.windowUnloadHandler);\n }\n }\n\n private detachWindowUnloadHook(): void {\n if (this.windowUnloadHandler) {\n debugAssert(\n typeof this.window?.removeEventListener === 'function',\n \"Expected 'window.removeEventListener' to be a function\"\n );\n this.window!.removeEventListener('pagehide', this.windowUnloadHandler);\n this.windowUnloadHandler = null;\n }\n }\n\n /**\n * Returns whether a client is \"zombied\" based on its LocalStorage entry.\n * Clients become zombied when their tab closes without running all of the\n * cleanup logic in `shutdown()`.\n */\n private isClientZombied(clientId: ClientId): boolean {\n try {\n const isZombied =\n this.webStorage?.getItem(\n this.zombiedClientLocalStorageKey(clientId)\n ) !== null;\n logDebug(\n LOG_TAG,\n `Client '${clientId}' ${\n isZombied ? 'is' : 'is not'\n } zombied in LocalStorage`\n );\n return isZombied;\n } catch (e) {\n // Gracefully handle if LocalStorage isn't working.\n logError(LOG_TAG, 'Failed to get zombied client id.', e);\n return false;\n }\n }\n\n /**\n * Record client as zombied (a client that had its tab closed). Zombied\n * clients are ignored during primary tab selection.\n */\n private markClientZombied(): void {\n if (!this.webStorage) {\n return;\n }\n try {\n this.webStorage.setItem(\n this.zombiedClientLocalStorageKey(this.clientId),\n String(Date.now())\n );\n } catch (e) {\n // Gracefully handle if LocalStorage isn't available / working.\n logError('Failed to set zombie client id.', e);\n }\n }\n\n /** Removes the zombied client entry if it exists. */\n private removeClientZombiedEntry(): void {\n if (!this.webStorage) {\n return;\n }\n try {\n this.webStorage.removeItem(\n this.zombiedClientLocalStorageKey(this.clientId)\n );\n } catch (e) {\n // Ignore\n }\n }\n\n private zombiedClientLocalStorageKey(clientId: ClientId): string {\n return `${ZOMBIED_CLIENTS_KEY_PREFIX}_${this.persistenceKey}_${clientId}`;\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the primary client object store.\n */\nfunction primaryClientStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbPrimaryClientStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the client metadata object store.\n */\nfunction clientMetadataStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbClientMetadataStore\n );\n}\n\n/**\n * Generates a string used as a prefix when storing data in IndexedDB and\n * LocalStorage.\n */\nexport function indexedDbStoragePrefix(\n databaseId: DatabaseId,\n persistenceKey: string\n): string {\n // Use two different prefix formats:\n //\n // * firestore / persistenceKey / projectID . databaseID / ...\n // * firestore / persistenceKey / projectID / ...\n //\n // projectIDs are DNS-compatible names and cannot contain dots\n // so there's no danger of collisions.\n let database = databaseId.projectId;\n if (!databaseId.isDefaultDatabase) {\n database += '.' + databaseId.database;\n }\n\n return 'firestore/' + persistenceKey + '/' + database + '/';\n}\n\nexport async function indexedDbClearPersistence(\n persistenceKey: string\n): Promise {\n if (!SimpleDb.isAvailable()) {\n return Promise.resolve();\n }\n const dbName = persistenceKey + MAIN_DATABASE;\n await SimpleDb.delete(dbName);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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(\n batch !== null,\n 0x90f9,\n 'Attempt to reject nonexistent batch!'\n );\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 0xbd9d,\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 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 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { BatchId, MutationBatchState, TargetId } from '../core/types';\nimport { debugAssert } from '../util/assert';\n\nimport { ClientId } from './shared_client_state';\nimport { QueryTargetState } from './shared_client_state_syncer';\n\n// The format of the LocalStorage key that stores the client state is:\n// firestore_clients__\nexport const CLIENT_STATE_KEY_PREFIX = 'firestore_clients';\n\n/** Assembles the key for a client state in WebStorage */\nexport function createWebStorageClientStateKey(\n persistenceKey: string,\n clientId: ClientId\n): string {\n debugAssert(\n clientId.indexOf('_') === -1,\n `Client key cannot contain '_', but was '${clientId}'`\n );\n\n return `${CLIENT_STATE_KEY_PREFIX}_${persistenceKey}_${clientId}`;\n}\n\n/**\n * The JSON representation of a clients's metadata as used during WebStorage\n * serialization. The ClientId is omitted here as it is encoded as part of the\n * key.\n */\nexport interface ClientStateSchema {\n activeTargetIds: number[];\n updateTimeMs: number;\n}\n\n// The format of the WebStorage key that stores the mutation state is:\n// firestore_mutations__\n// (for unauthenticated users)\n// or: firestore_mutations___\n//\n// 'user_uid' is last to avoid needing to escape '_' characters that it might\n// contain.\nexport const MUTATION_BATCH_KEY_PREFIX = 'firestore_mutations';\n\n/** Assembles the key for a mutation batch in WebStorage */\nexport function createWebStorageMutationBatchKey(\n persistenceKey: string,\n user: User,\n batchId: BatchId\n): string {\n let mutationKey = `${MUTATION_BATCH_KEY_PREFIX}_${persistenceKey}_${batchId}`;\n\n if (user.isAuthenticated()) {\n mutationKey += `_${user.uid}`;\n }\n\n return mutationKey;\n}\n\n/**\n * The JSON representation of a mutation batch's metadata as used during\n * WebStorage serialization. The UserId and BatchId is omitted as it is\n * encoded as part of the key.\n */\nexport interface MutationMetadataSchema {\n state: MutationBatchState;\n error?: { code: string; message: string }; // Only set when state === 'rejected'\n updateTimeMs: number;\n}\n\n// The format of the WebStorage key that stores a query target's metadata is:\n// firestore_targets__\nexport const QUERY_TARGET_KEY_PREFIX = 'firestore_targets';\n\n/** Assembles the key for a query state in WebStorage */\nexport function createWebStorageQueryTargetMetadataKey(\n persistenceKey: string,\n targetId: TargetId\n): string {\n return `${QUERY_TARGET_KEY_PREFIX}_${persistenceKey}_${targetId}`;\n}\n\n/**\n * The JSON representation of a query target's state as used during WebStorage\n * serialization. The TargetId is omitted as it is encoded as part of the key.\n */\nexport interface QueryTargetStateSchema {\n state: QueryTargetState;\n error?: { code: string; message: string }; // Only set when state === 'rejected'\n updateTimeMs: number;\n}\n\n// The WebStorage prefix that stores the primary tab's online state. The\n// format of the key is:\n// firestore_online_state_\nexport const ONLINE_STATE_KEY_PREFIX = 'firestore_online_state';\n\n/** Assembles the key for the online state of the primary tab. */\nexport function createWebStorageOnlineStateKey(persistenceKey: string): string {\n return `${ONLINE_STATE_KEY_PREFIX}_${persistenceKey}`;\n}\n\n// The WebStorage prefix that plays as a event to indicate the remote documents\n// might have changed due to some secondary tabs loading a bundle.\n// format of the key is:\n// firestore_bundle_loaded_v2_\n// The version ending with \"v2\" stores the list of modified collection groups.\nexport const BUNDLE_LOADED_KEY_PREFIX = 'firestore_bundle_loaded_v2';\nexport function createBundleLoadedKey(persistenceKey: string): string {\n return `${BUNDLE_LOADED_KEY_PREFIX}_${persistenceKey}`;\n}\n\n/**\n * The JSON representation of the system's online state, as written by the\n * primary client.\n */\nexport interface SharedOnlineStateSchema {\n /**\n * The clientId of the client that wrote this onlineState value. Tracked so\n * that on startup, clients can check if this client is still active when\n * determining whether to apply this value or not.\n */\n readonly clientId: string;\n readonly onlineState: string;\n}\n\n// The WebStorage key prefix for the key that stores the last sequence number allocated. The key\n// looks like 'firestore_sequence_number_'.\nexport const SEQUENCE_NUMBER_KEY_PREFIX = 'firestore_sequence_number';\n\n/** Assembles the key for the current sequence number. */\nexport function createWebStorageSequenceNumberKey(\n persistenceKey: string\n): string {\n return `${SEQUENCE_NUMBER_KEY_PREFIX}_${persistenceKey}`;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { ListenSequence } from '../core/listen_sequence';\nimport {\n BatchId,\n ListenSequenceNumber,\n MutationBatchState,\n OnlineState,\n TargetId\n} from '../core/types';\nimport { TargetIdSet, targetIdSet } from '../model/collections';\nimport { hardAssert, debugAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logError, logDebug } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport { isSafeInteger, WindowLike } from '../util/types';\n\nimport {\n CLIENT_STATE_KEY_PREFIX,\n ClientStateSchema,\n createBundleLoadedKey,\n createWebStorageClientStateKey,\n createWebStorageMutationBatchKey,\n createWebStorageOnlineStateKey,\n createWebStorageQueryTargetMetadataKey,\n createWebStorageSequenceNumberKey,\n MUTATION_BATCH_KEY_PREFIX,\n MutationMetadataSchema,\n QUERY_TARGET_KEY_PREFIX,\n QueryTargetStateSchema,\n SharedOnlineStateSchema\n} from './shared_client_state_schema';\nimport {\n QueryTargetState,\n SharedClientStateSyncer\n} from './shared_client_state_syncer';\n\nconst LOG_TAG = 'SharedClientState';\n\n/**\n * A randomly-generated key assigned to each Firestore instance at startup.\n */\nexport type ClientId = string;\n\n/**\n * A `SharedClientState` keeps track of the global state of the mutations\n * and query targets for all active clients with the same persistence key (i.e.\n * project ID and FirebaseApp name). It relays local changes to other clients\n * and updates its local state as new state is observed.\n *\n * `SharedClientState` is primarily used for synchronization in Multi-Tab\n * environments. Each tab is responsible for registering its active query\n * targets and mutations. `SharedClientState` will then notify the listener\n * assigned to `.syncEngine` for updates to mutations and queries that\n * originated in other clients.\n *\n * To receive notifications, `.syncEngine` and `.onlineStateHandler` has to be\n * assigned before calling `start()`.\n */\nexport interface SharedClientState {\n onlineStateHandler: ((onlineState: OnlineState) => void) | null;\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null;\n\n /** Registers the Mutation Batch ID of a newly pending mutation. */\n addPendingMutation(batchId: BatchId): void;\n\n /**\n * Records that a pending mutation has been acknowledged or rejected.\n * Called by the primary client to notify secondary clients of mutation\n * results as they come back from the backend.\n */\n updateMutationState(\n batchId: BatchId,\n state: 'acknowledged' | 'rejected',\n error?: FirestoreError\n ): void;\n\n /**\n * Associates a new Query Target ID with the local Firestore client. Returns\n * the new query state for the query (which can be 'current' if the query is\n * already associated with another tab).\n *\n * If the target id is already associated with local client, the method simply\n * returns its `QueryTargetState`.\n */\n addLocalQueryTarget(\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 0x77ac,\n 'Found non-numeric sequence number',\n { seqString }\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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 * Utilities for dealing with node.js-style APIs. See nodePromise for more\n * details.\n */\n\n/**\n * Creates a node-style callback that resolves or rejects a new Promise. The\n * callback is passed to the given action which can then use the callback as\n * a parameter to a node-style function.\n *\n * The intent is to directly bridge a node-style function (which takes a\n * callback) into a Promise without manually converting between the node-style\n * callback and the promise at each call.\n *\n * In effect it allows you to convert:\n *\n * @example\n * new Promise((resolve: (value?: fs.Stats) => void,\n * reject: (error?: any) => void) => {\n * fs.stat(path, (error?: any, stat?: fs.Stats) => {\n * if (error) {\n * reject(error);\n * } else {\n * resolve(stat);\n * }\n * });\n * });\n *\n * Into\n * @example\n * nodePromise((callback: NodeCallback) => {\n * fs.stat(path, callback);\n * });\n *\n * @param action - a function that takes a node-style callback as an argument\n * and then uses that callback to invoke some node-style API.\n * @returns a new Promise which will be rejected if the callback is given the\n * first Error parameter or will resolve to the value given otherwise.\n */\nexport function nodePromise(\n action: (callback: NodeCallback) => void\n): Promise {\n return new Promise(\n (resolve: (value: R) => void, reject: (error?: unknown) => void) => {\n action((error?: unknown, value?: R) => {\n if (error) {\n reject(error);\n } else {\n resolve(value!);\n }\n });\n }\n );\n}\n\n/**\n * A node-style callback which passes an Error as the first argument if there\n * was an error, or passes null and a proper value\n */\nexport interface NodeCallback {\n (error?: unknown, value?: R): void;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// Note: We have to use a package import here to avoid build errors such as\n// https://github.com/firebase/firebase-js-sdk/issues/5983\nimport * as grpc from '@grpc/grpc-js';\n\nimport { Token } from '../../api/credentials';\nimport { DatabaseInfo } from '../../core/database_info';\nimport { SDK_VERSION } from '../../core/version';\nimport { ResourcePath } from '../../model/path';\nimport { Connection, Stream } from '../../remote/connection';\nimport { mapCodeFromRpcCode } from '../../remote/rpc_error';\nimport { StreamBridge } from '../../remote/stream_bridge';\nimport { hardAssert } from '../../util/assert';\nimport { generateUniqueDebugId } from '../../util/debug_uid';\nimport { FirestoreError } from '../../util/error';\nimport { logError, logDebug, logWarn } from '../../util/log';\nimport { NodeCallback, nodePromise } from '../../util/node_api';\nimport { Deferred } from '../../util/promise';\n\n// TODO: Fetch runtime version from grpc-js/package.json instead\n// when there's a cleaner way to dynamic require JSON in both Node ESM and CJS\nconst grpcVersion = '__GRPC_VERSION__';\n\nconst LOG_TAG = 'GrpcConnection';\nconst X_GOOG_API_CLIENT_VALUE = `gl-node/${process.versions.node} fire/${SDK_VERSION} grpc/${grpcVersion}`;\n\nfunction createMetadata(\n databasePath: string,\n authToken: Token | null,\n appCheckToken: Token | null,\n appId: string\n): grpc.Metadata {\n hardAssert(\n authToken === null || authToken.type === 'OAuth',\n 0x9048,\n 'If provided, token must be OAuth'\n );\n const metadata = new grpc.Metadata();\n if (authToken) {\n authToken.headers.forEach((value, key) => metadata.set(key, value));\n }\n if (appCheckToken) {\n appCheckToken.headers.forEach((value, key) => metadata.set(key, value));\n }\n if (appId) {\n metadata.set('X-Firebase-GMPID', appId);\n }\n metadata.set('X-Goog-Api-Client', X_GOOG_API_CLIENT_VALUE);\n // These headers are used to improve routing and project isolation by the\n // backend.\n // TODO(b/199767712): We are keeping 'Google-Cloud-Resource-Prefix' until Emulators can be\n // released with cl/428820046. Currently blocked because Emulators are now built with Java\n // 11 from Google3.\n metadata.set('Google-Cloud-Resource-Prefix', databasePath);\n metadata.set('x-goog-request-params', databasePath);\n return metadata;\n}\n\n// The type of these stubs is dynamically generated by the GRPC runtime\n// from the protocol buffer.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype GeneratedGrpcStub = any;\n\n/**\n * A Connection implemented by GRPC-Node.\n */\nexport class GrpcConnection implements Connection {\n private readonly databasePath: string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private readonly firestore: any;\n\n // We cache stubs for the most-recently-used token.\n private cachedStub: GeneratedGrpcStub | null = null;\n\n get shouldResourcePathBeIncludedInRequest(): boolean {\n // Both `invokeRPC()` and `invokeStreamingRPC()` ignore their `path` arguments, and expect\n // the \"path\" to be part of the given `request`.\n return true;\n }\n\n constructor(protos: grpc.GrpcObject, private databaseInfo: DatabaseInfo) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n this.firestore = (protos as any)['google']['firestore']['v1'];\n this.databasePath = `projects/${databaseInfo.databaseId.projectId}/databases/${databaseInfo.databaseId.database}`;\n }\n\n private ensureActiveStub(): GeneratedGrpcStub {\n if (!this.cachedStub) {\n logDebug(LOG_TAG, 'Creating Firestore stub.');\n const credentials = this.databaseInfo.ssl\n ? grpc.credentials.createSsl()\n : grpc.credentials.createInsecure();\n this.cachedStub = new this.firestore.Firestore(\n this.databaseInfo.host,\n credentials\n );\n }\n return this.cachedStub;\n }\n\n invokeRPC(\n rpcName: string,\n path: ResourcePath,\n request: Req,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Promise {\n const streamId = generateUniqueDebugId();\n const stub = this.ensureActiveStub();\n const metadata = createMetadata(\n this.databasePath,\n authToken,\n appCheckToken,\n this.databaseInfo.appId\n );\n const jsonRequest = { database: this.databasePath, ...request };\n\n return nodePromise((callback: NodeCallback) => {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' ${streamId} invoked with request:`,\n request\n );\n return stub[rpcName](\n jsonRequest,\n metadata,\n (grpcError?: grpc.ServiceError, value?: Resp) => {\n if (grpcError) {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' ${streamId} failed with error:`,\n grpcError\n );\n callback(\n new FirestoreError(\n mapCodeFromRpcCode(grpcError.code),\n grpcError.message\n )\n );\n } else {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' ${streamId} completed with response:`,\n value\n );\n callback(undefined, value);\n }\n }\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 const streamId = generateUniqueDebugId();\n const results: Resp[] = [];\n const responseDeferred = new Deferred();\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' ${streamId} invoked (streaming) with request:`,\n request\n );\n const stub = this.ensureActiveStub();\n const metadata = createMetadata(\n this.databasePath,\n authToken,\n appCheckToken,\n this.databaseInfo.appId\n );\n const jsonRequest = { ...request, database: this.databasePath };\n const stream = stub[rpcName](jsonRequest, metadata);\n let callbackFired = false;\n stream.on('data', (response: Resp) => {\n logDebug(\n LOG_TAG,\n `RPC ${rpcName} ${streamId} received result:`,\n response\n );\n results.push(response);\n if (\n expectedResponseCount !== undefined &&\n results.length === expectedResponseCount\n ) {\n callbackFired = true;\n responseDeferred.resolve(results);\n }\n });\n stream.on('end', () => {\n logDebug(LOG_TAG, `RPC '${rpcName}' ${streamId} completed.`);\n if (!callbackFired) {\n callbackFired = true;\n responseDeferred.resolve(results);\n }\n });\n stream.on('error', (grpcError: grpc.ServiceError) => {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' ${streamId} failed with error:`,\n grpcError\n );\n const code = mapCodeFromRpcCode(grpcError.code);\n responseDeferred.reject(new FirestoreError(code, grpcError.message));\n });\n\n return responseDeferred.promise;\n }\n\n // TODO(mikelehen): This \"method\" is a monster. Should be refactored.\n openStream(\n rpcName: string,\n authToken: Token | null,\n appCheckToken: Token | null\n ): Stream {\n const streamId = generateUniqueDebugId();\n const stub = this.ensureActiveStub();\n const metadata = createMetadata(\n this.databasePath,\n authToken,\n appCheckToken,\n this.databaseInfo.appId\n );\n const grpcStream = stub[rpcName](metadata);\n\n let closed = false;\n const close = (err?: FirestoreError): void => {\n if (!closed) {\n closed = true;\n stream.callOnClose(err);\n grpcStream.end();\n }\n };\n\n const stream = new StreamBridge({\n sendFn: (msg: Req) => {\n if (!closed) {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} sending:`,\n msg\n );\n try {\n grpcStream.write(msg);\n } catch (e) {\n // This probably means we didn't conform to the proto. Make sure to\n // log the message we sent.\n logError('Failure sending:', msg);\n logError('Error:', e);\n throw e;\n }\n } else {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} ` +\n 'not sending because gRPC stream is closed:',\n msg\n );\n }\n },\n closeFn: () => {\n logDebug(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} closed locally via close().`\n );\n close();\n }\n });\n\n let onConnectedSent = false;\n grpcStream.on('data', (msg: Resp) => {\n if (!closed) {\n logDebug(LOG_TAG, `RPC '${rpcName}' stream ${streamId} received:`, msg);\n // Emulate the \"onConnected\" event that WebChannelConnection sends.\n if (!onConnectedSent) {\n stream.callOnConnected();\n onConnectedSent = true;\n }\n stream.callOnMessage(msg);\n }\n });\n\n grpcStream.on('end', () => {\n logDebug(LOG_TAG, `RPC '${rpcName}' stream ${streamId} ended.`);\n close();\n });\n\n grpcStream.on('error', (grpcError: grpc.ServiceError) => {\n if (!closed) {\n logWarn(\n LOG_TAG,\n `RPC '${rpcName}' stream ${streamId} error. Code:`,\n grpcError.code,\n 'Message:',\n grpcError.message\n );\n const code = mapCodeFromRpcCode(grpcError.code);\n close(new FirestoreError(code, grpcError.message));\n }\n });\n\n logDebug(\n LOG_TAG,\n `Opening RPC '${rpcName}' stream ${streamId} ` +\n `to ${this.databaseInfo.host}`\n );\n // TODO(dimond): Since grpc has no explicit open status (or does it?) we\n // simulate an onOpen in the next loop after the stream had it's listeners\n // registered\n setTimeout(() => {\n stream.callOnOpen();\n }, 0);\n\n return stream;\n }\n\n /**\n * Closes and cleans up any resources associated with the GrpcConnection.\n * If a gRPC client has been generated for this connection, the gRPC client\n * is closed. Failure to call terminate on a GrpcConnection can result\n * in leaked resources of the gRPC client.\n */\n terminate(): void {\n if (this.cachedStub) {\n this.cachedStub.close();\n this.cachedStub = undefined;\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 { join, resolve, isAbsolute } from 'path';\n\n// Note: We have to use a package import here to avoid build errors such as\n// https://github.com/firebase/firebase-js-sdk/issues/5983\n\nimport * as grpc from '@grpc/grpc-js';\nimport * as protoLoader from '@grpc/proto-loader';\n// only used in tests\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport { IConversionOptions, Root } from 'protobufjs';\n\nimport * as protos from '../../protos/protos.json';\n\n/** Used by tests so we can match @grpc/proto-loader behavior. */\nexport const protoLoaderOptions: IConversionOptions = {\n longs: String,\n enums: String,\n defaults: true,\n oneofs: false\n};\n\n/**\n * Loads the protocol buffer definitions for Firestore.\n *\n * @returns The GrpcObject representing our protos.\n */\nexport function loadProtos(): grpc.GrpcObject {\n const packageDefinition = protoLoader.fromJSON(protos, protoLoaderOptions);\n return grpc.loadPackageDefinition(packageDefinition);\n}\n\n/** Used by tests so we can directly create ProtobufJS proto message objects from JSON protos. */\nexport function loadRawProtos(): Root {\n const root = resolve(\n __dirname,\n process.env.FIRESTORE_PROTO_ROOT || '../../protos'\n );\n const firestoreProtoFile = join(root, 'google/firestore/v1/firestore.proto');\n\n const protoRoot = new Root();\n // Override the resolvePath function to look for protos in the 'root'\n // directory.\n protoRoot.resolvePath = (origin: string, target: string) => {\n if (isAbsolute(target)) {\n return target;\n }\n return join(root, target);\n };\n\n protoRoot.loadSync(firestoreProtoFile);\n protoRoot.resolveAll();\n return protoRoot;\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 { GrpcConnection } from './grpc_connection';\nimport { loadProtos } from './load_protos';\n\n/** Loads the GRPC stack */\nexport function newConnection(databaseInfo: DatabaseInfo): Connection {\n const protos = loadProtos();\n return new GrpcConnection(protos, databaseInfo);\n}\n\n/** Return the Platform-specific connectivity monitor. */\nexport function newConnectivityMonitor(): ConnectivityMonitor {\n return new NoopConnectivityMonitor();\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 if (process.env.USE_MOCK_PERSISTENCE === 'YES') {\n // eslint-disable-next-line no-restricted-globals\n return window;\n }\n\n return null;\n}\n\n/** The Platform's 'document' implementation or null if not available. */\nexport function getDocument(): Document | null {\n return null;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** 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= */ false);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { 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 0x7a5a,\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 0xda08,\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 0x3186,\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, 0xd7c2, 'Missing entity in write response for `key`', {\n key\n });\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 0xfcd7,\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 0xf76d,\n 'unsupported combination of changes: `change` after `oldChange`',\n {\n change,\n oldChange\n }\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 { 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LoadBundleTaskProgress } from '@firebase/firestore-types';\n\nimport { LocalStore } from '../local/local_store';\nimport {\n localStoreApplyBundledDocuments,\n localStoreSaveNamedQuery\n} from '../local/local_store_impl';\nimport { documentKeySet, DocumentKeySet } from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport {\n BundleMetadata as ProtoBundleMetadata,\n NamedQuery as ProtoNamedQuery\n} from '../protos/firestore_bundle_proto';\nimport { Timestamp as ApiTimestamp } from '../protos/firestore_proto_api';\nimport {\n fromDocument,\n fromName,\n fromVersion,\n JsonProtoSerializer\n} from '../remote/serializer';\nimport { debugAssert } from '../util/assert';\nimport { SizedBundleElement } from '../util/bundle_reader';\n\nimport {\n BundleConverter,\n BundledDocument,\n BundledDocuments,\n BundleLoadResult\n} from './bundle';\nimport { SnapshotVersion } from './snapshot_version';\n\n/**\n * Helper to convert objects from bundles to model objects in the SDK.\n */\nexport class BundleConverterImpl implements BundleConverter {\n constructor(private readonly serializer: JsonProtoSerializer) {}\n\n toDocumentKey(name: string): DocumentKey {\n return fromName(this.serializer, name);\n }\n\n /**\n * Converts a BundleDocument to a MutableDocument.\n */\n toMutableDocument(bundledDoc: BundledDocument): MutableDocument {\n if (bundledDoc.metadata.exists) {\n debugAssert(\n !!bundledDoc.document,\n 'Document is undefined when metadata.exist is true.'\n );\n return fromDocument(this.serializer, bundledDoc.document!, false);\n } else {\n return MutableDocument.newNoDocument(\n this.toDocumentKey(bundledDoc.metadata.name!),\n this.toSnapshotVersion(bundledDoc.metadata.readTime!)\n );\n }\n }\n\n toSnapshotVersion(time: ApiTimestamp): SnapshotVersion {\n return fromVersion(time);\n }\n}\n\n/**\n * A class to process the elements from a bundle, and optionally load them into local\n * storage and provide progress update while loading.\n */\nexport class BundleLoader {\n /** The current progress of loading */\n private progress: LoadBundleTaskProgress;\n /** Batched queries to be saved into storage */\n private _queries: ProtoNamedQuery[] = [];\n /** Batched documents to be saved into storage */\n private _documents: BundledDocuments = [];\n /** The collection groups affected by this bundle. */\n private collectionGroups = new Set();\n\n constructor(\n private bundleMetadata: ProtoBundleMetadata,\n private serializer: JsonProtoSerializer\n ) {\n this.progress = bundleInitialProgress(bundleMetadata);\n }\n\n /**\n * Returns the named queries that have been parsed from the SizeBundleElements added by\n * calling {@link adSizedElement}.\n */\n get queries(): ProtoNamedQuery[] {\n return this._queries;\n }\n\n /**\n * Returns the BundledDocuments that have been parsed from the SizeBundleElements added by\n * calling {@link addSizedElement}.\n */\n get documents(): BundledDocuments {\n return this._documents;\n }\n\n /**\n * Adds an element from the bundle to the loader.\n *\n * Returns a new progress if adding the element leads to a new progress,\n * otherwise returns null.\n */\n addSizedElement(element: SizedBundleElement): LoadBundleTaskProgress | null {\n debugAssert(!element.isBundleMetadata(), 'Unexpected bundle metadata.');\n\n this.progress.bytesLoaded += element.byteLength;\n\n let documentsLoaded = this.progress.documentsLoaded;\n\n if (element.payload.namedQuery) {\n this._queries.push(element.payload.namedQuery);\n } else if (element.payload.documentMetadata) {\n this._documents.push({ metadata: element.payload.documentMetadata });\n if (!element.payload.documentMetadata.exists) {\n ++documentsLoaded;\n }\n const path = ResourcePath.fromString(\n element.payload.documentMetadata.name!\n );\n debugAssert(\n path.length >= 2,\n 'The document name does not point to a document.'\n );\n this.collectionGroups.add(path.get(path.length - 2));\n } else if (element.payload.document) {\n debugAssert(\n this._documents.length > 0 &&\n this._documents[this._documents.length - 1].metadata.name ===\n element.payload.document.name,\n 'The document being added does not match the stored metadata.'\n );\n this._documents[this._documents.length - 1].document =\n element.payload.document;\n ++documentsLoaded;\n }\n\n if (documentsLoaded !== this.progress.documentsLoaded) {\n this.progress.documentsLoaded = documentsLoaded;\n return { ...this.progress };\n }\n\n return null;\n }\n\n private getQueryDocumentMapping(\n documents: BundledDocuments\n ): Map {\n const queryDocumentMap = new Map();\n const bundleConverter = new BundleConverterImpl(this.serializer);\n for (const bundleDoc of documents) {\n if (bundleDoc.metadata.queries) {\n const documentKey = bundleConverter.toDocumentKey(\n bundleDoc.metadata.name!\n );\n for (const queryName of bundleDoc.metadata.queries) {\n const documentKeys = (\n queryDocumentMap.get(queryName) || documentKeySet()\n ).add(documentKey);\n queryDocumentMap.set(queryName, documentKeys);\n }\n }\n }\n\n return queryDocumentMap;\n }\n\n /**\n * Update the progress to 'Success' and return the updated progress.\n */\n async completeAndStoreAsync(\n localStore: LocalStore\n ): Promise {\n debugAssert(\n this._documents[this._documents.length - 1]?.metadata.exists !== true ||\n !!this._documents[this._documents.length - 1].document,\n 'Bundled documents end with a document metadata element instead of a document.'\n );\n debugAssert(!!this.bundleMetadata.id, 'Bundle ID must be set.');\n\n const changedDocs = await localStoreApplyBundledDocuments(\n localStore,\n new BundleConverterImpl(this.serializer),\n this._documents,\n this.bundleMetadata.id!\n );\n\n const queryDocumentMap = this.getQueryDocumentMapping(this.documents);\n\n for (const q of this._queries) {\n await localStoreSaveNamedQuery(\n localStore,\n q,\n queryDocumentMap.get(q.name!)\n );\n }\n\n this.progress.taskState = 'Success';\n return {\n progress: this.progress,\n changedCollectionGroups: this.collectionGroups,\n changedDocs\n };\n }\n}\n\n/**\n * Returns a `LoadBundleTaskProgress` representing the initial progress of\n * loading a bundle.\n */\nexport function bundleInitialProgress(\n metadata: ProtoBundleMetadata\n): LoadBundleTaskProgress {\n return {\n taskState: 'Running',\n documentsLoaded: 0,\n bytesLoaded: 0,\n totalDocuments: metadata.totalDocuments!,\n totalBytes: metadata.totalBytes!\n };\n}\n\n/**\n * Returns a `LoadBundleTaskProgress` representing the progress that the loading\n * has succeeded.\n */\nexport function bundleSuccessProgress(\n metadata: ProtoBundleMetadata\n): LoadBundleTaskProgress {\n return {\n taskState: 'Success',\n documentsLoaded: metadata.totalDocuments!,\n bytesLoaded: metadata.totalBytes!,\n totalDocuments: metadata.totalDocuments!,\n totalBytes: metadata.totalBytes!\n };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { QueryResult } from '../local/local_store_impl';\nimport {\n documentKeySet,\n DocumentKeySet,\n DocumentMap\n} from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { DocumentSet } from '../model/document_set';\nimport { TargetChange } from '../remote/remote_event';\nimport { debugAssert, fail } from '../util/assert';\n\nimport { LimitType, newQueryComparator, Query, queryMatches } from './query';\nimport { OnlineState } from './types';\nimport {\n ChangeType,\n DocumentChangeSet,\n SyncState,\n ViewSnapshot\n} from './view_snapshot';\n\nexport type LimboDocumentChange = AddedLimboDocument | RemovedLimboDocument;\nexport class AddedLimboDocument {\n constructor(public key: DocumentKey) {}\n}\nexport class RemovedLimboDocument {\n constructor(public key: DocumentKey) {}\n}\n\n/** The result of applying a set of doc changes to a view. */\nexport interface ViewDocumentChanges {\n /** The new set of docs that should be in the view. */\n documentSet: DocumentSet;\n /** The diff of these docs with the previous set of docs. */\n changeSet: DocumentChangeSet;\n /**\n * Whether the set of documents passed in was not sufficient to calculate the\n * new state of the view and there needs to be another pass based on the\n * local cache.\n */\n needsRefill: boolean;\n\n mutatedKeys: DocumentKeySet;\n}\n\nexport interface ViewChange {\n snapshot?: ViewSnapshot;\n limboChanges: LimboDocumentChange[];\n}\n\n/**\n * View is responsible for computing the final merged truth of what docs are in\n * a query. It gets notified of local and remote changes to docs, and applies\n * the query filters and limits to determine the most correct possible results.\n */\nexport class View {\n private syncState: SyncState | null = null;\n private hasCachedResults: boolean = false;\n /**\n * A flag whether the view is current with the backend. A view is considered\n * current after it has seen the current flag from the backend and did not\n * lose consistency within the watch stream (e.g. because of an existence\n * filter mismatch).\n */\n private current = false;\n private documentSet: DocumentSet;\n /** Documents in the view but not in the remote target */\n private limboDocuments = documentKeySet();\n /** Document Keys that have local changes */\n private mutatedKeys = documentKeySet();\n /** Query comparator that defines the document order in this view. */\n private docComparator: (d1: Document, d2: Document) => number;\n\n constructor(\n private query: Query,\n /** Documents included in the remote target */\n private _syncedDocuments: DocumentKeySet\n ) {\n this.docComparator = newQueryComparator(query);\n this.documentSet = new DocumentSet(this.docComparator);\n }\n\n /**\n * The set of remote documents that the server has told us belongs to the target associated with\n * this view.\n */\n get syncedDocuments(): DocumentKeySet {\n return this._syncedDocuments;\n }\n\n /**\n * Iterates over a set of doc changes, applies the query limit, and computes\n * what the new results should be, what the changes were, and whether we may\n * need to go back to the local cache for more results. Does not make any\n * changes to the view.\n * @param docChanges - The doc changes to apply to this view.\n * @param previousChanges - If this is being called with a refill, then start\n * with this set of docs and changes instead of the current view.\n * @returns a new set of docs, changes, and refill flag.\n */\n computeDocChanges(\n docChanges: DocumentMap,\n previousChanges?: ViewDocumentChanges\n ): ViewDocumentChanges {\n const changeSet = previousChanges\n ? previousChanges.changeSet\n : new DocumentChangeSet();\n const oldDocumentSet = previousChanges\n ? previousChanges.documentSet\n : this.documentSet;\n let newMutatedKeys = previousChanges\n ? previousChanges.mutatedKeys\n : this.mutatedKeys;\n let newDocumentSet = oldDocumentSet;\n let needsRefill = false;\n\n // Track the last doc in a (full) limit. This is necessary, because some\n // update (a delete, or an update moving a doc past the old limit) might\n // mean there is some other document in the local cache that either should\n // come (1) between the old last limit doc and the new last document, in the\n // case of updates, or (2) after the new last document, in the case of\n // deletes. So we keep this doc at the old limit to compare the updates to.\n //\n // Note that this should never get used in a refill (when previousChanges is\n // set), because there will only be adds -- no deletes or updates.\n const lastDocInLimit =\n this.query.limitType === LimitType.First &&\n oldDocumentSet.size === this.query.limit\n ? oldDocumentSet.last()\n : null;\n const firstDocInLimit =\n this.query.limitType === LimitType.Last &&\n oldDocumentSet.size === this.query.limit\n ? oldDocumentSet.first()\n : null;\n\n docChanges.inorderTraversal((key, entry) => {\n const oldDoc = oldDocumentSet.get(key);\n const newDoc = queryMatches(this.query, entry) ? entry : null;\n\n const oldDocHadPendingMutations = oldDoc\n ? this.mutatedKeys.has(oldDoc.key)\n : false;\n const newDocHasPendingMutations = newDoc\n ? newDoc.hasLocalMutations ||\n // We only consider committed mutations for documents that were\n // mutated during the lifetime of the view.\n (this.mutatedKeys.has(newDoc.key) && newDoc.hasCommittedMutations)\n : false;\n\n let changeApplied = false;\n\n // Calculate change\n if (oldDoc && newDoc) {\n const docsEqual = oldDoc.data.isEqual(newDoc.data);\n if (!docsEqual) {\n if (!this.shouldWaitForSyncedDocument(oldDoc, newDoc)) {\n changeSet.track({\n type: ChangeType.Modified,\n doc: newDoc\n });\n changeApplied = true;\n\n if (\n (lastDocInLimit &&\n this.docComparator(newDoc, lastDocInLimit) > 0) ||\n (firstDocInLimit &&\n this.docComparator(newDoc, firstDocInLimit) < 0)\n ) {\n // This doc moved from inside the limit to outside the limit.\n // That means there may be some other doc in the local cache\n // that should be included instead.\n needsRefill = true;\n }\n }\n } else if (oldDocHadPendingMutations !== newDocHasPendingMutations) {\n changeSet.track({ type: ChangeType.Metadata, doc: newDoc });\n changeApplied = true;\n }\n } else if (!oldDoc && newDoc) {\n changeSet.track({ type: ChangeType.Added, doc: newDoc });\n changeApplied = true;\n } else if (oldDoc && !newDoc) {\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc });\n changeApplied = true;\n\n if (lastDocInLimit || firstDocInLimit) {\n // A doc was removed from a full limit query. We'll need to\n // requery from the local cache to see if we know about some other\n // doc that should be in the results.\n needsRefill = true;\n }\n }\n\n if (changeApplied) {\n if (newDoc) {\n newDocumentSet = newDocumentSet.add(newDoc);\n if (newDocHasPendingMutations) {\n newMutatedKeys = newMutatedKeys.add(key);\n } else {\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n } else {\n newDocumentSet = newDocumentSet.delete(key);\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n }\n });\n\n // Drop documents out to meet limit/limitToLast requirement.\n if (this.query.limit !== null) {\n while (newDocumentSet.size > this.query.limit!) {\n const oldDoc =\n this.query.limitType === LimitType.First\n ? newDocumentSet.last()\n : newDocumentSet.first();\n newDocumentSet = newDocumentSet.delete(oldDoc!.key);\n newMutatedKeys = newMutatedKeys.delete(oldDoc!.key);\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc! });\n }\n }\n\n debugAssert(\n !needsRefill || !previousChanges,\n 'View was refilled using docs that themselves needed refilling.'\n );\n return {\n documentSet: newDocumentSet,\n changeSet,\n needsRefill,\n mutatedKeys: newMutatedKeys\n };\n }\n\n private shouldWaitForSyncedDocument(\n oldDoc: Document,\n newDoc: Document\n ): boolean {\n // We suppress the initial change event for documents that were modified as\n // part of a write acknowledgment (e.g. when the value of a server transform\n // is applied) as Watch will send us the same document again.\n // By suppressing the event, we only raise two user visible events (one with\n // `hasPendingWrites` and the final state of the document) instead of three\n // (one with `hasPendingWrites`, the modified document with\n // `hasPendingWrites` and the final state of the document).\n return (\n oldDoc.hasLocalMutations &&\n newDoc.hasCommittedMutations &&\n !newDoc.hasLocalMutations\n );\n }\n\n /**\n * Updates the view with the given ViewDocumentChanges and optionally updates\n * limbo docs and sync state from the provided target change.\n * @param docChanges - The set of changes to make to the view's docs.\n * @param limboResolutionEnabled - Whether to update limbo documents based on\n * this change.\n * @param targetChange - A target change to apply for computing limbo docs and\n * sync state.\n * @param targetIsPendingReset - Whether the target is pending to reset due to\n * existence filter mismatch. If not explicitly specified, it is treated\n * equivalently to `false`.\n * @returns A new ViewChange with the given docs, changes, and sync state.\n */\n // PORTING NOTE: The iOS/Android clients always compute limbo document changes.\n applyChanges(\n docChanges: ViewDocumentChanges,\n limboResolutionEnabled: boolean,\n targetChange?: TargetChange,\n targetIsPendingReset?: boolean\n ): ViewChange {\n debugAssert(\n !docChanges.needsRefill,\n 'Cannot apply changes that need a refill'\n );\n const oldDocs = this.documentSet;\n this.documentSet = docChanges.documentSet;\n this.mutatedKeys = docChanges.mutatedKeys;\n // Sort changes based on type and query comparator\n const changes = docChanges.changeSet.getChanges();\n changes.sort((c1, c2) => {\n return (\n compareChangeType(c1.type, c2.type) ||\n this.docComparator(c1.doc, c2.doc)\n );\n });\n\n this.applyTargetChange(targetChange);\n\n targetIsPendingReset = targetIsPendingReset ?? false;\n const limboChanges =\n limboResolutionEnabled && !targetIsPendingReset\n ? this.updateLimboDocuments()\n : [];\n\n // We are at synced state if there is no limbo docs are waiting to be resolved, view is current\n // with the backend, and the query is not pending to reset due to existence filter mismatch.\n const synced =\n this.limboDocuments.size === 0 && this.current && !targetIsPendingReset;\n\n const newSyncState = synced ? SyncState.Synced : SyncState.Local;\n const syncStateChanged = newSyncState !== this.syncState;\n this.syncState = newSyncState;\n\n if (changes.length === 0 && !syncStateChanged) {\n // no changes\n return { limboChanges };\n } else {\n const snap: ViewSnapshot = new ViewSnapshot(\n this.query,\n docChanges.documentSet,\n oldDocs,\n changes,\n docChanges.mutatedKeys,\n newSyncState === SyncState.Local,\n syncStateChanged,\n /* excludesMetadataChanges= */ false,\n targetChange\n ? targetChange.resumeToken.approximateByteSize() > 0\n : false\n );\n return {\n snapshot: snap,\n limboChanges\n };\n }\n }\n\n /**\n * Applies an OnlineState change to the view, potentially generating a\n * ViewChange if the view's syncState changes as a result.\n */\n applyOnlineStateChange(onlineState: OnlineState): ViewChange {\n if (this.current && onlineState === OnlineState.Offline) {\n // If we're offline, set `current` to false and then call applyChanges()\n // to refresh our syncState and generate a ViewChange as appropriate. We\n // are guaranteed to get a new TargetChange that sets `current` back to\n // true once the client is back online.\n this.current = false;\n return this.applyChanges(\n {\n documentSet: this.documentSet,\n changeSet: new DocumentChangeSet(),\n mutatedKeys: this.mutatedKeys,\n needsRefill: false\n },\n /* limboResolutionEnabled= */ false\n );\n } else {\n // No effect, just return a no-op ViewChange.\n return { limboChanges: [] };\n }\n }\n\n /**\n * Returns whether the doc for the given key should be in limbo.\n */\n private shouldBeInLimbo(key: DocumentKey): boolean {\n // If the remote end says it's part of this query, it's not in limbo.\n if (this._syncedDocuments.has(key)) {\n return false;\n }\n // The local store doesn't think it's a result, so it shouldn't be in limbo.\n if (!this.documentSet.has(key)) {\n return false;\n }\n // If there are local changes to the doc, they might explain why the server\n // doesn't know that it's part of the query. So don't put it in limbo.\n // TODO(klimt): Ideally, we would only consider changes that might actually\n // affect this specific query.\n if (this.documentSet.get(key)!.hasLocalMutations) {\n return false;\n }\n // Everything else is in limbo.\n return true;\n }\n\n /**\n * Updates syncedDocuments, current, and limbo docs based on the given change.\n * Returns the list of changes to which docs are in limbo.\n */\n private applyTargetChange(targetChange?: TargetChange): void {\n if (targetChange) {\n targetChange.addedDocuments.forEach(\n key => (this._syncedDocuments = this._syncedDocuments.add(key))\n );\n targetChange.modifiedDocuments.forEach(key => {\n debugAssert(\n this._syncedDocuments.has(key),\n `Modified document ${key} not found in view.`\n );\n });\n targetChange.removedDocuments.forEach(\n key => (this._syncedDocuments = this._syncedDocuments.delete(key))\n );\n this.current = targetChange.current;\n }\n }\n\n private updateLimboDocuments(): LimboDocumentChange[] {\n // We can only determine limbo documents when we're in-sync with the server.\n if (!this.current) {\n return [];\n }\n\n // TODO(klimt): Do this incrementally so that it's not quadratic when\n // updating many documents.\n const oldLimboDocuments = this.limboDocuments;\n this.limboDocuments = documentKeySet();\n this.documentSet.forEach(doc => {\n if (this.shouldBeInLimbo(doc.key)) {\n this.limboDocuments = this.limboDocuments.add(doc.key);\n }\n });\n\n // Diff the new limbo docs with the old limbo docs.\n const changes: LimboDocumentChange[] = [];\n oldLimboDocuments.forEach(key => {\n if (!this.limboDocuments.has(key)) {\n changes.push(new RemovedLimboDocument(key));\n }\n });\n this.limboDocuments.forEach(key => {\n if (!oldLimboDocuments.has(key)) {\n changes.push(new AddedLimboDocument(key));\n }\n });\n return changes;\n }\n\n /**\n * Update the in-memory state of the current view with the state read from\n * persistence.\n *\n * We update the query view whenever a client's primary status changes:\n * - When a client transitions from primary to secondary, it can miss\n * LocalStorage updates and its query views may temporarily not be\n * synchronized with the state on disk.\n * - For secondary to primary transitions, the client needs to update the list\n * of `syncedDocuments` since secondary clients update their query views\n * based purely on synthesized RemoteEvents.\n *\n * @param queryResult.documents - The documents that match the query according\n * to the LocalStore.\n * @param queryResult.remoteKeys - The keys of the documents that match the\n * query according to the backend.\n *\n * @returns The ViewChange that resulted from this synchronization.\n */\n // PORTING NOTE: Multi-tab only.\n synchronizeWithPersistedState(queryResult: QueryResult): ViewChange {\n this._syncedDocuments = queryResult.remoteKeys;\n this.limboDocuments = documentKeySet();\n const docChanges = this.computeDocChanges(queryResult.documents);\n return this.applyChanges(docChanges, /* limboResolutionEnabled= */ true);\n }\n\n /**\n * Returns a view snapshot as if this query was just listened to. Contains\n * a document add for every existing document and the `fromCache` and\n * `hasPendingWrites` status of the already established view.\n */\n // PORTING NOTE: Multi-tab only.\n computeInitialSnapshot(): ViewSnapshot {\n return ViewSnapshot.fromInitialDocuments(\n this.query,\n this.documentSet,\n this.mutatedKeys,\n this.syncState === SyncState.Local,\n this.hasCachedResults\n );\n }\n}\n\nfunction compareChangeType(c1: ChangeType, c2: ChangeType): number {\n const order = (change: ChangeType): 0 | 1 | 2 => {\n switch (change) {\n case ChangeType.Added:\n return 1;\n case ChangeType.Modified:\n return 2;\n case ChangeType.Metadata:\n // A metadata change is converted to a modified change at the public\n // api layer. Since we sort by document key and then change type,\n // metadata and modified changes must be sorted equivalently.\n return 2;\n case ChangeType.Removed:\n return 0;\n default:\n return fail(0x4f35, '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 0x5858,\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 0x390f,\n 'Received change for limbo target document without add.'\n );\n } else if (targetChange.removedDocuments.size > 0) {\n hardAssert(\n limboResolution.receivedDocument,\n 0xa4f3,\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(0x4d4f, 'Unknown limbo change', { 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(0x1a40, `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(0xfa9b, '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(metadata, reader.serializer);\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.completeAndStoreAsync(syncEngine.localStore);\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 0xb743,\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 { debugAssert } from './assert';\n\n/**\n * How many bytes to read each time when `ReadableStreamReader.read()` is\n * called. Only applicable for byte streams that we control (e.g. those backed\n * by an UInt8Array).\n */\nexport const DEFAULT_BYTES_PER_READ = 10240;\n\n/**\n * Builds a `ByteStreamReader` from a UInt8Array.\n * @param source - The data source to use.\n * @param bytesPerRead - How many bytes each `read()` from the returned reader\n * will read.\n */\nexport function toByteStreamReaderHelper(\n source: Uint8Array,\n bytesPerRead: number = DEFAULT_BYTES_PER_READ\n): ReadableStreamDefaultReader {\n debugAssert(\n bytesPerRead > 0,\n `toByteStreamReader expects positive bytesPerRead, but got ${bytesPerRead}`\n );\n let readFrom = 0;\n // The TypeScript definition for ReadableStreamReader changed. We use\n // `any` here to allow this code to compile with different versions.\n // See https://github.com/microsoft/TypeScript/issues/42970\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const reader: any = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async read(): Promise {\n if (readFrom < source.byteLength) {\n const result = {\n value: source.slice(readFrom, readFrom + bytesPerRead),\n done: false\n } as const;\n readFrom += bytesPerRead;\n return result;\n }\n\n return { done: true };\n },\n async cancel(): Promise {},\n releaseLock() {},\n closed: Promise.resolve()\n };\n return reader;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BundleSource } from '../../util/bundle_reader';\nimport { toByteStreamReaderHelper } from '../../util/byte_stream';\nimport { Code, FirestoreError } from '../../util/error';\nimport { valueDescription } from '../../util/input_validation';\n\n/**\n * On Node, only supported data source is a `Uint8Array` for now.\n */\nexport function toByteStreamReader(\n source: BundleSource,\n bytesPerRead: number\n): ReadableStreamDefaultReader {\n if (!(source instanceof Uint8Array)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `NodePlatform.toByteStreamReader expects source to be Uint8Array, got ${valueDescription(\n source\n )}`\n );\n }\n return toByteStreamReaderHelper(source, bytesPerRead);\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n BundleElement,\n BundleMetadata\n} from '../protos/firestore_bundle_proto';\nimport { JsonProtoSerializer } from '../remote/serializer';\n\n/**\n * A complete element in the bundle stream, together with the byte length it\n * occupies in the stream.\n */\nexport class SizedBundleElement {\n constructor(\n public readonly payload: BundleElement,\n // How many bytes this element takes to store in the bundle.\n public readonly byteLength: number\n ) {}\n\n isBundleMetadata(): boolean {\n return 'metadata' in this.payload;\n }\n}\n\nexport type BundleSource =\n | ReadableStream\n | ArrayBuffer\n | Uint8Array;\n\n/**\n * A class representing a bundle.\n *\n * Takes a bundle stream or buffer, and presents abstractions to read bundled\n * elements out of the underlying content.\n */\nexport interface BundleReader {\n serializer: JsonProtoSerializer;\n\n close(): Promise;\n\n /**\n * Returns the metadata of the bundle.\n */\n getMetadata(): Promise;\n\n /**\n * Returns the next BundleElement (together with its byte size in the bundle)\n * that has not been read from underlying ReadableStream. Returns null if we\n * have reached the end of the stream.\n */\n nextElement(): Promise;\n}\n\n/**\n * A class representing a synchronized bundle reader.\n *\n * Takes a bundle string buffer, parses the data, and provides accessors to the data contained\n * within it.\n */\nexport interface BundleReaderSync {\n serializer: JsonProtoSerializer;\n\n /**\n * Returns the metadata of the bundle.\n */\n getMetadata(): BundleMetadata;\n\n /**\n * Returns BundleElements parsed from the bundle. Returns an empty array if no bundle elements\n * exist.\n */\n getElements(): SizedBundleElement[];\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { newTextDecoder } from '../platform/text_serializer';\nimport { BundleMetadata } from '../protos/firestore_bundle_proto';\nimport { JsonProtoSerializer } from '../remote/serializer';\n\nimport { debugAssert } from './assert';\nimport { BundleReader, SizedBundleElement } from './bundle_reader';\nimport { Deferred } from './promise';\n\n/**\n * A class representing a bundle.\n *\n * Takes a bundle stream or buffer, and presents abstractions to read bundled\n * elements out of the underlying content.\n */\nclass BundleReaderImpl implements BundleReader {\n /** Cached bundle metadata. */\n private metadata: Deferred = new Deferred();\n /**\n * Internal buffer to hold bundle content, accumulating incomplete element\n * content.\n */\n private buffer: Uint8Array = new Uint8Array();\n /** The decoder used to parse binary data into strings. */\n private textDecoder: TextDecoder;\n\n constructor(\n /** The reader to read from underlying binary bundle data source. */\n private reader: ReadableStreamDefaultReader,\n readonly serializer: JsonProtoSerializer\n ) {\n this.textDecoder = newTextDecoder();\n // Read the metadata (which is the first element).\n this.nextElementImpl().then(\n element => {\n if (element && element.isBundleMetadata()) {\n this.metadata.resolve(element.payload.metadata!);\n } else {\n this.metadata.reject(\n new Error(`The first element of the bundle is not a metadata, it is\n ${JSON.stringify(element?.payload)}`)\n );\n }\n },\n error => this.metadata.reject(error)\n );\n }\n\n close(): Promise {\n return this.reader.cancel();\n }\n\n async getMetadata(): Promise {\n return this.metadata.promise;\n }\n\n async nextElement(): Promise {\n // Makes sure metadata is read before proceeding.\n await this.getMetadata();\n return this.nextElementImpl();\n }\n\n /**\n * Reads from the head of internal buffer, and pulling more data from\n * underlying stream if a complete element cannot be found, until an\n * element(including the prefixed length and the JSON string) is found.\n *\n * Once a complete element is read, it is dropped from internal buffer.\n *\n * Returns either the bundled element, or null if we have reached the end of\n * the stream.\n */\n private async nextElementImpl(): Promise {\n const lengthBuffer = await this.readLength();\n if (lengthBuffer === null) {\n return null;\n }\n\n const lengthString = this.textDecoder.decode(lengthBuffer);\n const length = Number(lengthString);\n if (isNaN(length)) {\n this.raiseError(`length string (${lengthString}) is not valid number`);\n }\n\n const jsonString = await this.readJsonString(length);\n\n return new SizedBundleElement(\n JSON.parse(jsonString),\n lengthBuffer.length + length\n );\n }\n\n /** First index of '{' from the underlying buffer. */\n private indexOfOpenBracket(): number {\n return this.buffer.findIndex(v => v === '{'.charCodeAt(0));\n }\n\n /**\n * Reads from the beginning of the internal buffer, until the first '{', and\n * return the content.\n *\n * If reached end of the stream, returns a null.\n */\n private async readLength(): Promise {\n while (this.indexOfOpenBracket() < 0) {\n const done = await this.pullMoreDataToBuffer();\n if (done) {\n break;\n }\n }\n\n // Broke out of the loop because underlying stream is closed, and there\n // happens to be no more data to process.\n if (this.buffer.length === 0) {\n return null;\n }\n\n const position = this.indexOfOpenBracket();\n // Broke out of the loop because underlying stream is closed, but still\n // cannot find an open bracket.\n if (position < 0) {\n this.raiseError(\n 'Reached the end of bundle when a length string is expected.'\n );\n }\n\n const result = this.buffer.slice(0, position);\n // Update the internal buffer to drop the read length.\n this.buffer = this.buffer.slice(position);\n return result;\n }\n\n /**\n * Reads from a specified position from the internal buffer, for a specified\n * number of bytes, pulling more data from the underlying stream if needed.\n *\n * Returns a string decoded from the read bytes.\n */\n private async readJsonString(length: number): Promise {\n while (this.buffer.length < length) {\n const done = await this.pullMoreDataToBuffer();\n if (done) {\n this.raiseError('Reached the end of bundle when more is expected.');\n }\n }\n\n const result = this.textDecoder.decode(this.buffer.slice(0, length));\n // Update the internal buffer to drop the read json string.\n this.buffer = this.buffer.slice(length);\n return result;\n }\n\n private raiseError(message: string): void {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.reader.cancel();\n throw new Error(`Invalid bundle format: ${message}`);\n }\n\n /**\n * Pulls more data from underlying stream to internal buffer.\n * Returns a boolean indicating whether the stream is finished.\n */\n private async pullMoreDataToBuffer(): Promise {\n const result = await this.reader.read();\n if (!result.done) {\n debugAssert(!!result.value, 'Read undefined when \"done\" is false.');\n const newBuffer = new Uint8Array(\n this.buffer.length + result.value!.length\n );\n newBuffer.set(this.buffer);\n newBuffer.set(result.value!, this.buffer.length);\n this.buffer = newBuffer;\n }\n return result.done;\n }\n}\n\nexport function newBundleReader(\n reader: ReadableStreamDefaultReader,\n serializer: JsonProtoSerializer\n): BundleReader {\n return new BundleReaderImpl(reader, serializer);\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 } from '../protos/firestore_bundle_proto';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { BundleReaderSync, SizedBundleElement } from './bundle_reader';\n\n/**\n * A class that can parse a bundle form the string serialization of a bundle.\n */\nexport class BundleReaderSyncImpl implements BundleReaderSync {\n private metadata: BundleMetadata;\n private elements: SizedBundleElement[];\n private cursor: number;\n constructor(\n private bundleData: string,\n readonly serializer: JsonProtoSerializer\n ) {\n this.cursor = 0;\n this.elements = [];\n\n let element = this.nextElement();\n if (element && element.isBundleMetadata()) {\n this.metadata = element as BundleMetadata;\n } else {\n throw new Error(`The first element of the bundle is not a metadata object, it is\n ${JSON.stringify(element?.payload)}`);\n }\n\n do {\n element = this.nextElement();\n if (element !== null) {\n this.elements.push(element);\n }\n } while (element !== null);\n }\n\n /* Returns the parsed metadata of the bundle. */\n getMetadata(): BundleMetadata {\n return this.metadata;\n }\n\n /* Returns the DocumentSnapshot or NamedQuery elements of the bundle. */\n getElements(): SizedBundleElement[] {\n return this.elements;\n }\n\n /**\n * Parses the next element of the bundle.\n *\n * @returns a SizedBundleElement representation of the next element in the bundle, or null if\n * no more elements exist.\n */\n private nextElement(): SizedBundleElement | null {\n if (this.cursor === this.bundleData.length) {\n return null;\n }\n const length: number = this.readLength();\n const jsonString = this.readJsonString(length);\n return new SizedBundleElement(JSON.parse(jsonString), length);\n }\n\n /**\n * Reads from a specified position from the bundleData string, for a specified\n * number of bytes.\n *\n * @param length how many characters to read.\n * @returns a string parsed from the bundle.\n */\n private readJsonString(length: number): string {\n if (this.cursor + length > this.bundleData.length) {\n throw new FirestoreError(\n Code.INTERNAL,\n 'Reached the end of bundle when more is expected.'\n );\n }\n const result = this.bundleData.slice(this.cursor, (this.cursor += length));\n return result;\n }\n\n /**\n * Reads from the current cursor until the first '{'.\n *\n * @returns A string to integer represention of the parsed value.\n * @throws An {@link Error} if the cursor has reached the end of the stream, since lengths\n * prefix bundle objects.\n */\n private readLength(): number {\n const startIndex = this.cursor;\n let curIndex = this.cursor;\n while (curIndex < this.bundleData.length) {\n if (this.bundleData[curIndex] === '{') {\n if (curIndex === startIndex) {\n throw new Error('First character is a bracket and not a number');\n }\n this.cursor = curIndex;\n return Number(this.bundleData.slice(startIndex, curIndex));\n }\n curIndex++;\n }\n throw new Error('Reached the end of bundle when more is expected.');\n }\n}\n\n/**\n * Creates an instance of BundleReader without exposing the BundleReaderSyncImpl class type.\n */\nexport function newBundleReaderSync(\n bundleData: string,\n serializer: JsonProtoSerializer\n): BundleReaderSync {\n return new BundleReaderSyncImpl(bundleData, serializer);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParsedSetData, ParsedUpdateData } from '../lite-api/user_data_reader';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n DeleteMutation,\n Mutation,\n Precondition,\n VerifyMutation\n} from '../model/mutation';\nimport {\n Datastore,\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc\n} from '../remote/datastore';\nimport { fail, debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { SnapshotVersion } from './snapshot_version';\n\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nexport class Transaction {\n // The version of each document that was read during this transaction.\n private readVersions = new Map();\n private mutations: Mutation[] = [];\n private committed = false;\n\n /**\n * A deferred usage error that occurred previously in this transaction that\n * will cause the transaction to fail once it actually commits.\n */\n private lastTransactionError: FirestoreError | null = null;\n\n /**\n * Set of documents that have been written in the transaction.\n *\n * When there's more than one write to the same key in a transaction, any\n * writes after the first are handled differently.\n */\n private writtenDocs: Set = new Set();\n\n constructor(private datastore: Datastore) {}\n\n async lookup(keys: DocumentKey[]): Promise {\n this.ensureCommitNotCalled();\n\n if (this.mutations.length > 0) {\n this.lastTransactionError = new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Firestore transactions require all reads to be executed before all writes.'\n );\n throw this.lastTransactionError;\n }\n const docs = await invokeBatchGetDocumentsRpc(this.datastore, keys);\n docs.forEach(doc => this.recordVersion(doc));\n return docs;\n }\n\n set(key: DocumentKey, data: ParsedSetData): void {\n this.write(data.toMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n update(key: DocumentKey, data: ParsedUpdateData): void {\n try {\n this.write(data.toMutation(key, this.preconditionForUpdate(key)));\n } catch (e) {\n this.lastTransactionError = e as FirestoreError | null;\n }\n this.writtenDocs.add(key.toString());\n }\n\n delete(key: DocumentKey): void {\n this.write(new DeleteMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n async commit(): Promise {\n this.ensureCommitNotCalled();\n\n if (this.lastTransactionError) {\n throw this.lastTransactionError;\n }\n const unwritten = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach(mutation => {\n unwritten.delete(mutation.key.toString());\n });\n // For each document that was read but not written to, we want to perform\n // a `verify` operation.\n unwritten.forEach((_, path) => {\n const key = DocumentKey.fromPath(path);\n this.mutations.push(new VerifyMutation(key, this.precondition(key)));\n });\n await invokeCommitRpc(this.datastore, this.mutations);\n this.committed = true;\n }\n\n private recordVersion(doc: Document): void {\n let docVersion: SnapshotVersion;\n\n if (doc.isFoundDocument()) {\n docVersion = doc.version;\n } else if (doc.isNoDocument()) {\n // Represent a deleted doc using SnapshotVersion.min().\n docVersion = SnapshotVersion.min();\n } else {\n throw fail(0xc542, 'Document in a transaction was a ', {\n documentName: doc.constructor.name\n });\n }\n\n const existingVersion = this.readVersions.get(doc.key.toString());\n if (existingVersion) {\n if (!docVersion.isEqual(existingVersion)) {\n // This transaction will fail no matter what.\n throw new FirestoreError(\n Code.ABORTED,\n 'Document version changed between two reads.'\n );\n }\n } else {\n this.readVersions.set(doc.key.toString(), docVersion);\n }\n }\n\n /**\n * Returns the version of this document when it was read in this transaction,\n * as a precondition, or no precondition if it was not read.\n */\n private precondition(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n return Precondition.exists(false);\n } else {\n return Precondition.updateTime(version);\n }\n } else {\n return Precondition.none();\n }\n }\n\n /**\n * Returns the precondition for a document if the operation is an update.\n */\n private preconditionForUpdate(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n // The first time a document is written, we want to take into account the\n // read time and existence\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n // The document doesn't exist, so fail the transaction.\n\n // This has to be validated locally because you can't send a\n // precondition that a document does not exist without changing the\n // semantics of the backend write to be an insert. This is the reverse\n // of what we want, since we want to assert that the document doesn't\n // exist but then send the update and have it fail. Since we can't\n // express that to the backend, we have to validate locally.\n\n // Note: this can change once we can send separate verify writes in the\n // transaction.\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't update a document that doesn't exist.\"\n );\n }\n // Document exists, base precondition on document update time.\n return Precondition.updateTime(version);\n } else {\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return Precondition.exists(true);\n }\n }\n\n private write(mutation: Mutation): void {\n this.ensureCommitNotCalled();\n this.mutations.push(mutation);\n }\n\n private ensureCommitNotCalled(): void {\n debugAssert(\n !this.committed,\n 'A transaction object cannot be used after its update callback has been invoked.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ExponentialBackoff } from '../remote/backoff';\nimport { Datastore } from '../remote/datastore';\nimport { isPermanentError } from '../remote/rpc_error';\nimport { AsyncQueue, TimerId } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport { Deferred } from '../util/promise';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Transaction } from './transaction';\nimport { TransactionOptions } from './transaction_options';\n\n/**\n * TransactionRunner encapsulates the logic needed to run and retry transactions\n * with backoff.\n */\nexport class TransactionRunner {\n private attemptsRemaining: number;\n private backoff: ExponentialBackoff;\n\n constructor(\n private readonly asyncQueue: AsyncQueue,\n private readonly datastore: Datastore,\n private readonly options: TransactionOptions,\n private readonly updateFunction: (transaction: Transaction) => Promise,\n private readonly deferred: Deferred\n ) {\n this.attemptsRemaining = options.maxAttempts;\n this.backoff = new ExponentialBackoff(\n this.asyncQueue,\n TimerId.TransactionRetry\n );\n }\n\n /** Runs the transaction and sets the result on deferred. */\n run(): void {\n this.attemptsRemaining -= 1;\n this.runWithBackOff();\n }\n\n private runWithBackOff(): void {\n this.backoff.backoffAndRun(async () => {\n const transaction = new Transaction(this.datastore);\n const userPromise = this.tryRunUpdateFunction(transaction);\n if (userPromise) {\n userPromise\n .then(result => {\n this.asyncQueue.enqueueAndForget(() => {\n return transaction\n .commit()\n .then(() => {\n this.deferred.resolve(result);\n })\n .catch(commitError => {\n this.handleTransactionError(commitError);\n });\n });\n })\n .catch(userPromiseError => {\n this.handleTransactionError(userPromiseError);\n });\n }\n });\n }\n\n private tryRunUpdateFunction(transaction: Transaction): Promise | null {\n try {\n const userPromise = this.updateFunction(transaction);\n if (\n isNullOrUndefined(userPromise) ||\n !userPromise.catch ||\n !userPromise.then\n ) {\n this.deferred.reject(\n Error('Transaction callback must return a Promise')\n );\n return null;\n }\n return userPromise;\n } catch (error) {\n // Do not retry errors thrown by user provided updateFunction.\n this.deferred.reject(error as Error);\n return null;\n }\n }\n\n private handleTransactionError(error: Error): void {\n if (this.attemptsRemaining > 0 && this.isRetryableTransactionError(error)) {\n this.attemptsRemaining -= 1;\n this.asyncQueue.enqueueAndForget(() => {\n this.runWithBackOff();\n return Promise.resolve();\n });\n } else {\n this.deferred.reject(error);\n }\n }\n\n private isRetryableTransactionError(error: Error | undefined): boolean {\n if (error?.name === 'FirebaseError') {\n // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and\n // non-matching document versions with ABORTED. These errors should be retried.\n const code = (error as FirestoreError).code;\n return (\n code === 'aborted' ||\n code === 'failed-precondition' ||\n code === 'already-exists' ||\n !isPermanentError(code)\n );\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GetOptions } from '@firebase/firestore-types';\n\nimport { LoadBundleTask } from '../api/bundle';\nimport {\n CredentialChangeListener,\n CredentialsProvider\n} from '../api/credentials';\nimport { User } from '../auth/user';\nimport { LocalStore } from '../local/local_store';\nimport {\n localStoreConfigureFieldIndexes,\n localStoreDeleteAllFieldIndexes,\n localStoreExecuteQuery,\n localStoreGetNamedQuery,\n localStoreHandleUserChange,\n localStoreReadDocument,\n localStoreSetIndexAutoCreationEnabled\n} from '../local/local_store_impl';\nimport { Persistence } from '../local/persistence';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldIndex } from '../model/field_index';\nimport { Mutation } from '../model/mutation';\nimport { toByteStreamReader } from '../platform/byte_stream_reader';\nimport { newSerializer } from '../platform/serializer';\nimport { newTextEncoder } from '../platform/text_serializer';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { Datastore, invokeRunAggregationQueryRpc } from '../remote/datastore';\nimport {\n RemoteStore,\n remoteStoreDisableNetwork,\n remoteStoreEnableNetwork,\n remoteStoreHandleCredentialChange\n} from '../remote/remote_store';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { debugAssert } from '../util/assert';\nimport { AsyncObserver } from '../util/async_observer';\nimport { AsyncQueue, wrapInUserErrorIfRecoverable } from '../util/async_queue';\nimport { BundleReader, BundleReaderSync } from '../util/bundle_reader';\nimport { newBundleReader } from '../util/bundle_reader_impl';\nimport { newBundleReaderSync } from '../util/bundle_reader_sync_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 LruGcMemoryOfflineComponentProvider,\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 LruGcMemoryOfflineComponentProvider(undefined)\n );\n }\n }\n\n return client._offlineComponents!;\n}\n\nexport async 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 createBundleReaderSync(\n bundleData: string,\n serializer: JsonProtoSerializer\n): BundleReaderSync {\n return newBundleReaderSync(bundleData, 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 settings.isUsingEmulator\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 { EmulatorMockTokenOptions } from '@firebase/util';\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 emulatorOptions?: { mockUserToken?: EmulatorMockTokenOptions | string };\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 readonly isUsingEmulator: boolean;\n\n // Can be a google-auth-library or gapi client.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n credentials?: any;\n\n constructor(settings: PrivateSettings) {\n if (settings.host === undefined) {\n if (settings.ssl !== undefined) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't provide ssl option if host option is not set\"\n );\n }\n this.host = DEFAULT_HOST;\n this.ssl = DEFAULT_SSL;\n } else {\n this.host = settings.host;\n this.ssl = settings.ssl ?? DEFAULT_SSL;\n }\n this.isUsingEmulator = settings.emulatorOptions !== undefined;\n\n this.credentials = settings.credentials;\n this.ignoreUndefinedProperties = !!settings.ignoreUndefinedProperties;\n this.localCache = settings.localCache;\n\n if (settings.cacheSizeBytes === undefined) {\n this.cacheSizeBytes = LRU_DEFAULT_CACHE_SIZE_BYTES;\n } else {\n if (\n settings.cacheSizeBytes !== LRU_COLLECTION_DISABLED &&\n settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`\n );\n } else {\n this.cacheSizeBytes = settings.cacheSizeBytes;\n }\n }\n\n validateIsNotUsedTogether(\n 'experimentalForceLongPolling',\n settings.experimentalForceLongPolling,\n 'experimentalAutoDetectLongPolling',\n settings.experimentalAutoDetectLongPolling\n );\n\n this.experimentalForceLongPolling = !!settings.experimentalForceLongPolling;\n\n if (this.experimentalForceLongPolling) {\n this.experimentalAutoDetectLongPolling = false;\n } else if (settings.experimentalAutoDetectLongPolling === undefined) {\n this.experimentalAutoDetectLongPolling = DEFAULT_AUTO_DETECT_LONG_POLLING;\n } else {\n // For backwards compatibility, coerce the value to boolean even though\n // the TypeScript compiler has narrowed the type to boolean already.\n // noinspection PointlessBooleanExpressionJS\n this.experimentalAutoDetectLongPolling =\n !!settings.experimentalAutoDetectLongPolling;\n }\n\n this.experimentalLongPollingOptions = cloneLongPollingOptions(\n settings.experimentalLongPollingOptions ?? {}\n );\n validateLongPollingOptions(this.experimentalLongPollingOptions);\n\n this.useFetchStreams = !!settings.useFetchStreams;\n }\n\n isEqual(other: FirestoreSettingsImpl): boolean {\n return (\n this.host === other.host &&\n this.ssl === other.ssl &&\n this.credentials === other.credentials &&\n this.cacheSizeBytes === other.cacheSizeBytes &&\n this.experimentalForceLongPolling ===\n other.experimentalForceLongPolling &&\n this.experimentalAutoDetectLongPolling ===\n other.experimentalAutoDetectLongPolling &&\n longPollingOptionsEqual(\n this.experimentalLongPollingOptions,\n other.experimentalLongPollingOptions\n ) &&\n this.ignoreUndefinedProperties === other.ignoreUndefinedProperties &&\n this.useFetchStreams === other.useFetchStreams\n );\n }\n}\n\nfunction validateLongPollingOptions(\n options: ExperimentalLongPollingOptions\n): void {\n if (options.timeoutSeconds !== undefined) {\n if (isNaN(options.timeoutSeconds)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ` +\n `${options.timeoutSeconds} (must not be NaN)`\n );\n }\n if (options.timeoutSeconds < MIN_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(minimum allowed value is ${MIN_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n if (options.timeoutSeconds > MAX_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(maximum allowed value is ${MAX_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _getProvider,\n _removeServiceInstance,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport {\n createMockUserToken,\n deepEqual,\n EmulatorMockTokenOptions,\n getDefaultEmulatorHostnameAndPort,\n isCloudWorkstation,\n pingServer,\n updateEmulatorBanner\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 private _emulatorOptions: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {};\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 this._emulatorOptions = settings.emulatorOptions || {};\n\n if (settings.credentials !== undefined) {\n this._authCredentials = makeAuthCredentialsProvider(settings.credentials);\n }\n }\n\n _getSettings(): FirestoreSettingsImpl {\n return this._settings;\n }\n\n _getEmulatorOptions(): { mockUserToken?: EmulatorMockTokenOptions | string } {\n return this._emulatorOptions;\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 useSsl = isCloudWorkstation(host);\n const settings = firestore._getSettings();\n const existingConfig = {\n ...settings,\n emulatorOptions: firestore._getEmulatorOptions()\n };\n const newHostSetting = `${host}:${port}`;\n if (useSsl) {\n void pingServer(`https://${newHostSetting}`);\n updateEmulatorBanner('Firestore', true);\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 const newConfig = {\n ...settings,\n host: newHostSetting,\n ssl: useSsl,\n emulatorOptions: options\n };\n // No-op if the new configuration matches the current configuration. This supports SSR\n // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice.\n if (deepEqual(newConfig, existingConfig)) {\n return;\n }\n\n firestore._setSettings(newConfig);\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';\n// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_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 static _jsonSchemaVersion: string = 'firestore/documentReference/1.0';\n static _jsonSchema = {\n type: property('string', DocumentReference._jsonSchemaVersion),\n referencePath: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `DocumentReference` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: DocumentReference._jsonSchemaVersion,\n referencePath: this._key.toString()\n };\n }\n\n /**\n * Builds a `DocumentReference` instance from a JSON object created by\n * {@link DocumentReference.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json a JSON object represention of a `DocumentReference` instance\n * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(firestore: Firestore, json: object): DocumentReference;\n /**\n * Builds a `DocumentReference` instance from a JSON object created by\n * {@link DocumentReference.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json a JSON object represention of a `DocumentReference` instance\n * @param converter - Converts objects to and from Firestore.\n * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON<\n NewAppModelType = DocumentData,\n NewDbModelType extends DocumentData = DocumentData\n >(\n firestore: Firestore,\n json: object,\n converter: FirestoreDataConverter\n ): DocumentReference;\n static fromJSON<\n NewAppModelType = DocumentData,\n NewDbModelType extends DocumentData = DocumentData\n >(\n firestore: Firestore,\n json: object,\n converter?: FirestoreDataConverter\n ): DocumentReference {\n if (validateJSON(json, DocumentReference._jsonSchema)) {\n return new DocumentReference(\n firestore,\n converter ? converter : null,\n new DocumentKey(ResourcePath.fromString(json.referencePath))\n );\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Bytes from JSON.'\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(0xb815, 'AsyncQueue is already failed', {\n messageOrStack: getMessageOrStack(this.failure)\n });\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 { PartialObserver } from '../api/observer';\nimport { debugAssert } from '../util/assert';\nimport { FirestoreError } from '../util/error';\nimport { Deferred } from '../util/promise';\n\n/**\n * Represents the state of bundle loading tasks.\n *\n * Both 'Error' and 'Success' are sinking state: task will abort or complete and there will\n * be no more updates after they are reported.\n */\nexport type TaskState = 'Error' | 'Running' | 'Success';\n\n/**\n * Represents a progress update or a final state from loading bundles.\n */\nexport interface LoadBundleTaskProgress {\n /** How many documents have been loaded. */\n documentsLoaded: number;\n /** How many documents are in the bundle being loaded. */\n totalDocuments: number;\n /** How many bytes have been loaded. */\n bytesLoaded: number;\n /** How many bytes are in the bundle being loaded. */\n totalBytes: number;\n /** Current task state. */\n taskState: TaskState;\n}\n\n/**\n * Represents the task of loading a Firestore bundle. It provides progress of bundle\n * loading, as well as task completion and error events.\n *\n * The API is compatible with `Promise`.\n */\nexport class LoadBundleTask implements PromiseLike {\n private _progressObserver: PartialObserver = {};\n private _taskCompletionResolver = new Deferred();\n\n private _lastProgress: LoadBundleTaskProgress = {\n taskState: 'Running',\n totalBytes: 0,\n totalDocuments: 0,\n bytesLoaded: 0,\n documentsLoaded: 0\n };\n\n /**\n * Registers functions to listen to bundle loading progress events.\n * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur\n * each time a Firestore document is loaded from the bundle.\n * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the\n * error, and there should be no more updates after this.\n * @param complete - Called when the loading task is complete.\n */\n onProgress(\n next?: (progress: LoadBundleTaskProgress) => unknown,\n error?: (err: Error) => unknown,\n complete?: () => void\n ): void {\n this._progressObserver = {\n next,\n error,\n complete\n };\n }\n\n /**\n * Implements the `Promise.catch` interface.\n *\n * @param onRejected - Called when an error occurs during bundle loading.\n */\n catch(\n onRejected: (a: Error) => R | PromiseLike\n ): Promise {\n return this._taskCompletionResolver.promise.catch(onRejected);\n }\n\n /**\n * Implements the `Promise.then` interface.\n *\n * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update.\n * The update will always have its `taskState` set to `\"Success\"`.\n * @param onRejected - Called when an error occurs during bundle loading.\n */\n then(\n onFulfilled?: (a: LoadBundleTaskProgress) => T | PromiseLike,\n onRejected?: (a: Error) => R | PromiseLike\n ): Promise {\n return this._taskCompletionResolver.promise.then(onFulfilled, onRejected);\n }\n\n /**\n * Notifies all observers that bundle loading has completed, with a provided\n * `LoadBundleTaskProgress` object.\n *\n * @private\n */\n _completeWith(progress: LoadBundleTaskProgress): void {\n debugAssert(\n progress.taskState === 'Success',\n 'Task is not completed with Success.'\n );\n this._updateProgress(progress);\n if (this._progressObserver.complete) {\n this._progressObserver.complete();\n }\n\n this._taskCompletionResolver.resolve(progress);\n }\n\n /**\n * Notifies all observers that bundle loading has failed, with a provided\n * `Error` as the reason.\n *\n * @private\n */\n _failWith(error: FirestoreError): void {\n this._lastProgress.taskState = 'Error';\n\n if (this._progressObserver.next) {\n this._progressObserver.next(this._lastProgress);\n }\n\n if (this._progressObserver.error) {\n this._progressObserver.error(error);\n }\n\n this._taskCompletionResolver.reject(error);\n }\n\n /**\n * Notifies a progress update of loading a bundle.\n * @param progress - The new progress.\n *\n * @private\n */\n _updateProgress(progress: LoadBundleTaskProgress): void {\n debugAssert(\n this._lastProgress.taskState === 'Running',\n 'Cannot update progress on a completed or failed task'\n );\n\n this._lastProgress = progress;\n if (this._progressObserver.next) {\n this._progressObserver.next(progress);\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _getProvider,\n _removeServiceInstance,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport {\n deepEqual,\n getDefaultEmulatorHostnameAndPort,\n isCloudWorkstation,\n pingServer\n} 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 // Workaround to get cookies in Firebase Studio\n if (settings.host && isCloudWorkstation(settings.host)) {\n void pingServer(settings.host);\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 {\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 app,\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 esm, cjs, etc during the compilation\n registerVersion(name, version, '__BUILD_TARGET__');\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 { FieldPath } from '../model/path';\n\n/**\n * Union type representing the aggregate type to be performed.\n */\nexport type AggregateType = 'count' | 'avg' | 'sum';\n\n/**\n * Represents an Aggregate to be performed over a query result set.\n */\nexport interface Aggregate {\n readonly fieldPath?: FieldPath;\n readonly alias: string;\n readonly aggregateType: AggregateType;\n}\n\n/**\n * Concrete implementation of the Aggregate type.\n */\nexport class AggregateImpl implements Aggregate {\n constructor(\n readonly alias: string,\n readonly aggregateType: AggregateType,\n readonly fieldPath?: FieldPath\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 { AggregateType } from '../core/aggregate';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\n\nimport { average, count, sum } from './aggregate';\nimport { DocumentData, Query } from './reference';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\nexport { AggregateType };\n\n/**\n * Represents an aggregation that can be performed by Firestore.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport class AggregateField {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateField';\n\n /** Indicates the aggregation operation of this AggregateField. */\n readonly aggregateType: AggregateType;\n\n /**\n * Create a new AggregateField\n * @param aggregateType Specifies the type of aggregation operation to perform.\n * @param _internalFieldPath Optionally specifies the field that is aggregated.\n * @internal\n */\n constructor(\n aggregateType: AggregateType = 'count',\n readonly _internalFieldPath?: InternalFieldPath\n ) {\n this.aggregateType = aggregateType;\n }\n}\n\n/**\n * The union of all `AggregateField` types that are supported by Firestore.\n */\nexport type AggregateFieldType =\n | ReturnType\n | ReturnType\n | ReturnType;\n\n/**\n * Specifies a set of aggregations and their aliases.\n */\nexport interface AggregateSpec {\n [field: string]: AggregateFieldType;\n}\n\n/**\n * A type whose keys are taken from an `AggregateSpec`, and whose values are the\n * result of the aggregation performed by the corresponding `AggregateField`\n * from the input `AggregateSpec`.\n */\nexport type AggregateSpecData = {\n [P in keyof T]: T[P] extends AggregateField ? U : never;\n};\n\n/**\n * The results of executing an aggregation query.\n */\nexport class AggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateQuerySnapshot';\n\n /**\n * The underlying query over which the aggregations recorded in this\n * `AggregateQuerySnapshot` were performed.\n */\n readonly query: Query;\n\n /** @hideconstructor */\n constructor(\n query: Query,\n private readonly _userDataWriter: AbstractUserDataWriter,\n private readonly _data: ApiClientObjectMap\n ) {\n this.query = query;\n }\n\n /**\n * Returns the results of the aggregations performed over the underlying\n * query.\n *\n * The keys of the returned object will be the same as those of the\n * `AggregateSpec` object specified to the aggregation method, and the values\n * will be the corresponding aggregation result.\n *\n * @returns The results of the aggregations performed over the underlying\n * query.\n */\n data(): AggregateSpecData {\n return this._userDataWriter.convertObjectMap(\n this._data\n ) as AggregateSpecData;\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// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\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 static _jsonSchemaVersion: string = 'firestore/bytes/1.0';\n static _jsonSchema = {\n type: property('string', Bytes._jsonSchemaVersion),\n bytes: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `Bytes` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: Bytes._jsonSchemaVersion,\n bytes: this.toBase64()\n };\n }\n\n /**\n * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}.\n *\n * @param json a JSON object represention of a `Bytes` instance\n * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): Bytes {\n if (validateJSON(json, Bytes._jsonSchema)) {\n return Bytes.fromBase64String(json.bytes);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Bytes from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n 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';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\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 /**\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 static _jsonSchemaVersion: string = 'firestore/geoPoint/1.0';\n static _jsonSchema = {\n type: property('string', GeoPoint._jsonSchemaVersion),\n latitude: property('number'),\n longitude: property('number')\n };\n\n /**\n * Returns a JSON-serializable representation of this `GeoPoint` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): { latitude: number; longitude: number; type: string } {\n return {\n latitude: this._lat,\n longitude: this._long,\n type: GeoPoint._jsonSchemaVersion\n };\n }\n\n /**\n * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}.\n *\n * @param json a JSON object represention of a `GeoPoint` instance\n * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): GeoPoint {\n if (validateJSON(json, GeoPoint._jsonSchema)) {\n return new GeoPoint(json.latitude, json.longitude);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating GeoPoint from JSON.'\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';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\n\n/**\n * Represents a vector type in Firestore documents.\n * Create an instance with {@link 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` values have the same raw number arrays, returns `false` otherwise.\n */\n isEqual(other: VectorValue): boolean {\n return isPrimitiveArrayEqual(this._values, other._values);\n }\n\n static _jsonSchemaVersion: string = 'firestore/vectorValue/1.0';\n static _jsonSchema = {\n type: property('string', VectorValue._jsonSchemaVersion),\n vectorValues: property('object')\n };\n\n /**\n * Returns a JSON-serializable representation of this `VectorValue` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: VectorValue._jsonSchemaVersion,\n vectorValues: this._values\n };\n }\n\n /**\n * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}.\n *\n * @param json a JSON object represention of a `VectorValue` instance.\n * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): VectorValue {\n if (validateJSON(json, VectorValue._jsonSchema)) {\n if (\n Array.isArray(json.vectorValues) &&\n json.vectorValues.every(element => typeof element === 'number')\n ) {\n return new VectorValue(json.vectorValues);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Expected 'vectorValues' field to be a number array\"\n );\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Timestamp from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData,\n FieldPath as PublicFieldPath,\n SetOptions\n} from '@firebase/firestore-types';\nimport { Compat, deepEqual, getModularInstance } from '@firebase/util';\n\nimport { ParseContext } from '../api/parse_context';\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n FieldTransform,\n Mutation,\n PatchMutation,\n Precondition,\n SetMutation\n} from '../model/mutation';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform\n} from '../model/transform_operation';\nimport {\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(0x9c4b, 'Unexpected case for UserDataSource', {\n dataSource\n });\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\nexport function 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(0xf2a2, 'Invalid value type', {\n value\n });\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 0x25d8,\n 'ReferenceValue is not valid',\n { name }\n );\n const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3));\n const key = new DocumentKey(resourcePath.popFirst(5));\n\n if (!databaseId.isEqual(expectedDatabaseId)) {\n // TODO(b/64130202): Somehow support foreign references.\n logError(\n `Document ${key} contains a document ` +\n `reference within a different database (` +\n `${databaseId.projectId}/${databaseId.database}) which is not ` +\n `supported. It will be treated as a reference in the current ` +\n `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` +\n `instead.`\n );\n }\n return key;\n }\n\n protected abstract convertReference(name: string): unknown;\n\n protected abstract convertBytes(bytes: ByteString): unknown;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData as PublicDocumentData,\n SetOptions as PublicSetOptions\n} from '@firebase/firestore-types';\nimport { getModularInstance } from '@firebase/util';\n\nimport { LimitType } from '../core/query';\nimport { DeleteMutation, Precondition } from '../model/mutation';\nimport {\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc,\n invokeRunQueryRpc\n} from '../remote/datastore';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { cast } from '../util/input_validation';\n\nimport { Bytes } from './bytes';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { validateHasExplicitOrderByForLimitToLast } from './query';\nimport {\n CollectionReference,\n doc,\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot\n} from './snapshot';\nimport {\n newUserDataReader,\n ParsedUpdateData,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converts custom model object of type T into `DocumentData` by applying the\n * converter if it exists.\n *\n * This function is used when converting user objects to `DocumentData`\n * because we want to provide the user with a more specific error message if\n * their `set()` or fails due to invalid data originating from a `toFirestore()`\n * call.\n */\nexport function applyFirestoreDataConverter(\n converter: UntypedFirestoreDataConverter | null,\n value: WithFieldValue | PartialWithFieldValue,\n options?: PublicSetOptions\n): PublicDocumentData {\n let convertedValue;\n if (converter) {\n if (options && (options.merge || options.mergeFields)) {\n // Cast to `any` in order to satisfy the union type constraint on\n // toFirestore().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n convertedValue = (converter as any).toFirestore(value, options);\n } else {\n convertedValue = converter.toFirestore(value as WithFieldValue);\n }\n } else {\n convertedValue = value as PublicDocumentData;\n }\n return convertedValue;\n}\n\nexport class LiteUserDataWriter extends AbstractUserDataWriter {\n constructor(protected firestore: Firestore) {\n super();\n }\n\n protected convertBytes(bytes: ByteString): Bytes {\n return new Bytes(bytes);\n }\n\n protected convertReference(name: string): DocumentReference {\n const key = this.convertDocumentKey(name, this.firestore._databaseId);\n return new DocumentReference(this.firestore, /* converter= */ null, key);\n }\n}\n\n/**\n * Reads the document referred to by the specified document reference.\n *\n * All documents are directly fetched from the server, even if the document was\n * previously read or modified. Recent modifications are only reflected in the\n * retrieved `DocumentSnapshot` if they have already been applied by the\n * backend. If the client is offline, the read fails. If you like to use\n * caching or see local modifications, please use the full Firestore SDK.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the current\n * document contents.\n */\nexport function getDoc(\n reference: DocumentReference\n): Promise> {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n const userDataWriter = new LiteUserDataWriter(reference.firestore);\n\n return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then(\n result => {\n hardAssert(\n result.length === 1,\n 0x3d02,\n 'Expected a single document result'\n );\n const document = result[0];\n return new DocumentSnapshot(\n reference.firestore,\n userDataWriter,\n reference._key,\n document.isFoundDocument() ? document : null,\n reference.converter\n );\n }\n );\n}\n\n/**\n * Executes the query and returns the results as a {@link QuerySnapshot}.\n *\n * All queries are executed directly by the server, even if the query was\n * previously executed. Recent modifications are only reflected in the retrieved\n * results if they have already been applied by the backend. If the client is\n * offline, the operation fails. To see previously cached result and local\n * modifications, use the full Firestore SDK.\n *\n * @param query - The `Query` to execute.\n * @returns A Promise that will be resolved with the results of the query.\n */\nexport function getDocs(\n query: Query\n): Promise> {\n query = cast>(query, Query);\n validateHasExplicitOrderByForLimitToLast(query._query);\n\n const datastore = getDatastore(query.firestore);\n const userDataWriter = new LiteUserDataWriter(query.firestore);\n return invokeRunQueryRpc(datastore, query._query).then(result => {\n const docs = result.map(\n doc =>\n new QueryDocumentSnapshot(\n query.firestore,\n userDataWriter,\n doc.key,\n doc,\n query.converter\n )\n );\n\n if (query._query.limitType === LimitType.Last) {\n // Limit to last queries reverse the orderBy constraint that was\n // specified by the user. As such, we need to reverse the order of the\n // results to return the documents in the expected order.\n docs.reverse();\n }\n\n return new QuerySnapshot(query, docs);\n });\n}\n\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\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 * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\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 convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data,\n options\n );\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'setDoc',\n reference._key,\n convertedValue,\n reference.converter !== null,\n options\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference`. The update will fail if applied to a document that does\n * not exist.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\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 * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\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 dataReader = newUserDataReader(reference.firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed: ParsedUpdateData;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData\n );\n }\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.exists(true))\n ]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * The deletion will only be reflected in document reads that occur after the\n * returned promise resolves. If the client is offline, the\n * delete fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to delete.\n * @returns A `Promise` resolved once the document has been successfully\n * deleted from the backend.\n */\nexport function deleteDoc(\n reference: DocumentReference\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n new DeleteMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend.\n */\nexport function addDoc(\n reference: CollectionReference,\n data: WithFieldValue\n): Promise> {\n reference = cast>(\n reference,\n CollectionReference\n );\n const docRef = doc(reference);\n\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data as PartialWithFieldValue\n );\n\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'addDoc',\n docRef._key,\n convertedValue,\n docRef.converter !== null,\n {}\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(docRef._key, Precondition.exists(false))\n ]).then(() => docRef);\n}\n","/**\n * @license\n * Copyright 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 { deepEqual } from '@firebase/util';\n\nimport { AggregateImpl } from '../core/aggregate';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { invokeRunAggregationQueryRpc } from '../remote/datastore';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport {\n AggregateField,\n AggregateQuerySnapshot,\n AggregateSpec\n} from './aggregate_types';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { DocumentData, Query, queryEqual } from './reference';\nimport { LiteUserDataWriter } from './reference_impl';\nimport { fieldPathFromArgument } from './user_data_reader';\n\n/**\n * Calculates the number of documents in the result set of the given query\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can\n * count the documents in cases where the result set is prohibitively large to\n * download entirely (thousands of documents).\n *\n * @param query The query whose result set size is calculated.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */\nexport function getCount(\n query: Query\n): Promise<\n AggregateQuerySnapshot<\n { count: AggregateField },\n AppModelType,\n DbModelType\n >\n> {\n const countQuerySpec: { count: AggregateField } = {\n count: count()\n };\n\n return getAggregate(query, countQuerySpec);\n}\n\n/**\n * Calculates the specified aggregations over the documents in the result\n * set of the given query without actually downloading the documents.\n *\n * Using this function to perform aggregations is efficient because only the\n * final aggregation values, not the documents' data, are downloaded. This\n * function can perform aggregations of the documents in cases where the result\n * set is prohibitively large to download entirely (thousands of documents).\n *\n * @param query The query whose result set is aggregated over.\n * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates\n * to perform over the result set. The AggregateSpec specifies aliases for each\n * aggregate, which can be used to retrieve the aggregate result.\n * @example\n * ```typescript\n * const aggregateSnapshot = await getAggregate(query, {\n * countOfDocs: count(),\n * totalHours: sum('hours'),\n * averageScore: average('score')\n * });\n *\n * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;\n * const totalHours: number = aggregateSnapshot.data().totalHours;\n * const averageScore: number | null = aggregateSnapshot.data().averageScore;\n * ```\n */\nexport function getAggregate<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n aggregateSpec: AggregateSpecType\n): Promise<\n AggregateQuerySnapshot\n> {\n const firestore = cast(query.firestore, Firestore);\n const datastore = getDatastore(firestore);\n\n const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n\n // Run the aggregation and convert the results\n return invokeRunAggregationQueryRpc(\n datastore,\n query._query,\n internalAggregates\n ).then(aggregateResult =>\n convertToAggregateQuerySnapshot(firestore, query, aggregateResult)\n );\n}\n\nfunction convertToAggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n query: Query,\n aggregateResult: ApiClientObjectMap\n): AggregateQuerySnapshot {\n const userDataWriter = new LiteUserDataWriter(firestore);\n const querySnapshot = new AggregateQuerySnapshot<\n AggregateSpecType,\n AppModelType,\n DbModelType\n >(query, userDataWriter, aggregateResult);\n return querySnapshot;\n}\n\n/**\n * Create an AggregateField object that can be used to compute the sum of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to sum across the result set.\n */\nexport function sum(field: string | FieldPath): AggregateField {\n return new AggregateField('sum', fieldPathFromArgument('sum', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the average of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to average across the result set.\n */\nexport function average(\n field: string | FieldPath\n): AggregateField {\n return new AggregateField('avg', fieldPathFromArgument('average', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the count of\n * documents in the result set of a query.\n */\nexport function count(): AggregateField {\n return new AggregateField('count');\n}\n\n/**\n * Compares two 'AggregateField` instances for equality.\n *\n * @param left Compare this AggregateField to the `right`.\n * @param right Compare this AggregateField to the `left`.\n */\nexport function aggregateFieldEqual(\n left: AggregateField,\n right: AggregateField\n): boolean {\n return (\n left instanceof AggregateField &&\n right instanceof AggregateField &&\n left.aggregateType === right.aggregateType &&\n left._internalFieldPath?.canonicalString() ===\n right._internalFieldPath?.canonicalString()\n );\n}\n\n/**\n * Compares two `AggregateQuerySnapshot` instances for equality.\n *\n * Two `AggregateQuerySnapshot` instances are considered \"equal\" if they have\n * underlying queries that compare equal, and the same data.\n *\n * @param left - The first `AggregateQuerySnapshot` to compare.\n * @param right - The second `AggregateQuerySnapshot` to compare.\n *\n * @returns `true` if the objects are \"equal\", as defined above, or `false`\n * otherwise.\n */\nexport function aggregateQuerySnapshotEqual<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n left: AggregateQuerySnapshot,\n right: AggregateQuerySnapshot\n): boolean {\n return (\n queryEqual(left.query, right.query) && deepEqual(left.data(), right.data())\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { JsonObject } from '../model/object_value';\nimport { FirestoreError } from '../util/error';\n\n/**\n * Observer/Subscribe interfaces.\n */\nexport type NextFn = (value: T) => void;\nexport type ErrorFn = (error: FirestoreError) => void;\nexport type CompleteFn = () => void;\n\n// Allow for any of the Observer methods to be undefined.\nexport interface PartialObserver {\n next?: NextFn;\n error?: ErrorFn;\n complete?: CompleteFn;\n}\n\nexport function isPartialObserver(obj: unknown): obj is PartialObserver {\n return implementsAnyMethods(obj, ['next', 'error', 'complete']);\n}\n\n/**\n * Returns true if obj is an object and contains at least one of the specified\n * methods.\n */\nfunction implementsAnyMethods(obj: unknown, methods: string[]): boolean {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n\n const object = obj as JsonObject;\n for (const method of methods) {\n if (method in object && typeof object[method] === 'function') {\n return true;\n }\n }\n return false;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\nimport { DatabaseId } from '../../../src/core/database_info';\nimport {\n LimitType,\n Query,\n queryToTarget,\n queryWithLimit\n} from '../../../src/core/query';\nimport { DocumentKey } from '../../../src/model/document_key';\nimport { newSerializer } from '../../../src/platform/serializer';\nimport { newTextEncoder } from '../../../src/platform/text_serializer';\nimport {\n BundleElement,\n LimitType as BundleLimitType\n} from '../../../src/protos/firestore_bundle_proto';\nimport * as api from '../../../src/protos/firestore_proto_api';\nimport { Value } from '../../../src/protos/firestore_proto_api';\nimport {\n JsonProtoSerializer,\n toName,\n toQueryTarget\n} from '../../../src/remote/serializer';\n\nexport const encoder = newTextEncoder();\n\nfunction lengthPrefixedString(o: {}): string {\n const str = JSON.stringify(o);\n const l = encoder.encode(str).byteLength;\n return `${l}${str}`;\n}\n\nexport class TestBundleBuilder {\n readonly elements: BundleElement[] = [];\n private serializer: JsonProtoSerializer;\n constructor(private databaseId: DatabaseId) {\n this.serializer = newSerializer(databaseId);\n }\n\n addDocumentMetadata(\n docKey: DocumentKey,\n readTime: api.Timestamp,\n exists: boolean\n ): TestBundleBuilder {\n this.elements.push({\n documentMetadata: {\n name: toName(this.serializer, docKey),\n readTime,\n exists\n }\n });\n return this;\n }\n addDocument(\n docKey: DocumentKey,\n createTime: api.Timestamp,\n updateTime: api.Timestamp,\n fields: api.ApiClientObjectMap\n ): TestBundleBuilder {\n this.elements.push({\n document: {\n name: toName(this.serializer, docKey),\n createTime,\n updateTime,\n fields\n }\n });\n return this;\n }\n\n addNamedQuery(\n name: string,\n readTime: api.Timestamp,\n query: Query\n ): TestBundleBuilder {\n let bundledLimitType: BundleLimitType | undefined = !!query.limit\n ? 'FIRST'\n : undefined;\n if (query.limitType === LimitType.Last) {\n query = queryWithLimit(query, query.limit!, LimitType.First);\n bundledLimitType = 'LAST';\n }\n const queryTarget = toQueryTarget(\n this.serializer,\n queryToTarget(query)\n ).queryTarget;\n this.elements.push({\n namedQuery: {\n name,\n readTime,\n bundledQuery: {\n parent: queryTarget.parent,\n structuredQuery: queryTarget.structuredQuery,\n limitType: bundledLimitType\n }\n }\n });\n return this;\n }\n\n getMetadataElement(\n id: string,\n createTime: api.Timestamp,\n version = 1\n ): BundleElement {\n let totalDocuments = 0;\n let totalBytes = 0;\n for (const element of this.elements) {\n if (element.documentMetadata && !element.documentMetadata.exists) {\n totalDocuments += 1;\n }\n if (element.document) {\n totalDocuments += 1;\n }\n totalBytes += encoder.encode(lengthPrefixedString(element)).byteLength;\n }\n\n return {\n metadata: {\n id,\n createTime,\n version,\n totalDocuments,\n totalBytes\n }\n };\n }\n\n build(id: string, createTime: api.Timestamp, version = 1): string {\n let result = '';\n for (const element of this.elements) {\n result += lengthPrefixedString(element);\n }\n return (\n lengthPrefixedString(this.getMetadataElement(id, createTime, version)) +\n result\n );\n }\n}\n\n// TODO(wuandy): Ideally, these should use `TestBundleBuilder` above.\nexport const meta: BundleElement = {\n metadata: {\n id: 'test-bundle',\n createTime: { seconds: 1577836805, nanos: 6 },\n version: 1,\n totalDocuments: 1,\n totalBytes: 416\n }\n};\nexport const metaString = lengthPrefixedString(meta);\n\nexport const doc1Meta: BundleElement = {\n documentMetadata: {\n name: 'projects/test-project/databases/(default)/documents/collectionId/doc1',\n readTime: { seconds: 5, nanos: 6 },\n exists: true\n }\n};\nexport const doc1MetaString = lengthPrefixedString(doc1Meta);\nexport const doc1: BundleElement = {\n document: {\n name: 'projects/test-project/databases/(default)/documents/collectionId/doc1',\n createTime: { seconds: 1, nanos: 2000000 },\n updateTime: { seconds: 3, nanos: 4000 },\n fields: { foo: { stringValue: 'value' }, bar: { integerValue: -42 } }\n }\n};\nexport const doc1String = lengthPrefixedString(doc1);\n\nexport const doc2Meta: BundleElement = {\n documentMetadata: {\n name: 'projects/test-project/databases/(default)/documents/collectionId/doc2',\n readTime: { seconds: 5, nanos: 6 },\n exists: true\n }\n};\nexport const doc2MetaString = lengthPrefixedString(doc2Meta);\nexport const doc2: BundleElement = {\n document: {\n name: 'projects/test-project/databases/(default)/documents/collectionId/doc2',\n createTime: { seconds: 1, nanos: 2000000 },\n updateTime: { seconds: 3, nanos: 4000 },\n fields: {\n foo: { stringValue: 'value1' },\n bar: { integerValue: 42 },\n emptyArray: { arrayValue: {} },\n emptyMap: { mapValue: {} }\n }\n }\n};\nexport const doc2String = lengthPrefixedString(doc2);\n\nexport const noDocMeta: BundleElement = {\n documentMetadata: {\n name: 'projects/test-project/databases/(default)/documents/collectionId/nodoc',\n readTime: { seconds: 5, nanos: 6 },\n exists: false\n }\n};\nexport const noDocMetaString = lengthPrefixedString(noDocMeta);\n\nexport const limitQuery: BundleElement = {\n namedQuery: {\n name: 'limitQuery',\n bundledQuery: {\n parent: 'projects/fireeats-97d5e/databases/(default)/documents',\n structuredQuery: {\n from: [{ collectionId: 'node_3.7.5_7Li7XoCjutvNxwD0tpo9' }],\n orderBy: [{ field: { fieldPath: 'sort' }, direction: 'DESCENDING' }],\n limit: { 'value': 1 }\n },\n limitType: 'FIRST'\n },\n readTime: { 'seconds': 1590011379, 'nanos': 191164000 }\n }\n};\nexport const limitQueryString = lengthPrefixedString(limitQuery);\nexport const limitToLastQuery: BundleElement = {\n namedQuery: {\n name: 'limitToLastQuery',\n bundledQuery: {\n parent: 'projects/fireeats-97d5e/databases/(default)/documents',\n structuredQuery: {\n from: [{ collectionId: 'node_3.7.5_7Li7XoCjutvNxwD0tpo9' }],\n orderBy: [{ field: { fieldPath: 'sort' }, direction: 'ASCENDING' }],\n limit: { 'value': 1 }\n },\n limitType: 'LAST'\n },\n readTime: { 'seconds': 1590011379, 'nanos': 543063000 }\n }\n};\nexport const limitToLastQueryString = lengthPrefixedString(limitToLastQuery);\n","/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 JsonProtoSerializer,\n fromTimestamp,\n toName,\n toQueryTarget,\n toTimestamp\n} from '../../src/remote/serializer';\nimport { encoder } from '../../test/unit/util/bundle_data';\nimport { Firestore } from '../api/database';\nimport { DatabaseId } from '../core/database_info';\nimport { Query, queryToTarget } from '../core/query';\nimport { DocumentData } from '../lite-api/reference';\nimport { Timestamp } from '../lite-api/timestamp';\nimport {\n parseObject,\n UserDataReader,\n UserDataSource\n} from '../lite-api/user_data_reader';\nimport { DocumentKey } from '../model/document_key';\nimport {\n BundledDocumentMetadata as ProtoBundledDocumentMetadata,\n BundleElement as ProtoBundleElement,\n BundleMetadata as ProtoBundleMetadata,\n NamedQuery as ProtoNamedQuery\n} from '../protos/firestore_bundle_proto';\nimport {\n Document as ProtoDocument,\n Document\n} from '../protos/firestore_proto_api';\n\nconst BUNDLE_VERSION = 1;\n\n/**\n * Builds a Firestore data bundle with results from the given document and query snapshots.\n */\nexport class BundleBuilder {\n // Resulting documents for the bundle, keyed by full document path.\n private documents: Map = new Map();\n // Named queries saved in the bundle, keyed by query name.\n private namedQueries: Map = new Map();\n\n // The latest read time among all bundled documents and queries.\n private latestReadTime = new Timestamp(0, 0);\n\n // Database identifier which is part of the serialized bundle.\n private databaseId: DatabaseId;\n\n // Tools to convert public data types into their serialized form.\n private readonly serializer: JsonProtoSerializer;\n private readonly userDataReader: UserDataReader;\n\n constructor(private firestore: Firestore, readonly bundleId: string) {\n this.databaseId = firestore._databaseId;\n\n // useProto3Json is true because the objects will be serialized to JSON string\n // before being written to the bundle buffer.\n this.serializer = new JsonProtoSerializer(\n this.databaseId,\n /*useProto3Json=*/ true\n );\n\n this.userDataReader = new UserDataReader(\n this.databaseId,\n true,\n this.serializer\n );\n }\n\n /**\n * Adds data from a DocumentSnapshot to the bundle.\n * @internal\n * @param docBundleData A DocumentSnapshotBundleData containing information from the\n * DocumentSnapshot. Note we cannot accept a DocumentSnapshot directly due to a circular\n * dependency error.\n * @param queryName The name of the QuerySnapshot if this document is part of a Query.\n */\n addBundleDocument(\n docBundleData: DocumentSnapshotBundleData,\n queryName?: string\n ): void {\n const originalDocument = this.documents.get(docBundleData.documentPath);\n const originalQueries = originalDocument?.metadata.queries;\n const docReadTime: Timestamp | undefined = docBundleData.readTime;\n const origDocReadTime: Timestamp | null = !!originalDocument?.metadata\n .readTime\n ? fromTimestamp(originalDocument.metadata.readTime)\n : null;\n\n const neitherHasReadTime: boolean = !docReadTime && origDocReadTime == null;\n const docIsNewer: boolean =\n docReadTime !== undefined &&\n (origDocReadTime == null || origDocReadTime < docReadTime);\n if (neitherHasReadTime || docIsNewer) {\n // Store document.\n this.documents.set(docBundleData.documentPath, {\n document: this.toBundleDocument(docBundleData),\n metadata: {\n name: toName(this.serializer, docBundleData.documentKey),\n readTime: !!docReadTime\n ? toTimestamp(this.serializer, docReadTime) // Convert Timestamp to proto format.\n : undefined,\n exists: docBundleData.documentExists\n }\n });\n }\n if (docReadTime && docReadTime > this.latestReadTime) {\n this.latestReadTime = docReadTime;\n }\n // Update `queries` to include both original and `queryName`.\n if (queryName) {\n const newDocument = this.documents.get(docBundleData.documentPath)!;\n newDocument.metadata.queries = originalQueries || [];\n newDocument.metadata.queries!.push(queryName);\n }\n }\n\n /**\n * Adds data from a QuerySnapshot to the bundle.\n * @internal\n * @param docBundleData A QuerySnapshotBundleData containing information from the\n * QuerySnapshot. Note we cannot accept a QuerySnapshot directly due to a circular\n * dependency error.\n */\n addBundleQuery(queryBundleData: QuerySnapshotBundleData): void {\n if (this.namedQueries.has(queryBundleData.name)) {\n throw new Error(`Query name conflict: ${name} has already been added.`);\n }\n let latestReadTime = new Timestamp(0, 0);\n for (const docBundleData of queryBundleData.docBundleDataArray) {\n this.addBundleDocument(docBundleData, queryBundleData.name);\n if (docBundleData.readTime && docBundleData.readTime > latestReadTime) {\n latestReadTime = docBundleData.readTime;\n }\n }\n const queryTarget = toQueryTarget(\n this.serializer,\n queryToTarget(queryBundleData.query)\n );\n const bundledQuery = {\n parent: queryBundleData.parent,\n structuredQuery: queryTarget.queryTarget.structuredQuery\n };\n this.namedQueries.set(queryBundleData.name, {\n name: queryBundleData.name,\n bundledQuery,\n readTime: toTimestamp(this.serializer, latestReadTime)\n });\n }\n\n /**\n * Convert data from a DocumentSnapshot into the serialized form within a bundle.\n * @private\n * @internal\n * @param docBundleData a DocumentSnapshotBundleData containing the data required to\n * serialize a document.\n */\n private toBundleDocument(\n docBundleData: DocumentSnapshotBundleData\n ): ProtoDocument {\n // a parse context is typically used for validating and parsing user data, but in this\n // case we are using it internally to convert DocumentData to Proto3 JSON\n const context = this.userDataReader.createContext(\n UserDataSource.ArrayArgument,\n 'internal toBundledDocument'\n );\n const proto3Fields = parseObject(docBundleData.documentData, context);\n\n return {\n name: toName(this.serializer, docBundleData.documentKey),\n fields: proto3Fields.mapValue.fields,\n updateTime: toTimestamp(this.serializer, docBundleData.versionTime),\n createTime: toTimestamp(this.serializer, docBundleData.createdTime)\n };\n }\n\n /**\n * Converts a IBundleElement to a Buffer whose content is the length prefixed JSON representation\n * of the element.\n * @private\n * @internal\n * @param bundleElement A ProtoBundleElement that is expected to be Proto3 JSON compatible.\n */\n private lengthPrefixedString(bundleElement: ProtoBundleElement): string {\n const str = JSON.stringify(bundleElement);\n // TODO: it's not ideal to have to re-encode all of these strings multiple times\n // It may be more performant to return a UInt8Array that is concatenated to other\n // UInt8Arrays instead of returning and concatenating strings and then\n // converting the full string to UInt8Array.\n const l = encoder.encode(str).byteLength;\n return `${l}${str}`;\n }\n\n /**\n * Construct a serialized string containing document and query information that has previously\n * been added to the BundleBuilder through the addBundleDocument and addBundleQuery methods.\n * @internal\n */\n build(): string {\n let bundleString = '';\n\n for (const namedQuery of this.namedQueries.values()) {\n bundleString += this.lengthPrefixedString({ namedQuery });\n }\n\n for (const bundledDocument of this.documents.values()) {\n const documentMetadata: ProtoBundledDocumentMetadata =\n bundledDocument.metadata;\n\n bundleString += this.lengthPrefixedString({ documentMetadata });\n // Write to the bundle if document exists.\n const document = bundledDocument.document;\n if (document) {\n bundleString += this.lengthPrefixedString({ document });\n }\n }\n\n const metadata: ProtoBundleMetadata = {\n id: this.bundleId,\n createTime: toTimestamp(this.serializer, this.latestReadTime),\n version: BUNDLE_VERSION,\n totalDocuments: this.documents.size,\n // TODO: it's not ideal to have to re-encode all of these strings multiple times\n totalBytes: encoder.encode(bundleString).length\n };\n // Prepends the metadata element to the bundleBuffer: `bundleBuffer` is the second argument to `Buffer.concat`.\n bundleString = this.lengthPrefixedString({ metadata }) + bundleString;\n\n return bundleString;\n }\n}\n\n/**\n * Interface for an object that contains data required to bundle a DocumentSnapshot.\n * @internal\n */\nexport interface DocumentSnapshotBundleData {\n documentData: DocumentData;\n documentKey: DocumentKey;\n documentPath: string;\n documentExists: boolean;\n createdTime: Timestamp;\n readTime?: Timestamp;\n versionTime: Timestamp;\n}\n\n/**\n * Interface for an object that contains data required to bundle a QuerySnapshot.\n * @internal\n */\nexport interface QuerySnapshotBundleData {\n name: string;\n query: Query;\n parent: string;\n docBundleDataArray: DocumentSnapshotBundleData[];\n}\n\n/**\n * Convenient class to hold both the metadata and the actual content of a document to be bundled.\n * @private\n * @internal\n */\nclass BundledDocument {\n constructor(\n readonly metadata: ProtoBundledDocumentMetadata,\n readonly document?: Document\n ) {}\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 build JSON bundle implementations. */\nimport { Firestore } from '../../api/database';\nimport { Query } from '../../core/query';\nimport { DocumentData } from '../../lite-api/reference';\nimport { Document } from '../../model/document';\nimport {\n BundleBuilder,\n DocumentSnapshotBundleData,\n QuerySnapshotBundleData\n} from '../../util/bundle_builder_impl';\nimport { AutoId } from '../../util/misc';\n\nexport function buildDocumentSnapshotJsonBundle(\n db: Firestore,\n document: Document,\n docData: DocumentData,\n path: string\n): string {\n const builder: BundleBuilder = new BundleBuilder(db, AutoId.newId());\n builder.addBundleDocument(\n documentToDocumentSnapshotBundleData(path, docData, document)\n );\n return builder.build();\n}\n\nexport function buildQuerySnapshotJsonBundle(\n db: Firestore,\n query: Query,\n bundleName: string,\n parent: string,\n paths: string[],\n docs: Document[],\n documentData: DocumentData[]\n): string {\n const docBundleDataArray: DocumentSnapshotBundleData[] = [];\n for (let i = 0; i < docs.length; i++) {\n docBundleDataArray.push(\n documentToDocumentSnapshotBundleData(paths[i], documentData[i], docs[i])\n );\n }\n const bundleData: QuerySnapshotBundleData = {\n name: bundleName,\n query,\n parent,\n docBundleDataArray\n };\n const builder: BundleBuilder = new BundleBuilder(db, bundleName);\n builder.addBundleQuery(bundleData);\n return builder.build();\n}\n\n// Formats Document data for bundling a DocumentSnapshot.\nfunction documentToDocumentSnapshotBundleData(\n path: string,\n documentData: DocumentData,\n document: Document\n): DocumentSnapshotBundleData {\n return {\n documentData,\n documentKey: document.mutableCopy().key,\n documentPath: path,\n documentExists: true,\n createdTime: document.createTime.toTimestamp(),\n readTime: document.readTime.toTimestamp(),\n versionTime: document.version.toTimestamp()\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 { BundleLoader } from '../core/bundle_impl';\nimport { createBundleReaderSync } from '../core/firestore_client';\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 { LiteUserDataWriter } from '../lite-api/reference_impl';\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 { fromBundledQuery } from '../local/local_serializer';\nimport { documentKeySet } from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { DocumentSet } from '../model/document_set';\nimport { ResourcePath } from '../model/path';\nimport { newSerializer } from '../platform/serializer';\nimport {\n buildQuerySnapshotJsonBundle,\n buildDocumentSnapshotJsonBundle\n} from '../platform/snapshot_to_json';\nimport { fromDocument } from '../remote/serializer';\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\nimport { AutoId } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { SnapshotListenOptions } from './reference_impl';\n\nconst NOT_SUPPORTED = 'NOT SUPPORTED';\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 static _jsonSchemaVersion: string = 'firestore/documentSnapshot/1.0';\n static _jsonSchema = {\n type: property('string', DocumentSnapshot._jsonSchemaVersion),\n bundleSource: property('string', 'DocumentSnapshot'),\n bundleName: property('string'),\n bundle: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `DocumentSnapshot` instance.\n *\n * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this\n * `DocumentSnapshot` has pending writes.\n */\n toJSON(): object {\n if (this.metadata.hasPendingWrites) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'DocumentSnapshot.toJSON() attempted to serialize a document with pending writes. ' +\n 'Await waitForPendingWrites() before invoking toJSON().'\n );\n }\n const document = this._document;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: any = {};\n result['type'] = DocumentSnapshot._jsonSchemaVersion;\n result['bundle'] = '';\n result['bundleSource'] = 'DocumentSnapshot';\n result['bundleName'] = this._key.toString();\n\n if (\n !document ||\n !document.isValidDocument() ||\n !document.isFoundDocument()\n ) {\n return result;\n }\n const documentData = this._userDataWriter.convertObjectMap(\n document.data.value.mapValue.fields,\n 'previous'\n );\n result['bundle'] = buildDocumentSnapshotJsonBundle(\n this._firestore,\n document,\n documentData,\n this.ref.path\n );\n return result;\n }\n}\n\n/**\n * Builds a `DocumentSnapshot` instance from a JSON object created by\n * {@link DocumentSnapshot.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json - a JSON object represention of a `DocumentSnapshot` instance.\n * @returns an instance of {@link DocumentSnapshot} if the JSON object could be\n * parsed. Throws a {@link FirestoreError} if an error occurs.\n */\nexport function documentSnapshotFromJSON(\n db: Firestore,\n json: object\n): DocumentSnapshot;\n/**\n * Builds a `DocumentSnapshot` instance from a JSON object created by\n * {@link DocumentSnapshot.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json - a JSON object represention of a `DocumentSnapshot` instance.\n * @param converter - Converts objects to and from Firestore.\n * @returns an instance of {@link DocumentSnapshot} if the JSON object could be\n * parsed. Throws a {@link FirestoreError} if an error occurs.\n */\nexport function documentSnapshotFromJSON<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n>(\n db: Firestore,\n json: object,\n converter: FirestoreDataConverter\n): DocumentSnapshot;\nexport function documentSnapshotFromJSON<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n>(\n db: Firestore,\n json: object,\n converter?: FirestoreDataConverter\n): DocumentSnapshot {\n if (validateJSON(json, DocumentSnapshot._jsonSchema)) {\n if (json.bundle === NOT_SUPPORTED) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'The provided JSON object was created in a client environment, which is not supported.'\n );\n }\n // Parse the bundle data.\n const serializer = newSerializer(db._databaseId);\n const bundleReader = createBundleReaderSync(json.bundle, serializer);\n const elements = bundleReader.getElements();\n const bundleLoader: BundleLoader = new BundleLoader(\n bundleReader.getMetadata(),\n serializer\n );\n for (const element of elements) {\n bundleLoader.addSizedElement(element);\n }\n\n // Ensure that we have the correct number of documents in the bundle.\n const bundledDocuments = bundleLoader.documents;\n if (bundledDocuments.length !== 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Expected bundle data to contain 1 document, but it contains ${bundledDocuments.length} documents.`\n );\n }\n\n // Build out the internal document data.\n const document = fromDocument(serializer, bundledDocuments[0].document!);\n const documentKey = new DocumentKey(\n ResourcePath.fromString(json.bundleName)\n );\n\n // Return the external facing DocumentSnapshot.\n return new DocumentSnapshot(\n db,\n new LiteUserDataWriter(db),\n documentKey,\n document,\n new SnapshotMetadata(\n /* hasPendingWrites= */ false,\n /* fromCache= */ false\n ),\n converter ? converter : null\n );\n }\n throw new FirestoreError(\n Code.INTERNAL,\n 'Unexpected error creating DocumentSnapshot from JSON.'\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 static _jsonSchemaVersion: string = 'firestore/querySnapshot/1.0';\n static _jsonSchema = {\n type: property('string', QuerySnapshot._jsonSchemaVersion),\n bundleSource: property('string', 'QuerySnapshot'),\n bundleName: property('string'),\n bundle: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `QuerySnapshot` instance.\n *\n * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this\n * `QuerySnapshot` has pending writes.\n */\n toJSON(): object {\n if (this.metadata.hasPendingWrites) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'QuerySnapshot.toJSON() attempted to serialize a document with pending writes. ' +\n 'Await waitForPendingWrites() before invoking toJSON().'\n );\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: any = {};\n result['type'] = QuerySnapshot._jsonSchemaVersion;\n result['bundleSource'] = 'QuerySnapshot';\n result['bundleName'] = AutoId.newId();\n\n const databaseId = this._firestore._databaseId.database;\n const projectId = this._firestore._databaseId.projectId;\n const parent = `projects/${projectId}/databases/${databaseId}/documents`;\n const documents: Document[] = [];\n const documentData: DocumentData[] = [];\n const paths: string[] = [];\n\n this.docs.forEach(doc => {\n if (doc._document === null) {\n return;\n }\n documents.push(doc._document);\n documentData.push(\n this._userDataWriter.convertObjectMap(\n doc._document.data.value.mapValue.fields,\n 'previous'\n )\n );\n paths.push(doc.ref.path);\n });\n result['bundle'] = buildQuerySnapshotJsonBundle(\n this._firestore,\n this.query._query,\n result['bundleName'],\n parent,\n paths,\n documents,\n documentData\n );\n return result;\n }\n}\n\n/**\n * Builds a `QuerySnapshot` instance from a JSON object created by\n * {@link QuerySnapshot.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json - a JSON object represention of a `QuerySnapshot` instance.\n * @returns an instance of {@link QuerySnapshot} if the JSON object could be\n * parsed. Throws a {@link FirestoreError} if an error occurs.\n */\nexport function querySnapshotFromJSON(\n db: Firestore,\n json: object\n): QuerySnapshot;\n/**\n * Builds a `QuerySnapshot` instance from a JSON object created by\n * {@link QuerySnapshot.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json - a JSON object represention of a `QuerySnapshot` instance.\n * @param converter - Converts objects to and from Firestore.\n * @returns an instance of {@link QuerySnapshot} if the JSON object could be\n * parsed. Throws a {@link FirestoreError} if an error occurs.\n */\nexport function querySnapshotFromJSON<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n>(\n db: Firestore,\n json: object,\n converter: FirestoreDataConverter\n): QuerySnapshot;\nexport function querySnapshotFromJSON<\n AppModelType,\n DbModelType extends DocumentData\n>(\n db: Firestore,\n json: object,\n converter?: FirestoreDataConverter\n): QuerySnapshot {\n if (validateJSON(json, QuerySnapshot._jsonSchema)) {\n if (json.bundle === NOT_SUPPORTED) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'The provided JSON object was created in a client environment, which is not supported.'\n );\n }\n // Parse the bundle data.\n const serializer = newSerializer(db._databaseId);\n const bundleReader = createBundleReaderSync(json.bundle, serializer);\n const elements = bundleReader.getElements();\n const bundleLoader: BundleLoader = new BundleLoader(\n bundleReader.getMetadata(),\n serializer\n );\n for (const element of elements) {\n bundleLoader.addSizedElement(element);\n }\n\n if (bundleLoader.queries.length !== 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Snapshot data expected 1 query but found ${bundleLoader.queries.length} queries.`\n );\n }\n\n // Create an internal Query object from the named query in the bundle.\n const query = fromBundledQuery(bundleLoader.queries[0].bundledQuery!);\n\n // Construct the arrays of document data for the query.\n const bundledDocuments = bundleLoader.documents;\n let documentSet = new DocumentSet();\n bundledDocuments.map(bundledDocument => {\n const document = fromDocument(serializer, bundledDocument.document!);\n documentSet = documentSet.add(document);\n });\n // Create a view snapshot of the query and documents.\n const viewSnapshot = ViewSnapshot.fromInitialDocuments(\n query,\n documentSet,\n documentKeySet() /* Zero mutated keys signifies no pending writes. */,\n /* fromCache= */ false,\n /* hasCachedResults= */ false\n );\n\n // Create an external Query object, required to construct the QuerySnapshot.\n const externalQuery = new Query(\n db,\n converter ? converter : null,\n query\n );\n\n // Return a new QuerySnapshot with all of the collected data.\n return new QuerySnapshot(\n db,\n new LiteUserDataWriter(db),\n externalQuery,\n viewSnapshot\n );\n }\n throw new FirestoreError(\n Code.INTERNAL,\n 'Unexpected error creating QuerySnapshot from JSON.'\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(0xf03d, '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 { loadBundle, namedQuery } from '../api/database';\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 { DocumentKey } from '../model/document_key';\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { debugAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport {\n DocumentSnapshot,\n FirestoreDataConverter,\n QuerySnapshot,\n SnapshotMetadata\n} 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @returns An unsubscribe function that can be called to cancel 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @returns An unsubscribe function that can be called to cancel 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The\n * listener can be cancelled by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The\n * listener can be cancelled by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The\n * listener can be cancelled by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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` is available.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @returns An unsubscribe function that can be called to cancel 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The\n * listener can be cancelled by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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` is available.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @returns An unsubscribe function that can be called to cancel 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 // onSnapshot for Query or Document.\n reference = getModularInstance(reference);\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 }\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 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/**\n * Attaches a listener for `QuerySnapshot` events based on data generated by invoking\n * {@link QuerySnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks or\n * pass a single observer 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 never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}.\n * @param onNext - A callback to be called every time a new `QuerySnapshot` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n onNext: (snapshot: QuerySnapshot) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void,\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking\n * {@link DocumentSnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or\n * pass a single observer 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 never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}.\n * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are\n * never ending.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n onNext: (snapshot: DocumentSnapshot) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void,\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events based on data generated by invoking\n * {@link QuerySnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or\n * pass a single observer 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 never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param onNext - A callback to be called every time a new `QuerySnapshot` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n options: SnapshotListenOptions,\n onNext: (snapshot: QuerySnapshot) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void,\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking\n * {@link DocumentSnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks\n * or pass a single observer object with `next` and `error` callbacks. The listener can be cancelled\n * by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n options: SnapshotListenOptions,\n onNext: (snapshot: DocumentSnapshot) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void,\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events based on QuerySnapshot data generated by invoking\n * {@link QuerySnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or\n * pass a single observer 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 never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n observer: {\n next: (snapshot: QuerySnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n },\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking\n * {@link DocumentSnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks\n * or pass a single observer object with `next` and `error` callbacks. The listener can be cancelled\n * by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n observer: {\n next: (snapshot: DocumentSnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n },\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events based on QuerySnapshot data generated by invoking\n * {@link QuerySnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks or\n * pass a single observer 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 never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n options: SnapshotListenOptions,\n observer: {\n next: (snapshot: QuerySnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n },\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events based on QuerySnapshot data generated by\n * invoking {@link DocumentSnapshot.toJSON} You may either pass individual `onNext` and `onError`\n * callbacks or pass a single observer object with `next` and `error` callbacks. The listener can be\n * cancelled by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n options: SnapshotListenOptions,\n observer: {\n next: (snapshot: DocumentSnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n },\n converter?: FirestoreDataConverter\n): Unsubscribe;\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(reference: Firestore, snapshotJson: object, ...args: unknown[]): Unsubscribe {\n const db = getModularInstance(reference);\n const json = normalizeSnapshotJsonFields(snapshotJson);\n if (json.error) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, json.error);\n }\n let curArg = 0;\n let options: SnapshotListenOptions | undefined = undefined;\n if (typeof args[curArg] === 'object' && !isPartialObserver(args[curArg])) {\n options = args[curArg++] as SnapshotListenOptions;\n }\n\n if (json.bundleSource === 'QuerySnapshot') {\n let observer: {\n next: (snapshot: QuerySnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n } | null = null;\n if (typeof args[curArg] === 'object' && isPartialObserver(args[curArg])) {\n const userObserver = args[curArg++] as PartialObserver<\n QuerySnapshot\n >;\n observer = {\n next: userObserver.next!,\n error: userObserver.error,\n complete: userObserver.complete\n };\n } else {\n observer = {\n next: args[curArg++] as (\n snapshot: QuerySnapshot\n ) => void,\n error: args[curArg++] as (error: FirestoreError) => void,\n complete: args[curArg++] as () => void\n };\n }\n return onSnapshotQuerySnapshotBundle(\n db,\n json,\n options,\n observer!,\n args[curArg] as FirestoreDataConverter\n );\n } else if (json.bundleSource === 'DocumentSnapshot') {\n let observer: {\n next: (snapshot: DocumentSnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n } | null = null;\n if (typeof args[curArg] === 'object' && isPartialObserver(args[curArg])) {\n const userObserver = args[curArg++] as PartialObserver<\n DocumentSnapshot\n >;\n observer = {\n next: userObserver.next!,\n error: userObserver.error,\n complete: userObserver.complete\n };\n } else {\n observer = {\n next: args[curArg++] as (\n snapshot: DocumentSnapshot\n ) => void,\n error: args[curArg++] as (error: FirestoreError) => void,\n complete: args[curArg++] as () => void\n };\n }\n return onSnapshotDocumentSnapshotBundle(\n db,\n json,\n options,\n observer!,\n args[curArg] as FirestoreDataConverter\n );\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `unsupported bundle source: ${json.bundleSource}`\n );\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/**\n * Ensures the data required to construct an {@link onSnapshot} listener exist in a `snapshotJson`\n * object that originates from {@link DocumentSnapshot.toJSON} or {@link Querysnapshot.toJSON}. The\n * data is normalized into a typed object.\n *\n * @param snapshotJson - The JSON object that the app provided to {@link onSnapshot}.\n * @returns A normalized object that contains all of the required bundle JSON fields. If\n * {@link snapshotJson} doesn't contain the required fields, or if the fields exist as empty\n * strings, then the {@link snapshotJson.error} field will be a non empty string.\n *\n * @internal\n */\nfunction normalizeSnapshotJsonFields(snapshotJson: object): {\n bundle: string;\n bundleName: string;\n bundleSource: string;\n error?: string;\n} {\n const result: {\n bundle: string;\n bundleName: string;\n bundleSource: string;\n error?: string;\n } = {\n bundle: '',\n bundleName: '',\n bundleSource: ''\n };\n const requiredKeys = ['bundle', 'bundleName', 'bundleSource'];\n for (const key of requiredKeys) {\n if (!(key in snapshotJson)) {\n result.error = `snapshotJson missing required field: ${key}`;\n break;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const value = (snapshotJson as any)[key];\n if (typeof value !== 'string') {\n result.error = `snapshotJson field '${key}' must be a string.`;\n break;\n }\n if (value.length === 0) {\n result.error = `snapshotJson field '${key}' cannot be an empty string.`;\n break;\n }\n if (key === 'bundle') {\n result.bundle = value;\n } else if (key === 'bundleName') {\n result.bundleName = value;\n } else if (key === 'bundleSource') {\n result.bundleSource = value;\n }\n }\n return result;\n}\n\n/**\n * Loads the bundle in a separate task and then invokes {@link onSnapshot} with a\n * {@link DocumentReference} for the document in the bundle.\n *\n * @param firestore - The {@link Firestore} instance for the {@link onSnapshot} operation request.\n * @param json - The JSON bundle to load, produced by {@link DocumentSnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot\n * listener.\n *\n * @internal\n */\nfunction onSnapshotDocumentSnapshotBundle<\n AppModelType,\n DbModelType extends DocumentData\n>(\n db: Firestore,\n json: { bundle: string; bundleName: string; bundleSource: string },\n options: SnapshotListenOptions | undefined,\n observer: {\n next: (snapshot: DocumentSnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n },\n converter?: FirestoreDataConverter\n): Unsubscribe {\n let unsubscribed: boolean = false;\n let internalUnsubscribe: Unsubscribe | undefined;\n const loadTask = loadBundle(db, json.bundle);\n loadTask\n .then(() => {\n if (!unsubscribed) {\n const docReference = new DocumentReference(\n db,\n converter ? converter : null,\n DocumentKey.fromPath(json.bundleName)\n );\n internalUnsubscribe = onSnapshot(\n docReference as DocumentReference,\n options ? options : {},\n observer\n );\n }\n })\n .catch(e => {\n if (observer.error) {\n observer.error(e);\n }\n return () => {};\n });\n return () => {\n if (unsubscribed) {\n return;\n }\n unsubscribed = true;\n if (internalUnsubscribe) {\n internalUnsubscribe();\n }\n };\n}\n\n/**\n * Loads the bundle in a separate task and then invokes {@link onSnapshot} with a\n * {@link Query} that represents the Query in the bundle.\n *\n * @param firestore - The {@link Firestore} instance for the {@link onSnapshot} operation request.\n * @param json - The JSON bundle to load, produced by {@link QuerySnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot\n * listener.\n *\n * @internal\n */\nfunction onSnapshotQuerySnapshotBundle<\n AppModelType,\n DbModelType extends DocumentData\n>(\n db: Firestore,\n json: { bundle: string; bundleName: string; bundleSource: string },\n options: SnapshotListenOptions | undefined,\n observer: {\n next: (snapshot: QuerySnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n },\n converter?: FirestoreDataConverter\n): Unsubscribe {\n let unsubscribed: boolean = false;\n let internalUnsubscribe: Unsubscribe | undefined;\n const loadTask = loadBundle(db, json.bundle);\n loadTask\n .then(() => namedQuery(db, json.bundleName))\n .then(query => {\n if (query && !unsubscribed) {\n const realQuery: Query = (query as Query)!;\n if (converter) {\n realQuery.withConverter(converter);\n }\n internalUnsubscribe = onSnapshot(\n query as Query,\n options ? options : {},\n observer\n );\n }\n })\n .catch(e => {\n if (observer.error) {\n observer.error(e);\n }\n return () => {};\n });\n return () => {\n if (unsubscribed) {\n return;\n }\n unsubscribed = true;\n if (internalUnsubscribe) {\n internalUnsubscribe();\n }\n };\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AggregateField, AggregateSpec, DocumentData, Query } from '../api';\nimport { AggregateImpl } from '../core/aggregate';\nimport { firestoreClientRunAggregateQuery } from '../core/firestore_client';\nimport { count } from '../lite-api/aggregate';\nimport { AggregateQuerySnapshot } from '../lite-api/aggregate_types';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport { ExpUserDataWriter } from './reference_impl';\n\nexport {\n aggregateQuerySnapshotEqual,\n count,\n sum,\n average,\n aggregateFieldEqual\n} from '../lite-api/aggregate';\n\n/**\n * Calculates the number of documents in the result set of the given query\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can\n * count the documents in cases where the result set is prohibitively large to\n * download entirely (thousands of documents).\n *\n * The result received from the server is presented, unaltered, without\n * considering any local state. That is, documents in the local cache are not\n * taken into consideration, neither are local modifications not yet\n * synchronized with the server. Previously-downloaded results, if any, are not\n * used. Every invocation of this function necessarily involves a round trip to\n * the server.\n *\n * @param query The query whose result set size is calculated.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */\nexport function getCountFromServer<\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query\n): Promise<\n AggregateQuerySnapshot<\n { count: AggregateField },\n AppModelType,\n DbModelType\n >\n> {\n const countQuerySpec: { count: AggregateField } = {\n count: count()\n };\n\n return getAggregateFromServer(query, countQuerySpec);\n}\n\n/**\n * Calculates the specified aggregations over the documents in the result\n * set of the given query without actually downloading the documents.\n *\n * Using this function to perform aggregations is efficient because only the\n * final aggregation values, not the documents' data, are downloaded. This\n * function can perform aggregations of the documents in cases where the result\n * set is prohibitively large to download entirely (thousands of documents).\n *\n * The result received from the server is presented, unaltered, without\n * considering any local state. That is, documents in the local cache are not\n * taken into consideration, neither are local modifications not yet\n * synchronized with the server. Previously-downloaded results, if any, are not\n * used. Every invocation of this function necessarily involves a round trip to\n * the server.\n *\n * @param query The query whose result set is aggregated over.\n * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates\n * to perform over the result set. The AggregateSpec specifies aliases for each\n * aggregate, which can be used to retrieve the aggregate result.\n * @example\n * ```typescript\n * const aggregateSnapshot = await getAggregateFromServer(query, {\n * countOfDocs: count(),\n * totalHours: sum('hours'),\n * averageScore: average('score')\n * });\n *\n * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;\n * const totalHours: number = aggregateSnapshot.data().totalHours;\n * const averageScore: number | null = aggregateSnapshot.data().averageScore;\n * ```\n */\nexport function getAggregateFromServer<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n aggregateSpec: AggregateSpecType\n): Promise<\n AggregateQuerySnapshot\n> {\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n\n const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n\n // Run the aggregation and convert the results\n return firestoreClientRunAggregateQuery(\n client,\n query._query,\n internalAggregates\n ).then(aggregateResult =>\n convertToAggregateQuerySnapshot(firestore, query, aggregateResult)\n );\n}\n\n/**\n * Converts the core aggregation result to an `AggregateQuerySnapshot`\n * that can be returned to the consumer.\n * @param query\n * @param aggregateResult Core aggregation result\n * @internal\n */\nfunction convertToAggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n query: Query,\n aggregateResult: ApiClientObjectMap\n): AggregateQuerySnapshot {\n const userDataWriter = new ExpUserDataWriter(firestore);\n const querySnapshot = new AggregateQuerySnapshot<\n AggregateSpecType,\n AppModelType,\n DbModelType\n >(query, userDataWriter, aggregateResult);\n return querySnapshot;\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 IndexedDbOfflineComponentProvider,\n LruGcMemoryOfflineComponentProvider,\n MemoryOfflineComponentProvider,\n MultiTabOfflineComponentProvider,\n OfflineComponentProviderFactory,\n OnlineComponentProviderFactory,\n OnlineComponentProvider\n} from '../core/component_provider';\n\n/* eslint @typescript-eslint/consistent-type-definitions: [\"error\", \"type\"] */\n/**\n * Provides an in-memory cache to the SDK. This is the default cache unless explicitly\n * configured otherwise.\n *\n * To use, create an instance using the factory function {@link memoryLocalCache()}, then\n * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using\n * the settings object.\n */\nexport type MemoryLocalCache = {\n kind: 'memory';\n /**\n * @internal\n */\n _onlineComponentProvider: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n};\n\nclass MemoryLocalCacheImpl implements MemoryLocalCache {\n kind: 'memory' = 'memory';\n /**\n * @internal\n */\n _onlineComponentProvider: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n\n constructor(settings?: MemoryCacheSettings) {\n this._onlineComponentProvider = OnlineComponentProvider.provider;\n if (settings?.garbageCollector) {\n this._offlineComponentProvider =\n settings.garbageCollector._offlineComponentProvider;\n } else {\n this._offlineComponentProvider = {\n build: () => new LruGcMemoryOfflineComponentProvider(undefined)\n };\n }\n }\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n}\n\n/**\n * Provides a persistent cache backed by IndexedDb to the SDK.\n *\n * To use, create an instance using the factory function {@link persistentLocalCache()}, then\n * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using\n * the settings object.\n */\nexport type PersistentLocalCache = {\n kind: 'persistent';\n /**\n * @internal\n */\n _onlineComponentProvider: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n};\n\nclass PersistentLocalCacheImpl implements PersistentLocalCache {\n kind: 'persistent' = 'persistent';\n /**\n * @internal\n */\n _onlineComponentProvider: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n\n constructor(settings: PersistentCacheSettings | undefined) {\n let tabManager: PersistentTabManager;\n if (settings?.tabManager) {\n settings.tabManager._initialize(settings);\n tabManager = settings.tabManager;\n } else {\n tabManager = persistentSingleTabManager(undefined);\n tabManager._initialize(settings);\n }\n this._onlineComponentProvider = tabManager._onlineComponentProvider!;\n this._offlineComponentProvider = tabManager._offlineComponentProvider!;\n }\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n}\n\n/**\n * Union type from all supported SDK cache layer.\n */\nexport type FirestoreLocalCache = MemoryLocalCache | PersistentLocalCache;\n\n/**\n * Union type from all support garbage collectors for memory local cache.\n */\nexport type MemoryGarbageCollector =\n | MemoryEagerGarbageCollector\n | MemoryLruGarbageCollector;\n\n/**\n * A garbage collector deletes documents whenever they are not part of any\n * active queries, and have no local mutations attached to them.\n *\n * This collector tries to ensure lowest memory footprints from the SDK,\n * at the risk of documents not being cached for offline queries or for\n * direct queries to the cache.\n *\n * Use factory function {@link memoryEagerGarbageCollector()} to create an\n * instance of this collector.\n */\nexport type MemoryEagerGarbageCollector = {\n kind: 'memoryEager';\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n};\n\n/**\n * A garbage collector deletes Least-Recently-Used documents in multiple\n * batches.\n *\n * This collector is configured with a target size, and will only perform\n * collection when the cached documents exceed the target size. It avoids\n * querying backend repeated for the same query or document, at the risk\n * of having a larger memory footprint.\n *\n * Use factory function {@link memoryLruGarbageCollector()} to create a\n * instance of this collector.\n */\nexport type MemoryLruGarbageCollector = {\n kind: 'memoryLru';\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n};\n\nclass MemoryEagerGarbageCollectorImpl implements MemoryEagerGarbageCollector {\n kind: 'memoryEager' = 'memoryEager';\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n\n constructor() {\n this._offlineComponentProvider = MemoryOfflineComponentProvider.provider;\n }\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n}\n\nclass MemoryLruGarbageCollectorImpl implements MemoryLruGarbageCollector {\n kind: 'memoryLru' = 'memoryLru';\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n\n constructor(cacheSize?: number) {\n this._offlineComponentProvider = {\n build: () => new LruGcMemoryOfflineComponentProvider(cacheSize)\n };\n }\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n}\n\n/**\n * Creates an instance of `MemoryEagerGarbageCollector`. This is also the\n * default garbage collector unless it is explicitly specified otherwise.\n */\nexport function memoryEagerGarbageCollector(): MemoryEagerGarbageCollector {\n return new MemoryEagerGarbageCollectorImpl();\n}\n\n/**\n * Creates an instance of `MemoryLruGarbageCollector`.\n *\n * A target size can be specified as part of the setting parameter. The\n * collector will start deleting documents once the cache size exceeds\n * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes).\n */\nexport function memoryLruGarbageCollector(settings?: {\n cacheSizeBytes?: number;\n}): MemoryLruGarbageCollector {\n return new MemoryLruGarbageCollectorImpl(settings?.cacheSizeBytes);\n}\n\n/**\n * An settings object to configure an `MemoryLocalCache` instance.\n */\nexport type MemoryCacheSettings = {\n /**\n * The garbage collector to use, for the memory cache layer.\n * A `MemoryEagerGarbageCollector` is used when this is undefined.\n */\n garbageCollector?: MemoryGarbageCollector;\n};\n\n/**\n * Creates an instance of `MemoryLocalCache`. The instance can be set to\n * `FirestoreSettings.cache` to tell the SDK which cache layer to use.\n */\nexport function memoryLocalCache(\n settings?: MemoryCacheSettings\n): MemoryLocalCache {\n return new MemoryLocalCacheImpl(settings);\n}\n\n/**\n * An settings object to configure an `PersistentLocalCache` instance.\n *\n * Persistent cache cannot be used in a Node.js environment.\n */\nexport type PersistentCacheSettings = {\n /**\n * An approximate cache size threshold for the on-disk data. If the cache\n * grows beyond this size, Firestore will start removing data that hasn't been\n * recently used. The SDK does not guarantee that the cache will stay below\n * that size, only that if the cache exceeds the given size, cleanup will be\n * attempted.\n *\n * The default value is 40 MB. The threshold must be set to at least 1 MB, and\n * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection.\n */\n cacheSizeBytes?: number;\n\n /**\n * Specifies how multiple tabs/windows will be managed by the SDK.\n */\n tabManager?: PersistentTabManager;\n};\n\n/**\n * Creates an instance of `PersistentLocalCache`. The instance can be set to\n * `FirestoreSettings.cache` to tell the SDK which cache layer to use.\n *\n * Persistent cache cannot be used in a Node.js environment.\n */\nexport function persistentLocalCache(\n settings?: PersistentCacheSettings\n): PersistentLocalCache {\n return new PersistentLocalCacheImpl(settings);\n}\n\n/**\n * A tab manager supporting only one tab, no synchronization will be\n * performed across tabs.\n */\nexport type PersistentSingleTabManager = {\n kind: 'persistentSingleTab';\n /**\n * @internal\n */\n _initialize: (\n settings: Omit | undefined\n ) => void;\n /**\n * @internal\n */\n _onlineComponentProvider?: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider?: OfflineComponentProviderFactory;\n};\n\nclass SingleTabManagerImpl implements PersistentSingleTabManager {\n kind: 'persistentSingleTab' = 'persistentSingleTab';\n\n /**\n * @internal\n */\n _onlineComponentProvider?: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider?: OfflineComponentProviderFactory;\n\n constructor(private forceOwnership?: boolean) {}\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n\n /**\n * @internal\n */\n _initialize(\n settings: Omit | undefined\n ): void {\n this._onlineComponentProvider = OnlineComponentProvider.provider;\n this._offlineComponentProvider = {\n build: (onlineComponents: OnlineComponentProvider) =>\n new IndexedDbOfflineComponentProvider(\n onlineComponents,\n settings?.cacheSizeBytes,\n this.forceOwnership\n )\n };\n }\n}\n\n/**\n * A tab manager supporting multiple tabs. SDK will synchronize queries and\n * mutations done across all tabs using the SDK.\n */\nexport type PersistentMultipleTabManager = {\n kind: 'PersistentMultipleTab';\n /**\n * @internal\n */\n _initialize: (settings: Omit) => void;\n /**\n * @internal\n */\n _onlineComponentProvider?: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n\n _offlineComponentProvider?: OfflineComponentProviderFactory;\n};\n\nclass MultiTabManagerImpl implements PersistentMultipleTabManager {\n kind: 'PersistentMultipleTab' = 'PersistentMultipleTab';\n\n /**\n * @internal\n */\n _onlineComponentProvider?: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider?: OfflineComponentProviderFactory;\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n\n /**\n * @internal\n */\n _initialize(\n settings: Omit | undefined\n ): void {\n this._onlineComponentProvider = OnlineComponentProvider.provider;\n this._offlineComponentProvider = {\n build: (onlineComponents: OnlineComponentProvider) =>\n new MultiTabOfflineComponentProvider(\n onlineComponents,\n settings?.cacheSizeBytes\n )\n };\n }\n}\n\n/**\n * A union of all available tab managers.\n */\nexport type PersistentTabManager =\n | PersistentSingleTabManager\n | PersistentMultipleTabManager;\n\n/**\n * Type to configure an `PersistentSingleTabManager` instance.\n */\nexport type PersistentSingleTabManagerSettings = {\n /**\n * Whether to force-enable persistent (IndexedDB) cache for the client. This\n * cannot be used with multi-tab synchronization and is primarily intended for\n * use with Web Workers. Setting this to `true` will enable IndexedDB, but cause\n * other tabs using IndexedDB cache to fail.\n */\n forceOwnership?: boolean;\n};\n/**\n * Creates an instance of `PersistentSingleTabManager`.\n *\n * @param settings Configures the created tab manager.\n */\nexport function persistentSingleTabManager(\n settings: PersistentSingleTabManagerSettings | undefined\n): PersistentSingleTabManager {\n return new SingleTabManagerImpl(settings?.forceOwnership);\n}\n\n/**\n * Creates an instance of `PersistentMultipleTabManager`.\n */\nexport function persistentMultipleTabManager(): PersistentMultipleTabManager {\n return new MultiTabManagerImpl();\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\n\nexport const DEFAULT_TRANSACTION_OPTIONS: TransactionOptions = {\n maxAttempts: 5\n};\n\n/**\n * Options to customize transaction behavior.\n */\nexport declare interface TransactionOptions {\n /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */\n readonly maxAttempts: number;\n}\n\nexport function validateTransactionOptions(options: TransactionOptions): void {\n if (options.maxAttempts < 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Max attempts must be at least 1'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Compat, getModularInstance } from '@firebase/util';\n\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { invokeCommitRpc } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport { applyFirestoreDataConverter } from './reference_impl';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\n\n/**\n * A write batch, used to perform multiple writes as a single atomic unit.\n *\n * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It\n * provides methods for adding writes to the write batch. None of the writes\n * will be committed (or visible locally) until {@link WriteBatch.commit} is\n * called.\n */\nexport class WriteBatch {\n // This is the lite version of the WriteBatch API used in the legacy SDK. The\n // class is a close copy but takes different input types.\n\n private readonly _dataReader: UserDataReader;\n private _mutations = [] as Mutation[];\n private _committed = false;\n\n /** @hideconstructor */\n constructor(\n private readonly _firestore: Firestore,\n private readonly _commitHandler: (m: Mutation[]) => Promise\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): WriteBatch;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): WriteBatch;\n set(\n documentRef: DocumentReference,\n data: WithFieldValue | PartialWithFieldValue,\n options?: SetOptions\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n data,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'WriteBatch.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._mutations.push(parsed.toMutation(ref._key, Precondition.none()));\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): WriteBatch;\n /**\n * Updates fields in the document referred to by this {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be update by providing dot-separated field path strings\n * or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._mutations.push(\n parsed.toMutation(ref._key, Precondition.exists(true))\n );\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n this._mutations = this._mutations.concat(\n new DeleteMutation(ref._key, Precondition.none())\n );\n return this;\n }\n\n /**\n * Commits all of the writes in this write batch as a single atomic unit.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `Promise` resolved once all of the writes in the batch have been\n * successfully written to the backend as an atomic unit (note that it won't\n * resolve while you're offline).\n */\n commit(): Promise {\n this._verifyNotCommitted();\n this._committed = true;\n if (this._mutations.length > 0) {\n return this._commitHandler(this._mutations);\n }\n\n return Promise.resolve();\n }\n\n private _verifyNotCommitted(): void {\n if (this._committed) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A write batch can no longer be used after commit() ' +\n 'has been called.'\n );\n }\n }\n}\n\nexport function validateReference<\n AppModelType,\n DbModelType extends DocumentData\n>(\n documentRef:\n | DocumentReference\n | Compat>,\n firestore: Firestore\n): DocumentReference {\n documentRef = getModularInstance(documentRef);\n\n if (documentRef.firestore !== firestore) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Provided document reference is from a different Firestore instance.'\n );\n } else {\n return documentRef as DocumentReference;\n }\n}\n\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single WriteBatch\n * is 500.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `WriteBatch` that can be used to atomically execute multiple\n * writes.\n */\nexport function writeBatch(firestore: Firestore): WriteBatch {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n return new WriteBatch(firestore, writes =>\n invokeCommitRpc(datastore, writes)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport {\n DEFAULT_TRANSACTION_OPTIONS,\n TransactionOptions as TransactionOptionsInternal,\n validateTransactionOptions\n} from '../core/transaction_options';\nimport { TransactionRunner } from '../core/transaction_runner';\nimport { fail } from '../util/assert';\nimport { newAsyncQueue } from '../util/async_queue_impl';\nimport { cast } from '../util/input_validation';\nimport { Deferred } from '../util/promise';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n applyFirestoreDataConverter,\n LiteUserDataWriter\n} from './reference_impl';\nimport { DocumentSnapshot } from './snapshot';\nimport { TransactionOptions } from './transaction_options';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\nimport { validateReference } from './write_batch';\n\n// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the\n// legacy SDK.\n\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nexport class Transaction {\n // This is the tree-shakeable version of the Transaction class used in the\n // legacy SDK. The class is a close copy but takes different input and output\n // types. The firestore-exp SDK further extends this class to return its API\n // type.\n\n private readonly _dataReader: UserDataReader;\n\n /** @hideconstructor */\n constructor(\n protected readonly _firestore: Firestore,\n private readonly _transaction: InternalTransaction\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */\n get(\n documentRef: DocumentReference\n ): Promise> {\n const ref = validateReference(documentRef, this._firestore);\n const userDataWriter = new LiteUserDataWriter(this._firestore);\n return this._transaction.lookup([ref._key]).then(docs => {\n if (!docs || docs.length !== 1) {\n return fail(0x5de9, 'Mismatch in docs returned from document lookup.');\n }\n const doc = docs[0];\n if (doc.isFoundDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n doc.key,\n doc,\n ref.converter\n );\n } else if (doc.isNoDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n ref._key,\n null,\n ref.converter\n );\n } else {\n throw fail(\n 0x4801,\n 'BatchGetDocumentsRequest returned unexpected document',\n {\n doc\n }\n );\n }\n });\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): this;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): this;\n set(\n documentRef: DocumentReference,\n value: PartialWithFieldValue,\n options?: SetOptions\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n value,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'Transaction.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._transaction.set(ref._key, parsed);\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): this;\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key/value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._transaction.update(ref._key, parsed);\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n this._transaction.delete(ref._key);\n return this;\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */\nexport function runTransaction(\n firestore: Firestore,\n updateFunction: (transaction: Transaction) => Promise,\n options?: TransactionOptions\n): Promise {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n const optionsWithDefaults: TransactionOptionsInternal = {\n ...DEFAULT_TRANSACTION_OPTIONS,\n ...options\n };\n validateTransactionOptions(optionsWithDefaults);\n const deferred = new Deferred();\n new TransactionRunner(\n newAsyncQueue(),\n datastore,\n optionsWithDefaults,\n internalTransaction =>\n updateFunction(new Transaction(firestore, internalTransaction)),\n deferred\n ).run();\n return deferred.promise;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { firestoreClientTransaction } from '../core/firestore_client';\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport {\n TransactionOptions as TransactionOptionsInternal,\n DEFAULT_TRANSACTION_OPTIONS,\n validateTransactionOptions\n} from '../core/transaction_options';\nimport { DocumentData, DocumentReference } from '../lite-api/reference';\nimport { Transaction as LiteTransaction } from '../lite-api/transaction';\nimport { validateReference } from '../lite-api/write_batch';\nimport { cast } from '../util/input_validation';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport { ExpUserDataWriter } from './reference_impl';\nimport { DocumentSnapshot, SnapshotMetadata } from './snapshot';\nimport { TransactionOptions } from './transaction_options';\n\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nexport class Transaction extends LiteTransaction {\n // This class implements the same logic as the Transaction API in the Lite SDK\n // but is subclassed in order to return its own DocumentSnapshot types.\n\n /** @hideconstructor */\n constructor(\n protected readonly _firestore: Firestore,\n _transaction: InternalTransaction\n ) {\n super(_firestore, _transaction);\n }\n\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */\n get(\n documentRef: DocumentReference\n ): Promise> {\n const ref = validateReference(documentRef, this._firestore);\n const userDataWriter = new ExpUserDataWriter(this._firestore);\n return super\n .get(documentRef)\n .then(\n liteDocumentSnapshot =>\n new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n ref._key,\n liteDocumentSnapshot._document,\n new SnapshotMetadata(\n /* hasPendingWrites= */ false,\n /* fromCache= */ false\n ),\n ref.converter\n )\n );\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */\nexport function runTransaction(\n firestore: Firestore,\n updateFunction: (transaction: Transaction) => Promise,\n options?: TransactionOptions\n): Promise {\n firestore = cast(firestore, Firestore);\n const optionsWithDefaults: TransactionOptionsInternal = {\n ...DEFAULT_TRANSACTION_OPTIONS,\n ...options\n };\n validateTransactionOptions(optionsWithDefaults);\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientTransaction(\n client,\n internalTransaction =>\n updateFunction(new Transaction(firestore, internalTransaction)),\n optionsWithDefaults\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldValue } from './field_value';\nimport {\n ArrayRemoveFieldValueImpl,\n ArrayUnionFieldValueImpl,\n DeleteFieldValueImpl,\n NumericIncrementFieldValueImpl,\n ServerTimestampFieldValueImpl\n} from './user_data_reader';\nimport { VectorValue } from './vector_value';\n\n/**\n * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or\n * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.\n */\nexport function deleteField(): FieldValue {\n return new DeleteFieldValueImpl('deleteField');\n}\n\n/**\n * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to\n * include a server-generated timestamp in the written data.\n */\nexport function serverTimestamp(): FieldValue {\n return new ServerTimestampFieldValueImpl('serverTimestamp');\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array\n * value that already exists on the server. Each specified element that doesn't\n * already exist in the array will be added to the end. If the field being\n * modified is not already an array it will be overwritten with an array\n * containing exactly the specified elements.\n *\n * @param elements - The elements to union into the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`.\n */\nexport function arrayUnion(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayUnionFieldValueImpl('arrayUnion', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link (setDoc:1)} or {@link\n * updateDoc:1} that tells the server to remove the given elements from any\n * array value that already exists on the server. All instances of each element\n * specified will be removed from the array. If the field being modified is not\n * already an array it will be overwritten with an empty array.\n *\n * @param elements - The elements to remove from the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function arrayRemove(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayRemoveFieldValueImpl('arrayRemove', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by\n * the given value.\n *\n * If either the operand or the current field value uses floating point\n * precision, all arithmetic follows IEEE 754 semantics. If both values are\n * integers, values outside of JavaScript's safe number range\n * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to\n * precision loss. Furthermore, once processed by the Firestore backend, all\n * integer operations are capped between -2^63 and 2^63-1.\n *\n * If the current field value is not of type `number`, or if the field does not\n * yet exist, the transformation sets the field to the given value.\n *\n * @param n - The value to increment by.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function increment(n: number): FieldValue {\n return new NumericIncrementFieldValueImpl('increment', n);\n}\n\n/**\n * Creates a new `VectorValue` constructed with a copy of the given array of numbers.\n *\n * @param values - Create a `VectorValue` instance with a copy of this array of numbers.\n *\n * @returns A new `VectorValue` constructed with a copy of the given array of numbers.\n */\nexport function vector(values?: number[]): VectorValue {\n return new VectorValue(values);\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 { WriteBatch } from '../lite-api/write_batch';\nimport { cast } from '../util/input_validation';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport { executeWrite } from './reference_impl';\n\nexport { WriteBatch };\n\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch}\n * is 500.\n *\n * Unlike transactions, write batches are persisted offline and therefore are\n * preferable when you don't need to condition your writes on read data.\n *\n * @returns A {@link WriteBatch} that can be used to atomically execute multiple\n * writes.\n */\nexport function writeBatch(firestore: Firestore): WriteBatch {\n firestore = cast(firestore, Firestore);\n ensureFirestoreConfigured(firestore);\n return new WriteBatch(firestore, mutations =>\n executeWrite(firestore, mutations)\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 { firestoreClientSetIndexConfiguration } from '../core/firestore_client';\nimport { fieldPathFromDotSeparatedString } from '../lite-api/user_data_reader';\nimport {\n FieldIndex,\n IndexKind,\n IndexSegment,\n IndexState\n} from '../model/field_index';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\nimport { logWarn } from '../util/log';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\n\nexport {\n connectFirestoreEmulator,\n EmulatorMockTokenOptions\n} from '../lite-api/database';\n\n/**\n * A single field element in an index configuration.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport interface IndexField {\n /** The field path to index. */\n readonly fieldPath: string;\n /**\n * What type of array index to create. Set to `CONTAINS` for `array-contains`\n * and `array-contains-any` indexes.\n *\n * Only one of `arrayConfig` or `order` should be set;\n */\n readonly arrayConfig?: 'CONTAINS';\n /**\n * What type of array index to create. Set to `ASCENDING` or 'DESCENDING` for\n * `==`, `!=`, `<=`, `<=`, `in` and `not-in` filters.\n *\n * Only one of `arrayConfig` or `order` should be set.\n */\n readonly order?: 'ASCENDING' | 'DESCENDING';\n\n [key: string]: unknown;\n}\n\n/**\n * The SDK definition of a Firestore index.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport interface Index {\n /** The ID of the collection to index. */\n readonly collectionGroup: string;\n /** A list of fields to index. */\n readonly fields?: IndexField[];\n\n [key: string]: unknown;\n}\n\n/**\n * A list of Firestore indexes to speed up local query execution.\n *\n * See {@link https://firebase.google.com/docs/reference/firestore/indexes/#json_format | JSON Format}\n * for a description of the format of the index definition.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport interface IndexConfiguration {\n /** A list of all Firestore indexes. */\n readonly indexes?: Index[];\n\n [key: string]: unknown;\n}\n\n/**\n * Configures indexing for local query execution. Any previous index\n * configuration is overridden. The `Promise` resolves once the index\n * configuration has been persisted.\n *\n * The index entries themselves are created asynchronously. You can continue to\n * use queries that require indexing even if the indices are not yet available.\n * Query execution will automatically start using the index once the index\n * entries have been written.\n *\n * Indexes are only supported with IndexedDb persistence. If IndexedDb is not\n * enabled, any index configuration is ignored.\n *\n * @param firestore - The {@link Firestore} instance to configure indexes for.\n * @param configuration -The index definition.\n * @throws FirestoreError if the JSON format is invalid.\n * @returns A `Promise` that resolves once all indices are successfully\n * configured.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport function setIndexConfiguration(\n firestore: Firestore,\n configuration: IndexConfiguration\n): Promise;\n\n/**\n * Configures indexing for local query execution. Any previous index\n * configuration is overridden. The `Promise` resolves once the index\n * configuration has been persisted.\n *\n * The index entries themselves are created asynchronously. You can continue to\n * use queries that require indexing even if the indices are not yet available.\n * Query execution will automatically start using the index once the index\n * entries have been written.\n *\n * Indexes are only supported with IndexedDb persistence. Invoke either\n * `enableIndexedDbPersistence()` or `enableMultiTabIndexedDbPersistence()`\n * before setting an index configuration. If IndexedDb is not enabled, any\n * index configuration is ignored.\n *\n * The method accepts the JSON format exported by the Firebase CLI (`firebase\n * firestore:indexes`). If the JSON format is invalid, this method throws an\n * error.\n *\n * @param firestore - The {@link Firestore} instance to configure indexes for.\n * @param json -The JSON format exported by the Firebase CLI.\n * @throws FirestoreError if the JSON format is invalid.\n * @returns A `Promise` that resolves once all indices are successfully\n * configured.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport function setIndexConfiguration(\n firestore: Firestore,\n json: string\n): Promise;\n\nexport function setIndexConfiguration(\n firestore: Firestore,\n jsonOrConfiguration: string | IndexConfiguration\n): Promise {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n if (\n !client._uninitializedComponentsProvider ||\n client._uninitializedComponentsProvider._offline.kind === 'memory'\n ) {\n // PORTING NOTE: We don't return an error if the user has not enabled\n // persistence since `enableIndexeddbPersistence()` can fail on the Web.\n logWarn('Cannot enable indexes when persistence is disabled');\n return Promise.resolve();\n }\n const parsedIndexes = parseIndexes(jsonOrConfiguration);\n return firestoreClientSetIndexConfiguration(client, parsedIndexes);\n}\n\nexport function parseIndexes(\n jsonOrConfiguration: string | IndexConfiguration\n): FieldIndex[] {\n const indexConfiguration =\n typeof jsonOrConfiguration === 'string'\n ? (tryParseJson(jsonOrConfiguration) as IndexConfiguration)\n : jsonOrConfiguration;\n const parsedIndexes: FieldIndex[] = [];\n\n if (Array.isArray(indexConfiguration.indexes)) {\n for (const index of indexConfiguration.indexes) {\n const collectionGroup = tryGetString(index, 'collectionGroup');\n\n const segments: IndexSegment[] = [];\n if (Array.isArray(index.fields)) {\n for (const field of index.fields) {\n const fieldPathString = tryGetString(field, 'fieldPath');\n const fieldPath = fieldPathFromDotSeparatedString(\n 'setIndexConfiguration',\n fieldPathString\n );\n\n if (field.arrayConfig === 'CONTAINS') {\n segments.push(new IndexSegment(fieldPath, IndexKind.CONTAINS));\n } else if (field.order === 'ASCENDING') {\n segments.push(new IndexSegment(fieldPath, IndexKind.ASCENDING));\n } else if (field.order === 'DESCENDING') {\n segments.push(new IndexSegment(fieldPath, IndexKind.DESCENDING));\n }\n }\n }\n\n parsedIndexes.push(\n new FieldIndex(\n FieldIndex.UNKNOWN_ID,\n collectionGroup,\n segments,\n IndexState.empty()\n )\n );\n }\n }\n return parsedIndexes;\n}\n\nfunction tryParseJson(json: string): Record {\n try {\n return JSON.parse(json);\n } catch (e) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Failed to parse JSON: ' + (e as Error)?.message\n );\n }\n}\n\nfunction tryGetString(data: Record, property: string): string {\n if (typeof data[property] !== 'string') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Missing string value for: ' + property\n );\n }\n return data[property] as string;\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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ensureFirestoreConfigured, Firestore } from '../api/database';\nimport { AggregateImpl } from '../core/aggregate';\nimport { queryToAggregateTarget, queryToTarget } from '../core/query';\nimport { AggregateSpec } from '../lite-api/aggregate_types';\nimport { Query } from '../lite-api/reference';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport { toQueryTarget, toRunAggregationQueryRequest } from './serializer';\n\n/**\n * @internal\n * @private\n *\n * This function is for internal use only.\n *\n * Returns the `QueryTarget` representation of the given query. Returns `null`\n * if the Firestore client associated with the given query has not been\n * initialized or has been terminated.\n *\n * @param query - The Query to convert to proto representation.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function _internalQueryToProtoQueryTarget(query: Query): any {\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const serializer = client._onlineComponents?.datastore.serializer;\n if (serializer === undefined) {\n return null;\n }\n return toQueryTarget(serializer!, queryToTarget(query._query)).queryTarget;\n}\n\n/**\n * @internal\n * @private\n *\n * This function is for internal use only.\n *\n * Returns `RunAggregationQueryRequest` which contains the proto representation\n * of the given aggregation query request. Returns null if the Firestore client\n * associated with the given query has not been initialized or has been\n * terminated.\n *\n * @param query - The Query to convert to proto representation.\n * @param aggregateSpec - The set of aggregations and their aliases.\n */\nexport function _internalAggregationQueryToProtoRunAggregationQueryRequest<\n AggregateSpecType extends AggregateSpec\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n>(query: Query, aggregateSpec: AggregateSpecType): any {\n const aggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const serializer = client._onlineComponents?.datastore.serializer;\n if (serializer === undefined) {\n return null;\n }\n\n return toRunAggregationQueryRequest(\n serializer!,\n queryToAggregateTarget(query._query),\n aggregates,\n /* skipAliasing= */ true\n ).request;\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 { Unsubscribe } from '../api/reference_impl';\n\nimport {\n setTestingHooksSpi,\n ExistenceFilterMismatchInfo,\n TestingHooksSpi\n} from './testing_hooks_spi';\n\n/**\n * Testing hooks for use by Firestore's integration test suite to reach into the\n * SDK internals to validate logic and behavior that is not visible from the\n * public API surface.\n *\n * @internal\n */\nexport class TestingHooks {\n private constructor() {\n throw new Error('instances of this class should not be created');\n }\n\n /**\n * Registers a callback to be notified when an existence filter mismatch\n * occurs in the Watch listen stream.\n *\n * The relative order in which callbacks are notified is unspecified; do not\n * rely on any particular ordering. If a given callback is registered multiple\n * times then it will be notified multiple times, once per registration.\n *\n * @param callback the callback to invoke upon existence filter mismatch.\n *\n * @return a function that, when called, unregisters the given callback; only\n * the first invocation of the returned function does anything; all subsequent\n * invocations do nothing.\n */\n static onExistenceFilterMismatch(\n callback: ExistenceFilterMismatchCallback\n ): Unsubscribe {\n return TestingHooksSpiImpl.instance.onExistenceFilterMismatch(callback);\n }\n}\n\n/**\n * The signature of callbacks registered with\n * `TestingUtils.onExistenceFilterMismatch()`.\n *\n * The return value, if any, is ignored.\n *\n * @internal\n */\nexport type ExistenceFilterMismatchCallback = (\n info: ExistenceFilterMismatchInfo\n) => unknown;\n\n/**\n * The implementation of `TestingHooksSpi`.\n */\nclass TestingHooksSpiImpl implements TestingHooksSpi {\n private readonly existenceFilterMismatchCallbacksById = new Map<\n Symbol,\n ExistenceFilterMismatchCallback\n >();\n\n private constructor() {}\n\n static get instance(): TestingHooksSpiImpl {\n if (!testingHooksSpiImplInstance) {\n testingHooksSpiImplInstance = new TestingHooksSpiImpl();\n setTestingHooksSpi(testingHooksSpiImplInstance);\n }\n return testingHooksSpiImplInstance;\n }\n\n notifyOnExistenceFilterMismatch(info: ExistenceFilterMismatchInfo): void {\n this.existenceFilterMismatchCallbacksById.forEach(callback =>\n callback(info)\n );\n }\n\n onExistenceFilterMismatch(\n callback: ExistenceFilterMismatchCallback\n ): Unsubscribe {\n const id = Symbol();\n const callbacks = this.existenceFilterMismatchCallbacksById;\n callbacks.set(id, callback);\n return () => callbacks.delete(id);\n }\n}\n\nlet testingHooksSpiImplInstance: TestingHooksSpiImpl | null = null;\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 { registerFirestore } from './register';\n\nregisterFirestore('node');\n\nexport * from './api';\n"],"names":["inspect","Logger","LogLevel","FirebaseError","app","_isFirebaseServerApp","generateRandomBytes","MIN_SURROGATE","MAX_SURROGATE","Integer","FieldPath","LOG_TAG","getGlobal","isIndexedDBAvailable","getUA","DbRemoteDocumentStore","DbRemoteDocumentStoreLegacy","TYPE_KEY","serverTimestamp","isDocumentQuery","TextEncoder","TextDecoder","Md5","isSafariOrWebkit","sentinelKey","isSafari","grpc","protoLoader","protos","Transaction","Firestore","isCloudWorkstation","pingServer","updateEmulatorBanner","deepEqual","createMockUserToken","getModularInstance","LiteFirestore","_getProvider","getApp","getDefaultEmulatorHostnameAndPort","_removeServiceInstance","SDK_VERSION","_registerComponent","Component","registerVersion","name","version","InternalFieldPath","fieldPathFromArgument","DocumentSnapshot","QueryDocumentSnapshot","LiteDocumentSnapshot","LiteTransaction"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;;;;;;;;;;;AAeG;AAEH;;;AAGG;AACU,MAAA,IAAI,CAAA;AAUf,IAAA,WAAA,CAAqB,GAAkB,EAAA;AAAlB,QAAA,IAAG,CAAA,GAAA,GAAH,GAAG,CAAe;AAAI,KAAA;AAE3C,IAAA,eAAe,GAAA;AACb,QAAA,OAAO,IAAI,CAAC,GAAG,IAAI,IAAI,CAAC;AACzB,KAAA;AAED;;;AAGG;AACH,IAAA,KAAK,GAAA;AACH,QAAA,IAAI,IAAI,CAAC,eAAe,EAAE,EAAE;AAC1B,YAAA,OAAO,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC;AAC1B,SAAA;AAAM,aAAA;AACL,YAAA,OAAO,gBAAgB,CAAC;AACzB,SAAA;AACF,KAAA;AAED,IAAA,OAAO,CAAC,SAAe,EAAA;AACrB,QAAA,OAAO,SAAS,CAAC,GAAG,KAAK,IAAI,CAAC,GAAG,CAAC;AACnC,KAAA;;AA7BD;AACgB,IAAA,CAAA,eAAe,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,CAAC;AAEjD;AACA;AACgB,IAAA,CAAA,kBAAkB,GAAG,IAAI,IAAI,CAAC,wBAAwB,CAAC,CAAC;AACxD,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,CAAC;AACzE,KAAA;AACF,CAAA;AAcD;;AAEG;AACH,MAAM,mBAAmB,CAAA;AAMvB,IAAA,WAAA,GAAA;AALiB,QAAA,IAAA,CAAA,oCAAoC,GAAG,IAAI,GAAG,EAG5D,CAAC;AAEoB,KAAA;AAExB,IAAA,WAAW,QAAQ,GAAA;QACjB,IAAI,CAAC,2BAA2B,EAAE;AAChC,YAAA,2BAA2B,GAAG,IAAI,mBAAmB,EAAE,CAAC;YACxD,kBAAkB,CAAC,2BAA2B,CAAC,CAAC;AACjD,SAAA;AACD,QAAA,OAAO,2BAA2B,CAAC;AACpC,KAAA;AAED,IAAA,+BAA+B,CAAC,IAAiC,EAAA;AAC/D,QAAA,IAAI,CAAC,oCAAoC,CAAC,OAAO,CAAC,QAAQ,IACxD,QAAQ,CAAC,IAAI,CAAC,CACf,CAAC;AACH,KAAA;AAED,IAAA,yBAAyB,CACvB,QAAyC,EAAA;AAEzC,QAAA,MAAM,EAAE,GAAG,MAAM,EAAE,CAAC;AACpB,QAAA,MAAM,SAAS,GAAG,IAAI,CAAC,oCAAoC,CAAC;AAC5D,QAAA,SAAS,CAAC,GAAG,CAAC,EAAE,EAAE,QAAQ,CAAC,CAAC;AAC5B,QAAA,OAAO,MAAM,SAAS,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;AACnC,KAAA;AACF,CAAA;AAED,IAAI,2BAA2B,GAA+B,IAAI,CAAA;;ACzGlE;;;;;;;;;;;;;;;AAeG;AAIH,iBAAiB,CAAC,MAAM,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/frontend-old/node_modules/@firebase/firestore/dist/index.node.mjs b/frontend-old/node_modules/@firebase/firestore/dist/index.node.mjs new file mode 100644 index 0000000..2a0dd7b --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/index.node.mjs @@ -0,0 +1,33795 @@ +import { _getProvider, getApp, _removeServiceInstance, _registerComponent, registerVersion, _isFirebaseServerApp, SDK_VERSION as SDK_VERSION$1 } from '@firebase/app'; +import { Component } from '@firebase/component'; +import { Logger, LogLevel } from '@firebase/logger'; +import { TextEncoder, inspect, TextDecoder } from 'util'; +import { FirebaseError, isCloudWorkstation, pingServer, updateEmulatorBanner, deepEqual, createMockUserToken, getModularInstance, getDefaultEmulatorHostnameAndPort, getGlobal, isIndexedDBAvailable, getUA, isSafari, isSafariOrWebkit } from '@firebase/util'; +import { Integer, Md5 } from '@firebase/webchannel-wrapper/bloom-blob'; +import { randomBytes as randomBytes$1 } from 'crypto'; +import * as grpc from '@grpc/grpc-js'; +import * as protoLoader from '@grpc/proto-loader'; + +const name$1 = "@firebase/firestore"; +const version$1 = "4.9.2"; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Simple wrapper around a nullable UID. Mostly exists to make code more + * readable. + */ +class User { + constructor(uid) { + this.uid = uid; + } + isAuthenticated() { + return this.uid != null; + } + /** + * Returns a key representing this user, suitable for inclusion in a + * dictionary. + */ + toKey() { + if (this.isAuthenticated()) { + return 'uid:' + this.uid; + } + else { + return 'anonymous-user'; + } + } + isEqual(otherUser) { + return otherUser.uid === this.uid; + } +} +/** A user with a null UID. */ +User.UNAUTHENTICATED = new User(null); +// TODO(mikelehen): Look into getting a proper uid-equivalent for +// non-FirebaseAuth providers. +User.GOOGLE_CREDENTIALS = new User('google-credentials-uid'); +User.FIRST_PARTY = new User('first-party-uid'); +User.MOCK_USER = new User('mock-user'); + +const version = "12.3.0"; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let SDK_VERSION = version; +function setSDKVersion(version) { + SDK_VERSION = version; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Formats an object as a JSON string, suitable for logging. */ +function formatJSON(value) { + // util.inspect() results in much more readable output than JSON.stringify() + return inspect(value, { depth: 100 }); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const logClient = new Logger('@firebase/firestore'); +// Helper methods are needed because variables can't be exported as read/write +function getLogLevel() { + return logClient.logLevel; +} +/** + * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). + * + * @param logLevel - The verbosity you set for activity and error logging. Can + * be any of the following values: + * + *

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 0xd6db,\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\n/**\n * The smallest value representable by a 64-bit signed integer (long).\n */\nconst MIN_LONG_VALUE = '-9223372036854775808';\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 // Document keys are ordered first by numeric value (\"__id__\"),\n // then lexicographically by string value. Start the iterator at the minimum\n // possible Document key value.\n const prefix = new DocumentKey(\n collectionPath.child('__id' + MIN_LONG_VALUE + '__')\n );\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(0x251c, '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(\n 0xee44,\n 'orphanedDocuments is only valid during a transaction.'\n );\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isSafariOrWebkit } from '@firebase/util';\n\nimport { User } from '../auth/user';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { DocumentKeySet, documentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport {\n decodeResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { IndexedDbDocumentOverlayCache } from './indexeddb_document_overlay_cache';\nimport {\n dbDocumentSize,\n removeMutationBatch\n} from './indexeddb_mutation_batch_impl';\nimport { IndexedDbMutationQueue } from './indexeddb_mutation_queue';\nimport { newIndexedDbRemoteDocumentCache } from './indexeddb_remote_document_cache';\nimport {\n DbCollectionParent,\n DbDocumentMutation,\n DbMutationBatch,\n DbMutationQueue,\n DbRemoteDocument,\n DbRemoteDocumentGlobal,\n DbTarget,\n DbTargetDocument,\n DbTargetGlobal,\n SCHEMA_VERSION\n} from './indexeddb_schema';\nimport {\n DbRemoteDocument as DbRemoteDocumentLegacy,\n DbRemoteDocumentStore as DbRemoteDocumentStoreLegacy,\n DbRemoteDocumentKey as DbRemoteDocumentKeyLegacy\n} from './indexeddb_schema_legacy';\nimport {\n DbBundleKeyPath,\n DbBundleStore,\n DbClientMetadataKeyPath,\n DbClientMetadataStore,\n DbCollectionParentKey,\n DbCollectionParentKeyPath,\n DbCollectionParentStore,\n DbDocumentMutationKey,\n DbDocumentMutationStore,\n DbDocumentOverlayCollectionGroupOverlayIndex,\n DbDocumentOverlayCollectionGroupOverlayIndexPath,\n DbDocumentOverlayCollectionPathOverlayIndex,\n DbDocumentOverlayCollectionPathOverlayIndexPath,\n DbDocumentOverlayKeyPath,\n DbDocumentOverlayStore,\n DbGlobalsKeyPath,\n DbGlobalsStore,\n DbIndexConfigurationCollectionGroupIndex,\n DbIndexConfigurationCollectionGroupIndexPath,\n DbIndexConfigurationKeyPath,\n DbIndexConfigurationStore,\n DbIndexEntryDocumentKeyIndex,\n DbIndexEntryDocumentKeyIndexPath,\n DbIndexEntryKeyPath,\n DbIndexEntryStore,\n DbIndexStateKeyPath,\n DbIndexStateSequenceNumberIndex,\n DbIndexStateSequenceNumberIndexPath,\n DbIndexStateStore,\n DbMutationBatchKey,\n DbMutationBatchKeyPath,\n DbMutationBatchStore,\n DbMutationBatchUserMutationsIndex,\n DbMutationBatchUserMutationsKeyPath,\n DbMutationQueueKey,\n DbMutationQueueKeyPath,\n DbMutationQueueStore,\n DbNamedQueryKeyPath,\n DbNamedQueryStore,\n DbPrimaryClientStore,\n DbRemoteDocumentCollectionGroupIndex,\n DbRemoteDocumentCollectionGroupIndexPath,\n DbRemoteDocumentDocumentKeyIndex,\n DbRemoteDocumentDocumentKeyIndexPath,\n DbRemoteDocumentGlobalKey,\n DbRemoteDocumentGlobalStore,\n DbRemoteDocumentKey,\n DbRemoteDocumentKeyPath,\n DbRemoteDocumentStore,\n DbTargetDocumentDocumentTargetsIndex,\n DbTargetDocumentDocumentTargetsKeyPath,\n DbTargetDocumentKey,\n DbTargetDocumentKeyPath,\n DbTargetDocumentStore,\n DbTargetGlobalKey,\n DbTargetGlobalStore,\n DbTargetKey,\n DbTargetKeyPath,\n DbTargetQueryTargetsIndexName,\n DbTargetQueryTargetsKeyPath,\n DbTargetStore\n} from './indexeddb_sentinels';\nimport { IndexedDbTransaction } from './indexeddb_transaction';\nimport { LocalDocumentsView } from './local_documents_view';\nimport {\n fromDbMutationBatch,\n fromDbTarget,\n LocalSerializer,\n toDbTarget\n} from './local_serializer';\nimport { MemoryCollectionParentIndex } from './memory_index_manager';\nimport { MemoryEagerDelegate, MemoryPersistence } from './memory_persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { SimpleDbSchemaConverter, SimpleDbTransaction } from './simple_db';\n\n/** Performs database creation and schema upgrades. */\nexport class SchemaConverter implements SimpleDbSchemaConverter {\n constructor(private readonly serializer: LocalSerializer) {}\n\n /**\n * Performs database creation and schema upgrades.\n *\n * Note that in production, this method is only ever used to upgrade the schema\n * to SCHEMA_VERSION. Different values of toVersion are only used for testing\n * and local feature development.\n */\n createOrUpgrade(\n db: IDBDatabase,\n txn: IDBTransaction,\n fromVersion: number,\n toVersion: number\n ): PersistencePromise {\n debugAssert(\n fromVersion < toVersion &&\n fromVersion >= 0 &&\n toVersion <= SCHEMA_VERSION,\n `Unexpected schema upgrade from v${fromVersion} to v${toVersion}.`\n );\n\n const simpleDbTransaction = new SimpleDbTransaction('createOrUpgrade', txn);\n\n if (fromVersion < 1 && toVersion >= 1) {\n createPrimaryClientStore(db);\n createMutationQueue(db);\n createQueryCache(db);\n createLegacyRemoteDocumentCache(db);\n }\n\n // Migration 2 to populate the targetGlobal object no longer needed since\n // migration 3 unconditionally clears it.\n\n let p = PersistencePromise.resolve();\n if (fromVersion < 3 && toVersion >= 3) {\n // Brand new clients don't need to drop and recreate--only clients that\n // potentially have corrupt data.\n if (fromVersion !== 0) {\n dropQueryCache(db);\n createQueryCache(db);\n }\n p = p.next(() => writeEmptyTargetGlobalEntry(simpleDbTransaction));\n }\n\n if (fromVersion < 4 && toVersion >= 4) {\n if (fromVersion !== 0) {\n // Schema version 3 uses auto-generated keys to generate globally unique\n // mutation batch IDs (this was previously ensured internally by the\n // client). To migrate to the new schema, we have to read all mutations\n // and write them back out. We preserve the existing batch IDs to guarantee\n // consistency with other object stores. Any further mutation batch IDs will\n // be auto-generated.\n p = p.next(() =>\n upgradeMutationBatchSchemaAndMigrateData(db, simpleDbTransaction)\n );\n }\n\n p = p.next(() => {\n createClientMetadataStore(db);\n });\n }\n\n if (fromVersion < 5 && toVersion >= 5) {\n p = p.next(() => this.removeAcknowledgedMutations(simpleDbTransaction));\n }\n\n if (fromVersion < 6 && toVersion >= 6) {\n p = p.next(() => {\n createDocumentGlobalStore(db);\n return this.addDocumentGlobal(simpleDbTransaction);\n });\n }\n\n if (fromVersion < 7 && toVersion >= 7) {\n p = p.next(() => this.ensureSequenceNumbers(simpleDbTransaction));\n }\n\n if (fromVersion < 8 && toVersion >= 8) {\n p = p.next(() =>\n this.createCollectionParentIndex(db, simpleDbTransaction)\n );\n }\n\n if (fromVersion < 9 && toVersion >= 9) {\n p = p.next(() => {\n // Multi-Tab used to manage its own changelog, but this has been moved\n // to the DbRemoteDocument object store itself. Since the previous change\n // log only contained transient data, we can drop its object store.\n dropRemoteDocumentChangesStore(db);\n\n // Note: Schema version 9 used to create a read time index for the\n // RemoteDocumentCache. This is now done with schema version 13.\n });\n }\n\n if (fromVersion < 10 && toVersion >= 10) {\n p = p.next(() => this.rewriteCanonicalIds(simpleDbTransaction));\n }\n\n if (fromVersion < 11 && toVersion >= 11) {\n p = p.next(() => {\n createBundlesStore(db);\n createNamedQueriesStore(db);\n });\n }\n\n if (fromVersion < 12 && toVersion >= 12) {\n p = p.next(() => {\n createDocumentOverlayStore(db);\n });\n }\n\n if (fromVersion < 13 && toVersion >= 13) {\n p = p\n .next(() => createRemoteDocumentCache(db))\n .next(() => this.rewriteRemoteDocumentCache(db, simpleDbTransaction))\n .next(() => db.deleteObjectStore(DbRemoteDocumentStoreLegacy));\n }\n\n if (fromVersion < 14 && toVersion >= 14) {\n p = p.next(() => this.runOverlayMigration(db, simpleDbTransaction));\n }\n\n if (fromVersion < 15 && toVersion >= 15) {\n p = p.next(() => createFieldIndex(db));\n }\n\n if (fromVersion < 16 && toVersion >= 16) {\n // Clear the object stores to remove possibly corrupted index entries\n p = p\n .next(() => {\n const indexStateStore = txn.objectStore(DbIndexStateStore);\n indexStateStore.clear();\n })\n .next(() => {\n const indexEntryStore = txn.objectStore(DbIndexEntryStore);\n indexEntryStore.clear();\n });\n }\n\n if (fromVersion < 17 && toVersion >= 17) {\n p = p.next(() => {\n createGlobalsStore(db);\n });\n }\n\n if (fromVersion < 18 && toVersion >= 18) {\n // Clear the IndexEntryStores on WebKit and Safari to remove possibly\n // corrupted index entries\n if (isSafariOrWebkit()) {\n p = p\n .next(() => {\n const indexStateStore = txn.objectStore(DbIndexStateStore);\n indexStateStore.clear();\n })\n .next(() => {\n const indexEntryStore = txn.objectStore(DbIndexEntryStore);\n indexEntryStore.clear();\n });\n }\n }\n\n return p;\n }\n\n private addDocumentGlobal(\n txn: SimpleDbTransaction\n ): PersistencePromise {\n let byteSize = 0;\n return txn\n .store(\n DbRemoteDocumentStoreLegacy\n )\n .iterate((_, doc) => {\n byteSize += dbDocumentSize(doc);\n })\n .next(() => {\n const metadata: DbRemoteDocumentGlobal = { byteSize };\n return txn\n .store(\n DbRemoteDocumentGlobalStore\n )\n .put(DbRemoteDocumentGlobalKey, metadata);\n });\n }\n\n private removeAcknowledgedMutations(\n txn: SimpleDbTransaction\n ): PersistencePromise {\n const queuesStore = txn.store(\n DbMutationQueueStore\n );\n const mutationsStore = txn.store(\n DbMutationBatchStore\n );\n\n return queuesStore.loadAll().next(queues => {\n return PersistencePromise.forEach(queues, (queue: DbMutationQueue) => {\n const range = IDBKeyRange.bound(\n [queue.userId, BATCHID_UNKNOWN],\n [queue.userId, queue.lastAcknowledgedBatchId]\n );\n\n return mutationsStore\n .loadAll(DbMutationBatchUserMutationsIndex, range)\n .next(dbBatches => {\n return PersistencePromise.forEach(\n dbBatches,\n (dbBatch: DbMutationBatch) => {\n hardAssert(\n dbBatch.userId === queue.userId,\n 0x48da,\n `Cannot process batch from unexpected user`,\n { batchId: dbBatch.batchId }\n );\n const batch = fromDbMutationBatch(this.serializer, dbBatch);\n\n return removeMutationBatch(txn, queue.userId, batch).next(\n () => {}\n );\n }\n );\n });\n });\n });\n }\n\n /**\n * Ensures that every document in the remote document cache has a corresponding sentinel row\n * with a sequence number. Missing rows are given the most recently used sequence number.\n */\n private ensureSequenceNumbers(\n txn: SimpleDbTransaction\n ): PersistencePromise {\n const documentTargetStore = txn.store<\n DbTargetDocumentKey,\n DbTargetDocument\n >(DbTargetDocumentStore);\n const documentsStore = txn.store<\n DbRemoteDocumentKeyLegacy,\n DbRemoteDocumentKeyLegacy\n >(DbRemoteDocumentStoreLegacy);\n const globalTargetStore = txn.store(\n DbTargetGlobalStore\n );\n\n return globalTargetStore.get(DbTargetGlobalKey).next(metadata => {\n debugAssert(\n !!metadata,\n 'Metadata should have been written during the version 3 migration'\n );\n const writeSentinelKey = (\n path: ResourcePath\n ): PersistencePromise => {\n return documentTargetStore.put({\n targetId: 0,\n path: encodeResourcePath(path),\n sequenceNumber: metadata!.highestListenSequenceNumber!\n });\n };\n\n const promises: Array> = [];\n return documentsStore\n .iterate((key, doc) => {\n const path = new ResourcePath(key);\n const docSentinelKey = sentinelKey(path);\n promises.push(\n documentTargetStore.get(docSentinelKey).next(maybeSentinel => {\n if (!maybeSentinel) {\n return writeSentinelKey(path);\n } else {\n return PersistencePromise.resolve();\n }\n })\n );\n })\n .next(() => PersistencePromise.waitFor(promises));\n });\n }\n\n private createCollectionParentIndex(\n db: IDBDatabase,\n txn: SimpleDbTransaction\n ): PersistencePromise {\n // Create the index.\n db.createObjectStore(DbCollectionParentStore, {\n keyPath: DbCollectionParentKeyPath\n });\n\n const collectionParentsStore = txn.store<\n DbCollectionParentKey,\n DbCollectionParent\n >(DbCollectionParentStore);\n\n // Helper to add an index entry iff we haven't already written it.\n const cache = new MemoryCollectionParentIndex();\n const addEntry = (\n collectionPath: ResourcePath\n ): PersistencePromise | undefined => {\n if (cache.add(collectionPath)) {\n const collectionId = collectionPath.lastSegment();\n const parentPath = collectionPath.popLast();\n return collectionParentsStore.put({\n collectionId,\n parent: encodeResourcePath(parentPath)\n });\n }\n };\n\n // Index existing remote documents.\n return txn\n .store(\n DbRemoteDocumentStoreLegacy\n )\n .iterate({ keysOnly: true }, (pathSegments, _) => {\n const path = new ResourcePath(pathSegments);\n return addEntry(path.popLast());\n })\n .next(() => {\n // Index existing mutations.\n return txn\n .store(\n DbDocumentMutationStore\n )\n .iterate({ keysOnly: true }, ([userID, encodedPath, batchId], _) => {\n const path = decodeResourcePath(encodedPath);\n return addEntry(path.popLast());\n });\n });\n }\n\n private rewriteCanonicalIds(\n txn: SimpleDbTransaction\n ): PersistencePromise {\n const targetStore = txn.store(DbTargetStore);\n return targetStore.iterate((key, originalDbTarget) => {\n const originalTargetData = fromDbTarget(originalDbTarget);\n const updatedDbTarget = toDbTarget(this.serializer, originalTargetData);\n return targetStore.put(updatedDbTarget);\n });\n }\n\n private rewriteRemoteDocumentCache(\n db: IDBDatabase,\n transaction: SimpleDbTransaction\n ): PersistencePromise {\n const legacyRemoteDocumentStore = transaction.store<\n DbRemoteDocumentKeyLegacy,\n DbRemoteDocumentLegacy\n >(DbRemoteDocumentStoreLegacy);\n\n const writes: Array> = [];\n return legacyRemoteDocumentStore\n .iterate((_, legacyDocument) => {\n const remoteDocumentStore = transaction.store<\n DbRemoteDocumentKey,\n DbRemoteDocument\n >(DbRemoteDocumentStore);\n\n const path = extractKey(legacyDocument).path.toArray();\n const dbRemoteDocument = {\n prefixPath: path.slice(0, path.length - 2),\n collectionGroup: path[path.length - 2],\n documentId: path[path.length - 1],\n readTime: legacyDocument.readTime || [0, 0],\n unknownDocument: legacyDocument.unknownDocument,\n noDocument: legacyDocument.noDocument,\n document: legacyDocument.document,\n hasCommittedMutations: !!legacyDocument.hasCommittedMutations\n };\n writes.push(remoteDocumentStore.put(dbRemoteDocument));\n })\n .next(() => PersistencePromise.waitFor(writes));\n }\n\n private runOverlayMigration(\n db: IDBDatabase,\n transaction: SimpleDbTransaction\n ): PersistencePromise {\n const mutationsStore = transaction.store<\n DbMutationBatchKey,\n DbMutationBatch\n >(DbMutationBatchStore);\n\n const remoteDocumentCache = newIndexedDbRemoteDocumentCache(\n this.serializer\n );\n const memoryPersistence = new MemoryPersistence(\n MemoryEagerDelegate.factory,\n this.serializer.remoteSerializer\n );\n\n return mutationsStore.loadAll().next(dbBatches => {\n const userToDocumentSet = new Map();\n dbBatches.forEach(dbBatch => {\n let documentSet =\n userToDocumentSet.get(dbBatch.userId) ?? documentKeySet();\n const batch = fromDbMutationBatch(this.serializer, dbBatch);\n batch.keys().forEach(key => (documentSet = documentSet.add(key)));\n userToDocumentSet.set(dbBatch.userId, documentSet);\n });\n return PersistencePromise.forEach(\n userToDocumentSet,\n (allDocumentKeysForUser, userId) => {\n const user = new User(userId);\n const documentOverlayCache = IndexedDbDocumentOverlayCache.forUser(\n this.serializer,\n user\n );\n // NOTE: The index manager and the reference delegate are\n // irrelevant for the purpose of recalculating and saving\n // overlays. We can therefore simply use the memory\n // implementation.\n const indexManager = memoryPersistence.getIndexManager(user);\n const mutationQueue = IndexedDbMutationQueue.forUser(\n user,\n this.serializer,\n indexManager,\n memoryPersistence.referenceDelegate\n );\n const localDocumentsView = new LocalDocumentsView(\n remoteDocumentCache,\n mutationQueue,\n documentOverlayCache,\n indexManager\n );\n return localDocumentsView\n .recalculateAndSaveOverlaysForDocumentKeys(\n new IndexedDbTransaction(transaction, ListenSequence.INVALID),\n allDocumentKeysForUser\n )\n .next();\n }\n );\n });\n }\n}\n\nfunction sentinelKey(path: ResourcePath): DbTargetDocumentKey {\n return [0, encodeResourcePath(path)];\n}\n\nfunction createPrimaryClientStore(db: IDBDatabase): void {\n db.createObjectStore(DbPrimaryClientStore);\n}\n\nfunction createMutationQueue(db: IDBDatabase): void {\n db.createObjectStore(DbMutationQueueStore, {\n keyPath: DbMutationQueueKeyPath\n });\n\n const mutationBatchesStore = db.createObjectStore(DbMutationBatchStore, {\n keyPath: DbMutationBatchKeyPath,\n autoIncrement: true\n });\n mutationBatchesStore.createIndex(\n DbMutationBatchUserMutationsIndex,\n DbMutationBatchUserMutationsKeyPath,\n { unique: true }\n );\n\n db.createObjectStore(DbDocumentMutationStore);\n}\n\n/**\n * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads\n * and rewrites all data.\n */\nfunction upgradeMutationBatchSchemaAndMigrateData(\n db: IDBDatabase,\n txn: SimpleDbTransaction\n): PersistencePromise {\n const v1MutationsStore = txn.store<[string, number], DbMutationBatch>(\n DbMutationBatchStore\n );\n return v1MutationsStore.loadAll().next(existingMutations => {\n db.deleteObjectStore(DbMutationBatchStore);\n\n const mutationsStore = db.createObjectStore(DbMutationBatchStore, {\n keyPath: DbMutationBatchKeyPath,\n autoIncrement: true\n });\n mutationsStore.createIndex(\n DbMutationBatchUserMutationsIndex,\n DbMutationBatchUserMutationsKeyPath,\n { unique: true }\n );\n\n const v3MutationsStore = txn.store(\n DbMutationBatchStore\n );\n const writeAll = existingMutations.map(mutation =>\n v3MutationsStore.put(mutation)\n );\n\n return PersistencePromise.waitFor(writeAll);\n });\n}\n\nfunction createLegacyRemoteDocumentCache(db: IDBDatabase): void {\n db.createObjectStore(DbRemoteDocumentStoreLegacy);\n}\n\nfunction createRemoteDocumentCache(db: IDBDatabase): void {\n const remoteDocumentStore = db.createObjectStore(DbRemoteDocumentStore, {\n keyPath: DbRemoteDocumentKeyPath\n });\n remoteDocumentStore.createIndex(\n DbRemoteDocumentDocumentKeyIndex,\n DbRemoteDocumentDocumentKeyIndexPath\n );\n remoteDocumentStore.createIndex(\n DbRemoteDocumentCollectionGroupIndex,\n DbRemoteDocumentCollectionGroupIndexPath\n );\n}\n\nfunction createDocumentGlobalStore(db: IDBDatabase): void {\n db.createObjectStore(DbRemoteDocumentGlobalStore);\n}\n\nfunction createQueryCache(db: IDBDatabase): void {\n const targetDocumentsStore = db.createObjectStore(DbTargetDocumentStore, {\n keyPath: DbTargetDocumentKeyPath\n });\n targetDocumentsStore.createIndex(\n DbTargetDocumentDocumentTargetsIndex,\n DbTargetDocumentDocumentTargetsKeyPath,\n { unique: true }\n );\n\n const targetStore = db.createObjectStore(DbTargetStore, {\n keyPath: DbTargetKeyPath\n });\n\n // NOTE: This is unique only because the TargetId is the suffix.\n targetStore.createIndex(\n DbTargetQueryTargetsIndexName,\n DbTargetQueryTargetsKeyPath,\n { unique: true }\n );\n db.createObjectStore(DbTargetGlobalStore);\n}\n\nfunction dropQueryCache(db: IDBDatabase): void {\n db.deleteObjectStore(DbTargetDocumentStore);\n db.deleteObjectStore(DbTargetStore);\n db.deleteObjectStore(DbTargetGlobalStore);\n}\n\nfunction dropRemoteDocumentChangesStore(db: IDBDatabase): void {\n if (db.objectStoreNames.contains('remoteDocumentChanges')) {\n db.deleteObjectStore('remoteDocumentChanges');\n }\n}\n\n/**\n * Creates the target global singleton row.\n *\n * @param txn - The version upgrade transaction for indexeddb\n */\nfunction writeEmptyTargetGlobalEntry(\n txn: SimpleDbTransaction\n): PersistencePromise {\n const globalStore = txn.store(\n DbTargetGlobalStore\n );\n const metadata: DbTargetGlobal = {\n highestTargetId: 0,\n highestListenSequenceNumber: 0,\n lastRemoteSnapshotVersion: SnapshotVersion.min().toTimestamp(),\n targetCount: 0\n };\n return globalStore.put(DbTargetGlobalKey, metadata);\n}\n\nfunction createClientMetadataStore(db: IDBDatabase): void {\n db.createObjectStore(DbClientMetadataStore, {\n keyPath: DbClientMetadataKeyPath\n });\n}\n\nfunction createBundlesStore(db: IDBDatabase): void {\n db.createObjectStore(DbBundleStore, {\n keyPath: DbBundleKeyPath\n });\n}\n\nfunction createNamedQueriesStore(db: IDBDatabase): void {\n db.createObjectStore(DbNamedQueryStore, {\n keyPath: DbNamedQueryKeyPath\n });\n}\n\nfunction createFieldIndex(db: IDBDatabase): void {\n const indexConfigurationStore = db.createObjectStore(\n DbIndexConfigurationStore,\n {\n keyPath: DbIndexConfigurationKeyPath,\n autoIncrement: true\n }\n );\n indexConfigurationStore.createIndex(\n DbIndexConfigurationCollectionGroupIndex,\n DbIndexConfigurationCollectionGroupIndexPath,\n { unique: false }\n );\n\n const indexStateStore = db.createObjectStore(DbIndexStateStore, {\n keyPath: DbIndexStateKeyPath\n });\n indexStateStore.createIndex(\n DbIndexStateSequenceNumberIndex,\n DbIndexStateSequenceNumberIndexPath,\n { unique: false }\n );\n\n const indexEntryStore = db.createObjectStore(DbIndexEntryStore, {\n keyPath: DbIndexEntryKeyPath\n });\n indexEntryStore.createIndex(\n DbIndexEntryDocumentKeyIndex,\n DbIndexEntryDocumentKeyIndexPath,\n { unique: false }\n );\n}\n\nfunction createDocumentOverlayStore(db: IDBDatabase): void {\n const documentOverlayStore = db.createObjectStore(DbDocumentOverlayStore, {\n keyPath: DbDocumentOverlayKeyPath\n });\n documentOverlayStore.createIndex(\n DbDocumentOverlayCollectionPathOverlayIndex,\n DbDocumentOverlayCollectionPathOverlayIndexPath,\n { unique: false }\n );\n documentOverlayStore.createIndex(\n DbDocumentOverlayCollectionGroupOverlayIndex,\n DbDocumentOverlayCollectionGroupOverlayIndexPath,\n { unique: false }\n );\n}\n\nfunction createGlobalsStore(db: IDBDatabase): void {\n db.createObjectStore(DbGlobalsStore, {\n keyPath: DbGlobalsKeyPath\n });\n}\n\nfunction extractKey(remoteDoc: DbRemoteDocumentLegacy): DocumentKey {\n if (remoteDoc.document) {\n return new DocumentKey(\n ResourcePath.fromString(remoteDoc.document.name!).popFirst(5)\n );\n } else if (remoteDoc.noDocument) {\n return DocumentKey.fromSegments(remoteDoc.noDocument.path);\n } else if (remoteDoc.unknownDocument) {\n return DocumentKey.fromSegments(remoteDoc.unknownDocument.path);\n } else {\n return fail(0x8faf, 'Unexpected DbRemoteDocument');\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isSafari } from '@firebase/util';\n\nimport { User } from '../auth/user';\nimport { DatabaseId } from '../core/database_info';\nimport { ListenSequence, SequenceNumberSyncer } from '../core/listen_sequence';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logError } from '../util/log';\nimport { DocumentLike, WindowLike } from '../util/types';\n\nimport { BundleCache } from './bundle_cache';\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { GlobalsCache } from './globals_cache';\nimport { IndexManager } from './index_manager';\nimport { IndexedDbBundleCache } from './indexeddb_bundle_cache';\nimport { IndexedDbDocumentOverlayCache } from './indexeddb_document_overlay_cache';\nimport { IndexedDbGlobalsCache } from './indexeddb_globals_cache';\nimport { IndexedDbIndexManager } from './indexeddb_index_manager';\nimport { IndexedDbLruDelegateImpl } from './indexeddb_lru_delegate_impl';\nimport { IndexedDbMutationQueue } from './indexeddb_mutation_queue';\nimport {\n IndexedDbRemoteDocumentCache,\n newIndexedDbRemoteDocumentCache\n} from './indexeddb_remote_document_cache';\nimport {\n DbClientMetadata,\n DbPrimaryClient,\n SCHEMA_VERSION\n} from './indexeddb_schema';\nimport { SchemaConverter } from './indexeddb_schema_converter';\nimport {\n DbClientMetadataKey,\n DbClientMetadataStore,\n DbPrimaryClientKey,\n DbPrimaryClientStore,\n getObjectStores\n} from './indexeddb_sentinels';\nimport { IndexedDbTargetCache } from './indexeddb_target_cache';\nimport { getStore, IndexedDbTransaction } from './indexeddb_transaction';\nimport { LocalSerializer } from './local_serializer';\nimport { LruParams } from './lru_garbage_collector';\nimport { Persistence, PrimaryStateListener } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport {\n PersistenceTransaction,\n PersistenceTransactionMode,\n PRIMARY_LEASE_LOST_ERROR_MSG\n} from './persistence_transaction';\nimport { ClientId } from './shared_client_state';\nimport {\n isIndexedDbTransactionError,\n SimpleDb,\n SimpleDbStore\n} from './simple_db';\n\nconst LOG_TAG = 'IndexedDbPersistence';\n\n/**\n * Oldest acceptable age in milliseconds for client metadata before the client\n * is considered inactive and its associated data is garbage collected.\n */\nconst MAX_CLIENT_AGE_MS = 30 * 60 * 1000; // 30 minutes\n\n/**\n * Oldest acceptable metadata age for clients that may participate in the\n * primary lease election. Clients that have not updated their client metadata\n * within 5 seconds are not eligible to receive a primary lease.\n */\nconst MAX_PRIMARY_ELIGIBLE_AGE_MS = 5000;\n\n/**\n * The interval at which clients will update their metadata, including\n * refreshing their primary lease if held or potentially trying to acquire it if\n * not held.\n *\n * Primary clients may opportunistically refresh their metadata earlier\n * if they're already performing an IndexedDB operation.\n */\nconst CLIENT_METADATA_REFRESH_INTERVAL_MS = 4000;\n/** User-facing error when the primary lease is required but not available. */\nconst PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG =\n 'Failed to obtain exclusive access to the persistence layer. To allow ' +\n 'shared access, multi-tab synchronization has to be enabled in all tabs. ' +\n 'If you are using `experimentalForceOwningTab:true`, make sure that only ' +\n 'one tab has persistence enabled at any given time.';\nconst UNSUPPORTED_PLATFORM_ERROR_MSG =\n 'This platform is either missing IndexedDB or is known to have ' +\n 'an incomplete implementation. Offline persistence has been disabled.';\n\n// The format of the LocalStorage key that stores zombied client is:\n// firestore_zombie__\nconst ZOMBIED_CLIENTS_KEY_PREFIX = 'firestore_zombie';\n\n/**\n * The name of the main (and currently only) IndexedDB database. This name is\n * appended to the prefix provided to the IndexedDbPersistence constructor.\n */\nexport const MAIN_DATABASE = 'main';\n\n/**\n * An IndexedDB-backed instance of Persistence. Data is stored persistently\n * across sessions.\n *\n * On Web only, the Firestore SDKs support shared access to its persistence\n * layer. This allows multiple browser tabs to read and write to IndexedDb and\n * to synchronize state even without network connectivity. Shared access is\n * currently optional and not enabled unless all clients invoke\n * `enablePersistence()` with `{synchronizeTabs:true}`.\n *\n * In multi-tab mode, if multiple clients are active at the same time, the SDK\n * will designate one client as the \"primary client\". An effort is made to pick\n * a visible, network-connected and active client, and this client is\n * responsible for letting other clients know about its presence. The primary\n * client writes a unique client-generated identifier (the client ID) to\n * IndexedDb’s \"owner\" store every 4 seconds. If the primary client fails to\n * update this entry, another client can acquire the lease and take over as\n * primary.\n *\n * Some persistence operations in the SDK are designated as primary-client only\n * operations. This includes the acknowledgment of mutations and all updates of\n * remote documents. The effects of these operations are written to persistence\n * and then broadcast to other tabs via LocalStorage (see\n * `WebStorageSharedClientState`), which then refresh their state from\n * persistence.\n *\n * Similarly, the primary client listens to notifications sent by secondary\n * clients to discover persistence changes written by secondary clients, such as\n * the addition of new mutations and query targets.\n *\n * If multi-tab is not enabled and another tab already obtained the primary\n * lease, IndexedDbPersistence enters a failed state and all subsequent\n * operations will automatically fail.\n *\n * Additionally, there is an optimization so that when a tab is closed, the\n * primary lease is released immediately (this is especially important to make\n * sure that a refreshed tab is able to immediately re-acquire the primary\n * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload\n * since it is an asynchronous API. So in addition to attempting to give up the\n * lease, the leaseholder writes its client ID to a \"zombiedClient\" entry in\n * LocalStorage which acts as an indicator that another tab should go ahead and\n * take the primary lease immediately regardless of the current lease timestamp.\n *\n * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no\n * longer optional.\n */\nexport class IndexedDbPersistence implements Persistence {\n private simpleDb: SimpleDb;\n\n private listenSequence: ListenSequence | null = null;\n\n private _started = false;\n private isPrimary = false;\n private networkEnabled = true;\n private dbName: string;\n\n /** Our window.unload handler, if registered. */\n private windowUnloadHandler: (() => void) | null = null;\n private inForeground = false;\n\n private serializer: LocalSerializer;\n\n /** Our 'visibilitychange' listener if registered. */\n private documentVisibilityHandler: ((e?: Event) => void) | null = null;\n\n /** The client metadata refresh task. */\n private clientMetadataRefresher: DelayedOperation | null = null;\n\n /** The last time we garbage collected the client metadata object store. */\n private lastGarbageCollectionTime = Number.NEGATIVE_INFINITY;\n\n /** A listener to notify on primary state changes. */\n private primaryStateListener: PrimaryStateListener = _ => Promise.resolve();\n\n private readonly globalsCache: IndexedDbGlobalsCache;\n private readonly targetCache: IndexedDbTargetCache;\n private readonly remoteDocumentCache: IndexedDbRemoteDocumentCache;\n private readonly bundleCache: IndexedDbBundleCache;\n private readonly webStorage: Storage | null;\n readonly referenceDelegate: IndexedDbLruDelegateImpl;\n\n constructor(\n /**\n * Whether to synchronize the in-memory state of multiple tabs and share\n * access to local persistence.\n */\n private readonly allowTabSynchronization: boolean,\n\n private readonly persistenceKey: string,\n private readonly clientId: ClientId,\n lruParams: LruParams,\n private readonly queue: AsyncQueue,\n private readonly window: WindowLike | null,\n private readonly document: DocumentLike | null,\n serializer: JsonProtoSerializer,\n private readonly sequenceNumberSyncer: SequenceNumberSyncer,\n\n /**\n * If set to true, forcefully obtains database access. Existing tabs will\n * no longer be able to access IndexedDB.\n */\n private readonly forceOwningTab: boolean,\n private readonly schemaVersion = SCHEMA_VERSION\n ) {\n if (!IndexedDbPersistence.isAvailable()) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n UNSUPPORTED_PLATFORM_ERROR_MSG\n );\n }\n\n this.referenceDelegate = new IndexedDbLruDelegateImpl(this, lruParams);\n this.dbName = persistenceKey + MAIN_DATABASE;\n this.serializer = new LocalSerializer(serializer);\n this.simpleDb = new SimpleDb(\n this.dbName,\n this.schemaVersion,\n new SchemaConverter(this.serializer)\n );\n this.globalsCache = new IndexedDbGlobalsCache();\n this.targetCache = new IndexedDbTargetCache(\n this.referenceDelegate,\n this.serializer\n );\n this.remoteDocumentCache = newIndexedDbRemoteDocumentCache(this.serializer);\n this.bundleCache = new IndexedDbBundleCache();\n if (this.window && this.window.localStorage) {\n this.webStorage = this.window.localStorage;\n } else {\n this.webStorage = null;\n if (forceOwningTab === false) {\n logError(\n LOG_TAG,\n 'LocalStorage is unavailable. As a result, persistence may not work ' +\n 'reliably. In particular enablePersistence() could fail immediately ' +\n 'after refreshing the page.'\n );\n }\n }\n }\n\n /**\n * Attempt to start IndexedDb persistence.\n *\n * @returns Whether persistence was enabled.\n */\n start(): Promise {\n debugAssert(!this.started, 'IndexedDbPersistence double-started!');\n debugAssert(this.window !== null, \"Expected 'window' to be defined\");\n\n // NOTE: This is expected to fail sometimes (in the case of another tab\n // already having the persistence lock), so it's the first thing we should\n // do.\n return this.updateClientMetadataAndTryBecomePrimary()\n .then(() => {\n if (!this.isPrimary && !this.allowTabSynchronization) {\n // Fail `start()` if `synchronizeTabs` is disabled and we cannot\n // obtain the primary lease.\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG\n );\n }\n this.attachVisibilityHandler();\n this.attachWindowUnloadHook();\n\n this.scheduleClientMetadataAndPrimaryLeaseRefreshes();\n\n return this.runTransaction(\n 'getHighestListenSequenceNumber',\n 'readonly',\n txn => this.targetCache.getHighestSequenceNumber(txn)\n );\n })\n .then(highestListenSequenceNumber => {\n this.listenSequence = new ListenSequence(\n highestListenSequenceNumber,\n this.sequenceNumberSyncer\n );\n })\n .then(() => {\n this._started = true;\n })\n .catch(reason => {\n this.simpleDb && this.simpleDb.close();\n return Promise.reject(reason);\n });\n }\n\n /**\n * Registers a listener that gets called when the primary state of the\n * instance changes. Upon registering, this listener is invoked immediately\n * with the current primary state.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n setPrimaryStateListener(\n primaryStateListener: PrimaryStateListener\n ): Promise {\n this.primaryStateListener = async primaryState => {\n if (this.started) {\n return primaryStateListener(primaryState);\n }\n };\n return primaryStateListener(this.isPrimary);\n }\n\n /**\n * Registers a listener that gets called when the database receives a\n * version change event indicating that it has deleted.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n setDatabaseDeletedListener(\n databaseDeletedListener: () => Promise\n ): void {\n this.simpleDb.setVersionChangeListener(async event => {\n // Check if an attempt is made to delete IndexedDB.\n if (event.newVersion === null) {\n await databaseDeletedListener();\n }\n });\n }\n\n /**\n * Adjusts the current network state in the client's metadata, potentially\n * affecting the primary lease.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n setNetworkEnabled(networkEnabled: boolean): void {\n if (this.networkEnabled !== networkEnabled) {\n this.networkEnabled = networkEnabled;\n // Schedule a primary lease refresh for immediate execution. The eventual\n // lease update will be propagated via `primaryStateListener`.\n this.queue.enqueueAndForget(async () => {\n if (this.started) {\n await this.updateClientMetadataAndTryBecomePrimary();\n }\n });\n }\n }\n\n /**\n * Updates the client metadata in IndexedDb and attempts to either obtain or\n * extend the primary lease for the local client. Asynchronously notifies the\n * primary state listener if the client either newly obtained or released its\n * primary lease.\n */\n private updateClientMetadataAndTryBecomePrimary(): Promise {\n return this.runTransaction(\n 'updateClientMetadataAndTryBecomePrimary',\n 'readwrite',\n txn => {\n const metadataStore = clientMetadataStore(txn);\n return metadataStore\n .put({\n clientId: this.clientId,\n updateTimeMs: Date.now(),\n networkEnabled: this.networkEnabled,\n inForeground: this.inForeground\n })\n .next(() => {\n if (this.isPrimary) {\n return this.verifyPrimaryLease(txn).next(success => {\n if (!success) {\n this.isPrimary = false;\n this.queue.enqueueRetryable(() =>\n this.primaryStateListener(false)\n );\n }\n });\n }\n })\n .next(() => this.canActAsPrimary(txn))\n .next(canActAsPrimary => {\n if (this.isPrimary && !canActAsPrimary) {\n return this.releasePrimaryLeaseIfHeld(txn).next(() => false);\n } else if (canActAsPrimary) {\n return this.acquireOrExtendPrimaryLease(txn).next(() => true);\n } else {\n return /* canActAsPrimary= */ false;\n }\n });\n }\n )\n .catch(e => {\n if (isIndexedDbTransactionError(e)) {\n logDebug(LOG_TAG, 'Failed to extend owner lease: ', e);\n // Proceed with the existing state. Any subsequent access to\n // IndexedDB will verify the lease.\n return this.isPrimary;\n }\n\n if (!this.allowTabSynchronization) {\n throw e;\n }\n\n logDebug(\n LOG_TAG,\n 'Releasing owner lease after error during lease refresh',\n e\n );\n return /* isPrimary= */ false;\n })\n .then(isPrimary => {\n if (this.isPrimary !== isPrimary) {\n this.queue.enqueueRetryable(() =>\n this.primaryStateListener(isPrimary)\n );\n }\n this.isPrimary = isPrimary;\n });\n }\n\n private verifyPrimaryLease(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const store = primaryClientStore(txn);\n return store.get(DbPrimaryClientKey).next(primaryClient => {\n return PersistencePromise.resolve(this.isLocalClient(primaryClient));\n });\n }\n\n private removeClientMetadata(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const metadataStore = clientMetadataStore(txn);\n return metadataStore.delete(this.clientId);\n }\n\n /**\n * If the garbage collection threshold has passed, prunes the\n * RemoteDocumentChanges and the ClientMetadata store based on the last update\n * time of all clients.\n */\n private async maybeGarbageCollectMultiClientState(): Promise {\n if (\n this.isPrimary &&\n !this.isWithinAge(this.lastGarbageCollectionTime, MAX_CLIENT_AGE_MS)\n ) {\n this.lastGarbageCollectionTime = Date.now();\n\n const inactiveClients = await this.runTransaction(\n 'maybeGarbageCollectMultiClientState',\n 'readwrite-primary',\n txn => {\n const metadataStore = getStore(\n txn,\n DbClientMetadataStore\n );\n\n return metadataStore.loadAll().next(existingClients => {\n const active = this.filterActiveClients(\n existingClients,\n MAX_CLIENT_AGE_MS\n );\n const inactive = existingClients.filter(\n client => active.indexOf(client) === -1\n );\n\n // Delete metadata for clients that are no longer considered active.\n return PersistencePromise.forEach(\n inactive,\n (inactiveClient: DbClientMetadata) =>\n metadataStore.delete(inactiveClient.clientId)\n ).next(() => inactive);\n });\n }\n ).catch(() => {\n // Ignore primary lease violations or any other type of error. The next\n // primary will run `maybeGarbageCollectMultiClientState()` again.\n // We don't use `ignoreIfPrimaryLeaseLoss()` since we don't want to depend\n // on LocalStore.\n return [];\n });\n\n // Delete potential leftover entries that may continue to mark the\n // inactive clients as zombied in LocalStorage.\n // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for\n // the client atomically, but we can't. So we opt to delete the IndexedDb\n // entries first to avoid potentially reviving a zombied client.\n if (this.webStorage) {\n for (const inactiveClient of inactiveClients) {\n this.webStorage.removeItem(\n this.zombiedClientLocalStorageKey(inactiveClient.clientId)\n );\n }\n }\n }\n }\n\n /**\n * Schedules a recurring timer to update the client metadata and to either\n * extend or acquire the primary lease if the client is eligible.\n */\n private scheduleClientMetadataAndPrimaryLeaseRefreshes(): void {\n this.clientMetadataRefresher = this.queue.enqueueAfterDelay(\n TimerId.ClientMetadataRefresh,\n CLIENT_METADATA_REFRESH_INTERVAL_MS,\n () => {\n return this.updateClientMetadataAndTryBecomePrimary()\n .then(() => this.maybeGarbageCollectMultiClientState())\n .then(() => this.scheduleClientMetadataAndPrimaryLeaseRefreshes());\n }\n );\n }\n\n /** Checks whether `client` is the local client. */\n private isLocalClient(client: DbPrimaryClient | null): boolean {\n return client ? client.ownerId === this.clientId : false;\n }\n\n /**\n * Evaluate the state of all active clients and determine whether the local\n * client is or can act as the holder of the primary lease. Returns whether\n * the client is eligible for the lease, but does not actually acquire it.\n * May return 'false' even if there is no active leaseholder and another\n * (foreground) client should become leaseholder instead.\n */\n private canActAsPrimary(\n txn: PersistenceTransaction\n ): PersistencePromise {\n if (this.forceOwningTab) {\n return PersistencePromise.resolve(true);\n }\n const store = primaryClientStore(txn);\n return store\n .get(DbPrimaryClientKey)\n .next(currentPrimary => {\n const currentLeaseIsValid =\n currentPrimary !== null &&\n this.isWithinAge(\n currentPrimary.leaseTimestampMs,\n MAX_PRIMARY_ELIGIBLE_AGE_MS\n ) &&\n !this.isClientZombied(currentPrimary.ownerId);\n\n // A client is eligible for the primary lease if:\n // - its network is enabled and the client's tab is in the foreground.\n // - its network is enabled and no other client's tab is in the\n // foreground.\n // - every clients network is disabled and the client's tab is in the\n // foreground.\n // - every clients network is disabled and no other client's tab is in\n // the foreground.\n // - the `forceOwningTab` setting was passed in.\n if (currentLeaseIsValid) {\n if (this.isLocalClient(currentPrimary) && this.networkEnabled) {\n return true;\n }\n\n if (!this.isLocalClient(currentPrimary)) {\n if (!currentPrimary!.allowTabSynchronization) {\n // Fail the `canActAsPrimary` check if the current leaseholder has\n // not opted into multi-tab synchronization. If this happens at\n // client startup, we reject the Promise returned by\n // `enablePersistence()` and the user can continue to use Firestore\n // with in-memory persistence.\n // If this fails during a lease refresh, we will instead block the\n // AsyncQueue from executing further operations. Note that this is\n // acceptable since mixing & matching different `synchronizeTabs`\n // settings is not supported.\n //\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can\n // no longer be turned off.\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG\n );\n }\n\n return false;\n }\n }\n\n if (this.networkEnabled && this.inForeground) {\n return true;\n }\n\n return clientMetadataStore(txn)\n .loadAll()\n .next(existingClients => {\n // Process all existing clients and determine whether at least one of\n // them is better suited to obtain the primary lease.\n const preferredCandidate = this.filterActiveClients(\n existingClients,\n MAX_PRIMARY_ELIGIBLE_AGE_MS\n ).find(otherClient => {\n if (this.clientId !== otherClient.clientId) {\n const otherClientHasBetterNetworkState =\n !this.networkEnabled && otherClient.networkEnabled;\n const otherClientHasBetterVisibility =\n !this.inForeground && otherClient.inForeground;\n const otherClientHasSameNetworkState =\n this.networkEnabled === otherClient.networkEnabled;\n if (\n otherClientHasBetterNetworkState ||\n (otherClientHasBetterVisibility &&\n otherClientHasSameNetworkState)\n ) {\n return true;\n }\n }\n return false;\n });\n return preferredCandidate === undefined;\n });\n })\n .next(canActAsPrimary => {\n if (this.isPrimary !== canActAsPrimary) {\n logDebug(\n LOG_TAG,\n `Client ${\n canActAsPrimary ? 'is' : 'is not'\n } eligible for a primary lease.`\n );\n }\n return canActAsPrimary;\n });\n }\n\n async shutdown(): Promise {\n // The shutdown() operations are idempotent and can be called even when\n // start() aborted (e.g. because it couldn't acquire the persistence lease).\n this._started = false;\n\n this.markClientZombied();\n if (this.clientMetadataRefresher) {\n this.clientMetadataRefresher.cancel();\n this.clientMetadataRefresher = null;\n }\n this.detachVisibilityHandler();\n this.detachWindowUnloadHook();\n\n // Use `SimpleDb.runTransaction` directly to avoid failing if another tab\n // has obtained the primary lease.\n await this.simpleDb.runTransaction(\n 'shutdown',\n 'readwrite',\n [DbPrimaryClientStore, DbClientMetadataStore],\n simpleDbTxn => {\n const persistenceTransaction = new IndexedDbTransaction(\n simpleDbTxn,\n ListenSequence.INVALID\n );\n return this.releasePrimaryLeaseIfHeld(persistenceTransaction).next(() =>\n this.removeClientMetadata(persistenceTransaction)\n );\n }\n );\n this.simpleDb.close();\n\n // Remove the entry marking the client as zombied from LocalStorage since\n // we successfully deleted its metadata from IndexedDb.\n this.removeClientZombiedEntry();\n }\n\n /**\n * Returns clients that are not zombied and have an updateTime within the\n * provided threshold.\n */\n private filterActiveClients(\n clients: DbClientMetadata[],\n activityThresholdMs: number\n ): DbClientMetadata[] {\n return clients.filter(\n client =>\n this.isWithinAge(client.updateTimeMs, activityThresholdMs) &&\n !this.isClientZombied(client.clientId)\n );\n }\n\n /**\n * Returns the IDs of the clients that are currently active. If multi-tab\n * is not supported, returns an array that only contains the local client's\n * ID.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n getActiveClients(): Promise {\n return this.runTransaction('getActiveClients', 'readonly', txn => {\n return clientMetadataStore(txn)\n .loadAll()\n .next(clients =>\n this.filterActiveClients(clients, MAX_CLIENT_AGE_MS).map(\n clientMetadata => clientMetadata.clientId\n )\n );\n });\n }\n\n get started(): boolean {\n return this._started;\n }\n\n getGlobalsCache(): GlobalsCache {\n debugAssert(\n this.started,\n 'Cannot initialize GlobalsCache before persistence is started.'\n );\n return this.globalsCache;\n }\n\n getMutationQueue(\n user: User,\n indexManager: IndexManager\n ): IndexedDbMutationQueue {\n debugAssert(\n this.started,\n 'Cannot initialize MutationQueue before persistence is started.'\n );\n return IndexedDbMutationQueue.forUser(\n user,\n this.serializer,\n indexManager,\n this.referenceDelegate\n );\n }\n\n getTargetCache(): IndexedDbTargetCache {\n debugAssert(\n this.started,\n 'Cannot initialize TargetCache before persistence is started.'\n );\n return this.targetCache;\n }\n\n getRemoteDocumentCache(): IndexedDbRemoteDocumentCache {\n debugAssert(\n this.started,\n 'Cannot initialize RemoteDocumentCache before persistence is started.'\n );\n return this.remoteDocumentCache;\n }\n\n getIndexManager(user: User): IndexManager {\n debugAssert(\n this.started,\n 'Cannot initialize IndexManager before persistence is started.'\n );\n return new IndexedDbIndexManager(\n user,\n this.serializer.remoteSerializer.databaseId\n );\n }\n\n getDocumentOverlayCache(user: User): DocumentOverlayCache {\n debugAssert(\n this.started,\n 'Cannot initialize IndexedDbDocumentOverlayCache before persistence is started.'\n );\n return IndexedDbDocumentOverlayCache.forUser(this.serializer, user);\n }\n\n getBundleCache(): BundleCache {\n debugAssert(\n this.started,\n 'Cannot initialize BundleCache before persistence is started.'\n );\n return this.bundleCache;\n }\n\n runTransaction(\n action: string,\n mode: PersistenceTransactionMode,\n transactionOperation: (\n transaction: PersistenceTransaction\n ) => PersistencePromise\n ): Promise {\n logDebug(LOG_TAG, 'Starting transaction:', action);\n\n const simpleDbMode = mode === 'readonly' ? 'readonly' : 'readwrite';\n const objectStores = getObjectStores(this.schemaVersion);\n\n let persistenceTransaction: PersistenceTransaction;\n\n // Do all transactions as readwrite against all object stores, since we\n // are the only reader/writer.\n return this.simpleDb\n .runTransaction(action, simpleDbMode, objectStores, simpleDbTxn => {\n persistenceTransaction = new IndexedDbTransaction(\n simpleDbTxn,\n this.listenSequence\n ? this.listenSequence.next()\n : ListenSequence.INVALID\n );\n\n if (mode === 'readwrite-primary') {\n // While we merely verify that we have (or can acquire) the lease\n // immediately, we wait to extend the primary lease until after\n // executing transactionOperation(). This ensures that even if the\n // transactionOperation takes a long time, we'll use a recent\n // leaseTimestampMs in the extended (or newly acquired) lease.\n return this.verifyPrimaryLease(persistenceTransaction)\n .next(holdsPrimaryLease => {\n if (holdsPrimaryLease) {\n return /* holdsPrimaryLease= */ true;\n }\n return this.canActAsPrimary(persistenceTransaction);\n })\n .next(holdsPrimaryLease => {\n if (!holdsPrimaryLease) {\n logError(\n `Failed to obtain primary lease for action '${action}'.`\n );\n this.isPrimary = false;\n this.queue.enqueueRetryable(() =>\n this.primaryStateListener(false)\n );\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_LOST_ERROR_MSG\n );\n }\n return transactionOperation(persistenceTransaction);\n })\n .next(result => {\n return this.acquireOrExtendPrimaryLease(\n persistenceTransaction\n ).next(() => result);\n });\n } else {\n return this.verifyAllowTabSynchronization(\n persistenceTransaction\n ).next(() => transactionOperation(persistenceTransaction));\n }\n })\n .then(result => {\n persistenceTransaction.raiseOnCommittedEvent();\n return result;\n });\n }\n\n /**\n * Verifies that the current tab is the primary leaseholder or alternatively\n * that the leaseholder has opted into multi-tab synchronization.\n */\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer\n // be turned off.\n private verifyAllowTabSynchronization(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const store = primaryClientStore(txn);\n return store.get(DbPrimaryClientKey).next(currentPrimary => {\n const currentLeaseIsValid =\n currentPrimary !== null &&\n this.isWithinAge(\n currentPrimary.leaseTimestampMs,\n MAX_PRIMARY_ELIGIBLE_AGE_MS\n ) &&\n !this.isClientZombied(currentPrimary.ownerId);\n\n if (currentLeaseIsValid && !this.isLocalClient(currentPrimary)) {\n if (\n !this.forceOwningTab &&\n (!this.allowTabSynchronization ||\n !currentPrimary!.allowTabSynchronization)\n ) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG\n );\n }\n }\n });\n }\n\n /**\n * Obtains or extends the new primary lease for the local client. This\n * method does not verify that the client is eligible for this lease.\n */\n private acquireOrExtendPrimaryLease(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const newPrimary: DbPrimaryClient = {\n ownerId: this.clientId,\n allowTabSynchronization: this.allowTabSynchronization,\n leaseTimestampMs: Date.now()\n };\n return primaryClientStore(txn).put(DbPrimaryClientKey, newPrimary);\n }\n\n static isAvailable(): boolean {\n return SimpleDb.isAvailable();\n }\n\n /** Checks the primary lease and removes it if we are the current primary. */\n private releasePrimaryLeaseIfHeld(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const store = primaryClientStore(txn);\n return store.get(DbPrimaryClientKey).next(primaryClient => {\n if (this.isLocalClient(primaryClient)) {\n logDebug(LOG_TAG, 'Releasing primary lease.');\n return store.delete(DbPrimaryClientKey);\n } else {\n return PersistencePromise.resolve();\n }\n });\n }\n\n /** Verifies that `updateTimeMs` is within `maxAgeMs`. */\n private isWithinAge(updateTimeMs: number, maxAgeMs: number): boolean {\n const now = Date.now();\n const minAcceptable = now - maxAgeMs;\n const maxAcceptable = now;\n if (updateTimeMs < minAcceptable) {\n return false;\n } else if (updateTimeMs > maxAcceptable) {\n logError(\n `Detected an update time that is in the future: ${updateTimeMs} > ${maxAcceptable}`\n );\n return false;\n }\n\n return true;\n }\n\n private attachVisibilityHandler(): void {\n if (\n this.document !== null &&\n typeof this.document.addEventListener === 'function'\n ) {\n this.documentVisibilityHandler = () => {\n this.queue.enqueueAndForget(() => {\n this.inForeground = this.document!.visibilityState === 'visible';\n return this.updateClientMetadataAndTryBecomePrimary();\n });\n };\n\n this.document.addEventListener(\n 'visibilitychange',\n this.documentVisibilityHandler\n );\n\n this.inForeground = this.document.visibilityState === 'visible';\n }\n }\n\n private detachVisibilityHandler(): void {\n if (this.documentVisibilityHandler) {\n debugAssert(\n this.document !== null &&\n typeof this.document.addEventListener === 'function',\n \"Expected 'document.addEventListener' to be a function\"\n );\n this.document.removeEventListener(\n 'visibilitychange',\n this.documentVisibilityHandler\n );\n this.documentVisibilityHandler = null;\n }\n }\n\n /**\n * Attaches a window.unload handler that will synchronously write our\n * clientId to a \"zombie client id\" location in LocalStorage. This can be used\n * by tabs trying to acquire the primary lease to determine that the lease\n * is no longer valid even if the timestamp is recent. This is particularly\n * important for the refresh case (so the tab correctly re-acquires the\n * primary lease). LocalStorage is used for this rather than IndexedDb because\n * it is a synchronous API and so can be used reliably from an unload\n * handler.\n */\n private attachWindowUnloadHook(): void {\n if (typeof this.window?.addEventListener === 'function') {\n this.windowUnloadHandler = () => {\n // Note: In theory, this should be scheduled on the AsyncQueue since it\n // accesses internal state. We execute this code directly during shutdown\n // to make sure it gets a chance to run.\n this.markClientZombied();\n\n const safariIndexdbBugVersionRegex = /(?:Version|Mobile)\\/1[456]/;\n if (\n isSafari() &&\n (navigator.appVersion.match(safariIndexdbBugVersionRegex) ||\n navigator.userAgent.match(safariIndexdbBugVersionRegex))\n ) {\n // On Safari 14, 15, and 16, we do not run any cleanup actions as it might\n // trigger a bug that prevents Safari from re-opening IndexedDB during\n // the next page load.\n // See https://bugs.webkit.org/show_bug.cgi?id=226547\n this.queue.enterRestrictedMode(/* purgeExistingTasks= */ true);\n }\n\n this.queue.enqueueAndForget(() => {\n // Attempt graceful shutdown (including releasing our primary lease),\n // but there's no guarantee it will complete.\n return this.shutdown();\n });\n };\n this.window.addEventListener('pagehide', this.windowUnloadHandler);\n }\n }\n\n private detachWindowUnloadHook(): void {\n if (this.windowUnloadHandler) {\n debugAssert(\n typeof this.window?.removeEventListener === 'function',\n \"Expected 'window.removeEventListener' to be a function\"\n );\n this.window!.removeEventListener('pagehide', this.windowUnloadHandler);\n this.windowUnloadHandler = null;\n }\n }\n\n /**\n * Returns whether a client is \"zombied\" based on its LocalStorage entry.\n * Clients become zombied when their tab closes without running all of the\n * cleanup logic in `shutdown()`.\n */\n private isClientZombied(clientId: ClientId): boolean {\n try {\n const isZombied =\n this.webStorage?.getItem(\n this.zombiedClientLocalStorageKey(clientId)\n ) !== null;\n logDebug(\n LOG_TAG,\n `Client '${clientId}' ${\n isZombied ? 'is' : 'is not'\n } zombied in LocalStorage`\n );\n return isZombied;\n } catch (e) {\n // Gracefully handle if LocalStorage isn't working.\n logError(LOG_TAG, 'Failed to get zombied client id.', e);\n return false;\n }\n }\n\n /**\n * Record client as zombied (a client that had its tab closed). Zombied\n * clients are ignored during primary tab selection.\n */\n private markClientZombied(): void {\n if (!this.webStorage) {\n return;\n }\n try {\n this.webStorage.setItem(\n this.zombiedClientLocalStorageKey(this.clientId),\n String(Date.now())\n );\n } catch (e) {\n // Gracefully handle if LocalStorage isn't available / working.\n logError('Failed to set zombie client id.', e);\n }\n }\n\n /** Removes the zombied client entry if it exists. */\n private removeClientZombiedEntry(): void {\n if (!this.webStorage) {\n return;\n }\n try {\n this.webStorage.removeItem(\n this.zombiedClientLocalStorageKey(this.clientId)\n );\n } catch (e) {\n // Ignore\n }\n }\n\n private zombiedClientLocalStorageKey(clientId: ClientId): string {\n return `${ZOMBIED_CLIENTS_KEY_PREFIX}_${this.persistenceKey}_${clientId}`;\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the primary client object store.\n */\nfunction primaryClientStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbPrimaryClientStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the client metadata object store.\n */\nfunction clientMetadataStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbClientMetadataStore\n );\n}\n\n/**\n * Generates a string used as a prefix when storing data in IndexedDB and\n * LocalStorage.\n */\nexport function indexedDbStoragePrefix(\n databaseId: DatabaseId,\n persistenceKey: string\n): string {\n // Use two different prefix formats:\n //\n // * firestore / persistenceKey / projectID . databaseID / ...\n // * firestore / persistenceKey / projectID / ...\n //\n // projectIDs are DNS-compatible names and cannot contain dots\n // so there's no danger of collisions.\n let database = databaseId.projectId;\n if (!databaseId.isDefaultDatabase) {\n database += '.' + databaseId.database;\n }\n\n return 'firestore/' + persistenceKey + '/' + database + '/';\n}\n\nexport async function indexedDbClearPersistence(\n persistenceKey: string\n): Promise {\n if (!SimpleDb.isAvailable()) {\n return Promise.resolve();\n }\n const dbName = persistenceKey + MAIN_DATABASE;\n await SimpleDb.delete(dbName);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BatchId, ListenSequenceNumber, TargetId } from '../core/types';\nimport { IndexKind } from '../model/field_index';\nimport { BundledQuery } from '../protos/firestore_bundle_proto';\nimport {\n Document as ProtoDocument,\n DocumentsTarget as ProtoDocumentsTarget,\n QueryTarget as ProtoQueryTarget,\n Write as ProtoWrite\n} from '../protos/firestore_proto_api';\n\nimport { EncodedResourcePath } from './encoded_resource_path';\nimport { DbTimestampKey, KeySafeBytes } from './indexeddb_sentinels';\n\n/**\n * Schema Version for the Web client:\n * 1. Initial version including Mutation Queue, Query Cache, and Remote\n * Document Cache\n * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No\n * longer required because migration 3 unconditionally clears it.\n * 3. Dropped and re-created Query Cache to deal with cache corruption related\n * to limbo resolution. Addresses\n * https://github.com/firebase/firebase-ios-sdk/issues/1548\n * 4. Multi-Tab Support.\n * 5. Removal of held write acks.\n * 6. Create document global for tracking document cache size.\n * 7. Ensure every cached document has a sentinel row with a sequence number.\n * 8. Add collection-parent index for Collection Group queries.\n * 9. Change RemoteDocumentChanges store to be keyed by readTime rather than\n * an auto-incrementing ID. This is required for Index-Free queries.\n * 10. Rewrite the canonical IDs to the explicit Protobuf-based format.\n * 11. Add bundles and named_queries for bundle support.\n * 12. Add document overlays.\n * 13. Rewrite the keys of the remote document cache to allow for efficient\n * document lookup via `getAll()`.\n * 14. Add overlays.\n * 15. Add indexing support.\n * 16. Parse timestamp strings before creating index entries.\n * 17. TODO(tomandersen)\n * 18. Encode key safe representations of IndexEntry in DbIndexEntryStore.\n */\n\nexport const SCHEMA_VERSION = 18;\n\n/**\n * Wrapper class to store timestamps (seconds and nanos) in IndexedDb objects.\n */\nexport interface DbTimestamp {\n seconds: number;\n nanoseconds: number;\n}\n\n/**\n * A singleton object to be stored in the 'owner' store in IndexedDb.\n *\n * A given database can have a single primary tab assigned at a given time. That\n * tab must validate that it is still holding the primary lease before every\n * operation that requires locked access. The primary tab should regularly\n * write an updated timestamp to this lease to prevent other tabs from\n * \"stealing\" the primary lease\n */\nexport interface DbPrimaryClient {\n ownerId: string;\n /** Whether to allow shared access from multiple tabs. */\n allowTabSynchronization: boolean;\n leaseTimestampMs: number;\n}\n\n/**\n * An object to be stored in the 'mutationQueues' store in IndexedDb.\n *\n * Each user gets a single queue of MutationBatches to apply to the server.\n * DbMutationQueue tracks the metadata about the queue.\n */\nexport interface DbMutationQueue {\n /**\n * The normalized user ID to which this queue belongs.\n */\n userId: string;\n /**\n * An identifier for the highest numbered batch that has been acknowledged\n * by the server. All MutationBatches in this queue with batchIds less\n * than or equal to this value are considered to have been acknowledged by\n * the server.\n *\n * NOTE: this is deprecated and no longer used by the code.\n */\n lastAcknowledgedBatchId: number;\n /**\n * A stream token that was previously sent by the server.\n *\n * See StreamingWriteRequest in datastore.proto for more details about\n * usage.\n *\n * After sending this token, earlier tokens may not be used anymore so\n * only a single stream token is retained.\n *\n * NOTE: this is deprecated and no longer used by the code.\n */\n lastStreamToken: string;\n}\n\n/**\n * An object to be stored in the 'mutations' store in IndexedDb.\n *\n * Represents a batch of user-level mutations intended to be sent to the server\n * in a single write. Each user-level batch gets a separate DbMutationBatch\n * with a new batchId.\n */\nexport interface DbMutationBatch {\n /**\n * The normalized user ID to which this batch belongs.\n */\n userId: string;\n /**\n * An identifier for this batch, allocated using an auto-generated key.\n */\n batchId: BatchId;\n /**\n * The local write time of the batch, stored as milliseconds since the\n * epoch.\n */\n localWriteTimeMs: number;\n /**\n * A list of \"mutations\" that represent a partial base state from when this\n * write batch was initially created. During local application of the write\n * batch, these baseMutations are applied prior to the real writes in order\n * to override certain document fields from the remote document cache. This\n * is necessary in the case of non-idempotent writes (e.g. `increment()`\n * transforms) to make sure that the local view of the modified documents\n * doesn't flicker if the remote document cache receives the result of the\n * non-idempotent write before the write is removed from the queue.\n *\n * These mutations are never sent to the backend.\n */\n baseMutations?: ProtoWrite[];\n /**\n * A list of mutations to apply. All mutations will be applied atomically.\n *\n * Mutations are serialized via toMutation().\n */\n mutations: ProtoWrite[];\n}\n\n/**\n * An object to be stored in the 'documentMutations' store in IndexedDb.\n *\n * A manually maintained index of all the mutation batches that affect a given\n * document key. The rows in this table are references based on the contents of\n * DbMutationBatch.mutations.\n */\nexport interface DbDocumentMutation {}\n\n/**\n * Represents the known absence of a document at a particular version.\n * Stored in IndexedDb as part of a DbRemoteDocument object.\n */\nexport interface DbNoDocument {\n path: string[];\n readTime: DbTimestamp;\n}\n\n/**\n * Represents a document that is known to exist but whose data is unknown.\n * Stored in IndexedDb as part of a DbRemoteDocument object.\n */\nexport interface DbUnknownDocument {\n path: string[];\n version: DbTimestamp;\n}\n\n/**\n * An object to be stored in the 'remoteDocuments' store in IndexedDb.\n * It represents either:\n *\n * - A complete document.\n * - A \"no document\" representing a document that is known not to exist (at\n * some version).\n * - An \"unknown document\" representing a document that is known to exist (at\n * some version) but whose contents are unknown.\n *\n * The document key is split up across `prefixPath`, `collectionGroup` and\n * `documentId`.\n *\n * Note: This is the persisted equivalent of a MaybeDocument and could perhaps\n * be made more general if necessary.\n */\nexport interface DbRemoteDocument {\n /** The path to the document's collection (excluding). */\n prefixPath: string[];\n\n /** The collection ID the document is directly nested under. */\n collectionGroup: string;\n\n /** The document ID. */\n documentId: string;\n\n /** When the document was read from the backend. */\n readTime: DbTimestampKey;\n\n /**\n * Set to an instance of DbUnknownDocument if the data for a document is\n * not known, but it is known that a document exists at the specified\n * version (e.g. it had a successful update applied to it)\n */\n unknownDocument?: DbUnknownDocument;\n /**\n * Set to an instance of a DbNoDocument if it is known that no document\n * exists.\n */\n noDocument?: DbNoDocument;\n /**\n * Set to an instance of a Document if there's a cached version of the\n * document.\n */\n document?: ProtoDocument;\n /**\n * Documents that were written to the remote document store based on\n * a write acknowledgment are marked with `hasCommittedMutations`. These\n * documents are potentially inconsistent with the backend's copy and use\n * the write's commit version as their document version.\n */\n hasCommittedMutations: boolean;\n}\n\n/**\n * Contains a single entry that has metadata about the remote document cache.\n */\nexport interface DbRemoteDocumentGlobal {\n /**\n * Approximately the total size in bytes of all the\n * documents in the document cache.\n */\n byteSize: number;\n}\n\n/**\n * The persisted type for a query nested with in the 'targets' store in\n * IndexedDb. We use the proto definitions for these two kinds of queries in\n * order to avoid writing extra serialization logic.\n */\nexport type DbQuery = ProtoQueryTarget | ProtoDocumentsTarget;\n\n/**\n * An object to be stored in the 'targets' store in IndexedDb.\n *\n * This is based on and should be kept in sync with the proto used in the iOS\n * client.\n *\n * Each query the client listens to against the server is tracked on disk so\n * that the query can be efficiently resumed on restart.\n */\nexport interface DbTarget {\n /**\n * An auto-generated sequential numeric identifier for the query.\n *\n * Queries are stored using their canonicalId as the key, but these\n * canonicalIds can be quite long so we additionally assign a unique\n * queryId which can be used by referenced data structures (e.g.\n * indexes) to minimize the on-disk cost.\n */\n targetId: TargetId;\n /**\n * The canonical string representing this query. This is not unique.\n */\n canonicalId: string;\n /**\n * The last readTime received from the Watch Service for this query.\n *\n * This is the same value as TargetChange.read_time in the protos.\n */\n readTime: DbTimestamp;\n /**\n * An opaque, server-assigned token that allows watching a query to be\n * resumed after disconnecting without retransmitting all the data\n * that matches the query. The resume token essentially identifies a\n * point in time from which the server should resume sending results.\n *\n * This is related to the snapshotVersion in that the resumeToken\n * effectively also encodes that value, but the resumeToken is opaque\n * and sometimes encodes additional information.\n *\n * A consequence of this is that the resumeToken should be used when\n * asking the server to reason about where this client is in the watch\n * stream, but the client should use the snapshotVersion for its own\n * purposes.\n *\n * This is the same value as TargetChange.resume_token in the protos.\n */\n resumeToken: string;\n /**\n * A sequence number representing the last time this query was\n * listened to, used for garbage collection purposes.\n *\n * Conventionally this would be a timestamp value, but device-local\n * clocks are unreliable and they must be able to create new listens\n * even while disconnected. Instead this should be a monotonically\n * increasing number that's incremented on each listen call.\n *\n * This is different from the queryId since the queryId is an\n * immutable identifier assigned to the Query on first use while\n * lastListenSequenceNumber is updated every time the query is\n * listened to.\n */\n lastListenSequenceNumber: number;\n /**\n * Denotes the maximum snapshot version at which the associated query view\n * contained no limbo documents. Undefined for data written prior to\n * schema version 9.\n */\n lastLimboFreeSnapshotVersion?: DbTimestamp;\n /**\n * The query for this target.\n *\n * Because canonical ids are not unique we must store the actual query. We\n * use the proto to have an object we can persist without having to\n * duplicate translation logic to and from a `Query` object.\n */\n query: DbQuery;\n}\n\n/**\n * An object representing an association between a target and a document, or a\n * sentinel row marking the last sequence number at which a document was used.\n * Each document cached must have a corresponding sentinel row before lru\n * garbage collection is enabled.\n *\n * The target associations and sentinel rows are co-located so that orphaned\n * documents and their sequence numbers can be identified efficiently via a scan\n * of this store.\n */\nexport interface DbTargetDocument {\n /**\n * The targetId identifying a target or 0 for a sentinel row.\n */\n targetId: TargetId;\n /**\n * The path to the document, as encoded in the key.\n */\n path: EncodedResourcePath;\n /**\n * If this is a sentinel row, this should be the sequence number of the last\n * time the document specified by `path` was used. Otherwise, it should be\n * `undefined`.\n */\n sequenceNumber?: ListenSequenceNumber;\n}\n\n/**\n * A record of global state tracked across all Targets, tracked separately\n * to avoid the need for extra indexes.\n *\n * This should be kept in-sync with the proto used in the iOS client.\n */\nexport interface DbTargetGlobal {\n /**\n * The highest numbered target id across all targets.\n *\n * See DbTarget.targetId.\n */\n highestTargetId: TargetId;\n /**\n * The highest numbered lastListenSequenceNumber across all targets.\n *\n * See DbTarget.lastListenSequenceNumber.\n */\n highestListenSequenceNumber: number;\n /**\n * A global snapshot version representing the last consistent snapshot we\n * received from the backend. This is monotonically increasing and any\n * snapshots received from the backend prior to this version (e.g. for\n * targets resumed with a resumeToken) should be suppressed (buffered)\n * until the backend has caught up to this snapshot version again. This\n * prevents our cache from ever going backwards in time.\n */\n lastRemoteSnapshotVersion: DbTimestamp;\n /**\n * The number of targets persisted.\n */\n targetCount: number;\n}\n\n/**\n * An object representing an association between a Collection id (e.g. 'messages')\n * to a parent path (e.g. '/chats/123') that contains it as a (sub)collection.\n * This is used to efficiently find all collections to query when performing\n * a Collection Group query.\n */\nexport interface DbCollectionParent {\n /**\n * The collectionId (e.g. 'messages')\n */\n collectionId: string;\n /**\n * The path to the parent (either a document location or an empty path for\n * a root-level collection).\n */\n parent: EncodedResourcePath;\n}\n\n/**\n * A record of the metadata state of each client.\n *\n * PORTING NOTE: This is used to synchronize multi-tab state and does not need\n * to be ported to iOS or Android.\n */\nexport interface DbClientMetadata {\n // Note: Previous schema versions included a field\n // \"lastProcessedDocumentChangeId\". Don't use anymore.\n\n /** The auto-generated client id assigned at client startup. */\n clientId: string;\n /** The last time this state was updated. */\n updateTimeMs: number;\n /** Whether the client's network connection is enabled. */\n networkEnabled: boolean;\n /** Whether this client is running in a foreground tab. */\n inForeground: boolean;\n}\n\n/** An object representing a bundle loaded by the SDK. */\nexport interface DbBundle {\n /** The ID of the loaded bundle. */\n bundleId: string;\n /** The create time of the loaded bundle. */\n createTime: DbTimestamp;\n /** The schema version of the loaded bundle. */\n version: number;\n}\n\n/** An object representing a named query loaded by the SDK via a bundle. */\nexport interface DbNamedQuery {\n /** The name of the query. */\n name: string;\n /** The read time of the results saved in the bundle from the named query. */\n readTime: DbTimestamp;\n /** The query saved in the bundle. */\n bundledQuery: BundledQuery;\n}\n\n/** An object representing the global configuration for a field index. */\nexport interface DbIndexConfiguration {\n /**\n * The index id for this entry. Undefined for indexes that are not yet\n * persisted.\n */\n indexId?: number;\n /** The collection group this index belongs to. */\n collectionGroup: string;\n /** The fields to index for this index. */\n fields: Array<[name: string, kind: IndexKind]>;\n}\n\n/**\n * An object describing how up-to-date the index backfill is for each user and\n * index.\n */\nexport interface DbIndexState {\n /** The index id for this entry. */\n indexId: number;\n /** The user id for this entry. */\n uid: string;\n /**\n * A number that indicates when the index was last updated (relative to\n * other indexes).\n */\n sequenceNumber: number;\n /**\n * The latest read time that has been indexed by Firestore for this field\n * index. Set to `{seconds: 0, nanos: 0}` if no documents have been indexed.\n */\n readTime: DbTimestamp;\n /**\n * The last document that has been indexed for this field index. Empty if\n * no documents have been indexed.\n */\n documentKey: EncodedResourcePath;\n /**\n * The largest mutation batch id that has been processed for this index. -1\n * if no mutations have been indexed.\n */\n largestBatchId: number;\n}\n\n/** An object that stores the encoded entries for all documents and fields. */\nexport interface DbIndexEntry {\n // TODO(indexing): Consider just storing `orderedDocumentKey` and decoding\n // the ordered key into a document key. This would reduce storage space on\n // disk but require us to port parts of OrderedCodeReader.\n\n /** The index id for this entry. */\n indexId: number;\n /** The user id for this entry. */\n uid: string;\n /** The encoded array index value for this entry. */\n arrayValue: KeySafeBytes;\n /** The encoded directional value for equality and inequality filters. */\n directionalValue: KeySafeBytes;\n /**\n * The document key this entry points to. This entry is encoded by an ordered\n * encoder to match the key order of the index.\n */\n orderedDocumentKey: KeySafeBytes;\n /** The segments of the document key this entry points to. */\n documentKey: string[];\n}\n\n/**\n * An object representing a document overlay.\n */\nexport interface DbDocumentOverlay {\n /** The user ID to whom this overlay belongs. */\n userId: string;\n /** The path to the collection that contains the document. */\n collectionPath: string;\n /** The ID (key) of the document within the collection. */\n documentId: string;\n /** The collection group to which the document belongs. */\n collectionGroup: string;\n /** The largest batch ID that's been applied for this overlay. */\n largestBatchId: number;\n /** The overlay mutation. */\n overlayMutation: ProtoWrite;\n}\n\n/**\n * An object containing global name/value pair.\n */\nexport interface DbGlobals {\n /** Name is a globally unique identifier for a value. */\n name: string;\n /** Value is a general purpose storage for global data. */\n value: Uint8Array;\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(\n batch !== null,\n 0x90f9,\n 'Attempt to reject nonexistent batch!'\n );\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 0xbd9d,\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 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { BatchId, MutationBatchState, TargetId } from '../core/types';\nimport { debugAssert } from '../util/assert';\n\nimport { ClientId } from './shared_client_state';\nimport { QueryTargetState } from './shared_client_state_syncer';\n\n// The format of the LocalStorage key that stores the client state is:\n// firestore_clients__\nexport const CLIENT_STATE_KEY_PREFIX = 'firestore_clients';\n\n/** Assembles the key for a client state in WebStorage */\nexport function createWebStorageClientStateKey(\n persistenceKey: string,\n clientId: ClientId\n): string {\n debugAssert(\n clientId.indexOf('_') === -1,\n `Client key cannot contain '_', but was '${clientId}'`\n );\n\n return `${CLIENT_STATE_KEY_PREFIX}_${persistenceKey}_${clientId}`;\n}\n\n/**\n * The JSON representation of a clients's metadata as used during WebStorage\n * serialization. The ClientId is omitted here as it is encoded as part of the\n * key.\n */\nexport interface ClientStateSchema {\n activeTargetIds: number[];\n updateTimeMs: number;\n}\n\n// The format of the WebStorage key that stores the mutation state is:\n// firestore_mutations__\n// (for unauthenticated users)\n// or: firestore_mutations___\n//\n// 'user_uid' is last to avoid needing to escape '_' characters that it might\n// contain.\nexport const MUTATION_BATCH_KEY_PREFIX = 'firestore_mutations';\n\n/** Assembles the key for a mutation batch in WebStorage */\nexport function createWebStorageMutationBatchKey(\n persistenceKey: string,\n user: User,\n batchId: BatchId\n): string {\n let mutationKey = `${MUTATION_BATCH_KEY_PREFIX}_${persistenceKey}_${batchId}`;\n\n if (user.isAuthenticated()) {\n mutationKey += `_${user.uid}`;\n }\n\n return mutationKey;\n}\n\n/**\n * The JSON representation of a mutation batch's metadata as used during\n * WebStorage serialization. The UserId and BatchId is omitted as it is\n * encoded as part of the key.\n */\nexport interface MutationMetadataSchema {\n state: MutationBatchState;\n error?: { code: string; message: string }; // Only set when state === 'rejected'\n updateTimeMs: number;\n}\n\n// The format of the WebStorage key that stores a query target's metadata is:\n// firestore_targets__\nexport const QUERY_TARGET_KEY_PREFIX = 'firestore_targets';\n\n/** Assembles the key for a query state in WebStorage */\nexport function createWebStorageQueryTargetMetadataKey(\n persistenceKey: string,\n targetId: TargetId\n): string {\n return `${QUERY_TARGET_KEY_PREFIX}_${persistenceKey}_${targetId}`;\n}\n\n/**\n * The JSON representation of a query target's state as used during WebStorage\n * serialization. The TargetId is omitted as it is encoded as part of the key.\n */\nexport interface QueryTargetStateSchema {\n state: QueryTargetState;\n error?: { code: string; message: string }; // Only set when state === 'rejected'\n updateTimeMs: number;\n}\n\n// The WebStorage prefix that stores the primary tab's online state. The\n// format of the key is:\n// firestore_online_state_\nexport const ONLINE_STATE_KEY_PREFIX = 'firestore_online_state';\n\n/** Assembles the key for the online state of the primary tab. */\nexport function createWebStorageOnlineStateKey(persistenceKey: string): string {\n return `${ONLINE_STATE_KEY_PREFIX}_${persistenceKey}`;\n}\n\n// The WebStorage prefix that plays as a event to indicate the remote documents\n// might have changed due to some secondary tabs loading a bundle.\n// format of the key is:\n// firestore_bundle_loaded_v2_\n// The version ending with \"v2\" stores the list of modified collection groups.\nexport const BUNDLE_LOADED_KEY_PREFIX = 'firestore_bundle_loaded_v2';\nexport function createBundleLoadedKey(persistenceKey: string): string {\n return `${BUNDLE_LOADED_KEY_PREFIX}_${persistenceKey}`;\n}\n\n/**\n * The JSON representation of the system's online state, as written by the\n * primary client.\n */\nexport interface SharedOnlineStateSchema {\n /**\n * The clientId of the client that wrote this onlineState value. Tracked so\n * that on startup, clients can check if this client is still active when\n * determining whether to apply this value or not.\n */\n readonly clientId: string;\n readonly onlineState: string;\n}\n\n// The WebStorage key prefix for the key that stores the last sequence number allocated. The key\n// looks like 'firestore_sequence_number_'.\nexport const SEQUENCE_NUMBER_KEY_PREFIX = 'firestore_sequence_number';\n\n/** Assembles the key for the current sequence number. */\nexport function createWebStorageSequenceNumberKey(\n persistenceKey: string\n): string {\n return `${SEQUENCE_NUMBER_KEY_PREFIX}_${persistenceKey}`;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { ListenSequence } from '../core/listen_sequence';\nimport {\n BatchId,\n ListenSequenceNumber,\n MutationBatchState,\n OnlineState,\n TargetId\n} from '../core/types';\nimport { TargetIdSet, targetIdSet } from '../model/collections';\nimport { hardAssert, debugAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logError, logDebug } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport { isSafeInteger, WindowLike } from '../util/types';\n\nimport {\n CLIENT_STATE_KEY_PREFIX,\n ClientStateSchema,\n createBundleLoadedKey,\n createWebStorageClientStateKey,\n createWebStorageMutationBatchKey,\n createWebStorageOnlineStateKey,\n createWebStorageQueryTargetMetadataKey,\n createWebStorageSequenceNumberKey,\n MUTATION_BATCH_KEY_PREFIX,\n MutationMetadataSchema,\n QUERY_TARGET_KEY_PREFIX,\n QueryTargetStateSchema,\n SharedOnlineStateSchema\n} from './shared_client_state_schema';\nimport {\n QueryTargetState,\n SharedClientStateSyncer\n} from './shared_client_state_syncer';\n\nconst LOG_TAG = 'SharedClientState';\n\n/**\n * A randomly-generated key assigned to each Firestore instance at startup.\n */\nexport type ClientId = string;\n\n/**\n * A `SharedClientState` keeps track of the global state of the mutations\n * and query targets for all active clients with the same persistence key (i.e.\n * project ID and FirebaseApp name). It relays local changes to other clients\n * and updates its local state as new state is observed.\n *\n * `SharedClientState` is primarily used for synchronization in Multi-Tab\n * environments. Each tab is responsible for registering its active query\n * targets and mutations. `SharedClientState` will then notify the listener\n * assigned to `.syncEngine` for updates to mutations and queries that\n * originated in other clients.\n *\n * To receive notifications, `.syncEngine` and `.onlineStateHandler` has to be\n * assigned before calling `start()`.\n */\nexport interface SharedClientState {\n onlineStateHandler: ((onlineState: OnlineState) => void) | null;\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null;\n\n /** Registers the Mutation Batch ID of a newly pending mutation. */\n addPendingMutation(batchId: BatchId): void;\n\n /**\n * Records that a pending mutation has been acknowledged or rejected.\n * Called by the primary client to notify secondary clients of mutation\n * results as they come back from the backend.\n */\n updateMutationState(\n batchId: BatchId,\n state: 'acknowledged' | 'rejected',\n error?: FirestoreError\n ): void;\n\n /**\n * Associates a new Query Target ID with the local Firestore client. Returns\n * the new query state for the query (which can be 'current' if the query is\n * already associated with another tab).\n *\n * If the target id is already associated with local client, the method simply\n * returns its `QueryTargetState`.\n */\n addLocalQueryTarget(\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 0x77ac,\n 'Found non-numeric sequence number',\n { seqString }\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 { isCloudWorkstation } from '@firebase/util';\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 const { host } = new URL(url);\n const forwardCredentials = isCloudWorkstation(host);\n return this.performRPCRequest(\n rpcName,\n url,\n headers,\n req,\n forwardCredentials\n ).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 _forwardCredentials: boolean\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 /** A collection of open WebChannel instances */\n private openWebChannels: WebChannel[] = [];\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 _forwardCredentials: boolean\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 0x235f,\n 'RPC failed with unanticipated webchannel error. Giving up.',\n {\n rpcName,\n streamId,\n lastErrorCode: xhr.getLastErrorCode(),\n lastError: xhr.getLastError()\n }\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 this.addOpenWebChannel(channel);\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 this.removeOpenWebChannel(channel);\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. Name:`,\n err.name,\n 'Message:',\n err.message\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(\n !!msgData,\n 0x3fdd,\n 'Got a webchannel message without data.'\n );\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 as WebChannelError)?.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 * Closes and cleans up any resources associated with the connection.\n */\n terminate(): void {\n // If the Firestore instance is terminated, we will explicitly\n // close any remaining open WebChannel instances.\n this.openWebChannels.forEach(webChannel => webChannel.close());\n this.openWebChannels = [];\n }\n\n /**\n * Add a WebChannel instance to the collection of open instances.\n * @param webChannel\n */\n addOpenWebChannel(webChannel: WebChannel): void {\n this.openWebChannels.push(webChannel);\n }\n\n /**\n * Remove a WebChannel instance from the collection of open instances.\n * @param webChannel\n */\n removeOpenWebChannel(webChannel: WebChannel): void {\n this.openWebChannels = this.openWebChannels.filter(\n instance => instance === webChannel\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/** 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 0x7a5a,\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 0xda08,\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 0x3186,\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, 0xd7c2, 'Missing entity in write response for `key`', {\n key\n });\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 0xfcd7,\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 0xf76d,\n 'unsupported combination of changes: `change` after `oldChange`',\n {\n change,\n oldChange\n }\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n BundleElement,\n BundleMetadata\n} from '../protos/firestore_bundle_proto';\nimport { JsonProtoSerializer } from '../remote/serializer';\n\n/**\n * A complete element in the bundle stream, together with the byte length it\n * occupies in the stream.\n */\nexport class SizedBundleElement {\n constructor(\n public readonly payload: BundleElement,\n // How many bytes this element takes to store in the bundle.\n public readonly byteLength: number\n ) {}\n\n isBundleMetadata(): boolean {\n return 'metadata' in this.payload;\n }\n}\n\nexport type BundleSource =\n | ReadableStream\n | ArrayBuffer\n | Uint8Array;\n\n/**\n * A class representing a bundle.\n *\n * Takes a bundle stream or buffer, and presents abstractions to read bundled\n * elements out of the underlying content.\n */\nexport interface BundleReader {\n serializer: JsonProtoSerializer;\n\n close(): Promise;\n\n /**\n * Returns the metadata of the bundle.\n */\n getMetadata(): Promise;\n\n /**\n * Returns the next BundleElement (together with its byte size in the bundle)\n * that has not been read from underlying ReadableStream. Returns null if we\n * have reached the end of the stream.\n */\n nextElement(): Promise;\n}\n\n/**\n * A class representing a synchronized bundle reader.\n *\n * Takes a bundle string buffer, parses the data, and provides accessors to the data contained\n * within it.\n */\nexport interface BundleReaderSync {\n serializer: JsonProtoSerializer;\n\n /**\n * Returns the metadata of the bundle.\n */\n getMetadata(): BundleMetadata;\n\n /**\n * Returns BundleElements parsed from the bundle. Returns an empty array if no bundle elements\n * exist.\n */\n getElements(): SizedBundleElement[];\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LoadBundleTaskProgress } from '@firebase/firestore-types';\n\nimport { LocalStore } from '../local/local_store';\nimport {\n localStoreApplyBundledDocuments,\n localStoreSaveNamedQuery\n} from '../local/local_store_impl';\nimport { documentKeySet, DocumentKeySet } from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport {\n BundleMetadata as ProtoBundleMetadata,\n NamedQuery as ProtoNamedQuery\n} from '../protos/firestore_bundle_proto';\nimport { Timestamp as ApiTimestamp } from '../protos/firestore_proto_api';\nimport {\n fromDocument,\n fromName,\n fromVersion,\n JsonProtoSerializer\n} from '../remote/serializer';\nimport { debugAssert } from '../util/assert';\nimport { SizedBundleElement } from '../util/bundle_reader';\n\nimport {\n BundleConverter,\n BundledDocument,\n BundledDocuments,\n BundleLoadResult\n} from './bundle';\nimport { SnapshotVersion } from './snapshot_version';\n\n/**\n * Helper to convert objects from bundles to model objects in the SDK.\n */\nexport class BundleConverterImpl implements BundleConverter {\n constructor(private readonly serializer: JsonProtoSerializer) {}\n\n toDocumentKey(name: string): DocumentKey {\n return fromName(this.serializer, name);\n }\n\n /**\n * Converts a BundleDocument to a MutableDocument.\n */\n toMutableDocument(bundledDoc: BundledDocument): MutableDocument {\n if (bundledDoc.metadata.exists) {\n debugAssert(\n !!bundledDoc.document,\n 'Document is undefined when metadata.exist is true.'\n );\n return fromDocument(this.serializer, bundledDoc.document!, false);\n } else {\n return MutableDocument.newNoDocument(\n this.toDocumentKey(bundledDoc.metadata.name!),\n this.toSnapshotVersion(bundledDoc.metadata.readTime!)\n );\n }\n }\n\n toSnapshotVersion(time: ApiTimestamp): SnapshotVersion {\n return fromVersion(time);\n }\n}\n\n/**\n * A class to process the elements from a bundle, and optionally load them into local\n * storage and provide progress update while loading.\n */\nexport class BundleLoader {\n /** The current progress of loading */\n private progress: LoadBundleTaskProgress;\n /** Batched queries to be saved into storage */\n private _queries: ProtoNamedQuery[] = [];\n /** Batched documents to be saved into storage */\n private _documents: BundledDocuments = [];\n /** The collection groups affected by this bundle. */\n private collectionGroups = new Set();\n\n constructor(\n private bundleMetadata: ProtoBundleMetadata,\n private serializer: JsonProtoSerializer\n ) {\n this.progress = bundleInitialProgress(bundleMetadata);\n }\n\n /**\n * Returns the named queries that have been parsed from the SizeBundleElements added by\n * calling {@link adSizedElement}.\n */\n get queries(): ProtoNamedQuery[] {\n return this._queries;\n }\n\n /**\n * Returns the BundledDocuments that have been parsed from the SizeBundleElements added by\n * calling {@link addSizedElement}.\n */\n get documents(): BundledDocuments {\n return this._documents;\n }\n\n /**\n * Adds an element from the bundle to the loader.\n *\n * Returns a new progress if adding the element leads to a new progress,\n * otherwise returns null.\n */\n addSizedElement(element: SizedBundleElement): LoadBundleTaskProgress | null {\n debugAssert(!element.isBundleMetadata(), 'Unexpected bundle metadata.');\n\n this.progress.bytesLoaded += element.byteLength;\n\n let documentsLoaded = this.progress.documentsLoaded;\n\n if (element.payload.namedQuery) {\n this._queries.push(element.payload.namedQuery);\n } else if (element.payload.documentMetadata) {\n this._documents.push({ metadata: element.payload.documentMetadata });\n if (!element.payload.documentMetadata.exists) {\n ++documentsLoaded;\n }\n const path = ResourcePath.fromString(\n element.payload.documentMetadata.name!\n );\n debugAssert(\n path.length >= 2,\n 'The document name does not point to a document.'\n );\n this.collectionGroups.add(path.get(path.length - 2));\n } else if (element.payload.document) {\n debugAssert(\n this._documents.length > 0 &&\n this._documents[this._documents.length - 1].metadata.name ===\n element.payload.document.name,\n 'The document being added does not match the stored metadata.'\n );\n this._documents[this._documents.length - 1].document =\n element.payload.document;\n ++documentsLoaded;\n }\n\n if (documentsLoaded !== this.progress.documentsLoaded) {\n this.progress.documentsLoaded = documentsLoaded;\n return { ...this.progress };\n }\n\n return null;\n }\n\n private getQueryDocumentMapping(\n documents: BundledDocuments\n ): Map {\n const queryDocumentMap = new Map();\n const bundleConverter = new BundleConverterImpl(this.serializer);\n for (const bundleDoc of documents) {\n if (bundleDoc.metadata.queries) {\n const documentKey = bundleConverter.toDocumentKey(\n bundleDoc.metadata.name!\n );\n for (const queryName of bundleDoc.metadata.queries) {\n const documentKeys = (\n queryDocumentMap.get(queryName) || documentKeySet()\n ).add(documentKey);\n queryDocumentMap.set(queryName, documentKeys);\n }\n }\n }\n\n return queryDocumentMap;\n }\n\n /**\n * Update the progress to 'Success' and return the updated progress.\n */\n async completeAndStoreAsync(\n localStore: LocalStore\n ): Promise {\n debugAssert(\n this._documents[this._documents.length - 1]?.metadata.exists !== true ||\n !!this._documents[this._documents.length - 1].document,\n 'Bundled documents end with a document metadata element instead of a document.'\n );\n debugAssert(!!this.bundleMetadata.id, 'Bundle ID must be set.');\n\n const changedDocs = await localStoreApplyBundledDocuments(\n localStore,\n new BundleConverterImpl(this.serializer),\n this._documents,\n this.bundleMetadata.id!\n );\n\n const queryDocumentMap = this.getQueryDocumentMapping(this.documents);\n\n for (const q of this._queries) {\n await localStoreSaveNamedQuery(\n localStore,\n q,\n queryDocumentMap.get(q.name!)\n );\n }\n\n this.progress.taskState = 'Success';\n return {\n progress: this.progress,\n changedCollectionGroups: this.collectionGroups,\n changedDocs\n };\n }\n}\n\n/**\n * Returns a `LoadBundleTaskProgress` representing the initial progress of\n * loading a bundle.\n */\nexport function bundleInitialProgress(\n metadata: ProtoBundleMetadata\n): LoadBundleTaskProgress {\n return {\n taskState: 'Running',\n documentsLoaded: 0,\n bytesLoaded: 0,\n totalDocuments: metadata.totalDocuments!,\n totalBytes: metadata.totalBytes!\n };\n}\n\n/**\n * Returns a `LoadBundleTaskProgress` representing the progress that the loading\n * has succeeded.\n */\nexport function bundleSuccessProgress(\n metadata: ProtoBundleMetadata\n): LoadBundleTaskProgress {\n return {\n taskState: 'Success',\n documentsLoaded: metadata.totalDocuments!,\n bytesLoaded: metadata.totalBytes!,\n totalDocuments: metadata.totalDocuments!,\n totalBytes: metadata.totalBytes!\n };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { QueryResult } from '../local/local_store_impl';\nimport {\n documentKeySet,\n DocumentKeySet,\n DocumentMap\n} from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { DocumentSet } from '../model/document_set';\nimport { TargetChange } from '../remote/remote_event';\nimport { debugAssert, fail } from '../util/assert';\n\nimport { LimitType, newQueryComparator, Query, queryMatches } from './query';\nimport { OnlineState } from './types';\nimport {\n ChangeType,\n DocumentChangeSet,\n SyncState,\n ViewSnapshot\n} from './view_snapshot';\n\nexport type LimboDocumentChange = AddedLimboDocument | RemovedLimboDocument;\nexport class AddedLimboDocument {\n constructor(public key: DocumentKey) {}\n}\nexport class RemovedLimboDocument {\n constructor(public key: DocumentKey) {}\n}\n\n/** The result of applying a set of doc changes to a view. */\nexport interface ViewDocumentChanges {\n /** The new set of docs that should be in the view. */\n documentSet: DocumentSet;\n /** The diff of these docs with the previous set of docs. */\n changeSet: DocumentChangeSet;\n /**\n * Whether the set of documents passed in was not sufficient to calculate the\n * new state of the view and there needs to be another pass based on the\n * local cache.\n */\n needsRefill: boolean;\n\n mutatedKeys: DocumentKeySet;\n}\n\nexport interface ViewChange {\n snapshot?: ViewSnapshot;\n limboChanges: LimboDocumentChange[];\n}\n\n/**\n * View is responsible for computing the final merged truth of what docs are in\n * a query. It gets notified of local and remote changes to docs, and applies\n * the query filters and limits to determine the most correct possible results.\n */\nexport class View {\n private syncState: SyncState | null = null;\n private hasCachedResults: boolean = false;\n /**\n * A flag whether the view is current with the backend. A view is considered\n * current after it has seen the current flag from the backend and did not\n * lose consistency within the watch stream (e.g. because of an existence\n * filter mismatch).\n */\n private current = false;\n private documentSet: DocumentSet;\n /** Documents in the view but not in the remote target */\n private limboDocuments = documentKeySet();\n /** Document Keys that have local changes */\n private mutatedKeys = documentKeySet();\n /** Query comparator that defines the document order in this view. */\n private docComparator: (d1: Document, d2: Document) => number;\n\n constructor(\n private query: Query,\n /** Documents included in the remote target */\n private _syncedDocuments: DocumentKeySet\n ) {\n this.docComparator = newQueryComparator(query);\n this.documentSet = new DocumentSet(this.docComparator);\n }\n\n /**\n * The set of remote documents that the server has told us belongs to the target associated with\n * this view.\n */\n get syncedDocuments(): DocumentKeySet {\n return this._syncedDocuments;\n }\n\n /**\n * Iterates over a set of doc changes, applies the query limit, and computes\n * what the new results should be, what the changes were, and whether we may\n * need to go back to the local cache for more results. Does not make any\n * changes to the view.\n * @param docChanges - The doc changes to apply to this view.\n * @param previousChanges - If this is being called with a refill, then start\n * with this set of docs and changes instead of the current view.\n * @returns a new set of docs, changes, and refill flag.\n */\n computeDocChanges(\n docChanges: DocumentMap,\n previousChanges?: ViewDocumentChanges\n ): ViewDocumentChanges {\n const changeSet = previousChanges\n ? previousChanges.changeSet\n : new DocumentChangeSet();\n const oldDocumentSet = previousChanges\n ? previousChanges.documentSet\n : this.documentSet;\n let newMutatedKeys = previousChanges\n ? previousChanges.mutatedKeys\n : this.mutatedKeys;\n let newDocumentSet = oldDocumentSet;\n let needsRefill = false;\n\n // Track the last doc in a (full) limit. This is necessary, because some\n // update (a delete, or an update moving a doc past the old limit) might\n // mean there is some other document in the local cache that either should\n // come (1) between the old last limit doc and the new last document, in the\n // case of updates, or (2) after the new last document, in the case of\n // deletes. So we keep this doc at the old limit to compare the updates to.\n //\n // Note that this should never get used in a refill (when previousChanges is\n // set), because there will only be adds -- no deletes or updates.\n const lastDocInLimit =\n this.query.limitType === LimitType.First &&\n oldDocumentSet.size === this.query.limit\n ? oldDocumentSet.last()\n : null;\n const firstDocInLimit =\n this.query.limitType === LimitType.Last &&\n oldDocumentSet.size === this.query.limit\n ? oldDocumentSet.first()\n : null;\n\n docChanges.inorderTraversal((key, entry) => {\n const oldDoc = oldDocumentSet.get(key);\n const newDoc = queryMatches(this.query, entry) ? entry : null;\n\n const oldDocHadPendingMutations = oldDoc\n ? this.mutatedKeys.has(oldDoc.key)\n : false;\n const newDocHasPendingMutations = newDoc\n ? newDoc.hasLocalMutations ||\n // We only consider committed mutations for documents that were\n // mutated during the lifetime of the view.\n (this.mutatedKeys.has(newDoc.key) && newDoc.hasCommittedMutations)\n : false;\n\n let changeApplied = false;\n\n // Calculate change\n if (oldDoc && newDoc) {\n const docsEqual = oldDoc.data.isEqual(newDoc.data);\n if (!docsEqual) {\n if (!this.shouldWaitForSyncedDocument(oldDoc, newDoc)) {\n changeSet.track({\n type: ChangeType.Modified,\n doc: newDoc\n });\n changeApplied = true;\n\n if (\n (lastDocInLimit &&\n this.docComparator(newDoc, lastDocInLimit) > 0) ||\n (firstDocInLimit &&\n this.docComparator(newDoc, firstDocInLimit) < 0)\n ) {\n // This doc moved from inside the limit to outside the limit.\n // That means there may be some other doc in the local cache\n // that should be included instead.\n needsRefill = true;\n }\n }\n } else if (oldDocHadPendingMutations !== newDocHasPendingMutations) {\n changeSet.track({ type: ChangeType.Metadata, doc: newDoc });\n changeApplied = true;\n }\n } else if (!oldDoc && newDoc) {\n changeSet.track({ type: ChangeType.Added, doc: newDoc });\n changeApplied = true;\n } else if (oldDoc && !newDoc) {\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc });\n changeApplied = true;\n\n if (lastDocInLimit || firstDocInLimit) {\n // A doc was removed from a full limit query. We'll need to\n // requery from the local cache to see if we know about some other\n // doc that should be in the results.\n needsRefill = true;\n }\n }\n\n if (changeApplied) {\n if (newDoc) {\n newDocumentSet = newDocumentSet.add(newDoc);\n if (newDocHasPendingMutations) {\n newMutatedKeys = newMutatedKeys.add(key);\n } else {\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n } else {\n newDocumentSet = newDocumentSet.delete(key);\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n }\n });\n\n // Drop documents out to meet limit/limitToLast requirement.\n if (this.query.limit !== null) {\n while (newDocumentSet.size > this.query.limit!) {\n const oldDoc =\n this.query.limitType === LimitType.First\n ? newDocumentSet.last()\n : newDocumentSet.first();\n newDocumentSet = newDocumentSet.delete(oldDoc!.key);\n newMutatedKeys = newMutatedKeys.delete(oldDoc!.key);\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc! });\n }\n }\n\n debugAssert(\n !needsRefill || !previousChanges,\n 'View was refilled using docs that themselves needed refilling.'\n );\n return {\n documentSet: newDocumentSet,\n changeSet,\n needsRefill,\n mutatedKeys: newMutatedKeys\n };\n }\n\n private shouldWaitForSyncedDocument(\n oldDoc: Document,\n newDoc: Document\n ): boolean {\n // We suppress the initial change event for documents that were modified as\n // part of a write acknowledgment (e.g. when the value of a server transform\n // is applied) as Watch will send us the same document again.\n // By suppressing the event, we only raise two user visible events (one with\n // `hasPendingWrites` and the final state of the document) instead of three\n // (one with `hasPendingWrites`, the modified document with\n // `hasPendingWrites` and the final state of the document).\n return (\n oldDoc.hasLocalMutations &&\n newDoc.hasCommittedMutations &&\n !newDoc.hasLocalMutations\n );\n }\n\n /**\n * Updates the view with the given ViewDocumentChanges and optionally updates\n * limbo docs and sync state from the provided target change.\n * @param docChanges - The set of changes to make to the view's docs.\n * @param limboResolutionEnabled - Whether to update limbo documents based on\n * this change.\n * @param targetChange - A target change to apply for computing limbo docs and\n * sync state.\n * @param targetIsPendingReset - Whether the target is pending to reset due to\n * existence filter mismatch. If not explicitly specified, it is treated\n * equivalently to `false`.\n * @returns A new ViewChange with the given docs, changes, and sync state.\n */\n // PORTING NOTE: The iOS/Android clients always compute limbo document changes.\n applyChanges(\n docChanges: ViewDocumentChanges,\n limboResolutionEnabled: boolean,\n targetChange?: TargetChange,\n targetIsPendingReset?: boolean\n ): ViewChange {\n debugAssert(\n !docChanges.needsRefill,\n 'Cannot apply changes that need a refill'\n );\n const oldDocs = this.documentSet;\n this.documentSet = docChanges.documentSet;\n this.mutatedKeys = docChanges.mutatedKeys;\n // Sort changes based on type and query comparator\n const changes = docChanges.changeSet.getChanges();\n changes.sort((c1, c2) => {\n return (\n compareChangeType(c1.type, c2.type) ||\n this.docComparator(c1.doc, c2.doc)\n );\n });\n\n this.applyTargetChange(targetChange);\n\n targetIsPendingReset = targetIsPendingReset ?? false;\n const limboChanges =\n limboResolutionEnabled && !targetIsPendingReset\n ? this.updateLimboDocuments()\n : [];\n\n // We are at synced state if there is no limbo docs are waiting to be resolved, view is current\n // with the backend, and the query is not pending to reset due to existence filter mismatch.\n const synced =\n this.limboDocuments.size === 0 && this.current && !targetIsPendingReset;\n\n const newSyncState = synced ? SyncState.Synced : SyncState.Local;\n const syncStateChanged = newSyncState !== this.syncState;\n this.syncState = newSyncState;\n\n if (changes.length === 0 && !syncStateChanged) {\n // no changes\n return { limboChanges };\n } else {\n const snap: ViewSnapshot = new ViewSnapshot(\n this.query,\n docChanges.documentSet,\n oldDocs,\n changes,\n docChanges.mutatedKeys,\n newSyncState === SyncState.Local,\n syncStateChanged,\n /* excludesMetadataChanges= */ false,\n targetChange\n ? targetChange.resumeToken.approximateByteSize() > 0\n : false\n );\n return {\n snapshot: snap,\n limboChanges\n };\n }\n }\n\n /**\n * Applies an OnlineState change to the view, potentially generating a\n * ViewChange if the view's syncState changes as a result.\n */\n applyOnlineStateChange(onlineState: OnlineState): ViewChange {\n if (this.current && onlineState === OnlineState.Offline) {\n // If we're offline, set `current` to false and then call applyChanges()\n // to refresh our syncState and generate a ViewChange as appropriate. We\n // are guaranteed to get a new TargetChange that sets `current` back to\n // true once the client is back online.\n this.current = false;\n return this.applyChanges(\n {\n documentSet: this.documentSet,\n changeSet: new DocumentChangeSet(),\n mutatedKeys: this.mutatedKeys,\n needsRefill: false\n },\n /* limboResolutionEnabled= */ false\n );\n } else {\n // No effect, just return a no-op ViewChange.\n return { limboChanges: [] };\n }\n }\n\n /**\n * Returns whether the doc for the given key should be in limbo.\n */\n private shouldBeInLimbo(key: DocumentKey): boolean {\n // If the remote end says it's part of this query, it's not in limbo.\n if (this._syncedDocuments.has(key)) {\n return false;\n }\n // The local store doesn't think it's a result, so it shouldn't be in limbo.\n if (!this.documentSet.has(key)) {\n return false;\n }\n // If there are local changes to the doc, they might explain why the server\n // doesn't know that it's part of the query. So don't put it in limbo.\n // TODO(klimt): Ideally, we would only consider changes that might actually\n // affect this specific query.\n if (this.documentSet.get(key)!.hasLocalMutations) {\n return false;\n }\n // Everything else is in limbo.\n return true;\n }\n\n /**\n * Updates syncedDocuments, current, and limbo docs based on the given change.\n * Returns the list of changes to which docs are in limbo.\n */\n private applyTargetChange(targetChange?: TargetChange): void {\n if (targetChange) {\n targetChange.addedDocuments.forEach(\n key => (this._syncedDocuments = this._syncedDocuments.add(key))\n );\n targetChange.modifiedDocuments.forEach(key => {\n debugAssert(\n this._syncedDocuments.has(key),\n `Modified document ${key} not found in view.`\n );\n });\n targetChange.removedDocuments.forEach(\n key => (this._syncedDocuments = this._syncedDocuments.delete(key))\n );\n this.current = targetChange.current;\n }\n }\n\n private updateLimboDocuments(): LimboDocumentChange[] {\n // We can only determine limbo documents when we're in-sync with the server.\n if (!this.current) {\n return [];\n }\n\n // TODO(klimt): Do this incrementally so that it's not quadratic when\n // updating many documents.\n const oldLimboDocuments = this.limboDocuments;\n this.limboDocuments = documentKeySet();\n this.documentSet.forEach(doc => {\n if (this.shouldBeInLimbo(doc.key)) {\n this.limboDocuments = this.limboDocuments.add(doc.key);\n }\n });\n\n // Diff the new limbo docs with the old limbo docs.\n const changes: LimboDocumentChange[] = [];\n oldLimboDocuments.forEach(key => {\n if (!this.limboDocuments.has(key)) {\n changes.push(new RemovedLimboDocument(key));\n }\n });\n this.limboDocuments.forEach(key => {\n if (!oldLimboDocuments.has(key)) {\n changes.push(new AddedLimboDocument(key));\n }\n });\n return changes;\n }\n\n /**\n * Update the in-memory state of the current view with the state read from\n * persistence.\n *\n * We update the query view whenever a client's primary status changes:\n * - When a client transitions from primary to secondary, it can miss\n * LocalStorage updates and its query views may temporarily not be\n * synchronized with the state on disk.\n * - For secondary to primary transitions, the client needs to update the list\n * of `syncedDocuments` since secondary clients update their query views\n * based purely on synthesized RemoteEvents.\n *\n * @param queryResult.documents - The documents that match the query according\n * to the LocalStore.\n * @param queryResult.remoteKeys - The keys of the documents that match the\n * query according to the backend.\n *\n * @returns The ViewChange that resulted from this synchronization.\n */\n // PORTING NOTE: Multi-tab only.\n synchronizeWithPersistedState(queryResult: QueryResult): ViewChange {\n this._syncedDocuments = queryResult.remoteKeys;\n this.limboDocuments = documentKeySet();\n const docChanges = this.computeDocChanges(queryResult.documents);\n return this.applyChanges(docChanges, /* limboResolutionEnabled= */ true);\n }\n\n /**\n * Returns a view snapshot as if this query was just listened to. Contains\n * a document add for every existing document and the `fromCache` and\n * `hasPendingWrites` status of the already established view.\n */\n // PORTING NOTE: Multi-tab only.\n computeInitialSnapshot(): ViewSnapshot {\n return ViewSnapshot.fromInitialDocuments(\n this.query,\n this.documentSet,\n this.mutatedKeys,\n this.syncState === SyncState.Local,\n this.hasCachedResults\n );\n }\n}\n\nfunction compareChangeType(c1: ChangeType, c2: ChangeType): number {\n const order = (change: ChangeType): 0 | 1 | 2 => {\n switch (change) {\n case ChangeType.Added:\n return 1;\n case ChangeType.Modified:\n return 2;\n case ChangeType.Metadata:\n // A metadata change is converted to a modified change at the public\n // api layer. Since we sort by document key and then change type,\n // metadata and modified changes must be sorted equivalently.\n return 2;\n case ChangeType.Removed:\n return 0;\n default:\n return fail(0x4f35, '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 0x5858,\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 0x390f,\n 'Received change for limbo target document without add.'\n );\n } else if (targetChange.removedDocuments.size > 0) {\n hardAssert(\n limboResolution.receivedDocument,\n 0xa4f3,\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(0x4d4f, 'Unknown limbo change', { 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(0x1a40, `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(0xfa9b, '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(metadata, reader.serializer);\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.completeAndStoreAsync(syncEngine.localStore);\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 0xb743,\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from './assert';\n\n/**\n * How many bytes to read each time when `ReadableStreamReader.read()` is\n * called. Only applicable for byte streams that we control (e.g. those backed\n * by an UInt8Array).\n */\nexport const DEFAULT_BYTES_PER_READ = 10240;\n\n/**\n * Builds a `ByteStreamReader` from a UInt8Array.\n * @param source - The data source to use.\n * @param bytesPerRead - How many bytes each `read()` from the returned reader\n * will read.\n */\nexport function toByteStreamReaderHelper(\n source: Uint8Array,\n bytesPerRead: number = DEFAULT_BYTES_PER_READ\n): ReadableStreamDefaultReader {\n debugAssert(\n bytesPerRead > 0,\n `toByteStreamReader expects positive bytesPerRead, but got ${bytesPerRead}`\n );\n let readFrom = 0;\n // The TypeScript definition for ReadableStreamReader changed. We use\n // `any` here to allow this code to compile with different versions.\n // See https://github.com/microsoft/TypeScript/issues/42970\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const reader: any = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async read(): Promise {\n if (readFrom < source.byteLength) {\n const result = {\n value: source.slice(readFrom, readFrom + bytesPerRead),\n done: false\n } as const;\n readFrom += bytesPerRead;\n return result;\n }\n\n return { done: true };\n },\n async cancel(): Promise {},\n releaseLock() {},\n closed: Promise.resolve()\n };\n return reader;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Observer } from '../core/event_manager';\n\nimport { FirestoreError } from './error';\nimport { logError } from './log';\nimport { EventHandler } from './misc';\n\n/*\n * A wrapper implementation of Observer 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { newTextDecoder } from '../platform/text_serializer';\nimport { BundleMetadata } from '../protos/firestore_bundle_proto';\nimport { JsonProtoSerializer } from '../remote/serializer';\n\nimport { debugAssert } from './assert';\nimport { BundleReader, SizedBundleElement } from './bundle_reader';\nimport { Deferred } from './promise';\n\n/**\n * A class representing a bundle.\n *\n * Takes a bundle stream or buffer, and presents abstractions to read bundled\n * elements out of the underlying content.\n */\nclass BundleReaderImpl implements BundleReader {\n /** Cached bundle metadata. */\n private metadata: Deferred = new Deferred();\n /**\n * Internal buffer to hold bundle content, accumulating incomplete element\n * content.\n */\n private buffer: Uint8Array = new Uint8Array();\n /** The decoder used to parse binary data into strings. */\n private textDecoder: TextDecoder;\n\n constructor(\n /** The reader to read from underlying binary bundle data source. */\n private reader: ReadableStreamDefaultReader,\n readonly serializer: JsonProtoSerializer\n ) {\n this.textDecoder = newTextDecoder();\n // Read the metadata (which is the first element).\n this.nextElementImpl().then(\n element => {\n if (element && element.isBundleMetadata()) {\n this.metadata.resolve(element.payload.metadata!);\n } else {\n this.metadata.reject(\n new Error(`The first element of the bundle is not a metadata, it is\n ${JSON.stringify(element?.payload)}`)\n );\n }\n },\n error => this.metadata.reject(error)\n );\n }\n\n close(): Promise {\n return this.reader.cancel();\n }\n\n async getMetadata(): Promise {\n return this.metadata.promise;\n }\n\n async nextElement(): Promise {\n // Makes sure metadata is read before proceeding.\n await this.getMetadata();\n return this.nextElementImpl();\n }\n\n /**\n * Reads from the head of internal buffer, and pulling more data from\n * underlying stream if a complete element cannot be found, until an\n * element(including the prefixed length and the JSON string) is found.\n *\n * Once a complete element is read, it is dropped from internal buffer.\n *\n * Returns either the bundled element, or null if we have reached the end of\n * the stream.\n */\n private async nextElementImpl(): Promise {\n const lengthBuffer = await this.readLength();\n if (lengthBuffer === null) {\n return null;\n }\n\n const lengthString = this.textDecoder.decode(lengthBuffer);\n const length = Number(lengthString);\n if (isNaN(length)) {\n this.raiseError(`length string (${lengthString}) is not valid number`);\n }\n\n const jsonString = await this.readJsonString(length);\n\n return new SizedBundleElement(\n JSON.parse(jsonString),\n lengthBuffer.length + length\n );\n }\n\n /** First index of '{' from the underlying buffer. */\n private indexOfOpenBracket(): number {\n return this.buffer.findIndex(v => v === '{'.charCodeAt(0));\n }\n\n /**\n * Reads from the beginning of the internal buffer, until the first '{', and\n * return the content.\n *\n * If reached end of the stream, returns a null.\n */\n private async readLength(): Promise {\n while (this.indexOfOpenBracket() < 0) {\n const done = await this.pullMoreDataToBuffer();\n if (done) {\n break;\n }\n }\n\n // Broke out of the loop because underlying stream is closed, and there\n // happens to be no more data to process.\n if (this.buffer.length === 0) {\n return null;\n }\n\n const position = this.indexOfOpenBracket();\n // Broke out of the loop because underlying stream is closed, but still\n // cannot find an open bracket.\n if (position < 0) {\n this.raiseError(\n 'Reached the end of bundle when a length string is expected.'\n );\n }\n\n const result = this.buffer.slice(0, position);\n // Update the internal buffer to drop the read length.\n this.buffer = this.buffer.slice(position);\n return result;\n }\n\n /**\n * Reads from a specified position from the internal buffer, for a specified\n * number of bytes, pulling more data from the underlying stream if needed.\n *\n * Returns a string decoded from the read bytes.\n */\n private async readJsonString(length: number): Promise {\n while (this.buffer.length < length) {\n const done = await this.pullMoreDataToBuffer();\n if (done) {\n this.raiseError('Reached the end of bundle when more is expected.');\n }\n }\n\n const result = this.textDecoder.decode(this.buffer.slice(0, length));\n // Update the internal buffer to drop the read json string.\n this.buffer = this.buffer.slice(length);\n return result;\n }\n\n private raiseError(message: string): void {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.reader.cancel();\n throw new Error(`Invalid bundle format: ${message}`);\n }\n\n /**\n * Pulls more data from underlying stream to internal buffer.\n * Returns a boolean indicating whether the stream is finished.\n */\n private async pullMoreDataToBuffer(): Promise {\n const result = await this.reader.read();\n if (!result.done) {\n debugAssert(!!result.value, 'Read undefined when \"done\" is false.');\n const newBuffer = new Uint8Array(\n this.buffer.length + result.value!.length\n );\n newBuffer.set(this.buffer);\n newBuffer.set(result.value!, this.buffer.length);\n this.buffer = newBuffer;\n }\n return result.done;\n }\n}\n\nexport function newBundleReader(\n reader: ReadableStreamDefaultReader,\n serializer: JsonProtoSerializer\n): BundleReader {\n return new BundleReaderImpl(reader, serializer);\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 } from '../protos/firestore_bundle_proto';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { BundleReaderSync, SizedBundleElement } from './bundle_reader';\n\n/**\n * A class that can parse a bundle form the string serialization of a bundle.\n */\nexport class BundleReaderSyncImpl implements BundleReaderSync {\n private metadata: BundleMetadata;\n private elements: SizedBundleElement[];\n private cursor: number;\n constructor(\n private bundleData: string,\n readonly serializer: JsonProtoSerializer\n ) {\n this.cursor = 0;\n this.elements = [];\n\n let element = this.nextElement();\n if (element && element.isBundleMetadata()) {\n this.metadata = element as BundleMetadata;\n } else {\n throw new Error(`The first element of the bundle is not a metadata object, it is\n ${JSON.stringify(element?.payload)}`);\n }\n\n do {\n element = this.nextElement();\n if (element !== null) {\n this.elements.push(element);\n }\n } while (element !== null);\n }\n\n /* Returns the parsed metadata of the bundle. */\n getMetadata(): BundleMetadata {\n return this.metadata;\n }\n\n /* Returns the DocumentSnapshot or NamedQuery elements of the bundle. */\n getElements(): SizedBundleElement[] {\n return this.elements;\n }\n\n /**\n * Parses the next element of the bundle.\n *\n * @returns a SizedBundleElement representation of the next element in the bundle, or null if\n * no more elements exist.\n */\n private nextElement(): SizedBundleElement | null {\n if (this.cursor === this.bundleData.length) {\n return null;\n }\n const length: number = this.readLength();\n const jsonString = this.readJsonString(length);\n return new SizedBundleElement(JSON.parse(jsonString), length);\n }\n\n /**\n * Reads from a specified position from the bundleData string, for a specified\n * number of bytes.\n *\n * @param length how many characters to read.\n * @returns a string parsed from the bundle.\n */\n private readJsonString(length: number): string {\n if (this.cursor + length > this.bundleData.length) {\n throw new FirestoreError(\n Code.INTERNAL,\n 'Reached the end of bundle when more is expected.'\n );\n }\n const result = this.bundleData.slice(this.cursor, (this.cursor += length));\n return result;\n }\n\n /**\n * Reads from the current cursor until the first '{'.\n *\n * @returns A string to integer represention of the parsed value.\n * @throws An {@link Error} if the cursor has reached the end of the stream, since lengths\n * prefix bundle objects.\n */\n private readLength(): number {\n const startIndex = this.cursor;\n let curIndex = this.cursor;\n while (curIndex < this.bundleData.length) {\n if (this.bundleData[curIndex] === '{') {\n if (curIndex === startIndex) {\n throw new Error('First character is a bracket and not a number');\n }\n this.cursor = curIndex;\n return Number(this.bundleData.slice(startIndex, curIndex));\n }\n curIndex++;\n }\n throw new Error('Reached the end of bundle when more is expected.');\n }\n}\n\n/**\n * Creates an instance of BundleReader without exposing the BundleReaderSyncImpl class type.\n */\nexport function newBundleReaderSync(\n bundleData: string,\n serializer: JsonProtoSerializer\n): BundleReaderSync {\n return new BundleReaderSyncImpl(bundleData, serializer);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParsedSetData, ParsedUpdateData } from '../lite-api/user_data_reader';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n DeleteMutation,\n Mutation,\n Precondition,\n VerifyMutation\n} from '../model/mutation';\nimport {\n Datastore,\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc\n} from '../remote/datastore';\nimport { fail, debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { SnapshotVersion } from './snapshot_version';\n\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nexport class Transaction {\n // The version of each document that was read during this transaction.\n private readVersions = new Map();\n private mutations: Mutation[] = [];\n private committed = false;\n\n /**\n * A deferred usage error that occurred previously in this transaction that\n * will cause the transaction to fail once it actually commits.\n */\n private lastTransactionError: FirestoreError | null = null;\n\n /**\n * Set of documents that have been written in the transaction.\n *\n * When there's more than one write to the same key in a transaction, any\n * writes after the first are handled differently.\n */\n private writtenDocs: Set = new Set();\n\n constructor(private datastore: Datastore) {}\n\n async lookup(keys: DocumentKey[]): Promise {\n this.ensureCommitNotCalled();\n\n if (this.mutations.length > 0) {\n this.lastTransactionError = new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Firestore transactions require all reads to be executed before all writes.'\n );\n throw this.lastTransactionError;\n }\n const docs = await invokeBatchGetDocumentsRpc(this.datastore, keys);\n docs.forEach(doc => this.recordVersion(doc));\n return docs;\n }\n\n set(key: DocumentKey, data: ParsedSetData): void {\n this.write(data.toMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n update(key: DocumentKey, data: ParsedUpdateData): void {\n try {\n this.write(data.toMutation(key, this.preconditionForUpdate(key)));\n } catch (e) {\n this.lastTransactionError = e as FirestoreError | null;\n }\n this.writtenDocs.add(key.toString());\n }\n\n delete(key: DocumentKey): void {\n this.write(new DeleteMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n async commit(): Promise {\n this.ensureCommitNotCalled();\n\n if (this.lastTransactionError) {\n throw this.lastTransactionError;\n }\n const unwritten = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach(mutation => {\n unwritten.delete(mutation.key.toString());\n });\n // For each document that was read but not written to, we want to perform\n // a `verify` operation.\n unwritten.forEach((_, path) => {\n const key = DocumentKey.fromPath(path);\n this.mutations.push(new VerifyMutation(key, this.precondition(key)));\n });\n await invokeCommitRpc(this.datastore, this.mutations);\n this.committed = true;\n }\n\n private recordVersion(doc: Document): void {\n let docVersion: SnapshotVersion;\n\n if (doc.isFoundDocument()) {\n docVersion = doc.version;\n } else if (doc.isNoDocument()) {\n // Represent a deleted doc using SnapshotVersion.min().\n docVersion = SnapshotVersion.min();\n } else {\n throw fail(0xc542, 'Document in a transaction was a ', {\n documentName: doc.constructor.name\n });\n }\n\n const existingVersion = this.readVersions.get(doc.key.toString());\n if (existingVersion) {\n if (!docVersion.isEqual(existingVersion)) {\n // This transaction will fail no matter what.\n throw new FirestoreError(\n Code.ABORTED,\n 'Document version changed between two reads.'\n );\n }\n } else {\n this.readVersions.set(doc.key.toString(), docVersion);\n }\n }\n\n /**\n * Returns the version of this document when it was read in this transaction,\n * as a precondition, or no precondition if it was not read.\n */\n private precondition(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n return Precondition.exists(false);\n } else {\n return Precondition.updateTime(version);\n }\n } else {\n return Precondition.none();\n }\n }\n\n /**\n * Returns the precondition for a document if the operation is an update.\n */\n private preconditionForUpdate(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n // The first time a document is written, we want to take into account the\n // read time and existence\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n // The document doesn't exist, so fail the transaction.\n\n // This has to be validated locally because you can't send a\n // precondition that a document does not exist without changing the\n // semantics of the backend write to be an insert. This is the reverse\n // of what we want, since we want to assert that the document doesn't\n // exist but then send the update and have it fail. Since we can't\n // express that to the backend, we have to validate locally.\n\n // Note: this can change once we can send separate verify writes in the\n // transaction.\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't update a document that doesn't exist.\"\n );\n }\n // Document exists, base precondition on document update time.\n return Precondition.updateTime(version);\n } else {\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return Precondition.exists(true);\n }\n }\n\n private write(mutation: Mutation): void {\n this.ensureCommitNotCalled();\n this.mutations.push(mutation);\n }\n\n private ensureCommitNotCalled(): void {\n debugAssert(\n !this.committed,\n 'A transaction object cannot be used after its update callback has been invoked.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ExponentialBackoff } from '../remote/backoff';\nimport { Datastore } from '../remote/datastore';\nimport { isPermanentError } from '../remote/rpc_error';\nimport { AsyncQueue, TimerId } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport { Deferred } from '../util/promise';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Transaction } from './transaction';\nimport { TransactionOptions } from './transaction_options';\n\n/**\n * TransactionRunner encapsulates the logic needed to run and retry transactions\n * with backoff.\n */\nexport class TransactionRunner {\n private attemptsRemaining: number;\n private backoff: ExponentialBackoff;\n\n constructor(\n private readonly asyncQueue: AsyncQueue,\n private readonly datastore: Datastore,\n private readonly options: TransactionOptions,\n private readonly updateFunction: (transaction: Transaction) => Promise,\n private readonly deferred: Deferred\n ) {\n this.attemptsRemaining = options.maxAttempts;\n this.backoff = new ExponentialBackoff(\n this.asyncQueue,\n TimerId.TransactionRetry\n );\n }\n\n /** Runs the transaction and sets the result on deferred. */\n run(): void {\n this.attemptsRemaining -= 1;\n this.runWithBackOff();\n }\n\n private runWithBackOff(): void {\n this.backoff.backoffAndRun(async () => {\n const transaction = new Transaction(this.datastore);\n const userPromise = this.tryRunUpdateFunction(transaction);\n if (userPromise) {\n userPromise\n .then(result => {\n this.asyncQueue.enqueueAndForget(() => {\n return transaction\n .commit()\n .then(() => {\n this.deferred.resolve(result);\n })\n .catch(commitError => {\n this.handleTransactionError(commitError);\n });\n });\n })\n .catch(userPromiseError => {\n this.handleTransactionError(userPromiseError);\n });\n }\n });\n }\n\n private tryRunUpdateFunction(transaction: Transaction): Promise | null {\n try {\n const userPromise = this.updateFunction(transaction);\n if (\n isNullOrUndefined(userPromise) ||\n !userPromise.catch ||\n !userPromise.then\n ) {\n this.deferred.reject(\n Error('Transaction callback must return a Promise')\n );\n return null;\n }\n return userPromise;\n } catch (error) {\n // Do not retry errors thrown by user provided updateFunction.\n this.deferred.reject(error as Error);\n return null;\n }\n }\n\n private handleTransactionError(error: Error): void {\n if (this.attemptsRemaining > 0 && this.isRetryableTransactionError(error)) {\n this.attemptsRemaining -= 1;\n this.asyncQueue.enqueueAndForget(() => {\n this.runWithBackOff();\n return Promise.resolve();\n });\n } else {\n this.deferred.reject(error);\n }\n }\n\n private isRetryableTransactionError(error: Error | undefined): boolean {\n if (error?.name === 'FirebaseError') {\n // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and\n // non-matching document versions with ABORTED. These errors should be retried.\n const code = (error as FirestoreError).code;\n return (\n code === 'aborted' ||\n code === 'failed-precondition' ||\n code === 'already-exists' ||\n !isPermanentError(code)\n );\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GetOptions } from '@firebase/firestore-types';\n\nimport { LoadBundleTask } from '../api/bundle';\nimport {\n CredentialChangeListener,\n CredentialsProvider\n} from '../api/credentials';\nimport { User } from '../auth/user';\nimport { LocalStore } from '../local/local_store';\nimport {\n localStoreConfigureFieldIndexes,\n localStoreDeleteAllFieldIndexes,\n localStoreExecuteQuery,\n localStoreGetNamedQuery,\n localStoreHandleUserChange,\n localStoreReadDocument,\n localStoreSetIndexAutoCreationEnabled\n} from '../local/local_store_impl';\nimport { Persistence } from '../local/persistence';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldIndex } from '../model/field_index';\nimport { Mutation } from '../model/mutation';\nimport { toByteStreamReader } from '../platform/byte_stream_reader';\nimport { newSerializer } from '../platform/serializer';\nimport { newTextEncoder } from '../platform/text_serializer';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { Datastore, invokeRunAggregationQueryRpc } from '../remote/datastore';\nimport {\n RemoteStore,\n remoteStoreDisableNetwork,\n remoteStoreEnableNetwork,\n remoteStoreHandleCredentialChange\n} from '../remote/remote_store';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { debugAssert } from '../util/assert';\nimport { AsyncObserver } from '../util/async_observer';\nimport { AsyncQueue, wrapInUserErrorIfRecoverable } from '../util/async_queue';\nimport { BundleReader, BundleReaderSync } from '../util/bundle_reader';\nimport { newBundleReader } from '../util/bundle_reader_impl';\nimport { newBundleReaderSync } from '../util/bundle_reader_sync_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 LruGcMemoryOfflineComponentProvider,\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 LruGcMemoryOfflineComponentProvider(undefined)\n );\n }\n }\n\n return client._offlineComponents!;\n}\n\nexport async 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 createBundleReaderSync(\n bundleData: string,\n serializer: JsonProtoSerializer\n): BundleReaderSync {\n return newBundleReaderSync(bundleData, 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BundleSource } from '../../util/bundle_reader';\nimport { toByteStreamReaderHelper } from '../../util/byte_stream';\n\n/**\n * On web, a `ReadableStream` is wrapped around by a `ByteStreamReader`.\n */\nexport function toByteStreamReader(\n source: BundleSource,\n bytesPerRead: number\n): ReadableStreamDefaultReader {\n if (source instanceof Uint8Array) {\n return toByteStreamReaderHelper(source, bytesPerRead);\n }\n if (source instanceof ArrayBuffer) {\n return toByteStreamReaderHelper(new Uint8Array(source), bytesPerRead);\n }\n if (source instanceof ReadableStream) {\n return source.getReader();\n }\n throw new Error(\n 'Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream'\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 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 settings.isUsingEmulator\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 { EmulatorMockTokenOptions } from '@firebase/util';\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 emulatorOptions?: { mockUserToken?: EmulatorMockTokenOptions | string };\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 readonly isUsingEmulator: boolean;\n\n // Can be a google-auth-library or gapi client.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n credentials?: any;\n\n constructor(settings: PrivateSettings) {\n if (settings.host === undefined) {\n if (settings.ssl !== undefined) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't provide ssl option if host option is not set\"\n );\n }\n this.host = DEFAULT_HOST;\n this.ssl = DEFAULT_SSL;\n } else {\n this.host = settings.host;\n this.ssl = settings.ssl ?? DEFAULT_SSL;\n }\n this.isUsingEmulator = settings.emulatorOptions !== undefined;\n\n this.credentials = settings.credentials;\n this.ignoreUndefinedProperties = !!settings.ignoreUndefinedProperties;\n this.localCache = settings.localCache;\n\n if (settings.cacheSizeBytes === undefined) {\n this.cacheSizeBytes = LRU_DEFAULT_CACHE_SIZE_BYTES;\n } else {\n if (\n settings.cacheSizeBytes !== LRU_COLLECTION_DISABLED &&\n settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`\n );\n } else {\n this.cacheSizeBytes = settings.cacheSizeBytes;\n }\n }\n\n validateIsNotUsedTogether(\n 'experimentalForceLongPolling',\n settings.experimentalForceLongPolling,\n 'experimentalAutoDetectLongPolling',\n settings.experimentalAutoDetectLongPolling\n );\n\n this.experimentalForceLongPolling = !!settings.experimentalForceLongPolling;\n\n if (this.experimentalForceLongPolling) {\n this.experimentalAutoDetectLongPolling = false;\n } else if (settings.experimentalAutoDetectLongPolling === undefined) {\n this.experimentalAutoDetectLongPolling = DEFAULT_AUTO_DETECT_LONG_POLLING;\n } else {\n // For backwards compatibility, coerce the value to boolean even though\n // the TypeScript compiler has narrowed the type to boolean already.\n // noinspection PointlessBooleanExpressionJS\n this.experimentalAutoDetectLongPolling =\n !!settings.experimentalAutoDetectLongPolling;\n }\n\n this.experimentalLongPollingOptions = cloneLongPollingOptions(\n settings.experimentalLongPollingOptions ?? {}\n );\n validateLongPollingOptions(this.experimentalLongPollingOptions);\n\n this.useFetchStreams = !!settings.useFetchStreams;\n }\n\n isEqual(other: FirestoreSettingsImpl): boolean {\n return (\n this.host === other.host &&\n this.ssl === other.ssl &&\n this.credentials === other.credentials &&\n this.cacheSizeBytes === other.cacheSizeBytes &&\n this.experimentalForceLongPolling ===\n other.experimentalForceLongPolling &&\n this.experimentalAutoDetectLongPolling ===\n other.experimentalAutoDetectLongPolling &&\n longPollingOptionsEqual(\n this.experimentalLongPollingOptions,\n other.experimentalLongPollingOptions\n ) &&\n this.ignoreUndefinedProperties === other.ignoreUndefinedProperties &&\n this.useFetchStreams === other.useFetchStreams\n );\n }\n}\n\nfunction validateLongPollingOptions(\n options: ExperimentalLongPollingOptions\n): void {\n if (options.timeoutSeconds !== undefined) {\n if (isNaN(options.timeoutSeconds)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ` +\n `${options.timeoutSeconds} (must not be NaN)`\n );\n }\n if (options.timeoutSeconds < MIN_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(minimum allowed value is ${MIN_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n if (options.timeoutSeconds > MAX_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(maximum allowed value is ${MAX_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _getProvider,\n _removeServiceInstance,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport {\n createMockUserToken,\n deepEqual,\n EmulatorMockTokenOptions,\n getDefaultEmulatorHostnameAndPort,\n isCloudWorkstation,\n pingServer,\n updateEmulatorBanner\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 private _emulatorOptions: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {};\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 this._emulatorOptions = settings.emulatorOptions || {};\n\n if (settings.credentials !== undefined) {\n this._authCredentials = makeAuthCredentialsProvider(settings.credentials);\n }\n }\n\n _getSettings(): FirestoreSettingsImpl {\n return this._settings;\n }\n\n _getEmulatorOptions(): { mockUserToken?: EmulatorMockTokenOptions | string } {\n return this._emulatorOptions;\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 useSsl = isCloudWorkstation(host);\n const settings = firestore._getSettings();\n const existingConfig = {\n ...settings,\n emulatorOptions: firestore._getEmulatorOptions()\n };\n const newHostSetting = `${host}:${port}`;\n if (useSsl) {\n void pingServer(`https://${newHostSetting}`);\n updateEmulatorBanner('Firestore', true);\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 const newConfig = {\n ...settings,\n host: newHostSetting,\n ssl: useSsl,\n emulatorOptions: options\n };\n // No-op if the new configuration matches the current configuration. This supports SSR\n // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice.\n if (deepEqual(newConfig, existingConfig)) {\n return;\n }\n\n firestore._setSettings(newConfig);\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';\n// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_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 static _jsonSchemaVersion: string = 'firestore/documentReference/1.0';\n static _jsonSchema = {\n type: property('string', DocumentReference._jsonSchemaVersion),\n referencePath: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `DocumentReference` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: DocumentReference._jsonSchemaVersion,\n referencePath: this._key.toString()\n };\n }\n\n /**\n * Builds a `DocumentReference` instance from a JSON object created by\n * {@link DocumentReference.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json a JSON object represention of a `DocumentReference` instance\n * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(firestore: Firestore, json: object): DocumentReference;\n /**\n * Builds a `DocumentReference` instance from a JSON object created by\n * {@link DocumentReference.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json a JSON object represention of a `DocumentReference` instance\n * @param converter - Converts objects to and from Firestore.\n * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON<\n NewAppModelType = DocumentData,\n NewDbModelType extends DocumentData = DocumentData\n >(\n firestore: Firestore,\n json: object,\n converter: FirestoreDataConverter\n ): DocumentReference;\n static fromJSON<\n NewAppModelType = DocumentData,\n NewDbModelType extends DocumentData = DocumentData\n >(\n firestore: Firestore,\n json: object,\n converter?: FirestoreDataConverter\n ): DocumentReference {\n if (validateJSON(json, DocumentReference._jsonSchema)) {\n return new DocumentReference(\n firestore,\n converter ? converter : null,\n new DocumentKey(ResourcePath.fromString(json.referencePath))\n );\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Bytes from JSON.'\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(0xb815, 'AsyncQueue is already failed', {\n messageOrStack: getMessageOrStack(this.failure)\n });\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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { JsonObject } from '../model/object_value';\nimport { FirestoreError } from '../util/error';\n\n/**\n * Observer/Subscribe interfaces.\n */\nexport type NextFn = (value: T) => void;\nexport type ErrorFn = (error: FirestoreError) => void;\nexport type CompleteFn = () => void;\n\n// Allow for any of the Observer methods to be undefined.\nexport interface PartialObserver {\n next?: NextFn;\n error?: ErrorFn;\n complete?: CompleteFn;\n}\n\nexport function isPartialObserver(obj: unknown): obj is PartialObserver {\n return implementsAnyMethods(obj, ['next', 'error', 'complete']);\n}\n\n/**\n * Returns true if obj is an object and contains at least one of the specified\n * methods.\n */\nfunction implementsAnyMethods(obj: unknown, methods: string[]): boolean {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n\n const object = obj as JsonObject;\n for (const method of methods) {\n if (method in object && typeof object[method] === 'function') {\n return true;\n }\n }\n return false;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PartialObserver } from '../api/observer';\nimport { debugAssert } from '../util/assert';\nimport { FirestoreError } from '../util/error';\nimport { Deferred } from '../util/promise';\n\n/**\n * Represents the state of bundle loading tasks.\n *\n * Both 'Error' and 'Success' are sinking state: task will abort or complete and there will\n * be no more updates after they are reported.\n */\nexport type TaskState = 'Error' | 'Running' | 'Success';\n\n/**\n * Represents a progress update or a final state from loading bundles.\n */\nexport interface LoadBundleTaskProgress {\n /** How many documents have been loaded. */\n documentsLoaded: number;\n /** How many documents are in the bundle being loaded. */\n totalDocuments: number;\n /** How many bytes have been loaded. */\n bytesLoaded: number;\n /** How many bytes are in the bundle being loaded. */\n totalBytes: number;\n /** Current task state. */\n taskState: TaskState;\n}\n\n/**\n * Represents the task of loading a Firestore bundle. It provides progress of bundle\n * loading, as well as task completion and error events.\n *\n * The API is compatible with `Promise`.\n */\nexport class LoadBundleTask implements PromiseLike {\n private _progressObserver: PartialObserver = {};\n private _taskCompletionResolver = new Deferred();\n\n private _lastProgress: LoadBundleTaskProgress = {\n taskState: 'Running',\n totalBytes: 0,\n totalDocuments: 0,\n bytesLoaded: 0,\n documentsLoaded: 0\n };\n\n /**\n * Registers functions to listen to bundle loading progress events.\n * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur\n * each time a Firestore document is loaded from the bundle.\n * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the\n * error, and there should be no more updates after this.\n * @param complete - Called when the loading task is complete.\n */\n onProgress(\n next?: (progress: LoadBundleTaskProgress) => unknown,\n error?: (err: Error) => unknown,\n complete?: () => void\n ): void {\n this._progressObserver = {\n next,\n error,\n complete\n };\n }\n\n /**\n * Implements the `Promise.catch` interface.\n *\n * @param onRejected - Called when an error occurs during bundle loading.\n */\n catch(\n onRejected: (a: Error) => R | PromiseLike\n ): Promise {\n return this._taskCompletionResolver.promise.catch(onRejected);\n }\n\n /**\n * Implements the `Promise.then` interface.\n *\n * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update.\n * The update will always have its `taskState` set to `\"Success\"`.\n * @param onRejected - Called when an error occurs during bundle loading.\n */\n then(\n onFulfilled?: (a: LoadBundleTaskProgress) => T | PromiseLike,\n onRejected?: (a: Error) => R | PromiseLike\n ): Promise {\n return this._taskCompletionResolver.promise.then(onFulfilled, onRejected);\n }\n\n /**\n * Notifies all observers that bundle loading has completed, with a provided\n * `LoadBundleTaskProgress` object.\n *\n * @private\n */\n _completeWith(progress: LoadBundleTaskProgress): void {\n debugAssert(\n progress.taskState === 'Success',\n 'Task is not completed with Success.'\n );\n this._updateProgress(progress);\n if (this._progressObserver.complete) {\n this._progressObserver.complete();\n }\n\n this._taskCompletionResolver.resolve(progress);\n }\n\n /**\n * Notifies all observers that bundle loading has failed, with a provided\n * `Error` as the reason.\n *\n * @private\n */\n _failWith(error: FirestoreError): void {\n this._lastProgress.taskState = 'Error';\n\n if (this._progressObserver.next) {\n this._progressObserver.next(this._lastProgress);\n }\n\n if (this._progressObserver.error) {\n this._progressObserver.error(error);\n }\n\n this._taskCompletionResolver.reject(error);\n }\n\n /**\n * Notifies a progress update of loading a bundle.\n * @param progress - The new progress.\n *\n * @private\n */\n _updateProgress(progress: LoadBundleTaskProgress): void {\n debugAssert(\n this._lastProgress.taskState === 'Running',\n 'Cannot update progress on a completed or failed task'\n );\n\n this._lastProgress = progress;\n if (this._progressObserver.next) {\n this._progressObserver.next(progress);\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _getProvider,\n _removeServiceInstance,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport {\n deepEqual,\n getDefaultEmulatorHostnameAndPort,\n isCloudWorkstation,\n pingServer\n} 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 // Workaround to get cookies in Firebase Studio\n if (settings.host && isCloudWorkstation(settings.host)) {\n void pingServer(settings.host);\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 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 { AggregateType } from '../core/aggregate';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\n\nimport { average, count, sum } from './aggregate';\nimport { DocumentData, Query } from './reference';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\nexport { AggregateType };\n\n/**\n * Represents an aggregation that can be performed by Firestore.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport class AggregateField {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateField';\n\n /** Indicates the aggregation operation of this AggregateField. */\n readonly aggregateType: AggregateType;\n\n /**\n * Create a new AggregateField\n * @param aggregateType Specifies the type of aggregation operation to perform.\n * @param _internalFieldPath Optionally specifies the field that is aggregated.\n * @internal\n */\n constructor(\n aggregateType: AggregateType = 'count',\n readonly _internalFieldPath?: InternalFieldPath\n ) {\n this.aggregateType = aggregateType;\n }\n}\n\n/**\n * The union of all `AggregateField` types that are supported by Firestore.\n */\nexport type AggregateFieldType =\n | ReturnType\n | ReturnType\n | ReturnType;\n\n/**\n * Specifies a set of aggregations and their aliases.\n */\nexport interface AggregateSpec {\n [field: string]: AggregateFieldType;\n}\n\n/**\n * A type whose keys are taken from an `AggregateSpec`, and whose values are the\n * result of the aggregation performed by the corresponding `AggregateField`\n * from the input `AggregateSpec`.\n */\nexport type AggregateSpecData = {\n [P in keyof T]: T[P] extends AggregateField ? U : never;\n};\n\n/**\n * The results of executing an aggregation query.\n */\nexport class AggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateQuerySnapshot';\n\n /**\n * The underlying query over which the aggregations recorded in this\n * `AggregateQuerySnapshot` were performed.\n */\n readonly query: Query;\n\n /** @hideconstructor */\n constructor(\n query: Query,\n private readonly _userDataWriter: AbstractUserDataWriter,\n private readonly _data: ApiClientObjectMap\n ) {\n this.query = query;\n }\n\n /**\n * Returns the results of the aggregations performed over the underlying\n * query.\n *\n * The keys of the returned object will be the same as those of the\n * `AggregateSpec` object specified to the aggregation method, and the values\n * will be the corresponding aggregation result.\n *\n * @returns The results of the aggregations performed over the underlying\n * query.\n */\n data(): AggregateSpecData {\n return this._userDataWriter.convertObjectMap(\n this._data\n ) as AggregateSpecData;\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// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\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 static _jsonSchemaVersion: string = 'firestore/bytes/1.0';\n static _jsonSchema = {\n type: property('string', Bytes._jsonSchemaVersion),\n bytes: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `Bytes` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: Bytes._jsonSchemaVersion,\n bytes: this.toBase64()\n };\n }\n\n /**\n * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}.\n *\n * @param json a JSON object represention of a `Bytes` instance\n * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): Bytes {\n if (validateJSON(json, Bytes._jsonSchema)) {\n return Bytes.fromBase64String(json.bytes);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Bytes from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n 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';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\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 /**\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 static _jsonSchemaVersion: string = 'firestore/geoPoint/1.0';\n static _jsonSchema = {\n type: property('string', GeoPoint._jsonSchemaVersion),\n latitude: property('number'),\n longitude: property('number')\n };\n\n /**\n * Returns a JSON-serializable representation of this `GeoPoint` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): { latitude: number; longitude: number; type: string } {\n return {\n latitude: this._lat,\n longitude: this._long,\n type: GeoPoint._jsonSchemaVersion\n };\n }\n\n /**\n * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}.\n *\n * @param json a JSON object represention of a `GeoPoint` instance\n * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): GeoPoint {\n if (validateJSON(json, GeoPoint._jsonSchema)) {\n return new GeoPoint(json.latitude, json.longitude);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating GeoPoint from JSON.'\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';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\n\n/**\n * Represents a vector type in Firestore documents.\n * Create an instance with {@link 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` values have the same raw number arrays, returns `false` otherwise.\n */\n isEqual(other: VectorValue): boolean {\n return isPrimitiveArrayEqual(this._values, other._values);\n }\n\n static _jsonSchemaVersion: string = 'firestore/vectorValue/1.0';\n static _jsonSchema = {\n type: property('string', VectorValue._jsonSchemaVersion),\n vectorValues: property('object')\n };\n\n /**\n * Returns a JSON-serializable representation of this `VectorValue` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: VectorValue._jsonSchemaVersion,\n vectorValues: this._values\n };\n }\n\n /**\n * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}.\n *\n * @param json a JSON object represention of a `VectorValue` instance.\n * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): VectorValue {\n if (validateJSON(json, VectorValue._jsonSchema)) {\n if (\n Array.isArray(json.vectorValues) &&\n json.vectorValues.every(element => typeof element === 'number')\n ) {\n return new VectorValue(json.vectorValues);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Expected 'vectorValues' field to be a number array\"\n );\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Timestamp from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData,\n FieldPath as PublicFieldPath,\n SetOptions\n} from '@firebase/firestore-types';\nimport { Compat, deepEqual, getModularInstance } from '@firebase/util';\n\nimport { ParseContext } from '../api/parse_context';\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n FieldTransform,\n Mutation,\n PatchMutation,\n Precondition,\n SetMutation\n} from '../model/mutation';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform\n} from '../model/transform_operation';\nimport {\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(0x9c4b, 'Unexpected case for UserDataSource', {\n dataSource\n });\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\nexport function 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(0xf2a2, 'Invalid value type', {\n value\n });\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 0x25d8,\n 'ReferenceValue is not valid',\n { name }\n );\n const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3));\n const key = new DocumentKey(resourcePath.popFirst(5));\n\n if (!databaseId.isEqual(expectedDatabaseId)) {\n // TODO(b/64130202): Somehow support foreign references.\n logError(\n `Document ${key} contains a document ` +\n `reference within a different database (` +\n `${databaseId.projectId}/${databaseId.database}) which is not ` +\n `supported. It will be treated as a reference in the current ` +\n `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` +\n `instead.`\n );\n }\n return key;\n }\n\n protected abstract convertReference(name: string): unknown;\n\n protected abstract convertBytes(bytes: ByteString): unknown;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData as PublicDocumentData,\n SetOptions as PublicSetOptions\n} from '@firebase/firestore-types';\nimport { getModularInstance } from '@firebase/util';\n\nimport { LimitType } from '../core/query';\nimport { DeleteMutation, Precondition } from '../model/mutation';\nimport {\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc,\n invokeRunQueryRpc\n} from '../remote/datastore';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { cast } from '../util/input_validation';\n\nimport { Bytes } from './bytes';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { validateHasExplicitOrderByForLimitToLast } from './query';\nimport {\n CollectionReference,\n doc,\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot\n} from './snapshot';\nimport {\n newUserDataReader,\n ParsedUpdateData,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converts custom model object of type T into `DocumentData` by applying the\n * converter if it exists.\n *\n * This function is used when converting user objects to `DocumentData`\n * because we want to provide the user with a more specific error message if\n * their `set()` or fails due to invalid data originating from a `toFirestore()`\n * call.\n */\nexport function applyFirestoreDataConverter(\n converter: UntypedFirestoreDataConverter | null,\n value: WithFieldValue | PartialWithFieldValue,\n options?: PublicSetOptions\n): PublicDocumentData {\n let convertedValue;\n if (converter) {\n if (options && (options.merge || options.mergeFields)) {\n // Cast to `any` in order to satisfy the union type constraint on\n // toFirestore().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n convertedValue = (converter as any).toFirestore(value, options);\n } else {\n convertedValue = converter.toFirestore(value as WithFieldValue);\n }\n } else {\n convertedValue = value as PublicDocumentData;\n }\n return convertedValue;\n}\n\nexport class LiteUserDataWriter extends AbstractUserDataWriter {\n constructor(protected firestore: Firestore) {\n super();\n }\n\n protected convertBytes(bytes: ByteString): Bytes {\n return new Bytes(bytes);\n }\n\n protected convertReference(name: string): DocumentReference {\n const key = this.convertDocumentKey(name, this.firestore._databaseId);\n return new DocumentReference(this.firestore, /* converter= */ null, key);\n }\n}\n\n/**\n * Reads the document referred to by the specified document reference.\n *\n * All documents are directly fetched from the server, even if the document was\n * previously read or modified. Recent modifications are only reflected in the\n * retrieved `DocumentSnapshot` if they have already been applied by the\n * backend. If the client is offline, the read fails. If you like to use\n * caching or see local modifications, please use the full Firestore SDK.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the current\n * document contents.\n */\nexport function getDoc(\n reference: DocumentReference\n): Promise> {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n const userDataWriter = new LiteUserDataWriter(reference.firestore);\n\n return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then(\n result => {\n hardAssert(\n result.length === 1,\n 0x3d02,\n 'Expected a single document result'\n );\n const document = result[0];\n return new DocumentSnapshot(\n reference.firestore,\n userDataWriter,\n reference._key,\n document.isFoundDocument() ? document : null,\n reference.converter\n );\n }\n );\n}\n\n/**\n * Executes the query and returns the results as a {@link QuerySnapshot}.\n *\n * All queries are executed directly by the server, even if the query was\n * previously executed. Recent modifications are only reflected in the retrieved\n * results if they have already been applied by the backend. If the client is\n * offline, the operation fails. To see previously cached result and local\n * modifications, use the full Firestore SDK.\n *\n * @param query - The `Query` to execute.\n * @returns A Promise that will be resolved with the results of the query.\n */\nexport function getDocs(\n query: Query\n): Promise> {\n query = cast>(query, Query);\n validateHasExplicitOrderByForLimitToLast(query._query);\n\n const datastore = getDatastore(query.firestore);\n const userDataWriter = new LiteUserDataWriter(query.firestore);\n return invokeRunQueryRpc(datastore, query._query).then(result => {\n const docs = result.map(\n doc =>\n new QueryDocumentSnapshot(\n query.firestore,\n userDataWriter,\n doc.key,\n doc,\n query.converter\n )\n );\n\n if (query._query.limitType === LimitType.Last) {\n // Limit to last queries reverse the orderBy constraint that was\n // specified by the user. As such, we need to reverse the order of the\n // results to return the documents in the expected order.\n docs.reverse();\n }\n\n return new QuerySnapshot(query, docs);\n });\n}\n\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\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 * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\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 convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data,\n options\n );\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'setDoc',\n reference._key,\n convertedValue,\n reference.converter !== null,\n options\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference`. The update will fail if applied to a document that does\n * not exist.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\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 * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\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 dataReader = newUserDataReader(reference.firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed: ParsedUpdateData;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData\n );\n }\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.exists(true))\n ]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * The deletion will only be reflected in document reads that occur after the\n * returned promise resolves. If the client is offline, the\n * delete fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to delete.\n * @returns A `Promise` resolved once the document has been successfully\n * deleted from the backend.\n */\nexport function deleteDoc(\n reference: DocumentReference\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n new DeleteMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend.\n */\nexport function addDoc(\n reference: CollectionReference,\n data: WithFieldValue\n): Promise> {\n reference = cast>(\n reference,\n CollectionReference\n );\n const docRef = doc(reference);\n\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data as PartialWithFieldValue\n );\n\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'addDoc',\n docRef._key,\n convertedValue,\n docRef.converter !== null,\n {}\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(docRef._key, Precondition.exists(false))\n ]).then(() => docRef);\n}\n","/**\n * @license\n * Copyright 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 { deepEqual } from '@firebase/util';\n\nimport { AggregateImpl } from '../core/aggregate';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { invokeRunAggregationQueryRpc } from '../remote/datastore';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport {\n AggregateField,\n AggregateQuerySnapshot,\n AggregateSpec\n} from './aggregate_types';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { DocumentData, Query, queryEqual } from './reference';\nimport { LiteUserDataWriter } from './reference_impl';\nimport { fieldPathFromArgument } from './user_data_reader';\n\n/**\n * Calculates the number of documents in the result set of the given query\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can\n * count the documents in cases where the result set is prohibitively large to\n * download entirely (thousands of documents).\n *\n * @param query The query whose result set size is calculated.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */\nexport function getCount(\n query: Query\n): Promise<\n AggregateQuerySnapshot<\n { count: AggregateField },\n AppModelType,\n DbModelType\n >\n> {\n const countQuerySpec: { count: AggregateField } = {\n count: count()\n };\n\n return getAggregate(query, countQuerySpec);\n}\n\n/**\n * Calculates the specified aggregations over the documents in the result\n * set of the given query without actually downloading the documents.\n *\n * Using this function to perform aggregations is efficient because only the\n * final aggregation values, not the documents' data, are downloaded. This\n * function can perform aggregations of the documents in cases where the result\n * set is prohibitively large to download entirely (thousands of documents).\n *\n * @param query The query whose result set is aggregated over.\n * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates\n * to perform over the result set. The AggregateSpec specifies aliases for each\n * aggregate, which can be used to retrieve the aggregate result.\n * @example\n * ```typescript\n * const aggregateSnapshot = await getAggregate(query, {\n * countOfDocs: count(),\n * totalHours: sum('hours'),\n * averageScore: average('score')\n * });\n *\n * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;\n * const totalHours: number = aggregateSnapshot.data().totalHours;\n * const averageScore: number | null = aggregateSnapshot.data().averageScore;\n * ```\n */\nexport function getAggregate<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n aggregateSpec: AggregateSpecType\n): Promise<\n AggregateQuerySnapshot\n> {\n const firestore = cast(query.firestore, Firestore);\n const datastore = getDatastore(firestore);\n\n const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n\n // Run the aggregation and convert the results\n return invokeRunAggregationQueryRpc(\n datastore,\n query._query,\n internalAggregates\n ).then(aggregateResult =>\n convertToAggregateQuerySnapshot(firestore, query, aggregateResult)\n );\n}\n\nfunction convertToAggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n query: Query,\n aggregateResult: ApiClientObjectMap\n): AggregateQuerySnapshot {\n const userDataWriter = new LiteUserDataWriter(firestore);\n const querySnapshot = new AggregateQuerySnapshot<\n AggregateSpecType,\n AppModelType,\n DbModelType\n >(query, userDataWriter, aggregateResult);\n return querySnapshot;\n}\n\n/**\n * Create an AggregateField object that can be used to compute the sum of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to sum across the result set.\n */\nexport function sum(field: string | FieldPath): AggregateField {\n return new AggregateField('sum', fieldPathFromArgument('sum', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the average of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to average across the result set.\n */\nexport function average(\n field: string | FieldPath\n): AggregateField {\n return new AggregateField('avg', fieldPathFromArgument('average', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the count of\n * documents in the result set of a query.\n */\nexport function count(): AggregateField {\n return new AggregateField('count');\n}\n\n/**\n * Compares two 'AggregateField` instances for equality.\n *\n * @param left Compare this AggregateField to the `right`.\n * @param right Compare this AggregateField to the `left`.\n */\nexport function aggregateFieldEqual(\n left: AggregateField,\n right: AggregateField\n): boolean {\n return (\n left instanceof AggregateField &&\n right instanceof AggregateField &&\n left.aggregateType === right.aggregateType &&\n left._internalFieldPath?.canonicalString() ===\n right._internalFieldPath?.canonicalString()\n );\n}\n\n/**\n * Compares two `AggregateQuerySnapshot` instances for equality.\n *\n * Two `AggregateQuerySnapshot` instances are considered \"equal\" if they have\n * underlying queries that compare equal, and the same data.\n *\n * @param left - The first `AggregateQuerySnapshot` to compare.\n * @param right - The second `AggregateQuerySnapshot` to compare.\n *\n * @returns `true` if the objects are \"equal\", as defined above, or `false`\n * otherwise.\n */\nexport function aggregateQuerySnapshotEqual<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n left: AggregateQuerySnapshot,\n right: AggregateQuerySnapshot\n): boolean {\n return (\n queryEqual(left.query, right.query) && deepEqual(left.data(), right.data())\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 { BundleLoader } from '../core/bundle_impl';\nimport { createBundleReaderSync } from '../core/firestore_client';\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 { LiteUserDataWriter } from '../lite-api/reference_impl';\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 { fromBundledQuery } from '../local/local_serializer';\nimport { documentKeySet } from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { DocumentSet } from '../model/document_set';\nimport { ResourcePath } from '../model/path';\nimport { newSerializer } from '../platform/serializer';\nimport {\n buildQuerySnapshotJsonBundle,\n buildDocumentSnapshotJsonBundle\n} from '../platform/snapshot_to_json';\nimport { fromDocument } from '../remote/serializer';\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\nimport { AutoId } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { SnapshotListenOptions } from './reference_impl';\n\nconst NOT_SUPPORTED = 'NOT SUPPORTED';\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 static _jsonSchemaVersion: string = 'firestore/documentSnapshot/1.0';\n static _jsonSchema = {\n type: property('string', DocumentSnapshot._jsonSchemaVersion),\n bundleSource: property('string', 'DocumentSnapshot'),\n bundleName: property('string'),\n bundle: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `DocumentSnapshot` instance.\n *\n * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this\n * `DocumentSnapshot` has pending writes.\n */\n toJSON(): object {\n if (this.metadata.hasPendingWrites) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'DocumentSnapshot.toJSON() attempted to serialize a document with pending writes. ' +\n 'Await waitForPendingWrites() before invoking toJSON().'\n );\n }\n const document = this._document;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: any = {};\n result['type'] = DocumentSnapshot._jsonSchemaVersion;\n result['bundle'] = '';\n result['bundleSource'] = 'DocumentSnapshot';\n result['bundleName'] = this._key.toString();\n\n if (\n !document ||\n !document.isValidDocument() ||\n !document.isFoundDocument()\n ) {\n return result;\n }\n const documentData = this._userDataWriter.convertObjectMap(\n document.data.value.mapValue.fields,\n 'previous'\n );\n result['bundle'] = buildDocumentSnapshotJsonBundle(\n this._firestore,\n document,\n documentData,\n this.ref.path\n );\n return result;\n }\n}\n\n/**\n * Builds a `DocumentSnapshot` instance from a JSON object created by\n * {@link DocumentSnapshot.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json - a JSON object represention of a `DocumentSnapshot` instance.\n * @returns an instance of {@link DocumentSnapshot} if the JSON object could be\n * parsed. Throws a {@link FirestoreError} if an error occurs.\n */\nexport function documentSnapshotFromJSON(\n db: Firestore,\n json: object\n): DocumentSnapshot;\n/**\n * Builds a `DocumentSnapshot` instance from a JSON object created by\n * {@link DocumentSnapshot.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json - a JSON object represention of a `DocumentSnapshot` instance.\n * @param converter - Converts objects to and from Firestore.\n * @returns an instance of {@link DocumentSnapshot} if the JSON object could be\n * parsed. Throws a {@link FirestoreError} if an error occurs.\n */\nexport function documentSnapshotFromJSON<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n>(\n db: Firestore,\n json: object,\n converter: FirestoreDataConverter\n): DocumentSnapshot;\nexport function documentSnapshotFromJSON<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n>(\n db: Firestore,\n json: object,\n converter?: FirestoreDataConverter\n): DocumentSnapshot {\n if (validateJSON(json, DocumentSnapshot._jsonSchema)) {\n if (json.bundle === NOT_SUPPORTED) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'The provided JSON object was created in a client environment, which is not supported.'\n );\n }\n // Parse the bundle data.\n const serializer = newSerializer(db._databaseId);\n const bundleReader = createBundleReaderSync(json.bundle, serializer);\n const elements = bundleReader.getElements();\n const bundleLoader: BundleLoader = new BundleLoader(\n bundleReader.getMetadata(),\n serializer\n );\n for (const element of elements) {\n bundleLoader.addSizedElement(element);\n }\n\n // Ensure that we have the correct number of documents in the bundle.\n const bundledDocuments = bundleLoader.documents;\n if (bundledDocuments.length !== 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Expected bundle data to contain 1 document, but it contains ${bundledDocuments.length} documents.`\n );\n }\n\n // Build out the internal document data.\n const document = fromDocument(serializer, bundledDocuments[0].document!);\n const documentKey = new DocumentKey(\n ResourcePath.fromString(json.bundleName)\n );\n\n // Return the external facing DocumentSnapshot.\n return new DocumentSnapshot(\n db,\n new LiteUserDataWriter(db),\n documentKey,\n document,\n new SnapshotMetadata(\n /* hasPendingWrites= */ false,\n /* fromCache= */ false\n ),\n converter ? converter : null\n );\n }\n throw new FirestoreError(\n Code.INTERNAL,\n 'Unexpected error creating DocumentSnapshot from JSON.'\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 static _jsonSchemaVersion: string = 'firestore/querySnapshot/1.0';\n static _jsonSchema = {\n type: property('string', QuerySnapshot._jsonSchemaVersion),\n bundleSource: property('string', 'QuerySnapshot'),\n bundleName: property('string'),\n bundle: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `QuerySnapshot` instance.\n *\n * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this\n * `QuerySnapshot` has pending writes.\n */\n toJSON(): object {\n if (this.metadata.hasPendingWrites) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'QuerySnapshot.toJSON() attempted to serialize a document with pending writes. ' +\n 'Await waitForPendingWrites() before invoking toJSON().'\n );\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: any = {};\n result['type'] = QuerySnapshot._jsonSchemaVersion;\n result['bundleSource'] = 'QuerySnapshot';\n result['bundleName'] = AutoId.newId();\n\n const databaseId = this._firestore._databaseId.database;\n const projectId = this._firestore._databaseId.projectId;\n const parent = `projects/${projectId}/databases/${databaseId}/documents`;\n const documents: Document[] = [];\n const documentData: DocumentData[] = [];\n const paths: string[] = [];\n\n this.docs.forEach(doc => {\n if (doc._document === null) {\n return;\n }\n documents.push(doc._document);\n documentData.push(\n this._userDataWriter.convertObjectMap(\n doc._document.data.value.mapValue.fields,\n 'previous'\n )\n );\n paths.push(doc.ref.path);\n });\n result['bundle'] = buildQuerySnapshotJsonBundle(\n this._firestore,\n this.query._query,\n result['bundleName'],\n parent,\n paths,\n documents,\n documentData\n );\n return result;\n }\n}\n\n/**\n * Builds a `QuerySnapshot` instance from a JSON object created by\n * {@link QuerySnapshot.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json - a JSON object represention of a `QuerySnapshot` instance.\n * @returns an instance of {@link QuerySnapshot} if the JSON object could be\n * parsed. Throws a {@link FirestoreError} if an error occurs.\n */\nexport function querySnapshotFromJSON(\n db: Firestore,\n json: object\n): QuerySnapshot;\n/**\n * Builds a `QuerySnapshot` instance from a JSON object created by\n * {@link QuerySnapshot.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json - a JSON object represention of a `QuerySnapshot` instance.\n * @param converter - Converts objects to and from Firestore.\n * @returns an instance of {@link QuerySnapshot} if the JSON object could be\n * parsed. Throws a {@link FirestoreError} if an error occurs.\n */\nexport function querySnapshotFromJSON<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n>(\n db: Firestore,\n json: object,\n converter: FirestoreDataConverter\n): QuerySnapshot;\nexport function querySnapshotFromJSON<\n AppModelType,\n DbModelType extends DocumentData\n>(\n db: Firestore,\n json: object,\n converter?: FirestoreDataConverter\n): QuerySnapshot {\n if (validateJSON(json, QuerySnapshot._jsonSchema)) {\n if (json.bundle === NOT_SUPPORTED) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'The provided JSON object was created in a client environment, which is not supported.'\n );\n }\n // Parse the bundle data.\n const serializer = newSerializer(db._databaseId);\n const bundleReader = createBundleReaderSync(json.bundle, serializer);\n const elements = bundleReader.getElements();\n const bundleLoader: BundleLoader = new BundleLoader(\n bundleReader.getMetadata(),\n serializer\n );\n for (const element of elements) {\n bundleLoader.addSizedElement(element);\n }\n\n if (bundleLoader.queries.length !== 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Snapshot data expected 1 query but found ${bundleLoader.queries.length} queries.`\n );\n }\n\n // Create an internal Query object from the named query in the bundle.\n const query = fromBundledQuery(bundleLoader.queries[0].bundledQuery!);\n\n // Construct the arrays of document data for the query.\n const bundledDocuments = bundleLoader.documents;\n let documentSet = new DocumentSet();\n bundledDocuments.map(bundledDocument => {\n const document = fromDocument(serializer, bundledDocument.document!);\n documentSet = documentSet.add(document);\n });\n // Create a view snapshot of the query and documents.\n const viewSnapshot = ViewSnapshot.fromInitialDocuments(\n query,\n documentSet,\n documentKeySet() /* Zero mutated keys signifies no pending writes. */,\n /* fromCache= */ false,\n /* hasCachedResults= */ false\n );\n\n // Create an external Query object, required to construct the QuerySnapshot.\n const externalQuery = new Query(\n db,\n converter ? converter : null,\n query\n );\n\n // Return a new QuerySnapshot with all of the collected data.\n return new QuerySnapshot(\n db,\n new LiteUserDataWriter(db),\n externalQuery,\n viewSnapshot\n );\n }\n throw new FirestoreError(\n Code.INTERNAL,\n 'Unexpected error creating QuerySnapshot from JSON.'\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(0xf03d, '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 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 build JSON bundle implementations. */\nimport { Firestore } from '../../api/database';\nimport { Query } from '../../core/query';\nimport { DocumentData } from '../../lite-api/reference';\nimport { Document } from '../../model/document';\n\nexport function buildDocumentSnapshotJsonBundle(\n db: Firestore,\n document: Document,\n docData: DocumentData,\n path: string\n): string {\n return 'NOT SUPPORTED';\n}\n\nexport function buildQuerySnapshotJsonBundle(\n db: Firestore,\n query: Query,\n bundleName: string,\n parent: string,\n paths: string[],\n docs: Document[],\n documentData: DocumentData[]\n): string {\n return 'NOT SUPPORTED';\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 { loadBundle, namedQuery } from '../api/database';\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 { DocumentKey } from '../model/document_key';\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { debugAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport {\n DocumentSnapshot,\n FirestoreDataConverter,\n QuerySnapshot,\n SnapshotMetadata\n} 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @returns An unsubscribe function that can be called to cancel 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @returns An unsubscribe function that can be called to cancel 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The\n * listener can be cancelled by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The\n * listener can be cancelled by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The\n * listener can be cancelled by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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` is available.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @returns An unsubscribe function that can be called to cancel 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The\n * listener can be cancelled by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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` is available.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @returns An unsubscribe function that can be called to cancel 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 // onSnapshot for Query or Document.\n reference = getModularInstance(reference);\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 }\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 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/**\n * Attaches a listener for `QuerySnapshot` events based on data generated by invoking\n * {@link QuerySnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks or\n * pass a single observer 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 never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}.\n * @param onNext - A callback to be called every time a new `QuerySnapshot` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n onNext: (snapshot: QuerySnapshot) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void,\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking\n * {@link DocumentSnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or\n * pass a single observer 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 never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}.\n * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are\n * never ending.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n onNext: (snapshot: DocumentSnapshot) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void,\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events based on data generated by invoking\n * {@link QuerySnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or\n * pass a single observer 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 never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param onNext - A callback to be called every time a new `QuerySnapshot` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n options: SnapshotListenOptions,\n onNext: (snapshot: QuerySnapshot) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void,\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking\n * {@link DocumentSnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks\n * or pass a single observer object with `next` and `error` callbacks. The listener can be cancelled\n * by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n options: SnapshotListenOptions,\n onNext: (snapshot: DocumentSnapshot) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void,\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events based on QuerySnapshot data generated by invoking\n * {@link QuerySnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or\n * pass a single observer 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 never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n observer: {\n next: (snapshot: QuerySnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n },\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking\n * {@link DocumentSnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks\n * or pass a single observer object with `next` and `error` callbacks. The listener can be cancelled\n * by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n observer: {\n next: (snapshot: DocumentSnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n },\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events based on QuerySnapshot data generated by invoking\n * {@link QuerySnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks or\n * pass a single observer 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 never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n options: SnapshotListenOptions,\n observer: {\n next: (snapshot: QuerySnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n },\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events based on QuerySnapshot data generated by\n * invoking {@link DocumentSnapshot.toJSON} You may either pass individual `onNext` and `onError`\n * callbacks or pass a single observer object with `next` and `error` callbacks. The listener can be\n * cancelled by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n options: SnapshotListenOptions,\n observer: {\n next: (snapshot: DocumentSnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n },\n converter?: FirestoreDataConverter\n): Unsubscribe;\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(reference: Firestore, snapshotJson: object, ...args: unknown[]): Unsubscribe {\n const db = getModularInstance(reference);\n const json = normalizeSnapshotJsonFields(snapshotJson);\n if (json.error) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, json.error);\n }\n let curArg = 0;\n let options: SnapshotListenOptions | undefined = undefined;\n if (typeof args[curArg] === 'object' && !isPartialObserver(args[curArg])) {\n options = args[curArg++] as SnapshotListenOptions;\n }\n\n if (json.bundleSource === 'QuerySnapshot') {\n let observer: {\n next: (snapshot: QuerySnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n } | null = null;\n if (typeof args[curArg] === 'object' && isPartialObserver(args[curArg])) {\n const userObserver = args[curArg++] as PartialObserver<\n QuerySnapshot\n >;\n observer = {\n next: userObserver.next!,\n error: userObserver.error,\n complete: userObserver.complete\n };\n } else {\n observer = {\n next: args[curArg++] as (\n snapshot: QuerySnapshot\n ) => void,\n error: args[curArg++] as (error: FirestoreError) => void,\n complete: args[curArg++] as () => void\n };\n }\n return onSnapshotQuerySnapshotBundle(\n db,\n json,\n options,\n observer!,\n args[curArg] as FirestoreDataConverter\n );\n } else if (json.bundleSource === 'DocumentSnapshot') {\n let observer: {\n next: (snapshot: DocumentSnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n } | null = null;\n if (typeof args[curArg] === 'object' && isPartialObserver(args[curArg])) {\n const userObserver = args[curArg++] as PartialObserver<\n DocumentSnapshot\n >;\n observer = {\n next: userObserver.next!,\n error: userObserver.error,\n complete: userObserver.complete\n };\n } else {\n observer = {\n next: args[curArg++] as (\n snapshot: DocumentSnapshot\n ) => void,\n error: args[curArg++] as (error: FirestoreError) => void,\n complete: args[curArg++] as () => void\n };\n }\n return onSnapshotDocumentSnapshotBundle(\n db,\n json,\n options,\n observer!,\n args[curArg] as FirestoreDataConverter\n );\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `unsupported bundle source: ${json.bundleSource}`\n );\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/**\n * Ensures the data required to construct an {@link onSnapshot} listener exist in a `snapshotJson`\n * object that originates from {@link DocumentSnapshot.toJSON} or {@link Querysnapshot.toJSON}. The\n * data is normalized into a typed object.\n *\n * @param snapshotJson - The JSON object that the app provided to {@link onSnapshot}.\n * @returns A normalized object that contains all of the required bundle JSON fields. If\n * {@link snapshotJson} doesn't contain the required fields, or if the fields exist as empty\n * strings, then the {@link snapshotJson.error} field will be a non empty string.\n *\n * @internal\n */\nfunction normalizeSnapshotJsonFields(snapshotJson: object): {\n bundle: string;\n bundleName: string;\n bundleSource: string;\n error?: string;\n} {\n const result: {\n bundle: string;\n bundleName: string;\n bundleSource: string;\n error?: string;\n } = {\n bundle: '',\n bundleName: '',\n bundleSource: ''\n };\n const requiredKeys = ['bundle', 'bundleName', 'bundleSource'];\n for (const key of requiredKeys) {\n if (!(key in snapshotJson)) {\n result.error = `snapshotJson missing required field: ${key}`;\n break;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const value = (snapshotJson as any)[key];\n if (typeof value !== 'string') {\n result.error = `snapshotJson field '${key}' must be a string.`;\n break;\n }\n if (value.length === 0) {\n result.error = `snapshotJson field '${key}' cannot be an empty string.`;\n break;\n }\n if (key === 'bundle') {\n result.bundle = value;\n } else if (key === 'bundleName') {\n result.bundleName = value;\n } else if (key === 'bundleSource') {\n result.bundleSource = value;\n }\n }\n return result;\n}\n\n/**\n * Loads the bundle in a separate task and then invokes {@link onSnapshot} with a\n * {@link DocumentReference} for the document in the bundle.\n *\n * @param firestore - The {@link Firestore} instance for the {@link onSnapshot} operation request.\n * @param json - The JSON bundle to load, produced by {@link DocumentSnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot\n * listener.\n *\n * @internal\n */\nfunction onSnapshotDocumentSnapshotBundle<\n AppModelType,\n DbModelType extends DocumentData\n>(\n db: Firestore,\n json: { bundle: string; bundleName: string; bundleSource: string },\n options: SnapshotListenOptions | undefined,\n observer: {\n next: (snapshot: DocumentSnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n },\n converter?: FirestoreDataConverter\n): Unsubscribe {\n let unsubscribed: boolean = false;\n let internalUnsubscribe: Unsubscribe | undefined;\n const loadTask = loadBundle(db, json.bundle);\n loadTask\n .then(() => {\n if (!unsubscribed) {\n const docReference = new DocumentReference(\n db,\n converter ? converter : null,\n DocumentKey.fromPath(json.bundleName)\n );\n internalUnsubscribe = onSnapshot(\n docReference as DocumentReference,\n options ? options : {},\n observer\n );\n }\n })\n .catch(e => {\n if (observer.error) {\n observer.error(e);\n }\n return () => {};\n });\n return () => {\n if (unsubscribed) {\n return;\n }\n unsubscribed = true;\n if (internalUnsubscribe) {\n internalUnsubscribe();\n }\n };\n}\n\n/**\n * Loads the bundle in a separate task and then invokes {@link onSnapshot} with a\n * {@link Query} that represents the Query in the bundle.\n *\n * @param firestore - The {@link Firestore} instance for the {@link onSnapshot} operation request.\n * @param json - The JSON bundle to load, produced by {@link QuerySnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot\n * listener.\n *\n * @internal\n */\nfunction onSnapshotQuerySnapshotBundle<\n AppModelType,\n DbModelType extends DocumentData\n>(\n db: Firestore,\n json: { bundle: string; bundleName: string; bundleSource: string },\n options: SnapshotListenOptions | undefined,\n observer: {\n next: (snapshot: QuerySnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n },\n converter?: FirestoreDataConverter\n): Unsubscribe {\n let unsubscribed: boolean = false;\n let internalUnsubscribe: Unsubscribe | undefined;\n const loadTask = loadBundle(db, json.bundle);\n loadTask\n .then(() => namedQuery(db, json.bundleName))\n .then(query => {\n if (query && !unsubscribed) {\n const realQuery: Query = (query as Query)!;\n if (converter) {\n realQuery.withConverter(converter);\n }\n internalUnsubscribe = onSnapshot(\n query as Query,\n options ? options : {},\n observer\n );\n }\n })\n .catch(e => {\n if (observer.error) {\n observer.error(e);\n }\n return () => {};\n });\n return () => {\n if (unsubscribed) {\n return;\n }\n unsubscribed = true;\n if (internalUnsubscribe) {\n internalUnsubscribe();\n }\n };\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AggregateField, AggregateSpec, DocumentData, Query } from '../api';\nimport { AggregateImpl } from '../core/aggregate';\nimport { firestoreClientRunAggregateQuery } from '../core/firestore_client';\nimport { count } from '../lite-api/aggregate';\nimport { AggregateQuerySnapshot } from '../lite-api/aggregate_types';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport { ExpUserDataWriter } from './reference_impl';\n\nexport {\n aggregateQuerySnapshotEqual,\n count,\n sum,\n average,\n aggregateFieldEqual\n} from '../lite-api/aggregate';\n\n/**\n * Calculates the number of documents in the result set of the given query\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can\n * count the documents in cases where the result set is prohibitively large to\n * download entirely (thousands of documents).\n *\n * The result received from the server is presented, unaltered, without\n * considering any local state. That is, documents in the local cache are not\n * taken into consideration, neither are local modifications not yet\n * synchronized with the server. Previously-downloaded results, if any, are not\n * used. Every invocation of this function necessarily involves a round trip to\n * the server.\n *\n * @param query The query whose result set size is calculated.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */\nexport function getCountFromServer<\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query\n): Promise<\n AggregateQuerySnapshot<\n { count: AggregateField },\n AppModelType,\n DbModelType\n >\n> {\n const countQuerySpec: { count: AggregateField } = {\n count: count()\n };\n\n return getAggregateFromServer(query, countQuerySpec);\n}\n\n/**\n * Calculates the specified aggregations over the documents in the result\n * set of the given query without actually downloading the documents.\n *\n * Using this function to perform aggregations is efficient because only the\n * final aggregation values, not the documents' data, are downloaded. This\n * function can perform aggregations of the documents in cases where the result\n * set is prohibitively large to download entirely (thousands of documents).\n *\n * The result received from the server is presented, unaltered, without\n * considering any local state. That is, documents in the local cache are not\n * taken into consideration, neither are local modifications not yet\n * synchronized with the server. Previously-downloaded results, if any, are not\n * used. Every invocation of this function necessarily involves a round trip to\n * the server.\n *\n * @param query The query whose result set is aggregated over.\n * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates\n * to perform over the result set. The AggregateSpec specifies aliases for each\n * aggregate, which can be used to retrieve the aggregate result.\n * @example\n * ```typescript\n * const aggregateSnapshot = await getAggregateFromServer(query, {\n * countOfDocs: count(),\n * totalHours: sum('hours'),\n * averageScore: average('score')\n * });\n *\n * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;\n * const totalHours: number = aggregateSnapshot.data().totalHours;\n * const averageScore: number | null = aggregateSnapshot.data().averageScore;\n * ```\n */\nexport function getAggregateFromServer<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n aggregateSpec: AggregateSpecType\n): Promise<\n AggregateQuerySnapshot\n> {\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n\n const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n\n // Run the aggregation and convert the results\n return firestoreClientRunAggregateQuery(\n client,\n query._query,\n internalAggregates\n ).then(aggregateResult =>\n convertToAggregateQuerySnapshot(firestore, query, aggregateResult)\n );\n}\n\n/**\n * Converts the core aggregation result to an `AggregateQuerySnapshot`\n * that can be returned to the consumer.\n * @param query\n * @param aggregateResult Core aggregation result\n * @internal\n */\nfunction convertToAggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n query: Query,\n aggregateResult: ApiClientObjectMap\n): AggregateQuerySnapshot {\n const userDataWriter = new ExpUserDataWriter(firestore);\n const querySnapshot = new AggregateQuerySnapshot<\n AggregateSpecType,\n AppModelType,\n DbModelType\n >(query, userDataWriter, aggregateResult);\n return querySnapshot;\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 IndexedDbOfflineComponentProvider,\n LruGcMemoryOfflineComponentProvider,\n MemoryOfflineComponentProvider,\n MultiTabOfflineComponentProvider,\n OfflineComponentProviderFactory,\n OnlineComponentProviderFactory,\n OnlineComponentProvider\n} from '../core/component_provider';\n\n/* eslint @typescript-eslint/consistent-type-definitions: [\"error\", \"type\"] */\n/**\n * Provides an in-memory cache to the SDK. This is the default cache unless explicitly\n * configured otherwise.\n *\n * To use, create an instance using the factory function {@link memoryLocalCache()}, then\n * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using\n * the settings object.\n */\nexport type MemoryLocalCache = {\n kind: 'memory';\n /**\n * @internal\n */\n _onlineComponentProvider: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n};\n\nclass MemoryLocalCacheImpl implements MemoryLocalCache {\n kind: 'memory' = 'memory';\n /**\n * @internal\n */\n _onlineComponentProvider: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n\n constructor(settings?: MemoryCacheSettings) {\n this._onlineComponentProvider = OnlineComponentProvider.provider;\n if (settings?.garbageCollector) {\n this._offlineComponentProvider =\n settings.garbageCollector._offlineComponentProvider;\n } else {\n this._offlineComponentProvider = {\n build: () => new LruGcMemoryOfflineComponentProvider(undefined)\n };\n }\n }\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n}\n\n/**\n * Provides a persistent cache backed by IndexedDb to the SDK.\n *\n * To use, create an instance using the factory function {@link persistentLocalCache()}, then\n * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using\n * the settings object.\n */\nexport type PersistentLocalCache = {\n kind: 'persistent';\n /**\n * @internal\n */\n _onlineComponentProvider: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n};\n\nclass PersistentLocalCacheImpl implements PersistentLocalCache {\n kind: 'persistent' = 'persistent';\n /**\n * @internal\n */\n _onlineComponentProvider: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n\n constructor(settings: PersistentCacheSettings | undefined) {\n let tabManager: PersistentTabManager;\n if (settings?.tabManager) {\n settings.tabManager._initialize(settings);\n tabManager = settings.tabManager;\n } else {\n tabManager = persistentSingleTabManager(undefined);\n tabManager._initialize(settings);\n }\n this._onlineComponentProvider = tabManager._onlineComponentProvider!;\n this._offlineComponentProvider = tabManager._offlineComponentProvider!;\n }\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n}\n\n/**\n * Union type from all supported SDK cache layer.\n */\nexport type FirestoreLocalCache = MemoryLocalCache | PersistentLocalCache;\n\n/**\n * Union type from all support garbage collectors for memory local cache.\n */\nexport type MemoryGarbageCollector =\n | MemoryEagerGarbageCollector\n | MemoryLruGarbageCollector;\n\n/**\n * A garbage collector deletes documents whenever they are not part of any\n * active queries, and have no local mutations attached to them.\n *\n * This collector tries to ensure lowest memory footprints from the SDK,\n * at the risk of documents not being cached for offline queries or for\n * direct queries to the cache.\n *\n * Use factory function {@link memoryEagerGarbageCollector()} to create an\n * instance of this collector.\n */\nexport type MemoryEagerGarbageCollector = {\n kind: 'memoryEager';\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n};\n\n/**\n * A garbage collector deletes Least-Recently-Used documents in multiple\n * batches.\n *\n * This collector is configured with a target size, and will only perform\n * collection when the cached documents exceed the target size. It avoids\n * querying backend repeated for the same query or document, at the risk\n * of having a larger memory footprint.\n *\n * Use factory function {@link memoryLruGarbageCollector()} to create a\n * instance of this collector.\n */\nexport type MemoryLruGarbageCollector = {\n kind: 'memoryLru';\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n};\n\nclass MemoryEagerGarbageCollectorImpl implements MemoryEagerGarbageCollector {\n kind: 'memoryEager' = 'memoryEager';\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n\n constructor() {\n this._offlineComponentProvider = MemoryOfflineComponentProvider.provider;\n }\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n}\n\nclass MemoryLruGarbageCollectorImpl implements MemoryLruGarbageCollector {\n kind: 'memoryLru' = 'memoryLru';\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n\n constructor(cacheSize?: number) {\n this._offlineComponentProvider = {\n build: () => new LruGcMemoryOfflineComponentProvider(cacheSize)\n };\n }\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n}\n\n/**\n * Creates an instance of `MemoryEagerGarbageCollector`. This is also the\n * default garbage collector unless it is explicitly specified otherwise.\n */\nexport function memoryEagerGarbageCollector(): MemoryEagerGarbageCollector {\n return new MemoryEagerGarbageCollectorImpl();\n}\n\n/**\n * Creates an instance of `MemoryLruGarbageCollector`.\n *\n * A target size can be specified as part of the setting parameter. The\n * collector will start deleting documents once the cache size exceeds\n * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes).\n */\nexport function memoryLruGarbageCollector(settings?: {\n cacheSizeBytes?: number;\n}): MemoryLruGarbageCollector {\n return new MemoryLruGarbageCollectorImpl(settings?.cacheSizeBytes);\n}\n\n/**\n * An settings object to configure an `MemoryLocalCache` instance.\n */\nexport type MemoryCacheSettings = {\n /**\n * The garbage collector to use, for the memory cache layer.\n * A `MemoryEagerGarbageCollector` is used when this is undefined.\n */\n garbageCollector?: MemoryGarbageCollector;\n};\n\n/**\n * Creates an instance of `MemoryLocalCache`. The instance can be set to\n * `FirestoreSettings.cache` to tell the SDK which cache layer to use.\n */\nexport function memoryLocalCache(\n settings?: MemoryCacheSettings\n): MemoryLocalCache {\n return new MemoryLocalCacheImpl(settings);\n}\n\n/**\n * An settings object to configure an `PersistentLocalCache` instance.\n *\n * Persistent cache cannot be used in a Node.js environment.\n */\nexport type PersistentCacheSettings = {\n /**\n * An approximate cache size threshold for the on-disk data. If the cache\n * grows beyond this size, Firestore will start removing data that hasn't been\n * recently used. The SDK does not guarantee that the cache will stay below\n * that size, only that if the cache exceeds the given size, cleanup will be\n * attempted.\n *\n * The default value is 40 MB. The threshold must be set to at least 1 MB, and\n * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection.\n */\n cacheSizeBytes?: number;\n\n /**\n * Specifies how multiple tabs/windows will be managed by the SDK.\n */\n tabManager?: PersistentTabManager;\n};\n\n/**\n * Creates an instance of `PersistentLocalCache`. The instance can be set to\n * `FirestoreSettings.cache` to tell the SDK which cache layer to use.\n *\n * Persistent cache cannot be used in a Node.js environment.\n */\nexport function persistentLocalCache(\n settings?: PersistentCacheSettings\n): PersistentLocalCache {\n return new PersistentLocalCacheImpl(settings);\n}\n\n/**\n * A tab manager supporting only one tab, no synchronization will be\n * performed across tabs.\n */\nexport type PersistentSingleTabManager = {\n kind: 'persistentSingleTab';\n /**\n * @internal\n */\n _initialize: (\n settings: Omit | undefined\n ) => void;\n /**\n * @internal\n */\n _onlineComponentProvider?: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider?: OfflineComponentProviderFactory;\n};\n\nclass SingleTabManagerImpl implements PersistentSingleTabManager {\n kind: 'persistentSingleTab' = 'persistentSingleTab';\n\n /**\n * @internal\n */\n _onlineComponentProvider?: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider?: OfflineComponentProviderFactory;\n\n constructor(private forceOwnership?: boolean) {}\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n\n /**\n * @internal\n */\n _initialize(\n settings: Omit | undefined\n ): void {\n this._onlineComponentProvider = OnlineComponentProvider.provider;\n this._offlineComponentProvider = {\n build: (onlineComponents: OnlineComponentProvider) =>\n new IndexedDbOfflineComponentProvider(\n onlineComponents,\n settings?.cacheSizeBytes,\n this.forceOwnership\n )\n };\n }\n}\n\n/**\n * A tab manager supporting multiple tabs. SDK will synchronize queries and\n * mutations done across all tabs using the SDK.\n */\nexport type PersistentMultipleTabManager = {\n kind: 'PersistentMultipleTab';\n /**\n * @internal\n */\n _initialize: (settings: Omit) => void;\n /**\n * @internal\n */\n _onlineComponentProvider?: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n\n _offlineComponentProvider?: OfflineComponentProviderFactory;\n};\n\nclass MultiTabManagerImpl implements PersistentMultipleTabManager {\n kind: 'PersistentMultipleTab' = 'PersistentMultipleTab';\n\n /**\n * @internal\n */\n _onlineComponentProvider?: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider?: OfflineComponentProviderFactory;\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n\n /**\n * @internal\n */\n _initialize(\n settings: Omit | undefined\n ): void {\n this._onlineComponentProvider = OnlineComponentProvider.provider;\n this._offlineComponentProvider = {\n build: (onlineComponents: OnlineComponentProvider) =>\n new MultiTabOfflineComponentProvider(\n onlineComponents,\n settings?.cacheSizeBytes\n )\n };\n }\n}\n\n/**\n * A union of all available tab managers.\n */\nexport type PersistentTabManager =\n | PersistentSingleTabManager\n | PersistentMultipleTabManager;\n\n/**\n * Type to configure an `PersistentSingleTabManager` instance.\n */\nexport type PersistentSingleTabManagerSettings = {\n /**\n * Whether to force-enable persistent (IndexedDB) cache for the client. This\n * cannot be used with multi-tab synchronization and is primarily intended for\n * use with Web Workers. Setting this to `true` will enable IndexedDB, but cause\n * other tabs using IndexedDB cache to fail.\n */\n forceOwnership?: boolean;\n};\n/**\n * Creates an instance of `PersistentSingleTabManager`.\n *\n * @param settings Configures the created tab manager.\n */\nexport function persistentSingleTabManager(\n settings: PersistentSingleTabManagerSettings | undefined\n): PersistentSingleTabManager {\n return new SingleTabManagerImpl(settings?.forceOwnership);\n}\n\n/**\n * Creates an instance of `PersistentMultipleTabManager`.\n */\nexport function persistentMultipleTabManager(): PersistentMultipleTabManager {\n return new MultiTabManagerImpl();\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\n\nexport const DEFAULT_TRANSACTION_OPTIONS: TransactionOptions = {\n maxAttempts: 5\n};\n\n/**\n * Options to customize transaction behavior.\n */\nexport declare interface TransactionOptions {\n /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */\n readonly maxAttempts: number;\n}\n\nexport function validateTransactionOptions(options: TransactionOptions): void {\n if (options.maxAttempts < 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Max attempts must be at least 1'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Compat, getModularInstance } from '@firebase/util';\n\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { invokeCommitRpc } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport { applyFirestoreDataConverter } from './reference_impl';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\n\n/**\n * A write batch, used to perform multiple writes as a single atomic unit.\n *\n * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It\n * provides methods for adding writes to the write batch. None of the writes\n * will be committed (or visible locally) until {@link WriteBatch.commit} is\n * called.\n */\nexport class WriteBatch {\n // This is the lite version of the WriteBatch API used in the legacy SDK. The\n // class is a close copy but takes different input types.\n\n private readonly _dataReader: UserDataReader;\n private _mutations = [] as Mutation[];\n private _committed = false;\n\n /** @hideconstructor */\n constructor(\n private readonly _firestore: Firestore,\n private readonly _commitHandler: (m: Mutation[]) => Promise\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): WriteBatch;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): WriteBatch;\n set(\n documentRef: DocumentReference,\n data: WithFieldValue | PartialWithFieldValue,\n options?: SetOptions\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n data,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'WriteBatch.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._mutations.push(parsed.toMutation(ref._key, Precondition.none()));\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): WriteBatch;\n /**\n * Updates fields in the document referred to by this {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be update by providing dot-separated field path strings\n * or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._mutations.push(\n parsed.toMutation(ref._key, Precondition.exists(true))\n );\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n this._mutations = this._mutations.concat(\n new DeleteMutation(ref._key, Precondition.none())\n );\n return this;\n }\n\n /**\n * Commits all of the writes in this write batch as a single atomic unit.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `Promise` resolved once all of the writes in the batch have been\n * successfully written to the backend as an atomic unit (note that it won't\n * resolve while you're offline).\n */\n commit(): Promise {\n this._verifyNotCommitted();\n this._committed = true;\n if (this._mutations.length > 0) {\n return this._commitHandler(this._mutations);\n }\n\n return Promise.resolve();\n }\n\n private _verifyNotCommitted(): void {\n if (this._committed) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A write batch can no longer be used after commit() ' +\n 'has been called.'\n );\n }\n }\n}\n\nexport function validateReference<\n AppModelType,\n DbModelType extends DocumentData\n>(\n documentRef:\n | DocumentReference\n | Compat>,\n firestore: Firestore\n): DocumentReference {\n documentRef = getModularInstance(documentRef);\n\n if (documentRef.firestore !== firestore) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Provided document reference is from a different Firestore instance.'\n );\n } else {\n return documentRef as DocumentReference;\n }\n}\n\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single WriteBatch\n * is 500.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `WriteBatch` that can be used to atomically execute multiple\n * writes.\n */\nexport function writeBatch(firestore: Firestore): WriteBatch {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n return new WriteBatch(firestore, writes =>\n invokeCommitRpc(datastore, writes)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport {\n DEFAULT_TRANSACTION_OPTIONS,\n TransactionOptions as TransactionOptionsInternal,\n validateTransactionOptions\n} from '../core/transaction_options';\nimport { TransactionRunner } from '../core/transaction_runner';\nimport { fail } from '../util/assert';\nimport { newAsyncQueue } from '../util/async_queue_impl';\nimport { cast } from '../util/input_validation';\nimport { Deferred } from '../util/promise';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n applyFirestoreDataConverter,\n LiteUserDataWriter\n} from './reference_impl';\nimport { DocumentSnapshot } from './snapshot';\nimport { TransactionOptions } from './transaction_options';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\nimport { validateReference } from './write_batch';\n\n// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the\n// legacy SDK.\n\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nexport class Transaction {\n // This is the tree-shakeable version of the Transaction class used in the\n // legacy SDK. The class is a close copy but takes different input and output\n // types. The firestore-exp SDK further extends this class to return its API\n // type.\n\n private readonly _dataReader: UserDataReader;\n\n /** @hideconstructor */\n constructor(\n protected readonly _firestore: Firestore,\n private readonly _transaction: InternalTransaction\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */\n get(\n documentRef: DocumentReference\n ): Promise> {\n const ref = validateReference(documentRef, this._firestore);\n const userDataWriter = new LiteUserDataWriter(this._firestore);\n return this._transaction.lookup([ref._key]).then(docs => {\n if (!docs || docs.length !== 1) {\n return fail(0x5de9, 'Mismatch in docs returned from document lookup.');\n }\n const doc = docs[0];\n if (doc.isFoundDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n doc.key,\n doc,\n ref.converter\n );\n } else if (doc.isNoDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n ref._key,\n null,\n ref.converter\n );\n } else {\n throw fail(\n 0x4801,\n 'BatchGetDocumentsRequest returned unexpected document',\n {\n doc\n }\n );\n }\n });\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): this;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): this;\n set(\n documentRef: DocumentReference,\n value: PartialWithFieldValue,\n options?: SetOptions\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n value,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'Transaction.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._transaction.set(ref._key, parsed);\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): this;\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key/value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._transaction.update(ref._key, parsed);\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n this._transaction.delete(ref._key);\n return this;\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */\nexport function runTransaction(\n firestore: Firestore,\n updateFunction: (transaction: Transaction) => Promise,\n options?: TransactionOptions\n): Promise {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n const optionsWithDefaults: TransactionOptionsInternal = {\n ...DEFAULT_TRANSACTION_OPTIONS,\n ...options\n };\n validateTransactionOptions(optionsWithDefaults);\n const deferred = new Deferred();\n new TransactionRunner(\n newAsyncQueue(),\n datastore,\n optionsWithDefaults,\n internalTransaction =>\n updateFunction(new Transaction(firestore, internalTransaction)),\n deferred\n ).run();\n return deferred.promise;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { firestoreClientTransaction } from '../core/firestore_client';\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport {\n TransactionOptions as TransactionOptionsInternal,\n DEFAULT_TRANSACTION_OPTIONS,\n validateTransactionOptions\n} from '../core/transaction_options';\nimport { DocumentData, DocumentReference } from '../lite-api/reference';\nimport { Transaction as LiteTransaction } from '../lite-api/transaction';\nimport { validateReference } from '../lite-api/write_batch';\nimport { cast } from '../util/input_validation';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport { ExpUserDataWriter } from './reference_impl';\nimport { DocumentSnapshot, SnapshotMetadata } from './snapshot';\nimport { TransactionOptions } from './transaction_options';\n\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nexport class Transaction extends LiteTransaction {\n // This class implements the same logic as the Transaction API in the Lite SDK\n // but is subclassed in order to return its own DocumentSnapshot types.\n\n /** @hideconstructor */\n constructor(\n protected readonly _firestore: Firestore,\n _transaction: InternalTransaction\n ) {\n super(_firestore, _transaction);\n }\n\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */\n get(\n documentRef: DocumentReference\n ): Promise> {\n const ref = validateReference(documentRef, this._firestore);\n const userDataWriter = new ExpUserDataWriter(this._firestore);\n return super\n .get(documentRef)\n .then(\n liteDocumentSnapshot =>\n new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n ref._key,\n liteDocumentSnapshot._document,\n new SnapshotMetadata(\n /* hasPendingWrites= */ false,\n /* fromCache= */ false\n ),\n ref.converter\n )\n );\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */\nexport function runTransaction(\n firestore: Firestore,\n updateFunction: (transaction: Transaction) => Promise,\n options?: TransactionOptions\n): Promise {\n firestore = cast(firestore, Firestore);\n const optionsWithDefaults: TransactionOptionsInternal = {\n ...DEFAULT_TRANSACTION_OPTIONS,\n ...options\n };\n validateTransactionOptions(optionsWithDefaults);\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientTransaction(\n client,\n internalTransaction =>\n updateFunction(new Transaction(firestore, internalTransaction)),\n optionsWithDefaults\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldValue } from './field_value';\nimport {\n ArrayRemoveFieldValueImpl,\n ArrayUnionFieldValueImpl,\n DeleteFieldValueImpl,\n NumericIncrementFieldValueImpl,\n ServerTimestampFieldValueImpl\n} from './user_data_reader';\nimport { VectorValue } from './vector_value';\n\n/**\n * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or\n * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.\n */\nexport function deleteField(): FieldValue {\n return new DeleteFieldValueImpl('deleteField');\n}\n\n/**\n * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to\n * include a server-generated timestamp in the written data.\n */\nexport function serverTimestamp(): FieldValue {\n return new ServerTimestampFieldValueImpl('serverTimestamp');\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array\n * value that already exists on the server. Each specified element that doesn't\n * already exist in the array will be added to the end. If the field being\n * modified is not already an array it will be overwritten with an array\n * containing exactly the specified elements.\n *\n * @param elements - The elements to union into the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`.\n */\nexport function arrayUnion(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayUnionFieldValueImpl('arrayUnion', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link (setDoc:1)} or {@link\n * updateDoc:1} that tells the server to remove the given elements from any\n * array value that already exists on the server. All instances of each element\n * specified will be removed from the array. If the field being modified is not\n * already an array it will be overwritten with an empty array.\n *\n * @param elements - The elements to remove from the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function arrayRemove(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayRemoveFieldValueImpl('arrayRemove', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by\n * the given value.\n *\n * If either the operand or the current field value uses floating point\n * precision, all arithmetic follows IEEE 754 semantics. If both values are\n * integers, values outside of JavaScript's safe number range\n * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to\n * precision loss. Furthermore, once processed by the Firestore backend, all\n * integer operations are capped between -2^63 and 2^63-1.\n *\n * If the current field value is not of type `number`, or if the field does not\n * yet exist, the transformation sets the field to the given value.\n *\n * @param n - The value to increment by.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function increment(n: number): FieldValue {\n return new NumericIncrementFieldValueImpl('increment', n);\n}\n\n/**\n * Creates a new `VectorValue` constructed with a copy of the given array of numbers.\n *\n * @param values - Create a `VectorValue` instance with a copy of this array of numbers.\n *\n * @returns A new `VectorValue` constructed with a copy of the given array of numbers.\n */\nexport function vector(values?: number[]): VectorValue {\n return new VectorValue(values);\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 { WriteBatch } from '../lite-api/write_batch';\nimport { cast } from '../util/input_validation';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport { executeWrite } from './reference_impl';\n\nexport { WriteBatch };\n\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch}\n * is 500.\n *\n * Unlike transactions, write batches are persisted offline and therefore are\n * preferable when you don't need to condition your writes on read data.\n *\n * @returns A {@link WriteBatch} that can be used to atomically execute multiple\n * writes.\n */\nexport function writeBatch(firestore: Firestore): WriteBatch {\n firestore = cast(firestore, Firestore);\n ensureFirestoreConfigured(firestore);\n return new WriteBatch(firestore, mutations =>\n executeWrite(firestore, mutations)\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 { firestoreClientSetIndexConfiguration } from '../core/firestore_client';\nimport { fieldPathFromDotSeparatedString } from '../lite-api/user_data_reader';\nimport {\n FieldIndex,\n IndexKind,\n IndexSegment,\n IndexState\n} from '../model/field_index';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\nimport { logWarn } from '../util/log';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\n\nexport {\n connectFirestoreEmulator,\n EmulatorMockTokenOptions\n} from '../lite-api/database';\n\n/**\n * A single field element in an index configuration.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport interface IndexField {\n /** The field path to index. */\n readonly fieldPath: string;\n /**\n * What type of array index to create. Set to `CONTAINS` for `array-contains`\n * and `array-contains-any` indexes.\n *\n * Only one of `arrayConfig` or `order` should be set;\n */\n readonly arrayConfig?: 'CONTAINS';\n /**\n * What type of array index to create. Set to `ASCENDING` or 'DESCENDING` for\n * `==`, `!=`, `<=`, `<=`, `in` and `not-in` filters.\n *\n * Only one of `arrayConfig` or `order` should be set.\n */\n readonly order?: 'ASCENDING' | 'DESCENDING';\n\n [key: string]: unknown;\n}\n\n/**\n * The SDK definition of a Firestore index.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport interface Index {\n /** The ID of the collection to index. */\n readonly collectionGroup: string;\n /** A list of fields to index. */\n readonly fields?: IndexField[];\n\n [key: string]: unknown;\n}\n\n/**\n * A list of Firestore indexes to speed up local query execution.\n *\n * See {@link https://firebase.google.com/docs/reference/firestore/indexes/#json_format | JSON Format}\n * for a description of the format of the index definition.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport interface IndexConfiguration {\n /** A list of all Firestore indexes. */\n readonly indexes?: Index[];\n\n [key: string]: unknown;\n}\n\n/**\n * Configures indexing for local query execution. Any previous index\n * configuration is overridden. The `Promise` resolves once the index\n * configuration has been persisted.\n *\n * The index entries themselves are created asynchronously. You can continue to\n * use queries that require indexing even if the indices are not yet available.\n * Query execution will automatically start using the index once the index\n * entries have been written.\n *\n * Indexes are only supported with IndexedDb persistence. If IndexedDb is not\n * enabled, any index configuration is ignored.\n *\n * @param firestore - The {@link Firestore} instance to configure indexes for.\n * @param configuration -The index definition.\n * @throws FirestoreError if the JSON format is invalid.\n * @returns A `Promise` that resolves once all indices are successfully\n * configured.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport function setIndexConfiguration(\n firestore: Firestore,\n configuration: IndexConfiguration\n): Promise;\n\n/**\n * Configures indexing for local query execution. Any previous index\n * configuration is overridden. The `Promise` resolves once the index\n * configuration has been persisted.\n *\n * The index entries themselves are created asynchronously. You can continue to\n * use queries that require indexing even if the indices are not yet available.\n * Query execution will automatically start using the index once the index\n * entries have been written.\n *\n * Indexes are only supported with IndexedDb persistence. Invoke either\n * `enableIndexedDbPersistence()` or `enableMultiTabIndexedDbPersistence()`\n * before setting an index configuration. If IndexedDb is not enabled, any\n * index configuration is ignored.\n *\n * The method accepts the JSON format exported by the Firebase CLI (`firebase\n * firestore:indexes`). If the JSON format is invalid, this method throws an\n * error.\n *\n * @param firestore - The {@link Firestore} instance to configure indexes for.\n * @param json -The JSON format exported by the Firebase CLI.\n * @throws FirestoreError if the JSON format is invalid.\n * @returns A `Promise` that resolves once all indices are successfully\n * configured.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport function setIndexConfiguration(\n firestore: Firestore,\n json: string\n): Promise;\n\nexport function setIndexConfiguration(\n firestore: Firestore,\n jsonOrConfiguration: string | IndexConfiguration\n): Promise {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n if (\n !client._uninitializedComponentsProvider ||\n client._uninitializedComponentsProvider._offline.kind === 'memory'\n ) {\n // PORTING NOTE: We don't return an error if the user has not enabled\n // persistence since `enableIndexeddbPersistence()` can fail on the Web.\n logWarn('Cannot enable indexes when persistence is disabled');\n return Promise.resolve();\n }\n const parsedIndexes = parseIndexes(jsonOrConfiguration);\n return firestoreClientSetIndexConfiguration(client, parsedIndexes);\n}\n\nexport function parseIndexes(\n jsonOrConfiguration: string | IndexConfiguration\n): FieldIndex[] {\n const indexConfiguration =\n typeof jsonOrConfiguration === 'string'\n ? (tryParseJson(jsonOrConfiguration) as IndexConfiguration)\n : jsonOrConfiguration;\n const parsedIndexes: FieldIndex[] = [];\n\n if (Array.isArray(indexConfiguration.indexes)) {\n for (const index of indexConfiguration.indexes) {\n const collectionGroup = tryGetString(index, 'collectionGroup');\n\n const segments: IndexSegment[] = [];\n if (Array.isArray(index.fields)) {\n for (const field of index.fields) {\n const fieldPathString = tryGetString(field, 'fieldPath');\n const fieldPath = fieldPathFromDotSeparatedString(\n 'setIndexConfiguration',\n fieldPathString\n );\n\n if (field.arrayConfig === 'CONTAINS') {\n segments.push(new IndexSegment(fieldPath, IndexKind.CONTAINS));\n } else if (field.order === 'ASCENDING') {\n segments.push(new IndexSegment(fieldPath, IndexKind.ASCENDING));\n } else if (field.order === 'DESCENDING') {\n segments.push(new IndexSegment(fieldPath, IndexKind.DESCENDING));\n }\n }\n }\n\n parsedIndexes.push(\n new FieldIndex(\n FieldIndex.UNKNOWN_ID,\n collectionGroup,\n segments,\n IndexState.empty()\n )\n );\n }\n }\n return parsedIndexes;\n}\n\nfunction tryParseJson(json: string): Record {\n try {\n return JSON.parse(json);\n } catch (e) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Failed to parse JSON: ' + (e as Error)?.message\n );\n }\n}\n\nfunction tryGetString(data: Record, property: string): string {\n if (typeof data[property] !== 'string') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Missing string value for: ' + property\n );\n }\n return data[property] as string;\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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ensureFirestoreConfigured, Firestore } from '../api/database';\nimport { AggregateImpl } from '../core/aggregate';\nimport { queryToAggregateTarget, queryToTarget } from '../core/query';\nimport { AggregateSpec } from '../lite-api/aggregate_types';\nimport { Query } from '../lite-api/reference';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport { toQueryTarget, toRunAggregationQueryRequest } from './serializer';\n\n/**\n * @internal\n * @private\n *\n * This function is for internal use only.\n *\n * Returns the `QueryTarget` representation of the given query. Returns `null`\n * if the Firestore client associated with the given query has not been\n * initialized or has been terminated.\n *\n * @param query - The Query to convert to proto representation.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function _internalQueryToProtoQueryTarget(query: Query): any {\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const serializer = client._onlineComponents?.datastore.serializer;\n if (serializer === undefined) {\n return null;\n }\n return toQueryTarget(serializer!, queryToTarget(query._query)).queryTarget;\n}\n\n/**\n * @internal\n * @private\n *\n * This function is for internal use only.\n *\n * Returns `RunAggregationQueryRequest` which contains the proto representation\n * of the given aggregation query request. Returns null if the Firestore client\n * associated with the given query has not been initialized or has been\n * terminated.\n *\n * @param query - The Query to convert to proto representation.\n * @param aggregateSpec - The set of aggregations and their aliases.\n */\nexport function _internalAggregationQueryToProtoRunAggregationQueryRequest<\n AggregateSpecType extends AggregateSpec\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n>(query: Query, aggregateSpec: AggregateSpecType): any {\n const aggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const serializer = client._onlineComponents?.datastore.serializer;\n if (serializer === undefined) {\n return null;\n }\n\n return toRunAggregationQueryRequest(\n serializer!,\n queryToAggregateTarget(query._query),\n aggregates,\n /* skipAliasing= */ true\n ).request;\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 { Unsubscribe } from '../api/reference_impl';\n\nimport {\n setTestingHooksSpi,\n ExistenceFilterMismatchInfo,\n TestingHooksSpi\n} from './testing_hooks_spi';\n\n/**\n * Testing hooks for use by Firestore's integration test suite to reach into the\n * SDK internals to validate logic and behavior that is not visible from the\n * public API surface.\n *\n * @internal\n */\nexport class TestingHooks {\n private constructor() {\n throw new Error('instances of this class should not be created');\n }\n\n /**\n * Registers a callback to be notified when an existence filter mismatch\n * occurs in the Watch listen stream.\n *\n * The relative order in which callbacks are notified is unspecified; do not\n * rely on any particular ordering. If a given callback is registered multiple\n * times then it will be notified multiple times, once per registration.\n *\n * @param callback the callback to invoke upon existence filter mismatch.\n *\n * @return a function that, when called, unregisters the given callback; only\n * the first invocation of the returned function does anything; all subsequent\n * invocations do nothing.\n */\n static onExistenceFilterMismatch(\n callback: ExistenceFilterMismatchCallback\n ): Unsubscribe {\n return TestingHooksSpiImpl.instance.onExistenceFilterMismatch(callback);\n }\n}\n\n/**\n * The signature of callbacks registered with\n * `TestingUtils.onExistenceFilterMismatch()`.\n *\n * The return value, if any, is ignored.\n *\n * @internal\n */\nexport type ExistenceFilterMismatchCallback = (\n info: ExistenceFilterMismatchInfo\n) => unknown;\n\n/**\n * The implementation of `TestingHooksSpi`.\n */\nclass TestingHooksSpiImpl implements TestingHooksSpi {\n private readonly existenceFilterMismatchCallbacksById = new Map<\n Symbol,\n ExistenceFilterMismatchCallback\n >();\n\n private constructor() {}\n\n static get instance(): TestingHooksSpiImpl {\n if (!testingHooksSpiImplInstance) {\n testingHooksSpiImplInstance = new TestingHooksSpiImpl();\n setTestingHooksSpi(testingHooksSpiImplInstance);\n }\n return testingHooksSpiImplInstance;\n }\n\n notifyOnExistenceFilterMismatch(info: ExistenceFilterMismatchInfo): void {\n this.existenceFilterMismatchCallbacksById.forEach(callback =>\n callback(info)\n );\n }\n\n onExistenceFilterMismatch(\n callback: ExistenceFilterMismatchCallback\n ): Unsubscribe {\n const id = Symbol();\n const callbacks = this.existenceFilterMismatchCallbacksById;\n callbacks.set(id, callback);\n return () => callbacks.delete(id);\n }\n}\n\nlet testingHooksSpiImplInstance: TestingHooksSpiImpl | null = null;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 app,\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 esm, cjs, 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"],"names":["User","constructor","uid","this","isAuthenticated","toKey","isEqual","otherUser","UNAUTHENTICATED","GOOGLE_CREDENTIALS","FIRST_PARTY","MOCK_USER","SDK_VERSION","__PRIVATE_logClient","Logger","__PRIVATE_getLogLevel","logLevel","setLogLevel","__PRIVATE_logDebug","msg","obj","LogLevel","DEBUG","args","map","__PRIVATE_argToString","debug","__PRIVATE_logError","ERROR","error","__PRIVATE_logWarn","WARN","warn","__PRIVATE_formatJSON","value","JSON","stringify","e","fail","id","__PRIVATE_messageOrContext","context","message","__PRIVATE__fail","__PRIVATE_failure","toString","undefined","Error","__PRIVATE_hardAssert","assertion","__PRIVATE_debugAssert","__PRIVATE_debugCast","Code","OK","CANCELLED","UNKNOWN","INVALID_ARGUMENT","DEADLINE_EXCEEDED","NOT_FOUND","ALREADY_EXISTS","PERMISSION_DENIED","RESOURCE_EXHAUSTED","FAILED_PRECONDITION","ABORTED","OUT_OF_RANGE","UNIMPLEMENTED","INTERNAL","UNAVAILABLE","DATA_LOSS","FirestoreError","FirebaseError","code","super","name","__PRIVATE_Deferred","promise","Promise","resolve","reject","__PRIVATE_OAuthToken","user","type","headers","Map","set","__PRIVATE_EmptyAuthCredentialsProvider","getToken","invalidateToken","start","asyncQueue","changeListener","enqueueRetryable","shutdown","__PRIVATE_EmulatorAuthCredentialsProvider","token","__PRIVATE_FirebaseAuthCredentialsProvider","__PRIVATE_authProvider","currentUser","__PRIVATE_tokenCounter","forceRefresh","auth","__PRIVATE_tokenListener","__PRIVATE_lastTokenId","__PRIVATE_guardedChangeListener","__PRIVATE_nextToken","__PRIVATE_getUser","__PRIVATE_awaitNextToken","__PRIVATE_currentTokenAttempt","async","__PRIVATE_registerAuth","addAuthTokenListener","onInit","setTimeout","getImmediate","optional","__PRIVATE_initialTokenCounter","then","__PRIVATE_tokenData","accessToken","removeAuthTokenListener","__PRIVATE_currentUid","getUid","__PRIVATE_FirstPartyToken","__PRIVATE_sessionIndex","__PRIVATE_iamToken","__PRIVATE_authTokenFactory","__PRIVATE_getAuthToken","__PRIVATE__headers","__PRIVATE_authHeaderTokenValue","__PRIVATE_FirstPartyAuthCredentialsProvider","AppCheckToken","length","__PRIVATE_FirebaseAppCheckTokenProvider","app","__PRIVATE_appCheckProvider","appCheck","__PRIVATE_latestAppCheckToken","__PRIVATE_serverAppAppCheckToken","_isFirebaseServerApp","settings","appCheckToken","onTokenChanged","tokenResult","__PRIVATE_tokenUpdated","__PRIVATE_registerAppCheck","addTokenListener","removeTokenListener","__PRIVATE_EmptyAppCheckTokenProvider","__PRIVATE_randomBytes","__PRIVATE_nBytes","crypto","self","bytes","Uint8Array","getRandomValues","__PRIVATE_i","Math","floor","random","__PRIVATE_AutoId","newId","__PRIVATE_chars","__PRIVATE_maxMultiple","__PRIVATE_autoId","charAt","__PRIVATE_primitiveComparator","left","right","__PRIVATE_compareUtf8Strings","min","__PRIVATE_leftChar","__PRIVATE_rightChar","__PRIVATE_isSurrogate","__PRIVATE_MIN_SURROGATE","__PRIVATE_MAX_SURROGATE","s","c","charCodeAt","__PRIVATE_arrayEquals","comparator","every","index","__PRIVATE_immediateSuccessor","__PRIVATE_DOCUMENT_KEY_NAME","BasePath","segments","offset","range","len","other","child","nameOrPath","slice","limit","forEach","segment","push","construct","popFirst","size","popLast","firstSegment","lastSegment","get","isEmpty","isPrefixOf","isImmediateParentOf","potentialChild","fn","end","toArray","p1","p2","comparison","compareSegments","__PRIVATE_lhs","__PRIVATE_rhs","__PRIVATE_isLhsNumeric","isNumericId","__PRIVATE_isRhsNumeric","extractNumericId","compare","startsWith","endsWith","Integer","fromString","substring","ResourcePath","canonicalString","join","toUriEncodedString","encodeURIComponent","pathComponents","path","indexOf","split","filter","emptyPath","__PRIVATE_identifierRegExp","FieldPath","isValidIdentifier","test","str","replace","isKeyField","keyField","fromServerFormat","current","__PRIVATE_addCurrentSegment","__PRIVATE_inBackticks","next","DocumentKey","fromPath","fromName","empty","collectionGroup","hasCollectionId","collectionId","getCollectionGroup","getCollectionPath","k1","k2","isDocumentKey","fromSegments","__PRIVATE_validateNonEmptyArgument","__PRIVATE_functionName","__PRIVATE_argumentName","__PRIVATE_argument","__PRIVATE_validateIsNotUsedTogether","optionName1","argument1","optionName2","argument2","__PRIVATE_validateDocumentPath","__PRIVATE_validateCollectionPath","__PRIVATE_isPlainObject","input","Object","getPrototypeOf","prototype","__PRIVATE_valueDescription","Array","__PRIVATE_customObjectName","__PRIVATE_tryGetCustomObjectType","__PRIVATE_cast","_delegate","description","__PRIVATE_validatePositiveNumber","n","property","typeString","__PRIVATE_optionalValue","result","__PRIVATE_validateJSON","json","__PRIVATE_schema","key","__PRIVATE_fieldValue","__PRIVATE_MIN_SECONDS","__PRIVATE_MS_TO_NANOS","Timestamp","now","fromMillis","Date","fromDate","date","getTime","milliseconds","seconds","nanos","nanoseconds","toDate","toMillis","_compareTo","toJSON","_jsonSchemaVersion","fromJSON","_jsonSchema","valueOf","__PRIVATE_adjustedSeconds","String","padStart","SnapshotVersion","fromTimestamp","max","timestamp","compareTo","toMicroseconds","toTimestamp","__PRIVATE_INITIAL_LARGEST_BATCH_ID","FieldIndex","indexId","fields","indexState","__PRIVATE_fieldIndexGetArraySegment","__PRIVATE_fieldIndex","find","kind","__PRIVATE_fieldIndexGetDirectionalSegments","__PRIVATE_fieldIndexSemanticComparator","cmp","__PRIVATE_indexSegmentComparator","UNKNOWN_ID","IndexSegment","fieldPath","IndexState","sequenceNumber","IndexOffset","__PRIVATE_newIndexOffsetSuccessorFromReadTime","readTime","largestBatchId","__PRIVATE_successorSeconds","__PRIVATE_successorNanos","__PRIVATE_successor","__PRIVATE_newIndexOffsetFromDocument","document","documentKey","__PRIVATE_indexOffsetComparator","__PRIVATE_PRIMARY_LEASE_LOST_ERROR_MSG","PersistenceTransaction","onCommittedListeners","addOnCommittedListener","listener","raiseOnCommittedEvent","__PRIVATE_ignoreIfPrimaryLeaseLoss","err","PersistencePromise","callback","nextCallback","catchCallback","isDone","callbackAttached","nextFn","catchFn","wrapFailure","wrapSuccess","toPromise","wrapUserFunction","waitFor","all","expectedCount","__PRIVATE_resolvedCount","done","element","or","predicates","p","predicate","__PRIVATE_isTrue","collection","f","__PRIVATE_promises","r","call","mapArray","array","results","doWhile","condition","action","process","__PRIVATE_LOG_TAG","__PRIVATE_SimpleDbTransaction","open","db","mode","objectStoreNames","transaction","__PRIVATE_IndexedDbTransactionError","aborted","oncomplete","__PRIVATE_completionDeferred","onabort","onerror","event","__PRIVATE_checkForAndReportiOSError","target","__PRIVATE_completionPromise","abort","__PRIVATE_maybeCommit","__PRIVATE_maybeV3IndexedDb","commit","store","__PRIVATE_storeName","objectStore","__PRIVATE_SimpleDbStore","__PRIVATE_SimpleDb","__PRIVATE_wrapRequest","getGlobal","indexedDB","deleteDatabase","__PRIVATE_isAvailable","isIndexedDBAvailable","__PRIVATE_isMockPersistence","__PRIVATE_ua","getUA","__PRIVATE_iOSVersion","__PRIVATE_getIOSVersion","__PRIVATE_isUnsupportedIOS","__PRIVATE_androidVersion","__PRIVATE_getAndroidVersion","__PRIVATE_isUnsupportedAndroid","__PRIVATE_env","__PRIVATE_USE_MOCK_PERSISTENCE","__PRIVATE_getStore","txn","__PRIVATE_iOSVersionRegex","match","version","Number","__PRIVATE_schemaConverter","__PRIVATE_lastClosedDbVersion","__PRIVATE_ensureDb","request","onsuccess","onblocked","onupgradeneeded","oldVersion","__PRIVATE_createOrUpgrade","__PRIVATE_versionchangelistener","onversionchange","__PRIVATE_setVersionChangeListener","__PRIVATE_versionChangeListener","runTransaction","__PRIVATE_objectStores","__PRIVATE_transactionFn","__PRIVATE_readonly","__PRIVATE_attemptNumber","__PRIVATE_transactionFnResult","catch","__PRIVATE_retryable","close","__PRIVATE_androidVersionRegex","__PRIVATE_IterationController","__PRIVATE_dbCursor","__PRIVATE_shouldStop","__PRIVATE_nextKey","__PRIVATE_skipToKey","cursor","__PRIVATE_skip","delete","__PRIVATE_actionName","cause","__PRIVATE_isIndexedDbTransactionError","put","__PRIVATE_keyOrValue","add","count","__PRIVATE_loadAll","__PRIVATE_indexOrRange","__PRIVATE_iterateOptions","options","getAll","__PRIVATE_iterateCursor","__PRIVATE_loadFirst","__PRIVATE_deleteAll","__PRIVATE_keysOnly","control","__PRIVATE_iterate","__PRIVATE_optionsOrCallback","__PRIVATE_iterateSerial","__PRIVATE_cursorRequest","primaryKey","__PRIVATE_shouldContinue","continue","controller","__PRIVATE_userResult","__PRIVATE_userPromise","__PRIVATE_indexName","direction","reverse","openKeyCursor","openCursor","__PRIVATE_reportedIOSError","__PRIVATE_IOS_ERROR","__PRIVATE_newError","__PRIVATE_IndexBackfillerScheduler","__PRIVATE_backfiller","task","__PRIVATE_schedule","stop","cancel","started","delay","enqueueAfterDelay","__PRIVATE_documentsProcessed","__PRIVATE_backfill","__PRIVATE_IndexBackfiller","localStore","persistence","__PRIVATE_maxDocumentsToProcess","__PRIVATE_writeIndexEntries","__PRIVATE_processedCollectionGroups","Set","__PRIVATE_documentsRemaining","__PRIVATE_continueLoop","indexManager","getNextCollectionGroupToUpdate","has","__PRIVATE_writeEntriesForCollectionGroup","__PRIVATE_documentsRemainingUnderCap","getMinOffsetFromCollectionGroup","__PRIVATE_existingOffset","localDocuments","getNextDocuments","__PRIVATE_nextBatch","docs","changes","updateIndexEntries","__PRIVATE_getNewOffset","__PRIVATE_newOffset","updateCollectionGroup","__PRIVATE_lookupResult","__PRIVATE_maxOffset","batchId","__PRIVATE_ListenSequence","previousValue","__PRIVATE_sequenceNumberSyncer","sequenceNumberHandler","__PRIVATE_setPreviousValue","__PRIVATE_writeNewSequenceNumber","writeSequenceNumber","__PRIVATE_externalPreviousValue","__PRIVATE_nextValue","__PRIVATE_INVALID","__PRIVATE_BATCHID_UNKNOWN","__PRIVATE_isNullOrUndefined","__PRIVATE_isNegativeZero","isSafeInteger","isInteger","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","__PRIVATE_escapeChar","__PRIVATE_encodeResourcePath","__PRIVATE_encodeSeparator","__PRIVATE_encodeSegment","__PRIVATE_resultBuf","__PRIVATE_decodeResourcePath","__PRIVATE_lastReasonableEscapeIndex","__PRIVATE_segmentBuilder","__PRIVATE_currentPiece","DbRemoteDocumentStore","__PRIVATE_DbPrimaryClientStore","__PRIVATE_DbPrimaryClientKey","__PRIVATE_DbMutationQueueStore","__PRIVATE_DbMutationQueueKeyPath","__PRIVATE_DbMutationBatchStore","__PRIVATE_DbMutationBatchKeyPath","__PRIVATE_DbMutationBatchUserMutationsIndex","__PRIVATE_DbMutationBatchUserMutationsKeyPath","__PRIVATE_newDbDocumentMutationPrefixForPath","userId","__PRIVATE_newDbDocumentMutationKey","__PRIVATE_DbDocumentMutationPlaceholder","__PRIVATE_DbDocumentMutationStore","__PRIVATE_DbRemoteDocumentKeyPath","__PRIVATE_DbRemoteDocumentDocumentKeyIndex","__PRIVATE_DbRemoteDocumentDocumentKeyIndexPath","__PRIVATE_DbRemoteDocumentCollectionGroupIndex","__PRIVATE_DbRemoteDocumentCollectionGroupIndexPath","__PRIVATE_DbRemoteDocumentGlobalStore","__PRIVATE_DbRemoteDocumentGlobalKey","__PRIVATE_DbTargetStore","__PRIVATE_DbTargetQueryTargetsIndexName","__PRIVATE_DbTargetQueryTargetsKeyPath","__PRIVATE_DbTargetDocumentStore","__PRIVATE_DbTargetDocumentKeyPath","__PRIVATE_DbTargetDocumentDocumentTargetsIndex","__PRIVATE_DbTargetDocumentDocumentTargetsKeyPath","__PRIVATE_DbTargetGlobalKey","__PRIVATE_DbTargetGlobalStore","__PRIVATE_DbCollectionParentStore","__PRIVATE_DbCollectionParentKeyPath","__PRIVATE_DbClientMetadataStore","__PRIVATE_DbClientMetadataKeyPath","__PRIVATE_DbBundleStore","__PRIVATE_DbBundleKeyPath","__PRIVATE_DbNamedQueryStore","__PRIVATE_DbNamedQueryKeyPath","__PRIVATE_DbIndexConfigurationStore","__PRIVATE_DbIndexConfigurationKeyPath","__PRIVATE_DbIndexConfigurationCollectionGroupIndex","__PRIVATE_DbIndexConfigurationCollectionGroupIndexPath","__PRIVATE_DbIndexStateStore","__PRIVATE_DbIndexStateKeyPath","__PRIVATE_DbIndexStateSequenceNumberIndex","__PRIVATE_DbIndexStateSequenceNumberIndexPath","__PRIVATE_DbIndexEntryStore","__PRIVATE_DbIndexEntryKeyPath","__PRIVATE_DbIndexEntryDocumentKeyIndex","__PRIVATE_DbIndexEntryDocumentKeyIndexPath","__PRIVATE_DbDocumentOverlayStore","__PRIVATE_DbDocumentOverlayKeyPath","__PRIVATE_DbDocumentOverlayCollectionPathOverlayIndex","__PRIVATE_DbDocumentOverlayCollectionPathOverlayIndexPath","__PRIVATE_DbDocumentOverlayCollectionGroupOverlayIndex","__PRIVATE_DbDocumentOverlayCollectionGroupOverlayIndexPath","__PRIVATE_DbGlobalsStore","__PRIVATE_DbGlobalsKeyPath","__PRIVATE_V11_STORES","__PRIVATE_DbRemoteDocumentStoreLegacy","__PRIVATE_V12_STORES","__PRIVATE_V13_STORES","__PRIVATE_V14_STORES","__PRIVATE_V15_STORES","__PRIVATE_V16_STORES","__PRIVATE_V17_STORES","__PRIVATE_V18_STORES","__PRIVATE_IndexedDbTransaction","__PRIVATE_simpleDbTransaction","currentSequenceNumber","__PRIVATE_indexedDbTransaction","__PRIVATE_objectSize","hasOwnProperty","__PRIVATE_mapToArray","SortedMap","root","LLRBNode","EMPTY","insert","copy","BLACK","remove","node","__PRIVATE_prunedNodes","minKey","maxKey","inorderTraversal","k","v","__PRIVATE_descriptions","reverseTraversal","getIterator","SortedMapIterator","getIteratorFrom","getReverseIterator","getReverseIteratorFrom","startKey","isReverse","nodeStack","getNext","pop","hasNext","peek","color","RED","fixUp","removeMin","isRed","moveRedLeft","__PRIVATE_smallest","rotateRight","moveRedRight","rotateLeft","colorFlip","__PRIVATE_nl","__PRIVATE_nr","checkMaxDepth","__PRIVATE_blackDepth","check","pow","LLRBEmptyNode","SortedSet","data","elem","first","last","cb","forEachInRange","iter","forEachWhile","firstAfterOrEqual","SortedSetIterator","unionWith","__PRIVATE_thisIt","__PRIVATE_otherIt","__PRIVATE_thisElem","__PRIVATE_otherElem","__PRIVATE_res","targetId","__PRIVATE_advanceIterator","__PRIVATE_it","FieldMask","sort","extraFields","__PRIVATE_mergedMaskSet","covers","__PRIVATE_fieldMaskPath","l","__PRIVATE_Base64DecodeError","__PRIVATE_isBase64Available","atob","ByteString","binaryString","fromBase64String","base64","__PRIVATE_decodeBase64","__PRIVATE_encoded","DOMException","fromUint8Array","__PRIVATE_binaryStringFromUint8Array","fromCharCode","Symbol","iterator","toBase64","__PRIVATE_encodeBase64","raw","btoa","toUint8Array","__PRIVATE_uint8ArrayFromBinaryString","buffer","approximateByteSize","EMPTY_BYTE_STRING","__PRIVATE_ISO_TIMESTAMP_REG_EXP","RegExp","__PRIVATE_normalizeTimestamp","__PRIVATE_fraction","exec","__PRIVATE_nanoStr","substr","__PRIVATE_parsedDate","__PRIVATE_normalizeNumber","__PRIVATE_normalizeByteString","blob","__PRIVATE_SERVER_TIMESTAMP_SENTINEL","__PRIVATE_TYPE_KEY","__PRIVATE_PREVIOUS_VALUE_KEY","__PRIVATE_LOCAL_WRITE_TIME_KEY","__PRIVATE_isServerTimestamp","mapValue","stringValue","__PRIVATE_getPreviousValue","__PRIVATE_getLocalWriteTime","localWriteTime","timestampValue","DatabaseInfo","databaseId","appId","persistenceKey","host","ssl","forceLongPolling","autoDetectLongPolling","longPollingOptions","useFetchStreams","isUsingEmulator","__PRIVATE_DEFAULT_DATABASE_NAME","DatabaseId","projectId","database","isDefaultDatabase","__PRIVATE_MAX_VALUE_TYPE","MAX_VALUE","__type__","__PRIVATE_VECTOR_VALUE_SENTINEL","__PRIVATE_VECTOR_MAP_VECTORS_KEY","MIN_VALUE","nullValue","__PRIVATE_typeOrder","__PRIVATE_isMaxValue","__PRIVATE_isVectorValue","__PRIVATE_valueEquals","__PRIVATE_leftType","booleanValue","__PRIVATE_timestampEquals","__PRIVATE_leftTimestamp","__PRIVATE_rightTimestamp","__PRIVATE_blobEquals","bytesValue","referenceValue","__PRIVATE_geoPointEquals","geoPointValue","latitude","longitude","__PRIVATE_numberEquals","integerValue","__PRIVATE_n1","doubleValue","__PRIVATE_n2","isNaN","arrayValue","values","__PRIVATE_objectEquals","__PRIVATE_leftMap","__PRIVATE_rightMap","__PRIVATE_arrayValueContains","__PRIVATE_haystack","__PRIVATE_needle","__PRIVATE_valueCompare","__PRIVATE_rightType","__PRIVATE_compareNumbers","__PRIVATE_leftNumber","__PRIVATE_rightNumber","__PRIVATE_compareTimestamps","__PRIVATE_compareBlobs","__PRIVATE_leftBytes","__PRIVATE_rightBytes","__PRIVATE_compareReferences","__PRIVATE_leftPath","__PRIVATE_rightPath","__PRIVATE_leftSegments","__PRIVATE_rightSegments","__PRIVATE_compareGeoPoints","__PRIVATE_compareArrays","__PRIVATE_compareVectors","__PRIVATE_leftArrayValue","__PRIVATE_rightArrayValue","__PRIVATE_lengthCompare","__PRIVATE_compareMaps","__PRIVATE_leftKeys","keys","__PRIVATE_rightKeys","__PRIVATE_keyCompare","__PRIVATE_leftArray","__PRIVATE_rightArray","canonicalId","__PRIVATE_canonifyValue","__PRIVATE_canonifyTimestamp","__PRIVATE_normalizedTimestamp","__PRIVATE_canonifyByteString","byteString","__PRIVATE_canonifyReference","__PRIVATE_canonifyGeoPoint","__PRIVATE_geoPoint","__PRIVATE_canonifyArray","__PRIVATE_canonifyMap","__PRIVATE_sortedKeys","__PRIVATE_estimateByteSize","__PRIVATE_estimateArrayByteSize","reduce","__PRIVATE_previousSize","__PRIVATE_estimateMapByteSize","val","__PRIVATE_refValue","isArray","__PRIVATE_isNullValue","__PRIVATE_isNanValue","__PRIVATE_isMapValue","__PRIVATE_deepClone","source","__PRIVATE_MIN_VECTOR_VALUE","__PRIVATE_valuesGetLowerBound","NaN","__PRIVATE_valuesGetUpperBound","__PRIVATE_lowerBoundCompare","inclusive","__PRIVATE_upperBoundCompare","ObjectValue","field","__PRIVATE_currentLevel","getFieldsMap","setAll","parent","__PRIVATE_upserts","__PRIVATE_deletes","__PRIVATE_fieldsMap","applyChanges","__PRIVATE_nestedValue","__PRIVATE_inserts","clone","__PRIVATE_extractFieldMask","__PRIVATE_currentPath","__PRIVATE_nestedFields","__PRIVATE_nestedPath","MutableDocument","documentType","createTime","documentState","newInvalidDocument","newFoundDocument","newNoDocument","newUnknownDocument","convertToFoundDocument","convertToNoDocument","convertToUnknownDocument","setHasCommittedMutations","setHasLocalMutations","setReadTime","hasLocalMutations","hasCommittedMutations","hasPendingWrites","isValidDocument","isFoundDocument","isNoDocument","isUnknownDocument","mutableCopy","Bound","position","__PRIVATE_boundCompareToDocument","bound","orderBy","doc","__PRIVATE_orderByComponent","component","dir","__PRIVATE_boundEquals","OrderBy","__PRIVATE_orderByEquals","Filter","FieldFilter","op","create","createKeyFieldInFilter","__PRIVATE_KeyFieldFilter","__PRIVATE_ArrayContainsFilter","__PRIVATE_InFilter","__PRIVATE_NotInFilter","__PRIVATE_ArrayContainsAnyFilter","__PRIVATE_KeyFieldInFilter","__PRIVATE_KeyFieldNotInFilter","matches","matchesComparison","operator","isInequality","getFlattenedFilters","getFilters","CompositeFilter","filters","__PRIVATE_memoizedFlattenedFilters","__PRIVATE_compositeFilterIsConjunction","__PRIVATE_subfilter","concat","assign","compositeFilter","__PRIVATE_compositeFilterIsDisjunction","__PRIVATE_compositeFilterIsFlatConjunction","__PRIVATE_compositeFilterIsFlat","__PRIVATE_canonifyFilter","__PRIVATE_canonicalIdsString","__PRIVATE_filterEquals","__PRIVATE_f1","__PRIVATE_f2","__PRIVATE_fieldFilterEquals","__PRIVATE_compositeFilterEquals","__PRIVATE_f1Filter","__PRIVATE_compositeFilterWithAddedFilters","__PRIVATE_otherFilters","__PRIVATE_mergedFilters","__PRIVATE_stringifyFilter","__PRIVATE_stringifyFieldFilter","__PRIVATE_stringifyCompositeFilter","__PRIVATE_extractDocumentKeysFromArrayValue","some","__PRIVATE_TargetImpl","startAt","endAt","__PRIVATE_memoizedCanonicalId","__PRIVATE_newTarget","__PRIVATE_canonifyTarget","__PRIVATE_targetImpl","o","__PRIVATE_canonifyOrderBy","__PRIVATE_targetEquals","__PRIVATE_targetIsDocumentTarget","__PRIVATE_targetGetFieldFiltersForPath","__PRIVATE_targetGetAscendingBound","fieldFilter","__PRIVATE_filterValue","__PRIVATE_filterInclusive","__PRIVATE_cursorValue","__PRIVATE_targetGetDescendingBound","__PRIVATE_QueryImpl","explicitOrderBy","limitType","__PRIVATE_memoizedNormalizedOrderBy","__PRIVATE_memoizedTarget","__PRIVATE_memoizedAggregateTarget","__PRIVATE_newQuery","__PRIVATE_newQueryForPath","__PRIVATE_queryMatchesAllDocuments","query","__PRIVATE_isCollectionGroupQuery","__PRIVATE_queryNormalizedOrderBy","__PRIVATE_queryImpl","__PRIVATE_fieldsNormalized","__PRIVATE_lastDirection","__PRIVATE_inequalityFields","__PRIVATE_getInequalityFilterFields","__PRIVATE_queryToTarget","__PRIVATE__queryToTarget","__PRIVATE_queryToAggregateTarget","__PRIVATE_orderBys","__PRIVATE_queryWithAddedFilter","__PRIVATE_newFilters","__PRIVATE_queryWithLimit","__PRIVATE_queryEquals","__PRIVATE_canonifyQuery","__PRIVATE_stringifyQuery","__PRIVATE_stringifyTarget","__PRIVATE_stringifyOrderBy","__PRIVATE_queryMatches","__PRIVATE_queryMatchesPathAndCollectionGroup","__PRIVATE_docPath","__PRIVATE_queryMatchesOrderBy","__PRIVATE_queryMatchesFilters","__PRIVATE_queryMatchesBounds","__PRIVATE_boundSortsBeforeDocument","__PRIVATE_boundSortsAfterDocument","__PRIVATE_queryCollectionGroup","__PRIVATE_newQueryComparator","__PRIVATE_d1","__PRIVATE_d2","__PRIVATE_comparedOnKeyField","comp","__PRIVATE_compareDocs","__PRIVATE_compareDocumentsByField","v1","v2","ObjectMap","mapKeyFn","equalsFn","inner","innerSize","__PRIVATE_otherKey","splice","_","entries","__PRIVATE_EMPTY_MUTABLE_DOCUMENT_MAP","__PRIVATE_mutableDocumentMap","__PRIVATE_EMPTY_DOCUMENT_MAP","documentMap","__PRIVATE_convertOverlayedDocumentMapToDocumentMap","documents","overlayedDocument","__PRIVATE_newOverlayMap","__PRIVATE_newDocumentKeyMap","__PRIVATE_newMutationMap","__PRIVATE_EMPTY_DOCUMENT_VERSION_MAP","__PRIVATE_EMPTY_DOCUMENT_KEY_SET","__PRIVATE_documentKeySet","__PRIVATE_EMPTY_TARGET_ID_SET","__PRIVATE_targetIdSet","__PRIVATE_toDouble","serializer","useProto3Json","Infinity","__PRIVATE_toInteger","toNumber","TransformOperation","__PRIVATE_applyTransformOperationToLocalView","transform","__PRIVATE_ServerTimestampTransform","serverTimestamp","__PRIVATE_TYPE_KEY$1","__PRIVATE_ArrayUnionTransformOperation","__PRIVATE_applyArrayUnionTransformOperation","__PRIVATE_ArrayRemoveTransformOperation","__PRIVATE_applyArrayRemoveTransformOperation","__PRIVATE_applyNumericIncrementTransformOperationToLocalView","__PRIVATE_baseValue","__PRIVATE_computeTransformOperationBaseValue","sum","asNumber","__PRIVATE_operand","__PRIVATE_applyTransformOperationToRemoteDocument","__PRIVATE_transformResult","__PRIVATE_NumericIncrementTransformOperation","__PRIVATE_isNumber","__PRIVATE_isDouble","elements","__PRIVATE_coercedFieldValuesArray","__PRIVATE_toUnion","__PRIVATE_toRemove","FieldTransform","__PRIVATE_fieldTransformEquals","__PRIVATE_transformOperationEquals","MutationResult","transformResults","Precondition","updateTime","exists","none","isNone","__PRIVATE_preconditionIsValidForDocument","precondition","Mutation","__PRIVATE_calculateOverlayMutation","mask","__PRIVATE_DeleteMutation","__PRIVATE_SetMutation","__PRIVATE_docValue","__PRIVATE_patchValue","__PRIVATE_maskSet","__PRIVATE_PatchMutation","__PRIVATE_mutationApplyToRemoteDocument","mutation","__PRIVATE_mutationResult","__PRIVATE_setMutationApplyToRemoteDocument","__PRIVATE_newData","__PRIVATE_serverTransformResults","fieldTransforms","__PRIVATE_patchMutationApplyToRemoteDocument","__PRIVATE_getPatch","__PRIVATE_deleteMutationApplyToRemoteDocument","__PRIVATE_mutationApplyToLocalView","__PRIVATE_previousMask","__PRIVATE_setMutationApplyToLocalView","__PRIVATE_localTransformResults","__PRIVATE_patchMutationApplyToLocalView","fieldMask","__PRIVATE_deleteMutationApplyToLocalView","__PRIVATE_mutationExtractBaseValue","__PRIVATE_baseObject","__PRIVATE_fieldTransform","__PRIVATE_existingValue","__PRIVATE_coercedValue","__PRIVATE_mutationEquals","__PRIVATE_fieldTransformsAreEqual","getFieldMask","newValue","__PRIVATE_mutableDocument","__PRIVATE_serverTransformResultCount","__PRIVATE_fieldTransformCount","__PRIVATE_VerifyMutation","MutationBatch","baseMutations","mutations","applyToRemoteDocument","batchResult","mutationResults","applyToLocalView","mutatedFields","applyToLocalDocumentSet","documentsWithoutRemoteVersion","overlays","m","__PRIVATE_overlay","MutationBatchResult","batch","commitVersion","docVersions","from","__PRIVATE_mutationsSent","__PRIVATE_resultsReceived","__PRIVATE_versionMap","__PRIVATE_documentVersionMap","Overlay","getKey","__PRIVATE_AggregateImpl","alias","aggregateType","ExistenceFilter","unchangedNames","__PRIVATE_RpcCode","RpcCode","__PRIVATE_isPermanentError","__PRIVATE_mapCodeFromRpcCode","__PRIVATE_testingHooksSpi","__PRIVATE_newTextEncoder","TextEncoder","__PRIVATE_MAX_64_BIT_UNSIGNED_INTEGER","__PRIVATE_getMd5HashValue","__PRIVATE_encodedValue","encode","__PRIVATE_md5","Md5","update","digest","__PRIVATE_get64BitUints","Bytes","__PRIVATE_dataView","DataView","__PRIVATE_chunk1","getUint32","__PRIVATE_chunk2","__PRIVATE_chunk3","__PRIVATE_chunk4","BloomFilter","bitmap","padding","hashCount","__PRIVATE_BloomFilterError","__PRIVATE_bitCount","__PRIVATE_bitCountInInteger","fromNumber","__PRIVATE_getBitIndex","__PRIVATE_num1","__PRIVATE_num2","__PRIVATE_hashIndex","__PRIVATE_hashValue","multiply","getBits","modulo","__PRIVATE_isBitSet","mightContain","__PRIVATE_md5HashedValue","__PRIVATE_hash1","__PRIVATE_hash2","contains","ceil","bloomFilter","item","__PRIVATE_setBit","__PRIVATE_indexOfByte","RemoteEvent","snapshotVersion","targetChanges","targetMismatches","documentUpdates","resolvedLimboDocuments","createSynthesizedRemoteEventForCurrentChange","resumeToken","TargetChange","createSynthesizedTargetChangeForCurrentChange","addedDocuments","modifiedDocuments","removedDocuments","__PRIVATE_DocumentWatchChange","__PRIVATE_updatedTargetIds","removedTargetIds","__PRIVATE_newDoc","__PRIVATE_ExistenceFilterChange","__PRIVATE_existenceFilter","__PRIVATE_WatchTargetChange","state","targetIds","__PRIVATE_TargetState","__PRIVATE_pendingResponses","__PRIVATE_documentChanges","__PRIVATE_snapshotChangesMap","__PRIVATE__current","__PRIVATE__hasPendingChanges","__PRIVATE__resumeToken","__PRIVATE_isPending","__PRIVATE_hasPendingChanges","__PRIVATE_updateResumeToken","__PRIVATE_toTargetChange","changeType","__PRIVATE_clearPendingChanges","__PRIVATE_addDocumentChange","__PRIVATE_removeDocumentChange","__PRIVATE_recordPendingTargetRequest","__PRIVATE_recordTargetResponse","__PRIVATE_markCurrent","__PRIVATE_WatchChangeAggregator","__PRIVATE_metadataProvider","__PRIVATE_pendingDocumentUpdates","__PRIVATE_pendingDocumentUpdatesByTarget","__PRIVATE_documentTargetMap","__PRIVATE_pendingDocumentTargetMapping","__PRIVATE_pendingTargetResets","__PRIVATE_handleDocumentChange","__PRIVATE_docChange","__PRIVATE_addDocumentToTarget","__PRIVATE_removeDocumentFromTarget","__PRIVATE_handleTargetChange","targetChange","forEachTarget","__PRIVATE_targetState","__PRIVATE_ensureTargetState","__PRIVATE_isActiveTarget","removeTarget","__PRIVATE_resetTarget","__PRIVATE_targetStates","__PRIVATE_handleExistenceFilter","__PRIVATE_watchChange","targetData","__PRIVATE_targetDataForActiveTarget","__PRIVATE_currentSize","__PRIVATE_getCurrentDocumentCountForTarget","__PRIVATE_parseBloomFilter","status","__PRIVATE_applyBloomFilter","purpose","__PRIVATE_notifyOnExistenceFilterMismatch","__PRIVATE_createExistenceFilterMismatchInfoForTestingHooks","localCacheCount","__PRIVATE_bloomFilterStatus","existenceFilterCount","applied","bitmapLength","bits","__PRIVATE_getDatabaseId","__PRIVATE_normalizedBitmap","__PRIVATE_currentCount","__PRIVATE_filterRemovedDocuments","__PRIVATE_existingKeys","getRemoteKeysForTarget","__PRIVATE_removalCount","documentPath","__PRIVATE_createRemoteEvent","__PRIVATE_ensureDocumentUpdateByTarget","__PRIVATE_targetContainsDocument","__PRIVATE_targets","__PRIVATE_isOnlyLimboTarget","remoteEvent","__PRIVATE_ensureDocumentTargetMapping","__PRIVATE_updatedDocument","__PRIVATE_targetMapping","__PRIVATE_targetActive","__PRIVATE_getTargetDataForTarget","__PRIVATE_DIRECTIONS","__PRIVATE_dirs","__PRIVATE_OPERATORS","__PRIVATE_ops","__PRIVATE_COMPOSITE_OPERATORS","JsonProtoSerializer","__PRIVATE_toInt32Proto","toISOString","__PRIVATE_toBytes","__PRIVATE_toVersion","__PRIVATE_fromVersion","__PRIVATE_toResourceName","__PRIVATE_toResourcePath","__PRIVATE_resourcePath","__PRIVATE_fullyQualifiedPrefixPath","__PRIVATE_fromResourceName","__PRIVATE_resource","__PRIVATE_isValidResourceName","__PRIVATE_toName","__PRIVATE_extractLocalPathFromResourceName","__PRIVATE_toQueryPath","__PRIVATE_fromQueryPath","__PRIVATE_resourceName","__PRIVATE_getEncodedDatabaseId","__PRIVATE_toMutationDocument","__PRIVATE_fromDocument","__PRIVATE_fromBatchGetDocumentsResponse","__PRIVATE_fromFound","found","__PRIVATE_fromMissing","missing","__PRIVATE_fromWatchChange","__PRIVATE_change","__PRIVATE_fromWatchTargetChangeState","targetChangeType","__PRIVATE_fromBytes","Buffer","__PRIVATE_causeProto","__PRIVATE_fromRpcStatus","documentChange","__PRIVATE_entityChange","documentDelete","__PRIVATE_docDelete","documentRemove","__PRIVATE_docRemove","toMutation","updateMask","__PRIVATE_toDocumentMask","__PRIVATE_mutationType","verify","updateTransforms","__PRIVATE_toFieldTransform","setToServerValue","appendMissingElements","removeAllFromArray","increment","currentDocument","__PRIVATE_toPrecondition","__PRIVATE_fromMutation","proto","__PRIVATE_fromPrecondition","__PRIVATE_fromFieldTransform","__PRIVATE_fromDocumentMask","__PRIVATE_paths","fieldPaths","__PRIVATE_fromWriteResults","__PRIVATE_protos","commitTime","__PRIVATE_fromWriteResult","__PRIVATE_toDocumentsTarget","__PRIVATE_toQueryTarget","__PRIVATE_queryTarget","structuredQuery","allDescendants","where","__PRIVATE_toFilters","__PRIVATE_toFilter","__PRIVATE_toOrder","order","__PRIVATE_toPropertyOrder","__PRIVATE_toFieldPathReference","__PRIVATE_toDirection","__PRIVATE_toStartAtCursor","before","__PRIVATE_toEndAtCursor","__PRIVATE_toRunAggregationQueryRequest","__PRIVATE_aggregates","__PRIVATE_skipAliasing","ft","__PRIVATE_aliasMap","aggregations","__PRIVATE_aggregationNum","__PRIVATE_aggregate","__PRIVATE_serverAlias","avg","structuredAggregationQuery","__PRIVATE_convertQueryTargetToQuery","__PRIVATE_fromCount","__PRIVATE_filterBy","__PRIVATE_fromFilters","__PRIVATE_fromFilter","__PRIVATE_fromOrder","__PRIVATE_fromPropertyOrder","__PRIVATE_fromFieldPathReference","__PRIVATE_fromDirection","__PRIVATE_fromInt32Proto","__PRIVATE_fromStartAtCursor","__PRIVATE_fromEndAtCursor","__PRIVATE_toListenRequestLabels","__PRIVATE_toLabel","unaryFilter","__PRIVATE_fromUnaryFilter","__PRIVATE_nanField","__PRIVATE_nullField","__PRIVATE_notNanField","__PRIVATE_notNullField","__PRIVATE_fromFieldFilter","__PRIVATE_fromOperatorName","__PRIVATE_fromCompositeFilter","__PRIVATE_fromCompositeOperatorName","__PRIVATE_toOperatorName","__PRIVATE_toCompositeOperatorName","__PRIVATE_fieldReference","__PRIVATE_toUnaryOrFieldFilter","__PRIVATE_toCompositeFilter","__PRIVATE_canonicalFields","TargetData","lastLimboFreeSnapshotVersion","withSequenceNumber","withResumeToken","withExpectedCount","withLastLimboFreeSnapshotVersion","__PRIVATE_LocalSerializer","__PRIVATE_remoteSerializer","__PRIVATE_fromDbRemoteDocument","__PRIVATE_localSerializer","__PRIVATE_remoteDoc","noDocument","__PRIVATE_fromDbTimestamp","unknownDocument","__PRIVATE_fromDbTimestampKey","__PRIVATE_dbTimestampKey","__PRIVATE_toDbRemoteDocument","prefixPath","documentId","__PRIVATE_toDbTimestampKey","__PRIVATE_toDocument","__PRIVATE_toDbTimestamp","__PRIVATE_dbTimestamp","__PRIVATE_fromDbMutationBatch","__PRIVATE_dbBatch","__PRIVATE_currentMutation","__PRIVATE_transformMutation","localWriteTimeMs","__PRIVATE_fromDbTarget","__PRIVATE_dbTarget","__PRIVATE_isDocumentQuery","__PRIVATE_dbQuery","__PRIVATE_fromDocumentsTarget","__PRIVATE_documentsTarget","__PRIVATE_fromQueryTarget","lastListenSequenceNumber","__PRIVATE_toDbTarget","__PRIVATE_dbLastLimboFreeTimestamp","__PRIVATE_queryProto","__PRIVATE_fromBundledQuery","bundledQuery","__PRIVATE_fromDbDocumentOverlay","__PRIVATE_dbDocumentOverlay","overlayMutation","__PRIVATE_toDbDocumentOverlayKey","__PRIVATE_docKey","__PRIVATE_docId","__PRIVATE_toDbIndexState","__PRIVATE_IndexedDbBundleCache","getBundleMetadata","bundleId","__PRIVATE_bundlesStore","bundle","__PRIVATE_fromDbBundle","__PRIVATE_dbBundle","saveBundleMetadata","__PRIVATE_bundleMetadata","__PRIVATE_toDbBundle","metadata","getNamedQuery","queryName","__PRIVATE_namedQueriesStore","__PRIVATE_fromDbNamedQuery","__PRIVATE_dbNamedQuery","saveNamedQuery","__PRIVATE_toDbNamedQuery","__PRIVATE_IndexedDbDocumentOverlayCache","__PRIVATE_forUser","getOverlay","__PRIVATE_documentOverlayStore","__PRIVATE_dbOverlay","getOverlays","saveOverlays","__PRIVATE_saveOverlay","removeOverlaysForBatchId","documentKeys","__PRIVATE_collectionPaths","collectionPath","IDBKeyRange","getOverlaysForCollection","sinceBatchId","POSITIVE_INFINITY","__PRIVATE_dbOverlays","getOverlaysForCollectionGroup","__PRIVATE_currentBatchId","__PRIVATE_toDbDocumentOverlay","__PRIVATE_IndexedDbGlobalsCache","__PRIVATE_globalsStore","getSessionToken","global","setSessionToken","sessionToken","__PRIVATE_FirestoreIndexValueWriter","__PRIVATE_writeIndexValue","__PRIVATE_encoder","__PRIVATE_writeIndexValueAux","__PRIVATE_writeInfinity","__PRIVATE_indexValue","__PRIVATE_writeValueTypeLabel","__PRIVATE_writeNumber","__PRIVATE_writeString","__PRIVATE_writeIndexString","__PRIVATE_writeTruncationMarker","__PRIVATE_writeBytes","__PRIVATE_writeIndexEntityRef","__PRIVATE_writeIndexVector","__PRIVATE_writeIndexMap","__PRIVATE_writeIndexArray","__PRIVATE_stringIndexValue","__PRIVATE_writeUnlabeledIndexString","__PRIVATE_mapIndexValue","__PRIVATE_arrayIndexValue","__PRIVATE_ESCAPE2","__PRIVATE_numberOfLeadingZerosInByte","x","__PRIVATE_zeros","__PRIVATE_unsignedNumLength","__PRIVATE_numBits","__PRIVATE_numberOfLeadingZeros","__PRIVATE_leadingZeros","__PRIVATE_OrderedCodeWriter","__PRIVATE_writeBytesAscending","__PRIVATE_byte","__PRIVATE_writeByteAscending","__PRIVATE_writeSeparatorAscending","__PRIVATE_writeBytesDescending","__PRIVATE_writeByteDescending","__PRIVATE_writeSeparatorDescending","__PRIVATE_writeUtf8Ascending","__PRIVATE_sequence","charCode","__PRIVATE_codePoint","codePointAt","__PRIVATE_writeUtf8Descending","__PRIVATE_writeNumberAscending","__PRIVATE_toOrderedBits","__PRIVATE_ensureAvailable","__PRIVATE_writeNumberDescending","__PRIVATE_writeInfinityAscending","__PRIVATE_writeEscapedByteAscending","__PRIVATE_writeInfinityDescending","__PRIVATE_writeEscapedByteDescending","reset","seed","__PRIVATE_encodedBytes","__PRIVATE_doubleToLongBits","__PRIVATE_dv","ArrayBuffer","setFloat64","__PRIVATE_isNegative","b","__PRIVATE_masked","__PRIVATE_minCapacity","__PRIVATE_newLength","__PRIVATE_newBuffer","__PRIVATE_AscendingIndexByteEncoder","__PRIVATE_orderedCode","__PRIVATE_DescendingIndexByteEncoder","__PRIVATE_IndexByteEncoder","__PRIVATE_ascending","__PRIVATE_descending","__PRIVATE_forKind","__PRIVATE_IndexEntry","__PRIVATE__indexId","__PRIVATE__documentKey","__PRIVATE__arrayValue","__PRIVATE__directionalValue","__PRIVATE_currentLength","__PRIVATE_dbIndexEntry","orderedDocumentKey","__PRIVATE_encodeKeySafeBytes","directionalValue","__PRIVATE_dbIndexEntryKey","entry","__PRIVATE_indexEntryComparator","__PRIVATE_compareByteArrays","isSafariOrWebkit","__PRIVATE_encodeUint8ArrayToSortableString","__PRIVATE_decodeKeySafeBytes","__PRIVATE_decodeSortableStringToUint8Array","__PRIVATE_uint8array","__PRIVATE_TargetIndexMatcher","__PRIVATE_equalityFilters","__PRIVATE_inequalityFilters","__PRIVATE_hasMultipleInequality","__PRIVATE_servedByIndex","__PRIVATE_arraySegment","__PRIVATE_hasMatchingEqualityFilter","__PRIVATE_equalitySegments","__PRIVATE_segmentIndex","__PRIVATE_orderBysIndex","__PRIVATE_inequalityFilter","__PRIVATE_matchesFilter","__PRIVATE_matchesOrderBy","__PRIVATE_buildTargetIndex","__PRIVATE_uniqueFields","__PRIVATE_isArrayOperator","__PRIVATE_computeInExpansion","__PRIVATE_expandedFilters","__PRIVATE_getDnfTerms","__PRIVATE_computeDistributedNormalForm","__PRIVATE_isDisjunctiveNormalForm","__PRIVATE_isSingleFieldFilter","__PRIVATE_isFlatConjunction","__PRIVATE_isDisjunctionOfFieldFiltersAndFlatConjunctions","__PRIVATE_subFilter","__PRIVATE_newFilter","__PRIVATE_applyAssociation","__PRIVATE_runningResult","__PRIVATE_applyDistribution","__PRIVATE_applyDistributionFieldFilters","__PRIVATE_applyDistributionFieldAndCompositeFilters","__PRIVATE_applyDistributionCompositeFilters","__PRIVATE_disjunctionSide","__PRIVATE_otherSide","__PRIVATE_updatedFilters","__PRIVATE_newSubfilters","__PRIVATE_MemoryIndexManager","__PRIVATE_MemoryCollectionParentIndex","addToCollectionParentIndex","__PRIVATE_collectionParentIndex","getCollectionParents","getEntries","addFieldIndex","deleteFieldIndex","deleteAllFieldIndexes","createTargetIndexes","getDocumentsMatchingTarget","getIndexType","getFieldIndexes","getMinOffset","parentPath","__PRIVATE_existingParents","__PRIVATE_added","__PRIVATE_EMPTY_VALUE","__PRIVATE_IndexedDbIndexManager","t","__PRIVATE_collectionParentsCache","__PRIVATE_collectionParent","__PRIVATE_collectionParentsStore","__PRIVATE_parentPaths","indexes","__PRIVATE_indexConfigurationStore","__PRIVATE_dbIndex","__PRIVATE_toDbIndexConfiguration","states","__PRIVATE_indexStateStore","__PRIVATE_indexEntriesStore","__PRIVATE_getSubTargets","__PRIVATE_subTarget","__PRIVATE_indexEntries","__PRIVATE_canServeTarget","__PRIVATE_getFieldIndex","__PRIVATE_fieldIndexToString","__PRIVATE_arrayValues","__PRIVATE_targetGetArrayValues","__PRIVATE_notInValues","__PRIVATE_targetGetNotInValues","lowerBound","__PRIVATE_targetGetLowerBound","__PRIVATE_segmentBound","upperBound","__PRIVATE_targetGetUpperBound","__PRIVATE_lowerBoundEncoded","__PRIVATE_encodeBound","__PRIVATE_upperBoundEncoded","__PRIVATE_notInEncoded","__PRIVATE_encodeValues","__PRIVATE_indexRanges","__PRIVATE_generateIndexRanges","__PRIVATE_indexRange","__PRIVATE_subTargets","__PRIVATE_targetToDnfSubTargets","__PRIVATE_term","__PRIVATE_lowerBounds","__PRIVATE_lowerBoundInclusive","__PRIVATE_upperBounds","__PRIVATE_upperBoundInclusive","__PRIVATE_totalScans","__PRIVATE_scansPerArrayElement","__PRIVATE_encodeSingleElement","__PRIVATE_generateLowerBound","__PRIVATE_generateUpperBound","__PRIVATE_notInBound","__PRIVATE_notIn","createRange","__PRIVATE_targetIndexMatcher","candidate","__PRIVATE_indexType","__PRIVATE_targetGetSegmentCount","__PRIVATE_hasArraySegment","__PRIVATE_targetHasLimit","__PRIVATE_encodeDirectionalElements","__PRIVATE_directionalEncoder","__PRIVATE_INSTANCE","__PRIVATE_encodeDirectionalKey","__PRIVATE_fieldIndexGetKeyOrder","__PRIVATE_directionalSegments","__PRIVATE_encoders","__PRIVATE_valueIdx","__PRIVATE_isInFilter","__PRIVATE_expandIndexValues","__PRIVATE_getEncodedBytes","prefixes","__PRIVATE_arrayElement","prefix","__PRIVATE_clonedEncoder","__PRIVATE_indexConfigs","__PRIVATE_indexConfig","__PRIVATE_fromDbIndexConfiguration","__PRIVATE_decodedState","__PRIVATE_decodedSegments","__PRIVATE_getNextSequenceNumber","__PRIVATE_nextSequenceNumber","__PRIVATE_configs","config","__PRIVATE_memoizedIndexes","__PRIVATE_memoizedCollectionIndexes","__PRIVATE_fieldIndexes","__PRIVATE_getExistingIndexEntries","__PRIVATE_existingEntries","__PRIVATE_newEntries","__PRIVATE_computeIndexEntries","__PRIVATE_updateEntries","__PRIVATE_addIndexEntry","__PRIVATE_indexEntry","__PRIVATE_deleteIndexEntry","only","__PRIVATE_diffSortedSets","after","__PRIVATE_onAdd","__PRIVATE_onRemove","__PRIVATE_beforeIt","__PRIVATE_afterIt","__PRIVATE_beforeValue","__PRIVATE_afterValue","__PRIVATE_removed","lower","upper","el","__PRIVATE_bounds","__PRIVATE_notInValue","__PRIVATE_cmpToLower","__PRIVATE_cmpToUpper","__PRIVATE_ranges","__PRIVATE_isRangeMatchable","__PRIVATE_getMinOffsetFromFieldIndexes","__PRIVATE_minOffset","__PRIVATE_maxBatchId","__PRIVATE_GC_DID_NOT_RUN","didRun","sequenceNumbersCollected","targetsRemoved","documentsRemoved","__PRIVATE_LRU_DEFAULT_CACHE_SIZE_BYTES","LruParams","withCacheSize","cacheSize","DEFAULT_COLLECTION_PERCENTILE","DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT","cacheSizeCollectionThreshold","percentileToCollect","maximumSequenceNumbersToCollect","removeMutationBatch","__PRIVATE_mutationStore","__PRIVATE_indexTxn","__PRIVATE_numDeleted","__PRIVATE_removePromise","__PRIVATE_indexKey","__PRIVATE_dbDocumentSize","DEFAULT","DISABLED","__PRIVATE_IndexedDbMutationQueue","referenceDelegate","__PRIVATE_documentKeysByBatchId","checkEmpty","NEGATIVE_INFINITY","__PRIVATE_mutationsStore","addMutationBatch","__PRIVATE_documentStore","__PRIVATE_documentMutationsStore","__PRIVATE_toDbMutationBatch","__PRIVATE_serializedBaseMutations","__PRIVATE_serializedMutations","__PRIVATE_collectionParents","lookupMutationBatch","__PRIVATE_lookupMutationKeys","getNextMutationBatchAfterBatchId","__PRIVATE_nextBatchId","__PRIVATE_foundBatch","getHighestUnacknowledgedBatchId","getAllMutationBatches","__PRIVATE_dbBatches","getAllMutationBatchesAffectingDocumentKey","__PRIVATE_indexPrefix","__PRIVATE_indexStart","__PRIVATE_userID","__PRIVATE_encodedPath","getAllMutationBatchesAffectingDocumentKeys","__PRIVATE_uniqueBatchIDs","__PRIVATE_batchID","__PRIVATE_lookupMutationBatches","getAllMutationBatchesAffectingQuery","__PRIVATE_queryPath","__PRIVATE_immediateChildrenLength","__PRIVATE_batchIDs","__PRIVATE_removeCachedMutationKeys","markPotentiallyOrphaned","performConsistencyCheck","__PRIVATE_startRange","__PRIVATE_newDbDocumentMutationPrefixForUser","__PRIVATE_danglingMutationReferences","__PRIVATE_danglingKeys","containsKey","__PRIVATE_mutationQueueContainsKey","__PRIVATE_getMutationQueueMetadata","__PRIVATE_mutationQueuesStore","lastAcknowledgedBatchId","lastStreamToken","keyPath","__PRIVATE_TargetIdGenerator","__PRIVATE_lastId","__PRIVATE_forTargetCache","__PRIVATE_forSyncEngine","__PRIVATE_IndexedDbTargetCache","allocateTargetId","__PRIVATE_retrieveMetadata","__PRIVATE_targetIdGenerator","highestTargetId","__PRIVATE_saveMetadata","getLastRemoteSnapshotVersion","lastRemoteSnapshotVersion","getHighestSequenceNumber","__PRIVATE_targetGlobal","highestListenSequenceNumber","setTargetsMetadata","addTargetData","__PRIVATE_saveTargetData","targetCount","__PRIVATE_updateMetadataFromTargetData","updateTargetData","removeTargetData","removeMatchingKeysForTargetId","__PRIVATE_targetsStore","removeTargets","activeTargetIds","__PRIVATE_globalTargetStore","updated","getTargetCount","getTargetData","addMatchingKeys","__PRIVATE_documentTargetStore","addReference","removeMatchingKeys","removeReference","getMatchingKeysForTargetId","__PRIVATE_LRU_MINIMUM_CACHE_SIZE_BYTES","__PRIVATE_bufferEntryComparator","__PRIVATE_aSequence","__PRIVATE_aIndex","__PRIVATE_bSequence","__PRIVATE_bIndex","__PRIVATE_seqCmp","__PRIVATE_RollingSequenceNumberBuffer","__PRIVATE_maxElements","__PRIVATE_previousIndex","__PRIVATE_nextIndex","__PRIVATE_addElement","__PRIVATE_highestValue","maxValue","__PRIVATE_LruScheduler","garbageCollector","__PRIVATE_gcTask","params","__PRIVATE_scheduleGC","collectGarbage","__PRIVATE_LruGarbageCollectorImpl","__PRIVATE_delegate","calculateTargetCount","percentile","__PRIVATE_getSequenceNumberCount","nthSequenceNumber","__PRIVATE_forEachOrphanedDocumentSequenceNumber","removeOrphanedDocuments","collect","getCacheSize","__PRIVATE_runGarbageCollection","__PRIVATE_upperBoundSequenceNumber","__PRIVATE_sequenceNumbersToCollect","__PRIVATE_countedTargetsTs","__PRIVATE_foundUpperBoundTs","__PRIVATE_removedTargetsTs","__PRIVATE_removedDocumentsTs","__PRIVATE_startTs","__PRIVATE_sequenceNumbers","__PRIVATE_numTargetsRemoved","__PRIVATE_newLruGarbageCollector","__PRIVATE_IndexedDbLruDelegateImpl","__PRIVATE_docCountPromise","__PRIVATE_orphanedDocumentCount","getTargetCache","__PRIVATE_docCount","__PRIVATE_orphanedCount","__PRIVATE_forEachOrphanedDocument","__PRIVATE_writeSentinelKey","__PRIVATE_isPinned","__PRIVATE_mutationQueuesContainKey","__PRIVATE_changeBuffer","getRemoteDocumentCache","newChangeBuffer","__PRIVATE_documentCount","getEntry","removeEntry","__PRIVATE_sentinelKey","apply","updateLimboDocument","__PRIVATE_nextPath","__PRIVATE_nextToReport","getSize","__PRIVATE_sentinelRow","RemoteDocumentChangeBuffer","changesApplied","addEntry","assertNotApplied","__PRIVATE_bufferedEntry","getFromCache","getAllFromCache","__PRIVATE_IndexedDbRemoteDocumentCacheImpl","setIndexManager","__PRIVATE_remoteDocumentsStore","__PRIVATE_dbReadTimeKey","updateMetadata","__PRIVATE_sizeDelta","getMetadata","byteSize","__PRIVATE_setMetadata","__PRIVATE_dbKey","__PRIVATE_dbRemoteDoc","__PRIVATE_maybeDecodeDocument","__PRIVATE_getSizedEntry","__PRIVATE_forEachDbEntry","__PRIVATE_getSizedEntries","__PRIVATE_sizeMap","__PRIVATE_dbKeyComparator","__PRIVATE_keyIter","__PRIVATE_potentialKey","getDocumentsMatchingQuery","mutatedDocs","__PRIVATE_endKey","__PRIVATE_dbRemoteDocs","incrementDocumentReadCount","getAllFromCollectionGroup","__PRIVATE_dbCollectionGroupKey","__PRIVATE_IndexedDbRemoteDocumentChangeBuffer","trackRemovals","__PRIVATE_documentGlobalStore","__PRIVATE_newIndexedDbRemoteDocumentCache","__PRIVATE_documentCache","__PRIVATE_previousDoc","__PRIVATE_documentStates","__PRIVATE_deletedDoc","__PRIVATE_getResult","OverlayedDocument","LocalDocumentsView","remoteDocumentCache","mutationQueue","documentOverlayCache","getDocument","getDocuments","getLocalViewOfDocuments","existenceStateChanged","populateOverlays","computeViews","__PRIVATE_computeViewsResult","getOverlayedDocuments","__PRIVATE_missingOverlays","__PRIVATE_recalculateDocuments","__PRIVATE_newOverlayedDocumentMap","recalculateAndSaveOverlays","__PRIVATE_recalculatedFields","__PRIVATE_masks","__PRIVATE_documentsByBatchId","key1","key2","__PRIVATE_processed","__PRIVATE_batches","__PRIVATE_baseDoc","__PRIVATE_newSet","recalculateAndSaveOverlaysForDocumentKeys","getDocumentsMatchingDocumentQuery","getDocumentsMatchingCollectionGroupQuery","getDocumentsMatchingCollectionQuery","__PRIVATE_originalDocs","__PRIVATE_overlaysPromise","__PRIVATE_modifiedDocs","__PRIVATE_localDocs","__PRIVATE_parents","__PRIVATE_collectionQuery","__PRIVATE_asCollectionQueryAtPath","__PRIVATE_remoteDocuments","__PRIVATE_MemoryBundleCache","__PRIVATE_bundles","__PRIVATE_fromBundleMetadata","__PRIVATE_namedQueries","__PRIVATE_fromProtoNamedQuery","namedQuery","__PRIVATE_MemoryDocumentOverlayCache","__PRIVATE_overlayByBatchId","__PRIVATE_immediateChildrenPathLength","__PRIVATE_batchIdToOverlays","__PRIVATE_overlaysForBatchId","__PRIVATE_batchIter","__PRIVATE_existing","__PRIVATE_MemoryGlobalsCache","__PRIVATE_ReferenceSet","__PRIVATE_refsByKey","__PRIVATE_DocReference","__PRIVATE_compareByKey","__PRIVATE_refsByTarget","__PRIVATE_compareByTargetId","ref","__PRIVATE_addReferences","__PRIVATE_removeRef","__PRIVATE_removeReferences","__PRIVATE_removeReferencesForId","__PRIVATE_emptyKey","__PRIVATE_startRef","__PRIVATE_endRef","__PRIVATE_removeAllReferences","__PRIVATE_referencesForId","__PRIVATE_firstRef","__PRIVATE_targetOrBatchId","__PRIVATE_MemoryMutationQueue","__PRIVATE_batchesByDocumentKey","__PRIVATE_findMutationBatch","__PRIVATE_rawIndex","__PRIVATE_indexOfBatchId","__PRIVATE_findMutationBatches","__PRIVATE_startPath","__PRIVATE_rowKeyPath","__PRIVATE_indexOfExistingBatchId","shift","__PRIVATE_references","__PRIVATE_MemoryRemoteDocumentCacheImpl","__PRIVATE_sizer","__PRIVATE_documentEntryMap","__PRIVATE_forEachDocumentKey","__PRIVATE_MemoryRemoteDocumentChangeBuffer","__PRIVATE_MemoryTargetCache","__PRIVATE_highestSequenceNumber","__PRIVATE_removals","__PRIVATE_matchingKeys","__PRIVATE_MemoryPersistence","__PRIVATE_referenceDelegateFactory","__PRIVATE_mutationQueues","__PRIVATE_listenSequence","__PRIVATE__started","__PRIVATE_globalsCache","__PRIVATE_targetCache","__PRIVATE_newMemoryRemoteDocumentCache","__PRIVATE_documentSize","__PRIVATE_bundleCache","setDatabaseDeletedListener","setNetworkEnabled","getIndexManager","getDocumentOverlayCache","getMutationQueue","__PRIVATE_queue","getGlobalsCache","getBundleCache","transactionOperation","__PRIVATE_MemoryTransaction","__PRIVATE_onTransactionStarted","__PRIVATE_onTransactionCommitted","__PRIVATE_MemoryEagerDelegate","__PRIVATE__orphanedDocuments","__PRIVATE_factory","__PRIVATE_orphanedDocuments","__PRIVATE_localViewReferences","cache","__PRIVATE_isReferenced","__PRIVATE_MemoryLruDelegate","__PRIVATE_lruParams","__PRIVATE_orphanedSequenceNumbers","__PRIVATE_orphanedAt","__PRIVATE_SchemaConverter","__PRIVATE_createPrimaryClientStore","createObjectStore","__PRIVATE_createMutationQueue","__PRIVATE_mutationBatchesStore","autoIncrement","createIndex","unique","__PRIVATE_createQueryCache","__PRIVATE_createLegacyRemoteDocumentCache","__PRIVATE_dropQueryCache","deleteObjectStore","__PRIVATE_writeEmptyTargetGlobalEntry","__PRIVATE_globalStore","__PRIVATE_upgradeMutationBatchSchemaAndMigrateData","__PRIVATE_v1MutationsStore","__PRIVATE_existingMutations","__PRIVATE_v3MutationsStore","__PRIVATE_writeAll","__PRIVATE_createClientMetadataStore","__PRIVATE_removeAcknowledgedMutations","__PRIVATE_createDocumentGlobalStore","__PRIVATE_addDocumentGlobal","__PRIVATE_ensureSequenceNumbers","__PRIVATE_createCollectionParentIndex","__PRIVATE_dropRemoteDocumentChangesStore","__PRIVATE_rewriteCanonicalIds","__PRIVATE_createBundlesStore","__PRIVATE_createNamedQueriesStore","__PRIVATE_createDocumentOverlayStore","__PRIVATE_createRemoteDocumentCache","__PRIVATE_remoteDocumentStore","__PRIVATE_rewriteRemoteDocumentCache","__PRIVATE_runOverlayMigration","__PRIVATE_createFieldIndex","__PRIVATE_indexEntryStore","clear","__PRIVATE_createGlobalsStore","__PRIVATE_queuesStore","__PRIVATE_queues","__PRIVATE_documentsStore","__PRIVATE_docSentinelKey","__PRIVATE_maybeSentinel","pathSegments","__PRIVATE_targetStore","__PRIVATE_originalDbTarget","__PRIVATE_originalTargetData","__PRIVATE_updatedDbTarget","__PRIVATE_legacyRemoteDocumentStore","writes","__PRIVATE_legacyDocument","__PRIVATE_extractKey","__PRIVATE_dbRemoteDocument","__PRIVATE_memoryPersistence","__PRIVATE_userToDocumentSet","__PRIVATE_documentSet","__PRIVATE_allDocumentKeysForUser","__PRIVATE_MAX_CLIENT_AGE_MS","__PRIVATE_MAX_PRIMARY_ELIGIBLE_AGE_MS","__PRIVATE_PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG","__PRIVATE_MAIN_DATABASE","__PRIVATE_IndexedDbPersistence","allowTabSynchronization","clientId","window","__PRIVATE_forceOwningTab","__PRIVATE_schemaVersion","isPrimary","networkEnabled","__PRIVATE_windowUnloadHandler","inForeground","__PRIVATE_documentVisibilityHandler","__PRIVATE_clientMetadataRefresher","__PRIVATE_primaryStateListener","__PRIVATE_dbName","__PRIVATE_simpleDb","localStorage","__PRIVATE_webStorage","__PRIVATE_updateClientMetadataAndTryBecomePrimary","__PRIVATE_attachVisibilityHandler","__PRIVATE_attachWindowUnloadHook","__PRIVATE_scheduleClientMetadataAndPrimaryLeaseRefreshes","reason","__PRIVATE_setPrimaryStateListener","__PRIVATE_primaryState","databaseDeletedListener","newVersion","enqueueAndForget","__PRIVATE_clientMetadataStore","updateTimeMs","__PRIVATE_verifyPrimaryLease","__PRIVATE_success","__PRIVATE_canActAsPrimary","__PRIVATE_releasePrimaryLeaseIfHeld","__PRIVATE_acquireOrExtendPrimaryLease","__PRIVATE_primaryClientStore","__PRIVATE_primaryClient","__PRIVATE_isLocalClient","__PRIVATE_removeClientMetadata","__PRIVATE_maybeGarbageCollectMultiClientState","__PRIVATE_isWithinAge","__PRIVATE_lastGarbageCollectionTime","__PRIVATE_inactiveClients","__PRIVATE_metadataStore","__PRIVATE_existingClients","active","__PRIVATE_filterActiveClients","__PRIVATE_inactive","__PRIVATE_client","__PRIVATE_inactiveClient","removeItem","__PRIVATE_zombiedClientLocalStorageKey","ownerId","__PRIVATE_currentPrimary","leaseTimestampMs","__PRIVATE_isClientZombied","__PRIVATE_otherClient","__PRIVATE_otherClientHasBetterNetworkState","__PRIVATE_otherClientHasBetterVisibility","__PRIVATE_otherClientHasSameNetworkState","__PRIVATE_markClientZombied","__PRIVATE_detachVisibilityHandler","__PRIVATE_detachWindowUnloadHook","__PRIVATE_simpleDbTxn","__PRIVATE_persistenceTransaction","__PRIVATE_removeClientZombiedEntry","__PRIVATE_clients","__PRIVATE_activityThresholdMs","__PRIVATE_getActiveClients","__PRIVATE_clientMetadata","__PRIVATE_simpleDbMode","__PRIVATE_getObjectStores","__PRIVATE_holdsPrimaryLease","__PRIVATE_verifyAllowTabSynchronization","__PRIVATE_newPrimary","__PRIVATE_maxAgeMs","addEventListener","visibilityState","removeEventListener","__PRIVATE_safariIndexdbBugVersionRegex","isSafari","navigator","appVersion","userAgent","enterRestrictedMode","__PRIVATE_isZombied","getItem","setItem","__PRIVATE_indexedDbStoragePrefix","__PRIVATE_LocalViewChanges","fromCache","__PRIVATE_addedKeys","__PRIVATE_removedKeys","__PRIVATE_fromSnapshot","__PRIVATE_viewSnapshot","docChanges","QueryContext","_documentReadCount","documentReadCount","amount","__PRIVATE_QueryEngine","__PRIVATE_initialized","__PRIVATE_indexAutoCreationEnabled","__PRIVATE_indexAutoCreationMinCollectionSize","__PRIVATE_relativeIndexReadCostPerDocument","__PRIVATE_getDefaultRelativeIndexReadCostPerDocument","initialize","__PRIVATE_localDocumentsView","__PRIVATE_remoteKeys","__PRIVATE_queryResult","__PRIVATE_performQueryUsingIndex","__PRIVATE_performQueryUsingRemoteKeys","__PRIVATE_executeFullCollectionScan","__PRIVATE_createCacheIndexes","__PRIVATE_resultSize","__PRIVATE_indexedDocuments","__PRIVATE_previousResults","__PRIVATE_applyQuery","__PRIVATE_needsRefill","__PRIVATE_appendRemainingResults","__PRIVATE_queryResults","__PRIVATE_maybeDoc","__PRIVATE_sortedPreviousResults","__PRIVATE_limboFreeSnapshotVersion","__PRIVATE_docAtLimitEdge","__PRIVATE_indexedResults","__PRIVATE_remainingResults","d","__PRIVATE_RESUME_TOKEN_MAX_AGE_MICROS","__PRIVATE_LocalStoreImpl","__PRIVATE_queryEngine","initialUser","__PRIVATE_targetDataByTarget","__PRIVATE_targetIdByTarget","__PRIVATE_initializeUserComponents","__PRIVATE_newLocalStore","__PRIVATE_localStoreHandleUserChange","__PRIVATE_localStoreImpl","__PRIVATE_oldBatches","__PRIVATE_promisedOldBatches","__PRIVATE_newBatches","removedBatchIds","addedBatchIds","__PRIVATE_changedKeys","__PRIVATE_affectedDocuments","__PRIVATE_localStoreAcknowledgeBatch","__PRIVATE_affected","__PRIVATE_documentBuffer","__PRIVATE_applyWriteToRemoteDocuments","__PRIVATE_docKeys","__PRIVATE_promiseChain","__PRIVATE_ackVersion","__PRIVATE_getKeysWithTransformResults","__PRIVATE_localStoreGetLastRemoteSnapshotVersion","__PRIVATE_localStoreApplyRemoteEventToLocalCache","__PRIVATE_remoteVersion","__PRIVATE_newTargetDataByTargetMap","__PRIVATE_oldTargetData","__PRIVATE_newTargetData","__PRIVATE_shouldPersistTargetData","__PRIVATE_timeDelta","__PRIVATE_changedDocs","__PRIVATE_existenceChangedKeys","__PRIVATE_populateDocumentChangeBuffer","__PRIVATE_changedDocuments","__PRIVATE_updateRemoteVersion","__PRIVATE_updatedKeys","__PRIVATE_existingDocs","__PRIVATE_existingDoc","__PRIVATE_localStoreGetNextMutationBatch","__PRIVATE_afterBatchId","__PRIVATE_localStoreAllocateTarget","__PRIVATE_cached","__PRIVATE_cachedTargetData","__PRIVATE_localStoreReleaseTarget","__PRIVATE_keepPersistedTargetData","__PRIVATE_localStoreExecuteQuery","__PRIVATE_usePreviousResults","__PRIVATE_localStoreGetTargetData","__PRIVATE_setMaxReadTime","__PRIVATE_localStoreGetCachedTarget","__PRIVATE_targetCacheImpl","__PRIVATE_localStoreGetNewDocumentChanges","__PRIVATE_collectionGroupReadTime","__PRIVATE_localStoreApplyBundledDocuments","__PRIVATE_bundleConverter","bundleName","__PRIVATE_bundleDoc","__PRIVATE_toDocumentKey","__PRIVATE_toMutableDocument","__PRIVATE_toSnapshotVersion","__PRIVATE_umbrellaTargetData","__PRIVATE_umbrellaTarget","__PRIVATE_documentChangeResult","__PRIVATE_localStoreSaveNamedQuery","__PRIVATE_allocated","CLIENT_STATE_KEY_PREFIX","createWebStorageClientStateKey","MUTATION_BATCH_KEY_PREFIX","createWebStorageMutationBatchKey","__PRIVATE_mutationKey","QUERY_TARGET_KEY_PREFIX","createWebStorageQueryTargetMetadataKey","__PRIVATE_MutationMetadata","__PRIVATE_fromWebStorageEntry","__PRIVATE_mutationBatch","parse","__PRIVATE_firestoreError","__PRIVATE_validData","__PRIVATE_toWebStorageJSON","__PRIVATE_batchMetadata","__PRIVATE_QueryTargetMetadata","__PRIVATE_RemoteClientState","__PRIVATE_clientState","__PRIVATE_activeTargetIdsSet","__PRIVATE_SharedOnlineState","onlineState","__PRIVATE_LocalClientState","__PRIVATE_addQueryTarget","__PRIVATE_removeQueryTarget","__PRIVATE_WebStorageSharedClientState","__PRIVATE_localClientId","syncEngine","onlineStateHandler","__PRIVATE_storageListener","__PRIVATE_handleWebStorageEvent","bind","__PRIVATE_activeClients","__PRIVATE_earlyEvents","__PRIVATE_escapedPersistenceKey","storage","__PRIVATE_localClientStorageKey","__PRIVATE_sequenceNumberKey","createWebStorageSequenceNumberKey","__PRIVATE_clientStateKeyRe","__PRIVATE_mutationBatchKeyRe","__PRIVATE_queryTargetKeyRe","__PRIVATE_onlineStateKey","createWebStorageOnlineStateKey","__PRIVATE_bundleLoadedKey","createBundleLoadedKey","__PRIVATE_storageItem","__PRIVATE_persistClientState","__PRIVATE_onlineStateJSON","__PRIVATE_fromWebStorageOnlineState","__PRIVATE_handleOnlineStateEvent","getAllActiveQueryTargets","__PRIVATE_extractActiveQueryTargets","isActiveQueryTarget","addPendingMutation","__PRIVATE_persistMutationState","updateMutationState","__PRIVATE_removeMutationState","addLocalQueryTarget","addToActiveTargetIds","__PRIVATE_queryState","__PRIVATE_localClientState","removeLocalQueryTarget","isLocalQueryTarget","clearQueryState","updateQueryState","__PRIVATE_persistQueryTargetState","handleUserChange","setOnlineState","__PRIVATE_persistOnlineState","notifyBundleLoaded","collectionGroups","__PRIVATE_persistBundleLoadedState","__PRIVATE_storageEvent","storageArea","__PRIVATE_fromWebStorageClientStateKey","__PRIVATE_handleClientStateEvent","__PRIVATE_fromWebStorageClientState","__PRIVATE_mutationMetadata","__PRIVATE_fromWebStorageMutationMetadata","__PRIVATE_handleMutationBatchEvent","__PRIVATE_queryTargetMetadata","__PRIVATE_fromWebStorageQueryTargetMetadata","__PRIVATE_handleQueryTargetEvent","__PRIVATE_fromWebStorageSequenceNumber","__PRIVATE_seqString","__PRIVATE_parsed","__PRIVATE_fromWebStoreBundleLoadedState","__PRIVATE_cg","__PRIVATE_synchronizeWithChangedDocuments","__PRIVATE_mutationState","__PRIVATE_targetKey","__PRIVATE_targetMetadata","__PRIVATE_applyBatchState","__PRIVATE_applyTargetState","__PRIVATE_updatedClients","__PRIVATE_existingTargets","__PRIVATE_newTargets","__PRIVATE_addedTargets","__PRIVATE_removedTargets","__PRIVATE_applyActiveTargetsChange","__PRIVATE_activeTargets","__PRIVATE_kev","__PRIVATE_MemorySharedClientState","__PRIVATE_localState","__PRIVATE_NoopConnectivityMonitor","__PRIVATE_addCallback","__PRIVATE_BrowserConnectivityMonitor","__PRIVATE_networkAvailableListener","__PRIVATE_onNetworkAvailable","__PRIVATE_networkUnavailableListener","__PRIVATE_onNetworkUnavailable","__PRIVATE_callbacks","__PRIVATE_configureNetworkMonitoring","__PRIVATE_lastUniqueDebugId","__PRIVATE_generateUniqueDebugId","__PRIVATE_generateInitialUniqueDebugId","round","__PRIVATE_maxResult","__PRIVATE_RPC_NAME_URL_MAPPING","__PRIVATE_RestConnection","__PRIVATE_shouldResourcePathBeIncludedInRequest","databaseInfo","__PRIVATE_baseUrl","__PRIVATE_databasePath","__PRIVATE_requestParams","__PRIVATE_invokeRPC","__PRIVATE_rpcName","__PRIVATE_req","__PRIVATE_authToken","streamId","url","__PRIVATE_makeUrl","__PRIVATE_modifyHeadersForRequest","URL","__PRIVATE_forwardCredentials","isCloudWorkstation","__PRIVATE_performRPCRequest","response","__PRIVATE_invokeStreamingRPC","__PRIVATE_expectedResponseCount","__PRIVATE_getGoogApiClientValue","__PRIVATE_urlRpcName","terminate","__PRIVATE_StreamBridge","__PRIVATE_sendFn","__PRIVATE_closeFn","__PRIVATE_onConnected","__PRIVATE_wrappedOnConnected","__PRIVATE_onOpen","__PRIVATE_wrappedOnOpen","__PRIVATE_onClose","__PRIVATE_wrappedOnClose","onMessage","__PRIVATE_wrappedOnMessage","send","__PRIVATE_callOnConnected","__PRIVATE_callOnOpen","__PRIVATE_callOnClose","__PRIVATE_callOnMessage","__PRIVATE_WebChannelConnection","info","__PRIVATE_openWebChannels","body","__PRIVATE__forwardCredentials","__PRIVATE_xhr","XhrIo","setWithCredentials","listenOnce","EventType","COMPLETE","getLastErrorCode","ErrorCode","NO_ERROR","getResponseJson","TIMEOUT","HTTP_ERROR","getStatus","getResponseText","__PRIVATE_responseError","__PRIVATE_firestoreErrorCode","__PRIVATE_mapCodeFromHttpResponseErrorStatus","__PRIVATE_serverError","toLowerCase","__PRIVATE_lastErrorCode","__PRIVATE_lastError","getLastError","__PRIVATE_requestString","__PRIVATE_openStream","__PRIVATE_urlParts","__PRIVATE_webchannelTransport","createWebChannelTransport","__PRIVATE_requestStats","getStatEventTarget","httpSessionIdParam","initMessageHeaders","messageUrlParams","sendRawJson","supportsCrossDomainXhr","internalChannelParams","forwardChannelRequestTimeoutMs","detectBufferingProxy","__PRIVATE_longPollingTimeoutSeconds","timeoutSeconds","longPollingTimeout","encodeInitMessageHeaders","channel","createWebChannel","__PRIVATE_addOpenWebChannel","__PRIVATE_opened","closed","__PRIVATE_streamBridge","__PRIVATE_unguardedEventListen","listen","param","WebChannel","OPEN","CLOSE","__PRIVATE_removeOpenWebChannel","MESSAGE","__PRIVATE_msgData","__PRIVATE_msgDataOrError","__PRIVATE_mapCodeFromRpcStatus","Event","STAT_EVENT","stat","Stat","PROXY","NOPROXY","__PRIVATE_webChannel","instance","__PRIVATE_getWindow","__PRIVATE_newSerializer","__PRIVATE_ExponentialBackoff","timerId","__PRIVATE_initialDelayMs","__PRIVATE_backoffFactor","__PRIVATE_maxDelayMs","__PRIVATE_currentBaseMs","__PRIVATE_timerPromise","__PRIVATE_resetToMax","__PRIVATE_backoffAndRun","__PRIVATE_desiredDelayWithJitterMs","__PRIVATE_jitterDelayMs","__PRIVATE_delaySoFarMs","__PRIVATE_lastAttemptTime","__PRIVATE_remainingDelayMs","__PRIVATE_skipBackoff","skipDelay","__PRIVATE_PersistentStream","__PRIVATE_connectionTimerId","__PRIVATE_idleTimerId","__PRIVATE_healthTimerId","connection","authCredentialsProvider","appCheckCredentialsProvider","__PRIVATE_closeCount","__PRIVATE_idleTimer","__PRIVATE_healthCheck","stream","__PRIVATE_responseCount","__PRIVATE_backoff","__PRIVATE_isStarted","__PRIVATE_isOpen","__PRIVATE_performBackoff","__PRIVATE_inhibitBackoff","__PRIVATE_markIdle","__PRIVATE_handleIdleCloseTimer","__PRIVATE_sendRequest","__PRIVATE_cancelIdleCheck","__PRIVATE_cancelHealthCheck","__PRIVATE_finalState","__PRIVATE_tearDown","__PRIVATE_dispatchIfNotClosed","__PRIVATE_getCloseGuardedDispatcher","__PRIVATE_startStream","__PRIVATE_rpcError","__PRIVATE_handleStreamClose","__PRIVATE_startRpc","__PRIVATE_onFirst","onNext","__PRIVATE_startCloseCount","__PRIVATE_PersistentListenStream","authCredentials","appCheckCredentials","__PRIVATE_watchChangeProto","snapshot","__PRIVATE_versionFromListenResponse","__PRIVATE_onWatchChange","__PRIVATE_watch","addTarget","__PRIVATE_toTarget","labels","__PRIVATE_unwatch","__PRIVATE_PersistentWriteStream","__PRIVATE_handshakeComplete","__PRIVATE_writeMutations","__PRIVATE_responseProto","streamToken","writeResults","__PRIVATE_onHandshakeComplete","__PRIVATE_onMutationResult","__PRIVATE_writeHandshake","Datastore","__PRIVATE_DatastoreImpl","__PRIVATE_terminated","__PRIVATE_verifyInitialized","__PRIVATE_OnlineStateTracker","__PRIVATE_watchStreamFailures","__PRIVATE_onlineStateTimer","__PRIVATE_shouldWarnClientIsOffline","__PRIVATE_handleWatchStreamStart","__PRIVATE_setAndBroadcast","__PRIVATE_logClientOfflineWarningIfNecessary","__PRIVATE_handleWatchStreamFailure","__PRIVATE_clearOnlineStateTimer","newState","details","__PRIVATE_RemoteStoreImpl","datastore","__PRIVATE_connectivityMonitor","remoteSyncer","__PRIVATE_writePipeline","__PRIVATE_onNetworkStatusChange","__PRIVATE_canUseNetwork","__PRIVATE_restartNetwork","remoteStore","__PRIVATE_remoteStoreImpl","__PRIVATE_offlineCauses","__PRIVATE_disableNetworkInternal","__PRIVATE_onlineStateTracker","__PRIVATE_enableNetworkInternal","__PRIVATE_networkStatusHandler","__PRIVATE_remoteStoreListen","__PRIVATE_listenTargets","__PRIVATE_shouldStartWatchStream","__PRIVATE_startWatchStream","__PRIVATE_ensureWatchStream","__PRIVATE_sendWatchRequest","__PRIVATE_remoteStoreUnlisten","__PRIVATE_watchStream","__PRIVATE_sendUnwatchRequest","__PRIVATE_watchChangeAggregator","__PRIVATE_cleanUpWatchStreamState","__PRIVATE_onWatchStreamConnected","__PRIVATE_onWatchStreamOpen","__PRIVATE_onWatchStreamClose","__PRIVATE_onWatchStreamChange","__PRIVATE_handleTargetError","rejectListen","__PRIVATE_disableNetworkUntilRecovery","__PRIVATE_raiseWatchSnapshot","__PRIVATE_targetPurpose","__PRIVATE_requestTargetData","applyRemoteEvent","__PRIVATE_executeWithRecovery","__PRIVATE_fillWritePipeline","__PRIVATE_writeStream","__PRIVATE_ensureWriteStream","__PRIVATE_lastBatchIdRetrieved","__PRIVATE_canAddToWritePipeline","__PRIVATE_addToWritePipeline","__PRIVATE_shouldStartWriteStream","__PRIVATE_startWriteStream","__PRIVATE_onWriteStreamOpen","__PRIVATE_onWriteHandshakeComplete","applySuccessfulWrite","__PRIVATE_onWriteStreamClose","__PRIVATE_handleWriteError","__PRIVATE_isPermanentWriteError","rejectFailedWrite","__PRIVATE_remoteStoreHandleCredentialChange","verifyOperationInProgress","__PRIVATE_usesNetwork","handleCredentialChange","__PRIVATE_remoteStoreApplyPrimaryState","__PRIVATE_newPersistentWatchStream","__PRIVATE_datastoreImpl","enabled","__PRIVATE_newPersistentWriteStream","DelayedOperation","targetTimeMs","removalCallback","deferred","createAndSchedule","delayMs","__PRIVATE_targetTime","__PRIVATE_delayedOp","timerHandle","handleDelayElapsed","clearTimeout","__PRIVATE_wrapInUserErrorIfRecoverable","DocumentSet","emptySet","oldSet","keyedMap","sortedSet","__PRIVATE_thisDoc","__PRIVATE_otherDoc","__PRIVATE_docStrings","__PRIVATE_DocumentChangeSet","__PRIVATE_changeMap","track","__PRIVATE_oldChange","__PRIVATE_getChanges","ViewSnapshot","oldDocs","mutatedKeys","syncStateChanged","excludesMetadataChanges","hasCachedResults","fromInitialDocuments","__PRIVATE_otherChanges","__PRIVATE_QueryListenersInfo","__PRIVATE_viewSnap","__PRIVATE_listeners","__PRIVATE_hasRemoteListeners","__PRIVATE_listensToRemoteStore","__PRIVATE_EventManagerImpl","queries","__PRIVATE_newQueriesObjectMap","__PRIVATE_errorAllTargets","eventManager","__PRIVATE_eventManagerImpl","__PRIVATE_queryInfo","onError","q","__PRIVATE_eventManagerListen","__PRIVATE_listenerAction","onListen","onFirstRemoteStoreListen","__PRIVATE_applyOnlineStateChange","__PRIVATE_onViewSnapshot","__PRIVATE_raiseSnapshotsInSyncEvent","__PRIVATE_eventManagerUnlisten","onUnlisten","onLastRemoteStoreUnlisten","__PRIVATE_eventManagerOnWatchChange","__PRIVATE_viewSnaps","__PRIVATE_raisedEvent","__PRIVATE_eventManagerOnWatchError","__PRIVATE_snapshotsInSyncListeners","observer","__PRIVATE_ListenerDataSource","ListenerDataSource","__PRIVATE_QueryListener","__PRIVATE_queryObserver","__PRIVATE_raisedInitialEvent","__PRIVATE_snap","includeMetadataChanges","__PRIVATE_shouldRaiseEvent","__PRIVATE_shouldRaiseInitialEvent","__PRIVATE_raiseInitialEvent","__PRIVATE_maybeOnline","__PRIVATE_waitForSyncWhenOnline","__PRIVATE_hasPendingWritesChanged","Cache","__PRIVATE_SizedBundleElement","__PRIVATE_payload","byteLength","__PRIVATE_isBundleMetadata","__PRIVATE_BundleConverterImpl","__PRIVATE_bundledDoc","time","__PRIVATE_BundleLoader","__PRIVATE__queries","__PRIVATE__documents","progress","__PRIVATE_bundleInitialProgress","__PRIVATE_addSizedElement","bytesLoaded","documentsLoaded","documentMetadata","__PRIVATE_getQueryDocumentMapping","__PRIVATE_queryDocumentMap","__PRIVATE_completeAndStoreAsync","taskState","__PRIVATE_changedCollectionGroups","totalDocuments","totalBytes","__PRIVATE_AddedLimboDocument","__PRIVATE_RemovedLimboDocument","__PRIVATE_View","__PRIVATE__syncedDocuments","__PRIVATE_syncState","__PRIVATE_limboDocuments","__PRIVATE_docComparator","__PRIVATE_syncedDocuments","__PRIVATE_computeDocChanges","__PRIVATE_previousChanges","__PRIVATE_changeSet","__PRIVATE_oldDocumentSet","__PRIVATE_newMutatedKeys","__PRIVATE_newDocumentSet","__PRIVATE_lastDocInLimit","__PRIVATE_firstDocInLimit","__PRIVATE_oldDoc","__PRIVATE_oldDocHadPendingMutations","__PRIVATE_newDocHasPendingMutations","__PRIVATE_changeApplied","__PRIVATE_shouldWaitForSyncedDocument","__PRIVATE_limboResolutionEnabled","__PRIVATE_targetIsPendingReset","__PRIVATE_c1","__PRIVATE_c2","__PRIVATE_compareChangeType","__PRIVATE_applyTargetChange","__PRIVATE_limboChanges","__PRIVATE_updateLimboDocuments","__PRIVATE_newSyncState","__PRIVATE_shouldBeInLimbo","__PRIVATE_oldLimboDocuments","__PRIVATE_synchronizeWithPersistedState","__PRIVATE_computeInitialSnapshot","__PRIVATE_QueryView","view","LimboResolution","__PRIVATE_receivedDocument","__PRIVATE_SyncEngineImpl","sharedClientState","maxConcurrentLimboResolutions","__PRIVATE_syncEngineListener","__PRIVATE_queryViewsByQuery","__PRIVATE_activeLimboTargetsByKey","__PRIVATE_mutationUserCallbacks","__PRIVATE__isPrimaryClient","isPrimaryClient","__PRIVATE_syncEngineListen","__PRIVATE_shouldListenToRemote","__PRIVATE_syncEngineImpl","__PRIVATE_ensureWatchCallbacks","__PRIVATE_queryView","__PRIVATE_allocateTargetAndMaybeListen","__PRIVATE_triggerRemoteStoreListen","__PRIVATE_shouldInitializeView","__PRIVATE_initializeViewAndComputeSnapshot","__PRIVATE_applyDocChanges","__PRIVATE_viewDocChanges","__PRIVATE_viewChange","__PRIVATE_updateTrackedLimbos","__PRIVATE_synthesizedTargetChange","__PRIVATE_queriesByTarget","__PRIVATE_syncEngineUnlisten","__PRIVATE_shouldUnlistenToRemote","__PRIVATE_removeAndCleanupTarget","__PRIVATE_triggerRemoteStoreUnlisten","__PRIVATE_syncEngineWrite","__PRIVATE_userCallback","__PRIVATE_syncEngineEnsureWriteCallbacks","__PRIVATE_localStoreWriteLocally","__PRIVATE_overlayedDocuments","__PRIVATE_remoteDocs","__PRIVATE_docsWithoutRemoteVersion","__PRIVATE_addMutationCallback","__PRIVATE_newCallbacks","__PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore","__PRIVATE_syncEngineApplyRemoteEvent","__PRIVATE_limboResolution","__PRIVATE_activeLimboResolutionsByTarget","__PRIVATE_syncEngineApplyOnlineStateChange","__PRIVATE_newViewSnapshots","__PRIVATE_eventManagerOnOnlineStateChange","__PRIVATE_syncEngineRejectListen","__PRIVATE_limboKey","__PRIVATE_pumpEnqueuedLimboResolutions","__PRIVATE_syncEngineApplySuccessfulWrite","__PRIVATE_mutationBatchResult","__PRIVATE_processUserCallback","__PRIVATE_triggerPendingWritesCallbacks","__PRIVATE_syncEngineRejectFailedWrite","__PRIVATE_localStoreRejectBatch","__PRIVATE_affectedKeys","__PRIVATE_syncEngineRegisterPendingWritesCallback","__PRIVATE_highestBatchId","__PRIVATE_localStoreGetHighestUnacknowledgedBatchId","__PRIVATE_pendingWritesCallbacks","__PRIVATE_onWatchError","__PRIVATE_limboDocumentRefs","__PRIVATE_removeLimboTarget","__PRIVATE_enqueuedLimboResolutions","__PRIVATE_limboTargetId","__PRIVATE_limboChange","__PRIVATE_trackLimboChange","__PRIVATE_keyString","__PRIVATE_limboTargetIdGenerator","__PRIVATE_newSnaps","__PRIVATE_docChangesInAllViews","__PRIVATE_queriesProcessed","__PRIVATE_isCurrent","__PRIVATE_localStoreNotifyLocalViewChanges","__PRIVATE_viewChanges","__PRIVATE_updatedTargetData","__PRIVATE_syncEngineHandleCredentialChange","__PRIVATE_rejectOutstandingPendingWritesCallbacks","__PRIVATE_errorMessage","__PRIVATE_syncEngineGetRemoteKeysForTarget","__PRIVATE_keySet","__PRIVATE_synchronizeViewAndComputeSnapshot","__PRIVATE_syncEngineSynchronizeWithChangedDocuments","__PRIVATE_syncEngineApplyBatchState","__PRIVATE_batchState","__PRIVATE_localStoreLookupMutationDocuments","__PRIVATE_mutationQueueImpl","__PRIVATE_localStoreRemoveCachedMutationBatchMetadata","__PRIVATE_syncEngineApplyPrimaryState","__PRIVATE_activeQueries","__PRIVATE_synchronizeQueryViewsAndRaiseSnapshots","__PRIVATE_resetLimboDocuments","__PRIVATE_transitionToPrimary","__PRIVATE_synthesizeTargetToQuery","__PRIVATE_syncEngineGetActiveClients","__PRIVATE_localStoreGetActiveClients","__PRIVATE_syncEngineApplyTargetState","__PRIVATE_synthesizedRemoteEvent","__PRIVATE_syncEngineApplyActiveTargetsChange","__PRIVATE_syncEngineLoadBundle","__PRIVATE_bundleReader","__PRIVATE_loadBundleImpl","__PRIVATE_reader","__PRIVATE_localStoreHasNewerBundle","__PRIVATE_currentReadTime","_completeWith","__PRIVATE_bundleSuccessProgress","_updateProgress","__PRIVATE_loader","__PRIVATE_nextElement","__PRIVATE_localStoreSaveBundle","_failWith","__PRIVATE_MemoryOfflineComponentProvider","synchronizeTabs","cfg","__PRIVATE_createSharedClientState","__PRIVATE_createPersistence","__PRIVATE_createLocalStore","gcScheduler","__PRIVATE_createGarbageCollectionScheduler","indexBackfillerScheduler","__PRIVATE_createIndexBackfillerScheduler","provider","build","__PRIVATE_LruGcMemoryOfflineComponentProvider","cacheSizeBytes","__PRIVATE_IndexedDbOfflineComponentProvider","__PRIVATE_onlineComponentProvider","forceOwnership","__PRIVATE_indexBackfiller","__PRIVATE_MultiTabOfflineComponentProvider","OnlineComponentProvider","offlineComponentProvider","createDatastore","createRemoteStore","createEventManager","createSyncEngine","__PRIVATE_newEventManager","__PRIVATE_newConnection","__PRIVATE_newDatastore","__PRIVATE_newRemoteStore","__PRIVATE_newConnectivityMonitor","startAsPrimary","__PRIVATE_newSyncEngine","__PRIVATE_remoteStoreShutdown","__PRIVATE_toByteStreamReaderHelper","__PRIVATE_bytesPerRead","__PRIVATE_readFrom","read","releaseLock","__PRIVATE_AsyncObserver","muted","__PRIVATE_scheduleEvent","__PRIVATE_mute","__PRIVATE_eventHandler","__PRIVATE_BundleReaderImpl","__PRIVATE_textDecoder","__PRIVATE_newTextDecoder","TextDecoder","__PRIVATE_nextElementImpl","__PRIVATE_lengthBuffer","__PRIVATE_readLength","__PRIVATE_lengthString","decode","__PRIVATE_raiseError","__PRIVATE_jsonString","__PRIVATE_readJsonString","__PRIVATE_indexOfOpenBracket","findIndex","__PRIVATE_pullMoreDataToBuffer","__PRIVATE_BundleReaderSyncImpl","bundleData","__PRIVATE_getElements","__PRIVATE_startIndex","__PRIVATE_curIndex","Transaction","readVersions","committed","lastTransactionError","writtenDocs","lookup","ensureCommitNotCalled","__PRIVATE_invokeBatchGetDocumentsRpc","recordVersion","write","preconditionForUpdate","__PRIVATE_unwritten","__PRIVATE_invokeCommitRpc","__PRIVATE_docVersion","__PRIVATE_documentName","__PRIVATE_existingVersion","__PRIVATE_TransactionRunner","updateFunction","__PRIVATE_attemptsRemaining","maxAttempts","__PRIVATE_run","__PRIVATE_runWithBackOff","__PRIVATE_tryRunUpdateFunction","__PRIVATE_commitError","__PRIVATE_handleTransactionError","__PRIVATE_userPromiseError","__PRIVATE_isRetryableTransactionError","FirestoreClient","componentProvider","authCredentialListener","appCheckCredentialListener","_uninitializedComponentsProvider","__PRIVATE_newAppCheckToken","configuration","setCredentialChangeListener","setAppCheckTokenChangeListener","enqueueAndForgetEvenWhileRestricted","_onlineComponents","_offlineComponents","__PRIVATE_setOfflineComponentProvider","__PRIVATE_setOnlineComponentProvider","__PRIVATE_offlineComponents","__PRIVATE_ensureOfflineComponents","_offline","__PRIVATE_canFallbackFromIndexedDbError","__PRIVATE_ensureOnlineComponents","_online","__PRIVATE_getPersistence","__PRIVATE_getLocalStore","__PRIVATE_getRemoteStore","__PRIVATE_getSyncEngine","__PRIVATE_getDatastore","__PRIVATE_getEventManager","__PRIVATE_firestoreClientEnableNetwork","enqueue","__PRIVATE_remoteStoreEnableNetwork","__PRIVATE_firestoreClientDisableNetwork","__PRIVATE_remoteStoreDisableNetwork","__PRIVATE_firestoreClientGetDocumentFromLocalCache","__PRIVATE_readDocumentFromCache","__PRIVATE_localStoreReadDocument","__PRIVATE_firestoreClientGetDocumentViaSnapshotListener","__PRIVATE_readDocumentViaSnapshotListener","__PRIVATE_wrappedObserver","__PRIVATE_firestoreClientGetDocumentsFromLocalCache","__PRIVATE_executeQueryFromCache","__PRIVATE_firestoreClientGetDocumentsViaSnapshotListener","__PRIVATE_executeQueryViaSnapshotListener","__PRIVATE_firestoreClientRunAggregateQuery","__PRIVATE_invokeRunAggregationQueryRpc","gt","__PRIVATE_filteredResult","__PRIVATE_unmappedAggregateFields","aggregateFields","__PRIVATE_accumulator","__PRIVATE_firestoreClientAddSnapshotsInSyncListener","__PRIVATE_addSnapshotsInSyncListener","__PRIVATE_removeSnapshotsInSyncListener","__PRIVATE_firestoreClientLoadBundle","__PRIVATE_resultTask","__PRIVATE_createBundleReader","content","__PRIVATE_newBundleReader","__PRIVATE_toByteStreamReader","ReadableStream","getReader","__PRIVATE_firestoreClientGetNamedQuery","__PRIVATE_localStoreGetNamedQuery","__PRIVATE_createBundleReaderSync","__PRIVATE_newBundleReaderSync","__PRIVATE_firestoreClientSetIndexConfiguration","__PRIVATE_localStoreConfigureFieldIndexes","__PRIVATE_newFieldIndexes","__PRIVATE_oldFieldIndexes","__PRIVATE_diffArrays","__PRIVATE_bLen","__PRIVATE_aLen","a","__PRIVATE_firestoreClientSetPersistentCacheIndexAutoCreationEnabled","isEnabled","__PRIVATE_localStoreSetIndexAutoCreationEnabled","__PRIVATE_firestoreClientDeleteAllFieldIndexes","__PRIVATE_localStoreDeleteAllFieldIndexes","__PRIVATE_cloneLongPollingOptions","__PRIVATE_datastoreInstances","__PRIVATE_DEFAULT_HOST","__PRIVATE_DEFAULT_SSL","FirestoreSettingsImpl","emulatorOptions","credentials","ignoreUndefinedProperties","localCache","experimentalForceLongPolling","experimentalAutoDetectLongPolling","experimentalLongPollingOptions","__PRIVATE_validateLongPollingOptions","__PRIVATE_longPollingOptionsEqual","__PRIVATE_options1","__PRIVATE_options2","Firestore","_authCredentials","_appCheckCredentials","_databaseId","_app","_persistenceKey","_settings","_settingsFrozen","_emulatorOptions","_terminateTask","_initialized","_terminated","_setSettings","__PRIVATE_makeAuthCredentialsProvider","_getSettings","_getEmulatorOptions","_freezeSettings","_delete","_terminate","_restart","__PRIVATE_removeComponents","firestore","connectFirestoreEmulator","port","__PRIVATE_useSsl","__PRIVATE_existingConfig","__PRIVATE_newHostSetting","pingServer","updateEmulatorBanner","__PRIVATE_newConfig","deepEqual","mockUserToken","createMockUserToken","sub","user_id","Query","converter","_query","withConverter","DocumentReference","_key","_path","CollectionReference","referencePath","getModularInstance","__PRIVATE_absolutePath","__PRIVATE_newQueryForCollectionGroup","arguments","refEqual","queryEqual","__PRIVATE_AsyncQueueImpl","__PRIVATE_tail","__PRIVATE_retryableOps","__PRIVATE__isShuttingDown","__PRIVATE_delayedOperations","__PRIVATE_operationInProgress","__PRIVATE_skipNonRestrictedTasks","__PRIVATE_timerIdsToSkip","__PRIVATE_visibilityHandler","isShuttingDown","__PRIVATE_verifyNotFailed","__PRIVATE_enqueueInternal","purgeExistingTasks","__PRIVATE_retryNextOp","__PRIVATE_newTail","__PRIVATE_getMessageOrStack","__PRIVATE_removedOp","__PRIVATE_removeDelayedOperation","__PRIVATE_messageOrStack","__PRIVATE_drain","__PRIVATE_currentTail","__PRIVATE_containsDelayedOperation","__PRIVATE_runAllDelayedOperationsUntil","__PRIVATE_lastTimerId","__PRIVATE_skipDelaysForTimerId","stack","includes","__PRIVATE_isPartialObserver","__PRIVATE_implementsAnyMethods","__PRIVATE_methods","object","method","LoadBundleTask","_progressObserver","_taskCompletionResolver","_lastProgress","onProgress","complete","onRejected","onFulfilled","CACHE_SIZE_UNLIMITED","__PRIVATE_LiteFirestore","_queue","_firestoreClient","initializeFirestore","_getProvider","isInitialized","__PRIVATE_existingInstance","identifier","__PRIVATE_initialSettings","getOptions","instanceIdentifier","getFirestore","__PRIVATE_appOrDatabaseId","__PRIVATE_optionalDatabaseId","getApp","__PRIVATE_emulator","getDefaultEmulatorHostnameAndPort","ensureFirestoreConfigured","__PRIVATE_configureFirestore","__PRIVATE_makeDatabaseInfo","_componentsProvider","_offlineComponentProvider","_onlineComponentProvider","__PRIVATE_buildComponentProvider","__PRIVATE_componentsProvider","__PRIVATE_online","enableIndexedDbPersistence","persistenceSettings","__PRIVATE_setPersistenceProviders","onlineComponents","enableMultiTabIndexedDbPersistence","clearIndexedDbPersistence","__PRIVATE_indexedDbClearPersistence","waitForPendingWrites","__PRIVATE_firestoreClientWaitForPendingWrites","enableNetwork","disableNetwork","_removeServiceInstance","loadBundle","AggregateField","_internalFieldPath","AggregateQuerySnapshot","_userDataWriter","_data","convertObjectMap","_byteString","fieldNames","_internalPath","__PRIVATE_InternalFieldPath","FieldValue","_methodName","GeoPoint","isFinite","_lat","_long","VectorValue","_values","__PRIVATE_isPrimitiveArrayEqual","vectorValues","__PRIVATE_RESERVED_FIELD_REGEX","ParsedSetData","ParsedUpdateData","__PRIVATE_isWrite","__PRIVATE_dataSource","__PRIVATE_ParseContextImpl","__PRIVATE_validatePath","__PRIVATE_contextWith","__PRIVATE_childContextForField","__PRIVATE_childPath","__PRIVATE_validatePathSegment","__PRIVATE_childContextForFieldPath","__PRIVATE_childContextForArray","__PRIVATE_createError","methodName","__PRIVATE_hasConverter","__PRIVATE_targetDoc","__PRIVATE_UserDataReader","__PRIVATE_createContext","__PRIVATE_newUserDataReader","__PRIVATE_parseSetData","__PRIVATE_userDataReader","merge","mergeFields","__PRIVATE_validatePlainObject","__PRIVATE_updateData","__PRIVATE_parseObject","__PRIVATE_validatedFieldPaths","__PRIVATE_stringOrFieldPath","__PRIVATE_fieldPathFromArgument","__PRIVATE_fieldMaskContains","__PRIVATE_DeleteFieldValueImpl","_toFieldTransform","__PRIVATE_createSentinelChildContext","__PRIVATE_ServerTimestampFieldValueImpl","__PRIVATE_ArrayUnionFieldValueImpl","__PRIVATE__elements","__PRIVATE_parseContext","__PRIVATE_parsedElements","__PRIVATE_parseData","arrayUnion","__PRIVATE_ArrayRemoveFieldValueImpl","__PRIVATE_NumericIncrementFieldValueImpl","__PRIVATE__operand","__PRIVATE_numericIncrement","__PRIVATE_parseUpdateData","__PRIVATE_fieldMaskPaths","__PRIVATE_fieldPathFromDotSeparatedString","__PRIVATE_childContext","__PRIVATE_parsedValue","__PRIVATE_parseUpdateVarargs","moreFieldsAndValues","__PRIVATE_parseQueryValue","__PRIVATE_allowArrays","__PRIVATE_looksLikeJsonObject","__PRIVATE_parseSentinelFieldValue","__PRIVATE_parseArray","__PRIVATE_entryIndex","__PRIVATE_parsedEntry","__PRIVATE_parseScalarValue","__PRIVATE_thisDb","__PRIVATE_otherDb","__PRIVATE_parseVectorValue","__PRIVATE_FIELD_PATH_RESERVED","search","__PRIVATE_hasPath","__PRIVATE_hasDocument","DocumentSnapshot","_firestore","_document","_converter","QueryDocumentSnapshot","fromFirestore","convertValue","arg","__PRIVATE_validateHasExplicitOrderByForLimitToLast","AppliableConstraint","QueryConstraint","__PRIVATE_queryConstraint","__PRIVATE_additionalQueryConstraints","queryConstraints","__PRIVATE_validateQueryConstraintArray","__PRIVATE_compositeFilterCount","QueryCompositeFilterConstraint","__PRIVATE_fieldFilterCount","QueryFieldFilterConstraint","constraint","_apply","_field","_op","_value","_create","_parse","__PRIVATE_validateNewFieldFilter","__PRIVATE_newQueryFilter","__PRIVATE_dataReader","__PRIVATE_validateDisjunctiveFilterElements","__PRIVATE_referenceList","__PRIVATE_parseDocumentIdValue","opStr","_queryConstraints","__PRIVATE_parsedFilters","__PRIVATE_parsedFilter","_getOperator","__PRIVATE_validateNewFilter","__PRIVATE_testQuery","__PRIVATE_subFilters","_getQueryConstraints","__PRIVATE_validateQueryFilterConstraint","and","QueryOrderByConstraint","_direction","__PRIVATE_newQueryOrderBy","__PRIVATE_queryWithAddedOrderBy","__PRIVATE_newOrderBy","directionStr","QueryLimitConstraint","_limit","_limitType","limitToLast","QueryStartAtConstraint","_docOrFields","_inclusive","__PRIVATE_newQueryBoundFromDocOrFields","__PRIVATE_queryWithStartAt","__PRIVATE_docOrFields","startAfter","QueryEndAtConstraint","__PRIVATE_queryWithEndAt","endBefore","__PRIVATE_newQueryBoundFromDocument","components","__PRIVATE_newQueryBoundFromFields","__PRIVATE_rawValue","__PRIVATE_wrapped","__PRIVATE_documentIdValue","__PRIVATE_conflictingOp","__PRIVATE_findOpInsideFilters","__PRIVATE_operators","__PRIVATE_conflictingOps","AbstractUserDataWriter","serverTimestampBehavior","convertTimestamp","convertServerTimestamp","convertBytes","convertReference","convertGeoPoint","convertArray","convertObject","convertVectorValue","__PRIVATE_normalizedValue","convertDocumentKey","expectedDatabaseId","__PRIVATE_applyFirestoreDataConverter","__PRIVATE_convertedValue","toFirestore","__PRIVATE_LiteUserDataWriter","average","aggregateFieldEqual","aggregateQuerySnapshotEqual","__PRIVATE_NOT_SUPPORTED","SnapshotMetadata","__PRIVATE_LiteDocumentSnapshot","userDataWriter","_firestoreImpl","serverTimestamps","documentSnapshotFromJSON","__PRIVATE_bundleLoader","__PRIVATE_bundledDocuments","bundleSource","QuerySnapshot","_snapshot","thisArg","_cachedChanges","_cachedChangesIncludeMetadataChanges","__PRIVATE_changesFromSnapshot","__PRIVATE_querySnapshot","oldIndex","newIndex","__PRIVATE_indexTracker","__PRIVATE_resultChangeType","__PRIVATE_documentData","querySnapshotFromJSON","__PRIVATE_bundledDocument","__PRIVATE_externalQuery","snapshotEqual","getDoc","reference","__PRIVATE_convertToDocSnapshot","__PRIVATE_ExpUserDataWriter","getDocFromCache","getDocFromServer","getDocs","getDocsFromCache","getDocsFromServer","setDoc","executeWrite","updateDoc","__PRIVATE_fieldOrUpdateData","deleteDoc","addDoc","__PRIVATE_docRef","onSnapshot","__PRIVATE_currArg","__PRIVATE_internalOptions","__PRIVATE_userObserver","__PRIVATE_internalQuery","__PRIVATE_firestoreClientListen","onSnapshotResume","snapshotJson","__PRIVATE_normalizeSnapshotJsonFields","__PRIVATE_requiredKeys","__PRIVATE_curArg","__PRIVATE_onSnapshotQuerySnapshotBundle","__PRIVATE_internalUnsubscribe","__PRIVATE_unsubscribed","__PRIVATE_loadTask","__PRIVATE_onSnapshotDocumentSnapshotBundle","__PRIVATE_docReference","onSnapshotsInSync","__PRIVATE_firestoreClientWrite","getCountFromServer","getAggregateFromServer","aggregateSpec","__PRIVATE_internalAggregates","__PRIVATE_aggregateResult","__PRIVATE_convertToAggregateQuerySnapshot","__PRIVATE_MemoryLocalCacheImpl","__PRIVATE_PersistentLocalCacheImpl","tabManager","_initialize","persistentSingleTabManager","__PRIVATE_MemoryEagerGarbageCollectorImpl","__PRIVATE_MemoryLruGarbageCollectorImpl","memoryEagerGarbageCollector","memoryLruGarbageCollector","memoryLocalCache","persistentLocalCache","__PRIVATE_SingleTabManagerImpl","__PRIVATE_MultiTabManagerImpl","persistentMultipleTabManager","__PRIVATE_DEFAULT_TRANSACTION_OPTIONS","WriteBatch","_commitHandler","_mutations","_committed","_dataReader","documentRef","_verifyNotCommitted","__PRIVATE_validateReference","_transaction","__PRIVATE_LiteTransaction","__PRIVATE_liteDocumentSnapshot","__PRIVATE_optionsWithDefaults","__PRIVATE_validateTransactionOptions","__PRIVATE_firestoreClientTransaction","__PRIVATE_internalTransaction","deleteField","arrayRemove","vector","writeBatch","setIndexConfiguration","__PRIVATE_jsonOrConfiguration","__PRIVATE_parsedIndexes","__PRIVATE_parseIndexes","__PRIVATE_indexConfiguration","__PRIVATE_tryParseJson","__PRIVATE_tryGetString","arrayConfig","PersistentCacheIndexManager","getPersistentCacheIndexManager","__PRIVATE_cachedInstance","__PRIVATE_persistentCacheIndexManagerByFirestore","enablePersistentCacheIndexAutoCreation","__PRIVATE_setPersistentCacheIndexAutoCreationEnabled","disablePersistentCacheIndexAutoCreation","deleteAllPersistentCacheIndexes","WeakMap","_internalQueryToProtoQueryTarget","_internalAggregationQueryToProtoRunAggregationQueryRequest","TestingHooks","onExistenceFilterMismatch","__PRIVATE_TestingHooksSpiImpl","__PRIVATE_testingHooksSpiImplInstance","__PRIVATE_setTestingHooksSpi","__PRIVATE_existenceFilterMismatchCallbacksById","__PRIVATE_registerFirestore","variant","__PRIVATE_setSDKVersion","_registerComponent","Component","container","getProvider","__PRIVATE_firestoreInstance","__PRIVATE_databaseIdFromApp","setMultipleInstances","registerVersion"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqBaA,MAAAA,IAAAA,CAAAA;AAUX,IAAA,WAAAC,CAAqBC,CAAAA,EAAAA;AAAAC,QAAAA,IAAAA,CAAGD,GAAHA,GAAAA,CAAAA,CAAAA;AAAsB,KAAA;IAE3C,eAAAE,GAAAA;AACE,QAAA,OAAmB,QAAZD,IAAKD,CAAAA,GAAAA,CAAAA;AACb,KAAA;;;;WAMD,KAAAG,GAAAA;AACE,QAAA,OAAIF,IAAKC,CAAAA,eAAAA,EAAAA,GACA,MAASD,GA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Ita,cACRjB,CAAAA,CAAAA,CAAKI,gBACL,EAAA,qDAAA,CAAA,CAAA;AAIJ,YAAA,OAAO,IAAI2tB,UAAAA,CAAW9oB,CAAIsW,CAAAA,OAAAA,CAAQyS,SAAYC,EAAAA,CAAAA,CAAAA,CAAAA;AAChD,SsI7CU8yF,CAAkB97G,GAAKmoB,CACvBnoB,CAAAA,EAAAA,CAAAA,CAAAA,CAAAA;AAIF,QAAA,OAFAM,CAAW,GAAA;AAAEqoB,YAAAA,eAAAA,EAAAA,CAAAA;AAAoBroB,YAAAA,GAAAA,CAAAA;AACjCu7G,SAAAA,EAAAA,CAAAA,CAAkB/a,aAAaxgG,CACxBu7G,CAAAA,EAAAA,CAAAA,CAAAA;AAAiB,KAAA,GAE1B,QACAE,CAAAA,CAAAA,oBAAAA,CAAAA,CAAqB,CAEzBC,CAAAA,CAAAA,EAAAA,eAAAA,CAAgB5/G,GAAMuX,CAAS4nG,EAAAA,CAAAA,CAAAA;;AAE/BS,IAAAA,eAAAA,CAAgB5/G,GAAMuX,CAAS,EAAA,SAAA,CAAA,CAAA;AACjC,CCvCA2nG,EAAAA;;;;"} \ No newline at end of file diff --git a/frontend-old/node_modules/@firebase/firestore/dist/index.node.cjs.js b/frontend-old/node_modules/@firebase/firestore/dist/index.node.cjs.js new file mode 100644 index 0000000..1b60cab --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/index.node.cjs.js @@ -0,0 +1,33938 @@ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var app = require('@firebase/app'); +var component = require('@firebase/component'); +var logger = require('@firebase/logger'); +var util$1 = require('util'); +var util = require('@firebase/util'); +var bloomBlob = require('@firebase/webchannel-wrapper/bloom-blob'); +var crypto = require('crypto'); +var grpc = require('@grpc/grpc-js'); +var protoLoader = require('@grpc/proto-loader'); + +function _interopNamespace(e) { + if (e && e.__esModule) return e; + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n["default"] = e; + return Object.freeze(n); +} + +var grpc__namespace = /*#__PURE__*/_interopNamespace(grpc); +var protoLoader__namespace = /*#__PURE__*/_interopNamespace(protoLoader); + +const name$1 = "@firebase/firestore"; +const version$1 = "4.9.2"; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Simple wrapper around a nullable UID. Mostly exists to make code more + * readable. + */ +class User { + constructor(uid) { + this.uid = uid; + } + isAuthenticated() { + return this.uid != null; + } + /** + * Returns a key representing this user, suitable for inclusion in a + * dictionary. + */ + toKey() { + if (this.isAuthenticated()) { + return 'uid:' + this.uid; + } + else { + return 'anonymous-user'; + } + } + isEqual(otherUser) { + return otherUser.uid === this.uid; + } +} +/** A user with a null UID. */ +User.UNAUTHENTICATED = new User(null); +// TODO(mikelehen): Look into getting a proper uid-equivalent for +// non-FirebaseAuth providers. +User.GOOGLE_CREDENTIALS = new User('google-credentials-uid'); +User.FIRST_PARTY = new User('first-party-uid'); +User.MOCK_USER = new User('mock-user'); + +const version = "12.3.0"; + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +let SDK_VERSION = version; +function setSDKVersion(version) { + SDK_VERSION = version; +} + +/** + * @license + * Copyright 2020 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** Formats an object as a JSON string, suitable for logging. */ +function formatJSON(value) { + // util.inspect() results in much more readable output than JSON.stringify() + return util$1.inspect(value, { depth: 100 }); +} + +/** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const logClient = new logger.Logger('@firebase/firestore'); +// Helper methods are needed because variables can't be exported as read/write +function getLogLevel() { + return logClient.logLevel; +} +/** + * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). + * + * @param logLevel - The verbosity you set for activity and error logging. Can + * be any of the following values: + * + *

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 0xd6db,\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\n/**\n * The smallest value representable by a 64-bit signed integer (long).\n */\nconst MIN_LONG_VALUE = '-9223372036854775808';\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 // Document keys are ordered first by numeric value (\"__id__\"),\n // then lexicographically by string value. Start the iterator at the minimum\n // possible Document key value.\n const prefix = new DocumentKey(\n collectionPath.child('__id' + MIN_LONG_VALUE + '__')\n );\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(0x251c, '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(\n 0xee44,\n 'orphanedDocuments is only valid during a transaction.'\n );\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isSafariOrWebkit } from '@firebase/util';\n\nimport { User } from '../auth/user';\nimport { ListenSequence } from '../core/listen_sequence';\nimport { SnapshotVersion } from '../core/snapshot_version';\nimport { DocumentKeySet, documentKeySet } from '../model/collections';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport { debugAssert, fail, hardAssert } from '../util/assert';\nimport { BATCHID_UNKNOWN } from '../util/types';\n\nimport {\n decodeResourcePath,\n encodeResourcePath\n} from './encoded_resource_path';\nimport { IndexedDbDocumentOverlayCache } from './indexeddb_document_overlay_cache';\nimport {\n dbDocumentSize,\n removeMutationBatch\n} from './indexeddb_mutation_batch_impl';\nimport { IndexedDbMutationQueue } from './indexeddb_mutation_queue';\nimport { newIndexedDbRemoteDocumentCache } from './indexeddb_remote_document_cache';\nimport {\n DbCollectionParent,\n DbDocumentMutation,\n DbMutationBatch,\n DbMutationQueue,\n DbRemoteDocument,\n DbRemoteDocumentGlobal,\n DbTarget,\n DbTargetDocument,\n DbTargetGlobal,\n SCHEMA_VERSION\n} from './indexeddb_schema';\nimport {\n DbRemoteDocument as DbRemoteDocumentLegacy,\n DbRemoteDocumentStore as DbRemoteDocumentStoreLegacy,\n DbRemoteDocumentKey as DbRemoteDocumentKeyLegacy\n} from './indexeddb_schema_legacy';\nimport {\n DbBundleKeyPath,\n DbBundleStore,\n DbClientMetadataKeyPath,\n DbClientMetadataStore,\n DbCollectionParentKey,\n DbCollectionParentKeyPath,\n DbCollectionParentStore,\n DbDocumentMutationKey,\n DbDocumentMutationStore,\n DbDocumentOverlayCollectionGroupOverlayIndex,\n DbDocumentOverlayCollectionGroupOverlayIndexPath,\n DbDocumentOverlayCollectionPathOverlayIndex,\n DbDocumentOverlayCollectionPathOverlayIndexPath,\n DbDocumentOverlayKeyPath,\n DbDocumentOverlayStore,\n DbGlobalsKeyPath,\n DbGlobalsStore,\n DbIndexConfigurationCollectionGroupIndex,\n DbIndexConfigurationCollectionGroupIndexPath,\n DbIndexConfigurationKeyPath,\n DbIndexConfigurationStore,\n DbIndexEntryDocumentKeyIndex,\n DbIndexEntryDocumentKeyIndexPath,\n DbIndexEntryKeyPath,\n DbIndexEntryStore,\n DbIndexStateKeyPath,\n DbIndexStateSequenceNumberIndex,\n DbIndexStateSequenceNumberIndexPath,\n DbIndexStateStore,\n DbMutationBatchKey,\n DbMutationBatchKeyPath,\n DbMutationBatchStore,\n DbMutationBatchUserMutationsIndex,\n DbMutationBatchUserMutationsKeyPath,\n DbMutationQueueKey,\n DbMutationQueueKeyPath,\n DbMutationQueueStore,\n DbNamedQueryKeyPath,\n DbNamedQueryStore,\n DbPrimaryClientStore,\n DbRemoteDocumentCollectionGroupIndex,\n DbRemoteDocumentCollectionGroupIndexPath,\n DbRemoteDocumentDocumentKeyIndex,\n DbRemoteDocumentDocumentKeyIndexPath,\n DbRemoteDocumentGlobalKey,\n DbRemoteDocumentGlobalStore,\n DbRemoteDocumentKey,\n DbRemoteDocumentKeyPath,\n DbRemoteDocumentStore,\n DbTargetDocumentDocumentTargetsIndex,\n DbTargetDocumentDocumentTargetsKeyPath,\n DbTargetDocumentKey,\n DbTargetDocumentKeyPath,\n DbTargetDocumentStore,\n DbTargetGlobalKey,\n DbTargetGlobalStore,\n DbTargetKey,\n DbTargetKeyPath,\n DbTargetQueryTargetsIndexName,\n DbTargetQueryTargetsKeyPath,\n DbTargetStore\n} from './indexeddb_sentinels';\nimport { IndexedDbTransaction } from './indexeddb_transaction';\nimport { LocalDocumentsView } from './local_documents_view';\nimport {\n fromDbMutationBatch,\n fromDbTarget,\n LocalSerializer,\n toDbTarget\n} from './local_serializer';\nimport { MemoryCollectionParentIndex } from './memory_index_manager';\nimport { MemoryEagerDelegate, MemoryPersistence } from './memory_persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport { SimpleDbSchemaConverter, SimpleDbTransaction } from './simple_db';\n\n/** Performs database creation and schema upgrades. */\nexport class SchemaConverter implements SimpleDbSchemaConverter {\n constructor(private readonly serializer: LocalSerializer) {}\n\n /**\n * Performs database creation and schema upgrades.\n *\n * Note that in production, this method is only ever used to upgrade the schema\n * to SCHEMA_VERSION. Different values of toVersion are only used for testing\n * and local feature development.\n */\n createOrUpgrade(\n db: IDBDatabase,\n txn: IDBTransaction,\n fromVersion: number,\n toVersion: number\n ): PersistencePromise {\n debugAssert(\n fromVersion < toVersion &&\n fromVersion >= 0 &&\n toVersion <= SCHEMA_VERSION,\n `Unexpected schema upgrade from v${fromVersion} to v${toVersion}.`\n );\n\n const simpleDbTransaction = new SimpleDbTransaction('createOrUpgrade', txn);\n\n if (fromVersion < 1 && toVersion >= 1) {\n createPrimaryClientStore(db);\n createMutationQueue(db);\n createQueryCache(db);\n createLegacyRemoteDocumentCache(db);\n }\n\n // Migration 2 to populate the targetGlobal object no longer needed since\n // migration 3 unconditionally clears it.\n\n let p = PersistencePromise.resolve();\n if (fromVersion < 3 && toVersion >= 3) {\n // Brand new clients don't need to drop and recreate--only clients that\n // potentially have corrupt data.\n if (fromVersion !== 0) {\n dropQueryCache(db);\n createQueryCache(db);\n }\n p = p.next(() => writeEmptyTargetGlobalEntry(simpleDbTransaction));\n }\n\n if (fromVersion < 4 && toVersion >= 4) {\n if (fromVersion !== 0) {\n // Schema version 3 uses auto-generated keys to generate globally unique\n // mutation batch IDs (this was previously ensured internally by the\n // client). To migrate to the new schema, we have to read all mutations\n // and write them back out. We preserve the existing batch IDs to guarantee\n // consistency with other object stores. Any further mutation batch IDs will\n // be auto-generated.\n p = p.next(() =>\n upgradeMutationBatchSchemaAndMigrateData(db, simpleDbTransaction)\n );\n }\n\n p = p.next(() => {\n createClientMetadataStore(db);\n });\n }\n\n if (fromVersion < 5 && toVersion >= 5) {\n p = p.next(() => this.removeAcknowledgedMutations(simpleDbTransaction));\n }\n\n if (fromVersion < 6 && toVersion >= 6) {\n p = p.next(() => {\n createDocumentGlobalStore(db);\n return this.addDocumentGlobal(simpleDbTransaction);\n });\n }\n\n if (fromVersion < 7 && toVersion >= 7) {\n p = p.next(() => this.ensureSequenceNumbers(simpleDbTransaction));\n }\n\n if (fromVersion < 8 && toVersion >= 8) {\n p = p.next(() =>\n this.createCollectionParentIndex(db, simpleDbTransaction)\n );\n }\n\n if (fromVersion < 9 && toVersion >= 9) {\n p = p.next(() => {\n // Multi-Tab used to manage its own changelog, but this has been moved\n // to the DbRemoteDocument object store itself. Since the previous change\n // log only contained transient data, we can drop its object store.\n dropRemoteDocumentChangesStore(db);\n\n // Note: Schema version 9 used to create a read time index for the\n // RemoteDocumentCache. This is now done with schema version 13.\n });\n }\n\n if (fromVersion < 10 && toVersion >= 10) {\n p = p.next(() => this.rewriteCanonicalIds(simpleDbTransaction));\n }\n\n if (fromVersion < 11 && toVersion >= 11) {\n p = p.next(() => {\n createBundlesStore(db);\n createNamedQueriesStore(db);\n });\n }\n\n if (fromVersion < 12 && toVersion >= 12) {\n p = p.next(() => {\n createDocumentOverlayStore(db);\n });\n }\n\n if (fromVersion < 13 && toVersion >= 13) {\n p = p\n .next(() => createRemoteDocumentCache(db))\n .next(() => this.rewriteRemoteDocumentCache(db, simpleDbTransaction))\n .next(() => db.deleteObjectStore(DbRemoteDocumentStoreLegacy));\n }\n\n if (fromVersion < 14 && toVersion >= 14) {\n p = p.next(() => this.runOverlayMigration(db, simpleDbTransaction));\n }\n\n if (fromVersion < 15 && toVersion >= 15) {\n p = p.next(() => createFieldIndex(db));\n }\n\n if (fromVersion < 16 && toVersion >= 16) {\n // Clear the object stores to remove possibly corrupted index entries\n p = p\n .next(() => {\n const indexStateStore = txn.objectStore(DbIndexStateStore);\n indexStateStore.clear();\n })\n .next(() => {\n const indexEntryStore = txn.objectStore(DbIndexEntryStore);\n indexEntryStore.clear();\n });\n }\n\n if (fromVersion < 17 && toVersion >= 17) {\n p = p.next(() => {\n createGlobalsStore(db);\n });\n }\n\n if (fromVersion < 18 && toVersion >= 18) {\n // Clear the IndexEntryStores on WebKit and Safari to remove possibly\n // corrupted index entries\n if (isSafariOrWebkit()) {\n p = p\n .next(() => {\n const indexStateStore = txn.objectStore(DbIndexStateStore);\n indexStateStore.clear();\n })\n .next(() => {\n const indexEntryStore = txn.objectStore(DbIndexEntryStore);\n indexEntryStore.clear();\n });\n }\n }\n\n return p;\n }\n\n private addDocumentGlobal(\n txn: SimpleDbTransaction\n ): PersistencePromise {\n let byteSize = 0;\n return txn\n .store(\n DbRemoteDocumentStoreLegacy\n )\n .iterate((_, doc) => {\n byteSize += dbDocumentSize(doc);\n })\n .next(() => {\n const metadata: DbRemoteDocumentGlobal = { byteSize };\n return txn\n .store(\n DbRemoteDocumentGlobalStore\n )\n .put(DbRemoteDocumentGlobalKey, metadata);\n });\n }\n\n private removeAcknowledgedMutations(\n txn: SimpleDbTransaction\n ): PersistencePromise {\n const queuesStore = txn.store(\n DbMutationQueueStore\n );\n const mutationsStore = txn.store(\n DbMutationBatchStore\n );\n\n return queuesStore.loadAll().next(queues => {\n return PersistencePromise.forEach(queues, (queue: DbMutationQueue) => {\n const range = IDBKeyRange.bound(\n [queue.userId, BATCHID_UNKNOWN],\n [queue.userId, queue.lastAcknowledgedBatchId]\n );\n\n return mutationsStore\n .loadAll(DbMutationBatchUserMutationsIndex, range)\n .next(dbBatches => {\n return PersistencePromise.forEach(\n dbBatches,\n (dbBatch: DbMutationBatch) => {\n hardAssert(\n dbBatch.userId === queue.userId,\n 0x48da,\n `Cannot process batch from unexpected user`,\n { batchId: dbBatch.batchId }\n );\n const batch = fromDbMutationBatch(this.serializer, dbBatch);\n\n return removeMutationBatch(txn, queue.userId, batch).next(\n () => {}\n );\n }\n );\n });\n });\n });\n }\n\n /**\n * Ensures that every document in the remote document cache has a corresponding sentinel row\n * with a sequence number. Missing rows are given the most recently used sequence number.\n */\n private ensureSequenceNumbers(\n txn: SimpleDbTransaction\n ): PersistencePromise {\n const documentTargetStore = txn.store<\n DbTargetDocumentKey,\n DbTargetDocument\n >(DbTargetDocumentStore);\n const documentsStore = txn.store<\n DbRemoteDocumentKeyLegacy,\n DbRemoteDocumentKeyLegacy\n >(DbRemoteDocumentStoreLegacy);\n const globalTargetStore = txn.store(\n DbTargetGlobalStore\n );\n\n return globalTargetStore.get(DbTargetGlobalKey).next(metadata => {\n debugAssert(\n !!metadata,\n 'Metadata should have been written during the version 3 migration'\n );\n const writeSentinelKey = (\n path: ResourcePath\n ): PersistencePromise => {\n return documentTargetStore.put({\n targetId: 0,\n path: encodeResourcePath(path),\n sequenceNumber: metadata!.highestListenSequenceNumber!\n });\n };\n\n const promises: Array> = [];\n return documentsStore\n .iterate((key, doc) => {\n const path = new ResourcePath(key);\n const docSentinelKey = sentinelKey(path);\n promises.push(\n documentTargetStore.get(docSentinelKey).next(maybeSentinel => {\n if (!maybeSentinel) {\n return writeSentinelKey(path);\n } else {\n return PersistencePromise.resolve();\n }\n })\n );\n })\n .next(() => PersistencePromise.waitFor(promises));\n });\n }\n\n private createCollectionParentIndex(\n db: IDBDatabase,\n txn: SimpleDbTransaction\n ): PersistencePromise {\n // Create the index.\n db.createObjectStore(DbCollectionParentStore, {\n keyPath: DbCollectionParentKeyPath\n });\n\n const collectionParentsStore = txn.store<\n DbCollectionParentKey,\n DbCollectionParent\n >(DbCollectionParentStore);\n\n // Helper to add an index entry iff we haven't already written it.\n const cache = new MemoryCollectionParentIndex();\n const addEntry = (\n collectionPath: ResourcePath\n ): PersistencePromise | undefined => {\n if (cache.add(collectionPath)) {\n const collectionId = collectionPath.lastSegment();\n const parentPath = collectionPath.popLast();\n return collectionParentsStore.put({\n collectionId,\n parent: encodeResourcePath(parentPath)\n });\n }\n };\n\n // Index existing remote documents.\n return txn\n .store(\n DbRemoteDocumentStoreLegacy\n )\n .iterate({ keysOnly: true }, (pathSegments, _) => {\n const path = new ResourcePath(pathSegments);\n return addEntry(path.popLast());\n })\n .next(() => {\n // Index existing mutations.\n return txn\n .store(\n DbDocumentMutationStore\n )\n .iterate({ keysOnly: true }, ([userID, encodedPath, batchId], _) => {\n const path = decodeResourcePath(encodedPath);\n return addEntry(path.popLast());\n });\n });\n }\n\n private rewriteCanonicalIds(\n txn: SimpleDbTransaction\n ): PersistencePromise {\n const targetStore = txn.store(DbTargetStore);\n return targetStore.iterate((key, originalDbTarget) => {\n const originalTargetData = fromDbTarget(originalDbTarget);\n const updatedDbTarget = toDbTarget(this.serializer, originalTargetData);\n return targetStore.put(updatedDbTarget);\n });\n }\n\n private rewriteRemoteDocumentCache(\n db: IDBDatabase,\n transaction: SimpleDbTransaction\n ): PersistencePromise {\n const legacyRemoteDocumentStore = transaction.store<\n DbRemoteDocumentKeyLegacy,\n DbRemoteDocumentLegacy\n >(DbRemoteDocumentStoreLegacy);\n\n const writes: Array> = [];\n return legacyRemoteDocumentStore\n .iterate((_, legacyDocument) => {\n const remoteDocumentStore = transaction.store<\n DbRemoteDocumentKey,\n DbRemoteDocument\n >(DbRemoteDocumentStore);\n\n const path = extractKey(legacyDocument).path.toArray();\n const dbRemoteDocument = {\n prefixPath: path.slice(0, path.length - 2),\n collectionGroup: path[path.length - 2],\n documentId: path[path.length - 1],\n readTime: legacyDocument.readTime || [0, 0],\n unknownDocument: legacyDocument.unknownDocument,\n noDocument: legacyDocument.noDocument,\n document: legacyDocument.document,\n hasCommittedMutations: !!legacyDocument.hasCommittedMutations\n };\n writes.push(remoteDocumentStore.put(dbRemoteDocument));\n })\n .next(() => PersistencePromise.waitFor(writes));\n }\n\n private runOverlayMigration(\n db: IDBDatabase,\n transaction: SimpleDbTransaction\n ): PersistencePromise {\n const mutationsStore = transaction.store<\n DbMutationBatchKey,\n DbMutationBatch\n >(DbMutationBatchStore);\n\n const remoteDocumentCache = newIndexedDbRemoteDocumentCache(\n this.serializer\n );\n const memoryPersistence = new MemoryPersistence(\n MemoryEagerDelegate.factory,\n this.serializer.remoteSerializer\n );\n\n return mutationsStore.loadAll().next(dbBatches => {\n const userToDocumentSet = new Map();\n dbBatches.forEach(dbBatch => {\n let documentSet =\n userToDocumentSet.get(dbBatch.userId) ?? documentKeySet();\n const batch = fromDbMutationBatch(this.serializer, dbBatch);\n batch.keys().forEach(key => (documentSet = documentSet.add(key)));\n userToDocumentSet.set(dbBatch.userId, documentSet);\n });\n return PersistencePromise.forEach(\n userToDocumentSet,\n (allDocumentKeysForUser, userId) => {\n const user = new User(userId);\n const documentOverlayCache = IndexedDbDocumentOverlayCache.forUser(\n this.serializer,\n user\n );\n // NOTE: The index manager and the reference delegate are\n // irrelevant for the purpose of recalculating and saving\n // overlays. We can therefore simply use the memory\n // implementation.\n const indexManager = memoryPersistence.getIndexManager(user);\n const mutationQueue = IndexedDbMutationQueue.forUser(\n user,\n this.serializer,\n indexManager,\n memoryPersistence.referenceDelegate\n );\n const localDocumentsView = new LocalDocumentsView(\n remoteDocumentCache,\n mutationQueue,\n documentOverlayCache,\n indexManager\n );\n return localDocumentsView\n .recalculateAndSaveOverlaysForDocumentKeys(\n new IndexedDbTransaction(transaction, ListenSequence.INVALID),\n allDocumentKeysForUser\n )\n .next();\n }\n );\n });\n }\n}\n\nfunction sentinelKey(path: ResourcePath): DbTargetDocumentKey {\n return [0, encodeResourcePath(path)];\n}\n\nfunction createPrimaryClientStore(db: IDBDatabase): void {\n db.createObjectStore(DbPrimaryClientStore);\n}\n\nfunction createMutationQueue(db: IDBDatabase): void {\n db.createObjectStore(DbMutationQueueStore, {\n keyPath: DbMutationQueueKeyPath\n });\n\n const mutationBatchesStore = db.createObjectStore(DbMutationBatchStore, {\n keyPath: DbMutationBatchKeyPath,\n autoIncrement: true\n });\n mutationBatchesStore.createIndex(\n DbMutationBatchUserMutationsIndex,\n DbMutationBatchUserMutationsKeyPath,\n { unique: true }\n );\n\n db.createObjectStore(DbDocumentMutationStore);\n}\n\n/**\n * Upgrade function to migrate the 'mutations' store from V1 to V3. Loads\n * and rewrites all data.\n */\nfunction upgradeMutationBatchSchemaAndMigrateData(\n db: IDBDatabase,\n txn: SimpleDbTransaction\n): PersistencePromise {\n const v1MutationsStore = txn.store<[string, number], DbMutationBatch>(\n DbMutationBatchStore\n );\n return v1MutationsStore.loadAll().next(existingMutations => {\n db.deleteObjectStore(DbMutationBatchStore);\n\n const mutationsStore = db.createObjectStore(DbMutationBatchStore, {\n keyPath: DbMutationBatchKeyPath,\n autoIncrement: true\n });\n mutationsStore.createIndex(\n DbMutationBatchUserMutationsIndex,\n DbMutationBatchUserMutationsKeyPath,\n { unique: true }\n );\n\n const v3MutationsStore = txn.store(\n DbMutationBatchStore\n );\n const writeAll = existingMutations.map(mutation =>\n v3MutationsStore.put(mutation)\n );\n\n return PersistencePromise.waitFor(writeAll);\n });\n}\n\nfunction createLegacyRemoteDocumentCache(db: IDBDatabase): void {\n db.createObjectStore(DbRemoteDocumentStoreLegacy);\n}\n\nfunction createRemoteDocumentCache(db: IDBDatabase): void {\n const remoteDocumentStore = db.createObjectStore(DbRemoteDocumentStore, {\n keyPath: DbRemoteDocumentKeyPath\n });\n remoteDocumentStore.createIndex(\n DbRemoteDocumentDocumentKeyIndex,\n DbRemoteDocumentDocumentKeyIndexPath\n );\n remoteDocumentStore.createIndex(\n DbRemoteDocumentCollectionGroupIndex,\n DbRemoteDocumentCollectionGroupIndexPath\n );\n}\n\nfunction createDocumentGlobalStore(db: IDBDatabase): void {\n db.createObjectStore(DbRemoteDocumentGlobalStore);\n}\n\nfunction createQueryCache(db: IDBDatabase): void {\n const targetDocumentsStore = db.createObjectStore(DbTargetDocumentStore, {\n keyPath: DbTargetDocumentKeyPath\n });\n targetDocumentsStore.createIndex(\n DbTargetDocumentDocumentTargetsIndex,\n DbTargetDocumentDocumentTargetsKeyPath,\n { unique: true }\n );\n\n const targetStore = db.createObjectStore(DbTargetStore, {\n keyPath: DbTargetKeyPath\n });\n\n // NOTE: This is unique only because the TargetId is the suffix.\n targetStore.createIndex(\n DbTargetQueryTargetsIndexName,\n DbTargetQueryTargetsKeyPath,\n { unique: true }\n );\n db.createObjectStore(DbTargetGlobalStore);\n}\n\nfunction dropQueryCache(db: IDBDatabase): void {\n db.deleteObjectStore(DbTargetDocumentStore);\n db.deleteObjectStore(DbTargetStore);\n db.deleteObjectStore(DbTargetGlobalStore);\n}\n\nfunction dropRemoteDocumentChangesStore(db: IDBDatabase): void {\n if (db.objectStoreNames.contains('remoteDocumentChanges')) {\n db.deleteObjectStore('remoteDocumentChanges');\n }\n}\n\n/**\n * Creates the target global singleton row.\n *\n * @param txn - The version upgrade transaction for indexeddb\n */\nfunction writeEmptyTargetGlobalEntry(\n txn: SimpleDbTransaction\n): PersistencePromise {\n const globalStore = txn.store(\n DbTargetGlobalStore\n );\n const metadata: DbTargetGlobal = {\n highestTargetId: 0,\n highestListenSequenceNumber: 0,\n lastRemoteSnapshotVersion: SnapshotVersion.min().toTimestamp(),\n targetCount: 0\n };\n return globalStore.put(DbTargetGlobalKey, metadata);\n}\n\nfunction createClientMetadataStore(db: IDBDatabase): void {\n db.createObjectStore(DbClientMetadataStore, {\n keyPath: DbClientMetadataKeyPath\n });\n}\n\nfunction createBundlesStore(db: IDBDatabase): void {\n db.createObjectStore(DbBundleStore, {\n keyPath: DbBundleKeyPath\n });\n}\n\nfunction createNamedQueriesStore(db: IDBDatabase): void {\n db.createObjectStore(DbNamedQueryStore, {\n keyPath: DbNamedQueryKeyPath\n });\n}\n\nfunction createFieldIndex(db: IDBDatabase): void {\n const indexConfigurationStore = db.createObjectStore(\n DbIndexConfigurationStore,\n {\n keyPath: DbIndexConfigurationKeyPath,\n autoIncrement: true\n }\n );\n indexConfigurationStore.createIndex(\n DbIndexConfigurationCollectionGroupIndex,\n DbIndexConfigurationCollectionGroupIndexPath,\n { unique: false }\n );\n\n const indexStateStore = db.createObjectStore(DbIndexStateStore, {\n keyPath: DbIndexStateKeyPath\n });\n indexStateStore.createIndex(\n DbIndexStateSequenceNumberIndex,\n DbIndexStateSequenceNumberIndexPath,\n { unique: false }\n );\n\n const indexEntryStore = db.createObjectStore(DbIndexEntryStore, {\n keyPath: DbIndexEntryKeyPath\n });\n indexEntryStore.createIndex(\n DbIndexEntryDocumentKeyIndex,\n DbIndexEntryDocumentKeyIndexPath,\n { unique: false }\n );\n}\n\nfunction createDocumentOverlayStore(db: IDBDatabase): void {\n const documentOverlayStore = db.createObjectStore(DbDocumentOverlayStore, {\n keyPath: DbDocumentOverlayKeyPath\n });\n documentOverlayStore.createIndex(\n DbDocumentOverlayCollectionPathOverlayIndex,\n DbDocumentOverlayCollectionPathOverlayIndexPath,\n { unique: false }\n );\n documentOverlayStore.createIndex(\n DbDocumentOverlayCollectionGroupOverlayIndex,\n DbDocumentOverlayCollectionGroupOverlayIndexPath,\n { unique: false }\n );\n}\n\nfunction createGlobalsStore(db: IDBDatabase): void {\n db.createObjectStore(DbGlobalsStore, {\n keyPath: DbGlobalsKeyPath\n });\n}\n\nfunction extractKey(remoteDoc: DbRemoteDocumentLegacy): DocumentKey {\n if (remoteDoc.document) {\n return new DocumentKey(\n ResourcePath.fromString(remoteDoc.document.name!).popFirst(5)\n );\n } else if (remoteDoc.noDocument) {\n return DocumentKey.fromSegments(remoteDoc.noDocument.path);\n } else if (remoteDoc.unknownDocument) {\n return DocumentKey.fromSegments(remoteDoc.unknownDocument.path);\n } else {\n return fail(0x8faf, 'Unexpected DbRemoteDocument');\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { isSafari } from '@firebase/util';\n\nimport { User } from '../auth/user';\nimport { DatabaseId } from '../core/database_info';\nimport { ListenSequence, SequenceNumberSyncer } from '../core/listen_sequence';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { debugAssert } from '../util/assert';\nimport { AsyncQueue, DelayedOperation, TimerId } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logDebug, logError } from '../util/log';\nimport { DocumentLike, WindowLike } from '../util/types';\n\nimport { BundleCache } from './bundle_cache';\nimport { DocumentOverlayCache } from './document_overlay_cache';\nimport { GlobalsCache } from './globals_cache';\nimport { IndexManager } from './index_manager';\nimport { IndexedDbBundleCache } from './indexeddb_bundle_cache';\nimport { IndexedDbDocumentOverlayCache } from './indexeddb_document_overlay_cache';\nimport { IndexedDbGlobalsCache } from './indexeddb_globals_cache';\nimport { IndexedDbIndexManager } from './indexeddb_index_manager';\nimport { IndexedDbLruDelegateImpl } from './indexeddb_lru_delegate_impl';\nimport { IndexedDbMutationQueue } from './indexeddb_mutation_queue';\nimport {\n IndexedDbRemoteDocumentCache,\n newIndexedDbRemoteDocumentCache\n} from './indexeddb_remote_document_cache';\nimport {\n DbClientMetadata,\n DbPrimaryClient,\n SCHEMA_VERSION\n} from './indexeddb_schema';\nimport { SchemaConverter } from './indexeddb_schema_converter';\nimport {\n DbClientMetadataKey,\n DbClientMetadataStore,\n DbPrimaryClientKey,\n DbPrimaryClientStore,\n getObjectStores\n} from './indexeddb_sentinels';\nimport { IndexedDbTargetCache } from './indexeddb_target_cache';\nimport { getStore, IndexedDbTransaction } from './indexeddb_transaction';\nimport { LocalSerializer } from './local_serializer';\nimport { LruParams } from './lru_garbage_collector';\nimport { Persistence, PrimaryStateListener } from './persistence';\nimport { PersistencePromise } from './persistence_promise';\nimport {\n PersistenceTransaction,\n PersistenceTransactionMode,\n PRIMARY_LEASE_LOST_ERROR_MSG\n} from './persistence_transaction';\nimport { ClientId } from './shared_client_state';\nimport {\n isIndexedDbTransactionError,\n SimpleDb,\n SimpleDbStore\n} from './simple_db';\n\nconst LOG_TAG = 'IndexedDbPersistence';\n\n/**\n * Oldest acceptable age in milliseconds for client metadata before the client\n * is considered inactive and its associated data is garbage collected.\n */\nconst MAX_CLIENT_AGE_MS = 30 * 60 * 1000; // 30 minutes\n\n/**\n * Oldest acceptable metadata age for clients that may participate in the\n * primary lease election. Clients that have not updated their client metadata\n * within 5 seconds are not eligible to receive a primary lease.\n */\nconst MAX_PRIMARY_ELIGIBLE_AGE_MS = 5000;\n\n/**\n * The interval at which clients will update their metadata, including\n * refreshing their primary lease if held or potentially trying to acquire it if\n * not held.\n *\n * Primary clients may opportunistically refresh their metadata earlier\n * if they're already performing an IndexedDB operation.\n */\nconst CLIENT_METADATA_REFRESH_INTERVAL_MS = 4000;\n/** User-facing error when the primary lease is required but not available. */\nconst PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG =\n 'Failed to obtain exclusive access to the persistence layer. To allow ' +\n 'shared access, multi-tab synchronization has to be enabled in all tabs. ' +\n 'If you are using `experimentalForceOwningTab:true`, make sure that only ' +\n 'one tab has persistence enabled at any given time.';\nconst UNSUPPORTED_PLATFORM_ERROR_MSG =\n 'This platform is either missing IndexedDB or is known to have ' +\n 'an incomplete implementation. Offline persistence has been disabled.';\n\n// The format of the LocalStorage key that stores zombied client is:\n// firestore_zombie__\nconst ZOMBIED_CLIENTS_KEY_PREFIX = 'firestore_zombie';\n\n/**\n * The name of the main (and currently only) IndexedDB database. This name is\n * appended to the prefix provided to the IndexedDbPersistence constructor.\n */\nexport const MAIN_DATABASE = 'main';\n\n/**\n * An IndexedDB-backed instance of Persistence. Data is stored persistently\n * across sessions.\n *\n * On Web only, the Firestore SDKs support shared access to its persistence\n * layer. This allows multiple browser tabs to read and write to IndexedDb and\n * to synchronize state even without network connectivity. Shared access is\n * currently optional and not enabled unless all clients invoke\n * `enablePersistence()` with `{synchronizeTabs:true}`.\n *\n * In multi-tab mode, if multiple clients are active at the same time, the SDK\n * will designate one client as the \"primary client\". An effort is made to pick\n * a visible, network-connected and active client, and this client is\n * responsible for letting other clients know about its presence. The primary\n * client writes a unique client-generated identifier (the client ID) to\n * IndexedDb’s \"owner\" store every 4 seconds. If the primary client fails to\n * update this entry, another client can acquire the lease and take over as\n * primary.\n *\n * Some persistence operations in the SDK are designated as primary-client only\n * operations. This includes the acknowledgment of mutations and all updates of\n * remote documents. The effects of these operations are written to persistence\n * and then broadcast to other tabs via LocalStorage (see\n * `WebStorageSharedClientState`), which then refresh their state from\n * persistence.\n *\n * Similarly, the primary client listens to notifications sent by secondary\n * clients to discover persistence changes written by secondary clients, such as\n * the addition of new mutations and query targets.\n *\n * If multi-tab is not enabled and another tab already obtained the primary\n * lease, IndexedDbPersistence enters a failed state and all subsequent\n * operations will automatically fail.\n *\n * Additionally, there is an optimization so that when a tab is closed, the\n * primary lease is released immediately (this is especially important to make\n * sure that a refreshed tab is able to immediately re-acquire the primary\n * lease). Unfortunately, IndexedDB cannot be reliably used in window.unload\n * since it is an asynchronous API. So in addition to attempting to give up the\n * lease, the leaseholder writes its client ID to a \"zombiedClient\" entry in\n * LocalStorage which acts as an indicator that another tab should go ahead and\n * take the primary lease immediately regardless of the current lease timestamp.\n *\n * TODO(b/114226234): Remove `synchronizeTabs` section when multi-tab is no\n * longer optional.\n */\nexport class IndexedDbPersistence implements Persistence {\n private simpleDb: SimpleDb;\n\n private listenSequence: ListenSequence | null = null;\n\n private _started = false;\n private isPrimary = false;\n private networkEnabled = true;\n private dbName: string;\n\n /** Our window.unload handler, if registered. */\n private windowUnloadHandler: (() => void) | null = null;\n private inForeground = false;\n\n private serializer: LocalSerializer;\n\n /** Our 'visibilitychange' listener if registered. */\n private documentVisibilityHandler: ((e?: Event) => void) | null = null;\n\n /** The client metadata refresh task. */\n private clientMetadataRefresher: DelayedOperation | null = null;\n\n /** The last time we garbage collected the client metadata object store. */\n private lastGarbageCollectionTime = Number.NEGATIVE_INFINITY;\n\n /** A listener to notify on primary state changes. */\n private primaryStateListener: PrimaryStateListener = _ => Promise.resolve();\n\n private readonly globalsCache: IndexedDbGlobalsCache;\n private readonly targetCache: IndexedDbTargetCache;\n private readonly remoteDocumentCache: IndexedDbRemoteDocumentCache;\n private readonly bundleCache: IndexedDbBundleCache;\n private readonly webStorage: Storage | null;\n readonly referenceDelegate: IndexedDbLruDelegateImpl;\n\n constructor(\n /**\n * Whether to synchronize the in-memory state of multiple tabs and share\n * access to local persistence.\n */\n private readonly allowTabSynchronization: boolean,\n\n private readonly persistenceKey: string,\n private readonly clientId: ClientId,\n lruParams: LruParams,\n private readonly queue: AsyncQueue,\n private readonly window: WindowLike | null,\n private readonly document: DocumentLike | null,\n serializer: JsonProtoSerializer,\n private readonly sequenceNumberSyncer: SequenceNumberSyncer,\n\n /**\n * If set to true, forcefully obtains database access. Existing tabs will\n * no longer be able to access IndexedDB.\n */\n private readonly forceOwningTab: boolean,\n private readonly schemaVersion = SCHEMA_VERSION\n ) {\n if (!IndexedDbPersistence.isAvailable()) {\n throw new FirestoreError(\n Code.UNIMPLEMENTED,\n UNSUPPORTED_PLATFORM_ERROR_MSG\n );\n }\n\n this.referenceDelegate = new IndexedDbLruDelegateImpl(this, lruParams);\n this.dbName = persistenceKey + MAIN_DATABASE;\n this.serializer = new LocalSerializer(serializer);\n this.simpleDb = new SimpleDb(\n this.dbName,\n this.schemaVersion,\n new SchemaConverter(this.serializer)\n );\n this.globalsCache = new IndexedDbGlobalsCache();\n this.targetCache = new IndexedDbTargetCache(\n this.referenceDelegate,\n this.serializer\n );\n this.remoteDocumentCache = newIndexedDbRemoteDocumentCache(this.serializer);\n this.bundleCache = new IndexedDbBundleCache();\n if (this.window && this.window.localStorage) {\n this.webStorage = this.window.localStorage;\n } else {\n this.webStorage = null;\n if (forceOwningTab === false) {\n logError(\n LOG_TAG,\n 'LocalStorage is unavailable. As a result, persistence may not work ' +\n 'reliably. In particular enablePersistence() could fail immediately ' +\n 'after refreshing the page.'\n );\n }\n }\n }\n\n /**\n * Attempt to start IndexedDb persistence.\n *\n * @returns Whether persistence was enabled.\n */\n start(): Promise {\n debugAssert(!this.started, 'IndexedDbPersistence double-started!');\n debugAssert(this.window !== null, \"Expected 'window' to be defined\");\n\n // NOTE: This is expected to fail sometimes (in the case of another tab\n // already having the persistence lock), so it's the first thing we should\n // do.\n return this.updateClientMetadataAndTryBecomePrimary()\n .then(() => {\n if (!this.isPrimary && !this.allowTabSynchronization) {\n // Fail `start()` if `synchronizeTabs` is disabled and we cannot\n // obtain the primary lease.\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG\n );\n }\n this.attachVisibilityHandler();\n this.attachWindowUnloadHook();\n\n this.scheduleClientMetadataAndPrimaryLeaseRefreshes();\n\n return this.runTransaction(\n 'getHighestListenSequenceNumber',\n 'readonly',\n txn => this.targetCache.getHighestSequenceNumber(txn)\n );\n })\n .then(highestListenSequenceNumber => {\n this.listenSequence = new ListenSequence(\n highestListenSequenceNumber,\n this.sequenceNumberSyncer\n );\n })\n .then(() => {\n this._started = true;\n })\n .catch(reason => {\n this.simpleDb && this.simpleDb.close();\n return Promise.reject(reason);\n });\n }\n\n /**\n * Registers a listener that gets called when the primary state of the\n * instance changes. Upon registering, this listener is invoked immediately\n * with the current primary state.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n setPrimaryStateListener(\n primaryStateListener: PrimaryStateListener\n ): Promise {\n this.primaryStateListener = async primaryState => {\n if (this.started) {\n return primaryStateListener(primaryState);\n }\n };\n return primaryStateListener(this.isPrimary);\n }\n\n /**\n * Registers a listener that gets called when the database receives a\n * version change event indicating that it has deleted.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n setDatabaseDeletedListener(\n databaseDeletedListener: () => Promise\n ): void {\n this.simpleDb.setVersionChangeListener(async event => {\n // Check if an attempt is made to delete IndexedDB.\n if (event.newVersion === null) {\n await databaseDeletedListener();\n }\n });\n }\n\n /**\n * Adjusts the current network state in the client's metadata, potentially\n * affecting the primary lease.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n setNetworkEnabled(networkEnabled: boolean): void {\n if (this.networkEnabled !== networkEnabled) {\n this.networkEnabled = networkEnabled;\n // Schedule a primary lease refresh for immediate execution. The eventual\n // lease update will be propagated via `primaryStateListener`.\n this.queue.enqueueAndForget(async () => {\n if (this.started) {\n await this.updateClientMetadataAndTryBecomePrimary();\n }\n });\n }\n }\n\n /**\n * Updates the client metadata in IndexedDb and attempts to either obtain or\n * extend the primary lease for the local client. Asynchronously notifies the\n * primary state listener if the client either newly obtained or released its\n * primary lease.\n */\n private updateClientMetadataAndTryBecomePrimary(): Promise {\n return this.runTransaction(\n 'updateClientMetadataAndTryBecomePrimary',\n 'readwrite',\n txn => {\n const metadataStore = clientMetadataStore(txn);\n return metadataStore\n .put({\n clientId: this.clientId,\n updateTimeMs: Date.now(),\n networkEnabled: this.networkEnabled,\n inForeground: this.inForeground\n })\n .next(() => {\n if (this.isPrimary) {\n return this.verifyPrimaryLease(txn).next(success => {\n if (!success) {\n this.isPrimary = false;\n this.queue.enqueueRetryable(() =>\n this.primaryStateListener(false)\n );\n }\n });\n }\n })\n .next(() => this.canActAsPrimary(txn))\n .next(canActAsPrimary => {\n if (this.isPrimary && !canActAsPrimary) {\n return this.releasePrimaryLeaseIfHeld(txn).next(() => false);\n } else if (canActAsPrimary) {\n return this.acquireOrExtendPrimaryLease(txn).next(() => true);\n } else {\n return /* canActAsPrimary= */ false;\n }\n });\n }\n )\n .catch(e => {\n if (isIndexedDbTransactionError(e)) {\n logDebug(LOG_TAG, 'Failed to extend owner lease: ', e);\n // Proceed with the existing state. Any subsequent access to\n // IndexedDB will verify the lease.\n return this.isPrimary;\n }\n\n if (!this.allowTabSynchronization) {\n throw e;\n }\n\n logDebug(\n LOG_TAG,\n 'Releasing owner lease after error during lease refresh',\n e\n );\n return /* isPrimary= */ false;\n })\n .then(isPrimary => {\n if (this.isPrimary !== isPrimary) {\n this.queue.enqueueRetryable(() =>\n this.primaryStateListener(isPrimary)\n );\n }\n this.isPrimary = isPrimary;\n });\n }\n\n private verifyPrimaryLease(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const store = primaryClientStore(txn);\n return store.get(DbPrimaryClientKey).next(primaryClient => {\n return PersistencePromise.resolve(this.isLocalClient(primaryClient));\n });\n }\n\n private removeClientMetadata(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const metadataStore = clientMetadataStore(txn);\n return metadataStore.delete(this.clientId);\n }\n\n /**\n * If the garbage collection threshold has passed, prunes the\n * RemoteDocumentChanges and the ClientMetadata store based on the last update\n * time of all clients.\n */\n private async maybeGarbageCollectMultiClientState(): Promise {\n if (\n this.isPrimary &&\n !this.isWithinAge(this.lastGarbageCollectionTime, MAX_CLIENT_AGE_MS)\n ) {\n this.lastGarbageCollectionTime = Date.now();\n\n const inactiveClients = await this.runTransaction(\n 'maybeGarbageCollectMultiClientState',\n 'readwrite-primary',\n txn => {\n const metadataStore = getStore(\n txn,\n DbClientMetadataStore\n );\n\n return metadataStore.loadAll().next(existingClients => {\n const active = this.filterActiveClients(\n existingClients,\n MAX_CLIENT_AGE_MS\n );\n const inactive = existingClients.filter(\n client => active.indexOf(client) === -1\n );\n\n // Delete metadata for clients that are no longer considered active.\n return PersistencePromise.forEach(\n inactive,\n (inactiveClient: DbClientMetadata) =>\n metadataStore.delete(inactiveClient.clientId)\n ).next(() => inactive);\n });\n }\n ).catch(() => {\n // Ignore primary lease violations or any other type of error. The next\n // primary will run `maybeGarbageCollectMultiClientState()` again.\n // We don't use `ignoreIfPrimaryLeaseLoss()` since we don't want to depend\n // on LocalStore.\n return [];\n });\n\n // Delete potential leftover entries that may continue to mark the\n // inactive clients as zombied in LocalStorage.\n // Ideally we'd delete the IndexedDb and LocalStorage zombie entries for\n // the client atomically, but we can't. So we opt to delete the IndexedDb\n // entries first to avoid potentially reviving a zombied client.\n if (this.webStorage) {\n for (const inactiveClient of inactiveClients) {\n this.webStorage.removeItem(\n this.zombiedClientLocalStorageKey(inactiveClient.clientId)\n );\n }\n }\n }\n }\n\n /**\n * Schedules a recurring timer to update the client metadata and to either\n * extend or acquire the primary lease if the client is eligible.\n */\n private scheduleClientMetadataAndPrimaryLeaseRefreshes(): void {\n this.clientMetadataRefresher = this.queue.enqueueAfterDelay(\n TimerId.ClientMetadataRefresh,\n CLIENT_METADATA_REFRESH_INTERVAL_MS,\n () => {\n return this.updateClientMetadataAndTryBecomePrimary()\n .then(() => this.maybeGarbageCollectMultiClientState())\n .then(() => this.scheduleClientMetadataAndPrimaryLeaseRefreshes());\n }\n );\n }\n\n /** Checks whether `client` is the local client. */\n private isLocalClient(client: DbPrimaryClient | null): boolean {\n return client ? client.ownerId === this.clientId : false;\n }\n\n /**\n * Evaluate the state of all active clients and determine whether the local\n * client is or can act as the holder of the primary lease. Returns whether\n * the client is eligible for the lease, but does not actually acquire it.\n * May return 'false' even if there is no active leaseholder and another\n * (foreground) client should become leaseholder instead.\n */\n private canActAsPrimary(\n txn: PersistenceTransaction\n ): PersistencePromise {\n if (this.forceOwningTab) {\n return PersistencePromise.resolve(true);\n }\n const store = primaryClientStore(txn);\n return store\n .get(DbPrimaryClientKey)\n .next(currentPrimary => {\n const currentLeaseIsValid =\n currentPrimary !== null &&\n this.isWithinAge(\n currentPrimary.leaseTimestampMs,\n MAX_PRIMARY_ELIGIBLE_AGE_MS\n ) &&\n !this.isClientZombied(currentPrimary.ownerId);\n\n // A client is eligible for the primary lease if:\n // - its network is enabled and the client's tab is in the foreground.\n // - its network is enabled and no other client's tab is in the\n // foreground.\n // - every clients network is disabled and the client's tab is in the\n // foreground.\n // - every clients network is disabled and no other client's tab is in\n // the foreground.\n // - the `forceOwningTab` setting was passed in.\n if (currentLeaseIsValid) {\n if (this.isLocalClient(currentPrimary) && this.networkEnabled) {\n return true;\n }\n\n if (!this.isLocalClient(currentPrimary)) {\n if (!currentPrimary!.allowTabSynchronization) {\n // Fail the `canActAsPrimary` check if the current leaseholder has\n // not opted into multi-tab synchronization. If this happens at\n // client startup, we reject the Promise returned by\n // `enablePersistence()` and the user can continue to use Firestore\n // with in-memory persistence.\n // If this fails during a lease refresh, we will instead block the\n // AsyncQueue from executing further operations. Note that this is\n // acceptable since mixing & matching different `synchronizeTabs`\n // settings is not supported.\n //\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can\n // no longer be turned off.\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG\n );\n }\n\n return false;\n }\n }\n\n if (this.networkEnabled && this.inForeground) {\n return true;\n }\n\n return clientMetadataStore(txn)\n .loadAll()\n .next(existingClients => {\n // Process all existing clients and determine whether at least one of\n // them is better suited to obtain the primary lease.\n const preferredCandidate = this.filterActiveClients(\n existingClients,\n MAX_PRIMARY_ELIGIBLE_AGE_MS\n ).find(otherClient => {\n if (this.clientId !== otherClient.clientId) {\n const otherClientHasBetterNetworkState =\n !this.networkEnabled && otherClient.networkEnabled;\n const otherClientHasBetterVisibility =\n !this.inForeground && otherClient.inForeground;\n const otherClientHasSameNetworkState =\n this.networkEnabled === otherClient.networkEnabled;\n if (\n otherClientHasBetterNetworkState ||\n (otherClientHasBetterVisibility &&\n otherClientHasSameNetworkState)\n ) {\n return true;\n }\n }\n return false;\n });\n return preferredCandidate === undefined;\n });\n })\n .next(canActAsPrimary => {\n if (this.isPrimary !== canActAsPrimary) {\n logDebug(\n LOG_TAG,\n `Client ${\n canActAsPrimary ? 'is' : 'is not'\n } eligible for a primary lease.`\n );\n }\n return canActAsPrimary;\n });\n }\n\n async shutdown(): Promise {\n // The shutdown() operations are idempotent and can be called even when\n // start() aborted (e.g. because it couldn't acquire the persistence lease).\n this._started = false;\n\n this.markClientZombied();\n if (this.clientMetadataRefresher) {\n this.clientMetadataRefresher.cancel();\n this.clientMetadataRefresher = null;\n }\n this.detachVisibilityHandler();\n this.detachWindowUnloadHook();\n\n // Use `SimpleDb.runTransaction` directly to avoid failing if another tab\n // has obtained the primary lease.\n await this.simpleDb.runTransaction(\n 'shutdown',\n 'readwrite',\n [DbPrimaryClientStore, DbClientMetadataStore],\n simpleDbTxn => {\n const persistenceTransaction = new IndexedDbTransaction(\n simpleDbTxn,\n ListenSequence.INVALID\n );\n return this.releasePrimaryLeaseIfHeld(persistenceTransaction).next(() =>\n this.removeClientMetadata(persistenceTransaction)\n );\n }\n );\n this.simpleDb.close();\n\n // Remove the entry marking the client as zombied from LocalStorage since\n // we successfully deleted its metadata from IndexedDb.\n this.removeClientZombiedEntry();\n }\n\n /**\n * Returns clients that are not zombied and have an updateTime within the\n * provided threshold.\n */\n private filterActiveClients(\n clients: DbClientMetadata[],\n activityThresholdMs: number\n ): DbClientMetadata[] {\n return clients.filter(\n client =>\n this.isWithinAge(client.updateTimeMs, activityThresholdMs) &&\n !this.isClientZombied(client.clientId)\n );\n }\n\n /**\n * Returns the IDs of the clients that are currently active. If multi-tab\n * is not supported, returns an array that only contains the local client's\n * ID.\n *\n * PORTING NOTE: This is only used for Web multi-tab.\n */\n getActiveClients(): Promise {\n return this.runTransaction('getActiveClients', 'readonly', txn => {\n return clientMetadataStore(txn)\n .loadAll()\n .next(clients =>\n this.filterActiveClients(clients, MAX_CLIENT_AGE_MS).map(\n clientMetadata => clientMetadata.clientId\n )\n );\n });\n }\n\n get started(): boolean {\n return this._started;\n }\n\n getGlobalsCache(): GlobalsCache {\n debugAssert(\n this.started,\n 'Cannot initialize GlobalsCache before persistence is started.'\n );\n return this.globalsCache;\n }\n\n getMutationQueue(\n user: User,\n indexManager: IndexManager\n ): IndexedDbMutationQueue {\n debugAssert(\n this.started,\n 'Cannot initialize MutationQueue before persistence is started.'\n );\n return IndexedDbMutationQueue.forUser(\n user,\n this.serializer,\n indexManager,\n this.referenceDelegate\n );\n }\n\n getTargetCache(): IndexedDbTargetCache {\n debugAssert(\n this.started,\n 'Cannot initialize TargetCache before persistence is started.'\n );\n return this.targetCache;\n }\n\n getRemoteDocumentCache(): IndexedDbRemoteDocumentCache {\n debugAssert(\n this.started,\n 'Cannot initialize RemoteDocumentCache before persistence is started.'\n );\n return this.remoteDocumentCache;\n }\n\n getIndexManager(user: User): IndexManager {\n debugAssert(\n this.started,\n 'Cannot initialize IndexManager before persistence is started.'\n );\n return new IndexedDbIndexManager(\n user,\n this.serializer.remoteSerializer.databaseId\n );\n }\n\n getDocumentOverlayCache(user: User): DocumentOverlayCache {\n debugAssert(\n this.started,\n 'Cannot initialize IndexedDbDocumentOverlayCache before persistence is started.'\n );\n return IndexedDbDocumentOverlayCache.forUser(this.serializer, user);\n }\n\n getBundleCache(): BundleCache {\n debugAssert(\n this.started,\n 'Cannot initialize BundleCache before persistence is started.'\n );\n return this.bundleCache;\n }\n\n runTransaction(\n action: string,\n mode: PersistenceTransactionMode,\n transactionOperation: (\n transaction: PersistenceTransaction\n ) => PersistencePromise\n ): Promise {\n logDebug(LOG_TAG, 'Starting transaction:', action);\n\n const simpleDbMode = mode === 'readonly' ? 'readonly' : 'readwrite';\n const objectStores = getObjectStores(this.schemaVersion);\n\n let persistenceTransaction: PersistenceTransaction;\n\n // Do all transactions as readwrite against all object stores, since we\n // are the only reader/writer.\n return this.simpleDb\n .runTransaction(action, simpleDbMode, objectStores, simpleDbTxn => {\n persistenceTransaction = new IndexedDbTransaction(\n simpleDbTxn,\n this.listenSequence\n ? this.listenSequence.next()\n : ListenSequence.INVALID\n );\n\n if (mode === 'readwrite-primary') {\n // While we merely verify that we have (or can acquire) the lease\n // immediately, we wait to extend the primary lease until after\n // executing transactionOperation(). This ensures that even if the\n // transactionOperation takes a long time, we'll use a recent\n // leaseTimestampMs in the extended (or newly acquired) lease.\n return this.verifyPrimaryLease(persistenceTransaction)\n .next(holdsPrimaryLease => {\n if (holdsPrimaryLease) {\n return /* holdsPrimaryLease= */ true;\n }\n return this.canActAsPrimary(persistenceTransaction);\n })\n .next(holdsPrimaryLease => {\n if (!holdsPrimaryLease) {\n logError(\n `Failed to obtain primary lease for action '${action}'.`\n );\n this.isPrimary = false;\n this.queue.enqueueRetryable(() =>\n this.primaryStateListener(false)\n );\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_LOST_ERROR_MSG\n );\n }\n return transactionOperation(persistenceTransaction);\n })\n .next(result => {\n return this.acquireOrExtendPrimaryLease(\n persistenceTransaction\n ).next(() => result);\n });\n } else {\n return this.verifyAllowTabSynchronization(\n persistenceTransaction\n ).next(() => transactionOperation(persistenceTransaction));\n }\n })\n .then(result => {\n persistenceTransaction.raiseOnCommittedEvent();\n return result;\n });\n }\n\n /**\n * Verifies that the current tab is the primary leaseholder or alternatively\n * that the leaseholder has opted into multi-tab synchronization.\n */\n // TODO(b/114226234): Remove this check when `synchronizeTabs` can no longer\n // be turned off.\n private verifyAllowTabSynchronization(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const store = primaryClientStore(txn);\n return store.get(DbPrimaryClientKey).next(currentPrimary => {\n const currentLeaseIsValid =\n currentPrimary !== null &&\n this.isWithinAge(\n currentPrimary.leaseTimestampMs,\n MAX_PRIMARY_ELIGIBLE_AGE_MS\n ) &&\n !this.isClientZombied(currentPrimary.ownerId);\n\n if (currentLeaseIsValid && !this.isLocalClient(currentPrimary)) {\n if (\n !this.forceOwningTab &&\n (!this.allowTabSynchronization ||\n !currentPrimary!.allowTabSynchronization)\n ) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG\n );\n }\n }\n });\n }\n\n /**\n * Obtains or extends the new primary lease for the local client. This\n * method does not verify that the client is eligible for this lease.\n */\n private acquireOrExtendPrimaryLease(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const newPrimary: DbPrimaryClient = {\n ownerId: this.clientId,\n allowTabSynchronization: this.allowTabSynchronization,\n leaseTimestampMs: Date.now()\n };\n return primaryClientStore(txn).put(DbPrimaryClientKey, newPrimary);\n }\n\n static isAvailable(): boolean {\n return SimpleDb.isAvailable();\n }\n\n /** Checks the primary lease and removes it if we are the current primary. */\n private releasePrimaryLeaseIfHeld(\n txn: PersistenceTransaction\n ): PersistencePromise {\n const store = primaryClientStore(txn);\n return store.get(DbPrimaryClientKey).next(primaryClient => {\n if (this.isLocalClient(primaryClient)) {\n logDebug(LOG_TAG, 'Releasing primary lease.');\n return store.delete(DbPrimaryClientKey);\n } else {\n return PersistencePromise.resolve();\n }\n });\n }\n\n /** Verifies that `updateTimeMs` is within `maxAgeMs`. */\n private isWithinAge(updateTimeMs: number, maxAgeMs: number): boolean {\n const now = Date.now();\n const minAcceptable = now - maxAgeMs;\n const maxAcceptable = now;\n if (updateTimeMs < minAcceptable) {\n return false;\n } else if (updateTimeMs > maxAcceptable) {\n logError(\n `Detected an update time that is in the future: ${updateTimeMs} > ${maxAcceptable}`\n );\n return false;\n }\n\n return true;\n }\n\n private attachVisibilityHandler(): void {\n if (\n this.document !== null &&\n typeof this.document.addEventListener === 'function'\n ) {\n this.documentVisibilityHandler = () => {\n this.queue.enqueueAndForget(() => {\n this.inForeground = this.document!.visibilityState === 'visible';\n return this.updateClientMetadataAndTryBecomePrimary();\n });\n };\n\n this.document.addEventListener(\n 'visibilitychange',\n this.documentVisibilityHandler\n );\n\n this.inForeground = this.document.visibilityState === 'visible';\n }\n }\n\n private detachVisibilityHandler(): void {\n if (this.documentVisibilityHandler) {\n debugAssert(\n this.document !== null &&\n typeof this.document.addEventListener === 'function',\n \"Expected 'document.addEventListener' to be a function\"\n );\n this.document.removeEventListener(\n 'visibilitychange',\n this.documentVisibilityHandler\n );\n this.documentVisibilityHandler = null;\n }\n }\n\n /**\n * Attaches a window.unload handler that will synchronously write our\n * clientId to a \"zombie client id\" location in LocalStorage. This can be used\n * by tabs trying to acquire the primary lease to determine that the lease\n * is no longer valid even if the timestamp is recent. This is particularly\n * important for the refresh case (so the tab correctly re-acquires the\n * primary lease). LocalStorage is used for this rather than IndexedDb because\n * it is a synchronous API and so can be used reliably from an unload\n * handler.\n */\n private attachWindowUnloadHook(): void {\n if (typeof this.window?.addEventListener === 'function') {\n this.windowUnloadHandler = () => {\n // Note: In theory, this should be scheduled on the AsyncQueue since it\n // accesses internal state. We execute this code directly during shutdown\n // to make sure it gets a chance to run.\n this.markClientZombied();\n\n const safariIndexdbBugVersionRegex = /(?:Version|Mobile)\\/1[456]/;\n if (\n isSafari() &&\n (navigator.appVersion.match(safariIndexdbBugVersionRegex) ||\n navigator.userAgent.match(safariIndexdbBugVersionRegex))\n ) {\n // On Safari 14, 15, and 16, we do not run any cleanup actions as it might\n // trigger a bug that prevents Safari from re-opening IndexedDB during\n // the next page load.\n // See https://bugs.webkit.org/show_bug.cgi?id=226547\n this.queue.enterRestrictedMode(/* purgeExistingTasks= */ true);\n }\n\n this.queue.enqueueAndForget(() => {\n // Attempt graceful shutdown (including releasing our primary lease),\n // but there's no guarantee it will complete.\n return this.shutdown();\n });\n };\n this.window.addEventListener('pagehide', this.windowUnloadHandler);\n }\n }\n\n private detachWindowUnloadHook(): void {\n if (this.windowUnloadHandler) {\n debugAssert(\n typeof this.window?.removeEventListener === 'function',\n \"Expected 'window.removeEventListener' to be a function\"\n );\n this.window!.removeEventListener('pagehide', this.windowUnloadHandler);\n this.windowUnloadHandler = null;\n }\n }\n\n /**\n * Returns whether a client is \"zombied\" based on its LocalStorage entry.\n * Clients become zombied when their tab closes without running all of the\n * cleanup logic in `shutdown()`.\n */\n private isClientZombied(clientId: ClientId): boolean {\n try {\n const isZombied =\n this.webStorage?.getItem(\n this.zombiedClientLocalStorageKey(clientId)\n ) !== null;\n logDebug(\n LOG_TAG,\n `Client '${clientId}' ${\n isZombied ? 'is' : 'is not'\n } zombied in LocalStorage`\n );\n return isZombied;\n } catch (e) {\n // Gracefully handle if LocalStorage isn't working.\n logError(LOG_TAG, 'Failed to get zombied client id.', e);\n return false;\n }\n }\n\n /**\n * Record client as zombied (a client that had its tab closed). Zombied\n * clients are ignored during primary tab selection.\n */\n private markClientZombied(): void {\n if (!this.webStorage) {\n return;\n }\n try {\n this.webStorage.setItem(\n this.zombiedClientLocalStorageKey(this.clientId),\n String(Date.now())\n );\n } catch (e) {\n // Gracefully handle if LocalStorage isn't available / working.\n logError('Failed to set zombie client id.', e);\n }\n }\n\n /** Removes the zombied client entry if it exists. */\n private removeClientZombiedEntry(): void {\n if (!this.webStorage) {\n return;\n }\n try {\n this.webStorage.removeItem(\n this.zombiedClientLocalStorageKey(this.clientId)\n );\n } catch (e) {\n // Ignore\n }\n }\n\n private zombiedClientLocalStorageKey(clientId: ClientId): string {\n return `${ZOMBIED_CLIENTS_KEY_PREFIX}_${this.persistenceKey}_${clientId}`;\n }\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the primary client object store.\n */\nfunction primaryClientStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbPrimaryClientStore\n );\n}\n\n/**\n * Helper to get a typed SimpleDbStore for the client metadata object store.\n */\nfunction clientMetadataStore(\n txn: PersistenceTransaction\n): SimpleDbStore {\n return getStore(\n txn,\n DbClientMetadataStore\n );\n}\n\n/**\n * Generates a string used as a prefix when storing data in IndexedDB and\n * LocalStorage.\n */\nexport function indexedDbStoragePrefix(\n databaseId: DatabaseId,\n persistenceKey: string\n): string {\n // Use two different prefix formats:\n //\n // * firestore / persistenceKey / projectID . databaseID / ...\n // * firestore / persistenceKey / projectID / ...\n //\n // projectIDs are DNS-compatible names and cannot contain dots\n // so there's no danger of collisions.\n let database = databaseId.projectId;\n if (!databaseId.isDefaultDatabase) {\n database += '.' + databaseId.database;\n }\n\n return 'firestore/' + persistenceKey + '/' + database + '/';\n}\n\nexport async function indexedDbClearPersistence(\n persistenceKey: string\n): Promise {\n if (!SimpleDb.isAvailable()) {\n return Promise.resolve();\n }\n const dbName = persistenceKey + MAIN_DATABASE;\n await SimpleDb.delete(dbName);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BatchId, ListenSequenceNumber, TargetId } from '../core/types';\nimport { IndexKind } from '../model/field_index';\nimport { BundledQuery } from '../protos/firestore_bundle_proto';\nimport {\n Document as ProtoDocument,\n DocumentsTarget as ProtoDocumentsTarget,\n QueryTarget as ProtoQueryTarget,\n Write as ProtoWrite\n} from '../protos/firestore_proto_api';\n\nimport { EncodedResourcePath } from './encoded_resource_path';\nimport { DbTimestampKey, KeySafeBytes } from './indexeddb_sentinels';\n\n/**\n * Schema Version for the Web client:\n * 1. Initial version including Mutation Queue, Query Cache, and Remote\n * Document Cache\n * 2. Used to ensure a targetGlobal object exists and add targetCount to it. No\n * longer required because migration 3 unconditionally clears it.\n * 3. Dropped and re-created Query Cache to deal with cache corruption related\n * to limbo resolution. Addresses\n * https://github.com/firebase/firebase-ios-sdk/issues/1548\n * 4. Multi-Tab Support.\n * 5. Removal of held write acks.\n * 6. Create document global for tracking document cache size.\n * 7. Ensure every cached document has a sentinel row with a sequence number.\n * 8. Add collection-parent index for Collection Group queries.\n * 9. Change RemoteDocumentChanges store to be keyed by readTime rather than\n * an auto-incrementing ID. This is required for Index-Free queries.\n * 10. Rewrite the canonical IDs to the explicit Protobuf-based format.\n * 11. Add bundles and named_queries for bundle support.\n * 12. Add document overlays.\n * 13. Rewrite the keys of the remote document cache to allow for efficient\n * document lookup via `getAll()`.\n * 14. Add overlays.\n * 15. Add indexing support.\n * 16. Parse timestamp strings before creating index entries.\n * 17. TODO(tomandersen)\n * 18. Encode key safe representations of IndexEntry in DbIndexEntryStore.\n */\n\nexport const SCHEMA_VERSION = 18;\n\n/**\n * Wrapper class to store timestamps (seconds and nanos) in IndexedDb objects.\n */\nexport interface DbTimestamp {\n seconds: number;\n nanoseconds: number;\n}\n\n/**\n * A singleton object to be stored in the 'owner' store in IndexedDb.\n *\n * A given database can have a single primary tab assigned at a given time. That\n * tab must validate that it is still holding the primary lease before every\n * operation that requires locked access. The primary tab should regularly\n * write an updated timestamp to this lease to prevent other tabs from\n * \"stealing\" the primary lease\n */\nexport interface DbPrimaryClient {\n ownerId: string;\n /** Whether to allow shared access from multiple tabs. */\n allowTabSynchronization: boolean;\n leaseTimestampMs: number;\n}\n\n/**\n * An object to be stored in the 'mutationQueues' store in IndexedDb.\n *\n * Each user gets a single queue of MutationBatches to apply to the server.\n * DbMutationQueue tracks the metadata about the queue.\n */\nexport interface DbMutationQueue {\n /**\n * The normalized user ID to which this queue belongs.\n */\n userId: string;\n /**\n * An identifier for the highest numbered batch that has been acknowledged\n * by the server. All MutationBatches in this queue with batchIds less\n * than or equal to this value are considered to have been acknowledged by\n * the server.\n *\n * NOTE: this is deprecated and no longer used by the code.\n */\n lastAcknowledgedBatchId: number;\n /**\n * A stream token that was previously sent by the server.\n *\n * See StreamingWriteRequest in datastore.proto for more details about\n * usage.\n *\n * After sending this token, earlier tokens may not be used anymore so\n * only a single stream token is retained.\n *\n * NOTE: this is deprecated and no longer used by the code.\n */\n lastStreamToken: string;\n}\n\n/**\n * An object to be stored in the 'mutations' store in IndexedDb.\n *\n * Represents a batch of user-level mutations intended to be sent to the server\n * in a single write. Each user-level batch gets a separate DbMutationBatch\n * with a new batchId.\n */\nexport interface DbMutationBatch {\n /**\n * The normalized user ID to which this batch belongs.\n */\n userId: string;\n /**\n * An identifier for this batch, allocated using an auto-generated key.\n */\n batchId: BatchId;\n /**\n * The local write time of the batch, stored as milliseconds since the\n * epoch.\n */\n localWriteTimeMs: number;\n /**\n * A list of \"mutations\" that represent a partial base state from when this\n * write batch was initially created. During local application of the write\n * batch, these baseMutations are applied prior to the real writes in order\n * to override certain document fields from the remote document cache. This\n * is necessary in the case of non-idempotent writes (e.g. `increment()`\n * transforms) to make sure that the local view of the modified documents\n * doesn't flicker if the remote document cache receives the result of the\n * non-idempotent write before the write is removed from the queue.\n *\n * These mutations are never sent to the backend.\n */\n baseMutations?: ProtoWrite[];\n /**\n * A list of mutations to apply. All mutations will be applied atomically.\n *\n * Mutations are serialized via toMutation().\n */\n mutations: ProtoWrite[];\n}\n\n/**\n * An object to be stored in the 'documentMutations' store in IndexedDb.\n *\n * A manually maintained index of all the mutation batches that affect a given\n * document key. The rows in this table are references based on the contents of\n * DbMutationBatch.mutations.\n */\nexport interface DbDocumentMutation {}\n\n/**\n * Represents the known absence of a document at a particular version.\n * Stored in IndexedDb as part of a DbRemoteDocument object.\n */\nexport interface DbNoDocument {\n path: string[];\n readTime: DbTimestamp;\n}\n\n/**\n * Represents a document that is known to exist but whose data is unknown.\n * Stored in IndexedDb as part of a DbRemoteDocument object.\n */\nexport interface DbUnknownDocument {\n path: string[];\n version: DbTimestamp;\n}\n\n/**\n * An object to be stored in the 'remoteDocuments' store in IndexedDb.\n * It represents either:\n *\n * - A complete document.\n * - A \"no document\" representing a document that is known not to exist (at\n * some version).\n * - An \"unknown document\" representing a document that is known to exist (at\n * some version) but whose contents are unknown.\n *\n * The document key is split up across `prefixPath`, `collectionGroup` and\n * `documentId`.\n *\n * Note: This is the persisted equivalent of a MaybeDocument and could perhaps\n * be made more general if necessary.\n */\nexport interface DbRemoteDocument {\n /** The path to the document's collection (excluding). */\n prefixPath: string[];\n\n /** The collection ID the document is directly nested under. */\n collectionGroup: string;\n\n /** The document ID. */\n documentId: string;\n\n /** When the document was read from the backend. */\n readTime: DbTimestampKey;\n\n /**\n * Set to an instance of DbUnknownDocument if the data for a document is\n * not known, but it is known that a document exists at the specified\n * version (e.g. it had a successful update applied to it)\n */\n unknownDocument?: DbUnknownDocument;\n /**\n * Set to an instance of a DbNoDocument if it is known that no document\n * exists.\n */\n noDocument?: DbNoDocument;\n /**\n * Set to an instance of a Document if there's a cached version of the\n * document.\n */\n document?: ProtoDocument;\n /**\n * Documents that were written to the remote document store based on\n * a write acknowledgment are marked with `hasCommittedMutations`. These\n * documents are potentially inconsistent with the backend's copy and use\n * the write's commit version as their document version.\n */\n hasCommittedMutations: boolean;\n}\n\n/**\n * Contains a single entry that has metadata about the remote document cache.\n */\nexport interface DbRemoteDocumentGlobal {\n /**\n * Approximately the total size in bytes of all the\n * documents in the document cache.\n */\n byteSize: number;\n}\n\n/**\n * The persisted type for a query nested with in the 'targets' store in\n * IndexedDb. We use the proto definitions for these two kinds of queries in\n * order to avoid writing extra serialization logic.\n */\nexport type DbQuery = ProtoQueryTarget | ProtoDocumentsTarget;\n\n/**\n * An object to be stored in the 'targets' store in IndexedDb.\n *\n * This is based on and should be kept in sync with the proto used in the iOS\n * client.\n *\n * Each query the client listens to against the server is tracked on disk so\n * that the query can be efficiently resumed on restart.\n */\nexport interface DbTarget {\n /**\n * An auto-generated sequential numeric identifier for the query.\n *\n * Queries are stored using their canonicalId as the key, but these\n * canonicalIds can be quite long so we additionally assign a unique\n * queryId which can be used by referenced data structures (e.g.\n * indexes) to minimize the on-disk cost.\n */\n targetId: TargetId;\n /**\n * The canonical string representing this query. This is not unique.\n */\n canonicalId: string;\n /**\n * The last readTime received from the Watch Service for this query.\n *\n * This is the same value as TargetChange.read_time in the protos.\n */\n readTime: DbTimestamp;\n /**\n * An opaque, server-assigned token that allows watching a query to be\n * resumed after disconnecting without retransmitting all the data\n * that matches the query. The resume token essentially identifies a\n * point in time from which the server should resume sending results.\n *\n * This is related to the snapshotVersion in that the resumeToken\n * effectively also encodes that value, but the resumeToken is opaque\n * and sometimes encodes additional information.\n *\n * A consequence of this is that the resumeToken should be used when\n * asking the server to reason about where this client is in the watch\n * stream, but the client should use the snapshotVersion for its own\n * purposes.\n *\n * This is the same value as TargetChange.resume_token in the protos.\n */\n resumeToken: string;\n /**\n * A sequence number representing the last time this query was\n * listened to, used for garbage collection purposes.\n *\n * Conventionally this would be a timestamp value, but device-local\n * clocks are unreliable and they must be able to create new listens\n * even while disconnected. Instead this should be a monotonically\n * increasing number that's incremented on each listen call.\n *\n * This is different from the queryId since the queryId is an\n * immutable identifier assigned to the Query on first use while\n * lastListenSequenceNumber is updated every time the query is\n * listened to.\n */\n lastListenSequenceNumber: number;\n /**\n * Denotes the maximum snapshot version at which the associated query view\n * contained no limbo documents. Undefined for data written prior to\n * schema version 9.\n */\n lastLimboFreeSnapshotVersion?: DbTimestamp;\n /**\n * The query for this target.\n *\n * Because canonical ids are not unique we must store the actual query. We\n * use the proto to have an object we can persist without having to\n * duplicate translation logic to and from a `Query` object.\n */\n query: DbQuery;\n}\n\n/**\n * An object representing an association between a target and a document, or a\n * sentinel row marking the last sequence number at which a document was used.\n * Each document cached must have a corresponding sentinel row before lru\n * garbage collection is enabled.\n *\n * The target associations and sentinel rows are co-located so that orphaned\n * documents and their sequence numbers can be identified efficiently via a scan\n * of this store.\n */\nexport interface DbTargetDocument {\n /**\n * The targetId identifying a target or 0 for a sentinel row.\n */\n targetId: TargetId;\n /**\n * The path to the document, as encoded in the key.\n */\n path: EncodedResourcePath;\n /**\n * If this is a sentinel row, this should be the sequence number of the last\n * time the document specified by `path` was used. Otherwise, it should be\n * `undefined`.\n */\n sequenceNumber?: ListenSequenceNumber;\n}\n\n/**\n * A record of global state tracked across all Targets, tracked separately\n * to avoid the need for extra indexes.\n *\n * This should be kept in-sync with the proto used in the iOS client.\n */\nexport interface DbTargetGlobal {\n /**\n * The highest numbered target id across all targets.\n *\n * See DbTarget.targetId.\n */\n highestTargetId: TargetId;\n /**\n * The highest numbered lastListenSequenceNumber across all targets.\n *\n * See DbTarget.lastListenSequenceNumber.\n */\n highestListenSequenceNumber: number;\n /**\n * A global snapshot version representing the last consistent snapshot we\n * received from the backend. This is monotonically increasing and any\n * snapshots received from the backend prior to this version (e.g. for\n * targets resumed with a resumeToken) should be suppressed (buffered)\n * until the backend has caught up to this snapshot version again. This\n * prevents our cache from ever going backwards in time.\n */\n lastRemoteSnapshotVersion: DbTimestamp;\n /**\n * The number of targets persisted.\n */\n targetCount: number;\n}\n\n/**\n * An object representing an association between a Collection id (e.g. 'messages')\n * to a parent path (e.g. '/chats/123') that contains it as a (sub)collection.\n * This is used to efficiently find all collections to query when performing\n * a Collection Group query.\n */\nexport interface DbCollectionParent {\n /**\n * The collectionId (e.g. 'messages')\n */\n collectionId: string;\n /**\n * The path to the parent (either a document location or an empty path for\n * a root-level collection).\n */\n parent: EncodedResourcePath;\n}\n\n/**\n * A record of the metadata state of each client.\n *\n * PORTING NOTE: This is used to synchronize multi-tab state and does not need\n * to be ported to iOS or Android.\n */\nexport interface DbClientMetadata {\n // Note: Previous schema versions included a field\n // \"lastProcessedDocumentChangeId\". Don't use anymore.\n\n /** The auto-generated client id assigned at client startup. */\n clientId: string;\n /** The last time this state was updated. */\n updateTimeMs: number;\n /** Whether the client's network connection is enabled. */\n networkEnabled: boolean;\n /** Whether this client is running in a foreground tab. */\n inForeground: boolean;\n}\n\n/** An object representing a bundle loaded by the SDK. */\nexport interface DbBundle {\n /** The ID of the loaded bundle. */\n bundleId: string;\n /** The create time of the loaded bundle. */\n createTime: DbTimestamp;\n /** The schema version of the loaded bundle. */\n version: number;\n}\n\n/** An object representing a named query loaded by the SDK via a bundle. */\nexport interface DbNamedQuery {\n /** The name of the query. */\n name: string;\n /** The read time of the results saved in the bundle from the named query. */\n readTime: DbTimestamp;\n /** The query saved in the bundle. */\n bundledQuery: BundledQuery;\n}\n\n/** An object representing the global configuration for a field index. */\nexport interface DbIndexConfiguration {\n /**\n * The index id for this entry. Undefined for indexes that are not yet\n * persisted.\n */\n indexId?: number;\n /** The collection group this index belongs to. */\n collectionGroup: string;\n /** The fields to index for this index. */\n fields: Array<[name: string, kind: IndexKind]>;\n}\n\n/**\n * An object describing how up-to-date the index backfill is for each user and\n * index.\n */\nexport interface DbIndexState {\n /** The index id for this entry. */\n indexId: number;\n /** The user id for this entry. */\n uid: string;\n /**\n * A number that indicates when the index was last updated (relative to\n * other indexes).\n */\n sequenceNumber: number;\n /**\n * The latest read time that has been indexed by Firestore for this field\n * index. Set to `{seconds: 0, nanos: 0}` if no documents have been indexed.\n */\n readTime: DbTimestamp;\n /**\n * The last document that has been indexed for this field index. Empty if\n * no documents have been indexed.\n */\n documentKey: EncodedResourcePath;\n /**\n * The largest mutation batch id that has been processed for this index. -1\n * if no mutations have been indexed.\n */\n largestBatchId: number;\n}\n\n/** An object that stores the encoded entries for all documents and fields. */\nexport interface DbIndexEntry {\n // TODO(indexing): Consider just storing `orderedDocumentKey` and decoding\n // the ordered key into a document key. This would reduce storage space on\n // disk but require us to port parts of OrderedCodeReader.\n\n /** The index id for this entry. */\n indexId: number;\n /** The user id for this entry. */\n uid: string;\n /** The encoded array index value for this entry. */\n arrayValue: KeySafeBytes;\n /** The encoded directional value for equality and inequality filters. */\n directionalValue: KeySafeBytes;\n /**\n * The document key this entry points to. This entry is encoded by an ordered\n * encoder to match the key order of the index.\n */\n orderedDocumentKey: KeySafeBytes;\n /** The segments of the document key this entry points to. */\n documentKey: string[];\n}\n\n/**\n * An object representing a document overlay.\n */\nexport interface DbDocumentOverlay {\n /** The user ID to whom this overlay belongs. */\n userId: string;\n /** The path to the collection that contains the document. */\n collectionPath: string;\n /** The ID (key) of the document within the collection. */\n documentId: string;\n /** The collection group to which the document belongs. */\n collectionGroup: string;\n /** The largest batch ID that's been applied for this overlay. */\n largestBatchId: number;\n /** The overlay mutation. */\n overlayMutation: ProtoWrite;\n}\n\n/**\n * An object containing global name/value pair.\n */\nexport interface DbGlobals {\n /** Name is a globally unique identifier for a value. */\n name: string;\n /** Value is a general purpose storage for global data. */\n value: Uint8Array;\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(\n batch !== null,\n 0x90f9,\n 'Attempt to reject nonexistent batch!'\n );\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 0xbd9d,\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 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { BatchId, MutationBatchState, TargetId } from '../core/types';\nimport { debugAssert } from '../util/assert';\n\nimport { ClientId } from './shared_client_state';\nimport { QueryTargetState } from './shared_client_state_syncer';\n\n// The format of the LocalStorage key that stores the client state is:\n// firestore_clients__\nexport const CLIENT_STATE_KEY_PREFIX = 'firestore_clients';\n\n/** Assembles the key for a client state in WebStorage */\nexport function createWebStorageClientStateKey(\n persistenceKey: string,\n clientId: ClientId\n): string {\n debugAssert(\n clientId.indexOf('_') === -1,\n `Client key cannot contain '_', but was '${clientId}'`\n );\n\n return `${CLIENT_STATE_KEY_PREFIX}_${persistenceKey}_${clientId}`;\n}\n\n/**\n * The JSON representation of a clients's metadata as used during WebStorage\n * serialization. The ClientId is omitted here as it is encoded as part of the\n * key.\n */\nexport interface ClientStateSchema {\n activeTargetIds: number[];\n updateTimeMs: number;\n}\n\n// The format of the WebStorage key that stores the mutation state is:\n// firestore_mutations__\n// (for unauthenticated users)\n// or: firestore_mutations___\n//\n// 'user_uid' is last to avoid needing to escape '_' characters that it might\n// contain.\nexport const MUTATION_BATCH_KEY_PREFIX = 'firestore_mutations';\n\n/** Assembles the key for a mutation batch in WebStorage */\nexport function createWebStorageMutationBatchKey(\n persistenceKey: string,\n user: User,\n batchId: BatchId\n): string {\n let mutationKey = `${MUTATION_BATCH_KEY_PREFIX}_${persistenceKey}_${batchId}`;\n\n if (user.isAuthenticated()) {\n mutationKey += `_${user.uid}`;\n }\n\n return mutationKey;\n}\n\n/**\n * The JSON representation of a mutation batch's metadata as used during\n * WebStorage serialization. The UserId and BatchId is omitted as it is\n * encoded as part of the key.\n */\nexport interface MutationMetadataSchema {\n state: MutationBatchState;\n error?: { code: string; message: string }; // Only set when state === 'rejected'\n updateTimeMs: number;\n}\n\n// The format of the WebStorage key that stores a query target's metadata is:\n// firestore_targets__\nexport const QUERY_TARGET_KEY_PREFIX = 'firestore_targets';\n\n/** Assembles the key for a query state in WebStorage */\nexport function createWebStorageQueryTargetMetadataKey(\n persistenceKey: string,\n targetId: TargetId\n): string {\n return `${QUERY_TARGET_KEY_PREFIX}_${persistenceKey}_${targetId}`;\n}\n\n/**\n * The JSON representation of a query target's state as used during WebStorage\n * serialization. The TargetId is omitted as it is encoded as part of the key.\n */\nexport interface QueryTargetStateSchema {\n state: QueryTargetState;\n error?: { code: string; message: string }; // Only set when state === 'rejected'\n updateTimeMs: number;\n}\n\n// The WebStorage prefix that stores the primary tab's online state. The\n// format of the key is:\n// firestore_online_state_\nexport const ONLINE_STATE_KEY_PREFIX = 'firestore_online_state';\n\n/** Assembles the key for the online state of the primary tab. */\nexport function createWebStorageOnlineStateKey(persistenceKey: string): string {\n return `${ONLINE_STATE_KEY_PREFIX}_${persistenceKey}`;\n}\n\n// The WebStorage prefix that plays as a event to indicate the remote documents\n// might have changed due to some secondary tabs loading a bundle.\n// format of the key is:\n// firestore_bundle_loaded_v2_\n// The version ending with \"v2\" stores the list of modified collection groups.\nexport const BUNDLE_LOADED_KEY_PREFIX = 'firestore_bundle_loaded_v2';\nexport function createBundleLoadedKey(persistenceKey: string): string {\n return `${BUNDLE_LOADED_KEY_PREFIX}_${persistenceKey}`;\n}\n\n/**\n * The JSON representation of the system's online state, as written by the\n * primary client.\n */\nexport interface SharedOnlineStateSchema {\n /**\n * The clientId of the client that wrote this onlineState value. Tracked so\n * that on startup, clients can check if this client is still active when\n * determining whether to apply this value or not.\n */\n readonly clientId: string;\n readonly onlineState: string;\n}\n\n// The WebStorage key prefix for the key that stores the last sequence number allocated. The key\n// looks like 'firestore_sequence_number_'.\nexport const SEQUENCE_NUMBER_KEY_PREFIX = 'firestore_sequence_number';\n\n/** Assembles the key for the current sequence number. */\nexport function createWebStorageSequenceNumberKey(\n persistenceKey: string\n): string {\n return `${SEQUENCE_NUMBER_KEY_PREFIX}_${persistenceKey}`;\n}\n","/**\n * @license\n * Copyright 2018 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { User } from '../auth/user';\nimport { ListenSequence } from '../core/listen_sequence';\nimport {\n BatchId,\n ListenSequenceNumber,\n MutationBatchState,\n OnlineState,\n TargetId\n} from '../core/types';\nimport { TargetIdSet, targetIdSet } from '../model/collections';\nimport { hardAssert, debugAssert } from '../util/assert';\nimport { AsyncQueue } from '../util/async_queue';\nimport { Code, FirestoreError } from '../util/error';\nimport { logError, logDebug } from '../util/log';\nimport { primitiveComparator } from '../util/misc';\nimport { SortedMap } from '../util/sorted_map';\nimport { SortedSet } from '../util/sorted_set';\nimport { isSafeInteger, WindowLike } from '../util/types';\n\nimport {\n CLIENT_STATE_KEY_PREFIX,\n ClientStateSchema,\n createBundleLoadedKey,\n createWebStorageClientStateKey,\n createWebStorageMutationBatchKey,\n createWebStorageOnlineStateKey,\n createWebStorageQueryTargetMetadataKey,\n createWebStorageSequenceNumberKey,\n MUTATION_BATCH_KEY_PREFIX,\n MutationMetadataSchema,\n QUERY_TARGET_KEY_PREFIX,\n QueryTargetStateSchema,\n SharedOnlineStateSchema\n} from './shared_client_state_schema';\nimport {\n QueryTargetState,\n SharedClientStateSyncer\n} from './shared_client_state_syncer';\n\nconst LOG_TAG = 'SharedClientState';\n\n/**\n * A randomly-generated key assigned to each Firestore instance at startup.\n */\nexport type ClientId = string;\n\n/**\n * A `SharedClientState` keeps track of the global state of the mutations\n * and query targets for all active clients with the same persistence key (i.e.\n * project ID and FirebaseApp name). It relays local changes to other clients\n * and updates its local state as new state is observed.\n *\n * `SharedClientState` is primarily used for synchronization in Multi-Tab\n * environments. Each tab is responsible for registering its active query\n * targets and mutations. `SharedClientState` will then notify the listener\n * assigned to `.syncEngine` for updates to mutations and queries that\n * originated in other clients.\n *\n * To receive notifications, `.syncEngine` and `.onlineStateHandler` has to be\n * assigned before calling `start()`.\n */\nexport interface SharedClientState {\n onlineStateHandler: ((onlineState: OnlineState) => void) | null;\n sequenceNumberHandler:\n | ((sequenceNumber: ListenSequenceNumber) => void)\n | null;\n\n /** Registers the Mutation Batch ID of a newly pending mutation. */\n addPendingMutation(batchId: BatchId): void;\n\n /**\n * Records that a pending mutation has been acknowledged or rejected.\n * Called by the primary client to notify secondary clients of mutation\n * results as they come back from the backend.\n */\n updateMutationState(\n batchId: BatchId,\n state: 'acknowledged' | 'rejected',\n error?: FirestoreError\n ): void;\n\n /**\n * Associates a new Query Target ID with the local Firestore client. Returns\n * the new query state for the query (which can be 'current' if the query is\n * already associated with another tab).\n *\n * If the target id is already associated with local client, the method simply\n * returns its `QueryTargetState`.\n */\n addLocalQueryTarget(\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 0x77ac,\n 'Found non-numeric sequence number',\n { seqString }\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 { isCloudWorkstation } from '@firebase/util';\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 const { host } = new URL(url);\n const forwardCredentials = isCloudWorkstation(host);\n return this.performRPCRequest(\n rpcName,\n url,\n headers,\n req,\n forwardCredentials\n ).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 _forwardCredentials: boolean\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 /** A collection of open WebChannel instances */\n private openWebChannels: WebChannel[] = [];\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 _forwardCredentials: boolean\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 0x235f,\n 'RPC failed with unanticipated webchannel error. Giving up.',\n {\n rpcName,\n streamId,\n lastErrorCode: xhr.getLastErrorCode(),\n lastError: xhr.getLastError()\n }\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 this.addOpenWebChannel(channel);\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 this.removeOpenWebChannel(channel);\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. Name:`,\n err.name,\n 'Message:',\n err.message\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(\n !!msgData,\n 0x3fdd,\n 'Got a webchannel message without data.'\n );\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 as WebChannelError)?.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 * Closes and cleans up any resources associated with the connection.\n */\n terminate(): void {\n // If the Firestore instance is terminated, we will explicitly\n // close any remaining open WebChannel instances.\n this.openWebChannels.forEach(webChannel => webChannel.close());\n this.openWebChannels = [];\n }\n\n /**\n * Add a WebChannel instance to the collection of open instances.\n * @param webChannel\n */\n addOpenWebChannel(webChannel: WebChannel): void {\n this.openWebChannels.push(webChannel);\n }\n\n /**\n * Remove a WebChannel instance from the collection of open instances.\n * @param webChannel\n */\n removeOpenWebChannel(webChannel: WebChannel): void {\n this.openWebChannels = this.openWebChannels.filter(\n instance => instance === webChannel\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/** 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 0x7a5a,\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 0xda08,\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 0x3186,\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, 0xd7c2, 'Missing entity in write response for `key`', {\n key\n });\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 0xfcd7,\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 0xf76d,\n 'unsupported combination of changes: `change` after `oldChange`',\n {\n change,\n oldChange\n }\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n BundleElement,\n BundleMetadata\n} from '../protos/firestore_bundle_proto';\nimport { JsonProtoSerializer } from '../remote/serializer';\n\n/**\n * A complete element in the bundle stream, together with the byte length it\n * occupies in the stream.\n */\nexport class SizedBundleElement {\n constructor(\n public readonly payload: BundleElement,\n // How many bytes this element takes to store in the bundle.\n public readonly byteLength: number\n ) {}\n\n isBundleMetadata(): boolean {\n return 'metadata' in this.payload;\n }\n}\n\nexport type BundleSource =\n | ReadableStream\n | ArrayBuffer\n | Uint8Array;\n\n/**\n * A class representing a bundle.\n *\n * Takes a bundle stream or buffer, and presents abstractions to read bundled\n * elements out of the underlying content.\n */\nexport interface BundleReader {\n serializer: JsonProtoSerializer;\n\n close(): Promise;\n\n /**\n * Returns the metadata of the bundle.\n */\n getMetadata(): Promise;\n\n /**\n * Returns the next BundleElement (together with its byte size in the bundle)\n * that has not been read from underlying ReadableStream. Returns null if we\n * have reached the end of the stream.\n */\n nextElement(): Promise;\n}\n\n/**\n * A class representing a synchronized bundle reader.\n *\n * Takes a bundle string buffer, parses the data, and provides accessors to the data contained\n * within it.\n */\nexport interface BundleReaderSync {\n serializer: JsonProtoSerializer;\n\n /**\n * Returns the metadata of the bundle.\n */\n getMetadata(): BundleMetadata;\n\n /**\n * Returns BundleElements parsed from the bundle. Returns an empty array if no bundle elements\n * exist.\n */\n getElements(): SizedBundleElement[];\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { LoadBundleTaskProgress } from '@firebase/firestore-types';\n\nimport { LocalStore } from '../local/local_store';\nimport {\n localStoreApplyBundledDocuments,\n localStoreSaveNamedQuery\n} from '../local/local_store_impl';\nimport { documentKeySet, DocumentKeySet } from '../model/collections';\nimport { MutableDocument } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { ResourcePath } from '../model/path';\nimport {\n BundleMetadata as ProtoBundleMetadata,\n NamedQuery as ProtoNamedQuery\n} from '../protos/firestore_bundle_proto';\nimport { Timestamp as ApiTimestamp } from '../protos/firestore_proto_api';\nimport {\n fromDocument,\n fromName,\n fromVersion,\n JsonProtoSerializer\n} from '../remote/serializer';\nimport { debugAssert } from '../util/assert';\nimport { SizedBundleElement } from '../util/bundle_reader';\n\nimport {\n BundleConverter,\n BundledDocument,\n BundledDocuments,\n BundleLoadResult\n} from './bundle';\nimport { SnapshotVersion } from './snapshot_version';\n\n/**\n * Helper to convert objects from bundles to model objects in the SDK.\n */\nexport class BundleConverterImpl implements BundleConverter {\n constructor(private readonly serializer: JsonProtoSerializer) {}\n\n toDocumentKey(name: string): DocumentKey {\n return fromName(this.serializer, name);\n }\n\n /**\n * Converts a BundleDocument to a MutableDocument.\n */\n toMutableDocument(bundledDoc: BundledDocument): MutableDocument {\n if (bundledDoc.metadata.exists) {\n debugAssert(\n !!bundledDoc.document,\n 'Document is undefined when metadata.exist is true.'\n );\n return fromDocument(this.serializer, bundledDoc.document!, false);\n } else {\n return MutableDocument.newNoDocument(\n this.toDocumentKey(bundledDoc.metadata.name!),\n this.toSnapshotVersion(bundledDoc.metadata.readTime!)\n );\n }\n }\n\n toSnapshotVersion(time: ApiTimestamp): SnapshotVersion {\n return fromVersion(time);\n }\n}\n\n/**\n * A class to process the elements from a bundle, and optionally load them into local\n * storage and provide progress update while loading.\n */\nexport class BundleLoader {\n /** The current progress of loading */\n private progress: LoadBundleTaskProgress;\n /** Batched queries to be saved into storage */\n private _queries: ProtoNamedQuery[] = [];\n /** Batched documents to be saved into storage */\n private _documents: BundledDocuments = [];\n /** The collection groups affected by this bundle. */\n private collectionGroups = new Set();\n\n constructor(\n private bundleMetadata: ProtoBundleMetadata,\n private serializer: JsonProtoSerializer\n ) {\n this.progress = bundleInitialProgress(bundleMetadata);\n }\n\n /**\n * Returns the named queries that have been parsed from the SizeBundleElements added by\n * calling {@link adSizedElement}.\n */\n get queries(): ProtoNamedQuery[] {\n return this._queries;\n }\n\n /**\n * Returns the BundledDocuments that have been parsed from the SizeBundleElements added by\n * calling {@link addSizedElement}.\n */\n get documents(): BundledDocuments {\n return this._documents;\n }\n\n /**\n * Adds an element from the bundle to the loader.\n *\n * Returns a new progress if adding the element leads to a new progress,\n * otherwise returns null.\n */\n addSizedElement(element: SizedBundleElement): LoadBundleTaskProgress | null {\n debugAssert(!element.isBundleMetadata(), 'Unexpected bundle metadata.');\n\n this.progress.bytesLoaded += element.byteLength;\n\n let documentsLoaded = this.progress.documentsLoaded;\n\n if (element.payload.namedQuery) {\n this._queries.push(element.payload.namedQuery);\n } else if (element.payload.documentMetadata) {\n this._documents.push({ metadata: element.payload.documentMetadata });\n if (!element.payload.documentMetadata.exists) {\n ++documentsLoaded;\n }\n const path = ResourcePath.fromString(\n element.payload.documentMetadata.name!\n );\n debugAssert(\n path.length >= 2,\n 'The document name does not point to a document.'\n );\n this.collectionGroups.add(path.get(path.length - 2));\n } else if (element.payload.document) {\n debugAssert(\n this._documents.length > 0 &&\n this._documents[this._documents.length - 1].metadata.name ===\n element.payload.document.name,\n 'The document being added does not match the stored metadata.'\n );\n this._documents[this._documents.length - 1].document =\n element.payload.document;\n ++documentsLoaded;\n }\n\n if (documentsLoaded !== this.progress.documentsLoaded) {\n this.progress.documentsLoaded = documentsLoaded;\n return { ...this.progress };\n }\n\n return null;\n }\n\n private getQueryDocumentMapping(\n documents: BundledDocuments\n ): Map {\n const queryDocumentMap = new Map();\n const bundleConverter = new BundleConverterImpl(this.serializer);\n for (const bundleDoc of documents) {\n if (bundleDoc.metadata.queries) {\n const documentKey = bundleConverter.toDocumentKey(\n bundleDoc.metadata.name!\n );\n for (const queryName of bundleDoc.metadata.queries) {\n const documentKeys = (\n queryDocumentMap.get(queryName) || documentKeySet()\n ).add(documentKey);\n queryDocumentMap.set(queryName, documentKeys);\n }\n }\n }\n\n return queryDocumentMap;\n }\n\n /**\n * Update the progress to 'Success' and return the updated progress.\n */\n async completeAndStoreAsync(\n localStore: LocalStore\n ): Promise {\n debugAssert(\n this._documents[this._documents.length - 1]?.metadata.exists !== true ||\n !!this._documents[this._documents.length - 1].document,\n 'Bundled documents end with a document metadata element instead of a document.'\n );\n debugAssert(!!this.bundleMetadata.id, 'Bundle ID must be set.');\n\n const changedDocs = await localStoreApplyBundledDocuments(\n localStore,\n new BundleConverterImpl(this.serializer),\n this._documents,\n this.bundleMetadata.id!\n );\n\n const queryDocumentMap = this.getQueryDocumentMapping(this.documents);\n\n for (const q of this._queries) {\n await localStoreSaveNamedQuery(\n localStore,\n q,\n queryDocumentMap.get(q.name!)\n );\n }\n\n this.progress.taskState = 'Success';\n return {\n progress: this.progress,\n changedCollectionGroups: this.collectionGroups,\n changedDocs\n };\n }\n}\n\n/**\n * Returns a `LoadBundleTaskProgress` representing the initial progress of\n * loading a bundle.\n */\nexport function bundleInitialProgress(\n metadata: ProtoBundleMetadata\n): LoadBundleTaskProgress {\n return {\n taskState: 'Running',\n documentsLoaded: 0,\n bytesLoaded: 0,\n totalDocuments: metadata.totalDocuments!,\n totalBytes: metadata.totalBytes!\n };\n}\n\n/**\n * Returns a `LoadBundleTaskProgress` representing the progress that the loading\n * has succeeded.\n */\nexport function bundleSuccessProgress(\n metadata: ProtoBundleMetadata\n): LoadBundleTaskProgress {\n return {\n taskState: 'Success',\n documentsLoaded: metadata.totalDocuments!,\n bytesLoaded: metadata.totalBytes!,\n totalDocuments: metadata.totalDocuments!,\n totalBytes: metadata.totalBytes!\n };\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { QueryResult } from '../local/local_store_impl';\nimport {\n documentKeySet,\n DocumentKeySet,\n DocumentMap\n} from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { DocumentSet } from '../model/document_set';\nimport { TargetChange } from '../remote/remote_event';\nimport { debugAssert, fail } from '../util/assert';\n\nimport { LimitType, newQueryComparator, Query, queryMatches } from './query';\nimport { OnlineState } from './types';\nimport {\n ChangeType,\n DocumentChangeSet,\n SyncState,\n ViewSnapshot\n} from './view_snapshot';\n\nexport type LimboDocumentChange = AddedLimboDocument | RemovedLimboDocument;\nexport class AddedLimboDocument {\n constructor(public key: DocumentKey) {}\n}\nexport class RemovedLimboDocument {\n constructor(public key: DocumentKey) {}\n}\n\n/** The result of applying a set of doc changes to a view. */\nexport interface ViewDocumentChanges {\n /** The new set of docs that should be in the view. */\n documentSet: DocumentSet;\n /** The diff of these docs with the previous set of docs. */\n changeSet: DocumentChangeSet;\n /**\n * Whether the set of documents passed in was not sufficient to calculate the\n * new state of the view and there needs to be another pass based on the\n * local cache.\n */\n needsRefill: boolean;\n\n mutatedKeys: DocumentKeySet;\n}\n\nexport interface ViewChange {\n snapshot?: ViewSnapshot;\n limboChanges: LimboDocumentChange[];\n}\n\n/**\n * View is responsible for computing the final merged truth of what docs are in\n * a query. It gets notified of local and remote changes to docs, and applies\n * the query filters and limits to determine the most correct possible results.\n */\nexport class View {\n private syncState: SyncState | null = null;\n private hasCachedResults: boolean = false;\n /**\n * A flag whether the view is current with the backend. A view is considered\n * current after it has seen the current flag from the backend and did not\n * lose consistency within the watch stream (e.g. because of an existence\n * filter mismatch).\n */\n private current = false;\n private documentSet: DocumentSet;\n /** Documents in the view but not in the remote target */\n private limboDocuments = documentKeySet();\n /** Document Keys that have local changes */\n private mutatedKeys = documentKeySet();\n /** Query comparator that defines the document order in this view. */\n private docComparator: (d1: Document, d2: Document) => number;\n\n constructor(\n private query: Query,\n /** Documents included in the remote target */\n private _syncedDocuments: DocumentKeySet\n ) {\n this.docComparator = newQueryComparator(query);\n this.documentSet = new DocumentSet(this.docComparator);\n }\n\n /**\n * The set of remote documents that the server has told us belongs to the target associated with\n * this view.\n */\n get syncedDocuments(): DocumentKeySet {\n return this._syncedDocuments;\n }\n\n /**\n * Iterates over a set of doc changes, applies the query limit, and computes\n * what the new results should be, what the changes were, and whether we may\n * need to go back to the local cache for more results. Does not make any\n * changes to the view.\n * @param docChanges - The doc changes to apply to this view.\n * @param previousChanges - If this is being called with a refill, then start\n * with this set of docs and changes instead of the current view.\n * @returns a new set of docs, changes, and refill flag.\n */\n computeDocChanges(\n docChanges: DocumentMap,\n previousChanges?: ViewDocumentChanges\n ): ViewDocumentChanges {\n const changeSet = previousChanges\n ? previousChanges.changeSet\n : new DocumentChangeSet();\n const oldDocumentSet = previousChanges\n ? previousChanges.documentSet\n : this.documentSet;\n let newMutatedKeys = previousChanges\n ? previousChanges.mutatedKeys\n : this.mutatedKeys;\n let newDocumentSet = oldDocumentSet;\n let needsRefill = false;\n\n // Track the last doc in a (full) limit. This is necessary, because some\n // update (a delete, or an update moving a doc past the old limit) might\n // mean there is some other document in the local cache that either should\n // come (1) between the old last limit doc and the new last document, in the\n // case of updates, or (2) after the new last document, in the case of\n // deletes. So we keep this doc at the old limit to compare the updates to.\n //\n // Note that this should never get used in a refill (when previousChanges is\n // set), because there will only be adds -- no deletes or updates.\n const lastDocInLimit =\n this.query.limitType === LimitType.First &&\n oldDocumentSet.size === this.query.limit\n ? oldDocumentSet.last()\n : null;\n const firstDocInLimit =\n this.query.limitType === LimitType.Last &&\n oldDocumentSet.size === this.query.limit\n ? oldDocumentSet.first()\n : null;\n\n docChanges.inorderTraversal((key, entry) => {\n const oldDoc = oldDocumentSet.get(key);\n const newDoc = queryMatches(this.query, entry) ? entry : null;\n\n const oldDocHadPendingMutations = oldDoc\n ? this.mutatedKeys.has(oldDoc.key)\n : false;\n const newDocHasPendingMutations = newDoc\n ? newDoc.hasLocalMutations ||\n // We only consider committed mutations for documents that were\n // mutated during the lifetime of the view.\n (this.mutatedKeys.has(newDoc.key) && newDoc.hasCommittedMutations)\n : false;\n\n let changeApplied = false;\n\n // Calculate change\n if (oldDoc && newDoc) {\n const docsEqual = oldDoc.data.isEqual(newDoc.data);\n if (!docsEqual) {\n if (!this.shouldWaitForSyncedDocument(oldDoc, newDoc)) {\n changeSet.track({\n type: ChangeType.Modified,\n doc: newDoc\n });\n changeApplied = true;\n\n if (\n (lastDocInLimit &&\n this.docComparator(newDoc, lastDocInLimit) > 0) ||\n (firstDocInLimit &&\n this.docComparator(newDoc, firstDocInLimit) < 0)\n ) {\n // This doc moved from inside the limit to outside the limit.\n // That means there may be some other doc in the local cache\n // that should be included instead.\n needsRefill = true;\n }\n }\n } else if (oldDocHadPendingMutations !== newDocHasPendingMutations) {\n changeSet.track({ type: ChangeType.Metadata, doc: newDoc });\n changeApplied = true;\n }\n } else if (!oldDoc && newDoc) {\n changeSet.track({ type: ChangeType.Added, doc: newDoc });\n changeApplied = true;\n } else if (oldDoc && !newDoc) {\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc });\n changeApplied = true;\n\n if (lastDocInLimit || firstDocInLimit) {\n // A doc was removed from a full limit query. We'll need to\n // requery from the local cache to see if we know about some other\n // doc that should be in the results.\n needsRefill = true;\n }\n }\n\n if (changeApplied) {\n if (newDoc) {\n newDocumentSet = newDocumentSet.add(newDoc);\n if (newDocHasPendingMutations) {\n newMutatedKeys = newMutatedKeys.add(key);\n } else {\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n } else {\n newDocumentSet = newDocumentSet.delete(key);\n newMutatedKeys = newMutatedKeys.delete(key);\n }\n }\n });\n\n // Drop documents out to meet limit/limitToLast requirement.\n if (this.query.limit !== null) {\n while (newDocumentSet.size > this.query.limit!) {\n const oldDoc =\n this.query.limitType === LimitType.First\n ? newDocumentSet.last()\n : newDocumentSet.first();\n newDocumentSet = newDocumentSet.delete(oldDoc!.key);\n newMutatedKeys = newMutatedKeys.delete(oldDoc!.key);\n changeSet.track({ type: ChangeType.Removed, doc: oldDoc! });\n }\n }\n\n debugAssert(\n !needsRefill || !previousChanges,\n 'View was refilled using docs that themselves needed refilling.'\n );\n return {\n documentSet: newDocumentSet,\n changeSet,\n needsRefill,\n mutatedKeys: newMutatedKeys\n };\n }\n\n private shouldWaitForSyncedDocument(\n oldDoc: Document,\n newDoc: Document\n ): boolean {\n // We suppress the initial change event for documents that were modified as\n // part of a write acknowledgment (e.g. when the value of a server transform\n // is applied) as Watch will send us the same document again.\n // By suppressing the event, we only raise two user visible events (one with\n // `hasPendingWrites` and the final state of the document) instead of three\n // (one with `hasPendingWrites`, the modified document with\n // `hasPendingWrites` and the final state of the document).\n return (\n oldDoc.hasLocalMutations &&\n newDoc.hasCommittedMutations &&\n !newDoc.hasLocalMutations\n );\n }\n\n /**\n * Updates the view with the given ViewDocumentChanges and optionally updates\n * limbo docs and sync state from the provided target change.\n * @param docChanges - The set of changes to make to the view's docs.\n * @param limboResolutionEnabled - Whether to update limbo documents based on\n * this change.\n * @param targetChange - A target change to apply for computing limbo docs and\n * sync state.\n * @param targetIsPendingReset - Whether the target is pending to reset due to\n * existence filter mismatch. If not explicitly specified, it is treated\n * equivalently to `false`.\n * @returns A new ViewChange with the given docs, changes, and sync state.\n */\n // PORTING NOTE: The iOS/Android clients always compute limbo document changes.\n applyChanges(\n docChanges: ViewDocumentChanges,\n limboResolutionEnabled: boolean,\n targetChange?: TargetChange,\n targetIsPendingReset?: boolean\n ): ViewChange {\n debugAssert(\n !docChanges.needsRefill,\n 'Cannot apply changes that need a refill'\n );\n const oldDocs = this.documentSet;\n this.documentSet = docChanges.documentSet;\n this.mutatedKeys = docChanges.mutatedKeys;\n // Sort changes based on type and query comparator\n const changes = docChanges.changeSet.getChanges();\n changes.sort((c1, c2) => {\n return (\n compareChangeType(c1.type, c2.type) ||\n this.docComparator(c1.doc, c2.doc)\n );\n });\n\n this.applyTargetChange(targetChange);\n\n targetIsPendingReset = targetIsPendingReset ?? false;\n const limboChanges =\n limboResolutionEnabled && !targetIsPendingReset\n ? this.updateLimboDocuments()\n : [];\n\n // We are at synced state if there is no limbo docs are waiting to be resolved, view is current\n // with the backend, and the query is not pending to reset due to existence filter mismatch.\n const synced =\n this.limboDocuments.size === 0 && this.current && !targetIsPendingReset;\n\n const newSyncState = synced ? SyncState.Synced : SyncState.Local;\n const syncStateChanged = newSyncState !== this.syncState;\n this.syncState = newSyncState;\n\n if (changes.length === 0 && !syncStateChanged) {\n // no changes\n return { limboChanges };\n } else {\n const snap: ViewSnapshot = new ViewSnapshot(\n this.query,\n docChanges.documentSet,\n oldDocs,\n changes,\n docChanges.mutatedKeys,\n newSyncState === SyncState.Local,\n syncStateChanged,\n /* excludesMetadataChanges= */ false,\n targetChange\n ? targetChange.resumeToken.approximateByteSize() > 0\n : false\n );\n return {\n snapshot: snap,\n limboChanges\n };\n }\n }\n\n /**\n * Applies an OnlineState change to the view, potentially generating a\n * ViewChange if the view's syncState changes as a result.\n */\n applyOnlineStateChange(onlineState: OnlineState): ViewChange {\n if (this.current && onlineState === OnlineState.Offline) {\n // If we're offline, set `current` to false and then call applyChanges()\n // to refresh our syncState and generate a ViewChange as appropriate. We\n // are guaranteed to get a new TargetChange that sets `current` back to\n // true once the client is back online.\n this.current = false;\n return this.applyChanges(\n {\n documentSet: this.documentSet,\n changeSet: new DocumentChangeSet(),\n mutatedKeys: this.mutatedKeys,\n needsRefill: false\n },\n /* limboResolutionEnabled= */ false\n );\n } else {\n // No effect, just return a no-op ViewChange.\n return { limboChanges: [] };\n }\n }\n\n /**\n * Returns whether the doc for the given key should be in limbo.\n */\n private shouldBeInLimbo(key: DocumentKey): boolean {\n // If the remote end says it's part of this query, it's not in limbo.\n if (this._syncedDocuments.has(key)) {\n return false;\n }\n // The local store doesn't think it's a result, so it shouldn't be in limbo.\n if (!this.documentSet.has(key)) {\n return false;\n }\n // If there are local changes to the doc, they might explain why the server\n // doesn't know that it's part of the query. So don't put it in limbo.\n // TODO(klimt): Ideally, we would only consider changes that might actually\n // affect this specific query.\n if (this.documentSet.get(key)!.hasLocalMutations) {\n return false;\n }\n // Everything else is in limbo.\n return true;\n }\n\n /**\n * Updates syncedDocuments, current, and limbo docs based on the given change.\n * Returns the list of changes to which docs are in limbo.\n */\n private applyTargetChange(targetChange?: TargetChange): void {\n if (targetChange) {\n targetChange.addedDocuments.forEach(\n key => (this._syncedDocuments = this._syncedDocuments.add(key))\n );\n targetChange.modifiedDocuments.forEach(key => {\n debugAssert(\n this._syncedDocuments.has(key),\n `Modified document ${key} not found in view.`\n );\n });\n targetChange.removedDocuments.forEach(\n key => (this._syncedDocuments = this._syncedDocuments.delete(key))\n );\n this.current = targetChange.current;\n }\n }\n\n private updateLimboDocuments(): LimboDocumentChange[] {\n // We can only determine limbo documents when we're in-sync with the server.\n if (!this.current) {\n return [];\n }\n\n // TODO(klimt): Do this incrementally so that it's not quadratic when\n // updating many documents.\n const oldLimboDocuments = this.limboDocuments;\n this.limboDocuments = documentKeySet();\n this.documentSet.forEach(doc => {\n if (this.shouldBeInLimbo(doc.key)) {\n this.limboDocuments = this.limboDocuments.add(doc.key);\n }\n });\n\n // Diff the new limbo docs with the old limbo docs.\n const changes: LimboDocumentChange[] = [];\n oldLimboDocuments.forEach(key => {\n if (!this.limboDocuments.has(key)) {\n changes.push(new RemovedLimboDocument(key));\n }\n });\n this.limboDocuments.forEach(key => {\n if (!oldLimboDocuments.has(key)) {\n changes.push(new AddedLimboDocument(key));\n }\n });\n return changes;\n }\n\n /**\n * Update the in-memory state of the current view with the state read from\n * persistence.\n *\n * We update the query view whenever a client's primary status changes:\n * - When a client transitions from primary to secondary, it can miss\n * LocalStorage updates and its query views may temporarily not be\n * synchronized with the state on disk.\n * - For secondary to primary transitions, the client needs to update the list\n * of `syncedDocuments` since secondary clients update their query views\n * based purely on synthesized RemoteEvents.\n *\n * @param queryResult.documents - The documents that match the query according\n * to the LocalStore.\n * @param queryResult.remoteKeys - The keys of the documents that match the\n * query according to the backend.\n *\n * @returns The ViewChange that resulted from this synchronization.\n */\n // PORTING NOTE: Multi-tab only.\n synchronizeWithPersistedState(queryResult: QueryResult): ViewChange {\n this._syncedDocuments = queryResult.remoteKeys;\n this.limboDocuments = documentKeySet();\n const docChanges = this.computeDocChanges(queryResult.documents);\n return this.applyChanges(docChanges, /* limboResolutionEnabled= */ true);\n }\n\n /**\n * Returns a view snapshot as if this query was just listened to. Contains\n * a document add for every existing document and the `fromCache` and\n * `hasPendingWrites` status of the already established view.\n */\n // PORTING NOTE: Multi-tab only.\n computeInitialSnapshot(): ViewSnapshot {\n return ViewSnapshot.fromInitialDocuments(\n this.query,\n this.documentSet,\n this.mutatedKeys,\n this.syncState === SyncState.Local,\n this.hasCachedResults\n );\n }\n}\n\nfunction compareChangeType(c1: ChangeType, c2: ChangeType): number {\n const order = (change: ChangeType): 0 | 1 | 2 => {\n switch (change) {\n case ChangeType.Added:\n return 1;\n case ChangeType.Modified:\n return 2;\n case ChangeType.Metadata:\n // A metadata change is converted to a modified change at the public\n // api layer. Since we sort by document key and then change type,\n // metadata and modified changes must be sorted equivalently.\n return 2;\n case ChangeType.Removed:\n return 0;\n default:\n return fail(0x4f35, '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 0x5858,\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 0x390f,\n 'Received change for limbo target document without add.'\n );\n } else if (targetChange.removedDocuments.size > 0) {\n hardAssert(\n limboResolution.receivedDocument,\n 0xa4f3,\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(0x4d4f, 'Unknown limbo change', { 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(0x1a40, `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(0xfa9b, '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(metadata, reader.serializer);\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.completeAndStoreAsync(syncEngine.localStore);\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 0xb743,\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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { debugAssert } from './assert';\n\n/**\n * How many bytes to read each time when `ReadableStreamReader.read()` is\n * called. Only applicable for byte streams that we control (e.g. those backed\n * by an UInt8Array).\n */\nexport const DEFAULT_BYTES_PER_READ = 10240;\n\n/**\n * Builds a `ByteStreamReader` from a UInt8Array.\n * @param source - The data source to use.\n * @param bytesPerRead - How many bytes each `read()` from the returned reader\n * will read.\n */\nexport function toByteStreamReaderHelper(\n source: Uint8Array,\n bytesPerRead: number = DEFAULT_BYTES_PER_READ\n): ReadableStreamDefaultReader {\n debugAssert(\n bytesPerRead > 0,\n `toByteStreamReader expects positive bytesPerRead, but got ${bytesPerRead}`\n );\n let readFrom = 0;\n // The TypeScript definition for ReadableStreamReader changed. We use\n // `any` here to allow this code to compile with different versions.\n // See https://github.com/microsoft/TypeScript/issues/42970\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const reader: any = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n async read(): Promise {\n if (readFrom < source.byteLength) {\n const result = {\n value: source.slice(readFrom, readFrom + bytesPerRead),\n done: false\n } as const;\n readFrom += bytesPerRead;\n return result;\n }\n\n return { done: true };\n },\n async cancel(): Promise {},\n releaseLock() {},\n closed: Promise.resolve()\n };\n return reader;\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Observer } from '../core/event_manager';\n\nimport { FirestoreError } from './error';\nimport { logError } from './log';\nimport { EventHandler } from './misc';\n\n/*\n * A wrapper implementation of Observer 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { newTextDecoder } from '../platform/text_serializer';\nimport { BundleMetadata } from '../protos/firestore_bundle_proto';\nimport { JsonProtoSerializer } from '../remote/serializer';\n\nimport { debugAssert } from './assert';\nimport { BundleReader, SizedBundleElement } from './bundle_reader';\nimport { Deferred } from './promise';\n\n/**\n * A class representing a bundle.\n *\n * Takes a bundle stream or buffer, and presents abstractions to read bundled\n * elements out of the underlying content.\n */\nclass BundleReaderImpl implements BundleReader {\n /** Cached bundle metadata. */\n private metadata: Deferred = new Deferred();\n /**\n * Internal buffer to hold bundle content, accumulating incomplete element\n * content.\n */\n private buffer: Uint8Array = new Uint8Array();\n /** The decoder used to parse binary data into strings. */\n private textDecoder: TextDecoder;\n\n constructor(\n /** The reader to read from underlying binary bundle data source. */\n private reader: ReadableStreamDefaultReader,\n readonly serializer: JsonProtoSerializer\n ) {\n this.textDecoder = newTextDecoder();\n // Read the metadata (which is the first element).\n this.nextElementImpl().then(\n element => {\n if (element && element.isBundleMetadata()) {\n this.metadata.resolve(element.payload.metadata!);\n } else {\n this.metadata.reject(\n new Error(`The first element of the bundle is not a metadata, it is\n ${JSON.stringify(element?.payload)}`)\n );\n }\n },\n error => this.metadata.reject(error)\n );\n }\n\n close(): Promise {\n return this.reader.cancel();\n }\n\n async getMetadata(): Promise {\n return this.metadata.promise;\n }\n\n async nextElement(): Promise {\n // Makes sure metadata is read before proceeding.\n await this.getMetadata();\n return this.nextElementImpl();\n }\n\n /**\n * Reads from the head of internal buffer, and pulling more data from\n * underlying stream if a complete element cannot be found, until an\n * element(including the prefixed length and the JSON string) is found.\n *\n * Once a complete element is read, it is dropped from internal buffer.\n *\n * Returns either the bundled element, or null if we have reached the end of\n * the stream.\n */\n private async nextElementImpl(): Promise {\n const lengthBuffer = await this.readLength();\n if (lengthBuffer === null) {\n return null;\n }\n\n const lengthString = this.textDecoder.decode(lengthBuffer);\n const length = Number(lengthString);\n if (isNaN(length)) {\n this.raiseError(`length string (${lengthString}) is not valid number`);\n }\n\n const jsonString = await this.readJsonString(length);\n\n return new SizedBundleElement(\n JSON.parse(jsonString),\n lengthBuffer.length + length\n );\n }\n\n /** First index of '{' from the underlying buffer. */\n private indexOfOpenBracket(): number {\n return this.buffer.findIndex(v => v === '{'.charCodeAt(0));\n }\n\n /**\n * Reads from the beginning of the internal buffer, until the first '{', and\n * return the content.\n *\n * If reached end of the stream, returns a null.\n */\n private async readLength(): Promise {\n while (this.indexOfOpenBracket() < 0) {\n const done = await this.pullMoreDataToBuffer();\n if (done) {\n break;\n }\n }\n\n // Broke out of the loop because underlying stream is closed, and there\n // happens to be no more data to process.\n if (this.buffer.length === 0) {\n return null;\n }\n\n const position = this.indexOfOpenBracket();\n // Broke out of the loop because underlying stream is closed, but still\n // cannot find an open bracket.\n if (position < 0) {\n this.raiseError(\n 'Reached the end of bundle when a length string is expected.'\n );\n }\n\n const result = this.buffer.slice(0, position);\n // Update the internal buffer to drop the read length.\n this.buffer = this.buffer.slice(position);\n return result;\n }\n\n /**\n * Reads from a specified position from the internal buffer, for a specified\n * number of bytes, pulling more data from the underlying stream if needed.\n *\n * Returns a string decoded from the read bytes.\n */\n private async readJsonString(length: number): Promise {\n while (this.buffer.length < length) {\n const done = await this.pullMoreDataToBuffer();\n if (done) {\n this.raiseError('Reached the end of bundle when more is expected.');\n }\n }\n\n const result = this.textDecoder.decode(this.buffer.slice(0, length));\n // Update the internal buffer to drop the read json string.\n this.buffer = this.buffer.slice(length);\n return result;\n }\n\n private raiseError(message: string): void {\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.reader.cancel();\n throw new Error(`Invalid bundle format: ${message}`);\n }\n\n /**\n * Pulls more data from underlying stream to internal buffer.\n * Returns a boolean indicating whether the stream is finished.\n */\n private async pullMoreDataToBuffer(): Promise {\n const result = await this.reader.read();\n if (!result.done) {\n debugAssert(!!result.value, 'Read undefined when \"done\" is false.');\n const newBuffer = new Uint8Array(\n this.buffer.length + result.value!.length\n );\n newBuffer.set(this.buffer);\n newBuffer.set(result.value!, this.buffer.length);\n this.buffer = newBuffer;\n }\n return result.done;\n }\n}\n\nexport function newBundleReader(\n reader: ReadableStreamDefaultReader,\n serializer: JsonProtoSerializer\n): BundleReader {\n return new BundleReaderImpl(reader, serializer);\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 } from '../protos/firestore_bundle_proto';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { BundleReaderSync, SizedBundleElement } from './bundle_reader';\n\n/**\n * A class that can parse a bundle form the string serialization of a bundle.\n */\nexport class BundleReaderSyncImpl implements BundleReaderSync {\n private metadata: BundleMetadata;\n private elements: SizedBundleElement[];\n private cursor: number;\n constructor(\n private bundleData: string,\n readonly serializer: JsonProtoSerializer\n ) {\n this.cursor = 0;\n this.elements = [];\n\n let element = this.nextElement();\n if (element && element.isBundleMetadata()) {\n this.metadata = element as BundleMetadata;\n } else {\n throw new Error(`The first element of the bundle is not a metadata object, it is\n ${JSON.stringify(element?.payload)}`);\n }\n\n do {\n element = this.nextElement();\n if (element !== null) {\n this.elements.push(element);\n }\n } while (element !== null);\n }\n\n /* Returns the parsed metadata of the bundle. */\n getMetadata(): BundleMetadata {\n return this.metadata;\n }\n\n /* Returns the DocumentSnapshot or NamedQuery elements of the bundle. */\n getElements(): SizedBundleElement[] {\n return this.elements;\n }\n\n /**\n * Parses the next element of the bundle.\n *\n * @returns a SizedBundleElement representation of the next element in the bundle, or null if\n * no more elements exist.\n */\n private nextElement(): SizedBundleElement | null {\n if (this.cursor === this.bundleData.length) {\n return null;\n }\n const length: number = this.readLength();\n const jsonString = this.readJsonString(length);\n return new SizedBundleElement(JSON.parse(jsonString), length);\n }\n\n /**\n * Reads from a specified position from the bundleData string, for a specified\n * number of bytes.\n *\n * @param length how many characters to read.\n * @returns a string parsed from the bundle.\n */\n private readJsonString(length: number): string {\n if (this.cursor + length > this.bundleData.length) {\n throw new FirestoreError(\n Code.INTERNAL,\n 'Reached the end of bundle when more is expected.'\n );\n }\n const result = this.bundleData.slice(this.cursor, (this.cursor += length));\n return result;\n }\n\n /**\n * Reads from the current cursor until the first '{'.\n *\n * @returns A string to integer represention of the parsed value.\n * @throws An {@link Error} if the cursor has reached the end of the stream, since lengths\n * prefix bundle objects.\n */\n private readLength(): number {\n const startIndex = this.cursor;\n let curIndex = this.cursor;\n while (curIndex < this.bundleData.length) {\n if (this.bundleData[curIndex] === '{') {\n if (curIndex === startIndex) {\n throw new Error('First character is a bracket and not a number');\n }\n this.cursor = curIndex;\n return Number(this.bundleData.slice(startIndex, curIndex));\n }\n curIndex++;\n }\n throw new Error('Reached the end of bundle when more is expected.');\n }\n}\n\n/**\n * Creates an instance of BundleReader without exposing the BundleReaderSyncImpl class type.\n */\nexport function newBundleReaderSync(\n bundleData: string,\n serializer: JsonProtoSerializer\n): BundleReaderSync {\n return new BundleReaderSyncImpl(bundleData, serializer);\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ParsedSetData, ParsedUpdateData } from '../lite-api/user_data_reader';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport {\n DeleteMutation,\n Mutation,\n Precondition,\n VerifyMutation\n} from '../model/mutation';\nimport {\n Datastore,\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc\n} from '../remote/datastore';\nimport { fail, debugAssert } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n\nimport { SnapshotVersion } from './snapshot_version';\n\n/**\n * Internal transaction object responsible for accumulating the mutations to\n * perform and the base versions for any documents read.\n */\nexport class Transaction {\n // The version of each document that was read during this transaction.\n private readVersions = new Map();\n private mutations: Mutation[] = [];\n private committed = false;\n\n /**\n * A deferred usage error that occurred previously in this transaction that\n * will cause the transaction to fail once it actually commits.\n */\n private lastTransactionError: FirestoreError | null = null;\n\n /**\n * Set of documents that have been written in the transaction.\n *\n * When there's more than one write to the same key in a transaction, any\n * writes after the first are handled differently.\n */\n private writtenDocs: Set = new Set();\n\n constructor(private datastore: Datastore) {}\n\n async lookup(keys: DocumentKey[]): Promise {\n this.ensureCommitNotCalled();\n\n if (this.mutations.length > 0) {\n this.lastTransactionError = new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Firestore transactions require all reads to be executed before all writes.'\n );\n throw this.lastTransactionError;\n }\n const docs = await invokeBatchGetDocumentsRpc(this.datastore, keys);\n docs.forEach(doc => this.recordVersion(doc));\n return docs;\n }\n\n set(key: DocumentKey, data: ParsedSetData): void {\n this.write(data.toMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n update(key: DocumentKey, data: ParsedUpdateData): void {\n try {\n this.write(data.toMutation(key, this.preconditionForUpdate(key)));\n } catch (e) {\n this.lastTransactionError = e as FirestoreError | null;\n }\n this.writtenDocs.add(key.toString());\n }\n\n delete(key: DocumentKey): void {\n this.write(new DeleteMutation(key, this.precondition(key)));\n this.writtenDocs.add(key.toString());\n }\n\n async commit(): Promise {\n this.ensureCommitNotCalled();\n\n if (this.lastTransactionError) {\n throw this.lastTransactionError;\n }\n const unwritten = this.readVersions;\n // For each mutation, note that the doc was written.\n this.mutations.forEach(mutation => {\n unwritten.delete(mutation.key.toString());\n });\n // For each document that was read but not written to, we want to perform\n // a `verify` operation.\n unwritten.forEach((_, path) => {\n const key = DocumentKey.fromPath(path);\n this.mutations.push(new VerifyMutation(key, this.precondition(key)));\n });\n await invokeCommitRpc(this.datastore, this.mutations);\n this.committed = true;\n }\n\n private recordVersion(doc: Document): void {\n let docVersion: SnapshotVersion;\n\n if (doc.isFoundDocument()) {\n docVersion = doc.version;\n } else if (doc.isNoDocument()) {\n // Represent a deleted doc using SnapshotVersion.min().\n docVersion = SnapshotVersion.min();\n } else {\n throw fail(0xc542, 'Document in a transaction was a ', {\n documentName: doc.constructor.name\n });\n }\n\n const existingVersion = this.readVersions.get(doc.key.toString());\n if (existingVersion) {\n if (!docVersion.isEqual(existingVersion)) {\n // This transaction will fail no matter what.\n throw new FirestoreError(\n Code.ABORTED,\n 'Document version changed between two reads.'\n );\n }\n } else {\n this.readVersions.set(doc.key.toString(), docVersion);\n }\n }\n\n /**\n * Returns the version of this document when it was read in this transaction,\n * as a precondition, or no precondition if it was not read.\n */\n private precondition(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n return Precondition.exists(false);\n } else {\n return Precondition.updateTime(version);\n }\n } else {\n return Precondition.none();\n }\n }\n\n /**\n * Returns the precondition for a document if the operation is an update.\n */\n private preconditionForUpdate(key: DocumentKey): Precondition {\n const version = this.readVersions.get(key.toString());\n // The first time a document is written, we want to take into account the\n // read time and existence\n if (!this.writtenDocs.has(key.toString()) && version) {\n if (version.isEqual(SnapshotVersion.min())) {\n // The document doesn't exist, so fail the transaction.\n\n // This has to be validated locally because you can't send a\n // precondition that a document does not exist without changing the\n // semantics of the backend write to be an insert. This is the reverse\n // of what we want, since we want to assert that the document doesn't\n // exist but then send the update and have it fail. Since we can't\n // express that to the backend, we have to validate locally.\n\n // Note: this can change once we can send separate verify writes in the\n // transaction.\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't update a document that doesn't exist.\"\n );\n }\n // Document exists, base precondition on document update time.\n return Precondition.updateTime(version);\n } else {\n // Document was not read, so we just use the preconditions for a blind\n // update.\n return Precondition.exists(true);\n }\n }\n\n private write(mutation: Mutation): void {\n this.ensureCommitNotCalled();\n this.mutations.push(mutation);\n }\n\n private ensureCommitNotCalled(): void {\n debugAssert(\n !this.committed,\n 'A transaction object cannot be used after its update callback has been invoked.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2019 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ExponentialBackoff } from '../remote/backoff';\nimport { Datastore } from '../remote/datastore';\nimport { isPermanentError } from '../remote/rpc_error';\nimport { AsyncQueue, TimerId } from '../util/async_queue';\nimport { FirestoreError } from '../util/error';\nimport { Deferred } from '../util/promise';\nimport { isNullOrUndefined } from '../util/types';\n\nimport { Transaction } from './transaction';\nimport { TransactionOptions } from './transaction_options';\n\n/**\n * TransactionRunner encapsulates the logic needed to run and retry transactions\n * with backoff.\n */\nexport class TransactionRunner {\n private attemptsRemaining: number;\n private backoff: ExponentialBackoff;\n\n constructor(\n private readonly asyncQueue: AsyncQueue,\n private readonly datastore: Datastore,\n private readonly options: TransactionOptions,\n private readonly updateFunction: (transaction: Transaction) => Promise,\n private readonly deferred: Deferred\n ) {\n this.attemptsRemaining = options.maxAttempts;\n this.backoff = new ExponentialBackoff(\n this.asyncQueue,\n TimerId.TransactionRetry\n );\n }\n\n /** Runs the transaction and sets the result on deferred. */\n run(): void {\n this.attemptsRemaining -= 1;\n this.runWithBackOff();\n }\n\n private runWithBackOff(): void {\n this.backoff.backoffAndRun(async () => {\n const transaction = new Transaction(this.datastore);\n const userPromise = this.tryRunUpdateFunction(transaction);\n if (userPromise) {\n userPromise\n .then(result => {\n this.asyncQueue.enqueueAndForget(() => {\n return transaction\n .commit()\n .then(() => {\n this.deferred.resolve(result);\n })\n .catch(commitError => {\n this.handleTransactionError(commitError);\n });\n });\n })\n .catch(userPromiseError => {\n this.handleTransactionError(userPromiseError);\n });\n }\n });\n }\n\n private tryRunUpdateFunction(transaction: Transaction): Promise | null {\n try {\n const userPromise = this.updateFunction(transaction);\n if (\n isNullOrUndefined(userPromise) ||\n !userPromise.catch ||\n !userPromise.then\n ) {\n this.deferred.reject(\n Error('Transaction callback must return a Promise')\n );\n return null;\n }\n return userPromise;\n } catch (error) {\n // Do not retry errors thrown by user provided updateFunction.\n this.deferred.reject(error as Error);\n return null;\n }\n }\n\n private handleTransactionError(error: Error): void {\n if (this.attemptsRemaining > 0 && this.isRetryableTransactionError(error)) {\n this.attemptsRemaining -= 1;\n this.asyncQueue.enqueueAndForget(() => {\n this.runWithBackOff();\n return Promise.resolve();\n });\n } else {\n this.deferred.reject(error);\n }\n }\n\n private isRetryableTransactionError(error: Error | undefined): boolean {\n if (error?.name === 'FirebaseError') {\n // In transactions, the backend will fail outdated reads with FAILED_PRECONDITION and\n // non-matching document versions with ABORTED. These errors should be retried.\n const code = (error as FirestoreError).code;\n return (\n code === 'aborted' ||\n code === 'failed-precondition' ||\n code === 'already-exists' ||\n !isPermanentError(code)\n );\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GetOptions } from '@firebase/firestore-types';\n\nimport { LoadBundleTask } from '../api/bundle';\nimport {\n CredentialChangeListener,\n CredentialsProvider\n} from '../api/credentials';\nimport { User } from '../auth/user';\nimport { LocalStore } from '../local/local_store';\nimport {\n localStoreConfigureFieldIndexes,\n localStoreDeleteAllFieldIndexes,\n localStoreExecuteQuery,\n localStoreGetNamedQuery,\n localStoreHandleUserChange,\n localStoreReadDocument,\n localStoreSetIndexAutoCreationEnabled\n} from '../local/local_store_impl';\nimport { Persistence } from '../local/persistence';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldIndex } from '../model/field_index';\nimport { Mutation } from '../model/mutation';\nimport { toByteStreamReader } from '../platform/byte_stream_reader';\nimport { newSerializer } from '../platform/serializer';\nimport { newTextEncoder } from '../platform/text_serializer';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { Datastore, invokeRunAggregationQueryRpc } from '../remote/datastore';\nimport {\n RemoteStore,\n remoteStoreDisableNetwork,\n remoteStoreEnableNetwork,\n remoteStoreHandleCredentialChange\n} from '../remote/remote_store';\nimport { JsonProtoSerializer } from '../remote/serializer';\nimport { debugAssert } from '../util/assert';\nimport { AsyncObserver } from '../util/async_observer';\nimport { AsyncQueue, wrapInUserErrorIfRecoverable } from '../util/async_queue';\nimport { BundleReader, BundleReaderSync } from '../util/bundle_reader';\nimport { newBundleReader } from '../util/bundle_reader_impl';\nimport { newBundleReaderSync } from '../util/bundle_reader_sync_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 LruGcMemoryOfflineComponentProvider,\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 LruGcMemoryOfflineComponentProvider(undefined)\n );\n }\n }\n\n return client._offlineComponents!;\n}\n\nexport async 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 createBundleReaderSync(\n bundleData: string,\n serializer: JsonProtoSerializer\n): BundleReaderSync {\n return newBundleReaderSync(bundleData, 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 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { BundleSource } from '../../util/bundle_reader';\nimport { toByteStreamReaderHelper } from '../../util/byte_stream';\n\n/**\n * On web, a `ReadableStream` is wrapped around by a `ByteStreamReader`.\n */\nexport function toByteStreamReader(\n source: BundleSource,\n bytesPerRead: number\n): ReadableStreamDefaultReader {\n if (source instanceof Uint8Array) {\n return toByteStreamReaderHelper(source, bytesPerRead);\n }\n if (source instanceof ArrayBuffer) {\n return toByteStreamReaderHelper(new Uint8Array(source), bytesPerRead);\n }\n if (source instanceof ReadableStream) {\n return source.getReader();\n }\n throw new Error(\n 'Source of `toByteStreamReader` has to be a ArrayBuffer or ReadableStream'\n );\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 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 settings.isUsingEmulator\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 { EmulatorMockTokenOptions } from '@firebase/util';\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 emulatorOptions?: { mockUserToken?: EmulatorMockTokenOptions | string };\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 readonly isUsingEmulator: boolean;\n\n // Can be a google-auth-library or gapi client.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n credentials?: any;\n\n constructor(settings: PrivateSettings) {\n if (settings.host === undefined) {\n if (settings.ssl !== undefined) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Can't provide ssl option if host option is not set\"\n );\n }\n this.host = DEFAULT_HOST;\n this.ssl = DEFAULT_SSL;\n } else {\n this.host = settings.host;\n this.ssl = settings.ssl ?? DEFAULT_SSL;\n }\n this.isUsingEmulator = settings.emulatorOptions !== undefined;\n\n this.credentials = settings.credentials;\n this.ignoreUndefinedProperties = !!settings.ignoreUndefinedProperties;\n this.localCache = settings.localCache;\n\n if (settings.cacheSizeBytes === undefined) {\n this.cacheSizeBytes = LRU_DEFAULT_CACHE_SIZE_BYTES;\n } else {\n if (\n settings.cacheSizeBytes !== LRU_COLLECTION_DISABLED &&\n settings.cacheSizeBytes < LRU_MINIMUM_CACHE_SIZE_BYTES\n ) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `cacheSizeBytes must be at least ${LRU_MINIMUM_CACHE_SIZE_BYTES}`\n );\n } else {\n this.cacheSizeBytes = settings.cacheSizeBytes;\n }\n }\n\n validateIsNotUsedTogether(\n 'experimentalForceLongPolling',\n settings.experimentalForceLongPolling,\n 'experimentalAutoDetectLongPolling',\n settings.experimentalAutoDetectLongPolling\n );\n\n this.experimentalForceLongPolling = !!settings.experimentalForceLongPolling;\n\n if (this.experimentalForceLongPolling) {\n this.experimentalAutoDetectLongPolling = false;\n } else if (settings.experimentalAutoDetectLongPolling === undefined) {\n this.experimentalAutoDetectLongPolling = DEFAULT_AUTO_DETECT_LONG_POLLING;\n } else {\n // For backwards compatibility, coerce the value to boolean even though\n // the TypeScript compiler has narrowed the type to boolean already.\n // noinspection PointlessBooleanExpressionJS\n this.experimentalAutoDetectLongPolling =\n !!settings.experimentalAutoDetectLongPolling;\n }\n\n this.experimentalLongPollingOptions = cloneLongPollingOptions(\n settings.experimentalLongPollingOptions ?? {}\n );\n validateLongPollingOptions(this.experimentalLongPollingOptions);\n\n this.useFetchStreams = !!settings.useFetchStreams;\n }\n\n isEqual(other: FirestoreSettingsImpl): boolean {\n return (\n this.host === other.host &&\n this.ssl === other.ssl &&\n this.credentials === other.credentials &&\n this.cacheSizeBytes === other.cacheSizeBytes &&\n this.experimentalForceLongPolling ===\n other.experimentalForceLongPolling &&\n this.experimentalAutoDetectLongPolling ===\n other.experimentalAutoDetectLongPolling &&\n longPollingOptionsEqual(\n this.experimentalLongPollingOptions,\n other.experimentalLongPollingOptions\n ) &&\n this.ignoreUndefinedProperties === other.ignoreUndefinedProperties &&\n this.useFetchStreams === other.useFetchStreams\n );\n }\n}\n\nfunction validateLongPollingOptions(\n options: ExperimentalLongPollingOptions\n): void {\n if (options.timeoutSeconds !== undefined) {\n if (isNaN(options.timeoutSeconds)) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ` +\n `${options.timeoutSeconds} (must not be NaN)`\n );\n }\n if (options.timeoutSeconds < MIN_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(minimum allowed value is ${MIN_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n if (options.timeoutSeconds > MAX_LONG_POLLING_TIMEOUT_SECONDS) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `invalid long polling timeout: ${options.timeoutSeconds} ` +\n `(maximum allowed value is ${MAX_LONG_POLLING_TIMEOUT_SECONDS})`\n );\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// eslint-disable-next-line import/no-extraneous-dependencies\nimport {\n _getProvider,\n _removeServiceInstance,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport {\n createMockUserToken,\n deepEqual,\n EmulatorMockTokenOptions,\n getDefaultEmulatorHostnameAndPort,\n isCloudWorkstation,\n pingServer,\n updateEmulatorBanner\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 private _emulatorOptions: {\n mockUserToken?: EmulatorMockTokenOptions | string;\n } = {};\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 this._emulatorOptions = settings.emulatorOptions || {};\n\n if (settings.credentials !== undefined) {\n this._authCredentials = makeAuthCredentialsProvider(settings.credentials);\n }\n }\n\n _getSettings(): FirestoreSettingsImpl {\n return this._settings;\n }\n\n _getEmulatorOptions(): { mockUserToken?: EmulatorMockTokenOptions | string } {\n return this._emulatorOptions;\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 useSsl = isCloudWorkstation(host);\n const settings = firestore._getSettings();\n const existingConfig = {\n ...settings,\n emulatorOptions: firestore._getEmulatorOptions()\n };\n const newHostSetting = `${host}:${port}`;\n if (useSsl) {\n void pingServer(`https://${newHostSetting}`);\n updateEmulatorBanner('Firestore', true);\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 const newConfig = {\n ...settings,\n host: newHostSetting,\n ssl: useSsl,\n emulatorOptions: options\n };\n // No-op if the new configuration matches the current configuration. This supports SSR\n // enviornments which might call `connectFirestoreEmulator` multiple times as a standard practice.\n if (deepEqual(newConfig, existingConfig)) {\n return;\n }\n\n firestore._setSettings(newConfig);\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';\n// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_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 static _jsonSchemaVersion: string = 'firestore/documentReference/1.0';\n static _jsonSchema = {\n type: property('string', DocumentReference._jsonSchemaVersion),\n referencePath: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `DocumentReference` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: DocumentReference._jsonSchemaVersion,\n referencePath: this._key.toString()\n };\n }\n\n /**\n * Builds a `DocumentReference` instance from a JSON object created by\n * {@link DocumentReference.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json a JSON object represention of a `DocumentReference` instance\n * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(firestore: Firestore, json: object): DocumentReference;\n /**\n * Builds a `DocumentReference` instance from a JSON object created by\n * {@link DocumentReference.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json a JSON object represention of a `DocumentReference` instance\n * @param converter - Converts objects to and from Firestore.\n * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON<\n NewAppModelType = DocumentData,\n NewDbModelType extends DocumentData = DocumentData\n >(\n firestore: Firestore,\n json: object,\n converter: FirestoreDataConverter\n ): DocumentReference;\n static fromJSON<\n NewAppModelType = DocumentData,\n NewDbModelType extends DocumentData = DocumentData\n >(\n firestore: Firestore,\n json: object,\n converter?: FirestoreDataConverter\n ): DocumentReference {\n if (validateJSON(json, DocumentReference._jsonSchema)) {\n return new DocumentReference(\n firestore,\n converter ? converter : null,\n new DocumentKey(ResourcePath.fromString(json.referencePath))\n );\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Bytes from JSON.'\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(0xb815, 'AsyncQueue is already failed', {\n messageOrStack: getMessageOrStack(this.failure)\n });\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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { JsonObject } from '../model/object_value';\nimport { FirestoreError } from '../util/error';\n\n/**\n * Observer/Subscribe interfaces.\n */\nexport type NextFn = (value: T) => void;\nexport type ErrorFn = (error: FirestoreError) => void;\nexport type CompleteFn = () => void;\n\n// Allow for any of the Observer methods to be undefined.\nexport interface PartialObserver {\n next?: NextFn;\n error?: ErrorFn;\n complete?: CompleteFn;\n}\n\nexport function isPartialObserver(obj: unknown): obj is PartialObserver {\n return implementsAnyMethods(obj, ['next', 'error', 'complete']);\n}\n\n/**\n * Returns true if obj is an object and contains at least one of the specified\n * methods.\n */\nfunction implementsAnyMethods(obj: unknown, methods: string[]): boolean {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n\n const object = obj as JsonObject;\n for (const method of methods) {\n if (method in object && typeof object[method] === 'function') {\n return true;\n }\n }\n return false;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PartialObserver } from '../api/observer';\nimport { debugAssert } from '../util/assert';\nimport { FirestoreError } from '../util/error';\nimport { Deferred } from '../util/promise';\n\n/**\n * Represents the state of bundle loading tasks.\n *\n * Both 'Error' and 'Success' are sinking state: task will abort or complete and there will\n * be no more updates after they are reported.\n */\nexport type TaskState = 'Error' | 'Running' | 'Success';\n\n/**\n * Represents a progress update or a final state from loading bundles.\n */\nexport interface LoadBundleTaskProgress {\n /** How many documents have been loaded. */\n documentsLoaded: number;\n /** How many documents are in the bundle being loaded. */\n totalDocuments: number;\n /** How many bytes have been loaded. */\n bytesLoaded: number;\n /** How many bytes are in the bundle being loaded. */\n totalBytes: number;\n /** Current task state. */\n taskState: TaskState;\n}\n\n/**\n * Represents the task of loading a Firestore bundle. It provides progress of bundle\n * loading, as well as task completion and error events.\n *\n * The API is compatible with `Promise`.\n */\nexport class LoadBundleTask implements PromiseLike {\n private _progressObserver: PartialObserver = {};\n private _taskCompletionResolver = new Deferred();\n\n private _lastProgress: LoadBundleTaskProgress = {\n taskState: 'Running',\n totalBytes: 0,\n totalDocuments: 0,\n bytesLoaded: 0,\n documentsLoaded: 0\n };\n\n /**\n * Registers functions to listen to bundle loading progress events.\n * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur\n * each time a Firestore document is loaded from the bundle.\n * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the\n * error, and there should be no more updates after this.\n * @param complete - Called when the loading task is complete.\n */\n onProgress(\n next?: (progress: LoadBundleTaskProgress) => unknown,\n error?: (err: Error) => unknown,\n complete?: () => void\n ): void {\n this._progressObserver = {\n next,\n error,\n complete\n };\n }\n\n /**\n * Implements the `Promise.catch` interface.\n *\n * @param onRejected - Called when an error occurs during bundle loading.\n */\n catch(\n onRejected: (a: Error) => R | PromiseLike\n ): Promise {\n return this._taskCompletionResolver.promise.catch(onRejected);\n }\n\n /**\n * Implements the `Promise.then` interface.\n *\n * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update.\n * The update will always have its `taskState` set to `\"Success\"`.\n * @param onRejected - Called when an error occurs during bundle loading.\n */\n then(\n onFulfilled?: (a: LoadBundleTaskProgress) => T | PromiseLike,\n onRejected?: (a: Error) => R | PromiseLike\n ): Promise {\n return this._taskCompletionResolver.promise.then(onFulfilled, onRejected);\n }\n\n /**\n * Notifies all observers that bundle loading has completed, with a provided\n * `LoadBundleTaskProgress` object.\n *\n * @private\n */\n _completeWith(progress: LoadBundleTaskProgress): void {\n debugAssert(\n progress.taskState === 'Success',\n 'Task is not completed with Success.'\n );\n this._updateProgress(progress);\n if (this._progressObserver.complete) {\n this._progressObserver.complete();\n }\n\n this._taskCompletionResolver.resolve(progress);\n }\n\n /**\n * Notifies all observers that bundle loading has failed, with a provided\n * `Error` as the reason.\n *\n * @private\n */\n _failWith(error: FirestoreError): void {\n this._lastProgress.taskState = 'Error';\n\n if (this._progressObserver.next) {\n this._progressObserver.next(this._lastProgress);\n }\n\n if (this._progressObserver.error) {\n this._progressObserver.error(error);\n }\n\n this._taskCompletionResolver.reject(error);\n }\n\n /**\n * Notifies a progress update of loading a bundle.\n * @param progress - The new progress.\n *\n * @private\n */\n _updateProgress(progress: LoadBundleTaskProgress): void {\n debugAssert(\n this._lastProgress.taskState === 'Running',\n 'Cannot update progress on a completed or failed task'\n );\n\n this._lastProgress = progress;\n if (this._progressObserver.next) {\n this._progressObserver.next(progress);\n }\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n _getProvider,\n _removeServiceInstance,\n FirebaseApp,\n getApp\n} from '@firebase/app';\nimport {\n deepEqual,\n getDefaultEmulatorHostnameAndPort,\n isCloudWorkstation,\n pingServer\n} 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 // Workaround to get cookies in Firebase Studio\n if (settings.host && isCloudWorkstation(settings.host)) {\n void pingServer(settings.host);\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 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 { AggregateType } from '../core/aggregate';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\n\nimport { average, count, sum } from './aggregate';\nimport { DocumentData, Query } from './reference';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\nexport { AggregateType };\n\n/**\n * Represents an aggregation that can be performed by Firestore.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport class AggregateField {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateField';\n\n /** Indicates the aggregation operation of this AggregateField. */\n readonly aggregateType: AggregateType;\n\n /**\n * Create a new AggregateField\n * @param aggregateType Specifies the type of aggregation operation to perform.\n * @param _internalFieldPath Optionally specifies the field that is aggregated.\n * @internal\n */\n constructor(\n aggregateType: AggregateType = 'count',\n readonly _internalFieldPath?: InternalFieldPath\n ) {\n this.aggregateType = aggregateType;\n }\n}\n\n/**\n * The union of all `AggregateField` types that are supported by Firestore.\n */\nexport type AggregateFieldType =\n | ReturnType\n | ReturnType\n | ReturnType;\n\n/**\n * Specifies a set of aggregations and their aliases.\n */\nexport interface AggregateSpec {\n [field: string]: AggregateFieldType;\n}\n\n/**\n * A type whose keys are taken from an `AggregateSpec`, and whose values are the\n * result of the aggregation performed by the corresponding `AggregateField`\n * from the input `AggregateSpec`.\n */\nexport type AggregateSpecData = {\n [P in keyof T]: T[P] extends AggregateField ? U : never;\n};\n\n/**\n * The results of executing an aggregation query.\n */\nexport class AggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType = DocumentData,\n DbModelType extends DocumentData = DocumentData\n> {\n /** A type string to uniquely identify instances of this class. */\n readonly type = 'AggregateQuerySnapshot';\n\n /**\n * The underlying query over which the aggregations recorded in this\n * `AggregateQuerySnapshot` were performed.\n */\n readonly query: Query;\n\n /** @hideconstructor */\n constructor(\n query: Query,\n private readonly _userDataWriter: AbstractUserDataWriter,\n private readonly _data: ApiClientObjectMap\n ) {\n this.query = query;\n }\n\n /**\n * Returns the results of the aggregations performed over the underlying\n * query.\n *\n * The keys of the returned object will be the same as those of the\n * `AggregateSpec` object specified to the aggregation method, and the values\n * will be the corresponding aggregation result.\n *\n * @returns The results of the aggregations performed over the underlying\n * query.\n */\n data(): AggregateSpecData {\n return this._userDataWriter.convertObjectMap(\n this._data\n ) as AggregateSpecData;\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// API extractor fails importing property unless we also explicitly import Property.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\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 static _jsonSchemaVersion: string = 'firestore/bytes/1.0';\n static _jsonSchema = {\n type: property('string', Bytes._jsonSchemaVersion),\n bytes: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `Bytes` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: Bytes._jsonSchemaVersion,\n bytes: this.toBase64()\n };\n }\n\n /**\n * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}.\n *\n * @param json a JSON object represention of a `Bytes` instance\n * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): Bytes {\n if (validateJSON(json, Bytes._jsonSchema)) {\n return Bytes.fromBase64String(json.bytes);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Bytes from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n 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';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\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 /**\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 static _jsonSchemaVersion: string = 'firestore/geoPoint/1.0';\n static _jsonSchema = {\n type: property('string', GeoPoint._jsonSchemaVersion),\n latitude: property('number'),\n longitude: property('number')\n };\n\n /**\n * Returns a JSON-serializable representation of this `GeoPoint` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): { latitude: number; longitude: number; type: string } {\n return {\n latitude: this._lat,\n longitude: this._long,\n type: GeoPoint._jsonSchemaVersion\n };\n }\n\n /**\n * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}.\n *\n * @param json a JSON object represention of a `GeoPoint` instance\n * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): GeoPoint {\n if (validateJSON(json, GeoPoint._jsonSchema)) {\n return new GeoPoint(json.latitude, json.longitude);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating GeoPoint from JSON.'\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';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\n\n/**\n * Represents a vector type in Firestore documents.\n * Create an instance with {@link 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` values have the same raw number arrays, returns `false` otherwise.\n */\n isEqual(other: VectorValue): boolean {\n return isPrimitiveArrayEqual(this._values, other._values);\n }\n\n static _jsonSchemaVersion: string = 'firestore/vectorValue/1.0';\n static _jsonSchema = {\n type: property('string', VectorValue._jsonSchemaVersion),\n vectorValues: property('object')\n };\n\n /**\n * Returns a JSON-serializable representation of this `VectorValue` instance.\n *\n * @returns a JSON representation of this object.\n */\n toJSON(): object {\n return {\n type: VectorValue._jsonSchemaVersion,\n vectorValues: this._values\n };\n }\n\n /**\n * Builds a `VectorValue` instance from a JSON object created by {@link VectorValue.toJSON}.\n *\n * @param json a JSON object represention of a `VectorValue` instance.\n * @returns an instance of {@link VectorValue} if the JSON object could be parsed. Throws a\n * {@link FirestoreError} if an error occurs.\n */\n static fromJSON(json: object): VectorValue {\n if (validateJSON(json, VectorValue._jsonSchema)) {\n if (\n Array.isArray(json.vectorValues) &&\n json.vectorValues.every(element => typeof element === 'number')\n ) {\n return new VectorValue(json.vectorValues);\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n \"Expected 'vectorValues' field to be a number array\"\n );\n }\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Unexpected error creating Timestamp from JSON.'\n );\n }\n}\n","/**\n * @license\n * Copyright 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData,\n FieldPath as PublicFieldPath,\n SetOptions\n} from '@firebase/firestore-types';\nimport { Compat, deepEqual, getModularInstance } from '@firebase/util';\n\nimport { ParseContext } from '../api/parse_context';\nimport { DatabaseId } from '../core/database_info';\nimport { DocumentKey } from '../model/document_key';\nimport { FieldMask } from '../model/field_mask';\nimport {\n FieldTransform,\n Mutation,\n PatchMutation,\n Precondition,\n SetMutation\n} from '../model/mutation';\nimport { ObjectValue } from '../model/object_value';\nimport { FieldPath as InternalFieldPath } from '../model/path';\nimport {\n ArrayRemoveTransformOperation,\n ArrayUnionTransformOperation,\n NumericIncrementTransformOperation,\n ServerTimestampTransform\n} from '../model/transform_operation';\nimport {\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(0x9c4b, 'Unexpected case for UserDataSource', {\n dataSource\n });\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\nexport function 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(0xf2a2, 'Invalid value type', {\n value\n });\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 0x25d8,\n 'ReferenceValue is not valid',\n { name }\n );\n const databaseId = new DatabaseId(resourcePath.get(1), resourcePath.get(3));\n const key = new DocumentKey(resourcePath.popFirst(5));\n\n if (!databaseId.isEqual(expectedDatabaseId)) {\n // TODO(b/64130202): Somehow support foreign references.\n logError(\n `Document ${key} contains a document ` +\n `reference within a different database (` +\n `${databaseId.projectId}/${databaseId.database}) which is not ` +\n `supported. It will be treated as a reference in the current ` +\n `database (${expectedDatabaseId.projectId}/${expectedDatabaseId.database}) ` +\n `instead.`\n );\n }\n return key;\n }\n\n protected abstract convertReference(name: string): unknown;\n\n protected abstract convertBytes(bytes: ByteString): unknown;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n DocumentData as PublicDocumentData,\n SetOptions as PublicSetOptions\n} from '@firebase/firestore-types';\nimport { getModularInstance } from '@firebase/util';\n\nimport { LimitType } from '../core/query';\nimport { DeleteMutation, Precondition } from '../model/mutation';\nimport {\n invokeBatchGetDocumentsRpc,\n invokeCommitRpc,\n invokeRunQueryRpc\n} from '../remote/datastore';\nimport { hardAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { cast } from '../util/input_validation';\n\nimport { Bytes } from './bytes';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { validateHasExplicitOrderByForLimitToLast } from './query';\nimport {\n CollectionReference,\n doc,\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n Query,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n DocumentSnapshot,\n QueryDocumentSnapshot,\n QuerySnapshot\n} from './snapshot';\nimport {\n newUserDataReader,\n ParsedUpdateData,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UntypedFirestoreDataConverter\n} from './user_data_reader';\nimport { AbstractUserDataWriter } from './user_data_writer';\n\n/**\n * Converts custom model object of type T into `DocumentData` by applying the\n * converter if it exists.\n *\n * This function is used when converting user objects to `DocumentData`\n * because we want to provide the user with a more specific error message if\n * their `set()` or fails due to invalid data originating from a `toFirestore()`\n * call.\n */\nexport function applyFirestoreDataConverter(\n converter: UntypedFirestoreDataConverter | null,\n value: WithFieldValue | PartialWithFieldValue,\n options?: PublicSetOptions\n): PublicDocumentData {\n let convertedValue;\n if (converter) {\n if (options && (options.merge || options.mergeFields)) {\n // Cast to `any` in order to satisfy the union type constraint on\n // toFirestore().\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n convertedValue = (converter as any).toFirestore(value, options);\n } else {\n convertedValue = converter.toFirestore(value as WithFieldValue);\n }\n } else {\n convertedValue = value as PublicDocumentData;\n }\n return convertedValue;\n}\n\nexport class LiteUserDataWriter extends AbstractUserDataWriter {\n constructor(protected firestore: Firestore) {\n super();\n }\n\n protected convertBytes(bytes: ByteString): Bytes {\n return new Bytes(bytes);\n }\n\n protected convertReference(name: string): DocumentReference {\n const key = this.convertDocumentKey(name, this.firestore._databaseId);\n return new DocumentReference(this.firestore, /* converter= */ null, key);\n }\n}\n\n/**\n * Reads the document referred to by the specified document reference.\n *\n * All documents are directly fetched from the server, even if the document was\n * previously read or modified. Recent modifications are only reflected in the\n * retrieved `DocumentSnapshot` if they have already been applied by the\n * backend. If the client is offline, the read fails. If you like to use\n * caching or see local modifications, please use the full Firestore SDK.\n *\n * @param reference - The reference of the document to fetch.\n * @returns A Promise resolved with a `DocumentSnapshot` containing the current\n * document contents.\n */\nexport function getDoc(\n reference: DocumentReference\n): Promise> {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n const userDataWriter = new LiteUserDataWriter(reference.firestore);\n\n return invokeBatchGetDocumentsRpc(datastore, [reference._key]).then(\n result => {\n hardAssert(\n result.length === 1,\n 0x3d02,\n 'Expected a single document result'\n );\n const document = result[0];\n return new DocumentSnapshot(\n reference.firestore,\n userDataWriter,\n reference._key,\n document.isFoundDocument() ? document : null,\n reference.converter\n );\n }\n );\n}\n\n/**\n * Executes the query and returns the results as a {@link QuerySnapshot}.\n *\n * All queries are executed directly by the server, even if the query was\n * previously executed. Recent modifications are only reflected in the retrieved\n * results if they have already been applied by the backend. If the client is\n * offline, the operation fails. To see previously cached result and local\n * modifications, use the full Firestore SDK.\n *\n * @param query - The `Query` to execute.\n * @returns A Promise that will be resolved with the results of the query.\n */\nexport function getDocs(\n query: Query\n): Promise> {\n query = cast>(query, Query);\n validateHasExplicitOrderByForLimitToLast(query._query);\n\n const datastore = getDatastore(query.firestore);\n const userDataWriter = new LiteUserDataWriter(query.firestore);\n return invokeRunQueryRpc(datastore, query._query).then(result => {\n const docs = result.map(\n doc =>\n new QueryDocumentSnapshot(\n query.firestore,\n userDataWriter,\n doc.key,\n doc,\n query.converter\n )\n );\n\n if (query._query.limitType === LimitType.Last) {\n // Limit to last queries reverse the orderBy constraint that was\n // specified by the user. As such, we need to reverse the order of the\n // results to return the documents in the expected order.\n docs.reverse();\n }\n\n return new QuerySnapshot(query, docs);\n });\n}\n\n/**\n * Writes to the document referred to by the specified `DocumentReference`. If\n * the document does not yet exist, it will be created.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\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 * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to write.\n * @param data - A map of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function setDoc(\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 convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data,\n options\n );\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'setDoc',\n reference._key,\n convertedValue,\n reference.converter !== null,\n options\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Updates fields in the document referred to by the specified\n * `DocumentReference`. The update will fail if applied to a document that does\n * not exist.\n *\n * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\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 * The result of this update will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * update fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to update.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns A `Promise` resolved once the data has been successfully written\n * to the backend.\n */\nexport function updateDoc(\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 dataReader = newUserDataReader(reference.firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed: ParsedUpdateData;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n dataReader,\n 'updateDoc',\n reference._key,\n fieldOrUpdateData\n );\n }\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(reference._key, Precondition.exists(true))\n ]);\n}\n\n/**\n * Deletes the document referred to by the specified `DocumentReference`.\n *\n * The deletion will only be reflected in document reads that occur after the\n * returned promise resolves. If the client is offline, the\n * delete fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the document to delete.\n * @returns A `Promise` resolved once the document has been successfully\n * deleted from the backend.\n */\nexport function deleteDoc(\n reference: DocumentReference\n): Promise {\n reference = cast>(\n reference,\n DocumentReference\n );\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n new DeleteMutation(reference._key, Precondition.none())\n ]);\n}\n\n/**\n * Add a new document to specified `CollectionReference` with the given data,\n * assigning it a document ID automatically.\n *\n * The result of this write will only be reflected in document reads that occur\n * after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @param reference - A reference to the collection to add this document to.\n * @param data - An Object containing the data for the new document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns A `Promise` resolved with a `DocumentReference` pointing to the\n * newly created document after it has been written to the backend.\n */\nexport function addDoc(\n reference: CollectionReference,\n data: WithFieldValue\n): Promise> {\n reference = cast>(\n reference,\n CollectionReference\n );\n const docRef = doc(reference);\n\n const convertedValue = applyFirestoreDataConverter(\n reference.converter,\n data as PartialWithFieldValue\n );\n\n const dataReader = newUserDataReader(reference.firestore);\n const parsed = parseSetData(\n dataReader,\n 'addDoc',\n docRef._key,\n convertedValue,\n docRef.converter !== null,\n {}\n );\n\n const datastore = getDatastore(reference.firestore);\n return invokeCommitRpc(datastore, [\n parsed.toMutation(docRef._key, Precondition.exists(false))\n ]).then(() => docRef);\n}\n","/**\n * @license\n * Copyright 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 { deepEqual } from '@firebase/util';\n\nimport { AggregateImpl } from '../core/aggregate';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { invokeRunAggregationQueryRpc } from '../remote/datastore';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport {\n AggregateField,\n AggregateQuerySnapshot,\n AggregateSpec\n} from './aggregate_types';\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport { DocumentData, Query, queryEqual } from './reference';\nimport { LiteUserDataWriter } from './reference_impl';\nimport { fieldPathFromArgument } from './user_data_reader';\n\n/**\n * Calculates the number of documents in the result set of the given query\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can\n * count the documents in cases where the result set is prohibitively large to\n * download entirely (thousands of documents).\n *\n * @param query The query whose result set size is calculated.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */\nexport function getCount(\n query: Query\n): Promise<\n AggregateQuerySnapshot<\n { count: AggregateField },\n AppModelType,\n DbModelType\n >\n> {\n const countQuerySpec: { count: AggregateField } = {\n count: count()\n };\n\n return getAggregate(query, countQuerySpec);\n}\n\n/**\n * Calculates the specified aggregations over the documents in the result\n * set of the given query without actually downloading the documents.\n *\n * Using this function to perform aggregations is efficient because only the\n * final aggregation values, not the documents' data, are downloaded. This\n * function can perform aggregations of the documents in cases where the result\n * set is prohibitively large to download entirely (thousands of documents).\n *\n * @param query The query whose result set is aggregated over.\n * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates\n * to perform over the result set. The AggregateSpec specifies aliases for each\n * aggregate, which can be used to retrieve the aggregate result.\n * @example\n * ```typescript\n * const aggregateSnapshot = await getAggregate(query, {\n * countOfDocs: count(),\n * totalHours: sum('hours'),\n * averageScore: average('score')\n * });\n *\n * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;\n * const totalHours: number = aggregateSnapshot.data().totalHours;\n * const averageScore: number | null = aggregateSnapshot.data().averageScore;\n * ```\n */\nexport function getAggregate<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n aggregateSpec: AggregateSpecType\n): Promise<\n AggregateQuerySnapshot\n> {\n const firestore = cast(query.firestore, Firestore);\n const datastore = getDatastore(firestore);\n\n const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n\n // Run the aggregation and convert the results\n return invokeRunAggregationQueryRpc(\n datastore,\n query._query,\n internalAggregates\n ).then(aggregateResult =>\n convertToAggregateQuerySnapshot(firestore, query, aggregateResult)\n );\n}\n\nfunction convertToAggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n query: Query,\n aggregateResult: ApiClientObjectMap\n): AggregateQuerySnapshot {\n const userDataWriter = new LiteUserDataWriter(firestore);\n const querySnapshot = new AggregateQuerySnapshot<\n AggregateSpecType,\n AppModelType,\n DbModelType\n >(query, userDataWriter, aggregateResult);\n return querySnapshot;\n}\n\n/**\n * Create an AggregateField object that can be used to compute the sum of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to sum across the result set.\n */\nexport function sum(field: string | FieldPath): AggregateField {\n return new AggregateField('sum', fieldPathFromArgument('sum', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the average of\n * a specified field over a range of documents in the result set of a query.\n * @param field Specifies the field to average across the result set.\n */\nexport function average(\n field: string | FieldPath\n): AggregateField {\n return new AggregateField('avg', fieldPathFromArgument('average', field));\n}\n\n/**\n * Create an AggregateField object that can be used to compute the count of\n * documents in the result set of a query.\n */\nexport function count(): AggregateField {\n return new AggregateField('count');\n}\n\n/**\n * Compares two 'AggregateField` instances for equality.\n *\n * @param left Compare this AggregateField to the `right`.\n * @param right Compare this AggregateField to the `left`.\n */\nexport function aggregateFieldEqual(\n left: AggregateField,\n right: AggregateField\n): boolean {\n return (\n left instanceof AggregateField &&\n right instanceof AggregateField &&\n left.aggregateType === right.aggregateType &&\n left._internalFieldPath?.canonicalString() ===\n right._internalFieldPath?.canonicalString()\n );\n}\n\n/**\n * Compares two `AggregateQuerySnapshot` instances for equality.\n *\n * Two `AggregateQuerySnapshot` instances are considered \"equal\" if they have\n * underlying queries that compare equal, and the same data.\n *\n * @param left - The first `AggregateQuerySnapshot` to compare.\n * @param right - The second `AggregateQuerySnapshot` to compare.\n *\n * @returns `true` if the objects are \"equal\", as defined above, or `false`\n * otherwise.\n */\nexport function aggregateQuerySnapshotEqual<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n left: AggregateQuerySnapshot,\n right: AggregateQuerySnapshot\n): boolean {\n return (\n queryEqual(left.query, right.query) && deepEqual(left.data(), right.data())\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 { BundleLoader } from '../core/bundle_impl';\nimport { createBundleReaderSync } from '../core/firestore_client';\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 { LiteUserDataWriter } from '../lite-api/reference_impl';\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 { fromBundledQuery } from '../local/local_serializer';\nimport { documentKeySet } from '../model/collections';\nimport { Document } from '../model/document';\nimport { DocumentKey } from '../model/document_key';\nimport { DocumentSet } from '../model/document_set';\nimport { ResourcePath } from '../model/path';\nimport { newSerializer } from '../platform/serializer';\nimport {\n buildQuerySnapshotJsonBundle,\n buildDocumentSnapshotJsonBundle\n} from '../platform/snapshot_to_json';\nimport { fromDocument } from '../remote/serializer';\nimport { debugAssert, fail } from '../util/assert';\nimport { Code, FirestoreError } from '../util/error';\n// API extractor fails importing 'property' unless we also explicitly import 'Property'.\n// eslint-disable-next-line @typescript-eslint/no-unused-vars, unused-imports/no-unused-imports-ts\nimport { Property, property, validateJSON } from '../util/json_validation';\nimport { AutoId } from '../util/misc';\n\nimport { Firestore } from './database';\nimport { SnapshotListenOptions } from './reference_impl';\n\nconst NOT_SUPPORTED = 'NOT SUPPORTED';\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 static _jsonSchemaVersion: string = 'firestore/documentSnapshot/1.0';\n static _jsonSchema = {\n type: property('string', DocumentSnapshot._jsonSchemaVersion),\n bundleSource: property('string', 'DocumentSnapshot'),\n bundleName: property('string'),\n bundle: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `DocumentSnapshot` instance.\n *\n * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this\n * `DocumentSnapshot` has pending writes.\n */\n toJSON(): object {\n if (this.metadata.hasPendingWrites) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'DocumentSnapshot.toJSON() attempted to serialize a document with pending writes. ' +\n 'Await waitForPendingWrites() before invoking toJSON().'\n );\n }\n const document = this._document;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: any = {};\n result['type'] = DocumentSnapshot._jsonSchemaVersion;\n result['bundle'] = '';\n result['bundleSource'] = 'DocumentSnapshot';\n result['bundleName'] = this._key.toString();\n\n if (\n !document ||\n !document.isValidDocument() ||\n !document.isFoundDocument()\n ) {\n return result;\n }\n const documentData = this._userDataWriter.convertObjectMap(\n document.data.value.mapValue.fields,\n 'previous'\n );\n result['bundle'] = buildDocumentSnapshotJsonBundle(\n this._firestore,\n document,\n documentData,\n this.ref.path\n );\n return result;\n }\n}\n\n/**\n * Builds a `DocumentSnapshot` instance from a JSON object created by\n * {@link DocumentSnapshot.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json - a JSON object represention of a `DocumentSnapshot` instance.\n * @returns an instance of {@link DocumentSnapshot} if the JSON object could be\n * parsed. Throws a {@link FirestoreError} if an error occurs.\n */\nexport function documentSnapshotFromJSON(\n db: Firestore,\n json: object\n): DocumentSnapshot;\n/**\n * Builds a `DocumentSnapshot` instance from a JSON object created by\n * {@link DocumentSnapshot.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json - a JSON object represention of a `DocumentSnapshot` instance.\n * @param converter - Converts objects to and from Firestore.\n * @returns an instance of {@link DocumentSnapshot} if the JSON object could be\n * parsed. Throws a {@link FirestoreError} if an error occurs.\n */\nexport function documentSnapshotFromJSON<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n>(\n db: Firestore,\n json: object,\n converter: FirestoreDataConverter\n): DocumentSnapshot;\nexport function documentSnapshotFromJSON<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n>(\n db: Firestore,\n json: object,\n converter?: FirestoreDataConverter\n): DocumentSnapshot {\n if (validateJSON(json, DocumentSnapshot._jsonSchema)) {\n if (json.bundle === NOT_SUPPORTED) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'The provided JSON object was created in a client environment, which is not supported.'\n );\n }\n // Parse the bundle data.\n const serializer = newSerializer(db._databaseId);\n const bundleReader = createBundleReaderSync(json.bundle, serializer);\n const elements = bundleReader.getElements();\n const bundleLoader: BundleLoader = new BundleLoader(\n bundleReader.getMetadata(),\n serializer\n );\n for (const element of elements) {\n bundleLoader.addSizedElement(element);\n }\n\n // Ensure that we have the correct number of documents in the bundle.\n const bundledDocuments = bundleLoader.documents;\n if (bundledDocuments.length !== 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Expected bundle data to contain 1 document, but it contains ${bundledDocuments.length} documents.`\n );\n }\n\n // Build out the internal document data.\n const document = fromDocument(serializer, bundledDocuments[0].document!);\n const documentKey = new DocumentKey(\n ResourcePath.fromString(json.bundleName)\n );\n\n // Return the external facing DocumentSnapshot.\n return new DocumentSnapshot(\n db,\n new LiteUserDataWriter(db),\n documentKey,\n document,\n new SnapshotMetadata(\n /* hasPendingWrites= */ false,\n /* fromCache= */ false\n ),\n converter ? converter : null\n );\n }\n throw new FirestoreError(\n Code.INTERNAL,\n 'Unexpected error creating DocumentSnapshot from JSON.'\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 static _jsonSchemaVersion: string = 'firestore/querySnapshot/1.0';\n static _jsonSchema = {\n type: property('string', QuerySnapshot._jsonSchemaVersion),\n bundleSource: property('string', 'QuerySnapshot'),\n bundleName: property('string'),\n bundle: property('string')\n };\n\n /**\n * Returns a JSON-serializable representation of this `QuerySnapshot` instance.\n *\n * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this\n * `QuerySnapshot` has pending writes.\n */\n toJSON(): object {\n if (this.metadata.hasPendingWrites) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'QuerySnapshot.toJSON() attempted to serialize a document with pending writes. ' +\n 'Await waitForPendingWrites() before invoking toJSON().'\n );\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const result: any = {};\n result['type'] = QuerySnapshot._jsonSchemaVersion;\n result['bundleSource'] = 'QuerySnapshot';\n result['bundleName'] = AutoId.newId();\n\n const databaseId = this._firestore._databaseId.database;\n const projectId = this._firestore._databaseId.projectId;\n const parent = `projects/${projectId}/databases/${databaseId}/documents`;\n const documents: Document[] = [];\n const documentData: DocumentData[] = [];\n const paths: string[] = [];\n\n this.docs.forEach(doc => {\n if (doc._document === null) {\n return;\n }\n documents.push(doc._document);\n documentData.push(\n this._userDataWriter.convertObjectMap(\n doc._document.data.value.mapValue.fields,\n 'previous'\n )\n );\n paths.push(doc.ref.path);\n });\n result['bundle'] = buildQuerySnapshotJsonBundle(\n this._firestore,\n this.query._query,\n result['bundleName'],\n parent,\n paths,\n documents,\n documentData\n );\n return result;\n }\n}\n\n/**\n * Builds a `QuerySnapshot` instance from a JSON object created by\n * {@link QuerySnapshot.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json - a JSON object represention of a `QuerySnapshot` instance.\n * @returns an instance of {@link QuerySnapshot} if the JSON object could be\n * parsed. Throws a {@link FirestoreError} if an error occurs.\n */\nexport function querySnapshotFromJSON(\n db: Firestore,\n json: object\n): QuerySnapshot;\n/**\n * Builds a `QuerySnapshot` instance from a JSON object created by\n * {@link QuerySnapshot.toJSON}.\n *\n * @param firestore - The {@link Firestore} instance the snapshot should be loaded for.\n * @param json - a JSON object represention of a `QuerySnapshot` instance.\n * @param converter - Converts objects to and from Firestore.\n * @returns an instance of {@link QuerySnapshot} if the JSON object could be\n * parsed. Throws a {@link FirestoreError} if an error occurs.\n */\nexport function querySnapshotFromJSON<\n AppModelType,\n DbModelType extends DocumentData = DocumentData\n>(\n db: Firestore,\n json: object,\n converter: FirestoreDataConverter\n): QuerySnapshot;\nexport function querySnapshotFromJSON<\n AppModelType,\n DbModelType extends DocumentData\n>(\n db: Firestore,\n json: object,\n converter?: FirestoreDataConverter\n): QuerySnapshot {\n if (validateJSON(json, QuerySnapshot._jsonSchema)) {\n if (json.bundle === NOT_SUPPORTED) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'The provided JSON object was created in a client environment, which is not supported.'\n );\n }\n // Parse the bundle data.\n const serializer = newSerializer(db._databaseId);\n const bundleReader = createBundleReaderSync(json.bundle, serializer);\n const elements = bundleReader.getElements();\n const bundleLoader: BundleLoader = new BundleLoader(\n bundleReader.getMetadata(),\n serializer\n );\n for (const element of elements) {\n bundleLoader.addSizedElement(element);\n }\n\n if (bundleLoader.queries.length !== 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `Snapshot data expected 1 query but found ${bundleLoader.queries.length} queries.`\n );\n }\n\n // Create an internal Query object from the named query in the bundle.\n const query = fromBundledQuery(bundleLoader.queries[0].bundledQuery!);\n\n // Construct the arrays of document data for the query.\n const bundledDocuments = bundleLoader.documents;\n let documentSet = new DocumentSet();\n bundledDocuments.map(bundledDocument => {\n const document = fromDocument(serializer, bundledDocument.document!);\n documentSet = documentSet.add(document);\n });\n // Create a view snapshot of the query and documents.\n const viewSnapshot = ViewSnapshot.fromInitialDocuments(\n query,\n documentSet,\n documentKeySet() /* Zero mutated keys signifies no pending writes. */,\n /* fromCache= */ false,\n /* hasCachedResults= */ false\n );\n\n // Create an external Query object, required to construct the QuerySnapshot.\n const externalQuery = new Query(\n db,\n converter ? converter : null,\n query\n );\n\n // Return a new QuerySnapshot with all of the collected data.\n return new QuerySnapshot(\n db,\n new LiteUserDataWriter(db),\n externalQuery,\n viewSnapshot\n );\n }\n throw new FirestoreError(\n Code.INTERNAL,\n 'Unexpected error creating QuerySnapshot from JSON.'\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(0xf03d, '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 2025 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 build JSON bundle implementations. */\nimport { Firestore } from '../../api/database';\nimport { Query } from '../../core/query';\nimport { DocumentData } from '../../lite-api/reference';\nimport { Document } from '../../model/document';\n\nexport function buildDocumentSnapshotJsonBundle(\n db: Firestore,\n document: Document,\n docData: DocumentData,\n path: string\n): string {\n return 'NOT SUPPORTED';\n}\n\nexport function buildQuerySnapshotJsonBundle(\n db: Firestore,\n query: Query,\n bundleName: string,\n parent: string,\n paths: string[],\n docs: Document[],\n documentData: DocumentData[]\n): string {\n return 'NOT SUPPORTED';\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 { loadBundle, namedQuery } from '../api/database';\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 { DocumentKey } from '../model/document_key';\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { debugAssert } from '../util/assert';\nimport { ByteString } from '../util/byte_string';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport {\n DocumentSnapshot,\n FirestoreDataConverter,\n QuerySnapshot,\n SnapshotMetadata\n} 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @returns An unsubscribe function that can be called to cancel 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @returns An unsubscribe function that can be called to cancel 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The\n * listener can be cancelled by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The\n * listener can be cancelled by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The\n * listener can be cancelled by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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` is available.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @returns An unsubscribe function that can be called to cancel 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 individual `onNext` and\n * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The\n * listener can be cancelled by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * 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` is available.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @returns An unsubscribe function that can be called to cancel 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 // onSnapshot for Query or Document.\n reference = getModularInstance(reference);\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 }\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 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/**\n * Attaches a listener for `QuerySnapshot` events based on data generated by invoking\n * {@link QuerySnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks or\n * pass a single observer 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 never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}.\n * @param onNext - A callback to be called every time a new `QuerySnapshot` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n onNext: (snapshot: QuerySnapshot) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void,\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking\n * {@link DocumentSnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or\n * pass a single observer 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 never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}.\n * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are\n * never ending.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n onNext: (snapshot: DocumentSnapshot) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void,\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events based on data generated by invoking\n * {@link QuerySnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or\n * pass a single observer 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 never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param onNext - A callback to be called every time a new `QuerySnapshot` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n options: SnapshotListenOptions,\n onNext: (snapshot: QuerySnapshot) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void,\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking\n * {@link DocumentSnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks\n * or pass a single observer object with `next` and `error` callbacks. The listener can be cancelled\n * by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available.\n * @param onError - A callback to be called if the listen fails or is cancelled. No further\n * callbacks will occur.\n * @param onCompletion - Can be provided, but will not be called since streams are never ending.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n options: SnapshotListenOptions,\n onNext: (snapshot: DocumentSnapshot) => void,\n onError?: (error: FirestoreError) => void,\n onCompletion?: () => void,\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events based on QuerySnapshot data generated by invoking\n * {@link QuerySnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or\n * pass a single observer 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 never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n observer: {\n next: (snapshot: QuerySnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n },\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking\n * {@link DocumentSnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks\n * or pass a single observer object with `next` and `error` callbacks. The listener can be cancelled\n * by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n observer: {\n next: (snapshot: DocumentSnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n },\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `QuerySnapshot` events based on QuerySnapshot data generated by invoking\n * {@link QuerySnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks or\n * pass a single observer 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 never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel\n * the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n options: SnapshotListenOptions,\n observer: {\n next: (snapshot: QuerySnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n },\n converter?: FirestoreDataConverter\n): Unsubscribe;\n/**\n * Attaches a listener for `DocumentSnapshot` events based on QuerySnapshot data generated by\n * invoking {@link DocumentSnapshot.toJSON} You may either pass individual `onNext` and `onError`\n * callbacks or pass a single observer object with `next` and `error` callbacks. The listener can be\n * cancelled by calling the function that is returned when `onSnapshot` is called.\n *\n * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the\n * snapshot stream is never-ending.\n *\n * @param firestore - The {@link Firestore} instance to enable the listener for.\n * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot listener.\n */\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n snapshotJson: object,\n options: SnapshotListenOptions,\n observer: {\n next: (snapshot: DocumentSnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n },\n converter?: FirestoreDataConverter\n): Unsubscribe;\nexport function onSnapshotResume<\n AppModelType,\n DbModelType extends DocumentData\n>(reference: Firestore, snapshotJson: object, ...args: unknown[]): Unsubscribe {\n const db = getModularInstance(reference);\n const json = normalizeSnapshotJsonFields(snapshotJson);\n if (json.error) {\n throw new FirestoreError(Code.INVALID_ARGUMENT, json.error);\n }\n let curArg = 0;\n let options: SnapshotListenOptions | undefined = undefined;\n if (typeof args[curArg] === 'object' && !isPartialObserver(args[curArg])) {\n options = args[curArg++] as SnapshotListenOptions;\n }\n\n if (json.bundleSource === 'QuerySnapshot') {\n let observer: {\n next: (snapshot: QuerySnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n } | null = null;\n if (typeof args[curArg] === 'object' && isPartialObserver(args[curArg])) {\n const userObserver = args[curArg++] as PartialObserver<\n QuerySnapshot\n >;\n observer = {\n next: userObserver.next!,\n error: userObserver.error,\n complete: userObserver.complete\n };\n } else {\n observer = {\n next: args[curArg++] as (\n snapshot: QuerySnapshot\n ) => void,\n error: args[curArg++] as (error: FirestoreError) => void,\n complete: args[curArg++] as () => void\n };\n }\n return onSnapshotQuerySnapshotBundle(\n db,\n json,\n options,\n observer!,\n args[curArg] as FirestoreDataConverter\n );\n } else if (json.bundleSource === 'DocumentSnapshot') {\n let observer: {\n next: (snapshot: DocumentSnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n } | null = null;\n if (typeof args[curArg] === 'object' && isPartialObserver(args[curArg])) {\n const userObserver = args[curArg++] as PartialObserver<\n DocumentSnapshot\n >;\n observer = {\n next: userObserver.next!,\n error: userObserver.error,\n complete: userObserver.complete\n };\n } else {\n observer = {\n next: args[curArg++] as (\n snapshot: DocumentSnapshot\n ) => void,\n error: args[curArg++] as (error: FirestoreError) => void,\n complete: args[curArg++] as () => void\n };\n }\n return onSnapshotDocumentSnapshotBundle(\n db,\n json,\n options,\n observer!,\n args[curArg] as FirestoreDataConverter\n );\n } else {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n `unsupported bundle source: ${json.bundleSource}`\n );\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/**\n * Ensures the data required to construct an {@link onSnapshot} listener exist in a `snapshotJson`\n * object that originates from {@link DocumentSnapshot.toJSON} or {@link Querysnapshot.toJSON}. The\n * data is normalized into a typed object.\n *\n * @param snapshotJson - The JSON object that the app provided to {@link onSnapshot}.\n * @returns A normalized object that contains all of the required bundle JSON fields. If\n * {@link snapshotJson} doesn't contain the required fields, or if the fields exist as empty\n * strings, then the {@link snapshotJson.error} field will be a non empty string.\n *\n * @internal\n */\nfunction normalizeSnapshotJsonFields(snapshotJson: object): {\n bundle: string;\n bundleName: string;\n bundleSource: string;\n error?: string;\n} {\n const result: {\n bundle: string;\n bundleName: string;\n bundleSource: string;\n error?: string;\n } = {\n bundle: '',\n bundleName: '',\n bundleSource: ''\n };\n const requiredKeys = ['bundle', 'bundleName', 'bundleSource'];\n for (const key of requiredKeys) {\n if (!(key in snapshotJson)) {\n result.error = `snapshotJson missing required field: ${key}`;\n break;\n }\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const value = (snapshotJson as any)[key];\n if (typeof value !== 'string') {\n result.error = `snapshotJson field '${key}' must be a string.`;\n break;\n }\n if (value.length === 0) {\n result.error = `snapshotJson field '${key}' cannot be an empty string.`;\n break;\n }\n if (key === 'bundle') {\n result.bundle = value;\n } else if (key === 'bundleName') {\n result.bundleName = value;\n } else if (key === 'bundleSource') {\n result.bundleSource = value;\n }\n }\n return result;\n}\n\n/**\n * Loads the bundle in a separate task and then invokes {@link onSnapshot} with a\n * {@link DocumentReference} for the document in the bundle.\n *\n * @param firestore - The {@link Firestore} instance for the {@link onSnapshot} operation request.\n * @param json - The JSON bundle to load, produced by {@link DocumentSnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot\n * listener.\n *\n * @internal\n */\nfunction onSnapshotDocumentSnapshotBundle<\n AppModelType,\n DbModelType extends DocumentData\n>(\n db: Firestore,\n json: { bundle: string; bundleName: string; bundleSource: string },\n options: SnapshotListenOptions | undefined,\n observer: {\n next: (snapshot: DocumentSnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n },\n converter?: FirestoreDataConverter\n): Unsubscribe {\n let unsubscribed: boolean = false;\n let internalUnsubscribe: Unsubscribe | undefined;\n const loadTask = loadBundle(db, json.bundle);\n loadTask\n .then(() => {\n if (!unsubscribed) {\n const docReference = new DocumentReference(\n db,\n converter ? converter : null,\n DocumentKey.fromPath(json.bundleName)\n );\n internalUnsubscribe = onSnapshot(\n docReference as DocumentReference,\n options ? options : {},\n observer\n );\n }\n })\n .catch(e => {\n if (observer.error) {\n observer.error(e);\n }\n return () => {};\n });\n return () => {\n if (unsubscribed) {\n return;\n }\n unsubscribed = true;\n if (internalUnsubscribe) {\n internalUnsubscribe();\n }\n };\n}\n\n/**\n * Loads the bundle in a separate task and then invokes {@link onSnapshot} with a\n * {@link Query} that represents the Query in the bundle.\n *\n * @param firestore - The {@link Firestore} instance for the {@link onSnapshot} operation request.\n * @param json - The JSON bundle to load, produced by {@link QuerySnapshot.toJSON}.\n * @param options - Options controlling the listen behavior.\n * @param observer - A single object containing `next` and `error` callbacks.\n * @param converter - An optional object that converts objects from Firestore before the onNext\n * listener is invoked.\n * @returns An unsubscribe function that can be called to cancel the snapshot\n * listener.\n *\n * @internal\n */\nfunction onSnapshotQuerySnapshotBundle<\n AppModelType,\n DbModelType extends DocumentData\n>(\n db: Firestore,\n json: { bundle: string; bundleName: string; bundleSource: string },\n options: SnapshotListenOptions | undefined,\n observer: {\n next: (snapshot: QuerySnapshot) => void;\n error?: (error: FirestoreError) => void;\n complete?: () => void;\n },\n converter?: FirestoreDataConverter\n): Unsubscribe {\n let unsubscribed: boolean = false;\n let internalUnsubscribe: Unsubscribe | undefined;\n const loadTask = loadBundle(db, json.bundle);\n loadTask\n .then(() => namedQuery(db, json.bundleName))\n .then(query => {\n if (query && !unsubscribed) {\n const realQuery: Query = (query as Query)!;\n if (converter) {\n realQuery.withConverter(converter);\n }\n internalUnsubscribe = onSnapshot(\n query as Query,\n options ? options : {},\n observer\n );\n }\n })\n .catch(e => {\n if (observer.error) {\n observer.error(e);\n }\n return () => {};\n });\n return () => {\n if (unsubscribed) {\n return;\n }\n unsubscribed = true;\n if (internalUnsubscribe) {\n internalUnsubscribe();\n }\n };\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { AggregateField, AggregateSpec, DocumentData, Query } from '../api';\nimport { AggregateImpl } from '../core/aggregate';\nimport { firestoreClientRunAggregateQuery } from '../core/firestore_client';\nimport { count } from '../lite-api/aggregate';\nimport { AggregateQuerySnapshot } from '../lite-api/aggregate_types';\nimport { ApiClientObjectMap, Value } from '../protos/firestore_proto_api';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport { ExpUserDataWriter } from './reference_impl';\n\nexport {\n aggregateQuerySnapshotEqual,\n count,\n sum,\n average,\n aggregateFieldEqual\n} from '../lite-api/aggregate';\n\n/**\n * Calculates the number of documents in the result set of the given query\n * without actually downloading the documents.\n *\n * Using this function to count the documents is efficient because only the\n * final count, not the documents' data, is downloaded. This function can\n * count the documents in cases where the result set is prohibitively large to\n * download entirely (thousands of documents).\n *\n * The result received from the server is presented, unaltered, without\n * considering any local state. That is, documents in the local cache are not\n * taken into consideration, neither are local modifications not yet\n * synchronized with the server. Previously-downloaded results, if any, are not\n * used. Every invocation of this function necessarily involves a round trip to\n * the server.\n *\n * @param query The query whose result set size is calculated.\n * @returns A Promise that will be resolved with the count; the count can be\n * retrieved from `snapshot.data().count`, where `snapshot` is the\n * `AggregateQuerySnapshot` to which the returned Promise resolves.\n */\nexport function getCountFromServer<\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query\n): Promise<\n AggregateQuerySnapshot<\n { count: AggregateField },\n AppModelType,\n DbModelType\n >\n> {\n const countQuerySpec: { count: AggregateField } = {\n count: count()\n };\n\n return getAggregateFromServer(query, countQuerySpec);\n}\n\n/**\n * Calculates the specified aggregations over the documents in the result\n * set of the given query without actually downloading the documents.\n *\n * Using this function to perform aggregations is efficient because only the\n * final aggregation values, not the documents' data, are downloaded. This\n * function can perform aggregations of the documents in cases where the result\n * set is prohibitively large to download entirely (thousands of documents).\n *\n * The result received from the server is presented, unaltered, without\n * considering any local state. That is, documents in the local cache are not\n * taken into consideration, neither are local modifications not yet\n * synchronized with the server. Previously-downloaded results, if any, are not\n * used. Every invocation of this function necessarily involves a round trip to\n * the server.\n *\n * @param query The query whose result set is aggregated over.\n * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates\n * to perform over the result set. The AggregateSpec specifies aliases for each\n * aggregate, which can be used to retrieve the aggregate result.\n * @example\n * ```typescript\n * const aggregateSnapshot = await getAggregateFromServer(query, {\n * countOfDocs: count(),\n * totalHours: sum('hours'),\n * averageScore: average('score')\n * });\n *\n * const countOfDocs: number = aggregateSnapshot.data().countOfDocs;\n * const totalHours: number = aggregateSnapshot.data().totalHours;\n * const averageScore: number | null = aggregateSnapshot.data().averageScore;\n * ```\n */\nexport function getAggregateFromServer<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n query: Query,\n aggregateSpec: AggregateSpecType\n): Promise<\n AggregateQuerySnapshot\n> {\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n\n const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n\n // Run the aggregation and convert the results\n return firestoreClientRunAggregateQuery(\n client,\n query._query,\n internalAggregates\n ).then(aggregateResult =>\n convertToAggregateQuerySnapshot(firestore, query, aggregateResult)\n );\n}\n\n/**\n * Converts the core aggregation result to an `AggregateQuerySnapshot`\n * that can be returned to the consumer.\n * @param query\n * @param aggregateResult Core aggregation result\n * @internal\n */\nfunction convertToAggregateQuerySnapshot<\n AggregateSpecType extends AggregateSpec,\n AppModelType,\n DbModelType extends DocumentData\n>(\n firestore: Firestore,\n query: Query,\n aggregateResult: ApiClientObjectMap\n): AggregateQuerySnapshot {\n const userDataWriter = new ExpUserDataWriter(firestore);\n const querySnapshot = new AggregateQuerySnapshot<\n AggregateSpecType,\n AppModelType,\n DbModelType\n >(query, userDataWriter, aggregateResult);\n return querySnapshot;\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 IndexedDbOfflineComponentProvider,\n LruGcMemoryOfflineComponentProvider,\n MemoryOfflineComponentProvider,\n MultiTabOfflineComponentProvider,\n OfflineComponentProviderFactory,\n OnlineComponentProviderFactory,\n OnlineComponentProvider\n} from '../core/component_provider';\n\n/* eslint @typescript-eslint/consistent-type-definitions: [\"error\", \"type\"] */\n/**\n * Provides an in-memory cache to the SDK. This is the default cache unless explicitly\n * configured otherwise.\n *\n * To use, create an instance using the factory function {@link memoryLocalCache()}, then\n * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using\n * the settings object.\n */\nexport type MemoryLocalCache = {\n kind: 'memory';\n /**\n * @internal\n */\n _onlineComponentProvider: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n};\n\nclass MemoryLocalCacheImpl implements MemoryLocalCache {\n kind: 'memory' = 'memory';\n /**\n * @internal\n */\n _onlineComponentProvider: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n\n constructor(settings?: MemoryCacheSettings) {\n this._onlineComponentProvider = OnlineComponentProvider.provider;\n if (settings?.garbageCollector) {\n this._offlineComponentProvider =\n settings.garbageCollector._offlineComponentProvider;\n } else {\n this._offlineComponentProvider = {\n build: () => new LruGcMemoryOfflineComponentProvider(undefined)\n };\n }\n }\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n}\n\n/**\n * Provides a persistent cache backed by IndexedDb to the SDK.\n *\n * To use, create an instance using the factory function {@link persistentLocalCache()}, then\n * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using\n * the settings object.\n */\nexport type PersistentLocalCache = {\n kind: 'persistent';\n /**\n * @internal\n */\n _onlineComponentProvider: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n};\n\nclass PersistentLocalCacheImpl implements PersistentLocalCache {\n kind: 'persistent' = 'persistent';\n /**\n * @internal\n */\n _onlineComponentProvider: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n\n constructor(settings: PersistentCacheSettings | undefined) {\n let tabManager: PersistentTabManager;\n if (settings?.tabManager) {\n settings.tabManager._initialize(settings);\n tabManager = settings.tabManager;\n } else {\n tabManager = persistentSingleTabManager(undefined);\n tabManager._initialize(settings);\n }\n this._onlineComponentProvider = tabManager._onlineComponentProvider!;\n this._offlineComponentProvider = tabManager._offlineComponentProvider!;\n }\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n}\n\n/**\n * Union type from all supported SDK cache layer.\n */\nexport type FirestoreLocalCache = MemoryLocalCache | PersistentLocalCache;\n\n/**\n * Union type from all support garbage collectors for memory local cache.\n */\nexport type MemoryGarbageCollector =\n | MemoryEagerGarbageCollector\n | MemoryLruGarbageCollector;\n\n/**\n * A garbage collector deletes documents whenever they are not part of any\n * active queries, and have no local mutations attached to them.\n *\n * This collector tries to ensure lowest memory footprints from the SDK,\n * at the risk of documents not being cached for offline queries or for\n * direct queries to the cache.\n *\n * Use factory function {@link memoryEagerGarbageCollector()} to create an\n * instance of this collector.\n */\nexport type MemoryEagerGarbageCollector = {\n kind: 'memoryEager';\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n};\n\n/**\n * A garbage collector deletes Least-Recently-Used documents in multiple\n * batches.\n *\n * This collector is configured with a target size, and will only perform\n * collection when the cached documents exceed the target size. It avoids\n * querying backend repeated for the same query or document, at the risk\n * of having a larger memory footprint.\n *\n * Use factory function {@link memoryLruGarbageCollector()} to create a\n * instance of this collector.\n */\nexport type MemoryLruGarbageCollector = {\n kind: 'memoryLru';\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n};\n\nclass MemoryEagerGarbageCollectorImpl implements MemoryEagerGarbageCollector {\n kind: 'memoryEager' = 'memoryEager';\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n\n constructor() {\n this._offlineComponentProvider = MemoryOfflineComponentProvider.provider;\n }\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n}\n\nclass MemoryLruGarbageCollectorImpl implements MemoryLruGarbageCollector {\n kind: 'memoryLru' = 'memoryLru';\n /**\n * @internal\n */\n _offlineComponentProvider: OfflineComponentProviderFactory;\n\n constructor(cacheSize?: number) {\n this._offlineComponentProvider = {\n build: () => new LruGcMemoryOfflineComponentProvider(cacheSize)\n };\n }\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n}\n\n/**\n * Creates an instance of `MemoryEagerGarbageCollector`. This is also the\n * default garbage collector unless it is explicitly specified otherwise.\n */\nexport function memoryEagerGarbageCollector(): MemoryEagerGarbageCollector {\n return new MemoryEagerGarbageCollectorImpl();\n}\n\n/**\n * Creates an instance of `MemoryLruGarbageCollector`.\n *\n * A target size can be specified as part of the setting parameter. The\n * collector will start deleting documents once the cache size exceeds\n * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes).\n */\nexport function memoryLruGarbageCollector(settings?: {\n cacheSizeBytes?: number;\n}): MemoryLruGarbageCollector {\n return new MemoryLruGarbageCollectorImpl(settings?.cacheSizeBytes);\n}\n\n/**\n * An settings object to configure an `MemoryLocalCache` instance.\n */\nexport type MemoryCacheSettings = {\n /**\n * The garbage collector to use, for the memory cache layer.\n * A `MemoryEagerGarbageCollector` is used when this is undefined.\n */\n garbageCollector?: MemoryGarbageCollector;\n};\n\n/**\n * Creates an instance of `MemoryLocalCache`. The instance can be set to\n * `FirestoreSettings.cache` to tell the SDK which cache layer to use.\n */\nexport function memoryLocalCache(\n settings?: MemoryCacheSettings\n): MemoryLocalCache {\n return new MemoryLocalCacheImpl(settings);\n}\n\n/**\n * An settings object to configure an `PersistentLocalCache` instance.\n *\n * Persistent cache cannot be used in a Node.js environment.\n */\nexport type PersistentCacheSettings = {\n /**\n * An approximate cache size threshold for the on-disk data. If the cache\n * grows beyond this size, Firestore will start removing data that hasn't been\n * recently used. The SDK does not guarantee that the cache will stay below\n * that size, only that if the cache exceeds the given size, cleanup will be\n * attempted.\n *\n * The default value is 40 MB. The threshold must be set to at least 1 MB, and\n * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection.\n */\n cacheSizeBytes?: number;\n\n /**\n * Specifies how multiple tabs/windows will be managed by the SDK.\n */\n tabManager?: PersistentTabManager;\n};\n\n/**\n * Creates an instance of `PersistentLocalCache`. The instance can be set to\n * `FirestoreSettings.cache` to tell the SDK which cache layer to use.\n *\n * Persistent cache cannot be used in a Node.js environment.\n */\nexport function persistentLocalCache(\n settings?: PersistentCacheSettings\n): PersistentLocalCache {\n return new PersistentLocalCacheImpl(settings);\n}\n\n/**\n * A tab manager supporting only one tab, no synchronization will be\n * performed across tabs.\n */\nexport type PersistentSingleTabManager = {\n kind: 'persistentSingleTab';\n /**\n * @internal\n */\n _initialize: (\n settings: Omit | undefined\n ) => void;\n /**\n * @internal\n */\n _onlineComponentProvider?: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider?: OfflineComponentProviderFactory;\n};\n\nclass SingleTabManagerImpl implements PersistentSingleTabManager {\n kind: 'persistentSingleTab' = 'persistentSingleTab';\n\n /**\n * @internal\n */\n _onlineComponentProvider?: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider?: OfflineComponentProviderFactory;\n\n constructor(private forceOwnership?: boolean) {}\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n\n /**\n * @internal\n */\n _initialize(\n settings: Omit | undefined\n ): void {\n this._onlineComponentProvider = OnlineComponentProvider.provider;\n this._offlineComponentProvider = {\n build: (onlineComponents: OnlineComponentProvider) =>\n new IndexedDbOfflineComponentProvider(\n onlineComponents,\n settings?.cacheSizeBytes,\n this.forceOwnership\n )\n };\n }\n}\n\n/**\n * A tab manager supporting multiple tabs. SDK will synchronize queries and\n * mutations done across all tabs using the SDK.\n */\nexport type PersistentMultipleTabManager = {\n kind: 'PersistentMultipleTab';\n /**\n * @internal\n */\n _initialize: (settings: Omit) => void;\n /**\n * @internal\n */\n _onlineComponentProvider?: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n\n _offlineComponentProvider?: OfflineComponentProviderFactory;\n};\n\nclass MultiTabManagerImpl implements PersistentMultipleTabManager {\n kind: 'PersistentMultipleTab' = 'PersistentMultipleTab';\n\n /**\n * @internal\n */\n _onlineComponentProvider?: OnlineComponentProviderFactory;\n /**\n * @internal\n */\n _offlineComponentProvider?: OfflineComponentProviderFactory;\n\n toJSON(): {} {\n return { kind: this.kind };\n }\n\n /**\n * @internal\n */\n _initialize(\n settings: Omit | undefined\n ): void {\n this._onlineComponentProvider = OnlineComponentProvider.provider;\n this._offlineComponentProvider = {\n build: (onlineComponents: OnlineComponentProvider) =>\n new MultiTabOfflineComponentProvider(\n onlineComponents,\n settings?.cacheSizeBytes\n )\n };\n }\n}\n\n/**\n * A union of all available tab managers.\n */\nexport type PersistentTabManager =\n | PersistentSingleTabManager\n | PersistentMultipleTabManager;\n\n/**\n * Type to configure an `PersistentSingleTabManager` instance.\n */\nexport type PersistentSingleTabManagerSettings = {\n /**\n * Whether to force-enable persistent (IndexedDB) cache for the client. This\n * cannot be used with multi-tab synchronization and is primarily intended for\n * use with Web Workers. Setting this to `true` will enable IndexedDB, but cause\n * other tabs using IndexedDB cache to fail.\n */\n forceOwnership?: boolean;\n};\n/**\n * Creates an instance of `PersistentSingleTabManager`.\n *\n * @param settings Configures the created tab manager.\n */\nexport function persistentSingleTabManager(\n settings: PersistentSingleTabManagerSettings | undefined\n): PersistentSingleTabManager {\n return new SingleTabManagerImpl(settings?.forceOwnership);\n}\n\n/**\n * Creates an instance of `PersistentMultipleTabManager`.\n */\nexport function persistentMultipleTabManager(): PersistentMultipleTabManager {\n return new MultiTabManagerImpl();\n}\n","/**\n * @license\n * Copyright 2022 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Code, FirestoreError } from '../util/error';\n\nexport const DEFAULT_TRANSACTION_OPTIONS: TransactionOptions = {\n maxAttempts: 5\n};\n\n/**\n * Options to customize transaction behavior.\n */\nexport declare interface TransactionOptions {\n /** Maximum number of attempts to commit, after which transaction fails. Default is 5. */\n readonly maxAttempts: number;\n}\n\nexport function validateTransactionOptions(options: TransactionOptions): void {\n if (options.maxAttempts < 1) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Max attempts must be at least 1'\n );\n }\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { Compat, getModularInstance } from '@firebase/util';\n\nimport { DeleteMutation, Mutation, Precondition } from '../model/mutation';\nimport { invokeCommitRpc } from '../remote/datastore';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport { applyFirestoreDataConverter } from './reference_impl';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\n\n/**\n * A write batch, used to perform multiple writes as a single atomic unit.\n *\n * A `WriteBatch` object can be acquired by calling {@link writeBatch}. It\n * provides methods for adding writes to the write batch. None of the writes\n * will be committed (or visible locally) until {@link WriteBatch.commit} is\n * called.\n */\nexport class WriteBatch {\n // This is the lite version of the WriteBatch API used in the legacy SDK. The\n // class is a close copy but takes different input types.\n\n private readonly _dataReader: UserDataReader;\n private _mutations = [] as Mutation[];\n private _committed = false;\n\n /** @hideconstructor */\n constructor(\n private readonly _firestore: Firestore,\n private readonly _commitHandler: (m: Mutation[]) => Promise\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): WriteBatch;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): WriteBatch;\n set(\n documentRef: DocumentReference,\n data: WithFieldValue | PartialWithFieldValue,\n options?: SetOptions\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n data,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'WriteBatch.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._mutations.push(parsed.toMutation(ref._key, Precondition.none()));\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): WriteBatch;\n /**\n * Updates fields in the document referred to by this {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be update by providing dot-separated field path strings\n * or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'WriteBatch.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._mutations.push(\n parsed.toMutation(ref._key, Precondition.exists(true))\n );\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `WriteBatch` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): WriteBatch {\n this._verifyNotCommitted();\n const ref = validateReference(documentRef, this._firestore);\n this._mutations = this._mutations.concat(\n new DeleteMutation(ref._key, Precondition.none())\n );\n return this;\n }\n\n /**\n * Commits all of the writes in this write batch as a single atomic unit.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `Promise` resolved once all of the writes in the batch have been\n * successfully written to the backend as an atomic unit (note that it won't\n * resolve while you're offline).\n */\n commit(): Promise {\n this._verifyNotCommitted();\n this._committed = true;\n if (this._mutations.length > 0) {\n return this._commitHandler(this._mutations);\n }\n\n return Promise.resolve();\n }\n\n private _verifyNotCommitted(): void {\n if (this._committed) {\n throw new FirestoreError(\n Code.FAILED_PRECONDITION,\n 'A write batch can no longer be used after commit() ' +\n 'has been called.'\n );\n }\n }\n}\n\nexport function validateReference<\n AppModelType,\n DbModelType extends DocumentData\n>(\n documentRef:\n | DocumentReference\n | Compat>,\n firestore: Firestore\n): DocumentReference {\n documentRef = getModularInstance(documentRef);\n\n if (documentRef.firestore !== firestore) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Provided document reference is from a different Firestore instance.'\n );\n } else {\n return documentRef as DocumentReference;\n }\n}\n\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single WriteBatch\n * is 500.\n *\n * The result of these writes will only be reflected in document reads that\n * occur after the returned promise resolves. If the client is offline, the\n * write fails. If you would like to see local modifications or buffer writes\n * until the client is online, use the full Firestore SDK.\n *\n * @returns A `WriteBatch` that can be used to atomically execute multiple\n * writes.\n */\nexport function writeBatch(firestore: Firestore): WriteBatch {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n return new WriteBatch(firestore, writes =>\n invokeCommitRpc(datastore, writes)\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { getModularInstance } from '@firebase/util';\n\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport {\n DEFAULT_TRANSACTION_OPTIONS,\n TransactionOptions as TransactionOptionsInternal,\n validateTransactionOptions\n} from '../core/transaction_options';\nimport { TransactionRunner } from '../core/transaction_runner';\nimport { fail } from '../util/assert';\nimport { newAsyncQueue } from '../util/async_queue_impl';\nimport { cast } from '../util/input_validation';\nimport { Deferred } from '../util/promise';\n\nimport { getDatastore } from './components';\nimport { Firestore } from './database';\nimport { FieldPath } from './field_path';\nimport {\n DocumentData,\n DocumentReference,\n PartialWithFieldValue,\n SetOptions,\n UpdateData,\n WithFieldValue\n} from './reference';\nimport {\n applyFirestoreDataConverter,\n LiteUserDataWriter\n} from './reference_impl';\nimport { DocumentSnapshot } from './snapshot';\nimport { TransactionOptions } from './transaction_options';\nimport {\n newUserDataReader,\n parseSetData,\n parseUpdateData,\n parseUpdateVarargs,\n UserDataReader\n} from './user_data_reader';\nimport { validateReference } from './write_batch';\n\n// TODO(mrschmidt) Consider using `BaseTransaction` as the base class in the\n// legacy SDK.\n\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nexport class Transaction {\n // This is the tree-shakeable version of the Transaction class used in the\n // legacy SDK. The class is a close copy but takes different input and output\n // types. The firestore-exp SDK further extends this class to return its API\n // type.\n\n private readonly _dataReader: UserDataReader;\n\n /** @hideconstructor */\n constructor(\n protected readonly _firestore: Firestore,\n private readonly _transaction: InternalTransaction\n ) {\n this._dataReader = newUserDataReader(_firestore);\n }\n\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */\n get(\n documentRef: DocumentReference\n ): Promise> {\n const ref = validateReference(documentRef, this._firestore);\n const userDataWriter = new LiteUserDataWriter(this._firestore);\n return this._transaction.lookup([ref._key]).then(docs => {\n if (!docs || docs.length !== 1) {\n return fail(0x5de9, 'Mismatch in docs returned from document lookup.');\n }\n const doc = docs[0];\n if (doc.isFoundDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n doc.key,\n doc,\n ref.converter\n );\n } else if (doc.isNoDocument()) {\n return new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n ref._key,\n null,\n ref.converter\n );\n } else {\n throw fail(\n 0x4801,\n 'BatchGetDocumentsRequest returned unexpected document',\n {\n doc\n }\n );\n }\n });\n }\n\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: WithFieldValue\n ): this;\n /**\n * Writes to the document referred to by the provided {@link\n * DocumentReference}. If the document does not exist yet, it will be created.\n * If you provide `merge` or `mergeFields`, the provided data can be merged\n * into an existing document.\n *\n * @param documentRef - A reference to the document to be set.\n * @param data - An object of the fields and values for the document.\n * @param options - An object to configure the set behavior.\n * @throws Error - If the provided input is not a valid Firestore document.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n set(\n documentRef: DocumentReference,\n data: PartialWithFieldValue,\n options: SetOptions\n ): this;\n set(\n documentRef: DocumentReference,\n value: PartialWithFieldValue,\n options?: SetOptions\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n const convertedValue = applyFirestoreDataConverter(\n ref.converter,\n value,\n options\n );\n const parsed = parseSetData(\n this._dataReader,\n 'Transaction.set',\n ref._key,\n convertedValue,\n ref.converter !== null,\n options\n );\n this._transaction.set(ref._key, parsed);\n return this;\n }\n\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param data - An object containing the fields and values with which to\n * update the document. Fields can contain dots to reference nested fields\n * within the document.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n data: UpdateData\n ): this;\n /**\n * Updates fields in the document referred to by the provided {@link\n * DocumentReference}. The update will fail if applied to a document that does\n * not exist.\n *\n * Nested fields can be updated by providing dot-separated field path\n * strings or by providing `FieldPath` objects.\n *\n * @param documentRef - A reference to the document to be updated.\n * @param field - The first field to update.\n * @param value - The first value.\n * @param moreFieldsAndValues - Additional key/value pairs.\n * @throws Error - If the provided input is not valid Firestore data.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n update(\n documentRef: DocumentReference,\n field: string | FieldPath,\n value: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this;\n update(\n documentRef: DocumentReference,\n fieldOrUpdateData: string | FieldPath | UpdateData,\n value?: unknown,\n ...moreFieldsAndValues: unknown[]\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n\n // For Compat types, we have to \"extract\" the underlying types before\n // performing validation.\n fieldOrUpdateData = getModularInstance(fieldOrUpdateData);\n\n let parsed;\n if (\n typeof fieldOrUpdateData === 'string' ||\n fieldOrUpdateData instanceof FieldPath\n ) {\n parsed = parseUpdateVarargs(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData,\n value,\n moreFieldsAndValues\n );\n } else {\n parsed = parseUpdateData(\n this._dataReader,\n 'Transaction.update',\n ref._key,\n fieldOrUpdateData\n );\n }\n\n this._transaction.update(ref._key, parsed);\n return this;\n }\n\n /**\n * Deletes the document referred to by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be deleted.\n * @returns This `Transaction` instance. Used for chaining method calls.\n */\n delete(\n documentRef: DocumentReference\n ): this {\n const ref = validateReference(documentRef, this._firestore);\n this._transaction.delete(ref._key);\n return this;\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */\nexport function runTransaction(\n firestore: Firestore,\n updateFunction: (transaction: Transaction) => Promise,\n options?: TransactionOptions\n): Promise {\n firestore = cast(firestore, Firestore);\n const datastore = getDatastore(firestore);\n const optionsWithDefaults: TransactionOptionsInternal = {\n ...DEFAULT_TRANSACTION_OPTIONS,\n ...options\n };\n validateTransactionOptions(optionsWithDefaults);\n const deferred = new Deferred();\n new TransactionRunner(\n newAsyncQueue(),\n datastore,\n optionsWithDefaults,\n internalTransaction =>\n updateFunction(new Transaction(firestore, internalTransaction)),\n deferred\n ).run();\n return deferred.promise;\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { firestoreClientTransaction } from '../core/firestore_client';\nimport { Transaction as InternalTransaction } from '../core/transaction';\nimport {\n TransactionOptions as TransactionOptionsInternal,\n DEFAULT_TRANSACTION_OPTIONS,\n validateTransactionOptions\n} from '../core/transaction_options';\nimport { DocumentData, DocumentReference } from '../lite-api/reference';\nimport { Transaction as LiteTransaction } from '../lite-api/transaction';\nimport { validateReference } from '../lite-api/write_batch';\nimport { cast } from '../util/input_validation';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport { ExpUserDataWriter } from './reference_impl';\nimport { DocumentSnapshot, SnapshotMetadata } from './snapshot';\nimport { TransactionOptions } from './transaction_options';\n\n/**\n * A reference to a transaction.\n *\n * The `Transaction` object passed to a transaction's `updateFunction` provides\n * the methods to read and write data within the transaction context. See\n * {@link runTransaction}.\n */\nexport class Transaction extends LiteTransaction {\n // This class implements the same logic as the Transaction API in the Lite SDK\n // but is subclassed in order to return its own DocumentSnapshot types.\n\n /** @hideconstructor */\n constructor(\n protected readonly _firestore: Firestore,\n _transaction: InternalTransaction\n ) {\n super(_firestore, _transaction);\n }\n\n /**\n * Reads the document referenced by the provided {@link DocumentReference}.\n *\n * @param documentRef - A reference to the document to be read.\n * @returns A `DocumentSnapshot` with the read data.\n */\n get(\n documentRef: DocumentReference\n ): Promise> {\n const ref = validateReference(documentRef, this._firestore);\n const userDataWriter = new ExpUserDataWriter(this._firestore);\n return super\n .get(documentRef)\n .then(\n liteDocumentSnapshot =>\n new DocumentSnapshot(\n this._firestore,\n userDataWriter,\n ref._key,\n liteDocumentSnapshot._document,\n new SnapshotMetadata(\n /* hasPendingWrites= */ false,\n /* fromCache= */ false\n ),\n ref.converter\n )\n );\n }\n}\n\n/**\n * Executes the given `updateFunction` and then attempts to commit the changes\n * applied within the transaction. If any document read within the transaction\n * has changed, Cloud Firestore retries the `updateFunction`. If it fails to\n * commit after 5 attempts, the transaction fails.\n *\n * The maximum number of writes allowed in a single transaction is 500.\n *\n * @param firestore - A reference to the Firestore database to run this\n * transaction against.\n * @param updateFunction - The function to execute within the transaction\n * context.\n * @param options - An options object to configure maximum number of attempts to\n * commit.\n * @returns If the transaction completed successfully or was explicitly aborted\n * (the `updateFunction` returned a failed promise), the promise returned by the\n * `updateFunction `is returned here. Otherwise, if the transaction failed, a\n * rejected promise with the corresponding failure error is returned.\n */\nexport function runTransaction(\n firestore: Firestore,\n updateFunction: (transaction: Transaction) => Promise,\n options?: TransactionOptions\n): Promise {\n firestore = cast(firestore, Firestore);\n const optionsWithDefaults: TransactionOptionsInternal = {\n ...DEFAULT_TRANSACTION_OPTIONS,\n ...options\n };\n validateTransactionOptions(optionsWithDefaults);\n const client = ensureFirestoreConfigured(firestore);\n return firestoreClientTransaction(\n client,\n internalTransaction =>\n updateFunction(new Transaction(firestore, internalTransaction)),\n optionsWithDefaults\n );\n}\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { FieldValue } from './field_value';\nimport {\n ArrayRemoveFieldValueImpl,\n ArrayUnionFieldValueImpl,\n DeleteFieldValueImpl,\n NumericIncrementFieldValueImpl,\n ServerTimestampFieldValueImpl\n} from './user_data_reader';\nimport { VectorValue } from './vector_value';\n\n/**\n * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or\n * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion.\n */\nexport function deleteField(): FieldValue {\n return new DeleteFieldValueImpl('deleteField');\n}\n\n/**\n * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to\n * include a server-generated timestamp in the written data.\n */\nexport function serverTimestamp(): FieldValue {\n return new ServerTimestampFieldValueImpl('serverTimestamp');\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array\n * value that already exists on the server. Each specified element that doesn't\n * already exist in the array will be added to the end. If the field being\n * modified is not already an array it will be overwritten with an array\n * containing exactly the specified elements.\n *\n * @param elements - The elements to union into the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`.\n */\nexport function arrayUnion(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayUnionFieldValueImpl('arrayUnion', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link (setDoc:1)} or {@link\n * updateDoc:1} that tells the server to remove the given elements from any\n * array value that already exists on the server. All instances of each element\n * specified will be removed from the array. If the field being modified is not\n * already an array it will be overwritten with an empty array.\n *\n * @param elements - The elements to remove from the array.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function arrayRemove(...elements: unknown[]): FieldValue {\n // NOTE: We don't actually parse the data until it's used in set() or\n // update() since we'd need the Firestore instance to do this.\n return new ArrayRemoveFieldValueImpl('arrayRemove', elements);\n}\n\n/**\n * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link\n * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by\n * the given value.\n *\n * If either the operand or the current field value uses floating point\n * precision, all arithmetic follows IEEE 754 semantics. If both values are\n * integers, values outside of JavaScript's safe number range\n * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to\n * precision loss. Furthermore, once processed by the Firestore backend, all\n * integer operations are capped between -2^63 and 2^63-1.\n *\n * If the current field value is not of type `number`, or if the field does not\n * yet exist, the transformation sets the field to the given value.\n *\n * @param n - The value to increment by.\n * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or\n * `updateDoc()`\n */\nexport function increment(n: number): FieldValue {\n return new NumericIncrementFieldValueImpl('increment', n);\n}\n\n/**\n * Creates a new `VectorValue` constructed with a copy of the given array of numbers.\n *\n * @param values - Create a `VectorValue` instance with a copy of this array of numbers.\n *\n * @returns A new `VectorValue` constructed with a copy of the given array of numbers.\n */\nexport function vector(values?: number[]): VectorValue {\n return new VectorValue(values);\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 { WriteBatch } from '../lite-api/write_batch';\nimport { cast } from '../util/input_validation';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\nimport { executeWrite } from './reference_impl';\n\nexport { WriteBatch };\n\n/**\n * Creates a write batch, used for performing multiple writes as a single\n * atomic operation. The maximum number of writes allowed in a single {@link WriteBatch}\n * is 500.\n *\n * Unlike transactions, write batches are persisted offline and therefore are\n * preferable when you don't need to condition your writes on read data.\n *\n * @returns A {@link WriteBatch} that can be used to atomically execute multiple\n * writes.\n */\nexport function writeBatch(firestore: Firestore): WriteBatch {\n firestore = cast(firestore, Firestore);\n ensureFirestoreConfigured(firestore);\n return new WriteBatch(firestore, mutations =>\n executeWrite(firestore, mutations)\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 { firestoreClientSetIndexConfiguration } from '../core/firestore_client';\nimport { fieldPathFromDotSeparatedString } from '../lite-api/user_data_reader';\nimport {\n FieldIndex,\n IndexKind,\n IndexSegment,\n IndexState\n} from '../model/field_index';\nimport { Code, FirestoreError } from '../util/error';\nimport { cast } from '../util/input_validation';\nimport { logWarn } from '../util/log';\n\nimport { ensureFirestoreConfigured, Firestore } from './database';\n\nexport {\n connectFirestoreEmulator,\n EmulatorMockTokenOptions\n} from '../lite-api/database';\n\n/**\n * A single field element in an index configuration.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport interface IndexField {\n /** The field path to index. */\n readonly fieldPath: string;\n /**\n * What type of array index to create. Set to `CONTAINS` for `array-contains`\n * and `array-contains-any` indexes.\n *\n * Only one of `arrayConfig` or `order` should be set;\n */\n readonly arrayConfig?: 'CONTAINS';\n /**\n * What type of array index to create. Set to `ASCENDING` or 'DESCENDING` for\n * `==`, `!=`, `<=`, `<=`, `in` and `not-in` filters.\n *\n * Only one of `arrayConfig` or `order` should be set.\n */\n readonly order?: 'ASCENDING' | 'DESCENDING';\n\n [key: string]: unknown;\n}\n\n/**\n * The SDK definition of a Firestore index.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport interface Index {\n /** The ID of the collection to index. */\n readonly collectionGroup: string;\n /** A list of fields to index. */\n readonly fields?: IndexField[];\n\n [key: string]: unknown;\n}\n\n/**\n * A list of Firestore indexes to speed up local query execution.\n *\n * See {@link https://firebase.google.com/docs/reference/firestore/indexes/#json_format | JSON Format}\n * for a description of the format of the index definition.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport interface IndexConfiguration {\n /** A list of all Firestore indexes. */\n readonly indexes?: Index[];\n\n [key: string]: unknown;\n}\n\n/**\n * Configures indexing for local query execution. Any previous index\n * configuration is overridden. The `Promise` resolves once the index\n * configuration has been persisted.\n *\n * The index entries themselves are created asynchronously. You can continue to\n * use queries that require indexing even if the indices are not yet available.\n * Query execution will automatically start using the index once the index\n * entries have been written.\n *\n * Indexes are only supported with IndexedDb persistence. If IndexedDb is not\n * enabled, any index configuration is ignored.\n *\n * @param firestore - The {@link Firestore} instance to configure indexes for.\n * @param configuration -The index definition.\n * @throws FirestoreError if the JSON format is invalid.\n * @returns A `Promise` that resolves once all indices are successfully\n * configured.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport function setIndexConfiguration(\n firestore: Firestore,\n configuration: IndexConfiguration\n): Promise;\n\n/**\n * Configures indexing for local query execution. Any previous index\n * configuration is overridden. The `Promise` resolves once the index\n * configuration has been persisted.\n *\n * The index entries themselves are created asynchronously. You can continue to\n * use queries that require indexing even if the indices are not yet available.\n * Query execution will automatically start using the index once the index\n * entries have been written.\n *\n * Indexes are only supported with IndexedDb persistence. Invoke either\n * `enableIndexedDbPersistence()` or `enableMultiTabIndexedDbPersistence()`\n * before setting an index configuration. If IndexedDb is not enabled, any\n * index configuration is ignored.\n *\n * The method accepts the JSON format exported by the Firebase CLI (`firebase\n * firestore:indexes`). If the JSON format is invalid, this method throws an\n * error.\n *\n * @param firestore - The {@link Firestore} instance to configure indexes for.\n * @param json -The JSON format exported by the Firebase CLI.\n * @throws FirestoreError if the JSON format is invalid.\n * @returns A `Promise` that resolves once all indices are successfully\n * configured.\n *\n * @deprecated Instead of creating cache indexes manually, consider using\n * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to\n * create cache indexes for queries running locally.\n *\n * @beta\n */\nexport function setIndexConfiguration(\n firestore: Firestore,\n json: string\n): Promise;\n\nexport function setIndexConfiguration(\n firestore: Firestore,\n jsonOrConfiguration: string | IndexConfiguration\n): Promise {\n firestore = cast(firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n if (\n !client._uninitializedComponentsProvider ||\n client._uninitializedComponentsProvider._offline.kind === 'memory'\n ) {\n // PORTING NOTE: We don't return an error if the user has not enabled\n // persistence since `enableIndexeddbPersistence()` can fail on the Web.\n logWarn('Cannot enable indexes when persistence is disabled');\n return Promise.resolve();\n }\n const parsedIndexes = parseIndexes(jsonOrConfiguration);\n return firestoreClientSetIndexConfiguration(client, parsedIndexes);\n}\n\nexport function parseIndexes(\n jsonOrConfiguration: string | IndexConfiguration\n): FieldIndex[] {\n const indexConfiguration =\n typeof jsonOrConfiguration === 'string'\n ? (tryParseJson(jsonOrConfiguration) as IndexConfiguration)\n : jsonOrConfiguration;\n const parsedIndexes: FieldIndex[] = [];\n\n if (Array.isArray(indexConfiguration.indexes)) {\n for (const index of indexConfiguration.indexes) {\n const collectionGroup = tryGetString(index, 'collectionGroup');\n\n const segments: IndexSegment[] = [];\n if (Array.isArray(index.fields)) {\n for (const field of index.fields) {\n const fieldPathString = tryGetString(field, 'fieldPath');\n const fieldPath = fieldPathFromDotSeparatedString(\n 'setIndexConfiguration',\n fieldPathString\n );\n\n if (field.arrayConfig === 'CONTAINS') {\n segments.push(new IndexSegment(fieldPath, IndexKind.CONTAINS));\n } else if (field.order === 'ASCENDING') {\n segments.push(new IndexSegment(fieldPath, IndexKind.ASCENDING));\n } else if (field.order === 'DESCENDING') {\n segments.push(new IndexSegment(fieldPath, IndexKind.DESCENDING));\n }\n }\n }\n\n parsedIndexes.push(\n new FieldIndex(\n FieldIndex.UNKNOWN_ID,\n collectionGroup,\n segments,\n IndexState.empty()\n )\n );\n }\n }\n return parsedIndexes;\n}\n\nfunction tryParseJson(json: string): Record {\n try {\n return JSON.parse(json);\n } catch (e) {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Failed to parse JSON: ' + (e as Error)?.message\n );\n }\n}\n\nfunction tryGetString(data: Record, property: string): string {\n if (typeof data[property] !== 'string') {\n throw new FirestoreError(\n Code.INVALID_ARGUMENT,\n 'Missing string value for: ' + property\n );\n }\n return data[property] as string;\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 2017 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { ensureFirestoreConfigured, Firestore } from '../api/database';\nimport { AggregateImpl } from '../core/aggregate';\nimport { queryToAggregateTarget, queryToTarget } from '../core/query';\nimport { AggregateSpec } from '../lite-api/aggregate_types';\nimport { Query } from '../lite-api/reference';\nimport { cast } from '../util/input_validation';\nimport { mapToArray } from '../util/obj';\n\nimport { toQueryTarget, toRunAggregationQueryRequest } from './serializer';\n\n/**\n * @internal\n * @private\n *\n * This function is for internal use only.\n *\n * Returns the `QueryTarget` representation of the given query. Returns `null`\n * if the Firestore client associated with the given query has not been\n * initialized or has been terminated.\n *\n * @param query - The Query to convert to proto representation.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function _internalQueryToProtoQueryTarget(query: Query): any {\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const serializer = client._onlineComponents?.datastore.serializer;\n if (serializer === undefined) {\n return null;\n }\n return toQueryTarget(serializer!, queryToTarget(query._query)).queryTarget;\n}\n\n/**\n * @internal\n * @private\n *\n * This function is for internal use only.\n *\n * Returns `RunAggregationQueryRequest` which contains the proto representation\n * of the given aggregation query request. Returns null if the Firestore client\n * associated with the given query has not been initialized or has been\n * terminated.\n *\n * @param query - The Query to convert to proto representation.\n * @param aggregateSpec - The set of aggregations and their aliases.\n */\nexport function _internalAggregationQueryToProtoRunAggregationQueryRequest<\n AggregateSpecType extends AggregateSpec\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n>(query: Query, aggregateSpec: AggregateSpecType): any {\n const aggregates = mapToArray(aggregateSpec, (aggregate, alias) => {\n return new AggregateImpl(\n alias,\n aggregate.aggregateType,\n aggregate._internalFieldPath\n );\n });\n const firestore = cast(query.firestore, Firestore);\n const client = ensureFirestoreConfigured(firestore);\n const serializer = client._onlineComponents?.datastore.serializer;\n if (serializer === undefined) {\n return null;\n }\n\n return toRunAggregationQueryRequest(\n serializer!,\n queryToAggregateTarget(query._query),\n aggregates,\n /* skipAliasing= */ true\n ).request;\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 { Unsubscribe } from '../api/reference_impl';\n\nimport {\n setTestingHooksSpi,\n ExistenceFilterMismatchInfo,\n TestingHooksSpi\n} from './testing_hooks_spi';\n\n/**\n * Testing hooks for use by Firestore's integration test suite to reach into the\n * SDK internals to validate logic and behavior that is not visible from the\n * public API surface.\n *\n * @internal\n */\nexport class TestingHooks {\n private constructor() {\n throw new Error('instances of this class should not be created');\n }\n\n /**\n * Registers a callback to be notified when an existence filter mismatch\n * occurs in the Watch listen stream.\n *\n * The relative order in which callbacks are notified is unspecified; do not\n * rely on any particular ordering. If a given callback is registered multiple\n * times then it will be notified multiple times, once per registration.\n *\n * @param callback the callback to invoke upon existence filter mismatch.\n *\n * @return a function that, when called, unregisters the given callback; only\n * the first invocation of the returned function does anything; all subsequent\n * invocations do nothing.\n */\n static onExistenceFilterMismatch(\n callback: ExistenceFilterMismatchCallback\n ): Unsubscribe {\n return TestingHooksSpiImpl.instance.onExistenceFilterMismatch(callback);\n }\n}\n\n/**\n * The signature of callbacks registered with\n * `TestingUtils.onExistenceFilterMismatch()`.\n *\n * The return value, if any, is ignored.\n *\n * @internal\n */\nexport type ExistenceFilterMismatchCallback = (\n info: ExistenceFilterMismatchInfo\n) => unknown;\n\n/**\n * The implementation of `TestingHooksSpi`.\n */\nclass TestingHooksSpiImpl implements TestingHooksSpi {\n private readonly existenceFilterMismatchCallbacksById = new Map<\n Symbol,\n ExistenceFilterMismatchCallback\n >();\n\n private constructor() {}\n\n static get instance(): TestingHooksSpiImpl {\n if (!testingHooksSpiImplInstance) {\n testingHooksSpiImplInstance = new TestingHooksSpiImpl();\n setTestingHooksSpi(testingHooksSpiImplInstance);\n }\n return testingHooksSpiImplInstance;\n }\n\n notifyOnExistenceFilterMismatch(info: ExistenceFilterMismatchInfo): void {\n this.existenceFilterMismatchCallbacksById.forEach(callback =>\n callback(info)\n );\n }\n\n onExistenceFilterMismatch(\n callback: ExistenceFilterMismatchCallback\n ): Unsubscribe {\n const id = Symbol();\n const callbacks = this.existenceFilterMismatchCallbacksById;\n callbacks.set(id, callback);\n return () => callbacks.delete(id);\n }\n}\n\nlet testingHooksSpiImplInstance: TestingHooksSpiImpl | null = null;\n","/**\n * @license\n * Copyright 2020 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY 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 app,\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 esm, cjs, 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"],"names":["User","constructor","uid","this","isAuthenticated","toKey","isEqual","otherUser","UNAUTHENTICATED","GOOGLE_CREDENTIALS","FIRST_PARTY","MOCK_USER","SDK_VERSION","__PRIVATE_logClient","Logger","__PRIVATE_getLogLevel","logLevel","setLogLevel","__PRIVATE_logDebug","msg","obj","LogLevel","DEBUG","args","map","__PRIVATE_argToString","debug","__PRIVATE_logError","ERROR","error","__PRIVATE_logWarn","WARN","warn","__PRIVATE_formatJSON","value","JSON","stringify","e","fail","id","__PRIVATE_messageOrContext","context","message","__PRIVATE__fail","__PRIVATE_failure","toString","undefined","Error","__PRIVATE_hardAssert","assertion","__PRIVATE_debugAssert","__PRIVATE_debugCast","Code","OK","CANCELLED","UNKNOWN","INVALID_ARGUMENT","DEADLINE_EXCEEDED","NOT_FOUND","ALREADY_EXISTS","PERMISSION_DENIED","RESOURCE_EXHAUSTED","FAILED_PRECONDITION","ABORTED","OUT_OF_RANGE","UNIMPLEMENTED","INTERNAL","UNAVAILABLE","DATA_LOSS","FirestoreError","FirebaseError","code","super","name","__PRIVATE_Deferred","promise","Promise","resolve","reject","__PRIVATE_OAuthToken","user","type","headers","Map","set","__PRIVATE_EmptyAuthCredentialsProvider","getToken","invalidateToken","start","asyncQueue","changeListener","enqueueRetryable","shutdown","__PRIVATE_EmulatorAuthCredentialsProvider","token","__PRIVATE_FirebaseAuthCredentialsProvider","__PRIVATE_authProvider","currentUser","__PRIVATE_tokenCounter","forceRefresh","auth","__PRIVATE_tokenListener","__PRIVATE_lastTokenId","__PRIVATE_guardedChangeListener","__PRIVATE_nextToken","__PRIVATE_getUser","__PRIVATE_awaitNextToken","__PRIVATE_currentTokenAttempt","async","__PRIVATE_registerAuth","addAuthTokenListener","onInit","setTimeout","getImmediate","optional","__PRIVATE_initialTokenCounter","then","__PRIVATE_tokenData","accessToken","removeAuthTokenListener","__PRIVATE_currentUid","getUid","__PRIVATE_FirstPartyToken","__PRIVATE_sessionIndex","__PRIVATE_iamToken","__PRIVATE_authTokenFactory","__PRIVATE_getAuthToken","__PRIVATE__headers","__PRIVATE_authHeaderTokenValue","__PRIVATE_FirstPartyAuthCredentialsProvider","AppCheckToken","length","__PRIVATE_FirebaseAppCheckTokenProvider","app","__PRIVATE_appCheckProvider","appCheck","__PRIVATE_latestAppCheckToken","__PRIVATE_serverAppAppCheckToken","_isFirebaseServerApp","settings","appCheckToken","onTokenChanged","tokenResult","__PRIVATE_tokenUpdated","__PRIVATE_registerAppCheck","addTokenListener","removeTokenListener","__PRIVATE_EmptyAppCheckTokenProvider","__PRIVATE_randomBytes","__PRIVATE_nBytes","crypto","self","bytes","Uint8Array","getRandomValues","__PRIVATE_i","Math","floor","random","__PRIVATE_AutoId","newId","__PRIVATE_chars","__PRIVATE_maxMultiple","__PRIVATE_autoId","charAt","__PRIVATE_primitiveComparator","left","right","__PRIVATE_compareUtf8Strings","min","__PRIVATE_leftChar","__PRIVATE_rightChar","__PRIVATE_isSurrogate","__PRIVATE_MIN_SURROGATE","__PRIVATE_MAX_SURROGATE","s","c","charCodeAt","__PRIVATE_arrayEquals","comparator","every","index","__PRIVATE_immediateSuccessor","__PRIVATE_DOCUMENT_KEY_NAME","BasePath","segments","offset","range","len","other","child","nameOrPath","slice","limit","forEach","segment","push","construct","popFirst","size","popLast","firstSegment","lastSegment","get","isEmpty","isPrefixOf","isImmediateParentOf","potentialChild","fn","end","toArray","p1","p2","comparison","compareSegments","__PRIVATE_lhs","__PRIVATE_rhs","__PRIVATE_isLhsNumeric","isNumericId","__PRIVATE_isRhsNumeric","extractNumericId","compare","startsWith","endsWith","Integer","fromString","substring","ResourcePath","canonicalString","join","toUriEncodedString","encodeURIComponent","pathComponents","path","indexOf","split","filter","emptyPath","__PRIVATE_identifierRegExp","FieldPath","isValidIdentifier","test","str","replace","isKeyField","keyField","fromServerFormat","current","__PRIVATE_addCurrentSegment","__PRIVATE_inBackticks","next","DocumentKey","fromPath","fromName","empty","collectionGroup","hasCollectionId","collectionId","getCollectionGroup","getCollectionPath","k1","k2","isDocumentKey","fromSegments","__PRIVATE_validateNonEmptyArgument","__PRIVATE_functionName","__PRIVATE_argumentName","__PRIVATE_argument","__PRIVATE_validateIsNotUsedTogether","optionName1","argument1","optionName2","argument2","__PRIVATE_validateDocumentPath","__PRIVATE_validateCollectionPath","__PRIVATE_isPlainObject","input","Object","getPrototypeOf","prototype","__PRIVATE_valueDescription","Array","__PRIVATE_customObjectName","__PRIVATE_tryGetCustomObjectType","__PRIVATE_cast","_delegate","description","__PRIVATE_validatePositiveNumber","n","property","typeString","__PRIVATE_optionalValue","result","__PRIVATE_validateJSON","json","__PRIVATE_schema","key","__PRIVATE_fieldValue","__PRIVATE_MIN_SECONDS","__PRIVATE_MS_TO_NANOS","Timestamp","now","fromMillis","Date","fromDate","date","getTime","milliseconds","seconds","nanos","nanoseconds","toDate","toMillis","_compareTo","toJSON","_jsonSchemaVersion","fromJSON","_jsonSchema","valueOf","__PRIVATE_adjustedSeconds","String","padStart","SnapshotVersion","fromTimestamp","max","timestamp","compareTo","toMicroseconds","toTimestamp","__PRIVATE_INITIAL_LARGEST_BATCH_ID","FieldIndex","indexId","fields","indexState","__PRIVATE_fieldIndexGetArraySegment","__PRIVATE_fieldIndex","find","kind","__PRIVATE_fieldIndexGetDirectionalSegments","__PRIVATE_fieldIndexSemanticComparator","cmp","__PRIVATE_indexSegmentComparator","UNKNOWN_ID","IndexSegment","fieldPath","IndexState","sequenceNumber","IndexOffset","__PRIVATE_newIndexOffsetSuccessorFromReadTime","readTime","largestBatchId","__PRIVATE_successorSeconds","__PRIVATE_successorNanos","__PRIVATE_successor","__PRIVATE_newIndexOffsetFromDocument","document","documentKey","__PRIVATE_indexOffsetComparator","__PRIVATE_PRIMARY_LEASE_LOST_ERROR_MSG","PersistenceTransaction","onCommittedListeners","addOnCommittedListener","listener","raiseOnCommittedEvent","__PRIVATE_ignoreIfPrimaryLeaseLoss","err","PersistencePromise","callback","nextCallback","catchCallback","isDone","callbackAttached","nextFn","catchFn","wrapFailure","wrapSuccess","toPromise","wrapUserFunction","waitFor","all","expectedCount","__PRIVATE_resolvedCount","done","element","or","predicates","p","predicate","__PRIVATE_isTrue","collection","f","__PRIVATE_promises","r","call","mapArray","array","results","doWhile","condition","action","process","__PRIVATE_LOG_TAG","__PRIVATE_SimpleDbTransaction","open","db","mode","objectStoreNames","transaction","__PRIVATE_IndexedDbTransactionError","aborted","oncomplete","__PRIVATE_completionDeferred","onabort","onerror","event","__PRIVATE_checkForAndReportiOSError","target","__PRIVATE_completionPromise","abort","__PRIVATE_maybeCommit","__PRIVATE_maybeV3IndexedDb","commit","store","__PRIVATE_storeName","objectStore","__PRIVATE_SimpleDbStore","__PRIVATE_SimpleDb","__PRIVATE_wrapRequest","getGlobal","indexedDB","deleteDatabase","__PRIVATE_isAvailable","isIndexedDBAvailable","__PRIVATE_isMockPersistence","__PRIVATE_ua","getUA","__PRIVATE_iOSVersion","__PRIVATE_getIOSVersion","__PRIVATE_isUnsupportedIOS","__PRIVATE_androidVersion","__PRIVATE_getAndroidVersion","__PRIVATE_isUnsupportedAndroid","__PRIVATE_env","__PRIVATE_USE_MOCK_PERSISTENCE","__PRIVATE_getStore","txn","__PRIVATE_iOSVersionRegex","match","version","Number","__PRIVATE_schemaConverter","__PRIVATE_lastClosedDbVersion","__PRIVATE_ensureDb","request","onsuccess","onblocked","onupgradeneeded","oldVersion","__PRIVATE_createOrUpgrade","__PRIVATE_versionchangelistener","onversionchange","__PRIVATE_setVersionChangeListener","__PRIVATE_versionChangeListener","runTransaction","__PRIVATE_objectStores","__PRIVATE_transactionFn","__PRIVATE_readonly","__PRIVATE_attemptNumber","__PRIVATE_transactionFnResult","catch","__PRIVATE_retryable","close","__PRIVATE_androidVersionRegex","__PRIVATE_IterationController","__PRIVATE_dbCursor","__PRIVATE_shouldStop","__PRIVATE_nextKey","__PRIVATE_skipToKey","cursor","__PRIVATE_skip","delete","__PRIVATE_actionName","cause","__PRIVATE_isIndexedDbTransactionError","put","__PRIVATE_keyOrValue","add","count","__PRIVATE_loadAll","__PRIVATE_indexOrRange","__PRIVATE_iterateOptions","options","getAll","__PRIVATE_iterateCursor","__PRIVATE_loadFirst","__PRIVATE_deleteAll","__PRIVATE_keysOnly","control","__PRIVATE_iterate","__PRIVATE_optionsOrCallback","__PRIVATE_iterateSerial","__PRIVATE_cursorRequest","primaryKey","__PRIVATE_shouldContinue","continue","controller","__PRIVATE_userResult","__PRIVATE_userPromise","__PRIVATE_indexName","direction","reverse","openKeyCursor","openCursor","__PRIVATE_reportedIOSError","__PRIVATE_IOS_ERROR","__PRIVATE_newError","__PRIVATE_IndexBackfillerScheduler","__PRIVATE_backfiller","task","__PRIVATE_schedule","stop","cancel","started","delay","enqueueAfterDelay","__PRIVATE_documentsProcessed","__PRIVATE_backfill","__PRIVATE_IndexBackfiller","localStore","persistence","__PRIVATE_maxDocumentsToProcess","__PRIVATE_writeIndexEntries","__PRIVATE_processedCollectionGroups","Set","__PRIVATE_documentsRemaining","__PRIVATE_continueLoop","indexManager","getNextCollectionGroupToUpdate","has","__PRIVATE_writeEntriesForCollectionGroup","__PRIVATE_documentsRemainingUnderCap","getMinOffsetFromCollectionGroup","__PRIVATE_existingOffset","localDocuments","getNextDocuments","__PRIVATE_nextBatch","docs","changes","updateIndexEntries","__PRIVATE_getNewOffset","__PRIVATE_newOffset","updateCollectionGroup","__PRIVATE_lookupResult","__PRIVATE_maxOffset","batchId","__PRIVATE_ListenSequence","previousValue","__PRIVATE_sequenceNumberSyncer","sequenceNumberHandler","__PRIVATE_setPreviousValue","__PRIVATE_writeNewSequenceNumber","writeSequenceNumber","__PRIVATE_externalPreviousValue","__PRIVATE_nextValue","__PRIVATE_INVALID","__PRIVATE_BATCHID_UNKNOWN","__PRIVATE_isNullOrUndefined","__PRIVATE_isNegativeZero","isSafeInteger","isInteger","MAX_SAFE_INTEGER","MIN_SAFE_INTEGER","__PRIVATE_escapeChar","__PRIVATE_encodeResourcePath","__PRIVATE_encodeSeparator","__PRIVATE_encodeSegment","__PRIVATE_resultBuf","__PRIVATE_decodeResourcePath","__PRIVATE_lastReasonableEscapeIndex","__PRIVATE_segmentBuilder","__PRIVATE_currentPiece","DbRemoteDocumentStore","__PRIVATE_DbPrimaryClientStore","__PRIVATE_DbPrimaryClientKey","__PRIVATE_DbMutationQueueStore","__PRIVATE_DbMutationQueueKeyPath","__PRIVATE_DbMutationBatchStore","__PRIVATE_DbMutationBatchKeyPath","__PRIVATE_DbMutationBatchUserMutationsIndex","__PRIVATE_DbMutationBatchUserMutationsKeyPath","__PRIVATE_newDbDocumentMutationPrefixForPath","userId","__PRIVATE_newDbDocumentMutationKey","__PRIVATE_DbDocumentMutationPlaceholder","__PRIVATE_DbDocumentMutationStore","__PRIVATE_DbRemoteDocumentKeyPath","__PRIVATE_DbRemoteDocumentDocumentKeyIndex","__PRIVATE_DbRemoteDocumentDocumentKeyIndexPath","__PRIVATE_DbRemoteDocumentCollectionGroupIndex","__PRIVATE_DbRemoteDocumentCollectionGroupIndexPath","__PRIVATE_DbRemoteDocumentGlobalStore","__PRIVATE_DbRemoteDocumentGlobalKey","__PRIVATE_DbTargetStore","__PRIVATE_DbTargetQueryTargetsIndexName","__PRIVATE_DbTargetQueryTargetsKeyPath","__PRIVATE_DbTargetDocumentStore","__PRIVATE_DbTargetDocumentKeyPath","__PRIVATE_DbTargetDocumentDocumentTargetsIndex","__PRIVATE_DbTargetDocumentDocumentTargetsKeyPath","__PRIVATE_DbTargetGlobalKey","__PRIVATE_DbTargetGlobalStore","__PRIVATE_DbCollectionParentStore","__PRIVATE_DbCollectionParentKeyPath","__PRIVATE_DbClientMetadataStore","__PRIVATE_DbClientMetadataKeyPath","__PRIVATE_DbBundleStore","__PRIVATE_DbBundleKeyPath","__PRIVATE_DbNamedQueryStore","__PRIVATE_DbNamedQueryKeyPath","__PRIVATE_DbIndexConfigurationStore","__PRIVATE_DbIndexConfigurationKeyPath","__PRIVATE_DbIndexConfigurationCollectionGroupIndex","__PRIVATE_DbIndexConfigurationCollectionGroupIndexPath","__PRIVATE_DbIndexStateStore","__PRIVATE_DbIndexStateKeyPath","__PRIVATE_DbIndexStateSequenceNumberIndex","__PRIVATE_DbIndexStateSequenceNumberIndexPath","__PRIVATE_DbIndexEntryStore","__PRIVATE_DbIndexEntryKeyPath","__PRIVATE_DbIndexEntryDocumentKeyIndex","__PRIVATE_DbIndexEntryDocumentKeyIndexPath","__PRIVATE_DbDocumentOverlayStore","__PRIVATE_DbDocumentOverlayKeyPath","__PRIVATE_DbDocumentOverlayCollectionPathOverlayIndex","__PRIVATE_DbDocumentOverlayCollectionPathOverlayIndexPath","__PRIVATE_DbDocumentOverlayCollectionGroupOverlayIndex","__PRIVATE_DbDocumentOverlayCollectionGroupOverlayIndexPath","__PRIVATE_DbGlobalsStore","__PRIVATE_DbGlobalsKeyPath","__PRIVATE_V11_STORES","__PRIVATE_DbRemoteDocumentStoreLegacy","__PRIVATE_V12_STORES","__PRIVATE_V13_STORES","__PRIVATE_V14_STORES","__PRIVATE_V15_STORES","__PRIVATE_V16_STORES","__PRIVATE_V17_STORES","__PRIVATE_V18_STORES","__PRIVATE_IndexedDbTransaction","__PRIVATE_simpleDbTransaction","currentSequenceNumber","__PRIVATE_indexedDbTransaction","__PRIVATE_objectSize","hasOwnProperty","__PRIVATE_mapToArray","SortedMap","root","LLRBNode","EMPTY","insert","copy","BLACK","remove","node","__PRIVATE_prunedNodes","minKey","maxKey","inorderTraversal","k","v","__PRIVATE_descriptions","reverseTraversal","getIterator","SortedMapIterator","getIteratorFrom","getReverseIterator","getReverseIteratorFrom","startKey","isReverse","nodeStack","getNext","pop","hasNext","peek","color","RED","fixUp","removeMin","isRed","moveRedLeft","__PRIVATE_smallest","rotateRight","moveRedRight","rotateLeft","colorFlip","__PRIVATE_nl","__PRIVATE_nr","checkMaxDepth","__PRIVATE_blackDepth","check","pow","LLRBEmptyNode","SortedSet","data","elem","first","last","cb","forEachInRange","iter","forEachWhile","firstAfterOrEqual","SortedSetIterator","unionWith","__PRIVATE_thisIt","__PRIVATE_otherIt","__PRIVATE_thisElem","__PRIVATE_otherElem","__PRIVATE_res","targetId","__PRIVATE_advanceIterator","__PRIVATE_it","FieldMask","sort","extraFields","__PRIVATE_mergedMaskSet","covers","__PRIVATE_fieldMaskPath","l","__PRIVATE_Base64DecodeError","__PRIVATE_isBase64Available","atob","ByteString","binaryString","fromBase64String","base64","__PRIVATE_decodeBase64","__PRIVATE_encoded","DOMException","fromUint8Array","__PRIVATE_binaryStringFromUint8Array","fromCharCode","Symbol","iterator","toBase64","__PRIVATE_encodeBase64","raw","btoa","toUint8Array","__PRIVATE_uint8ArrayFromBinaryString","buffer","approximateByteSize","EMPTY_BYTE_STRING","__PRIVATE_ISO_TIMESTAMP_REG_EXP","RegExp","__PRIVATE_normalizeTimestamp","__PRIVATE_fraction","exec","__PRIVATE_nanoStr","substr","__PRIVATE_parsedDate","__PRIVATE_normalizeNumber","__PRIVATE_normalizeByteString","blob","__PRIVATE_SERVER_TIMESTAMP_SENTINEL","__PRIVATE_TYPE_KEY","__PRIVATE_PREVIOUS_VALUE_KEY","__PRIVATE_LOCAL_WRITE_TIME_KEY","__PRIVATE_isServerTimestamp","mapValue","stringValue","__PRIVATE_getPreviousValue","__PRIVATE_getLocalWriteTime","localWriteTime","timestampValue","DatabaseInfo","databaseId","appId","persistenceKey","host","ssl","forceLongPolling","autoDetectLongPolling","longPollingOptions","useFetchStreams","isUsingEmulator","__PRIVATE_DEFAULT_DATABASE_NAME","DatabaseId","projectId","database","isDefaultDatabase","__PRIVATE_MAX_VALUE_TYPE","MAX_VALUE","__type__","__PRIVATE_VECTOR_VALUE_SENTINEL","__PRIVATE_VECTOR_MAP_VECTORS_KEY","MIN_VALUE","nullValue","__PRIVATE_typeOrder","__PRIVATE_isMaxValue","__PRIVATE_isVectorValue","__PRIVATE_valueEquals","__PRIVATE_leftType","booleanValue","__PRIVATE_timestampEquals","__PRIVATE_leftTimestamp","__PRIVATE_rightTimestamp","__PRIVATE_blobEquals","bytesValue","referenceValue","__PRIVATE_geoPointEquals","geoPointValue","latitude","longitude","__PRIVATE_numberEquals","integerValue","__PRIVATE_n1","doubleValue","__PRIVATE_n2","isNaN","arrayValue","values","__PRIVATE_objectEquals","__PRIVATE_leftMap","__PRIVATE_rightMap","__PRIVATE_arrayValueContains","__PRIVATE_haystack","__PRIVATE_needle","__PRIVATE_valueCompare","__PRIVATE_rightType","__PRIVATE_compareNumbers","__PRIVATE_leftNumber","__PRIVATE_rightNumber","__PRIVATE_compareTimestamps","__PRIVATE_compareBlobs","__PRIVATE_leftBytes","__PRIVATE_rightBytes","__PRIVATE_compareReferences","__PRIVATE_leftPath","__PRIVATE_rightPath","__PRIVATE_leftSegments","__PRIVATE_rightSegments","__PRIVATE_compareGeoPoints","__PRIVATE_compareArrays","__PRIVATE_compareVectors","__PRIVATE_leftArrayValue","__PRIVATE_rightArrayValue","__PRIVATE_lengthCompare","__PRIVATE_compareMaps","__PRIVATE_leftKeys","keys","__PRIVATE_rightKeys","__PRIVATE_keyCompare","__PRIVATE_leftArray","__PRIVATE_rightArray","canonicalId","__PRIVATE_canonifyValue","__PRIVATE_canonifyTimestamp","__PRIVATE_normalizedTimestamp","__PRIVATE_canonifyByteString","byteString","__PRIVATE_canonifyReference","__PRIVATE_canonifyGeoPoint","__PRIVATE_geoPoint","__PRIVATE_canonifyArray","__PRIVATE_canonifyMap","__PRIVATE_sortedKeys","__PRIVATE_estimateByteSize","__PRIVATE_estimateArrayByteSize","reduce","__PRIVATE_previousSize","__PRIVATE_estimateMapByteSize","val","__PRIVATE_refValue","isArray","__PRIVATE_isNullValue","__PRIVATE_isNanValue","__PRIVATE_isMapValue","__PRIVATE_deepClone","source","__PRIVATE_MIN_VECTOR_VALUE","__PRIVATE_valuesGetLowerBound","NaN","__PRIVATE_valuesGetUpperBound","__PRIVATE_lowerBoundCompare","inclusive","__PRIVATE_upperBoundCompare","ObjectValue","field","__PRIVATE_currentLevel","getFieldsMap","setAll","parent","__PRIVATE_upserts","__PRIVATE_deletes","__PRIVATE_fieldsMap","applyChanges","__PRIVATE_nestedValue","__PRIVATE_inserts","clone","__PRIVATE_extractFieldMask","__PRIVATE_currentPath","__PRIVATE_nestedFields","__PRIVATE_nestedPath","MutableDocument","documentType","createTime","documentState","newInvalidDocument","newFoundDocument","newNoDocument","newUnknownDocument","convertToFoundDocument","convertToNoDocument","convertToUnknownDocument","setHasCommittedMutations","setHasLocalMutations","setReadTime","hasLocalMutations","hasCommittedMutations","hasPendingWrites","isValidDocument","isFoundDocument","isNoDocument","isUnknownDocument","mutableCopy","Bound","position","__PRIVATE_boundCompareToDocument","bound","orderBy","doc","__PRIVATE_orderByComponent","component","dir","__PRIVATE_boundEquals","OrderBy","__PRIVATE_orderByEquals","Filter","FieldFilter","op","create","createKeyFieldInFilter","__PRIVATE_KeyFieldFilter","__PRIVATE_ArrayContainsFilter","__PRIVATE_InFilter","__PRIVATE_NotInFilter","__PRIVATE_ArrayContainsAnyFilter","__PRIVATE_KeyFieldInFilter","__PRIVATE_KeyFieldNotInFilter","matches","matchesComparison","operator","isInequality","getFlattenedFilters","getFilters","CompositeFilter","filters","__PRIVATE_memoizedFlattenedFilters","__PRIVATE_compositeFilterIsConjunction","__PRIVATE_subfilter","concat","assign","compositeFilter","__PRIVATE_compositeFilterIsDisjunction","__PRIVATE_compositeFilterIsFlatConjunction","__PRIVATE_compositeFilterIsFlat","__PRIVATE_canonifyFilter","__PRIVATE_canonicalIdsString","__PRIVATE_filterEquals","__PRIVATE_f1","__PRIVATE_f2","__PRIVATE_fieldFilterEquals","__PRIVATE_compositeFilterEquals","__PRIVATE_f1Filter","__PRIVATE_compositeFilterWithAddedFilters","__PRIVATE_otherFilters","__PRIVATE_mergedFilters","__PRIVATE_stringifyFilter","__PRIVATE_stringifyFieldFilter","__PRIVATE_stringifyCompositeFilter","__PRIVATE_extractDocumentKeysFromArrayValue","some","__PRIVATE_TargetImpl","startAt","endAt","__PRIVATE_memoizedCanonicalId","__PRIVATE_newTarget","__PRIVATE_canonifyTarget","__PRIVATE_targetImpl","o","__PRIVATE_canonifyOrderBy","__PRIVATE_targetEquals","__PRIVATE_targetIsDocumentTarget","__PRIVATE_targetGetFieldFiltersForPath","__PRIVATE_targetGetAscendingBound","fieldFilter","__PRIVATE_filterValue","__PRIVATE_filterInclusive","__PRIVATE_cursorValue","__PRIVATE_targetGetDescendingBound","__PRIVATE_QueryImpl","explicitOrderBy","limitType","__PRIVATE_memoizedNormalizedOrderBy","__PRIVATE_memoizedTarget","__PRIVATE_memoizedAggregateTarget","__PRIVATE_newQuery","__PRIVATE_newQueryForPath","__PRIVATE_queryMatchesAllDocuments","query","__PRIVATE_isCollectionGroupQuery","__PRIVATE_queryNormalizedOrderBy","__PRIVATE_queryImpl","__PRIVATE_fieldsNormalized","__PRIVATE_lastDirection","__PRIVATE_inequalityFields","__PRIVATE_getInequalityFilterFields","__PRIVATE_queryToTarget","__PRIVATE__queryToTarget","__PRIVATE_queryToAggregateTarget","__PRIVATE_orderBys","__PRIVATE_queryWithAddedFilter","__PRIVATE_newFilters","__PRIVATE_queryWithLimit","__PRIVATE_queryEquals","__PRIVATE_canonifyQuery","__PRIVATE_stringifyQuery","__PRIVATE_stringifyTarget","__PRIVATE_stringifyOrderBy","__PRIVATE_queryMatches","__PRIVATE_queryMatchesPathAndCollectionGroup","__PRIVATE_docPath","__PRIVATE_queryMatchesOrderBy","__PRIVATE_queryMatchesFilters","__PRIVATE_queryMatchesBounds","__PRIVATE_boundSortsBeforeDocument","__PRIVATE_boundSortsAfterDocument","__PRIVATE_queryCollectionGroup","__PRIVATE_newQueryComparator","__PRIVATE_d1","__PRIVATE_d2","__PRIVATE_comparedOnKeyField","comp","__PRIVATE_compareDocs","__PRIVATE_compareDocumentsByField","v1","v2","ObjectMap","mapKeyFn","equalsFn","inner","innerSize","__PRIVATE_otherKey","splice","_","entries","__PRIVATE_EMPTY_MUTABLE_DOCUMENT_MAP","__PRIVATE_mutableDocumentMap","__PRIVATE_EMPTY_DOCUMENT_MAP","documentMap","__PRIVATE_convertOverlayedDocumentMapToDocumentMap","documents","overlayedDocument","__PRIVATE_newOverlayMap","__PRIVATE_newDocumentKeyMap","__PRIVATE_newMutationMap","__PRIVATE_EMPTY_DOCUMENT_VERSION_MAP","__PRIVATE_EMPTY_DOCUMENT_KEY_SET","__PRIVATE_documentKeySet","__PRIVATE_EMPTY_TARGET_ID_SET","__PRIVATE_targetIdSet","__PRIVATE_toDouble","serializer","useProto3Json","Infinity","__PRIVATE_toInteger","toNumber","TransformOperation","__PRIVATE_applyTransformOperationToLocalView","transform","__PRIVATE_ServerTimestampTransform","serverTimestamp","__PRIVATE_TYPE_KEY$1","__PRIVATE_ArrayUnionTransformOperation","__PRIVATE_applyArrayUnionTransformOperation","__PRIVATE_ArrayRemoveTransformOperation","__PRIVATE_applyArrayRemoveTransformOperation","__PRIVATE_applyNumericIncrementTransformOperationToLocalView","__PRIVATE_baseValue","__PRIVATE_computeTransformOperationBaseValue","sum","asNumber","__PRIVATE_operand","__PRIVATE_applyTransformOperationToRemoteDocument","__PRIVATE_transformResult","__PRIVATE_NumericIncrementTransformOperation","__PRIVATE_isNumber","__PRIVATE_isDouble","elements","__PRIVATE_coercedFieldValuesArray","__PRIVATE_toUnion","__PRIVATE_toRemove","FieldTransform","__PRIVATE_fieldTransformEquals","__PRIVATE_transformOperationEquals","MutationResult","transformResults","Precondition","updateTime","exists","none","isNone","__PRIVATE_preconditionIsValidForDocument","precondition","Mutation","__PRIVATE_calculateOverlayMutation","mask","__PRIVATE_DeleteMutation","__PRIVATE_SetMutation","__PRIVATE_docValue","__PRIVATE_patchValue","__PRIVATE_maskSet","__PRIVATE_PatchMutation","__PRIVATE_mutationApplyToRemoteDocument","mutation","__PRIVATE_mutationResult","__PRIVATE_setMutationApplyToRemoteDocument","__PRIVATE_newData","__PRIVATE_serverTransformResults","fieldTransforms","__PRIVATE_patchMutationApplyToRemoteDocument","__PRIVATE_getPatch","__PRIVATE_deleteMutationApplyToRemoteDocument","__PRIVATE_mutationApplyToLocalView","__PRIVATE_previousMask","__PRIVATE_setMutationApplyToLocalView","__PRIVATE_localTransformResults","__PRIVATE_patchMutationApplyToLocalView","fieldMask","__PRIVATE_deleteMutationApplyToLocalView","__PRIVATE_mutationExtractBaseValue","__PRIVATE_baseObject","__PRIVATE_fieldTransform","__PRIVATE_existingValue","__PRIVATE_coercedValue","__PRIVATE_mutationEquals","__PRIVATE_fieldTransformsAreEqual","getFieldMask","newValue","__PRIVATE_mutableDocument","__PRIVATE_serverTransformResultCount","__PRIVATE_fieldTransformCount","__PRIVATE_VerifyMutation","MutationBatch","baseMutations","mutations","applyToRemoteDocument","batchResult","mutationResults","applyToLocalView","mutatedFields","applyToLocalDocumentSet","documentsWithoutRemoteVersion","overlays","m","__PRIVATE_overlay","MutationBatchResult","batch","commitVersion","docVersions","from","__PRIVATE_mutationsSent","__PRIVATE_resultsReceived","__PRIVATE_versionMap","__PRIVATE_documentVersionMap","Overlay","getKey","__PRIVATE_AggregateImpl","alias","aggregateType","ExistenceFilter","unchangedNames","__PRIVATE_RpcCode","RpcCode","__PRIVATE_isPermanentError","__PRIVATE_mapCodeFromRpcCode","__PRIVATE_testingHooksSpi","__PRIVATE_newTextEncoder","TextEncoder","__PRIVATE_MAX_64_BIT_UNSIGNED_INTEGER","__PRIVATE_getMd5HashValue","__PRIVATE_encodedValue","encode","__PRIVATE_md5","Md5","update","digest","__PRIVATE_get64BitUints","Bytes","__PRIVATE_dataView","DataView","__PRIVATE_chunk1","getUint32","__PRIVATE_chunk2","__PRIVATE_chunk3","__PRIVATE_chunk4","BloomFilter","bitmap","padding","hashCount","__PRIVATE_BloomFilterError","__PRIVATE_bitCount","__PRIVATE_bitCountInInteger","fromNumber","__PRIVATE_getBitIndex","__PRIVATE_num1","__PRIVATE_num2","__PRIVATE_hashIndex","__PRIVATE_hashValue","multiply","getBits","modulo","__PRIVATE_isBitSet","mightContain","__PRIVATE_md5HashedValue","__PRIVATE_hash1","__PRIVATE_hash2","contains","ceil","bloomFilter","item","__PRIVATE_setBit","__PRIVATE_indexOfByte","RemoteEvent","snapshotVersion","targetChanges","targetMismatches","documentUpdates","resolvedLimboDocuments","createSynthesizedRemoteEventForCurrentChange","resumeToken","TargetChange","createSynthesizedTargetChangeForCurrentChange","addedDocuments","modifiedDocuments","removedDocuments","__PRIVATE_DocumentWatchChange","__PRIVATE_updatedTargetIds","removedTargetIds","__PRIVATE_newDoc","__PRIVATE_ExistenceFilterChange","__PRIVATE_existenceFilter","__PRIVATE_WatchTargetChange","state","targetIds","__PRIVATE_TargetState","__PRIVATE_pendingResponses","__PRIVATE_documentChanges","__PRIVATE_snapshotChangesMap","__PRIVATE__current","__PRIVATE__hasPendingChanges","__PRIVATE__resumeToken","__PRIVATE_isPending","__PRIVATE_hasPendingChanges","__PRIVATE_updateResumeToken","__PRIVATE_toTargetChange","changeType","__PRIVATE_clearPendingChanges","__PRIVATE_addDocumentChange","__PRIVATE_removeDocumentChange","__PRIVATE_recordPendingTargetRequest","__PRIVATE_recordTargetResponse","__PRIVATE_markCurrent","__PRIVATE_WatchChangeAggregator","__PRIVATE_metadataProvider","__PRIVATE_pendingDocumentUpdates","__PRIVATE_pendingDocumentUpdatesByTarget","__PRIVATE_documentTargetMap","__PRIVATE_pendingDocumentTargetMapping","__PRIVATE_pendingTargetResets","__PRIVATE_handleDocumentChange","__PRIVATE_docChange","__PRIVATE_addDocumentToTarget","__PRIVATE_removeDocumentFromTarget","__PRIVATE_handleTargetChange","targetChange","forEachTarget","__PRIVATE_targetState","__PRIVATE_ensureTargetState","__PRIVATE_isActiveTarget","removeTarget","__PRIVATE_resetTarget","__PRIVATE_targetStates","__PRIVATE_handleExistenceFilter","__PRIVATE_watchChange","targetData","__PRIVATE_targetDataForActiveTarget","__PRIVATE_currentSize","__PRIVATE_getCurrentDocumentCountForTarget","__PRIVATE_parseBloomFilter","status","__PRIVATE_applyBloomFilter","purpose","__PRIVATE_notifyOnExistenceFilterMismatch","__PRIVATE_createExistenceFilterMismatchInfoForTestingHooks","localCacheCount","__PRIVATE_bloomFilterStatus","existenceFilterCount","applied","bitmapLength","bits","__PRIVATE_getDatabaseId","__PRIVATE_normalizedBitmap","__PRIVATE_currentCount","__PRIVATE_filterRemovedDocuments","__PRIVATE_existingKeys","getRemoteKeysForTarget","__PRIVATE_removalCount","documentPath","__PRIVATE_createRemoteEvent","__PRIVATE_ensureDocumentUpdateByTarget","__PRIVATE_targetContainsDocument","__PRIVATE_targets","__PRIVATE_isOnlyLimboTarget","remoteEvent","__PRIVATE_ensureDocumentTargetMapping","__PRIVATE_updatedDocument","__PRIVATE_targetMapping","__PRIVATE_targetActive","__PRIVATE_getTargetDataForTarget","__PRIVATE_DIRECTIONS","__PRIVATE_dirs","__PRIVATE_OPERATORS","__PRIVATE_ops","__PRIVATE_COMPOSITE_OPERATORS","JsonProtoSerializer","__PRIVATE_toInt32Proto","toISOString","__PRIVATE_toBytes","__PRIVATE_toVersion","__PRIVATE_fromVersion","__PRIVATE_toResourceName","__PRIVATE_toResourcePath","__PRIVATE_resourcePath","__PRIVATE_fullyQualifiedPrefixPath","__PRIVATE_fromResourceName","__PRIVATE_resource","__PRIVATE_isValidResourceName","__PRIVATE_toName","__PRIVATE_extractLocalPathFromResourceName","__PRIVATE_toQueryPath","__PRIVATE_fromQueryPath","__PRIVATE_resourceName","__PRIVATE_getEncodedDatabaseId","__PRIVATE_toMutationDocument","__PRIVATE_fromDocument","__PRIVATE_fromBatchGetDocumentsResponse","__PRIVATE_fromFound","found","__PRIVATE_fromMissing","missing","__PRIVATE_fromWatchChange","__PRIVATE_change","__PRIVATE_fromWatchTargetChangeState","targetChangeType","__PRIVATE_fromBytes","Buffer","__PRIVATE_causeProto","__PRIVATE_fromRpcStatus","documentChange","__PRIVATE_entityChange","documentDelete","__PRIVATE_docDelete","documentRemove","__PRIVATE_docRemove","toMutation","updateMask","__PRIVATE_toDocumentMask","__PRIVATE_mutationType","verify","updateTransforms","__PRIVATE_toFieldTransform","setToServerValue","appendMissingElements","removeAllFromArray","increment","currentDocument","__PRIVATE_toPrecondition","__PRIVATE_fromMutation","proto","__PRIVATE_fromPrecondition","__PRIVATE_fromFieldTransform","__PRIVATE_fromDocumentMask","__PRIVATE_paths","fieldPaths","__PRIVATE_fromWriteResults","__PRIVATE_protos","commitTime","__PRIVATE_fromWriteResult","__PRIVATE_toDocumentsTarget","__PRIVATE_toQueryTarget","__PRIVATE_queryTarget","structuredQuery","allDescendants","where","__PRIVATE_toFilters","__PRIVATE_toFilter","__PRIVATE_toOrder","order","__PRIVATE_toPropertyOrder","__PRIVATE_toFieldPathReference","__PRIVATE_toDirection","__PRIVATE_toStartAtCursor","before","__PRIVATE_toEndAtCursor","__PRIVATE_toRunAggregationQueryRequest","__PRIVATE_aggregates","__PRIVATE_skipAliasing","ft","__PRIVATE_aliasMap","aggregations","__PRIVATE_aggregationNum","__PRIVATE_aggregate","__PRIVATE_serverAlias","avg","structuredAggregationQuery","__PRIVATE_convertQueryTargetToQuery","__PRIVATE_fromCount","__PRIVATE_filterBy","__PRIVATE_fromFilters","__PRIVATE_fromFilter","__PRIVATE_fromOrder","__PRIVATE_fromPropertyOrder","__PRIVATE_fromFieldPathReference","__PRIVATE_fromDirection","__PRIVATE_fromInt32Proto","__PRIVATE_fromStartAtCursor","__PRIVATE_fromEndAtCursor","__PRIVATE_toListenRequestLabels","__PRIVATE_toLabel","unaryFilter","__PRIVATE_fromUnaryFilter","__PRIVATE_nanField","__PRIVATE_nullField","__PRIVATE_notNanField","__PRIVATE_notNullField","__PRIVATE_fromFieldFilter","__PRIVATE_fromOperatorName","__PRIVATE_fromCompositeFilter","__PRIVATE_fromCompositeOperatorName","__PRIVATE_toOperatorName","__PRIVATE_toCompositeOperatorName","__PRIVATE_fieldReference","__PRIVATE_toUnaryOrFieldFilter","__PRIVATE_toCompositeFilter","__PRIVATE_canonicalFields","TargetData","lastLimboFreeSnapshotVersion","withSequenceNumber","withResumeToken","withExpectedCount","withLastLimboFreeSnapshotVersion","__PRIVATE_LocalSerializer","__PRIVATE_remoteSerializer","__PRIVATE_fromDbRemoteDocument","__PRIVATE_localSerializer","__PRIVATE_remoteDoc","noDocument","__PRIVATE_fromDbTimestamp","unknownDocument","__PRIVATE_fromDbTimestampKey","__PRIVATE_dbTimestampKey","__PRIVATE_toDbRemoteDocument","prefixPath","documentId","__PRIVATE_toDbTimestampKey","__PRIVATE_toDocument","__PRIVATE_toDbTimestamp","__PRIVATE_dbTimestamp","__PRIVATE_fromDbMutationBatch","__PRIVATE_dbBatch","__PRIVATE_currentMutation","__PRIVATE_transformMutation","localWriteTimeMs","__PRIVATE_fromDbTarget","__PRIVATE_dbTarget","__PRIVATE_isDocumentQuery","__PRIVATE_dbQuery","__PRIVATE_fromDocumentsTarget","__PRIVATE_documentsTarget","__PRIVATE_fromQueryTarget","lastListenSequenceNumber","__PRIVATE_toDbTarget","__PRIVATE_dbLastLimboFreeTimestamp","__PRIVATE_queryProto","__PRIVATE_fromBundledQuery","bundledQuery","__PRIVATE_fromDbDocumentOverlay","__PRIVATE_dbDocumentOverlay","overlayMutation","__PRIVATE_toDbDocumentOverlayKey","__PRIVATE_docKey","__PRIVATE_docId","__PRIVATE_toDbIndexState","__PRIVATE_IndexedDbBundleCache","getBundleMetadata","bundleId","__PRIVATE_bundlesStore","bundle","__PRIVATE_fromDbBundle","__PRIVATE_dbBundle","saveBundleMetadata","__PRIVATE_bundleMetadata","__PRIVATE_toDbBundle","metadata","getNamedQuery","queryName","__PRIVATE_namedQueriesStore","__PRIVATE_fromDbNamedQuery","__PRIVATE_dbNamedQuery","saveNamedQuery","__PRIVATE_toDbNamedQuery","__PRIVATE_IndexedDbDocumentOverlayCache","__PRIVATE_forUser","getOverlay","__PRIVATE_documentOverlayStore","__PRIVATE_dbOverlay","getOverlays","saveOverlays","__PRIVATE_saveOverlay","removeOverlaysForBatchId","documentKeys","__PRIVATE_collectionPaths","collectionPath","IDBKeyRange","getOverlaysForCollection","sinceBatchId","POSITIVE_INFINITY","__PRIVATE_dbOverlays","getOverlaysForCollectionGroup","__PRIVATE_currentBatchId","__PRIVATE_toDbDocumentOverlay","__PRIVATE_IndexedDbGlobalsCache","__PRIVATE_globalsStore","getSessionToken","global","setSessionToken","sessionToken","__PRIVATE_FirestoreIndexValueWriter","__PRIVATE_writeIndexValue","__PRIVATE_encoder","__PRIVATE_writeIndexValueAux","__PRIVATE_writeInfinity","__PRIVATE_indexValue","__PRIVATE_writeValueTypeLabel","__PRIVATE_writeNumber","__PRIVATE_writeString","__PRIVATE_writeIndexString","__PRIVATE_writeTruncationMarker","__PRIVATE_writeBytes","__PRIVATE_writeIndexEntityRef","__PRIVATE_writeIndexVector","__PRIVATE_writeIndexMap","__PRIVATE_writeIndexArray","__PRIVATE_stringIndexValue","__PRIVATE_writeUnlabeledIndexString","__PRIVATE_mapIndexValue","__PRIVATE_arrayIndexValue","__PRIVATE_ESCAPE2","__PRIVATE_numberOfLeadingZerosInByte","x","__PRIVATE_zeros","__PRIVATE_unsignedNumLength","__PRIVATE_numBits","__PRIVATE_numberOfLeadingZeros","__PRIVATE_leadingZeros","__PRIVATE_OrderedCodeWriter","__PRIVATE_writeBytesAscending","__PRIVATE_byte","__PRIVATE_writeByteAscending","__PRIVATE_writeSeparatorAscending","__PRIVATE_writeBytesDescending","__PRIVATE_writeByteDescending","__PRIVATE_writeSeparatorDescending","__PRIVATE_writeUtf8Ascending","__PRIVATE_sequence","charCode","__PRIVATE_codePoint","codePointAt","__PRIVATE_writeUtf8Descending","__PRIVATE_writeNumberAscending","__PRIVATE_toOrderedBits","__PRIVATE_ensureAvailable","__PRIVATE_writeNumberDescending","__PRIVATE_writeInfinityAscending","__PRIVATE_writeEscapedByteAscending","__PRIVATE_writeInfinityDescending","__PRIVATE_writeEscapedByteDescending","reset","seed","__PRIVATE_encodedBytes","__PRIVATE_doubleToLongBits","__PRIVATE_dv","ArrayBuffer","setFloat64","__PRIVATE_isNegative","b","__PRIVATE_masked","__PRIVATE_minCapacity","__PRIVATE_newLength","__PRIVATE_newBuffer","__PRIVATE_AscendingIndexByteEncoder","__PRIVATE_orderedCode","__PRIVATE_DescendingIndexByteEncoder","__PRIVATE_IndexByteEncoder","__PRIVATE_ascending","__PRIVATE_descending","__PRIVATE_forKind","__PRIVATE_IndexEntry","__PRIVATE__indexId","__PRIVATE__documentKey","__PRIVATE__arrayValue","__PRIVATE__directionalValue","__PRIVATE_currentLength","__PRIVATE_dbIndexEntry","orderedDocumentKey","__PRIVATE_encodeKeySafeBytes","directionalValue","__PRIVATE_dbIndexEntryKey","entry","__PRIVATE_indexEntryComparator","__PRIVATE_compareByteArrays","isSafariOrWebkit","__PRIVATE_encodeUint8ArrayToSortableString","__PRIVATE_decodeKeySafeBytes","__PRIVATE_decodeSortableStringToUint8Array","__PRIVATE_uint8array","__PRIVATE_TargetIndexMatcher","__PRIVATE_equalityFilters","__PRIVATE_inequalityFilters","__PRIVATE_hasMultipleInequality","__PRIVATE_servedByIndex","__PRIVATE_arraySegment","__PRIVATE_hasMatchingEqualityFilter","__PRIVATE_equalitySegments","__PRIVATE_segmentIndex","__PRIVATE_orderBysIndex","__PRIVATE_inequalityFilter","__PRIVATE_matchesFilter","__PRIVATE_matchesOrderBy","__PRIVATE_buildTargetIndex","__PRIVATE_uniqueFields","__PRIVATE_isArrayOperator","__PRIVATE_computeInExpansion","__PRIVATE_expandedFilters","__PRIVATE_getDnfTerms","__PRIVATE_computeDistributedNormalForm","__PRIVATE_isDisjunctiveNormalForm","__PRIVATE_isSingleFieldFilter","__PRIVATE_isFlatConjunction","__PRIVATE_isDisjunctionOfFieldFiltersAndFlatConjunctions","__PRIVATE_subFilter","__PRIVATE_newFilter","__PRIVATE_applyAssociation","__PRIVATE_runningResult","__PRIVATE_applyDistribution","__PRIVATE_applyDistributionFieldFilters","__PRIVATE_applyDistributionFieldAndCompositeFilters","__PRIVATE_applyDistributionCompositeFilters","__PRIVATE_disjunctionSide","__PRIVATE_otherSide","__PRIVATE_updatedFilters","__PRIVATE_newSubfilters","__PRIVATE_MemoryIndexManager","__PRIVATE_MemoryCollectionParentIndex","addToCollectionParentIndex","__PRIVATE_collectionParentIndex","getCollectionParents","getEntries","addFieldIndex","deleteFieldIndex","deleteAllFieldIndexes","createTargetIndexes","getDocumentsMatchingTarget","getIndexType","getFieldIndexes","getMinOffset","parentPath","__PRIVATE_existingParents","__PRIVATE_added","__PRIVATE_EMPTY_VALUE","__PRIVATE_IndexedDbIndexManager","t","__PRIVATE_collectionParentsCache","__PRIVATE_collectionParent","__PRIVATE_collectionParentsStore","__PRIVATE_parentPaths","indexes","__PRIVATE_indexConfigurationStore","__PRIVATE_dbIndex","__PRIVATE_toDbIndexConfiguration","states","__PRIVATE_indexStateStore","__PRIVATE_indexEntriesStore","__PRIVATE_getSubTargets","__PRIVATE_subTarget","__PRIVATE_indexEntries","__PRIVATE_canServeTarget","__PRIVATE_getFieldIndex","__PRIVATE_fieldIndexToString","__PRIVATE_arrayValues","__PRIVATE_targetGetArrayValues","__PRIVATE_notInValues","__PRIVATE_targetGetNotInValues","lowerBound","__PRIVATE_targetGetLowerBound","__PRIVATE_segmentBound","upperBound","__PRIVATE_targetGetUpperBound","__PRIVATE_lowerBoundEncoded","__PRIVATE_encodeBound","__PRIVATE_upperBoundEncoded","__PRIVATE_notInEncoded","__PRIVATE_encodeValues","__PRIVATE_indexRanges","__PRIVATE_generateIndexRanges","__PRIVATE_indexRange","__PRIVATE_subTargets","__PRIVATE_targetToDnfSubTargets","__PRIVATE_term","__PRIVATE_lowerBounds","__PRIVATE_lowerBoundInclusive","__PRIVATE_upperBounds","__PRIVATE_upperBoundInclusive","__PRIVATE_totalScans","__PRIVATE_scansPerArrayElement","__PRIVATE_encodeSingleElement","__PRIVATE_generateLowerBound","__PRIVATE_generateUpperBound","__PRIVATE_notInBound","__PRIVATE_notIn","createRange","__PRIVATE_targetIndexMatcher","candidate","__PRIVATE_indexType","__PRIVATE_targetGetSegmentCount","__PRIVATE_hasArraySegment","__PRIVATE_targetHasLimit","__PRIVATE_encodeDirectionalElements","__PRIVATE_directionalEncoder","__PRIVATE_INSTANCE","__PRIVATE_encodeDirectionalKey","__PRIVATE_fieldIndexGetKeyOrder","__PRIVATE_directionalSegments","__PRIVATE_encoders","__PRIVATE_valueIdx","__PRIVATE_isInFilter","__PRIVATE_expandIndexValues","__PRIVATE_getEncodedBytes","prefixes","__PRIVATE_arrayElement","prefix","__PRIVATE_clonedEncoder","__PRIVATE_indexConfigs","__PRIVATE_indexConfig","__PRIVATE_fromDbIndexConfiguration","__PRIVATE_decodedState","__PRIVATE_decodedSegments","__PRIVATE_getNextSequenceNumber","__PRIVATE_nextSequenceNumber","__PRIVATE_configs","config","__PRIVATE_memoizedIndexes","__PRIVATE_memoizedCollectionIndexes","__PRIVATE_fieldIndexes","__PRIVATE_getExistingIndexEntries","__PRIVATE_existingEntries","__PRIVATE_newEntries","__PRIVATE_computeIndexEntries","__PRIVATE_updateEntries","__PRIVATE_addIndexEntry","__PRIVATE_indexEntry","__PRIVATE_deleteIndexEntry","only","__PRIVATE_diffSortedSets","after","__PRIVATE_onAdd","__PRIVATE_onRemove","__PRIVATE_beforeIt","__PRIVATE_afterIt","__PRIVATE_beforeValue","__PRIVATE_afterValue","__PRIVATE_removed","lower","upper","el","__PRIVATE_bounds","__PRIVATE_notInValue","__PRIVATE_cmpToLower","__PRIVATE_cmpToUpper","__PRIVATE_ranges","__PRIVATE_isRangeMatchable","__PRIVATE_getMinOffsetFromFieldIndexes","__PRIVATE_minOffset","__PRIVATE_maxBatchId","__PRIVATE_GC_DID_NOT_RUN","didRun","sequenceNumbersCollected","targetsRemoved","documentsRemoved","__PRIVATE_LRU_DEFAULT_CACHE_SIZE_BYTES","LruParams","withCacheSize","cacheSize","DEFAULT_COLLECTION_PERCENTILE","DEFAULT_MAX_SEQUENCE_NUMBERS_TO_COLLECT","cacheSizeCollectionThreshold","percentileToCollect","maximumSequenceNumbersToCollect","removeMutationBatch","__PRIVATE_mutationStore","__PRIVATE_indexTxn","__PRIVATE_numDeleted","__PRIVATE_removePromise","__PRIVATE_indexKey","__PRIVATE_dbDocumentSize","DEFAULT","DISABLED","__PRIVATE_IndexedDbMutationQueue","referenceDelegate","__PRIVATE_documentKeysByBatchId","checkEmpty","NEGATIVE_INFINITY","__PRIVATE_mutationsStore","addMutationBatch","__PRIVATE_documentStore","__PRIVATE_documentMutationsStore","__PRIVATE_toDbMutationBatch","__PRIVATE_serializedBaseMutations","__PRIVATE_serializedMutations","__PRIVATE_collectionParents","lookupMutationBatch","__PRIVATE_lookupMutationKeys","getNextMutationBatchAfterBatchId","__PRIVATE_nextBatchId","__PRIVATE_foundBatch","getHighestUnacknowledgedBatchId","getAllMutationBatches","__PRIVATE_dbBatches","getAllMutationBatchesAffectingDocumentKey","__PRIVATE_indexPrefix","__PRIVATE_indexStart","__PRIVATE_userID","__PRIVATE_encodedPath","getAllMutationBatchesAffectingDocumentKeys","__PRIVATE_uniqueBatchIDs","__PRIVATE_batchID","__PRIVATE_lookupMutationBatches","getAllMutationBatchesAffectingQuery","__PRIVATE_queryPath","__PRIVATE_immediateChildrenLength","__PRIVATE_batchIDs","__PRIVATE_removeCachedMutationKeys","markPotentiallyOrphaned","performConsistencyCheck","__PRIVATE_startRange","__PRIVATE_newDbDocumentMutationPrefixForUser","__PRIVATE_danglingMutationReferences","__PRIVATE_danglingKeys","containsKey","__PRIVATE_mutationQueueContainsKey","__PRIVATE_getMutationQueueMetadata","__PRIVATE_mutationQueuesStore","lastAcknowledgedBatchId","lastStreamToken","keyPath","__PRIVATE_TargetIdGenerator","__PRIVATE_lastId","__PRIVATE_forTargetCache","__PRIVATE_forSyncEngine","__PRIVATE_IndexedDbTargetCache","allocateTargetId","__PRIVATE_retrieveMetadata","__PRIVATE_targetIdGenerator","highestTargetId","__PRIVATE_saveMetadata","getLastRemoteSnapshotVersion","lastRemoteSnapshotVersion","getHighestSequenceNumber","__PRIVATE_targetGlobal","highestListenSequenceNumber","setTargetsMetadata","addTargetData","__PRIVATE_saveTargetData","targetCount","__PRIVATE_updateMetadataFromTargetData","updateTargetData","removeTargetData","removeMatchingKeysForTargetId","__PRIVATE_targetsStore","removeTargets","activeTargetIds","__PRIVATE_globalTargetStore","updated","getTargetCount","getTargetData","addMatchingKeys","__PRIVATE_documentTargetStore","addReference","removeMatchingKeys","removeReference","getMatchingKeysForTargetId","__PRIVATE_LRU_MINIMUM_CACHE_SIZE_BYTES","__PRIVATE_bufferEntryComparator","__PRIVATE_aSequence","__PRIVATE_aIndex","__PRIVATE_bSequence","__PRIVATE_bIndex","__PRIVATE_seqCmp","__PRIVATE_RollingSequenceNumberBuffer","__PRIVATE_maxElements","__PRIVATE_previousIndex","__PRIVATE_nextIndex","__PRIVATE_addElement","__PRIVATE_highestValue","maxValue","__PRIVATE_LruScheduler","garbageCollector","__PRIVATE_gcTask","params","__PRIVATE_scheduleGC","collectGarbage","__PRIVATE_LruGarbageCollectorImpl","__PRIVATE_delegate","calculateTargetCount","percentile","__PRIVATE_getSequenceNumberCount","nthSequenceNumber","__PRIVATE_forEachOrphanedDocumentSequenceNumber","removeOrphanedDocuments","collect","getCacheSize","__PRIVATE_runGarbageCollection","__PRIVATE_upperBoundSequenceNumber","__PRIVATE_sequenceNumbersToCollect","__PRIVATE_countedTargetsTs","__PRIVATE_foundUpperBoundTs","__PRIVATE_removedTargetsTs","__PRIVATE_removedDocumentsTs","__PRIVATE_startTs","__PRIVATE_sequenceNumbers","__PRIVATE_numTargetsRemoved","__PRIVATE_newLruGarbageCollector","__PRIVATE_IndexedDbLruDelegateImpl","__PRIVATE_docCountPromise","__PRIVATE_orphanedDocumentCount","getTargetCache","__PRIVATE_docCount","__PRIVATE_orphanedCount","__PRIVATE_forEachOrphanedDocument","__PRIVATE_writeSentinelKey","__PRIVATE_isPinned","__PRIVATE_mutationQueuesContainKey","__PRIVATE_changeBuffer","getRemoteDocumentCache","newChangeBuffer","__PRIVATE_documentCount","getEntry","removeEntry","__PRIVATE_sentinelKey","apply","updateLimboDocument","__PRIVATE_nextPath","__PRIVATE_nextToReport","getSize","__PRIVATE_sentinelRow","RemoteDocumentChangeBuffer","changesApplied","addEntry","assertNotApplied","__PRIVATE_bufferedEntry","getFromCache","getAllFromCache","__PRIVATE_IndexedDbRemoteDocumentCacheImpl","setIndexManager","__PRIVATE_remoteDocumentsStore","__PRIVATE_dbReadTimeKey","updateMetadata","__PRIVATE_sizeDelta","getMetadata","byteSize","__PRIVATE_setMetadata","__PRIVATE_dbKey","__PRIVATE_dbRemoteDoc","__PRIVATE_maybeDecodeDocument","__PRIVATE_getSizedEntry","__PRIVATE_forEachDbEntry","__PRIVATE_getSizedEntries","__PRIVATE_sizeMap","__PRIVATE_dbKeyComparator","__PRIVATE_keyIter","__PRIVATE_potentialKey","getDocumentsMatchingQuery","mutatedDocs","__PRIVATE_endKey","__PRIVATE_dbRemoteDocs","incrementDocumentReadCount","getAllFromCollectionGroup","__PRIVATE_dbCollectionGroupKey","__PRIVATE_IndexedDbRemoteDocumentChangeBuffer","trackRemovals","__PRIVATE_documentGlobalStore","__PRIVATE_newIndexedDbRemoteDocumentCache","__PRIVATE_documentCache","__PRIVATE_previousDoc","__PRIVATE_documentStates","__PRIVATE_deletedDoc","__PRIVATE_getResult","OverlayedDocument","LocalDocumentsView","remoteDocumentCache","mutationQueue","documentOverlayCache","getDocument","getDocuments","getLocalViewOfDocuments","existenceStateChanged","populateOverlays","computeViews","__PRIVATE_computeViewsResult","getOverlayedDocuments","__PRIVATE_missingOverlays","__PRIVATE_recalculateDocuments","__PRIVATE_newOverlayedDocumentMap","recalculateAndSaveOverlays","__PRIVATE_recalculatedFields","__PRIVATE_masks","__PRIVATE_documentsByBatchId","key1","key2","__PRIVATE_processed","__PRIVATE_batches","__PRIVATE_baseDoc","__PRIVATE_newSet","recalculateAndSaveOverlaysForDocumentKeys","getDocumentsMatchingDocumentQuery","getDocumentsMatchingCollectionGroupQuery","getDocumentsMatchingCollectionQuery","__PRIVATE_originalDocs","__PRIVATE_overlaysPromise","__PRIVATE_modifiedDocs","__PRIVATE_localDocs","__PRIVATE_parents","__PRIVATE_collectionQuery","__PRIVATE_asCollectionQueryAtPath","__PRIVATE_remoteDocuments","__PRIVATE_MemoryBundleCache","__PRIVATE_bundles","__PRIVATE_fromBundleMetadata","__PRIVATE_namedQueries","__PRIVATE_fromProtoNamedQuery","namedQuery","__PRIVATE_MemoryDocumentOverlayCache","__PRIVATE_overlayByBatchId","__PRIVATE_immediateChildrenPathLength","__PRIVATE_batchIdToOverlays","__PRIVATE_overlaysForBatchId","__PRIVATE_batchIter","__PRIVATE_existing","__PRIVATE_MemoryGlobalsCache","__PRIVATE_ReferenceSet","__PRIVATE_refsByKey","__PRIVATE_DocReference","__PRIVATE_compareByKey","__PRIVATE_refsByTarget","__PRIVATE_compareByTargetId","ref","__PRIVATE_addReferences","__PRIVATE_removeRef","__PRIVATE_removeReferences","__PRIVATE_removeReferencesForId","__PRIVATE_emptyKey","__PRIVATE_startRef","__PRIVATE_endRef","__PRIVATE_removeAllReferences","__PRIVATE_referencesForId","__PRIVATE_firstRef","__PRIVATE_targetOrBatchId","__PRIVATE_MemoryMutationQueue","__PRIVATE_batchesByDocumentKey","__PRIVATE_findMutationBatch","__PRIVATE_rawIndex","__PRIVATE_indexOfBatchId","__PRIVATE_findMutationBatches","__PRIVATE_startPath","__PRIVATE_rowKeyPath","__PRIVATE_indexOfExistingBatchId","shift","__PRIVATE_references","__PRIVATE_MemoryRemoteDocumentCacheImpl","__PRIVATE_sizer","__PRIVATE_documentEntryMap","__PRIVATE_forEachDocumentKey","__PRIVATE_MemoryRemoteDocumentChangeBuffer","__PRIVATE_MemoryTargetCache","__PRIVATE_highestSequenceNumber","__PRIVATE_removals","__PRIVATE_matchingKeys","__PRIVATE_MemoryPersistence","__PRIVATE_referenceDelegateFactory","__PRIVATE_mutationQueues","__PRIVATE_listenSequence","__PRIVATE__started","__PRIVATE_globalsCache","__PRIVATE_targetCache","__PRIVATE_newMemoryRemoteDocumentCache","__PRIVATE_documentSize","__PRIVATE_bundleCache","setDatabaseDeletedListener","setNetworkEnabled","getIndexManager","getDocumentOverlayCache","getMutationQueue","__PRIVATE_queue","getGlobalsCache","getBundleCache","transactionOperation","__PRIVATE_MemoryTransaction","__PRIVATE_onTransactionStarted","__PRIVATE_onTransactionCommitted","__PRIVATE_MemoryEagerDelegate","__PRIVATE__orphanedDocuments","__PRIVATE_factory","__PRIVATE_orphanedDocuments","__PRIVATE_localViewReferences","cache","__PRIVATE_isReferenced","__PRIVATE_MemoryLruDelegate","__PRIVATE_lruParams","__PRIVATE_orphanedSequenceNumbers","__PRIVATE_orphanedAt","__PRIVATE_SchemaConverter","__PRIVATE_createPrimaryClientStore","createObjectStore","__PRIVATE_createMutationQueue","__PRIVATE_mutationBatchesStore","autoIncrement","createIndex","unique","__PRIVATE_createQueryCache","__PRIVATE_createLegacyRemoteDocumentCache","__PRIVATE_dropQueryCache","deleteObjectStore","__PRIVATE_writeEmptyTargetGlobalEntry","__PRIVATE_globalStore","__PRIVATE_upgradeMutationBatchSchemaAndMigrateData","__PRIVATE_v1MutationsStore","__PRIVATE_existingMutations","__PRIVATE_v3MutationsStore","__PRIVATE_writeAll","__PRIVATE_createClientMetadataStore","__PRIVATE_removeAcknowledgedMutations","__PRIVATE_createDocumentGlobalStore","__PRIVATE_addDocumentGlobal","__PRIVATE_ensureSequenceNumbers","__PRIVATE_createCollectionParentIndex","__PRIVATE_dropRemoteDocumentChangesStore","__PRIVATE_rewriteCanonicalIds","__PRIVATE_createBundlesStore","__PRIVATE_createNamedQueriesStore","__PRIVATE_createDocumentOverlayStore","__PRIVATE_createRemoteDocumentCache","__PRIVATE_remoteDocumentStore","__PRIVATE_rewriteRemoteDocumentCache","__PRIVATE_runOverlayMigration","__PRIVATE_createFieldIndex","__PRIVATE_indexEntryStore","clear","__PRIVATE_createGlobalsStore","__PRIVATE_queuesStore","__PRIVATE_queues","__PRIVATE_documentsStore","__PRIVATE_docSentinelKey","__PRIVATE_maybeSentinel","pathSegments","__PRIVATE_targetStore","__PRIVATE_originalDbTarget","__PRIVATE_originalTargetData","__PRIVATE_updatedDbTarget","__PRIVATE_legacyRemoteDocumentStore","writes","__PRIVATE_legacyDocument","__PRIVATE_extractKey","__PRIVATE_dbRemoteDocument","__PRIVATE_memoryPersistence","__PRIVATE_userToDocumentSet","__PRIVATE_documentSet","__PRIVATE_allDocumentKeysForUser","__PRIVATE_MAX_CLIENT_AGE_MS","__PRIVATE_MAX_PRIMARY_ELIGIBLE_AGE_MS","__PRIVATE_PRIMARY_LEASE_EXCLUSIVE_ERROR_MSG","__PRIVATE_MAIN_DATABASE","__PRIVATE_IndexedDbPersistence","allowTabSynchronization","clientId","window","__PRIVATE_forceOwningTab","__PRIVATE_schemaVersion","isPrimary","networkEnabled","__PRIVATE_windowUnloadHandler","inForeground","__PRIVATE_documentVisibilityHandler","__PRIVATE_clientMetadataRefresher","__PRIVATE_primaryStateListener","__PRIVATE_dbName","__PRIVATE_simpleDb","localStorage","__PRIVATE_webStorage","__PRIVATE_updateClientMetadataAndTryBecomePrimary","__PRIVATE_attachVisibilityHandler","__PRIVATE_attachWindowUnloadHook","__PRIVATE_scheduleClientMetadataAndPrimaryLeaseRefreshes","reason","__PRIVATE_setPrimaryStateListener","__PRIVATE_primaryState","databaseDeletedListener","newVersion","enqueueAndForget","__PRIVATE_clientMetadataStore","updateTimeMs","__PRIVATE_verifyPrimaryLease","__PRIVATE_success","__PRIVATE_canActAsPrimary","__PRIVATE_releasePrimaryLeaseIfHeld","__PRIVATE_acquireOrExtendPrimaryLease","__PRIVATE_primaryClientStore","__PRIVATE_primaryClient","__PRIVATE_isLocalClient","__PRIVATE_removeClientMetadata","__PRIVATE_maybeGarbageCollectMultiClientState","__PRIVATE_isWithinAge","__PRIVATE_lastGarbageCollectionTime","__PRIVATE_inactiveClients","__PRIVATE_metadataStore","__PRIVATE_existingClients","active","__PRIVATE_filterActiveClients","__PRIVATE_inactive","__PRIVATE_client","__PRIVATE_inactiveClient","removeItem","__PRIVATE_zombiedClientLocalStorageKey","ownerId","__PRIVATE_currentPrimary","leaseTimestampMs","__PRIVATE_isClientZombied","__PRIVATE_otherClient","__PRIVATE_otherClientHasBetterNetworkState","__PRIVATE_otherClientHasBetterVisibility","__PRIVATE_otherClientHasSameNetworkState","__PRIVATE_markClientZombied","__PRIVATE_detachVisibilityHandler","__PRIVATE_detachWindowUnloadHook","__PRIVATE_simpleDbTxn","__PRIVATE_persistenceTransaction","__PRIVATE_removeClientZombiedEntry","__PRIVATE_clients","__PRIVATE_activityThresholdMs","__PRIVATE_getActiveClients","__PRIVATE_clientMetadata","__PRIVATE_simpleDbMode","__PRIVATE_getObjectStores","__PRIVATE_holdsPrimaryLease","__PRIVATE_verifyAllowTabSynchronization","__PRIVATE_newPrimary","__PRIVATE_maxAgeMs","addEventListener","visibilityState","removeEventListener","__PRIVATE_safariIndexdbBugVersionRegex","isSafari","navigator","appVersion","userAgent","enterRestrictedMode","__PRIVATE_isZombied","getItem","setItem","__PRIVATE_indexedDbStoragePrefix","__PRIVATE_LocalViewChanges","fromCache","__PRIVATE_addedKeys","__PRIVATE_removedKeys","__PRIVATE_fromSnapshot","__PRIVATE_viewSnapshot","docChanges","QueryContext","_documentReadCount","documentReadCount","amount","__PRIVATE_QueryEngine","__PRIVATE_initialized","__PRIVATE_indexAutoCreationEnabled","__PRIVATE_indexAutoCreationMinCollectionSize","__PRIVATE_relativeIndexReadCostPerDocument","__PRIVATE_getDefaultRelativeIndexReadCostPerDocument","initialize","__PRIVATE_localDocumentsView","__PRIVATE_remoteKeys","__PRIVATE_queryResult","__PRIVATE_performQueryUsingIndex","__PRIVATE_performQueryUsingRemoteKeys","__PRIVATE_executeFullCollectionScan","__PRIVATE_createCacheIndexes","__PRIVATE_resultSize","__PRIVATE_indexedDocuments","__PRIVATE_previousResults","__PRIVATE_applyQuery","__PRIVATE_needsRefill","__PRIVATE_appendRemainingResults","__PRIVATE_queryResults","__PRIVATE_maybeDoc","__PRIVATE_sortedPreviousResults","__PRIVATE_limboFreeSnapshotVersion","__PRIVATE_docAtLimitEdge","__PRIVATE_indexedResults","__PRIVATE_remainingResults","d","__PRIVATE_RESUME_TOKEN_MAX_AGE_MICROS","__PRIVATE_LocalStoreImpl","__PRIVATE_queryEngine","initialUser","__PRIVATE_targetDataByTarget","__PRIVATE_targetIdByTarget","__PRIVATE_initializeUserComponents","__PRIVATE_newLocalStore","__PRIVATE_localStoreHandleUserChange","__PRIVATE_localStoreImpl","__PRIVATE_oldBatches","__PRIVATE_promisedOldBatches","__PRIVATE_newBatches","removedBatchIds","addedBatchIds","__PRIVATE_changedKeys","__PRIVATE_affectedDocuments","__PRIVATE_localStoreAcknowledgeBatch","__PRIVATE_affected","__PRIVATE_documentBuffer","__PRIVATE_applyWriteToRemoteDocuments","__PRIVATE_docKeys","__PRIVATE_promiseChain","__PRIVATE_ackVersion","__PRIVATE_getKeysWithTransformResults","__PRIVATE_localStoreGetLastRemoteSnapshotVersion","__PRIVATE_localStoreApplyRemoteEventToLocalCache","__PRIVATE_remoteVersion","__PRIVATE_newTargetDataByTargetMap","__PRIVATE_oldTargetData","__PRIVATE_newTargetData","__PRIVATE_shouldPersistTargetData","__PRIVATE_timeDelta","__PRIVATE_changedDocs","__PRIVATE_existenceChangedKeys","__PRIVATE_populateDocumentChangeBuffer","__PRIVATE_changedDocuments","__PRIVATE_updateRemoteVersion","__PRIVATE_updatedKeys","__PRIVATE_existingDocs","__PRIVATE_existingDoc","__PRIVATE_localStoreGetNextMutationBatch","__PRIVATE_afterBatchId","__PRIVATE_localStoreAllocateTarget","__PRIVATE_cached","__PRIVATE_cachedTargetData","__PRIVATE_localStoreReleaseTarget","__PRIVATE_keepPersistedTargetData","__PRIVATE_localStoreExecuteQuery","__PRIVATE_usePreviousResults","__PRIVATE_localStoreGetTargetData","__PRIVATE_setMaxReadTime","__PRIVATE_localStoreGetCachedTarget","__PRIVATE_targetCacheImpl","__PRIVATE_localStoreGetNewDocumentChanges","__PRIVATE_collectionGroupReadTime","__PRIVATE_localStoreApplyBundledDocuments","__PRIVATE_bundleConverter","bundleName","__PRIVATE_bundleDoc","__PRIVATE_toDocumentKey","__PRIVATE_toMutableDocument","__PRIVATE_toSnapshotVersion","__PRIVATE_umbrellaTargetData","__PRIVATE_umbrellaTarget","__PRIVATE_documentChangeResult","__PRIVATE_localStoreSaveNamedQuery","__PRIVATE_allocated","CLIENT_STATE_KEY_PREFIX","createWebStorageClientStateKey","MUTATION_BATCH_KEY_PREFIX","createWebStorageMutationBatchKey","__PRIVATE_mutationKey","QUERY_TARGET_KEY_PREFIX","createWebStorageQueryTargetMetadataKey","__PRIVATE_MutationMetadata","__PRIVATE_fromWebStorageEntry","__PRIVATE_mutationBatch","parse","__PRIVATE_firestoreError","__PRIVATE_validData","__PRIVATE_toWebStorageJSON","__PRIVATE_batchMetadata","__PRIVATE_QueryTargetMetadata","__PRIVATE_RemoteClientState","__PRIVATE_clientState","__PRIVATE_activeTargetIdsSet","__PRIVATE_SharedOnlineState","onlineState","__PRIVATE_LocalClientState","__PRIVATE_addQueryTarget","__PRIVATE_removeQueryTarget","__PRIVATE_WebStorageSharedClientState","__PRIVATE_localClientId","syncEngine","onlineStateHandler","__PRIVATE_storageListener","__PRIVATE_handleWebStorageEvent","bind","__PRIVATE_activeClients","__PRIVATE_earlyEvents","__PRIVATE_escapedPersistenceKey","storage","__PRIVATE_localClientStorageKey","__PRIVATE_sequenceNumberKey","createWebStorageSequenceNumberKey","__PRIVATE_clientStateKeyRe","__PRIVATE_mutationBatchKeyRe","__PRIVATE_queryTargetKeyRe","__PRIVATE_onlineStateKey","createWebStorageOnlineStateKey","__PRIVATE_bundleLoadedKey","createBundleLoadedKey","__PRIVATE_storageItem","__PRIVATE_persistClientState","__PRIVATE_onlineStateJSON","__PRIVATE_fromWebStorageOnlineState","__PRIVATE_handleOnlineStateEvent","getAllActiveQueryTargets","__PRIVATE_extractActiveQueryTargets","isActiveQueryTarget","addPendingMutation","__PRIVATE_persistMutationState","updateMutationState","__PRIVATE_removeMutationState","addLocalQueryTarget","addToActiveTargetIds","__PRIVATE_queryState","__PRIVATE_localClientState","removeLocalQueryTarget","isLocalQueryTarget","clearQueryState","updateQueryState","__PRIVATE_persistQueryTargetState","handleUserChange","setOnlineState","__PRIVATE_persistOnlineState","notifyBundleLoaded","collectionGroups","__PRIVATE_persistBundleLoadedState","__PRIVATE_storageEvent","storageArea","__PRIVATE_fromWebStorageClientStateKey","__PRIVATE_handleClientStateEvent","__PRIVATE_fromWebStorageClientState","__PRIVATE_mutationMetadata","__PRIVATE_fromWebStorageMutationMetadata","__PRIVATE_handleMutationBatchEvent","__PRIVATE_queryTargetMetadata","__PRIVATE_fromWebStorageQueryTargetMetadata","__PRIVATE_handleQueryTargetEvent","__PRIVATE_fromWebStorageSequenceNumber","__PRIVATE_seqString","__PRIVATE_parsed","__PRIVATE_fromWebStoreBundleLoadedState","__PRIVATE_cg","__PRIVATE_synchronizeWithChangedDocuments","__PRIVATE_mutationState","__PRIVATE_targetKey","__PRIVATE_targetMetadata","__PRIVATE_applyBatchState","__PRIVATE_applyTargetState","__PRIVATE_updatedClients","__PRIVATE_existingTargets","__PRIVATE_newTargets","__PRIVATE_addedTargets","__PRIVATE_removedTargets","__PRIVATE_applyActiveTargetsChange","__PRIVATE_activeTargets","__PRIVATE_kev","__PRIVATE_MemorySharedClientState","__PRIVATE_localState","__PRIVATE_NoopConnectivityMonitor","__PRIVATE_addCallback","__PRIVATE_BrowserConnectivityMonitor","__PRIVATE_networkAvailableListener","__PRIVATE_onNetworkAvailable","__PRIVATE_networkUnavailableListener","__PRIVATE_onNetworkUnavailable","__PRIVATE_callbacks","__PRIVATE_configureNetworkMonitoring","__PRIVATE_lastUniqueDebugId","__PRIVATE_generateUniqueDebugId","__PRIVATE_generateInitialUniqueDebugId","round","__PRIVATE_maxResult","__PRIVATE_RPC_NAME_URL_MAPPING","__PRIVATE_RestConnection","__PRIVATE_shouldResourcePathBeIncludedInRequest","databaseInfo","__PRIVATE_baseUrl","__PRIVATE_databasePath","__PRIVATE_requestParams","__PRIVATE_invokeRPC","__PRIVATE_rpcName","__PRIVATE_req","__PRIVATE_authToken","streamId","url","__PRIVATE_makeUrl","__PRIVATE_modifyHeadersForRequest","URL","__PRIVATE_forwardCredentials","isCloudWorkstation","__PRIVATE_performRPCRequest","response","__PRIVATE_invokeStreamingRPC","__PRIVATE_expectedResponseCount","__PRIVATE_getGoogApiClientValue","__PRIVATE_urlRpcName","terminate","__PRIVATE_StreamBridge","__PRIVATE_sendFn","__PRIVATE_closeFn","__PRIVATE_onConnected","__PRIVATE_wrappedOnConnected","__PRIVATE_onOpen","__PRIVATE_wrappedOnOpen","__PRIVATE_onClose","__PRIVATE_wrappedOnClose","onMessage","__PRIVATE_wrappedOnMessage","send","__PRIVATE_callOnConnected","__PRIVATE_callOnOpen","__PRIVATE_callOnClose","__PRIVATE_callOnMessage","__PRIVATE_WebChannelConnection","info","__PRIVATE_openWebChannels","body","__PRIVATE__forwardCredentials","__PRIVATE_xhr","XhrIo","setWithCredentials","listenOnce","EventType","COMPLETE","getLastErrorCode","ErrorCode","NO_ERROR","getResponseJson","TIMEOUT","HTTP_ERROR","getStatus","getResponseText","__PRIVATE_responseError","__PRIVATE_firestoreErrorCode","__PRIVATE_mapCodeFromHttpResponseErrorStatus","__PRIVATE_serverError","toLowerCase","__PRIVATE_lastErrorCode","__PRIVATE_lastError","getLastError","__PRIVATE_requestString","__PRIVATE_openStream","__PRIVATE_urlParts","__PRIVATE_webchannelTransport","createWebChannelTransport","__PRIVATE_requestStats","getStatEventTarget","httpSessionIdParam","initMessageHeaders","messageUrlParams","sendRawJson","supportsCrossDomainXhr","internalChannelParams","forwardChannelRequestTimeoutMs","detectBufferingProxy","__PRIVATE_longPollingTimeoutSeconds","timeoutSeconds","longPollingTimeout","encodeInitMessageHeaders","channel","createWebChannel","__PRIVATE_addOpenWebChannel","__PRIVATE_opened","closed","__PRIVATE_streamBridge","__PRIVATE_unguardedEventListen","listen","param","WebChannel","OPEN","CLOSE","__PRIVATE_removeOpenWebChannel","MESSAGE","__PRIVATE_msgData","__PRIVATE_msgDataOrError","__PRIVATE_mapCodeFromRpcStatus","Event","STAT_EVENT","stat","Stat","PROXY","NOPROXY","__PRIVATE_webChannel","instance","__PRIVATE_getWindow","__PRIVATE_newSerializer","__PRIVATE_ExponentialBackoff","timerId","__PRIVATE_initialDelayMs","__PRIVATE_backoffFactor","__PRIVATE_maxDelayMs","__PRIVATE_currentBaseMs","__PRIVATE_timerPromise","__PRIVATE_resetToMax","__PRIVATE_backoffAndRun","__PRIVATE_desiredDelayWithJitterMs","__PRIVATE_jitterDelayMs","__PRIVATE_delaySoFarMs","__PRIVATE_lastAttemptTime","__PRIVATE_remainingDelayMs","__PRIVATE_skipBackoff","skipDelay","__PRIVATE_PersistentStream","__PRIVATE_connectionTimerId","__PRIVATE_idleTimerId","__PRIVATE_healthTimerId","connection","authCredentialsProvider","appCheckCredentialsProvider","__PRIVATE_closeCount","__PRIVATE_idleTimer","__PRIVATE_healthCheck","stream","__PRIVATE_responseCount","__PRIVATE_backoff","__PRIVATE_isStarted","__PRIVATE_isOpen","__PRIVATE_performBackoff","__PRIVATE_inhibitBackoff","__PRIVATE_markIdle","__PRIVATE_handleIdleCloseTimer","__PRIVATE_sendRequest","__PRIVATE_cancelIdleCheck","__PRIVATE_cancelHealthCheck","__PRIVATE_finalState","__PRIVATE_tearDown","__PRIVATE_dispatchIfNotClosed","__PRIVATE_getCloseGuardedDispatcher","__PRIVATE_startStream","__PRIVATE_rpcError","__PRIVATE_handleStreamClose","__PRIVATE_startRpc","__PRIVATE_onFirst","onNext","__PRIVATE_startCloseCount","__PRIVATE_PersistentListenStream","authCredentials","appCheckCredentials","__PRIVATE_watchChangeProto","snapshot","__PRIVATE_versionFromListenResponse","__PRIVATE_onWatchChange","__PRIVATE_watch","addTarget","__PRIVATE_toTarget","labels","__PRIVATE_unwatch","__PRIVATE_PersistentWriteStream","__PRIVATE_handshakeComplete","__PRIVATE_writeMutations","__PRIVATE_responseProto","streamToken","writeResults","__PRIVATE_onHandshakeComplete","__PRIVATE_onMutationResult","__PRIVATE_writeHandshake","Datastore","__PRIVATE_DatastoreImpl","__PRIVATE_terminated","__PRIVATE_verifyInitialized","__PRIVATE_OnlineStateTracker","__PRIVATE_watchStreamFailures","__PRIVATE_onlineStateTimer","__PRIVATE_shouldWarnClientIsOffline","__PRIVATE_handleWatchStreamStart","__PRIVATE_setAndBroadcast","__PRIVATE_logClientOfflineWarningIfNecessary","__PRIVATE_handleWatchStreamFailure","__PRIVATE_clearOnlineStateTimer","newState","details","__PRIVATE_RemoteStoreImpl","datastore","__PRIVATE_connectivityMonitor","remoteSyncer","__PRIVATE_writePipeline","__PRIVATE_onNetworkStatusChange","__PRIVATE_canUseNetwork","__PRIVATE_restartNetwork","remoteStore","__PRIVATE_remoteStoreImpl","__PRIVATE_offlineCauses","__PRIVATE_disableNetworkInternal","__PRIVATE_onlineStateTracker","__PRIVATE_enableNetworkInternal","__PRIVATE_networkStatusHandler","__PRIVATE_remoteStoreListen","__PRIVATE_listenTargets","__PRIVATE_shouldStartWatchStream","__PRIVATE_startWatchStream","__PRIVATE_ensureWatchStream","__PRIVATE_sendWatchRequest","__PRIVATE_remoteStoreUnlisten","__PRIVATE_watchStream","__PRIVATE_sendUnwatchRequest","__PRIVATE_watchChangeAggregator","__PRIVATE_cleanUpWatchStreamState","__PRIVATE_onWatchStreamConnected","__PRIVATE_onWatchStreamOpen","__PRIVATE_onWatchStreamClose","__PRIVATE_onWatchStreamChange","__PRIVATE_handleTargetError","rejectListen","__PRIVATE_disableNetworkUntilRecovery","__PRIVATE_raiseWatchSnapshot","__PRIVATE_targetPurpose","__PRIVATE_requestTargetData","applyRemoteEvent","__PRIVATE_executeWithRecovery","__PRIVATE_fillWritePipeline","__PRIVATE_writeStream","__PRIVATE_ensureWriteStream","__PRIVATE_lastBatchIdRetrieved","__PRIVATE_canAddToWritePipeline","__PRIVATE_addToWritePipeline","__PRIVATE_shouldStartWriteStream","__PRIVATE_startWriteStream","__PRIVATE_onWriteStreamOpen","__PRIVATE_onWriteHandshakeComplete","applySuccessfulWrite","__PRIVATE_onWriteStreamClose","__PRIVATE_handleWriteError","__PRIVATE_isPermanentWriteError","rejectFailedWrite","__PRIVATE_remoteStoreHandleCredentialChange","verifyOperationInProgress","__PRIVATE_usesNetwork","handleCredentialChange","__PRIVATE_remoteStoreApplyPrimaryState","__PRIVATE_newPersistentWatchStream","__PRIVATE_datastoreImpl","enabled","__PRIVATE_newPersistentWriteStream","DelayedOperation","targetTimeMs","removalCallback","deferred","createAndSchedule","delayMs","__PRIVATE_targetTime","__PRIVATE_delayedOp","timerHandle","handleDelayElapsed","clearTimeout","__PRIVATE_wrapInUserErrorIfRecoverable","DocumentSet","emptySet","oldSet","keyedMap","sortedSet","__PRIVATE_thisDoc","__PRIVATE_otherDoc","__PRIVATE_docStrings","__PRIVATE_DocumentChangeSet","__PRIVATE_changeMap","track","__PRIVATE_oldChange","__PRIVATE_getChanges","ViewSnapshot","oldDocs","mutatedKeys","syncStateChanged","excludesMetadataChanges","hasCachedResults","fromInitialDocuments","__PRIVATE_otherChanges","__PRIVATE_QueryListenersInfo","__PRIVATE_viewSnap","__PRIVATE_listeners","__PRIVATE_hasRemoteListeners","__PRIVATE_listensToRemoteStore","__PRIVATE_EventManagerImpl","queries","__PRIVATE_newQueriesObjectMap","__PRIVATE_errorAllTargets","eventManager","__PRIVATE_eventManagerImpl","__PRIVATE_queryInfo","onError","q","__PRIVATE_eventManagerListen","__PRIVATE_listenerAction","onListen","onFirstRemoteStoreListen","__PRIVATE_applyOnlineStateChange","__PRIVATE_onViewSnapshot","__PRIVATE_raiseSnapshotsInSyncEvent","__PRIVATE_eventManagerUnlisten","onUnlisten","onLastRemoteStoreUnlisten","__PRIVATE_eventManagerOnWatchChange","__PRIVATE_viewSnaps","__PRIVATE_raisedEvent","__PRIVATE_eventManagerOnWatchError","__PRIVATE_snapshotsInSyncListeners","observer","__PRIVATE_ListenerDataSource","ListenerDataSource","__PRIVATE_QueryListener","__PRIVATE_queryObserver","__PRIVATE_raisedInitialEvent","__PRIVATE_snap","includeMetadataChanges","__PRIVATE_shouldRaiseEvent","__PRIVATE_shouldRaiseInitialEvent","__PRIVATE_raiseInitialEvent","__PRIVATE_maybeOnline","__PRIVATE_waitForSyncWhenOnline","__PRIVATE_hasPendingWritesChanged","Cache","__PRIVATE_SizedBundleElement","__PRIVATE_payload","byteLength","__PRIVATE_isBundleMetadata","__PRIVATE_BundleConverterImpl","__PRIVATE_bundledDoc","time","__PRIVATE_BundleLoader","__PRIVATE__queries","__PRIVATE__documents","progress","__PRIVATE_bundleInitialProgress","__PRIVATE_addSizedElement","bytesLoaded","documentsLoaded","documentMetadata","__PRIVATE_getQueryDocumentMapping","__PRIVATE_queryDocumentMap","__PRIVATE_completeAndStoreAsync","taskState","__PRIVATE_changedCollectionGroups","totalDocuments","totalBytes","__PRIVATE_AddedLimboDocument","__PRIVATE_RemovedLimboDocument","__PRIVATE_View","__PRIVATE__syncedDocuments","__PRIVATE_syncState","__PRIVATE_limboDocuments","__PRIVATE_docComparator","__PRIVATE_syncedDocuments","__PRIVATE_computeDocChanges","__PRIVATE_previousChanges","__PRIVATE_changeSet","__PRIVATE_oldDocumentSet","__PRIVATE_newMutatedKeys","__PRIVATE_newDocumentSet","__PRIVATE_lastDocInLimit","__PRIVATE_firstDocInLimit","__PRIVATE_oldDoc","__PRIVATE_oldDocHadPendingMutations","__PRIVATE_newDocHasPendingMutations","__PRIVATE_changeApplied","__PRIVATE_shouldWaitForSyncedDocument","__PRIVATE_limboResolutionEnabled","__PRIVATE_targetIsPendingReset","__PRIVATE_c1","__PRIVATE_c2","__PRIVATE_compareChangeType","__PRIVATE_applyTargetChange","__PRIVATE_limboChanges","__PRIVATE_updateLimboDocuments","__PRIVATE_newSyncState","__PRIVATE_shouldBeInLimbo","__PRIVATE_oldLimboDocuments","__PRIVATE_synchronizeWithPersistedState","__PRIVATE_computeInitialSnapshot","__PRIVATE_QueryView","view","LimboResolution","__PRIVATE_receivedDocument","__PRIVATE_SyncEngineImpl","sharedClientState","maxConcurrentLimboResolutions","__PRIVATE_syncEngineListener","__PRIVATE_queryViewsByQuery","__PRIVATE_activeLimboTargetsByKey","__PRIVATE_mutationUserCallbacks","__PRIVATE__isPrimaryClient","isPrimaryClient","__PRIVATE_syncEngineListen","__PRIVATE_shouldListenToRemote","__PRIVATE_syncEngineImpl","__PRIVATE_ensureWatchCallbacks","__PRIVATE_queryView","__PRIVATE_allocateTargetAndMaybeListen","__PRIVATE_triggerRemoteStoreListen","__PRIVATE_shouldInitializeView","__PRIVATE_initializeViewAndComputeSnapshot","__PRIVATE_applyDocChanges","__PRIVATE_viewDocChanges","__PRIVATE_viewChange","__PRIVATE_updateTrackedLimbos","__PRIVATE_synthesizedTargetChange","__PRIVATE_queriesByTarget","__PRIVATE_syncEngineUnlisten","__PRIVATE_shouldUnlistenToRemote","__PRIVATE_removeAndCleanupTarget","__PRIVATE_triggerRemoteStoreUnlisten","__PRIVATE_syncEngineWrite","__PRIVATE_userCallback","__PRIVATE_syncEngineEnsureWriteCallbacks","__PRIVATE_localStoreWriteLocally","__PRIVATE_overlayedDocuments","__PRIVATE_remoteDocs","__PRIVATE_docsWithoutRemoteVersion","__PRIVATE_addMutationCallback","__PRIVATE_newCallbacks","__PRIVATE_syncEngineEmitNewSnapsAndNotifyLocalStore","__PRIVATE_syncEngineApplyRemoteEvent","__PRIVATE_limboResolution","__PRIVATE_activeLimboResolutionsByTarget","__PRIVATE_syncEngineApplyOnlineStateChange","__PRIVATE_newViewSnapshots","__PRIVATE_eventManagerOnOnlineStateChange","__PRIVATE_syncEngineRejectListen","__PRIVATE_limboKey","__PRIVATE_pumpEnqueuedLimboResolutions","__PRIVATE_syncEngineApplySuccessfulWrite","__PRIVATE_mutationBatchResult","__PRIVATE_processUserCallback","__PRIVATE_triggerPendingWritesCallbacks","__PRIVATE_syncEngineRejectFailedWrite","__PRIVATE_localStoreRejectBatch","__PRIVATE_affectedKeys","__PRIVATE_syncEngineRegisterPendingWritesCallback","__PRIVATE_highestBatchId","__PRIVATE_localStoreGetHighestUnacknowledgedBatchId","__PRIVATE_pendingWritesCallbacks","__PRIVATE_onWatchError","__PRIVATE_limboDocumentRefs","__PRIVATE_removeLimboTarget","__PRIVATE_enqueuedLimboResolutions","__PRIVATE_limboTargetId","__PRIVATE_limboChange","__PRIVATE_trackLimboChange","__PRIVATE_keyString","__PRIVATE_limboTargetIdGenerator","__PRIVATE_newSnaps","__PRIVATE_docChangesInAllViews","__PRIVATE_queriesProcessed","__PRIVATE_isCurrent","__PRIVATE_localStoreNotifyLocalViewChanges","__PRIVATE_viewChanges","__PRIVATE_updatedTargetData","__PRIVATE_syncEngineHandleCredentialChange","__PRIVATE_rejectOutstandingPendingWritesCallbacks","__PRIVATE_errorMessage","__PRIVATE_syncEngineGetRemoteKeysForTarget","__PRIVATE_keySet","__PRIVATE_synchronizeViewAndComputeSnapshot","__PRIVATE_syncEngineSynchronizeWithChangedDocuments","__PRIVATE_syncEngineApplyBatchState","__PRIVATE_batchState","__PRIVATE_localStoreLookupMutationDocuments","__PRIVATE_mutationQueueImpl","__PRIVATE_localStoreRemoveCachedMutationBatchMetadata","__PRIVATE_syncEngineApplyPrimaryState","__PRIVATE_activeQueries","__PRIVATE_synchronizeQueryViewsAndRaiseSnapshots","__PRIVATE_resetLimboDocuments","__PRIVATE_transitionToPrimary","__PRIVATE_synthesizeTargetToQuery","__PRIVATE_syncEngineGetActiveClients","__PRIVATE_localStoreGetActiveClients","__PRIVATE_syncEngineApplyTargetState","__PRIVATE_synthesizedRemoteEvent","__PRIVATE_syncEngineApplyActiveTargetsChange","__PRIVATE_syncEngineLoadBundle","__PRIVATE_bundleReader","__PRIVATE_loadBundleImpl","__PRIVATE_reader","__PRIVATE_localStoreHasNewerBundle","__PRIVATE_currentReadTime","_completeWith","__PRIVATE_bundleSuccessProgress","_updateProgress","__PRIVATE_loader","__PRIVATE_nextElement","__PRIVATE_localStoreSaveBundle","_failWith","__PRIVATE_MemoryOfflineComponentProvider","synchronizeTabs","cfg","__PRIVATE_createSharedClientState","__PRIVATE_createPersistence","__PRIVATE_createLocalStore","gcScheduler","__PRIVATE_createGarbageCollectionScheduler","indexBackfillerScheduler","__PRIVATE_createIndexBackfillerScheduler","provider","build","__PRIVATE_LruGcMemoryOfflineComponentProvider","cacheSizeBytes","__PRIVATE_IndexedDbOfflineComponentProvider","__PRIVATE_onlineComponentProvider","forceOwnership","__PRIVATE_indexBackfiller","__PRIVATE_MultiTabOfflineComponentProvider","OnlineComponentProvider","offlineComponentProvider","createDatastore","createRemoteStore","createEventManager","createSyncEngine","__PRIVATE_newEventManager","__PRIVATE_newConnection","__PRIVATE_newDatastore","__PRIVATE_newRemoteStore","__PRIVATE_newConnectivityMonitor","startAsPrimary","__PRIVATE_newSyncEngine","__PRIVATE_remoteStoreShutdown","__PRIVATE_toByteStreamReaderHelper","__PRIVATE_bytesPerRead","__PRIVATE_readFrom","read","releaseLock","__PRIVATE_AsyncObserver","muted","__PRIVATE_scheduleEvent","__PRIVATE_mute","__PRIVATE_eventHandler","__PRIVATE_BundleReaderImpl","__PRIVATE_textDecoder","__PRIVATE_newTextDecoder","TextDecoder","__PRIVATE_nextElementImpl","__PRIVATE_lengthBuffer","__PRIVATE_readLength","__PRIVATE_lengthString","decode","__PRIVATE_raiseError","__PRIVATE_jsonString","__PRIVATE_readJsonString","__PRIVATE_indexOfOpenBracket","findIndex","__PRIVATE_pullMoreDataToBuffer","__PRIVATE_BundleReaderSyncImpl","bundleData","__PRIVATE_getElements","__PRIVATE_startIndex","__PRIVATE_curIndex","Transaction","readVersions","committed","lastTransactionError","writtenDocs","lookup","ensureCommitNotCalled","__PRIVATE_invokeBatchGetDocumentsRpc","recordVersion","write","preconditionForUpdate","__PRIVATE_unwritten","__PRIVATE_invokeCommitRpc","__PRIVATE_docVersion","__PRIVATE_documentName","__PRIVATE_existingVersion","__PRIVATE_TransactionRunner","updateFunction","__PRIVATE_attemptsRemaining","maxAttempts","__PRIVATE_run","__PRIVATE_runWithBackOff","__PRIVATE_tryRunUpdateFunction","__PRIVATE_commitError","__PRIVATE_handleTransactionError","__PRIVATE_userPromiseError","__PRIVATE_isRetryableTransactionError","FirestoreClient","componentProvider","authCredentialListener","appCheckCredentialListener","_uninitializedComponentsProvider","__PRIVATE_newAppCheckToken","configuration","setCredentialChangeListener","setAppCheckTokenChangeListener","enqueueAndForgetEvenWhileRestricted","_onlineComponents","_offlineComponents","__PRIVATE_setOfflineComponentProvider","__PRIVATE_setOnlineComponentProvider","__PRIVATE_offlineComponents","__PRIVATE_ensureOfflineComponents","_offline","__PRIVATE_canFallbackFromIndexedDbError","__PRIVATE_ensureOnlineComponents","_online","__PRIVATE_getPersistence","__PRIVATE_getLocalStore","__PRIVATE_getRemoteStore","__PRIVATE_getSyncEngine","__PRIVATE_getDatastore","__PRIVATE_getEventManager","__PRIVATE_firestoreClientEnableNetwork","enqueue","__PRIVATE_remoteStoreEnableNetwork","__PRIVATE_firestoreClientDisableNetwork","__PRIVATE_remoteStoreDisableNetwork","__PRIVATE_firestoreClientGetDocumentFromLocalCache","__PRIVATE_readDocumentFromCache","__PRIVATE_localStoreReadDocument","__PRIVATE_firestoreClientGetDocumentViaSnapshotListener","__PRIVATE_readDocumentViaSnapshotListener","__PRIVATE_wrappedObserver","__PRIVATE_firestoreClientGetDocumentsFromLocalCache","__PRIVATE_executeQueryFromCache","__PRIVATE_firestoreClientGetDocumentsViaSnapshotListener","__PRIVATE_executeQueryViaSnapshotListener","__PRIVATE_firestoreClientRunAggregateQuery","__PRIVATE_invokeRunAggregationQueryRpc","gt","__PRIVATE_filteredResult","__PRIVATE_unmappedAggregateFields","aggregateFields","__PRIVATE_accumulator","__PRIVATE_firestoreClientAddSnapshotsInSyncListener","__PRIVATE_addSnapshotsInSyncListener","__PRIVATE_removeSnapshotsInSyncListener","__PRIVATE_firestoreClientLoadBundle","__PRIVATE_resultTask","__PRIVATE_createBundleReader","content","__PRIVATE_newBundleReader","__PRIVATE_toByteStreamReader","ReadableStream","getReader","__PRIVATE_firestoreClientGetNamedQuery","__PRIVATE_localStoreGetNamedQuery","__PRIVATE_createBundleReaderSync","__PRIVATE_newBundleReaderSync","__PRIVATE_firestoreClientSetIndexConfiguration","__PRIVATE_localStoreConfigureFieldIndexes","__PRIVATE_newFieldIndexes","__PRIVATE_oldFieldIndexes","__PRIVATE_diffArrays","__PRIVATE_bLen","__PRIVATE_aLen","a","__PRIVATE_firestoreClientSetPersistentCacheIndexAutoCreationEnabled","isEnabled","__PRIVATE_localStoreSetIndexAutoCreationEnabled","__PRIVATE_firestoreClientDeleteAllFieldIndexes","__PRIVATE_localStoreDeleteAllFieldIndexes","__PRIVATE_cloneLongPollingOptions","__PRIVATE_datastoreInstances","__PRIVATE_DEFAULT_HOST","__PRIVATE_DEFAULT_SSL","FirestoreSettingsImpl","emulatorOptions","credentials","ignoreUndefinedProperties","localCache","experimentalForceLongPolling","experimentalAutoDetectLongPolling","experimentalLongPollingOptions","__PRIVATE_validateLongPollingOptions","__PRIVATE_longPollingOptionsEqual","__PRIVATE_options1","__PRIVATE_options2","Firestore","_authCredentials","_appCheckCredentials","_databaseId","_app","_persistenceKey","_settings","_settingsFrozen","_emulatorOptions","_terminateTask","_initialized","_terminated","_setSettings","__PRIVATE_makeAuthCredentialsProvider","_getSettings","_getEmulatorOptions","_freezeSettings","_delete","_terminate","_restart","__PRIVATE_removeComponents","firestore","connectFirestoreEmulator","port","__PRIVATE_useSsl","__PRIVATE_existingConfig","__PRIVATE_newHostSetting","pingServer","updateEmulatorBanner","__PRIVATE_newConfig","deepEqual","mockUserToken","createMockUserToken","sub","user_id","Query","converter","_query","withConverter","DocumentReference","_key","_path","CollectionReference","referencePath","getModularInstance","__PRIVATE_absolutePath","__PRIVATE_newQueryForCollectionGroup","arguments","refEqual","queryEqual","__PRIVATE_AsyncQueueImpl","__PRIVATE_tail","__PRIVATE_retryableOps","__PRIVATE__isShuttingDown","__PRIVATE_delayedOperations","__PRIVATE_operationInProgress","__PRIVATE_skipNonRestrictedTasks","__PRIVATE_timerIdsToSkip","__PRIVATE_visibilityHandler","isShuttingDown","__PRIVATE_verifyNotFailed","__PRIVATE_enqueueInternal","purgeExistingTasks","__PRIVATE_retryNextOp","__PRIVATE_newTail","__PRIVATE_getMessageOrStack","__PRIVATE_removedOp","__PRIVATE_removeDelayedOperation","__PRIVATE_messageOrStack","__PRIVATE_drain","__PRIVATE_currentTail","__PRIVATE_containsDelayedOperation","__PRIVATE_runAllDelayedOperationsUntil","__PRIVATE_lastTimerId","__PRIVATE_skipDelaysForTimerId","stack","includes","__PRIVATE_isPartialObserver","__PRIVATE_implementsAnyMethods","__PRIVATE_methods","object","method","LoadBundleTask","_progressObserver","_taskCompletionResolver","_lastProgress","onProgress","complete","onRejected","onFulfilled","CACHE_SIZE_UNLIMITED","__PRIVATE_LiteFirestore","_queue","_firestoreClient","initializeFirestore","_getProvider","isInitialized","__PRIVATE_existingInstance","identifier","__PRIVATE_initialSettings","getOptions","instanceIdentifier","getFirestore","__PRIVATE_appOrDatabaseId","__PRIVATE_optionalDatabaseId","getApp","__PRIVATE_emulator","getDefaultEmulatorHostnameAndPort","ensureFirestoreConfigured","__PRIVATE_configureFirestore","__PRIVATE_makeDatabaseInfo","_componentsProvider","_offlineComponentProvider","_onlineComponentProvider","__PRIVATE_buildComponentProvider","__PRIVATE_componentsProvider","__PRIVATE_online","enableIndexedDbPersistence","persistenceSettings","__PRIVATE_setPersistenceProviders","onlineComponents","enableMultiTabIndexedDbPersistence","clearIndexedDbPersistence","__PRIVATE_indexedDbClearPersistence","waitForPendingWrites","__PRIVATE_firestoreClientWaitForPendingWrites","enableNetwork","disableNetwork","_removeServiceInstance","loadBundle","AggregateField","_internalFieldPath","AggregateQuerySnapshot","_userDataWriter","_data","convertObjectMap","_byteString","fieldNames","_internalPath","__PRIVATE_InternalFieldPath","FieldValue","_methodName","GeoPoint","isFinite","_lat","_long","VectorValue","_values","__PRIVATE_isPrimitiveArrayEqual","vectorValues","__PRIVATE_RESERVED_FIELD_REGEX","ParsedSetData","ParsedUpdateData","__PRIVATE_isWrite","__PRIVATE_dataSource","__PRIVATE_ParseContextImpl","__PRIVATE_validatePath","__PRIVATE_contextWith","__PRIVATE_childContextForField","__PRIVATE_childPath","__PRIVATE_validatePathSegment","__PRIVATE_childContextForFieldPath","__PRIVATE_childContextForArray","__PRIVATE_createError","methodName","__PRIVATE_hasConverter","__PRIVATE_targetDoc","__PRIVATE_UserDataReader","__PRIVATE_createContext","__PRIVATE_newUserDataReader","__PRIVATE_parseSetData","__PRIVATE_userDataReader","merge","mergeFields","__PRIVATE_validatePlainObject","__PRIVATE_updateData","__PRIVATE_parseObject","__PRIVATE_validatedFieldPaths","__PRIVATE_stringOrFieldPath","__PRIVATE_fieldPathFromArgument","__PRIVATE_fieldMaskContains","__PRIVATE_DeleteFieldValueImpl","_toFieldTransform","__PRIVATE_createSentinelChildContext","__PRIVATE_ServerTimestampFieldValueImpl","__PRIVATE_ArrayUnionFieldValueImpl","__PRIVATE__elements","__PRIVATE_parseContext","__PRIVATE_parsedElements","__PRIVATE_parseData","arrayUnion","__PRIVATE_ArrayRemoveFieldValueImpl","__PRIVATE_NumericIncrementFieldValueImpl","__PRIVATE__operand","__PRIVATE_numericIncrement","__PRIVATE_parseUpdateData","__PRIVATE_fieldMaskPaths","__PRIVATE_fieldPathFromDotSeparatedString","__PRIVATE_childContext","__PRIVATE_parsedValue","__PRIVATE_parseUpdateVarargs","moreFieldsAndValues","__PRIVATE_parseQueryValue","__PRIVATE_allowArrays","__PRIVATE_looksLikeJsonObject","__PRIVATE_parseSentinelFieldValue","__PRIVATE_parseArray","__PRIVATE_entryIndex","__PRIVATE_parsedEntry","__PRIVATE_parseScalarValue","__PRIVATE_thisDb","__PRIVATE_otherDb","__PRIVATE_parseVectorValue","__PRIVATE_FIELD_PATH_RESERVED","search","__PRIVATE_hasPath","__PRIVATE_hasDocument","DocumentSnapshot","_firestore","_document","_converter","QueryDocumentSnapshot","fromFirestore","convertValue","arg","__PRIVATE_validateHasExplicitOrderByForLimitToLast","AppliableConstraint","QueryConstraint","__PRIVATE_queryConstraint","__PRIVATE_additionalQueryConstraints","queryConstraints","__PRIVATE_validateQueryConstraintArray","__PRIVATE_compositeFilterCount","QueryCompositeFilterConstraint","__PRIVATE_fieldFilterCount","QueryFieldFilterConstraint","constraint","_apply","_field","_op","_value","_create","_parse","__PRIVATE_validateNewFieldFilter","__PRIVATE_newQueryFilter","__PRIVATE_dataReader","__PRIVATE_validateDisjunctiveFilterElements","__PRIVATE_referenceList","__PRIVATE_parseDocumentIdValue","opStr","_queryConstraints","__PRIVATE_parsedFilters","__PRIVATE_parsedFilter","_getOperator","__PRIVATE_validateNewFilter","__PRIVATE_testQuery","__PRIVATE_subFilters","_getQueryConstraints","__PRIVATE_validateQueryFilterConstraint","and","QueryOrderByConstraint","_direction","__PRIVATE_newQueryOrderBy","__PRIVATE_queryWithAddedOrderBy","__PRIVATE_newOrderBy","directionStr","QueryLimitConstraint","_limit","_limitType","limitToLast","QueryStartAtConstraint","_docOrFields","_inclusive","__PRIVATE_newQueryBoundFromDocOrFields","__PRIVATE_queryWithStartAt","__PRIVATE_docOrFields","startAfter","QueryEndAtConstraint","__PRIVATE_queryWithEndAt","endBefore","__PRIVATE_newQueryBoundFromDocument","components","__PRIVATE_newQueryBoundFromFields","__PRIVATE_rawValue","__PRIVATE_wrapped","__PRIVATE_documentIdValue","__PRIVATE_conflictingOp","__PRIVATE_findOpInsideFilters","__PRIVATE_operators","__PRIVATE_conflictingOps","AbstractUserDataWriter","serverTimestampBehavior","convertTimestamp","convertServerTimestamp","convertBytes","convertReference","convertGeoPoint","convertArray","convertObject","convertVectorValue","__PRIVATE_normalizedValue","convertDocumentKey","expectedDatabaseId","__PRIVATE_applyFirestoreDataConverter","__PRIVATE_convertedValue","toFirestore","__PRIVATE_LiteUserDataWriter","average","aggregateFieldEqual","aggregateQuerySnapshotEqual","__PRIVATE_NOT_SUPPORTED","SnapshotMetadata","__PRIVATE_LiteDocumentSnapshot","userDataWriter","_firestoreImpl","serverTimestamps","documentSnapshotFromJSON","__PRIVATE_bundleLoader","__PRIVATE_bundledDocuments","bundleSource","QuerySnapshot","_snapshot","thisArg","_cachedChanges","_cachedChangesIncludeMetadataChanges","__PRIVATE_changesFromSnapshot","__PRIVATE_querySnapshot","oldIndex","newIndex","__PRIVATE_indexTracker","__PRIVATE_resultChangeType","__PRIVATE_documentData","querySnapshotFromJSON","__PRIVATE_bundledDocument","__PRIVATE_externalQuery","snapshotEqual","getDoc","reference","__PRIVATE_convertToDocSnapshot","__PRIVATE_ExpUserDataWriter","getDocFromCache","getDocFromServer","getDocs","getDocsFromCache","getDocsFromServer","setDoc","executeWrite","updateDoc","__PRIVATE_fieldOrUpdateData","deleteDoc","addDoc","__PRIVATE_docRef","onSnapshot","__PRIVATE_currArg","__PRIVATE_internalOptions","__PRIVATE_userObserver","__PRIVATE_internalQuery","__PRIVATE_firestoreClientListen","onSnapshotResume","snapshotJson","__PRIVATE_normalizeSnapshotJsonFields","__PRIVATE_requiredKeys","__PRIVATE_curArg","__PRIVATE_onSnapshotQuerySnapshotBundle","__PRIVATE_internalUnsubscribe","__PRIVATE_unsubscribed","__PRIVATE_loadTask","__PRIVATE_onSnapshotDocumentSnapshotBundle","__PRIVATE_docReference","onSnapshotsInSync","__PRIVATE_firestoreClientWrite","getCountFromServer","getAggregateFromServer","aggregateSpec","__PRIVATE_internalAggregates","__PRIVATE_aggregateResult","__PRIVATE_convertToAggregateQuerySnapshot","__PRIVATE_MemoryLocalCacheImpl","__PRIVATE_PersistentLocalCacheImpl","tabManager","_initialize","persistentSingleTabManager","__PRIVATE_MemoryEagerGarbageCollectorImpl","__PRIVATE_MemoryLruGarbageCollectorImpl","memoryEagerGarbageCollector","memoryLruGarbageCollector","memoryLocalCache","persistentLocalCache","__PRIVATE_SingleTabManagerImpl","__PRIVATE_MultiTabManagerImpl","persistentMultipleTabManager","__PRIVATE_DEFAULT_TRANSACTION_OPTIONS","WriteBatch","_commitHandler","_mutations","_committed","_dataReader","documentRef","_verifyNotCommitted","__PRIVATE_validateReference","_transaction","__PRIVATE_LiteTransaction","__PRIVATE_liteDocumentSnapshot","__PRIVATE_optionsWithDefaults","__PRIVATE_validateTransactionOptions","__PRIVATE_firestoreClientTransaction","__PRIVATE_internalTransaction","deleteField","arrayRemove","vector","writeBatch","setIndexConfiguration","__PRIVATE_jsonOrConfiguration","__PRIVATE_parsedIndexes","__PRIVATE_parseIndexes","__PRIVATE_indexConfiguration","__PRIVATE_tryParseJson","__PRIVATE_tryGetString","arrayConfig","PersistentCacheIndexManager","getPersistentCacheIndexManager","__PRIVATE_cachedInstance","__PRIVATE_persistentCacheIndexManagerByFirestore","enablePersistentCacheIndexAutoCreation","__PRIVATE_setPersistentCacheIndexAutoCreationEnabled","disablePersistentCacheIndexAutoCreation","deleteAllPersistentCacheIndexes","WeakMap","_internalQueryToProtoQueryTarget","_internalAggregationQueryToProtoRunAggregationQueryRequest","TestingHooks","onExistenceFilterMismatch","__PRIVATE_TestingHooksSpiImpl","__PRIVATE_testingHooksSpiImplInstance","__PRIVATE_setTestingHooksSpi","__PRIVATE_existenceFilterMismatchCallbacksById","__PRIVATE_registerFirestore","variant","__PRIVATE_setSDKVersion","_registerComponent","Component","container","getProvider","__PRIVATE_firestoreInstance","__PRIVATE_databaseIdFromApp","setMultipleInstances","registerVersion"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqBaA,MAAAA,IAAAA,CAAAA;AAUX,IAAA,WAAAC,CAAqBC,CAAAA,EAAAA;AAAAC,QAAAA,IAAAA,CAAGD,GAAHA,GAAAA,CAAAA,CAAAA;AAAsB,KAAA;IAE3C,eAAAE,GAAAA;AACE,QAAA,OAAmB,QAAZD,IAAKD,CAAAA,GAAAA,CAAAA;AACb,KAAA;;;;WAMD,KAAAG,GAAAA;AACE,QAAA,OAAIF,IAAKC,CAAAA,eAAAA,EAAAA,GACA,MAASD,GAAAA,IAAAA,CAAKD,GAEd,GAAA,gBAAA,CAAA;AAEV,KAAA;AAED,IAAA,OAAAI,CAAQC,CAAAA,EAAAA;QACN,OAAOA,CAAAA,CAAUL,QAAQC,IAAKD,CAAAA,GAAAA,CAAAA;AAC/B,KAAA;;;+BA5BeM,IAAAA,CAAAA,eAAAA,GAAkB,IAAIR,IAAK,CAAA,IAAA,CAAA;;;AAI3BA,IAAAA,CAAAS,qBAAqB,IAAIT,IAAAA,CAAK,2BAC9BA,IAAAU,CAAAA,WAAAA,GAAc,IAAIV,IAAK,CAAA,iBAAA,CAAA;AACvBA,IAAAW,CAAAA,SAAAA,GAAY,IAAIX,IAAK,CAAA,WAAA,CAAA,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AaxgG,CACxBu7G,CAAAA,EAAAA,CAAAA,CAAAA;AAAiB,KAAA,GAE1B,QACAE,CAAAA,CAAAA,oBAAAA,CAAAA,CAAqB,CAEzBC,CAAAA,CAAAA,EAAAA,mBAAAA,CAAgB5/G,GAAMuX,CAAS4nG,EAAAA,CAAAA,CAAAA;;AAE/BS,IAAAA,mBAAAA,CAAgB5/G,GAAMuX,CAAS,EAAA,SAAA,CAAA,CAAA;AACjC,CCvCA2nG,EAAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"} \ No newline at end of file diff --git a/frontend-old/node_modules/@firebase/firestore/dist/index.d.ts b/frontend-old/node_modules/@firebase/firestore/dist/index.d.ts new file mode 100644 index 0000000..794cf97 --- /dev/null +++ b/frontend-old/node_modules/@firebase/firestore/dist/index.d.ts @@ -0,0 +1,3223 @@ +/** + * Cloud Firestore + * + * @packageDocumentation + */ +import { FirebaseApp } from '@firebase/app'; +import { LogLevelString as LogLevel } from '@firebase/logger'; +import { EmulatorMockTokenOptions } from '@firebase/util'; +import { FirebaseError } from '@firebase/util'; + +/** + * Add a new document to specified `CollectionReference` with the given data, + * assigning it a document ID automatically. + * + * @param reference - A reference to the collection to add this document to. + * @param data - An Object containing the data for the new document. + * @returns A `Promise` resolved with a `DocumentReference` pointing to the + * newly created document after it has been written to the backend (Note that it + * won't resolve while you're offline). + */ +export declare function addDoc(reference: CollectionReference, data: WithFieldValue): Promise>; +/** + * Returns a new map where every key is prefixed with the outer key appended + * to a dot. + */ +export declare type AddPrefixToKeys> = { + [K in keyof T & string as `${Prefix}.${K}`]+?: string extends K ? any : T[K]; +}; +/** + * Represents an aggregation that can be performed by Firestore. + */ +export declare class AggregateField { + /** A type string to uniquely identify instances of this class. */ + readonly type = "AggregateField"; + /** Indicates the aggregation operation of this AggregateField. */ + readonly aggregateType: AggregateType; +} +/** + * Compares two 'AggregateField` instances for equality. + * + * @param left Compare this AggregateField to the `right`. + * @param right Compare this AggregateField to the `left`. + */ +export declare function aggregateFieldEqual(left: AggregateField, right: AggregateField): boolean; +/** + * The union of all `AggregateField` types that are supported by Firestore. + */ +export declare type AggregateFieldType = ReturnType | ReturnType | ReturnType; +/** + * The results of executing an aggregation query. + */ +export declare class AggregateQuerySnapshot { + /** A type string to uniquely identify instances of this class. */ + readonly type = "AggregateQuerySnapshot"; + /** + * The underlying query over which the aggregations recorded in this + * `AggregateQuerySnapshot` were performed. + */ + readonly query: Query; + private constructor(); + /** + * Returns the results of the aggregations performed over the underlying + * query. + * + * The keys of the returned object will be the same as those of the + * `AggregateSpec` object specified to the aggregation method, and the values + * will be the corresponding aggregation result. + * + * @returns The results of the aggregations performed over the underlying + * query. + */ + data(): AggregateSpecData; +} +/** + * Compares two `AggregateQuerySnapshot` instances for equality. + * + * Two `AggregateQuerySnapshot` instances are considered "equal" if they have + * underlying queries that compare equal, and the same data. + * + * @param left - The first `AggregateQuerySnapshot` to compare. + * @param right - The second `AggregateQuerySnapshot` to compare. + * + * @returns `true` if the objects are "equal", as defined above, or `false` + * otherwise. + */ +export declare function aggregateQuerySnapshotEqual(left: AggregateQuerySnapshot, right: AggregateQuerySnapshot): boolean; +/** + * Specifies a set of aggregations and their aliases. + */ +export declare interface AggregateSpec { + [field: string]: AggregateFieldType; +} +/** + * A type whose keys are taken from an `AggregateSpec`, and whose values are the + * result of the aggregation performed by the corresponding `AggregateField` + * from the input `AggregateSpec`. + */ +export declare type AggregateSpecData = { + [P in keyof T]: T[P] extends AggregateField ? U : never; +}; +/** + * Union type representing the aggregate type to be performed. + */ +export declare type AggregateType = 'count' | 'avg' | 'sum'; +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a conjunction of + * the given filter constraints. A conjunction filter includes a document if it + * satisfies all of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a conjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +export declare function and(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; +/** + * Returns a special value that can be used with {@link (setDoc:1)} or {@link + * updateDoc:1} that tells the server to remove the given elements from any + * array value that already exists on the server. All instances of each element + * specified will be removed from the array. If the field being modified is not + * already an array it will be overwritten with an empty array. + * + * @param elements - The elements to remove from the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +export declare function arrayRemove(...elements: unknown[]): FieldValue; +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to union the given elements with any array + * value that already exists on the server. Each specified element that doesn't + * already exist in the array will be added to the end. If the field being + * modified is not already an array it will be overwritten with an array + * containing exactly the specified elements. + * + * @param elements - The elements to union into the array. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()`. + */ +export declare function arrayUnion(...elements: unknown[]): FieldValue; +/* Excluded from this release type: AuthTokenFactory */ +/* Excluded from this release type: _AutoId */ +/** + * Create an AggregateField object that can be used to compute the average of + * a specified field over a range of documents in the result set of a query. + * @param field Specifies the field to average across the result set. + */ +export declare function average(field: string | FieldPath): AggregateField; +/** + * An immutable object representing an array of bytes. + */ +export declare class Bytes { + private constructor(); + /** + * Creates a new `Bytes` object from the given Base64 string, converting it to + * bytes. + * + * @param base64 - The Base64 string used to create the `Bytes` object. + */ + static fromBase64String(base64: string): Bytes; + /** + * Creates a new `Bytes` object from the given Uint8Array. + * + * @param array - The Uint8Array used to create the `Bytes` object. + */ + static fromUint8Array(array: Uint8Array): Bytes; + /** + * Returns the underlying bytes as a Base64-encoded string. + * + * @returns The Base64-encoded string created from the `Bytes` object. + */ + toBase64(): string; + /** + * Returns the underlying bytes in a new `Uint8Array`. + * + * @returns The Uint8Array created from the `Bytes` object. + */ + toUint8Array(): Uint8Array; + /** + * Returns a string representation of the `Bytes` object. + * + * @returns A string representation of the `Bytes` object. + */ + toString(): string; + /** + * Returns true if this `Bytes` object is equal to the provided one. + * + * @param other - The `Bytes` object to compare against. + * @returns true if this `Bytes` object is equal to the provided one. + */ + isEqual(other: Bytes): boolean; + /** + * Returns a JSON-serializable representation of this `Bytes` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `Bytes` instance from a JSON object created by {@link Bytes.toJSON}. + * + * @param json a JSON object represention of a `Bytes` instance + * @returns an instance of {@link Bytes} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): Bytes; +} +/* Excluded from this release type: _ByteString */ +/** + * Constant used to indicate the LRU garbage collection should be disabled. + * Set this value as the `cacheSizeBytes` on the settings passed to the + * {@link Firestore} instance. + */ +export declare const CACHE_SIZE_UNLIMITED = -1; +/** + * Helper for calculating the nested fields for a given type T1. This is needed + * to distribute union types such as `undefined | {...}` (happens for optional + * props) or `{a: A} | {b: B}`. + * + * In this use case, `V` is used to distribute the union types of `T[K]` on + * `Record`, since `T[K]` is evaluated as an expression and not distributed. + * + * See https://www.typescriptlang.org/docs/handbook/advanced-types.html#distributive-conditional-types + */ +export declare type ChildUpdateFields = V extends Record ? AddPrefixToKeys> : never; +/** + * Clears the persistent storage. This includes pending writes and cached + * documents. + * + * Must be called while the {@link Firestore} instance is not started (after the app is + * terminated or when the app is first initialized). On startup, this function + * must be called before other functions (other than {@link + * initializeFirestore} or {@link (getFirestore:1)})). If the {@link Firestore} + * instance is still running, the promise will be rejected with the error code + * of `failed-precondition`. + * + * Note: `clearIndexedDbPersistence()` is primarily intended to help write + * reliable tests that use Cloud Firestore. It uses an efficient mechanism for + * dropping existing data but does not attempt to securely overwrite or + * otherwise make cached data unrecoverable. For applications that are sensitive + * to the disclosure of cached data in between user sessions, we strongly + * recommend not enabling persistence at all. + * + * @param firestore - The {@link Firestore} instance to clear persistence for. + * @returns A `Promise` that is resolved when the persistent storage is + * cleared. Otherwise, the promise is rejected with an error. + */ +export declare function clearIndexedDbPersistence(firestore: Firestore): Promise; +/** + * Gets a `CollectionReference` instance that refers to the collection at + * the specified absolute path. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments to apply relative to the first + * argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(firestore: Firestore, path: string, ...pathSegments: string[]): CollectionReference; +/** + * Gets a `CollectionReference` instance that refers to a subcollection of + * `reference` at the specified relative path. + * + * @param reference - A reference to a collection. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments to apply relative to the first + * argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(reference: CollectionReference, path: string, ...pathSegments: string[]): CollectionReference; +/** + * Gets a `CollectionReference` instance that refers to a subcollection of + * `reference` at the specified relative path. + * + * @param reference - A reference to a Firestore document. + * @param path - A slash-separated path to a collection. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an even number of segments and does not point + * to a collection. + * @returns The `CollectionReference` instance. + */ +export declare function collection(reference: DocumentReference, path: string, ...pathSegments: string[]): CollectionReference; +/** + * Creates and returns a new `Query` instance that includes all documents in the + * database that are contained in a collection or subcollection with the + * given `collectionId`. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param collectionId - Identifies the collections to query over. Every + * collection or subcollection with this ID as the last segment of its path + * will be included. Cannot contain a slash. + * @returns The created `Query`. + */ +export declare function collectionGroup(firestore: Firestore, collectionId: string): Query; +/** + * A `CollectionReference` object can be used for adding documents, getting + * document references, and querying for documents (using {@link (query:1)}). + */ +export declare class CollectionReference extends Query { + /** The type of this Firestore reference. */ + readonly type = "collection"; + private constructor(); + /** The collection's identifier. */ + get id(): string; + /** + * A string representing the path of the referenced collection (relative + * to the root of the database). + */ + get path(): string; + /** + * A reference to the containing `DocumentReference` if this is a + * subcollection. If this isn't a subcollection, the reference is null. + */ + get parent(): DocumentReference | null; + /** + * Applies a custom data converter to this `CollectionReference`, allowing you + * to use your own custom model objects with Firestore. When you call {@link + * addDoc} with the returned `CollectionReference` instance, the provided + * converter will convert between Firestore data of type `NewDbModelType` and + * your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `CollectionReference` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter): CollectionReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `CollectionReference` that does not + * use a converter. + */ + withConverter(converter: null): CollectionReference; +} +/** + * Modify this instance to communicate with the Cloud Firestore emulator. + * + * Note: This must be called before this instance has been used to do any + * operations. + * + * @param firestore - The `Firestore` instance to configure to connect to the + * emulator. + * @param host - the emulator host (ex: localhost). + * @param port - the emulator port (ex: 9000). + * @param options.mockUserToken - the mock auth token to use for unit testing + * Security Rules. + */ +export declare function connectFirestoreEmulator(firestore: Firestore, host: string, port: number, options?: { + mockUserToken?: EmulatorMockTokenOptions | string; +}): void; +/** + * Create an AggregateField object that can be used to compute the count of + * documents in the result set of a query. + */ +export declare function count(): AggregateField; +/** + * Removes all persistent cache indexes. + * + * Please note this function will also deletes indexes generated by + * `setIndexConfiguration()`, which is deprecated. + */ +export declare function deleteAllPersistentCacheIndexes(indexManager: PersistentCacheIndexManager): void; +/** + * Deletes the document referred to by the specified `DocumentReference`. + * + * @param reference - A reference to the document to delete. + * @returns A Promise resolved once the document has been successfully + * deleted from the backend (note that it won't resolve while you're offline). + */ +export declare function deleteDoc(reference: DocumentReference): Promise; +/** + * Returns a sentinel for use with {@link @firebase/firestore/lite#(updateDoc:1)} or + * {@link @firebase/firestore/lite#(setDoc:1)} with `{merge: true}` to mark a field for deletion. + */ +export declare function deleteField(): FieldValue; +/** + * Disables network usage for this instance. It can be re-enabled via {@link + * enableNetwork}. While the network is disabled, any snapshot listeners, + * `getDoc()` or `getDocs()` calls will return results from cache, and any write + * operations will be queued until the network is restored. + * + * @returns A `Promise` that is resolved once the network has been disabled. + */ +export declare function disableNetwork(firestore: Firestore): Promise; +/** + * Stops creating persistent cache indexes automatically for local query + * execution. The indexes which have been created by calling + * `enablePersistentCacheIndexAutoCreation()` still take effect. + */ +export declare function disablePersistentCacheIndexAutoCreation(indexManager: PersistentCacheIndexManager): void; +/** + * Gets a `DocumentReference` instance that refers to the document at the + * specified absolute path. + * + * @param firestore - A reference to the root `Firestore` instance. + * @param path - A slash-separated path to a document. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(firestore: Firestore, path: string, ...pathSegments: string[]): DocumentReference; +/** + * Gets a `DocumentReference` instance that refers to a document within + * `reference` at the specified relative path. If no path is specified, an + * automatically-generated unique ID will be used for the returned + * `DocumentReference`. + * + * @param reference - A reference to a collection. + * @param path - A slash-separated path to a document. Has to be omitted to use + * auto-generated IDs. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(reference: CollectionReference, path?: string, ...pathSegments: string[]): DocumentReference; +/** + * Gets a `DocumentReference` instance that refers to a document within + * `reference` at the specified relative path. + * + * @param reference - A reference to a Firestore document. + * @param path - A slash-separated path to a document. + * @param pathSegments - Additional path segments that will be applied relative + * to the first argument. + * @throws If the final path has an odd number of segments and does not point to + * a document. + * @returns The `DocumentReference` instance. + */ +export declare function doc(reference: DocumentReference, path: string, ...pathSegments: string[]): DocumentReference; +/** + * A `DocumentChange` represents a change to the documents matching a query. + * It contains the document affected and the type of change that occurred. + */ +export declare interface DocumentChange { + /** The type of change ('added', 'modified', or 'removed'). */ + readonly type: DocumentChangeType; + /** The document affected by this change. */ + readonly doc: QueryDocumentSnapshot; + /** + * The index of the changed document in the result set immediately prior to + * this `DocumentChange` (i.e. supposing that all prior `DocumentChange` objects + * have been applied). Is `-1` for 'added' events. + */ + readonly oldIndex: number; + /** + * The index of the changed document in the result set immediately after + * this `DocumentChange` (i.e. supposing that all prior `DocumentChange` + * objects and the current `DocumentChange` object have been applied). + * Is -1 for 'removed' events. + */ + readonly newIndex: number; +} +/** + * The type of a `DocumentChange` may be 'added', 'removed', or 'modified'. + */ +export declare type DocumentChangeType = 'added' | 'removed' | 'modified'; +/** + * Document data (for use with {@link @firebase/firestore/lite#(setDoc:1)}) consists of fields mapped to + * values. + */ +export declare interface DocumentData { + /** A mapping between a field and its value. */ + [field: string]: any; +} +/** + * Returns a special sentinel `FieldPath` to refer to the ID of a document. + * It can be used in queries to sort or filter by the document ID. + */ +export declare function documentId(): FieldPath; +/** + * A `DocumentReference` refers to a document location in a Firestore database + * and can be used to write, read, or listen to the location. The document at + * the referenced location may or may not exist. + */ +export declare class DocumentReference { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter | null; + /** The type of this Firestore reference. */ + readonly type = "document"; + /** + * The {@link Firestore} instance the document is in. + * This is useful for performing transactions, for example. + */ + readonly firestore: Firestore; + private constructor(); + /** + * The document's identifier within its collection. + */ + get id(): string; + /** + * A string representing the path of the referenced document (relative + * to the root of the database). + */ + get path(): string; + /** + * The collection this `DocumentReference` belongs to. + */ + get parent(): CollectionReference; + /** + * Applies a custom data converter to this `DocumentReference`, allowing you + * to use your own custom model objects with Firestore. When you call {@link + * @firebase/firestore/lite#(setDoc:1)}, {@link @firebase/firestore/lite#getDoc}, etc. with the returned `DocumentReference` + * instance, the provided converter will convert between Firestore data of + * type `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `DocumentReference` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter): DocumentReference; + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `DocumentReference` that does not + * use a converter. + */ + withConverter(converter: null): DocumentReference; + /** + * Returns a JSON-serializable representation of this `DocumentReference` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): object; + /** + * Builds a `DocumentReference` instance from a JSON object created by + * {@link DocumentReference.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json a JSON object represention of a `DocumentReference` instance + * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(firestore: Firestore, json: object): DocumentReference; + /** + * Builds a `DocumentReference` instance from a JSON object created by + * {@link DocumentReference.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json a JSON object represention of a `DocumentReference` instance + * @param converter - Converts objects to and from Firestore. + * @returns an instance of {@link DocumentReference} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(firestore: Firestore, json: object, converter: FirestoreDataConverter): DocumentReference; +} +/** + * A `DocumentSnapshot` contains data read from a document in your Firestore + * database. The data can be extracted with `.data()` or `.get()` to + * get a specific field. + * + * For a `DocumentSnapshot` that points to a non-existing document, any data + * access will return 'undefined'. You can use the `exists()` method to + * explicitly verify a document's existence. + */ +export declare class DocumentSnapshot { + /** + * Metadata about the `DocumentSnapshot`, including information about its + * source and local modifications. + */ + readonly metadata: SnapshotMetadata; + protected constructor(); + /** + * Returns whether or not the data exists. True if the document exists. + */ + exists(): this is QueryDocumentSnapshot; + /** + * Retrieves all fields in the document as an `Object`. Returns `undefined` if + * the document doesn't exist. + * + * By default, `serverTimestamp()` values that have not yet been + * set to their final value will be returned as `null`. You can override + * this by passing an options object. + * + * @param options - An options object to configure how data is retrieved from + * the snapshot (for example the desired behavior for server timestamps that + * have not yet been set to their final value). + * @returns An `Object` containing all fields in the document or `undefined` if + * the document doesn't exist. + */ + data(options?: SnapshotOptions): AppModelType | undefined; + /** + * Retrieves the field specified by `fieldPath`. Returns `undefined` if the + * document or field doesn't exist. + * + * By default, a `serverTimestamp()` that has not yet been set to + * its final value will be returned as `null`. You can override this by + * passing an options object. + * + * @param fieldPath - The path (for example 'foo' or 'foo.bar') to a specific + * field. + * @param options - An options object to configure how the field is retrieved + * from the snapshot (for example the desired behavior for server timestamps + * that have not yet been set to their final value). + * @returns The data at the specified field location or undefined if no such + * field exists in the document. + */ + get(fieldPath: string | FieldPath, options?: SnapshotOptions): any; + /** + * Returns a JSON-serializable representation of this `DocumentSnapshot` instance. + * + * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this + * `DocumentSnapshot` has pending writes. + */ + toJSON(): object; + /** + * Property of the `DocumentSnapshot` that provides the document's ID. + */ + get id(): string; + /** + * The `DocumentReference` for the document included in the `DocumentSnapshot`. + */ + get ref(): DocumentReference; +} +/** + * Builds a `DocumentSnapshot` instance from a JSON object created by + * {@link DocumentSnapshot.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json - a JSON object represention of a `DocumentSnapshot` instance. + * @returns an instance of {@link DocumentSnapshot} if the JSON object could be + * parsed. Throws a {@link FirestoreError} if an error occurs. + */ +export declare function documentSnapshotFromJSON(db: Firestore, json: object): DocumentSnapshot; +/** + * Builds a `DocumentSnapshot` instance from a JSON object created by + * {@link DocumentSnapshot.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json - a JSON object represention of a `DocumentSnapshot` instance. + * @param converter - Converts objects to and from Firestore. + * @returns an instance of {@link DocumentSnapshot} if the JSON object could be + * parsed. Throws a {@link FirestoreError} if an error occurs. + */ +export declare function documentSnapshotFromJSON(db: Firestore, json: object, converter: FirestoreDataConverter): DocumentSnapshot; +/* Excluded from this release type: _EmptyAppCheckTokenProvider */ +/* Excluded from this release type: _EmptyAuthCredentialsProvider */ +export { EmulatorMockTokenOptions }; +/** + * Attempts to enable persistent storage, if possible. + * + * On failure, `enableIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. + * + * * failed-precondition: The app is already open in another browser tab. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. + * + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. + * + * Note: `enableIndexedDbPersistence()` must be called before any other functions + * (other than {@link initializeFirestore}, {@link (getFirestore:1)} or + * {@link clearIndexedDbPersistence}. + * + * Persistence cannot be used in a Node.js environment. + * + * @param firestore - The {@link Firestore} instance to enable persistence for. + * @param persistenceSettings - Optional settings object to configure + * persistence. + * @returns A `Promise` that represents successfully enabling persistent storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on IndexedDb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. + */ +export declare function enableIndexedDbPersistence(firestore: Firestore, persistenceSettings?: PersistenceSettings): Promise; +/** + * Attempts to enable multi-tab persistent storage, if possible. If enabled + * across all tabs, all operations share access to local persistence, including + * shared execution of queries and latency-compensated local document updates + * across all connected instances. + * + * On failure, `enableMultiTabIndexedDbPersistence()` will reject the promise or + * throw an exception. There are several reasons why this can fail, which can be + * identified by the `code` on the error. + * + * * failed-precondition: The app is already open in another browser tab and + * multi-tab is not enabled. + * * unimplemented: The browser is incompatible with the offline persistence + * implementation. + * + * Note that even after a failure, the {@link Firestore} instance will remain + * usable, however offline persistence will be disabled. + * + * @param firestore - The {@link Firestore} instance to enable persistence for. + * @returns A `Promise` that represents successfully enabling persistent + * storage. + * @deprecated This function will be removed in a future major release. Instead, set + * `FirestoreSettings.localCache` to an instance of `PersistentLocalCache` to + * turn on indexeddb cache. Calling this function when `FirestoreSettings.localCache` + * is already specified will throw an exception. + */ +export declare function enableMultiTabIndexedDbPersistence(firestore: Firestore): Promise; +/** + * Re-enables use of the network for this {@link Firestore} instance after a prior + * call to {@link disableNetwork}. + * + * @returns A `Promise` that is resolved once the network has been enabled. + */ +export declare function enableNetwork(firestore: Firestore): Promise; +/** + * Enables the SDK to create persistent cache indexes automatically for local + * query execution when the SDK believes cache indexes can help improve + * performance. + * + * This feature is disabled by default. + */ +export declare function enablePersistentCacheIndexAutoCreation(indexManager: PersistentCacheIndexManager): void; +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided document (inclusive). The end position is relative to the order + * of the query. The document must contain all of the fields provided in the + * orderBy of the query. + * + * @param snapshot - The snapshot of the document to end at. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endAt(snapshot: DocumentSnapshot): QueryEndAtConstraint; +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end at + * the provided fields relative to the order of the query. The order of the field + * values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to end this query at, in order + * of the query's order by. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endAt(...fieldValues: unknown[]): QueryEndAtConstraint; +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided document (exclusive). The end position is relative to the + * order of the query. The document must contain all of the fields provided in + * the orderBy of the query. + * + * @param snapshot - The snapshot of the document to end before. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endBefore(snapshot: DocumentSnapshot): QueryEndAtConstraint; +/** + * Creates a {@link QueryEndAtConstraint} that modifies the result set to end + * before the provided fields relative to the order of the query. The order of + * the field values must match the order of the order by clauses of the query. + * + * @param fieldValues - The field values to end this query before, in order + * of the query's order by. + * @returns A {@link QueryEndAtConstraint} to pass to `query()` + */ +export declare function endBefore(...fieldValues: unknown[]): QueryEndAtConstraint; +/* Excluded from this release type: executeWrite */ +/** + * @license + * Copyright 2023 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Options that configure the SDK’s underlying network transport (WebChannel) + * when long-polling is used. + * + * Note: This interface is "experimental" and is subject to change. + * + * See `FirestoreSettings.experimentalAutoDetectLongPolling`, + * `FirestoreSettings.experimentalForceLongPolling`, and + * `FirestoreSettings.experimentalLongPollingOptions`. + */ +export declare interface ExperimentalLongPollingOptions { + /** + * The desired maximum timeout interval, in seconds, to complete a + * long-polling GET response. Valid values are between 5 and 30, inclusive. + * Floating point values are allowed and will be rounded to the nearest + * millisecond. + * + * By default, when long-polling is used the "hanging GET" request sent by + * the client times out after 30 seconds. To request a different timeout + * from the server, set this setting with the desired timeout. + * + * Changing the default timeout may be useful, for example, if the buffering + * proxy that necessitated enabling long-polling in the first place has a + * shorter timeout for hanging GET requests, in which case setting the + * long-polling timeout to a shorter value, such as 25 seconds, may fix + * prematurely-closed hanging GET requests. + * For example, see https://github.com/firebase/firebase-js-sdk/issues/6987. + */ + timeoutSeconds?: number; +} +/** + * A `FieldPath` refers to a field in a document. The path may consist of a + * single field name (referring to a top-level field in the document), or a + * list of field names (referring to a nested field in the document). + * + * Create a `FieldPath` by providing field names. If more than one field + * name is provided, the path will point to a nested field in a document. + */ +export declare class FieldPath { + /** + * Creates a `FieldPath` from the provided field names. If more than one field + * name is provided, the path will point to a nested field in a document. + * + * @param fieldNames - A list of field names. + */ + constructor(...fieldNames: string[]); + /** + * Returns true if this `FieldPath` is equal to the provided one. + * + * @param other - The `FieldPath` to compare against. + * @returns true if this `FieldPath` is equal to the provided one. + */ + isEqual(other: FieldPath): boolean; +} +/** + * Sentinel values that can be used when writing document fields with `set()` + * or `update()`. + */ +export declare abstract class FieldValue { + private constructor(); + /** Compares `FieldValue`s for equality. */ + abstract isEqual(other: FieldValue): boolean; +} +/* Excluded from this release type: _FirebaseService */ +/** + * The Cloud Firestore service interface. + * + * Do not call this constructor directly. Instead, use {@link (getFirestore:1)}. + */ +export declare class Firestore { + /** + * Whether it's a {@link Firestore} or Firestore Lite instance. + */ + type: 'firestore-lite' | 'firestore'; + private constructor(); + /** + * The {@link @firebase/app#FirebaseApp} associated with this `Firestore` service + * instance. + */ + get app(): FirebaseApp; + /** + * Returns a JSON-serializable representation of this `Firestore` instance. + */ + toJSON(): object; +} +/** + * Converter used by `withConverter()` to transform user objects of type + * `AppModelType` into Firestore data of type `DbModelType`. + * + * Using the converter allows you to specify generic type arguments when + * storing and retrieving objects from Firestore. + * + * In this context, an "AppModel" is a class that is used in an application to + * package together related information and functionality. Such a class could, + * for example, have properties with complex, nested data types, properties used + * for memoization, properties of types not supported by Firestore (such as + * `symbol` and `bigint`), and helper functions that perform compound + * operations. Such classes are not suitable and/or possible to store into a + * Firestore database. Instead, instances of such classes need to be converted + * to "plain old JavaScript objects" (POJOs) with exclusively primitive + * properties, potentially nested inside other POJOs or arrays of POJOs. In this + * context, this type is referred to as the "DbModel" and would be an object + * suitable for persisting into Firestore. For convenience, applications can + * implement `FirestoreDataConverter` and register the converter with Firestore + * objects, such as `DocumentReference` or `Query`, to automatically convert + * `AppModel` to `DbModel` when storing into Firestore, and convert `DbModel` + * to `AppModel` when retrieving from Firestore. + * + * @example + * + * Simple Example + * + * ```typescript + * const numberConverter = { + * toFirestore(value: WithFieldValue) { + * return { value }; + * }, + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions) { + * return snapshot.data(options).value as number; + * } + * }; + * + * async function simpleDemo(db: Firestore): Promise { + * const documentRef = doc(db, 'values/value123').withConverter(numberConverter); + * + * // converters are used with `setDoc`, `addDoc`, and `getDoc` + * await setDoc(documentRef, 42); + * const snapshot1 = await getDoc(documentRef); + * assertEqual(snapshot1.data(), 42); + * + * // converters are not used when writing data with `updateDoc` + * await updateDoc(documentRef, { value: 999 }); + * const snapshot2 = await getDoc(documentRef); + * assertEqual(snapshot2.data(), 999); + * } + * ``` + * + * Advanced Example + * + * ```typescript + * // The Post class is a model that is used by our application. + * // This class may have properties and methods that are specific + * // to our application execution, which do not need to be persisted + * // to Firestore. + * class Post { + * constructor( + * readonly title: string, + * readonly author: string, + * readonly lastUpdatedMillis: number + * ) {} + * toString(): string { + * return `${this.title} by ${this.author}`; + * } + * } + * + * // The PostDbModel represents how we want our posts to be stored + * // in Firestore. This DbModel has different properties (`ttl`, + * // `aut`, and `lut`) from the Post class we use in our application. + * interface PostDbModel { + * ttl: string; + * aut: { firstName: string; lastName: string }; + * lut: Timestamp; + * } + * + * // The `PostConverter` implements `FirestoreDataConverter` and specifies + * // how the Firestore SDK can convert `Post` objects to `PostDbModel` + * // objects and vice versa. + * class PostConverter implements FirestoreDataConverter { + * toFirestore(post: WithFieldValue): WithFieldValue { + * return { + * ttl: post.title, + * aut: this._autFromAuthor(post.author), + * lut: this._lutFromLastUpdatedMillis(post.lastUpdatedMillis) + * }; + * } + * + * fromFirestore(snapshot: QueryDocumentSnapshot, options: SnapshotOptions): Post { + * const data = snapshot.data(options) as PostDbModel; + * const author = `${data.aut.firstName} ${data.aut.lastName}`; + * return new Post(data.ttl, author, data.lut.toMillis()); + * } + * + * _autFromAuthor( + * author: string | FieldValue + * ): { firstName: string; lastName: string } | FieldValue { + * if (typeof author !== 'string') { + * // `author` is a FieldValue, so just return it. + * return author; + * } + * const [firstName, lastName] = author.split(' '); + * return {firstName, lastName}; + * } + * + * _lutFromLastUpdatedMillis( + * lastUpdatedMillis: number | FieldValue + * ): Timestamp | FieldValue { + * if (typeof lastUpdatedMillis !== 'number') { + * // `lastUpdatedMillis` must be a FieldValue, so just return it. + * return lastUpdatedMillis; + * } + * return Timestamp.fromMillis(lastUpdatedMillis); + * } + * } + * + * async function advancedDemo(db: Firestore): Promise { + * // Create a `DocumentReference` with a `FirestoreDataConverter`. + * const documentRef = doc(db, 'posts/post123').withConverter(new PostConverter()); + * + * // The `data` argument specified to `setDoc()` is type checked by the + * // TypeScript compiler to be compatible with `Post`. Since the `data` + * // argument is typed as `WithFieldValue` rather than just `Post`, + * // this allows properties of the `data` argument to also be special + * // Firestore values that perform server-side mutations, such as + * // `arrayRemove()`, `deleteField()`, and `serverTimestamp()`. + * await setDoc(documentRef, { + * title: 'My Life', + * author: 'Foo Bar', + * lastUpdatedMillis: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `setDoc()` is _not_ compatible with `WithFieldValue`. This + * // type checking prevents the caller from specifying objects with incorrect + * // properties or property values. + * // @ts-expect-error "Argument of type { ttl: string; } is not assignable + * // to parameter of type WithFieldValue" + * await setDoc(documentRef, { ttl: 'The Title' }); + * + * // When retrieving a document with `getDoc()` the `DocumentSnapshot` + * // object's `data()` method returns a `Post`, rather than a generic object, + * // which would have been returned if the `DocumentReference` did _not_ have a + * // `FirestoreDataConverter` attached to it. + * const snapshot1: DocumentSnapshot = await getDoc(documentRef); + * const post1: Post = snapshot1.data()!; + * if (post1) { + * assertEqual(post1.title, 'My Life'); + * assertEqual(post1.author, 'Foo Bar'); + * } + * + * // The `data` argument specified to `updateDoc()` is type checked by the + * // TypeScript compiler to be compatible with `PostDbModel`. Note that + * // unlike `setDoc()`, whose `data` argument must be compatible with `Post`, + * // the `data` argument to `updateDoc()` must be compatible with + * // `PostDbModel`. Similar to `setDoc()`, since the `data` argument is typed + * // as `WithFieldValue` rather than just `PostDbModel`, this + * // allows properties of the `data` argument to also be those special + * // Firestore values, like `arrayRemove()`, `deleteField()`, and + * // `serverTimestamp()`. + * await updateDoc(documentRef, { + * 'aut.firstName': 'NewFirstName', + * lut: serverTimestamp() + * }); + * + * // The TypeScript compiler will fail to compile if the `data` argument to + * // `updateDoc()` is _not_ compatible with `WithFieldValue`. + * // This type checking prevents the caller from specifying objects with + * // incorrect properties or property values. + * // @ts-expect-error "Argument of type { title: string; } is not assignable + * // to parameter of type WithFieldValue" + * await updateDoc(documentRef, { title: 'New Title' }); + * const snapshot2: DocumentSnapshot = await getDoc(documentRef); + * const post2: Post = snapshot2.data()!; + * if (post2) { + * assertEqual(post2.title, 'My Life'); + * assertEqual(post2.author, 'NewFirstName Bar'); + * } + * } + * ``` + */ +export declare interface FirestoreDataConverter { + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. To use `set()` + * with `merge` and `mergeFields`, `toFirestore()` must be defined with + * `PartialWithFieldValue`. + * + * The `WithFieldValue` type extends `T` to also allow FieldValues such as + * {@link (deleteField:1)} to be used as property values. + */ + toFirestore(modelObject: WithFieldValue): WithFieldValue; + /** + * Called by the Firestore SDK to convert a custom model object of type + * `AppModelType` into a plain JavaScript object (suitable for writing + * directly to the Firestore database) of type `DbModelType`. Used with + * {@link (setDoc:1)}, {@link (WriteBatch.set:1)} and + * {@link (Transaction.set:1)} with `merge:true` or `mergeFields`. + * + * The `PartialWithFieldValue` type extends `Partial` to allow + * FieldValues such as {@link (arrayUnion:1)} to be used as property values. + * It also supports nested `Partial` by allowing nested fields to be + * omitted. + */ + toFirestore(modelObject: PartialWithFieldValue, options: SetOptions): PartialWithFieldValue; + /** + * Called by the Firestore SDK to convert Firestore data into an object of + * type `AppModelType`. You can access your data by calling: + * `snapshot.data(options)`. + * + * Generally, the data returned from `snapshot.data()` can be cast to + * `DbModelType`; however, this is not guaranteed because Firestore does not + * enforce a schema on the database. For example, writes from a previous + * version of the application or writes from another client that did not use a + * type converter could have written data with different properties and/or + * property types. The implementation will need to choose whether to + * gracefully recover from non-conforming data or throw an error. + * + * To override this method, see {@link (FirestoreDataConverter.fromFirestore:1)}. + * + * @param snapshot - A `QueryDocumentSnapshot` containing your data and metadata. + * @param options - The `SnapshotOptions` from the initial call to `data()`. + */ + fromFirestore(snapshot: QueryDocumentSnapshot, options?: SnapshotOptions): AppModelType; +} +/** An error returned by a Firestore operation. */ +export declare class FirestoreError extends FirebaseError { + /** + * The backend error code associated with this error. + */ + readonly code: FirestoreErrorCode; + /** + * A custom error description. + */ + readonly message: string; + /** The stack of the error. */ + readonly stack?: string; + private constructor(); +} +/** + * The set of Firestore status codes. The codes are the same at the ones + * exposed by gRPC here: + * https://github.com/grpc/grpc/blob/master/doc/statuscodes.md + * + * Possible values: + * - 'cancelled': The operation was cancelled (typically by the caller). + * - 'unknown': Unknown error or an error from a different error domain. + * - 'invalid-argument': Client specified an invalid argument. Note that this + * differs from 'failed-precondition'. 'invalid-argument' indicates + * arguments that are problematic regardless of the state of the system + * (e.g. an invalid field name). + * - 'deadline-exceeded': Deadline expired before operation could complete. + * For operations that change the state of the system, this error may be + * returned even if the operation has completed successfully. For example, + * a successful response from a server could have been delayed long enough + * for the deadline to expire. + * - 'not-found': Some requested document was not found. + * - 'already-exists': Some document that we attempted to create already + * exists. + * - 'permission-denied': The caller does not have permission to execute the + * specified operation. + * - 'resource-exhausted': Some resource has been exhausted, perhaps a + * per-user quota, or perhaps the entire file system is out of space. + * - 'failed-precondition': Operation was rejected because the system is not + * in a state required for the operation's execution. + * - 'aborted': The operation was aborted, typically due to a concurrency + * issue like transaction aborts, etc. + * - 'out-of-range': Operation was attempted past the valid range. + * - 'unimplemented': Operation is not implemented or not supported/enabled. + * - 'internal': Internal errors. Means some invariants expected by + * underlying system has been broken. If you see one of these errors, + * something is very broken. + * - 'unavailable': The service is currently unavailable. This is most likely + * a transient condition and may be corrected by retrying with a backoff. + * - 'data-loss': Unrecoverable data loss or corruption. + * - 'unauthenticated': The request does not have valid authentication + * credentials for the operation. + */ +export declare type FirestoreErrorCode = 'cancelled' | 'unknown' | 'invalid-argument' | 'deadline-exceeded' | 'not-found' | 'already-exists' | 'permission-denied' | 'resource-exhausted' | 'failed-precondition' | 'aborted' | 'out-of-range' | 'unimplemented' | 'internal' | 'unavailable' | 'data-loss' | 'unauthenticated'; +/** + * Union type from all supported SDK cache layer. + */ +export declare type FirestoreLocalCache = MemoryLocalCache | PersistentLocalCache; +/** + * Specifies custom configurations for your Cloud Firestore instance. + * You must set these before invoking any other methods. + */ +export declare interface FirestoreSettings { + /** + * NOTE: This field will be deprecated in a future major release. Use `cache` field + * instead to specify cache size, and other cache configurations. + * + * An approximate cache size threshold for the on-disk data. If the cache + * grows beyond this size, Firestore will start removing data that hasn't been + * recently used. The size is not a guarantee that the cache will stay below + * that size, only that if the cache exceeds the given size, cleanup will be + * attempted. + * + * The default value is 40 MB. The threshold must be set to at least 1 MB, and + * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection. + */ + cacheSizeBytes?: number; + /** + * Specifies the cache used by the SDK. Available options are `MemoryLocalCache` + * and `PersistentLocalCache`, each with different configuration options. + * + * When unspecified, `MemoryLocalCache` will be used by default. + * + * NOTE: setting this field and `cacheSizeBytes` at the same time will throw + * exception during SDK initialization. Instead, using the configuration in + * the `FirestoreLocalCache` object to specify the cache size. + */ + localCache?: FirestoreLocalCache; + /** + * Forces the SDK’s underlying network transport (WebChannel) to use + * long-polling. Each response from the backend will be closed immediately + * after the backend sends data (by default responses are kept open in + * case the backend has more data to send). This avoids incompatibility + * issues with certain proxies, antivirus software, etc. that incorrectly + * buffer traffic indefinitely. Use of this option will cause some + * performance degradation though. + * + * This setting cannot be used with `experimentalAutoDetectLongPolling` and + * may be removed in a future release. If you find yourself using it to + * work around a specific network reliability issue, please tell us about + * it in https://github.com/firebase/firebase-js-sdk/issues/1674. + * + * This setting cannot be used in a Node.js environment. + */ + experimentalForceLongPolling?: boolean; + /** + * Configures the SDK's underlying transport (WebChannel) to automatically + * detect if long-polling should be used. This is very similar to + * `experimentalForceLongPolling`, but only uses long-polling if required. + * + * After having had a default value of `false` since its inception in 2019, + * the default value of this setting was changed in May 2023 to `true` in + * v9.22.0 of the Firebase JavaScript SDK. That is, auto-detection of long + * polling is now enabled by default. To disable it, set this setting to + * `false`, and please open a GitHub issue to share the problems that + * motivated you disabling long-polling auto-detection. + * + * This setting cannot be used in a Node.js environment. + */ + experimentalAutoDetectLongPolling?: boolean; + /** + * Options that configure the SDK’s underlying network transport (WebChannel) + * when long-polling is used. + * + * These options are only used if `experimentalForceLongPolling` is true or if + * `experimentalAutoDetectLongPolling` is true and the auto-detection + * determined that long-polling was needed. Otherwise, these options have no + * effect. + */ + experimentalLongPollingOptions?: ExperimentalLongPollingOptions; + /** + * The hostname to connect to. + */ + host?: string; + /** + * Whether to use SSL when connecting. + */ + ssl?: boolean; + /** + * Whether to skip nested properties that are set to `undefined` during + * object serialization. If set to `true`, these properties are skipped + * and not written to Firestore. If set to `false` or omitted, the SDK + * throws an exception when it encounters properties of type `undefined`. + */ + ignoreUndefinedProperties?: boolean; +} +/** + * An immutable object representing a geographic location in Firestore. The + * location is represented as latitude/longitude pair. + * + * Latitude values are in the range of [-90, 90]. + * Longitude values are in the range of [-180, 180]. + */ +export declare class GeoPoint { + /** + * Creates a new immutable `GeoPoint` object with the provided latitude and + * longitude values. + * @param latitude - The latitude as number between -90 and 90. + * @param longitude - The longitude as number between -180 and 180. + */ + constructor(latitude: number, longitude: number); + /** + * The latitude of this `GeoPoint` instance. + */ + get latitude(): number; + /** + * The longitude of this `GeoPoint` instance. + */ + get longitude(): number; + /** + * Returns true if this `GeoPoint` is equal to the provided one. + * + * @param other - The `GeoPoint` to compare against. + * @returns true if this `GeoPoint` is equal to the provided one. + */ + isEqual(other: GeoPoint): boolean; + /** + * Returns a JSON-serializable representation of this `GeoPoint` instance. + * + * @returns a JSON representation of this object. + */ + toJSON(): { + latitude: number; + longitude: number; + type: string; + }; + /** + * Builds a `GeoPoint` instance from a JSON object created by {@link GeoPoint.toJSON}. + * + * @param json a JSON object represention of a `GeoPoint` instance + * @returns an instance of {@link GeoPoint} if the JSON object could be parsed. Throws a + * {@link FirestoreError} if an error occurs. + */ + static fromJSON(json: object): GeoPoint; +} +/** + * Calculates the specified aggregations over the documents in the result + * set of the given query without actually downloading the documents. + * + * Using this function to perform aggregations is efficient because only the + * final aggregation values, not the documents' data, are downloaded. This + * function can perform aggregations of the documents in cases where the result + * set is prohibitively large to download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set is aggregated over. + * @param aggregateSpec An `AggregateSpec` object that specifies the aggregates + * to perform over the result set. The AggregateSpec specifies aliases for each + * aggregate, which can be used to retrieve the aggregate result. + * @example + * ```typescript + * const aggregateSnapshot = await getAggregateFromServer(query, { + * countOfDocs: count(), + * totalHours: sum('hours'), + * averageScore: average('score') + * }); + * + * const countOfDocs: number = aggregateSnapshot.data().countOfDocs; + * const totalHours: number = aggregateSnapshot.data().totalHours; + * const averageScore: number | null = aggregateSnapshot.data().averageScore; + * ``` + */ +export declare function getAggregateFromServer(query: Query, aggregateSpec: AggregateSpecType): Promise>; +/** + * Calculates the number of documents in the result set of the given query + * without actually downloading the documents. + * + * Using this function to count the documents is efficient because only the + * final count, not the documents' data, is downloaded. This function can + * count the documents in cases where the result set is prohibitively large to + * download entirely (thousands of documents). + * + * The result received from the server is presented, unaltered, without + * considering any local state. That is, documents in the local cache are not + * taken into consideration, neither are local modifications not yet + * synchronized with the server. Previously-downloaded results, if any, are not + * used. Every invocation of this function necessarily involves a round trip to + * the server. + * + * @param query The query whose result set size is calculated. + * @returns A Promise that will be resolved with the count; the count can be + * retrieved from `snapshot.data().count`, where `snapshot` is the + * `AggregateQuerySnapshot` to which the returned Promise resolves. + */ +export declare function getCountFromServer(query: Query): Promise; +}, AppModelType, DbModelType>>; +/** + * Reads the document referred to by this `DocumentReference`. + * + * Note: `getDoc()` attempts to provide up-to-date data when possible by waiting + * for data from the server, but it may return cached data or fail if you are + * offline and the server cannot be reached. To specify this behavior, invoke + * {@link getDocFromCache} or {@link getDocFromServer}. + * + * @param reference - The reference of the document to fetch. + * @returns A Promise resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +export declare function getDoc(reference: DocumentReference): Promise>; +/** + * Reads the document referred to by this `DocumentReference` from cache. + * Returns an error if the document is not currently cached. + * + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +export declare function getDocFromCache(reference: DocumentReference): Promise>; +/** + * Reads the document referred to by this `DocumentReference` from the server. + * Returns an error if the network is not available. + * + * @returns A `Promise` resolved with a `DocumentSnapshot` containing the + * current document contents. + */ +export declare function getDocFromServer(reference: DocumentReference): Promise>; +/** + * Executes the query and returns the results as a `QuerySnapshot`. + * + * Note: `getDocs()` attempts to provide up-to-date data when possible by + * waiting for data from the server, but it may return cached data or fail if + * you are offline and the server cannot be reached. To specify this behavior, + * invoke {@link getDocsFromCache} or {@link getDocsFromServer}. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +export declare function getDocs(query: Query): Promise>; +/** + * Executes the query and returns the results as a `QuerySnapshot` from cache. + * Returns an empty result set if no documents matching the query are currently + * cached. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +export declare function getDocsFromCache(query: Query): Promise>; +/** + * Executes the query and returns the results as a `QuerySnapshot` from the + * server. Returns an error if the network is not available. + * + * @returns A `Promise` that will be resolved with the results of the query. + */ +export declare function getDocsFromServer(query: Query): Promise>; +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @returns The default {@link Firestore} instance of the default app. + */ +export declare function getFirestore(): Firestore; +/** + * Returns the existing default {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @returns The default {@link Firestore} instance of the provided app. + */ +export declare function getFirestore(app: FirebaseApp): Firestore; +/** + * Returns the existing named {@link Firestore} instance that is associated with the + * default {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param databaseId - The name of the database. + * @returns The named {@link Firestore} instance of the default app. + * @beta + */ +export declare function getFirestore(databaseId: string): Firestore; +/** + * Returns the existing named {@link Firestore} instance that is associated with the + * provided {@link @firebase/app#FirebaseApp}. If no instance exists, initializes a new + * instance with default settings. + * + * @param app - The {@link @firebase/app#FirebaseApp} instance that the returned {@link Firestore} + * instance is associated with. + * @param databaseId - The name of the database. + * @returns The named {@link Firestore} instance of the provided app. + * @beta + */ +export declare function getFirestore(app: FirebaseApp, databaseId: string): Firestore; +/** + * Returns the PersistentCache Index Manager used by the given `Firestore` + * object. + * + * @return The `PersistentCacheIndexManager` instance, or `null` if local + * persistent storage is not in use. + */ +export declare function getPersistentCacheIndexManager(firestore: Firestore): PersistentCacheIndexManager | null; +/** + * Returns a special value that can be used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link + * @firebase/firestore/lite#(updateDoc:1)} that tells the server to increment the field's current value by + * the given value. + * + * If either the operand or the current field value uses floating point + * precision, all arithmetic follows IEEE 754 semantics. If both values are + * integers, values outside of JavaScript's safe number range + * (`Number.MIN_SAFE_INTEGER` to `Number.MAX_SAFE_INTEGER`) are also subject to + * precision loss. Furthermore, once processed by the Firestore backend, all + * integer operations are capped between -2^63 and 2^63-1. + * + * If the current field value is not of type `number`, or if the field does not + * yet exist, the transformation sets the field to the given value. + * + * @param n - The value to increment by. + * @returns The `FieldValue` sentinel for use in a call to `setDoc()` or + * `updateDoc()` + */ +export declare function increment(n: number): FieldValue; +/** + * The SDK definition of a Firestore index. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare interface Index { + /** The ID of the collection to index. */ + readonly collectionGroup: string; + /** A list of fields to index. */ + readonly fields?: IndexField[]; + [key: string]: unknown; +} +/** + * A list of Firestore indexes to speed up local query execution. + * + * See {@link https://firebase.google.com/docs/reference/firestore/indexes/#json_format | JSON Format} + * for a description of the format of the index definition. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare interface IndexConfiguration { + /** A list of all Firestore indexes. */ + readonly indexes?: Index[]; + [key: string]: unknown; +} +/** + * A single field element in an index configuration. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare interface IndexField { + /** The field path to index. */ + readonly fieldPath: string; + /** + * What type of array index to create. Set to `CONTAINS` for `array-contains` + * and `array-contains-any` indexes. + * + * Only one of `arrayConfig` or `order` should be set; + */ + readonly arrayConfig?: 'CONTAINS'; + /** + * What type of array index to create. Set to `ASCENDING` or 'DESCENDING` for + * `==`, `!=`, `<=`, `<=`, `in` and `not-in` filters. + * + * Only one of `arrayConfig` or `order` should be set. + */ + readonly order?: 'ASCENDING' | 'DESCENDING'; + [key: string]: unknown; +} +/** + * Initializes a new instance of {@link Firestore} with the provided settings. + * Can only be called before any other function, including + * {@link (getFirestore:1)}. If the custom settings are empty, this function is + * equivalent to calling {@link (getFirestore:1)}. + * + * @param app - The {@link @firebase/app#FirebaseApp} with which the {@link Firestore} instance will + * be associated. + * @param settings - A settings object to configure the {@link Firestore} instance. + * @param databaseId - The name of the database. + * @returns A newly initialized {@link Firestore} instance. + */ +export declare function initializeFirestore(app: FirebaseApp, settings: FirestoreSettings, databaseId?: string): Firestore; +/** + * Creates a {@link QueryLimitConstraint} that only returns the first matching + * documents. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +export declare function limit(limit: number): QueryLimitConstraint; +/** + * Creates a {@link QueryLimitConstraint} that only returns the last matching + * documents. + * + * You must specify at least one `orderBy` clause for `limitToLast` queries, + * otherwise an exception will be thrown during execution. + * + * @param limit - The maximum number of items to return. + * @returns The created {@link QueryLimitConstraint}. + */ +export declare function limitToLast(limit: number): QueryLimitConstraint; +/** + * Describe the source a query listens to. + * + * Set to `default` to listen to both cache and server changes. Set to `cache` + * to listen to changes in cache only. + */ +export declare type ListenSource = 'default' | 'cache'; +/** + * Loads a Firestore bundle into the local cache. + * + * @param firestore - The {@link Firestore} instance to load bundles for. + * @param bundleData - An object representing the bundle to be loaded. Valid + * objects are `ArrayBuffer`, `ReadableStream` or `string`. + * + * @returns A `LoadBundleTask` object, which notifies callers with progress + * updates, and completion or error events. It can be used as a + * `Promise`. + */ +export declare function loadBundle(firestore: Firestore, bundleData: ReadableStream | ArrayBuffer | string): LoadBundleTask; +/** + * Represents the task of loading a Firestore bundle. It provides progress of bundle + * loading, as well as task completion and error events. + * + * The API is compatible with `Promise`. + */ +export declare class LoadBundleTask implements PromiseLike { + /** + * Registers functions to listen to bundle loading progress events. + * @param next - Called when there is a progress update from bundle loading. Typically `next` calls occur + * each time a Firestore document is loaded from the bundle. + * @param error - Called when an error occurs during bundle loading. The task aborts after reporting the + * error, and there should be no more updates after this. + * @param complete - Called when the loading task is complete. + */ + onProgress(next?: (progress: LoadBundleTaskProgress) => unknown, error?: (err: Error) => unknown, complete?: () => void): void; + /** + * Implements the `Promise.catch` interface. + * + * @param onRejected - Called when an error occurs during bundle loading. + */ + catch(onRejected: (a: Error) => R | PromiseLike): Promise; + /** + * Implements the `Promise.then` interface. + * + * @param onFulfilled - Called on the completion of the loading task with a final `LoadBundleTaskProgress` update. + * The update will always have its `taskState` set to `"Success"`. + * @param onRejected - Called when an error occurs during bundle loading. + */ + then(onFulfilled?: (a: LoadBundleTaskProgress) => T | PromiseLike, onRejected?: (a: Error) => R | PromiseLike): Promise; +} +/** + * Represents a progress update or a final state from loading bundles. + */ +export declare interface LoadBundleTaskProgress { + /** How many documents have been loaded. */ + documentsLoaded: number; + /** How many documents are in the bundle being loaded. */ + totalDocuments: number; + /** How many bytes have been loaded. */ + bytesLoaded: number; + /** How many bytes are in the bundle being loaded. */ + totalBytes: number; + /** Current task state. */ + taskState: TaskState; +} +export { LogLevel }; +/** + * An settings object to configure an `MemoryLocalCache` instance. + */ +export declare interface MemoryCacheSettings { + /** + * The garbage collector to use, for the memory cache layer. + * A `MemoryEagerGarbageCollector` is used when this is undefined. + */ + garbageCollector?: MemoryGarbageCollector; +} +/** + * A garbage collector deletes documents whenever they are not part of any + * active queries, and have no local mutations attached to them. + * + * This collector tries to ensure lowest memory footprints from the SDK, + * at the risk of documents not being cached for offline queries or for + * direct queries to the cache. + * + * Use factory function {@link memoryEagerGarbageCollector()} to create an + * instance of this collector. + */ +export declare interface MemoryEagerGarbageCollector { + kind: 'memoryEager'; +} +/** + * Creates an instance of `MemoryEagerGarbageCollector`. This is also the + * default garbage collector unless it is explicitly specified otherwise. + */ +export declare function memoryEagerGarbageCollector(): MemoryEagerGarbageCollector; +/** + * Union type from all support garbage collectors for memory local cache. + */ +export declare type MemoryGarbageCollector = MemoryEagerGarbageCollector | MemoryLruGarbageCollector; +/** + * Provides an in-memory cache to the SDK. This is the default cache unless explicitly + * configured otherwise. + * + * To use, create an instance using the factory function {@link memoryLocalCache()}, then + * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using + * the settings object. + */ +export declare interface MemoryLocalCache { + kind: 'memory'; +} +/** + * Creates an instance of `MemoryLocalCache`. The instance can be set to + * `FirestoreSettings.cache` to tell the SDK which cache layer to use. + */ +export declare function memoryLocalCache(settings?: MemoryCacheSettings): MemoryLocalCache; +/** + * A garbage collector deletes Least-Recently-Used documents in multiple + * batches. + * + * This collector is configured with a target size, and will only perform + * collection when the cached documents exceed the target size. It avoids + * querying backend repeated for the same query or document, at the risk + * of having a larger memory footprint. + * + * Use factory function {@link memoryLruGarbageCollector()} to create a + * instance of this collector. + */ +export declare interface MemoryLruGarbageCollector { + kind: 'memoryLru'; +} +/** + * Creates an instance of `MemoryLruGarbageCollector`. + * + * A target size can be specified as part of the setting parameter. The + * collector will start deleting documents once the cache size exceeds + * the given size. The default cache size is 40MB (40 * 1024 * 1024 bytes). + */ +export declare function memoryLruGarbageCollector(settings?: { + cacheSizeBytes?: number; +}): MemoryLruGarbageCollector; +/** + * Reads a Firestore {@link Query} from local cache, identified by the given + * name. + * + * The named queries are packaged into bundles on the server side (along + * with resulting documents), and loaded to local cache using `loadBundle`. Once + * in local cache, use this method to extract a {@link Query} by name. + * + * @param firestore - The {@link Firestore} instance to read the query from. + * @param name - The name of the query. + * @returns A `Promise` that is resolved with the Query or `null`. + */ +export declare function namedQuery(firestore: Firestore, name: string): Promise; +/** + * For each field (e.g. 'bar'), find all nested keys (e.g. {'bar.baz': T1, + * 'bar.qux': T2}). Intersect them together to make a single map containing + * all possible keys that are all marked as optional + */ +export declare type NestedUpdateFields> = UnionToIntersection<{ + [K in keyof T & string]: ChildUpdateFields; +}[keyof T & string]>; +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshot(reference: DocumentReference, observer: { + next?: (snapshot: DocumentSnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshot(reference: DocumentReference, options: SnapshotListenOptions, observer: { + next?: (snapshot: DocumentSnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(reference: DocumentReference, onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param reference - A reference to the document to listen to. + * @param options - Options controlling the listen behavior. + * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(reference: DocumentReference, options: SnapshotListenOptions, onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The + * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(query: Query, observer: { + next?: (snapshot: QuerySnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The + * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(query: Query, options: SnapshotListenOptions, observer: { + next?: (snapshot: QuerySnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The + * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(query: Query, onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events. You may either pass individual `onNext` and + * `onError` callbacks or pass a single observer object with `next` and `error` callbacks. The + * listener can be cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param query - The query to listen to. + * @param options - Options controlling the listen behavior. + * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshot(query: Query, options: SnapshotListenOptions, onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events based on data generated by invoking + * {@link QuerySnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. + * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking + * {@link DocumentSnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. + * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are + * never ending. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events based on data generated by invoking + * {@link QuerySnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param onNext - A callback to be called every time a new `QuerySnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, options: SnapshotListenOptions, onNext: (snapshot: QuerySnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking + * {@link DocumentSnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks + * or pass a single observer object with `next` and `error` callbacks. The listener can be cancelled + * by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param onNext - A callback to be called every time a new `DocumentSnapshot` is available. + * @param onError - A callback to be called if the listen fails or is cancelled. No further + * callbacks will occur. + * @param onCompletion - Can be provided, but will not be called since streams are never ending. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, options: SnapshotListenOptions, onNext: (snapshot: DocumentSnapshot) => void, onError?: (error: FirestoreError) => void, onCompletion?: () => void, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events based on QuerySnapshot data generated by invoking + * {@link QuerySnapshot.toJSON}. You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, observer: { + next: (snapshot: QuerySnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events based on data generated by invoking + * {@link DocumentSnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks + * or pass a single observer object with `next` and `error` callbacks. The listener can be cancelled + * by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, observer: { + next: (snapshot: DocumentSnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `QuerySnapshot` events based on QuerySnapshot data generated by invoking + * {@link QuerySnapshot.toJSON} You may either pass individual `onNext` and `onError` callbacks or + * pass a single observer object with `next` and `error` callbacks. The listener can be cancelled by + * calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link QuerySnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel + * the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, options: SnapshotListenOptions, observer: { + next: (snapshot: QuerySnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for `DocumentSnapshot` events based on QuerySnapshot data generated by + * invoking {@link DocumentSnapshot.toJSON} You may either pass individual `onNext` and `onError` + * callbacks or pass a single observer object with `next` and `error` callbacks. The listener can be + * cancelled by calling the function that is returned when `onSnapshot` is called. + * + * NOTE: Although an `onCompletion` callback can be provided, it will never be called because the + * snapshot stream is never-ending. + * + * @param firestore - The {@link Firestore} instance to enable the listener for. + * @param snapshotJson - A JSON object generated by invoking {@link DocumentSnapshot.toJSON}. + * @param options - Options controlling the listen behavior. + * @param observer - A single object containing `next` and `error` callbacks. + * @param converter - An optional object that converts objects from Firestore before the onNext + * listener is invoked. + * @returns An unsubscribe function that can be called to cancel the snapshot listener. + */ +export declare function onSnapshotResume(firestore: Firestore, snapshotJson: object, options: SnapshotListenOptions, observer: { + next: (snapshot: DocumentSnapshot) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}, converter?: FirestoreDataConverter): Unsubscribe; +/** + * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync + * event indicates that all listeners affected by a given change have fired, + * even if a single server-generated change affects multiple listeners. + * + * NOTE: The snapshots-in-sync event only indicates that listeners are in sync + * with each other, but does not relate to whether those snapshots are in sync + * with the server. Use SnapshotMetadata in the individual listeners to + * determine if a snapshot is from the cache or the server. + * + * @param firestore - The instance of Firestore for synchronizing snapshots. + * @param observer - A single object containing `next` and `error` callbacks. + * @returns An unsubscribe function that can be called to cancel the snapshot + * listener. + */ +export declare function onSnapshotsInSync(firestore: Firestore, observer: { + next?: (value: void) => void; + error?: (error: FirestoreError) => void; + complete?: () => void; +}): Unsubscribe; +/** + * Attaches a listener for a snapshots-in-sync event. The snapshots-in-sync + * event indicates that all listeners affected by a given change have fired, + * even if a single server-generated change affects multiple listeners. + * + * NOTE: The snapshots-in-sync event only indicates that listeners are in sync + * with each other, but does not relate to whether those snapshots are in sync + * with the server. Use `SnapshotMetadata` in the individual listeners to + * determine if a snapshot is from the cache or the server. + * + * @param firestore - The `Firestore` instance for synchronizing snapshots. + * @param onSync - A callback to be called every time all snapshot listeners are + * in sync with each other. + * @returns An unsubscribe function that can be called to cancel the snapshot + * listener. + */ +export declare function onSnapshotsInSync(firestore: Firestore, onSync: () => void): Unsubscribe; +/** + * Creates a new {@link QueryCompositeFilterConstraint} that is a disjunction of + * the given filter constraints. A disjunction filter includes a document if it + * satisfies any of the given filters. + * + * @param queryConstraints - Optional. The list of + * {@link QueryFilterConstraint}s to perform a disjunction for. These must be + * created with calls to {@link where}, {@link or}, or {@link and}. + * @returns The newly created {@link QueryCompositeFilterConstraint}. + */ +export declare function or(...queryConstraints: QueryFilterConstraint[]): QueryCompositeFilterConstraint; +/** + * Creates a {@link QueryOrderByConstraint} that sorts the query result by the + * specified field, optionally in descending order instead of ascending. + * + * Note: Documents that do not contain the specified field will not be present + * in the query result. + * + * @param fieldPath - The field to sort by. + * @param directionStr - Optional direction to sort by ('asc' or 'desc'). If + * not specified, order will be ascending. + * @returns The created {@link QueryOrderByConstraint}. + */ +export declare function orderBy(fieldPath: string | FieldPath, directionStr?: OrderByDirection): QueryOrderByConstraint; +/** + * The direction of a {@link orderBy} clause is specified as 'desc' or 'asc' + * (descending or ascending). + */ +export declare type OrderByDirection = 'desc' | 'asc'; +/** + * Similar to TypeScript's `Partial`, but allows nested fields to be + * omitted and FieldValues to be passed in as property values. + */ +export declare type PartialWithFieldValue = Partial | (T extends Primitive ? T : T extends {} ? { + [K in keyof T]?: PartialWithFieldValue | FieldValue; +} : never); +/** + * Settings that can be passed to `enableIndexedDbPersistence()` to configure + * Firestore persistence. + * + * Persistence cannot be used in a Node.js environment. + */ +export declare interface PersistenceSettings { + /** + * Whether to force enable persistence for the client. This cannot be used + * with multi-tab synchronization and is primarily intended for use with Web + * Workers. Setting this to `true` will enable persistence, but cause other + * tabs using persistence to fail. + */ + forceOwnership?: boolean; +} +/** + * A `PersistentCacheIndexManager` for configuring persistent cache indexes used + * for local query execution. + * + * To use, call `getPersistentCacheIndexManager()` to get an instance. + */ +export declare class PersistentCacheIndexManager { + /** A type string to uniquely identify instances of this class. */ + readonly type: 'PersistentCacheIndexManager'; + private constructor(); +} +/** + * An settings object to configure an `PersistentLocalCache` instance. + * + * Persistent cache cannot be used in a Node.js environment. + */ +export declare interface PersistentCacheSettings { + /** + * An approximate cache size threshold for the on-disk data. If the cache + * grows beyond this size, Firestore will start removing data that hasn't been + * recently used. The SDK does not guarantee that the cache will stay below + * that size, only that if the cache exceeds the given size, cleanup will be + * attempted. + * + * The default value is 40 MB. The threshold must be set to at least 1 MB, and + * can be set to `CACHE_SIZE_UNLIMITED` to disable garbage collection. + */ + cacheSizeBytes?: number; + /** + * Specifies how multiple tabs/windows will be managed by the SDK. + */ + tabManager?: PersistentTabManager; +} +/** + * Provides a persistent cache backed by IndexedDb to the SDK. + * + * To use, create an instance using the factory function {@link persistentLocalCache()}, then + * set the instance to `FirestoreSettings.cache` and call `initializeFirestore` using + * the settings object. + */ +export declare interface PersistentLocalCache { + kind: 'persistent'; +} +/** + * Creates an instance of `PersistentLocalCache`. The instance can be set to + * `FirestoreSettings.cache` to tell the SDK which cache layer to use. + * + * Persistent cache cannot be used in a Node.js environment. + */ +export declare function persistentLocalCache(settings?: PersistentCacheSettings): PersistentLocalCache; +/** + * A tab manager supporting multiple tabs. SDK will synchronize queries and + * mutations done across all tabs using the SDK. + */ +export declare interface PersistentMultipleTabManager { + kind: 'PersistentMultipleTab'; +} +/** + * Creates an instance of `PersistentMultipleTabManager`. + */ +export declare function persistentMultipleTabManager(): PersistentMultipleTabManager; +/** + * A tab manager supporting only one tab, no synchronization will be + * performed across tabs. + */ +export declare interface PersistentSingleTabManager { + kind: 'persistentSingleTab'; +} +/** + * Creates an instance of `PersistentSingleTabManager`. + * + * @param settings Configures the created tab manager. + */ +export declare function persistentSingleTabManager(settings: PersistentSingleTabManagerSettings | undefined): PersistentSingleTabManager; +/** + * Type to configure an `PersistentSingleTabManager` instance. + */ +export declare interface PersistentSingleTabManagerSettings { + /** + * Whether to force-enable persistent (IndexedDB) cache for the client. This + * cannot be used with multi-tab synchronization and is primarily intended for + * use with Web Workers. Setting this to `true` will enable IndexedDB, but cause + * other tabs using IndexedDB cache to fail. + */ + forceOwnership?: boolean; +} +/** + * A union of all available tab managers. + */ +export declare type PersistentTabManager = PersistentSingleTabManager | PersistentMultipleTabManager; +/** + * These types primarily exist to support the `UpdateData`, + * `WithFieldValue`, and `PartialWithFieldValue` types and are not consumed + * directly by the end developer. + */ +/** Primitive types. */ +export declare type Primitive = string | number | boolean | undefined | null; +/** + * A `Query` refers to a query which you can read or listen to. You can also + * construct refined `Query` objects by adding filters and ordering. + */ +export declare class Query { + /** + * If provided, the `FirestoreDataConverter` associated with this instance. + */ + readonly converter: FirestoreDataConverter | null; + /** The type of this Firestore reference. */ + readonly type: 'query' | 'collection'; + /** + * The `Firestore` instance for the Firestore database (useful for performing + * transactions, etc.). + */ + readonly firestore: Firestore; + protected constructor(); + /** + * Removes the current converter. + * + * @param converter - `null` removes the current converter. + * @returns A `Query` that does not use a + * converter. + */ + withConverter(converter: null): Query; + /** + * Applies a custom data converter to this query, allowing you to use your own + * custom model objects with Firestore. When you call {@link getDocs} with + * the returned query, the provided converter will convert between Firestore + * data of type `NewDbModelType` and your custom type `NewAppModelType`. + * + * @param converter - Converts objects to and from Firestore. + * @returns A `Query` that uses the provided converter. + */ + withConverter(converter: FirestoreDataConverter): Query; +} +/** + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. + * + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param compositeFilter - The {@link QueryCompositeFilterConstraint} to + * apply. Create {@link QueryCompositeFilterConstraint} using {@link and} or + * {@link or}. + * @param queryConstraints - Additional {@link QueryNonFilterConstraint}s to + * apply (e.g. {@link orderBy}, {@link limit}). + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query(query: Query, compositeFilter: QueryCompositeFilterConstraint, ...queryConstraints: QueryNonFilterConstraint[]): Query; +/** + * Creates a new immutable instance of {@link Query} that is extended to also + * include additional query constraints. + * + * @param query - The {@link Query} instance to use as a base for the new + * constraints. + * @param queryConstraints - The list of {@link QueryConstraint}s to apply. + * @throws if any of the provided query constraints cannot be combined with the + * existing or new constraints. + */ +export declare function query(query: Query, ...queryConstraints: QueryConstraint[]): Query; +/** + * A `QueryCompositeFilterConstraint` is used to narrow the set of documents + * returned by a Firestore query by performing the logical OR or AND of multiple + * {@link QueryFieldFilterConstraint}s or {@link QueryCompositeFilterConstraint}s. + * `QueryCompositeFilterConstraint`s are created by invoking {@link or} or + * {@link and} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains the `QueryCompositeFilterConstraint`. + */ +export declare class QueryCompositeFilterConstraint { + /** The type of this query constraint */ + readonly type: 'or' | 'and'; +} +/** + * A `QueryConstraint` is used to narrow the set of documents returned by a + * Firestore query. `QueryConstraint`s are created by invoking {@link where}, + * {@link orderBy}, {@link (startAt:1)}, {@link (startAfter:1)}, {@link + * (endBefore:1)}, {@link (endAt:1)}, {@link limit}, {@link limitToLast} and + * can then be passed to {@link (query:1)} to create a new query instance that + * also contains this `QueryConstraint`. + */ +export declare abstract class QueryConstraint { + /** The type of this query constraint */ + abstract readonly type: QueryConstraintType; +} +/** Describes the different query constraints available in this SDK. */ +export declare type QueryConstraintType = 'where' | 'orderBy' | 'limit' | 'limitToLast' | 'startAt' | 'startAfter' | 'endAt' | 'endBefore'; +/** + * A `QueryDocumentSnapshot` contains data read from a document in your + * Firestore database as part of a query. The document is guaranteed to exist + * and its data can be extracted with `.data()` or `.get()` to get a + * specific field. + * + * A `QueryDocumentSnapshot` offers the same API surface as a + * `DocumentSnapshot`. Since query results contain only existing documents, the + * `exists` property will always be true and `data()` will never return + * 'undefined'. + */ +export declare class QueryDocumentSnapshot extends DocumentSnapshot { + /** + * Retrieves all fields in the document as an `Object`. + * + * By default, `serverTimestamp()` values that have not yet been + * set to their final value will be returned as `null`. You can override + * this by passing an options object. + * + * @override + * @param options - An options object to configure how data is retrieved from + * the snapshot (for example the desired behavior for server timestamps that + * have not yet been set to their final value). + * @returns An `Object` containing all fields in the document. + */ + data(options?: SnapshotOptions): AppModelType; +} +/** + * A `QueryEndAtConstraint` is used to exclude documents from the end of a + * result set returned by a Firestore query. + * `QueryEndAtConstraint`s are created by invoking {@link (endAt:1)} or + * {@link (endBefore:1)} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryEndAtConstraint`. + */ +export declare class QueryEndAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'endBefore' | 'endAt'; +} +/** + * Returns true if the provided queries point to the same collection and apply + * the same constraints. + * + * @param left - A `Query` to compare. + * @param right - A `Query` to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +export declare function queryEqual(left: Query, right: Query): boolean; +/** + * A `QueryFieldFilterConstraint` is used to narrow the set of documents returned by + * a Firestore query by filtering on one or more document fields. + * `QueryFieldFilterConstraint`s are created by invoking {@link where} and can then + * be passed to {@link (query:1)} to create a new query instance that also contains + * this `QueryFieldFilterConstraint`. + */ +export declare class QueryFieldFilterConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type = "where"; +} +/** + * `QueryFilterConstraint` is a helper union type that represents + * {@link QueryFieldFilterConstraint} and {@link QueryCompositeFilterConstraint}. + */ +export declare type QueryFilterConstraint = QueryFieldFilterConstraint | QueryCompositeFilterConstraint; +/** + * A `QueryLimitConstraint` is used to limit the number of documents returned by + * a Firestore query. + * `QueryLimitConstraint`s are created by invoking {@link limit} or + * {@link limitToLast} and can then be passed to {@link (query:1)} to create a new + * query instance that also contains this `QueryLimitConstraint`. + */ +export declare class QueryLimitConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'limit' | 'limitToLast'; +} +/** + * `QueryNonFilterConstraint` is a helper union type that represents + * QueryConstraints which are used to narrow or order the set of documents, + * but that do not explicitly filter on a document field. + * `QueryNonFilterConstraint`s are created by invoking {@link orderBy}, + * {@link (startAt:1)}, {@link (startAfter:1)}, {@link (endBefore:1)}, {@link (endAt:1)}, + * {@link limit} or {@link limitToLast} and can then be passed to {@link (query:1)} + * to create a new query instance that also contains the `QueryConstraint`. + */ +export declare type QueryNonFilterConstraint = QueryOrderByConstraint | QueryLimitConstraint | QueryStartAtConstraint | QueryEndAtConstraint; +/** + * A `QueryOrderByConstraint` is used to sort the set of documents returned by a + * Firestore query. `QueryOrderByConstraint`s are created by invoking + * {@link orderBy} and can then be passed to {@link (query:1)} to create a new query + * instance that also contains this `QueryOrderByConstraint`. + * + * Note: Documents that do not contain the orderBy field will not be present in + * the query result. + */ +export declare class QueryOrderByConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type = "orderBy"; +} +/** + * A `QuerySnapshot` contains zero or more `DocumentSnapshot` objects + * representing the results of a query. The documents can be accessed as an + * array via the `docs` property or enumerated using the `forEach` method. The + * number of documents can be determined via the `empty` and `size` + * properties. + */ +export declare class QuerySnapshot { + /** + * Metadata about this snapshot, concerning its source and if it has local + * modifications. + */ + readonly metadata: SnapshotMetadata; + /** + * The query on which you called `get` or `onSnapshot` in order to get this + * `QuerySnapshot`. + */ + readonly query: Query; + private constructor(); + /** An array of all the documents in the `QuerySnapshot`. */ + get docs(): Array>; + /** The number of documents in the `QuerySnapshot`. */ + get size(): number; + /** True if there are no documents in the `QuerySnapshot`. */ + get empty(): boolean; + /** + * Enumerates all of the documents in the `QuerySnapshot`. + * + * @param callback - A callback to be called with a `QueryDocumentSnapshot` for + * each document in the snapshot. + * @param thisArg - The `this` binding for the callback. + */ + forEach(callback: (result: QueryDocumentSnapshot) => void, thisArg?: unknown): void; + /** + * Returns an array of the documents changes since the last snapshot. If this + * is the first snapshot, all documents will be in the list as 'added' + * changes. + * + * @param options - `SnapshotListenOptions` that control whether metadata-only + * changes (i.e. only `DocumentSnapshot.metadata` changed) should trigger + * snapshot events. + */ + docChanges(options?: SnapshotListenOptions): Array>; + /** + * Returns a JSON-serializable representation of this `QuerySnapshot` instance. + * + * @returns a JSON representation of this object. Throws a {@link FirestoreError} if this + * `QuerySnapshot` has pending writes. + */ + toJSON(): object; +} +/** + * Builds a `QuerySnapshot` instance from a JSON object created by + * {@link QuerySnapshot.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json - a JSON object represention of a `QuerySnapshot` instance. + * @returns an instance of {@link QuerySnapshot} if the JSON object could be + * parsed. Throws a {@link FirestoreError} if an error occurs. + */ +export declare function querySnapshotFromJSON(db: Firestore, json: object): QuerySnapshot; +/** + * Builds a `QuerySnapshot` instance from a JSON object created by + * {@link QuerySnapshot.toJSON}. + * + * @param firestore - The {@link Firestore} instance the snapshot should be loaded for. + * @param json - a JSON object represention of a `QuerySnapshot` instance. + * @param converter - Converts objects to and from Firestore. + * @returns an instance of {@link QuerySnapshot} if the JSON object could be + * parsed. Throws a {@link FirestoreError} if an error occurs. + */ +export declare function querySnapshotFromJSON(db: Firestore, json: object, converter: FirestoreDataConverter): QuerySnapshot; +/** + * A `QueryStartAtConstraint` is used to exclude documents from the start of a + * result set returned by a Firestore query. + * `QueryStartAtConstraint`s are created by invoking {@link (startAt:1)} or + * {@link (startAfter:1)} and can then be passed to {@link (query:1)} to create a + * new query instance that also contains this `QueryStartAtConstraint`. + */ +export declare class QueryStartAtConstraint extends QueryConstraint { + /** The type of this query constraint */ + readonly type: 'startAt' | 'startAfter'; +} +/** + * Returns true if the provided references are equal. + * + * @param left - A reference to compare. + * @param right - A reference to compare. + * @returns true if the references point to the same location in the same + * Firestore database. + */ +export declare function refEqual(left: DocumentReference | CollectionReference, right: DocumentReference | CollectionReference): boolean; +/* Excluded from this release type: _ResourcePath */ +/** + * Executes the given `updateFunction` and then attempts to commit the changes + * applied within the transaction. If any document read within the transaction + * has changed, Cloud Firestore retries the `updateFunction`. If it fails to + * commit after 5 attempts, the transaction fails. + * + * The maximum number of writes allowed in a single transaction is 500. + * + * @param firestore - A reference to the Firestore database to run this + * transaction against. + * @param updateFunction - The function to execute within the transaction + * context. + * @param options - An options object to configure maximum number of attempts to + * commit. + * @returns If the transaction completed successfully or was explicitly aborted + * (the `updateFunction` returned a failed promise), the promise returned by the + * `updateFunction `is returned here. Otherwise, if the transaction failed, a + * rejected promise with the corresponding failure error is returned. + */ +export declare function runTransaction(firestore: Firestore, updateFunction: (transaction: Transaction) => Promise, options?: TransactionOptions): Promise; +/** + * Returns a sentinel used with {@link @firebase/firestore/lite#(setDoc:1)} or {@link @firebase/firestore/lite#(updateDoc:1)} to + * include a server-generated timestamp in the written data. + */ +export declare function serverTimestamp(): FieldValue; +/** + * Writes to the document referred to by this `DocumentReference`. If the + * document does not yet exist, it will be created. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @returns A `Promise` resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +export declare function setDoc(reference: DocumentReference, data: WithFieldValue): Promise; +/** + * Writes to the document referred to by the specified `DocumentReference`. If + * the document does not yet exist, it will be created. If you provide `merge` + * or `mergeFields`, the provided data can be merged into an existing document. + * + * @param reference - A reference to the document to write. + * @param data - A map of the fields and values for the document. + * @param options - An object to configure the set behavior. + * @returns A Promise resolved once the data has been successfully written + * to the backend (note that it won't resolve while you're offline). + */ +export declare function setDoc(reference: DocumentReference, data: PartialWithFieldValue, options: SetOptions): Promise; +/** + * Configures indexing for local query execution. Any previous index + * configuration is overridden. The `Promise` resolves once the index + * configuration has been persisted. + * + * The index entries themselves are created asynchronously. You can continue to + * use queries that require indexing even if the indices are not yet available. + * Query execution will automatically start using the index once the index + * entries have been written. + * + * Indexes are only supported with IndexedDb persistence. If IndexedDb is not + * enabled, any index configuration is ignored. + * + * @param firestore - The {@link Firestore} instance to configure indexes for. + * @param configuration -The index definition. + * @throws FirestoreError if the JSON format is invalid. + * @returns A `Promise` that resolves once all indices are successfully + * configured. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare function setIndexConfiguration(firestore: Firestore, configuration: IndexConfiguration): Promise; +/** + * Configures indexing for local query execution. Any previous index + * configuration is overridden. The `Promise` resolves once the index + * configuration has been persisted. + * + * The index entries themselves are created asynchronously. You can continue to + * use queries that require indexing even if the indices are not yet available. + * Query execution will automatically start using the index once the index + * entries have been written. + * + * Indexes are only supported with IndexedDb persistence. Invoke either + * `enableIndexedDbPersistence()` or `enableMultiTabIndexedDbPersistence()` + * before setting an index configuration. If IndexedDb is not enabled, any + * index configuration is ignored. + * + * The method accepts the JSON format exported by the Firebase CLI (`firebase + * firestore:indexes`). If the JSON format is invalid, this method throws an + * error. + * + * @param firestore - The {@link Firestore} instance to configure indexes for. + * @param json -The JSON format exported by the Firebase CLI. + * @throws FirestoreError if the JSON format is invalid. + * @returns A `Promise` that resolves once all indices are successfully + * configured. + * + * @deprecated Instead of creating cache indexes manually, consider using + * `enablePersistentCacheIndexAutoCreation()` to let the SDK decide whether to + * create cache indexes for queries running locally. + * + * @beta + */ +export declare function setIndexConfiguration(firestore: Firestore, json: string): Promise; +/** + * Sets the verbosity of Cloud Firestore logs (debug, error, or silent). + * + * @param logLevel - The verbosity you set for activity and error logging. Can + * be any of the following values: + * + *